1 // SPDX-License-Identifier: GPL-2.0-only 2 /* Copyright (c) 2011-2014 PLUMgrid, http://plumgrid.com 3 * Copyright (c) 2016 Facebook 4 * Copyright (c) 2018 Covalent IO, Inc. http://covalent.io 5 */ 6 #include <uapi/linux/btf.h> 7 #include <linux/bpf-cgroup.h> 8 #include <linux/kernel.h> 9 #include <linux/types.h> 10 #include <linux/slab.h> 11 #include <linux/bpf.h> 12 #include <linux/btf.h> 13 #include <linux/bpf_verifier.h> 14 #include <linux/filter.h> 15 #include <net/netlink.h> 16 #include <linux/file.h> 17 #include <linux/vmalloc.h> 18 #include <linux/stringify.h> 19 #include <linux/bsearch.h> 20 #include <linux/sort.h> 21 #include <linux/perf_event.h> 22 #include <linux/ctype.h> 23 #include <linux/error-injection.h> 24 #include <linux/bpf_lsm.h> 25 #include <linux/btf_ids.h> 26 #include <linux/poison.h> 27 #include <linux/module.h> 28 #include <linux/cpumask.h> 29 #include <linux/bpf_mem_alloc.h> 30 #include <net/xdp.h> 31 #include <linux/trace_events.h> 32 #include <linux/kallsyms.h> 33 34 #include "disasm.h" 35 36 static const struct bpf_verifier_ops * const bpf_verifier_ops[] = { 37 #define BPF_PROG_TYPE(_id, _name, prog_ctx_type, kern_ctx_type) \ 38 [_id] = & _name ## _verifier_ops, 39 #define BPF_MAP_TYPE(_id, _ops) 40 #define BPF_LINK_TYPE(_id, _name) 41 #include <linux/bpf_types.h> 42 #undef BPF_PROG_TYPE 43 #undef BPF_MAP_TYPE 44 #undef BPF_LINK_TYPE 45 }; 46 47 enum bpf_features { 48 BPF_FEAT_RDONLY_CAST_TO_VOID = 0, 49 BPF_FEAT_STREAMS = 1, 50 __MAX_BPF_FEAT, 51 }; 52 53 struct bpf_mem_alloc bpf_global_percpu_ma; 54 static bool bpf_global_percpu_ma_set; 55 56 /* bpf_check() is a static code analyzer that walks eBPF program 57 * instruction by instruction and updates register/stack state. 58 * All paths of conditional branches are analyzed until 'bpf_exit' insn. 59 * 60 * The first pass is depth-first-search to check that the program is a DAG. 61 * It rejects the following programs: 62 * - larger than BPF_MAXINSNS insns 63 * - if loop is present (detected via back-edge) 64 * - unreachable insns exist (shouldn't be a forest. program = one function) 65 * - out of bounds or malformed jumps 66 * The second pass is all possible path descent from the 1st insn. 67 * Since it's analyzing all paths through the program, the length of the 68 * analysis is limited to 64k insn, which may be hit even if total number of 69 * insn is less then 4K, but there are too many branches that change stack/regs. 70 * Number of 'branches to be analyzed' is limited to 1k 71 * 72 * On entry to each instruction, each register has a type, and the instruction 73 * changes the types of the registers depending on instruction semantics. 74 * If instruction is BPF_MOV64_REG(BPF_REG_1, BPF_REG_5), then type of R5 is 75 * copied to R1. 76 * 77 * All registers are 64-bit. 78 * R0 - return register 79 * R1-R5 argument passing registers 80 * R6-R9 callee saved registers 81 * R10 - frame pointer read-only 82 * 83 * At the start of BPF program the register R1 contains a pointer to bpf_context 84 * and has type PTR_TO_CTX. 85 * 86 * Verifier tracks arithmetic operations on pointers in case: 87 * BPF_MOV64_REG(BPF_REG_1, BPF_REG_10), 88 * BPF_ALU64_IMM(BPF_ADD, BPF_REG_1, -20), 89 * 1st insn copies R10 (which has FRAME_PTR) type into R1 90 * and 2nd arithmetic instruction is pattern matched to recognize 91 * that it wants to construct a pointer to some element within stack. 92 * So after 2nd insn, the register R1 has type PTR_TO_STACK 93 * (and -20 constant is saved for further stack bounds checking). 94 * Meaning that this reg is a pointer to stack plus known immediate constant. 95 * 96 * Most of the time the registers have SCALAR_VALUE type, which 97 * means the register has some value, but it's not a valid pointer. 98 * (like pointer plus pointer becomes SCALAR_VALUE type) 99 * 100 * When verifier sees load or store instructions the type of base register 101 * can be: PTR_TO_MAP_VALUE, PTR_TO_CTX, PTR_TO_STACK, PTR_TO_SOCKET. These are 102 * four pointer types recognized by check_mem_access() function. 103 * 104 * PTR_TO_MAP_VALUE means that this register is pointing to 'map element value' 105 * and the range of [ptr, ptr + map's value_size) is accessible. 106 * 107 * registers used to pass values to function calls are checked against 108 * function argument constraints. 109 * 110 * ARG_PTR_TO_MAP_KEY is one of such argument constraints. 111 * It means that the register type passed to this function must be 112 * PTR_TO_STACK and it will be used inside the function as 113 * 'pointer to map element key' 114 * 115 * For example the argument constraints for bpf_map_lookup_elem(): 116 * .ret_type = RET_PTR_TO_MAP_VALUE_OR_NULL, 117 * .arg1_type = ARG_CONST_MAP_PTR, 118 * .arg2_type = ARG_PTR_TO_MAP_KEY, 119 * 120 * ret_type says that this function returns 'pointer to map elem value or null' 121 * function expects 1st argument to be a const pointer to 'struct bpf_map' and 122 * 2nd argument should be a pointer to stack, which will be used inside 123 * the helper function as a pointer to map element key. 124 * 125 * On the kernel side the helper function looks like: 126 * u64 bpf_map_lookup_elem(u64 r1, u64 r2, u64 r3, u64 r4, u64 r5) 127 * { 128 * struct bpf_map *map = (struct bpf_map *) (unsigned long) r1; 129 * void *key = (void *) (unsigned long) r2; 130 * void *value; 131 * 132 * here kernel can access 'key' and 'map' pointers safely, knowing that 133 * [key, key + map->key_size) bytes are valid and were initialized on 134 * the stack of eBPF program. 135 * } 136 * 137 * Corresponding eBPF program may look like: 138 * BPF_MOV64_REG(BPF_REG_2, BPF_REG_10), // after this insn R2 type is FRAME_PTR 139 * BPF_ALU64_IMM(BPF_ADD, BPF_REG_2, -4), // after this insn R2 type is PTR_TO_STACK 140 * BPF_LD_MAP_FD(BPF_REG_1, map_fd), // after this insn R1 type is CONST_PTR_TO_MAP 141 * BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0, BPF_FUNC_map_lookup_elem), 142 * here verifier looks at prototype of map_lookup_elem() and sees: 143 * .arg1_type == ARG_CONST_MAP_PTR and R1->type == CONST_PTR_TO_MAP, which is ok, 144 * Now verifier knows that this map has key of R1->map_ptr->key_size bytes 145 * 146 * Then .arg2_type == ARG_PTR_TO_MAP_KEY and R2->type == PTR_TO_STACK, ok so far, 147 * Now verifier checks that [R2, R2 + map's key_size) are within stack limits 148 * and were initialized prior to this call. 149 * If it's ok, then verifier allows this BPF_CALL insn and looks at 150 * .ret_type which is RET_PTR_TO_MAP_VALUE_OR_NULL, so it sets 151 * R0->type = PTR_TO_MAP_VALUE_OR_NULL which means bpf_map_lookup_elem() function 152 * returns either pointer to map value or NULL. 153 * 154 * When type PTR_TO_MAP_VALUE_OR_NULL passes through 'if (reg != 0) goto +off' 155 * insn, the register holding that pointer in the true branch changes state to 156 * PTR_TO_MAP_VALUE and the same register changes state to CONST_IMM in the false 157 * branch. See check_cond_jmp_op(). 158 * 159 * After the call R0 is set to return type of the function and registers R1-R5 160 * are set to NOT_INIT to indicate that they are no longer readable. 161 * 162 * The following reference types represent a potential reference to a kernel 163 * resource which, after first being allocated, must be checked and freed by 164 * the BPF program: 165 * - PTR_TO_SOCKET_OR_NULL, PTR_TO_SOCKET 166 * 167 * When the verifier sees a helper call return a reference type, it allocates a 168 * pointer id for the reference and stores it in the current function state. 169 * Similar to the way that PTR_TO_MAP_VALUE_OR_NULL is converted into 170 * PTR_TO_MAP_VALUE, PTR_TO_SOCKET_OR_NULL becomes PTR_TO_SOCKET when the type 171 * passes through a NULL-check conditional. For the branch wherein the state is 172 * changed to CONST_IMM, the verifier releases the reference. 173 * 174 * For each helper function that allocates a reference, such as 175 * bpf_sk_lookup_tcp(), there is a corresponding release function, such as 176 * bpf_sk_release(). When a reference type passes into the release function, 177 * the verifier also releases the reference. If any unchecked or unreleased 178 * reference remains at the end of the program, the verifier rejects it. 179 */ 180 181 /* verifier_state + insn_idx are pushed to stack when branch is encountered */ 182 struct bpf_verifier_stack_elem { 183 /* verifier state is 'st' 184 * before processing instruction 'insn_idx' 185 * and after processing instruction 'prev_insn_idx' 186 */ 187 struct bpf_verifier_state st; 188 int insn_idx; 189 int prev_insn_idx; 190 struct bpf_verifier_stack_elem *next; 191 /* length of verifier log at the time this state was pushed on stack */ 192 u32 log_pos; 193 }; 194 195 #define BPF_COMPLEXITY_LIMIT_JMP_SEQ 8192 196 #define BPF_COMPLEXITY_LIMIT_STATES 64 197 198 #define BPF_MAP_KEY_POISON (1ULL << 63) 199 #define BPF_MAP_KEY_SEEN (1ULL << 62) 200 201 #define BPF_GLOBAL_PERCPU_MA_MAX_SIZE 512 202 203 #define BPF_PRIV_STACK_MIN_SIZE 64 204 205 static int acquire_reference(struct bpf_verifier_env *env, int insn_idx); 206 static int release_reference_nomark(struct bpf_verifier_state *state, int ref_obj_id); 207 static int release_reference(struct bpf_verifier_env *env, int ref_obj_id); 208 static void invalidate_non_owning_refs(struct bpf_verifier_env *env); 209 static bool in_rbtree_lock_required_cb(struct bpf_verifier_env *env); 210 static int ref_set_non_owning(struct bpf_verifier_env *env, 211 struct bpf_reg_state *reg); 212 static void specialize_kfunc(struct bpf_verifier_env *env, 213 u32 func_id, u16 offset, unsigned long *addr); 214 static bool is_trusted_reg(const struct bpf_reg_state *reg); 215 216 static bool bpf_map_ptr_poisoned(const struct bpf_insn_aux_data *aux) 217 { 218 return aux->map_ptr_state.poison; 219 } 220 221 static bool bpf_map_ptr_unpriv(const struct bpf_insn_aux_data *aux) 222 { 223 return aux->map_ptr_state.unpriv; 224 } 225 226 static void bpf_map_ptr_store(struct bpf_insn_aux_data *aux, 227 struct bpf_map *map, 228 bool unpriv, bool poison) 229 { 230 unpriv |= bpf_map_ptr_unpriv(aux); 231 aux->map_ptr_state.unpriv = unpriv; 232 aux->map_ptr_state.poison = poison; 233 aux->map_ptr_state.map_ptr = map; 234 } 235 236 static bool bpf_map_key_poisoned(const struct bpf_insn_aux_data *aux) 237 { 238 return aux->map_key_state & BPF_MAP_KEY_POISON; 239 } 240 241 static bool bpf_map_key_unseen(const struct bpf_insn_aux_data *aux) 242 { 243 return !(aux->map_key_state & BPF_MAP_KEY_SEEN); 244 } 245 246 static u64 bpf_map_key_immediate(const struct bpf_insn_aux_data *aux) 247 { 248 return aux->map_key_state & ~(BPF_MAP_KEY_SEEN | BPF_MAP_KEY_POISON); 249 } 250 251 static void bpf_map_key_store(struct bpf_insn_aux_data *aux, u64 state) 252 { 253 bool poisoned = bpf_map_key_poisoned(aux); 254 255 aux->map_key_state = state | BPF_MAP_KEY_SEEN | 256 (poisoned ? BPF_MAP_KEY_POISON : 0ULL); 257 } 258 259 static bool bpf_helper_call(const struct bpf_insn *insn) 260 { 261 return insn->code == (BPF_JMP | BPF_CALL) && 262 insn->src_reg == 0; 263 } 264 265 static bool bpf_pseudo_call(const struct bpf_insn *insn) 266 { 267 return insn->code == (BPF_JMP | BPF_CALL) && 268 insn->src_reg == BPF_PSEUDO_CALL; 269 } 270 271 static bool bpf_pseudo_kfunc_call(const struct bpf_insn *insn) 272 { 273 return insn->code == (BPF_JMP | BPF_CALL) && 274 insn->src_reg == BPF_PSEUDO_KFUNC_CALL; 275 } 276 277 struct bpf_call_arg_meta { 278 struct bpf_map *map_ptr; 279 bool raw_mode; 280 bool pkt_access; 281 u8 release_regno; 282 int regno; 283 int access_size; 284 int mem_size; 285 u64 msize_max_value; 286 int ref_obj_id; 287 int dynptr_id; 288 int map_uid; 289 int func_id; 290 struct btf *btf; 291 u32 btf_id; 292 struct btf *ret_btf; 293 u32 ret_btf_id; 294 u32 subprogno; 295 struct btf_field *kptr_field; 296 s64 const_map_key; 297 }; 298 299 struct bpf_kfunc_call_arg_meta { 300 /* In parameters */ 301 struct btf *btf; 302 u32 func_id; 303 u32 kfunc_flags; 304 const struct btf_type *func_proto; 305 const char *func_name; 306 /* Out parameters */ 307 u32 ref_obj_id; 308 u8 release_regno; 309 bool r0_rdonly; 310 u32 ret_btf_id; 311 u64 r0_size; 312 u32 subprogno; 313 struct { 314 u64 value; 315 bool found; 316 } arg_constant; 317 318 /* arg_{btf,btf_id,owning_ref} are used by kfunc-specific handling, 319 * generally to pass info about user-defined local kptr types to later 320 * verification logic 321 * bpf_obj_drop/bpf_percpu_obj_drop 322 * Record the local kptr type to be drop'd 323 * bpf_refcount_acquire (via KF_ARG_PTR_TO_REFCOUNTED_KPTR arg type) 324 * Record the local kptr type to be refcount_incr'd and use 325 * arg_owning_ref to determine whether refcount_acquire should be 326 * fallible 327 */ 328 struct btf *arg_btf; 329 u32 arg_btf_id; 330 bool arg_owning_ref; 331 bool arg_prog; 332 333 struct { 334 struct btf_field *field; 335 } arg_list_head; 336 struct { 337 struct btf_field *field; 338 } arg_rbtree_root; 339 struct { 340 enum bpf_dynptr_type type; 341 u32 id; 342 u32 ref_obj_id; 343 } initialized_dynptr; 344 struct { 345 u8 spi; 346 u8 frameno; 347 } iter; 348 struct { 349 struct bpf_map *ptr; 350 int uid; 351 } map; 352 u64 mem_size; 353 }; 354 355 struct btf *btf_vmlinux; 356 357 static const char *btf_type_name(const struct btf *btf, u32 id) 358 { 359 return btf_name_by_offset(btf, btf_type_by_id(btf, id)->name_off); 360 } 361 362 static DEFINE_MUTEX(bpf_verifier_lock); 363 static DEFINE_MUTEX(bpf_percpu_ma_lock); 364 365 __printf(2, 3) static void verbose(void *private_data, const char *fmt, ...) 366 { 367 struct bpf_verifier_env *env = private_data; 368 va_list args; 369 370 if (!bpf_verifier_log_needed(&env->log)) 371 return; 372 373 va_start(args, fmt); 374 bpf_verifier_vlog(&env->log, fmt, args); 375 va_end(args); 376 } 377 378 static void verbose_invalid_scalar(struct bpf_verifier_env *env, 379 struct bpf_reg_state *reg, 380 struct bpf_retval_range range, const char *ctx, 381 const char *reg_name) 382 { 383 bool unknown = true; 384 385 verbose(env, "%s the register %s has", ctx, reg_name); 386 if (reg->smin_value > S64_MIN) { 387 verbose(env, " smin=%lld", reg->smin_value); 388 unknown = false; 389 } 390 if (reg->smax_value < S64_MAX) { 391 verbose(env, " smax=%lld", reg->smax_value); 392 unknown = false; 393 } 394 if (unknown) 395 verbose(env, " unknown scalar value"); 396 verbose(env, " should have been in [%d, %d]\n", range.minval, range.maxval); 397 } 398 399 static bool reg_not_null(const struct bpf_reg_state *reg) 400 { 401 enum bpf_reg_type type; 402 403 type = reg->type; 404 if (type_may_be_null(type)) 405 return false; 406 407 type = base_type(type); 408 return type == PTR_TO_SOCKET || 409 type == PTR_TO_TCP_SOCK || 410 type == PTR_TO_MAP_VALUE || 411 type == PTR_TO_MAP_KEY || 412 type == PTR_TO_SOCK_COMMON || 413 (type == PTR_TO_BTF_ID && is_trusted_reg(reg)) || 414 (type == PTR_TO_MEM && !(reg->type & PTR_UNTRUSTED)) || 415 type == CONST_PTR_TO_MAP; 416 } 417 418 static struct btf_record *reg_btf_record(const struct bpf_reg_state *reg) 419 { 420 struct btf_record *rec = NULL; 421 struct btf_struct_meta *meta; 422 423 if (reg->type == PTR_TO_MAP_VALUE) { 424 rec = reg->map_ptr->record; 425 } else if (type_is_ptr_alloc_obj(reg->type)) { 426 meta = btf_find_struct_meta(reg->btf, reg->btf_id); 427 if (meta) 428 rec = meta->record; 429 } 430 return rec; 431 } 432 433 static bool subprog_is_global(const struct bpf_verifier_env *env, int subprog) 434 { 435 struct bpf_func_info_aux *aux = env->prog->aux->func_info_aux; 436 437 return aux && aux[subprog].linkage == BTF_FUNC_GLOBAL; 438 } 439 440 static const char *subprog_name(const struct bpf_verifier_env *env, int subprog) 441 { 442 struct bpf_func_info *info; 443 444 if (!env->prog->aux->func_info) 445 return ""; 446 447 info = &env->prog->aux->func_info[subprog]; 448 return btf_type_name(env->prog->aux->btf, info->type_id); 449 } 450 451 static void mark_subprog_exc_cb(struct bpf_verifier_env *env, int subprog) 452 { 453 struct bpf_subprog_info *info = subprog_info(env, subprog); 454 455 info->is_cb = true; 456 info->is_async_cb = true; 457 info->is_exception_cb = true; 458 } 459 460 static bool subprog_is_exc_cb(struct bpf_verifier_env *env, int subprog) 461 { 462 return subprog_info(env, subprog)->is_exception_cb; 463 } 464 465 static bool reg_may_point_to_spin_lock(const struct bpf_reg_state *reg) 466 { 467 return btf_record_has_field(reg_btf_record(reg), BPF_SPIN_LOCK | BPF_RES_SPIN_LOCK); 468 } 469 470 static bool type_is_rdonly_mem(u32 type) 471 { 472 return type & MEM_RDONLY; 473 } 474 475 static bool is_acquire_function(enum bpf_func_id func_id, 476 const struct bpf_map *map) 477 { 478 enum bpf_map_type map_type = map ? map->map_type : BPF_MAP_TYPE_UNSPEC; 479 480 if (func_id == BPF_FUNC_sk_lookup_tcp || 481 func_id == BPF_FUNC_sk_lookup_udp || 482 func_id == BPF_FUNC_skc_lookup_tcp || 483 func_id == BPF_FUNC_ringbuf_reserve || 484 func_id == BPF_FUNC_kptr_xchg) 485 return true; 486 487 if (func_id == BPF_FUNC_map_lookup_elem && 488 (map_type == BPF_MAP_TYPE_SOCKMAP || 489 map_type == BPF_MAP_TYPE_SOCKHASH)) 490 return true; 491 492 return false; 493 } 494 495 static bool is_ptr_cast_function(enum bpf_func_id func_id) 496 { 497 return func_id == BPF_FUNC_tcp_sock || 498 func_id == BPF_FUNC_sk_fullsock || 499 func_id == BPF_FUNC_skc_to_tcp_sock || 500 func_id == BPF_FUNC_skc_to_tcp6_sock || 501 func_id == BPF_FUNC_skc_to_udp6_sock || 502 func_id == BPF_FUNC_skc_to_mptcp_sock || 503 func_id == BPF_FUNC_skc_to_tcp_timewait_sock || 504 func_id == BPF_FUNC_skc_to_tcp_request_sock; 505 } 506 507 static bool is_dynptr_ref_function(enum bpf_func_id func_id) 508 { 509 return func_id == BPF_FUNC_dynptr_data; 510 } 511 512 static bool is_sync_callback_calling_kfunc(u32 btf_id); 513 static bool is_async_callback_calling_kfunc(u32 btf_id); 514 static bool is_callback_calling_kfunc(u32 btf_id); 515 static bool is_bpf_throw_kfunc(struct bpf_insn *insn); 516 517 static bool is_bpf_wq_set_callback_impl_kfunc(u32 btf_id); 518 519 static bool is_sync_callback_calling_function(enum bpf_func_id func_id) 520 { 521 return func_id == BPF_FUNC_for_each_map_elem || 522 func_id == BPF_FUNC_find_vma || 523 func_id == BPF_FUNC_loop || 524 func_id == BPF_FUNC_user_ringbuf_drain; 525 } 526 527 static bool is_async_callback_calling_function(enum bpf_func_id func_id) 528 { 529 return func_id == BPF_FUNC_timer_set_callback; 530 } 531 532 static bool is_callback_calling_function(enum bpf_func_id func_id) 533 { 534 return is_sync_callback_calling_function(func_id) || 535 is_async_callback_calling_function(func_id); 536 } 537 538 static bool is_sync_callback_calling_insn(struct bpf_insn *insn) 539 { 540 return (bpf_helper_call(insn) && is_sync_callback_calling_function(insn->imm)) || 541 (bpf_pseudo_kfunc_call(insn) && is_sync_callback_calling_kfunc(insn->imm)); 542 } 543 544 static bool is_async_callback_calling_insn(struct bpf_insn *insn) 545 { 546 return (bpf_helper_call(insn) && is_async_callback_calling_function(insn->imm)) || 547 (bpf_pseudo_kfunc_call(insn) && is_async_callback_calling_kfunc(insn->imm)); 548 } 549 550 static bool is_may_goto_insn(struct bpf_insn *insn) 551 { 552 return insn->code == (BPF_JMP | BPF_JCOND) && insn->src_reg == BPF_MAY_GOTO; 553 } 554 555 static bool is_may_goto_insn_at(struct bpf_verifier_env *env, int insn_idx) 556 { 557 return is_may_goto_insn(&env->prog->insnsi[insn_idx]); 558 } 559 560 static bool is_storage_get_function(enum bpf_func_id func_id) 561 { 562 return func_id == BPF_FUNC_sk_storage_get || 563 func_id == BPF_FUNC_inode_storage_get || 564 func_id == BPF_FUNC_task_storage_get || 565 func_id == BPF_FUNC_cgrp_storage_get; 566 } 567 568 static bool helper_multiple_ref_obj_use(enum bpf_func_id func_id, 569 const struct bpf_map *map) 570 { 571 int ref_obj_uses = 0; 572 573 if (is_ptr_cast_function(func_id)) 574 ref_obj_uses++; 575 if (is_acquire_function(func_id, map)) 576 ref_obj_uses++; 577 if (is_dynptr_ref_function(func_id)) 578 ref_obj_uses++; 579 580 return ref_obj_uses > 1; 581 } 582 583 static bool is_cmpxchg_insn(const struct bpf_insn *insn) 584 { 585 return BPF_CLASS(insn->code) == BPF_STX && 586 BPF_MODE(insn->code) == BPF_ATOMIC && 587 insn->imm == BPF_CMPXCHG; 588 } 589 590 static bool is_atomic_load_insn(const struct bpf_insn *insn) 591 { 592 return BPF_CLASS(insn->code) == BPF_STX && 593 BPF_MODE(insn->code) == BPF_ATOMIC && 594 insn->imm == BPF_LOAD_ACQ; 595 } 596 597 static int __get_spi(s32 off) 598 { 599 return (-off - 1) / BPF_REG_SIZE; 600 } 601 602 static struct bpf_func_state *func(struct bpf_verifier_env *env, 603 const struct bpf_reg_state *reg) 604 { 605 struct bpf_verifier_state *cur = env->cur_state; 606 607 return cur->frame[reg->frameno]; 608 } 609 610 static bool is_spi_bounds_valid(struct bpf_func_state *state, int spi, int nr_slots) 611 { 612 int allocated_slots = state->allocated_stack / BPF_REG_SIZE; 613 614 /* We need to check that slots between [spi - nr_slots + 1, spi] are 615 * within [0, allocated_stack). 616 * 617 * Please note that the spi grows downwards. For example, a dynptr 618 * takes the size of two stack slots; the first slot will be at 619 * spi and the second slot will be at spi - 1. 620 */ 621 return spi - nr_slots + 1 >= 0 && spi < allocated_slots; 622 } 623 624 static int stack_slot_obj_get_spi(struct bpf_verifier_env *env, struct bpf_reg_state *reg, 625 const char *obj_kind, int nr_slots) 626 { 627 int off, spi; 628 629 if (!tnum_is_const(reg->var_off)) { 630 verbose(env, "%s has to be at a constant offset\n", obj_kind); 631 return -EINVAL; 632 } 633 634 off = reg->off + reg->var_off.value; 635 if (off % BPF_REG_SIZE) { 636 verbose(env, "cannot pass in %s at an offset=%d\n", obj_kind, off); 637 return -EINVAL; 638 } 639 640 spi = __get_spi(off); 641 if (spi + 1 < nr_slots) { 642 verbose(env, "cannot pass in %s at an offset=%d\n", obj_kind, off); 643 return -EINVAL; 644 } 645 646 if (!is_spi_bounds_valid(func(env, reg), spi, nr_slots)) 647 return -ERANGE; 648 return spi; 649 } 650 651 static int dynptr_get_spi(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 652 { 653 return stack_slot_obj_get_spi(env, reg, "dynptr", BPF_DYNPTR_NR_SLOTS); 654 } 655 656 static int iter_get_spi(struct bpf_verifier_env *env, struct bpf_reg_state *reg, int nr_slots) 657 { 658 return stack_slot_obj_get_spi(env, reg, "iter", nr_slots); 659 } 660 661 static int irq_flag_get_spi(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 662 { 663 return stack_slot_obj_get_spi(env, reg, "irq_flag", 1); 664 } 665 666 static enum bpf_dynptr_type arg_to_dynptr_type(enum bpf_arg_type arg_type) 667 { 668 switch (arg_type & DYNPTR_TYPE_FLAG_MASK) { 669 case DYNPTR_TYPE_LOCAL: 670 return BPF_DYNPTR_TYPE_LOCAL; 671 case DYNPTR_TYPE_RINGBUF: 672 return BPF_DYNPTR_TYPE_RINGBUF; 673 case DYNPTR_TYPE_SKB: 674 return BPF_DYNPTR_TYPE_SKB; 675 case DYNPTR_TYPE_XDP: 676 return BPF_DYNPTR_TYPE_XDP; 677 case DYNPTR_TYPE_SKB_META: 678 return BPF_DYNPTR_TYPE_SKB_META; 679 default: 680 return BPF_DYNPTR_TYPE_INVALID; 681 } 682 } 683 684 static enum bpf_type_flag get_dynptr_type_flag(enum bpf_dynptr_type type) 685 { 686 switch (type) { 687 case BPF_DYNPTR_TYPE_LOCAL: 688 return DYNPTR_TYPE_LOCAL; 689 case BPF_DYNPTR_TYPE_RINGBUF: 690 return DYNPTR_TYPE_RINGBUF; 691 case BPF_DYNPTR_TYPE_SKB: 692 return DYNPTR_TYPE_SKB; 693 case BPF_DYNPTR_TYPE_XDP: 694 return DYNPTR_TYPE_XDP; 695 case BPF_DYNPTR_TYPE_SKB_META: 696 return DYNPTR_TYPE_SKB_META; 697 default: 698 return 0; 699 } 700 } 701 702 static bool dynptr_type_refcounted(enum bpf_dynptr_type type) 703 { 704 return type == BPF_DYNPTR_TYPE_RINGBUF; 705 } 706 707 static void __mark_dynptr_reg(struct bpf_reg_state *reg, 708 enum bpf_dynptr_type type, 709 bool first_slot, int dynptr_id); 710 711 static void __mark_reg_not_init(const struct bpf_verifier_env *env, 712 struct bpf_reg_state *reg); 713 714 static void mark_dynptr_stack_regs(struct bpf_verifier_env *env, 715 struct bpf_reg_state *sreg1, 716 struct bpf_reg_state *sreg2, 717 enum bpf_dynptr_type type) 718 { 719 int id = ++env->id_gen; 720 721 __mark_dynptr_reg(sreg1, type, true, id); 722 __mark_dynptr_reg(sreg2, type, false, id); 723 } 724 725 static void mark_dynptr_cb_reg(struct bpf_verifier_env *env, 726 struct bpf_reg_state *reg, 727 enum bpf_dynptr_type type) 728 { 729 __mark_dynptr_reg(reg, type, true, ++env->id_gen); 730 } 731 732 static int destroy_if_dynptr_stack_slot(struct bpf_verifier_env *env, 733 struct bpf_func_state *state, int spi); 734 735 static int mark_stack_slots_dynptr(struct bpf_verifier_env *env, struct bpf_reg_state *reg, 736 enum bpf_arg_type arg_type, int insn_idx, int clone_ref_obj_id) 737 { 738 struct bpf_func_state *state = func(env, reg); 739 enum bpf_dynptr_type type; 740 int spi, i, err; 741 742 spi = dynptr_get_spi(env, reg); 743 if (spi < 0) 744 return spi; 745 746 /* We cannot assume both spi and spi - 1 belong to the same dynptr, 747 * hence we need to call destroy_if_dynptr_stack_slot twice for both, 748 * to ensure that for the following example: 749 * [d1][d1][d2][d2] 750 * spi 3 2 1 0 751 * So marking spi = 2 should lead to destruction of both d1 and d2. In 752 * case they do belong to same dynptr, second call won't see slot_type 753 * as STACK_DYNPTR and will simply skip destruction. 754 */ 755 err = destroy_if_dynptr_stack_slot(env, state, spi); 756 if (err) 757 return err; 758 err = destroy_if_dynptr_stack_slot(env, state, spi - 1); 759 if (err) 760 return err; 761 762 for (i = 0; i < BPF_REG_SIZE; i++) { 763 state->stack[spi].slot_type[i] = STACK_DYNPTR; 764 state->stack[spi - 1].slot_type[i] = STACK_DYNPTR; 765 } 766 767 type = arg_to_dynptr_type(arg_type); 768 if (type == BPF_DYNPTR_TYPE_INVALID) 769 return -EINVAL; 770 771 mark_dynptr_stack_regs(env, &state->stack[spi].spilled_ptr, 772 &state->stack[spi - 1].spilled_ptr, type); 773 774 if (dynptr_type_refcounted(type)) { 775 /* The id is used to track proper releasing */ 776 int id; 777 778 if (clone_ref_obj_id) 779 id = clone_ref_obj_id; 780 else 781 id = acquire_reference(env, insn_idx); 782 783 if (id < 0) 784 return id; 785 786 state->stack[spi].spilled_ptr.ref_obj_id = id; 787 state->stack[spi - 1].spilled_ptr.ref_obj_id = id; 788 } 789 790 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN; 791 state->stack[spi - 1].spilled_ptr.live |= REG_LIVE_WRITTEN; 792 793 return 0; 794 } 795 796 static void invalidate_dynptr(struct bpf_verifier_env *env, struct bpf_func_state *state, int spi) 797 { 798 int i; 799 800 for (i = 0; i < BPF_REG_SIZE; i++) { 801 state->stack[spi].slot_type[i] = STACK_INVALID; 802 state->stack[spi - 1].slot_type[i] = STACK_INVALID; 803 } 804 805 __mark_reg_not_init(env, &state->stack[spi].spilled_ptr); 806 __mark_reg_not_init(env, &state->stack[spi - 1].spilled_ptr); 807 808 /* Why do we need to set REG_LIVE_WRITTEN for STACK_INVALID slot? 809 * 810 * While we don't allow reading STACK_INVALID, it is still possible to 811 * do <8 byte writes marking some but not all slots as STACK_MISC. Then, 812 * helpers or insns can do partial read of that part without failing, 813 * but check_stack_range_initialized, check_stack_read_var_off, and 814 * check_stack_read_fixed_off will do mark_reg_read for all 8-bytes of 815 * the slot conservatively. Hence we need to prevent those liveness 816 * marking walks. 817 * 818 * This was not a problem before because STACK_INVALID is only set by 819 * default (where the default reg state has its reg->parent as NULL), or 820 * in clean_live_states after REG_LIVE_DONE (at which point 821 * mark_reg_read won't walk reg->parent chain), but not randomly during 822 * verifier state exploration (like we did above). Hence, for our case 823 * parentage chain will still be live (i.e. reg->parent may be 824 * non-NULL), while earlier reg->parent was NULL, so we need 825 * REG_LIVE_WRITTEN to screen off read marker propagation when it is 826 * done later on reads or by mark_dynptr_read as well to unnecessary 827 * mark registers in verifier state. 828 */ 829 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN; 830 state->stack[spi - 1].spilled_ptr.live |= REG_LIVE_WRITTEN; 831 } 832 833 static int unmark_stack_slots_dynptr(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 834 { 835 struct bpf_func_state *state = func(env, reg); 836 int spi, ref_obj_id, i; 837 838 spi = dynptr_get_spi(env, reg); 839 if (spi < 0) 840 return spi; 841 842 if (!dynptr_type_refcounted(state->stack[spi].spilled_ptr.dynptr.type)) { 843 invalidate_dynptr(env, state, spi); 844 return 0; 845 } 846 847 ref_obj_id = state->stack[spi].spilled_ptr.ref_obj_id; 848 849 /* If the dynptr has a ref_obj_id, then we need to invalidate 850 * two things: 851 * 852 * 1) Any dynptrs with a matching ref_obj_id (clones) 853 * 2) Any slices derived from this dynptr. 854 */ 855 856 /* Invalidate any slices associated with this dynptr */ 857 WARN_ON_ONCE(release_reference(env, ref_obj_id)); 858 859 /* Invalidate any dynptr clones */ 860 for (i = 1; i < state->allocated_stack / BPF_REG_SIZE; i++) { 861 if (state->stack[i].spilled_ptr.ref_obj_id != ref_obj_id) 862 continue; 863 864 /* it should always be the case that if the ref obj id 865 * matches then the stack slot also belongs to a 866 * dynptr 867 */ 868 if (state->stack[i].slot_type[0] != STACK_DYNPTR) { 869 verifier_bug(env, "misconfigured ref_obj_id"); 870 return -EFAULT; 871 } 872 if (state->stack[i].spilled_ptr.dynptr.first_slot) 873 invalidate_dynptr(env, state, i); 874 } 875 876 return 0; 877 } 878 879 static void __mark_reg_unknown(const struct bpf_verifier_env *env, 880 struct bpf_reg_state *reg); 881 882 static void mark_reg_invalid(const struct bpf_verifier_env *env, struct bpf_reg_state *reg) 883 { 884 if (!env->allow_ptr_leaks) 885 __mark_reg_not_init(env, reg); 886 else 887 __mark_reg_unknown(env, reg); 888 } 889 890 static int destroy_if_dynptr_stack_slot(struct bpf_verifier_env *env, 891 struct bpf_func_state *state, int spi) 892 { 893 struct bpf_func_state *fstate; 894 struct bpf_reg_state *dreg; 895 int i, dynptr_id; 896 897 /* We always ensure that STACK_DYNPTR is never set partially, 898 * hence just checking for slot_type[0] is enough. This is 899 * different for STACK_SPILL, where it may be only set for 900 * 1 byte, so code has to use is_spilled_reg. 901 */ 902 if (state->stack[spi].slot_type[0] != STACK_DYNPTR) 903 return 0; 904 905 /* Reposition spi to first slot */ 906 if (!state->stack[spi].spilled_ptr.dynptr.first_slot) 907 spi = spi + 1; 908 909 if (dynptr_type_refcounted(state->stack[spi].spilled_ptr.dynptr.type)) { 910 verbose(env, "cannot overwrite referenced dynptr\n"); 911 return -EINVAL; 912 } 913 914 mark_stack_slot_scratched(env, spi); 915 mark_stack_slot_scratched(env, spi - 1); 916 917 /* Writing partially to one dynptr stack slot destroys both. */ 918 for (i = 0; i < BPF_REG_SIZE; i++) { 919 state->stack[spi].slot_type[i] = STACK_INVALID; 920 state->stack[spi - 1].slot_type[i] = STACK_INVALID; 921 } 922 923 dynptr_id = state->stack[spi].spilled_ptr.id; 924 /* Invalidate any slices associated with this dynptr */ 925 bpf_for_each_reg_in_vstate(env->cur_state, fstate, dreg, ({ 926 /* Dynptr slices are only PTR_TO_MEM_OR_NULL and PTR_TO_MEM */ 927 if (dreg->type != (PTR_TO_MEM | PTR_MAYBE_NULL) && dreg->type != PTR_TO_MEM) 928 continue; 929 if (dreg->dynptr_id == dynptr_id) 930 mark_reg_invalid(env, dreg); 931 })); 932 933 /* Do not release reference state, we are destroying dynptr on stack, 934 * not using some helper to release it. Just reset register. 935 */ 936 __mark_reg_not_init(env, &state->stack[spi].spilled_ptr); 937 __mark_reg_not_init(env, &state->stack[spi - 1].spilled_ptr); 938 939 /* Same reason as unmark_stack_slots_dynptr above */ 940 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN; 941 state->stack[spi - 1].spilled_ptr.live |= REG_LIVE_WRITTEN; 942 943 return 0; 944 } 945 946 static bool is_dynptr_reg_valid_uninit(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 947 { 948 int spi; 949 950 if (reg->type == CONST_PTR_TO_DYNPTR) 951 return false; 952 953 spi = dynptr_get_spi(env, reg); 954 955 /* -ERANGE (i.e. spi not falling into allocated stack slots) isn't an 956 * error because this just means the stack state hasn't been updated yet. 957 * We will do check_mem_access to check and update stack bounds later. 958 */ 959 if (spi < 0 && spi != -ERANGE) 960 return false; 961 962 /* We don't need to check if the stack slots are marked by previous 963 * dynptr initializations because we allow overwriting existing unreferenced 964 * STACK_DYNPTR slots, see mark_stack_slots_dynptr which calls 965 * destroy_if_dynptr_stack_slot to ensure dynptr objects at the slots we are 966 * touching are completely destructed before we reinitialize them for a new 967 * one. For referenced ones, destroy_if_dynptr_stack_slot returns an error early 968 * instead of delaying it until the end where the user will get "Unreleased 969 * reference" error. 970 */ 971 return true; 972 } 973 974 static bool is_dynptr_reg_valid_init(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 975 { 976 struct bpf_func_state *state = func(env, reg); 977 int i, spi; 978 979 /* This already represents first slot of initialized bpf_dynptr. 980 * 981 * CONST_PTR_TO_DYNPTR already has fixed and var_off as 0 due to 982 * check_func_arg_reg_off's logic, so we don't need to check its 983 * offset and alignment. 984 */ 985 if (reg->type == CONST_PTR_TO_DYNPTR) 986 return true; 987 988 spi = dynptr_get_spi(env, reg); 989 if (spi < 0) 990 return false; 991 if (!state->stack[spi].spilled_ptr.dynptr.first_slot) 992 return false; 993 994 for (i = 0; i < BPF_REG_SIZE; i++) { 995 if (state->stack[spi].slot_type[i] != STACK_DYNPTR || 996 state->stack[spi - 1].slot_type[i] != STACK_DYNPTR) 997 return false; 998 } 999 1000 return true; 1001 } 1002 1003 static bool is_dynptr_type_expected(struct bpf_verifier_env *env, struct bpf_reg_state *reg, 1004 enum bpf_arg_type arg_type) 1005 { 1006 struct bpf_func_state *state = func(env, reg); 1007 enum bpf_dynptr_type dynptr_type; 1008 int spi; 1009 1010 /* ARG_PTR_TO_DYNPTR takes any type of dynptr */ 1011 if (arg_type == ARG_PTR_TO_DYNPTR) 1012 return true; 1013 1014 dynptr_type = arg_to_dynptr_type(arg_type); 1015 if (reg->type == CONST_PTR_TO_DYNPTR) { 1016 return reg->dynptr.type == dynptr_type; 1017 } else { 1018 spi = dynptr_get_spi(env, reg); 1019 if (spi < 0) 1020 return false; 1021 return state->stack[spi].spilled_ptr.dynptr.type == dynptr_type; 1022 } 1023 } 1024 1025 static void __mark_reg_known_zero(struct bpf_reg_state *reg); 1026 1027 static bool in_rcu_cs(struct bpf_verifier_env *env); 1028 1029 static bool is_kfunc_rcu_protected(struct bpf_kfunc_call_arg_meta *meta); 1030 1031 static int mark_stack_slots_iter(struct bpf_verifier_env *env, 1032 struct bpf_kfunc_call_arg_meta *meta, 1033 struct bpf_reg_state *reg, int insn_idx, 1034 struct btf *btf, u32 btf_id, int nr_slots) 1035 { 1036 struct bpf_func_state *state = func(env, reg); 1037 int spi, i, j, id; 1038 1039 spi = iter_get_spi(env, reg, nr_slots); 1040 if (spi < 0) 1041 return spi; 1042 1043 id = acquire_reference(env, insn_idx); 1044 if (id < 0) 1045 return id; 1046 1047 for (i = 0; i < nr_slots; i++) { 1048 struct bpf_stack_state *slot = &state->stack[spi - i]; 1049 struct bpf_reg_state *st = &slot->spilled_ptr; 1050 1051 __mark_reg_known_zero(st); 1052 st->type = PTR_TO_STACK; /* we don't have dedicated reg type */ 1053 if (is_kfunc_rcu_protected(meta)) { 1054 if (in_rcu_cs(env)) 1055 st->type |= MEM_RCU; 1056 else 1057 st->type |= PTR_UNTRUSTED; 1058 } 1059 st->live |= REG_LIVE_WRITTEN; 1060 st->ref_obj_id = i == 0 ? id : 0; 1061 st->iter.btf = btf; 1062 st->iter.btf_id = btf_id; 1063 st->iter.state = BPF_ITER_STATE_ACTIVE; 1064 st->iter.depth = 0; 1065 1066 for (j = 0; j < BPF_REG_SIZE; j++) 1067 slot->slot_type[j] = STACK_ITER; 1068 1069 mark_stack_slot_scratched(env, spi - i); 1070 } 1071 1072 return 0; 1073 } 1074 1075 static int unmark_stack_slots_iter(struct bpf_verifier_env *env, 1076 struct bpf_reg_state *reg, int nr_slots) 1077 { 1078 struct bpf_func_state *state = func(env, reg); 1079 int spi, i, j; 1080 1081 spi = iter_get_spi(env, reg, nr_slots); 1082 if (spi < 0) 1083 return spi; 1084 1085 for (i = 0; i < nr_slots; i++) { 1086 struct bpf_stack_state *slot = &state->stack[spi - i]; 1087 struct bpf_reg_state *st = &slot->spilled_ptr; 1088 1089 if (i == 0) 1090 WARN_ON_ONCE(release_reference(env, st->ref_obj_id)); 1091 1092 __mark_reg_not_init(env, st); 1093 1094 /* see unmark_stack_slots_dynptr() for why we need to set REG_LIVE_WRITTEN */ 1095 st->live |= REG_LIVE_WRITTEN; 1096 1097 for (j = 0; j < BPF_REG_SIZE; j++) 1098 slot->slot_type[j] = STACK_INVALID; 1099 1100 mark_stack_slot_scratched(env, spi - i); 1101 } 1102 1103 return 0; 1104 } 1105 1106 static bool is_iter_reg_valid_uninit(struct bpf_verifier_env *env, 1107 struct bpf_reg_state *reg, int nr_slots) 1108 { 1109 struct bpf_func_state *state = func(env, reg); 1110 int spi, i, j; 1111 1112 /* For -ERANGE (i.e. spi not falling into allocated stack slots), we 1113 * will do check_mem_access to check and update stack bounds later, so 1114 * return true for that case. 1115 */ 1116 spi = iter_get_spi(env, reg, nr_slots); 1117 if (spi == -ERANGE) 1118 return true; 1119 if (spi < 0) 1120 return false; 1121 1122 for (i = 0; i < nr_slots; i++) { 1123 struct bpf_stack_state *slot = &state->stack[spi - i]; 1124 1125 for (j = 0; j < BPF_REG_SIZE; j++) 1126 if (slot->slot_type[j] == STACK_ITER) 1127 return false; 1128 } 1129 1130 return true; 1131 } 1132 1133 static int is_iter_reg_valid_init(struct bpf_verifier_env *env, struct bpf_reg_state *reg, 1134 struct btf *btf, u32 btf_id, int nr_slots) 1135 { 1136 struct bpf_func_state *state = func(env, reg); 1137 int spi, i, j; 1138 1139 spi = iter_get_spi(env, reg, nr_slots); 1140 if (spi < 0) 1141 return -EINVAL; 1142 1143 for (i = 0; i < nr_slots; i++) { 1144 struct bpf_stack_state *slot = &state->stack[spi - i]; 1145 struct bpf_reg_state *st = &slot->spilled_ptr; 1146 1147 if (st->type & PTR_UNTRUSTED) 1148 return -EPROTO; 1149 /* only main (first) slot has ref_obj_id set */ 1150 if (i == 0 && !st->ref_obj_id) 1151 return -EINVAL; 1152 if (i != 0 && st->ref_obj_id) 1153 return -EINVAL; 1154 if (st->iter.btf != btf || st->iter.btf_id != btf_id) 1155 return -EINVAL; 1156 1157 for (j = 0; j < BPF_REG_SIZE; j++) 1158 if (slot->slot_type[j] != STACK_ITER) 1159 return -EINVAL; 1160 } 1161 1162 return 0; 1163 } 1164 1165 static int acquire_irq_state(struct bpf_verifier_env *env, int insn_idx); 1166 static int release_irq_state(struct bpf_verifier_state *state, int id); 1167 1168 static int mark_stack_slot_irq_flag(struct bpf_verifier_env *env, 1169 struct bpf_kfunc_call_arg_meta *meta, 1170 struct bpf_reg_state *reg, int insn_idx, 1171 int kfunc_class) 1172 { 1173 struct bpf_func_state *state = func(env, reg); 1174 struct bpf_stack_state *slot; 1175 struct bpf_reg_state *st; 1176 int spi, i, id; 1177 1178 spi = irq_flag_get_spi(env, reg); 1179 if (spi < 0) 1180 return spi; 1181 1182 id = acquire_irq_state(env, insn_idx); 1183 if (id < 0) 1184 return id; 1185 1186 slot = &state->stack[spi]; 1187 st = &slot->spilled_ptr; 1188 1189 __mark_reg_known_zero(st); 1190 st->type = PTR_TO_STACK; /* we don't have dedicated reg type */ 1191 st->live |= REG_LIVE_WRITTEN; 1192 st->ref_obj_id = id; 1193 st->irq.kfunc_class = kfunc_class; 1194 1195 for (i = 0; i < BPF_REG_SIZE; i++) 1196 slot->slot_type[i] = STACK_IRQ_FLAG; 1197 1198 mark_stack_slot_scratched(env, spi); 1199 return 0; 1200 } 1201 1202 static int unmark_stack_slot_irq_flag(struct bpf_verifier_env *env, struct bpf_reg_state *reg, 1203 int kfunc_class) 1204 { 1205 struct bpf_func_state *state = func(env, reg); 1206 struct bpf_stack_state *slot; 1207 struct bpf_reg_state *st; 1208 int spi, i, err; 1209 1210 spi = irq_flag_get_spi(env, reg); 1211 if (spi < 0) 1212 return spi; 1213 1214 slot = &state->stack[spi]; 1215 st = &slot->spilled_ptr; 1216 1217 if (st->irq.kfunc_class != kfunc_class) { 1218 const char *flag_kfunc = st->irq.kfunc_class == IRQ_NATIVE_KFUNC ? "native" : "lock"; 1219 const char *used_kfunc = kfunc_class == IRQ_NATIVE_KFUNC ? "native" : "lock"; 1220 1221 verbose(env, "irq flag acquired by %s kfuncs cannot be restored with %s kfuncs\n", 1222 flag_kfunc, used_kfunc); 1223 return -EINVAL; 1224 } 1225 1226 err = release_irq_state(env->cur_state, st->ref_obj_id); 1227 WARN_ON_ONCE(err && err != -EACCES); 1228 if (err) { 1229 int insn_idx = 0; 1230 1231 for (int i = 0; i < env->cur_state->acquired_refs; i++) { 1232 if (env->cur_state->refs[i].id == env->cur_state->active_irq_id) { 1233 insn_idx = env->cur_state->refs[i].insn_idx; 1234 break; 1235 } 1236 } 1237 1238 verbose(env, "cannot restore irq state out of order, expected id=%d acquired at insn_idx=%d\n", 1239 env->cur_state->active_irq_id, insn_idx); 1240 return err; 1241 } 1242 1243 __mark_reg_not_init(env, st); 1244 1245 /* see unmark_stack_slots_dynptr() for why we need to set REG_LIVE_WRITTEN */ 1246 st->live |= REG_LIVE_WRITTEN; 1247 1248 for (i = 0; i < BPF_REG_SIZE; i++) 1249 slot->slot_type[i] = STACK_INVALID; 1250 1251 mark_stack_slot_scratched(env, spi); 1252 return 0; 1253 } 1254 1255 static bool is_irq_flag_reg_valid_uninit(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 1256 { 1257 struct bpf_func_state *state = func(env, reg); 1258 struct bpf_stack_state *slot; 1259 int spi, i; 1260 1261 /* For -ERANGE (i.e. spi not falling into allocated stack slots), we 1262 * will do check_mem_access to check and update stack bounds later, so 1263 * return true for that case. 1264 */ 1265 spi = irq_flag_get_spi(env, reg); 1266 if (spi == -ERANGE) 1267 return true; 1268 if (spi < 0) 1269 return false; 1270 1271 slot = &state->stack[spi]; 1272 1273 for (i = 0; i < BPF_REG_SIZE; i++) 1274 if (slot->slot_type[i] == STACK_IRQ_FLAG) 1275 return false; 1276 return true; 1277 } 1278 1279 static int is_irq_flag_reg_valid_init(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 1280 { 1281 struct bpf_func_state *state = func(env, reg); 1282 struct bpf_stack_state *slot; 1283 struct bpf_reg_state *st; 1284 int spi, i; 1285 1286 spi = irq_flag_get_spi(env, reg); 1287 if (spi < 0) 1288 return -EINVAL; 1289 1290 slot = &state->stack[spi]; 1291 st = &slot->spilled_ptr; 1292 1293 if (!st->ref_obj_id) 1294 return -EINVAL; 1295 1296 for (i = 0; i < BPF_REG_SIZE; i++) 1297 if (slot->slot_type[i] != STACK_IRQ_FLAG) 1298 return -EINVAL; 1299 return 0; 1300 } 1301 1302 /* Check if given stack slot is "special": 1303 * - spilled register state (STACK_SPILL); 1304 * - dynptr state (STACK_DYNPTR); 1305 * - iter state (STACK_ITER). 1306 * - irq flag state (STACK_IRQ_FLAG) 1307 */ 1308 static bool is_stack_slot_special(const struct bpf_stack_state *stack) 1309 { 1310 enum bpf_stack_slot_type type = stack->slot_type[BPF_REG_SIZE - 1]; 1311 1312 switch (type) { 1313 case STACK_SPILL: 1314 case STACK_DYNPTR: 1315 case STACK_ITER: 1316 case STACK_IRQ_FLAG: 1317 return true; 1318 case STACK_INVALID: 1319 case STACK_MISC: 1320 case STACK_ZERO: 1321 return false; 1322 default: 1323 WARN_ONCE(1, "unknown stack slot type %d\n", type); 1324 return true; 1325 } 1326 } 1327 1328 /* The reg state of a pointer or a bounded scalar was saved when 1329 * it was spilled to the stack. 1330 */ 1331 static bool is_spilled_reg(const struct bpf_stack_state *stack) 1332 { 1333 return stack->slot_type[BPF_REG_SIZE - 1] == STACK_SPILL; 1334 } 1335 1336 static bool is_spilled_scalar_reg(const struct bpf_stack_state *stack) 1337 { 1338 return stack->slot_type[BPF_REG_SIZE - 1] == STACK_SPILL && 1339 stack->spilled_ptr.type == SCALAR_VALUE; 1340 } 1341 1342 static bool is_spilled_scalar_reg64(const struct bpf_stack_state *stack) 1343 { 1344 return stack->slot_type[0] == STACK_SPILL && 1345 stack->spilled_ptr.type == SCALAR_VALUE; 1346 } 1347 1348 /* Mark stack slot as STACK_MISC, unless it is already STACK_INVALID, in which 1349 * case they are equivalent, or it's STACK_ZERO, in which case we preserve 1350 * more precise STACK_ZERO. 1351 * Regardless of allow_ptr_leaks setting (i.e., privileged or unprivileged 1352 * mode), we won't promote STACK_INVALID to STACK_MISC. In privileged case it is 1353 * unnecessary as both are considered equivalent when loading data and pruning, 1354 * in case of unprivileged mode it will be incorrect to allow reads of invalid 1355 * slots. 1356 */ 1357 static void mark_stack_slot_misc(struct bpf_verifier_env *env, u8 *stype) 1358 { 1359 if (*stype == STACK_ZERO) 1360 return; 1361 if (*stype == STACK_INVALID) 1362 return; 1363 *stype = STACK_MISC; 1364 } 1365 1366 static void scrub_spilled_slot(u8 *stype) 1367 { 1368 if (*stype != STACK_INVALID) 1369 *stype = STACK_MISC; 1370 } 1371 1372 /* copy array src of length n * size bytes to dst. dst is reallocated if it's too 1373 * small to hold src. This is different from krealloc since we don't want to preserve 1374 * the contents of dst. 1375 * 1376 * Leaves dst untouched if src is NULL or length is zero. Returns NULL if memory could 1377 * not be allocated. 1378 */ 1379 static void *copy_array(void *dst, const void *src, size_t n, size_t size, gfp_t flags) 1380 { 1381 size_t alloc_bytes; 1382 void *orig = dst; 1383 size_t bytes; 1384 1385 if (ZERO_OR_NULL_PTR(src)) 1386 goto out; 1387 1388 if (unlikely(check_mul_overflow(n, size, &bytes))) 1389 return NULL; 1390 1391 alloc_bytes = max(ksize(orig), kmalloc_size_roundup(bytes)); 1392 dst = krealloc(orig, alloc_bytes, flags); 1393 if (!dst) { 1394 kfree(orig); 1395 return NULL; 1396 } 1397 1398 memcpy(dst, src, bytes); 1399 out: 1400 return dst ? dst : ZERO_SIZE_PTR; 1401 } 1402 1403 /* resize an array from old_n items to new_n items. the array is reallocated if it's too 1404 * small to hold new_n items. new items are zeroed out if the array grows. 1405 * 1406 * Contrary to krealloc_array, does not free arr if new_n is zero. 1407 */ 1408 static void *realloc_array(void *arr, size_t old_n, size_t new_n, size_t size) 1409 { 1410 size_t alloc_size; 1411 void *new_arr; 1412 1413 if (!new_n || old_n == new_n) 1414 goto out; 1415 1416 alloc_size = kmalloc_size_roundup(size_mul(new_n, size)); 1417 new_arr = krealloc(arr, alloc_size, GFP_KERNEL_ACCOUNT); 1418 if (!new_arr) { 1419 kfree(arr); 1420 return NULL; 1421 } 1422 arr = new_arr; 1423 1424 if (new_n > old_n) 1425 memset(arr + old_n * size, 0, (new_n - old_n) * size); 1426 1427 out: 1428 return arr ? arr : ZERO_SIZE_PTR; 1429 } 1430 1431 static int copy_reference_state(struct bpf_verifier_state *dst, const struct bpf_verifier_state *src) 1432 { 1433 dst->refs = copy_array(dst->refs, src->refs, src->acquired_refs, 1434 sizeof(struct bpf_reference_state), GFP_KERNEL_ACCOUNT); 1435 if (!dst->refs) 1436 return -ENOMEM; 1437 1438 dst->acquired_refs = src->acquired_refs; 1439 dst->active_locks = src->active_locks; 1440 dst->active_preempt_locks = src->active_preempt_locks; 1441 dst->active_rcu_lock = src->active_rcu_lock; 1442 dst->active_irq_id = src->active_irq_id; 1443 dst->active_lock_id = src->active_lock_id; 1444 dst->active_lock_ptr = src->active_lock_ptr; 1445 return 0; 1446 } 1447 1448 static int copy_stack_state(struct bpf_func_state *dst, const struct bpf_func_state *src) 1449 { 1450 size_t n = src->allocated_stack / BPF_REG_SIZE; 1451 1452 dst->stack = copy_array(dst->stack, src->stack, n, sizeof(struct bpf_stack_state), 1453 GFP_KERNEL_ACCOUNT); 1454 if (!dst->stack) 1455 return -ENOMEM; 1456 1457 dst->allocated_stack = src->allocated_stack; 1458 return 0; 1459 } 1460 1461 static int resize_reference_state(struct bpf_verifier_state *state, size_t n) 1462 { 1463 state->refs = realloc_array(state->refs, state->acquired_refs, n, 1464 sizeof(struct bpf_reference_state)); 1465 if (!state->refs) 1466 return -ENOMEM; 1467 1468 state->acquired_refs = n; 1469 return 0; 1470 } 1471 1472 /* Possibly update state->allocated_stack to be at least size bytes. Also 1473 * possibly update the function's high-water mark in its bpf_subprog_info. 1474 */ 1475 static int grow_stack_state(struct bpf_verifier_env *env, struct bpf_func_state *state, int size) 1476 { 1477 size_t old_n = state->allocated_stack / BPF_REG_SIZE, n; 1478 1479 /* The stack size is always a multiple of BPF_REG_SIZE. */ 1480 size = round_up(size, BPF_REG_SIZE); 1481 n = size / BPF_REG_SIZE; 1482 1483 if (old_n >= n) 1484 return 0; 1485 1486 state->stack = realloc_array(state->stack, old_n, n, sizeof(struct bpf_stack_state)); 1487 if (!state->stack) 1488 return -ENOMEM; 1489 1490 state->allocated_stack = size; 1491 1492 /* update known max for given subprogram */ 1493 if (env->subprog_info[state->subprogno].stack_depth < size) 1494 env->subprog_info[state->subprogno].stack_depth = size; 1495 1496 return 0; 1497 } 1498 1499 /* Acquire a pointer id from the env and update the state->refs to include 1500 * this new pointer reference. 1501 * On success, returns a valid pointer id to associate with the register 1502 * On failure, returns a negative errno. 1503 */ 1504 static struct bpf_reference_state *acquire_reference_state(struct bpf_verifier_env *env, int insn_idx) 1505 { 1506 struct bpf_verifier_state *state = env->cur_state; 1507 int new_ofs = state->acquired_refs; 1508 int err; 1509 1510 err = resize_reference_state(state, state->acquired_refs + 1); 1511 if (err) 1512 return NULL; 1513 state->refs[new_ofs].insn_idx = insn_idx; 1514 1515 return &state->refs[new_ofs]; 1516 } 1517 1518 static int acquire_reference(struct bpf_verifier_env *env, int insn_idx) 1519 { 1520 struct bpf_reference_state *s; 1521 1522 s = acquire_reference_state(env, insn_idx); 1523 if (!s) 1524 return -ENOMEM; 1525 s->type = REF_TYPE_PTR; 1526 s->id = ++env->id_gen; 1527 return s->id; 1528 } 1529 1530 static int acquire_lock_state(struct bpf_verifier_env *env, int insn_idx, enum ref_state_type type, 1531 int id, void *ptr) 1532 { 1533 struct bpf_verifier_state *state = env->cur_state; 1534 struct bpf_reference_state *s; 1535 1536 s = acquire_reference_state(env, insn_idx); 1537 if (!s) 1538 return -ENOMEM; 1539 s->type = type; 1540 s->id = id; 1541 s->ptr = ptr; 1542 1543 state->active_locks++; 1544 state->active_lock_id = id; 1545 state->active_lock_ptr = ptr; 1546 return 0; 1547 } 1548 1549 static int acquire_irq_state(struct bpf_verifier_env *env, int insn_idx) 1550 { 1551 struct bpf_verifier_state *state = env->cur_state; 1552 struct bpf_reference_state *s; 1553 1554 s = acquire_reference_state(env, insn_idx); 1555 if (!s) 1556 return -ENOMEM; 1557 s->type = REF_TYPE_IRQ; 1558 s->id = ++env->id_gen; 1559 1560 state->active_irq_id = s->id; 1561 return s->id; 1562 } 1563 1564 static void release_reference_state(struct bpf_verifier_state *state, int idx) 1565 { 1566 int last_idx; 1567 size_t rem; 1568 1569 /* IRQ state requires the relative ordering of elements remaining the 1570 * same, since it relies on the refs array to behave as a stack, so that 1571 * it can detect out-of-order IRQ restore. Hence use memmove to shift 1572 * the array instead of swapping the final element into the deleted idx. 1573 */ 1574 last_idx = state->acquired_refs - 1; 1575 rem = state->acquired_refs - idx - 1; 1576 if (last_idx && idx != last_idx) 1577 memmove(&state->refs[idx], &state->refs[idx + 1], sizeof(*state->refs) * rem); 1578 memset(&state->refs[last_idx], 0, sizeof(*state->refs)); 1579 state->acquired_refs--; 1580 return; 1581 } 1582 1583 static bool find_reference_state(struct bpf_verifier_state *state, int ptr_id) 1584 { 1585 int i; 1586 1587 for (i = 0; i < state->acquired_refs; i++) 1588 if (state->refs[i].id == ptr_id) 1589 return true; 1590 1591 return false; 1592 } 1593 1594 static int release_lock_state(struct bpf_verifier_state *state, int type, int id, void *ptr) 1595 { 1596 void *prev_ptr = NULL; 1597 u32 prev_id = 0; 1598 int i; 1599 1600 for (i = 0; i < state->acquired_refs; i++) { 1601 if (state->refs[i].type == type && state->refs[i].id == id && 1602 state->refs[i].ptr == ptr) { 1603 release_reference_state(state, i); 1604 state->active_locks--; 1605 /* Reassign active lock (id, ptr). */ 1606 state->active_lock_id = prev_id; 1607 state->active_lock_ptr = prev_ptr; 1608 return 0; 1609 } 1610 if (state->refs[i].type & REF_TYPE_LOCK_MASK) { 1611 prev_id = state->refs[i].id; 1612 prev_ptr = state->refs[i].ptr; 1613 } 1614 } 1615 return -EINVAL; 1616 } 1617 1618 static int release_irq_state(struct bpf_verifier_state *state, int id) 1619 { 1620 u32 prev_id = 0; 1621 int i; 1622 1623 if (id != state->active_irq_id) 1624 return -EACCES; 1625 1626 for (i = 0; i < state->acquired_refs; i++) { 1627 if (state->refs[i].type != REF_TYPE_IRQ) 1628 continue; 1629 if (state->refs[i].id == id) { 1630 release_reference_state(state, i); 1631 state->active_irq_id = prev_id; 1632 return 0; 1633 } else { 1634 prev_id = state->refs[i].id; 1635 } 1636 } 1637 return -EINVAL; 1638 } 1639 1640 static struct bpf_reference_state *find_lock_state(struct bpf_verifier_state *state, enum ref_state_type type, 1641 int id, void *ptr) 1642 { 1643 int i; 1644 1645 for (i = 0; i < state->acquired_refs; i++) { 1646 struct bpf_reference_state *s = &state->refs[i]; 1647 1648 if (!(s->type & type)) 1649 continue; 1650 1651 if (s->id == id && s->ptr == ptr) 1652 return s; 1653 } 1654 return NULL; 1655 } 1656 1657 static void update_peak_states(struct bpf_verifier_env *env) 1658 { 1659 u32 cur_states; 1660 1661 cur_states = env->explored_states_size + env->free_list_size + env->num_backedges; 1662 env->peak_states = max(env->peak_states, cur_states); 1663 } 1664 1665 static void free_func_state(struct bpf_func_state *state) 1666 { 1667 if (!state) 1668 return; 1669 kfree(state->stack); 1670 kfree(state); 1671 } 1672 1673 static void clear_jmp_history(struct bpf_verifier_state *state) 1674 { 1675 kfree(state->jmp_history); 1676 state->jmp_history = NULL; 1677 state->jmp_history_cnt = 0; 1678 } 1679 1680 static void free_verifier_state(struct bpf_verifier_state *state, 1681 bool free_self) 1682 { 1683 int i; 1684 1685 for (i = 0; i <= state->curframe; i++) { 1686 free_func_state(state->frame[i]); 1687 state->frame[i] = NULL; 1688 } 1689 kfree(state->refs); 1690 clear_jmp_history(state); 1691 if (free_self) 1692 kfree(state); 1693 } 1694 1695 /* struct bpf_verifier_state->parent refers to states 1696 * that are in either of env->{expored_states,free_list}. 1697 * In both cases the state is contained in struct bpf_verifier_state_list. 1698 */ 1699 static struct bpf_verifier_state_list *state_parent_as_list(struct bpf_verifier_state *st) 1700 { 1701 if (st->parent) 1702 return container_of(st->parent, struct bpf_verifier_state_list, state); 1703 return NULL; 1704 } 1705 1706 static bool incomplete_read_marks(struct bpf_verifier_env *env, 1707 struct bpf_verifier_state *st); 1708 1709 /* A state can be freed if it is no longer referenced: 1710 * - is in the env->free_list; 1711 * - has no children states; 1712 */ 1713 static void maybe_free_verifier_state(struct bpf_verifier_env *env, 1714 struct bpf_verifier_state_list *sl) 1715 { 1716 if (!sl->in_free_list 1717 || sl->state.branches != 0 1718 || incomplete_read_marks(env, &sl->state)) 1719 return; 1720 list_del(&sl->node); 1721 free_verifier_state(&sl->state, false); 1722 kfree(sl); 1723 env->free_list_size--; 1724 } 1725 1726 /* copy verifier state from src to dst growing dst stack space 1727 * when necessary to accommodate larger src stack 1728 */ 1729 static int copy_func_state(struct bpf_func_state *dst, 1730 const struct bpf_func_state *src) 1731 { 1732 memcpy(dst, src, offsetof(struct bpf_func_state, stack)); 1733 return copy_stack_state(dst, src); 1734 } 1735 1736 static int copy_verifier_state(struct bpf_verifier_state *dst_state, 1737 const struct bpf_verifier_state *src) 1738 { 1739 struct bpf_func_state *dst; 1740 int i, err; 1741 1742 dst_state->jmp_history = copy_array(dst_state->jmp_history, src->jmp_history, 1743 src->jmp_history_cnt, sizeof(*dst_state->jmp_history), 1744 GFP_KERNEL_ACCOUNT); 1745 if (!dst_state->jmp_history) 1746 return -ENOMEM; 1747 dst_state->jmp_history_cnt = src->jmp_history_cnt; 1748 1749 /* if dst has more stack frames then src frame, free them, this is also 1750 * necessary in case of exceptional exits using bpf_throw. 1751 */ 1752 for (i = src->curframe + 1; i <= dst_state->curframe; i++) { 1753 free_func_state(dst_state->frame[i]); 1754 dst_state->frame[i] = NULL; 1755 } 1756 err = copy_reference_state(dst_state, src); 1757 if (err) 1758 return err; 1759 dst_state->speculative = src->speculative; 1760 dst_state->in_sleepable = src->in_sleepable; 1761 dst_state->curframe = src->curframe; 1762 dst_state->branches = src->branches; 1763 dst_state->parent = src->parent; 1764 dst_state->first_insn_idx = src->first_insn_idx; 1765 dst_state->last_insn_idx = src->last_insn_idx; 1766 dst_state->dfs_depth = src->dfs_depth; 1767 dst_state->callback_unroll_depth = src->callback_unroll_depth; 1768 dst_state->may_goto_depth = src->may_goto_depth; 1769 dst_state->equal_state = src->equal_state; 1770 for (i = 0; i <= src->curframe; i++) { 1771 dst = dst_state->frame[i]; 1772 if (!dst) { 1773 dst = kzalloc(sizeof(*dst), GFP_KERNEL_ACCOUNT); 1774 if (!dst) 1775 return -ENOMEM; 1776 dst_state->frame[i] = dst; 1777 } 1778 err = copy_func_state(dst, src->frame[i]); 1779 if (err) 1780 return err; 1781 } 1782 return 0; 1783 } 1784 1785 static u32 state_htab_size(struct bpf_verifier_env *env) 1786 { 1787 return env->prog->len; 1788 } 1789 1790 static struct list_head *explored_state(struct bpf_verifier_env *env, int idx) 1791 { 1792 struct bpf_verifier_state *cur = env->cur_state; 1793 struct bpf_func_state *state = cur->frame[cur->curframe]; 1794 1795 return &env->explored_states[(idx ^ state->callsite) % state_htab_size(env)]; 1796 } 1797 1798 static bool same_callsites(struct bpf_verifier_state *a, struct bpf_verifier_state *b) 1799 { 1800 int fr; 1801 1802 if (a->curframe != b->curframe) 1803 return false; 1804 1805 for (fr = a->curframe; fr >= 0; fr--) 1806 if (a->frame[fr]->callsite != b->frame[fr]->callsite) 1807 return false; 1808 1809 return true; 1810 } 1811 1812 /* Return IP for a given frame in a call stack */ 1813 static u32 frame_insn_idx(struct bpf_verifier_state *st, u32 frame) 1814 { 1815 return frame == st->curframe 1816 ? st->insn_idx 1817 : st->frame[frame + 1]->callsite; 1818 } 1819 1820 /* For state @st look for a topmost frame with frame_insn_idx() in some SCC, 1821 * if such frame exists form a corresponding @callchain as an array of 1822 * call sites leading to this frame and SCC id. 1823 * E.g.: 1824 * 1825 * void foo() { A: loop {... SCC#1 ...}; } 1826 * void bar() { B: loop { C: foo(); ... SCC#2 ... } 1827 * D: loop { E: foo(); ... SCC#3 ... } } 1828 * void main() { F: bar(); } 1829 * 1830 * @callchain at (A) would be either (F,SCC#2) or (F,SCC#3) depending 1831 * on @st frame call sites being (F,C,A) or (F,E,A). 1832 */ 1833 static bool compute_scc_callchain(struct bpf_verifier_env *env, 1834 struct bpf_verifier_state *st, 1835 struct bpf_scc_callchain *callchain) 1836 { 1837 u32 i, scc, insn_idx; 1838 1839 memset(callchain, 0, sizeof(*callchain)); 1840 for (i = 0; i <= st->curframe; i++) { 1841 insn_idx = frame_insn_idx(st, i); 1842 scc = env->insn_aux_data[insn_idx].scc; 1843 if (scc) { 1844 callchain->scc = scc; 1845 break; 1846 } else if (i < st->curframe) { 1847 callchain->callsites[i] = insn_idx; 1848 } else { 1849 return false; 1850 } 1851 } 1852 return true; 1853 } 1854 1855 /* Check if bpf_scc_visit instance for @callchain exists. */ 1856 static struct bpf_scc_visit *scc_visit_lookup(struct bpf_verifier_env *env, 1857 struct bpf_scc_callchain *callchain) 1858 { 1859 struct bpf_scc_info *info = env->scc_info[callchain->scc]; 1860 struct bpf_scc_visit *visits = info->visits; 1861 u32 i; 1862 1863 if (!info) 1864 return NULL; 1865 for (i = 0; i < info->num_visits; i++) 1866 if (memcmp(callchain, &visits[i].callchain, sizeof(*callchain)) == 0) 1867 return &visits[i]; 1868 return NULL; 1869 } 1870 1871 /* Allocate a new bpf_scc_visit instance corresponding to @callchain. 1872 * Allocated instances are alive for a duration of the do_check_common() 1873 * call and are freed by free_states(). 1874 */ 1875 static struct bpf_scc_visit *scc_visit_alloc(struct bpf_verifier_env *env, 1876 struct bpf_scc_callchain *callchain) 1877 { 1878 struct bpf_scc_visit *visit; 1879 struct bpf_scc_info *info; 1880 u32 scc, num_visits; 1881 u64 new_sz; 1882 1883 scc = callchain->scc; 1884 info = env->scc_info[scc]; 1885 num_visits = info ? info->num_visits : 0; 1886 new_sz = sizeof(*info) + sizeof(struct bpf_scc_visit) * (num_visits + 1); 1887 info = kvrealloc(env->scc_info[scc], new_sz, GFP_KERNEL_ACCOUNT); 1888 if (!info) 1889 return NULL; 1890 env->scc_info[scc] = info; 1891 info->num_visits = num_visits + 1; 1892 visit = &info->visits[num_visits]; 1893 memset(visit, 0, sizeof(*visit)); 1894 memcpy(&visit->callchain, callchain, sizeof(*callchain)); 1895 return visit; 1896 } 1897 1898 /* Form a string '(callsite#1,callsite#2,...,scc)' in env->tmp_str_buf */ 1899 static char *format_callchain(struct bpf_verifier_env *env, struct bpf_scc_callchain *callchain) 1900 { 1901 char *buf = env->tmp_str_buf; 1902 int i, delta = 0; 1903 1904 delta += snprintf(buf + delta, TMP_STR_BUF_LEN - delta, "("); 1905 for (i = 0; i < ARRAY_SIZE(callchain->callsites); i++) { 1906 if (!callchain->callsites[i]) 1907 break; 1908 delta += snprintf(buf + delta, TMP_STR_BUF_LEN - delta, "%u,", 1909 callchain->callsites[i]); 1910 } 1911 delta += snprintf(buf + delta, TMP_STR_BUF_LEN - delta, "%u)", callchain->scc); 1912 return env->tmp_str_buf; 1913 } 1914 1915 /* If callchain for @st exists (@st is in some SCC), ensure that 1916 * bpf_scc_visit instance for this callchain exists. 1917 * If instance does not exist or is empty, assign visit->entry_state to @st. 1918 */ 1919 static int maybe_enter_scc(struct bpf_verifier_env *env, struct bpf_verifier_state *st) 1920 { 1921 struct bpf_scc_callchain *callchain = &env->callchain_buf; 1922 struct bpf_scc_visit *visit; 1923 1924 if (!compute_scc_callchain(env, st, callchain)) 1925 return 0; 1926 visit = scc_visit_lookup(env, callchain); 1927 visit = visit ?: scc_visit_alloc(env, callchain); 1928 if (!visit) 1929 return -ENOMEM; 1930 if (!visit->entry_state) { 1931 visit->entry_state = st; 1932 if (env->log.level & BPF_LOG_LEVEL2) 1933 verbose(env, "SCC enter %s\n", format_callchain(env, callchain)); 1934 } 1935 return 0; 1936 } 1937 1938 static int propagate_backedges(struct bpf_verifier_env *env, struct bpf_scc_visit *visit); 1939 1940 /* If callchain for @st exists (@st is in some SCC), make it empty: 1941 * - set visit->entry_state to NULL; 1942 * - flush accumulated backedges. 1943 */ 1944 static int maybe_exit_scc(struct bpf_verifier_env *env, struct bpf_verifier_state *st) 1945 { 1946 struct bpf_scc_callchain *callchain = &env->callchain_buf; 1947 struct bpf_scc_visit *visit; 1948 1949 if (!compute_scc_callchain(env, st, callchain)) 1950 return 0; 1951 visit = scc_visit_lookup(env, callchain); 1952 if (!visit) { 1953 verifier_bug(env, "scc exit: no visit info for call chain %s", 1954 format_callchain(env, callchain)); 1955 return -EFAULT; 1956 } 1957 if (visit->entry_state != st) 1958 return 0; 1959 if (env->log.level & BPF_LOG_LEVEL2) 1960 verbose(env, "SCC exit %s\n", format_callchain(env, callchain)); 1961 visit->entry_state = NULL; 1962 env->num_backedges -= visit->num_backedges; 1963 visit->num_backedges = 0; 1964 update_peak_states(env); 1965 return propagate_backedges(env, visit); 1966 } 1967 1968 /* Lookup an bpf_scc_visit instance corresponding to @st callchain 1969 * and add @backedge to visit->backedges. @st callchain must exist. 1970 */ 1971 static int add_scc_backedge(struct bpf_verifier_env *env, 1972 struct bpf_verifier_state *st, 1973 struct bpf_scc_backedge *backedge) 1974 { 1975 struct bpf_scc_callchain *callchain = &env->callchain_buf; 1976 struct bpf_scc_visit *visit; 1977 1978 if (!compute_scc_callchain(env, st, callchain)) { 1979 verifier_bug(env, "add backedge: no SCC in verification path, insn_idx %d", 1980 st->insn_idx); 1981 return -EFAULT; 1982 } 1983 visit = scc_visit_lookup(env, callchain); 1984 if (!visit) { 1985 verifier_bug(env, "add backedge: no visit info for call chain %s", 1986 format_callchain(env, callchain)); 1987 return -EFAULT; 1988 } 1989 if (env->log.level & BPF_LOG_LEVEL2) 1990 verbose(env, "SCC backedge %s\n", format_callchain(env, callchain)); 1991 backedge->next = visit->backedges; 1992 visit->backedges = backedge; 1993 visit->num_backedges++; 1994 env->num_backedges++; 1995 update_peak_states(env); 1996 return 0; 1997 } 1998 1999 /* bpf_reg_state->live marks for registers in a state @st are incomplete, 2000 * if state @st is in some SCC and not all execution paths starting at this 2001 * SCC are fully explored. 2002 */ 2003 static bool incomplete_read_marks(struct bpf_verifier_env *env, 2004 struct bpf_verifier_state *st) 2005 { 2006 struct bpf_scc_callchain *callchain = &env->callchain_buf; 2007 struct bpf_scc_visit *visit; 2008 2009 if (!compute_scc_callchain(env, st, callchain)) 2010 return false; 2011 visit = scc_visit_lookup(env, callchain); 2012 if (!visit) 2013 return false; 2014 return !!visit->backedges; 2015 } 2016 2017 static void free_backedges(struct bpf_scc_visit *visit) 2018 { 2019 struct bpf_scc_backedge *backedge, *next; 2020 2021 for (backedge = visit->backedges; backedge; backedge = next) { 2022 free_verifier_state(&backedge->state, false); 2023 next = backedge->next; 2024 kvfree(backedge); 2025 } 2026 visit->backedges = NULL; 2027 } 2028 2029 static int update_branch_counts(struct bpf_verifier_env *env, struct bpf_verifier_state *st) 2030 { 2031 struct bpf_verifier_state_list *sl = NULL, *parent_sl; 2032 struct bpf_verifier_state *parent; 2033 int err; 2034 2035 while (st) { 2036 u32 br = --st->branches; 2037 2038 /* verifier_bug_if(br > 1, ...) technically makes sense here, 2039 * but see comment in push_stack(), hence: 2040 */ 2041 verifier_bug_if((int)br < 0, env, "%s:branches_to_explore=%d", __func__, br); 2042 if (br) 2043 break; 2044 err = maybe_exit_scc(env, st); 2045 if (err) 2046 return err; 2047 parent = st->parent; 2048 parent_sl = state_parent_as_list(st); 2049 if (sl) 2050 maybe_free_verifier_state(env, sl); 2051 st = parent; 2052 sl = parent_sl; 2053 } 2054 return 0; 2055 } 2056 2057 static int pop_stack(struct bpf_verifier_env *env, int *prev_insn_idx, 2058 int *insn_idx, bool pop_log) 2059 { 2060 struct bpf_verifier_state *cur = env->cur_state; 2061 struct bpf_verifier_stack_elem *elem, *head = env->head; 2062 int err; 2063 2064 if (env->head == NULL) 2065 return -ENOENT; 2066 2067 if (cur) { 2068 err = copy_verifier_state(cur, &head->st); 2069 if (err) 2070 return err; 2071 } 2072 if (pop_log) 2073 bpf_vlog_reset(&env->log, head->log_pos); 2074 if (insn_idx) 2075 *insn_idx = head->insn_idx; 2076 if (prev_insn_idx) 2077 *prev_insn_idx = head->prev_insn_idx; 2078 elem = head->next; 2079 free_verifier_state(&head->st, false); 2080 kfree(head); 2081 env->head = elem; 2082 env->stack_size--; 2083 return 0; 2084 } 2085 2086 static bool error_recoverable_with_nospec(int err) 2087 { 2088 /* Should only return true for non-fatal errors that are allowed to 2089 * occur during speculative verification. For these we can insert a 2090 * nospec and the program might still be accepted. Do not include 2091 * something like ENOMEM because it is likely to re-occur for the next 2092 * architectural path once it has been recovered-from in all speculative 2093 * paths. 2094 */ 2095 return err == -EPERM || err == -EACCES || err == -EINVAL; 2096 } 2097 2098 static struct bpf_verifier_state *push_stack(struct bpf_verifier_env *env, 2099 int insn_idx, int prev_insn_idx, 2100 bool speculative) 2101 { 2102 struct bpf_verifier_state *cur = env->cur_state; 2103 struct bpf_verifier_stack_elem *elem; 2104 int err; 2105 2106 elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL_ACCOUNT); 2107 if (!elem) 2108 return NULL; 2109 2110 elem->insn_idx = insn_idx; 2111 elem->prev_insn_idx = prev_insn_idx; 2112 elem->next = env->head; 2113 elem->log_pos = env->log.end_pos; 2114 env->head = elem; 2115 env->stack_size++; 2116 err = copy_verifier_state(&elem->st, cur); 2117 if (err) 2118 return NULL; 2119 elem->st.speculative |= speculative; 2120 if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) { 2121 verbose(env, "The sequence of %d jumps is too complex.\n", 2122 env->stack_size); 2123 return NULL; 2124 } 2125 if (elem->st.parent) { 2126 ++elem->st.parent->branches; 2127 /* WARN_ON(branches > 2) technically makes sense here, 2128 * but 2129 * 1. speculative states will bump 'branches' for non-branch 2130 * instructions 2131 * 2. is_state_visited() heuristics may decide not to create 2132 * a new state for a sequence of branches and all such current 2133 * and cloned states will be pointing to a single parent state 2134 * which might have large 'branches' count. 2135 */ 2136 } 2137 return &elem->st; 2138 } 2139 2140 #define CALLER_SAVED_REGS 6 2141 static const int caller_saved[CALLER_SAVED_REGS] = { 2142 BPF_REG_0, BPF_REG_1, BPF_REG_2, BPF_REG_3, BPF_REG_4, BPF_REG_5 2143 }; 2144 2145 /* This helper doesn't clear reg->id */ 2146 static void ___mark_reg_known(struct bpf_reg_state *reg, u64 imm) 2147 { 2148 reg->var_off = tnum_const(imm); 2149 reg->smin_value = (s64)imm; 2150 reg->smax_value = (s64)imm; 2151 reg->umin_value = imm; 2152 reg->umax_value = imm; 2153 2154 reg->s32_min_value = (s32)imm; 2155 reg->s32_max_value = (s32)imm; 2156 reg->u32_min_value = (u32)imm; 2157 reg->u32_max_value = (u32)imm; 2158 } 2159 2160 /* Mark the unknown part of a register (variable offset or scalar value) as 2161 * known to have the value @imm. 2162 */ 2163 static void __mark_reg_known(struct bpf_reg_state *reg, u64 imm) 2164 { 2165 /* Clear off and union(map_ptr, range) */ 2166 memset(((u8 *)reg) + sizeof(reg->type), 0, 2167 offsetof(struct bpf_reg_state, var_off) - sizeof(reg->type)); 2168 reg->id = 0; 2169 reg->ref_obj_id = 0; 2170 ___mark_reg_known(reg, imm); 2171 } 2172 2173 static void __mark_reg32_known(struct bpf_reg_state *reg, u64 imm) 2174 { 2175 reg->var_off = tnum_const_subreg(reg->var_off, imm); 2176 reg->s32_min_value = (s32)imm; 2177 reg->s32_max_value = (s32)imm; 2178 reg->u32_min_value = (u32)imm; 2179 reg->u32_max_value = (u32)imm; 2180 } 2181 2182 /* Mark the 'variable offset' part of a register as zero. This should be 2183 * used only on registers holding a pointer type. 2184 */ 2185 static void __mark_reg_known_zero(struct bpf_reg_state *reg) 2186 { 2187 __mark_reg_known(reg, 0); 2188 } 2189 2190 static void __mark_reg_const_zero(const struct bpf_verifier_env *env, struct bpf_reg_state *reg) 2191 { 2192 __mark_reg_known(reg, 0); 2193 reg->type = SCALAR_VALUE; 2194 /* all scalars are assumed imprecise initially (unless unprivileged, 2195 * in which case everything is forced to be precise) 2196 */ 2197 reg->precise = !env->bpf_capable; 2198 } 2199 2200 static void mark_reg_known_zero(struct bpf_verifier_env *env, 2201 struct bpf_reg_state *regs, u32 regno) 2202 { 2203 if (WARN_ON(regno >= MAX_BPF_REG)) { 2204 verbose(env, "mark_reg_known_zero(regs, %u)\n", regno); 2205 /* Something bad happened, let's kill all regs */ 2206 for (regno = 0; regno < MAX_BPF_REG; regno++) 2207 __mark_reg_not_init(env, regs + regno); 2208 return; 2209 } 2210 __mark_reg_known_zero(regs + regno); 2211 } 2212 2213 static void __mark_dynptr_reg(struct bpf_reg_state *reg, enum bpf_dynptr_type type, 2214 bool first_slot, int dynptr_id) 2215 { 2216 /* reg->type has no meaning for STACK_DYNPTR, but when we set reg for 2217 * callback arguments, it does need to be CONST_PTR_TO_DYNPTR, so simply 2218 * set it unconditionally as it is ignored for STACK_DYNPTR anyway. 2219 */ 2220 __mark_reg_known_zero(reg); 2221 reg->type = CONST_PTR_TO_DYNPTR; 2222 /* Give each dynptr a unique id to uniquely associate slices to it. */ 2223 reg->id = dynptr_id; 2224 reg->dynptr.type = type; 2225 reg->dynptr.first_slot = first_slot; 2226 } 2227 2228 static void mark_ptr_not_null_reg(struct bpf_reg_state *reg) 2229 { 2230 if (base_type(reg->type) == PTR_TO_MAP_VALUE) { 2231 const struct bpf_map *map = reg->map_ptr; 2232 2233 if (map->inner_map_meta) { 2234 reg->type = CONST_PTR_TO_MAP; 2235 reg->map_ptr = map->inner_map_meta; 2236 /* transfer reg's id which is unique for every map_lookup_elem 2237 * as UID of the inner map. 2238 */ 2239 if (btf_record_has_field(map->inner_map_meta->record, BPF_TIMER)) 2240 reg->map_uid = reg->id; 2241 if (btf_record_has_field(map->inner_map_meta->record, BPF_WORKQUEUE)) 2242 reg->map_uid = reg->id; 2243 } else if (map->map_type == BPF_MAP_TYPE_XSKMAP) { 2244 reg->type = PTR_TO_XDP_SOCK; 2245 } else if (map->map_type == BPF_MAP_TYPE_SOCKMAP || 2246 map->map_type == BPF_MAP_TYPE_SOCKHASH) { 2247 reg->type = PTR_TO_SOCKET; 2248 } else { 2249 reg->type = PTR_TO_MAP_VALUE; 2250 } 2251 return; 2252 } 2253 2254 reg->type &= ~PTR_MAYBE_NULL; 2255 } 2256 2257 static void mark_reg_graph_node(struct bpf_reg_state *regs, u32 regno, 2258 struct btf_field_graph_root *ds_head) 2259 { 2260 __mark_reg_known_zero(®s[regno]); 2261 regs[regno].type = PTR_TO_BTF_ID | MEM_ALLOC; 2262 regs[regno].btf = ds_head->btf; 2263 regs[regno].btf_id = ds_head->value_btf_id; 2264 regs[regno].off = ds_head->node_offset; 2265 } 2266 2267 static bool reg_is_pkt_pointer(const struct bpf_reg_state *reg) 2268 { 2269 return type_is_pkt_pointer(reg->type); 2270 } 2271 2272 static bool reg_is_pkt_pointer_any(const struct bpf_reg_state *reg) 2273 { 2274 return reg_is_pkt_pointer(reg) || 2275 reg->type == PTR_TO_PACKET_END; 2276 } 2277 2278 static bool reg_is_dynptr_slice_pkt(const struct bpf_reg_state *reg) 2279 { 2280 return base_type(reg->type) == PTR_TO_MEM && 2281 (reg->type & 2282 (DYNPTR_TYPE_SKB | DYNPTR_TYPE_XDP | DYNPTR_TYPE_SKB_META)); 2283 } 2284 2285 /* Unmodified PTR_TO_PACKET[_META,_END] register from ctx access. */ 2286 static bool reg_is_init_pkt_pointer(const struct bpf_reg_state *reg, 2287 enum bpf_reg_type which) 2288 { 2289 /* The register can already have a range from prior markings. 2290 * This is fine as long as it hasn't been advanced from its 2291 * origin. 2292 */ 2293 return reg->type == which && 2294 reg->id == 0 && 2295 reg->off == 0 && 2296 tnum_equals_const(reg->var_off, 0); 2297 } 2298 2299 /* Reset the min/max bounds of a register */ 2300 static void __mark_reg_unbounded(struct bpf_reg_state *reg) 2301 { 2302 reg->smin_value = S64_MIN; 2303 reg->smax_value = S64_MAX; 2304 reg->umin_value = 0; 2305 reg->umax_value = U64_MAX; 2306 2307 reg->s32_min_value = S32_MIN; 2308 reg->s32_max_value = S32_MAX; 2309 reg->u32_min_value = 0; 2310 reg->u32_max_value = U32_MAX; 2311 } 2312 2313 static void __mark_reg64_unbounded(struct bpf_reg_state *reg) 2314 { 2315 reg->smin_value = S64_MIN; 2316 reg->smax_value = S64_MAX; 2317 reg->umin_value = 0; 2318 reg->umax_value = U64_MAX; 2319 } 2320 2321 static void __mark_reg32_unbounded(struct bpf_reg_state *reg) 2322 { 2323 reg->s32_min_value = S32_MIN; 2324 reg->s32_max_value = S32_MAX; 2325 reg->u32_min_value = 0; 2326 reg->u32_max_value = U32_MAX; 2327 } 2328 2329 static void __update_reg32_bounds(struct bpf_reg_state *reg) 2330 { 2331 struct tnum var32_off = tnum_subreg(reg->var_off); 2332 2333 /* min signed is max(sign bit) | min(other bits) */ 2334 reg->s32_min_value = max_t(s32, reg->s32_min_value, 2335 var32_off.value | (var32_off.mask & S32_MIN)); 2336 /* max signed is min(sign bit) | max(other bits) */ 2337 reg->s32_max_value = min_t(s32, reg->s32_max_value, 2338 var32_off.value | (var32_off.mask & S32_MAX)); 2339 reg->u32_min_value = max_t(u32, reg->u32_min_value, (u32)var32_off.value); 2340 reg->u32_max_value = min(reg->u32_max_value, 2341 (u32)(var32_off.value | var32_off.mask)); 2342 } 2343 2344 static void __update_reg64_bounds(struct bpf_reg_state *reg) 2345 { 2346 /* min signed is max(sign bit) | min(other bits) */ 2347 reg->smin_value = max_t(s64, reg->smin_value, 2348 reg->var_off.value | (reg->var_off.mask & S64_MIN)); 2349 /* max signed is min(sign bit) | max(other bits) */ 2350 reg->smax_value = min_t(s64, reg->smax_value, 2351 reg->var_off.value | (reg->var_off.mask & S64_MAX)); 2352 reg->umin_value = max(reg->umin_value, reg->var_off.value); 2353 reg->umax_value = min(reg->umax_value, 2354 reg->var_off.value | reg->var_off.mask); 2355 } 2356 2357 static void __update_reg_bounds(struct bpf_reg_state *reg) 2358 { 2359 __update_reg32_bounds(reg); 2360 __update_reg64_bounds(reg); 2361 } 2362 2363 /* Uses signed min/max values to inform unsigned, and vice-versa */ 2364 static void __reg32_deduce_bounds(struct bpf_reg_state *reg) 2365 { 2366 /* If upper 32 bits of u64/s64 range don't change, we can use lower 32 2367 * bits to improve our u32/s32 boundaries. 2368 * 2369 * E.g., the case where we have upper 32 bits as zero ([10, 20] in 2370 * u64) is pretty trivial, it's obvious that in u32 we'll also have 2371 * [10, 20] range. But this property holds for any 64-bit range as 2372 * long as upper 32 bits in that entire range of values stay the same. 2373 * 2374 * E.g., u64 range [0x10000000A, 0x10000000F] ([4294967306, 4294967311] 2375 * in decimal) has the same upper 32 bits throughout all the values in 2376 * that range. As such, lower 32 bits form a valid [0xA, 0xF] ([10, 15]) 2377 * range. 2378 * 2379 * Note also, that [0xA, 0xF] is a valid range both in u32 and in s32, 2380 * following the rules outlined below about u64/s64 correspondence 2381 * (which equally applies to u32 vs s32 correspondence). In general it 2382 * depends on actual hexadecimal values of 32-bit range. They can form 2383 * only valid u32, or only valid s32 ranges in some cases. 2384 * 2385 * So we use all these insights to derive bounds for subregisters here. 2386 */ 2387 if ((reg->umin_value >> 32) == (reg->umax_value >> 32)) { 2388 /* u64 to u32 casting preserves validity of low 32 bits as 2389 * a range, if upper 32 bits are the same 2390 */ 2391 reg->u32_min_value = max_t(u32, reg->u32_min_value, (u32)reg->umin_value); 2392 reg->u32_max_value = min_t(u32, reg->u32_max_value, (u32)reg->umax_value); 2393 2394 if ((s32)reg->umin_value <= (s32)reg->umax_value) { 2395 reg->s32_min_value = max_t(s32, reg->s32_min_value, (s32)reg->umin_value); 2396 reg->s32_max_value = min_t(s32, reg->s32_max_value, (s32)reg->umax_value); 2397 } 2398 } 2399 if ((reg->smin_value >> 32) == (reg->smax_value >> 32)) { 2400 /* low 32 bits should form a proper u32 range */ 2401 if ((u32)reg->smin_value <= (u32)reg->smax_value) { 2402 reg->u32_min_value = max_t(u32, reg->u32_min_value, (u32)reg->smin_value); 2403 reg->u32_max_value = min_t(u32, reg->u32_max_value, (u32)reg->smax_value); 2404 } 2405 /* low 32 bits should form a proper s32 range */ 2406 if ((s32)reg->smin_value <= (s32)reg->smax_value) { 2407 reg->s32_min_value = max_t(s32, reg->s32_min_value, (s32)reg->smin_value); 2408 reg->s32_max_value = min_t(s32, reg->s32_max_value, (s32)reg->smax_value); 2409 } 2410 } 2411 /* Special case where upper bits form a small sequence of two 2412 * sequential numbers (in 32-bit unsigned space, so 0xffffffff to 2413 * 0x00000000 is also valid), while lower bits form a proper s32 range 2414 * going from negative numbers to positive numbers. E.g., let's say we 2415 * have s64 range [-1, 1] ([0xffffffffffffffff, 0x0000000000000001]). 2416 * Possible s64 values are {-1, 0, 1} ({0xffffffffffffffff, 2417 * 0x0000000000000000, 0x00000000000001}). Ignoring upper 32 bits, 2418 * we still get a valid s32 range [-1, 1] ([0xffffffff, 0x00000001]). 2419 * Note that it doesn't have to be 0xffffffff going to 0x00000000 in 2420 * upper 32 bits. As a random example, s64 range 2421 * [0xfffffff0fffffff0; 0xfffffff100000010], forms a valid s32 range 2422 * [-16, 16] ([0xfffffff0; 0x00000010]) in its 32 bit subregister. 2423 */ 2424 if ((u32)(reg->umin_value >> 32) + 1 == (u32)(reg->umax_value >> 32) && 2425 (s32)reg->umin_value < 0 && (s32)reg->umax_value >= 0) { 2426 reg->s32_min_value = max_t(s32, reg->s32_min_value, (s32)reg->umin_value); 2427 reg->s32_max_value = min_t(s32, reg->s32_max_value, (s32)reg->umax_value); 2428 } 2429 if ((u32)(reg->smin_value >> 32) + 1 == (u32)(reg->smax_value >> 32) && 2430 (s32)reg->smin_value < 0 && (s32)reg->smax_value >= 0) { 2431 reg->s32_min_value = max_t(s32, reg->s32_min_value, (s32)reg->smin_value); 2432 reg->s32_max_value = min_t(s32, reg->s32_max_value, (s32)reg->smax_value); 2433 } 2434 /* if u32 range forms a valid s32 range (due to matching sign bit), 2435 * try to learn from that 2436 */ 2437 if ((s32)reg->u32_min_value <= (s32)reg->u32_max_value) { 2438 reg->s32_min_value = max_t(s32, reg->s32_min_value, reg->u32_min_value); 2439 reg->s32_max_value = min_t(s32, reg->s32_max_value, reg->u32_max_value); 2440 } 2441 /* If we cannot cross the sign boundary, then signed and unsigned bounds 2442 * are the same, so combine. This works even in the negative case, e.g. 2443 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff. 2444 */ 2445 if ((u32)reg->s32_min_value <= (u32)reg->s32_max_value) { 2446 reg->u32_min_value = max_t(u32, reg->s32_min_value, reg->u32_min_value); 2447 reg->u32_max_value = min_t(u32, reg->s32_max_value, reg->u32_max_value); 2448 } 2449 } 2450 2451 static void __reg64_deduce_bounds(struct bpf_reg_state *reg) 2452 { 2453 /* If u64 range forms a valid s64 range (due to matching sign bit), 2454 * try to learn from that. Let's do a bit of ASCII art to see when 2455 * this is happening. Let's take u64 range first: 2456 * 2457 * 0 0x7fffffffffffffff 0x8000000000000000 U64_MAX 2458 * |-------------------------------|--------------------------------| 2459 * 2460 * Valid u64 range is formed when umin and umax are anywhere in the 2461 * range [0, U64_MAX], and umin <= umax. u64 case is simple and 2462 * straightforward. Let's see how s64 range maps onto the same range 2463 * of values, annotated below the line for comparison: 2464 * 2465 * 0 0x7fffffffffffffff 0x8000000000000000 U64_MAX 2466 * |-------------------------------|--------------------------------| 2467 * 0 S64_MAX S64_MIN -1 2468 * 2469 * So s64 values basically start in the middle and they are logically 2470 * contiguous to the right of it, wrapping around from -1 to 0, and 2471 * then finishing as S64_MAX (0x7fffffffffffffff) right before 2472 * S64_MIN. We can try drawing the continuity of u64 vs s64 values 2473 * more visually as mapped to sign-agnostic range of hex values. 2474 * 2475 * u64 start u64 end 2476 * _______________________________________________________________ 2477 * / \ 2478 * 0 0x7fffffffffffffff 0x8000000000000000 U64_MAX 2479 * |-------------------------------|--------------------------------| 2480 * 0 S64_MAX S64_MIN -1 2481 * / \ 2482 * >------------------------------ -------------------------------> 2483 * s64 continues... s64 end s64 start s64 "midpoint" 2484 * 2485 * What this means is that, in general, we can't always derive 2486 * something new about u64 from any random s64 range, and vice versa. 2487 * 2488 * But we can do that in two particular cases. One is when entire 2489 * u64/s64 range is *entirely* contained within left half of the above 2490 * diagram or when it is *entirely* contained in the right half. I.e.: 2491 * 2492 * |-------------------------------|--------------------------------| 2493 * ^ ^ ^ ^ 2494 * A B C D 2495 * 2496 * [A, B] and [C, D] are contained entirely in their respective halves 2497 * and form valid contiguous ranges as both u64 and s64 values. [A, B] 2498 * will be non-negative both as u64 and s64 (and in fact it will be 2499 * identical ranges no matter the signedness). [C, D] treated as s64 2500 * will be a range of negative values, while in u64 it will be 2501 * non-negative range of values larger than 0x8000000000000000. 2502 * 2503 * Now, any other range here can't be represented in both u64 and s64 2504 * simultaneously. E.g., [A, C], [A, D], [B, C], [B, D] are valid 2505 * contiguous u64 ranges, but they are discontinuous in s64. [B, C] 2506 * in s64 would be properly presented as [S64_MIN, C] and [B, S64_MAX], 2507 * for example. Similarly, valid s64 range [D, A] (going from negative 2508 * to positive values), would be two separate [D, U64_MAX] and [0, A] 2509 * ranges as u64. Currently reg_state can't represent two segments per 2510 * numeric domain, so in such situations we can only derive maximal 2511 * possible range ([0, U64_MAX] for u64, and [S64_MIN, S64_MAX] for s64). 2512 * 2513 * So we use these facts to derive umin/umax from smin/smax and vice 2514 * versa only if they stay within the same "half". This is equivalent 2515 * to checking sign bit: lower half will have sign bit as zero, upper 2516 * half have sign bit 1. Below in code we simplify this by just 2517 * casting umin/umax as smin/smax and checking if they form valid 2518 * range, and vice versa. Those are equivalent checks. 2519 */ 2520 if ((s64)reg->umin_value <= (s64)reg->umax_value) { 2521 reg->smin_value = max_t(s64, reg->smin_value, reg->umin_value); 2522 reg->smax_value = min_t(s64, reg->smax_value, reg->umax_value); 2523 } 2524 /* If we cannot cross the sign boundary, then signed and unsigned bounds 2525 * are the same, so combine. This works even in the negative case, e.g. 2526 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff. 2527 */ 2528 if ((u64)reg->smin_value <= (u64)reg->smax_value) { 2529 reg->umin_value = max_t(u64, reg->smin_value, reg->umin_value); 2530 reg->umax_value = min_t(u64, reg->smax_value, reg->umax_value); 2531 } else { 2532 /* If the s64 range crosses the sign boundary, then it's split 2533 * between the beginning and end of the U64 domain. In that 2534 * case, we can derive new bounds if the u64 range overlaps 2535 * with only one end of the s64 range. 2536 * 2537 * In the following example, the u64 range overlaps only with 2538 * positive portion of the s64 range. 2539 * 2540 * 0 U64_MAX 2541 * | [xxxxxxxxxxxxxx u64 range xxxxxxxxxxxxxx] | 2542 * |----------------------------|----------------------------| 2543 * |xxxxx s64 range xxxxxxxxx] [xxxxxxx| 2544 * 0 S64_MAX S64_MIN -1 2545 * 2546 * We can thus derive the following new s64 and u64 ranges. 2547 * 2548 * 0 U64_MAX 2549 * | [xxxxxx u64 range xxxxx] | 2550 * |----------------------------|----------------------------| 2551 * | [xxxxxx s64 range xxxxx] | 2552 * 0 S64_MAX S64_MIN -1 2553 * 2554 * If they overlap in two places, we can't derive anything 2555 * because reg_state can't represent two ranges per numeric 2556 * domain. 2557 * 2558 * 0 U64_MAX 2559 * | [xxxxxxxxxxxxxxxxx u64 range xxxxxxxxxxxxxxxxx] | 2560 * |----------------------------|----------------------------| 2561 * |xxxxx s64 range xxxxxxxxx] [xxxxxxxxxx| 2562 * 0 S64_MAX S64_MIN -1 2563 * 2564 * The first condition below corresponds to the first diagram 2565 * above. 2566 */ 2567 if (reg->umax_value < (u64)reg->smin_value) { 2568 reg->smin_value = (s64)reg->umin_value; 2569 reg->umax_value = min_t(u64, reg->umax_value, reg->smax_value); 2570 } else if ((u64)reg->smax_value < reg->umin_value) { 2571 /* This second condition considers the case where the u64 range 2572 * overlaps with the negative portion of the s64 range: 2573 * 2574 * 0 U64_MAX 2575 * | [xxxxxxxxxxxxxx u64 range xxxxxxxxxxxxxx] | 2576 * |----------------------------|----------------------------| 2577 * |xxxxxxxxx] [xxxxxxxxxxxx s64 range | 2578 * 0 S64_MAX S64_MIN -1 2579 */ 2580 reg->smax_value = (s64)reg->umax_value; 2581 reg->umin_value = max_t(u64, reg->umin_value, reg->smin_value); 2582 } 2583 } 2584 } 2585 2586 static void __reg_deduce_mixed_bounds(struct bpf_reg_state *reg) 2587 { 2588 /* Try to tighten 64-bit bounds from 32-bit knowledge, using 32-bit 2589 * values on both sides of 64-bit range in hope to have tighter range. 2590 * E.g., if r1 is [0x1'00000000, 0x3'80000000], and we learn from 2591 * 32-bit signed > 0 operation that s32 bounds are now [1; 0x7fffffff]. 2592 * With this, we can substitute 1 as low 32-bits of _low_ 64-bit bound 2593 * (0x100000000 -> 0x100000001) and 0x7fffffff as low 32-bits of 2594 * _high_ 64-bit bound (0x380000000 -> 0x37fffffff) and arrive at a 2595 * better overall bounds for r1 as [0x1'000000001; 0x3'7fffffff]. 2596 * We just need to make sure that derived bounds we are intersecting 2597 * with are well-formed ranges in respective s64 or u64 domain, just 2598 * like we do with similar kinds of 32-to-64 or 64-to-32 adjustments. 2599 */ 2600 __u64 new_umin, new_umax; 2601 __s64 new_smin, new_smax; 2602 2603 /* u32 -> u64 tightening, it's always well-formed */ 2604 new_umin = (reg->umin_value & ~0xffffffffULL) | reg->u32_min_value; 2605 new_umax = (reg->umax_value & ~0xffffffffULL) | reg->u32_max_value; 2606 reg->umin_value = max_t(u64, reg->umin_value, new_umin); 2607 reg->umax_value = min_t(u64, reg->umax_value, new_umax); 2608 /* u32 -> s64 tightening, u32 range embedded into s64 preserves range validity */ 2609 new_smin = (reg->smin_value & ~0xffffffffULL) | reg->u32_min_value; 2610 new_smax = (reg->smax_value & ~0xffffffffULL) | reg->u32_max_value; 2611 reg->smin_value = max_t(s64, reg->smin_value, new_smin); 2612 reg->smax_value = min_t(s64, reg->smax_value, new_smax); 2613 2614 /* Here we would like to handle a special case after sign extending load, 2615 * when upper bits for a 64-bit range are all 1s or all 0s. 2616 * 2617 * Upper bits are all 1s when register is in a range: 2618 * [0xffff_ffff_0000_0000, 0xffff_ffff_ffff_ffff] 2619 * Upper bits are all 0s when register is in a range: 2620 * [0x0000_0000_0000_0000, 0x0000_0000_ffff_ffff] 2621 * Together this forms are continuous range: 2622 * [0xffff_ffff_0000_0000, 0x0000_0000_ffff_ffff] 2623 * 2624 * Now, suppose that register range is in fact tighter: 2625 * [0xffff_ffff_8000_0000, 0x0000_0000_ffff_ffff] (R) 2626 * Also suppose that it's 32-bit range is positive, 2627 * meaning that lower 32-bits of the full 64-bit register 2628 * are in the range: 2629 * [0x0000_0000, 0x7fff_ffff] (W) 2630 * 2631 * If this happens, then any value in a range: 2632 * [0xffff_ffff_0000_0000, 0xffff_ffff_7fff_ffff] 2633 * is smaller than a lowest bound of the range (R): 2634 * 0xffff_ffff_8000_0000 2635 * which means that upper bits of the full 64-bit register 2636 * can't be all 1s, when lower bits are in range (W). 2637 * 2638 * Note that: 2639 * - 0xffff_ffff_8000_0000 == (s64)S32_MIN 2640 * - 0x0000_0000_7fff_ffff == (s64)S32_MAX 2641 * These relations are used in the conditions below. 2642 */ 2643 if (reg->s32_min_value >= 0 && reg->smin_value >= S32_MIN && reg->smax_value <= S32_MAX) { 2644 reg->smin_value = reg->s32_min_value; 2645 reg->smax_value = reg->s32_max_value; 2646 reg->umin_value = reg->s32_min_value; 2647 reg->umax_value = reg->s32_max_value; 2648 reg->var_off = tnum_intersect(reg->var_off, 2649 tnum_range(reg->smin_value, reg->smax_value)); 2650 } 2651 } 2652 2653 static void __reg_deduce_bounds(struct bpf_reg_state *reg) 2654 { 2655 __reg32_deduce_bounds(reg); 2656 __reg64_deduce_bounds(reg); 2657 __reg_deduce_mixed_bounds(reg); 2658 } 2659 2660 /* Attempts to improve var_off based on unsigned min/max information */ 2661 static void __reg_bound_offset(struct bpf_reg_state *reg) 2662 { 2663 struct tnum var64_off = tnum_intersect(reg->var_off, 2664 tnum_range(reg->umin_value, 2665 reg->umax_value)); 2666 struct tnum var32_off = tnum_intersect(tnum_subreg(var64_off), 2667 tnum_range(reg->u32_min_value, 2668 reg->u32_max_value)); 2669 2670 reg->var_off = tnum_or(tnum_clear_subreg(var64_off), var32_off); 2671 } 2672 2673 static void reg_bounds_sync(struct bpf_reg_state *reg) 2674 { 2675 /* We might have learned new bounds from the var_off. */ 2676 __update_reg_bounds(reg); 2677 /* We might have learned something about the sign bit. */ 2678 __reg_deduce_bounds(reg); 2679 __reg_deduce_bounds(reg); 2680 __reg_deduce_bounds(reg); 2681 /* We might have learned some bits from the bounds. */ 2682 __reg_bound_offset(reg); 2683 /* Intersecting with the old var_off might have improved our bounds 2684 * slightly, e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc), 2685 * then new var_off is (0; 0x7f...fc) which improves our umax. 2686 */ 2687 __update_reg_bounds(reg); 2688 } 2689 2690 static int reg_bounds_sanity_check(struct bpf_verifier_env *env, 2691 struct bpf_reg_state *reg, const char *ctx) 2692 { 2693 const char *msg; 2694 2695 if (reg->umin_value > reg->umax_value || 2696 reg->smin_value > reg->smax_value || 2697 reg->u32_min_value > reg->u32_max_value || 2698 reg->s32_min_value > reg->s32_max_value) { 2699 msg = "range bounds violation"; 2700 goto out; 2701 } 2702 2703 if (tnum_is_const(reg->var_off)) { 2704 u64 uval = reg->var_off.value; 2705 s64 sval = (s64)uval; 2706 2707 if (reg->umin_value != uval || reg->umax_value != uval || 2708 reg->smin_value != sval || reg->smax_value != sval) { 2709 msg = "const tnum out of sync with range bounds"; 2710 goto out; 2711 } 2712 } 2713 2714 if (tnum_subreg_is_const(reg->var_off)) { 2715 u32 uval32 = tnum_subreg(reg->var_off).value; 2716 s32 sval32 = (s32)uval32; 2717 2718 if (reg->u32_min_value != uval32 || reg->u32_max_value != uval32 || 2719 reg->s32_min_value != sval32 || reg->s32_max_value != sval32) { 2720 msg = "const subreg tnum out of sync with range bounds"; 2721 goto out; 2722 } 2723 } 2724 2725 return 0; 2726 out: 2727 verifier_bug(env, "REG INVARIANTS VIOLATION (%s): %s u64=[%#llx, %#llx] " 2728 "s64=[%#llx, %#llx] u32=[%#x, %#x] s32=[%#x, %#x] var_off=(%#llx, %#llx)", 2729 ctx, msg, reg->umin_value, reg->umax_value, 2730 reg->smin_value, reg->smax_value, 2731 reg->u32_min_value, reg->u32_max_value, 2732 reg->s32_min_value, reg->s32_max_value, 2733 reg->var_off.value, reg->var_off.mask); 2734 if (env->test_reg_invariants) 2735 return -EFAULT; 2736 __mark_reg_unbounded(reg); 2737 return 0; 2738 } 2739 2740 static bool __reg32_bound_s64(s32 a) 2741 { 2742 return a >= 0 && a <= S32_MAX; 2743 } 2744 2745 static void __reg_assign_32_into_64(struct bpf_reg_state *reg) 2746 { 2747 reg->umin_value = reg->u32_min_value; 2748 reg->umax_value = reg->u32_max_value; 2749 2750 /* Attempt to pull 32-bit signed bounds into 64-bit bounds but must 2751 * be positive otherwise set to worse case bounds and refine later 2752 * from tnum. 2753 */ 2754 if (__reg32_bound_s64(reg->s32_min_value) && 2755 __reg32_bound_s64(reg->s32_max_value)) { 2756 reg->smin_value = reg->s32_min_value; 2757 reg->smax_value = reg->s32_max_value; 2758 } else { 2759 reg->smin_value = 0; 2760 reg->smax_value = U32_MAX; 2761 } 2762 } 2763 2764 /* Mark a register as having a completely unknown (scalar) value. */ 2765 static void __mark_reg_unknown_imprecise(struct bpf_reg_state *reg) 2766 { 2767 /* 2768 * Clear type, off, and union(map_ptr, range) and 2769 * padding between 'type' and union 2770 */ 2771 memset(reg, 0, offsetof(struct bpf_reg_state, var_off)); 2772 reg->type = SCALAR_VALUE; 2773 reg->id = 0; 2774 reg->ref_obj_id = 0; 2775 reg->var_off = tnum_unknown; 2776 reg->frameno = 0; 2777 reg->precise = false; 2778 __mark_reg_unbounded(reg); 2779 } 2780 2781 /* Mark a register as having a completely unknown (scalar) value, 2782 * initialize .precise as true when not bpf capable. 2783 */ 2784 static void __mark_reg_unknown(const struct bpf_verifier_env *env, 2785 struct bpf_reg_state *reg) 2786 { 2787 __mark_reg_unknown_imprecise(reg); 2788 reg->precise = !env->bpf_capable; 2789 } 2790 2791 static void mark_reg_unknown(struct bpf_verifier_env *env, 2792 struct bpf_reg_state *regs, u32 regno) 2793 { 2794 if (WARN_ON(regno >= MAX_BPF_REG)) { 2795 verbose(env, "mark_reg_unknown(regs, %u)\n", regno); 2796 /* Something bad happened, let's kill all regs except FP */ 2797 for (regno = 0; regno < BPF_REG_FP; regno++) 2798 __mark_reg_not_init(env, regs + regno); 2799 return; 2800 } 2801 __mark_reg_unknown(env, regs + regno); 2802 } 2803 2804 static int __mark_reg_s32_range(struct bpf_verifier_env *env, 2805 struct bpf_reg_state *regs, 2806 u32 regno, 2807 s32 s32_min, 2808 s32 s32_max) 2809 { 2810 struct bpf_reg_state *reg = regs + regno; 2811 2812 reg->s32_min_value = max_t(s32, reg->s32_min_value, s32_min); 2813 reg->s32_max_value = min_t(s32, reg->s32_max_value, s32_max); 2814 2815 reg->smin_value = max_t(s64, reg->smin_value, s32_min); 2816 reg->smax_value = min_t(s64, reg->smax_value, s32_max); 2817 2818 reg_bounds_sync(reg); 2819 2820 return reg_bounds_sanity_check(env, reg, "s32_range"); 2821 } 2822 2823 static void __mark_reg_not_init(const struct bpf_verifier_env *env, 2824 struct bpf_reg_state *reg) 2825 { 2826 __mark_reg_unknown(env, reg); 2827 reg->type = NOT_INIT; 2828 } 2829 2830 static void mark_reg_not_init(struct bpf_verifier_env *env, 2831 struct bpf_reg_state *regs, u32 regno) 2832 { 2833 if (WARN_ON(regno >= MAX_BPF_REG)) { 2834 verbose(env, "mark_reg_not_init(regs, %u)\n", regno); 2835 /* Something bad happened, let's kill all regs except FP */ 2836 for (regno = 0; regno < BPF_REG_FP; regno++) 2837 __mark_reg_not_init(env, regs + regno); 2838 return; 2839 } 2840 __mark_reg_not_init(env, regs + regno); 2841 } 2842 2843 static int mark_btf_ld_reg(struct bpf_verifier_env *env, 2844 struct bpf_reg_state *regs, u32 regno, 2845 enum bpf_reg_type reg_type, 2846 struct btf *btf, u32 btf_id, 2847 enum bpf_type_flag flag) 2848 { 2849 switch (reg_type) { 2850 case SCALAR_VALUE: 2851 mark_reg_unknown(env, regs, regno); 2852 return 0; 2853 case PTR_TO_BTF_ID: 2854 mark_reg_known_zero(env, regs, regno); 2855 regs[regno].type = PTR_TO_BTF_ID | flag; 2856 regs[regno].btf = btf; 2857 regs[regno].btf_id = btf_id; 2858 if (type_may_be_null(flag)) 2859 regs[regno].id = ++env->id_gen; 2860 return 0; 2861 case PTR_TO_MEM: 2862 mark_reg_known_zero(env, regs, regno); 2863 regs[regno].type = PTR_TO_MEM | flag; 2864 regs[regno].mem_size = 0; 2865 return 0; 2866 default: 2867 verifier_bug(env, "unexpected reg_type %d in %s\n", reg_type, __func__); 2868 return -EFAULT; 2869 } 2870 } 2871 2872 #define DEF_NOT_SUBREG (0) 2873 static void init_reg_state(struct bpf_verifier_env *env, 2874 struct bpf_func_state *state) 2875 { 2876 struct bpf_reg_state *regs = state->regs; 2877 int i; 2878 2879 for (i = 0; i < MAX_BPF_REG; i++) { 2880 mark_reg_not_init(env, regs, i); 2881 regs[i].live = REG_LIVE_NONE; 2882 regs[i].parent = NULL; 2883 regs[i].subreg_def = DEF_NOT_SUBREG; 2884 } 2885 2886 /* frame pointer */ 2887 regs[BPF_REG_FP].type = PTR_TO_STACK; 2888 mark_reg_known_zero(env, regs, BPF_REG_FP); 2889 regs[BPF_REG_FP].frameno = state->frameno; 2890 } 2891 2892 static struct bpf_retval_range retval_range(s32 minval, s32 maxval) 2893 { 2894 return (struct bpf_retval_range){ minval, maxval }; 2895 } 2896 2897 #define BPF_MAIN_FUNC (-1) 2898 static void init_func_state(struct bpf_verifier_env *env, 2899 struct bpf_func_state *state, 2900 int callsite, int frameno, int subprogno) 2901 { 2902 state->callsite = callsite; 2903 state->frameno = frameno; 2904 state->subprogno = subprogno; 2905 state->callback_ret_range = retval_range(0, 0); 2906 init_reg_state(env, state); 2907 mark_verifier_state_scratched(env); 2908 } 2909 2910 /* Similar to push_stack(), but for async callbacks */ 2911 static struct bpf_verifier_state *push_async_cb(struct bpf_verifier_env *env, 2912 int insn_idx, int prev_insn_idx, 2913 int subprog, bool is_sleepable) 2914 { 2915 struct bpf_verifier_stack_elem *elem; 2916 struct bpf_func_state *frame; 2917 2918 elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL_ACCOUNT); 2919 if (!elem) 2920 return NULL; 2921 2922 elem->insn_idx = insn_idx; 2923 elem->prev_insn_idx = prev_insn_idx; 2924 elem->next = env->head; 2925 elem->log_pos = env->log.end_pos; 2926 env->head = elem; 2927 env->stack_size++; 2928 if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) { 2929 verbose(env, 2930 "The sequence of %d jumps is too complex for async cb.\n", 2931 env->stack_size); 2932 return NULL; 2933 } 2934 /* Unlike push_stack() do not copy_verifier_state(). 2935 * The caller state doesn't matter. 2936 * This is async callback. It starts in a fresh stack. 2937 * Initialize it similar to do_check_common(). 2938 */ 2939 elem->st.branches = 1; 2940 elem->st.in_sleepable = is_sleepable; 2941 frame = kzalloc(sizeof(*frame), GFP_KERNEL_ACCOUNT); 2942 if (!frame) 2943 return NULL; 2944 init_func_state(env, frame, 2945 BPF_MAIN_FUNC /* callsite */, 2946 0 /* frameno within this callchain */, 2947 subprog /* subprog number within this prog */); 2948 elem->st.frame[0] = frame; 2949 return &elem->st; 2950 } 2951 2952 2953 enum reg_arg_type { 2954 SRC_OP, /* register is used as source operand */ 2955 DST_OP, /* register is used as destination operand */ 2956 DST_OP_NO_MARK /* same as above, check only, don't mark */ 2957 }; 2958 2959 static int cmp_subprogs(const void *a, const void *b) 2960 { 2961 return ((struct bpf_subprog_info *)a)->start - 2962 ((struct bpf_subprog_info *)b)->start; 2963 } 2964 2965 /* Find subprogram that contains instruction at 'off' */ 2966 static struct bpf_subprog_info *find_containing_subprog(struct bpf_verifier_env *env, int off) 2967 { 2968 struct bpf_subprog_info *vals = env->subprog_info; 2969 int l, r, m; 2970 2971 if (off >= env->prog->len || off < 0 || env->subprog_cnt == 0) 2972 return NULL; 2973 2974 l = 0; 2975 r = env->subprog_cnt - 1; 2976 while (l < r) { 2977 m = l + (r - l + 1) / 2; 2978 if (vals[m].start <= off) 2979 l = m; 2980 else 2981 r = m - 1; 2982 } 2983 return &vals[l]; 2984 } 2985 2986 /* Find subprogram that starts exactly at 'off' */ 2987 static int find_subprog(struct bpf_verifier_env *env, int off) 2988 { 2989 struct bpf_subprog_info *p; 2990 2991 p = find_containing_subprog(env, off); 2992 if (!p || p->start != off) 2993 return -ENOENT; 2994 return p - env->subprog_info; 2995 } 2996 2997 static int add_subprog(struct bpf_verifier_env *env, int off) 2998 { 2999 int insn_cnt = env->prog->len; 3000 int ret; 3001 3002 if (off >= insn_cnt || off < 0) { 3003 verbose(env, "call to invalid destination\n"); 3004 return -EINVAL; 3005 } 3006 ret = find_subprog(env, off); 3007 if (ret >= 0) 3008 return ret; 3009 if (env->subprog_cnt >= BPF_MAX_SUBPROGS) { 3010 verbose(env, "too many subprograms\n"); 3011 return -E2BIG; 3012 } 3013 /* determine subprog starts. The end is one before the next starts */ 3014 env->subprog_info[env->subprog_cnt++].start = off; 3015 sort(env->subprog_info, env->subprog_cnt, 3016 sizeof(env->subprog_info[0]), cmp_subprogs, NULL); 3017 return env->subprog_cnt - 1; 3018 } 3019 3020 static int bpf_find_exception_callback_insn_off(struct bpf_verifier_env *env) 3021 { 3022 struct bpf_prog_aux *aux = env->prog->aux; 3023 struct btf *btf = aux->btf; 3024 const struct btf_type *t; 3025 u32 main_btf_id, id; 3026 const char *name; 3027 int ret, i; 3028 3029 /* Non-zero func_info_cnt implies valid btf */ 3030 if (!aux->func_info_cnt) 3031 return 0; 3032 main_btf_id = aux->func_info[0].type_id; 3033 3034 t = btf_type_by_id(btf, main_btf_id); 3035 if (!t) { 3036 verbose(env, "invalid btf id for main subprog in func_info\n"); 3037 return -EINVAL; 3038 } 3039 3040 name = btf_find_decl_tag_value(btf, t, -1, "exception_callback:"); 3041 if (IS_ERR(name)) { 3042 ret = PTR_ERR(name); 3043 /* If there is no tag present, there is no exception callback */ 3044 if (ret == -ENOENT) 3045 ret = 0; 3046 else if (ret == -EEXIST) 3047 verbose(env, "multiple exception callback tags for main subprog\n"); 3048 return ret; 3049 } 3050 3051 ret = btf_find_by_name_kind(btf, name, BTF_KIND_FUNC); 3052 if (ret < 0) { 3053 verbose(env, "exception callback '%s' could not be found in BTF\n", name); 3054 return ret; 3055 } 3056 id = ret; 3057 t = btf_type_by_id(btf, id); 3058 if (btf_func_linkage(t) != BTF_FUNC_GLOBAL) { 3059 verbose(env, "exception callback '%s' must have global linkage\n", name); 3060 return -EINVAL; 3061 } 3062 ret = 0; 3063 for (i = 0; i < aux->func_info_cnt; i++) { 3064 if (aux->func_info[i].type_id != id) 3065 continue; 3066 ret = aux->func_info[i].insn_off; 3067 /* Further func_info and subprog checks will also happen 3068 * later, so assume this is the right insn_off for now. 3069 */ 3070 if (!ret) { 3071 verbose(env, "invalid exception callback insn_off in func_info: 0\n"); 3072 ret = -EINVAL; 3073 } 3074 } 3075 if (!ret) { 3076 verbose(env, "exception callback type id not found in func_info\n"); 3077 ret = -EINVAL; 3078 } 3079 return ret; 3080 } 3081 3082 #define MAX_KFUNC_DESCS 256 3083 #define MAX_KFUNC_BTFS 256 3084 3085 struct bpf_kfunc_desc { 3086 struct btf_func_model func_model; 3087 u32 func_id; 3088 s32 imm; 3089 u16 offset; 3090 unsigned long addr; 3091 }; 3092 3093 struct bpf_kfunc_btf { 3094 struct btf *btf; 3095 struct module *module; 3096 u16 offset; 3097 }; 3098 3099 struct bpf_kfunc_desc_tab { 3100 /* Sorted by func_id (BTF ID) and offset (fd_array offset) during 3101 * verification. JITs do lookups by bpf_insn, where func_id may not be 3102 * available, therefore at the end of verification do_misc_fixups() 3103 * sorts this by imm and offset. 3104 */ 3105 struct bpf_kfunc_desc descs[MAX_KFUNC_DESCS]; 3106 u32 nr_descs; 3107 }; 3108 3109 struct bpf_kfunc_btf_tab { 3110 struct bpf_kfunc_btf descs[MAX_KFUNC_BTFS]; 3111 u32 nr_descs; 3112 }; 3113 3114 static int kfunc_desc_cmp_by_id_off(const void *a, const void *b) 3115 { 3116 const struct bpf_kfunc_desc *d0 = a; 3117 const struct bpf_kfunc_desc *d1 = b; 3118 3119 /* func_id is not greater than BTF_MAX_TYPE */ 3120 return d0->func_id - d1->func_id ?: d0->offset - d1->offset; 3121 } 3122 3123 static int kfunc_btf_cmp_by_off(const void *a, const void *b) 3124 { 3125 const struct bpf_kfunc_btf *d0 = a; 3126 const struct bpf_kfunc_btf *d1 = b; 3127 3128 return d0->offset - d1->offset; 3129 } 3130 3131 static const struct bpf_kfunc_desc * 3132 find_kfunc_desc(const struct bpf_prog *prog, u32 func_id, u16 offset) 3133 { 3134 struct bpf_kfunc_desc desc = { 3135 .func_id = func_id, 3136 .offset = offset, 3137 }; 3138 struct bpf_kfunc_desc_tab *tab; 3139 3140 tab = prog->aux->kfunc_tab; 3141 return bsearch(&desc, tab->descs, tab->nr_descs, 3142 sizeof(tab->descs[0]), kfunc_desc_cmp_by_id_off); 3143 } 3144 3145 int bpf_get_kfunc_addr(const struct bpf_prog *prog, u32 func_id, 3146 u16 btf_fd_idx, u8 **func_addr) 3147 { 3148 const struct bpf_kfunc_desc *desc; 3149 3150 desc = find_kfunc_desc(prog, func_id, btf_fd_idx); 3151 if (!desc) 3152 return -EFAULT; 3153 3154 *func_addr = (u8 *)desc->addr; 3155 return 0; 3156 } 3157 3158 static struct btf *__find_kfunc_desc_btf(struct bpf_verifier_env *env, 3159 s16 offset) 3160 { 3161 struct bpf_kfunc_btf kf_btf = { .offset = offset }; 3162 struct bpf_kfunc_btf_tab *tab; 3163 struct bpf_kfunc_btf *b; 3164 struct module *mod; 3165 struct btf *btf; 3166 int btf_fd; 3167 3168 tab = env->prog->aux->kfunc_btf_tab; 3169 b = bsearch(&kf_btf, tab->descs, tab->nr_descs, 3170 sizeof(tab->descs[0]), kfunc_btf_cmp_by_off); 3171 if (!b) { 3172 if (tab->nr_descs == MAX_KFUNC_BTFS) { 3173 verbose(env, "too many different module BTFs\n"); 3174 return ERR_PTR(-E2BIG); 3175 } 3176 3177 if (bpfptr_is_null(env->fd_array)) { 3178 verbose(env, "kfunc offset > 0 without fd_array is invalid\n"); 3179 return ERR_PTR(-EPROTO); 3180 } 3181 3182 if (copy_from_bpfptr_offset(&btf_fd, env->fd_array, 3183 offset * sizeof(btf_fd), 3184 sizeof(btf_fd))) 3185 return ERR_PTR(-EFAULT); 3186 3187 btf = btf_get_by_fd(btf_fd); 3188 if (IS_ERR(btf)) { 3189 verbose(env, "invalid module BTF fd specified\n"); 3190 return btf; 3191 } 3192 3193 if (!btf_is_module(btf)) { 3194 verbose(env, "BTF fd for kfunc is not a module BTF\n"); 3195 btf_put(btf); 3196 return ERR_PTR(-EINVAL); 3197 } 3198 3199 mod = btf_try_get_module(btf); 3200 if (!mod) { 3201 btf_put(btf); 3202 return ERR_PTR(-ENXIO); 3203 } 3204 3205 b = &tab->descs[tab->nr_descs++]; 3206 b->btf = btf; 3207 b->module = mod; 3208 b->offset = offset; 3209 3210 /* sort() reorders entries by value, so b may no longer point 3211 * to the right entry after this 3212 */ 3213 sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]), 3214 kfunc_btf_cmp_by_off, NULL); 3215 } else { 3216 btf = b->btf; 3217 } 3218 3219 return btf; 3220 } 3221 3222 void bpf_free_kfunc_btf_tab(struct bpf_kfunc_btf_tab *tab) 3223 { 3224 if (!tab) 3225 return; 3226 3227 while (tab->nr_descs--) { 3228 module_put(tab->descs[tab->nr_descs].module); 3229 btf_put(tab->descs[tab->nr_descs].btf); 3230 } 3231 kfree(tab); 3232 } 3233 3234 static struct btf *find_kfunc_desc_btf(struct bpf_verifier_env *env, s16 offset) 3235 { 3236 if (offset) { 3237 if (offset < 0) { 3238 /* In the future, this can be allowed to increase limit 3239 * of fd index into fd_array, interpreted as u16. 3240 */ 3241 verbose(env, "negative offset disallowed for kernel module function call\n"); 3242 return ERR_PTR(-EINVAL); 3243 } 3244 3245 return __find_kfunc_desc_btf(env, offset); 3246 } 3247 return btf_vmlinux ?: ERR_PTR(-ENOENT); 3248 } 3249 3250 static int add_kfunc_call(struct bpf_verifier_env *env, u32 func_id, s16 offset) 3251 { 3252 const struct btf_type *func, *func_proto; 3253 struct bpf_kfunc_btf_tab *btf_tab; 3254 struct bpf_kfunc_desc_tab *tab; 3255 struct bpf_prog_aux *prog_aux; 3256 struct bpf_kfunc_desc *desc; 3257 const char *func_name; 3258 struct btf *desc_btf; 3259 unsigned long call_imm; 3260 unsigned long addr; 3261 int err; 3262 3263 prog_aux = env->prog->aux; 3264 tab = prog_aux->kfunc_tab; 3265 btf_tab = prog_aux->kfunc_btf_tab; 3266 if (!tab) { 3267 if (!btf_vmlinux) { 3268 verbose(env, "calling kernel function is not supported without CONFIG_DEBUG_INFO_BTF\n"); 3269 return -ENOTSUPP; 3270 } 3271 3272 if (!env->prog->jit_requested) { 3273 verbose(env, "JIT is required for calling kernel function\n"); 3274 return -ENOTSUPP; 3275 } 3276 3277 if (!bpf_jit_supports_kfunc_call()) { 3278 verbose(env, "JIT does not support calling kernel function\n"); 3279 return -ENOTSUPP; 3280 } 3281 3282 if (!env->prog->gpl_compatible) { 3283 verbose(env, "cannot call kernel function from non-GPL compatible program\n"); 3284 return -EINVAL; 3285 } 3286 3287 tab = kzalloc(sizeof(*tab), GFP_KERNEL_ACCOUNT); 3288 if (!tab) 3289 return -ENOMEM; 3290 prog_aux->kfunc_tab = tab; 3291 } 3292 3293 /* func_id == 0 is always invalid, but instead of returning an error, be 3294 * conservative and wait until the code elimination pass before returning 3295 * error, so that invalid calls that get pruned out can be in BPF programs 3296 * loaded from userspace. It is also required that offset be untouched 3297 * for such calls. 3298 */ 3299 if (!func_id && !offset) 3300 return 0; 3301 3302 if (!btf_tab && offset) { 3303 btf_tab = kzalloc(sizeof(*btf_tab), GFP_KERNEL_ACCOUNT); 3304 if (!btf_tab) 3305 return -ENOMEM; 3306 prog_aux->kfunc_btf_tab = btf_tab; 3307 } 3308 3309 desc_btf = find_kfunc_desc_btf(env, offset); 3310 if (IS_ERR(desc_btf)) { 3311 verbose(env, "failed to find BTF for kernel function\n"); 3312 return PTR_ERR(desc_btf); 3313 } 3314 3315 if (find_kfunc_desc(env->prog, func_id, offset)) 3316 return 0; 3317 3318 if (tab->nr_descs == MAX_KFUNC_DESCS) { 3319 verbose(env, "too many different kernel function calls\n"); 3320 return -E2BIG; 3321 } 3322 3323 func = btf_type_by_id(desc_btf, func_id); 3324 if (!func || !btf_type_is_func(func)) { 3325 verbose(env, "kernel btf_id %u is not a function\n", 3326 func_id); 3327 return -EINVAL; 3328 } 3329 func_proto = btf_type_by_id(desc_btf, func->type); 3330 if (!func_proto || !btf_type_is_func_proto(func_proto)) { 3331 verbose(env, "kernel function btf_id %u does not have a valid func_proto\n", 3332 func_id); 3333 return -EINVAL; 3334 } 3335 3336 func_name = btf_name_by_offset(desc_btf, func->name_off); 3337 addr = kallsyms_lookup_name(func_name); 3338 if (!addr) { 3339 verbose(env, "cannot find address for kernel function %s\n", 3340 func_name); 3341 return -EINVAL; 3342 } 3343 specialize_kfunc(env, func_id, offset, &addr); 3344 3345 if (bpf_jit_supports_far_kfunc_call()) { 3346 call_imm = func_id; 3347 } else { 3348 call_imm = BPF_CALL_IMM(addr); 3349 /* Check whether the relative offset overflows desc->imm */ 3350 if ((unsigned long)(s32)call_imm != call_imm) { 3351 verbose(env, "address of kernel function %s is out of range\n", 3352 func_name); 3353 return -EINVAL; 3354 } 3355 } 3356 3357 if (bpf_dev_bound_kfunc_id(func_id)) { 3358 err = bpf_dev_bound_kfunc_check(&env->log, prog_aux); 3359 if (err) 3360 return err; 3361 } 3362 3363 desc = &tab->descs[tab->nr_descs++]; 3364 desc->func_id = func_id; 3365 desc->imm = call_imm; 3366 desc->offset = offset; 3367 desc->addr = addr; 3368 err = btf_distill_func_proto(&env->log, desc_btf, 3369 func_proto, func_name, 3370 &desc->func_model); 3371 if (!err) 3372 sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]), 3373 kfunc_desc_cmp_by_id_off, NULL); 3374 return err; 3375 } 3376 3377 static int kfunc_desc_cmp_by_imm_off(const void *a, const void *b) 3378 { 3379 const struct bpf_kfunc_desc *d0 = a; 3380 const struct bpf_kfunc_desc *d1 = b; 3381 3382 if (d0->imm != d1->imm) 3383 return d0->imm < d1->imm ? -1 : 1; 3384 if (d0->offset != d1->offset) 3385 return d0->offset < d1->offset ? -1 : 1; 3386 return 0; 3387 } 3388 3389 static void sort_kfunc_descs_by_imm_off(struct bpf_prog *prog) 3390 { 3391 struct bpf_kfunc_desc_tab *tab; 3392 3393 tab = prog->aux->kfunc_tab; 3394 if (!tab) 3395 return; 3396 3397 sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]), 3398 kfunc_desc_cmp_by_imm_off, NULL); 3399 } 3400 3401 bool bpf_prog_has_kfunc_call(const struct bpf_prog *prog) 3402 { 3403 return !!prog->aux->kfunc_tab; 3404 } 3405 3406 const struct btf_func_model * 3407 bpf_jit_find_kfunc_model(const struct bpf_prog *prog, 3408 const struct bpf_insn *insn) 3409 { 3410 const struct bpf_kfunc_desc desc = { 3411 .imm = insn->imm, 3412 .offset = insn->off, 3413 }; 3414 const struct bpf_kfunc_desc *res; 3415 struct bpf_kfunc_desc_tab *tab; 3416 3417 tab = prog->aux->kfunc_tab; 3418 res = bsearch(&desc, tab->descs, tab->nr_descs, 3419 sizeof(tab->descs[0]), kfunc_desc_cmp_by_imm_off); 3420 3421 return res ? &res->func_model : NULL; 3422 } 3423 3424 static int add_kfunc_in_insns(struct bpf_verifier_env *env, 3425 struct bpf_insn *insn, int cnt) 3426 { 3427 int i, ret; 3428 3429 for (i = 0; i < cnt; i++, insn++) { 3430 if (bpf_pseudo_kfunc_call(insn)) { 3431 ret = add_kfunc_call(env, insn->imm, insn->off); 3432 if (ret < 0) 3433 return ret; 3434 } 3435 } 3436 return 0; 3437 } 3438 3439 static int add_subprog_and_kfunc(struct bpf_verifier_env *env) 3440 { 3441 struct bpf_subprog_info *subprog = env->subprog_info; 3442 int i, ret, insn_cnt = env->prog->len, ex_cb_insn; 3443 struct bpf_insn *insn = env->prog->insnsi; 3444 3445 /* Add entry function. */ 3446 ret = add_subprog(env, 0); 3447 if (ret) 3448 return ret; 3449 3450 for (i = 0; i < insn_cnt; i++, insn++) { 3451 if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn) && 3452 !bpf_pseudo_kfunc_call(insn)) 3453 continue; 3454 3455 if (!env->bpf_capable) { 3456 verbose(env, "loading/calling other bpf or kernel functions are allowed for CAP_BPF and CAP_SYS_ADMIN\n"); 3457 return -EPERM; 3458 } 3459 3460 if (bpf_pseudo_func(insn) || bpf_pseudo_call(insn)) 3461 ret = add_subprog(env, i + insn->imm + 1); 3462 else 3463 ret = add_kfunc_call(env, insn->imm, insn->off); 3464 3465 if (ret < 0) 3466 return ret; 3467 } 3468 3469 ret = bpf_find_exception_callback_insn_off(env); 3470 if (ret < 0) 3471 return ret; 3472 ex_cb_insn = ret; 3473 3474 /* If ex_cb_insn > 0, this means that the main program has a subprog 3475 * marked using BTF decl tag to serve as the exception callback. 3476 */ 3477 if (ex_cb_insn) { 3478 ret = add_subprog(env, ex_cb_insn); 3479 if (ret < 0) 3480 return ret; 3481 for (i = 1; i < env->subprog_cnt; i++) { 3482 if (env->subprog_info[i].start != ex_cb_insn) 3483 continue; 3484 env->exception_callback_subprog = i; 3485 mark_subprog_exc_cb(env, i); 3486 break; 3487 } 3488 } 3489 3490 /* Add a fake 'exit' subprog which could simplify subprog iteration 3491 * logic. 'subprog_cnt' should not be increased. 3492 */ 3493 subprog[env->subprog_cnt].start = insn_cnt; 3494 3495 if (env->log.level & BPF_LOG_LEVEL2) 3496 for (i = 0; i < env->subprog_cnt; i++) 3497 verbose(env, "func#%d @%d\n", i, subprog[i].start); 3498 3499 return 0; 3500 } 3501 3502 static int jmp_offset(struct bpf_insn *insn) 3503 { 3504 u8 code = insn->code; 3505 3506 if (code == (BPF_JMP32 | BPF_JA)) 3507 return insn->imm; 3508 return insn->off; 3509 } 3510 3511 static int check_subprogs(struct bpf_verifier_env *env) 3512 { 3513 int i, subprog_start, subprog_end, off, cur_subprog = 0; 3514 struct bpf_subprog_info *subprog = env->subprog_info; 3515 struct bpf_insn *insn = env->prog->insnsi; 3516 int insn_cnt = env->prog->len; 3517 3518 /* now check that all jumps are within the same subprog */ 3519 subprog_start = subprog[cur_subprog].start; 3520 subprog_end = subprog[cur_subprog + 1].start; 3521 for (i = 0; i < insn_cnt; i++) { 3522 u8 code = insn[i].code; 3523 3524 if (code == (BPF_JMP | BPF_CALL) && 3525 insn[i].src_reg == 0 && 3526 insn[i].imm == BPF_FUNC_tail_call) { 3527 subprog[cur_subprog].has_tail_call = true; 3528 subprog[cur_subprog].tail_call_reachable = true; 3529 } 3530 if (BPF_CLASS(code) == BPF_LD && 3531 (BPF_MODE(code) == BPF_ABS || BPF_MODE(code) == BPF_IND)) 3532 subprog[cur_subprog].has_ld_abs = true; 3533 if (BPF_CLASS(code) != BPF_JMP && BPF_CLASS(code) != BPF_JMP32) 3534 goto next; 3535 if (BPF_OP(code) == BPF_EXIT || BPF_OP(code) == BPF_CALL) 3536 goto next; 3537 off = i + jmp_offset(&insn[i]) + 1; 3538 if (off < subprog_start || off >= subprog_end) { 3539 verbose(env, "jump out of range from insn %d to %d\n", i, off); 3540 return -EINVAL; 3541 } 3542 next: 3543 if (i == subprog_end - 1) { 3544 /* to avoid fall-through from one subprog into another 3545 * the last insn of the subprog should be either exit 3546 * or unconditional jump back or bpf_throw call 3547 */ 3548 if (code != (BPF_JMP | BPF_EXIT) && 3549 code != (BPF_JMP32 | BPF_JA) && 3550 code != (BPF_JMP | BPF_JA)) { 3551 verbose(env, "last insn is not an exit or jmp\n"); 3552 return -EINVAL; 3553 } 3554 subprog_start = subprog_end; 3555 cur_subprog++; 3556 if (cur_subprog < env->subprog_cnt) 3557 subprog_end = subprog[cur_subprog + 1].start; 3558 } 3559 } 3560 return 0; 3561 } 3562 3563 /* Parentage chain of this register (or stack slot) should take care of all 3564 * issues like callee-saved registers, stack slot allocation time, etc. 3565 */ 3566 static int mark_reg_read(struct bpf_verifier_env *env, 3567 const struct bpf_reg_state *state, 3568 struct bpf_reg_state *parent, u8 flag) 3569 { 3570 bool writes = parent == state->parent; /* Observe write marks */ 3571 int cnt = 0; 3572 3573 while (parent) { 3574 /* if read wasn't screened by an earlier write ... */ 3575 if (writes && state->live & REG_LIVE_WRITTEN) 3576 break; 3577 if (verifier_bug_if(parent->live & REG_LIVE_DONE, env, 3578 "type %s var_off %lld off %d", 3579 reg_type_str(env, parent->type), 3580 parent->var_off.value, parent->off)) 3581 return -EFAULT; 3582 /* The first condition is more likely to be true than the 3583 * second, checked it first. 3584 */ 3585 if ((parent->live & REG_LIVE_READ) == flag || 3586 parent->live & REG_LIVE_READ64) 3587 /* The parentage chain never changes and 3588 * this parent was already marked as LIVE_READ. 3589 * There is no need to keep walking the chain again and 3590 * keep re-marking all parents as LIVE_READ. 3591 * This case happens when the same register is read 3592 * multiple times without writes into it in-between. 3593 * Also, if parent has the stronger REG_LIVE_READ64 set, 3594 * then no need to set the weak REG_LIVE_READ32. 3595 */ 3596 break; 3597 /* ... then we depend on parent's value */ 3598 parent->live |= flag; 3599 /* REG_LIVE_READ64 overrides REG_LIVE_READ32. */ 3600 if (flag == REG_LIVE_READ64) 3601 parent->live &= ~REG_LIVE_READ32; 3602 state = parent; 3603 parent = state->parent; 3604 writes = true; 3605 cnt++; 3606 } 3607 3608 if (env->longest_mark_read_walk < cnt) 3609 env->longest_mark_read_walk = cnt; 3610 return 0; 3611 } 3612 3613 static int mark_stack_slot_obj_read(struct bpf_verifier_env *env, struct bpf_reg_state *reg, 3614 int spi, int nr_slots) 3615 { 3616 struct bpf_func_state *state = func(env, reg); 3617 int err, i; 3618 3619 for (i = 0; i < nr_slots; i++) { 3620 struct bpf_reg_state *st = &state->stack[spi - i].spilled_ptr; 3621 3622 err = mark_reg_read(env, st, st->parent, REG_LIVE_READ64); 3623 if (err) 3624 return err; 3625 3626 mark_stack_slot_scratched(env, spi - i); 3627 } 3628 return 0; 3629 } 3630 3631 static int mark_dynptr_read(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 3632 { 3633 int spi; 3634 3635 /* For CONST_PTR_TO_DYNPTR, it must have already been done by 3636 * check_reg_arg in check_helper_call and mark_btf_func_reg_size in 3637 * check_kfunc_call. 3638 */ 3639 if (reg->type == CONST_PTR_TO_DYNPTR) 3640 return 0; 3641 spi = dynptr_get_spi(env, reg); 3642 if (spi < 0) 3643 return spi; 3644 /* Caller ensures dynptr is valid and initialized, which means spi is in 3645 * bounds and spi is the first dynptr slot. Simply mark stack slot as 3646 * read. 3647 */ 3648 return mark_stack_slot_obj_read(env, reg, spi, BPF_DYNPTR_NR_SLOTS); 3649 } 3650 3651 static int mark_iter_read(struct bpf_verifier_env *env, struct bpf_reg_state *reg, 3652 int spi, int nr_slots) 3653 { 3654 return mark_stack_slot_obj_read(env, reg, spi, nr_slots); 3655 } 3656 3657 static int mark_irq_flag_read(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 3658 { 3659 int spi; 3660 3661 spi = irq_flag_get_spi(env, reg); 3662 if (spi < 0) 3663 return spi; 3664 return mark_stack_slot_obj_read(env, reg, spi, 1); 3665 } 3666 3667 /* This function is supposed to be used by the following 32-bit optimization 3668 * code only. It returns TRUE if the source or destination register operates 3669 * on 64-bit, otherwise return FALSE. 3670 */ 3671 static bool is_reg64(struct bpf_verifier_env *env, struct bpf_insn *insn, 3672 u32 regno, struct bpf_reg_state *reg, enum reg_arg_type t) 3673 { 3674 u8 code, class, op; 3675 3676 code = insn->code; 3677 class = BPF_CLASS(code); 3678 op = BPF_OP(code); 3679 if (class == BPF_JMP) { 3680 /* BPF_EXIT for "main" will reach here. Return TRUE 3681 * conservatively. 3682 */ 3683 if (op == BPF_EXIT) 3684 return true; 3685 if (op == BPF_CALL) { 3686 /* BPF to BPF call will reach here because of marking 3687 * caller saved clobber with DST_OP_NO_MARK for which we 3688 * don't care the register def because they are anyway 3689 * marked as NOT_INIT already. 3690 */ 3691 if (insn->src_reg == BPF_PSEUDO_CALL) 3692 return false; 3693 /* Helper call will reach here because of arg type 3694 * check, conservatively return TRUE. 3695 */ 3696 if (t == SRC_OP) 3697 return true; 3698 3699 return false; 3700 } 3701 } 3702 3703 if (class == BPF_ALU64 && op == BPF_END && (insn->imm == 16 || insn->imm == 32)) 3704 return false; 3705 3706 if (class == BPF_ALU64 || class == BPF_JMP || 3707 (class == BPF_ALU && op == BPF_END && insn->imm == 64)) 3708 return true; 3709 3710 if (class == BPF_ALU || class == BPF_JMP32) 3711 return false; 3712 3713 if (class == BPF_LDX) { 3714 if (t != SRC_OP) 3715 return BPF_SIZE(code) == BPF_DW || BPF_MODE(code) == BPF_MEMSX; 3716 /* LDX source must be ptr. */ 3717 return true; 3718 } 3719 3720 if (class == BPF_STX) { 3721 /* BPF_STX (including atomic variants) has one or more source 3722 * operands, one of which is a ptr. Check whether the caller is 3723 * asking about it. 3724 */ 3725 if (t == SRC_OP && reg->type != SCALAR_VALUE) 3726 return true; 3727 return BPF_SIZE(code) == BPF_DW; 3728 } 3729 3730 if (class == BPF_LD) { 3731 u8 mode = BPF_MODE(code); 3732 3733 /* LD_IMM64 */ 3734 if (mode == BPF_IMM) 3735 return true; 3736 3737 /* Both LD_IND and LD_ABS return 32-bit data. */ 3738 if (t != SRC_OP) 3739 return false; 3740 3741 /* Implicit ctx ptr. */ 3742 if (regno == BPF_REG_6) 3743 return true; 3744 3745 /* Explicit source could be any width. */ 3746 return true; 3747 } 3748 3749 if (class == BPF_ST) 3750 /* The only source register for BPF_ST is a ptr. */ 3751 return true; 3752 3753 /* Conservatively return true at default. */ 3754 return true; 3755 } 3756 3757 /* Return the regno defined by the insn, or -1. */ 3758 static int insn_def_regno(const struct bpf_insn *insn) 3759 { 3760 switch (BPF_CLASS(insn->code)) { 3761 case BPF_JMP: 3762 case BPF_JMP32: 3763 case BPF_ST: 3764 return -1; 3765 case BPF_STX: 3766 if (BPF_MODE(insn->code) == BPF_ATOMIC || 3767 BPF_MODE(insn->code) == BPF_PROBE_ATOMIC) { 3768 if (insn->imm == BPF_CMPXCHG) 3769 return BPF_REG_0; 3770 else if (insn->imm == BPF_LOAD_ACQ) 3771 return insn->dst_reg; 3772 else if (insn->imm & BPF_FETCH) 3773 return insn->src_reg; 3774 } 3775 return -1; 3776 default: 3777 return insn->dst_reg; 3778 } 3779 } 3780 3781 /* Return TRUE if INSN has defined any 32-bit value explicitly. */ 3782 static bool insn_has_def32(struct bpf_verifier_env *env, struct bpf_insn *insn) 3783 { 3784 int dst_reg = insn_def_regno(insn); 3785 3786 if (dst_reg == -1) 3787 return false; 3788 3789 return !is_reg64(env, insn, dst_reg, NULL, DST_OP); 3790 } 3791 3792 static void mark_insn_zext(struct bpf_verifier_env *env, 3793 struct bpf_reg_state *reg) 3794 { 3795 s32 def_idx = reg->subreg_def; 3796 3797 if (def_idx == DEF_NOT_SUBREG) 3798 return; 3799 3800 env->insn_aux_data[def_idx - 1].zext_dst = true; 3801 /* The dst will be zero extended, so won't be sub-register anymore. */ 3802 reg->subreg_def = DEF_NOT_SUBREG; 3803 } 3804 3805 static int __check_reg_arg(struct bpf_verifier_env *env, struct bpf_reg_state *regs, u32 regno, 3806 enum reg_arg_type t) 3807 { 3808 struct bpf_insn *insn = env->prog->insnsi + env->insn_idx; 3809 struct bpf_reg_state *reg; 3810 bool rw64; 3811 3812 if (regno >= MAX_BPF_REG) { 3813 verbose(env, "R%d is invalid\n", regno); 3814 return -EINVAL; 3815 } 3816 3817 mark_reg_scratched(env, regno); 3818 3819 reg = ®s[regno]; 3820 rw64 = is_reg64(env, insn, regno, reg, t); 3821 if (t == SRC_OP) { 3822 /* check whether register used as source operand can be read */ 3823 if (reg->type == NOT_INIT) { 3824 verbose(env, "R%d !read_ok\n", regno); 3825 return -EACCES; 3826 } 3827 /* We don't need to worry about FP liveness because it's read-only */ 3828 if (regno == BPF_REG_FP) 3829 return 0; 3830 3831 if (rw64) 3832 mark_insn_zext(env, reg); 3833 3834 return mark_reg_read(env, reg, reg->parent, 3835 rw64 ? REG_LIVE_READ64 : REG_LIVE_READ32); 3836 } else { 3837 /* check whether register used as dest operand can be written to */ 3838 if (regno == BPF_REG_FP) { 3839 verbose(env, "frame pointer is read only\n"); 3840 return -EACCES; 3841 } 3842 reg->live |= REG_LIVE_WRITTEN; 3843 reg->subreg_def = rw64 ? DEF_NOT_SUBREG : env->insn_idx + 1; 3844 if (t == DST_OP) 3845 mark_reg_unknown(env, regs, regno); 3846 } 3847 return 0; 3848 } 3849 3850 static int check_reg_arg(struct bpf_verifier_env *env, u32 regno, 3851 enum reg_arg_type t) 3852 { 3853 struct bpf_verifier_state *vstate = env->cur_state; 3854 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 3855 3856 return __check_reg_arg(env, state->regs, regno, t); 3857 } 3858 3859 static int insn_stack_access_flags(int frameno, int spi) 3860 { 3861 return INSN_F_STACK_ACCESS | (spi << INSN_F_SPI_SHIFT) | frameno; 3862 } 3863 3864 static int insn_stack_access_spi(int insn_flags) 3865 { 3866 return (insn_flags >> INSN_F_SPI_SHIFT) & INSN_F_SPI_MASK; 3867 } 3868 3869 static int insn_stack_access_frameno(int insn_flags) 3870 { 3871 return insn_flags & INSN_F_FRAMENO_MASK; 3872 } 3873 3874 static void mark_jmp_point(struct bpf_verifier_env *env, int idx) 3875 { 3876 env->insn_aux_data[idx].jmp_point = true; 3877 } 3878 3879 static bool is_jmp_point(struct bpf_verifier_env *env, int insn_idx) 3880 { 3881 return env->insn_aux_data[insn_idx].jmp_point; 3882 } 3883 3884 #define LR_FRAMENO_BITS 3 3885 #define LR_SPI_BITS 6 3886 #define LR_ENTRY_BITS (LR_SPI_BITS + LR_FRAMENO_BITS + 1) 3887 #define LR_SIZE_BITS 4 3888 #define LR_FRAMENO_MASK ((1ull << LR_FRAMENO_BITS) - 1) 3889 #define LR_SPI_MASK ((1ull << LR_SPI_BITS) - 1) 3890 #define LR_SIZE_MASK ((1ull << LR_SIZE_BITS) - 1) 3891 #define LR_SPI_OFF LR_FRAMENO_BITS 3892 #define LR_IS_REG_OFF (LR_SPI_BITS + LR_FRAMENO_BITS) 3893 #define LINKED_REGS_MAX 6 3894 3895 struct linked_reg { 3896 u8 frameno; 3897 union { 3898 u8 spi; 3899 u8 regno; 3900 }; 3901 bool is_reg; 3902 }; 3903 3904 struct linked_regs { 3905 int cnt; 3906 struct linked_reg entries[LINKED_REGS_MAX]; 3907 }; 3908 3909 static struct linked_reg *linked_regs_push(struct linked_regs *s) 3910 { 3911 if (s->cnt < LINKED_REGS_MAX) 3912 return &s->entries[s->cnt++]; 3913 3914 return NULL; 3915 } 3916 3917 /* Use u64 as a vector of 6 10-bit values, use first 4-bits to track 3918 * number of elements currently in stack. 3919 * Pack one history entry for linked registers as 10 bits in the following format: 3920 * - 3-bits frameno 3921 * - 6-bits spi_or_reg 3922 * - 1-bit is_reg 3923 */ 3924 static u64 linked_regs_pack(struct linked_regs *s) 3925 { 3926 u64 val = 0; 3927 int i; 3928 3929 for (i = 0; i < s->cnt; ++i) { 3930 struct linked_reg *e = &s->entries[i]; 3931 u64 tmp = 0; 3932 3933 tmp |= e->frameno; 3934 tmp |= e->spi << LR_SPI_OFF; 3935 tmp |= (e->is_reg ? 1 : 0) << LR_IS_REG_OFF; 3936 3937 val <<= LR_ENTRY_BITS; 3938 val |= tmp; 3939 } 3940 val <<= LR_SIZE_BITS; 3941 val |= s->cnt; 3942 return val; 3943 } 3944 3945 static void linked_regs_unpack(u64 val, struct linked_regs *s) 3946 { 3947 int i; 3948 3949 s->cnt = val & LR_SIZE_MASK; 3950 val >>= LR_SIZE_BITS; 3951 3952 for (i = 0; i < s->cnt; ++i) { 3953 struct linked_reg *e = &s->entries[i]; 3954 3955 e->frameno = val & LR_FRAMENO_MASK; 3956 e->spi = (val >> LR_SPI_OFF) & LR_SPI_MASK; 3957 e->is_reg = (val >> LR_IS_REG_OFF) & 0x1; 3958 val >>= LR_ENTRY_BITS; 3959 } 3960 } 3961 3962 /* for any branch, call, exit record the history of jmps in the given state */ 3963 static int push_jmp_history(struct bpf_verifier_env *env, struct bpf_verifier_state *cur, 3964 int insn_flags, u64 linked_regs) 3965 { 3966 u32 cnt = cur->jmp_history_cnt; 3967 struct bpf_jmp_history_entry *p; 3968 size_t alloc_size; 3969 3970 /* combine instruction flags if we already recorded this instruction */ 3971 if (env->cur_hist_ent) { 3972 /* atomic instructions push insn_flags twice, for READ and 3973 * WRITE sides, but they should agree on stack slot 3974 */ 3975 verifier_bug_if((env->cur_hist_ent->flags & insn_flags) && 3976 (env->cur_hist_ent->flags & insn_flags) != insn_flags, 3977 env, "insn history: insn_idx %d cur flags %x new flags %x", 3978 env->insn_idx, env->cur_hist_ent->flags, insn_flags); 3979 env->cur_hist_ent->flags |= insn_flags; 3980 verifier_bug_if(env->cur_hist_ent->linked_regs != 0, env, 3981 "insn history: insn_idx %d linked_regs: %#llx", 3982 env->insn_idx, env->cur_hist_ent->linked_regs); 3983 env->cur_hist_ent->linked_regs = linked_regs; 3984 return 0; 3985 } 3986 3987 cnt++; 3988 alloc_size = kmalloc_size_roundup(size_mul(cnt, sizeof(*p))); 3989 p = krealloc(cur->jmp_history, alloc_size, GFP_KERNEL_ACCOUNT); 3990 if (!p) 3991 return -ENOMEM; 3992 cur->jmp_history = p; 3993 3994 p = &cur->jmp_history[cnt - 1]; 3995 p->idx = env->insn_idx; 3996 p->prev_idx = env->prev_insn_idx; 3997 p->flags = insn_flags; 3998 p->linked_regs = linked_regs; 3999 cur->jmp_history_cnt = cnt; 4000 env->cur_hist_ent = p; 4001 4002 return 0; 4003 } 4004 4005 static struct bpf_jmp_history_entry *get_jmp_hist_entry(struct bpf_verifier_state *st, 4006 u32 hist_end, int insn_idx) 4007 { 4008 if (hist_end > 0 && st->jmp_history[hist_end - 1].idx == insn_idx) 4009 return &st->jmp_history[hist_end - 1]; 4010 return NULL; 4011 } 4012 4013 /* Backtrack one insn at a time. If idx is not at the top of recorded 4014 * history then previous instruction came from straight line execution. 4015 * Return -ENOENT if we exhausted all instructions within given state. 4016 * 4017 * It's legal to have a bit of a looping with the same starting and ending 4018 * insn index within the same state, e.g.: 3->4->5->3, so just because current 4019 * instruction index is the same as state's first_idx doesn't mean we are 4020 * done. If there is still some jump history left, we should keep going. We 4021 * need to take into account that we might have a jump history between given 4022 * state's parent and itself, due to checkpointing. In this case, we'll have 4023 * history entry recording a jump from last instruction of parent state and 4024 * first instruction of given state. 4025 */ 4026 static int get_prev_insn_idx(struct bpf_verifier_state *st, int i, 4027 u32 *history) 4028 { 4029 u32 cnt = *history; 4030 4031 if (i == st->first_insn_idx) { 4032 if (cnt == 0) 4033 return -ENOENT; 4034 if (cnt == 1 && st->jmp_history[0].idx == i) 4035 return -ENOENT; 4036 } 4037 4038 if (cnt && st->jmp_history[cnt - 1].idx == i) { 4039 i = st->jmp_history[cnt - 1].prev_idx; 4040 (*history)--; 4041 } else { 4042 i--; 4043 } 4044 return i; 4045 } 4046 4047 static const char *disasm_kfunc_name(void *data, const struct bpf_insn *insn) 4048 { 4049 const struct btf_type *func; 4050 struct btf *desc_btf; 4051 4052 if (insn->src_reg != BPF_PSEUDO_KFUNC_CALL) 4053 return NULL; 4054 4055 desc_btf = find_kfunc_desc_btf(data, insn->off); 4056 if (IS_ERR(desc_btf)) 4057 return "<error>"; 4058 4059 func = btf_type_by_id(desc_btf, insn->imm); 4060 return btf_name_by_offset(desc_btf, func->name_off); 4061 } 4062 4063 static void verbose_insn(struct bpf_verifier_env *env, struct bpf_insn *insn) 4064 { 4065 const struct bpf_insn_cbs cbs = { 4066 .cb_call = disasm_kfunc_name, 4067 .cb_print = verbose, 4068 .private_data = env, 4069 }; 4070 4071 print_bpf_insn(&cbs, insn, env->allow_ptr_leaks); 4072 } 4073 4074 static inline void bt_init(struct backtrack_state *bt, u32 frame) 4075 { 4076 bt->frame = frame; 4077 } 4078 4079 static inline void bt_reset(struct backtrack_state *bt) 4080 { 4081 struct bpf_verifier_env *env = bt->env; 4082 4083 memset(bt, 0, sizeof(*bt)); 4084 bt->env = env; 4085 } 4086 4087 static inline u32 bt_empty(struct backtrack_state *bt) 4088 { 4089 u64 mask = 0; 4090 int i; 4091 4092 for (i = 0; i <= bt->frame; i++) 4093 mask |= bt->reg_masks[i] | bt->stack_masks[i]; 4094 4095 return mask == 0; 4096 } 4097 4098 static inline int bt_subprog_enter(struct backtrack_state *bt) 4099 { 4100 if (bt->frame == MAX_CALL_FRAMES - 1) { 4101 verifier_bug(bt->env, "subprog enter from frame %d", bt->frame); 4102 return -EFAULT; 4103 } 4104 bt->frame++; 4105 return 0; 4106 } 4107 4108 static inline int bt_subprog_exit(struct backtrack_state *bt) 4109 { 4110 if (bt->frame == 0) { 4111 verifier_bug(bt->env, "subprog exit from frame 0"); 4112 return -EFAULT; 4113 } 4114 bt->frame--; 4115 return 0; 4116 } 4117 4118 static inline void bt_set_frame_reg(struct backtrack_state *bt, u32 frame, u32 reg) 4119 { 4120 bt->reg_masks[frame] |= 1 << reg; 4121 } 4122 4123 static inline void bt_clear_frame_reg(struct backtrack_state *bt, u32 frame, u32 reg) 4124 { 4125 bt->reg_masks[frame] &= ~(1 << reg); 4126 } 4127 4128 static inline void bt_set_reg(struct backtrack_state *bt, u32 reg) 4129 { 4130 bt_set_frame_reg(bt, bt->frame, reg); 4131 } 4132 4133 static inline void bt_clear_reg(struct backtrack_state *bt, u32 reg) 4134 { 4135 bt_clear_frame_reg(bt, bt->frame, reg); 4136 } 4137 4138 static inline void bt_set_frame_slot(struct backtrack_state *bt, u32 frame, u32 slot) 4139 { 4140 bt->stack_masks[frame] |= 1ull << slot; 4141 } 4142 4143 static inline void bt_clear_frame_slot(struct backtrack_state *bt, u32 frame, u32 slot) 4144 { 4145 bt->stack_masks[frame] &= ~(1ull << slot); 4146 } 4147 4148 static inline u32 bt_frame_reg_mask(struct backtrack_state *bt, u32 frame) 4149 { 4150 return bt->reg_masks[frame]; 4151 } 4152 4153 static inline u32 bt_reg_mask(struct backtrack_state *bt) 4154 { 4155 return bt->reg_masks[bt->frame]; 4156 } 4157 4158 static inline u64 bt_frame_stack_mask(struct backtrack_state *bt, u32 frame) 4159 { 4160 return bt->stack_masks[frame]; 4161 } 4162 4163 static inline u64 bt_stack_mask(struct backtrack_state *bt) 4164 { 4165 return bt->stack_masks[bt->frame]; 4166 } 4167 4168 static inline bool bt_is_reg_set(struct backtrack_state *bt, u32 reg) 4169 { 4170 return bt->reg_masks[bt->frame] & (1 << reg); 4171 } 4172 4173 static inline bool bt_is_frame_reg_set(struct backtrack_state *bt, u32 frame, u32 reg) 4174 { 4175 return bt->reg_masks[frame] & (1 << reg); 4176 } 4177 4178 static inline bool bt_is_frame_slot_set(struct backtrack_state *bt, u32 frame, u32 slot) 4179 { 4180 return bt->stack_masks[frame] & (1ull << slot); 4181 } 4182 4183 /* format registers bitmask, e.g., "r0,r2,r4" for 0x15 mask */ 4184 static void fmt_reg_mask(char *buf, ssize_t buf_sz, u32 reg_mask) 4185 { 4186 DECLARE_BITMAP(mask, 64); 4187 bool first = true; 4188 int i, n; 4189 4190 buf[0] = '\0'; 4191 4192 bitmap_from_u64(mask, reg_mask); 4193 for_each_set_bit(i, mask, 32) { 4194 n = snprintf(buf, buf_sz, "%sr%d", first ? "" : ",", i); 4195 first = false; 4196 buf += n; 4197 buf_sz -= n; 4198 if (buf_sz < 0) 4199 break; 4200 } 4201 } 4202 /* format stack slots bitmask, e.g., "-8,-24,-40" for 0x15 mask */ 4203 static void fmt_stack_mask(char *buf, ssize_t buf_sz, u64 stack_mask) 4204 { 4205 DECLARE_BITMAP(mask, 64); 4206 bool first = true; 4207 int i, n; 4208 4209 buf[0] = '\0'; 4210 4211 bitmap_from_u64(mask, stack_mask); 4212 for_each_set_bit(i, mask, 64) { 4213 n = snprintf(buf, buf_sz, "%s%d", first ? "" : ",", -(i + 1) * 8); 4214 first = false; 4215 buf += n; 4216 buf_sz -= n; 4217 if (buf_sz < 0) 4218 break; 4219 } 4220 } 4221 4222 /* If any register R in hist->linked_regs is marked as precise in bt, 4223 * do bt_set_frame_{reg,slot}(bt, R) for all registers in hist->linked_regs. 4224 */ 4225 static void bt_sync_linked_regs(struct backtrack_state *bt, struct bpf_jmp_history_entry *hist) 4226 { 4227 struct linked_regs linked_regs; 4228 bool some_precise = false; 4229 int i; 4230 4231 if (!hist || hist->linked_regs == 0) 4232 return; 4233 4234 linked_regs_unpack(hist->linked_regs, &linked_regs); 4235 for (i = 0; i < linked_regs.cnt; ++i) { 4236 struct linked_reg *e = &linked_regs.entries[i]; 4237 4238 if ((e->is_reg && bt_is_frame_reg_set(bt, e->frameno, e->regno)) || 4239 (!e->is_reg && bt_is_frame_slot_set(bt, e->frameno, e->spi))) { 4240 some_precise = true; 4241 break; 4242 } 4243 } 4244 4245 if (!some_precise) 4246 return; 4247 4248 for (i = 0; i < linked_regs.cnt; ++i) { 4249 struct linked_reg *e = &linked_regs.entries[i]; 4250 4251 if (e->is_reg) 4252 bt_set_frame_reg(bt, e->frameno, e->regno); 4253 else 4254 bt_set_frame_slot(bt, e->frameno, e->spi); 4255 } 4256 } 4257 4258 static bool calls_callback(struct bpf_verifier_env *env, int insn_idx); 4259 4260 /* For given verifier state backtrack_insn() is called from the last insn to 4261 * the first insn. Its purpose is to compute a bitmask of registers and 4262 * stack slots that needs precision in the parent verifier state. 4263 * 4264 * @idx is an index of the instruction we are currently processing; 4265 * @subseq_idx is an index of the subsequent instruction that: 4266 * - *would be* executed next, if jump history is viewed in forward order; 4267 * - *was* processed previously during backtracking. 4268 */ 4269 static int backtrack_insn(struct bpf_verifier_env *env, int idx, int subseq_idx, 4270 struct bpf_jmp_history_entry *hist, struct backtrack_state *bt) 4271 { 4272 struct bpf_insn *insn = env->prog->insnsi + idx; 4273 u8 class = BPF_CLASS(insn->code); 4274 u8 opcode = BPF_OP(insn->code); 4275 u8 mode = BPF_MODE(insn->code); 4276 u32 dreg = insn->dst_reg; 4277 u32 sreg = insn->src_reg; 4278 u32 spi, i, fr; 4279 4280 if (insn->code == 0) 4281 return 0; 4282 if (env->log.level & BPF_LOG_LEVEL2) { 4283 fmt_reg_mask(env->tmp_str_buf, TMP_STR_BUF_LEN, bt_reg_mask(bt)); 4284 verbose(env, "mark_precise: frame%d: regs=%s ", 4285 bt->frame, env->tmp_str_buf); 4286 fmt_stack_mask(env->tmp_str_buf, TMP_STR_BUF_LEN, bt_stack_mask(bt)); 4287 verbose(env, "stack=%s before ", env->tmp_str_buf); 4288 verbose(env, "%d: ", idx); 4289 verbose_insn(env, insn); 4290 } 4291 4292 /* If there is a history record that some registers gained range at this insn, 4293 * propagate precision marks to those registers, so that bt_is_reg_set() 4294 * accounts for these registers. 4295 */ 4296 bt_sync_linked_regs(bt, hist); 4297 4298 if (class == BPF_ALU || class == BPF_ALU64) { 4299 if (!bt_is_reg_set(bt, dreg)) 4300 return 0; 4301 if (opcode == BPF_END || opcode == BPF_NEG) { 4302 /* sreg is reserved and unused 4303 * dreg still need precision before this insn 4304 */ 4305 return 0; 4306 } else if (opcode == BPF_MOV) { 4307 if (BPF_SRC(insn->code) == BPF_X) { 4308 /* dreg = sreg or dreg = (s8, s16, s32)sreg 4309 * dreg needs precision after this insn 4310 * sreg needs precision before this insn 4311 */ 4312 bt_clear_reg(bt, dreg); 4313 if (sreg != BPF_REG_FP) 4314 bt_set_reg(bt, sreg); 4315 } else { 4316 /* dreg = K 4317 * dreg needs precision after this insn. 4318 * Corresponding register is already marked 4319 * as precise=true in this verifier state. 4320 * No further markings in parent are necessary 4321 */ 4322 bt_clear_reg(bt, dreg); 4323 } 4324 } else { 4325 if (BPF_SRC(insn->code) == BPF_X) { 4326 /* dreg += sreg 4327 * both dreg and sreg need precision 4328 * before this insn 4329 */ 4330 if (sreg != BPF_REG_FP) 4331 bt_set_reg(bt, sreg); 4332 } /* else dreg += K 4333 * dreg still needs precision before this insn 4334 */ 4335 } 4336 } else if (class == BPF_LDX || is_atomic_load_insn(insn)) { 4337 if (!bt_is_reg_set(bt, dreg)) 4338 return 0; 4339 bt_clear_reg(bt, dreg); 4340 4341 /* scalars can only be spilled into stack w/o losing precision. 4342 * Load from any other memory can be zero extended. 4343 * The desire to keep that precision is already indicated 4344 * by 'precise' mark in corresponding register of this state. 4345 * No further tracking necessary. 4346 */ 4347 if (!hist || !(hist->flags & INSN_F_STACK_ACCESS)) 4348 return 0; 4349 /* dreg = *(u64 *)[fp - off] was a fill from the stack. 4350 * that [fp - off] slot contains scalar that needs to be 4351 * tracked with precision 4352 */ 4353 spi = insn_stack_access_spi(hist->flags); 4354 fr = insn_stack_access_frameno(hist->flags); 4355 bt_set_frame_slot(bt, fr, spi); 4356 } else if (class == BPF_STX || class == BPF_ST) { 4357 if (bt_is_reg_set(bt, dreg)) 4358 /* stx & st shouldn't be using _scalar_ dst_reg 4359 * to access memory. It means backtracking 4360 * encountered a case of pointer subtraction. 4361 */ 4362 return -ENOTSUPP; 4363 /* scalars can only be spilled into stack */ 4364 if (!hist || !(hist->flags & INSN_F_STACK_ACCESS)) 4365 return 0; 4366 spi = insn_stack_access_spi(hist->flags); 4367 fr = insn_stack_access_frameno(hist->flags); 4368 if (!bt_is_frame_slot_set(bt, fr, spi)) 4369 return 0; 4370 bt_clear_frame_slot(bt, fr, spi); 4371 if (class == BPF_STX) 4372 bt_set_reg(bt, sreg); 4373 } else if (class == BPF_JMP || class == BPF_JMP32) { 4374 if (bpf_pseudo_call(insn)) { 4375 int subprog_insn_idx, subprog; 4376 4377 subprog_insn_idx = idx + insn->imm + 1; 4378 subprog = find_subprog(env, subprog_insn_idx); 4379 if (subprog < 0) 4380 return -EFAULT; 4381 4382 if (subprog_is_global(env, subprog)) { 4383 /* check that jump history doesn't have any 4384 * extra instructions from subprog; the next 4385 * instruction after call to global subprog 4386 * should be literally next instruction in 4387 * caller program 4388 */ 4389 verifier_bug_if(idx + 1 != subseq_idx, env, 4390 "extra insn from subprog"); 4391 /* r1-r5 are invalidated after subprog call, 4392 * so for global func call it shouldn't be set 4393 * anymore 4394 */ 4395 if (bt_reg_mask(bt) & BPF_REGMASK_ARGS) { 4396 verifier_bug(env, "global subprog unexpected regs %x", 4397 bt_reg_mask(bt)); 4398 return -EFAULT; 4399 } 4400 /* global subprog always sets R0 */ 4401 bt_clear_reg(bt, BPF_REG_0); 4402 return 0; 4403 } else { 4404 /* static subprog call instruction, which 4405 * means that we are exiting current subprog, 4406 * so only r1-r5 could be still requested as 4407 * precise, r0 and r6-r10 or any stack slot in 4408 * the current frame should be zero by now 4409 */ 4410 if (bt_reg_mask(bt) & ~BPF_REGMASK_ARGS) { 4411 verifier_bug(env, "static subprog unexpected regs %x", 4412 bt_reg_mask(bt)); 4413 return -EFAULT; 4414 } 4415 /* we are now tracking register spills correctly, 4416 * so any instance of leftover slots is a bug 4417 */ 4418 if (bt_stack_mask(bt) != 0) { 4419 verifier_bug(env, 4420 "static subprog leftover stack slots %llx", 4421 bt_stack_mask(bt)); 4422 return -EFAULT; 4423 } 4424 /* propagate r1-r5 to the caller */ 4425 for (i = BPF_REG_1; i <= BPF_REG_5; i++) { 4426 if (bt_is_reg_set(bt, i)) { 4427 bt_clear_reg(bt, i); 4428 bt_set_frame_reg(bt, bt->frame - 1, i); 4429 } 4430 } 4431 if (bt_subprog_exit(bt)) 4432 return -EFAULT; 4433 return 0; 4434 } 4435 } else if (is_sync_callback_calling_insn(insn) && idx != subseq_idx - 1) { 4436 /* exit from callback subprog to callback-calling helper or 4437 * kfunc call. Use idx/subseq_idx check to discern it from 4438 * straight line code backtracking. 4439 * Unlike the subprog call handling above, we shouldn't 4440 * propagate precision of r1-r5 (if any requested), as they are 4441 * not actually arguments passed directly to callback subprogs 4442 */ 4443 if (bt_reg_mask(bt) & ~BPF_REGMASK_ARGS) { 4444 verifier_bug(env, "callback unexpected regs %x", 4445 bt_reg_mask(bt)); 4446 return -EFAULT; 4447 } 4448 if (bt_stack_mask(bt) != 0) { 4449 verifier_bug(env, "callback leftover stack slots %llx", 4450 bt_stack_mask(bt)); 4451 return -EFAULT; 4452 } 4453 /* clear r1-r5 in callback subprog's mask */ 4454 for (i = BPF_REG_1; i <= BPF_REG_5; i++) 4455 bt_clear_reg(bt, i); 4456 if (bt_subprog_exit(bt)) 4457 return -EFAULT; 4458 return 0; 4459 } else if (opcode == BPF_CALL) { 4460 /* kfunc with imm==0 is invalid and fixup_kfunc_call will 4461 * catch this error later. Make backtracking conservative 4462 * with ENOTSUPP. 4463 */ 4464 if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL && insn->imm == 0) 4465 return -ENOTSUPP; 4466 /* regular helper call sets R0 */ 4467 bt_clear_reg(bt, BPF_REG_0); 4468 if (bt_reg_mask(bt) & BPF_REGMASK_ARGS) { 4469 /* if backtracking was looking for registers R1-R5 4470 * they should have been found already. 4471 */ 4472 verifier_bug(env, "backtracking call unexpected regs %x", 4473 bt_reg_mask(bt)); 4474 return -EFAULT; 4475 } 4476 } else if (opcode == BPF_EXIT) { 4477 bool r0_precise; 4478 4479 /* Backtracking to a nested function call, 'idx' is a part of 4480 * the inner frame 'subseq_idx' is a part of the outer frame. 4481 * In case of a regular function call, instructions giving 4482 * precision to registers R1-R5 should have been found already. 4483 * In case of a callback, it is ok to have R1-R5 marked for 4484 * backtracking, as these registers are set by the function 4485 * invoking callback. 4486 */ 4487 if (subseq_idx >= 0 && calls_callback(env, subseq_idx)) 4488 for (i = BPF_REG_1; i <= BPF_REG_5; i++) 4489 bt_clear_reg(bt, i); 4490 if (bt_reg_mask(bt) & BPF_REGMASK_ARGS) { 4491 verifier_bug(env, "backtracking exit unexpected regs %x", 4492 bt_reg_mask(bt)); 4493 return -EFAULT; 4494 } 4495 4496 /* BPF_EXIT in subprog or callback always returns 4497 * right after the call instruction, so by checking 4498 * whether the instruction at subseq_idx-1 is subprog 4499 * call or not we can distinguish actual exit from 4500 * *subprog* from exit from *callback*. In the former 4501 * case, we need to propagate r0 precision, if 4502 * necessary. In the former we never do that. 4503 */ 4504 r0_precise = subseq_idx - 1 >= 0 && 4505 bpf_pseudo_call(&env->prog->insnsi[subseq_idx - 1]) && 4506 bt_is_reg_set(bt, BPF_REG_0); 4507 4508 bt_clear_reg(bt, BPF_REG_0); 4509 if (bt_subprog_enter(bt)) 4510 return -EFAULT; 4511 4512 if (r0_precise) 4513 bt_set_reg(bt, BPF_REG_0); 4514 /* r6-r9 and stack slots will stay set in caller frame 4515 * bitmasks until we return back from callee(s) 4516 */ 4517 return 0; 4518 } else if (BPF_SRC(insn->code) == BPF_X) { 4519 if (!bt_is_reg_set(bt, dreg) && !bt_is_reg_set(bt, sreg)) 4520 return 0; 4521 /* dreg <cond> sreg 4522 * Both dreg and sreg need precision before 4523 * this insn. If only sreg was marked precise 4524 * before it would be equally necessary to 4525 * propagate it to dreg. 4526 */ 4527 if (!hist || !(hist->flags & INSN_F_SRC_REG_STACK)) 4528 bt_set_reg(bt, sreg); 4529 if (!hist || !(hist->flags & INSN_F_DST_REG_STACK)) 4530 bt_set_reg(bt, dreg); 4531 } else if (BPF_SRC(insn->code) == BPF_K) { 4532 /* dreg <cond> K 4533 * Only dreg still needs precision before 4534 * this insn, so for the K-based conditional 4535 * there is nothing new to be marked. 4536 */ 4537 } 4538 } else if (class == BPF_LD) { 4539 if (!bt_is_reg_set(bt, dreg)) 4540 return 0; 4541 bt_clear_reg(bt, dreg); 4542 /* It's ld_imm64 or ld_abs or ld_ind. 4543 * For ld_imm64 no further tracking of precision 4544 * into parent is necessary 4545 */ 4546 if (mode == BPF_IND || mode == BPF_ABS) 4547 /* to be analyzed */ 4548 return -ENOTSUPP; 4549 } 4550 /* Propagate precision marks to linked registers, to account for 4551 * registers marked as precise in this function. 4552 */ 4553 bt_sync_linked_regs(bt, hist); 4554 return 0; 4555 } 4556 4557 /* the scalar precision tracking algorithm: 4558 * . at the start all registers have precise=false. 4559 * . scalar ranges are tracked as normal through alu and jmp insns. 4560 * . once precise value of the scalar register is used in: 4561 * . ptr + scalar alu 4562 * . if (scalar cond K|scalar) 4563 * . helper_call(.., scalar, ...) where ARG_CONST is expected 4564 * backtrack through the verifier states and mark all registers and 4565 * stack slots with spilled constants that these scalar registers 4566 * should be precise. 4567 * . during state pruning two registers (or spilled stack slots) 4568 * are equivalent if both are not precise. 4569 * 4570 * Note the verifier cannot simply walk register parentage chain, 4571 * since many different registers and stack slots could have been 4572 * used to compute single precise scalar. 4573 * 4574 * The approach of starting with precise=true for all registers and then 4575 * backtrack to mark a register as not precise when the verifier detects 4576 * that program doesn't care about specific value (e.g., when helper 4577 * takes register as ARG_ANYTHING parameter) is not safe. 4578 * 4579 * It's ok to walk single parentage chain of the verifier states. 4580 * It's possible that this backtracking will go all the way till 1st insn. 4581 * All other branches will be explored for needing precision later. 4582 * 4583 * The backtracking needs to deal with cases like: 4584 * R8=map_value(id=0,off=0,ks=4,vs=1952,imm=0) R9_w=map_value(id=0,off=40,ks=4,vs=1952,imm=0) 4585 * r9 -= r8 4586 * r5 = r9 4587 * if r5 > 0x79f goto pc+7 4588 * R5_w=inv(id=0,umax_value=1951,var_off=(0x0; 0x7ff)) 4589 * r5 += 1 4590 * ... 4591 * call bpf_perf_event_output#25 4592 * where .arg5_type = ARG_CONST_SIZE_OR_ZERO 4593 * 4594 * and this case: 4595 * r6 = 1 4596 * call foo // uses callee's r6 inside to compute r0 4597 * r0 += r6 4598 * if r0 == 0 goto 4599 * 4600 * to track above reg_mask/stack_mask needs to be independent for each frame. 4601 * 4602 * Also if parent's curframe > frame where backtracking started, 4603 * the verifier need to mark registers in both frames, otherwise callees 4604 * may incorrectly prune callers. This is similar to 4605 * commit 7640ead93924 ("bpf: verifier: make sure callees don't prune with caller differences") 4606 * 4607 * For now backtracking falls back into conservative marking. 4608 */ 4609 static void mark_all_scalars_precise(struct bpf_verifier_env *env, 4610 struct bpf_verifier_state *st) 4611 { 4612 struct bpf_func_state *func; 4613 struct bpf_reg_state *reg; 4614 int i, j; 4615 4616 if (env->log.level & BPF_LOG_LEVEL2) { 4617 verbose(env, "mark_precise: frame%d: falling back to forcing all scalars precise\n", 4618 st->curframe); 4619 } 4620 4621 /* big hammer: mark all scalars precise in this path. 4622 * pop_stack may still get !precise scalars. 4623 * We also skip current state and go straight to first parent state, 4624 * because precision markings in current non-checkpointed state are 4625 * not needed. See why in the comment in __mark_chain_precision below. 4626 */ 4627 for (st = st->parent; st; st = st->parent) { 4628 for (i = 0; i <= st->curframe; i++) { 4629 func = st->frame[i]; 4630 for (j = 0; j < BPF_REG_FP; j++) { 4631 reg = &func->regs[j]; 4632 if (reg->type != SCALAR_VALUE || reg->precise) 4633 continue; 4634 reg->precise = true; 4635 if (env->log.level & BPF_LOG_LEVEL2) { 4636 verbose(env, "force_precise: frame%d: forcing r%d to be precise\n", 4637 i, j); 4638 } 4639 } 4640 for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) { 4641 if (!is_spilled_reg(&func->stack[j])) 4642 continue; 4643 reg = &func->stack[j].spilled_ptr; 4644 if (reg->type != SCALAR_VALUE || reg->precise) 4645 continue; 4646 reg->precise = true; 4647 if (env->log.level & BPF_LOG_LEVEL2) { 4648 verbose(env, "force_precise: frame%d: forcing fp%d to be precise\n", 4649 i, -(j + 1) * 8); 4650 } 4651 } 4652 } 4653 } 4654 } 4655 4656 static void mark_all_scalars_imprecise(struct bpf_verifier_env *env, struct bpf_verifier_state *st) 4657 { 4658 struct bpf_func_state *func; 4659 struct bpf_reg_state *reg; 4660 int i, j; 4661 4662 for (i = 0; i <= st->curframe; i++) { 4663 func = st->frame[i]; 4664 for (j = 0; j < BPF_REG_FP; j++) { 4665 reg = &func->regs[j]; 4666 if (reg->type != SCALAR_VALUE) 4667 continue; 4668 reg->precise = false; 4669 } 4670 for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) { 4671 if (!is_spilled_reg(&func->stack[j])) 4672 continue; 4673 reg = &func->stack[j].spilled_ptr; 4674 if (reg->type != SCALAR_VALUE) 4675 continue; 4676 reg->precise = false; 4677 } 4678 } 4679 } 4680 4681 /* 4682 * __mark_chain_precision() backtracks BPF program instruction sequence and 4683 * chain of verifier states making sure that register *regno* (if regno >= 0) 4684 * and/or stack slot *spi* (if spi >= 0) are marked as precisely tracked 4685 * SCALARS, as well as any other registers and slots that contribute to 4686 * a tracked state of given registers/stack slots, depending on specific BPF 4687 * assembly instructions (see backtrack_insns() for exact instruction handling 4688 * logic). This backtracking relies on recorded jmp_history and is able to 4689 * traverse entire chain of parent states. This process ends only when all the 4690 * necessary registers/slots and their transitive dependencies are marked as 4691 * precise. 4692 * 4693 * One important and subtle aspect is that precise marks *do not matter* in 4694 * the currently verified state (current state). It is important to understand 4695 * why this is the case. 4696 * 4697 * First, note that current state is the state that is not yet "checkpointed", 4698 * i.e., it is not yet put into env->explored_states, and it has no children 4699 * states as well. It's ephemeral, and can end up either a) being discarded if 4700 * compatible explored state is found at some point or BPF_EXIT instruction is 4701 * reached or b) checkpointed and put into env->explored_states, branching out 4702 * into one or more children states. 4703 * 4704 * In the former case, precise markings in current state are completely 4705 * ignored by state comparison code (see regsafe() for details). Only 4706 * checkpointed ("old") state precise markings are important, and if old 4707 * state's register/slot is precise, regsafe() assumes current state's 4708 * register/slot as precise and checks value ranges exactly and precisely. If 4709 * states turn out to be compatible, current state's necessary precise 4710 * markings and any required parent states' precise markings are enforced 4711 * after the fact with propagate_precision() logic, after the fact. But it's 4712 * important to realize that in this case, even after marking current state 4713 * registers/slots as precise, we immediately discard current state. So what 4714 * actually matters is any of the precise markings propagated into current 4715 * state's parent states, which are always checkpointed (due to b) case above). 4716 * As such, for scenario a) it doesn't matter if current state has precise 4717 * markings set or not. 4718 * 4719 * Now, for the scenario b), checkpointing and forking into child(ren) 4720 * state(s). Note that before current state gets to checkpointing step, any 4721 * processed instruction always assumes precise SCALAR register/slot 4722 * knowledge: if precise value or range is useful to prune jump branch, BPF 4723 * verifier takes this opportunity enthusiastically. Similarly, when 4724 * register's value is used to calculate offset or memory address, exact 4725 * knowledge of SCALAR range is assumed, checked, and enforced. So, similar to 4726 * what we mentioned above about state comparison ignoring precise markings 4727 * during state comparison, BPF verifier ignores and also assumes precise 4728 * markings *at will* during instruction verification process. But as verifier 4729 * assumes precision, it also propagates any precision dependencies across 4730 * parent states, which are not yet finalized, so can be further restricted 4731 * based on new knowledge gained from restrictions enforced by their children 4732 * states. This is so that once those parent states are finalized, i.e., when 4733 * they have no more active children state, state comparison logic in 4734 * is_state_visited() would enforce strict and precise SCALAR ranges, if 4735 * required for correctness. 4736 * 4737 * To build a bit more intuition, note also that once a state is checkpointed, 4738 * the path we took to get to that state is not important. This is crucial 4739 * property for state pruning. When state is checkpointed and finalized at 4740 * some instruction index, it can be correctly and safely used to "short 4741 * circuit" any *compatible* state that reaches exactly the same instruction 4742 * index. I.e., if we jumped to that instruction from a completely different 4743 * code path than original finalized state was derived from, it doesn't 4744 * matter, current state can be discarded because from that instruction 4745 * forward having a compatible state will ensure we will safely reach the 4746 * exit. States describe preconditions for further exploration, but completely 4747 * forget the history of how we got here. 4748 * 4749 * This also means that even if we needed precise SCALAR range to get to 4750 * finalized state, but from that point forward *that same* SCALAR register is 4751 * never used in a precise context (i.e., it's precise value is not needed for 4752 * correctness), it's correct and safe to mark such register as "imprecise" 4753 * (i.e., precise marking set to false). This is what we rely on when we do 4754 * not set precise marking in current state. If no child state requires 4755 * precision for any given SCALAR register, it's safe to dictate that it can 4756 * be imprecise. If any child state does require this register to be precise, 4757 * we'll mark it precise later retroactively during precise markings 4758 * propagation from child state to parent states. 4759 * 4760 * Skipping precise marking setting in current state is a mild version of 4761 * relying on the above observation. But we can utilize this property even 4762 * more aggressively by proactively forgetting any precise marking in the 4763 * current state (which we inherited from the parent state), right before we 4764 * checkpoint it and branch off into new child state. This is done by 4765 * mark_all_scalars_imprecise() to hopefully get more permissive and generic 4766 * finalized states which help in short circuiting more future states. 4767 */ 4768 static int __mark_chain_precision(struct bpf_verifier_env *env, 4769 struct bpf_verifier_state *starting_state, 4770 int regno, 4771 bool *changed) 4772 { 4773 struct bpf_verifier_state *st = starting_state; 4774 struct backtrack_state *bt = &env->bt; 4775 int first_idx = st->first_insn_idx; 4776 int last_idx = starting_state->insn_idx; 4777 int subseq_idx = -1; 4778 struct bpf_func_state *func; 4779 bool tmp, skip_first = true; 4780 struct bpf_reg_state *reg; 4781 int i, fr, err; 4782 4783 if (!env->bpf_capable) 4784 return 0; 4785 4786 changed = changed ?: &tmp; 4787 /* set frame number from which we are starting to backtrack */ 4788 bt_init(bt, starting_state->curframe); 4789 4790 /* Do sanity checks against current state of register and/or stack 4791 * slot, but don't set precise flag in current state, as precision 4792 * tracking in the current state is unnecessary. 4793 */ 4794 func = st->frame[bt->frame]; 4795 if (regno >= 0) { 4796 reg = &func->regs[regno]; 4797 if (reg->type != SCALAR_VALUE) { 4798 verifier_bug(env, "backtracking misuse"); 4799 return -EFAULT; 4800 } 4801 bt_set_reg(bt, regno); 4802 } 4803 4804 if (bt_empty(bt)) 4805 return 0; 4806 4807 for (;;) { 4808 DECLARE_BITMAP(mask, 64); 4809 u32 history = st->jmp_history_cnt; 4810 struct bpf_jmp_history_entry *hist; 4811 4812 if (env->log.level & BPF_LOG_LEVEL2) { 4813 verbose(env, "mark_precise: frame%d: last_idx %d first_idx %d subseq_idx %d \n", 4814 bt->frame, last_idx, first_idx, subseq_idx); 4815 } 4816 4817 if (last_idx < 0) { 4818 /* we are at the entry into subprog, which 4819 * is expected for global funcs, but only if 4820 * requested precise registers are R1-R5 4821 * (which are global func's input arguments) 4822 */ 4823 if (st->curframe == 0 && 4824 st->frame[0]->subprogno > 0 && 4825 st->frame[0]->callsite == BPF_MAIN_FUNC && 4826 bt_stack_mask(bt) == 0 && 4827 (bt_reg_mask(bt) & ~BPF_REGMASK_ARGS) == 0) { 4828 bitmap_from_u64(mask, bt_reg_mask(bt)); 4829 for_each_set_bit(i, mask, 32) { 4830 reg = &st->frame[0]->regs[i]; 4831 bt_clear_reg(bt, i); 4832 if (reg->type == SCALAR_VALUE) { 4833 reg->precise = true; 4834 *changed = true; 4835 } 4836 } 4837 return 0; 4838 } 4839 4840 verifier_bug(env, "backtracking func entry subprog %d reg_mask %x stack_mask %llx", 4841 st->frame[0]->subprogno, bt_reg_mask(bt), bt_stack_mask(bt)); 4842 return -EFAULT; 4843 } 4844 4845 for (i = last_idx;;) { 4846 if (skip_first) { 4847 err = 0; 4848 skip_first = false; 4849 } else { 4850 hist = get_jmp_hist_entry(st, history, i); 4851 err = backtrack_insn(env, i, subseq_idx, hist, bt); 4852 } 4853 if (err == -ENOTSUPP) { 4854 mark_all_scalars_precise(env, starting_state); 4855 bt_reset(bt); 4856 return 0; 4857 } else if (err) { 4858 return err; 4859 } 4860 if (bt_empty(bt)) 4861 /* Found assignment(s) into tracked register in this state. 4862 * Since this state is already marked, just return. 4863 * Nothing to be tracked further in the parent state. 4864 */ 4865 return 0; 4866 subseq_idx = i; 4867 i = get_prev_insn_idx(st, i, &history); 4868 if (i == -ENOENT) 4869 break; 4870 if (i >= env->prog->len) { 4871 /* This can happen if backtracking reached insn 0 4872 * and there are still reg_mask or stack_mask 4873 * to backtrack. 4874 * It means the backtracking missed the spot where 4875 * particular register was initialized with a constant. 4876 */ 4877 verifier_bug(env, "backtracking idx %d", i); 4878 return -EFAULT; 4879 } 4880 } 4881 st = st->parent; 4882 if (!st) 4883 break; 4884 4885 for (fr = bt->frame; fr >= 0; fr--) { 4886 func = st->frame[fr]; 4887 bitmap_from_u64(mask, bt_frame_reg_mask(bt, fr)); 4888 for_each_set_bit(i, mask, 32) { 4889 reg = &func->regs[i]; 4890 if (reg->type != SCALAR_VALUE) { 4891 bt_clear_frame_reg(bt, fr, i); 4892 continue; 4893 } 4894 if (reg->precise) { 4895 bt_clear_frame_reg(bt, fr, i); 4896 } else { 4897 reg->precise = true; 4898 *changed = true; 4899 } 4900 } 4901 4902 bitmap_from_u64(mask, bt_frame_stack_mask(bt, fr)); 4903 for_each_set_bit(i, mask, 64) { 4904 if (verifier_bug_if(i >= func->allocated_stack / BPF_REG_SIZE, 4905 env, "stack slot %d, total slots %d", 4906 i, func->allocated_stack / BPF_REG_SIZE)) 4907 return -EFAULT; 4908 4909 if (!is_spilled_scalar_reg(&func->stack[i])) { 4910 bt_clear_frame_slot(bt, fr, i); 4911 continue; 4912 } 4913 reg = &func->stack[i].spilled_ptr; 4914 if (reg->precise) { 4915 bt_clear_frame_slot(bt, fr, i); 4916 } else { 4917 reg->precise = true; 4918 *changed = true; 4919 } 4920 } 4921 if (env->log.level & BPF_LOG_LEVEL2) { 4922 fmt_reg_mask(env->tmp_str_buf, TMP_STR_BUF_LEN, 4923 bt_frame_reg_mask(bt, fr)); 4924 verbose(env, "mark_precise: frame%d: parent state regs=%s ", 4925 fr, env->tmp_str_buf); 4926 fmt_stack_mask(env->tmp_str_buf, TMP_STR_BUF_LEN, 4927 bt_frame_stack_mask(bt, fr)); 4928 verbose(env, "stack=%s: ", env->tmp_str_buf); 4929 print_verifier_state(env, st, fr, true); 4930 } 4931 } 4932 4933 if (bt_empty(bt)) 4934 return 0; 4935 4936 subseq_idx = first_idx; 4937 last_idx = st->last_insn_idx; 4938 first_idx = st->first_insn_idx; 4939 } 4940 4941 /* if we still have requested precise regs or slots, we missed 4942 * something (e.g., stack access through non-r10 register), so 4943 * fallback to marking all precise 4944 */ 4945 if (!bt_empty(bt)) { 4946 mark_all_scalars_precise(env, starting_state); 4947 bt_reset(bt); 4948 } 4949 4950 return 0; 4951 } 4952 4953 int mark_chain_precision(struct bpf_verifier_env *env, int regno) 4954 { 4955 return __mark_chain_precision(env, env->cur_state, regno, NULL); 4956 } 4957 4958 /* mark_chain_precision_batch() assumes that env->bt is set in the caller to 4959 * desired reg and stack masks across all relevant frames 4960 */ 4961 static int mark_chain_precision_batch(struct bpf_verifier_env *env, 4962 struct bpf_verifier_state *starting_state) 4963 { 4964 return __mark_chain_precision(env, starting_state, -1, NULL); 4965 } 4966 4967 static bool is_spillable_regtype(enum bpf_reg_type type) 4968 { 4969 switch (base_type(type)) { 4970 case PTR_TO_MAP_VALUE: 4971 case PTR_TO_STACK: 4972 case PTR_TO_CTX: 4973 case PTR_TO_PACKET: 4974 case PTR_TO_PACKET_META: 4975 case PTR_TO_PACKET_END: 4976 case PTR_TO_FLOW_KEYS: 4977 case CONST_PTR_TO_MAP: 4978 case PTR_TO_SOCKET: 4979 case PTR_TO_SOCK_COMMON: 4980 case PTR_TO_TCP_SOCK: 4981 case PTR_TO_XDP_SOCK: 4982 case PTR_TO_BTF_ID: 4983 case PTR_TO_BUF: 4984 case PTR_TO_MEM: 4985 case PTR_TO_FUNC: 4986 case PTR_TO_MAP_KEY: 4987 case PTR_TO_ARENA: 4988 return true; 4989 default: 4990 return false; 4991 } 4992 } 4993 4994 /* Does this register contain a constant zero? */ 4995 static bool register_is_null(struct bpf_reg_state *reg) 4996 { 4997 return reg->type == SCALAR_VALUE && tnum_equals_const(reg->var_off, 0); 4998 } 4999 5000 /* check if register is a constant scalar value */ 5001 static bool is_reg_const(struct bpf_reg_state *reg, bool subreg32) 5002 { 5003 return reg->type == SCALAR_VALUE && 5004 tnum_is_const(subreg32 ? tnum_subreg(reg->var_off) : reg->var_off); 5005 } 5006 5007 /* assuming is_reg_const() is true, return constant value of a register */ 5008 static u64 reg_const_value(struct bpf_reg_state *reg, bool subreg32) 5009 { 5010 return subreg32 ? tnum_subreg(reg->var_off).value : reg->var_off.value; 5011 } 5012 5013 static bool __is_pointer_value(bool allow_ptr_leaks, 5014 const struct bpf_reg_state *reg) 5015 { 5016 if (allow_ptr_leaks) 5017 return false; 5018 5019 return reg->type != SCALAR_VALUE; 5020 } 5021 5022 static void assign_scalar_id_before_mov(struct bpf_verifier_env *env, 5023 struct bpf_reg_state *src_reg) 5024 { 5025 if (src_reg->type != SCALAR_VALUE) 5026 return; 5027 5028 if (src_reg->id & BPF_ADD_CONST) { 5029 /* 5030 * The verifier is processing rX = rY insn and 5031 * rY->id has special linked register already. 5032 * Cleared it, since multiple rX += const are not supported. 5033 */ 5034 src_reg->id = 0; 5035 src_reg->off = 0; 5036 } 5037 5038 if (!src_reg->id && !tnum_is_const(src_reg->var_off)) 5039 /* Ensure that src_reg has a valid ID that will be copied to 5040 * dst_reg and then will be used by sync_linked_regs() to 5041 * propagate min/max range. 5042 */ 5043 src_reg->id = ++env->id_gen; 5044 } 5045 5046 /* Copy src state preserving dst->parent and dst->live fields */ 5047 static void copy_register_state(struct bpf_reg_state *dst, const struct bpf_reg_state *src) 5048 { 5049 struct bpf_reg_state *parent = dst->parent; 5050 enum bpf_reg_liveness live = dst->live; 5051 5052 *dst = *src; 5053 dst->parent = parent; 5054 dst->live = live; 5055 } 5056 5057 static void save_register_state(struct bpf_verifier_env *env, 5058 struct bpf_func_state *state, 5059 int spi, struct bpf_reg_state *reg, 5060 int size) 5061 { 5062 int i; 5063 5064 copy_register_state(&state->stack[spi].spilled_ptr, reg); 5065 if (size == BPF_REG_SIZE) 5066 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN; 5067 5068 for (i = BPF_REG_SIZE; i > BPF_REG_SIZE - size; i--) 5069 state->stack[spi].slot_type[i - 1] = STACK_SPILL; 5070 5071 /* size < 8 bytes spill */ 5072 for (; i; i--) 5073 mark_stack_slot_misc(env, &state->stack[spi].slot_type[i - 1]); 5074 } 5075 5076 static bool is_bpf_st_mem(struct bpf_insn *insn) 5077 { 5078 return BPF_CLASS(insn->code) == BPF_ST && BPF_MODE(insn->code) == BPF_MEM; 5079 } 5080 5081 static int get_reg_width(struct bpf_reg_state *reg) 5082 { 5083 return fls64(reg->umax_value); 5084 } 5085 5086 /* See comment for mark_fastcall_pattern_for_call() */ 5087 static void check_fastcall_stack_contract(struct bpf_verifier_env *env, 5088 struct bpf_func_state *state, int insn_idx, int off) 5089 { 5090 struct bpf_subprog_info *subprog = &env->subprog_info[state->subprogno]; 5091 struct bpf_insn_aux_data *aux = env->insn_aux_data; 5092 int i; 5093 5094 if (subprog->fastcall_stack_off <= off || aux[insn_idx].fastcall_pattern) 5095 return; 5096 /* access to the region [max_stack_depth .. fastcall_stack_off) 5097 * from something that is not a part of the fastcall pattern, 5098 * disable fastcall rewrites for current subprogram by setting 5099 * fastcall_stack_off to a value smaller than any possible offset. 5100 */ 5101 subprog->fastcall_stack_off = S16_MIN; 5102 /* reset fastcall aux flags within subprogram, 5103 * happens at most once per subprogram 5104 */ 5105 for (i = subprog->start; i < (subprog + 1)->start; ++i) { 5106 aux[i].fastcall_spills_num = 0; 5107 aux[i].fastcall_pattern = 0; 5108 } 5109 } 5110 5111 /* check_stack_{read,write}_fixed_off functions track spill/fill of registers, 5112 * stack boundary and alignment are checked in check_mem_access() 5113 */ 5114 static int check_stack_write_fixed_off(struct bpf_verifier_env *env, 5115 /* stack frame we're writing to */ 5116 struct bpf_func_state *state, 5117 int off, int size, int value_regno, 5118 int insn_idx) 5119 { 5120 struct bpf_func_state *cur; /* state of the current function */ 5121 int i, slot = -off - 1, spi = slot / BPF_REG_SIZE, err; 5122 struct bpf_insn *insn = &env->prog->insnsi[insn_idx]; 5123 struct bpf_reg_state *reg = NULL; 5124 int insn_flags = insn_stack_access_flags(state->frameno, spi); 5125 5126 /* caller checked that off % size == 0 and -MAX_BPF_STACK <= off < 0, 5127 * so it's aligned access and [off, off + size) are within stack limits 5128 */ 5129 if (!env->allow_ptr_leaks && 5130 is_spilled_reg(&state->stack[spi]) && 5131 !is_spilled_scalar_reg(&state->stack[spi]) && 5132 size != BPF_REG_SIZE) { 5133 verbose(env, "attempt to corrupt spilled pointer on stack\n"); 5134 return -EACCES; 5135 } 5136 5137 cur = env->cur_state->frame[env->cur_state->curframe]; 5138 if (value_regno >= 0) 5139 reg = &cur->regs[value_regno]; 5140 if (!env->bypass_spec_v4) { 5141 bool sanitize = reg && is_spillable_regtype(reg->type); 5142 5143 for (i = 0; i < size; i++) { 5144 u8 type = state->stack[spi].slot_type[i]; 5145 5146 if (type != STACK_MISC && type != STACK_ZERO) { 5147 sanitize = true; 5148 break; 5149 } 5150 } 5151 5152 if (sanitize) 5153 env->insn_aux_data[insn_idx].nospec_result = true; 5154 } 5155 5156 err = destroy_if_dynptr_stack_slot(env, state, spi); 5157 if (err) 5158 return err; 5159 5160 check_fastcall_stack_contract(env, state, insn_idx, off); 5161 mark_stack_slot_scratched(env, spi); 5162 if (reg && !(off % BPF_REG_SIZE) && reg->type == SCALAR_VALUE && env->bpf_capable) { 5163 bool reg_value_fits; 5164 5165 reg_value_fits = get_reg_width(reg) <= BITS_PER_BYTE * size; 5166 /* Make sure that reg had an ID to build a relation on spill. */ 5167 if (reg_value_fits) 5168 assign_scalar_id_before_mov(env, reg); 5169 save_register_state(env, state, spi, reg, size); 5170 /* Break the relation on a narrowing spill. */ 5171 if (!reg_value_fits) 5172 state->stack[spi].spilled_ptr.id = 0; 5173 } else if (!reg && !(off % BPF_REG_SIZE) && is_bpf_st_mem(insn) && 5174 env->bpf_capable) { 5175 struct bpf_reg_state *tmp_reg = &env->fake_reg[0]; 5176 5177 memset(tmp_reg, 0, sizeof(*tmp_reg)); 5178 __mark_reg_known(tmp_reg, insn->imm); 5179 tmp_reg->type = SCALAR_VALUE; 5180 save_register_state(env, state, spi, tmp_reg, size); 5181 } else if (reg && is_spillable_regtype(reg->type)) { 5182 /* register containing pointer is being spilled into stack */ 5183 if (size != BPF_REG_SIZE) { 5184 verbose_linfo(env, insn_idx, "; "); 5185 verbose(env, "invalid size of register spill\n"); 5186 return -EACCES; 5187 } 5188 if (state != cur && reg->type == PTR_TO_STACK) { 5189 verbose(env, "cannot spill pointers to stack into stack frame of the caller\n"); 5190 return -EINVAL; 5191 } 5192 save_register_state(env, state, spi, reg, size); 5193 } else { 5194 u8 type = STACK_MISC; 5195 5196 /* regular write of data into stack destroys any spilled ptr */ 5197 state->stack[spi].spilled_ptr.type = NOT_INIT; 5198 /* Mark slots as STACK_MISC if they belonged to spilled ptr/dynptr/iter. */ 5199 if (is_stack_slot_special(&state->stack[spi])) 5200 for (i = 0; i < BPF_REG_SIZE; i++) 5201 scrub_spilled_slot(&state->stack[spi].slot_type[i]); 5202 5203 /* only mark the slot as written if all 8 bytes were written 5204 * otherwise read propagation may incorrectly stop too soon 5205 * when stack slots are partially written. 5206 * This heuristic means that read propagation will be 5207 * conservative, since it will add reg_live_read marks 5208 * to stack slots all the way to first state when programs 5209 * writes+reads less than 8 bytes 5210 */ 5211 if (size == BPF_REG_SIZE) 5212 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN; 5213 5214 /* when we zero initialize stack slots mark them as such */ 5215 if ((reg && register_is_null(reg)) || 5216 (!reg && is_bpf_st_mem(insn) && insn->imm == 0)) { 5217 /* STACK_ZERO case happened because register spill 5218 * wasn't properly aligned at the stack slot boundary, 5219 * so it's not a register spill anymore; force 5220 * originating register to be precise to make 5221 * STACK_ZERO correct for subsequent states 5222 */ 5223 err = mark_chain_precision(env, value_regno); 5224 if (err) 5225 return err; 5226 type = STACK_ZERO; 5227 } 5228 5229 /* Mark slots affected by this stack write. */ 5230 for (i = 0; i < size; i++) 5231 state->stack[spi].slot_type[(slot - i) % BPF_REG_SIZE] = type; 5232 insn_flags = 0; /* not a register spill */ 5233 } 5234 5235 if (insn_flags) 5236 return push_jmp_history(env, env->cur_state, insn_flags, 0); 5237 return 0; 5238 } 5239 5240 /* Write the stack: 'stack[ptr_regno + off] = value_regno'. 'ptr_regno' is 5241 * known to contain a variable offset. 5242 * This function checks whether the write is permitted and conservatively 5243 * tracks the effects of the write, considering that each stack slot in the 5244 * dynamic range is potentially written to. 5245 * 5246 * 'off' includes 'regno->off'. 5247 * 'value_regno' can be -1, meaning that an unknown value is being written to 5248 * the stack. 5249 * 5250 * Spilled pointers in range are not marked as written because we don't know 5251 * what's going to be actually written. This means that read propagation for 5252 * future reads cannot be terminated by this write. 5253 * 5254 * For privileged programs, uninitialized stack slots are considered 5255 * initialized by this write (even though we don't know exactly what offsets 5256 * are going to be written to). The idea is that we don't want the verifier to 5257 * reject future reads that access slots written to through variable offsets. 5258 */ 5259 static int check_stack_write_var_off(struct bpf_verifier_env *env, 5260 /* func where register points to */ 5261 struct bpf_func_state *state, 5262 int ptr_regno, int off, int size, 5263 int value_regno, int insn_idx) 5264 { 5265 struct bpf_func_state *cur; /* state of the current function */ 5266 int min_off, max_off; 5267 int i, err; 5268 struct bpf_reg_state *ptr_reg = NULL, *value_reg = NULL; 5269 struct bpf_insn *insn = &env->prog->insnsi[insn_idx]; 5270 bool writing_zero = false; 5271 /* set if the fact that we're writing a zero is used to let any 5272 * stack slots remain STACK_ZERO 5273 */ 5274 bool zero_used = false; 5275 5276 cur = env->cur_state->frame[env->cur_state->curframe]; 5277 ptr_reg = &cur->regs[ptr_regno]; 5278 min_off = ptr_reg->smin_value + off; 5279 max_off = ptr_reg->smax_value + off + size; 5280 if (value_regno >= 0) 5281 value_reg = &cur->regs[value_regno]; 5282 if ((value_reg && register_is_null(value_reg)) || 5283 (!value_reg && is_bpf_st_mem(insn) && insn->imm == 0)) 5284 writing_zero = true; 5285 5286 for (i = min_off; i < max_off; i++) { 5287 int spi; 5288 5289 spi = __get_spi(i); 5290 err = destroy_if_dynptr_stack_slot(env, state, spi); 5291 if (err) 5292 return err; 5293 } 5294 5295 check_fastcall_stack_contract(env, state, insn_idx, min_off); 5296 /* Variable offset writes destroy any spilled pointers in range. */ 5297 for (i = min_off; i < max_off; i++) { 5298 u8 new_type, *stype; 5299 int slot, spi; 5300 5301 slot = -i - 1; 5302 spi = slot / BPF_REG_SIZE; 5303 stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE]; 5304 mark_stack_slot_scratched(env, spi); 5305 5306 if (!env->allow_ptr_leaks && *stype != STACK_MISC && *stype != STACK_ZERO) { 5307 /* Reject the write if range we may write to has not 5308 * been initialized beforehand. If we didn't reject 5309 * here, the ptr status would be erased below (even 5310 * though not all slots are actually overwritten), 5311 * possibly opening the door to leaks. 5312 * 5313 * We do however catch STACK_INVALID case below, and 5314 * only allow reading possibly uninitialized memory 5315 * later for CAP_PERFMON, as the write may not happen to 5316 * that slot. 5317 */ 5318 verbose(env, "spilled ptr in range of var-offset stack write; insn %d, ptr off: %d", 5319 insn_idx, i); 5320 return -EINVAL; 5321 } 5322 5323 /* If writing_zero and the spi slot contains a spill of value 0, 5324 * maintain the spill type. 5325 */ 5326 if (writing_zero && *stype == STACK_SPILL && 5327 is_spilled_scalar_reg(&state->stack[spi])) { 5328 struct bpf_reg_state *spill_reg = &state->stack[spi].spilled_ptr; 5329 5330 if (tnum_is_const(spill_reg->var_off) && spill_reg->var_off.value == 0) { 5331 zero_used = true; 5332 continue; 5333 } 5334 } 5335 5336 /* Erase all other spilled pointers. */ 5337 state->stack[spi].spilled_ptr.type = NOT_INIT; 5338 5339 /* Update the slot type. */ 5340 new_type = STACK_MISC; 5341 if (writing_zero && *stype == STACK_ZERO) { 5342 new_type = STACK_ZERO; 5343 zero_used = true; 5344 } 5345 /* If the slot is STACK_INVALID, we check whether it's OK to 5346 * pretend that it will be initialized by this write. The slot 5347 * might not actually be written to, and so if we mark it as 5348 * initialized future reads might leak uninitialized memory. 5349 * For privileged programs, we will accept such reads to slots 5350 * that may or may not be written because, if we're reject 5351 * them, the error would be too confusing. 5352 */ 5353 if (*stype == STACK_INVALID && !env->allow_uninit_stack) { 5354 verbose(env, "uninit stack in range of var-offset write prohibited for !root; insn %d, off: %d", 5355 insn_idx, i); 5356 return -EINVAL; 5357 } 5358 *stype = new_type; 5359 } 5360 if (zero_used) { 5361 /* backtracking doesn't work for STACK_ZERO yet. */ 5362 err = mark_chain_precision(env, value_regno); 5363 if (err) 5364 return err; 5365 } 5366 return 0; 5367 } 5368 5369 /* When register 'dst_regno' is assigned some values from stack[min_off, 5370 * max_off), we set the register's type according to the types of the 5371 * respective stack slots. If all the stack values are known to be zeros, then 5372 * so is the destination reg. Otherwise, the register is considered to be 5373 * SCALAR. This function does not deal with register filling; the caller must 5374 * ensure that all spilled registers in the stack range have been marked as 5375 * read. 5376 */ 5377 static void mark_reg_stack_read(struct bpf_verifier_env *env, 5378 /* func where src register points to */ 5379 struct bpf_func_state *ptr_state, 5380 int min_off, int max_off, int dst_regno) 5381 { 5382 struct bpf_verifier_state *vstate = env->cur_state; 5383 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 5384 int i, slot, spi; 5385 u8 *stype; 5386 int zeros = 0; 5387 5388 for (i = min_off; i < max_off; i++) { 5389 slot = -i - 1; 5390 spi = slot / BPF_REG_SIZE; 5391 mark_stack_slot_scratched(env, spi); 5392 stype = ptr_state->stack[spi].slot_type; 5393 if (stype[slot % BPF_REG_SIZE] != STACK_ZERO) 5394 break; 5395 zeros++; 5396 } 5397 if (zeros == max_off - min_off) { 5398 /* Any access_size read into register is zero extended, 5399 * so the whole register == const_zero. 5400 */ 5401 __mark_reg_const_zero(env, &state->regs[dst_regno]); 5402 } else { 5403 /* have read misc data from the stack */ 5404 mark_reg_unknown(env, state->regs, dst_regno); 5405 } 5406 state->regs[dst_regno].live |= REG_LIVE_WRITTEN; 5407 } 5408 5409 /* Read the stack at 'off' and put the results into the register indicated by 5410 * 'dst_regno'. It handles reg filling if the addressed stack slot is a 5411 * spilled reg. 5412 * 5413 * 'dst_regno' can be -1, meaning that the read value is not going to a 5414 * register. 5415 * 5416 * The access is assumed to be within the current stack bounds. 5417 */ 5418 static int check_stack_read_fixed_off(struct bpf_verifier_env *env, 5419 /* func where src register points to */ 5420 struct bpf_func_state *reg_state, 5421 int off, int size, int dst_regno) 5422 { 5423 struct bpf_verifier_state *vstate = env->cur_state; 5424 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 5425 int i, slot = -off - 1, spi = slot / BPF_REG_SIZE; 5426 struct bpf_reg_state *reg; 5427 u8 *stype, type; 5428 int insn_flags = insn_stack_access_flags(reg_state->frameno, spi); 5429 5430 stype = reg_state->stack[spi].slot_type; 5431 reg = ®_state->stack[spi].spilled_ptr; 5432 5433 mark_stack_slot_scratched(env, spi); 5434 check_fastcall_stack_contract(env, state, env->insn_idx, off); 5435 5436 if (is_spilled_reg(®_state->stack[spi])) { 5437 u8 spill_size = 1; 5438 5439 for (i = BPF_REG_SIZE - 1; i > 0 && stype[i - 1] == STACK_SPILL; i--) 5440 spill_size++; 5441 5442 if (size != BPF_REG_SIZE || spill_size != BPF_REG_SIZE) { 5443 if (reg->type != SCALAR_VALUE) { 5444 verbose_linfo(env, env->insn_idx, "; "); 5445 verbose(env, "invalid size of register fill\n"); 5446 return -EACCES; 5447 } 5448 5449 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64); 5450 if (dst_regno < 0) 5451 return 0; 5452 5453 if (size <= spill_size && 5454 bpf_stack_narrow_access_ok(off, size, spill_size)) { 5455 /* The earlier check_reg_arg() has decided the 5456 * subreg_def for this insn. Save it first. 5457 */ 5458 s32 subreg_def = state->regs[dst_regno].subreg_def; 5459 5460 copy_register_state(&state->regs[dst_regno], reg); 5461 state->regs[dst_regno].subreg_def = subreg_def; 5462 5463 /* Break the relation on a narrowing fill. 5464 * coerce_reg_to_size will adjust the boundaries. 5465 */ 5466 if (get_reg_width(reg) > size * BITS_PER_BYTE) 5467 state->regs[dst_regno].id = 0; 5468 } else { 5469 int spill_cnt = 0, zero_cnt = 0; 5470 5471 for (i = 0; i < size; i++) { 5472 type = stype[(slot - i) % BPF_REG_SIZE]; 5473 if (type == STACK_SPILL) { 5474 spill_cnt++; 5475 continue; 5476 } 5477 if (type == STACK_MISC) 5478 continue; 5479 if (type == STACK_ZERO) { 5480 zero_cnt++; 5481 continue; 5482 } 5483 if (type == STACK_INVALID && env->allow_uninit_stack) 5484 continue; 5485 verbose(env, "invalid read from stack off %d+%d size %d\n", 5486 off, i, size); 5487 return -EACCES; 5488 } 5489 5490 if (spill_cnt == size && 5491 tnum_is_const(reg->var_off) && reg->var_off.value == 0) { 5492 __mark_reg_const_zero(env, &state->regs[dst_regno]); 5493 /* this IS register fill, so keep insn_flags */ 5494 } else if (zero_cnt == size) { 5495 /* similarly to mark_reg_stack_read(), preserve zeroes */ 5496 __mark_reg_const_zero(env, &state->regs[dst_regno]); 5497 insn_flags = 0; /* not restoring original register state */ 5498 } else { 5499 mark_reg_unknown(env, state->regs, dst_regno); 5500 insn_flags = 0; /* not restoring original register state */ 5501 } 5502 } 5503 state->regs[dst_regno].live |= REG_LIVE_WRITTEN; 5504 } else if (dst_regno >= 0) { 5505 /* restore register state from stack */ 5506 copy_register_state(&state->regs[dst_regno], reg); 5507 /* mark reg as written since spilled pointer state likely 5508 * has its liveness marks cleared by is_state_visited() 5509 * which resets stack/reg liveness for state transitions 5510 */ 5511 state->regs[dst_regno].live |= REG_LIVE_WRITTEN; 5512 } else if (__is_pointer_value(env->allow_ptr_leaks, reg)) { 5513 /* If dst_regno==-1, the caller is asking us whether 5514 * it is acceptable to use this value as a SCALAR_VALUE 5515 * (e.g. for XADD). 5516 * We must not allow unprivileged callers to do that 5517 * with spilled pointers. 5518 */ 5519 verbose(env, "leaking pointer from stack off %d\n", 5520 off); 5521 return -EACCES; 5522 } 5523 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64); 5524 } else { 5525 for (i = 0; i < size; i++) { 5526 type = stype[(slot - i) % BPF_REG_SIZE]; 5527 if (type == STACK_MISC) 5528 continue; 5529 if (type == STACK_ZERO) 5530 continue; 5531 if (type == STACK_INVALID && env->allow_uninit_stack) 5532 continue; 5533 verbose(env, "invalid read from stack off %d+%d size %d\n", 5534 off, i, size); 5535 return -EACCES; 5536 } 5537 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64); 5538 if (dst_regno >= 0) 5539 mark_reg_stack_read(env, reg_state, off, off + size, dst_regno); 5540 insn_flags = 0; /* we are not restoring spilled register */ 5541 } 5542 if (insn_flags) 5543 return push_jmp_history(env, env->cur_state, insn_flags, 0); 5544 return 0; 5545 } 5546 5547 enum bpf_access_src { 5548 ACCESS_DIRECT = 1, /* the access is performed by an instruction */ 5549 ACCESS_HELPER = 2, /* the access is performed by a helper */ 5550 }; 5551 5552 static int check_stack_range_initialized(struct bpf_verifier_env *env, 5553 int regno, int off, int access_size, 5554 bool zero_size_allowed, 5555 enum bpf_access_type type, 5556 struct bpf_call_arg_meta *meta); 5557 5558 static struct bpf_reg_state *reg_state(struct bpf_verifier_env *env, int regno) 5559 { 5560 return cur_regs(env) + regno; 5561 } 5562 5563 /* Read the stack at 'ptr_regno + off' and put the result into the register 5564 * 'dst_regno'. 5565 * 'off' includes the pointer register's fixed offset(i.e. 'ptr_regno.off'), 5566 * but not its variable offset. 5567 * 'size' is assumed to be <= reg size and the access is assumed to be aligned. 5568 * 5569 * As opposed to check_stack_read_fixed_off, this function doesn't deal with 5570 * filling registers (i.e. reads of spilled register cannot be detected when 5571 * the offset is not fixed). We conservatively mark 'dst_regno' as containing 5572 * SCALAR_VALUE. That's why we assert that the 'ptr_regno' has a variable 5573 * offset; for a fixed offset check_stack_read_fixed_off should be used 5574 * instead. 5575 */ 5576 static int check_stack_read_var_off(struct bpf_verifier_env *env, 5577 int ptr_regno, int off, int size, int dst_regno) 5578 { 5579 /* The state of the source register. */ 5580 struct bpf_reg_state *reg = reg_state(env, ptr_regno); 5581 struct bpf_func_state *ptr_state = func(env, reg); 5582 int err; 5583 int min_off, max_off; 5584 5585 /* Note that we pass a NULL meta, so raw access will not be permitted. 5586 */ 5587 err = check_stack_range_initialized(env, ptr_regno, off, size, 5588 false, BPF_READ, NULL); 5589 if (err) 5590 return err; 5591 5592 min_off = reg->smin_value + off; 5593 max_off = reg->smax_value + off; 5594 mark_reg_stack_read(env, ptr_state, min_off, max_off + size, dst_regno); 5595 check_fastcall_stack_contract(env, ptr_state, env->insn_idx, min_off); 5596 return 0; 5597 } 5598 5599 /* check_stack_read dispatches to check_stack_read_fixed_off or 5600 * check_stack_read_var_off. 5601 * 5602 * The caller must ensure that the offset falls within the allocated stack 5603 * bounds. 5604 * 5605 * 'dst_regno' is a register which will receive the value from the stack. It 5606 * can be -1, meaning that the read value is not going to a register. 5607 */ 5608 static int check_stack_read(struct bpf_verifier_env *env, 5609 int ptr_regno, int off, int size, 5610 int dst_regno) 5611 { 5612 struct bpf_reg_state *reg = reg_state(env, ptr_regno); 5613 struct bpf_func_state *state = func(env, reg); 5614 int err; 5615 /* Some accesses are only permitted with a static offset. */ 5616 bool var_off = !tnum_is_const(reg->var_off); 5617 5618 /* The offset is required to be static when reads don't go to a 5619 * register, in order to not leak pointers (see 5620 * check_stack_read_fixed_off). 5621 */ 5622 if (dst_regno < 0 && var_off) { 5623 char tn_buf[48]; 5624 5625 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 5626 verbose(env, "variable offset stack pointer cannot be passed into helper function; var_off=%s off=%d size=%d\n", 5627 tn_buf, off, size); 5628 return -EACCES; 5629 } 5630 /* Variable offset is prohibited for unprivileged mode for simplicity 5631 * since it requires corresponding support in Spectre masking for stack 5632 * ALU. See also retrieve_ptr_limit(). The check in 5633 * check_stack_access_for_ptr_arithmetic() called by 5634 * adjust_ptr_min_max_vals() prevents users from creating stack pointers 5635 * with variable offsets, therefore no check is required here. Further, 5636 * just checking it here would be insufficient as speculative stack 5637 * writes could still lead to unsafe speculative behaviour. 5638 */ 5639 if (!var_off) { 5640 off += reg->var_off.value; 5641 err = check_stack_read_fixed_off(env, state, off, size, 5642 dst_regno); 5643 } else { 5644 /* Variable offset stack reads need more conservative handling 5645 * than fixed offset ones. Note that dst_regno >= 0 on this 5646 * branch. 5647 */ 5648 err = check_stack_read_var_off(env, ptr_regno, off, size, 5649 dst_regno); 5650 } 5651 return err; 5652 } 5653 5654 5655 /* check_stack_write dispatches to check_stack_write_fixed_off or 5656 * check_stack_write_var_off. 5657 * 5658 * 'ptr_regno' is the register used as a pointer into the stack. 5659 * 'off' includes 'ptr_regno->off', but not its variable offset (if any). 5660 * 'value_regno' is the register whose value we're writing to the stack. It can 5661 * be -1, meaning that we're not writing from a register. 5662 * 5663 * The caller must ensure that the offset falls within the maximum stack size. 5664 */ 5665 static int check_stack_write(struct bpf_verifier_env *env, 5666 int ptr_regno, int off, int size, 5667 int value_regno, int insn_idx) 5668 { 5669 struct bpf_reg_state *reg = reg_state(env, ptr_regno); 5670 struct bpf_func_state *state = func(env, reg); 5671 int err; 5672 5673 if (tnum_is_const(reg->var_off)) { 5674 off += reg->var_off.value; 5675 err = check_stack_write_fixed_off(env, state, off, size, 5676 value_regno, insn_idx); 5677 } else { 5678 /* Variable offset stack reads need more conservative handling 5679 * than fixed offset ones. 5680 */ 5681 err = check_stack_write_var_off(env, state, 5682 ptr_regno, off, size, 5683 value_regno, insn_idx); 5684 } 5685 return err; 5686 } 5687 5688 static int check_map_access_type(struct bpf_verifier_env *env, u32 regno, 5689 int off, int size, enum bpf_access_type type) 5690 { 5691 struct bpf_reg_state *regs = cur_regs(env); 5692 struct bpf_map *map = regs[regno].map_ptr; 5693 u32 cap = bpf_map_flags_to_cap(map); 5694 5695 if (type == BPF_WRITE && !(cap & BPF_MAP_CAN_WRITE)) { 5696 verbose(env, "write into map forbidden, value_size=%d off=%d size=%d\n", 5697 map->value_size, off, size); 5698 return -EACCES; 5699 } 5700 5701 if (type == BPF_READ && !(cap & BPF_MAP_CAN_READ)) { 5702 verbose(env, "read from map forbidden, value_size=%d off=%d size=%d\n", 5703 map->value_size, off, size); 5704 return -EACCES; 5705 } 5706 5707 return 0; 5708 } 5709 5710 /* check read/write into memory region (e.g., map value, ringbuf sample, etc) */ 5711 static int __check_mem_access(struct bpf_verifier_env *env, int regno, 5712 int off, int size, u32 mem_size, 5713 bool zero_size_allowed) 5714 { 5715 bool size_ok = size > 0 || (size == 0 && zero_size_allowed); 5716 struct bpf_reg_state *reg; 5717 5718 if (off >= 0 && size_ok && (u64)off + size <= mem_size) 5719 return 0; 5720 5721 reg = &cur_regs(env)[regno]; 5722 switch (reg->type) { 5723 case PTR_TO_MAP_KEY: 5724 verbose(env, "invalid access to map key, key_size=%d off=%d size=%d\n", 5725 mem_size, off, size); 5726 break; 5727 case PTR_TO_MAP_VALUE: 5728 verbose(env, "invalid access to map value, value_size=%d off=%d size=%d\n", 5729 mem_size, off, size); 5730 break; 5731 case PTR_TO_PACKET: 5732 case PTR_TO_PACKET_META: 5733 case PTR_TO_PACKET_END: 5734 verbose(env, "invalid access to packet, off=%d size=%d, R%d(id=%d,off=%d,r=%d)\n", 5735 off, size, regno, reg->id, off, mem_size); 5736 break; 5737 case PTR_TO_MEM: 5738 default: 5739 verbose(env, "invalid access to memory, mem_size=%u off=%d size=%d\n", 5740 mem_size, off, size); 5741 } 5742 5743 return -EACCES; 5744 } 5745 5746 /* check read/write into a memory region with possible variable offset */ 5747 static int check_mem_region_access(struct bpf_verifier_env *env, u32 regno, 5748 int off, int size, u32 mem_size, 5749 bool zero_size_allowed) 5750 { 5751 struct bpf_verifier_state *vstate = env->cur_state; 5752 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 5753 struct bpf_reg_state *reg = &state->regs[regno]; 5754 int err; 5755 5756 /* We may have adjusted the register pointing to memory region, so we 5757 * need to try adding each of min_value and max_value to off 5758 * to make sure our theoretical access will be safe. 5759 * 5760 * The minimum value is only important with signed 5761 * comparisons where we can't assume the floor of a 5762 * value is 0. If we are using signed variables for our 5763 * index'es we need to make sure that whatever we use 5764 * will have a set floor within our range. 5765 */ 5766 if (reg->smin_value < 0 && 5767 (reg->smin_value == S64_MIN || 5768 (off + reg->smin_value != (s64)(s32)(off + reg->smin_value)) || 5769 reg->smin_value + off < 0)) { 5770 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n", 5771 regno); 5772 return -EACCES; 5773 } 5774 err = __check_mem_access(env, regno, reg->smin_value + off, size, 5775 mem_size, zero_size_allowed); 5776 if (err) { 5777 verbose(env, "R%d min value is outside of the allowed memory range\n", 5778 regno); 5779 return err; 5780 } 5781 5782 /* If we haven't set a max value then we need to bail since we can't be 5783 * sure we won't do bad things. 5784 * If reg->umax_value + off could overflow, treat that as unbounded too. 5785 */ 5786 if (reg->umax_value >= BPF_MAX_VAR_OFF) { 5787 verbose(env, "R%d unbounded memory access, make sure to bounds check any such access\n", 5788 regno); 5789 return -EACCES; 5790 } 5791 err = __check_mem_access(env, regno, reg->umax_value + off, size, 5792 mem_size, zero_size_allowed); 5793 if (err) { 5794 verbose(env, "R%d max value is outside of the allowed memory range\n", 5795 regno); 5796 return err; 5797 } 5798 5799 return 0; 5800 } 5801 5802 static int __check_ptr_off_reg(struct bpf_verifier_env *env, 5803 const struct bpf_reg_state *reg, int regno, 5804 bool fixed_off_ok) 5805 { 5806 /* Access to this pointer-typed register or passing it to a helper 5807 * is only allowed in its original, unmodified form. 5808 */ 5809 5810 if (reg->off < 0) { 5811 verbose(env, "negative offset %s ptr R%d off=%d disallowed\n", 5812 reg_type_str(env, reg->type), regno, reg->off); 5813 return -EACCES; 5814 } 5815 5816 if (!fixed_off_ok && reg->off) { 5817 verbose(env, "dereference of modified %s ptr R%d off=%d disallowed\n", 5818 reg_type_str(env, reg->type), regno, reg->off); 5819 return -EACCES; 5820 } 5821 5822 if (!tnum_is_const(reg->var_off) || reg->var_off.value) { 5823 char tn_buf[48]; 5824 5825 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 5826 verbose(env, "variable %s access var_off=%s disallowed\n", 5827 reg_type_str(env, reg->type), tn_buf); 5828 return -EACCES; 5829 } 5830 5831 return 0; 5832 } 5833 5834 static int check_ptr_off_reg(struct bpf_verifier_env *env, 5835 const struct bpf_reg_state *reg, int regno) 5836 { 5837 return __check_ptr_off_reg(env, reg, regno, false); 5838 } 5839 5840 static int map_kptr_match_type(struct bpf_verifier_env *env, 5841 struct btf_field *kptr_field, 5842 struct bpf_reg_state *reg, u32 regno) 5843 { 5844 const char *targ_name = btf_type_name(kptr_field->kptr.btf, kptr_field->kptr.btf_id); 5845 int perm_flags; 5846 const char *reg_name = ""; 5847 5848 if (btf_is_kernel(reg->btf)) { 5849 perm_flags = PTR_MAYBE_NULL | PTR_TRUSTED | MEM_RCU; 5850 5851 /* Only unreferenced case accepts untrusted pointers */ 5852 if (kptr_field->type == BPF_KPTR_UNREF) 5853 perm_flags |= PTR_UNTRUSTED; 5854 } else { 5855 perm_flags = PTR_MAYBE_NULL | MEM_ALLOC; 5856 if (kptr_field->type == BPF_KPTR_PERCPU) 5857 perm_flags |= MEM_PERCPU; 5858 } 5859 5860 if (base_type(reg->type) != PTR_TO_BTF_ID || (type_flag(reg->type) & ~perm_flags)) 5861 goto bad_type; 5862 5863 /* We need to verify reg->type and reg->btf, before accessing reg->btf */ 5864 reg_name = btf_type_name(reg->btf, reg->btf_id); 5865 5866 /* For ref_ptr case, release function check should ensure we get one 5867 * referenced PTR_TO_BTF_ID, and that its fixed offset is 0. For the 5868 * normal store of unreferenced kptr, we must ensure var_off is zero. 5869 * Since ref_ptr cannot be accessed directly by BPF insns, checks for 5870 * reg->off and reg->ref_obj_id are not needed here. 5871 */ 5872 if (__check_ptr_off_reg(env, reg, regno, true)) 5873 return -EACCES; 5874 5875 /* A full type match is needed, as BTF can be vmlinux, module or prog BTF, and 5876 * we also need to take into account the reg->off. 5877 * 5878 * We want to support cases like: 5879 * 5880 * struct foo { 5881 * struct bar br; 5882 * struct baz bz; 5883 * }; 5884 * 5885 * struct foo *v; 5886 * v = func(); // PTR_TO_BTF_ID 5887 * val->foo = v; // reg->off is zero, btf and btf_id match type 5888 * val->bar = &v->br; // reg->off is still zero, but we need to retry with 5889 * // first member type of struct after comparison fails 5890 * val->baz = &v->bz; // reg->off is non-zero, so struct needs to be walked 5891 * // to match type 5892 * 5893 * In the kptr_ref case, check_func_arg_reg_off already ensures reg->off 5894 * is zero. We must also ensure that btf_struct_ids_match does not walk 5895 * the struct to match type against first member of struct, i.e. reject 5896 * second case from above. Hence, when type is BPF_KPTR_REF, we set 5897 * strict mode to true for type match. 5898 */ 5899 if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off, 5900 kptr_field->kptr.btf, kptr_field->kptr.btf_id, 5901 kptr_field->type != BPF_KPTR_UNREF)) 5902 goto bad_type; 5903 return 0; 5904 bad_type: 5905 verbose(env, "invalid kptr access, R%d type=%s%s ", regno, 5906 reg_type_str(env, reg->type), reg_name); 5907 verbose(env, "expected=%s%s", reg_type_str(env, PTR_TO_BTF_ID), targ_name); 5908 if (kptr_field->type == BPF_KPTR_UNREF) 5909 verbose(env, " or %s%s\n", reg_type_str(env, PTR_TO_BTF_ID | PTR_UNTRUSTED), 5910 targ_name); 5911 else 5912 verbose(env, "\n"); 5913 return -EINVAL; 5914 } 5915 5916 static bool in_sleepable(struct bpf_verifier_env *env) 5917 { 5918 return env->prog->sleepable || 5919 (env->cur_state && env->cur_state->in_sleepable); 5920 } 5921 5922 /* The non-sleepable programs and sleepable programs with explicit bpf_rcu_read_lock() 5923 * can dereference RCU protected pointers and result is PTR_TRUSTED. 5924 */ 5925 static bool in_rcu_cs(struct bpf_verifier_env *env) 5926 { 5927 return env->cur_state->active_rcu_lock || 5928 env->cur_state->active_locks || 5929 !in_sleepable(env); 5930 } 5931 5932 /* Once GCC supports btf_type_tag the following mechanism will be replaced with tag check */ 5933 BTF_SET_START(rcu_protected_types) 5934 #ifdef CONFIG_NET 5935 BTF_ID(struct, prog_test_ref_kfunc) 5936 #endif 5937 #ifdef CONFIG_CGROUPS 5938 BTF_ID(struct, cgroup) 5939 #endif 5940 #ifdef CONFIG_BPF_JIT 5941 BTF_ID(struct, bpf_cpumask) 5942 #endif 5943 BTF_ID(struct, task_struct) 5944 #ifdef CONFIG_CRYPTO 5945 BTF_ID(struct, bpf_crypto_ctx) 5946 #endif 5947 BTF_SET_END(rcu_protected_types) 5948 5949 static bool rcu_protected_object(const struct btf *btf, u32 btf_id) 5950 { 5951 if (!btf_is_kernel(btf)) 5952 return true; 5953 return btf_id_set_contains(&rcu_protected_types, btf_id); 5954 } 5955 5956 static struct btf_record *kptr_pointee_btf_record(struct btf_field *kptr_field) 5957 { 5958 struct btf_struct_meta *meta; 5959 5960 if (btf_is_kernel(kptr_field->kptr.btf)) 5961 return NULL; 5962 5963 meta = btf_find_struct_meta(kptr_field->kptr.btf, 5964 kptr_field->kptr.btf_id); 5965 5966 return meta ? meta->record : NULL; 5967 } 5968 5969 static bool rcu_safe_kptr(const struct btf_field *field) 5970 { 5971 const struct btf_field_kptr *kptr = &field->kptr; 5972 5973 return field->type == BPF_KPTR_PERCPU || 5974 (field->type == BPF_KPTR_REF && rcu_protected_object(kptr->btf, kptr->btf_id)); 5975 } 5976 5977 static u32 btf_ld_kptr_type(struct bpf_verifier_env *env, struct btf_field *kptr_field) 5978 { 5979 struct btf_record *rec; 5980 u32 ret; 5981 5982 ret = PTR_MAYBE_NULL; 5983 if (rcu_safe_kptr(kptr_field) && in_rcu_cs(env)) { 5984 ret |= MEM_RCU; 5985 if (kptr_field->type == BPF_KPTR_PERCPU) 5986 ret |= MEM_PERCPU; 5987 else if (!btf_is_kernel(kptr_field->kptr.btf)) 5988 ret |= MEM_ALLOC; 5989 5990 rec = kptr_pointee_btf_record(kptr_field); 5991 if (rec && btf_record_has_field(rec, BPF_GRAPH_NODE)) 5992 ret |= NON_OWN_REF; 5993 } else { 5994 ret |= PTR_UNTRUSTED; 5995 } 5996 5997 return ret; 5998 } 5999 6000 static int mark_uptr_ld_reg(struct bpf_verifier_env *env, u32 regno, 6001 struct btf_field *field) 6002 { 6003 struct bpf_reg_state *reg; 6004 const struct btf_type *t; 6005 6006 t = btf_type_by_id(field->kptr.btf, field->kptr.btf_id); 6007 mark_reg_known_zero(env, cur_regs(env), regno); 6008 reg = reg_state(env, regno); 6009 reg->type = PTR_TO_MEM | PTR_MAYBE_NULL; 6010 reg->mem_size = t->size; 6011 reg->id = ++env->id_gen; 6012 6013 return 0; 6014 } 6015 6016 static int check_map_kptr_access(struct bpf_verifier_env *env, u32 regno, 6017 int value_regno, int insn_idx, 6018 struct btf_field *kptr_field) 6019 { 6020 struct bpf_insn *insn = &env->prog->insnsi[insn_idx]; 6021 int class = BPF_CLASS(insn->code); 6022 struct bpf_reg_state *val_reg; 6023 int ret; 6024 6025 /* Things we already checked for in check_map_access and caller: 6026 * - Reject cases where variable offset may touch kptr 6027 * - size of access (must be BPF_DW) 6028 * - tnum_is_const(reg->var_off) 6029 * - kptr_field->offset == off + reg->var_off.value 6030 */ 6031 /* Only BPF_[LDX,STX,ST] | BPF_MEM | BPF_DW is supported */ 6032 if (BPF_MODE(insn->code) != BPF_MEM) { 6033 verbose(env, "kptr in map can only be accessed using BPF_MEM instruction mode\n"); 6034 return -EACCES; 6035 } 6036 6037 /* We only allow loading referenced kptr, since it will be marked as 6038 * untrusted, similar to unreferenced kptr. 6039 */ 6040 if (class != BPF_LDX && 6041 (kptr_field->type == BPF_KPTR_REF || kptr_field->type == BPF_KPTR_PERCPU)) { 6042 verbose(env, "store to referenced kptr disallowed\n"); 6043 return -EACCES; 6044 } 6045 if (class != BPF_LDX && kptr_field->type == BPF_UPTR) { 6046 verbose(env, "store to uptr disallowed\n"); 6047 return -EACCES; 6048 } 6049 6050 if (class == BPF_LDX) { 6051 if (kptr_field->type == BPF_UPTR) 6052 return mark_uptr_ld_reg(env, value_regno, kptr_field); 6053 6054 /* We can simply mark the value_regno receiving the pointer 6055 * value from map as PTR_TO_BTF_ID, with the correct type. 6056 */ 6057 ret = mark_btf_ld_reg(env, cur_regs(env), value_regno, PTR_TO_BTF_ID, 6058 kptr_field->kptr.btf, kptr_field->kptr.btf_id, 6059 btf_ld_kptr_type(env, kptr_field)); 6060 if (ret < 0) 6061 return ret; 6062 } else if (class == BPF_STX) { 6063 val_reg = reg_state(env, value_regno); 6064 if (!register_is_null(val_reg) && 6065 map_kptr_match_type(env, kptr_field, val_reg, value_regno)) 6066 return -EACCES; 6067 } else if (class == BPF_ST) { 6068 if (insn->imm) { 6069 verbose(env, "BPF_ST imm must be 0 when storing to kptr at off=%u\n", 6070 kptr_field->offset); 6071 return -EACCES; 6072 } 6073 } else { 6074 verbose(env, "kptr in map can only be accessed using BPF_LDX/BPF_STX/BPF_ST\n"); 6075 return -EACCES; 6076 } 6077 return 0; 6078 } 6079 6080 /* check read/write into a map element with possible variable offset */ 6081 static int check_map_access(struct bpf_verifier_env *env, u32 regno, 6082 int off, int size, bool zero_size_allowed, 6083 enum bpf_access_src src) 6084 { 6085 struct bpf_verifier_state *vstate = env->cur_state; 6086 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 6087 struct bpf_reg_state *reg = &state->regs[regno]; 6088 struct bpf_map *map = reg->map_ptr; 6089 struct btf_record *rec; 6090 int err, i; 6091 6092 err = check_mem_region_access(env, regno, off, size, map->value_size, 6093 zero_size_allowed); 6094 if (err) 6095 return err; 6096 6097 if (IS_ERR_OR_NULL(map->record)) 6098 return 0; 6099 rec = map->record; 6100 for (i = 0; i < rec->cnt; i++) { 6101 struct btf_field *field = &rec->fields[i]; 6102 u32 p = field->offset; 6103 6104 /* If any part of a field can be touched by load/store, reject 6105 * this program. To check that [x1, x2) overlaps with [y1, y2), 6106 * it is sufficient to check x1 < y2 && y1 < x2. 6107 */ 6108 if (reg->smin_value + off < p + field->size && 6109 p < reg->umax_value + off + size) { 6110 switch (field->type) { 6111 case BPF_KPTR_UNREF: 6112 case BPF_KPTR_REF: 6113 case BPF_KPTR_PERCPU: 6114 case BPF_UPTR: 6115 if (src != ACCESS_DIRECT) { 6116 verbose(env, "%s cannot be accessed indirectly by helper\n", 6117 btf_field_type_name(field->type)); 6118 return -EACCES; 6119 } 6120 if (!tnum_is_const(reg->var_off)) { 6121 verbose(env, "%s access cannot have variable offset\n", 6122 btf_field_type_name(field->type)); 6123 return -EACCES; 6124 } 6125 if (p != off + reg->var_off.value) { 6126 verbose(env, "%s access misaligned expected=%u off=%llu\n", 6127 btf_field_type_name(field->type), 6128 p, off + reg->var_off.value); 6129 return -EACCES; 6130 } 6131 if (size != bpf_size_to_bytes(BPF_DW)) { 6132 verbose(env, "%s access size must be BPF_DW\n", 6133 btf_field_type_name(field->type)); 6134 return -EACCES; 6135 } 6136 break; 6137 default: 6138 verbose(env, "%s cannot be accessed directly by load/store\n", 6139 btf_field_type_name(field->type)); 6140 return -EACCES; 6141 } 6142 } 6143 } 6144 return 0; 6145 } 6146 6147 #define MAX_PACKET_OFF 0xffff 6148 6149 static bool may_access_direct_pkt_data(struct bpf_verifier_env *env, 6150 const struct bpf_call_arg_meta *meta, 6151 enum bpf_access_type t) 6152 { 6153 enum bpf_prog_type prog_type = resolve_prog_type(env->prog); 6154 6155 switch (prog_type) { 6156 /* Program types only with direct read access go here! */ 6157 case BPF_PROG_TYPE_LWT_IN: 6158 case BPF_PROG_TYPE_LWT_OUT: 6159 case BPF_PROG_TYPE_LWT_SEG6LOCAL: 6160 case BPF_PROG_TYPE_SK_REUSEPORT: 6161 case BPF_PROG_TYPE_FLOW_DISSECTOR: 6162 case BPF_PROG_TYPE_CGROUP_SKB: 6163 if (t == BPF_WRITE) 6164 return false; 6165 fallthrough; 6166 6167 /* Program types with direct read + write access go here! */ 6168 case BPF_PROG_TYPE_SCHED_CLS: 6169 case BPF_PROG_TYPE_SCHED_ACT: 6170 case BPF_PROG_TYPE_XDP: 6171 case BPF_PROG_TYPE_LWT_XMIT: 6172 case BPF_PROG_TYPE_SK_SKB: 6173 case BPF_PROG_TYPE_SK_MSG: 6174 if (meta) 6175 return meta->pkt_access; 6176 6177 env->seen_direct_write = true; 6178 return true; 6179 6180 case BPF_PROG_TYPE_CGROUP_SOCKOPT: 6181 if (t == BPF_WRITE) 6182 env->seen_direct_write = true; 6183 6184 return true; 6185 6186 default: 6187 return false; 6188 } 6189 } 6190 6191 static int check_packet_access(struct bpf_verifier_env *env, u32 regno, int off, 6192 int size, bool zero_size_allowed) 6193 { 6194 struct bpf_reg_state *regs = cur_regs(env); 6195 struct bpf_reg_state *reg = ®s[regno]; 6196 int err; 6197 6198 /* We may have added a variable offset to the packet pointer; but any 6199 * reg->range we have comes after that. We are only checking the fixed 6200 * offset. 6201 */ 6202 6203 /* We don't allow negative numbers, because we aren't tracking enough 6204 * detail to prove they're safe. 6205 */ 6206 if (reg->smin_value < 0) { 6207 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n", 6208 regno); 6209 return -EACCES; 6210 } 6211 6212 err = reg->range < 0 ? -EINVAL : 6213 __check_mem_access(env, regno, off, size, reg->range, 6214 zero_size_allowed); 6215 if (err) { 6216 verbose(env, "R%d offset is outside of the packet\n", regno); 6217 return err; 6218 } 6219 6220 /* __check_mem_access has made sure "off + size - 1" is within u16. 6221 * reg->umax_value can't be bigger than MAX_PACKET_OFF which is 0xffff, 6222 * otherwise find_good_pkt_pointers would have refused to set range info 6223 * that __check_mem_access would have rejected this pkt access. 6224 * Therefore, "off + reg->umax_value + size - 1" won't overflow u32. 6225 */ 6226 env->prog->aux->max_pkt_offset = 6227 max_t(u32, env->prog->aux->max_pkt_offset, 6228 off + reg->umax_value + size - 1); 6229 6230 return err; 6231 } 6232 6233 /* check access to 'struct bpf_context' fields. Supports fixed offsets only */ 6234 static int check_ctx_access(struct bpf_verifier_env *env, int insn_idx, int off, int size, 6235 enum bpf_access_type t, struct bpf_insn_access_aux *info) 6236 { 6237 if (env->ops->is_valid_access && 6238 env->ops->is_valid_access(off, size, t, env->prog, info)) { 6239 /* A non zero info.ctx_field_size indicates that this field is a 6240 * candidate for later verifier transformation to load the whole 6241 * field and then apply a mask when accessed with a narrower 6242 * access than actual ctx access size. A zero info.ctx_field_size 6243 * will only allow for whole field access and rejects any other 6244 * type of narrower access. 6245 */ 6246 if (base_type(info->reg_type) == PTR_TO_BTF_ID) { 6247 if (info->ref_obj_id && 6248 !find_reference_state(env->cur_state, info->ref_obj_id)) { 6249 verbose(env, "invalid bpf_context access off=%d. Reference may already be released\n", 6250 off); 6251 return -EACCES; 6252 } 6253 } else { 6254 env->insn_aux_data[insn_idx].ctx_field_size = info->ctx_field_size; 6255 } 6256 /* remember the offset of last byte accessed in ctx */ 6257 if (env->prog->aux->max_ctx_offset < off + size) 6258 env->prog->aux->max_ctx_offset = off + size; 6259 return 0; 6260 } 6261 6262 verbose(env, "invalid bpf_context access off=%d size=%d\n", off, size); 6263 return -EACCES; 6264 } 6265 6266 static int check_flow_keys_access(struct bpf_verifier_env *env, int off, 6267 int size) 6268 { 6269 if (size < 0 || off < 0 || 6270 (u64)off + size > sizeof(struct bpf_flow_keys)) { 6271 verbose(env, "invalid access to flow keys off=%d size=%d\n", 6272 off, size); 6273 return -EACCES; 6274 } 6275 return 0; 6276 } 6277 6278 static int check_sock_access(struct bpf_verifier_env *env, int insn_idx, 6279 u32 regno, int off, int size, 6280 enum bpf_access_type t) 6281 { 6282 struct bpf_reg_state *regs = cur_regs(env); 6283 struct bpf_reg_state *reg = ®s[regno]; 6284 struct bpf_insn_access_aux info = {}; 6285 bool valid; 6286 6287 if (reg->smin_value < 0) { 6288 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n", 6289 regno); 6290 return -EACCES; 6291 } 6292 6293 switch (reg->type) { 6294 case PTR_TO_SOCK_COMMON: 6295 valid = bpf_sock_common_is_valid_access(off, size, t, &info); 6296 break; 6297 case PTR_TO_SOCKET: 6298 valid = bpf_sock_is_valid_access(off, size, t, &info); 6299 break; 6300 case PTR_TO_TCP_SOCK: 6301 valid = bpf_tcp_sock_is_valid_access(off, size, t, &info); 6302 break; 6303 case PTR_TO_XDP_SOCK: 6304 valid = bpf_xdp_sock_is_valid_access(off, size, t, &info); 6305 break; 6306 default: 6307 valid = false; 6308 } 6309 6310 6311 if (valid) { 6312 env->insn_aux_data[insn_idx].ctx_field_size = 6313 info.ctx_field_size; 6314 return 0; 6315 } 6316 6317 verbose(env, "R%d invalid %s access off=%d size=%d\n", 6318 regno, reg_type_str(env, reg->type), off, size); 6319 6320 return -EACCES; 6321 } 6322 6323 static bool is_pointer_value(struct bpf_verifier_env *env, int regno) 6324 { 6325 return __is_pointer_value(env->allow_ptr_leaks, reg_state(env, regno)); 6326 } 6327 6328 static bool is_ctx_reg(struct bpf_verifier_env *env, int regno) 6329 { 6330 const struct bpf_reg_state *reg = reg_state(env, regno); 6331 6332 return reg->type == PTR_TO_CTX; 6333 } 6334 6335 static bool is_sk_reg(struct bpf_verifier_env *env, int regno) 6336 { 6337 const struct bpf_reg_state *reg = reg_state(env, regno); 6338 6339 return type_is_sk_pointer(reg->type); 6340 } 6341 6342 static bool is_pkt_reg(struct bpf_verifier_env *env, int regno) 6343 { 6344 const struct bpf_reg_state *reg = reg_state(env, regno); 6345 6346 return type_is_pkt_pointer(reg->type); 6347 } 6348 6349 static bool is_flow_key_reg(struct bpf_verifier_env *env, int regno) 6350 { 6351 const struct bpf_reg_state *reg = reg_state(env, regno); 6352 6353 /* Separate to is_ctx_reg() since we still want to allow BPF_ST here. */ 6354 return reg->type == PTR_TO_FLOW_KEYS; 6355 } 6356 6357 static bool is_arena_reg(struct bpf_verifier_env *env, int regno) 6358 { 6359 const struct bpf_reg_state *reg = reg_state(env, regno); 6360 6361 return reg->type == PTR_TO_ARENA; 6362 } 6363 6364 /* Return false if @regno contains a pointer whose type isn't supported for 6365 * atomic instruction @insn. 6366 */ 6367 static bool atomic_ptr_type_ok(struct bpf_verifier_env *env, int regno, 6368 struct bpf_insn *insn) 6369 { 6370 if (is_ctx_reg(env, regno)) 6371 return false; 6372 if (is_pkt_reg(env, regno)) 6373 return false; 6374 if (is_flow_key_reg(env, regno)) 6375 return false; 6376 if (is_sk_reg(env, regno)) 6377 return false; 6378 if (is_arena_reg(env, regno)) 6379 return bpf_jit_supports_insn(insn, true); 6380 6381 return true; 6382 } 6383 6384 static u32 *reg2btf_ids[__BPF_REG_TYPE_MAX] = { 6385 #ifdef CONFIG_NET 6386 [PTR_TO_SOCKET] = &btf_sock_ids[BTF_SOCK_TYPE_SOCK], 6387 [PTR_TO_SOCK_COMMON] = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON], 6388 [PTR_TO_TCP_SOCK] = &btf_sock_ids[BTF_SOCK_TYPE_TCP], 6389 #endif 6390 [CONST_PTR_TO_MAP] = btf_bpf_map_id, 6391 }; 6392 6393 static bool is_trusted_reg(const struct bpf_reg_state *reg) 6394 { 6395 /* A referenced register is always trusted. */ 6396 if (reg->ref_obj_id) 6397 return true; 6398 6399 /* Types listed in the reg2btf_ids are always trusted */ 6400 if (reg2btf_ids[base_type(reg->type)] && 6401 !bpf_type_has_unsafe_modifiers(reg->type)) 6402 return true; 6403 6404 /* If a register is not referenced, it is trusted if it has the 6405 * MEM_ALLOC or PTR_TRUSTED type modifiers, and no others. Some of the 6406 * other type modifiers may be safe, but we elect to take an opt-in 6407 * approach here as some (e.g. PTR_UNTRUSTED and PTR_MAYBE_NULL) are 6408 * not. 6409 * 6410 * Eventually, we should make PTR_TRUSTED the single source of truth 6411 * for whether a register is trusted. 6412 */ 6413 return type_flag(reg->type) & BPF_REG_TRUSTED_MODIFIERS && 6414 !bpf_type_has_unsafe_modifiers(reg->type); 6415 } 6416 6417 static bool is_rcu_reg(const struct bpf_reg_state *reg) 6418 { 6419 return reg->type & MEM_RCU; 6420 } 6421 6422 static void clear_trusted_flags(enum bpf_type_flag *flag) 6423 { 6424 *flag &= ~(BPF_REG_TRUSTED_MODIFIERS | MEM_RCU); 6425 } 6426 6427 static int check_pkt_ptr_alignment(struct bpf_verifier_env *env, 6428 const struct bpf_reg_state *reg, 6429 int off, int size, bool strict) 6430 { 6431 struct tnum reg_off; 6432 int ip_align; 6433 6434 /* Byte size accesses are always allowed. */ 6435 if (!strict || size == 1) 6436 return 0; 6437 6438 /* For platforms that do not have a Kconfig enabling 6439 * CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS the value of 6440 * NET_IP_ALIGN is universally set to '2'. And on platforms 6441 * that do set CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS, we get 6442 * to this code only in strict mode where we want to emulate 6443 * the NET_IP_ALIGN==2 checking. Therefore use an 6444 * unconditional IP align value of '2'. 6445 */ 6446 ip_align = 2; 6447 6448 reg_off = tnum_add(reg->var_off, tnum_const(ip_align + reg->off + off)); 6449 if (!tnum_is_aligned(reg_off, size)) { 6450 char tn_buf[48]; 6451 6452 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 6453 verbose(env, 6454 "misaligned packet access off %d+%s+%d+%d size %d\n", 6455 ip_align, tn_buf, reg->off, off, size); 6456 return -EACCES; 6457 } 6458 6459 return 0; 6460 } 6461 6462 static int check_generic_ptr_alignment(struct bpf_verifier_env *env, 6463 const struct bpf_reg_state *reg, 6464 const char *pointer_desc, 6465 int off, int size, bool strict) 6466 { 6467 struct tnum reg_off; 6468 6469 /* Byte size accesses are always allowed. */ 6470 if (!strict || size == 1) 6471 return 0; 6472 6473 reg_off = tnum_add(reg->var_off, tnum_const(reg->off + off)); 6474 if (!tnum_is_aligned(reg_off, size)) { 6475 char tn_buf[48]; 6476 6477 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 6478 verbose(env, "misaligned %saccess off %s+%d+%d size %d\n", 6479 pointer_desc, tn_buf, reg->off, off, size); 6480 return -EACCES; 6481 } 6482 6483 return 0; 6484 } 6485 6486 static int check_ptr_alignment(struct bpf_verifier_env *env, 6487 const struct bpf_reg_state *reg, int off, 6488 int size, bool strict_alignment_once) 6489 { 6490 bool strict = env->strict_alignment || strict_alignment_once; 6491 const char *pointer_desc = ""; 6492 6493 switch (reg->type) { 6494 case PTR_TO_PACKET: 6495 case PTR_TO_PACKET_META: 6496 /* Special case, because of NET_IP_ALIGN. Given metadata sits 6497 * right in front, treat it the very same way. 6498 */ 6499 return check_pkt_ptr_alignment(env, reg, off, size, strict); 6500 case PTR_TO_FLOW_KEYS: 6501 pointer_desc = "flow keys "; 6502 break; 6503 case PTR_TO_MAP_KEY: 6504 pointer_desc = "key "; 6505 break; 6506 case PTR_TO_MAP_VALUE: 6507 pointer_desc = "value "; 6508 break; 6509 case PTR_TO_CTX: 6510 pointer_desc = "context "; 6511 break; 6512 case PTR_TO_STACK: 6513 pointer_desc = "stack "; 6514 /* The stack spill tracking logic in check_stack_write_fixed_off() 6515 * and check_stack_read_fixed_off() relies on stack accesses being 6516 * aligned. 6517 */ 6518 strict = true; 6519 break; 6520 case PTR_TO_SOCKET: 6521 pointer_desc = "sock "; 6522 break; 6523 case PTR_TO_SOCK_COMMON: 6524 pointer_desc = "sock_common "; 6525 break; 6526 case PTR_TO_TCP_SOCK: 6527 pointer_desc = "tcp_sock "; 6528 break; 6529 case PTR_TO_XDP_SOCK: 6530 pointer_desc = "xdp_sock "; 6531 break; 6532 case PTR_TO_ARENA: 6533 return 0; 6534 default: 6535 break; 6536 } 6537 return check_generic_ptr_alignment(env, reg, pointer_desc, off, size, 6538 strict); 6539 } 6540 6541 static enum priv_stack_mode bpf_enable_priv_stack(struct bpf_prog *prog) 6542 { 6543 if (!bpf_jit_supports_private_stack()) 6544 return NO_PRIV_STACK; 6545 6546 /* bpf_prog_check_recur() checks all prog types that use bpf trampoline 6547 * while kprobe/tp/perf_event/raw_tp don't use trampoline hence checked 6548 * explicitly. 6549 */ 6550 switch (prog->type) { 6551 case BPF_PROG_TYPE_KPROBE: 6552 case BPF_PROG_TYPE_TRACEPOINT: 6553 case BPF_PROG_TYPE_PERF_EVENT: 6554 case BPF_PROG_TYPE_RAW_TRACEPOINT: 6555 return PRIV_STACK_ADAPTIVE; 6556 case BPF_PROG_TYPE_TRACING: 6557 case BPF_PROG_TYPE_LSM: 6558 case BPF_PROG_TYPE_STRUCT_OPS: 6559 if (prog->aux->priv_stack_requested || bpf_prog_check_recur(prog)) 6560 return PRIV_STACK_ADAPTIVE; 6561 fallthrough; 6562 default: 6563 break; 6564 } 6565 6566 return NO_PRIV_STACK; 6567 } 6568 6569 static int round_up_stack_depth(struct bpf_verifier_env *env, int stack_depth) 6570 { 6571 if (env->prog->jit_requested) 6572 return round_up(stack_depth, 16); 6573 6574 /* round up to 32-bytes, since this is granularity 6575 * of interpreter stack size 6576 */ 6577 return round_up(max_t(u32, stack_depth, 1), 32); 6578 } 6579 6580 /* starting from main bpf function walk all instructions of the function 6581 * and recursively walk all callees that given function can call. 6582 * Ignore jump and exit insns. 6583 * Since recursion is prevented by check_cfg() this algorithm 6584 * only needs a local stack of MAX_CALL_FRAMES to remember callsites 6585 */ 6586 static int check_max_stack_depth_subprog(struct bpf_verifier_env *env, int idx, 6587 bool priv_stack_supported) 6588 { 6589 struct bpf_subprog_info *subprog = env->subprog_info; 6590 struct bpf_insn *insn = env->prog->insnsi; 6591 int depth = 0, frame = 0, i, subprog_end, subprog_depth; 6592 bool tail_call_reachable = false; 6593 int ret_insn[MAX_CALL_FRAMES]; 6594 int ret_prog[MAX_CALL_FRAMES]; 6595 int j; 6596 6597 i = subprog[idx].start; 6598 if (!priv_stack_supported) 6599 subprog[idx].priv_stack_mode = NO_PRIV_STACK; 6600 process_func: 6601 /* protect against potential stack overflow that might happen when 6602 * bpf2bpf calls get combined with tailcalls. Limit the caller's stack 6603 * depth for such case down to 256 so that the worst case scenario 6604 * would result in 8k stack size (32 which is tailcall limit * 256 = 6605 * 8k). 6606 * 6607 * To get the idea what might happen, see an example: 6608 * func1 -> sub rsp, 128 6609 * subfunc1 -> sub rsp, 256 6610 * tailcall1 -> add rsp, 256 6611 * func2 -> sub rsp, 192 (total stack size = 128 + 192 = 320) 6612 * subfunc2 -> sub rsp, 64 6613 * subfunc22 -> sub rsp, 128 6614 * tailcall2 -> add rsp, 128 6615 * func3 -> sub rsp, 32 (total stack size 128 + 192 + 64 + 32 = 416) 6616 * 6617 * tailcall will unwind the current stack frame but it will not get rid 6618 * of caller's stack as shown on the example above. 6619 */ 6620 if (idx && subprog[idx].has_tail_call && depth >= 256) { 6621 verbose(env, 6622 "tail_calls are not allowed when call stack of previous frames is %d bytes. Too large\n", 6623 depth); 6624 return -EACCES; 6625 } 6626 6627 subprog_depth = round_up_stack_depth(env, subprog[idx].stack_depth); 6628 if (priv_stack_supported) { 6629 /* Request private stack support only if the subprog stack 6630 * depth is no less than BPF_PRIV_STACK_MIN_SIZE. This is to 6631 * avoid jit penalty if the stack usage is small. 6632 */ 6633 if (subprog[idx].priv_stack_mode == PRIV_STACK_UNKNOWN && 6634 subprog_depth >= BPF_PRIV_STACK_MIN_SIZE) 6635 subprog[idx].priv_stack_mode = PRIV_STACK_ADAPTIVE; 6636 } 6637 6638 if (subprog[idx].priv_stack_mode == PRIV_STACK_ADAPTIVE) { 6639 if (subprog_depth > MAX_BPF_STACK) { 6640 verbose(env, "stack size of subprog %d is %d. Too large\n", 6641 idx, subprog_depth); 6642 return -EACCES; 6643 } 6644 } else { 6645 depth += subprog_depth; 6646 if (depth > MAX_BPF_STACK) { 6647 verbose(env, "combined stack size of %d calls is %d. Too large\n", 6648 frame + 1, depth); 6649 return -EACCES; 6650 } 6651 } 6652 continue_func: 6653 subprog_end = subprog[idx + 1].start; 6654 for (; i < subprog_end; i++) { 6655 int next_insn, sidx; 6656 6657 if (bpf_pseudo_kfunc_call(insn + i) && !insn[i].off) { 6658 bool err = false; 6659 6660 if (!is_bpf_throw_kfunc(insn + i)) 6661 continue; 6662 if (subprog[idx].is_cb) 6663 err = true; 6664 for (int c = 0; c < frame && !err; c++) { 6665 if (subprog[ret_prog[c]].is_cb) { 6666 err = true; 6667 break; 6668 } 6669 } 6670 if (!err) 6671 continue; 6672 verbose(env, 6673 "bpf_throw kfunc (insn %d) cannot be called from callback subprog %d\n", 6674 i, idx); 6675 return -EINVAL; 6676 } 6677 6678 if (!bpf_pseudo_call(insn + i) && !bpf_pseudo_func(insn + i)) 6679 continue; 6680 /* remember insn and function to return to */ 6681 ret_insn[frame] = i + 1; 6682 ret_prog[frame] = idx; 6683 6684 /* find the callee */ 6685 next_insn = i + insn[i].imm + 1; 6686 sidx = find_subprog(env, next_insn); 6687 if (verifier_bug_if(sidx < 0, env, "callee not found at insn %d", next_insn)) 6688 return -EFAULT; 6689 if (subprog[sidx].is_async_cb) { 6690 if (subprog[sidx].has_tail_call) { 6691 verifier_bug(env, "subprog has tail_call and async cb"); 6692 return -EFAULT; 6693 } 6694 /* async callbacks don't increase bpf prog stack size unless called directly */ 6695 if (!bpf_pseudo_call(insn + i)) 6696 continue; 6697 if (subprog[sidx].is_exception_cb) { 6698 verbose(env, "insn %d cannot call exception cb directly", i); 6699 return -EINVAL; 6700 } 6701 } 6702 i = next_insn; 6703 idx = sidx; 6704 if (!priv_stack_supported) 6705 subprog[idx].priv_stack_mode = NO_PRIV_STACK; 6706 6707 if (subprog[idx].has_tail_call) 6708 tail_call_reachable = true; 6709 6710 frame++; 6711 if (frame >= MAX_CALL_FRAMES) { 6712 verbose(env, "the call stack of %d frames is too deep !\n", 6713 frame); 6714 return -E2BIG; 6715 } 6716 goto process_func; 6717 } 6718 /* if tail call got detected across bpf2bpf calls then mark each of the 6719 * currently present subprog frames as tail call reachable subprogs; 6720 * this info will be utilized by JIT so that we will be preserving the 6721 * tail call counter throughout bpf2bpf calls combined with tailcalls 6722 */ 6723 if (tail_call_reachable) 6724 for (j = 0; j < frame; j++) { 6725 if (subprog[ret_prog[j]].is_exception_cb) { 6726 verbose(env, "cannot tail call within exception cb\n"); 6727 return -EINVAL; 6728 } 6729 subprog[ret_prog[j]].tail_call_reachable = true; 6730 } 6731 if (subprog[0].tail_call_reachable) 6732 env->prog->aux->tail_call_reachable = true; 6733 6734 /* end of for() loop means the last insn of the 'subprog' 6735 * was reached. Doesn't matter whether it was JA or EXIT 6736 */ 6737 if (frame == 0) 6738 return 0; 6739 if (subprog[idx].priv_stack_mode != PRIV_STACK_ADAPTIVE) 6740 depth -= round_up_stack_depth(env, subprog[idx].stack_depth); 6741 frame--; 6742 i = ret_insn[frame]; 6743 idx = ret_prog[frame]; 6744 goto continue_func; 6745 } 6746 6747 static int check_max_stack_depth(struct bpf_verifier_env *env) 6748 { 6749 enum priv_stack_mode priv_stack_mode = PRIV_STACK_UNKNOWN; 6750 struct bpf_subprog_info *si = env->subprog_info; 6751 bool priv_stack_supported; 6752 int ret; 6753 6754 for (int i = 0; i < env->subprog_cnt; i++) { 6755 if (si[i].has_tail_call) { 6756 priv_stack_mode = NO_PRIV_STACK; 6757 break; 6758 } 6759 } 6760 6761 if (priv_stack_mode == PRIV_STACK_UNKNOWN) 6762 priv_stack_mode = bpf_enable_priv_stack(env->prog); 6763 6764 /* All async_cb subprogs use normal kernel stack. If a particular 6765 * subprog appears in both main prog and async_cb subtree, that 6766 * subprog will use normal kernel stack to avoid potential nesting. 6767 * The reverse subprog traversal ensures when main prog subtree is 6768 * checked, the subprogs appearing in async_cb subtrees are already 6769 * marked as using normal kernel stack, so stack size checking can 6770 * be done properly. 6771 */ 6772 for (int i = env->subprog_cnt - 1; i >= 0; i--) { 6773 if (!i || si[i].is_async_cb) { 6774 priv_stack_supported = !i && priv_stack_mode == PRIV_STACK_ADAPTIVE; 6775 ret = check_max_stack_depth_subprog(env, i, priv_stack_supported); 6776 if (ret < 0) 6777 return ret; 6778 } 6779 } 6780 6781 for (int i = 0; i < env->subprog_cnt; i++) { 6782 if (si[i].priv_stack_mode == PRIV_STACK_ADAPTIVE) { 6783 env->prog->aux->jits_use_priv_stack = true; 6784 break; 6785 } 6786 } 6787 6788 return 0; 6789 } 6790 6791 #ifndef CONFIG_BPF_JIT_ALWAYS_ON 6792 static int get_callee_stack_depth(struct bpf_verifier_env *env, 6793 const struct bpf_insn *insn, int idx) 6794 { 6795 int start = idx + insn->imm + 1, subprog; 6796 6797 subprog = find_subprog(env, start); 6798 if (verifier_bug_if(subprog < 0, env, "get stack depth: no program at insn %d", start)) 6799 return -EFAULT; 6800 return env->subprog_info[subprog].stack_depth; 6801 } 6802 #endif 6803 6804 static int __check_buffer_access(struct bpf_verifier_env *env, 6805 const char *buf_info, 6806 const struct bpf_reg_state *reg, 6807 int regno, int off, int size) 6808 { 6809 if (off < 0) { 6810 verbose(env, 6811 "R%d invalid %s buffer access: off=%d, size=%d\n", 6812 regno, buf_info, off, size); 6813 return -EACCES; 6814 } 6815 if (!tnum_is_const(reg->var_off) || reg->var_off.value) { 6816 char tn_buf[48]; 6817 6818 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 6819 verbose(env, 6820 "R%d invalid variable buffer offset: off=%d, var_off=%s\n", 6821 regno, off, tn_buf); 6822 return -EACCES; 6823 } 6824 6825 return 0; 6826 } 6827 6828 static int check_tp_buffer_access(struct bpf_verifier_env *env, 6829 const struct bpf_reg_state *reg, 6830 int regno, int off, int size) 6831 { 6832 int err; 6833 6834 err = __check_buffer_access(env, "tracepoint", reg, regno, off, size); 6835 if (err) 6836 return err; 6837 6838 if (off + size > env->prog->aux->max_tp_access) 6839 env->prog->aux->max_tp_access = off + size; 6840 6841 return 0; 6842 } 6843 6844 static int check_buffer_access(struct bpf_verifier_env *env, 6845 const struct bpf_reg_state *reg, 6846 int regno, int off, int size, 6847 bool zero_size_allowed, 6848 u32 *max_access) 6849 { 6850 const char *buf_info = type_is_rdonly_mem(reg->type) ? "rdonly" : "rdwr"; 6851 int err; 6852 6853 err = __check_buffer_access(env, buf_info, reg, regno, off, size); 6854 if (err) 6855 return err; 6856 6857 if (off + size > *max_access) 6858 *max_access = off + size; 6859 6860 return 0; 6861 } 6862 6863 /* BPF architecture zero extends alu32 ops into 64-bit registesr */ 6864 static void zext_32_to_64(struct bpf_reg_state *reg) 6865 { 6866 reg->var_off = tnum_subreg(reg->var_off); 6867 __reg_assign_32_into_64(reg); 6868 } 6869 6870 /* truncate register to smaller size (in bytes) 6871 * must be called with size < BPF_REG_SIZE 6872 */ 6873 static void coerce_reg_to_size(struct bpf_reg_state *reg, int size) 6874 { 6875 u64 mask; 6876 6877 /* clear high bits in bit representation */ 6878 reg->var_off = tnum_cast(reg->var_off, size); 6879 6880 /* fix arithmetic bounds */ 6881 mask = ((u64)1 << (size * 8)) - 1; 6882 if ((reg->umin_value & ~mask) == (reg->umax_value & ~mask)) { 6883 reg->umin_value &= mask; 6884 reg->umax_value &= mask; 6885 } else { 6886 reg->umin_value = 0; 6887 reg->umax_value = mask; 6888 } 6889 reg->smin_value = reg->umin_value; 6890 reg->smax_value = reg->umax_value; 6891 6892 /* If size is smaller than 32bit register the 32bit register 6893 * values are also truncated so we push 64-bit bounds into 6894 * 32-bit bounds. Above were truncated < 32-bits already. 6895 */ 6896 if (size < 4) 6897 __mark_reg32_unbounded(reg); 6898 6899 reg_bounds_sync(reg); 6900 } 6901 6902 static void set_sext64_default_val(struct bpf_reg_state *reg, int size) 6903 { 6904 if (size == 1) { 6905 reg->smin_value = reg->s32_min_value = S8_MIN; 6906 reg->smax_value = reg->s32_max_value = S8_MAX; 6907 } else if (size == 2) { 6908 reg->smin_value = reg->s32_min_value = S16_MIN; 6909 reg->smax_value = reg->s32_max_value = S16_MAX; 6910 } else { 6911 /* size == 4 */ 6912 reg->smin_value = reg->s32_min_value = S32_MIN; 6913 reg->smax_value = reg->s32_max_value = S32_MAX; 6914 } 6915 reg->umin_value = reg->u32_min_value = 0; 6916 reg->umax_value = U64_MAX; 6917 reg->u32_max_value = U32_MAX; 6918 reg->var_off = tnum_unknown; 6919 } 6920 6921 static void coerce_reg_to_size_sx(struct bpf_reg_state *reg, int size) 6922 { 6923 s64 init_s64_max, init_s64_min, s64_max, s64_min, u64_cval; 6924 u64 top_smax_value, top_smin_value; 6925 u64 num_bits = size * 8; 6926 6927 if (tnum_is_const(reg->var_off)) { 6928 u64_cval = reg->var_off.value; 6929 if (size == 1) 6930 reg->var_off = tnum_const((s8)u64_cval); 6931 else if (size == 2) 6932 reg->var_off = tnum_const((s16)u64_cval); 6933 else 6934 /* size == 4 */ 6935 reg->var_off = tnum_const((s32)u64_cval); 6936 6937 u64_cval = reg->var_off.value; 6938 reg->smax_value = reg->smin_value = u64_cval; 6939 reg->umax_value = reg->umin_value = u64_cval; 6940 reg->s32_max_value = reg->s32_min_value = u64_cval; 6941 reg->u32_max_value = reg->u32_min_value = u64_cval; 6942 return; 6943 } 6944 6945 top_smax_value = ((u64)reg->smax_value >> num_bits) << num_bits; 6946 top_smin_value = ((u64)reg->smin_value >> num_bits) << num_bits; 6947 6948 if (top_smax_value != top_smin_value) 6949 goto out; 6950 6951 /* find the s64_min and s64_min after sign extension */ 6952 if (size == 1) { 6953 init_s64_max = (s8)reg->smax_value; 6954 init_s64_min = (s8)reg->smin_value; 6955 } else if (size == 2) { 6956 init_s64_max = (s16)reg->smax_value; 6957 init_s64_min = (s16)reg->smin_value; 6958 } else { 6959 init_s64_max = (s32)reg->smax_value; 6960 init_s64_min = (s32)reg->smin_value; 6961 } 6962 6963 s64_max = max(init_s64_max, init_s64_min); 6964 s64_min = min(init_s64_max, init_s64_min); 6965 6966 /* both of s64_max/s64_min positive or negative */ 6967 if ((s64_max >= 0) == (s64_min >= 0)) { 6968 reg->s32_min_value = reg->smin_value = s64_min; 6969 reg->s32_max_value = reg->smax_value = s64_max; 6970 reg->u32_min_value = reg->umin_value = s64_min; 6971 reg->u32_max_value = reg->umax_value = s64_max; 6972 reg->var_off = tnum_range(s64_min, s64_max); 6973 return; 6974 } 6975 6976 out: 6977 set_sext64_default_val(reg, size); 6978 } 6979 6980 static void set_sext32_default_val(struct bpf_reg_state *reg, int size) 6981 { 6982 if (size == 1) { 6983 reg->s32_min_value = S8_MIN; 6984 reg->s32_max_value = S8_MAX; 6985 } else { 6986 /* size == 2 */ 6987 reg->s32_min_value = S16_MIN; 6988 reg->s32_max_value = S16_MAX; 6989 } 6990 reg->u32_min_value = 0; 6991 reg->u32_max_value = U32_MAX; 6992 reg->var_off = tnum_subreg(tnum_unknown); 6993 } 6994 6995 static void coerce_subreg_to_size_sx(struct bpf_reg_state *reg, int size) 6996 { 6997 s32 init_s32_max, init_s32_min, s32_max, s32_min, u32_val; 6998 u32 top_smax_value, top_smin_value; 6999 u32 num_bits = size * 8; 7000 7001 if (tnum_is_const(reg->var_off)) { 7002 u32_val = reg->var_off.value; 7003 if (size == 1) 7004 reg->var_off = tnum_const((s8)u32_val); 7005 else 7006 reg->var_off = tnum_const((s16)u32_val); 7007 7008 u32_val = reg->var_off.value; 7009 reg->s32_min_value = reg->s32_max_value = u32_val; 7010 reg->u32_min_value = reg->u32_max_value = u32_val; 7011 return; 7012 } 7013 7014 top_smax_value = ((u32)reg->s32_max_value >> num_bits) << num_bits; 7015 top_smin_value = ((u32)reg->s32_min_value >> num_bits) << num_bits; 7016 7017 if (top_smax_value != top_smin_value) 7018 goto out; 7019 7020 /* find the s32_min and s32_min after sign extension */ 7021 if (size == 1) { 7022 init_s32_max = (s8)reg->s32_max_value; 7023 init_s32_min = (s8)reg->s32_min_value; 7024 } else { 7025 /* size == 2 */ 7026 init_s32_max = (s16)reg->s32_max_value; 7027 init_s32_min = (s16)reg->s32_min_value; 7028 } 7029 s32_max = max(init_s32_max, init_s32_min); 7030 s32_min = min(init_s32_max, init_s32_min); 7031 7032 if ((s32_min >= 0) == (s32_max >= 0)) { 7033 reg->s32_min_value = s32_min; 7034 reg->s32_max_value = s32_max; 7035 reg->u32_min_value = (u32)s32_min; 7036 reg->u32_max_value = (u32)s32_max; 7037 reg->var_off = tnum_subreg(tnum_range(s32_min, s32_max)); 7038 return; 7039 } 7040 7041 out: 7042 set_sext32_default_val(reg, size); 7043 } 7044 7045 static bool bpf_map_is_rdonly(const struct bpf_map *map) 7046 { 7047 /* A map is considered read-only if the following condition are true: 7048 * 7049 * 1) BPF program side cannot change any of the map content. The 7050 * BPF_F_RDONLY_PROG flag is throughout the lifetime of a map 7051 * and was set at map creation time. 7052 * 2) The map value(s) have been initialized from user space by a 7053 * loader and then "frozen", such that no new map update/delete 7054 * operations from syscall side are possible for the rest of 7055 * the map's lifetime from that point onwards. 7056 * 3) Any parallel/pending map update/delete operations from syscall 7057 * side have been completed. Only after that point, it's safe to 7058 * assume that map value(s) are immutable. 7059 */ 7060 return (map->map_flags & BPF_F_RDONLY_PROG) && 7061 READ_ONCE(map->frozen) && 7062 !bpf_map_write_active(map); 7063 } 7064 7065 static int bpf_map_direct_read(struct bpf_map *map, int off, int size, u64 *val, 7066 bool is_ldsx) 7067 { 7068 void *ptr; 7069 u64 addr; 7070 int err; 7071 7072 err = map->ops->map_direct_value_addr(map, &addr, off); 7073 if (err) 7074 return err; 7075 ptr = (void *)(long)addr + off; 7076 7077 switch (size) { 7078 case sizeof(u8): 7079 *val = is_ldsx ? (s64)*(s8 *)ptr : (u64)*(u8 *)ptr; 7080 break; 7081 case sizeof(u16): 7082 *val = is_ldsx ? (s64)*(s16 *)ptr : (u64)*(u16 *)ptr; 7083 break; 7084 case sizeof(u32): 7085 *val = is_ldsx ? (s64)*(s32 *)ptr : (u64)*(u32 *)ptr; 7086 break; 7087 case sizeof(u64): 7088 *val = *(u64 *)ptr; 7089 break; 7090 default: 7091 return -EINVAL; 7092 } 7093 return 0; 7094 } 7095 7096 #define BTF_TYPE_SAFE_RCU(__type) __PASTE(__type, __safe_rcu) 7097 #define BTF_TYPE_SAFE_RCU_OR_NULL(__type) __PASTE(__type, __safe_rcu_or_null) 7098 #define BTF_TYPE_SAFE_TRUSTED(__type) __PASTE(__type, __safe_trusted) 7099 #define BTF_TYPE_SAFE_TRUSTED_OR_NULL(__type) __PASTE(__type, __safe_trusted_or_null) 7100 7101 /* 7102 * Allow list few fields as RCU trusted or full trusted. 7103 * This logic doesn't allow mix tagging and will be removed once GCC supports 7104 * btf_type_tag. 7105 */ 7106 7107 /* RCU trusted: these fields are trusted in RCU CS and never NULL */ 7108 BTF_TYPE_SAFE_RCU(struct task_struct) { 7109 const cpumask_t *cpus_ptr; 7110 struct css_set __rcu *cgroups; 7111 struct task_struct __rcu *real_parent; 7112 struct task_struct *group_leader; 7113 }; 7114 7115 BTF_TYPE_SAFE_RCU(struct cgroup) { 7116 /* cgrp->kn is always accessible as documented in kernel/cgroup/cgroup.c */ 7117 struct kernfs_node *kn; 7118 }; 7119 7120 BTF_TYPE_SAFE_RCU(struct css_set) { 7121 struct cgroup *dfl_cgrp; 7122 }; 7123 7124 BTF_TYPE_SAFE_RCU(struct cgroup_subsys_state) { 7125 struct cgroup *cgroup; 7126 }; 7127 7128 /* RCU trusted: these fields are trusted in RCU CS and can be NULL */ 7129 BTF_TYPE_SAFE_RCU_OR_NULL(struct mm_struct) { 7130 struct file __rcu *exe_file; 7131 }; 7132 7133 /* skb->sk, req->sk are not RCU protected, but we mark them as such 7134 * because bpf prog accessible sockets are SOCK_RCU_FREE. 7135 */ 7136 BTF_TYPE_SAFE_RCU_OR_NULL(struct sk_buff) { 7137 struct sock *sk; 7138 }; 7139 7140 BTF_TYPE_SAFE_RCU_OR_NULL(struct request_sock) { 7141 struct sock *sk; 7142 }; 7143 7144 /* full trusted: these fields are trusted even outside of RCU CS and never NULL */ 7145 BTF_TYPE_SAFE_TRUSTED(struct bpf_iter_meta) { 7146 struct seq_file *seq; 7147 }; 7148 7149 BTF_TYPE_SAFE_TRUSTED(struct bpf_iter__task) { 7150 struct bpf_iter_meta *meta; 7151 struct task_struct *task; 7152 }; 7153 7154 BTF_TYPE_SAFE_TRUSTED(struct linux_binprm) { 7155 struct file *file; 7156 }; 7157 7158 BTF_TYPE_SAFE_TRUSTED(struct file) { 7159 struct inode *f_inode; 7160 }; 7161 7162 BTF_TYPE_SAFE_TRUSTED_OR_NULL(struct dentry) { 7163 struct inode *d_inode; 7164 }; 7165 7166 BTF_TYPE_SAFE_TRUSTED_OR_NULL(struct socket) { 7167 struct sock *sk; 7168 }; 7169 7170 static bool type_is_rcu(struct bpf_verifier_env *env, 7171 struct bpf_reg_state *reg, 7172 const char *field_name, u32 btf_id) 7173 { 7174 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct task_struct)); 7175 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct cgroup)); 7176 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct css_set)); 7177 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct cgroup_subsys_state)); 7178 7179 return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_rcu"); 7180 } 7181 7182 static bool type_is_rcu_or_null(struct bpf_verifier_env *env, 7183 struct bpf_reg_state *reg, 7184 const char *field_name, u32 btf_id) 7185 { 7186 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct mm_struct)); 7187 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct sk_buff)); 7188 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct request_sock)); 7189 7190 return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_rcu_or_null"); 7191 } 7192 7193 static bool type_is_trusted(struct bpf_verifier_env *env, 7194 struct bpf_reg_state *reg, 7195 const char *field_name, u32 btf_id) 7196 { 7197 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct bpf_iter_meta)); 7198 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct bpf_iter__task)); 7199 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct linux_binprm)); 7200 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct file)); 7201 7202 return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_trusted"); 7203 } 7204 7205 static bool type_is_trusted_or_null(struct bpf_verifier_env *env, 7206 struct bpf_reg_state *reg, 7207 const char *field_name, u32 btf_id) 7208 { 7209 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED_OR_NULL(struct socket)); 7210 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED_OR_NULL(struct dentry)); 7211 7212 return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, 7213 "__safe_trusted_or_null"); 7214 } 7215 7216 static int check_ptr_to_btf_access(struct bpf_verifier_env *env, 7217 struct bpf_reg_state *regs, 7218 int regno, int off, int size, 7219 enum bpf_access_type atype, 7220 int value_regno) 7221 { 7222 struct bpf_reg_state *reg = regs + regno; 7223 const struct btf_type *t = btf_type_by_id(reg->btf, reg->btf_id); 7224 const char *tname = btf_name_by_offset(reg->btf, t->name_off); 7225 const char *field_name = NULL; 7226 enum bpf_type_flag flag = 0; 7227 u32 btf_id = 0; 7228 int ret; 7229 7230 if (!env->allow_ptr_leaks) { 7231 verbose(env, 7232 "'struct %s' access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n", 7233 tname); 7234 return -EPERM; 7235 } 7236 if (!env->prog->gpl_compatible && btf_is_kernel(reg->btf)) { 7237 verbose(env, 7238 "Cannot access kernel 'struct %s' from non-GPL compatible program\n", 7239 tname); 7240 return -EINVAL; 7241 } 7242 if (off < 0) { 7243 verbose(env, 7244 "R%d is ptr_%s invalid negative access: off=%d\n", 7245 regno, tname, off); 7246 return -EACCES; 7247 } 7248 if (!tnum_is_const(reg->var_off) || reg->var_off.value) { 7249 char tn_buf[48]; 7250 7251 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 7252 verbose(env, 7253 "R%d is ptr_%s invalid variable offset: off=%d, var_off=%s\n", 7254 regno, tname, off, tn_buf); 7255 return -EACCES; 7256 } 7257 7258 if (reg->type & MEM_USER) { 7259 verbose(env, 7260 "R%d is ptr_%s access user memory: off=%d\n", 7261 regno, tname, off); 7262 return -EACCES; 7263 } 7264 7265 if (reg->type & MEM_PERCPU) { 7266 verbose(env, 7267 "R%d is ptr_%s access percpu memory: off=%d\n", 7268 regno, tname, off); 7269 return -EACCES; 7270 } 7271 7272 if (env->ops->btf_struct_access && !type_is_alloc(reg->type) && atype == BPF_WRITE) { 7273 if (!btf_is_kernel(reg->btf)) { 7274 verifier_bug(env, "reg->btf must be kernel btf"); 7275 return -EFAULT; 7276 } 7277 ret = env->ops->btf_struct_access(&env->log, reg, off, size); 7278 } else { 7279 /* Writes are permitted with default btf_struct_access for 7280 * program allocated objects (which always have ref_obj_id > 0), 7281 * but not for untrusted PTR_TO_BTF_ID | MEM_ALLOC. 7282 */ 7283 if (atype != BPF_READ && !type_is_ptr_alloc_obj(reg->type)) { 7284 verbose(env, "only read is supported\n"); 7285 return -EACCES; 7286 } 7287 7288 if (type_is_alloc(reg->type) && !type_is_non_owning_ref(reg->type) && 7289 !(reg->type & MEM_RCU) && !reg->ref_obj_id) { 7290 verifier_bug(env, "ref_obj_id for allocated object must be non-zero"); 7291 return -EFAULT; 7292 } 7293 7294 ret = btf_struct_access(&env->log, reg, off, size, atype, &btf_id, &flag, &field_name); 7295 } 7296 7297 if (ret < 0) 7298 return ret; 7299 7300 if (ret != PTR_TO_BTF_ID) { 7301 /* just mark; */ 7302 7303 } else if (type_flag(reg->type) & PTR_UNTRUSTED) { 7304 /* If this is an untrusted pointer, all pointers formed by walking it 7305 * also inherit the untrusted flag. 7306 */ 7307 flag = PTR_UNTRUSTED; 7308 7309 } else if (is_trusted_reg(reg) || is_rcu_reg(reg)) { 7310 /* By default any pointer obtained from walking a trusted pointer is no 7311 * longer trusted, unless the field being accessed has explicitly been 7312 * marked as inheriting its parent's state of trust (either full or RCU). 7313 * For example: 7314 * 'cgroups' pointer is untrusted if task->cgroups dereference 7315 * happened in a sleepable program outside of bpf_rcu_read_lock() 7316 * section. In a non-sleepable program it's trusted while in RCU CS (aka MEM_RCU). 7317 * Note bpf_rcu_read_unlock() converts MEM_RCU pointers to PTR_UNTRUSTED. 7318 * 7319 * A regular RCU-protected pointer with __rcu tag can also be deemed 7320 * trusted if we are in an RCU CS. Such pointer can be NULL. 7321 */ 7322 if (type_is_trusted(env, reg, field_name, btf_id)) { 7323 flag |= PTR_TRUSTED; 7324 } else if (type_is_trusted_or_null(env, reg, field_name, btf_id)) { 7325 flag |= PTR_TRUSTED | PTR_MAYBE_NULL; 7326 } else if (in_rcu_cs(env) && !type_may_be_null(reg->type)) { 7327 if (type_is_rcu(env, reg, field_name, btf_id)) { 7328 /* ignore __rcu tag and mark it MEM_RCU */ 7329 flag |= MEM_RCU; 7330 } else if (flag & MEM_RCU || 7331 type_is_rcu_or_null(env, reg, field_name, btf_id)) { 7332 /* __rcu tagged pointers can be NULL */ 7333 flag |= MEM_RCU | PTR_MAYBE_NULL; 7334 7335 /* We always trust them */ 7336 if (type_is_rcu_or_null(env, reg, field_name, btf_id) && 7337 flag & PTR_UNTRUSTED) 7338 flag &= ~PTR_UNTRUSTED; 7339 } else if (flag & (MEM_PERCPU | MEM_USER)) { 7340 /* keep as-is */ 7341 } else { 7342 /* walking unknown pointers yields old deprecated PTR_TO_BTF_ID */ 7343 clear_trusted_flags(&flag); 7344 } 7345 } else { 7346 /* 7347 * If not in RCU CS or MEM_RCU pointer can be NULL then 7348 * aggressively mark as untrusted otherwise such 7349 * pointers will be plain PTR_TO_BTF_ID without flags 7350 * and will be allowed to be passed into helpers for 7351 * compat reasons. 7352 */ 7353 flag = PTR_UNTRUSTED; 7354 } 7355 } else { 7356 /* Old compat. Deprecated */ 7357 clear_trusted_flags(&flag); 7358 } 7359 7360 if (atype == BPF_READ && value_regno >= 0) { 7361 ret = mark_btf_ld_reg(env, regs, value_regno, ret, reg->btf, btf_id, flag); 7362 if (ret < 0) 7363 return ret; 7364 } 7365 7366 return 0; 7367 } 7368 7369 static int check_ptr_to_map_access(struct bpf_verifier_env *env, 7370 struct bpf_reg_state *regs, 7371 int regno, int off, int size, 7372 enum bpf_access_type atype, 7373 int value_regno) 7374 { 7375 struct bpf_reg_state *reg = regs + regno; 7376 struct bpf_map *map = reg->map_ptr; 7377 struct bpf_reg_state map_reg; 7378 enum bpf_type_flag flag = 0; 7379 const struct btf_type *t; 7380 const char *tname; 7381 u32 btf_id; 7382 int ret; 7383 7384 if (!btf_vmlinux) { 7385 verbose(env, "map_ptr access not supported without CONFIG_DEBUG_INFO_BTF\n"); 7386 return -ENOTSUPP; 7387 } 7388 7389 if (!map->ops->map_btf_id || !*map->ops->map_btf_id) { 7390 verbose(env, "map_ptr access not supported for map type %d\n", 7391 map->map_type); 7392 return -ENOTSUPP; 7393 } 7394 7395 t = btf_type_by_id(btf_vmlinux, *map->ops->map_btf_id); 7396 tname = btf_name_by_offset(btf_vmlinux, t->name_off); 7397 7398 if (!env->allow_ptr_leaks) { 7399 verbose(env, 7400 "'struct %s' access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n", 7401 tname); 7402 return -EPERM; 7403 } 7404 7405 if (off < 0) { 7406 verbose(env, "R%d is %s invalid negative access: off=%d\n", 7407 regno, tname, off); 7408 return -EACCES; 7409 } 7410 7411 if (atype != BPF_READ) { 7412 verbose(env, "only read from %s is supported\n", tname); 7413 return -EACCES; 7414 } 7415 7416 /* Simulate access to a PTR_TO_BTF_ID */ 7417 memset(&map_reg, 0, sizeof(map_reg)); 7418 ret = mark_btf_ld_reg(env, &map_reg, 0, PTR_TO_BTF_ID, 7419 btf_vmlinux, *map->ops->map_btf_id, 0); 7420 if (ret < 0) 7421 return ret; 7422 ret = btf_struct_access(&env->log, &map_reg, off, size, atype, &btf_id, &flag, NULL); 7423 if (ret < 0) 7424 return ret; 7425 7426 if (value_regno >= 0) { 7427 ret = mark_btf_ld_reg(env, regs, value_regno, ret, btf_vmlinux, btf_id, flag); 7428 if (ret < 0) 7429 return ret; 7430 } 7431 7432 return 0; 7433 } 7434 7435 /* Check that the stack access at the given offset is within bounds. The 7436 * maximum valid offset is -1. 7437 * 7438 * The minimum valid offset is -MAX_BPF_STACK for writes, and 7439 * -state->allocated_stack for reads. 7440 */ 7441 static int check_stack_slot_within_bounds(struct bpf_verifier_env *env, 7442 s64 off, 7443 struct bpf_func_state *state, 7444 enum bpf_access_type t) 7445 { 7446 int min_valid_off; 7447 7448 if (t == BPF_WRITE || env->allow_uninit_stack) 7449 min_valid_off = -MAX_BPF_STACK; 7450 else 7451 min_valid_off = -state->allocated_stack; 7452 7453 if (off < min_valid_off || off > -1) 7454 return -EACCES; 7455 return 0; 7456 } 7457 7458 /* Check that the stack access at 'regno + off' falls within the maximum stack 7459 * bounds. 7460 * 7461 * 'off' includes `regno->offset`, but not its dynamic part (if any). 7462 */ 7463 static int check_stack_access_within_bounds( 7464 struct bpf_verifier_env *env, 7465 int regno, int off, int access_size, 7466 enum bpf_access_type type) 7467 { 7468 struct bpf_reg_state *regs = cur_regs(env); 7469 struct bpf_reg_state *reg = regs + regno; 7470 struct bpf_func_state *state = func(env, reg); 7471 s64 min_off, max_off; 7472 int err; 7473 char *err_extra; 7474 7475 if (type == BPF_READ) 7476 err_extra = " read from"; 7477 else 7478 err_extra = " write to"; 7479 7480 if (tnum_is_const(reg->var_off)) { 7481 min_off = (s64)reg->var_off.value + off; 7482 max_off = min_off + access_size; 7483 } else { 7484 if (reg->smax_value >= BPF_MAX_VAR_OFF || 7485 reg->smin_value <= -BPF_MAX_VAR_OFF) { 7486 verbose(env, "invalid unbounded variable-offset%s stack R%d\n", 7487 err_extra, regno); 7488 return -EACCES; 7489 } 7490 min_off = reg->smin_value + off; 7491 max_off = reg->smax_value + off + access_size; 7492 } 7493 7494 err = check_stack_slot_within_bounds(env, min_off, state, type); 7495 if (!err && max_off > 0) 7496 err = -EINVAL; /* out of stack access into non-negative offsets */ 7497 if (!err && access_size < 0) 7498 /* access_size should not be negative (or overflow an int); others checks 7499 * along the way should have prevented such an access. 7500 */ 7501 err = -EFAULT; /* invalid negative access size; integer overflow? */ 7502 7503 if (err) { 7504 if (tnum_is_const(reg->var_off)) { 7505 verbose(env, "invalid%s stack R%d off=%d size=%d\n", 7506 err_extra, regno, off, access_size); 7507 } else { 7508 char tn_buf[48]; 7509 7510 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 7511 verbose(env, "invalid variable-offset%s stack R%d var_off=%s off=%d size=%d\n", 7512 err_extra, regno, tn_buf, off, access_size); 7513 } 7514 return err; 7515 } 7516 7517 /* Note that there is no stack access with offset zero, so the needed stack 7518 * size is -min_off, not -min_off+1. 7519 */ 7520 return grow_stack_state(env, state, -min_off /* size */); 7521 } 7522 7523 static bool get_func_retval_range(struct bpf_prog *prog, 7524 struct bpf_retval_range *range) 7525 { 7526 if (prog->type == BPF_PROG_TYPE_LSM && 7527 prog->expected_attach_type == BPF_LSM_MAC && 7528 !bpf_lsm_get_retval_range(prog, range)) { 7529 return true; 7530 } 7531 return false; 7532 } 7533 7534 /* check whether memory at (regno + off) is accessible for t = (read | write) 7535 * if t==write, value_regno is a register which value is stored into memory 7536 * if t==read, value_regno is a register which will receive the value from memory 7537 * if t==write && value_regno==-1, some unknown value is stored into memory 7538 * if t==read && value_regno==-1, don't care what we read from memory 7539 */ 7540 static int check_mem_access(struct bpf_verifier_env *env, int insn_idx, u32 regno, 7541 int off, int bpf_size, enum bpf_access_type t, 7542 int value_regno, bool strict_alignment_once, bool is_ldsx) 7543 { 7544 struct bpf_reg_state *regs = cur_regs(env); 7545 struct bpf_reg_state *reg = regs + regno; 7546 int size, err = 0; 7547 7548 size = bpf_size_to_bytes(bpf_size); 7549 if (size < 0) 7550 return size; 7551 7552 /* alignment checks will add in reg->off themselves */ 7553 err = check_ptr_alignment(env, reg, off, size, strict_alignment_once); 7554 if (err) 7555 return err; 7556 7557 /* for access checks, reg->off is just part of off */ 7558 off += reg->off; 7559 7560 if (reg->type == PTR_TO_MAP_KEY) { 7561 if (t == BPF_WRITE) { 7562 verbose(env, "write to change key R%d not allowed\n", regno); 7563 return -EACCES; 7564 } 7565 7566 err = check_mem_region_access(env, regno, off, size, 7567 reg->map_ptr->key_size, false); 7568 if (err) 7569 return err; 7570 if (value_regno >= 0) 7571 mark_reg_unknown(env, regs, value_regno); 7572 } else if (reg->type == PTR_TO_MAP_VALUE) { 7573 struct btf_field *kptr_field = NULL; 7574 7575 if (t == BPF_WRITE && value_regno >= 0 && 7576 is_pointer_value(env, value_regno)) { 7577 verbose(env, "R%d leaks addr into map\n", value_regno); 7578 return -EACCES; 7579 } 7580 err = check_map_access_type(env, regno, off, size, t); 7581 if (err) 7582 return err; 7583 err = check_map_access(env, regno, off, size, false, ACCESS_DIRECT); 7584 if (err) 7585 return err; 7586 if (tnum_is_const(reg->var_off)) 7587 kptr_field = btf_record_find(reg->map_ptr->record, 7588 off + reg->var_off.value, BPF_KPTR | BPF_UPTR); 7589 if (kptr_field) { 7590 err = check_map_kptr_access(env, regno, value_regno, insn_idx, kptr_field); 7591 } else if (t == BPF_READ && value_regno >= 0) { 7592 struct bpf_map *map = reg->map_ptr; 7593 7594 /* if map is read-only, track its contents as scalars */ 7595 if (tnum_is_const(reg->var_off) && 7596 bpf_map_is_rdonly(map) && 7597 map->ops->map_direct_value_addr) { 7598 int map_off = off + reg->var_off.value; 7599 u64 val = 0; 7600 7601 err = bpf_map_direct_read(map, map_off, size, 7602 &val, is_ldsx); 7603 if (err) 7604 return err; 7605 7606 regs[value_regno].type = SCALAR_VALUE; 7607 __mark_reg_known(®s[value_regno], val); 7608 } else { 7609 mark_reg_unknown(env, regs, value_regno); 7610 } 7611 } 7612 } else if (base_type(reg->type) == PTR_TO_MEM) { 7613 bool rdonly_mem = type_is_rdonly_mem(reg->type); 7614 bool rdonly_untrusted = rdonly_mem && (reg->type & PTR_UNTRUSTED); 7615 7616 if (type_may_be_null(reg->type)) { 7617 verbose(env, "R%d invalid mem access '%s'\n", regno, 7618 reg_type_str(env, reg->type)); 7619 return -EACCES; 7620 } 7621 7622 if (t == BPF_WRITE && rdonly_mem) { 7623 verbose(env, "R%d cannot write into %s\n", 7624 regno, reg_type_str(env, reg->type)); 7625 return -EACCES; 7626 } 7627 7628 if (t == BPF_WRITE && value_regno >= 0 && 7629 is_pointer_value(env, value_regno)) { 7630 verbose(env, "R%d leaks addr into mem\n", value_regno); 7631 return -EACCES; 7632 } 7633 7634 /* 7635 * Accesses to untrusted PTR_TO_MEM are done through probe 7636 * instructions, hence no need to check bounds in that case. 7637 */ 7638 if (!rdonly_untrusted) 7639 err = check_mem_region_access(env, regno, off, size, 7640 reg->mem_size, false); 7641 if (!err && value_regno >= 0 && (t == BPF_READ || rdonly_mem)) 7642 mark_reg_unknown(env, regs, value_regno); 7643 } else if (reg->type == PTR_TO_CTX) { 7644 struct bpf_retval_range range; 7645 struct bpf_insn_access_aux info = { 7646 .reg_type = SCALAR_VALUE, 7647 .is_ldsx = is_ldsx, 7648 .log = &env->log, 7649 }; 7650 7651 if (t == BPF_WRITE && value_regno >= 0 && 7652 is_pointer_value(env, value_regno)) { 7653 verbose(env, "R%d leaks addr into ctx\n", value_regno); 7654 return -EACCES; 7655 } 7656 7657 err = check_ptr_off_reg(env, reg, regno); 7658 if (err < 0) 7659 return err; 7660 7661 err = check_ctx_access(env, insn_idx, off, size, t, &info); 7662 if (err) 7663 verbose_linfo(env, insn_idx, "; "); 7664 if (!err && t == BPF_READ && value_regno >= 0) { 7665 /* ctx access returns either a scalar, or a 7666 * PTR_TO_PACKET[_META,_END]. In the latter 7667 * case, we know the offset is zero. 7668 */ 7669 if (info.reg_type == SCALAR_VALUE) { 7670 if (info.is_retval && get_func_retval_range(env->prog, &range)) { 7671 err = __mark_reg_s32_range(env, regs, value_regno, 7672 range.minval, range.maxval); 7673 if (err) 7674 return err; 7675 } else { 7676 mark_reg_unknown(env, regs, value_regno); 7677 } 7678 } else { 7679 mark_reg_known_zero(env, regs, 7680 value_regno); 7681 if (type_may_be_null(info.reg_type)) 7682 regs[value_regno].id = ++env->id_gen; 7683 /* A load of ctx field could have different 7684 * actual load size with the one encoded in the 7685 * insn. When the dst is PTR, it is for sure not 7686 * a sub-register. 7687 */ 7688 regs[value_regno].subreg_def = DEF_NOT_SUBREG; 7689 if (base_type(info.reg_type) == PTR_TO_BTF_ID) { 7690 regs[value_regno].btf = info.btf; 7691 regs[value_regno].btf_id = info.btf_id; 7692 regs[value_regno].ref_obj_id = info.ref_obj_id; 7693 } 7694 } 7695 regs[value_regno].type = info.reg_type; 7696 } 7697 7698 } else if (reg->type == PTR_TO_STACK) { 7699 /* Basic bounds checks. */ 7700 err = check_stack_access_within_bounds(env, regno, off, size, t); 7701 if (err) 7702 return err; 7703 7704 if (t == BPF_READ) 7705 err = check_stack_read(env, regno, off, size, 7706 value_regno); 7707 else 7708 err = check_stack_write(env, regno, off, size, 7709 value_regno, insn_idx); 7710 } else if (reg_is_pkt_pointer(reg)) { 7711 if (t == BPF_WRITE && !may_access_direct_pkt_data(env, NULL, t)) { 7712 verbose(env, "cannot write into packet\n"); 7713 return -EACCES; 7714 } 7715 if (t == BPF_WRITE && value_regno >= 0 && 7716 is_pointer_value(env, value_regno)) { 7717 verbose(env, "R%d leaks addr into packet\n", 7718 value_regno); 7719 return -EACCES; 7720 } 7721 err = check_packet_access(env, regno, off, size, false); 7722 if (!err && t == BPF_READ && value_regno >= 0) 7723 mark_reg_unknown(env, regs, value_regno); 7724 } else if (reg->type == PTR_TO_FLOW_KEYS) { 7725 if (t == BPF_WRITE && value_regno >= 0 && 7726 is_pointer_value(env, value_regno)) { 7727 verbose(env, "R%d leaks addr into flow keys\n", 7728 value_regno); 7729 return -EACCES; 7730 } 7731 7732 err = check_flow_keys_access(env, off, size); 7733 if (!err && t == BPF_READ && value_regno >= 0) 7734 mark_reg_unknown(env, regs, value_regno); 7735 } else if (type_is_sk_pointer(reg->type)) { 7736 if (t == BPF_WRITE) { 7737 verbose(env, "R%d cannot write into %s\n", 7738 regno, reg_type_str(env, reg->type)); 7739 return -EACCES; 7740 } 7741 err = check_sock_access(env, insn_idx, regno, off, size, t); 7742 if (!err && value_regno >= 0) 7743 mark_reg_unknown(env, regs, value_regno); 7744 } else if (reg->type == PTR_TO_TP_BUFFER) { 7745 err = check_tp_buffer_access(env, reg, regno, off, size); 7746 if (!err && t == BPF_READ && value_regno >= 0) 7747 mark_reg_unknown(env, regs, value_regno); 7748 } else if (base_type(reg->type) == PTR_TO_BTF_ID && 7749 !type_may_be_null(reg->type)) { 7750 err = check_ptr_to_btf_access(env, regs, regno, off, size, t, 7751 value_regno); 7752 } else if (reg->type == CONST_PTR_TO_MAP) { 7753 err = check_ptr_to_map_access(env, regs, regno, off, size, t, 7754 value_regno); 7755 } else if (base_type(reg->type) == PTR_TO_BUF) { 7756 bool rdonly_mem = type_is_rdonly_mem(reg->type); 7757 u32 *max_access; 7758 7759 if (rdonly_mem) { 7760 if (t == BPF_WRITE) { 7761 verbose(env, "R%d cannot write into %s\n", 7762 regno, reg_type_str(env, reg->type)); 7763 return -EACCES; 7764 } 7765 max_access = &env->prog->aux->max_rdonly_access; 7766 } else { 7767 max_access = &env->prog->aux->max_rdwr_access; 7768 } 7769 7770 err = check_buffer_access(env, reg, regno, off, size, false, 7771 max_access); 7772 7773 if (!err && value_regno >= 0 && (rdonly_mem || t == BPF_READ)) 7774 mark_reg_unknown(env, regs, value_regno); 7775 } else if (reg->type == PTR_TO_ARENA) { 7776 if (t == BPF_READ && value_regno >= 0) 7777 mark_reg_unknown(env, regs, value_regno); 7778 } else { 7779 verbose(env, "R%d invalid mem access '%s'\n", regno, 7780 reg_type_str(env, reg->type)); 7781 return -EACCES; 7782 } 7783 7784 if (!err && size < BPF_REG_SIZE && value_regno >= 0 && t == BPF_READ && 7785 regs[value_regno].type == SCALAR_VALUE) { 7786 if (!is_ldsx) 7787 /* b/h/w load zero-extends, mark upper bits as known 0 */ 7788 coerce_reg_to_size(®s[value_regno], size); 7789 else 7790 coerce_reg_to_size_sx(®s[value_regno], size); 7791 } 7792 return err; 7793 } 7794 7795 static int save_aux_ptr_type(struct bpf_verifier_env *env, enum bpf_reg_type type, 7796 bool allow_trust_mismatch); 7797 7798 static int check_load_mem(struct bpf_verifier_env *env, struct bpf_insn *insn, 7799 bool strict_alignment_once, bool is_ldsx, 7800 bool allow_trust_mismatch, const char *ctx) 7801 { 7802 struct bpf_reg_state *regs = cur_regs(env); 7803 enum bpf_reg_type src_reg_type; 7804 int err; 7805 7806 /* check src operand */ 7807 err = check_reg_arg(env, insn->src_reg, SRC_OP); 7808 if (err) 7809 return err; 7810 7811 /* check dst operand */ 7812 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK); 7813 if (err) 7814 return err; 7815 7816 src_reg_type = regs[insn->src_reg].type; 7817 7818 /* Check if (src_reg + off) is readable. The state of dst_reg will be 7819 * updated by this call. 7820 */ 7821 err = check_mem_access(env, env->insn_idx, insn->src_reg, insn->off, 7822 BPF_SIZE(insn->code), BPF_READ, insn->dst_reg, 7823 strict_alignment_once, is_ldsx); 7824 err = err ?: save_aux_ptr_type(env, src_reg_type, 7825 allow_trust_mismatch); 7826 err = err ?: reg_bounds_sanity_check(env, ®s[insn->dst_reg], ctx); 7827 7828 return err; 7829 } 7830 7831 static int check_store_reg(struct bpf_verifier_env *env, struct bpf_insn *insn, 7832 bool strict_alignment_once) 7833 { 7834 struct bpf_reg_state *regs = cur_regs(env); 7835 enum bpf_reg_type dst_reg_type; 7836 int err; 7837 7838 /* check src1 operand */ 7839 err = check_reg_arg(env, insn->src_reg, SRC_OP); 7840 if (err) 7841 return err; 7842 7843 /* check src2 operand */ 7844 err = check_reg_arg(env, insn->dst_reg, SRC_OP); 7845 if (err) 7846 return err; 7847 7848 dst_reg_type = regs[insn->dst_reg].type; 7849 7850 /* Check if (dst_reg + off) is writeable. */ 7851 err = check_mem_access(env, env->insn_idx, insn->dst_reg, insn->off, 7852 BPF_SIZE(insn->code), BPF_WRITE, insn->src_reg, 7853 strict_alignment_once, false); 7854 err = err ?: save_aux_ptr_type(env, dst_reg_type, false); 7855 7856 return err; 7857 } 7858 7859 static int check_atomic_rmw(struct bpf_verifier_env *env, 7860 struct bpf_insn *insn) 7861 { 7862 int load_reg; 7863 int err; 7864 7865 if (BPF_SIZE(insn->code) != BPF_W && BPF_SIZE(insn->code) != BPF_DW) { 7866 verbose(env, "invalid atomic operand size\n"); 7867 return -EINVAL; 7868 } 7869 7870 /* check src1 operand */ 7871 err = check_reg_arg(env, insn->src_reg, SRC_OP); 7872 if (err) 7873 return err; 7874 7875 /* check src2 operand */ 7876 err = check_reg_arg(env, insn->dst_reg, SRC_OP); 7877 if (err) 7878 return err; 7879 7880 if (insn->imm == BPF_CMPXCHG) { 7881 /* Check comparison of R0 with memory location */ 7882 const u32 aux_reg = BPF_REG_0; 7883 7884 err = check_reg_arg(env, aux_reg, SRC_OP); 7885 if (err) 7886 return err; 7887 7888 if (is_pointer_value(env, aux_reg)) { 7889 verbose(env, "R%d leaks addr into mem\n", aux_reg); 7890 return -EACCES; 7891 } 7892 } 7893 7894 if (is_pointer_value(env, insn->src_reg)) { 7895 verbose(env, "R%d leaks addr into mem\n", insn->src_reg); 7896 return -EACCES; 7897 } 7898 7899 if (!atomic_ptr_type_ok(env, insn->dst_reg, insn)) { 7900 verbose(env, "BPF_ATOMIC stores into R%d %s is not allowed\n", 7901 insn->dst_reg, 7902 reg_type_str(env, reg_state(env, insn->dst_reg)->type)); 7903 return -EACCES; 7904 } 7905 7906 if (insn->imm & BPF_FETCH) { 7907 if (insn->imm == BPF_CMPXCHG) 7908 load_reg = BPF_REG_0; 7909 else 7910 load_reg = insn->src_reg; 7911 7912 /* check and record load of old value */ 7913 err = check_reg_arg(env, load_reg, DST_OP); 7914 if (err) 7915 return err; 7916 } else { 7917 /* This instruction accesses a memory location but doesn't 7918 * actually load it into a register. 7919 */ 7920 load_reg = -1; 7921 } 7922 7923 /* Check whether we can read the memory, with second call for fetch 7924 * case to simulate the register fill. 7925 */ 7926 err = check_mem_access(env, env->insn_idx, insn->dst_reg, insn->off, 7927 BPF_SIZE(insn->code), BPF_READ, -1, true, false); 7928 if (!err && load_reg >= 0) 7929 err = check_mem_access(env, env->insn_idx, insn->dst_reg, 7930 insn->off, BPF_SIZE(insn->code), 7931 BPF_READ, load_reg, true, false); 7932 if (err) 7933 return err; 7934 7935 if (is_arena_reg(env, insn->dst_reg)) { 7936 err = save_aux_ptr_type(env, PTR_TO_ARENA, false); 7937 if (err) 7938 return err; 7939 } 7940 /* Check whether we can write into the same memory. */ 7941 err = check_mem_access(env, env->insn_idx, insn->dst_reg, insn->off, 7942 BPF_SIZE(insn->code), BPF_WRITE, -1, true, false); 7943 if (err) 7944 return err; 7945 return 0; 7946 } 7947 7948 static int check_atomic_load(struct bpf_verifier_env *env, 7949 struct bpf_insn *insn) 7950 { 7951 int err; 7952 7953 err = check_load_mem(env, insn, true, false, false, "atomic_load"); 7954 if (err) 7955 return err; 7956 7957 if (!atomic_ptr_type_ok(env, insn->src_reg, insn)) { 7958 verbose(env, "BPF_ATOMIC loads from R%d %s is not allowed\n", 7959 insn->src_reg, 7960 reg_type_str(env, reg_state(env, insn->src_reg)->type)); 7961 return -EACCES; 7962 } 7963 7964 return 0; 7965 } 7966 7967 static int check_atomic_store(struct bpf_verifier_env *env, 7968 struct bpf_insn *insn) 7969 { 7970 int err; 7971 7972 err = check_store_reg(env, insn, true); 7973 if (err) 7974 return err; 7975 7976 if (!atomic_ptr_type_ok(env, insn->dst_reg, insn)) { 7977 verbose(env, "BPF_ATOMIC stores into R%d %s is not allowed\n", 7978 insn->dst_reg, 7979 reg_type_str(env, reg_state(env, insn->dst_reg)->type)); 7980 return -EACCES; 7981 } 7982 7983 return 0; 7984 } 7985 7986 static int check_atomic(struct bpf_verifier_env *env, struct bpf_insn *insn) 7987 { 7988 switch (insn->imm) { 7989 case BPF_ADD: 7990 case BPF_ADD | BPF_FETCH: 7991 case BPF_AND: 7992 case BPF_AND | BPF_FETCH: 7993 case BPF_OR: 7994 case BPF_OR | BPF_FETCH: 7995 case BPF_XOR: 7996 case BPF_XOR | BPF_FETCH: 7997 case BPF_XCHG: 7998 case BPF_CMPXCHG: 7999 return check_atomic_rmw(env, insn); 8000 case BPF_LOAD_ACQ: 8001 if (BPF_SIZE(insn->code) == BPF_DW && BITS_PER_LONG != 64) { 8002 verbose(env, 8003 "64-bit load-acquires are only supported on 64-bit arches\n"); 8004 return -EOPNOTSUPP; 8005 } 8006 return check_atomic_load(env, insn); 8007 case BPF_STORE_REL: 8008 if (BPF_SIZE(insn->code) == BPF_DW && BITS_PER_LONG != 64) { 8009 verbose(env, 8010 "64-bit store-releases are only supported on 64-bit arches\n"); 8011 return -EOPNOTSUPP; 8012 } 8013 return check_atomic_store(env, insn); 8014 default: 8015 verbose(env, "BPF_ATOMIC uses invalid atomic opcode %02x\n", 8016 insn->imm); 8017 return -EINVAL; 8018 } 8019 } 8020 8021 /* When register 'regno' is used to read the stack (either directly or through 8022 * a helper function) make sure that it's within stack boundary and, depending 8023 * on the access type and privileges, that all elements of the stack are 8024 * initialized. 8025 * 8026 * 'off' includes 'regno->off', but not its dynamic part (if any). 8027 * 8028 * All registers that have been spilled on the stack in the slots within the 8029 * read offsets are marked as read. 8030 */ 8031 static int check_stack_range_initialized( 8032 struct bpf_verifier_env *env, int regno, int off, 8033 int access_size, bool zero_size_allowed, 8034 enum bpf_access_type type, struct bpf_call_arg_meta *meta) 8035 { 8036 struct bpf_reg_state *reg = reg_state(env, regno); 8037 struct bpf_func_state *state = func(env, reg); 8038 int err, min_off, max_off, i, j, slot, spi; 8039 /* Some accesses can write anything into the stack, others are 8040 * read-only. 8041 */ 8042 bool clobber = false; 8043 8044 if (access_size == 0 && !zero_size_allowed) { 8045 verbose(env, "invalid zero-sized read\n"); 8046 return -EACCES; 8047 } 8048 8049 if (type == BPF_WRITE) 8050 clobber = true; 8051 8052 err = check_stack_access_within_bounds(env, regno, off, access_size, type); 8053 if (err) 8054 return err; 8055 8056 8057 if (tnum_is_const(reg->var_off)) { 8058 min_off = max_off = reg->var_off.value + off; 8059 } else { 8060 /* Variable offset is prohibited for unprivileged mode for 8061 * simplicity since it requires corresponding support in 8062 * Spectre masking for stack ALU. 8063 * See also retrieve_ptr_limit(). 8064 */ 8065 if (!env->bypass_spec_v1) { 8066 char tn_buf[48]; 8067 8068 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 8069 verbose(env, "R%d variable offset stack access prohibited for !root, var_off=%s\n", 8070 regno, tn_buf); 8071 return -EACCES; 8072 } 8073 /* Only initialized buffer on stack is allowed to be accessed 8074 * with variable offset. With uninitialized buffer it's hard to 8075 * guarantee that whole memory is marked as initialized on 8076 * helper return since specific bounds are unknown what may 8077 * cause uninitialized stack leaking. 8078 */ 8079 if (meta && meta->raw_mode) 8080 meta = NULL; 8081 8082 min_off = reg->smin_value + off; 8083 max_off = reg->smax_value + off; 8084 } 8085 8086 if (meta && meta->raw_mode) { 8087 /* Ensure we won't be overwriting dynptrs when simulating byte 8088 * by byte access in check_helper_call using meta.access_size. 8089 * This would be a problem if we have a helper in the future 8090 * which takes: 8091 * 8092 * helper(uninit_mem, len, dynptr) 8093 * 8094 * Now, uninint_mem may overlap with dynptr pointer. Hence, it 8095 * may end up writing to dynptr itself when touching memory from 8096 * arg 1. This can be relaxed on a case by case basis for known 8097 * safe cases, but reject due to the possibilitiy of aliasing by 8098 * default. 8099 */ 8100 for (i = min_off; i < max_off + access_size; i++) { 8101 int stack_off = -i - 1; 8102 8103 spi = __get_spi(i); 8104 /* raw_mode may write past allocated_stack */ 8105 if (state->allocated_stack <= stack_off) 8106 continue; 8107 if (state->stack[spi].slot_type[stack_off % BPF_REG_SIZE] == STACK_DYNPTR) { 8108 verbose(env, "potential write to dynptr at off=%d disallowed\n", i); 8109 return -EACCES; 8110 } 8111 } 8112 meta->access_size = access_size; 8113 meta->regno = regno; 8114 return 0; 8115 } 8116 8117 for (i = min_off; i < max_off + access_size; i++) { 8118 u8 *stype; 8119 8120 slot = -i - 1; 8121 spi = slot / BPF_REG_SIZE; 8122 if (state->allocated_stack <= slot) { 8123 verbose(env, "allocated_stack too small\n"); 8124 return -EFAULT; 8125 } 8126 8127 stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE]; 8128 if (*stype == STACK_MISC) 8129 goto mark; 8130 if ((*stype == STACK_ZERO) || 8131 (*stype == STACK_INVALID && env->allow_uninit_stack)) { 8132 if (clobber) { 8133 /* helper can write anything into the stack */ 8134 *stype = STACK_MISC; 8135 } 8136 goto mark; 8137 } 8138 8139 if (is_spilled_reg(&state->stack[spi]) && 8140 (state->stack[spi].spilled_ptr.type == SCALAR_VALUE || 8141 env->allow_ptr_leaks)) { 8142 if (clobber) { 8143 __mark_reg_unknown(env, &state->stack[spi].spilled_ptr); 8144 for (j = 0; j < BPF_REG_SIZE; j++) 8145 scrub_spilled_slot(&state->stack[spi].slot_type[j]); 8146 } 8147 goto mark; 8148 } 8149 8150 if (tnum_is_const(reg->var_off)) { 8151 verbose(env, "invalid read from stack R%d off %d+%d size %d\n", 8152 regno, min_off, i - min_off, access_size); 8153 } else { 8154 char tn_buf[48]; 8155 8156 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 8157 verbose(env, "invalid read from stack R%d var_off %s+%d size %d\n", 8158 regno, tn_buf, i - min_off, access_size); 8159 } 8160 return -EACCES; 8161 mark: 8162 /* reading any byte out of 8-byte 'spill_slot' will cause 8163 * the whole slot to be marked as 'read' 8164 */ 8165 mark_reg_read(env, &state->stack[spi].spilled_ptr, 8166 state->stack[spi].spilled_ptr.parent, 8167 REG_LIVE_READ64); 8168 /* We do not set REG_LIVE_WRITTEN for stack slot, as we can not 8169 * be sure that whether stack slot is written to or not. Hence, 8170 * we must still conservatively propagate reads upwards even if 8171 * helper may write to the entire memory range. 8172 */ 8173 } 8174 return 0; 8175 } 8176 8177 static int check_helper_mem_access(struct bpf_verifier_env *env, int regno, 8178 int access_size, enum bpf_access_type access_type, 8179 bool zero_size_allowed, 8180 struct bpf_call_arg_meta *meta) 8181 { 8182 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno]; 8183 u32 *max_access; 8184 8185 switch (base_type(reg->type)) { 8186 case PTR_TO_PACKET: 8187 case PTR_TO_PACKET_META: 8188 return check_packet_access(env, regno, reg->off, access_size, 8189 zero_size_allowed); 8190 case PTR_TO_MAP_KEY: 8191 if (access_type == BPF_WRITE) { 8192 verbose(env, "R%d cannot write into %s\n", regno, 8193 reg_type_str(env, reg->type)); 8194 return -EACCES; 8195 } 8196 return check_mem_region_access(env, regno, reg->off, access_size, 8197 reg->map_ptr->key_size, false); 8198 case PTR_TO_MAP_VALUE: 8199 if (check_map_access_type(env, regno, reg->off, access_size, access_type)) 8200 return -EACCES; 8201 return check_map_access(env, regno, reg->off, access_size, 8202 zero_size_allowed, ACCESS_HELPER); 8203 case PTR_TO_MEM: 8204 if (type_is_rdonly_mem(reg->type)) { 8205 if (access_type == BPF_WRITE) { 8206 verbose(env, "R%d cannot write into %s\n", regno, 8207 reg_type_str(env, reg->type)); 8208 return -EACCES; 8209 } 8210 } 8211 return check_mem_region_access(env, regno, reg->off, 8212 access_size, reg->mem_size, 8213 zero_size_allowed); 8214 case PTR_TO_BUF: 8215 if (type_is_rdonly_mem(reg->type)) { 8216 if (access_type == BPF_WRITE) { 8217 verbose(env, "R%d cannot write into %s\n", regno, 8218 reg_type_str(env, reg->type)); 8219 return -EACCES; 8220 } 8221 8222 max_access = &env->prog->aux->max_rdonly_access; 8223 } else { 8224 max_access = &env->prog->aux->max_rdwr_access; 8225 } 8226 return check_buffer_access(env, reg, regno, reg->off, 8227 access_size, zero_size_allowed, 8228 max_access); 8229 case PTR_TO_STACK: 8230 return check_stack_range_initialized( 8231 env, 8232 regno, reg->off, access_size, 8233 zero_size_allowed, access_type, meta); 8234 case PTR_TO_BTF_ID: 8235 return check_ptr_to_btf_access(env, regs, regno, reg->off, 8236 access_size, BPF_READ, -1); 8237 case PTR_TO_CTX: 8238 /* in case the function doesn't know how to access the context, 8239 * (because we are in a program of type SYSCALL for example), we 8240 * can not statically check its size. 8241 * Dynamically check it now. 8242 */ 8243 if (!env->ops->convert_ctx_access) { 8244 int offset = access_size - 1; 8245 8246 /* Allow zero-byte read from PTR_TO_CTX */ 8247 if (access_size == 0) 8248 return zero_size_allowed ? 0 : -EACCES; 8249 8250 return check_mem_access(env, env->insn_idx, regno, offset, BPF_B, 8251 access_type, -1, false, false); 8252 } 8253 8254 fallthrough; 8255 default: /* scalar_value or invalid ptr */ 8256 /* Allow zero-byte read from NULL, regardless of pointer type */ 8257 if (zero_size_allowed && access_size == 0 && 8258 register_is_null(reg)) 8259 return 0; 8260 8261 verbose(env, "R%d type=%s ", regno, 8262 reg_type_str(env, reg->type)); 8263 verbose(env, "expected=%s\n", reg_type_str(env, PTR_TO_STACK)); 8264 return -EACCES; 8265 } 8266 } 8267 8268 /* verify arguments to helpers or kfuncs consisting of a pointer and an access 8269 * size. 8270 * 8271 * @regno is the register containing the access size. regno-1 is the register 8272 * containing the pointer. 8273 */ 8274 static int check_mem_size_reg(struct bpf_verifier_env *env, 8275 struct bpf_reg_state *reg, u32 regno, 8276 enum bpf_access_type access_type, 8277 bool zero_size_allowed, 8278 struct bpf_call_arg_meta *meta) 8279 { 8280 int err; 8281 8282 /* This is used to refine r0 return value bounds for helpers 8283 * that enforce this value as an upper bound on return values. 8284 * See do_refine_retval_range() for helpers that can refine 8285 * the return value. C type of helper is u32 so we pull register 8286 * bound from umax_value however, if negative verifier errors 8287 * out. Only upper bounds can be learned because retval is an 8288 * int type and negative retvals are allowed. 8289 */ 8290 meta->msize_max_value = reg->umax_value; 8291 8292 /* The register is SCALAR_VALUE; the access check happens using 8293 * its boundaries. For unprivileged variable accesses, disable 8294 * raw mode so that the program is required to initialize all 8295 * the memory that the helper could just partially fill up. 8296 */ 8297 if (!tnum_is_const(reg->var_off)) 8298 meta = NULL; 8299 8300 if (reg->smin_value < 0) { 8301 verbose(env, "R%d min value is negative, either use unsigned or 'var &= const'\n", 8302 regno); 8303 return -EACCES; 8304 } 8305 8306 if (reg->umin_value == 0 && !zero_size_allowed) { 8307 verbose(env, "R%d invalid zero-sized read: u64=[%lld,%lld]\n", 8308 regno, reg->umin_value, reg->umax_value); 8309 return -EACCES; 8310 } 8311 8312 if (reg->umax_value >= BPF_MAX_VAR_SIZ) { 8313 verbose(env, "R%d unbounded memory access, use 'var &= const' or 'if (var < const)'\n", 8314 regno); 8315 return -EACCES; 8316 } 8317 err = check_helper_mem_access(env, regno - 1, reg->umax_value, 8318 access_type, zero_size_allowed, meta); 8319 if (!err) 8320 err = mark_chain_precision(env, regno); 8321 return err; 8322 } 8323 8324 static int check_mem_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg, 8325 u32 regno, u32 mem_size) 8326 { 8327 bool may_be_null = type_may_be_null(reg->type); 8328 struct bpf_reg_state saved_reg; 8329 int err; 8330 8331 if (register_is_null(reg)) 8332 return 0; 8333 8334 /* Assuming that the register contains a value check if the memory 8335 * access is safe. Temporarily save and restore the register's state as 8336 * the conversion shouldn't be visible to a caller. 8337 */ 8338 if (may_be_null) { 8339 saved_reg = *reg; 8340 mark_ptr_not_null_reg(reg); 8341 } 8342 8343 err = check_helper_mem_access(env, regno, mem_size, BPF_READ, true, NULL); 8344 err = err ?: check_helper_mem_access(env, regno, mem_size, BPF_WRITE, true, NULL); 8345 8346 if (may_be_null) 8347 *reg = saved_reg; 8348 8349 return err; 8350 } 8351 8352 static int check_kfunc_mem_size_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg, 8353 u32 regno) 8354 { 8355 struct bpf_reg_state *mem_reg = &cur_regs(env)[regno - 1]; 8356 bool may_be_null = type_may_be_null(mem_reg->type); 8357 struct bpf_reg_state saved_reg; 8358 struct bpf_call_arg_meta meta; 8359 int err; 8360 8361 WARN_ON_ONCE(regno < BPF_REG_2 || regno > BPF_REG_5); 8362 8363 memset(&meta, 0, sizeof(meta)); 8364 8365 if (may_be_null) { 8366 saved_reg = *mem_reg; 8367 mark_ptr_not_null_reg(mem_reg); 8368 } 8369 8370 err = check_mem_size_reg(env, reg, regno, BPF_READ, true, &meta); 8371 err = err ?: check_mem_size_reg(env, reg, regno, BPF_WRITE, true, &meta); 8372 8373 if (may_be_null) 8374 *mem_reg = saved_reg; 8375 8376 return err; 8377 } 8378 8379 enum { 8380 PROCESS_SPIN_LOCK = (1 << 0), 8381 PROCESS_RES_LOCK = (1 << 1), 8382 PROCESS_LOCK_IRQ = (1 << 2), 8383 }; 8384 8385 /* Implementation details: 8386 * bpf_map_lookup returns PTR_TO_MAP_VALUE_OR_NULL. 8387 * bpf_obj_new returns PTR_TO_BTF_ID | MEM_ALLOC | PTR_MAYBE_NULL. 8388 * Two bpf_map_lookups (even with the same key) will have different reg->id. 8389 * Two separate bpf_obj_new will also have different reg->id. 8390 * For traditional PTR_TO_MAP_VALUE or PTR_TO_BTF_ID | MEM_ALLOC, the verifier 8391 * clears reg->id after value_or_null->value transition, since the verifier only 8392 * cares about the range of access to valid map value pointer and doesn't care 8393 * about actual address of the map element. 8394 * For maps with 'struct bpf_spin_lock' inside map value the verifier keeps 8395 * reg->id > 0 after value_or_null->value transition. By doing so 8396 * two bpf_map_lookups will be considered two different pointers that 8397 * point to different bpf_spin_locks. Likewise for pointers to allocated objects 8398 * returned from bpf_obj_new. 8399 * The verifier allows taking only one bpf_spin_lock at a time to avoid 8400 * dead-locks. 8401 * Since only one bpf_spin_lock is allowed the checks are simpler than 8402 * reg_is_refcounted() logic. The verifier needs to remember only 8403 * one spin_lock instead of array of acquired_refs. 8404 * env->cur_state->active_locks remembers which map value element or allocated 8405 * object got locked and clears it after bpf_spin_unlock. 8406 */ 8407 static int process_spin_lock(struct bpf_verifier_env *env, int regno, int flags) 8408 { 8409 bool is_lock = flags & PROCESS_SPIN_LOCK, is_res_lock = flags & PROCESS_RES_LOCK; 8410 const char *lock_str = is_res_lock ? "bpf_res_spin" : "bpf_spin"; 8411 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno]; 8412 struct bpf_verifier_state *cur = env->cur_state; 8413 bool is_const = tnum_is_const(reg->var_off); 8414 bool is_irq = flags & PROCESS_LOCK_IRQ; 8415 u64 val = reg->var_off.value; 8416 struct bpf_map *map = NULL; 8417 struct btf *btf = NULL; 8418 struct btf_record *rec; 8419 u32 spin_lock_off; 8420 int err; 8421 8422 if (!is_const) { 8423 verbose(env, 8424 "R%d doesn't have constant offset. %s_lock has to be at the constant offset\n", 8425 regno, lock_str); 8426 return -EINVAL; 8427 } 8428 if (reg->type == PTR_TO_MAP_VALUE) { 8429 map = reg->map_ptr; 8430 if (!map->btf) { 8431 verbose(env, 8432 "map '%s' has to have BTF in order to use %s_lock\n", 8433 map->name, lock_str); 8434 return -EINVAL; 8435 } 8436 } else { 8437 btf = reg->btf; 8438 } 8439 8440 rec = reg_btf_record(reg); 8441 if (!btf_record_has_field(rec, is_res_lock ? BPF_RES_SPIN_LOCK : BPF_SPIN_LOCK)) { 8442 verbose(env, "%s '%s' has no valid %s_lock\n", map ? "map" : "local", 8443 map ? map->name : "kptr", lock_str); 8444 return -EINVAL; 8445 } 8446 spin_lock_off = is_res_lock ? rec->res_spin_lock_off : rec->spin_lock_off; 8447 if (spin_lock_off != val + reg->off) { 8448 verbose(env, "off %lld doesn't point to 'struct %s_lock' that is at %d\n", 8449 val + reg->off, lock_str, spin_lock_off); 8450 return -EINVAL; 8451 } 8452 if (is_lock) { 8453 void *ptr; 8454 int type; 8455 8456 if (map) 8457 ptr = map; 8458 else 8459 ptr = btf; 8460 8461 if (!is_res_lock && cur->active_locks) { 8462 if (find_lock_state(env->cur_state, REF_TYPE_LOCK, 0, NULL)) { 8463 verbose(env, 8464 "Locking two bpf_spin_locks are not allowed\n"); 8465 return -EINVAL; 8466 } 8467 } else if (is_res_lock && cur->active_locks) { 8468 if (find_lock_state(env->cur_state, REF_TYPE_RES_LOCK | REF_TYPE_RES_LOCK_IRQ, reg->id, ptr)) { 8469 verbose(env, "Acquiring the same lock again, AA deadlock detected\n"); 8470 return -EINVAL; 8471 } 8472 } 8473 8474 if (is_res_lock && is_irq) 8475 type = REF_TYPE_RES_LOCK_IRQ; 8476 else if (is_res_lock) 8477 type = REF_TYPE_RES_LOCK; 8478 else 8479 type = REF_TYPE_LOCK; 8480 err = acquire_lock_state(env, env->insn_idx, type, reg->id, ptr); 8481 if (err < 0) { 8482 verbose(env, "Failed to acquire lock state\n"); 8483 return err; 8484 } 8485 } else { 8486 void *ptr; 8487 int type; 8488 8489 if (map) 8490 ptr = map; 8491 else 8492 ptr = btf; 8493 8494 if (!cur->active_locks) { 8495 verbose(env, "%s_unlock without taking a lock\n", lock_str); 8496 return -EINVAL; 8497 } 8498 8499 if (is_res_lock && is_irq) 8500 type = REF_TYPE_RES_LOCK_IRQ; 8501 else if (is_res_lock) 8502 type = REF_TYPE_RES_LOCK; 8503 else 8504 type = REF_TYPE_LOCK; 8505 if (!find_lock_state(cur, type, reg->id, ptr)) { 8506 verbose(env, "%s_unlock of different lock\n", lock_str); 8507 return -EINVAL; 8508 } 8509 if (reg->id != cur->active_lock_id || ptr != cur->active_lock_ptr) { 8510 verbose(env, "%s_unlock cannot be out of order\n", lock_str); 8511 return -EINVAL; 8512 } 8513 if (release_lock_state(cur, type, reg->id, ptr)) { 8514 verbose(env, "%s_unlock of different lock\n", lock_str); 8515 return -EINVAL; 8516 } 8517 8518 invalidate_non_owning_refs(env); 8519 } 8520 return 0; 8521 } 8522 8523 static int process_timer_func(struct bpf_verifier_env *env, int regno, 8524 struct bpf_call_arg_meta *meta) 8525 { 8526 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno]; 8527 bool is_const = tnum_is_const(reg->var_off); 8528 struct bpf_map *map = reg->map_ptr; 8529 u64 val = reg->var_off.value; 8530 8531 if (!is_const) { 8532 verbose(env, 8533 "R%d doesn't have constant offset. bpf_timer has to be at the constant offset\n", 8534 regno); 8535 return -EINVAL; 8536 } 8537 if (!map->btf) { 8538 verbose(env, "map '%s' has to have BTF in order to use bpf_timer\n", 8539 map->name); 8540 return -EINVAL; 8541 } 8542 if (!btf_record_has_field(map->record, BPF_TIMER)) { 8543 verbose(env, "map '%s' has no valid bpf_timer\n", map->name); 8544 return -EINVAL; 8545 } 8546 if (map->record->timer_off != val + reg->off) { 8547 verbose(env, "off %lld doesn't point to 'struct bpf_timer' that is at %d\n", 8548 val + reg->off, map->record->timer_off); 8549 return -EINVAL; 8550 } 8551 if (meta->map_ptr) { 8552 verifier_bug(env, "Two map pointers in a timer helper"); 8553 return -EFAULT; 8554 } 8555 if (IS_ENABLED(CONFIG_PREEMPT_RT)) { 8556 verbose(env, "bpf_timer cannot be used for PREEMPT_RT.\n"); 8557 return -EOPNOTSUPP; 8558 } 8559 meta->map_uid = reg->map_uid; 8560 meta->map_ptr = map; 8561 return 0; 8562 } 8563 8564 static int process_wq_func(struct bpf_verifier_env *env, int regno, 8565 struct bpf_kfunc_call_arg_meta *meta) 8566 { 8567 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno]; 8568 struct bpf_map *map = reg->map_ptr; 8569 u64 val = reg->var_off.value; 8570 8571 if (map->record->wq_off != val + reg->off) { 8572 verbose(env, "off %lld doesn't point to 'struct bpf_wq' that is at %d\n", 8573 val + reg->off, map->record->wq_off); 8574 return -EINVAL; 8575 } 8576 meta->map.uid = reg->map_uid; 8577 meta->map.ptr = map; 8578 return 0; 8579 } 8580 8581 static int process_kptr_func(struct bpf_verifier_env *env, int regno, 8582 struct bpf_call_arg_meta *meta) 8583 { 8584 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno]; 8585 struct btf_field *kptr_field; 8586 struct bpf_map *map_ptr; 8587 struct btf_record *rec; 8588 u32 kptr_off; 8589 8590 if (type_is_ptr_alloc_obj(reg->type)) { 8591 rec = reg_btf_record(reg); 8592 } else { /* PTR_TO_MAP_VALUE */ 8593 map_ptr = reg->map_ptr; 8594 if (!map_ptr->btf) { 8595 verbose(env, "map '%s' has to have BTF in order to use bpf_kptr_xchg\n", 8596 map_ptr->name); 8597 return -EINVAL; 8598 } 8599 rec = map_ptr->record; 8600 meta->map_ptr = map_ptr; 8601 } 8602 8603 if (!tnum_is_const(reg->var_off)) { 8604 verbose(env, 8605 "R%d doesn't have constant offset. kptr has to be at the constant offset\n", 8606 regno); 8607 return -EINVAL; 8608 } 8609 8610 if (!btf_record_has_field(rec, BPF_KPTR)) { 8611 verbose(env, "R%d has no valid kptr\n", regno); 8612 return -EINVAL; 8613 } 8614 8615 kptr_off = reg->off + reg->var_off.value; 8616 kptr_field = btf_record_find(rec, kptr_off, BPF_KPTR); 8617 if (!kptr_field) { 8618 verbose(env, "off=%d doesn't point to kptr\n", kptr_off); 8619 return -EACCES; 8620 } 8621 if (kptr_field->type != BPF_KPTR_REF && kptr_field->type != BPF_KPTR_PERCPU) { 8622 verbose(env, "off=%d kptr isn't referenced kptr\n", kptr_off); 8623 return -EACCES; 8624 } 8625 meta->kptr_field = kptr_field; 8626 return 0; 8627 } 8628 8629 /* There are two register types representing a bpf_dynptr, one is PTR_TO_STACK 8630 * which points to a stack slot, and the other is CONST_PTR_TO_DYNPTR. 8631 * 8632 * In both cases we deal with the first 8 bytes, but need to mark the next 8 8633 * bytes as STACK_DYNPTR in case of PTR_TO_STACK. In case of 8634 * CONST_PTR_TO_DYNPTR, we are guaranteed to get the beginning of the object. 8635 * 8636 * Mutability of bpf_dynptr is at two levels, one is at the level of struct 8637 * bpf_dynptr itself, i.e. whether the helper is receiving a pointer to struct 8638 * bpf_dynptr or pointer to const struct bpf_dynptr. In the former case, it can 8639 * mutate the view of the dynptr and also possibly destroy it. In the latter 8640 * case, it cannot mutate the bpf_dynptr itself but it can still mutate the 8641 * memory that dynptr points to. 8642 * 8643 * The verifier will keep track both levels of mutation (bpf_dynptr's in 8644 * reg->type and the memory's in reg->dynptr.type), but there is no support for 8645 * readonly dynptr view yet, hence only the first case is tracked and checked. 8646 * 8647 * This is consistent with how C applies the const modifier to a struct object, 8648 * where the pointer itself inside bpf_dynptr becomes const but not what it 8649 * points to. 8650 * 8651 * Helpers which do not mutate the bpf_dynptr set MEM_RDONLY in their argument 8652 * type, and declare it as 'const struct bpf_dynptr *' in their prototype. 8653 */ 8654 static int process_dynptr_func(struct bpf_verifier_env *env, int regno, int insn_idx, 8655 enum bpf_arg_type arg_type, int clone_ref_obj_id) 8656 { 8657 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno]; 8658 int err; 8659 8660 if (reg->type != PTR_TO_STACK && reg->type != CONST_PTR_TO_DYNPTR) { 8661 verbose(env, 8662 "arg#%d expected pointer to stack or const struct bpf_dynptr\n", 8663 regno - 1); 8664 return -EINVAL; 8665 } 8666 8667 /* MEM_UNINIT and MEM_RDONLY are exclusive, when applied to an 8668 * ARG_PTR_TO_DYNPTR (or ARG_PTR_TO_DYNPTR | DYNPTR_TYPE_*): 8669 */ 8670 if ((arg_type & (MEM_UNINIT | MEM_RDONLY)) == (MEM_UNINIT | MEM_RDONLY)) { 8671 verifier_bug(env, "misconfigured dynptr helper type flags"); 8672 return -EFAULT; 8673 } 8674 8675 /* MEM_UNINIT - Points to memory that is an appropriate candidate for 8676 * constructing a mutable bpf_dynptr object. 8677 * 8678 * Currently, this is only possible with PTR_TO_STACK 8679 * pointing to a region of at least 16 bytes which doesn't 8680 * contain an existing bpf_dynptr. 8681 * 8682 * MEM_RDONLY - Points to a initialized bpf_dynptr that will not be 8683 * mutated or destroyed. However, the memory it points to 8684 * may be mutated. 8685 * 8686 * None - Points to a initialized dynptr that can be mutated and 8687 * destroyed, including mutation of the memory it points 8688 * to. 8689 */ 8690 if (arg_type & MEM_UNINIT) { 8691 int i; 8692 8693 if (!is_dynptr_reg_valid_uninit(env, reg)) { 8694 verbose(env, "Dynptr has to be an uninitialized dynptr\n"); 8695 return -EINVAL; 8696 } 8697 8698 /* we write BPF_DW bits (8 bytes) at a time */ 8699 for (i = 0; i < BPF_DYNPTR_SIZE; i += 8) { 8700 err = check_mem_access(env, insn_idx, regno, 8701 i, BPF_DW, BPF_WRITE, -1, false, false); 8702 if (err) 8703 return err; 8704 } 8705 8706 err = mark_stack_slots_dynptr(env, reg, arg_type, insn_idx, clone_ref_obj_id); 8707 } else /* MEM_RDONLY and None case from above */ { 8708 /* For the reg->type == PTR_TO_STACK case, bpf_dynptr is never const */ 8709 if (reg->type == CONST_PTR_TO_DYNPTR && !(arg_type & MEM_RDONLY)) { 8710 verbose(env, "cannot pass pointer to const bpf_dynptr, the helper mutates it\n"); 8711 return -EINVAL; 8712 } 8713 8714 if (!is_dynptr_reg_valid_init(env, reg)) { 8715 verbose(env, 8716 "Expected an initialized dynptr as arg #%d\n", 8717 regno - 1); 8718 return -EINVAL; 8719 } 8720 8721 /* Fold modifiers (in this case, MEM_RDONLY) when checking expected type */ 8722 if (!is_dynptr_type_expected(env, reg, arg_type & ~MEM_RDONLY)) { 8723 verbose(env, 8724 "Expected a dynptr of type %s as arg #%d\n", 8725 dynptr_type_str(arg_to_dynptr_type(arg_type)), regno - 1); 8726 return -EINVAL; 8727 } 8728 8729 err = mark_dynptr_read(env, reg); 8730 } 8731 return err; 8732 } 8733 8734 static u32 iter_ref_obj_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg, int spi) 8735 { 8736 struct bpf_func_state *state = func(env, reg); 8737 8738 return state->stack[spi].spilled_ptr.ref_obj_id; 8739 } 8740 8741 static bool is_iter_kfunc(struct bpf_kfunc_call_arg_meta *meta) 8742 { 8743 return meta->kfunc_flags & (KF_ITER_NEW | KF_ITER_NEXT | KF_ITER_DESTROY); 8744 } 8745 8746 static bool is_iter_new_kfunc(struct bpf_kfunc_call_arg_meta *meta) 8747 { 8748 return meta->kfunc_flags & KF_ITER_NEW; 8749 } 8750 8751 static bool is_iter_next_kfunc(struct bpf_kfunc_call_arg_meta *meta) 8752 { 8753 return meta->kfunc_flags & KF_ITER_NEXT; 8754 } 8755 8756 static bool is_iter_destroy_kfunc(struct bpf_kfunc_call_arg_meta *meta) 8757 { 8758 return meta->kfunc_flags & KF_ITER_DESTROY; 8759 } 8760 8761 static bool is_kfunc_arg_iter(struct bpf_kfunc_call_arg_meta *meta, int arg_idx, 8762 const struct btf_param *arg) 8763 { 8764 /* btf_check_iter_kfuncs() guarantees that first argument of any iter 8765 * kfunc is iter state pointer 8766 */ 8767 if (is_iter_kfunc(meta)) 8768 return arg_idx == 0; 8769 8770 /* iter passed as an argument to a generic kfunc */ 8771 return btf_param_match_suffix(meta->btf, arg, "__iter"); 8772 } 8773 8774 static int process_iter_arg(struct bpf_verifier_env *env, int regno, int insn_idx, 8775 struct bpf_kfunc_call_arg_meta *meta) 8776 { 8777 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno]; 8778 const struct btf_type *t; 8779 int spi, err, i, nr_slots, btf_id; 8780 8781 if (reg->type != PTR_TO_STACK) { 8782 verbose(env, "arg#%d expected pointer to an iterator on stack\n", regno - 1); 8783 return -EINVAL; 8784 } 8785 8786 /* For iter_{new,next,destroy} functions, btf_check_iter_kfuncs() 8787 * ensures struct convention, so we wouldn't need to do any BTF 8788 * validation here. But given iter state can be passed as a parameter 8789 * to any kfunc, if arg has "__iter" suffix, we need to be a bit more 8790 * conservative here. 8791 */ 8792 btf_id = btf_check_iter_arg(meta->btf, meta->func_proto, regno - 1); 8793 if (btf_id < 0) { 8794 verbose(env, "expected valid iter pointer as arg #%d\n", regno - 1); 8795 return -EINVAL; 8796 } 8797 t = btf_type_by_id(meta->btf, btf_id); 8798 nr_slots = t->size / BPF_REG_SIZE; 8799 8800 if (is_iter_new_kfunc(meta)) { 8801 /* bpf_iter_<type>_new() expects pointer to uninit iter state */ 8802 if (!is_iter_reg_valid_uninit(env, reg, nr_slots)) { 8803 verbose(env, "expected uninitialized iter_%s as arg #%d\n", 8804 iter_type_str(meta->btf, btf_id), regno - 1); 8805 return -EINVAL; 8806 } 8807 8808 for (i = 0; i < nr_slots * 8; i += BPF_REG_SIZE) { 8809 err = check_mem_access(env, insn_idx, regno, 8810 i, BPF_DW, BPF_WRITE, -1, false, false); 8811 if (err) 8812 return err; 8813 } 8814 8815 err = mark_stack_slots_iter(env, meta, reg, insn_idx, meta->btf, btf_id, nr_slots); 8816 if (err) 8817 return err; 8818 } else { 8819 /* iter_next() or iter_destroy(), as well as any kfunc 8820 * accepting iter argument, expect initialized iter state 8821 */ 8822 err = is_iter_reg_valid_init(env, reg, meta->btf, btf_id, nr_slots); 8823 switch (err) { 8824 case 0: 8825 break; 8826 case -EINVAL: 8827 verbose(env, "expected an initialized iter_%s as arg #%d\n", 8828 iter_type_str(meta->btf, btf_id), regno - 1); 8829 return err; 8830 case -EPROTO: 8831 verbose(env, "expected an RCU CS when using %s\n", meta->func_name); 8832 return err; 8833 default: 8834 return err; 8835 } 8836 8837 spi = iter_get_spi(env, reg, nr_slots); 8838 if (spi < 0) 8839 return spi; 8840 8841 err = mark_iter_read(env, reg, spi, nr_slots); 8842 if (err) 8843 return err; 8844 8845 /* remember meta->iter info for process_iter_next_call() */ 8846 meta->iter.spi = spi; 8847 meta->iter.frameno = reg->frameno; 8848 meta->ref_obj_id = iter_ref_obj_id(env, reg, spi); 8849 8850 if (is_iter_destroy_kfunc(meta)) { 8851 err = unmark_stack_slots_iter(env, reg, nr_slots); 8852 if (err) 8853 return err; 8854 } 8855 } 8856 8857 return 0; 8858 } 8859 8860 /* Look for a previous loop entry at insn_idx: nearest parent state 8861 * stopped at insn_idx with callsites matching those in cur->frame. 8862 */ 8863 static struct bpf_verifier_state *find_prev_entry(struct bpf_verifier_env *env, 8864 struct bpf_verifier_state *cur, 8865 int insn_idx) 8866 { 8867 struct bpf_verifier_state_list *sl; 8868 struct bpf_verifier_state *st; 8869 struct list_head *pos, *head; 8870 8871 /* Explored states are pushed in stack order, most recent states come first */ 8872 head = explored_state(env, insn_idx); 8873 list_for_each(pos, head) { 8874 sl = container_of(pos, struct bpf_verifier_state_list, node); 8875 /* If st->branches != 0 state is a part of current DFS verification path, 8876 * hence cur & st for a loop. 8877 */ 8878 st = &sl->state; 8879 if (st->insn_idx == insn_idx && st->branches && same_callsites(st, cur) && 8880 st->dfs_depth < cur->dfs_depth) 8881 return st; 8882 } 8883 8884 return NULL; 8885 } 8886 8887 static void reset_idmap_scratch(struct bpf_verifier_env *env); 8888 static bool regs_exact(const struct bpf_reg_state *rold, 8889 const struct bpf_reg_state *rcur, 8890 struct bpf_idmap *idmap); 8891 8892 static void maybe_widen_reg(struct bpf_verifier_env *env, 8893 struct bpf_reg_state *rold, struct bpf_reg_state *rcur, 8894 struct bpf_idmap *idmap) 8895 { 8896 if (rold->type != SCALAR_VALUE) 8897 return; 8898 if (rold->type != rcur->type) 8899 return; 8900 if (rold->precise || rcur->precise || regs_exact(rold, rcur, idmap)) 8901 return; 8902 __mark_reg_unknown(env, rcur); 8903 } 8904 8905 static int widen_imprecise_scalars(struct bpf_verifier_env *env, 8906 struct bpf_verifier_state *old, 8907 struct bpf_verifier_state *cur) 8908 { 8909 struct bpf_func_state *fold, *fcur; 8910 int i, fr; 8911 8912 reset_idmap_scratch(env); 8913 for (fr = old->curframe; fr >= 0; fr--) { 8914 fold = old->frame[fr]; 8915 fcur = cur->frame[fr]; 8916 8917 for (i = 0; i < MAX_BPF_REG; i++) 8918 maybe_widen_reg(env, 8919 &fold->regs[i], 8920 &fcur->regs[i], 8921 &env->idmap_scratch); 8922 8923 for (i = 0; i < fold->allocated_stack / BPF_REG_SIZE; i++) { 8924 if (!is_spilled_reg(&fold->stack[i]) || 8925 !is_spilled_reg(&fcur->stack[i])) 8926 continue; 8927 8928 maybe_widen_reg(env, 8929 &fold->stack[i].spilled_ptr, 8930 &fcur->stack[i].spilled_ptr, 8931 &env->idmap_scratch); 8932 } 8933 } 8934 return 0; 8935 } 8936 8937 static struct bpf_reg_state *get_iter_from_state(struct bpf_verifier_state *cur_st, 8938 struct bpf_kfunc_call_arg_meta *meta) 8939 { 8940 int iter_frameno = meta->iter.frameno; 8941 int iter_spi = meta->iter.spi; 8942 8943 return &cur_st->frame[iter_frameno]->stack[iter_spi].spilled_ptr; 8944 } 8945 8946 /* process_iter_next_call() is called when verifier gets to iterator's next 8947 * "method" (e.g., bpf_iter_num_next() for numbers iterator) call. We'll refer 8948 * to it as just "iter_next()" in comments below. 8949 * 8950 * BPF verifier relies on a crucial contract for any iter_next() 8951 * implementation: it should *eventually* return NULL, and once that happens 8952 * it should keep returning NULL. That is, once iterator exhausts elements to 8953 * iterate, it should never reset or spuriously return new elements. 8954 * 8955 * With the assumption of such contract, process_iter_next_call() simulates 8956 * a fork in the verifier state to validate loop logic correctness and safety 8957 * without having to simulate infinite amount of iterations. 8958 * 8959 * In current state, we first assume that iter_next() returned NULL and 8960 * iterator state is set to DRAINED (BPF_ITER_STATE_DRAINED). In such 8961 * conditions we should not form an infinite loop and should eventually reach 8962 * exit. 8963 * 8964 * Besides that, we also fork current state and enqueue it for later 8965 * verification. In a forked state we keep iterator state as ACTIVE 8966 * (BPF_ITER_STATE_ACTIVE) and assume non-NULL return from iter_next(). We 8967 * also bump iteration depth to prevent erroneous infinite loop detection 8968 * later on (see iter_active_depths_differ() comment for details). In this 8969 * state we assume that we'll eventually loop back to another iter_next() 8970 * calls (it could be in exactly same location or in some other instruction, 8971 * it doesn't matter, we don't make any unnecessary assumptions about this, 8972 * everything revolves around iterator state in a stack slot, not which 8973 * instruction is calling iter_next()). When that happens, we either will come 8974 * to iter_next() with equivalent state and can conclude that next iteration 8975 * will proceed in exactly the same way as we just verified, so it's safe to 8976 * assume that loop converges. If not, we'll go on another iteration 8977 * simulation with a different input state, until all possible starting states 8978 * are validated or we reach maximum number of instructions limit. 8979 * 8980 * This way, we will either exhaustively discover all possible input states 8981 * that iterator loop can start with and eventually will converge, or we'll 8982 * effectively regress into bounded loop simulation logic and either reach 8983 * maximum number of instructions if loop is not provably convergent, or there 8984 * is some statically known limit on number of iterations (e.g., if there is 8985 * an explicit `if n > 100 then break;` statement somewhere in the loop). 8986 * 8987 * Iteration convergence logic in is_state_visited() relies on exact 8988 * states comparison, which ignores read and precision marks. 8989 * This is necessary because read and precision marks are not finalized 8990 * while in the loop. Exact comparison might preclude convergence for 8991 * simple programs like below: 8992 * 8993 * i = 0; 8994 * while(iter_next(&it)) 8995 * i++; 8996 * 8997 * At each iteration step i++ would produce a new distinct state and 8998 * eventually instruction processing limit would be reached. 8999 * 9000 * To avoid such behavior speculatively forget (widen) range for 9001 * imprecise scalar registers, if those registers were not precise at the 9002 * end of the previous iteration and do not match exactly. 9003 * 9004 * This is a conservative heuristic that allows to verify wide range of programs, 9005 * however it precludes verification of programs that conjure an 9006 * imprecise value on the first loop iteration and use it as precise on a second. 9007 * For example, the following safe program would fail to verify: 9008 * 9009 * struct bpf_num_iter it; 9010 * int arr[10]; 9011 * int i = 0, a = 0; 9012 * bpf_iter_num_new(&it, 0, 10); 9013 * while (bpf_iter_num_next(&it)) { 9014 * if (a == 0) { 9015 * a = 1; 9016 * i = 7; // Because i changed verifier would forget 9017 * // it's range on second loop entry. 9018 * } else { 9019 * arr[i] = 42; // This would fail to verify. 9020 * } 9021 * } 9022 * bpf_iter_num_destroy(&it); 9023 */ 9024 static int process_iter_next_call(struct bpf_verifier_env *env, int insn_idx, 9025 struct bpf_kfunc_call_arg_meta *meta) 9026 { 9027 struct bpf_verifier_state *cur_st = env->cur_state, *queued_st, *prev_st; 9028 struct bpf_func_state *cur_fr = cur_st->frame[cur_st->curframe], *queued_fr; 9029 struct bpf_reg_state *cur_iter, *queued_iter; 9030 9031 BTF_TYPE_EMIT(struct bpf_iter); 9032 9033 cur_iter = get_iter_from_state(cur_st, meta); 9034 9035 if (cur_iter->iter.state != BPF_ITER_STATE_ACTIVE && 9036 cur_iter->iter.state != BPF_ITER_STATE_DRAINED) { 9037 verifier_bug(env, "unexpected iterator state %d (%s)", 9038 cur_iter->iter.state, iter_state_str(cur_iter->iter.state)); 9039 return -EFAULT; 9040 } 9041 9042 if (cur_iter->iter.state == BPF_ITER_STATE_ACTIVE) { 9043 /* Because iter_next() call is a checkpoint is_state_visitied() 9044 * should guarantee parent state with same call sites and insn_idx. 9045 */ 9046 if (!cur_st->parent || cur_st->parent->insn_idx != insn_idx || 9047 !same_callsites(cur_st->parent, cur_st)) { 9048 verifier_bug(env, "bad parent state for iter next call"); 9049 return -EFAULT; 9050 } 9051 /* Note cur_st->parent in the call below, it is necessary to skip 9052 * checkpoint created for cur_st by is_state_visited() 9053 * right at this instruction. 9054 */ 9055 prev_st = find_prev_entry(env, cur_st->parent, insn_idx); 9056 /* branch out active iter state */ 9057 queued_st = push_stack(env, insn_idx + 1, insn_idx, false); 9058 if (!queued_st) 9059 return -ENOMEM; 9060 9061 queued_iter = get_iter_from_state(queued_st, meta); 9062 queued_iter->iter.state = BPF_ITER_STATE_ACTIVE; 9063 queued_iter->iter.depth++; 9064 if (prev_st) 9065 widen_imprecise_scalars(env, prev_st, queued_st); 9066 9067 queued_fr = queued_st->frame[queued_st->curframe]; 9068 mark_ptr_not_null_reg(&queued_fr->regs[BPF_REG_0]); 9069 } 9070 9071 /* switch to DRAINED state, but keep the depth unchanged */ 9072 /* mark current iter state as drained and assume returned NULL */ 9073 cur_iter->iter.state = BPF_ITER_STATE_DRAINED; 9074 __mark_reg_const_zero(env, &cur_fr->regs[BPF_REG_0]); 9075 9076 return 0; 9077 } 9078 9079 static bool arg_type_is_mem_size(enum bpf_arg_type type) 9080 { 9081 return type == ARG_CONST_SIZE || 9082 type == ARG_CONST_SIZE_OR_ZERO; 9083 } 9084 9085 static bool arg_type_is_raw_mem(enum bpf_arg_type type) 9086 { 9087 return base_type(type) == ARG_PTR_TO_MEM && 9088 type & MEM_UNINIT; 9089 } 9090 9091 static bool arg_type_is_release(enum bpf_arg_type type) 9092 { 9093 return type & OBJ_RELEASE; 9094 } 9095 9096 static bool arg_type_is_dynptr(enum bpf_arg_type type) 9097 { 9098 return base_type(type) == ARG_PTR_TO_DYNPTR; 9099 } 9100 9101 static int resolve_map_arg_type(struct bpf_verifier_env *env, 9102 const struct bpf_call_arg_meta *meta, 9103 enum bpf_arg_type *arg_type) 9104 { 9105 if (!meta->map_ptr) { 9106 /* kernel subsystem misconfigured verifier */ 9107 verifier_bug(env, "invalid map_ptr to access map->type"); 9108 return -EFAULT; 9109 } 9110 9111 switch (meta->map_ptr->map_type) { 9112 case BPF_MAP_TYPE_SOCKMAP: 9113 case BPF_MAP_TYPE_SOCKHASH: 9114 if (*arg_type == ARG_PTR_TO_MAP_VALUE) { 9115 *arg_type = ARG_PTR_TO_BTF_ID_SOCK_COMMON; 9116 } else { 9117 verbose(env, "invalid arg_type for sockmap/sockhash\n"); 9118 return -EINVAL; 9119 } 9120 break; 9121 case BPF_MAP_TYPE_BLOOM_FILTER: 9122 if (meta->func_id == BPF_FUNC_map_peek_elem) 9123 *arg_type = ARG_PTR_TO_MAP_VALUE; 9124 break; 9125 default: 9126 break; 9127 } 9128 return 0; 9129 } 9130 9131 struct bpf_reg_types { 9132 const enum bpf_reg_type types[10]; 9133 u32 *btf_id; 9134 }; 9135 9136 static const struct bpf_reg_types sock_types = { 9137 .types = { 9138 PTR_TO_SOCK_COMMON, 9139 PTR_TO_SOCKET, 9140 PTR_TO_TCP_SOCK, 9141 PTR_TO_XDP_SOCK, 9142 }, 9143 }; 9144 9145 #ifdef CONFIG_NET 9146 static const struct bpf_reg_types btf_id_sock_common_types = { 9147 .types = { 9148 PTR_TO_SOCK_COMMON, 9149 PTR_TO_SOCKET, 9150 PTR_TO_TCP_SOCK, 9151 PTR_TO_XDP_SOCK, 9152 PTR_TO_BTF_ID, 9153 PTR_TO_BTF_ID | PTR_TRUSTED, 9154 }, 9155 .btf_id = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON], 9156 }; 9157 #endif 9158 9159 static const struct bpf_reg_types mem_types = { 9160 .types = { 9161 PTR_TO_STACK, 9162 PTR_TO_PACKET, 9163 PTR_TO_PACKET_META, 9164 PTR_TO_MAP_KEY, 9165 PTR_TO_MAP_VALUE, 9166 PTR_TO_MEM, 9167 PTR_TO_MEM | MEM_RINGBUF, 9168 PTR_TO_BUF, 9169 PTR_TO_BTF_ID | PTR_TRUSTED, 9170 }, 9171 }; 9172 9173 static const struct bpf_reg_types spin_lock_types = { 9174 .types = { 9175 PTR_TO_MAP_VALUE, 9176 PTR_TO_BTF_ID | MEM_ALLOC, 9177 } 9178 }; 9179 9180 static const struct bpf_reg_types fullsock_types = { .types = { PTR_TO_SOCKET } }; 9181 static const struct bpf_reg_types scalar_types = { .types = { SCALAR_VALUE } }; 9182 static const struct bpf_reg_types context_types = { .types = { PTR_TO_CTX } }; 9183 static const struct bpf_reg_types ringbuf_mem_types = { .types = { PTR_TO_MEM | MEM_RINGBUF } }; 9184 static const struct bpf_reg_types const_map_ptr_types = { .types = { CONST_PTR_TO_MAP } }; 9185 static const struct bpf_reg_types btf_ptr_types = { 9186 .types = { 9187 PTR_TO_BTF_ID, 9188 PTR_TO_BTF_ID | PTR_TRUSTED, 9189 PTR_TO_BTF_ID | MEM_RCU, 9190 }, 9191 }; 9192 static const struct bpf_reg_types percpu_btf_ptr_types = { 9193 .types = { 9194 PTR_TO_BTF_ID | MEM_PERCPU, 9195 PTR_TO_BTF_ID | MEM_PERCPU | MEM_RCU, 9196 PTR_TO_BTF_ID | MEM_PERCPU | PTR_TRUSTED, 9197 } 9198 }; 9199 static const struct bpf_reg_types func_ptr_types = { .types = { PTR_TO_FUNC } }; 9200 static const struct bpf_reg_types stack_ptr_types = { .types = { PTR_TO_STACK } }; 9201 static const struct bpf_reg_types const_str_ptr_types = { .types = { PTR_TO_MAP_VALUE } }; 9202 static const struct bpf_reg_types timer_types = { .types = { PTR_TO_MAP_VALUE } }; 9203 static const struct bpf_reg_types kptr_xchg_dest_types = { 9204 .types = { 9205 PTR_TO_MAP_VALUE, 9206 PTR_TO_BTF_ID | MEM_ALLOC 9207 } 9208 }; 9209 static const struct bpf_reg_types dynptr_types = { 9210 .types = { 9211 PTR_TO_STACK, 9212 CONST_PTR_TO_DYNPTR, 9213 } 9214 }; 9215 9216 static const struct bpf_reg_types *compatible_reg_types[__BPF_ARG_TYPE_MAX] = { 9217 [ARG_PTR_TO_MAP_KEY] = &mem_types, 9218 [ARG_PTR_TO_MAP_VALUE] = &mem_types, 9219 [ARG_CONST_SIZE] = &scalar_types, 9220 [ARG_CONST_SIZE_OR_ZERO] = &scalar_types, 9221 [ARG_CONST_ALLOC_SIZE_OR_ZERO] = &scalar_types, 9222 [ARG_CONST_MAP_PTR] = &const_map_ptr_types, 9223 [ARG_PTR_TO_CTX] = &context_types, 9224 [ARG_PTR_TO_SOCK_COMMON] = &sock_types, 9225 #ifdef CONFIG_NET 9226 [ARG_PTR_TO_BTF_ID_SOCK_COMMON] = &btf_id_sock_common_types, 9227 #endif 9228 [ARG_PTR_TO_SOCKET] = &fullsock_types, 9229 [ARG_PTR_TO_BTF_ID] = &btf_ptr_types, 9230 [ARG_PTR_TO_SPIN_LOCK] = &spin_lock_types, 9231 [ARG_PTR_TO_MEM] = &mem_types, 9232 [ARG_PTR_TO_RINGBUF_MEM] = &ringbuf_mem_types, 9233 [ARG_PTR_TO_PERCPU_BTF_ID] = &percpu_btf_ptr_types, 9234 [ARG_PTR_TO_FUNC] = &func_ptr_types, 9235 [ARG_PTR_TO_STACK] = &stack_ptr_types, 9236 [ARG_PTR_TO_CONST_STR] = &const_str_ptr_types, 9237 [ARG_PTR_TO_TIMER] = &timer_types, 9238 [ARG_KPTR_XCHG_DEST] = &kptr_xchg_dest_types, 9239 [ARG_PTR_TO_DYNPTR] = &dynptr_types, 9240 }; 9241 9242 static int check_reg_type(struct bpf_verifier_env *env, u32 regno, 9243 enum bpf_arg_type arg_type, 9244 const u32 *arg_btf_id, 9245 struct bpf_call_arg_meta *meta) 9246 { 9247 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno]; 9248 enum bpf_reg_type expected, type = reg->type; 9249 const struct bpf_reg_types *compatible; 9250 int i, j; 9251 9252 compatible = compatible_reg_types[base_type(arg_type)]; 9253 if (!compatible) { 9254 verifier_bug(env, "unsupported arg type %d", arg_type); 9255 return -EFAULT; 9256 } 9257 9258 /* ARG_PTR_TO_MEM + RDONLY is compatible with PTR_TO_MEM and PTR_TO_MEM + RDONLY, 9259 * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM and NOT with PTR_TO_MEM + RDONLY 9260 * 9261 * Same for MAYBE_NULL: 9262 * 9263 * ARG_PTR_TO_MEM + MAYBE_NULL is compatible with PTR_TO_MEM and PTR_TO_MEM + MAYBE_NULL, 9264 * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM but NOT with PTR_TO_MEM + MAYBE_NULL 9265 * 9266 * ARG_PTR_TO_MEM is compatible with PTR_TO_MEM that is tagged with a dynptr type. 9267 * 9268 * Therefore we fold these flags depending on the arg_type before comparison. 9269 */ 9270 if (arg_type & MEM_RDONLY) 9271 type &= ~MEM_RDONLY; 9272 if (arg_type & PTR_MAYBE_NULL) 9273 type &= ~PTR_MAYBE_NULL; 9274 if (base_type(arg_type) == ARG_PTR_TO_MEM) 9275 type &= ~DYNPTR_TYPE_FLAG_MASK; 9276 9277 /* Local kptr types are allowed as the source argument of bpf_kptr_xchg */ 9278 if (meta->func_id == BPF_FUNC_kptr_xchg && type_is_alloc(type) && regno == BPF_REG_2) { 9279 type &= ~MEM_ALLOC; 9280 type &= ~MEM_PERCPU; 9281 } 9282 9283 for (i = 0; i < ARRAY_SIZE(compatible->types); i++) { 9284 expected = compatible->types[i]; 9285 if (expected == NOT_INIT) 9286 break; 9287 9288 if (type == expected) 9289 goto found; 9290 } 9291 9292 verbose(env, "R%d type=%s expected=", regno, reg_type_str(env, reg->type)); 9293 for (j = 0; j + 1 < i; j++) 9294 verbose(env, "%s, ", reg_type_str(env, compatible->types[j])); 9295 verbose(env, "%s\n", reg_type_str(env, compatible->types[j])); 9296 return -EACCES; 9297 9298 found: 9299 if (base_type(reg->type) != PTR_TO_BTF_ID) 9300 return 0; 9301 9302 if (compatible == &mem_types) { 9303 if (!(arg_type & MEM_RDONLY)) { 9304 verbose(env, 9305 "%s() may write into memory pointed by R%d type=%s\n", 9306 func_id_name(meta->func_id), 9307 regno, reg_type_str(env, reg->type)); 9308 return -EACCES; 9309 } 9310 return 0; 9311 } 9312 9313 switch ((int)reg->type) { 9314 case PTR_TO_BTF_ID: 9315 case PTR_TO_BTF_ID | PTR_TRUSTED: 9316 case PTR_TO_BTF_ID | PTR_TRUSTED | PTR_MAYBE_NULL: 9317 case PTR_TO_BTF_ID | MEM_RCU: 9318 case PTR_TO_BTF_ID | PTR_MAYBE_NULL: 9319 case PTR_TO_BTF_ID | PTR_MAYBE_NULL | MEM_RCU: 9320 { 9321 /* For bpf_sk_release, it needs to match against first member 9322 * 'struct sock_common', hence make an exception for it. This 9323 * allows bpf_sk_release to work for multiple socket types. 9324 */ 9325 bool strict_type_match = arg_type_is_release(arg_type) && 9326 meta->func_id != BPF_FUNC_sk_release; 9327 9328 if (type_may_be_null(reg->type) && 9329 (!type_may_be_null(arg_type) || arg_type_is_release(arg_type))) { 9330 verbose(env, "Possibly NULL pointer passed to helper arg%d\n", regno); 9331 return -EACCES; 9332 } 9333 9334 if (!arg_btf_id) { 9335 if (!compatible->btf_id) { 9336 verifier_bug(env, "missing arg compatible BTF ID"); 9337 return -EFAULT; 9338 } 9339 arg_btf_id = compatible->btf_id; 9340 } 9341 9342 if (meta->func_id == BPF_FUNC_kptr_xchg) { 9343 if (map_kptr_match_type(env, meta->kptr_field, reg, regno)) 9344 return -EACCES; 9345 } else { 9346 if (arg_btf_id == BPF_PTR_POISON) { 9347 verbose(env, "verifier internal error:"); 9348 verbose(env, "R%d has non-overwritten BPF_PTR_POISON type\n", 9349 regno); 9350 return -EACCES; 9351 } 9352 9353 if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off, 9354 btf_vmlinux, *arg_btf_id, 9355 strict_type_match)) { 9356 verbose(env, "R%d is of type %s but %s is expected\n", 9357 regno, btf_type_name(reg->btf, reg->btf_id), 9358 btf_type_name(btf_vmlinux, *arg_btf_id)); 9359 return -EACCES; 9360 } 9361 } 9362 break; 9363 } 9364 case PTR_TO_BTF_ID | MEM_ALLOC: 9365 case PTR_TO_BTF_ID | MEM_PERCPU | MEM_ALLOC: 9366 if (meta->func_id != BPF_FUNC_spin_lock && meta->func_id != BPF_FUNC_spin_unlock && 9367 meta->func_id != BPF_FUNC_kptr_xchg) { 9368 verifier_bug(env, "unimplemented handling of MEM_ALLOC"); 9369 return -EFAULT; 9370 } 9371 /* Check if local kptr in src arg matches kptr in dst arg */ 9372 if (meta->func_id == BPF_FUNC_kptr_xchg && regno == BPF_REG_2) { 9373 if (map_kptr_match_type(env, meta->kptr_field, reg, regno)) 9374 return -EACCES; 9375 } 9376 break; 9377 case PTR_TO_BTF_ID | MEM_PERCPU: 9378 case PTR_TO_BTF_ID | MEM_PERCPU | MEM_RCU: 9379 case PTR_TO_BTF_ID | MEM_PERCPU | PTR_TRUSTED: 9380 /* Handled by helper specific checks */ 9381 break; 9382 default: 9383 verifier_bug(env, "invalid PTR_TO_BTF_ID register for type match"); 9384 return -EFAULT; 9385 } 9386 return 0; 9387 } 9388 9389 static struct btf_field * 9390 reg_find_field_offset(const struct bpf_reg_state *reg, s32 off, u32 fields) 9391 { 9392 struct btf_field *field; 9393 struct btf_record *rec; 9394 9395 rec = reg_btf_record(reg); 9396 if (!rec) 9397 return NULL; 9398 9399 field = btf_record_find(rec, off, fields); 9400 if (!field) 9401 return NULL; 9402 9403 return field; 9404 } 9405 9406 static int check_func_arg_reg_off(struct bpf_verifier_env *env, 9407 const struct bpf_reg_state *reg, int regno, 9408 enum bpf_arg_type arg_type) 9409 { 9410 u32 type = reg->type; 9411 9412 /* When referenced register is passed to release function, its fixed 9413 * offset must be 0. 9414 * 9415 * We will check arg_type_is_release reg has ref_obj_id when storing 9416 * meta->release_regno. 9417 */ 9418 if (arg_type_is_release(arg_type)) { 9419 /* ARG_PTR_TO_DYNPTR with OBJ_RELEASE is a bit special, as it 9420 * may not directly point to the object being released, but to 9421 * dynptr pointing to such object, which might be at some offset 9422 * on the stack. In that case, we simply to fallback to the 9423 * default handling. 9424 */ 9425 if (arg_type_is_dynptr(arg_type) && type == PTR_TO_STACK) 9426 return 0; 9427 9428 /* Doing check_ptr_off_reg check for the offset will catch this 9429 * because fixed_off_ok is false, but checking here allows us 9430 * to give the user a better error message. 9431 */ 9432 if (reg->off) { 9433 verbose(env, "R%d must have zero offset when passed to release func or trusted arg to kfunc\n", 9434 regno); 9435 return -EINVAL; 9436 } 9437 return __check_ptr_off_reg(env, reg, regno, false); 9438 } 9439 9440 switch (type) { 9441 /* Pointer types where both fixed and variable offset is explicitly allowed: */ 9442 case PTR_TO_STACK: 9443 case PTR_TO_PACKET: 9444 case PTR_TO_PACKET_META: 9445 case PTR_TO_MAP_KEY: 9446 case PTR_TO_MAP_VALUE: 9447 case PTR_TO_MEM: 9448 case PTR_TO_MEM | MEM_RDONLY: 9449 case PTR_TO_MEM | MEM_RINGBUF: 9450 case PTR_TO_BUF: 9451 case PTR_TO_BUF | MEM_RDONLY: 9452 case PTR_TO_ARENA: 9453 case SCALAR_VALUE: 9454 return 0; 9455 /* All the rest must be rejected, except PTR_TO_BTF_ID which allows 9456 * fixed offset. 9457 */ 9458 case PTR_TO_BTF_ID: 9459 case PTR_TO_BTF_ID | MEM_ALLOC: 9460 case PTR_TO_BTF_ID | PTR_TRUSTED: 9461 case PTR_TO_BTF_ID | MEM_RCU: 9462 case PTR_TO_BTF_ID | MEM_ALLOC | NON_OWN_REF: 9463 case PTR_TO_BTF_ID | MEM_ALLOC | NON_OWN_REF | MEM_RCU: 9464 /* When referenced PTR_TO_BTF_ID is passed to release function, 9465 * its fixed offset must be 0. In the other cases, fixed offset 9466 * can be non-zero. This was already checked above. So pass 9467 * fixed_off_ok as true to allow fixed offset for all other 9468 * cases. var_off always must be 0 for PTR_TO_BTF_ID, hence we 9469 * still need to do checks instead of returning. 9470 */ 9471 return __check_ptr_off_reg(env, reg, regno, true); 9472 default: 9473 return __check_ptr_off_reg(env, reg, regno, false); 9474 } 9475 } 9476 9477 static struct bpf_reg_state *get_dynptr_arg_reg(struct bpf_verifier_env *env, 9478 const struct bpf_func_proto *fn, 9479 struct bpf_reg_state *regs) 9480 { 9481 struct bpf_reg_state *state = NULL; 9482 int i; 9483 9484 for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++) 9485 if (arg_type_is_dynptr(fn->arg_type[i])) { 9486 if (state) { 9487 verbose(env, "verifier internal error: multiple dynptr args\n"); 9488 return NULL; 9489 } 9490 state = ®s[BPF_REG_1 + i]; 9491 } 9492 9493 if (!state) 9494 verbose(env, "verifier internal error: no dynptr arg found\n"); 9495 9496 return state; 9497 } 9498 9499 static int dynptr_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 9500 { 9501 struct bpf_func_state *state = func(env, reg); 9502 int spi; 9503 9504 if (reg->type == CONST_PTR_TO_DYNPTR) 9505 return reg->id; 9506 spi = dynptr_get_spi(env, reg); 9507 if (spi < 0) 9508 return spi; 9509 return state->stack[spi].spilled_ptr.id; 9510 } 9511 9512 static int dynptr_ref_obj_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 9513 { 9514 struct bpf_func_state *state = func(env, reg); 9515 int spi; 9516 9517 if (reg->type == CONST_PTR_TO_DYNPTR) 9518 return reg->ref_obj_id; 9519 spi = dynptr_get_spi(env, reg); 9520 if (spi < 0) 9521 return spi; 9522 return state->stack[spi].spilled_ptr.ref_obj_id; 9523 } 9524 9525 static enum bpf_dynptr_type dynptr_get_type(struct bpf_verifier_env *env, 9526 struct bpf_reg_state *reg) 9527 { 9528 struct bpf_func_state *state = func(env, reg); 9529 int spi; 9530 9531 if (reg->type == CONST_PTR_TO_DYNPTR) 9532 return reg->dynptr.type; 9533 9534 spi = __get_spi(reg->off); 9535 if (spi < 0) { 9536 verbose(env, "verifier internal error: invalid spi when querying dynptr type\n"); 9537 return BPF_DYNPTR_TYPE_INVALID; 9538 } 9539 9540 return state->stack[spi].spilled_ptr.dynptr.type; 9541 } 9542 9543 static int check_reg_const_str(struct bpf_verifier_env *env, 9544 struct bpf_reg_state *reg, u32 regno) 9545 { 9546 struct bpf_map *map = reg->map_ptr; 9547 int err; 9548 int map_off; 9549 u64 map_addr; 9550 char *str_ptr; 9551 9552 if (reg->type != PTR_TO_MAP_VALUE) 9553 return -EINVAL; 9554 9555 if (!bpf_map_is_rdonly(map)) { 9556 verbose(env, "R%d does not point to a readonly map'\n", regno); 9557 return -EACCES; 9558 } 9559 9560 if (!tnum_is_const(reg->var_off)) { 9561 verbose(env, "R%d is not a constant address'\n", regno); 9562 return -EACCES; 9563 } 9564 9565 if (!map->ops->map_direct_value_addr) { 9566 verbose(env, "no direct value access support for this map type\n"); 9567 return -EACCES; 9568 } 9569 9570 err = check_map_access(env, regno, reg->off, 9571 map->value_size - reg->off, false, 9572 ACCESS_HELPER); 9573 if (err) 9574 return err; 9575 9576 map_off = reg->off + reg->var_off.value; 9577 err = map->ops->map_direct_value_addr(map, &map_addr, map_off); 9578 if (err) { 9579 verbose(env, "direct value access on string failed\n"); 9580 return err; 9581 } 9582 9583 str_ptr = (char *)(long)(map_addr); 9584 if (!strnchr(str_ptr + map_off, map->value_size - map_off, 0)) { 9585 verbose(env, "string is not zero-terminated\n"); 9586 return -EINVAL; 9587 } 9588 return 0; 9589 } 9590 9591 /* Returns constant key value in `value` if possible, else negative error */ 9592 static int get_constant_map_key(struct bpf_verifier_env *env, 9593 struct bpf_reg_state *key, 9594 u32 key_size, 9595 s64 *value) 9596 { 9597 struct bpf_func_state *state = func(env, key); 9598 struct bpf_reg_state *reg; 9599 int slot, spi, off; 9600 int spill_size = 0; 9601 int zero_size = 0; 9602 int stack_off; 9603 int i, err; 9604 u8 *stype; 9605 9606 if (!env->bpf_capable) 9607 return -EOPNOTSUPP; 9608 if (key->type != PTR_TO_STACK) 9609 return -EOPNOTSUPP; 9610 if (!tnum_is_const(key->var_off)) 9611 return -EOPNOTSUPP; 9612 9613 stack_off = key->off + key->var_off.value; 9614 slot = -stack_off - 1; 9615 spi = slot / BPF_REG_SIZE; 9616 off = slot % BPF_REG_SIZE; 9617 stype = state->stack[spi].slot_type; 9618 9619 /* First handle precisely tracked STACK_ZERO */ 9620 for (i = off; i >= 0 && stype[i] == STACK_ZERO; i--) 9621 zero_size++; 9622 if (zero_size >= key_size) { 9623 *value = 0; 9624 return 0; 9625 } 9626 9627 /* Check that stack contains a scalar spill of expected size */ 9628 if (!is_spilled_scalar_reg(&state->stack[spi])) 9629 return -EOPNOTSUPP; 9630 for (i = off; i >= 0 && stype[i] == STACK_SPILL; i--) 9631 spill_size++; 9632 if (spill_size != key_size) 9633 return -EOPNOTSUPP; 9634 9635 reg = &state->stack[spi].spilled_ptr; 9636 if (!tnum_is_const(reg->var_off)) 9637 /* Stack value not statically known */ 9638 return -EOPNOTSUPP; 9639 9640 /* We are relying on a constant value. So mark as precise 9641 * to prevent pruning on it. 9642 */ 9643 bt_set_frame_slot(&env->bt, key->frameno, spi); 9644 err = mark_chain_precision_batch(env, env->cur_state); 9645 if (err < 0) 9646 return err; 9647 9648 *value = reg->var_off.value; 9649 return 0; 9650 } 9651 9652 static bool can_elide_value_nullness(enum bpf_map_type type); 9653 9654 static int check_func_arg(struct bpf_verifier_env *env, u32 arg, 9655 struct bpf_call_arg_meta *meta, 9656 const struct bpf_func_proto *fn, 9657 int insn_idx) 9658 { 9659 u32 regno = BPF_REG_1 + arg; 9660 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno]; 9661 enum bpf_arg_type arg_type = fn->arg_type[arg]; 9662 enum bpf_reg_type type = reg->type; 9663 u32 *arg_btf_id = NULL; 9664 u32 key_size; 9665 int err = 0; 9666 9667 if (arg_type == ARG_DONTCARE) 9668 return 0; 9669 9670 err = check_reg_arg(env, regno, SRC_OP); 9671 if (err) 9672 return err; 9673 9674 if (arg_type == ARG_ANYTHING) { 9675 if (is_pointer_value(env, regno)) { 9676 verbose(env, "R%d leaks addr into helper function\n", 9677 regno); 9678 return -EACCES; 9679 } 9680 return 0; 9681 } 9682 9683 if (type_is_pkt_pointer(type) && 9684 !may_access_direct_pkt_data(env, meta, BPF_READ)) { 9685 verbose(env, "helper access to the packet is not allowed\n"); 9686 return -EACCES; 9687 } 9688 9689 if (base_type(arg_type) == ARG_PTR_TO_MAP_VALUE) { 9690 err = resolve_map_arg_type(env, meta, &arg_type); 9691 if (err) 9692 return err; 9693 } 9694 9695 if (register_is_null(reg) && type_may_be_null(arg_type)) 9696 /* A NULL register has a SCALAR_VALUE type, so skip 9697 * type checking. 9698 */ 9699 goto skip_type_check; 9700 9701 /* arg_btf_id and arg_size are in a union. */ 9702 if (base_type(arg_type) == ARG_PTR_TO_BTF_ID || 9703 base_type(arg_type) == ARG_PTR_TO_SPIN_LOCK) 9704 arg_btf_id = fn->arg_btf_id[arg]; 9705 9706 err = check_reg_type(env, regno, arg_type, arg_btf_id, meta); 9707 if (err) 9708 return err; 9709 9710 err = check_func_arg_reg_off(env, reg, regno, arg_type); 9711 if (err) 9712 return err; 9713 9714 skip_type_check: 9715 if (arg_type_is_release(arg_type)) { 9716 if (arg_type_is_dynptr(arg_type)) { 9717 struct bpf_func_state *state = func(env, reg); 9718 int spi; 9719 9720 /* Only dynptr created on stack can be released, thus 9721 * the get_spi and stack state checks for spilled_ptr 9722 * should only be done before process_dynptr_func for 9723 * PTR_TO_STACK. 9724 */ 9725 if (reg->type == PTR_TO_STACK) { 9726 spi = dynptr_get_spi(env, reg); 9727 if (spi < 0 || !state->stack[spi].spilled_ptr.ref_obj_id) { 9728 verbose(env, "arg %d is an unacquired reference\n", regno); 9729 return -EINVAL; 9730 } 9731 } else { 9732 verbose(env, "cannot release unowned const bpf_dynptr\n"); 9733 return -EINVAL; 9734 } 9735 } else if (!reg->ref_obj_id && !register_is_null(reg)) { 9736 verbose(env, "R%d must be referenced when passed to release function\n", 9737 regno); 9738 return -EINVAL; 9739 } 9740 if (meta->release_regno) { 9741 verifier_bug(env, "more than one release argument"); 9742 return -EFAULT; 9743 } 9744 meta->release_regno = regno; 9745 } 9746 9747 if (reg->ref_obj_id && base_type(arg_type) != ARG_KPTR_XCHG_DEST) { 9748 if (meta->ref_obj_id) { 9749 verbose(env, "more than one arg with ref_obj_id R%d %u %u", 9750 regno, reg->ref_obj_id, 9751 meta->ref_obj_id); 9752 return -EACCES; 9753 } 9754 meta->ref_obj_id = reg->ref_obj_id; 9755 } 9756 9757 switch (base_type(arg_type)) { 9758 case ARG_CONST_MAP_PTR: 9759 /* bpf_map_xxx(map_ptr) call: remember that map_ptr */ 9760 if (meta->map_ptr) { 9761 /* Use map_uid (which is unique id of inner map) to reject: 9762 * inner_map1 = bpf_map_lookup_elem(outer_map, key1) 9763 * inner_map2 = bpf_map_lookup_elem(outer_map, key2) 9764 * if (inner_map1 && inner_map2) { 9765 * timer = bpf_map_lookup_elem(inner_map1); 9766 * if (timer) 9767 * // mismatch would have been allowed 9768 * bpf_timer_init(timer, inner_map2); 9769 * } 9770 * 9771 * Comparing map_ptr is enough to distinguish normal and outer maps. 9772 */ 9773 if (meta->map_ptr != reg->map_ptr || 9774 meta->map_uid != reg->map_uid) { 9775 verbose(env, 9776 "timer pointer in R1 map_uid=%d doesn't match map pointer in R2 map_uid=%d\n", 9777 meta->map_uid, reg->map_uid); 9778 return -EINVAL; 9779 } 9780 } 9781 meta->map_ptr = reg->map_ptr; 9782 meta->map_uid = reg->map_uid; 9783 break; 9784 case ARG_PTR_TO_MAP_KEY: 9785 /* bpf_map_xxx(..., map_ptr, ..., key) call: 9786 * check that [key, key + map->key_size) are within 9787 * stack limits and initialized 9788 */ 9789 if (!meta->map_ptr) { 9790 /* in function declaration map_ptr must come before 9791 * map_key, so that it's verified and known before 9792 * we have to check map_key here. Otherwise it means 9793 * that kernel subsystem misconfigured verifier 9794 */ 9795 verifier_bug(env, "invalid map_ptr to access map->key"); 9796 return -EFAULT; 9797 } 9798 key_size = meta->map_ptr->key_size; 9799 err = check_helper_mem_access(env, regno, key_size, BPF_READ, false, NULL); 9800 if (err) 9801 return err; 9802 if (can_elide_value_nullness(meta->map_ptr->map_type)) { 9803 err = get_constant_map_key(env, reg, key_size, &meta->const_map_key); 9804 if (err < 0) { 9805 meta->const_map_key = -1; 9806 if (err == -EOPNOTSUPP) 9807 err = 0; 9808 else 9809 return err; 9810 } 9811 } 9812 break; 9813 case ARG_PTR_TO_MAP_VALUE: 9814 if (type_may_be_null(arg_type) && register_is_null(reg)) 9815 return 0; 9816 9817 /* bpf_map_xxx(..., map_ptr, ..., value) call: 9818 * check [value, value + map->value_size) validity 9819 */ 9820 if (!meta->map_ptr) { 9821 /* kernel subsystem misconfigured verifier */ 9822 verifier_bug(env, "invalid map_ptr to access map->value"); 9823 return -EFAULT; 9824 } 9825 meta->raw_mode = arg_type & MEM_UNINIT; 9826 err = check_helper_mem_access(env, regno, meta->map_ptr->value_size, 9827 arg_type & MEM_WRITE ? BPF_WRITE : BPF_READ, 9828 false, meta); 9829 break; 9830 case ARG_PTR_TO_PERCPU_BTF_ID: 9831 if (!reg->btf_id) { 9832 verbose(env, "Helper has invalid btf_id in R%d\n", regno); 9833 return -EACCES; 9834 } 9835 meta->ret_btf = reg->btf; 9836 meta->ret_btf_id = reg->btf_id; 9837 break; 9838 case ARG_PTR_TO_SPIN_LOCK: 9839 if (in_rbtree_lock_required_cb(env)) { 9840 verbose(env, "can't spin_{lock,unlock} in rbtree cb\n"); 9841 return -EACCES; 9842 } 9843 if (meta->func_id == BPF_FUNC_spin_lock) { 9844 err = process_spin_lock(env, regno, PROCESS_SPIN_LOCK); 9845 if (err) 9846 return err; 9847 } else if (meta->func_id == BPF_FUNC_spin_unlock) { 9848 err = process_spin_lock(env, regno, 0); 9849 if (err) 9850 return err; 9851 } else { 9852 verifier_bug(env, "spin lock arg on unexpected helper"); 9853 return -EFAULT; 9854 } 9855 break; 9856 case ARG_PTR_TO_TIMER: 9857 err = process_timer_func(env, regno, meta); 9858 if (err) 9859 return err; 9860 break; 9861 case ARG_PTR_TO_FUNC: 9862 meta->subprogno = reg->subprogno; 9863 break; 9864 case ARG_PTR_TO_MEM: 9865 /* The access to this pointer is only checked when we hit the 9866 * next is_mem_size argument below. 9867 */ 9868 meta->raw_mode = arg_type & MEM_UNINIT; 9869 if (arg_type & MEM_FIXED_SIZE) { 9870 err = check_helper_mem_access(env, regno, fn->arg_size[arg], 9871 arg_type & MEM_WRITE ? BPF_WRITE : BPF_READ, 9872 false, meta); 9873 if (err) 9874 return err; 9875 if (arg_type & MEM_ALIGNED) 9876 err = check_ptr_alignment(env, reg, 0, fn->arg_size[arg], true); 9877 } 9878 break; 9879 case ARG_CONST_SIZE: 9880 err = check_mem_size_reg(env, reg, regno, 9881 fn->arg_type[arg - 1] & MEM_WRITE ? 9882 BPF_WRITE : BPF_READ, 9883 false, meta); 9884 break; 9885 case ARG_CONST_SIZE_OR_ZERO: 9886 err = check_mem_size_reg(env, reg, regno, 9887 fn->arg_type[arg - 1] & MEM_WRITE ? 9888 BPF_WRITE : BPF_READ, 9889 true, meta); 9890 break; 9891 case ARG_PTR_TO_DYNPTR: 9892 err = process_dynptr_func(env, regno, insn_idx, arg_type, 0); 9893 if (err) 9894 return err; 9895 break; 9896 case ARG_CONST_ALLOC_SIZE_OR_ZERO: 9897 if (!tnum_is_const(reg->var_off)) { 9898 verbose(env, "R%d is not a known constant'\n", 9899 regno); 9900 return -EACCES; 9901 } 9902 meta->mem_size = reg->var_off.value; 9903 err = mark_chain_precision(env, regno); 9904 if (err) 9905 return err; 9906 break; 9907 case ARG_PTR_TO_CONST_STR: 9908 { 9909 err = check_reg_const_str(env, reg, regno); 9910 if (err) 9911 return err; 9912 break; 9913 } 9914 case ARG_KPTR_XCHG_DEST: 9915 err = process_kptr_func(env, regno, meta); 9916 if (err) 9917 return err; 9918 break; 9919 } 9920 9921 return err; 9922 } 9923 9924 static bool may_update_sockmap(struct bpf_verifier_env *env, int func_id) 9925 { 9926 enum bpf_attach_type eatype = env->prog->expected_attach_type; 9927 enum bpf_prog_type type = resolve_prog_type(env->prog); 9928 9929 if (func_id != BPF_FUNC_map_update_elem && 9930 func_id != BPF_FUNC_map_delete_elem) 9931 return false; 9932 9933 /* It's not possible to get access to a locked struct sock in these 9934 * contexts, so updating is safe. 9935 */ 9936 switch (type) { 9937 case BPF_PROG_TYPE_TRACING: 9938 if (eatype == BPF_TRACE_ITER) 9939 return true; 9940 break; 9941 case BPF_PROG_TYPE_SOCK_OPS: 9942 /* map_update allowed only via dedicated helpers with event type checks */ 9943 if (func_id == BPF_FUNC_map_delete_elem) 9944 return true; 9945 break; 9946 case BPF_PROG_TYPE_SOCKET_FILTER: 9947 case BPF_PROG_TYPE_SCHED_CLS: 9948 case BPF_PROG_TYPE_SCHED_ACT: 9949 case BPF_PROG_TYPE_XDP: 9950 case BPF_PROG_TYPE_SK_REUSEPORT: 9951 case BPF_PROG_TYPE_FLOW_DISSECTOR: 9952 case BPF_PROG_TYPE_SK_LOOKUP: 9953 return true; 9954 default: 9955 break; 9956 } 9957 9958 verbose(env, "cannot update sockmap in this context\n"); 9959 return false; 9960 } 9961 9962 static bool allow_tail_call_in_subprogs(struct bpf_verifier_env *env) 9963 { 9964 return env->prog->jit_requested && 9965 bpf_jit_supports_subprog_tailcalls(); 9966 } 9967 9968 static int check_map_func_compatibility(struct bpf_verifier_env *env, 9969 struct bpf_map *map, int func_id) 9970 { 9971 if (!map) 9972 return 0; 9973 9974 /* We need a two way check, first is from map perspective ... */ 9975 switch (map->map_type) { 9976 case BPF_MAP_TYPE_PROG_ARRAY: 9977 if (func_id != BPF_FUNC_tail_call) 9978 goto error; 9979 break; 9980 case BPF_MAP_TYPE_PERF_EVENT_ARRAY: 9981 if (func_id != BPF_FUNC_perf_event_read && 9982 func_id != BPF_FUNC_perf_event_output && 9983 func_id != BPF_FUNC_skb_output && 9984 func_id != BPF_FUNC_perf_event_read_value && 9985 func_id != BPF_FUNC_xdp_output) 9986 goto error; 9987 break; 9988 case BPF_MAP_TYPE_RINGBUF: 9989 if (func_id != BPF_FUNC_ringbuf_output && 9990 func_id != BPF_FUNC_ringbuf_reserve && 9991 func_id != BPF_FUNC_ringbuf_query && 9992 func_id != BPF_FUNC_ringbuf_reserve_dynptr && 9993 func_id != BPF_FUNC_ringbuf_submit_dynptr && 9994 func_id != BPF_FUNC_ringbuf_discard_dynptr) 9995 goto error; 9996 break; 9997 case BPF_MAP_TYPE_USER_RINGBUF: 9998 if (func_id != BPF_FUNC_user_ringbuf_drain) 9999 goto error; 10000 break; 10001 case BPF_MAP_TYPE_STACK_TRACE: 10002 if (func_id != BPF_FUNC_get_stackid) 10003 goto error; 10004 break; 10005 case BPF_MAP_TYPE_CGROUP_ARRAY: 10006 if (func_id != BPF_FUNC_skb_under_cgroup && 10007 func_id != BPF_FUNC_current_task_under_cgroup) 10008 goto error; 10009 break; 10010 case BPF_MAP_TYPE_CGROUP_STORAGE: 10011 case BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE: 10012 if (func_id != BPF_FUNC_get_local_storage) 10013 goto error; 10014 break; 10015 case BPF_MAP_TYPE_DEVMAP: 10016 case BPF_MAP_TYPE_DEVMAP_HASH: 10017 if (func_id != BPF_FUNC_redirect_map && 10018 func_id != BPF_FUNC_map_lookup_elem) 10019 goto error; 10020 break; 10021 /* Restrict bpf side of cpumap and xskmap, open when use-cases 10022 * appear. 10023 */ 10024 case BPF_MAP_TYPE_CPUMAP: 10025 if (func_id != BPF_FUNC_redirect_map) 10026 goto error; 10027 break; 10028 case BPF_MAP_TYPE_XSKMAP: 10029 if (func_id != BPF_FUNC_redirect_map && 10030 func_id != BPF_FUNC_map_lookup_elem) 10031 goto error; 10032 break; 10033 case BPF_MAP_TYPE_ARRAY_OF_MAPS: 10034 case BPF_MAP_TYPE_HASH_OF_MAPS: 10035 if (func_id != BPF_FUNC_map_lookup_elem) 10036 goto error; 10037 break; 10038 case BPF_MAP_TYPE_SOCKMAP: 10039 if (func_id != BPF_FUNC_sk_redirect_map && 10040 func_id != BPF_FUNC_sock_map_update && 10041 func_id != BPF_FUNC_msg_redirect_map && 10042 func_id != BPF_FUNC_sk_select_reuseport && 10043 func_id != BPF_FUNC_map_lookup_elem && 10044 !may_update_sockmap(env, func_id)) 10045 goto error; 10046 break; 10047 case BPF_MAP_TYPE_SOCKHASH: 10048 if (func_id != BPF_FUNC_sk_redirect_hash && 10049 func_id != BPF_FUNC_sock_hash_update && 10050 func_id != BPF_FUNC_msg_redirect_hash && 10051 func_id != BPF_FUNC_sk_select_reuseport && 10052 func_id != BPF_FUNC_map_lookup_elem && 10053 !may_update_sockmap(env, func_id)) 10054 goto error; 10055 break; 10056 case BPF_MAP_TYPE_REUSEPORT_SOCKARRAY: 10057 if (func_id != BPF_FUNC_sk_select_reuseport) 10058 goto error; 10059 break; 10060 case BPF_MAP_TYPE_QUEUE: 10061 case BPF_MAP_TYPE_STACK: 10062 if (func_id != BPF_FUNC_map_peek_elem && 10063 func_id != BPF_FUNC_map_pop_elem && 10064 func_id != BPF_FUNC_map_push_elem) 10065 goto error; 10066 break; 10067 case BPF_MAP_TYPE_SK_STORAGE: 10068 if (func_id != BPF_FUNC_sk_storage_get && 10069 func_id != BPF_FUNC_sk_storage_delete && 10070 func_id != BPF_FUNC_kptr_xchg) 10071 goto error; 10072 break; 10073 case BPF_MAP_TYPE_INODE_STORAGE: 10074 if (func_id != BPF_FUNC_inode_storage_get && 10075 func_id != BPF_FUNC_inode_storage_delete && 10076 func_id != BPF_FUNC_kptr_xchg) 10077 goto error; 10078 break; 10079 case BPF_MAP_TYPE_TASK_STORAGE: 10080 if (func_id != BPF_FUNC_task_storage_get && 10081 func_id != BPF_FUNC_task_storage_delete && 10082 func_id != BPF_FUNC_kptr_xchg) 10083 goto error; 10084 break; 10085 case BPF_MAP_TYPE_CGRP_STORAGE: 10086 if (func_id != BPF_FUNC_cgrp_storage_get && 10087 func_id != BPF_FUNC_cgrp_storage_delete && 10088 func_id != BPF_FUNC_kptr_xchg) 10089 goto error; 10090 break; 10091 case BPF_MAP_TYPE_BLOOM_FILTER: 10092 if (func_id != BPF_FUNC_map_peek_elem && 10093 func_id != BPF_FUNC_map_push_elem) 10094 goto error; 10095 break; 10096 default: 10097 break; 10098 } 10099 10100 /* ... and second from the function itself. */ 10101 switch (func_id) { 10102 case BPF_FUNC_tail_call: 10103 if (map->map_type != BPF_MAP_TYPE_PROG_ARRAY) 10104 goto error; 10105 if (env->subprog_cnt > 1 && !allow_tail_call_in_subprogs(env)) { 10106 verbose(env, "mixing of tail_calls and bpf-to-bpf calls is not supported\n"); 10107 return -EINVAL; 10108 } 10109 break; 10110 case BPF_FUNC_perf_event_read: 10111 case BPF_FUNC_perf_event_output: 10112 case BPF_FUNC_perf_event_read_value: 10113 case BPF_FUNC_skb_output: 10114 case BPF_FUNC_xdp_output: 10115 if (map->map_type != BPF_MAP_TYPE_PERF_EVENT_ARRAY) 10116 goto error; 10117 break; 10118 case BPF_FUNC_ringbuf_output: 10119 case BPF_FUNC_ringbuf_reserve: 10120 case BPF_FUNC_ringbuf_query: 10121 case BPF_FUNC_ringbuf_reserve_dynptr: 10122 case BPF_FUNC_ringbuf_submit_dynptr: 10123 case BPF_FUNC_ringbuf_discard_dynptr: 10124 if (map->map_type != BPF_MAP_TYPE_RINGBUF) 10125 goto error; 10126 break; 10127 case BPF_FUNC_user_ringbuf_drain: 10128 if (map->map_type != BPF_MAP_TYPE_USER_RINGBUF) 10129 goto error; 10130 break; 10131 case BPF_FUNC_get_stackid: 10132 if (map->map_type != BPF_MAP_TYPE_STACK_TRACE) 10133 goto error; 10134 break; 10135 case BPF_FUNC_current_task_under_cgroup: 10136 case BPF_FUNC_skb_under_cgroup: 10137 if (map->map_type != BPF_MAP_TYPE_CGROUP_ARRAY) 10138 goto error; 10139 break; 10140 case BPF_FUNC_redirect_map: 10141 if (map->map_type != BPF_MAP_TYPE_DEVMAP && 10142 map->map_type != BPF_MAP_TYPE_DEVMAP_HASH && 10143 map->map_type != BPF_MAP_TYPE_CPUMAP && 10144 map->map_type != BPF_MAP_TYPE_XSKMAP) 10145 goto error; 10146 break; 10147 case BPF_FUNC_sk_redirect_map: 10148 case BPF_FUNC_msg_redirect_map: 10149 case BPF_FUNC_sock_map_update: 10150 if (map->map_type != BPF_MAP_TYPE_SOCKMAP) 10151 goto error; 10152 break; 10153 case BPF_FUNC_sk_redirect_hash: 10154 case BPF_FUNC_msg_redirect_hash: 10155 case BPF_FUNC_sock_hash_update: 10156 if (map->map_type != BPF_MAP_TYPE_SOCKHASH) 10157 goto error; 10158 break; 10159 case BPF_FUNC_get_local_storage: 10160 if (map->map_type != BPF_MAP_TYPE_CGROUP_STORAGE && 10161 map->map_type != BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE) 10162 goto error; 10163 break; 10164 case BPF_FUNC_sk_select_reuseport: 10165 if (map->map_type != BPF_MAP_TYPE_REUSEPORT_SOCKARRAY && 10166 map->map_type != BPF_MAP_TYPE_SOCKMAP && 10167 map->map_type != BPF_MAP_TYPE_SOCKHASH) 10168 goto error; 10169 break; 10170 case BPF_FUNC_map_pop_elem: 10171 if (map->map_type != BPF_MAP_TYPE_QUEUE && 10172 map->map_type != BPF_MAP_TYPE_STACK) 10173 goto error; 10174 break; 10175 case BPF_FUNC_map_peek_elem: 10176 case BPF_FUNC_map_push_elem: 10177 if (map->map_type != BPF_MAP_TYPE_QUEUE && 10178 map->map_type != BPF_MAP_TYPE_STACK && 10179 map->map_type != BPF_MAP_TYPE_BLOOM_FILTER) 10180 goto error; 10181 break; 10182 case BPF_FUNC_map_lookup_percpu_elem: 10183 if (map->map_type != BPF_MAP_TYPE_PERCPU_ARRAY && 10184 map->map_type != BPF_MAP_TYPE_PERCPU_HASH && 10185 map->map_type != BPF_MAP_TYPE_LRU_PERCPU_HASH) 10186 goto error; 10187 break; 10188 case BPF_FUNC_sk_storage_get: 10189 case BPF_FUNC_sk_storage_delete: 10190 if (map->map_type != BPF_MAP_TYPE_SK_STORAGE) 10191 goto error; 10192 break; 10193 case BPF_FUNC_inode_storage_get: 10194 case BPF_FUNC_inode_storage_delete: 10195 if (map->map_type != BPF_MAP_TYPE_INODE_STORAGE) 10196 goto error; 10197 break; 10198 case BPF_FUNC_task_storage_get: 10199 case BPF_FUNC_task_storage_delete: 10200 if (map->map_type != BPF_MAP_TYPE_TASK_STORAGE) 10201 goto error; 10202 break; 10203 case BPF_FUNC_cgrp_storage_get: 10204 case BPF_FUNC_cgrp_storage_delete: 10205 if (map->map_type != BPF_MAP_TYPE_CGRP_STORAGE) 10206 goto error; 10207 break; 10208 default: 10209 break; 10210 } 10211 10212 return 0; 10213 error: 10214 verbose(env, "cannot pass map_type %d into func %s#%d\n", 10215 map->map_type, func_id_name(func_id), func_id); 10216 return -EINVAL; 10217 } 10218 10219 static bool check_raw_mode_ok(const struct bpf_func_proto *fn) 10220 { 10221 int count = 0; 10222 10223 if (arg_type_is_raw_mem(fn->arg1_type)) 10224 count++; 10225 if (arg_type_is_raw_mem(fn->arg2_type)) 10226 count++; 10227 if (arg_type_is_raw_mem(fn->arg3_type)) 10228 count++; 10229 if (arg_type_is_raw_mem(fn->arg4_type)) 10230 count++; 10231 if (arg_type_is_raw_mem(fn->arg5_type)) 10232 count++; 10233 10234 /* We only support one arg being in raw mode at the moment, 10235 * which is sufficient for the helper functions we have 10236 * right now. 10237 */ 10238 return count <= 1; 10239 } 10240 10241 static bool check_args_pair_invalid(const struct bpf_func_proto *fn, int arg) 10242 { 10243 bool is_fixed = fn->arg_type[arg] & MEM_FIXED_SIZE; 10244 bool has_size = fn->arg_size[arg] != 0; 10245 bool is_next_size = false; 10246 10247 if (arg + 1 < ARRAY_SIZE(fn->arg_type)) 10248 is_next_size = arg_type_is_mem_size(fn->arg_type[arg + 1]); 10249 10250 if (base_type(fn->arg_type[arg]) != ARG_PTR_TO_MEM) 10251 return is_next_size; 10252 10253 return has_size == is_next_size || is_next_size == is_fixed; 10254 } 10255 10256 static bool check_arg_pair_ok(const struct bpf_func_proto *fn) 10257 { 10258 /* bpf_xxx(..., buf, len) call will access 'len' 10259 * bytes from memory 'buf'. Both arg types need 10260 * to be paired, so make sure there's no buggy 10261 * helper function specification. 10262 */ 10263 if (arg_type_is_mem_size(fn->arg1_type) || 10264 check_args_pair_invalid(fn, 0) || 10265 check_args_pair_invalid(fn, 1) || 10266 check_args_pair_invalid(fn, 2) || 10267 check_args_pair_invalid(fn, 3) || 10268 check_args_pair_invalid(fn, 4)) 10269 return false; 10270 10271 return true; 10272 } 10273 10274 static bool check_btf_id_ok(const struct bpf_func_proto *fn) 10275 { 10276 int i; 10277 10278 for (i = 0; i < ARRAY_SIZE(fn->arg_type); i++) { 10279 if (base_type(fn->arg_type[i]) == ARG_PTR_TO_BTF_ID) 10280 return !!fn->arg_btf_id[i]; 10281 if (base_type(fn->arg_type[i]) == ARG_PTR_TO_SPIN_LOCK) 10282 return fn->arg_btf_id[i] == BPF_PTR_POISON; 10283 if (base_type(fn->arg_type[i]) != ARG_PTR_TO_BTF_ID && fn->arg_btf_id[i] && 10284 /* arg_btf_id and arg_size are in a union. */ 10285 (base_type(fn->arg_type[i]) != ARG_PTR_TO_MEM || 10286 !(fn->arg_type[i] & MEM_FIXED_SIZE))) 10287 return false; 10288 } 10289 10290 return true; 10291 } 10292 10293 static int check_func_proto(const struct bpf_func_proto *fn, int func_id) 10294 { 10295 return check_raw_mode_ok(fn) && 10296 check_arg_pair_ok(fn) && 10297 check_btf_id_ok(fn) ? 0 : -EINVAL; 10298 } 10299 10300 /* Packet data might have moved, any old PTR_TO_PACKET[_META,_END] 10301 * are now invalid, so turn them into unknown SCALAR_VALUE. 10302 * 10303 * This also applies to dynptr slices belonging to skb and xdp dynptrs, 10304 * since these slices point to packet data. 10305 */ 10306 static void clear_all_pkt_pointers(struct bpf_verifier_env *env) 10307 { 10308 struct bpf_func_state *state; 10309 struct bpf_reg_state *reg; 10310 10311 bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({ 10312 if (reg_is_pkt_pointer_any(reg) || reg_is_dynptr_slice_pkt(reg)) 10313 mark_reg_invalid(env, reg); 10314 })); 10315 } 10316 10317 enum { 10318 AT_PKT_END = -1, 10319 BEYOND_PKT_END = -2, 10320 }; 10321 10322 static void mark_pkt_end(struct bpf_verifier_state *vstate, int regn, bool range_open) 10323 { 10324 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 10325 struct bpf_reg_state *reg = &state->regs[regn]; 10326 10327 if (reg->type != PTR_TO_PACKET) 10328 /* PTR_TO_PACKET_META is not supported yet */ 10329 return; 10330 10331 /* The 'reg' is pkt > pkt_end or pkt >= pkt_end. 10332 * How far beyond pkt_end it goes is unknown. 10333 * if (!range_open) it's the case of pkt >= pkt_end 10334 * if (range_open) it's the case of pkt > pkt_end 10335 * hence this pointer is at least 1 byte bigger than pkt_end 10336 */ 10337 if (range_open) 10338 reg->range = BEYOND_PKT_END; 10339 else 10340 reg->range = AT_PKT_END; 10341 } 10342 10343 static int release_reference_nomark(struct bpf_verifier_state *state, int ref_obj_id) 10344 { 10345 int i; 10346 10347 for (i = 0; i < state->acquired_refs; i++) { 10348 if (state->refs[i].type != REF_TYPE_PTR) 10349 continue; 10350 if (state->refs[i].id == ref_obj_id) { 10351 release_reference_state(state, i); 10352 return 0; 10353 } 10354 } 10355 return -EINVAL; 10356 } 10357 10358 /* The pointer with the specified id has released its reference to kernel 10359 * resources. Identify all copies of the same pointer and clear the reference. 10360 * 10361 * This is the release function corresponding to acquire_reference(). Idempotent. 10362 */ 10363 static int release_reference(struct bpf_verifier_env *env, int ref_obj_id) 10364 { 10365 struct bpf_verifier_state *vstate = env->cur_state; 10366 struct bpf_func_state *state; 10367 struct bpf_reg_state *reg; 10368 int err; 10369 10370 err = release_reference_nomark(vstate, ref_obj_id); 10371 if (err) 10372 return err; 10373 10374 bpf_for_each_reg_in_vstate(vstate, state, reg, ({ 10375 if (reg->ref_obj_id == ref_obj_id) 10376 mark_reg_invalid(env, reg); 10377 })); 10378 10379 return 0; 10380 } 10381 10382 static void invalidate_non_owning_refs(struct bpf_verifier_env *env) 10383 { 10384 struct bpf_func_state *unused; 10385 struct bpf_reg_state *reg; 10386 10387 bpf_for_each_reg_in_vstate(env->cur_state, unused, reg, ({ 10388 if (type_is_non_owning_ref(reg->type)) 10389 mark_reg_invalid(env, reg); 10390 })); 10391 } 10392 10393 static void clear_caller_saved_regs(struct bpf_verifier_env *env, 10394 struct bpf_reg_state *regs) 10395 { 10396 int i; 10397 10398 /* after the call registers r0 - r5 were scratched */ 10399 for (i = 0; i < CALLER_SAVED_REGS; i++) { 10400 mark_reg_not_init(env, regs, caller_saved[i]); 10401 __check_reg_arg(env, regs, caller_saved[i], DST_OP_NO_MARK); 10402 } 10403 } 10404 10405 typedef int (*set_callee_state_fn)(struct bpf_verifier_env *env, 10406 struct bpf_func_state *caller, 10407 struct bpf_func_state *callee, 10408 int insn_idx); 10409 10410 static int set_callee_state(struct bpf_verifier_env *env, 10411 struct bpf_func_state *caller, 10412 struct bpf_func_state *callee, int insn_idx); 10413 10414 static int setup_func_entry(struct bpf_verifier_env *env, int subprog, int callsite, 10415 set_callee_state_fn set_callee_state_cb, 10416 struct bpf_verifier_state *state) 10417 { 10418 struct bpf_func_state *caller, *callee; 10419 int err; 10420 10421 if (state->curframe + 1 >= MAX_CALL_FRAMES) { 10422 verbose(env, "the call stack of %d frames is too deep\n", 10423 state->curframe + 2); 10424 return -E2BIG; 10425 } 10426 10427 if (state->frame[state->curframe + 1]) { 10428 verifier_bug(env, "Frame %d already allocated", state->curframe + 1); 10429 return -EFAULT; 10430 } 10431 10432 caller = state->frame[state->curframe]; 10433 callee = kzalloc(sizeof(*callee), GFP_KERNEL_ACCOUNT); 10434 if (!callee) 10435 return -ENOMEM; 10436 state->frame[state->curframe + 1] = callee; 10437 10438 /* callee cannot access r0, r6 - r9 for reading and has to write 10439 * into its own stack before reading from it. 10440 * callee can read/write into caller's stack 10441 */ 10442 init_func_state(env, callee, 10443 /* remember the callsite, it will be used by bpf_exit */ 10444 callsite, 10445 state->curframe + 1 /* frameno within this callchain */, 10446 subprog /* subprog number within this prog */); 10447 err = set_callee_state_cb(env, caller, callee, callsite); 10448 if (err) 10449 goto err_out; 10450 10451 /* only increment it after check_reg_arg() finished */ 10452 state->curframe++; 10453 10454 return 0; 10455 10456 err_out: 10457 free_func_state(callee); 10458 state->frame[state->curframe + 1] = NULL; 10459 return err; 10460 } 10461 10462 static int btf_check_func_arg_match(struct bpf_verifier_env *env, int subprog, 10463 const struct btf *btf, 10464 struct bpf_reg_state *regs) 10465 { 10466 struct bpf_subprog_info *sub = subprog_info(env, subprog); 10467 struct bpf_verifier_log *log = &env->log; 10468 u32 i; 10469 int ret; 10470 10471 ret = btf_prepare_func_args(env, subprog); 10472 if (ret) 10473 return ret; 10474 10475 /* check that BTF function arguments match actual types that the 10476 * verifier sees. 10477 */ 10478 for (i = 0; i < sub->arg_cnt; i++) { 10479 u32 regno = i + 1; 10480 struct bpf_reg_state *reg = ®s[regno]; 10481 struct bpf_subprog_arg_info *arg = &sub->args[i]; 10482 10483 if (arg->arg_type == ARG_ANYTHING) { 10484 if (reg->type != SCALAR_VALUE) { 10485 bpf_log(log, "R%d is not a scalar\n", regno); 10486 return -EINVAL; 10487 } 10488 } else if (arg->arg_type & PTR_UNTRUSTED) { 10489 /* 10490 * Anything is allowed for untrusted arguments, as these are 10491 * read-only and probe read instructions would protect against 10492 * invalid memory access. 10493 */ 10494 } else if (arg->arg_type == ARG_PTR_TO_CTX) { 10495 ret = check_func_arg_reg_off(env, reg, regno, ARG_DONTCARE); 10496 if (ret < 0) 10497 return ret; 10498 /* If function expects ctx type in BTF check that caller 10499 * is passing PTR_TO_CTX. 10500 */ 10501 if (reg->type != PTR_TO_CTX) { 10502 bpf_log(log, "arg#%d expects pointer to ctx\n", i); 10503 return -EINVAL; 10504 } 10505 } else if (base_type(arg->arg_type) == ARG_PTR_TO_MEM) { 10506 ret = check_func_arg_reg_off(env, reg, regno, ARG_DONTCARE); 10507 if (ret < 0) 10508 return ret; 10509 if (check_mem_reg(env, reg, regno, arg->mem_size)) 10510 return -EINVAL; 10511 if (!(arg->arg_type & PTR_MAYBE_NULL) && (reg->type & PTR_MAYBE_NULL)) { 10512 bpf_log(log, "arg#%d is expected to be non-NULL\n", i); 10513 return -EINVAL; 10514 } 10515 } else if (base_type(arg->arg_type) == ARG_PTR_TO_ARENA) { 10516 /* 10517 * Can pass any value and the kernel won't crash, but 10518 * only PTR_TO_ARENA or SCALAR make sense. Everything 10519 * else is a bug in the bpf program. Point it out to 10520 * the user at the verification time instead of 10521 * run-time debug nightmare. 10522 */ 10523 if (reg->type != PTR_TO_ARENA && reg->type != SCALAR_VALUE) { 10524 bpf_log(log, "R%d is not a pointer to arena or scalar.\n", regno); 10525 return -EINVAL; 10526 } 10527 } else if (arg->arg_type == (ARG_PTR_TO_DYNPTR | MEM_RDONLY)) { 10528 ret = check_func_arg_reg_off(env, reg, regno, ARG_PTR_TO_DYNPTR); 10529 if (ret) 10530 return ret; 10531 10532 ret = process_dynptr_func(env, regno, -1, arg->arg_type, 0); 10533 if (ret) 10534 return ret; 10535 } else if (base_type(arg->arg_type) == ARG_PTR_TO_BTF_ID) { 10536 struct bpf_call_arg_meta meta; 10537 int err; 10538 10539 if (register_is_null(reg) && type_may_be_null(arg->arg_type)) 10540 continue; 10541 10542 memset(&meta, 0, sizeof(meta)); /* leave func_id as zero */ 10543 err = check_reg_type(env, regno, arg->arg_type, &arg->btf_id, &meta); 10544 err = err ?: check_func_arg_reg_off(env, reg, regno, arg->arg_type); 10545 if (err) 10546 return err; 10547 } else { 10548 verifier_bug(env, "unrecognized arg#%d type %d", i, arg->arg_type); 10549 return -EFAULT; 10550 } 10551 } 10552 10553 return 0; 10554 } 10555 10556 /* Compare BTF of a function call with given bpf_reg_state. 10557 * Returns: 10558 * EFAULT - there is a verifier bug. Abort verification. 10559 * EINVAL - there is a type mismatch or BTF is not available. 10560 * 0 - BTF matches with what bpf_reg_state expects. 10561 * Only PTR_TO_CTX and SCALAR_VALUE states are recognized. 10562 */ 10563 static int btf_check_subprog_call(struct bpf_verifier_env *env, int subprog, 10564 struct bpf_reg_state *regs) 10565 { 10566 struct bpf_prog *prog = env->prog; 10567 struct btf *btf = prog->aux->btf; 10568 u32 btf_id; 10569 int err; 10570 10571 if (!prog->aux->func_info) 10572 return -EINVAL; 10573 10574 btf_id = prog->aux->func_info[subprog].type_id; 10575 if (!btf_id) 10576 return -EFAULT; 10577 10578 if (prog->aux->func_info_aux[subprog].unreliable) 10579 return -EINVAL; 10580 10581 err = btf_check_func_arg_match(env, subprog, btf, regs); 10582 /* Compiler optimizations can remove arguments from static functions 10583 * or mismatched type can be passed into a global function. 10584 * In such cases mark the function as unreliable from BTF point of view. 10585 */ 10586 if (err) 10587 prog->aux->func_info_aux[subprog].unreliable = true; 10588 return err; 10589 } 10590 10591 static int push_callback_call(struct bpf_verifier_env *env, struct bpf_insn *insn, 10592 int insn_idx, int subprog, 10593 set_callee_state_fn set_callee_state_cb) 10594 { 10595 struct bpf_verifier_state *state = env->cur_state, *callback_state; 10596 struct bpf_func_state *caller, *callee; 10597 int err; 10598 10599 caller = state->frame[state->curframe]; 10600 err = btf_check_subprog_call(env, subprog, caller->regs); 10601 if (err == -EFAULT) 10602 return err; 10603 10604 /* set_callee_state is used for direct subprog calls, but we are 10605 * interested in validating only BPF helpers that can call subprogs as 10606 * callbacks 10607 */ 10608 env->subprog_info[subprog].is_cb = true; 10609 if (bpf_pseudo_kfunc_call(insn) && 10610 !is_callback_calling_kfunc(insn->imm)) { 10611 verifier_bug(env, "kfunc %s#%d not marked as callback-calling", 10612 func_id_name(insn->imm), insn->imm); 10613 return -EFAULT; 10614 } else if (!bpf_pseudo_kfunc_call(insn) && 10615 !is_callback_calling_function(insn->imm)) { /* helper */ 10616 verifier_bug(env, "helper %s#%d not marked as callback-calling", 10617 func_id_name(insn->imm), insn->imm); 10618 return -EFAULT; 10619 } 10620 10621 if (is_async_callback_calling_insn(insn)) { 10622 struct bpf_verifier_state *async_cb; 10623 10624 /* there is no real recursion here. timer and workqueue callbacks are async */ 10625 env->subprog_info[subprog].is_async_cb = true; 10626 async_cb = push_async_cb(env, env->subprog_info[subprog].start, 10627 insn_idx, subprog, 10628 is_bpf_wq_set_callback_impl_kfunc(insn->imm)); 10629 if (!async_cb) 10630 return -EFAULT; 10631 callee = async_cb->frame[0]; 10632 callee->async_entry_cnt = caller->async_entry_cnt + 1; 10633 10634 /* Convert bpf_timer_set_callback() args into timer callback args */ 10635 err = set_callee_state_cb(env, caller, callee, insn_idx); 10636 if (err) 10637 return err; 10638 10639 return 0; 10640 } 10641 10642 /* for callback functions enqueue entry to callback and 10643 * proceed with next instruction within current frame. 10644 */ 10645 callback_state = push_stack(env, env->subprog_info[subprog].start, insn_idx, false); 10646 if (!callback_state) 10647 return -ENOMEM; 10648 10649 err = setup_func_entry(env, subprog, insn_idx, set_callee_state_cb, 10650 callback_state); 10651 if (err) 10652 return err; 10653 10654 callback_state->callback_unroll_depth++; 10655 callback_state->frame[callback_state->curframe - 1]->callback_depth++; 10656 caller->callback_depth = 0; 10657 return 0; 10658 } 10659 10660 static int check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn, 10661 int *insn_idx) 10662 { 10663 struct bpf_verifier_state *state = env->cur_state; 10664 struct bpf_func_state *caller; 10665 int err, subprog, target_insn; 10666 10667 target_insn = *insn_idx + insn->imm + 1; 10668 subprog = find_subprog(env, target_insn); 10669 if (verifier_bug_if(subprog < 0, env, "target of func call at insn %d is not a program", 10670 target_insn)) 10671 return -EFAULT; 10672 10673 caller = state->frame[state->curframe]; 10674 err = btf_check_subprog_call(env, subprog, caller->regs); 10675 if (err == -EFAULT) 10676 return err; 10677 if (subprog_is_global(env, subprog)) { 10678 const char *sub_name = subprog_name(env, subprog); 10679 10680 if (env->cur_state->active_locks) { 10681 verbose(env, "global function calls are not allowed while holding a lock,\n" 10682 "use static function instead\n"); 10683 return -EINVAL; 10684 } 10685 10686 if (env->subprog_info[subprog].might_sleep && 10687 (env->cur_state->active_rcu_lock || env->cur_state->active_preempt_locks || 10688 env->cur_state->active_irq_id || !in_sleepable(env))) { 10689 verbose(env, "global functions that may sleep are not allowed in non-sleepable context,\n" 10690 "i.e., in a RCU/IRQ/preempt-disabled section, or in\n" 10691 "a non-sleepable BPF program context\n"); 10692 return -EINVAL; 10693 } 10694 10695 if (err) { 10696 verbose(env, "Caller passes invalid args into func#%d ('%s')\n", 10697 subprog, sub_name); 10698 return err; 10699 } 10700 10701 verbose(env, "Func#%d ('%s') is global and assumed valid.\n", 10702 subprog, sub_name); 10703 if (env->subprog_info[subprog].changes_pkt_data) 10704 clear_all_pkt_pointers(env); 10705 /* mark global subprog for verifying after main prog */ 10706 subprog_aux(env, subprog)->called = true; 10707 clear_caller_saved_regs(env, caller->regs); 10708 10709 /* All global functions return a 64-bit SCALAR_VALUE */ 10710 mark_reg_unknown(env, caller->regs, BPF_REG_0); 10711 caller->regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG; 10712 10713 /* continue with next insn after call */ 10714 return 0; 10715 } 10716 10717 /* for regular function entry setup new frame and continue 10718 * from that frame. 10719 */ 10720 err = setup_func_entry(env, subprog, *insn_idx, set_callee_state, state); 10721 if (err) 10722 return err; 10723 10724 clear_caller_saved_regs(env, caller->regs); 10725 10726 /* and go analyze first insn of the callee */ 10727 *insn_idx = env->subprog_info[subprog].start - 1; 10728 10729 if (env->log.level & BPF_LOG_LEVEL) { 10730 verbose(env, "caller:\n"); 10731 print_verifier_state(env, state, caller->frameno, true); 10732 verbose(env, "callee:\n"); 10733 print_verifier_state(env, state, state->curframe, true); 10734 } 10735 10736 return 0; 10737 } 10738 10739 int map_set_for_each_callback_args(struct bpf_verifier_env *env, 10740 struct bpf_func_state *caller, 10741 struct bpf_func_state *callee) 10742 { 10743 /* bpf_for_each_map_elem(struct bpf_map *map, void *callback_fn, 10744 * void *callback_ctx, u64 flags); 10745 * callback_fn(struct bpf_map *map, void *key, void *value, 10746 * void *callback_ctx); 10747 */ 10748 callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1]; 10749 10750 callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY; 10751 __mark_reg_known_zero(&callee->regs[BPF_REG_2]); 10752 callee->regs[BPF_REG_2].map_ptr = caller->regs[BPF_REG_1].map_ptr; 10753 10754 callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE; 10755 __mark_reg_known_zero(&callee->regs[BPF_REG_3]); 10756 callee->regs[BPF_REG_3].map_ptr = caller->regs[BPF_REG_1].map_ptr; 10757 10758 /* pointer to stack or null */ 10759 callee->regs[BPF_REG_4] = caller->regs[BPF_REG_3]; 10760 10761 /* unused */ 10762 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]); 10763 return 0; 10764 } 10765 10766 static int set_callee_state(struct bpf_verifier_env *env, 10767 struct bpf_func_state *caller, 10768 struct bpf_func_state *callee, int insn_idx) 10769 { 10770 int i; 10771 10772 /* copy r1 - r5 args that callee can access. The copy includes parent 10773 * pointers, which connects us up to the liveness chain 10774 */ 10775 for (i = BPF_REG_1; i <= BPF_REG_5; i++) 10776 callee->regs[i] = caller->regs[i]; 10777 return 0; 10778 } 10779 10780 static int set_map_elem_callback_state(struct bpf_verifier_env *env, 10781 struct bpf_func_state *caller, 10782 struct bpf_func_state *callee, 10783 int insn_idx) 10784 { 10785 struct bpf_insn_aux_data *insn_aux = &env->insn_aux_data[insn_idx]; 10786 struct bpf_map *map; 10787 int err; 10788 10789 /* valid map_ptr and poison value does not matter */ 10790 map = insn_aux->map_ptr_state.map_ptr; 10791 if (!map->ops->map_set_for_each_callback_args || 10792 !map->ops->map_for_each_callback) { 10793 verbose(env, "callback function not allowed for map\n"); 10794 return -ENOTSUPP; 10795 } 10796 10797 err = map->ops->map_set_for_each_callback_args(env, caller, callee); 10798 if (err) 10799 return err; 10800 10801 callee->in_callback_fn = true; 10802 callee->callback_ret_range = retval_range(0, 1); 10803 return 0; 10804 } 10805 10806 static int set_loop_callback_state(struct bpf_verifier_env *env, 10807 struct bpf_func_state *caller, 10808 struct bpf_func_state *callee, 10809 int insn_idx) 10810 { 10811 /* bpf_loop(u32 nr_loops, void *callback_fn, void *callback_ctx, 10812 * u64 flags); 10813 * callback_fn(u64 index, void *callback_ctx); 10814 */ 10815 callee->regs[BPF_REG_1].type = SCALAR_VALUE; 10816 callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3]; 10817 10818 /* unused */ 10819 __mark_reg_not_init(env, &callee->regs[BPF_REG_3]); 10820 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]); 10821 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]); 10822 10823 callee->in_callback_fn = true; 10824 callee->callback_ret_range = retval_range(0, 1); 10825 return 0; 10826 } 10827 10828 static int set_timer_callback_state(struct bpf_verifier_env *env, 10829 struct bpf_func_state *caller, 10830 struct bpf_func_state *callee, 10831 int insn_idx) 10832 { 10833 struct bpf_map *map_ptr = caller->regs[BPF_REG_1].map_ptr; 10834 10835 /* bpf_timer_set_callback(struct bpf_timer *timer, void *callback_fn); 10836 * callback_fn(struct bpf_map *map, void *key, void *value); 10837 */ 10838 callee->regs[BPF_REG_1].type = CONST_PTR_TO_MAP; 10839 __mark_reg_known_zero(&callee->regs[BPF_REG_1]); 10840 callee->regs[BPF_REG_1].map_ptr = map_ptr; 10841 10842 callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY; 10843 __mark_reg_known_zero(&callee->regs[BPF_REG_2]); 10844 callee->regs[BPF_REG_2].map_ptr = map_ptr; 10845 10846 callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE; 10847 __mark_reg_known_zero(&callee->regs[BPF_REG_3]); 10848 callee->regs[BPF_REG_3].map_ptr = map_ptr; 10849 10850 /* unused */ 10851 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]); 10852 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]); 10853 callee->in_async_callback_fn = true; 10854 callee->callback_ret_range = retval_range(0, 1); 10855 return 0; 10856 } 10857 10858 static int set_find_vma_callback_state(struct bpf_verifier_env *env, 10859 struct bpf_func_state *caller, 10860 struct bpf_func_state *callee, 10861 int insn_idx) 10862 { 10863 /* bpf_find_vma(struct task_struct *task, u64 addr, 10864 * void *callback_fn, void *callback_ctx, u64 flags) 10865 * (callback_fn)(struct task_struct *task, 10866 * struct vm_area_struct *vma, void *callback_ctx); 10867 */ 10868 callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1]; 10869 10870 callee->regs[BPF_REG_2].type = PTR_TO_BTF_ID; 10871 __mark_reg_known_zero(&callee->regs[BPF_REG_2]); 10872 callee->regs[BPF_REG_2].btf = btf_vmlinux; 10873 callee->regs[BPF_REG_2].btf_id = btf_tracing_ids[BTF_TRACING_TYPE_VMA]; 10874 10875 /* pointer to stack or null */ 10876 callee->regs[BPF_REG_3] = caller->regs[BPF_REG_4]; 10877 10878 /* unused */ 10879 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]); 10880 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]); 10881 callee->in_callback_fn = true; 10882 callee->callback_ret_range = retval_range(0, 1); 10883 return 0; 10884 } 10885 10886 static int set_user_ringbuf_callback_state(struct bpf_verifier_env *env, 10887 struct bpf_func_state *caller, 10888 struct bpf_func_state *callee, 10889 int insn_idx) 10890 { 10891 /* bpf_user_ringbuf_drain(struct bpf_map *map, void *callback_fn, void 10892 * callback_ctx, u64 flags); 10893 * callback_fn(const struct bpf_dynptr_t* dynptr, void *callback_ctx); 10894 */ 10895 __mark_reg_not_init(env, &callee->regs[BPF_REG_0]); 10896 mark_dynptr_cb_reg(env, &callee->regs[BPF_REG_1], BPF_DYNPTR_TYPE_LOCAL); 10897 callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3]; 10898 10899 /* unused */ 10900 __mark_reg_not_init(env, &callee->regs[BPF_REG_3]); 10901 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]); 10902 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]); 10903 10904 callee->in_callback_fn = true; 10905 callee->callback_ret_range = retval_range(0, 1); 10906 return 0; 10907 } 10908 10909 static int set_rbtree_add_callback_state(struct bpf_verifier_env *env, 10910 struct bpf_func_state *caller, 10911 struct bpf_func_state *callee, 10912 int insn_idx) 10913 { 10914 /* void bpf_rbtree_add_impl(struct bpf_rb_root *root, struct bpf_rb_node *node, 10915 * bool (less)(struct bpf_rb_node *a, const struct bpf_rb_node *b)); 10916 * 10917 * 'struct bpf_rb_node *node' arg to bpf_rbtree_add_impl is the same PTR_TO_BTF_ID w/ offset 10918 * that 'less' callback args will be receiving. However, 'node' arg was release_reference'd 10919 * by this point, so look at 'root' 10920 */ 10921 struct btf_field *field; 10922 10923 field = reg_find_field_offset(&caller->regs[BPF_REG_1], caller->regs[BPF_REG_1].off, 10924 BPF_RB_ROOT); 10925 if (!field || !field->graph_root.value_btf_id) 10926 return -EFAULT; 10927 10928 mark_reg_graph_node(callee->regs, BPF_REG_1, &field->graph_root); 10929 ref_set_non_owning(env, &callee->regs[BPF_REG_1]); 10930 mark_reg_graph_node(callee->regs, BPF_REG_2, &field->graph_root); 10931 ref_set_non_owning(env, &callee->regs[BPF_REG_2]); 10932 10933 __mark_reg_not_init(env, &callee->regs[BPF_REG_3]); 10934 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]); 10935 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]); 10936 callee->in_callback_fn = true; 10937 callee->callback_ret_range = retval_range(0, 1); 10938 return 0; 10939 } 10940 10941 static bool is_rbtree_lock_required_kfunc(u32 btf_id); 10942 10943 /* Are we currently verifying the callback for a rbtree helper that must 10944 * be called with lock held? If so, no need to complain about unreleased 10945 * lock 10946 */ 10947 static bool in_rbtree_lock_required_cb(struct bpf_verifier_env *env) 10948 { 10949 struct bpf_verifier_state *state = env->cur_state; 10950 struct bpf_insn *insn = env->prog->insnsi; 10951 struct bpf_func_state *callee; 10952 int kfunc_btf_id; 10953 10954 if (!state->curframe) 10955 return false; 10956 10957 callee = state->frame[state->curframe]; 10958 10959 if (!callee->in_callback_fn) 10960 return false; 10961 10962 kfunc_btf_id = insn[callee->callsite].imm; 10963 return is_rbtree_lock_required_kfunc(kfunc_btf_id); 10964 } 10965 10966 static bool retval_range_within(struct bpf_retval_range range, const struct bpf_reg_state *reg, 10967 bool return_32bit) 10968 { 10969 if (return_32bit) 10970 return range.minval <= reg->s32_min_value && reg->s32_max_value <= range.maxval; 10971 else 10972 return range.minval <= reg->smin_value && reg->smax_value <= range.maxval; 10973 } 10974 10975 static int prepare_func_exit(struct bpf_verifier_env *env, int *insn_idx) 10976 { 10977 struct bpf_verifier_state *state = env->cur_state, *prev_st; 10978 struct bpf_func_state *caller, *callee; 10979 struct bpf_reg_state *r0; 10980 bool in_callback_fn; 10981 int err; 10982 10983 callee = state->frame[state->curframe]; 10984 r0 = &callee->regs[BPF_REG_0]; 10985 if (r0->type == PTR_TO_STACK) { 10986 /* technically it's ok to return caller's stack pointer 10987 * (or caller's caller's pointer) back to the caller, 10988 * since these pointers are valid. Only current stack 10989 * pointer will be invalid as soon as function exits, 10990 * but let's be conservative 10991 */ 10992 verbose(env, "cannot return stack pointer to the caller\n"); 10993 return -EINVAL; 10994 } 10995 10996 caller = state->frame[state->curframe - 1]; 10997 if (callee->in_callback_fn) { 10998 if (r0->type != SCALAR_VALUE) { 10999 verbose(env, "R0 not a scalar value\n"); 11000 return -EACCES; 11001 } 11002 11003 /* we are going to rely on register's precise value */ 11004 err = mark_reg_read(env, r0, r0->parent, REG_LIVE_READ64); 11005 err = err ?: mark_chain_precision(env, BPF_REG_0); 11006 if (err) 11007 return err; 11008 11009 /* enforce R0 return value range, and bpf_callback_t returns 64bit */ 11010 if (!retval_range_within(callee->callback_ret_range, r0, false)) { 11011 verbose_invalid_scalar(env, r0, callee->callback_ret_range, 11012 "At callback return", "R0"); 11013 return -EINVAL; 11014 } 11015 if (!calls_callback(env, callee->callsite)) { 11016 verifier_bug(env, "in callback at %d, callsite %d !calls_callback", 11017 *insn_idx, callee->callsite); 11018 return -EFAULT; 11019 } 11020 } else { 11021 /* return to the caller whatever r0 had in the callee */ 11022 caller->regs[BPF_REG_0] = *r0; 11023 } 11024 11025 /* for callbacks like bpf_loop or bpf_for_each_map_elem go back to callsite, 11026 * there function call logic would reschedule callback visit. If iteration 11027 * converges is_state_visited() would prune that visit eventually. 11028 */ 11029 in_callback_fn = callee->in_callback_fn; 11030 if (in_callback_fn) 11031 *insn_idx = callee->callsite; 11032 else 11033 *insn_idx = callee->callsite + 1; 11034 11035 if (env->log.level & BPF_LOG_LEVEL) { 11036 verbose(env, "returning from callee:\n"); 11037 print_verifier_state(env, state, callee->frameno, true); 11038 verbose(env, "to caller at %d:\n", *insn_idx); 11039 print_verifier_state(env, state, caller->frameno, true); 11040 } 11041 /* clear everything in the callee. In case of exceptional exits using 11042 * bpf_throw, this will be done by copy_verifier_state for extra frames. */ 11043 free_func_state(callee); 11044 state->frame[state->curframe--] = NULL; 11045 11046 /* for callbacks widen imprecise scalars to make programs like below verify: 11047 * 11048 * struct ctx { int i; } 11049 * void cb(int idx, struct ctx *ctx) { ctx->i++; ... } 11050 * ... 11051 * struct ctx = { .i = 0; } 11052 * bpf_loop(100, cb, &ctx, 0); 11053 * 11054 * This is similar to what is done in process_iter_next_call() for open 11055 * coded iterators. 11056 */ 11057 prev_st = in_callback_fn ? find_prev_entry(env, state, *insn_idx) : NULL; 11058 if (prev_st) { 11059 err = widen_imprecise_scalars(env, prev_st, state); 11060 if (err) 11061 return err; 11062 } 11063 return 0; 11064 } 11065 11066 static int do_refine_retval_range(struct bpf_verifier_env *env, 11067 struct bpf_reg_state *regs, int ret_type, 11068 int func_id, 11069 struct bpf_call_arg_meta *meta) 11070 { 11071 struct bpf_reg_state *ret_reg = ®s[BPF_REG_0]; 11072 11073 if (ret_type != RET_INTEGER) 11074 return 0; 11075 11076 switch (func_id) { 11077 case BPF_FUNC_get_stack: 11078 case BPF_FUNC_get_task_stack: 11079 case BPF_FUNC_probe_read_str: 11080 case BPF_FUNC_probe_read_kernel_str: 11081 case BPF_FUNC_probe_read_user_str: 11082 ret_reg->smax_value = meta->msize_max_value; 11083 ret_reg->s32_max_value = meta->msize_max_value; 11084 ret_reg->smin_value = -MAX_ERRNO; 11085 ret_reg->s32_min_value = -MAX_ERRNO; 11086 reg_bounds_sync(ret_reg); 11087 break; 11088 case BPF_FUNC_get_smp_processor_id: 11089 ret_reg->umax_value = nr_cpu_ids - 1; 11090 ret_reg->u32_max_value = nr_cpu_ids - 1; 11091 ret_reg->smax_value = nr_cpu_ids - 1; 11092 ret_reg->s32_max_value = nr_cpu_ids - 1; 11093 ret_reg->umin_value = 0; 11094 ret_reg->u32_min_value = 0; 11095 ret_reg->smin_value = 0; 11096 ret_reg->s32_min_value = 0; 11097 reg_bounds_sync(ret_reg); 11098 break; 11099 } 11100 11101 return reg_bounds_sanity_check(env, ret_reg, "retval"); 11102 } 11103 11104 static int 11105 record_func_map(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta, 11106 int func_id, int insn_idx) 11107 { 11108 struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx]; 11109 struct bpf_map *map = meta->map_ptr; 11110 11111 if (func_id != BPF_FUNC_tail_call && 11112 func_id != BPF_FUNC_map_lookup_elem && 11113 func_id != BPF_FUNC_map_update_elem && 11114 func_id != BPF_FUNC_map_delete_elem && 11115 func_id != BPF_FUNC_map_push_elem && 11116 func_id != BPF_FUNC_map_pop_elem && 11117 func_id != BPF_FUNC_map_peek_elem && 11118 func_id != BPF_FUNC_for_each_map_elem && 11119 func_id != BPF_FUNC_redirect_map && 11120 func_id != BPF_FUNC_map_lookup_percpu_elem) 11121 return 0; 11122 11123 if (map == NULL) { 11124 verifier_bug(env, "expected map for helper call"); 11125 return -EFAULT; 11126 } 11127 11128 /* In case of read-only, some additional restrictions 11129 * need to be applied in order to prevent altering the 11130 * state of the map from program side. 11131 */ 11132 if ((map->map_flags & BPF_F_RDONLY_PROG) && 11133 (func_id == BPF_FUNC_map_delete_elem || 11134 func_id == BPF_FUNC_map_update_elem || 11135 func_id == BPF_FUNC_map_push_elem || 11136 func_id == BPF_FUNC_map_pop_elem)) { 11137 verbose(env, "write into map forbidden\n"); 11138 return -EACCES; 11139 } 11140 11141 if (!aux->map_ptr_state.map_ptr) 11142 bpf_map_ptr_store(aux, meta->map_ptr, 11143 !meta->map_ptr->bypass_spec_v1, false); 11144 else if (aux->map_ptr_state.map_ptr != meta->map_ptr) 11145 bpf_map_ptr_store(aux, meta->map_ptr, 11146 !meta->map_ptr->bypass_spec_v1, true); 11147 return 0; 11148 } 11149 11150 static int 11151 record_func_key(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta, 11152 int func_id, int insn_idx) 11153 { 11154 struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx]; 11155 struct bpf_reg_state *regs = cur_regs(env), *reg; 11156 struct bpf_map *map = meta->map_ptr; 11157 u64 val, max; 11158 int err; 11159 11160 if (func_id != BPF_FUNC_tail_call) 11161 return 0; 11162 if (!map || map->map_type != BPF_MAP_TYPE_PROG_ARRAY) { 11163 verbose(env, "expected prog array map for tail call"); 11164 return -EINVAL; 11165 } 11166 11167 reg = ®s[BPF_REG_3]; 11168 val = reg->var_off.value; 11169 max = map->max_entries; 11170 11171 if (!(is_reg_const(reg, false) && val < max)) { 11172 bpf_map_key_store(aux, BPF_MAP_KEY_POISON); 11173 return 0; 11174 } 11175 11176 err = mark_chain_precision(env, BPF_REG_3); 11177 if (err) 11178 return err; 11179 if (bpf_map_key_unseen(aux)) 11180 bpf_map_key_store(aux, val); 11181 else if (!bpf_map_key_poisoned(aux) && 11182 bpf_map_key_immediate(aux) != val) 11183 bpf_map_key_store(aux, BPF_MAP_KEY_POISON); 11184 return 0; 11185 } 11186 11187 static int check_reference_leak(struct bpf_verifier_env *env, bool exception_exit) 11188 { 11189 struct bpf_verifier_state *state = env->cur_state; 11190 enum bpf_prog_type type = resolve_prog_type(env->prog); 11191 struct bpf_reg_state *reg = reg_state(env, BPF_REG_0); 11192 bool refs_lingering = false; 11193 int i; 11194 11195 if (!exception_exit && cur_func(env)->frameno) 11196 return 0; 11197 11198 for (i = 0; i < state->acquired_refs; i++) { 11199 if (state->refs[i].type != REF_TYPE_PTR) 11200 continue; 11201 /* Allow struct_ops programs to return a referenced kptr back to 11202 * kernel. Type checks are performed later in check_return_code. 11203 */ 11204 if (type == BPF_PROG_TYPE_STRUCT_OPS && !exception_exit && 11205 reg->ref_obj_id == state->refs[i].id) 11206 continue; 11207 verbose(env, "Unreleased reference id=%d alloc_insn=%d\n", 11208 state->refs[i].id, state->refs[i].insn_idx); 11209 refs_lingering = true; 11210 } 11211 return refs_lingering ? -EINVAL : 0; 11212 } 11213 11214 static int check_resource_leak(struct bpf_verifier_env *env, bool exception_exit, bool check_lock, const char *prefix) 11215 { 11216 int err; 11217 11218 if (check_lock && env->cur_state->active_locks) { 11219 verbose(env, "%s cannot be used inside bpf_spin_lock-ed region\n", prefix); 11220 return -EINVAL; 11221 } 11222 11223 err = check_reference_leak(env, exception_exit); 11224 if (err) { 11225 verbose(env, "%s would lead to reference leak\n", prefix); 11226 return err; 11227 } 11228 11229 if (check_lock && env->cur_state->active_irq_id) { 11230 verbose(env, "%s cannot be used inside bpf_local_irq_save-ed region\n", prefix); 11231 return -EINVAL; 11232 } 11233 11234 if (check_lock && env->cur_state->active_rcu_lock) { 11235 verbose(env, "%s cannot be used inside bpf_rcu_read_lock-ed region\n", prefix); 11236 return -EINVAL; 11237 } 11238 11239 if (check_lock && env->cur_state->active_preempt_locks) { 11240 verbose(env, "%s cannot be used inside bpf_preempt_disable-ed region\n", prefix); 11241 return -EINVAL; 11242 } 11243 11244 return 0; 11245 } 11246 11247 static int check_bpf_snprintf_call(struct bpf_verifier_env *env, 11248 struct bpf_reg_state *regs) 11249 { 11250 struct bpf_reg_state *fmt_reg = ®s[BPF_REG_3]; 11251 struct bpf_reg_state *data_len_reg = ®s[BPF_REG_5]; 11252 struct bpf_map *fmt_map = fmt_reg->map_ptr; 11253 struct bpf_bprintf_data data = {}; 11254 int err, fmt_map_off, num_args; 11255 u64 fmt_addr; 11256 char *fmt; 11257 11258 /* data must be an array of u64 */ 11259 if (data_len_reg->var_off.value % 8) 11260 return -EINVAL; 11261 num_args = data_len_reg->var_off.value / 8; 11262 11263 /* fmt being ARG_PTR_TO_CONST_STR guarantees that var_off is const 11264 * and map_direct_value_addr is set. 11265 */ 11266 fmt_map_off = fmt_reg->off + fmt_reg->var_off.value; 11267 err = fmt_map->ops->map_direct_value_addr(fmt_map, &fmt_addr, 11268 fmt_map_off); 11269 if (err) { 11270 verbose(env, "failed to retrieve map value address\n"); 11271 return -EFAULT; 11272 } 11273 fmt = (char *)(long)fmt_addr + fmt_map_off; 11274 11275 /* We are also guaranteed that fmt+fmt_map_off is NULL terminated, we 11276 * can focus on validating the format specifiers. 11277 */ 11278 err = bpf_bprintf_prepare(fmt, UINT_MAX, NULL, num_args, &data); 11279 if (err < 0) 11280 verbose(env, "Invalid format string\n"); 11281 11282 return err; 11283 } 11284 11285 static int check_get_func_ip(struct bpf_verifier_env *env) 11286 { 11287 enum bpf_prog_type type = resolve_prog_type(env->prog); 11288 int func_id = BPF_FUNC_get_func_ip; 11289 11290 if (type == BPF_PROG_TYPE_TRACING) { 11291 if (!bpf_prog_has_trampoline(env->prog)) { 11292 verbose(env, "func %s#%d supported only for fentry/fexit/fmod_ret programs\n", 11293 func_id_name(func_id), func_id); 11294 return -ENOTSUPP; 11295 } 11296 return 0; 11297 } else if (type == BPF_PROG_TYPE_KPROBE) { 11298 return 0; 11299 } 11300 11301 verbose(env, "func %s#%d not supported for program type %d\n", 11302 func_id_name(func_id), func_id, type); 11303 return -ENOTSUPP; 11304 } 11305 11306 static struct bpf_insn_aux_data *cur_aux(const struct bpf_verifier_env *env) 11307 { 11308 return &env->insn_aux_data[env->insn_idx]; 11309 } 11310 11311 static bool loop_flag_is_zero(struct bpf_verifier_env *env) 11312 { 11313 struct bpf_reg_state *regs = cur_regs(env); 11314 struct bpf_reg_state *reg = ®s[BPF_REG_4]; 11315 bool reg_is_null = register_is_null(reg); 11316 11317 if (reg_is_null) 11318 mark_chain_precision(env, BPF_REG_4); 11319 11320 return reg_is_null; 11321 } 11322 11323 static void update_loop_inline_state(struct bpf_verifier_env *env, u32 subprogno) 11324 { 11325 struct bpf_loop_inline_state *state = &cur_aux(env)->loop_inline_state; 11326 11327 if (!state->initialized) { 11328 state->initialized = 1; 11329 state->fit_for_inline = loop_flag_is_zero(env); 11330 state->callback_subprogno = subprogno; 11331 return; 11332 } 11333 11334 if (!state->fit_for_inline) 11335 return; 11336 11337 state->fit_for_inline = (loop_flag_is_zero(env) && 11338 state->callback_subprogno == subprogno); 11339 } 11340 11341 /* Returns whether or not the given map type can potentially elide 11342 * lookup return value nullness check. This is possible if the key 11343 * is statically known. 11344 */ 11345 static bool can_elide_value_nullness(enum bpf_map_type type) 11346 { 11347 switch (type) { 11348 case BPF_MAP_TYPE_ARRAY: 11349 case BPF_MAP_TYPE_PERCPU_ARRAY: 11350 return true; 11351 default: 11352 return false; 11353 } 11354 } 11355 11356 static int get_helper_proto(struct bpf_verifier_env *env, int func_id, 11357 const struct bpf_func_proto **ptr) 11358 { 11359 if (func_id < 0 || func_id >= __BPF_FUNC_MAX_ID) 11360 return -ERANGE; 11361 11362 if (!env->ops->get_func_proto) 11363 return -EINVAL; 11364 11365 *ptr = env->ops->get_func_proto(func_id, env->prog); 11366 return *ptr && (*ptr)->func ? 0 : -EINVAL; 11367 } 11368 11369 static int check_helper_call(struct bpf_verifier_env *env, struct bpf_insn *insn, 11370 int *insn_idx_p) 11371 { 11372 enum bpf_prog_type prog_type = resolve_prog_type(env->prog); 11373 bool returns_cpu_specific_alloc_ptr = false; 11374 const struct bpf_func_proto *fn = NULL; 11375 enum bpf_return_type ret_type; 11376 enum bpf_type_flag ret_flag; 11377 struct bpf_reg_state *regs; 11378 struct bpf_call_arg_meta meta; 11379 int insn_idx = *insn_idx_p; 11380 bool changes_data; 11381 int i, err, func_id; 11382 11383 /* find function prototype */ 11384 func_id = insn->imm; 11385 err = get_helper_proto(env, insn->imm, &fn); 11386 if (err == -ERANGE) { 11387 verbose(env, "invalid func %s#%d\n", func_id_name(func_id), func_id); 11388 return -EINVAL; 11389 } 11390 11391 if (err) { 11392 verbose(env, "program of this type cannot use helper %s#%d\n", 11393 func_id_name(func_id), func_id); 11394 return err; 11395 } 11396 11397 /* eBPF programs must be GPL compatible to use GPL-ed functions */ 11398 if (!env->prog->gpl_compatible && fn->gpl_only) { 11399 verbose(env, "cannot call GPL-restricted function from non-GPL compatible program\n"); 11400 return -EINVAL; 11401 } 11402 11403 if (fn->allowed && !fn->allowed(env->prog)) { 11404 verbose(env, "helper call is not allowed in probe\n"); 11405 return -EINVAL; 11406 } 11407 11408 if (!in_sleepable(env) && fn->might_sleep) { 11409 verbose(env, "helper call might sleep in a non-sleepable prog\n"); 11410 return -EINVAL; 11411 } 11412 11413 /* With LD_ABS/IND some JITs save/restore skb from r1. */ 11414 changes_data = bpf_helper_changes_pkt_data(func_id); 11415 if (changes_data && fn->arg1_type != ARG_PTR_TO_CTX) { 11416 verifier_bug(env, "func %s#%d: r1 != ctx", func_id_name(func_id), func_id); 11417 return -EFAULT; 11418 } 11419 11420 memset(&meta, 0, sizeof(meta)); 11421 meta.pkt_access = fn->pkt_access; 11422 11423 err = check_func_proto(fn, func_id); 11424 if (err) { 11425 verifier_bug(env, "incorrect func proto %s#%d", func_id_name(func_id), func_id); 11426 return err; 11427 } 11428 11429 if (env->cur_state->active_rcu_lock) { 11430 if (fn->might_sleep) { 11431 verbose(env, "sleepable helper %s#%d in rcu_read_lock region\n", 11432 func_id_name(func_id), func_id); 11433 return -EINVAL; 11434 } 11435 11436 if (in_sleepable(env) && is_storage_get_function(func_id)) 11437 env->insn_aux_data[insn_idx].storage_get_func_atomic = true; 11438 } 11439 11440 if (env->cur_state->active_preempt_locks) { 11441 if (fn->might_sleep) { 11442 verbose(env, "sleepable helper %s#%d in non-preemptible region\n", 11443 func_id_name(func_id), func_id); 11444 return -EINVAL; 11445 } 11446 11447 if (in_sleepable(env) && is_storage_get_function(func_id)) 11448 env->insn_aux_data[insn_idx].storage_get_func_atomic = true; 11449 } 11450 11451 if (env->cur_state->active_irq_id) { 11452 if (fn->might_sleep) { 11453 verbose(env, "sleepable helper %s#%d in IRQ-disabled region\n", 11454 func_id_name(func_id), func_id); 11455 return -EINVAL; 11456 } 11457 11458 if (in_sleepable(env) && is_storage_get_function(func_id)) 11459 env->insn_aux_data[insn_idx].storage_get_func_atomic = true; 11460 } 11461 11462 meta.func_id = func_id; 11463 /* check args */ 11464 for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++) { 11465 err = check_func_arg(env, i, &meta, fn, insn_idx); 11466 if (err) 11467 return err; 11468 } 11469 11470 err = record_func_map(env, &meta, func_id, insn_idx); 11471 if (err) 11472 return err; 11473 11474 err = record_func_key(env, &meta, func_id, insn_idx); 11475 if (err) 11476 return err; 11477 11478 /* Mark slots with STACK_MISC in case of raw mode, stack offset 11479 * is inferred from register state. 11480 */ 11481 for (i = 0; i < meta.access_size; i++) { 11482 err = check_mem_access(env, insn_idx, meta.regno, i, BPF_B, 11483 BPF_WRITE, -1, false, false); 11484 if (err) 11485 return err; 11486 } 11487 11488 regs = cur_regs(env); 11489 11490 if (meta.release_regno) { 11491 err = -EINVAL; 11492 /* This can only be set for PTR_TO_STACK, as CONST_PTR_TO_DYNPTR cannot 11493 * be released by any dynptr helper. Hence, unmark_stack_slots_dynptr 11494 * is safe to do directly. 11495 */ 11496 if (arg_type_is_dynptr(fn->arg_type[meta.release_regno - BPF_REG_1])) { 11497 if (regs[meta.release_regno].type == CONST_PTR_TO_DYNPTR) { 11498 verifier_bug(env, "CONST_PTR_TO_DYNPTR cannot be released"); 11499 return -EFAULT; 11500 } 11501 err = unmark_stack_slots_dynptr(env, ®s[meta.release_regno]); 11502 } else if (func_id == BPF_FUNC_kptr_xchg && meta.ref_obj_id) { 11503 u32 ref_obj_id = meta.ref_obj_id; 11504 bool in_rcu = in_rcu_cs(env); 11505 struct bpf_func_state *state; 11506 struct bpf_reg_state *reg; 11507 11508 err = release_reference_nomark(env->cur_state, ref_obj_id); 11509 if (!err) { 11510 bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({ 11511 if (reg->ref_obj_id == ref_obj_id) { 11512 if (in_rcu && (reg->type & MEM_ALLOC) && (reg->type & MEM_PERCPU)) { 11513 reg->ref_obj_id = 0; 11514 reg->type &= ~MEM_ALLOC; 11515 reg->type |= MEM_RCU; 11516 } else { 11517 mark_reg_invalid(env, reg); 11518 } 11519 } 11520 })); 11521 } 11522 } else if (meta.ref_obj_id) { 11523 err = release_reference(env, meta.ref_obj_id); 11524 } else if (register_is_null(®s[meta.release_regno])) { 11525 /* meta.ref_obj_id can only be 0 if register that is meant to be 11526 * released is NULL, which must be > R0. 11527 */ 11528 err = 0; 11529 } 11530 if (err) { 11531 verbose(env, "func %s#%d reference has not been acquired before\n", 11532 func_id_name(func_id), func_id); 11533 return err; 11534 } 11535 } 11536 11537 switch (func_id) { 11538 case BPF_FUNC_tail_call: 11539 err = check_resource_leak(env, false, true, "tail_call"); 11540 if (err) 11541 return err; 11542 break; 11543 case BPF_FUNC_get_local_storage: 11544 /* check that flags argument in get_local_storage(map, flags) is 0, 11545 * this is required because get_local_storage() can't return an error. 11546 */ 11547 if (!register_is_null(®s[BPF_REG_2])) { 11548 verbose(env, "get_local_storage() doesn't support non-zero flags\n"); 11549 return -EINVAL; 11550 } 11551 break; 11552 case BPF_FUNC_for_each_map_elem: 11553 err = push_callback_call(env, insn, insn_idx, meta.subprogno, 11554 set_map_elem_callback_state); 11555 break; 11556 case BPF_FUNC_timer_set_callback: 11557 err = push_callback_call(env, insn, insn_idx, meta.subprogno, 11558 set_timer_callback_state); 11559 break; 11560 case BPF_FUNC_find_vma: 11561 err = push_callback_call(env, insn, insn_idx, meta.subprogno, 11562 set_find_vma_callback_state); 11563 break; 11564 case BPF_FUNC_snprintf: 11565 err = check_bpf_snprintf_call(env, regs); 11566 break; 11567 case BPF_FUNC_loop: 11568 update_loop_inline_state(env, meta.subprogno); 11569 /* Verifier relies on R1 value to determine if bpf_loop() iteration 11570 * is finished, thus mark it precise. 11571 */ 11572 err = mark_chain_precision(env, BPF_REG_1); 11573 if (err) 11574 return err; 11575 if (cur_func(env)->callback_depth < regs[BPF_REG_1].umax_value) { 11576 err = push_callback_call(env, insn, insn_idx, meta.subprogno, 11577 set_loop_callback_state); 11578 } else { 11579 cur_func(env)->callback_depth = 0; 11580 if (env->log.level & BPF_LOG_LEVEL2) 11581 verbose(env, "frame%d bpf_loop iteration limit reached\n", 11582 env->cur_state->curframe); 11583 } 11584 break; 11585 case BPF_FUNC_dynptr_from_mem: 11586 if (regs[BPF_REG_1].type != PTR_TO_MAP_VALUE) { 11587 verbose(env, "Unsupported reg type %s for bpf_dynptr_from_mem data\n", 11588 reg_type_str(env, regs[BPF_REG_1].type)); 11589 return -EACCES; 11590 } 11591 break; 11592 case BPF_FUNC_set_retval: 11593 if (prog_type == BPF_PROG_TYPE_LSM && 11594 env->prog->expected_attach_type == BPF_LSM_CGROUP) { 11595 if (!env->prog->aux->attach_func_proto->type) { 11596 /* Make sure programs that attach to void 11597 * hooks don't try to modify return value. 11598 */ 11599 verbose(env, "BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n"); 11600 return -EINVAL; 11601 } 11602 } 11603 break; 11604 case BPF_FUNC_dynptr_data: 11605 { 11606 struct bpf_reg_state *reg; 11607 int id, ref_obj_id; 11608 11609 reg = get_dynptr_arg_reg(env, fn, regs); 11610 if (!reg) 11611 return -EFAULT; 11612 11613 11614 if (meta.dynptr_id) { 11615 verifier_bug(env, "meta.dynptr_id already set"); 11616 return -EFAULT; 11617 } 11618 if (meta.ref_obj_id) { 11619 verifier_bug(env, "meta.ref_obj_id already set"); 11620 return -EFAULT; 11621 } 11622 11623 id = dynptr_id(env, reg); 11624 if (id < 0) { 11625 verifier_bug(env, "failed to obtain dynptr id"); 11626 return id; 11627 } 11628 11629 ref_obj_id = dynptr_ref_obj_id(env, reg); 11630 if (ref_obj_id < 0) { 11631 verifier_bug(env, "failed to obtain dynptr ref_obj_id"); 11632 return ref_obj_id; 11633 } 11634 11635 meta.dynptr_id = id; 11636 meta.ref_obj_id = ref_obj_id; 11637 11638 break; 11639 } 11640 case BPF_FUNC_dynptr_write: 11641 { 11642 enum bpf_dynptr_type dynptr_type; 11643 struct bpf_reg_state *reg; 11644 11645 reg = get_dynptr_arg_reg(env, fn, regs); 11646 if (!reg) 11647 return -EFAULT; 11648 11649 dynptr_type = dynptr_get_type(env, reg); 11650 if (dynptr_type == BPF_DYNPTR_TYPE_INVALID) 11651 return -EFAULT; 11652 11653 if (dynptr_type == BPF_DYNPTR_TYPE_SKB || 11654 dynptr_type == BPF_DYNPTR_TYPE_SKB_META) 11655 /* this will trigger clear_all_pkt_pointers(), which will 11656 * invalidate all dynptr slices associated with the skb 11657 */ 11658 changes_data = true; 11659 11660 break; 11661 } 11662 case BPF_FUNC_per_cpu_ptr: 11663 case BPF_FUNC_this_cpu_ptr: 11664 { 11665 struct bpf_reg_state *reg = ®s[BPF_REG_1]; 11666 const struct btf_type *type; 11667 11668 if (reg->type & MEM_RCU) { 11669 type = btf_type_by_id(reg->btf, reg->btf_id); 11670 if (!type || !btf_type_is_struct(type)) { 11671 verbose(env, "Helper has invalid btf/btf_id in R1\n"); 11672 return -EFAULT; 11673 } 11674 returns_cpu_specific_alloc_ptr = true; 11675 env->insn_aux_data[insn_idx].call_with_percpu_alloc_ptr = true; 11676 } 11677 break; 11678 } 11679 case BPF_FUNC_user_ringbuf_drain: 11680 err = push_callback_call(env, insn, insn_idx, meta.subprogno, 11681 set_user_ringbuf_callback_state); 11682 break; 11683 } 11684 11685 if (err) 11686 return err; 11687 11688 /* reset caller saved regs */ 11689 for (i = 0; i < CALLER_SAVED_REGS; i++) { 11690 mark_reg_not_init(env, regs, caller_saved[i]); 11691 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK); 11692 } 11693 11694 /* helper call returns 64-bit value. */ 11695 regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG; 11696 11697 /* update return register (already marked as written above) */ 11698 ret_type = fn->ret_type; 11699 ret_flag = type_flag(ret_type); 11700 11701 switch (base_type(ret_type)) { 11702 case RET_INTEGER: 11703 /* sets type to SCALAR_VALUE */ 11704 mark_reg_unknown(env, regs, BPF_REG_0); 11705 break; 11706 case RET_VOID: 11707 regs[BPF_REG_0].type = NOT_INIT; 11708 break; 11709 case RET_PTR_TO_MAP_VALUE: 11710 /* There is no offset yet applied, variable or fixed */ 11711 mark_reg_known_zero(env, regs, BPF_REG_0); 11712 /* remember map_ptr, so that check_map_access() 11713 * can check 'value_size' boundary of memory access 11714 * to map element returned from bpf_map_lookup_elem() 11715 */ 11716 if (meta.map_ptr == NULL) { 11717 verifier_bug(env, "unexpected null map_ptr"); 11718 return -EFAULT; 11719 } 11720 11721 if (func_id == BPF_FUNC_map_lookup_elem && 11722 can_elide_value_nullness(meta.map_ptr->map_type) && 11723 meta.const_map_key >= 0 && 11724 meta.const_map_key < meta.map_ptr->max_entries) 11725 ret_flag &= ~PTR_MAYBE_NULL; 11726 11727 regs[BPF_REG_0].map_ptr = meta.map_ptr; 11728 regs[BPF_REG_0].map_uid = meta.map_uid; 11729 regs[BPF_REG_0].type = PTR_TO_MAP_VALUE | ret_flag; 11730 if (!type_may_be_null(ret_flag) && 11731 btf_record_has_field(meta.map_ptr->record, BPF_SPIN_LOCK | BPF_RES_SPIN_LOCK)) { 11732 regs[BPF_REG_0].id = ++env->id_gen; 11733 } 11734 break; 11735 case RET_PTR_TO_SOCKET: 11736 mark_reg_known_zero(env, regs, BPF_REG_0); 11737 regs[BPF_REG_0].type = PTR_TO_SOCKET | ret_flag; 11738 break; 11739 case RET_PTR_TO_SOCK_COMMON: 11740 mark_reg_known_zero(env, regs, BPF_REG_0); 11741 regs[BPF_REG_0].type = PTR_TO_SOCK_COMMON | ret_flag; 11742 break; 11743 case RET_PTR_TO_TCP_SOCK: 11744 mark_reg_known_zero(env, regs, BPF_REG_0); 11745 regs[BPF_REG_0].type = PTR_TO_TCP_SOCK | ret_flag; 11746 break; 11747 case RET_PTR_TO_MEM: 11748 mark_reg_known_zero(env, regs, BPF_REG_0); 11749 regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag; 11750 regs[BPF_REG_0].mem_size = meta.mem_size; 11751 break; 11752 case RET_PTR_TO_MEM_OR_BTF_ID: 11753 { 11754 const struct btf_type *t; 11755 11756 mark_reg_known_zero(env, regs, BPF_REG_0); 11757 t = btf_type_skip_modifiers(meta.ret_btf, meta.ret_btf_id, NULL); 11758 if (!btf_type_is_struct(t)) { 11759 u32 tsize; 11760 const struct btf_type *ret; 11761 const char *tname; 11762 11763 /* resolve the type size of ksym. */ 11764 ret = btf_resolve_size(meta.ret_btf, t, &tsize); 11765 if (IS_ERR(ret)) { 11766 tname = btf_name_by_offset(meta.ret_btf, t->name_off); 11767 verbose(env, "unable to resolve the size of type '%s': %ld\n", 11768 tname, PTR_ERR(ret)); 11769 return -EINVAL; 11770 } 11771 regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag; 11772 regs[BPF_REG_0].mem_size = tsize; 11773 } else { 11774 if (returns_cpu_specific_alloc_ptr) { 11775 regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC | MEM_RCU; 11776 } else { 11777 /* MEM_RDONLY may be carried from ret_flag, but it 11778 * doesn't apply on PTR_TO_BTF_ID. Fold it, otherwise 11779 * it will confuse the check of PTR_TO_BTF_ID in 11780 * check_mem_access(). 11781 */ 11782 ret_flag &= ~MEM_RDONLY; 11783 regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag; 11784 } 11785 11786 regs[BPF_REG_0].btf = meta.ret_btf; 11787 regs[BPF_REG_0].btf_id = meta.ret_btf_id; 11788 } 11789 break; 11790 } 11791 case RET_PTR_TO_BTF_ID: 11792 { 11793 struct btf *ret_btf; 11794 int ret_btf_id; 11795 11796 mark_reg_known_zero(env, regs, BPF_REG_0); 11797 regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag; 11798 if (func_id == BPF_FUNC_kptr_xchg) { 11799 ret_btf = meta.kptr_field->kptr.btf; 11800 ret_btf_id = meta.kptr_field->kptr.btf_id; 11801 if (!btf_is_kernel(ret_btf)) { 11802 regs[BPF_REG_0].type |= MEM_ALLOC; 11803 if (meta.kptr_field->type == BPF_KPTR_PERCPU) 11804 regs[BPF_REG_0].type |= MEM_PERCPU; 11805 } 11806 } else { 11807 if (fn->ret_btf_id == BPF_PTR_POISON) { 11808 verifier_bug(env, "func %s has non-overwritten BPF_PTR_POISON return type", 11809 func_id_name(func_id)); 11810 return -EFAULT; 11811 } 11812 ret_btf = btf_vmlinux; 11813 ret_btf_id = *fn->ret_btf_id; 11814 } 11815 if (ret_btf_id == 0) { 11816 verbose(env, "invalid return type %u of func %s#%d\n", 11817 base_type(ret_type), func_id_name(func_id), 11818 func_id); 11819 return -EINVAL; 11820 } 11821 regs[BPF_REG_0].btf = ret_btf; 11822 regs[BPF_REG_0].btf_id = ret_btf_id; 11823 break; 11824 } 11825 default: 11826 verbose(env, "unknown return type %u of func %s#%d\n", 11827 base_type(ret_type), func_id_name(func_id), func_id); 11828 return -EINVAL; 11829 } 11830 11831 if (type_may_be_null(regs[BPF_REG_0].type)) 11832 regs[BPF_REG_0].id = ++env->id_gen; 11833 11834 if (helper_multiple_ref_obj_use(func_id, meta.map_ptr)) { 11835 verifier_bug(env, "func %s#%d sets ref_obj_id more than once", 11836 func_id_name(func_id), func_id); 11837 return -EFAULT; 11838 } 11839 11840 if (is_dynptr_ref_function(func_id)) 11841 regs[BPF_REG_0].dynptr_id = meta.dynptr_id; 11842 11843 if (is_ptr_cast_function(func_id) || is_dynptr_ref_function(func_id)) { 11844 /* For release_reference() */ 11845 regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id; 11846 } else if (is_acquire_function(func_id, meta.map_ptr)) { 11847 int id = acquire_reference(env, insn_idx); 11848 11849 if (id < 0) 11850 return id; 11851 /* For mark_ptr_or_null_reg() */ 11852 regs[BPF_REG_0].id = id; 11853 /* For release_reference() */ 11854 regs[BPF_REG_0].ref_obj_id = id; 11855 } 11856 11857 err = do_refine_retval_range(env, regs, fn->ret_type, func_id, &meta); 11858 if (err) 11859 return err; 11860 11861 err = check_map_func_compatibility(env, meta.map_ptr, func_id); 11862 if (err) 11863 return err; 11864 11865 if ((func_id == BPF_FUNC_get_stack || 11866 func_id == BPF_FUNC_get_task_stack) && 11867 !env->prog->has_callchain_buf) { 11868 const char *err_str; 11869 11870 #ifdef CONFIG_PERF_EVENTS 11871 err = get_callchain_buffers(sysctl_perf_event_max_stack); 11872 err_str = "cannot get callchain buffer for func %s#%d\n"; 11873 #else 11874 err = -ENOTSUPP; 11875 err_str = "func %s#%d not supported without CONFIG_PERF_EVENTS\n"; 11876 #endif 11877 if (err) { 11878 verbose(env, err_str, func_id_name(func_id), func_id); 11879 return err; 11880 } 11881 11882 env->prog->has_callchain_buf = true; 11883 } 11884 11885 if (func_id == BPF_FUNC_get_stackid || func_id == BPF_FUNC_get_stack) 11886 env->prog->call_get_stack = true; 11887 11888 if (func_id == BPF_FUNC_get_func_ip) { 11889 if (check_get_func_ip(env)) 11890 return -ENOTSUPP; 11891 env->prog->call_get_func_ip = true; 11892 } 11893 11894 if (changes_data) 11895 clear_all_pkt_pointers(env); 11896 return 0; 11897 } 11898 11899 /* mark_btf_func_reg_size() is used when the reg size is determined by 11900 * the BTF func_proto's return value size and argument. 11901 */ 11902 static void __mark_btf_func_reg_size(struct bpf_verifier_env *env, struct bpf_reg_state *regs, 11903 u32 regno, size_t reg_size) 11904 { 11905 struct bpf_reg_state *reg = ®s[regno]; 11906 11907 if (regno == BPF_REG_0) { 11908 /* Function return value */ 11909 reg->live |= REG_LIVE_WRITTEN; 11910 reg->subreg_def = reg_size == sizeof(u64) ? 11911 DEF_NOT_SUBREG : env->insn_idx + 1; 11912 } else { 11913 /* Function argument */ 11914 if (reg_size == sizeof(u64)) { 11915 mark_insn_zext(env, reg); 11916 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64); 11917 } else { 11918 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ32); 11919 } 11920 } 11921 } 11922 11923 static void mark_btf_func_reg_size(struct bpf_verifier_env *env, u32 regno, 11924 size_t reg_size) 11925 { 11926 return __mark_btf_func_reg_size(env, cur_regs(env), regno, reg_size); 11927 } 11928 11929 static bool is_kfunc_acquire(struct bpf_kfunc_call_arg_meta *meta) 11930 { 11931 return meta->kfunc_flags & KF_ACQUIRE; 11932 } 11933 11934 static bool is_kfunc_release(struct bpf_kfunc_call_arg_meta *meta) 11935 { 11936 return meta->kfunc_flags & KF_RELEASE; 11937 } 11938 11939 static bool is_kfunc_trusted_args(struct bpf_kfunc_call_arg_meta *meta) 11940 { 11941 return (meta->kfunc_flags & KF_TRUSTED_ARGS) || is_kfunc_release(meta); 11942 } 11943 11944 static bool is_kfunc_sleepable(struct bpf_kfunc_call_arg_meta *meta) 11945 { 11946 return meta->kfunc_flags & KF_SLEEPABLE; 11947 } 11948 11949 static bool is_kfunc_destructive(struct bpf_kfunc_call_arg_meta *meta) 11950 { 11951 return meta->kfunc_flags & KF_DESTRUCTIVE; 11952 } 11953 11954 static bool is_kfunc_rcu(struct bpf_kfunc_call_arg_meta *meta) 11955 { 11956 return meta->kfunc_flags & KF_RCU; 11957 } 11958 11959 static bool is_kfunc_rcu_protected(struct bpf_kfunc_call_arg_meta *meta) 11960 { 11961 return meta->kfunc_flags & KF_RCU_PROTECTED; 11962 } 11963 11964 static bool is_kfunc_arg_mem_size(const struct btf *btf, 11965 const struct btf_param *arg, 11966 const struct bpf_reg_state *reg) 11967 { 11968 const struct btf_type *t; 11969 11970 t = btf_type_skip_modifiers(btf, arg->type, NULL); 11971 if (!btf_type_is_scalar(t) || reg->type != SCALAR_VALUE) 11972 return false; 11973 11974 return btf_param_match_suffix(btf, arg, "__sz"); 11975 } 11976 11977 static bool is_kfunc_arg_const_mem_size(const struct btf *btf, 11978 const struct btf_param *arg, 11979 const struct bpf_reg_state *reg) 11980 { 11981 const struct btf_type *t; 11982 11983 t = btf_type_skip_modifiers(btf, arg->type, NULL); 11984 if (!btf_type_is_scalar(t) || reg->type != SCALAR_VALUE) 11985 return false; 11986 11987 return btf_param_match_suffix(btf, arg, "__szk"); 11988 } 11989 11990 static bool is_kfunc_arg_optional(const struct btf *btf, const struct btf_param *arg) 11991 { 11992 return btf_param_match_suffix(btf, arg, "__opt"); 11993 } 11994 11995 static bool is_kfunc_arg_constant(const struct btf *btf, const struct btf_param *arg) 11996 { 11997 return btf_param_match_suffix(btf, arg, "__k"); 11998 } 11999 12000 static bool is_kfunc_arg_ignore(const struct btf *btf, const struct btf_param *arg) 12001 { 12002 return btf_param_match_suffix(btf, arg, "__ign"); 12003 } 12004 12005 static bool is_kfunc_arg_map(const struct btf *btf, const struct btf_param *arg) 12006 { 12007 return btf_param_match_suffix(btf, arg, "__map"); 12008 } 12009 12010 static bool is_kfunc_arg_alloc_obj(const struct btf *btf, const struct btf_param *arg) 12011 { 12012 return btf_param_match_suffix(btf, arg, "__alloc"); 12013 } 12014 12015 static bool is_kfunc_arg_uninit(const struct btf *btf, const struct btf_param *arg) 12016 { 12017 return btf_param_match_suffix(btf, arg, "__uninit"); 12018 } 12019 12020 static bool is_kfunc_arg_refcounted_kptr(const struct btf *btf, const struct btf_param *arg) 12021 { 12022 return btf_param_match_suffix(btf, arg, "__refcounted_kptr"); 12023 } 12024 12025 static bool is_kfunc_arg_nullable(const struct btf *btf, const struct btf_param *arg) 12026 { 12027 return btf_param_match_suffix(btf, arg, "__nullable"); 12028 } 12029 12030 static bool is_kfunc_arg_const_str(const struct btf *btf, const struct btf_param *arg) 12031 { 12032 return btf_param_match_suffix(btf, arg, "__str"); 12033 } 12034 12035 static bool is_kfunc_arg_irq_flag(const struct btf *btf, const struct btf_param *arg) 12036 { 12037 return btf_param_match_suffix(btf, arg, "__irq_flag"); 12038 } 12039 12040 static bool is_kfunc_arg_prog(const struct btf *btf, const struct btf_param *arg) 12041 { 12042 return btf_param_match_suffix(btf, arg, "__prog"); 12043 } 12044 12045 static bool is_kfunc_arg_scalar_with_name(const struct btf *btf, 12046 const struct btf_param *arg, 12047 const char *name) 12048 { 12049 int len, target_len = strlen(name); 12050 const char *param_name; 12051 12052 param_name = btf_name_by_offset(btf, arg->name_off); 12053 if (str_is_empty(param_name)) 12054 return false; 12055 len = strlen(param_name); 12056 if (len != target_len) 12057 return false; 12058 if (strcmp(param_name, name)) 12059 return false; 12060 12061 return true; 12062 } 12063 12064 enum { 12065 KF_ARG_DYNPTR_ID, 12066 KF_ARG_LIST_HEAD_ID, 12067 KF_ARG_LIST_NODE_ID, 12068 KF_ARG_RB_ROOT_ID, 12069 KF_ARG_RB_NODE_ID, 12070 KF_ARG_WORKQUEUE_ID, 12071 KF_ARG_RES_SPIN_LOCK_ID, 12072 }; 12073 12074 BTF_ID_LIST(kf_arg_btf_ids) 12075 BTF_ID(struct, bpf_dynptr) 12076 BTF_ID(struct, bpf_list_head) 12077 BTF_ID(struct, bpf_list_node) 12078 BTF_ID(struct, bpf_rb_root) 12079 BTF_ID(struct, bpf_rb_node) 12080 BTF_ID(struct, bpf_wq) 12081 BTF_ID(struct, bpf_res_spin_lock) 12082 12083 static bool __is_kfunc_ptr_arg_type(const struct btf *btf, 12084 const struct btf_param *arg, int type) 12085 { 12086 const struct btf_type *t; 12087 u32 res_id; 12088 12089 t = btf_type_skip_modifiers(btf, arg->type, NULL); 12090 if (!t) 12091 return false; 12092 if (!btf_type_is_ptr(t)) 12093 return false; 12094 t = btf_type_skip_modifiers(btf, t->type, &res_id); 12095 if (!t) 12096 return false; 12097 return btf_types_are_same(btf, res_id, btf_vmlinux, kf_arg_btf_ids[type]); 12098 } 12099 12100 static bool is_kfunc_arg_dynptr(const struct btf *btf, const struct btf_param *arg) 12101 { 12102 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_DYNPTR_ID); 12103 } 12104 12105 static bool is_kfunc_arg_list_head(const struct btf *btf, const struct btf_param *arg) 12106 { 12107 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_LIST_HEAD_ID); 12108 } 12109 12110 static bool is_kfunc_arg_list_node(const struct btf *btf, const struct btf_param *arg) 12111 { 12112 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_LIST_NODE_ID); 12113 } 12114 12115 static bool is_kfunc_arg_rbtree_root(const struct btf *btf, const struct btf_param *arg) 12116 { 12117 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_RB_ROOT_ID); 12118 } 12119 12120 static bool is_kfunc_arg_rbtree_node(const struct btf *btf, const struct btf_param *arg) 12121 { 12122 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_RB_NODE_ID); 12123 } 12124 12125 static bool is_kfunc_arg_wq(const struct btf *btf, const struct btf_param *arg) 12126 { 12127 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_WORKQUEUE_ID); 12128 } 12129 12130 static bool is_kfunc_arg_res_spin_lock(const struct btf *btf, const struct btf_param *arg) 12131 { 12132 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_RES_SPIN_LOCK_ID); 12133 } 12134 12135 static bool is_rbtree_node_type(const struct btf_type *t) 12136 { 12137 return t == btf_type_by_id(btf_vmlinux, kf_arg_btf_ids[KF_ARG_RB_NODE_ID]); 12138 } 12139 12140 static bool is_list_node_type(const struct btf_type *t) 12141 { 12142 return t == btf_type_by_id(btf_vmlinux, kf_arg_btf_ids[KF_ARG_LIST_NODE_ID]); 12143 } 12144 12145 static bool is_kfunc_arg_callback(struct bpf_verifier_env *env, const struct btf *btf, 12146 const struct btf_param *arg) 12147 { 12148 const struct btf_type *t; 12149 12150 t = btf_type_resolve_func_ptr(btf, arg->type, NULL); 12151 if (!t) 12152 return false; 12153 12154 return true; 12155 } 12156 12157 /* Returns true if struct is composed of scalars, 4 levels of nesting allowed */ 12158 static bool __btf_type_is_scalar_struct(struct bpf_verifier_env *env, 12159 const struct btf *btf, 12160 const struct btf_type *t, int rec) 12161 { 12162 const struct btf_type *member_type; 12163 const struct btf_member *member; 12164 u32 i; 12165 12166 if (!btf_type_is_struct(t)) 12167 return false; 12168 12169 for_each_member(i, t, member) { 12170 const struct btf_array *array; 12171 12172 member_type = btf_type_skip_modifiers(btf, member->type, NULL); 12173 if (btf_type_is_struct(member_type)) { 12174 if (rec >= 3) { 12175 verbose(env, "max struct nesting depth exceeded\n"); 12176 return false; 12177 } 12178 if (!__btf_type_is_scalar_struct(env, btf, member_type, rec + 1)) 12179 return false; 12180 continue; 12181 } 12182 if (btf_type_is_array(member_type)) { 12183 array = btf_array(member_type); 12184 if (!array->nelems) 12185 return false; 12186 member_type = btf_type_skip_modifiers(btf, array->type, NULL); 12187 if (!btf_type_is_scalar(member_type)) 12188 return false; 12189 continue; 12190 } 12191 if (!btf_type_is_scalar(member_type)) 12192 return false; 12193 } 12194 return true; 12195 } 12196 12197 enum kfunc_ptr_arg_type { 12198 KF_ARG_PTR_TO_CTX, 12199 KF_ARG_PTR_TO_ALLOC_BTF_ID, /* Allocated object */ 12200 KF_ARG_PTR_TO_REFCOUNTED_KPTR, /* Refcounted local kptr */ 12201 KF_ARG_PTR_TO_DYNPTR, 12202 KF_ARG_PTR_TO_ITER, 12203 KF_ARG_PTR_TO_LIST_HEAD, 12204 KF_ARG_PTR_TO_LIST_NODE, 12205 KF_ARG_PTR_TO_BTF_ID, /* Also covers reg2btf_ids conversions */ 12206 KF_ARG_PTR_TO_MEM, 12207 KF_ARG_PTR_TO_MEM_SIZE, /* Size derived from next argument, skip it */ 12208 KF_ARG_PTR_TO_CALLBACK, 12209 KF_ARG_PTR_TO_RB_ROOT, 12210 KF_ARG_PTR_TO_RB_NODE, 12211 KF_ARG_PTR_TO_NULL, 12212 KF_ARG_PTR_TO_CONST_STR, 12213 KF_ARG_PTR_TO_MAP, 12214 KF_ARG_PTR_TO_WORKQUEUE, 12215 KF_ARG_PTR_TO_IRQ_FLAG, 12216 KF_ARG_PTR_TO_RES_SPIN_LOCK, 12217 }; 12218 12219 enum special_kfunc_type { 12220 KF_bpf_obj_new_impl, 12221 KF_bpf_obj_drop_impl, 12222 KF_bpf_refcount_acquire_impl, 12223 KF_bpf_list_push_front_impl, 12224 KF_bpf_list_push_back_impl, 12225 KF_bpf_list_pop_front, 12226 KF_bpf_list_pop_back, 12227 KF_bpf_list_front, 12228 KF_bpf_list_back, 12229 KF_bpf_cast_to_kern_ctx, 12230 KF_bpf_rdonly_cast, 12231 KF_bpf_rcu_read_lock, 12232 KF_bpf_rcu_read_unlock, 12233 KF_bpf_rbtree_remove, 12234 KF_bpf_rbtree_add_impl, 12235 KF_bpf_rbtree_first, 12236 KF_bpf_rbtree_root, 12237 KF_bpf_rbtree_left, 12238 KF_bpf_rbtree_right, 12239 KF_bpf_dynptr_from_skb, 12240 KF_bpf_dynptr_from_xdp, 12241 KF_bpf_dynptr_from_skb_meta, 12242 KF_bpf_xdp_pull_data, 12243 KF_bpf_dynptr_slice, 12244 KF_bpf_dynptr_slice_rdwr, 12245 KF_bpf_dynptr_clone, 12246 KF_bpf_percpu_obj_new_impl, 12247 KF_bpf_percpu_obj_drop_impl, 12248 KF_bpf_throw, 12249 KF_bpf_wq_set_callback_impl, 12250 KF_bpf_preempt_disable, 12251 KF_bpf_preempt_enable, 12252 KF_bpf_iter_css_task_new, 12253 KF_bpf_session_cookie, 12254 KF_bpf_get_kmem_cache, 12255 KF_bpf_local_irq_save, 12256 KF_bpf_local_irq_restore, 12257 KF_bpf_iter_num_new, 12258 KF_bpf_iter_num_next, 12259 KF_bpf_iter_num_destroy, 12260 KF_bpf_set_dentry_xattr, 12261 KF_bpf_remove_dentry_xattr, 12262 KF_bpf_res_spin_lock, 12263 KF_bpf_res_spin_unlock, 12264 KF_bpf_res_spin_lock_irqsave, 12265 KF_bpf_res_spin_unlock_irqrestore, 12266 KF___bpf_trap, 12267 }; 12268 12269 BTF_ID_LIST(special_kfunc_list) 12270 BTF_ID(func, bpf_obj_new_impl) 12271 BTF_ID(func, bpf_obj_drop_impl) 12272 BTF_ID(func, bpf_refcount_acquire_impl) 12273 BTF_ID(func, bpf_list_push_front_impl) 12274 BTF_ID(func, bpf_list_push_back_impl) 12275 BTF_ID(func, bpf_list_pop_front) 12276 BTF_ID(func, bpf_list_pop_back) 12277 BTF_ID(func, bpf_list_front) 12278 BTF_ID(func, bpf_list_back) 12279 BTF_ID(func, bpf_cast_to_kern_ctx) 12280 BTF_ID(func, bpf_rdonly_cast) 12281 BTF_ID(func, bpf_rcu_read_lock) 12282 BTF_ID(func, bpf_rcu_read_unlock) 12283 BTF_ID(func, bpf_rbtree_remove) 12284 BTF_ID(func, bpf_rbtree_add_impl) 12285 BTF_ID(func, bpf_rbtree_first) 12286 BTF_ID(func, bpf_rbtree_root) 12287 BTF_ID(func, bpf_rbtree_left) 12288 BTF_ID(func, bpf_rbtree_right) 12289 #ifdef CONFIG_NET 12290 BTF_ID(func, bpf_dynptr_from_skb) 12291 BTF_ID(func, bpf_dynptr_from_xdp) 12292 BTF_ID(func, bpf_dynptr_from_skb_meta) 12293 BTF_ID(func, bpf_xdp_pull_data) 12294 #else 12295 BTF_ID_UNUSED 12296 BTF_ID_UNUSED 12297 BTF_ID_UNUSED 12298 BTF_ID_UNUSED 12299 #endif 12300 BTF_ID(func, bpf_dynptr_slice) 12301 BTF_ID(func, bpf_dynptr_slice_rdwr) 12302 BTF_ID(func, bpf_dynptr_clone) 12303 BTF_ID(func, bpf_percpu_obj_new_impl) 12304 BTF_ID(func, bpf_percpu_obj_drop_impl) 12305 BTF_ID(func, bpf_throw) 12306 BTF_ID(func, bpf_wq_set_callback_impl) 12307 BTF_ID(func, bpf_preempt_disable) 12308 BTF_ID(func, bpf_preempt_enable) 12309 #ifdef CONFIG_CGROUPS 12310 BTF_ID(func, bpf_iter_css_task_new) 12311 #else 12312 BTF_ID_UNUSED 12313 #endif 12314 #ifdef CONFIG_BPF_EVENTS 12315 BTF_ID(func, bpf_session_cookie) 12316 #else 12317 BTF_ID_UNUSED 12318 #endif 12319 BTF_ID(func, bpf_get_kmem_cache) 12320 BTF_ID(func, bpf_local_irq_save) 12321 BTF_ID(func, bpf_local_irq_restore) 12322 BTF_ID(func, bpf_iter_num_new) 12323 BTF_ID(func, bpf_iter_num_next) 12324 BTF_ID(func, bpf_iter_num_destroy) 12325 #ifdef CONFIG_BPF_LSM 12326 BTF_ID(func, bpf_set_dentry_xattr) 12327 BTF_ID(func, bpf_remove_dentry_xattr) 12328 #else 12329 BTF_ID_UNUSED 12330 BTF_ID_UNUSED 12331 #endif 12332 BTF_ID(func, bpf_res_spin_lock) 12333 BTF_ID(func, bpf_res_spin_unlock) 12334 BTF_ID(func, bpf_res_spin_lock_irqsave) 12335 BTF_ID(func, bpf_res_spin_unlock_irqrestore) 12336 BTF_ID(func, __bpf_trap) 12337 12338 static bool is_kfunc_ret_null(struct bpf_kfunc_call_arg_meta *meta) 12339 { 12340 if (meta->func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl] && 12341 meta->arg_owning_ref) { 12342 return false; 12343 } 12344 12345 return meta->kfunc_flags & KF_RET_NULL; 12346 } 12347 12348 static bool is_kfunc_bpf_rcu_read_lock(struct bpf_kfunc_call_arg_meta *meta) 12349 { 12350 return meta->func_id == special_kfunc_list[KF_bpf_rcu_read_lock]; 12351 } 12352 12353 static bool is_kfunc_bpf_rcu_read_unlock(struct bpf_kfunc_call_arg_meta *meta) 12354 { 12355 return meta->func_id == special_kfunc_list[KF_bpf_rcu_read_unlock]; 12356 } 12357 12358 static bool is_kfunc_bpf_preempt_disable(struct bpf_kfunc_call_arg_meta *meta) 12359 { 12360 return meta->func_id == special_kfunc_list[KF_bpf_preempt_disable]; 12361 } 12362 12363 static bool is_kfunc_bpf_preempt_enable(struct bpf_kfunc_call_arg_meta *meta) 12364 { 12365 return meta->func_id == special_kfunc_list[KF_bpf_preempt_enable]; 12366 } 12367 12368 static bool is_kfunc_pkt_changing(struct bpf_kfunc_call_arg_meta *meta) 12369 { 12370 return meta->func_id == special_kfunc_list[KF_bpf_xdp_pull_data]; 12371 } 12372 12373 static enum kfunc_ptr_arg_type 12374 get_kfunc_ptr_arg_type(struct bpf_verifier_env *env, 12375 struct bpf_kfunc_call_arg_meta *meta, 12376 const struct btf_type *t, const struct btf_type *ref_t, 12377 const char *ref_tname, const struct btf_param *args, 12378 int argno, int nargs) 12379 { 12380 u32 regno = argno + 1; 12381 struct bpf_reg_state *regs = cur_regs(env); 12382 struct bpf_reg_state *reg = ®s[regno]; 12383 bool arg_mem_size = false; 12384 12385 if (meta->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx]) 12386 return KF_ARG_PTR_TO_CTX; 12387 12388 /* In this function, we verify the kfunc's BTF as per the argument type, 12389 * leaving the rest of the verification with respect to the register 12390 * type to our caller. When a set of conditions hold in the BTF type of 12391 * arguments, we resolve it to a known kfunc_ptr_arg_type. 12392 */ 12393 if (btf_is_prog_ctx_type(&env->log, meta->btf, t, resolve_prog_type(env->prog), argno)) 12394 return KF_ARG_PTR_TO_CTX; 12395 12396 if (is_kfunc_arg_nullable(meta->btf, &args[argno]) && register_is_null(reg)) 12397 return KF_ARG_PTR_TO_NULL; 12398 12399 if (is_kfunc_arg_alloc_obj(meta->btf, &args[argno])) 12400 return KF_ARG_PTR_TO_ALLOC_BTF_ID; 12401 12402 if (is_kfunc_arg_refcounted_kptr(meta->btf, &args[argno])) 12403 return KF_ARG_PTR_TO_REFCOUNTED_KPTR; 12404 12405 if (is_kfunc_arg_dynptr(meta->btf, &args[argno])) 12406 return KF_ARG_PTR_TO_DYNPTR; 12407 12408 if (is_kfunc_arg_iter(meta, argno, &args[argno])) 12409 return KF_ARG_PTR_TO_ITER; 12410 12411 if (is_kfunc_arg_list_head(meta->btf, &args[argno])) 12412 return KF_ARG_PTR_TO_LIST_HEAD; 12413 12414 if (is_kfunc_arg_list_node(meta->btf, &args[argno])) 12415 return KF_ARG_PTR_TO_LIST_NODE; 12416 12417 if (is_kfunc_arg_rbtree_root(meta->btf, &args[argno])) 12418 return KF_ARG_PTR_TO_RB_ROOT; 12419 12420 if (is_kfunc_arg_rbtree_node(meta->btf, &args[argno])) 12421 return KF_ARG_PTR_TO_RB_NODE; 12422 12423 if (is_kfunc_arg_const_str(meta->btf, &args[argno])) 12424 return KF_ARG_PTR_TO_CONST_STR; 12425 12426 if (is_kfunc_arg_map(meta->btf, &args[argno])) 12427 return KF_ARG_PTR_TO_MAP; 12428 12429 if (is_kfunc_arg_wq(meta->btf, &args[argno])) 12430 return KF_ARG_PTR_TO_WORKQUEUE; 12431 12432 if (is_kfunc_arg_irq_flag(meta->btf, &args[argno])) 12433 return KF_ARG_PTR_TO_IRQ_FLAG; 12434 12435 if (is_kfunc_arg_res_spin_lock(meta->btf, &args[argno])) 12436 return KF_ARG_PTR_TO_RES_SPIN_LOCK; 12437 12438 if ((base_type(reg->type) == PTR_TO_BTF_ID || reg2btf_ids[base_type(reg->type)])) { 12439 if (!btf_type_is_struct(ref_t)) { 12440 verbose(env, "kernel function %s args#%d pointer type %s %s is not supported\n", 12441 meta->func_name, argno, btf_type_str(ref_t), ref_tname); 12442 return -EINVAL; 12443 } 12444 return KF_ARG_PTR_TO_BTF_ID; 12445 } 12446 12447 if (is_kfunc_arg_callback(env, meta->btf, &args[argno])) 12448 return KF_ARG_PTR_TO_CALLBACK; 12449 12450 if (argno + 1 < nargs && 12451 (is_kfunc_arg_mem_size(meta->btf, &args[argno + 1], ®s[regno + 1]) || 12452 is_kfunc_arg_const_mem_size(meta->btf, &args[argno + 1], ®s[regno + 1]))) 12453 arg_mem_size = true; 12454 12455 /* This is the catch all argument type of register types supported by 12456 * check_helper_mem_access. However, we only allow when argument type is 12457 * pointer to scalar, or struct composed (recursively) of scalars. When 12458 * arg_mem_size is true, the pointer can be void *. 12459 */ 12460 if (!btf_type_is_scalar(ref_t) && !__btf_type_is_scalar_struct(env, meta->btf, ref_t, 0) && 12461 (arg_mem_size ? !btf_type_is_void(ref_t) : 1)) { 12462 verbose(env, "arg#%d pointer type %s %s must point to %sscalar, or struct with scalar\n", 12463 argno, btf_type_str(ref_t), ref_tname, arg_mem_size ? "void, " : ""); 12464 return -EINVAL; 12465 } 12466 return arg_mem_size ? KF_ARG_PTR_TO_MEM_SIZE : KF_ARG_PTR_TO_MEM; 12467 } 12468 12469 static int process_kf_arg_ptr_to_btf_id(struct bpf_verifier_env *env, 12470 struct bpf_reg_state *reg, 12471 const struct btf_type *ref_t, 12472 const char *ref_tname, u32 ref_id, 12473 struct bpf_kfunc_call_arg_meta *meta, 12474 int argno) 12475 { 12476 const struct btf_type *reg_ref_t; 12477 bool strict_type_match = false; 12478 const struct btf *reg_btf; 12479 const char *reg_ref_tname; 12480 bool taking_projection; 12481 bool struct_same; 12482 u32 reg_ref_id; 12483 12484 if (base_type(reg->type) == PTR_TO_BTF_ID) { 12485 reg_btf = reg->btf; 12486 reg_ref_id = reg->btf_id; 12487 } else { 12488 reg_btf = btf_vmlinux; 12489 reg_ref_id = *reg2btf_ids[base_type(reg->type)]; 12490 } 12491 12492 /* Enforce strict type matching for calls to kfuncs that are acquiring 12493 * or releasing a reference, or are no-cast aliases. We do _not_ 12494 * enforce strict matching for plain KF_TRUSTED_ARGS kfuncs by default, 12495 * as we want to enable BPF programs to pass types that are bitwise 12496 * equivalent without forcing them to explicitly cast with something 12497 * like bpf_cast_to_kern_ctx(). 12498 * 12499 * For example, say we had a type like the following: 12500 * 12501 * struct bpf_cpumask { 12502 * cpumask_t cpumask; 12503 * refcount_t usage; 12504 * }; 12505 * 12506 * Note that as specified in <linux/cpumask.h>, cpumask_t is typedef'ed 12507 * to a struct cpumask, so it would be safe to pass a struct 12508 * bpf_cpumask * to a kfunc expecting a struct cpumask *. 12509 * 12510 * The philosophy here is similar to how we allow scalars of different 12511 * types to be passed to kfuncs as long as the size is the same. The 12512 * only difference here is that we're simply allowing 12513 * btf_struct_ids_match() to walk the struct at the 0th offset, and 12514 * resolve types. 12515 */ 12516 if ((is_kfunc_release(meta) && reg->ref_obj_id) || 12517 btf_type_ids_nocast_alias(&env->log, reg_btf, reg_ref_id, meta->btf, ref_id)) 12518 strict_type_match = true; 12519 12520 WARN_ON_ONCE(is_kfunc_release(meta) && 12521 (reg->off || !tnum_is_const(reg->var_off) || 12522 reg->var_off.value)); 12523 12524 reg_ref_t = btf_type_skip_modifiers(reg_btf, reg_ref_id, ®_ref_id); 12525 reg_ref_tname = btf_name_by_offset(reg_btf, reg_ref_t->name_off); 12526 struct_same = btf_struct_ids_match(&env->log, reg_btf, reg_ref_id, reg->off, meta->btf, ref_id, strict_type_match); 12527 /* If kfunc is accepting a projection type (ie. __sk_buff), it cannot 12528 * actually use it -- it must cast to the underlying type. So we allow 12529 * caller to pass in the underlying type. 12530 */ 12531 taking_projection = btf_is_projection_of(ref_tname, reg_ref_tname); 12532 if (!taking_projection && !struct_same) { 12533 verbose(env, "kernel function %s args#%d expected pointer to %s %s but R%d has a pointer to %s %s\n", 12534 meta->func_name, argno, btf_type_str(ref_t), ref_tname, argno + 1, 12535 btf_type_str(reg_ref_t), reg_ref_tname); 12536 return -EINVAL; 12537 } 12538 return 0; 12539 } 12540 12541 static int process_irq_flag(struct bpf_verifier_env *env, int regno, 12542 struct bpf_kfunc_call_arg_meta *meta) 12543 { 12544 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno]; 12545 int err, kfunc_class = IRQ_NATIVE_KFUNC; 12546 bool irq_save; 12547 12548 if (meta->func_id == special_kfunc_list[KF_bpf_local_irq_save] || 12549 meta->func_id == special_kfunc_list[KF_bpf_res_spin_lock_irqsave]) { 12550 irq_save = true; 12551 if (meta->func_id == special_kfunc_list[KF_bpf_res_spin_lock_irqsave]) 12552 kfunc_class = IRQ_LOCK_KFUNC; 12553 } else if (meta->func_id == special_kfunc_list[KF_bpf_local_irq_restore] || 12554 meta->func_id == special_kfunc_list[KF_bpf_res_spin_unlock_irqrestore]) { 12555 irq_save = false; 12556 if (meta->func_id == special_kfunc_list[KF_bpf_res_spin_unlock_irqrestore]) 12557 kfunc_class = IRQ_LOCK_KFUNC; 12558 } else { 12559 verifier_bug(env, "unknown irq flags kfunc"); 12560 return -EFAULT; 12561 } 12562 12563 if (irq_save) { 12564 if (!is_irq_flag_reg_valid_uninit(env, reg)) { 12565 verbose(env, "expected uninitialized irq flag as arg#%d\n", regno - 1); 12566 return -EINVAL; 12567 } 12568 12569 err = check_mem_access(env, env->insn_idx, regno, 0, BPF_DW, BPF_WRITE, -1, false, false); 12570 if (err) 12571 return err; 12572 12573 err = mark_stack_slot_irq_flag(env, meta, reg, env->insn_idx, kfunc_class); 12574 if (err) 12575 return err; 12576 } else { 12577 err = is_irq_flag_reg_valid_init(env, reg); 12578 if (err) { 12579 verbose(env, "expected an initialized irq flag as arg#%d\n", regno - 1); 12580 return err; 12581 } 12582 12583 err = mark_irq_flag_read(env, reg); 12584 if (err) 12585 return err; 12586 12587 err = unmark_stack_slot_irq_flag(env, reg, kfunc_class); 12588 if (err) 12589 return err; 12590 } 12591 return 0; 12592 } 12593 12594 12595 static int ref_set_non_owning(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 12596 { 12597 struct btf_record *rec = reg_btf_record(reg); 12598 12599 if (!env->cur_state->active_locks) { 12600 verifier_bug(env, "%s w/o active lock", __func__); 12601 return -EFAULT; 12602 } 12603 12604 if (type_flag(reg->type) & NON_OWN_REF) { 12605 verifier_bug(env, "NON_OWN_REF already set"); 12606 return -EFAULT; 12607 } 12608 12609 reg->type |= NON_OWN_REF; 12610 if (rec->refcount_off >= 0) 12611 reg->type |= MEM_RCU; 12612 12613 return 0; 12614 } 12615 12616 static int ref_convert_owning_non_owning(struct bpf_verifier_env *env, u32 ref_obj_id) 12617 { 12618 struct bpf_verifier_state *state = env->cur_state; 12619 struct bpf_func_state *unused; 12620 struct bpf_reg_state *reg; 12621 int i; 12622 12623 if (!ref_obj_id) { 12624 verifier_bug(env, "ref_obj_id is zero for owning -> non-owning conversion"); 12625 return -EFAULT; 12626 } 12627 12628 for (i = 0; i < state->acquired_refs; i++) { 12629 if (state->refs[i].id != ref_obj_id) 12630 continue; 12631 12632 /* Clear ref_obj_id here so release_reference doesn't clobber 12633 * the whole reg 12634 */ 12635 bpf_for_each_reg_in_vstate(env->cur_state, unused, reg, ({ 12636 if (reg->ref_obj_id == ref_obj_id) { 12637 reg->ref_obj_id = 0; 12638 ref_set_non_owning(env, reg); 12639 } 12640 })); 12641 return 0; 12642 } 12643 12644 verifier_bug(env, "ref state missing for ref_obj_id"); 12645 return -EFAULT; 12646 } 12647 12648 /* Implementation details: 12649 * 12650 * Each register points to some region of memory, which we define as an 12651 * allocation. Each allocation may embed a bpf_spin_lock which protects any 12652 * special BPF objects (bpf_list_head, bpf_rb_root, etc.) part of the same 12653 * allocation. The lock and the data it protects are colocated in the same 12654 * memory region. 12655 * 12656 * Hence, everytime a register holds a pointer value pointing to such 12657 * allocation, the verifier preserves a unique reg->id for it. 12658 * 12659 * The verifier remembers the lock 'ptr' and the lock 'id' whenever 12660 * bpf_spin_lock is called. 12661 * 12662 * To enable this, lock state in the verifier captures two values: 12663 * active_lock.ptr = Register's type specific pointer 12664 * active_lock.id = A unique ID for each register pointer value 12665 * 12666 * Currently, PTR_TO_MAP_VALUE and PTR_TO_BTF_ID | MEM_ALLOC are the two 12667 * supported register types. 12668 * 12669 * The active_lock.ptr in case of map values is the reg->map_ptr, and in case of 12670 * allocated objects is the reg->btf pointer. 12671 * 12672 * The active_lock.id is non-unique for maps supporting direct_value_addr, as we 12673 * can establish the provenance of the map value statically for each distinct 12674 * lookup into such maps. They always contain a single map value hence unique 12675 * IDs for each pseudo load pessimizes the algorithm and rejects valid programs. 12676 * 12677 * So, in case of global variables, they use array maps with max_entries = 1, 12678 * hence their active_lock.ptr becomes map_ptr and id = 0 (since they all point 12679 * into the same map value as max_entries is 1, as described above). 12680 * 12681 * In case of inner map lookups, the inner map pointer has same map_ptr as the 12682 * outer map pointer (in verifier context), but each lookup into an inner map 12683 * assigns a fresh reg->id to the lookup, so while lookups into distinct inner 12684 * maps from the same outer map share the same map_ptr as active_lock.ptr, they 12685 * will get different reg->id assigned to each lookup, hence different 12686 * active_lock.id. 12687 * 12688 * In case of allocated objects, active_lock.ptr is the reg->btf, and the 12689 * reg->id is a unique ID preserved after the NULL pointer check on the pointer 12690 * returned from bpf_obj_new. Each allocation receives a new reg->id. 12691 */ 12692 static int check_reg_allocation_locked(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 12693 { 12694 struct bpf_reference_state *s; 12695 void *ptr; 12696 u32 id; 12697 12698 switch ((int)reg->type) { 12699 case PTR_TO_MAP_VALUE: 12700 ptr = reg->map_ptr; 12701 break; 12702 case PTR_TO_BTF_ID | MEM_ALLOC: 12703 ptr = reg->btf; 12704 break; 12705 default: 12706 verifier_bug(env, "unknown reg type for lock check"); 12707 return -EFAULT; 12708 } 12709 id = reg->id; 12710 12711 if (!env->cur_state->active_locks) 12712 return -EINVAL; 12713 s = find_lock_state(env->cur_state, REF_TYPE_LOCK_MASK, id, ptr); 12714 if (!s) { 12715 verbose(env, "held lock and object are not in the same allocation\n"); 12716 return -EINVAL; 12717 } 12718 return 0; 12719 } 12720 12721 static bool is_bpf_list_api_kfunc(u32 btf_id) 12722 { 12723 return btf_id == special_kfunc_list[KF_bpf_list_push_front_impl] || 12724 btf_id == special_kfunc_list[KF_bpf_list_push_back_impl] || 12725 btf_id == special_kfunc_list[KF_bpf_list_pop_front] || 12726 btf_id == special_kfunc_list[KF_bpf_list_pop_back] || 12727 btf_id == special_kfunc_list[KF_bpf_list_front] || 12728 btf_id == special_kfunc_list[KF_bpf_list_back]; 12729 } 12730 12731 static bool is_bpf_rbtree_api_kfunc(u32 btf_id) 12732 { 12733 return btf_id == special_kfunc_list[KF_bpf_rbtree_add_impl] || 12734 btf_id == special_kfunc_list[KF_bpf_rbtree_remove] || 12735 btf_id == special_kfunc_list[KF_bpf_rbtree_first] || 12736 btf_id == special_kfunc_list[KF_bpf_rbtree_root] || 12737 btf_id == special_kfunc_list[KF_bpf_rbtree_left] || 12738 btf_id == special_kfunc_list[KF_bpf_rbtree_right]; 12739 } 12740 12741 static bool is_bpf_iter_num_api_kfunc(u32 btf_id) 12742 { 12743 return btf_id == special_kfunc_list[KF_bpf_iter_num_new] || 12744 btf_id == special_kfunc_list[KF_bpf_iter_num_next] || 12745 btf_id == special_kfunc_list[KF_bpf_iter_num_destroy]; 12746 } 12747 12748 static bool is_bpf_graph_api_kfunc(u32 btf_id) 12749 { 12750 return is_bpf_list_api_kfunc(btf_id) || is_bpf_rbtree_api_kfunc(btf_id) || 12751 btf_id == special_kfunc_list[KF_bpf_refcount_acquire_impl]; 12752 } 12753 12754 static bool is_bpf_res_spin_lock_kfunc(u32 btf_id) 12755 { 12756 return btf_id == special_kfunc_list[KF_bpf_res_spin_lock] || 12757 btf_id == special_kfunc_list[KF_bpf_res_spin_unlock] || 12758 btf_id == special_kfunc_list[KF_bpf_res_spin_lock_irqsave] || 12759 btf_id == special_kfunc_list[KF_bpf_res_spin_unlock_irqrestore]; 12760 } 12761 12762 static bool kfunc_spin_allowed(u32 btf_id) 12763 { 12764 return is_bpf_graph_api_kfunc(btf_id) || is_bpf_iter_num_api_kfunc(btf_id) || 12765 is_bpf_res_spin_lock_kfunc(btf_id); 12766 } 12767 12768 static bool is_sync_callback_calling_kfunc(u32 btf_id) 12769 { 12770 return btf_id == special_kfunc_list[KF_bpf_rbtree_add_impl]; 12771 } 12772 12773 static bool is_async_callback_calling_kfunc(u32 btf_id) 12774 { 12775 return btf_id == special_kfunc_list[KF_bpf_wq_set_callback_impl]; 12776 } 12777 12778 static bool is_bpf_throw_kfunc(struct bpf_insn *insn) 12779 { 12780 return bpf_pseudo_kfunc_call(insn) && insn->off == 0 && 12781 insn->imm == special_kfunc_list[KF_bpf_throw]; 12782 } 12783 12784 static bool is_bpf_wq_set_callback_impl_kfunc(u32 btf_id) 12785 { 12786 return btf_id == special_kfunc_list[KF_bpf_wq_set_callback_impl]; 12787 } 12788 12789 static bool is_callback_calling_kfunc(u32 btf_id) 12790 { 12791 return is_sync_callback_calling_kfunc(btf_id) || 12792 is_async_callback_calling_kfunc(btf_id); 12793 } 12794 12795 static bool is_rbtree_lock_required_kfunc(u32 btf_id) 12796 { 12797 return is_bpf_rbtree_api_kfunc(btf_id); 12798 } 12799 12800 static bool check_kfunc_is_graph_root_api(struct bpf_verifier_env *env, 12801 enum btf_field_type head_field_type, 12802 u32 kfunc_btf_id) 12803 { 12804 bool ret; 12805 12806 switch (head_field_type) { 12807 case BPF_LIST_HEAD: 12808 ret = is_bpf_list_api_kfunc(kfunc_btf_id); 12809 break; 12810 case BPF_RB_ROOT: 12811 ret = is_bpf_rbtree_api_kfunc(kfunc_btf_id); 12812 break; 12813 default: 12814 verbose(env, "verifier internal error: unexpected graph root argument type %s\n", 12815 btf_field_type_name(head_field_type)); 12816 return false; 12817 } 12818 12819 if (!ret) 12820 verbose(env, "verifier internal error: %s head arg for unknown kfunc\n", 12821 btf_field_type_name(head_field_type)); 12822 return ret; 12823 } 12824 12825 static bool check_kfunc_is_graph_node_api(struct bpf_verifier_env *env, 12826 enum btf_field_type node_field_type, 12827 u32 kfunc_btf_id) 12828 { 12829 bool ret; 12830 12831 switch (node_field_type) { 12832 case BPF_LIST_NODE: 12833 ret = (kfunc_btf_id == special_kfunc_list[KF_bpf_list_push_front_impl] || 12834 kfunc_btf_id == special_kfunc_list[KF_bpf_list_push_back_impl]); 12835 break; 12836 case BPF_RB_NODE: 12837 ret = (kfunc_btf_id == special_kfunc_list[KF_bpf_rbtree_remove] || 12838 kfunc_btf_id == special_kfunc_list[KF_bpf_rbtree_add_impl] || 12839 kfunc_btf_id == special_kfunc_list[KF_bpf_rbtree_left] || 12840 kfunc_btf_id == special_kfunc_list[KF_bpf_rbtree_right]); 12841 break; 12842 default: 12843 verbose(env, "verifier internal error: unexpected graph node argument type %s\n", 12844 btf_field_type_name(node_field_type)); 12845 return false; 12846 } 12847 12848 if (!ret) 12849 verbose(env, "verifier internal error: %s node arg for unknown kfunc\n", 12850 btf_field_type_name(node_field_type)); 12851 return ret; 12852 } 12853 12854 static int 12855 __process_kf_arg_ptr_to_graph_root(struct bpf_verifier_env *env, 12856 struct bpf_reg_state *reg, u32 regno, 12857 struct bpf_kfunc_call_arg_meta *meta, 12858 enum btf_field_type head_field_type, 12859 struct btf_field **head_field) 12860 { 12861 const char *head_type_name; 12862 struct btf_field *field; 12863 struct btf_record *rec; 12864 u32 head_off; 12865 12866 if (meta->btf != btf_vmlinux) { 12867 verifier_bug(env, "unexpected btf mismatch in kfunc call"); 12868 return -EFAULT; 12869 } 12870 12871 if (!check_kfunc_is_graph_root_api(env, head_field_type, meta->func_id)) 12872 return -EFAULT; 12873 12874 head_type_name = btf_field_type_name(head_field_type); 12875 if (!tnum_is_const(reg->var_off)) { 12876 verbose(env, 12877 "R%d doesn't have constant offset. %s has to be at the constant offset\n", 12878 regno, head_type_name); 12879 return -EINVAL; 12880 } 12881 12882 rec = reg_btf_record(reg); 12883 head_off = reg->off + reg->var_off.value; 12884 field = btf_record_find(rec, head_off, head_field_type); 12885 if (!field) { 12886 verbose(env, "%s not found at offset=%u\n", head_type_name, head_off); 12887 return -EINVAL; 12888 } 12889 12890 /* All functions require bpf_list_head to be protected using a bpf_spin_lock */ 12891 if (check_reg_allocation_locked(env, reg)) { 12892 verbose(env, "bpf_spin_lock at off=%d must be held for %s\n", 12893 rec->spin_lock_off, head_type_name); 12894 return -EINVAL; 12895 } 12896 12897 if (*head_field) { 12898 verifier_bug(env, "repeating %s arg", head_type_name); 12899 return -EFAULT; 12900 } 12901 *head_field = field; 12902 return 0; 12903 } 12904 12905 static int process_kf_arg_ptr_to_list_head(struct bpf_verifier_env *env, 12906 struct bpf_reg_state *reg, u32 regno, 12907 struct bpf_kfunc_call_arg_meta *meta) 12908 { 12909 return __process_kf_arg_ptr_to_graph_root(env, reg, regno, meta, BPF_LIST_HEAD, 12910 &meta->arg_list_head.field); 12911 } 12912 12913 static int process_kf_arg_ptr_to_rbtree_root(struct bpf_verifier_env *env, 12914 struct bpf_reg_state *reg, u32 regno, 12915 struct bpf_kfunc_call_arg_meta *meta) 12916 { 12917 return __process_kf_arg_ptr_to_graph_root(env, reg, regno, meta, BPF_RB_ROOT, 12918 &meta->arg_rbtree_root.field); 12919 } 12920 12921 static int 12922 __process_kf_arg_ptr_to_graph_node(struct bpf_verifier_env *env, 12923 struct bpf_reg_state *reg, u32 regno, 12924 struct bpf_kfunc_call_arg_meta *meta, 12925 enum btf_field_type head_field_type, 12926 enum btf_field_type node_field_type, 12927 struct btf_field **node_field) 12928 { 12929 const char *node_type_name; 12930 const struct btf_type *et, *t; 12931 struct btf_field *field; 12932 u32 node_off; 12933 12934 if (meta->btf != btf_vmlinux) { 12935 verifier_bug(env, "unexpected btf mismatch in kfunc call"); 12936 return -EFAULT; 12937 } 12938 12939 if (!check_kfunc_is_graph_node_api(env, node_field_type, meta->func_id)) 12940 return -EFAULT; 12941 12942 node_type_name = btf_field_type_name(node_field_type); 12943 if (!tnum_is_const(reg->var_off)) { 12944 verbose(env, 12945 "R%d doesn't have constant offset. %s has to be at the constant offset\n", 12946 regno, node_type_name); 12947 return -EINVAL; 12948 } 12949 12950 node_off = reg->off + reg->var_off.value; 12951 field = reg_find_field_offset(reg, node_off, node_field_type); 12952 if (!field) { 12953 verbose(env, "%s not found at offset=%u\n", node_type_name, node_off); 12954 return -EINVAL; 12955 } 12956 12957 field = *node_field; 12958 12959 et = btf_type_by_id(field->graph_root.btf, field->graph_root.value_btf_id); 12960 t = btf_type_by_id(reg->btf, reg->btf_id); 12961 if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, 0, field->graph_root.btf, 12962 field->graph_root.value_btf_id, true)) { 12963 verbose(env, "operation on %s expects arg#1 %s at offset=%d " 12964 "in struct %s, but arg is at offset=%d in struct %s\n", 12965 btf_field_type_name(head_field_type), 12966 btf_field_type_name(node_field_type), 12967 field->graph_root.node_offset, 12968 btf_name_by_offset(field->graph_root.btf, et->name_off), 12969 node_off, btf_name_by_offset(reg->btf, t->name_off)); 12970 return -EINVAL; 12971 } 12972 meta->arg_btf = reg->btf; 12973 meta->arg_btf_id = reg->btf_id; 12974 12975 if (node_off != field->graph_root.node_offset) { 12976 verbose(env, "arg#1 offset=%d, but expected %s at offset=%d in struct %s\n", 12977 node_off, btf_field_type_name(node_field_type), 12978 field->graph_root.node_offset, 12979 btf_name_by_offset(field->graph_root.btf, et->name_off)); 12980 return -EINVAL; 12981 } 12982 12983 return 0; 12984 } 12985 12986 static int process_kf_arg_ptr_to_list_node(struct bpf_verifier_env *env, 12987 struct bpf_reg_state *reg, u32 regno, 12988 struct bpf_kfunc_call_arg_meta *meta) 12989 { 12990 return __process_kf_arg_ptr_to_graph_node(env, reg, regno, meta, 12991 BPF_LIST_HEAD, BPF_LIST_NODE, 12992 &meta->arg_list_head.field); 12993 } 12994 12995 static int process_kf_arg_ptr_to_rbtree_node(struct bpf_verifier_env *env, 12996 struct bpf_reg_state *reg, u32 regno, 12997 struct bpf_kfunc_call_arg_meta *meta) 12998 { 12999 return __process_kf_arg_ptr_to_graph_node(env, reg, regno, meta, 13000 BPF_RB_ROOT, BPF_RB_NODE, 13001 &meta->arg_rbtree_root.field); 13002 } 13003 13004 /* 13005 * css_task iter allowlist is needed to avoid dead locking on css_set_lock. 13006 * LSM hooks and iters (both sleepable and non-sleepable) are safe. 13007 * Any sleepable progs are also safe since bpf_check_attach_target() enforce 13008 * them can only be attached to some specific hook points. 13009 */ 13010 static bool check_css_task_iter_allowlist(struct bpf_verifier_env *env) 13011 { 13012 enum bpf_prog_type prog_type = resolve_prog_type(env->prog); 13013 13014 switch (prog_type) { 13015 case BPF_PROG_TYPE_LSM: 13016 return true; 13017 case BPF_PROG_TYPE_TRACING: 13018 if (env->prog->expected_attach_type == BPF_TRACE_ITER) 13019 return true; 13020 fallthrough; 13021 default: 13022 return in_sleepable(env); 13023 } 13024 } 13025 13026 static int check_kfunc_args(struct bpf_verifier_env *env, struct bpf_kfunc_call_arg_meta *meta, 13027 int insn_idx) 13028 { 13029 const char *func_name = meta->func_name, *ref_tname; 13030 const struct btf *btf = meta->btf; 13031 const struct btf_param *args; 13032 struct btf_record *rec; 13033 u32 i, nargs; 13034 int ret; 13035 13036 args = (const struct btf_param *)(meta->func_proto + 1); 13037 nargs = btf_type_vlen(meta->func_proto); 13038 if (nargs > MAX_BPF_FUNC_REG_ARGS) { 13039 verbose(env, "Function %s has %d > %d args\n", func_name, nargs, 13040 MAX_BPF_FUNC_REG_ARGS); 13041 return -EINVAL; 13042 } 13043 13044 /* Check that BTF function arguments match actual types that the 13045 * verifier sees. 13046 */ 13047 for (i = 0; i < nargs; i++) { 13048 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[i + 1]; 13049 const struct btf_type *t, *ref_t, *resolve_ret; 13050 enum bpf_arg_type arg_type = ARG_DONTCARE; 13051 u32 regno = i + 1, ref_id, type_size; 13052 bool is_ret_buf_sz = false; 13053 int kf_arg_type; 13054 13055 t = btf_type_skip_modifiers(btf, args[i].type, NULL); 13056 13057 if (is_kfunc_arg_ignore(btf, &args[i])) 13058 continue; 13059 13060 if (is_kfunc_arg_prog(btf, &args[i])) { 13061 /* Used to reject repeated use of __prog. */ 13062 if (meta->arg_prog) { 13063 verifier_bug(env, "Only 1 prog->aux argument supported per-kfunc"); 13064 return -EFAULT; 13065 } 13066 meta->arg_prog = true; 13067 cur_aux(env)->arg_prog = regno; 13068 continue; 13069 } 13070 13071 if (btf_type_is_scalar(t)) { 13072 if (reg->type != SCALAR_VALUE) { 13073 verbose(env, "R%d is not a scalar\n", regno); 13074 return -EINVAL; 13075 } 13076 13077 if (is_kfunc_arg_constant(meta->btf, &args[i])) { 13078 if (meta->arg_constant.found) { 13079 verifier_bug(env, "only one constant argument permitted"); 13080 return -EFAULT; 13081 } 13082 if (!tnum_is_const(reg->var_off)) { 13083 verbose(env, "R%d must be a known constant\n", regno); 13084 return -EINVAL; 13085 } 13086 ret = mark_chain_precision(env, regno); 13087 if (ret < 0) 13088 return ret; 13089 meta->arg_constant.found = true; 13090 meta->arg_constant.value = reg->var_off.value; 13091 } else if (is_kfunc_arg_scalar_with_name(btf, &args[i], "rdonly_buf_size")) { 13092 meta->r0_rdonly = true; 13093 is_ret_buf_sz = true; 13094 } else if (is_kfunc_arg_scalar_with_name(btf, &args[i], "rdwr_buf_size")) { 13095 is_ret_buf_sz = true; 13096 } 13097 13098 if (is_ret_buf_sz) { 13099 if (meta->r0_size) { 13100 verbose(env, "2 or more rdonly/rdwr_buf_size parameters for kfunc"); 13101 return -EINVAL; 13102 } 13103 13104 if (!tnum_is_const(reg->var_off)) { 13105 verbose(env, "R%d is not a const\n", regno); 13106 return -EINVAL; 13107 } 13108 13109 meta->r0_size = reg->var_off.value; 13110 ret = mark_chain_precision(env, regno); 13111 if (ret) 13112 return ret; 13113 } 13114 continue; 13115 } 13116 13117 if (!btf_type_is_ptr(t)) { 13118 verbose(env, "Unrecognized arg#%d type %s\n", i, btf_type_str(t)); 13119 return -EINVAL; 13120 } 13121 13122 if ((is_kfunc_trusted_args(meta) || is_kfunc_rcu(meta)) && 13123 (register_is_null(reg) || type_may_be_null(reg->type)) && 13124 !is_kfunc_arg_nullable(meta->btf, &args[i])) { 13125 verbose(env, "Possibly NULL pointer passed to trusted arg%d\n", i); 13126 return -EACCES; 13127 } 13128 13129 if (reg->ref_obj_id) { 13130 if (is_kfunc_release(meta) && meta->ref_obj_id) { 13131 verifier_bug(env, "more than one arg with ref_obj_id R%d %u %u", 13132 regno, reg->ref_obj_id, 13133 meta->ref_obj_id); 13134 return -EFAULT; 13135 } 13136 meta->ref_obj_id = reg->ref_obj_id; 13137 if (is_kfunc_release(meta)) 13138 meta->release_regno = regno; 13139 } 13140 13141 ref_t = btf_type_skip_modifiers(btf, t->type, &ref_id); 13142 ref_tname = btf_name_by_offset(btf, ref_t->name_off); 13143 13144 kf_arg_type = get_kfunc_ptr_arg_type(env, meta, t, ref_t, ref_tname, args, i, nargs); 13145 if (kf_arg_type < 0) 13146 return kf_arg_type; 13147 13148 switch (kf_arg_type) { 13149 case KF_ARG_PTR_TO_NULL: 13150 continue; 13151 case KF_ARG_PTR_TO_MAP: 13152 if (!reg->map_ptr) { 13153 verbose(env, "pointer in R%d isn't map pointer\n", regno); 13154 return -EINVAL; 13155 } 13156 if (meta->map.ptr && reg->map_ptr->record->wq_off >= 0) { 13157 /* Use map_uid (which is unique id of inner map) to reject: 13158 * inner_map1 = bpf_map_lookup_elem(outer_map, key1) 13159 * inner_map2 = bpf_map_lookup_elem(outer_map, key2) 13160 * if (inner_map1 && inner_map2) { 13161 * wq = bpf_map_lookup_elem(inner_map1); 13162 * if (wq) 13163 * // mismatch would have been allowed 13164 * bpf_wq_init(wq, inner_map2); 13165 * } 13166 * 13167 * Comparing map_ptr is enough to distinguish normal and outer maps. 13168 */ 13169 if (meta->map.ptr != reg->map_ptr || 13170 meta->map.uid != reg->map_uid) { 13171 verbose(env, 13172 "workqueue pointer in R1 map_uid=%d doesn't match map pointer in R2 map_uid=%d\n", 13173 meta->map.uid, reg->map_uid); 13174 return -EINVAL; 13175 } 13176 } 13177 meta->map.ptr = reg->map_ptr; 13178 meta->map.uid = reg->map_uid; 13179 fallthrough; 13180 case KF_ARG_PTR_TO_ALLOC_BTF_ID: 13181 case KF_ARG_PTR_TO_BTF_ID: 13182 if (!is_kfunc_trusted_args(meta) && !is_kfunc_rcu(meta)) 13183 break; 13184 13185 if (!is_trusted_reg(reg)) { 13186 if (!is_kfunc_rcu(meta)) { 13187 verbose(env, "R%d must be referenced or trusted\n", regno); 13188 return -EINVAL; 13189 } 13190 if (!is_rcu_reg(reg)) { 13191 verbose(env, "R%d must be a rcu pointer\n", regno); 13192 return -EINVAL; 13193 } 13194 } 13195 fallthrough; 13196 case KF_ARG_PTR_TO_CTX: 13197 case KF_ARG_PTR_TO_DYNPTR: 13198 case KF_ARG_PTR_TO_ITER: 13199 case KF_ARG_PTR_TO_LIST_HEAD: 13200 case KF_ARG_PTR_TO_LIST_NODE: 13201 case KF_ARG_PTR_TO_RB_ROOT: 13202 case KF_ARG_PTR_TO_RB_NODE: 13203 case KF_ARG_PTR_TO_MEM: 13204 case KF_ARG_PTR_TO_MEM_SIZE: 13205 case KF_ARG_PTR_TO_CALLBACK: 13206 case KF_ARG_PTR_TO_REFCOUNTED_KPTR: 13207 case KF_ARG_PTR_TO_CONST_STR: 13208 case KF_ARG_PTR_TO_WORKQUEUE: 13209 case KF_ARG_PTR_TO_IRQ_FLAG: 13210 case KF_ARG_PTR_TO_RES_SPIN_LOCK: 13211 break; 13212 default: 13213 verifier_bug(env, "unknown kfunc arg type %d", kf_arg_type); 13214 return -EFAULT; 13215 } 13216 13217 if (is_kfunc_release(meta) && reg->ref_obj_id) 13218 arg_type |= OBJ_RELEASE; 13219 ret = check_func_arg_reg_off(env, reg, regno, arg_type); 13220 if (ret < 0) 13221 return ret; 13222 13223 switch (kf_arg_type) { 13224 case KF_ARG_PTR_TO_CTX: 13225 if (reg->type != PTR_TO_CTX) { 13226 verbose(env, "arg#%d expected pointer to ctx, but got %s\n", 13227 i, reg_type_str(env, reg->type)); 13228 return -EINVAL; 13229 } 13230 13231 if (meta->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx]) { 13232 ret = get_kern_ctx_btf_id(&env->log, resolve_prog_type(env->prog)); 13233 if (ret < 0) 13234 return -EINVAL; 13235 meta->ret_btf_id = ret; 13236 } 13237 break; 13238 case KF_ARG_PTR_TO_ALLOC_BTF_ID: 13239 if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC)) { 13240 if (meta->func_id != special_kfunc_list[KF_bpf_obj_drop_impl]) { 13241 verbose(env, "arg#%d expected for bpf_obj_drop_impl()\n", i); 13242 return -EINVAL; 13243 } 13244 } else if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC | MEM_PERCPU)) { 13245 if (meta->func_id != special_kfunc_list[KF_bpf_percpu_obj_drop_impl]) { 13246 verbose(env, "arg#%d expected for bpf_percpu_obj_drop_impl()\n", i); 13247 return -EINVAL; 13248 } 13249 } else { 13250 verbose(env, "arg#%d expected pointer to allocated object\n", i); 13251 return -EINVAL; 13252 } 13253 if (!reg->ref_obj_id) { 13254 verbose(env, "allocated object must be referenced\n"); 13255 return -EINVAL; 13256 } 13257 if (meta->btf == btf_vmlinux) { 13258 meta->arg_btf = reg->btf; 13259 meta->arg_btf_id = reg->btf_id; 13260 } 13261 break; 13262 case KF_ARG_PTR_TO_DYNPTR: 13263 { 13264 enum bpf_arg_type dynptr_arg_type = ARG_PTR_TO_DYNPTR; 13265 int clone_ref_obj_id = 0; 13266 13267 if (reg->type == CONST_PTR_TO_DYNPTR) 13268 dynptr_arg_type |= MEM_RDONLY; 13269 13270 if (is_kfunc_arg_uninit(btf, &args[i])) 13271 dynptr_arg_type |= MEM_UNINIT; 13272 13273 if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_from_skb]) { 13274 dynptr_arg_type |= DYNPTR_TYPE_SKB; 13275 } else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_from_xdp]) { 13276 dynptr_arg_type |= DYNPTR_TYPE_XDP; 13277 } else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_from_skb_meta]) { 13278 dynptr_arg_type |= DYNPTR_TYPE_SKB_META; 13279 } else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_clone] && 13280 (dynptr_arg_type & MEM_UNINIT)) { 13281 enum bpf_dynptr_type parent_type = meta->initialized_dynptr.type; 13282 13283 if (parent_type == BPF_DYNPTR_TYPE_INVALID) { 13284 verifier_bug(env, "no dynptr type for parent of clone"); 13285 return -EFAULT; 13286 } 13287 13288 dynptr_arg_type |= (unsigned int)get_dynptr_type_flag(parent_type); 13289 clone_ref_obj_id = meta->initialized_dynptr.ref_obj_id; 13290 if (dynptr_type_refcounted(parent_type) && !clone_ref_obj_id) { 13291 verifier_bug(env, "missing ref obj id for parent of clone"); 13292 return -EFAULT; 13293 } 13294 } 13295 13296 ret = process_dynptr_func(env, regno, insn_idx, dynptr_arg_type, clone_ref_obj_id); 13297 if (ret < 0) 13298 return ret; 13299 13300 if (!(dynptr_arg_type & MEM_UNINIT)) { 13301 int id = dynptr_id(env, reg); 13302 13303 if (id < 0) { 13304 verifier_bug(env, "failed to obtain dynptr id"); 13305 return id; 13306 } 13307 meta->initialized_dynptr.id = id; 13308 meta->initialized_dynptr.type = dynptr_get_type(env, reg); 13309 meta->initialized_dynptr.ref_obj_id = dynptr_ref_obj_id(env, reg); 13310 } 13311 13312 break; 13313 } 13314 case KF_ARG_PTR_TO_ITER: 13315 if (meta->func_id == special_kfunc_list[KF_bpf_iter_css_task_new]) { 13316 if (!check_css_task_iter_allowlist(env)) { 13317 verbose(env, "css_task_iter is only allowed in bpf_lsm, bpf_iter and sleepable progs\n"); 13318 return -EINVAL; 13319 } 13320 } 13321 ret = process_iter_arg(env, regno, insn_idx, meta); 13322 if (ret < 0) 13323 return ret; 13324 break; 13325 case KF_ARG_PTR_TO_LIST_HEAD: 13326 if (reg->type != PTR_TO_MAP_VALUE && 13327 reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) { 13328 verbose(env, "arg#%d expected pointer to map value or allocated object\n", i); 13329 return -EINVAL; 13330 } 13331 if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC) && !reg->ref_obj_id) { 13332 verbose(env, "allocated object must be referenced\n"); 13333 return -EINVAL; 13334 } 13335 ret = process_kf_arg_ptr_to_list_head(env, reg, regno, meta); 13336 if (ret < 0) 13337 return ret; 13338 break; 13339 case KF_ARG_PTR_TO_RB_ROOT: 13340 if (reg->type != PTR_TO_MAP_VALUE && 13341 reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) { 13342 verbose(env, "arg#%d expected pointer to map value or allocated object\n", i); 13343 return -EINVAL; 13344 } 13345 if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC) && !reg->ref_obj_id) { 13346 verbose(env, "allocated object must be referenced\n"); 13347 return -EINVAL; 13348 } 13349 ret = process_kf_arg_ptr_to_rbtree_root(env, reg, regno, meta); 13350 if (ret < 0) 13351 return ret; 13352 break; 13353 case KF_ARG_PTR_TO_LIST_NODE: 13354 if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) { 13355 verbose(env, "arg#%d expected pointer to allocated object\n", i); 13356 return -EINVAL; 13357 } 13358 if (!reg->ref_obj_id) { 13359 verbose(env, "allocated object must be referenced\n"); 13360 return -EINVAL; 13361 } 13362 ret = process_kf_arg_ptr_to_list_node(env, reg, regno, meta); 13363 if (ret < 0) 13364 return ret; 13365 break; 13366 case KF_ARG_PTR_TO_RB_NODE: 13367 if (meta->func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) { 13368 if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) { 13369 verbose(env, "arg#%d expected pointer to allocated object\n", i); 13370 return -EINVAL; 13371 } 13372 if (!reg->ref_obj_id) { 13373 verbose(env, "allocated object must be referenced\n"); 13374 return -EINVAL; 13375 } 13376 } else { 13377 if (!type_is_non_owning_ref(reg->type) && !reg->ref_obj_id) { 13378 verbose(env, "%s can only take non-owning or refcounted bpf_rb_node pointer\n", func_name); 13379 return -EINVAL; 13380 } 13381 if (in_rbtree_lock_required_cb(env)) { 13382 verbose(env, "%s not allowed in rbtree cb\n", func_name); 13383 return -EINVAL; 13384 } 13385 } 13386 13387 ret = process_kf_arg_ptr_to_rbtree_node(env, reg, regno, meta); 13388 if (ret < 0) 13389 return ret; 13390 break; 13391 case KF_ARG_PTR_TO_MAP: 13392 /* If argument has '__map' suffix expect 'struct bpf_map *' */ 13393 ref_id = *reg2btf_ids[CONST_PTR_TO_MAP]; 13394 ref_t = btf_type_by_id(btf_vmlinux, ref_id); 13395 ref_tname = btf_name_by_offset(btf, ref_t->name_off); 13396 fallthrough; 13397 case KF_ARG_PTR_TO_BTF_ID: 13398 /* Only base_type is checked, further checks are done here */ 13399 if ((base_type(reg->type) != PTR_TO_BTF_ID || 13400 (bpf_type_has_unsafe_modifiers(reg->type) && !is_rcu_reg(reg))) && 13401 !reg2btf_ids[base_type(reg->type)]) { 13402 verbose(env, "arg#%d is %s ", i, reg_type_str(env, reg->type)); 13403 verbose(env, "expected %s or socket\n", 13404 reg_type_str(env, base_type(reg->type) | 13405 (type_flag(reg->type) & BPF_REG_TRUSTED_MODIFIERS))); 13406 return -EINVAL; 13407 } 13408 ret = process_kf_arg_ptr_to_btf_id(env, reg, ref_t, ref_tname, ref_id, meta, i); 13409 if (ret < 0) 13410 return ret; 13411 break; 13412 case KF_ARG_PTR_TO_MEM: 13413 resolve_ret = btf_resolve_size(btf, ref_t, &type_size); 13414 if (IS_ERR(resolve_ret)) { 13415 verbose(env, "arg#%d reference type('%s %s') size cannot be determined: %ld\n", 13416 i, btf_type_str(ref_t), ref_tname, PTR_ERR(resolve_ret)); 13417 return -EINVAL; 13418 } 13419 ret = check_mem_reg(env, reg, regno, type_size); 13420 if (ret < 0) 13421 return ret; 13422 break; 13423 case KF_ARG_PTR_TO_MEM_SIZE: 13424 { 13425 struct bpf_reg_state *buff_reg = ®s[regno]; 13426 const struct btf_param *buff_arg = &args[i]; 13427 struct bpf_reg_state *size_reg = ®s[regno + 1]; 13428 const struct btf_param *size_arg = &args[i + 1]; 13429 13430 if (!register_is_null(buff_reg) || !is_kfunc_arg_optional(meta->btf, buff_arg)) { 13431 ret = check_kfunc_mem_size_reg(env, size_reg, regno + 1); 13432 if (ret < 0) { 13433 verbose(env, "arg#%d arg#%d memory, len pair leads to invalid memory access\n", i, i + 1); 13434 return ret; 13435 } 13436 } 13437 13438 if (is_kfunc_arg_const_mem_size(meta->btf, size_arg, size_reg)) { 13439 if (meta->arg_constant.found) { 13440 verifier_bug(env, "only one constant argument permitted"); 13441 return -EFAULT; 13442 } 13443 if (!tnum_is_const(size_reg->var_off)) { 13444 verbose(env, "R%d must be a known constant\n", regno + 1); 13445 return -EINVAL; 13446 } 13447 meta->arg_constant.found = true; 13448 meta->arg_constant.value = size_reg->var_off.value; 13449 } 13450 13451 /* Skip next '__sz' or '__szk' argument */ 13452 i++; 13453 break; 13454 } 13455 case KF_ARG_PTR_TO_CALLBACK: 13456 if (reg->type != PTR_TO_FUNC) { 13457 verbose(env, "arg%d expected pointer to func\n", i); 13458 return -EINVAL; 13459 } 13460 meta->subprogno = reg->subprogno; 13461 break; 13462 case KF_ARG_PTR_TO_REFCOUNTED_KPTR: 13463 if (!type_is_ptr_alloc_obj(reg->type)) { 13464 verbose(env, "arg#%d is neither owning or non-owning ref\n", i); 13465 return -EINVAL; 13466 } 13467 if (!type_is_non_owning_ref(reg->type)) 13468 meta->arg_owning_ref = true; 13469 13470 rec = reg_btf_record(reg); 13471 if (!rec) { 13472 verifier_bug(env, "Couldn't find btf_record"); 13473 return -EFAULT; 13474 } 13475 13476 if (rec->refcount_off < 0) { 13477 verbose(env, "arg#%d doesn't point to a type with bpf_refcount field\n", i); 13478 return -EINVAL; 13479 } 13480 13481 meta->arg_btf = reg->btf; 13482 meta->arg_btf_id = reg->btf_id; 13483 break; 13484 case KF_ARG_PTR_TO_CONST_STR: 13485 if (reg->type != PTR_TO_MAP_VALUE) { 13486 verbose(env, "arg#%d doesn't point to a const string\n", i); 13487 return -EINVAL; 13488 } 13489 ret = check_reg_const_str(env, reg, regno); 13490 if (ret) 13491 return ret; 13492 break; 13493 case KF_ARG_PTR_TO_WORKQUEUE: 13494 if (reg->type != PTR_TO_MAP_VALUE) { 13495 verbose(env, "arg#%d doesn't point to a map value\n", i); 13496 return -EINVAL; 13497 } 13498 ret = process_wq_func(env, regno, meta); 13499 if (ret < 0) 13500 return ret; 13501 break; 13502 case KF_ARG_PTR_TO_IRQ_FLAG: 13503 if (reg->type != PTR_TO_STACK) { 13504 verbose(env, "arg#%d doesn't point to an irq flag on stack\n", i); 13505 return -EINVAL; 13506 } 13507 ret = process_irq_flag(env, regno, meta); 13508 if (ret < 0) 13509 return ret; 13510 break; 13511 case KF_ARG_PTR_TO_RES_SPIN_LOCK: 13512 { 13513 int flags = PROCESS_RES_LOCK; 13514 13515 if (reg->type != PTR_TO_MAP_VALUE && reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) { 13516 verbose(env, "arg#%d doesn't point to map value or allocated object\n", i); 13517 return -EINVAL; 13518 } 13519 13520 if (!is_bpf_res_spin_lock_kfunc(meta->func_id)) 13521 return -EFAULT; 13522 if (meta->func_id == special_kfunc_list[KF_bpf_res_spin_lock] || 13523 meta->func_id == special_kfunc_list[KF_bpf_res_spin_lock_irqsave]) 13524 flags |= PROCESS_SPIN_LOCK; 13525 if (meta->func_id == special_kfunc_list[KF_bpf_res_spin_lock_irqsave] || 13526 meta->func_id == special_kfunc_list[KF_bpf_res_spin_unlock_irqrestore]) 13527 flags |= PROCESS_LOCK_IRQ; 13528 ret = process_spin_lock(env, regno, flags); 13529 if (ret < 0) 13530 return ret; 13531 break; 13532 } 13533 } 13534 } 13535 13536 if (is_kfunc_release(meta) && !meta->release_regno) { 13537 verbose(env, "release kernel function %s expects refcounted PTR_TO_BTF_ID\n", 13538 func_name); 13539 return -EINVAL; 13540 } 13541 13542 return 0; 13543 } 13544 13545 static int fetch_kfunc_meta(struct bpf_verifier_env *env, 13546 struct bpf_insn *insn, 13547 struct bpf_kfunc_call_arg_meta *meta, 13548 const char **kfunc_name) 13549 { 13550 const struct btf_type *func, *func_proto; 13551 u32 func_id, *kfunc_flags; 13552 const char *func_name; 13553 struct btf *desc_btf; 13554 13555 if (kfunc_name) 13556 *kfunc_name = NULL; 13557 13558 if (!insn->imm) 13559 return -EINVAL; 13560 13561 desc_btf = find_kfunc_desc_btf(env, insn->off); 13562 if (IS_ERR(desc_btf)) 13563 return PTR_ERR(desc_btf); 13564 13565 func_id = insn->imm; 13566 func = btf_type_by_id(desc_btf, func_id); 13567 func_name = btf_name_by_offset(desc_btf, func->name_off); 13568 if (kfunc_name) 13569 *kfunc_name = func_name; 13570 func_proto = btf_type_by_id(desc_btf, func->type); 13571 13572 kfunc_flags = btf_kfunc_id_set_contains(desc_btf, func_id, env->prog); 13573 if (!kfunc_flags) { 13574 return -EACCES; 13575 } 13576 13577 memset(meta, 0, sizeof(*meta)); 13578 meta->btf = desc_btf; 13579 meta->func_id = func_id; 13580 meta->kfunc_flags = *kfunc_flags; 13581 meta->func_proto = func_proto; 13582 meta->func_name = func_name; 13583 13584 return 0; 13585 } 13586 13587 /* check special kfuncs and return: 13588 * 1 - not fall-through to 'else' branch, continue verification 13589 * 0 - fall-through to 'else' branch 13590 * < 0 - not fall-through to 'else' branch, return error 13591 */ 13592 static int check_special_kfunc(struct bpf_verifier_env *env, struct bpf_kfunc_call_arg_meta *meta, 13593 struct bpf_reg_state *regs, struct bpf_insn_aux_data *insn_aux, 13594 const struct btf_type *ptr_type, struct btf *desc_btf) 13595 { 13596 const struct btf_type *ret_t; 13597 int err = 0; 13598 13599 if (meta->btf != btf_vmlinux) 13600 return 0; 13601 13602 if (meta->func_id == special_kfunc_list[KF_bpf_obj_new_impl] || 13603 meta->func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl]) { 13604 struct btf_struct_meta *struct_meta; 13605 struct btf *ret_btf; 13606 u32 ret_btf_id; 13607 13608 if (meta->func_id == special_kfunc_list[KF_bpf_obj_new_impl] && !bpf_global_ma_set) 13609 return -ENOMEM; 13610 13611 if (((u64)(u32)meta->arg_constant.value) != meta->arg_constant.value) { 13612 verbose(env, "local type ID argument must be in range [0, U32_MAX]\n"); 13613 return -EINVAL; 13614 } 13615 13616 ret_btf = env->prog->aux->btf; 13617 ret_btf_id = meta->arg_constant.value; 13618 13619 /* This may be NULL due to user not supplying a BTF */ 13620 if (!ret_btf) { 13621 verbose(env, "bpf_obj_new/bpf_percpu_obj_new requires prog BTF\n"); 13622 return -EINVAL; 13623 } 13624 13625 ret_t = btf_type_by_id(ret_btf, ret_btf_id); 13626 if (!ret_t || !__btf_type_is_struct(ret_t)) { 13627 verbose(env, "bpf_obj_new/bpf_percpu_obj_new type ID argument must be of a struct\n"); 13628 return -EINVAL; 13629 } 13630 13631 if (meta->func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl]) { 13632 if (ret_t->size > BPF_GLOBAL_PERCPU_MA_MAX_SIZE) { 13633 verbose(env, "bpf_percpu_obj_new type size (%d) is greater than %d\n", 13634 ret_t->size, BPF_GLOBAL_PERCPU_MA_MAX_SIZE); 13635 return -EINVAL; 13636 } 13637 13638 if (!bpf_global_percpu_ma_set) { 13639 mutex_lock(&bpf_percpu_ma_lock); 13640 if (!bpf_global_percpu_ma_set) { 13641 /* Charge memory allocated with bpf_global_percpu_ma to 13642 * root memcg. The obj_cgroup for root memcg is NULL. 13643 */ 13644 err = bpf_mem_alloc_percpu_init(&bpf_global_percpu_ma, NULL); 13645 if (!err) 13646 bpf_global_percpu_ma_set = true; 13647 } 13648 mutex_unlock(&bpf_percpu_ma_lock); 13649 if (err) 13650 return err; 13651 } 13652 13653 mutex_lock(&bpf_percpu_ma_lock); 13654 err = bpf_mem_alloc_percpu_unit_init(&bpf_global_percpu_ma, ret_t->size); 13655 mutex_unlock(&bpf_percpu_ma_lock); 13656 if (err) 13657 return err; 13658 } 13659 13660 struct_meta = btf_find_struct_meta(ret_btf, ret_btf_id); 13661 if (meta->func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl]) { 13662 if (!__btf_type_is_scalar_struct(env, ret_btf, ret_t, 0)) { 13663 verbose(env, "bpf_percpu_obj_new type ID argument must be of a struct of scalars\n"); 13664 return -EINVAL; 13665 } 13666 13667 if (struct_meta) { 13668 verbose(env, "bpf_percpu_obj_new type ID argument must not contain special fields\n"); 13669 return -EINVAL; 13670 } 13671 } 13672 13673 mark_reg_known_zero(env, regs, BPF_REG_0); 13674 regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC; 13675 regs[BPF_REG_0].btf = ret_btf; 13676 regs[BPF_REG_0].btf_id = ret_btf_id; 13677 if (meta->func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl]) 13678 regs[BPF_REG_0].type |= MEM_PERCPU; 13679 13680 insn_aux->obj_new_size = ret_t->size; 13681 insn_aux->kptr_struct_meta = struct_meta; 13682 } else if (meta->func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl]) { 13683 mark_reg_known_zero(env, regs, BPF_REG_0); 13684 regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC; 13685 regs[BPF_REG_0].btf = meta->arg_btf; 13686 regs[BPF_REG_0].btf_id = meta->arg_btf_id; 13687 13688 insn_aux->kptr_struct_meta = 13689 btf_find_struct_meta(meta->arg_btf, 13690 meta->arg_btf_id); 13691 } else if (is_list_node_type(ptr_type)) { 13692 struct btf_field *field = meta->arg_list_head.field; 13693 13694 mark_reg_graph_node(regs, BPF_REG_0, &field->graph_root); 13695 } else if (is_rbtree_node_type(ptr_type)) { 13696 struct btf_field *field = meta->arg_rbtree_root.field; 13697 13698 mark_reg_graph_node(regs, BPF_REG_0, &field->graph_root); 13699 } else if (meta->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx]) { 13700 mark_reg_known_zero(env, regs, BPF_REG_0); 13701 regs[BPF_REG_0].type = PTR_TO_BTF_ID | PTR_TRUSTED; 13702 regs[BPF_REG_0].btf = desc_btf; 13703 regs[BPF_REG_0].btf_id = meta->ret_btf_id; 13704 } else if (meta->func_id == special_kfunc_list[KF_bpf_rdonly_cast]) { 13705 ret_t = btf_type_by_id(desc_btf, meta->arg_constant.value); 13706 if (!ret_t) { 13707 verbose(env, "Unknown type ID %lld passed to kfunc bpf_rdonly_cast\n", 13708 meta->arg_constant.value); 13709 return -EINVAL; 13710 } else if (btf_type_is_struct(ret_t)) { 13711 mark_reg_known_zero(env, regs, BPF_REG_0); 13712 regs[BPF_REG_0].type = PTR_TO_BTF_ID | PTR_UNTRUSTED; 13713 regs[BPF_REG_0].btf = desc_btf; 13714 regs[BPF_REG_0].btf_id = meta->arg_constant.value; 13715 } else if (btf_type_is_void(ret_t)) { 13716 mark_reg_known_zero(env, regs, BPF_REG_0); 13717 regs[BPF_REG_0].type = PTR_TO_MEM | MEM_RDONLY | PTR_UNTRUSTED; 13718 regs[BPF_REG_0].mem_size = 0; 13719 } else { 13720 verbose(env, 13721 "kfunc bpf_rdonly_cast type ID argument must be of a struct or void\n"); 13722 return -EINVAL; 13723 } 13724 } else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_slice] || 13725 meta->func_id == special_kfunc_list[KF_bpf_dynptr_slice_rdwr]) { 13726 enum bpf_type_flag type_flag = get_dynptr_type_flag(meta->initialized_dynptr.type); 13727 13728 mark_reg_known_zero(env, regs, BPF_REG_0); 13729 13730 if (!meta->arg_constant.found) { 13731 verifier_bug(env, "bpf_dynptr_slice(_rdwr) no constant size"); 13732 return -EFAULT; 13733 } 13734 13735 regs[BPF_REG_0].mem_size = meta->arg_constant.value; 13736 13737 /* PTR_MAYBE_NULL will be added when is_kfunc_ret_null is checked */ 13738 regs[BPF_REG_0].type = PTR_TO_MEM | type_flag; 13739 13740 if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_slice]) { 13741 regs[BPF_REG_0].type |= MEM_RDONLY; 13742 } else { 13743 /* this will set env->seen_direct_write to true */ 13744 if (!may_access_direct_pkt_data(env, NULL, BPF_WRITE)) { 13745 verbose(env, "the prog does not allow writes to packet data\n"); 13746 return -EINVAL; 13747 } 13748 } 13749 13750 if (!meta->initialized_dynptr.id) { 13751 verifier_bug(env, "no dynptr id"); 13752 return -EFAULT; 13753 } 13754 regs[BPF_REG_0].dynptr_id = meta->initialized_dynptr.id; 13755 13756 /* we don't need to set BPF_REG_0's ref obj id 13757 * because packet slices are not refcounted (see 13758 * dynptr_type_refcounted) 13759 */ 13760 } else { 13761 return 0; 13762 } 13763 13764 return 1; 13765 } 13766 13767 static int check_return_code(struct bpf_verifier_env *env, int regno, const char *reg_name); 13768 13769 static int check_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn, 13770 int *insn_idx_p) 13771 { 13772 bool sleepable, rcu_lock, rcu_unlock, preempt_disable, preempt_enable; 13773 u32 i, nargs, ptr_type_id, release_ref_obj_id; 13774 struct bpf_reg_state *regs = cur_regs(env); 13775 const char *func_name, *ptr_type_name; 13776 const struct btf_type *t, *ptr_type; 13777 struct bpf_kfunc_call_arg_meta meta; 13778 struct bpf_insn_aux_data *insn_aux; 13779 int err, insn_idx = *insn_idx_p; 13780 const struct btf_param *args; 13781 struct btf *desc_btf; 13782 13783 /* skip for now, but return error when we find this in fixup_kfunc_call */ 13784 if (!insn->imm) 13785 return 0; 13786 13787 err = fetch_kfunc_meta(env, insn, &meta, &func_name); 13788 if (err == -EACCES && func_name) 13789 verbose(env, "calling kernel function %s is not allowed\n", func_name); 13790 if (err) 13791 return err; 13792 desc_btf = meta.btf; 13793 insn_aux = &env->insn_aux_data[insn_idx]; 13794 13795 insn_aux->is_iter_next = is_iter_next_kfunc(&meta); 13796 13797 if (!insn->off && 13798 (insn->imm == special_kfunc_list[KF_bpf_res_spin_lock] || 13799 insn->imm == special_kfunc_list[KF_bpf_res_spin_lock_irqsave])) { 13800 struct bpf_verifier_state *branch; 13801 struct bpf_reg_state *regs; 13802 13803 branch = push_stack(env, env->insn_idx + 1, env->insn_idx, false); 13804 if (!branch) { 13805 verbose(env, "failed to push state for failed lock acquisition\n"); 13806 return -ENOMEM; 13807 } 13808 13809 regs = branch->frame[branch->curframe]->regs; 13810 13811 /* Clear r0-r5 registers in forked state */ 13812 for (i = 0; i < CALLER_SAVED_REGS; i++) 13813 mark_reg_not_init(env, regs, caller_saved[i]); 13814 13815 mark_reg_unknown(env, regs, BPF_REG_0); 13816 err = __mark_reg_s32_range(env, regs, BPF_REG_0, -MAX_ERRNO, -1); 13817 if (err) { 13818 verbose(env, "failed to mark s32 range for retval in forked state for lock\n"); 13819 return err; 13820 } 13821 __mark_btf_func_reg_size(env, regs, BPF_REG_0, sizeof(u32)); 13822 } else if (!insn->off && insn->imm == special_kfunc_list[KF___bpf_trap]) { 13823 verbose(env, "unexpected __bpf_trap() due to uninitialized variable?\n"); 13824 return -EFAULT; 13825 } 13826 13827 if (is_kfunc_destructive(&meta) && !capable(CAP_SYS_BOOT)) { 13828 verbose(env, "destructive kfunc calls require CAP_SYS_BOOT capability\n"); 13829 return -EACCES; 13830 } 13831 13832 sleepable = is_kfunc_sleepable(&meta); 13833 if (sleepable && !in_sleepable(env)) { 13834 verbose(env, "program must be sleepable to call sleepable kfunc %s\n", func_name); 13835 return -EACCES; 13836 } 13837 13838 /* Check the arguments */ 13839 err = check_kfunc_args(env, &meta, insn_idx); 13840 if (err < 0) 13841 return err; 13842 13843 if (meta.func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) { 13844 err = push_callback_call(env, insn, insn_idx, meta.subprogno, 13845 set_rbtree_add_callback_state); 13846 if (err) { 13847 verbose(env, "kfunc %s#%d failed callback verification\n", 13848 func_name, meta.func_id); 13849 return err; 13850 } 13851 } 13852 13853 if (meta.func_id == special_kfunc_list[KF_bpf_session_cookie]) { 13854 meta.r0_size = sizeof(u64); 13855 meta.r0_rdonly = false; 13856 } 13857 13858 if (is_bpf_wq_set_callback_impl_kfunc(meta.func_id)) { 13859 err = push_callback_call(env, insn, insn_idx, meta.subprogno, 13860 set_timer_callback_state); 13861 if (err) { 13862 verbose(env, "kfunc %s#%d failed callback verification\n", 13863 func_name, meta.func_id); 13864 return err; 13865 } 13866 } 13867 13868 rcu_lock = is_kfunc_bpf_rcu_read_lock(&meta); 13869 rcu_unlock = is_kfunc_bpf_rcu_read_unlock(&meta); 13870 13871 preempt_disable = is_kfunc_bpf_preempt_disable(&meta); 13872 preempt_enable = is_kfunc_bpf_preempt_enable(&meta); 13873 13874 if (env->cur_state->active_rcu_lock) { 13875 struct bpf_func_state *state; 13876 struct bpf_reg_state *reg; 13877 u32 clear_mask = (1 << STACK_SPILL) | (1 << STACK_ITER); 13878 13879 if (in_rbtree_lock_required_cb(env) && (rcu_lock || rcu_unlock)) { 13880 verbose(env, "Calling bpf_rcu_read_{lock,unlock} in unnecessary rbtree callback\n"); 13881 return -EACCES; 13882 } 13883 13884 if (rcu_lock) { 13885 verbose(env, "nested rcu read lock (kernel function %s)\n", func_name); 13886 return -EINVAL; 13887 } else if (rcu_unlock) { 13888 bpf_for_each_reg_in_vstate_mask(env->cur_state, state, reg, clear_mask, ({ 13889 if (reg->type & MEM_RCU) { 13890 reg->type &= ~(MEM_RCU | PTR_MAYBE_NULL); 13891 reg->type |= PTR_UNTRUSTED; 13892 } 13893 })); 13894 env->cur_state->active_rcu_lock = false; 13895 } else if (sleepable) { 13896 verbose(env, "kernel func %s is sleepable within rcu_read_lock region\n", func_name); 13897 return -EACCES; 13898 } 13899 } else if (rcu_lock) { 13900 env->cur_state->active_rcu_lock = true; 13901 } else if (rcu_unlock) { 13902 verbose(env, "unmatched rcu read unlock (kernel function %s)\n", func_name); 13903 return -EINVAL; 13904 } 13905 13906 if (env->cur_state->active_preempt_locks) { 13907 if (preempt_disable) { 13908 env->cur_state->active_preempt_locks++; 13909 } else if (preempt_enable) { 13910 env->cur_state->active_preempt_locks--; 13911 } else if (sleepable) { 13912 verbose(env, "kernel func %s is sleepable within non-preemptible region\n", func_name); 13913 return -EACCES; 13914 } 13915 } else if (preempt_disable) { 13916 env->cur_state->active_preempt_locks++; 13917 } else if (preempt_enable) { 13918 verbose(env, "unmatched attempt to enable preemption (kernel function %s)\n", func_name); 13919 return -EINVAL; 13920 } 13921 13922 if (env->cur_state->active_irq_id && sleepable) { 13923 verbose(env, "kernel func %s is sleepable within IRQ-disabled region\n", func_name); 13924 return -EACCES; 13925 } 13926 13927 /* In case of release function, we get register number of refcounted 13928 * PTR_TO_BTF_ID in bpf_kfunc_arg_meta, do the release now. 13929 */ 13930 if (meta.release_regno) { 13931 err = release_reference(env, regs[meta.release_regno].ref_obj_id); 13932 if (err) { 13933 verbose(env, "kfunc %s#%d reference has not been acquired before\n", 13934 func_name, meta.func_id); 13935 return err; 13936 } 13937 } 13938 13939 if (meta.func_id == special_kfunc_list[KF_bpf_list_push_front_impl] || 13940 meta.func_id == special_kfunc_list[KF_bpf_list_push_back_impl] || 13941 meta.func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) { 13942 release_ref_obj_id = regs[BPF_REG_2].ref_obj_id; 13943 insn_aux->insert_off = regs[BPF_REG_2].off; 13944 insn_aux->kptr_struct_meta = btf_find_struct_meta(meta.arg_btf, meta.arg_btf_id); 13945 err = ref_convert_owning_non_owning(env, release_ref_obj_id); 13946 if (err) { 13947 verbose(env, "kfunc %s#%d conversion of owning ref to non-owning failed\n", 13948 func_name, meta.func_id); 13949 return err; 13950 } 13951 13952 err = release_reference(env, release_ref_obj_id); 13953 if (err) { 13954 verbose(env, "kfunc %s#%d reference has not been acquired before\n", 13955 func_name, meta.func_id); 13956 return err; 13957 } 13958 } 13959 13960 if (meta.func_id == special_kfunc_list[KF_bpf_throw]) { 13961 if (!bpf_jit_supports_exceptions()) { 13962 verbose(env, "JIT does not support calling kfunc %s#%d\n", 13963 func_name, meta.func_id); 13964 return -ENOTSUPP; 13965 } 13966 env->seen_exception = true; 13967 13968 /* In the case of the default callback, the cookie value passed 13969 * to bpf_throw becomes the return value of the program. 13970 */ 13971 if (!env->exception_callback_subprog) { 13972 err = check_return_code(env, BPF_REG_1, "R1"); 13973 if (err < 0) 13974 return err; 13975 } 13976 } 13977 13978 for (i = 0; i < CALLER_SAVED_REGS; i++) 13979 mark_reg_not_init(env, regs, caller_saved[i]); 13980 13981 /* Check return type */ 13982 t = btf_type_skip_modifiers(desc_btf, meta.func_proto->type, NULL); 13983 13984 if (is_kfunc_acquire(&meta) && !btf_type_is_struct_ptr(meta.btf, t)) { 13985 /* Only exception is bpf_obj_new_impl */ 13986 if (meta.btf != btf_vmlinux || 13987 (meta.func_id != special_kfunc_list[KF_bpf_obj_new_impl] && 13988 meta.func_id != special_kfunc_list[KF_bpf_percpu_obj_new_impl] && 13989 meta.func_id != special_kfunc_list[KF_bpf_refcount_acquire_impl])) { 13990 verbose(env, "acquire kernel function does not return PTR_TO_BTF_ID\n"); 13991 return -EINVAL; 13992 } 13993 } 13994 13995 if (btf_type_is_scalar(t)) { 13996 mark_reg_unknown(env, regs, BPF_REG_0); 13997 if (meta.btf == btf_vmlinux && (meta.func_id == special_kfunc_list[KF_bpf_res_spin_lock] || 13998 meta.func_id == special_kfunc_list[KF_bpf_res_spin_lock_irqsave])) 13999 __mark_reg_const_zero(env, ®s[BPF_REG_0]); 14000 mark_btf_func_reg_size(env, BPF_REG_0, t->size); 14001 } else if (btf_type_is_ptr(t)) { 14002 ptr_type = btf_type_skip_modifiers(desc_btf, t->type, &ptr_type_id); 14003 err = check_special_kfunc(env, &meta, regs, insn_aux, ptr_type, desc_btf); 14004 if (err) { 14005 if (err < 0) 14006 return err; 14007 } else if (btf_type_is_void(ptr_type)) { 14008 /* kfunc returning 'void *' is equivalent to returning scalar */ 14009 mark_reg_unknown(env, regs, BPF_REG_0); 14010 } else if (!__btf_type_is_struct(ptr_type)) { 14011 if (!meta.r0_size) { 14012 __u32 sz; 14013 14014 if (!IS_ERR(btf_resolve_size(desc_btf, ptr_type, &sz))) { 14015 meta.r0_size = sz; 14016 meta.r0_rdonly = true; 14017 } 14018 } 14019 if (!meta.r0_size) { 14020 ptr_type_name = btf_name_by_offset(desc_btf, 14021 ptr_type->name_off); 14022 verbose(env, 14023 "kernel function %s returns pointer type %s %s is not supported\n", 14024 func_name, 14025 btf_type_str(ptr_type), 14026 ptr_type_name); 14027 return -EINVAL; 14028 } 14029 14030 mark_reg_known_zero(env, regs, BPF_REG_0); 14031 regs[BPF_REG_0].type = PTR_TO_MEM; 14032 regs[BPF_REG_0].mem_size = meta.r0_size; 14033 14034 if (meta.r0_rdonly) 14035 regs[BPF_REG_0].type |= MEM_RDONLY; 14036 14037 /* Ensures we don't access the memory after a release_reference() */ 14038 if (meta.ref_obj_id) 14039 regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id; 14040 } else { 14041 mark_reg_known_zero(env, regs, BPF_REG_0); 14042 regs[BPF_REG_0].btf = desc_btf; 14043 regs[BPF_REG_0].type = PTR_TO_BTF_ID; 14044 regs[BPF_REG_0].btf_id = ptr_type_id; 14045 14046 if (meta.func_id == special_kfunc_list[KF_bpf_get_kmem_cache]) 14047 regs[BPF_REG_0].type |= PTR_UNTRUSTED; 14048 14049 if (is_iter_next_kfunc(&meta)) { 14050 struct bpf_reg_state *cur_iter; 14051 14052 cur_iter = get_iter_from_state(env->cur_state, &meta); 14053 14054 if (cur_iter->type & MEM_RCU) /* KF_RCU_PROTECTED */ 14055 regs[BPF_REG_0].type |= MEM_RCU; 14056 else 14057 regs[BPF_REG_0].type |= PTR_TRUSTED; 14058 } 14059 } 14060 14061 if (is_kfunc_ret_null(&meta)) { 14062 regs[BPF_REG_0].type |= PTR_MAYBE_NULL; 14063 /* For mark_ptr_or_null_reg, see 93c230e3f5bd6 */ 14064 regs[BPF_REG_0].id = ++env->id_gen; 14065 } 14066 mark_btf_func_reg_size(env, BPF_REG_0, sizeof(void *)); 14067 if (is_kfunc_acquire(&meta)) { 14068 int id = acquire_reference(env, insn_idx); 14069 14070 if (id < 0) 14071 return id; 14072 if (is_kfunc_ret_null(&meta)) 14073 regs[BPF_REG_0].id = id; 14074 regs[BPF_REG_0].ref_obj_id = id; 14075 } else if (is_rbtree_node_type(ptr_type) || is_list_node_type(ptr_type)) { 14076 ref_set_non_owning(env, ®s[BPF_REG_0]); 14077 } 14078 14079 if (reg_may_point_to_spin_lock(®s[BPF_REG_0]) && !regs[BPF_REG_0].id) 14080 regs[BPF_REG_0].id = ++env->id_gen; 14081 } else if (btf_type_is_void(t)) { 14082 if (meta.btf == btf_vmlinux) { 14083 if (meta.func_id == special_kfunc_list[KF_bpf_obj_drop_impl] || 14084 meta.func_id == special_kfunc_list[KF_bpf_percpu_obj_drop_impl]) { 14085 insn_aux->kptr_struct_meta = 14086 btf_find_struct_meta(meta.arg_btf, 14087 meta.arg_btf_id); 14088 } 14089 } 14090 } 14091 14092 if (is_kfunc_pkt_changing(&meta)) 14093 clear_all_pkt_pointers(env); 14094 14095 nargs = btf_type_vlen(meta.func_proto); 14096 args = (const struct btf_param *)(meta.func_proto + 1); 14097 for (i = 0; i < nargs; i++) { 14098 u32 regno = i + 1; 14099 14100 t = btf_type_skip_modifiers(desc_btf, args[i].type, NULL); 14101 if (btf_type_is_ptr(t)) 14102 mark_btf_func_reg_size(env, regno, sizeof(void *)); 14103 else 14104 /* scalar. ensured by btf_check_kfunc_arg_match() */ 14105 mark_btf_func_reg_size(env, regno, t->size); 14106 } 14107 14108 if (is_iter_next_kfunc(&meta)) { 14109 err = process_iter_next_call(env, insn_idx, &meta); 14110 if (err) 14111 return err; 14112 } 14113 14114 return 0; 14115 } 14116 14117 static bool check_reg_sane_offset(struct bpf_verifier_env *env, 14118 const struct bpf_reg_state *reg, 14119 enum bpf_reg_type type) 14120 { 14121 bool known = tnum_is_const(reg->var_off); 14122 s64 val = reg->var_off.value; 14123 s64 smin = reg->smin_value; 14124 14125 if (known && (val >= BPF_MAX_VAR_OFF || val <= -BPF_MAX_VAR_OFF)) { 14126 verbose(env, "math between %s pointer and %lld is not allowed\n", 14127 reg_type_str(env, type), val); 14128 return false; 14129 } 14130 14131 if (reg->off >= BPF_MAX_VAR_OFF || reg->off <= -BPF_MAX_VAR_OFF) { 14132 verbose(env, "%s pointer offset %d is not allowed\n", 14133 reg_type_str(env, type), reg->off); 14134 return false; 14135 } 14136 14137 if (smin == S64_MIN) { 14138 verbose(env, "math between %s pointer and register with unbounded min value is not allowed\n", 14139 reg_type_str(env, type)); 14140 return false; 14141 } 14142 14143 if (smin >= BPF_MAX_VAR_OFF || smin <= -BPF_MAX_VAR_OFF) { 14144 verbose(env, "value %lld makes %s pointer be out of bounds\n", 14145 smin, reg_type_str(env, type)); 14146 return false; 14147 } 14148 14149 return true; 14150 } 14151 14152 enum { 14153 REASON_BOUNDS = -1, 14154 REASON_TYPE = -2, 14155 REASON_PATHS = -3, 14156 REASON_LIMIT = -4, 14157 REASON_STACK = -5, 14158 }; 14159 14160 static int retrieve_ptr_limit(const struct bpf_reg_state *ptr_reg, 14161 u32 *alu_limit, bool mask_to_left) 14162 { 14163 u32 max = 0, ptr_limit = 0; 14164 14165 switch (ptr_reg->type) { 14166 case PTR_TO_STACK: 14167 /* Offset 0 is out-of-bounds, but acceptable start for the 14168 * left direction, see BPF_REG_FP. Also, unknown scalar 14169 * offset where we would need to deal with min/max bounds is 14170 * currently prohibited for unprivileged. 14171 */ 14172 max = MAX_BPF_STACK + mask_to_left; 14173 ptr_limit = -(ptr_reg->var_off.value + ptr_reg->off); 14174 break; 14175 case PTR_TO_MAP_VALUE: 14176 max = ptr_reg->map_ptr->value_size; 14177 ptr_limit = (mask_to_left ? 14178 ptr_reg->smin_value : 14179 ptr_reg->umax_value) + ptr_reg->off; 14180 break; 14181 default: 14182 return REASON_TYPE; 14183 } 14184 14185 if (ptr_limit >= max) 14186 return REASON_LIMIT; 14187 *alu_limit = ptr_limit; 14188 return 0; 14189 } 14190 14191 static bool can_skip_alu_sanitation(const struct bpf_verifier_env *env, 14192 const struct bpf_insn *insn) 14193 { 14194 return env->bypass_spec_v1 || 14195 BPF_SRC(insn->code) == BPF_K || 14196 cur_aux(env)->nospec; 14197 } 14198 14199 static int update_alu_sanitation_state(struct bpf_insn_aux_data *aux, 14200 u32 alu_state, u32 alu_limit) 14201 { 14202 /* If we arrived here from different branches with different 14203 * state or limits to sanitize, then this won't work. 14204 */ 14205 if (aux->alu_state && 14206 (aux->alu_state != alu_state || 14207 aux->alu_limit != alu_limit)) 14208 return REASON_PATHS; 14209 14210 /* Corresponding fixup done in do_misc_fixups(). */ 14211 aux->alu_state = alu_state; 14212 aux->alu_limit = alu_limit; 14213 return 0; 14214 } 14215 14216 static int sanitize_val_alu(struct bpf_verifier_env *env, 14217 struct bpf_insn *insn) 14218 { 14219 struct bpf_insn_aux_data *aux = cur_aux(env); 14220 14221 if (can_skip_alu_sanitation(env, insn)) 14222 return 0; 14223 14224 return update_alu_sanitation_state(aux, BPF_ALU_NON_POINTER, 0); 14225 } 14226 14227 static bool sanitize_needed(u8 opcode) 14228 { 14229 return opcode == BPF_ADD || opcode == BPF_SUB; 14230 } 14231 14232 struct bpf_sanitize_info { 14233 struct bpf_insn_aux_data aux; 14234 bool mask_to_left; 14235 }; 14236 14237 static struct bpf_verifier_state * 14238 sanitize_speculative_path(struct bpf_verifier_env *env, 14239 const struct bpf_insn *insn, 14240 u32 next_idx, u32 curr_idx) 14241 { 14242 struct bpf_verifier_state *branch; 14243 struct bpf_reg_state *regs; 14244 14245 branch = push_stack(env, next_idx, curr_idx, true); 14246 if (branch && insn) { 14247 regs = branch->frame[branch->curframe]->regs; 14248 if (BPF_SRC(insn->code) == BPF_K) { 14249 mark_reg_unknown(env, regs, insn->dst_reg); 14250 } else if (BPF_SRC(insn->code) == BPF_X) { 14251 mark_reg_unknown(env, regs, insn->dst_reg); 14252 mark_reg_unknown(env, regs, insn->src_reg); 14253 } 14254 } 14255 return branch; 14256 } 14257 14258 static int sanitize_ptr_alu(struct bpf_verifier_env *env, 14259 struct bpf_insn *insn, 14260 const struct bpf_reg_state *ptr_reg, 14261 const struct bpf_reg_state *off_reg, 14262 struct bpf_reg_state *dst_reg, 14263 struct bpf_sanitize_info *info, 14264 const bool commit_window) 14265 { 14266 struct bpf_insn_aux_data *aux = commit_window ? cur_aux(env) : &info->aux; 14267 struct bpf_verifier_state *vstate = env->cur_state; 14268 bool off_is_imm = tnum_is_const(off_reg->var_off); 14269 bool off_is_neg = off_reg->smin_value < 0; 14270 bool ptr_is_dst_reg = ptr_reg == dst_reg; 14271 u8 opcode = BPF_OP(insn->code); 14272 u32 alu_state, alu_limit; 14273 struct bpf_reg_state tmp; 14274 bool ret; 14275 int err; 14276 14277 if (can_skip_alu_sanitation(env, insn)) 14278 return 0; 14279 14280 /* We already marked aux for masking from non-speculative 14281 * paths, thus we got here in the first place. We only care 14282 * to explore bad access from here. 14283 */ 14284 if (vstate->speculative) 14285 goto do_sim; 14286 14287 if (!commit_window) { 14288 if (!tnum_is_const(off_reg->var_off) && 14289 (off_reg->smin_value < 0) != (off_reg->smax_value < 0)) 14290 return REASON_BOUNDS; 14291 14292 info->mask_to_left = (opcode == BPF_ADD && off_is_neg) || 14293 (opcode == BPF_SUB && !off_is_neg); 14294 } 14295 14296 err = retrieve_ptr_limit(ptr_reg, &alu_limit, info->mask_to_left); 14297 if (err < 0) 14298 return err; 14299 14300 if (commit_window) { 14301 /* In commit phase we narrow the masking window based on 14302 * the observed pointer move after the simulated operation. 14303 */ 14304 alu_state = info->aux.alu_state; 14305 alu_limit = abs(info->aux.alu_limit - alu_limit); 14306 } else { 14307 alu_state = off_is_neg ? BPF_ALU_NEG_VALUE : 0; 14308 alu_state |= off_is_imm ? BPF_ALU_IMMEDIATE : 0; 14309 alu_state |= ptr_is_dst_reg ? 14310 BPF_ALU_SANITIZE_SRC : BPF_ALU_SANITIZE_DST; 14311 14312 /* Limit pruning on unknown scalars to enable deep search for 14313 * potential masking differences from other program paths. 14314 */ 14315 if (!off_is_imm) 14316 env->explore_alu_limits = true; 14317 } 14318 14319 err = update_alu_sanitation_state(aux, alu_state, alu_limit); 14320 if (err < 0) 14321 return err; 14322 do_sim: 14323 /* If we're in commit phase, we're done here given we already 14324 * pushed the truncated dst_reg into the speculative verification 14325 * stack. 14326 * 14327 * Also, when register is a known constant, we rewrite register-based 14328 * operation to immediate-based, and thus do not need masking (and as 14329 * a consequence, do not need to simulate the zero-truncation either). 14330 */ 14331 if (commit_window || off_is_imm) 14332 return 0; 14333 14334 /* Simulate and find potential out-of-bounds access under 14335 * speculative execution from truncation as a result of 14336 * masking when off was not within expected range. If off 14337 * sits in dst, then we temporarily need to move ptr there 14338 * to simulate dst (== 0) +/-= ptr. Needed, for example, 14339 * for cases where we use K-based arithmetic in one direction 14340 * and truncated reg-based in the other in order to explore 14341 * bad access. 14342 */ 14343 if (!ptr_is_dst_reg) { 14344 tmp = *dst_reg; 14345 copy_register_state(dst_reg, ptr_reg); 14346 } 14347 ret = sanitize_speculative_path(env, NULL, env->insn_idx + 1, 14348 env->insn_idx); 14349 if (!ptr_is_dst_reg && ret) 14350 *dst_reg = tmp; 14351 return !ret ? REASON_STACK : 0; 14352 } 14353 14354 static void sanitize_mark_insn_seen(struct bpf_verifier_env *env) 14355 { 14356 struct bpf_verifier_state *vstate = env->cur_state; 14357 14358 /* If we simulate paths under speculation, we don't update the 14359 * insn as 'seen' such that when we verify unreachable paths in 14360 * the non-speculative domain, sanitize_dead_code() can still 14361 * rewrite/sanitize them. 14362 */ 14363 if (!vstate->speculative) 14364 env->insn_aux_data[env->insn_idx].seen = env->pass_cnt; 14365 } 14366 14367 static int sanitize_err(struct bpf_verifier_env *env, 14368 const struct bpf_insn *insn, int reason, 14369 const struct bpf_reg_state *off_reg, 14370 const struct bpf_reg_state *dst_reg) 14371 { 14372 static const char *err = "pointer arithmetic with it prohibited for !root"; 14373 const char *op = BPF_OP(insn->code) == BPF_ADD ? "add" : "sub"; 14374 u32 dst = insn->dst_reg, src = insn->src_reg; 14375 14376 switch (reason) { 14377 case REASON_BOUNDS: 14378 verbose(env, "R%d has unknown scalar with mixed signed bounds, %s\n", 14379 off_reg == dst_reg ? dst : src, err); 14380 break; 14381 case REASON_TYPE: 14382 verbose(env, "R%d has pointer with unsupported alu operation, %s\n", 14383 off_reg == dst_reg ? src : dst, err); 14384 break; 14385 case REASON_PATHS: 14386 verbose(env, "R%d tried to %s from different maps, paths or scalars, %s\n", 14387 dst, op, err); 14388 break; 14389 case REASON_LIMIT: 14390 verbose(env, "R%d tried to %s beyond pointer bounds, %s\n", 14391 dst, op, err); 14392 break; 14393 case REASON_STACK: 14394 verbose(env, "R%d could not be pushed for speculative verification, %s\n", 14395 dst, err); 14396 return -ENOMEM; 14397 default: 14398 verifier_bug(env, "unknown reason (%d)", reason); 14399 break; 14400 } 14401 14402 return -EACCES; 14403 } 14404 14405 /* check that stack access falls within stack limits and that 'reg' doesn't 14406 * have a variable offset. 14407 * 14408 * Variable offset is prohibited for unprivileged mode for simplicity since it 14409 * requires corresponding support in Spectre masking for stack ALU. See also 14410 * retrieve_ptr_limit(). 14411 * 14412 * 14413 * 'off' includes 'reg->off'. 14414 */ 14415 static int check_stack_access_for_ptr_arithmetic( 14416 struct bpf_verifier_env *env, 14417 int regno, 14418 const struct bpf_reg_state *reg, 14419 int off) 14420 { 14421 if (!tnum_is_const(reg->var_off)) { 14422 char tn_buf[48]; 14423 14424 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 14425 verbose(env, "R%d variable stack access prohibited for !root, var_off=%s off=%d\n", 14426 regno, tn_buf, off); 14427 return -EACCES; 14428 } 14429 14430 if (off >= 0 || off < -MAX_BPF_STACK) { 14431 verbose(env, "R%d stack pointer arithmetic goes out of range, " 14432 "prohibited for !root; off=%d\n", regno, off); 14433 return -EACCES; 14434 } 14435 14436 return 0; 14437 } 14438 14439 static int sanitize_check_bounds(struct bpf_verifier_env *env, 14440 const struct bpf_insn *insn, 14441 const struct bpf_reg_state *dst_reg) 14442 { 14443 u32 dst = insn->dst_reg; 14444 14445 /* For unprivileged we require that resulting offset must be in bounds 14446 * in order to be able to sanitize access later on. 14447 */ 14448 if (env->bypass_spec_v1) 14449 return 0; 14450 14451 switch (dst_reg->type) { 14452 case PTR_TO_STACK: 14453 if (check_stack_access_for_ptr_arithmetic(env, dst, dst_reg, 14454 dst_reg->off + dst_reg->var_off.value)) 14455 return -EACCES; 14456 break; 14457 case PTR_TO_MAP_VALUE: 14458 if (check_map_access(env, dst, dst_reg->off, 1, false, ACCESS_HELPER)) { 14459 verbose(env, "R%d pointer arithmetic of map value goes out of range, " 14460 "prohibited for !root\n", dst); 14461 return -EACCES; 14462 } 14463 break; 14464 default: 14465 return -EOPNOTSUPP; 14466 } 14467 14468 return 0; 14469 } 14470 14471 /* Handles arithmetic on a pointer and a scalar: computes new min/max and var_off. 14472 * Caller should also handle BPF_MOV case separately. 14473 * If we return -EACCES, caller may want to try again treating pointer as a 14474 * scalar. So we only emit a diagnostic if !env->allow_ptr_leaks. 14475 */ 14476 static int adjust_ptr_min_max_vals(struct bpf_verifier_env *env, 14477 struct bpf_insn *insn, 14478 const struct bpf_reg_state *ptr_reg, 14479 const struct bpf_reg_state *off_reg) 14480 { 14481 struct bpf_verifier_state *vstate = env->cur_state; 14482 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 14483 struct bpf_reg_state *regs = state->regs, *dst_reg; 14484 bool known = tnum_is_const(off_reg->var_off); 14485 s64 smin_val = off_reg->smin_value, smax_val = off_reg->smax_value, 14486 smin_ptr = ptr_reg->smin_value, smax_ptr = ptr_reg->smax_value; 14487 u64 umin_val = off_reg->umin_value, umax_val = off_reg->umax_value, 14488 umin_ptr = ptr_reg->umin_value, umax_ptr = ptr_reg->umax_value; 14489 struct bpf_sanitize_info info = {}; 14490 u8 opcode = BPF_OP(insn->code); 14491 u32 dst = insn->dst_reg; 14492 int ret, bounds_ret; 14493 14494 dst_reg = ®s[dst]; 14495 14496 if ((known && (smin_val != smax_val || umin_val != umax_val)) || 14497 smin_val > smax_val || umin_val > umax_val) { 14498 /* Taint dst register if offset had invalid bounds derived from 14499 * e.g. dead branches. 14500 */ 14501 __mark_reg_unknown(env, dst_reg); 14502 return 0; 14503 } 14504 14505 if (BPF_CLASS(insn->code) != BPF_ALU64) { 14506 /* 32-bit ALU ops on pointers produce (meaningless) scalars */ 14507 if (opcode == BPF_SUB && env->allow_ptr_leaks) { 14508 __mark_reg_unknown(env, dst_reg); 14509 return 0; 14510 } 14511 14512 verbose(env, 14513 "R%d 32-bit pointer arithmetic prohibited\n", 14514 dst); 14515 return -EACCES; 14516 } 14517 14518 if (ptr_reg->type & PTR_MAYBE_NULL) { 14519 verbose(env, "R%d pointer arithmetic on %s prohibited, null-check it first\n", 14520 dst, reg_type_str(env, ptr_reg->type)); 14521 return -EACCES; 14522 } 14523 14524 /* 14525 * Accesses to untrusted PTR_TO_MEM are done through probe 14526 * instructions, hence no need to track offsets. 14527 */ 14528 if (base_type(ptr_reg->type) == PTR_TO_MEM && (ptr_reg->type & PTR_UNTRUSTED)) 14529 return 0; 14530 14531 switch (base_type(ptr_reg->type)) { 14532 case PTR_TO_CTX: 14533 case PTR_TO_MAP_VALUE: 14534 case PTR_TO_MAP_KEY: 14535 case PTR_TO_STACK: 14536 case PTR_TO_PACKET_META: 14537 case PTR_TO_PACKET: 14538 case PTR_TO_TP_BUFFER: 14539 case PTR_TO_BTF_ID: 14540 case PTR_TO_MEM: 14541 case PTR_TO_BUF: 14542 case PTR_TO_FUNC: 14543 case CONST_PTR_TO_DYNPTR: 14544 break; 14545 case PTR_TO_FLOW_KEYS: 14546 if (known) 14547 break; 14548 fallthrough; 14549 case CONST_PTR_TO_MAP: 14550 /* smin_val represents the known value */ 14551 if (known && smin_val == 0 && opcode == BPF_ADD) 14552 break; 14553 fallthrough; 14554 default: 14555 verbose(env, "R%d pointer arithmetic on %s prohibited\n", 14556 dst, reg_type_str(env, ptr_reg->type)); 14557 return -EACCES; 14558 } 14559 14560 /* In case of 'scalar += pointer', dst_reg inherits pointer type and id. 14561 * The id may be overwritten later if we create a new variable offset. 14562 */ 14563 dst_reg->type = ptr_reg->type; 14564 dst_reg->id = ptr_reg->id; 14565 14566 if (!check_reg_sane_offset(env, off_reg, ptr_reg->type) || 14567 !check_reg_sane_offset(env, ptr_reg, ptr_reg->type)) 14568 return -EINVAL; 14569 14570 /* pointer types do not carry 32-bit bounds at the moment. */ 14571 __mark_reg32_unbounded(dst_reg); 14572 14573 if (sanitize_needed(opcode)) { 14574 ret = sanitize_ptr_alu(env, insn, ptr_reg, off_reg, dst_reg, 14575 &info, false); 14576 if (ret < 0) 14577 return sanitize_err(env, insn, ret, off_reg, dst_reg); 14578 } 14579 14580 switch (opcode) { 14581 case BPF_ADD: 14582 /* We can take a fixed offset as long as it doesn't overflow 14583 * the s32 'off' field 14584 */ 14585 if (known && (ptr_reg->off + smin_val == 14586 (s64)(s32)(ptr_reg->off + smin_val))) { 14587 /* pointer += K. Accumulate it into fixed offset */ 14588 dst_reg->smin_value = smin_ptr; 14589 dst_reg->smax_value = smax_ptr; 14590 dst_reg->umin_value = umin_ptr; 14591 dst_reg->umax_value = umax_ptr; 14592 dst_reg->var_off = ptr_reg->var_off; 14593 dst_reg->off = ptr_reg->off + smin_val; 14594 dst_reg->raw = ptr_reg->raw; 14595 break; 14596 } 14597 /* A new variable offset is created. Note that off_reg->off 14598 * == 0, since it's a scalar. 14599 * dst_reg gets the pointer type and since some positive 14600 * integer value was added to the pointer, give it a new 'id' 14601 * if it's a PTR_TO_PACKET. 14602 * this creates a new 'base' pointer, off_reg (variable) gets 14603 * added into the variable offset, and we copy the fixed offset 14604 * from ptr_reg. 14605 */ 14606 if (check_add_overflow(smin_ptr, smin_val, &dst_reg->smin_value) || 14607 check_add_overflow(smax_ptr, smax_val, &dst_reg->smax_value)) { 14608 dst_reg->smin_value = S64_MIN; 14609 dst_reg->smax_value = S64_MAX; 14610 } 14611 if (check_add_overflow(umin_ptr, umin_val, &dst_reg->umin_value) || 14612 check_add_overflow(umax_ptr, umax_val, &dst_reg->umax_value)) { 14613 dst_reg->umin_value = 0; 14614 dst_reg->umax_value = U64_MAX; 14615 } 14616 dst_reg->var_off = tnum_add(ptr_reg->var_off, off_reg->var_off); 14617 dst_reg->off = ptr_reg->off; 14618 dst_reg->raw = ptr_reg->raw; 14619 if (reg_is_pkt_pointer(ptr_reg)) { 14620 dst_reg->id = ++env->id_gen; 14621 /* something was added to pkt_ptr, set range to zero */ 14622 memset(&dst_reg->raw, 0, sizeof(dst_reg->raw)); 14623 } 14624 break; 14625 case BPF_SUB: 14626 if (dst_reg == off_reg) { 14627 /* scalar -= pointer. Creates an unknown scalar */ 14628 verbose(env, "R%d tried to subtract pointer from scalar\n", 14629 dst); 14630 return -EACCES; 14631 } 14632 /* We don't allow subtraction from FP, because (according to 14633 * test_verifier.c test "invalid fp arithmetic", JITs might not 14634 * be able to deal with it. 14635 */ 14636 if (ptr_reg->type == PTR_TO_STACK) { 14637 verbose(env, "R%d subtraction from stack pointer prohibited\n", 14638 dst); 14639 return -EACCES; 14640 } 14641 if (known && (ptr_reg->off - smin_val == 14642 (s64)(s32)(ptr_reg->off - smin_val))) { 14643 /* pointer -= K. Subtract it from fixed offset */ 14644 dst_reg->smin_value = smin_ptr; 14645 dst_reg->smax_value = smax_ptr; 14646 dst_reg->umin_value = umin_ptr; 14647 dst_reg->umax_value = umax_ptr; 14648 dst_reg->var_off = ptr_reg->var_off; 14649 dst_reg->id = ptr_reg->id; 14650 dst_reg->off = ptr_reg->off - smin_val; 14651 dst_reg->raw = ptr_reg->raw; 14652 break; 14653 } 14654 /* A new variable offset is created. If the subtrahend is known 14655 * nonnegative, then any reg->range we had before is still good. 14656 */ 14657 if (check_sub_overflow(smin_ptr, smax_val, &dst_reg->smin_value) || 14658 check_sub_overflow(smax_ptr, smin_val, &dst_reg->smax_value)) { 14659 /* Overflow possible, we know nothing */ 14660 dst_reg->smin_value = S64_MIN; 14661 dst_reg->smax_value = S64_MAX; 14662 } 14663 if (umin_ptr < umax_val) { 14664 /* Overflow possible, we know nothing */ 14665 dst_reg->umin_value = 0; 14666 dst_reg->umax_value = U64_MAX; 14667 } else { 14668 /* Cannot overflow (as long as bounds are consistent) */ 14669 dst_reg->umin_value = umin_ptr - umax_val; 14670 dst_reg->umax_value = umax_ptr - umin_val; 14671 } 14672 dst_reg->var_off = tnum_sub(ptr_reg->var_off, off_reg->var_off); 14673 dst_reg->off = ptr_reg->off; 14674 dst_reg->raw = ptr_reg->raw; 14675 if (reg_is_pkt_pointer(ptr_reg)) { 14676 dst_reg->id = ++env->id_gen; 14677 /* something was added to pkt_ptr, set range to zero */ 14678 if (smin_val < 0) 14679 memset(&dst_reg->raw, 0, sizeof(dst_reg->raw)); 14680 } 14681 break; 14682 case BPF_AND: 14683 case BPF_OR: 14684 case BPF_XOR: 14685 /* bitwise ops on pointers are troublesome, prohibit. */ 14686 verbose(env, "R%d bitwise operator %s on pointer prohibited\n", 14687 dst, bpf_alu_string[opcode >> 4]); 14688 return -EACCES; 14689 default: 14690 /* other operators (e.g. MUL,LSH) produce non-pointer results */ 14691 verbose(env, "R%d pointer arithmetic with %s operator prohibited\n", 14692 dst, bpf_alu_string[opcode >> 4]); 14693 return -EACCES; 14694 } 14695 14696 if (!check_reg_sane_offset(env, dst_reg, ptr_reg->type)) 14697 return -EINVAL; 14698 reg_bounds_sync(dst_reg); 14699 bounds_ret = sanitize_check_bounds(env, insn, dst_reg); 14700 if (bounds_ret == -EACCES) 14701 return bounds_ret; 14702 if (sanitize_needed(opcode)) { 14703 ret = sanitize_ptr_alu(env, insn, dst_reg, off_reg, dst_reg, 14704 &info, true); 14705 if (verifier_bug_if(!can_skip_alu_sanitation(env, insn) 14706 && !env->cur_state->speculative 14707 && bounds_ret 14708 && !ret, 14709 env, "Pointer type unsupported by sanitize_check_bounds() not rejected by retrieve_ptr_limit() as required")) { 14710 return -EFAULT; 14711 } 14712 if (ret < 0) 14713 return sanitize_err(env, insn, ret, off_reg, dst_reg); 14714 } 14715 14716 return 0; 14717 } 14718 14719 static void scalar32_min_max_add(struct bpf_reg_state *dst_reg, 14720 struct bpf_reg_state *src_reg) 14721 { 14722 s32 *dst_smin = &dst_reg->s32_min_value; 14723 s32 *dst_smax = &dst_reg->s32_max_value; 14724 u32 *dst_umin = &dst_reg->u32_min_value; 14725 u32 *dst_umax = &dst_reg->u32_max_value; 14726 u32 umin_val = src_reg->u32_min_value; 14727 u32 umax_val = src_reg->u32_max_value; 14728 bool min_overflow, max_overflow; 14729 14730 if (check_add_overflow(*dst_smin, src_reg->s32_min_value, dst_smin) || 14731 check_add_overflow(*dst_smax, src_reg->s32_max_value, dst_smax)) { 14732 *dst_smin = S32_MIN; 14733 *dst_smax = S32_MAX; 14734 } 14735 14736 /* If either all additions overflow or no additions overflow, then 14737 * it is okay to set: dst_umin = dst_umin + src_umin, dst_umax = 14738 * dst_umax + src_umax. Otherwise (some additions overflow), set 14739 * the output bounds to unbounded. 14740 */ 14741 min_overflow = check_add_overflow(*dst_umin, umin_val, dst_umin); 14742 max_overflow = check_add_overflow(*dst_umax, umax_val, dst_umax); 14743 14744 if (!min_overflow && max_overflow) { 14745 *dst_umin = 0; 14746 *dst_umax = U32_MAX; 14747 } 14748 } 14749 14750 static void scalar_min_max_add(struct bpf_reg_state *dst_reg, 14751 struct bpf_reg_state *src_reg) 14752 { 14753 s64 *dst_smin = &dst_reg->smin_value; 14754 s64 *dst_smax = &dst_reg->smax_value; 14755 u64 *dst_umin = &dst_reg->umin_value; 14756 u64 *dst_umax = &dst_reg->umax_value; 14757 u64 umin_val = src_reg->umin_value; 14758 u64 umax_val = src_reg->umax_value; 14759 bool min_overflow, max_overflow; 14760 14761 if (check_add_overflow(*dst_smin, src_reg->smin_value, dst_smin) || 14762 check_add_overflow(*dst_smax, src_reg->smax_value, dst_smax)) { 14763 *dst_smin = S64_MIN; 14764 *dst_smax = S64_MAX; 14765 } 14766 14767 /* If either all additions overflow or no additions overflow, then 14768 * it is okay to set: dst_umin = dst_umin + src_umin, dst_umax = 14769 * dst_umax + src_umax. Otherwise (some additions overflow), set 14770 * the output bounds to unbounded. 14771 */ 14772 min_overflow = check_add_overflow(*dst_umin, umin_val, dst_umin); 14773 max_overflow = check_add_overflow(*dst_umax, umax_val, dst_umax); 14774 14775 if (!min_overflow && max_overflow) { 14776 *dst_umin = 0; 14777 *dst_umax = U64_MAX; 14778 } 14779 } 14780 14781 static void scalar32_min_max_sub(struct bpf_reg_state *dst_reg, 14782 struct bpf_reg_state *src_reg) 14783 { 14784 s32 *dst_smin = &dst_reg->s32_min_value; 14785 s32 *dst_smax = &dst_reg->s32_max_value; 14786 u32 *dst_umin = &dst_reg->u32_min_value; 14787 u32 *dst_umax = &dst_reg->u32_max_value; 14788 u32 umin_val = src_reg->u32_min_value; 14789 u32 umax_val = src_reg->u32_max_value; 14790 bool min_underflow, max_underflow; 14791 14792 if (check_sub_overflow(*dst_smin, src_reg->s32_max_value, dst_smin) || 14793 check_sub_overflow(*dst_smax, src_reg->s32_min_value, dst_smax)) { 14794 /* Overflow possible, we know nothing */ 14795 *dst_smin = S32_MIN; 14796 *dst_smax = S32_MAX; 14797 } 14798 14799 /* If either all subtractions underflow or no subtractions 14800 * underflow, it is okay to set: dst_umin = dst_umin - src_umax, 14801 * dst_umax = dst_umax - src_umin. Otherwise (some subtractions 14802 * underflow), set the output bounds to unbounded. 14803 */ 14804 min_underflow = check_sub_overflow(*dst_umin, umax_val, dst_umin); 14805 max_underflow = check_sub_overflow(*dst_umax, umin_val, dst_umax); 14806 14807 if (min_underflow && !max_underflow) { 14808 *dst_umin = 0; 14809 *dst_umax = U32_MAX; 14810 } 14811 } 14812 14813 static void scalar_min_max_sub(struct bpf_reg_state *dst_reg, 14814 struct bpf_reg_state *src_reg) 14815 { 14816 s64 *dst_smin = &dst_reg->smin_value; 14817 s64 *dst_smax = &dst_reg->smax_value; 14818 u64 *dst_umin = &dst_reg->umin_value; 14819 u64 *dst_umax = &dst_reg->umax_value; 14820 u64 umin_val = src_reg->umin_value; 14821 u64 umax_val = src_reg->umax_value; 14822 bool min_underflow, max_underflow; 14823 14824 if (check_sub_overflow(*dst_smin, src_reg->smax_value, dst_smin) || 14825 check_sub_overflow(*dst_smax, src_reg->smin_value, dst_smax)) { 14826 /* Overflow possible, we know nothing */ 14827 *dst_smin = S64_MIN; 14828 *dst_smax = S64_MAX; 14829 } 14830 14831 /* If either all subtractions underflow or no subtractions 14832 * underflow, it is okay to set: dst_umin = dst_umin - src_umax, 14833 * dst_umax = dst_umax - src_umin. Otherwise (some subtractions 14834 * underflow), set the output bounds to unbounded. 14835 */ 14836 min_underflow = check_sub_overflow(*dst_umin, umax_val, dst_umin); 14837 max_underflow = check_sub_overflow(*dst_umax, umin_val, dst_umax); 14838 14839 if (min_underflow && !max_underflow) { 14840 *dst_umin = 0; 14841 *dst_umax = U64_MAX; 14842 } 14843 } 14844 14845 static void scalar32_min_max_mul(struct bpf_reg_state *dst_reg, 14846 struct bpf_reg_state *src_reg) 14847 { 14848 s32 *dst_smin = &dst_reg->s32_min_value; 14849 s32 *dst_smax = &dst_reg->s32_max_value; 14850 u32 *dst_umin = &dst_reg->u32_min_value; 14851 u32 *dst_umax = &dst_reg->u32_max_value; 14852 s32 tmp_prod[4]; 14853 14854 if (check_mul_overflow(*dst_umax, src_reg->u32_max_value, dst_umax) || 14855 check_mul_overflow(*dst_umin, src_reg->u32_min_value, dst_umin)) { 14856 /* Overflow possible, we know nothing */ 14857 *dst_umin = 0; 14858 *dst_umax = U32_MAX; 14859 } 14860 if (check_mul_overflow(*dst_smin, src_reg->s32_min_value, &tmp_prod[0]) || 14861 check_mul_overflow(*dst_smin, src_reg->s32_max_value, &tmp_prod[1]) || 14862 check_mul_overflow(*dst_smax, src_reg->s32_min_value, &tmp_prod[2]) || 14863 check_mul_overflow(*dst_smax, src_reg->s32_max_value, &tmp_prod[3])) { 14864 /* Overflow possible, we know nothing */ 14865 *dst_smin = S32_MIN; 14866 *dst_smax = S32_MAX; 14867 } else { 14868 *dst_smin = min_array(tmp_prod, 4); 14869 *dst_smax = max_array(tmp_prod, 4); 14870 } 14871 } 14872 14873 static void scalar_min_max_mul(struct bpf_reg_state *dst_reg, 14874 struct bpf_reg_state *src_reg) 14875 { 14876 s64 *dst_smin = &dst_reg->smin_value; 14877 s64 *dst_smax = &dst_reg->smax_value; 14878 u64 *dst_umin = &dst_reg->umin_value; 14879 u64 *dst_umax = &dst_reg->umax_value; 14880 s64 tmp_prod[4]; 14881 14882 if (check_mul_overflow(*dst_umax, src_reg->umax_value, dst_umax) || 14883 check_mul_overflow(*dst_umin, src_reg->umin_value, dst_umin)) { 14884 /* Overflow possible, we know nothing */ 14885 *dst_umin = 0; 14886 *dst_umax = U64_MAX; 14887 } 14888 if (check_mul_overflow(*dst_smin, src_reg->smin_value, &tmp_prod[0]) || 14889 check_mul_overflow(*dst_smin, src_reg->smax_value, &tmp_prod[1]) || 14890 check_mul_overflow(*dst_smax, src_reg->smin_value, &tmp_prod[2]) || 14891 check_mul_overflow(*dst_smax, src_reg->smax_value, &tmp_prod[3])) { 14892 /* Overflow possible, we know nothing */ 14893 *dst_smin = S64_MIN; 14894 *dst_smax = S64_MAX; 14895 } else { 14896 *dst_smin = min_array(tmp_prod, 4); 14897 *dst_smax = max_array(tmp_prod, 4); 14898 } 14899 } 14900 14901 static void scalar32_min_max_and(struct bpf_reg_state *dst_reg, 14902 struct bpf_reg_state *src_reg) 14903 { 14904 bool src_known = tnum_subreg_is_const(src_reg->var_off); 14905 bool dst_known = tnum_subreg_is_const(dst_reg->var_off); 14906 struct tnum var32_off = tnum_subreg(dst_reg->var_off); 14907 u32 umax_val = src_reg->u32_max_value; 14908 14909 if (src_known && dst_known) { 14910 __mark_reg32_known(dst_reg, var32_off.value); 14911 return; 14912 } 14913 14914 /* We get our minimum from the var_off, since that's inherently 14915 * bitwise. Our maximum is the minimum of the operands' maxima. 14916 */ 14917 dst_reg->u32_min_value = var32_off.value; 14918 dst_reg->u32_max_value = min(dst_reg->u32_max_value, umax_val); 14919 14920 /* Safe to set s32 bounds by casting u32 result into s32 when u32 14921 * doesn't cross sign boundary. Otherwise set s32 bounds to unbounded. 14922 */ 14923 if ((s32)dst_reg->u32_min_value <= (s32)dst_reg->u32_max_value) { 14924 dst_reg->s32_min_value = dst_reg->u32_min_value; 14925 dst_reg->s32_max_value = dst_reg->u32_max_value; 14926 } else { 14927 dst_reg->s32_min_value = S32_MIN; 14928 dst_reg->s32_max_value = S32_MAX; 14929 } 14930 } 14931 14932 static void scalar_min_max_and(struct bpf_reg_state *dst_reg, 14933 struct bpf_reg_state *src_reg) 14934 { 14935 bool src_known = tnum_is_const(src_reg->var_off); 14936 bool dst_known = tnum_is_const(dst_reg->var_off); 14937 u64 umax_val = src_reg->umax_value; 14938 14939 if (src_known && dst_known) { 14940 __mark_reg_known(dst_reg, dst_reg->var_off.value); 14941 return; 14942 } 14943 14944 /* We get our minimum from the var_off, since that's inherently 14945 * bitwise. Our maximum is the minimum of the operands' maxima. 14946 */ 14947 dst_reg->umin_value = dst_reg->var_off.value; 14948 dst_reg->umax_value = min(dst_reg->umax_value, umax_val); 14949 14950 /* Safe to set s64 bounds by casting u64 result into s64 when u64 14951 * doesn't cross sign boundary. Otherwise set s64 bounds to unbounded. 14952 */ 14953 if ((s64)dst_reg->umin_value <= (s64)dst_reg->umax_value) { 14954 dst_reg->smin_value = dst_reg->umin_value; 14955 dst_reg->smax_value = dst_reg->umax_value; 14956 } else { 14957 dst_reg->smin_value = S64_MIN; 14958 dst_reg->smax_value = S64_MAX; 14959 } 14960 /* We may learn something more from the var_off */ 14961 __update_reg_bounds(dst_reg); 14962 } 14963 14964 static void scalar32_min_max_or(struct bpf_reg_state *dst_reg, 14965 struct bpf_reg_state *src_reg) 14966 { 14967 bool src_known = tnum_subreg_is_const(src_reg->var_off); 14968 bool dst_known = tnum_subreg_is_const(dst_reg->var_off); 14969 struct tnum var32_off = tnum_subreg(dst_reg->var_off); 14970 u32 umin_val = src_reg->u32_min_value; 14971 14972 if (src_known && dst_known) { 14973 __mark_reg32_known(dst_reg, var32_off.value); 14974 return; 14975 } 14976 14977 /* We get our maximum from the var_off, and our minimum is the 14978 * maximum of the operands' minima 14979 */ 14980 dst_reg->u32_min_value = max(dst_reg->u32_min_value, umin_val); 14981 dst_reg->u32_max_value = var32_off.value | var32_off.mask; 14982 14983 /* Safe to set s32 bounds by casting u32 result into s32 when u32 14984 * doesn't cross sign boundary. Otherwise set s32 bounds to unbounded. 14985 */ 14986 if ((s32)dst_reg->u32_min_value <= (s32)dst_reg->u32_max_value) { 14987 dst_reg->s32_min_value = dst_reg->u32_min_value; 14988 dst_reg->s32_max_value = dst_reg->u32_max_value; 14989 } else { 14990 dst_reg->s32_min_value = S32_MIN; 14991 dst_reg->s32_max_value = S32_MAX; 14992 } 14993 } 14994 14995 static void scalar_min_max_or(struct bpf_reg_state *dst_reg, 14996 struct bpf_reg_state *src_reg) 14997 { 14998 bool src_known = tnum_is_const(src_reg->var_off); 14999 bool dst_known = tnum_is_const(dst_reg->var_off); 15000 u64 umin_val = src_reg->umin_value; 15001 15002 if (src_known && dst_known) { 15003 __mark_reg_known(dst_reg, dst_reg->var_off.value); 15004 return; 15005 } 15006 15007 /* We get our maximum from the var_off, and our minimum is the 15008 * maximum of the operands' minima 15009 */ 15010 dst_reg->umin_value = max(dst_reg->umin_value, umin_val); 15011 dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask; 15012 15013 /* Safe to set s64 bounds by casting u64 result into s64 when u64 15014 * doesn't cross sign boundary. Otherwise set s64 bounds to unbounded. 15015 */ 15016 if ((s64)dst_reg->umin_value <= (s64)dst_reg->umax_value) { 15017 dst_reg->smin_value = dst_reg->umin_value; 15018 dst_reg->smax_value = dst_reg->umax_value; 15019 } else { 15020 dst_reg->smin_value = S64_MIN; 15021 dst_reg->smax_value = S64_MAX; 15022 } 15023 /* We may learn something more from the var_off */ 15024 __update_reg_bounds(dst_reg); 15025 } 15026 15027 static void scalar32_min_max_xor(struct bpf_reg_state *dst_reg, 15028 struct bpf_reg_state *src_reg) 15029 { 15030 bool src_known = tnum_subreg_is_const(src_reg->var_off); 15031 bool dst_known = tnum_subreg_is_const(dst_reg->var_off); 15032 struct tnum var32_off = tnum_subreg(dst_reg->var_off); 15033 15034 if (src_known && dst_known) { 15035 __mark_reg32_known(dst_reg, var32_off.value); 15036 return; 15037 } 15038 15039 /* We get both minimum and maximum from the var32_off. */ 15040 dst_reg->u32_min_value = var32_off.value; 15041 dst_reg->u32_max_value = var32_off.value | var32_off.mask; 15042 15043 /* Safe to set s32 bounds by casting u32 result into s32 when u32 15044 * doesn't cross sign boundary. Otherwise set s32 bounds to unbounded. 15045 */ 15046 if ((s32)dst_reg->u32_min_value <= (s32)dst_reg->u32_max_value) { 15047 dst_reg->s32_min_value = dst_reg->u32_min_value; 15048 dst_reg->s32_max_value = dst_reg->u32_max_value; 15049 } else { 15050 dst_reg->s32_min_value = S32_MIN; 15051 dst_reg->s32_max_value = S32_MAX; 15052 } 15053 } 15054 15055 static void scalar_min_max_xor(struct bpf_reg_state *dst_reg, 15056 struct bpf_reg_state *src_reg) 15057 { 15058 bool src_known = tnum_is_const(src_reg->var_off); 15059 bool dst_known = tnum_is_const(dst_reg->var_off); 15060 15061 if (src_known && dst_known) { 15062 /* dst_reg->var_off.value has been updated earlier */ 15063 __mark_reg_known(dst_reg, dst_reg->var_off.value); 15064 return; 15065 } 15066 15067 /* We get both minimum and maximum from the var_off. */ 15068 dst_reg->umin_value = dst_reg->var_off.value; 15069 dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask; 15070 15071 /* Safe to set s64 bounds by casting u64 result into s64 when u64 15072 * doesn't cross sign boundary. Otherwise set s64 bounds to unbounded. 15073 */ 15074 if ((s64)dst_reg->umin_value <= (s64)dst_reg->umax_value) { 15075 dst_reg->smin_value = dst_reg->umin_value; 15076 dst_reg->smax_value = dst_reg->umax_value; 15077 } else { 15078 dst_reg->smin_value = S64_MIN; 15079 dst_reg->smax_value = S64_MAX; 15080 } 15081 15082 __update_reg_bounds(dst_reg); 15083 } 15084 15085 static void __scalar32_min_max_lsh(struct bpf_reg_state *dst_reg, 15086 u64 umin_val, u64 umax_val) 15087 { 15088 /* We lose all sign bit information (except what we can pick 15089 * up from var_off) 15090 */ 15091 dst_reg->s32_min_value = S32_MIN; 15092 dst_reg->s32_max_value = S32_MAX; 15093 /* If we might shift our top bit out, then we know nothing */ 15094 if (umax_val > 31 || dst_reg->u32_max_value > 1ULL << (31 - umax_val)) { 15095 dst_reg->u32_min_value = 0; 15096 dst_reg->u32_max_value = U32_MAX; 15097 } else { 15098 dst_reg->u32_min_value <<= umin_val; 15099 dst_reg->u32_max_value <<= umax_val; 15100 } 15101 } 15102 15103 static void scalar32_min_max_lsh(struct bpf_reg_state *dst_reg, 15104 struct bpf_reg_state *src_reg) 15105 { 15106 u32 umax_val = src_reg->u32_max_value; 15107 u32 umin_val = src_reg->u32_min_value; 15108 /* u32 alu operation will zext upper bits */ 15109 struct tnum subreg = tnum_subreg(dst_reg->var_off); 15110 15111 __scalar32_min_max_lsh(dst_reg, umin_val, umax_val); 15112 dst_reg->var_off = tnum_subreg(tnum_lshift(subreg, umin_val)); 15113 /* Not required but being careful mark reg64 bounds as unknown so 15114 * that we are forced to pick them up from tnum and zext later and 15115 * if some path skips this step we are still safe. 15116 */ 15117 __mark_reg64_unbounded(dst_reg); 15118 __update_reg32_bounds(dst_reg); 15119 } 15120 15121 static void __scalar64_min_max_lsh(struct bpf_reg_state *dst_reg, 15122 u64 umin_val, u64 umax_val) 15123 { 15124 /* Special case <<32 because it is a common compiler pattern to sign 15125 * extend subreg by doing <<32 s>>32. In this case if 32bit bounds are 15126 * positive we know this shift will also be positive so we can track 15127 * bounds correctly. Otherwise we lose all sign bit information except 15128 * what we can pick up from var_off. Perhaps we can generalize this 15129 * later to shifts of any length. 15130 */ 15131 if (umin_val == 32 && umax_val == 32 && dst_reg->s32_max_value >= 0) 15132 dst_reg->smax_value = (s64)dst_reg->s32_max_value << 32; 15133 else 15134 dst_reg->smax_value = S64_MAX; 15135 15136 if (umin_val == 32 && umax_val == 32 && dst_reg->s32_min_value >= 0) 15137 dst_reg->smin_value = (s64)dst_reg->s32_min_value << 32; 15138 else 15139 dst_reg->smin_value = S64_MIN; 15140 15141 /* If we might shift our top bit out, then we know nothing */ 15142 if (dst_reg->umax_value > 1ULL << (63 - umax_val)) { 15143 dst_reg->umin_value = 0; 15144 dst_reg->umax_value = U64_MAX; 15145 } else { 15146 dst_reg->umin_value <<= umin_val; 15147 dst_reg->umax_value <<= umax_val; 15148 } 15149 } 15150 15151 static void scalar_min_max_lsh(struct bpf_reg_state *dst_reg, 15152 struct bpf_reg_state *src_reg) 15153 { 15154 u64 umax_val = src_reg->umax_value; 15155 u64 umin_val = src_reg->umin_value; 15156 15157 /* scalar64 calc uses 32bit unshifted bounds so must be called first */ 15158 __scalar64_min_max_lsh(dst_reg, umin_val, umax_val); 15159 __scalar32_min_max_lsh(dst_reg, umin_val, umax_val); 15160 15161 dst_reg->var_off = tnum_lshift(dst_reg->var_off, umin_val); 15162 /* We may learn something more from the var_off */ 15163 __update_reg_bounds(dst_reg); 15164 } 15165 15166 static void scalar32_min_max_rsh(struct bpf_reg_state *dst_reg, 15167 struct bpf_reg_state *src_reg) 15168 { 15169 struct tnum subreg = tnum_subreg(dst_reg->var_off); 15170 u32 umax_val = src_reg->u32_max_value; 15171 u32 umin_val = src_reg->u32_min_value; 15172 15173 /* BPF_RSH is an unsigned shift. If the value in dst_reg might 15174 * be negative, then either: 15175 * 1) src_reg might be zero, so the sign bit of the result is 15176 * unknown, so we lose our signed bounds 15177 * 2) it's known negative, thus the unsigned bounds capture the 15178 * signed bounds 15179 * 3) the signed bounds cross zero, so they tell us nothing 15180 * about the result 15181 * If the value in dst_reg is known nonnegative, then again the 15182 * unsigned bounds capture the signed bounds. 15183 * Thus, in all cases it suffices to blow away our signed bounds 15184 * and rely on inferring new ones from the unsigned bounds and 15185 * var_off of the result. 15186 */ 15187 dst_reg->s32_min_value = S32_MIN; 15188 dst_reg->s32_max_value = S32_MAX; 15189 15190 dst_reg->var_off = tnum_rshift(subreg, umin_val); 15191 dst_reg->u32_min_value >>= umax_val; 15192 dst_reg->u32_max_value >>= umin_val; 15193 15194 __mark_reg64_unbounded(dst_reg); 15195 __update_reg32_bounds(dst_reg); 15196 } 15197 15198 static void scalar_min_max_rsh(struct bpf_reg_state *dst_reg, 15199 struct bpf_reg_state *src_reg) 15200 { 15201 u64 umax_val = src_reg->umax_value; 15202 u64 umin_val = src_reg->umin_value; 15203 15204 /* BPF_RSH is an unsigned shift. If the value in dst_reg might 15205 * be negative, then either: 15206 * 1) src_reg might be zero, so the sign bit of the result is 15207 * unknown, so we lose our signed bounds 15208 * 2) it's known negative, thus the unsigned bounds capture the 15209 * signed bounds 15210 * 3) the signed bounds cross zero, so they tell us nothing 15211 * about the result 15212 * If the value in dst_reg is known nonnegative, then again the 15213 * unsigned bounds capture the signed bounds. 15214 * Thus, in all cases it suffices to blow away our signed bounds 15215 * and rely on inferring new ones from the unsigned bounds and 15216 * var_off of the result. 15217 */ 15218 dst_reg->smin_value = S64_MIN; 15219 dst_reg->smax_value = S64_MAX; 15220 dst_reg->var_off = tnum_rshift(dst_reg->var_off, umin_val); 15221 dst_reg->umin_value >>= umax_val; 15222 dst_reg->umax_value >>= umin_val; 15223 15224 /* Its not easy to operate on alu32 bounds here because it depends 15225 * on bits being shifted in. Take easy way out and mark unbounded 15226 * so we can recalculate later from tnum. 15227 */ 15228 __mark_reg32_unbounded(dst_reg); 15229 __update_reg_bounds(dst_reg); 15230 } 15231 15232 static void scalar32_min_max_arsh(struct bpf_reg_state *dst_reg, 15233 struct bpf_reg_state *src_reg) 15234 { 15235 u64 umin_val = src_reg->u32_min_value; 15236 15237 /* Upon reaching here, src_known is true and 15238 * umax_val is equal to umin_val. 15239 */ 15240 dst_reg->s32_min_value = (u32)(((s32)dst_reg->s32_min_value) >> umin_val); 15241 dst_reg->s32_max_value = (u32)(((s32)dst_reg->s32_max_value) >> umin_val); 15242 15243 dst_reg->var_off = tnum_arshift(tnum_subreg(dst_reg->var_off), umin_val, 32); 15244 15245 /* blow away the dst_reg umin_value/umax_value and rely on 15246 * dst_reg var_off to refine the result. 15247 */ 15248 dst_reg->u32_min_value = 0; 15249 dst_reg->u32_max_value = U32_MAX; 15250 15251 __mark_reg64_unbounded(dst_reg); 15252 __update_reg32_bounds(dst_reg); 15253 } 15254 15255 static void scalar_min_max_arsh(struct bpf_reg_state *dst_reg, 15256 struct bpf_reg_state *src_reg) 15257 { 15258 u64 umin_val = src_reg->umin_value; 15259 15260 /* Upon reaching here, src_known is true and umax_val is equal 15261 * to umin_val. 15262 */ 15263 dst_reg->smin_value >>= umin_val; 15264 dst_reg->smax_value >>= umin_val; 15265 15266 dst_reg->var_off = tnum_arshift(dst_reg->var_off, umin_val, 64); 15267 15268 /* blow away the dst_reg umin_value/umax_value and rely on 15269 * dst_reg var_off to refine the result. 15270 */ 15271 dst_reg->umin_value = 0; 15272 dst_reg->umax_value = U64_MAX; 15273 15274 /* Its not easy to operate on alu32 bounds here because it depends 15275 * on bits being shifted in from upper 32-bits. Take easy way out 15276 * and mark unbounded so we can recalculate later from tnum. 15277 */ 15278 __mark_reg32_unbounded(dst_reg); 15279 __update_reg_bounds(dst_reg); 15280 } 15281 15282 static bool is_safe_to_compute_dst_reg_range(struct bpf_insn *insn, 15283 const struct bpf_reg_state *src_reg) 15284 { 15285 bool src_is_const = false; 15286 u64 insn_bitness = (BPF_CLASS(insn->code) == BPF_ALU64) ? 64 : 32; 15287 15288 if (insn_bitness == 32) { 15289 if (tnum_subreg_is_const(src_reg->var_off) 15290 && src_reg->s32_min_value == src_reg->s32_max_value 15291 && src_reg->u32_min_value == src_reg->u32_max_value) 15292 src_is_const = true; 15293 } else { 15294 if (tnum_is_const(src_reg->var_off) 15295 && src_reg->smin_value == src_reg->smax_value 15296 && src_reg->umin_value == src_reg->umax_value) 15297 src_is_const = true; 15298 } 15299 15300 switch (BPF_OP(insn->code)) { 15301 case BPF_ADD: 15302 case BPF_SUB: 15303 case BPF_NEG: 15304 case BPF_AND: 15305 case BPF_XOR: 15306 case BPF_OR: 15307 case BPF_MUL: 15308 return true; 15309 15310 /* Shift operators range is only computable if shift dimension operand 15311 * is a constant. Shifts greater than 31 or 63 are undefined. This 15312 * includes shifts by a negative number. 15313 */ 15314 case BPF_LSH: 15315 case BPF_RSH: 15316 case BPF_ARSH: 15317 return (src_is_const && src_reg->umax_value < insn_bitness); 15318 default: 15319 return false; 15320 } 15321 } 15322 15323 /* WARNING: This function does calculations on 64-bit values, but the actual 15324 * execution may occur on 32-bit values. Therefore, things like bitshifts 15325 * need extra checks in the 32-bit case. 15326 */ 15327 static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env, 15328 struct bpf_insn *insn, 15329 struct bpf_reg_state *dst_reg, 15330 struct bpf_reg_state src_reg) 15331 { 15332 u8 opcode = BPF_OP(insn->code); 15333 bool alu32 = (BPF_CLASS(insn->code) != BPF_ALU64); 15334 int ret; 15335 15336 if (!is_safe_to_compute_dst_reg_range(insn, &src_reg)) { 15337 __mark_reg_unknown(env, dst_reg); 15338 return 0; 15339 } 15340 15341 if (sanitize_needed(opcode)) { 15342 ret = sanitize_val_alu(env, insn); 15343 if (ret < 0) 15344 return sanitize_err(env, insn, ret, NULL, NULL); 15345 } 15346 15347 /* Calculate sign/unsigned bounds and tnum for alu32 and alu64 bit ops. 15348 * There are two classes of instructions: The first class we track both 15349 * alu32 and alu64 sign/unsigned bounds independently this provides the 15350 * greatest amount of precision when alu operations are mixed with jmp32 15351 * operations. These operations are BPF_ADD, BPF_SUB, BPF_MUL, BPF_ADD, 15352 * and BPF_OR. This is possible because these ops have fairly easy to 15353 * understand and calculate behavior in both 32-bit and 64-bit alu ops. 15354 * See alu32 verifier tests for examples. The second class of 15355 * operations, BPF_LSH, BPF_RSH, and BPF_ARSH, however are not so easy 15356 * with regards to tracking sign/unsigned bounds because the bits may 15357 * cross subreg boundaries in the alu64 case. When this happens we mark 15358 * the reg unbounded in the subreg bound space and use the resulting 15359 * tnum to calculate an approximation of the sign/unsigned bounds. 15360 */ 15361 switch (opcode) { 15362 case BPF_ADD: 15363 scalar32_min_max_add(dst_reg, &src_reg); 15364 scalar_min_max_add(dst_reg, &src_reg); 15365 dst_reg->var_off = tnum_add(dst_reg->var_off, src_reg.var_off); 15366 break; 15367 case BPF_SUB: 15368 scalar32_min_max_sub(dst_reg, &src_reg); 15369 scalar_min_max_sub(dst_reg, &src_reg); 15370 dst_reg->var_off = tnum_sub(dst_reg->var_off, src_reg.var_off); 15371 break; 15372 case BPF_NEG: 15373 env->fake_reg[0] = *dst_reg; 15374 __mark_reg_known(dst_reg, 0); 15375 scalar32_min_max_sub(dst_reg, &env->fake_reg[0]); 15376 scalar_min_max_sub(dst_reg, &env->fake_reg[0]); 15377 dst_reg->var_off = tnum_neg(env->fake_reg[0].var_off); 15378 break; 15379 case BPF_MUL: 15380 dst_reg->var_off = tnum_mul(dst_reg->var_off, src_reg.var_off); 15381 scalar32_min_max_mul(dst_reg, &src_reg); 15382 scalar_min_max_mul(dst_reg, &src_reg); 15383 break; 15384 case BPF_AND: 15385 dst_reg->var_off = tnum_and(dst_reg->var_off, src_reg.var_off); 15386 scalar32_min_max_and(dst_reg, &src_reg); 15387 scalar_min_max_and(dst_reg, &src_reg); 15388 break; 15389 case BPF_OR: 15390 dst_reg->var_off = tnum_or(dst_reg->var_off, src_reg.var_off); 15391 scalar32_min_max_or(dst_reg, &src_reg); 15392 scalar_min_max_or(dst_reg, &src_reg); 15393 break; 15394 case BPF_XOR: 15395 dst_reg->var_off = tnum_xor(dst_reg->var_off, src_reg.var_off); 15396 scalar32_min_max_xor(dst_reg, &src_reg); 15397 scalar_min_max_xor(dst_reg, &src_reg); 15398 break; 15399 case BPF_LSH: 15400 if (alu32) 15401 scalar32_min_max_lsh(dst_reg, &src_reg); 15402 else 15403 scalar_min_max_lsh(dst_reg, &src_reg); 15404 break; 15405 case BPF_RSH: 15406 if (alu32) 15407 scalar32_min_max_rsh(dst_reg, &src_reg); 15408 else 15409 scalar_min_max_rsh(dst_reg, &src_reg); 15410 break; 15411 case BPF_ARSH: 15412 if (alu32) 15413 scalar32_min_max_arsh(dst_reg, &src_reg); 15414 else 15415 scalar_min_max_arsh(dst_reg, &src_reg); 15416 break; 15417 default: 15418 break; 15419 } 15420 15421 /* ALU32 ops are zero extended into 64bit register */ 15422 if (alu32) 15423 zext_32_to_64(dst_reg); 15424 reg_bounds_sync(dst_reg); 15425 return 0; 15426 } 15427 15428 /* Handles ALU ops other than BPF_END, BPF_NEG and BPF_MOV: computes new min/max 15429 * and var_off. 15430 */ 15431 static int adjust_reg_min_max_vals(struct bpf_verifier_env *env, 15432 struct bpf_insn *insn) 15433 { 15434 struct bpf_verifier_state *vstate = env->cur_state; 15435 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 15436 struct bpf_reg_state *regs = state->regs, *dst_reg, *src_reg; 15437 struct bpf_reg_state *ptr_reg = NULL, off_reg = {0}; 15438 bool alu32 = (BPF_CLASS(insn->code) != BPF_ALU64); 15439 u8 opcode = BPF_OP(insn->code); 15440 int err; 15441 15442 dst_reg = ®s[insn->dst_reg]; 15443 src_reg = NULL; 15444 15445 if (dst_reg->type == PTR_TO_ARENA) { 15446 struct bpf_insn_aux_data *aux = cur_aux(env); 15447 15448 if (BPF_CLASS(insn->code) == BPF_ALU64) 15449 /* 15450 * 32-bit operations zero upper bits automatically. 15451 * 64-bit operations need to be converted to 32. 15452 */ 15453 aux->needs_zext = true; 15454 15455 /* Any arithmetic operations are allowed on arena pointers */ 15456 return 0; 15457 } 15458 15459 if (dst_reg->type != SCALAR_VALUE) 15460 ptr_reg = dst_reg; 15461 15462 if (BPF_SRC(insn->code) == BPF_X) { 15463 src_reg = ®s[insn->src_reg]; 15464 if (src_reg->type != SCALAR_VALUE) { 15465 if (dst_reg->type != SCALAR_VALUE) { 15466 /* Combining two pointers by any ALU op yields 15467 * an arbitrary scalar. Disallow all math except 15468 * pointer subtraction 15469 */ 15470 if (opcode == BPF_SUB && env->allow_ptr_leaks) { 15471 mark_reg_unknown(env, regs, insn->dst_reg); 15472 return 0; 15473 } 15474 verbose(env, "R%d pointer %s pointer prohibited\n", 15475 insn->dst_reg, 15476 bpf_alu_string[opcode >> 4]); 15477 return -EACCES; 15478 } else { 15479 /* scalar += pointer 15480 * This is legal, but we have to reverse our 15481 * src/dest handling in computing the range 15482 */ 15483 err = mark_chain_precision(env, insn->dst_reg); 15484 if (err) 15485 return err; 15486 return adjust_ptr_min_max_vals(env, insn, 15487 src_reg, dst_reg); 15488 } 15489 } else if (ptr_reg) { 15490 /* pointer += scalar */ 15491 err = mark_chain_precision(env, insn->src_reg); 15492 if (err) 15493 return err; 15494 return adjust_ptr_min_max_vals(env, insn, 15495 dst_reg, src_reg); 15496 } else if (dst_reg->precise) { 15497 /* if dst_reg is precise, src_reg should be precise as well */ 15498 err = mark_chain_precision(env, insn->src_reg); 15499 if (err) 15500 return err; 15501 } 15502 } else { 15503 /* Pretend the src is a reg with a known value, since we only 15504 * need to be able to read from this state. 15505 */ 15506 off_reg.type = SCALAR_VALUE; 15507 __mark_reg_known(&off_reg, insn->imm); 15508 src_reg = &off_reg; 15509 if (ptr_reg) /* pointer += K */ 15510 return adjust_ptr_min_max_vals(env, insn, 15511 ptr_reg, src_reg); 15512 } 15513 15514 /* Got here implies adding two SCALAR_VALUEs */ 15515 if (WARN_ON_ONCE(ptr_reg)) { 15516 print_verifier_state(env, vstate, vstate->curframe, true); 15517 verbose(env, "verifier internal error: unexpected ptr_reg\n"); 15518 return -EFAULT; 15519 } 15520 if (WARN_ON(!src_reg)) { 15521 print_verifier_state(env, vstate, vstate->curframe, true); 15522 verbose(env, "verifier internal error: no src_reg\n"); 15523 return -EFAULT; 15524 } 15525 err = adjust_scalar_min_max_vals(env, insn, dst_reg, *src_reg); 15526 if (err) 15527 return err; 15528 /* 15529 * Compilers can generate the code 15530 * r1 = r2 15531 * r1 += 0x1 15532 * if r2 < 1000 goto ... 15533 * use r1 in memory access 15534 * So for 64-bit alu remember constant delta between r2 and r1 and 15535 * update r1 after 'if' condition. 15536 */ 15537 if (env->bpf_capable && 15538 BPF_OP(insn->code) == BPF_ADD && !alu32 && 15539 dst_reg->id && is_reg_const(src_reg, false)) { 15540 u64 val = reg_const_value(src_reg, false); 15541 15542 if ((dst_reg->id & BPF_ADD_CONST) || 15543 /* prevent overflow in sync_linked_regs() later */ 15544 val > (u32)S32_MAX) { 15545 /* 15546 * If the register already went through rX += val 15547 * we cannot accumulate another val into rx->off. 15548 */ 15549 dst_reg->off = 0; 15550 dst_reg->id = 0; 15551 } else { 15552 dst_reg->id |= BPF_ADD_CONST; 15553 dst_reg->off = val; 15554 } 15555 } else { 15556 /* 15557 * Make sure ID is cleared otherwise dst_reg min/max could be 15558 * incorrectly propagated into other registers by sync_linked_regs() 15559 */ 15560 dst_reg->id = 0; 15561 } 15562 return 0; 15563 } 15564 15565 /* check validity of 32-bit and 64-bit arithmetic operations */ 15566 static int check_alu_op(struct bpf_verifier_env *env, struct bpf_insn *insn) 15567 { 15568 struct bpf_reg_state *regs = cur_regs(env); 15569 u8 opcode = BPF_OP(insn->code); 15570 int err; 15571 15572 if (opcode == BPF_END || opcode == BPF_NEG) { 15573 if (opcode == BPF_NEG) { 15574 if (BPF_SRC(insn->code) != BPF_K || 15575 insn->src_reg != BPF_REG_0 || 15576 insn->off != 0 || insn->imm != 0) { 15577 verbose(env, "BPF_NEG uses reserved fields\n"); 15578 return -EINVAL; 15579 } 15580 } else { 15581 if (insn->src_reg != BPF_REG_0 || insn->off != 0 || 15582 (insn->imm != 16 && insn->imm != 32 && insn->imm != 64) || 15583 (BPF_CLASS(insn->code) == BPF_ALU64 && 15584 BPF_SRC(insn->code) != BPF_TO_LE)) { 15585 verbose(env, "BPF_END uses reserved fields\n"); 15586 return -EINVAL; 15587 } 15588 } 15589 15590 /* check src operand */ 15591 err = check_reg_arg(env, insn->dst_reg, SRC_OP); 15592 if (err) 15593 return err; 15594 15595 if (is_pointer_value(env, insn->dst_reg)) { 15596 verbose(env, "R%d pointer arithmetic prohibited\n", 15597 insn->dst_reg); 15598 return -EACCES; 15599 } 15600 15601 /* check dest operand */ 15602 if (opcode == BPF_NEG) { 15603 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK); 15604 err = err ?: adjust_scalar_min_max_vals(env, insn, 15605 ®s[insn->dst_reg], 15606 regs[insn->dst_reg]); 15607 } else { 15608 err = check_reg_arg(env, insn->dst_reg, DST_OP); 15609 } 15610 if (err) 15611 return err; 15612 15613 } else if (opcode == BPF_MOV) { 15614 15615 if (BPF_SRC(insn->code) == BPF_X) { 15616 if (BPF_CLASS(insn->code) == BPF_ALU) { 15617 if ((insn->off != 0 && insn->off != 8 && insn->off != 16) || 15618 insn->imm) { 15619 verbose(env, "BPF_MOV uses reserved fields\n"); 15620 return -EINVAL; 15621 } 15622 } else if (insn->off == BPF_ADDR_SPACE_CAST) { 15623 if (insn->imm != 1 && insn->imm != 1u << 16) { 15624 verbose(env, "addr_space_cast insn can only convert between address space 1 and 0\n"); 15625 return -EINVAL; 15626 } 15627 if (!env->prog->aux->arena) { 15628 verbose(env, "addr_space_cast insn can only be used in a program that has an associated arena\n"); 15629 return -EINVAL; 15630 } 15631 } else { 15632 if ((insn->off != 0 && insn->off != 8 && insn->off != 16 && 15633 insn->off != 32) || insn->imm) { 15634 verbose(env, "BPF_MOV uses reserved fields\n"); 15635 return -EINVAL; 15636 } 15637 } 15638 15639 /* check src operand */ 15640 err = check_reg_arg(env, insn->src_reg, SRC_OP); 15641 if (err) 15642 return err; 15643 } else { 15644 if (insn->src_reg != BPF_REG_0 || insn->off != 0) { 15645 verbose(env, "BPF_MOV uses reserved fields\n"); 15646 return -EINVAL; 15647 } 15648 } 15649 15650 /* check dest operand, mark as required later */ 15651 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK); 15652 if (err) 15653 return err; 15654 15655 if (BPF_SRC(insn->code) == BPF_X) { 15656 struct bpf_reg_state *src_reg = regs + insn->src_reg; 15657 struct bpf_reg_state *dst_reg = regs + insn->dst_reg; 15658 15659 if (BPF_CLASS(insn->code) == BPF_ALU64) { 15660 if (insn->imm) { 15661 /* off == BPF_ADDR_SPACE_CAST */ 15662 mark_reg_unknown(env, regs, insn->dst_reg); 15663 if (insn->imm == 1) { /* cast from as(1) to as(0) */ 15664 dst_reg->type = PTR_TO_ARENA; 15665 /* PTR_TO_ARENA is 32-bit */ 15666 dst_reg->subreg_def = env->insn_idx + 1; 15667 } 15668 } else if (insn->off == 0) { 15669 /* case: R1 = R2 15670 * copy register state to dest reg 15671 */ 15672 assign_scalar_id_before_mov(env, src_reg); 15673 copy_register_state(dst_reg, src_reg); 15674 dst_reg->live |= REG_LIVE_WRITTEN; 15675 dst_reg->subreg_def = DEF_NOT_SUBREG; 15676 } else { 15677 /* case: R1 = (s8, s16 s32)R2 */ 15678 if (is_pointer_value(env, insn->src_reg)) { 15679 verbose(env, 15680 "R%d sign-extension part of pointer\n", 15681 insn->src_reg); 15682 return -EACCES; 15683 } else if (src_reg->type == SCALAR_VALUE) { 15684 bool no_sext; 15685 15686 no_sext = src_reg->umax_value < (1ULL << (insn->off - 1)); 15687 if (no_sext) 15688 assign_scalar_id_before_mov(env, src_reg); 15689 copy_register_state(dst_reg, src_reg); 15690 if (!no_sext) 15691 dst_reg->id = 0; 15692 coerce_reg_to_size_sx(dst_reg, insn->off >> 3); 15693 dst_reg->live |= REG_LIVE_WRITTEN; 15694 dst_reg->subreg_def = DEF_NOT_SUBREG; 15695 } else { 15696 mark_reg_unknown(env, regs, insn->dst_reg); 15697 } 15698 } 15699 } else { 15700 /* R1 = (u32) R2 */ 15701 if (is_pointer_value(env, insn->src_reg)) { 15702 verbose(env, 15703 "R%d partial copy of pointer\n", 15704 insn->src_reg); 15705 return -EACCES; 15706 } else if (src_reg->type == SCALAR_VALUE) { 15707 if (insn->off == 0) { 15708 bool is_src_reg_u32 = get_reg_width(src_reg) <= 32; 15709 15710 if (is_src_reg_u32) 15711 assign_scalar_id_before_mov(env, src_reg); 15712 copy_register_state(dst_reg, src_reg); 15713 /* Make sure ID is cleared if src_reg is not in u32 15714 * range otherwise dst_reg min/max could be incorrectly 15715 * propagated into src_reg by sync_linked_regs() 15716 */ 15717 if (!is_src_reg_u32) 15718 dst_reg->id = 0; 15719 dst_reg->live |= REG_LIVE_WRITTEN; 15720 dst_reg->subreg_def = env->insn_idx + 1; 15721 } else { 15722 /* case: W1 = (s8, s16)W2 */ 15723 bool no_sext = src_reg->umax_value < (1ULL << (insn->off - 1)); 15724 15725 if (no_sext) 15726 assign_scalar_id_before_mov(env, src_reg); 15727 copy_register_state(dst_reg, src_reg); 15728 if (!no_sext) 15729 dst_reg->id = 0; 15730 dst_reg->live |= REG_LIVE_WRITTEN; 15731 dst_reg->subreg_def = env->insn_idx + 1; 15732 coerce_subreg_to_size_sx(dst_reg, insn->off >> 3); 15733 } 15734 } else { 15735 mark_reg_unknown(env, regs, 15736 insn->dst_reg); 15737 } 15738 zext_32_to_64(dst_reg); 15739 reg_bounds_sync(dst_reg); 15740 } 15741 } else { 15742 /* case: R = imm 15743 * remember the value we stored into this reg 15744 */ 15745 /* clear any state __mark_reg_known doesn't set */ 15746 mark_reg_unknown(env, regs, insn->dst_reg); 15747 regs[insn->dst_reg].type = SCALAR_VALUE; 15748 if (BPF_CLASS(insn->code) == BPF_ALU64) { 15749 __mark_reg_known(regs + insn->dst_reg, 15750 insn->imm); 15751 } else { 15752 __mark_reg_known(regs + insn->dst_reg, 15753 (u32)insn->imm); 15754 } 15755 } 15756 15757 } else if (opcode > BPF_END) { 15758 verbose(env, "invalid BPF_ALU opcode %x\n", opcode); 15759 return -EINVAL; 15760 15761 } else { /* all other ALU ops: and, sub, xor, add, ... */ 15762 15763 if (BPF_SRC(insn->code) == BPF_X) { 15764 if (insn->imm != 0 || insn->off > 1 || 15765 (insn->off == 1 && opcode != BPF_MOD && opcode != BPF_DIV)) { 15766 verbose(env, "BPF_ALU uses reserved fields\n"); 15767 return -EINVAL; 15768 } 15769 /* check src1 operand */ 15770 err = check_reg_arg(env, insn->src_reg, SRC_OP); 15771 if (err) 15772 return err; 15773 } else { 15774 if (insn->src_reg != BPF_REG_0 || insn->off > 1 || 15775 (insn->off == 1 && opcode != BPF_MOD && opcode != BPF_DIV)) { 15776 verbose(env, "BPF_ALU uses reserved fields\n"); 15777 return -EINVAL; 15778 } 15779 } 15780 15781 /* check src2 operand */ 15782 err = check_reg_arg(env, insn->dst_reg, SRC_OP); 15783 if (err) 15784 return err; 15785 15786 if ((opcode == BPF_MOD || opcode == BPF_DIV) && 15787 BPF_SRC(insn->code) == BPF_K && insn->imm == 0) { 15788 verbose(env, "div by zero\n"); 15789 return -EINVAL; 15790 } 15791 15792 if ((opcode == BPF_LSH || opcode == BPF_RSH || 15793 opcode == BPF_ARSH) && BPF_SRC(insn->code) == BPF_K) { 15794 int size = BPF_CLASS(insn->code) == BPF_ALU64 ? 64 : 32; 15795 15796 if (insn->imm < 0 || insn->imm >= size) { 15797 verbose(env, "invalid shift %d\n", insn->imm); 15798 return -EINVAL; 15799 } 15800 } 15801 15802 /* check dest operand */ 15803 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK); 15804 err = err ?: adjust_reg_min_max_vals(env, insn); 15805 if (err) 15806 return err; 15807 } 15808 15809 return reg_bounds_sanity_check(env, ®s[insn->dst_reg], "alu"); 15810 } 15811 15812 static void find_good_pkt_pointers(struct bpf_verifier_state *vstate, 15813 struct bpf_reg_state *dst_reg, 15814 enum bpf_reg_type type, 15815 bool range_right_open) 15816 { 15817 struct bpf_func_state *state; 15818 struct bpf_reg_state *reg; 15819 int new_range; 15820 15821 if (dst_reg->off < 0 || 15822 (dst_reg->off == 0 && range_right_open)) 15823 /* This doesn't give us any range */ 15824 return; 15825 15826 if (dst_reg->umax_value > MAX_PACKET_OFF || 15827 dst_reg->umax_value + dst_reg->off > MAX_PACKET_OFF) 15828 /* Risk of overflow. For instance, ptr + (1<<63) may be less 15829 * than pkt_end, but that's because it's also less than pkt. 15830 */ 15831 return; 15832 15833 new_range = dst_reg->off; 15834 if (range_right_open) 15835 new_range++; 15836 15837 /* Examples for register markings: 15838 * 15839 * pkt_data in dst register: 15840 * 15841 * r2 = r3; 15842 * r2 += 8; 15843 * if (r2 > pkt_end) goto <handle exception> 15844 * <access okay> 15845 * 15846 * r2 = r3; 15847 * r2 += 8; 15848 * if (r2 < pkt_end) goto <access okay> 15849 * <handle exception> 15850 * 15851 * Where: 15852 * r2 == dst_reg, pkt_end == src_reg 15853 * r2=pkt(id=n,off=8,r=0) 15854 * r3=pkt(id=n,off=0,r=0) 15855 * 15856 * pkt_data in src register: 15857 * 15858 * r2 = r3; 15859 * r2 += 8; 15860 * if (pkt_end >= r2) goto <access okay> 15861 * <handle exception> 15862 * 15863 * r2 = r3; 15864 * r2 += 8; 15865 * if (pkt_end <= r2) goto <handle exception> 15866 * <access okay> 15867 * 15868 * Where: 15869 * pkt_end == dst_reg, r2 == src_reg 15870 * r2=pkt(id=n,off=8,r=0) 15871 * r3=pkt(id=n,off=0,r=0) 15872 * 15873 * Find register r3 and mark its range as r3=pkt(id=n,off=0,r=8) 15874 * or r3=pkt(id=n,off=0,r=8-1), so that range of bytes [r3, r3 + 8) 15875 * and [r3, r3 + 8-1) respectively is safe to access depending on 15876 * the check. 15877 */ 15878 15879 /* If our ids match, then we must have the same max_value. And we 15880 * don't care about the other reg's fixed offset, since if it's too big 15881 * the range won't allow anything. 15882 * dst_reg->off is known < MAX_PACKET_OFF, therefore it fits in a u16. 15883 */ 15884 bpf_for_each_reg_in_vstate(vstate, state, reg, ({ 15885 if (reg->type == type && reg->id == dst_reg->id) 15886 /* keep the maximum range already checked */ 15887 reg->range = max(reg->range, new_range); 15888 })); 15889 } 15890 15891 /* 15892 * <reg1> <op> <reg2>, currently assuming reg2 is a constant 15893 */ 15894 static int is_scalar_branch_taken(struct bpf_reg_state *reg1, struct bpf_reg_state *reg2, 15895 u8 opcode, bool is_jmp32) 15896 { 15897 struct tnum t1 = is_jmp32 ? tnum_subreg(reg1->var_off) : reg1->var_off; 15898 struct tnum t2 = is_jmp32 ? tnum_subreg(reg2->var_off) : reg2->var_off; 15899 u64 umin1 = is_jmp32 ? (u64)reg1->u32_min_value : reg1->umin_value; 15900 u64 umax1 = is_jmp32 ? (u64)reg1->u32_max_value : reg1->umax_value; 15901 s64 smin1 = is_jmp32 ? (s64)reg1->s32_min_value : reg1->smin_value; 15902 s64 smax1 = is_jmp32 ? (s64)reg1->s32_max_value : reg1->smax_value; 15903 u64 umin2 = is_jmp32 ? (u64)reg2->u32_min_value : reg2->umin_value; 15904 u64 umax2 = is_jmp32 ? (u64)reg2->u32_max_value : reg2->umax_value; 15905 s64 smin2 = is_jmp32 ? (s64)reg2->s32_min_value : reg2->smin_value; 15906 s64 smax2 = is_jmp32 ? (s64)reg2->s32_max_value : reg2->smax_value; 15907 15908 switch (opcode) { 15909 case BPF_JEQ: 15910 /* constants, umin/umax and smin/smax checks would be 15911 * redundant in this case because they all should match 15912 */ 15913 if (tnum_is_const(t1) && tnum_is_const(t2)) 15914 return t1.value == t2.value; 15915 /* non-overlapping ranges */ 15916 if (umin1 > umax2 || umax1 < umin2) 15917 return 0; 15918 if (smin1 > smax2 || smax1 < smin2) 15919 return 0; 15920 if (!is_jmp32) { 15921 /* if 64-bit ranges are inconclusive, see if we can 15922 * utilize 32-bit subrange knowledge to eliminate 15923 * branches that can't be taken a priori 15924 */ 15925 if (reg1->u32_min_value > reg2->u32_max_value || 15926 reg1->u32_max_value < reg2->u32_min_value) 15927 return 0; 15928 if (reg1->s32_min_value > reg2->s32_max_value || 15929 reg1->s32_max_value < reg2->s32_min_value) 15930 return 0; 15931 } 15932 break; 15933 case BPF_JNE: 15934 /* constants, umin/umax and smin/smax checks would be 15935 * redundant in this case because they all should match 15936 */ 15937 if (tnum_is_const(t1) && tnum_is_const(t2)) 15938 return t1.value != t2.value; 15939 /* non-overlapping ranges */ 15940 if (umin1 > umax2 || umax1 < umin2) 15941 return 1; 15942 if (smin1 > smax2 || smax1 < smin2) 15943 return 1; 15944 if (!is_jmp32) { 15945 /* if 64-bit ranges are inconclusive, see if we can 15946 * utilize 32-bit subrange knowledge to eliminate 15947 * branches that can't be taken a priori 15948 */ 15949 if (reg1->u32_min_value > reg2->u32_max_value || 15950 reg1->u32_max_value < reg2->u32_min_value) 15951 return 1; 15952 if (reg1->s32_min_value > reg2->s32_max_value || 15953 reg1->s32_max_value < reg2->s32_min_value) 15954 return 1; 15955 } 15956 break; 15957 case BPF_JSET: 15958 if (!is_reg_const(reg2, is_jmp32)) { 15959 swap(reg1, reg2); 15960 swap(t1, t2); 15961 } 15962 if (!is_reg_const(reg2, is_jmp32)) 15963 return -1; 15964 if ((~t1.mask & t1.value) & t2.value) 15965 return 1; 15966 if (!((t1.mask | t1.value) & t2.value)) 15967 return 0; 15968 break; 15969 case BPF_JGT: 15970 if (umin1 > umax2) 15971 return 1; 15972 else if (umax1 <= umin2) 15973 return 0; 15974 break; 15975 case BPF_JSGT: 15976 if (smin1 > smax2) 15977 return 1; 15978 else if (smax1 <= smin2) 15979 return 0; 15980 break; 15981 case BPF_JLT: 15982 if (umax1 < umin2) 15983 return 1; 15984 else if (umin1 >= umax2) 15985 return 0; 15986 break; 15987 case BPF_JSLT: 15988 if (smax1 < smin2) 15989 return 1; 15990 else if (smin1 >= smax2) 15991 return 0; 15992 break; 15993 case BPF_JGE: 15994 if (umin1 >= umax2) 15995 return 1; 15996 else if (umax1 < umin2) 15997 return 0; 15998 break; 15999 case BPF_JSGE: 16000 if (smin1 >= smax2) 16001 return 1; 16002 else if (smax1 < smin2) 16003 return 0; 16004 break; 16005 case BPF_JLE: 16006 if (umax1 <= umin2) 16007 return 1; 16008 else if (umin1 > umax2) 16009 return 0; 16010 break; 16011 case BPF_JSLE: 16012 if (smax1 <= smin2) 16013 return 1; 16014 else if (smin1 > smax2) 16015 return 0; 16016 break; 16017 } 16018 16019 return -1; 16020 } 16021 16022 static int flip_opcode(u32 opcode) 16023 { 16024 /* How can we transform "a <op> b" into "b <op> a"? */ 16025 static const u8 opcode_flip[16] = { 16026 /* these stay the same */ 16027 [BPF_JEQ >> 4] = BPF_JEQ, 16028 [BPF_JNE >> 4] = BPF_JNE, 16029 [BPF_JSET >> 4] = BPF_JSET, 16030 /* these swap "lesser" and "greater" (L and G in the opcodes) */ 16031 [BPF_JGE >> 4] = BPF_JLE, 16032 [BPF_JGT >> 4] = BPF_JLT, 16033 [BPF_JLE >> 4] = BPF_JGE, 16034 [BPF_JLT >> 4] = BPF_JGT, 16035 [BPF_JSGE >> 4] = BPF_JSLE, 16036 [BPF_JSGT >> 4] = BPF_JSLT, 16037 [BPF_JSLE >> 4] = BPF_JSGE, 16038 [BPF_JSLT >> 4] = BPF_JSGT 16039 }; 16040 return opcode_flip[opcode >> 4]; 16041 } 16042 16043 static int is_pkt_ptr_branch_taken(struct bpf_reg_state *dst_reg, 16044 struct bpf_reg_state *src_reg, 16045 u8 opcode) 16046 { 16047 struct bpf_reg_state *pkt; 16048 16049 if (src_reg->type == PTR_TO_PACKET_END) { 16050 pkt = dst_reg; 16051 } else if (dst_reg->type == PTR_TO_PACKET_END) { 16052 pkt = src_reg; 16053 opcode = flip_opcode(opcode); 16054 } else { 16055 return -1; 16056 } 16057 16058 if (pkt->range >= 0) 16059 return -1; 16060 16061 switch (opcode) { 16062 case BPF_JLE: 16063 /* pkt <= pkt_end */ 16064 fallthrough; 16065 case BPF_JGT: 16066 /* pkt > pkt_end */ 16067 if (pkt->range == BEYOND_PKT_END) 16068 /* pkt has at last one extra byte beyond pkt_end */ 16069 return opcode == BPF_JGT; 16070 break; 16071 case BPF_JLT: 16072 /* pkt < pkt_end */ 16073 fallthrough; 16074 case BPF_JGE: 16075 /* pkt >= pkt_end */ 16076 if (pkt->range == BEYOND_PKT_END || pkt->range == AT_PKT_END) 16077 return opcode == BPF_JGE; 16078 break; 16079 } 16080 return -1; 16081 } 16082 16083 /* compute branch direction of the expression "if (<reg1> opcode <reg2>) goto target;" 16084 * and return: 16085 * 1 - branch will be taken and "goto target" will be executed 16086 * 0 - branch will not be taken and fall-through to next insn 16087 * -1 - unknown. Example: "if (reg1 < 5)" is unknown when register value 16088 * range [0,10] 16089 */ 16090 static int is_branch_taken(struct bpf_reg_state *reg1, struct bpf_reg_state *reg2, 16091 u8 opcode, bool is_jmp32) 16092 { 16093 if (reg_is_pkt_pointer_any(reg1) && reg_is_pkt_pointer_any(reg2) && !is_jmp32) 16094 return is_pkt_ptr_branch_taken(reg1, reg2, opcode); 16095 16096 if (__is_pointer_value(false, reg1) || __is_pointer_value(false, reg2)) { 16097 u64 val; 16098 16099 /* arrange that reg2 is a scalar, and reg1 is a pointer */ 16100 if (!is_reg_const(reg2, is_jmp32)) { 16101 opcode = flip_opcode(opcode); 16102 swap(reg1, reg2); 16103 } 16104 /* and ensure that reg2 is a constant */ 16105 if (!is_reg_const(reg2, is_jmp32)) 16106 return -1; 16107 16108 if (!reg_not_null(reg1)) 16109 return -1; 16110 16111 /* If pointer is valid tests against zero will fail so we can 16112 * use this to direct branch taken. 16113 */ 16114 val = reg_const_value(reg2, is_jmp32); 16115 if (val != 0) 16116 return -1; 16117 16118 switch (opcode) { 16119 case BPF_JEQ: 16120 return 0; 16121 case BPF_JNE: 16122 return 1; 16123 default: 16124 return -1; 16125 } 16126 } 16127 16128 /* now deal with two scalars, but not necessarily constants */ 16129 return is_scalar_branch_taken(reg1, reg2, opcode, is_jmp32); 16130 } 16131 16132 /* Opcode that corresponds to a *false* branch condition. 16133 * E.g., if r1 < r2, then reverse (false) condition is r1 >= r2 16134 */ 16135 static u8 rev_opcode(u8 opcode) 16136 { 16137 switch (opcode) { 16138 case BPF_JEQ: return BPF_JNE; 16139 case BPF_JNE: return BPF_JEQ; 16140 /* JSET doesn't have it's reverse opcode in BPF, so add 16141 * BPF_X flag to denote the reverse of that operation 16142 */ 16143 case BPF_JSET: return BPF_JSET | BPF_X; 16144 case BPF_JSET | BPF_X: return BPF_JSET; 16145 case BPF_JGE: return BPF_JLT; 16146 case BPF_JGT: return BPF_JLE; 16147 case BPF_JLE: return BPF_JGT; 16148 case BPF_JLT: return BPF_JGE; 16149 case BPF_JSGE: return BPF_JSLT; 16150 case BPF_JSGT: return BPF_JSLE; 16151 case BPF_JSLE: return BPF_JSGT; 16152 case BPF_JSLT: return BPF_JSGE; 16153 default: return 0; 16154 } 16155 } 16156 16157 /* Refine range knowledge for <reg1> <op> <reg>2 conditional operation. */ 16158 static void regs_refine_cond_op(struct bpf_reg_state *reg1, struct bpf_reg_state *reg2, 16159 u8 opcode, bool is_jmp32) 16160 { 16161 struct tnum t; 16162 u64 val; 16163 16164 /* In case of GE/GT/SGE/JST, reuse LE/LT/SLE/SLT logic from below */ 16165 switch (opcode) { 16166 case BPF_JGE: 16167 case BPF_JGT: 16168 case BPF_JSGE: 16169 case BPF_JSGT: 16170 opcode = flip_opcode(opcode); 16171 swap(reg1, reg2); 16172 break; 16173 default: 16174 break; 16175 } 16176 16177 switch (opcode) { 16178 case BPF_JEQ: 16179 if (is_jmp32) { 16180 reg1->u32_min_value = max(reg1->u32_min_value, reg2->u32_min_value); 16181 reg1->u32_max_value = min(reg1->u32_max_value, reg2->u32_max_value); 16182 reg1->s32_min_value = max(reg1->s32_min_value, reg2->s32_min_value); 16183 reg1->s32_max_value = min(reg1->s32_max_value, reg2->s32_max_value); 16184 reg2->u32_min_value = reg1->u32_min_value; 16185 reg2->u32_max_value = reg1->u32_max_value; 16186 reg2->s32_min_value = reg1->s32_min_value; 16187 reg2->s32_max_value = reg1->s32_max_value; 16188 16189 t = tnum_intersect(tnum_subreg(reg1->var_off), tnum_subreg(reg2->var_off)); 16190 reg1->var_off = tnum_with_subreg(reg1->var_off, t); 16191 reg2->var_off = tnum_with_subreg(reg2->var_off, t); 16192 } else { 16193 reg1->umin_value = max(reg1->umin_value, reg2->umin_value); 16194 reg1->umax_value = min(reg1->umax_value, reg2->umax_value); 16195 reg1->smin_value = max(reg1->smin_value, reg2->smin_value); 16196 reg1->smax_value = min(reg1->smax_value, reg2->smax_value); 16197 reg2->umin_value = reg1->umin_value; 16198 reg2->umax_value = reg1->umax_value; 16199 reg2->smin_value = reg1->smin_value; 16200 reg2->smax_value = reg1->smax_value; 16201 16202 reg1->var_off = tnum_intersect(reg1->var_off, reg2->var_off); 16203 reg2->var_off = reg1->var_off; 16204 } 16205 break; 16206 case BPF_JNE: 16207 if (!is_reg_const(reg2, is_jmp32)) 16208 swap(reg1, reg2); 16209 if (!is_reg_const(reg2, is_jmp32)) 16210 break; 16211 16212 /* try to recompute the bound of reg1 if reg2 is a const and 16213 * is exactly the edge of reg1. 16214 */ 16215 val = reg_const_value(reg2, is_jmp32); 16216 if (is_jmp32) { 16217 /* u32_min_value is not equal to 0xffffffff at this point, 16218 * because otherwise u32_max_value is 0xffffffff as well, 16219 * in such a case both reg1 and reg2 would be constants, 16220 * jump would be predicted and reg_set_min_max() won't 16221 * be called. 16222 * 16223 * Same reasoning works for all {u,s}{min,max}{32,64} cases 16224 * below. 16225 */ 16226 if (reg1->u32_min_value == (u32)val) 16227 reg1->u32_min_value++; 16228 if (reg1->u32_max_value == (u32)val) 16229 reg1->u32_max_value--; 16230 if (reg1->s32_min_value == (s32)val) 16231 reg1->s32_min_value++; 16232 if (reg1->s32_max_value == (s32)val) 16233 reg1->s32_max_value--; 16234 } else { 16235 if (reg1->umin_value == (u64)val) 16236 reg1->umin_value++; 16237 if (reg1->umax_value == (u64)val) 16238 reg1->umax_value--; 16239 if (reg1->smin_value == (s64)val) 16240 reg1->smin_value++; 16241 if (reg1->smax_value == (s64)val) 16242 reg1->smax_value--; 16243 } 16244 break; 16245 case BPF_JSET: 16246 if (!is_reg_const(reg2, is_jmp32)) 16247 swap(reg1, reg2); 16248 if (!is_reg_const(reg2, is_jmp32)) 16249 break; 16250 val = reg_const_value(reg2, is_jmp32); 16251 /* BPF_JSET (i.e., TRUE branch, *not* BPF_JSET | BPF_X) 16252 * requires single bit to learn something useful. E.g., if we 16253 * know that `r1 & 0x3` is true, then which bits (0, 1, or both) 16254 * are actually set? We can learn something definite only if 16255 * it's a single-bit value to begin with. 16256 * 16257 * BPF_JSET | BPF_X (i.e., negation of BPF_JSET) doesn't have 16258 * this restriction. I.e., !(r1 & 0x3) means neither bit 0 nor 16259 * bit 1 is set, which we can readily use in adjustments. 16260 */ 16261 if (!is_power_of_2(val)) 16262 break; 16263 if (is_jmp32) { 16264 t = tnum_or(tnum_subreg(reg1->var_off), tnum_const(val)); 16265 reg1->var_off = tnum_with_subreg(reg1->var_off, t); 16266 } else { 16267 reg1->var_off = tnum_or(reg1->var_off, tnum_const(val)); 16268 } 16269 break; 16270 case BPF_JSET | BPF_X: /* reverse of BPF_JSET, see rev_opcode() */ 16271 if (!is_reg_const(reg2, is_jmp32)) 16272 swap(reg1, reg2); 16273 if (!is_reg_const(reg2, is_jmp32)) 16274 break; 16275 val = reg_const_value(reg2, is_jmp32); 16276 /* Forget the ranges before narrowing tnums, to avoid invariant 16277 * violations if we're on a dead branch. 16278 */ 16279 __mark_reg_unbounded(reg1); 16280 if (is_jmp32) { 16281 t = tnum_and(tnum_subreg(reg1->var_off), tnum_const(~val)); 16282 reg1->var_off = tnum_with_subreg(reg1->var_off, t); 16283 } else { 16284 reg1->var_off = tnum_and(reg1->var_off, tnum_const(~val)); 16285 } 16286 break; 16287 case BPF_JLE: 16288 if (is_jmp32) { 16289 reg1->u32_max_value = min(reg1->u32_max_value, reg2->u32_max_value); 16290 reg2->u32_min_value = max(reg1->u32_min_value, reg2->u32_min_value); 16291 } else { 16292 reg1->umax_value = min(reg1->umax_value, reg2->umax_value); 16293 reg2->umin_value = max(reg1->umin_value, reg2->umin_value); 16294 } 16295 break; 16296 case BPF_JLT: 16297 if (is_jmp32) { 16298 reg1->u32_max_value = min(reg1->u32_max_value, reg2->u32_max_value - 1); 16299 reg2->u32_min_value = max(reg1->u32_min_value + 1, reg2->u32_min_value); 16300 } else { 16301 reg1->umax_value = min(reg1->umax_value, reg2->umax_value - 1); 16302 reg2->umin_value = max(reg1->umin_value + 1, reg2->umin_value); 16303 } 16304 break; 16305 case BPF_JSLE: 16306 if (is_jmp32) { 16307 reg1->s32_max_value = min(reg1->s32_max_value, reg2->s32_max_value); 16308 reg2->s32_min_value = max(reg1->s32_min_value, reg2->s32_min_value); 16309 } else { 16310 reg1->smax_value = min(reg1->smax_value, reg2->smax_value); 16311 reg2->smin_value = max(reg1->smin_value, reg2->smin_value); 16312 } 16313 break; 16314 case BPF_JSLT: 16315 if (is_jmp32) { 16316 reg1->s32_max_value = min(reg1->s32_max_value, reg2->s32_max_value - 1); 16317 reg2->s32_min_value = max(reg1->s32_min_value + 1, reg2->s32_min_value); 16318 } else { 16319 reg1->smax_value = min(reg1->smax_value, reg2->smax_value - 1); 16320 reg2->smin_value = max(reg1->smin_value + 1, reg2->smin_value); 16321 } 16322 break; 16323 default: 16324 return; 16325 } 16326 } 16327 16328 /* Adjusts the register min/max values in the case that the dst_reg and 16329 * src_reg are both SCALAR_VALUE registers (or we are simply doing a BPF_K 16330 * check, in which case we have a fake SCALAR_VALUE representing insn->imm). 16331 * Technically we can do similar adjustments for pointers to the same object, 16332 * but we don't support that right now. 16333 */ 16334 static int reg_set_min_max(struct bpf_verifier_env *env, 16335 struct bpf_reg_state *true_reg1, 16336 struct bpf_reg_state *true_reg2, 16337 struct bpf_reg_state *false_reg1, 16338 struct bpf_reg_state *false_reg2, 16339 u8 opcode, bool is_jmp32) 16340 { 16341 int err; 16342 16343 /* If either register is a pointer, we can't learn anything about its 16344 * variable offset from the compare (unless they were a pointer into 16345 * the same object, but we don't bother with that). 16346 */ 16347 if (false_reg1->type != SCALAR_VALUE || false_reg2->type != SCALAR_VALUE) 16348 return 0; 16349 16350 /* fallthrough (FALSE) branch */ 16351 regs_refine_cond_op(false_reg1, false_reg2, rev_opcode(opcode), is_jmp32); 16352 reg_bounds_sync(false_reg1); 16353 reg_bounds_sync(false_reg2); 16354 16355 /* jump (TRUE) branch */ 16356 regs_refine_cond_op(true_reg1, true_reg2, opcode, is_jmp32); 16357 reg_bounds_sync(true_reg1); 16358 reg_bounds_sync(true_reg2); 16359 16360 err = reg_bounds_sanity_check(env, true_reg1, "true_reg1"); 16361 err = err ?: reg_bounds_sanity_check(env, true_reg2, "true_reg2"); 16362 err = err ?: reg_bounds_sanity_check(env, false_reg1, "false_reg1"); 16363 err = err ?: reg_bounds_sanity_check(env, false_reg2, "false_reg2"); 16364 return err; 16365 } 16366 16367 static void mark_ptr_or_null_reg(struct bpf_func_state *state, 16368 struct bpf_reg_state *reg, u32 id, 16369 bool is_null) 16370 { 16371 if (type_may_be_null(reg->type) && reg->id == id && 16372 (is_rcu_reg(reg) || !WARN_ON_ONCE(!reg->id))) { 16373 /* Old offset (both fixed and variable parts) should have been 16374 * known-zero, because we don't allow pointer arithmetic on 16375 * pointers that might be NULL. If we see this happening, don't 16376 * convert the register. 16377 * 16378 * But in some cases, some helpers that return local kptrs 16379 * advance offset for the returned pointer. In those cases, it 16380 * is fine to expect to see reg->off. 16381 */ 16382 if (WARN_ON_ONCE(reg->smin_value || reg->smax_value || !tnum_equals_const(reg->var_off, 0))) 16383 return; 16384 if (!(type_is_ptr_alloc_obj(reg->type) || type_is_non_owning_ref(reg->type)) && 16385 WARN_ON_ONCE(reg->off)) 16386 return; 16387 16388 if (is_null) { 16389 reg->type = SCALAR_VALUE; 16390 /* We don't need id and ref_obj_id from this point 16391 * onwards anymore, thus we should better reset it, 16392 * so that state pruning has chances to take effect. 16393 */ 16394 reg->id = 0; 16395 reg->ref_obj_id = 0; 16396 16397 return; 16398 } 16399 16400 mark_ptr_not_null_reg(reg); 16401 16402 if (!reg_may_point_to_spin_lock(reg)) { 16403 /* For not-NULL ptr, reg->ref_obj_id will be reset 16404 * in release_reference(). 16405 * 16406 * reg->id is still used by spin_lock ptr. Other 16407 * than spin_lock ptr type, reg->id can be reset. 16408 */ 16409 reg->id = 0; 16410 } 16411 } 16412 } 16413 16414 /* The logic is similar to find_good_pkt_pointers(), both could eventually 16415 * be folded together at some point. 16416 */ 16417 static void mark_ptr_or_null_regs(struct bpf_verifier_state *vstate, u32 regno, 16418 bool is_null) 16419 { 16420 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 16421 struct bpf_reg_state *regs = state->regs, *reg; 16422 u32 ref_obj_id = regs[regno].ref_obj_id; 16423 u32 id = regs[regno].id; 16424 16425 if (ref_obj_id && ref_obj_id == id && is_null) 16426 /* regs[regno] is in the " == NULL" branch. 16427 * No one could have freed the reference state before 16428 * doing the NULL check. 16429 */ 16430 WARN_ON_ONCE(release_reference_nomark(vstate, id)); 16431 16432 bpf_for_each_reg_in_vstate(vstate, state, reg, ({ 16433 mark_ptr_or_null_reg(state, reg, id, is_null); 16434 })); 16435 } 16436 16437 static bool try_match_pkt_pointers(const struct bpf_insn *insn, 16438 struct bpf_reg_state *dst_reg, 16439 struct bpf_reg_state *src_reg, 16440 struct bpf_verifier_state *this_branch, 16441 struct bpf_verifier_state *other_branch) 16442 { 16443 if (BPF_SRC(insn->code) != BPF_X) 16444 return false; 16445 16446 /* Pointers are always 64-bit. */ 16447 if (BPF_CLASS(insn->code) == BPF_JMP32) 16448 return false; 16449 16450 switch (BPF_OP(insn->code)) { 16451 case BPF_JGT: 16452 if ((dst_reg->type == PTR_TO_PACKET && 16453 src_reg->type == PTR_TO_PACKET_END) || 16454 (dst_reg->type == PTR_TO_PACKET_META && 16455 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) { 16456 /* pkt_data' > pkt_end, pkt_meta' > pkt_data */ 16457 find_good_pkt_pointers(this_branch, dst_reg, 16458 dst_reg->type, false); 16459 mark_pkt_end(other_branch, insn->dst_reg, true); 16460 } else if ((dst_reg->type == PTR_TO_PACKET_END && 16461 src_reg->type == PTR_TO_PACKET) || 16462 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) && 16463 src_reg->type == PTR_TO_PACKET_META)) { 16464 /* pkt_end > pkt_data', pkt_data > pkt_meta' */ 16465 find_good_pkt_pointers(other_branch, src_reg, 16466 src_reg->type, true); 16467 mark_pkt_end(this_branch, insn->src_reg, false); 16468 } else { 16469 return false; 16470 } 16471 break; 16472 case BPF_JLT: 16473 if ((dst_reg->type == PTR_TO_PACKET && 16474 src_reg->type == PTR_TO_PACKET_END) || 16475 (dst_reg->type == PTR_TO_PACKET_META && 16476 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) { 16477 /* pkt_data' < pkt_end, pkt_meta' < pkt_data */ 16478 find_good_pkt_pointers(other_branch, dst_reg, 16479 dst_reg->type, true); 16480 mark_pkt_end(this_branch, insn->dst_reg, false); 16481 } else if ((dst_reg->type == PTR_TO_PACKET_END && 16482 src_reg->type == PTR_TO_PACKET) || 16483 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) && 16484 src_reg->type == PTR_TO_PACKET_META)) { 16485 /* pkt_end < pkt_data', pkt_data > pkt_meta' */ 16486 find_good_pkt_pointers(this_branch, src_reg, 16487 src_reg->type, false); 16488 mark_pkt_end(other_branch, insn->src_reg, true); 16489 } else { 16490 return false; 16491 } 16492 break; 16493 case BPF_JGE: 16494 if ((dst_reg->type == PTR_TO_PACKET && 16495 src_reg->type == PTR_TO_PACKET_END) || 16496 (dst_reg->type == PTR_TO_PACKET_META && 16497 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) { 16498 /* pkt_data' >= pkt_end, pkt_meta' >= pkt_data */ 16499 find_good_pkt_pointers(this_branch, dst_reg, 16500 dst_reg->type, true); 16501 mark_pkt_end(other_branch, insn->dst_reg, false); 16502 } else if ((dst_reg->type == PTR_TO_PACKET_END && 16503 src_reg->type == PTR_TO_PACKET) || 16504 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) && 16505 src_reg->type == PTR_TO_PACKET_META)) { 16506 /* pkt_end >= pkt_data', pkt_data >= pkt_meta' */ 16507 find_good_pkt_pointers(other_branch, src_reg, 16508 src_reg->type, false); 16509 mark_pkt_end(this_branch, insn->src_reg, true); 16510 } else { 16511 return false; 16512 } 16513 break; 16514 case BPF_JLE: 16515 if ((dst_reg->type == PTR_TO_PACKET && 16516 src_reg->type == PTR_TO_PACKET_END) || 16517 (dst_reg->type == PTR_TO_PACKET_META && 16518 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) { 16519 /* pkt_data' <= pkt_end, pkt_meta' <= pkt_data */ 16520 find_good_pkt_pointers(other_branch, dst_reg, 16521 dst_reg->type, false); 16522 mark_pkt_end(this_branch, insn->dst_reg, true); 16523 } else if ((dst_reg->type == PTR_TO_PACKET_END && 16524 src_reg->type == PTR_TO_PACKET) || 16525 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) && 16526 src_reg->type == PTR_TO_PACKET_META)) { 16527 /* pkt_end <= pkt_data', pkt_data <= pkt_meta' */ 16528 find_good_pkt_pointers(this_branch, src_reg, 16529 src_reg->type, true); 16530 mark_pkt_end(other_branch, insn->src_reg, false); 16531 } else { 16532 return false; 16533 } 16534 break; 16535 default: 16536 return false; 16537 } 16538 16539 return true; 16540 } 16541 16542 static void __collect_linked_regs(struct linked_regs *reg_set, struct bpf_reg_state *reg, 16543 u32 id, u32 frameno, u32 spi_or_reg, bool is_reg) 16544 { 16545 struct linked_reg *e; 16546 16547 if (reg->type != SCALAR_VALUE || (reg->id & ~BPF_ADD_CONST) != id) 16548 return; 16549 16550 e = linked_regs_push(reg_set); 16551 if (e) { 16552 e->frameno = frameno; 16553 e->is_reg = is_reg; 16554 e->regno = spi_or_reg; 16555 } else { 16556 reg->id = 0; 16557 } 16558 } 16559 16560 /* For all R being scalar registers or spilled scalar registers 16561 * in verifier state, save R in linked_regs if R->id == id. 16562 * If there are too many Rs sharing same id, reset id for leftover Rs. 16563 */ 16564 static void collect_linked_regs(struct bpf_verifier_state *vstate, u32 id, 16565 struct linked_regs *linked_regs) 16566 { 16567 struct bpf_func_state *func; 16568 struct bpf_reg_state *reg; 16569 int i, j; 16570 16571 id = id & ~BPF_ADD_CONST; 16572 for (i = vstate->curframe; i >= 0; i--) { 16573 func = vstate->frame[i]; 16574 for (j = 0; j < BPF_REG_FP; j++) { 16575 reg = &func->regs[j]; 16576 __collect_linked_regs(linked_regs, reg, id, i, j, true); 16577 } 16578 for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) { 16579 if (!is_spilled_reg(&func->stack[j])) 16580 continue; 16581 reg = &func->stack[j].spilled_ptr; 16582 __collect_linked_regs(linked_regs, reg, id, i, j, false); 16583 } 16584 } 16585 } 16586 16587 /* For all R in linked_regs, copy known_reg range into R 16588 * if R->id == known_reg->id. 16589 */ 16590 static void sync_linked_regs(struct bpf_verifier_state *vstate, struct bpf_reg_state *known_reg, 16591 struct linked_regs *linked_regs) 16592 { 16593 struct bpf_reg_state fake_reg; 16594 struct bpf_reg_state *reg; 16595 struct linked_reg *e; 16596 int i; 16597 16598 for (i = 0; i < linked_regs->cnt; ++i) { 16599 e = &linked_regs->entries[i]; 16600 reg = e->is_reg ? &vstate->frame[e->frameno]->regs[e->regno] 16601 : &vstate->frame[e->frameno]->stack[e->spi].spilled_ptr; 16602 if (reg->type != SCALAR_VALUE || reg == known_reg) 16603 continue; 16604 if ((reg->id & ~BPF_ADD_CONST) != (known_reg->id & ~BPF_ADD_CONST)) 16605 continue; 16606 if ((!(reg->id & BPF_ADD_CONST) && !(known_reg->id & BPF_ADD_CONST)) || 16607 reg->off == known_reg->off) { 16608 s32 saved_subreg_def = reg->subreg_def; 16609 16610 copy_register_state(reg, known_reg); 16611 reg->subreg_def = saved_subreg_def; 16612 } else { 16613 s32 saved_subreg_def = reg->subreg_def; 16614 s32 saved_off = reg->off; 16615 16616 fake_reg.type = SCALAR_VALUE; 16617 __mark_reg_known(&fake_reg, (s32)reg->off - (s32)known_reg->off); 16618 16619 /* reg = known_reg; reg += delta */ 16620 copy_register_state(reg, known_reg); 16621 /* 16622 * Must preserve off, id and add_const flag, 16623 * otherwise another sync_linked_regs() will be incorrect. 16624 */ 16625 reg->off = saved_off; 16626 reg->subreg_def = saved_subreg_def; 16627 16628 scalar32_min_max_add(reg, &fake_reg); 16629 scalar_min_max_add(reg, &fake_reg); 16630 reg->var_off = tnum_add(reg->var_off, fake_reg.var_off); 16631 } 16632 } 16633 } 16634 16635 static int check_cond_jmp_op(struct bpf_verifier_env *env, 16636 struct bpf_insn *insn, int *insn_idx) 16637 { 16638 struct bpf_verifier_state *this_branch = env->cur_state; 16639 struct bpf_verifier_state *other_branch; 16640 struct bpf_reg_state *regs = this_branch->frame[this_branch->curframe]->regs; 16641 struct bpf_reg_state *dst_reg, *other_branch_regs, *src_reg = NULL; 16642 struct bpf_reg_state *eq_branch_regs; 16643 struct linked_regs linked_regs = {}; 16644 u8 opcode = BPF_OP(insn->code); 16645 int insn_flags = 0; 16646 bool is_jmp32; 16647 int pred = -1; 16648 int err; 16649 16650 /* Only conditional jumps are expected to reach here. */ 16651 if (opcode == BPF_JA || opcode > BPF_JCOND) { 16652 verbose(env, "invalid BPF_JMP/JMP32 opcode %x\n", opcode); 16653 return -EINVAL; 16654 } 16655 16656 if (opcode == BPF_JCOND) { 16657 struct bpf_verifier_state *cur_st = env->cur_state, *queued_st, *prev_st; 16658 int idx = *insn_idx; 16659 16660 if (insn->code != (BPF_JMP | BPF_JCOND) || 16661 insn->src_reg != BPF_MAY_GOTO || 16662 insn->dst_reg || insn->imm) { 16663 verbose(env, "invalid may_goto imm %d\n", insn->imm); 16664 return -EINVAL; 16665 } 16666 prev_st = find_prev_entry(env, cur_st->parent, idx); 16667 16668 /* branch out 'fallthrough' insn as a new state to explore */ 16669 queued_st = push_stack(env, idx + 1, idx, false); 16670 if (!queued_st) 16671 return -ENOMEM; 16672 16673 queued_st->may_goto_depth++; 16674 if (prev_st) 16675 widen_imprecise_scalars(env, prev_st, queued_st); 16676 *insn_idx += insn->off; 16677 return 0; 16678 } 16679 16680 /* check src2 operand */ 16681 err = check_reg_arg(env, insn->dst_reg, SRC_OP); 16682 if (err) 16683 return err; 16684 16685 dst_reg = ®s[insn->dst_reg]; 16686 if (BPF_SRC(insn->code) == BPF_X) { 16687 if (insn->imm != 0) { 16688 verbose(env, "BPF_JMP/JMP32 uses reserved fields\n"); 16689 return -EINVAL; 16690 } 16691 16692 /* check src1 operand */ 16693 err = check_reg_arg(env, insn->src_reg, SRC_OP); 16694 if (err) 16695 return err; 16696 16697 src_reg = ®s[insn->src_reg]; 16698 if (!(reg_is_pkt_pointer_any(dst_reg) && reg_is_pkt_pointer_any(src_reg)) && 16699 is_pointer_value(env, insn->src_reg)) { 16700 verbose(env, "R%d pointer comparison prohibited\n", 16701 insn->src_reg); 16702 return -EACCES; 16703 } 16704 16705 if (src_reg->type == PTR_TO_STACK) 16706 insn_flags |= INSN_F_SRC_REG_STACK; 16707 if (dst_reg->type == PTR_TO_STACK) 16708 insn_flags |= INSN_F_DST_REG_STACK; 16709 } else { 16710 if (insn->src_reg != BPF_REG_0) { 16711 verbose(env, "BPF_JMP/JMP32 uses reserved fields\n"); 16712 return -EINVAL; 16713 } 16714 src_reg = &env->fake_reg[0]; 16715 memset(src_reg, 0, sizeof(*src_reg)); 16716 src_reg->type = SCALAR_VALUE; 16717 __mark_reg_known(src_reg, insn->imm); 16718 16719 if (dst_reg->type == PTR_TO_STACK) 16720 insn_flags |= INSN_F_DST_REG_STACK; 16721 } 16722 16723 if (insn_flags) { 16724 err = push_jmp_history(env, this_branch, insn_flags, 0); 16725 if (err) 16726 return err; 16727 } 16728 16729 is_jmp32 = BPF_CLASS(insn->code) == BPF_JMP32; 16730 pred = is_branch_taken(dst_reg, src_reg, opcode, is_jmp32); 16731 if (pred >= 0) { 16732 /* If we get here with a dst_reg pointer type it is because 16733 * above is_branch_taken() special cased the 0 comparison. 16734 */ 16735 if (!__is_pointer_value(false, dst_reg)) 16736 err = mark_chain_precision(env, insn->dst_reg); 16737 if (BPF_SRC(insn->code) == BPF_X && !err && 16738 !__is_pointer_value(false, src_reg)) 16739 err = mark_chain_precision(env, insn->src_reg); 16740 if (err) 16741 return err; 16742 } 16743 16744 if (pred == 1) { 16745 /* Only follow the goto, ignore fall-through. If needed, push 16746 * the fall-through branch for simulation under speculative 16747 * execution. 16748 */ 16749 if (!env->bypass_spec_v1 && 16750 !sanitize_speculative_path(env, insn, *insn_idx + 1, 16751 *insn_idx)) 16752 return -EFAULT; 16753 if (env->log.level & BPF_LOG_LEVEL) 16754 print_insn_state(env, this_branch, this_branch->curframe); 16755 *insn_idx += insn->off; 16756 return 0; 16757 } else if (pred == 0) { 16758 /* Only follow the fall-through branch, since that's where the 16759 * program will go. If needed, push the goto branch for 16760 * simulation under speculative execution. 16761 */ 16762 if (!env->bypass_spec_v1 && 16763 !sanitize_speculative_path(env, insn, 16764 *insn_idx + insn->off + 1, 16765 *insn_idx)) 16766 return -EFAULT; 16767 if (env->log.level & BPF_LOG_LEVEL) 16768 print_insn_state(env, this_branch, this_branch->curframe); 16769 return 0; 16770 } 16771 16772 /* Push scalar registers sharing same ID to jump history, 16773 * do this before creating 'other_branch', so that both 16774 * 'this_branch' and 'other_branch' share this history 16775 * if parent state is created. 16776 */ 16777 if (BPF_SRC(insn->code) == BPF_X && src_reg->type == SCALAR_VALUE && src_reg->id) 16778 collect_linked_regs(this_branch, src_reg->id, &linked_regs); 16779 if (dst_reg->type == SCALAR_VALUE && dst_reg->id) 16780 collect_linked_regs(this_branch, dst_reg->id, &linked_regs); 16781 if (linked_regs.cnt > 1) { 16782 err = push_jmp_history(env, this_branch, 0, linked_regs_pack(&linked_regs)); 16783 if (err) 16784 return err; 16785 } 16786 16787 other_branch = push_stack(env, *insn_idx + insn->off + 1, *insn_idx, 16788 false); 16789 if (!other_branch) 16790 return -EFAULT; 16791 other_branch_regs = other_branch->frame[other_branch->curframe]->regs; 16792 16793 if (BPF_SRC(insn->code) == BPF_X) { 16794 err = reg_set_min_max(env, 16795 &other_branch_regs[insn->dst_reg], 16796 &other_branch_regs[insn->src_reg], 16797 dst_reg, src_reg, opcode, is_jmp32); 16798 } else /* BPF_SRC(insn->code) == BPF_K */ { 16799 /* reg_set_min_max() can mangle the fake_reg. Make a copy 16800 * so that these are two different memory locations. The 16801 * src_reg is not used beyond here in context of K. 16802 */ 16803 memcpy(&env->fake_reg[1], &env->fake_reg[0], 16804 sizeof(env->fake_reg[0])); 16805 err = reg_set_min_max(env, 16806 &other_branch_regs[insn->dst_reg], 16807 &env->fake_reg[0], 16808 dst_reg, &env->fake_reg[1], 16809 opcode, is_jmp32); 16810 } 16811 if (err) 16812 return err; 16813 16814 if (BPF_SRC(insn->code) == BPF_X && 16815 src_reg->type == SCALAR_VALUE && src_reg->id && 16816 !WARN_ON_ONCE(src_reg->id != other_branch_regs[insn->src_reg].id)) { 16817 sync_linked_regs(this_branch, src_reg, &linked_regs); 16818 sync_linked_regs(other_branch, &other_branch_regs[insn->src_reg], &linked_regs); 16819 } 16820 if (dst_reg->type == SCALAR_VALUE && dst_reg->id && 16821 !WARN_ON_ONCE(dst_reg->id != other_branch_regs[insn->dst_reg].id)) { 16822 sync_linked_regs(this_branch, dst_reg, &linked_regs); 16823 sync_linked_regs(other_branch, &other_branch_regs[insn->dst_reg], &linked_regs); 16824 } 16825 16826 /* if one pointer register is compared to another pointer 16827 * register check if PTR_MAYBE_NULL could be lifted. 16828 * E.g. register A - maybe null 16829 * register B - not null 16830 * for JNE A, B, ... - A is not null in the false branch; 16831 * for JEQ A, B, ... - A is not null in the true branch. 16832 * 16833 * Since PTR_TO_BTF_ID points to a kernel struct that does 16834 * not need to be null checked by the BPF program, i.e., 16835 * could be null even without PTR_MAYBE_NULL marking, so 16836 * only propagate nullness when neither reg is that type. 16837 */ 16838 if (!is_jmp32 && BPF_SRC(insn->code) == BPF_X && 16839 __is_pointer_value(false, src_reg) && __is_pointer_value(false, dst_reg) && 16840 type_may_be_null(src_reg->type) != type_may_be_null(dst_reg->type) && 16841 base_type(src_reg->type) != PTR_TO_BTF_ID && 16842 base_type(dst_reg->type) != PTR_TO_BTF_ID) { 16843 eq_branch_regs = NULL; 16844 switch (opcode) { 16845 case BPF_JEQ: 16846 eq_branch_regs = other_branch_regs; 16847 break; 16848 case BPF_JNE: 16849 eq_branch_regs = regs; 16850 break; 16851 default: 16852 /* do nothing */ 16853 break; 16854 } 16855 if (eq_branch_regs) { 16856 if (type_may_be_null(src_reg->type)) 16857 mark_ptr_not_null_reg(&eq_branch_regs[insn->src_reg]); 16858 else 16859 mark_ptr_not_null_reg(&eq_branch_regs[insn->dst_reg]); 16860 } 16861 } 16862 16863 /* detect if R == 0 where R is returned from bpf_map_lookup_elem(). 16864 * NOTE: these optimizations below are related with pointer comparison 16865 * which will never be JMP32. 16866 */ 16867 if (!is_jmp32 && BPF_SRC(insn->code) == BPF_K && 16868 insn->imm == 0 && (opcode == BPF_JEQ || opcode == BPF_JNE) && 16869 type_may_be_null(dst_reg->type)) { 16870 /* Mark all identical registers in each branch as either 16871 * safe or unknown depending R == 0 or R != 0 conditional. 16872 */ 16873 mark_ptr_or_null_regs(this_branch, insn->dst_reg, 16874 opcode == BPF_JNE); 16875 mark_ptr_or_null_regs(other_branch, insn->dst_reg, 16876 opcode == BPF_JEQ); 16877 } else if (!try_match_pkt_pointers(insn, dst_reg, ®s[insn->src_reg], 16878 this_branch, other_branch) && 16879 is_pointer_value(env, insn->dst_reg)) { 16880 verbose(env, "R%d pointer comparison prohibited\n", 16881 insn->dst_reg); 16882 return -EACCES; 16883 } 16884 if (env->log.level & BPF_LOG_LEVEL) 16885 print_insn_state(env, this_branch, this_branch->curframe); 16886 return 0; 16887 } 16888 16889 /* verify BPF_LD_IMM64 instruction */ 16890 static int check_ld_imm(struct bpf_verifier_env *env, struct bpf_insn *insn) 16891 { 16892 struct bpf_insn_aux_data *aux = cur_aux(env); 16893 struct bpf_reg_state *regs = cur_regs(env); 16894 struct bpf_reg_state *dst_reg; 16895 struct bpf_map *map; 16896 int err; 16897 16898 if (BPF_SIZE(insn->code) != BPF_DW) { 16899 verbose(env, "invalid BPF_LD_IMM insn\n"); 16900 return -EINVAL; 16901 } 16902 if (insn->off != 0) { 16903 verbose(env, "BPF_LD_IMM64 uses reserved fields\n"); 16904 return -EINVAL; 16905 } 16906 16907 err = check_reg_arg(env, insn->dst_reg, DST_OP); 16908 if (err) 16909 return err; 16910 16911 dst_reg = ®s[insn->dst_reg]; 16912 if (insn->src_reg == 0) { 16913 u64 imm = ((u64)(insn + 1)->imm << 32) | (u32)insn->imm; 16914 16915 dst_reg->type = SCALAR_VALUE; 16916 __mark_reg_known(®s[insn->dst_reg], imm); 16917 return 0; 16918 } 16919 16920 /* All special src_reg cases are listed below. From this point onwards 16921 * we either succeed and assign a corresponding dst_reg->type after 16922 * zeroing the offset, or fail and reject the program. 16923 */ 16924 mark_reg_known_zero(env, regs, insn->dst_reg); 16925 16926 if (insn->src_reg == BPF_PSEUDO_BTF_ID) { 16927 dst_reg->type = aux->btf_var.reg_type; 16928 switch (base_type(dst_reg->type)) { 16929 case PTR_TO_MEM: 16930 dst_reg->mem_size = aux->btf_var.mem_size; 16931 break; 16932 case PTR_TO_BTF_ID: 16933 dst_reg->btf = aux->btf_var.btf; 16934 dst_reg->btf_id = aux->btf_var.btf_id; 16935 break; 16936 default: 16937 verifier_bug(env, "pseudo btf id: unexpected dst reg type"); 16938 return -EFAULT; 16939 } 16940 return 0; 16941 } 16942 16943 if (insn->src_reg == BPF_PSEUDO_FUNC) { 16944 struct bpf_prog_aux *aux = env->prog->aux; 16945 u32 subprogno = find_subprog(env, 16946 env->insn_idx + insn->imm + 1); 16947 16948 if (!aux->func_info) { 16949 verbose(env, "missing btf func_info\n"); 16950 return -EINVAL; 16951 } 16952 if (aux->func_info_aux[subprogno].linkage != BTF_FUNC_STATIC) { 16953 verbose(env, "callback function not static\n"); 16954 return -EINVAL; 16955 } 16956 16957 dst_reg->type = PTR_TO_FUNC; 16958 dst_reg->subprogno = subprogno; 16959 return 0; 16960 } 16961 16962 map = env->used_maps[aux->map_index]; 16963 dst_reg->map_ptr = map; 16964 16965 if (insn->src_reg == BPF_PSEUDO_MAP_VALUE || 16966 insn->src_reg == BPF_PSEUDO_MAP_IDX_VALUE) { 16967 if (map->map_type == BPF_MAP_TYPE_ARENA) { 16968 __mark_reg_unknown(env, dst_reg); 16969 return 0; 16970 } 16971 dst_reg->type = PTR_TO_MAP_VALUE; 16972 dst_reg->off = aux->map_off; 16973 WARN_ON_ONCE(map->max_entries != 1); 16974 /* We want reg->id to be same (0) as map_value is not distinct */ 16975 } else if (insn->src_reg == BPF_PSEUDO_MAP_FD || 16976 insn->src_reg == BPF_PSEUDO_MAP_IDX) { 16977 dst_reg->type = CONST_PTR_TO_MAP; 16978 } else { 16979 verifier_bug(env, "unexpected src reg value for ldimm64"); 16980 return -EFAULT; 16981 } 16982 16983 return 0; 16984 } 16985 16986 static bool may_access_skb(enum bpf_prog_type type) 16987 { 16988 switch (type) { 16989 case BPF_PROG_TYPE_SOCKET_FILTER: 16990 case BPF_PROG_TYPE_SCHED_CLS: 16991 case BPF_PROG_TYPE_SCHED_ACT: 16992 return true; 16993 default: 16994 return false; 16995 } 16996 } 16997 16998 /* verify safety of LD_ABS|LD_IND instructions: 16999 * - they can only appear in the programs where ctx == skb 17000 * - since they are wrappers of function calls, they scratch R1-R5 registers, 17001 * preserve R6-R9, and store return value into R0 17002 * 17003 * Implicit input: 17004 * ctx == skb == R6 == CTX 17005 * 17006 * Explicit input: 17007 * SRC == any register 17008 * IMM == 32-bit immediate 17009 * 17010 * Output: 17011 * R0 - 8/16/32-bit skb data converted to cpu endianness 17012 */ 17013 static int check_ld_abs(struct bpf_verifier_env *env, struct bpf_insn *insn) 17014 { 17015 struct bpf_reg_state *regs = cur_regs(env); 17016 static const int ctx_reg = BPF_REG_6; 17017 u8 mode = BPF_MODE(insn->code); 17018 int i, err; 17019 17020 if (!may_access_skb(resolve_prog_type(env->prog))) { 17021 verbose(env, "BPF_LD_[ABS|IND] instructions not allowed for this program type\n"); 17022 return -EINVAL; 17023 } 17024 17025 if (!env->ops->gen_ld_abs) { 17026 verifier_bug(env, "gen_ld_abs is null"); 17027 return -EFAULT; 17028 } 17029 17030 if (insn->dst_reg != BPF_REG_0 || insn->off != 0 || 17031 BPF_SIZE(insn->code) == BPF_DW || 17032 (mode == BPF_ABS && insn->src_reg != BPF_REG_0)) { 17033 verbose(env, "BPF_LD_[ABS|IND] uses reserved fields\n"); 17034 return -EINVAL; 17035 } 17036 17037 /* check whether implicit source operand (register R6) is readable */ 17038 err = check_reg_arg(env, ctx_reg, SRC_OP); 17039 if (err) 17040 return err; 17041 17042 /* Disallow usage of BPF_LD_[ABS|IND] with reference tracking, as 17043 * gen_ld_abs() may terminate the program at runtime, leading to 17044 * reference leak. 17045 */ 17046 err = check_resource_leak(env, false, true, "BPF_LD_[ABS|IND]"); 17047 if (err) 17048 return err; 17049 17050 if (regs[ctx_reg].type != PTR_TO_CTX) { 17051 verbose(env, 17052 "at the time of BPF_LD_ABS|IND R6 != pointer to skb\n"); 17053 return -EINVAL; 17054 } 17055 17056 if (mode == BPF_IND) { 17057 /* check explicit source operand */ 17058 err = check_reg_arg(env, insn->src_reg, SRC_OP); 17059 if (err) 17060 return err; 17061 } 17062 17063 err = check_ptr_off_reg(env, ®s[ctx_reg], ctx_reg); 17064 if (err < 0) 17065 return err; 17066 17067 /* reset caller saved regs to unreadable */ 17068 for (i = 0; i < CALLER_SAVED_REGS; i++) { 17069 mark_reg_not_init(env, regs, caller_saved[i]); 17070 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK); 17071 } 17072 17073 /* mark destination R0 register as readable, since it contains 17074 * the value fetched from the packet. 17075 * Already marked as written above. 17076 */ 17077 mark_reg_unknown(env, regs, BPF_REG_0); 17078 /* ld_abs load up to 32-bit skb data. */ 17079 regs[BPF_REG_0].subreg_def = env->insn_idx + 1; 17080 return 0; 17081 } 17082 17083 static int check_return_code(struct bpf_verifier_env *env, int regno, const char *reg_name) 17084 { 17085 const char *exit_ctx = "At program exit"; 17086 struct tnum enforce_attach_type_range = tnum_unknown; 17087 const struct bpf_prog *prog = env->prog; 17088 struct bpf_reg_state *reg = reg_state(env, regno); 17089 struct bpf_retval_range range = retval_range(0, 1); 17090 enum bpf_prog_type prog_type = resolve_prog_type(env->prog); 17091 int err; 17092 struct bpf_func_state *frame = env->cur_state->frame[0]; 17093 const bool is_subprog = frame->subprogno; 17094 bool return_32bit = false; 17095 const struct btf_type *reg_type, *ret_type = NULL; 17096 17097 /* LSM and struct_ops func-ptr's return type could be "void" */ 17098 if (!is_subprog || frame->in_exception_callback_fn) { 17099 switch (prog_type) { 17100 case BPF_PROG_TYPE_LSM: 17101 if (prog->expected_attach_type == BPF_LSM_CGROUP) 17102 /* See below, can be 0 or 0-1 depending on hook. */ 17103 break; 17104 if (!prog->aux->attach_func_proto->type) 17105 return 0; 17106 break; 17107 case BPF_PROG_TYPE_STRUCT_OPS: 17108 if (!prog->aux->attach_func_proto->type) 17109 return 0; 17110 17111 if (frame->in_exception_callback_fn) 17112 break; 17113 17114 /* Allow a struct_ops program to return a referenced kptr if it 17115 * matches the operator's return type and is in its unmodified 17116 * form. A scalar zero (i.e., a null pointer) is also allowed. 17117 */ 17118 reg_type = reg->btf ? btf_type_by_id(reg->btf, reg->btf_id) : NULL; 17119 ret_type = btf_type_resolve_ptr(prog->aux->attach_btf, 17120 prog->aux->attach_func_proto->type, 17121 NULL); 17122 if (ret_type && ret_type == reg_type && reg->ref_obj_id) 17123 return __check_ptr_off_reg(env, reg, regno, false); 17124 break; 17125 default: 17126 break; 17127 } 17128 } 17129 17130 /* eBPF calling convention is such that R0 is used 17131 * to return the value from eBPF program. 17132 * Make sure that it's readable at this time 17133 * of bpf_exit, which means that program wrote 17134 * something into it earlier 17135 */ 17136 err = check_reg_arg(env, regno, SRC_OP); 17137 if (err) 17138 return err; 17139 17140 if (is_pointer_value(env, regno)) { 17141 verbose(env, "R%d leaks addr as return value\n", regno); 17142 return -EACCES; 17143 } 17144 17145 if (frame->in_async_callback_fn) { 17146 /* enforce return zero from async callbacks like timer */ 17147 exit_ctx = "At async callback return"; 17148 range = retval_range(0, 0); 17149 goto enforce_retval; 17150 } 17151 17152 if (is_subprog && !frame->in_exception_callback_fn) { 17153 if (reg->type != SCALAR_VALUE) { 17154 verbose(env, "At subprogram exit the register R%d is not a scalar value (%s)\n", 17155 regno, reg_type_str(env, reg->type)); 17156 return -EINVAL; 17157 } 17158 return 0; 17159 } 17160 17161 switch (prog_type) { 17162 case BPF_PROG_TYPE_CGROUP_SOCK_ADDR: 17163 if (env->prog->expected_attach_type == BPF_CGROUP_UDP4_RECVMSG || 17164 env->prog->expected_attach_type == BPF_CGROUP_UDP6_RECVMSG || 17165 env->prog->expected_attach_type == BPF_CGROUP_UNIX_RECVMSG || 17166 env->prog->expected_attach_type == BPF_CGROUP_INET4_GETPEERNAME || 17167 env->prog->expected_attach_type == BPF_CGROUP_INET6_GETPEERNAME || 17168 env->prog->expected_attach_type == BPF_CGROUP_UNIX_GETPEERNAME || 17169 env->prog->expected_attach_type == BPF_CGROUP_INET4_GETSOCKNAME || 17170 env->prog->expected_attach_type == BPF_CGROUP_INET6_GETSOCKNAME || 17171 env->prog->expected_attach_type == BPF_CGROUP_UNIX_GETSOCKNAME) 17172 range = retval_range(1, 1); 17173 if (env->prog->expected_attach_type == BPF_CGROUP_INET4_BIND || 17174 env->prog->expected_attach_type == BPF_CGROUP_INET6_BIND) 17175 range = retval_range(0, 3); 17176 break; 17177 case BPF_PROG_TYPE_CGROUP_SKB: 17178 if (env->prog->expected_attach_type == BPF_CGROUP_INET_EGRESS) { 17179 range = retval_range(0, 3); 17180 enforce_attach_type_range = tnum_range(2, 3); 17181 } 17182 break; 17183 case BPF_PROG_TYPE_CGROUP_SOCK: 17184 case BPF_PROG_TYPE_SOCK_OPS: 17185 case BPF_PROG_TYPE_CGROUP_DEVICE: 17186 case BPF_PROG_TYPE_CGROUP_SYSCTL: 17187 case BPF_PROG_TYPE_CGROUP_SOCKOPT: 17188 break; 17189 case BPF_PROG_TYPE_RAW_TRACEPOINT: 17190 if (!env->prog->aux->attach_btf_id) 17191 return 0; 17192 range = retval_range(0, 0); 17193 break; 17194 case BPF_PROG_TYPE_TRACING: 17195 switch (env->prog->expected_attach_type) { 17196 case BPF_TRACE_FENTRY: 17197 case BPF_TRACE_FEXIT: 17198 range = retval_range(0, 0); 17199 break; 17200 case BPF_TRACE_RAW_TP: 17201 case BPF_MODIFY_RETURN: 17202 return 0; 17203 case BPF_TRACE_ITER: 17204 break; 17205 default: 17206 return -ENOTSUPP; 17207 } 17208 break; 17209 case BPF_PROG_TYPE_KPROBE: 17210 switch (env->prog->expected_attach_type) { 17211 case BPF_TRACE_KPROBE_SESSION: 17212 case BPF_TRACE_UPROBE_SESSION: 17213 range = retval_range(0, 1); 17214 break; 17215 default: 17216 return 0; 17217 } 17218 break; 17219 case BPF_PROG_TYPE_SK_LOOKUP: 17220 range = retval_range(SK_DROP, SK_PASS); 17221 break; 17222 17223 case BPF_PROG_TYPE_LSM: 17224 if (env->prog->expected_attach_type != BPF_LSM_CGROUP) { 17225 /* no range found, any return value is allowed */ 17226 if (!get_func_retval_range(env->prog, &range)) 17227 return 0; 17228 /* no restricted range, any return value is allowed */ 17229 if (range.minval == S32_MIN && range.maxval == S32_MAX) 17230 return 0; 17231 return_32bit = true; 17232 } else if (!env->prog->aux->attach_func_proto->type) { 17233 /* Make sure programs that attach to void 17234 * hooks don't try to modify return value. 17235 */ 17236 range = retval_range(1, 1); 17237 } 17238 break; 17239 17240 case BPF_PROG_TYPE_NETFILTER: 17241 range = retval_range(NF_DROP, NF_ACCEPT); 17242 break; 17243 case BPF_PROG_TYPE_STRUCT_OPS: 17244 if (!ret_type) 17245 return 0; 17246 range = retval_range(0, 0); 17247 break; 17248 case BPF_PROG_TYPE_EXT: 17249 /* freplace program can return anything as its return value 17250 * depends on the to-be-replaced kernel func or bpf program. 17251 */ 17252 default: 17253 return 0; 17254 } 17255 17256 enforce_retval: 17257 if (reg->type != SCALAR_VALUE) { 17258 verbose(env, "%s the register R%d is not a known value (%s)\n", 17259 exit_ctx, regno, reg_type_str(env, reg->type)); 17260 return -EINVAL; 17261 } 17262 17263 err = mark_chain_precision(env, regno); 17264 if (err) 17265 return err; 17266 17267 if (!retval_range_within(range, reg, return_32bit)) { 17268 verbose_invalid_scalar(env, reg, range, exit_ctx, reg_name); 17269 if (!is_subprog && 17270 prog->expected_attach_type == BPF_LSM_CGROUP && 17271 prog_type == BPF_PROG_TYPE_LSM && 17272 !prog->aux->attach_func_proto->type) 17273 verbose(env, "Note, BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n"); 17274 return -EINVAL; 17275 } 17276 17277 if (!tnum_is_unknown(enforce_attach_type_range) && 17278 tnum_in(enforce_attach_type_range, reg->var_off)) 17279 env->prog->enforce_expected_attach_type = 1; 17280 return 0; 17281 } 17282 17283 static void mark_subprog_changes_pkt_data(struct bpf_verifier_env *env, int off) 17284 { 17285 struct bpf_subprog_info *subprog; 17286 17287 subprog = find_containing_subprog(env, off); 17288 subprog->changes_pkt_data = true; 17289 } 17290 17291 static void mark_subprog_might_sleep(struct bpf_verifier_env *env, int off) 17292 { 17293 struct bpf_subprog_info *subprog; 17294 17295 subprog = find_containing_subprog(env, off); 17296 subprog->might_sleep = true; 17297 } 17298 17299 /* 't' is an index of a call-site. 17300 * 'w' is a callee entry point. 17301 * Eventually this function would be called when env->cfg.insn_state[w] == EXPLORED. 17302 * Rely on DFS traversal order and absence of recursive calls to guarantee that 17303 * callee's change_pkt_data marks would be correct at that moment. 17304 */ 17305 static void merge_callee_effects(struct bpf_verifier_env *env, int t, int w) 17306 { 17307 struct bpf_subprog_info *caller, *callee; 17308 17309 caller = find_containing_subprog(env, t); 17310 callee = find_containing_subprog(env, w); 17311 caller->changes_pkt_data |= callee->changes_pkt_data; 17312 caller->might_sleep |= callee->might_sleep; 17313 } 17314 17315 /* non-recursive DFS pseudo code 17316 * 1 procedure DFS-iterative(G,v): 17317 * 2 label v as discovered 17318 * 3 let S be a stack 17319 * 4 S.push(v) 17320 * 5 while S is not empty 17321 * 6 t <- S.peek() 17322 * 7 if t is what we're looking for: 17323 * 8 return t 17324 * 9 for all edges e in G.adjacentEdges(t) do 17325 * 10 if edge e is already labelled 17326 * 11 continue with the next edge 17327 * 12 w <- G.adjacentVertex(t,e) 17328 * 13 if vertex w is not discovered and not explored 17329 * 14 label e as tree-edge 17330 * 15 label w as discovered 17331 * 16 S.push(w) 17332 * 17 continue at 5 17333 * 18 else if vertex w is discovered 17334 * 19 label e as back-edge 17335 * 20 else 17336 * 21 // vertex w is explored 17337 * 22 label e as forward- or cross-edge 17338 * 23 label t as explored 17339 * 24 S.pop() 17340 * 17341 * convention: 17342 * 0x10 - discovered 17343 * 0x11 - discovered and fall-through edge labelled 17344 * 0x12 - discovered and fall-through and branch edges labelled 17345 * 0x20 - explored 17346 */ 17347 17348 enum { 17349 DISCOVERED = 0x10, 17350 EXPLORED = 0x20, 17351 FALLTHROUGH = 1, 17352 BRANCH = 2, 17353 }; 17354 17355 static void mark_prune_point(struct bpf_verifier_env *env, int idx) 17356 { 17357 env->insn_aux_data[idx].prune_point = true; 17358 } 17359 17360 static bool is_prune_point(struct bpf_verifier_env *env, int insn_idx) 17361 { 17362 return env->insn_aux_data[insn_idx].prune_point; 17363 } 17364 17365 static void mark_force_checkpoint(struct bpf_verifier_env *env, int idx) 17366 { 17367 env->insn_aux_data[idx].force_checkpoint = true; 17368 } 17369 17370 static bool is_force_checkpoint(struct bpf_verifier_env *env, int insn_idx) 17371 { 17372 return env->insn_aux_data[insn_idx].force_checkpoint; 17373 } 17374 17375 static void mark_calls_callback(struct bpf_verifier_env *env, int idx) 17376 { 17377 env->insn_aux_data[idx].calls_callback = true; 17378 } 17379 17380 static bool calls_callback(struct bpf_verifier_env *env, int insn_idx) 17381 { 17382 return env->insn_aux_data[insn_idx].calls_callback; 17383 } 17384 17385 enum { 17386 DONE_EXPLORING = 0, 17387 KEEP_EXPLORING = 1, 17388 }; 17389 17390 /* t, w, e - match pseudo-code above: 17391 * t - index of current instruction 17392 * w - next instruction 17393 * e - edge 17394 */ 17395 static int push_insn(int t, int w, int e, struct bpf_verifier_env *env) 17396 { 17397 int *insn_stack = env->cfg.insn_stack; 17398 int *insn_state = env->cfg.insn_state; 17399 17400 if (e == FALLTHROUGH && insn_state[t] >= (DISCOVERED | FALLTHROUGH)) 17401 return DONE_EXPLORING; 17402 17403 if (e == BRANCH && insn_state[t] >= (DISCOVERED | BRANCH)) 17404 return DONE_EXPLORING; 17405 17406 if (w < 0 || w >= env->prog->len) { 17407 verbose_linfo(env, t, "%d: ", t); 17408 verbose(env, "jump out of range from insn %d to %d\n", t, w); 17409 return -EINVAL; 17410 } 17411 17412 if (e == BRANCH) { 17413 /* mark branch target for state pruning */ 17414 mark_prune_point(env, w); 17415 mark_jmp_point(env, w); 17416 } 17417 17418 if (insn_state[w] == 0) { 17419 /* tree-edge */ 17420 insn_state[t] = DISCOVERED | e; 17421 insn_state[w] = DISCOVERED; 17422 if (env->cfg.cur_stack >= env->prog->len) 17423 return -E2BIG; 17424 insn_stack[env->cfg.cur_stack++] = w; 17425 return KEEP_EXPLORING; 17426 } else if ((insn_state[w] & 0xF0) == DISCOVERED) { 17427 if (env->bpf_capable) 17428 return DONE_EXPLORING; 17429 verbose_linfo(env, t, "%d: ", t); 17430 verbose_linfo(env, w, "%d: ", w); 17431 verbose(env, "back-edge from insn %d to %d\n", t, w); 17432 return -EINVAL; 17433 } else if (insn_state[w] == EXPLORED) { 17434 /* forward- or cross-edge */ 17435 insn_state[t] = DISCOVERED | e; 17436 } else { 17437 verifier_bug(env, "insn state internal bug"); 17438 return -EFAULT; 17439 } 17440 return DONE_EXPLORING; 17441 } 17442 17443 static int visit_func_call_insn(int t, struct bpf_insn *insns, 17444 struct bpf_verifier_env *env, 17445 bool visit_callee) 17446 { 17447 int ret, insn_sz; 17448 int w; 17449 17450 insn_sz = bpf_is_ldimm64(&insns[t]) ? 2 : 1; 17451 ret = push_insn(t, t + insn_sz, FALLTHROUGH, env); 17452 if (ret) 17453 return ret; 17454 17455 mark_prune_point(env, t + insn_sz); 17456 /* when we exit from subprog, we need to record non-linear history */ 17457 mark_jmp_point(env, t + insn_sz); 17458 17459 if (visit_callee) { 17460 w = t + insns[t].imm + 1; 17461 mark_prune_point(env, t); 17462 merge_callee_effects(env, t, w); 17463 ret = push_insn(t, w, BRANCH, env); 17464 } 17465 return ret; 17466 } 17467 17468 /* Bitmask with 1s for all caller saved registers */ 17469 #define ALL_CALLER_SAVED_REGS ((1u << CALLER_SAVED_REGS) - 1) 17470 17471 /* True if do_misc_fixups() replaces calls to helper number 'imm', 17472 * replacement patch is presumed to follow bpf_fastcall contract 17473 * (see mark_fastcall_pattern_for_call() below). 17474 */ 17475 static bool verifier_inlines_helper_call(struct bpf_verifier_env *env, s32 imm) 17476 { 17477 switch (imm) { 17478 #ifdef CONFIG_X86_64 17479 case BPF_FUNC_get_smp_processor_id: 17480 return env->prog->jit_requested && bpf_jit_supports_percpu_insn(); 17481 #endif 17482 default: 17483 return false; 17484 } 17485 } 17486 17487 struct call_summary { 17488 u8 num_params; 17489 bool is_void; 17490 bool fastcall; 17491 }; 17492 17493 /* If @call is a kfunc or helper call, fills @cs and returns true, 17494 * otherwise returns false. 17495 */ 17496 static bool get_call_summary(struct bpf_verifier_env *env, struct bpf_insn *call, 17497 struct call_summary *cs) 17498 { 17499 struct bpf_kfunc_call_arg_meta meta; 17500 const struct bpf_func_proto *fn; 17501 int i; 17502 17503 if (bpf_helper_call(call)) { 17504 17505 if (get_helper_proto(env, call->imm, &fn) < 0) 17506 /* error would be reported later */ 17507 return false; 17508 cs->fastcall = fn->allow_fastcall && 17509 (verifier_inlines_helper_call(env, call->imm) || 17510 bpf_jit_inlines_helper_call(call->imm)); 17511 cs->is_void = fn->ret_type == RET_VOID; 17512 cs->num_params = 0; 17513 for (i = 0; i < ARRAY_SIZE(fn->arg_type); ++i) { 17514 if (fn->arg_type[i] == ARG_DONTCARE) 17515 break; 17516 cs->num_params++; 17517 } 17518 return true; 17519 } 17520 17521 if (bpf_pseudo_kfunc_call(call)) { 17522 int err; 17523 17524 err = fetch_kfunc_meta(env, call, &meta, NULL); 17525 if (err < 0) 17526 /* error would be reported later */ 17527 return false; 17528 cs->num_params = btf_type_vlen(meta.func_proto); 17529 cs->fastcall = meta.kfunc_flags & KF_FASTCALL; 17530 cs->is_void = btf_type_is_void(btf_type_by_id(meta.btf, meta.func_proto->type)); 17531 return true; 17532 } 17533 17534 return false; 17535 } 17536 17537 /* LLVM define a bpf_fastcall function attribute. 17538 * This attribute means that function scratches only some of 17539 * the caller saved registers defined by ABI. 17540 * For BPF the set of such registers could be defined as follows: 17541 * - R0 is scratched only if function is non-void; 17542 * - R1-R5 are scratched only if corresponding parameter type is defined 17543 * in the function prototype. 17544 * 17545 * The contract between kernel and clang allows to simultaneously use 17546 * such functions and maintain backwards compatibility with old 17547 * kernels that don't understand bpf_fastcall calls: 17548 * 17549 * - for bpf_fastcall calls clang allocates registers as-if relevant r0-r5 17550 * registers are not scratched by the call; 17551 * 17552 * - as a post-processing step, clang visits each bpf_fastcall call and adds 17553 * spill/fill for every live r0-r5; 17554 * 17555 * - stack offsets used for the spill/fill are allocated as lowest 17556 * stack offsets in whole function and are not used for any other 17557 * purposes; 17558 * 17559 * - when kernel loads a program, it looks for such patterns 17560 * (bpf_fastcall function surrounded by spills/fills) and checks if 17561 * spill/fill stack offsets are used exclusively in fastcall patterns; 17562 * 17563 * - if so, and if verifier or current JIT inlines the call to the 17564 * bpf_fastcall function (e.g. a helper call), kernel removes unnecessary 17565 * spill/fill pairs; 17566 * 17567 * - when old kernel loads a program, presence of spill/fill pairs 17568 * keeps BPF program valid, albeit slightly less efficient. 17569 * 17570 * For example: 17571 * 17572 * r1 = 1; 17573 * r2 = 2; 17574 * *(u64 *)(r10 - 8) = r1; r1 = 1; 17575 * *(u64 *)(r10 - 16) = r2; r2 = 2; 17576 * call %[to_be_inlined] --> call %[to_be_inlined] 17577 * r2 = *(u64 *)(r10 - 16); r0 = r1; 17578 * r1 = *(u64 *)(r10 - 8); r0 += r2; 17579 * r0 = r1; exit; 17580 * r0 += r2; 17581 * exit; 17582 * 17583 * The purpose of mark_fastcall_pattern_for_call is to: 17584 * - look for such patterns; 17585 * - mark spill and fill instructions in env->insn_aux_data[*].fastcall_pattern; 17586 * - mark set env->insn_aux_data[*].fastcall_spills_num for call instruction; 17587 * - update env->subprog_info[*]->fastcall_stack_off to find an offset 17588 * at which bpf_fastcall spill/fill stack slots start; 17589 * - update env->subprog_info[*]->keep_fastcall_stack. 17590 * 17591 * The .fastcall_pattern and .fastcall_stack_off are used by 17592 * check_fastcall_stack_contract() to check if every stack access to 17593 * fastcall spill/fill stack slot originates from spill/fill 17594 * instructions, members of fastcall patterns. 17595 * 17596 * If such condition holds true for a subprogram, fastcall patterns could 17597 * be rewritten by remove_fastcall_spills_fills(). 17598 * Otherwise bpf_fastcall patterns are not changed in the subprogram 17599 * (code, presumably, generated by an older clang version). 17600 * 17601 * For example, it is *not* safe to remove spill/fill below: 17602 * 17603 * r1 = 1; 17604 * *(u64 *)(r10 - 8) = r1; r1 = 1; 17605 * call %[to_be_inlined] --> call %[to_be_inlined] 17606 * r1 = *(u64 *)(r10 - 8); r0 = *(u64 *)(r10 - 8); <---- wrong !!! 17607 * r0 = *(u64 *)(r10 - 8); r0 += r1; 17608 * r0 += r1; exit; 17609 * exit; 17610 */ 17611 static void mark_fastcall_pattern_for_call(struct bpf_verifier_env *env, 17612 struct bpf_subprog_info *subprog, 17613 int insn_idx, s16 lowest_off) 17614 { 17615 struct bpf_insn *insns = env->prog->insnsi, *stx, *ldx; 17616 struct bpf_insn *call = &env->prog->insnsi[insn_idx]; 17617 u32 clobbered_regs_mask; 17618 struct call_summary cs; 17619 u32 expected_regs_mask; 17620 s16 off; 17621 int i; 17622 17623 if (!get_call_summary(env, call, &cs)) 17624 return; 17625 17626 /* A bitmask specifying which caller saved registers are clobbered 17627 * by a call to a helper/kfunc *as if* this helper/kfunc follows 17628 * bpf_fastcall contract: 17629 * - includes R0 if function is non-void; 17630 * - includes R1-R5 if corresponding parameter has is described 17631 * in the function prototype. 17632 */ 17633 clobbered_regs_mask = GENMASK(cs.num_params, cs.is_void ? 1 : 0); 17634 /* e.g. if helper call clobbers r{0,1}, expect r{2,3,4,5} in the pattern */ 17635 expected_regs_mask = ~clobbered_regs_mask & ALL_CALLER_SAVED_REGS; 17636 17637 /* match pairs of form: 17638 * 17639 * *(u64 *)(r10 - Y) = rX (where Y % 8 == 0) 17640 * ... 17641 * call %[to_be_inlined] 17642 * ... 17643 * rX = *(u64 *)(r10 - Y) 17644 */ 17645 for (i = 1, off = lowest_off; i <= ARRAY_SIZE(caller_saved); ++i, off += BPF_REG_SIZE) { 17646 if (insn_idx - i < 0 || insn_idx + i >= env->prog->len) 17647 break; 17648 stx = &insns[insn_idx - i]; 17649 ldx = &insns[insn_idx + i]; 17650 /* must be a stack spill/fill pair */ 17651 if (stx->code != (BPF_STX | BPF_MEM | BPF_DW) || 17652 ldx->code != (BPF_LDX | BPF_MEM | BPF_DW) || 17653 stx->dst_reg != BPF_REG_10 || 17654 ldx->src_reg != BPF_REG_10) 17655 break; 17656 /* must be a spill/fill for the same reg */ 17657 if (stx->src_reg != ldx->dst_reg) 17658 break; 17659 /* must be one of the previously unseen registers */ 17660 if ((BIT(stx->src_reg) & expected_regs_mask) == 0) 17661 break; 17662 /* must be a spill/fill for the same expected offset, 17663 * no need to check offset alignment, BPF_DW stack access 17664 * is always 8-byte aligned. 17665 */ 17666 if (stx->off != off || ldx->off != off) 17667 break; 17668 expected_regs_mask &= ~BIT(stx->src_reg); 17669 env->insn_aux_data[insn_idx - i].fastcall_pattern = 1; 17670 env->insn_aux_data[insn_idx + i].fastcall_pattern = 1; 17671 } 17672 if (i == 1) 17673 return; 17674 17675 /* Conditionally set 'fastcall_spills_num' to allow forward 17676 * compatibility when more helper functions are marked as 17677 * bpf_fastcall at compile time than current kernel supports, e.g: 17678 * 17679 * 1: *(u64 *)(r10 - 8) = r1 17680 * 2: call A ;; assume A is bpf_fastcall for current kernel 17681 * 3: r1 = *(u64 *)(r10 - 8) 17682 * 4: *(u64 *)(r10 - 8) = r1 17683 * 5: call B ;; assume B is not bpf_fastcall for current kernel 17684 * 6: r1 = *(u64 *)(r10 - 8) 17685 * 17686 * There is no need to block bpf_fastcall rewrite for such program. 17687 * Set 'fastcall_pattern' for both calls to keep check_fastcall_stack_contract() happy, 17688 * don't set 'fastcall_spills_num' for call B so that remove_fastcall_spills_fills() 17689 * does not remove spill/fill pair {4,6}. 17690 */ 17691 if (cs.fastcall) 17692 env->insn_aux_data[insn_idx].fastcall_spills_num = i - 1; 17693 else 17694 subprog->keep_fastcall_stack = 1; 17695 subprog->fastcall_stack_off = min(subprog->fastcall_stack_off, off); 17696 } 17697 17698 static int mark_fastcall_patterns(struct bpf_verifier_env *env) 17699 { 17700 struct bpf_subprog_info *subprog = env->subprog_info; 17701 struct bpf_insn *insn; 17702 s16 lowest_off; 17703 int s, i; 17704 17705 for (s = 0; s < env->subprog_cnt; ++s, ++subprog) { 17706 /* find lowest stack spill offset used in this subprog */ 17707 lowest_off = 0; 17708 for (i = subprog->start; i < (subprog + 1)->start; ++i) { 17709 insn = env->prog->insnsi + i; 17710 if (insn->code != (BPF_STX | BPF_MEM | BPF_DW) || 17711 insn->dst_reg != BPF_REG_10) 17712 continue; 17713 lowest_off = min(lowest_off, insn->off); 17714 } 17715 /* use this offset to find fastcall patterns */ 17716 for (i = subprog->start; i < (subprog + 1)->start; ++i) { 17717 insn = env->prog->insnsi + i; 17718 if (insn->code != (BPF_JMP | BPF_CALL)) 17719 continue; 17720 mark_fastcall_pattern_for_call(env, subprog, i, lowest_off); 17721 } 17722 } 17723 return 0; 17724 } 17725 17726 /* Visits the instruction at index t and returns one of the following: 17727 * < 0 - an error occurred 17728 * DONE_EXPLORING - the instruction was fully explored 17729 * KEEP_EXPLORING - there is still work to be done before it is fully explored 17730 */ 17731 static int visit_insn(int t, struct bpf_verifier_env *env) 17732 { 17733 struct bpf_insn *insns = env->prog->insnsi, *insn = &insns[t]; 17734 int ret, off, insn_sz; 17735 17736 if (bpf_pseudo_func(insn)) 17737 return visit_func_call_insn(t, insns, env, true); 17738 17739 /* All non-branch instructions have a single fall-through edge. */ 17740 if (BPF_CLASS(insn->code) != BPF_JMP && 17741 BPF_CLASS(insn->code) != BPF_JMP32) { 17742 insn_sz = bpf_is_ldimm64(insn) ? 2 : 1; 17743 return push_insn(t, t + insn_sz, FALLTHROUGH, env); 17744 } 17745 17746 switch (BPF_OP(insn->code)) { 17747 case BPF_EXIT: 17748 return DONE_EXPLORING; 17749 17750 case BPF_CALL: 17751 if (is_async_callback_calling_insn(insn)) 17752 /* Mark this call insn as a prune point to trigger 17753 * is_state_visited() check before call itself is 17754 * processed by __check_func_call(). Otherwise new 17755 * async state will be pushed for further exploration. 17756 */ 17757 mark_prune_point(env, t); 17758 /* For functions that invoke callbacks it is not known how many times 17759 * callback would be called. Verifier models callback calling functions 17760 * by repeatedly visiting callback bodies and returning to origin call 17761 * instruction. 17762 * In order to stop such iteration verifier needs to identify when a 17763 * state identical some state from a previous iteration is reached. 17764 * Check below forces creation of checkpoint before callback calling 17765 * instruction to allow search for such identical states. 17766 */ 17767 if (is_sync_callback_calling_insn(insn)) { 17768 mark_calls_callback(env, t); 17769 mark_force_checkpoint(env, t); 17770 mark_prune_point(env, t); 17771 mark_jmp_point(env, t); 17772 } 17773 if (bpf_helper_call(insn)) { 17774 const struct bpf_func_proto *fp; 17775 17776 ret = get_helper_proto(env, insn->imm, &fp); 17777 /* If called in a non-sleepable context program will be 17778 * rejected anyway, so we should end up with precise 17779 * sleepable marks on subprogs, except for dead code 17780 * elimination. 17781 */ 17782 if (ret == 0 && fp->might_sleep) 17783 mark_subprog_might_sleep(env, t); 17784 if (bpf_helper_changes_pkt_data(insn->imm)) 17785 mark_subprog_changes_pkt_data(env, t); 17786 } else if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) { 17787 struct bpf_kfunc_call_arg_meta meta; 17788 17789 ret = fetch_kfunc_meta(env, insn, &meta, NULL); 17790 if (ret == 0 && is_iter_next_kfunc(&meta)) { 17791 mark_prune_point(env, t); 17792 /* Checking and saving state checkpoints at iter_next() call 17793 * is crucial for fast convergence of open-coded iterator loop 17794 * logic, so we need to force it. If we don't do that, 17795 * is_state_visited() might skip saving a checkpoint, causing 17796 * unnecessarily long sequence of not checkpointed 17797 * instructions and jumps, leading to exhaustion of jump 17798 * history buffer, and potentially other undesired outcomes. 17799 * It is expected that with correct open-coded iterators 17800 * convergence will happen quickly, so we don't run a risk of 17801 * exhausting memory. 17802 */ 17803 mark_force_checkpoint(env, t); 17804 } 17805 /* Same as helpers, if called in a non-sleepable context 17806 * program will be rejected anyway, so we should end up 17807 * with precise sleepable marks on subprogs, except for 17808 * dead code elimination. 17809 */ 17810 if (ret == 0 && is_kfunc_sleepable(&meta)) 17811 mark_subprog_might_sleep(env, t); 17812 if (ret == 0 && is_kfunc_pkt_changing(&meta)) 17813 mark_subprog_changes_pkt_data(env, t); 17814 } 17815 return visit_func_call_insn(t, insns, env, insn->src_reg == BPF_PSEUDO_CALL); 17816 17817 case BPF_JA: 17818 if (BPF_SRC(insn->code) != BPF_K) 17819 return -EINVAL; 17820 17821 if (BPF_CLASS(insn->code) == BPF_JMP) 17822 off = insn->off; 17823 else 17824 off = insn->imm; 17825 17826 /* unconditional jump with single edge */ 17827 ret = push_insn(t, t + off + 1, FALLTHROUGH, env); 17828 if (ret) 17829 return ret; 17830 17831 mark_prune_point(env, t + off + 1); 17832 mark_jmp_point(env, t + off + 1); 17833 17834 return ret; 17835 17836 default: 17837 /* conditional jump with two edges */ 17838 mark_prune_point(env, t); 17839 if (is_may_goto_insn(insn)) 17840 mark_force_checkpoint(env, t); 17841 17842 ret = push_insn(t, t + 1, FALLTHROUGH, env); 17843 if (ret) 17844 return ret; 17845 17846 return push_insn(t, t + insn->off + 1, BRANCH, env); 17847 } 17848 } 17849 17850 /* non-recursive depth-first-search to detect loops in BPF program 17851 * loop == back-edge in directed graph 17852 */ 17853 static int check_cfg(struct bpf_verifier_env *env) 17854 { 17855 int insn_cnt = env->prog->len; 17856 int *insn_stack, *insn_state, *insn_postorder; 17857 int ex_insn_beg, i, ret = 0; 17858 17859 insn_state = env->cfg.insn_state = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL_ACCOUNT); 17860 if (!insn_state) 17861 return -ENOMEM; 17862 17863 insn_stack = env->cfg.insn_stack = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL_ACCOUNT); 17864 if (!insn_stack) { 17865 kvfree(insn_state); 17866 return -ENOMEM; 17867 } 17868 17869 insn_postorder = env->cfg.insn_postorder = 17870 kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL_ACCOUNT); 17871 if (!insn_postorder) { 17872 kvfree(insn_state); 17873 kvfree(insn_stack); 17874 return -ENOMEM; 17875 } 17876 17877 ex_insn_beg = env->exception_callback_subprog 17878 ? env->subprog_info[env->exception_callback_subprog].start 17879 : 0; 17880 17881 insn_state[0] = DISCOVERED; /* mark 1st insn as discovered */ 17882 insn_stack[0] = 0; /* 0 is the first instruction */ 17883 env->cfg.cur_stack = 1; 17884 17885 walk_cfg: 17886 while (env->cfg.cur_stack > 0) { 17887 int t = insn_stack[env->cfg.cur_stack - 1]; 17888 17889 ret = visit_insn(t, env); 17890 switch (ret) { 17891 case DONE_EXPLORING: 17892 insn_state[t] = EXPLORED; 17893 env->cfg.cur_stack--; 17894 insn_postorder[env->cfg.cur_postorder++] = t; 17895 break; 17896 case KEEP_EXPLORING: 17897 break; 17898 default: 17899 if (ret > 0) { 17900 verifier_bug(env, "visit_insn internal bug"); 17901 ret = -EFAULT; 17902 } 17903 goto err_free; 17904 } 17905 } 17906 17907 if (env->cfg.cur_stack < 0) { 17908 verifier_bug(env, "pop stack internal bug"); 17909 ret = -EFAULT; 17910 goto err_free; 17911 } 17912 17913 if (ex_insn_beg && insn_state[ex_insn_beg] != EXPLORED) { 17914 insn_state[ex_insn_beg] = DISCOVERED; 17915 insn_stack[0] = ex_insn_beg; 17916 env->cfg.cur_stack = 1; 17917 goto walk_cfg; 17918 } 17919 17920 for (i = 0; i < insn_cnt; i++) { 17921 struct bpf_insn *insn = &env->prog->insnsi[i]; 17922 17923 if (insn_state[i] != EXPLORED) { 17924 verbose(env, "unreachable insn %d\n", i); 17925 ret = -EINVAL; 17926 goto err_free; 17927 } 17928 if (bpf_is_ldimm64(insn)) { 17929 if (insn_state[i + 1] != 0) { 17930 verbose(env, "jump into the middle of ldimm64 insn %d\n", i); 17931 ret = -EINVAL; 17932 goto err_free; 17933 } 17934 i++; /* skip second half of ldimm64 */ 17935 } 17936 } 17937 ret = 0; /* cfg looks good */ 17938 env->prog->aux->changes_pkt_data = env->subprog_info[0].changes_pkt_data; 17939 env->prog->aux->might_sleep = env->subprog_info[0].might_sleep; 17940 17941 err_free: 17942 kvfree(insn_state); 17943 kvfree(insn_stack); 17944 env->cfg.insn_state = env->cfg.insn_stack = NULL; 17945 return ret; 17946 } 17947 17948 static int check_abnormal_return(struct bpf_verifier_env *env) 17949 { 17950 int i; 17951 17952 for (i = 1; i < env->subprog_cnt; i++) { 17953 if (env->subprog_info[i].has_ld_abs) { 17954 verbose(env, "LD_ABS is not allowed in subprogs without BTF\n"); 17955 return -EINVAL; 17956 } 17957 if (env->subprog_info[i].has_tail_call) { 17958 verbose(env, "tail_call is not allowed in subprogs without BTF\n"); 17959 return -EINVAL; 17960 } 17961 } 17962 return 0; 17963 } 17964 17965 /* The minimum supported BTF func info size */ 17966 #define MIN_BPF_FUNCINFO_SIZE 8 17967 #define MAX_FUNCINFO_REC_SIZE 252 17968 17969 static int check_btf_func_early(struct bpf_verifier_env *env, 17970 const union bpf_attr *attr, 17971 bpfptr_t uattr) 17972 { 17973 u32 krec_size = sizeof(struct bpf_func_info); 17974 const struct btf_type *type, *func_proto; 17975 u32 i, nfuncs, urec_size, min_size; 17976 struct bpf_func_info *krecord; 17977 struct bpf_prog *prog; 17978 const struct btf *btf; 17979 u32 prev_offset = 0; 17980 bpfptr_t urecord; 17981 int ret = -ENOMEM; 17982 17983 nfuncs = attr->func_info_cnt; 17984 if (!nfuncs) { 17985 if (check_abnormal_return(env)) 17986 return -EINVAL; 17987 return 0; 17988 } 17989 17990 urec_size = attr->func_info_rec_size; 17991 if (urec_size < MIN_BPF_FUNCINFO_SIZE || 17992 urec_size > MAX_FUNCINFO_REC_SIZE || 17993 urec_size % sizeof(u32)) { 17994 verbose(env, "invalid func info rec size %u\n", urec_size); 17995 return -EINVAL; 17996 } 17997 17998 prog = env->prog; 17999 btf = prog->aux->btf; 18000 18001 urecord = make_bpfptr(attr->func_info, uattr.is_kernel); 18002 min_size = min_t(u32, krec_size, urec_size); 18003 18004 krecord = kvcalloc(nfuncs, krec_size, GFP_KERNEL_ACCOUNT | __GFP_NOWARN); 18005 if (!krecord) 18006 return -ENOMEM; 18007 18008 for (i = 0; i < nfuncs; i++) { 18009 ret = bpf_check_uarg_tail_zero(urecord, krec_size, urec_size); 18010 if (ret) { 18011 if (ret == -E2BIG) { 18012 verbose(env, "nonzero tailing record in func info"); 18013 /* set the size kernel expects so loader can zero 18014 * out the rest of the record. 18015 */ 18016 if (copy_to_bpfptr_offset(uattr, 18017 offsetof(union bpf_attr, func_info_rec_size), 18018 &min_size, sizeof(min_size))) 18019 ret = -EFAULT; 18020 } 18021 goto err_free; 18022 } 18023 18024 if (copy_from_bpfptr(&krecord[i], urecord, min_size)) { 18025 ret = -EFAULT; 18026 goto err_free; 18027 } 18028 18029 /* check insn_off */ 18030 ret = -EINVAL; 18031 if (i == 0) { 18032 if (krecord[i].insn_off) { 18033 verbose(env, 18034 "nonzero insn_off %u for the first func info record", 18035 krecord[i].insn_off); 18036 goto err_free; 18037 } 18038 } else if (krecord[i].insn_off <= prev_offset) { 18039 verbose(env, 18040 "same or smaller insn offset (%u) than previous func info record (%u)", 18041 krecord[i].insn_off, prev_offset); 18042 goto err_free; 18043 } 18044 18045 /* check type_id */ 18046 type = btf_type_by_id(btf, krecord[i].type_id); 18047 if (!type || !btf_type_is_func(type)) { 18048 verbose(env, "invalid type id %d in func info", 18049 krecord[i].type_id); 18050 goto err_free; 18051 } 18052 18053 func_proto = btf_type_by_id(btf, type->type); 18054 if (unlikely(!func_proto || !btf_type_is_func_proto(func_proto))) 18055 /* btf_func_check() already verified it during BTF load */ 18056 goto err_free; 18057 18058 prev_offset = krecord[i].insn_off; 18059 bpfptr_add(&urecord, urec_size); 18060 } 18061 18062 prog->aux->func_info = krecord; 18063 prog->aux->func_info_cnt = nfuncs; 18064 return 0; 18065 18066 err_free: 18067 kvfree(krecord); 18068 return ret; 18069 } 18070 18071 static int check_btf_func(struct bpf_verifier_env *env, 18072 const union bpf_attr *attr, 18073 bpfptr_t uattr) 18074 { 18075 const struct btf_type *type, *func_proto, *ret_type; 18076 u32 i, nfuncs, urec_size; 18077 struct bpf_func_info *krecord; 18078 struct bpf_func_info_aux *info_aux = NULL; 18079 struct bpf_prog *prog; 18080 const struct btf *btf; 18081 bpfptr_t urecord; 18082 bool scalar_return; 18083 int ret = -ENOMEM; 18084 18085 nfuncs = attr->func_info_cnt; 18086 if (!nfuncs) { 18087 if (check_abnormal_return(env)) 18088 return -EINVAL; 18089 return 0; 18090 } 18091 if (nfuncs != env->subprog_cnt) { 18092 verbose(env, "number of funcs in func_info doesn't match number of subprogs\n"); 18093 return -EINVAL; 18094 } 18095 18096 urec_size = attr->func_info_rec_size; 18097 18098 prog = env->prog; 18099 btf = prog->aux->btf; 18100 18101 urecord = make_bpfptr(attr->func_info, uattr.is_kernel); 18102 18103 krecord = prog->aux->func_info; 18104 info_aux = kcalloc(nfuncs, sizeof(*info_aux), GFP_KERNEL_ACCOUNT | __GFP_NOWARN); 18105 if (!info_aux) 18106 return -ENOMEM; 18107 18108 for (i = 0; i < nfuncs; i++) { 18109 /* check insn_off */ 18110 ret = -EINVAL; 18111 18112 if (env->subprog_info[i].start != krecord[i].insn_off) { 18113 verbose(env, "func_info BTF section doesn't match subprog layout in BPF program\n"); 18114 goto err_free; 18115 } 18116 18117 /* Already checked type_id */ 18118 type = btf_type_by_id(btf, krecord[i].type_id); 18119 info_aux[i].linkage = BTF_INFO_VLEN(type->info); 18120 /* Already checked func_proto */ 18121 func_proto = btf_type_by_id(btf, type->type); 18122 18123 ret_type = btf_type_skip_modifiers(btf, func_proto->type, NULL); 18124 scalar_return = 18125 btf_type_is_small_int(ret_type) || btf_is_any_enum(ret_type); 18126 if (i && !scalar_return && env->subprog_info[i].has_ld_abs) { 18127 verbose(env, "LD_ABS is only allowed in functions that return 'int'.\n"); 18128 goto err_free; 18129 } 18130 if (i && !scalar_return && env->subprog_info[i].has_tail_call) { 18131 verbose(env, "tail_call is only allowed in functions that return 'int'.\n"); 18132 goto err_free; 18133 } 18134 18135 bpfptr_add(&urecord, urec_size); 18136 } 18137 18138 prog->aux->func_info_aux = info_aux; 18139 return 0; 18140 18141 err_free: 18142 kfree(info_aux); 18143 return ret; 18144 } 18145 18146 static void adjust_btf_func(struct bpf_verifier_env *env) 18147 { 18148 struct bpf_prog_aux *aux = env->prog->aux; 18149 int i; 18150 18151 if (!aux->func_info) 18152 return; 18153 18154 /* func_info is not available for hidden subprogs */ 18155 for (i = 0; i < env->subprog_cnt - env->hidden_subprog_cnt; i++) 18156 aux->func_info[i].insn_off = env->subprog_info[i].start; 18157 } 18158 18159 #define MIN_BPF_LINEINFO_SIZE offsetofend(struct bpf_line_info, line_col) 18160 #define MAX_LINEINFO_REC_SIZE MAX_FUNCINFO_REC_SIZE 18161 18162 static int check_btf_line(struct bpf_verifier_env *env, 18163 const union bpf_attr *attr, 18164 bpfptr_t uattr) 18165 { 18166 u32 i, s, nr_linfo, ncopy, expected_size, rec_size, prev_offset = 0; 18167 struct bpf_subprog_info *sub; 18168 struct bpf_line_info *linfo; 18169 struct bpf_prog *prog; 18170 const struct btf *btf; 18171 bpfptr_t ulinfo; 18172 int err; 18173 18174 nr_linfo = attr->line_info_cnt; 18175 if (!nr_linfo) 18176 return 0; 18177 if (nr_linfo > INT_MAX / sizeof(struct bpf_line_info)) 18178 return -EINVAL; 18179 18180 rec_size = attr->line_info_rec_size; 18181 if (rec_size < MIN_BPF_LINEINFO_SIZE || 18182 rec_size > MAX_LINEINFO_REC_SIZE || 18183 rec_size & (sizeof(u32) - 1)) 18184 return -EINVAL; 18185 18186 /* Need to zero it in case the userspace may 18187 * pass in a smaller bpf_line_info object. 18188 */ 18189 linfo = kvcalloc(nr_linfo, sizeof(struct bpf_line_info), 18190 GFP_KERNEL_ACCOUNT | __GFP_NOWARN); 18191 if (!linfo) 18192 return -ENOMEM; 18193 18194 prog = env->prog; 18195 btf = prog->aux->btf; 18196 18197 s = 0; 18198 sub = env->subprog_info; 18199 ulinfo = make_bpfptr(attr->line_info, uattr.is_kernel); 18200 expected_size = sizeof(struct bpf_line_info); 18201 ncopy = min_t(u32, expected_size, rec_size); 18202 for (i = 0; i < nr_linfo; i++) { 18203 err = bpf_check_uarg_tail_zero(ulinfo, expected_size, rec_size); 18204 if (err) { 18205 if (err == -E2BIG) { 18206 verbose(env, "nonzero tailing record in line_info"); 18207 if (copy_to_bpfptr_offset(uattr, 18208 offsetof(union bpf_attr, line_info_rec_size), 18209 &expected_size, sizeof(expected_size))) 18210 err = -EFAULT; 18211 } 18212 goto err_free; 18213 } 18214 18215 if (copy_from_bpfptr(&linfo[i], ulinfo, ncopy)) { 18216 err = -EFAULT; 18217 goto err_free; 18218 } 18219 18220 /* 18221 * Check insn_off to ensure 18222 * 1) strictly increasing AND 18223 * 2) bounded by prog->len 18224 * 18225 * The linfo[0].insn_off == 0 check logically falls into 18226 * the later "missing bpf_line_info for func..." case 18227 * because the first linfo[0].insn_off must be the 18228 * first sub also and the first sub must have 18229 * subprog_info[0].start == 0. 18230 */ 18231 if ((i && linfo[i].insn_off <= prev_offset) || 18232 linfo[i].insn_off >= prog->len) { 18233 verbose(env, "Invalid line_info[%u].insn_off:%u (prev_offset:%u prog->len:%u)\n", 18234 i, linfo[i].insn_off, prev_offset, 18235 prog->len); 18236 err = -EINVAL; 18237 goto err_free; 18238 } 18239 18240 if (!prog->insnsi[linfo[i].insn_off].code) { 18241 verbose(env, 18242 "Invalid insn code at line_info[%u].insn_off\n", 18243 i); 18244 err = -EINVAL; 18245 goto err_free; 18246 } 18247 18248 if (!btf_name_by_offset(btf, linfo[i].line_off) || 18249 !btf_name_by_offset(btf, linfo[i].file_name_off)) { 18250 verbose(env, "Invalid line_info[%u].line_off or .file_name_off\n", i); 18251 err = -EINVAL; 18252 goto err_free; 18253 } 18254 18255 if (s != env->subprog_cnt) { 18256 if (linfo[i].insn_off == sub[s].start) { 18257 sub[s].linfo_idx = i; 18258 s++; 18259 } else if (sub[s].start < linfo[i].insn_off) { 18260 verbose(env, "missing bpf_line_info for func#%u\n", s); 18261 err = -EINVAL; 18262 goto err_free; 18263 } 18264 } 18265 18266 prev_offset = linfo[i].insn_off; 18267 bpfptr_add(&ulinfo, rec_size); 18268 } 18269 18270 if (s != env->subprog_cnt) { 18271 verbose(env, "missing bpf_line_info for %u funcs starting from func#%u\n", 18272 env->subprog_cnt - s, s); 18273 err = -EINVAL; 18274 goto err_free; 18275 } 18276 18277 prog->aux->linfo = linfo; 18278 prog->aux->nr_linfo = nr_linfo; 18279 18280 return 0; 18281 18282 err_free: 18283 kvfree(linfo); 18284 return err; 18285 } 18286 18287 #define MIN_CORE_RELO_SIZE sizeof(struct bpf_core_relo) 18288 #define MAX_CORE_RELO_SIZE MAX_FUNCINFO_REC_SIZE 18289 18290 static int check_core_relo(struct bpf_verifier_env *env, 18291 const union bpf_attr *attr, 18292 bpfptr_t uattr) 18293 { 18294 u32 i, nr_core_relo, ncopy, expected_size, rec_size; 18295 struct bpf_core_relo core_relo = {}; 18296 struct bpf_prog *prog = env->prog; 18297 const struct btf *btf = prog->aux->btf; 18298 struct bpf_core_ctx ctx = { 18299 .log = &env->log, 18300 .btf = btf, 18301 }; 18302 bpfptr_t u_core_relo; 18303 int err; 18304 18305 nr_core_relo = attr->core_relo_cnt; 18306 if (!nr_core_relo) 18307 return 0; 18308 if (nr_core_relo > INT_MAX / sizeof(struct bpf_core_relo)) 18309 return -EINVAL; 18310 18311 rec_size = attr->core_relo_rec_size; 18312 if (rec_size < MIN_CORE_RELO_SIZE || 18313 rec_size > MAX_CORE_RELO_SIZE || 18314 rec_size % sizeof(u32)) 18315 return -EINVAL; 18316 18317 u_core_relo = make_bpfptr(attr->core_relos, uattr.is_kernel); 18318 expected_size = sizeof(struct bpf_core_relo); 18319 ncopy = min_t(u32, expected_size, rec_size); 18320 18321 /* Unlike func_info and line_info, copy and apply each CO-RE 18322 * relocation record one at a time. 18323 */ 18324 for (i = 0; i < nr_core_relo; i++) { 18325 /* future proofing when sizeof(bpf_core_relo) changes */ 18326 err = bpf_check_uarg_tail_zero(u_core_relo, expected_size, rec_size); 18327 if (err) { 18328 if (err == -E2BIG) { 18329 verbose(env, "nonzero tailing record in core_relo"); 18330 if (copy_to_bpfptr_offset(uattr, 18331 offsetof(union bpf_attr, core_relo_rec_size), 18332 &expected_size, sizeof(expected_size))) 18333 err = -EFAULT; 18334 } 18335 break; 18336 } 18337 18338 if (copy_from_bpfptr(&core_relo, u_core_relo, ncopy)) { 18339 err = -EFAULT; 18340 break; 18341 } 18342 18343 if (core_relo.insn_off % 8 || core_relo.insn_off / 8 >= prog->len) { 18344 verbose(env, "Invalid core_relo[%u].insn_off:%u prog->len:%u\n", 18345 i, core_relo.insn_off, prog->len); 18346 err = -EINVAL; 18347 break; 18348 } 18349 18350 err = bpf_core_apply(&ctx, &core_relo, i, 18351 &prog->insnsi[core_relo.insn_off / 8]); 18352 if (err) 18353 break; 18354 bpfptr_add(&u_core_relo, rec_size); 18355 } 18356 return err; 18357 } 18358 18359 static int check_btf_info_early(struct bpf_verifier_env *env, 18360 const union bpf_attr *attr, 18361 bpfptr_t uattr) 18362 { 18363 struct btf *btf; 18364 int err; 18365 18366 if (!attr->func_info_cnt && !attr->line_info_cnt) { 18367 if (check_abnormal_return(env)) 18368 return -EINVAL; 18369 return 0; 18370 } 18371 18372 btf = btf_get_by_fd(attr->prog_btf_fd); 18373 if (IS_ERR(btf)) 18374 return PTR_ERR(btf); 18375 if (btf_is_kernel(btf)) { 18376 btf_put(btf); 18377 return -EACCES; 18378 } 18379 env->prog->aux->btf = btf; 18380 18381 err = check_btf_func_early(env, attr, uattr); 18382 if (err) 18383 return err; 18384 return 0; 18385 } 18386 18387 static int check_btf_info(struct bpf_verifier_env *env, 18388 const union bpf_attr *attr, 18389 bpfptr_t uattr) 18390 { 18391 int err; 18392 18393 if (!attr->func_info_cnt && !attr->line_info_cnt) { 18394 if (check_abnormal_return(env)) 18395 return -EINVAL; 18396 return 0; 18397 } 18398 18399 err = check_btf_func(env, attr, uattr); 18400 if (err) 18401 return err; 18402 18403 err = check_btf_line(env, attr, uattr); 18404 if (err) 18405 return err; 18406 18407 err = check_core_relo(env, attr, uattr); 18408 if (err) 18409 return err; 18410 18411 return 0; 18412 } 18413 18414 /* check %cur's range satisfies %old's */ 18415 static bool range_within(const struct bpf_reg_state *old, 18416 const struct bpf_reg_state *cur) 18417 { 18418 return old->umin_value <= cur->umin_value && 18419 old->umax_value >= cur->umax_value && 18420 old->smin_value <= cur->smin_value && 18421 old->smax_value >= cur->smax_value && 18422 old->u32_min_value <= cur->u32_min_value && 18423 old->u32_max_value >= cur->u32_max_value && 18424 old->s32_min_value <= cur->s32_min_value && 18425 old->s32_max_value >= cur->s32_max_value; 18426 } 18427 18428 /* If in the old state two registers had the same id, then they need to have 18429 * the same id in the new state as well. But that id could be different from 18430 * the old state, so we need to track the mapping from old to new ids. 18431 * Once we have seen that, say, a reg with old id 5 had new id 9, any subsequent 18432 * regs with old id 5 must also have new id 9 for the new state to be safe. But 18433 * regs with a different old id could still have new id 9, we don't care about 18434 * that. 18435 * So we look through our idmap to see if this old id has been seen before. If 18436 * so, we require the new id to match; otherwise, we add the id pair to the map. 18437 */ 18438 static bool check_ids(u32 old_id, u32 cur_id, struct bpf_idmap *idmap) 18439 { 18440 struct bpf_id_pair *map = idmap->map; 18441 unsigned int i; 18442 18443 /* either both IDs should be set or both should be zero */ 18444 if (!!old_id != !!cur_id) 18445 return false; 18446 18447 if (old_id == 0) /* cur_id == 0 as well */ 18448 return true; 18449 18450 for (i = 0; i < BPF_ID_MAP_SIZE; i++) { 18451 if (!map[i].old) { 18452 /* Reached an empty slot; haven't seen this id before */ 18453 map[i].old = old_id; 18454 map[i].cur = cur_id; 18455 return true; 18456 } 18457 if (map[i].old == old_id) 18458 return map[i].cur == cur_id; 18459 if (map[i].cur == cur_id) 18460 return false; 18461 } 18462 /* We ran out of idmap slots, which should be impossible */ 18463 WARN_ON_ONCE(1); 18464 return false; 18465 } 18466 18467 /* Similar to check_ids(), but allocate a unique temporary ID 18468 * for 'old_id' or 'cur_id' of zero. 18469 * This makes pairs like '0 vs unique ID', 'unique ID vs 0' valid. 18470 */ 18471 static bool check_scalar_ids(u32 old_id, u32 cur_id, struct bpf_idmap *idmap) 18472 { 18473 old_id = old_id ? old_id : ++idmap->tmp_id_gen; 18474 cur_id = cur_id ? cur_id : ++idmap->tmp_id_gen; 18475 18476 return check_ids(old_id, cur_id, idmap); 18477 } 18478 18479 static void clean_func_state(struct bpf_verifier_env *env, 18480 struct bpf_func_state *st) 18481 { 18482 enum bpf_reg_liveness live; 18483 int i, j; 18484 18485 for (i = 0; i < BPF_REG_FP; i++) { 18486 live = st->regs[i].live; 18487 /* liveness must not touch this register anymore */ 18488 st->regs[i].live |= REG_LIVE_DONE; 18489 if (!(live & REG_LIVE_READ)) 18490 /* since the register is unused, clear its state 18491 * to make further comparison simpler 18492 */ 18493 __mark_reg_not_init(env, &st->regs[i]); 18494 } 18495 18496 for (i = 0; i < st->allocated_stack / BPF_REG_SIZE; i++) { 18497 live = st->stack[i].spilled_ptr.live; 18498 /* liveness must not touch this stack slot anymore */ 18499 st->stack[i].spilled_ptr.live |= REG_LIVE_DONE; 18500 if (!(live & REG_LIVE_READ)) { 18501 __mark_reg_not_init(env, &st->stack[i].spilled_ptr); 18502 for (j = 0; j < BPF_REG_SIZE; j++) 18503 st->stack[i].slot_type[j] = STACK_INVALID; 18504 } 18505 } 18506 } 18507 18508 static void clean_verifier_state(struct bpf_verifier_env *env, 18509 struct bpf_verifier_state *st) 18510 { 18511 int i; 18512 18513 for (i = 0; i <= st->curframe; i++) 18514 clean_func_state(env, st->frame[i]); 18515 } 18516 18517 /* the parentage chains form a tree. 18518 * the verifier states are added to state lists at given insn and 18519 * pushed into state stack for future exploration. 18520 * when the verifier reaches bpf_exit insn some of the verifier states 18521 * stored in the state lists have their final liveness state already, 18522 * but a lot of states will get revised from liveness point of view when 18523 * the verifier explores other branches. 18524 * Example: 18525 * 1: r0 = 1 18526 * 2: if r1 == 100 goto pc+1 18527 * 3: r0 = 2 18528 * 4: exit 18529 * when the verifier reaches exit insn the register r0 in the state list of 18530 * insn 2 will be seen as !REG_LIVE_READ. Then the verifier pops the other_branch 18531 * of insn 2 and goes exploring further. At the insn 4 it will walk the 18532 * parentage chain from insn 4 into insn 2 and will mark r0 as REG_LIVE_READ. 18533 * 18534 * Since the verifier pushes the branch states as it sees them while exploring 18535 * the program the condition of walking the branch instruction for the second 18536 * time means that all states below this branch were already explored and 18537 * their final liveness marks are already propagated. 18538 * Hence when the verifier completes the search of state list in is_state_visited() 18539 * we can call this clean_live_states() function to mark all liveness states 18540 * as REG_LIVE_DONE to indicate that 'parent' pointers of 'struct bpf_reg_state' 18541 * will not be used. 18542 * This function also clears the registers and stack for states that !READ 18543 * to simplify state merging. 18544 * 18545 * Important note here that walking the same branch instruction in the callee 18546 * doesn't meant that the states are DONE. The verifier has to compare 18547 * the callsites 18548 */ 18549 static void clean_live_states(struct bpf_verifier_env *env, int insn, 18550 struct bpf_verifier_state *cur) 18551 { 18552 struct bpf_verifier_state_list *sl; 18553 struct list_head *pos, *head; 18554 18555 head = explored_state(env, insn); 18556 list_for_each(pos, head) { 18557 sl = container_of(pos, struct bpf_verifier_state_list, node); 18558 if (sl->state.branches) 18559 continue; 18560 if (sl->state.insn_idx != insn || 18561 !same_callsites(&sl->state, cur)) 18562 continue; 18563 if (sl->state.frame[0]->regs[0].live & REG_LIVE_DONE) 18564 /* all regs in this state in all frames were already marked */ 18565 continue; 18566 if (incomplete_read_marks(env, &sl->state)) 18567 continue; 18568 clean_verifier_state(env, &sl->state); 18569 } 18570 } 18571 18572 static bool regs_exact(const struct bpf_reg_state *rold, 18573 const struct bpf_reg_state *rcur, 18574 struct bpf_idmap *idmap) 18575 { 18576 return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 && 18577 check_ids(rold->id, rcur->id, idmap) && 18578 check_ids(rold->ref_obj_id, rcur->ref_obj_id, idmap); 18579 } 18580 18581 enum exact_level { 18582 NOT_EXACT, 18583 EXACT, 18584 RANGE_WITHIN 18585 }; 18586 18587 /* Returns true if (rold safe implies rcur safe) */ 18588 static bool regsafe(struct bpf_verifier_env *env, struct bpf_reg_state *rold, 18589 struct bpf_reg_state *rcur, struct bpf_idmap *idmap, 18590 enum exact_level exact) 18591 { 18592 if (exact == EXACT) 18593 return regs_exact(rold, rcur, idmap); 18594 18595 if (!(rold->live & REG_LIVE_READ) && exact == NOT_EXACT) 18596 /* explored state didn't use this */ 18597 return true; 18598 if (rold->type == NOT_INIT) { 18599 if (exact == NOT_EXACT || rcur->type == NOT_INIT) 18600 /* explored state can't have used this */ 18601 return true; 18602 } 18603 18604 /* Enforce that register types have to match exactly, including their 18605 * modifiers (like PTR_MAYBE_NULL, MEM_RDONLY, etc), as a general 18606 * rule. 18607 * 18608 * One can make a point that using a pointer register as unbounded 18609 * SCALAR would be technically acceptable, but this could lead to 18610 * pointer leaks because scalars are allowed to leak while pointers 18611 * are not. We could make this safe in special cases if root is 18612 * calling us, but it's probably not worth the hassle. 18613 * 18614 * Also, register types that are *not* MAYBE_NULL could technically be 18615 * safe to use as their MAYBE_NULL variants (e.g., PTR_TO_MAP_VALUE 18616 * is safe to be used as PTR_TO_MAP_VALUE_OR_NULL, provided both point 18617 * to the same map). 18618 * However, if the old MAYBE_NULL register then got NULL checked, 18619 * doing so could have affected others with the same id, and we can't 18620 * check for that because we lost the id when we converted to 18621 * a non-MAYBE_NULL variant. 18622 * So, as a general rule we don't allow mixing MAYBE_NULL and 18623 * non-MAYBE_NULL registers as well. 18624 */ 18625 if (rold->type != rcur->type) 18626 return false; 18627 18628 switch (base_type(rold->type)) { 18629 case SCALAR_VALUE: 18630 if (env->explore_alu_limits) { 18631 /* explore_alu_limits disables tnum_in() and range_within() 18632 * logic and requires everything to be strict 18633 */ 18634 return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 && 18635 check_scalar_ids(rold->id, rcur->id, idmap); 18636 } 18637 if (!rold->precise && exact == NOT_EXACT) 18638 return true; 18639 if ((rold->id & BPF_ADD_CONST) != (rcur->id & BPF_ADD_CONST)) 18640 return false; 18641 if ((rold->id & BPF_ADD_CONST) && (rold->off != rcur->off)) 18642 return false; 18643 /* Why check_ids() for scalar registers? 18644 * 18645 * Consider the following BPF code: 18646 * 1: r6 = ... unbound scalar, ID=a ... 18647 * 2: r7 = ... unbound scalar, ID=b ... 18648 * 3: if (r6 > r7) goto +1 18649 * 4: r6 = r7 18650 * 5: if (r6 > X) goto ... 18651 * 6: ... memory operation using r7 ... 18652 * 18653 * First verification path is [1-6]: 18654 * - at (4) same bpf_reg_state::id (b) would be assigned to r6 and r7; 18655 * - at (5) r6 would be marked <= X, sync_linked_regs() would also mark 18656 * r7 <= X, because r6 and r7 share same id. 18657 * Next verification path is [1-4, 6]. 18658 * 18659 * Instruction (6) would be reached in two states: 18660 * I. r6{.id=b}, r7{.id=b} via path 1-6; 18661 * II. r6{.id=a}, r7{.id=b} via path 1-4, 6. 18662 * 18663 * Use check_ids() to distinguish these states. 18664 * --- 18665 * Also verify that new value satisfies old value range knowledge. 18666 */ 18667 return range_within(rold, rcur) && 18668 tnum_in(rold->var_off, rcur->var_off) && 18669 check_scalar_ids(rold->id, rcur->id, idmap); 18670 case PTR_TO_MAP_KEY: 18671 case PTR_TO_MAP_VALUE: 18672 case PTR_TO_MEM: 18673 case PTR_TO_BUF: 18674 case PTR_TO_TP_BUFFER: 18675 /* If the new min/max/var_off satisfy the old ones and 18676 * everything else matches, we are OK. 18677 */ 18678 return memcmp(rold, rcur, offsetof(struct bpf_reg_state, var_off)) == 0 && 18679 range_within(rold, rcur) && 18680 tnum_in(rold->var_off, rcur->var_off) && 18681 check_ids(rold->id, rcur->id, idmap) && 18682 check_ids(rold->ref_obj_id, rcur->ref_obj_id, idmap); 18683 case PTR_TO_PACKET_META: 18684 case PTR_TO_PACKET: 18685 /* We must have at least as much range as the old ptr 18686 * did, so that any accesses which were safe before are 18687 * still safe. This is true even if old range < old off, 18688 * since someone could have accessed through (ptr - k), or 18689 * even done ptr -= k in a register, to get a safe access. 18690 */ 18691 if (rold->range > rcur->range) 18692 return false; 18693 /* If the offsets don't match, we can't trust our alignment; 18694 * nor can we be sure that we won't fall out of range. 18695 */ 18696 if (rold->off != rcur->off) 18697 return false; 18698 /* id relations must be preserved */ 18699 if (!check_ids(rold->id, rcur->id, idmap)) 18700 return false; 18701 /* new val must satisfy old val knowledge */ 18702 return range_within(rold, rcur) && 18703 tnum_in(rold->var_off, rcur->var_off); 18704 case PTR_TO_STACK: 18705 /* two stack pointers are equal only if they're pointing to 18706 * the same stack frame, since fp-8 in foo != fp-8 in bar 18707 */ 18708 return regs_exact(rold, rcur, idmap) && rold->frameno == rcur->frameno; 18709 case PTR_TO_ARENA: 18710 return true; 18711 default: 18712 return regs_exact(rold, rcur, idmap); 18713 } 18714 } 18715 18716 static struct bpf_reg_state unbound_reg; 18717 18718 static __init int unbound_reg_init(void) 18719 { 18720 __mark_reg_unknown_imprecise(&unbound_reg); 18721 unbound_reg.live |= REG_LIVE_READ; 18722 return 0; 18723 } 18724 late_initcall(unbound_reg_init); 18725 18726 static bool is_stack_all_misc(struct bpf_verifier_env *env, 18727 struct bpf_stack_state *stack) 18728 { 18729 u32 i; 18730 18731 for (i = 0; i < ARRAY_SIZE(stack->slot_type); ++i) { 18732 if ((stack->slot_type[i] == STACK_MISC) || 18733 (stack->slot_type[i] == STACK_INVALID && env->allow_uninit_stack)) 18734 continue; 18735 return false; 18736 } 18737 18738 return true; 18739 } 18740 18741 static struct bpf_reg_state *scalar_reg_for_stack(struct bpf_verifier_env *env, 18742 struct bpf_stack_state *stack) 18743 { 18744 if (is_spilled_scalar_reg64(stack)) 18745 return &stack->spilled_ptr; 18746 18747 if (is_stack_all_misc(env, stack)) 18748 return &unbound_reg; 18749 18750 return NULL; 18751 } 18752 18753 static bool stacksafe(struct bpf_verifier_env *env, struct bpf_func_state *old, 18754 struct bpf_func_state *cur, struct bpf_idmap *idmap, 18755 enum exact_level exact) 18756 { 18757 int i, spi; 18758 18759 /* walk slots of the explored stack and ignore any additional 18760 * slots in the current stack, since explored(safe) state 18761 * didn't use them 18762 */ 18763 for (i = 0; i < old->allocated_stack; i++) { 18764 struct bpf_reg_state *old_reg, *cur_reg; 18765 18766 spi = i / BPF_REG_SIZE; 18767 18768 if (exact != NOT_EXACT && 18769 (i >= cur->allocated_stack || 18770 old->stack[spi].slot_type[i % BPF_REG_SIZE] != 18771 cur->stack[spi].slot_type[i % BPF_REG_SIZE])) 18772 return false; 18773 18774 if (!(old->stack[spi].spilled_ptr.live & REG_LIVE_READ) 18775 && exact == NOT_EXACT) { 18776 i += BPF_REG_SIZE - 1; 18777 /* explored state didn't use this */ 18778 continue; 18779 } 18780 18781 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_INVALID) 18782 continue; 18783 18784 if (env->allow_uninit_stack && 18785 old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC) 18786 continue; 18787 18788 /* explored stack has more populated slots than current stack 18789 * and these slots were used 18790 */ 18791 if (i >= cur->allocated_stack) 18792 return false; 18793 18794 /* 64-bit scalar spill vs all slots MISC and vice versa. 18795 * Load from all slots MISC produces unbound scalar. 18796 * Construct a fake register for such stack and call 18797 * regsafe() to ensure scalar ids are compared. 18798 */ 18799 old_reg = scalar_reg_for_stack(env, &old->stack[spi]); 18800 cur_reg = scalar_reg_for_stack(env, &cur->stack[spi]); 18801 if (old_reg && cur_reg) { 18802 if (!regsafe(env, old_reg, cur_reg, idmap, exact)) 18803 return false; 18804 i += BPF_REG_SIZE - 1; 18805 continue; 18806 } 18807 18808 /* if old state was safe with misc data in the stack 18809 * it will be safe with zero-initialized stack. 18810 * The opposite is not true 18811 */ 18812 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC && 18813 cur->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_ZERO) 18814 continue; 18815 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] != 18816 cur->stack[spi].slot_type[i % BPF_REG_SIZE]) 18817 /* Ex: old explored (safe) state has STACK_SPILL in 18818 * this stack slot, but current has STACK_MISC -> 18819 * this verifier states are not equivalent, 18820 * return false to continue verification of this path 18821 */ 18822 return false; 18823 if (i % BPF_REG_SIZE != BPF_REG_SIZE - 1) 18824 continue; 18825 /* Both old and cur are having same slot_type */ 18826 switch (old->stack[spi].slot_type[BPF_REG_SIZE - 1]) { 18827 case STACK_SPILL: 18828 /* when explored and current stack slot are both storing 18829 * spilled registers, check that stored pointers types 18830 * are the same as well. 18831 * Ex: explored safe path could have stored 18832 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -8} 18833 * but current path has stored: 18834 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -16} 18835 * such verifier states are not equivalent. 18836 * return false to continue verification of this path 18837 */ 18838 if (!regsafe(env, &old->stack[spi].spilled_ptr, 18839 &cur->stack[spi].spilled_ptr, idmap, exact)) 18840 return false; 18841 break; 18842 case STACK_DYNPTR: 18843 old_reg = &old->stack[spi].spilled_ptr; 18844 cur_reg = &cur->stack[spi].spilled_ptr; 18845 if (old_reg->dynptr.type != cur_reg->dynptr.type || 18846 old_reg->dynptr.first_slot != cur_reg->dynptr.first_slot || 18847 !check_ids(old_reg->ref_obj_id, cur_reg->ref_obj_id, idmap)) 18848 return false; 18849 break; 18850 case STACK_ITER: 18851 old_reg = &old->stack[spi].spilled_ptr; 18852 cur_reg = &cur->stack[spi].spilled_ptr; 18853 /* iter.depth is not compared between states as it 18854 * doesn't matter for correctness and would otherwise 18855 * prevent convergence; we maintain it only to prevent 18856 * infinite loop check triggering, see 18857 * iter_active_depths_differ() 18858 */ 18859 if (old_reg->iter.btf != cur_reg->iter.btf || 18860 old_reg->iter.btf_id != cur_reg->iter.btf_id || 18861 old_reg->iter.state != cur_reg->iter.state || 18862 /* ignore {old_reg,cur_reg}->iter.depth, see above */ 18863 !check_ids(old_reg->ref_obj_id, cur_reg->ref_obj_id, idmap)) 18864 return false; 18865 break; 18866 case STACK_IRQ_FLAG: 18867 old_reg = &old->stack[spi].spilled_ptr; 18868 cur_reg = &cur->stack[spi].spilled_ptr; 18869 if (!check_ids(old_reg->ref_obj_id, cur_reg->ref_obj_id, idmap) || 18870 old_reg->irq.kfunc_class != cur_reg->irq.kfunc_class) 18871 return false; 18872 break; 18873 case STACK_MISC: 18874 case STACK_ZERO: 18875 case STACK_INVALID: 18876 continue; 18877 /* Ensure that new unhandled slot types return false by default */ 18878 default: 18879 return false; 18880 } 18881 } 18882 return true; 18883 } 18884 18885 static bool refsafe(struct bpf_verifier_state *old, struct bpf_verifier_state *cur, 18886 struct bpf_idmap *idmap) 18887 { 18888 int i; 18889 18890 if (old->acquired_refs != cur->acquired_refs) 18891 return false; 18892 18893 if (old->active_locks != cur->active_locks) 18894 return false; 18895 18896 if (old->active_preempt_locks != cur->active_preempt_locks) 18897 return false; 18898 18899 if (old->active_rcu_lock != cur->active_rcu_lock) 18900 return false; 18901 18902 if (!check_ids(old->active_irq_id, cur->active_irq_id, idmap)) 18903 return false; 18904 18905 if (!check_ids(old->active_lock_id, cur->active_lock_id, idmap) || 18906 old->active_lock_ptr != cur->active_lock_ptr) 18907 return false; 18908 18909 for (i = 0; i < old->acquired_refs; i++) { 18910 if (!check_ids(old->refs[i].id, cur->refs[i].id, idmap) || 18911 old->refs[i].type != cur->refs[i].type) 18912 return false; 18913 switch (old->refs[i].type) { 18914 case REF_TYPE_PTR: 18915 case REF_TYPE_IRQ: 18916 break; 18917 case REF_TYPE_LOCK: 18918 case REF_TYPE_RES_LOCK: 18919 case REF_TYPE_RES_LOCK_IRQ: 18920 if (old->refs[i].ptr != cur->refs[i].ptr) 18921 return false; 18922 break; 18923 default: 18924 WARN_ONCE(1, "Unhandled enum type for reference state: %d\n", old->refs[i].type); 18925 return false; 18926 } 18927 } 18928 18929 return true; 18930 } 18931 18932 /* compare two verifier states 18933 * 18934 * all states stored in state_list are known to be valid, since 18935 * verifier reached 'bpf_exit' instruction through them 18936 * 18937 * this function is called when verifier exploring different branches of 18938 * execution popped from the state stack. If it sees an old state that has 18939 * more strict register state and more strict stack state then this execution 18940 * branch doesn't need to be explored further, since verifier already 18941 * concluded that more strict state leads to valid finish. 18942 * 18943 * Therefore two states are equivalent if register state is more conservative 18944 * and explored stack state is more conservative than the current one. 18945 * Example: 18946 * explored current 18947 * (slot1=INV slot2=MISC) == (slot1=MISC slot2=MISC) 18948 * (slot1=MISC slot2=MISC) != (slot1=INV slot2=MISC) 18949 * 18950 * In other words if current stack state (one being explored) has more 18951 * valid slots than old one that already passed validation, it means 18952 * the verifier can stop exploring and conclude that current state is valid too 18953 * 18954 * Similarly with registers. If explored state has register type as invalid 18955 * whereas register type in current state is meaningful, it means that 18956 * the current state will reach 'bpf_exit' instruction safely 18957 */ 18958 static bool func_states_equal(struct bpf_verifier_env *env, struct bpf_func_state *old, 18959 struct bpf_func_state *cur, u32 insn_idx, enum exact_level exact) 18960 { 18961 u16 live_regs = env->insn_aux_data[insn_idx].live_regs_before; 18962 u16 i; 18963 18964 if (old->callback_depth > cur->callback_depth) 18965 return false; 18966 18967 for (i = 0; i < MAX_BPF_REG; i++) 18968 if (((1 << i) & live_regs) && 18969 !regsafe(env, &old->regs[i], &cur->regs[i], 18970 &env->idmap_scratch, exact)) 18971 return false; 18972 18973 if (!stacksafe(env, old, cur, &env->idmap_scratch, exact)) 18974 return false; 18975 18976 return true; 18977 } 18978 18979 static void reset_idmap_scratch(struct bpf_verifier_env *env) 18980 { 18981 env->idmap_scratch.tmp_id_gen = env->id_gen; 18982 memset(&env->idmap_scratch.map, 0, sizeof(env->idmap_scratch.map)); 18983 } 18984 18985 static bool states_equal(struct bpf_verifier_env *env, 18986 struct bpf_verifier_state *old, 18987 struct bpf_verifier_state *cur, 18988 enum exact_level exact) 18989 { 18990 u32 insn_idx; 18991 int i; 18992 18993 if (old->curframe != cur->curframe) 18994 return false; 18995 18996 reset_idmap_scratch(env); 18997 18998 /* Verification state from speculative execution simulation 18999 * must never prune a non-speculative execution one. 19000 */ 19001 if (old->speculative && !cur->speculative) 19002 return false; 19003 19004 if (old->in_sleepable != cur->in_sleepable) 19005 return false; 19006 19007 if (!refsafe(old, cur, &env->idmap_scratch)) 19008 return false; 19009 19010 /* for states to be equal callsites have to be the same 19011 * and all frame states need to be equivalent 19012 */ 19013 for (i = 0; i <= old->curframe; i++) { 19014 insn_idx = frame_insn_idx(old, i); 19015 if (old->frame[i]->callsite != cur->frame[i]->callsite) 19016 return false; 19017 if (!func_states_equal(env, old->frame[i], cur->frame[i], insn_idx, exact)) 19018 return false; 19019 } 19020 return true; 19021 } 19022 19023 /* Return 0 if no propagation happened. Return negative error code if error 19024 * happened. Otherwise, return the propagated bit. 19025 */ 19026 static int propagate_liveness_reg(struct bpf_verifier_env *env, 19027 struct bpf_reg_state *reg, 19028 struct bpf_reg_state *parent_reg) 19029 { 19030 u8 parent_flag = parent_reg->live & REG_LIVE_READ; 19031 u8 flag = reg->live & REG_LIVE_READ; 19032 int err; 19033 19034 /* When comes here, read flags of PARENT_REG or REG could be any of 19035 * REG_LIVE_READ64, REG_LIVE_READ32, REG_LIVE_NONE. There is no need 19036 * of propagation if PARENT_REG has strongest REG_LIVE_READ64. 19037 */ 19038 if (parent_flag == REG_LIVE_READ64 || 19039 /* Or if there is no read flag from REG. */ 19040 !flag || 19041 /* Or if the read flag from REG is the same as PARENT_REG. */ 19042 parent_flag == flag) 19043 return 0; 19044 19045 err = mark_reg_read(env, reg, parent_reg, flag); 19046 if (err) 19047 return err; 19048 19049 return flag; 19050 } 19051 19052 /* A write screens off any subsequent reads; but write marks come from the 19053 * straight-line code between a state and its parent. When we arrive at an 19054 * equivalent state (jump target or such) we didn't arrive by the straight-line 19055 * code, so read marks in the state must propagate to the parent regardless 19056 * of the state's write marks. That's what 'parent == state->parent' comparison 19057 * in mark_reg_read() is for. 19058 */ 19059 static int propagate_liveness(struct bpf_verifier_env *env, 19060 const struct bpf_verifier_state *vstate, 19061 struct bpf_verifier_state *vparent, 19062 bool *changed) 19063 { 19064 struct bpf_reg_state *state_reg, *parent_reg; 19065 struct bpf_func_state *state, *parent; 19066 int i, frame, err = 0; 19067 bool tmp = false; 19068 19069 changed = changed ?: &tmp; 19070 if (vparent->curframe != vstate->curframe) { 19071 WARN(1, "propagate_live: parent frame %d current frame %d\n", 19072 vparent->curframe, vstate->curframe); 19073 return -EFAULT; 19074 } 19075 /* Propagate read liveness of registers... */ 19076 BUILD_BUG_ON(BPF_REG_FP + 1 != MAX_BPF_REG); 19077 for (frame = 0; frame <= vstate->curframe; frame++) { 19078 parent = vparent->frame[frame]; 19079 state = vstate->frame[frame]; 19080 parent_reg = parent->regs; 19081 state_reg = state->regs; 19082 /* We don't need to worry about FP liveness, it's read-only */ 19083 for (i = frame < vstate->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++) { 19084 err = propagate_liveness_reg(env, &state_reg[i], 19085 &parent_reg[i]); 19086 if (err < 0) 19087 return err; 19088 *changed |= err > 0; 19089 if (err == REG_LIVE_READ64) 19090 mark_insn_zext(env, &parent_reg[i]); 19091 } 19092 19093 /* Propagate stack slots. */ 19094 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE && 19095 i < parent->allocated_stack / BPF_REG_SIZE; i++) { 19096 parent_reg = &parent->stack[i].spilled_ptr; 19097 state_reg = &state->stack[i].spilled_ptr; 19098 err = propagate_liveness_reg(env, state_reg, 19099 parent_reg); 19100 *changed |= err > 0; 19101 if (err < 0) 19102 return err; 19103 } 19104 } 19105 return 0; 19106 } 19107 19108 /* find precise scalars in the previous equivalent state and 19109 * propagate them into the current state 19110 */ 19111 static int propagate_precision(struct bpf_verifier_env *env, 19112 const struct bpf_verifier_state *old, 19113 struct bpf_verifier_state *cur, 19114 bool *changed) 19115 { 19116 struct bpf_reg_state *state_reg; 19117 struct bpf_func_state *state; 19118 int i, err = 0, fr; 19119 bool first; 19120 19121 for (fr = old->curframe; fr >= 0; fr--) { 19122 state = old->frame[fr]; 19123 state_reg = state->regs; 19124 first = true; 19125 for (i = 0; i < BPF_REG_FP; i++, state_reg++) { 19126 if (state_reg->type != SCALAR_VALUE || 19127 !state_reg->precise || 19128 !(state_reg->live & REG_LIVE_READ)) 19129 continue; 19130 if (env->log.level & BPF_LOG_LEVEL2) { 19131 if (first) 19132 verbose(env, "frame %d: propagating r%d", fr, i); 19133 else 19134 verbose(env, ",r%d", i); 19135 } 19136 bt_set_frame_reg(&env->bt, fr, i); 19137 first = false; 19138 } 19139 19140 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) { 19141 if (!is_spilled_reg(&state->stack[i])) 19142 continue; 19143 state_reg = &state->stack[i].spilled_ptr; 19144 if (state_reg->type != SCALAR_VALUE || 19145 !state_reg->precise || 19146 !(state_reg->live & REG_LIVE_READ)) 19147 continue; 19148 if (env->log.level & BPF_LOG_LEVEL2) { 19149 if (first) 19150 verbose(env, "frame %d: propagating fp%d", 19151 fr, (-i - 1) * BPF_REG_SIZE); 19152 else 19153 verbose(env, ",fp%d", (-i - 1) * BPF_REG_SIZE); 19154 } 19155 bt_set_frame_slot(&env->bt, fr, i); 19156 first = false; 19157 } 19158 if (!first) 19159 verbose(env, "\n"); 19160 } 19161 19162 err = __mark_chain_precision(env, cur, -1, changed); 19163 if (err < 0) 19164 return err; 19165 19166 return 0; 19167 } 19168 19169 #define MAX_BACKEDGE_ITERS 64 19170 19171 /* Propagate read and precision marks from visit->backedges[*].state->equal_state 19172 * to corresponding parent states of visit->backedges[*].state until fixed point is reached, 19173 * then free visit->backedges. 19174 * After execution of this function incomplete_read_marks() will return false 19175 * for all states corresponding to @visit->callchain. 19176 */ 19177 static int propagate_backedges(struct bpf_verifier_env *env, struct bpf_scc_visit *visit) 19178 { 19179 struct bpf_scc_backedge *backedge; 19180 struct bpf_verifier_state *st; 19181 bool changed; 19182 int i, err; 19183 19184 i = 0; 19185 do { 19186 if (i++ > MAX_BACKEDGE_ITERS) { 19187 if (env->log.level & BPF_LOG_LEVEL2) 19188 verbose(env, "%s: too many iterations\n", __func__); 19189 for (backedge = visit->backedges; backedge; backedge = backedge->next) 19190 mark_all_scalars_precise(env, &backedge->state); 19191 break; 19192 } 19193 changed = false; 19194 for (backedge = visit->backedges; backedge; backedge = backedge->next) { 19195 st = &backedge->state; 19196 err = propagate_liveness(env, st->equal_state, st, &changed); 19197 if (err) 19198 return err; 19199 err = propagate_precision(env, st->equal_state, st, &changed); 19200 if (err) 19201 return err; 19202 } 19203 } while (changed); 19204 19205 free_backedges(visit); 19206 return 0; 19207 } 19208 19209 static bool states_maybe_looping(struct bpf_verifier_state *old, 19210 struct bpf_verifier_state *cur) 19211 { 19212 struct bpf_func_state *fold, *fcur; 19213 int i, fr = cur->curframe; 19214 19215 if (old->curframe != fr) 19216 return false; 19217 19218 fold = old->frame[fr]; 19219 fcur = cur->frame[fr]; 19220 for (i = 0; i < MAX_BPF_REG; i++) 19221 if (memcmp(&fold->regs[i], &fcur->regs[i], 19222 offsetof(struct bpf_reg_state, parent))) 19223 return false; 19224 return true; 19225 } 19226 19227 static bool is_iter_next_insn(struct bpf_verifier_env *env, int insn_idx) 19228 { 19229 return env->insn_aux_data[insn_idx].is_iter_next; 19230 } 19231 19232 /* is_state_visited() handles iter_next() (see process_iter_next_call() for 19233 * terminology) calls specially: as opposed to bounded BPF loops, it *expects* 19234 * states to match, which otherwise would look like an infinite loop. So while 19235 * iter_next() calls are taken care of, we still need to be careful and 19236 * prevent erroneous and too eager declaration of "infinite loop", when 19237 * iterators are involved. 19238 * 19239 * Here's a situation in pseudo-BPF assembly form: 19240 * 19241 * 0: again: ; set up iter_next() call args 19242 * 1: r1 = &it ; <CHECKPOINT HERE> 19243 * 2: call bpf_iter_num_next ; this is iter_next() call 19244 * 3: if r0 == 0 goto done 19245 * 4: ... something useful here ... 19246 * 5: goto again ; another iteration 19247 * 6: done: 19248 * 7: r1 = &it 19249 * 8: call bpf_iter_num_destroy ; clean up iter state 19250 * 9: exit 19251 * 19252 * This is a typical loop. Let's assume that we have a prune point at 1:, 19253 * before we get to `call bpf_iter_num_next` (e.g., because of that `goto 19254 * again`, assuming other heuristics don't get in a way). 19255 * 19256 * When we first time come to 1:, let's say we have some state X. We proceed 19257 * to 2:, fork states, enqueue ACTIVE, validate NULL case successfully, exit. 19258 * Now we come back to validate that forked ACTIVE state. We proceed through 19259 * 3-5, come to goto, jump to 1:. Let's assume our state didn't change, so we 19260 * are converging. But the problem is that we don't know that yet, as this 19261 * convergence has to happen at iter_next() call site only. So if nothing is 19262 * done, at 1: verifier will use bounded loop logic and declare infinite 19263 * looping (and would be *technically* correct, if not for iterator's 19264 * "eventual sticky NULL" contract, see process_iter_next_call()). But we 19265 * don't want that. So what we do in process_iter_next_call() when we go on 19266 * another ACTIVE iteration, we bump slot->iter.depth, to mark that it's 19267 * a different iteration. So when we suspect an infinite loop, we additionally 19268 * check if any of the *ACTIVE* iterator states depths differ. If yes, we 19269 * pretend we are not looping and wait for next iter_next() call. 19270 * 19271 * This only applies to ACTIVE state. In DRAINED state we don't expect to 19272 * loop, because that would actually mean infinite loop, as DRAINED state is 19273 * "sticky", and so we'll keep returning into the same instruction with the 19274 * same state (at least in one of possible code paths). 19275 * 19276 * This approach allows to keep infinite loop heuristic even in the face of 19277 * active iterator. E.g., C snippet below is and will be detected as 19278 * infinitely looping: 19279 * 19280 * struct bpf_iter_num it; 19281 * int *p, x; 19282 * 19283 * bpf_iter_num_new(&it, 0, 10); 19284 * while ((p = bpf_iter_num_next(&t))) { 19285 * x = p; 19286 * while (x--) {} // <<-- infinite loop here 19287 * } 19288 * 19289 */ 19290 static bool iter_active_depths_differ(struct bpf_verifier_state *old, struct bpf_verifier_state *cur) 19291 { 19292 struct bpf_reg_state *slot, *cur_slot; 19293 struct bpf_func_state *state; 19294 int i, fr; 19295 19296 for (fr = old->curframe; fr >= 0; fr--) { 19297 state = old->frame[fr]; 19298 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) { 19299 if (state->stack[i].slot_type[0] != STACK_ITER) 19300 continue; 19301 19302 slot = &state->stack[i].spilled_ptr; 19303 if (slot->iter.state != BPF_ITER_STATE_ACTIVE) 19304 continue; 19305 19306 cur_slot = &cur->frame[fr]->stack[i].spilled_ptr; 19307 if (cur_slot->iter.depth != slot->iter.depth) 19308 return true; 19309 } 19310 } 19311 return false; 19312 } 19313 19314 static int is_state_visited(struct bpf_verifier_env *env, int insn_idx) 19315 { 19316 struct bpf_verifier_state_list *new_sl; 19317 struct bpf_verifier_state_list *sl; 19318 struct bpf_verifier_state *cur = env->cur_state, *new; 19319 bool force_new_state, add_new_state, loop; 19320 int i, j, n, err, states_cnt = 0; 19321 struct list_head *pos, *tmp, *head; 19322 19323 force_new_state = env->test_state_freq || is_force_checkpoint(env, insn_idx) || 19324 /* Avoid accumulating infinitely long jmp history */ 19325 cur->jmp_history_cnt > 40; 19326 19327 /* bpf progs typically have pruning point every 4 instructions 19328 * http://vger.kernel.org/bpfconf2019.html#session-1 19329 * Do not add new state for future pruning if the verifier hasn't seen 19330 * at least 2 jumps and at least 8 instructions. 19331 * This heuristics helps decrease 'total_states' and 'peak_states' metric. 19332 * In tests that amounts to up to 50% reduction into total verifier 19333 * memory consumption and 20% verifier time speedup. 19334 */ 19335 add_new_state = force_new_state; 19336 if (env->jmps_processed - env->prev_jmps_processed >= 2 && 19337 env->insn_processed - env->prev_insn_processed >= 8) 19338 add_new_state = true; 19339 19340 clean_live_states(env, insn_idx, cur); 19341 19342 loop = false; 19343 head = explored_state(env, insn_idx); 19344 list_for_each_safe(pos, tmp, head) { 19345 sl = container_of(pos, struct bpf_verifier_state_list, node); 19346 states_cnt++; 19347 if (sl->state.insn_idx != insn_idx) 19348 continue; 19349 19350 if (sl->state.branches) { 19351 struct bpf_func_state *frame = sl->state.frame[sl->state.curframe]; 19352 19353 if (frame->in_async_callback_fn && 19354 frame->async_entry_cnt != cur->frame[cur->curframe]->async_entry_cnt) { 19355 /* Different async_entry_cnt means that the verifier is 19356 * processing another entry into async callback. 19357 * Seeing the same state is not an indication of infinite 19358 * loop or infinite recursion. 19359 * But finding the same state doesn't mean that it's safe 19360 * to stop processing the current state. The previous state 19361 * hasn't yet reached bpf_exit, since state.branches > 0. 19362 * Checking in_async_callback_fn alone is not enough either. 19363 * Since the verifier still needs to catch infinite loops 19364 * inside async callbacks. 19365 */ 19366 goto skip_inf_loop_check; 19367 } 19368 /* BPF open-coded iterators loop detection is special. 19369 * states_maybe_looping() logic is too simplistic in detecting 19370 * states that *might* be equivalent, because it doesn't know 19371 * about ID remapping, so don't even perform it. 19372 * See process_iter_next_call() and iter_active_depths_differ() 19373 * for overview of the logic. When current and one of parent 19374 * states are detected as equivalent, it's a good thing: we prove 19375 * convergence and can stop simulating further iterations. 19376 * It's safe to assume that iterator loop will finish, taking into 19377 * account iter_next() contract of eventually returning 19378 * sticky NULL result. 19379 * 19380 * Note, that states have to be compared exactly in this case because 19381 * read and precision marks might not be finalized inside the loop. 19382 * E.g. as in the program below: 19383 * 19384 * 1. r7 = -16 19385 * 2. r6 = bpf_get_prandom_u32() 19386 * 3. while (bpf_iter_num_next(&fp[-8])) { 19387 * 4. if (r6 != 42) { 19388 * 5. r7 = -32 19389 * 6. r6 = bpf_get_prandom_u32() 19390 * 7. continue 19391 * 8. } 19392 * 9. r0 = r10 19393 * 10. r0 += r7 19394 * 11. r8 = *(u64 *)(r0 + 0) 19395 * 12. r6 = bpf_get_prandom_u32() 19396 * 13. } 19397 * 19398 * Here verifier would first visit path 1-3, create a checkpoint at 3 19399 * with r7=-16, continue to 4-7,3. Existing checkpoint at 3 does 19400 * not have read or precision mark for r7 yet, thus inexact states 19401 * comparison would discard current state with r7=-32 19402 * => unsafe memory access at 11 would not be caught. 19403 */ 19404 if (is_iter_next_insn(env, insn_idx)) { 19405 if (states_equal(env, &sl->state, cur, RANGE_WITHIN)) { 19406 struct bpf_func_state *cur_frame; 19407 struct bpf_reg_state *iter_state, *iter_reg; 19408 int spi; 19409 19410 cur_frame = cur->frame[cur->curframe]; 19411 /* btf_check_iter_kfuncs() enforces that 19412 * iter state pointer is always the first arg 19413 */ 19414 iter_reg = &cur_frame->regs[BPF_REG_1]; 19415 /* current state is valid due to states_equal(), 19416 * so we can assume valid iter and reg state, 19417 * no need for extra (re-)validations 19418 */ 19419 spi = __get_spi(iter_reg->off + iter_reg->var_off.value); 19420 iter_state = &func(env, iter_reg)->stack[spi].spilled_ptr; 19421 if (iter_state->iter.state == BPF_ITER_STATE_ACTIVE) { 19422 loop = true; 19423 goto hit; 19424 } 19425 } 19426 goto skip_inf_loop_check; 19427 } 19428 if (is_may_goto_insn_at(env, insn_idx)) { 19429 if (sl->state.may_goto_depth != cur->may_goto_depth && 19430 states_equal(env, &sl->state, cur, RANGE_WITHIN)) { 19431 loop = true; 19432 goto hit; 19433 } 19434 } 19435 if (calls_callback(env, insn_idx)) { 19436 if (states_equal(env, &sl->state, cur, RANGE_WITHIN)) 19437 goto hit; 19438 goto skip_inf_loop_check; 19439 } 19440 /* attempt to detect infinite loop to avoid unnecessary doomed work */ 19441 if (states_maybe_looping(&sl->state, cur) && 19442 states_equal(env, &sl->state, cur, EXACT) && 19443 !iter_active_depths_differ(&sl->state, cur) && 19444 sl->state.may_goto_depth == cur->may_goto_depth && 19445 sl->state.callback_unroll_depth == cur->callback_unroll_depth) { 19446 verbose_linfo(env, insn_idx, "; "); 19447 verbose(env, "infinite loop detected at insn %d\n", insn_idx); 19448 verbose(env, "cur state:"); 19449 print_verifier_state(env, cur, cur->curframe, true); 19450 verbose(env, "old state:"); 19451 print_verifier_state(env, &sl->state, cur->curframe, true); 19452 return -EINVAL; 19453 } 19454 /* if the verifier is processing a loop, avoid adding new state 19455 * too often, since different loop iterations have distinct 19456 * states and may not help future pruning. 19457 * This threshold shouldn't be too low to make sure that 19458 * a loop with large bound will be rejected quickly. 19459 * The most abusive loop will be: 19460 * r1 += 1 19461 * if r1 < 1000000 goto pc-2 19462 * 1M insn_procssed limit / 100 == 10k peak states. 19463 * This threshold shouldn't be too high either, since states 19464 * at the end of the loop are likely to be useful in pruning. 19465 */ 19466 skip_inf_loop_check: 19467 if (!force_new_state && 19468 env->jmps_processed - env->prev_jmps_processed < 20 && 19469 env->insn_processed - env->prev_insn_processed < 100) 19470 add_new_state = false; 19471 goto miss; 19472 } 19473 /* See comments for mark_all_regs_read_and_precise() */ 19474 loop = incomplete_read_marks(env, &sl->state); 19475 if (states_equal(env, &sl->state, cur, loop ? RANGE_WITHIN : NOT_EXACT)) { 19476 hit: 19477 sl->hit_cnt++; 19478 /* reached equivalent register/stack state, 19479 * prune the search. 19480 * Registers read by the continuation are read by us. 19481 * If we have any write marks in env->cur_state, they 19482 * will prevent corresponding reads in the continuation 19483 * from reaching our parent (an explored_state). Our 19484 * own state will get the read marks recorded, but 19485 * they'll be immediately forgotten as we're pruning 19486 * this state and will pop a new one. 19487 */ 19488 err = propagate_liveness(env, &sl->state, cur, NULL); 19489 19490 /* if previous state reached the exit with precision and 19491 * current state is equivalent to it (except precision marks) 19492 * the precision needs to be propagated back in 19493 * the current state. 19494 */ 19495 if (is_jmp_point(env, env->insn_idx)) 19496 err = err ? : push_jmp_history(env, cur, 0, 0); 19497 err = err ? : propagate_precision(env, &sl->state, cur, NULL); 19498 if (err) 19499 return err; 19500 /* When processing iterator based loops above propagate_liveness and 19501 * propagate_precision calls are not sufficient to transfer all relevant 19502 * read and precision marks. E.g. consider the following case: 19503 * 19504 * .-> A --. Assume the states are visited in the order A, B, C. 19505 * | | | Assume that state B reaches a state equivalent to state A. 19506 * | v v At this point, state C is not processed yet, so state A 19507 * '-- B C has not received any read or precision marks from C. 19508 * Thus, marks propagated from A to B are incomplete. 19509 * 19510 * The verifier mitigates this by performing the following steps: 19511 * 19512 * - Prior to the main verification pass, strongly connected components 19513 * (SCCs) are computed over the program's control flow graph, 19514 * intraprocedurally. 19515 * 19516 * - During the main verification pass, `maybe_enter_scc()` checks 19517 * whether the current verifier state is entering an SCC. If so, an 19518 * instance of a `bpf_scc_visit` object is created, and the state 19519 * entering the SCC is recorded as the entry state. 19520 * 19521 * - This instance is associated not with the SCC itself, but with a 19522 * `bpf_scc_callchain`: a tuple consisting of the call sites leading to 19523 * the SCC and the SCC id. See `compute_scc_callchain()`. 19524 * 19525 * - When a verification path encounters a `states_equal(..., 19526 * RANGE_WITHIN)` condition, there exists a call chain describing the 19527 * current state and a corresponding `bpf_scc_visit` instance. A copy 19528 * of the current state is created and added to 19529 * `bpf_scc_visit->backedges`. 19530 * 19531 * - When a verification path terminates, `maybe_exit_scc()` is called 19532 * from `update_branch_counts()`. For states with `branches == 0`, it 19533 * checks whether the state is the entry state of any `bpf_scc_visit` 19534 * instance. If it is, this indicates that all paths originating from 19535 * this SCC visit have been explored. `propagate_backedges()` is then 19536 * called, which propagates read and precision marks through the 19537 * backedges until a fixed point is reached. 19538 * (In the earlier example, this would propagate marks from A to B, 19539 * from C to A, and then again from A to B.) 19540 * 19541 * A note on callchains 19542 * -------------------- 19543 * 19544 * Consider the following example: 19545 * 19546 * void foo() { loop { ... SCC#1 ... } } 19547 * void main() { 19548 * A: foo(); 19549 * B: ... 19550 * C: foo(); 19551 * } 19552 * 19553 * Here, there are two distinct callchains leading to SCC#1: 19554 * - (A, SCC#1) 19555 * - (C, SCC#1) 19556 * 19557 * Each callchain identifies a separate `bpf_scc_visit` instance that 19558 * accumulates backedge states. The `propagate_{liveness,precision}()` 19559 * functions traverse the parent state of each backedge state, which 19560 * means these parent states must remain valid (i.e., not freed) while 19561 * the corresponding `bpf_scc_visit` instance exists. 19562 * 19563 * Associating `bpf_scc_visit` instances directly with SCCs instead of 19564 * callchains would break this invariant: 19565 * - States explored during `C: foo()` would contribute backedges to 19566 * SCC#1, but SCC#1 would only be exited once the exploration of 19567 * `A: foo()` completes. 19568 * - By that time, the states explored between `A: foo()` and `C: foo()` 19569 * (i.e., `B: ...`) may have already been freed, causing the parent 19570 * links for states from `C: foo()` to become invalid. 19571 */ 19572 if (loop) { 19573 struct bpf_scc_backedge *backedge; 19574 19575 backedge = kzalloc(sizeof(*backedge), GFP_KERNEL_ACCOUNT); 19576 if (!backedge) 19577 return -ENOMEM; 19578 err = copy_verifier_state(&backedge->state, cur); 19579 backedge->state.equal_state = &sl->state; 19580 backedge->state.insn_idx = insn_idx; 19581 err = err ?: add_scc_backedge(env, &sl->state, backedge); 19582 if (err) { 19583 free_verifier_state(&backedge->state, false); 19584 kvfree(backedge); 19585 return err; 19586 } 19587 } 19588 return 1; 19589 } 19590 miss: 19591 /* when new state is not going to be added do not increase miss count. 19592 * Otherwise several loop iterations will remove the state 19593 * recorded earlier. The goal of these heuristics is to have 19594 * states from some iterations of the loop (some in the beginning 19595 * and some at the end) to help pruning. 19596 */ 19597 if (add_new_state) 19598 sl->miss_cnt++; 19599 /* heuristic to determine whether this state is beneficial 19600 * to keep checking from state equivalence point of view. 19601 * Higher numbers increase max_states_per_insn and verification time, 19602 * but do not meaningfully decrease insn_processed. 19603 * 'n' controls how many times state could miss before eviction. 19604 * Use bigger 'n' for checkpoints because evicting checkpoint states 19605 * too early would hinder iterator convergence. 19606 */ 19607 n = is_force_checkpoint(env, insn_idx) && sl->state.branches > 0 ? 64 : 3; 19608 if (sl->miss_cnt > sl->hit_cnt * n + n) { 19609 /* the state is unlikely to be useful. Remove it to 19610 * speed up verification 19611 */ 19612 sl->in_free_list = true; 19613 list_del(&sl->node); 19614 list_add(&sl->node, &env->free_list); 19615 env->free_list_size++; 19616 env->explored_states_size--; 19617 maybe_free_verifier_state(env, sl); 19618 } 19619 } 19620 19621 if (env->max_states_per_insn < states_cnt) 19622 env->max_states_per_insn = states_cnt; 19623 19624 if (!env->bpf_capable && states_cnt > BPF_COMPLEXITY_LIMIT_STATES) 19625 return 0; 19626 19627 if (!add_new_state) 19628 return 0; 19629 19630 /* There were no equivalent states, remember the current one. 19631 * Technically the current state is not proven to be safe yet, 19632 * but it will either reach outer most bpf_exit (which means it's safe) 19633 * or it will be rejected. When there are no loops the verifier won't be 19634 * seeing this tuple (frame[0].callsite, frame[1].callsite, .. insn_idx) 19635 * again on the way to bpf_exit. 19636 * When looping the sl->state.branches will be > 0 and this state 19637 * will not be considered for equivalence until branches == 0. 19638 */ 19639 new_sl = kzalloc(sizeof(struct bpf_verifier_state_list), GFP_KERNEL_ACCOUNT); 19640 if (!new_sl) 19641 return -ENOMEM; 19642 env->total_states++; 19643 env->explored_states_size++; 19644 update_peak_states(env); 19645 env->prev_jmps_processed = env->jmps_processed; 19646 env->prev_insn_processed = env->insn_processed; 19647 19648 /* forget precise markings we inherited, see __mark_chain_precision */ 19649 if (env->bpf_capable) 19650 mark_all_scalars_imprecise(env, cur); 19651 19652 /* add new state to the head of linked list */ 19653 new = &new_sl->state; 19654 err = copy_verifier_state(new, cur); 19655 if (err) { 19656 free_verifier_state(new, false); 19657 kfree(new_sl); 19658 return err; 19659 } 19660 new->insn_idx = insn_idx; 19661 verifier_bug_if(new->branches != 1, env, 19662 "%s:branches_to_explore=%d insn %d", 19663 __func__, new->branches, insn_idx); 19664 err = maybe_enter_scc(env, new); 19665 if (err) { 19666 free_verifier_state(new, false); 19667 kvfree(new_sl); 19668 return err; 19669 } 19670 19671 cur->parent = new; 19672 cur->first_insn_idx = insn_idx; 19673 cur->dfs_depth = new->dfs_depth + 1; 19674 clear_jmp_history(cur); 19675 list_add(&new_sl->node, head); 19676 19677 /* connect new state to parentage chain. Current frame needs all 19678 * registers connected. Only r6 - r9 of the callers are alive (pushed 19679 * to the stack implicitly by JITs) so in callers' frames connect just 19680 * r6 - r9 as an optimization. Callers will have r1 - r5 connected to 19681 * the state of the call instruction (with WRITTEN set), and r0 comes 19682 * from callee with its full parentage chain, anyway. 19683 */ 19684 /* clear write marks in current state: the writes we did are not writes 19685 * our child did, so they don't screen off its reads from us. 19686 * (There are no read marks in current state, because reads always mark 19687 * their parent and current state never has children yet. Only 19688 * explored_states can get read marks.) 19689 */ 19690 for (j = 0; j <= cur->curframe; j++) { 19691 for (i = j < cur->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++) 19692 cur->frame[j]->regs[i].parent = &new->frame[j]->regs[i]; 19693 for (i = 0; i < BPF_REG_FP; i++) 19694 cur->frame[j]->regs[i].live = REG_LIVE_NONE; 19695 } 19696 19697 /* all stack frames are accessible from callee, clear them all */ 19698 for (j = 0; j <= cur->curframe; j++) { 19699 struct bpf_func_state *frame = cur->frame[j]; 19700 struct bpf_func_state *newframe = new->frame[j]; 19701 19702 for (i = 0; i < frame->allocated_stack / BPF_REG_SIZE; i++) { 19703 frame->stack[i].spilled_ptr.live = REG_LIVE_NONE; 19704 frame->stack[i].spilled_ptr.parent = 19705 &newframe->stack[i].spilled_ptr; 19706 } 19707 } 19708 return 0; 19709 } 19710 19711 /* Return true if it's OK to have the same insn return a different type. */ 19712 static bool reg_type_mismatch_ok(enum bpf_reg_type type) 19713 { 19714 switch (base_type(type)) { 19715 case PTR_TO_CTX: 19716 case PTR_TO_SOCKET: 19717 case PTR_TO_SOCK_COMMON: 19718 case PTR_TO_TCP_SOCK: 19719 case PTR_TO_XDP_SOCK: 19720 case PTR_TO_BTF_ID: 19721 case PTR_TO_ARENA: 19722 return false; 19723 default: 19724 return true; 19725 } 19726 } 19727 19728 /* If an instruction was previously used with particular pointer types, then we 19729 * need to be careful to avoid cases such as the below, where it may be ok 19730 * for one branch accessing the pointer, but not ok for the other branch: 19731 * 19732 * R1 = sock_ptr 19733 * goto X; 19734 * ... 19735 * R1 = some_other_valid_ptr; 19736 * goto X; 19737 * ... 19738 * R2 = *(u32 *)(R1 + 0); 19739 */ 19740 static bool reg_type_mismatch(enum bpf_reg_type src, enum bpf_reg_type prev) 19741 { 19742 return src != prev && (!reg_type_mismatch_ok(src) || 19743 !reg_type_mismatch_ok(prev)); 19744 } 19745 19746 static bool is_ptr_to_mem_or_btf_id(enum bpf_reg_type type) 19747 { 19748 switch (base_type(type)) { 19749 case PTR_TO_MEM: 19750 case PTR_TO_BTF_ID: 19751 return true; 19752 default: 19753 return false; 19754 } 19755 } 19756 19757 static bool is_ptr_to_mem(enum bpf_reg_type type) 19758 { 19759 return base_type(type) == PTR_TO_MEM; 19760 } 19761 19762 static int save_aux_ptr_type(struct bpf_verifier_env *env, enum bpf_reg_type type, 19763 bool allow_trust_mismatch) 19764 { 19765 enum bpf_reg_type *prev_type = &env->insn_aux_data[env->insn_idx].ptr_type; 19766 enum bpf_reg_type merged_type; 19767 19768 if (*prev_type == NOT_INIT) { 19769 /* Saw a valid insn 19770 * dst_reg = *(u32 *)(src_reg + off) 19771 * save type to validate intersecting paths 19772 */ 19773 *prev_type = type; 19774 } else if (reg_type_mismatch(type, *prev_type)) { 19775 /* Abuser program is trying to use the same insn 19776 * dst_reg = *(u32*) (src_reg + off) 19777 * with different pointer types: 19778 * src_reg == ctx in one branch and 19779 * src_reg == stack|map in some other branch. 19780 * Reject it. 19781 */ 19782 if (allow_trust_mismatch && 19783 is_ptr_to_mem_or_btf_id(type) && 19784 is_ptr_to_mem_or_btf_id(*prev_type)) { 19785 /* 19786 * Have to support a use case when one path through 19787 * the program yields TRUSTED pointer while another 19788 * is UNTRUSTED. Fallback to UNTRUSTED to generate 19789 * BPF_PROBE_MEM/BPF_PROBE_MEMSX. 19790 * Same behavior of MEM_RDONLY flag. 19791 */ 19792 if (is_ptr_to_mem(type) || is_ptr_to_mem(*prev_type)) 19793 merged_type = PTR_TO_MEM; 19794 else 19795 merged_type = PTR_TO_BTF_ID; 19796 if ((type & PTR_UNTRUSTED) || (*prev_type & PTR_UNTRUSTED)) 19797 merged_type |= PTR_UNTRUSTED; 19798 if ((type & MEM_RDONLY) || (*prev_type & MEM_RDONLY)) 19799 merged_type |= MEM_RDONLY; 19800 *prev_type = merged_type; 19801 } else { 19802 verbose(env, "same insn cannot be used with different pointers\n"); 19803 return -EINVAL; 19804 } 19805 } 19806 19807 return 0; 19808 } 19809 19810 enum { 19811 PROCESS_BPF_EXIT = 1 19812 }; 19813 19814 static int process_bpf_exit_full(struct bpf_verifier_env *env, 19815 bool *do_print_state, 19816 bool exception_exit) 19817 { 19818 /* We must do check_reference_leak here before 19819 * prepare_func_exit to handle the case when 19820 * state->curframe > 0, it may be a callback function, 19821 * for which reference_state must match caller reference 19822 * state when it exits. 19823 */ 19824 int err = check_resource_leak(env, exception_exit, 19825 !env->cur_state->curframe, 19826 "BPF_EXIT instruction in main prog"); 19827 if (err) 19828 return err; 19829 19830 /* The side effect of the prepare_func_exit which is 19831 * being skipped is that it frees bpf_func_state. 19832 * Typically, process_bpf_exit will only be hit with 19833 * outermost exit. copy_verifier_state in pop_stack will 19834 * handle freeing of any extra bpf_func_state left over 19835 * from not processing all nested function exits. We 19836 * also skip return code checks as they are not needed 19837 * for exceptional exits. 19838 */ 19839 if (exception_exit) 19840 return PROCESS_BPF_EXIT; 19841 19842 if (env->cur_state->curframe) { 19843 /* exit from nested function */ 19844 err = prepare_func_exit(env, &env->insn_idx); 19845 if (err) 19846 return err; 19847 *do_print_state = true; 19848 return 0; 19849 } 19850 19851 err = check_return_code(env, BPF_REG_0, "R0"); 19852 if (err) 19853 return err; 19854 return PROCESS_BPF_EXIT; 19855 } 19856 19857 static int do_check_insn(struct bpf_verifier_env *env, bool *do_print_state) 19858 { 19859 int err; 19860 struct bpf_insn *insn = &env->prog->insnsi[env->insn_idx]; 19861 u8 class = BPF_CLASS(insn->code); 19862 19863 if (class == BPF_ALU || class == BPF_ALU64) { 19864 err = check_alu_op(env, insn); 19865 if (err) 19866 return err; 19867 19868 } else if (class == BPF_LDX) { 19869 bool is_ldsx = BPF_MODE(insn->code) == BPF_MEMSX; 19870 19871 /* Check for reserved fields is already done in 19872 * resolve_pseudo_ldimm64(). 19873 */ 19874 err = check_load_mem(env, insn, false, is_ldsx, true, "ldx"); 19875 if (err) 19876 return err; 19877 } else if (class == BPF_STX) { 19878 if (BPF_MODE(insn->code) == BPF_ATOMIC) { 19879 err = check_atomic(env, insn); 19880 if (err) 19881 return err; 19882 env->insn_idx++; 19883 return 0; 19884 } 19885 19886 if (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0) { 19887 verbose(env, "BPF_STX uses reserved fields\n"); 19888 return -EINVAL; 19889 } 19890 19891 err = check_store_reg(env, insn, false); 19892 if (err) 19893 return err; 19894 } else if (class == BPF_ST) { 19895 enum bpf_reg_type dst_reg_type; 19896 19897 if (BPF_MODE(insn->code) != BPF_MEM || 19898 insn->src_reg != BPF_REG_0) { 19899 verbose(env, "BPF_ST uses reserved fields\n"); 19900 return -EINVAL; 19901 } 19902 /* check src operand */ 19903 err = check_reg_arg(env, insn->dst_reg, SRC_OP); 19904 if (err) 19905 return err; 19906 19907 dst_reg_type = cur_regs(env)[insn->dst_reg].type; 19908 19909 /* check that memory (dst_reg + off) is writeable */ 19910 err = check_mem_access(env, env->insn_idx, insn->dst_reg, 19911 insn->off, BPF_SIZE(insn->code), 19912 BPF_WRITE, -1, false, false); 19913 if (err) 19914 return err; 19915 19916 err = save_aux_ptr_type(env, dst_reg_type, false); 19917 if (err) 19918 return err; 19919 } else if (class == BPF_JMP || class == BPF_JMP32) { 19920 u8 opcode = BPF_OP(insn->code); 19921 19922 env->jmps_processed++; 19923 if (opcode == BPF_CALL) { 19924 if (BPF_SRC(insn->code) != BPF_K || 19925 (insn->src_reg != BPF_PSEUDO_KFUNC_CALL && 19926 insn->off != 0) || 19927 (insn->src_reg != BPF_REG_0 && 19928 insn->src_reg != BPF_PSEUDO_CALL && 19929 insn->src_reg != BPF_PSEUDO_KFUNC_CALL) || 19930 insn->dst_reg != BPF_REG_0 || class == BPF_JMP32) { 19931 verbose(env, "BPF_CALL uses reserved fields\n"); 19932 return -EINVAL; 19933 } 19934 19935 if (env->cur_state->active_locks) { 19936 if ((insn->src_reg == BPF_REG_0 && 19937 insn->imm != BPF_FUNC_spin_unlock) || 19938 (insn->src_reg == BPF_PSEUDO_KFUNC_CALL && 19939 (insn->off != 0 || !kfunc_spin_allowed(insn->imm)))) { 19940 verbose(env, 19941 "function calls are not allowed while holding a lock\n"); 19942 return -EINVAL; 19943 } 19944 } 19945 if (insn->src_reg == BPF_PSEUDO_CALL) { 19946 err = check_func_call(env, insn, &env->insn_idx); 19947 } else if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) { 19948 err = check_kfunc_call(env, insn, &env->insn_idx); 19949 if (!err && is_bpf_throw_kfunc(insn)) 19950 return process_bpf_exit_full(env, do_print_state, true); 19951 } else { 19952 err = check_helper_call(env, insn, &env->insn_idx); 19953 } 19954 if (err) 19955 return err; 19956 19957 mark_reg_scratched(env, BPF_REG_0); 19958 } else if (opcode == BPF_JA) { 19959 if (BPF_SRC(insn->code) != BPF_K || 19960 insn->src_reg != BPF_REG_0 || 19961 insn->dst_reg != BPF_REG_0 || 19962 (class == BPF_JMP && insn->imm != 0) || 19963 (class == BPF_JMP32 && insn->off != 0)) { 19964 verbose(env, "BPF_JA uses reserved fields\n"); 19965 return -EINVAL; 19966 } 19967 19968 if (class == BPF_JMP) 19969 env->insn_idx += insn->off + 1; 19970 else 19971 env->insn_idx += insn->imm + 1; 19972 return 0; 19973 } else if (opcode == BPF_EXIT) { 19974 if (BPF_SRC(insn->code) != BPF_K || 19975 insn->imm != 0 || 19976 insn->src_reg != BPF_REG_0 || 19977 insn->dst_reg != BPF_REG_0 || 19978 class == BPF_JMP32) { 19979 verbose(env, "BPF_EXIT uses reserved fields\n"); 19980 return -EINVAL; 19981 } 19982 return process_bpf_exit_full(env, do_print_state, false); 19983 } else { 19984 err = check_cond_jmp_op(env, insn, &env->insn_idx); 19985 if (err) 19986 return err; 19987 } 19988 } else if (class == BPF_LD) { 19989 u8 mode = BPF_MODE(insn->code); 19990 19991 if (mode == BPF_ABS || mode == BPF_IND) { 19992 err = check_ld_abs(env, insn); 19993 if (err) 19994 return err; 19995 19996 } else if (mode == BPF_IMM) { 19997 err = check_ld_imm(env, insn); 19998 if (err) 19999 return err; 20000 20001 env->insn_idx++; 20002 sanitize_mark_insn_seen(env); 20003 } else { 20004 verbose(env, "invalid BPF_LD mode\n"); 20005 return -EINVAL; 20006 } 20007 } else { 20008 verbose(env, "unknown insn class %d\n", class); 20009 return -EINVAL; 20010 } 20011 20012 env->insn_idx++; 20013 return 0; 20014 } 20015 20016 static int do_check(struct bpf_verifier_env *env) 20017 { 20018 bool pop_log = !(env->log.level & BPF_LOG_LEVEL2); 20019 struct bpf_verifier_state *state = env->cur_state; 20020 struct bpf_insn *insns = env->prog->insnsi; 20021 int insn_cnt = env->prog->len; 20022 bool do_print_state = false; 20023 int prev_insn_idx = -1; 20024 20025 for (;;) { 20026 struct bpf_insn *insn; 20027 struct bpf_insn_aux_data *insn_aux; 20028 int err; 20029 20030 /* reset current history entry on each new instruction */ 20031 env->cur_hist_ent = NULL; 20032 20033 env->prev_insn_idx = prev_insn_idx; 20034 if (env->insn_idx >= insn_cnt) { 20035 verbose(env, "invalid insn idx %d insn_cnt %d\n", 20036 env->insn_idx, insn_cnt); 20037 return -EFAULT; 20038 } 20039 20040 insn = &insns[env->insn_idx]; 20041 insn_aux = &env->insn_aux_data[env->insn_idx]; 20042 20043 if (++env->insn_processed > BPF_COMPLEXITY_LIMIT_INSNS) { 20044 verbose(env, 20045 "BPF program is too large. Processed %d insn\n", 20046 env->insn_processed); 20047 return -E2BIG; 20048 } 20049 20050 state->last_insn_idx = env->prev_insn_idx; 20051 state->insn_idx = env->insn_idx; 20052 20053 if (is_prune_point(env, env->insn_idx)) { 20054 err = is_state_visited(env, env->insn_idx); 20055 if (err < 0) 20056 return err; 20057 if (err == 1) { 20058 /* found equivalent state, can prune the search */ 20059 if (env->log.level & BPF_LOG_LEVEL) { 20060 if (do_print_state) 20061 verbose(env, "\nfrom %d to %d%s: safe\n", 20062 env->prev_insn_idx, env->insn_idx, 20063 env->cur_state->speculative ? 20064 " (speculative execution)" : ""); 20065 else 20066 verbose(env, "%d: safe\n", env->insn_idx); 20067 } 20068 goto process_bpf_exit; 20069 } 20070 } 20071 20072 if (is_jmp_point(env, env->insn_idx)) { 20073 err = push_jmp_history(env, state, 0, 0); 20074 if (err) 20075 return err; 20076 } 20077 20078 if (signal_pending(current)) 20079 return -EAGAIN; 20080 20081 if (need_resched()) 20082 cond_resched(); 20083 20084 if (env->log.level & BPF_LOG_LEVEL2 && do_print_state) { 20085 verbose(env, "\nfrom %d to %d%s:", 20086 env->prev_insn_idx, env->insn_idx, 20087 env->cur_state->speculative ? 20088 " (speculative execution)" : ""); 20089 print_verifier_state(env, state, state->curframe, true); 20090 do_print_state = false; 20091 } 20092 20093 if (env->log.level & BPF_LOG_LEVEL) { 20094 if (verifier_state_scratched(env)) 20095 print_insn_state(env, state, state->curframe); 20096 20097 verbose_linfo(env, env->insn_idx, "; "); 20098 env->prev_log_pos = env->log.end_pos; 20099 verbose(env, "%d: ", env->insn_idx); 20100 verbose_insn(env, insn); 20101 env->prev_insn_print_pos = env->log.end_pos - env->prev_log_pos; 20102 env->prev_log_pos = env->log.end_pos; 20103 } 20104 20105 if (bpf_prog_is_offloaded(env->prog->aux)) { 20106 err = bpf_prog_offload_verify_insn(env, env->insn_idx, 20107 env->prev_insn_idx); 20108 if (err) 20109 return err; 20110 } 20111 20112 sanitize_mark_insn_seen(env); 20113 prev_insn_idx = env->insn_idx; 20114 20115 /* Reduce verification complexity by stopping speculative path 20116 * verification when a nospec is encountered. 20117 */ 20118 if (state->speculative && insn_aux->nospec) 20119 goto process_bpf_exit; 20120 20121 err = do_check_insn(env, &do_print_state); 20122 if (error_recoverable_with_nospec(err) && state->speculative) { 20123 /* Prevent this speculative path from ever reaching the 20124 * insn that would have been unsafe to execute. 20125 */ 20126 insn_aux->nospec = true; 20127 /* If it was an ADD/SUB insn, potentially remove any 20128 * markings for alu sanitization. 20129 */ 20130 insn_aux->alu_state = 0; 20131 goto process_bpf_exit; 20132 } else if (err < 0) { 20133 return err; 20134 } else if (err == PROCESS_BPF_EXIT) { 20135 goto process_bpf_exit; 20136 } 20137 WARN_ON_ONCE(err); 20138 20139 if (state->speculative && insn_aux->nospec_result) { 20140 /* If we are on a path that performed a jump-op, this 20141 * may skip a nospec patched-in after the jump. This can 20142 * currently never happen because nospec_result is only 20143 * used for the write-ops 20144 * `*(size*)(dst_reg+off)=src_reg|imm32` which must 20145 * never skip the following insn. Still, add a warning 20146 * to document this in case nospec_result is used 20147 * elsewhere in the future. 20148 * 20149 * All non-branch instructions have a single 20150 * fall-through edge. For these, nospec_result should 20151 * already work. 20152 */ 20153 if (verifier_bug_if(BPF_CLASS(insn->code) == BPF_JMP || 20154 BPF_CLASS(insn->code) == BPF_JMP32, env, 20155 "speculation barrier after jump instruction may not have the desired effect")) 20156 return -EFAULT; 20157 process_bpf_exit: 20158 mark_verifier_state_scratched(env); 20159 err = update_branch_counts(env, env->cur_state); 20160 if (err) 20161 return err; 20162 err = pop_stack(env, &prev_insn_idx, &env->insn_idx, 20163 pop_log); 20164 if (err < 0) { 20165 if (err != -ENOENT) 20166 return err; 20167 break; 20168 } else { 20169 do_print_state = true; 20170 continue; 20171 } 20172 } 20173 } 20174 20175 return 0; 20176 } 20177 20178 static int find_btf_percpu_datasec(struct btf *btf) 20179 { 20180 const struct btf_type *t; 20181 const char *tname; 20182 int i, n; 20183 20184 /* 20185 * Both vmlinux and module each have their own ".data..percpu" 20186 * DATASECs in BTF. So for module's case, we need to skip vmlinux BTF 20187 * types to look at only module's own BTF types. 20188 */ 20189 n = btf_nr_types(btf); 20190 if (btf_is_module(btf)) 20191 i = btf_nr_types(btf_vmlinux); 20192 else 20193 i = 1; 20194 20195 for(; i < n; i++) { 20196 t = btf_type_by_id(btf, i); 20197 if (BTF_INFO_KIND(t->info) != BTF_KIND_DATASEC) 20198 continue; 20199 20200 tname = btf_name_by_offset(btf, t->name_off); 20201 if (!strcmp(tname, ".data..percpu")) 20202 return i; 20203 } 20204 20205 return -ENOENT; 20206 } 20207 20208 /* 20209 * Add btf to the used_btfs array and return the index. (If the btf was 20210 * already added, then just return the index.) Upon successful insertion 20211 * increase btf refcnt, and, if present, also refcount the corresponding 20212 * kernel module. 20213 */ 20214 static int __add_used_btf(struct bpf_verifier_env *env, struct btf *btf) 20215 { 20216 struct btf_mod_pair *btf_mod; 20217 int i; 20218 20219 /* check whether we recorded this BTF (and maybe module) already */ 20220 for (i = 0; i < env->used_btf_cnt; i++) 20221 if (env->used_btfs[i].btf == btf) 20222 return i; 20223 20224 if (env->used_btf_cnt >= MAX_USED_BTFS) 20225 return -E2BIG; 20226 20227 btf_get(btf); 20228 20229 btf_mod = &env->used_btfs[env->used_btf_cnt]; 20230 btf_mod->btf = btf; 20231 btf_mod->module = NULL; 20232 20233 /* if we reference variables from kernel module, bump its refcount */ 20234 if (btf_is_module(btf)) { 20235 btf_mod->module = btf_try_get_module(btf); 20236 if (!btf_mod->module) { 20237 btf_put(btf); 20238 return -ENXIO; 20239 } 20240 } 20241 20242 return env->used_btf_cnt++; 20243 } 20244 20245 /* replace pseudo btf_id with kernel symbol address */ 20246 static int __check_pseudo_btf_id(struct bpf_verifier_env *env, 20247 struct bpf_insn *insn, 20248 struct bpf_insn_aux_data *aux, 20249 struct btf *btf) 20250 { 20251 const struct btf_var_secinfo *vsi; 20252 const struct btf_type *datasec; 20253 const struct btf_type *t; 20254 const char *sym_name; 20255 bool percpu = false; 20256 u32 type, id = insn->imm; 20257 s32 datasec_id; 20258 u64 addr; 20259 int i; 20260 20261 t = btf_type_by_id(btf, id); 20262 if (!t) { 20263 verbose(env, "ldimm64 insn specifies invalid btf_id %d.\n", id); 20264 return -ENOENT; 20265 } 20266 20267 if (!btf_type_is_var(t) && !btf_type_is_func(t)) { 20268 verbose(env, "pseudo btf_id %d in ldimm64 isn't KIND_VAR or KIND_FUNC\n", id); 20269 return -EINVAL; 20270 } 20271 20272 sym_name = btf_name_by_offset(btf, t->name_off); 20273 addr = kallsyms_lookup_name(sym_name); 20274 if (!addr) { 20275 verbose(env, "ldimm64 failed to find the address for kernel symbol '%s'.\n", 20276 sym_name); 20277 return -ENOENT; 20278 } 20279 insn[0].imm = (u32)addr; 20280 insn[1].imm = addr >> 32; 20281 20282 if (btf_type_is_func(t)) { 20283 aux->btf_var.reg_type = PTR_TO_MEM | MEM_RDONLY; 20284 aux->btf_var.mem_size = 0; 20285 return 0; 20286 } 20287 20288 datasec_id = find_btf_percpu_datasec(btf); 20289 if (datasec_id > 0) { 20290 datasec = btf_type_by_id(btf, datasec_id); 20291 for_each_vsi(i, datasec, vsi) { 20292 if (vsi->type == id) { 20293 percpu = true; 20294 break; 20295 } 20296 } 20297 } 20298 20299 type = t->type; 20300 t = btf_type_skip_modifiers(btf, type, NULL); 20301 if (percpu) { 20302 aux->btf_var.reg_type = PTR_TO_BTF_ID | MEM_PERCPU; 20303 aux->btf_var.btf = btf; 20304 aux->btf_var.btf_id = type; 20305 } else if (!btf_type_is_struct(t)) { 20306 const struct btf_type *ret; 20307 const char *tname; 20308 u32 tsize; 20309 20310 /* resolve the type size of ksym. */ 20311 ret = btf_resolve_size(btf, t, &tsize); 20312 if (IS_ERR(ret)) { 20313 tname = btf_name_by_offset(btf, t->name_off); 20314 verbose(env, "ldimm64 unable to resolve the size of type '%s': %ld\n", 20315 tname, PTR_ERR(ret)); 20316 return -EINVAL; 20317 } 20318 aux->btf_var.reg_type = PTR_TO_MEM | MEM_RDONLY; 20319 aux->btf_var.mem_size = tsize; 20320 } else { 20321 aux->btf_var.reg_type = PTR_TO_BTF_ID; 20322 aux->btf_var.btf = btf; 20323 aux->btf_var.btf_id = type; 20324 } 20325 20326 return 0; 20327 } 20328 20329 static int check_pseudo_btf_id(struct bpf_verifier_env *env, 20330 struct bpf_insn *insn, 20331 struct bpf_insn_aux_data *aux) 20332 { 20333 struct btf *btf; 20334 int btf_fd; 20335 int err; 20336 20337 btf_fd = insn[1].imm; 20338 if (btf_fd) { 20339 CLASS(fd, f)(btf_fd); 20340 20341 btf = __btf_get_by_fd(f); 20342 if (IS_ERR(btf)) { 20343 verbose(env, "invalid module BTF object FD specified.\n"); 20344 return -EINVAL; 20345 } 20346 } else { 20347 if (!btf_vmlinux) { 20348 verbose(env, "kernel is missing BTF, make sure CONFIG_DEBUG_INFO_BTF=y is specified in Kconfig.\n"); 20349 return -EINVAL; 20350 } 20351 btf = btf_vmlinux; 20352 } 20353 20354 err = __check_pseudo_btf_id(env, insn, aux, btf); 20355 if (err) 20356 return err; 20357 20358 err = __add_used_btf(env, btf); 20359 if (err < 0) 20360 return err; 20361 return 0; 20362 } 20363 20364 static bool is_tracing_prog_type(enum bpf_prog_type type) 20365 { 20366 switch (type) { 20367 case BPF_PROG_TYPE_KPROBE: 20368 case BPF_PROG_TYPE_TRACEPOINT: 20369 case BPF_PROG_TYPE_PERF_EVENT: 20370 case BPF_PROG_TYPE_RAW_TRACEPOINT: 20371 case BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE: 20372 return true; 20373 default: 20374 return false; 20375 } 20376 } 20377 20378 static bool bpf_map_is_cgroup_storage(struct bpf_map *map) 20379 { 20380 return (map->map_type == BPF_MAP_TYPE_CGROUP_STORAGE || 20381 map->map_type == BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE); 20382 } 20383 20384 static int check_map_prog_compatibility(struct bpf_verifier_env *env, 20385 struct bpf_map *map, 20386 struct bpf_prog *prog) 20387 20388 { 20389 enum bpf_prog_type prog_type = resolve_prog_type(prog); 20390 20391 if (btf_record_has_field(map->record, BPF_LIST_HEAD) || 20392 btf_record_has_field(map->record, BPF_RB_ROOT)) { 20393 if (is_tracing_prog_type(prog_type)) { 20394 verbose(env, "tracing progs cannot use bpf_{list_head,rb_root} yet\n"); 20395 return -EINVAL; 20396 } 20397 } 20398 20399 if (btf_record_has_field(map->record, BPF_SPIN_LOCK | BPF_RES_SPIN_LOCK)) { 20400 if (prog_type == BPF_PROG_TYPE_SOCKET_FILTER) { 20401 verbose(env, "socket filter progs cannot use bpf_spin_lock yet\n"); 20402 return -EINVAL; 20403 } 20404 20405 if (is_tracing_prog_type(prog_type)) { 20406 verbose(env, "tracing progs cannot use bpf_spin_lock yet\n"); 20407 return -EINVAL; 20408 } 20409 } 20410 20411 if (btf_record_has_field(map->record, BPF_TIMER)) { 20412 if (is_tracing_prog_type(prog_type)) { 20413 verbose(env, "tracing progs cannot use bpf_timer yet\n"); 20414 return -EINVAL; 20415 } 20416 } 20417 20418 if (btf_record_has_field(map->record, BPF_WORKQUEUE)) { 20419 if (is_tracing_prog_type(prog_type)) { 20420 verbose(env, "tracing progs cannot use bpf_wq yet\n"); 20421 return -EINVAL; 20422 } 20423 } 20424 20425 if ((bpf_prog_is_offloaded(prog->aux) || bpf_map_is_offloaded(map)) && 20426 !bpf_offload_prog_map_match(prog, map)) { 20427 verbose(env, "offload device mismatch between prog and map\n"); 20428 return -EINVAL; 20429 } 20430 20431 if (map->map_type == BPF_MAP_TYPE_STRUCT_OPS) { 20432 verbose(env, "bpf_struct_ops map cannot be used in prog\n"); 20433 return -EINVAL; 20434 } 20435 20436 if (prog->sleepable) 20437 switch (map->map_type) { 20438 case BPF_MAP_TYPE_HASH: 20439 case BPF_MAP_TYPE_LRU_HASH: 20440 case BPF_MAP_TYPE_ARRAY: 20441 case BPF_MAP_TYPE_PERCPU_HASH: 20442 case BPF_MAP_TYPE_PERCPU_ARRAY: 20443 case BPF_MAP_TYPE_LRU_PERCPU_HASH: 20444 case BPF_MAP_TYPE_ARRAY_OF_MAPS: 20445 case BPF_MAP_TYPE_HASH_OF_MAPS: 20446 case BPF_MAP_TYPE_RINGBUF: 20447 case BPF_MAP_TYPE_USER_RINGBUF: 20448 case BPF_MAP_TYPE_INODE_STORAGE: 20449 case BPF_MAP_TYPE_SK_STORAGE: 20450 case BPF_MAP_TYPE_TASK_STORAGE: 20451 case BPF_MAP_TYPE_CGRP_STORAGE: 20452 case BPF_MAP_TYPE_QUEUE: 20453 case BPF_MAP_TYPE_STACK: 20454 case BPF_MAP_TYPE_ARENA: 20455 break; 20456 default: 20457 verbose(env, 20458 "Sleepable programs can only use array, hash, ringbuf and local storage maps\n"); 20459 return -EINVAL; 20460 } 20461 20462 if (bpf_map_is_cgroup_storage(map) && 20463 bpf_cgroup_storage_assign(env->prog->aux, map)) { 20464 verbose(env, "only one cgroup storage of each type is allowed\n"); 20465 return -EBUSY; 20466 } 20467 20468 if (map->map_type == BPF_MAP_TYPE_ARENA) { 20469 if (env->prog->aux->arena) { 20470 verbose(env, "Only one arena per program\n"); 20471 return -EBUSY; 20472 } 20473 if (!env->allow_ptr_leaks || !env->bpf_capable) { 20474 verbose(env, "CAP_BPF and CAP_PERFMON are required to use arena\n"); 20475 return -EPERM; 20476 } 20477 if (!env->prog->jit_requested) { 20478 verbose(env, "JIT is required to use arena\n"); 20479 return -EOPNOTSUPP; 20480 } 20481 if (!bpf_jit_supports_arena()) { 20482 verbose(env, "JIT doesn't support arena\n"); 20483 return -EOPNOTSUPP; 20484 } 20485 env->prog->aux->arena = (void *)map; 20486 if (!bpf_arena_get_user_vm_start(env->prog->aux->arena)) { 20487 verbose(env, "arena's user address must be set via map_extra or mmap()\n"); 20488 return -EINVAL; 20489 } 20490 } 20491 20492 return 0; 20493 } 20494 20495 static int __add_used_map(struct bpf_verifier_env *env, struct bpf_map *map) 20496 { 20497 int i, err; 20498 20499 /* check whether we recorded this map already */ 20500 for (i = 0; i < env->used_map_cnt; i++) 20501 if (env->used_maps[i] == map) 20502 return i; 20503 20504 if (env->used_map_cnt >= MAX_USED_MAPS) { 20505 verbose(env, "The total number of maps per program has reached the limit of %u\n", 20506 MAX_USED_MAPS); 20507 return -E2BIG; 20508 } 20509 20510 err = check_map_prog_compatibility(env, map, env->prog); 20511 if (err) 20512 return err; 20513 20514 if (env->prog->sleepable) 20515 atomic64_inc(&map->sleepable_refcnt); 20516 20517 /* hold the map. If the program is rejected by verifier, 20518 * the map will be released by release_maps() or it 20519 * will be used by the valid program until it's unloaded 20520 * and all maps are released in bpf_free_used_maps() 20521 */ 20522 bpf_map_inc(map); 20523 20524 env->used_maps[env->used_map_cnt++] = map; 20525 20526 return env->used_map_cnt - 1; 20527 } 20528 20529 /* Add map behind fd to used maps list, if it's not already there, and return 20530 * its index. 20531 * Returns <0 on error, or >= 0 index, on success. 20532 */ 20533 static int add_used_map(struct bpf_verifier_env *env, int fd) 20534 { 20535 struct bpf_map *map; 20536 CLASS(fd, f)(fd); 20537 20538 map = __bpf_map_get(f); 20539 if (IS_ERR(map)) { 20540 verbose(env, "fd %d is not pointing to valid bpf_map\n", fd); 20541 return PTR_ERR(map); 20542 } 20543 20544 return __add_used_map(env, map); 20545 } 20546 20547 /* find and rewrite pseudo imm in ld_imm64 instructions: 20548 * 20549 * 1. if it accesses map FD, replace it with actual map pointer. 20550 * 2. if it accesses btf_id of a VAR, replace it with pointer to the var. 20551 * 20552 * NOTE: btf_vmlinux is required for converting pseudo btf_id. 20553 */ 20554 static int resolve_pseudo_ldimm64(struct bpf_verifier_env *env) 20555 { 20556 struct bpf_insn *insn = env->prog->insnsi; 20557 int insn_cnt = env->prog->len; 20558 int i, err; 20559 20560 err = bpf_prog_calc_tag(env->prog); 20561 if (err) 20562 return err; 20563 20564 for (i = 0; i < insn_cnt; i++, insn++) { 20565 if (BPF_CLASS(insn->code) == BPF_LDX && 20566 ((BPF_MODE(insn->code) != BPF_MEM && BPF_MODE(insn->code) != BPF_MEMSX) || 20567 insn->imm != 0)) { 20568 verbose(env, "BPF_LDX uses reserved fields\n"); 20569 return -EINVAL; 20570 } 20571 20572 if (insn[0].code == (BPF_LD | BPF_IMM | BPF_DW)) { 20573 struct bpf_insn_aux_data *aux; 20574 struct bpf_map *map; 20575 int map_idx; 20576 u64 addr; 20577 u32 fd; 20578 20579 if (i == insn_cnt - 1 || insn[1].code != 0 || 20580 insn[1].dst_reg != 0 || insn[1].src_reg != 0 || 20581 insn[1].off != 0) { 20582 verbose(env, "invalid bpf_ld_imm64 insn\n"); 20583 return -EINVAL; 20584 } 20585 20586 if (insn[0].src_reg == 0) 20587 /* valid generic load 64-bit imm */ 20588 goto next_insn; 20589 20590 if (insn[0].src_reg == BPF_PSEUDO_BTF_ID) { 20591 aux = &env->insn_aux_data[i]; 20592 err = check_pseudo_btf_id(env, insn, aux); 20593 if (err) 20594 return err; 20595 goto next_insn; 20596 } 20597 20598 if (insn[0].src_reg == BPF_PSEUDO_FUNC) { 20599 aux = &env->insn_aux_data[i]; 20600 aux->ptr_type = PTR_TO_FUNC; 20601 goto next_insn; 20602 } 20603 20604 /* In final convert_pseudo_ld_imm64() step, this is 20605 * converted into regular 64-bit imm load insn. 20606 */ 20607 switch (insn[0].src_reg) { 20608 case BPF_PSEUDO_MAP_VALUE: 20609 case BPF_PSEUDO_MAP_IDX_VALUE: 20610 break; 20611 case BPF_PSEUDO_MAP_FD: 20612 case BPF_PSEUDO_MAP_IDX: 20613 if (insn[1].imm == 0) 20614 break; 20615 fallthrough; 20616 default: 20617 verbose(env, "unrecognized bpf_ld_imm64 insn\n"); 20618 return -EINVAL; 20619 } 20620 20621 switch (insn[0].src_reg) { 20622 case BPF_PSEUDO_MAP_IDX_VALUE: 20623 case BPF_PSEUDO_MAP_IDX: 20624 if (bpfptr_is_null(env->fd_array)) { 20625 verbose(env, "fd_idx without fd_array is invalid\n"); 20626 return -EPROTO; 20627 } 20628 if (copy_from_bpfptr_offset(&fd, env->fd_array, 20629 insn[0].imm * sizeof(fd), 20630 sizeof(fd))) 20631 return -EFAULT; 20632 break; 20633 default: 20634 fd = insn[0].imm; 20635 break; 20636 } 20637 20638 map_idx = add_used_map(env, fd); 20639 if (map_idx < 0) 20640 return map_idx; 20641 map = env->used_maps[map_idx]; 20642 20643 aux = &env->insn_aux_data[i]; 20644 aux->map_index = map_idx; 20645 20646 if (insn[0].src_reg == BPF_PSEUDO_MAP_FD || 20647 insn[0].src_reg == BPF_PSEUDO_MAP_IDX) { 20648 addr = (unsigned long)map; 20649 } else { 20650 u32 off = insn[1].imm; 20651 20652 if (off >= BPF_MAX_VAR_OFF) { 20653 verbose(env, "direct value offset of %u is not allowed\n", off); 20654 return -EINVAL; 20655 } 20656 20657 if (!map->ops->map_direct_value_addr) { 20658 verbose(env, "no direct value access support for this map type\n"); 20659 return -EINVAL; 20660 } 20661 20662 err = map->ops->map_direct_value_addr(map, &addr, off); 20663 if (err) { 20664 verbose(env, "invalid access to map value pointer, value_size=%u off=%u\n", 20665 map->value_size, off); 20666 return err; 20667 } 20668 20669 aux->map_off = off; 20670 addr += off; 20671 } 20672 20673 insn[0].imm = (u32)addr; 20674 insn[1].imm = addr >> 32; 20675 20676 next_insn: 20677 insn++; 20678 i++; 20679 continue; 20680 } 20681 20682 /* Basic sanity check before we invest more work here. */ 20683 if (!bpf_opcode_in_insntable(insn->code)) { 20684 verbose(env, "unknown opcode %02x\n", insn->code); 20685 return -EINVAL; 20686 } 20687 } 20688 20689 /* now all pseudo BPF_LD_IMM64 instructions load valid 20690 * 'struct bpf_map *' into a register instead of user map_fd. 20691 * These pointers will be used later by verifier to validate map access. 20692 */ 20693 return 0; 20694 } 20695 20696 /* drop refcnt of maps used by the rejected program */ 20697 static void release_maps(struct bpf_verifier_env *env) 20698 { 20699 __bpf_free_used_maps(env->prog->aux, env->used_maps, 20700 env->used_map_cnt); 20701 } 20702 20703 /* drop refcnt of maps used by the rejected program */ 20704 static void release_btfs(struct bpf_verifier_env *env) 20705 { 20706 __bpf_free_used_btfs(env->used_btfs, env->used_btf_cnt); 20707 } 20708 20709 /* convert pseudo BPF_LD_IMM64 into generic BPF_LD_IMM64 */ 20710 static void convert_pseudo_ld_imm64(struct bpf_verifier_env *env) 20711 { 20712 struct bpf_insn *insn = env->prog->insnsi; 20713 int insn_cnt = env->prog->len; 20714 int i; 20715 20716 for (i = 0; i < insn_cnt; i++, insn++) { 20717 if (insn->code != (BPF_LD | BPF_IMM | BPF_DW)) 20718 continue; 20719 if (insn->src_reg == BPF_PSEUDO_FUNC) 20720 continue; 20721 insn->src_reg = 0; 20722 } 20723 } 20724 20725 /* single env->prog->insni[off] instruction was replaced with the range 20726 * insni[off, off + cnt). Adjust corresponding insn_aux_data by copying 20727 * [0, off) and [off, end) to new locations, so the patched range stays zero 20728 */ 20729 static void adjust_insn_aux_data(struct bpf_verifier_env *env, 20730 struct bpf_insn_aux_data *new_data, 20731 struct bpf_prog *new_prog, u32 off, u32 cnt) 20732 { 20733 struct bpf_insn_aux_data *old_data = env->insn_aux_data; 20734 struct bpf_insn *insn = new_prog->insnsi; 20735 u32 old_seen = old_data[off].seen; 20736 u32 prog_len; 20737 int i; 20738 20739 /* aux info at OFF always needs adjustment, no matter fast path 20740 * (cnt == 1) is taken or not. There is no guarantee INSN at OFF is the 20741 * original insn at old prog. 20742 */ 20743 old_data[off].zext_dst = insn_has_def32(env, insn + off + cnt - 1); 20744 20745 if (cnt == 1) 20746 return; 20747 prog_len = new_prog->len; 20748 20749 memcpy(new_data, old_data, sizeof(struct bpf_insn_aux_data) * off); 20750 memcpy(new_data + off + cnt - 1, old_data + off, 20751 sizeof(struct bpf_insn_aux_data) * (prog_len - off - cnt + 1)); 20752 for (i = off; i < off + cnt - 1; i++) { 20753 /* Expand insni[off]'s seen count to the patched range. */ 20754 new_data[i].seen = old_seen; 20755 new_data[i].zext_dst = insn_has_def32(env, insn + i); 20756 } 20757 env->insn_aux_data = new_data; 20758 vfree(old_data); 20759 } 20760 20761 static void adjust_subprog_starts(struct bpf_verifier_env *env, u32 off, u32 len) 20762 { 20763 int i; 20764 20765 if (len == 1) 20766 return; 20767 /* NOTE: fake 'exit' subprog should be updated as well. */ 20768 for (i = 0; i <= env->subprog_cnt; i++) { 20769 if (env->subprog_info[i].start <= off) 20770 continue; 20771 env->subprog_info[i].start += len - 1; 20772 } 20773 } 20774 20775 static void adjust_poke_descs(struct bpf_prog *prog, u32 off, u32 len) 20776 { 20777 struct bpf_jit_poke_descriptor *tab = prog->aux->poke_tab; 20778 int i, sz = prog->aux->size_poke_tab; 20779 struct bpf_jit_poke_descriptor *desc; 20780 20781 for (i = 0; i < sz; i++) { 20782 desc = &tab[i]; 20783 if (desc->insn_idx <= off) 20784 continue; 20785 desc->insn_idx += len - 1; 20786 } 20787 } 20788 20789 static struct bpf_prog *bpf_patch_insn_data(struct bpf_verifier_env *env, u32 off, 20790 const struct bpf_insn *patch, u32 len) 20791 { 20792 struct bpf_prog *new_prog; 20793 struct bpf_insn_aux_data *new_data = NULL; 20794 20795 if (len > 1) { 20796 new_data = vzalloc(array_size(env->prog->len + len - 1, 20797 sizeof(struct bpf_insn_aux_data))); 20798 if (!new_data) 20799 return NULL; 20800 } 20801 20802 new_prog = bpf_patch_insn_single(env->prog, off, patch, len); 20803 if (IS_ERR(new_prog)) { 20804 if (PTR_ERR(new_prog) == -ERANGE) 20805 verbose(env, 20806 "insn %d cannot be patched due to 16-bit range\n", 20807 env->insn_aux_data[off].orig_idx); 20808 vfree(new_data); 20809 return NULL; 20810 } 20811 adjust_insn_aux_data(env, new_data, new_prog, off, len); 20812 adjust_subprog_starts(env, off, len); 20813 adjust_poke_descs(new_prog, off, len); 20814 return new_prog; 20815 } 20816 20817 /* 20818 * For all jmp insns in a given 'prog' that point to 'tgt_idx' insn adjust the 20819 * jump offset by 'delta'. 20820 */ 20821 static int adjust_jmp_off(struct bpf_prog *prog, u32 tgt_idx, u32 delta) 20822 { 20823 struct bpf_insn *insn = prog->insnsi; 20824 u32 insn_cnt = prog->len, i; 20825 s32 imm; 20826 s16 off; 20827 20828 for (i = 0; i < insn_cnt; i++, insn++) { 20829 u8 code = insn->code; 20830 20831 if (tgt_idx <= i && i < tgt_idx + delta) 20832 continue; 20833 20834 if ((BPF_CLASS(code) != BPF_JMP && BPF_CLASS(code) != BPF_JMP32) || 20835 BPF_OP(code) == BPF_CALL || BPF_OP(code) == BPF_EXIT) 20836 continue; 20837 20838 if (insn->code == (BPF_JMP32 | BPF_JA)) { 20839 if (i + 1 + insn->imm != tgt_idx) 20840 continue; 20841 if (check_add_overflow(insn->imm, delta, &imm)) 20842 return -ERANGE; 20843 insn->imm = imm; 20844 } else { 20845 if (i + 1 + insn->off != tgt_idx) 20846 continue; 20847 if (check_add_overflow(insn->off, delta, &off)) 20848 return -ERANGE; 20849 insn->off = off; 20850 } 20851 } 20852 return 0; 20853 } 20854 20855 static int adjust_subprog_starts_after_remove(struct bpf_verifier_env *env, 20856 u32 off, u32 cnt) 20857 { 20858 int i, j; 20859 20860 /* find first prog starting at or after off (first to remove) */ 20861 for (i = 0; i < env->subprog_cnt; i++) 20862 if (env->subprog_info[i].start >= off) 20863 break; 20864 /* find first prog starting at or after off + cnt (first to stay) */ 20865 for (j = i; j < env->subprog_cnt; j++) 20866 if (env->subprog_info[j].start >= off + cnt) 20867 break; 20868 /* if j doesn't start exactly at off + cnt, we are just removing 20869 * the front of previous prog 20870 */ 20871 if (env->subprog_info[j].start != off + cnt) 20872 j--; 20873 20874 if (j > i) { 20875 struct bpf_prog_aux *aux = env->prog->aux; 20876 int move; 20877 20878 /* move fake 'exit' subprog as well */ 20879 move = env->subprog_cnt + 1 - j; 20880 20881 memmove(env->subprog_info + i, 20882 env->subprog_info + j, 20883 sizeof(*env->subprog_info) * move); 20884 env->subprog_cnt -= j - i; 20885 20886 /* remove func_info */ 20887 if (aux->func_info) { 20888 move = aux->func_info_cnt - j; 20889 20890 memmove(aux->func_info + i, 20891 aux->func_info + j, 20892 sizeof(*aux->func_info) * move); 20893 aux->func_info_cnt -= j - i; 20894 /* func_info->insn_off is set after all code rewrites, 20895 * in adjust_btf_func() - no need to adjust 20896 */ 20897 } 20898 } else { 20899 /* convert i from "first prog to remove" to "first to adjust" */ 20900 if (env->subprog_info[i].start == off) 20901 i++; 20902 } 20903 20904 /* update fake 'exit' subprog as well */ 20905 for (; i <= env->subprog_cnt; i++) 20906 env->subprog_info[i].start -= cnt; 20907 20908 return 0; 20909 } 20910 20911 static int bpf_adj_linfo_after_remove(struct bpf_verifier_env *env, u32 off, 20912 u32 cnt) 20913 { 20914 struct bpf_prog *prog = env->prog; 20915 u32 i, l_off, l_cnt, nr_linfo; 20916 struct bpf_line_info *linfo; 20917 20918 nr_linfo = prog->aux->nr_linfo; 20919 if (!nr_linfo) 20920 return 0; 20921 20922 linfo = prog->aux->linfo; 20923 20924 /* find first line info to remove, count lines to be removed */ 20925 for (i = 0; i < nr_linfo; i++) 20926 if (linfo[i].insn_off >= off) 20927 break; 20928 20929 l_off = i; 20930 l_cnt = 0; 20931 for (; i < nr_linfo; i++) 20932 if (linfo[i].insn_off < off + cnt) 20933 l_cnt++; 20934 else 20935 break; 20936 20937 /* First live insn doesn't match first live linfo, it needs to "inherit" 20938 * last removed linfo. prog is already modified, so prog->len == off 20939 * means no live instructions after (tail of the program was removed). 20940 */ 20941 if (prog->len != off && l_cnt && 20942 (i == nr_linfo || linfo[i].insn_off != off + cnt)) { 20943 l_cnt--; 20944 linfo[--i].insn_off = off + cnt; 20945 } 20946 20947 /* remove the line info which refer to the removed instructions */ 20948 if (l_cnt) { 20949 memmove(linfo + l_off, linfo + i, 20950 sizeof(*linfo) * (nr_linfo - i)); 20951 20952 prog->aux->nr_linfo -= l_cnt; 20953 nr_linfo = prog->aux->nr_linfo; 20954 } 20955 20956 /* pull all linfo[i].insn_off >= off + cnt in by cnt */ 20957 for (i = l_off; i < nr_linfo; i++) 20958 linfo[i].insn_off -= cnt; 20959 20960 /* fix up all subprogs (incl. 'exit') which start >= off */ 20961 for (i = 0; i <= env->subprog_cnt; i++) 20962 if (env->subprog_info[i].linfo_idx > l_off) { 20963 /* program may have started in the removed region but 20964 * may not be fully removed 20965 */ 20966 if (env->subprog_info[i].linfo_idx >= l_off + l_cnt) 20967 env->subprog_info[i].linfo_idx -= l_cnt; 20968 else 20969 env->subprog_info[i].linfo_idx = l_off; 20970 } 20971 20972 return 0; 20973 } 20974 20975 static int verifier_remove_insns(struct bpf_verifier_env *env, u32 off, u32 cnt) 20976 { 20977 struct bpf_insn_aux_data *aux_data = env->insn_aux_data; 20978 unsigned int orig_prog_len = env->prog->len; 20979 int err; 20980 20981 if (bpf_prog_is_offloaded(env->prog->aux)) 20982 bpf_prog_offload_remove_insns(env, off, cnt); 20983 20984 err = bpf_remove_insns(env->prog, off, cnt); 20985 if (err) 20986 return err; 20987 20988 err = adjust_subprog_starts_after_remove(env, off, cnt); 20989 if (err) 20990 return err; 20991 20992 err = bpf_adj_linfo_after_remove(env, off, cnt); 20993 if (err) 20994 return err; 20995 20996 memmove(aux_data + off, aux_data + off + cnt, 20997 sizeof(*aux_data) * (orig_prog_len - off - cnt)); 20998 20999 return 0; 21000 } 21001 21002 /* The verifier does more data flow analysis than llvm and will not 21003 * explore branches that are dead at run time. Malicious programs can 21004 * have dead code too. Therefore replace all dead at-run-time code 21005 * with 'ja -1'. 21006 * 21007 * Just nops are not optimal, e.g. if they would sit at the end of the 21008 * program and through another bug we would manage to jump there, then 21009 * we'd execute beyond program memory otherwise. Returning exception 21010 * code also wouldn't work since we can have subprogs where the dead 21011 * code could be located. 21012 */ 21013 static void sanitize_dead_code(struct bpf_verifier_env *env) 21014 { 21015 struct bpf_insn_aux_data *aux_data = env->insn_aux_data; 21016 struct bpf_insn trap = BPF_JMP_IMM(BPF_JA, 0, 0, -1); 21017 struct bpf_insn *insn = env->prog->insnsi; 21018 const int insn_cnt = env->prog->len; 21019 int i; 21020 21021 for (i = 0; i < insn_cnt; i++) { 21022 if (aux_data[i].seen) 21023 continue; 21024 memcpy(insn + i, &trap, sizeof(trap)); 21025 aux_data[i].zext_dst = false; 21026 } 21027 } 21028 21029 static bool insn_is_cond_jump(u8 code) 21030 { 21031 u8 op; 21032 21033 op = BPF_OP(code); 21034 if (BPF_CLASS(code) == BPF_JMP32) 21035 return op != BPF_JA; 21036 21037 if (BPF_CLASS(code) != BPF_JMP) 21038 return false; 21039 21040 return op != BPF_JA && op != BPF_EXIT && op != BPF_CALL; 21041 } 21042 21043 static void opt_hard_wire_dead_code_branches(struct bpf_verifier_env *env) 21044 { 21045 struct bpf_insn_aux_data *aux_data = env->insn_aux_data; 21046 struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0); 21047 struct bpf_insn *insn = env->prog->insnsi; 21048 const int insn_cnt = env->prog->len; 21049 int i; 21050 21051 for (i = 0; i < insn_cnt; i++, insn++) { 21052 if (!insn_is_cond_jump(insn->code)) 21053 continue; 21054 21055 if (!aux_data[i + 1].seen) 21056 ja.off = insn->off; 21057 else if (!aux_data[i + 1 + insn->off].seen) 21058 ja.off = 0; 21059 else 21060 continue; 21061 21062 if (bpf_prog_is_offloaded(env->prog->aux)) 21063 bpf_prog_offload_replace_insn(env, i, &ja); 21064 21065 memcpy(insn, &ja, sizeof(ja)); 21066 } 21067 } 21068 21069 static int opt_remove_dead_code(struct bpf_verifier_env *env) 21070 { 21071 struct bpf_insn_aux_data *aux_data = env->insn_aux_data; 21072 int insn_cnt = env->prog->len; 21073 int i, err; 21074 21075 for (i = 0; i < insn_cnt; i++) { 21076 int j; 21077 21078 j = 0; 21079 while (i + j < insn_cnt && !aux_data[i + j].seen) 21080 j++; 21081 if (!j) 21082 continue; 21083 21084 err = verifier_remove_insns(env, i, j); 21085 if (err) 21086 return err; 21087 insn_cnt = env->prog->len; 21088 } 21089 21090 return 0; 21091 } 21092 21093 static const struct bpf_insn NOP = BPF_JMP_IMM(BPF_JA, 0, 0, 0); 21094 static const struct bpf_insn MAY_GOTO_0 = BPF_RAW_INSN(BPF_JMP | BPF_JCOND, 0, 0, 0, 0); 21095 21096 static int opt_remove_nops(struct bpf_verifier_env *env) 21097 { 21098 struct bpf_insn *insn = env->prog->insnsi; 21099 int insn_cnt = env->prog->len; 21100 bool is_may_goto_0, is_ja; 21101 int i, err; 21102 21103 for (i = 0; i < insn_cnt; i++) { 21104 is_may_goto_0 = !memcmp(&insn[i], &MAY_GOTO_0, sizeof(MAY_GOTO_0)); 21105 is_ja = !memcmp(&insn[i], &NOP, sizeof(NOP)); 21106 21107 if (!is_may_goto_0 && !is_ja) 21108 continue; 21109 21110 err = verifier_remove_insns(env, i, 1); 21111 if (err) 21112 return err; 21113 insn_cnt--; 21114 /* Go back one insn to catch may_goto +1; may_goto +0 sequence */ 21115 i -= (is_may_goto_0 && i > 0) ? 2 : 1; 21116 } 21117 21118 return 0; 21119 } 21120 21121 static int opt_subreg_zext_lo32_rnd_hi32(struct bpf_verifier_env *env, 21122 const union bpf_attr *attr) 21123 { 21124 struct bpf_insn *patch; 21125 /* use env->insn_buf as two independent buffers */ 21126 struct bpf_insn *zext_patch = env->insn_buf; 21127 struct bpf_insn *rnd_hi32_patch = &env->insn_buf[2]; 21128 struct bpf_insn_aux_data *aux = env->insn_aux_data; 21129 int i, patch_len, delta = 0, len = env->prog->len; 21130 struct bpf_insn *insns = env->prog->insnsi; 21131 struct bpf_prog *new_prog; 21132 bool rnd_hi32; 21133 21134 rnd_hi32 = attr->prog_flags & BPF_F_TEST_RND_HI32; 21135 zext_patch[1] = BPF_ZEXT_REG(0); 21136 rnd_hi32_patch[1] = BPF_ALU64_IMM(BPF_MOV, BPF_REG_AX, 0); 21137 rnd_hi32_patch[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_AX, 32); 21138 rnd_hi32_patch[3] = BPF_ALU64_REG(BPF_OR, 0, BPF_REG_AX); 21139 for (i = 0; i < len; i++) { 21140 int adj_idx = i + delta; 21141 struct bpf_insn insn; 21142 int load_reg; 21143 21144 insn = insns[adj_idx]; 21145 load_reg = insn_def_regno(&insn); 21146 if (!aux[adj_idx].zext_dst) { 21147 u8 code, class; 21148 u32 imm_rnd; 21149 21150 if (!rnd_hi32) 21151 continue; 21152 21153 code = insn.code; 21154 class = BPF_CLASS(code); 21155 if (load_reg == -1) 21156 continue; 21157 21158 /* NOTE: arg "reg" (the fourth one) is only used for 21159 * BPF_STX + SRC_OP, so it is safe to pass NULL 21160 * here. 21161 */ 21162 if (is_reg64(env, &insn, load_reg, NULL, DST_OP)) { 21163 if (class == BPF_LD && 21164 BPF_MODE(code) == BPF_IMM) 21165 i++; 21166 continue; 21167 } 21168 21169 /* ctx load could be transformed into wider load. */ 21170 if (class == BPF_LDX && 21171 aux[adj_idx].ptr_type == PTR_TO_CTX) 21172 continue; 21173 21174 imm_rnd = get_random_u32(); 21175 rnd_hi32_patch[0] = insn; 21176 rnd_hi32_patch[1].imm = imm_rnd; 21177 rnd_hi32_patch[3].dst_reg = load_reg; 21178 patch = rnd_hi32_patch; 21179 patch_len = 4; 21180 goto apply_patch_buffer; 21181 } 21182 21183 /* Add in an zero-extend instruction if a) the JIT has requested 21184 * it or b) it's a CMPXCHG. 21185 * 21186 * The latter is because: BPF_CMPXCHG always loads a value into 21187 * R0, therefore always zero-extends. However some archs' 21188 * equivalent instruction only does this load when the 21189 * comparison is successful. This detail of CMPXCHG is 21190 * orthogonal to the general zero-extension behaviour of the 21191 * CPU, so it's treated independently of bpf_jit_needs_zext. 21192 */ 21193 if (!bpf_jit_needs_zext() && !is_cmpxchg_insn(&insn)) 21194 continue; 21195 21196 /* Zero-extension is done by the caller. */ 21197 if (bpf_pseudo_kfunc_call(&insn)) 21198 continue; 21199 21200 if (verifier_bug_if(load_reg == -1, env, 21201 "zext_dst is set, but no reg is defined")) 21202 return -EFAULT; 21203 21204 zext_patch[0] = insn; 21205 zext_patch[1].dst_reg = load_reg; 21206 zext_patch[1].src_reg = load_reg; 21207 patch = zext_patch; 21208 patch_len = 2; 21209 apply_patch_buffer: 21210 new_prog = bpf_patch_insn_data(env, adj_idx, patch, patch_len); 21211 if (!new_prog) 21212 return -ENOMEM; 21213 env->prog = new_prog; 21214 insns = new_prog->insnsi; 21215 aux = env->insn_aux_data; 21216 delta += patch_len - 1; 21217 } 21218 21219 return 0; 21220 } 21221 21222 /* convert load instructions that access fields of a context type into a 21223 * sequence of instructions that access fields of the underlying structure: 21224 * struct __sk_buff -> struct sk_buff 21225 * struct bpf_sock_ops -> struct sock 21226 */ 21227 static int convert_ctx_accesses(struct bpf_verifier_env *env) 21228 { 21229 struct bpf_subprog_info *subprogs = env->subprog_info; 21230 const struct bpf_verifier_ops *ops = env->ops; 21231 int i, cnt, size, ctx_field_size, ret, delta = 0, epilogue_cnt = 0; 21232 const int insn_cnt = env->prog->len; 21233 struct bpf_insn *epilogue_buf = env->epilogue_buf; 21234 struct bpf_insn *insn_buf = env->insn_buf; 21235 struct bpf_insn *insn; 21236 u32 target_size, size_default, off; 21237 struct bpf_prog *new_prog; 21238 enum bpf_access_type type; 21239 bool is_narrower_load; 21240 int epilogue_idx = 0; 21241 21242 if (ops->gen_epilogue) { 21243 epilogue_cnt = ops->gen_epilogue(epilogue_buf, env->prog, 21244 -(subprogs[0].stack_depth + 8)); 21245 if (epilogue_cnt >= INSN_BUF_SIZE) { 21246 verifier_bug(env, "epilogue is too long"); 21247 return -EFAULT; 21248 } else if (epilogue_cnt) { 21249 /* Save the ARG_PTR_TO_CTX for the epilogue to use */ 21250 cnt = 0; 21251 subprogs[0].stack_depth += 8; 21252 insn_buf[cnt++] = BPF_STX_MEM(BPF_DW, BPF_REG_FP, BPF_REG_1, 21253 -subprogs[0].stack_depth); 21254 insn_buf[cnt++] = env->prog->insnsi[0]; 21255 new_prog = bpf_patch_insn_data(env, 0, insn_buf, cnt); 21256 if (!new_prog) 21257 return -ENOMEM; 21258 env->prog = new_prog; 21259 delta += cnt - 1; 21260 21261 ret = add_kfunc_in_insns(env, epilogue_buf, epilogue_cnt - 1); 21262 if (ret < 0) 21263 return ret; 21264 } 21265 } 21266 21267 if (ops->gen_prologue || env->seen_direct_write) { 21268 if (!ops->gen_prologue) { 21269 verifier_bug(env, "gen_prologue is null"); 21270 return -EFAULT; 21271 } 21272 cnt = ops->gen_prologue(insn_buf, env->seen_direct_write, 21273 env->prog); 21274 if (cnt >= INSN_BUF_SIZE) { 21275 verifier_bug(env, "prologue is too long"); 21276 return -EFAULT; 21277 } else if (cnt) { 21278 new_prog = bpf_patch_insn_data(env, 0, insn_buf, cnt); 21279 if (!new_prog) 21280 return -ENOMEM; 21281 21282 env->prog = new_prog; 21283 delta += cnt - 1; 21284 21285 ret = add_kfunc_in_insns(env, insn_buf, cnt - 1); 21286 if (ret < 0) 21287 return ret; 21288 } 21289 } 21290 21291 if (delta) 21292 WARN_ON(adjust_jmp_off(env->prog, 0, delta)); 21293 21294 if (bpf_prog_is_offloaded(env->prog->aux)) 21295 return 0; 21296 21297 insn = env->prog->insnsi + delta; 21298 21299 for (i = 0; i < insn_cnt; i++, insn++) { 21300 bpf_convert_ctx_access_t convert_ctx_access; 21301 u8 mode; 21302 21303 if (env->insn_aux_data[i + delta].nospec) { 21304 WARN_ON_ONCE(env->insn_aux_data[i + delta].alu_state); 21305 struct bpf_insn *patch = insn_buf; 21306 21307 *patch++ = BPF_ST_NOSPEC(); 21308 *patch++ = *insn; 21309 cnt = patch - insn_buf; 21310 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 21311 if (!new_prog) 21312 return -ENOMEM; 21313 21314 delta += cnt - 1; 21315 env->prog = new_prog; 21316 insn = new_prog->insnsi + i + delta; 21317 /* This can not be easily merged with the 21318 * nospec_result-case, because an insn may require a 21319 * nospec before and after itself. Therefore also do not 21320 * 'continue' here but potentially apply further 21321 * patching to insn. *insn should equal patch[1] now. 21322 */ 21323 } 21324 21325 if (insn->code == (BPF_LDX | BPF_MEM | BPF_B) || 21326 insn->code == (BPF_LDX | BPF_MEM | BPF_H) || 21327 insn->code == (BPF_LDX | BPF_MEM | BPF_W) || 21328 insn->code == (BPF_LDX | BPF_MEM | BPF_DW) || 21329 insn->code == (BPF_LDX | BPF_MEMSX | BPF_B) || 21330 insn->code == (BPF_LDX | BPF_MEMSX | BPF_H) || 21331 insn->code == (BPF_LDX | BPF_MEMSX | BPF_W)) { 21332 type = BPF_READ; 21333 } else if (insn->code == (BPF_STX | BPF_MEM | BPF_B) || 21334 insn->code == (BPF_STX | BPF_MEM | BPF_H) || 21335 insn->code == (BPF_STX | BPF_MEM | BPF_W) || 21336 insn->code == (BPF_STX | BPF_MEM | BPF_DW) || 21337 insn->code == (BPF_ST | BPF_MEM | BPF_B) || 21338 insn->code == (BPF_ST | BPF_MEM | BPF_H) || 21339 insn->code == (BPF_ST | BPF_MEM | BPF_W) || 21340 insn->code == (BPF_ST | BPF_MEM | BPF_DW)) { 21341 type = BPF_WRITE; 21342 } else if ((insn->code == (BPF_STX | BPF_ATOMIC | BPF_B) || 21343 insn->code == (BPF_STX | BPF_ATOMIC | BPF_H) || 21344 insn->code == (BPF_STX | BPF_ATOMIC | BPF_W) || 21345 insn->code == (BPF_STX | BPF_ATOMIC | BPF_DW)) && 21346 env->insn_aux_data[i + delta].ptr_type == PTR_TO_ARENA) { 21347 insn->code = BPF_STX | BPF_PROBE_ATOMIC | BPF_SIZE(insn->code); 21348 env->prog->aux->num_exentries++; 21349 continue; 21350 } else if (insn->code == (BPF_JMP | BPF_EXIT) && 21351 epilogue_cnt && 21352 i + delta < subprogs[1].start) { 21353 /* Generate epilogue for the main prog */ 21354 if (epilogue_idx) { 21355 /* jump back to the earlier generated epilogue */ 21356 insn_buf[0] = BPF_JMP32_A(epilogue_idx - i - delta - 1); 21357 cnt = 1; 21358 } else { 21359 memcpy(insn_buf, epilogue_buf, 21360 epilogue_cnt * sizeof(*epilogue_buf)); 21361 cnt = epilogue_cnt; 21362 /* epilogue_idx cannot be 0. It must have at 21363 * least one ctx ptr saving insn before the 21364 * epilogue. 21365 */ 21366 epilogue_idx = i + delta; 21367 } 21368 goto patch_insn_buf; 21369 } else { 21370 continue; 21371 } 21372 21373 if (type == BPF_WRITE && 21374 env->insn_aux_data[i + delta].nospec_result) { 21375 /* nospec_result is only used to mitigate Spectre v4 and 21376 * to limit verification-time for Spectre v1. 21377 */ 21378 struct bpf_insn *patch = insn_buf; 21379 21380 *patch++ = *insn; 21381 *patch++ = BPF_ST_NOSPEC(); 21382 cnt = patch - insn_buf; 21383 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 21384 if (!new_prog) 21385 return -ENOMEM; 21386 21387 delta += cnt - 1; 21388 env->prog = new_prog; 21389 insn = new_prog->insnsi + i + delta; 21390 continue; 21391 } 21392 21393 switch ((int)env->insn_aux_data[i + delta].ptr_type) { 21394 case PTR_TO_CTX: 21395 if (!ops->convert_ctx_access) 21396 continue; 21397 convert_ctx_access = ops->convert_ctx_access; 21398 break; 21399 case PTR_TO_SOCKET: 21400 case PTR_TO_SOCK_COMMON: 21401 convert_ctx_access = bpf_sock_convert_ctx_access; 21402 break; 21403 case PTR_TO_TCP_SOCK: 21404 convert_ctx_access = bpf_tcp_sock_convert_ctx_access; 21405 break; 21406 case PTR_TO_XDP_SOCK: 21407 convert_ctx_access = bpf_xdp_sock_convert_ctx_access; 21408 break; 21409 case PTR_TO_BTF_ID: 21410 case PTR_TO_BTF_ID | PTR_UNTRUSTED: 21411 /* PTR_TO_BTF_ID | MEM_ALLOC always has a valid lifetime, unlike 21412 * PTR_TO_BTF_ID, and an active ref_obj_id, but the same cannot 21413 * be said once it is marked PTR_UNTRUSTED, hence we must handle 21414 * any faults for loads into such types. BPF_WRITE is disallowed 21415 * for this case. 21416 */ 21417 case PTR_TO_BTF_ID | MEM_ALLOC | PTR_UNTRUSTED: 21418 case PTR_TO_MEM | MEM_RDONLY | PTR_UNTRUSTED: 21419 if (type == BPF_READ) { 21420 if (BPF_MODE(insn->code) == BPF_MEM) 21421 insn->code = BPF_LDX | BPF_PROBE_MEM | 21422 BPF_SIZE((insn)->code); 21423 else 21424 insn->code = BPF_LDX | BPF_PROBE_MEMSX | 21425 BPF_SIZE((insn)->code); 21426 env->prog->aux->num_exentries++; 21427 } 21428 continue; 21429 case PTR_TO_ARENA: 21430 if (BPF_MODE(insn->code) == BPF_MEMSX) { 21431 verbose(env, "sign extending loads from arena are not supported yet\n"); 21432 return -EOPNOTSUPP; 21433 } 21434 insn->code = BPF_CLASS(insn->code) | BPF_PROBE_MEM32 | BPF_SIZE(insn->code); 21435 env->prog->aux->num_exentries++; 21436 continue; 21437 default: 21438 continue; 21439 } 21440 21441 ctx_field_size = env->insn_aux_data[i + delta].ctx_field_size; 21442 size = BPF_LDST_BYTES(insn); 21443 mode = BPF_MODE(insn->code); 21444 21445 /* If the read access is a narrower load of the field, 21446 * convert to a 4/8-byte load, to minimum program type specific 21447 * convert_ctx_access changes. If conversion is successful, 21448 * we will apply proper mask to the result. 21449 */ 21450 is_narrower_load = size < ctx_field_size; 21451 size_default = bpf_ctx_off_adjust_machine(ctx_field_size); 21452 off = insn->off; 21453 if (is_narrower_load) { 21454 u8 size_code; 21455 21456 if (type == BPF_WRITE) { 21457 verifier_bug(env, "narrow ctx access misconfigured"); 21458 return -EFAULT; 21459 } 21460 21461 size_code = BPF_H; 21462 if (ctx_field_size == 4) 21463 size_code = BPF_W; 21464 else if (ctx_field_size == 8) 21465 size_code = BPF_DW; 21466 21467 insn->off = off & ~(size_default - 1); 21468 insn->code = BPF_LDX | BPF_MEM | size_code; 21469 } 21470 21471 target_size = 0; 21472 cnt = convert_ctx_access(type, insn, insn_buf, env->prog, 21473 &target_size); 21474 if (cnt == 0 || cnt >= INSN_BUF_SIZE || 21475 (ctx_field_size && !target_size)) { 21476 verifier_bug(env, "error during ctx access conversion (%d)", cnt); 21477 return -EFAULT; 21478 } 21479 21480 if (is_narrower_load && size < target_size) { 21481 u8 shift = bpf_ctx_narrow_access_offset( 21482 off, size, size_default) * 8; 21483 if (shift && cnt + 1 >= INSN_BUF_SIZE) { 21484 verifier_bug(env, "narrow ctx load misconfigured"); 21485 return -EFAULT; 21486 } 21487 if (ctx_field_size <= 4) { 21488 if (shift) 21489 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_RSH, 21490 insn->dst_reg, 21491 shift); 21492 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg, 21493 (1 << size * 8) - 1); 21494 } else { 21495 if (shift) 21496 insn_buf[cnt++] = BPF_ALU64_IMM(BPF_RSH, 21497 insn->dst_reg, 21498 shift); 21499 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg, 21500 (1ULL << size * 8) - 1); 21501 } 21502 } 21503 if (mode == BPF_MEMSX) 21504 insn_buf[cnt++] = BPF_RAW_INSN(BPF_ALU64 | BPF_MOV | BPF_X, 21505 insn->dst_reg, insn->dst_reg, 21506 size * 8, 0); 21507 21508 patch_insn_buf: 21509 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 21510 if (!new_prog) 21511 return -ENOMEM; 21512 21513 delta += cnt - 1; 21514 21515 /* keep walking new program and skip insns we just inserted */ 21516 env->prog = new_prog; 21517 insn = new_prog->insnsi + i + delta; 21518 } 21519 21520 return 0; 21521 } 21522 21523 static int jit_subprogs(struct bpf_verifier_env *env) 21524 { 21525 struct bpf_prog *prog = env->prog, **func, *tmp; 21526 int i, j, subprog_start, subprog_end = 0, len, subprog; 21527 struct bpf_map *map_ptr; 21528 struct bpf_insn *insn; 21529 void *old_bpf_func; 21530 int err, num_exentries; 21531 21532 if (env->subprog_cnt <= 1) 21533 return 0; 21534 21535 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) { 21536 if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn)) 21537 continue; 21538 21539 /* Upon error here we cannot fall back to interpreter but 21540 * need a hard reject of the program. Thus -EFAULT is 21541 * propagated in any case. 21542 */ 21543 subprog = find_subprog(env, i + insn->imm + 1); 21544 if (verifier_bug_if(subprog < 0, env, "No program to jit at insn %d", 21545 i + insn->imm + 1)) 21546 return -EFAULT; 21547 /* temporarily remember subprog id inside insn instead of 21548 * aux_data, since next loop will split up all insns into funcs 21549 */ 21550 insn->off = subprog; 21551 /* remember original imm in case JIT fails and fallback 21552 * to interpreter will be needed 21553 */ 21554 env->insn_aux_data[i].call_imm = insn->imm; 21555 /* point imm to __bpf_call_base+1 from JITs point of view */ 21556 insn->imm = 1; 21557 if (bpf_pseudo_func(insn)) { 21558 #if defined(MODULES_VADDR) 21559 u64 addr = MODULES_VADDR; 21560 #else 21561 u64 addr = VMALLOC_START; 21562 #endif 21563 /* jit (e.g. x86_64) may emit fewer instructions 21564 * if it learns a u32 imm is the same as a u64 imm. 21565 * Set close enough to possible prog address. 21566 */ 21567 insn[0].imm = (u32)addr; 21568 insn[1].imm = addr >> 32; 21569 } 21570 } 21571 21572 err = bpf_prog_alloc_jited_linfo(prog); 21573 if (err) 21574 goto out_undo_insn; 21575 21576 err = -ENOMEM; 21577 func = kcalloc(env->subprog_cnt, sizeof(prog), GFP_KERNEL); 21578 if (!func) 21579 goto out_undo_insn; 21580 21581 for (i = 0; i < env->subprog_cnt; i++) { 21582 subprog_start = subprog_end; 21583 subprog_end = env->subprog_info[i + 1].start; 21584 21585 len = subprog_end - subprog_start; 21586 /* bpf_prog_run() doesn't call subprogs directly, 21587 * hence main prog stats include the runtime of subprogs. 21588 * subprogs don't have IDs and not reachable via prog_get_next_id 21589 * func[i]->stats will never be accessed and stays NULL 21590 */ 21591 func[i] = bpf_prog_alloc_no_stats(bpf_prog_size(len), GFP_USER); 21592 if (!func[i]) 21593 goto out_free; 21594 memcpy(func[i]->insnsi, &prog->insnsi[subprog_start], 21595 len * sizeof(struct bpf_insn)); 21596 func[i]->type = prog->type; 21597 func[i]->len = len; 21598 if (bpf_prog_calc_tag(func[i])) 21599 goto out_free; 21600 func[i]->is_func = 1; 21601 func[i]->sleepable = prog->sleepable; 21602 func[i]->aux->func_idx = i; 21603 /* Below members will be freed only at prog->aux */ 21604 func[i]->aux->btf = prog->aux->btf; 21605 func[i]->aux->func_info = prog->aux->func_info; 21606 func[i]->aux->func_info_cnt = prog->aux->func_info_cnt; 21607 func[i]->aux->poke_tab = prog->aux->poke_tab; 21608 func[i]->aux->size_poke_tab = prog->aux->size_poke_tab; 21609 21610 for (j = 0; j < prog->aux->size_poke_tab; j++) { 21611 struct bpf_jit_poke_descriptor *poke; 21612 21613 poke = &prog->aux->poke_tab[j]; 21614 if (poke->insn_idx < subprog_end && 21615 poke->insn_idx >= subprog_start) 21616 poke->aux = func[i]->aux; 21617 } 21618 21619 func[i]->aux->name[0] = 'F'; 21620 func[i]->aux->stack_depth = env->subprog_info[i].stack_depth; 21621 if (env->subprog_info[i].priv_stack_mode == PRIV_STACK_ADAPTIVE) 21622 func[i]->aux->jits_use_priv_stack = true; 21623 21624 func[i]->jit_requested = 1; 21625 func[i]->blinding_requested = prog->blinding_requested; 21626 func[i]->aux->kfunc_tab = prog->aux->kfunc_tab; 21627 func[i]->aux->kfunc_btf_tab = prog->aux->kfunc_btf_tab; 21628 func[i]->aux->linfo = prog->aux->linfo; 21629 func[i]->aux->nr_linfo = prog->aux->nr_linfo; 21630 func[i]->aux->jited_linfo = prog->aux->jited_linfo; 21631 func[i]->aux->linfo_idx = env->subprog_info[i].linfo_idx; 21632 func[i]->aux->arena = prog->aux->arena; 21633 num_exentries = 0; 21634 insn = func[i]->insnsi; 21635 for (j = 0; j < func[i]->len; j++, insn++) { 21636 if (BPF_CLASS(insn->code) == BPF_LDX && 21637 (BPF_MODE(insn->code) == BPF_PROBE_MEM || 21638 BPF_MODE(insn->code) == BPF_PROBE_MEM32 || 21639 BPF_MODE(insn->code) == BPF_PROBE_MEMSX)) 21640 num_exentries++; 21641 if ((BPF_CLASS(insn->code) == BPF_STX || 21642 BPF_CLASS(insn->code) == BPF_ST) && 21643 BPF_MODE(insn->code) == BPF_PROBE_MEM32) 21644 num_exentries++; 21645 if (BPF_CLASS(insn->code) == BPF_STX && 21646 BPF_MODE(insn->code) == BPF_PROBE_ATOMIC) 21647 num_exentries++; 21648 } 21649 func[i]->aux->num_exentries = num_exentries; 21650 func[i]->aux->tail_call_reachable = env->subprog_info[i].tail_call_reachable; 21651 func[i]->aux->exception_cb = env->subprog_info[i].is_exception_cb; 21652 func[i]->aux->changes_pkt_data = env->subprog_info[i].changes_pkt_data; 21653 func[i]->aux->might_sleep = env->subprog_info[i].might_sleep; 21654 if (!i) 21655 func[i]->aux->exception_boundary = env->seen_exception; 21656 func[i] = bpf_int_jit_compile(func[i]); 21657 if (!func[i]->jited) { 21658 err = -ENOTSUPP; 21659 goto out_free; 21660 } 21661 cond_resched(); 21662 } 21663 21664 /* at this point all bpf functions were successfully JITed 21665 * now populate all bpf_calls with correct addresses and 21666 * run last pass of JIT 21667 */ 21668 for (i = 0; i < env->subprog_cnt; i++) { 21669 insn = func[i]->insnsi; 21670 for (j = 0; j < func[i]->len; j++, insn++) { 21671 if (bpf_pseudo_func(insn)) { 21672 subprog = insn->off; 21673 insn[0].imm = (u32)(long)func[subprog]->bpf_func; 21674 insn[1].imm = ((u64)(long)func[subprog]->bpf_func) >> 32; 21675 continue; 21676 } 21677 if (!bpf_pseudo_call(insn)) 21678 continue; 21679 subprog = insn->off; 21680 insn->imm = BPF_CALL_IMM(func[subprog]->bpf_func); 21681 } 21682 21683 /* we use the aux data to keep a list of the start addresses 21684 * of the JITed images for each function in the program 21685 * 21686 * for some architectures, such as powerpc64, the imm field 21687 * might not be large enough to hold the offset of the start 21688 * address of the callee's JITed image from __bpf_call_base 21689 * 21690 * in such cases, we can lookup the start address of a callee 21691 * by using its subprog id, available from the off field of 21692 * the call instruction, as an index for this list 21693 */ 21694 func[i]->aux->func = func; 21695 func[i]->aux->func_cnt = env->subprog_cnt - env->hidden_subprog_cnt; 21696 func[i]->aux->real_func_cnt = env->subprog_cnt; 21697 } 21698 for (i = 0; i < env->subprog_cnt; i++) { 21699 old_bpf_func = func[i]->bpf_func; 21700 tmp = bpf_int_jit_compile(func[i]); 21701 if (tmp != func[i] || func[i]->bpf_func != old_bpf_func) { 21702 verbose(env, "JIT doesn't support bpf-to-bpf calls\n"); 21703 err = -ENOTSUPP; 21704 goto out_free; 21705 } 21706 cond_resched(); 21707 } 21708 21709 /* finally lock prog and jit images for all functions and 21710 * populate kallsysm. Begin at the first subprogram, since 21711 * bpf_prog_load will add the kallsyms for the main program. 21712 */ 21713 for (i = 1; i < env->subprog_cnt; i++) { 21714 err = bpf_prog_lock_ro(func[i]); 21715 if (err) 21716 goto out_free; 21717 } 21718 21719 for (i = 1; i < env->subprog_cnt; i++) 21720 bpf_prog_kallsyms_add(func[i]); 21721 21722 /* Last step: make now unused interpreter insns from main 21723 * prog consistent for later dump requests, so they can 21724 * later look the same as if they were interpreted only. 21725 */ 21726 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) { 21727 if (bpf_pseudo_func(insn)) { 21728 insn[0].imm = env->insn_aux_data[i].call_imm; 21729 insn[1].imm = insn->off; 21730 insn->off = 0; 21731 continue; 21732 } 21733 if (!bpf_pseudo_call(insn)) 21734 continue; 21735 insn->off = env->insn_aux_data[i].call_imm; 21736 subprog = find_subprog(env, i + insn->off + 1); 21737 insn->imm = subprog; 21738 } 21739 21740 prog->jited = 1; 21741 prog->bpf_func = func[0]->bpf_func; 21742 prog->jited_len = func[0]->jited_len; 21743 prog->aux->extable = func[0]->aux->extable; 21744 prog->aux->num_exentries = func[0]->aux->num_exentries; 21745 prog->aux->func = func; 21746 prog->aux->func_cnt = env->subprog_cnt - env->hidden_subprog_cnt; 21747 prog->aux->real_func_cnt = env->subprog_cnt; 21748 prog->aux->bpf_exception_cb = (void *)func[env->exception_callback_subprog]->bpf_func; 21749 prog->aux->exception_boundary = func[0]->aux->exception_boundary; 21750 bpf_prog_jit_attempt_done(prog); 21751 return 0; 21752 out_free: 21753 /* We failed JIT'ing, so at this point we need to unregister poke 21754 * descriptors from subprogs, so that kernel is not attempting to 21755 * patch it anymore as we're freeing the subprog JIT memory. 21756 */ 21757 for (i = 0; i < prog->aux->size_poke_tab; i++) { 21758 map_ptr = prog->aux->poke_tab[i].tail_call.map; 21759 map_ptr->ops->map_poke_untrack(map_ptr, prog->aux); 21760 } 21761 /* At this point we're guaranteed that poke descriptors are not 21762 * live anymore. We can just unlink its descriptor table as it's 21763 * released with the main prog. 21764 */ 21765 for (i = 0; i < env->subprog_cnt; i++) { 21766 if (!func[i]) 21767 continue; 21768 func[i]->aux->poke_tab = NULL; 21769 bpf_jit_free(func[i]); 21770 } 21771 kfree(func); 21772 out_undo_insn: 21773 /* cleanup main prog to be interpreted */ 21774 prog->jit_requested = 0; 21775 prog->blinding_requested = 0; 21776 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) { 21777 if (!bpf_pseudo_call(insn)) 21778 continue; 21779 insn->off = 0; 21780 insn->imm = env->insn_aux_data[i].call_imm; 21781 } 21782 bpf_prog_jit_attempt_done(prog); 21783 return err; 21784 } 21785 21786 static int fixup_call_args(struct bpf_verifier_env *env) 21787 { 21788 #ifndef CONFIG_BPF_JIT_ALWAYS_ON 21789 struct bpf_prog *prog = env->prog; 21790 struct bpf_insn *insn = prog->insnsi; 21791 bool has_kfunc_call = bpf_prog_has_kfunc_call(prog); 21792 int i, depth; 21793 #endif 21794 int err = 0; 21795 21796 if (env->prog->jit_requested && 21797 !bpf_prog_is_offloaded(env->prog->aux)) { 21798 err = jit_subprogs(env); 21799 if (err == 0) 21800 return 0; 21801 if (err == -EFAULT) 21802 return err; 21803 } 21804 #ifndef CONFIG_BPF_JIT_ALWAYS_ON 21805 if (has_kfunc_call) { 21806 verbose(env, "calling kernel functions are not allowed in non-JITed programs\n"); 21807 return -EINVAL; 21808 } 21809 if (env->subprog_cnt > 1 && env->prog->aux->tail_call_reachable) { 21810 /* When JIT fails the progs with bpf2bpf calls and tail_calls 21811 * have to be rejected, since interpreter doesn't support them yet. 21812 */ 21813 verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n"); 21814 return -EINVAL; 21815 } 21816 for (i = 0; i < prog->len; i++, insn++) { 21817 if (bpf_pseudo_func(insn)) { 21818 /* When JIT fails the progs with callback calls 21819 * have to be rejected, since interpreter doesn't support them yet. 21820 */ 21821 verbose(env, "callbacks are not allowed in non-JITed programs\n"); 21822 return -EINVAL; 21823 } 21824 21825 if (!bpf_pseudo_call(insn)) 21826 continue; 21827 depth = get_callee_stack_depth(env, insn, i); 21828 if (depth < 0) 21829 return depth; 21830 bpf_patch_call_args(insn, depth); 21831 } 21832 err = 0; 21833 #endif 21834 return err; 21835 } 21836 21837 /* replace a generic kfunc with a specialized version if necessary */ 21838 static void specialize_kfunc(struct bpf_verifier_env *env, 21839 u32 func_id, u16 offset, unsigned long *addr) 21840 { 21841 struct bpf_prog *prog = env->prog; 21842 bool seen_direct_write; 21843 void *xdp_kfunc; 21844 bool is_rdonly; 21845 21846 if (bpf_dev_bound_kfunc_id(func_id)) { 21847 xdp_kfunc = bpf_dev_bound_resolve_kfunc(prog, func_id); 21848 if (xdp_kfunc) { 21849 *addr = (unsigned long)xdp_kfunc; 21850 return; 21851 } 21852 /* fallback to default kfunc when not supported by netdev */ 21853 } 21854 21855 if (offset) 21856 return; 21857 21858 if (func_id == special_kfunc_list[KF_bpf_dynptr_from_skb]) { 21859 seen_direct_write = env->seen_direct_write; 21860 is_rdonly = !may_access_direct_pkt_data(env, NULL, BPF_WRITE); 21861 21862 if (is_rdonly) 21863 *addr = (unsigned long)bpf_dynptr_from_skb_rdonly; 21864 21865 /* restore env->seen_direct_write to its original value, since 21866 * may_access_direct_pkt_data mutates it 21867 */ 21868 env->seen_direct_write = seen_direct_write; 21869 } 21870 21871 if (func_id == special_kfunc_list[KF_bpf_set_dentry_xattr] && 21872 bpf_lsm_has_d_inode_locked(prog)) 21873 *addr = (unsigned long)bpf_set_dentry_xattr_locked; 21874 21875 if (func_id == special_kfunc_list[KF_bpf_remove_dentry_xattr] && 21876 bpf_lsm_has_d_inode_locked(prog)) 21877 *addr = (unsigned long)bpf_remove_dentry_xattr_locked; 21878 } 21879 21880 static void __fixup_collection_insert_kfunc(struct bpf_insn_aux_data *insn_aux, 21881 u16 struct_meta_reg, 21882 u16 node_offset_reg, 21883 struct bpf_insn *insn, 21884 struct bpf_insn *insn_buf, 21885 int *cnt) 21886 { 21887 struct btf_struct_meta *kptr_struct_meta = insn_aux->kptr_struct_meta; 21888 struct bpf_insn addr[2] = { BPF_LD_IMM64(struct_meta_reg, (long)kptr_struct_meta) }; 21889 21890 insn_buf[0] = addr[0]; 21891 insn_buf[1] = addr[1]; 21892 insn_buf[2] = BPF_MOV64_IMM(node_offset_reg, insn_aux->insert_off); 21893 insn_buf[3] = *insn; 21894 *cnt = 4; 21895 } 21896 21897 static int fixup_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn, 21898 struct bpf_insn *insn_buf, int insn_idx, int *cnt) 21899 { 21900 const struct bpf_kfunc_desc *desc; 21901 21902 if (!insn->imm) { 21903 verbose(env, "invalid kernel function call not eliminated in verifier pass\n"); 21904 return -EINVAL; 21905 } 21906 21907 *cnt = 0; 21908 21909 /* insn->imm has the btf func_id. Replace it with an offset relative to 21910 * __bpf_call_base, unless the JIT needs to call functions that are 21911 * further than 32 bits away (bpf_jit_supports_far_kfunc_call()). 21912 */ 21913 desc = find_kfunc_desc(env->prog, insn->imm, insn->off); 21914 if (!desc) { 21915 verifier_bug(env, "kernel function descriptor not found for func_id %u", 21916 insn->imm); 21917 return -EFAULT; 21918 } 21919 21920 if (!bpf_jit_supports_far_kfunc_call()) 21921 insn->imm = BPF_CALL_IMM(desc->addr); 21922 if (insn->off) 21923 return 0; 21924 if (desc->func_id == special_kfunc_list[KF_bpf_obj_new_impl] || 21925 desc->func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl]) { 21926 struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta; 21927 struct bpf_insn addr[2] = { BPF_LD_IMM64(BPF_REG_2, (long)kptr_struct_meta) }; 21928 u64 obj_new_size = env->insn_aux_data[insn_idx].obj_new_size; 21929 21930 if (desc->func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl] && kptr_struct_meta) { 21931 verifier_bug(env, "NULL kptr_struct_meta expected at insn_idx %d", 21932 insn_idx); 21933 return -EFAULT; 21934 } 21935 21936 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_1, obj_new_size); 21937 insn_buf[1] = addr[0]; 21938 insn_buf[2] = addr[1]; 21939 insn_buf[3] = *insn; 21940 *cnt = 4; 21941 } else if (desc->func_id == special_kfunc_list[KF_bpf_obj_drop_impl] || 21942 desc->func_id == special_kfunc_list[KF_bpf_percpu_obj_drop_impl] || 21943 desc->func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl]) { 21944 struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta; 21945 struct bpf_insn addr[2] = { BPF_LD_IMM64(BPF_REG_2, (long)kptr_struct_meta) }; 21946 21947 if (desc->func_id == special_kfunc_list[KF_bpf_percpu_obj_drop_impl] && kptr_struct_meta) { 21948 verifier_bug(env, "NULL kptr_struct_meta expected at insn_idx %d", 21949 insn_idx); 21950 return -EFAULT; 21951 } 21952 21953 if (desc->func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl] && 21954 !kptr_struct_meta) { 21955 verifier_bug(env, "kptr_struct_meta expected at insn_idx %d", 21956 insn_idx); 21957 return -EFAULT; 21958 } 21959 21960 insn_buf[0] = addr[0]; 21961 insn_buf[1] = addr[1]; 21962 insn_buf[2] = *insn; 21963 *cnt = 3; 21964 } else if (desc->func_id == special_kfunc_list[KF_bpf_list_push_back_impl] || 21965 desc->func_id == special_kfunc_list[KF_bpf_list_push_front_impl] || 21966 desc->func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) { 21967 struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta; 21968 int struct_meta_reg = BPF_REG_3; 21969 int node_offset_reg = BPF_REG_4; 21970 21971 /* rbtree_add has extra 'less' arg, so args-to-fixup are in diff regs */ 21972 if (desc->func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) { 21973 struct_meta_reg = BPF_REG_4; 21974 node_offset_reg = BPF_REG_5; 21975 } 21976 21977 if (!kptr_struct_meta) { 21978 verifier_bug(env, "kptr_struct_meta expected at insn_idx %d", 21979 insn_idx); 21980 return -EFAULT; 21981 } 21982 21983 __fixup_collection_insert_kfunc(&env->insn_aux_data[insn_idx], struct_meta_reg, 21984 node_offset_reg, insn, insn_buf, cnt); 21985 } else if (desc->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx] || 21986 desc->func_id == special_kfunc_list[KF_bpf_rdonly_cast]) { 21987 insn_buf[0] = BPF_MOV64_REG(BPF_REG_0, BPF_REG_1); 21988 *cnt = 1; 21989 } 21990 21991 if (env->insn_aux_data[insn_idx].arg_prog) { 21992 u32 regno = env->insn_aux_data[insn_idx].arg_prog; 21993 struct bpf_insn ld_addrs[2] = { BPF_LD_IMM64(regno, (long)env->prog->aux) }; 21994 int idx = *cnt; 21995 21996 insn_buf[idx++] = ld_addrs[0]; 21997 insn_buf[idx++] = ld_addrs[1]; 21998 insn_buf[idx++] = *insn; 21999 *cnt = idx; 22000 } 22001 return 0; 22002 } 22003 22004 /* The function requires that first instruction in 'patch' is insnsi[prog->len - 1] */ 22005 static int add_hidden_subprog(struct bpf_verifier_env *env, struct bpf_insn *patch, int len) 22006 { 22007 struct bpf_subprog_info *info = env->subprog_info; 22008 int cnt = env->subprog_cnt; 22009 struct bpf_prog *prog; 22010 22011 /* We only reserve one slot for hidden subprogs in subprog_info. */ 22012 if (env->hidden_subprog_cnt) { 22013 verifier_bug(env, "only one hidden subprog supported"); 22014 return -EFAULT; 22015 } 22016 /* We're not patching any existing instruction, just appending the new 22017 * ones for the hidden subprog. Hence all of the adjustment operations 22018 * in bpf_patch_insn_data are no-ops. 22019 */ 22020 prog = bpf_patch_insn_data(env, env->prog->len - 1, patch, len); 22021 if (!prog) 22022 return -ENOMEM; 22023 env->prog = prog; 22024 info[cnt + 1].start = info[cnt].start; 22025 info[cnt].start = prog->len - len + 1; 22026 env->subprog_cnt++; 22027 env->hidden_subprog_cnt++; 22028 return 0; 22029 } 22030 22031 /* Do various post-verification rewrites in a single program pass. 22032 * These rewrites simplify JIT and interpreter implementations. 22033 */ 22034 static int do_misc_fixups(struct bpf_verifier_env *env) 22035 { 22036 struct bpf_prog *prog = env->prog; 22037 enum bpf_attach_type eatype = prog->expected_attach_type; 22038 enum bpf_prog_type prog_type = resolve_prog_type(prog); 22039 struct bpf_insn *insn = prog->insnsi; 22040 const struct bpf_func_proto *fn; 22041 const int insn_cnt = prog->len; 22042 const struct bpf_map_ops *ops; 22043 struct bpf_insn_aux_data *aux; 22044 struct bpf_insn *insn_buf = env->insn_buf; 22045 struct bpf_prog *new_prog; 22046 struct bpf_map *map_ptr; 22047 int i, ret, cnt, delta = 0, cur_subprog = 0; 22048 struct bpf_subprog_info *subprogs = env->subprog_info; 22049 u16 stack_depth = subprogs[cur_subprog].stack_depth; 22050 u16 stack_depth_extra = 0; 22051 22052 if (env->seen_exception && !env->exception_callback_subprog) { 22053 struct bpf_insn *patch = insn_buf; 22054 22055 *patch++ = env->prog->insnsi[insn_cnt - 1]; 22056 *patch++ = BPF_MOV64_REG(BPF_REG_0, BPF_REG_1); 22057 *patch++ = BPF_EXIT_INSN(); 22058 ret = add_hidden_subprog(env, insn_buf, patch - insn_buf); 22059 if (ret < 0) 22060 return ret; 22061 prog = env->prog; 22062 insn = prog->insnsi; 22063 22064 env->exception_callback_subprog = env->subprog_cnt - 1; 22065 /* Don't update insn_cnt, as add_hidden_subprog always appends insns */ 22066 mark_subprog_exc_cb(env, env->exception_callback_subprog); 22067 } 22068 22069 for (i = 0; i < insn_cnt;) { 22070 if (insn->code == (BPF_ALU64 | BPF_MOV | BPF_X) && insn->imm) { 22071 if ((insn->off == BPF_ADDR_SPACE_CAST && insn->imm == 1) || 22072 (((struct bpf_map *)env->prog->aux->arena)->map_flags & BPF_F_NO_USER_CONV)) { 22073 /* convert to 32-bit mov that clears upper 32-bit */ 22074 insn->code = BPF_ALU | BPF_MOV | BPF_X; 22075 /* clear off and imm, so it's a normal 'wX = wY' from JIT pov */ 22076 insn->off = 0; 22077 insn->imm = 0; 22078 } /* cast from as(0) to as(1) should be handled by JIT */ 22079 goto next_insn; 22080 } 22081 22082 if (env->insn_aux_data[i + delta].needs_zext) 22083 /* Convert BPF_CLASS(insn->code) == BPF_ALU64 to 32-bit ALU */ 22084 insn->code = BPF_ALU | BPF_OP(insn->code) | BPF_SRC(insn->code); 22085 22086 /* Make sdiv/smod divide-by-minus-one exceptions impossible. */ 22087 if ((insn->code == (BPF_ALU64 | BPF_MOD | BPF_K) || 22088 insn->code == (BPF_ALU64 | BPF_DIV | BPF_K) || 22089 insn->code == (BPF_ALU | BPF_MOD | BPF_K) || 22090 insn->code == (BPF_ALU | BPF_DIV | BPF_K)) && 22091 insn->off == 1 && insn->imm == -1) { 22092 bool is64 = BPF_CLASS(insn->code) == BPF_ALU64; 22093 bool isdiv = BPF_OP(insn->code) == BPF_DIV; 22094 struct bpf_insn *patch = insn_buf; 22095 22096 if (isdiv) 22097 *patch++ = BPF_RAW_INSN((is64 ? BPF_ALU64 : BPF_ALU) | 22098 BPF_NEG | BPF_K, insn->dst_reg, 22099 0, 0, 0); 22100 else 22101 *patch++ = BPF_MOV32_IMM(insn->dst_reg, 0); 22102 22103 cnt = patch - insn_buf; 22104 22105 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 22106 if (!new_prog) 22107 return -ENOMEM; 22108 22109 delta += cnt - 1; 22110 env->prog = prog = new_prog; 22111 insn = new_prog->insnsi + i + delta; 22112 goto next_insn; 22113 } 22114 22115 /* Make divide-by-zero and divide-by-minus-one exceptions impossible. */ 22116 if (insn->code == (BPF_ALU64 | BPF_MOD | BPF_X) || 22117 insn->code == (BPF_ALU64 | BPF_DIV | BPF_X) || 22118 insn->code == (BPF_ALU | BPF_MOD | BPF_X) || 22119 insn->code == (BPF_ALU | BPF_DIV | BPF_X)) { 22120 bool is64 = BPF_CLASS(insn->code) == BPF_ALU64; 22121 bool isdiv = BPF_OP(insn->code) == BPF_DIV; 22122 bool is_sdiv = isdiv && insn->off == 1; 22123 bool is_smod = !isdiv && insn->off == 1; 22124 struct bpf_insn *patch = insn_buf; 22125 22126 if (is_sdiv) { 22127 /* [R,W]x sdiv 0 -> 0 22128 * LLONG_MIN sdiv -1 -> LLONG_MIN 22129 * INT_MIN sdiv -1 -> INT_MIN 22130 */ 22131 *patch++ = BPF_MOV64_REG(BPF_REG_AX, insn->src_reg); 22132 *patch++ = BPF_RAW_INSN((is64 ? BPF_ALU64 : BPF_ALU) | 22133 BPF_ADD | BPF_K, BPF_REG_AX, 22134 0, 0, 1); 22135 *patch++ = BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) | 22136 BPF_JGT | BPF_K, BPF_REG_AX, 22137 0, 4, 1); 22138 *patch++ = BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) | 22139 BPF_JEQ | BPF_K, BPF_REG_AX, 22140 0, 1, 0); 22141 *patch++ = BPF_RAW_INSN((is64 ? BPF_ALU64 : BPF_ALU) | 22142 BPF_MOV | BPF_K, insn->dst_reg, 22143 0, 0, 0); 22144 /* BPF_NEG(LLONG_MIN) == -LLONG_MIN == LLONG_MIN */ 22145 *patch++ = BPF_RAW_INSN((is64 ? BPF_ALU64 : BPF_ALU) | 22146 BPF_NEG | BPF_K, insn->dst_reg, 22147 0, 0, 0); 22148 *patch++ = BPF_JMP_IMM(BPF_JA, 0, 0, 1); 22149 *patch++ = *insn; 22150 cnt = patch - insn_buf; 22151 } else if (is_smod) { 22152 /* [R,W]x mod 0 -> [R,W]x */ 22153 /* [R,W]x mod -1 -> 0 */ 22154 *patch++ = BPF_MOV64_REG(BPF_REG_AX, insn->src_reg); 22155 *patch++ = BPF_RAW_INSN((is64 ? BPF_ALU64 : BPF_ALU) | 22156 BPF_ADD | BPF_K, BPF_REG_AX, 22157 0, 0, 1); 22158 *patch++ = BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) | 22159 BPF_JGT | BPF_K, BPF_REG_AX, 22160 0, 3, 1); 22161 *patch++ = BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) | 22162 BPF_JEQ | BPF_K, BPF_REG_AX, 22163 0, 3 + (is64 ? 0 : 1), 1); 22164 *patch++ = BPF_MOV32_IMM(insn->dst_reg, 0); 22165 *patch++ = BPF_JMP_IMM(BPF_JA, 0, 0, 1); 22166 *patch++ = *insn; 22167 22168 if (!is64) { 22169 *patch++ = BPF_JMP_IMM(BPF_JA, 0, 0, 1); 22170 *patch++ = BPF_MOV32_REG(insn->dst_reg, insn->dst_reg); 22171 } 22172 cnt = patch - insn_buf; 22173 } else if (isdiv) { 22174 /* [R,W]x div 0 -> 0 */ 22175 *patch++ = BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) | 22176 BPF_JNE | BPF_K, insn->src_reg, 22177 0, 2, 0); 22178 *patch++ = BPF_ALU32_REG(BPF_XOR, insn->dst_reg, insn->dst_reg); 22179 *patch++ = BPF_JMP_IMM(BPF_JA, 0, 0, 1); 22180 *patch++ = *insn; 22181 cnt = patch - insn_buf; 22182 } else { 22183 /* [R,W]x mod 0 -> [R,W]x */ 22184 *patch++ = BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) | 22185 BPF_JEQ | BPF_K, insn->src_reg, 22186 0, 1 + (is64 ? 0 : 1), 0); 22187 *patch++ = *insn; 22188 22189 if (!is64) { 22190 *patch++ = BPF_JMP_IMM(BPF_JA, 0, 0, 1); 22191 *patch++ = BPF_MOV32_REG(insn->dst_reg, insn->dst_reg); 22192 } 22193 cnt = patch - insn_buf; 22194 } 22195 22196 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 22197 if (!new_prog) 22198 return -ENOMEM; 22199 22200 delta += cnt - 1; 22201 env->prog = prog = new_prog; 22202 insn = new_prog->insnsi + i + delta; 22203 goto next_insn; 22204 } 22205 22206 /* Make it impossible to de-reference a userspace address */ 22207 if (BPF_CLASS(insn->code) == BPF_LDX && 22208 (BPF_MODE(insn->code) == BPF_PROBE_MEM || 22209 BPF_MODE(insn->code) == BPF_PROBE_MEMSX)) { 22210 struct bpf_insn *patch = insn_buf; 22211 u64 uaddress_limit = bpf_arch_uaddress_limit(); 22212 22213 if (!uaddress_limit) 22214 goto next_insn; 22215 22216 *patch++ = BPF_MOV64_REG(BPF_REG_AX, insn->src_reg); 22217 if (insn->off) 22218 *patch++ = BPF_ALU64_IMM(BPF_ADD, BPF_REG_AX, insn->off); 22219 *patch++ = BPF_ALU64_IMM(BPF_RSH, BPF_REG_AX, 32); 22220 *patch++ = BPF_JMP_IMM(BPF_JLE, BPF_REG_AX, uaddress_limit >> 32, 2); 22221 *patch++ = *insn; 22222 *patch++ = BPF_JMP_IMM(BPF_JA, 0, 0, 1); 22223 *patch++ = BPF_MOV64_IMM(insn->dst_reg, 0); 22224 22225 cnt = patch - insn_buf; 22226 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 22227 if (!new_prog) 22228 return -ENOMEM; 22229 22230 delta += cnt - 1; 22231 env->prog = prog = new_prog; 22232 insn = new_prog->insnsi + i + delta; 22233 goto next_insn; 22234 } 22235 22236 /* Implement LD_ABS and LD_IND with a rewrite, if supported by the program type. */ 22237 if (BPF_CLASS(insn->code) == BPF_LD && 22238 (BPF_MODE(insn->code) == BPF_ABS || 22239 BPF_MODE(insn->code) == BPF_IND)) { 22240 cnt = env->ops->gen_ld_abs(insn, insn_buf); 22241 if (cnt == 0 || cnt >= INSN_BUF_SIZE) { 22242 verifier_bug(env, "%d insns generated for ld_abs", cnt); 22243 return -EFAULT; 22244 } 22245 22246 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 22247 if (!new_prog) 22248 return -ENOMEM; 22249 22250 delta += cnt - 1; 22251 env->prog = prog = new_prog; 22252 insn = new_prog->insnsi + i + delta; 22253 goto next_insn; 22254 } 22255 22256 /* Rewrite pointer arithmetic to mitigate speculation attacks. */ 22257 if (insn->code == (BPF_ALU64 | BPF_ADD | BPF_X) || 22258 insn->code == (BPF_ALU64 | BPF_SUB | BPF_X)) { 22259 const u8 code_add = BPF_ALU64 | BPF_ADD | BPF_X; 22260 const u8 code_sub = BPF_ALU64 | BPF_SUB | BPF_X; 22261 struct bpf_insn *patch = insn_buf; 22262 bool issrc, isneg, isimm; 22263 u32 off_reg; 22264 22265 aux = &env->insn_aux_data[i + delta]; 22266 if (!aux->alu_state || 22267 aux->alu_state == BPF_ALU_NON_POINTER) 22268 goto next_insn; 22269 22270 isneg = aux->alu_state & BPF_ALU_NEG_VALUE; 22271 issrc = (aux->alu_state & BPF_ALU_SANITIZE) == 22272 BPF_ALU_SANITIZE_SRC; 22273 isimm = aux->alu_state & BPF_ALU_IMMEDIATE; 22274 22275 off_reg = issrc ? insn->src_reg : insn->dst_reg; 22276 if (isimm) { 22277 *patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit); 22278 } else { 22279 if (isneg) 22280 *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1); 22281 *patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit); 22282 *patch++ = BPF_ALU64_REG(BPF_SUB, BPF_REG_AX, off_reg); 22283 *patch++ = BPF_ALU64_REG(BPF_OR, BPF_REG_AX, off_reg); 22284 *patch++ = BPF_ALU64_IMM(BPF_NEG, BPF_REG_AX, 0); 22285 *patch++ = BPF_ALU64_IMM(BPF_ARSH, BPF_REG_AX, 63); 22286 *patch++ = BPF_ALU64_REG(BPF_AND, BPF_REG_AX, off_reg); 22287 } 22288 if (!issrc) 22289 *patch++ = BPF_MOV64_REG(insn->dst_reg, insn->src_reg); 22290 insn->src_reg = BPF_REG_AX; 22291 if (isneg) 22292 insn->code = insn->code == code_add ? 22293 code_sub : code_add; 22294 *patch++ = *insn; 22295 if (issrc && isneg && !isimm) 22296 *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1); 22297 cnt = patch - insn_buf; 22298 22299 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 22300 if (!new_prog) 22301 return -ENOMEM; 22302 22303 delta += cnt - 1; 22304 env->prog = prog = new_prog; 22305 insn = new_prog->insnsi + i + delta; 22306 goto next_insn; 22307 } 22308 22309 if (is_may_goto_insn(insn) && bpf_jit_supports_timed_may_goto()) { 22310 int stack_off_cnt = -stack_depth - 16; 22311 22312 /* 22313 * Two 8 byte slots, depth-16 stores the count, and 22314 * depth-8 stores the start timestamp of the loop. 22315 * 22316 * The starting value of count is BPF_MAX_TIMED_LOOPS 22317 * (0xffff). Every iteration loads it and subs it by 1, 22318 * until the value becomes 0 in AX (thus, 1 in stack), 22319 * after which we call arch_bpf_timed_may_goto, which 22320 * either sets AX to 0xffff to keep looping, or to 0 22321 * upon timeout. AX is then stored into the stack. In 22322 * the next iteration, we either see 0 and break out, or 22323 * continue iterating until the next time value is 0 22324 * after subtraction, rinse and repeat. 22325 */ 22326 stack_depth_extra = 16; 22327 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_AX, BPF_REG_10, stack_off_cnt); 22328 if (insn->off >= 0) 22329 insn_buf[1] = BPF_JMP_IMM(BPF_JEQ, BPF_REG_AX, 0, insn->off + 5); 22330 else 22331 insn_buf[1] = BPF_JMP_IMM(BPF_JEQ, BPF_REG_AX, 0, insn->off - 1); 22332 insn_buf[2] = BPF_ALU64_IMM(BPF_SUB, BPF_REG_AX, 1); 22333 insn_buf[3] = BPF_JMP_IMM(BPF_JNE, BPF_REG_AX, 0, 2); 22334 /* 22335 * AX is used as an argument to pass in stack_off_cnt 22336 * (to add to r10/fp), and also as the return value of 22337 * the call to arch_bpf_timed_may_goto. 22338 */ 22339 insn_buf[4] = BPF_MOV64_IMM(BPF_REG_AX, stack_off_cnt); 22340 insn_buf[5] = BPF_EMIT_CALL(arch_bpf_timed_may_goto); 22341 insn_buf[6] = BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_AX, stack_off_cnt); 22342 cnt = 7; 22343 22344 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 22345 if (!new_prog) 22346 return -ENOMEM; 22347 22348 delta += cnt - 1; 22349 env->prog = prog = new_prog; 22350 insn = new_prog->insnsi + i + delta; 22351 goto next_insn; 22352 } else if (is_may_goto_insn(insn)) { 22353 int stack_off = -stack_depth - 8; 22354 22355 stack_depth_extra = 8; 22356 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_AX, BPF_REG_10, stack_off); 22357 if (insn->off >= 0) 22358 insn_buf[1] = BPF_JMP_IMM(BPF_JEQ, BPF_REG_AX, 0, insn->off + 2); 22359 else 22360 insn_buf[1] = BPF_JMP_IMM(BPF_JEQ, BPF_REG_AX, 0, insn->off - 1); 22361 insn_buf[2] = BPF_ALU64_IMM(BPF_SUB, BPF_REG_AX, 1); 22362 insn_buf[3] = BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_AX, stack_off); 22363 cnt = 4; 22364 22365 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 22366 if (!new_prog) 22367 return -ENOMEM; 22368 22369 delta += cnt - 1; 22370 env->prog = prog = new_prog; 22371 insn = new_prog->insnsi + i + delta; 22372 goto next_insn; 22373 } 22374 22375 if (insn->code != (BPF_JMP | BPF_CALL)) 22376 goto next_insn; 22377 if (insn->src_reg == BPF_PSEUDO_CALL) 22378 goto next_insn; 22379 if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) { 22380 ret = fixup_kfunc_call(env, insn, insn_buf, i + delta, &cnt); 22381 if (ret) 22382 return ret; 22383 if (cnt == 0) 22384 goto next_insn; 22385 22386 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 22387 if (!new_prog) 22388 return -ENOMEM; 22389 22390 delta += cnt - 1; 22391 env->prog = prog = new_prog; 22392 insn = new_prog->insnsi + i + delta; 22393 goto next_insn; 22394 } 22395 22396 /* Skip inlining the helper call if the JIT does it. */ 22397 if (bpf_jit_inlines_helper_call(insn->imm)) 22398 goto next_insn; 22399 22400 if (insn->imm == BPF_FUNC_get_route_realm) 22401 prog->dst_needed = 1; 22402 if (insn->imm == BPF_FUNC_get_prandom_u32) 22403 bpf_user_rnd_init_once(); 22404 if (insn->imm == BPF_FUNC_override_return) 22405 prog->kprobe_override = 1; 22406 if (insn->imm == BPF_FUNC_tail_call) { 22407 /* If we tail call into other programs, we 22408 * cannot make any assumptions since they can 22409 * be replaced dynamically during runtime in 22410 * the program array. 22411 */ 22412 prog->cb_access = 1; 22413 if (!allow_tail_call_in_subprogs(env)) 22414 prog->aux->stack_depth = MAX_BPF_STACK; 22415 prog->aux->max_pkt_offset = MAX_PACKET_OFF; 22416 22417 /* mark bpf_tail_call as different opcode to avoid 22418 * conditional branch in the interpreter for every normal 22419 * call and to prevent accidental JITing by JIT compiler 22420 * that doesn't support bpf_tail_call yet 22421 */ 22422 insn->imm = 0; 22423 insn->code = BPF_JMP | BPF_TAIL_CALL; 22424 22425 aux = &env->insn_aux_data[i + delta]; 22426 if (env->bpf_capable && !prog->blinding_requested && 22427 prog->jit_requested && 22428 !bpf_map_key_poisoned(aux) && 22429 !bpf_map_ptr_poisoned(aux) && 22430 !bpf_map_ptr_unpriv(aux)) { 22431 struct bpf_jit_poke_descriptor desc = { 22432 .reason = BPF_POKE_REASON_TAIL_CALL, 22433 .tail_call.map = aux->map_ptr_state.map_ptr, 22434 .tail_call.key = bpf_map_key_immediate(aux), 22435 .insn_idx = i + delta, 22436 }; 22437 22438 ret = bpf_jit_add_poke_descriptor(prog, &desc); 22439 if (ret < 0) { 22440 verbose(env, "adding tail call poke descriptor failed\n"); 22441 return ret; 22442 } 22443 22444 insn->imm = ret + 1; 22445 goto next_insn; 22446 } 22447 22448 if (!bpf_map_ptr_unpriv(aux)) 22449 goto next_insn; 22450 22451 /* instead of changing every JIT dealing with tail_call 22452 * emit two extra insns: 22453 * if (index >= max_entries) goto out; 22454 * index &= array->index_mask; 22455 * to avoid out-of-bounds cpu speculation 22456 */ 22457 if (bpf_map_ptr_poisoned(aux)) { 22458 verbose(env, "tail_call abusing map_ptr\n"); 22459 return -EINVAL; 22460 } 22461 22462 map_ptr = aux->map_ptr_state.map_ptr; 22463 insn_buf[0] = BPF_JMP_IMM(BPF_JGE, BPF_REG_3, 22464 map_ptr->max_entries, 2); 22465 insn_buf[1] = BPF_ALU32_IMM(BPF_AND, BPF_REG_3, 22466 container_of(map_ptr, 22467 struct bpf_array, 22468 map)->index_mask); 22469 insn_buf[2] = *insn; 22470 cnt = 3; 22471 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 22472 if (!new_prog) 22473 return -ENOMEM; 22474 22475 delta += cnt - 1; 22476 env->prog = prog = new_prog; 22477 insn = new_prog->insnsi + i + delta; 22478 goto next_insn; 22479 } 22480 22481 if (insn->imm == BPF_FUNC_timer_set_callback) { 22482 /* The verifier will process callback_fn as many times as necessary 22483 * with different maps and the register states prepared by 22484 * set_timer_callback_state will be accurate. 22485 * 22486 * The following use case is valid: 22487 * map1 is shared by prog1, prog2, prog3. 22488 * prog1 calls bpf_timer_init for some map1 elements 22489 * prog2 calls bpf_timer_set_callback for some map1 elements. 22490 * Those that were not bpf_timer_init-ed will return -EINVAL. 22491 * prog3 calls bpf_timer_start for some map1 elements. 22492 * Those that were not both bpf_timer_init-ed and 22493 * bpf_timer_set_callback-ed will return -EINVAL. 22494 */ 22495 struct bpf_insn ld_addrs[2] = { 22496 BPF_LD_IMM64(BPF_REG_3, (long)prog->aux), 22497 }; 22498 22499 insn_buf[0] = ld_addrs[0]; 22500 insn_buf[1] = ld_addrs[1]; 22501 insn_buf[2] = *insn; 22502 cnt = 3; 22503 22504 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 22505 if (!new_prog) 22506 return -ENOMEM; 22507 22508 delta += cnt - 1; 22509 env->prog = prog = new_prog; 22510 insn = new_prog->insnsi + i + delta; 22511 goto patch_call_imm; 22512 } 22513 22514 if (is_storage_get_function(insn->imm)) { 22515 if (!in_sleepable(env) || 22516 env->insn_aux_data[i + delta].storage_get_func_atomic) 22517 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_5, (__force __s32)GFP_ATOMIC); 22518 else 22519 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_5, (__force __s32)GFP_KERNEL); 22520 insn_buf[1] = *insn; 22521 cnt = 2; 22522 22523 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 22524 if (!new_prog) 22525 return -ENOMEM; 22526 22527 delta += cnt - 1; 22528 env->prog = prog = new_prog; 22529 insn = new_prog->insnsi + i + delta; 22530 goto patch_call_imm; 22531 } 22532 22533 /* bpf_per_cpu_ptr() and bpf_this_cpu_ptr() */ 22534 if (env->insn_aux_data[i + delta].call_with_percpu_alloc_ptr) { 22535 /* patch with 'r1 = *(u64 *)(r1 + 0)' since for percpu data, 22536 * bpf_mem_alloc() returns a ptr to the percpu data ptr. 22537 */ 22538 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_1, BPF_REG_1, 0); 22539 insn_buf[1] = *insn; 22540 cnt = 2; 22541 22542 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 22543 if (!new_prog) 22544 return -ENOMEM; 22545 22546 delta += cnt - 1; 22547 env->prog = prog = new_prog; 22548 insn = new_prog->insnsi + i + delta; 22549 goto patch_call_imm; 22550 } 22551 22552 /* BPF_EMIT_CALL() assumptions in some of the map_gen_lookup 22553 * and other inlining handlers are currently limited to 64 bit 22554 * only. 22555 */ 22556 if (prog->jit_requested && BITS_PER_LONG == 64 && 22557 (insn->imm == BPF_FUNC_map_lookup_elem || 22558 insn->imm == BPF_FUNC_map_update_elem || 22559 insn->imm == BPF_FUNC_map_delete_elem || 22560 insn->imm == BPF_FUNC_map_push_elem || 22561 insn->imm == BPF_FUNC_map_pop_elem || 22562 insn->imm == BPF_FUNC_map_peek_elem || 22563 insn->imm == BPF_FUNC_redirect_map || 22564 insn->imm == BPF_FUNC_for_each_map_elem || 22565 insn->imm == BPF_FUNC_map_lookup_percpu_elem)) { 22566 aux = &env->insn_aux_data[i + delta]; 22567 if (bpf_map_ptr_poisoned(aux)) 22568 goto patch_call_imm; 22569 22570 map_ptr = aux->map_ptr_state.map_ptr; 22571 ops = map_ptr->ops; 22572 if (insn->imm == BPF_FUNC_map_lookup_elem && 22573 ops->map_gen_lookup) { 22574 cnt = ops->map_gen_lookup(map_ptr, insn_buf); 22575 if (cnt == -EOPNOTSUPP) 22576 goto patch_map_ops_generic; 22577 if (cnt <= 0 || cnt >= INSN_BUF_SIZE) { 22578 verifier_bug(env, "%d insns generated for map lookup", cnt); 22579 return -EFAULT; 22580 } 22581 22582 new_prog = bpf_patch_insn_data(env, i + delta, 22583 insn_buf, cnt); 22584 if (!new_prog) 22585 return -ENOMEM; 22586 22587 delta += cnt - 1; 22588 env->prog = prog = new_prog; 22589 insn = new_prog->insnsi + i + delta; 22590 goto next_insn; 22591 } 22592 22593 BUILD_BUG_ON(!__same_type(ops->map_lookup_elem, 22594 (void *(*)(struct bpf_map *map, void *key))NULL)); 22595 BUILD_BUG_ON(!__same_type(ops->map_delete_elem, 22596 (long (*)(struct bpf_map *map, void *key))NULL)); 22597 BUILD_BUG_ON(!__same_type(ops->map_update_elem, 22598 (long (*)(struct bpf_map *map, void *key, void *value, 22599 u64 flags))NULL)); 22600 BUILD_BUG_ON(!__same_type(ops->map_push_elem, 22601 (long (*)(struct bpf_map *map, void *value, 22602 u64 flags))NULL)); 22603 BUILD_BUG_ON(!__same_type(ops->map_pop_elem, 22604 (long (*)(struct bpf_map *map, void *value))NULL)); 22605 BUILD_BUG_ON(!__same_type(ops->map_peek_elem, 22606 (long (*)(struct bpf_map *map, void *value))NULL)); 22607 BUILD_BUG_ON(!__same_type(ops->map_redirect, 22608 (long (*)(struct bpf_map *map, u64 index, u64 flags))NULL)); 22609 BUILD_BUG_ON(!__same_type(ops->map_for_each_callback, 22610 (long (*)(struct bpf_map *map, 22611 bpf_callback_t callback_fn, 22612 void *callback_ctx, 22613 u64 flags))NULL)); 22614 BUILD_BUG_ON(!__same_type(ops->map_lookup_percpu_elem, 22615 (void *(*)(struct bpf_map *map, void *key, u32 cpu))NULL)); 22616 22617 patch_map_ops_generic: 22618 switch (insn->imm) { 22619 case BPF_FUNC_map_lookup_elem: 22620 insn->imm = BPF_CALL_IMM(ops->map_lookup_elem); 22621 goto next_insn; 22622 case BPF_FUNC_map_update_elem: 22623 insn->imm = BPF_CALL_IMM(ops->map_update_elem); 22624 goto next_insn; 22625 case BPF_FUNC_map_delete_elem: 22626 insn->imm = BPF_CALL_IMM(ops->map_delete_elem); 22627 goto next_insn; 22628 case BPF_FUNC_map_push_elem: 22629 insn->imm = BPF_CALL_IMM(ops->map_push_elem); 22630 goto next_insn; 22631 case BPF_FUNC_map_pop_elem: 22632 insn->imm = BPF_CALL_IMM(ops->map_pop_elem); 22633 goto next_insn; 22634 case BPF_FUNC_map_peek_elem: 22635 insn->imm = BPF_CALL_IMM(ops->map_peek_elem); 22636 goto next_insn; 22637 case BPF_FUNC_redirect_map: 22638 insn->imm = BPF_CALL_IMM(ops->map_redirect); 22639 goto next_insn; 22640 case BPF_FUNC_for_each_map_elem: 22641 insn->imm = BPF_CALL_IMM(ops->map_for_each_callback); 22642 goto next_insn; 22643 case BPF_FUNC_map_lookup_percpu_elem: 22644 insn->imm = BPF_CALL_IMM(ops->map_lookup_percpu_elem); 22645 goto next_insn; 22646 } 22647 22648 goto patch_call_imm; 22649 } 22650 22651 /* Implement bpf_jiffies64 inline. */ 22652 if (prog->jit_requested && BITS_PER_LONG == 64 && 22653 insn->imm == BPF_FUNC_jiffies64) { 22654 struct bpf_insn ld_jiffies_addr[2] = { 22655 BPF_LD_IMM64(BPF_REG_0, 22656 (unsigned long)&jiffies), 22657 }; 22658 22659 insn_buf[0] = ld_jiffies_addr[0]; 22660 insn_buf[1] = ld_jiffies_addr[1]; 22661 insn_buf[2] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, 22662 BPF_REG_0, 0); 22663 cnt = 3; 22664 22665 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 22666 cnt); 22667 if (!new_prog) 22668 return -ENOMEM; 22669 22670 delta += cnt - 1; 22671 env->prog = prog = new_prog; 22672 insn = new_prog->insnsi + i + delta; 22673 goto next_insn; 22674 } 22675 22676 #if defined(CONFIG_X86_64) && !defined(CONFIG_UML) 22677 /* Implement bpf_get_smp_processor_id() inline. */ 22678 if (insn->imm == BPF_FUNC_get_smp_processor_id && 22679 verifier_inlines_helper_call(env, insn->imm)) { 22680 /* BPF_FUNC_get_smp_processor_id inlining is an 22681 * optimization, so if cpu_number is ever 22682 * changed in some incompatible and hard to support 22683 * way, it's fine to back out this inlining logic 22684 */ 22685 #ifdef CONFIG_SMP 22686 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_0, (u32)(unsigned long)&cpu_number); 22687 insn_buf[1] = BPF_MOV64_PERCPU_REG(BPF_REG_0, BPF_REG_0); 22688 insn_buf[2] = BPF_LDX_MEM(BPF_W, BPF_REG_0, BPF_REG_0, 0); 22689 cnt = 3; 22690 #else 22691 insn_buf[0] = BPF_ALU32_REG(BPF_XOR, BPF_REG_0, BPF_REG_0); 22692 cnt = 1; 22693 #endif 22694 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 22695 if (!new_prog) 22696 return -ENOMEM; 22697 22698 delta += cnt - 1; 22699 env->prog = prog = new_prog; 22700 insn = new_prog->insnsi + i + delta; 22701 goto next_insn; 22702 } 22703 #endif 22704 /* Implement bpf_get_func_arg inline. */ 22705 if (prog_type == BPF_PROG_TYPE_TRACING && 22706 insn->imm == BPF_FUNC_get_func_arg) { 22707 /* Load nr_args from ctx - 8 */ 22708 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8); 22709 insn_buf[1] = BPF_JMP32_REG(BPF_JGE, BPF_REG_2, BPF_REG_0, 6); 22710 insn_buf[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_2, 3); 22711 insn_buf[3] = BPF_ALU64_REG(BPF_ADD, BPF_REG_2, BPF_REG_1); 22712 insn_buf[4] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_2, 0); 22713 insn_buf[5] = BPF_STX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0); 22714 insn_buf[6] = BPF_MOV64_IMM(BPF_REG_0, 0); 22715 insn_buf[7] = BPF_JMP_A(1); 22716 insn_buf[8] = BPF_MOV64_IMM(BPF_REG_0, -EINVAL); 22717 cnt = 9; 22718 22719 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 22720 if (!new_prog) 22721 return -ENOMEM; 22722 22723 delta += cnt - 1; 22724 env->prog = prog = new_prog; 22725 insn = new_prog->insnsi + i + delta; 22726 goto next_insn; 22727 } 22728 22729 /* Implement bpf_get_func_ret inline. */ 22730 if (prog_type == BPF_PROG_TYPE_TRACING && 22731 insn->imm == BPF_FUNC_get_func_ret) { 22732 if (eatype == BPF_TRACE_FEXIT || 22733 eatype == BPF_MODIFY_RETURN) { 22734 /* Load nr_args from ctx - 8 */ 22735 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8); 22736 insn_buf[1] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_0, 3); 22737 insn_buf[2] = BPF_ALU64_REG(BPF_ADD, BPF_REG_0, BPF_REG_1); 22738 insn_buf[3] = BPF_LDX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0); 22739 insn_buf[4] = BPF_STX_MEM(BPF_DW, BPF_REG_2, BPF_REG_3, 0); 22740 insn_buf[5] = BPF_MOV64_IMM(BPF_REG_0, 0); 22741 cnt = 6; 22742 } else { 22743 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_0, -EOPNOTSUPP); 22744 cnt = 1; 22745 } 22746 22747 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 22748 if (!new_prog) 22749 return -ENOMEM; 22750 22751 delta += cnt - 1; 22752 env->prog = prog = new_prog; 22753 insn = new_prog->insnsi + i + delta; 22754 goto next_insn; 22755 } 22756 22757 /* Implement get_func_arg_cnt inline. */ 22758 if (prog_type == BPF_PROG_TYPE_TRACING && 22759 insn->imm == BPF_FUNC_get_func_arg_cnt) { 22760 /* Load nr_args from ctx - 8 */ 22761 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8); 22762 22763 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1); 22764 if (!new_prog) 22765 return -ENOMEM; 22766 22767 env->prog = prog = new_prog; 22768 insn = new_prog->insnsi + i + delta; 22769 goto next_insn; 22770 } 22771 22772 /* Implement bpf_get_func_ip inline. */ 22773 if (prog_type == BPF_PROG_TYPE_TRACING && 22774 insn->imm == BPF_FUNC_get_func_ip) { 22775 /* Load IP address from ctx - 16 */ 22776 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -16); 22777 22778 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1); 22779 if (!new_prog) 22780 return -ENOMEM; 22781 22782 env->prog = prog = new_prog; 22783 insn = new_prog->insnsi + i + delta; 22784 goto next_insn; 22785 } 22786 22787 /* Implement bpf_get_branch_snapshot inline. */ 22788 if (IS_ENABLED(CONFIG_PERF_EVENTS) && 22789 prog->jit_requested && BITS_PER_LONG == 64 && 22790 insn->imm == BPF_FUNC_get_branch_snapshot) { 22791 /* We are dealing with the following func protos: 22792 * u64 bpf_get_branch_snapshot(void *buf, u32 size, u64 flags); 22793 * int perf_snapshot_branch_stack(struct perf_branch_entry *entries, u32 cnt); 22794 */ 22795 const u32 br_entry_size = sizeof(struct perf_branch_entry); 22796 22797 /* struct perf_branch_entry is part of UAPI and is 22798 * used as an array element, so extremely unlikely to 22799 * ever grow or shrink 22800 */ 22801 BUILD_BUG_ON(br_entry_size != 24); 22802 22803 /* if (unlikely(flags)) return -EINVAL */ 22804 insn_buf[0] = BPF_JMP_IMM(BPF_JNE, BPF_REG_3, 0, 7); 22805 22806 /* Transform size (bytes) into number of entries (cnt = size / 24). 22807 * But to avoid expensive division instruction, we implement 22808 * divide-by-3 through multiplication, followed by further 22809 * division by 8 through 3-bit right shift. 22810 * Refer to book "Hacker's Delight, 2nd ed." by Henry S. Warren, Jr., 22811 * p. 227, chapter "Unsigned Division by 3" for details and proofs. 22812 * 22813 * N / 3 <=> M * N / 2^33, where M = (2^33 + 1) / 3 = 0xaaaaaaab. 22814 */ 22815 insn_buf[1] = BPF_MOV32_IMM(BPF_REG_0, 0xaaaaaaab); 22816 insn_buf[2] = BPF_ALU64_REG(BPF_MUL, BPF_REG_2, BPF_REG_0); 22817 insn_buf[3] = BPF_ALU64_IMM(BPF_RSH, BPF_REG_2, 36); 22818 22819 /* call perf_snapshot_branch_stack implementation */ 22820 insn_buf[4] = BPF_EMIT_CALL(static_call_query(perf_snapshot_branch_stack)); 22821 /* if (entry_cnt == 0) return -ENOENT */ 22822 insn_buf[5] = BPF_JMP_IMM(BPF_JEQ, BPF_REG_0, 0, 4); 22823 /* return entry_cnt * sizeof(struct perf_branch_entry) */ 22824 insn_buf[6] = BPF_ALU32_IMM(BPF_MUL, BPF_REG_0, br_entry_size); 22825 insn_buf[7] = BPF_JMP_A(3); 22826 /* return -EINVAL; */ 22827 insn_buf[8] = BPF_MOV64_IMM(BPF_REG_0, -EINVAL); 22828 insn_buf[9] = BPF_JMP_A(1); 22829 /* return -ENOENT; */ 22830 insn_buf[10] = BPF_MOV64_IMM(BPF_REG_0, -ENOENT); 22831 cnt = 11; 22832 22833 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 22834 if (!new_prog) 22835 return -ENOMEM; 22836 22837 delta += cnt - 1; 22838 env->prog = prog = new_prog; 22839 insn = new_prog->insnsi + i + delta; 22840 goto next_insn; 22841 } 22842 22843 /* Implement bpf_kptr_xchg inline */ 22844 if (prog->jit_requested && BITS_PER_LONG == 64 && 22845 insn->imm == BPF_FUNC_kptr_xchg && 22846 bpf_jit_supports_ptr_xchg()) { 22847 insn_buf[0] = BPF_MOV64_REG(BPF_REG_0, BPF_REG_2); 22848 insn_buf[1] = BPF_ATOMIC_OP(BPF_DW, BPF_XCHG, BPF_REG_1, BPF_REG_0, 0); 22849 cnt = 2; 22850 22851 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 22852 if (!new_prog) 22853 return -ENOMEM; 22854 22855 delta += cnt - 1; 22856 env->prog = prog = new_prog; 22857 insn = new_prog->insnsi + i + delta; 22858 goto next_insn; 22859 } 22860 patch_call_imm: 22861 fn = env->ops->get_func_proto(insn->imm, env->prog); 22862 /* all functions that have prototype and verifier allowed 22863 * programs to call them, must be real in-kernel functions 22864 */ 22865 if (!fn->func) { 22866 verifier_bug(env, 22867 "not inlined functions %s#%d is missing func", 22868 func_id_name(insn->imm), insn->imm); 22869 return -EFAULT; 22870 } 22871 insn->imm = fn->func - __bpf_call_base; 22872 next_insn: 22873 if (subprogs[cur_subprog + 1].start == i + delta + 1) { 22874 subprogs[cur_subprog].stack_depth += stack_depth_extra; 22875 subprogs[cur_subprog].stack_extra = stack_depth_extra; 22876 22877 stack_depth = subprogs[cur_subprog].stack_depth; 22878 if (stack_depth > MAX_BPF_STACK && !prog->jit_requested) { 22879 verbose(env, "stack size %d(extra %d) is too large\n", 22880 stack_depth, stack_depth_extra); 22881 return -EINVAL; 22882 } 22883 cur_subprog++; 22884 stack_depth = subprogs[cur_subprog].stack_depth; 22885 stack_depth_extra = 0; 22886 } 22887 i++; 22888 insn++; 22889 } 22890 22891 env->prog->aux->stack_depth = subprogs[0].stack_depth; 22892 for (i = 0; i < env->subprog_cnt; i++) { 22893 int delta = bpf_jit_supports_timed_may_goto() ? 2 : 1; 22894 int subprog_start = subprogs[i].start; 22895 int stack_slots = subprogs[i].stack_extra / 8; 22896 int slots = delta, cnt = 0; 22897 22898 if (!stack_slots) 22899 continue; 22900 /* We need two slots in case timed may_goto is supported. */ 22901 if (stack_slots > slots) { 22902 verifier_bug(env, "stack_slots supports may_goto only"); 22903 return -EFAULT; 22904 } 22905 22906 stack_depth = subprogs[i].stack_depth; 22907 if (bpf_jit_supports_timed_may_goto()) { 22908 insn_buf[cnt++] = BPF_ST_MEM(BPF_DW, BPF_REG_FP, -stack_depth, 22909 BPF_MAX_TIMED_LOOPS); 22910 insn_buf[cnt++] = BPF_ST_MEM(BPF_DW, BPF_REG_FP, -stack_depth + 8, 0); 22911 } else { 22912 /* Add ST insn to subprog prologue to init extra stack */ 22913 insn_buf[cnt++] = BPF_ST_MEM(BPF_DW, BPF_REG_FP, -stack_depth, 22914 BPF_MAX_LOOPS); 22915 } 22916 /* Copy first actual insn to preserve it */ 22917 insn_buf[cnt++] = env->prog->insnsi[subprog_start]; 22918 22919 new_prog = bpf_patch_insn_data(env, subprog_start, insn_buf, cnt); 22920 if (!new_prog) 22921 return -ENOMEM; 22922 env->prog = prog = new_prog; 22923 /* 22924 * If may_goto is a first insn of a prog there could be a jmp 22925 * insn that points to it, hence adjust all such jmps to point 22926 * to insn after BPF_ST that inits may_goto count. 22927 * Adjustment will succeed because bpf_patch_insn_data() didn't fail. 22928 */ 22929 WARN_ON(adjust_jmp_off(env->prog, subprog_start, delta)); 22930 } 22931 22932 /* Since poke tab is now finalized, publish aux to tracker. */ 22933 for (i = 0; i < prog->aux->size_poke_tab; i++) { 22934 map_ptr = prog->aux->poke_tab[i].tail_call.map; 22935 if (!map_ptr->ops->map_poke_track || 22936 !map_ptr->ops->map_poke_untrack || 22937 !map_ptr->ops->map_poke_run) { 22938 verifier_bug(env, "poke tab is misconfigured"); 22939 return -EFAULT; 22940 } 22941 22942 ret = map_ptr->ops->map_poke_track(map_ptr, prog->aux); 22943 if (ret < 0) { 22944 verbose(env, "tracking tail call prog failed\n"); 22945 return ret; 22946 } 22947 } 22948 22949 sort_kfunc_descs_by_imm_off(env->prog); 22950 22951 return 0; 22952 } 22953 22954 static struct bpf_prog *inline_bpf_loop(struct bpf_verifier_env *env, 22955 int position, 22956 s32 stack_base, 22957 u32 callback_subprogno, 22958 u32 *total_cnt) 22959 { 22960 s32 r6_offset = stack_base + 0 * BPF_REG_SIZE; 22961 s32 r7_offset = stack_base + 1 * BPF_REG_SIZE; 22962 s32 r8_offset = stack_base + 2 * BPF_REG_SIZE; 22963 int reg_loop_max = BPF_REG_6; 22964 int reg_loop_cnt = BPF_REG_7; 22965 int reg_loop_ctx = BPF_REG_8; 22966 22967 struct bpf_insn *insn_buf = env->insn_buf; 22968 struct bpf_prog *new_prog; 22969 u32 callback_start; 22970 u32 call_insn_offset; 22971 s32 callback_offset; 22972 u32 cnt = 0; 22973 22974 /* This represents an inlined version of bpf_iter.c:bpf_loop, 22975 * be careful to modify this code in sync. 22976 */ 22977 22978 /* Return error and jump to the end of the patch if 22979 * expected number of iterations is too big. 22980 */ 22981 insn_buf[cnt++] = BPF_JMP_IMM(BPF_JLE, BPF_REG_1, BPF_MAX_LOOPS, 2); 22982 insn_buf[cnt++] = BPF_MOV32_IMM(BPF_REG_0, -E2BIG); 22983 insn_buf[cnt++] = BPF_JMP_IMM(BPF_JA, 0, 0, 16); 22984 /* spill R6, R7, R8 to use these as loop vars */ 22985 insn_buf[cnt++] = BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_6, r6_offset); 22986 insn_buf[cnt++] = BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_7, r7_offset); 22987 insn_buf[cnt++] = BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_8, r8_offset); 22988 /* initialize loop vars */ 22989 insn_buf[cnt++] = BPF_MOV64_REG(reg_loop_max, BPF_REG_1); 22990 insn_buf[cnt++] = BPF_MOV32_IMM(reg_loop_cnt, 0); 22991 insn_buf[cnt++] = BPF_MOV64_REG(reg_loop_ctx, BPF_REG_3); 22992 /* loop header, 22993 * if reg_loop_cnt >= reg_loop_max skip the loop body 22994 */ 22995 insn_buf[cnt++] = BPF_JMP_REG(BPF_JGE, reg_loop_cnt, reg_loop_max, 5); 22996 /* callback call, 22997 * correct callback offset would be set after patching 22998 */ 22999 insn_buf[cnt++] = BPF_MOV64_REG(BPF_REG_1, reg_loop_cnt); 23000 insn_buf[cnt++] = BPF_MOV64_REG(BPF_REG_2, reg_loop_ctx); 23001 insn_buf[cnt++] = BPF_CALL_REL(0); 23002 /* increment loop counter */ 23003 insn_buf[cnt++] = BPF_ALU64_IMM(BPF_ADD, reg_loop_cnt, 1); 23004 /* jump to loop header if callback returned 0 */ 23005 insn_buf[cnt++] = BPF_JMP_IMM(BPF_JEQ, BPF_REG_0, 0, -6); 23006 /* return value of bpf_loop, 23007 * set R0 to the number of iterations 23008 */ 23009 insn_buf[cnt++] = BPF_MOV64_REG(BPF_REG_0, reg_loop_cnt); 23010 /* restore original values of R6, R7, R8 */ 23011 insn_buf[cnt++] = BPF_LDX_MEM(BPF_DW, BPF_REG_6, BPF_REG_10, r6_offset); 23012 insn_buf[cnt++] = BPF_LDX_MEM(BPF_DW, BPF_REG_7, BPF_REG_10, r7_offset); 23013 insn_buf[cnt++] = BPF_LDX_MEM(BPF_DW, BPF_REG_8, BPF_REG_10, r8_offset); 23014 23015 *total_cnt = cnt; 23016 new_prog = bpf_patch_insn_data(env, position, insn_buf, cnt); 23017 if (!new_prog) 23018 return new_prog; 23019 23020 /* callback start is known only after patching */ 23021 callback_start = env->subprog_info[callback_subprogno].start; 23022 /* Note: insn_buf[12] is an offset of BPF_CALL_REL instruction */ 23023 call_insn_offset = position + 12; 23024 callback_offset = callback_start - call_insn_offset - 1; 23025 new_prog->insnsi[call_insn_offset].imm = callback_offset; 23026 23027 return new_prog; 23028 } 23029 23030 static bool is_bpf_loop_call(struct bpf_insn *insn) 23031 { 23032 return insn->code == (BPF_JMP | BPF_CALL) && 23033 insn->src_reg == 0 && 23034 insn->imm == BPF_FUNC_loop; 23035 } 23036 23037 /* For all sub-programs in the program (including main) check 23038 * insn_aux_data to see if there are bpf_loop calls that require 23039 * inlining. If such calls are found the calls are replaced with a 23040 * sequence of instructions produced by `inline_bpf_loop` function and 23041 * subprog stack_depth is increased by the size of 3 registers. 23042 * This stack space is used to spill values of the R6, R7, R8. These 23043 * registers are used to store the loop bound, counter and context 23044 * variables. 23045 */ 23046 static int optimize_bpf_loop(struct bpf_verifier_env *env) 23047 { 23048 struct bpf_subprog_info *subprogs = env->subprog_info; 23049 int i, cur_subprog = 0, cnt, delta = 0; 23050 struct bpf_insn *insn = env->prog->insnsi; 23051 int insn_cnt = env->prog->len; 23052 u16 stack_depth = subprogs[cur_subprog].stack_depth; 23053 u16 stack_depth_roundup = round_up(stack_depth, 8) - stack_depth; 23054 u16 stack_depth_extra = 0; 23055 23056 for (i = 0; i < insn_cnt; i++, insn++) { 23057 struct bpf_loop_inline_state *inline_state = 23058 &env->insn_aux_data[i + delta].loop_inline_state; 23059 23060 if (is_bpf_loop_call(insn) && inline_state->fit_for_inline) { 23061 struct bpf_prog *new_prog; 23062 23063 stack_depth_extra = BPF_REG_SIZE * 3 + stack_depth_roundup; 23064 new_prog = inline_bpf_loop(env, 23065 i + delta, 23066 -(stack_depth + stack_depth_extra), 23067 inline_state->callback_subprogno, 23068 &cnt); 23069 if (!new_prog) 23070 return -ENOMEM; 23071 23072 delta += cnt - 1; 23073 env->prog = new_prog; 23074 insn = new_prog->insnsi + i + delta; 23075 } 23076 23077 if (subprogs[cur_subprog + 1].start == i + delta + 1) { 23078 subprogs[cur_subprog].stack_depth += stack_depth_extra; 23079 cur_subprog++; 23080 stack_depth = subprogs[cur_subprog].stack_depth; 23081 stack_depth_roundup = round_up(stack_depth, 8) - stack_depth; 23082 stack_depth_extra = 0; 23083 } 23084 } 23085 23086 env->prog->aux->stack_depth = env->subprog_info[0].stack_depth; 23087 23088 return 0; 23089 } 23090 23091 /* Remove unnecessary spill/fill pairs, members of fastcall pattern, 23092 * adjust subprograms stack depth when possible. 23093 */ 23094 static int remove_fastcall_spills_fills(struct bpf_verifier_env *env) 23095 { 23096 struct bpf_subprog_info *subprog = env->subprog_info; 23097 struct bpf_insn_aux_data *aux = env->insn_aux_data; 23098 struct bpf_insn *insn = env->prog->insnsi; 23099 int insn_cnt = env->prog->len; 23100 u32 spills_num; 23101 bool modified = false; 23102 int i, j; 23103 23104 for (i = 0; i < insn_cnt; i++, insn++) { 23105 if (aux[i].fastcall_spills_num > 0) { 23106 spills_num = aux[i].fastcall_spills_num; 23107 /* NOPs would be removed by opt_remove_nops() */ 23108 for (j = 1; j <= spills_num; ++j) { 23109 *(insn - j) = NOP; 23110 *(insn + j) = NOP; 23111 } 23112 modified = true; 23113 } 23114 if ((subprog + 1)->start == i + 1) { 23115 if (modified && !subprog->keep_fastcall_stack) 23116 subprog->stack_depth = -subprog->fastcall_stack_off; 23117 subprog++; 23118 modified = false; 23119 } 23120 } 23121 23122 return 0; 23123 } 23124 23125 static void free_states(struct bpf_verifier_env *env) 23126 { 23127 struct bpf_verifier_state_list *sl; 23128 struct list_head *head, *pos, *tmp; 23129 struct bpf_scc_info *info; 23130 int i, j; 23131 23132 free_verifier_state(env->cur_state, true); 23133 env->cur_state = NULL; 23134 while (!pop_stack(env, NULL, NULL, false)); 23135 23136 list_for_each_safe(pos, tmp, &env->free_list) { 23137 sl = container_of(pos, struct bpf_verifier_state_list, node); 23138 free_verifier_state(&sl->state, false); 23139 kfree(sl); 23140 } 23141 INIT_LIST_HEAD(&env->free_list); 23142 23143 for (i = 0; i < env->scc_cnt; ++i) { 23144 info = env->scc_info[i]; 23145 if (!info) 23146 continue; 23147 for (j = 0; j < info->num_visits; j++) 23148 free_backedges(&info->visits[j]); 23149 kvfree(info); 23150 env->scc_info[i] = NULL; 23151 } 23152 23153 if (!env->explored_states) 23154 return; 23155 23156 for (i = 0; i < state_htab_size(env); i++) { 23157 head = &env->explored_states[i]; 23158 23159 list_for_each_safe(pos, tmp, head) { 23160 sl = container_of(pos, struct bpf_verifier_state_list, node); 23161 free_verifier_state(&sl->state, false); 23162 kfree(sl); 23163 } 23164 INIT_LIST_HEAD(&env->explored_states[i]); 23165 } 23166 } 23167 23168 static int do_check_common(struct bpf_verifier_env *env, int subprog) 23169 { 23170 bool pop_log = !(env->log.level & BPF_LOG_LEVEL2); 23171 struct bpf_subprog_info *sub = subprog_info(env, subprog); 23172 struct bpf_prog_aux *aux = env->prog->aux; 23173 struct bpf_verifier_state *state; 23174 struct bpf_reg_state *regs; 23175 int ret, i; 23176 23177 env->prev_linfo = NULL; 23178 env->pass_cnt++; 23179 23180 state = kzalloc(sizeof(struct bpf_verifier_state), GFP_KERNEL_ACCOUNT); 23181 if (!state) 23182 return -ENOMEM; 23183 state->curframe = 0; 23184 state->speculative = false; 23185 state->branches = 1; 23186 state->frame[0] = kzalloc(sizeof(struct bpf_func_state), GFP_KERNEL_ACCOUNT); 23187 if (!state->frame[0]) { 23188 kfree(state); 23189 return -ENOMEM; 23190 } 23191 env->cur_state = state; 23192 init_func_state(env, state->frame[0], 23193 BPF_MAIN_FUNC /* callsite */, 23194 0 /* frameno */, 23195 subprog); 23196 state->first_insn_idx = env->subprog_info[subprog].start; 23197 state->last_insn_idx = -1; 23198 23199 regs = state->frame[state->curframe]->regs; 23200 if (subprog || env->prog->type == BPF_PROG_TYPE_EXT) { 23201 const char *sub_name = subprog_name(env, subprog); 23202 struct bpf_subprog_arg_info *arg; 23203 struct bpf_reg_state *reg; 23204 23205 verbose(env, "Validating %s() func#%d...\n", sub_name, subprog); 23206 ret = btf_prepare_func_args(env, subprog); 23207 if (ret) 23208 goto out; 23209 23210 if (subprog_is_exc_cb(env, subprog)) { 23211 state->frame[0]->in_exception_callback_fn = true; 23212 /* We have already ensured that the callback returns an integer, just 23213 * like all global subprogs. We need to determine it only has a single 23214 * scalar argument. 23215 */ 23216 if (sub->arg_cnt != 1 || sub->args[0].arg_type != ARG_ANYTHING) { 23217 verbose(env, "exception cb only supports single integer argument\n"); 23218 ret = -EINVAL; 23219 goto out; 23220 } 23221 } 23222 for (i = BPF_REG_1; i <= sub->arg_cnt; i++) { 23223 arg = &sub->args[i - BPF_REG_1]; 23224 reg = ®s[i]; 23225 23226 if (arg->arg_type == ARG_PTR_TO_CTX) { 23227 reg->type = PTR_TO_CTX; 23228 mark_reg_known_zero(env, regs, i); 23229 } else if (arg->arg_type == ARG_ANYTHING) { 23230 reg->type = SCALAR_VALUE; 23231 mark_reg_unknown(env, regs, i); 23232 } else if (arg->arg_type == (ARG_PTR_TO_DYNPTR | MEM_RDONLY)) { 23233 /* assume unspecial LOCAL dynptr type */ 23234 __mark_dynptr_reg(reg, BPF_DYNPTR_TYPE_LOCAL, true, ++env->id_gen); 23235 } else if (base_type(arg->arg_type) == ARG_PTR_TO_MEM) { 23236 reg->type = PTR_TO_MEM; 23237 reg->type |= arg->arg_type & 23238 (PTR_MAYBE_NULL | PTR_UNTRUSTED | MEM_RDONLY); 23239 mark_reg_known_zero(env, regs, i); 23240 reg->mem_size = arg->mem_size; 23241 if (arg->arg_type & PTR_MAYBE_NULL) 23242 reg->id = ++env->id_gen; 23243 } else if (base_type(arg->arg_type) == ARG_PTR_TO_BTF_ID) { 23244 reg->type = PTR_TO_BTF_ID; 23245 if (arg->arg_type & PTR_MAYBE_NULL) 23246 reg->type |= PTR_MAYBE_NULL; 23247 if (arg->arg_type & PTR_UNTRUSTED) 23248 reg->type |= PTR_UNTRUSTED; 23249 if (arg->arg_type & PTR_TRUSTED) 23250 reg->type |= PTR_TRUSTED; 23251 mark_reg_known_zero(env, regs, i); 23252 reg->btf = bpf_get_btf_vmlinux(); /* can't fail at this point */ 23253 reg->btf_id = arg->btf_id; 23254 reg->id = ++env->id_gen; 23255 } else if (base_type(arg->arg_type) == ARG_PTR_TO_ARENA) { 23256 /* caller can pass either PTR_TO_ARENA or SCALAR */ 23257 mark_reg_unknown(env, regs, i); 23258 } else { 23259 verifier_bug(env, "unhandled arg#%d type %d", 23260 i - BPF_REG_1, arg->arg_type); 23261 ret = -EFAULT; 23262 goto out; 23263 } 23264 } 23265 } else { 23266 /* if main BPF program has associated BTF info, validate that 23267 * it's matching expected signature, and otherwise mark BTF 23268 * info for main program as unreliable 23269 */ 23270 if (env->prog->aux->func_info_aux) { 23271 ret = btf_prepare_func_args(env, 0); 23272 if (ret || sub->arg_cnt != 1 || sub->args[0].arg_type != ARG_PTR_TO_CTX) 23273 env->prog->aux->func_info_aux[0].unreliable = true; 23274 } 23275 23276 /* 1st arg to a function */ 23277 regs[BPF_REG_1].type = PTR_TO_CTX; 23278 mark_reg_known_zero(env, regs, BPF_REG_1); 23279 } 23280 23281 /* Acquire references for struct_ops program arguments tagged with "__ref" */ 23282 if (!subprog && env->prog->type == BPF_PROG_TYPE_STRUCT_OPS) { 23283 for (i = 0; i < aux->ctx_arg_info_size; i++) 23284 aux->ctx_arg_info[i].ref_obj_id = aux->ctx_arg_info[i].refcounted ? 23285 acquire_reference(env, 0) : 0; 23286 } 23287 23288 ret = do_check(env); 23289 out: 23290 if (!ret && pop_log) 23291 bpf_vlog_reset(&env->log, 0); 23292 free_states(env); 23293 return ret; 23294 } 23295 23296 /* Lazily verify all global functions based on their BTF, if they are called 23297 * from main BPF program or any of subprograms transitively. 23298 * BPF global subprogs called from dead code are not validated. 23299 * All callable global functions must pass verification. 23300 * Otherwise the whole program is rejected. 23301 * Consider: 23302 * int bar(int); 23303 * int foo(int f) 23304 * { 23305 * return bar(f); 23306 * } 23307 * int bar(int b) 23308 * { 23309 * ... 23310 * } 23311 * foo() will be verified first for R1=any_scalar_value. During verification it 23312 * will be assumed that bar() already verified successfully and call to bar() 23313 * from foo() will be checked for type match only. Later bar() will be verified 23314 * independently to check that it's safe for R1=any_scalar_value. 23315 */ 23316 static int do_check_subprogs(struct bpf_verifier_env *env) 23317 { 23318 struct bpf_prog_aux *aux = env->prog->aux; 23319 struct bpf_func_info_aux *sub_aux; 23320 int i, ret, new_cnt; 23321 23322 if (!aux->func_info) 23323 return 0; 23324 23325 /* exception callback is presumed to be always called */ 23326 if (env->exception_callback_subprog) 23327 subprog_aux(env, env->exception_callback_subprog)->called = true; 23328 23329 again: 23330 new_cnt = 0; 23331 for (i = 1; i < env->subprog_cnt; i++) { 23332 if (!subprog_is_global(env, i)) 23333 continue; 23334 23335 sub_aux = subprog_aux(env, i); 23336 if (!sub_aux->called || sub_aux->verified) 23337 continue; 23338 23339 env->insn_idx = env->subprog_info[i].start; 23340 WARN_ON_ONCE(env->insn_idx == 0); 23341 ret = do_check_common(env, i); 23342 if (ret) { 23343 return ret; 23344 } else if (env->log.level & BPF_LOG_LEVEL) { 23345 verbose(env, "Func#%d ('%s') is safe for any args that match its prototype\n", 23346 i, subprog_name(env, i)); 23347 } 23348 23349 /* We verified new global subprog, it might have called some 23350 * more global subprogs that we haven't verified yet, so we 23351 * need to do another pass over subprogs to verify those. 23352 */ 23353 sub_aux->verified = true; 23354 new_cnt++; 23355 } 23356 23357 /* We can't loop forever as we verify at least one global subprog on 23358 * each pass. 23359 */ 23360 if (new_cnt) 23361 goto again; 23362 23363 return 0; 23364 } 23365 23366 static int do_check_main(struct bpf_verifier_env *env) 23367 { 23368 int ret; 23369 23370 env->insn_idx = 0; 23371 ret = do_check_common(env, 0); 23372 if (!ret) 23373 env->prog->aux->stack_depth = env->subprog_info[0].stack_depth; 23374 return ret; 23375 } 23376 23377 23378 static void print_verification_stats(struct bpf_verifier_env *env) 23379 { 23380 int i; 23381 23382 if (env->log.level & BPF_LOG_STATS) { 23383 verbose(env, "verification time %lld usec\n", 23384 div_u64(env->verification_time, 1000)); 23385 verbose(env, "stack depth "); 23386 for (i = 0; i < env->subprog_cnt; i++) { 23387 u32 depth = env->subprog_info[i].stack_depth; 23388 23389 verbose(env, "%d", depth); 23390 if (i + 1 < env->subprog_cnt) 23391 verbose(env, "+"); 23392 } 23393 verbose(env, "\n"); 23394 } 23395 verbose(env, "processed %d insns (limit %d) max_states_per_insn %d " 23396 "total_states %d peak_states %d mark_read %d\n", 23397 env->insn_processed, BPF_COMPLEXITY_LIMIT_INSNS, 23398 env->max_states_per_insn, env->total_states, 23399 env->peak_states, env->longest_mark_read_walk); 23400 } 23401 23402 int bpf_prog_ctx_arg_info_init(struct bpf_prog *prog, 23403 const struct bpf_ctx_arg_aux *info, u32 cnt) 23404 { 23405 prog->aux->ctx_arg_info = kmemdup_array(info, cnt, sizeof(*info), GFP_KERNEL_ACCOUNT); 23406 prog->aux->ctx_arg_info_size = cnt; 23407 23408 return prog->aux->ctx_arg_info ? 0 : -ENOMEM; 23409 } 23410 23411 static int check_struct_ops_btf_id(struct bpf_verifier_env *env) 23412 { 23413 const struct btf_type *t, *func_proto; 23414 const struct bpf_struct_ops_desc *st_ops_desc; 23415 const struct bpf_struct_ops *st_ops; 23416 const struct btf_member *member; 23417 struct bpf_prog *prog = env->prog; 23418 bool has_refcounted_arg = false; 23419 u32 btf_id, member_idx, member_off; 23420 struct btf *btf; 23421 const char *mname; 23422 int i, err; 23423 23424 if (!prog->gpl_compatible) { 23425 verbose(env, "struct ops programs must have a GPL compatible license\n"); 23426 return -EINVAL; 23427 } 23428 23429 if (!prog->aux->attach_btf_id) 23430 return -ENOTSUPP; 23431 23432 btf = prog->aux->attach_btf; 23433 if (btf_is_module(btf)) { 23434 /* Make sure st_ops is valid through the lifetime of env */ 23435 env->attach_btf_mod = btf_try_get_module(btf); 23436 if (!env->attach_btf_mod) { 23437 verbose(env, "struct_ops module %s is not found\n", 23438 btf_get_name(btf)); 23439 return -ENOTSUPP; 23440 } 23441 } 23442 23443 btf_id = prog->aux->attach_btf_id; 23444 st_ops_desc = bpf_struct_ops_find(btf, btf_id); 23445 if (!st_ops_desc) { 23446 verbose(env, "attach_btf_id %u is not a supported struct\n", 23447 btf_id); 23448 return -ENOTSUPP; 23449 } 23450 st_ops = st_ops_desc->st_ops; 23451 23452 t = st_ops_desc->type; 23453 member_idx = prog->expected_attach_type; 23454 if (member_idx >= btf_type_vlen(t)) { 23455 verbose(env, "attach to invalid member idx %u of struct %s\n", 23456 member_idx, st_ops->name); 23457 return -EINVAL; 23458 } 23459 23460 member = &btf_type_member(t)[member_idx]; 23461 mname = btf_name_by_offset(btf, member->name_off); 23462 func_proto = btf_type_resolve_func_ptr(btf, member->type, 23463 NULL); 23464 if (!func_proto) { 23465 verbose(env, "attach to invalid member %s(@idx %u) of struct %s\n", 23466 mname, member_idx, st_ops->name); 23467 return -EINVAL; 23468 } 23469 23470 member_off = __btf_member_bit_offset(t, member) / 8; 23471 err = bpf_struct_ops_supported(st_ops, member_off); 23472 if (err) { 23473 verbose(env, "attach to unsupported member %s of struct %s\n", 23474 mname, st_ops->name); 23475 return err; 23476 } 23477 23478 if (st_ops->check_member) { 23479 err = st_ops->check_member(t, member, prog); 23480 23481 if (err) { 23482 verbose(env, "attach to unsupported member %s of struct %s\n", 23483 mname, st_ops->name); 23484 return err; 23485 } 23486 } 23487 23488 if (prog->aux->priv_stack_requested && !bpf_jit_supports_private_stack()) { 23489 verbose(env, "Private stack not supported by jit\n"); 23490 return -EACCES; 23491 } 23492 23493 for (i = 0; i < st_ops_desc->arg_info[member_idx].cnt; i++) { 23494 if (st_ops_desc->arg_info[member_idx].info->refcounted) { 23495 has_refcounted_arg = true; 23496 break; 23497 } 23498 } 23499 23500 /* Tail call is not allowed for programs with refcounted arguments since we 23501 * cannot guarantee that valid refcounted kptrs will be passed to the callee. 23502 */ 23503 for (i = 0; i < env->subprog_cnt; i++) { 23504 if (has_refcounted_arg && env->subprog_info[i].has_tail_call) { 23505 verbose(env, "program with __ref argument cannot tail call\n"); 23506 return -EINVAL; 23507 } 23508 } 23509 23510 prog->aux->st_ops = st_ops; 23511 prog->aux->attach_st_ops_member_off = member_off; 23512 23513 prog->aux->attach_func_proto = func_proto; 23514 prog->aux->attach_func_name = mname; 23515 env->ops = st_ops->verifier_ops; 23516 23517 return bpf_prog_ctx_arg_info_init(prog, st_ops_desc->arg_info[member_idx].info, 23518 st_ops_desc->arg_info[member_idx].cnt); 23519 } 23520 #define SECURITY_PREFIX "security_" 23521 23522 static int check_attach_modify_return(unsigned long addr, const char *func_name) 23523 { 23524 if (within_error_injection_list(addr) || 23525 !strncmp(SECURITY_PREFIX, func_name, sizeof(SECURITY_PREFIX) - 1)) 23526 return 0; 23527 23528 return -EINVAL; 23529 } 23530 23531 /* list of non-sleepable functions that are otherwise on 23532 * ALLOW_ERROR_INJECTION list 23533 */ 23534 BTF_SET_START(btf_non_sleepable_error_inject) 23535 /* Three functions below can be called from sleepable and non-sleepable context. 23536 * Assume non-sleepable from bpf safety point of view. 23537 */ 23538 BTF_ID(func, __filemap_add_folio) 23539 #ifdef CONFIG_FAIL_PAGE_ALLOC 23540 BTF_ID(func, should_fail_alloc_page) 23541 #endif 23542 #ifdef CONFIG_FAILSLAB 23543 BTF_ID(func, should_failslab) 23544 #endif 23545 BTF_SET_END(btf_non_sleepable_error_inject) 23546 23547 static int check_non_sleepable_error_inject(u32 btf_id) 23548 { 23549 return btf_id_set_contains(&btf_non_sleepable_error_inject, btf_id); 23550 } 23551 23552 int bpf_check_attach_target(struct bpf_verifier_log *log, 23553 const struct bpf_prog *prog, 23554 const struct bpf_prog *tgt_prog, 23555 u32 btf_id, 23556 struct bpf_attach_target_info *tgt_info) 23557 { 23558 bool prog_extension = prog->type == BPF_PROG_TYPE_EXT; 23559 bool prog_tracing = prog->type == BPF_PROG_TYPE_TRACING; 23560 char trace_symbol[KSYM_SYMBOL_LEN]; 23561 const char prefix[] = "btf_trace_"; 23562 struct bpf_raw_event_map *btp; 23563 int ret = 0, subprog = -1, i; 23564 const struct btf_type *t; 23565 bool conservative = true; 23566 const char *tname, *fname; 23567 struct btf *btf; 23568 long addr = 0; 23569 struct module *mod = NULL; 23570 23571 if (!btf_id) { 23572 bpf_log(log, "Tracing programs must provide btf_id\n"); 23573 return -EINVAL; 23574 } 23575 btf = tgt_prog ? tgt_prog->aux->btf : prog->aux->attach_btf; 23576 if (!btf) { 23577 bpf_log(log, 23578 "FENTRY/FEXIT program can only be attached to another program annotated with BTF\n"); 23579 return -EINVAL; 23580 } 23581 t = btf_type_by_id(btf, btf_id); 23582 if (!t) { 23583 bpf_log(log, "attach_btf_id %u is invalid\n", btf_id); 23584 return -EINVAL; 23585 } 23586 tname = btf_name_by_offset(btf, t->name_off); 23587 if (!tname) { 23588 bpf_log(log, "attach_btf_id %u doesn't have a name\n", btf_id); 23589 return -EINVAL; 23590 } 23591 if (tgt_prog) { 23592 struct bpf_prog_aux *aux = tgt_prog->aux; 23593 bool tgt_changes_pkt_data; 23594 bool tgt_might_sleep; 23595 23596 if (bpf_prog_is_dev_bound(prog->aux) && 23597 !bpf_prog_dev_bound_match(prog, tgt_prog)) { 23598 bpf_log(log, "Target program bound device mismatch"); 23599 return -EINVAL; 23600 } 23601 23602 for (i = 0; i < aux->func_info_cnt; i++) 23603 if (aux->func_info[i].type_id == btf_id) { 23604 subprog = i; 23605 break; 23606 } 23607 if (subprog == -1) { 23608 bpf_log(log, "Subprog %s doesn't exist\n", tname); 23609 return -EINVAL; 23610 } 23611 if (aux->func && aux->func[subprog]->aux->exception_cb) { 23612 bpf_log(log, 23613 "%s programs cannot attach to exception callback\n", 23614 prog_extension ? "Extension" : "FENTRY/FEXIT"); 23615 return -EINVAL; 23616 } 23617 conservative = aux->func_info_aux[subprog].unreliable; 23618 if (prog_extension) { 23619 if (conservative) { 23620 bpf_log(log, 23621 "Cannot replace static functions\n"); 23622 return -EINVAL; 23623 } 23624 if (!prog->jit_requested) { 23625 bpf_log(log, 23626 "Extension programs should be JITed\n"); 23627 return -EINVAL; 23628 } 23629 tgt_changes_pkt_data = aux->func 23630 ? aux->func[subprog]->aux->changes_pkt_data 23631 : aux->changes_pkt_data; 23632 if (prog->aux->changes_pkt_data && !tgt_changes_pkt_data) { 23633 bpf_log(log, 23634 "Extension program changes packet data, while original does not\n"); 23635 return -EINVAL; 23636 } 23637 23638 tgt_might_sleep = aux->func 23639 ? aux->func[subprog]->aux->might_sleep 23640 : aux->might_sleep; 23641 if (prog->aux->might_sleep && !tgt_might_sleep) { 23642 bpf_log(log, 23643 "Extension program may sleep, while original does not\n"); 23644 return -EINVAL; 23645 } 23646 } 23647 if (!tgt_prog->jited) { 23648 bpf_log(log, "Can attach to only JITed progs\n"); 23649 return -EINVAL; 23650 } 23651 if (prog_tracing) { 23652 if (aux->attach_tracing_prog) { 23653 /* 23654 * Target program is an fentry/fexit which is already attached 23655 * to another tracing program. More levels of nesting 23656 * attachment are not allowed. 23657 */ 23658 bpf_log(log, "Cannot nest tracing program attach more than once\n"); 23659 return -EINVAL; 23660 } 23661 } else if (tgt_prog->type == prog->type) { 23662 /* 23663 * To avoid potential call chain cycles, prevent attaching of a 23664 * program extension to another extension. It's ok to attach 23665 * fentry/fexit to extension program. 23666 */ 23667 bpf_log(log, "Cannot recursively attach\n"); 23668 return -EINVAL; 23669 } 23670 if (tgt_prog->type == BPF_PROG_TYPE_TRACING && 23671 prog_extension && 23672 (tgt_prog->expected_attach_type == BPF_TRACE_FENTRY || 23673 tgt_prog->expected_attach_type == BPF_TRACE_FEXIT)) { 23674 /* Program extensions can extend all program types 23675 * except fentry/fexit. The reason is the following. 23676 * The fentry/fexit programs are used for performance 23677 * analysis, stats and can be attached to any program 23678 * type. When extension program is replacing XDP function 23679 * it is necessary to allow performance analysis of all 23680 * functions. Both original XDP program and its program 23681 * extension. Hence attaching fentry/fexit to 23682 * BPF_PROG_TYPE_EXT is allowed. If extending of 23683 * fentry/fexit was allowed it would be possible to create 23684 * long call chain fentry->extension->fentry->extension 23685 * beyond reasonable stack size. Hence extending fentry 23686 * is not allowed. 23687 */ 23688 bpf_log(log, "Cannot extend fentry/fexit\n"); 23689 return -EINVAL; 23690 } 23691 } else { 23692 if (prog_extension) { 23693 bpf_log(log, "Cannot replace kernel functions\n"); 23694 return -EINVAL; 23695 } 23696 } 23697 23698 switch (prog->expected_attach_type) { 23699 case BPF_TRACE_RAW_TP: 23700 if (tgt_prog) { 23701 bpf_log(log, 23702 "Only FENTRY/FEXIT progs are attachable to another BPF prog\n"); 23703 return -EINVAL; 23704 } 23705 if (!btf_type_is_typedef(t)) { 23706 bpf_log(log, "attach_btf_id %u is not a typedef\n", 23707 btf_id); 23708 return -EINVAL; 23709 } 23710 if (strncmp(prefix, tname, sizeof(prefix) - 1)) { 23711 bpf_log(log, "attach_btf_id %u points to wrong type name %s\n", 23712 btf_id, tname); 23713 return -EINVAL; 23714 } 23715 tname += sizeof(prefix) - 1; 23716 23717 /* The func_proto of "btf_trace_##tname" is generated from typedef without argument 23718 * names. Thus using bpf_raw_event_map to get argument names. 23719 */ 23720 btp = bpf_get_raw_tracepoint(tname); 23721 if (!btp) 23722 return -EINVAL; 23723 fname = kallsyms_lookup((unsigned long)btp->bpf_func, NULL, NULL, NULL, 23724 trace_symbol); 23725 bpf_put_raw_tracepoint(btp); 23726 23727 if (fname) 23728 ret = btf_find_by_name_kind(btf, fname, BTF_KIND_FUNC); 23729 23730 if (!fname || ret < 0) { 23731 bpf_log(log, "Cannot find btf of tracepoint template, fall back to %s%s.\n", 23732 prefix, tname); 23733 t = btf_type_by_id(btf, t->type); 23734 if (!btf_type_is_ptr(t)) 23735 /* should never happen in valid vmlinux build */ 23736 return -EINVAL; 23737 } else { 23738 t = btf_type_by_id(btf, ret); 23739 if (!btf_type_is_func(t)) 23740 /* should never happen in valid vmlinux build */ 23741 return -EINVAL; 23742 } 23743 23744 t = btf_type_by_id(btf, t->type); 23745 if (!btf_type_is_func_proto(t)) 23746 /* should never happen in valid vmlinux build */ 23747 return -EINVAL; 23748 23749 break; 23750 case BPF_TRACE_ITER: 23751 if (!btf_type_is_func(t)) { 23752 bpf_log(log, "attach_btf_id %u is not a function\n", 23753 btf_id); 23754 return -EINVAL; 23755 } 23756 t = btf_type_by_id(btf, t->type); 23757 if (!btf_type_is_func_proto(t)) 23758 return -EINVAL; 23759 ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel); 23760 if (ret) 23761 return ret; 23762 break; 23763 default: 23764 if (!prog_extension) 23765 return -EINVAL; 23766 fallthrough; 23767 case BPF_MODIFY_RETURN: 23768 case BPF_LSM_MAC: 23769 case BPF_LSM_CGROUP: 23770 case BPF_TRACE_FENTRY: 23771 case BPF_TRACE_FEXIT: 23772 if (!btf_type_is_func(t)) { 23773 bpf_log(log, "attach_btf_id %u is not a function\n", 23774 btf_id); 23775 return -EINVAL; 23776 } 23777 if (prog_extension && 23778 btf_check_type_match(log, prog, btf, t)) 23779 return -EINVAL; 23780 t = btf_type_by_id(btf, t->type); 23781 if (!btf_type_is_func_proto(t)) 23782 return -EINVAL; 23783 23784 if ((prog->aux->saved_dst_prog_type || prog->aux->saved_dst_attach_type) && 23785 (!tgt_prog || prog->aux->saved_dst_prog_type != tgt_prog->type || 23786 prog->aux->saved_dst_attach_type != tgt_prog->expected_attach_type)) 23787 return -EINVAL; 23788 23789 if (tgt_prog && conservative) 23790 t = NULL; 23791 23792 ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel); 23793 if (ret < 0) 23794 return ret; 23795 23796 if (tgt_prog) { 23797 if (subprog == 0) 23798 addr = (long) tgt_prog->bpf_func; 23799 else 23800 addr = (long) tgt_prog->aux->func[subprog]->bpf_func; 23801 } else { 23802 if (btf_is_module(btf)) { 23803 mod = btf_try_get_module(btf); 23804 if (mod) 23805 addr = find_kallsyms_symbol_value(mod, tname); 23806 else 23807 addr = 0; 23808 } else { 23809 addr = kallsyms_lookup_name(tname); 23810 } 23811 if (!addr) { 23812 module_put(mod); 23813 bpf_log(log, 23814 "The address of function %s cannot be found\n", 23815 tname); 23816 return -ENOENT; 23817 } 23818 } 23819 23820 if (prog->sleepable) { 23821 ret = -EINVAL; 23822 switch (prog->type) { 23823 case BPF_PROG_TYPE_TRACING: 23824 23825 /* fentry/fexit/fmod_ret progs can be sleepable if they are 23826 * attached to ALLOW_ERROR_INJECTION and are not in denylist. 23827 */ 23828 if (!check_non_sleepable_error_inject(btf_id) && 23829 within_error_injection_list(addr)) 23830 ret = 0; 23831 /* fentry/fexit/fmod_ret progs can also be sleepable if they are 23832 * in the fmodret id set with the KF_SLEEPABLE flag. 23833 */ 23834 else { 23835 u32 *flags = btf_kfunc_is_modify_return(btf, btf_id, 23836 prog); 23837 23838 if (flags && (*flags & KF_SLEEPABLE)) 23839 ret = 0; 23840 } 23841 break; 23842 case BPF_PROG_TYPE_LSM: 23843 /* LSM progs check that they are attached to bpf_lsm_*() funcs. 23844 * Only some of them are sleepable. 23845 */ 23846 if (bpf_lsm_is_sleepable_hook(btf_id)) 23847 ret = 0; 23848 break; 23849 default: 23850 break; 23851 } 23852 if (ret) { 23853 module_put(mod); 23854 bpf_log(log, "%s is not sleepable\n", tname); 23855 return ret; 23856 } 23857 } else if (prog->expected_attach_type == BPF_MODIFY_RETURN) { 23858 if (tgt_prog) { 23859 module_put(mod); 23860 bpf_log(log, "can't modify return codes of BPF programs\n"); 23861 return -EINVAL; 23862 } 23863 ret = -EINVAL; 23864 if (btf_kfunc_is_modify_return(btf, btf_id, prog) || 23865 !check_attach_modify_return(addr, tname)) 23866 ret = 0; 23867 if (ret) { 23868 module_put(mod); 23869 bpf_log(log, "%s() is not modifiable\n", tname); 23870 return ret; 23871 } 23872 } 23873 23874 break; 23875 } 23876 tgt_info->tgt_addr = addr; 23877 tgt_info->tgt_name = tname; 23878 tgt_info->tgt_type = t; 23879 tgt_info->tgt_mod = mod; 23880 return 0; 23881 } 23882 23883 BTF_SET_START(btf_id_deny) 23884 BTF_ID_UNUSED 23885 #ifdef CONFIG_SMP 23886 BTF_ID(func, migrate_disable) 23887 BTF_ID(func, migrate_enable) 23888 #endif 23889 #if !defined CONFIG_PREEMPT_RCU && !defined CONFIG_TINY_RCU 23890 BTF_ID(func, rcu_read_unlock_strict) 23891 #endif 23892 #if defined(CONFIG_DEBUG_PREEMPT) || defined(CONFIG_TRACE_PREEMPT_TOGGLE) 23893 BTF_ID(func, preempt_count_add) 23894 BTF_ID(func, preempt_count_sub) 23895 #endif 23896 #ifdef CONFIG_PREEMPT_RCU 23897 BTF_ID(func, __rcu_read_lock) 23898 BTF_ID(func, __rcu_read_unlock) 23899 #endif 23900 BTF_SET_END(btf_id_deny) 23901 23902 /* fexit and fmod_ret can't be used to attach to __noreturn functions. 23903 * Currently, we must manually list all __noreturn functions here. Once a more 23904 * robust solution is implemented, this workaround can be removed. 23905 */ 23906 BTF_SET_START(noreturn_deny) 23907 #ifdef CONFIG_IA32_EMULATION 23908 BTF_ID(func, __ia32_sys_exit) 23909 BTF_ID(func, __ia32_sys_exit_group) 23910 #endif 23911 #ifdef CONFIG_KUNIT 23912 BTF_ID(func, __kunit_abort) 23913 BTF_ID(func, kunit_try_catch_throw) 23914 #endif 23915 #ifdef CONFIG_MODULES 23916 BTF_ID(func, __module_put_and_kthread_exit) 23917 #endif 23918 #ifdef CONFIG_X86_64 23919 BTF_ID(func, __x64_sys_exit) 23920 BTF_ID(func, __x64_sys_exit_group) 23921 #endif 23922 BTF_ID(func, do_exit) 23923 BTF_ID(func, do_group_exit) 23924 BTF_ID(func, kthread_complete_and_exit) 23925 BTF_ID(func, kthread_exit) 23926 BTF_ID(func, make_task_dead) 23927 BTF_SET_END(noreturn_deny) 23928 23929 static bool can_be_sleepable(struct bpf_prog *prog) 23930 { 23931 if (prog->type == BPF_PROG_TYPE_TRACING) { 23932 switch (prog->expected_attach_type) { 23933 case BPF_TRACE_FENTRY: 23934 case BPF_TRACE_FEXIT: 23935 case BPF_MODIFY_RETURN: 23936 case BPF_TRACE_ITER: 23937 return true; 23938 default: 23939 return false; 23940 } 23941 } 23942 return prog->type == BPF_PROG_TYPE_LSM || 23943 prog->type == BPF_PROG_TYPE_KPROBE /* only for uprobes */ || 23944 prog->type == BPF_PROG_TYPE_STRUCT_OPS; 23945 } 23946 23947 static int check_attach_btf_id(struct bpf_verifier_env *env) 23948 { 23949 struct bpf_prog *prog = env->prog; 23950 struct bpf_prog *tgt_prog = prog->aux->dst_prog; 23951 struct bpf_attach_target_info tgt_info = {}; 23952 u32 btf_id = prog->aux->attach_btf_id; 23953 struct bpf_trampoline *tr; 23954 int ret; 23955 u64 key; 23956 23957 if (prog->type == BPF_PROG_TYPE_SYSCALL) { 23958 if (prog->sleepable) 23959 /* attach_btf_id checked to be zero already */ 23960 return 0; 23961 verbose(env, "Syscall programs can only be sleepable\n"); 23962 return -EINVAL; 23963 } 23964 23965 if (prog->sleepable && !can_be_sleepable(prog)) { 23966 verbose(env, "Only fentry/fexit/fmod_ret, lsm, iter, uprobe, and struct_ops programs can be sleepable\n"); 23967 return -EINVAL; 23968 } 23969 23970 if (prog->type == BPF_PROG_TYPE_STRUCT_OPS) 23971 return check_struct_ops_btf_id(env); 23972 23973 if (prog->type != BPF_PROG_TYPE_TRACING && 23974 prog->type != BPF_PROG_TYPE_LSM && 23975 prog->type != BPF_PROG_TYPE_EXT) 23976 return 0; 23977 23978 ret = bpf_check_attach_target(&env->log, prog, tgt_prog, btf_id, &tgt_info); 23979 if (ret) 23980 return ret; 23981 23982 if (tgt_prog && prog->type == BPF_PROG_TYPE_EXT) { 23983 /* to make freplace equivalent to their targets, they need to 23984 * inherit env->ops and expected_attach_type for the rest of the 23985 * verification 23986 */ 23987 env->ops = bpf_verifier_ops[tgt_prog->type]; 23988 prog->expected_attach_type = tgt_prog->expected_attach_type; 23989 } 23990 23991 /* store info about the attachment target that will be used later */ 23992 prog->aux->attach_func_proto = tgt_info.tgt_type; 23993 prog->aux->attach_func_name = tgt_info.tgt_name; 23994 prog->aux->mod = tgt_info.tgt_mod; 23995 23996 if (tgt_prog) { 23997 prog->aux->saved_dst_prog_type = tgt_prog->type; 23998 prog->aux->saved_dst_attach_type = tgt_prog->expected_attach_type; 23999 } 24000 24001 if (prog->expected_attach_type == BPF_TRACE_RAW_TP) { 24002 prog->aux->attach_btf_trace = true; 24003 return 0; 24004 } else if (prog->expected_attach_type == BPF_TRACE_ITER) { 24005 return bpf_iter_prog_supported(prog); 24006 } 24007 24008 if (prog->type == BPF_PROG_TYPE_LSM) { 24009 ret = bpf_lsm_verify_prog(&env->log, prog); 24010 if (ret < 0) 24011 return ret; 24012 } else if (prog->type == BPF_PROG_TYPE_TRACING && 24013 btf_id_set_contains(&btf_id_deny, btf_id)) { 24014 verbose(env, "Attaching tracing programs to function '%s' is rejected.\n", 24015 tgt_info.tgt_name); 24016 return -EINVAL; 24017 } else if ((prog->expected_attach_type == BPF_TRACE_FEXIT || 24018 prog->expected_attach_type == BPF_MODIFY_RETURN) && 24019 btf_id_set_contains(&noreturn_deny, btf_id)) { 24020 verbose(env, "Attaching fexit/fmod_ret to __noreturn function '%s' is rejected.\n", 24021 tgt_info.tgt_name); 24022 return -EINVAL; 24023 } 24024 24025 key = bpf_trampoline_compute_key(tgt_prog, prog->aux->attach_btf, btf_id); 24026 tr = bpf_trampoline_get(key, &tgt_info); 24027 if (!tr) 24028 return -ENOMEM; 24029 24030 if (tgt_prog && tgt_prog->aux->tail_call_reachable) 24031 tr->flags = BPF_TRAMP_F_TAIL_CALL_CTX; 24032 24033 prog->aux->dst_trampoline = tr; 24034 return 0; 24035 } 24036 24037 struct btf *bpf_get_btf_vmlinux(void) 24038 { 24039 if (!btf_vmlinux && IS_ENABLED(CONFIG_DEBUG_INFO_BTF)) { 24040 mutex_lock(&bpf_verifier_lock); 24041 if (!btf_vmlinux) 24042 btf_vmlinux = btf_parse_vmlinux(); 24043 mutex_unlock(&bpf_verifier_lock); 24044 } 24045 return btf_vmlinux; 24046 } 24047 24048 /* 24049 * The add_fd_from_fd_array() is executed only if fd_array_cnt is non-zero. In 24050 * this case expect that every file descriptor in the array is either a map or 24051 * a BTF. Everything else is considered to be trash. 24052 */ 24053 static int add_fd_from_fd_array(struct bpf_verifier_env *env, int fd) 24054 { 24055 struct bpf_map *map; 24056 struct btf *btf; 24057 CLASS(fd, f)(fd); 24058 int err; 24059 24060 map = __bpf_map_get(f); 24061 if (!IS_ERR(map)) { 24062 err = __add_used_map(env, map); 24063 if (err < 0) 24064 return err; 24065 return 0; 24066 } 24067 24068 btf = __btf_get_by_fd(f); 24069 if (!IS_ERR(btf)) { 24070 err = __add_used_btf(env, btf); 24071 if (err < 0) 24072 return err; 24073 return 0; 24074 } 24075 24076 verbose(env, "fd %d is not pointing to valid bpf_map or btf\n", fd); 24077 return PTR_ERR(map); 24078 } 24079 24080 static int process_fd_array(struct bpf_verifier_env *env, union bpf_attr *attr, bpfptr_t uattr) 24081 { 24082 size_t size = sizeof(int); 24083 int ret; 24084 int fd; 24085 u32 i; 24086 24087 env->fd_array = make_bpfptr(attr->fd_array, uattr.is_kernel); 24088 24089 /* 24090 * The only difference between old (no fd_array_cnt is given) and new 24091 * APIs is that in the latter case the fd_array is expected to be 24092 * continuous and is scanned for map fds right away 24093 */ 24094 if (!attr->fd_array_cnt) 24095 return 0; 24096 24097 /* Check for integer overflow */ 24098 if (attr->fd_array_cnt >= (U32_MAX / size)) { 24099 verbose(env, "fd_array_cnt is too big (%u)\n", attr->fd_array_cnt); 24100 return -EINVAL; 24101 } 24102 24103 for (i = 0; i < attr->fd_array_cnt; i++) { 24104 if (copy_from_bpfptr_offset(&fd, env->fd_array, i * size, size)) 24105 return -EFAULT; 24106 24107 ret = add_fd_from_fd_array(env, fd); 24108 if (ret) 24109 return ret; 24110 } 24111 24112 return 0; 24113 } 24114 24115 static bool can_fallthrough(struct bpf_insn *insn) 24116 { 24117 u8 class = BPF_CLASS(insn->code); 24118 u8 opcode = BPF_OP(insn->code); 24119 24120 if (class != BPF_JMP && class != BPF_JMP32) 24121 return true; 24122 24123 if (opcode == BPF_EXIT || opcode == BPF_JA) 24124 return false; 24125 24126 return true; 24127 } 24128 24129 static bool can_jump(struct bpf_insn *insn) 24130 { 24131 u8 class = BPF_CLASS(insn->code); 24132 u8 opcode = BPF_OP(insn->code); 24133 24134 if (class != BPF_JMP && class != BPF_JMP32) 24135 return false; 24136 24137 switch (opcode) { 24138 case BPF_JA: 24139 case BPF_JEQ: 24140 case BPF_JNE: 24141 case BPF_JLT: 24142 case BPF_JLE: 24143 case BPF_JGT: 24144 case BPF_JGE: 24145 case BPF_JSGT: 24146 case BPF_JSGE: 24147 case BPF_JSLT: 24148 case BPF_JSLE: 24149 case BPF_JCOND: 24150 case BPF_JSET: 24151 return true; 24152 } 24153 24154 return false; 24155 } 24156 24157 static int insn_successors(struct bpf_prog *prog, u32 idx, u32 succ[2]) 24158 { 24159 struct bpf_insn *insn = &prog->insnsi[idx]; 24160 int i = 0, insn_sz; 24161 u32 dst; 24162 24163 insn_sz = bpf_is_ldimm64(insn) ? 2 : 1; 24164 if (can_fallthrough(insn) && idx + 1 < prog->len) 24165 succ[i++] = idx + insn_sz; 24166 24167 if (can_jump(insn)) { 24168 dst = idx + jmp_offset(insn) + 1; 24169 if (i == 0 || succ[0] != dst) 24170 succ[i++] = dst; 24171 } 24172 24173 return i; 24174 } 24175 24176 /* Each field is a register bitmask */ 24177 struct insn_live_regs { 24178 u16 use; /* registers read by instruction */ 24179 u16 def; /* registers written by instruction */ 24180 u16 in; /* registers that may be alive before instruction */ 24181 u16 out; /* registers that may be alive after instruction */ 24182 }; 24183 24184 /* Bitmask with 1s for all caller saved registers */ 24185 #define ALL_CALLER_SAVED_REGS ((1u << CALLER_SAVED_REGS) - 1) 24186 24187 /* Compute info->{use,def} fields for the instruction */ 24188 static void compute_insn_live_regs(struct bpf_verifier_env *env, 24189 struct bpf_insn *insn, 24190 struct insn_live_regs *info) 24191 { 24192 struct call_summary cs; 24193 u8 class = BPF_CLASS(insn->code); 24194 u8 code = BPF_OP(insn->code); 24195 u8 mode = BPF_MODE(insn->code); 24196 u16 src = BIT(insn->src_reg); 24197 u16 dst = BIT(insn->dst_reg); 24198 u16 r0 = BIT(0); 24199 u16 def = 0; 24200 u16 use = 0xffff; 24201 24202 switch (class) { 24203 case BPF_LD: 24204 switch (mode) { 24205 case BPF_IMM: 24206 if (BPF_SIZE(insn->code) == BPF_DW) { 24207 def = dst; 24208 use = 0; 24209 } 24210 break; 24211 case BPF_LD | BPF_ABS: 24212 case BPF_LD | BPF_IND: 24213 /* stick with defaults */ 24214 break; 24215 } 24216 break; 24217 case BPF_LDX: 24218 switch (mode) { 24219 case BPF_MEM: 24220 case BPF_MEMSX: 24221 def = dst; 24222 use = src; 24223 break; 24224 } 24225 break; 24226 case BPF_ST: 24227 switch (mode) { 24228 case BPF_MEM: 24229 def = 0; 24230 use = dst; 24231 break; 24232 } 24233 break; 24234 case BPF_STX: 24235 switch (mode) { 24236 case BPF_MEM: 24237 def = 0; 24238 use = dst | src; 24239 break; 24240 case BPF_ATOMIC: 24241 switch (insn->imm) { 24242 case BPF_CMPXCHG: 24243 use = r0 | dst | src; 24244 def = r0; 24245 break; 24246 case BPF_LOAD_ACQ: 24247 def = dst; 24248 use = src; 24249 break; 24250 case BPF_STORE_REL: 24251 def = 0; 24252 use = dst | src; 24253 break; 24254 default: 24255 use = dst | src; 24256 if (insn->imm & BPF_FETCH) 24257 def = src; 24258 else 24259 def = 0; 24260 } 24261 break; 24262 } 24263 break; 24264 case BPF_ALU: 24265 case BPF_ALU64: 24266 switch (code) { 24267 case BPF_END: 24268 use = dst; 24269 def = dst; 24270 break; 24271 case BPF_MOV: 24272 def = dst; 24273 if (BPF_SRC(insn->code) == BPF_K) 24274 use = 0; 24275 else 24276 use = src; 24277 break; 24278 default: 24279 def = dst; 24280 if (BPF_SRC(insn->code) == BPF_K) 24281 use = dst; 24282 else 24283 use = dst | src; 24284 } 24285 break; 24286 case BPF_JMP: 24287 case BPF_JMP32: 24288 switch (code) { 24289 case BPF_JA: 24290 case BPF_JCOND: 24291 def = 0; 24292 use = 0; 24293 break; 24294 case BPF_EXIT: 24295 def = 0; 24296 use = r0; 24297 break; 24298 case BPF_CALL: 24299 def = ALL_CALLER_SAVED_REGS; 24300 use = def & ~BIT(BPF_REG_0); 24301 if (get_call_summary(env, insn, &cs)) 24302 use = GENMASK(cs.num_params, 1); 24303 break; 24304 default: 24305 def = 0; 24306 if (BPF_SRC(insn->code) == BPF_K) 24307 use = dst; 24308 else 24309 use = dst | src; 24310 } 24311 break; 24312 } 24313 24314 info->def = def; 24315 info->use = use; 24316 } 24317 24318 /* Compute may-live registers after each instruction in the program. 24319 * The register is live after the instruction I if it is read by some 24320 * instruction S following I during program execution and is not 24321 * overwritten between I and S. 24322 * 24323 * Store result in env->insn_aux_data[i].live_regs. 24324 */ 24325 static int compute_live_registers(struct bpf_verifier_env *env) 24326 { 24327 struct bpf_insn_aux_data *insn_aux = env->insn_aux_data; 24328 struct bpf_insn *insns = env->prog->insnsi; 24329 struct insn_live_regs *state; 24330 int insn_cnt = env->prog->len; 24331 int err = 0, i, j; 24332 bool changed; 24333 24334 /* Use the following algorithm: 24335 * - define the following: 24336 * - I.use : a set of all registers read by instruction I; 24337 * - I.def : a set of all registers written by instruction I; 24338 * - I.in : a set of all registers that may be alive before I execution; 24339 * - I.out : a set of all registers that may be alive after I execution; 24340 * - insn_successors(I): a set of instructions S that might immediately 24341 * follow I for some program execution; 24342 * - associate separate empty sets 'I.in' and 'I.out' with each instruction; 24343 * - visit each instruction in a postorder and update 24344 * state[i].in, state[i].out as follows: 24345 * 24346 * state[i].out = U [state[s].in for S in insn_successors(i)] 24347 * state[i].in = (state[i].out / state[i].def) U state[i].use 24348 * 24349 * (where U stands for set union, / stands for set difference) 24350 * - repeat the computation while {in,out} fields changes for 24351 * any instruction. 24352 */ 24353 state = kvcalloc(insn_cnt, sizeof(*state), GFP_KERNEL_ACCOUNT); 24354 if (!state) { 24355 err = -ENOMEM; 24356 goto out; 24357 } 24358 24359 for (i = 0; i < insn_cnt; ++i) 24360 compute_insn_live_regs(env, &insns[i], &state[i]); 24361 24362 changed = true; 24363 while (changed) { 24364 changed = false; 24365 for (i = 0; i < env->cfg.cur_postorder; ++i) { 24366 int insn_idx = env->cfg.insn_postorder[i]; 24367 struct insn_live_regs *live = &state[insn_idx]; 24368 int succ_num; 24369 u32 succ[2]; 24370 u16 new_out = 0; 24371 u16 new_in = 0; 24372 24373 succ_num = insn_successors(env->prog, insn_idx, succ); 24374 for (int s = 0; s < succ_num; ++s) 24375 new_out |= state[succ[s]].in; 24376 new_in = (new_out & ~live->def) | live->use; 24377 if (new_out != live->out || new_in != live->in) { 24378 live->in = new_in; 24379 live->out = new_out; 24380 changed = true; 24381 } 24382 } 24383 } 24384 24385 for (i = 0; i < insn_cnt; ++i) 24386 insn_aux[i].live_regs_before = state[i].in; 24387 24388 if (env->log.level & BPF_LOG_LEVEL2) { 24389 verbose(env, "Live regs before insn:\n"); 24390 for (i = 0; i < insn_cnt; ++i) { 24391 if (env->insn_aux_data[i].scc) 24392 verbose(env, "%3d ", env->insn_aux_data[i].scc); 24393 else 24394 verbose(env, " "); 24395 verbose(env, "%3d: ", i); 24396 for (j = BPF_REG_0; j < BPF_REG_10; ++j) 24397 if (insn_aux[i].live_regs_before & BIT(j)) 24398 verbose(env, "%d", j); 24399 else 24400 verbose(env, "."); 24401 verbose(env, " "); 24402 verbose_insn(env, &insns[i]); 24403 if (bpf_is_ldimm64(&insns[i])) 24404 i++; 24405 } 24406 } 24407 24408 out: 24409 kvfree(state); 24410 kvfree(env->cfg.insn_postorder); 24411 env->cfg.insn_postorder = NULL; 24412 env->cfg.cur_postorder = 0; 24413 return err; 24414 } 24415 24416 /* 24417 * Compute strongly connected components (SCCs) on the CFG. 24418 * Assign an SCC number to each instruction, recorded in env->insn_aux[*].scc. 24419 * If instruction is a sole member of its SCC and there are no self edges, 24420 * assign it SCC number of zero. 24421 * Uses a non-recursive adaptation of Tarjan's algorithm for SCC computation. 24422 */ 24423 static int compute_scc(struct bpf_verifier_env *env) 24424 { 24425 const u32 NOT_ON_STACK = U32_MAX; 24426 24427 struct bpf_insn_aux_data *aux = env->insn_aux_data; 24428 const u32 insn_cnt = env->prog->len; 24429 int stack_sz, dfs_sz, err = 0; 24430 u32 *stack, *pre, *low, *dfs; 24431 u32 succ_cnt, i, j, t, w; 24432 u32 next_preorder_num; 24433 u32 next_scc_id; 24434 bool assign_scc; 24435 u32 succ[2]; 24436 24437 next_preorder_num = 1; 24438 next_scc_id = 1; 24439 /* 24440 * - 'stack' accumulates vertices in DFS order, see invariant comment below; 24441 * - 'pre[t] == p' => preorder number of vertex 't' is 'p'; 24442 * - 'low[t] == n' => smallest preorder number of the vertex reachable from 't' is 'n'; 24443 * - 'dfs' DFS traversal stack, used to emulate explicit recursion. 24444 */ 24445 stack = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL_ACCOUNT); 24446 pre = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL_ACCOUNT); 24447 low = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL_ACCOUNT); 24448 dfs = kvcalloc(insn_cnt, sizeof(*dfs), GFP_KERNEL_ACCOUNT); 24449 if (!stack || !pre || !low || !dfs) { 24450 err = -ENOMEM; 24451 goto exit; 24452 } 24453 /* 24454 * References: 24455 * [1] R. Tarjan "Depth-First Search and Linear Graph Algorithms" 24456 * [2] D. J. Pearce "A Space-Efficient Algorithm for Finding Strongly Connected Components" 24457 * 24458 * The algorithm maintains the following invariant: 24459 * - suppose there is a path 'u' ~> 'v', such that 'pre[v] < pre[u]'; 24460 * - then, vertex 'u' remains on stack while vertex 'v' is on stack. 24461 * 24462 * Consequently: 24463 * - If 'low[v] < pre[v]', there is a path from 'v' to some vertex 'u', 24464 * such that 'pre[u] == low[v]'; vertex 'u' is currently on the stack, 24465 * and thus there is an SCC (loop) containing both 'u' and 'v'. 24466 * - If 'low[v] == pre[v]', loops containing 'v' have been explored, 24467 * and 'v' can be considered the root of some SCC. 24468 * 24469 * Here is a pseudo-code for an explicitly recursive version of the algorithm: 24470 * 24471 * NOT_ON_STACK = insn_cnt + 1 24472 * pre = [0] * insn_cnt 24473 * low = [0] * insn_cnt 24474 * scc = [0] * insn_cnt 24475 * stack = [] 24476 * 24477 * next_preorder_num = 1 24478 * next_scc_id = 1 24479 * 24480 * def recur(w): 24481 * nonlocal next_preorder_num 24482 * nonlocal next_scc_id 24483 * 24484 * pre[w] = next_preorder_num 24485 * low[w] = next_preorder_num 24486 * next_preorder_num += 1 24487 * stack.append(w) 24488 * for s in successors(w): 24489 * # Note: for classic algorithm the block below should look as: 24490 * # 24491 * # if pre[s] == 0: 24492 * # recur(s) 24493 * # low[w] = min(low[w], low[s]) 24494 * # elif low[s] != NOT_ON_STACK: 24495 * # low[w] = min(low[w], pre[s]) 24496 * # 24497 * # But replacing both 'min' instructions with 'low[w] = min(low[w], low[s])' 24498 * # does not break the invariant and makes itartive version of the algorithm 24499 * # simpler. See 'Algorithm #3' from [2]. 24500 * 24501 * # 's' not yet visited 24502 * if pre[s] == 0: 24503 * recur(s) 24504 * # if 's' is on stack, pick lowest reachable preorder number from it; 24505 * # if 's' is not on stack 'low[s] == NOT_ON_STACK > low[w]', 24506 * # so 'min' would be a noop. 24507 * low[w] = min(low[w], low[s]) 24508 * 24509 * if low[w] == pre[w]: 24510 * # 'w' is the root of an SCC, pop all vertices 24511 * # below 'w' on stack and assign same SCC to them. 24512 * while True: 24513 * t = stack.pop() 24514 * low[t] = NOT_ON_STACK 24515 * scc[t] = next_scc_id 24516 * if t == w: 24517 * break 24518 * next_scc_id += 1 24519 * 24520 * for i in range(0, insn_cnt): 24521 * if pre[i] == 0: 24522 * recur(i) 24523 * 24524 * Below implementation replaces explicit recursion with array 'dfs'. 24525 */ 24526 for (i = 0; i < insn_cnt; i++) { 24527 if (pre[i]) 24528 continue; 24529 stack_sz = 0; 24530 dfs_sz = 1; 24531 dfs[0] = i; 24532 dfs_continue: 24533 while (dfs_sz) { 24534 w = dfs[dfs_sz - 1]; 24535 if (pre[w] == 0) { 24536 low[w] = next_preorder_num; 24537 pre[w] = next_preorder_num; 24538 next_preorder_num++; 24539 stack[stack_sz++] = w; 24540 } 24541 /* Visit 'w' successors */ 24542 succ_cnt = insn_successors(env->prog, w, succ); 24543 for (j = 0; j < succ_cnt; ++j) { 24544 if (pre[succ[j]]) { 24545 low[w] = min(low[w], low[succ[j]]); 24546 } else { 24547 dfs[dfs_sz++] = succ[j]; 24548 goto dfs_continue; 24549 } 24550 } 24551 /* 24552 * Preserve the invariant: if some vertex above in the stack 24553 * is reachable from 'w', keep 'w' on the stack. 24554 */ 24555 if (low[w] < pre[w]) { 24556 dfs_sz--; 24557 goto dfs_continue; 24558 } 24559 /* 24560 * Assign SCC number only if component has two or more elements, 24561 * or if component has a self reference. 24562 */ 24563 assign_scc = stack[stack_sz - 1] != w; 24564 for (j = 0; j < succ_cnt; ++j) { 24565 if (succ[j] == w) { 24566 assign_scc = true; 24567 break; 24568 } 24569 } 24570 /* Pop component elements from stack */ 24571 do { 24572 t = stack[--stack_sz]; 24573 low[t] = NOT_ON_STACK; 24574 if (assign_scc) 24575 aux[t].scc = next_scc_id; 24576 } while (t != w); 24577 if (assign_scc) 24578 next_scc_id++; 24579 dfs_sz--; 24580 } 24581 } 24582 env->scc_info = kvcalloc(next_scc_id, sizeof(*env->scc_info), GFP_KERNEL_ACCOUNT); 24583 if (!env->scc_info) { 24584 err = -ENOMEM; 24585 goto exit; 24586 } 24587 env->scc_cnt = next_scc_id; 24588 exit: 24589 kvfree(stack); 24590 kvfree(pre); 24591 kvfree(low); 24592 kvfree(dfs); 24593 return err; 24594 } 24595 24596 int bpf_check(struct bpf_prog **prog, union bpf_attr *attr, bpfptr_t uattr, __u32 uattr_size) 24597 { 24598 u64 start_time = ktime_get_ns(); 24599 struct bpf_verifier_env *env; 24600 int i, len, ret = -EINVAL, err; 24601 u32 log_true_size; 24602 bool is_priv; 24603 24604 BTF_TYPE_EMIT(enum bpf_features); 24605 24606 /* no program is valid */ 24607 if (ARRAY_SIZE(bpf_verifier_ops) == 0) 24608 return -EINVAL; 24609 24610 /* 'struct bpf_verifier_env' can be global, but since it's not small, 24611 * allocate/free it every time bpf_check() is called 24612 */ 24613 env = kvzalloc(sizeof(struct bpf_verifier_env), GFP_KERNEL_ACCOUNT); 24614 if (!env) 24615 return -ENOMEM; 24616 24617 env->bt.env = env; 24618 24619 len = (*prog)->len; 24620 env->insn_aux_data = 24621 vzalloc(array_size(sizeof(struct bpf_insn_aux_data), len)); 24622 ret = -ENOMEM; 24623 if (!env->insn_aux_data) 24624 goto err_free_env; 24625 for (i = 0; i < len; i++) 24626 env->insn_aux_data[i].orig_idx = i; 24627 env->prog = *prog; 24628 env->ops = bpf_verifier_ops[env->prog->type]; 24629 24630 env->allow_ptr_leaks = bpf_allow_ptr_leaks(env->prog->aux->token); 24631 env->allow_uninit_stack = bpf_allow_uninit_stack(env->prog->aux->token); 24632 env->bypass_spec_v1 = bpf_bypass_spec_v1(env->prog->aux->token); 24633 env->bypass_spec_v4 = bpf_bypass_spec_v4(env->prog->aux->token); 24634 env->bpf_capable = is_priv = bpf_token_capable(env->prog->aux->token, CAP_BPF); 24635 24636 bpf_get_btf_vmlinux(); 24637 24638 /* grab the mutex to protect few globals used by verifier */ 24639 if (!is_priv) 24640 mutex_lock(&bpf_verifier_lock); 24641 24642 /* user could have requested verbose verifier output 24643 * and supplied buffer to store the verification trace 24644 */ 24645 ret = bpf_vlog_init(&env->log, attr->log_level, 24646 (char __user *) (unsigned long) attr->log_buf, 24647 attr->log_size); 24648 if (ret) 24649 goto err_unlock; 24650 24651 ret = process_fd_array(env, attr, uattr); 24652 if (ret) 24653 goto skip_full_check; 24654 24655 mark_verifier_state_clean(env); 24656 24657 if (IS_ERR(btf_vmlinux)) { 24658 /* Either gcc or pahole or kernel are broken. */ 24659 verbose(env, "in-kernel BTF is malformed\n"); 24660 ret = PTR_ERR(btf_vmlinux); 24661 goto skip_full_check; 24662 } 24663 24664 env->strict_alignment = !!(attr->prog_flags & BPF_F_STRICT_ALIGNMENT); 24665 if (!IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS)) 24666 env->strict_alignment = true; 24667 if (attr->prog_flags & BPF_F_ANY_ALIGNMENT) 24668 env->strict_alignment = false; 24669 24670 if (is_priv) 24671 env->test_state_freq = attr->prog_flags & BPF_F_TEST_STATE_FREQ; 24672 env->test_reg_invariants = attr->prog_flags & BPF_F_TEST_REG_INVARIANTS; 24673 24674 env->explored_states = kvcalloc(state_htab_size(env), 24675 sizeof(struct list_head), 24676 GFP_KERNEL_ACCOUNT); 24677 ret = -ENOMEM; 24678 if (!env->explored_states) 24679 goto skip_full_check; 24680 24681 for (i = 0; i < state_htab_size(env); i++) 24682 INIT_LIST_HEAD(&env->explored_states[i]); 24683 INIT_LIST_HEAD(&env->free_list); 24684 24685 ret = check_btf_info_early(env, attr, uattr); 24686 if (ret < 0) 24687 goto skip_full_check; 24688 24689 ret = add_subprog_and_kfunc(env); 24690 if (ret < 0) 24691 goto skip_full_check; 24692 24693 ret = check_subprogs(env); 24694 if (ret < 0) 24695 goto skip_full_check; 24696 24697 ret = check_btf_info(env, attr, uattr); 24698 if (ret < 0) 24699 goto skip_full_check; 24700 24701 ret = resolve_pseudo_ldimm64(env); 24702 if (ret < 0) 24703 goto skip_full_check; 24704 24705 if (bpf_prog_is_offloaded(env->prog->aux)) { 24706 ret = bpf_prog_offload_verifier_prep(env->prog); 24707 if (ret) 24708 goto skip_full_check; 24709 } 24710 24711 ret = check_cfg(env); 24712 if (ret < 0) 24713 goto skip_full_check; 24714 24715 ret = check_attach_btf_id(env); 24716 if (ret) 24717 goto skip_full_check; 24718 24719 ret = compute_scc(env); 24720 if (ret < 0) 24721 goto skip_full_check; 24722 24723 ret = compute_live_registers(env); 24724 if (ret < 0) 24725 goto skip_full_check; 24726 24727 ret = mark_fastcall_patterns(env); 24728 if (ret < 0) 24729 goto skip_full_check; 24730 24731 ret = do_check_main(env); 24732 ret = ret ?: do_check_subprogs(env); 24733 24734 if (ret == 0 && bpf_prog_is_offloaded(env->prog->aux)) 24735 ret = bpf_prog_offload_finalize(env); 24736 24737 skip_full_check: 24738 kvfree(env->explored_states); 24739 24740 /* might decrease stack depth, keep it before passes that 24741 * allocate additional slots. 24742 */ 24743 if (ret == 0) 24744 ret = remove_fastcall_spills_fills(env); 24745 24746 if (ret == 0) 24747 ret = check_max_stack_depth(env); 24748 24749 /* instruction rewrites happen after this point */ 24750 if (ret == 0) 24751 ret = optimize_bpf_loop(env); 24752 24753 if (is_priv) { 24754 if (ret == 0) 24755 opt_hard_wire_dead_code_branches(env); 24756 if (ret == 0) 24757 ret = opt_remove_dead_code(env); 24758 if (ret == 0) 24759 ret = opt_remove_nops(env); 24760 } else { 24761 if (ret == 0) 24762 sanitize_dead_code(env); 24763 } 24764 24765 if (ret == 0) 24766 /* program is valid, convert *(u32*)(ctx + off) accesses */ 24767 ret = convert_ctx_accesses(env); 24768 24769 if (ret == 0) 24770 ret = do_misc_fixups(env); 24771 24772 /* do 32-bit optimization after insn patching has done so those patched 24773 * insns could be handled correctly. 24774 */ 24775 if (ret == 0 && !bpf_prog_is_offloaded(env->prog->aux)) { 24776 ret = opt_subreg_zext_lo32_rnd_hi32(env, attr); 24777 env->prog->aux->verifier_zext = bpf_jit_needs_zext() ? !ret 24778 : false; 24779 } 24780 24781 if (ret == 0) 24782 ret = fixup_call_args(env); 24783 24784 env->verification_time = ktime_get_ns() - start_time; 24785 print_verification_stats(env); 24786 env->prog->aux->verified_insns = env->insn_processed; 24787 24788 /* preserve original error even if log finalization is successful */ 24789 err = bpf_vlog_finalize(&env->log, &log_true_size); 24790 if (err) 24791 ret = err; 24792 24793 if (uattr_size >= offsetofend(union bpf_attr, log_true_size) && 24794 copy_to_bpfptr_offset(uattr, offsetof(union bpf_attr, log_true_size), 24795 &log_true_size, sizeof(log_true_size))) { 24796 ret = -EFAULT; 24797 goto err_release_maps; 24798 } 24799 24800 if (ret) 24801 goto err_release_maps; 24802 24803 if (env->used_map_cnt) { 24804 /* if program passed verifier, update used_maps in bpf_prog_info */ 24805 env->prog->aux->used_maps = kmalloc_array(env->used_map_cnt, 24806 sizeof(env->used_maps[0]), 24807 GFP_KERNEL_ACCOUNT); 24808 24809 if (!env->prog->aux->used_maps) { 24810 ret = -ENOMEM; 24811 goto err_release_maps; 24812 } 24813 24814 memcpy(env->prog->aux->used_maps, env->used_maps, 24815 sizeof(env->used_maps[0]) * env->used_map_cnt); 24816 env->prog->aux->used_map_cnt = env->used_map_cnt; 24817 } 24818 if (env->used_btf_cnt) { 24819 /* if program passed verifier, update used_btfs in bpf_prog_aux */ 24820 env->prog->aux->used_btfs = kmalloc_array(env->used_btf_cnt, 24821 sizeof(env->used_btfs[0]), 24822 GFP_KERNEL_ACCOUNT); 24823 if (!env->prog->aux->used_btfs) { 24824 ret = -ENOMEM; 24825 goto err_release_maps; 24826 } 24827 24828 memcpy(env->prog->aux->used_btfs, env->used_btfs, 24829 sizeof(env->used_btfs[0]) * env->used_btf_cnt); 24830 env->prog->aux->used_btf_cnt = env->used_btf_cnt; 24831 } 24832 if (env->used_map_cnt || env->used_btf_cnt) { 24833 /* program is valid. Convert pseudo bpf_ld_imm64 into generic 24834 * bpf_ld_imm64 instructions 24835 */ 24836 convert_pseudo_ld_imm64(env); 24837 } 24838 24839 adjust_btf_func(env); 24840 24841 err_release_maps: 24842 if (!env->prog->aux->used_maps) 24843 /* if we didn't copy map pointers into bpf_prog_info, release 24844 * them now. Otherwise free_used_maps() will release them. 24845 */ 24846 release_maps(env); 24847 if (!env->prog->aux->used_btfs) 24848 release_btfs(env); 24849 24850 /* extension progs temporarily inherit the attach_type of their targets 24851 for verification purposes, so set it back to zero before returning 24852 */ 24853 if (env->prog->type == BPF_PROG_TYPE_EXT) 24854 env->prog->expected_attach_type = 0; 24855 24856 *prog = env->prog; 24857 24858 module_put(env->attach_btf_mod); 24859 err_unlock: 24860 if (!is_priv) 24861 mutex_unlock(&bpf_verifier_lock); 24862 vfree(env->insn_aux_data); 24863 err_free_env: 24864 kvfree(env->cfg.insn_postorder); 24865 kvfree(env->scc_info); 24866 kvfree(env); 24867 return ret; 24868 } 24869