1 // SPDX-License-Identifier: GPL-2.0-only 2 /* Copyright (c) 2011-2014 PLUMgrid, http://plumgrid.com 3 * Copyright (c) 2016 Facebook 4 * Copyright (c) 2018 Covalent IO, Inc. http://covalent.io 5 */ 6 #include <uapi/linux/btf.h> 7 #include <linux/bpf-cgroup.h> 8 #include <linux/kernel.h> 9 #include <linux/types.h> 10 #include <linux/slab.h> 11 #include <linux/bpf.h> 12 #include <linux/btf.h> 13 #include <linux/bpf_verifier.h> 14 #include <linux/filter.h> 15 #include <net/netlink.h> 16 #include <linux/file.h> 17 #include <linux/vmalloc.h> 18 #include <linux/stringify.h> 19 #include <linux/bsearch.h> 20 #include <linux/sort.h> 21 #include <linux/perf_event.h> 22 #include <linux/ctype.h> 23 #include <linux/error-injection.h> 24 #include <linux/bpf_lsm.h> 25 #include <linux/btf_ids.h> 26 #include <linux/poison.h> 27 #include <linux/module.h> 28 #include <linux/cpumask.h> 29 #include <linux/cnum.h> 30 #include <linux/bpf_mem_alloc.h> 31 #include <net/xdp.h> 32 #include <linux/trace_events.h> 33 #include <linux/kallsyms.h> 34 35 #include "disasm.h" 36 37 static const struct bpf_verifier_ops * const bpf_verifier_ops[] = { 38 #define BPF_PROG_TYPE(_id, _name, prog_ctx_type, kern_ctx_type) \ 39 [_id] = & _name ## _verifier_ops, 40 #define BPF_MAP_TYPE(_id, _ops) 41 #define BPF_LINK_TYPE(_id, _name) 42 #include <linux/bpf_types.h> 43 #undef BPF_PROG_TYPE 44 #undef BPF_MAP_TYPE 45 #undef BPF_LINK_TYPE 46 }; 47 48 enum bpf_features { 49 BPF_FEAT_RDONLY_CAST_TO_VOID = 0, 50 BPF_FEAT_STREAMS = 1, 51 __MAX_BPF_FEAT, 52 }; 53 54 struct bpf_mem_alloc bpf_global_percpu_ma; 55 static bool bpf_global_percpu_ma_set; 56 57 /* bpf_check() is a static code analyzer that walks eBPF program 58 * instruction by instruction and updates register/stack state. 59 * All paths of conditional branches are analyzed until 'bpf_exit' insn. 60 * 61 * The first pass is depth-first-search to check that the program is a DAG. 62 * It rejects the following programs: 63 * - larger than BPF_MAXINSNS insns 64 * - if loop is present (detected via back-edge) 65 * - unreachable insns exist (shouldn't be a forest. program = one function) 66 * - out of bounds or malformed jumps 67 * The second pass is all possible path descent from the 1st insn. 68 * Since it's analyzing all paths through the program, the length of the 69 * analysis is limited to 64k insn, which may be hit even if total number of 70 * insn is less then 4K, but there are too many branches that change stack/regs. 71 * Number of 'branches to be analyzed' is limited to 1k 72 * 73 * On entry to each instruction, each register has a type, and the instruction 74 * changes the types of the registers depending on instruction semantics. 75 * If instruction is BPF_MOV64_REG(BPF_REG_1, BPF_REG_5), then type of R5 is 76 * copied to R1. 77 * 78 * All registers are 64-bit. 79 * R0 - return register 80 * R1-R5 argument passing registers 81 * R6-R9 callee saved registers 82 * R10 - frame pointer read-only 83 * 84 * At the start of BPF program the register R1 contains a pointer to bpf_context 85 * and has type PTR_TO_CTX. 86 * 87 * Verifier tracks arithmetic operations on pointers in case: 88 * BPF_MOV64_REG(BPF_REG_1, BPF_REG_10), 89 * BPF_ALU64_IMM(BPF_ADD, BPF_REG_1, -20), 90 * 1st insn copies R10 (which has FRAME_PTR) type into R1 91 * and 2nd arithmetic instruction is pattern matched to recognize 92 * that it wants to construct a pointer to some element within stack. 93 * So after 2nd insn, the register R1 has type PTR_TO_STACK 94 * (and -20 constant is saved for further stack bounds checking). 95 * Meaning that this reg is a pointer to stack plus known immediate constant. 96 * 97 * Most of the time the registers have SCALAR_VALUE type, which 98 * means the register has some value, but it's not a valid pointer. 99 * (like pointer plus pointer becomes SCALAR_VALUE type) 100 * 101 * When verifier sees load or store instructions the type of base register 102 * can be: PTR_TO_MAP_VALUE, PTR_TO_CTX, PTR_TO_STACK, PTR_TO_SOCKET. These are 103 * four pointer types recognized by check_mem_access() function. 104 * 105 * PTR_TO_MAP_VALUE means that this register is pointing to 'map element value' 106 * and the range of [ptr, ptr + map's value_size) is accessible. 107 * 108 * registers used to pass values to function calls are checked against 109 * function argument constraints. 110 * 111 * ARG_PTR_TO_MAP_KEY is one of such argument constraints. 112 * It means that the register type passed to this function must be 113 * PTR_TO_STACK and it will be used inside the function as 114 * 'pointer to map element key' 115 * 116 * For example the argument constraints for bpf_map_lookup_elem(): 117 * .ret_type = RET_PTR_TO_MAP_VALUE_OR_NULL, 118 * .arg1_type = ARG_CONST_MAP_PTR, 119 * .arg2_type = ARG_PTR_TO_MAP_KEY, 120 * 121 * ret_type says that this function returns 'pointer to map elem value or null' 122 * function expects 1st argument to be a const pointer to 'struct bpf_map' and 123 * 2nd argument should be a pointer to stack, which will be used inside 124 * the helper function as a pointer to map element key. 125 * 126 * On the kernel side the helper function looks like: 127 * u64 bpf_map_lookup_elem(u64 r1, u64 r2, u64 r3, u64 r4, u64 r5) 128 * { 129 * struct bpf_map *map = (struct bpf_map *) (unsigned long) r1; 130 * void *key = (void *) (unsigned long) r2; 131 * void *value; 132 * 133 * here kernel can access 'key' and 'map' pointers safely, knowing that 134 * [key, key + map->key_size) bytes are valid and were initialized on 135 * the stack of eBPF program. 136 * } 137 * 138 * Corresponding eBPF program may look like: 139 * BPF_MOV64_REG(BPF_REG_2, BPF_REG_10), // after this insn R2 type is FRAME_PTR 140 * BPF_ALU64_IMM(BPF_ADD, BPF_REG_2, -4), // after this insn R2 type is PTR_TO_STACK 141 * BPF_LD_MAP_FD(BPF_REG_1, map_fd), // after this insn R1 type is CONST_PTR_TO_MAP 142 * BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0, BPF_FUNC_map_lookup_elem), 143 * here verifier looks at prototype of map_lookup_elem() and sees: 144 * .arg1_type == ARG_CONST_MAP_PTR and R1->type == CONST_PTR_TO_MAP, which is ok, 145 * Now verifier knows that this map has key of R1->map_ptr->key_size bytes 146 * 147 * Then .arg2_type == ARG_PTR_TO_MAP_KEY and R2->type == PTR_TO_STACK, ok so far, 148 * Now verifier checks that [R2, R2 + map's key_size) are within stack limits 149 * and were initialized prior to this call. 150 * If it's ok, then verifier allows this BPF_CALL insn and looks at 151 * .ret_type which is RET_PTR_TO_MAP_VALUE_OR_NULL, so it sets 152 * R0->type = PTR_TO_MAP_VALUE_OR_NULL which means bpf_map_lookup_elem() function 153 * returns either pointer to map value or NULL. 154 * 155 * When type PTR_TO_MAP_VALUE_OR_NULL passes through 'if (reg != 0) goto +off' 156 * insn, the register holding that pointer in the true branch changes state to 157 * PTR_TO_MAP_VALUE and the same register changes state to CONST_IMM in the false 158 * branch. See check_cond_jmp_op(). 159 * 160 * After the call R0 is set to return type of the function and registers R1-R5 161 * are set to NOT_INIT to indicate that they are no longer readable. 162 * 163 * The following reference types represent a potential reference to a kernel 164 * resource which, after first being allocated, must be checked and freed by 165 * the BPF program: 166 * - PTR_TO_SOCKET_OR_NULL, PTR_TO_SOCKET 167 * 168 * When the verifier sees a helper call return a reference type, it allocates a 169 * pointer id for the reference and stores it in the current function state. 170 * Similar to the way that PTR_TO_MAP_VALUE_OR_NULL is converted into 171 * PTR_TO_MAP_VALUE, PTR_TO_SOCKET_OR_NULL becomes PTR_TO_SOCKET when the type 172 * passes through a NULL-check conditional. For the branch wherein the state is 173 * changed to CONST_IMM, the verifier releases the reference. 174 * 175 * For each helper function that allocates a reference, such as 176 * bpf_sk_lookup_tcp(), there is a corresponding release function, such as 177 * bpf_sk_release(). When a reference type passes into the release function, 178 * the verifier also releases the reference. If any unchecked or unreleased 179 * reference remains at the end of the program, the verifier rejects it. 180 */ 181 182 /* verifier_state + insn_idx are pushed to stack when branch is encountered */ 183 struct bpf_verifier_stack_elem { 184 /* verifier state is 'st' 185 * before processing instruction 'insn_idx' 186 * and after processing instruction 'prev_insn_idx' 187 */ 188 struct bpf_verifier_state st; 189 int insn_idx; 190 int prev_insn_idx; 191 struct bpf_verifier_stack_elem *next; 192 /* length of verifier log at the time this state was pushed on stack */ 193 u32 log_pos; 194 }; 195 196 #define BPF_COMPLEXITY_LIMIT_JMP_SEQ 8192 197 #define BPF_COMPLEXITY_LIMIT_STATES 64 198 199 #define BPF_GLOBAL_PERCPU_MA_MAX_SIZE 512 200 201 #define BPF_PRIV_STACK_MIN_SIZE 64 202 203 static int acquire_reference(struct bpf_verifier_env *env, int insn_idx); 204 static int release_reference_nomark(struct bpf_verifier_state *state, int ref_obj_id); 205 static int release_reference(struct bpf_verifier_env *env, int ref_obj_id); 206 static void invalidate_non_owning_refs(struct bpf_verifier_env *env); 207 static bool in_rbtree_lock_required_cb(struct bpf_verifier_env *env); 208 static int ref_set_non_owning(struct bpf_verifier_env *env, 209 struct bpf_reg_state *reg); 210 static bool is_trusted_reg(const struct bpf_reg_state *reg); 211 static inline bool in_sleepable_context(struct bpf_verifier_env *env); 212 static const char *non_sleepable_context_description(struct bpf_verifier_env *env); 213 static void scalar32_min_max_add(struct bpf_reg_state *dst_reg, struct bpf_reg_state *src_reg); 214 static void scalar_min_max_add(struct bpf_reg_state *dst_reg, struct bpf_reg_state *src_reg); 215 216 static void bpf_map_ptr_store(struct bpf_insn_aux_data *aux, 217 struct bpf_map *map, 218 bool unpriv, bool poison) 219 { 220 unpriv |= bpf_map_ptr_unpriv(aux); 221 aux->map_ptr_state.unpriv = unpriv; 222 aux->map_ptr_state.poison = poison; 223 aux->map_ptr_state.map_ptr = map; 224 } 225 226 static void bpf_map_key_store(struct bpf_insn_aux_data *aux, u64 state) 227 { 228 bool poisoned = bpf_map_key_poisoned(aux); 229 230 aux->map_key_state = state | BPF_MAP_KEY_SEEN | 231 (poisoned ? BPF_MAP_KEY_POISON : 0ULL); 232 } 233 234 struct bpf_call_arg_meta { 235 struct bpf_map_desc map; 236 bool raw_mode; 237 bool pkt_access; 238 u8 release_regno; 239 int regno; 240 int access_size; 241 int mem_size; 242 u64 msize_max_value; 243 int ref_obj_id; 244 int dynptr_id; 245 int func_id; 246 struct btf *btf; 247 u32 btf_id; 248 struct btf *ret_btf; 249 u32 ret_btf_id; 250 u32 subprogno; 251 struct btf_field *kptr_field; 252 s64 const_map_key; 253 }; 254 255 struct bpf_kfunc_meta { 256 struct btf *btf; 257 const struct btf_type *proto; 258 const char *name; 259 const u32 *flags; 260 s32 id; 261 }; 262 263 struct btf *btf_vmlinux; 264 265 typedef struct argno { 266 int argno; 267 } argno_t; 268 269 static argno_t argno_from_reg(u32 regno) 270 { 271 return (argno_t){ .argno = regno }; 272 } 273 274 static argno_t argno_from_arg(u32 arg) 275 { 276 return (argno_t){ .argno = -arg }; 277 } 278 279 static int reg_from_argno(argno_t a) 280 { 281 if (a.argno >= 0) 282 return a.argno; 283 if (a.argno >= -MAX_BPF_FUNC_REG_ARGS) 284 return -a.argno; 285 return -1; 286 } 287 288 static int arg_from_argno(argno_t a) 289 { 290 if (a.argno < 0) 291 return -a.argno; 292 return -1; 293 } 294 295 static int arg_idx_from_argno(argno_t a) 296 { 297 return arg_from_argno(a) - 1; 298 } 299 300 static const char *btf_type_name(const struct btf *btf, u32 id) 301 { 302 return btf_name_by_offset(btf, btf_type_by_id(btf, id)->name_off); 303 } 304 305 static DEFINE_MUTEX(bpf_verifier_lock); 306 static DEFINE_MUTEX(bpf_percpu_ma_lock); 307 308 __printf(2, 3) static void verbose(void *private_data, const char *fmt, ...) 309 { 310 struct bpf_verifier_env *env = private_data; 311 va_list args; 312 313 if (!bpf_verifier_log_needed(&env->log)) 314 return; 315 316 va_start(args, fmt); 317 bpf_verifier_vlog(&env->log, fmt, args); 318 va_end(args); 319 } 320 321 static void verbose_invalid_scalar(struct bpf_verifier_env *env, 322 struct bpf_reg_state *reg, 323 struct bpf_retval_range range, const char *ctx, 324 const char *reg_name) 325 { 326 bool unknown = true; 327 328 verbose(env, "%s the register %s has", ctx, reg_name); 329 if (reg_smin(reg) > S64_MIN) { 330 verbose(env, " smin=%lld", reg_smin(reg)); 331 unknown = false; 332 } 333 if (reg_smax(reg) < S64_MAX) { 334 verbose(env, " smax=%lld", reg_smax(reg)); 335 unknown = false; 336 } 337 if (unknown) 338 verbose(env, " unknown scalar value"); 339 verbose(env, " should have been in [%d, %d]\n", range.minval, range.maxval); 340 } 341 342 static bool reg_not_null(const struct bpf_reg_state *reg) 343 { 344 enum bpf_reg_type type; 345 346 type = reg->type; 347 if (type_may_be_null(type)) 348 return false; 349 350 type = base_type(type); 351 return type == PTR_TO_SOCKET || 352 type == PTR_TO_TCP_SOCK || 353 type == PTR_TO_MAP_VALUE || 354 type == PTR_TO_MAP_KEY || 355 type == PTR_TO_SOCK_COMMON || 356 (type == PTR_TO_BTF_ID && is_trusted_reg(reg)) || 357 (type == PTR_TO_MEM && !(reg->type & PTR_UNTRUSTED)) || 358 type == CONST_PTR_TO_MAP; 359 } 360 361 static struct btf_record *reg_btf_record(const struct bpf_reg_state *reg) 362 { 363 struct btf_record *rec = NULL; 364 struct btf_struct_meta *meta; 365 366 if (reg->type == PTR_TO_MAP_VALUE) { 367 rec = reg->map_ptr->record; 368 } else if (type_is_ptr_alloc_obj(reg->type)) { 369 meta = btf_find_struct_meta(reg->btf, reg->btf_id); 370 if (meta) 371 rec = meta->record; 372 } 373 return rec; 374 } 375 376 bool bpf_subprog_is_global(const struct bpf_verifier_env *env, int subprog) 377 { 378 struct bpf_func_info_aux *aux = env->prog->aux->func_info_aux; 379 380 return aux && aux[subprog].linkage == BTF_FUNC_GLOBAL; 381 } 382 383 static bool subprog_returns_void(struct bpf_verifier_env *env, int subprog) 384 { 385 const struct btf_type *type, *func, *func_proto; 386 const struct btf *btf = env->prog->aux->btf; 387 u32 btf_id; 388 389 btf_id = env->prog->aux->func_info[subprog].type_id; 390 391 func = btf_type_by_id(btf, btf_id); 392 if (verifier_bug_if(!func, env, "btf_id %u not found", btf_id)) 393 return false; 394 395 func_proto = btf_type_by_id(btf, func->type); 396 if (!func_proto) 397 return false; 398 399 type = btf_type_skip_modifiers(btf, func_proto->type, NULL); 400 if (!type) 401 return false; 402 403 return btf_type_is_void(type); 404 } 405 406 static const char *subprog_name(const struct bpf_verifier_env *env, int subprog) 407 { 408 struct bpf_func_info *info; 409 410 if (!env->prog->aux->func_info) 411 return ""; 412 413 info = &env->prog->aux->func_info[subprog]; 414 return btf_type_name(env->prog->aux->btf, info->type_id); 415 } 416 417 void bpf_mark_subprog_exc_cb(struct bpf_verifier_env *env, int subprog) 418 { 419 struct bpf_subprog_info *info = subprog_info(env, subprog); 420 421 info->is_cb = true; 422 info->is_async_cb = true; 423 info->is_exception_cb = true; 424 } 425 426 static bool subprog_is_exc_cb(struct bpf_verifier_env *env, int subprog) 427 { 428 return subprog_info(env, subprog)->is_exception_cb; 429 } 430 431 static bool reg_may_point_to_spin_lock(const struct bpf_reg_state *reg) 432 { 433 return btf_record_has_field(reg_btf_record(reg), BPF_SPIN_LOCK | BPF_RES_SPIN_LOCK); 434 } 435 436 static bool type_is_rdonly_mem(u32 type) 437 { 438 return type & MEM_RDONLY; 439 } 440 441 static bool is_acquire_function(enum bpf_func_id func_id, 442 const struct bpf_map *map) 443 { 444 enum bpf_map_type map_type = map ? map->map_type : BPF_MAP_TYPE_UNSPEC; 445 446 if (func_id == BPF_FUNC_sk_lookup_tcp || 447 func_id == BPF_FUNC_sk_lookup_udp || 448 func_id == BPF_FUNC_skc_lookup_tcp || 449 func_id == BPF_FUNC_ringbuf_reserve || 450 func_id == BPF_FUNC_kptr_xchg) 451 return true; 452 453 if (func_id == BPF_FUNC_map_lookup_elem && 454 (map_type == BPF_MAP_TYPE_SOCKMAP || 455 map_type == BPF_MAP_TYPE_SOCKHASH)) 456 return true; 457 458 return false; 459 } 460 461 static bool is_ptr_cast_function(enum bpf_func_id func_id) 462 { 463 return func_id == BPF_FUNC_tcp_sock || 464 func_id == BPF_FUNC_sk_fullsock || 465 func_id == BPF_FUNC_skc_to_tcp_sock || 466 func_id == BPF_FUNC_skc_to_tcp6_sock || 467 func_id == BPF_FUNC_skc_to_udp6_sock || 468 func_id == BPF_FUNC_skc_to_mptcp_sock || 469 func_id == BPF_FUNC_skc_to_tcp_timewait_sock || 470 func_id == BPF_FUNC_skc_to_tcp_request_sock; 471 } 472 473 static bool is_dynptr_ref_function(enum bpf_func_id func_id) 474 { 475 return func_id == BPF_FUNC_dynptr_data; 476 } 477 478 static bool is_sync_callback_calling_kfunc(u32 btf_id); 479 static bool is_async_callback_calling_kfunc(u32 btf_id); 480 static bool is_callback_calling_kfunc(u32 btf_id); 481 482 static bool is_bpf_wq_set_callback_kfunc(u32 btf_id); 483 static bool is_task_work_add_kfunc(u32 func_id); 484 485 static bool is_sync_callback_calling_function(enum bpf_func_id func_id) 486 { 487 return func_id == BPF_FUNC_for_each_map_elem || 488 func_id == BPF_FUNC_find_vma || 489 func_id == BPF_FUNC_loop || 490 func_id == BPF_FUNC_user_ringbuf_drain; 491 } 492 493 static bool is_async_callback_calling_function(enum bpf_func_id func_id) 494 { 495 return func_id == BPF_FUNC_timer_set_callback; 496 } 497 498 static bool is_callback_calling_function(enum bpf_func_id func_id) 499 { 500 return is_sync_callback_calling_function(func_id) || 501 is_async_callback_calling_function(func_id); 502 } 503 504 bool bpf_is_sync_callback_calling_insn(struct bpf_insn *insn) 505 { 506 return (bpf_helper_call(insn) && is_sync_callback_calling_function(insn->imm)) || 507 (bpf_pseudo_kfunc_call(insn) && is_sync_callback_calling_kfunc(insn->imm)); 508 } 509 510 bool bpf_is_async_callback_calling_insn(struct bpf_insn *insn) 511 { 512 return (bpf_helper_call(insn) && is_async_callback_calling_function(insn->imm)) || 513 (bpf_pseudo_kfunc_call(insn) && is_async_callback_calling_kfunc(insn->imm)); 514 } 515 516 static bool is_async_cb_sleepable(struct bpf_verifier_env *env, struct bpf_insn *insn) 517 { 518 /* bpf_timer callbacks are never sleepable. */ 519 if (bpf_helper_call(insn) && insn->imm == BPF_FUNC_timer_set_callback) 520 return false; 521 522 /* bpf_wq and bpf_task_work callbacks are always sleepable. */ 523 if (bpf_pseudo_kfunc_call(insn) && insn->off == 0 && 524 (is_bpf_wq_set_callback_kfunc(insn->imm) || is_task_work_add_kfunc(insn->imm))) 525 return true; 526 527 verifier_bug(env, "unhandled async callback in is_async_cb_sleepable"); 528 return false; 529 } 530 531 bool bpf_is_may_goto_insn(struct bpf_insn *insn) 532 { 533 return insn->code == (BPF_JMP | BPF_JCOND) && insn->src_reg == BPF_MAY_GOTO; 534 } 535 536 static bool helper_multiple_ref_obj_use(enum bpf_func_id func_id, 537 const struct bpf_map *map) 538 { 539 int ref_obj_uses = 0; 540 541 if (is_ptr_cast_function(func_id)) 542 ref_obj_uses++; 543 if (is_acquire_function(func_id, map)) 544 ref_obj_uses++; 545 if (is_dynptr_ref_function(func_id)) 546 ref_obj_uses++; 547 548 return ref_obj_uses > 1; 549 } 550 551 552 static bool is_spi_bounds_valid(struct bpf_func_state *state, int spi, int nr_slots) 553 { 554 int allocated_slots = state->allocated_stack / BPF_REG_SIZE; 555 556 /* We need to check that slots between [spi - nr_slots + 1, spi] are 557 * within [0, allocated_stack). 558 * 559 * Please note that the spi grows downwards. For example, a dynptr 560 * takes the size of two stack slots; the first slot will be at 561 * spi and the second slot will be at spi - 1. 562 */ 563 return spi - nr_slots + 1 >= 0 && spi < allocated_slots; 564 } 565 566 static int stack_slot_obj_get_spi(struct bpf_verifier_env *env, struct bpf_reg_state *reg, 567 const char *obj_kind, int nr_slots) 568 { 569 int off, spi; 570 571 if (!tnum_is_const(reg->var_off)) { 572 verbose(env, "%s has to be at a constant offset\n", obj_kind); 573 return -EINVAL; 574 } 575 576 off = reg->var_off.value; 577 if (off % BPF_REG_SIZE) { 578 verbose(env, "cannot pass in %s at an offset=%d\n", obj_kind, off); 579 return -EINVAL; 580 } 581 582 spi = bpf_get_spi(off); 583 if (spi + 1 < nr_slots) { 584 verbose(env, "cannot pass in %s at an offset=%d\n", obj_kind, off); 585 return -EINVAL; 586 } 587 588 if (!is_spi_bounds_valid(bpf_func(env, reg), spi, nr_slots)) 589 return -ERANGE; 590 return spi; 591 } 592 593 static int dynptr_get_spi(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 594 { 595 return stack_slot_obj_get_spi(env, reg, "dynptr", BPF_DYNPTR_NR_SLOTS); 596 } 597 598 static int iter_get_spi(struct bpf_verifier_env *env, struct bpf_reg_state *reg, int nr_slots) 599 { 600 return stack_slot_obj_get_spi(env, reg, "iter", nr_slots); 601 } 602 603 static int irq_flag_get_spi(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 604 { 605 return stack_slot_obj_get_spi(env, reg, "irq_flag", 1); 606 } 607 608 static enum bpf_dynptr_type arg_to_dynptr_type(enum bpf_arg_type arg_type) 609 { 610 switch (arg_type & DYNPTR_TYPE_FLAG_MASK) { 611 case DYNPTR_TYPE_LOCAL: 612 return BPF_DYNPTR_TYPE_LOCAL; 613 case DYNPTR_TYPE_RINGBUF: 614 return BPF_DYNPTR_TYPE_RINGBUF; 615 case DYNPTR_TYPE_SKB: 616 return BPF_DYNPTR_TYPE_SKB; 617 case DYNPTR_TYPE_XDP: 618 return BPF_DYNPTR_TYPE_XDP; 619 case DYNPTR_TYPE_SKB_META: 620 return BPF_DYNPTR_TYPE_SKB_META; 621 case DYNPTR_TYPE_FILE: 622 return BPF_DYNPTR_TYPE_FILE; 623 default: 624 return BPF_DYNPTR_TYPE_INVALID; 625 } 626 } 627 628 static enum bpf_type_flag get_dynptr_type_flag(enum bpf_dynptr_type type) 629 { 630 switch (type) { 631 case BPF_DYNPTR_TYPE_LOCAL: 632 return DYNPTR_TYPE_LOCAL; 633 case BPF_DYNPTR_TYPE_RINGBUF: 634 return DYNPTR_TYPE_RINGBUF; 635 case BPF_DYNPTR_TYPE_SKB: 636 return DYNPTR_TYPE_SKB; 637 case BPF_DYNPTR_TYPE_XDP: 638 return DYNPTR_TYPE_XDP; 639 case BPF_DYNPTR_TYPE_SKB_META: 640 return DYNPTR_TYPE_SKB_META; 641 case BPF_DYNPTR_TYPE_FILE: 642 return DYNPTR_TYPE_FILE; 643 default: 644 return 0; 645 } 646 } 647 648 static bool dynptr_type_refcounted(enum bpf_dynptr_type type) 649 { 650 return type == BPF_DYNPTR_TYPE_RINGBUF || type == BPF_DYNPTR_TYPE_FILE; 651 } 652 653 static void __mark_dynptr_reg(struct bpf_reg_state *reg, 654 enum bpf_dynptr_type type, 655 bool first_slot, int dynptr_id); 656 657 658 static void mark_dynptr_stack_regs(struct bpf_verifier_env *env, 659 struct bpf_reg_state *sreg1, 660 struct bpf_reg_state *sreg2, 661 enum bpf_dynptr_type type) 662 { 663 int id = ++env->id_gen; 664 665 __mark_dynptr_reg(sreg1, type, true, id); 666 __mark_dynptr_reg(sreg2, type, false, id); 667 } 668 669 static void mark_dynptr_cb_reg(struct bpf_verifier_env *env, 670 struct bpf_reg_state *reg, 671 enum bpf_dynptr_type type) 672 { 673 __mark_dynptr_reg(reg, type, true, ++env->id_gen); 674 } 675 676 static int destroy_if_dynptr_stack_slot(struct bpf_verifier_env *env, 677 struct bpf_func_state *state, int spi); 678 679 static int mark_stack_slots_dynptr(struct bpf_verifier_env *env, struct bpf_reg_state *reg, 680 enum bpf_arg_type arg_type, int insn_idx, int clone_ref_obj_id) 681 { 682 struct bpf_func_state *state = bpf_func(env, reg); 683 enum bpf_dynptr_type type; 684 int spi, i, err; 685 686 spi = dynptr_get_spi(env, reg); 687 if (spi < 0) 688 return spi; 689 690 /* We cannot assume both spi and spi - 1 belong to the same dynptr, 691 * hence we need to call destroy_if_dynptr_stack_slot twice for both, 692 * to ensure that for the following example: 693 * [d1][d1][d2][d2] 694 * spi 3 2 1 0 695 * So marking spi = 2 should lead to destruction of both d1 and d2. In 696 * case they do belong to same dynptr, second call won't see slot_type 697 * as STACK_DYNPTR and will simply skip destruction. 698 */ 699 err = destroy_if_dynptr_stack_slot(env, state, spi); 700 if (err) 701 return err; 702 err = destroy_if_dynptr_stack_slot(env, state, spi - 1); 703 if (err) 704 return err; 705 706 for (i = 0; i < BPF_REG_SIZE; i++) { 707 state->stack[spi].slot_type[i] = STACK_DYNPTR; 708 state->stack[spi - 1].slot_type[i] = STACK_DYNPTR; 709 } 710 711 type = arg_to_dynptr_type(arg_type); 712 if (type == BPF_DYNPTR_TYPE_INVALID) 713 return -EINVAL; 714 715 mark_dynptr_stack_regs(env, &state->stack[spi].spilled_ptr, 716 &state->stack[spi - 1].spilled_ptr, type); 717 718 if (dynptr_type_refcounted(type)) { 719 /* The id is used to track proper releasing */ 720 int id; 721 722 if (clone_ref_obj_id) 723 id = clone_ref_obj_id; 724 else 725 id = acquire_reference(env, insn_idx); 726 727 if (id < 0) 728 return id; 729 730 state->stack[spi].spilled_ptr.ref_obj_id = id; 731 state->stack[spi - 1].spilled_ptr.ref_obj_id = id; 732 } 733 734 return 0; 735 } 736 737 static void invalidate_dynptr(struct bpf_verifier_env *env, struct bpf_func_state *state, int spi) 738 { 739 int i; 740 741 for (i = 0; i < BPF_REG_SIZE; i++) { 742 state->stack[spi].slot_type[i] = STACK_INVALID; 743 state->stack[spi - 1].slot_type[i] = STACK_INVALID; 744 } 745 746 bpf_mark_reg_not_init(env, &state->stack[spi].spilled_ptr); 747 bpf_mark_reg_not_init(env, &state->stack[spi - 1].spilled_ptr); 748 } 749 750 static int unmark_stack_slots_dynptr(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 751 { 752 struct bpf_func_state *state = bpf_func(env, reg); 753 int spi, ref_obj_id, i; 754 755 spi = dynptr_get_spi(env, reg); 756 if (spi < 0) 757 return spi; 758 759 if (!dynptr_type_refcounted(state->stack[spi].spilled_ptr.dynptr.type)) { 760 invalidate_dynptr(env, state, spi); 761 return 0; 762 } 763 764 ref_obj_id = state->stack[spi].spilled_ptr.ref_obj_id; 765 766 /* If the dynptr has a ref_obj_id, then we need to invalidate 767 * two things: 768 * 769 * 1) Any dynptrs with a matching ref_obj_id (clones) 770 * 2) Any slices derived from this dynptr. 771 */ 772 773 /* Invalidate any slices associated with this dynptr */ 774 WARN_ON_ONCE(release_reference(env, ref_obj_id)); 775 776 /* Invalidate any dynptr clones */ 777 for (i = 1; i < state->allocated_stack / BPF_REG_SIZE; i++) { 778 if (state->stack[i].spilled_ptr.ref_obj_id != ref_obj_id) 779 continue; 780 781 /* it should always be the case that if the ref obj id 782 * matches then the stack slot also belongs to a 783 * dynptr 784 */ 785 if (state->stack[i].slot_type[0] != STACK_DYNPTR) { 786 verifier_bug(env, "misconfigured ref_obj_id"); 787 return -EFAULT; 788 } 789 if (state->stack[i].spilled_ptr.dynptr.first_slot) 790 invalidate_dynptr(env, state, i); 791 } 792 793 return 0; 794 } 795 796 static void __mark_reg_unknown(const struct bpf_verifier_env *env, 797 struct bpf_reg_state *reg); 798 799 static void mark_reg_invalid(const struct bpf_verifier_env *env, struct bpf_reg_state *reg) 800 { 801 if (!env->allow_ptr_leaks) 802 bpf_mark_reg_not_init(env, reg); 803 else 804 __mark_reg_unknown(env, reg); 805 } 806 807 static int destroy_if_dynptr_stack_slot(struct bpf_verifier_env *env, 808 struct bpf_func_state *state, int spi) 809 { 810 struct bpf_func_state *fstate; 811 struct bpf_reg_state *dreg; 812 int i, dynptr_id; 813 814 /* We always ensure that STACK_DYNPTR is never set partially, 815 * hence just checking for slot_type[0] is enough. This is 816 * different for STACK_SPILL, where it may be only set for 817 * 1 byte, so code has to use is_spilled_reg. 818 */ 819 if (state->stack[spi].slot_type[0] != STACK_DYNPTR) 820 return 0; 821 822 /* Reposition spi to first slot */ 823 if (!state->stack[spi].spilled_ptr.dynptr.first_slot) 824 spi = spi + 1; 825 826 if (dynptr_type_refcounted(state->stack[spi].spilled_ptr.dynptr.type)) { 827 int ref_obj_id = state->stack[spi].spilled_ptr.ref_obj_id; 828 int ref_cnt = 0; 829 830 /* 831 * A referenced dynptr can be overwritten only if there is at 832 * least one other dynptr sharing the same ref_obj_id, 833 * ensuring the reference can still be properly released. 834 */ 835 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) { 836 if (state->stack[i].slot_type[0] != STACK_DYNPTR) 837 continue; 838 if (!state->stack[i].spilled_ptr.dynptr.first_slot) 839 continue; 840 if (state->stack[i].spilled_ptr.ref_obj_id == ref_obj_id) 841 ref_cnt++; 842 } 843 844 if (ref_cnt <= 1) { 845 verbose(env, "cannot overwrite referenced dynptr\n"); 846 return -EINVAL; 847 } 848 } 849 850 mark_stack_slot_scratched(env, spi); 851 mark_stack_slot_scratched(env, spi - 1); 852 853 /* Writing partially to one dynptr stack slot destroys both. */ 854 for (i = 0; i < BPF_REG_SIZE; i++) { 855 state->stack[spi].slot_type[i] = STACK_INVALID; 856 state->stack[spi - 1].slot_type[i] = STACK_INVALID; 857 } 858 859 dynptr_id = state->stack[spi].spilled_ptr.id; 860 /* Invalidate any slices associated with this dynptr */ 861 bpf_for_each_reg_in_vstate(env->cur_state, fstate, dreg, ({ 862 /* Dynptr slices are only PTR_TO_MEM_OR_NULL and PTR_TO_MEM */ 863 if (dreg->type != (PTR_TO_MEM | PTR_MAYBE_NULL) && dreg->type != PTR_TO_MEM) 864 continue; 865 if (dreg->dynptr_id == dynptr_id) 866 mark_reg_invalid(env, dreg); 867 })); 868 869 /* Do not release reference state, we are destroying dynptr on stack, 870 * not using some helper to release it. Just reset register. 871 */ 872 bpf_mark_reg_not_init(env, &state->stack[spi].spilled_ptr); 873 bpf_mark_reg_not_init(env, &state->stack[spi - 1].spilled_ptr); 874 875 return 0; 876 } 877 878 static bool is_dynptr_reg_valid_uninit(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 879 { 880 int spi; 881 882 if (reg->type == CONST_PTR_TO_DYNPTR) 883 return false; 884 885 spi = dynptr_get_spi(env, reg); 886 887 /* -ERANGE (i.e. spi not falling into allocated stack slots) isn't an 888 * error because this just means the stack state hasn't been updated yet. 889 * We will do check_mem_access to check and update stack bounds later. 890 */ 891 if (spi < 0 && spi != -ERANGE) 892 return false; 893 894 /* We don't need to check if the stack slots are marked by previous 895 * dynptr initializations because we allow overwriting existing unreferenced 896 * STACK_DYNPTR slots, see mark_stack_slots_dynptr which calls 897 * destroy_if_dynptr_stack_slot to ensure dynptr objects at the slots we are 898 * touching are completely destructed before we reinitialize them for a new 899 * one. For referenced ones, destroy_if_dynptr_stack_slot returns an error early 900 * instead of delaying it until the end where the user will get "Unreleased 901 * reference" error. 902 */ 903 return true; 904 } 905 906 static bool is_dynptr_reg_valid_init(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 907 { 908 struct bpf_func_state *state = bpf_func(env, reg); 909 int i, spi; 910 911 /* This already represents first slot of initialized bpf_dynptr. 912 * 913 * CONST_PTR_TO_DYNPTR already has fixed and var_off as 0 due to 914 * check_func_arg_reg_off's logic, so we don't need to check its 915 * offset and alignment. 916 */ 917 if (reg->type == CONST_PTR_TO_DYNPTR) 918 return true; 919 920 spi = dynptr_get_spi(env, reg); 921 if (spi < 0) 922 return false; 923 if (!state->stack[spi].spilled_ptr.dynptr.first_slot) 924 return false; 925 926 for (i = 0; i < BPF_REG_SIZE; i++) { 927 if (state->stack[spi].slot_type[i] != STACK_DYNPTR || 928 state->stack[spi - 1].slot_type[i] != STACK_DYNPTR) 929 return false; 930 } 931 932 return true; 933 } 934 935 static bool is_dynptr_type_expected(struct bpf_verifier_env *env, struct bpf_reg_state *reg, 936 enum bpf_arg_type arg_type) 937 { 938 struct bpf_func_state *state = bpf_func(env, reg); 939 enum bpf_dynptr_type dynptr_type; 940 int spi; 941 942 /* ARG_PTR_TO_DYNPTR takes any type of dynptr */ 943 if (arg_type == ARG_PTR_TO_DYNPTR) 944 return true; 945 946 dynptr_type = arg_to_dynptr_type(arg_type); 947 if (reg->type == CONST_PTR_TO_DYNPTR) { 948 return reg->dynptr.type == dynptr_type; 949 } else { 950 spi = dynptr_get_spi(env, reg); 951 if (spi < 0) 952 return false; 953 return state->stack[spi].spilled_ptr.dynptr.type == dynptr_type; 954 } 955 } 956 957 static void __mark_reg_known_zero(struct bpf_reg_state *reg); 958 959 static bool in_rcu_cs(struct bpf_verifier_env *env); 960 961 static bool is_kfunc_rcu_protected(struct bpf_kfunc_call_arg_meta *meta); 962 963 static int mark_stack_slots_iter(struct bpf_verifier_env *env, 964 struct bpf_kfunc_call_arg_meta *meta, 965 struct bpf_reg_state *reg, int insn_idx, 966 struct btf *btf, u32 btf_id, int nr_slots) 967 { 968 struct bpf_func_state *state = bpf_func(env, reg); 969 int spi, i, j, id; 970 971 spi = iter_get_spi(env, reg, nr_slots); 972 if (spi < 0) 973 return spi; 974 975 id = acquire_reference(env, insn_idx); 976 if (id < 0) 977 return id; 978 979 for (i = 0; i < nr_slots; i++) { 980 struct bpf_stack_state *slot = &state->stack[spi - i]; 981 struct bpf_reg_state *st = &slot->spilled_ptr; 982 983 __mark_reg_known_zero(st); 984 st->type = PTR_TO_STACK; /* we don't have dedicated reg type */ 985 if (is_kfunc_rcu_protected(meta)) { 986 if (in_rcu_cs(env)) 987 st->type |= MEM_RCU; 988 else 989 st->type |= PTR_UNTRUSTED; 990 } 991 st->ref_obj_id = i == 0 ? id : 0; 992 st->iter.btf = btf; 993 st->iter.btf_id = btf_id; 994 st->iter.state = BPF_ITER_STATE_ACTIVE; 995 st->iter.depth = 0; 996 997 for (j = 0; j < BPF_REG_SIZE; j++) 998 slot->slot_type[j] = STACK_ITER; 999 1000 mark_stack_slot_scratched(env, spi - i); 1001 } 1002 1003 return 0; 1004 } 1005 1006 static int unmark_stack_slots_iter(struct bpf_verifier_env *env, 1007 struct bpf_reg_state *reg, int nr_slots) 1008 { 1009 struct bpf_func_state *state = bpf_func(env, reg); 1010 int spi, i, j; 1011 1012 spi = iter_get_spi(env, reg, nr_slots); 1013 if (spi < 0) 1014 return spi; 1015 1016 for (i = 0; i < nr_slots; i++) { 1017 struct bpf_stack_state *slot = &state->stack[spi - i]; 1018 struct bpf_reg_state *st = &slot->spilled_ptr; 1019 1020 if (i == 0) 1021 WARN_ON_ONCE(release_reference(env, st->ref_obj_id)); 1022 1023 bpf_mark_reg_not_init(env, st); 1024 1025 for (j = 0; j < BPF_REG_SIZE; j++) 1026 slot->slot_type[j] = STACK_INVALID; 1027 1028 mark_stack_slot_scratched(env, spi - i); 1029 } 1030 1031 return 0; 1032 } 1033 1034 static bool is_iter_reg_valid_uninit(struct bpf_verifier_env *env, 1035 struct bpf_reg_state *reg, int nr_slots) 1036 { 1037 struct bpf_func_state *state = bpf_func(env, reg); 1038 int spi, i, j; 1039 1040 /* For -ERANGE (i.e. spi not falling into allocated stack slots), we 1041 * will do check_mem_access to check and update stack bounds later, so 1042 * return true for that case. 1043 */ 1044 spi = iter_get_spi(env, reg, nr_slots); 1045 if (spi == -ERANGE) 1046 return true; 1047 if (spi < 0) 1048 return false; 1049 1050 for (i = 0; i < nr_slots; i++) { 1051 struct bpf_stack_state *slot = &state->stack[spi - i]; 1052 1053 for (j = 0; j < BPF_REG_SIZE; j++) 1054 if (slot->slot_type[j] == STACK_ITER) 1055 return false; 1056 } 1057 1058 return true; 1059 } 1060 1061 static int is_iter_reg_valid_init(struct bpf_verifier_env *env, struct bpf_reg_state *reg, 1062 struct btf *btf, u32 btf_id, int nr_slots) 1063 { 1064 struct bpf_func_state *state = bpf_func(env, reg); 1065 int spi, i, j; 1066 1067 spi = iter_get_spi(env, reg, nr_slots); 1068 if (spi < 0) 1069 return -EINVAL; 1070 1071 for (i = 0; i < nr_slots; i++) { 1072 struct bpf_stack_state *slot = &state->stack[spi - i]; 1073 struct bpf_reg_state *st = &slot->spilled_ptr; 1074 1075 if (st->type & PTR_UNTRUSTED) 1076 return -EPROTO; 1077 /* only main (first) slot has ref_obj_id set */ 1078 if (i == 0 && !st->ref_obj_id) 1079 return -EINVAL; 1080 if (i != 0 && st->ref_obj_id) 1081 return -EINVAL; 1082 if (st->iter.btf != btf || st->iter.btf_id != btf_id) 1083 return -EINVAL; 1084 1085 for (j = 0; j < BPF_REG_SIZE; j++) 1086 if (slot->slot_type[j] != STACK_ITER) 1087 return -EINVAL; 1088 } 1089 1090 return 0; 1091 } 1092 1093 static int acquire_irq_state(struct bpf_verifier_env *env, int insn_idx); 1094 static int release_irq_state(struct bpf_verifier_state *state, int id); 1095 1096 static int mark_stack_slot_irq_flag(struct bpf_verifier_env *env, 1097 struct bpf_kfunc_call_arg_meta *meta, 1098 struct bpf_reg_state *reg, int insn_idx, 1099 int kfunc_class) 1100 { 1101 struct bpf_func_state *state = bpf_func(env, reg); 1102 struct bpf_stack_state *slot; 1103 struct bpf_reg_state *st; 1104 int spi, i, id; 1105 1106 spi = irq_flag_get_spi(env, reg); 1107 if (spi < 0) 1108 return spi; 1109 1110 id = acquire_irq_state(env, insn_idx); 1111 if (id < 0) 1112 return id; 1113 1114 slot = &state->stack[spi]; 1115 st = &slot->spilled_ptr; 1116 1117 __mark_reg_known_zero(st); 1118 st->type = PTR_TO_STACK; /* we don't have dedicated reg type */ 1119 st->ref_obj_id = id; 1120 st->irq.kfunc_class = kfunc_class; 1121 1122 for (i = 0; i < BPF_REG_SIZE; i++) 1123 slot->slot_type[i] = STACK_IRQ_FLAG; 1124 1125 mark_stack_slot_scratched(env, spi); 1126 return 0; 1127 } 1128 1129 static int unmark_stack_slot_irq_flag(struct bpf_verifier_env *env, struct bpf_reg_state *reg, 1130 int kfunc_class) 1131 { 1132 struct bpf_func_state *state = bpf_func(env, reg); 1133 struct bpf_stack_state *slot; 1134 struct bpf_reg_state *st; 1135 int spi, i, err; 1136 1137 spi = irq_flag_get_spi(env, reg); 1138 if (spi < 0) 1139 return spi; 1140 1141 slot = &state->stack[spi]; 1142 st = &slot->spilled_ptr; 1143 1144 if (st->irq.kfunc_class != kfunc_class) { 1145 const char *flag_kfunc = st->irq.kfunc_class == IRQ_NATIVE_KFUNC ? "native" : "lock"; 1146 const char *used_kfunc = kfunc_class == IRQ_NATIVE_KFUNC ? "native" : "lock"; 1147 1148 verbose(env, "irq flag acquired by %s kfuncs cannot be restored with %s kfuncs\n", 1149 flag_kfunc, used_kfunc); 1150 return -EINVAL; 1151 } 1152 1153 err = release_irq_state(env->cur_state, st->ref_obj_id); 1154 WARN_ON_ONCE(err && err != -EACCES); 1155 if (err) { 1156 int insn_idx = 0; 1157 1158 for (int i = 0; i < env->cur_state->acquired_refs; i++) { 1159 if (env->cur_state->refs[i].id == env->cur_state->active_irq_id) { 1160 insn_idx = env->cur_state->refs[i].insn_idx; 1161 break; 1162 } 1163 } 1164 1165 verbose(env, "cannot restore irq state out of order, expected id=%d acquired at insn_idx=%d\n", 1166 env->cur_state->active_irq_id, insn_idx); 1167 return err; 1168 } 1169 1170 bpf_mark_reg_not_init(env, st); 1171 1172 for (i = 0; i < BPF_REG_SIZE; i++) 1173 slot->slot_type[i] = STACK_INVALID; 1174 1175 mark_stack_slot_scratched(env, spi); 1176 return 0; 1177 } 1178 1179 static bool is_irq_flag_reg_valid_uninit(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 1180 { 1181 struct bpf_func_state *state = bpf_func(env, reg); 1182 struct bpf_stack_state *slot; 1183 int spi, i; 1184 1185 /* For -ERANGE (i.e. spi not falling into allocated stack slots), we 1186 * will do check_mem_access to check and update stack bounds later, so 1187 * return true for that case. 1188 */ 1189 spi = irq_flag_get_spi(env, reg); 1190 if (spi == -ERANGE) 1191 return true; 1192 if (spi < 0) 1193 return false; 1194 1195 slot = &state->stack[spi]; 1196 1197 for (i = 0; i < BPF_REG_SIZE; i++) 1198 if (slot->slot_type[i] == STACK_IRQ_FLAG) 1199 return false; 1200 return true; 1201 } 1202 1203 static int is_irq_flag_reg_valid_init(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 1204 { 1205 struct bpf_func_state *state = bpf_func(env, reg); 1206 struct bpf_stack_state *slot; 1207 struct bpf_reg_state *st; 1208 int spi, i; 1209 1210 spi = irq_flag_get_spi(env, reg); 1211 if (spi < 0) 1212 return -EINVAL; 1213 1214 slot = &state->stack[spi]; 1215 st = &slot->spilled_ptr; 1216 1217 if (!st->ref_obj_id) 1218 return -EINVAL; 1219 1220 for (i = 0; i < BPF_REG_SIZE; i++) 1221 if (slot->slot_type[i] != STACK_IRQ_FLAG) 1222 return -EINVAL; 1223 return 0; 1224 } 1225 1226 /* Check if given stack slot is "special": 1227 * - spilled register state (STACK_SPILL); 1228 * - dynptr state (STACK_DYNPTR); 1229 * - iter state (STACK_ITER). 1230 * - irq flag state (STACK_IRQ_FLAG) 1231 */ 1232 static bool is_stack_slot_special(const struct bpf_stack_state *stack) 1233 { 1234 enum bpf_stack_slot_type type = stack->slot_type[BPF_REG_SIZE - 1]; 1235 1236 switch (type) { 1237 case STACK_SPILL: 1238 case STACK_DYNPTR: 1239 case STACK_ITER: 1240 case STACK_IRQ_FLAG: 1241 return true; 1242 case STACK_INVALID: 1243 case STACK_POISON: 1244 case STACK_MISC: 1245 case STACK_ZERO: 1246 return false; 1247 default: 1248 WARN_ONCE(1, "unknown stack slot type %d\n", type); 1249 return true; 1250 } 1251 } 1252 1253 /* The reg state of a pointer or a bounded scalar was saved when 1254 * it was spilled to the stack. 1255 */ 1256 1257 /* 1258 * Mark stack slot as STACK_MISC, unless it is already: 1259 * - STACK_INVALID, in which case they are equivalent. 1260 * - STACK_ZERO, in which case we preserve more precise STACK_ZERO. 1261 * - STACK_POISON, which truly forbids access to the slot. 1262 * Regardless of allow_ptr_leaks setting (i.e., privileged or unprivileged 1263 * mode), we won't promote STACK_INVALID to STACK_MISC. In privileged case it is 1264 * unnecessary as both are considered equivalent when loading data and pruning, 1265 * in case of unprivileged mode it will be incorrect to allow reads of invalid 1266 * slots. 1267 */ 1268 static void mark_stack_slot_misc(struct bpf_verifier_env *env, u8 *stype) 1269 { 1270 if (*stype == STACK_ZERO) 1271 return; 1272 if (*stype == STACK_INVALID || *stype == STACK_POISON) 1273 return; 1274 *stype = STACK_MISC; 1275 } 1276 1277 static void scrub_spilled_slot(u8 *stype) 1278 { 1279 if (*stype != STACK_INVALID && *stype != STACK_POISON) 1280 *stype = STACK_MISC; 1281 } 1282 1283 /* copy array src of length n * size bytes to dst. dst is reallocated if it's too 1284 * small to hold src. This is different from krealloc since we don't want to preserve 1285 * the contents of dst. 1286 * 1287 * Leaves dst untouched if src is NULL or length is zero. Returns NULL if memory could 1288 * not be allocated. 1289 */ 1290 static void *copy_array(void *dst, const void *src, size_t n, size_t size, gfp_t flags) 1291 { 1292 size_t alloc_bytes; 1293 void *orig = dst; 1294 size_t bytes; 1295 1296 if (ZERO_OR_NULL_PTR(src)) 1297 goto out; 1298 1299 if (unlikely(check_mul_overflow(n, size, &bytes))) 1300 return NULL; 1301 1302 alloc_bytes = max(ksize(orig), kmalloc_size_roundup(bytes)); 1303 dst = krealloc(orig, alloc_bytes, flags); 1304 if (!dst) { 1305 kfree(orig); 1306 return NULL; 1307 } 1308 1309 memcpy(dst, src, bytes); 1310 out: 1311 return dst ? dst : ZERO_SIZE_PTR; 1312 } 1313 1314 /* resize an array from old_n items to new_n items. the array is reallocated if it's too 1315 * small to hold new_n items. new items are zeroed out if the array grows. 1316 * 1317 * Contrary to krealloc_array, does not free arr if new_n is zero. 1318 */ 1319 static void *realloc_array(void *arr, size_t old_n, size_t new_n, size_t size) 1320 { 1321 size_t alloc_size; 1322 void *new_arr; 1323 1324 if (!new_n || old_n == new_n) 1325 goto out; 1326 1327 alloc_size = kmalloc_size_roundup(size_mul(new_n, size)); 1328 new_arr = krealloc(arr, alloc_size, GFP_KERNEL_ACCOUNT); 1329 if (!new_arr) { 1330 kfree(arr); 1331 return NULL; 1332 } 1333 arr = new_arr; 1334 1335 if (new_n > old_n) 1336 memset(arr + old_n * size, 0, (new_n - old_n) * size); 1337 1338 out: 1339 return arr ? arr : ZERO_SIZE_PTR; 1340 } 1341 1342 static int copy_reference_state(struct bpf_verifier_state *dst, const struct bpf_verifier_state *src) 1343 { 1344 dst->refs = copy_array(dst->refs, src->refs, src->acquired_refs, 1345 sizeof(struct bpf_reference_state), GFP_KERNEL_ACCOUNT); 1346 if (!dst->refs) 1347 return -ENOMEM; 1348 1349 dst->acquired_refs = src->acquired_refs; 1350 dst->active_locks = src->active_locks; 1351 dst->active_preempt_locks = src->active_preempt_locks; 1352 dst->active_rcu_locks = src->active_rcu_locks; 1353 dst->active_irq_id = src->active_irq_id; 1354 dst->active_lock_id = src->active_lock_id; 1355 dst->active_lock_ptr = src->active_lock_ptr; 1356 return 0; 1357 } 1358 1359 static int copy_stack_state(struct bpf_func_state *dst, const struct bpf_func_state *src) 1360 { 1361 size_t n = src->allocated_stack / BPF_REG_SIZE; 1362 1363 dst->stack = copy_array(dst->stack, src->stack, n, sizeof(struct bpf_stack_state), 1364 GFP_KERNEL_ACCOUNT); 1365 if (!dst->stack) 1366 return -ENOMEM; 1367 1368 dst->allocated_stack = src->allocated_stack; 1369 1370 /* copy stack args state */ 1371 n = src->out_stack_arg_cnt; 1372 if (n) { 1373 dst->stack_arg_regs = copy_array(dst->stack_arg_regs, src->stack_arg_regs, n, 1374 sizeof(struct bpf_reg_state), 1375 GFP_KERNEL_ACCOUNT); 1376 if (!dst->stack_arg_regs) 1377 return -ENOMEM; 1378 } 1379 1380 dst->out_stack_arg_cnt = src->out_stack_arg_cnt; 1381 return 0; 1382 } 1383 1384 static int resize_reference_state(struct bpf_verifier_state *state, size_t n) 1385 { 1386 state->refs = realloc_array(state->refs, state->acquired_refs, n, 1387 sizeof(struct bpf_reference_state)); 1388 if (!state->refs) 1389 return -ENOMEM; 1390 1391 state->acquired_refs = n; 1392 return 0; 1393 } 1394 1395 /* Possibly update state->allocated_stack to be at least size bytes. Also 1396 * possibly update the function's high-water mark in its bpf_subprog_info. 1397 */ 1398 static int grow_stack_state(struct bpf_verifier_env *env, struct bpf_func_state *state, int size) 1399 { 1400 size_t old_n = state->allocated_stack / BPF_REG_SIZE, n; 1401 1402 /* The stack size is always a multiple of BPF_REG_SIZE. */ 1403 size = round_up(size, BPF_REG_SIZE); 1404 n = size / BPF_REG_SIZE; 1405 1406 if (old_n >= n) 1407 return 0; 1408 1409 state->stack = realloc_array(state->stack, old_n, n, sizeof(struct bpf_stack_state)); 1410 if (!state->stack) 1411 return -ENOMEM; 1412 1413 state->allocated_stack = size; 1414 1415 /* update known max for given subprogram */ 1416 if (env->subprog_info[state->subprogno].stack_depth < size) 1417 env->subprog_info[state->subprogno].stack_depth = size; 1418 1419 return 0; 1420 } 1421 1422 static int grow_stack_arg_slots(struct bpf_verifier_env *env, 1423 struct bpf_func_state *state, int cnt) 1424 { 1425 size_t old_n = state->out_stack_arg_cnt; 1426 1427 if (old_n >= cnt) 1428 return 0; 1429 1430 state->stack_arg_regs = realloc_array(state->stack_arg_regs, old_n, cnt, 1431 sizeof(struct bpf_reg_state)); 1432 if (!state->stack_arg_regs) 1433 return -ENOMEM; 1434 1435 state->out_stack_arg_cnt = cnt; 1436 return 0; 1437 } 1438 1439 /* Acquire a pointer id from the env and update the state->refs to include 1440 * this new pointer reference. 1441 * On success, returns a valid pointer id to associate with the register 1442 * On failure, returns a negative errno. 1443 */ 1444 static struct bpf_reference_state *acquire_reference_state(struct bpf_verifier_env *env, int insn_idx) 1445 { 1446 struct bpf_verifier_state *state = env->cur_state; 1447 int new_ofs = state->acquired_refs; 1448 int err; 1449 1450 err = resize_reference_state(state, state->acquired_refs + 1); 1451 if (err) 1452 return NULL; 1453 state->refs[new_ofs].insn_idx = insn_idx; 1454 1455 return &state->refs[new_ofs]; 1456 } 1457 1458 static int acquire_reference(struct bpf_verifier_env *env, int insn_idx) 1459 { 1460 struct bpf_reference_state *s; 1461 1462 s = acquire_reference_state(env, insn_idx); 1463 if (!s) 1464 return -ENOMEM; 1465 s->type = REF_TYPE_PTR; 1466 s->id = ++env->id_gen; 1467 return s->id; 1468 } 1469 1470 static int acquire_lock_state(struct bpf_verifier_env *env, int insn_idx, enum ref_state_type type, 1471 int id, void *ptr) 1472 { 1473 struct bpf_verifier_state *state = env->cur_state; 1474 struct bpf_reference_state *s; 1475 1476 s = acquire_reference_state(env, insn_idx); 1477 if (!s) 1478 return -ENOMEM; 1479 s->type = type; 1480 s->id = id; 1481 s->ptr = ptr; 1482 1483 state->active_locks++; 1484 state->active_lock_id = id; 1485 state->active_lock_ptr = ptr; 1486 return 0; 1487 } 1488 1489 static int acquire_irq_state(struct bpf_verifier_env *env, int insn_idx) 1490 { 1491 struct bpf_verifier_state *state = env->cur_state; 1492 struct bpf_reference_state *s; 1493 1494 s = acquire_reference_state(env, insn_idx); 1495 if (!s) 1496 return -ENOMEM; 1497 s->type = REF_TYPE_IRQ; 1498 s->id = ++env->id_gen; 1499 1500 state->active_irq_id = s->id; 1501 return s->id; 1502 } 1503 1504 static void release_reference_state(struct bpf_verifier_state *state, int idx) 1505 { 1506 int last_idx; 1507 size_t rem; 1508 1509 /* IRQ state requires the relative ordering of elements remaining the 1510 * same, since it relies on the refs array to behave as a stack, so that 1511 * it can detect out-of-order IRQ restore. Hence use memmove to shift 1512 * the array instead of swapping the final element into the deleted idx. 1513 */ 1514 last_idx = state->acquired_refs - 1; 1515 rem = state->acquired_refs - idx - 1; 1516 if (last_idx && idx != last_idx) 1517 memmove(&state->refs[idx], &state->refs[idx + 1], sizeof(*state->refs) * rem); 1518 memset(&state->refs[last_idx], 0, sizeof(*state->refs)); 1519 state->acquired_refs--; 1520 return; 1521 } 1522 1523 static bool find_reference_state(struct bpf_verifier_state *state, int ptr_id) 1524 { 1525 int i; 1526 1527 for (i = 0; i < state->acquired_refs; i++) 1528 if (state->refs[i].id == ptr_id) 1529 return true; 1530 1531 return false; 1532 } 1533 1534 static int release_lock_state(struct bpf_verifier_state *state, int type, int id, void *ptr) 1535 { 1536 void *prev_ptr = NULL; 1537 u32 prev_id = 0; 1538 int i; 1539 1540 for (i = 0; i < state->acquired_refs; i++) { 1541 if (state->refs[i].type == type && state->refs[i].id == id && 1542 state->refs[i].ptr == ptr) { 1543 release_reference_state(state, i); 1544 state->active_locks--; 1545 /* Reassign active lock (id, ptr). */ 1546 state->active_lock_id = prev_id; 1547 state->active_lock_ptr = prev_ptr; 1548 return 0; 1549 } 1550 if (state->refs[i].type & REF_TYPE_LOCK_MASK) { 1551 prev_id = state->refs[i].id; 1552 prev_ptr = state->refs[i].ptr; 1553 } 1554 } 1555 return -EINVAL; 1556 } 1557 1558 static int release_irq_state(struct bpf_verifier_state *state, int id) 1559 { 1560 u32 prev_id = 0; 1561 int i; 1562 1563 if (id != state->active_irq_id) 1564 return -EACCES; 1565 1566 for (i = 0; i < state->acquired_refs; i++) { 1567 if (state->refs[i].type != REF_TYPE_IRQ) 1568 continue; 1569 if (state->refs[i].id == id) { 1570 release_reference_state(state, i); 1571 state->active_irq_id = prev_id; 1572 return 0; 1573 } else { 1574 prev_id = state->refs[i].id; 1575 } 1576 } 1577 return -EINVAL; 1578 } 1579 1580 static struct bpf_reference_state *find_lock_state(struct bpf_verifier_state *state, enum ref_state_type type, 1581 int id, void *ptr) 1582 { 1583 int i; 1584 1585 for (i = 0; i < state->acquired_refs; i++) { 1586 struct bpf_reference_state *s = &state->refs[i]; 1587 1588 if (!(s->type & type)) 1589 continue; 1590 1591 if (s->id == id && s->ptr == ptr) 1592 return s; 1593 } 1594 return NULL; 1595 } 1596 1597 static void free_func_state(struct bpf_func_state *state) 1598 { 1599 if (!state) 1600 return; 1601 kfree(state->stack_arg_regs); 1602 kfree(state->stack); 1603 kfree(state); 1604 } 1605 1606 void bpf_clear_jmp_history(struct bpf_verifier_state *state) 1607 { 1608 kfree(state->jmp_history); 1609 state->jmp_history = NULL; 1610 state->jmp_history_cnt = 0; 1611 } 1612 1613 void bpf_free_verifier_state(struct bpf_verifier_state *state, 1614 bool free_self) 1615 { 1616 int i; 1617 1618 for (i = 0; i <= state->curframe; i++) { 1619 free_func_state(state->frame[i]); 1620 state->frame[i] = NULL; 1621 } 1622 kfree(state->refs); 1623 bpf_clear_jmp_history(state); 1624 if (free_self) 1625 kfree(state); 1626 } 1627 1628 /* copy verifier state from src to dst growing dst stack space 1629 * when necessary to accommodate larger src stack 1630 */ 1631 static int copy_func_state(struct bpf_func_state *dst, 1632 const struct bpf_func_state *src) 1633 { 1634 memcpy(dst, src, offsetof(struct bpf_func_state, stack)); 1635 return copy_stack_state(dst, src); 1636 } 1637 1638 int bpf_copy_verifier_state(struct bpf_verifier_state *dst_state, 1639 const struct bpf_verifier_state *src) 1640 { 1641 struct bpf_func_state *dst; 1642 int i, err; 1643 1644 dst_state->jmp_history = copy_array(dst_state->jmp_history, src->jmp_history, 1645 src->jmp_history_cnt, sizeof(*dst_state->jmp_history), 1646 GFP_KERNEL_ACCOUNT); 1647 if (!dst_state->jmp_history) 1648 return -ENOMEM; 1649 dst_state->jmp_history_cnt = src->jmp_history_cnt; 1650 1651 /* if dst has more stack frames then src frame, free them, this is also 1652 * necessary in case of exceptional exits using bpf_throw. 1653 */ 1654 for (i = src->curframe + 1; i <= dst_state->curframe; i++) { 1655 free_func_state(dst_state->frame[i]); 1656 dst_state->frame[i] = NULL; 1657 } 1658 err = copy_reference_state(dst_state, src); 1659 if (err) 1660 return err; 1661 dst_state->speculative = src->speculative; 1662 dst_state->in_sleepable = src->in_sleepable; 1663 dst_state->curframe = src->curframe; 1664 dst_state->branches = src->branches; 1665 dst_state->parent = src->parent; 1666 dst_state->first_insn_idx = src->first_insn_idx; 1667 dst_state->last_insn_idx = src->last_insn_idx; 1668 dst_state->dfs_depth = src->dfs_depth; 1669 dst_state->callback_unroll_depth = src->callback_unroll_depth; 1670 dst_state->may_goto_depth = src->may_goto_depth; 1671 dst_state->equal_state = src->equal_state; 1672 for (i = 0; i <= src->curframe; i++) { 1673 dst = dst_state->frame[i]; 1674 if (!dst) { 1675 dst = kzalloc_obj(*dst, GFP_KERNEL_ACCOUNT); 1676 if (!dst) 1677 return -ENOMEM; 1678 dst_state->frame[i] = dst; 1679 } 1680 err = copy_func_state(dst, src->frame[i]); 1681 if (err) 1682 return err; 1683 } 1684 return 0; 1685 } 1686 1687 static u32 state_htab_size(struct bpf_verifier_env *env) 1688 { 1689 return env->prog->len; 1690 } 1691 1692 struct list_head *bpf_explored_state(struct bpf_verifier_env *env, int idx) 1693 { 1694 struct bpf_verifier_state *cur = env->cur_state; 1695 struct bpf_func_state *state = cur->frame[cur->curframe]; 1696 1697 return &env->explored_states[(idx ^ state->callsite) % state_htab_size(env)]; 1698 } 1699 1700 static bool same_callsites(struct bpf_verifier_state *a, struct bpf_verifier_state *b) 1701 { 1702 int fr; 1703 1704 if (a->curframe != b->curframe) 1705 return false; 1706 1707 for (fr = a->curframe; fr >= 0; fr--) 1708 if (a->frame[fr]->callsite != b->frame[fr]->callsite) 1709 return false; 1710 1711 return true; 1712 } 1713 1714 1715 void bpf_free_backedges(struct bpf_scc_visit *visit) 1716 { 1717 struct bpf_scc_backedge *backedge, *next; 1718 1719 for (backedge = visit->backedges; backedge; backedge = next) { 1720 bpf_free_verifier_state(&backedge->state, false); 1721 next = backedge->next; 1722 kfree(backedge); 1723 } 1724 visit->backedges = NULL; 1725 } 1726 1727 static int pop_stack(struct bpf_verifier_env *env, int *prev_insn_idx, 1728 int *insn_idx, bool pop_log) 1729 { 1730 struct bpf_verifier_state *cur = env->cur_state; 1731 struct bpf_verifier_stack_elem *elem, *head = env->head; 1732 int err; 1733 1734 if (env->head == NULL) 1735 return -ENOENT; 1736 1737 if (cur) { 1738 err = bpf_copy_verifier_state(cur, &head->st); 1739 if (err) 1740 return err; 1741 } 1742 if (pop_log) 1743 bpf_vlog_reset(&env->log, head->log_pos); 1744 if (insn_idx) 1745 *insn_idx = head->insn_idx; 1746 if (prev_insn_idx) 1747 *prev_insn_idx = head->prev_insn_idx; 1748 elem = head->next; 1749 bpf_free_verifier_state(&head->st, false); 1750 kfree(head); 1751 env->head = elem; 1752 env->stack_size--; 1753 return 0; 1754 } 1755 1756 static bool error_recoverable_with_nospec(int err) 1757 { 1758 /* Should only return true for non-fatal errors that are allowed to 1759 * occur during speculative verification. For these we can insert a 1760 * nospec and the program might still be accepted. Do not include 1761 * something like ENOMEM because it is likely to re-occur for the next 1762 * architectural path once it has been recovered-from in all speculative 1763 * paths. 1764 */ 1765 return err == -EPERM || err == -EACCES || err == -EINVAL; 1766 } 1767 1768 static struct bpf_verifier_state *push_stack(struct bpf_verifier_env *env, 1769 int insn_idx, int prev_insn_idx, 1770 bool speculative) 1771 { 1772 struct bpf_verifier_state *cur = env->cur_state; 1773 struct bpf_verifier_stack_elem *elem; 1774 int err; 1775 1776 elem = kzalloc_obj(struct bpf_verifier_stack_elem, GFP_KERNEL_ACCOUNT); 1777 if (!elem) 1778 return ERR_PTR(-ENOMEM); 1779 1780 elem->insn_idx = insn_idx; 1781 elem->prev_insn_idx = prev_insn_idx; 1782 elem->next = env->head; 1783 elem->log_pos = env->log.end_pos; 1784 env->head = elem; 1785 env->stack_size++; 1786 err = bpf_copy_verifier_state(&elem->st, cur); 1787 if (err) 1788 return ERR_PTR(-ENOMEM); 1789 elem->st.speculative |= speculative; 1790 if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) { 1791 verbose(env, "The sequence of %d jumps is too complex.\n", 1792 env->stack_size); 1793 return ERR_PTR(-E2BIG); 1794 } 1795 if (elem->st.parent) { 1796 ++elem->st.parent->branches; 1797 /* WARN_ON(branches > 2) technically makes sense here, 1798 * but 1799 * 1. speculative states will bump 'branches' for non-branch 1800 * instructions 1801 * 2. is_state_visited() heuristics may decide not to create 1802 * a new state for a sequence of branches and all such current 1803 * and cloned states will be pointing to a single parent state 1804 * which might have large 'branches' count. 1805 */ 1806 } 1807 return &elem->st; 1808 } 1809 1810 static const char *reg_arg_name(struct bpf_verifier_env *env, argno_t argno) 1811 { 1812 char *buf = env->tmp_arg_name; 1813 int len = sizeof(env->tmp_arg_name); 1814 int arg, regno = reg_from_argno(argno); 1815 1816 if (regno >= 0) { 1817 snprintf(buf, len, "R%d", regno); 1818 } else { 1819 arg = arg_from_argno(argno); 1820 snprintf(buf, len, "*(R11-%u)", (arg - MAX_BPF_FUNC_REG_ARGS) * BPF_REG_SIZE); 1821 } 1822 1823 return buf; 1824 } 1825 1826 static const int caller_saved[CALLER_SAVED_REGS] = { 1827 BPF_REG_0, BPF_REG_1, BPF_REG_2, BPF_REG_3, BPF_REG_4, BPF_REG_5 1828 }; 1829 1830 /* This helper doesn't clear reg->id */ 1831 static void ___mark_reg_known(struct bpf_reg_state *reg, u64 imm) 1832 { 1833 reg->var_off = tnum_const(imm); 1834 reg->r64 = cnum64_from_urange(imm, imm); 1835 reg->r32 = cnum32_from_urange((u32)imm, (u32)imm); 1836 } 1837 1838 /* Mark the unknown part of a register (variable offset or scalar value) as 1839 * known to have the value @imm. 1840 */ 1841 static void __mark_reg_known(struct bpf_reg_state *reg, u64 imm) 1842 { 1843 /* Clear off and union(map_ptr, range) */ 1844 memset(((u8 *)reg) + sizeof(reg->type), 0, 1845 offsetof(struct bpf_reg_state, var_off) - sizeof(reg->type)); 1846 reg->id = 0; 1847 reg->ref_obj_id = 0; 1848 ___mark_reg_known(reg, imm); 1849 } 1850 1851 static void __mark_reg32_known(struct bpf_reg_state *reg, u64 imm) 1852 { 1853 reg->var_off = tnum_const_subreg(reg->var_off, imm); 1854 reg->r32 = cnum32_from_urange((u32)imm, (u32)imm); 1855 } 1856 1857 /* Mark the 'variable offset' part of a register as zero. This should be 1858 * used only on registers holding a pointer type. 1859 */ 1860 static void __mark_reg_known_zero(struct bpf_reg_state *reg) 1861 { 1862 __mark_reg_known(reg, 0); 1863 } 1864 1865 static void __mark_reg_const_zero(const struct bpf_verifier_env *env, struct bpf_reg_state *reg) 1866 { 1867 __mark_reg_known(reg, 0); 1868 reg->type = SCALAR_VALUE; 1869 /* all scalars are assumed imprecise initially (unless unprivileged, 1870 * in which case everything is forced to be precise) 1871 */ 1872 reg->precise = !env->bpf_capable; 1873 } 1874 1875 static void mark_reg_known_zero(struct bpf_verifier_env *env, 1876 struct bpf_reg_state *regs, u32 regno) 1877 { 1878 __mark_reg_known_zero(regs + regno); 1879 } 1880 1881 static void __mark_dynptr_reg(struct bpf_reg_state *reg, enum bpf_dynptr_type type, 1882 bool first_slot, int dynptr_id) 1883 { 1884 /* reg->type has no meaning for STACK_DYNPTR, but when we set reg for 1885 * callback arguments, it does need to be CONST_PTR_TO_DYNPTR, so simply 1886 * set it unconditionally as it is ignored for STACK_DYNPTR anyway. 1887 */ 1888 __mark_reg_known_zero(reg); 1889 reg->type = CONST_PTR_TO_DYNPTR; 1890 /* Give each dynptr a unique id to uniquely associate slices to it. */ 1891 reg->id = dynptr_id; 1892 reg->dynptr.type = type; 1893 reg->dynptr.first_slot = first_slot; 1894 } 1895 1896 static void mark_ptr_not_null_reg(struct bpf_reg_state *reg) 1897 { 1898 if (base_type(reg->type) == PTR_TO_MAP_VALUE) { 1899 const struct bpf_map *map = reg->map_ptr; 1900 1901 if (map->inner_map_meta) { 1902 reg->type = CONST_PTR_TO_MAP; 1903 reg->map_ptr = map->inner_map_meta; 1904 /* transfer reg's id which is unique for every map_lookup_elem 1905 * as UID of the inner map. 1906 */ 1907 if (btf_record_has_field(map->inner_map_meta->record, 1908 BPF_TIMER | BPF_WORKQUEUE | BPF_TASK_WORK)) { 1909 reg->map_uid = reg->id; 1910 } 1911 } else if (map->map_type == BPF_MAP_TYPE_XSKMAP) { 1912 reg->type = PTR_TO_XDP_SOCK; 1913 } else if (map->map_type == BPF_MAP_TYPE_SOCKMAP || 1914 map->map_type == BPF_MAP_TYPE_SOCKHASH) { 1915 reg->type = PTR_TO_SOCKET; 1916 } else { 1917 reg->type = PTR_TO_MAP_VALUE; 1918 } 1919 return; 1920 } 1921 1922 reg->type &= ~PTR_MAYBE_NULL; 1923 } 1924 1925 static void mark_reg_graph_node(struct bpf_reg_state *regs, u32 regno, 1926 struct btf_field_graph_root *ds_head) 1927 { 1928 __mark_reg_known(®s[regno], ds_head->node_offset); 1929 regs[regno].type = PTR_TO_BTF_ID | MEM_ALLOC; 1930 regs[regno].btf = ds_head->btf; 1931 regs[regno].btf_id = ds_head->value_btf_id; 1932 } 1933 1934 static bool reg_is_pkt_pointer(const struct bpf_reg_state *reg) 1935 { 1936 return type_is_pkt_pointer(reg->type); 1937 } 1938 1939 static bool reg_is_pkt_pointer_any(const struct bpf_reg_state *reg) 1940 { 1941 return reg_is_pkt_pointer(reg) || 1942 reg->type == PTR_TO_PACKET_END; 1943 } 1944 1945 static bool reg_is_dynptr_slice_pkt(const struct bpf_reg_state *reg) 1946 { 1947 return base_type(reg->type) == PTR_TO_MEM && 1948 (reg->type & 1949 (DYNPTR_TYPE_SKB | DYNPTR_TYPE_XDP | DYNPTR_TYPE_SKB_META)); 1950 } 1951 1952 /* Unmodified PTR_TO_PACKET[_META,_END] register from ctx access. */ 1953 static bool reg_is_init_pkt_pointer(const struct bpf_reg_state *reg, 1954 enum bpf_reg_type which) 1955 { 1956 /* The register can already have a range from prior markings. 1957 * This is fine as long as it hasn't been advanced from its 1958 * origin. 1959 */ 1960 return reg->type == which && 1961 reg->id == 0 && 1962 tnum_equals_const(reg->var_off, 0); 1963 } 1964 1965 static void __mark_reg32_unbounded(struct bpf_reg_state *reg) 1966 { 1967 reg->r32 = CNUM32_UNBOUNDED; 1968 } 1969 1970 static void __mark_reg64_unbounded(struct bpf_reg_state *reg) 1971 { 1972 reg->r64 = CNUM64_UNBOUNDED; 1973 } 1974 1975 /* Reset the min/max bounds of a register */ 1976 static void __mark_reg_unbounded(struct bpf_reg_state *reg) 1977 { 1978 __mark_reg64_unbounded(reg); 1979 __mark_reg32_unbounded(reg); 1980 } 1981 1982 static void reset_reg64_and_tnum(struct bpf_reg_state *reg) 1983 { 1984 __mark_reg64_unbounded(reg); 1985 reg->var_off = tnum_unknown; 1986 } 1987 1988 static void reset_reg32_and_tnum(struct bpf_reg_state *reg) 1989 { 1990 __mark_reg32_unbounded(reg); 1991 reg->var_off = tnum_unknown; 1992 } 1993 1994 static struct cnum32 cnum32_from_tnum(struct tnum tnum) 1995 { 1996 tnum = tnum_subreg(tnum); 1997 if ((tnum.mask & S32_MIN) || (tnum.value & S32_MIN)) 1998 /* min signed is max(sign bit) | min(other bits) */ 1999 /* max signed is min(sign bit) | max(other bits) */ 2000 return cnum32_from_srange(tnum.value | (tnum.mask & S32_MIN), 2001 tnum.value | (tnum.mask & S32_MAX)); 2002 else 2003 return cnum32_from_urange(tnum.value, (tnum.value | tnum.mask)); 2004 } 2005 2006 static struct cnum64 cnum64_from_tnum(struct tnum tnum) 2007 { 2008 if ((tnum.mask & S64_MIN) || (tnum.value & S64_MIN)) 2009 /* min signed is max(sign bit) | min(other bits) */ 2010 /* max signed is min(sign bit) | max(other bits) */ 2011 return cnum64_from_srange(tnum.value | (tnum.mask & S64_MIN), 2012 tnum.value | (tnum.mask & S64_MAX)); 2013 else 2014 return cnum64_from_urange(tnum.value, (tnum.value | tnum.mask)); 2015 } 2016 2017 static void __update_reg32_bounds(struct bpf_reg_state *reg) 2018 { 2019 cnum32_intersect_with(®->r32, cnum32_from_tnum(reg->var_off)); 2020 } 2021 2022 static void __update_reg64_bounds(struct bpf_reg_state *reg) 2023 { 2024 u64 tnum_next, tmax; 2025 bool umin_in_tnum; 2026 2027 cnum64_intersect_with(®->r64, cnum64_from_tnum(reg->var_off)); 2028 2029 /* Check if u64 and tnum overlap in a single value */ 2030 tnum_next = tnum_step(reg->var_off, reg_umin(reg)); 2031 umin_in_tnum = (reg_umin(reg) & ~reg->var_off.mask) == reg->var_off.value; 2032 tmax = reg->var_off.value | reg->var_off.mask; 2033 if (umin_in_tnum && tnum_next > reg_umax(reg)) { 2034 /* The u64 range and the tnum only overlap in umin. 2035 * u64: ---[xxxxxx]----- 2036 * tnum: --xx----------x- 2037 */ 2038 ___mark_reg_known(reg, reg_umin(reg)); 2039 } else if (!umin_in_tnum && tnum_next == tmax) { 2040 /* The u64 range and the tnum only overlap in the maximum value 2041 * represented by the tnum, called tmax. 2042 * u64: ---[xxxxxx]----- 2043 * tnum: xx-----x-------- 2044 */ 2045 ___mark_reg_known(reg, tmax); 2046 } else if (!umin_in_tnum && tnum_next <= reg_umax(reg) && 2047 tnum_step(reg->var_off, tnum_next) > reg_umax(reg)) { 2048 /* The u64 range and the tnum only overlap in between umin 2049 * (excluded) and umax. 2050 * u64: ---[xxxxxx]----- 2051 * tnum: xx----x-------x- 2052 */ 2053 ___mark_reg_known(reg, tnum_next); 2054 } 2055 } 2056 2057 static void __update_reg_bounds(struct bpf_reg_state *reg) 2058 { 2059 __update_reg32_bounds(reg); 2060 __update_reg64_bounds(reg); 2061 } 2062 2063 static void deduce_bounds_32_from_64(struct bpf_reg_state *reg) 2064 { 2065 cnum32_intersect_with(®->r32, cnum32_from_cnum64(reg->r64)); 2066 } 2067 2068 static void deduce_bounds_64_from_32(struct bpf_reg_state *reg) 2069 { 2070 reg->r64 = cnum64_cnum32_intersect(reg->r64, reg->r32); 2071 } 2072 2073 static void __reg_deduce_bounds(struct bpf_reg_state *reg) 2074 { 2075 deduce_bounds_32_from_64(reg); 2076 deduce_bounds_64_from_32(reg); 2077 } 2078 2079 /* Attempts to improve var_off based on unsigned min/max information */ 2080 static void __reg_bound_offset(struct bpf_reg_state *reg) 2081 { 2082 struct tnum var64_off = tnum_intersect(reg->var_off, 2083 tnum_range(reg_umin(reg), 2084 reg_umax(reg))); 2085 struct tnum var32_off = tnum_intersect(tnum_subreg(var64_off), 2086 tnum_range(reg_u32_min(reg), 2087 reg_u32_max(reg))); 2088 2089 reg->var_off = tnum_or(tnum_clear_subreg(var64_off), var32_off); 2090 } 2091 2092 static bool range_bounds_violation(struct bpf_reg_state *reg); 2093 2094 static void reg_bounds_sync(struct bpf_reg_state *reg) 2095 { 2096 /* If the input reg_state is invalid, we can exit early */ 2097 if (range_bounds_violation(reg)) 2098 return; 2099 /* We might have learned new bounds from the var_off. */ 2100 __update_reg_bounds(reg); 2101 /* We might have learned something about the sign bit. */ 2102 __reg_deduce_bounds(reg); 2103 __reg_deduce_bounds(reg); 2104 /* We might have learned some bits from the bounds. */ 2105 __reg_bound_offset(reg); 2106 /* Intersecting with the old var_off might have improved our bounds 2107 * slightly, e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc), 2108 * then new var_off is (0; 0x7f...fc) which improves our umax. 2109 */ 2110 __update_reg_bounds(reg); 2111 } 2112 2113 static bool const_tnum_range_mismatch(struct bpf_reg_state *reg) 2114 { 2115 if (!tnum_is_const(reg->var_off)) 2116 return false; 2117 2118 return !cnum64_is_const(reg->r64) || reg->r64.base != reg->var_off.value; 2119 } 2120 2121 static bool const_tnum_range_mismatch_32(struct bpf_reg_state *reg) 2122 { 2123 if (!tnum_subreg_is_const(reg->var_off)) 2124 return false; 2125 2126 return !cnum32_is_const(reg->r32) || reg->r32.base != tnum_subreg(reg->var_off).value; 2127 } 2128 2129 static bool range_bounds_violation(struct bpf_reg_state *reg) 2130 { 2131 return cnum32_is_empty(reg->r32) || cnum64_is_empty(reg->r64); 2132 } 2133 2134 static int reg_bounds_sanity_check(struct bpf_verifier_env *env, 2135 struct bpf_reg_state *reg, const char *ctx) 2136 { 2137 const char *msg; 2138 2139 if (range_bounds_violation(reg)) { 2140 msg = "range bounds violation"; 2141 goto out; 2142 } 2143 2144 if (const_tnum_range_mismatch(reg)) { 2145 msg = "const tnum out of sync with range bounds"; 2146 goto out; 2147 } 2148 2149 if (const_tnum_range_mismatch_32(reg)) { 2150 msg = "const subreg tnum out of sync with range bounds"; 2151 goto out; 2152 } 2153 2154 return 0; 2155 out: 2156 verifier_bug(env, "REG INVARIANTS VIOLATION (%s): %s r64={.base=%#llx, .size=%#llx} " 2157 "r32={.base=%#x, .size=%#x} var_off=(%#llx, %#llx)", 2158 ctx, msg, 2159 reg->r64.base, reg->r64.size, 2160 reg->r32.base, reg->r32.size, 2161 reg->var_off.value, reg->var_off.mask); 2162 if (env->test_reg_invariants) 2163 return -EFAULT; 2164 __mark_reg_unbounded(reg); 2165 return 0; 2166 } 2167 2168 /* Mark a register as having a completely unknown (scalar) value. */ 2169 void bpf_mark_reg_unknown_imprecise(struct bpf_reg_state *reg) 2170 { 2171 /* 2172 * Clear type, off, and union(map_ptr, range) and 2173 * padding between 'type' and union 2174 */ 2175 memset(reg, 0, offsetof(struct bpf_reg_state, var_off)); 2176 reg->type = SCALAR_VALUE; 2177 reg->id = 0; 2178 reg->ref_obj_id = 0; 2179 reg->var_off = tnum_unknown; 2180 reg->frameno = 0; 2181 reg->precise = false; 2182 __mark_reg_unbounded(reg); 2183 } 2184 2185 /* Mark a register as having a completely unknown (scalar) value, 2186 * initialize .precise as true when not bpf capable. 2187 */ 2188 static void __mark_reg_unknown(const struct bpf_verifier_env *env, 2189 struct bpf_reg_state *reg) 2190 { 2191 bpf_mark_reg_unknown_imprecise(reg); 2192 reg->precise = !env->bpf_capable; 2193 } 2194 2195 static void mark_reg_unknown(struct bpf_verifier_env *env, 2196 struct bpf_reg_state *regs, u32 regno) 2197 { 2198 __mark_reg_unknown(env, regs + regno); 2199 } 2200 2201 static int __mark_reg_s32_range(struct bpf_verifier_env *env, 2202 struct bpf_reg_state *regs, 2203 u32 regno, 2204 s32 s32_min, 2205 s32 s32_max) 2206 { 2207 struct bpf_reg_state *reg = regs + regno; 2208 2209 reg_set_srange32(reg, 2210 max_t(s32, reg_s32_min(reg), s32_min), 2211 min_t(s32, reg_s32_max(reg), s32_max)); 2212 reg_set_srange64(reg, 2213 max_t(s64, reg_smin(reg), s32_min), 2214 min_t(s64, reg_smax(reg), s32_max)); 2215 2216 reg_bounds_sync(reg); 2217 2218 return reg_bounds_sanity_check(env, reg, "s32_range"); 2219 } 2220 2221 void bpf_mark_reg_not_init(const struct bpf_verifier_env *env, 2222 struct bpf_reg_state *reg) 2223 { 2224 __mark_reg_unknown(env, reg); 2225 reg->type = NOT_INIT; 2226 } 2227 2228 static int mark_btf_ld_reg(struct bpf_verifier_env *env, 2229 struct bpf_reg_state *regs, u32 regno, 2230 enum bpf_reg_type reg_type, 2231 struct btf *btf, u32 btf_id, 2232 enum bpf_type_flag flag) 2233 { 2234 switch (reg_type) { 2235 case SCALAR_VALUE: 2236 mark_reg_unknown(env, regs, regno); 2237 return 0; 2238 case PTR_TO_BTF_ID: 2239 mark_reg_known_zero(env, regs, regno); 2240 regs[regno].type = PTR_TO_BTF_ID | flag; 2241 regs[regno].btf = btf; 2242 regs[regno].btf_id = btf_id; 2243 if (type_may_be_null(flag)) 2244 regs[regno].id = ++env->id_gen; 2245 return 0; 2246 case PTR_TO_MEM: 2247 mark_reg_known_zero(env, regs, regno); 2248 regs[regno].type = PTR_TO_MEM | flag; 2249 regs[regno].mem_size = 0; 2250 return 0; 2251 default: 2252 verifier_bug(env, "unexpected reg_type %d in %s\n", reg_type, __func__); 2253 return -EFAULT; 2254 } 2255 } 2256 2257 #define DEF_NOT_SUBREG (0) 2258 static void init_reg_state(struct bpf_verifier_env *env, 2259 struct bpf_func_state *state) 2260 { 2261 struct bpf_reg_state *regs = state->regs; 2262 int i; 2263 2264 for (i = 0; i < MAX_BPF_REG; i++) { 2265 bpf_mark_reg_not_init(env, ®s[i]); 2266 regs[i].subreg_def = DEF_NOT_SUBREG; 2267 } 2268 2269 /* frame pointer */ 2270 regs[BPF_REG_FP].type = PTR_TO_STACK; 2271 mark_reg_known_zero(env, regs, BPF_REG_FP); 2272 regs[BPF_REG_FP].frameno = state->frameno; 2273 } 2274 2275 static struct bpf_retval_range retval_range(s32 minval, s32 maxval) 2276 { 2277 /* 2278 * return_32bit is set to false by default and set explicitly 2279 * by the caller when necessary. 2280 */ 2281 return (struct bpf_retval_range){ minval, maxval, false }; 2282 } 2283 2284 static void init_func_state(struct bpf_verifier_env *env, 2285 struct bpf_func_state *state, 2286 int callsite, int frameno, int subprogno) 2287 { 2288 state->callsite = callsite; 2289 state->frameno = frameno; 2290 state->subprogno = subprogno; 2291 state->callback_ret_range = retval_range(0, 0); 2292 init_reg_state(env, state); 2293 mark_verifier_state_scratched(env); 2294 } 2295 2296 /* Similar to push_stack(), but for async callbacks */ 2297 static struct bpf_verifier_state *push_async_cb(struct bpf_verifier_env *env, 2298 int insn_idx, int prev_insn_idx, 2299 int subprog, bool is_sleepable) 2300 { 2301 struct bpf_verifier_stack_elem *elem; 2302 struct bpf_func_state *frame; 2303 2304 elem = kzalloc_obj(struct bpf_verifier_stack_elem, GFP_KERNEL_ACCOUNT); 2305 if (!elem) 2306 return ERR_PTR(-ENOMEM); 2307 2308 elem->insn_idx = insn_idx; 2309 elem->prev_insn_idx = prev_insn_idx; 2310 elem->next = env->head; 2311 elem->log_pos = env->log.end_pos; 2312 env->head = elem; 2313 env->stack_size++; 2314 if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) { 2315 verbose(env, 2316 "The sequence of %d jumps is too complex for async cb.\n", 2317 env->stack_size); 2318 return ERR_PTR(-E2BIG); 2319 } 2320 /* Unlike push_stack() do not bpf_copy_verifier_state(). 2321 * The caller state doesn't matter. 2322 * This is async callback. It starts in a fresh stack. 2323 * Initialize it similar to do_check_common(). 2324 */ 2325 elem->st.branches = 1; 2326 elem->st.in_sleepable = is_sleepable; 2327 frame = kzalloc_obj(*frame, GFP_KERNEL_ACCOUNT); 2328 if (!frame) 2329 return ERR_PTR(-ENOMEM); 2330 init_func_state(env, frame, 2331 BPF_MAIN_FUNC /* callsite */, 2332 0 /* frameno within this callchain */, 2333 subprog /* subprog number within this prog */); 2334 elem->st.frame[0] = frame; 2335 return &elem->st; 2336 } 2337 2338 2339 static int cmp_subprogs(const void *a, const void *b) 2340 { 2341 return ((struct bpf_subprog_info *)a)->start - 2342 ((struct bpf_subprog_info *)b)->start; 2343 } 2344 2345 /* Find subprogram that contains instruction at 'off' */ 2346 struct bpf_subprog_info *bpf_find_containing_subprog(struct bpf_verifier_env *env, int off) 2347 { 2348 struct bpf_subprog_info *vals = env->subprog_info; 2349 int l, r, m; 2350 2351 if (off >= env->prog->len || off < 0 || env->subprog_cnt == 0) 2352 return NULL; 2353 2354 l = 0; 2355 r = env->subprog_cnt - 1; 2356 while (l < r) { 2357 m = l + (r - l + 1) / 2; 2358 if (vals[m].start <= off) 2359 l = m; 2360 else 2361 r = m - 1; 2362 } 2363 return &vals[l]; 2364 } 2365 2366 /* Find subprogram that starts exactly at 'off' */ 2367 int bpf_find_subprog(struct bpf_verifier_env *env, int off) 2368 { 2369 struct bpf_subprog_info *p; 2370 2371 p = bpf_find_containing_subprog(env, off); 2372 if (!p || p->start != off) 2373 return -ENOENT; 2374 return p - env->subprog_info; 2375 } 2376 2377 static int add_subprog(struct bpf_verifier_env *env, int off) 2378 { 2379 int insn_cnt = env->prog->len; 2380 int ret; 2381 2382 if (off >= insn_cnt || off < 0) { 2383 verbose(env, "call to invalid destination\n"); 2384 return -EINVAL; 2385 } 2386 ret = bpf_find_subprog(env, off); 2387 if (ret >= 0) 2388 return ret; 2389 if (env->subprog_cnt >= BPF_MAX_SUBPROGS) { 2390 verbose(env, "too many subprograms\n"); 2391 return -E2BIG; 2392 } 2393 /* determine subprog starts. The end is one before the next starts */ 2394 env->subprog_info[env->subprog_cnt++].start = off; 2395 sort(env->subprog_info, env->subprog_cnt, 2396 sizeof(env->subprog_info[0]), cmp_subprogs, NULL); 2397 return env->subprog_cnt - 1; 2398 } 2399 2400 static int bpf_find_exception_callback_insn_off(struct bpf_verifier_env *env) 2401 { 2402 struct bpf_prog_aux *aux = env->prog->aux; 2403 struct btf *btf = aux->btf; 2404 const struct btf_type *t; 2405 u32 main_btf_id, id; 2406 const char *name; 2407 int ret, i; 2408 2409 /* Non-zero func_info_cnt implies valid btf */ 2410 if (!aux->func_info_cnt) 2411 return 0; 2412 main_btf_id = aux->func_info[0].type_id; 2413 2414 t = btf_type_by_id(btf, main_btf_id); 2415 if (!t) { 2416 verbose(env, "invalid btf id for main subprog in func_info\n"); 2417 return -EINVAL; 2418 } 2419 2420 name = btf_find_decl_tag_value(btf, t, -1, "exception_callback:"); 2421 if (IS_ERR(name)) { 2422 ret = PTR_ERR(name); 2423 /* If there is no tag present, there is no exception callback */ 2424 if (ret == -ENOENT) 2425 ret = 0; 2426 else if (ret == -EEXIST) 2427 verbose(env, "multiple exception callback tags for main subprog\n"); 2428 return ret; 2429 } 2430 2431 ret = btf_find_by_name_kind(btf, name, BTF_KIND_FUNC); 2432 if (ret < 0) { 2433 verbose(env, "exception callback '%s' could not be found in BTF\n", name); 2434 return ret; 2435 } 2436 id = ret; 2437 t = btf_type_by_id(btf, id); 2438 if (btf_func_linkage(t) != BTF_FUNC_GLOBAL) { 2439 verbose(env, "exception callback '%s' must have global linkage\n", name); 2440 return -EINVAL; 2441 } 2442 ret = 0; 2443 for (i = 0; i < aux->func_info_cnt; i++) { 2444 if (aux->func_info[i].type_id != id) 2445 continue; 2446 ret = aux->func_info[i].insn_off; 2447 /* Further func_info and subprog checks will also happen 2448 * later, so assume this is the right insn_off for now. 2449 */ 2450 if (!ret) { 2451 verbose(env, "invalid exception callback insn_off in func_info: 0\n"); 2452 ret = -EINVAL; 2453 } 2454 } 2455 if (!ret) { 2456 verbose(env, "exception callback type id not found in func_info\n"); 2457 ret = -EINVAL; 2458 } 2459 return ret; 2460 } 2461 2462 #define MAX_KFUNC_BTFS 256 2463 2464 struct bpf_kfunc_btf { 2465 struct btf *btf; 2466 struct module *module; 2467 u16 offset; 2468 }; 2469 2470 struct bpf_kfunc_btf_tab { 2471 struct bpf_kfunc_btf descs[MAX_KFUNC_BTFS]; 2472 u32 nr_descs; 2473 }; 2474 2475 static int kfunc_desc_cmp_by_id_off(const void *a, const void *b) 2476 { 2477 const struct bpf_kfunc_desc *d0 = a; 2478 const struct bpf_kfunc_desc *d1 = b; 2479 2480 /* func_id is not greater than BTF_MAX_TYPE */ 2481 return d0->func_id - d1->func_id ?: d0->offset - d1->offset; 2482 } 2483 2484 static int kfunc_btf_cmp_by_off(const void *a, const void *b) 2485 { 2486 const struct bpf_kfunc_btf *d0 = a; 2487 const struct bpf_kfunc_btf *d1 = b; 2488 2489 return d0->offset - d1->offset; 2490 } 2491 2492 static struct bpf_kfunc_desc * 2493 find_kfunc_desc(const struct bpf_prog *prog, u32 func_id, u16 offset) 2494 { 2495 struct bpf_kfunc_desc desc = { 2496 .func_id = func_id, 2497 .offset = offset, 2498 }; 2499 struct bpf_kfunc_desc_tab *tab; 2500 2501 tab = prog->aux->kfunc_tab; 2502 return bsearch(&desc, tab->descs, tab->nr_descs, 2503 sizeof(tab->descs[0]), kfunc_desc_cmp_by_id_off); 2504 } 2505 2506 int bpf_get_kfunc_addr(const struct bpf_prog *prog, u32 func_id, 2507 u16 btf_fd_idx, u8 **func_addr) 2508 { 2509 const struct bpf_kfunc_desc *desc; 2510 2511 desc = find_kfunc_desc(prog, func_id, btf_fd_idx); 2512 if (!desc) 2513 return -EFAULT; 2514 2515 *func_addr = (u8 *)desc->addr; 2516 return 0; 2517 } 2518 2519 static struct btf *__find_kfunc_desc_btf(struct bpf_verifier_env *env, 2520 s16 offset) 2521 { 2522 struct bpf_kfunc_btf kf_btf = { .offset = offset }; 2523 struct bpf_kfunc_btf_tab *tab; 2524 struct bpf_kfunc_btf *b; 2525 struct module *mod; 2526 struct btf *btf; 2527 int btf_fd; 2528 2529 tab = env->prog->aux->kfunc_btf_tab; 2530 b = bsearch(&kf_btf, tab->descs, tab->nr_descs, 2531 sizeof(tab->descs[0]), kfunc_btf_cmp_by_off); 2532 if (!b) { 2533 if (tab->nr_descs == MAX_KFUNC_BTFS) { 2534 verbose(env, "too many different module BTFs\n"); 2535 return ERR_PTR(-E2BIG); 2536 } 2537 2538 if (bpfptr_is_null(env->fd_array)) { 2539 verbose(env, "kfunc offset > 0 without fd_array is invalid\n"); 2540 return ERR_PTR(-EPROTO); 2541 } 2542 2543 if (copy_from_bpfptr_offset(&btf_fd, env->fd_array, 2544 offset * sizeof(btf_fd), 2545 sizeof(btf_fd))) 2546 return ERR_PTR(-EFAULT); 2547 2548 btf = btf_get_by_fd(btf_fd); 2549 if (IS_ERR(btf)) { 2550 verbose(env, "invalid module BTF fd specified\n"); 2551 return btf; 2552 } 2553 2554 if (!btf_is_module(btf)) { 2555 verbose(env, "BTF fd for kfunc is not a module BTF\n"); 2556 btf_put(btf); 2557 return ERR_PTR(-EINVAL); 2558 } 2559 2560 mod = btf_try_get_module(btf); 2561 if (!mod) { 2562 btf_put(btf); 2563 return ERR_PTR(-ENXIO); 2564 } 2565 2566 b = &tab->descs[tab->nr_descs++]; 2567 b->btf = btf; 2568 b->module = mod; 2569 b->offset = offset; 2570 2571 /* sort() reorders entries by value, so b may no longer point 2572 * to the right entry after this 2573 */ 2574 sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]), 2575 kfunc_btf_cmp_by_off, NULL); 2576 } else { 2577 btf = b->btf; 2578 } 2579 2580 return btf; 2581 } 2582 2583 void bpf_free_kfunc_btf_tab(struct bpf_kfunc_btf_tab *tab) 2584 { 2585 if (!tab) 2586 return; 2587 2588 while (tab->nr_descs--) { 2589 module_put(tab->descs[tab->nr_descs].module); 2590 btf_put(tab->descs[tab->nr_descs].btf); 2591 } 2592 kfree(tab); 2593 } 2594 2595 static struct btf *find_kfunc_desc_btf(struct bpf_verifier_env *env, s16 offset) 2596 { 2597 if (offset) { 2598 if (offset < 0) { 2599 /* In the future, this can be allowed to increase limit 2600 * of fd index into fd_array, interpreted as u16. 2601 */ 2602 verbose(env, "negative offset disallowed for kernel module function call\n"); 2603 return ERR_PTR(-EINVAL); 2604 } 2605 2606 return __find_kfunc_desc_btf(env, offset); 2607 } 2608 return btf_vmlinux ?: ERR_PTR(-ENOENT); 2609 } 2610 2611 #define KF_IMPL_SUFFIX "_impl" 2612 2613 static const struct btf_type *find_kfunc_impl_proto(struct bpf_verifier_env *env, 2614 struct btf *btf, 2615 const char *func_name) 2616 { 2617 char *buf = env->tmp_str_buf; 2618 const struct btf_type *func; 2619 s32 impl_id; 2620 int len; 2621 2622 len = snprintf(buf, TMP_STR_BUF_LEN, "%s%s", func_name, KF_IMPL_SUFFIX); 2623 if (len < 0 || len >= TMP_STR_BUF_LEN) { 2624 verbose(env, "function name %s%s is too long\n", func_name, KF_IMPL_SUFFIX); 2625 return NULL; 2626 } 2627 2628 impl_id = btf_find_by_name_kind(btf, buf, BTF_KIND_FUNC); 2629 if (impl_id <= 0) { 2630 verbose(env, "cannot find function %s in BTF\n", buf); 2631 return NULL; 2632 } 2633 2634 func = btf_type_by_id(btf, impl_id); 2635 2636 return btf_type_by_id(btf, func->type); 2637 } 2638 2639 static int fetch_kfunc_meta(struct bpf_verifier_env *env, 2640 s32 func_id, 2641 s16 offset, 2642 struct bpf_kfunc_meta *kfunc) 2643 { 2644 const struct btf_type *func, *func_proto; 2645 const char *func_name; 2646 u32 *kfunc_flags; 2647 struct btf *btf; 2648 2649 if (func_id <= 0) { 2650 verbose(env, "invalid kernel function btf_id %d\n", func_id); 2651 return -EINVAL; 2652 } 2653 2654 btf = find_kfunc_desc_btf(env, offset); 2655 if (IS_ERR(btf)) { 2656 verbose(env, "failed to find BTF for kernel function\n"); 2657 return PTR_ERR(btf); 2658 } 2659 2660 /* 2661 * Note that kfunc_flags may be NULL at this point, which 2662 * means that we couldn't find func_id in any relevant 2663 * kfunc_id_set. This most likely indicates an invalid kfunc 2664 * call. However we don't fail with an error here, 2665 * and let the caller decide what to do with NULL kfunc->flags. 2666 */ 2667 kfunc_flags = btf_kfunc_flags(btf, func_id, env->prog); 2668 2669 func = btf_type_by_id(btf, func_id); 2670 if (!func || !btf_type_is_func(func)) { 2671 verbose(env, "kernel btf_id %d is not a function\n", func_id); 2672 return -EINVAL; 2673 } 2674 2675 func_name = btf_name_by_offset(btf, func->name_off); 2676 2677 /* 2678 * An actual prototype of a kfunc with KF_IMPLICIT_ARGS flag 2679 * can be found through the counterpart _impl kfunc. 2680 */ 2681 if (kfunc_flags && (*kfunc_flags & KF_IMPLICIT_ARGS)) 2682 func_proto = find_kfunc_impl_proto(env, btf, func_name); 2683 else 2684 func_proto = btf_type_by_id(btf, func->type); 2685 2686 if (!func_proto || !btf_type_is_func_proto(func_proto)) { 2687 verbose(env, "kernel function btf_id %d does not have a valid func_proto\n", 2688 func_id); 2689 return -EINVAL; 2690 } 2691 2692 memset(kfunc, 0, sizeof(*kfunc)); 2693 kfunc->btf = btf; 2694 kfunc->id = func_id; 2695 kfunc->name = func_name; 2696 kfunc->proto = func_proto; 2697 kfunc->flags = kfunc_flags; 2698 2699 return 0; 2700 } 2701 2702 int bpf_add_kfunc_call(struct bpf_verifier_env *env, u32 func_id, u16 offset) 2703 { 2704 struct bpf_kfunc_btf_tab *btf_tab; 2705 struct btf_func_model func_model; 2706 struct bpf_kfunc_desc_tab *tab; 2707 struct bpf_prog_aux *prog_aux; 2708 struct bpf_kfunc_meta kfunc; 2709 struct bpf_kfunc_desc *desc; 2710 unsigned long addr; 2711 int err; 2712 2713 prog_aux = env->prog->aux; 2714 tab = prog_aux->kfunc_tab; 2715 btf_tab = prog_aux->kfunc_btf_tab; 2716 if (!tab) { 2717 if (!btf_vmlinux) { 2718 verbose(env, "calling kernel function is not supported without CONFIG_DEBUG_INFO_BTF\n"); 2719 return -ENOTSUPP; 2720 } 2721 2722 if (!env->prog->jit_requested) { 2723 verbose(env, "JIT is required for calling kernel function\n"); 2724 return -ENOTSUPP; 2725 } 2726 2727 if (!bpf_jit_supports_kfunc_call()) { 2728 verbose(env, "JIT does not support calling kernel function\n"); 2729 return -ENOTSUPP; 2730 } 2731 2732 if (!env->prog->gpl_compatible) { 2733 verbose(env, "cannot call kernel function from non-GPL compatible program\n"); 2734 return -EINVAL; 2735 } 2736 2737 tab = kzalloc_obj(*tab, GFP_KERNEL_ACCOUNT); 2738 if (!tab) 2739 return -ENOMEM; 2740 prog_aux->kfunc_tab = tab; 2741 } 2742 2743 /* func_id == 0 is always invalid, but instead of returning an error, be 2744 * conservative and wait until the code elimination pass before returning 2745 * error, so that invalid calls that get pruned out can be in BPF programs 2746 * loaded from userspace. It is also required that offset be untouched 2747 * for such calls. 2748 */ 2749 if (!func_id && !offset) 2750 return 0; 2751 2752 if (!btf_tab && offset) { 2753 btf_tab = kzalloc_obj(*btf_tab, GFP_KERNEL_ACCOUNT); 2754 if (!btf_tab) 2755 return -ENOMEM; 2756 prog_aux->kfunc_btf_tab = btf_tab; 2757 } 2758 2759 if (find_kfunc_desc(env->prog, func_id, offset)) 2760 return 0; 2761 2762 if (tab->nr_descs == MAX_KFUNC_DESCS) { 2763 verbose(env, "too many different kernel function calls\n"); 2764 return -E2BIG; 2765 } 2766 2767 err = fetch_kfunc_meta(env, func_id, offset, &kfunc); 2768 if (err) 2769 return err; 2770 2771 addr = kallsyms_lookup_name(kfunc.name); 2772 if (!addr) { 2773 verbose(env, "cannot find address for kernel function %s\n", kfunc.name); 2774 return -EINVAL; 2775 } 2776 2777 if (bpf_dev_bound_kfunc_id(func_id)) { 2778 err = bpf_dev_bound_kfunc_check(&env->log, prog_aux); 2779 if (err) 2780 return err; 2781 } 2782 2783 err = btf_distill_func_proto(&env->log, kfunc.btf, kfunc.proto, kfunc.name, &func_model); 2784 if (err) 2785 return err; 2786 2787 desc = &tab->descs[tab->nr_descs++]; 2788 desc->func_id = func_id; 2789 desc->offset = offset; 2790 desc->addr = addr; 2791 desc->func_model = func_model; 2792 sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]), 2793 kfunc_desc_cmp_by_id_off, NULL); 2794 return 0; 2795 } 2796 2797 bool bpf_prog_has_kfunc_call(const struct bpf_prog *prog) 2798 { 2799 return !!prog->aux->kfunc_tab; 2800 } 2801 2802 static int add_subprog_and_kfunc(struct bpf_verifier_env *env) 2803 { 2804 struct bpf_subprog_info *subprog = env->subprog_info; 2805 int i, ret, insn_cnt = env->prog->len, ex_cb_insn; 2806 struct bpf_insn *insn = env->prog->insnsi; 2807 2808 /* Add entry function. */ 2809 ret = add_subprog(env, 0); 2810 if (ret) 2811 return ret; 2812 2813 for (i = 0; i < insn_cnt; i++, insn++) { 2814 if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn) && 2815 !bpf_pseudo_kfunc_call(insn)) 2816 continue; 2817 2818 if (!env->bpf_capable) { 2819 verbose(env, "loading/calling other bpf or kernel functions are allowed for CAP_BPF and CAP_SYS_ADMIN\n"); 2820 return -EPERM; 2821 } 2822 2823 if (bpf_pseudo_func(insn) || bpf_pseudo_call(insn)) 2824 ret = add_subprog(env, i + insn->imm + 1); 2825 else 2826 ret = bpf_add_kfunc_call(env, insn->imm, insn->off); 2827 2828 if (ret < 0) 2829 return ret; 2830 } 2831 2832 ret = bpf_find_exception_callback_insn_off(env); 2833 if (ret < 0) 2834 return ret; 2835 ex_cb_insn = ret; 2836 2837 /* If ex_cb_insn > 0, this means that the main program has a subprog 2838 * marked using BTF decl tag to serve as the exception callback. 2839 */ 2840 if (ex_cb_insn) { 2841 ret = add_subprog(env, ex_cb_insn); 2842 if (ret < 0) 2843 return ret; 2844 for (i = 1; i < env->subprog_cnt; i++) { 2845 if (env->subprog_info[i].start != ex_cb_insn) 2846 continue; 2847 env->exception_callback_subprog = i; 2848 bpf_mark_subprog_exc_cb(env, i); 2849 break; 2850 } 2851 } 2852 2853 /* Add a fake 'exit' subprog which could simplify subprog iteration 2854 * logic. 'subprog_cnt' should not be increased. 2855 */ 2856 subprog[env->subprog_cnt].start = insn_cnt; 2857 2858 if (env->log.level & BPF_LOG_LEVEL2) 2859 for (i = 0; i < env->subprog_cnt; i++) 2860 verbose(env, "func#%d @%d\n", i, subprog[i].start); 2861 2862 return 0; 2863 } 2864 2865 static int check_subprogs(struct bpf_verifier_env *env) 2866 { 2867 int i, subprog_start, subprog_end, off, cur_subprog = 0; 2868 struct bpf_subprog_info *subprog = env->subprog_info; 2869 struct bpf_insn *insn = env->prog->insnsi; 2870 int insn_cnt = env->prog->len; 2871 2872 /* now check that all jumps are within the same subprog */ 2873 subprog_start = subprog[cur_subprog].start; 2874 subprog_end = subprog[cur_subprog + 1].start; 2875 for (i = 0; i < insn_cnt; i++) { 2876 u8 code = insn[i].code; 2877 2878 if (code == (BPF_JMP | BPF_CALL) && 2879 insn[i].src_reg == 0 && 2880 insn[i].imm == BPF_FUNC_tail_call) { 2881 subprog[cur_subprog].has_tail_call = true; 2882 subprog[cur_subprog].tail_call_reachable = true; 2883 } 2884 if (BPF_CLASS(code) == BPF_LD && 2885 (BPF_MODE(code) == BPF_ABS || BPF_MODE(code) == BPF_IND)) 2886 subprog[cur_subprog].has_ld_abs = true; 2887 if (BPF_CLASS(code) != BPF_JMP && BPF_CLASS(code) != BPF_JMP32) 2888 goto next; 2889 if (BPF_OP(code) == BPF_CALL) 2890 goto next; 2891 if (BPF_OP(code) == BPF_EXIT) { 2892 subprog[cur_subprog].exit_idx = i; 2893 goto next; 2894 } 2895 off = i + bpf_jmp_offset(&insn[i]) + 1; 2896 if (off < subprog_start || off >= subprog_end) { 2897 verbose(env, "jump out of range from insn %d to %d\n", i, off); 2898 return -EINVAL; 2899 } 2900 next: 2901 if (i == subprog_end - 1) { 2902 /* to avoid fall-through from one subprog into another 2903 * the last insn of the subprog should be either exit 2904 * or unconditional jump back or bpf_throw call 2905 */ 2906 if (code != (BPF_JMP | BPF_EXIT) && 2907 code != (BPF_JMP32 | BPF_JA) && 2908 code != (BPF_JMP | BPF_JA)) { 2909 verbose(env, "last insn is not an exit or jmp\n"); 2910 return -EINVAL; 2911 } 2912 subprog_start = subprog_end; 2913 cur_subprog++; 2914 if (cur_subprog < env->subprog_cnt) 2915 subprog_end = subprog[cur_subprog + 1].start; 2916 } 2917 } 2918 return 0; 2919 } 2920 2921 /* 2922 * Sort subprogs in topological order so that leaf subprogs come first and 2923 * their callers come later. This is a DFS post-order traversal of the call 2924 * graph. Scan only reachable instructions (those in the computed postorder) of 2925 * the current subprog to discover callees (direct subprogs and sync 2926 * callbacks). 2927 */ 2928 static int sort_subprogs_topo(struct bpf_verifier_env *env) 2929 { 2930 struct bpf_subprog_info *si = env->subprog_info; 2931 int *insn_postorder = env->cfg.insn_postorder; 2932 struct bpf_insn *insn = env->prog->insnsi; 2933 int cnt = env->subprog_cnt; 2934 int *dfs_stack = NULL; 2935 int top = 0, order = 0; 2936 int i, ret = 0; 2937 u8 *color = NULL; 2938 2939 color = kvzalloc_objs(*color, cnt, GFP_KERNEL_ACCOUNT); 2940 dfs_stack = kvmalloc_objs(*dfs_stack, cnt, GFP_KERNEL_ACCOUNT); 2941 if (!color || !dfs_stack) { 2942 ret = -ENOMEM; 2943 goto out; 2944 } 2945 2946 /* 2947 * DFS post-order traversal. 2948 * Color values: 0 = unvisited, 1 = on stack, 2 = done. 2949 */ 2950 for (i = 0; i < cnt; i++) { 2951 if (color[i]) 2952 continue; 2953 color[i] = 1; 2954 dfs_stack[top++] = i; 2955 2956 while (top > 0) { 2957 int cur = dfs_stack[top - 1]; 2958 int po_start = si[cur].postorder_start; 2959 int po_end = si[cur + 1].postorder_start; 2960 bool pushed = false; 2961 int j; 2962 2963 for (j = po_start; j < po_end; j++) { 2964 int idx = insn_postorder[j]; 2965 int callee; 2966 2967 if (!bpf_pseudo_call(&insn[idx]) && !bpf_pseudo_func(&insn[idx])) 2968 continue; 2969 callee = bpf_find_subprog(env, idx + insn[idx].imm + 1); 2970 if (callee < 0) { 2971 ret = -EFAULT; 2972 goto out; 2973 } 2974 if (color[callee] == 2) 2975 continue; 2976 if (color[callee] == 1) { 2977 if (bpf_pseudo_func(&insn[idx])) 2978 continue; 2979 verbose(env, "recursive call from %s() to %s()\n", 2980 subprog_name(env, cur), 2981 subprog_name(env, callee)); 2982 ret = -EINVAL; 2983 goto out; 2984 } 2985 color[callee] = 1; 2986 dfs_stack[top++] = callee; 2987 pushed = true; 2988 break; 2989 } 2990 2991 if (!pushed) { 2992 color[cur] = 2; 2993 env->subprog_topo_order[order++] = cur; 2994 top--; 2995 } 2996 } 2997 } 2998 2999 if (env->log.level & BPF_LOG_LEVEL2) 3000 for (i = 0; i < cnt; i++) 3001 verbose(env, "topo_order[%d] = %s\n", 3002 i, subprog_name(env, env->subprog_topo_order[i])); 3003 out: 3004 kvfree(dfs_stack); 3005 kvfree(color); 3006 return ret; 3007 } 3008 3009 static int mark_stack_slot_obj_read(struct bpf_verifier_env *env, struct bpf_reg_state *reg, 3010 int spi, int nr_slots) 3011 { 3012 int i; 3013 3014 for (i = 0; i < nr_slots; i++) 3015 mark_stack_slot_scratched(env, spi - i); 3016 return 0; 3017 } 3018 3019 static int mark_dynptr_read(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 3020 { 3021 int spi; 3022 3023 /* For CONST_PTR_TO_DYNPTR, it must have already been done by 3024 * check_reg_arg in check_helper_call and mark_btf_func_reg_size in 3025 * check_kfunc_call. 3026 */ 3027 if (reg->type == CONST_PTR_TO_DYNPTR) 3028 return 0; 3029 spi = dynptr_get_spi(env, reg); 3030 if (spi < 0) 3031 return spi; 3032 /* Caller ensures dynptr is valid and initialized, which means spi is in 3033 * bounds and spi is the first dynptr slot. Simply mark stack slot as 3034 * read. 3035 */ 3036 return mark_stack_slot_obj_read(env, reg, spi, BPF_DYNPTR_NR_SLOTS); 3037 } 3038 3039 static int mark_iter_read(struct bpf_verifier_env *env, struct bpf_reg_state *reg, 3040 int spi, int nr_slots) 3041 { 3042 return mark_stack_slot_obj_read(env, reg, spi, nr_slots); 3043 } 3044 3045 static int mark_irq_flag_read(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 3046 { 3047 int spi; 3048 3049 spi = irq_flag_get_spi(env, reg); 3050 if (spi < 0) 3051 return spi; 3052 return mark_stack_slot_obj_read(env, reg, spi, 1); 3053 } 3054 3055 /* This function is supposed to be used by the following 32-bit optimization 3056 * code only. It returns TRUE if the source or destination register operates 3057 * on 64-bit, otherwise return FALSE. 3058 */ 3059 bool bpf_is_reg64(struct bpf_insn *insn, 3060 u32 regno, struct bpf_reg_state *reg, enum bpf_reg_arg_type t) 3061 { 3062 u8 code, class, op; 3063 3064 code = insn->code; 3065 class = BPF_CLASS(code); 3066 op = BPF_OP(code); 3067 if (class == BPF_JMP) { 3068 /* BPF_EXIT for "main" will reach here. Return TRUE 3069 * conservatively. 3070 */ 3071 if (op == BPF_EXIT) 3072 return true; 3073 if (op == BPF_CALL) { 3074 /* BPF to BPF call will reach here because of marking 3075 * caller saved clobber with DST_OP_NO_MARK for which we 3076 * don't care the register def because they are anyway 3077 * marked as NOT_INIT already. 3078 */ 3079 if (insn->src_reg == BPF_PSEUDO_CALL) 3080 return false; 3081 /* Helper call will reach here because of arg type 3082 * check, conservatively return TRUE. 3083 */ 3084 if (t == SRC_OP) 3085 return true; 3086 3087 return false; 3088 } 3089 } 3090 3091 if (class == BPF_ALU64 && op == BPF_END && (insn->imm == 16 || insn->imm == 32)) 3092 return false; 3093 3094 if (class == BPF_ALU64 || class == BPF_JMP || 3095 (class == BPF_ALU && op == BPF_END && insn->imm == 64)) 3096 return true; 3097 3098 if (class == BPF_ALU || class == BPF_JMP32) 3099 return false; 3100 3101 if (class == BPF_LDX) { 3102 if (t != SRC_OP) 3103 return BPF_SIZE(code) == BPF_DW || BPF_MODE(code) == BPF_MEMSX; 3104 /* LDX source must be ptr. */ 3105 return true; 3106 } 3107 3108 if (class == BPF_STX) { 3109 /* BPF_STX (including atomic variants) has one or more source 3110 * operands, one of which is a ptr. Check whether the caller is 3111 * asking about it. 3112 */ 3113 if (t == SRC_OP && reg->type != SCALAR_VALUE) 3114 return true; 3115 return BPF_SIZE(code) == BPF_DW; 3116 } 3117 3118 if (class == BPF_LD) { 3119 u8 mode = BPF_MODE(code); 3120 3121 /* LD_IMM64 */ 3122 if (mode == BPF_IMM) 3123 return true; 3124 3125 /* Both LD_IND and LD_ABS return 32-bit data. */ 3126 if (t != SRC_OP) 3127 return false; 3128 3129 /* Implicit ctx ptr. */ 3130 if (regno == BPF_REG_6) 3131 return true; 3132 3133 /* Explicit source could be any width. */ 3134 return true; 3135 } 3136 3137 if (class == BPF_ST) 3138 /* The only source register for BPF_ST is a ptr. */ 3139 return true; 3140 3141 /* Conservatively return true at default. */ 3142 return true; 3143 } 3144 3145 static void mark_insn_zext(struct bpf_verifier_env *env, 3146 struct bpf_reg_state *reg) 3147 { 3148 s32 def_idx = reg->subreg_def; 3149 3150 if (def_idx == DEF_NOT_SUBREG) 3151 return; 3152 3153 env->insn_aux_data[def_idx - 1].zext_dst = true; 3154 /* The dst will be zero extended, so won't be sub-register anymore. */ 3155 reg->subreg_def = DEF_NOT_SUBREG; 3156 } 3157 3158 static int __check_reg_arg(struct bpf_verifier_env *env, struct bpf_reg_state *regs, u32 regno, 3159 enum bpf_reg_arg_type t) 3160 { 3161 struct bpf_insn *insn = env->prog->insnsi + env->insn_idx; 3162 struct bpf_reg_state *reg; 3163 bool rw64; 3164 3165 mark_reg_scratched(env, regno); 3166 3167 reg = ®s[regno]; 3168 rw64 = bpf_is_reg64(insn, regno, reg, t); 3169 if (t == SRC_OP) { 3170 /* check whether register used as source operand can be read */ 3171 if (reg->type == NOT_INIT) { 3172 verbose(env, "R%d !read_ok\n", regno); 3173 return -EACCES; 3174 } 3175 /* We don't need to worry about FP liveness because it's read-only */ 3176 if (regno == BPF_REG_FP) 3177 return 0; 3178 3179 if (rw64) 3180 mark_insn_zext(env, reg); 3181 3182 return 0; 3183 } else { 3184 /* check whether register used as dest operand can be written to */ 3185 if (regno == BPF_REG_FP) { 3186 verbose(env, "frame pointer is read only\n"); 3187 return -EACCES; 3188 } 3189 reg->subreg_def = rw64 ? DEF_NOT_SUBREG : env->insn_idx + 1; 3190 if (t == DST_OP) 3191 mark_reg_unknown(env, regs, regno); 3192 } 3193 return 0; 3194 } 3195 3196 static int check_reg_arg(struct bpf_verifier_env *env, u32 regno, 3197 enum bpf_reg_arg_type t) 3198 { 3199 struct bpf_verifier_state *vstate = env->cur_state; 3200 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 3201 3202 return __check_reg_arg(env, state->regs, regno, t); 3203 } 3204 3205 static void mark_indirect_target(struct bpf_verifier_env *env, int idx) 3206 { 3207 env->insn_aux_data[idx].indirect_target = true; 3208 } 3209 3210 #define LR_FRAMENO_BITS 3 3211 #define LR_SPI_BITS 6 3212 #define LR_ENTRY_BITS (LR_SPI_BITS + LR_FRAMENO_BITS + 1) 3213 #define LR_SIZE_BITS 4 3214 #define LR_FRAMENO_MASK ((1ull << LR_FRAMENO_BITS) - 1) 3215 #define LR_SPI_MASK ((1ull << LR_SPI_BITS) - 1) 3216 #define LR_SIZE_MASK ((1ull << LR_SIZE_BITS) - 1) 3217 #define LR_SPI_OFF LR_FRAMENO_BITS 3218 #define LR_IS_REG_OFF (LR_SPI_BITS + LR_FRAMENO_BITS) 3219 #define LINKED_REGS_MAX 6 3220 3221 struct linked_reg { 3222 u8 frameno; 3223 union { 3224 u8 spi; 3225 u8 regno; 3226 }; 3227 bool is_reg; 3228 }; 3229 3230 struct linked_regs { 3231 int cnt; 3232 struct linked_reg entries[LINKED_REGS_MAX]; 3233 }; 3234 3235 static struct linked_reg *linked_regs_push(struct linked_regs *s) 3236 { 3237 if (s->cnt < LINKED_REGS_MAX) 3238 return &s->entries[s->cnt++]; 3239 3240 return NULL; 3241 } 3242 3243 /* Use u64 as a vector of 6 10-bit values, use first 4-bits to track 3244 * number of elements currently in stack. 3245 * Pack one history entry for linked registers as 10 bits in the following format: 3246 * - 3-bits frameno 3247 * - 6-bits spi_or_reg 3248 * - 1-bit is_reg 3249 */ 3250 static u64 linked_regs_pack(struct linked_regs *s) 3251 { 3252 u64 val = 0; 3253 int i; 3254 3255 for (i = 0; i < s->cnt; ++i) { 3256 struct linked_reg *e = &s->entries[i]; 3257 u64 tmp = 0; 3258 3259 tmp |= e->frameno; 3260 tmp |= e->spi << LR_SPI_OFF; 3261 tmp |= (e->is_reg ? 1 : 0) << LR_IS_REG_OFF; 3262 3263 val <<= LR_ENTRY_BITS; 3264 val |= tmp; 3265 } 3266 val <<= LR_SIZE_BITS; 3267 val |= s->cnt; 3268 return val; 3269 } 3270 3271 static void linked_regs_unpack(u64 val, struct linked_regs *s) 3272 { 3273 int i; 3274 3275 s->cnt = val & LR_SIZE_MASK; 3276 val >>= LR_SIZE_BITS; 3277 3278 for (i = 0; i < s->cnt; ++i) { 3279 struct linked_reg *e = &s->entries[i]; 3280 3281 e->frameno = val & LR_FRAMENO_MASK; 3282 e->spi = (val >> LR_SPI_OFF) & LR_SPI_MASK; 3283 e->is_reg = (val >> LR_IS_REG_OFF) & 0x1; 3284 val >>= LR_ENTRY_BITS; 3285 } 3286 } 3287 3288 static const char *disasm_kfunc_name(void *data, const struct bpf_insn *insn) 3289 { 3290 const struct btf_type *func; 3291 struct btf *desc_btf; 3292 3293 if (insn->src_reg != BPF_PSEUDO_KFUNC_CALL) 3294 return NULL; 3295 3296 desc_btf = find_kfunc_desc_btf(data, insn->off); 3297 if (IS_ERR(desc_btf)) 3298 return "<error>"; 3299 3300 func = btf_type_by_id(desc_btf, insn->imm); 3301 return btf_name_by_offset(desc_btf, func->name_off); 3302 } 3303 3304 void bpf_verbose_insn(struct bpf_verifier_env *env, struct bpf_insn *insn) 3305 { 3306 const struct bpf_insn_cbs cbs = { 3307 .cb_call = disasm_kfunc_name, 3308 .cb_print = verbose, 3309 .private_data = env, 3310 }; 3311 3312 print_bpf_insn(&cbs, insn, env->allow_ptr_leaks); 3313 } 3314 3315 /* If any register R in hist->linked_regs is marked as precise in bt, 3316 * do bt_set_frame_{reg,slot}(bt, R) for all registers in hist->linked_regs. 3317 */ 3318 void bpf_bt_sync_linked_regs(struct backtrack_state *bt, struct bpf_jmp_history_entry *hist) 3319 { 3320 struct linked_regs linked_regs; 3321 bool some_precise = false; 3322 int i; 3323 3324 if (!hist || hist->linked_regs == 0) 3325 return; 3326 3327 linked_regs_unpack(hist->linked_regs, &linked_regs); 3328 for (i = 0; i < linked_regs.cnt; ++i) { 3329 struct linked_reg *e = &linked_regs.entries[i]; 3330 3331 if ((e->is_reg && bt_is_frame_reg_set(bt, e->frameno, e->regno)) || 3332 (!e->is_reg && bt_is_frame_slot_set(bt, e->frameno, e->spi))) { 3333 some_precise = true; 3334 break; 3335 } 3336 } 3337 3338 if (!some_precise) 3339 return; 3340 3341 for (i = 0; i < linked_regs.cnt; ++i) { 3342 struct linked_reg *e = &linked_regs.entries[i]; 3343 3344 if (e->is_reg) 3345 bpf_bt_set_frame_reg(bt, e->frameno, e->regno); 3346 else 3347 bpf_bt_set_frame_slot(bt, e->frameno, e->spi); 3348 } 3349 } 3350 3351 int mark_chain_precision(struct bpf_verifier_env *env, int regno) 3352 { 3353 return bpf_mark_chain_precision(env, env->cur_state, regno, NULL); 3354 } 3355 3356 /* mark_chain_precision_batch() assumes that env->bt is set in the caller to 3357 * desired reg and stack masks across all relevant frames 3358 */ 3359 static int mark_chain_precision_batch(struct bpf_verifier_env *env, 3360 struct bpf_verifier_state *starting_state) 3361 { 3362 return bpf_mark_chain_precision(env, starting_state, -1, NULL); 3363 } 3364 3365 static bool is_spillable_regtype(enum bpf_reg_type type) 3366 { 3367 switch (base_type(type)) { 3368 case PTR_TO_MAP_VALUE: 3369 case PTR_TO_STACK: 3370 case PTR_TO_CTX: 3371 case PTR_TO_PACKET: 3372 case PTR_TO_PACKET_META: 3373 case PTR_TO_PACKET_END: 3374 case PTR_TO_FLOW_KEYS: 3375 case CONST_PTR_TO_MAP: 3376 case PTR_TO_SOCKET: 3377 case PTR_TO_SOCK_COMMON: 3378 case PTR_TO_TCP_SOCK: 3379 case PTR_TO_XDP_SOCK: 3380 case PTR_TO_BTF_ID: 3381 case PTR_TO_BUF: 3382 case PTR_TO_MEM: 3383 case PTR_TO_FUNC: 3384 case PTR_TO_MAP_KEY: 3385 case PTR_TO_ARENA: 3386 return true; 3387 default: 3388 return false; 3389 } 3390 } 3391 3392 3393 /* check if register is a constant scalar value */ 3394 static bool is_reg_const(struct bpf_reg_state *reg, bool subreg32) 3395 { 3396 return reg->type == SCALAR_VALUE && 3397 tnum_is_const(subreg32 ? tnum_subreg(reg->var_off) : reg->var_off); 3398 } 3399 3400 /* assuming is_reg_const() is true, return constant value of a register */ 3401 static u64 reg_const_value(struct bpf_reg_state *reg, bool subreg32) 3402 { 3403 return subreg32 ? tnum_subreg(reg->var_off).value : reg->var_off.value; 3404 } 3405 3406 static bool __is_pointer_value(bool allow_ptr_leaks, 3407 const struct bpf_reg_state *reg) 3408 { 3409 if (allow_ptr_leaks) 3410 return false; 3411 3412 return reg->type != SCALAR_VALUE; 3413 } 3414 3415 static void clear_scalar_id(struct bpf_reg_state *reg) 3416 { 3417 reg->id = 0; 3418 reg->delta = 0; 3419 } 3420 3421 static void assign_scalar_id_before_mov(struct bpf_verifier_env *env, 3422 struct bpf_reg_state *src_reg) 3423 { 3424 if (src_reg->type != SCALAR_VALUE) 3425 return; 3426 /* 3427 * The verifier is processing rX = rY insn and 3428 * rY->id has special linked register already. 3429 * Cleared it, since multiple rX += const are not supported. 3430 */ 3431 if (src_reg->id & BPF_ADD_CONST) 3432 clear_scalar_id(src_reg); 3433 /* 3434 * Ensure that src_reg has a valid ID that will be copied to 3435 * dst_reg and then will be used by sync_linked_regs() to 3436 * propagate min/max range. 3437 */ 3438 if (!src_reg->id && !tnum_is_const(src_reg->var_off)) 3439 src_reg->id = ++env->id_gen; 3440 } 3441 3442 static void save_register_state(struct bpf_verifier_env *env, 3443 struct bpf_func_state *state, 3444 int spi, struct bpf_reg_state *reg, 3445 int size) 3446 { 3447 int i; 3448 3449 state->stack[spi].spilled_ptr = *reg; 3450 3451 for (i = BPF_REG_SIZE; i > BPF_REG_SIZE - size; i--) 3452 state->stack[spi].slot_type[i - 1] = STACK_SPILL; 3453 3454 /* size < 8 bytes spill */ 3455 for (; i; i--) 3456 mark_stack_slot_misc(env, &state->stack[spi].slot_type[i - 1]); 3457 } 3458 3459 static bool is_bpf_st_mem(struct bpf_insn *insn) 3460 { 3461 return BPF_CLASS(insn->code) == BPF_ST && BPF_MODE(insn->code) == BPF_MEM; 3462 } 3463 3464 static int get_reg_width(struct bpf_reg_state *reg) 3465 { 3466 return fls64(reg_umax(reg)); 3467 } 3468 3469 /* See comment for mark_fastcall_pattern_for_call() */ 3470 static void check_fastcall_stack_contract(struct bpf_verifier_env *env, 3471 struct bpf_func_state *state, int insn_idx, int off) 3472 { 3473 struct bpf_subprog_info *subprog = &env->subprog_info[state->subprogno]; 3474 struct bpf_insn_aux_data *aux = env->insn_aux_data; 3475 int i; 3476 3477 if (subprog->fastcall_stack_off <= off || aux[insn_idx].fastcall_pattern) 3478 return; 3479 /* access to the region [max_stack_depth .. fastcall_stack_off) 3480 * from something that is not a part of the fastcall pattern, 3481 * disable fastcall rewrites for current subprogram by setting 3482 * fastcall_stack_off to a value smaller than any possible offset. 3483 */ 3484 subprog->fastcall_stack_off = S16_MIN; 3485 /* reset fastcall aux flags within subprogram, 3486 * happens at most once per subprogram 3487 */ 3488 for (i = subprog->start; i < (subprog + 1)->start; ++i) { 3489 aux[i].fastcall_spills_num = 0; 3490 aux[i].fastcall_pattern = 0; 3491 } 3492 } 3493 3494 static void scrub_special_slot(struct bpf_func_state *state, int spi) 3495 { 3496 int i; 3497 3498 /* regular write of data into stack destroys any spilled ptr */ 3499 state->stack[spi].spilled_ptr.type = NOT_INIT; 3500 /* Mark slots as STACK_MISC if they belonged to spilled ptr/dynptr/iter. */ 3501 if (is_stack_slot_special(&state->stack[spi])) 3502 for (i = 0; i < BPF_REG_SIZE; i++) 3503 scrub_spilled_slot(&state->stack[spi].slot_type[i]); 3504 } 3505 3506 /* check_stack_{read,write}_fixed_off functions track spill/fill of registers, 3507 * stack boundary and alignment are checked in check_mem_access() 3508 */ 3509 static int check_stack_write_fixed_off(struct bpf_verifier_env *env, 3510 /* stack frame we're writing to */ 3511 struct bpf_func_state *state, 3512 int off, int size, int value_regno, 3513 int insn_idx) 3514 { 3515 struct bpf_func_state *cur; /* state of the current function */ 3516 int i, slot = -off - 1, spi = slot / BPF_REG_SIZE, err; 3517 struct bpf_insn *insn = &env->prog->insnsi[insn_idx]; 3518 struct bpf_reg_state *reg = NULL; 3519 int insn_flags = INSN_F_STACK_ACCESS; 3520 int hist_spi = spi, hist_frame = state->frameno; 3521 3522 /* caller checked that off % size == 0 and -MAX_BPF_STACK <= off < 0, 3523 * so it's aligned access and [off, off + size) are within stack limits 3524 */ 3525 if (!env->allow_ptr_leaks && 3526 bpf_is_spilled_reg(&state->stack[spi]) && 3527 !bpf_is_spilled_scalar_reg(&state->stack[spi]) && 3528 size != BPF_REG_SIZE) { 3529 verbose(env, "attempt to corrupt spilled pointer on stack\n"); 3530 return -EACCES; 3531 } 3532 3533 cur = env->cur_state->frame[env->cur_state->curframe]; 3534 if (value_regno >= 0) 3535 reg = &cur->regs[value_regno]; 3536 if (!env->bypass_spec_v4) { 3537 bool sanitize = reg && is_spillable_regtype(reg->type); 3538 3539 for (i = 0; i < size; i++) { 3540 u8 type = state->stack[spi].slot_type[i]; 3541 3542 if (type != STACK_MISC && type != STACK_ZERO) { 3543 sanitize = true; 3544 break; 3545 } 3546 } 3547 3548 if (sanitize) 3549 env->insn_aux_data[insn_idx].nospec_result = true; 3550 } 3551 3552 err = destroy_if_dynptr_stack_slot(env, state, spi); 3553 if (err) 3554 return err; 3555 3556 check_fastcall_stack_contract(env, state, insn_idx, off); 3557 mark_stack_slot_scratched(env, spi); 3558 if (reg && !(off % BPF_REG_SIZE) && reg->type == SCALAR_VALUE && env->bpf_capable) { 3559 bool reg_value_fits; 3560 3561 reg_value_fits = get_reg_width(reg) <= BITS_PER_BYTE * size; 3562 /* Make sure that reg had an ID to build a relation on spill. */ 3563 if (reg_value_fits) 3564 assign_scalar_id_before_mov(env, reg); 3565 save_register_state(env, state, spi, reg, size); 3566 /* Break the relation on a narrowing spill. */ 3567 if (!reg_value_fits) 3568 state->stack[spi].spilled_ptr.id = 0; 3569 } else if (!reg && !(off % BPF_REG_SIZE) && is_bpf_st_mem(insn) && 3570 env->bpf_capable) { 3571 struct bpf_reg_state *tmp_reg = &env->fake_reg[0]; 3572 3573 memset(tmp_reg, 0, sizeof(*tmp_reg)); 3574 __mark_reg_known(tmp_reg, insn->imm); 3575 tmp_reg->type = SCALAR_VALUE; 3576 save_register_state(env, state, spi, tmp_reg, size); 3577 } else if (reg && is_spillable_regtype(reg->type)) { 3578 /* register containing pointer is being spilled into stack */ 3579 if (size != BPF_REG_SIZE) { 3580 verbose_linfo(env, insn_idx, "; "); 3581 verbose(env, "invalid size of register spill\n"); 3582 return -EACCES; 3583 } 3584 if (state != cur && reg->type == PTR_TO_STACK) { 3585 verbose(env, "cannot spill pointers to stack into stack frame of the caller\n"); 3586 return -EINVAL; 3587 } 3588 save_register_state(env, state, spi, reg, size); 3589 } else { 3590 u8 type = STACK_MISC; 3591 3592 scrub_special_slot(state, spi); 3593 3594 /* when we zero initialize stack slots mark them as such */ 3595 if ((reg && bpf_register_is_null(reg)) || 3596 (!reg && is_bpf_st_mem(insn) && insn->imm == 0)) { 3597 /* STACK_ZERO case happened because register spill 3598 * wasn't properly aligned at the stack slot boundary, 3599 * so it's not a register spill anymore; force 3600 * originating register to be precise to make 3601 * STACK_ZERO correct for subsequent states 3602 */ 3603 err = mark_chain_precision(env, value_regno); 3604 if (err) 3605 return err; 3606 type = STACK_ZERO; 3607 } 3608 3609 /* Mark slots affected by this stack write. */ 3610 for (i = 0; i < size; i++) 3611 state->stack[spi].slot_type[(slot - i) % BPF_REG_SIZE] = type; 3612 insn_flags = 0; /* not a register spill */ 3613 } 3614 3615 if (insn_flags) 3616 return bpf_push_jmp_history(env, env->cur_state, insn_flags, 3617 hist_spi, hist_frame, 0); 3618 return 0; 3619 } 3620 3621 /* Write the stack: 'stack[ptr_reg + off] = value_regno'. 'ptr_reg' is 3622 * known to contain a variable offset. 3623 * This function checks whether the write is permitted and conservatively 3624 * tracks the effects of the write, considering that each stack slot in the 3625 * dynamic range is potentially written to. 3626 * 3627 * 'value_regno' can be -1, meaning that an unknown value is being written to 3628 * the stack. 3629 * 3630 * Spilled pointers in range are not marked as written because we don't know 3631 * what's going to be actually written. This means that read propagation for 3632 * future reads cannot be terminated by this write. 3633 * 3634 * For privileged programs, uninitialized stack slots are considered 3635 * initialized by this write (even though we don't know exactly what offsets 3636 * are going to be written to). The idea is that we don't want the verifier to 3637 * reject future reads that access slots written to through variable offsets. 3638 */ 3639 static int check_stack_write_var_off(struct bpf_verifier_env *env, 3640 /* func where register points to */ 3641 struct bpf_func_state *state, 3642 struct bpf_reg_state *ptr_reg, int off, int size, 3643 int value_regno, int insn_idx) 3644 { 3645 struct bpf_func_state *cur; /* state of the current function */ 3646 int min_off, max_off; 3647 int i, err; 3648 struct bpf_reg_state *value_reg = NULL; 3649 struct bpf_insn *insn = &env->prog->insnsi[insn_idx]; 3650 bool writing_zero = false; 3651 /* set if the fact that we're writing a zero is used to let any 3652 * stack slots remain STACK_ZERO 3653 */ 3654 bool zero_used = false; 3655 3656 cur = env->cur_state->frame[env->cur_state->curframe]; 3657 min_off = reg_smin(ptr_reg) + off; 3658 max_off = reg_smax(ptr_reg) + off + size; 3659 if (value_regno >= 0) 3660 value_reg = &cur->regs[value_regno]; 3661 if ((value_reg && bpf_register_is_null(value_reg)) || 3662 (!value_reg && is_bpf_st_mem(insn) && insn->imm == 0)) 3663 writing_zero = true; 3664 3665 for (i = min_off; i < max_off; i++) { 3666 int spi; 3667 3668 spi = bpf_get_spi(i); 3669 err = destroy_if_dynptr_stack_slot(env, state, spi); 3670 if (err) 3671 return err; 3672 } 3673 3674 check_fastcall_stack_contract(env, state, insn_idx, min_off); 3675 /* Variable offset writes destroy any spilled pointers in range. */ 3676 for (i = min_off; i < max_off; i++) { 3677 u8 new_type, *stype; 3678 int slot, spi; 3679 3680 slot = -i - 1; 3681 spi = slot / BPF_REG_SIZE; 3682 stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE]; 3683 mark_stack_slot_scratched(env, spi); 3684 3685 if (!env->allow_ptr_leaks && *stype != STACK_MISC && *stype != STACK_ZERO) { 3686 /* Reject the write if range we may write to has not 3687 * been initialized beforehand. If we didn't reject 3688 * here, the ptr status would be erased below (even 3689 * though not all slots are actually overwritten), 3690 * possibly opening the door to leaks. 3691 * 3692 * We do however catch STACK_INVALID case below, and 3693 * only allow reading possibly uninitialized memory 3694 * later for CAP_PERFMON, as the write may not happen to 3695 * that slot. 3696 */ 3697 verbose(env, "spilled ptr in range of var-offset stack write; insn %d, ptr off: %d", 3698 insn_idx, i); 3699 return -EINVAL; 3700 } 3701 3702 /* If writing_zero and the spi slot contains a spill of value 0, 3703 * maintain the spill type. 3704 */ 3705 if (writing_zero && *stype == STACK_SPILL && 3706 bpf_is_spilled_scalar_reg(&state->stack[spi])) { 3707 struct bpf_reg_state *spill_reg = &state->stack[spi].spilled_ptr; 3708 3709 if (tnum_is_const(spill_reg->var_off) && spill_reg->var_off.value == 0) { 3710 zero_used = true; 3711 continue; 3712 } 3713 } 3714 3715 /* 3716 * Scrub slots if variable-offset stack write goes over spilled pointers. 3717 * Otherwise bpf_is_spilled_reg() may == true && spilled_ptr.type == NOT_INIT 3718 * and valid program is rejected by check_stack_read_fixed_off() 3719 * with obscure "invalid size of register fill" message. 3720 */ 3721 scrub_special_slot(state, spi); 3722 3723 /* Update the slot type. */ 3724 new_type = STACK_MISC; 3725 if (writing_zero && *stype == STACK_ZERO) { 3726 new_type = STACK_ZERO; 3727 zero_used = true; 3728 } 3729 /* If the slot is STACK_INVALID, we check whether it's OK to 3730 * pretend that it will be initialized by this write. The slot 3731 * might not actually be written to, and so if we mark it as 3732 * initialized future reads might leak uninitialized memory. 3733 * For privileged programs, we will accept such reads to slots 3734 * that may or may not be written because, if we're reject 3735 * them, the error would be too confusing. 3736 * Conservatively, treat STACK_POISON in a similar way. 3737 */ 3738 if ((*stype == STACK_INVALID || *stype == STACK_POISON) && 3739 !env->allow_uninit_stack) { 3740 verbose(env, "uninit stack in range of var-offset write prohibited for !root; insn %d, off: %d", 3741 insn_idx, i); 3742 return -EINVAL; 3743 } 3744 *stype = new_type; 3745 } 3746 if (zero_used) { 3747 /* backtracking doesn't work for STACK_ZERO yet. */ 3748 err = mark_chain_precision(env, value_regno); 3749 if (err) 3750 return err; 3751 } 3752 return 0; 3753 } 3754 3755 /* When register 'dst_regno' is assigned some values from stack[min_off, 3756 * max_off), we set the register's type according to the types of the 3757 * respective stack slots. If all the stack values are known to be zeros, then 3758 * so is the destination reg. Otherwise, the register is considered to be 3759 * SCALAR. This function does not deal with register filling; the caller must 3760 * ensure that all spilled registers in the stack range have been marked as 3761 * read. 3762 */ 3763 static void mark_reg_stack_read(struct bpf_verifier_env *env, 3764 /* func where src register points to */ 3765 struct bpf_func_state *ptr_state, 3766 int min_off, int max_off, int dst_regno) 3767 { 3768 struct bpf_verifier_state *vstate = env->cur_state; 3769 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 3770 int i, slot, spi; 3771 u8 *stype; 3772 int zeros = 0; 3773 3774 for (i = min_off; i < max_off; i++) { 3775 slot = -i - 1; 3776 spi = slot / BPF_REG_SIZE; 3777 mark_stack_slot_scratched(env, spi); 3778 stype = ptr_state->stack[spi].slot_type; 3779 if (stype[slot % BPF_REG_SIZE] != STACK_ZERO) 3780 break; 3781 zeros++; 3782 } 3783 if (zeros == max_off - min_off) { 3784 /* Any access_size read into register is zero extended, 3785 * so the whole register == const_zero. 3786 */ 3787 __mark_reg_const_zero(env, &state->regs[dst_regno]); 3788 } else { 3789 /* have read misc data from the stack */ 3790 mark_reg_unknown(env, state->regs, dst_regno); 3791 } 3792 } 3793 3794 /* Read the stack at 'off' and put the results into the register indicated by 3795 * 'dst_regno'. It handles reg filling if the addressed stack slot is a 3796 * spilled reg. 3797 * 3798 * 'dst_regno' can be -1, meaning that the read value is not going to a 3799 * register. 3800 * 3801 * The access is assumed to be within the current stack bounds. 3802 */ 3803 static int check_stack_read_fixed_off(struct bpf_verifier_env *env, 3804 /* func where src register points to */ 3805 struct bpf_func_state *reg_state, 3806 int off, int size, int dst_regno) 3807 { 3808 struct bpf_verifier_state *vstate = env->cur_state; 3809 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 3810 int i, slot = -off - 1, spi = slot / BPF_REG_SIZE; 3811 struct bpf_reg_state *reg; 3812 u8 *stype, type; 3813 int insn_flags = INSN_F_STACK_ACCESS; 3814 int hist_spi = spi, hist_frame = reg_state->frameno; 3815 3816 stype = reg_state->stack[spi].slot_type; 3817 reg = ®_state->stack[spi].spilled_ptr; 3818 3819 mark_stack_slot_scratched(env, spi); 3820 check_fastcall_stack_contract(env, state, env->insn_idx, off); 3821 3822 if (bpf_is_spilled_reg(®_state->stack[spi])) { 3823 u8 spill_size = 1; 3824 3825 for (i = BPF_REG_SIZE - 1; i > 0 && stype[i - 1] == STACK_SPILL; i--) 3826 spill_size++; 3827 3828 if (size != BPF_REG_SIZE || spill_size != BPF_REG_SIZE) { 3829 if (reg->type != SCALAR_VALUE) { 3830 verbose_linfo(env, env->insn_idx, "; "); 3831 verbose(env, "invalid size of register fill\n"); 3832 return -EACCES; 3833 } 3834 3835 if (dst_regno < 0) 3836 return 0; 3837 3838 if (size <= spill_size && 3839 bpf_stack_narrow_access_ok(off, size, spill_size)) { 3840 /* The earlier check_reg_arg() has decided the 3841 * subreg_def for this insn. Save it first. 3842 */ 3843 s32 subreg_def = state->regs[dst_regno].subreg_def; 3844 3845 if (env->bpf_capable && size == 4 && spill_size == 4 && 3846 get_reg_width(reg) <= 32) 3847 /* Ensure stack slot has an ID to build a relation 3848 * with the destination register on fill. 3849 */ 3850 assign_scalar_id_before_mov(env, reg); 3851 state->regs[dst_regno] = *reg; 3852 state->regs[dst_regno].subreg_def = subreg_def; 3853 3854 /* Break the relation on a narrowing fill. 3855 * coerce_reg_to_size will adjust the boundaries. 3856 */ 3857 if (get_reg_width(reg) > size * BITS_PER_BYTE) 3858 clear_scalar_id(&state->regs[dst_regno]); 3859 } else { 3860 int spill_cnt = 0, zero_cnt = 0; 3861 3862 for (i = 0; i < size; i++) { 3863 type = stype[(slot - i) % BPF_REG_SIZE]; 3864 if (type == STACK_SPILL) { 3865 spill_cnt++; 3866 continue; 3867 } 3868 if (type == STACK_MISC) 3869 continue; 3870 if (type == STACK_ZERO) { 3871 zero_cnt++; 3872 continue; 3873 } 3874 if (type == STACK_INVALID && env->allow_uninit_stack) 3875 continue; 3876 if (type == STACK_POISON) { 3877 verbose(env, "reading from stack off %d+%d size %d, slot poisoned by dead code elimination\n", 3878 off, i, size); 3879 } else { 3880 verbose(env, "invalid read from stack off %d+%d size %d\n", 3881 off, i, size); 3882 } 3883 return -EACCES; 3884 } 3885 3886 if (spill_cnt == size && 3887 tnum_is_const(reg->var_off) && reg->var_off.value == 0) { 3888 __mark_reg_const_zero(env, &state->regs[dst_regno]); 3889 /* this IS register fill, so keep insn_flags */ 3890 } else if (zero_cnt == size) { 3891 /* similarly to mark_reg_stack_read(), preserve zeroes */ 3892 __mark_reg_const_zero(env, &state->regs[dst_regno]); 3893 insn_flags = 0; /* not restoring original register state */ 3894 } else { 3895 mark_reg_unknown(env, state->regs, dst_regno); 3896 insn_flags = 0; /* not restoring original register state */ 3897 } 3898 } 3899 } else if (dst_regno >= 0) { 3900 /* restore register state from stack */ 3901 if (env->bpf_capable) 3902 /* Ensure stack slot has an ID to build a relation 3903 * with the destination register on fill. 3904 */ 3905 assign_scalar_id_before_mov(env, reg); 3906 state->regs[dst_regno] = *reg; 3907 /* mark reg as written since spilled pointer state likely 3908 * has its liveness marks cleared by is_state_visited() 3909 * which resets stack/reg liveness for state transitions 3910 */ 3911 } else if (__is_pointer_value(env->allow_ptr_leaks, reg)) { 3912 /* If dst_regno==-1, the caller is asking us whether 3913 * it is acceptable to use this value as a SCALAR_VALUE 3914 * (e.g. for XADD). 3915 * We must not allow unprivileged callers to do that 3916 * with spilled pointers. 3917 */ 3918 verbose(env, "leaking pointer from stack off %d\n", 3919 off); 3920 return -EACCES; 3921 } 3922 } else { 3923 for (i = 0; i < size; i++) { 3924 type = stype[(slot - i) % BPF_REG_SIZE]; 3925 if (type == STACK_MISC) 3926 continue; 3927 if (type == STACK_ZERO) 3928 continue; 3929 if (type == STACK_INVALID && env->allow_uninit_stack) 3930 continue; 3931 if (type == STACK_POISON) { 3932 verbose(env, "reading from stack off %d+%d size %d, slot poisoned by dead code elimination\n", 3933 off, i, size); 3934 } else { 3935 verbose(env, "invalid read from stack off %d+%d size %d\n", 3936 off, i, size); 3937 } 3938 return -EACCES; 3939 } 3940 if (dst_regno >= 0) 3941 mark_reg_stack_read(env, reg_state, off, off + size, dst_regno); 3942 insn_flags = 0; /* we are not restoring spilled register */ 3943 } 3944 if (insn_flags) 3945 return bpf_push_jmp_history(env, env->cur_state, insn_flags, 3946 hist_spi, hist_frame, 0); 3947 return 0; 3948 } 3949 3950 enum bpf_access_src { 3951 ACCESS_DIRECT = 1, /* the access is performed by an instruction */ 3952 ACCESS_HELPER = 2, /* the access is performed by a helper */ 3953 }; 3954 3955 static int check_stack_range_initialized(struct bpf_verifier_env *env, struct bpf_reg_state *reg, 3956 argno_t argno, int off, int access_size, 3957 bool zero_size_allowed, 3958 enum bpf_access_type type, 3959 struct bpf_call_arg_meta *meta); 3960 3961 static struct bpf_reg_state *reg_state(struct bpf_verifier_env *env, int regno) 3962 { 3963 return cur_regs(env) + regno; 3964 } 3965 3966 /* Read the stack at 'reg + off' and put the result into the register 3967 * 'dst_regno'. 3968 * 'off' includes the pointer register's fixed offset(i.e. 'reg->off'), 3969 * but not its variable offset. 3970 * 'size' is assumed to be <= reg size and the access is assumed to be aligned. 3971 * 3972 * As opposed to check_stack_read_fixed_off, this function doesn't deal with 3973 * filling registers (i.e. reads of spilled register cannot be detected when 3974 * the offset is not fixed). We conservatively mark 'dst_regno' as containing 3975 * SCALAR_VALUE. That's why we assert that the 'reg' has a variable 3976 * offset; for a fixed offset check_stack_read_fixed_off should be used 3977 * instead. 3978 */ 3979 static int check_stack_read_var_off(struct bpf_verifier_env *env, struct bpf_reg_state *reg, 3980 argno_t ptr_argno, int off, int size, int dst_regno) 3981 { 3982 struct bpf_func_state *ptr_state = bpf_func(env, reg); 3983 int err; 3984 int min_off, max_off; 3985 3986 /* Note that we pass a NULL meta, so raw access will not be permitted. 3987 */ 3988 err = check_stack_range_initialized(env, reg, ptr_argno, off, size, 3989 false, BPF_READ, NULL); 3990 if (err) 3991 return err; 3992 3993 min_off = reg_smin(reg) + off; 3994 max_off = reg_smax(reg) + off; 3995 mark_reg_stack_read(env, ptr_state, min_off, max_off + size, dst_regno); 3996 check_fastcall_stack_contract(env, ptr_state, env->insn_idx, min_off); 3997 return 0; 3998 } 3999 4000 /* check_stack_read dispatches to check_stack_read_fixed_off or 4001 * check_stack_read_var_off. 4002 * 4003 * The caller must ensure that the offset falls within the allocated stack 4004 * bounds. 4005 * 4006 * 'dst_regno' is a register which will receive the value from the stack. It 4007 * can be -1, meaning that the read value is not going to a register. 4008 */ 4009 static int check_stack_read(struct bpf_verifier_env *env, 4010 struct bpf_reg_state *reg, argno_t ptr_argno, int off, int size, 4011 int dst_regno) 4012 { 4013 struct bpf_func_state *state = bpf_func(env, reg); 4014 int err; 4015 /* Some accesses are only permitted with a static offset. */ 4016 bool var_off = !tnum_is_const(reg->var_off); 4017 4018 /* The offset is required to be static when reads don't go to a 4019 * register, in order to not leak pointers (see 4020 * check_stack_read_fixed_off). 4021 */ 4022 if (dst_regno < 0 && var_off) { 4023 char tn_buf[48]; 4024 4025 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 4026 verbose(env, "variable offset stack pointer cannot be passed into helper function; var_off=%s off=%d size=%d\n", 4027 tn_buf, off, size); 4028 return -EACCES; 4029 } 4030 /* Variable offset is prohibited for unprivileged mode for simplicity 4031 * since it requires corresponding support in Spectre masking for stack 4032 * ALU. See also retrieve_ptr_limit(). The check in 4033 * check_stack_access_for_ptr_arithmetic() called by 4034 * adjust_ptr_min_max_vals() prevents users from creating stack pointers 4035 * with variable offsets, therefore no check is required here. Further, 4036 * just checking it here would be insufficient as speculative stack 4037 * writes could still lead to unsafe speculative behaviour. 4038 */ 4039 if (!var_off) { 4040 off += reg->var_off.value; 4041 err = check_stack_read_fixed_off(env, state, off, size, 4042 dst_regno); 4043 } else { 4044 /* Variable offset stack reads need more conservative handling 4045 * than fixed offset ones. Note that dst_regno >= 0 on this 4046 * branch. 4047 */ 4048 err = check_stack_read_var_off(env, reg, ptr_argno, off, size, 4049 dst_regno); 4050 } 4051 return err; 4052 } 4053 4054 4055 /* check_stack_write dispatches to check_stack_write_fixed_off or 4056 * check_stack_write_var_off. 4057 * 4058 * 'reg' is the register used as a pointer into the stack. 4059 * 'value_regno' is the register whose value we're writing to the stack. It can 4060 * be -1, meaning that we're not writing from a register. 4061 * 4062 * The caller must ensure that the offset falls within the maximum stack size. 4063 */ 4064 static int check_stack_write(struct bpf_verifier_env *env, 4065 struct bpf_reg_state *reg, int off, int size, 4066 int value_regno, int insn_idx) 4067 { 4068 struct bpf_func_state *state = bpf_func(env, reg); 4069 int err; 4070 4071 if (tnum_is_const(reg->var_off)) { 4072 off += reg->var_off.value; 4073 err = check_stack_write_fixed_off(env, state, off, size, 4074 value_regno, insn_idx); 4075 } else { 4076 /* Variable offset stack reads need more conservative handling 4077 * than fixed offset ones. 4078 */ 4079 err = check_stack_write_var_off(env, state, 4080 reg, off, size, 4081 value_regno, insn_idx); 4082 } 4083 return err; 4084 } 4085 4086 /* 4087 * Write a value to the outgoing stack arg area. 4088 * off is a negative offset from r11 (e.g. -8 for arg6, -16 for arg7). 4089 */ 4090 static int check_stack_arg_write(struct bpf_verifier_env *env, struct bpf_func_state *state, 4091 int off, struct bpf_reg_state *value_reg) 4092 { 4093 int max_stack_arg_regs = MAX_BPF_FUNC_ARGS - MAX_BPF_FUNC_REG_ARGS; 4094 struct bpf_subprog_info *subprog = &env->subprog_info[state->subprogno]; 4095 int spi = -off / BPF_REG_SIZE - 1; 4096 struct bpf_reg_state *arg; 4097 int err; 4098 4099 if (spi >= max_stack_arg_regs) { 4100 verbose(env, "stack arg write offset %d exceeds max %d stack args\n", 4101 off, max_stack_arg_regs); 4102 return -EINVAL; 4103 } 4104 4105 err = grow_stack_arg_slots(env, state, spi + 1); 4106 if (err) 4107 return err; 4108 4109 /* Track the max outgoing stack arg slot count. */ 4110 if (spi + 1 > subprog->max_out_stack_arg_cnt) 4111 subprog->max_out_stack_arg_cnt = spi + 1; 4112 4113 if (value_reg) { 4114 state->stack_arg_regs[spi] = *value_reg; 4115 } else { 4116 /* BPF_ST: store immediate, treat as scalar */ 4117 arg = &state->stack_arg_regs[spi]; 4118 arg->type = SCALAR_VALUE; 4119 __mark_reg_known(arg, env->prog->insnsi[env->insn_idx].imm); 4120 } 4121 state->no_stack_arg_load = true; 4122 return bpf_push_jmp_history(env, env->cur_state, 4123 INSN_F_STACK_ARG_ACCESS, spi, 0, 0); 4124 } 4125 4126 /* 4127 * Read a value from the incoming stack arg area. 4128 * off is a positive offset from r11 (e.g. +8 for arg6, +16 for arg7). 4129 */ 4130 static int check_stack_arg_read(struct bpf_verifier_env *env, struct bpf_func_state *state, 4131 int off, int dst_regno) 4132 { 4133 struct bpf_subprog_info *subprog = &env->subprog_info[state->subprogno]; 4134 struct bpf_verifier_state *vstate = env->cur_state; 4135 int spi = off / BPF_REG_SIZE - 1; 4136 struct bpf_func_state *caller, *cur; 4137 struct bpf_reg_state *arg; 4138 4139 if (state->no_stack_arg_load) { 4140 verbose(env, "r11 load must be before any r11 store or call insn\n"); 4141 return -EINVAL; 4142 } 4143 4144 if (spi + 1 > bpf_in_stack_arg_cnt(subprog)) { 4145 verbose(env, "invalid read from stack arg off %d depth %d\n", 4146 off, bpf_in_stack_arg_cnt(subprog) * BPF_REG_SIZE); 4147 return -EACCES; 4148 } 4149 4150 caller = vstate->frame[vstate->curframe - 1]; 4151 arg = &caller->stack_arg_regs[spi]; 4152 cur = vstate->frame[vstate->curframe]; 4153 cur->regs[dst_regno] = *arg; 4154 return bpf_push_jmp_history(env, env->cur_state, 4155 INSN_F_STACK_ARG_ACCESS, spi, 0, 0); 4156 } 4157 4158 static int mark_stack_arg_precision(struct bpf_verifier_env *env, int arg_idx) 4159 { 4160 struct bpf_func_state *caller = cur_func(env); 4161 int spi = arg_idx - MAX_BPF_FUNC_REG_ARGS; 4162 4163 bt_set_frame_stack_arg_slot(&env->bt, caller->frameno, spi); 4164 return mark_chain_precision_batch(env, env->cur_state); 4165 } 4166 4167 static int check_outgoing_stack_args(struct bpf_verifier_env *env, struct bpf_func_state *caller, 4168 int nargs) 4169 { 4170 int i, spi; 4171 4172 for (i = MAX_BPF_FUNC_REG_ARGS; i < nargs; i++) { 4173 spi = i - MAX_BPF_FUNC_REG_ARGS; 4174 if (spi >= caller->out_stack_arg_cnt || 4175 caller->stack_arg_regs[spi].type == NOT_INIT) { 4176 verbose(env, "callee expects %d args, stack arg%d is not initialized\n", 4177 nargs, spi + 1); 4178 return -EFAULT; 4179 } 4180 } 4181 4182 return 0; 4183 } 4184 4185 static struct bpf_reg_state *get_func_arg_reg(struct bpf_func_state *caller, 4186 struct bpf_reg_state *regs, int arg) 4187 { 4188 if (arg < MAX_BPF_FUNC_REG_ARGS) 4189 return ®s[arg + 1]; 4190 4191 return &caller->stack_arg_regs[arg - MAX_BPF_FUNC_REG_ARGS]; 4192 } 4193 4194 static int check_map_access_type(struct bpf_verifier_env *env, struct bpf_reg_state *reg, 4195 int off, int size, enum bpf_access_type type) 4196 { 4197 struct bpf_map *map = reg->map_ptr; 4198 u32 cap = bpf_map_flags_to_cap(map); 4199 4200 if (type == BPF_WRITE && !(cap & BPF_MAP_CAN_WRITE)) { 4201 verbose(env, "write into map forbidden, value_size=%d off=%lld size=%d\n", 4202 map->value_size, reg_smin(reg) + off, size); 4203 return -EACCES; 4204 } 4205 4206 if (type == BPF_READ && !(cap & BPF_MAP_CAN_READ)) { 4207 verbose(env, "read from map forbidden, value_size=%d off=%lld size=%d\n", 4208 map->value_size, reg_smin(reg) + off, size); 4209 return -EACCES; 4210 } 4211 4212 return 0; 4213 } 4214 4215 /* check read/write into memory region (e.g., map value, ringbuf sample, etc) */ 4216 static int __check_mem_access(struct bpf_verifier_env *env, struct bpf_reg_state *reg, argno_t argno, 4217 int off, int size, u32 mem_size, 4218 bool zero_size_allowed) 4219 { 4220 bool size_ok = size > 0 || (size == 0 && zero_size_allowed); 4221 4222 if (off >= 0 && size_ok && (u64)off + size <= mem_size) 4223 return 0; 4224 4225 switch (reg->type) { 4226 case PTR_TO_MAP_KEY: 4227 verbose(env, "invalid access to map key, key_size=%d off=%d size=%d\n", 4228 mem_size, off, size); 4229 break; 4230 case PTR_TO_MAP_VALUE: 4231 verbose(env, "invalid access to map value, value_size=%d off=%d size=%d\n", 4232 mem_size, off, size); 4233 break; 4234 case PTR_TO_PACKET: 4235 case PTR_TO_PACKET_META: 4236 case PTR_TO_PACKET_END: 4237 verbose(env, "invalid access to packet, off=%d size=%d, %s(id=%d,off=%d,r=%d)\n", 4238 off, size, reg_arg_name(env, argno), reg->id, off, mem_size); 4239 break; 4240 case PTR_TO_CTX: 4241 verbose(env, "invalid access to context, ctx_size=%d off=%d size=%d\n", 4242 mem_size, off, size); 4243 break; 4244 case PTR_TO_MEM: 4245 default: 4246 verbose(env, "invalid access to memory, mem_size=%u off=%d size=%d\n", 4247 mem_size, off, size); 4248 } 4249 4250 return -EACCES; 4251 } 4252 4253 /* check read/write into a memory region with possible variable offset */ 4254 static int check_mem_region_access(struct bpf_verifier_env *env, struct bpf_reg_state *reg, argno_t argno, 4255 int off, int size, u32 mem_size, 4256 bool zero_size_allowed) 4257 { 4258 int err; 4259 4260 /* We may have adjusted the register pointing to memory region, so we 4261 * need to try adding each of min_value and max_value to off 4262 * to make sure our theoretical access will be safe. 4263 * 4264 * The minimum value is only important with signed 4265 * comparisons where we can't assume the floor of a 4266 * value is 0. If we are using signed variables for our 4267 * index'es we need to make sure that whatever we use 4268 * will have a set floor within our range. 4269 */ 4270 if (reg_smin(reg) < 0 && 4271 (reg_smin(reg) == S64_MIN || 4272 (off + reg_smin(reg) != (s64)(s32)(off + reg_smin(reg))) || 4273 reg_smin(reg) + off < 0)) { 4274 verbose(env, "%s min value is negative, either use unsigned index or do a if (index >=0) check.\n", 4275 reg_arg_name(env, argno)); 4276 return -EACCES; 4277 } 4278 err = __check_mem_access(env, reg, argno, reg_smin(reg) + off, size, 4279 mem_size, zero_size_allowed); 4280 if (err) { 4281 verbose(env, "%s min value is outside of the allowed memory range\n", 4282 reg_arg_name(env, argno)); 4283 return err; 4284 } 4285 4286 /* If we haven't set a max value then we need to bail since we can't be 4287 * sure we won't do bad things. 4288 * If reg_umax(reg) + off could overflow, treat that as unbounded too. 4289 */ 4290 if (reg_umax(reg) >= BPF_MAX_VAR_OFF) { 4291 verbose(env, "%s unbounded memory access, make sure to bounds check any such access\n", 4292 reg_arg_name(env, argno)); 4293 return -EACCES; 4294 } 4295 err = __check_mem_access(env, reg, argno, reg_umax(reg) + off, size, 4296 mem_size, zero_size_allowed); 4297 if (err) { 4298 verbose(env, "%s max value is outside of the allowed memory range\n", 4299 reg_arg_name(env, argno)); 4300 return err; 4301 } 4302 4303 return 0; 4304 } 4305 4306 static int __check_ptr_off_reg(struct bpf_verifier_env *env, 4307 const struct bpf_reg_state *reg, argno_t argno, 4308 bool fixed_off_ok) 4309 { 4310 /* Access to this pointer-typed register or passing it to a helper 4311 * is only allowed in its original, unmodified form. 4312 */ 4313 4314 if (!tnum_is_const(reg->var_off)) { 4315 char tn_buf[48]; 4316 4317 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 4318 verbose(env, "variable %s access var_off=%s disallowed\n", 4319 reg_type_str(env, reg->type), tn_buf); 4320 return -EACCES; 4321 } 4322 4323 if (reg_smin(reg) < 0) { 4324 verbose(env, "negative offset %s ptr %s off=%lld disallowed\n", 4325 reg_type_str(env, reg->type), reg_arg_name(env, argno), reg->var_off.value); 4326 return -EACCES; 4327 } 4328 4329 if (!fixed_off_ok && reg->var_off.value != 0) { 4330 verbose(env, "dereference of modified %s ptr %s off=%lld disallowed\n", 4331 reg_type_str(env, reg->type), reg_arg_name(env, argno), reg->var_off.value); 4332 return -EACCES; 4333 } 4334 4335 return 0; 4336 } 4337 4338 static int check_ptr_off_reg(struct bpf_verifier_env *env, 4339 const struct bpf_reg_state *reg, int regno) 4340 { 4341 return __check_ptr_off_reg(env, reg, argno_from_reg(regno), false); 4342 } 4343 4344 static int map_kptr_match_type(struct bpf_verifier_env *env, 4345 struct btf_field *kptr_field, 4346 struct bpf_reg_state *reg, u32 regno) 4347 { 4348 const char *targ_name = btf_type_name(kptr_field->kptr.btf, kptr_field->kptr.btf_id); 4349 int perm_flags; 4350 const char *reg_name = ""; 4351 4352 if (base_type(reg->type) != PTR_TO_BTF_ID) 4353 goto bad_type; 4354 4355 if (btf_is_kernel(reg->btf)) { 4356 perm_flags = PTR_MAYBE_NULL | PTR_TRUSTED | MEM_RCU; 4357 4358 /* Only unreferenced case accepts untrusted pointers */ 4359 if (kptr_field->type == BPF_KPTR_UNREF) 4360 perm_flags |= PTR_UNTRUSTED; 4361 } else { 4362 perm_flags = PTR_MAYBE_NULL | MEM_ALLOC; 4363 if (kptr_field->type == BPF_KPTR_PERCPU) 4364 perm_flags |= MEM_PERCPU; 4365 } 4366 4367 if (type_flag(reg->type) & ~perm_flags) 4368 goto bad_type; 4369 4370 /* We need to verify reg->type and reg->btf, before accessing reg->btf */ 4371 reg_name = btf_type_name(reg->btf, reg->btf_id); 4372 4373 /* For ref_ptr case, release function check should ensure we get one 4374 * referenced PTR_TO_BTF_ID, and that its fixed offset is 0. For the 4375 * normal store of unreferenced kptr, we must ensure var_off is zero. 4376 * Since ref_ptr cannot be accessed directly by BPF insns, check for 4377 * reg->ref_obj_id is not needed here. 4378 */ 4379 if (__check_ptr_off_reg(env, reg, argno_from_reg(regno), true)) 4380 return -EACCES; 4381 4382 /* A full type match is needed, as BTF can be vmlinux, module or prog BTF, and 4383 * we also need to take into account the reg->var_off. 4384 * 4385 * We want to support cases like: 4386 * 4387 * struct foo { 4388 * struct bar br; 4389 * struct baz bz; 4390 * }; 4391 * 4392 * struct foo *v; 4393 * v = func(); // PTR_TO_BTF_ID 4394 * val->foo = v; // reg->var_off is zero, btf and btf_id match type 4395 * val->bar = &v->br; // reg->var_off is still zero, but we need to retry with 4396 * // first member type of struct after comparison fails 4397 * val->baz = &v->bz; // reg->var_off is non-zero, so struct needs to be walked 4398 * // to match type 4399 * 4400 * In the kptr_ref case, check_func_arg_reg_off already ensures reg->var_off 4401 * is zero. We must also ensure that btf_struct_ids_match does not walk 4402 * the struct to match type against first member of struct, i.e. reject 4403 * second case from above. Hence, when type is BPF_KPTR_REF, we set 4404 * strict mode to true for type match. 4405 */ 4406 if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->var_off.value, 4407 kptr_field->kptr.btf, kptr_field->kptr.btf_id, 4408 kptr_field->type != BPF_KPTR_UNREF)) 4409 goto bad_type; 4410 return 0; 4411 bad_type: 4412 verbose(env, "invalid kptr access, R%d type=%s%s ", regno, 4413 reg_type_str(env, reg->type), reg_name); 4414 verbose(env, "expected=%s%s", reg_type_str(env, PTR_TO_BTF_ID), targ_name); 4415 if (kptr_field->type == BPF_KPTR_UNREF) 4416 verbose(env, " or %s%s\n", reg_type_str(env, PTR_TO_BTF_ID | PTR_UNTRUSTED), 4417 targ_name); 4418 else 4419 verbose(env, "\n"); 4420 return -EINVAL; 4421 } 4422 4423 static bool in_sleepable(struct bpf_verifier_env *env) 4424 { 4425 return env->cur_state->in_sleepable; 4426 } 4427 4428 /* The non-sleepable programs and sleepable programs with explicit bpf_rcu_read_lock() 4429 * can dereference RCU protected pointers and result is PTR_TRUSTED. 4430 */ 4431 static bool in_rcu_cs(struct bpf_verifier_env *env) 4432 { 4433 return env->cur_state->active_rcu_locks || 4434 env->cur_state->active_locks || 4435 !in_sleepable(env); 4436 } 4437 4438 /* Once GCC supports btf_type_tag the following mechanism will be replaced with tag check */ 4439 BTF_SET_START(rcu_protected_types) 4440 #ifdef CONFIG_NET 4441 BTF_ID(struct, prog_test_ref_kfunc) 4442 #endif 4443 #ifdef CONFIG_CGROUPS 4444 BTF_ID(struct, cgroup) 4445 #endif 4446 #ifdef CONFIG_BPF_JIT 4447 BTF_ID(struct, bpf_cpumask) 4448 #endif 4449 BTF_ID(struct, task_struct) 4450 #ifdef CONFIG_CRYPTO 4451 BTF_ID(struct, bpf_crypto_ctx) 4452 #endif 4453 BTF_SET_END(rcu_protected_types) 4454 4455 static bool rcu_protected_object(const struct btf *btf, u32 btf_id) 4456 { 4457 if (!btf_is_kernel(btf)) 4458 return true; 4459 return btf_id_set_contains(&rcu_protected_types, btf_id); 4460 } 4461 4462 static struct btf_record *kptr_pointee_btf_record(struct btf_field *kptr_field) 4463 { 4464 struct btf_struct_meta *meta; 4465 4466 if (btf_is_kernel(kptr_field->kptr.btf)) 4467 return NULL; 4468 4469 meta = btf_find_struct_meta(kptr_field->kptr.btf, 4470 kptr_field->kptr.btf_id); 4471 4472 return meta ? meta->record : NULL; 4473 } 4474 4475 static bool rcu_safe_kptr(const struct btf_field *field) 4476 { 4477 const struct btf_field_kptr *kptr = &field->kptr; 4478 4479 return field->type == BPF_KPTR_PERCPU || 4480 (field->type == BPF_KPTR_REF && rcu_protected_object(kptr->btf, kptr->btf_id)); 4481 } 4482 4483 static u32 btf_ld_kptr_type(struct bpf_verifier_env *env, struct btf_field *kptr_field) 4484 { 4485 struct btf_record *rec; 4486 u32 ret; 4487 4488 ret = PTR_MAYBE_NULL; 4489 if (rcu_safe_kptr(kptr_field) && in_rcu_cs(env)) { 4490 ret |= MEM_RCU; 4491 if (kptr_field->type == BPF_KPTR_PERCPU) 4492 ret |= MEM_PERCPU; 4493 else if (!btf_is_kernel(kptr_field->kptr.btf)) 4494 ret |= MEM_ALLOC; 4495 4496 rec = kptr_pointee_btf_record(kptr_field); 4497 if (rec && btf_record_has_field(rec, BPF_GRAPH_NODE)) 4498 ret |= NON_OWN_REF; 4499 } else { 4500 ret |= PTR_UNTRUSTED; 4501 } 4502 4503 return ret; 4504 } 4505 4506 static int mark_uptr_ld_reg(struct bpf_verifier_env *env, u32 regno, 4507 struct btf_field *field) 4508 { 4509 struct bpf_reg_state *reg; 4510 const struct btf_type *t; 4511 4512 t = btf_type_by_id(field->kptr.btf, field->kptr.btf_id); 4513 mark_reg_known_zero(env, cur_regs(env), regno); 4514 reg = reg_state(env, regno); 4515 reg->type = PTR_TO_MEM | PTR_MAYBE_NULL; 4516 reg->mem_size = t->size; 4517 reg->id = ++env->id_gen; 4518 4519 return 0; 4520 } 4521 4522 static int check_map_kptr_access(struct bpf_verifier_env *env, 4523 int value_regno, int insn_idx, 4524 struct btf_field *kptr_field) 4525 { 4526 struct bpf_insn *insn = &env->prog->insnsi[insn_idx]; 4527 int class = BPF_CLASS(insn->code); 4528 struct bpf_reg_state *val_reg; 4529 int ret; 4530 4531 /* Things we already checked for in check_map_access and caller: 4532 * - Reject cases where variable offset may touch kptr 4533 * - size of access (must be BPF_DW) 4534 * - tnum_is_const(reg->var_off) 4535 * - kptr_field->offset == off + reg->var_off.value 4536 */ 4537 /* Only BPF_[LDX,STX,ST] | BPF_MEM | BPF_DW is supported */ 4538 if (BPF_MODE(insn->code) != BPF_MEM) { 4539 verbose(env, "kptr in map can only be accessed using BPF_MEM instruction mode\n"); 4540 return -EACCES; 4541 } 4542 4543 /* We only allow loading referenced kptr, since it will be marked as 4544 * untrusted, similar to unreferenced kptr. 4545 */ 4546 if (class != BPF_LDX && 4547 (kptr_field->type == BPF_KPTR_REF || kptr_field->type == BPF_KPTR_PERCPU)) { 4548 verbose(env, "store to referenced kptr disallowed\n"); 4549 return -EACCES; 4550 } 4551 if (class != BPF_LDX && kptr_field->type == BPF_UPTR) { 4552 verbose(env, "store to uptr disallowed\n"); 4553 return -EACCES; 4554 } 4555 4556 if (class == BPF_LDX) { 4557 if (kptr_field->type == BPF_UPTR) 4558 return mark_uptr_ld_reg(env, value_regno, kptr_field); 4559 4560 /* We can simply mark the value_regno receiving the pointer 4561 * value from map as PTR_TO_BTF_ID, with the correct type. 4562 */ 4563 ret = mark_btf_ld_reg(env, cur_regs(env), value_regno, PTR_TO_BTF_ID, 4564 kptr_field->kptr.btf, kptr_field->kptr.btf_id, 4565 btf_ld_kptr_type(env, kptr_field)); 4566 if (ret < 0) 4567 return ret; 4568 } else if (class == BPF_STX) { 4569 val_reg = reg_state(env, value_regno); 4570 if (!bpf_register_is_null(val_reg) && 4571 map_kptr_match_type(env, kptr_field, val_reg, value_regno)) 4572 return -EACCES; 4573 } else if (class == BPF_ST) { 4574 if (insn->imm) { 4575 verbose(env, "BPF_ST imm must be 0 when storing to kptr at off=%u\n", 4576 kptr_field->offset); 4577 return -EACCES; 4578 } 4579 } else { 4580 verbose(env, "kptr in map can only be accessed using BPF_LDX/BPF_STX/BPF_ST\n"); 4581 return -EACCES; 4582 } 4583 return 0; 4584 } 4585 4586 /* 4587 * Return the size of the memory region accessible from a pointer to map value. 4588 * For INSN_ARRAY maps whole bpf_insn_array->ips array is accessible. 4589 */ 4590 static u32 map_mem_size(const struct bpf_map *map) 4591 { 4592 if (map->map_type == BPF_MAP_TYPE_INSN_ARRAY) 4593 return map->max_entries * sizeof(long); 4594 4595 return map->value_size; 4596 } 4597 4598 /* check read/write into a map element with possible variable offset */ 4599 static int check_map_access(struct bpf_verifier_env *env, struct bpf_reg_state *reg, argno_t argno, 4600 int off, int size, bool zero_size_allowed, 4601 enum bpf_access_src src) 4602 { 4603 struct bpf_map *map = reg->map_ptr; 4604 u32 mem_size = map_mem_size(map); 4605 struct btf_record *rec; 4606 int err, i; 4607 4608 err = check_mem_region_access(env, reg, argno, off, size, mem_size, zero_size_allowed); 4609 if (err) 4610 return err; 4611 4612 if (IS_ERR_OR_NULL(map->record)) 4613 return 0; 4614 rec = map->record; 4615 for (i = 0; i < rec->cnt; i++) { 4616 struct btf_field *field = &rec->fields[i]; 4617 u32 p = field->offset; 4618 4619 /* If any part of a field can be touched by load/store, reject 4620 * this program. To check that [x1, x2) overlaps with [y1, y2), 4621 * it is sufficient to check x1 < y2 && y1 < x2. 4622 */ 4623 if (reg_smin(reg) + off < p + field->size && 4624 p < reg_umax(reg) + off + size) { 4625 switch (field->type) { 4626 case BPF_KPTR_UNREF: 4627 case BPF_KPTR_REF: 4628 case BPF_KPTR_PERCPU: 4629 case BPF_UPTR: 4630 if (src != ACCESS_DIRECT) { 4631 verbose(env, "%s cannot be accessed indirectly by helper\n", 4632 btf_field_type_name(field->type)); 4633 return -EACCES; 4634 } 4635 if (!tnum_is_const(reg->var_off)) { 4636 verbose(env, "%s access cannot have variable offset\n", 4637 btf_field_type_name(field->type)); 4638 return -EACCES; 4639 } 4640 if (p != off + reg->var_off.value) { 4641 verbose(env, "%s access misaligned expected=%u off=%llu\n", 4642 btf_field_type_name(field->type), 4643 p, off + reg->var_off.value); 4644 return -EACCES; 4645 } 4646 if (size != bpf_size_to_bytes(BPF_DW)) { 4647 verbose(env, "%s access size must be BPF_DW\n", 4648 btf_field_type_name(field->type)); 4649 return -EACCES; 4650 } 4651 break; 4652 default: 4653 verbose(env, "%s cannot be accessed directly by load/store\n", 4654 btf_field_type_name(field->type)); 4655 return -EACCES; 4656 } 4657 } 4658 } 4659 return 0; 4660 } 4661 4662 static bool may_access_direct_pkt_data(struct bpf_verifier_env *env, 4663 const struct bpf_call_arg_meta *meta, 4664 enum bpf_access_type t) 4665 { 4666 enum bpf_prog_type prog_type = resolve_prog_type(env->prog); 4667 4668 switch (prog_type) { 4669 /* Program types only with direct read access go here! */ 4670 case BPF_PROG_TYPE_LWT_IN: 4671 case BPF_PROG_TYPE_LWT_OUT: 4672 case BPF_PROG_TYPE_LWT_SEG6LOCAL: 4673 case BPF_PROG_TYPE_SK_REUSEPORT: 4674 case BPF_PROG_TYPE_FLOW_DISSECTOR: 4675 case BPF_PROG_TYPE_CGROUP_SKB: 4676 if (t == BPF_WRITE) 4677 return false; 4678 fallthrough; 4679 4680 /* Program types with direct read + write access go here! */ 4681 case BPF_PROG_TYPE_SCHED_CLS: 4682 case BPF_PROG_TYPE_SCHED_ACT: 4683 case BPF_PROG_TYPE_XDP: 4684 case BPF_PROG_TYPE_LWT_XMIT: 4685 case BPF_PROG_TYPE_SK_SKB: 4686 case BPF_PROG_TYPE_SK_MSG: 4687 if (meta) 4688 return meta->pkt_access; 4689 4690 env->seen_direct_write = true; 4691 return true; 4692 4693 case BPF_PROG_TYPE_CGROUP_SOCKOPT: 4694 if (t == BPF_WRITE) 4695 env->seen_direct_write = true; 4696 4697 return true; 4698 4699 default: 4700 return false; 4701 } 4702 } 4703 4704 static int check_packet_access(struct bpf_verifier_env *env, struct bpf_reg_state *reg, argno_t argno, int off, 4705 int size, bool zero_size_allowed) 4706 { 4707 int err; 4708 4709 if (reg->range < 0) { 4710 verbose(env, "%s offset is outside of the packet\n", reg_arg_name(env, argno)); 4711 return -EINVAL; 4712 } 4713 4714 err = check_mem_region_access(env, reg, argno, off, size, reg->range, zero_size_allowed); 4715 if (err) 4716 return err; 4717 4718 /* __check_mem_access has made sure "off + size - 1" is within u16. 4719 * reg_umax(reg) can't be bigger than MAX_PACKET_OFF which is 0xffff, 4720 * otherwise find_good_pkt_pointers would have refused to set range info 4721 * that __check_mem_access would have rejected this pkt access. 4722 * Therefore, "off + reg_umax(reg) + size - 1" won't overflow u32. 4723 */ 4724 env->prog->aux->max_pkt_offset = 4725 max_t(u32, env->prog->aux->max_pkt_offset, 4726 off + reg_umax(reg) + size - 1); 4727 4728 return 0; 4729 } 4730 4731 static bool is_var_ctx_off_allowed(struct bpf_prog *prog) 4732 { 4733 return resolve_prog_type(prog) == BPF_PROG_TYPE_SYSCALL; 4734 } 4735 4736 /* check access to 'struct bpf_context' fields. Supports fixed offsets only */ 4737 static int __check_ctx_access(struct bpf_verifier_env *env, int insn_idx, int off, int size, 4738 enum bpf_access_type t, struct bpf_insn_access_aux *info) 4739 { 4740 if (env->ops->is_valid_access && 4741 env->ops->is_valid_access(off, size, t, env->prog, info)) { 4742 /* A non zero info.ctx_field_size indicates that this field is a 4743 * candidate for later verifier transformation to load the whole 4744 * field and then apply a mask when accessed with a narrower 4745 * access than actual ctx access size. A zero info.ctx_field_size 4746 * will only allow for whole field access and rejects any other 4747 * type of narrower access. 4748 */ 4749 if (base_type(info->reg_type) == PTR_TO_BTF_ID) { 4750 if (info->ref_obj_id && 4751 !find_reference_state(env->cur_state, info->ref_obj_id)) { 4752 verbose(env, "invalid bpf_context access off=%d. Reference may already be released\n", 4753 off); 4754 return -EACCES; 4755 } 4756 } else { 4757 env->insn_aux_data[insn_idx].ctx_field_size = info->ctx_field_size; 4758 } 4759 /* remember the offset of last byte accessed in ctx */ 4760 if (env->prog->aux->max_ctx_offset < off + size) 4761 env->prog->aux->max_ctx_offset = off + size; 4762 return 0; 4763 } 4764 4765 verbose(env, "invalid bpf_context access off=%d size=%d\n", off, size); 4766 return -EACCES; 4767 } 4768 4769 static int check_ctx_access(struct bpf_verifier_env *env, int insn_idx, struct bpf_reg_state *reg, argno_t argno, 4770 int off, int access_size, enum bpf_access_type t, 4771 struct bpf_insn_access_aux *info) 4772 { 4773 /* 4774 * Program types that don't rewrite ctx accesses can safely 4775 * dereference ctx pointers with fixed offsets. 4776 */ 4777 bool var_off_ok = is_var_ctx_off_allowed(env->prog); 4778 bool fixed_off_ok = !env->ops->convert_ctx_access; 4779 int err; 4780 4781 if (var_off_ok) 4782 err = check_mem_region_access(env, reg, argno, off, access_size, U16_MAX, false); 4783 else 4784 err = __check_ptr_off_reg(env, reg, argno, fixed_off_ok); 4785 if (err) 4786 return err; 4787 off += reg_umax(reg); 4788 4789 err = __check_ctx_access(env, insn_idx, off, access_size, t, info); 4790 if (err) 4791 verbose_linfo(env, insn_idx, "; "); 4792 return err; 4793 } 4794 4795 static int check_flow_keys_access(struct bpf_verifier_env *env, int off, 4796 int size) 4797 { 4798 if (size < 0 || off < 0 || 4799 (u64)off + size > sizeof(struct bpf_flow_keys)) { 4800 verbose(env, "invalid access to flow keys off=%d size=%d\n", 4801 off, size); 4802 return -EACCES; 4803 } 4804 return 0; 4805 } 4806 4807 static int check_sock_access(struct bpf_verifier_env *env, int insn_idx, 4808 struct bpf_reg_state *reg, argno_t argno, int off, int size, 4809 enum bpf_access_type t) 4810 { 4811 struct bpf_insn_access_aux info = {}; 4812 bool valid; 4813 4814 if (reg_smin(reg) < 0) { 4815 verbose(env, "%s min value is negative, either use unsigned index or do a if (index >=0) check.\n", 4816 reg_arg_name(env, argno)); 4817 return -EACCES; 4818 } 4819 4820 switch (reg->type) { 4821 case PTR_TO_SOCK_COMMON: 4822 valid = bpf_sock_common_is_valid_access(off, size, t, &info); 4823 break; 4824 case PTR_TO_SOCKET: 4825 valid = bpf_sock_is_valid_access(off, size, t, &info); 4826 break; 4827 case PTR_TO_TCP_SOCK: 4828 valid = bpf_tcp_sock_is_valid_access(off, size, t, &info); 4829 break; 4830 case PTR_TO_XDP_SOCK: 4831 valid = bpf_xdp_sock_is_valid_access(off, size, t, &info); 4832 break; 4833 default: 4834 valid = false; 4835 } 4836 4837 4838 if (valid) { 4839 env->insn_aux_data[insn_idx].ctx_field_size = 4840 info.ctx_field_size; 4841 return 0; 4842 } 4843 4844 verbose(env, "%s invalid %s access off=%d size=%d\n", 4845 reg_arg_name(env, argno), reg_type_str(env, reg->type), off, size); 4846 4847 return -EACCES; 4848 } 4849 4850 static bool is_pointer_value(struct bpf_verifier_env *env, int regno) 4851 { 4852 return __is_pointer_value(env->allow_ptr_leaks, reg_state(env, regno)); 4853 } 4854 4855 static bool is_ctx_reg(struct bpf_verifier_env *env, int regno) 4856 { 4857 const struct bpf_reg_state *reg = reg_state(env, regno); 4858 4859 return reg->type == PTR_TO_CTX; 4860 } 4861 4862 static bool is_sk_reg(struct bpf_verifier_env *env, int regno) 4863 { 4864 const struct bpf_reg_state *reg = reg_state(env, regno); 4865 4866 return type_is_sk_pointer(reg->type); 4867 } 4868 4869 static bool is_pkt_reg(struct bpf_verifier_env *env, int regno) 4870 { 4871 const struct bpf_reg_state *reg = reg_state(env, regno); 4872 4873 return type_is_pkt_pointer(reg->type); 4874 } 4875 4876 static bool is_flow_key_reg(struct bpf_verifier_env *env, int regno) 4877 { 4878 const struct bpf_reg_state *reg = reg_state(env, regno); 4879 4880 /* Separate to is_ctx_reg() since we still want to allow BPF_ST here. */ 4881 return reg->type == PTR_TO_FLOW_KEYS; 4882 } 4883 4884 static bool is_arena_reg(struct bpf_verifier_env *env, int regno) 4885 { 4886 const struct bpf_reg_state *reg = reg_state(env, regno); 4887 4888 return reg->type == PTR_TO_ARENA; 4889 } 4890 4891 /* Return false if @regno contains a pointer whose type isn't supported for 4892 * atomic instruction @insn. 4893 */ 4894 static bool atomic_ptr_type_ok(struct bpf_verifier_env *env, int regno, 4895 struct bpf_insn *insn) 4896 { 4897 if (is_ctx_reg(env, regno)) 4898 return false; 4899 if (is_pkt_reg(env, regno)) 4900 return false; 4901 if (is_flow_key_reg(env, regno)) 4902 return false; 4903 if (is_sk_reg(env, regno)) 4904 return false; 4905 if (is_arena_reg(env, regno)) 4906 return bpf_jit_supports_insn(insn, true); 4907 4908 return true; 4909 } 4910 4911 static u32 *reg2btf_ids[__BPF_REG_TYPE_MAX] = { 4912 #ifdef CONFIG_NET 4913 [PTR_TO_SOCKET] = &btf_sock_ids[BTF_SOCK_TYPE_SOCK], 4914 [PTR_TO_SOCK_COMMON] = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON], 4915 [PTR_TO_TCP_SOCK] = &btf_sock_ids[BTF_SOCK_TYPE_TCP], 4916 #endif 4917 [CONST_PTR_TO_MAP] = btf_bpf_map_id, 4918 }; 4919 4920 static bool is_trusted_reg(const struct bpf_reg_state *reg) 4921 { 4922 /* A referenced register is always trusted. */ 4923 if (reg->ref_obj_id) 4924 return true; 4925 4926 /* Types listed in the reg2btf_ids are always trusted */ 4927 if (reg2btf_ids[base_type(reg->type)] && 4928 !bpf_type_has_unsafe_modifiers(reg->type)) 4929 return true; 4930 4931 /* If a register is not referenced, it is trusted if it has the 4932 * MEM_ALLOC or PTR_TRUSTED type modifiers, and no others. Some of the 4933 * other type modifiers may be safe, but we elect to take an opt-in 4934 * approach here as some (e.g. PTR_UNTRUSTED and PTR_MAYBE_NULL) are 4935 * not. 4936 * 4937 * Eventually, we should make PTR_TRUSTED the single source of truth 4938 * for whether a register is trusted. 4939 */ 4940 return type_flag(reg->type) & BPF_REG_TRUSTED_MODIFIERS && 4941 !bpf_type_has_unsafe_modifiers(reg->type); 4942 } 4943 4944 static bool is_rcu_reg(const struct bpf_reg_state *reg) 4945 { 4946 return reg->type & MEM_RCU; 4947 } 4948 4949 static void clear_trusted_flags(enum bpf_type_flag *flag) 4950 { 4951 *flag &= ~(BPF_REG_TRUSTED_MODIFIERS | MEM_RCU); 4952 } 4953 4954 static int check_pkt_ptr_alignment(struct bpf_verifier_env *env, 4955 const struct bpf_reg_state *reg, 4956 int off, int size, bool strict) 4957 { 4958 struct tnum reg_off; 4959 int ip_align; 4960 4961 /* Byte size accesses are always allowed. */ 4962 if (!strict || size == 1) 4963 return 0; 4964 4965 /* For platforms that do not have a Kconfig enabling 4966 * CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS the value of 4967 * NET_IP_ALIGN is universally set to '2'. And on platforms 4968 * that do set CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS, we get 4969 * to this code only in strict mode where we want to emulate 4970 * the NET_IP_ALIGN==2 checking. Therefore use an 4971 * unconditional IP align value of '2'. 4972 */ 4973 ip_align = 2; 4974 4975 reg_off = tnum_add(reg->var_off, tnum_const(ip_align + off)); 4976 if (!tnum_is_aligned(reg_off, size)) { 4977 char tn_buf[48]; 4978 4979 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 4980 verbose(env, 4981 "misaligned packet access off %d+%s+%d size %d\n", 4982 ip_align, tn_buf, off, size); 4983 return -EACCES; 4984 } 4985 4986 return 0; 4987 } 4988 4989 static int check_generic_ptr_alignment(struct bpf_verifier_env *env, 4990 const struct bpf_reg_state *reg, 4991 const char *pointer_desc, 4992 int off, int size, bool strict) 4993 { 4994 struct tnum reg_off; 4995 4996 /* Byte size accesses are always allowed. */ 4997 if (!strict || size == 1) 4998 return 0; 4999 5000 reg_off = tnum_add(reg->var_off, tnum_const(off)); 5001 if (!tnum_is_aligned(reg_off, size)) { 5002 char tn_buf[48]; 5003 5004 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 5005 verbose(env, "misaligned %saccess off %s+%d size %d\n", 5006 pointer_desc, tn_buf, off, size); 5007 return -EACCES; 5008 } 5009 5010 return 0; 5011 } 5012 5013 static int check_ptr_alignment(struct bpf_verifier_env *env, 5014 const struct bpf_reg_state *reg, int off, 5015 int size, bool strict_alignment_once) 5016 { 5017 bool strict = env->strict_alignment || strict_alignment_once; 5018 const char *pointer_desc = ""; 5019 5020 switch (reg->type) { 5021 case PTR_TO_PACKET: 5022 case PTR_TO_PACKET_META: 5023 /* Special case, because of NET_IP_ALIGN. Given metadata sits 5024 * right in front, treat it the very same way. 5025 */ 5026 return check_pkt_ptr_alignment(env, reg, off, size, strict); 5027 case PTR_TO_FLOW_KEYS: 5028 pointer_desc = "flow keys "; 5029 break; 5030 case PTR_TO_MAP_KEY: 5031 pointer_desc = "key "; 5032 break; 5033 case PTR_TO_MAP_VALUE: 5034 pointer_desc = "value "; 5035 if (reg->map_ptr->map_type == BPF_MAP_TYPE_INSN_ARRAY) 5036 strict = true; 5037 break; 5038 case PTR_TO_CTX: 5039 pointer_desc = "context "; 5040 break; 5041 case PTR_TO_STACK: 5042 pointer_desc = "stack "; 5043 /* The stack spill tracking logic in check_stack_write_fixed_off() 5044 * and check_stack_read_fixed_off() relies on stack accesses being 5045 * aligned. 5046 */ 5047 strict = true; 5048 break; 5049 case PTR_TO_SOCKET: 5050 pointer_desc = "sock "; 5051 break; 5052 case PTR_TO_SOCK_COMMON: 5053 pointer_desc = "sock_common "; 5054 break; 5055 case PTR_TO_TCP_SOCK: 5056 pointer_desc = "tcp_sock "; 5057 break; 5058 case PTR_TO_XDP_SOCK: 5059 pointer_desc = "xdp_sock "; 5060 break; 5061 case PTR_TO_ARENA: 5062 return 0; 5063 default: 5064 break; 5065 } 5066 return check_generic_ptr_alignment(env, reg, pointer_desc, off, size, 5067 strict); 5068 } 5069 5070 static enum priv_stack_mode bpf_enable_priv_stack(struct bpf_prog *prog) 5071 { 5072 if (!bpf_jit_supports_private_stack()) 5073 return NO_PRIV_STACK; 5074 5075 /* bpf_prog_check_recur() checks all prog types that use bpf trampoline 5076 * while kprobe/tp/perf_event/raw_tp don't use trampoline hence checked 5077 * explicitly. 5078 */ 5079 switch (prog->type) { 5080 case BPF_PROG_TYPE_KPROBE: 5081 case BPF_PROG_TYPE_TRACEPOINT: 5082 case BPF_PROG_TYPE_PERF_EVENT: 5083 case BPF_PROG_TYPE_RAW_TRACEPOINT: 5084 return PRIV_STACK_ADAPTIVE; 5085 case BPF_PROG_TYPE_TRACING: 5086 case BPF_PROG_TYPE_LSM: 5087 case BPF_PROG_TYPE_STRUCT_OPS: 5088 if (prog->aux->priv_stack_requested || bpf_prog_check_recur(prog)) 5089 return PRIV_STACK_ADAPTIVE; 5090 fallthrough; 5091 default: 5092 break; 5093 } 5094 5095 return NO_PRIV_STACK; 5096 } 5097 5098 static int round_up_stack_depth(struct bpf_verifier_env *env, int stack_depth) 5099 { 5100 if (env->prog->jit_requested) 5101 return round_up(stack_depth, 16); 5102 5103 /* round up to 32-bytes, since this is granularity 5104 * of interpreter stack size 5105 */ 5106 return round_up(max_t(u32, stack_depth, 1), 32); 5107 } 5108 5109 /* temporary state used for call frame depth calculation */ 5110 struct bpf_subprog_call_depth_info { 5111 int ret_insn; /* caller instruction where we return to. */ 5112 int caller; /* caller subprogram idx */ 5113 int frame; /* # of consecutive static call stack frames on top of stack */ 5114 }; 5115 5116 /* starting from main bpf function walk all instructions of the function 5117 * and recursively walk all callees that given function can call. 5118 * Ignore jump and exit insns. 5119 */ 5120 static int check_max_stack_depth_subprog(struct bpf_verifier_env *env, int idx, 5121 struct bpf_subprog_call_depth_info *dinfo, 5122 bool priv_stack_supported) 5123 { 5124 struct bpf_subprog_info *subprog = env->subprog_info; 5125 struct bpf_insn *insn = env->prog->insnsi; 5126 int depth = 0, frame = 0, i, subprog_end, subprog_depth; 5127 bool tail_call_reachable = false; 5128 int total; 5129 int tmp; 5130 5131 /* no caller idx */ 5132 dinfo[idx].caller = -1; 5133 5134 i = subprog[idx].start; 5135 if (!priv_stack_supported) 5136 subprog[idx].priv_stack_mode = NO_PRIV_STACK; 5137 process_func: 5138 /* protect against potential stack overflow that might happen when 5139 * bpf2bpf calls get combined with tailcalls. Limit the caller's stack 5140 * depth for such case down to 256 so that the worst case scenario 5141 * would result in 8k stack size (32 which is tailcall limit * 256 = 5142 * 8k). 5143 * 5144 * To get the idea what might happen, see an example: 5145 * func1 -> sub rsp, 128 5146 * subfunc1 -> sub rsp, 256 5147 * tailcall1 -> add rsp, 256 5148 * func2 -> sub rsp, 192 (total stack size = 128 + 192 = 320) 5149 * subfunc2 -> sub rsp, 64 5150 * subfunc22 -> sub rsp, 128 5151 * tailcall2 -> add rsp, 128 5152 * func3 -> sub rsp, 32 (total stack size 128 + 192 + 64 + 32 = 416) 5153 * 5154 * tailcall will unwind the current stack frame but it will not get rid 5155 * of caller's stack as shown on the example above. 5156 */ 5157 if (idx && subprog[idx].has_tail_call && depth >= 256) { 5158 verbose(env, 5159 "tail_calls are not allowed when call stack of previous frames is %d bytes. Too large\n", 5160 depth); 5161 return -EACCES; 5162 } 5163 5164 subprog_depth = round_up_stack_depth(env, subprog[idx].stack_depth); 5165 if (IS_ENABLED(CONFIG_X86_64) && subprog[idx].stack_arg_cnt) { 5166 /* x86-64 uses R9 for both private stack frame pointer and arg6. */ 5167 subprog[idx].priv_stack_mode = NO_PRIV_STACK; 5168 } else if (priv_stack_supported) { 5169 /* Request private stack support only if the subprog stack 5170 * depth is no less than BPF_PRIV_STACK_MIN_SIZE. This is to 5171 * avoid jit penalty if the stack usage is small. 5172 */ 5173 if (subprog[idx].priv_stack_mode == PRIV_STACK_UNKNOWN && 5174 subprog_depth >= BPF_PRIV_STACK_MIN_SIZE) 5175 subprog[idx].priv_stack_mode = PRIV_STACK_ADAPTIVE; 5176 } 5177 5178 if (subprog[idx].priv_stack_mode == PRIV_STACK_ADAPTIVE) { 5179 if (subprog_depth > env->max_stack_depth) 5180 env->max_stack_depth = subprog_depth; 5181 if (subprog_depth > MAX_BPF_STACK) { 5182 verbose(env, "stack size of subprog %d is %d. Too large\n", 5183 idx, subprog_depth); 5184 return -EACCES; 5185 } 5186 } else { 5187 depth += subprog_depth; 5188 if (depth > env->max_stack_depth) 5189 env->max_stack_depth = depth; 5190 if (depth > MAX_BPF_STACK) { 5191 total = 0; 5192 for (tmp = idx; tmp >= 0; tmp = dinfo[tmp].caller) 5193 total++; 5194 5195 verbose(env, "combined stack size of %d calls is %d. Too large\n", 5196 total, depth); 5197 return -EACCES; 5198 } 5199 } 5200 continue_func: 5201 subprog_end = subprog[idx + 1].start; 5202 for (; i < subprog_end; i++) { 5203 int next_insn, sidx; 5204 5205 if (bpf_pseudo_kfunc_call(insn + i) && !insn[i].off) { 5206 bool err = false; 5207 5208 if (!bpf_is_throw_kfunc(insn + i)) 5209 continue; 5210 for (tmp = idx; tmp >= 0 && !err; tmp = dinfo[tmp].caller) { 5211 if (subprog[tmp].is_cb) { 5212 err = true; 5213 break; 5214 } 5215 } 5216 if (!err) 5217 continue; 5218 verbose(env, 5219 "bpf_throw kfunc (insn %d) cannot be called from callback subprog %d\n", 5220 i, idx); 5221 return -EINVAL; 5222 } 5223 5224 if (!bpf_pseudo_call(insn + i) && !bpf_pseudo_func(insn + i)) 5225 continue; 5226 /* remember insn and function to return to */ 5227 5228 /* find the callee */ 5229 next_insn = i + insn[i].imm + 1; 5230 sidx = bpf_find_subprog(env, next_insn); 5231 if (verifier_bug_if(sidx < 0, env, "callee not found at insn %d", next_insn)) 5232 return -EFAULT; 5233 if (subprog[sidx].is_async_cb) { 5234 if (subprog[sidx].has_tail_call) { 5235 verifier_bug(env, "subprog has tail_call and async cb"); 5236 return -EFAULT; 5237 } 5238 /* async callbacks don't increase bpf prog stack size unless called directly */ 5239 if (!bpf_pseudo_call(insn + i)) 5240 continue; 5241 if (subprog[sidx].is_exception_cb) { 5242 verbose(env, "insn %d cannot call exception cb directly", i); 5243 return -EINVAL; 5244 } 5245 } 5246 5247 /* store caller info for after we return from callee */ 5248 dinfo[idx].frame = frame; 5249 dinfo[idx].ret_insn = i + 1; 5250 5251 /* push caller idx into callee's dinfo */ 5252 dinfo[sidx].caller = idx; 5253 5254 i = next_insn; 5255 5256 idx = sidx; 5257 if (!priv_stack_supported) 5258 subprog[idx].priv_stack_mode = NO_PRIV_STACK; 5259 5260 if (subprog[idx].has_tail_call) 5261 tail_call_reachable = true; 5262 5263 frame = bpf_subprog_is_global(env, idx) ? 0 : frame + 1; 5264 if (frame >= MAX_CALL_FRAMES) { 5265 verbose(env, "the call stack of %d frames is too deep !\n", 5266 frame); 5267 return -E2BIG; 5268 } 5269 goto process_func; 5270 } 5271 /* if tail call got detected across bpf2bpf calls then mark each of the 5272 * currently present subprog frames as tail call reachable subprogs; 5273 * this info will be utilized by JIT so that we will be preserving the 5274 * tail call counter throughout bpf2bpf calls combined with tailcalls 5275 */ 5276 if (tail_call_reachable) { 5277 for (tmp = idx; tmp >= 0; tmp = dinfo[tmp].caller) { 5278 if (subprog[tmp].is_exception_cb) { 5279 verbose(env, "cannot tail call within exception cb\n"); 5280 return -EINVAL; 5281 } 5282 if (subprog[tmp].stack_arg_cnt) { 5283 verbose(env, "tail_calls are not allowed in programs with stack args\n"); 5284 return -EINVAL; 5285 } 5286 subprog[tmp].tail_call_reachable = true; 5287 } 5288 } else if (!idx && subprog[0].has_tail_call && subprog[0].stack_arg_cnt) { 5289 verbose(env, "tail_calls are not allowed in programs with stack args\n"); 5290 return -EINVAL; 5291 } 5292 5293 if (subprog[0].tail_call_reachable) 5294 env->prog->aux->tail_call_reachable = true; 5295 5296 /* end of for() loop means the last insn of the 'subprog' 5297 * was reached. Doesn't matter whether it was JA or EXIT 5298 */ 5299 if (frame == 0 && dinfo[idx].caller < 0) 5300 return 0; 5301 if (subprog[idx].priv_stack_mode != PRIV_STACK_ADAPTIVE) 5302 depth -= round_up_stack_depth(env, subprog[idx].stack_depth); 5303 5304 /* pop caller idx from callee */ 5305 idx = dinfo[idx].caller; 5306 5307 /* retrieve caller state from its frame */ 5308 frame = dinfo[idx].frame; 5309 i = dinfo[idx].ret_insn; 5310 5311 /* reset tail_call_reachable to the parent's actual state */ 5312 tail_call_reachable = subprog[idx].tail_call_reachable; 5313 5314 goto continue_func; 5315 } 5316 5317 static int check_max_stack_depth(struct bpf_verifier_env *env) 5318 { 5319 enum priv_stack_mode priv_stack_mode = PRIV_STACK_UNKNOWN; 5320 struct bpf_subprog_call_depth_info *dinfo; 5321 struct bpf_subprog_info *si = env->subprog_info; 5322 bool priv_stack_supported; 5323 int ret; 5324 5325 dinfo = kvcalloc(env->subprog_cnt, sizeof(*dinfo), GFP_KERNEL_ACCOUNT); 5326 if (!dinfo) 5327 return -ENOMEM; 5328 5329 for (int i = 0; i < env->subprog_cnt; i++) { 5330 if (si[i].has_tail_call) { 5331 priv_stack_mode = NO_PRIV_STACK; 5332 break; 5333 } 5334 } 5335 5336 if (priv_stack_mode == PRIV_STACK_UNKNOWN) 5337 priv_stack_mode = bpf_enable_priv_stack(env->prog); 5338 5339 /* All async_cb subprogs use normal kernel stack. If a particular 5340 * subprog appears in both main prog and async_cb subtree, that 5341 * subprog will use normal kernel stack to avoid potential nesting. 5342 * The reverse subprog traversal ensures when main prog subtree is 5343 * checked, the subprogs appearing in async_cb subtrees are already 5344 * marked as using normal kernel stack, so stack size checking can 5345 * be done properly. 5346 */ 5347 for (int i = env->subprog_cnt - 1; i >= 0; i--) { 5348 if (!i || si[i].is_async_cb) { 5349 priv_stack_supported = !i && priv_stack_mode == PRIV_STACK_ADAPTIVE; 5350 ret = check_max_stack_depth_subprog(env, i, dinfo, 5351 priv_stack_supported); 5352 if (ret < 0) { 5353 kvfree(dinfo); 5354 return ret; 5355 } 5356 } 5357 } 5358 5359 for (int i = 0; i < env->subprog_cnt; i++) { 5360 if (si[i].priv_stack_mode == PRIV_STACK_ADAPTIVE) { 5361 env->prog->aux->jits_use_priv_stack = true; 5362 break; 5363 } 5364 } 5365 5366 kvfree(dinfo); 5367 5368 return 0; 5369 } 5370 5371 static int __check_buffer_access(struct bpf_verifier_env *env, 5372 const char *buf_info, 5373 const struct bpf_reg_state *reg, 5374 argno_t argno, int off, int size) 5375 { 5376 if (off < 0) { 5377 verbose(env, 5378 "%s invalid %s buffer access: off=%d, size=%d\n", 5379 reg_arg_name(env, argno), buf_info, off, size); 5380 return -EACCES; 5381 } 5382 if (!tnum_is_const(reg->var_off)) { 5383 char tn_buf[48]; 5384 5385 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 5386 verbose(env, 5387 "%s invalid variable buffer offset: off=%d, var_off=%s\n", 5388 reg_arg_name(env, argno), off, tn_buf); 5389 return -EACCES; 5390 } 5391 5392 return 0; 5393 } 5394 5395 static int check_tp_buffer_access(struct bpf_verifier_env *env, 5396 const struct bpf_reg_state *reg, 5397 argno_t argno, int off, int size) 5398 { 5399 int err; 5400 5401 err = __check_buffer_access(env, "tracepoint", reg, argno, off, size); 5402 if (err) 5403 return err; 5404 5405 env->prog->aux->max_tp_access = max(reg->var_off.value + off + size, 5406 env->prog->aux->max_tp_access); 5407 5408 return 0; 5409 } 5410 5411 static int check_buffer_access(struct bpf_verifier_env *env, 5412 const struct bpf_reg_state *reg, 5413 argno_t argno, int off, int size, 5414 bool zero_size_allowed, 5415 u32 *max_access) 5416 { 5417 const char *buf_info = type_is_rdonly_mem(reg->type) ? "rdonly" : "rdwr"; 5418 int err; 5419 5420 err = __check_buffer_access(env, buf_info, reg, argno, off, size); 5421 if (err) 5422 return err; 5423 5424 *max_access = max(reg->var_off.value + off + size, *max_access); 5425 5426 return 0; 5427 } 5428 5429 /* BPF architecture zero extends alu32 ops into 64-bit registesr */ 5430 static void zext_32_to_64(struct bpf_reg_state *reg) 5431 { 5432 reg->var_off = tnum_subreg(reg->var_off); 5433 reg_set_urange64(reg, reg_u32_min(reg), reg_u32_max(reg)); 5434 } 5435 5436 /* truncate register to smaller size (in bytes) 5437 * must be called with size < BPF_REG_SIZE 5438 */ 5439 static void coerce_reg_to_size(struct bpf_reg_state *reg, int size) 5440 { 5441 u64 mask; 5442 5443 /* clear high bits in bit representation */ 5444 reg->var_off = tnum_cast(reg->var_off, size); 5445 5446 /* fix arithmetic bounds */ 5447 mask = ((u64)1 << (size * 8)) - 1; 5448 if ((reg_umin(reg) & ~mask) == (reg_umax(reg) & ~mask)) 5449 reg_set_urange64(reg, reg_umin(reg) & mask, reg_umax(reg) & mask); 5450 else 5451 reg_set_urange64(reg, 0, mask); 5452 5453 /* If size is smaller than 32bit register the 32bit register 5454 * values are also truncated so we push 64-bit bounds into 5455 * 32-bit bounds. Above were truncated < 32-bits already. 5456 */ 5457 if (size < 4) 5458 __mark_reg32_unbounded(reg); 5459 5460 reg_bounds_sync(reg); 5461 } 5462 5463 static void set_sext64_default_val(struct bpf_reg_state *reg, int size) 5464 { 5465 if (size == 1) { 5466 reg_set_srange64(reg, S8_MIN, S8_MAX); 5467 reg_set_srange32(reg, S8_MIN, S8_MAX); 5468 } else if (size == 2) { 5469 reg_set_srange64(reg, S16_MIN, S16_MAX); 5470 reg_set_srange32(reg, S16_MIN, S16_MAX); 5471 } else { 5472 /* size == 4 */ 5473 reg_set_srange64(reg, S32_MIN, S32_MAX); 5474 reg_set_srange32(reg, S32_MIN, S32_MAX); 5475 } 5476 reg->var_off = tnum_unknown; 5477 } 5478 5479 static void coerce_reg_to_size_sx(struct bpf_reg_state *reg, int size) 5480 { 5481 s64 init_s64_max, init_s64_min, s64_max, s64_min, u64_cval; 5482 u64 top_smax_value, top_smin_value; 5483 u64 num_bits = size * 8; 5484 5485 if (tnum_is_const(reg->var_off)) { 5486 u64_cval = reg->var_off.value; 5487 if (size == 1) 5488 reg->var_off = tnum_const((s8)u64_cval); 5489 else if (size == 2) 5490 reg->var_off = tnum_const((s16)u64_cval); 5491 else 5492 /* size == 4 */ 5493 reg->var_off = tnum_const((s32)u64_cval); 5494 5495 u64_cval = reg->var_off.value; 5496 reg->r64 = cnum64_from_urange(u64_cval, u64_cval); 5497 reg->r32 = cnum32_from_urange((u32)u64_cval, (u32)u64_cval); 5498 return; 5499 } 5500 5501 top_smax_value = ((u64)reg_smax(reg) >> num_bits) << num_bits; 5502 top_smin_value = ((u64)reg_smin(reg) >> num_bits) << num_bits; 5503 5504 if (top_smax_value != top_smin_value) 5505 goto out; 5506 5507 /* find the s64_min and s64_min after sign extension */ 5508 if (size == 1) { 5509 init_s64_max = (s8)reg_smax(reg); 5510 init_s64_min = (s8)reg_smin(reg); 5511 } else if (size == 2) { 5512 init_s64_max = (s16)reg_smax(reg); 5513 init_s64_min = (s16)reg_smin(reg); 5514 } else { 5515 init_s64_max = (s32)reg_smax(reg); 5516 init_s64_min = (s32)reg_smin(reg); 5517 } 5518 5519 s64_max = max(init_s64_max, init_s64_min); 5520 s64_min = min(init_s64_max, init_s64_min); 5521 5522 /* both of s64_max/s64_min positive or negative */ 5523 if ((s64_max >= 0) == (s64_min >= 0)) { 5524 reg_set_srange64(reg, s64_min, s64_max); 5525 reg_set_srange32(reg, s64_min, s64_max); 5526 reg->var_off = tnum_range(s64_min, s64_max); 5527 return; 5528 } 5529 5530 out: 5531 set_sext64_default_val(reg, size); 5532 } 5533 5534 static void set_sext32_default_val(struct bpf_reg_state *reg, int size) 5535 { 5536 if (size == 1) 5537 reg_set_srange32(reg, S8_MIN, S8_MAX); 5538 else 5539 /* size == 2 */ 5540 reg_set_srange32(reg, S16_MIN, S16_MAX); 5541 reg->var_off = tnum_subreg(tnum_unknown); 5542 } 5543 5544 static void coerce_subreg_to_size_sx(struct bpf_reg_state *reg, int size) 5545 { 5546 s32 init_s32_max, init_s32_min, s32_max, s32_min, u32_val; 5547 u32 top_smax_value, top_smin_value; 5548 u32 num_bits = size * 8; 5549 5550 if (tnum_is_const(reg->var_off)) { 5551 u32_val = reg->var_off.value; 5552 if (size == 1) 5553 reg->var_off = tnum_const((s8)u32_val); 5554 else 5555 reg->var_off = tnum_const((s16)u32_val); 5556 5557 u32_val = reg->var_off.value; 5558 reg_set_srange32(reg, u32_val, u32_val); 5559 return; 5560 } 5561 5562 top_smax_value = ((u32)reg_s32_max(reg) >> num_bits) << num_bits; 5563 top_smin_value = ((u32)reg_s32_min(reg) >> num_bits) << num_bits; 5564 5565 if (top_smax_value != top_smin_value) 5566 goto out; 5567 5568 /* find the s32_min and s32_min after sign extension */ 5569 if (size == 1) { 5570 init_s32_max = (s8)reg_s32_max(reg); 5571 init_s32_min = (s8)reg_s32_min(reg); 5572 } else { 5573 /* size == 2 */ 5574 init_s32_max = (s16)reg_s32_max(reg); 5575 init_s32_min = (s16)reg_s32_min(reg); 5576 } 5577 s32_max = max(init_s32_max, init_s32_min); 5578 s32_min = min(init_s32_max, init_s32_min); 5579 5580 if ((s32_min >= 0) == (s32_max >= 0)) { 5581 reg_set_srange32(reg, s32_min, s32_max); 5582 reg->var_off = tnum_subreg(tnum_range(s32_min, s32_max)); 5583 return; 5584 } 5585 5586 out: 5587 set_sext32_default_val(reg, size); 5588 } 5589 5590 bool bpf_map_is_rdonly(const struct bpf_map *map) 5591 { 5592 /* A map is considered read-only if the following condition are true: 5593 * 5594 * 1) BPF program side cannot change any of the map content. The 5595 * BPF_F_RDONLY_PROG flag is throughout the lifetime of a map 5596 * and was set at map creation time. 5597 * 2) The map value(s) have been initialized from user space by a 5598 * loader and then "frozen", such that no new map update/delete 5599 * operations from syscall side are possible for the rest of 5600 * the map's lifetime from that point onwards. 5601 * 3) Any parallel/pending map update/delete operations from syscall 5602 * side have been completed. Only after that point, it's safe to 5603 * assume that map value(s) are immutable. 5604 */ 5605 return (map->map_flags & BPF_F_RDONLY_PROG) && 5606 READ_ONCE(map->frozen) && 5607 !bpf_map_write_active(map); 5608 } 5609 5610 int bpf_map_direct_read(struct bpf_map *map, int off, int size, u64 *val, 5611 bool is_ldsx) 5612 { 5613 void *ptr; 5614 u64 addr; 5615 int err; 5616 5617 err = map->ops->map_direct_value_addr(map, &addr, off); 5618 if (err) 5619 return err; 5620 ptr = (void *)(long)addr + off; 5621 5622 switch (size) { 5623 case sizeof(u8): 5624 *val = is_ldsx ? (s64)*(s8 *)ptr : (u64)*(u8 *)ptr; 5625 break; 5626 case sizeof(u16): 5627 *val = is_ldsx ? (s64)*(s16 *)ptr : (u64)*(u16 *)ptr; 5628 break; 5629 case sizeof(u32): 5630 *val = is_ldsx ? (s64)*(s32 *)ptr : (u64)*(u32 *)ptr; 5631 break; 5632 case sizeof(u64): 5633 *val = *(u64 *)ptr; 5634 break; 5635 default: 5636 return -EINVAL; 5637 } 5638 return 0; 5639 } 5640 5641 #define BTF_TYPE_SAFE_RCU(__type) __PASTE(__type, __safe_rcu) 5642 #define BTF_TYPE_SAFE_RCU_OR_NULL(__type) __PASTE(__type, __safe_rcu_or_null) 5643 #define BTF_TYPE_SAFE_TRUSTED(__type) __PASTE(__type, __safe_trusted) 5644 #define BTF_TYPE_SAFE_TRUSTED_OR_NULL(__type) __PASTE(__type, __safe_trusted_or_null) 5645 5646 /* 5647 * Allow list few fields as RCU trusted or full trusted. 5648 * This logic doesn't allow mix tagging and will be removed once GCC supports 5649 * btf_type_tag. 5650 */ 5651 5652 /* RCU trusted: these fields are trusted in RCU CS and never NULL */ 5653 BTF_TYPE_SAFE_RCU(struct task_struct) { 5654 const cpumask_t *cpus_ptr; 5655 struct css_set __rcu *cgroups; 5656 struct task_struct __rcu *real_parent; 5657 struct task_struct *group_leader; 5658 }; 5659 5660 BTF_TYPE_SAFE_RCU(struct cgroup) { 5661 /* cgrp->kn is always accessible as documented in kernel/cgroup/cgroup.c */ 5662 struct kernfs_node *kn; 5663 }; 5664 5665 BTF_TYPE_SAFE_RCU(struct css_set) { 5666 struct cgroup *dfl_cgrp; 5667 }; 5668 5669 BTF_TYPE_SAFE_RCU(struct cgroup_subsys_state) { 5670 struct cgroup *cgroup; 5671 }; 5672 5673 /* RCU trusted: these fields are trusted in RCU CS and can be NULL */ 5674 BTF_TYPE_SAFE_RCU_OR_NULL(struct mm_struct) { 5675 struct file __rcu *exe_file; 5676 #ifdef CONFIG_MEMCG 5677 struct task_struct __rcu *owner; 5678 #endif 5679 }; 5680 5681 /* skb->sk, req->sk are not RCU protected, but we mark them as such 5682 * because bpf prog accessible sockets are SOCK_RCU_FREE. 5683 */ 5684 BTF_TYPE_SAFE_RCU_OR_NULL(struct sk_buff) { 5685 struct sock *sk; 5686 }; 5687 5688 BTF_TYPE_SAFE_RCU_OR_NULL(struct request_sock) { 5689 struct sock *sk; 5690 }; 5691 5692 /* full trusted: these fields are trusted even outside of RCU CS and never NULL */ 5693 BTF_TYPE_SAFE_TRUSTED(struct bpf_iter_meta) { 5694 struct seq_file *seq; 5695 }; 5696 5697 BTF_TYPE_SAFE_TRUSTED(struct bpf_iter__task) { 5698 struct bpf_iter_meta *meta; 5699 struct task_struct *task; 5700 }; 5701 5702 BTF_TYPE_SAFE_TRUSTED(struct linux_binprm) { 5703 struct file *file; 5704 }; 5705 5706 BTF_TYPE_SAFE_TRUSTED(struct file) { 5707 struct inode *f_inode; 5708 }; 5709 5710 BTF_TYPE_SAFE_TRUSTED_OR_NULL(struct dentry) { 5711 struct inode *d_inode; 5712 }; 5713 5714 BTF_TYPE_SAFE_TRUSTED_OR_NULL(struct socket) { 5715 struct sock *sk; 5716 }; 5717 5718 BTF_TYPE_SAFE_TRUSTED_OR_NULL(struct vm_area_struct) { 5719 struct mm_struct *vm_mm; 5720 struct file *vm_file; 5721 }; 5722 5723 static bool type_is_rcu(struct bpf_verifier_env *env, 5724 struct bpf_reg_state *reg, 5725 const char *field_name, u32 btf_id) 5726 { 5727 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct task_struct)); 5728 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct cgroup)); 5729 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct css_set)); 5730 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct cgroup_subsys_state)); 5731 5732 return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_rcu"); 5733 } 5734 5735 static bool type_is_rcu_or_null(struct bpf_verifier_env *env, 5736 struct bpf_reg_state *reg, 5737 const char *field_name, u32 btf_id) 5738 { 5739 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct mm_struct)); 5740 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct sk_buff)); 5741 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct request_sock)); 5742 5743 return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_rcu_or_null"); 5744 } 5745 5746 static bool type_is_trusted(struct bpf_verifier_env *env, 5747 struct bpf_reg_state *reg, 5748 const char *field_name, u32 btf_id) 5749 { 5750 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct bpf_iter_meta)); 5751 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct bpf_iter__task)); 5752 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct linux_binprm)); 5753 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct file)); 5754 5755 return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_trusted"); 5756 } 5757 5758 static bool type_is_trusted_or_null(struct bpf_verifier_env *env, 5759 struct bpf_reg_state *reg, 5760 const char *field_name, u32 btf_id) 5761 { 5762 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED_OR_NULL(struct socket)); 5763 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED_OR_NULL(struct dentry)); 5764 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED_OR_NULL(struct vm_area_struct)); 5765 5766 return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, 5767 "__safe_trusted_or_null"); 5768 } 5769 5770 static int check_ptr_to_btf_access(struct bpf_verifier_env *env, 5771 struct bpf_reg_state *regs, struct bpf_reg_state *reg, 5772 argno_t argno, int off, int size, 5773 enum bpf_access_type atype, 5774 int value_regno) 5775 { 5776 const struct btf_type *t = btf_type_by_id(reg->btf, reg->btf_id); 5777 const char *tname = btf_name_by_offset(reg->btf, t->name_off); 5778 const char *field_name = NULL; 5779 enum bpf_type_flag flag = 0; 5780 u32 btf_id = 0; 5781 int ret; 5782 5783 if (!env->allow_ptr_leaks) { 5784 verbose(env, 5785 "'struct %s' access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n", 5786 tname); 5787 return -EPERM; 5788 } 5789 if (!env->prog->gpl_compatible && btf_is_kernel(reg->btf)) { 5790 verbose(env, 5791 "Cannot access kernel 'struct %s' from non-GPL compatible program\n", 5792 tname); 5793 return -EINVAL; 5794 } 5795 5796 if (!tnum_is_const(reg->var_off)) { 5797 char tn_buf[48]; 5798 5799 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 5800 verbose(env, 5801 "%s is ptr_%s invalid variable offset: off=%d, var_off=%s\n", 5802 reg_arg_name(env, argno), tname, off, tn_buf); 5803 return -EACCES; 5804 } 5805 5806 off += reg->var_off.value; 5807 5808 if (off < 0) { 5809 verbose(env, 5810 "%s is ptr_%s invalid negative access: off=%d\n", 5811 reg_arg_name(env, argno), tname, off); 5812 return -EACCES; 5813 } 5814 5815 if (reg->type & MEM_USER) { 5816 verbose(env, 5817 "%s is ptr_%s access user memory: off=%d\n", 5818 reg_arg_name(env, argno), tname, off); 5819 return -EACCES; 5820 } 5821 5822 if (reg->type & MEM_PERCPU) { 5823 verbose(env, 5824 "%s is ptr_%s access percpu memory: off=%d\n", 5825 reg_arg_name(env, argno), tname, off); 5826 return -EACCES; 5827 } 5828 5829 if (env->ops->btf_struct_access && !type_is_alloc(reg->type) && atype == BPF_WRITE) { 5830 if (!btf_is_kernel(reg->btf)) { 5831 verifier_bug(env, "reg->btf must be kernel btf"); 5832 return -EFAULT; 5833 } 5834 ret = env->ops->btf_struct_access(&env->log, reg, off, size); 5835 } else { 5836 /* Writes are permitted with default btf_struct_access for 5837 * program allocated objects (which always have ref_obj_id > 0), 5838 * but not for untrusted PTR_TO_BTF_ID | MEM_ALLOC. 5839 */ 5840 if (atype != BPF_READ && !type_is_ptr_alloc_obj(reg->type)) { 5841 verbose(env, "only read is supported\n"); 5842 return -EACCES; 5843 } 5844 5845 if (type_is_alloc(reg->type) && !type_is_non_owning_ref(reg->type) && 5846 !(reg->type & MEM_RCU) && !reg->ref_obj_id) { 5847 verifier_bug(env, "ref_obj_id for allocated object must be non-zero"); 5848 return -EFAULT; 5849 } 5850 5851 ret = btf_struct_access(&env->log, reg, off, size, atype, &btf_id, &flag, &field_name); 5852 } 5853 5854 if (ret < 0) 5855 return ret; 5856 5857 if (ret != PTR_TO_BTF_ID) { 5858 /* just mark; */ 5859 5860 } else if (type_flag(reg->type) & PTR_UNTRUSTED) { 5861 /* If this is an untrusted pointer, all pointers formed by walking it 5862 * also inherit the untrusted flag. 5863 */ 5864 flag = PTR_UNTRUSTED; 5865 5866 } else if (is_trusted_reg(reg) || is_rcu_reg(reg)) { 5867 /* By default any pointer obtained from walking a trusted pointer is no 5868 * longer trusted, unless the field being accessed has explicitly been 5869 * marked as inheriting its parent's state of trust (either full or RCU). 5870 * For example: 5871 * 'cgroups' pointer is untrusted if task->cgroups dereference 5872 * happened in a sleepable program outside of bpf_rcu_read_lock() 5873 * section. In a non-sleepable program it's trusted while in RCU CS (aka MEM_RCU). 5874 * Note bpf_rcu_read_unlock() converts MEM_RCU pointers to PTR_UNTRUSTED. 5875 * 5876 * A regular RCU-protected pointer with __rcu tag can also be deemed 5877 * trusted if we are in an RCU CS. Such pointer can be NULL. 5878 */ 5879 if (type_is_trusted(env, reg, field_name, btf_id)) { 5880 flag |= PTR_TRUSTED; 5881 } else if (type_is_trusted_or_null(env, reg, field_name, btf_id)) { 5882 flag |= PTR_TRUSTED | PTR_MAYBE_NULL; 5883 } else if (in_rcu_cs(env) && !type_may_be_null(reg->type)) { 5884 if (type_is_rcu(env, reg, field_name, btf_id)) { 5885 /* ignore __rcu tag and mark it MEM_RCU */ 5886 flag |= MEM_RCU; 5887 } else if (flag & MEM_RCU || 5888 type_is_rcu_or_null(env, reg, field_name, btf_id)) { 5889 /* __rcu tagged pointers can be NULL */ 5890 flag |= MEM_RCU | PTR_MAYBE_NULL; 5891 5892 /* We always trust them */ 5893 if (type_is_rcu_or_null(env, reg, field_name, btf_id) && 5894 flag & PTR_UNTRUSTED) 5895 flag &= ~PTR_UNTRUSTED; 5896 } else if (flag & (MEM_PERCPU | MEM_USER)) { 5897 /* keep as-is */ 5898 } else { 5899 /* walking unknown pointers yields old deprecated PTR_TO_BTF_ID */ 5900 clear_trusted_flags(&flag); 5901 } 5902 } else { 5903 /* 5904 * If not in RCU CS or MEM_RCU pointer can be NULL then 5905 * aggressively mark as untrusted otherwise such 5906 * pointers will be plain PTR_TO_BTF_ID without flags 5907 * and will be allowed to be passed into helpers for 5908 * compat reasons. 5909 */ 5910 flag = PTR_UNTRUSTED; 5911 } 5912 } else { 5913 /* Old compat. Deprecated */ 5914 clear_trusted_flags(&flag); 5915 } 5916 5917 if (atype == BPF_READ && value_regno >= 0) { 5918 ret = mark_btf_ld_reg(env, regs, value_regno, ret, reg->btf, btf_id, flag); 5919 if (ret < 0) 5920 return ret; 5921 } 5922 5923 return 0; 5924 } 5925 5926 static int check_ptr_to_map_access(struct bpf_verifier_env *env, 5927 struct bpf_reg_state *regs, struct bpf_reg_state *reg, 5928 argno_t argno, int off, int size, 5929 enum bpf_access_type atype, 5930 int value_regno) 5931 { 5932 struct bpf_map *map = reg->map_ptr; 5933 struct bpf_reg_state map_reg; 5934 enum bpf_type_flag flag = 0; 5935 const struct btf_type *t; 5936 const char *tname; 5937 u32 btf_id; 5938 int ret; 5939 5940 if (!btf_vmlinux) { 5941 verbose(env, "map_ptr access not supported without CONFIG_DEBUG_INFO_BTF\n"); 5942 return -ENOTSUPP; 5943 } 5944 5945 if (!map->ops->map_btf_id || !*map->ops->map_btf_id) { 5946 verbose(env, "map_ptr access not supported for map type %d\n", 5947 map->map_type); 5948 return -ENOTSUPP; 5949 } 5950 5951 t = btf_type_by_id(btf_vmlinux, *map->ops->map_btf_id); 5952 tname = btf_name_by_offset(btf_vmlinux, t->name_off); 5953 5954 if (!env->allow_ptr_leaks) { 5955 verbose(env, 5956 "'struct %s' access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n", 5957 tname); 5958 return -EPERM; 5959 } 5960 5961 if (off < 0) { 5962 verbose(env, "%s is %s invalid negative access: off=%d\n", 5963 reg_arg_name(env, argno), tname, off); 5964 return -EACCES; 5965 } 5966 5967 if (atype != BPF_READ) { 5968 verbose(env, "only read from %s is supported\n", tname); 5969 return -EACCES; 5970 } 5971 5972 /* Simulate access to a PTR_TO_BTF_ID */ 5973 memset(&map_reg, 0, sizeof(map_reg)); 5974 ret = mark_btf_ld_reg(env, &map_reg, 0, PTR_TO_BTF_ID, 5975 btf_vmlinux, *map->ops->map_btf_id, 0); 5976 if (ret < 0) 5977 return ret; 5978 ret = btf_struct_access(&env->log, &map_reg, off, size, atype, &btf_id, &flag, NULL); 5979 if (ret < 0) 5980 return ret; 5981 5982 if (value_regno >= 0) { 5983 ret = mark_btf_ld_reg(env, regs, value_regno, ret, btf_vmlinux, btf_id, flag); 5984 if (ret < 0) 5985 return ret; 5986 } 5987 5988 return 0; 5989 } 5990 5991 /* Check that the stack access at the given offset is within bounds. The 5992 * maximum valid offset is -1. 5993 * 5994 * The minimum valid offset is -MAX_BPF_STACK for writes, and 5995 * -state->allocated_stack for reads. 5996 */ 5997 static int check_stack_slot_within_bounds(struct bpf_verifier_env *env, 5998 s64 off, 5999 struct bpf_func_state *state, 6000 enum bpf_access_type t) 6001 { 6002 int min_valid_off; 6003 6004 if (t == BPF_WRITE || env->allow_uninit_stack) 6005 min_valid_off = -MAX_BPF_STACK; 6006 else 6007 min_valid_off = -state->allocated_stack; 6008 6009 if (off < min_valid_off || off > -1) 6010 return -EACCES; 6011 return 0; 6012 } 6013 6014 /* Check that the stack access at 'regno + off' falls within the maximum stack 6015 * bounds. 6016 * 6017 * 'off' includes `regno->offset`, but not its dynamic part (if any). 6018 */ 6019 static int check_stack_access_within_bounds( 6020 struct bpf_verifier_env *env, struct bpf_reg_state *reg, 6021 argno_t argno, int off, int access_size, 6022 enum bpf_access_type type) 6023 { 6024 struct bpf_func_state *state = bpf_func(env, reg); 6025 s64 min_off, max_off; 6026 int err; 6027 char *err_extra; 6028 6029 if (type == BPF_READ) 6030 err_extra = " read from"; 6031 else 6032 err_extra = " write to"; 6033 6034 if (tnum_is_const(reg->var_off)) { 6035 min_off = (s64)reg->var_off.value + off; 6036 max_off = min_off + access_size; 6037 } else { 6038 if (reg_smax(reg) >= BPF_MAX_VAR_OFF || 6039 reg_smin(reg) <= -BPF_MAX_VAR_OFF) { 6040 verbose(env, "invalid unbounded variable-offset%s stack %s\n", 6041 err_extra, reg_arg_name(env, argno)); 6042 return -EACCES; 6043 } 6044 min_off = reg_smin(reg) + off; 6045 max_off = reg_smax(reg) + off + access_size; 6046 } 6047 6048 err = check_stack_slot_within_bounds(env, min_off, state, type); 6049 if (!err && max_off > 0) 6050 err = -EINVAL; /* out of stack access into non-negative offsets */ 6051 if (!err && access_size < 0) 6052 /* access_size should not be negative (or overflow an int); others checks 6053 * along the way should have prevented such an access. 6054 */ 6055 err = -EFAULT; /* invalid negative access size; integer overflow? */ 6056 6057 if (err) { 6058 if (tnum_is_const(reg->var_off)) { 6059 verbose(env, "invalid%s stack %s off=%lld size=%d\n", 6060 err_extra, reg_arg_name(env, argno), min_off, access_size); 6061 } else { 6062 char tn_buf[48]; 6063 6064 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 6065 verbose(env, "invalid variable-offset%s stack %s var_off=%s off=%d size=%d\n", 6066 err_extra, reg_arg_name(env, argno), tn_buf, off, access_size); 6067 } 6068 return err; 6069 } 6070 6071 /* Note that there is no stack access with offset zero, so the needed stack 6072 * size is -min_off, not -min_off+1. 6073 */ 6074 return grow_stack_state(env, state, -min_off /* size */); 6075 } 6076 6077 static bool get_func_retval_range(struct bpf_prog *prog, 6078 struct bpf_retval_range *range) 6079 { 6080 if (prog->type == BPF_PROG_TYPE_LSM && 6081 prog->expected_attach_type == BPF_LSM_MAC && 6082 !bpf_lsm_get_retval_range(prog, range)) { 6083 return true; 6084 } 6085 return false; 6086 } 6087 6088 static void add_scalar_to_reg(struct bpf_reg_state *dst_reg, s64 val) 6089 { 6090 struct bpf_reg_state fake_reg; 6091 6092 if (!val) 6093 return; 6094 6095 fake_reg.type = SCALAR_VALUE; 6096 __mark_reg_known(&fake_reg, val); 6097 6098 scalar32_min_max_add(dst_reg, &fake_reg); 6099 scalar_min_max_add(dst_reg, &fake_reg); 6100 dst_reg->var_off = tnum_add(dst_reg->var_off, fake_reg.var_off); 6101 6102 reg_bounds_sync(dst_reg); 6103 } 6104 6105 /* check whether memory at (regno + off) is accessible for t = (read | write) 6106 * if t==write, value_regno is a register which value is stored into memory 6107 * if t==read, value_regno is a register which will receive the value from memory 6108 * if t==write && value_regno==-1, some unknown value is stored into memory 6109 * if t==read && value_regno==-1, don't care what we read from memory 6110 */ 6111 static int check_mem_access(struct bpf_verifier_env *env, int insn_idx, struct bpf_reg_state *reg, argno_t argno, 6112 int off, int bpf_size, enum bpf_access_type t, 6113 int value_regno, bool strict_alignment_once, bool is_ldsx) 6114 { 6115 struct bpf_reg_state *regs = cur_regs(env); 6116 int size, err = 0; 6117 6118 size = bpf_size_to_bytes(bpf_size); 6119 if (size < 0) 6120 return size; 6121 6122 err = check_ptr_alignment(env, reg, off, size, strict_alignment_once); 6123 if (err) 6124 return err; 6125 6126 if (reg->type == PTR_TO_MAP_KEY) { 6127 if (t == BPF_WRITE) { 6128 verbose(env, "write to change key %s not allowed\n", 6129 reg_arg_name(env, argno)); 6130 return -EACCES; 6131 } 6132 6133 err = check_mem_region_access(env, reg, argno, off, size, 6134 reg->map_ptr->key_size, false); 6135 if (err) 6136 return err; 6137 if (value_regno >= 0) 6138 mark_reg_unknown(env, regs, value_regno); 6139 } else if (reg->type == PTR_TO_MAP_VALUE) { 6140 struct btf_field *kptr_field = NULL; 6141 6142 if (t == BPF_WRITE && value_regno >= 0 && 6143 is_pointer_value(env, value_regno)) { 6144 verbose(env, "R%d leaks addr into map\n", value_regno); 6145 return -EACCES; 6146 } 6147 err = check_map_access_type(env, reg, off, size, t); 6148 if (err) 6149 return err; 6150 err = check_map_access(env, reg, argno, off, size, false, ACCESS_DIRECT); 6151 if (err) 6152 return err; 6153 if (tnum_is_const(reg->var_off)) 6154 kptr_field = btf_record_find(reg->map_ptr->record, 6155 off + reg->var_off.value, BPF_KPTR | BPF_UPTR); 6156 if (kptr_field) { 6157 err = check_map_kptr_access(env, value_regno, insn_idx, kptr_field); 6158 } else if (t == BPF_READ && value_regno >= 0) { 6159 struct bpf_map *map = reg->map_ptr; 6160 6161 /* 6162 * If map is read-only, track its contents as scalars, 6163 * unless it is an insn array (see the special case below) 6164 */ 6165 if (tnum_is_const(reg->var_off) && 6166 bpf_map_is_rdonly(map) && 6167 map->ops->map_direct_value_addr && 6168 map->map_type != BPF_MAP_TYPE_INSN_ARRAY) { 6169 int map_off = off + reg->var_off.value; 6170 u64 val = 0; 6171 6172 err = bpf_map_direct_read(map, map_off, size, 6173 &val, is_ldsx); 6174 if (err) 6175 return err; 6176 6177 regs[value_regno].type = SCALAR_VALUE; 6178 __mark_reg_known(®s[value_regno], val); 6179 } else if (map->map_type == BPF_MAP_TYPE_INSN_ARRAY) { 6180 if (bpf_size != BPF_DW) { 6181 verbose(env, "Invalid read of %d bytes from insn_array\n", 6182 size); 6183 return -EACCES; 6184 } 6185 regs[value_regno] = *reg; 6186 add_scalar_to_reg(®s[value_regno], off); 6187 regs[value_regno].type = PTR_TO_INSN; 6188 } else { 6189 mark_reg_unknown(env, regs, value_regno); 6190 } 6191 } 6192 } else if (base_type(reg->type) == PTR_TO_MEM) { 6193 bool rdonly_mem = type_is_rdonly_mem(reg->type); 6194 bool rdonly_untrusted = rdonly_mem && (reg->type & PTR_UNTRUSTED); 6195 6196 if (type_may_be_null(reg->type)) { 6197 verbose(env, "%s invalid mem access '%s'\n", reg_arg_name(env, argno), 6198 reg_type_str(env, reg->type)); 6199 return -EACCES; 6200 } 6201 6202 if (t == BPF_WRITE && rdonly_mem) { 6203 verbose(env, "%s cannot write into %s\n", 6204 reg_arg_name(env, argno), reg_type_str(env, reg->type)); 6205 return -EACCES; 6206 } 6207 6208 if (t == BPF_WRITE && value_regno >= 0 && 6209 is_pointer_value(env, value_regno)) { 6210 verbose(env, "R%d leaks addr into mem\n", value_regno); 6211 return -EACCES; 6212 } 6213 6214 /* 6215 * Accesses to untrusted PTR_TO_MEM are done through probe 6216 * instructions, hence no need to check bounds in that case. 6217 */ 6218 if (!rdonly_untrusted) 6219 err = check_mem_region_access(env, reg, argno, off, size, 6220 reg->mem_size, false); 6221 if (!err && value_regno >= 0 && (t == BPF_READ || rdonly_mem)) 6222 mark_reg_unknown(env, regs, value_regno); 6223 } else if (reg->type == PTR_TO_CTX) { 6224 struct bpf_insn_access_aux info = { 6225 .reg_type = SCALAR_VALUE, 6226 .is_ldsx = is_ldsx, 6227 .log = &env->log, 6228 }; 6229 struct bpf_retval_range range; 6230 6231 if (t == BPF_WRITE && value_regno >= 0 && 6232 is_pointer_value(env, value_regno)) { 6233 verbose(env, "R%d leaks addr into ctx\n", value_regno); 6234 return -EACCES; 6235 } 6236 6237 err = check_ctx_access(env, insn_idx, reg, argno, off, size, t, &info); 6238 if (!err && t == BPF_READ && value_regno >= 0) { 6239 /* ctx access returns either a scalar, or a 6240 * PTR_TO_PACKET[_META,_END]. In the latter 6241 * case, we know the offset is zero. 6242 */ 6243 if (info.reg_type == SCALAR_VALUE) { 6244 if (info.is_retval && get_func_retval_range(env->prog, &range)) { 6245 err = __mark_reg_s32_range(env, regs, value_regno, 6246 range.minval, range.maxval); 6247 if (err) 6248 return err; 6249 } else { 6250 mark_reg_unknown(env, regs, value_regno); 6251 } 6252 } else { 6253 mark_reg_known_zero(env, regs, 6254 value_regno); 6255 if (type_may_be_null(info.reg_type)) 6256 regs[value_regno].id = ++env->id_gen; 6257 /* A load of ctx field could have different 6258 * actual load size with the one encoded in the 6259 * insn. When the dst is PTR, it is for sure not 6260 * a sub-register. 6261 */ 6262 regs[value_regno].subreg_def = DEF_NOT_SUBREG; 6263 if (base_type(info.reg_type) == PTR_TO_BTF_ID) { 6264 regs[value_regno].btf = info.btf; 6265 regs[value_regno].btf_id = info.btf_id; 6266 regs[value_regno].ref_obj_id = info.ref_obj_id; 6267 } 6268 } 6269 regs[value_regno].type = info.reg_type; 6270 } 6271 6272 } else if (reg->type == PTR_TO_STACK) { 6273 /* Basic bounds checks. */ 6274 err = check_stack_access_within_bounds(env, reg, argno, off, size, t); 6275 if (err) 6276 return err; 6277 6278 if (t == BPF_READ) 6279 err = check_stack_read(env, reg, argno, off, size, 6280 value_regno); 6281 else 6282 err = check_stack_write(env, reg, off, size, 6283 value_regno, insn_idx); 6284 } else if (reg_is_pkt_pointer(reg)) { 6285 if (t == BPF_WRITE && !may_access_direct_pkt_data(env, NULL, t)) { 6286 verbose(env, "cannot write into packet\n"); 6287 return -EACCES; 6288 } 6289 if (t == BPF_WRITE && value_regno >= 0 && 6290 is_pointer_value(env, value_regno)) { 6291 verbose(env, "R%d leaks addr into packet\n", 6292 value_regno); 6293 return -EACCES; 6294 } 6295 err = check_packet_access(env, reg, argno, off, size, false); 6296 if (!err && t == BPF_READ && value_regno >= 0) 6297 mark_reg_unknown(env, regs, value_regno); 6298 } else if (reg->type == PTR_TO_FLOW_KEYS) { 6299 if (t == BPF_WRITE && value_regno >= 0 && 6300 is_pointer_value(env, value_regno)) { 6301 verbose(env, "R%d leaks addr into flow keys\n", 6302 value_regno); 6303 return -EACCES; 6304 } 6305 6306 err = check_flow_keys_access(env, off, size); 6307 if (!err && t == BPF_READ && value_regno >= 0) 6308 mark_reg_unknown(env, regs, value_regno); 6309 } else if (type_is_sk_pointer(reg->type)) { 6310 if (t == BPF_WRITE) { 6311 verbose(env, "%s cannot write into %s\n", 6312 reg_arg_name(env, argno), reg_type_str(env, reg->type)); 6313 return -EACCES; 6314 } 6315 err = check_sock_access(env, insn_idx, reg, argno, off, size, t); 6316 if (!err && value_regno >= 0) 6317 mark_reg_unknown(env, regs, value_regno); 6318 } else if (reg->type == PTR_TO_TP_BUFFER) { 6319 err = check_tp_buffer_access(env, reg, argno, off, size); 6320 if (!err && t == BPF_READ && value_regno >= 0) 6321 mark_reg_unknown(env, regs, value_regno); 6322 } else if (base_type(reg->type) == PTR_TO_BTF_ID && 6323 !type_may_be_null(reg->type)) { 6324 err = check_ptr_to_btf_access(env, regs, reg, argno, off, size, t, 6325 value_regno); 6326 } else if (reg->type == CONST_PTR_TO_MAP) { 6327 err = check_ptr_to_map_access(env, regs, reg, argno, off, size, t, 6328 value_regno); 6329 } else if (base_type(reg->type) == PTR_TO_BUF && 6330 !type_may_be_null(reg->type)) { 6331 bool rdonly_mem = type_is_rdonly_mem(reg->type); 6332 u32 *max_access; 6333 6334 if (rdonly_mem) { 6335 if (t == BPF_WRITE) { 6336 verbose(env, "%s cannot write into %s\n", 6337 reg_arg_name(env, argno), reg_type_str(env, reg->type)); 6338 return -EACCES; 6339 } 6340 max_access = &env->prog->aux->max_rdonly_access; 6341 } else { 6342 max_access = &env->prog->aux->max_rdwr_access; 6343 } 6344 6345 err = check_buffer_access(env, reg, argno, off, size, false, 6346 max_access); 6347 6348 if (!err && value_regno >= 0 && (rdonly_mem || t == BPF_READ)) 6349 mark_reg_unknown(env, regs, value_regno); 6350 } else if (reg->type == PTR_TO_ARENA) { 6351 if (t == BPF_READ && value_regno >= 0) 6352 mark_reg_unknown(env, regs, value_regno); 6353 } else { 6354 verbose(env, "%s invalid mem access '%s'\n", reg_arg_name(env, argno), 6355 reg_type_str(env, reg->type)); 6356 return -EACCES; 6357 } 6358 6359 if (!err && size < BPF_REG_SIZE && value_regno >= 0 && t == BPF_READ && 6360 regs[value_regno].type == SCALAR_VALUE) { 6361 if (!is_ldsx) 6362 /* b/h/w load zero-extends, mark upper bits as known 0 */ 6363 coerce_reg_to_size(®s[value_regno], size); 6364 else 6365 coerce_reg_to_size_sx(®s[value_regno], size); 6366 } 6367 return err; 6368 } 6369 6370 static int save_aux_ptr_type(struct bpf_verifier_env *env, enum bpf_reg_type type, 6371 bool allow_trust_mismatch); 6372 6373 static int check_load_mem(struct bpf_verifier_env *env, struct bpf_insn *insn, 6374 bool strict_alignment_once, bool is_ldsx, 6375 bool allow_trust_mismatch, const char *ctx) 6376 { 6377 struct bpf_verifier_state *vstate = env->cur_state; 6378 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 6379 struct bpf_reg_state *regs = cur_regs(env); 6380 enum bpf_reg_type src_reg_type; 6381 int err; 6382 6383 /* Handle stack arg read */ 6384 if (is_stack_arg_ldx(insn)) { 6385 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK); 6386 if (err) 6387 return err; 6388 return check_stack_arg_read(env, state, insn->off, insn->dst_reg); 6389 } 6390 6391 /* check src operand */ 6392 err = check_reg_arg(env, insn->src_reg, SRC_OP); 6393 if (err) 6394 return err; 6395 6396 /* check dst operand */ 6397 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK); 6398 if (err) 6399 return err; 6400 6401 src_reg_type = regs[insn->src_reg].type; 6402 6403 /* Check if (src_reg + off) is readable. The state of dst_reg will be 6404 * updated by this call. 6405 */ 6406 err = check_mem_access(env, env->insn_idx, regs + insn->src_reg, argno_from_reg(insn->src_reg), insn->off, 6407 BPF_SIZE(insn->code), BPF_READ, insn->dst_reg, 6408 strict_alignment_once, is_ldsx); 6409 err = err ?: save_aux_ptr_type(env, src_reg_type, 6410 allow_trust_mismatch); 6411 err = err ?: reg_bounds_sanity_check(env, ®s[insn->dst_reg], ctx); 6412 6413 return err; 6414 } 6415 6416 static int check_store_reg(struct bpf_verifier_env *env, struct bpf_insn *insn, 6417 bool strict_alignment_once) 6418 { 6419 struct bpf_verifier_state *vstate = env->cur_state; 6420 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 6421 struct bpf_reg_state *regs = cur_regs(env); 6422 enum bpf_reg_type dst_reg_type; 6423 int err; 6424 6425 /* Handle stack arg write */ 6426 if (is_stack_arg_stx(insn)) { 6427 err = check_reg_arg(env, insn->src_reg, SRC_OP); 6428 if (err) 6429 return err; 6430 return check_stack_arg_write(env, state, insn->off, regs + insn->src_reg); 6431 } 6432 6433 /* check src1 operand */ 6434 err = check_reg_arg(env, insn->src_reg, SRC_OP); 6435 if (err) 6436 return err; 6437 6438 /* check src2 operand */ 6439 err = check_reg_arg(env, insn->dst_reg, SRC_OP); 6440 if (err) 6441 return err; 6442 6443 dst_reg_type = regs[insn->dst_reg].type; 6444 6445 /* Check if (dst_reg + off) is writeable. */ 6446 err = check_mem_access(env, env->insn_idx, regs + insn->dst_reg, argno_from_reg(insn->dst_reg), insn->off, 6447 BPF_SIZE(insn->code), BPF_WRITE, insn->src_reg, 6448 strict_alignment_once, false); 6449 err = err ?: save_aux_ptr_type(env, dst_reg_type, false); 6450 6451 return err; 6452 } 6453 6454 static int check_atomic_rmw(struct bpf_verifier_env *env, 6455 struct bpf_insn *insn) 6456 { 6457 struct bpf_reg_state *dst_reg; 6458 int load_reg; 6459 int err; 6460 6461 if (BPF_SIZE(insn->code) != BPF_W && BPF_SIZE(insn->code) != BPF_DW) { 6462 verbose(env, "invalid atomic operand size\n"); 6463 return -EINVAL; 6464 } 6465 6466 /* check src1 operand */ 6467 err = check_reg_arg(env, insn->src_reg, SRC_OP); 6468 if (err) 6469 return err; 6470 6471 /* check src2 operand */ 6472 err = check_reg_arg(env, insn->dst_reg, SRC_OP); 6473 if (err) 6474 return err; 6475 6476 if (insn->imm == BPF_CMPXCHG) { 6477 /* Check comparison of R0 with memory location */ 6478 const u32 aux_reg = BPF_REG_0; 6479 6480 err = check_reg_arg(env, aux_reg, SRC_OP); 6481 if (err) 6482 return err; 6483 6484 if (is_pointer_value(env, aux_reg)) { 6485 verbose(env, "R%d leaks addr into mem\n", aux_reg); 6486 return -EACCES; 6487 } 6488 } 6489 6490 if (is_pointer_value(env, insn->src_reg)) { 6491 verbose(env, "R%d leaks addr into mem\n", insn->src_reg); 6492 return -EACCES; 6493 } 6494 6495 if (!atomic_ptr_type_ok(env, insn->dst_reg, insn)) { 6496 verbose(env, "BPF_ATOMIC stores into R%d %s is not allowed\n", 6497 insn->dst_reg, 6498 reg_type_str(env, reg_state(env, insn->dst_reg)->type)); 6499 return -EACCES; 6500 } 6501 6502 if (insn->imm & BPF_FETCH) { 6503 if (insn->imm == BPF_CMPXCHG) 6504 load_reg = BPF_REG_0; 6505 else 6506 load_reg = insn->src_reg; 6507 6508 /* check and record load of old value */ 6509 err = check_reg_arg(env, load_reg, DST_OP); 6510 if (err) 6511 return err; 6512 } else { 6513 /* This instruction accesses a memory location but doesn't 6514 * actually load it into a register. 6515 */ 6516 load_reg = -1; 6517 } 6518 6519 dst_reg = cur_regs(env) + insn->dst_reg; 6520 6521 /* Check whether we can read the memory, with second call for fetch 6522 * case to simulate the register fill. 6523 */ 6524 err = check_mem_access(env, env->insn_idx, dst_reg, argno_from_reg(insn->dst_reg), insn->off, 6525 BPF_SIZE(insn->code), BPF_READ, -1, true, false); 6526 if (!err && load_reg >= 0) 6527 err = check_mem_access(env, env->insn_idx, dst_reg, argno_from_reg(insn->dst_reg), 6528 insn->off, BPF_SIZE(insn->code), 6529 BPF_READ, load_reg, true, false); 6530 if (err) 6531 return err; 6532 6533 if (is_arena_reg(env, insn->dst_reg)) { 6534 err = save_aux_ptr_type(env, PTR_TO_ARENA, false); 6535 if (err) 6536 return err; 6537 } 6538 /* Check whether we can write into the same memory. */ 6539 err = check_mem_access(env, env->insn_idx, dst_reg, argno_from_reg(insn->dst_reg), insn->off, 6540 BPF_SIZE(insn->code), BPF_WRITE, -1, true, false); 6541 if (err) 6542 return err; 6543 return 0; 6544 } 6545 6546 static int check_atomic_load(struct bpf_verifier_env *env, 6547 struct bpf_insn *insn) 6548 { 6549 int err; 6550 6551 err = check_load_mem(env, insn, true, false, false, "atomic_load"); 6552 if (err) 6553 return err; 6554 6555 if (!atomic_ptr_type_ok(env, insn->src_reg, insn)) { 6556 verbose(env, "BPF_ATOMIC loads from R%d %s is not allowed\n", 6557 insn->src_reg, 6558 reg_type_str(env, reg_state(env, insn->src_reg)->type)); 6559 return -EACCES; 6560 } 6561 6562 return 0; 6563 } 6564 6565 static int check_atomic_store(struct bpf_verifier_env *env, 6566 struct bpf_insn *insn) 6567 { 6568 int err; 6569 6570 err = check_store_reg(env, insn, true); 6571 if (err) 6572 return err; 6573 6574 if (!atomic_ptr_type_ok(env, insn->dst_reg, insn)) { 6575 verbose(env, "BPF_ATOMIC stores into R%d %s is not allowed\n", 6576 insn->dst_reg, 6577 reg_type_str(env, reg_state(env, insn->dst_reg)->type)); 6578 return -EACCES; 6579 } 6580 6581 return 0; 6582 } 6583 6584 static int check_atomic(struct bpf_verifier_env *env, struct bpf_insn *insn) 6585 { 6586 switch (insn->imm) { 6587 case BPF_ADD: 6588 case BPF_ADD | BPF_FETCH: 6589 case BPF_AND: 6590 case BPF_AND | BPF_FETCH: 6591 case BPF_OR: 6592 case BPF_OR | BPF_FETCH: 6593 case BPF_XOR: 6594 case BPF_XOR | BPF_FETCH: 6595 case BPF_XCHG: 6596 case BPF_CMPXCHG: 6597 return check_atomic_rmw(env, insn); 6598 case BPF_LOAD_ACQ: 6599 if (BPF_SIZE(insn->code) == BPF_DW && BITS_PER_LONG != 64) { 6600 verbose(env, 6601 "64-bit load-acquires are only supported on 64-bit arches\n"); 6602 return -EOPNOTSUPP; 6603 } 6604 return check_atomic_load(env, insn); 6605 case BPF_STORE_REL: 6606 if (BPF_SIZE(insn->code) == BPF_DW && BITS_PER_LONG != 64) { 6607 verbose(env, 6608 "64-bit store-releases are only supported on 64-bit arches\n"); 6609 return -EOPNOTSUPP; 6610 } 6611 return check_atomic_store(env, insn); 6612 default: 6613 verbose(env, "BPF_ATOMIC uses invalid atomic opcode %02x\n", 6614 insn->imm); 6615 return -EINVAL; 6616 } 6617 } 6618 6619 /* When register 'regno' is used to read the stack (either directly or through 6620 * a helper function) make sure that it's within stack boundary and, depending 6621 * on the access type and privileges, that all elements of the stack are 6622 * initialized. 6623 * 6624 * All registers that have been spilled on the stack in the slots within the 6625 * read offsets are marked as read. 6626 */ 6627 static int check_stack_range_initialized( 6628 struct bpf_verifier_env *env, struct bpf_reg_state *reg, argno_t argno, int off, 6629 int access_size, bool zero_size_allowed, 6630 enum bpf_access_type type, struct bpf_call_arg_meta *meta) 6631 { 6632 struct bpf_func_state *state = bpf_func(env, reg); 6633 int err, min_off, max_off, i, j, slot, spi; 6634 /* Some accesses can write anything into the stack, others are 6635 * read-only. 6636 */ 6637 bool clobber = type == BPF_WRITE; 6638 /* 6639 * Negative access_size signals global subprog/kfunc arg check where 6640 * STACK_POISON slots are acceptable. static stack liveness 6641 * might have determined that subprog doesn't read them, 6642 * but BTF based global subprog validation isn't accurate enough. 6643 */ 6644 bool allow_poison = access_size < 0 || clobber; 6645 6646 access_size = abs(access_size); 6647 6648 if (access_size == 0 && !zero_size_allowed) { 6649 verbose(env, "invalid zero-sized read\n"); 6650 return -EACCES; 6651 } 6652 6653 err = check_stack_access_within_bounds(env, reg, argno, off, access_size, type); 6654 if (err) 6655 return err; 6656 6657 6658 if (tnum_is_const(reg->var_off)) { 6659 min_off = max_off = reg->var_off.value + off; 6660 } else { 6661 /* Variable offset is prohibited for unprivileged mode for 6662 * simplicity since it requires corresponding support in 6663 * Spectre masking for stack ALU. 6664 * See also retrieve_ptr_limit(). 6665 */ 6666 if (!env->bypass_spec_v1) { 6667 char tn_buf[48]; 6668 6669 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 6670 verbose(env, "%s variable offset stack access prohibited for !root, var_off=%s\n", 6671 reg_arg_name(env, argno), tn_buf); 6672 return -EACCES; 6673 } 6674 /* Only initialized buffer on stack is allowed to be accessed 6675 * with variable offset. With uninitialized buffer it's hard to 6676 * guarantee that whole memory is marked as initialized on 6677 * helper return since specific bounds are unknown what may 6678 * cause uninitialized stack leaking. 6679 */ 6680 if (meta && meta->raw_mode) 6681 meta = NULL; 6682 6683 min_off = reg_smin(reg) + off; 6684 max_off = reg_smax(reg) + off; 6685 } 6686 6687 if (meta && meta->raw_mode) { 6688 /* Ensure we won't be overwriting dynptrs when simulating byte 6689 * by byte access in check_helper_call using meta.access_size. 6690 * This would be a problem if we have a helper in the future 6691 * which takes: 6692 * 6693 * helper(uninit_mem, len, dynptr) 6694 * 6695 * Now, uninint_mem may overlap with dynptr pointer. Hence, it 6696 * may end up writing to dynptr itself when touching memory from 6697 * arg 1. This can be relaxed on a case by case basis for known 6698 * safe cases, but reject due to the possibilitiy of aliasing by 6699 * default. 6700 */ 6701 for (i = min_off; i < max_off + access_size; i++) { 6702 int stack_off = -i - 1; 6703 6704 spi = bpf_get_spi(i); 6705 /* raw_mode may write past allocated_stack */ 6706 if (state->allocated_stack <= stack_off) 6707 continue; 6708 if (state->stack[spi].slot_type[stack_off % BPF_REG_SIZE] == STACK_DYNPTR) { 6709 verbose(env, "potential write to dynptr at off=%d disallowed\n", i); 6710 return -EACCES; 6711 } 6712 } 6713 meta->access_size = access_size; 6714 meta->regno = reg_from_argno(argno); 6715 return 0; 6716 } 6717 6718 for (i = min_off; i < max_off + access_size; i++) { 6719 u8 *stype; 6720 6721 slot = -i - 1; 6722 spi = slot / BPF_REG_SIZE; 6723 if (state->allocated_stack <= slot) { 6724 verbose(env, "allocated_stack too small\n"); 6725 return -EFAULT; 6726 } 6727 6728 stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE]; 6729 if (*stype == STACK_MISC) 6730 goto mark; 6731 if ((*stype == STACK_ZERO) || 6732 (*stype == STACK_INVALID && env->allow_uninit_stack)) { 6733 if (clobber) { 6734 /* helper can write anything into the stack */ 6735 *stype = STACK_MISC; 6736 } 6737 goto mark; 6738 } 6739 6740 if (bpf_is_spilled_reg(&state->stack[spi]) && 6741 (state->stack[spi].spilled_ptr.type == SCALAR_VALUE || 6742 env->allow_ptr_leaks)) { 6743 if (clobber) { 6744 __mark_reg_unknown(env, &state->stack[spi].spilled_ptr); 6745 for (j = 0; j < BPF_REG_SIZE; j++) 6746 scrub_spilled_slot(&state->stack[spi].slot_type[j]); 6747 } 6748 goto mark; 6749 } 6750 6751 if (*stype == STACK_POISON) { 6752 if (allow_poison) 6753 goto mark; 6754 verbose(env, "reading from stack %s off %d+%d size %d, slot poisoned by dead code elimination\n", 6755 reg_arg_name(env, argno), min_off, i - min_off, access_size); 6756 } else if (tnum_is_const(reg->var_off)) { 6757 verbose(env, "invalid read from stack %s off %d+%d size %d\n", 6758 reg_arg_name(env, argno), min_off, i - min_off, access_size); 6759 } else { 6760 char tn_buf[48]; 6761 6762 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 6763 verbose(env, "invalid read from stack %s var_off %s+%d size %d\n", 6764 reg_arg_name(env, argno), tn_buf, i - min_off, access_size); 6765 } 6766 return -EACCES; 6767 mark: 6768 ; 6769 } 6770 return 0; 6771 } 6772 6773 static int check_helper_mem_access(struct bpf_verifier_env *env, struct bpf_reg_state *reg, argno_t argno, 6774 int access_size, enum bpf_access_type access_type, 6775 bool zero_size_allowed, 6776 struct bpf_call_arg_meta *meta) 6777 { 6778 struct bpf_reg_state *regs = cur_regs(env); 6779 u32 *max_access; 6780 6781 switch (base_type(reg->type)) { 6782 case PTR_TO_PACKET: 6783 case PTR_TO_PACKET_META: 6784 return check_packet_access(env, reg, argno, 0, access_size, 6785 zero_size_allowed); 6786 case PTR_TO_MAP_KEY: 6787 if (access_type == BPF_WRITE) { 6788 verbose(env, "%s cannot write into %s\n", 6789 reg_arg_name(env, argno), reg_type_str(env, reg->type)); 6790 return -EACCES; 6791 } 6792 return check_mem_region_access(env, reg, argno, 0, access_size, 6793 reg->map_ptr->key_size, false); 6794 case PTR_TO_MAP_VALUE: 6795 if (check_map_access_type(env, reg, 0, access_size, access_type)) 6796 return -EACCES; 6797 return check_map_access(env, reg, argno, 0, access_size, 6798 zero_size_allowed, ACCESS_HELPER); 6799 case PTR_TO_MEM: 6800 if (type_is_rdonly_mem(reg->type)) { 6801 if (access_type == BPF_WRITE) { 6802 verbose(env, "%s cannot write into %s\n", 6803 reg_arg_name(env, argno), reg_type_str(env, reg->type)); 6804 return -EACCES; 6805 } 6806 } 6807 return check_mem_region_access(env, reg, argno, 0, 6808 access_size, reg->mem_size, 6809 zero_size_allowed); 6810 case PTR_TO_BUF: 6811 if (type_is_rdonly_mem(reg->type)) { 6812 if (access_type == BPF_WRITE) { 6813 verbose(env, "%s cannot write into %s\n", 6814 reg_arg_name(env, argno), reg_type_str(env, reg->type)); 6815 return -EACCES; 6816 } 6817 6818 max_access = &env->prog->aux->max_rdonly_access; 6819 } else { 6820 max_access = &env->prog->aux->max_rdwr_access; 6821 } 6822 return check_buffer_access(env, reg, argno, 0, 6823 access_size, zero_size_allowed, 6824 max_access); 6825 case PTR_TO_STACK: 6826 return check_stack_range_initialized( 6827 env, reg, 6828 argno, 0, access_size, 6829 zero_size_allowed, access_type, meta); 6830 case PTR_TO_BTF_ID: 6831 return check_ptr_to_btf_access(env, regs, reg, argno, 0, 6832 access_size, BPF_READ, -1); 6833 case PTR_TO_CTX: 6834 /* Only permit reading or writing syscall context using helper calls. */ 6835 if (is_var_ctx_off_allowed(env->prog)) { 6836 int err = check_mem_region_access(env, reg, argno, 0, access_size, U16_MAX, 6837 zero_size_allowed); 6838 if (err) 6839 return err; 6840 if (env->prog->aux->max_ctx_offset < reg_umax(reg) + access_size) 6841 env->prog->aux->max_ctx_offset = reg_umax(reg) + access_size; 6842 return 0; 6843 } 6844 fallthrough; 6845 default: /* scalar_value or invalid ptr */ 6846 /* Allow zero-byte read from NULL, regardless of pointer type */ 6847 if (zero_size_allowed && access_size == 0 && 6848 bpf_register_is_null(reg)) 6849 return 0; 6850 6851 verbose(env, "%s type=%s ", reg_arg_name(env, argno), 6852 reg_type_str(env, reg->type)); 6853 verbose(env, "expected=%s\n", reg_type_str(env, PTR_TO_STACK)); 6854 return -EACCES; 6855 } 6856 } 6857 6858 /* verify arguments to helpers or kfuncs consisting of a pointer and an access 6859 * size. 6860 * 6861 * @mem_reg contains the pointer, @size_reg contains the access size. 6862 */ 6863 static int check_mem_size_reg(struct bpf_verifier_env *env, 6864 struct bpf_reg_state *mem_reg, 6865 struct bpf_reg_state *size_reg, argno_t mem_argno, 6866 argno_t size_argno, enum bpf_access_type access_type, 6867 bool zero_size_allowed, 6868 struct bpf_call_arg_meta *meta) 6869 { 6870 int err; 6871 6872 /* This is used to refine r0 return value bounds for helpers 6873 * that enforce this value as an upper bound on return values. 6874 * See do_refine_retval_range() for helpers that can refine 6875 * the return value. C type of helper is u32 so we pull register 6876 * bound from umax_value however, if negative verifier errors 6877 * out. Only upper bounds can be learned because retval is an 6878 * int type and negative retvals are allowed. 6879 */ 6880 meta->msize_max_value = reg_umax(size_reg); 6881 6882 /* The register is SCALAR_VALUE; the access check happens using 6883 * its boundaries. For unprivileged variable accesses, disable 6884 * raw mode so that the program is required to initialize all 6885 * the memory that the helper could just partially fill up. 6886 */ 6887 if (!tnum_is_const(size_reg->var_off)) 6888 meta = NULL; 6889 6890 if (reg_smin(size_reg) < 0) { 6891 verbose(env, "%s min value is negative, either use unsigned or 'var &= const'\n", 6892 reg_arg_name(env, size_argno)); 6893 return -EACCES; 6894 } 6895 6896 if (reg_umin(size_reg) == 0 && !zero_size_allowed) { 6897 verbose(env, "%s invalid zero-sized read: u64=[%lld,%lld]\n", 6898 reg_arg_name(env, size_argno), reg_umin(size_reg), reg_umax(size_reg)); 6899 return -EACCES; 6900 } 6901 6902 if (reg_umax(size_reg) >= BPF_MAX_VAR_SIZ) { 6903 verbose(env, "%s unbounded memory access, use 'var &= const' or 'if (var < const)'\n", 6904 reg_arg_name(env, size_argno)); 6905 return -EACCES; 6906 } 6907 err = check_helper_mem_access(env, mem_reg, mem_argno, reg_umax(size_reg), 6908 access_type, zero_size_allowed, meta); 6909 if (!err) { 6910 int regno = reg_from_argno(size_argno); 6911 6912 if (regno >= 0) 6913 err = mark_chain_precision(env, regno); 6914 else 6915 err = mark_stack_arg_precision(env, arg_idx_from_argno(size_argno)); 6916 } 6917 return err; 6918 } 6919 6920 static int check_mem_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg, 6921 argno_t argno, u32 mem_size) 6922 { 6923 bool may_be_null = type_may_be_null(reg->type); 6924 struct bpf_reg_state saved_reg; 6925 int err; 6926 6927 if (bpf_register_is_null(reg)) 6928 return 0; 6929 6930 /* Assuming that the register contains a value check if the memory 6931 * access is safe. Temporarily save and restore the register's state as 6932 * the conversion shouldn't be visible to a caller. 6933 */ 6934 if (may_be_null) { 6935 saved_reg = *reg; 6936 mark_ptr_not_null_reg(reg); 6937 } 6938 6939 int size = base_type(reg->type) == PTR_TO_STACK ? -(int)mem_size : mem_size; 6940 6941 err = check_helper_mem_access(env, reg, argno, size, BPF_READ, true, NULL); 6942 err = err ?: check_helper_mem_access(env, reg, argno, size, BPF_WRITE, true, NULL); 6943 6944 if (may_be_null) 6945 *reg = saved_reg; 6946 6947 return err; 6948 } 6949 6950 static int check_kfunc_mem_size_reg(struct bpf_verifier_env *env, struct bpf_reg_state *mem_reg, 6951 struct bpf_reg_state *size_reg, argno_t mem_argno, argno_t size_argno) 6952 { 6953 bool may_be_null = type_may_be_null(mem_reg->type); 6954 struct bpf_reg_state saved_reg; 6955 struct bpf_call_arg_meta meta; 6956 int err; 6957 6958 memset(&meta, 0, sizeof(meta)); 6959 6960 if (may_be_null) { 6961 saved_reg = *mem_reg; 6962 mark_ptr_not_null_reg(mem_reg); 6963 } 6964 6965 err = check_mem_size_reg(env, mem_reg, size_reg, mem_argno, size_argno, BPF_READ, true, &meta); 6966 err = err ?: check_mem_size_reg(env, mem_reg, size_reg, mem_argno, size_argno, BPF_WRITE, true, &meta); 6967 6968 if (may_be_null) 6969 *mem_reg = saved_reg; 6970 6971 return err; 6972 } 6973 6974 enum { 6975 PROCESS_SPIN_LOCK = (1 << 0), 6976 PROCESS_RES_LOCK = (1 << 1), 6977 PROCESS_LOCK_IRQ = (1 << 2), 6978 }; 6979 6980 /* Implementation details: 6981 * bpf_map_lookup returns PTR_TO_MAP_VALUE_OR_NULL. 6982 * bpf_obj_new returns PTR_TO_BTF_ID | MEM_ALLOC | PTR_MAYBE_NULL. 6983 * Two bpf_map_lookups (even with the same key) will have different reg->id. 6984 * Two separate bpf_obj_new will also have different reg->id. 6985 * For traditional PTR_TO_MAP_VALUE or PTR_TO_BTF_ID | MEM_ALLOC, the verifier 6986 * clears reg->id after value_or_null->value transition, since the verifier only 6987 * cares about the range of access to valid map value pointer and doesn't care 6988 * about actual address of the map element. 6989 * For maps with 'struct bpf_spin_lock' inside map value the verifier keeps 6990 * reg->id > 0 after value_or_null->value transition. By doing so 6991 * two bpf_map_lookups will be considered two different pointers that 6992 * point to different bpf_spin_locks. Likewise for pointers to allocated objects 6993 * returned from bpf_obj_new. 6994 * The verifier allows taking only one bpf_spin_lock at a time to avoid 6995 * dead-locks. 6996 * Since only one bpf_spin_lock is allowed the checks are simpler than 6997 * reg_is_refcounted() logic. The verifier needs to remember only 6998 * one spin_lock instead of array of acquired_refs. 6999 * env->cur_state->active_locks remembers which map value element or allocated 7000 * object got locked and clears it after bpf_spin_unlock. 7001 */ 7002 static int process_spin_lock(struct bpf_verifier_env *env, struct bpf_reg_state *reg, argno_t argno, int flags) 7003 { 7004 bool is_lock = flags & PROCESS_SPIN_LOCK, is_res_lock = flags & PROCESS_RES_LOCK; 7005 const char *lock_str = is_res_lock ? "bpf_res_spin" : "bpf_spin"; 7006 struct bpf_verifier_state *cur = env->cur_state; 7007 bool is_const = tnum_is_const(reg->var_off); 7008 bool is_irq = flags & PROCESS_LOCK_IRQ; 7009 u64 val = reg->var_off.value; 7010 struct bpf_map *map = NULL; 7011 struct btf *btf = NULL; 7012 struct btf_record *rec; 7013 u32 spin_lock_off; 7014 int err; 7015 7016 if (!is_const) { 7017 verbose(env, 7018 "%s doesn't have constant offset. %s_lock has to be at the constant offset\n", 7019 reg_arg_name(env, argno), lock_str); 7020 return -EINVAL; 7021 } 7022 if (reg->type == PTR_TO_MAP_VALUE) { 7023 map = reg->map_ptr; 7024 if (!map->btf) { 7025 verbose(env, 7026 "map '%s' has to have BTF in order to use %s_lock\n", 7027 map->name, lock_str); 7028 return -EINVAL; 7029 } 7030 } else { 7031 btf = reg->btf; 7032 } 7033 7034 rec = reg_btf_record(reg); 7035 if (!btf_record_has_field(rec, is_res_lock ? BPF_RES_SPIN_LOCK : BPF_SPIN_LOCK)) { 7036 verbose(env, "%s '%s' has no valid %s_lock\n", map ? "map" : "local", 7037 map ? map->name : "kptr", lock_str); 7038 return -EINVAL; 7039 } 7040 spin_lock_off = is_res_lock ? rec->res_spin_lock_off : rec->spin_lock_off; 7041 if (spin_lock_off != val) { 7042 verbose(env, "off %lld doesn't point to 'struct %s_lock' that is at %d\n", 7043 val, lock_str, spin_lock_off); 7044 return -EINVAL; 7045 } 7046 if (is_lock) { 7047 void *ptr; 7048 int type; 7049 7050 if (map) 7051 ptr = map; 7052 else 7053 ptr = btf; 7054 7055 if (!is_res_lock && cur->active_locks) { 7056 if (find_lock_state(env->cur_state, REF_TYPE_LOCK, 0, NULL)) { 7057 verbose(env, 7058 "Locking two bpf_spin_locks are not allowed\n"); 7059 return -EINVAL; 7060 } 7061 } else if (is_res_lock && cur->active_locks) { 7062 if (find_lock_state(env->cur_state, REF_TYPE_RES_LOCK | REF_TYPE_RES_LOCK_IRQ, reg->id, ptr)) { 7063 verbose(env, "Acquiring the same lock again, AA deadlock detected\n"); 7064 return -EINVAL; 7065 } 7066 } 7067 7068 if (is_res_lock && is_irq) 7069 type = REF_TYPE_RES_LOCK_IRQ; 7070 else if (is_res_lock) 7071 type = REF_TYPE_RES_LOCK; 7072 else 7073 type = REF_TYPE_LOCK; 7074 err = acquire_lock_state(env, env->insn_idx, type, reg->id, ptr); 7075 if (err < 0) { 7076 verbose(env, "Failed to acquire lock state\n"); 7077 return err; 7078 } 7079 } else { 7080 void *ptr; 7081 int type; 7082 7083 if (map) 7084 ptr = map; 7085 else 7086 ptr = btf; 7087 7088 if (!cur->active_locks) { 7089 verbose(env, "%s_unlock without taking a lock\n", lock_str); 7090 return -EINVAL; 7091 } 7092 7093 if (is_res_lock && is_irq) 7094 type = REF_TYPE_RES_LOCK_IRQ; 7095 else if (is_res_lock) 7096 type = REF_TYPE_RES_LOCK; 7097 else 7098 type = REF_TYPE_LOCK; 7099 if (!find_lock_state(cur, type, reg->id, ptr)) { 7100 verbose(env, "%s_unlock of different lock\n", lock_str); 7101 return -EINVAL; 7102 } 7103 if (reg->id != cur->active_lock_id || ptr != cur->active_lock_ptr) { 7104 verbose(env, "%s_unlock cannot be out of order\n", lock_str); 7105 return -EINVAL; 7106 } 7107 if (release_lock_state(cur, type, reg->id, ptr)) { 7108 verbose(env, "%s_unlock of different lock\n", lock_str); 7109 return -EINVAL; 7110 } 7111 7112 invalidate_non_owning_refs(env); 7113 } 7114 return 0; 7115 } 7116 7117 /* Check if @regno is a pointer to a specific field in a map value */ 7118 static int check_map_field_pointer(struct bpf_verifier_env *env, struct bpf_reg_state *reg, argno_t argno, 7119 enum btf_field_type field_type, 7120 struct bpf_map_desc *map_desc) 7121 { 7122 bool is_const = tnum_is_const(reg->var_off); 7123 struct bpf_map *map = reg->map_ptr; 7124 u64 val = reg->var_off.value; 7125 const char *struct_name = btf_field_type_name(field_type); 7126 int field_off = -1; 7127 7128 if (!is_const) { 7129 verbose(env, 7130 "%s doesn't have constant offset. %s has to be at the constant offset\n", 7131 reg_arg_name(env, argno), struct_name); 7132 return -EINVAL; 7133 } 7134 if (!map->btf) { 7135 verbose(env, "map '%s' has to have BTF in order to use %s\n", map->name, 7136 struct_name); 7137 return -EINVAL; 7138 } 7139 if (!btf_record_has_field(map->record, field_type)) { 7140 verbose(env, "map '%s' has no valid %s\n", map->name, struct_name); 7141 return -EINVAL; 7142 } 7143 switch (field_type) { 7144 case BPF_TIMER: 7145 field_off = map->record->timer_off; 7146 break; 7147 case BPF_TASK_WORK: 7148 field_off = map->record->task_work_off; 7149 break; 7150 case BPF_WORKQUEUE: 7151 field_off = map->record->wq_off; 7152 break; 7153 default: 7154 verifier_bug(env, "unsupported BTF field type: %s\n", struct_name); 7155 return -EINVAL; 7156 } 7157 if (field_off != val) { 7158 verbose(env, "off %lld doesn't point to 'struct %s' that is at %d\n", 7159 val, struct_name, field_off); 7160 return -EINVAL; 7161 } 7162 if (map_desc->ptr) { 7163 verifier_bug(env, "Two map pointers in a %s helper", struct_name); 7164 return -EFAULT; 7165 } 7166 map_desc->uid = reg->map_uid; 7167 map_desc->ptr = map; 7168 return 0; 7169 } 7170 7171 static int process_timer_func(struct bpf_verifier_env *env, struct bpf_reg_state *reg, argno_t argno, 7172 struct bpf_map_desc *map) 7173 { 7174 if (IS_ENABLED(CONFIG_PREEMPT_RT)) { 7175 verbose(env, "bpf_timer cannot be used for PREEMPT_RT.\n"); 7176 return -EOPNOTSUPP; 7177 } 7178 return check_map_field_pointer(env, reg, argno, BPF_TIMER, map); 7179 } 7180 7181 static int process_timer_helper(struct bpf_verifier_env *env, struct bpf_reg_state *reg, argno_t argno, 7182 struct bpf_call_arg_meta *meta) 7183 { 7184 return process_timer_func(env, reg, argno, &meta->map); 7185 } 7186 7187 static int process_timer_kfunc(struct bpf_verifier_env *env, struct bpf_reg_state *reg, argno_t argno, 7188 struct bpf_kfunc_call_arg_meta *meta) 7189 { 7190 return process_timer_func(env, reg, argno, &meta->map); 7191 } 7192 7193 static int process_kptr_func(struct bpf_verifier_env *env, int regno, 7194 struct bpf_call_arg_meta *meta) 7195 { 7196 struct bpf_reg_state *reg = reg_state(env, regno); 7197 struct btf_field *kptr_field; 7198 struct bpf_map *map_ptr; 7199 struct btf_record *rec; 7200 u32 kptr_off; 7201 7202 if (type_is_ptr_alloc_obj(reg->type)) { 7203 rec = reg_btf_record(reg); 7204 } else { /* PTR_TO_MAP_VALUE */ 7205 map_ptr = reg->map_ptr; 7206 if (!map_ptr->btf) { 7207 verbose(env, "map '%s' has to have BTF in order to use bpf_kptr_xchg\n", 7208 map_ptr->name); 7209 return -EINVAL; 7210 } 7211 rec = map_ptr->record; 7212 meta->map.ptr = map_ptr; 7213 } 7214 7215 if (!tnum_is_const(reg->var_off)) { 7216 verbose(env, 7217 "R%d doesn't have constant offset. kptr has to be at the constant offset\n", 7218 regno); 7219 return -EINVAL; 7220 } 7221 7222 if (!btf_record_has_field(rec, BPF_KPTR)) { 7223 verbose(env, "R%d has no valid kptr\n", regno); 7224 return -EINVAL; 7225 } 7226 7227 kptr_off = reg->var_off.value; 7228 kptr_field = btf_record_find(rec, kptr_off, BPF_KPTR); 7229 if (!kptr_field) { 7230 verbose(env, "off=%d doesn't point to kptr\n", kptr_off); 7231 return -EACCES; 7232 } 7233 if (kptr_field->type != BPF_KPTR_REF && kptr_field->type != BPF_KPTR_PERCPU) { 7234 verbose(env, "off=%d kptr isn't referenced kptr\n", kptr_off); 7235 return -EACCES; 7236 } 7237 meta->kptr_field = kptr_field; 7238 return 0; 7239 } 7240 7241 /* There are two register types representing a bpf_dynptr, one is PTR_TO_STACK 7242 * which points to a stack slot, and the other is CONST_PTR_TO_DYNPTR. 7243 * 7244 * In both cases we deal with the first 8 bytes, but need to mark the next 8 7245 * bytes as STACK_DYNPTR in case of PTR_TO_STACK. In case of 7246 * CONST_PTR_TO_DYNPTR, we are guaranteed to get the beginning of the object. 7247 * 7248 * Mutability of bpf_dynptr is at two levels: the dynptr and the memory the 7249 * dynptr points to. At the first level, the verifier will make sure a 7250 * CONST_PTR_TO_DYNPTR cannot be reinitialized or destroyed. The mutability of 7251 * a dynptr's view (i.e., start and offset) is not tracked as there is not such 7252 * use case. The second level is tracked using the upper bit of bpf_dynptr->size 7253 * and checked dynamically during runtime. 7254 */ 7255 static int process_dynptr_func(struct bpf_verifier_env *env, struct bpf_reg_state *reg, argno_t argno, int insn_idx, 7256 enum bpf_arg_type arg_type, int clone_ref_obj_id) 7257 { 7258 int err; 7259 7260 if (reg->type != PTR_TO_STACK && reg->type != CONST_PTR_TO_DYNPTR) { 7261 verbose(env, 7262 "%s expected pointer to stack or const struct bpf_dynptr\n", 7263 reg_arg_name(env, argno)); 7264 return -EINVAL; 7265 } 7266 7267 /* MEM_UNINIT - Points to memory that is an appropriate candidate for 7268 * constructing a mutable bpf_dynptr object. 7269 * 7270 * Currently, this is only possible with PTR_TO_STACK 7271 * pointing to a region of at least 16 bytes which doesn't 7272 * contain an existing bpf_dynptr. 7273 * 7274 * OBJ_RELEASE - Points to a initialized bpf_dynptr that will be 7275 * destroyed. 7276 * 7277 * None - Points to a initialized dynptr that cannot be 7278 * reinitialized or destroyed. However, the view of the 7279 * dynptr and the memory it points to may be mutated. 7280 */ 7281 if (arg_type & MEM_UNINIT) { 7282 int i; 7283 7284 if (!is_dynptr_reg_valid_uninit(env, reg)) { 7285 verbose(env, "Dynptr has to be an uninitialized dynptr\n"); 7286 return -EINVAL; 7287 } 7288 7289 /* we write BPF_DW bits (8 bytes) at a time */ 7290 for (i = 0; i < BPF_DYNPTR_SIZE; i += 8) { 7291 err = check_mem_access(env, insn_idx, reg, argno, 7292 i, BPF_DW, BPF_WRITE, -1, false, false); 7293 if (err) 7294 return err; 7295 } 7296 7297 err = mark_stack_slots_dynptr(env, reg, arg_type, insn_idx, clone_ref_obj_id); 7298 } else /* OBJ_RELEASE and None case from above */ { 7299 /* For the reg->type == PTR_TO_STACK case, bpf_dynptr is never const */ 7300 if (reg->type == CONST_PTR_TO_DYNPTR && (arg_type & OBJ_RELEASE)) { 7301 verbose(env, "CONST_PTR_TO_DYNPTR cannot be released\n"); 7302 return -EINVAL; 7303 } 7304 7305 if (!is_dynptr_reg_valid_init(env, reg)) { 7306 verbose(env, "Expected an initialized dynptr as %s\n", 7307 reg_arg_name(env, argno)); 7308 return -EINVAL; 7309 } 7310 7311 /* Fold modifiers (in this case, OBJ_RELEASE) when checking expected type */ 7312 if (!is_dynptr_type_expected(env, reg, arg_type & ~OBJ_RELEASE)) { 7313 verbose(env, 7314 "Expected a dynptr of type %s as %s\n", 7315 dynptr_type_str(arg_to_dynptr_type(arg_type)), 7316 reg_arg_name(env, argno)); 7317 return -EINVAL; 7318 } 7319 7320 err = mark_dynptr_read(env, reg); 7321 } 7322 return err; 7323 } 7324 7325 static u32 iter_ref_obj_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg, int spi) 7326 { 7327 struct bpf_func_state *state = bpf_func(env, reg); 7328 7329 return state->stack[spi].spilled_ptr.ref_obj_id; 7330 } 7331 7332 static bool is_iter_kfunc(struct bpf_kfunc_call_arg_meta *meta) 7333 { 7334 return meta->kfunc_flags & (KF_ITER_NEW | KF_ITER_NEXT | KF_ITER_DESTROY); 7335 } 7336 7337 static bool is_iter_new_kfunc(struct bpf_kfunc_call_arg_meta *meta) 7338 { 7339 return meta->kfunc_flags & KF_ITER_NEW; 7340 } 7341 7342 7343 static bool is_iter_destroy_kfunc(struct bpf_kfunc_call_arg_meta *meta) 7344 { 7345 return meta->kfunc_flags & KF_ITER_DESTROY; 7346 } 7347 7348 static bool is_kfunc_arg_iter(struct bpf_kfunc_call_arg_meta *meta, int arg_idx, 7349 const struct btf_param *arg) 7350 { 7351 /* btf_check_iter_kfuncs() guarantees that first argument of any iter 7352 * kfunc is iter state pointer 7353 */ 7354 if (is_iter_kfunc(meta)) 7355 return arg_idx == 0; 7356 7357 /* iter passed as an argument to a generic kfunc */ 7358 return btf_param_match_suffix(meta->btf, arg, "__iter"); 7359 } 7360 7361 static int process_iter_arg(struct bpf_verifier_env *env, struct bpf_reg_state *reg, argno_t argno, int insn_idx, 7362 struct bpf_kfunc_call_arg_meta *meta) 7363 { 7364 const struct btf_type *t; 7365 u32 arg_idx = arg_idx_from_argno(argno); 7366 int spi, err, i, nr_slots, btf_id; 7367 7368 if (reg->type != PTR_TO_STACK) { 7369 verbose(env, "%s expected pointer to an iterator on stack\n", 7370 reg_arg_name(env, argno)); 7371 return -EINVAL; 7372 } 7373 7374 /* For iter_{new,next,destroy} functions, btf_check_iter_kfuncs() 7375 * ensures struct convention, so we wouldn't need to do any BTF 7376 * validation here. But given iter state can be passed as a parameter 7377 * to any kfunc, if arg has "__iter" suffix, we need to be a bit more 7378 * conservative here. 7379 */ 7380 btf_id = btf_check_iter_arg(meta->btf, meta->func_proto, arg_idx); 7381 if (btf_id < 0) { 7382 verbose(env, "expected valid iter pointer as %s\n", 7383 reg_arg_name(env, argno)); 7384 return -EINVAL; 7385 } 7386 t = btf_type_by_id(meta->btf, btf_id); 7387 nr_slots = t->size / BPF_REG_SIZE; 7388 7389 if (is_iter_new_kfunc(meta)) { 7390 /* bpf_iter_<type>_new() expects pointer to uninit iter state */ 7391 if (!is_iter_reg_valid_uninit(env, reg, nr_slots)) { 7392 verbose(env, "expected uninitialized iter_%s as %s\n", 7393 iter_type_str(meta->btf, btf_id), reg_arg_name(env, argno)); 7394 return -EINVAL; 7395 } 7396 7397 for (i = 0; i < nr_slots * 8; i += BPF_REG_SIZE) { 7398 err = check_mem_access(env, insn_idx, reg, argno, 7399 i, BPF_DW, BPF_WRITE, -1, false, false); 7400 if (err) 7401 return err; 7402 } 7403 7404 err = mark_stack_slots_iter(env, meta, reg, insn_idx, meta->btf, btf_id, nr_slots); 7405 if (err) 7406 return err; 7407 } else { 7408 /* iter_next() or iter_destroy(), as well as any kfunc 7409 * accepting iter argument, expect initialized iter state 7410 */ 7411 err = is_iter_reg_valid_init(env, reg, meta->btf, btf_id, nr_slots); 7412 switch (err) { 7413 case 0: 7414 break; 7415 case -EINVAL: 7416 verbose(env, "expected an initialized iter_%s as %s\n", 7417 iter_type_str(meta->btf, btf_id), reg_arg_name(env, argno)); 7418 return err; 7419 case -EPROTO: 7420 verbose(env, "expected an RCU CS when using %s\n", meta->func_name); 7421 return err; 7422 default: 7423 return err; 7424 } 7425 7426 spi = iter_get_spi(env, reg, nr_slots); 7427 if (spi < 0) 7428 return spi; 7429 7430 err = mark_iter_read(env, reg, spi, nr_slots); 7431 if (err) 7432 return err; 7433 7434 /* remember meta->iter info for process_iter_next_call() */ 7435 meta->iter.spi = spi; 7436 meta->iter.frameno = reg->frameno; 7437 meta->ref_obj_id = iter_ref_obj_id(env, reg, spi); 7438 7439 if (is_iter_destroy_kfunc(meta)) { 7440 err = unmark_stack_slots_iter(env, reg, nr_slots); 7441 if (err) 7442 return err; 7443 } 7444 } 7445 7446 return 0; 7447 } 7448 7449 /* Look for a previous loop entry at insn_idx: nearest parent state 7450 * stopped at insn_idx with callsites matching those in cur->frame. 7451 */ 7452 static struct bpf_verifier_state *find_prev_entry(struct bpf_verifier_env *env, 7453 struct bpf_verifier_state *cur, 7454 int insn_idx) 7455 { 7456 struct bpf_verifier_state_list *sl; 7457 struct bpf_verifier_state *st; 7458 struct list_head *pos, *head; 7459 7460 /* Explored states are pushed in stack order, most recent states come first */ 7461 head = bpf_explored_state(env, insn_idx); 7462 list_for_each(pos, head) { 7463 sl = container_of(pos, struct bpf_verifier_state_list, node); 7464 /* If st->branches != 0 state is a part of current DFS verification path, 7465 * hence cur & st for a loop. 7466 */ 7467 st = &sl->state; 7468 if (st->insn_idx == insn_idx && st->branches && same_callsites(st, cur) && 7469 st->dfs_depth < cur->dfs_depth) 7470 return st; 7471 } 7472 7473 return NULL; 7474 } 7475 7476 /* 7477 * Check if scalar registers are exact for the purpose of not widening. 7478 * More lenient than regs_exact() 7479 */ 7480 static bool scalars_exact_for_widen(const struct bpf_reg_state *rold, 7481 const struct bpf_reg_state *rcur) 7482 { 7483 return !memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)); 7484 } 7485 7486 static void maybe_widen_reg(struct bpf_verifier_env *env, 7487 struct bpf_reg_state *rold, struct bpf_reg_state *rcur) 7488 { 7489 if (rold->type != SCALAR_VALUE) 7490 return; 7491 if (rold->type != rcur->type) 7492 return; 7493 if (rold->precise || rcur->precise || scalars_exact_for_widen(rold, rcur)) 7494 return; 7495 __mark_reg_unknown(env, rcur); 7496 } 7497 7498 static int widen_imprecise_scalars(struct bpf_verifier_env *env, 7499 struct bpf_verifier_state *old, 7500 struct bpf_verifier_state *cur) 7501 { 7502 struct bpf_func_state *fold, *fcur; 7503 int i, fr, num_slots; 7504 7505 for (fr = old->curframe; fr >= 0; fr--) { 7506 fold = old->frame[fr]; 7507 fcur = cur->frame[fr]; 7508 7509 for (i = 0; i < MAX_BPF_REG; i++) 7510 maybe_widen_reg(env, 7511 &fold->regs[i], 7512 &fcur->regs[i]); 7513 7514 num_slots = min(fold->allocated_stack / BPF_REG_SIZE, 7515 fcur->allocated_stack / BPF_REG_SIZE); 7516 for (i = 0; i < num_slots; i++) { 7517 if (!bpf_is_spilled_reg(&fold->stack[i]) || 7518 !bpf_is_spilled_reg(&fcur->stack[i])) 7519 continue; 7520 7521 maybe_widen_reg(env, 7522 &fold->stack[i].spilled_ptr, 7523 &fcur->stack[i].spilled_ptr); 7524 } 7525 } 7526 return 0; 7527 } 7528 7529 static struct bpf_reg_state *get_iter_from_state(struct bpf_verifier_state *cur_st, 7530 struct bpf_kfunc_call_arg_meta *meta) 7531 { 7532 int iter_frameno = meta->iter.frameno; 7533 int iter_spi = meta->iter.spi; 7534 7535 return &cur_st->frame[iter_frameno]->stack[iter_spi].spilled_ptr; 7536 } 7537 7538 /* process_iter_next_call() is called when verifier gets to iterator's next 7539 * "method" (e.g., bpf_iter_num_next() for numbers iterator) call. We'll refer 7540 * to it as just "iter_next()" in comments below. 7541 * 7542 * BPF verifier relies on a crucial contract for any iter_next() 7543 * implementation: it should *eventually* return NULL, and once that happens 7544 * it should keep returning NULL. That is, once iterator exhausts elements to 7545 * iterate, it should never reset or spuriously return new elements. 7546 * 7547 * With the assumption of such contract, process_iter_next_call() simulates 7548 * a fork in the verifier state to validate loop logic correctness and safety 7549 * without having to simulate infinite amount of iterations. 7550 * 7551 * In current state, we first assume that iter_next() returned NULL and 7552 * iterator state is set to DRAINED (BPF_ITER_STATE_DRAINED). In such 7553 * conditions we should not form an infinite loop and should eventually reach 7554 * exit. 7555 * 7556 * Besides that, we also fork current state and enqueue it for later 7557 * verification. In a forked state we keep iterator state as ACTIVE 7558 * (BPF_ITER_STATE_ACTIVE) and assume non-NULL return from iter_next(). We 7559 * also bump iteration depth to prevent erroneous infinite loop detection 7560 * later on (see iter_active_depths_differ() comment for details). In this 7561 * state we assume that we'll eventually loop back to another iter_next() 7562 * calls (it could be in exactly same location or in some other instruction, 7563 * it doesn't matter, we don't make any unnecessary assumptions about this, 7564 * everything revolves around iterator state in a stack slot, not which 7565 * instruction is calling iter_next()). When that happens, we either will come 7566 * to iter_next() with equivalent state and can conclude that next iteration 7567 * will proceed in exactly the same way as we just verified, so it's safe to 7568 * assume that loop converges. If not, we'll go on another iteration 7569 * simulation with a different input state, until all possible starting states 7570 * are validated or we reach maximum number of instructions limit. 7571 * 7572 * This way, we will either exhaustively discover all possible input states 7573 * that iterator loop can start with and eventually will converge, or we'll 7574 * effectively regress into bounded loop simulation logic and either reach 7575 * maximum number of instructions if loop is not provably convergent, or there 7576 * is some statically known limit on number of iterations (e.g., if there is 7577 * an explicit `if n > 100 then break;` statement somewhere in the loop). 7578 * 7579 * Iteration convergence logic in is_state_visited() relies on exact 7580 * states comparison, which ignores read and precision marks. 7581 * This is necessary because read and precision marks are not finalized 7582 * while in the loop. Exact comparison might preclude convergence for 7583 * simple programs like below: 7584 * 7585 * i = 0; 7586 * while(iter_next(&it)) 7587 * i++; 7588 * 7589 * At each iteration step i++ would produce a new distinct state and 7590 * eventually instruction processing limit would be reached. 7591 * 7592 * To avoid such behavior speculatively forget (widen) range for 7593 * imprecise scalar registers, if those registers were not precise at the 7594 * end of the previous iteration and do not match exactly. 7595 * 7596 * This is a conservative heuristic that allows to verify wide range of programs, 7597 * however it precludes verification of programs that conjure an 7598 * imprecise value on the first loop iteration and use it as precise on a second. 7599 * For example, the following safe program would fail to verify: 7600 * 7601 * struct bpf_num_iter it; 7602 * int arr[10]; 7603 * int i = 0, a = 0; 7604 * bpf_iter_num_new(&it, 0, 10); 7605 * while (bpf_iter_num_next(&it)) { 7606 * if (a == 0) { 7607 * a = 1; 7608 * i = 7; // Because i changed verifier would forget 7609 * // it's range on second loop entry. 7610 * } else { 7611 * arr[i] = 42; // This would fail to verify. 7612 * } 7613 * } 7614 * bpf_iter_num_destroy(&it); 7615 */ 7616 static int process_iter_next_call(struct bpf_verifier_env *env, int insn_idx, 7617 struct bpf_kfunc_call_arg_meta *meta) 7618 { 7619 struct bpf_verifier_state *cur_st = env->cur_state, *queued_st, *prev_st; 7620 struct bpf_func_state *cur_fr = cur_st->frame[cur_st->curframe], *queued_fr; 7621 struct bpf_reg_state *cur_iter, *queued_iter; 7622 7623 BTF_TYPE_EMIT(struct bpf_iter); 7624 7625 cur_iter = get_iter_from_state(cur_st, meta); 7626 7627 if (cur_iter->iter.state != BPF_ITER_STATE_ACTIVE && 7628 cur_iter->iter.state != BPF_ITER_STATE_DRAINED) { 7629 verifier_bug(env, "unexpected iterator state %d (%s)", 7630 cur_iter->iter.state, iter_state_str(cur_iter->iter.state)); 7631 return -EFAULT; 7632 } 7633 7634 if (cur_iter->iter.state == BPF_ITER_STATE_ACTIVE) { 7635 /* Because iter_next() call is a checkpoint is_state_visitied() 7636 * should guarantee parent state with same call sites and insn_idx. 7637 */ 7638 if (!cur_st->parent || cur_st->parent->insn_idx != insn_idx || 7639 !same_callsites(cur_st->parent, cur_st)) { 7640 verifier_bug(env, "bad parent state for iter next call"); 7641 return -EFAULT; 7642 } 7643 /* Note cur_st->parent in the call below, it is necessary to skip 7644 * checkpoint created for cur_st by is_state_visited() 7645 * right at this instruction. 7646 */ 7647 prev_st = find_prev_entry(env, cur_st->parent, insn_idx); 7648 /* branch out active iter state */ 7649 queued_st = push_stack(env, insn_idx + 1, insn_idx, false); 7650 if (IS_ERR(queued_st)) 7651 return PTR_ERR(queued_st); 7652 7653 queued_iter = get_iter_from_state(queued_st, meta); 7654 queued_iter->iter.state = BPF_ITER_STATE_ACTIVE; 7655 queued_iter->iter.depth++; 7656 if (prev_st) 7657 widen_imprecise_scalars(env, prev_st, queued_st); 7658 7659 queued_fr = queued_st->frame[queued_st->curframe]; 7660 mark_ptr_not_null_reg(&queued_fr->regs[BPF_REG_0]); 7661 } 7662 7663 /* switch to DRAINED state, but keep the depth unchanged */ 7664 /* mark current iter state as drained and assume returned NULL */ 7665 cur_iter->iter.state = BPF_ITER_STATE_DRAINED; 7666 __mark_reg_const_zero(env, &cur_fr->regs[BPF_REG_0]); 7667 7668 return 0; 7669 } 7670 7671 static bool arg_type_is_mem_size(enum bpf_arg_type type) 7672 { 7673 return type == ARG_CONST_SIZE || 7674 type == ARG_CONST_SIZE_OR_ZERO; 7675 } 7676 7677 static bool arg_type_is_raw_mem(enum bpf_arg_type type) 7678 { 7679 return base_type(type) == ARG_PTR_TO_MEM && 7680 type & MEM_UNINIT; 7681 } 7682 7683 static bool arg_type_is_release(enum bpf_arg_type type) 7684 { 7685 return type & OBJ_RELEASE; 7686 } 7687 7688 static bool arg_type_is_dynptr(enum bpf_arg_type type) 7689 { 7690 return base_type(type) == ARG_PTR_TO_DYNPTR; 7691 } 7692 7693 static int resolve_map_arg_type(struct bpf_verifier_env *env, 7694 const struct bpf_call_arg_meta *meta, 7695 enum bpf_arg_type *arg_type) 7696 { 7697 if (!meta->map.ptr) { 7698 /* kernel subsystem misconfigured verifier */ 7699 verifier_bug(env, "invalid map_ptr to access map->type"); 7700 return -EFAULT; 7701 } 7702 7703 switch (meta->map.ptr->map_type) { 7704 case BPF_MAP_TYPE_SOCKMAP: 7705 case BPF_MAP_TYPE_SOCKHASH: 7706 if (*arg_type == ARG_PTR_TO_MAP_VALUE) { 7707 *arg_type = ARG_PTR_TO_BTF_ID_SOCK_COMMON; 7708 } else { 7709 verbose(env, "invalid arg_type for sockmap/sockhash\n"); 7710 return -EINVAL; 7711 } 7712 break; 7713 case BPF_MAP_TYPE_BLOOM_FILTER: 7714 if (meta->func_id == BPF_FUNC_map_peek_elem) 7715 *arg_type = ARG_PTR_TO_MAP_VALUE; 7716 break; 7717 default: 7718 break; 7719 } 7720 return 0; 7721 } 7722 7723 struct bpf_reg_types { 7724 const enum bpf_reg_type types[10]; 7725 u32 *btf_id; 7726 }; 7727 7728 static const struct bpf_reg_types sock_types = { 7729 .types = { 7730 PTR_TO_SOCK_COMMON, 7731 PTR_TO_SOCKET, 7732 PTR_TO_TCP_SOCK, 7733 PTR_TO_XDP_SOCK, 7734 }, 7735 }; 7736 7737 #ifdef CONFIG_NET 7738 static const struct bpf_reg_types btf_id_sock_common_types = { 7739 .types = { 7740 PTR_TO_SOCK_COMMON, 7741 PTR_TO_SOCKET, 7742 PTR_TO_TCP_SOCK, 7743 PTR_TO_XDP_SOCK, 7744 PTR_TO_BTF_ID, 7745 PTR_TO_BTF_ID | PTR_TRUSTED, 7746 }, 7747 .btf_id = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON], 7748 }; 7749 #endif 7750 7751 static const struct bpf_reg_types mem_types = { 7752 .types = { 7753 PTR_TO_STACK, 7754 PTR_TO_PACKET, 7755 PTR_TO_PACKET_META, 7756 PTR_TO_MAP_KEY, 7757 PTR_TO_MAP_VALUE, 7758 PTR_TO_MEM, 7759 PTR_TO_MEM | MEM_RINGBUF, 7760 PTR_TO_BUF, 7761 PTR_TO_BTF_ID | PTR_TRUSTED, 7762 PTR_TO_CTX, 7763 }, 7764 }; 7765 7766 static const struct bpf_reg_types spin_lock_types = { 7767 .types = { 7768 PTR_TO_MAP_VALUE, 7769 PTR_TO_BTF_ID | MEM_ALLOC, 7770 } 7771 }; 7772 7773 static const struct bpf_reg_types fullsock_types = { .types = { PTR_TO_SOCKET } }; 7774 static const struct bpf_reg_types scalar_types = { .types = { SCALAR_VALUE } }; 7775 static const struct bpf_reg_types context_types = { .types = { PTR_TO_CTX } }; 7776 static const struct bpf_reg_types ringbuf_mem_types = { .types = { PTR_TO_MEM | MEM_RINGBUF } }; 7777 static const struct bpf_reg_types const_map_ptr_types = { .types = { CONST_PTR_TO_MAP } }; 7778 static const struct bpf_reg_types btf_ptr_types = { 7779 .types = { 7780 PTR_TO_BTF_ID, 7781 PTR_TO_BTF_ID | PTR_TRUSTED, 7782 PTR_TO_BTF_ID | MEM_RCU, 7783 }, 7784 }; 7785 static const struct bpf_reg_types percpu_btf_ptr_types = { 7786 .types = { 7787 PTR_TO_BTF_ID | MEM_PERCPU, 7788 PTR_TO_BTF_ID | MEM_PERCPU | MEM_RCU, 7789 PTR_TO_BTF_ID | MEM_PERCPU | PTR_TRUSTED, 7790 } 7791 }; 7792 static const struct bpf_reg_types func_ptr_types = { .types = { PTR_TO_FUNC } }; 7793 static const struct bpf_reg_types stack_ptr_types = { .types = { PTR_TO_STACK } }; 7794 static const struct bpf_reg_types const_str_ptr_types = { .types = { PTR_TO_MAP_VALUE } }; 7795 static const struct bpf_reg_types timer_types = { .types = { PTR_TO_MAP_VALUE } }; 7796 static const struct bpf_reg_types kptr_xchg_dest_types = { 7797 .types = { 7798 PTR_TO_MAP_VALUE, 7799 PTR_TO_BTF_ID | MEM_ALLOC, 7800 PTR_TO_BTF_ID | MEM_ALLOC | NON_OWN_REF, 7801 PTR_TO_BTF_ID | MEM_ALLOC | NON_OWN_REF | MEM_RCU, 7802 } 7803 }; 7804 static const struct bpf_reg_types dynptr_types = { 7805 .types = { 7806 PTR_TO_STACK, 7807 CONST_PTR_TO_DYNPTR, 7808 } 7809 }; 7810 7811 static const struct bpf_reg_types *compatible_reg_types[__BPF_ARG_TYPE_MAX] = { 7812 [ARG_PTR_TO_MAP_KEY] = &mem_types, 7813 [ARG_PTR_TO_MAP_VALUE] = &mem_types, 7814 [ARG_CONST_SIZE] = &scalar_types, 7815 [ARG_CONST_SIZE_OR_ZERO] = &scalar_types, 7816 [ARG_CONST_ALLOC_SIZE_OR_ZERO] = &scalar_types, 7817 [ARG_CONST_MAP_PTR] = &const_map_ptr_types, 7818 [ARG_PTR_TO_CTX] = &context_types, 7819 [ARG_PTR_TO_SOCK_COMMON] = &sock_types, 7820 #ifdef CONFIG_NET 7821 [ARG_PTR_TO_BTF_ID_SOCK_COMMON] = &btf_id_sock_common_types, 7822 #endif 7823 [ARG_PTR_TO_SOCKET] = &fullsock_types, 7824 [ARG_PTR_TO_BTF_ID] = &btf_ptr_types, 7825 [ARG_PTR_TO_SPIN_LOCK] = &spin_lock_types, 7826 [ARG_PTR_TO_MEM] = &mem_types, 7827 [ARG_PTR_TO_RINGBUF_MEM] = &ringbuf_mem_types, 7828 [ARG_PTR_TO_PERCPU_BTF_ID] = &percpu_btf_ptr_types, 7829 [ARG_PTR_TO_FUNC] = &func_ptr_types, 7830 [ARG_PTR_TO_STACK] = &stack_ptr_types, 7831 [ARG_PTR_TO_CONST_STR] = &const_str_ptr_types, 7832 [ARG_PTR_TO_TIMER] = &timer_types, 7833 [ARG_KPTR_XCHG_DEST] = &kptr_xchg_dest_types, 7834 [ARG_PTR_TO_DYNPTR] = &dynptr_types, 7835 }; 7836 7837 static int check_reg_type(struct bpf_verifier_env *env, struct bpf_reg_state *reg, argno_t argno, 7838 enum bpf_arg_type arg_type, 7839 const u32 *arg_btf_id, 7840 struct bpf_call_arg_meta *meta) 7841 { 7842 enum bpf_reg_type expected, type = reg->type; 7843 const struct bpf_reg_types *compatible; 7844 int i, j, err; 7845 7846 compatible = compatible_reg_types[base_type(arg_type)]; 7847 if (!compatible) { 7848 verifier_bug(env, "unsupported arg type %d", arg_type); 7849 return -EFAULT; 7850 } 7851 7852 /* ARG_PTR_TO_MEM + RDONLY is compatible with PTR_TO_MEM and PTR_TO_MEM + RDONLY, 7853 * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM and NOT with PTR_TO_MEM + RDONLY 7854 * 7855 * Same for MAYBE_NULL: 7856 * 7857 * ARG_PTR_TO_MEM + MAYBE_NULL is compatible with PTR_TO_MEM and PTR_TO_MEM + MAYBE_NULL, 7858 * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM but NOT with PTR_TO_MEM + MAYBE_NULL 7859 * 7860 * ARG_PTR_TO_MEM is compatible with PTR_TO_MEM that is tagged with a dynptr type. 7861 * 7862 * Therefore we fold these flags depending on the arg_type before comparison. 7863 */ 7864 if (arg_type & MEM_RDONLY) 7865 type &= ~MEM_RDONLY; 7866 if (arg_type & PTR_MAYBE_NULL) 7867 type &= ~PTR_MAYBE_NULL; 7868 if (base_type(arg_type) == ARG_PTR_TO_MEM) 7869 type &= ~DYNPTR_TYPE_FLAG_MASK; 7870 7871 /* Local kptr types are allowed as the source argument of bpf_kptr_xchg */ 7872 if (meta->func_id == BPF_FUNC_kptr_xchg && type_is_alloc(type) && reg_from_argno(argno) == BPF_REG_2) { 7873 type &= ~MEM_ALLOC; 7874 type &= ~MEM_PERCPU; 7875 } 7876 7877 for (i = 0; i < ARRAY_SIZE(compatible->types); i++) { 7878 expected = compatible->types[i]; 7879 if (expected == NOT_INIT) 7880 break; 7881 7882 if (type == expected) 7883 goto found; 7884 } 7885 7886 verbose(env, "%s type=%s expected=", reg_arg_name(env, argno), reg_type_str(env, reg->type)); 7887 for (j = 0; j + 1 < i; j++) 7888 verbose(env, "%s, ", reg_type_str(env, compatible->types[j])); 7889 verbose(env, "%s\n", reg_type_str(env, compatible->types[j])); 7890 return -EACCES; 7891 7892 found: 7893 if (base_type(reg->type) != PTR_TO_BTF_ID) 7894 return 0; 7895 7896 if (compatible == &mem_types) { 7897 if (!(arg_type & MEM_RDONLY)) { 7898 verbose(env, 7899 "%s() may write into memory pointed by %s type=%s\n", 7900 func_id_name(meta->func_id), 7901 reg_arg_name(env, argno), reg_type_str(env, reg->type)); 7902 return -EACCES; 7903 } 7904 return 0; 7905 } 7906 7907 switch ((int)reg->type) { 7908 case PTR_TO_BTF_ID: 7909 case PTR_TO_BTF_ID | PTR_TRUSTED: 7910 case PTR_TO_BTF_ID | PTR_TRUSTED | PTR_MAYBE_NULL: 7911 case PTR_TO_BTF_ID | MEM_RCU: 7912 case PTR_TO_BTF_ID | PTR_MAYBE_NULL: 7913 case PTR_TO_BTF_ID | PTR_MAYBE_NULL | MEM_RCU: 7914 { 7915 /* For bpf_sk_release, it needs to match against first member 7916 * 'struct sock_common', hence make an exception for it. This 7917 * allows bpf_sk_release to work for multiple socket types. 7918 */ 7919 bool strict_type_match = arg_type_is_release(arg_type) && 7920 meta->func_id != BPF_FUNC_sk_release; 7921 7922 if (type_may_be_null(reg->type) && 7923 (!type_may_be_null(arg_type) || arg_type_is_release(arg_type))) { 7924 verbose(env, "Possibly NULL pointer passed to helper %s\n", 7925 reg_arg_name(env, argno)); 7926 return -EACCES; 7927 } 7928 7929 if (!arg_btf_id) { 7930 if (!compatible->btf_id) { 7931 verifier_bug(env, "missing arg compatible BTF ID"); 7932 return -EFAULT; 7933 } 7934 arg_btf_id = compatible->btf_id; 7935 } 7936 7937 if (meta->func_id == BPF_FUNC_kptr_xchg) { 7938 if (map_kptr_match_type(env, meta->kptr_field, reg, reg_from_argno(argno))) 7939 return -EACCES; 7940 } else { 7941 if (arg_btf_id == BPF_PTR_POISON) { 7942 verbose(env, "verifier internal error:"); 7943 verbose(env, "%s has non-overwritten BPF_PTR_POISON type\n", 7944 reg_arg_name(env, argno)); 7945 return -EACCES; 7946 } 7947 7948 err = __check_ptr_off_reg(env, reg, argno, true); 7949 if (err) 7950 return err; 7951 7952 if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, 7953 reg->var_off.value, btf_vmlinux, *arg_btf_id, 7954 strict_type_match)) { 7955 verbose(env, "%s is of type %s but %s is expected\n", 7956 reg_arg_name(env, argno), 7957 btf_type_name(reg->btf, reg->btf_id), 7958 btf_type_name(btf_vmlinux, *arg_btf_id)); 7959 return -EACCES; 7960 } 7961 } 7962 break; 7963 } 7964 case PTR_TO_BTF_ID | MEM_ALLOC: 7965 case PTR_TO_BTF_ID | MEM_PERCPU | MEM_ALLOC: 7966 case PTR_TO_BTF_ID | MEM_ALLOC | NON_OWN_REF: 7967 case PTR_TO_BTF_ID | MEM_ALLOC | NON_OWN_REF | MEM_RCU: 7968 if (meta->func_id != BPF_FUNC_spin_lock && meta->func_id != BPF_FUNC_spin_unlock && 7969 meta->func_id != BPF_FUNC_kptr_xchg) { 7970 verifier_bug(env, "unimplemented handling of MEM_ALLOC"); 7971 return -EFAULT; 7972 } 7973 /* Check if local kptr in src arg matches kptr in dst arg */ 7974 if (meta->func_id == BPF_FUNC_kptr_xchg) { 7975 int regno = reg_from_argno(argno); 7976 7977 if (regno == BPF_REG_2 && 7978 map_kptr_match_type(env, meta->kptr_field, reg, regno)) 7979 return -EACCES; 7980 } 7981 break; 7982 case PTR_TO_BTF_ID | MEM_PERCPU: 7983 case PTR_TO_BTF_ID | MEM_PERCPU | MEM_RCU: 7984 case PTR_TO_BTF_ID | MEM_PERCPU | PTR_TRUSTED: 7985 /* Handled by helper specific checks */ 7986 break; 7987 default: 7988 verifier_bug(env, "invalid PTR_TO_BTF_ID register for type match"); 7989 return -EFAULT; 7990 } 7991 return 0; 7992 } 7993 7994 static struct btf_field * 7995 reg_find_field_offset(const struct bpf_reg_state *reg, s32 off, u32 fields) 7996 { 7997 struct btf_field *field; 7998 struct btf_record *rec; 7999 8000 rec = reg_btf_record(reg); 8001 if (!rec) 8002 return NULL; 8003 8004 field = btf_record_find(rec, off, fields); 8005 if (!field) 8006 return NULL; 8007 8008 return field; 8009 } 8010 8011 static int check_func_arg_reg_off(struct bpf_verifier_env *env, 8012 const struct bpf_reg_state *reg, argno_t argno, 8013 enum bpf_arg_type arg_type) 8014 { 8015 u32 type = reg->type; 8016 8017 /* When referenced register is passed to release function, its fixed 8018 * offset must be 0. 8019 * 8020 * We will check arg_type_is_release reg has ref_obj_id when storing 8021 * meta->release_regno. 8022 */ 8023 if (arg_type_is_release(arg_type)) { 8024 /* ARG_PTR_TO_DYNPTR with OBJ_RELEASE is a bit special, as it 8025 * may not directly point to the object being released, but to 8026 * dynptr pointing to such object, which might be at some offset 8027 * on the stack. In that case, we simply to fallback to the 8028 * default handling. 8029 */ 8030 if (arg_type_is_dynptr(arg_type) && type == PTR_TO_STACK) 8031 return 0; 8032 8033 /* Doing check_ptr_off_reg check for the offset will catch this 8034 * because fixed_off_ok is false, but checking here allows us 8035 * to give the user a better error message. 8036 */ 8037 if (!tnum_is_const(reg->var_off) || reg->var_off.value != 0) { 8038 verbose(env, "%s must have zero offset when passed to release func or trusted arg to kfunc\n", 8039 reg_arg_name(env, argno)); 8040 return -EINVAL; 8041 } 8042 } 8043 8044 switch (type) { 8045 /* Pointer types where both fixed and variable offset is explicitly allowed: */ 8046 case PTR_TO_STACK: 8047 case PTR_TO_PACKET: 8048 case PTR_TO_PACKET_META: 8049 case PTR_TO_MAP_KEY: 8050 case PTR_TO_MAP_VALUE: 8051 case PTR_TO_MEM: 8052 case PTR_TO_MEM | MEM_RDONLY: 8053 case PTR_TO_MEM | MEM_RINGBUF: 8054 case PTR_TO_BUF: 8055 case PTR_TO_BUF | MEM_RDONLY: 8056 case PTR_TO_ARENA: 8057 case SCALAR_VALUE: 8058 return 0; 8059 /* All the rest must be rejected, except PTR_TO_BTF_ID which allows 8060 * fixed offset. 8061 */ 8062 case PTR_TO_BTF_ID: 8063 case PTR_TO_BTF_ID | MEM_ALLOC: 8064 case PTR_TO_BTF_ID | PTR_TRUSTED: 8065 case PTR_TO_BTF_ID | MEM_RCU: 8066 case PTR_TO_BTF_ID | MEM_ALLOC | NON_OWN_REF: 8067 case PTR_TO_BTF_ID | MEM_ALLOC | NON_OWN_REF | MEM_RCU: 8068 /* When referenced PTR_TO_BTF_ID is passed to release function, 8069 * its fixed offset must be 0. In the other cases, fixed offset 8070 * can be non-zero. This was already checked above. So pass 8071 * fixed_off_ok as true to allow fixed offset for all other 8072 * cases. var_off always must be 0 for PTR_TO_BTF_ID, hence we 8073 * still need to do checks instead of returning. 8074 */ 8075 return __check_ptr_off_reg(env, reg, argno, true); 8076 case PTR_TO_CTX: 8077 /* 8078 * Allow fixed and variable offsets for syscall context, but 8079 * only when the argument is passed as memory, not ctx, 8080 * otherwise we may get modified ctx in tail called programs and 8081 * global subprogs (that may act as extension prog hooks). 8082 */ 8083 if (arg_type != ARG_PTR_TO_CTX && is_var_ctx_off_allowed(env->prog)) 8084 return 0; 8085 fallthrough; 8086 default: 8087 return __check_ptr_off_reg(env, reg, argno, false); 8088 } 8089 } 8090 8091 static struct bpf_reg_state *get_dynptr_arg_reg(struct bpf_verifier_env *env, 8092 const struct bpf_func_proto *fn, 8093 struct bpf_reg_state *regs) 8094 { 8095 struct bpf_reg_state *state = NULL; 8096 int i; 8097 8098 for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++) 8099 if (arg_type_is_dynptr(fn->arg_type[i])) { 8100 if (state) { 8101 verbose(env, "verifier internal error: multiple dynptr args\n"); 8102 return NULL; 8103 } 8104 state = ®s[BPF_REG_1 + i]; 8105 } 8106 8107 if (!state) 8108 verbose(env, "verifier internal error: no dynptr arg found\n"); 8109 8110 return state; 8111 } 8112 8113 static int dynptr_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 8114 { 8115 struct bpf_func_state *state = bpf_func(env, reg); 8116 int spi; 8117 8118 if (reg->type == CONST_PTR_TO_DYNPTR) 8119 return reg->id; 8120 spi = dynptr_get_spi(env, reg); 8121 if (spi < 0) 8122 return spi; 8123 return state->stack[spi].spilled_ptr.id; 8124 } 8125 8126 static int dynptr_ref_obj_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 8127 { 8128 struct bpf_func_state *state = bpf_func(env, reg); 8129 int spi; 8130 8131 if (reg->type == CONST_PTR_TO_DYNPTR) 8132 return reg->ref_obj_id; 8133 spi = dynptr_get_spi(env, reg); 8134 if (spi < 0) 8135 return spi; 8136 return state->stack[spi].spilled_ptr.ref_obj_id; 8137 } 8138 8139 static enum bpf_dynptr_type dynptr_get_type(struct bpf_verifier_env *env, 8140 struct bpf_reg_state *reg) 8141 { 8142 struct bpf_func_state *state = bpf_func(env, reg); 8143 int spi; 8144 8145 if (reg->type == CONST_PTR_TO_DYNPTR) 8146 return reg->dynptr.type; 8147 8148 spi = bpf_get_spi(reg->var_off.value); 8149 if (spi < 0) { 8150 verbose(env, "verifier internal error: invalid spi when querying dynptr type\n"); 8151 return BPF_DYNPTR_TYPE_INVALID; 8152 } 8153 8154 return state->stack[spi].spilled_ptr.dynptr.type; 8155 } 8156 8157 static int check_arg_const_str(struct bpf_verifier_env *env, 8158 struct bpf_reg_state *reg, argno_t argno) 8159 { 8160 struct bpf_map *map = reg->map_ptr; 8161 int err; 8162 int map_off; 8163 u64 map_addr; 8164 char *str_ptr; 8165 8166 if (reg->type != PTR_TO_MAP_VALUE) 8167 return -EINVAL; 8168 8169 if (map->map_type == BPF_MAP_TYPE_INSN_ARRAY) { 8170 verbose(env, "%s points to insn_array map which cannot be used as const string\n", 8171 reg_arg_name(env, argno)); 8172 return -EACCES; 8173 } 8174 8175 if (!bpf_map_is_rdonly(map)) { 8176 verbose(env, "%s does not point to a readonly map'\n", reg_arg_name(env, argno)); 8177 return -EACCES; 8178 } 8179 8180 if (!tnum_is_const(reg->var_off)) { 8181 verbose(env, "%s is not a constant address'\n", reg_arg_name(env, argno)); 8182 return -EACCES; 8183 } 8184 8185 if (!map->ops->map_direct_value_addr) { 8186 verbose(env, "no direct value access support for this map type\n"); 8187 return -EACCES; 8188 } 8189 8190 err = check_map_access(env, reg, argno, 0, 8191 map->value_size - reg->var_off.value, false, 8192 ACCESS_HELPER); 8193 if (err) 8194 return err; 8195 8196 map_off = reg->var_off.value; 8197 err = map->ops->map_direct_value_addr(map, &map_addr, map_off); 8198 if (err) { 8199 verbose(env, "direct value access on string failed\n"); 8200 return err; 8201 } 8202 8203 str_ptr = (char *)(long)(map_addr); 8204 if (!strnchr(str_ptr + map_off, map->value_size - map_off, 0)) { 8205 verbose(env, "string is not zero-terminated\n"); 8206 return -EINVAL; 8207 } 8208 return 0; 8209 } 8210 8211 /* Returns constant key value in `value` if possible, else negative error */ 8212 static int get_constant_map_key(struct bpf_verifier_env *env, 8213 struct bpf_reg_state *key, 8214 u32 key_size, 8215 s64 *value) 8216 { 8217 struct bpf_func_state *state = bpf_func(env, key); 8218 struct bpf_reg_state *reg; 8219 int slot, spi, off; 8220 int spill_size = 0; 8221 int zero_size = 0; 8222 int stack_off; 8223 int i, err; 8224 u8 *stype; 8225 8226 if (!env->bpf_capable) 8227 return -EOPNOTSUPP; 8228 if (key->type != PTR_TO_STACK) 8229 return -EOPNOTSUPP; 8230 if (!tnum_is_const(key->var_off)) 8231 return -EOPNOTSUPP; 8232 8233 stack_off = key->var_off.value; 8234 slot = -stack_off - 1; 8235 spi = slot / BPF_REG_SIZE; 8236 off = slot % BPF_REG_SIZE; 8237 stype = state->stack[spi].slot_type; 8238 8239 /* First handle precisely tracked STACK_ZERO */ 8240 for (i = off; i >= 0 && stype[i] == STACK_ZERO; i--) 8241 zero_size++; 8242 if (zero_size >= key_size) { 8243 *value = 0; 8244 return 0; 8245 } 8246 8247 /* Check that stack contains a scalar spill of expected size */ 8248 if (!bpf_is_spilled_scalar_reg(&state->stack[spi])) 8249 return -EOPNOTSUPP; 8250 for (i = off; i >= 0 && stype[i] == STACK_SPILL; i--) 8251 spill_size++; 8252 if (spill_size != key_size) 8253 return -EOPNOTSUPP; 8254 8255 reg = &state->stack[spi].spilled_ptr; 8256 if (!tnum_is_const(reg->var_off)) 8257 /* Stack value not statically known */ 8258 return -EOPNOTSUPP; 8259 8260 /* We are relying on a constant value. So mark as precise 8261 * to prevent pruning on it. 8262 */ 8263 bpf_bt_set_frame_slot(&env->bt, key->frameno, spi); 8264 err = mark_chain_precision_batch(env, env->cur_state); 8265 if (err < 0) 8266 return err; 8267 8268 *value = reg->var_off.value; 8269 return 0; 8270 } 8271 8272 static bool can_elide_value_nullness(enum bpf_map_type type); 8273 8274 static int check_func_arg(struct bpf_verifier_env *env, u32 arg, 8275 struct bpf_call_arg_meta *meta, 8276 const struct bpf_func_proto *fn, 8277 int insn_idx) 8278 { 8279 u32 regno = BPF_REG_1 + arg; 8280 struct bpf_reg_state *reg = reg_state(env, regno); 8281 enum bpf_arg_type arg_type = fn->arg_type[arg]; 8282 enum bpf_reg_type type = reg->type; 8283 u32 *arg_btf_id = NULL; 8284 u32 key_size; 8285 int err = 0; 8286 8287 if (arg_type == ARG_DONTCARE) 8288 return 0; 8289 8290 err = check_reg_arg(env, regno, SRC_OP); 8291 if (err) 8292 return err; 8293 8294 if (arg_type == ARG_ANYTHING) { 8295 if (is_pointer_value(env, regno)) { 8296 verbose(env, "R%d leaks addr into helper function\n", 8297 regno); 8298 return -EACCES; 8299 } 8300 return 0; 8301 } 8302 8303 if (type_is_pkt_pointer(type) && 8304 !may_access_direct_pkt_data(env, meta, BPF_READ)) { 8305 verbose(env, "helper access to the packet is not allowed\n"); 8306 return -EACCES; 8307 } 8308 8309 if (base_type(arg_type) == ARG_PTR_TO_MAP_VALUE) { 8310 err = resolve_map_arg_type(env, meta, &arg_type); 8311 if (err) 8312 return err; 8313 } 8314 8315 if (bpf_register_is_null(reg) && type_may_be_null(arg_type)) 8316 /* A NULL register has a SCALAR_VALUE type, so skip 8317 * type checking. 8318 */ 8319 goto skip_type_check; 8320 8321 /* arg_btf_id and arg_size are in a union. */ 8322 if (base_type(arg_type) == ARG_PTR_TO_BTF_ID || 8323 base_type(arg_type) == ARG_PTR_TO_SPIN_LOCK) 8324 arg_btf_id = fn->arg_btf_id[arg]; 8325 8326 err = check_reg_type(env, reg, argno_from_reg(regno), arg_type, arg_btf_id, meta); 8327 if (err) 8328 return err; 8329 8330 err = check_func_arg_reg_off(env, reg, argno_from_reg(regno), arg_type); 8331 if (err) 8332 return err; 8333 8334 skip_type_check: 8335 if (arg_type_is_release(arg_type)) { 8336 if (arg_type_is_dynptr(arg_type)) { 8337 struct bpf_func_state *state = bpf_func(env, reg); 8338 int spi; 8339 8340 /* Only dynptr created on stack can be released, thus 8341 * the get_spi and stack state checks for spilled_ptr 8342 * should only be done before process_dynptr_func for 8343 * PTR_TO_STACK. 8344 */ 8345 if (reg->type == PTR_TO_STACK) { 8346 spi = dynptr_get_spi(env, reg); 8347 if (spi < 0 || !state->stack[spi].spilled_ptr.ref_obj_id) { 8348 verbose(env, "arg %d is an unacquired reference\n", regno); 8349 return -EINVAL; 8350 } 8351 } else { 8352 verbose(env, "cannot release unowned const bpf_dynptr\n"); 8353 return -EINVAL; 8354 } 8355 } else if (!reg->ref_obj_id && !bpf_register_is_null(reg)) { 8356 verbose(env, "R%d must be referenced when passed to release function\n", 8357 regno); 8358 return -EINVAL; 8359 } 8360 if (meta->release_regno) { 8361 verifier_bug(env, "more than one release argument"); 8362 return -EFAULT; 8363 } 8364 meta->release_regno = regno; 8365 } 8366 8367 if (reg->ref_obj_id && base_type(arg_type) != ARG_KPTR_XCHG_DEST) { 8368 if (meta->ref_obj_id) { 8369 verbose(env, "more than one arg with ref_obj_id R%d %u %u", 8370 regno, reg->ref_obj_id, 8371 meta->ref_obj_id); 8372 return -EACCES; 8373 } 8374 meta->ref_obj_id = reg->ref_obj_id; 8375 } 8376 8377 switch (base_type(arg_type)) { 8378 case ARG_CONST_MAP_PTR: 8379 /* bpf_map_xxx(map_ptr) call: remember that map_ptr */ 8380 if (meta->map.ptr) { 8381 /* Use map_uid (which is unique id of inner map) to reject: 8382 * inner_map1 = bpf_map_lookup_elem(outer_map, key1) 8383 * inner_map2 = bpf_map_lookup_elem(outer_map, key2) 8384 * if (inner_map1 && inner_map2) { 8385 * timer = bpf_map_lookup_elem(inner_map1); 8386 * if (timer) 8387 * // mismatch would have been allowed 8388 * bpf_timer_init(timer, inner_map2); 8389 * } 8390 * 8391 * Comparing map_ptr is enough to distinguish normal and outer maps. 8392 */ 8393 if (meta->map.ptr != reg->map_ptr || 8394 meta->map.uid != reg->map_uid) { 8395 verbose(env, 8396 "timer pointer in R1 map_uid=%d doesn't match map pointer in R2 map_uid=%d\n", 8397 meta->map.uid, reg->map_uid); 8398 return -EINVAL; 8399 } 8400 } 8401 meta->map.ptr = reg->map_ptr; 8402 meta->map.uid = reg->map_uid; 8403 break; 8404 case ARG_PTR_TO_MAP_KEY: 8405 /* bpf_map_xxx(..., map_ptr, ..., key) call: 8406 * check that [key, key + map->key_size) are within 8407 * stack limits and initialized 8408 */ 8409 if (!meta->map.ptr) { 8410 /* in function declaration map_ptr must come before 8411 * map_key, so that it's verified and known before 8412 * we have to check map_key here. Otherwise it means 8413 * that kernel subsystem misconfigured verifier 8414 */ 8415 verifier_bug(env, "invalid map_ptr to access map->key"); 8416 return -EFAULT; 8417 } 8418 key_size = meta->map.ptr->key_size; 8419 err = check_helper_mem_access(env, reg, argno_from_reg(regno), key_size, BPF_READ, false, NULL); 8420 if (err) 8421 return err; 8422 if (can_elide_value_nullness(meta->map.ptr->map_type)) { 8423 err = get_constant_map_key(env, reg, key_size, &meta->const_map_key); 8424 if (err < 0) { 8425 meta->const_map_key = -1; 8426 if (err == -EOPNOTSUPP) 8427 err = 0; 8428 else 8429 return err; 8430 } 8431 } 8432 break; 8433 case ARG_PTR_TO_MAP_VALUE: 8434 if (type_may_be_null(arg_type) && bpf_register_is_null(reg)) 8435 return 0; 8436 8437 /* bpf_map_xxx(..., map_ptr, ..., value) call: 8438 * check [value, value + map->value_size) validity 8439 */ 8440 if (!meta->map.ptr) { 8441 /* kernel subsystem misconfigured verifier */ 8442 verifier_bug(env, "invalid map_ptr to access map->value"); 8443 return -EFAULT; 8444 } 8445 meta->raw_mode = arg_type & MEM_UNINIT; 8446 err = check_helper_mem_access(env, reg, argno_from_reg(regno), meta->map.ptr->value_size, 8447 arg_type & MEM_WRITE ? BPF_WRITE : BPF_READ, 8448 false, meta); 8449 break; 8450 case ARG_PTR_TO_PERCPU_BTF_ID: 8451 if (!reg->btf_id) { 8452 verbose(env, "Helper has invalid btf_id in R%d\n", regno); 8453 return -EACCES; 8454 } 8455 meta->ret_btf = reg->btf; 8456 meta->ret_btf_id = reg->btf_id; 8457 break; 8458 case ARG_PTR_TO_SPIN_LOCK: 8459 if (in_rbtree_lock_required_cb(env)) { 8460 verbose(env, "can't spin_{lock,unlock} in rbtree cb\n"); 8461 return -EACCES; 8462 } 8463 if (meta->func_id == BPF_FUNC_spin_lock) { 8464 err = process_spin_lock(env, reg, argno_from_reg(regno), PROCESS_SPIN_LOCK); 8465 if (err) 8466 return err; 8467 } else if (meta->func_id == BPF_FUNC_spin_unlock) { 8468 err = process_spin_lock(env, reg, argno_from_reg(regno), 0); 8469 if (err) 8470 return err; 8471 } else { 8472 verifier_bug(env, "spin lock arg on unexpected helper"); 8473 return -EFAULT; 8474 } 8475 break; 8476 case ARG_PTR_TO_TIMER: 8477 err = process_timer_helper(env, reg, argno_from_reg(regno), meta); 8478 if (err) 8479 return err; 8480 break; 8481 case ARG_PTR_TO_FUNC: 8482 meta->subprogno = reg->subprogno; 8483 break; 8484 case ARG_PTR_TO_MEM: 8485 /* The access to this pointer is only checked when we hit the 8486 * next is_mem_size argument below. 8487 */ 8488 meta->raw_mode = arg_type & MEM_UNINIT; 8489 if (arg_type & MEM_FIXED_SIZE) { 8490 err = check_helper_mem_access(env, reg, argno_from_reg(regno), fn->arg_size[arg], 8491 arg_type & MEM_WRITE ? BPF_WRITE : BPF_READ, 8492 false, meta); 8493 if (err) 8494 return err; 8495 if (arg_type & MEM_ALIGNED) 8496 err = check_ptr_alignment(env, reg, 0, fn->arg_size[arg], true); 8497 } 8498 break; 8499 case ARG_CONST_SIZE: 8500 err = check_mem_size_reg(env, reg_state(env, regno - 1), reg, argno_from_reg(regno - 1), 8501 argno_from_reg(regno), 8502 fn->arg_type[arg - 1] & MEM_WRITE ? 8503 BPF_WRITE : BPF_READ, 8504 false, meta); 8505 break; 8506 case ARG_CONST_SIZE_OR_ZERO: 8507 err = check_mem_size_reg(env, reg_state(env, regno - 1), reg, argno_from_reg(regno - 1), 8508 argno_from_reg(regno), 8509 fn->arg_type[arg - 1] & MEM_WRITE ? 8510 BPF_WRITE : BPF_READ, 8511 true, meta); 8512 break; 8513 case ARG_PTR_TO_DYNPTR: 8514 err = process_dynptr_func(env, reg, argno_from_reg(regno), insn_idx, arg_type, 0); 8515 if (err) 8516 return err; 8517 break; 8518 case ARG_CONST_ALLOC_SIZE_OR_ZERO: 8519 if (!tnum_is_const(reg->var_off)) { 8520 verbose(env, "R%d is not a known constant'\n", 8521 regno); 8522 return -EACCES; 8523 } 8524 meta->mem_size = reg->var_off.value; 8525 err = mark_chain_precision(env, regno); 8526 if (err) 8527 return err; 8528 break; 8529 case ARG_PTR_TO_CONST_STR: 8530 { 8531 err = check_arg_const_str(env, reg, argno_from_reg(regno)); 8532 if (err) 8533 return err; 8534 break; 8535 } 8536 case ARG_KPTR_XCHG_DEST: 8537 err = process_kptr_func(env, regno, meta); 8538 if (err) 8539 return err; 8540 break; 8541 } 8542 8543 return err; 8544 } 8545 8546 static bool may_update_sockmap(struct bpf_verifier_env *env, int func_id) 8547 { 8548 enum bpf_attach_type eatype = env->prog->expected_attach_type; 8549 enum bpf_prog_type type = resolve_prog_type(env->prog); 8550 8551 if (func_id != BPF_FUNC_map_update_elem && 8552 func_id != BPF_FUNC_map_delete_elem) 8553 return false; 8554 8555 /* It's not possible to get access to a locked struct sock in these 8556 * contexts, so updating is safe. 8557 */ 8558 switch (type) { 8559 case BPF_PROG_TYPE_TRACING: 8560 if (eatype == BPF_TRACE_ITER) 8561 return true; 8562 break; 8563 case BPF_PROG_TYPE_SOCK_OPS: 8564 /* map_update allowed only via dedicated helpers with event type checks */ 8565 if (func_id == BPF_FUNC_map_delete_elem) 8566 return true; 8567 break; 8568 case BPF_PROG_TYPE_SOCKET_FILTER: 8569 case BPF_PROG_TYPE_SCHED_CLS: 8570 case BPF_PROG_TYPE_SCHED_ACT: 8571 case BPF_PROG_TYPE_XDP: 8572 case BPF_PROG_TYPE_SK_REUSEPORT: 8573 case BPF_PROG_TYPE_FLOW_DISSECTOR: 8574 case BPF_PROG_TYPE_SK_LOOKUP: 8575 return true; 8576 default: 8577 break; 8578 } 8579 8580 verbose(env, "cannot update sockmap in this context\n"); 8581 return false; 8582 } 8583 8584 bool bpf_allow_tail_call_in_subprogs(struct bpf_verifier_env *env) 8585 { 8586 return env->prog->jit_requested && 8587 bpf_jit_supports_subprog_tailcalls(); 8588 } 8589 8590 static int check_map_func_compatibility(struct bpf_verifier_env *env, 8591 struct bpf_map *map, int func_id) 8592 { 8593 if (!map) 8594 return 0; 8595 8596 /* We need a two way check, first is from map perspective ... */ 8597 switch (map->map_type) { 8598 case BPF_MAP_TYPE_PROG_ARRAY: 8599 if (func_id != BPF_FUNC_tail_call) 8600 goto error; 8601 break; 8602 case BPF_MAP_TYPE_PERF_EVENT_ARRAY: 8603 if (func_id != BPF_FUNC_perf_event_read && 8604 func_id != BPF_FUNC_perf_event_output && 8605 func_id != BPF_FUNC_skb_output && 8606 func_id != BPF_FUNC_perf_event_read_value && 8607 func_id != BPF_FUNC_xdp_output) 8608 goto error; 8609 break; 8610 case BPF_MAP_TYPE_RINGBUF: 8611 if (func_id != BPF_FUNC_ringbuf_output && 8612 func_id != BPF_FUNC_ringbuf_reserve && 8613 func_id != BPF_FUNC_ringbuf_query && 8614 func_id != BPF_FUNC_ringbuf_reserve_dynptr && 8615 func_id != BPF_FUNC_ringbuf_submit_dynptr && 8616 func_id != BPF_FUNC_ringbuf_discard_dynptr) 8617 goto error; 8618 break; 8619 case BPF_MAP_TYPE_USER_RINGBUF: 8620 if (func_id != BPF_FUNC_user_ringbuf_drain) 8621 goto error; 8622 break; 8623 case BPF_MAP_TYPE_STACK_TRACE: 8624 if (func_id != BPF_FUNC_get_stackid) 8625 goto error; 8626 break; 8627 case BPF_MAP_TYPE_CGROUP_ARRAY: 8628 if (func_id != BPF_FUNC_skb_under_cgroup && 8629 func_id != BPF_FUNC_current_task_under_cgroup) 8630 goto error; 8631 break; 8632 case BPF_MAP_TYPE_CGROUP_STORAGE: 8633 case BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE: 8634 if (func_id != BPF_FUNC_get_local_storage) 8635 goto error; 8636 break; 8637 case BPF_MAP_TYPE_DEVMAP: 8638 case BPF_MAP_TYPE_DEVMAP_HASH: 8639 if (func_id != BPF_FUNC_redirect_map && 8640 func_id != BPF_FUNC_map_lookup_elem) 8641 goto error; 8642 break; 8643 /* Restrict bpf side of cpumap and xskmap, open when use-cases 8644 * appear. 8645 */ 8646 case BPF_MAP_TYPE_CPUMAP: 8647 if (func_id != BPF_FUNC_redirect_map) 8648 goto error; 8649 break; 8650 case BPF_MAP_TYPE_XSKMAP: 8651 if (func_id != BPF_FUNC_redirect_map && 8652 func_id != BPF_FUNC_map_lookup_elem) 8653 goto error; 8654 break; 8655 case BPF_MAP_TYPE_ARRAY_OF_MAPS: 8656 case BPF_MAP_TYPE_HASH_OF_MAPS: 8657 if (func_id != BPF_FUNC_map_lookup_elem) 8658 goto error; 8659 break; 8660 case BPF_MAP_TYPE_SOCKMAP: 8661 if (func_id != BPF_FUNC_sk_redirect_map && 8662 func_id != BPF_FUNC_sock_map_update && 8663 func_id != BPF_FUNC_msg_redirect_map && 8664 func_id != BPF_FUNC_sk_select_reuseport && 8665 func_id != BPF_FUNC_map_lookup_elem && 8666 !may_update_sockmap(env, func_id)) 8667 goto error; 8668 break; 8669 case BPF_MAP_TYPE_SOCKHASH: 8670 if (func_id != BPF_FUNC_sk_redirect_hash && 8671 func_id != BPF_FUNC_sock_hash_update && 8672 func_id != BPF_FUNC_msg_redirect_hash && 8673 func_id != BPF_FUNC_sk_select_reuseport && 8674 func_id != BPF_FUNC_map_lookup_elem && 8675 !may_update_sockmap(env, func_id)) 8676 goto error; 8677 break; 8678 case BPF_MAP_TYPE_REUSEPORT_SOCKARRAY: 8679 if (func_id != BPF_FUNC_sk_select_reuseport) 8680 goto error; 8681 break; 8682 case BPF_MAP_TYPE_QUEUE: 8683 case BPF_MAP_TYPE_STACK: 8684 if (func_id != BPF_FUNC_map_peek_elem && 8685 func_id != BPF_FUNC_map_pop_elem && 8686 func_id != BPF_FUNC_map_push_elem) 8687 goto error; 8688 break; 8689 case BPF_MAP_TYPE_SK_STORAGE: 8690 if (func_id != BPF_FUNC_sk_storage_get && 8691 func_id != BPF_FUNC_sk_storage_delete && 8692 func_id != BPF_FUNC_kptr_xchg) 8693 goto error; 8694 break; 8695 case BPF_MAP_TYPE_INODE_STORAGE: 8696 if (func_id != BPF_FUNC_inode_storage_get && 8697 func_id != BPF_FUNC_inode_storage_delete && 8698 func_id != BPF_FUNC_kptr_xchg) 8699 goto error; 8700 break; 8701 case BPF_MAP_TYPE_TASK_STORAGE: 8702 if (func_id != BPF_FUNC_task_storage_get && 8703 func_id != BPF_FUNC_task_storage_delete && 8704 func_id != BPF_FUNC_kptr_xchg) 8705 goto error; 8706 break; 8707 case BPF_MAP_TYPE_CGRP_STORAGE: 8708 if (func_id != BPF_FUNC_cgrp_storage_get && 8709 func_id != BPF_FUNC_cgrp_storage_delete && 8710 func_id != BPF_FUNC_kptr_xchg) 8711 goto error; 8712 break; 8713 case BPF_MAP_TYPE_BLOOM_FILTER: 8714 if (func_id != BPF_FUNC_map_peek_elem && 8715 func_id != BPF_FUNC_map_push_elem) 8716 goto error; 8717 break; 8718 case BPF_MAP_TYPE_INSN_ARRAY: 8719 goto error; 8720 default: 8721 break; 8722 } 8723 8724 /* ... and second from the function itself. */ 8725 switch (func_id) { 8726 case BPF_FUNC_tail_call: 8727 if (map->map_type != BPF_MAP_TYPE_PROG_ARRAY) 8728 goto error; 8729 if (env->subprog_cnt > 1 && !bpf_allow_tail_call_in_subprogs(env)) { 8730 verbose(env, "mixing of tail_calls and bpf-to-bpf calls is not supported\n"); 8731 return -EINVAL; 8732 } 8733 break; 8734 case BPF_FUNC_perf_event_read: 8735 case BPF_FUNC_perf_event_output: 8736 case BPF_FUNC_perf_event_read_value: 8737 case BPF_FUNC_skb_output: 8738 case BPF_FUNC_xdp_output: 8739 if (map->map_type != BPF_MAP_TYPE_PERF_EVENT_ARRAY) 8740 goto error; 8741 break; 8742 case BPF_FUNC_ringbuf_output: 8743 case BPF_FUNC_ringbuf_reserve: 8744 case BPF_FUNC_ringbuf_query: 8745 case BPF_FUNC_ringbuf_reserve_dynptr: 8746 case BPF_FUNC_ringbuf_submit_dynptr: 8747 case BPF_FUNC_ringbuf_discard_dynptr: 8748 if (map->map_type != BPF_MAP_TYPE_RINGBUF) 8749 goto error; 8750 break; 8751 case BPF_FUNC_user_ringbuf_drain: 8752 if (map->map_type != BPF_MAP_TYPE_USER_RINGBUF) 8753 goto error; 8754 break; 8755 case BPF_FUNC_get_stackid: 8756 if (map->map_type != BPF_MAP_TYPE_STACK_TRACE) 8757 goto error; 8758 break; 8759 case BPF_FUNC_current_task_under_cgroup: 8760 case BPF_FUNC_skb_under_cgroup: 8761 if (map->map_type != BPF_MAP_TYPE_CGROUP_ARRAY) 8762 goto error; 8763 break; 8764 case BPF_FUNC_redirect_map: 8765 if (map->map_type != BPF_MAP_TYPE_DEVMAP && 8766 map->map_type != BPF_MAP_TYPE_DEVMAP_HASH && 8767 map->map_type != BPF_MAP_TYPE_CPUMAP && 8768 map->map_type != BPF_MAP_TYPE_XSKMAP) 8769 goto error; 8770 break; 8771 case BPF_FUNC_sk_redirect_map: 8772 case BPF_FUNC_msg_redirect_map: 8773 case BPF_FUNC_sock_map_update: 8774 if (map->map_type != BPF_MAP_TYPE_SOCKMAP) 8775 goto error; 8776 break; 8777 case BPF_FUNC_sk_redirect_hash: 8778 case BPF_FUNC_msg_redirect_hash: 8779 case BPF_FUNC_sock_hash_update: 8780 if (map->map_type != BPF_MAP_TYPE_SOCKHASH) 8781 goto error; 8782 break; 8783 case BPF_FUNC_get_local_storage: 8784 if (map->map_type != BPF_MAP_TYPE_CGROUP_STORAGE && 8785 map->map_type != BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE) 8786 goto error; 8787 break; 8788 case BPF_FUNC_sk_select_reuseport: 8789 if (map->map_type != BPF_MAP_TYPE_REUSEPORT_SOCKARRAY && 8790 map->map_type != BPF_MAP_TYPE_SOCKMAP && 8791 map->map_type != BPF_MAP_TYPE_SOCKHASH) 8792 goto error; 8793 break; 8794 case BPF_FUNC_map_pop_elem: 8795 if (map->map_type != BPF_MAP_TYPE_QUEUE && 8796 map->map_type != BPF_MAP_TYPE_STACK) 8797 goto error; 8798 break; 8799 case BPF_FUNC_map_peek_elem: 8800 case BPF_FUNC_map_push_elem: 8801 if (map->map_type != BPF_MAP_TYPE_QUEUE && 8802 map->map_type != BPF_MAP_TYPE_STACK && 8803 map->map_type != BPF_MAP_TYPE_BLOOM_FILTER) 8804 goto error; 8805 break; 8806 case BPF_FUNC_map_lookup_percpu_elem: 8807 if (map->map_type != BPF_MAP_TYPE_PERCPU_ARRAY && 8808 map->map_type != BPF_MAP_TYPE_PERCPU_HASH && 8809 map->map_type != BPF_MAP_TYPE_LRU_PERCPU_HASH) 8810 goto error; 8811 break; 8812 case BPF_FUNC_sk_storage_get: 8813 case BPF_FUNC_sk_storage_delete: 8814 if (map->map_type != BPF_MAP_TYPE_SK_STORAGE) 8815 goto error; 8816 break; 8817 case BPF_FUNC_inode_storage_get: 8818 case BPF_FUNC_inode_storage_delete: 8819 if (map->map_type != BPF_MAP_TYPE_INODE_STORAGE) 8820 goto error; 8821 break; 8822 case BPF_FUNC_task_storage_get: 8823 case BPF_FUNC_task_storage_delete: 8824 if (map->map_type != BPF_MAP_TYPE_TASK_STORAGE) 8825 goto error; 8826 break; 8827 case BPF_FUNC_cgrp_storage_get: 8828 case BPF_FUNC_cgrp_storage_delete: 8829 if (map->map_type != BPF_MAP_TYPE_CGRP_STORAGE) 8830 goto error; 8831 break; 8832 default: 8833 break; 8834 } 8835 8836 return 0; 8837 error: 8838 verbose(env, "cannot pass map_type %d into func %s#%d\n", 8839 map->map_type, func_id_name(func_id), func_id); 8840 return -EINVAL; 8841 } 8842 8843 static bool check_raw_mode_ok(const struct bpf_func_proto *fn) 8844 { 8845 int count = 0; 8846 8847 if (arg_type_is_raw_mem(fn->arg1_type)) 8848 count++; 8849 if (arg_type_is_raw_mem(fn->arg2_type)) 8850 count++; 8851 if (arg_type_is_raw_mem(fn->arg3_type)) 8852 count++; 8853 if (arg_type_is_raw_mem(fn->arg4_type)) 8854 count++; 8855 if (arg_type_is_raw_mem(fn->arg5_type)) 8856 count++; 8857 8858 /* We only support one arg being in raw mode at the moment, 8859 * which is sufficient for the helper functions we have 8860 * right now. 8861 */ 8862 return count <= 1; 8863 } 8864 8865 static bool check_args_pair_invalid(const struct bpf_func_proto *fn, int arg) 8866 { 8867 bool is_fixed = fn->arg_type[arg] & MEM_FIXED_SIZE; 8868 bool has_size = fn->arg_size[arg] != 0; 8869 bool is_next_size = false; 8870 8871 if (arg + 1 < ARRAY_SIZE(fn->arg_type)) 8872 is_next_size = arg_type_is_mem_size(fn->arg_type[arg + 1]); 8873 8874 if (base_type(fn->arg_type[arg]) != ARG_PTR_TO_MEM) 8875 return is_next_size; 8876 8877 return has_size == is_next_size || is_next_size == is_fixed; 8878 } 8879 8880 static bool check_arg_pair_ok(const struct bpf_func_proto *fn) 8881 { 8882 /* bpf_xxx(..., buf, len) call will access 'len' 8883 * bytes from memory 'buf'. Both arg types need 8884 * to be paired, so make sure there's no buggy 8885 * helper function specification. 8886 */ 8887 if (arg_type_is_mem_size(fn->arg1_type) || 8888 check_args_pair_invalid(fn, 0) || 8889 check_args_pair_invalid(fn, 1) || 8890 check_args_pair_invalid(fn, 2) || 8891 check_args_pair_invalid(fn, 3) || 8892 check_args_pair_invalid(fn, 4)) 8893 return false; 8894 8895 return true; 8896 } 8897 8898 static bool check_btf_id_ok(const struct bpf_func_proto *fn) 8899 { 8900 int i; 8901 8902 for (i = 0; i < ARRAY_SIZE(fn->arg_type); i++) { 8903 if (base_type(fn->arg_type[i]) == ARG_PTR_TO_BTF_ID) 8904 return !!fn->arg_btf_id[i]; 8905 if (base_type(fn->arg_type[i]) == ARG_PTR_TO_SPIN_LOCK) 8906 return fn->arg_btf_id[i] == BPF_PTR_POISON; 8907 if (base_type(fn->arg_type[i]) != ARG_PTR_TO_BTF_ID && fn->arg_btf_id[i] && 8908 /* arg_btf_id and arg_size are in a union. */ 8909 (base_type(fn->arg_type[i]) != ARG_PTR_TO_MEM || 8910 !(fn->arg_type[i] & MEM_FIXED_SIZE))) 8911 return false; 8912 } 8913 8914 return true; 8915 } 8916 8917 static bool check_mem_arg_rw_flag_ok(const struct bpf_func_proto *fn) 8918 { 8919 int i; 8920 8921 for (i = 0; i < ARRAY_SIZE(fn->arg_type); i++) { 8922 enum bpf_arg_type arg_type = fn->arg_type[i]; 8923 8924 if (base_type(arg_type) != ARG_PTR_TO_MEM) 8925 continue; 8926 if (!(arg_type & (MEM_WRITE | MEM_RDONLY))) 8927 return false; 8928 } 8929 8930 return true; 8931 } 8932 8933 static int check_func_proto(const struct bpf_func_proto *fn) 8934 { 8935 return check_raw_mode_ok(fn) && 8936 check_arg_pair_ok(fn) && 8937 check_mem_arg_rw_flag_ok(fn) && 8938 check_btf_id_ok(fn) ? 0 : -EINVAL; 8939 } 8940 8941 /* Packet data might have moved, any old PTR_TO_PACKET[_META,_END] 8942 * are now invalid, so turn them into unknown SCALAR_VALUE. 8943 * 8944 * This also applies to dynptr slices belonging to skb and xdp dynptrs, 8945 * since these slices point to packet data. 8946 */ 8947 static void clear_all_pkt_pointers(struct bpf_verifier_env *env) 8948 { 8949 struct bpf_func_state *state; 8950 struct bpf_reg_state *reg; 8951 8952 bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({ 8953 if (reg_is_pkt_pointer_any(reg) || reg_is_dynptr_slice_pkt(reg)) 8954 mark_reg_invalid(env, reg); 8955 })); 8956 } 8957 8958 enum { 8959 AT_PKT_END = -1, 8960 BEYOND_PKT_END = -2, 8961 }; 8962 8963 static void mark_pkt_end(struct bpf_verifier_state *vstate, int regn, bool range_open) 8964 { 8965 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 8966 struct bpf_reg_state *reg = &state->regs[regn]; 8967 8968 if (reg->type != PTR_TO_PACKET) 8969 /* PTR_TO_PACKET_META is not supported yet */ 8970 return; 8971 8972 /* The 'reg' is pkt > pkt_end or pkt >= pkt_end. 8973 * How far beyond pkt_end it goes is unknown. 8974 * if (!range_open) it's the case of pkt >= pkt_end 8975 * if (range_open) it's the case of pkt > pkt_end 8976 * hence this pointer is at least 1 byte bigger than pkt_end 8977 */ 8978 if (range_open) 8979 reg->range = BEYOND_PKT_END; 8980 else 8981 reg->range = AT_PKT_END; 8982 } 8983 8984 static int release_reference_nomark(struct bpf_verifier_state *state, int ref_obj_id) 8985 { 8986 int i; 8987 8988 for (i = 0; i < state->acquired_refs; i++) { 8989 if (state->refs[i].type != REF_TYPE_PTR) 8990 continue; 8991 if (state->refs[i].id == ref_obj_id) { 8992 release_reference_state(state, i); 8993 return 0; 8994 } 8995 } 8996 return -EINVAL; 8997 } 8998 8999 /* The pointer with the specified id has released its reference to kernel 9000 * resources. Identify all copies of the same pointer and clear the reference. 9001 * 9002 * This is the release function corresponding to acquire_reference(). Idempotent. 9003 */ 9004 static int release_reference(struct bpf_verifier_env *env, int ref_obj_id) 9005 { 9006 struct bpf_verifier_state *vstate = env->cur_state; 9007 struct bpf_func_state *state; 9008 struct bpf_reg_state *reg; 9009 int err; 9010 9011 err = release_reference_nomark(vstate, ref_obj_id); 9012 if (err) 9013 return err; 9014 9015 bpf_for_each_reg_in_vstate(vstate, state, reg, ({ 9016 if (reg->ref_obj_id == ref_obj_id) 9017 mark_reg_invalid(env, reg); 9018 })); 9019 9020 return 0; 9021 } 9022 9023 static void invalidate_non_owning_refs(struct bpf_verifier_env *env) 9024 { 9025 struct bpf_func_state *unused; 9026 struct bpf_reg_state *reg; 9027 9028 bpf_for_each_reg_in_vstate(env->cur_state, unused, reg, ({ 9029 if (type_is_non_owning_ref(reg->type)) 9030 mark_reg_invalid(env, reg); 9031 })); 9032 } 9033 9034 static void clear_caller_saved_regs(struct bpf_verifier_env *env, 9035 struct bpf_reg_state *regs) 9036 { 9037 int i; 9038 9039 /* after the call registers r0 - r5 were scratched */ 9040 for (i = 0; i < CALLER_SAVED_REGS; i++) { 9041 bpf_mark_reg_not_init(env, ®s[caller_saved[i]]); 9042 __check_reg_arg(env, regs, caller_saved[i], DST_OP_NO_MARK); 9043 } 9044 } 9045 9046 static void invalidate_outgoing_stack_args(const struct bpf_verifier_env *env, 9047 struct bpf_func_state *state) 9048 { 9049 int i, nslots = state->out_stack_arg_cnt; 9050 9051 for (i = 0; i < nslots; i++) 9052 bpf_mark_reg_not_init(env, &state->stack_arg_regs[i]); 9053 } 9054 9055 typedef int (*set_callee_state_fn)(struct bpf_verifier_env *env, 9056 struct bpf_func_state *caller, 9057 struct bpf_func_state *callee, 9058 int insn_idx); 9059 9060 static int set_callee_state(struct bpf_verifier_env *env, 9061 struct bpf_func_state *caller, 9062 struct bpf_func_state *callee, int insn_idx); 9063 9064 static int setup_func_entry(struct bpf_verifier_env *env, int subprog, int callsite, 9065 set_callee_state_fn set_callee_state_cb, 9066 struct bpf_verifier_state *state) 9067 { 9068 struct bpf_func_state *caller, *callee; 9069 int err; 9070 9071 if (state->curframe + 1 >= MAX_CALL_FRAMES) { 9072 verbose(env, "the call stack of %d frames is too deep\n", 9073 state->curframe + 2); 9074 return -E2BIG; 9075 } 9076 9077 if (state->frame[state->curframe + 1]) { 9078 verifier_bug(env, "Frame %d already allocated", state->curframe + 1); 9079 return -EFAULT; 9080 } 9081 9082 caller = state->frame[state->curframe]; 9083 callee = kzalloc_obj(*callee, GFP_KERNEL_ACCOUNT); 9084 if (!callee) 9085 return -ENOMEM; 9086 state->frame[state->curframe + 1] = callee; 9087 9088 /* callee cannot access r0, r6 - r9 for reading and has to write 9089 * into its own stack before reading from it. 9090 * callee can read/write into caller's stack 9091 */ 9092 init_func_state(env, callee, 9093 /* remember the callsite, it will be used by bpf_exit */ 9094 callsite, 9095 state->curframe + 1 /* frameno within this callchain */, 9096 subprog /* subprog number within this prog */); 9097 err = set_callee_state_cb(env, caller, callee, callsite); 9098 if (err) 9099 goto err_out; 9100 9101 /* only increment it after check_reg_arg() finished */ 9102 state->curframe++; 9103 9104 return 0; 9105 9106 err_out: 9107 free_func_state(callee); 9108 state->frame[state->curframe + 1] = NULL; 9109 return err; 9110 } 9111 9112 static int btf_check_func_arg_match(struct bpf_verifier_env *env, int subprog, 9113 const struct btf *btf, 9114 struct bpf_reg_state *regs) 9115 { 9116 struct bpf_subprog_info *sub = subprog_info(env, subprog); 9117 struct bpf_func_state *caller = cur_func(env); 9118 struct bpf_verifier_log *log = &env->log; 9119 u32 i; 9120 int ret, err; 9121 9122 ret = btf_prepare_func_args(env, subprog); 9123 if (ret) { 9124 if (bpf_in_stack_arg_cnt(sub) > 0) { 9125 err = check_outgoing_stack_args(env, caller, sub->arg_cnt); 9126 if (err) 9127 return err; 9128 } 9129 return ret; 9130 } 9131 9132 ret = check_outgoing_stack_args(env, caller, sub->arg_cnt); 9133 if (ret) 9134 return ret; 9135 9136 /* check that BTF function arguments match actual types that the 9137 * verifier sees. 9138 */ 9139 for (i = 0; i < sub->arg_cnt; i++) { 9140 argno_t argno = argno_from_arg(i + 1); 9141 struct bpf_reg_state *reg = get_func_arg_reg(caller, regs, i); 9142 struct bpf_subprog_arg_info *arg = &sub->args[i]; 9143 9144 if (arg->arg_type == ARG_ANYTHING) { 9145 if (reg->type != SCALAR_VALUE) { 9146 bpf_log(log, "%s is not a scalar\n", reg_arg_name(env, argno)); 9147 return -EINVAL; 9148 } 9149 } else if (arg->arg_type & PTR_UNTRUSTED) { 9150 /* 9151 * Anything is allowed for untrusted arguments, as these are 9152 * read-only and probe read instructions would protect against 9153 * invalid memory access. 9154 */ 9155 } else if (arg->arg_type == ARG_PTR_TO_CTX) { 9156 ret = check_func_arg_reg_off(env, reg, argno, ARG_PTR_TO_CTX); 9157 if (ret < 0) 9158 return ret; 9159 /* If function expects ctx type in BTF check that caller 9160 * is passing PTR_TO_CTX. 9161 */ 9162 if (reg->type != PTR_TO_CTX) { 9163 bpf_log(log, "%s expects pointer to ctx\n", 9164 reg_arg_name(env, argno)); 9165 return -EINVAL; 9166 } 9167 } else if (base_type(arg->arg_type) == ARG_PTR_TO_MEM) { 9168 ret = check_func_arg_reg_off(env, reg, argno, ARG_DONTCARE); 9169 if (ret < 0) 9170 return ret; 9171 if (check_mem_reg(env, reg, argno, arg->mem_size)) 9172 return -EINVAL; 9173 if (!(arg->arg_type & PTR_MAYBE_NULL) && (reg->type & PTR_MAYBE_NULL)) { 9174 bpf_log(log, "%s is expected to be non-NULL\n", 9175 reg_arg_name(env, argno)); 9176 return -EINVAL; 9177 } 9178 } else if (base_type(arg->arg_type) == ARG_PTR_TO_ARENA) { 9179 /* 9180 * Can pass any value and the kernel won't crash, but 9181 * only PTR_TO_ARENA or SCALAR make sense. Everything 9182 * else is a bug in the bpf program. Point it out to 9183 * the user at the verification time instead of 9184 * run-time debug nightmare. 9185 */ 9186 if (reg->type != PTR_TO_ARENA && reg->type != SCALAR_VALUE) { 9187 bpf_log(log, "%s is not a pointer to arena or scalar.\n", 9188 reg_arg_name(env, argno)); 9189 return -EINVAL; 9190 } 9191 } else if (arg->arg_type == ARG_PTR_TO_DYNPTR) { 9192 ret = check_func_arg_reg_off(env, reg, argno, ARG_PTR_TO_DYNPTR); 9193 if (ret) 9194 return ret; 9195 9196 ret = process_dynptr_func(env, reg, argno, -1, arg->arg_type, 0); 9197 if (ret) 9198 return ret; 9199 } else if (base_type(arg->arg_type) == ARG_PTR_TO_BTF_ID) { 9200 struct bpf_call_arg_meta meta; 9201 int err; 9202 9203 if (bpf_register_is_null(reg) && type_may_be_null(arg->arg_type)) 9204 continue; 9205 9206 memset(&meta, 0, sizeof(meta)); /* leave func_id as zero */ 9207 err = check_reg_type(env, reg, argno, arg->arg_type, &arg->btf_id, &meta); 9208 err = err ?: check_func_arg_reg_off(env, reg, argno, arg->arg_type); 9209 if (err) 9210 return err; 9211 } else { 9212 verifier_bug(env, "unrecognized %s type %d", 9213 reg_arg_name(env, argno), arg->arg_type); 9214 return -EFAULT; 9215 } 9216 } 9217 9218 return 0; 9219 } 9220 9221 /* Compare BTF of a function call with given bpf_reg_state. 9222 * Returns: 9223 * EFAULT - there is a verifier bug. Abort verification. 9224 * EINVAL - there is a type mismatch or BTF is not available. 9225 * 0 - BTF matches with what bpf_reg_state expects. 9226 * Only PTR_TO_CTX and SCALAR_VALUE states are recognized. 9227 */ 9228 static int btf_check_subprog_call(struct bpf_verifier_env *env, int subprog, 9229 struct bpf_reg_state *regs) 9230 { 9231 struct bpf_prog *prog = env->prog; 9232 struct btf *btf = prog->aux->btf; 9233 u32 btf_id; 9234 int err; 9235 9236 if (!prog->aux->func_info) 9237 return -EINVAL; 9238 9239 btf_id = prog->aux->func_info[subprog].type_id; 9240 if (!btf_id) 9241 return -EFAULT; 9242 9243 if (prog->aux->func_info_aux[subprog].unreliable) 9244 return -EINVAL; 9245 9246 err = btf_check_func_arg_match(env, subprog, btf, regs); 9247 /* Compiler optimizations can remove arguments from static functions 9248 * or mismatched type can be passed into a global function. 9249 * In such cases mark the function as unreliable from BTF point of view. 9250 */ 9251 if (err) 9252 prog->aux->func_info_aux[subprog].unreliable = true; 9253 return err; 9254 } 9255 9256 static int push_callback_call(struct bpf_verifier_env *env, struct bpf_insn *insn, 9257 int insn_idx, int subprog, 9258 set_callee_state_fn set_callee_state_cb) 9259 { 9260 struct bpf_verifier_state *state = env->cur_state, *callback_state; 9261 struct bpf_func_state *caller, *callee; 9262 int err; 9263 9264 caller = state->frame[state->curframe]; 9265 err = btf_check_subprog_call(env, subprog, caller->regs); 9266 if (err == -EFAULT) 9267 return err; 9268 9269 /* set_callee_state is used for direct subprog calls, but we are 9270 * interested in validating only BPF helpers that can call subprogs as 9271 * callbacks 9272 */ 9273 env->subprog_info[subprog].is_cb = true; 9274 if (bpf_pseudo_kfunc_call(insn) && 9275 !is_callback_calling_kfunc(insn->imm)) { 9276 verifier_bug(env, "kfunc %s#%d not marked as callback-calling", 9277 func_id_name(insn->imm), insn->imm); 9278 return -EFAULT; 9279 } else if (!bpf_pseudo_kfunc_call(insn) && 9280 !is_callback_calling_function(insn->imm)) { /* helper */ 9281 verifier_bug(env, "helper %s#%d not marked as callback-calling", 9282 func_id_name(insn->imm), insn->imm); 9283 return -EFAULT; 9284 } 9285 9286 if (bpf_is_async_callback_calling_insn(insn)) { 9287 struct bpf_verifier_state *async_cb; 9288 9289 /* there is no real recursion here. timer and workqueue callbacks are async */ 9290 env->subprog_info[subprog].is_async_cb = true; 9291 async_cb = push_async_cb(env, env->subprog_info[subprog].start, 9292 insn_idx, subprog, 9293 is_async_cb_sleepable(env, insn)); 9294 if (IS_ERR(async_cb)) 9295 return PTR_ERR(async_cb); 9296 callee = async_cb->frame[0]; 9297 callee->async_entry_cnt = caller->async_entry_cnt + 1; 9298 9299 /* Convert bpf_timer_set_callback() args into timer callback args */ 9300 err = set_callee_state_cb(env, caller, callee, insn_idx); 9301 if (err) 9302 return err; 9303 9304 return 0; 9305 } 9306 9307 /* for callback functions enqueue entry to callback and 9308 * proceed with next instruction within current frame. 9309 */ 9310 callback_state = push_stack(env, env->subprog_info[subprog].start, insn_idx, false); 9311 if (IS_ERR(callback_state)) 9312 return PTR_ERR(callback_state); 9313 9314 err = setup_func_entry(env, subprog, insn_idx, set_callee_state_cb, 9315 callback_state); 9316 if (err) 9317 return err; 9318 9319 callback_state->callback_unroll_depth++; 9320 callback_state->frame[callback_state->curframe - 1]->callback_depth++; 9321 caller->callback_depth = 0; 9322 return 0; 9323 } 9324 9325 static int process_bpf_exit_full(struct bpf_verifier_env *env, 9326 bool *do_print_state, bool exception_exit); 9327 9328 static int check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn, 9329 int *insn_idx) 9330 { 9331 struct bpf_verifier_state *state = env->cur_state; 9332 struct bpf_subprog_info *caller_info; 9333 u16 callee_incoming, stack_arg_cnt; 9334 struct bpf_func_state *caller; 9335 int err, subprog, target_insn; 9336 9337 target_insn = *insn_idx + insn->imm + 1; 9338 subprog = bpf_find_subprog(env, target_insn); 9339 if (verifier_bug_if(subprog < 0, env, "target of func call at insn %d is not a program", 9340 target_insn)) 9341 return -EFAULT; 9342 9343 caller = state->frame[state->curframe]; 9344 err = btf_check_subprog_call(env, subprog, caller->regs); 9345 if (err == -EFAULT) 9346 return err; 9347 if (bpf_subprog_is_global(env, subprog)) { 9348 const char *sub_name = subprog_name(env, subprog); 9349 9350 if (env->cur_state->active_locks) { 9351 verbose(env, "global function calls are not allowed while holding a lock,\n" 9352 "use static function instead\n"); 9353 return -EINVAL; 9354 } 9355 9356 if (env->subprog_info[subprog].might_sleep && !in_sleepable_context(env)) { 9357 verbose(env, "sleepable global function %s() called in %s\n", 9358 sub_name, non_sleepable_context_description(env)); 9359 return -EINVAL; 9360 } 9361 9362 if (err) { 9363 verbose(env, "Caller passes invalid args into func#%d ('%s')\n", 9364 subprog, sub_name); 9365 return err; 9366 } 9367 9368 if (env->log.level & BPF_LOG_LEVEL) 9369 verbose(env, "Func#%d ('%s') is global and assumed valid.\n", 9370 subprog, sub_name); 9371 if (env->subprog_info[subprog].changes_pkt_data) 9372 clear_all_pkt_pointers(env); 9373 /* mark global subprog for verifying after main prog */ 9374 subprog_aux(env, subprog)->called = true; 9375 clear_caller_saved_regs(env, caller->regs); 9376 invalidate_outgoing_stack_args(env, cur_func(env)); 9377 9378 /* All non-void global functions return a 64-bit SCALAR_VALUE. */ 9379 if (!subprog_returns_void(env, subprog)) { 9380 mark_reg_unknown(env, caller->regs, BPF_REG_0); 9381 caller->regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG; 9382 } 9383 9384 if (env->subprog_info[subprog].might_throw) { 9385 struct bpf_verifier_state *branch; 9386 9387 branch = push_stack(env, *insn_idx + 1, *insn_idx, false); 9388 if (IS_ERR(branch)) { 9389 verbose(env, "failed to push state for global subprog exception path\n"); 9390 return PTR_ERR(branch); 9391 } 9392 return process_bpf_exit_full(env, NULL, true); 9393 } 9394 9395 /* continue with next insn after call */ 9396 return 0; 9397 } 9398 9399 /* 9400 * Track caller's total stack arg count (incoming + max outgoing). 9401 * This is needed so the JIT knows how much stack arg space to allocate. 9402 */ 9403 caller_info = &env->subprog_info[caller->subprogno]; 9404 callee_incoming = bpf_in_stack_arg_cnt(&env->subprog_info[subprog]); 9405 stack_arg_cnt = bpf_in_stack_arg_cnt(caller_info) + callee_incoming; 9406 if (stack_arg_cnt > caller_info->stack_arg_cnt) 9407 caller_info->stack_arg_cnt = stack_arg_cnt; 9408 9409 /* for regular function entry setup new frame and continue 9410 * from that frame. 9411 */ 9412 err = setup_func_entry(env, subprog, *insn_idx, set_callee_state, state); 9413 if (err) 9414 return err; 9415 9416 clear_caller_saved_regs(env, caller->regs); 9417 9418 /* and go analyze first insn of the callee */ 9419 *insn_idx = env->subprog_info[subprog].start - 1; 9420 9421 if (env->log.level & BPF_LOG_LEVEL) { 9422 verbose(env, "caller:\n"); 9423 print_verifier_state(env, state, caller->frameno, true); 9424 verbose(env, "callee:\n"); 9425 print_verifier_state(env, state, state->curframe, true); 9426 } 9427 9428 return 0; 9429 } 9430 9431 int map_set_for_each_callback_args(struct bpf_verifier_env *env, 9432 struct bpf_func_state *caller, 9433 struct bpf_func_state *callee) 9434 { 9435 /* bpf_for_each_map_elem(struct bpf_map *map, void *callback_fn, 9436 * void *callback_ctx, u64 flags); 9437 * callback_fn(struct bpf_map *map, void *key, void *value, 9438 * void *callback_ctx); 9439 */ 9440 callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1]; 9441 9442 callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY; 9443 __mark_reg_known_zero(&callee->regs[BPF_REG_2]); 9444 callee->regs[BPF_REG_2].map_ptr = caller->regs[BPF_REG_1].map_ptr; 9445 9446 callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE; 9447 __mark_reg_known_zero(&callee->regs[BPF_REG_3]); 9448 callee->regs[BPF_REG_3].map_ptr = caller->regs[BPF_REG_1].map_ptr; 9449 9450 /* pointer to stack or null */ 9451 callee->regs[BPF_REG_4] = caller->regs[BPF_REG_3]; 9452 9453 /* unused */ 9454 bpf_mark_reg_not_init(env, &callee->regs[BPF_REG_5]); 9455 return 0; 9456 } 9457 9458 static int set_callee_state(struct bpf_verifier_env *env, 9459 struct bpf_func_state *caller, 9460 struct bpf_func_state *callee, int insn_idx) 9461 { 9462 int i; 9463 9464 /* copy r1 - r5 args that callee can access. The copy includes parent 9465 * pointers, which connects us up to the liveness chain 9466 */ 9467 for (i = BPF_REG_1; i <= BPF_REG_5; i++) 9468 callee->regs[i] = caller->regs[i]; 9469 return 0; 9470 } 9471 9472 static int set_map_elem_callback_state(struct bpf_verifier_env *env, 9473 struct bpf_func_state *caller, 9474 struct bpf_func_state *callee, 9475 int insn_idx) 9476 { 9477 struct bpf_insn_aux_data *insn_aux = &env->insn_aux_data[insn_idx]; 9478 struct bpf_map *map; 9479 int err; 9480 9481 /* valid map_ptr and poison value does not matter */ 9482 map = insn_aux->map_ptr_state.map_ptr; 9483 if (!map->ops->map_set_for_each_callback_args || 9484 !map->ops->map_for_each_callback) { 9485 verbose(env, "callback function not allowed for map\n"); 9486 return -ENOTSUPP; 9487 } 9488 9489 err = map->ops->map_set_for_each_callback_args(env, caller, callee); 9490 if (err) 9491 return err; 9492 9493 callee->in_callback_fn = true; 9494 callee->callback_ret_range = retval_range(0, 1); 9495 return 0; 9496 } 9497 9498 static int set_loop_callback_state(struct bpf_verifier_env *env, 9499 struct bpf_func_state *caller, 9500 struct bpf_func_state *callee, 9501 int insn_idx) 9502 { 9503 /* bpf_loop(u32 nr_loops, void *callback_fn, void *callback_ctx, 9504 * u64 flags); 9505 * callback_fn(u64 index, void *callback_ctx); 9506 */ 9507 callee->regs[BPF_REG_1].type = SCALAR_VALUE; 9508 callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3]; 9509 9510 /* unused */ 9511 bpf_mark_reg_not_init(env, &callee->regs[BPF_REG_3]); 9512 bpf_mark_reg_not_init(env, &callee->regs[BPF_REG_4]); 9513 bpf_mark_reg_not_init(env, &callee->regs[BPF_REG_5]); 9514 9515 callee->in_callback_fn = true; 9516 callee->callback_ret_range = retval_range(0, 1); 9517 return 0; 9518 } 9519 9520 static int set_timer_callback_state(struct bpf_verifier_env *env, 9521 struct bpf_func_state *caller, 9522 struct bpf_func_state *callee, 9523 int insn_idx) 9524 { 9525 struct bpf_map *map_ptr = caller->regs[BPF_REG_1].map_ptr; 9526 9527 /* bpf_timer_set_callback(struct bpf_timer *timer, void *callback_fn); 9528 * callback_fn(struct bpf_map *map, void *key, void *value); 9529 */ 9530 callee->regs[BPF_REG_1].type = CONST_PTR_TO_MAP; 9531 __mark_reg_known_zero(&callee->regs[BPF_REG_1]); 9532 callee->regs[BPF_REG_1].map_ptr = map_ptr; 9533 9534 callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY; 9535 __mark_reg_known_zero(&callee->regs[BPF_REG_2]); 9536 callee->regs[BPF_REG_2].map_ptr = map_ptr; 9537 9538 callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE; 9539 __mark_reg_known_zero(&callee->regs[BPF_REG_3]); 9540 callee->regs[BPF_REG_3].map_ptr = map_ptr; 9541 9542 /* unused */ 9543 bpf_mark_reg_not_init(env, &callee->regs[BPF_REG_4]); 9544 bpf_mark_reg_not_init(env, &callee->regs[BPF_REG_5]); 9545 callee->in_async_callback_fn = true; 9546 callee->callback_ret_range = retval_range(0, 0); 9547 return 0; 9548 } 9549 9550 static int set_find_vma_callback_state(struct bpf_verifier_env *env, 9551 struct bpf_func_state *caller, 9552 struct bpf_func_state *callee, 9553 int insn_idx) 9554 { 9555 /* bpf_find_vma(struct task_struct *task, u64 addr, 9556 * void *callback_fn, void *callback_ctx, u64 flags) 9557 * (callback_fn)(struct task_struct *task, 9558 * struct vm_area_struct *vma, void *callback_ctx); 9559 */ 9560 callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1]; 9561 9562 callee->regs[BPF_REG_2].type = PTR_TO_BTF_ID; 9563 __mark_reg_known_zero(&callee->regs[BPF_REG_2]); 9564 callee->regs[BPF_REG_2].btf = btf_vmlinux; 9565 callee->regs[BPF_REG_2].btf_id = btf_tracing_ids[BTF_TRACING_TYPE_VMA]; 9566 9567 /* pointer to stack or null */ 9568 callee->regs[BPF_REG_3] = caller->regs[BPF_REG_4]; 9569 9570 /* unused */ 9571 bpf_mark_reg_not_init(env, &callee->regs[BPF_REG_4]); 9572 bpf_mark_reg_not_init(env, &callee->regs[BPF_REG_5]); 9573 callee->in_callback_fn = true; 9574 callee->callback_ret_range = retval_range(0, 1); 9575 return 0; 9576 } 9577 9578 static int set_user_ringbuf_callback_state(struct bpf_verifier_env *env, 9579 struct bpf_func_state *caller, 9580 struct bpf_func_state *callee, 9581 int insn_idx) 9582 { 9583 /* bpf_user_ringbuf_drain(struct bpf_map *map, void *callback_fn, void 9584 * callback_ctx, u64 flags); 9585 * callback_fn(const struct bpf_dynptr_t* dynptr, void *callback_ctx); 9586 */ 9587 bpf_mark_reg_not_init(env, &callee->regs[BPF_REG_0]); 9588 mark_dynptr_cb_reg(env, &callee->regs[BPF_REG_1], BPF_DYNPTR_TYPE_LOCAL); 9589 callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3]; 9590 9591 /* unused */ 9592 bpf_mark_reg_not_init(env, &callee->regs[BPF_REG_3]); 9593 bpf_mark_reg_not_init(env, &callee->regs[BPF_REG_4]); 9594 bpf_mark_reg_not_init(env, &callee->regs[BPF_REG_5]); 9595 9596 callee->in_callback_fn = true; 9597 callee->callback_ret_range = retval_range(0, 1); 9598 return 0; 9599 } 9600 9601 static int set_rbtree_add_callback_state(struct bpf_verifier_env *env, 9602 struct bpf_func_state *caller, 9603 struct bpf_func_state *callee, 9604 int insn_idx) 9605 { 9606 /* void bpf_rbtree_add_impl(struct bpf_rb_root *root, struct bpf_rb_node *node, 9607 * bool (less)(struct bpf_rb_node *a, const struct bpf_rb_node *b)); 9608 * 9609 * 'struct bpf_rb_node *node' arg to bpf_rbtree_add_impl is the same PTR_TO_BTF_ID w/ offset 9610 * that 'less' callback args will be receiving. However, 'node' arg was release_reference'd 9611 * by this point, so look at 'root' 9612 */ 9613 struct btf_field *field; 9614 9615 field = reg_find_field_offset(&caller->regs[BPF_REG_1], 9616 caller->regs[BPF_REG_1].var_off.value, 9617 BPF_RB_ROOT); 9618 if (!field || !field->graph_root.value_btf_id) 9619 return -EFAULT; 9620 9621 mark_reg_graph_node(callee->regs, BPF_REG_1, &field->graph_root); 9622 ref_set_non_owning(env, &callee->regs[BPF_REG_1]); 9623 mark_reg_graph_node(callee->regs, BPF_REG_2, &field->graph_root); 9624 ref_set_non_owning(env, &callee->regs[BPF_REG_2]); 9625 9626 bpf_mark_reg_not_init(env, &callee->regs[BPF_REG_3]); 9627 bpf_mark_reg_not_init(env, &callee->regs[BPF_REG_4]); 9628 bpf_mark_reg_not_init(env, &callee->regs[BPF_REG_5]); 9629 callee->in_callback_fn = true; 9630 callee->callback_ret_range = retval_range(0, 1); 9631 return 0; 9632 } 9633 9634 static int set_task_work_schedule_callback_state(struct bpf_verifier_env *env, 9635 struct bpf_func_state *caller, 9636 struct bpf_func_state *callee, 9637 int insn_idx) 9638 { 9639 struct bpf_map *map_ptr = caller->regs[BPF_REG_3].map_ptr; 9640 9641 /* 9642 * callback_fn(struct bpf_map *map, void *key, void *value); 9643 */ 9644 callee->regs[BPF_REG_1].type = CONST_PTR_TO_MAP; 9645 __mark_reg_known_zero(&callee->regs[BPF_REG_1]); 9646 callee->regs[BPF_REG_1].map_ptr = map_ptr; 9647 9648 callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY; 9649 __mark_reg_known_zero(&callee->regs[BPF_REG_2]); 9650 callee->regs[BPF_REG_2].map_ptr = map_ptr; 9651 9652 callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE; 9653 __mark_reg_known_zero(&callee->regs[BPF_REG_3]); 9654 callee->regs[BPF_REG_3].map_ptr = map_ptr; 9655 9656 /* unused */ 9657 bpf_mark_reg_not_init(env, &callee->regs[BPF_REG_4]); 9658 bpf_mark_reg_not_init(env, &callee->regs[BPF_REG_5]); 9659 callee->in_async_callback_fn = true; 9660 callee->callback_ret_range = retval_range(S32_MIN, S32_MAX); 9661 return 0; 9662 } 9663 9664 static bool is_rbtree_lock_required_kfunc(u32 btf_id); 9665 9666 /* Are we currently verifying the callback for a rbtree helper that must 9667 * be called with lock held? If so, no need to complain about unreleased 9668 * lock 9669 */ 9670 static bool in_rbtree_lock_required_cb(struct bpf_verifier_env *env) 9671 { 9672 struct bpf_verifier_state *state = env->cur_state; 9673 struct bpf_insn *insn = env->prog->insnsi; 9674 struct bpf_func_state *callee; 9675 int kfunc_btf_id; 9676 9677 if (!state->curframe) 9678 return false; 9679 9680 callee = state->frame[state->curframe]; 9681 9682 if (!callee->in_callback_fn) 9683 return false; 9684 9685 kfunc_btf_id = insn[callee->callsite].imm; 9686 return is_rbtree_lock_required_kfunc(kfunc_btf_id); 9687 } 9688 9689 static bool retval_range_within(struct bpf_retval_range range, const struct bpf_reg_state *reg) 9690 { 9691 if (range.return_32bit) 9692 return range.minval <= reg_s32_min(reg) && reg_s32_max(reg) <= range.maxval; 9693 else 9694 return range.minval <= reg_smin(reg) && reg_smax(reg) <= range.maxval; 9695 } 9696 9697 static int prepare_func_exit(struct bpf_verifier_env *env, int *insn_idx) 9698 { 9699 struct bpf_verifier_state *state = env->cur_state, *prev_st; 9700 struct bpf_func_state *caller, *callee; 9701 struct bpf_reg_state *r0; 9702 bool in_callback_fn; 9703 int err; 9704 9705 callee = state->frame[state->curframe]; 9706 r0 = &callee->regs[BPF_REG_0]; 9707 if (r0->type == PTR_TO_STACK) { 9708 /* technically it's ok to return caller's stack pointer 9709 * (or caller's caller's pointer) back to the caller, 9710 * since these pointers are valid. Only current stack 9711 * pointer will be invalid as soon as function exits, 9712 * but let's be conservative 9713 */ 9714 verbose(env, "cannot return stack pointer to the caller\n"); 9715 return -EINVAL; 9716 } 9717 9718 caller = state->frame[state->curframe - 1]; 9719 if (callee->in_callback_fn) { 9720 if (r0->type != SCALAR_VALUE) { 9721 verbose(env, "R0 not a scalar value\n"); 9722 return -EACCES; 9723 } 9724 9725 /* we are going to rely on register's precise value */ 9726 err = mark_chain_precision(env, BPF_REG_0); 9727 if (err) 9728 return err; 9729 9730 /* enforce R0 return value range, and bpf_callback_t returns 64bit */ 9731 if (!retval_range_within(callee->callback_ret_range, r0)) { 9732 verbose_invalid_scalar(env, r0, callee->callback_ret_range, 9733 "At callback return", "R0"); 9734 return -EINVAL; 9735 } 9736 if (!bpf_calls_callback(env, callee->callsite)) { 9737 verifier_bug(env, "in callback at %d, callsite %d !calls_callback", 9738 *insn_idx, callee->callsite); 9739 return -EFAULT; 9740 } 9741 } else { 9742 /* return to the caller whatever r0 had in the callee */ 9743 caller->regs[BPF_REG_0] = *r0; 9744 } 9745 9746 /* for callbacks like bpf_loop or bpf_for_each_map_elem go back to callsite, 9747 * there function call logic would reschedule callback visit. If iteration 9748 * converges is_state_visited() would prune that visit eventually. 9749 */ 9750 in_callback_fn = callee->in_callback_fn; 9751 if (in_callback_fn) 9752 *insn_idx = callee->callsite; 9753 else 9754 *insn_idx = callee->callsite + 1; 9755 9756 if (env->log.level & BPF_LOG_LEVEL) { 9757 verbose(env, "returning from callee:\n"); 9758 print_verifier_state(env, state, callee->frameno, true); 9759 verbose(env, "to caller at %d:\n", *insn_idx); 9760 print_verifier_state(env, state, caller->frameno, true); 9761 } 9762 /* clear everything in the callee. In case of exceptional exits using 9763 * bpf_throw, this will be done by copy_verifier_state for extra frames. */ 9764 free_func_state(callee); 9765 state->frame[state->curframe--] = NULL; 9766 invalidate_outgoing_stack_args(env, caller); 9767 9768 /* for callbacks widen imprecise scalars to make programs like below verify: 9769 * 9770 * struct ctx { int i; } 9771 * void cb(int idx, struct ctx *ctx) { ctx->i++; ... } 9772 * ... 9773 * struct ctx = { .i = 0; } 9774 * bpf_loop(100, cb, &ctx, 0); 9775 * 9776 * This is similar to what is done in process_iter_next_call() for open 9777 * coded iterators. 9778 */ 9779 prev_st = in_callback_fn ? find_prev_entry(env, state, *insn_idx) : NULL; 9780 if (prev_st) { 9781 err = widen_imprecise_scalars(env, prev_st, state); 9782 if (err) 9783 return err; 9784 } 9785 return 0; 9786 } 9787 9788 static int do_refine_retval_range(struct bpf_verifier_env *env, 9789 struct bpf_reg_state *regs, int ret_type, 9790 int func_id, 9791 struct bpf_call_arg_meta *meta) 9792 { 9793 struct bpf_reg_state *ret_reg = ®s[BPF_REG_0]; 9794 9795 if (ret_type != RET_INTEGER) 9796 return 0; 9797 9798 switch (func_id) { 9799 case BPF_FUNC_get_stack: 9800 case BPF_FUNC_get_task_stack: 9801 case BPF_FUNC_probe_read_str: 9802 case BPF_FUNC_probe_read_kernel_str: 9803 case BPF_FUNC_probe_read_user_str: 9804 reg_set_srange64(ret_reg, -MAX_ERRNO, meta->msize_max_value); 9805 reg_set_srange32(ret_reg, -MAX_ERRNO, meta->msize_max_value); 9806 reg_bounds_sync(ret_reg); 9807 break; 9808 case BPF_FUNC_get_smp_processor_id: 9809 reg_set_urange64(ret_reg, 0, nr_cpu_ids - 1); 9810 reg_set_urange32(ret_reg, 0, nr_cpu_ids - 1); 9811 reg_bounds_sync(ret_reg); 9812 break; 9813 } 9814 9815 return reg_bounds_sanity_check(env, ret_reg, "retval"); 9816 } 9817 9818 static int 9819 record_func_map(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta, 9820 int func_id, int insn_idx) 9821 { 9822 struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx]; 9823 struct bpf_map *map = meta->map.ptr; 9824 9825 if (func_id != BPF_FUNC_tail_call && 9826 func_id != BPF_FUNC_map_lookup_elem && 9827 func_id != BPF_FUNC_map_update_elem && 9828 func_id != BPF_FUNC_map_delete_elem && 9829 func_id != BPF_FUNC_map_push_elem && 9830 func_id != BPF_FUNC_map_pop_elem && 9831 func_id != BPF_FUNC_map_peek_elem && 9832 func_id != BPF_FUNC_for_each_map_elem && 9833 func_id != BPF_FUNC_redirect_map && 9834 func_id != BPF_FUNC_map_lookup_percpu_elem) 9835 return 0; 9836 9837 if (map == NULL) { 9838 verifier_bug(env, "expected map for helper call"); 9839 return -EFAULT; 9840 } 9841 9842 /* In case of read-only, some additional restrictions 9843 * need to be applied in order to prevent altering the 9844 * state of the map from program side. 9845 */ 9846 if ((map->map_flags & BPF_F_RDONLY_PROG) && 9847 (func_id == BPF_FUNC_map_delete_elem || 9848 func_id == BPF_FUNC_map_update_elem || 9849 func_id == BPF_FUNC_map_push_elem || 9850 func_id == BPF_FUNC_map_pop_elem)) { 9851 verbose(env, "write into map forbidden\n"); 9852 return -EACCES; 9853 } 9854 9855 if (!aux->map_ptr_state.map_ptr) 9856 bpf_map_ptr_store(aux, meta->map.ptr, 9857 !meta->map.ptr->bypass_spec_v1, false); 9858 else if (aux->map_ptr_state.map_ptr != meta->map.ptr) 9859 bpf_map_ptr_store(aux, meta->map.ptr, 9860 !meta->map.ptr->bypass_spec_v1, true); 9861 return 0; 9862 } 9863 9864 static int 9865 record_func_key(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta, 9866 int func_id, int insn_idx) 9867 { 9868 struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx]; 9869 struct bpf_reg_state *reg; 9870 struct bpf_map *map = meta->map.ptr; 9871 u64 val, max; 9872 int err; 9873 9874 if (func_id != BPF_FUNC_tail_call) 9875 return 0; 9876 if (!map || map->map_type != BPF_MAP_TYPE_PROG_ARRAY) { 9877 verbose(env, "expected prog array map for tail call"); 9878 return -EINVAL; 9879 } 9880 9881 reg = reg_state(env, BPF_REG_3); 9882 val = reg->var_off.value; 9883 max = map->max_entries; 9884 9885 if (!(is_reg_const(reg, false) && val < max)) { 9886 bpf_map_key_store(aux, BPF_MAP_KEY_POISON); 9887 return 0; 9888 } 9889 9890 err = mark_chain_precision(env, BPF_REG_3); 9891 if (err) 9892 return err; 9893 if (bpf_map_key_unseen(aux)) 9894 bpf_map_key_store(aux, val); 9895 else if (!bpf_map_key_poisoned(aux) && 9896 bpf_map_key_immediate(aux) != val) 9897 bpf_map_key_store(aux, BPF_MAP_KEY_POISON); 9898 return 0; 9899 } 9900 9901 static int check_reference_leak(struct bpf_verifier_env *env, bool exception_exit) 9902 { 9903 struct bpf_verifier_state *state = env->cur_state; 9904 enum bpf_prog_type type = resolve_prog_type(env->prog); 9905 struct bpf_reg_state *reg = reg_state(env, BPF_REG_0); 9906 bool refs_lingering = false; 9907 int i; 9908 9909 if (!exception_exit && cur_func(env)->frameno) 9910 return 0; 9911 9912 for (i = 0; i < state->acquired_refs; i++) { 9913 if (state->refs[i].type != REF_TYPE_PTR) 9914 continue; 9915 /* Allow struct_ops programs to return a referenced kptr back to 9916 * kernel. Type checks are performed later in check_return_code. 9917 */ 9918 if (type == BPF_PROG_TYPE_STRUCT_OPS && !exception_exit && 9919 reg->ref_obj_id == state->refs[i].id) 9920 continue; 9921 verbose(env, "Unreleased reference id=%d alloc_insn=%d\n", 9922 state->refs[i].id, state->refs[i].insn_idx); 9923 refs_lingering = true; 9924 } 9925 return refs_lingering ? -EINVAL : 0; 9926 } 9927 9928 static int check_resource_leak(struct bpf_verifier_env *env, bool exception_exit, bool check_lock, const char *prefix) 9929 { 9930 int err; 9931 9932 if (check_lock && env->cur_state->active_locks) { 9933 verbose(env, "%s cannot be used inside bpf_spin_lock-ed region\n", prefix); 9934 return -EINVAL; 9935 } 9936 9937 err = check_reference_leak(env, exception_exit); 9938 if (err) { 9939 verbose(env, "%s would lead to reference leak\n", prefix); 9940 return err; 9941 } 9942 9943 if (check_lock && env->cur_state->active_irq_id) { 9944 verbose(env, "%s cannot be used inside bpf_local_irq_save-ed region\n", prefix); 9945 return -EINVAL; 9946 } 9947 9948 if (check_lock && env->cur_state->active_rcu_locks) { 9949 verbose(env, "%s cannot be used inside bpf_rcu_read_lock-ed region\n", prefix); 9950 return -EINVAL; 9951 } 9952 9953 if (check_lock && env->cur_state->active_preempt_locks) { 9954 verbose(env, "%s cannot be used inside bpf_preempt_disable-ed region\n", prefix); 9955 return -EINVAL; 9956 } 9957 9958 return 0; 9959 } 9960 9961 static int check_bpf_snprintf_call(struct bpf_verifier_env *env, 9962 struct bpf_reg_state *regs) 9963 { 9964 struct bpf_reg_state *fmt_reg = ®s[BPF_REG_3]; 9965 struct bpf_reg_state *data_len_reg = ®s[BPF_REG_5]; 9966 struct bpf_map *fmt_map = fmt_reg->map_ptr; 9967 struct bpf_bprintf_data data = {}; 9968 int err, fmt_map_off, num_args; 9969 u64 fmt_addr; 9970 char *fmt; 9971 9972 /* data must be an array of u64 */ 9973 if (data_len_reg->var_off.value % 8) 9974 return -EINVAL; 9975 num_args = data_len_reg->var_off.value / 8; 9976 9977 /* fmt being ARG_PTR_TO_CONST_STR guarantees that var_off is const 9978 * and map_direct_value_addr is set. 9979 */ 9980 fmt_map_off = fmt_reg->var_off.value; 9981 err = fmt_map->ops->map_direct_value_addr(fmt_map, &fmt_addr, 9982 fmt_map_off); 9983 if (err) { 9984 verbose(env, "failed to retrieve map value address\n"); 9985 return -EFAULT; 9986 } 9987 fmt = (char *)(long)fmt_addr + fmt_map_off; 9988 9989 /* We are also guaranteed that fmt+fmt_map_off is NULL terminated, we 9990 * can focus on validating the format specifiers. 9991 */ 9992 err = bpf_bprintf_prepare(fmt, UINT_MAX, NULL, num_args, &data); 9993 if (err < 0) 9994 verbose(env, "Invalid format string\n"); 9995 9996 return err; 9997 } 9998 9999 static int check_get_func_ip(struct bpf_verifier_env *env) 10000 { 10001 enum bpf_prog_type type = resolve_prog_type(env->prog); 10002 int func_id = BPF_FUNC_get_func_ip; 10003 10004 if (type == BPF_PROG_TYPE_TRACING) { 10005 if (!bpf_prog_has_trampoline(env->prog)) { 10006 verbose(env, "func %s#%d supported only for fentry/fexit/fsession/fmod_ret programs\n", 10007 func_id_name(func_id), func_id); 10008 return -ENOTSUPP; 10009 } 10010 return 0; 10011 } else if (type == BPF_PROG_TYPE_KPROBE) { 10012 return 0; 10013 } 10014 10015 verbose(env, "func %s#%d not supported for program type %d\n", 10016 func_id_name(func_id), func_id, type); 10017 return -ENOTSUPP; 10018 } 10019 10020 static struct bpf_insn_aux_data *cur_aux(const struct bpf_verifier_env *env) 10021 { 10022 return &env->insn_aux_data[env->insn_idx]; 10023 } 10024 10025 static bool loop_flag_is_zero(struct bpf_verifier_env *env) 10026 { 10027 struct bpf_reg_state *reg = reg_state(env, BPF_REG_4); 10028 bool reg_is_null = bpf_register_is_null(reg); 10029 10030 if (reg_is_null) 10031 mark_chain_precision(env, BPF_REG_4); 10032 10033 return reg_is_null; 10034 } 10035 10036 static void update_loop_inline_state(struct bpf_verifier_env *env, u32 subprogno) 10037 { 10038 struct bpf_loop_inline_state *state = &cur_aux(env)->loop_inline_state; 10039 10040 if (!state->initialized) { 10041 state->initialized = 1; 10042 state->fit_for_inline = loop_flag_is_zero(env); 10043 state->callback_subprogno = subprogno; 10044 return; 10045 } 10046 10047 if (!state->fit_for_inline) 10048 return; 10049 10050 state->fit_for_inline = (loop_flag_is_zero(env) && 10051 state->callback_subprogno == subprogno); 10052 } 10053 10054 /* Returns whether or not the given map type can potentially elide 10055 * lookup return value nullness check. This is possible if the key 10056 * is statically known. 10057 */ 10058 static bool can_elide_value_nullness(enum bpf_map_type type) 10059 { 10060 switch (type) { 10061 case BPF_MAP_TYPE_ARRAY: 10062 case BPF_MAP_TYPE_PERCPU_ARRAY: 10063 return true; 10064 default: 10065 return false; 10066 } 10067 } 10068 10069 int bpf_get_helper_proto(struct bpf_verifier_env *env, int func_id, 10070 const struct bpf_func_proto **ptr) 10071 { 10072 if (func_id < 0 || func_id >= __BPF_FUNC_MAX_ID) 10073 return -ERANGE; 10074 10075 if (!env->ops->get_func_proto) 10076 return -EINVAL; 10077 10078 *ptr = env->ops->get_func_proto(func_id, env->prog); 10079 return *ptr && (*ptr)->func ? 0 : -EINVAL; 10080 } 10081 10082 /* Check if we're in a sleepable context. */ 10083 static inline bool in_sleepable_context(struct bpf_verifier_env *env) 10084 { 10085 return !env->cur_state->active_rcu_locks && 10086 !env->cur_state->active_preempt_locks && 10087 !env->cur_state->active_locks && 10088 !env->cur_state->active_irq_id && 10089 in_sleepable(env); 10090 } 10091 10092 static const char *non_sleepable_context_description(struct bpf_verifier_env *env) 10093 { 10094 if (env->cur_state->active_rcu_locks) 10095 return "rcu_read_lock region"; 10096 if (env->cur_state->active_preempt_locks) 10097 return "non-preemptible region"; 10098 if (env->cur_state->active_irq_id) 10099 return "IRQ-disabled region"; 10100 if (env->cur_state->active_locks) 10101 return "lock region"; 10102 return "non-sleepable prog"; 10103 } 10104 10105 static int check_helper_call(struct bpf_verifier_env *env, struct bpf_insn *insn, 10106 int *insn_idx_p) 10107 { 10108 enum bpf_prog_type prog_type = resolve_prog_type(env->prog); 10109 bool returns_cpu_specific_alloc_ptr = false; 10110 const struct bpf_func_proto *fn = NULL; 10111 enum bpf_return_type ret_type; 10112 enum bpf_type_flag ret_flag; 10113 struct bpf_reg_state *regs; 10114 struct bpf_call_arg_meta meta; 10115 int insn_idx = *insn_idx_p; 10116 bool changes_data; 10117 int i, err, func_id; 10118 10119 /* find function prototype */ 10120 func_id = insn->imm; 10121 err = bpf_get_helper_proto(env, insn->imm, &fn); 10122 if (err == -ERANGE) { 10123 verbose(env, "invalid func %s#%d\n", func_id_name(func_id), func_id); 10124 return -EINVAL; 10125 } 10126 10127 if (err) { 10128 verbose(env, "program of this type cannot use helper %s#%d\n", 10129 func_id_name(func_id), func_id); 10130 return err; 10131 } 10132 10133 /* eBPF programs must be GPL compatible to use GPL-ed functions */ 10134 if (!env->prog->gpl_compatible && fn->gpl_only) { 10135 verbose(env, "cannot call GPL-restricted function from non-GPL compatible program\n"); 10136 return -EINVAL; 10137 } 10138 10139 if (fn->allowed && !fn->allowed(env->prog)) { 10140 verbose(env, "helper call is not allowed in probe\n"); 10141 return -EINVAL; 10142 } 10143 10144 /* With LD_ABS/IND some JITs save/restore skb from r1. */ 10145 changes_data = bpf_helper_changes_pkt_data(func_id); 10146 if (changes_data && fn->arg1_type != ARG_PTR_TO_CTX) { 10147 verifier_bug(env, "func %s#%d: r1 != ctx", func_id_name(func_id), func_id); 10148 return -EFAULT; 10149 } 10150 10151 memset(&meta, 0, sizeof(meta)); 10152 meta.pkt_access = fn->pkt_access; 10153 10154 err = check_func_proto(fn); 10155 if (err) { 10156 verifier_bug(env, "incorrect func proto %s#%d", func_id_name(func_id), func_id); 10157 return err; 10158 } 10159 10160 if (fn->might_sleep && !in_sleepable_context(env)) { 10161 verbose(env, "sleepable helper %s#%d in %s\n", func_id_name(func_id), func_id, 10162 non_sleepable_context_description(env)); 10163 return -EINVAL; 10164 } 10165 10166 /* Track non-sleepable context for helpers. */ 10167 if (!in_sleepable_context(env)) 10168 env->insn_aux_data[insn_idx].non_sleepable = true; 10169 10170 meta.func_id = func_id; 10171 /* check args */ 10172 for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++) { 10173 err = check_func_arg(env, i, &meta, fn, insn_idx); 10174 if (err) 10175 return err; 10176 } 10177 10178 err = record_func_map(env, &meta, func_id, insn_idx); 10179 if (err) 10180 return err; 10181 10182 err = record_func_key(env, &meta, func_id, insn_idx); 10183 if (err) 10184 return err; 10185 10186 regs = cur_regs(env); 10187 10188 /* Mark slots with STACK_MISC in case of raw mode, stack offset 10189 * is inferred from register state. 10190 */ 10191 for (i = 0; i < meta.access_size; i++) { 10192 err = check_mem_access(env, insn_idx, regs + meta.regno, argno_from_reg(meta.regno), i, BPF_B, 10193 BPF_WRITE, -1, false, false); 10194 if (err) 10195 return err; 10196 } 10197 10198 if (meta.release_regno) { 10199 err = -EINVAL; 10200 if (arg_type_is_dynptr(fn->arg_type[meta.release_regno - BPF_REG_1])) { 10201 err = unmark_stack_slots_dynptr(env, ®s[meta.release_regno]); 10202 } else if (func_id == BPF_FUNC_kptr_xchg && meta.ref_obj_id) { 10203 u32 ref_obj_id = meta.ref_obj_id; 10204 bool in_rcu = in_rcu_cs(env); 10205 struct bpf_func_state *state; 10206 struct bpf_reg_state *reg; 10207 10208 err = release_reference_nomark(env->cur_state, ref_obj_id); 10209 if (!err) { 10210 bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({ 10211 if (reg->ref_obj_id == ref_obj_id) { 10212 if (in_rcu && (reg->type & MEM_ALLOC) && (reg->type & MEM_PERCPU)) { 10213 reg->ref_obj_id = 0; 10214 reg->type &= ~MEM_ALLOC; 10215 reg->type |= MEM_RCU; 10216 } else { 10217 mark_reg_invalid(env, reg); 10218 } 10219 } 10220 })); 10221 } 10222 } else if (meta.ref_obj_id) { 10223 err = release_reference(env, meta.ref_obj_id); 10224 } else if (bpf_register_is_null(®s[meta.release_regno])) { 10225 /* meta.ref_obj_id can only be 0 if register that is meant to be 10226 * released is NULL, which must be > R0. 10227 */ 10228 err = 0; 10229 } 10230 if (err) { 10231 verbose(env, "func %s#%d reference has not been acquired before\n", 10232 func_id_name(func_id), func_id); 10233 return err; 10234 } 10235 } 10236 10237 switch (func_id) { 10238 case BPF_FUNC_tail_call: 10239 err = check_resource_leak(env, false, true, "tail_call"); 10240 if (err) 10241 return err; 10242 break; 10243 case BPF_FUNC_get_local_storage: 10244 /* check that flags argument in get_local_storage(map, flags) is 0, 10245 * this is required because get_local_storage() can't return an error. 10246 */ 10247 if (!bpf_register_is_null(®s[BPF_REG_2])) { 10248 verbose(env, "get_local_storage() doesn't support non-zero flags\n"); 10249 return -EINVAL; 10250 } 10251 break; 10252 case BPF_FUNC_for_each_map_elem: 10253 err = push_callback_call(env, insn, insn_idx, meta.subprogno, 10254 set_map_elem_callback_state); 10255 break; 10256 case BPF_FUNC_timer_set_callback: 10257 err = push_callback_call(env, insn, insn_idx, meta.subprogno, 10258 set_timer_callback_state); 10259 break; 10260 case BPF_FUNC_find_vma: 10261 err = push_callback_call(env, insn, insn_idx, meta.subprogno, 10262 set_find_vma_callback_state); 10263 break; 10264 case BPF_FUNC_snprintf: 10265 err = check_bpf_snprintf_call(env, regs); 10266 break; 10267 case BPF_FUNC_loop: 10268 update_loop_inline_state(env, meta.subprogno); 10269 /* Verifier relies on R1 value to determine if bpf_loop() iteration 10270 * is finished, thus mark it precise. 10271 */ 10272 err = mark_chain_precision(env, BPF_REG_1); 10273 if (err) 10274 return err; 10275 if (cur_func(env)->callback_depth < reg_umax(®s[BPF_REG_1])) { 10276 err = push_callback_call(env, insn, insn_idx, meta.subprogno, 10277 set_loop_callback_state); 10278 } else { 10279 cur_func(env)->callback_depth = 0; 10280 if (env->log.level & BPF_LOG_LEVEL2) 10281 verbose(env, "frame%d bpf_loop iteration limit reached\n", 10282 env->cur_state->curframe); 10283 } 10284 break; 10285 case BPF_FUNC_dynptr_from_mem: 10286 if (regs[BPF_REG_1].type != PTR_TO_MAP_VALUE) { 10287 verbose(env, "Unsupported reg type %s for bpf_dynptr_from_mem data\n", 10288 reg_type_str(env, regs[BPF_REG_1].type)); 10289 return -EACCES; 10290 } 10291 break; 10292 case BPF_FUNC_set_retval: 10293 if (prog_type == BPF_PROG_TYPE_LSM && 10294 env->prog->expected_attach_type == BPF_LSM_CGROUP) { 10295 if (!env->prog->aux->attach_func_proto->type) { 10296 /* Make sure programs that attach to void 10297 * hooks don't try to modify return value. 10298 */ 10299 verbose(env, "BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n"); 10300 return -EINVAL; 10301 } 10302 } 10303 break; 10304 case BPF_FUNC_dynptr_data: 10305 { 10306 struct bpf_reg_state *reg; 10307 int id, ref_obj_id; 10308 10309 reg = get_dynptr_arg_reg(env, fn, regs); 10310 if (!reg) 10311 return -EFAULT; 10312 10313 10314 if (meta.dynptr_id) { 10315 verifier_bug(env, "meta.dynptr_id already set"); 10316 return -EFAULT; 10317 } 10318 if (meta.ref_obj_id) { 10319 verifier_bug(env, "meta.ref_obj_id already set"); 10320 return -EFAULT; 10321 } 10322 10323 id = dynptr_id(env, reg); 10324 if (id < 0) { 10325 verifier_bug(env, "failed to obtain dynptr id"); 10326 return id; 10327 } 10328 10329 ref_obj_id = dynptr_ref_obj_id(env, reg); 10330 if (ref_obj_id < 0) { 10331 verifier_bug(env, "failed to obtain dynptr ref_obj_id"); 10332 return ref_obj_id; 10333 } 10334 10335 meta.dynptr_id = id; 10336 meta.ref_obj_id = ref_obj_id; 10337 10338 break; 10339 } 10340 case BPF_FUNC_dynptr_write: 10341 { 10342 enum bpf_dynptr_type dynptr_type; 10343 struct bpf_reg_state *reg; 10344 10345 reg = get_dynptr_arg_reg(env, fn, regs); 10346 if (!reg) 10347 return -EFAULT; 10348 10349 dynptr_type = dynptr_get_type(env, reg); 10350 if (dynptr_type == BPF_DYNPTR_TYPE_INVALID) 10351 return -EFAULT; 10352 10353 if (dynptr_type == BPF_DYNPTR_TYPE_SKB || 10354 dynptr_type == BPF_DYNPTR_TYPE_SKB_META) 10355 /* this will trigger clear_all_pkt_pointers(), which will 10356 * invalidate all dynptr slices associated with the skb 10357 */ 10358 changes_data = true; 10359 10360 break; 10361 } 10362 case BPF_FUNC_per_cpu_ptr: 10363 case BPF_FUNC_this_cpu_ptr: 10364 { 10365 struct bpf_reg_state *reg = ®s[BPF_REG_1]; 10366 const struct btf_type *type; 10367 10368 if (reg->type & MEM_RCU) { 10369 type = btf_type_by_id(reg->btf, reg->btf_id); 10370 if (!type || !btf_type_is_struct(type)) { 10371 verbose(env, "Helper has invalid btf/btf_id in R1\n"); 10372 return -EFAULT; 10373 } 10374 returns_cpu_specific_alloc_ptr = true; 10375 env->insn_aux_data[insn_idx].call_with_percpu_alloc_ptr = true; 10376 } 10377 break; 10378 } 10379 case BPF_FUNC_user_ringbuf_drain: 10380 err = push_callback_call(env, insn, insn_idx, meta.subprogno, 10381 set_user_ringbuf_callback_state); 10382 break; 10383 } 10384 10385 if (err) 10386 return err; 10387 10388 /* reset caller saved regs */ 10389 for (i = 0; i < CALLER_SAVED_REGS; i++) { 10390 bpf_mark_reg_not_init(env, ®s[caller_saved[i]]); 10391 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK); 10392 } 10393 invalidate_outgoing_stack_args(env, cur_func(env)); 10394 10395 /* helper call returns 64-bit value. */ 10396 regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG; 10397 10398 /* update return register (already marked as written above) */ 10399 ret_type = fn->ret_type; 10400 ret_flag = type_flag(ret_type); 10401 10402 switch (base_type(ret_type)) { 10403 case RET_INTEGER: 10404 /* sets type to SCALAR_VALUE */ 10405 mark_reg_unknown(env, regs, BPF_REG_0); 10406 break; 10407 case RET_VOID: 10408 regs[BPF_REG_0].type = NOT_INIT; 10409 break; 10410 case RET_PTR_TO_MAP_VALUE: 10411 /* There is no offset yet applied, variable or fixed */ 10412 mark_reg_known_zero(env, regs, BPF_REG_0); 10413 /* remember map_ptr, so that check_map_access() 10414 * can check 'value_size' boundary of memory access 10415 * to map element returned from bpf_map_lookup_elem() 10416 */ 10417 if (meta.map.ptr == NULL) { 10418 verifier_bug(env, "unexpected null map_ptr"); 10419 return -EFAULT; 10420 } 10421 10422 if (func_id == BPF_FUNC_map_lookup_elem && 10423 can_elide_value_nullness(meta.map.ptr->map_type) && 10424 meta.const_map_key >= 0 && 10425 meta.const_map_key < meta.map.ptr->max_entries) 10426 ret_flag &= ~PTR_MAYBE_NULL; 10427 10428 regs[BPF_REG_0].map_ptr = meta.map.ptr; 10429 regs[BPF_REG_0].map_uid = meta.map.uid; 10430 regs[BPF_REG_0].type = PTR_TO_MAP_VALUE | ret_flag; 10431 if (!type_may_be_null(ret_flag) && 10432 btf_record_has_field(meta.map.ptr->record, BPF_SPIN_LOCK | BPF_RES_SPIN_LOCK)) { 10433 regs[BPF_REG_0].id = ++env->id_gen; 10434 } 10435 break; 10436 case RET_PTR_TO_SOCKET: 10437 mark_reg_known_zero(env, regs, BPF_REG_0); 10438 regs[BPF_REG_0].type = PTR_TO_SOCKET | ret_flag; 10439 break; 10440 case RET_PTR_TO_SOCK_COMMON: 10441 mark_reg_known_zero(env, regs, BPF_REG_0); 10442 regs[BPF_REG_0].type = PTR_TO_SOCK_COMMON | ret_flag; 10443 break; 10444 case RET_PTR_TO_TCP_SOCK: 10445 mark_reg_known_zero(env, regs, BPF_REG_0); 10446 regs[BPF_REG_0].type = PTR_TO_TCP_SOCK | ret_flag; 10447 break; 10448 case RET_PTR_TO_MEM: 10449 mark_reg_known_zero(env, regs, BPF_REG_0); 10450 regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag; 10451 regs[BPF_REG_0].mem_size = meta.mem_size; 10452 break; 10453 case RET_PTR_TO_MEM_OR_BTF_ID: 10454 { 10455 const struct btf_type *t; 10456 10457 mark_reg_known_zero(env, regs, BPF_REG_0); 10458 t = btf_type_skip_modifiers(meta.ret_btf, meta.ret_btf_id, NULL); 10459 if (!btf_type_is_struct(t)) { 10460 u32 tsize; 10461 const struct btf_type *ret; 10462 const char *tname; 10463 10464 /* resolve the type size of ksym. */ 10465 ret = btf_resolve_size(meta.ret_btf, t, &tsize); 10466 if (IS_ERR(ret)) { 10467 tname = btf_name_by_offset(meta.ret_btf, t->name_off); 10468 verbose(env, "unable to resolve the size of type '%s': %ld\n", 10469 tname, PTR_ERR(ret)); 10470 return -EINVAL; 10471 } 10472 regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag; 10473 regs[BPF_REG_0].mem_size = tsize; 10474 } else { 10475 if (returns_cpu_specific_alloc_ptr) { 10476 regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC | MEM_RCU; 10477 } else { 10478 /* MEM_RDONLY may be carried from ret_flag, but it 10479 * doesn't apply on PTR_TO_BTF_ID. Fold it, otherwise 10480 * it will confuse the check of PTR_TO_BTF_ID in 10481 * check_mem_access(). 10482 */ 10483 ret_flag &= ~MEM_RDONLY; 10484 regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag; 10485 } 10486 10487 regs[BPF_REG_0].btf = meta.ret_btf; 10488 regs[BPF_REG_0].btf_id = meta.ret_btf_id; 10489 } 10490 break; 10491 } 10492 case RET_PTR_TO_BTF_ID: 10493 { 10494 struct btf *ret_btf; 10495 int ret_btf_id; 10496 10497 mark_reg_known_zero(env, regs, BPF_REG_0); 10498 regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag; 10499 if (func_id == BPF_FUNC_kptr_xchg) { 10500 ret_btf = meta.kptr_field->kptr.btf; 10501 ret_btf_id = meta.kptr_field->kptr.btf_id; 10502 if (!btf_is_kernel(ret_btf)) { 10503 regs[BPF_REG_0].type |= MEM_ALLOC; 10504 if (meta.kptr_field->type == BPF_KPTR_PERCPU) 10505 regs[BPF_REG_0].type |= MEM_PERCPU; 10506 } 10507 } else { 10508 if (fn->ret_btf_id == BPF_PTR_POISON) { 10509 verifier_bug(env, "func %s has non-overwritten BPF_PTR_POISON return type", 10510 func_id_name(func_id)); 10511 return -EFAULT; 10512 } 10513 ret_btf = btf_vmlinux; 10514 ret_btf_id = *fn->ret_btf_id; 10515 } 10516 if (ret_btf_id == 0) { 10517 verbose(env, "invalid return type %u of func %s#%d\n", 10518 base_type(ret_type), func_id_name(func_id), 10519 func_id); 10520 return -EINVAL; 10521 } 10522 regs[BPF_REG_0].btf = ret_btf; 10523 regs[BPF_REG_0].btf_id = ret_btf_id; 10524 break; 10525 } 10526 default: 10527 verbose(env, "unknown return type %u of func %s#%d\n", 10528 base_type(ret_type), func_id_name(func_id), func_id); 10529 return -EINVAL; 10530 } 10531 10532 if (type_may_be_null(regs[BPF_REG_0].type)) 10533 regs[BPF_REG_0].id = ++env->id_gen; 10534 10535 if (helper_multiple_ref_obj_use(func_id, meta.map.ptr)) { 10536 verifier_bug(env, "func %s#%d sets ref_obj_id more than once", 10537 func_id_name(func_id), func_id); 10538 return -EFAULT; 10539 } 10540 10541 if (is_dynptr_ref_function(func_id)) 10542 regs[BPF_REG_0].dynptr_id = meta.dynptr_id; 10543 10544 if (is_ptr_cast_function(func_id) || is_dynptr_ref_function(func_id)) { 10545 /* For release_reference() */ 10546 regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id; 10547 } else if (is_acquire_function(func_id, meta.map.ptr)) { 10548 int id = acquire_reference(env, insn_idx); 10549 10550 if (id < 0) 10551 return id; 10552 /* For mark_ptr_or_null_reg() */ 10553 regs[BPF_REG_0].id = id; 10554 /* For release_reference() */ 10555 regs[BPF_REG_0].ref_obj_id = id; 10556 } 10557 10558 err = do_refine_retval_range(env, regs, fn->ret_type, func_id, &meta); 10559 if (err) 10560 return err; 10561 10562 err = check_map_func_compatibility(env, meta.map.ptr, func_id); 10563 if (err) 10564 return err; 10565 10566 if ((func_id == BPF_FUNC_get_stack || 10567 func_id == BPF_FUNC_get_task_stack) && 10568 !env->prog->has_callchain_buf) { 10569 const char *err_str; 10570 10571 #ifdef CONFIG_PERF_EVENTS 10572 err = get_callchain_buffers(sysctl_perf_event_max_stack); 10573 err_str = "cannot get callchain buffer for func %s#%d\n"; 10574 #else 10575 err = -ENOTSUPP; 10576 err_str = "func %s#%d not supported without CONFIG_PERF_EVENTS\n"; 10577 #endif 10578 if (err) { 10579 verbose(env, err_str, func_id_name(func_id), func_id); 10580 return err; 10581 } 10582 10583 env->prog->has_callchain_buf = true; 10584 } 10585 10586 if (func_id == BPF_FUNC_get_stackid || func_id == BPF_FUNC_get_stack) 10587 env->prog->call_get_stack = true; 10588 10589 if (func_id == BPF_FUNC_get_func_ip) { 10590 if (check_get_func_ip(env)) 10591 return -ENOTSUPP; 10592 env->prog->call_get_func_ip = true; 10593 } 10594 10595 if (func_id == BPF_FUNC_tail_call) { 10596 if (env->cur_state->curframe) { 10597 struct bpf_verifier_state *branch; 10598 10599 mark_reg_scratched(env, BPF_REG_0); 10600 branch = push_stack(env, env->insn_idx + 1, env->insn_idx, false); 10601 if (IS_ERR(branch)) 10602 return PTR_ERR(branch); 10603 clear_all_pkt_pointers(env); 10604 mark_reg_unknown(env, regs, BPF_REG_0); 10605 err = prepare_func_exit(env, &env->insn_idx); 10606 if (err) 10607 return err; 10608 env->insn_idx--; 10609 } else { 10610 changes_data = false; 10611 } 10612 } 10613 10614 if (changes_data) 10615 clear_all_pkt_pointers(env); 10616 return 0; 10617 } 10618 10619 /* mark_btf_func_reg_size() is used when the reg size is determined by 10620 * the BTF func_proto's return value size and argument. 10621 */ 10622 static void __mark_btf_func_reg_size(struct bpf_verifier_env *env, struct bpf_reg_state *regs, 10623 u32 regno, size_t reg_size) 10624 { 10625 struct bpf_reg_state *reg = ®s[regno]; 10626 10627 if (regno == BPF_REG_0) { 10628 /* Function return value */ 10629 reg->subreg_def = reg_size == sizeof(u64) ? 10630 DEF_NOT_SUBREG : env->insn_idx + 1; 10631 } else if (reg_size == sizeof(u64)) { 10632 /* Function argument */ 10633 mark_insn_zext(env, reg); 10634 } 10635 } 10636 10637 static void mark_btf_func_reg_size(struct bpf_verifier_env *env, u32 regno, 10638 size_t reg_size) 10639 { 10640 return __mark_btf_func_reg_size(env, cur_regs(env), regno, reg_size); 10641 } 10642 10643 static bool is_kfunc_acquire(struct bpf_kfunc_call_arg_meta *meta) 10644 { 10645 return meta->kfunc_flags & KF_ACQUIRE; 10646 } 10647 10648 static bool is_kfunc_release(struct bpf_kfunc_call_arg_meta *meta) 10649 { 10650 return meta->kfunc_flags & KF_RELEASE; 10651 } 10652 10653 10654 static bool is_kfunc_destructive(struct bpf_kfunc_call_arg_meta *meta) 10655 { 10656 return meta->kfunc_flags & KF_DESTRUCTIVE; 10657 } 10658 10659 static bool is_kfunc_rcu(struct bpf_kfunc_call_arg_meta *meta) 10660 { 10661 return meta->kfunc_flags & KF_RCU; 10662 } 10663 10664 static bool is_kfunc_rcu_protected(struct bpf_kfunc_call_arg_meta *meta) 10665 { 10666 return meta->kfunc_flags & KF_RCU_PROTECTED; 10667 } 10668 10669 static bool is_kfunc_arg_mem_size(const struct btf *btf, 10670 const struct btf_param *arg, 10671 const struct bpf_reg_state *reg) 10672 { 10673 const struct btf_type *t; 10674 10675 t = btf_type_skip_modifiers(btf, arg->type, NULL); 10676 if (!btf_type_is_scalar(t) || reg->type != SCALAR_VALUE) 10677 return false; 10678 10679 return btf_param_match_suffix(btf, arg, "__sz"); 10680 } 10681 10682 static bool is_kfunc_arg_const_mem_size(const struct btf *btf, 10683 const struct btf_param *arg, 10684 const struct bpf_reg_state *reg) 10685 { 10686 const struct btf_type *t; 10687 10688 t = btf_type_skip_modifiers(btf, arg->type, NULL); 10689 if (!btf_type_is_scalar(t) || reg->type != SCALAR_VALUE) 10690 return false; 10691 10692 return btf_param_match_suffix(btf, arg, "__szk"); 10693 } 10694 10695 static bool is_kfunc_arg_constant(const struct btf *btf, const struct btf_param *arg) 10696 { 10697 return btf_param_match_suffix(btf, arg, "__k"); 10698 } 10699 10700 static bool is_kfunc_arg_ignore(const struct btf *btf, const struct btf_param *arg) 10701 { 10702 return btf_param_match_suffix(btf, arg, "__ign"); 10703 } 10704 10705 static bool is_kfunc_arg_map(const struct btf *btf, const struct btf_param *arg) 10706 { 10707 return btf_param_match_suffix(btf, arg, "__map"); 10708 } 10709 10710 static bool is_kfunc_arg_alloc_obj(const struct btf *btf, const struct btf_param *arg) 10711 { 10712 return btf_param_match_suffix(btf, arg, "__alloc"); 10713 } 10714 10715 static bool is_kfunc_arg_uninit(const struct btf *btf, const struct btf_param *arg) 10716 { 10717 return btf_param_match_suffix(btf, arg, "__uninit"); 10718 } 10719 10720 static bool is_kfunc_arg_refcounted_kptr(const struct btf *btf, const struct btf_param *arg) 10721 { 10722 return btf_param_match_suffix(btf, arg, "__refcounted_kptr"); 10723 } 10724 10725 static bool is_kfunc_arg_nullable(const struct btf *btf, const struct btf_param *arg) 10726 { 10727 return btf_param_match_suffix(btf, arg, "__nullable"); 10728 } 10729 10730 static bool is_kfunc_arg_nonown_allowed(const struct btf *btf, const struct btf_param *arg) 10731 { 10732 return btf_param_match_suffix(btf, arg, "__nonown_allowed"); 10733 } 10734 10735 static bool is_kfunc_arg_const_str(const struct btf *btf, const struct btf_param *arg) 10736 { 10737 return btf_param_match_suffix(btf, arg, "__str"); 10738 } 10739 10740 static bool is_kfunc_arg_irq_flag(const struct btf *btf, const struct btf_param *arg) 10741 { 10742 return btf_param_match_suffix(btf, arg, "__irq_flag"); 10743 } 10744 10745 static bool is_kfunc_arg_scalar_with_name(const struct btf *btf, 10746 const struct btf_param *arg, 10747 const char *name) 10748 { 10749 int len, target_len = strlen(name); 10750 const char *param_name; 10751 10752 param_name = btf_name_by_offset(btf, arg->name_off); 10753 if (str_is_empty(param_name)) 10754 return false; 10755 len = strlen(param_name); 10756 if (len != target_len) 10757 return false; 10758 if (strcmp(param_name, name)) 10759 return false; 10760 10761 return true; 10762 } 10763 10764 enum { 10765 KF_ARG_DYNPTR_ID, 10766 KF_ARG_LIST_HEAD_ID, 10767 KF_ARG_LIST_NODE_ID, 10768 KF_ARG_RB_ROOT_ID, 10769 KF_ARG_RB_NODE_ID, 10770 KF_ARG_WORKQUEUE_ID, 10771 KF_ARG_RES_SPIN_LOCK_ID, 10772 KF_ARG_TASK_WORK_ID, 10773 KF_ARG_PROG_AUX_ID, 10774 KF_ARG_TIMER_ID 10775 }; 10776 10777 BTF_ID_LIST(kf_arg_btf_ids) 10778 BTF_ID(struct, bpf_dynptr) 10779 BTF_ID(struct, bpf_list_head) 10780 BTF_ID(struct, bpf_list_node) 10781 BTF_ID(struct, bpf_rb_root) 10782 BTF_ID(struct, bpf_rb_node) 10783 BTF_ID(struct, bpf_wq) 10784 BTF_ID(struct, bpf_res_spin_lock) 10785 BTF_ID(struct, bpf_task_work) 10786 BTF_ID(struct, bpf_prog_aux) 10787 BTF_ID(struct, bpf_timer) 10788 10789 static bool __is_kfunc_ptr_arg_type(const struct btf *btf, 10790 const struct btf_param *arg, int type) 10791 { 10792 const struct btf_type *t; 10793 u32 res_id; 10794 10795 t = btf_type_skip_modifiers(btf, arg->type, NULL); 10796 if (!t) 10797 return false; 10798 if (!btf_type_is_ptr(t)) 10799 return false; 10800 t = btf_type_skip_modifiers(btf, t->type, &res_id); 10801 if (!t) 10802 return false; 10803 return btf_types_are_same(btf, res_id, btf_vmlinux, kf_arg_btf_ids[type]); 10804 } 10805 10806 static bool is_kfunc_arg_dynptr(const struct btf *btf, const struct btf_param *arg) 10807 { 10808 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_DYNPTR_ID); 10809 } 10810 10811 static bool is_kfunc_arg_list_head(const struct btf *btf, const struct btf_param *arg) 10812 { 10813 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_LIST_HEAD_ID); 10814 } 10815 10816 static bool is_kfunc_arg_list_node(const struct btf *btf, const struct btf_param *arg) 10817 { 10818 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_LIST_NODE_ID); 10819 } 10820 10821 static bool is_kfunc_arg_rbtree_root(const struct btf *btf, const struct btf_param *arg) 10822 { 10823 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_RB_ROOT_ID); 10824 } 10825 10826 static bool is_kfunc_arg_rbtree_node(const struct btf *btf, const struct btf_param *arg) 10827 { 10828 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_RB_NODE_ID); 10829 } 10830 10831 static bool is_kfunc_arg_timer(const struct btf *btf, const struct btf_param *arg) 10832 { 10833 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_TIMER_ID); 10834 } 10835 10836 static bool is_kfunc_arg_wq(const struct btf *btf, const struct btf_param *arg) 10837 { 10838 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_WORKQUEUE_ID); 10839 } 10840 10841 static bool is_kfunc_arg_task_work(const struct btf *btf, const struct btf_param *arg) 10842 { 10843 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_TASK_WORK_ID); 10844 } 10845 10846 static bool is_kfunc_arg_res_spin_lock(const struct btf *btf, const struct btf_param *arg) 10847 { 10848 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_RES_SPIN_LOCK_ID); 10849 } 10850 10851 static bool is_rbtree_node_type(const struct btf_type *t) 10852 { 10853 return t == btf_type_by_id(btf_vmlinux, kf_arg_btf_ids[KF_ARG_RB_NODE_ID]); 10854 } 10855 10856 static bool is_list_node_type(const struct btf_type *t) 10857 { 10858 return t == btf_type_by_id(btf_vmlinux, kf_arg_btf_ids[KF_ARG_LIST_NODE_ID]); 10859 } 10860 10861 static bool is_kfunc_arg_callback(struct bpf_verifier_env *env, const struct btf *btf, 10862 const struct btf_param *arg) 10863 { 10864 const struct btf_type *t; 10865 10866 t = btf_type_resolve_func_ptr(btf, arg->type, NULL); 10867 if (!t) 10868 return false; 10869 10870 return true; 10871 } 10872 10873 static bool is_kfunc_arg_prog_aux(const struct btf *btf, const struct btf_param *arg) 10874 { 10875 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_PROG_AUX_ID); 10876 } 10877 10878 /* 10879 * A kfunc with KF_IMPLICIT_ARGS has two prototypes in BTF: 10880 * - the _impl prototype with full arg list (meta->func_proto) 10881 * - the BPF API prototype w/o implicit args (func->type in BTF) 10882 * To determine whether an argument is implicit, we compare its position 10883 * against the number of arguments in the prototype w/o implicit args. 10884 */ 10885 static bool is_kfunc_arg_implicit(const struct bpf_kfunc_call_arg_meta *meta, u32 arg_idx) 10886 { 10887 const struct btf_type *func, *func_proto; 10888 u32 argn; 10889 10890 if (!(meta->kfunc_flags & KF_IMPLICIT_ARGS)) 10891 return false; 10892 10893 func = btf_type_by_id(meta->btf, meta->func_id); 10894 func_proto = btf_type_by_id(meta->btf, func->type); 10895 argn = btf_type_vlen(func_proto); 10896 10897 return argn <= arg_idx; 10898 } 10899 10900 /* Returns true if struct is composed of scalars, 4 levels of nesting allowed */ 10901 static bool __btf_type_is_scalar_struct(struct bpf_verifier_env *env, 10902 const struct btf *btf, 10903 const struct btf_type *t, int rec) 10904 { 10905 const struct btf_type *member_type; 10906 const struct btf_member *member; 10907 u32 i; 10908 10909 if (!btf_type_is_struct(t)) 10910 return false; 10911 10912 for_each_member(i, t, member) { 10913 const struct btf_array *array; 10914 10915 member_type = btf_type_skip_modifiers(btf, member->type, NULL); 10916 if (btf_type_is_struct(member_type)) { 10917 if (rec >= 3) { 10918 verbose(env, "max struct nesting depth exceeded\n"); 10919 return false; 10920 } 10921 if (!__btf_type_is_scalar_struct(env, btf, member_type, rec + 1)) 10922 return false; 10923 continue; 10924 } 10925 if (btf_type_is_array(member_type)) { 10926 array = btf_array(member_type); 10927 if (!array->nelems) 10928 return false; 10929 member_type = btf_type_skip_modifiers(btf, array->type, NULL); 10930 if (!btf_type_is_scalar(member_type)) 10931 return false; 10932 continue; 10933 } 10934 if (!btf_type_is_scalar(member_type)) 10935 return false; 10936 } 10937 return true; 10938 } 10939 10940 enum kfunc_ptr_arg_type { 10941 KF_ARG_PTR_TO_CTX, 10942 KF_ARG_PTR_TO_ALLOC_BTF_ID, /* Allocated object */ 10943 KF_ARG_PTR_TO_REFCOUNTED_KPTR, /* Refcounted local kptr */ 10944 KF_ARG_PTR_TO_DYNPTR, 10945 KF_ARG_PTR_TO_ITER, 10946 KF_ARG_PTR_TO_LIST_HEAD, 10947 KF_ARG_PTR_TO_LIST_NODE, 10948 KF_ARG_PTR_TO_BTF_ID, /* Also covers reg2btf_ids conversions */ 10949 KF_ARG_PTR_TO_MEM, 10950 KF_ARG_PTR_TO_MEM_SIZE, /* Size derived from next argument, skip it */ 10951 KF_ARG_PTR_TO_CALLBACK, 10952 KF_ARG_PTR_TO_RB_ROOT, 10953 KF_ARG_PTR_TO_RB_NODE, 10954 KF_ARG_PTR_TO_NULL, 10955 KF_ARG_PTR_TO_CONST_STR, 10956 KF_ARG_PTR_TO_MAP, 10957 KF_ARG_PTR_TO_TIMER, 10958 KF_ARG_PTR_TO_WORKQUEUE, 10959 KF_ARG_PTR_TO_IRQ_FLAG, 10960 KF_ARG_PTR_TO_RES_SPIN_LOCK, 10961 KF_ARG_PTR_TO_TASK_WORK, 10962 }; 10963 10964 enum special_kfunc_type { 10965 KF_bpf_obj_new_impl, 10966 KF_bpf_obj_new, 10967 KF_bpf_obj_drop_impl, 10968 KF_bpf_obj_drop, 10969 KF_bpf_refcount_acquire_impl, 10970 KF_bpf_refcount_acquire, 10971 KF_bpf_list_push_front_impl, 10972 KF_bpf_list_push_front, 10973 KF_bpf_list_push_back_impl, 10974 KF_bpf_list_push_back, 10975 KF_bpf_list_add, 10976 KF_bpf_list_pop_front, 10977 KF_bpf_list_pop_back, 10978 KF_bpf_list_del, 10979 KF_bpf_list_front, 10980 KF_bpf_list_back, 10981 KF_bpf_list_is_first, 10982 KF_bpf_list_is_last, 10983 KF_bpf_list_empty, 10984 KF_bpf_cast_to_kern_ctx, 10985 KF_bpf_rdonly_cast, 10986 KF_bpf_rcu_read_lock, 10987 KF_bpf_rcu_read_unlock, 10988 KF_bpf_rbtree_remove, 10989 KF_bpf_rbtree_add_impl, 10990 KF_bpf_rbtree_add, 10991 KF_bpf_rbtree_first, 10992 KF_bpf_rbtree_root, 10993 KF_bpf_rbtree_left, 10994 KF_bpf_rbtree_right, 10995 KF_bpf_dynptr_from_skb, 10996 KF_bpf_dynptr_from_xdp, 10997 KF_bpf_dynptr_from_skb_meta, 10998 KF_bpf_xdp_pull_data, 10999 KF_bpf_dynptr_slice, 11000 KF_bpf_dynptr_slice_rdwr, 11001 KF_bpf_dynptr_clone, 11002 KF_bpf_percpu_obj_new_impl, 11003 KF_bpf_percpu_obj_new, 11004 KF_bpf_percpu_obj_drop_impl, 11005 KF_bpf_percpu_obj_drop, 11006 KF_bpf_throw, 11007 KF_bpf_wq_set_callback, 11008 KF_bpf_preempt_disable, 11009 KF_bpf_preempt_enable, 11010 KF_bpf_iter_css_task_new, 11011 KF_bpf_session_cookie, 11012 KF_bpf_get_kmem_cache, 11013 KF_bpf_local_irq_save, 11014 KF_bpf_local_irq_restore, 11015 KF_bpf_iter_num_new, 11016 KF_bpf_iter_num_next, 11017 KF_bpf_iter_num_destroy, 11018 KF_bpf_set_dentry_xattr, 11019 KF_bpf_remove_dentry_xattr, 11020 KF_bpf_res_spin_lock, 11021 KF_bpf_res_spin_unlock, 11022 KF_bpf_res_spin_lock_irqsave, 11023 KF_bpf_res_spin_unlock_irqrestore, 11024 KF_bpf_dynptr_from_file, 11025 KF_bpf_dynptr_file_discard, 11026 KF___bpf_trap, 11027 KF_bpf_task_work_schedule_signal, 11028 KF_bpf_task_work_schedule_resume, 11029 KF_bpf_arena_alloc_pages, 11030 KF_bpf_arena_free_pages, 11031 KF_bpf_arena_reserve_pages, 11032 KF_bpf_session_is_return, 11033 KF_bpf_stream_vprintk, 11034 KF_bpf_stream_print_stack, 11035 }; 11036 11037 BTF_ID_LIST(special_kfunc_list) 11038 BTF_ID(func, bpf_obj_new_impl) 11039 BTF_ID(func, bpf_obj_new) 11040 BTF_ID(func, bpf_obj_drop_impl) 11041 BTF_ID(func, bpf_obj_drop) 11042 BTF_ID(func, bpf_refcount_acquire_impl) 11043 BTF_ID(func, bpf_refcount_acquire) 11044 BTF_ID(func, bpf_list_push_front_impl) 11045 BTF_ID(func, bpf_list_push_front) 11046 BTF_ID(func, bpf_list_push_back_impl) 11047 BTF_ID(func, bpf_list_push_back) 11048 BTF_ID(func, bpf_list_add) 11049 BTF_ID(func, bpf_list_pop_front) 11050 BTF_ID(func, bpf_list_pop_back) 11051 BTF_ID(func, bpf_list_del) 11052 BTF_ID(func, bpf_list_front) 11053 BTF_ID(func, bpf_list_back) 11054 BTF_ID(func, bpf_list_is_first) 11055 BTF_ID(func, bpf_list_is_last) 11056 BTF_ID(func, bpf_list_empty) 11057 BTF_ID(func, bpf_cast_to_kern_ctx) 11058 BTF_ID(func, bpf_rdonly_cast) 11059 BTF_ID(func, bpf_rcu_read_lock) 11060 BTF_ID(func, bpf_rcu_read_unlock) 11061 BTF_ID(func, bpf_rbtree_remove) 11062 BTF_ID(func, bpf_rbtree_add_impl) 11063 BTF_ID(func, bpf_rbtree_add) 11064 BTF_ID(func, bpf_rbtree_first) 11065 BTF_ID(func, bpf_rbtree_root) 11066 BTF_ID(func, bpf_rbtree_left) 11067 BTF_ID(func, bpf_rbtree_right) 11068 #ifdef CONFIG_NET 11069 BTF_ID(func, bpf_dynptr_from_skb) 11070 BTF_ID(func, bpf_dynptr_from_xdp) 11071 BTF_ID(func, bpf_dynptr_from_skb_meta) 11072 BTF_ID(func, bpf_xdp_pull_data) 11073 #else 11074 BTF_ID_UNUSED 11075 BTF_ID_UNUSED 11076 BTF_ID_UNUSED 11077 BTF_ID_UNUSED 11078 #endif 11079 BTF_ID(func, bpf_dynptr_slice) 11080 BTF_ID(func, bpf_dynptr_slice_rdwr) 11081 BTF_ID(func, bpf_dynptr_clone) 11082 BTF_ID(func, bpf_percpu_obj_new_impl) 11083 BTF_ID(func, bpf_percpu_obj_new) 11084 BTF_ID(func, bpf_percpu_obj_drop_impl) 11085 BTF_ID(func, bpf_percpu_obj_drop) 11086 BTF_ID(func, bpf_throw) 11087 BTF_ID(func, bpf_wq_set_callback) 11088 BTF_ID(func, bpf_preempt_disable) 11089 BTF_ID(func, bpf_preempt_enable) 11090 #ifdef CONFIG_CGROUPS 11091 BTF_ID(func, bpf_iter_css_task_new) 11092 #else 11093 BTF_ID_UNUSED 11094 #endif 11095 #ifdef CONFIG_BPF_EVENTS 11096 BTF_ID(func, bpf_session_cookie) 11097 #else 11098 BTF_ID_UNUSED 11099 #endif 11100 BTF_ID(func, bpf_get_kmem_cache) 11101 BTF_ID(func, bpf_local_irq_save) 11102 BTF_ID(func, bpf_local_irq_restore) 11103 BTF_ID(func, bpf_iter_num_new) 11104 BTF_ID(func, bpf_iter_num_next) 11105 BTF_ID(func, bpf_iter_num_destroy) 11106 #ifdef CONFIG_BPF_LSM 11107 BTF_ID(func, bpf_set_dentry_xattr) 11108 BTF_ID(func, bpf_remove_dentry_xattr) 11109 #else 11110 BTF_ID_UNUSED 11111 BTF_ID_UNUSED 11112 #endif 11113 BTF_ID(func, bpf_res_spin_lock) 11114 BTF_ID(func, bpf_res_spin_unlock) 11115 BTF_ID(func, bpf_res_spin_lock_irqsave) 11116 BTF_ID(func, bpf_res_spin_unlock_irqrestore) 11117 BTF_ID(func, bpf_dynptr_from_file) 11118 BTF_ID(func, bpf_dynptr_file_discard) 11119 BTF_ID(func, __bpf_trap) 11120 BTF_ID(func, bpf_task_work_schedule_signal) 11121 BTF_ID(func, bpf_task_work_schedule_resume) 11122 BTF_ID(func, bpf_arena_alloc_pages) 11123 BTF_ID(func, bpf_arena_free_pages) 11124 BTF_ID(func, bpf_arena_reserve_pages) 11125 #ifdef CONFIG_BPF_EVENTS 11126 BTF_ID(func, bpf_session_is_return) 11127 #else 11128 BTF_ID_UNUSED 11129 #endif 11130 BTF_ID(func, bpf_stream_vprintk) 11131 BTF_ID(func, bpf_stream_print_stack) 11132 11133 static bool is_bpf_obj_new_kfunc(u32 func_id) 11134 { 11135 return func_id == special_kfunc_list[KF_bpf_obj_new] || 11136 func_id == special_kfunc_list[KF_bpf_obj_new_impl]; 11137 } 11138 11139 static bool is_bpf_percpu_obj_new_kfunc(u32 func_id) 11140 { 11141 return func_id == special_kfunc_list[KF_bpf_percpu_obj_new] || 11142 func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl]; 11143 } 11144 11145 static bool is_bpf_obj_drop_kfunc(u32 func_id) 11146 { 11147 return func_id == special_kfunc_list[KF_bpf_obj_drop] || 11148 func_id == special_kfunc_list[KF_bpf_obj_drop_impl]; 11149 } 11150 11151 static bool is_bpf_percpu_obj_drop_kfunc(u32 func_id) 11152 { 11153 return func_id == special_kfunc_list[KF_bpf_percpu_obj_drop] || 11154 func_id == special_kfunc_list[KF_bpf_percpu_obj_drop_impl]; 11155 } 11156 11157 static bool is_bpf_refcount_acquire_kfunc(u32 func_id) 11158 { 11159 return func_id == special_kfunc_list[KF_bpf_refcount_acquire] || 11160 func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl]; 11161 } 11162 11163 static bool is_bpf_list_push_kfunc(u32 func_id) 11164 { 11165 return func_id == special_kfunc_list[KF_bpf_list_push_front] || 11166 func_id == special_kfunc_list[KF_bpf_list_push_front_impl] || 11167 func_id == special_kfunc_list[KF_bpf_list_push_back] || 11168 func_id == special_kfunc_list[KF_bpf_list_push_back_impl] || 11169 func_id == special_kfunc_list[KF_bpf_list_add]; 11170 } 11171 11172 static bool is_bpf_rbtree_add_kfunc(u32 func_id) 11173 { 11174 return func_id == special_kfunc_list[KF_bpf_rbtree_add] || 11175 func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]; 11176 } 11177 11178 static bool is_task_work_add_kfunc(u32 func_id) 11179 { 11180 return func_id == special_kfunc_list[KF_bpf_task_work_schedule_signal] || 11181 func_id == special_kfunc_list[KF_bpf_task_work_schedule_resume]; 11182 } 11183 11184 static bool is_kfunc_ret_null(struct bpf_kfunc_call_arg_meta *meta) 11185 { 11186 if (is_bpf_refcount_acquire_kfunc(meta->func_id) && meta->arg_owning_ref) 11187 return false; 11188 11189 return meta->kfunc_flags & KF_RET_NULL; 11190 } 11191 11192 static bool is_kfunc_bpf_rcu_read_lock(struct bpf_kfunc_call_arg_meta *meta) 11193 { 11194 return meta->func_id == special_kfunc_list[KF_bpf_rcu_read_lock]; 11195 } 11196 11197 static bool is_kfunc_bpf_rcu_read_unlock(struct bpf_kfunc_call_arg_meta *meta) 11198 { 11199 return meta->func_id == special_kfunc_list[KF_bpf_rcu_read_unlock]; 11200 } 11201 11202 static bool is_kfunc_bpf_preempt_disable(struct bpf_kfunc_call_arg_meta *meta) 11203 { 11204 return meta->func_id == special_kfunc_list[KF_bpf_preempt_disable]; 11205 } 11206 11207 static bool is_kfunc_bpf_preempt_enable(struct bpf_kfunc_call_arg_meta *meta) 11208 { 11209 return meta->func_id == special_kfunc_list[KF_bpf_preempt_enable]; 11210 } 11211 11212 bool bpf_is_kfunc_pkt_changing(struct bpf_kfunc_call_arg_meta *meta) 11213 { 11214 return meta->func_id == special_kfunc_list[KF_bpf_xdp_pull_data]; 11215 } 11216 11217 static enum kfunc_ptr_arg_type 11218 get_kfunc_ptr_arg_type(struct bpf_verifier_env *env, struct bpf_func_state *caller, 11219 struct bpf_reg_state *regs, struct bpf_kfunc_call_arg_meta *meta, 11220 const struct btf_type *t, const struct btf_type *ref_t, 11221 const char *ref_tname, const struct btf_param *args, 11222 int arg, int nargs, argno_t argno, struct bpf_reg_state *reg) 11223 { 11224 bool arg_mem_size = false; 11225 11226 if (meta->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx] || 11227 meta->func_id == special_kfunc_list[KF_bpf_session_is_return] || 11228 meta->func_id == special_kfunc_list[KF_bpf_session_cookie]) 11229 return KF_ARG_PTR_TO_CTX; 11230 11231 if (arg + 1 < nargs && 11232 (is_kfunc_arg_mem_size(meta->btf, &args[arg + 1], get_func_arg_reg(caller, regs, arg + 1)) || 11233 is_kfunc_arg_const_mem_size(meta->btf, &args[arg + 1], get_func_arg_reg(caller, regs, arg + 1)))) 11234 arg_mem_size = true; 11235 11236 /* In this function, we verify the kfunc's BTF as per the argument type, 11237 * leaving the rest of the verification with respect to the register 11238 * type to our caller. When a set of conditions hold in the BTF type of 11239 * arguments, we resolve it to a known kfunc_ptr_arg_type. 11240 */ 11241 if (btf_is_prog_ctx_type(&env->log, meta->btf, t, resolve_prog_type(env->prog), arg)) 11242 return KF_ARG_PTR_TO_CTX; 11243 11244 if (is_kfunc_arg_nullable(meta->btf, &args[arg]) && bpf_register_is_null(reg) && 11245 !arg_mem_size) 11246 return KF_ARG_PTR_TO_NULL; 11247 11248 if (is_kfunc_arg_alloc_obj(meta->btf, &args[arg])) 11249 return KF_ARG_PTR_TO_ALLOC_BTF_ID; 11250 11251 if (is_kfunc_arg_refcounted_kptr(meta->btf, &args[arg])) 11252 return KF_ARG_PTR_TO_REFCOUNTED_KPTR; 11253 11254 if (is_kfunc_arg_dynptr(meta->btf, &args[arg])) 11255 return KF_ARG_PTR_TO_DYNPTR; 11256 11257 if (is_kfunc_arg_iter(meta, arg, &args[arg])) 11258 return KF_ARG_PTR_TO_ITER; 11259 11260 if (is_kfunc_arg_list_head(meta->btf, &args[arg])) 11261 return KF_ARG_PTR_TO_LIST_HEAD; 11262 11263 if (is_kfunc_arg_list_node(meta->btf, &args[arg])) 11264 return KF_ARG_PTR_TO_LIST_NODE; 11265 11266 if (is_kfunc_arg_rbtree_root(meta->btf, &args[arg])) 11267 return KF_ARG_PTR_TO_RB_ROOT; 11268 11269 if (is_kfunc_arg_rbtree_node(meta->btf, &args[arg])) 11270 return KF_ARG_PTR_TO_RB_NODE; 11271 11272 if (is_kfunc_arg_const_str(meta->btf, &args[arg])) 11273 return KF_ARG_PTR_TO_CONST_STR; 11274 11275 if (is_kfunc_arg_map(meta->btf, &args[arg])) 11276 return KF_ARG_PTR_TO_MAP; 11277 11278 if (is_kfunc_arg_wq(meta->btf, &args[arg])) 11279 return KF_ARG_PTR_TO_WORKQUEUE; 11280 11281 if (is_kfunc_arg_timer(meta->btf, &args[arg])) 11282 return KF_ARG_PTR_TO_TIMER; 11283 11284 if (is_kfunc_arg_task_work(meta->btf, &args[arg])) 11285 return KF_ARG_PTR_TO_TASK_WORK; 11286 11287 if (is_kfunc_arg_irq_flag(meta->btf, &args[arg])) 11288 return KF_ARG_PTR_TO_IRQ_FLAG; 11289 11290 if (is_kfunc_arg_res_spin_lock(meta->btf, &args[arg])) 11291 return KF_ARG_PTR_TO_RES_SPIN_LOCK; 11292 11293 if ((base_type(reg->type) == PTR_TO_BTF_ID || reg2btf_ids[base_type(reg->type)])) { 11294 if (!btf_type_is_struct(ref_t)) { 11295 verbose(env, "kernel function %s %s pointer type %s %s is not supported\n", 11296 meta->func_name, reg_arg_name(env, argno), 11297 btf_type_str(ref_t), ref_tname); 11298 return -EINVAL; 11299 } 11300 return KF_ARG_PTR_TO_BTF_ID; 11301 } 11302 11303 if (is_kfunc_arg_callback(env, meta->btf, &args[arg])) 11304 return KF_ARG_PTR_TO_CALLBACK; 11305 11306 /* This is the catch all argument type of register types supported by 11307 * check_helper_mem_access. However, we only allow when argument type is 11308 * pointer to scalar, or struct composed (recursively) of scalars. When 11309 * arg_mem_size is true, the pointer can be void *. 11310 */ 11311 if (!btf_type_is_scalar(ref_t) && !__btf_type_is_scalar_struct(env, meta->btf, ref_t, 0) && 11312 (arg_mem_size ? !btf_type_is_void(ref_t) : 1)) { 11313 verbose(env, "%s pointer type %s %s must point to %sscalar, or struct with scalar\n", 11314 reg_arg_name(env, argno), 11315 btf_type_str(ref_t), ref_tname, arg_mem_size ? "void, " : ""); 11316 return -EINVAL; 11317 } 11318 return arg_mem_size ? KF_ARG_PTR_TO_MEM_SIZE : KF_ARG_PTR_TO_MEM; 11319 } 11320 11321 static int process_kf_arg_ptr_to_btf_id(struct bpf_verifier_env *env, 11322 struct bpf_reg_state *reg, 11323 const struct btf_type *ref_t, 11324 const char *ref_tname, u32 ref_id, 11325 struct bpf_kfunc_call_arg_meta *meta, 11326 int arg, argno_t argno) 11327 { 11328 const struct btf_type *reg_ref_t; 11329 bool strict_type_match = false; 11330 const struct btf *reg_btf; 11331 const char *reg_ref_tname; 11332 bool taking_projection; 11333 bool struct_same; 11334 u32 reg_ref_id; 11335 11336 if (base_type(reg->type) == PTR_TO_BTF_ID) { 11337 reg_btf = reg->btf; 11338 reg_ref_id = reg->btf_id; 11339 } else { 11340 reg_btf = btf_vmlinux; 11341 reg_ref_id = *reg2btf_ids[base_type(reg->type)]; 11342 } 11343 11344 /* Enforce strict type matching for calls to kfuncs that are acquiring 11345 * or releasing a reference, or are no-cast aliases. We do _not_ 11346 * enforce strict matching for kfuncs by default, 11347 * as we want to enable BPF programs to pass types that are bitwise 11348 * equivalent without forcing them to explicitly cast with something 11349 * like bpf_cast_to_kern_ctx(). 11350 * 11351 * For example, say we had a type like the following: 11352 * 11353 * struct bpf_cpumask { 11354 * cpumask_t cpumask; 11355 * refcount_t usage; 11356 * }; 11357 * 11358 * Note that as specified in <linux/cpumask.h>, cpumask_t is typedef'ed 11359 * to a struct cpumask, so it would be safe to pass a struct 11360 * bpf_cpumask * to a kfunc expecting a struct cpumask *. 11361 * 11362 * The philosophy here is similar to how we allow scalars of different 11363 * types to be passed to kfuncs as long as the size is the same. The 11364 * only difference here is that we're simply allowing 11365 * btf_struct_ids_match() to walk the struct at the 0th offset, and 11366 * resolve types. 11367 */ 11368 if ((is_kfunc_release(meta) && reg->ref_obj_id) || 11369 btf_type_ids_nocast_alias(&env->log, reg_btf, reg_ref_id, meta->btf, ref_id)) 11370 strict_type_match = true; 11371 11372 WARN_ON_ONCE(is_kfunc_release(meta) && !tnum_is_const(reg->var_off)); 11373 11374 reg_ref_t = btf_type_skip_modifiers(reg_btf, reg_ref_id, ®_ref_id); 11375 reg_ref_tname = btf_name_by_offset(reg_btf, reg_ref_t->name_off); 11376 struct_same = btf_struct_ids_match(&env->log, reg_btf, reg_ref_id, reg->var_off.value, 11377 meta->btf, ref_id, strict_type_match); 11378 /* If kfunc is accepting a projection type (ie. __sk_buff), it cannot 11379 * actually use it -- it must cast to the underlying type. So we allow 11380 * caller to pass in the underlying type. 11381 */ 11382 taking_projection = btf_is_projection_of(ref_tname, reg_ref_tname); 11383 if (!taking_projection && !struct_same) { 11384 verbose(env, "kernel function %s %s expected pointer to %s %s but %s has a pointer to %s %s\n", 11385 meta->func_name, reg_arg_name(env, argno), 11386 btf_type_str(ref_t), ref_tname, reg_arg_name(env, argno), 11387 btf_type_str(reg_ref_t), reg_ref_tname); 11388 return -EINVAL; 11389 } 11390 return 0; 11391 } 11392 11393 static int process_irq_flag(struct bpf_verifier_env *env, struct bpf_reg_state *reg, argno_t argno, 11394 struct bpf_kfunc_call_arg_meta *meta) 11395 { 11396 int err, kfunc_class = IRQ_NATIVE_KFUNC; 11397 bool irq_save; 11398 11399 if (meta->func_id == special_kfunc_list[KF_bpf_local_irq_save] || 11400 meta->func_id == special_kfunc_list[KF_bpf_res_spin_lock_irqsave]) { 11401 irq_save = true; 11402 if (meta->func_id == special_kfunc_list[KF_bpf_res_spin_lock_irqsave]) 11403 kfunc_class = IRQ_LOCK_KFUNC; 11404 } else if (meta->func_id == special_kfunc_list[KF_bpf_local_irq_restore] || 11405 meta->func_id == special_kfunc_list[KF_bpf_res_spin_unlock_irqrestore]) { 11406 irq_save = false; 11407 if (meta->func_id == special_kfunc_list[KF_bpf_res_spin_unlock_irqrestore]) 11408 kfunc_class = IRQ_LOCK_KFUNC; 11409 } else { 11410 verifier_bug(env, "unknown irq flags kfunc"); 11411 return -EFAULT; 11412 } 11413 11414 if (irq_save) { 11415 if (!is_irq_flag_reg_valid_uninit(env, reg)) { 11416 verbose(env, "expected uninitialized irq flag as %s\n", 11417 reg_arg_name(env, argno)); 11418 return -EINVAL; 11419 } 11420 11421 err = check_mem_access(env, env->insn_idx, reg, argno, 0, BPF_DW, 11422 BPF_WRITE, -1, false, false); 11423 if (err) 11424 return err; 11425 11426 err = mark_stack_slot_irq_flag(env, meta, reg, env->insn_idx, kfunc_class); 11427 if (err) 11428 return err; 11429 } else { 11430 err = is_irq_flag_reg_valid_init(env, reg); 11431 if (err) { 11432 verbose(env, "expected an initialized irq flag as %s\n", 11433 reg_arg_name(env, argno)); 11434 return err; 11435 } 11436 11437 err = mark_irq_flag_read(env, reg); 11438 if (err) 11439 return err; 11440 11441 err = unmark_stack_slot_irq_flag(env, reg, kfunc_class); 11442 if (err) 11443 return err; 11444 } 11445 return 0; 11446 } 11447 11448 11449 static int ref_set_non_owning(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 11450 { 11451 struct btf_record *rec = reg_btf_record(reg); 11452 11453 if (!env->cur_state->active_locks) { 11454 verifier_bug(env, "%s w/o active lock", __func__); 11455 return -EFAULT; 11456 } 11457 11458 if (type_flag(reg->type) & NON_OWN_REF) { 11459 verifier_bug(env, "NON_OWN_REF already set"); 11460 return -EFAULT; 11461 } 11462 11463 reg->type |= NON_OWN_REF; 11464 if (rec->refcount_off >= 0) 11465 reg->type |= MEM_RCU; 11466 11467 return 0; 11468 } 11469 11470 static int ref_convert_owning_non_owning(struct bpf_verifier_env *env, u32 ref_obj_id) 11471 { 11472 struct bpf_verifier_state *state = env->cur_state; 11473 struct bpf_func_state *unused; 11474 struct bpf_reg_state *reg; 11475 int i; 11476 11477 if (!ref_obj_id) { 11478 verifier_bug(env, "ref_obj_id is zero for owning -> non-owning conversion"); 11479 return -EFAULT; 11480 } 11481 11482 for (i = 0; i < state->acquired_refs; i++) { 11483 if (state->refs[i].id != ref_obj_id) 11484 continue; 11485 11486 /* Clear ref_obj_id here so release_reference doesn't clobber 11487 * the whole reg 11488 */ 11489 bpf_for_each_reg_in_vstate(env->cur_state, unused, reg, ({ 11490 if (reg->ref_obj_id == ref_obj_id) { 11491 reg->ref_obj_id = 0; 11492 ref_set_non_owning(env, reg); 11493 } 11494 })); 11495 return 0; 11496 } 11497 11498 verifier_bug(env, "ref state missing for ref_obj_id"); 11499 return -EFAULT; 11500 } 11501 11502 /* Implementation details: 11503 * 11504 * Each register points to some region of memory, which we define as an 11505 * allocation. Each allocation may embed a bpf_spin_lock which protects any 11506 * special BPF objects (bpf_list_head, bpf_rb_root, etc.) part of the same 11507 * allocation. The lock and the data it protects are colocated in the same 11508 * memory region. 11509 * 11510 * Hence, everytime a register holds a pointer value pointing to such 11511 * allocation, the verifier preserves a unique reg->id for it. 11512 * 11513 * The verifier remembers the lock 'ptr' and the lock 'id' whenever 11514 * bpf_spin_lock is called. 11515 * 11516 * To enable this, lock state in the verifier captures two values: 11517 * active_lock.ptr = Register's type specific pointer 11518 * active_lock.id = A unique ID for each register pointer value 11519 * 11520 * Currently, PTR_TO_MAP_VALUE and PTR_TO_BTF_ID | MEM_ALLOC are the two 11521 * supported register types. 11522 * 11523 * The active_lock.ptr in case of map values is the reg->map_ptr, and in case of 11524 * allocated objects is the reg->btf pointer. 11525 * 11526 * The active_lock.id is non-unique for maps supporting direct_value_addr, as we 11527 * can establish the provenance of the map value statically for each distinct 11528 * lookup into such maps. They always contain a single map value hence unique 11529 * IDs for each pseudo load pessimizes the algorithm and rejects valid programs. 11530 * 11531 * So, in case of global variables, they use array maps with max_entries = 1, 11532 * hence their active_lock.ptr becomes map_ptr and id = 0 (since they all point 11533 * into the same map value as max_entries is 1, as described above). 11534 * 11535 * In case of inner map lookups, the inner map pointer has same map_ptr as the 11536 * outer map pointer (in verifier context), but each lookup into an inner map 11537 * assigns a fresh reg->id to the lookup, so while lookups into distinct inner 11538 * maps from the same outer map share the same map_ptr as active_lock.ptr, they 11539 * will get different reg->id assigned to each lookup, hence different 11540 * active_lock.id. 11541 * 11542 * In case of allocated objects, active_lock.ptr is the reg->btf, and the 11543 * reg->id is a unique ID preserved after the NULL pointer check on the pointer 11544 * returned from bpf_obj_new. Each allocation receives a new reg->id. 11545 */ 11546 static int check_reg_allocation_locked(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 11547 { 11548 struct bpf_reference_state *s; 11549 void *ptr; 11550 u32 id; 11551 11552 switch ((int)reg->type) { 11553 case PTR_TO_MAP_VALUE: 11554 ptr = reg->map_ptr; 11555 break; 11556 case PTR_TO_BTF_ID | MEM_ALLOC: 11557 ptr = reg->btf; 11558 break; 11559 default: 11560 verifier_bug(env, "unknown reg type for lock check"); 11561 return -EFAULT; 11562 } 11563 id = reg->id; 11564 11565 if (!env->cur_state->active_locks) 11566 return -EINVAL; 11567 s = find_lock_state(env->cur_state, REF_TYPE_LOCK_MASK, id, ptr); 11568 if (!s) { 11569 verbose(env, "held lock and object are not in the same allocation\n"); 11570 return -EINVAL; 11571 } 11572 return 0; 11573 } 11574 11575 static bool is_bpf_list_api_kfunc(u32 btf_id) 11576 { 11577 return is_bpf_list_push_kfunc(btf_id) || 11578 btf_id == special_kfunc_list[KF_bpf_list_pop_front] || 11579 btf_id == special_kfunc_list[KF_bpf_list_pop_back] || 11580 btf_id == special_kfunc_list[KF_bpf_list_del] || 11581 btf_id == special_kfunc_list[KF_bpf_list_front] || 11582 btf_id == special_kfunc_list[KF_bpf_list_back] || 11583 btf_id == special_kfunc_list[KF_bpf_list_is_first] || 11584 btf_id == special_kfunc_list[KF_bpf_list_is_last] || 11585 btf_id == special_kfunc_list[KF_bpf_list_empty]; 11586 } 11587 11588 static bool is_bpf_rbtree_api_kfunc(u32 btf_id) 11589 { 11590 return is_bpf_rbtree_add_kfunc(btf_id) || 11591 btf_id == special_kfunc_list[KF_bpf_rbtree_remove] || 11592 btf_id == special_kfunc_list[KF_bpf_rbtree_first] || 11593 btf_id == special_kfunc_list[KF_bpf_rbtree_root] || 11594 btf_id == special_kfunc_list[KF_bpf_rbtree_left] || 11595 btf_id == special_kfunc_list[KF_bpf_rbtree_right]; 11596 } 11597 11598 static bool is_bpf_iter_num_api_kfunc(u32 btf_id) 11599 { 11600 return btf_id == special_kfunc_list[KF_bpf_iter_num_new] || 11601 btf_id == special_kfunc_list[KF_bpf_iter_num_next] || 11602 btf_id == special_kfunc_list[KF_bpf_iter_num_destroy]; 11603 } 11604 11605 static bool is_bpf_graph_api_kfunc(u32 btf_id) 11606 { 11607 return is_bpf_list_api_kfunc(btf_id) || 11608 is_bpf_rbtree_api_kfunc(btf_id) || 11609 is_bpf_refcount_acquire_kfunc(btf_id); 11610 } 11611 11612 static bool is_bpf_res_spin_lock_kfunc(u32 btf_id) 11613 { 11614 return btf_id == special_kfunc_list[KF_bpf_res_spin_lock] || 11615 btf_id == special_kfunc_list[KF_bpf_res_spin_unlock] || 11616 btf_id == special_kfunc_list[KF_bpf_res_spin_lock_irqsave] || 11617 btf_id == special_kfunc_list[KF_bpf_res_spin_unlock_irqrestore]; 11618 } 11619 11620 static bool is_bpf_arena_kfunc(u32 btf_id) 11621 { 11622 return btf_id == special_kfunc_list[KF_bpf_arena_alloc_pages] || 11623 btf_id == special_kfunc_list[KF_bpf_arena_free_pages] || 11624 btf_id == special_kfunc_list[KF_bpf_arena_reserve_pages]; 11625 } 11626 11627 static bool is_bpf_stream_kfunc(u32 btf_id) 11628 { 11629 return btf_id == special_kfunc_list[KF_bpf_stream_vprintk] || 11630 btf_id == special_kfunc_list[KF_bpf_stream_print_stack]; 11631 } 11632 11633 static bool kfunc_spin_allowed(u32 btf_id) 11634 { 11635 return is_bpf_graph_api_kfunc(btf_id) || is_bpf_iter_num_api_kfunc(btf_id) || 11636 is_bpf_res_spin_lock_kfunc(btf_id) || is_bpf_arena_kfunc(btf_id) || 11637 is_bpf_stream_kfunc(btf_id); 11638 } 11639 11640 static bool is_sync_callback_calling_kfunc(u32 btf_id) 11641 { 11642 return is_bpf_rbtree_add_kfunc(btf_id); 11643 } 11644 11645 static bool is_async_callback_calling_kfunc(u32 btf_id) 11646 { 11647 return is_bpf_wq_set_callback_kfunc(btf_id) || 11648 is_task_work_add_kfunc(btf_id); 11649 } 11650 11651 bool bpf_is_throw_kfunc(struct bpf_insn *insn) 11652 { 11653 return bpf_pseudo_kfunc_call(insn) && insn->off == 0 && 11654 insn->imm == special_kfunc_list[KF_bpf_throw]; 11655 } 11656 11657 static bool is_bpf_wq_set_callback_kfunc(u32 btf_id) 11658 { 11659 return btf_id == special_kfunc_list[KF_bpf_wq_set_callback]; 11660 } 11661 11662 static bool is_callback_calling_kfunc(u32 btf_id) 11663 { 11664 return is_sync_callback_calling_kfunc(btf_id) || 11665 is_async_callback_calling_kfunc(btf_id); 11666 } 11667 11668 static bool is_rbtree_lock_required_kfunc(u32 btf_id) 11669 { 11670 return is_bpf_rbtree_api_kfunc(btf_id); 11671 } 11672 11673 static bool check_kfunc_is_graph_root_api(struct bpf_verifier_env *env, 11674 enum btf_field_type head_field_type, 11675 u32 kfunc_btf_id) 11676 { 11677 bool ret; 11678 11679 switch (head_field_type) { 11680 case BPF_LIST_HEAD: 11681 ret = is_bpf_list_api_kfunc(kfunc_btf_id); 11682 break; 11683 case BPF_RB_ROOT: 11684 ret = is_bpf_rbtree_api_kfunc(kfunc_btf_id); 11685 break; 11686 default: 11687 verbose(env, "verifier internal error: unexpected graph root argument type %s\n", 11688 btf_field_type_name(head_field_type)); 11689 return false; 11690 } 11691 11692 if (!ret) 11693 verbose(env, "verifier internal error: %s head arg for unknown kfunc\n", 11694 btf_field_type_name(head_field_type)); 11695 return ret; 11696 } 11697 11698 static bool check_kfunc_is_graph_node_api(struct bpf_verifier_env *env, 11699 enum btf_field_type node_field_type, 11700 u32 kfunc_btf_id) 11701 { 11702 bool ret; 11703 11704 switch (node_field_type) { 11705 case BPF_LIST_NODE: 11706 ret = is_bpf_list_push_kfunc(kfunc_btf_id) || 11707 kfunc_btf_id == special_kfunc_list[KF_bpf_list_del] || 11708 kfunc_btf_id == special_kfunc_list[KF_bpf_list_is_first] || 11709 kfunc_btf_id == special_kfunc_list[KF_bpf_list_is_last]; 11710 break; 11711 case BPF_RB_NODE: 11712 ret = (is_bpf_rbtree_add_kfunc(kfunc_btf_id) || 11713 kfunc_btf_id == special_kfunc_list[KF_bpf_rbtree_remove] || 11714 kfunc_btf_id == special_kfunc_list[KF_bpf_rbtree_left] || 11715 kfunc_btf_id == special_kfunc_list[KF_bpf_rbtree_right]); 11716 break; 11717 default: 11718 verbose(env, "verifier internal error: unexpected graph node argument type %s\n", 11719 btf_field_type_name(node_field_type)); 11720 return false; 11721 } 11722 11723 if (!ret) 11724 verbose(env, "verifier internal error: %s node arg for unknown kfunc\n", 11725 btf_field_type_name(node_field_type)); 11726 return ret; 11727 } 11728 11729 static int 11730 __process_kf_arg_ptr_to_graph_root(struct bpf_verifier_env *env, 11731 struct bpf_reg_state *reg, argno_t argno, 11732 struct bpf_kfunc_call_arg_meta *meta, 11733 enum btf_field_type head_field_type, 11734 struct btf_field **head_field) 11735 { 11736 const char *head_type_name; 11737 struct btf_field *field; 11738 struct btf_record *rec; 11739 u32 head_off; 11740 11741 if (meta->btf != btf_vmlinux) { 11742 verifier_bug(env, "unexpected btf mismatch in kfunc call"); 11743 return -EFAULT; 11744 } 11745 11746 if (!check_kfunc_is_graph_root_api(env, head_field_type, meta->func_id)) 11747 return -EFAULT; 11748 11749 head_type_name = btf_field_type_name(head_field_type); 11750 if (!tnum_is_const(reg->var_off)) { 11751 verbose(env, 11752 "%s doesn't have constant offset. %s has to be at the constant offset\n", 11753 reg_arg_name(env, argno), head_type_name); 11754 return -EINVAL; 11755 } 11756 11757 rec = reg_btf_record(reg); 11758 head_off = reg->var_off.value; 11759 field = btf_record_find(rec, head_off, head_field_type); 11760 if (!field) { 11761 verbose(env, "%s not found at offset=%u\n", head_type_name, head_off); 11762 return -EINVAL; 11763 } 11764 11765 /* All functions require bpf_list_head to be protected using a bpf_spin_lock */ 11766 if (check_reg_allocation_locked(env, reg)) { 11767 verbose(env, "bpf_spin_lock at off=%d must be held for %s\n", 11768 rec->spin_lock_off, head_type_name); 11769 return -EINVAL; 11770 } 11771 11772 if (*head_field) { 11773 verifier_bug(env, "repeating %s arg", head_type_name); 11774 return -EFAULT; 11775 } 11776 *head_field = field; 11777 return 0; 11778 } 11779 11780 static int process_kf_arg_ptr_to_list_head(struct bpf_verifier_env *env, 11781 struct bpf_reg_state *reg, argno_t argno, 11782 struct bpf_kfunc_call_arg_meta *meta) 11783 { 11784 return __process_kf_arg_ptr_to_graph_root(env, reg, argno, meta, BPF_LIST_HEAD, 11785 &meta->arg_list_head.field); 11786 } 11787 11788 static int process_kf_arg_ptr_to_rbtree_root(struct bpf_verifier_env *env, 11789 struct bpf_reg_state *reg, argno_t argno, 11790 struct bpf_kfunc_call_arg_meta *meta) 11791 { 11792 return __process_kf_arg_ptr_to_graph_root(env, reg, argno, meta, BPF_RB_ROOT, 11793 &meta->arg_rbtree_root.field); 11794 } 11795 11796 static int 11797 __process_kf_arg_ptr_to_graph_node(struct bpf_verifier_env *env, 11798 struct bpf_reg_state *reg, argno_t argno, 11799 struct bpf_kfunc_call_arg_meta *meta, 11800 enum btf_field_type head_field_type, 11801 enum btf_field_type node_field_type, 11802 struct btf_field **node_field) 11803 { 11804 const char *node_type_name; 11805 const struct btf_type *et, *t; 11806 struct btf_field *field; 11807 u32 node_off; 11808 11809 if (meta->btf != btf_vmlinux) { 11810 verifier_bug(env, "unexpected btf mismatch in kfunc call"); 11811 return -EFAULT; 11812 } 11813 11814 if (!check_kfunc_is_graph_node_api(env, node_field_type, meta->func_id)) 11815 return -EFAULT; 11816 11817 node_type_name = btf_field_type_name(node_field_type); 11818 if (!tnum_is_const(reg->var_off)) { 11819 verbose(env, 11820 "%s doesn't have constant offset. %s has to be at the constant offset\n", 11821 reg_arg_name(env, argno), node_type_name); 11822 return -EINVAL; 11823 } 11824 11825 node_off = reg->var_off.value; 11826 field = reg_find_field_offset(reg, node_off, node_field_type); 11827 if (!field) { 11828 verbose(env, "%s not found at offset=%u\n", node_type_name, node_off); 11829 return -EINVAL; 11830 } 11831 11832 field = *node_field; 11833 11834 et = btf_type_by_id(field->graph_root.btf, field->graph_root.value_btf_id); 11835 t = btf_type_by_id(reg->btf, reg->btf_id); 11836 if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, 0, field->graph_root.btf, 11837 field->graph_root.value_btf_id, true)) { 11838 verbose(env, "operation on %s expects arg#1 %s at offset=%d " 11839 "in struct %s, but arg is at offset=%d in struct %s\n", 11840 btf_field_type_name(head_field_type), 11841 btf_field_type_name(node_field_type), 11842 field->graph_root.node_offset, 11843 btf_name_by_offset(field->graph_root.btf, et->name_off), 11844 node_off, btf_name_by_offset(reg->btf, t->name_off)); 11845 return -EINVAL; 11846 } 11847 meta->arg_btf = reg->btf; 11848 meta->arg_btf_id = reg->btf_id; 11849 11850 if (node_off != field->graph_root.node_offset) { 11851 verbose(env, "arg#1 offset=%d, but expected %s at offset=%d in struct %s\n", 11852 node_off, btf_field_type_name(node_field_type), 11853 field->graph_root.node_offset, 11854 btf_name_by_offset(field->graph_root.btf, et->name_off)); 11855 return -EINVAL; 11856 } 11857 11858 return 0; 11859 } 11860 11861 static int process_kf_arg_ptr_to_list_node(struct bpf_verifier_env *env, 11862 struct bpf_reg_state *reg, argno_t argno, 11863 struct bpf_kfunc_call_arg_meta *meta) 11864 { 11865 return __process_kf_arg_ptr_to_graph_node(env, reg, argno, meta, 11866 BPF_LIST_HEAD, BPF_LIST_NODE, 11867 &meta->arg_list_head.field); 11868 } 11869 11870 static int process_kf_arg_ptr_to_rbtree_node(struct bpf_verifier_env *env, 11871 struct bpf_reg_state *reg, argno_t argno, 11872 struct bpf_kfunc_call_arg_meta *meta) 11873 { 11874 return __process_kf_arg_ptr_to_graph_node(env, reg, argno, meta, 11875 BPF_RB_ROOT, BPF_RB_NODE, 11876 &meta->arg_rbtree_root.field); 11877 } 11878 11879 /* 11880 * css_task iter allowlist is needed to avoid dead locking on css_set_lock. 11881 * LSM hooks and iters (both sleepable and non-sleepable) are safe. 11882 * Any sleepable progs are also safe since bpf_check_attach_target() enforce 11883 * them can only be attached to some specific hook points. 11884 */ 11885 static bool check_css_task_iter_allowlist(struct bpf_verifier_env *env) 11886 { 11887 enum bpf_prog_type prog_type = resolve_prog_type(env->prog); 11888 11889 switch (prog_type) { 11890 case BPF_PROG_TYPE_LSM: 11891 return true; 11892 case BPF_PROG_TYPE_TRACING: 11893 if (env->prog->expected_attach_type == BPF_TRACE_ITER) 11894 return true; 11895 fallthrough; 11896 default: 11897 return in_sleepable(env); 11898 } 11899 } 11900 11901 static int check_kfunc_args(struct bpf_verifier_env *env, struct bpf_kfunc_call_arg_meta *meta, 11902 int insn_idx) 11903 { 11904 const char *func_name = meta->func_name, *ref_tname; 11905 struct bpf_func_state *caller = cur_func(env); 11906 struct bpf_reg_state *regs = cur_regs(env); 11907 const struct btf *btf = meta->btf; 11908 const struct btf_param *args; 11909 struct btf_record *rec; 11910 u32 i, nargs; 11911 int ret; 11912 11913 args = (const struct btf_param *)(meta->func_proto + 1); 11914 nargs = btf_type_vlen(meta->func_proto); 11915 if (nargs > MAX_BPF_FUNC_ARGS) { 11916 verbose(env, "Function %s has %d > %d args\n", func_name, nargs, 11917 MAX_BPF_FUNC_ARGS); 11918 return -EINVAL; 11919 } 11920 if (nargs > MAX_BPF_FUNC_REG_ARGS && !bpf_jit_supports_stack_args()) { 11921 verbose(env, "JIT does not support kfunc %s() with %d args\n", 11922 func_name, nargs); 11923 return -ENOTSUPP; 11924 } 11925 11926 ret = check_outgoing_stack_args(env, caller, nargs); 11927 if (ret) 11928 return ret; 11929 11930 /* Check that BTF function arguments match actual types that the 11931 * verifier sees. 11932 */ 11933 for (i = 0; i < nargs; i++) { 11934 struct bpf_reg_state *reg = get_func_arg_reg(caller, regs, i); 11935 const struct btf_type *t, *ref_t, *resolve_ret; 11936 enum bpf_arg_type arg_type = ARG_DONTCARE; 11937 argno_t argno = argno_from_arg(i + 1); 11938 int regno = reg_from_argno(argno); 11939 u32 ref_id, type_size; 11940 bool is_ret_buf_sz = false; 11941 int kf_arg_type; 11942 11943 if (is_kfunc_arg_prog_aux(btf, &args[i])) { 11944 /* Reject repeated use bpf_prog_aux */ 11945 if (meta->arg_prog) { 11946 verifier_bug(env, "Only 1 prog->aux argument supported per-kfunc"); 11947 return -EFAULT; 11948 } 11949 if (regno < 0) { 11950 verbose(env, "%s prog->aux cannot be a stack argument\n", 11951 reg_arg_name(env, argno)); 11952 return -EINVAL; 11953 } 11954 meta->arg_prog = true; 11955 cur_aux(env)->arg_prog = regno; 11956 continue; 11957 } 11958 11959 if (is_kfunc_arg_ignore(btf, &args[i]) || is_kfunc_arg_implicit(meta, i)) 11960 continue; 11961 11962 t = btf_type_skip_modifiers(btf, args[i].type, NULL); 11963 11964 if (btf_type_is_scalar(t)) { 11965 if (reg->type != SCALAR_VALUE) { 11966 verbose(env, "%s is not a scalar\n", reg_arg_name(env, argno)); 11967 return -EINVAL; 11968 } 11969 11970 if (is_kfunc_arg_constant(meta->btf, &args[i])) { 11971 if (meta->arg_constant.found) { 11972 verifier_bug(env, "only one constant argument permitted"); 11973 return -EFAULT; 11974 } 11975 if (!tnum_is_const(reg->var_off)) { 11976 verbose(env, "%s must be a known constant\n", 11977 reg_arg_name(env, argno)); 11978 return -EINVAL; 11979 } 11980 if (regno >= 0) 11981 ret = mark_chain_precision(env, regno); 11982 else 11983 ret = mark_stack_arg_precision(env, i); 11984 if (ret < 0) 11985 return ret; 11986 meta->arg_constant.found = true; 11987 meta->arg_constant.value = reg->var_off.value; 11988 } else if (is_kfunc_arg_scalar_with_name(btf, &args[i], "rdonly_buf_size")) { 11989 meta->r0_rdonly = true; 11990 is_ret_buf_sz = true; 11991 } else if (is_kfunc_arg_scalar_with_name(btf, &args[i], "rdwr_buf_size")) { 11992 is_ret_buf_sz = true; 11993 } 11994 11995 if (is_ret_buf_sz) { 11996 if (meta->r0_size) { 11997 verbose(env, "2 or more rdonly/rdwr_buf_size parameters for kfunc"); 11998 return -EINVAL; 11999 } 12000 12001 if (!tnum_is_const(reg->var_off)) { 12002 verbose(env, "%s is not a const\n", 12003 reg_arg_name(env, argno)); 12004 return -EINVAL; 12005 } 12006 12007 meta->r0_size = reg->var_off.value; 12008 if (regno >= 0) 12009 ret = mark_chain_precision(env, regno); 12010 else 12011 ret = mark_stack_arg_precision(env, i); 12012 if (ret) 12013 return ret; 12014 } 12015 continue; 12016 } 12017 12018 if (!btf_type_is_ptr(t)) { 12019 verbose(env, "Unrecognized %s type %s\n", 12020 reg_arg_name(env, argno), btf_type_str(t)); 12021 return -EINVAL; 12022 } 12023 12024 if ((bpf_register_is_null(reg) || type_may_be_null(reg->type)) && 12025 !is_kfunc_arg_nullable(meta->btf, &args[i])) { 12026 verbose(env, "Possibly NULL pointer passed to trusted %s\n", 12027 reg_arg_name(env, argno)); 12028 return -EACCES; 12029 } 12030 12031 if (reg->ref_obj_id) { 12032 if (is_kfunc_release(meta) && meta->ref_obj_id) { 12033 verifier_bug(env, "more than one arg with ref_obj_id %s %u %u", 12034 reg_arg_name(env, argno), reg->ref_obj_id, 12035 meta->ref_obj_id); 12036 return -EFAULT; 12037 } 12038 meta->ref_obj_id = reg->ref_obj_id; 12039 if (is_kfunc_release(meta)) { 12040 if (regno < 0) { 12041 verbose(env, "%s release arg cannot be a stack argument\n", 12042 reg_arg_name(env, argno)); 12043 return -EINVAL; 12044 } 12045 meta->release_regno = regno; 12046 } 12047 } 12048 12049 ref_t = btf_type_skip_modifiers(btf, t->type, &ref_id); 12050 ref_tname = btf_name_by_offset(btf, ref_t->name_off); 12051 12052 kf_arg_type = get_kfunc_ptr_arg_type(env, caller, regs, meta, t, ref_t, ref_tname, 12053 args, i, nargs, argno, reg); 12054 if (kf_arg_type < 0) 12055 return kf_arg_type; 12056 12057 switch (kf_arg_type) { 12058 case KF_ARG_PTR_TO_NULL: 12059 continue; 12060 case KF_ARG_PTR_TO_MAP: 12061 if (!reg->map_ptr) { 12062 verbose(env, "pointer in %s isn't map pointer\n", 12063 reg_arg_name(env, argno)); 12064 return -EINVAL; 12065 } 12066 if (meta->map.ptr && (reg->map_ptr->record->wq_off >= 0 || 12067 reg->map_ptr->record->task_work_off >= 0)) { 12068 /* Use map_uid (which is unique id of inner map) to reject: 12069 * inner_map1 = bpf_map_lookup_elem(outer_map, key1) 12070 * inner_map2 = bpf_map_lookup_elem(outer_map, key2) 12071 * if (inner_map1 && inner_map2) { 12072 * wq = bpf_map_lookup_elem(inner_map1); 12073 * if (wq) 12074 * // mismatch would have been allowed 12075 * bpf_wq_init(wq, inner_map2); 12076 * } 12077 * 12078 * Comparing map_ptr is enough to distinguish normal and outer maps. 12079 */ 12080 if (meta->map.ptr != reg->map_ptr || 12081 meta->map.uid != reg->map_uid) { 12082 if (reg->map_ptr->record->task_work_off >= 0) { 12083 verbose(env, 12084 "bpf_task_work pointer in R2 map_uid=%d doesn't match map pointer in R3 map_uid=%d\n", 12085 meta->map.uid, reg->map_uid); 12086 return -EINVAL; 12087 } 12088 verbose(env, 12089 "workqueue pointer in R1 map_uid=%d doesn't match map pointer in R2 map_uid=%d\n", 12090 meta->map.uid, reg->map_uid); 12091 return -EINVAL; 12092 } 12093 } 12094 meta->map.ptr = reg->map_ptr; 12095 meta->map.uid = reg->map_uid; 12096 fallthrough; 12097 case KF_ARG_PTR_TO_ALLOC_BTF_ID: 12098 case KF_ARG_PTR_TO_BTF_ID: 12099 if (!is_trusted_reg(reg)) { 12100 if (!is_kfunc_rcu(meta)) { 12101 verbose(env, "%s must be referenced or trusted\n", 12102 reg_arg_name(env, argno)); 12103 return -EINVAL; 12104 } 12105 if (!is_rcu_reg(reg)) { 12106 verbose(env, "%s must be a rcu pointer\n", 12107 reg_arg_name(env, argno)); 12108 return -EINVAL; 12109 } 12110 } 12111 fallthrough; 12112 case KF_ARG_PTR_TO_DYNPTR: 12113 case KF_ARG_PTR_TO_ITER: 12114 case KF_ARG_PTR_TO_LIST_HEAD: 12115 case KF_ARG_PTR_TO_LIST_NODE: 12116 case KF_ARG_PTR_TO_RB_ROOT: 12117 case KF_ARG_PTR_TO_RB_NODE: 12118 case KF_ARG_PTR_TO_MEM: 12119 case KF_ARG_PTR_TO_MEM_SIZE: 12120 case KF_ARG_PTR_TO_CALLBACK: 12121 case KF_ARG_PTR_TO_REFCOUNTED_KPTR: 12122 case KF_ARG_PTR_TO_CONST_STR: 12123 case KF_ARG_PTR_TO_WORKQUEUE: 12124 case KF_ARG_PTR_TO_TIMER: 12125 case KF_ARG_PTR_TO_TASK_WORK: 12126 case KF_ARG_PTR_TO_IRQ_FLAG: 12127 case KF_ARG_PTR_TO_RES_SPIN_LOCK: 12128 break; 12129 case KF_ARG_PTR_TO_CTX: 12130 arg_type = ARG_PTR_TO_CTX; 12131 break; 12132 default: 12133 verifier_bug(env, "unknown kfunc arg type %d", kf_arg_type); 12134 return -EFAULT; 12135 } 12136 12137 if (is_kfunc_release(meta) && reg->ref_obj_id) 12138 arg_type |= OBJ_RELEASE; 12139 ret = check_func_arg_reg_off(env, reg, argno, arg_type); 12140 if (ret < 0) 12141 return ret; 12142 12143 switch (kf_arg_type) { 12144 case KF_ARG_PTR_TO_CTX: 12145 if (reg->type != PTR_TO_CTX) { 12146 verbose(env, "%s expected pointer to ctx, but got %s\n", 12147 reg_arg_name(env, argno), reg_type_str(env, reg->type)); 12148 return -EINVAL; 12149 } 12150 12151 if (meta->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx]) { 12152 ret = get_kern_ctx_btf_id(&env->log, resolve_prog_type(env->prog)); 12153 if (ret < 0) 12154 return -EINVAL; 12155 meta->ret_btf_id = ret; 12156 } 12157 break; 12158 case KF_ARG_PTR_TO_ALLOC_BTF_ID: 12159 if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC)) { 12160 if (!is_bpf_obj_drop_kfunc(meta->func_id)) { 12161 verbose(env, "%s expected for bpf_obj_drop()\n", 12162 reg_arg_name(env, argno)); 12163 return -EINVAL; 12164 } 12165 } else if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC | MEM_PERCPU)) { 12166 if (!is_bpf_percpu_obj_drop_kfunc(meta->func_id)) { 12167 verbose(env, "%s expected for bpf_percpu_obj_drop()\n", 12168 reg_arg_name(env, argno)); 12169 return -EINVAL; 12170 } 12171 } else { 12172 verbose(env, "%s expected pointer to allocated object\n", 12173 reg_arg_name(env, argno)); 12174 return -EINVAL; 12175 } 12176 if (!reg->ref_obj_id) { 12177 verbose(env, "allocated object must be referenced\n"); 12178 return -EINVAL; 12179 } 12180 if (meta->btf == btf_vmlinux) { 12181 meta->arg_btf = reg->btf; 12182 meta->arg_btf_id = reg->btf_id; 12183 } 12184 break; 12185 case KF_ARG_PTR_TO_DYNPTR: 12186 { 12187 enum bpf_arg_type dynptr_arg_type = ARG_PTR_TO_DYNPTR; 12188 int clone_ref_obj_id = 0; 12189 12190 if (is_kfunc_arg_uninit(btf, &args[i])) 12191 dynptr_arg_type |= MEM_UNINIT; 12192 12193 if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_from_skb]) { 12194 dynptr_arg_type |= DYNPTR_TYPE_SKB; 12195 } else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_from_xdp]) { 12196 dynptr_arg_type |= DYNPTR_TYPE_XDP; 12197 } else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_from_skb_meta]) { 12198 dynptr_arg_type |= DYNPTR_TYPE_SKB_META; 12199 } else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_from_file]) { 12200 dynptr_arg_type |= DYNPTR_TYPE_FILE; 12201 } else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_file_discard]) { 12202 dynptr_arg_type |= DYNPTR_TYPE_FILE | OBJ_RELEASE; 12203 if (regno < 0) { 12204 verbose(env, "%s release arg cannot be a stack argument\n", 12205 reg_arg_name(env, argno)); 12206 return -EINVAL; 12207 } 12208 meta->release_regno = regno; 12209 } else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_clone] && 12210 (dynptr_arg_type & MEM_UNINIT)) { 12211 enum bpf_dynptr_type parent_type = meta->initialized_dynptr.type; 12212 12213 if (parent_type == BPF_DYNPTR_TYPE_INVALID) { 12214 verifier_bug(env, "no dynptr type for parent of clone"); 12215 return -EFAULT; 12216 } 12217 12218 dynptr_arg_type |= (unsigned int)get_dynptr_type_flag(parent_type); 12219 clone_ref_obj_id = meta->initialized_dynptr.ref_obj_id; 12220 if (dynptr_type_refcounted(parent_type) && !clone_ref_obj_id) { 12221 verifier_bug(env, "missing ref obj id for parent of clone"); 12222 return -EFAULT; 12223 } 12224 } 12225 12226 ret = process_dynptr_func(env, reg, argno, insn_idx, 12227 dynptr_arg_type, clone_ref_obj_id); 12228 if (ret < 0) 12229 return ret; 12230 12231 if (!(dynptr_arg_type & MEM_UNINIT)) { 12232 int id = dynptr_id(env, reg); 12233 12234 if (id < 0) { 12235 verifier_bug(env, "failed to obtain dynptr id"); 12236 return id; 12237 } 12238 meta->initialized_dynptr.id = id; 12239 meta->initialized_dynptr.type = dynptr_get_type(env, reg); 12240 meta->initialized_dynptr.ref_obj_id = dynptr_ref_obj_id(env, reg); 12241 } 12242 12243 break; 12244 } 12245 case KF_ARG_PTR_TO_ITER: 12246 if (meta->func_id == special_kfunc_list[KF_bpf_iter_css_task_new]) { 12247 if (!check_css_task_iter_allowlist(env)) { 12248 verbose(env, "css_task_iter is only allowed in bpf_lsm, bpf_iter and sleepable progs\n"); 12249 return -EINVAL; 12250 } 12251 } 12252 ret = process_iter_arg(env, reg, argno, insn_idx, meta); 12253 if (ret < 0) 12254 return ret; 12255 break; 12256 case KF_ARG_PTR_TO_LIST_HEAD: 12257 if (reg->type != PTR_TO_MAP_VALUE && 12258 reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) { 12259 verbose(env, "%s expected pointer to map value or allocated object\n", 12260 reg_arg_name(env, argno)); 12261 return -EINVAL; 12262 } 12263 if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC) && !reg->ref_obj_id) { 12264 verbose(env, "allocated object must be referenced\n"); 12265 return -EINVAL; 12266 } 12267 ret = process_kf_arg_ptr_to_list_head(env, reg, argno, meta); 12268 if (ret < 0) 12269 return ret; 12270 break; 12271 case KF_ARG_PTR_TO_RB_ROOT: 12272 if (reg->type != PTR_TO_MAP_VALUE && 12273 reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) { 12274 verbose(env, "%s expected pointer to map value or allocated object\n", 12275 reg_arg_name(env, argno)); 12276 return -EINVAL; 12277 } 12278 if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC) && !reg->ref_obj_id) { 12279 verbose(env, "allocated object must be referenced\n"); 12280 return -EINVAL; 12281 } 12282 ret = process_kf_arg_ptr_to_rbtree_root(env, reg, argno, meta); 12283 if (ret < 0) 12284 return ret; 12285 break; 12286 case KF_ARG_PTR_TO_LIST_NODE: 12287 if (is_kfunc_arg_nonown_allowed(btf, &args[i]) && 12288 type_is_non_owning_ref(reg->type) && !reg->ref_obj_id) { 12289 /* Allow bpf_list_front/back return value for 12290 * __nonown_allowed list-node arguments. 12291 */ 12292 goto check_ok; 12293 } 12294 if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) { 12295 verbose(env, "%s expected pointer to allocated object\n", 12296 reg_arg_name(env, argno)); 12297 return -EINVAL; 12298 } 12299 if (!reg->ref_obj_id) { 12300 verbose(env, "allocated object must be referenced\n"); 12301 return -EINVAL; 12302 } 12303 check_ok: 12304 ret = process_kf_arg_ptr_to_list_node(env, reg, argno, meta); 12305 if (ret < 0) 12306 return ret; 12307 break; 12308 case KF_ARG_PTR_TO_RB_NODE: 12309 if (is_bpf_rbtree_add_kfunc(meta->func_id)) { 12310 if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) { 12311 verbose(env, "%s expected pointer to allocated object\n", 12312 reg_arg_name(env, argno)); 12313 return -EINVAL; 12314 } 12315 if (!reg->ref_obj_id) { 12316 verbose(env, "allocated object must be referenced\n"); 12317 return -EINVAL; 12318 } 12319 } else { 12320 if (!type_is_non_owning_ref(reg->type) && !reg->ref_obj_id) { 12321 verbose(env, "%s can only take non-owning or refcounted bpf_rb_node pointer\n", func_name); 12322 return -EINVAL; 12323 } 12324 if (in_rbtree_lock_required_cb(env)) { 12325 verbose(env, "%s not allowed in rbtree cb\n", func_name); 12326 return -EINVAL; 12327 } 12328 } 12329 12330 ret = process_kf_arg_ptr_to_rbtree_node(env, reg, argno, meta); 12331 if (ret < 0) 12332 return ret; 12333 break; 12334 case KF_ARG_PTR_TO_MAP: 12335 /* If argument has '__map' suffix expect 'struct bpf_map *' */ 12336 ref_id = *reg2btf_ids[CONST_PTR_TO_MAP]; 12337 ref_t = btf_type_by_id(btf_vmlinux, ref_id); 12338 ref_tname = btf_name_by_offset(btf, ref_t->name_off); 12339 fallthrough; 12340 case KF_ARG_PTR_TO_BTF_ID: 12341 /* Only base_type is checked, further checks are done here */ 12342 if ((base_type(reg->type) != PTR_TO_BTF_ID || 12343 (bpf_type_has_unsafe_modifiers(reg->type) && !is_rcu_reg(reg))) && 12344 !reg2btf_ids[base_type(reg->type)]) { 12345 verbose(env, "%s is %s ", reg_arg_name(env, argno), 12346 reg_type_str(env, reg->type)); 12347 verbose(env, "expected %s or socket\n", 12348 reg_type_str(env, base_type(reg->type) | 12349 (type_flag(reg->type) & BPF_REG_TRUSTED_MODIFIERS))); 12350 return -EINVAL; 12351 } 12352 ret = process_kf_arg_ptr_to_btf_id(env, reg, ref_t, ref_tname, ref_id, meta, i, argno); 12353 if (ret < 0) 12354 return ret; 12355 break; 12356 case KF_ARG_PTR_TO_MEM: 12357 resolve_ret = btf_resolve_size(btf, ref_t, &type_size); 12358 if (IS_ERR(resolve_ret)) { 12359 verbose(env, "%s reference type('%s %s') size cannot be determined: %ld\n", 12360 reg_arg_name(env, argno), btf_type_str(ref_t), 12361 ref_tname, PTR_ERR(resolve_ret)); 12362 return -EINVAL; 12363 } 12364 ret = check_mem_reg(env, reg, argno, type_size); 12365 if (ret < 0) 12366 return ret; 12367 break; 12368 case KF_ARG_PTR_TO_MEM_SIZE: 12369 { 12370 struct bpf_reg_state *buff_reg = reg; 12371 const struct btf_param *buff_arg = &args[i]; 12372 struct bpf_reg_state *size_reg = get_func_arg_reg(caller, regs, i + 1); 12373 const struct btf_param *size_arg = &args[i + 1]; 12374 argno_t next_argno = argno_from_arg(i + 2); 12375 12376 if (!bpf_register_is_null(buff_reg) || !is_kfunc_arg_nullable(meta->btf, buff_arg)) { 12377 ret = check_kfunc_mem_size_reg(env, buff_reg, size_reg, 12378 argno, next_argno); 12379 if (ret < 0) { 12380 verbose(env, "%s and ", reg_arg_name(env, argno)); 12381 verbose(env, "%s memory, len pair leads to invalid memory access\n", 12382 reg_arg_name(env, next_argno)); 12383 return ret; 12384 } 12385 } 12386 12387 if (is_kfunc_arg_const_mem_size(meta->btf, size_arg, size_reg)) { 12388 if (meta->arg_constant.found) { 12389 verifier_bug(env, "only one constant argument permitted"); 12390 return -EFAULT; 12391 } 12392 if (!tnum_is_const(size_reg->var_off)) { 12393 verbose(env, "%s must be a known constant\n", 12394 reg_arg_name(env, next_argno)); 12395 return -EINVAL; 12396 } 12397 meta->arg_constant.found = true; 12398 meta->arg_constant.value = size_reg->var_off.value; 12399 } 12400 12401 /* Skip next '__sz' or '__szk' argument */ 12402 i++; 12403 break; 12404 } 12405 case KF_ARG_PTR_TO_CALLBACK: 12406 if (reg->type != PTR_TO_FUNC) { 12407 verbose(env, "%s expected pointer to func\n", reg_arg_name(env, argno)); 12408 return -EINVAL; 12409 } 12410 meta->subprogno = reg->subprogno; 12411 break; 12412 case KF_ARG_PTR_TO_REFCOUNTED_KPTR: 12413 if (!type_is_ptr_alloc_obj(reg->type)) { 12414 verbose(env, "%s is neither owning or non-owning ref\n", 12415 reg_arg_name(env, argno)); 12416 return -EINVAL; 12417 } 12418 if (!type_is_non_owning_ref(reg->type)) 12419 meta->arg_owning_ref = true; 12420 12421 rec = reg_btf_record(reg); 12422 if (!rec) { 12423 verifier_bug(env, "Couldn't find btf_record"); 12424 return -EFAULT; 12425 } 12426 12427 if (rec->refcount_off < 0) { 12428 verbose(env, "%s doesn't point to a type with bpf_refcount field\n", 12429 reg_arg_name(env, argno)); 12430 return -EINVAL; 12431 } 12432 12433 meta->arg_btf = reg->btf; 12434 meta->arg_btf_id = reg->btf_id; 12435 break; 12436 case KF_ARG_PTR_TO_CONST_STR: 12437 if (reg->type != PTR_TO_MAP_VALUE) { 12438 verbose(env, "%s doesn't point to a const string\n", 12439 reg_arg_name(env, argno)); 12440 return -EINVAL; 12441 } 12442 ret = check_arg_const_str(env, reg, argno); 12443 if (ret) 12444 return ret; 12445 break; 12446 case KF_ARG_PTR_TO_WORKQUEUE: 12447 if (reg->type != PTR_TO_MAP_VALUE) { 12448 verbose(env, "%s doesn't point to a map value\n", 12449 reg_arg_name(env, argno)); 12450 return -EINVAL; 12451 } 12452 ret = check_map_field_pointer(env, reg, argno, BPF_WORKQUEUE, &meta->map); 12453 if (ret < 0) 12454 return ret; 12455 break; 12456 case KF_ARG_PTR_TO_TIMER: 12457 if (reg->type != PTR_TO_MAP_VALUE) { 12458 verbose(env, "%s doesn't point to a map value\n", 12459 reg_arg_name(env, argno)); 12460 return -EINVAL; 12461 } 12462 ret = process_timer_kfunc(env, reg, argno, meta); 12463 if (ret < 0) 12464 return ret; 12465 break; 12466 case KF_ARG_PTR_TO_TASK_WORK: 12467 if (reg->type != PTR_TO_MAP_VALUE) { 12468 verbose(env, "%s doesn't point to a map value\n", 12469 reg_arg_name(env, argno)); 12470 return -EINVAL; 12471 } 12472 ret = check_map_field_pointer(env, reg, argno, BPF_TASK_WORK, &meta->map); 12473 if (ret < 0) 12474 return ret; 12475 break; 12476 case KF_ARG_PTR_TO_IRQ_FLAG: 12477 if (reg->type != PTR_TO_STACK) { 12478 verbose(env, "%s doesn't point to an irq flag on stack\n", 12479 reg_arg_name(env, argno)); 12480 return -EINVAL; 12481 } 12482 ret = process_irq_flag(env, reg, argno, meta); 12483 if (ret < 0) 12484 return ret; 12485 break; 12486 case KF_ARG_PTR_TO_RES_SPIN_LOCK: 12487 { 12488 int flags = PROCESS_RES_LOCK; 12489 12490 if (reg->type != PTR_TO_MAP_VALUE && reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) { 12491 verbose(env, "%s doesn't point to map value or allocated object\n", 12492 reg_arg_name(env, argno)); 12493 return -EINVAL; 12494 } 12495 12496 if (!is_bpf_res_spin_lock_kfunc(meta->func_id)) 12497 return -EFAULT; 12498 if (meta->func_id == special_kfunc_list[KF_bpf_res_spin_lock] || 12499 meta->func_id == special_kfunc_list[KF_bpf_res_spin_lock_irqsave]) 12500 flags |= PROCESS_SPIN_LOCK; 12501 if (meta->func_id == special_kfunc_list[KF_bpf_res_spin_lock_irqsave] || 12502 meta->func_id == special_kfunc_list[KF_bpf_res_spin_unlock_irqrestore]) 12503 flags |= PROCESS_LOCK_IRQ; 12504 ret = process_spin_lock(env, reg, argno, flags); 12505 if (ret < 0) 12506 return ret; 12507 break; 12508 } 12509 } 12510 } 12511 12512 if (is_kfunc_release(meta) && !meta->release_regno) { 12513 verbose(env, "release kernel function %s expects refcounted PTR_TO_BTF_ID\n", 12514 func_name); 12515 return -EINVAL; 12516 } 12517 12518 return 0; 12519 } 12520 12521 int bpf_fetch_kfunc_arg_meta(struct bpf_verifier_env *env, 12522 s32 func_id, 12523 s16 offset, 12524 struct bpf_kfunc_call_arg_meta *meta) 12525 { 12526 struct bpf_kfunc_meta kfunc; 12527 int err; 12528 12529 err = fetch_kfunc_meta(env, func_id, offset, &kfunc); 12530 if (err) 12531 return err; 12532 12533 memset(meta, 0, sizeof(*meta)); 12534 meta->btf = kfunc.btf; 12535 meta->func_id = kfunc.id; 12536 meta->func_proto = kfunc.proto; 12537 meta->func_name = kfunc.name; 12538 12539 if (!kfunc.flags || !btf_kfunc_is_allowed(kfunc.btf, kfunc.id, env->prog)) 12540 return -EACCES; 12541 12542 meta->kfunc_flags = *kfunc.flags; 12543 12544 return 0; 12545 } 12546 12547 /* 12548 * Determine how many bytes a helper accesses through a stack pointer at 12549 * argument position @arg (0-based, corresponding to R1-R5). 12550 * 12551 * Returns: 12552 * > 0 known read access size in bytes 12553 * 0 doesn't read anything directly 12554 * S64_MIN unknown 12555 * < 0 known write access of (-return) bytes 12556 */ 12557 s64 bpf_helper_stack_access_bytes(struct bpf_verifier_env *env, struct bpf_insn *insn, 12558 int arg, int insn_idx) 12559 { 12560 struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx]; 12561 const struct bpf_func_proto *fn; 12562 enum bpf_arg_type at; 12563 s64 size; 12564 12565 if (bpf_get_helper_proto(env, insn->imm, &fn) < 0) 12566 return S64_MIN; 12567 12568 at = fn->arg_type[arg]; 12569 12570 switch (base_type(at)) { 12571 case ARG_PTR_TO_MAP_KEY: 12572 case ARG_PTR_TO_MAP_VALUE: { 12573 bool is_key = base_type(at) == ARG_PTR_TO_MAP_KEY; 12574 u64 val; 12575 int i, map_reg; 12576 12577 for (i = 0; i < arg; i++) { 12578 if (base_type(fn->arg_type[i]) == ARG_CONST_MAP_PTR) 12579 break; 12580 } 12581 if (i >= arg) 12582 goto scan_all_maps; 12583 12584 map_reg = BPF_REG_1 + i; 12585 12586 if (!(aux->const_reg_map_mask & BIT(map_reg))) 12587 goto scan_all_maps; 12588 12589 i = aux->const_reg_vals[map_reg]; 12590 if (i < env->used_map_cnt) { 12591 size = is_key ? env->used_maps[i]->key_size 12592 : env->used_maps[i]->value_size; 12593 goto out; 12594 } 12595 scan_all_maps: 12596 /* 12597 * Map pointer is not known at this call site (e.g. different 12598 * maps on merged paths). Conservatively return the largest 12599 * key_size or value_size across all maps used by the program. 12600 */ 12601 val = 0; 12602 for (i = 0; i < env->used_map_cnt; i++) { 12603 struct bpf_map *map = env->used_maps[i]; 12604 u32 sz = is_key ? map->key_size : map->value_size; 12605 12606 if (sz > val) 12607 val = sz; 12608 if (map->inner_map_meta) { 12609 sz = is_key ? map->inner_map_meta->key_size 12610 : map->inner_map_meta->value_size; 12611 if (sz > val) 12612 val = sz; 12613 } 12614 } 12615 if (!val) 12616 return S64_MIN; 12617 size = val; 12618 goto out; 12619 } 12620 case ARG_PTR_TO_MEM: 12621 if (at & MEM_FIXED_SIZE) { 12622 size = fn->arg_size[arg]; 12623 goto out; 12624 } 12625 if (arg + 1 < ARRAY_SIZE(fn->arg_type) && 12626 arg_type_is_mem_size(fn->arg_type[arg + 1])) { 12627 int size_reg = BPF_REG_1 + arg + 1; 12628 12629 if (aux->const_reg_mask & BIT(size_reg)) { 12630 size = (s64)aux->const_reg_vals[size_reg]; 12631 goto out; 12632 } 12633 /* 12634 * Size arg is const on each path but differs across merged 12635 * paths. MAX_BPF_STACK is a safe upper bound for reads. 12636 */ 12637 if (at & MEM_UNINIT) 12638 return 0; 12639 return MAX_BPF_STACK; 12640 } 12641 return S64_MIN; 12642 case ARG_PTR_TO_DYNPTR: 12643 size = BPF_DYNPTR_SIZE; 12644 break; 12645 case ARG_PTR_TO_STACK: 12646 /* 12647 * Only used by bpf_calls_callback() helpers. The helper itself 12648 * doesn't access stack. The callback subprog does and it's 12649 * analyzed separately. 12650 */ 12651 return 0; 12652 default: 12653 return S64_MIN; 12654 } 12655 out: 12656 /* 12657 * MEM_UNINIT args are write-only: the helper initializes the 12658 * buffer without reading it. 12659 */ 12660 if (at & MEM_UNINIT) 12661 return -size; 12662 return size; 12663 } 12664 12665 /* 12666 * Determine how many bytes a kfunc accesses through a stack pointer at 12667 * argument position @arg (0-based, corresponding to R1-R5). 12668 * 12669 * Returns: 12670 * > 0 known read access size in bytes 12671 * 0 doesn't access memory through that argument (ex: not a pointer) 12672 * S64_MIN unknown 12673 * < 0 known write access of (-return) bytes 12674 */ 12675 s64 bpf_kfunc_stack_access_bytes(struct bpf_verifier_env *env, struct bpf_insn *insn, 12676 int arg, int insn_idx) 12677 { 12678 struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx]; 12679 struct bpf_kfunc_call_arg_meta meta; 12680 const struct btf_param *args; 12681 const struct btf_type *t, *ref_t; 12682 const struct btf *btf; 12683 u32 nargs, type_size; 12684 s64 size; 12685 12686 if (bpf_fetch_kfunc_arg_meta(env, insn->imm, insn->off, &meta) < 0) 12687 return S64_MIN; 12688 12689 btf = meta.btf; 12690 args = btf_params(meta.func_proto); 12691 nargs = btf_type_vlen(meta.func_proto); 12692 if (arg >= nargs) 12693 return 0; 12694 12695 t = btf_type_skip_modifiers(btf, args[arg].type, NULL); 12696 if (!btf_type_is_ptr(t)) 12697 return 0; 12698 12699 /* dynptr: fixed 16-byte on-stack representation */ 12700 if (is_kfunc_arg_dynptr(btf, &args[arg])) { 12701 size = BPF_DYNPTR_SIZE; 12702 goto out; 12703 } 12704 12705 /* ptr + __sz/__szk pair: size is in the next register */ 12706 if (arg + 1 < nargs && 12707 (btf_param_match_suffix(btf, &args[arg + 1], "__sz") || 12708 btf_param_match_suffix(btf, &args[arg + 1], "__szk"))) { 12709 int size_reg = BPF_REG_1 + arg + 1; 12710 12711 if (aux->const_reg_mask & BIT(size_reg)) { 12712 size = (s64)aux->const_reg_vals[size_reg]; 12713 goto out; 12714 } 12715 return MAX_BPF_STACK; 12716 } 12717 12718 /* fixed-size pointed-to type: resolve via BTF */ 12719 ref_t = btf_type_skip_modifiers(btf, t->type, NULL); 12720 if (!IS_ERR(btf_resolve_size(btf, ref_t, &type_size))) { 12721 size = type_size; 12722 goto out; 12723 } 12724 12725 return S64_MIN; 12726 out: 12727 /* KF_ITER_NEW kfuncs initialize the iterator state at arg 0 */ 12728 if (arg == 0 && meta.kfunc_flags & KF_ITER_NEW) 12729 return -size; 12730 if (is_kfunc_arg_uninit(btf, &args[arg])) 12731 return -size; 12732 return size; 12733 } 12734 12735 /* check special kfuncs and return: 12736 * 1 - not fall-through to 'else' branch, continue verification 12737 * 0 - fall-through to 'else' branch 12738 * < 0 - not fall-through to 'else' branch, return error 12739 */ 12740 static int check_special_kfunc(struct bpf_verifier_env *env, struct bpf_kfunc_call_arg_meta *meta, 12741 struct bpf_reg_state *regs, struct bpf_insn_aux_data *insn_aux, 12742 const struct btf_type *ptr_type, struct btf *desc_btf) 12743 { 12744 const struct btf_type *ret_t; 12745 int err = 0; 12746 12747 if (meta->btf != btf_vmlinux) 12748 return 0; 12749 12750 if (is_bpf_obj_new_kfunc(meta->func_id) || is_bpf_percpu_obj_new_kfunc(meta->func_id)) { 12751 struct btf_struct_meta *struct_meta; 12752 struct btf *ret_btf; 12753 u32 ret_btf_id; 12754 12755 if (is_bpf_obj_new_kfunc(meta->func_id) && !bpf_global_ma_set) 12756 return -ENOMEM; 12757 12758 if (((u64)(u32)meta->arg_constant.value) != meta->arg_constant.value) { 12759 verbose(env, "local type ID argument must be in range [0, U32_MAX]\n"); 12760 return -EINVAL; 12761 } 12762 12763 ret_btf = env->prog->aux->btf; 12764 ret_btf_id = meta->arg_constant.value; 12765 12766 /* This may be NULL due to user not supplying a BTF */ 12767 if (!ret_btf) { 12768 verbose(env, "bpf_obj_new/bpf_percpu_obj_new requires prog BTF\n"); 12769 return -EINVAL; 12770 } 12771 12772 ret_t = btf_type_by_id(ret_btf, ret_btf_id); 12773 if (!ret_t || !__btf_type_is_struct(ret_t)) { 12774 verbose(env, "bpf_obj_new/bpf_percpu_obj_new type ID argument must be of a struct\n"); 12775 return -EINVAL; 12776 } 12777 12778 if (is_bpf_percpu_obj_new_kfunc(meta->func_id)) { 12779 if (ret_t->size > BPF_GLOBAL_PERCPU_MA_MAX_SIZE) { 12780 verbose(env, "bpf_percpu_obj_new type size (%d) is greater than %d\n", 12781 ret_t->size, BPF_GLOBAL_PERCPU_MA_MAX_SIZE); 12782 return -EINVAL; 12783 } 12784 12785 if (!bpf_global_percpu_ma_set) { 12786 mutex_lock(&bpf_percpu_ma_lock); 12787 if (!bpf_global_percpu_ma_set) { 12788 /* Charge memory allocated with bpf_global_percpu_ma to 12789 * root memcg. The obj_cgroup for root memcg is NULL. 12790 */ 12791 err = bpf_mem_alloc_percpu_init(&bpf_global_percpu_ma, NULL); 12792 if (!err) 12793 bpf_global_percpu_ma_set = true; 12794 } 12795 mutex_unlock(&bpf_percpu_ma_lock); 12796 if (err) 12797 return err; 12798 } 12799 12800 mutex_lock(&bpf_percpu_ma_lock); 12801 err = bpf_mem_alloc_percpu_unit_init(&bpf_global_percpu_ma, ret_t->size); 12802 mutex_unlock(&bpf_percpu_ma_lock); 12803 if (err) 12804 return err; 12805 } 12806 12807 struct_meta = btf_find_struct_meta(ret_btf, ret_btf_id); 12808 if (is_bpf_percpu_obj_new_kfunc(meta->func_id)) { 12809 if (!__btf_type_is_scalar_struct(env, ret_btf, ret_t, 0)) { 12810 verbose(env, "bpf_percpu_obj_new type ID argument must be of a struct of scalars\n"); 12811 return -EINVAL; 12812 } 12813 12814 if (struct_meta) { 12815 verbose(env, "bpf_percpu_obj_new type ID argument must not contain special fields\n"); 12816 return -EINVAL; 12817 } 12818 } 12819 12820 mark_reg_known_zero(env, regs, BPF_REG_0); 12821 regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC; 12822 regs[BPF_REG_0].btf = ret_btf; 12823 regs[BPF_REG_0].btf_id = ret_btf_id; 12824 if (is_bpf_percpu_obj_new_kfunc(meta->func_id)) 12825 regs[BPF_REG_0].type |= MEM_PERCPU; 12826 12827 insn_aux->obj_new_size = ret_t->size; 12828 insn_aux->kptr_struct_meta = struct_meta; 12829 } else if (is_bpf_refcount_acquire_kfunc(meta->func_id)) { 12830 mark_reg_known_zero(env, regs, BPF_REG_0); 12831 regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC; 12832 regs[BPF_REG_0].btf = meta->arg_btf; 12833 regs[BPF_REG_0].btf_id = meta->arg_btf_id; 12834 12835 insn_aux->kptr_struct_meta = 12836 btf_find_struct_meta(meta->arg_btf, 12837 meta->arg_btf_id); 12838 } else if (is_list_node_type(ptr_type)) { 12839 struct btf_field *field = meta->arg_list_head.field; 12840 12841 mark_reg_graph_node(regs, BPF_REG_0, &field->graph_root); 12842 } else if (is_rbtree_node_type(ptr_type)) { 12843 struct btf_field *field = meta->arg_rbtree_root.field; 12844 12845 mark_reg_graph_node(regs, BPF_REG_0, &field->graph_root); 12846 } else if (meta->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx]) { 12847 mark_reg_known_zero(env, regs, BPF_REG_0); 12848 regs[BPF_REG_0].type = PTR_TO_BTF_ID | PTR_TRUSTED; 12849 regs[BPF_REG_0].btf = desc_btf; 12850 regs[BPF_REG_0].btf_id = meta->ret_btf_id; 12851 } else if (meta->func_id == special_kfunc_list[KF_bpf_rdonly_cast]) { 12852 ret_t = btf_type_by_id(desc_btf, meta->arg_constant.value); 12853 if (!ret_t) { 12854 verbose(env, "Unknown type ID %lld passed to kfunc bpf_rdonly_cast\n", 12855 meta->arg_constant.value); 12856 return -EINVAL; 12857 } else if (btf_type_is_struct(ret_t)) { 12858 mark_reg_known_zero(env, regs, BPF_REG_0); 12859 regs[BPF_REG_0].type = PTR_TO_BTF_ID | PTR_UNTRUSTED; 12860 regs[BPF_REG_0].btf = desc_btf; 12861 regs[BPF_REG_0].btf_id = meta->arg_constant.value; 12862 } else if (btf_type_is_void(ret_t)) { 12863 mark_reg_known_zero(env, regs, BPF_REG_0); 12864 regs[BPF_REG_0].type = PTR_TO_MEM | MEM_RDONLY | PTR_UNTRUSTED; 12865 regs[BPF_REG_0].mem_size = 0; 12866 } else { 12867 verbose(env, 12868 "kfunc bpf_rdonly_cast type ID argument must be of a struct or void\n"); 12869 return -EINVAL; 12870 } 12871 } else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_slice] || 12872 meta->func_id == special_kfunc_list[KF_bpf_dynptr_slice_rdwr]) { 12873 enum bpf_type_flag type_flag = get_dynptr_type_flag(meta->initialized_dynptr.type); 12874 12875 mark_reg_known_zero(env, regs, BPF_REG_0); 12876 12877 if (!meta->arg_constant.found) { 12878 verifier_bug(env, "bpf_dynptr_slice(_rdwr) no constant size"); 12879 return -EFAULT; 12880 } 12881 12882 regs[BPF_REG_0].mem_size = meta->arg_constant.value; 12883 12884 /* PTR_MAYBE_NULL will be added when is_kfunc_ret_null is checked */ 12885 regs[BPF_REG_0].type = PTR_TO_MEM | type_flag; 12886 12887 if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_slice]) { 12888 regs[BPF_REG_0].type |= MEM_RDONLY; 12889 } else { 12890 /* this will set env->seen_direct_write to true */ 12891 if (!may_access_direct_pkt_data(env, NULL, BPF_WRITE)) { 12892 verbose(env, "the prog does not allow writes to packet data\n"); 12893 return -EINVAL; 12894 } 12895 } 12896 12897 if (!meta->initialized_dynptr.id) { 12898 verifier_bug(env, "no dynptr id"); 12899 return -EFAULT; 12900 } 12901 regs[BPF_REG_0].dynptr_id = meta->initialized_dynptr.id; 12902 12903 /* we don't need to set BPF_REG_0's ref obj id 12904 * because packet slices are not refcounted (see 12905 * dynptr_type_refcounted) 12906 */ 12907 } else { 12908 return 0; 12909 } 12910 12911 return 1; 12912 } 12913 12914 static int check_return_code(struct bpf_verifier_env *env, int regno, const char *reg_name); 12915 12916 static int check_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn, 12917 int *insn_idx_p) 12918 { 12919 bool sleepable, rcu_lock, rcu_unlock, preempt_disable, preempt_enable; 12920 u32 i, nargs, ptr_type_id, release_ref_obj_id; 12921 struct bpf_reg_state *regs = cur_regs(env); 12922 const char *func_name, *ptr_type_name; 12923 const struct btf_type *t, *ptr_type; 12924 struct bpf_kfunc_call_arg_meta meta; 12925 struct bpf_insn_aux_data *insn_aux; 12926 int err, insn_idx = *insn_idx_p; 12927 const struct btf_param *args; 12928 struct btf *desc_btf; 12929 12930 /* skip for now, but return error when we find this in fixup_kfunc_call */ 12931 if (!insn->imm) 12932 return 0; 12933 12934 err = bpf_fetch_kfunc_arg_meta(env, insn->imm, insn->off, &meta); 12935 if (err == -EACCES && meta.func_name) 12936 verbose(env, "calling kernel function %s is not allowed\n", meta.func_name); 12937 if (err) 12938 return err; 12939 desc_btf = meta.btf; 12940 func_name = meta.func_name; 12941 insn_aux = &env->insn_aux_data[insn_idx]; 12942 12943 insn_aux->is_iter_next = bpf_is_iter_next_kfunc(&meta); 12944 12945 if (!insn->off && 12946 (insn->imm == special_kfunc_list[KF_bpf_res_spin_lock] || 12947 insn->imm == special_kfunc_list[KF_bpf_res_spin_lock_irqsave])) { 12948 struct bpf_verifier_state *branch; 12949 struct bpf_reg_state *regs; 12950 12951 branch = push_stack(env, env->insn_idx + 1, env->insn_idx, false); 12952 if (IS_ERR(branch)) { 12953 verbose(env, "failed to push state for failed lock acquisition\n"); 12954 return PTR_ERR(branch); 12955 } 12956 12957 regs = branch->frame[branch->curframe]->regs; 12958 12959 /* Clear r0-r5 registers in forked state */ 12960 for (i = 0; i < CALLER_SAVED_REGS; i++) 12961 bpf_mark_reg_not_init(env, ®s[caller_saved[i]]); 12962 12963 mark_reg_unknown(env, regs, BPF_REG_0); 12964 err = __mark_reg_s32_range(env, regs, BPF_REG_0, -MAX_ERRNO, -1); 12965 if (err) { 12966 verbose(env, "failed to mark s32 range for retval in forked state for lock\n"); 12967 return err; 12968 } 12969 __mark_btf_func_reg_size(env, regs, BPF_REG_0, sizeof(u32)); 12970 } else if (!insn->off && insn->imm == special_kfunc_list[KF___bpf_trap]) { 12971 verbose(env, "unexpected __bpf_trap() due to uninitialized variable?\n"); 12972 return -EFAULT; 12973 } 12974 12975 if (is_kfunc_destructive(&meta) && !capable(CAP_SYS_BOOT)) { 12976 verbose(env, "destructive kfunc calls require CAP_SYS_BOOT capability\n"); 12977 return -EACCES; 12978 } 12979 12980 sleepable = bpf_is_kfunc_sleepable(&meta); 12981 if (sleepable && !in_sleepable(env)) { 12982 verbose(env, "program must be sleepable to call sleepable kfunc %s\n", func_name); 12983 return -EACCES; 12984 } 12985 12986 /* Track non-sleepable context for kfuncs, same as for helpers. */ 12987 if (!in_sleepable_context(env)) 12988 insn_aux->non_sleepable = true; 12989 12990 /* Check the arguments */ 12991 err = check_kfunc_args(env, &meta, insn_idx); 12992 if (err < 0) 12993 return err; 12994 12995 if (is_bpf_rbtree_add_kfunc(meta.func_id)) { 12996 err = push_callback_call(env, insn, insn_idx, meta.subprogno, 12997 set_rbtree_add_callback_state); 12998 if (err) { 12999 verbose(env, "kfunc %s#%d failed callback verification\n", 13000 func_name, meta.func_id); 13001 return err; 13002 } 13003 } 13004 13005 if (meta.func_id == special_kfunc_list[KF_bpf_session_cookie]) { 13006 meta.r0_size = sizeof(u64); 13007 meta.r0_rdonly = false; 13008 } 13009 13010 if (is_bpf_wq_set_callback_kfunc(meta.func_id)) { 13011 err = push_callback_call(env, insn, insn_idx, meta.subprogno, 13012 set_timer_callback_state); 13013 if (err) { 13014 verbose(env, "kfunc %s#%d failed callback verification\n", 13015 func_name, meta.func_id); 13016 return err; 13017 } 13018 } 13019 13020 if (is_task_work_add_kfunc(meta.func_id)) { 13021 err = push_callback_call(env, insn, insn_idx, meta.subprogno, 13022 set_task_work_schedule_callback_state); 13023 if (err) { 13024 verbose(env, "kfunc %s#%d failed callback verification\n", 13025 func_name, meta.func_id); 13026 return err; 13027 } 13028 } 13029 13030 rcu_lock = is_kfunc_bpf_rcu_read_lock(&meta); 13031 rcu_unlock = is_kfunc_bpf_rcu_read_unlock(&meta); 13032 13033 preempt_disable = is_kfunc_bpf_preempt_disable(&meta); 13034 preempt_enable = is_kfunc_bpf_preempt_enable(&meta); 13035 13036 if (rcu_lock) { 13037 env->cur_state->active_rcu_locks++; 13038 } else if (rcu_unlock) { 13039 struct bpf_func_state *state; 13040 struct bpf_reg_state *reg; 13041 u32 clear_mask = (1 << STACK_SPILL) | (1 << STACK_ITER); 13042 13043 if (env->cur_state->active_rcu_locks == 0) { 13044 verbose(env, "unmatched rcu read unlock (kernel function %s)\n", func_name); 13045 return -EINVAL; 13046 } 13047 if (--env->cur_state->active_rcu_locks == 0) { 13048 bpf_for_each_reg_in_vstate_mask(env->cur_state, state, reg, clear_mask, ({ 13049 if (reg->type & MEM_RCU) { 13050 reg->type &= ~(MEM_RCU | PTR_MAYBE_NULL); 13051 reg->type |= PTR_UNTRUSTED; 13052 } 13053 })); 13054 } 13055 } else if (preempt_disable) { 13056 env->cur_state->active_preempt_locks++; 13057 } else if (preempt_enable) { 13058 if (env->cur_state->active_preempt_locks == 0) { 13059 verbose(env, "unmatched attempt to enable preemption (kernel function %s)\n", func_name); 13060 return -EINVAL; 13061 } 13062 env->cur_state->active_preempt_locks--; 13063 } 13064 13065 if (sleepable && !in_sleepable_context(env)) { 13066 verbose(env, "kernel func %s is sleepable within %s\n", 13067 func_name, non_sleepable_context_description(env)); 13068 return -EACCES; 13069 } 13070 13071 if (in_rbtree_lock_required_cb(env) && (rcu_lock || rcu_unlock)) { 13072 verbose(env, "Calling bpf_rcu_read_{lock,unlock} in unnecessary rbtree callback\n"); 13073 return -EACCES; 13074 } 13075 13076 if (is_kfunc_rcu_protected(&meta) && !in_rcu_cs(env)) { 13077 verbose(env, "kernel func %s requires RCU critical section protection\n", func_name); 13078 return -EACCES; 13079 } 13080 13081 /* In case of release function, we get register number of refcounted 13082 * PTR_TO_BTF_ID in bpf_kfunc_arg_meta, do the release now. 13083 */ 13084 if (meta.release_regno) { 13085 struct bpf_reg_state *reg = ®s[meta.release_regno]; 13086 13087 if (meta.initialized_dynptr.ref_obj_id) { 13088 err = unmark_stack_slots_dynptr(env, reg); 13089 } else { 13090 err = release_reference(env, reg->ref_obj_id); 13091 if (err) 13092 verbose(env, "kfunc %s#%d reference has not been acquired before\n", 13093 func_name, meta.func_id); 13094 } 13095 if (err) 13096 return err; 13097 } 13098 13099 if (is_bpf_list_push_kfunc(meta.func_id) || is_bpf_rbtree_add_kfunc(meta.func_id)) { 13100 release_ref_obj_id = regs[BPF_REG_2].ref_obj_id; 13101 insn_aux->insert_off = regs[BPF_REG_2].var_off.value; 13102 insn_aux->kptr_struct_meta = btf_find_struct_meta(meta.arg_btf, meta.arg_btf_id); 13103 err = ref_convert_owning_non_owning(env, release_ref_obj_id); 13104 if (err) { 13105 verbose(env, "kfunc %s#%d conversion of owning ref to non-owning failed\n", 13106 func_name, meta.func_id); 13107 return err; 13108 } 13109 13110 err = release_reference(env, release_ref_obj_id); 13111 if (err) { 13112 verbose(env, "kfunc %s#%d reference has not been acquired before\n", 13113 func_name, meta.func_id); 13114 return err; 13115 } 13116 } 13117 13118 if (meta.func_id == special_kfunc_list[KF_bpf_throw]) { 13119 if (!bpf_jit_supports_exceptions()) { 13120 verbose(env, "JIT does not support calling kfunc %s#%d\n", 13121 func_name, meta.func_id); 13122 return -ENOTSUPP; 13123 } 13124 env->seen_exception = true; 13125 13126 /* In the case of the default callback, the cookie value passed 13127 * to bpf_throw becomes the return value of the program. 13128 */ 13129 if (!env->exception_callback_subprog) { 13130 err = check_return_code(env, BPF_REG_1, "R1"); 13131 if (err < 0) 13132 return err; 13133 } 13134 } 13135 13136 for (i = 0; i < CALLER_SAVED_REGS; i++) { 13137 u32 regno = caller_saved[i]; 13138 13139 bpf_mark_reg_not_init(env, ®s[regno]); 13140 regs[regno].subreg_def = DEF_NOT_SUBREG; 13141 } 13142 invalidate_outgoing_stack_args(env, cur_func(env)); 13143 13144 /* Check return type */ 13145 t = btf_type_skip_modifiers(desc_btf, meta.func_proto->type, NULL); 13146 13147 if (is_kfunc_acquire(&meta) && !btf_type_is_struct_ptr(meta.btf, t)) { 13148 if (meta.btf != btf_vmlinux || 13149 (!is_bpf_obj_new_kfunc(meta.func_id) && 13150 !is_bpf_percpu_obj_new_kfunc(meta.func_id) && 13151 !is_bpf_refcount_acquire_kfunc(meta.func_id))) { 13152 verbose(env, "acquire kernel function does not return PTR_TO_BTF_ID\n"); 13153 return -EINVAL; 13154 } 13155 } 13156 13157 if (btf_type_is_scalar(t)) { 13158 mark_reg_unknown(env, regs, BPF_REG_0); 13159 if (meta.btf == btf_vmlinux && (meta.func_id == special_kfunc_list[KF_bpf_res_spin_lock] || 13160 meta.func_id == special_kfunc_list[KF_bpf_res_spin_lock_irqsave])) 13161 __mark_reg_const_zero(env, ®s[BPF_REG_0]); 13162 mark_btf_func_reg_size(env, BPF_REG_0, t->size); 13163 } else if (btf_type_is_ptr(t)) { 13164 ptr_type = btf_type_skip_modifiers(desc_btf, t->type, &ptr_type_id); 13165 err = check_special_kfunc(env, &meta, regs, insn_aux, ptr_type, desc_btf); 13166 if (err) { 13167 if (err < 0) 13168 return err; 13169 } else if (btf_type_is_void(ptr_type)) { 13170 /* kfunc returning 'void *' is equivalent to returning scalar */ 13171 mark_reg_unknown(env, regs, BPF_REG_0); 13172 } else if (!__btf_type_is_struct(ptr_type)) { 13173 if (!meta.r0_size) { 13174 __u32 sz; 13175 13176 if (!IS_ERR(btf_resolve_size(desc_btf, ptr_type, &sz))) { 13177 meta.r0_size = sz; 13178 meta.r0_rdonly = true; 13179 } 13180 } 13181 if (!meta.r0_size) { 13182 ptr_type_name = btf_name_by_offset(desc_btf, 13183 ptr_type->name_off); 13184 verbose(env, 13185 "kernel function %s returns pointer type %s %s is not supported\n", 13186 func_name, 13187 btf_type_str(ptr_type), 13188 ptr_type_name); 13189 return -EINVAL; 13190 } 13191 13192 mark_reg_known_zero(env, regs, BPF_REG_0); 13193 regs[BPF_REG_0].type = PTR_TO_MEM; 13194 regs[BPF_REG_0].mem_size = meta.r0_size; 13195 13196 if (meta.r0_rdonly) 13197 regs[BPF_REG_0].type |= MEM_RDONLY; 13198 13199 /* Ensures we don't access the memory after a release_reference() */ 13200 if (meta.ref_obj_id) 13201 regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id; 13202 13203 if (is_kfunc_rcu_protected(&meta)) 13204 regs[BPF_REG_0].type |= MEM_RCU; 13205 } else { 13206 enum bpf_reg_type type = PTR_TO_BTF_ID; 13207 13208 if (meta.func_id == special_kfunc_list[KF_bpf_get_kmem_cache]) 13209 type |= PTR_UNTRUSTED; 13210 else if (is_kfunc_rcu_protected(&meta) || 13211 (bpf_is_iter_next_kfunc(&meta) && 13212 (get_iter_from_state(env->cur_state, &meta) 13213 ->type & MEM_RCU))) { 13214 /* 13215 * If the iterator's constructor (the _new 13216 * function e.g., bpf_iter_task_new) has been 13217 * annotated with BPF kfunc flag 13218 * KF_RCU_PROTECTED and was called within a RCU 13219 * read-side critical section, also propagate 13220 * the MEM_RCU flag to the pointer returned from 13221 * the iterator's next function (e.g., 13222 * bpf_iter_task_next). 13223 */ 13224 type |= MEM_RCU; 13225 } else { 13226 /* 13227 * Any PTR_TO_BTF_ID that is returned from a BPF 13228 * kfunc should by default be treated as 13229 * implicitly trusted. 13230 */ 13231 type |= PTR_TRUSTED; 13232 } 13233 13234 mark_reg_known_zero(env, regs, BPF_REG_0); 13235 regs[BPF_REG_0].btf = desc_btf; 13236 regs[BPF_REG_0].type = type; 13237 regs[BPF_REG_0].btf_id = ptr_type_id; 13238 } 13239 13240 if (is_kfunc_ret_null(&meta)) { 13241 regs[BPF_REG_0].type |= PTR_MAYBE_NULL; 13242 /* For mark_ptr_or_null_reg, see 93c230e3f5bd6 */ 13243 regs[BPF_REG_0].id = ++env->id_gen; 13244 } 13245 mark_btf_func_reg_size(env, BPF_REG_0, sizeof(void *)); 13246 if (is_kfunc_acquire(&meta)) { 13247 int id = acquire_reference(env, insn_idx); 13248 13249 if (id < 0) 13250 return id; 13251 if (is_kfunc_ret_null(&meta)) 13252 regs[BPF_REG_0].id = id; 13253 regs[BPF_REG_0].ref_obj_id = id; 13254 } else if (is_rbtree_node_type(ptr_type) || is_list_node_type(ptr_type)) { 13255 ref_set_non_owning(env, ®s[BPF_REG_0]); 13256 } 13257 13258 if (reg_may_point_to_spin_lock(®s[BPF_REG_0]) && !regs[BPF_REG_0].id) 13259 regs[BPF_REG_0].id = ++env->id_gen; 13260 } else if (btf_type_is_void(t)) { 13261 if (meta.btf == btf_vmlinux) { 13262 if (is_bpf_obj_drop_kfunc(meta.func_id) || 13263 is_bpf_percpu_obj_drop_kfunc(meta.func_id)) { 13264 insn_aux->kptr_struct_meta = 13265 btf_find_struct_meta(meta.arg_btf, 13266 meta.arg_btf_id); 13267 } 13268 } 13269 } 13270 13271 if (bpf_is_kfunc_pkt_changing(&meta)) 13272 clear_all_pkt_pointers(env); 13273 13274 nargs = btf_type_vlen(meta.func_proto); 13275 if (nargs > MAX_BPF_FUNC_REG_ARGS) { 13276 struct bpf_func_state *caller = cur_func(env); 13277 struct bpf_subprog_info *caller_info = &env->subprog_info[caller->subprogno]; 13278 u16 out_stack_arg_cnt = nargs - MAX_BPF_FUNC_REG_ARGS; 13279 u16 stack_arg_cnt = bpf_in_stack_arg_cnt(caller_info) + out_stack_arg_cnt; 13280 13281 if (stack_arg_cnt > caller_info->stack_arg_cnt) 13282 caller_info->stack_arg_cnt = stack_arg_cnt; 13283 } 13284 13285 args = (const struct btf_param *)(meta.func_proto + 1); 13286 for (i = 0; i < min_t(int, nargs, MAX_BPF_FUNC_REG_ARGS); i++) { 13287 u32 regno = i + 1; 13288 13289 t = btf_type_skip_modifiers(desc_btf, args[i].type, NULL); 13290 if (btf_type_is_ptr(t)) 13291 mark_btf_func_reg_size(env, regno, sizeof(void *)); 13292 else 13293 /* scalar. ensured by check_kfunc_args() */ 13294 mark_btf_func_reg_size(env, regno, t->size); 13295 } 13296 13297 if (bpf_is_iter_next_kfunc(&meta)) { 13298 err = process_iter_next_call(env, insn_idx, &meta); 13299 if (err) 13300 return err; 13301 } 13302 13303 if (meta.func_id == special_kfunc_list[KF_bpf_session_cookie]) 13304 env->prog->call_session_cookie = true; 13305 13306 if (bpf_is_throw_kfunc(insn)) 13307 return process_bpf_exit_full(env, NULL, true); 13308 13309 return 0; 13310 } 13311 13312 static bool check_reg_sane_offset_scalar(struct bpf_verifier_env *env, 13313 const struct bpf_reg_state *reg, 13314 enum bpf_reg_type type) 13315 { 13316 bool known = tnum_is_const(reg->var_off); 13317 s64 val = reg->var_off.value; 13318 s64 smin = reg_smin(reg); 13319 13320 if (known && (val >= BPF_MAX_VAR_OFF || val <= -BPF_MAX_VAR_OFF)) { 13321 verbose(env, "math between %s pointer and %lld is not allowed\n", 13322 reg_type_str(env, type), val); 13323 return false; 13324 } 13325 13326 if (smin == S64_MIN) { 13327 verbose(env, "math between %s pointer and register with unbounded min value is not allowed\n", 13328 reg_type_str(env, type)); 13329 return false; 13330 } 13331 13332 if (smin >= BPF_MAX_VAR_OFF || smin <= -BPF_MAX_VAR_OFF) { 13333 verbose(env, "value %lld makes %s pointer be out of bounds\n", 13334 smin, reg_type_str(env, type)); 13335 return false; 13336 } 13337 13338 return true; 13339 } 13340 13341 static bool check_reg_sane_offset_ptr(struct bpf_verifier_env *env, 13342 const struct bpf_reg_state *reg, 13343 enum bpf_reg_type type) 13344 { 13345 bool known = tnum_is_const(reg->var_off); 13346 s64 val = reg->var_off.value; 13347 s64 smin = reg_smin(reg); 13348 13349 if (known && (val >= BPF_MAX_VAR_OFF || val <= -BPF_MAX_VAR_OFF)) { 13350 verbose(env, "%s pointer offset %lld is not allowed\n", 13351 reg_type_str(env, type), val); 13352 return false; 13353 } 13354 13355 if (smin >= BPF_MAX_VAR_OFF || smin <= -BPF_MAX_VAR_OFF) { 13356 verbose(env, "%s pointer offset %lld is not allowed\n", 13357 reg_type_str(env, type), smin); 13358 return false; 13359 } 13360 13361 return true; 13362 } 13363 13364 enum { 13365 REASON_BOUNDS = -1, 13366 REASON_TYPE = -2, 13367 REASON_PATHS = -3, 13368 REASON_LIMIT = -4, 13369 REASON_STACK = -5, 13370 }; 13371 13372 static int retrieve_ptr_limit(const struct bpf_reg_state *ptr_reg, 13373 u32 *alu_limit, bool mask_to_left) 13374 { 13375 u32 max = 0, ptr_limit = 0; 13376 13377 switch (ptr_reg->type) { 13378 case PTR_TO_STACK: 13379 /* Offset 0 is out-of-bounds, but acceptable start for the 13380 * left direction, see BPF_REG_FP. Also, unknown scalar 13381 * offset where we would need to deal with min/max bounds is 13382 * currently prohibited for unprivileged. 13383 */ 13384 max = MAX_BPF_STACK + mask_to_left; 13385 ptr_limit = -ptr_reg->var_off.value; 13386 break; 13387 case PTR_TO_MAP_VALUE: 13388 max = ptr_reg->map_ptr->value_size; 13389 ptr_limit = mask_to_left ? reg_smin(ptr_reg) : reg_umax(ptr_reg); 13390 break; 13391 default: 13392 return REASON_TYPE; 13393 } 13394 13395 if (ptr_limit >= max) 13396 return REASON_LIMIT; 13397 *alu_limit = ptr_limit; 13398 return 0; 13399 } 13400 13401 static bool can_skip_alu_sanitation(const struct bpf_verifier_env *env, 13402 const struct bpf_insn *insn) 13403 { 13404 return env->bypass_spec_v1 || 13405 BPF_SRC(insn->code) == BPF_K || 13406 cur_aux(env)->nospec; 13407 } 13408 13409 static int update_alu_sanitation_state(struct bpf_insn_aux_data *aux, 13410 u32 alu_state, u32 alu_limit) 13411 { 13412 /* If we arrived here from different branches with different 13413 * state or limits to sanitize, then this won't work. 13414 */ 13415 if (aux->alu_state && 13416 (aux->alu_state != alu_state || 13417 aux->alu_limit != alu_limit)) 13418 return REASON_PATHS; 13419 13420 /* Corresponding fixup done in do_misc_fixups(). */ 13421 aux->alu_state = alu_state; 13422 aux->alu_limit = alu_limit; 13423 return 0; 13424 } 13425 13426 static int sanitize_val_alu(struct bpf_verifier_env *env, 13427 struct bpf_insn *insn) 13428 { 13429 struct bpf_insn_aux_data *aux = cur_aux(env); 13430 13431 if (can_skip_alu_sanitation(env, insn)) 13432 return 0; 13433 13434 return update_alu_sanitation_state(aux, BPF_ALU_NON_POINTER, 0); 13435 } 13436 13437 static bool sanitize_needed(u8 opcode) 13438 { 13439 return opcode == BPF_ADD || opcode == BPF_SUB; 13440 } 13441 13442 struct bpf_sanitize_info { 13443 struct bpf_insn_aux_data aux; 13444 bool mask_to_left; 13445 }; 13446 13447 static int sanitize_speculative_path(struct bpf_verifier_env *env, 13448 const struct bpf_insn *insn, 13449 u32 next_idx, u32 curr_idx) 13450 { 13451 struct bpf_verifier_state *branch; 13452 struct bpf_reg_state *regs; 13453 13454 branch = push_stack(env, next_idx, curr_idx, true); 13455 if (!IS_ERR(branch) && insn) { 13456 regs = branch->frame[branch->curframe]->regs; 13457 if (BPF_SRC(insn->code) == BPF_K) { 13458 mark_reg_unknown(env, regs, insn->dst_reg); 13459 } else if (BPF_SRC(insn->code) == BPF_X) { 13460 mark_reg_unknown(env, regs, insn->dst_reg); 13461 mark_reg_unknown(env, regs, insn->src_reg); 13462 } 13463 } 13464 return PTR_ERR_OR_ZERO(branch); 13465 } 13466 13467 static int sanitize_ptr_alu(struct bpf_verifier_env *env, 13468 struct bpf_insn *insn, 13469 const struct bpf_reg_state *ptr_reg, 13470 const struct bpf_reg_state *off_reg, 13471 struct bpf_reg_state *dst_reg, 13472 struct bpf_sanitize_info *info, 13473 const bool commit_window) 13474 { 13475 struct bpf_insn_aux_data *aux = commit_window ? cur_aux(env) : &info->aux; 13476 struct bpf_verifier_state *vstate = env->cur_state; 13477 bool off_is_imm = tnum_is_const(off_reg->var_off); 13478 bool off_is_neg = reg_smin(off_reg) < 0; 13479 bool ptr_is_dst_reg = ptr_reg == dst_reg; 13480 u8 opcode = BPF_OP(insn->code); 13481 u32 alu_state, alu_limit; 13482 struct bpf_reg_state tmp; 13483 int err; 13484 13485 if (can_skip_alu_sanitation(env, insn)) 13486 return 0; 13487 13488 /* We already marked aux for masking from non-speculative 13489 * paths, thus we got here in the first place. We only care 13490 * to explore bad access from here. 13491 */ 13492 if (vstate->speculative) 13493 goto do_sim; 13494 13495 if (!commit_window) { 13496 if (!tnum_is_const(off_reg->var_off) && 13497 (reg_smin(off_reg) < 0) != (reg_smax(off_reg) < 0)) 13498 return REASON_BOUNDS; 13499 13500 info->mask_to_left = (opcode == BPF_ADD && off_is_neg) || 13501 (opcode == BPF_SUB && !off_is_neg); 13502 } 13503 13504 err = retrieve_ptr_limit(ptr_reg, &alu_limit, info->mask_to_left); 13505 if (err < 0) 13506 return err; 13507 13508 if (commit_window) { 13509 /* In commit phase we narrow the masking window based on 13510 * the observed pointer move after the simulated operation. 13511 */ 13512 alu_state = info->aux.alu_state; 13513 alu_limit = abs(info->aux.alu_limit - alu_limit); 13514 } else { 13515 alu_state = off_is_neg ? BPF_ALU_NEG_VALUE : 0; 13516 alu_state |= off_is_imm ? BPF_ALU_IMMEDIATE : 0; 13517 alu_state |= ptr_is_dst_reg ? 13518 BPF_ALU_SANITIZE_SRC : BPF_ALU_SANITIZE_DST; 13519 13520 /* Limit pruning on unknown scalars to enable deep search for 13521 * potential masking differences from other program paths. 13522 */ 13523 if (!off_is_imm) 13524 env->explore_alu_limits = true; 13525 } 13526 13527 err = update_alu_sanitation_state(aux, alu_state, alu_limit); 13528 if (err < 0) 13529 return err; 13530 do_sim: 13531 /* If we're in commit phase, we're done here given we already 13532 * pushed the truncated dst_reg into the speculative verification 13533 * stack. 13534 * 13535 * Also, when register is a known constant, we rewrite register-based 13536 * operation to immediate-based, and thus do not need masking (and as 13537 * a consequence, do not need to simulate the zero-truncation either). 13538 */ 13539 if (commit_window || off_is_imm) 13540 return 0; 13541 13542 /* Simulate and find potential out-of-bounds access under 13543 * speculative execution from truncation as a result of 13544 * masking when off was not within expected range. If off 13545 * sits in dst, then we temporarily need to move ptr there 13546 * to simulate dst (== 0) +/-= ptr. Needed, for example, 13547 * for cases where we use K-based arithmetic in one direction 13548 * and truncated reg-based in the other in order to explore 13549 * bad access. 13550 */ 13551 if (!ptr_is_dst_reg) { 13552 tmp = *dst_reg; 13553 *dst_reg = *ptr_reg; 13554 } 13555 err = sanitize_speculative_path(env, NULL, env->insn_idx + 1, env->insn_idx); 13556 if (err < 0) 13557 return REASON_STACK; 13558 if (!ptr_is_dst_reg) 13559 *dst_reg = tmp; 13560 return 0; 13561 } 13562 13563 static void sanitize_mark_insn_seen(struct bpf_verifier_env *env) 13564 { 13565 struct bpf_verifier_state *vstate = env->cur_state; 13566 13567 /* If we simulate paths under speculation, we don't update the 13568 * insn as 'seen' such that when we verify unreachable paths in 13569 * the non-speculative domain, sanitize_dead_code() can still 13570 * rewrite/sanitize them. 13571 */ 13572 if (!vstate->speculative) 13573 env->insn_aux_data[env->insn_idx].seen = env->pass_cnt; 13574 } 13575 13576 static int sanitize_err(struct bpf_verifier_env *env, 13577 const struct bpf_insn *insn, int reason, 13578 const struct bpf_reg_state *off_reg, 13579 const struct bpf_reg_state *dst_reg) 13580 { 13581 static const char *err = "pointer arithmetic with it prohibited for !root"; 13582 const char *op = BPF_OP(insn->code) == BPF_ADD ? "add" : "sub"; 13583 u32 dst = insn->dst_reg, src = insn->src_reg; 13584 13585 switch (reason) { 13586 case REASON_BOUNDS: 13587 verbose(env, "R%d has unknown scalar with mixed signed bounds, %s\n", 13588 off_reg == dst_reg ? dst : src, err); 13589 break; 13590 case REASON_TYPE: 13591 verbose(env, "R%d has pointer with unsupported alu operation, %s\n", 13592 off_reg == dst_reg ? src : dst, err); 13593 break; 13594 case REASON_PATHS: 13595 verbose(env, "R%d tried to %s from different maps, paths or scalars, %s\n", 13596 dst, op, err); 13597 break; 13598 case REASON_LIMIT: 13599 verbose(env, "R%d tried to %s beyond pointer bounds, %s\n", 13600 dst, op, err); 13601 break; 13602 case REASON_STACK: 13603 verbose(env, "R%d could not be pushed for speculative verification, %s\n", 13604 dst, err); 13605 return -ENOMEM; 13606 default: 13607 verifier_bug(env, "unknown reason (%d)", reason); 13608 break; 13609 } 13610 13611 return -EACCES; 13612 } 13613 13614 /* check that stack access falls within stack limits and that 'reg' doesn't 13615 * have a variable offset. 13616 * 13617 * Variable offset is prohibited for unprivileged mode for simplicity since it 13618 * requires corresponding support in Spectre masking for stack ALU. See also 13619 * retrieve_ptr_limit(). 13620 */ 13621 static int check_stack_access_for_ptr_arithmetic( 13622 struct bpf_verifier_env *env, 13623 int regno, 13624 const struct bpf_reg_state *reg, 13625 int off) 13626 { 13627 if (!tnum_is_const(reg->var_off)) { 13628 char tn_buf[48]; 13629 13630 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 13631 verbose(env, "R%d variable stack access prohibited for !root, var_off=%s off=%d\n", 13632 regno, tn_buf, off); 13633 return -EACCES; 13634 } 13635 13636 if (off >= 0 || off < -MAX_BPF_STACK) { 13637 verbose(env, "R%d stack pointer arithmetic goes out of range, " 13638 "prohibited for !root; off=%d\n", regno, off); 13639 return -EACCES; 13640 } 13641 13642 return 0; 13643 } 13644 13645 static int sanitize_check_bounds(struct bpf_verifier_env *env, 13646 const struct bpf_insn *insn, 13647 struct bpf_reg_state *dst_reg) 13648 { 13649 u32 dst = insn->dst_reg; 13650 13651 /* For unprivileged we require that resulting offset must be in bounds 13652 * in order to be able to sanitize access later on. 13653 */ 13654 if (env->bypass_spec_v1) 13655 return 0; 13656 13657 switch (dst_reg->type) { 13658 case PTR_TO_STACK: 13659 if (check_stack_access_for_ptr_arithmetic(env, dst, dst_reg, 13660 dst_reg->var_off.value)) 13661 return -EACCES; 13662 break; 13663 case PTR_TO_MAP_VALUE: 13664 if (check_map_access(env, dst_reg, argno_from_reg(dst), 0, 1, false, ACCESS_HELPER)) { 13665 verbose(env, "R%d pointer arithmetic of map value goes out of range, " 13666 "prohibited for !root\n", dst); 13667 return -EACCES; 13668 } 13669 break; 13670 default: 13671 return -EOPNOTSUPP; 13672 } 13673 13674 return 0; 13675 } 13676 13677 /* Handles arithmetic on a pointer and a scalar: computes new min/max and var_off. 13678 * Caller should also handle BPF_MOV case separately. 13679 * If we return -EACCES, caller may want to try again treating pointer as a 13680 * scalar. So we only emit a diagnostic if !env->allow_ptr_leaks. 13681 */ 13682 static int adjust_ptr_min_max_vals(struct bpf_verifier_env *env, 13683 struct bpf_insn *insn, 13684 const struct bpf_reg_state *ptr_reg, 13685 const struct bpf_reg_state *off_reg) 13686 { 13687 struct bpf_verifier_state *vstate = env->cur_state; 13688 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 13689 struct bpf_reg_state *regs = state->regs, *dst_reg; 13690 bool known = tnum_is_const(off_reg->var_off); 13691 s64 smin_val = reg_smin(off_reg), smax_val = reg_smax(off_reg); 13692 u64 umin_val = reg_umin(off_reg), umax_val = reg_umax(off_reg); 13693 struct bpf_sanitize_info info = {}; 13694 u8 opcode = BPF_OP(insn->code); 13695 u32 dst = insn->dst_reg; 13696 int ret, bounds_ret; 13697 13698 dst_reg = ®s[dst]; 13699 13700 if ((known && (smin_val != smax_val || umin_val != umax_val)) || 13701 smin_val > smax_val || umin_val > umax_val) { 13702 /* Taint dst register if offset had invalid bounds derived from 13703 * e.g. dead branches. 13704 */ 13705 __mark_reg_unknown(env, dst_reg); 13706 return 0; 13707 } 13708 13709 if (BPF_CLASS(insn->code) != BPF_ALU64) { 13710 /* 32-bit ALU ops on pointers produce (meaningless) scalars */ 13711 if (opcode == BPF_SUB && env->allow_ptr_leaks) { 13712 __mark_reg_unknown(env, dst_reg); 13713 return 0; 13714 } 13715 13716 verbose(env, 13717 "R%d 32-bit pointer arithmetic prohibited\n", 13718 dst); 13719 return -EACCES; 13720 } 13721 13722 if (ptr_reg->type & PTR_MAYBE_NULL) { 13723 verbose(env, "R%d pointer arithmetic on %s prohibited, null-check it first\n", 13724 dst, reg_type_str(env, ptr_reg->type)); 13725 return -EACCES; 13726 } 13727 13728 /* 13729 * Accesses to untrusted PTR_TO_MEM are done through probe 13730 * instructions, hence no need to track offsets. 13731 */ 13732 if (base_type(ptr_reg->type) == PTR_TO_MEM && (ptr_reg->type & PTR_UNTRUSTED)) 13733 return 0; 13734 13735 switch (base_type(ptr_reg->type)) { 13736 case PTR_TO_CTX: 13737 case PTR_TO_MAP_VALUE: 13738 case PTR_TO_MAP_KEY: 13739 case PTR_TO_STACK: 13740 case PTR_TO_PACKET_META: 13741 case PTR_TO_PACKET: 13742 case PTR_TO_TP_BUFFER: 13743 case PTR_TO_BTF_ID: 13744 case PTR_TO_MEM: 13745 case PTR_TO_BUF: 13746 case PTR_TO_FUNC: 13747 case CONST_PTR_TO_DYNPTR: 13748 break; 13749 case PTR_TO_FLOW_KEYS: 13750 if (known) 13751 break; 13752 fallthrough; 13753 case CONST_PTR_TO_MAP: 13754 /* smin_val represents the known value */ 13755 if (known && smin_val == 0 && opcode == BPF_ADD) 13756 break; 13757 fallthrough; 13758 default: 13759 verbose(env, "R%d pointer arithmetic on %s prohibited\n", 13760 dst, reg_type_str(env, ptr_reg->type)); 13761 return -EACCES; 13762 } 13763 13764 /* In case of 'scalar += pointer', dst_reg inherits pointer type and id. 13765 * The id may be overwritten later if we create a new variable offset. 13766 */ 13767 dst_reg->type = ptr_reg->type; 13768 dst_reg->id = ptr_reg->id; 13769 13770 if (!check_reg_sane_offset_scalar(env, off_reg, ptr_reg->type) || 13771 !check_reg_sane_offset_ptr(env, ptr_reg, ptr_reg->type)) 13772 return -EINVAL; 13773 13774 /* pointer types do not carry 32-bit bounds at the moment. */ 13775 __mark_reg32_unbounded(dst_reg); 13776 13777 if (sanitize_needed(opcode)) { 13778 ret = sanitize_ptr_alu(env, insn, ptr_reg, off_reg, dst_reg, 13779 &info, false); 13780 if (ret < 0) 13781 return sanitize_err(env, insn, ret, off_reg, dst_reg); 13782 } 13783 13784 switch (opcode) { 13785 case BPF_ADD: 13786 /* 13787 * dst_reg gets the pointer type and since some positive 13788 * integer value was added to the pointer, give it a new 'id' 13789 * if it's a PTR_TO_PACKET. 13790 * this creates a new 'base' pointer, off_reg (variable) gets 13791 * added into the variable offset, and we copy the fixed offset 13792 * from ptr_reg. 13793 */ 13794 dst_reg->r64 = cnum64_add(ptr_reg->r64, off_reg->r64); 13795 dst_reg->var_off = tnum_add(ptr_reg->var_off, off_reg->var_off); 13796 dst_reg->raw = ptr_reg->raw; 13797 if (reg_is_pkt_pointer(ptr_reg)) { 13798 if (!known) 13799 dst_reg->id = ++env->id_gen; 13800 /* 13801 * Clear range for unknown addends since we can't know 13802 * where the pkt pointer ended up. Also clear AT_PKT_END / 13803 * BEYOND_PKT_END from prior comparison as any pointer 13804 * arithmetic invalidates them. 13805 */ 13806 if (!known || dst_reg->range < 0) 13807 memset(&dst_reg->raw, 0, sizeof(dst_reg->raw)); 13808 } 13809 break; 13810 case BPF_SUB: 13811 if (dst_reg == off_reg) { 13812 /* scalar -= pointer. Creates an unknown scalar */ 13813 verbose(env, "R%d tried to subtract pointer from scalar\n", 13814 dst); 13815 return -EACCES; 13816 } 13817 /* We don't allow subtraction from FP, because (according to 13818 * test_verifier.c test "invalid fp arithmetic", JITs might not 13819 * be able to deal with it. 13820 */ 13821 if (ptr_reg->type == PTR_TO_STACK) { 13822 verbose(env, "R%d subtraction from stack pointer prohibited\n", 13823 dst); 13824 return -EACCES; 13825 } 13826 dst_reg->r64 = cnum64_add(ptr_reg->r64, cnum64_negate(off_reg->r64)); 13827 dst_reg->var_off = tnum_sub(ptr_reg->var_off, off_reg->var_off); 13828 dst_reg->raw = ptr_reg->raw; 13829 if (reg_is_pkt_pointer(ptr_reg)) { 13830 if (!known) 13831 dst_reg->id = ++env->id_gen; 13832 /* 13833 * Clear range if the subtrahend may be negative since 13834 * pkt pointer could move past its bounds. A positive 13835 * subtrahend moves it backwards keeping positive range 13836 * intact. Also clear AT_PKT_END / BEYOND_PKT_END from 13837 * prior comparison as arithmetic invalidates them. 13838 */ 13839 if ((!known && smin_val < 0) || dst_reg->range < 0) 13840 memset(&dst_reg->raw, 0, sizeof(dst_reg->raw)); 13841 } 13842 break; 13843 case BPF_AND: 13844 case BPF_OR: 13845 case BPF_XOR: 13846 /* bitwise ops on pointers are troublesome, prohibit. */ 13847 verbose(env, "R%d bitwise operator %s on pointer prohibited\n", 13848 dst, bpf_alu_string[opcode >> 4]); 13849 return -EACCES; 13850 default: 13851 /* other operators (e.g. MUL,LSH) produce non-pointer results */ 13852 verbose(env, "R%d pointer arithmetic with %s operator prohibited\n", 13853 dst, bpf_alu_string[opcode >> 4]); 13854 return -EACCES; 13855 } 13856 13857 if (!check_reg_sane_offset_ptr(env, dst_reg, ptr_reg->type)) 13858 return -EINVAL; 13859 reg_bounds_sync(dst_reg); 13860 bounds_ret = sanitize_check_bounds(env, insn, dst_reg); 13861 if (bounds_ret == -EACCES) 13862 return bounds_ret; 13863 if (sanitize_needed(opcode)) { 13864 ret = sanitize_ptr_alu(env, insn, dst_reg, off_reg, dst_reg, 13865 &info, true); 13866 if (verifier_bug_if(!can_skip_alu_sanitation(env, insn) 13867 && !env->cur_state->speculative 13868 && bounds_ret 13869 && !ret, 13870 env, "Pointer type unsupported by sanitize_check_bounds() not rejected by retrieve_ptr_limit() as required")) { 13871 return -EFAULT; 13872 } 13873 if (ret < 0) 13874 return sanitize_err(env, insn, ret, off_reg, dst_reg); 13875 } 13876 13877 return 0; 13878 } 13879 13880 static void scalar32_min_max_add(struct bpf_reg_state *dst_reg, 13881 struct bpf_reg_state *src_reg) 13882 { 13883 dst_reg->r32 = cnum32_add(dst_reg->r32, src_reg->r32); 13884 } 13885 13886 static void scalar_min_max_add(struct bpf_reg_state *dst_reg, 13887 struct bpf_reg_state *src_reg) 13888 { 13889 dst_reg->r64 = cnum64_add(dst_reg->r64, src_reg->r64); 13890 } 13891 13892 static void scalar32_min_max_sub(struct bpf_reg_state *dst_reg, 13893 struct bpf_reg_state *src_reg) 13894 { 13895 dst_reg->r32 = cnum32_add(dst_reg->r32, cnum32_negate(src_reg->r32)); 13896 } 13897 13898 static void scalar_min_max_sub(struct bpf_reg_state *dst_reg, 13899 struct bpf_reg_state *src_reg) 13900 { 13901 dst_reg->r64 = cnum64_add(dst_reg->r64, cnum64_negate(src_reg->r64)); 13902 } 13903 13904 static void scalar32_min_max_mul(struct bpf_reg_state *dst_reg, 13905 struct bpf_reg_state *src_reg) 13906 { 13907 s32 smin = reg_s32_min(dst_reg); 13908 s32 smax = reg_s32_max(dst_reg); 13909 u32 umin = reg_u32_min(dst_reg); 13910 u32 umax = reg_u32_max(dst_reg); 13911 s32 tmp_prod[4]; 13912 13913 if (check_mul_overflow(umax, reg_u32_max(src_reg), &umax) || 13914 check_mul_overflow(umin, reg_u32_min(src_reg), &umin)) { 13915 /* Overflow possible, we know nothing */ 13916 umin = 0; 13917 umax = U32_MAX; 13918 } 13919 if (check_mul_overflow(smin, reg_s32_min(src_reg), &tmp_prod[0]) || 13920 check_mul_overflow(smin, reg_s32_max(src_reg), &tmp_prod[1]) || 13921 check_mul_overflow(smax, reg_s32_min(src_reg), &tmp_prod[2]) || 13922 check_mul_overflow(smax, reg_s32_max(src_reg), &tmp_prod[3])) { 13923 /* Overflow possible, we know nothing */ 13924 smin = S32_MIN; 13925 smax = S32_MAX; 13926 } else { 13927 smin = min_array(tmp_prod, 4); 13928 smax = max_array(tmp_prod, 4); 13929 } 13930 13931 dst_reg->r32 = cnum32_intersect(cnum32_from_urange(umin, umax), 13932 cnum32_from_srange(smin, smax)); 13933 } 13934 13935 static void scalar_min_max_mul(struct bpf_reg_state *dst_reg, 13936 struct bpf_reg_state *src_reg) 13937 { 13938 s64 smin = reg_smin(dst_reg); 13939 s64 smax = reg_smax(dst_reg); 13940 u64 umin = reg_umin(dst_reg); 13941 u64 umax = reg_umax(dst_reg); 13942 s64 tmp_prod[4]; 13943 13944 if (check_mul_overflow(umax, reg_umax(src_reg), &umax) || 13945 check_mul_overflow(umin, reg_umin(src_reg), &umin)) { 13946 /* Overflow possible, we know nothing */ 13947 umin = 0; 13948 umax = U64_MAX; 13949 } 13950 if (check_mul_overflow(smin, reg_smin(src_reg), &tmp_prod[0]) || 13951 check_mul_overflow(smin, reg_smax(src_reg), &tmp_prod[1]) || 13952 check_mul_overflow(smax, reg_smin(src_reg), &tmp_prod[2]) || 13953 check_mul_overflow(smax, reg_smax(src_reg), &tmp_prod[3])) { 13954 /* Overflow possible, we know nothing */ 13955 smin = S64_MIN; 13956 smax = S64_MAX; 13957 } else { 13958 smin = min_array(tmp_prod, 4); 13959 smax = max_array(tmp_prod, 4); 13960 } 13961 13962 dst_reg->r64 = cnum64_intersect(cnum64_from_urange(umin, umax), 13963 cnum64_from_srange(smin, smax)); 13964 } 13965 13966 static void scalar32_min_max_udiv(struct bpf_reg_state *dst_reg, 13967 struct bpf_reg_state *src_reg) 13968 { 13969 u32 src_val = reg_u32_min(src_reg); /* non-zero, const divisor */ 13970 13971 reg_set_urange32(dst_reg, reg_u32_min(dst_reg) / src_val, 13972 reg_u32_max(dst_reg) / src_val); 13973 13974 /* Reset other ranges/tnum to unbounded/unknown. */ 13975 reset_reg64_and_tnum(dst_reg); 13976 } 13977 13978 static void scalar_min_max_udiv(struct bpf_reg_state *dst_reg, 13979 struct bpf_reg_state *src_reg) 13980 { 13981 u64 src_val = reg_umin(src_reg); /* non-zero, const divisor */ 13982 13983 reg_set_urange64(dst_reg, div64_u64(reg_umin(dst_reg), src_val), 13984 div64_u64(reg_umax(dst_reg), src_val)); 13985 13986 /* Reset other ranges/tnum to unbounded/unknown. */ 13987 reset_reg32_and_tnum(dst_reg); 13988 } 13989 13990 static void scalar32_min_max_sdiv(struct bpf_reg_state *dst_reg, 13991 struct bpf_reg_state *src_reg) 13992 { 13993 s32 smin = reg_s32_min(dst_reg); 13994 s32 smax = reg_s32_max(dst_reg); 13995 s32 src_val = reg_s32_min(src_reg); /* non-zero, const divisor */ 13996 s32 res1, res2; 13997 13998 /* BPF div specification: S32_MIN / -1 = S32_MIN */ 13999 if (smin == S32_MIN && src_val == -1) { 14000 /* 14001 * If the dividend range contains more than just S32_MIN, 14002 * we cannot precisely track the result, so it becomes unbounded. 14003 * e.g., [S32_MIN, S32_MIN+10]/(-1), 14004 * = {S32_MIN} U [-(S32_MIN+10), -(S32_MIN+1)] 14005 * = {S32_MIN} U [S32_MAX-9, S32_MAX] = [S32_MIN, S32_MAX] 14006 * Otherwise (if dividend is exactly S32_MIN), result remains S32_MIN. 14007 */ 14008 if (smax != S32_MIN) { 14009 smin = S32_MIN; 14010 smax = S32_MAX; 14011 } 14012 goto reset; 14013 } 14014 14015 res1 = smin / src_val; 14016 res2 = smax / src_val; 14017 smin = min(res1, res2); 14018 smax = max(res1, res2); 14019 14020 reset: 14021 reg_set_srange32(dst_reg, smin, smax); 14022 /* Reset other ranges/tnum to unbounded/unknown. */ 14023 reset_reg64_and_tnum(dst_reg); 14024 } 14025 14026 static void scalar_min_max_sdiv(struct bpf_reg_state *dst_reg, 14027 struct bpf_reg_state *src_reg) 14028 { 14029 s64 smin = reg_smin(dst_reg); 14030 s64 smax = reg_smax(dst_reg); 14031 s64 src_val = reg_smin(src_reg); /* non-zero, const divisor */ 14032 s64 res1, res2; 14033 14034 /* BPF div specification: S64_MIN / -1 = S64_MIN */ 14035 if (smin == S64_MIN && src_val == -1) { 14036 /* 14037 * If the dividend range contains more than just S64_MIN, 14038 * we cannot precisely track the result, so it becomes unbounded. 14039 * e.g., [S64_MIN, S64_MIN+10]/(-1), 14040 * = {S64_MIN} U [-(S64_MIN+10), -(S64_MIN+1)] 14041 * = {S64_MIN} U [S64_MAX-9, S64_MAX] = [S64_MIN, S64_MAX] 14042 * Otherwise (if dividend is exactly S64_MIN), result remains S64_MIN. 14043 */ 14044 if (smax != S64_MIN) { 14045 smin = S64_MIN; 14046 smax = S64_MAX; 14047 } 14048 goto reset; 14049 } 14050 14051 res1 = div64_s64(smin, src_val); 14052 res2 = div64_s64(smax, src_val); 14053 smin = min(res1, res2); 14054 smax = max(res1, res2); 14055 14056 reset: 14057 reg_set_srange64(dst_reg, smin, smax); 14058 /* Reset other ranges/tnum to unbounded/unknown. */ 14059 reset_reg32_and_tnum(dst_reg); 14060 } 14061 14062 static void scalar32_min_max_umod(struct bpf_reg_state *dst_reg, 14063 struct bpf_reg_state *src_reg) 14064 { 14065 u32 src_val = reg_u32_min(src_reg); /* non-zero, const divisor */ 14066 u32 res_max = src_val - 1; 14067 14068 /* 14069 * If dst_umax <= res_max, the result remains unchanged. 14070 * e.g., [2, 5] % 10 = [2, 5]. 14071 */ 14072 if (reg_u32_max(dst_reg) <= res_max) 14073 return; 14074 14075 reg_set_urange32(dst_reg, 0, min(reg_u32_max(dst_reg), res_max)); 14076 14077 /* Reset other ranges/tnum to unbounded/unknown. */ 14078 reset_reg64_and_tnum(dst_reg); 14079 } 14080 14081 static void scalar_min_max_umod(struct bpf_reg_state *dst_reg, 14082 struct bpf_reg_state *src_reg) 14083 { 14084 u64 src_val = reg_umin(src_reg); /* non-zero, const divisor */ 14085 u64 res_max = src_val - 1; 14086 14087 /* 14088 * If dst_umax <= res_max, the result remains unchanged. 14089 * e.g., [2, 5] % 10 = [2, 5]. 14090 */ 14091 if (reg_umax(dst_reg) <= res_max) 14092 return; 14093 14094 reg_set_urange64(dst_reg, 0, min(reg_umax(dst_reg), res_max)); 14095 14096 /* Reset other ranges/tnum to unbounded/unknown. */ 14097 reset_reg32_and_tnum(dst_reg); 14098 } 14099 14100 static void scalar32_min_max_smod(struct bpf_reg_state *dst_reg, 14101 struct bpf_reg_state *src_reg) 14102 { 14103 s32 src_val = reg_s32_min(src_reg); /* non-zero, const divisor */ 14104 14105 /* 14106 * Safe absolute value calculation: 14107 * If src_val == S32_MIN (-2147483648), src_abs becomes 2147483648. 14108 * Here use unsigned integer to avoid overflow. 14109 */ 14110 u32 src_abs = (src_val > 0) ? (u32)src_val : -(u32)src_val; 14111 14112 /* 14113 * Calculate the maximum possible absolute value of the result. 14114 * Even if src_abs is 2147483648 (S32_MIN), subtracting 1 gives 14115 * 2147483647 (S32_MAX), which fits perfectly in s32. 14116 */ 14117 s32 res_max_abs = src_abs - 1; 14118 14119 /* 14120 * If the dividend is already within the result range, 14121 * the result remains unchanged. e.g., [-2, 5] % 10 = [-2, 5]. 14122 */ 14123 if (reg_s32_min(dst_reg) >= -res_max_abs && reg_s32_max(dst_reg) <= res_max_abs) 14124 return; 14125 14126 /* General case: result has the same sign as the dividend. */ 14127 if (reg_s32_min(dst_reg) >= 0) { 14128 reg_set_srange32(dst_reg, 0, min(reg_s32_max(dst_reg), res_max_abs)); 14129 } else if (reg_s32_max(dst_reg) <= 0) { 14130 reg_set_srange32(dst_reg, max(reg_s32_min(dst_reg), -res_max_abs), 0); 14131 } else { 14132 reg_set_srange32(dst_reg, -res_max_abs, res_max_abs); 14133 } 14134 14135 /* Reset other ranges/tnum to unbounded/unknown. */ 14136 reset_reg64_and_tnum(dst_reg); 14137 } 14138 14139 static void scalar_min_max_smod(struct bpf_reg_state *dst_reg, 14140 struct bpf_reg_state *src_reg) 14141 { 14142 s64 src_val = reg_smin(src_reg); /* non-zero, const divisor */ 14143 14144 /* 14145 * Safe absolute value calculation: 14146 * If src_val == S64_MIN (-2^63), src_abs becomes 2^63. 14147 * Here use unsigned integer to avoid overflow. 14148 */ 14149 u64 src_abs = (src_val > 0) ? (u64)src_val : -(u64)src_val; 14150 14151 /* 14152 * Calculate the maximum possible absolute value of the result. 14153 * Even if src_abs is 2^63 (S64_MIN), subtracting 1 gives 14154 * 2^63 - 1 (S64_MAX), which fits perfectly in s64. 14155 */ 14156 s64 res_max_abs = src_abs - 1; 14157 14158 /* 14159 * If the dividend is already within the result range, 14160 * the result remains unchanged. e.g., [-2, 5] % 10 = [-2, 5]. 14161 */ 14162 if (reg_smin(dst_reg) >= -res_max_abs && reg_smax(dst_reg) <= res_max_abs) 14163 return; 14164 14165 /* General case: result has the same sign as the dividend. */ 14166 if (reg_smin(dst_reg) >= 0) { 14167 reg_set_srange64(dst_reg, 0, min(reg_smax(dst_reg), res_max_abs)); 14168 } else if (reg_smax(dst_reg) <= 0) { 14169 reg_set_srange64(dst_reg, max(reg_smin(dst_reg), -res_max_abs), 0); 14170 } else { 14171 reg_set_srange64(dst_reg, -res_max_abs, res_max_abs); 14172 } 14173 14174 /* Reset other ranges/tnum to unbounded/unknown. */ 14175 reset_reg32_and_tnum(dst_reg); 14176 } 14177 14178 static void scalar32_min_max_and(struct bpf_reg_state *dst_reg, 14179 struct bpf_reg_state *src_reg) 14180 { 14181 bool src_known = tnum_subreg_is_const(src_reg->var_off); 14182 bool dst_known = tnum_subreg_is_const(dst_reg->var_off); 14183 struct tnum var32_off = tnum_subreg(dst_reg->var_off); 14184 u32 umax_val = reg_u32_max(src_reg); 14185 14186 if (src_known && dst_known) { 14187 __mark_reg32_known(dst_reg, var32_off.value); 14188 return; 14189 } 14190 14191 /* We get our minimum from the var_off, since that's inherently 14192 * bitwise. Our maximum is the minimum of the operands' maxima. 14193 */ 14194 reg_set_urange32(dst_reg, 14195 var32_off.value, 14196 min(reg_u32_max(dst_reg), umax_val)); 14197 } 14198 14199 static void scalar_min_max_and(struct bpf_reg_state *dst_reg, 14200 struct bpf_reg_state *src_reg) 14201 { 14202 bool src_known = tnum_is_const(src_reg->var_off); 14203 bool dst_known = tnum_is_const(dst_reg->var_off); 14204 u64 umax_val = reg_umax(src_reg); 14205 14206 if (src_known && dst_known) { 14207 __mark_reg_known(dst_reg, dst_reg->var_off.value); 14208 return; 14209 } 14210 14211 /* We get our minimum from the var_off, since that's inherently 14212 * bitwise. Our maximum is the minimum of the operands' maxima. 14213 */ 14214 reg_set_urange64(dst_reg, 14215 dst_reg->var_off.value, 14216 min(reg_umax(dst_reg), umax_val)); 14217 14218 /* We may learn something more from the var_off */ 14219 __update_reg_bounds(dst_reg); 14220 } 14221 14222 static void scalar32_min_max_or(struct bpf_reg_state *dst_reg, 14223 struct bpf_reg_state *src_reg) 14224 { 14225 bool src_known = tnum_subreg_is_const(src_reg->var_off); 14226 bool dst_known = tnum_subreg_is_const(dst_reg->var_off); 14227 struct tnum var32_off = tnum_subreg(dst_reg->var_off); 14228 u32 umin_val = reg_u32_min(src_reg); 14229 14230 if (src_known && dst_known) { 14231 __mark_reg32_known(dst_reg, var32_off.value); 14232 return; 14233 } 14234 14235 /* We get our maximum from the var_off, and our minimum is the 14236 * maximum of the operands' minima 14237 */ 14238 reg_set_urange32(dst_reg, 14239 max(reg_u32_min(dst_reg), umin_val), 14240 var32_off.value | var32_off.mask); 14241 } 14242 14243 static void scalar_min_max_or(struct bpf_reg_state *dst_reg, 14244 struct bpf_reg_state *src_reg) 14245 { 14246 bool src_known = tnum_is_const(src_reg->var_off); 14247 bool dst_known = tnum_is_const(dst_reg->var_off); 14248 u64 umin_val = reg_umin(src_reg); 14249 14250 if (src_known && dst_known) { 14251 __mark_reg_known(dst_reg, dst_reg->var_off.value); 14252 return; 14253 } 14254 14255 /* We get our maximum from the var_off, and our minimum is the 14256 * maximum of the operands' minima 14257 */ 14258 reg_set_urange64(dst_reg, 14259 max(reg_umin(dst_reg), umin_val), 14260 dst_reg->var_off.value | dst_reg->var_off.mask); 14261 14262 /* We may learn something more from the var_off */ 14263 __update_reg_bounds(dst_reg); 14264 } 14265 14266 static void scalar32_min_max_xor(struct bpf_reg_state *dst_reg, 14267 struct bpf_reg_state *src_reg) 14268 { 14269 bool src_known = tnum_subreg_is_const(src_reg->var_off); 14270 bool dst_known = tnum_subreg_is_const(dst_reg->var_off); 14271 struct tnum var32_off = tnum_subreg(dst_reg->var_off); 14272 14273 if (src_known && dst_known) { 14274 __mark_reg32_known(dst_reg, var32_off.value); 14275 return; 14276 } 14277 14278 /* We get both minimum and maximum from the var32_off. */ 14279 reg_set_urange32(dst_reg, var32_off.value, var32_off.value | var32_off.mask); 14280 } 14281 14282 static void scalar_min_max_xor(struct bpf_reg_state *dst_reg, 14283 struct bpf_reg_state *src_reg) 14284 { 14285 bool src_known = tnum_is_const(src_reg->var_off); 14286 bool dst_known = tnum_is_const(dst_reg->var_off); 14287 14288 if (src_known && dst_known) { 14289 /* dst_reg->var_off.value has been updated earlier */ 14290 __mark_reg_known(dst_reg, dst_reg->var_off.value); 14291 return; 14292 } 14293 14294 /* We get both minimum and maximum from the var_off. */ 14295 reg_set_urange64(dst_reg, 14296 dst_reg->var_off.value, 14297 dst_reg->var_off.value | dst_reg->var_off.mask); 14298 } 14299 14300 static void __scalar32_min_max_lsh(struct bpf_reg_state *dst_reg, 14301 u64 umin_val, u64 umax_val) 14302 { 14303 /* If we might shift our top bit out, then we know nothing */ 14304 if (umax_val > 31 || reg_u32_max(dst_reg) > 1ULL << (31 - umax_val)) 14305 reg_set_urange32(dst_reg, 0, U32_MAX); 14306 else 14307 /* We lose all sign bit information (except what we can pick 14308 * up from var_off) 14309 */ 14310 reg_set_urange32(dst_reg, reg_u32_min(dst_reg) << umin_val, 14311 reg_u32_max(dst_reg) << umax_val); 14312 } 14313 14314 static void scalar32_min_max_lsh(struct bpf_reg_state *dst_reg, 14315 struct bpf_reg_state *src_reg) 14316 { 14317 u32 umax_val = reg_u32_max(src_reg); 14318 u32 umin_val = reg_u32_min(src_reg); 14319 /* u32 alu operation will zext upper bits */ 14320 struct tnum subreg = tnum_subreg(dst_reg->var_off); 14321 14322 __scalar32_min_max_lsh(dst_reg, umin_val, umax_val); 14323 dst_reg->var_off = tnum_subreg(tnum_lshift(subreg, umin_val)); 14324 /* Not required but being careful mark reg64 bounds as unknown so 14325 * that we are forced to pick them up from tnum and zext later and 14326 * if some path skips this step we are still safe. 14327 */ 14328 __mark_reg64_unbounded(dst_reg); 14329 __update_reg32_bounds(dst_reg); 14330 } 14331 14332 static void __scalar64_min_max_lsh(struct bpf_reg_state *dst_reg, 14333 u64 umin_val, u64 umax_val) 14334 { 14335 struct cnum64 u, s; 14336 14337 /* Special case <<32 because it is a common compiler pattern to sign 14338 * extend subreg by doing <<32 s>>32. smin/smax assignments are correct 14339 * because s32 bounds don't flip sign when shifting to the left by 14340 * 32bits. 14341 */ 14342 if (umin_val == 32 && umax_val == 32) 14343 s = cnum64_from_srange((s64)reg_s32_min(dst_reg) << 32, 14344 (s64)reg_s32_max(dst_reg) << 32); 14345 else 14346 s = CNUM64_UNBOUNDED; 14347 14348 /* If we might shift our top bit out, then we know nothing */ 14349 if (reg_umax(dst_reg) > 1ULL << (63 - umax_val)) 14350 u = CNUM64_UNBOUNDED; 14351 else 14352 u = cnum64_from_urange(reg_umin(dst_reg) << umin_val, 14353 reg_umax(dst_reg) << umax_val); 14354 14355 dst_reg->r64 = cnum64_intersect(u, s); 14356 } 14357 14358 static void scalar_min_max_lsh(struct bpf_reg_state *dst_reg, 14359 struct bpf_reg_state *src_reg) 14360 { 14361 u64 umax_val = reg_umax(src_reg); 14362 u64 umin_val = reg_umin(src_reg); 14363 14364 /* scalar64 calc uses 32bit unshifted bounds so must be called first */ 14365 __scalar64_min_max_lsh(dst_reg, umin_val, umax_val); 14366 __scalar32_min_max_lsh(dst_reg, umin_val, umax_val); 14367 14368 dst_reg->var_off = tnum_lshift(dst_reg->var_off, umin_val); 14369 /* We may learn something more from the var_off */ 14370 __update_reg_bounds(dst_reg); 14371 } 14372 14373 static void scalar32_min_max_rsh(struct bpf_reg_state *dst_reg, 14374 struct bpf_reg_state *src_reg) 14375 { 14376 struct tnum subreg = tnum_subreg(dst_reg->var_off); 14377 u32 umax_val = reg_u32_max(src_reg); 14378 u32 umin_val = reg_u32_min(src_reg); 14379 14380 /* BPF_RSH is an unsigned shift. If the value in dst_reg might 14381 * be negative, then either: 14382 * 1) src_reg might be zero, so the sign bit of the result is 14383 * unknown, so we lose our signed bounds 14384 * 2) it's known negative, thus the unsigned bounds capture the 14385 * signed bounds 14386 * 3) the signed bounds cross zero, so they tell us nothing 14387 * about the result 14388 * If the value in dst_reg is known nonnegative, then again the 14389 * unsigned bounds capture the signed bounds. 14390 * Thus, in all cases it suffices to blow away our signed bounds 14391 * and rely on inferring new ones from the unsigned bounds and 14392 * var_off of the result. 14393 */ 14394 14395 dst_reg->var_off = tnum_rshift(subreg, umin_val); 14396 reg_set_urange32(dst_reg, reg_u32_min(dst_reg) >> umax_val, 14397 reg_u32_max(dst_reg) >> umin_val); 14398 14399 __mark_reg64_unbounded(dst_reg); 14400 __update_reg32_bounds(dst_reg); 14401 } 14402 14403 static void scalar_min_max_rsh(struct bpf_reg_state *dst_reg, 14404 struct bpf_reg_state *src_reg) 14405 { 14406 u64 umax_val = reg_umax(src_reg); 14407 u64 umin_val = reg_umin(src_reg); 14408 14409 /* BPF_RSH is an unsigned shift. If the value in dst_reg might 14410 * be negative, then either: 14411 * 1) src_reg might be zero, so the sign bit of the result is 14412 * unknown, so we lose our signed bounds 14413 * 2) it's known negative, thus the unsigned bounds capture the 14414 * signed bounds 14415 * 3) the signed bounds cross zero, so they tell us nothing 14416 * about the result 14417 * If the value in dst_reg is known nonnegative, then again the 14418 * unsigned bounds capture the signed bounds. 14419 * Thus, in all cases it suffices to blow away our signed bounds 14420 * and rely on inferring new ones from the unsigned bounds and 14421 * var_off of the result. 14422 */ 14423 dst_reg->var_off = tnum_rshift(dst_reg->var_off, umin_val); 14424 reg_set_urange64(dst_reg, reg_umin(dst_reg) >> umax_val, 14425 reg_umax(dst_reg) >> umin_val); 14426 14427 /* Its not easy to operate on alu32 bounds here because it depends 14428 * on bits being shifted in. Take easy way out and mark unbounded 14429 * so we can recalculate later from tnum. 14430 */ 14431 __mark_reg32_unbounded(dst_reg); 14432 __update_reg_bounds(dst_reg); 14433 } 14434 14435 static void scalar32_min_max_arsh(struct bpf_reg_state *dst_reg, 14436 struct bpf_reg_state *src_reg) 14437 { 14438 u64 umin_val = reg_u32_min(src_reg); 14439 14440 /* Upon reaching here, src_known is true and 14441 * umax_val is equal to umin_val. 14442 * Blow away the dst_reg umin_value/umax_value and rely on 14443 * dst_reg var_off to refine the result. 14444 */ 14445 reg_set_srange32(dst_reg, 14446 (u32)(((s32)reg_s32_min(dst_reg)) >> umin_val), 14447 (u32)(((s32)reg_s32_max(dst_reg)) >> umin_val)); 14448 14449 dst_reg->var_off = tnum_arshift(tnum_subreg(dst_reg->var_off), umin_val, 32); 14450 14451 __mark_reg64_unbounded(dst_reg); 14452 __update_reg32_bounds(dst_reg); 14453 } 14454 14455 static void scalar_min_max_arsh(struct bpf_reg_state *dst_reg, 14456 struct bpf_reg_state *src_reg) 14457 { 14458 u64 umin_val = reg_umin(src_reg); 14459 14460 /* Upon reaching here, src_known is true and umax_val is equal 14461 * to umin_val. 14462 */ 14463 reg_set_srange64(dst_reg, reg_smin(dst_reg) >> umin_val, 14464 reg_smax(dst_reg) >> umin_val); 14465 14466 dst_reg->var_off = tnum_arshift(dst_reg->var_off, umin_val, 64); 14467 14468 /* Its not easy to operate on alu32 bounds here because it depends 14469 * on bits being shifted in from upper 32-bits. Take easy way out 14470 * and mark unbounded so we can recalculate later from tnum. 14471 */ 14472 __mark_reg32_unbounded(dst_reg); 14473 __update_reg_bounds(dst_reg); 14474 } 14475 14476 static void scalar_byte_swap(struct bpf_reg_state *dst_reg, struct bpf_insn *insn) 14477 { 14478 /* 14479 * Byte swap operation - update var_off using tnum_bswap. 14480 * Three cases: 14481 * 1. bswap(16|32|64): opcode=0xd7 (BPF_END | BPF_ALU64 | BPF_TO_LE) 14482 * unconditional swap 14483 * 2. to_le(16|32|64): opcode=0xd4 (BPF_END | BPF_ALU | BPF_TO_LE) 14484 * swap on big-endian, truncation or no-op on little-endian 14485 * 3. to_be(16|32|64): opcode=0xdc (BPF_END | BPF_ALU | BPF_TO_BE) 14486 * swap on little-endian, truncation or no-op on big-endian 14487 */ 14488 14489 bool alu64 = BPF_CLASS(insn->code) == BPF_ALU64; 14490 bool to_le = BPF_SRC(insn->code) == BPF_TO_LE; 14491 bool is_big_endian; 14492 #ifdef CONFIG_CPU_BIG_ENDIAN 14493 is_big_endian = true; 14494 #else 14495 is_big_endian = false; 14496 #endif 14497 /* Apply bswap if alu64 or switch between big-endian and little-endian machines */ 14498 bool need_bswap = alu64 || (to_le == is_big_endian); 14499 14500 /* 14501 * If the register is mutated, manually reset its scalar ID to break 14502 * any existing ties and avoid incorrect bounds propagation. 14503 */ 14504 if (need_bswap || insn->imm == 16 || insn->imm == 32) 14505 clear_scalar_id(dst_reg); 14506 14507 if (need_bswap) { 14508 if (insn->imm == 16) 14509 dst_reg->var_off = tnum_bswap16(dst_reg->var_off); 14510 else if (insn->imm == 32) 14511 dst_reg->var_off = tnum_bswap32(dst_reg->var_off); 14512 else if (insn->imm == 64) 14513 dst_reg->var_off = tnum_bswap64(dst_reg->var_off); 14514 /* 14515 * Byteswap scrambles the range, so we must reset bounds. 14516 * Bounds will be re-derived from the new tnum later. 14517 */ 14518 __mark_reg_unbounded(dst_reg); 14519 } 14520 /* For bswap16/32, truncate dst register to match the swapped size */ 14521 if (insn->imm == 16 || insn->imm == 32) 14522 coerce_reg_to_size(dst_reg, insn->imm / 8); 14523 } 14524 14525 static bool is_safe_to_compute_dst_reg_range(struct bpf_insn *insn, 14526 const struct bpf_reg_state *src_reg) 14527 { 14528 bool src_is_const = false; 14529 u64 insn_bitness = (BPF_CLASS(insn->code) == BPF_ALU64) ? 64 : 32; 14530 14531 if (insn_bitness == 32) { 14532 if (tnum_subreg_is_const(src_reg->var_off) 14533 && reg_s32_min(src_reg) == reg_s32_max(src_reg) 14534 && reg_u32_min(src_reg) == reg_u32_max(src_reg)) 14535 src_is_const = true; 14536 } else { 14537 if (tnum_is_const(src_reg->var_off) 14538 && reg_smin(src_reg) == reg_smax(src_reg) 14539 && reg_umin(src_reg) == reg_umax(src_reg)) 14540 src_is_const = true; 14541 } 14542 14543 switch (BPF_OP(insn->code)) { 14544 case BPF_ADD: 14545 case BPF_SUB: 14546 case BPF_NEG: 14547 case BPF_AND: 14548 case BPF_XOR: 14549 case BPF_OR: 14550 case BPF_MUL: 14551 case BPF_END: 14552 return true; 14553 14554 /* 14555 * Division and modulo operators range is only safe to compute when the 14556 * divisor is a constant. 14557 */ 14558 case BPF_DIV: 14559 case BPF_MOD: 14560 return src_is_const; 14561 14562 /* Shift operators range is only computable if shift dimension operand 14563 * is a constant. Shifts greater than 31 or 63 are undefined. This 14564 * includes shifts by a negative number. 14565 */ 14566 case BPF_LSH: 14567 case BPF_RSH: 14568 case BPF_ARSH: 14569 return (src_is_const && reg_umax(src_reg) < insn_bitness); 14570 default: 14571 return false; 14572 } 14573 } 14574 14575 static int maybe_fork_scalars(struct bpf_verifier_env *env, struct bpf_insn *insn, 14576 struct bpf_reg_state *dst_reg) 14577 { 14578 struct bpf_verifier_state *branch; 14579 struct bpf_reg_state *regs; 14580 bool alu32; 14581 14582 if (reg_smin(dst_reg) == -1 && reg_smax(dst_reg) == 0) 14583 alu32 = false; 14584 else if (reg_s32_min(dst_reg) == -1 && reg_s32_max(dst_reg) == 0) 14585 alu32 = true; 14586 else 14587 return 0; 14588 14589 branch = push_stack(env, env->insn_idx, env->insn_idx, false); 14590 if (IS_ERR(branch)) 14591 return PTR_ERR(branch); 14592 14593 regs = branch->frame[branch->curframe]->regs; 14594 if (alu32) { 14595 __mark_reg32_known(®s[insn->dst_reg], 0); 14596 __mark_reg32_known(dst_reg, -1ull); 14597 } else { 14598 __mark_reg_known(®s[insn->dst_reg], 0); 14599 __mark_reg_known(dst_reg, -1ull); 14600 } 14601 return 0; 14602 } 14603 14604 /* WARNING: This function does calculations on 64-bit values, but the actual 14605 * execution may occur on 32-bit values. Therefore, things like bitshifts 14606 * need extra checks in the 32-bit case. 14607 */ 14608 static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env, 14609 struct bpf_insn *insn, 14610 struct bpf_reg_state *dst_reg, 14611 struct bpf_reg_state src_reg) 14612 { 14613 u8 opcode = BPF_OP(insn->code); 14614 s16 off = insn->off; 14615 bool alu32 = (BPF_CLASS(insn->code) != BPF_ALU64); 14616 int ret; 14617 14618 if (!is_safe_to_compute_dst_reg_range(insn, &src_reg)) { 14619 __mark_reg_unknown(env, dst_reg); 14620 return 0; 14621 } 14622 14623 if (sanitize_needed(opcode)) { 14624 ret = sanitize_val_alu(env, insn); 14625 if (ret < 0) 14626 return sanitize_err(env, insn, ret, NULL, NULL); 14627 } 14628 14629 /* Calculate sign/unsigned bounds and tnum for alu32 and alu64 bit ops. 14630 * There are two classes of instructions: The first class we track both 14631 * alu32 and alu64 sign/unsigned bounds independently this provides the 14632 * greatest amount of precision when alu operations are mixed with jmp32 14633 * operations. These operations are BPF_ADD, BPF_SUB, BPF_MUL, BPF_ADD, 14634 * and BPF_OR. This is possible because these ops have fairly easy to 14635 * understand and calculate behavior in both 32-bit and 64-bit alu ops. 14636 * See alu32 verifier tests for examples. The second class of 14637 * operations, BPF_LSH, BPF_RSH, and BPF_ARSH, however are not so easy 14638 * with regards to tracking sign/unsigned bounds because the bits may 14639 * cross subreg boundaries in the alu64 case. When this happens we mark 14640 * the reg unbounded in the subreg bound space and use the resulting 14641 * tnum to calculate an approximation of the sign/unsigned bounds. 14642 */ 14643 switch (opcode) { 14644 case BPF_ADD: 14645 scalar32_min_max_add(dst_reg, &src_reg); 14646 scalar_min_max_add(dst_reg, &src_reg); 14647 dst_reg->var_off = tnum_add(dst_reg->var_off, src_reg.var_off); 14648 break; 14649 case BPF_SUB: 14650 scalar32_min_max_sub(dst_reg, &src_reg); 14651 scalar_min_max_sub(dst_reg, &src_reg); 14652 dst_reg->var_off = tnum_sub(dst_reg->var_off, src_reg.var_off); 14653 break; 14654 case BPF_NEG: 14655 env->fake_reg[0] = *dst_reg; 14656 __mark_reg_known(dst_reg, 0); 14657 scalar32_min_max_sub(dst_reg, &env->fake_reg[0]); 14658 scalar_min_max_sub(dst_reg, &env->fake_reg[0]); 14659 dst_reg->var_off = tnum_neg(env->fake_reg[0].var_off); 14660 break; 14661 case BPF_MUL: 14662 dst_reg->var_off = tnum_mul(dst_reg->var_off, src_reg.var_off); 14663 scalar32_min_max_mul(dst_reg, &src_reg); 14664 scalar_min_max_mul(dst_reg, &src_reg); 14665 break; 14666 case BPF_DIV: 14667 /* BPF div specification: x / 0 = 0 */ 14668 if ((alu32 && reg_u32_min(&src_reg) == 0) || (!alu32 && reg_umin(&src_reg) == 0)) { 14669 ___mark_reg_known(dst_reg, 0); 14670 break; 14671 } 14672 if (alu32) 14673 if (off == 1) 14674 scalar32_min_max_sdiv(dst_reg, &src_reg); 14675 else 14676 scalar32_min_max_udiv(dst_reg, &src_reg); 14677 else 14678 if (off == 1) 14679 scalar_min_max_sdiv(dst_reg, &src_reg); 14680 else 14681 scalar_min_max_udiv(dst_reg, &src_reg); 14682 break; 14683 case BPF_MOD: 14684 /* BPF mod specification: x % 0 = x */ 14685 if ((alu32 && reg_u32_min(&src_reg) == 0) || (!alu32 && reg_umin(&src_reg) == 0)) 14686 break; 14687 if (alu32) 14688 if (off == 1) 14689 scalar32_min_max_smod(dst_reg, &src_reg); 14690 else 14691 scalar32_min_max_umod(dst_reg, &src_reg); 14692 else 14693 if (off == 1) 14694 scalar_min_max_smod(dst_reg, &src_reg); 14695 else 14696 scalar_min_max_umod(dst_reg, &src_reg); 14697 break; 14698 case BPF_AND: 14699 if (tnum_is_const(src_reg.var_off)) { 14700 ret = maybe_fork_scalars(env, insn, dst_reg); 14701 if (ret) 14702 return ret; 14703 } 14704 dst_reg->var_off = tnum_and(dst_reg->var_off, src_reg.var_off); 14705 scalar32_min_max_and(dst_reg, &src_reg); 14706 scalar_min_max_and(dst_reg, &src_reg); 14707 break; 14708 case BPF_OR: 14709 if (tnum_is_const(src_reg.var_off)) { 14710 ret = maybe_fork_scalars(env, insn, dst_reg); 14711 if (ret) 14712 return ret; 14713 } 14714 dst_reg->var_off = tnum_or(dst_reg->var_off, src_reg.var_off); 14715 scalar32_min_max_or(dst_reg, &src_reg); 14716 scalar_min_max_or(dst_reg, &src_reg); 14717 break; 14718 case BPF_XOR: 14719 dst_reg->var_off = tnum_xor(dst_reg->var_off, src_reg.var_off); 14720 scalar32_min_max_xor(dst_reg, &src_reg); 14721 scalar_min_max_xor(dst_reg, &src_reg); 14722 break; 14723 case BPF_LSH: 14724 if (alu32) 14725 scalar32_min_max_lsh(dst_reg, &src_reg); 14726 else 14727 scalar_min_max_lsh(dst_reg, &src_reg); 14728 break; 14729 case BPF_RSH: 14730 if (alu32) 14731 scalar32_min_max_rsh(dst_reg, &src_reg); 14732 else 14733 scalar_min_max_rsh(dst_reg, &src_reg); 14734 break; 14735 case BPF_ARSH: 14736 if (alu32) 14737 scalar32_min_max_arsh(dst_reg, &src_reg); 14738 else 14739 scalar_min_max_arsh(dst_reg, &src_reg); 14740 break; 14741 case BPF_END: 14742 scalar_byte_swap(dst_reg, insn); 14743 break; 14744 default: 14745 break; 14746 } 14747 14748 /* 14749 * ALU32 ops are zero extended into 64bit register. 14750 * 14751 * BPF_END is already handled inside the helper (truncation), 14752 * so skip zext here to avoid unexpected zero extension. 14753 * e.g., le64: opcode=(BPF_END|BPF_ALU|BPF_TO_LE), imm=0x40 14754 * This is a 64bit byte swap operation with alu32==true, 14755 * but we should not zero extend the result. 14756 */ 14757 if (alu32 && opcode != BPF_END) 14758 zext_32_to_64(dst_reg); 14759 reg_bounds_sync(dst_reg); 14760 return 0; 14761 } 14762 14763 /* Handles ALU ops other than BPF_END, BPF_NEG and BPF_MOV: computes new min/max 14764 * and var_off. 14765 */ 14766 static int adjust_reg_min_max_vals(struct bpf_verifier_env *env, 14767 struct bpf_insn *insn) 14768 { 14769 struct bpf_verifier_state *vstate = env->cur_state; 14770 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 14771 struct bpf_reg_state *regs = state->regs, *dst_reg, *src_reg; 14772 struct bpf_reg_state *ptr_reg = NULL, off_reg = {0}; 14773 bool alu32 = (BPF_CLASS(insn->code) != BPF_ALU64); 14774 u8 opcode = BPF_OP(insn->code); 14775 int err; 14776 14777 dst_reg = ®s[insn->dst_reg]; 14778 if (BPF_SRC(insn->code) == BPF_X) 14779 src_reg = ®s[insn->src_reg]; 14780 else 14781 src_reg = NULL; 14782 14783 /* Case where at least one operand is an arena. */ 14784 if (dst_reg->type == PTR_TO_ARENA || (src_reg && src_reg->type == PTR_TO_ARENA)) { 14785 struct bpf_insn_aux_data *aux = cur_aux(env); 14786 14787 if (dst_reg->type != PTR_TO_ARENA) 14788 *dst_reg = *src_reg; 14789 14790 dst_reg->subreg_def = env->insn_idx + 1; 14791 14792 if (BPF_CLASS(insn->code) == BPF_ALU64) 14793 /* 14794 * 32-bit operations zero upper bits automatically. 14795 * 64-bit operations need to be converted to 32. 14796 */ 14797 aux->needs_zext = true; 14798 14799 /* Any arithmetic operations are allowed on arena pointers */ 14800 return 0; 14801 } 14802 14803 if (dst_reg->type != SCALAR_VALUE) 14804 ptr_reg = dst_reg; 14805 14806 if (BPF_SRC(insn->code) == BPF_X) { 14807 if (src_reg->type != SCALAR_VALUE) { 14808 if (dst_reg->type != SCALAR_VALUE) { 14809 /* Combining two pointers by any ALU op yields 14810 * an arbitrary scalar. Disallow all math except 14811 * pointer subtraction 14812 */ 14813 if (opcode == BPF_SUB && env->allow_ptr_leaks) { 14814 mark_reg_unknown(env, regs, insn->dst_reg); 14815 return 0; 14816 } 14817 verbose(env, "R%d pointer %s pointer prohibited\n", 14818 insn->dst_reg, 14819 bpf_alu_string[opcode >> 4]); 14820 return -EACCES; 14821 } else { 14822 /* scalar += pointer 14823 * This is legal, but we have to reverse our 14824 * src/dest handling in computing the range 14825 */ 14826 err = mark_chain_precision(env, insn->dst_reg); 14827 if (err) 14828 return err; 14829 return adjust_ptr_min_max_vals(env, insn, 14830 src_reg, dst_reg); 14831 } 14832 } else if (ptr_reg) { 14833 /* pointer += scalar */ 14834 err = mark_chain_precision(env, insn->src_reg); 14835 if (err) 14836 return err; 14837 return adjust_ptr_min_max_vals(env, insn, 14838 dst_reg, src_reg); 14839 } else if (dst_reg->precise) { 14840 /* if dst_reg is precise, src_reg should be precise as well */ 14841 err = mark_chain_precision(env, insn->src_reg); 14842 if (err) 14843 return err; 14844 } 14845 } else { 14846 /* Pretend the src is a reg with a known value, since we only 14847 * need to be able to read from this state. 14848 */ 14849 off_reg.type = SCALAR_VALUE; 14850 __mark_reg_known(&off_reg, insn->imm); 14851 src_reg = &off_reg; 14852 if (ptr_reg) /* pointer += K */ 14853 return adjust_ptr_min_max_vals(env, insn, 14854 ptr_reg, src_reg); 14855 } 14856 14857 /* Got here implies adding two SCALAR_VALUEs */ 14858 if (WARN_ON_ONCE(ptr_reg)) { 14859 print_verifier_state(env, vstate, vstate->curframe, true); 14860 verbose(env, "verifier internal error: unexpected ptr_reg\n"); 14861 return -EFAULT; 14862 } 14863 if (WARN_ON(!src_reg)) { 14864 print_verifier_state(env, vstate, vstate->curframe, true); 14865 verbose(env, "verifier internal error: no src_reg\n"); 14866 return -EFAULT; 14867 } 14868 /* 14869 * For alu32 linked register tracking, we need to check dst_reg's 14870 * umax_value before the ALU operation. After adjust_scalar_min_max_vals(), 14871 * alu32 ops will have zero-extended the result, making umax_value <= U32_MAX. 14872 */ 14873 u64 dst_umax = reg_umax(dst_reg); 14874 14875 err = adjust_scalar_min_max_vals(env, insn, dst_reg, *src_reg); 14876 if (err) 14877 return err; 14878 /* 14879 * Compilers can generate the code 14880 * r1 = r2 14881 * r1 += 0x1 14882 * if r2 < 1000 goto ... 14883 * use r1 in memory access 14884 * So remember constant delta between r2 and r1 and update r1 after 14885 * 'if' condition. 14886 */ 14887 if (env->bpf_capable && 14888 (BPF_OP(insn->code) == BPF_ADD || BPF_OP(insn->code) == BPF_SUB) && 14889 dst_reg->id && is_reg_const(src_reg, alu32) && 14890 !(BPF_SRC(insn->code) == BPF_X && insn->src_reg == insn->dst_reg)) { 14891 u64 val = reg_const_value(src_reg, alu32); 14892 s32 off; 14893 14894 if (!alu32 && ((s64)val < S32_MIN || (s64)val > S32_MAX)) 14895 goto clear_id; 14896 14897 if (alu32 && (dst_umax > U32_MAX)) 14898 goto clear_id; 14899 14900 off = (s32)val; 14901 14902 if (BPF_OP(insn->code) == BPF_SUB) { 14903 /* Negating S32_MIN would overflow */ 14904 if (off == S32_MIN) 14905 goto clear_id; 14906 off = -off; 14907 } 14908 14909 if (dst_reg->id & BPF_ADD_CONST) { 14910 /* 14911 * If the register already went through rX += val 14912 * we cannot accumulate another val into rx->off. 14913 */ 14914 clear_id: 14915 clear_scalar_id(dst_reg); 14916 } else { 14917 if (alu32) 14918 dst_reg->id |= BPF_ADD_CONST32; 14919 else 14920 dst_reg->id |= BPF_ADD_CONST64; 14921 dst_reg->delta = off; 14922 } 14923 } else { 14924 /* 14925 * Make sure ID is cleared otherwise dst_reg min/max could be 14926 * incorrectly propagated into other registers by sync_linked_regs() 14927 */ 14928 clear_scalar_id(dst_reg); 14929 } 14930 return 0; 14931 } 14932 14933 /* check validity of 32-bit and 64-bit arithmetic operations */ 14934 static int check_alu_op(struct bpf_verifier_env *env, struct bpf_insn *insn) 14935 { 14936 struct bpf_reg_state *regs = cur_regs(env); 14937 u8 opcode = BPF_OP(insn->code); 14938 int err; 14939 14940 if (opcode == BPF_END || opcode == BPF_NEG) { 14941 /* check src operand */ 14942 err = check_reg_arg(env, insn->dst_reg, SRC_OP); 14943 if (err) 14944 return err; 14945 14946 if (is_pointer_value(env, insn->dst_reg)) { 14947 verbose(env, "R%d pointer arithmetic prohibited\n", 14948 insn->dst_reg); 14949 return -EACCES; 14950 } 14951 14952 /* check dest operand */ 14953 if (regs[insn->dst_reg].type == SCALAR_VALUE) { 14954 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK); 14955 err = err ?: adjust_scalar_min_max_vals(env, insn, 14956 ®s[insn->dst_reg], 14957 regs[insn->dst_reg]); 14958 } else { 14959 err = check_reg_arg(env, insn->dst_reg, DST_OP); 14960 } 14961 if (err) 14962 return err; 14963 14964 } else if (opcode == BPF_MOV) { 14965 14966 if (BPF_SRC(insn->code) == BPF_X) { 14967 if (insn->off == BPF_ADDR_SPACE_CAST) { 14968 if (!env->prog->aux->arena) { 14969 verbose(env, "addr_space_cast insn can only be used in a program that has an associated arena\n"); 14970 return -EINVAL; 14971 } 14972 } 14973 14974 /* check src operand */ 14975 err = check_reg_arg(env, insn->src_reg, SRC_OP); 14976 if (err) 14977 return err; 14978 } 14979 14980 /* check dest operand, mark as required later */ 14981 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK); 14982 if (err) 14983 return err; 14984 14985 if (BPF_SRC(insn->code) == BPF_X) { 14986 struct bpf_reg_state *src_reg = regs + insn->src_reg; 14987 struct bpf_reg_state *dst_reg = regs + insn->dst_reg; 14988 14989 if (BPF_CLASS(insn->code) == BPF_ALU64) { 14990 if (insn->imm) { 14991 /* off == BPF_ADDR_SPACE_CAST */ 14992 mark_reg_unknown(env, regs, insn->dst_reg); 14993 if (insn->imm == 1) { /* cast from as(1) to as(0) */ 14994 dst_reg->type = PTR_TO_ARENA; 14995 /* PTR_TO_ARENA is 32-bit */ 14996 dst_reg->subreg_def = env->insn_idx + 1; 14997 } 14998 } else if (insn->off == 0) { 14999 /* case: R1 = R2 15000 * copy register state to dest reg 15001 */ 15002 assign_scalar_id_before_mov(env, src_reg); 15003 *dst_reg = *src_reg; 15004 dst_reg->subreg_def = DEF_NOT_SUBREG; 15005 } else { 15006 /* case: R1 = (s8, s16 s32)R2 */ 15007 if (is_pointer_value(env, insn->src_reg)) { 15008 verbose(env, 15009 "R%d sign-extension part of pointer\n", 15010 insn->src_reg); 15011 return -EACCES; 15012 } else if (src_reg->type == SCALAR_VALUE) { 15013 bool no_sext; 15014 15015 no_sext = reg_umax(src_reg) < (1ULL << (insn->off - 1)); 15016 if (no_sext) 15017 assign_scalar_id_before_mov(env, src_reg); 15018 *dst_reg = *src_reg; 15019 if (!no_sext) 15020 clear_scalar_id(dst_reg); 15021 coerce_reg_to_size_sx(dst_reg, insn->off >> 3); 15022 dst_reg->subreg_def = DEF_NOT_SUBREG; 15023 } else { 15024 mark_reg_unknown(env, regs, insn->dst_reg); 15025 } 15026 } 15027 } else { 15028 /* R1 = (u32) R2 */ 15029 if (is_pointer_value(env, insn->src_reg)) { 15030 verbose(env, 15031 "R%d partial copy of pointer\n", 15032 insn->src_reg); 15033 return -EACCES; 15034 } else if (src_reg->type == SCALAR_VALUE) { 15035 if (insn->off == 0) { 15036 bool is_src_reg_u32 = get_reg_width(src_reg) <= 32; 15037 15038 if (is_src_reg_u32) 15039 assign_scalar_id_before_mov(env, src_reg); 15040 *dst_reg = *src_reg; 15041 /* Make sure ID is cleared if src_reg is not in u32 15042 * range otherwise dst_reg min/max could be incorrectly 15043 * propagated into src_reg by sync_linked_regs() 15044 */ 15045 if (!is_src_reg_u32) 15046 clear_scalar_id(dst_reg); 15047 dst_reg->subreg_def = env->insn_idx + 1; 15048 } else { 15049 /* case: W1 = (s8, s16)W2 */ 15050 bool no_sext = reg_umax(src_reg) < (1ULL << (insn->off - 1)); 15051 15052 if (no_sext) 15053 assign_scalar_id_before_mov(env, src_reg); 15054 *dst_reg = *src_reg; 15055 if (!no_sext) 15056 clear_scalar_id(dst_reg); 15057 dst_reg->subreg_def = env->insn_idx + 1; 15058 coerce_subreg_to_size_sx(dst_reg, insn->off >> 3); 15059 } 15060 } else { 15061 mark_reg_unknown(env, regs, 15062 insn->dst_reg); 15063 } 15064 zext_32_to_64(dst_reg); 15065 reg_bounds_sync(dst_reg); 15066 } 15067 } else { 15068 /* case: R = imm 15069 * remember the value we stored into this reg 15070 */ 15071 /* clear any state __mark_reg_known doesn't set */ 15072 mark_reg_unknown(env, regs, insn->dst_reg); 15073 regs[insn->dst_reg].type = SCALAR_VALUE; 15074 if (BPF_CLASS(insn->code) == BPF_ALU64) { 15075 __mark_reg_known(regs + insn->dst_reg, 15076 insn->imm); 15077 } else { 15078 __mark_reg_known(regs + insn->dst_reg, 15079 (u32)insn->imm); 15080 } 15081 } 15082 15083 } else { /* all other ALU ops: and, sub, xor, add, ... */ 15084 15085 if (BPF_SRC(insn->code) == BPF_X) { 15086 /* check src1 operand */ 15087 err = check_reg_arg(env, insn->src_reg, SRC_OP); 15088 if (err) 15089 return err; 15090 } 15091 15092 /* check src2 operand */ 15093 err = check_reg_arg(env, insn->dst_reg, SRC_OP); 15094 if (err) 15095 return err; 15096 15097 if ((opcode == BPF_MOD || opcode == BPF_DIV) && 15098 BPF_SRC(insn->code) == BPF_K && insn->imm == 0) { 15099 verbose(env, "div by zero\n"); 15100 return -EINVAL; 15101 } 15102 15103 if ((opcode == BPF_LSH || opcode == BPF_RSH || 15104 opcode == BPF_ARSH) && BPF_SRC(insn->code) == BPF_K) { 15105 int size = BPF_CLASS(insn->code) == BPF_ALU64 ? 64 : 32; 15106 15107 if (insn->imm < 0 || insn->imm >= size) { 15108 verbose(env, "invalid shift %d\n", insn->imm); 15109 return -EINVAL; 15110 } 15111 } 15112 15113 /* check dest operand */ 15114 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK); 15115 err = err ?: adjust_reg_min_max_vals(env, insn); 15116 if (err) 15117 return err; 15118 } 15119 15120 return reg_bounds_sanity_check(env, ®s[insn->dst_reg], "alu"); 15121 } 15122 15123 static void find_good_pkt_pointers(struct bpf_verifier_state *vstate, 15124 struct bpf_reg_state *dst_reg, 15125 enum bpf_reg_type type, 15126 bool range_right_open) 15127 { 15128 struct bpf_func_state *state; 15129 struct bpf_reg_state *reg; 15130 int new_range; 15131 15132 if (reg_umax(dst_reg) == 0 && range_right_open) 15133 /* This doesn't give us any range */ 15134 return; 15135 15136 if (reg_umax(dst_reg) > MAX_PACKET_OFF) 15137 /* Risk of overflow. For instance, ptr + (1<<63) may be less 15138 * than pkt_end, but that's because it's also less than pkt. 15139 */ 15140 return; 15141 15142 new_range = reg_umax(dst_reg); 15143 if (range_right_open) 15144 new_range++; 15145 15146 /* Examples for register markings: 15147 * 15148 * pkt_data in dst register: 15149 * 15150 * r2 = r3; 15151 * r2 += 8; 15152 * if (r2 > pkt_end) goto <handle exception> 15153 * <access okay> 15154 * 15155 * r2 = r3; 15156 * r2 += 8; 15157 * if (r2 < pkt_end) goto <access okay> 15158 * <handle exception> 15159 * 15160 * Where: 15161 * r2 == dst_reg, pkt_end == src_reg 15162 * r2=pkt(id=n,off=8,r=0) 15163 * r3=pkt(id=n,off=0,r=0) 15164 * 15165 * pkt_data in src register: 15166 * 15167 * r2 = r3; 15168 * r2 += 8; 15169 * if (pkt_end >= r2) goto <access okay> 15170 * <handle exception> 15171 * 15172 * r2 = r3; 15173 * r2 += 8; 15174 * if (pkt_end <= r2) goto <handle exception> 15175 * <access okay> 15176 * 15177 * Where: 15178 * pkt_end == dst_reg, r2 == src_reg 15179 * r2=pkt(id=n,off=8,r=0) 15180 * r3=pkt(id=n,off=0,r=0) 15181 * 15182 * Find register r3 and mark its range as r3=pkt(id=n,off=0,r=8) 15183 * or r3=pkt(id=n,off=0,r=8-1), so that range of bytes [r3, r3 + 8) 15184 * and [r3, r3 + 8-1) respectively is safe to access depending on 15185 * the check. 15186 */ 15187 15188 /* If our ids match, then we must have the same max_value. And we 15189 * don't care about the other reg's fixed offset, since if it's too big 15190 * the range won't allow anything. 15191 * reg_umax(dst_reg) is known < MAX_PACKET_OFF, therefore it fits in a u16. 15192 */ 15193 bpf_for_each_reg_in_vstate(vstate, state, reg, ({ 15194 if (reg->type == type && reg->id == dst_reg->id) 15195 /* keep the maximum range already checked */ 15196 reg->range = max(reg->range, new_range); 15197 })); 15198 } 15199 15200 static void regs_refine_cond_op(struct bpf_reg_state *reg1, struct bpf_reg_state *reg2, 15201 u8 opcode, bool is_jmp32); 15202 static u8 rev_opcode(u8 opcode); 15203 15204 /* 15205 * Learn more information about live branches by simulating refinement on both branches. 15206 * regs_refine_cond_op() is sound, so producing ill-formed register bounds for the branch means 15207 * that branch is dead. 15208 */ 15209 static int simulate_both_branches_taken(struct bpf_verifier_env *env, u8 opcode, bool is_jmp32) 15210 { 15211 /* Fallthrough (FALSE) branch */ 15212 regs_refine_cond_op(&env->false_reg1, &env->false_reg2, rev_opcode(opcode), is_jmp32); 15213 reg_bounds_sync(&env->false_reg1); 15214 reg_bounds_sync(&env->false_reg2); 15215 /* 15216 * If there is a range bounds violation in *any* of the abstract values in either 15217 * reg_states in the FALSE branch (i.e. reg1, reg2), the FALSE branch must be dead. Only 15218 * TRUE branch will be taken. 15219 */ 15220 if (range_bounds_violation(&env->false_reg1) || range_bounds_violation(&env->false_reg2)) 15221 return 1; 15222 15223 /* Jump (TRUE) branch */ 15224 regs_refine_cond_op(&env->true_reg1, &env->true_reg2, opcode, is_jmp32); 15225 reg_bounds_sync(&env->true_reg1); 15226 reg_bounds_sync(&env->true_reg2); 15227 /* 15228 * If there is a range bounds violation in *any* of the abstract values in either 15229 * reg_states in the TRUE branch (i.e. true_reg1, true_reg2), the TRUE branch must be dead. 15230 * Only FALSE branch will be taken. 15231 */ 15232 if (range_bounds_violation(&env->true_reg1) || range_bounds_violation(&env->true_reg2)) 15233 return 0; 15234 15235 /* Both branches are possible, we can't determine which one will be taken. */ 15236 return -1; 15237 } 15238 15239 /* 15240 * <reg1> <op> <reg2>, currently assuming reg2 is a constant 15241 */ 15242 static int is_scalar_branch_taken(struct bpf_verifier_env *env, struct bpf_reg_state *reg1, 15243 struct bpf_reg_state *reg2, u8 opcode, bool is_jmp32) 15244 { 15245 struct tnum t1 = is_jmp32 ? tnum_subreg(reg1->var_off) : reg1->var_off; 15246 struct tnum t2 = is_jmp32 ? tnum_subreg(reg2->var_off) : reg2->var_off; 15247 u64 umin1 = is_jmp32 ? (u64)reg_u32_min(reg1) : reg_umin(reg1); 15248 u64 umax1 = is_jmp32 ? (u64)reg_u32_max(reg1) : reg_umax(reg1); 15249 s64 smin1 = is_jmp32 ? (s64)reg_s32_min(reg1) : reg_smin(reg1); 15250 s64 smax1 = is_jmp32 ? (s64)reg_s32_max(reg1) : reg_smax(reg1); 15251 u64 umin2 = is_jmp32 ? (u64)reg_u32_min(reg2) : reg_umin(reg2); 15252 u64 umax2 = is_jmp32 ? (u64)reg_u32_max(reg2) : reg_umax(reg2); 15253 s64 smin2 = is_jmp32 ? (s64)reg_s32_min(reg2) : reg_smin(reg2); 15254 s64 smax2 = is_jmp32 ? (s64)reg_s32_max(reg2) : reg_smax(reg2); 15255 15256 if (reg1 == reg2) { 15257 switch (opcode) { 15258 case BPF_JGE: 15259 case BPF_JLE: 15260 case BPF_JSGE: 15261 case BPF_JSLE: 15262 case BPF_JEQ: 15263 return 1; 15264 case BPF_JGT: 15265 case BPF_JLT: 15266 case BPF_JSGT: 15267 case BPF_JSLT: 15268 case BPF_JNE: 15269 return 0; 15270 case BPF_JSET: 15271 if (tnum_is_const(t1)) 15272 return t1.value != 0; 15273 else 15274 return (smin1 <= 0 && smax1 >= 0) ? -1 : 1; 15275 default: 15276 return -1; 15277 } 15278 } 15279 15280 switch (opcode) { 15281 case BPF_JEQ: 15282 /* constants, umin/umax and smin/smax checks would be 15283 * redundant in this case because they all should match 15284 */ 15285 if (tnum_is_const(t1) && tnum_is_const(t2)) 15286 return t1.value == t2.value; 15287 if (!tnum_overlap(t1, t2)) 15288 return 0; 15289 /* non-overlapping ranges */ 15290 if (umin1 > umax2 || umax1 < umin2) 15291 return 0; 15292 if (smin1 > smax2 || smax1 < smin2) 15293 return 0; 15294 if (!is_jmp32) { 15295 /* if 64-bit ranges are inconclusive, see if we can 15296 * utilize 32-bit subrange knowledge to eliminate 15297 * branches that can't be taken a priori 15298 */ 15299 if (reg_u32_min(reg1) > reg_u32_max(reg2) || 15300 reg_u32_max(reg1) < reg_u32_min(reg2)) 15301 return 0; 15302 if (reg_s32_min(reg1) > reg_s32_max(reg2) || 15303 reg_s32_max(reg1) < reg_s32_min(reg2)) 15304 return 0; 15305 } 15306 break; 15307 case BPF_JNE: 15308 /* constants, umin/umax and smin/smax checks would be 15309 * redundant in this case because they all should match 15310 */ 15311 if (tnum_is_const(t1) && tnum_is_const(t2)) 15312 return t1.value != t2.value; 15313 if (!tnum_overlap(t1, t2)) 15314 return 1; 15315 /* non-overlapping ranges */ 15316 if (umin1 > umax2 || umax1 < umin2) 15317 return 1; 15318 if (smin1 > smax2 || smax1 < smin2) 15319 return 1; 15320 if (!is_jmp32) { 15321 /* if 64-bit ranges are inconclusive, see if we can 15322 * utilize 32-bit subrange knowledge to eliminate 15323 * branches that can't be taken a priori 15324 */ 15325 if (reg_u32_min(reg1) > reg_u32_max(reg2) || 15326 reg_u32_max(reg1) < reg_u32_min(reg2)) 15327 return 1; 15328 if (reg_s32_min(reg1) > reg_s32_max(reg2) || 15329 reg_s32_max(reg1) < reg_s32_min(reg2)) 15330 return 1; 15331 } 15332 break; 15333 case BPF_JSET: 15334 if (!is_reg_const(reg2, is_jmp32)) { 15335 swap(reg1, reg2); 15336 swap(t1, t2); 15337 } 15338 if (!is_reg_const(reg2, is_jmp32)) 15339 return -1; 15340 if ((~t1.mask & t1.value) & t2.value) 15341 return 1; 15342 if (!((t1.mask | t1.value) & t2.value)) 15343 return 0; 15344 break; 15345 case BPF_JGT: 15346 if (umin1 > umax2) 15347 return 1; 15348 else if (umax1 <= umin2) 15349 return 0; 15350 break; 15351 case BPF_JSGT: 15352 if (smin1 > smax2) 15353 return 1; 15354 else if (smax1 <= smin2) 15355 return 0; 15356 break; 15357 case BPF_JLT: 15358 if (umax1 < umin2) 15359 return 1; 15360 else if (umin1 >= umax2) 15361 return 0; 15362 break; 15363 case BPF_JSLT: 15364 if (smax1 < smin2) 15365 return 1; 15366 else if (smin1 >= smax2) 15367 return 0; 15368 break; 15369 case BPF_JGE: 15370 if (umin1 >= umax2) 15371 return 1; 15372 else if (umax1 < umin2) 15373 return 0; 15374 break; 15375 case BPF_JSGE: 15376 if (smin1 >= smax2) 15377 return 1; 15378 else if (smax1 < smin2) 15379 return 0; 15380 break; 15381 case BPF_JLE: 15382 if (umax1 <= umin2) 15383 return 1; 15384 else if (umin1 > umax2) 15385 return 0; 15386 break; 15387 case BPF_JSLE: 15388 if (smax1 <= smin2) 15389 return 1; 15390 else if (smin1 > smax2) 15391 return 0; 15392 break; 15393 } 15394 15395 return simulate_both_branches_taken(env, opcode, is_jmp32); 15396 } 15397 15398 static int flip_opcode(u32 opcode) 15399 { 15400 /* How can we transform "a <op> b" into "b <op> a"? */ 15401 static const u8 opcode_flip[16] = { 15402 /* these stay the same */ 15403 [BPF_JEQ >> 4] = BPF_JEQ, 15404 [BPF_JNE >> 4] = BPF_JNE, 15405 [BPF_JSET >> 4] = BPF_JSET, 15406 /* these swap "lesser" and "greater" (L and G in the opcodes) */ 15407 [BPF_JGE >> 4] = BPF_JLE, 15408 [BPF_JGT >> 4] = BPF_JLT, 15409 [BPF_JLE >> 4] = BPF_JGE, 15410 [BPF_JLT >> 4] = BPF_JGT, 15411 [BPF_JSGE >> 4] = BPF_JSLE, 15412 [BPF_JSGT >> 4] = BPF_JSLT, 15413 [BPF_JSLE >> 4] = BPF_JSGE, 15414 [BPF_JSLT >> 4] = BPF_JSGT 15415 }; 15416 return opcode_flip[opcode >> 4]; 15417 } 15418 15419 static int is_pkt_ptr_branch_taken(struct bpf_reg_state *dst_reg, 15420 struct bpf_reg_state *src_reg, 15421 u8 opcode) 15422 { 15423 struct bpf_reg_state *pkt; 15424 15425 if (src_reg->type == PTR_TO_PACKET_END) { 15426 pkt = dst_reg; 15427 } else if (dst_reg->type == PTR_TO_PACKET_END) { 15428 pkt = src_reg; 15429 opcode = flip_opcode(opcode); 15430 } else { 15431 return -1; 15432 } 15433 15434 if (pkt->range >= 0) 15435 return -1; 15436 15437 switch (opcode) { 15438 case BPF_JLE: 15439 /* pkt <= pkt_end */ 15440 fallthrough; 15441 case BPF_JGT: 15442 /* pkt > pkt_end */ 15443 if (pkt->range == BEYOND_PKT_END) 15444 /* pkt has at last one extra byte beyond pkt_end */ 15445 return opcode == BPF_JGT; 15446 break; 15447 case BPF_JLT: 15448 /* pkt < pkt_end */ 15449 fallthrough; 15450 case BPF_JGE: 15451 /* pkt >= pkt_end */ 15452 if (pkt->range == BEYOND_PKT_END || pkt->range == AT_PKT_END) 15453 return opcode == BPF_JGE; 15454 break; 15455 } 15456 return -1; 15457 } 15458 15459 /* compute branch direction of the expression "if (<reg1> opcode <reg2>) goto target;" 15460 * and return: 15461 * 1 - branch will be taken and "goto target" will be executed 15462 * 0 - branch will not be taken and fall-through to next insn 15463 * -1 - unknown. Example: "if (reg1 < 5)" is unknown when register value 15464 * range [0,10] 15465 */ 15466 static int is_branch_taken(struct bpf_verifier_env *env, struct bpf_reg_state *reg1, 15467 struct bpf_reg_state *reg2, u8 opcode, bool is_jmp32) 15468 { 15469 if (reg_is_pkt_pointer_any(reg1) && reg_is_pkt_pointer_any(reg2) && !is_jmp32) 15470 return is_pkt_ptr_branch_taken(reg1, reg2, opcode); 15471 15472 if (__is_pointer_value(false, reg1) || __is_pointer_value(false, reg2)) { 15473 u64 val; 15474 15475 /* arrange that reg2 is a scalar, and reg1 is a pointer */ 15476 if (!is_reg_const(reg2, is_jmp32)) { 15477 opcode = flip_opcode(opcode); 15478 swap(reg1, reg2); 15479 } 15480 /* and ensure that reg2 is a constant */ 15481 if (!is_reg_const(reg2, is_jmp32)) 15482 return -1; 15483 15484 if (!reg_not_null(reg1)) 15485 return -1; 15486 15487 /* If pointer is valid tests against zero will fail so we can 15488 * use this to direct branch taken. 15489 */ 15490 val = reg_const_value(reg2, is_jmp32); 15491 if (val != 0) 15492 return -1; 15493 15494 switch (opcode) { 15495 case BPF_JEQ: 15496 return 0; 15497 case BPF_JNE: 15498 return 1; 15499 default: 15500 return -1; 15501 } 15502 } 15503 15504 /* now deal with two scalars, but not necessarily constants */ 15505 return is_scalar_branch_taken(env, reg1, reg2, opcode, is_jmp32); 15506 } 15507 15508 /* Opcode that corresponds to a *false* branch condition. 15509 * E.g., if r1 < r2, then reverse (false) condition is r1 >= r2 15510 */ 15511 static u8 rev_opcode(u8 opcode) 15512 { 15513 switch (opcode) { 15514 case BPF_JEQ: return BPF_JNE; 15515 case BPF_JNE: return BPF_JEQ; 15516 /* JSET doesn't have it's reverse opcode in BPF, so add 15517 * BPF_X flag to denote the reverse of that operation 15518 */ 15519 case BPF_JSET: return BPF_JSET | BPF_X; 15520 case BPF_JSET | BPF_X: return BPF_JSET; 15521 case BPF_JGE: return BPF_JLT; 15522 case BPF_JGT: return BPF_JLE; 15523 case BPF_JLE: return BPF_JGT; 15524 case BPF_JLT: return BPF_JGE; 15525 case BPF_JSGE: return BPF_JSLT; 15526 case BPF_JSGT: return BPF_JSLE; 15527 case BPF_JSLE: return BPF_JSGT; 15528 case BPF_JSLT: return BPF_JSGE; 15529 default: return 0; 15530 } 15531 } 15532 15533 /* Refine range knowledge for <reg1> <op> <reg>2 conditional operation. */ 15534 static void regs_refine_cond_op(struct bpf_reg_state *reg1, struct bpf_reg_state *reg2, 15535 u8 opcode, bool is_jmp32) 15536 { 15537 struct tnum t; 15538 u64 val; 15539 15540 /* In case of GE/GT/SGE/JST, reuse LE/LT/SLE/SLT logic from below */ 15541 switch (opcode) { 15542 case BPF_JGE: 15543 case BPF_JGT: 15544 case BPF_JSGE: 15545 case BPF_JSGT: 15546 opcode = flip_opcode(opcode); 15547 swap(reg1, reg2); 15548 break; 15549 default: 15550 break; 15551 } 15552 15553 switch (opcode) { 15554 case BPF_JEQ: 15555 if (is_jmp32) { 15556 reg1->r32 = cnum32_intersect(reg1->r32, reg2->r32); 15557 reg2->r32 = reg1->r32; 15558 15559 t = tnum_intersect(tnum_subreg(reg1->var_off), tnum_subreg(reg2->var_off)); 15560 reg1->var_off = tnum_with_subreg(reg1->var_off, t); 15561 reg2->var_off = tnum_with_subreg(reg2->var_off, t); 15562 } else { 15563 reg1->r64 = cnum64_intersect(reg1->r64, reg2->r64); 15564 reg2->r64 = reg1->r64; 15565 15566 reg1->var_off = tnum_intersect(reg1->var_off, reg2->var_off); 15567 reg2->var_off = reg1->var_off; 15568 } 15569 break; 15570 case BPF_JNE: 15571 if (!is_reg_const(reg2, is_jmp32)) 15572 swap(reg1, reg2); 15573 if (!is_reg_const(reg2, is_jmp32)) 15574 break; 15575 15576 /* try to recompute the bound of reg1 if reg2 is a const and 15577 * is exactly the edge of reg1. 15578 */ 15579 val = reg_const_value(reg2, is_jmp32); 15580 if (is_jmp32) { 15581 /* Complement of the range [val, val] as cnum32. */ 15582 cnum32_intersect_with(®1->r32, (struct cnum32){ val + 1, U32_MAX - 1 }); 15583 } else { 15584 /* Complement of the range [val, val] as cnum64. */ 15585 cnum64_intersect_with(®1->r64, (struct cnum64){ val + 1, U64_MAX - 1 }); 15586 } 15587 break; 15588 case BPF_JSET: 15589 if (!is_reg_const(reg2, is_jmp32)) 15590 swap(reg1, reg2); 15591 if (!is_reg_const(reg2, is_jmp32)) 15592 break; 15593 val = reg_const_value(reg2, is_jmp32); 15594 /* BPF_JSET (i.e., TRUE branch, *not* BPF_JSET | BPF_X) 15595 * requires single bit to learn something useful. E.g., if we 15596 * know that `r1 & 0x3` is true, then which bits (0, 1, or both) 15597 * are actually set? We can learn something definite only if 15598 * it's a single-bit value to begin with. 15599 * 15600 * BPF_JSET | BPF_X (i.e., negation of BPF_JSET) doesn't have 15601 * this restriction. I.e., !(r1 & 0x3) means neither bit 0 nor 15602 * bit 1 is set, which we can readily use in adjustments. 15603 */ 15604 if (!is_power_of_2(val)) 15605 break; 15606 if (is_jmp32) { 15607 t = tnum_or(tnum_subreg(reg1->var_off), tnum_const(val)); 15608 reg1->var_off = tnum_with_subreg(reg1->var_off, t); 15609 } else { 15610 reg1->var_off = tnum_or(reg1->var_off, tnum_const(val)); 15611 } 15612 break; 15613 case BPF_JSET | BPF_X: /* reverse of BPF_JSET, see rev_opcode() */ 15614 if (!is_reg_const(reg2, is_jmp32)) 15615 swap(reg1, reg2); 15616 if (!is_reg_const(reg2, is_jmp32)) 15617 break; 15618 val = reg_const_value(reg2, is_jmp32); 15619 /* Forget the ranges before narrowing tnums, to avoid invariant 15620 * violations if we're on a dead branch. 15621 */ 15622 __mark_reg_unbounded(reg1); 15623 if (is_jmp32) { 15624 t = tnum_and(tnum_subreg(reg1->var_off), tnum_const(~val)); 15625 reg1->var_off = tnum_with_subreg(reg1->var_off, t); 15626 } else { 15627 reg1->var_off = tnum_and(reg1->var_off, tnum_const(~val)); 15628 } 15629 break; 15630 case BPF_JLE: 15631 if (is_jmp32) { 15632 cnum32_intersect_with_urange(®1->r32, 0, reg_u32_max(reg2)); 15633 cnum32_intersect_with_urange(®2->r32, reg_u32_min(reg1), U32_MAX); 15634 } else { 15635 cnum64_intersect_with_urange(®1->r64, 0, reg_umax(reg2)); 15636 cnum64_intersect_with_urange(®2->r64, reg_umin(reg1), U64_MAX); 15637 } 15638 break; 15639 case BPF_JLT: 15640 if (is_jmp32) { 15641 cnum32_intersect_with_urange(®1->r32, 0, reg_u32_max(reg2) - 1); 15642 cnum32_intersect_with_urange(®2->r32, reg_u32_min(reg1) + 1, U32_MAX); 15643 } else { 15644 cnum64_intersect_with_urange(®1->r64, 0, reg_umax(reg2) - 1); 15645 cnum64_intersect_with_urange(®2->r64, reg_umin(reg1) + 1, U64_MAX); 15646 } 15647 break; 15648 case BPF_JSLE: 15649 if (is_jmp32) { 15650 cnum32_intersect_with_srange(®1->r32, S32_MIN, reg_s32_max(reg2)); 15651 cnum32_intersect_with_srange(®2->r32, reg_s32_min(reg1), S32_MAX); 15652 } else { 15653 cnum64_intersect_with_srange(®1->r64, S64_MIN, reg_smax(reg2)); 15654 cnum64_intersect_with_srange(®2->r64, reg_smin(reg1), S64_MAX); 15655 } 15656 break; 15657 case BPF_JSLT: 15658 if (is_jmp32) { 15659 cnum32_intersect_with_srange(®1->r32, S32_MIN, reg_s32_max(reg2) - 1); 15660 cnum32_intersect_with_srange(®2->r32, reg_s32_min(reg1) + 1, S32_MAX); 15661 } else { 15662 cnum64_intersect_with_srange(®1->r64, S64_MIN, reg_smax(reg2) - 1); 15663 cnum64_intersect_with_srange(®2->r64, reg_smin(reg1) + 1, S64_MAX); 15664 } 15665 break; 15666 default: 15667 return; 15668 } 15669 } 15670 15671 /* Check for invariant violations on the registers for both branches of a condition */ 15672 static int regs_bounds_sanity_check_branches(struct bpf_verifier_env *env) 15673 { 15674 int err; 15675 15676 err = reg_bounds_sanity_check(env, &env->true_reg1, "true_reg1"); 15677 err = err ?: reg_bounds_sanity_check(env, &env->true_reg2, "true_reg2"); 15678 err = err ?: reg_bounds_sanity_check(env, &env->false_reg1, "false_reg1"); 15679 err = err ?: reg_bounds_sanity_check(env, &env->false_reg2, "false_reg2"); 15680 return err; 15681 } 15682 15683 static void mark_ptr_or_null_reg(struct bpf_func_state *state, 15684 struct bpf_reg_state *reg, u32 id, 15685 bool is_null) 15686 { 15687 if (type_may_be_null(reg->type) && reg->id == id && 15688 (is_rcu_reg(reg) || !WARN_ON_ONCE(!reg->id))) { 15689 /* Old offset should have been known-zero, because we don't 15690 * allow pointer arithmetic on pointers that might be NULL. 15691 * If we see this happening, don't convert the register. 15692 * 15693 * But in some cases, some helpers that return local kptrs 15694 * advance offset for the returned pointer. In those cases, 15695 * it is fine to expect to see reg->var_off. 15696 */ 15697 if (!(type_is_ptr_alloc_obj(reg->type) || type_is_non_owning_ref(reg->type)) && 15698 WARN_ON_ONCE(!tnum_equals_const(reg->var_off, 0))) 15699 return; 15700 if (is_null) { 15701 /* We don't need id and ref_obj_id from this point 15702 * onwards anymore, thus we should better reset it, 15703 * so that state pruning has chances to take effect. 15704 */ 15705 __mark_reg_known_zero(reg); 15706 reg->type = SCALAR_VALUE; 15707 15708 return; 15709 } 15710 15711 mark_ptr_not_null_reg(reg); 15712 15713 if (!reg_may_point_to_spin_lock(reg)) { 15714 /* For not-NULL ptr, reg->ref_obj_id will be reset 15715 * in release_reference(). 15716 * 15717 * reg->id is still used by spin_lock ptr. Other 15718 * than spin_lock ptr type, reg->id can be reset. 15719 */ 15720 reg->id = 0; 15721 } 15722 } 15723 } 15724 15725 /* The logic is similar to find_good_pkt_pointers(), both could eventually 15726 * be folded together at some point. 15727 */ 15728 static void mark_ptr_or_null_regs(struct bpf_verifier_state *vstate, u32 regno, 15729 bool is_null) 15730 { 15731 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 15732 struct bpf_reg_state *regs = state->regs, *reg; 15733 u32 ref_obj_id = regs[regno].ref_obj_id; 15734 u32 id = regs[regno].id; 15735 15736 if (ref_obj_id && ref_obj_id == id && is_null) 15737 /* regs[regno] is in the " == NULL" branch. 15738 * No one could have freed the reference state before 15739 * doing the NULL check. 15740 */ 15741 WARN_ON_ONCE(release_reference_nomark(vstate, id)); 15742 15743 bpf_for_each_reg_in_vstate(vstate, state, reg, ({ 15744 mark_ptr_or_null_reg(state, reg, id, is_null); 15745 })); 15746 } 15747 15748 static bool try_match_pkt_pointers(const struct bpf_insn *insn, 15749 struct bpf_reg_state *dst_reg, 15750 struct bpf_reg_state *src_reg, 15751 struct bpf_verifier_state *this_branch, 15752 struct bpf_verifier_state *other_branch) 15753 { 15754 if (BPF_SRC(insn->code) != BPF_X) 15755 return false; 15756 15757 /* Pointers are always 64-bit. */ 15758 if (BPF_CLASS(insn->code) == BPF_JMP32) 15759 return false; 15760 15761 switch (BPF_OP(insn->code)) { 15762 case BPF_JGT: 15763 if ((dst_reg->type == PTR_TO_PACKET && 15764 src_reg->type == PTR_TO_PACKET_END) || 15765 (dst_reg->type == PTR_TO_PACKET_META && 15766 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) { 15767 /* pkt_data' > pkt_end, pkt_meta' > pkt_data */ 15768 find_good_pkt_pointers(this_branch, dst_reg, 15769 dst_reg->type, false); 15770 mark_pkt_end(other_branch, insn->dst_reg, true); 15771 } else if ((dst_reg->type == PTR_TO_PACKET_END && 15772 src_reg->type == PTR_TO_PACKET) || 15773 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) && 15774 src_reg->type == PTR_TO_PACKET_META)) { 15775 /* pkt_end > pkt_data', pkt_data > pkt_meta' */ 15776 find_good_pkt_pointers(other_branch, src_reg, 15777 src_reg->type, true); 15778 mark_pkt_end(this_branch, insn->src_reg, false); 15779 } else { 15780 return false; 15781 } 15782 break; 15783 case BPF_JLT: 15784 if ((dst_reg->type == PTR_TO_PACKET && 15785 src_reg->type == PTR_TO_PACKET_END) || 15786 (dst_reg->type == PTR_TO_PACKET_META && 15787 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) { 15788 /* pkt_data' < pkt_end, pkt_meta' < pkt_data */ 15789 find_good_pkt_pointers(other_branch, dst_reg, 15790 dst_reg->type, true); 15791 mark_pkt_end(this_branch, insn->dst_reg, false); 15792 } else if ((dst_reg->type == PTR_TO_PACKET_END && 15793 src_reg->type == PTR_TO_PACKET) || 15794 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) && 15795 src_reg->type == PTR_TO_PACKET_META)) { 15796 /* pkt_end < pkt_data', pkt_data > pkt_meta' */ 15797 find_good_pkt_pointers(this_branch, src_reg, 15798 src_reg->type, false); 15799 mark_pkt_end(other_branch, insn->src_reg, true); 15800 } else { 15801 return false; 15802 } 15803 break; 15804 case BPF_JGE: 15805 if ((dst_reg->type == PTR_TO_PACKET && 15806 src_reg->type == PTR_TO_PACKET_END) || 15807 (dst_reg->type == PTR_TO_PACKET_META && 15808 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) { 15809 /* pkt_data' >= pkt_end, pkt_meta' >= pkt_data */ 15810 find_good_pkt_pointers(this_branch, dst_reg, 15811 dst_reg->type, true); 15812 mark_pkt_end(other_branch, insn->dst_reg, false); 15813 } else if ((dst_reg->type == PTR_TO_PACKET_END && 15814 src_reg->type == PTR_TO_PACKET) || 15815 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) && 15816 src_reg->type == PTR_TO_PACKET_META)) { 15817 /* pkt_end >= pkt_data', pkt_data >= pkt_meta' */ 15818 find_good_pkt_pointers(other_branch, src_reg, 15819 src_reg->type, false); 15820 mark_pkt_end(this_branch, insn->src_reg, true); 15821 } else { 15822 return false; 15823 } 15824 break; 15825 case BPF_JLE: 15826 if ((dst_reg->type == PTR_TO_PACKET && 15827 src_reg->type == PTR_TO_PACKET_END) || 15828 (dst_reg->type == PTR_TO_PACKET_META && 15829 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) { 15830 /* pkt_data' <= pkt_end, pkt_meta' <= pkt_data */ 15831 find_good_pkt_pointers(other_branch, dst_reg, 15832 dst_reg->type, false); 15833 mark_pkt_end(this_branch, insn->dst_reg, true); 15834 } else if ((dst_reg->type == PTR_TO_PACKET_END && 15835 src_reg->type == PTR_TO_PACKET) || 15836 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) && 15837 src_reg->type == PTR_TO_PACKET_META)) { 15838 /* pkt_end <= pkt_data', pkt_data <= pkt_meta' */ 15839 find_good_pkt_pointers(this_branch, src_reg, 15840 src_reg->type, true); 15841 mark_pkt_end(other_branch, insn->src_reg, false); 15842 } else { 15843 return false; 15844 } 15845 break; 15846 default: 15847 return false; 15848 } 15849 15850 return true; 15851 } 15852 15853 static void __collect_linked_regs(struct linked_regs *reg_set, struct bpf_reg_state *reg, 15854 u32 id, u32 frameno, u32 spi_or_reg, bool is_reg) 15855 { 15856 struct linked_reg *e; 15857 15858 if (reg->type != SCALAR_VALUE || (reg->id & ~BPF_ADD_CONST) != id) 15859 return; 15860 15861 e = linked_regs_push(reg_set); 15862 if (e) { 15863 e->frameno = frameno; 15864 e->is_reg = is_reg; 15865 e->regno = spi_or_reg; 15866 } else { 15867 clear_scalar_id(reg); 15868 } 15869 } 15870 15871 /* For all R being scalar registers or spilled scalar registers 15872 * in verifier state, save R in linked_regs if R->id == id. 15873 * If there are too many Rs sharing same id, reset id for leftover Rs. 15874 */ 15875 static void collect_linked_regs(struct bpf_verifier_env *env, 15876 struct bpf_verifier_state *vstate, 15877 u32 id, 15878 struct linked_regs *linked_regs) 15879 { 15880 struct bpf_insn_aux_data *aux = env->insn_aux_data; 15881 struct bpf_func_state *func; 15882 struct bpf_reg_state *reg; 15883 u16 live_regs; 15884 int i, j; 15885 15886 id = id & ~BPF_ADD_CONST; 15887 for (i = vstate->curframe; i >= 0; i--) { 15888 live_regs = aux[bpf_frame_insn_idx(vstate, i)].live_regs_before; 15889 func = vstate->frame[i]; 15890 for (j = 0; j < BPF_REG_FP; j++) { 15891 if (!(live_regs & BIT(j))) 15892 continue; 15893 reg = &func->regs[j]; 15894 __collect_linked_regs(linked_regs, reg, id, i, j, true); 15895 } 15896 for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) { 15897 if (!bpf_is_spilled_reg(&func->stack[j])) 15898 continue; 15899 reg = &func->stack[j].spilled_ptr; 15900 __collect_linked_regs(linked_regs, reg, id, i, j, false); 15901 } 15902 } 15903 } 15904 15905 /* For all R in linked_regs, copy known_reg range into R 15906 * if R->id == known_reg->id. 15907 */ 15908 static void sync_linked_regs(struct bpf_verifier_env *env, struct bpf_verifier_state *vstate, 15909 struct bpf_reg_state *known_reg, struct linked_regs *linked_regs) 15910 { 15911 struct bpf_reg_state fake_reg; 15912 struct bpf_reg_state *reg; 15913 struct linked_reg *e; 15914 int i; 15915 15916 for (i = 0; i < linked_regs->cnt; ++i) { 15917 e = &linked_regs->entries[i]; 15918 reg = e->is_reg ? &vstate->frame[e->frameno]->regs[e->regno] 15919 : &vstate->frame[e->frameno]->stack[e->spi].spilled_ptr; 15920 if (reg->type != SCALAR_VALUE || reg == known_reg) 15921 continue; 15922 if ((reg->id & ~BPF_ADD_CONST) != (known_reg->id & ~BPF_ADD_CONST)) 15923 continue; 15924 /* 15925 * Skip mixed 32/64-bit links: the delta relationship doesn't 15926 * hold across different ALU widths. 15927 */ 15928 if (((reg->id ^ known_reg->id) & BPF_ADD_CONST) == BPF_ADD_CONST) 15929 continue; 15930 if ((!(reg->id & BPF_ADD_CONST) && !(known_reg->id & BPF_ADD_CONST)) || 15931 reg->delta == known_reg->delta) { 15932 s32 saved_subreg_def = reg->subreg_def; 15933 15934 *reg = *known_reg; 15935 reg->subreg_def = saved_subreg_def; 15936 } else { 15937 s32 saved_subreg_def = reg->subreg_def; 15938 s32 saved_off = reg->delta; 15939 u32 saved_id = reg->id; 15940 15941 fake_reg.type = SCALAR_VALUE; 15942 __mark_reg_known(&fake_reg, (s64)reg->delta - (s64)known_reg->delta); 15943 15944 /* reg = known_reg; reg += delta */ 15945 *reg = *known_reg; 15946 /* 15947 * Must preserve off, id and subreg_def flag, 15948 * otherwise another sync_linked_regs() will be incorrect. 15949 */ 15950 reg->delta = saved_off; 15951 reg->id = saved_id; 15952 reg->subreg_def = saved_subreg_def; 15953 15954 scalar32_min_max_add(reg, &fake_reg); 15955 scalar_min_max_add(reg, &fake_reg); 15956 reg->var_off = tnum_add(reg->var_off, fake_reg.var_off); 15957 if ((reg->id | known_reg->id) & BPF_ADD_CONST32) 15958 zext_32_to_64(reg); 15959 reg_bounds_sync(reg); 15960 } 15961 if (e->is_reg) 15962 mark_reg_scratched(env, e->regno); 15963 else 15964 mark_stack_slot_scratched(env, e->spi); 15965 } 15966 } 15967 15968 static int check_cond_jmp_op(struct bpf_verifier_env *env, 15969 struct bpf_insn *insn, int *insn_idx) 15970 { 15971 struct bpf_verifier_state *this_branch = env->cur_state; 15972 struct bpf_verifier_state *other_branch; 15973 struct bpf_reg_state *regs = this_branch->frame[this_branch->curframe]->regs; 15974 struct bpf_reg_state *dst_reg, *other_branch_regs, *src_reg = NULL; 15975 struct bpf_reg_state *eq_branch_regs; 15976 struct linked_regs linked_regs = {}; 15977 u8 opcode = BPF_OP(insn->code); 15978 int insn_flags = 0; 15979 bool is_jmp32; 15980 int pred = -1; 15981 int err; 15982 15983 /* Only conditional jumps are expected to reach here. */ 15984 if (opcode == BPF_JA || opcode > BPF_JCOND) { 15985 verbose(env, "invalid BPF_JMP/JMP32 opcode %x\n", opcode); 15986 return -EINVAL; 15987 } 15988 15989 if (opcode == BPF_JCOND) { 15990 struct bpf_verifier_state *cur_st = env->cur_state, *queued_st, *prev_st; 15991 int idx = *insn_idx; 15992 15993 prev_st = find_prev_entry(env, cur_st->parent, idx); 15994 15995 /* branch out 'fallthrough' insn as a new state to explore */ 15996 queued_st = push_stack(env, idx + 1, idx, false); 15997 if (IS_ERR(queued_st)) 15998 return PTR_ERR(queued_st); 15999 16000 queued_st->may_goto_depth++; 16001 if (prev_st) 16002 widen_imprecise_scalars(env, prev_st, queued_st); 16003 *insn_idx += insn->off; 16004 return 0; 16005 } 16006 16007 /* check src2 operand */ 16008 err = check_reg_arg(env, insn->dst_reg, SRC_OP); 16009 if (err) 16010 return err; 16011 16012 dst_reg = ®s[insn->dst_reg]; 16013 if (BPF_SRC(insn->code) == BPF_X) { 16014 /* check src1 operand */ 16015 err = check_reg_arg(env, insn->src_reg, SRC_OP); 16016 if (err) 16017 return err; 16018 16019 src_reg = ®s[insn->src_reg]; 16020 if (!(reg_is_pkt_pointer_any(dst_reg) && reg_is_pkt_pointer_any(src_reg)) && 16021 is_pointer_value(env, insn->src_reg)) { 16022 verbose(env, "R%d pointer comparison prohibited\n", 16023 insn->src_reg); 16024 return -EACCES; 16025 } 16026 16027 if (src_reg->type == PTR_TO_STACK) 16028 insn_flags |= INSN_F_SRC_REG_STACK; 16029 if (dst_reg->type == PTR_TO_STACK) 16030 insn_flags |= INSN_F_DST_REG_STACK; 16031 } else { 16032 src_reg = &env->fake_reg[0]; 16033 memset(src_reg, 0, sizeof(*src_reg)); 16034 src_reg->type = SCALAR_VALUE; 16035 __mark_reg_known(src_reg, insn->imm); 16036 16037 if (dst_reg->type == PTR_TO_STACK) 16038 insn_flags |= INSN_F_DST_REG_STACK; 16039 } 16040 16041 if (insn_flags) { 16042 err = bpf_push_jmp_history(env, this_branch, insn_flags, 0, 0, 0); 16043 if (err) 16044 return err; 16045 } 16046 16047 is_jmp32 = BPF_CLASS(insn->code) == BPF_JMP32; 16048 env->false_reg1 = *dst_reg; 16049 env->false_reg2 = *src_reg; 16050 env->true_reg1 = *dst_reg; 16051 env->true_reg2 = *src_reg; 16052 pred = is_branch_taken(env, dst_reg, src_reg, opcode, is_jmp32); 16053 if (pred >= 0) { 16054 /* If we get here with a dst_reg pointer type it is because 16055 * above is_branch_taken() special cased the 0 comparison. 16056 */ 16057 if (!__is_pointer_value(false, dst_reg)) 16058 err = mark_chain_precision(env, insn->dst_reg); 16059 if (BPF_SRC(insn->code) == BPF_X && !err && 16060 !__is_pointer_value(false, src_reg)) 16061 err = mark_chain_precision(env, insn->src_reg); 16062 if (err) 16063 return err; 16064 } 16065 16066 if (pred == 1) { 16067 /* Only follow the goto, ignore fall-through. If needed, push 16068 * the fall-through branch for simulation under speculative 16069 * execution. 16070 */ 16071 if (!env->bypass_spec_v1) { 16072 err = sanitize_speculative_path(env, insn, *insn_idx + 1, *insn_idx); 16073 if (err < 0) 16074 return err; 16075 } 16076 if (env->log.level & BPF_LOG_LEVEL) 16077 print_insn_state(env, this_branch, this_branch->curframe); 16078 *insn_idx += insn->off; 16079 return 0; 16080 } else if (pred == 0) { 16081 /* Only follow the fall-through branch, since that's where the 16082 * program will go. If needed, push the goto branch for 16083 * simulation under speculative execution. 16084 */ 16085 if (!env->bypass_spec_v1) { 16086 err = sanitize_speculative_path(env, insn, *insn_idx + insn->off + 1, 16087 *insn_idx); 16088 if (err < 0) 16089 return err; 16090 } 16091 if (env->log.level & BPF_LOG_LEVEL) 16092 print_insn_state(env, this_branch, this_branch->curframe); 16093 return 0; 16094 } 16095 16096 /* Push scalar registers sharing same ID to jump history, 16097 * do this before creating 'other_branch', so that both 16098 * 'this_branch' and 'other_branch' share this history 16099 * if parent state is created. 16100 */ 16101 if (BPF_SRC(insn->code) == BPF_X && src_reg->type == SCALAR_VALUE && src_reg->id) 16102 collect_linked_regs(env, this_branch, src_reg->id, &linked_regs); 16103 if (dst_reg->type == SCALAR_VALUE && dst_reg->id) 16104 collect_linked_regs(env, this_branch, dst_reg->id, &linked_regs); 16105 if (linked_regs.cnt > 1) { 16106 err = bpf_push_jmp_history(env, this_branch, 0, 0, 0, linked_regs_pack(&linked_regs)); 16107 if (err) 16108 return err; 16109 } 16110 16111 other_branch = push_stack(env, *insn_idx + insn->off + 1, *insn_idx, false); 16112 if (IS_ERR(other_branch)) 16113 return PTR_ERR(other_branch); 16114 other_branch_regs = other_branch->frame[other_branch->curframe]->regs; 16115 16116 err = regs_bounds_sanity_check_branches(env); 16117 if (err) 16118 return err; 16119 16120 *dst_reg = env->false_reg1; 16121 *src_reg = env->false_reg2; 16122 other_branch_regs[insn->dst_reg] = env->true_reg1; 16123 if (BPF_SRC(insn->code) == BPF_X) 16124 other_branch_regs[insn->src_reg] = env->true_reg2; 16125 16126 if (BPF_SRC(insn->code) == BPF_X && 16127 src_reg->type == SCALAR_VALUE && src_reg->id && 16128 !WARN_ON_ONCE(src_reg->id != other_branch_regs[insn->src_reg].id)) { 16129 sync_linked_regs(env, this_branch, src_reg, &linked_regs); 16130 sync_linked_regs(env, other_branch, &other_branch_regs[insn->src_reg], 16131 &linked_regs); 16132 } 16133 if (dst_reg->type == SCALAR_VALUE && dst_reg->id && 16134 !WARN_ON_ONCE(dst_reg->id != other_branch_regs[insn->dst_reg].id)) { 16135 sync_linked_regs(env, this_branch, dst_reg, &linked_regs); 16136 sync_linked_regs(env, other_branch, &other_branch_regs[insn->dst_reg], 16137 &linked_regs); 16138 } 16139 16140 /* if one pointer register is compared to another pointer 16141 * register check if PTR_MAYBE_NULL could be lifted. 16142 * E.g. register A - maybe null 16143 * register B - not null 16144 * for JNE A, B, ... - A is not null in the false branch; 16145 * for JEQ A, B, ... - A is not null in the true branch. 16146 * 16147 * Since PTR_TO_BTF_ID points to a kernel struct that does 16148 * not need to be null checked by the BPF program, i.e., 16149 * could be null even without PTR_MAYBE_NULL marking, so 16150 * only propagate nullness when neither reg is that type. 16151 */ 16152 if (!is_jmp32 && BPF_SRC(insn->code) == BPF_X && 16153 __is_pointer_value(false, src_reg) && __is_pointer_value(false, dst_reg) && 16154 type_may_be_null(src_reg->type) != type_may_be_null(dst_reg->type) && 16155 base_type(src_reg->type) != PTR_TO_BTF_ID && 16156 base_type(dst_reg->type) != PTR_TO_BTF_ID) { 16157 eq_branch_regs = NULL; 16158 switch (opcode) { 16159 case BPF_JEQ: 16160 eq_branch_regs = other_branch_regs; 16161 break; 16162 case BPF_JNE: 16163 eq_branch_regs = regs; 16164 break; 16165 default: 16166 /* do nothing */ 16167 break; 16168 } 16169 if (eq_branch_regs) { 16170 if (type_may_be_null(src_reg->type)) 16171 mark_ptr_not_null_reg(&eq_branch_regs[insn->src_reg]); 16172 else 16173 mark_ptr_not_null_reg(&eq_branch_regs[insn->dst_reg]); 16174 } 16175 } 16176 16177 /* detect if R == 0 where R is returned from bpf_map_lookup_elem(). 16178 * Also does the same detection for a register whose the value is 16179 * known to be 0. 16180 * NOTE: these optimizations below are related with pointer comparison 16181 * which will never be JMP32. 16182 */ 16183 if (!is_jmp32 && (opcode == BPF_JEQ || opcode == BPF_JNE) && 16184 type_may_be_null(dst_reg->type) && 16185 ((BPF_SRC(insn->code) == BPF_K && insn->imm == 0) || 16186 (BPF_SRC(insn->code) == BPF_X && bpf_register_is_null(src_reg)))) { 16187 /* Mark all identical registers in each branch as either 16188 * safe or unknown depending R == 0 or R != 0 conditional. 16189 */ 16190 mark_ptr_or_null_regs(this_branch, insn->dst_reg, 16191 opcode == BPF_JNE); 16192 mark_ptr_or_null_regs(other_branch, insn->dst_reg, 16193 opcode == BPF_JEQ); 16194 } else if (!try_match_pkt_pointers(insn, dst_reg, ®s[insn->src_reg], 16195 this_branch, other_branch) && 16196 is_pointer_value(env, insn->dst_reg)) { 16197 verbose(env, "R%d pointer comparison prohibited\n", 16198 insn->dst_reg); 16199 return -EACCES; 16200 } 16201 if (env->log.level & BPF_LOG_LEVEL) 16202 print_insn_state(env, this_branch, this_branch->curframe); 16203 return 0; 16204 } 16205 16206 /* verify BPF_LD_IMM64 instruction */ 16207 static int check_ld_imm(struct bpf_verifier_env *env, struct bpf_insn *insn) 16208 { 16209 struct bpf_insn_aux_data *aux = cur_aux(env); 16210 struct bpf_reg_state *regs = cur_regs(env); 16211 struct bpf_reg_state *dst_reg; 16212 struct bpf_map *map; 16213 int err; 16214 16215 if (BPF_SIZE(insn->code) != BPF_DW) { 16216 verbose(env, "invalid BPF_LD_IMM insn\n"); 16217 return -EINVAL; 16218 } 16219 16220 err = check_reg_arg(env, insn->dst_reg, DST_OP); 16221 if (err) 16222 return err; 16223 16224 dst_reg = ®s[insn->dst_reg]; 16225 if (insn->src_reg == 0) { 16226 u64 imm = ((u64)(insn + 1)->imm << 32) | (u32)insn->imm; 16227 16228 dst_reg->type = SCALAR_VALUE; 16229 __mark_reg_known(®s[insn->dst_reg], imm); 16230 return 0; 16231 } 16232 16233 /* All special src_reg cases are listed below. From this point onwards 16234 * we either succeed and assign a corresponding dst_reg->type after 16235 * zeroing the offset, or fail and reject the program. 16236 */ 16237 mark_reg_known_zero(env, regs, insn->dst_reg); 16238 16239 if (insn->src_reg == BPF_PSEUDO_BTF_ID) { 16240 dst_reg->type = aux->btf_var.reg_type; 16241 switch (base_type(dst_reg->type)) { 16242 case PTR_TO_MEM: 16243 dst_reg->mem_size = aux->btf_var.mem_size; 16244 break; 16245 case PTR_TO_BTF_ID: 16246 dst_reg->btf = aux->btf_var.btf; 16247 dst_reg->btf_id = aux->btf_var.btf_id; 16248 break; 16249 default: 16250 verifier_bug(env, "pseudo btf id: unexpected dst reg type"); 16251 return -EFAULT; 16252 } 16253 return 0; 16254 } 16255 16256 if (insn->src_reg == BPF_PSEUDO_FUNC) { 16257 struct bpf_prog_aux *aux = env->prog->aux; 16258 u32 subprogno = bpf_find_subprog(env, 16259 env->insn_idx + insn->imm + 1); 16260 16261 if (!aux->func_info) { 16262 verbose(env, "missing btf func_info\n"); 16263 return -EINVAL; 16264 } 16265 if (aux->func_info_aux[subprogno].linkage != BTF_FUNC_STATIC) { 16266 verbose(env, "callback function not static\n"); 16267 return -EINVAL; 16268 } 16269 16270 dst_reg->type = PTR_TO_FUNC; 16271 dst_reg->subprogno = subprogno; 16272 return 0; 16273 } 16274 16275 map = env->used_maps[aux->map_index]; 16276 16277 if (insn->src_reg == BPF_PSEUDO_MAP_VALUE || 16278 insn->src_reg == BPF_PSEUDO_MAP_IDX_VALUE) { 16279 if (map->map_type == BPF_MAP_TYPE_ARENA) { 16280 __mark_reg_unknown(env, dst_reg); 16281 dst_reg->map_ptr = map; 16282 return 0; 16283 } 16284 __mark_reg_known(dst_reg, aux->map_off); 16285 dst_reg->type = PTR_TO_MAP_VALUE; 16286 dst_reg->map_ptr = map; 16287 WARN_ON_ONCE(map->map_type != BPF_MAP_TYPE_INSN_ARRAY && 16288 map->max_entries != 1); 16289 /* We want reg->id to be same (0) as map_value is not distinct */ 16290 } else if (insn->src_reg == BPF_PSEUDO_MAP_FD || 16291 insn->src_reg == BPF_PSEUDO_MAP_IDX) { 16292 dst_reg->type = CONST_PTR_TO_MAP; 16293 dst_reg->map_ptr = map; 16294 } else { 16295 verifier_bug(env, "unexpected src reg value for ldimm64"); 16296 return -EFAULT; 16297 } 16298 16299 return 0; 16300 } 16301 16302 static bool may_access_skb(enum bpf_prog_type type) 16303 { 16304 switch (type) { 16305 case BPF_PROG_TYPE_SOCKET_FILTER: 16306 case BPF_PROG_TYPE_SCHED_CLS: 16307 case BPF_PROG_TYPE_SCHED_ACT: 16308 return true; 16309 default: 16310 return false; 16311 } 16312 } 16313 16314 /* verify safety of LD_ABS|LD_IND instructions: 16315 * - they can only appear in the programs where ctx == skb 16316 * - since they are wrappers of function calls, they scratch R1-R5 registers, 16317 * preserve R6-R9, and store return value into R0 16318 * 16319 * Implicit input: 16320 * ctx == skb == R6 == CTX 16321 * 16322 * Explicit input: 16323 * SRC == any register 16324 * IMM == 32-bit immediate 16325 * 16326 * Output: 16327 * R0 - 8/16/32-bit skb data converted to cpu endianness 16328 */ 16329 static int check_ld_abs(struct bpf_verifier_env *env, struct bpf_insn *insn) 16330 { 16331 struct bpf_reg_state *regs = cur_regs(env); 16332 static const int ctx_reg = BPF_REG_6; 16333 u8 mode = BPF_MODE(insn->code); 16334 int i, err; 16335 16336 if (!may_access_skb(resolve_prog_type(env->prog))) { 16337 verbose(env, "BPF_LD_[ABS|IND] instructions not allowed for this program type\n"); 16338 return -EINVAL; 16339 } 16340 16341 if (!env->ops->gen_ld_abs) { 16342 verifier_bug(env, "gen_ld_abs is null"); 16343 return -EFAULT; 16344 } 16345 16346 /* check whether implicit source operand (register R6) is readable */ 16347 err = check_reg_arg(env, ctx_reg, SRC_OP); 16348 if (err) 16349 return err; 16350 16351 /* Disallow usage of BPF_LD_[ABS|IND] with reference tracking, as 16352 * gen_ld_abs() may terminate the program at runtime, leading to 16353 * reference leak. 16354 */ 16355 err = check_resource_leak(env, false, true, "BPF_LD_[ABS|IND]"); 16356 if (err) 16357 return err; 16358 16359 if (regs[ctx_reg].type != PTR_TO_CTX) { 16360 verbose(env, 16361 "at the time of BPF_LD_ABS|IND R6 != pointer to skb\n"); 16362 return -EINVAL; 16363 } 16364 16365 if (mode == BPF_IND) { 16366 /* check explicit source operand */ 16367 err = check_reg_arg(env, insn->src_reg, SRC_OP); 16368 if (err) 16369 return err; 16370 } 16371 16372 err = check_ptr_off_reg(env, ®s[ctx_reg], ctx_reg); 16373 if (err < 0) 16374 return err; 16375 16376 /* reset caller saved regs to unreadable */ 16377 for (i = 0; i < CALLER_SAVED_REGS; i++) { 16378 bpf_mark_reg_not_init(env, ®s[caller_saved[i]]); 16379 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK); 16380 } 16381 16382 /* mark destination R0 register as readable, since it contains 16383 * the value fetched from the packet. 16384 * Already marked as written above. 16385 */ 16386 mark_reg_unknown(env, regs, BPF_REG_0); 16387 /* ld_abs load up to 32-bit skb data. */ 16388 regs[BPF_REG_0].subreg_def = env->insn_idx + 1; 16389 /* 16390 * See bpf_gen_ld_abs() which emits a hidden BPF_EXIT with r0=0 16391 * which must be explored by the verifier when in a subprog. 16392 */ 16393 if (env->cur_state->curframe) { 16394 struct bpf_verifier_state *branch; 16395 16396 mark_reg_scratched(env, BPF_REG_0); 16397 branch = push_stack(env, env->insn_idx + 1, env->insn_idx, false); 16398 if (IS_ERR(branch)) 16399 return PTR_ERR(branch); 16400 mark_reg_known_zero(env, regs, BPF_REG_0); 16401 err = prepare_func_exit(env, &env->insn_idx); 16402 if (err) 16403 return err; 16404 env->insn_idx--; 16405 } 16406 return 0; 16407 } 16408 16409 16410 static bool return_retval_range(struct bpf_verifier_env *env, struct bpf_retval_range *range) 16411 { 16412 enum bpf_prog_type prog_type = resolve_prog_type(env->prog); 16413 16414 /* Default return value range. */ 16415 *range = retval_range(0, 1); 16416 16417 switch (prog_type) { 16418 case BPF_PROG_TYPE_CGROUP_SOCK_ADDR: 16419 switch (env->prog->expected_attach_type) { 16420 case BPF_CGROUP_UDP4_RECVMSG: 16421 case BPF_CGROUP_UDP6_RECVMSG: 16422 case BPF_CGROUP_UNIX_RECVMSG: 16423 case BPF_CGROUP_INET4_GETPEERNAME: 16424 case BPF_CGROUP_INET6_GETPEERNAME: 16425 case BPF_CGROUP_UNIX_GETPEERNAME: 16426 case BPF_CGROUP_INET4_GETSOCKNAME: 16427 case BPF_CGROUP_INET6_GETSOCKNAME: 16428 case BPF_CGROUP_UNIX_GETSOCKNAME: 16429 *range = retval_range(1, 1); 16430 break; 16431 case BPF_CGROUP_INET4_BIND: 16432 case BPF_CGROUP_INET6_BIND: 16433 *range = retval_range(0, 3); 16434 break; 16435 default: 16436 break; 16437 } 16438 break; 16439 case BPF_PROG_TYPE_CGROUP_SKB: 16440 if (env->prog->expected_attach_type == BPF_CGROUP_INET_EGRESS) 16441 *range = retval_range(0, 3); 16442 break; 16443 case BPF_PROG_TYPE_CGROUP_SOCK: 16444 case BPF_PROG_TYPE_SOCK_OPS: 16445 case BPF_PROG_TYPE_CGROUP_DEVICE: 16446 case BPF_PROG_TYPE_CGROUP_SYSCTL: 16447 case BPF_PROG_TYPE_CGROUP_SOCKOPT: 16448 break; 16449 case BPF_PROG_TYPE_RAW_TRACEPOINT: 16450 if (!env->prog->aux->attach_btf_id) 16451 return false; 16452 *range = retval_range(0, 0); 16453 break; 16454 case BPF_PROG_TYPE_TRACING: 16455 switch (env->prog->expected_attach_type) { 16456 case BPF_TRACE_FENTRY: 16457 case BPF_TRACE_FEXIT: 16458 case BPF_TRACE_FSESSION: 16459 *range = retval_range(0, 0); 16460 break; 16461 case BPF_TRACE_RAW_TP: 16462 case BPF_MODIFY_RETURN: 16463 return false; 16464 case BPF_TRACE_ITER: 16465 default: 16466 break; 16467 } 16468 break; 16469 case BPF_PROG_TYPE_KPROBE: 16470 switch (env->prog->expected_attach_type) { 16471 case BPF_TRACE_KPROBE_SESSION: 16472 case BPF_TRACE_UPROBE_SESSION: 16473 break; 16474 default: 16475 return false; 16476 } 16477 break; 16478 case BPF_PROG_TYPE_SK_LOOKUP: 16479 *range = retval_range(SK_DROP, SK_PASS); 16480 break; 16481 16482 case BPF_PROG_TYPE_LSM: 16483 if (env->prog->expected_attach_type != BPF_LSM_CGROUP) { 16484 /* no range found, any return value is allowed */ 16485 if (!get_func_retval_range(env->prog, range)) 16486 return false; 16487 /* no restricted range, any return value is allowed */ 16488 if (range->minval == S32_MIN && range->maxval == S32_MAX) 16489 return false; 16490 range->return_32bit = true; 16491 } else if (!env->prog->aux->attach_func_proto->type) { 16492 /* Make sure programs that attach to void 16493 * hooks don't try to modify return value. 16494 */ 16495 *range = retval_range(1, 1); 16496 } 16497 break; 16498 16499 case BPF_PROG_TYPE_NETFILTER: 16500 *range = retval_range(NF_DROP, NF_ACCEPT); 16501 break; 16502 case BPF_PROG_TYPE_STRUCT_OPS: 16503 *range = retval_range(0, 0); 16504 break; 16505 case BPF_PROG_TYPE_EXT: 16506 /* freplace program can return anything as its return value 16507 * depends on the to-be-replaced kernel func or bpf program. 16508 */ 16509 default: 16510 return false; 16511 } 16512 16513 /* Continue calculating. */ 16514 16515 return true; 16516 } 16517 16518 static bool program_returns_void(struct bpf_verifier_env *env) 16519 { 16520 const struct bpf_prog *prog = env->prog; 16521 enum bpf_prog_type prog_type = prog->type; 16522 16523 switch (prog_type) { 16524 case BPF_PROG_TYPE_LSM: 16525 /* See return_retval_range, for BPF_LSM_CGROUP can be 0 or 0-1 depending on hook. */ 16526 if (prog->expected_attach_type != BPF_LSM_CGROUP && 16527 !prog->aux->attach_func_proto->type) 16528 return true; 16529 break; 16530 case BPF_PROG_TYPE_STRUCT_OPS: 16531 if (!prog->aux->attach_func_proto->type) 16532 return true; 16533 break; 16534 case BPF_PROG_TYPE_EXT: 16535 /* 16536 * If the actual program is an extension, let it 16537 * return void - attaching will succeed only if the 16538 * program being replaced also returns void, and since 16539 * it has passed verification its actual type doesn't matter. 16540 */ 16541 if (subprog_returns_void(env, 0)) 16542 return true; 16543 break; 16544 default: 16545 break; 16546 } 16547 return false; 16548 } 16549 16550 static int check_return_code(struct bpf_verifier_env *env, int regno, const char *reg_name) 16551 { 16552 const char *exit_ctx = "At program exit"; 16553 struct tnum enforce_attach_type_range = tnum_unknown; 16554 const struct bpf_prog *prog = env->prog; 16555 struct bpf_reg_state *reg = reg_state(env, regno); 16556 struct bpf_retval_range range = retval_range(0, 1); 16557 enum bpf_prog_type prog_type = resolve_prog_type(env->prog); 16558 struct bpf_func_state *frame = env->cur_state->frame[0]; 16559 const struct btf_type *reg_type, *ret_type = NULL; 16560 int err; 16561 16562 /* LSM and struct_ops func-ptr's return type could be "void" */ 16563 if (!frame->in_async_callback_fn && program_returns_void(env)) 16564 return 0; 16565 16566 if (prog_type == BPF_PROG_TYPE_STRUCT_OPS) { 16567 /* Allow a struct_ops program to return a referenced kptr if it 16568 * matches the operator's return type and is in its unmodified 16569 * form. A scalar zero (i.e., a null pointer) is also allowed. 16570 */ 16571 reg_type = reg->btf ? btf_type_by_id(reg->btf, reg->btf_id) : NULL; 16572 ret_type = btf_type_resolve_ptr(prog->aux->attach_btf, 16573 prog->aux->attach_func_proto->type, 16574 NULL); 16575 if (ret_type && ret_type == reg_type && reg->ref_obj_id) 16576 return __check_ptr_off_reg(env, reg, argno_from_reg(regno), false); 16577 } 16578 16579 /* eBPF calling convention is such that R0 is used 16580 * to return the value from eBPF program. 16581 * Make sure that it's readable at this time 16582 * of bpf_exit, which means that program wrote 16583 * something into it earlier 16584 */ 16585 err = check_reg_arg(env, regno, SRC_OP); 16586 if (err) 16587 return err; 16588 16589 if (is_pointer_value(env, regno)) { 16590 verbose(env, "R%d leaks addr as return value\n", regno); 16591 return -EACCES; 16592 } 16593 16594 if (frame->in_async_callback_fn) { 16595 exit_ctx = "At async callback return"; 16596 range = frame->callback_ret_range; 16597 goto enforce_retval; 16598 } 16599 16600 if (prog_type == BPF_PROG_TYPE_STRUCT_OPS && !ret_type) 16601 return 0; 16602 16603 if (prog_type == BPF_PROG_TYPE_CGROUP_SKB && (env->prog->expected_attach_type == BPF_CGROUP_INET_EGRESS)) 16604 enforce_attach_type_range = tnum_range(2, 3); 16605 16606 if (!return_retval_range(env, &range)) 16607 return 0; 16608 16609 enforce_retval: 16610 if (reg->type != SCALAR_VALUE) { 16611 verbose(env, "%s the register R%d is not a known value (%s)\n", 16612 exit_ctx, regno, reg_type_str(env, reg->type)); 16613 return -EINVAL; 16614 } 16615 16616 err = mark_chain_precision(env, regno); 16617 if (err) 16618 return err; 16619 16620 if (!retval_range_within(range, reg)) { 16621 verbose_invalid_scalar(env, reg, range, exit_ctx, reg_name); 16622 if (prog->expected_attach_type == BPF_LSM_CGROUP && 16623 prog_type == BPF_PROG_TYPE_LSM && 16624 !prog->aux->attach_func_proto->type) 16625 verbose(env, "Note, BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n"); 16626 return -EINVAL; 16627 } 16628 16629 if (!tnum_is_unknown(enforce_attach_type_range) && 16630 tnum_in(enforce_attach_type_range, reg->var_off)) 16631 env->prog->enforce_expected_attach_type = 1; 16632 return 0; 16633 } 16634 16635 static int check_global_subprog_return_code(struct bpf_verifier_env *env) 16636 { 16637 struct bpf_reg_state *reg = reg_state(env, BPF_REG_0); 16638 struct bpf_func_state *cur_frame = cur_func(env); 16639 int err; 16640 16641 if (subprog_returns_void(env, cur_frame->subprogno)) 16642 return 0; 16643 16644 err = check_reg_arg(env, BPF_REG_0, SRC_OP); 16645 if (err) 16646 return err; 16647 16648 if (is_pointer_value(env, BPF_REG_0)) { 16649 verbose(env, "R%d leaks addr as return value\n", BPF_REG_0); 16650 return -EACCES; 16651 } 16652 16653 if (reg->type != SCALAR_VALUE) { 16654 verbose(env, "At subprogram exit the register R0 is not a scalar value (%s)\n", 16655 reg_type_str(env, reg->type)); 16656 return -EINVAL; 16657 } 16658 16659 return 0; 16660 } 16661 16662 /* Bitmask with 1s for all caller saved registers */ 16663 #define ALL_CALLER_SAVED_REGS ((1u << CALLER_SAVED_REGS) - 1) 16664 16665 /* True if do_misc_fixups() replaces calls to helper number 'imm', 16666 * replacement patch is presumed to follow bpf_fastcall contract 16667 * (see mark_fastcall_pattern_for_call() below). 16668 */ 16669 bool bpf_verifier_inlines_helper_call(struct bpf_verifier_env *env, s32 imm) 16670 { 16671 switch (imm) { 16672 #ifdef CONFIG_X86_64 16673 case BPF_FUNC_get_smp_processor_id: 16674 #ifdef CONFIG_SMP 16675 case BPF_FUNC_get_current_task_btf: 16676 case BPF_FUNC_get_current_task: 16677 #endif 16678 return env->prog->jit_requested && bpf_jit_supports_percpu_insn(); 16679 #endif 16680 default: 16681 return false; 16682 } 16683 } 16684 16685 /* If @call is a kfunc or helper call, fills @cs and returns true, 16686 * otherwise returns false. 16687 */ 16688 bool bpf_get_call_summary(struct bpf_verifier_env *env, struct bpf_insn *call, 16689 struct bpf_call_summary *cs) 16690 { 16691 struct bpf_kfunc_call_arg_meta meta; 16692 const struct bpf_func_proto *fn; 16693 int i; 16694 16695 if (bpf_helper_call(call)) { 16696 16697 if (bpf_get_helper_proto(env, call->imm, &fn) < 0) 16698 /* error would be reported later */ 16699 return false; 16700 cs->fastcall = fn->allow_fastcall && 16701 (bpf_verifier_inlines_helper_call(env, call->imm) || 16702 bpf_jit_inlines_helper_call(call->imm)); 16703 cs->is_void = fn->ret_type == RET_VOID; 16704 cs->num_params = 0; 16705 for (i = 0; i < ARRAY_SIZE(fn->arg_type); ++i) { 16706 if (fn->arg_type[i] == ARG_DONTCARE) 16707 break; 16708 cs->num_params++; 16709 } 16710 return true; 16711 } 16712 16713 if (bpf_pseudo_kfunc_call(call)) { 16714 int err; 16715 16716 err = bpf_fetch_kfunc_arg_meta(env, call->imm, call->off, &meta); 16717 if (err < 0) 16718 /* error would be reported later */ 16719 return false; 16720 cs->num_params = btf_type_vlen(meta.func_proto); 16721 cs->fastcall = meta.kfunc_flags & KF_FASTCALL; 16722 cs->is_void = btf_type_is_void(btf_type_by_id(meta.btf, meta.func_proto->type)); 16723 return true; 16724 } 16725 16726 return false; 16727 } 16728 16729 /* LLVM define a bpf_fastcall function attribute. 16730 * This attribute means that function scratches only some of 16731 * the caller saved registers defined by ABI. 16732 * For BPF the set of such registers could be defined as follows: 16733 * - R0 is scratched only if function is non-void; 16734 * - R1-R5 are scratched only if corresponding parameter type is defined 16735 * in the function prototype. 16736 * 16737 * The contract between kernel and clang allows to simultaneously use 16738 * such functions and maintain backwards compatibility with old 16739 * kernels that don't understand bpf_fastcall calls: 16740 * 16741 * - for bpf_fastcall calls clang allocates registers as-if relevant r0-r5 16742 * registers are not scratched by the call; 16743 * 16744 * - as a post-processing step, clang visits each bpf_fastcall call and adds 16745 * spill/fill for every live r0-r5; 16746 * 16747 * - stack offsets used for the spill/fill are allocated as lowest 16748 * stack offsets in whole function and are not used for any other 16749 * purposes; 16750 * 16751 * - when kernel loads a program, it looks for such patterns 16752 * (bpf_fastcall function surrounded by spills/fills) and checks if 16753 * spill/fill stack offsets are used exclusively in fastcall patterns; 16754 * 16755 * - if so, and if verifier or current JIT inlines the call to the 16756 * bpf_fastcall function (e.g. a helper call), kernel removes unnecessary 16757 * spill/fill pairs; 16758 * 16759 * - when old kernel loads a program, presence of spill/fill pairs 16760 * keeps BPF program valid, albeit slightly less efficient. 16761 * 16762 * For example: 16763 * 16764 * r1 = 1; 16765 * r2 = 2; 16766 * *(u64 *)(r10 - 8) = r1; r1 = 1; 16767 * *(u64 *)(r10 - 16) = r2; r2 = 2; 16768 * call %[to_be_inlined] --> call %[to_be_inlined] 16769 * r2 = *(u64 *)(r10 - 16); r0 = r1; 16770 * r1 = *(u64 *)(r10 - 8); r0 += r2; 16771 * r0 = r1; exit; 16772 * r0 += r2; 16773 * exit; 16774 * 16775 * The purpose of mark_fastcall_pattern_for_call is to: 16776 * - look for such patterns; 16777 * - mark spill and fill instructions in env->insn_aux_data[*].fastcall_pattern; 16778 * - mark set env->insn_aux_data[*].fastcall_spills_num for call instruction; 16779 * - update env->subprog_info[*]->fastcall_stack_off to find an offset 16780 * at which bpf_fastcall spill/fill stack slots start; 16781 * - update env->subprog_info[*]->keep_fastcall_stack. 16782 * 16783 * The .fastcall_pattern and .fastcall_stack_off are used by 16784 * check_fastcall_stack_contract() to check if every stack access to 16785 * fastcall spill/fill stack slot originates from spill/fill 16786 * instructions, members of fastcall patterns. 16787 * 16788 * If such condition holds true for a subprogram, fastcall patterns could 16789 * be rewritten by remove_fastcall_spills_fills(). 16790 * Otherwise bpf_fastcall patterns are not changed in the subprogram 16791 * (code, presumably, generated by an older clang version). 16792 * 16793 * For example, it is *not* safe to remove spill/fill below: 16794 * 16795 * r1 = 1; 16796 * *(u64 *)(r10 - 8) = r1; r1 = 1; 16797 * call %[to_be_inlined] --> call %[to_be_inlined] 16798 * r1 = *(u64 *)(r10 - 8); r0 = *(u64 *)(r10 - 8); <---- wrong !!! 16799 * r0 = *(u64 *)(r10 - 8); r0 += r1; 16800 * r0 += r1; exit; 16801 * exit; 16802 */ 16803 static void mark_fastcall_pattern_for_call(struct bpf_verifier_env *env, 16804 struct bpf_subprog_info *subprog, 16805 int insn_idx, s16 lowest_off) 16806 { 16807 struct bpf_insn *insns = env->prog->insnsi, *stx, *ldx; 16808 struct bpf_insn *call = &env->prog->insnsi[insn_idx]; 16809 u32 clobbered_regs_mask; 16810 struct bpf_call_summary cs; 16811 u32 expected_regs_mask; 16812 s16 off; 16813 int i; 16814 16815 if (!bpf_get_call_summary(env, call, &cs)) 16816 return; 16817 16818 /* A bitmask specifying which caller saved registers are clobbered 16819 * by a call to a helper/kfunc *as if* this helper/kfunc follows 16820 * bpf_fastcall contract: 16821 * - includes R0 if function is non-void; 16822 * - includes R1-R5 if corresponding parameter has is described 16823 * in the function prototype. 16824 */ 16825 clobbered_regs_mask = GENMASK(cs.num_params, cs.is_void ? 1 : 0); 16826 /* e.g. if helper call clobbers r{0,1}, expect r{2,3,4,5} in the pattern */ 16827 expected_regs_mask = ~clobbered_regs_mask & ALL_CALLER_SAVED_REGS; 16828 16829 /* match pairs of form: 16830 * 16831 * *(u64 *)(r10 - Y) = rX (where Y % 8 == 0) 16832 * ... 16833 * call %[to_be_inlined] 16834 * ... 16835 * rX = *(u64 *)(r10 - Y) 16836 */ 16837 for (i = 1, off = lowest_off; i <= ARRAY_SIZE(caller_saved); ++i, off += BPF_REG_SIZE) { 16838 if (insn_idx - i < 0 || insn_idx + i >= env->prog->len) 16839 break; 16840 stx = &insns[insn_idx - i]; 16841 ldx = &insns[insn_idx + i]; 16842 /* must be a stack spill/fill pair */ 16843 if (stx->code != (BPF_STX | BPF_MEM | BPF_DW) || 16844 ldx->code != (BPF_LDX | BPF_MEM | BPF_DW) || 16845 stx->dst_reg != BPF_REG_10 || 16846 ldx->src_reg != BPF_REG_10) 16847 break; 16848 /* must be a spill/fill for the same reg */ 16849 if (stx->src_reg != ldx->dst_reg) 16850 break; 16851 /* must be one of the previously unseen registers */ 16852 if ((BIT(stx->src_reg) & expected_regs_mask) == 0) 16853 break; 16854 /* must be a spill/fill for the same expected offset, 16855 * no need to check offset alignment, BPF_DW stack access 16856 * is always 8-byte aligned. 16857 */ 16858 if (stx->off != off || ldx->off != off) 16859 break; 16860 expected_regs_mask &= ~BIT(stx->src_reg); 16861 env->insn_aux_data[insn_idx - i].fastcall_pattern = 1; 16862 env->insn_aux_data[insn_idx + i].fastcall_pattern = 1; 16863 } 16864 if (i == 1) 16865 return; 16866 16867 /* Conditionally set 'fastcall_spills_num' to allow forward 16868 * compatibility when more helper functions are marked as 16869 * bpf_fastcall at compile time than current kernel supports, e.g: 16870 * 16871 * 1: *(u64 *)(r10 - 8) = r1 16872 * 2: call A ;; assume A is bpf_fastcall for current kernel 16873 * 3: r1 = *(u64 *)(r10 - 8) 16874 * 4: *(u64 *)(r10 - 8) = r1 16875 * 5: call B ;; assume B is not bpf_fastcall for current kernel 16876 * 6: r1 = *(u64 *)(r10 - 8) 16877 * 16878 * There is no need to block bpf_fastcall rewrite for such program. 16879 * Set 'fastcall_pattern' for both calls to keep check_fastcall_stack_contract() happy, 16880 * don't set 'fastcall_spills_num' for call B so that remove_fastcall_spills_fills() 16881 * does not remove spill/fill pair {4,6}. 16882 */ 16883 if (cs.fastcall) 16884 env->insn_aux_data[insn_idx].fastcall_spills_num = i - 1; 16885 else 16886 subprog->keep_fastcall_stack = 1; 16887 subprog->fastcall_stack_off = min(subprog->fastcall_stack_off, off); 16888 } 16889 16890 static int mark_fastcall_patterns(struct bpf_verifier_env *env) 16891 { 16892 struct bpf_subprog_info *subprog = env->subprog_info; 16893 struct bpf_insn *insn; 16894 s16 lowest_off; 16895 int s, i; 16896 16897 for (s = 0; s < env->subprog_cnt; ++s, ++subprog) { 16898 /* find lowest stack spill offset used in this subprog */ 16899 lowest_off = 0; 16900 for (i = subprog->start; i < (subprog + 1)->start; ++i) { 16901 insn = env->prog->insnsi + i; 16902 if (insn->code != (BPF_STX | BPF_MEM | BPF_DW) || 16903 insn->dst_reg != BPF_REG_10) 16904 continue; 16905 lowest_off = min(lowest_off, insn->off); 16906 } 16907 /* use this offset to find fastcall patterns */ 16908 for (i = subprog->start; i < (subprog + 1)->start; ++i) { 16909 insn = env->prog->insnsi + i; 16910 if (insn->code != (BPF_JMP | BPF_CALL)) 16911 continue; 16912 mark_fastcall_pattern_for_call(env, subprog, i, lowest_off); 16913 } 16914 } 16915 return 0; 16916 } 16917 16918 static void adjust_btf_func(struct bpf_verifier_env *env) 16919 { 16920 struct bpf_prog_aux *aux = env->prog->aux; 16921 int i; 16922 16923 if (!aux->func_info) 16924 return; 16925 16926 /* func_info is not available for hidden subprogs */ 16927 for (i = 0; i < env->subprog_cnt - env->hidden_subprog_cnt; i++) 16928 aux->func_info[i].insn_off = env->subprog_info[i].start; 16929 } 16930 16931 /* Find id in idset and increment its count, or add new entry */ 16932 static void idset_cnt_inc(struct bpf_idset *idset, u32 id) 16933 { 16934 u32 i; 16935 16936 for (i = 0; i < idset->num_ids; i++) { 16937 if (idset->entries[i].id == id) { 16938 idset->entries[i].cnt++; 16939 return; 16940 } 16941 } 16942 /* New id */ 16943 if (idset->num_ids < BPF_ID_MAP_SIZE) { 16944 idset->entries[idset->num_ids].id = id; 16945 idset->entries[idset->num_ids].cnt = 1; 16946 idset->num_ids++; 16947 } 16948 } 16949 16950 /* Find id in idset and return its count, or 0 if not found */ 16951 static u32 idset_cnt_get(struct bpf_idset *idset, u32 id) 16952 { 16953 u32 i; 16954 16955 for (i = 0; i < idset->num_ids; i++) { 16956 if (idset->entries[i].id == id) 16957 return idset->entries[i].cnt; 16958 } 16959 return 0; 16960 } 16961 16962 /* 16963 * Clear singular scalar ids in a state. 16964 * A register with a non-zero id is called singular if no other register shares 16965 * the same base id. Such registers can be treated as independent (id=0). 16966 */ 16967 void bpf_clear_singular_ids(struct bpf_verifier_env *env, 16968 struct bpf_verifier_state *st) 16969 { 16970 struct bpf_idset *idset = &env->idset_scratch; 16971 struct bpf_func_state *func; 16972 struct bpf_reg_state *reg; 16973 16974 idset->num_ids = 0; 16975 16976 bpf_for_each_reg_in_vstate(st, func, reg, ({ 16977 if (reg->type != SCALAR_VALUE) 16978 continue; 16979 if (!reg->id) 16980 continue; 16981 idset_cnt_inc(idset, reg->id & ~BPF_ADD_CONST); 16982 })); 16983 16984 bpf_for_each_reg_in_vstate(st, func, reg, ({ 16985 if (reg->type != SCALAR_VALUE) 16986 continue; 16987 if (!reg->id) 16988 continue; 16989 if (idset_cnt_get(idset, reg->id & ~BPF_ADD_CONST) == 1) 16990 clear_scalar_id(reg); 16991 })); 16992 } 16993 16994 /* Return true if it's OK to have the same insn return a different type. */ 16995 static bool reg_type_mismatch_ok(enum bpf_reg_type type) 16996 { 16997 switch (base_type(type)) { 16998 case PTR_TO_CTX: 16999 case PTR_TO_SOCKET: 17000 case PTR_TO_SOCK_COMMON: 17001 case PTR_TO_TCP_SOCK: 17002 case PTR_TO_XDP_SOCK: 17003 case PTR_TO_BTF_ID: 17004 case PTR_TO_ARENA: 17005 return false; 17006 default: 17007 return true; 17008 } 17009 } 17010 17011 /* If an instruction was previously used with particular pointer types, then we 17012 * need to be careful to avoid cases such as the below, where it may be ok 17013 * for one branch accessing the pointer, but not ok for the other branch: 17014 * 17015 * R1 = sock_ptr 17016 * goto X; 17017 * ... 17018 * R1 = some_other_valid_ptr; 17019 * goto X; 17020 * ... 17021 * R2 = *(u32 *)(R1 + 0); 17022 */ 17023 static bool reg_type_mismatch(enum bpf_reg_type src, enum bpf_reg_type prev) 17024 { 17025 return src != prev && (!reg_type_mismatch_ok(src) || 17026 !reg_type_mismatch_ok(prev)); 17027 } 17028 17029 static bool is_ptr_to_mem_or_btf_id(enum bpf_reg_type type) 17030 { 17031 switch (base_type(type)) { 17032 case PTR_TO_MEM: 17033 case PTR_TO_BTF_ID: 17034 return true; 17035 default: 17036 return false; 17037 } 17038 } 17039 17040 static bool is_ptr_to_mem(enum bpf_reg_type type) 17041 { 17042 return base_type(type) == PTR_TO_MEM; 17043 } 17044 17045 static int save_aux_ptr_type(struct bpf_verifier_env *env, enum bpf_reg_type type, 17046 bool allow_trust_mismatch) 17047 { 17048 enum bpf_reg_type *prev_type = &env->insn_aux_data[env->insn_idx].ptr_type; 17049 enum bpf_reg_type merged_type; 17050 17051 if (*prev_type == NOT_INIT) { 17052 /* Saw a valid insn 17053 * dst_reg = *(u32 *)(src_reg + off) 17054 * save type to validate intersecting paths 17055 */ 17056 *prev_type = type; 17057 } else if (reg_type_mismatch(type, *prev_type)) { 17058 /* Abuser program is trying to use the same insn 17059 * dst_reg = *(u32*) (src_reg + off) 17060 * with different pointer types: 17061 * src_reg == ctx in one branch and 17062 * src_reg == stack|map in some other branch. 17063 * Reject it. 17064 */ 17065 if (allow_trust_mismatch && 17066 is_ptr_to_mem_or_btf_id(type) && 17067 is_ptr_to_mem_or_btf_id(*prev_type)) { 17068 /* 17069 * Have to support a use case when one path through 17070 * the program yields TRUSTED pointer while another 17071 * is UNTRUSTED. Fallback to UNTRUSTED to generate 17072 * BPF_PROBE_MEM/BPF_PROBE_MEMSX. 17073 * Same behavior of MEM_RDONLY flag. 17074 */ 17075 if (is_ptr_to_mem(type) || is_ptr_to_mem(*prev_type)) 17076 merged_type = PTR_TO_MEM; 17077 else 17078 merged_type = PTR_TO_BTF_ID; 17079 if ((type & PTR_UNTRUSTED) || (*prev_type & PTR_UNTRUSTED)) 17080 merged_type |= PTR_UNTRUSTED; 17081 if ((type & MEM_RDONLY) || (*prev_type & MEM_RDONLY)) 17082 merged_type |= MEM_RDONLY; 17083 *prev_type = merged_type; 17084 } else { 17085 verbose(env, "same insn cannot be used with different pointers\n"); 17086 return -EINVAL; 17087 } 17088 } 17089 17090 return 0; 17091 } 17092 17093 enum { 17094 PROCESS_BPF_EXIT = 1, 17095 INSN_IDX_UPDATED = 2, 17096 }; 17097 17098 static int process_bpf_exit_full(struct bpf_verifier_env *env, 17099 bool *do_print_state, 17100 bool exception_exit) 17101 { 17102 struct bpf_func_state *cur_frame = cur_func(env); 17103 17104 /* We must do check_reference_leak here before 17105 * prepare_func_exit to handle the case when 17106 * state->curframe > 0, it may be a callback function, 17107 * for which reference_state must match caller reference 17108 * state when it exits. 17109 */ 17110 int err = check_resource_leak(env, exception_exit, 17111 exception_exit || !env->cur_state->curframe, 17112 exception_exit ? "bpf_throw" : 17113 "BPF_EXIT instruction in main prog"); 17114 if (err) 17115 return err; 17116 17117 /* The side effect of the prepare_func_exit which is 17118 * being skipped is that it frees bpf_func_state. 17119 * Typically, process_bpf_exit will only be hit with 17120 * outermost exit. copy_verifier_state in pop_stack will 17121 * handle freeing of any extra bpf_func_state left over 17122 * from not processing all nested function exits. We 17123 * also skip return code checks as they are not needed 17124 * for exceptional exits. 17125 */ 17126 if (exception_exit) 17127 return PROCESS_BPF_EXIT; 17128 17129 if (env->cur_state->curframe) { 17130 /* exit from nested function */ 17131 err = prepare_func_exit(env, &env->insn_idx); 17132 if (err) 17133 return err; 17134 *do_print_state = true; 17135 return INSN_IDX_UPDATED; 17136 } 17137 17138 /* 17139 * Return from a regular global subprogram differs from return 17140 * from the main program or async/exception callback. 17141 * Main program exit implies return code restrictions 17142 * that depend on program type. 17143 * Exit from exception callback is equivalent to main program exit. 17144 * Exit from async callback implies return code restrictions 17145 * that depend on async scheduling mechanism. 17146 */ 17147 if (cur_frame->subprogno && 17148 !cur_frame->in_async_callback_fn && 17149 !cur_frame->in_exception_callback_fn) 17150 err = check_global_subprog_return_code(env); 17151 else 17152 err = check_return_code(env, BPF_REG_0, "R0"); 17153 if (err) 17154 return err; 17155 return PROCESS_BPF_EXIT; 17156 } 17157 17158 static int indirect_jump_min_max_index(struct bpf_verifier_env *env, 17159 int regno, 17160 struct bpf_map *map, 17161 u32 *pmin_index, u32 *pmax_index) 17162 { 17163 struct bpf_reg_state *reg = reg_state(env, regno); 17164 u64 min_index = reg_umin(reg); 17165 u64 max_index = reg_umax(reg); 17166 const u32 size = 8; 17167 17168 if (min_index > (u64) U32_MAX * size) { 17169 verbose(env, "the sum of R%u umin_value %llu is too big\n", regno, reg_umin(reg)); 17170 return -ERANGE; 17171 } 17172 if (max_index > (u64) U32_MAX * size) { 17173 verbose(env, "the sum of R%u umax_value %llu is too big\n", regno, reg_umax(reg)); 17174 return -ERANGE; 17175 } 17176 17177 min_index /= size; 17178 max_index /= size; 17179 17180 if (max_index >= map->max_entries) { 17181 verbose(env, "R%u points to outside of jump table: [%llu,%llu] max_entries %u\n", 17182 regno, min_index, max_index, map->max_entries); 17183 return -EINVAL; 17184 } 17185 17186 *pmin_index = min_index; 17187 *pmax_index = max_index; 17188 return 0; 17189 } 17190 17191 /* gotox *dst_reg */ 17192 static int check_indirect_jump(struct bpf_verifier_env *env, struct bpf_insn *insn) 17193 { 17194 struct bpf_verifier_state *other_branch; 17195 struct bpf_reg_state *dst_reg; 17196 struct bpf_map *map; 17197 u32 min_index, max_index; 17198 int err = 0; 17199 int n; 17200 int i; 17201 17202 dst_reg = reg_state(env, insn->dst_reg); 17203 if (dst_reg->type != PTR_TO_INSN) { 17204 verbose(env, "R%d has type %s, expected PTR_TO_INSN\n", 17205 insn->dst_reg, reg_type_str(env, dst_reg->type)); 17206 return -EINVAL; 17207 } 17208 17209 map = dst_reg->map_ptr; 17210 if (verifier_bug_if(!map, env, "R%d has an empty map pointer", insn->dst_reg)) 17211 return -EFAULT; 17212 17213 if (verifier_bug_if(map->map_type != BPF_MAP_TYPE_INSN_ARRAY, env, 17214 "R%d has incorrect map type %d", insn->dst_reg, map->map_type)) 17215 return -EFAULT; 17216 17217 err = indirect_jump_min_max_index(env, insn->dst_reg, map, &min_index, &max_index); 17218 if (err) 17219 return err; 17220 17221 /* Ensure that the buffer is large enough */ 17222 if (!env->gotox_tmp_buf || env->gotox_tmp_buf->cnt < max_index - min_index + 1) { 17223 env->gotox_tmp_buf = bpf_iarray_realloc(env->gotox_tmp_buf, 17224 max_index - min_index + 1); 17225 if (!env->gotox_tmp_buf) 17226 return -ENOMEM; 17227 } 17228 17229 n = bpf_copy_insn_array_uniq(map, min_index, max_index, env->gotox_tmp_buf->items); 17230 if (n < 0) 17231 return n; 17232 if (n == 0) { 17233 verbose(env, "register R%d doesn't point to any offset in map id=%d\n", 17234 insn->dst_reg, map->id); 17235 return -EINVAL; 17236 } 17237 17238 for (i = 0; i < n - 1; i++) { 17239 mark_indirect_target(env, env->gotox_tmp_buf->items[i]); 17240 other_branch = push_stack(env, env->gotox_tmp_buf->items[i], 17241 env->insn_idx, env->cur_state->speculative); 17242 if (IS_ERR(other_branch)) 17243 return PTR_ERR(other_branch); 17244 } 17245 env->insn_idx = env->gotox_tmp_buf->items[n-1]; 17246 mark_indirect_target(env, env->insn_idx); 17247 return INSN_IDX_UPDATED; 17248 } 17249 17250 static int do_check_insn(struct bpf_verifier_env *env, bool *do_print_state) 17251 { 17252 int err; 17253 struct bpf_insn *insn = &env->prog->insnsi[env->insn_idx]; 17254 u8 class = BPF_CLASS(insn->code); 17255 17256 switch (class) { 17257 case BPF_ALU: 17258 case BPF_ALU64: 17259 return check_alu_op(env, insn); 17260 17261 case BPF_LDX: 17262 return check_load_mem(env, insn, false, 17263 BPF_MODE(insn->code) == BPF_MEMSX, 17264 true, "ldx"); 17265 17266 case BPF_STX: 17267 if (BPF_MODE(insn->code) == BPF_ATOMIC) 17268 return check_atomic(env, insn); 17269 return check_store_reg(env, insn, false); 17270 17271 case BPF_ST: { 17272 /* Handle stack arg write (store immediate) */ 17273 if (is_stack_arg_st(insn)) { 17274 struct bpf_verifier_state *vstate = env->cur_state; 17275 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 17276 17277 return check_stack_arg_write(env, state, insn->off, NULL); 17278 } 17279 17280 enum bpf_reg_type dst_reg_type; 17281 17282 err = check_reg_arg(env, insn->dst_reg, SRC_OP); 17283 if (err) 17284 return err; 17285 17286 dst_reg_type = cur_regs(env)[insn->dst_reg].type; 17287 17288 err = check_mem_access(env, env->insn_idx, cur_regs(env) + insn->dst_reg, argno_from_reg(insn->dst_reg), 17289 insn->off, BPF_SIZE(insn->code), 17290 BPF_WRITE, -1, false, false); 17291 if (err) 17292 return err; 17293 17294 return save_aux_ptr_type(env, dst_reg_type, false); 17295 } 17296 case BPF_JMP: 17297 case BPF_JMP32: { 17298 u8 opcode = BPF_OP(insn->code); 17299 17300 env->jmps_processed++; 17301 if (opcode == BPF_CALL) { 17302 if (env->cur_state->active_locks) { 17303 if ((insn->src_reg == BPF_REG_0 && 17304 insn->imm != BPF_FUNC_spin_unlock && 17305 insn->imm != BPF_FUNC_kptr_xchg) || 17306 (insn->src_reg == BPF_PSEUDO_KFUNC_CALL && 17307 (insn->off != 0 || !kfunc_spin_allowed(insn->imm)))) { 17308 verbose(env, 17309 "function calls are not allowed while holding a lock\n"); 17310 return -EINVAL; 17311 } 17312 } 17313 mark_reg_scratched(env, BPF_REG_0); 17314 if (bpf_in_stack_arg_cnt(&env->subprog_info[cur_func(env)->subprogno])) 17315 cur_func(env)->no_stack_arg_load = true; 17316 if (insn->src_reg == BPF_PSEUDO_CALL) 17317 return check_func_call(env, insn, &env->insn_idx); 17318 if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) 17319 return check_kfunc_call(env, insn, &env->insn_idx); 17320 return check_helper_call(env, insn, &env->insn_idx); 17321 } else if (opcode == BPF_JA) { 17322 if (BPF_SRC(insn->code) == BPF_X) 17323 return check_indirect_jump(env, insn); 17324 17325 if (class == BPF_JMP) 17326 env->insn_idx += insn->off + 1; 17327 else 17328 env->insn_idx += insn->imm + 1; 17329 return INSN_IDX_UPDATED; 17330 } else if (opcode == BPF_EXIT) { 17331 return process_bpf_exit_full(env, do_print_state, false); 17332 } 17333 return check_cond_jmp_op(env, insn, &env->insn_idx); 17334 } 17335 case BPF_LD: { 17336 u8 mode = BPF_MODE(insn->code); 17337 17338 if (mode == BPF_ABS || mode == BPF_IND) 17339 return check_ld_abs(env, insn); 17340 17341 if (mode == BPF_IMM) { 17342 err = check_ld_imm(env, insn); 17343 if (err) 17344 return err; 17345 17346 env->insn_idx++; 17347 sanitize_mark_insn_seen(env); 17348 } 17349 return 0; 17350 } 17351 } 17352 /* all class values are handled above. silence compiler warning */ 17353 return -EFAULT; 17354 } 17355 17356 static int do_check(struct bpf_verifier_env *env) 17357 { 17358 bool pop_log = !(env->log.level & BPF_LOG_LEVEL2); 17359 struct bpf_verifier_state *state = env->cur_state; 17360 struct bpf_insn *insns = env->prog->insnsi; 17361 int insn_cnt = env->prog->len; 17362 bool do_print_state = false; 17363 int prev_insn_idx = -1; 17364 17365 for (;;) { 17366 struct bpf_insn *insn; 17367 struct bpf_insn_aux_data *insn_aux; 17368 int err; 17369 17370 /* reset current history entry on each new instruction */ 17371 env->cur_hist_ent = NULL; 17372 17373 env->prev_insn_idx = prev_insn_idx; 17374 if (env->insn_idx >= insn_cnt) { 17375 verbose(env, "invalid insn idx %d insn_cnt %d\n", 17376 env->insn_idx, insn_cnt); 17377 return -EFAULT; 17378 } 17379 17380 insn = &insns[env->insn_idx]; 17381 insn_aux = &env->insn_aux_data[env->insn_idx]; 17382 17383 if (++env->insn_processed > BPF_COMPLEXITY_LIMIT_INSNS) { 17384 verbose(env, 17385 "BPF program is too large. Processed %d insn\n", 17386 env->insn_processed); 17387 return -E2BIG; 17388 } 17389 17390 state->last_insn_idx = env->prev_insn_idx; 17391 state->insn_idx = env->insn_idx; 17392 17393 if (bpf_is_prune_point(env, env->insn_idx)) { 17394 err = bpf_is_state_visited(env, env->insn_idx); 17395 if (err < 0) 17396 return err; 17397 if (err == 1) { 17398 /* found equivalent state, can prune the search */ 17399 if (env->log.level & BPF_LOG_LEVEL) { 17400 if (do_print_state) 17401 verbose(env, "\nfrom %d to %d%s: safe\n", 17402 env->prev_insn_idx, env->insn_idx, 17403 env->cur_state->speculative ? 17404 " (speculative execution)" : ""); 17405 else 17406 verbose(env, "%d: safe\n", env->insn_idx); 17407 } 17408 goto process_bpf_exit; 17409 } 17410 } 17411 17412 if (bpf_is_jmp_point(env, env->insn_idx)) { 17413 err = bpf_push_jmp_history(env, state, 0, 0, 0, 0); 17414 if (err) 17415 return err; 17416 } 17417 17418 if (signal_pending(current)) 17419 return -EAGAIN; 17420 17421 if (need_resched()) 17422 cond_resched(); 17423 17424 if (env->log.level & BPF_LOG_LEVEL2 && do_print_state) { 17425 verbose(env, "\nfrom %d to %d%s:", 17426 env->prev_insn_idx, env->insn_idx, 17427 env->cur_state->speculative ? 17428 " (speculative execution)" : ""); 17429 print_verifier_state(env, state, state->curframe, true); 17430 do_print_state = false; 17431 } 17432 17433 if (env->log.level & BPF_LOG_LEVEL) { 17434 if (verifier_state_scratched(env)) 17435 print_insn_state(env, state, state->curframe); 17436 17437 verbose_linfo(env, env->insn_idx, "; "); 17438 env->prev_log_pos = env->log.end_pos; 17439 verbose(env, "%d: ", env->insn_idx); 17440 bpf_verbose_insn(env, insn); 17441 env->prev_insn_print_pos = env->log.end_pos - env->prev_log_pos; 17442 env->prev_log_pos = env->log.end_pos; 17443 } 17444 17445 if (bpf_prog_is_offloaded(env->prog->aux)) { 17446 err = bpf_prog_offload_verify_insn(env, env->insn_idx, 17447 env->prev_insn_idx); 17448 if (err) 17449 return err; 17450 } 17451 17452 sanitize_mark_insn_seen(env); 17453 prev_insn_idx = env->insn_idx; 17454 17455 /* Sanity check: precomputed constants must match verifier state */ 17456 if (!state->speculative && insn_aux->const_reg_mask) { 17457 struct bpf_reg_state *regs = cur_regs(env); 17458 u16 mask = insn_aux->const_reg_mask; 17459 17460 for (int r = 0; r < ARRAY_SIZE(insn_aux->const_reg_vals); r++) { 17461 u32 cval = insn_aux->const_reg_vals[r]; 17462 17463 if (!(mask & BIT(r))) 17464 continue; 17465 if (regs[r].type != SCALAR_VALUE) 17466 continue; 17467 if (!tnum_is_const(regs[r].var_off)) 17468 continue; 17469 if (verifier_bug_if((u32)regs[r].var_off.value != cval, 17470 env, "const R%d: %u != %llu", 17471 r, cval, regs[r].var_off.value)) 17472 return -EFAULT; 17473 } 17474 } 17475 17476 /* Reduce verification complexity by stopping speculative path 17477 * verification when a nospec is encountered. 17478 */ 17479 if (state->speculative && insn_aux->nospec) 17480 goto process_bpf_exit; 17481 17482 err = do_check_insn(env, &do_print_state); 17483 if (error_recoverable_with_nospec(err) && state->speculative) { 17484 /* Prevent this speculative path from ever reaching the 17485 * insn that would have been unsafe to execute. 17486 */ 17487 insn_aux->nospec = true; 17488 /* If it was an ADD/SUB insn, potentially remove any 17489 * markings for alu sanitization. 17490 */ 17491 insn_aux->alu_state = 0; 17492 goto process_bpf_exit; 17493 } else if (err < 0) { 17494 return err; 17495 } else if (err == PROCESS_BPF_EXIT) { 17496 goto process_bpf_exit; 17497 } else if (err == INSN_IDX_UPDATED) { 17498 } else if (err == 0) { 17499 env->insn_idx++; 17500 } 17501 17502 if (state->speculative && insn_aux->nospec_result) { 17503 /* If we are on a path that performed a jump-op, this 17504 * may skip a nospec patched-in after the jump. This can 17505 * currently never happen because nospec_result is only 17506 * used for the write-ops 17507 * `*(size*)(dst_reg+off)=src_reg|imm32` and helper 17508 * calls. These must never skip the following insn 17509 * (i.e., bpf_insn_successors()'s opcode_info.can_jump 17510 * is false). Still, add a warning to document this in 17511 * case nospec_result is used elsewhere in the future. 17512 * 17513 * All non-branch instructions have a single 17514 * fall-through edge. For these, nospec_result should 17515 * already work. 17516 */ 17517 if (verifier_bug_if((BPF_CLASS(insn->code) == BPF_JMP || 17518 BPF_CLASS(insn->code) == BPF_JMP32) && 17519 BPF_OP(insn->code) != BPF_CALL, env, 17520 "speculation barrier after jump instruction may not have the desired effect")) 17521 return -EFAULT; 17522 process_bpf_exit: 17523 mark_verifier_state_scratched(env); 17524 err = bpf_update_branch_counts(env, env->cur_state); 17525 if (err) 17526 return err; 17527 err = pop_stack(env, &prev_insn_idx, &env->insn_idx, 17528 pop_log); 17529 if (err < 0) { 17530 if (err != -ENOENT) 17531 return err; 17532 break; 17533 } else { 17534 do_print_state = true; 17535 continue; 17536 } 17537 } 17538 } 17539 17540 return 0; 17541 } 17542 17543 static int find_btf_percpu_datasec(struct btf *btf) 17544 { 17545 const struct btf_type *t; 17546 const char *tname; 17547 int i, n; 17548 17549 /* 17550 * Both vmlinux and module each have their own ".data..percpu" 17551 * DATASECs in BTF. So for module's case, we need to skip vmlinux BTF 17552 * types to look at only module's own BTF types. 17553 */ 17554 n = btf_nr_types(btf); 17555 for (i = btf_named_start_id(btf, true); i < n; i++) { 17556 t = btf_type_by_id(btf, i); 17557 if (BTF_INFO_KIND(t->info) != BTF_KIND_DATASEC) 17558 continue; 17559 17560 tname = btf_name_by_offset(btf, t->name_off); 17561 if (!strcmp(tname, ".data..percpu")) 17562 return i; 17563 } 17564 17565 return -ENOENT; 17566 } 17567 17568 /* 17569 * Add btf to the env->used_btfs array. If needed, refcount the 17570 * corresponding kernel module. To simplify caller's logic 17571 * in case of error or if btf was added before the function 17572 * decreases the btf refcount. 17573 */ 17574 static int __add_used_btf(struct bpf_verifier_env *env, struct btf *btf) 17575 { 17576 struct btf_mod_pair *btf_mod; 17577 int ret = 0; 17578 int i; 17579 17580 /* check whether we recorded this BTF (and maybe module) already */ 17581 for (i = 0; i < env->used_btf_cnt; i++) 17582 if (env->used_btfs[i].btf == btf) 17583 goto ret_put; 17584 17585 if (env->used_btf_cnt >= MAX_USED_BTFS) { 17586 verbose(env, "The total number of btfs per program has reached the limit of %u\n", 17587 MAX_USED_BTFS); 17588 ret = -E2BIG; 17589 goto ret_put; 17590 } 17591 17592 btf_mod = &env->used_btfs[env->used_btf_cnt]; 17593 btf_mod->btf = btf; 17594 btf_mod->module = NULL; 17595 17596 /* if we reference variables from kernel module, bump its refcount */ 17597 if (btf_is_module(btf)) { 17598 btf_mod->module = btf_try_get_module(btf); 17599 if (!btf_mod->module) { 17600 ret = -ENXIO; 17601 goto ret_put; 17602 } 17603 } 17604 17605 env->used_btf_cnt++; 17606 return 0; 17607 17608 ret_put: 17609 /* Either error or this BTF was already added */ 17610 btf_put(btf); 17611 return ret; 17612 } 17613 17614 /* replace pseudo btf_id with kernel symbol address */ 17615 static int __check_pseudo_btf_id(struct bpf_verifier_env *env, 17616 struct bpf_insn *insn, 17617 struct bpf_insn_aux_data *aux, 17618 struct btf *btf) 17619 { 17620 const struct btf_var_secinfo *vsi; 17621 const struct btf_type *datasec; 17622 const struct btf_type *t; 17623 const char *sym_name; 17624 bool percpu = false; 17625 u32 type, id = insn->imm; 17626 s32 datasec_id; 17627 u64 addr; 17628 int i; 17629 17630 t = btf_type_by_id(btf, id); 17631 if (!t) { 17632 verbose(env, "ldimm64 insn specifies invalid btf_id %d.\n", id); 17633 return -ENOENT; 17634 } 17635 17636 if (!btf_type_is_var(t) && !btf_type_is_func(t)) { 17637 verbose(env, "pseudo btf_id %d in ldimm64 isn't KIND_VAR or KIND_FUNC\n", id); 17638 return -EINVAL; 17639 } 17640 17641 sym_name = btf_name_by_offset(btf, t->name_off); 17642 addr = kallsyms_lookup_name(sym_name); 17643 if (!addr) { 17644 verbose(env, "ldimm64 failed to find the address for kernel symbol '%s'.\n", 17645 sym_name); 17646 return -ENOENT; 17647 } 17648 insn[0].imm = (u32)addr; 17649 insn[1].imm = addr >> 32; 17650 17651 if (btf_type_is_func(t)) { 17652 aux->btf_var.reg_type = PTR_TO_MEM | MEM_RDONLY; 17653 aux->btf_var.mem_size = 0; 17654 return 0; 17655 } 17656 17657 datasec_id = find_btf_percpu_datasec(btf); 17658 if (datasec_id > 0) { 17659 datasec = btf_type_by_id(btf, datasec_id); 17660 for_each_vsi(i, datasec, vsi) { 17661 if (vsi->type == id) { 17662 percpu = true; 17663 break; 17664 } 17665 } 17666 } 17667 17668 type = t->type; 17669 t = btf_type_skip_modifiers(btf, type, NULL); 17670 if (percpu) { 17671 aux->btf_var.reg_type = PTR_TO_BTF_ID | MEM_PERCPU; 17672 aux->btf_var.btf = btf; 17673 aux->btf_var.btf_id = type; 17674 } else if (!btf_type_is_struct(t)) { 17675 const struct btf_type *ret; 17676 const char *tname; 17677 u32 tsize; 17678 17679 /* resolve the type size of ksym. */ 17680 ret = btf_resolve_size(btf, t, &tsize); 17681 if (IS_ERR(ret)) { 17682 tname = btf_name_by_offset(btf, t->name_off); 17683 verbose(env, "ldimm64 unable to resolve the size of type '%s': %ld\n", 17684 tname, PTR_ERR(ret)); 17685 return -EINVAL; 17686 } 17687 aux->btf_var.reg_type = PTR_TO_MEM | MEM_RDONLY; 17688 aux->btf_var.mem_size = tsize; 17689 } else { 17690 aux->btf_var.reg_type = PTR_TO_BTF_ID; 17691 aux->btf_var.btf = btf; 17692 aux->btf_var.btf_id = type; 17693 } 17694 17695 return 0; 17696 } 17697 17698 static int check_pseudo_btf_id(struct bpf_verifier_env *env, 17699 struct bpf_insn *insn, 17700 struct bpf_insn_aux_data *aux) 17701 { 17702 struct btf *btf; 17703 int btf_fd; 17704 int err; 17705 17706 btf_fd = insn[1].imm; 17707 if (btf_fd) { 17708 btf = btf_get_by_fd(btf_fd); 17709 if (IS_ERR(btf)) { 17710 verbose(env, "invalid module BTF object FD specified.\n"); 17711 return -EINVAL; 17712 } 17713 } else { 17714 if (!btf_vmlinux) { 17715 verbose(env, "kernel is missing BTF, make sure CONFIG_DEBUG_INFO_BTF=y is specified in Kconfig.\n"); 17716 return -EINVAL; 17717 } 17718 btf_get(btf_vmlinux); 17719 btf = btf_vmlinux; 17720 } 17721 17722 err = __check_pseudo_btf_id(env, insn, aux, btf); 17723 if (err) { 17724 btf_put(btf); 17725 return err; 17726 } 17727 17728 return __add_used_btf(env, btf); 17729 } 17730 17731 static bool is_tracing_prog_type(enum bpf_prog_type type) 17732 { 17733 switch (type) { 17734 case BPF_PROG_TYPE_KPROBE: 17735 case BPF_PROG_TYPE_TRACEPOINT: 17736 case BPF_PROG_TYPE_PERF_EVENT: 17737 case BPF_PROG_TYPE_RAW_TRACEPOINT: 17738 case BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE: 17739 return true; 17740 default: 17741 return false; 17742 } 17743 } 17744 17745 static bool bpf_map_is_cgroup_storage(struct bpf_map *map) 17746 { 17747 return (map->map_type == BPF_MAP_TYPE_CGROUP_STORAGE || 17748 map->map_type == BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE); 17749 } 17750 17751 static int check_map_prog_compatibility(struct bpf_verifier_env *env, 17752 struct bpf_map *map, 17753 struct bpf_prog *prog) 17754 17755 { 17756 enum bpf_prog_type prog_type = resolve_prog_type(prog); 17757 17758 if (map->excl_prog_sha && 17759 memcmp(map->excl_prog_sha, prog->digest, SHA256_DIGEST_SIZE)) { 17760 verbose(env, "program's hash doesn't match map's excl_prog_hash\n"); 17761 return -EACCES; 17762 } 17763 17764 if (btf_record_has_field(map->record, BPF_LIST_HEAD) || 17765 btf_record_has_field(map->record, BPF_RB_ROOT)) { 17766 if (is_tracing_prog_type(prog_type)) { 17767 verbose(env, "tracing progs cannot use bpf_{list_head,rb_root} yet\n"); 17768 return -EINVAL; 17769 } 17770 } 17771 17772 if (btf_record_has_field(map->record, BPF_SPIN_LOCK | BPF_RES_SPIN_LOCK)) { 17773 if (prog_type == BPF_PROG_TYPE_SOCKET_FILTER) { 17774 verbose(env, "socket filter progs cannot use bpf_spin_lock yet\n"); 17775 return -EINVAL; 17776 } 17777 17778 if (is_tracing_prog_type(prog_type)) { 17779 verbose(env, "tracing progs cannot use bpf_spin_lock yet\n"); 17780 return -EINVAL; 17781 } 17782 } 17783 17784 if ((bpf_prog_is_offloaded(prog->aux) || bpf_map_is_offloaded(map)) && 17785 !bpf_offload_prog_map_match(prog, map)) { 17786 verbose(env, "offload device mismatch between prog and map\n"); 17787 return -EINVAL; 17788 } 17789 17790 if (map->map_type == BPF_MAP_TYPE_STRUCT_OPS) { 17791 verbose(env, "bpf_struct_ops map cannot be used in prog\n"); 17792 return -EINVAL; 17793 } 17794 17795 if (prog->sleepable) 17796 switch (map->map_type) { 17797 case BPF_MAP_TYPE_HASH: 17798 case BPF_MAP_TYPE_LRU_HASH: 17799 case BPF_MAP_TYPE_ARRAY: 17800 case BPF_MAP_TYPE_PERCPU_HASH: 17801 case BPF_MAP_TYPE_PERCPU_ARRAY: 17802 case BPF_MAP_TYPE_LRU_PERCPU_HASH: 17803 case BPF_MAP_TYPE_ARRAY_OF_MAPS: 17804 case BPF_MAP_TYPE_HASH_OF_MAPS: 17805 case BPF_MAP_TYPE_RINGBUF: 17806 case BPF_MAP_TYPE_USER_RINGBUF: 17807 case BPF_MAP_TYPE_INODE_STORAGE: 17808 case BPF_MAP_TYPE_SK_STORAGE: 17809 case BPF_MAP_TYPE_TASK_STORAGE: 17810 case BPF_MAP_TYPE_CGRP_STORAGE: 17811 case BPF_MAP_TYPE_QUEUE: 17812 case BPF_MAP_TYPE_STACK: 17813 case BPF_MAP_TYPE_ARENA: 17814 case BPF_MAP_TYPE_INSN_ARRAY: 17815 case BPF_MAP_TYPE_PROG_ARRAY: 17816 break; 17817 default: 17818 verbose(env, 17819 "Sleepable programs can only use array, hash, ringbuf and local storage maps\n"); 17820 return -EINVAL; 17821 } 17822 17823 if (bpf_map_is_cgroup_storage(map) && 17824 bpf_cgroup_storage_assign(env->prog->aux, map)) { 17825 verbose(env, "only one cgroup storage of each type is allowed\n"); 17826 return -EBUSY; 17827 } 17828 17829 if (map->map_type == BPF_MAP_TYPE_ARENA) { 17830 if (env->prog->aux->arena) { 17831 verbose(env, "Only one arena per program\n"); 17832 return -EBUSY; 17833 } 17834 if (!env->allow_ptr_leaks || !env->bpf_capable) { 17835 verbose(env, "CAP_BPF and CAP_PERFMON are required to use arena\n"); 17836 return -EPERM; 17837 } 17838 if (!env->prog->jit_requested) { 17839 verbose(env, "JIT is required to use arena\n"); 17840 return -EOPNOTSUPP; 17841 } 17842 if (!bpf_jit_supports_arena()) { 17843 verbose(env, "JIT doesn't support arena\n"); 17844 return -EOPNOTSUPP; 17845 } 17846 env->prog->aux->arena = (void *)map; 17847 if (!bpf_arena_get_user_vm_start(env->prog->aux->arena)) { 17848 verbose(env, "arena's user address must be set via map_extra or mmap()\n"); 17849 return -EINVAL; 17850 } 17851 } 17852 17853 return 0; 17854 } 17855 17856 static int __add_used_map(struct bpf_verifier_env *env, struct bpf_map *map) 17857 { 17858 int i, err; 17859 17860 /* check whether we recorded this map already */ 17861 for (i = 0; i < env->used_map_cnt; i++) 17862 if (env->used_maps[i] == map) 17863 return i; 17864 17865 if (env->used_map_cnt >= MAX_USED_MAPS) { 17866 verbose(env, "The total number of maps per program has reached the limit of %u\n", 17867 MAX_USED_MAPS); 17868 return -E2BIG; 17869 } 17870 17871 err = check_map_prog_compatibility(env, map, env->prog); 17872 if (err) 17873 return err; 17874 17875 if (env->prog->sleepable) 17876 atomic64_inc(&map->sleepable_refcnt); 17877 17878 /* hold the map. If the program is rejected by verifier, 17879 * the map will be released by release_maps() or it 17880 * will be used by the valid program until it's unloaded 17881 * and all maps are released in bpf_free_used_maps() 17882 */ 17883 bpf_map_inc(map); 17884 17885 env->used_maps[env->used_map_cnt++] = map; 17886 17887 if (map->map_type == BPF_MAP_TYPE_INSN_ARRAY) { 17888 err = bpf_insn_array_init(map, env->prog); 17889 if (err) { 17890 verbose(env, "Failed to properly initialize insn array\n"); 17891 return err; 17892 } 17893 env->insn_array_maps[env->insn_array_map_cnt++] = map; 17894 } 17895 17896 return env->used_map_cnt - 1; 17897 } 17898 17899 /* Add map behind fd to used maps list, if it's not already there, and return 17900 * its index. 17901 * Returns <0 on error, or >= 0 index, on success. 17902 */ 17903 static int add_used_map(struct bpf_verifier_env *env, int fd) 17904 { 17905 struct bpf_map *map; 17906 CLASS(fd, f)(fd); 17907 17908 map = __bpf_map_get(f); 17909 if (IS_ERR(map)) { 17910 verbose(env, "fd %d is not pointing to valid bpf_map\n", fd); 17911 return PTR_ERR(map); 17912 } 17913 17914 return __add_used_map(env, map); 17915 } 17916 17917 static int check_alu_fields(struct bpf_verifier_env *env, struct bpf_insn *insn) 17918 { 17919 u8 class = BPF_CLASS(insn->code); 17920 u8 opcode = BPF_OP(insn->code); 17921 17922 switch (opcode) { 17923 case BPF_NEG: 17924 if (BPF_SRC(insn->code) != BPF_K || insn->src_reg != BPF_REG_0 || 17925 insn->off != 0 || insn->imm != 0) { 17926 verbose(env, "BPF_NEG uses reserved fields\n"); 17927 return -EINVAL; 17928 } 17929 return 0; 17930 case BPF_END: 17931 if (insn->src_reg != BPF_REG_0 || insn->off != 0 || 17932 (insn->imm != 16 && insn->imm != 32 && insn->imm != 64) || 17933 (class == BPF_ALU64 && BPF_SRC(insn->code) != BPF_TO_LE)) { 17934 verbose(env, "BPF_END uses reserved fields\n"); 17935 return -EINVAL; 17936 } 17937 return 0; 17938 case BPF_MOV: 17939 if (BPF_SRC(insn->code) == BPF_X) { 17940 if (class == BPF_ALU) { 17941 if ((insn->off != 0 && insn->off != 8 && insn->off != 16) || 17942 insn->imm) { 17943 verbose(env, "BPF_MOV uses reserved fields\n"); 17944 return -EINVAL; 17945 } 17946 } else if (insn->off == BPF_ADDR_SPACE_CAST) { 17947 if (insn->imm != 1 && insn->imm != 1u << 16) { 17948 verbose(env, "addr_space_cast insn can only convert between address space 1 and 0\n"); 17949 return -EINVAL; 17950 } 17951 } else if ((insn->off != 0 && insn->off != 8 && 17952 insn->off != 16 && insn->off != 32) || insn->imm) { 17953 verbose(env, "BPF_MOV uses reserved fields\n"); 17954 return -EINVAL; 17955 } 17956 } else if (insn->src_reg != BPF_REG_0 || insn->off != 0) { 17957 verbose(env, "BPF_MOV uses reserved fields\n"); 17958 return -EINVAL; 17959 } 17960 return 0; 17961 case BPF_ADD: 17962 case BPF_SUB: 17963 case BPF_AND: 17964 case BPF_OR: 17965 case BPF_XOR: 17966 case BPF_LSH: 17967 case BPF_RSH: 17968 case BPF_ARSH: 17969 case BPF_MUL: 17970 case BPF_DIV: 17971 case BPF_MOD: 17972 if (BPF_SRC(insn->code) == BPF_X) { 17973 if (insn->imm != 0 || (insn->off != 0 && insn->off != 1) || 17974 (insn->off == 1 && opcode != BPF_MOD && opcode != BPF_DIV)) { 17975 verbose(env, "BPF_ALU uses reserved fields\n"); 17976 return -EINVAL; 17977 } 17978 } else if (insn->src_reg != BPF_REG_0 || 17979 (insn->off != 0 && insn->off != 1) || 17980 (insn->off == 1 && opcode != BPF_MOD && opcode != BPF_DIV)) { 17981 verbose(env, "BPF_ALU uses reserved fields\n"); 17982 return -EINVAL; 17983 } 17984 return 0; 17985 default: 17986 verbose(env, "invalid BPF_ALU opcode %x\n", opcode); 17987 return -EINVAL; 17988 } 17989 } 17990 17991 static int check_jmp_fields(struct bpf_verifier_env *env, struct bpf_insn *insn) 17992 { 17993 u8 class = BPF_CLASS(insn->code); 17994 u8 opcode = BPF_OP(insn->code); 17995 17996 switch (opcode) { 17997 case BPF_CALL: 17998 if (BPF_SRC(insn->code) != BPF_K || 17999 (insn->src_reg != BPF_PSEUDO_KFUNC_CALL && insn->off != 0) || 18000 (insn->src_reg != BPF_REG_0 && insn->src_reg != BPF_PSEUDO_CALL && 18001 insn->src_reg != BPF_PSEUDO_KFUNC_CALL) || 18002 insn->dst_reg != BPF_REG_0 || class == BPF_JMP32) { 18003 verbose(env, "BPF_CALL uses reserved fields\n"); 18004 return -EINVAL; 18005 } 18006 return 0; 18007 case BPF_JA: 18008 if (BPF_SRC(insn->code) == BPF_X) { 18009 if (insn->src_reg != BPF_REG_0 || insn->imm != 0 || insn->off != 0) { 18010 verbose(env, "BPF_JA|BPF_X uses reserved fields\n"); 18011 return -EINVAL; 18012 } 18013 } else if (insn->src_reg != BPF_REG_0 || insn->dst_reg != BPF_REG_0 || 18014 (class == BPF_JMP && insn->imm != 0) || 18015 (class == BPF_JMP32 && insn->off != 0)) { 18016 verbose(env, "BPF_JA uses reserved fields\n"); 18017 return -EINVAL; 18018 } 18019 return 0; 18020 case BPF_EXIT: 18021 if (BPF_SRC(insn->code) != BPF_K || insn->imm != 0 || 18022 insn->src_reg != BPF_REG_0 || insn->dst_reg != BPF_REG_0 || 18023 class == BPF_JMP32) { 18024 verbose(env, "BPF_EXIT uses reserved fields\n"); 18025 return -EINVAL; 18026 } 18027 return 0; 18028 case BPF_JCOND: 18029 if (insn->code != (BPF_JMP | BPF_JCOND) || insn->src_reg != BPF_MAY_GOTO || 18030 insn->dst_reg || insn->imm) { 18031 verbose(env, "invalid may_goto imm %d\n", insn->imm); 18032 return -EINVAL; 18033 } 18034 return 0; 18035 default: 18036 if (BPF_SRC(insn->code) == BPF_X) { 18037 if (insn->imm != 0) { 18038 verbose(env, "BPF_JMP/JMP32 uses reserved fields\n"); 18039 return -EINVAL; 18040 } 18041 } else if (insn->src_reg != BPF_REG_0) { 18042 verbose(env, "BPF_JMP/JMP32 uses reserved fields\n"); 18043 return -EINVAL; 18044 } 18045 return 0; 18046 } 18047 } 18048 18049 static int check_insn_fields(struct bpf_verifier_env *env, struct bpf_insn *insn) 18050 { 18051 switch (BPF_CLASS(insn->code)) { 18052 case BPF_ALU: 18053 case BPF_ALU64: 18054 return check_alu_fields(env, insn); 18055 case BPF_LDX: 18056 if ((BPF_MODE(insn->code) != BPF_MEM && BPF_MODE(insn->code) != BPF_MEMSX) || 18057 insn->imm != 0) { 18058 verbose(env, "BPF_LDX uses reserved fields\n"); 18059 return -EINVAL; 18060 } 18061 return 0; 18062 case BPF_STX: 18063 if (BPF_MODE(insn->code) == BPF_ATOMIC) 18064 return 0; 18065 if (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0) { 18066 verbose(env, "BPF_STX uses reserved fields\n"); 18067 return -EINVAL; 18068 } 18069 return 0; 18070 case BPF_ST: 18071 if (BPF_MODE(insn->code) != BPF_MEM || insn->src_reg != BPF_REG_0) { 18072 verbose(env, "BPF_ST uses reserved fields\n"); 18073 return -EINVAL; 18074 } 18075 return 0; 18076 case BPF_JMP: 18077 case BPF_JMP32: 18078 return check_jmp_fields(env, insn); 18079 case BPF_LD: { 18080 u8 mode = BPF_MODE(insn->code); 18081 18082 if (mode == BPF_ABS || mode == BPF_IND) { 18083 if (insn->dst_reg != BPF_REG_0 || insn->off != 0 || 18084 BPF_SIZE(insn->code) == BPF_DW || 18085 (mode == BPF_ABS && insn->src_reg != BPF_REG_0)) { 18086 verbose(env, "BPF_LD_[ABS|IND] uses reserved fields\n"); 18087 return -EINVAL; 18088 } 18089 } else if (mode != BPF_IMM) { 18090 verbose(env, "invalid BPF_LD mode\n"); 18091 return -EINVAL; 18092 } 18093 return 0; 18094 } 18095 default: 18096 verbose(env, "unknown insn class %d\n", BPF_CLASS(insn->code)); 18097 return -EINVAL; 18098 } 18099 } 18100 18101 /* 18102 * Check that insns are sane and rewrite pseudo imm in ld_imm64 instructions: 18103 * 18104 * 1. if it accesses map FD, replace it with actual map pointer. 18105 * 2. if it accesses btf_id of a VAR, replace it with pointer to the var. 18106 * 18107 * NOTE: btf_vmlinux is required for converting pseudo btf_id. 18108 */ 18109 static int check_and_resolve_insns(struct bpf_verifier_env *env) 18110 { 18111 struct bpf_insn *insn = env->prog->insnsi; 18112 int insn_cnt = env->prog->len; 18113 int i, err; 18114 18115 err = bpf_prog_calc_tag(env->prog); 18116 if (err) 18117 return err; 18118 18119 for (i = 0; i < insn_cnt; i++, insn++) { 18120 if (insn->dst_reg >= MAX_BPF_REG && 18121 !is_stack_arg_st(insn) && !is_stack_arg_stx(insn)) { 18122 verbose(env, "R%d is invalid\n", insn->dst_reg); 18123 return -EINVAL; 18124 } 18125 if (insn->src_reg >= MAX_BPF_REG && !is_stack_arg_ldx(insn)) { 18126 verbose(env, "R%d is invalid\n", insn->src_reg); 18127 return -EINVAL; 18128 } 18129 if (insn[0].code == (BPF_LD | BPF_IMM | BPF_DW)) { 18130 struct bpf_insn_aux_data *aux; 18131 struct bpf_map *map; 18132 int map_idx; 18133 u64 addr; 18134 u32 fd; 18135 18136 if (i == insn_cnt - 1 || insn[1].code != 0 || 18137 insn[1].dst_reg != 0 || insn[1].src_reg != 0 || 18138 insn[1].off != 0) { 18139 verbose(env, "invalid bpf_ld_imm64 insn\n"); 18140 return -EINVAL; 18141 } 18142 18143 if (insn[0].off != 0) { 18144 verbose(env, "BPF_LD_IMM64 uses reserved fields\n"); 18145 return -EINVAL; 18146 } 18147 18148 if (insn[0].src_reg == 0) 18149 /* valid generic load 64-bit imm */ 18150 goto next_insn; 18151 18152 if (insn[0].src_reg == BPF_PSEUDO_BTF_ID) { 18153 aux = &env->insn_aux_data[i]; 18154 err = check_pseudo_btf_id(env, insn, aux); 18155 if (err) 18156 return err; 18157 goto next_insn; 18158 } 18159 18160 if (insn[0].src_reg == BPF_PSEUDO_FUNC) { 18161 aux = &env->insn_aux_data[i]; 18162 aux->ptr_type = PTR_TO_FUNC; 18163 goto next_insn; 18164 } 18165 18166 /* In final convert_pseudo_ld_imm64() step, this is 18167 * converted into regular 64-bit imm load insn. 18168 */ 18169 switch (insn[0].src_reg) { 18170 case BPF_PSEUDO_MAP_VALUE: 18171 case BPF_PSEUDO_MAP_IDX_VALUE: 18172 break; 18173 case BPF_PSEUDO_MAP_FD: 18174 case BPF_PSEUDO_MAP_IDX: 18175 if (insn[1].imm == 0) 18176 break; 18177 fallthrough; 18178 default: 18179 verbose(env, "unrecognized bpf_ld_imm64 insn\n"); 18180 return -EINVAL; 18181 } 18182 18183 switch (insn[0].src_reg) { 18184 case BPF_PSEUDO_MAP_IDX_VALUE: 18185 case BPF_PSEUDO_MAP_IDX: 18186 if (bpfptr_is_null(env->fd_array)) { 18187 verbose(env, "fd_idx without fd_array is invalid\n"); 18188 return -EPROTO; 18189 } 18190 if (copy_from_bpfptr_offset(&fd, env->fd_array, 18191 insn[0].imm * sizeof(fd), 18192 sizeof(fd))) 18193 return -EFAULT; 18194 break; 18195 default: 18196 fd = insn[0].imm; 18197 break; 18198 } 18199 18200 map_idx = add_used_map(env, fd); 18201 if (map_idx < 0) 18202 return map_idx; 18203 map = env->used_maps[map_idx]; 18204 18205 aux = &env->insn_aux_data[i]; 18206 aux->map_index = map_idx; 18207 18208 if (insn[0].src_reg == BPF_PSEUDO_MAP_FD || 18209 insn[0].src_reg == BPF_PSEUDO_MAP_IDX) { 18210 addr = (unsigned long)map; 18211 } else { 18212 u32 off = insn[1].imm; 18213 18214 if (!map->ops->map_direct_value_addr) { 18215 verbose(env, "no direct value access support for this map type\n"); 18216 return -EINVAL; 18217 } 18218 18219 err = map->ops->map_direct_value_addr(map, &addr, off); 18220 if (err) { 18221 verbose(env, "invalid access to map value pointer, value_size=%u off=%u\n", 18222 map->value_size, off); 18223 return err; 18224 } 18225 18226 aux->map_off = off; 18227 addr += off; 18228 } 18229 18230 insn[0].imm = (u32)addr; 18231 insn[1].imm = addr >> 32; 18232 18233 next_insn: 18234 insn++; 18235 i++; 18236 continue; 18237 } 18238 18239 /* Basic sanity check before we invest more work here. */ 18240 if (!bpf_opcode_in_insntable(insn->code)) { 18241 verbose(env, "unknown opcode %02x\n", insn->code); 18242 return -EINVAL; 18243 } 18244 18245 err = check_insn_fields(env, insn); 18246 if (err) 18247 return err; 18248 } 18249 18250 /* now all pseudo BPF_LD_IMM64 instructions load valid 18251 * 'struct bpf_map *' into a register instead of user map_fd. 18252 * These pointers will be used later by verifier to validate map access. 18253 */ 18254 return 0; 18255 } 18256 18257 /* drop refcnt of maps used by the rejected program */ 18258 static void release_maps(struct bpf_verifier_env *env) 18259 { 18260 __bpf_free_used_maps(env->prog->aux, env->used_maps, 18261 env->used_map_cnt); 18262 } 18263 18264 /* drop refcnt of maps used by the rejected program */ 18265 static void release_btfs(struct bpf_verifier_env *env) 18266 { 18267 __bpf_free_used_btfs(env->used_btfs, env->used_btf_cnt); 18268 } 18269 18270 /* convert pseudo BPF_LD_IMM64 into generic BPF_LD_IMM64 */ 18271 static void convert_pseudo_ld_imm64(struct bpf_verifier_env *env) 18272 { 18273 struct bpf_insn *insn = env->prog->insnsi; 18274 int insn_cnt = env->prog->len; 18275 int i; 18276 18277 for (i = 0; i < insn_cnt; i++, insn++) { 18278 if (insn->code != (BPF_LD | BPF_IMM | BPF_DW)) 18279 continue; 18280 if (insn->src_reg == BPF_PSEUDO_FUNC) 18281 continue; 18282 insn->src_reg = 0; 18283 } 18284 } 18285 18286 static void release_insn_arrays(struct bpf_verifier_env *env) 18287 { 18288 int i; 18289 18290 for (i = 0; i < env->insn_array_map_cnt; i++) 18291 bpf_insn_array_release(env->insn_array_maps[i]); 18292 } 18293 18294 18295 18296 /* The verifier does more data flow analysis than llvm and will not 18297 * explore branches that are dead at run time. Malicious programs can 18298 * have dead code too. Therefore replace all dead at-run-time code 18299 * with 'ja -1'. 18300 * 18301 * Just nops are not optimal, e.g. if they would sit at the end of the 18302 * program and through another bug we would manage to jump there, then 18303 * we'd execute beyond program memory otherwise. Returning exception 18304 * code also wouldn't work since we can have subprogs where the dead 18305 * code could be located. 18306 */ 18307 static void sanitize_dead_code(struct bpf_verifier_env *env) 18308 { 18309 struct bpf_insn_aux_data *aux_data = env->insn_aux_data; 18310 struct bpf_insn trap = BPF_JMP_IMM(BPF_JA, 0, 0, -1); 18311 struct bpf_insn *insn = env->prog->insnsi; 18312 const int insn_cnt = env->prog->len; 18313 int i; 18314 18315 for (i = 0; i < insn_cnt; i++) { 18316 if (aux_data[i].seen) 18317 continue; 18318 memcpy(insn + i, &trap, sizeof(trap)); 18319 aux_data[i].zext_dst = false; 18320 } 18321 } 18322 18323 18324 18325 static void free_states(struct bpf_verifier_env *env) 18326 { 18327 struct bpf_verifier_state_list *sl; 18328 struct list_head *head, *pos, *tmp; 18329 struct bpf_scc_info *info; 18330 int i, j; 18331 18332 bpf_free_verifier_state(env->cur_state, true); 18333 env->cur_state = NULL; 18334 while (!pop_stack(env, NULL, NULL, false)); 18335 18336 list_for_each_safe(pos, tmp, &env->free_list) { 18337 sl = container_of(pos, struct bpf_verifier_state_list, node); 18338 bpf_free_verifier_state(&sl->state, false); 18339 kfree(sl); 18340 } 18341 INIT_LIST_HEAD(&env->free_list); 18342 18343 for (i = 0; i < env->scc_cnt; ++i) { 18344 info = env->scc_info[i]; 18345 if (!info) 18346 continue; 18347 for (j = 0; j < info->num_visits; j++) 18348 bpf_free_backedges(&info->visits[j]); 18349 kvfree(info); 18350 env->scc_info[i] = NULL; 18351 } 18352 18353 if (!env->explored_states) 18354 return; 18355 18356 for (i = 0; i < state_htab_size(env); i++) { 18357 head = &env->explored_states[i]; 18358 18359 list_for_each_safe(pos, tmp, head) { 18360 sl = container_of(pos, struct bpf_verifier_state_list, node); 18361 bpf_free_verifier_state(&sl->state, false); 18362 kfree(sl); 18363 } 18364 INIT_LIST_HEAD(&env->explored_states[i]); 18365 } 18366 } 18367 18368 static int do_check_common(struct bpf_verifier_env *env, int subprog) 18369 { 18370 bool pop_log = !(env->log.level & BPF_LOG_LEVEL2); 18371 struct bpf_subprog_info *sub = subprog_info(env, subprog); 18372 struct bpf_prog_aux *aux = env->prog->aux; 18373 struct bpf_verifier_state *state; 18374 struct bpf_reg_state *regs; 18375 int ret, i; 18376 18377 env->prev_linfo = NULL; 18378 env->pass_cnt++; 18379 18380 state = kzalloc_obj(struct bpf_verifier_state, GFP_KERNEL_ACCOUNT); 18381 if (!state) 18382 return -ENOMEM; 18383 state->curframe = 0; 18384 state->speculative = false; 18385 state->branches = 1; 18386 state->in_sleepable = env->prog->sleepable; 18387 state->frame[0] = kzalloc_obj(struct bpf_func_state, GFP_KERNEL_ACCOUNT); 18388 if (!state->frame[0]) { 18389 kfree(state); 18390 return -ENOMEM; 18391 } 18392 env->cur_state = state; 18393 init_func_state(env, state->frame[0], 18394 BPF_MAIN_FUNC /* callsite */, 18395 0 /* frameno */, 18396 subprog); 18397 state->first_insn_idx = env->subprog_info[subprog].start; 18398 state->last_insn_idx = -1; 18399 18400 regs = state->frame[state->curframe]->regs; 18401 if (subprog || env->prog->type == BPF_PROG_TYPE_EXT) { 18402 const char *sub_name = subprog_name(env, subprog); 18403 struct bpf_subprog_arg_info *arg; 18404 struct bpf_reg_state *reg; 18405 18406 if (env->log.level & BPF_LOG_LEVEL) 18407 verbose(env, "Validating %s() func#%d...\n", sub_name, subprog); 18408 ret = btf_prepare_func_args(env, subprog); 18409 if (ret) 18410 goto out; 18411 18412 if (subprog_is_exc_cb(env, subprog)) { 18413 state->frame[0]->in_exception_callback_fn = true; 18414 18415 /* 18416 * Global functions are scalar or void, make sure 18417 * we return a scalar. 18418 */ 18419 if (subprog_returns_void(env, subprog)) { 18420 verbose(env, "exception cb cannot return void\n"); 18421 ret = -EINVAL; 18422 goto out; 18423 } 18424 18425 /* Also ensure the callback only has a single scalar argument. */ 18426 if (sub->arg_cnt != 1 || sub->args[0].arg_type != ARG_ANYTHING) { 18427 verbose(env, "exception cb only supports single integer argument\n"); 18428 ret = -EINVAL; 18429 goto out; 18430 } 18431 } 18432 for (i = BPF_REG_1; i <= min_t(u32, sub->arg_cnt, MAX_BPF_FUNC_REG_ARGS); i++) { 18433 arg = &sub->args[i - BPF_REG_1]; 18434 reg = ®s[i]; 18435 18436 if (arg->arg_type == ARG_PTR_TO_CTX) { 18437 reg->type = PTR_TO_CTX; 18438 mark_reg_known_zero(env, regs, i); 18439 } else if (arg->arg_type == ARG_ANYTHING) { 18440 reg->type = SCALAR_VALUE; 18441 mark_reg_unknown(env, regs, i); 18442 } else if (arg->arg_type == ARG_PTR_TO_DYNPTR) { 18443 /* assume unspecial LOCAL dynptr type */ 18444 __mark_dynptr_reg(reg, BPF_DYNPTR_TYPE_LOCAL, true, ++env->id_gen); 18445 } else if (base_type(arg->arg_type) == ARG_PTR_TO_MEM) { 18446 reg->type = PTR_TO_MEM; 18447 reg->type |= arg->arg_type & 18448 (PTR_MAYBE_NULL | PTR_UNTRUSTED | MEM_RDONLY); 18449 mark_reg_known_zero(env, regs, i); 18450 reg->mem_size = arg->mem_size; 18451 if (arg->arg_type & PTR_MAYBE_NULL) 18452 reg->id = ++env->id_gen; 18453 } else if (base_type(arg->arg_type) == ARG_PTR_TO_BTF_ID) { 18454 reg->type = PTR_TO_BTF_ID; 18455 if (arg->arg_type & PTR_MAYBE_NULL) 18456 reg->type |= PTR_MAYBE_NULL; 18457 if (arg->arg_type & PTR_UNTRUSTED) 18458 reg->type |= PTR_UNTRUSTED; 18459 if (arg->arg_type & PTR_TRUSTED) 18460 reg->type |= PTR_TRUSTED; 18461 mark_reg_known_zero(env, regs, i); 18462 reg->btf = bpf_get_btf_vmlinux(); /* can't fail at this point */ 18463 reg->btf_id = arg->btf_id; 18464 reg->id = ++env->id_gen; 18465 } else if (base_type(arg->arg_type) == ARG_PTR_TO_ARENA) { 18466 /* caller can pass either PTR_TO_ARENA or SCALAR */ 18467 mark_reg_unknown(env, regs, i); 18468 } else { 18469 verifier_bug(env, "unhandled arg#%d type %d", 18470 i - BPF_REG_1 + 1, arg->arg_type); 18471 ret = -EFAULT; 18472 goto out; 18473 } 18474 } 18475 if (env->prog->type == BPF_PROG_TYPE_EXT && sub->arg_cnt > MAX_BPF_FUNC_REG_ARGS) { 18476 verbose(env, "freplace programs with >%d args not supported yet\n", 18477 MAX_BPF_FUNC_REG_ARGS); 18478 ret = -EINVAL; 18479 goto out; 18480 } 18481 } else { 18482 /* if main BPF program has associated BTF info, validate that 18483 * it's matching expected signature, and otherwise mark BTF 18484 * info for main program as unreliable 18485 */ 18486 if (env->prog->aux->func_info_aux) { 18487 ret = btf_prepare_func_args(env, 0); 18488 if (ret || sub->arg_cnt != 1 || sub->args[0].arg_type != ARG_PTR_TO_CTX) { 18489 env->prog->aux->func_info_aux[0].unreliable = true; 18490 sub->arg_cnt = 1; 18491 sub->stack_arg_cnt = 0; 18492 } 18493 } 18494 18495 /* 1st arg to a function */ 18496 regs[BPF_REG_1].type = PTR_TO_CTX; 18497 mark_reg_known_zero(env, regs, BPF_REG_1); 18498 } 18499 18500 /* Acquire references for struct_ops program arguments tagged with "__ref" */ 18501 if (!subprog && env->prog->type == BPF_PROG_TYPE_STRUCT_OPS) { 18502 for (i = 0; i < aux->ctx_arg_info_size; i++) 18503 aux->ctx_arg_info[i].ref_obj_id = aux->ctx_arg_info[i].refcounted ? 18504 acquire_reference(env, 0) : 0; 18505 } 18506 18507 ret = do_check(env); 18508 out: 18509 if (!ret && pop_log) 18510 bpf_vlog_reset(&env->log, 0); 18511 free_states(env); 18512 return ret; 18513 } 18514 18515 /* Lazily verify all global functions based on their BTF, if they are called 18516 * from main BPF program or any of subprograms transitively. 18517 * BPF global subprogs called from dead code are not validated. 18518 * All callable global functions must pass verification. 18519 * Otherwise the whole program is rejected. 18520 * Consider: 18521 * int bar(int); 18522 * int foo(int f) 18523 * { 18524 * return bar(f); 18525 * } 18526 * int bar(int b) 18527 * { 18528 * ... 18529 * } 18530 * foo() will be verified first for R1=any_scalar_value. During verification it 18531 * will be assumed that bar() already verified successfully and call to bar() 18532 * from foo() will be checked for type match only. Later bar() will be verified 18533 * independently to check that it's safe for R1=any_scalar_value. 18534 */ 18535 static int do_check_subprogs(struct bpf_verifier_env *env) 18536 { 18537 struct bpf_prog_aux *aux = env->prog->aux; 18538 struct bpf_func_info_aux *sub_aux; 18539 int i, ret, new_cnt; 18540 u32 insn_processed; 18541 18542 if (!aux->func_info) 18543 return 0; 18544 18545 /* exception callback is presumed to be always called */ 18546 if (env->exception_callback_subprog) 18547 subprog_aux(env, env->exception_callback_subprog)->called = true; 18548 18549 again: 18550 new_cnt = 0; 18551 for (i = 1; i < env->subprog_cnt; i++) { 18552 if (!bpf_subprog_is_global(env, i)) 18553 continue; 18554 18555 insn_processed = env->insn_processed; 18556 18557 sub_aux = subprog_aux(env, i); 18558 if (!sub_aux->called || sub_aux->verified) 18559 continue; 18560 18561 env->insn_idx = env->subprog_info[i].start; 18562 WARN_ON_ONCE(env->insn_idx == 0); 18563 ret = do_check_common(env, i); 18564 env->subprog_info[i].insn_processed = env->insn_processed - insn_processed; 18565 if (ret) { 18566 return ret; 18567 } else if (env->log.level & BPF_LOG_LEVEL) { 18568 verbose(env, "Func#%d ('%s') is safe for any args that match its prototype\n", 18569 i, subprog_name(env, i)); 18570 } 18571 18572 /* We verified new global subprog, it might have called some 18573 * more global subprogs that we haven't verified yet, so we 18574 * need to do another pass over subprogs to verify those. 18575 */ 18576 sub_aux->verified = true; 18577 new_cnt++; 18578 } 18579 18580 /* We can't loop forever as we verify at least one global subprog on 18581 * each pass. 18582 */ 18583 if (new_cnt) 18584 goto again; 18585 18586 return 0; 18587 } 18588 18589 static int do_check_main(struct bpf_verifier_env *env) 18590 { 18591 u32 insn_processed = env->insn_processed; 18592 int ret; 18593 18594 env->insn_idx = 0; 18595 ret = do_check_common(env, 0); 18596 env->subprog_info[0].insn_processed = env->insn_processed - insn_processed; 18597 if (!ret) 18598 env->prog->aux->stack_depth = env->subprog_info[0].stack_depth; 18599 return ret; 18600 } 18601 18602 18603 static void print_verification_stats(struct bpf_verifier_env *env) 18604 { 18605 /* Skip over hidden subprogs which are not verified. */ 18606 int i, subprog_cnt = env->subprog_cnt - env->hidden_subprog_cnt; 18607 18608 if (env->log.level & BPF_LOG_STATS) { 18609 verbose(env, "verification time %lld usec\n", 18610 div_u64(env->verification_time, 1000)); 18611 verbose(env, "stack depth %d", env->subprog_info[0].stack_depth); 18612 for (i = 1; i < subprog_cnt; i++) 18613 verbose(env, "+%d", env->subprog_info[i].stack_depth); 18614 verbose(env, " max %d\n", env->max_stack_depth); 18615 verbose(env, "insns processed %d", env->subprog_info[0].insn_processed); 18616 for (i = 1; i < subprog_cnt; i++) 18617 if (bpf_subprog_is_global(env, i)) 18618 verbose(env, "+%d", env->subprog_info[i].insn_processed); 18619 verbose(env, "\n"); 18620 } 18621 verbose(env, "processed %d insns (limit %d) max_states_per_insn %d " 18622 "total_states %d peak_states %d mark_read %d\n", 18623 env->insn_processed, BPF_COMPLEXITY_LIMIT_INSNS, 18624 env->max_states_per_insn, env->total_states, 18625 env->peak_states, env->longest_mark_read_walk); 18626 } 18627 18628 int bpf_prog_ctx_arg_info_init(struct bpf_prog *prog, 18629 const struct bpf_ctx_arg_aux *info, u32 cnt) 18630 { 18631 prog->aux->ctx_arg_info = kmemdup_array(info, cnt, sizeof(*info), GFP_KERNEL_ACCOUNT); 18632 prog->aux->ctx_arg_info_size = cnt; 18633 18634 return prog->aux->ctx_arg_info ? 0 : -ENOMEM; 18635 } 18636 18637 static int check_struct_ops_btf_id(struct bpf_verifier_env *env) 18638 { 18639 const struct btf_type *t, *func_proto; 18640 const struct bpf_struct_ops_desc *st_ops_desc; 18641 const struct bpf_struct_ops *st_ops; 18642 const struct btf_member *member; 18643 struct bpf_prog *prog = env->prog; 18644 bool has_refcounted_arg = false; 18645 u32 btf_id, member_idx, member_off; 18646 struct btf *btf; 18647 const char *mname; 18648 int i, err; 18649 18650 if (!prog->gpl_compatible) { 18651 verbose(env, "struct ops programs must have a GPL compatible license\n"); 18652 return -EINVAL; 18653 } 18654 18655 if (!prog->aux->attach_btf_id) 18656 return -ENOTSUPP; 18657 18658 btf = prog->aux->attach_btf; 18659 if (btf_is_module(btf)) { 18660 /* Make sure st_ops is valid through the lifetime of env */ 18661 env->attach_btf_mod = btf_try_get_module(btf); 18662 if (!env->attach_btf_mod) { 18663 verbose(env, "struct_ops module %s is not found\n", 18664 btf_get_name(btf)); 18665 return -ENOTSUPP; 18666 } 18667 } 18668 18669 btf_id = prog->aux->attach_btf_id; 18670 st_ops_desc = bpf_struct_ops_find(btf, btf_id); 18671 if (!st_ops_desc) { 18672 verbose(env, "attach_btf_id %u is not a supported struct\n", 18673 btf_id); 18674 return -ENOTSUPP; 18675 } 18676 st_ops = st_ops_desc->st_ops; 18677 18678 t = st_ops_desc->type; 18679 member_idx = prog->expected_attach_type; 18680 if (member_idx >= btf_type_vlen(t)) { 18681 verbose(env, "attach to invalid member idx %u of struct %s\n", 18682 member_idx, st_ops->name); 18683 return -EINVAL; 18684 } 18685 18686 member = &btf_type_member(t)[member_idx]; 18687 mname = btf_name_by_offset(btf, member->name_off); 18688 func_proto = btf_type_resolve_func_ptr(btf, member->type, 18689 NULL); 18690 if (!func_proto) { 18691 verbose(env, "attach to invalid member %s(@idx %u) of struct %s\n", 18692 mname, member_idx, st_ops->name); 18693 return -EINVAL; 18694 } 18695 18696 member_off = __btf_member_bit_offset(t, member) / 8; 18697 err = bpf_struct_ops_supported(st_ops, member_off); 18698 if (err) { 18699 verbose(env, "attach to unsupported member %s of struct %s\n", 18700 mname, st_ops->name); 18701 return err; 18702 } 18703 18704 if (st_ops->check_member) { 18705 err = st_ops->check_member(t, member, prog); 18706 18707 if (err) { 18708 verbose(env, "attach to unsupported member %s of struct %s\n", 18709 mname, st_ops->name); 18710 return err; 18711 } 18712 } 18713 18714 if (prog->aux->priv_stack_requested && !bpf_jit_supports_private_stack()) { 18715 verbose(env, "Private stack not supported by jit\n"); 18716 return -EACCES; 18717 } 18718 18719 for (i = 0; i < st_ops_desc->arg_info[member_idx].cnt; i++) { 18720 if (st_ops_desc->arg_info[member_idx].info[i].refcounted) { 18721 has_refcounted_arg = true; 18722 break; 18723 } 18724 } 18725 18726 /* Tail call is not allowed for programs with refcounted arguments since we 18727 * cannot guarantee that valid refcounted kptrs will be passed to the callee. 18728 */ 18729 for (i = 0; i < env->subprog_cnt; i++) { 18730 if (has_refcounted_arg && env->subprog_info[i].has_tail_call) { 18731 verbose(env, "program with __ref argument cannot tail call\n"); 18732 return -EINVAL; 18733 } 18734 } 18735 18736 prog->aux->st_ops = st_ops; 18737 prog->aux->attach_st_ops_member_off = member_off; 18738 18739 prog->aux->attach_func_proto = func_proto; 18740 prog->aux->attach_func_name = mname; 18741 env->ops = st_ops->verifier_ops; 18742 18743 return bpf_prog_ctx_arg_info_init(prog, st_ops_desc->arg_info[member_idx].info, 18744 st_ops_desc->arg_info[member_idx].cnt); 18745 } 18746 #define SECURITY_PREFIX "security_" 18747 18748 #ifdef CONFIG_FUNCTION_ERROR_INJECTION 18749 18750 /* list of non-sleepable functions that are otherwise on 18751 * ALLOW_ERROR_INJECTION list 18752 */ 18753 BTF_SET_START(btf_non_sleepable_error_inject) 18754 /* Three functions below can be called from sleepable and non-sleepable context. 18755 * Assume non-sleepable from bpf safety point of view. 18756 */ 18757 BTF_ID(func, __filemap_add_folio) 18758 #ifdef CONFIG_FAIL_PAGE_ALLOC 18759 BTF_ID(func, should_fail_alloc_page) 18760 #endif 18761 #ifdef CONFIG_FAILSLAB 18762 BTF_ID(func, should_failslab) 18763 #endif 18764 BTF_SET_END(btf_non_sleepable_error_inject) 18765 18766 static int check_non_sleepable_error_inject(u32 btf_id) 18767 { 18768 return btf_id_set_contains(&btf_non_sleepable_error_inject, btf_id); 18769 } 18770 18771 static int check_attach_sleepable(u32 btf_id, unsigned long addr, const char *func_name) 18772 { 18773 /* fentry/fexit/fmod_ret progs can be sleepable if they are 18774 * attached to ALLOW_ERROR_INJECTION and are not in denylist. 18775 */ 18776 if (!check_non_sleepable_error_inject(btf_id) && 18777 within_error_injection_list(addr)) 18778 return 0; 18779 18780 return -EINVAL; 18781 } 18782 18783 static int check_attach_modify_return(unsigned long addr, const char *func_name) 18784 { 18785 if (within_error_injection_list(addr) || 18786 !strncmp(SECURITY_PREFIX, func_name, sizeof(SECURITY_PREFIX) - 1)) 18787 return 0; 18788 18789 return -EINVAL; 18790 } 18791 18792 #else 18793 18794 /* Unfortunately, the arch-specific prefixes are hard-coded in arch syscall code 18795 * so we need to hard-code them, too. Ftrace has arch_syscall_match_sym_name() 18796 * but that just compares two concrete function names. 18797 */ 18798 static bool has_arch_syscall_prefix(const char *func_name) 18799 { 18800 #if defined(__x86_64__) 18801 return !strncmp(func_name, "__x64_", 6); 18802 #elif defined(__i386__) 18803 return !strncmp(func_name, "__ia32_", 7); 18804 #elif defined(__s390x__) 18805 return !strncmp(func_name, "__s390x_", 8); 18806 #elif defined(__aarch64__) 18807 return !strncmp(func_name, "__arm64_", 8); 18808 #elif defined(__riscv) 18809 return !strncmp(func_name, "__riscv_", 8); 18810 #elif defined(__powerpc__) || defined(__powerpc64__) 18811 return !strncmp(func_name, "sys_", 4); 18812 #elif defined(__loongarch__) 18813 return !strncmp(func_name, "sys_", 4); 18814 #else 18815 return false; 18816 #endif 18817 } 18818 18819 /* Without error injection, allow sleepable and fmod_ret progs on syscalls. */ 18820 18821 static int check_attach_sleepable(u32 btf_id, unsigned long addr, const char *func_name) 18822 { 18823 if (has_arch_syscall_prefix(func_name)) 18824 return 0; 18825 18826 return -EINVAL; 18827 } 18828 18829 static int check_attach_modify_return(unsigned long addr, const char *func_name) 18830 { 18831 if (has_arch_syscall_prefix(func_name) || 18832 !strncmp(SECURITY_PREFIX, func_name, sizeof(SECURITY_PREFIX) - 1)) 18833 return 0; 18834 18835 return -EINVAL; 18836 } 18837 18838 #endif /* CONFIG_FUNCTION_ERROR_INJECTION */ 18839 18840 int bpf_check_attach_target(struct bpf_verifier_log *log, 18841 const struct bpf_prog *prog, 18842 const struct bpf_prog *tgt_prog, 18843 u32 btf_id, 18844 struct bpf_attach_target_info *tgt_info) 18845 { 18846 bool prog_extension = prog->type == BPF_PROG_TYPE_EXT; 18847 bool prog_tracing = prog->type == BPF_PROG_TYPE_TRACING; 18848 char trace_symbol[KSYM_SYMBOL_LEN]; 18849 const char prefix[] = "btf_trace_"; 18850 struct bpf_raw_event_map *btp; 18851 int ret = 0, subprog = -1, i; 18852 const struct btf_type *t; 18853 bool conservative = true; 18854 const char *tname, *fname; 18855 struct btf *btf; 18856 long addr = 0; 18857 struct module *mod = NULL; 18858 18859 if (!btf_id) { 18860 bpf_log(log, "Tracing programs must provide btf_id\n"); 18861 return -EINVAL; 18862 } 18863 btf = tgt_prog ? tgt_prog->aux->btf : prog->aux->attach_btf; 18864 if (!btf) { 18865 bpf_log(log, 18866 "Tracing program can only be attached to another program annotated with BTF\n"); 18867 return -EINVAL; 18868 } 18869 t = btf_type_by_id(btf, btf_id); 18870 if (!t) { 18871 bpf_log(log, "attach_btf_id %u is invalid\n", btf_id); 18872 return -EINVAL; 18873 } 18874 tname = btf_name_by_offset(btf, t->name_off); 18875 if (!tname) { 18876 bpf_log(log, "attach_btf_id %u doesn't have a name\n", btf_id); 18877 return -EINVAL; 18878 } 18879 if (tgt_prog) { 18880 struct bpf_prog_aux *aux = tgt_prog->aux; 18881 bool tgt_changes_pkt_data; 18882 bool tgt_might_sleep; 18883 18884 if (bpf_prog_is_dev_bound(prog->aux) && 18885 !bpf_prog_dev_bound_match(prog, tgt_prog)) { 18886 bpf_log(log, "Target program bound device mismatch"); 18887 return -EINVAL; 18888 } 18889 18890 for (i = 0; i < aux->func_info_cnt; i++) 18891 if (aux->func_info[i].type_id == btf_id) { 18892 subprog = i; 18893 break; 18894 } 18895 if (subprog == -1) { 18896 bpf_log(log, "Subprog %s doesn't exist\n", tname); 18897 return -EINVAL; 18898 } 18899 if (aux->func && aux->func[subprog]->aux->exception_cb) { 18900 bpf_log(log, 18901 "%s programs cannot attach to exception callback\n", 18902 prog_extension ? "Extension" : "Tracing"); 18903 return -EINVAL; 18904 } 18905 conservative = aux->func_info_aux[subprog].unreliable; 18906 if (prog_extension) { 18907 if (conservative) { 18908 bpf_log(log, 18909 "Cannot replace static functions\n"); 18910 return -EINVAL; 18911 } 18912 if (!prog->jit_requested) { 18913 bpf_log(log, 18914 "Extension programs should be JITed\n"); 18915 return -EINVAL; 18916 } 18917 tgt_changes_pkt_data = aux->func 18918 ? aux->func[subprog]->aux->changes_pkt_data 18919 : aux->changes_pkt_data; 18920 if (prog->aux->changes_pkt_data && !tgt_changes_pkt_data) { 18921 bpf_log(log, 18922 "Extension program changes packet data, while original does not\n"); 18923 return -EINVAL; 18924 } 18925 18926 tgt_might_sleep = aux->func 18927 ? aux->func[subprog]->aux->might_sleep 18928 : aux->might_sleep; 18929 if (prog->aux->might_sleep && !tgt_might_sleep) { 18930 bpf_log(log, 18931 "Extension program may sleep, while original does not\n"); 18932 return -EINVAL; 18933 } 18934 } 18935 if (!tgt_prog->jited) { 18936 bpf_log(log, "Can attach to only JITed progs\n"); 18937 return -EINVAL; 18938 } 18939 if (prog_tracing) { 18940 if (aux->attach_tracing_prog) { 18941 /* 18942 * Target program is an fentry/fexit which is already attached 18943 * to another tracing program. More levels of nesting 18944 * attachment are not allowed. 18945 */ 18946 bpf_log(log, "Cannot nest tracing program attach more than once\n"); 18947 return -EINVAL; 18948 } 18949 } else if (tgt_prog->type == prog->type) { 18950 /* 18951 * To avoid potential call chain cycles, prevent attaching of a 18952 * program extension to another extension. It's ok to attach 18953 * fentry/fexit to extension program. 18954 */ 18955 bpf_log(log, "Cannot recursively attach\n"); 18956 return -EINVAL; 18957 } 18958 if (tgt_prog->type == BPF_PROG_TYPE_TRACING && 18959 prog_extension && 18960 (tgt_prog->expected_attach_type == BPF_TRACE_FENTRY || 18961 tgt_prog->expected_attach_type == BPF_TRACE_FEXIT || 18962 tgt_prog->expected_attach_type == BPF_TRACE_FSESSION)) { 18963 /* Program extensions can extend all program types 18964 * except fentry/fexit. The reason is the following. 18965 * The fentry/fexit programs are used for performance 18966 * analysis, stats and can be attached to any program 18967 * type. When extension program is replacing XDP function 18968 * it is necessary to allow performance analysis of all 18969 * functions. Both original XDP program and its program 18970 * extension. Hence attaching fentry/fexit to 18971 * BPF_PROG_TYPE_EXT is allowed. If extending of 18972 * fentry/fexit was allowed it would be possible to create 18973 * long call chain fentry->extension->fentry->extension 18974 * beyond reasonable stack size. Hence extending fentry 18975 * is not allowed. 18976 */ 18977 bpf_log(log, "Cannot extend fentry/fexit/fsession\n"); 18978 return -EINVAL; 18979 } 18980 } else { 18981 if (prog_extension) { 18982 bpf_log(log, "Cannot replace kernel functions\n"); 18983 return -EINVAL; 18984 } 18985 } 18986 18987 switch (prog->expected_attach_type) { 18988 case BPF_TRACE_RAW_TP: 18989 if (tgt_prog) { 18990 bpf_log(log, 18991 "Only FENTRY/FEXIT/FSESSION progs are attachable to another BPF prog\n"); 18992 return -EINVAL; 18993 } 18994 if (!btf_type_is_typedef(t)) { 18995 bpf_log(log, "attach_btf_id %u is not a typedef\n", 18996 btf_id); 18997 return -EINVAL; 18998 } 18999 if (strncmp(prefix, tname, sizeof(prefix) - 1)) { 19000 bpf_log(log, "attach_btf_id %u points to wrong type name %s\n", 19001 btf_id, tname); 19002 return -EINVAL; 19003 } 19004 tname += sizeof(prefix) - 1; 19005 19006 /* The func_proto of "btf_trace_##tname" is generated from typedef without argument 19007 * names. Thus using bpf_raw_event_map to get argument names. 19008 */ 19009 btp = bpf_get_raw_tracepoint(tname); 19010 if (!btp) 19011 return -EINVAL; 19012 if (prog->sleepable && !tracepoint_is_faultable(btp->tp)) { 19013 bpf_log(log, "Sleepable program cannot attach to non-faultable tracepoint %s\n", 19014 tname); 19015 bpf_put_raw_tracepoint(btp); 19016 return -EINVAL; 19017 } 19018 fname = kallsyms_lookup((unsigned long)btp->bpf_func, NULL, NULL, NULL, 19019 trace_symbol); 19020 bpf_put_raw_tracepoint(btp); 19021 19022 if (fname) 19023 ret = btf_find_by_name_kind(btf, fname, BTF_KIND_FUNC); 19024 19025 if (!fname || ret < 0) { 19026 bpf_log(log, "Cannot find btf of tracepoint template, fall back to %s%s.\n", 19027 prefix, tname); 19028 t = btf_type_by_id(btf, t->type); 19029 if (!btf_type_is_ptr(t)) 19030 /* should never happen in valid vmlinux build */ 19031 return -EINVAL; 19032 } else { 19033 t = btf_type_by_id(btf, ret); 19034 if (!btf_type_is_func(t)) 19035 /* should never happen in valid vmlinux build */ 19036 return -EINVAL; 19037 } 19038 19039 t = btf_type_by_id(btf, t->type); 19040 if (!btf_type_is_func_proto(t)) 19041 /* should never happen in valid vmlinux build */ 19042 return -EINVAL; 19043 19044 break; 19045 case BPF_TRACE_ITER: 19046 if (!btf_type_is_func(t)) { 19047 bpf_log(log, "attach_btf_id %u is not a function\n", 19048 btf_id); 19049 return -EINVAL; 19050 } 19051 t = btf_type_by_id(btf, t->type); 19052 if (!btf_type_is_func_proto(t)) 19053 return -EINVAL; 19054 ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel); 19055 if (ret) 19056 return ret; 19057 break; 19058 default: 19059 if (!prog_extension) 19060 return -EINVAL; 19061 fallthrough; 19062 case BPF_MODIFY_RETURN: 19063 case BPF_LSM_MAC: 19064 case BPF_LSM_CGROUP: 19065 case BPF_TRACE_FENTRY: 19066 case BPF_TRACE_FEXIT: 19067 case BPF_TRACE_FSESSION: 19068 if (prog->expected_attach_type == BPF_TRACE_FSESSION && 19069 !bpf_jit_supports_fsession()) { 19070 bpf_log(log, "JIT does not support fsession\n"); 19071 return -EOPNOTSUPP; 19072 } 19073 if (!btf_type_is_func(t)) { 19074 bpf_log(log, "attach_btf_id %u is not a function\n", 19075 btf_id); 19076 return -EINVAL; 19077 } 19078 if (prog_extension && 19079 btf_check_type_match(log, prog, btf, t)) 19080 return -EINVAL; 19081 t = btf_type_by_id(btf, t->type); 19082 if (!btf_type_is_func_proto(t)) 19083 return -EINVAL; 19084 19085 if ((prog->aux->saved_dst_prog_type || prog->aux->saved_dst_attach_type) && 19086 (!tgt_prog || prog->aux->saved_dst_prog_type != tgt_prog->type || 19087 prog->aux->saved_dst_attach_type != tgt_prog->expected_attach_type)) 19088 return -EINVAL; 19089 19090 if (tgt_prog && conservative) 19091 t = NULL; 19092 19093 ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel); 19094 if (ret < 0) 19095 return ret; 19096 19097 if (tgt_prog) { 19098 if (subprog == 0) 19099 addr = (long) tgt_prog->bpf_func; 19100 else 19101 addr = (long) tgt_prog->aux->func[subprog]->bpf_func; 19102 } else { 19103 if (btf_is_module(btf)) { 19104 mod = btf_try_get_module(btf); 19105 if (mod) 19106 addr = find_kallsyms_symbol_value(mod, tname); 19107 else 19108 addr = 0; 19109 } else { 19110 addr = kallsyms_lookup_name(tname); 19111 } 19112 if (!addr) { 19113 module_put(mod); 19114 bpf_log(log, 19115 "The address of function %s cannot be found\n", 19116 tname); 19117 return -ENOENT; 19118 } 19119 } 19120 19121 if (prog->sleepable) { 19122 ret = -EINVAL; 19123 switch (prog->type) { 19124 case BPF_PROG_TYPE_TRACING: 19125 if (!check_attach_sleepable(btf_id, addr, tname)) 19126 ret = 0; 19127 /* fentry/fexit/fmod_ret progs can also be sleepable if they are 19128 * in the fmodret id set with the KF_SLEEPABLE flag. 19129 */ 19130 else { 19131 u32 *flags = btf_kfunc_is_modify_return(btf, btf_id, 19132 prog); 19133 19134 if (flags && (*flags & KF_SLEEPABLE)) 19135 ret = 0; 19136 } 19137 break; 19138 case BPF_PROG_TYPE_LSM: 19139 /* LSM progs check that they are attached to bpf_lsm_*() funcs. 19140 * Only some of them are sleepable. 19141 */ 19142 if (bpf_lsm_is_sleepable_hook(btf_id)) 19143 ret = 0; 19144 break; 19145 default: 19146 break; 19147 } 19148 if (ret) { 19149 module_put(mod); 19150 bpf_log(log, "%s is not sleepable\n", tname); 19151 return ret; 19152 } 19153 } else if (prog->expected_attach_type == BPF_MODIFY_RETURN) { 19154 if (tgt_prog) { 19155 module_put(mod); 19156 bpf_log(log, "can't modify return codes of BPF programs\n"); 19157 return -EINVAL; 19158 } 19159 ret = -EINVAL; 19160 if (btf_kfunc_is_modify_return(btf, btf_id, prog) || 19161 !check_attach_modify_return(addr, tname)) 19162 ret = 0; 19163 if (ret) { 19164 module_put(mod); 19165 bpf_log(log, "%s() is not modifiable\n", tname); 19166 return ret; 19167 } 19168 } 19169 19170 break; 19171 } 19172 tgt_info->tgt_addr = addr; 19173 tgt_info->tgt_name = tname; 19174 tgt_info->tgt_type = t; 19175 tgt_info->tgt_mod = mod; 19176 return 0; 19177 } 19178 19179 BTF_SET_START(btf_id_deny) 19180 BTF_ID_UNUSED 19181 #ifdef CONFIG_SMP 19182 BTF_ID(func, ___migrate_enable) 19183 BTF_ID(func, migrate_disable) 19184 BTF_ID(func, migrate_enable) 19185 #endif 19186 #if !defined CONFIG_PREEMPT_RCU && !defined CONFIG_TINY_RCU 19187 BTF_ID(func, rcu_read_unlock_strict) 19188 #endif 19189 #if defined(CONFIG_DEBUG_PREEMPT) || defined(CONFIG_TRACE_PREEMPT_TOGGLE) 19190 BTF_ID(func, preempt_count_add) 19191 BTF_ID(func, preempt_count_sub) 19192 #endif 19193 #ifdef CONFIG_PREEMPT_RCU 19194 BTF_ID(func, __rcu_read_lock) 19195 BTF_ID(func, __rcu_read_unlock) 19196 #endif 19197 BTF_SET_END(btf_id_deny) 19198 19199 /* fexit and fmod_ret can't be used to attach to __noreturn functions. 19200 * Currently, we must manually list all __noreturn functions here. Once a more 19201 * robust solution is implemented, this workaround can be removed. 19202 */ 19203 BTF_SET_START(noreturn_deny) 19204 #ifdef CONFIG_IA32_EMULATION 19205 BTF_ID(func, __ia32_sys_exit) 19206 BTF_ID(func, __ia32_sys_exit_group) 19207 #endif 19208 #ifdef CONFIG_KUNIT 19209 BTF_ID(func, __kunit_abort) 19210 BTF_ID(func, kunit_try_catch_throw) 19211 #endif 19212 #ifdef CONFIG_MODULES 19213 BTF_ID(func, __module_put_and_kthread_exit) 19214 #endif 19215 #ifdef CONFIG_X86_64 19216 BTF_ID(func, __x64_sys_exit) 19217 BTF_ID(func, __x64_sys_exit_group) 19218 #endif 19219 BTF_ID(func, do_exit) 19220 BTF_ID(func, do_group_exit) 19221 BTF_ID(func, kthread_complete_and_exit) 19222 BTF_ID(func, make_task_dead) 19223 BTF_SET_END(noreturn_deny) 19224 19225 static bool can_be_sleepable(struct bpf_prog *prog) 19226 { 19227 if (prog->type == BPF_PROG_TYPE_TRACING) { 19228 switch (prog->expected_attach_type) { 19229 case BPF_TRACE_FENTRY: 19230 case BPF_TRACE_FEXIT: 19231 case BPF_MODIFY_RETURN: 19232 case BPF_TRACE_ITER: 19233 case BPF_TRACE_FSESSION: 19234 case BPF_TRACE_RAW_TP: 19235 return true; 19236 default: 19237 return false; 19238 } 19239 } 19240 return prog->type == BPF_PROG_TYPE_LSM || 19241 prog->type == BPF_PROG_TYPE_KPROBE /* only for uprobes */ || 19242 prog->type == BPF_PROG_TYPE_STRUCT_OPS || 19243 prog->type == BPF_PROG_TYPE_RAW_TRACEPOINT || 19244 prog->type == BPF_PROG_TYPE_TRACEPOINT; 19245 } 19246 19247 static int check_attach_btf_id(struct bpf_verifier_env *env) 19248 { 19249 struct bpf_prog *prog = env->prog; 19250 struct bpf_prog *tgt_prog = prog->aux->dst_prog; 19251 struct bpf_attach_target_info tgt_info = {}; 19252 u32 btf_id = prog->aux->attach_btf_id; 19253 struct bpf_trampoline *tr; 19254 int ret; 19255 u64 key; 19256 19257 if (prog->type == BPF_PROG_TYPE_SYSCALL) { 19258 if (prog->sleepable) 19259 /* attach_btf_id checked to be zero already */ 19260 return 0; 19261 verbose(env, "Syscall programs can only be sleepable\n"); 19262 return -EINVAL; 19263 } 19264 19265 if (prog->sleepable && !can_be_sleepable(prog)) { 19266 verbose(env, "Program of this type cannot be sleepable\n"); 19267 return -EINVAL; 19268 } 19269 19270 if (prog->type == BPF_PROG_TYPE_STRUCT_OPS) 19271 return check_struct_ops_btf_id(env); 19272 19273 if (prog->type != BPF_PROG_TYPE_TRACING && 19274 prog->type != BPF_PROG_TYPE_LSM && 19275 prog->type != BPF_PROG_TYPE_EXT) 19276 return 0; 19277 19278 ret = bpf_check_attach_target(&env->log, prog, tgt_prog, btf_id, &tgt_info); 19279 if (ret) 19280 return ret; 19281 19282 if (tgt_prog && prog->type == BPF_PROG_TYPE_EXT) { 19283 /* to make freplace equivalent to their targets, they need to 19284 * inherit env->ops and expected_attach_type for the rest of the 19285 * verification 19286 */ 19287 env->ops = bpf_verifier_ops[tgt_prog->type]; 19288 prog->expected_attach_type = tgt_prog->expected_attach_type; 19289 } 19290 19291 /* store info about the attachment target that will be used later */ 19292 prog->aux->attach_func_proto = tgt_info.tgt_type; 19293 prog->aux->attach_func_name = tgt_info.tgt_name; 19294 prog->aux->mod = tgt_info.tgt_mod; 19295 19296 if (tgt_prog) { 19297 prog->aux->saved_dst_prog_type = tgt_prog->type; 19298 prog->aux->saved_dst_attach_type = tgt_prog->expected_attach_type; 19299 } 19300 19301 if (prog->expected_attach_type == BPF_TRACE_RAW_TP) { 19302 prog->aux->attach_btf_trace = true; 19303 return 0; 19304 } else if (prog->expected_attach_type == BPF_TRACE_ITER) { 19305 return bpf_iter_prog_supported(prog); 19306 } 19307 19308 if (prog->type == BPF_PROG_TYPE_LSM) { 19309 ret = bpf_lsm_verify_prog(&env->log, prog); 19310 if (ret < 0) 19311 return ret; 19312 } else if (prog->type == BPF_PROG_TYPE_TRACING && 19313 btf_id_set_contains(&btf_id_deny, btf_id)) { 19314 verbose(env, "Attaching tracing programs to function '%s' is rejected.\n", 19315 tgt_info.tgt_name); 19316 return -EINVAL; 19317 } else if ((prog->expected_attach_type == BPF_TRACE_FEXIT || 19318 prog->expected_attach_type == BPF_TRACE_FSESSION || 19319 prog->expected_attach_type == BPF_MODIFY_RETURN) && 19320 btf_id_set_contains(&noreturn_deny, btf_id)) { 19321 verbose(env, "Attaching fexit/fsession/fmod_ret to __noreturn function '%s' is rejected.\n", 19322 tgt_info.tgt_name); 19323 return -EINVAL; 19324 } 19325 19326 key = bpf_trampoline_compute_key(tgt_prog, prog->aux->attach_btf, btf_id); 19327 tr = bpf_trampoline_get(key, &tgt_info); 19328 if (!tr) 19329 return -ENOMEM; 19330 19331 if (tgt_prog && tgt_prog->aux->tail_call_reachable) 19332 tr->flags = BPF_TRAMP_F_TAIL_CALL_CTX; 19333 19334 prog->aux->dst_trampoline = tr; 19335 return 0; 19336 } 19337 19338 struct btf *bpf_get_btf_vmlinux(void) 19339 { 19340 if (!btf_vmlinux && IS_ENABLED(CONFIG_DEBUG_INFO_BTF)) { 19341 mutex_lock(&bpf_verifier_lock); 19342 if (!btf_vmlinux) 19343 btf_vmlinux = btf_parse_vmlinux(); 19344 mutex_unlock(&bpf_verifier_lock); 19345 } 19346 return btf_vmlinux; 19347 } 19348 19349 /* 19350 * The add_fd_from_fd_array() is executed only if fd_array_cnt is non-zero. In 19351 * this case expect that every file descriptor in the array is either a map or 19352 * a BTF. Everything else is considered to be trash. 19353 */ 19354 static int add_fd_from_fd_array(struct bpf_verifier_env *env, int fd) 19355 { 19356 struct bpf_map *map; 19357 struct btf *btf; 19358 CLASS(fd, f)(fd); 19359 int err; 19360 19361 map = __bpf_map_get(f); 19362 if (!IS_ERR(map)) { 19363 err = __add_used_map(env, map); 19364 if (err < 0) 19365 return err; 19366 return 0; 19367 } 19368 19369 btf = __btf_get_by_fd(f); 19370 if (!IS_ERR(btf)) { 19371 btf_get(btf); 19372 return __add_used_btf(env, btf); 19373 } 19374 19375 verbose(env, "fd %d is not pointing to valid bpf_map or btf\n", fd); 19376 return PTR_ERR(map); 19377 } 19378 19379 static int process_fd_array(struct bpf_verifier_env *env, union bpf_attr *attr, bpfptr_t uattr) 19380 { 19381 size_t size = sizeof(int); 19382 int ret; 19383 int fd; 19384 u32 i; 19385 19386 env->fd_array = make_bpfptr(attr->fd_array, uattr.is_kernel); 19387 19388 /* 19389 * The only difference between old (no fd_array_cnt is given) and new 19390 * APIs is that in the latter case the fd_array is expected to be 19391 * continuous and is scanned for map fds right away 19392 */ 19393 if (!attr->fd_array_cnt) 19394 return 0; 19395 19396 /* Check for integer overflow */ 19397 if (attr->fd_array_cnt >= (U32_MAX / size)) { 19398 verbose(env, "fd_array_cnt is too big (%u)\n", attr->fd_array_cnt); 19399 return -EINVAL; 19400 } 19401 19402 for (i = 0; i < attr->fd_array_cnt; i++) { 19403 if (copy_from_bpfptr_offset(&fd, env->fd_array, i * size, size)) 19404 return -EFAULT; 19405 19406 ret = add_fd_from_fd_array(env, fd); 19407 if (ret) 19408 return ret; 19409 } 19410 19411 return 0; 19412 } 19413 19414 /* replace a generic kfunc with a specialized version if necessary */ 19415 static int specialize_kfunc(struct bpf_verifier_env *env, struct bpf_kfunc_desc *desc, int insn_idx) 19416 { 19417 struct bpf_prog *prog = env->prog; 19418 bool seen_direct_write; 19419 void *xdp_kfunc; 19420 bool is_rdonly; 19421 u32 func_id = desc->func_id; 19422 u16 offset = desc->offset; 19423 unsigned long addr = desc->addr; 19424 19425 if (offset) /* return if module BTF is used */ 19426 return 0; 19427 19428 if (bpf_dev_bound_kfunc_id(func_id)) { 19429 xdp_kfunc = bpf_dev_bound_resolve_kfunc(prog, func_id); 19430 if (xdp_kfunc) 19431 addr = (unsigned long)xdp_kfunc; 19432 /* fallback to default kfunc when not supported by netdev */ 19433 } else if (func_id == special_kfunc_list[KF_bpf_dynptr_from_skb]) { 19434 seen_direct_write = env->seen_direct_write; 19435 is_rdonly = !may_access_direct_pkt_data(env, NULL, BPF_WRITE); 19436 19437 if (is_rdonly) 19438 addr = (unsigned long)bpf_dynptr_from_skb_rdonly; 19439 19440 /* restore env->seen_direct_write to its original value, since 19441 * may_access_direct_pkt_data mutates it 19442 */ 19443 env->seen_direct_write = seen_direct_write; 19444 } else if (func_id == special_kfunc_list[KF_bpf_set_dentry_xattr]) { 19445 if (bpf_lsm_has_d_inode_locked(prog)) 19446 addr = (unsigned long)bpf_set_dentry_xattr_locked; 19447 } else if (func_id == special_kfunc_list[KF_bpf_remove_dentry_xattr]) { 19448 if (bpf_lsm_has_d_inode_locked(prog)) 19449 addr = (unsigned long)bpf_remove_dentry_xattr_locked; 19450 } else if (func_id == special_kfunc_list[KF_bpf_dynptr_from_file]) { 19451 if (!env->insn_aux_data[insn_idx].non_sleepable) 19452 addr = (unsigned long)bpf_dynptr_from_file_sleepable; 19453 } else if (func_id == special_kfunc_list[KF_bpf_arena_alloc_pages]) { 19454 if (env->insn_aux_data[insn_idx].non_sleepable) 19455 addr = (unsigned long)bpf_arena_alloc_pages_non_sleepable; 19456 } else if (func_id == special_kfunc_list[KF_bpf_arena_free_pages]) { 19457 if (env->insn_aux_data[insn_idx].non_sleepable) 19458 addr = (unsigned long)bpf_arena_free_pages_non_sleepable; 19459 } 19460 desc->addr = addr; 19461 return 0; 19462 } 19463 19464 static void __fixup_collection_insert_kfunc(struct bpf_insn_aux_data *insn_aux, 19465 u16 struct_meta_reg, 19466 u16 node_offset_reg, 19467 struct bpf_insn *insn, 19468 struct bpf_insn *insn_buf, 19469 int *cnt) 19470 { 19471 struct btf_struct_meta *kptr_struct_meta = insn_aux->kptr_struct_meta; 19472 struct bpf_insn addr[2] = { BPF_LD_IMM64(struct_meta_reg, (long)kptr_struct_meta) }; 19473 19474 insn_buf[0] = addr[0]; 19475 insn_buf[1] = addr[1]; 19476 insn_buf[2] = BPF_MOV64_IMM(node_offset_reg, insn_aux->insert_off); 19477 insn_buf[3] = *insn; 19478 *cnt = 4; 19479 } 19480 19481 int bpf_fixup_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn, 19482 struct bpf_insn *insn_buf, int insn_idx, int *cnt) 19483 { 19484 struct bpf_kfunc_desc *desc; 19485 int err; 19486 19487 if (!insn->imm) { 19488 verbose(env, "invalid kernel function call not eliminated in verifier pass\n"); 19489 return -EINVAL; 19490 } 19491 19492 *cnt = 0; 19493 19494 /* insn->imm has the btf func_id. Replace it with an offset relative to 19495 * __bpf_call_base, unless the JIT needs to call functions that are 19496 * further than 32 bits away (bpf_jit_supports_far_kfunc_call()). 19497 */ 19498 desc = find_kfunc_desc(env->prog, insn->imm, insn->off); 19499 if (!desc) { 19500 verifier_bug(env, "kernel function descriptor not found for func_id %u", 19501 insn->imm); 19502 return -EFAULT; 19503 } 19504 19505 err = specialize_kfunc(env, desc, insn_idx); 19506 if (err) 19507 return err; 19508 19509 if (!bpf_jit_supports_far_kfunc_call()) 19510 insn->imm = BPF_CALL_IMM(desc->addr); 19511 19512 if (is_bpf_obj_new_kfunc(desc->func_id) || is_bpf_percpu_obj_new_kfunc(desc->func_id)) { 19513 struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta; 19514 struct bpf_insn addr[2] = { BPF_LD_IMM64(BPF_REG_2, (long)kptr_struct_meta) }; 19515 u64 obj_new_size = env->insn_aux_data[insn_idx].obj_new_size; 19516 19517 if (is_bpf_percpu_obj_new_kfunc(desc->func_id) && kptr_struct_meta) { 19518 verifier_bug(env, "NULL kptr_struct_meta expected at insn_idx %d", 19519 insn_idx); 19520 return -EFAULT; 19521 } 19522 19523 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_1, obj_new_size); 19524 insn_buf[1] = addr[0]; 19525 insn_buf[2] = addr[1]; 19526 insn_buf[3] = *insn; 19527 *cnt = 4; 19528 } else if (is_bpf_obj_drop_kfunc(desc->func_id) || 19529 is_bpf_percpu_obj_drop_kfunc(desc->func_id) || 19530 is_bpf_refcount_acquire_kfunc(desc->func_id)) { 19531 struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta; 19532 struct bpf_insn addr[2] = { BPF_LD_IMM64(BPF_REG_2, (long)kptr_struct_meta) }; 19533 19534 if (is_bpf_percpu_obj_drop_kfunc(desc->func_id) && kptr_struct_meta) { 19535 verifier_bug(env, "NULL kptr_struct_meta expected at insn_idx %d", 19536 insn_idx); 19537 return -EFAULT; 19538 } 19539 19540 if (is_bpf_refcount_acquire_kfunc(desc->func_id) && !kptr_struct_meta) { 19541 verifier_bug(env, "kptr_struct_meta expected at insn_idx %d", 19542 insn_idx); 19543 return -EFAULT; 19544 } 19545 19546 insn_buf[0] = addr[0]; 19547 insn_buf[1] = addr[1]; 19548 insn_buf[2] = *insn; 19549 *cnt = 3; 19550 } else if (is_bpf_list_push_kfunc(desc->func_id) || 19551 is_bpf_rbtree_add_kfunc(desc->func_id)) { 19552 struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta; 19553 int struct_meta_reg = BPF_REG_3; 19554 int node_offset_reg = BPF_REG_4; 19555 19556 /* list_add/rbtree_add have an extra arg (prev/less), 19557 * so args-to-fixup are in diff regs. 19558 */ 19559 if (desc->func_id == special_kfunc_list[KF_bpf_list_add] || 19560 is_bpf_rbtree_add_kfunc(desc->func_id)) { 19561 struct_meta_reg = BPF_REG_4; 19562 node_offset_reg = BPF_REG_5; 19563 } 19564 19565 if (!kptr_struct_meta) { 19566 verifier_bug(env, "kptr_struct_meta expected at insn_idx %d", 19567 insn_idx); 19568 return -EFAULT; 19569 } 19570 19571 __fixup_collection_insert_kfunc(&env->insn_aux_data[insn_idx], struct_meta_reg, 19572 node_offset_reg, insn, insn_buf, cnt); 19573 } else if (desc->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx] || 19574 desc->func_id == special_kfunc_list[KF_bpf_rdonly_cast]) { 19575 insn_buf[0] = BPF_MOV64_REG(BPF_REG_0, BPF_REG_1); 19576 *cnt = 1; 19577 } else if (desc->func_id == special_kfunc_list[KF_bpf_session_is_return] && 19578 env->prog->expected_attach_type == BPF_TRACE_FSESSION) { 19579 /* 19580 * inline the bpf_session_is_return() for fsession: 19581 * bool bpf_session_is_return(void *ctx) 19582 * { 19583 * return (((u64 *)ctx)[-1] >> BPF_TRAMP_IS_RETURN_SHIFT) & 1; 19584 * } 19585 */ 19586 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8); 19587 insn_buf[1] = BPF_ALU64_IMM(BPF_RSH, BPF_REG_0, BPF_TRAMP_IS_RETURN_SHIFT); 19588 insn_buf[2] = BPF_ALU64_IMM(BPF_AND, BPF_REG_0, 1); 19589 *cnt = 3; 19590 } else if (desc->func_id == special_kfunc_list[KF_bpf_session_cookie] && 19591 env->prog->expected_attach_type == BPF_TRACE_FSESSION) { 19592 /* 19593 * inline bpf_session_cookie() for fsession: 19594 * __u64 *bpf_session_cookie(void *ctx) 19595 * { 19596 * u64 off = (((u64 *)ctx)[-1] >> BPF_TRAMP_COOKIE_INDEX_SHIFT) & 0xFF; 19597 * return &((u64 *)ctx)[-off]; 19598 * } 19599 */ 19600 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8); 19601 insn_buf[1] = BPF_ALU64_IMM(BPF_RSH, BPF_REG_0, BPF_TRAMP_COOKIE_INDEX_SHIFT); 19602 insn_buf[2] = BPF_ALU64_IMM(BPF_AND, BPF_REG_0, 0xFF); 19603 insn_buf[3] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_0, 3); 19604 insn_buf[4] = BPF_ALU64_REG(BPF_SUB, BPF_REG_0, BPF_REG_1); 19605 insn_buf[5] = BPF_ALU64_IMM(BPF_NEG, BPF_REG_0, 0); 19606 *cnt = 6; 19607 } 19608 19609 if (env->insn_aux_data[insn_idx].arg_prog) { 19610 u32 regno = env->insn_aux_data[insn_idx].arg_prog; 19611 struct bpf_insn ld_addrs[2] = { BPF_LD_IMM64(regno, (long)env->prog->aux) }; 19612 int idx = *cnt; 19613 19614 insn_buf[idx++] = ld_addrs[0]; 19615 insn_buf[idx++] = ld_addrs[1]; 19616 insn_buf[idx++] = *insn; 19617 *cnt = idx; 19618 } 19619 return 0; 19620 } 19621 19622 int bpf_check(struct bpf_prog **prog, union bpf_attr *attr, bpfptr_t uattr, 19623 struct bpf_log_attr *attr_log) 19624 { 19625 u64 start_time = ktime_get_ns(); 19626 struct bpf_verifier_env *env; 19627 int i, len, ret = -EINVAL, err; 19628 bool is_priv; 19629 19630 BTF_TYPE_EMIT(enum bpf_features); 19631 19632 /* no program is valid */ 19633 if (ARRAY_SIZE(bpf_verifier_ops) == 0) 19634 return -EINVAL; 19635 19636 /* 'struct bpf_verifier_env' can be global, but since it's not small, 19637 * allocate/free it every time bpf_check() is called 19638 */ 19639 env = kvzalloc_obj(struct bpf_verifier_env, GFP_KERNEL_ACCOUNT); 19640 if (!env) 19641 return -ENOMEM; 19642 19643 env->bt.env = env; 19644 19645 len = (*prog)->len; 19646 env->insn_aux_data = 19647 vzalloc(array_size(sizeof(struct bpf_insn_aux_data), len)); 19648 ret = -ENOMEM; 19649 if (!env->insn_aux_data) 19650 goto err_free_env; 19651 for (i = 0; i < len; i++) 19652 env->insn_aux_data[i].orig_idx = i; 19653 env->succ = bpf_iarray_realloc(NULL, 2); 19654 if (!env->succ) 19655 goto err_free_env; 19656 env->prog = *prog; 19657 env->ops = bpf_verifier_ops[env->prog->type]; 19658 19659 env->allow_ptr_leaks = bpf_allow_ptr_leaks(env->prog->aux->token); 19660 env->allow_uninit_stack = bpf_allow_uninit_stack(env->prog->aux->token); 19661 env->bypass_spec_v1 = bpf_bypass_spec_v1(env->prog->aux->token); 19662 env->bypass_spec_v4 = bpf_bypass_spec_v4(env->prog->aux->token); 19663 env->bpf_capable = is_priv = bpf_token_capable(env->prog->aux->token, CAP_BPF); 19664 19665 bpf_get_btf_vmlinux(); 19666 19667 /* grab the mutex to protect few globals used by verifier */ 19668 if (!is_priv) 19669 mutex_lock(&bpf_verifier_lock); 19670 19671 /* user could have requested verbose verifier output 19672 * and supplied buffer to store the verification trace 19673 */ 19674 ret = bpf_vlog_init(&env->log, attr_log->level, attr_log->ubuf, attr_log->size); 19675 if (ret) 19676 goto err_unlock; 19677 19678 ret = process_fd_array(env, attr, uattr); 19679 if (ret) 19680 goto skip_full_check; 19681 19682 mark_verifier_state_clean(env); 19683 19684 if (IS_ERR(btf_vmlinux)) { 19685 /* Either gcc or pahole or kernel are broken. */ 19686 verbose(env, "in-kernel BTF is malformed\n"); 19687 ret = PTR_ERR(btf_vmlinux); 19688 goto skip_full_check; 19689 } 19690 19691 env->strict_alignment = !!(attr->prog_flags & BPF_F_STRICT_ALIGNMENT); 19692 if (!IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS)) 19693 env->strict_alignment = true; 19694 if (attr->prog_flags & BPF_F_ANY_ALIGNMENT) 19695 env->strict_alignment = false; 19696 19697 if (is_priv) 19698 env->test_state_freq = attr->prog_flags & BPF_F_TEST_STATE_FREQ; 19699 env->test_reg_invariants = attr->prog_flags & BPF_F_TEST_REG_INVARIANTS; 19700 19701 env->explored_states = kvzalloc_objs(struct list_head, 19702 state_htab_size(env), 19703 GFP_KERNEL_ACCOUNT); 19704 ret = -ENOMEM; 19705 if (!env->explored_states) 19706 goto skip_full_check; 19707 19708 for (i = 0; i < state_htab_size(env); i++) 19709 INIT_LIST_HEAD(&env->explored_states[i]); 19710 INIT_LIST_HEAD(&env->free_list); 19711 19712 ret = bpf_check_btf_info_early(env, attr, uattr); 19713 if (ret < 0) 19714 goto skip_full_check; 19715 19716 ret = add_subprog_and_kfunc(env); 19717 if (ret < 0) 19718 goto skip_full_check; 19719 19720 ret = check_subprogs(env); 19721 if (ret < 0) 19722 goto skip_full_check; 19723 19724 ret = bpf_check_btf_info(env, attr, uattr); 19725 if (ret < 0) 19726 goto skip_full_check; 19727 19728 ret = check_and_resolve_insns(env); 19729 if (ret < 0) 19730 goto skip_full_check; 19731 19732 if (bpf_prog_is_offloaded(env->prog->aux)) { 19733 ret = bpf_prog_offload_verifier_prep(env->prog); 19734 if (ret) 19735 goto skip_full_check; 19736 } 19737 19738 ret = bpf_check_cfg(env); 19739 if (ret < 0) 19740 goto skip_full_check; 19741 19742 ret = bpf_compute_postorder(env); 19743 if (ret < 0) 19744 goto skip_full_check; 19745 19746 ret = bpf_stack_liveness_init(env); 19747 if (ret) 19748 goto skip_full_check; 19749 19750 ret = check_attach_btf_id(env); 19751 if (ret) 19752 goto skip_full_check; 19753 19754 ret = bpf_compute_const_regs(env); 19755 if (ret < 0) 19756 goto skip_full_check; 19757 19758 ret = bpf_prune_dead_branches(env); 19759 if (ret < 0) 19760 goto skip_full_check; 19761 19762 ret = sort_subprogs_topo(env); 19763 if (ret < 0) 19764 goto skip_full_check; 19765 19766 ret = bpf_compute_scc(env); 19767 if (ret < 0) 19768 goto skip_full_check; 19769 19770 ret = bpf_compute_live_registers(env); 19771 if (ret < 0) 19772 goto skip_full_check; 19773 19774 ret = mark_fastcall_patterns(env); 19775 if (ret < 0) 19776 goto skip_full_check; 19777 19778 ret = do_check_main(env); 19779 ret = ret ?: do_check_subprogs(env); 19780 19781 if (ret == 0 && bpf_prog_is_offloaded(env->prog->aux)) 19782 ret = bpf_prog_offload_finalize(env); 19783 19784 skip_full_check: 19785 kvfree(env->explored_states); 19786 19787 /* might decrease stack depth, keep it before passes that 19788 * allocate additional slots. 19789 */ 19790 if (ret == 0) 19791 ret = bpf_remove_fastcall_spills_fills(env); 19792 19793 if (ret == 0) 19794 ret = check_max_stack_depth(env); 19795 19796 /* instruction rewrites happen after this point */ 19797 if (ret == 0) 19798 ret = bpf_optimize_bpf_loop(env); 19799 19800 if (is_priv) { 19801 if (ret == 0) 19802 bpf_opt_hard_wire_dead_code_branches(env); 19803 if (ret == 0) 19804 ret = bpf_opt_remove_dead_code(env); 19805 if (ret == 0) 19806 ret = bpf_opt_remove_nops(env); 19807 } else { 19808 if (ret == 0) 19809 sanitize_dead_code(env); 19810 } 19811 19812 if (ret == 0) 19813 /* program is valid, convert *(u32*)(ctx + off) accesses */ 19814 ret = bpf_convert_ctx_accesses(env); 19815 19816 if (ret == 0) 19817 ret = bpf_do_misc_fixups(env); 19818 19819 /* do 32-bit optimization after insn patching has done so those patched 19820 * insns could be handled correctly. 19821 */ 19822 if (ret == 0 && !bpf_prog_is_offloaded(env->prog->aux)) { 19823 ret = bpf_opt_subreg_zext_lo32_rnd_hi32(env, attr); 19824 env->prog->aux->verifier_zext = bpf_jit_needs_zext() ? !ret 19825 : false; 19826 } 19827 19828 if (ret == 0) 19829 ret = bpf_fixup_call_args(env); 19830 19831 env->verification_time = ktime_get_ns() - start_time; 19832 print_verification_stats(env); 19833 env->prog->aux->verified_insns = env->insn_processed; 19834 19835 /* preserve original error even if log finalization is successful */ 19836 err = bpf_log_attr_finalize(attr_log, &env->log); 19837 if (err) 19838 ret = err; 19839 19840 if (ret) 19841 goto err_release_maps; 19842 19843 if (env->used_map_cnt) { 19844 /* if program passed verifier, update used_maps in bpf_prog_info */ 19845 env->prog->aux->used_maps = kmalloc_objs(env->used_maps[0], 19846 env->used_map_cnt, 19847 GFP_KERNEL_ACCOUNT); 19848 19849 if (!env->prog->aux->used_maps) { 19850 ret = -ENOMEM; 19851 goto err_release_maps; 19852 } 19853 19854 memcpy(env->prog->aux->used_maps, env->used_maps, 19855 sizeof(env->used_maps[0]) * env->used_map_cnt); 19856 env->prog->aux->used_map_cnt = env->used_map_cnt; 19857 } 19858 if (env->used_btf_cnt) { 19859 /* if program passed verifier, update used_btfs in bpf_prog_aux */ 19860 env->prog->aux->used_btfs = kmalloc_objs(env->used_btfs[0], 19861 env->used_btf_cnt, 19862 GFP_KERNEL_ACCOUNT); 19863 if (!env->prog->aux->used_btfs) { 19864 ret = -ENOMEM; 19865 goto err_release_maps; 19866 } 19867 19868 memcpy(env->prog->aux->used_btfs, env->used_btfs, 19869 sizeof(env->used_btfs[0]) * env->used_btf_cnt); 19870 env->prog->aux->used_btf_cnt = env->used_btf_cnt; 19871 } 19872 if (env->used_map_cnt || env->used_btf_cnt) { 19873 /* program is valid. Convert pseudo bpf_ld_imm64 into generic 19874 * bpf_ld_imm64 instructions 19875 */ 19876 convert_pseudo_ld_imm64(env); 19877 } 19878 19879 adjust_btf_func(env); 19880 19881 /* extension progs temporarily inherit the attach_type of their targets 19882 for verification purposes, so set it back to zero before returning 19883 */ 19884 if (env->prog->type == BPF_PROG_TYPE_EXT) 19885 env->prog->expected_attach_type = 0; 19886 19887 env->prog = __bpf_prog_select_runtime(env, env->prog, &ret); 19888 19889 err_release_maps: 19890 if (ret) 19891 release_insn_arrays(env); 19892 if (!env->prog->aux->used_maps) 19893 /* if we didn't copy map pointers into bpf_prog_info, release 19894 * them now. Otherwise free_used_maps() will release them. 19895 */ 19896 release_maps(env); 19897 if (!env->prog->aux->used_btfs) 19898 release_btfs(env); 19899 19900 *prog = env->prog; 19901 19902 module_put(env->attach_btf_mod); 19903 err_unlock: 19904 if (!is_priv) 19905 mutex_unlock(&bpf_verifier_lock); 19906 bpf_clear_insn_aux_data(env, 0, env->prog->len); 19907 vfree(env->insn_aux_data); 19908 err_free_env: 19909 bpf_stack_liveness_free(env); 19910 kvfree(env->cfg.insn_postorder); 19911 kvfree(env->scc_info); 19912 kvfree(env->succ); 19913 kvfree(env->gotox_tmp_buf); 19914 kvfree(env); 19915 return ret; 19916 } 19917