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_dynptr_slice, 12243 KF_bpf_dynptr_slice_rdwr, 12244 KF_bpf_dynptr_clone, 12245 KF_bpf_percpu_obj_new_impl, 12246 KF_bpf_percpu_obj_drop_impl, 12247 KF_bpf_throw, 12248 KF_bpf_wq_set_callback_impl, 12249 KF_bpf_preempt_disable, 12250 KF_bpf_preempt_enable, 12251 KF_bpf_iter_css_task_new, 12252 KF_bpf_session_cookie, 12253 KF_bpf_get_kmem_cache, 12254 KF_bpf_local_irq_save, 12255 KF_bpf_local_irq_restore, 12256 KF_bpf_iter_num_new, 12257 KF_bpf_iter_num_next, 12258 KF_bpf_iter_num_destroy, 12259 KF_bpf_set_dentry_xattr, 12260 KF_bpf_remove_dentry_xattr, 12261 KF_bpf_res_spin_lock, 12262 KF_bpf_res_spin_unlock, 12263 KF_bpf_res_spin_lock_irqsave, 12264 KF_bpf_res_spin_unlock_irqrestore, 12265 KF___bpf_trap, 12266 }; 12267 12268 BTF_ID_LIST(special_kfunc_list) 12269 BTF_ID(func, bpf_obj_new_impl) 12270 BTF_ID(func, bpf_obj_drop_impl) 12271 BTF_ID(func, bpf_refcount_acquire_impl) 12272 BTF_ID(func, bpf_list_push_front_impl) 12273 BTF_ID(func, bpf_list_push_back_impl) 12274 BTF_ID(func, bpf_list_pop_front) 12275 BTF_ID(func, bpf_list_pop_back) 12276 BTF_ID(func, bpf_list_front) 12277 BTF_ID(func, bpf_list_back) 12278 BTF_ID(func, bpf_cast_to_kern_ctx) 12279 BTF_ID(func, bpf_rdonly_cast) 12280 BTF_ID(func, bpf_rcu_read_lock) 12281 BTF_ID(func, bpf_rcu_read_unlock) 12282 BTF_ID(func, bpf_rbtree_remove) 12283 BTF_ID(func, bpf_rbtree_add_impl) 12284 BTF_ID(func, bpf_rbtree_first) 12285 BTF_ID(func, bpf_rbtree_root) 12286 BTF_ID(func, bpf_rbtree_left) 12287 BTF_ID(func, bpf_rbtree_right) 12288 #ifdef CONFIG_NET 12289 BTF_ID(func, bpf_dynptr_from_skb) 12290 BTF_ID(func, bpf_dynptr_from_xdp) 12291 BTF_ID(func, bpf_dynptr_from_skb_meta) 12292 #else 12293 BTF_ID_UNUSED 12294 BTF_ID_UNUSED 12295 BTF_ID_UNUSED 12296 #endif 12297 BTF_ID(func, bpf_dynptr_slice) 12298 BTF_ID(func, bpf_dynptr_slice_rdwr) 12299 BTF_ID(func, bpf_dynptr_clone) 12300 BTF_ID(func, bpf_percpu_obj_new_impl) 12301 BTF_ID(func, bpf_percpu_obj_drop_impl) 12302 BTF_ID(func, bpf_throw) 12303 BTF_ID(func, bpf_wq_set_callback_impl) 12304 BTF_ID(func, bpf_preempt_disable) 12305 BTF_ID(func, bpf_preempt_enable) 12306 #ifdef CONFIG_CGROUPS 12307 BTF_ID(func, bpf_iter_css_task_new) 12308 #else 12309 BTF_ID_UNUSED 12310 #endif 12311 #ifdef CONFIG_BPF_EVENTS 12312 BTF_ID(func, bpf_session_cookie) 12313 #else 12314 BTF_ID_UNUSED 12315 #endif 12316 BTF_ID(func, bpf_get_kmem_cache) 12317 BTF_ID(func, bpf_local_irq_save) 12318 BTF_ID(func, bpf_local_irq_restore) 12319 BTF_ID(func, bpf_iter_num_new) 12320 BTF_ID(func, bpf_iter_num_next) 12321 BTF_ID(func, bpf_iter_num_destroy) 12322 #ifdef CONFIG_BPF_LSM 12323 BTF_ID(func, bpf_set_dentry_xattr) 12324 BTF_ID(func, bpf_remove_dentry_xattr) 12325 #else 12326 BTF_ID_UNUSED 12327 BTF_ID_UNUSED 12328 #endif 12329 BTF_ID(func, bpf_res_spin_lock) 12330 BTF_ID(func, bpf_res_spin_unlock) 12331 BTF_ID(func, bpf_res_spin_lock_irqsave) 12332 BTF_ID(func, bpf_res_spin_unlock_irqrestore) 12333 BTF_ID(func, __bpf_trap) 12334 12335 static bool is_kfunc_ret_null(struct bpf_kfunc_call_arg_meta *meta) 12336 { 12337 if (meta->func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl] && 12338 meta->arg_owning_ref) { 12339 return false; 12340 } 12341 12342 return meta->kfunc_flags & KF_RET_NULL; 12343 } 12344 12345 static bool is_kfunc_bpf_rcu_read_lock(struct bpf_kfunc_call_arg_meta *meta) 12346 { 12347 return meta->func_id == special_kfunc_list[KF_bpf_rcu_read_lock]; 12348 } 12349 12350 static bool is_kfunc_bpf_rcu_read_unlock(struct bpf_kfunc_call_arg_meta *meta) 12351 { 12352 return meta->func_id == special_kfunc_list[KF_bpf_rcu_read_unlock]; 12353 } 12354 12355 static bool is_kfunc_bpf_preempt_disable(struct bpf_kfunc_call_arg_meta *meta) 12356 { 12357 return meta->func_id == special_kfunc_list[KF_bpf_preempt_disable]; 12358 } 12359 12360 static bool is_kfunc_bpf_preempt_enable(struct bpf_kfunc_call_arg_meta *meta) 12361 { 12362 return meta->func_id == special_kfunc_list[KF_bpf_preempt_enable]; 12363 } 12364 12365 static enum kfunc_ptr_arg_type 12366 get_kfunc_ptr_arg_type(struct bpf_verifier_env *env, 12367 struct bpf_kfunc_call_arg_meta *meta, 12368 const struct btf_type *t, const struct btf_type *ref_t, 12369 const char *ref_tname, const struct btf_param *args, 12370 int argno, int nargs) 12371 { 12372 u32 regno = argno + 1; 12373 struct bpf_reg_state *regs = cur_regs(env); 12374 struct bpf_reg_state *reg = ®s[regno]; 12375 bool arg_mem_size = false; 12376 12377 if (meta->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx]) 12378 return KF_ARG_PTR_TO_CTX; 12379 12380 /* In this function, we verify the kfunc's BTF as per the argument type, 12381 * leaving the rest of the verification with respect to the register 12382 * type to our caller. When a set of conditions hold in the BTF type of 12383 * arguments, we resolve it to a known kfunc_ptr_arg_type. 12384 */ 12385 if (btf_is_prog_ctx_type(&env->log, meta->btf, t, resolve_prog_type(env->prog), argno)) 12386 return KF_ARG_PTR_TO_CTX; 12387 12388 if (is_kfunc_arg_nullable(meta->btf, &args[argno]) && register_is_null(reg)) 12389 return KF_ARG_PTR_TO_NULL; 12390 12391 if (is_kfunc_arg_alloc_obj(meta->btf, &args[argno])) 12392 return KF_ARG_PTR_TO_ALLOC_BTF_ID; 12393 12394 if (is_kfunc_arg_refcounted_kptr(meta->btf, &args[argno])) 12395 return KF_ARG_PTR_TO_REFCOUNTED_KPTR; 12396 12397 if (is_kfunc_arg_dynptr(meta->btf, &args[argno])) 12398 return KF_ARG_PTR_TO_DYNPTR; 12399 12400 if (is_kfunc_arg_iter(meta, argno, &args[argno])) 12401 return KF_ARG_PTR_TO_ITER; 12402 12403 if (is_kfunc_arg_list_head(meta->btf, &args[argno])) 12404 return KF_ARG_PTR_TO_LIST_HEAD; 12405 12406 if (is_kfunc_arg_list_node(meta->btf, &args[argno])) 12407 return KF_ARG_PTR_TO_LIST_NODE; 12408 12409 if (is_kfunc_arg_rbtree_root(meta->btf, &args[argno])) 12410 return KF_ARG_PTR_TO_RB_ROOT; 12411 12412 if (is_kfunc_arg_rbtree_node(meta->btf, &args[argno])) 12413 return KF_ARG_PTR_TO_RB_NODE; 12414 12415 if (is_kfunc_arg_const_str(meta->btf, &args[argno])) 12416 return KF_ARG_PTR_TO_CONST_STR; 12417 12418 if (is_kfunc_arg_map(meta->btf, &args[argno])) 12419 return KF_ARG_PTR_TO_MAP; 12420 12421 if (is_kfunc_arg_wq(meta->btf, &args[argno])) 12422 return KF_ARG_PTR_TO_WORKQUEUE; 12423 12424 if (is_kfunc_arg_irq_flag(meta->btf, &args[argno])) 12425 return KF_ARG_PTR_TO_IRQ_FLAG; 12426 12427 if (is_kfunc_arg_res_spin_lock(meta->btf, &args[argno])) 12428 return KF_ARG_PTR_TO_RES_SPIN_LOCK; 12429 12430 if ((base_type(reg->type) == PTR_TO_BTF_ID || reg2btf_ids[base_type(reg->type)])) { 12431 if (!btf_type_is_struct(ref_t)) { 12432 verbose(env, "kernel function %s args#%d pointer type %s %s is not supported\n", 12433 meta->func_name, argno, btf_type_str(ref_t), ref_tname); 12434 return -EINVAL; 12435 } 12436 return KF_ARG_PTR_TO_BTF_ID; 12437 } 12438 12439 if (is_kfunc_arg_callback(env, meta->btf, &args[argno])) 12440 return KF_ARG_PTR_TO_CALLBACK; 12441 12442 if (argno + 1 < nargs && 12443 (is_kfunc_arg_mem_size(meta->btf, &args[argno + 1], ®s[regno + 1]) || 12444 is_kfunc_arg_const_mem_size(meta->btf, &args[argno + 1], ®s[regno + 1]))) 12445 arg_mem_size = true; 12446 12447 /* This is the catch all argument type of register types supported by 12448 * check_helper_mem_access. However, we only allow when argument type is 12449 * pointer to scalar, or struct composed (recursively) of scalars. When 12450 * arg_mem_size is true, the pointer can be void *. 12451 */ 12452 if (!btf_type_is_scalar(ref_t) && !__btf_type_is_scalar_struct(env, meta->btf, ref_t, 0) && 12453 (arg_mem_size ? !btf_type_is_void(ref_t) : 1)) { 12454 verbose(env, "arg#%d pointer type %s %s must point to %sscalar, or struct with scalar\n", 12455 argno, btf_type_str(ref_t), ref_tname, arg_mem_size ? "void, " : ""); 12456 return -EINVAL; 12457 } 12458 return arg_mem_size ? KF_ARG_PTR_TO_MEM_SIZE : KF_ARG_PTR_TO_MEM; 12459 } 12460 12461 static int process_kf_arg_ptr_to_btf_id(struct bpf_verifier_env *env, 12462 struct bpf_reg_state *reg, 12463 const struct btf_type *ref_t, 12464 const char *ref_tname, u32 ref_id, 12465 struct bpf_kfunc_call_arg_meta *meta, 12466 int argno) 12467 { 12468 const struct btf_type *reg_ref_t; 12469 bool strict_type_match = false; 12470 const struct btf *reg_btf; 12471 const char *reg_ref_tname; 12472 bool taking_projection; 12473 bool struct_same; 12474 u32 reg_ref_id; 12475 12476 if (base_type(reg->type) == PTR_TO_BTF_ID) { 12477 reg_btf = reg->btf; 12478 reg_ref_id = reg->btf_id; 12479 } else { 12480 reg_btf = btf_vmlinux; 12481 reg_ref_id = *reg2btf_ids[base_type(reg->type)]; 12482 } 12483 12484 /* Enforce strict type matching for calls to kfuncs that are acquiring 12485 * or releasing a reference, or are no-cast aliases. We do _not_ 12486 * enforce strict matching for plain KF_TRUSTED_ARGS kfuncs by default, 12487 * as we want to enable BPF programs to pass types that are bitwise 12488 * equivalent without forcing them to explicitly cast with something 12489 * like bpf_cast_to_kern_ctx(). 12490 * 12491 * For example, say we had a type like the following: 12492 * 12493 * struct bpf_cpumask { 12494 * cpumask_t cpumask; 12495 * refcount_t usage; 12496 * }; 12497 * 12498 * Note that as specified in <linux/cpumask.h>, cpumask_t is typedef'ed 12499 * to a struct cpumask, so it would be safe to pass a struct 12500 * bpf_cpumask * to a kfunc expecting a struct cpumask *. 12501 * 12502 * The philosophy here is similar to how we allow scalars of different 12503 * types to be passed to kfuncs as long as the size is the same. The 12504 * only difference here is that we're simply allowing 12505 * btf_struct_ids_match() to walk the struct at the 0th offset, and 12506 * resolve types. 12507 */ 12508 if ((is_kfunc_release(meta) && reg->ref_obj_id) || 12509 btf_type_ids_nocast_alias(&env->log, reg_btf, reg_ref_id, meta->btf, ref_id)) 12510 strict_type_match = true; 12511 12512 WARN_ON_ONCE(is_kfunc_release(meta) && 12513 (reg->off || !tnum_is_const(reg->var_off) || 12514 reg->var_off.value)); 12515 12516 reg_ref_t = btf_type_skip_modifiers(reg_btf, reg_ref_id, ®_ref_id); 12517 reg_ref_tname = btf_name_by_offset(reg_btf, reg_ref_t->name_off); 12518 struct_same = btf_struct_ids_match(&env->log, reg_btf, reg_ref_id, reg->off, meta->btf, ref_id, strict_type_match); 12519 /* If kfunc is accepting a projection type (ie. __sk_buff), it cannot 12520 * actually use it -- it must cast to the underlying type. So we allow 12521 * caller to pass in the underlying type. 12522 */ 12523 taking_projection = btf_is_projection_of(ref_tname, reg_ref_tname); 12524 if (!taking_projection && !struct_same) { 12525 verbose(env, "kernel function %s args#%d expected pointer to %s %s but R%d has a pointer to %s %s\n", 12526 meta->func_name, argno, btf_type_str(ref_t), ref_tname, argno + 1, 12527 btf_type_str(reg_ref_t), reg_ref_tname); 12528 return -EINVAL; 12529 } 12530 return 0; 12531 } 12532 12533 static int process_irq_flag(struct bpf_verifier_env *env, int regno, 12534 struct bpf_kfunc_call_arg_meta *meta) 12535 { 12536 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno]; 12537 int err, kfunc_class = IRQ_NATIVE_KFUNC; 12538 bool irq_save; 12539 12540 if (meta->func_id == special_kfunc_list[KF_bpf_local_irq_save] || 12541 meta->func_id == special_kfunc_list[KF_bpf_res_spin_lock_irqsave]) { 12542 irq_save = true; 12543 if (meta->func_id == special_kfunc_list[KF_bpf_res_spin_lock_irqsave]) 12544 kfunc_class = IRQ_LOCK_KFUNC; 12545 } else if (meta->func_id == special_kfunc_list[KF_bpf_local_irq_restore] || 12546 meta->func_id == special_kfunc_list[KF_bpf_res_spin_unlock_irqrestore]) { 12547 irq_save = false; 12548 if (meta->func_id == special_kfunc_list[KF_bpf_res_spin_unlock_irqrestore]) 12549 kfunc_class = IRQ_LOCK_KFUNC; 12550 } else { 12551 verifier_bug(env, "unknown irq flags kfunc"); 12552 return -EFAULT; 12553 } 12554 12555 if (irq_save) { 12556 if (!is_irq_flag_reg_valid_uninit(env, reg)) { 12557 verbose(env, "expected uninitialized irq flag as arg#%d\n", regno - 1); 12558 return -EINVAL; 12559 } 12560 12561 err = check_mem_access(env, env->insn_idx, regno, 0, BPF_DW, BPF_WRITE, -1, false, false); 12562 if (err) 12563 return err; 12564 12565 err = mark_stack_slot_irq_flag(env, meta, reg, env->insn_idx, kfunc_class); 12566 if (err) 12567 return err; 12568 } else { 12569 err = is_irq_flag_reg_valid_init(env, reg); 12570 if (err) { 12571 verbose(env, "expected an initialized irq flag as arg#%d\n", regno - 1); 12572 return err; 12573 } 12574 12575 err = mark_irq_flag_read(env, reg); 12576 if (err) 12577 return err; 12578 12579 err = unmark_stack_slot_irq_flag(env, reg, kfunc_class); 12580 if (err) 12581 return err; 12582 } 12583 return 0; 12584 } 12585 12586 12587 static int ref_set_non_owning(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 12588 { 12589 struct btf_record *rec = reg_btf_record(reg); 12590 12591 if (!env->cur_state->active_locks) { 12592 verifier_bug(env, "%s w/o active lock", __func__); 12593 return -EFAULT; 12594 } 12595 12596 if (type_flag(reg->type) & NON_OWN_REF) { 12597 verifier_bug(env, "NON_OWN_REF already set"); 12598 return -EFAULT; 12599 } 12600 12601 reg->type |= NON_OWN_REF; 12602 if (rec->refcount_off >= 0) 12603 reg->type |= MEM_RCU; 12604 12605 return 0; 12606 } 12607 12608 static int ref_convert_owning_non_owning(struct bpf_verifier_env *env, u32 ref_obj_id) 12609 { 12610 struct bpf_verifier_state *state = env->cur_state; 12611 struct bpf_func_state *unused; 12612 struct bpf_reg_state *reg; 12613 int i; 12614 12615 if (!ref_obj_id) { 12616 verifier_bug(env, "ref_obj_id is zero for owning -> non-owning conversion"); 12617 return -EFAULT; 12618 } 12619 12620 for (i = 0; i < state->acquired_refs; i++) { 12621 if (state->refs[i].id != ref_obj_id) 12622 continue; 12623 12624 /* Clear ref_obj_id here so release_reference doesn't clobber 12625 * the whole reg 12626 */ 12627 bpf_for_each_reg_in_vstate(env->cur_state, unused, reg, ({ 12628 if (reg->ref_obj_id == ref_obj_id) { 12629 reg->ref_obj_id = 0; 12630 ref_set_non_owning(env, reg); 12631 } 12632 })); 12633 return 0; 12634 } 12635 12636 verifier_bug(env, "ref state missing for ref_obj_id"); 12637 return -EFAULT; 12638 } 12639 12640 /* Implementation details: 12641 * 12642 * Each register points to some region of memory, which we define as an 12643 * allocation. Each allocation may embed a bpf_spin_lock which protects any 12644 * special BPF objects (bpf_list_head, bpf_rb_root, etc.) part of the same 12645 * allocation. The lock and the data it protects are colocated in the same 12646 * memory region. 12647 * 12648 * Hence, everytime a register holds a pointer value pointing to such 12649 * allocation, the verifier preserves a unique reg->id for it. 12650 * 12651 * The verifier remembers the lock 'ptr' and the lock 'id' whenever 12652 * bpf_spin_lock is called. 12653 * 12654 * To enable this, lock state in the verifier captures two values: 12655 * active_lock.ptr = Register's type specific pointer 12656 * active_lock.id = A unique ID for each register pointer value 12657 * 12658 * Currently, PTR_TO_MAP_VALUE and PTR_TO_BTF_ID | MEM_ALLOC are the two 12659 * supported register types. 12660 * 12661 * The active_lock.ptr in case of map values is the reg->map_ptr, and in case of 12662 * allocated objects is the reg->btf pointer. 12663 * 12664 * The active_lock.id is non-unique for maps supporting direct_value_addr, as we 12665 * can establish the provenance of the map value statically for each distinct 12666 * lookup into such maps. They always contain a single map value hence unique 12667 * IDs for each pseudo load pessimizes the algorithm and rejects valid programs. 12668 * 12669 * So, in case of global variables, they use array maps with max_entries = 1, 12670 * hence their active_lock.ptr becomes map_ptr and id = 0 (since they all point 12671 * into the same map value as max_entries is 1, as described above). 12672 * 12673 * In case of inner map lookups, the inner map pointer has same map_ptr as the 12674 * outer map pointer (in verifier context), but each lookup into an inner map 12675 * assigns a fresh reg->id to the lookup, so while lookups into distinct inner 12676 * maps from the same outer map share the same map_ptr as active_lock.ptr, they 12677 * will get different reg->id assigned to each lookup, hence different 12678 * active_lock.id. 12679 * 12680 * In case of allocated objects, active_lock.ptr is the reg->btf, and the 12681 * reg->id is a unique ID preserved after the NULL pointer check on the pointer 12682 * returned from bpf_obj_new. Each allocation receives a new reg->id. 12683 */ 12684 static int check_reg_allocation_locked(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 12685 { 12686 struct bpf_reference_state *s; 12687 void *ptr; 12688 u32 id; 12689 12690 switch ((int)reg->type) { 12691 case PTR_TO_MAP_VALUE: 12692 ptr = reg->map_ptr; 12693 break; 12694 case PTR_TO_BTF_ID | MEM_ALLOC: 12695 ptr = reg->btf; 12696 break; 12697 default: 12698 verifier_bug(env, "unknown reg type for lock check"); 12699 return -EFAULT; 12700 } 12701 id = reg->id; 12702 12703 if (!env->cur_state->active_locks) 12704 return -EINVAL; 12705 s = find_lock_state(env->cur_state, REF_TYPE_LOCK_MASK, id, ptr); 12706 if (!s) { 12707 verbose(env, "held lock and object are not in the same allocation\n"); 12708 return -EINVAL; 12709 } 12710 return 0; 12711 } 12712 12713 static bool is_bpf_list_api_kfunc(u32 btf_id) 12714 { 12715 return btf_id == special_kfunc_list[KF_bpf_list_push_front_impl] || 12716 btf_id == special_kfunc_list[KF_bpf_list_push_back_impl] || 12717 btf_id == special_kfunc_list[KF_bpf_list_pop_front] || 12718 btf_id == special_kfunc_list[KF_bpf_list_pop_back] || 12719 btf_id == special_kfunc_list[KF_bpf_list_front] || 12720 btf_id == special_kfunc_list[KF_bpf_list_back]; 12721 } 12722 12723 static bool is_bpf_rbtree_api_kfunc(u32 btf_id) 12724 { 12725 return btf_id == special_kfunc_list[KF_bpf_rbtree_add_impl] || 12726 btf_id == special_kfunc_list[KF_bpf_rbtree_remove] || 12727 btf_id == special_kfunc_list[KF_bpf_rbtree_first] || 12728 btf_id == special_kfunc_list[KF_bpf_rbtree_root] || 12729 btf_id == special_kfunc_list[KF_bpf_rbtree_left] || 12730 btf_id == special_kfunc_list[KF_bpf_rbtree_right]; 12731 } 12732 12733 static bool is_bpf_iter_num_api_kfunc(u32 btf_id) 12734 { 12735 return btf_id == special_kfunc_list[KF_bpf_iter_num_new] || 12736 btf_id == special_kfunc_list[KF_bpf_iter_num_next] || 12737 btf_id == special_kfunc_list[KF_bpf_iter_num_destroy]; 12738 } 12739 12740 static bool is_bpf_graph_api_kfunc(u32 btf_id) 12741 { 12742 return is_bpf_list_api_kfunc(btf_id) || is_bpf_rbtree_api_kfunc(btf_id) || 12743 btf_id == special_kfunc_list[KF_bpf_refcount_acquire_impl]; 12744 } 12745 12746 static bool is_bpf_res_spin_lock_kfunc(u32 btf_id) 12747 { 12748 return btf_id == special_kfunc_list[KF_bpf_res_spin_lock] || 12749 btf_id == special_kfunc_list[KF_bpf_res_spin_unlock] || 12750 btf_id == special_kfunc_list[KF_bpf_res_spin_lock_irqsave] || 12751 btf_id == special_kfunc_list[KF_bpf_res_spin_unlock_irqrestore]; 12752 } 12753 12754 static bool kfunc_spin_allowed(u32 btf_id) 12755 { 12756 return is_bpf_graph_api_kfunc(btf_id) || is_bpf_iter_num_api_kfunc(btf_id) || 12757 is_bpf_res_spin_lock_kfunc(btf_id); 12758 } 12759 12760 static bool is_sync_callback_calling_kfunc(u32 btf_id) 12761 { 12762 return btf_id == special_kfunc_list[KF_bpf_rbtree_add_impl]; 12763 } 12764 12765 static bool is_async_callback_calling_kfunc(u32 btf_id) 12766 { 12767 return btf_id == special_kfunc_list[KF_bpf_wq_set_callback_impl]; 12768 } 12769 12770 static bool is_bpf_throw_kfunc(struct bpf_insn *insn) 12771 { 12772 return bpf_pseudo_kfunc_call(insn) && insn->off == 0 && 12773 insn->imm == special_kfunc_list[KF_bpf_throw]; 12774 } 12775 12776 static bool is_bpf_wq_set_callback_impl_kfunc(u32 btf_id) 12777 { 12778 return btf_id == special_kfunc_list[KF_bpf_wq_set_callback_impl]; 12779 } 12780 12781 static bool is_callback_calling_kfunc(u32 btf_id) 12782 { 12783 return is_sync_callback_calling_kfunc(btf_id) || 12784 is_async_callback_calling_kfunc(btf_id); 12785 } 12786 12787 static bool is_rbtree_lock_required_kfunc(u32 btf_id) 12788 { 12789 return is_bpf_rbtree_api_kfunc(btf_id); 12790 } 12791 12792 static bool check_kfunc_is_graph_root_api(struct bpf_verifier_env *env, 12793 enum btf_field_type head_field_type, 12794 u32 kfunc_btf_id) 12795 { 12796 bool ret; 12797 12798 switch (head_field_type) { 12799 case BPF_LIST_HEAD: 12800 ret = is_bpf_list_api_kfunc(kfunc_btf_id); 12801 break; 12802 case BPF_RB_ROOT: 12803 ret = is_bpf_rbtree_api_kfunc(kfunc_btf_id); 12804 break; 12805 default: 12806 verbose(env, "verifier internal error: unexpected graph root argument type %s\n", 12807 btf_field_type_name(head_field_type)); 12808 return false; 12809 } 12810 12811 if (!ret) 12812 verbose(env, "verifier internal error: %s head arg for unknown kfunc\n", 12813 btf_field_type_name(head_field_type)); 12814 return ret; 12815 } 12816 12817 static bool check_kfunc_is_graph_node_api(struct bpf_verifier_env *env, 12818 enum btf_field_type node_field_type, 12819 u32 kfunc_btf_id) 12820 { 12821 bool ret; 12822 12823 switch (node_field_type) { 12824 case BPF_LIST_NODE: 12825 ret = (kfunc_btf_id == special_kfunc_list[KF_bpf_list_push_front_impl] || 12826 kfunc_btf_id == special_kfunc_list[KF_bpf_list_push_back_impl]); 12827 break; 12828 case BPF_RB_NODE: 12829 ret = (kfunc_btf_id == special_kfunc_list[KF_bpf_rbtree_remove] || 12830 kfunc_btf_id == special_kfunc_list[KF_bpf_rbtree_add_impl] || 12831 kfunc_btf_id == special_kfunc_list[KF_bpf_rbtree_left] || 12832 kfunc_btf_id == special_kfunc_list[KF_bpf_rbtree_right]); 12833 break; 12834 default: 12835 verbose(env, "verifier internal error: unexpected graph node argument type %s\n", 12836 btf_field_type_name(node_field_type)); 12837 return false; 12838 } 12839 12840 if (!ret) 12841 verbose(env, "verifier internal error: %s node arg for unknown kfunc\n", 12842 btf_field_type_name(node_field_type)); 12843 return ret; 12844 } 12845 12846 static int 12847 __process_kf_arg_ptr_to_graph_root(struct bpf_verifier_env *env, 12848 struct bpf_reg_state *reg, u32 regno, 12849 struct bpf_kfunc_call_arg_meta *meta, 12850 enum btf_field_type head_field_type, 12851 struct btf_field **head_field) 12852 { 12853 const char *head_type_name; 12854 struct btf_field *field; 12855 struct btf_record *rec; 12856 u32 head_off; 12857 12858 if (meta->btf != btf_vmlinux) { 12859 verifier_bug(env, "unexpected btf mismatch in kfunc call"); 12860 return -EFAULT; 12861 } 12862 12863 if (!check_kfunc_is_graph_root_api(env, head_field_type, meta->func_id)) 12864 return -EFAULT; 12865 12866 head_type_name = btf_field_type_name(head_field_type); 12867 if (!tnum_is_const(reg->var_off)) { 12868 verbose(env, 12869 "R%d doesn't have constant offset. %s has to be at the constant offset\n", 12870 regno, head_type_name); 12871 return -EINVAL; 12872 } 12873 12874 rec = reg_btf_record(reg); 12875 head_off = reg->off + reg->var_off.value; 12876 field = btf_record_find(rec, head_off, head_field_type); 12877 if (!field) { 12878 verbose(env, "%s not found at offset=%u\n", head_type_name, head_off); 12879 return -EINVAL; 12880 } 12881 12882 /* All functions require bpf_list_head to be protected using a bpf_spin_lock */ 12883 if (check_reg_allocation_locked(env, reg)) { 12884 verbose(env, "bpf_spin_lock at off=%d must be held for %s\n", 12885 rec->spin_lock_off, head_type_name); 12886 return -EINVAL; 12887 } 12888 12889 if (*head_field) { 12890 verifier_bug(env, "repeating %s arg", head_type_name); 12891 return -EFAULT; 12892 } 12893 *head_field = field; 12894 return 0; 12895 } 12896 12897 static int process_kf_arg_ptr_to_list_head(struct bpf_verifier_env *env, 12898 struct bpf_reg_state *reg, u32 regno, 12899 struct bpf_kfunc_call_arg_meta *meta) 12900 { 12901 return __process_kf_arg_ptr_to_graph_root(env, reg, regno, meta, BPF_LIST_HEAD, 12902 &meta->arg_list_head.field); 12903 } 12904 12905 static int process_kf_arg_ptr_to_rbtree_root(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_RB_ROOT, 12910 &meta->arg_rbtree_root.field); 12911 } 12912 12913 static int 12914 __process_kf_arg_ptr_to_graph_node(struct bpf_verifier_env *env, 12915 struct bpf_reg_state *reg, u32 regno, 12916 struct bpf_kfunc_call_arg_meta *meta, 12917 enum btf_field_type head_field_type, 12918 enum btf_field_type node_field_type, 12919 struct btf_field **node_field) 12920 { 12921 const char *node_type_name; 12922 const struct btf_type *et, *t; 12923 struct btf_field *field; 12924 u32 node_off; 12925 12926 if (meta->btf != btf_vmlinux) { 12927 verifier_bug(env, "unexpected btf mismatch in kfunc call"); 12928 return -EFAULT; 12929 } 12930 12931 if (!check_kfunc_is_graph_node_api(env, node_field_type, meta->func_id)) 12932 return -EFAULT; 12933 12934 node_type_name = btf_field_type_name(node_field_type); 12935 if (!tnum_is_const(reg->var_off)) { 12936 verbose(env, 12937 "R%d doesn't have constant offset. %s has to be at the constant offset\n", 12938 regno, node_type_name); 12939 return -EINVAL; 12940 } 12941 12942 node_off = reg->off + reg->var_off.value; 12943 field = reg_find_field_offset(reg, node_off, node_field_type); 12944 if (!field) { 12945 verbose(env, "%s not found at offset=%u\n", node_type_name, node_off); 12946 return -EINVAL; 12947 } 12948 12949 field = *node_field; 12950 12951 et = btf_type_by_id(field->graph_root.btf, field->graph_root.value_btf_id); 12952 t = btf_type_by_id(reg->btf, reg->btf_id); 12953 if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, 0, field->graph_root.btf, 12954 field->graph_root.value_btf_id, true)) { 12955 verbose(env, "operation on %s expects arg#1 %s at offset=%d " 12956 "in struct %s, but arg is at offset=%d in struct %s\n", 12957 btf_field_type_name(head_field_type), 12958 btf_field_type_name(node_field_type), 12959 field->graph_root.node_offset, 12960 btf_name_by_offset(field->graph_root.btf, et->name_off), 12961 node_off, btf_name_by_offset(reg->btf, t->name_off)); 12962 return -EINVAL; 12963 } 12964 meta->arg_btf = reg->btf; 12965 meta->arg_btf_id = reg->btf_id; 12966 12967 if (node_off != field->graph_root.node_offset) { 12968 verbose(env, "arg#1 offset=%d, but expected %s at offset=%d in struct %s\n", 12969 node_off, btf_field_type_name(node_field_type), 12970 field->graph_root.node_offset, 12971 btf_name_by_offset(field->graph_root.btf, et->name_off)); 12972 return -EINVAL; 12973 } 12974 12975 return 0; 12976 } 12977 12978 static int process_kf_arg_ptr_to_list_node(struct bpf_verifier_env *env, 12979 struct bpf_reg_state *reg, u32 regno, 12980 struct bpf_kfunc_call_arg_meta *meta) 12981 { 12982 return __process_kf_arg_ptr_to_graph_node(env, reg, regno, meta, 12983 BPF_LIST_HEAD, BPF_LIST_NODE, 12984 &meta->arg_list_head.field); 12985 } 12986 12987 static int process_kf_arg_ptr_to_rbtree_node(struct bpf_verifier_env *env, 12988 struct bpf_reg_state *reg, u32 regno, 12989 struct bpf_kfunc_call_arg_meta *meta) 12990 { 12991 return __process_kf_arg_ptr_to_graph_node(env, reg, regno, meta, 12992 BPF_RB_ROOT, BPF_RB_NODE, 12993 &meta->arg_rbtree_root.field); 12994 } 12995 12996 /* 12997 * css_task iter allowlist is needed to avoid dead locking on css_set_lock. 12998 * LSM hooks and iters (both sleepable and non-sleepable) are safe. 12999 * Any sleepable progs are also safe since bpf_check_attach_target() enforce 13000 * them can only be attached to some specific hook points. 13001 */ 13002 static bool check_css_task_iter_allowlist(struct bpf_verifier_env *env) 13003 { 13004 enum bpf_prog_type prog_type = resolve_prog_type(env->prog); 13005 13006 switch (prog_type) { 13007 case BPF_PROG_TYPE_LSM: 13008 return true; 13009 case BPF_PROG_TYPE_TRACING: 13010 if (env->prog->expected_attach_type == BPF_TRACE_ITER) 13011 return true; 13012 fallthrough; 13013 default: 13014 return in_sleepable(env); 13015 } 13016 } 13017 13018 static int check_kfunc_args(struct bpf_verifier_env *env, struct bpf_kfunc_call_arg_meta *meta, 13019 int insn_idx) 13020 { 13021 const char *func_name = meta->func_name, *ref_tname; 13022 const struct btf *btf = meta->btf; 13023 const struct btf_param *args; 13024 struct btf_record *rec; 13025 u32 i, nargs; 13026 int ret; 13027 13028 args = (const struct btf_param *)(meta->func_proto + 1); 13029 nargs = btf_type_vlen(meta->func_proto); 13030 if (nargs > MAX_BPF_FUNC_REG_ARGS) { 13031 verbose(env, "Function %s has %d > %d args\n", func_name, nargs, 13032 MAX_BPF_FUNC_REG_ARGS); 13033 return -EINVAL; 13034 } 13035 13036 /* Check that BTF function arguments match actual types that the 13037 * verifier sees. 13038 */ 13039 for (i = 0; i < nargs; i++) { 13040 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[i + 1]; 13041 const struct btf_type *t, *ref_t, *resolve_ret; 13042 enum bpf_arg_type arg_type = ARG_DONTCARE; 13043 u32 regno = i + 1, ref_id, type_size; 13044 bool is_ret_buf_sz = false; 13045 int kf_arg_type; 13046 13047 t = btf_type_skip_modifiers(btf, args[i].type, NULL); 13048 13049 if (is_kfunc_arg_ignore(btf, &args[i])) 13050 continue; 13051 13052 if (is_kfunc_arg_prog(btf, &args[i])) { 13053 /* Used to reject repeated use of __prog. */ 13054 if (meta->arg_prog) { 13055 verifier_bug(env, "Only 1 prog->aux argument supported per-kfunc"); 13056 return -EFAULT; 13057 } 13058 meta->arg_prog = true; 13059 cur_aux(env)->arg_prog = regno; 13060 continue; 13061 } 13062 13063 if (btf_type_is_scalar(t)) { 13064 if (reg->type != SCALAR_VALUE) { 13065 verbose(env, "R%d is not a scalar\n", regno); 13066 return -EINVAL; 13067 } 13068 13069 if (is_kfunc_arg_constant(meta->btf, &args[i])) { 13070 if (meta->arg_constant.found) { 13071 verifier_bug(env, "only one constant argument permitted"); 13072 return -EFAULT; 13073 } 13074 if (!tnum_is_const(reg->var_off)) { 13075 verbose(env, "R%d must be a known constant\n", regno); 13076 return -EINVAL; 13077 } 13078 ret = mark_chain_precision(env, regno); 13079 if (ret < 0) 13080 return ret; 13081 meta->arg_constant.found = true; 13082 meta->arg_constant.value = reg->var_off.value; 13083 } else if (is_kfunc_arg_scalar_with_name(btf, &args[i], "rdonly_buf_size")) { 13084 meta->r0_rdonly = true; 13085 is_ret_buf_sz = true; 13086 } else if (is_kfunc_arg_scalar_with_name(btf, &args[i], "rdwr_buf_size")) { 13087 is_ret_buf_sz = true; 13088 } 13089 13090 if (is_ret_buf_sz) { 13091 if (meta->r0_size) { 13092 verbose(env, "2 or more rdonly/rdwr_buf_size parameters for kfunc"); 13093 return -EINVAL; 13094 } 13095 13096 if (!tnum_is_const(reg->var_off)) { 13097 verbose(env, "R%d is not a const\n", regno); 13098 return -EINVAL; 13099 } 13100 13101 meta->r0_size = reg->var_off.value; 13102 ret = mark_chain_precision(env, regno); 13103 if (ret) 13104 return ret; 13105 } 13106 continue; 13107 } 13108 13109 if (!btf_type_is_ptr(t)) { 13110 verbose(env, "Unrecognized arg#%d type %s\n", i, btf_type_str(t)); 13111 return -EINVAL; 13112 } 13113 13114 if ((is_kfunc_trusted_args(meta) || is_kfunc_rcu(meta)) && 13115 (register_is_null(reg) || type_may_be_null(reg->type)) && 13116 !is_kfunc_arg_nullable(meta->btf, &args[i])) { 13117 verbose(env, "Possibly NULL pointer passed to trusted arg%d\n", i); 13118 return -EACCES; 13119 } 13120 13121 if (reg->ref_obj_id) { 13122 if (is_kfunc_release(meta) && meta->ref_obj_id) { 13123 verifier_bug(env, "more than one arg with ref_obj_id R%d %u %u", 13124 regno, reg->ref_obj_id, 13125 meta->ref_obj_id); 13126 return -EFAULT; 13127 } 13128 meta->ref_obj_id = reg->ref_obj_id; 13129 if (is_kfunc_release(meta)) 13130 meta->release_regno = regno; 13131 } 13132 13133 ref_t = btf_type_skip_modifiers(btf, t->type, &ref_id); 13134 ref_tname = btf_name_by_offset(btf, ref_t->name_off); 13135 13136 kf_arg_type = get_kfunc_ptr_arg_type(env, meta, t, ref_t, ref_tname, args, i, nargs); 13137 if (kf_arg_type < 0) 13138 return kf_arg_type; 13139 13140 switch (kf_arg_type) { 13141 case KF_ARG_PTR_TO_NULL: 13142 continue; 13143 case KF_ARG_PTR_TO_MAP: 13144 if (!reg->map_ptr) { 13145 verbose(env, "pointer in R%d isn't map pointer\n", regno); 13146 return -EINVAL; 13147 } 13148 if (meta->map.ptr && reg->map_ptr->record->wq_off >= 0) { 13149 /* Use map_uid (which is unique id of inner map) to reject: 13150 * inner_map1 = bpf_map_lookup_elem(outer_map, key1) 13151 * inner_map2 = bpf_map_lookup_elem(outer_map, key2) 13152 * if (inner_map1 && inner_map2) { 13153 * wq = bpf_map_lookup_elem(inner_map1); 13154 * if (wq) 13155 * // mismatch would have been allowed 13156 * bpf_wq_init(wq, inner_map2); 13157 * } 13158 * 13159 * Comparing map_ptr is enough to distinguish normal and outer maps. 13160 */ 13161 if (meta->map.ptr != reg->map_ptr || 13162 meta->map.uid != reg->map_uid) { 13163 verbose(env, 13164 "workqueue pointer in R1 map_uid=%d doesn't match map pointer in R2 map_uid=%d\n", 13165 meta->map.uid, reg->map_uid); 13166 return -EINVAL; 13167 } 13168 } 13169 meta->map.ptr = reg->map_ptr; 13170 meta->map.uid = reg->map_uid; 13171 fallthrough; 13172 case KF_ARG_PTR_TO_ALLOC_BTF_ID: 13173 case KF_ARG_PTR_TO_BTF_ID: 13174 if (!is_kfunc_trusted_args(meta) && !is_kfunc_rcu(meta)) 13175 break; 13176 13177 if (!is_trusted_reg(reg)) { 13178 if (!is_kfunc_rcu(meta)) { 13179 verbose(env, "R%d must be referenced or trusted\n", regno); 13180 return -EINVAL; 13181 } 13182 if (!is_rcu_reg(reg)) { 13183 verbose(env, "R%d must be a rcu pointer\n", regno); 13184 return -EINVAL; 13185 } 13186 } 13187 fallthrough; 13188 case KF_ARG_PTR_TO_CTX: 13189 case KF_ARG_PTR_TO_DYNPTR: 13190 case KF_ARG_PTR_TO_ITER: 13191 case KF_ARG_PTR_TO_LIST_HEAD: 13192 case KF_ARG_PTR_TO_LIST_NODE: 13193 case KF_ARG_PTR_TO_RB_ROOT: 13194 case KF_ARG_PTR_TO_RB_NODE: 13195 case KF_ARG_PTR_TO_MEM: 13196 case KF_ARG_PTR_TO_MEM_SIZE: 13197 case KF_ARG_PTR_TO_CALLBACK: 13198 case KF_ARG_PTR_TO_REFCOUNTED_KPTR: 13199 case KF_ARG_PTR_TO_CONST_STR: 13200 case KF_ARG_PTR_TO_WORKQUEUE: 13201 case KF_ARG_PTR_TO_IRQ_FLAG: 13202 case KF_ARG_PTR_TO_RES_SPIN_LOCK: 13203 break; 13204 default: 13205 verifier_bug(env, "unknown kfunc arg type %d", kf_arg_type); 13206 return -EFAULT; 13207 } 13208 13209 if (is_kfunc_release(meta) && reg->ref_obj_id) 13210 arg_type |= OBJ_RELEASE; 13211 ret = check_func_arg_reg_off(env, reg, regno, arg_type); 13212 if (ret < 0) 13213 return ret; 13214 13215 switch (kf_arg_type) { 13216 case KF_ARG_PTR_TO_CTX: 13217 if (reg->type != PTR_TO_CTX) { 13218 verbose(env, "arg#%d expected pointer to ctx, but got %s\n", 13219 i, reg_type_str(env, reg->type)); 13220 return -EINVAL; 13221 } 13222 13223 if (meta->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx]) { 13224 ret = get_kern_ctx_btf_id(&env->log, resolve_prog_type(env->prog)); 13225 if (ret < 0) 13226 return -EINVAL; 13227 meta->ret_btf_id = ret; 13228 } 13229 break; 13230 case KF_ARG_PTR_TO_ALLOC_BTF_ID: 13231 if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC)) { 13232 if (meta->func_id != special_kfunc_list[KF_bpf_obj_drop_impl]) { 13233 verbose(env, "arg#%d expected for bpf_obj_drop_impl()\n", i); 13234 return -EINVAL; 13235 } 13236 } else if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC | MEM_PERCPU)) { 13237 if (meta->func_id != special_kfunc_list[KF_bpf_percpu_obj_drop_impl]) { 13238 verbose(env, "arg#%d expected for bpf_percpu_obj_drop_impl()\n", i); 13239 return -EINVAL; 13240 } 13241 } else { 13242 verbose(env, "arg#%d expected pointer to allocated object\n", i); 13243 return -EINVAL; 13244 } 13245 if (!reg->ref_obj_id) { 13246 verbose(env, "allocated object must be referenced\n"); 13247 return -EINVAL; 13248 } 13249 if (meta->btf == btf_vmlinux) { 13250 meta->arg_btf = reg->btf; 13251 meta->arg_btf_id = reg->btf_id; 13252 } 13253 break; 13254 case KF_ARG_PTR_TO_DYNPTR: 13255 { 13256 enum bpf_arg_type dynptr_arg_type = ARG_PTR_TO_DYNPTR; 13257 int clone_ref_obj_id = 0; 13258 13259 if (reg->type == CONST_PTR_TO_DYNPTR) 13260 dynptr_arg_type |= MEM_RDONLY; 13261 13262 if (is_kfunc_arg_uninit(btf, &args[i])) 13263 dynptr_arg_type |= MEM_UNINIT; 13264 13265 if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_from_skb]) { 13266 dynptr_arg_type |= DYNPTR_TYPE_SKB; 13267 } else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_from_xdp]) { 13268 dynptr_arg_type |= DYNPTR_TYPE_XDP; 13269 } else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_from_skb_meta]) { 13270 dynptr_arg_type |= DYNPTR_TYPE_SKB_META; 13271 } else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_clone] && 13272 (dynptr_arg_type & MEM_UNINIT)) { 13273 enum bpf_dynptr_type parent_type = meta->initialized_dynptr.type; 13274 13275 if (parent_type == BPF_DYNPTR_TYPE_INVALID) { 13276 verifier_bug(env, "no dynptr type for parent of clone"); 13277 return -EFAULT; 13278 } 13279 13280 dynptr_arg_type |= (unsigned int)get_dynptr_type_flag(parent_type); 13281 clone_ref_obj_id = meta->initialized_dynptr.ref_obj_id; 13282 if (dynptr_type_refcounted(parent_type) && !clone_ref_obj_id) { 13283 verifier_bug(env, "missing ref obj id for parent of clone"); 13284 return -EFAULT; 13285 } 13286 } 13287 13288 ret = process_dynptr_func(env, regno, insn_idx, dynptr_arg_type, clone_ref_obj_id); 13289 if (ret < 0) 13290 return ret; 13291 13292 if (!(dynptr_arg_type & MEM_UNINIT)) { 13293 int id = dynptr_id(env, reg); 13294 13295 if (id < 0) { 13296 verifier_bug(env, "failed to obtain dynptr id"); 13297 return id; 13298 } 13299 meta->initialized_dynptr.id = id; 13300 meta->initialized_dynptr.type = dynptr_get_type(env, reg); 13301 meta->initialized_dynptr.ref_obj_id = dynptr_ref_obj_id(env, reg); 13302 } 13303 13304 break; 13305 } 13306 case KF_ARG_PTR_TO_ITER: 13307 if (meta->func_id == special_kfunc_list[KF_bpf_iter_css_task_new]) { 13308 if (!check_css_task_iter_allowlist(env)) { 13309 verbose(env, "css_task_iter is only allowed in bpf_lsm, bpf_iter and sleepable progs\n"); 13310 return -EINVAL; 13311 } 13312 } 13313 ret = process_iter_arg(env, regno, insn_idx, meta); 13314 if (ret < 0) 13315 return ret; 13316 break; 13317 case KF_ARG_PTR_TO_LIST_HEAD: 13318 if (reg->type != PTR_TO_MAP_VALUE && 13319 reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) { 13320 verbose(env, "arg#%d expected pointer to map value or allocated object\n", i); 13321 return -EINVAL; 13322 } 13323 if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC) && !reg->ref_obj_id) { 13324 verbose(env, "allocated object must be referenced\n"); 13325 return -EINVAL; 13326 } 13327 ret = process_kf_arg_ptr_to_list_head(env, reg, regno, meta); 13328 if (ret < 0) 13329 return ret; 13330 break; 13331 case KF_ARG_PTR_TO_RB_ROOT: 13332 if (reg->type != PTR_TO_MAP_VALUE && 13333 reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) { 13334 verbose(env, "arg#%d expected pointer to map value or allocated object\n", i); 13335 return -EINVAL; 13336 } 13337 if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC) && !reg->ref_obj_id) { 13338 verbose(env, "allocated object must be referenced\n"); 13339 return -EINVAL; 13340 } 13341 ret = process_kf_arg_ptr_to_rbtree_root(env, reg, regno, meta); 13342 if (ret < 0) 13343 return ret; 13344 break; 13345 case KF_ARG_PTR_TO_LIST_NODE: 13346 if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) { 13347 verbose(env, "arg#%d expected pointer to allocated object\n", i); 13348 return -EINVAL; 13349 } 13350 if (!reg->ref_obj_id) { 13351 verbose(env, "allocated object must be referenced\n"); 13352 return -EINVAL; 13353 } 13354 ret = process_kf_arg_ptr_to_list_node(env, reg, regno, meta); 13355 if (ret < 0) 13356 return ret; 13357 break; 13358 case KF_ARG_PTR_TO_RB_NODE: 13359 if (meta->func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) { 13360 if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) { 13361 verbose(env, "arg#%d expected pointer to allocated object\n", i); 13362 return -EINVAL; 13363 } 13364 if (!reg->ref_obj_id) { 13365 verbose(env, "allocated object must be referenced\n"); 13366 return -EINVAL; 13367 } 13368 } else { 13369 if (!type_is_non_owning_ref(reg->type) && !reg->ref_obj_id) { 13370 verbose(env, "%s can only take non-owning or refcounted bpf_rb_node pointer\n", func_name); 13371 return -EINVAL; 13372 } 13373 if (in_rbtree_lock_required_cb(env)) { 13374 verbose(env, "%s not allowed in rbtree cb\n", func_name); 13375 return -EINVAL; 13376 } 13377 } 13378 13379 ret = process_kf_arg_ptr_to_rbtree_node(env, reg, regno, meta); 13380 if (ret < 0) 13381 return ret; 13382 break; 13383 case KF_ARG_PTR_TO_MAP: 13384 /* If argument has '__map' suffix expect 'struct bpf_map *' */ 13385 ref_id = *reg2btf_ids[CONST_PTR_TO_MAP]; 13386 ref_t = btf_type_by_id(btf_vmlinux, ref_id); 13387 ref_tname = btf_name_by_offset(btf, ref_t->name_off); 13388 fallthrough; 13389 case KF_ARG_PTR_TO_BTF_ID: 13390 /* Only base_type is checked, further checks are done here */ 13391 if ((base_type(reg->type) != PTR_TO_BTF_ID || 13392 (bpf_type_has_unsafe_modifiers(reg->type) && !is_rcu_reg(reg))) && 13393 !reg2btf_ids[base_type(reg->type)]) { 13394 verbose(env, "arg#%d is %s ", i, reg_type_str(env, reg->type)); 13395 verbose(env, "expected %s or socket\n", 13396 reg_type_str(env, base_type(reg->type) | 13397 (type_flag(reg->type) & BPF_REG_TRUSTED_MODIFIERS))); 13398 return -EINVAL; 13399 } 13400 ret = process_kf_arg_ptr_to_btf_id(env, reg, ref_t, ref_tname, ref_id, meta, i); 13401 if (ret < 0) 13402 return ret; 13403 break; 13404 case KF_ARG_PTR_TO_MEM: 13405 resolve_ret = btf_resolve_size(btf, ref_t, &type_size); 13406 if (IS_ERR(resolve_ret)) { 13407 verbose(env, "arg#%d reference type('%s %s') size cannot be determined: %ld\n", 13408 i, btf_type_str(ref_t), ref_tname, PTR_ERR(resolve_ret)); 13409 return -EINVAL; 13410 } 13411 ret = check_mem_reg(env, reg, regno, type_size); 13412 if (ret < 0) 13413 return ret; 13414 break; 13415 case KF_ARG_PTR_TO_MEM_SIZE: 13416 { 13417 struct bpf_reg_state *buff_reg = ®s[regno]; 13418 const struct btf_param *buff_arg = &args[i]; 13419 struct bpf_reg_state *size_reg = ®s[regno + 1]; 13420 const struct btf_param *size_arg = &args[i + 1]; 13421 13422 if (!register_is_null(buff_reg) || !is_kfunc_arg_optional(meta->btf, buff_arg)) { 13423 ret = check_kfunc_mem_size_reg(env, size_reg, regno + 1); 13424 if (ret < 0) { 13425 verbose(env, "arg#%d arg#%d memory, len pair leads to invalid memory access\n", i, i + 1); 13426 return ret; 13427 } 13428 } 13429 13430 if (is_kfunc_arg_const_mem_size(meta->btf, size_arg, size_reg)) { 13431 if (meta->arg_constant.found) { 13432 verifier_bug(env, "only one constant argument permitted"); 13433 return -EFAULT; 13434 } 13435 if (!tnum_is_const(size_reg->var_off)) { 13436 verbose(env, "R%d must be a known constant\n", regno + 1); 13437 return -EINVAL; 13438 } 13439 meta->arg_constant.found = true; 13440 meta->arg_constant.value = size_reg->var_off.value; 13441 } 13442 13443 /* Skip next '__sz' or '__szk' argument */ 13444 i++; 13445 break; 13446 } 13447 case KF_ARG_PTR_TO_CALLBACK: 13448 if (reg->type != PTR_TO_FUNC) { 13449 verbose(env, "arg%d expected pointer to func\n", i); 13450 return -EINVAL; 13451 } 13452 meta->subprogno = reg->subprogno; 13453 break; 13454 case KF_ARG_PTR_TO_REFCOUNTED_KPTR: 13455 if (!type_is_ptr_alloc_obj(reg->type)) { 13456 verbose(env, "arg#%d is neither owning or non-owning ref\n", i); 13457 return -EINVAL; 13458 } 13459 if (!type_is_non_owning_ref(reg->type)) 13460 meta->arg_owning_ref = true; 13461 13462 rec = reg_btf_record(reg); 13463 if (!rec) { 13464 verifier_bug(env, "Couldn't find btf_record"); 13465 return -EFAULT; 13466 } 13467 13468 if (rec->refcount_off < 0) { 13469 verbose(env, "arg#%d doesn't point to a type with bpf_refcount field\n", i); 13470 return -EINVAL; 13471 } 13472 13473 meta->arg_btf = reg->btf; 13474 meta->arg_btf_id = reg->btf_id; 13475 break; 13476 case KF_ARG_PTR_TO_CONST_STR: 13477 if (reg->type != PTR_TO_MAP_VALUE) { 13478 verbose(env, "arg#%d doesn't point to a const string\n", i); 13479 return -EINVAL; 13480 } 13481 ret = check_reg_const_str(env, reg, regno); 13482 if (ret) 13483 return ret; 13484 break; 13485 case KF_ARG_PTR_TO_WORKQUEUE: 13486 if (reg->type != PTR_TO_MAP_VALUE) { 13487 verbose(env, "arg#%d doesn't point to a map value\n", i); 13488 return -EINVAL; 13489 } 13490 ret = process_wq_func(env, regno, meta); 13491 if (ret < 0) 13492 return ret; 13493 break; 13494 case KF_ARG_PTR_TO_IRQ_FLAG: 13495 if (reg->type != PTR_TO_STACK) { 13496 verbose(env, "arg#%d doesn't point to an irq flag on stack\n", i); 13497 return -EINVAL; 13498 } 13499 ret = process_irq_flag(env, regno, meta); 13500 if (ret < 0) 13501 return ret; 13502 break; 13503 case KF_ARG_PTR_TO_RES_SPIN_LOCK: 13504 { 13505 int flags = PROCESS_RES_LOCK; 13506 13507 if (reg->type != PTR_TO_MAP_VALUE && reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) { 13508 verbose(env, "arg#%d doesn't point to map value or allocated object\n", i); 13509 return -EINVAL; 13510 } 13511 13512 if (!is_bpf_res_spin_lock_kfunc(meta->func_id)) 13513 return -EFAULT; 13514 if (meta->func_id == special_kfunc_list[KF_bpf_res_spin_lock] || 13515 meta->func_id == special_kfunc_list[KF_bpf_res_spin_lock_irqsave]) 13516 flags |= PROCESS_SPIN_LOCK; 13517 if (meta->func_id == special_kfunc_list[KF_bpf_res_spin_lock_irqsave] || 13518 meta->func_id == special_kfunc_list[KF_bpf_res_spin_unlock_irqrestore]) 13519 flags |= PROCESS_LOCK_IRQ; 13520 ret = process_spin_lock(env, regno, flags); 13521 if (ret < 0) 13522 return ret; 13523 break; 13524 } 13525 } 13526 } 13527 13528 if (is_kfunc_release(meta) && !meta->release_regno) { 13529 verbose(env, "release kernel function %s expects refcounted PTR_TO_BTF_ID\n", 13530 func_name); 13531 return -EINVAL; 13532 } 13533 13534 return 0; 13535 } 13536 13537 static int fetch_kfunc_meta(struct bpf_verifier_env *env, 13538 struct bpf_insn *insn, 13539 struct bpf_kfunc_call_arg_meta *meta, 13540 const char **kfunc_name) 13541 { 13542 const struct btf_type *func, *func_proto; 13543 u32 func_id, *kfunc_flags; 13544 const char *func_name; 13545 struct btf *desc_btf; 13546 13547 if (kfunc_name) 13548 *kfunc_name = NULL; 13549 13550 if (!insn->imm) 13551 return -EINVAL; 13552 13553 desc_btf = find_kfunc_desc_btf(env, insn->off); 13554 if (IS_ERR(desc_btf)) 13555 return PTR_ERR(desc_btf); 13556 13557 func_id = insn->imm; 13558 func = btf_type_by_id(desc_btf, func_id); 13559 func_name = btf_name_by_offset(desc_btf, func->name_off); 13560 if (kfunc_name) 13561 *kfunc_name = func_name; 13562 func_proto = btf_type_by_id(desc_btf, func->type); 13563 13564 kfunc_flags = btf_kfunc_id_set_contains(desc_btf, func_id, env->prog); 13565 if (!kfunc_flags) { 13566 return -EACCES; 13567 } 13568 13569 memset(meta, 0, sizeof(*meta)); 13570 meta->btf = desc_btf; 13571 meta->func_id = func_id; 13572 meta->kfunc_flags = *kfunc_flags; 13573 meta->func_proto = func_proto; 13574 meta->func_name = func_name; 13575 13576 return 0; 13577 } 13578 13579 /* check special kfuncs and return: 13580 * 1 - not fall-through to 'else' branch, continue verification 13581 * 0 - fall-through to 'else' branch 13582 * < 0 - not fall-through to 'else' branch, return error 13583 */ 13584 static int check_special_kfunc(struct bpf_verifier_env *env, struct bpf_kfunc_call_arg_meta *meta, 13585 struct bpf_reg_state *regs, struct bpf_insn_aux_data *insn_aux, 13586 const struct btf_type *ptr_type, struct btf *desc_btf) 13587 { 13588 const struct btf_type *ret_t; 13589 int err = 0; 13590 13591 if (meta->btf != btf_vmlinux) 13592 return 0; 13593 13594 if (meta->func_id == special_kfunc_list[KF_bpf_obj_new_impl] || 13595 meta->func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl]) { 13596 struct btf_struct_meta *struct_meta; 13597 struct btf *ret_btf; 13598 u32 ret_btf_id; 13599 13600 if (meta->func_id == special_kfunc_list[KF_bpf_obj_new_impl] && !bpf_global_ma_set) 13601 return -ENOMEM; 13602 13603 if (((u64)(u32)meta->arg_constant.value) != meta->arg_constant.value) { 13604 verbose(env, "local type ID argument must be in range [0, U32_MAX]\n"); 13605 return -EINVAL; 13606 } 13607 13608 ret_btf = env->prog->aux->btf; 13609 ret_btf_id = meta->arg_constant.value; 13610 13611 /* This may be NULL due to user not supplying a BTF */ 13612 if (!ret_btf) { 13613 verbose(env, "bpf_obj_new/bpf_percpu_obj_new requires prog BTF\n"); 13614 return -EINVAL; 13615 } 13616 13617 ret_t = btf_type_by_id(ret_btf, ret_btf_id); 13618 if (!ret_t || !__btf_type_is_struct(ret_t)) { 13619 verbose(env, "bpf_obj_new/bpf_percpu_obj_new type ID argument must be of a struct\n"); 13620 return -EINVAL; 13621 } 13622 13623 if (meta->func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl]) { 13624 if (ret_t->size > BPF_GLOBAL_PERCPU_MA_MAX_SIZE) { 13625 verbose(env, "bpf_percpu_obj_new type size (%d) is greater than %d\n", 13626 ret_t->size, BPF_GLOBAL_PERCPU_MA_MAX_SIZE); 13627 return -EINVAL; 13628 } 13629 13630 if (!bpf_global_percpu_ma_set) { 13631 mutex_lock(&bpf_percpu_ma_lock); 13632 if (!bpf_global_percpu_ma_set) { 13633 /* Charge memory allocated with bpf_global_percpu_ma to 13634 * root memcg. The obj_cgroup for root memcg is NULL. 13635 */ 13636 err = bpf_mem_alloc_percpu_init(&bpf_global_percpu_ma, NULL); 13637 if (!err) 13638 bpf_global_percpu_ma_set = true; 13639 } 13640 mutex_unlock(&bpf_percpu_ma_lock); 13641 if (err) 13642 return err; 13643 } 13644 13645 mutex_lock(&bpf_percpu_ma_lock); 13646 err = bpf_mem_alloc_percpu_unit_init(&bpf_global_percpu_ma, ret_t->size); 13647 mutex_unlock(&bpf_percpu_ma_lock); 13648 if (err) 13649 return err; 13650 } 13651 13652 struct_meta = btf_find_struct_meta(ret_btf, ret_btf_id); 13653 if (meta->func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl]) { 13654 if (!__btf_type_is_scalar_struct(env, ret_btf, ret_t, 0)) { 13655 verbose(env, "bpf_percpu_obj_new type ID argument must be of a struct of scalars\n"); 13656 return -EINVAL; 13657 } 13658 13659 if (struct_meta) { 13660 verbose(env, "bpf_percpu_obj_new type ID argument must not contain special fields\n"); 13661 return -EINVAL; 13662 } 13663 } 13664 13665 mark_reg_known_zero(env, regs, BPF_REG_0); 13666 regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC; 13667 regs[BPF_REG_0].btf = ret_btf; 13668 regs[BPF_REG_0].btf_id = ret_btf_id; 13669 if (meta->func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl]) 13670 regs[BPF_REG_0].type |= MEM_PERCPU; 13671 13672 insn_aux->obj_new_size = ret_t->size; 13673 insn_aux->kptr_struct_meta = struct_meta; 13674 } else if (meta->func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl]) { 13675 mark_reg_known_zero(env, regs, BPF_REG_0); 13676 regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC; 13677 regs[BPF_REG_0].btf = meta->arg_btf; 13678 regs[BPF_REG_0].btf_id = meta->arg_btf_id; 13679 13680 insn_aux->kptr_struct_meta = 13681 btf_find_struct_meta(meta->arg_btf, 13682 meta->arg_btf_id); 13683 } else if (is_list_node_type(ptr_type)) { 13684 struct btf_field *field = meta->arg_list_head.field; 13685 13686 mark_reg_graph_node(regs, BPF_REG_0, &field->graph_root); 13687 } else if (is_rbtree_node_type(ptr_type)) { 13688 struct btf_field *field = meta->arg_rbtree_root.field; 13689 13690 mark_reg_graph_node(regs, BPF_REG_0, &field->graph_root); 13691 } else if (meta->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx]) { 13692 mark_reg_known_zero(env, regs, BPF_REG_0); 13693 regs[BPF_REG_0].type = PTR_TO_BTF_ID | PTR_TRUSTED; 13694 regs[BPF_REG_0].btf = desc_btf; 13695 regs[BPF_REG_0].btf_id = meta->ret_btf_id; 13696 } else if (meta->func_id == special_kfunc_list[KF_bpf_rdonly_cast]) { 13697 ret_t = btf_type_by_id(desc_btf, meta->arg_constant.value); 13698 if (!ret_t) { 13699 verbose(env, "Unknown type ID %lld passed to kfunc bpf_rdonly_cast\n", 13700 meta->arg_constant.value); 13701 return -EINVAL; 13702 } else if (btf_type_is_struct(ret_t)) { 13703 mark_reg_known_zero(env, regs, BPF_REG_0); 13704 regs[BPF_REG_0].type = PTR_TO_BTF_ID | PTR_UNTRUSTED; 13705 regs[BPF_REG_0].btf = desc_btf; 13706 regs[BPF_REG_0].btf_id = meta->arg_constant.value; 13707 } else if (btf_type_is_void(ret_t)) { 13708 mark_reg_known_zero(env, regs, BPF_REG_0); 13709 regs[BPF_REG_0].type = PTR_TO_MEM | MEM_RDONLY | PTR_UNTRUSTED; 13710 regs[BPF_REG_0].mem_size = 0; 13711 } else { 13712 verbose(env, 13713 "kfunc bpf_rdonly_cast type ID argument must be of a struct or void\n"); 13714 return -EINVAL; 13715 } 13716 } else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_slice] || 13717 meta->func_id == special_kfunc_list[KF_bpf_dynptr_slice_rdwr]) { 13718 enum bpf_type_flag type_flag = get_dynptr_type_flag(meta->initialized_dynptr.type); 13719 13720 mark_reg_known_zero(env, regs, BPF_REG_0); 13721 13722 if (!meta->arg_constant.found) { 13723 verifier_bug(env, "bpf_dynptr_slice(_rdwr) no constant size"); 13724 return -EFAULT; 13725 } 13726 13727 regs[BPF_REG_0].mem_size = meta->arg_constant.value; 13728 13729 /* PTR_MAYBE_NULL will be added when is_kfunc_ret_null is checked */ 13730 regs[BPF_REG_0].type = PTR_TO_MEM | type_flag; 13731 13732 if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_slice]) { 13733 regs[BPF_REG_0].type |= MEM_RDONLY; 13734 } else { 13735 /* this will set env->seen_direct_write to true */ 13736 if (!may_access_direct_pkt_data(env, NULL, BPF_WRITE)) { 13737 verbose(env, "the prog does not allow writes to packet data\n"); 13738 return -EINVAL; 13739 } 13740 } 13741 13742 if (!meta->initialized_dynptr.id) { 13743 verifier_bug(env, "no dynptr id"); 13744 return -EFAULT; 13745 } 13746 regs[BPF_REG_0].dynptr_id = meta->initialized_dynptr.id; 13747 13748 /* we don't need to set BPF_REG_0's ref obj id 13749 * because packet slices are not refcounted (see 13750 * dynptr_type_refcounted) 13751 */ 13752 } else { 13753 return 0; 13754 } 13755 13756 return 1; 13757 } 13758 13759 static int check_return_code(struct bpf_verifier_env *env, int regno, const char *reg_name); 13760 13761 static int check_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn, 13762 int *insn_idx_p) 13763 { 13764 bool sleepable, rcu_lock, rcu_unlock, preempt_disable, preempt_enable; 13765 u32 i, nargs, ptr_type_id, release_ref_obj_id; 13766 struct bpf_reg_state *regs = cur_regs(env); 13767 const char *func_name, *ptr_type_name; 13768 const struct btf_type *t, *ptr_type; 13769 struct bpf_kfunc_call_arg_meta meta; 13770 struct bpf_insn_aux_data *insn_aux; 13771 int err, insn_idx = *insn_idx_p; 13772 const struct btf_param *args; 13773 struct btf *desc_btf; 13774 13775 /* skip for now, but return error when we find this in fixup_kfunc_call */ 13776 if (!insn->imm) 13777 return 0; 13778 13779 err = fetch_kfunc_meta(env, insn, &meta, &func_name); 13780 if (err == -EACCES && func_name) 13781 verbose(env, "calling kernel function %s is not allowed\n", func_name); 13782 if (err) 13783 return err; 13784 desc_btf = meta.btf; 13785 insn_aux = &env->insn_aux_data[insn_idx]; 13786 13787 insn_aux->is_iter_next = is_iter_next_kfunc(&meta); 13788 13789 if (!insn->off && 13790 (insn->imm == special_kfunc_list[KF_bpf_res_spin_lock] || 13791 insn->imm == special_kfunc_list[KF_bpf_res_spin_lock_irqsave])) { 13792 struct bpf_verifier_state *branch; 13793 struct bpf_reg_state *regs; 13794 13795 branch = push_stack(env, env->insn_idx + 1, env->insn_idx, false); 13796 if (!branch) { 13797 verbose(env, "failed to push state for failed lock acquisition\n"); 13798 return -ENOMEM; 13799 } 13800 13801 regs = branch->frame[branch->curframe]->regs; 13802 13803 /* Clear r0-r5 registers in forked state */ 13804 for (i = 0; i < CALLER_SAVED_REGS; i++) 13805 mark_reg_not_init(env, regs, caller_saved[i]); 13806 13807 mark_reg_unknown(env, regs, BPF_REG_0); 13808 err = __mark_reg_s32_range(env, regs, BPF_REG_0, -MAX_ERRNO, -1); 13809 if (err) { 13810 verbose(env, "failed to mark s32 range for retval in forked state for lock\n"); 13811 return err; 13812 } 13813 __mark_btf_func_reg_size(env, regs, BPF_REG_0, sizeof(u32)); 13814 } else if (!insn->off && insn->imm == special_kfunc_list[KF___bpf_trap]) { 13815 verbose(env, "unexpected __bpf_trap() due to uninitialized variable?\n"); 13816 return -EFAULT; 13817 } 13818 13819 if (is_kfunc_destructive(&meta) && !capable(CAP_SYS_BOOT)) { 13820 verbose(env, "destructive kfunc calls require CAP_SYS_BOOT capability\n"); 13821 return -EACCES; 13822 } 13823 13824 sleepable = is_kfunc_sleepable(&meta); 13825 if (sleepable && !in_sleepable(env)) { 13826 verbose(env, "program must be sleepable to call sleepable kfunc %s\n", func_name); 13827 return -EACCES; 13828 } 13829 13830 /* Check the arguments */ 13831 err = check_kfunc_args(env, &meta, insn_idx); 13832 if (err < 0) 13833 return err; 13834 13835 if (meta.func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) { 13836 err = push_callback_call(env, insn, insn_idx, meta.subprogno, 13837 set_rbtree_add_callback_state); 13838 if (err) { 13839 verbose(env, "kfunc %s#%d failed callback verification\n", 13840 func_name, meta.func_id); 13841 return err; 13842 } 13843 } 13844 13845 if (meta.func_id == special_kfunc_list[KF_bpf_session_cookie]) { 13846 meta.r0_size = sizeof(u64); 13847 meta.r0_rdonly = false; 13848 } 13849 13850 if (is_bpf_wq_set_callback_impl_kfunc(meta.func_id)) { 13851 err = push_callback_call(env, insn, insn_idx, meta.subprogno, 13852 set_timer_callback_state); 13853 if (err) { 13854 verbose(env, "kfunc %s#%d failed callback verification\n", 13855 func_name, meta.func_id); 13856 return err; 13857 } 13858 } 13859 13860 rcu_lock = is_kfunc_bpf_rcu_read_lock(&meta); 13861 rcu_unlock = is_kfunc_bpf_rcu_read_unlock(&meta); 13862 13863 preempt_disable = is_kfunc_bpf_preempt_disable(&meta); 13864 preempt_enable = is_kfunc_bpf_preempt_enable(&meta); 13865 13866 if (env->cur_state->active_rcu_lock) { 13867 struct bpf_func_state *state; 13868 struct bpf_reg_state *reg; 13869 u32 clear_mask = (1 << STACK_SPILL) | (1 << STACK_ITER); 13870 13871 if (in_rbtree_lock_required_cb(env) && (rcu_lock || rcu_unlock)) { 13872 verbose(env, "Calling bpf_rcu_read_{lock,unlock} in unnecessary rbtree callback\n"); 13873 return -EACCES; 13874 } 13875 13876 if (rcu_lock) { 13877 verbose(env, "nested rcu read lock (kernel function %s)\n", func_name); 13878 return -EINVAL; 13879 } else if (rcu_unlock) { 13880 bpf_for_each_reg_in_vstate_mask(env->cur_state, state, reg, clear_mask, ({ 13881 if (reg->type & MEM_RCU) { 13882 reg->type &= ~(MEM_RCU | PTR_MAYBE_NULL); 13883 reg->type |= PTR_UNTRUSTED; 13884 } 13885 })); 13886 env->cur_state->active_rcu_lock = false; 13887 } else if (sleepable) { 13888 verbose(env, "kernel func %s is sleepable within rcu_read_lock region\n", func_name); 13889 return -EACCES; 13890 } 13891 } else if (rcu_lock) { 13892 env->cur_state->active_rcu_lock = true; 13893 } else if (rcu_unlock) { 13894 verbose(env, "unmatched rcu read unlock (kernel function %s)\n", func_name); 13895 return -EINVAL; 13896 } 13897 13898 if (env->cur_state->active_preempt_locks) { 13899 if (preempt_disable) { 13900 env->cur_state->active_preempt_locks++; 13901 } else if (preempt_enable) { 13902 env->cur_state->active_preempt_locks--; 13903 } else if (sleepable) { 13904 verbose(env, "kernel func %s is sleepable within non-preemptible region\n", func_name); 13905 return -EACCES; 13906 } 13907 } else if (preempt_disable) { 13908 env->cur_state->active_preempt_locks++; 13909 } else if (preempt_enable) { 13910 verbose(env, "unmatched attempt to enable preemption (kernel function %s)\n", func_name); 13911 return -EINVAL; 13912 } 13913 13914 if (env->cur_state->active_irq_id && sleepable) { 13915 verbose(env, "kernel func %s is sleepable within IRQ-disabled region\n", func_name); 13916 return -EACCES; 13917 } 13918 13919 /* In case of release function, we get register number of refcounted 13920 * PTR_TO_BTF_ID in bpf_kfunc_arg_meta, do the release now. 13921 */ 13922 if (meta.release_regno) { 13923 err = release_reference(env, regs[meta.release_regno].ref_obj_id); 13924 if (err) { 13925 verbose(env, "kfunc %s#%d reference has not been acquired before\n", 13926 func_name, meta.func_id); 13927 return err; 13928 } 13929 } 13930 13931 if (meta.func_id == special_kfunc_list[KF_bpf_list_push_front_impl] || 13932 meta.func_id == special_kfunc_list[KF_bpf_list_push_back_impl] || 13933 meta.func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) { 13934 release_ref_obj_id = regs[BPF_REG_2].ref_obj_id; 13935 insn_aux->insert_off = regs[BPF_REG_2].off; 13936 insn_aux->kptr_struct_meta = btf_find_struct_meta(meta.arg_btf, meta.arg_btf_id); 13937 err = ref_convert_owning_non_owning(env, release_ref_obj_id); 13938 if (err) { 13939 verbose(env, "kfunc %s#%d conversion of owning ref to non-owning failed\n", 13940 func_name, meta.func_id); 13941 return err; 13942 } 13943 13944 err = release_reference(env, release_ref_obj_id); 13945 if (err) { 13946 verbose(env, "kfunc %s#%d reference has not been acquired before\n", 13947 func_name, meta.func_id); 13948 return err; 13949 } 13950 } 13951 13952 if (meta.func_id == special_kfunc_list[KF_bpf_throw]) { 13953 if (!bpf_jit_supports_exceptions()) { 13954 verbose(env, "JIT does not support calling kfunc %s#%d\n", 13955 func_name, meta.func_id); 13956 return -ENOTSUPP; 13957 } 13958 env->seen_exception = true; 13959 13960 /* In the case of the default callback, the cookie value passed 13961 * to bpf_throw becomes the return value of the program. 13962 */ 13963 if (!env->exception_callback_subprog) { 13964 err = check_return_code(env, BPF_REG_1, "R1"); 13965 if (err < 0) 13966 return err; 13967 } 13968 } 13969 13970 for (i = 0; i < CALLER_SAVED_REGS; i++) 13971 mark_reg_not_init(env, regs, caller_saved[i]); 13972 13973 /* Check return type */ 13974 t = btf_type_skip_modifiers(desc_btf, meta.func_proto->type, NULL); 13975 13976 if (is_kfunc_acquire(&meta) && !btf_type_is_struct_ptr(meta.btf, t)) { 13977 /* Only exception is bpf_obj_new_impl */ 13978 if (meta.btf != btf_vmlinux || 13979 (meta.func_id != special_kfunc_list[KF_bpf_obj_new_impl] && 13980 meta.func_id != special_kfunc_list[KF_bpf_percpu_obj_new_impl] && 13981 meta.func_id != special_kfunc_list[KF_bpf_refcount_acquire_impl])) { 13982 verbose(env, "acquire kernel function does not return PTR_TO_BTF_ID\n"); 13983 return -EINVAL; 13984 } 13985 } 13986 13987 if (btf_type_is_scalar(t)) { 13988 mark_reg_unknown(env, regs, BPF_REG_0); 13989 if (meta.btf == btf_vmlinux && (meta.func_id == special_kfunc_list[KF_bpf_res_spin_lock] || 13990 meta.func_id == special_kfunc_list[KF_bpf_res_spin_lock_irqsave])) 13991 __mark_reg_const_zero(env, ®s[BPF_REG_0]); 13992 mark_btf_func_reg_size(env, BPF_REG_0, t->size); 13993 } else if (btf_type_is_ptr(t)) { 13994 ptr_type = btf_type_skip_modifiers(desc_btf, t->type, &ptr_type_id); 13995 err = check_special_kfunc(env, &meta, regs, insn_aux, ptr_type, desc_btf); 13996 if (err) { 13997 if (err < 0) 13998 return err; 13999 } else if (btf_type_is_void(ptr_type)) { 14000 /* kfunc returning 'void *' is equivalent to returning scalar */ 14001 mark_reg_unknown(env, regs, BPF_REG_0); 14002 } else if (!__btf_type_is_struct(ptr_type)) { 14003 if (!meta.r0_size) { 14004 __u32 sz; 14005 14006 if (!IS_ERR(btf_resolve_size(desc_btf, ptr_type, &sz))) { 14007 meta.r0_size = sz; 14008 meta.r0_rdonly = true; 14009 } 14010 } 14011 if (!meta.r0_size) { 14012 ptr_type_name = btf_name_by_offset(desc_btf, 14013 ptr_type->name_off); 14014 verbose(env, 14015 "kernel function %s returns pointer type %s %s is not supported\n", 14016 func_name, 14017 btf_type_str(ptr_type), 14018 ptr_type_name); 14019 return -EINVAL; 14020 } 14021 14022 mark_reg_known_zero(env, regs, BPF_REG_0); 14023 regs[BPF_REG_0].type = PTR_TO_MEM; 14024 regs[BPF_REG_0].mem_size = meta.r0_size; 14025 14026 if (meta.r0_rdonly) 14027 regs[BPF_REG_0].type |= MEM_RDONLY; 14028 14029 /* Ensures we don't access the memory after a release_reference() */ 14030 if (meta.ref_obj_id) 14031 regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id; 14032 } else { 14033 mark_reg_known_zero(env, regs, BPF_REG_0); 14034 regs[BPF_REG_0].btf = desc_btf; 14035 regs[BPF_REG_0].type = PTR_TO_BTF_ID; 14036 regs[BPF_REG_0].btf_id = ptr_type_id; 14037 14038 if (meta.func_id == special_kfunc_list[KF_bpf_get_kmem_cache]) 14039 regs[BPF_REG_0].type |= PTR_UNTRUSTED; 14040 14041 if (is_iter_next_kfunc(&meta)) { 14042 struct bpf_reg_state *cur_iter; 14043 14044 cur_iter = get_iter_from_state(env->cur_state, &meta); 14045 14046 if (cur_iter->type & MEM_RCU) /* KF_RCU_PROTECTED */ 14047 regs[BPF_REG_0].type |= MEM_RCU; 14048 else 14049 regs[BPF_REG_0].type |= PTR_TRUSTED; 14050 } 14051 } 14052 14053 if (is_kfunc_ret_null(&meta)) { 14054 regs[BPF_REG_0].type |= PTR_MAYBE_NULL; 14055 /* For mark_ptr_or_null_reg, see 93c230e3f5bd6 */ 14056 regs[BPF_REG_0].id = ++env->id_gen; 14057 } 14058 mark_btf_func_reg_size(env, BPF_REG_0, sizeof(void *)); 14059 if (is_kfunc_acquire(&meta)) { 14060 int id = acquire_reference(env, insn_idx); 14061 14062 if (id < 0) 14063 return id; 14064 if (is_kfunc_ret_null(&meta)) 14065 regs[BPF_REG_0].id = id; 14066 regs[BPF_REG_0].ref_obj_id = id; 14067 } else if (is_rbtree_node_type(ptr_type) || is_list_node_type(ptr_type)) { 14068 ref_set_non_owning(env, ®s[BPF_REG_0]); 14069 } 14070 14071 if (reg_may_point_to_spin_lock(®s[BPF_REG_0]) && !regs[BPF_REG_0].id) 14072 regs[BPF_REG_0].id = ++env->id_gen; 14073 } else if (btf_type_is_void(t)) { 14074 if (meta.btf == btf_vmlinux) { 14075 if (meta.func_id == special_kfunc_list[KF_bpf_obj_drop_impl] || 14076 meta.func_id == special_kfunc_list[KF_bpf_percpu_obj_drop_impl]) { 14077 insn_aux->kptr_struct_meta = 14078 btf_find_struct_meta(meta.arg_btf, 14079 meta.arg_btf_id); 14080 } 14081 } 14082 } 14083 14084 nargs = btf_type_vlen(meta.func_proto); 14085 args = (const struct btf_param *)(meta.func_proto + 1); 14086 for (i = 0; i < nargs; i++) { 14087 u32 regno = i + 1; 14088 14089 t = btf_type_skip_modifiers(desc_btf, args[i].type, NULL); 14090 if (btf_type_is_ptr(t)) 14091 mark_btf_func_reg_size(env, regno, sizeof(void *)); 14092 else 14093 /* scalar. ensured by btf_check_kfunc_arg_match() */ 14094 mark_btf_func_reg_size(env, regno, t->size); 14095 } 14096 14097 if (is_iter_next_kfunc(&meta)) { 14098 err = process_iter_next_call(env, insn_idx, &meta); 14099 if (err) 14100 return err; 14101 } 14102 14103 return 0; 14104 } 14105 14106 static bool check_reg_sane_offset(struct bpf_verifier_env *env, 14107 const struct bpf_reg_state *reg, 14108 enum bpf_reg_type type) 14109 { 14110 bool known = tnum_is_const(reg->var_off); 14111 s64 val = reg->var_off.value; 14112 s64 smin = reg->smin_value; 14113 14114 if (known && (val >= BPF_MAX_VAR_OFF || val <= -BPF_MAX_VAR_OFF)) { 14115 verbose(env, "math between %s pointer and %lld is not allowed\n", 14116 reg_type_str(env, type), val); 14117 return false; 14118 } 14119 14120 if (reg->off >= BPF_MAX_VAR_OFF || reg->off <= -BPF_MAX_VAR_OFF) { 14121 verbose(env, "%s pointer offset %d is not allowed\n", 14122 reg_type_str(env, type), reg->off); 14123 return false; 14124 } 14125 14126 if (smin == S64_MIN) { 14127 verbose(env, "math between %s pointer and register with unbounded min value is not allowed\n", 14128 reg_type_str(env, type)); 14129 return false; 14130 } 14131 14132 if (smin >= BPF_MAX_VAR_OFF || smin <= -BPF_MAX_VAR_OFF) { 14133 verbose(env, "value %lld makes %s pointer be out of bounds\n", 14134 smin, reg_type_str(env, type)); 14135 return false; 14136 } 14137 14138 return true; 14139 } 14140 14141 enum { 14142 REASON_BOUNDS = -1, 14143 REASON_TYPE = -2, 14144 REASON_PATHS = -3, 14145 REASON_LIMIT = -4, 14146 REASON_STACK = -5, 14147 }; 14148 14149 static int retrieve_ptr_limit(const struct bpf_reg_state *ptr_reg, 14150 u32 *alu_limit, bool mask_to_left) 14151 { 14152 u32 max = 0, ptr_limit = 0; 14153 14154 switch (ptr_reg->type) { 14155 case PTR_TO_STACK: 14156 /* Offset 0 is out-of-bounds, but acceptable start for the 14157 * left direction, see BPF_REG_FP. Also, unknown scalar 14158 * offset where we would need to deal with min/max bounds is 14159 * currently prohibited for unprivileged. 14160 */ 14161 max = MAX_BPF_STACK + mask_to_left; 14162 ptr_limit = -(ptr_reg->var_off.value + ptr_reg->off); 14163 break; 14164 case PTR_TO_MAP_VALUE: 14165 max = ptr_reg->map_ptr->value_size; 14166 ptr_limit = (mask_to_left ? 14167 ptr_reg->smin_value : 14168 ptr_reg->umax_value) + ptr_reg->off; 14169 break; 14170 default: 14171 return REASON_TYPE; 14172 } 14173 14174 if (ptr_limit >= max) 14175 return REASON_LIMIT; 14176 *alu_limit = ptr_limit; 14177 return 0; 14178 } 14179 14180 static bool can_skip_alu_sanitation(const struct bpf_verifier_env *env, 14181 const struct bpf_insn *insn) 14182 { 14183 return env->bypass_spec_v1 || 14184 BPF_SRC(insn->code) == BPF_K || 14185 cur_aux(env)->nospec; 14186 } 14187 14188 static int update_alu_sanitation_state(struct bpf_insn_aux_data *aux, 14189 u32 alu_state, u32 alu_limit) 14190 { 14191 /* If we arrived here from different branches with different 14192 * state or limits to sanitize, then this won't work. 14193 */ 14194 if (aux->alu_state && 14195 (aux->alu_state != alu_state || 14196 aux->alu_limit != alu_limit)) 14197 return REASON_PATHS; 14198 14199 /* Corresponding fixup done in do_misc_fixups(). */ 14200 aux->alu_state = alu_state; 14201 aux->alu_limit = alu_limit; 14202 return 0; 14203 } 14204 14205 static int sanitize_val_alu(struct bpf_verifier_env *env, 14206 struct bpf_insn *insn) 14207 { 14208 struct bpf_insn_aux_data *aux = cur_aux(env); 14209 14210 if (can_skip_alu_sanitation(env, insn)) 14211 return 0; 14212 14213 return update_alu_sanitation_state(aux, BPF_ALU_NON_POINTER, 0); 14214 } 14215 14216 static bool sanitize_needed(u8 opcode) 14217 { 14218 return opcode == BPF_ADD || opcode == BPF_SUB; 14219 } 14220 14221 struct bpf_sanitize_info { 14222 struct bpf_insn_aux_data aux; 14223 bool mask_to_left; 14224 }; 14225 14226 static struct bpf_verifier_state * 14227 sanitize_speculative_path(struct bpf_verifier_env *env, 14228 const struct bpf_insn *insn, 14229 u32 next_idx, u32 curr_idx) 14230 { 14231 struct bpf_verifier_state *branch; 14232 struct bpf_reg_state *regs; 14233 14234 branch = push_stack(env, next_idx, curr_idx, true); 14235 if (branch && insn) { 14236 regs = branch->frame[branch->curframe]->regs; 14237 if (BPF_SRC(insn->code) == BPF_K) { 14238 mark_reg_unknown(env, regs, insn->dst_reg); 14239 } else if (BPF_SRC(insn->code) == BPF_X) { 14240 mark_reg_unknown(env, regs, insn->dst_reg); 14241 mark_reg_unknown(env, regs, insn->src_reg); 14242 } 14243 } 14244 return branch; 14245 } 14246 14247 static int sanitize_ptr_alu(struct bpf_verifier_env *env, 14248 struct bpf_insn *insn, 14249 const struct bpf_reg_state *ptr_reg, 14250 const struct bpf_reg_state *off_reg, 14251 struct bpf_reg_state *dst_reg, 14252 struct bpf_sanitize_info *info, 14253 const bool commit_window) 14254 { 14255 struct bpf_insn_aux_data *aux = commit_window ? cur_aux(env) : &info->aux; 14256 struct bpf_verifier_state *vstate = env->cur_state; 14257 bool off_is_imm = tnum_is_const(off_reg->var_off); 14258 bool off_is_neg = off_reg->smin_value < 0; 14259 bool ptr_is_dst_reg = ptr_reg == dst_reg; 14260 u8 opcode = BPF_OP(insn->code); 14261 u32 alu_state, alu_limit; 14262 struct bpf_reg_state tmp; 14263 bool ret; 14264 int err; 14265 14266 if (can_skip_alu_sanitation(env, insn)) 14267 return 0; 14268 14269 /* We already marked aux for masking from non-speculative 14270 * paths, thus we got here in the first place. We only care 14271 * to explore bad access from here. 14272 */ 14273 if (vstate->speculative) 14274 goto do_sim; 14275 14276 if (!commit_window) { 14277 if (!tnum_is_const(off_reg->var_off) && 14278 (off_reg->smin_value < 0) != (off_reg->smax_value < 0)) 14279 return REASON_BOUNDS; 14280 14281 info->mask_to_left = (opcode == BPF_ADD && off_is_neg) || 14282 (opcode == BPF_SUB && !off_is_neg); 14283 } 14284 14285 err = retrieve_ptr_limit(ptr_reg, &alu_limit, info->mask_to_left); 14286 if (err < 0) 14287 return err; 14288 14289 if (commit_window) { 14290 /* In commit phase we narrow the masking window based on 14291 * the observed pointer move after the simulated operation. 14292 */ 14293 alu_state = info->aux.alu_state; 14294 alu_limit = abs(info->aux.alu_limit - alu_limit); 14295 } else { 14296 alu_state = off_is_neg ? BPF_ALU_NEG_VALUE : 0; 14297 alu_state |= off_is_imm ? BPF_ALU_IMMEDIATE : 0; 14298 alu_state |= ptr_is_dst_reg ? 14299 BPF_ALU_SANITIZE_SRC : BPF_ALU_SANITIZE_DST; 14300 14301 /* Limit pruning on unknown scalars to enable deep search for 14302 * potential masking differences from other program paths. 14303 */ 14304 if (!off_is_imm) 14305 env->explore_alu_limits = true; 14306 } 14307 14308 err = update_alu_sanitation_state(aux, alu_state, alu_limit); 14309 if (err < 0) 14310 return err; 14311 do_sim: 14312 /* If we're in commit phase, we're done here given we already 14313 * pushed the truncated dst_reg into the speculative verification 14314 * stack. 14315 * 14316 * Also, when register is a known constant, we rewrite register-based 14317 * operation to immediate-based, and thus do not need masking (and as 14318 * a consequence, do not need to simulate the zero-truncation either). 14319 */ 14320 if (commit_window || off_is_imm) 14321 return 0; 14322 14323 /* Simulate and find potential out-of-bounds access under 14324 * speculative execution from truncation as a result of 14325 * masking when off was not within expected range. If off 14326 * sits in dst, then we temporarily need to move ptr there 14327 * to simulate dst (== 0) +/-= ptr. Needed, for example, 14328 * for cases where we use K-based arithmetic in one direction 14329 * and truncated reg-based in the other in order to explore 14330 * bad access. 14331 */ 14332 if (!ptr_is_dst_reg) { 14333 tmp = *dst_reg; 14334 copy_register_state(dst_reg, ptr_reg); 14335 } 14336 ret = sanitize_speculative_path(env, NULL, env->insn_idx + 1, 14337 env->insn_idx); 14338 if (!ptr_is_dst_reg && ret) 14339 *dst_reg = tmp; 14340 return !ret ? REASON_STACK : 0; 14341 } 14342 14343 static void sanitize_mark_insn_seen(struct bpf_verifier_env *env) 14344 { 14345 struct bpf_verifier_state *vstate = env->cur_state; 14346 14347 /* If we simulate paths under speculation, we don't update the 14348 * insn as 'seen' such that when we verify unreachable paths in 14349 * the non-speculative domain, sanitize_dead_code() can still 14350 * rewrite/sanitize them. 14351 */ 14352 if (!vstate->speculative) 14353 env->insn_aux_data[env->insn_idx].seen = env->pass_cnt; 14354 } 14355 14356 static int sanitize_err(struct bpf_verifier_env *env, 14357 const struct bpf_insn *insn, int reason, 14358 const struct bpf_reg_state *off_reg, 14359 const struct bpf_reg_state *dst_reg) 14360 { 14361 static const char *err = "pointer arithmetic with it prohibited for !root"; 14362 const char *op = BPF_OP(insn->code) == BPF_ADD ? "add" : "sub"; 14363 u32 dst = insn->dst_reg, src = insn->src_reg; 14364 14365 switch (reason) { 14366 case REASON_BOUNDS: 14367 verbose(env, "R%d has unknown scalar with mixed signed bounds, %s\n", 14368 off_reg == dst_reg ? dst : src, err); 14369 break; 14370 case REASON_TYPE: 14371 verbose(env, "R%d has pointer with unsupported alu operation, %s\n", 14372 off_reg == dst_reg ? src : dst, err); 14373 break; 14374 case REASON_PATHS: 14375 verbose(env, "R%d tried to %s from different maps, paths or scalars, %s\n", 14376 dst, op, err); 14377 break; 14378 case REASON_LIMIT: 14379 verbose(env, "R%d tried to %s beyond pointer bounds, %s\n", 14380 dst, op, err); 14381 break; 14382 case REASON_STACK: 14383 verbose(env, "R%d could not be pushed for speculative verification, %s\n", 14384 dst, err); 14385 return -ENOMEM; 14386 default: 14387 verifier_bug(env, "unknown reason (%d)", reason); 14388 break; 14389 } 14390 14391 return -EACCES; 14392 } 14393 14394 /* check that stack access falls within stack limits and that 'reg' doesn't 14395 * have a variable offset. 14396 * 14397 * Variable offset is prohibited for unprivileged mode for simplicity since it 14398 * requires corresponding support in Spectre masking for stack ALU. See also 14399 * retrieve_ptr_limit(). 14400 * 14401 * 14402 * 'off' includes 'reg->off'. 14403 */ 14404 static int check_stack_access_for_ptr_arithmetic( 14405 struct bpf_verifier_env *env, 14406 int regno, 14407 const struct bpf_reg_state *reg, 14408 int off) 14409 { 14410 if (!tnum_is_const(reg->var_off)) { 14411 char tn_buf[48]; 14412 14413 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 14414 verbose(env, "R%d variable stack access prohibited for !root, var_off=%s off=%d\n", 14415 regno, tn_buf, off); 14416 return -EACCES; 14417 } 14418 14419 if (off >= 0 || off < -MAX_BPF_STACK) { 14420 verbose(env, "R%d stack pointer arithmetic goes out of range, " 14421 "prohibited for !root; off=%d\n", regno, off); 14422 return -EACCES; 14423 } 14424 14425 return 0; 14426 } 14427 14428 static int sanitize_check_bounds(struct bpf_verifier_env *env, 14429 const struct bpf_insn *insn, 14430 const struct bpf_reg_state *dst_reg) 14431 { 14432 u32 dst = insn->dst_reg; 14433 14434 /* For unprivileged we require that resulting offset must be in bounds 14435 * in order to be able to sanitize access later on. 14436 */ 14437 if (env->bypass_spec_v1) 14438 return 0; 14439 14440 switch (dst_reg->type) { 14441 case PTR_TO_STACK: 14442 if (check_stack_access_for_ptr_arithmetic(env, dst, dst_reg, 14443 dst_reg->off + dst_reg->var_off.value)) 14444 return -EACCES; 14445 break; 14446 case PTR_TO_MAP_VALUE: 14447 if (check_map_access(env, dst, dst_reg->off, 1, false, ACCESS_HELPER)) { 14448 verbose(env, "R%d pointer arithmetic of map value goes out of range, " 14449 "prohibited for !root\n", dst); 14450 return -EACCES; 14451 } 14452 break; 14453 default: 14454 return -EOPNOTSUPP; 14455 } 14456 14457 return 0; 14458 } 14459 14460 /* Handles arithmetic on a pointer and a scalar: computes new min/max and var_off. 14461 * Caller should also handle BPF_MOV case separately. 14462 * If we return -EACCES, caller may want to try again treating pointer as a 14463 * scalar. So we only emit a diagnostic if !env->allow_ptr_leaks. 14464 */ 14465 static int adjust_ptr_min_max_vals(struct bpf_verifier_env *env, 14466 struct bpf_insn *insn, 14467 const struct bpf_reg_state *ptr_reg, 14468 const struct bpf_reg_state *off_reg) 14469 { 14470 struct bpf_verifier_state *vstate = env->cur_state; 14471 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 14472 struct bpf_reg_state *regs = state->regs, *dst_reg; 14473 bool known = tnum_is_const(off_reg->var_off); 14474 s64 smin_val = off_reg->smin_value, smax_val = off_reg->smax_value, 14475 smin_ptr = ptr_reg->smin_value, smax_ptr = ptr_reg->smax_value; 14476 u64 umin_val = off_reg->umin_value, umax_val = off_reg->umax_value, 14477 umin_ptr = ptr_reg->umin_value, umax_ptr = ptr_reg->umax_value; 14478 struct bpf_sanitize_info info = {}; 14479 u8 opcode = BPF_OP(insn->code); 14480 u32 dst = insn->dst_reg; 14481 int ret, bounds_ret; 14482 14483 dst_reg = ®s[dst]; 14484 14485 if ((known && (smin_val != smax_val || umin_val != umax_val)) || 14486 smin_val > smax_val || umin_val > umax_val) { 14487 /* Taint dst register if offset had invalid bounds derived from 14488 * e.g. dead branches. 14489 */ 14490 __mark_reg_unknown(env, dst_reg); 14491 return 0; 14492 } 14493 14494 if (BPF_CLASS(insn->code) != BPF_ALU64) { 14495 /* 32-bit ALU ops on pointers produce (meaningless) scalars */ 14496 if (opcode == BPF_SUB && env->allow_ptr_leaks) { 14497 __mark_reg_unknown(env, dst_reg); 14498 return 0; 14499 } 14500 14501 verbose(env, 14502 "R%d 32-bit pointer arithmetic prohibited\n", 14503 dst); 14504 return -EACCES; 14505 } 14506 14507 if (ptr_reg->type & PTR_MAYBE_NULL) { 14508 verbose(env, "R%d pointer arithmetic on %s prohibited, null-check it first\n", 14509 dst, reg_type_str(env, ptr_reg->type)); 14510 return -EACCES; 14511 } 14512 14513 /* 14514 * Accesses to untrusted PTR_TO_MEM are done through probe 14515 * instructions, hence no need to track offsets. 14516 */ 14517 if (base_type(ptr_reg->type) == PTR_TO_MEM && (ptr_reg->type & PTR_UNTRUSTED)) 14518 return 0; 14519 14520 switch (base_type(ptr_reg->type)) { 14521 case PTR_TO_CTX: 14522 case PTR_TO_MAP_VALUE: 14523 case PTR_TO_MAP_KEY: 14524 case PTR_TO_STACK: 14525 case PTR_TO_PACKET_META: 14526 case PTR_TO_PACKET: 14527 case PTR_TO_TP_BUFFER: 14528 case PTR_TO_BTF_ID: 14529 case PTR_TO_MEM: 14530 case PTR_TO_BUF: 14531 case PTR_TO_FUNC: 14532 case CONST_PTR_TO_DYNPTR: 14533 break; 14534 case PTR_TO_FLOW_KEYS: 14535 if (known) 14536 break; 14537 fallthrough; 14538 case CONST_PTR_TO_MAP: 14539 /* smin_val represents the known value */ 14540 if (known && smin_val == 0 && opcode == BPF_ADD) 14541 break; 14542 fallthrough; 14543 default: 14544 verbose(env, "R%d pointer arithmetic on %s prohibited\n", 14545 dst, reg_type_str(env, ptr_reg->type)); 14546 return -EACCES; 14547 } 14548 14549 /* In case of 'scalar += pointer', dst_reg inherits pointer type and id. 14550 * The id may be overwritten later if we create a new variable offset. 14551 */ 14552 dst_reg->type = ptr_reg->type; 14553 dst_reg->id = ptr_reg->id; 14554 14555 if (!check_reg_sane_offset(env, off_reg, ptr_reg->type) || 14556 !check_reg_sane_offset(env, ptr_reg, ptr_reg->type)) 14557 return -EINVAL; 14558 14559 /* pointer types do not carry 32-bit bounds at the moment. */ 14560 __mark_reg32_unbounded(dst_reg); 14561 14562 if (sanitize_needed(opcode)) { 14563 ret = sanitize_ptr_alu(env, insn, ptr_reg, off_reg, dst_reg, 14564 &info, false); 14565 if (ret < 0) 14566 return sanitize_err(env, insn, ret, off_reg, dst_reg); 14567 } 14568 14569 switch (opcode) { 14570 case BPF_ADD: 14571 /* We can take a fixed offset as long as it doesn't overflow 14572 * the s32 'off' field 14573 */ 14574 if (known && (ptr_reg->off + smin_val == 14575 (s64)(s32)(ptr_reg->off + smin_val))) { 14576 /* pointer += K. Accumulate it into fixed offset */ 14577 dst_reg->smin_value = smin_ptr; 14578 dst_reg->smax_value = smax_ptr; 14579 dst_reg->umin_value = umin_ptr; 14580 dst_reg->umax_value = umax_ptr; 14581 dst_reg->var_off = ptr_reg->var_off; 14582 dst_reg->off = ptr_reg->off + smin_val; 14583 dst_reg->raw = ptr_reg->raw; 14584 break; 14585 } 14586 /* A new variable offset is created. Note that off_reg->off 14587 * == 0, since it's a scalar. 14588 * dst_reg gets the pointer type and since some positive 14589 * integer value was added to the pointer, give it a new 'id' 14590 * if it's a PTR_TO_PACKET. 14591 * this creates a new 'base' pointer, off_reg (variable) gets 14592 * added into the variable offset, and we copy the fixed offset 14593 * from ptr_reg. 14594 */ 14595 if (check_add_overflow(smin_ptr, smin_val, &dst_reg->smin_value) || 14596 check_add_overflow(smax_ptr, smax_val, &dst_reg->smax_value)) { 14597 dst_reg->smin_value = S64_MIN; 14598 dst_reg->smax_value = S64_MAX; 14599 } 14600 if (check_add_overflow(umin_ptr, umin_val, &dst_reg->umin_value) || 14601 check_add_overflow(umax_ptr, umax_val, &dst_reg->umax_value)) { 14602 dst_reg->umin_value = 0; 14603 dst_reg->umax_value = U64_MAX; 14604 } 14605 dst_reg->var_off = tnum_add(ptr_reg->var_off, off_reg->var_off); 14606 dst_reg->off = ptr_reg->off; 14607 dst_reg->raw = ptr_reg->raw; 14608 if (reg_is_pkt_pointer(ptr_reg)) { 14609 dst_reg->id = ++env->id_gen; 14610 /* something was added to pkt_ptr, set range to zero */ 14611 memset(&dst_reg->raw, 0, sizeof(dst_reg->raw)); 14612 } 14613 break; 14614 case BPF_SUB: 14615 if (dst_reg == off_reg) { 14616 /* scalar -= pointer. Creates an unknown scalar */ 14617 verbose(env, "R%d tried to subtract pointer from scalar\n", 14618 dst); 14619 return -EACCES; 14620 } 14621 /* We don't allow subtraction from FP, because (according to 14622 * test_verifier.c test "invalid fp arithmetic", JITs might not 14623 * be able to deal with it. 14624 */ 14625 if (ptr_reg->type == PTR_TO_STACK) { 14626 verbose(env, "R%d subtraction from stack pointer prohibited\n", 14627 dst); 14628 return -EACCES; 14629 } 14630 if (known && (ptr_reg->off - smin_val == 14631 (s64)(s32)(ptr_reg->off - smin_val))) { 14632 /* pointer -= K. Subtract it from fixed offset */ 14633 dst_reg->smin_value = smin_ptr; 14634 dst_reg->smax_value = smax_ptr; 14635 dst_reg->umin_value = umin_ptr; 14636 dst_reg->umax_value = umax_ptr; 14637 dst_reg->var_off = ptr_reg->var_off; 14638 dst_reg->id = ptr_reg->id; 14639 dst_reg->off = ptr_reg->off - smin_val; 14640 dst_reg->raw = ptr_reg->raw; 14641 break; 14642 } 14643 /* A new variable offset is created. If the subtrahend is known 14644 * nonnegative, then any reg->range we had before is still good. 14645 */ 14646 if (check_sub_overflow(smin_ptr, smax_val, &dst_reg->smin_value) || 14647 check_sub_overflow(smax_ptr, smin_val, &dst_reg->smax_value)) { 14648 /* Overflow possible, we know nothing */ 14649 dst_reg->smin_value = S64_MIN; 14650 dst_reg->smax_value = S64_MAX; 14651 } 14652 if (umin_ptr < umax_val) { 14653 /* Overflow possible, we know nothing */ 14654 dst_reg->umin_value = 0; 14655 dst_reg->umax_value = U64_MAX; 14656 } else { 14657 /* Cannot overflow (as long as bounds are consistent) */ 14658 dst_reg->umin_value = umin_ptr - umax_val; 14659 dst_reg->umax_value = umax_ptr - umin_val; 14660 } 14661 dst_reg->var_off = tnum_sub(ptr_reg->var_off, off_reg->var_off); 14662 dst_reg->off = ptr_reg->off; 14663 dst_reg->raw = ptr_reg->raw; 14664 if (reg_is_pkt_pointer(ptr_reg)) { 14665 dst_reg->id = ++env->id_gen; 14666 /* something was added to pkt_ptr, set range to zero */ 14667 if (smin_val < 0) 14668 memset(&dst_reg->raw, 0, sizeof(dst_reg->raw)); 14669 } 14670 break; 14671 case BPF_AND: 14672 case BPF_OR: 14673 case BPF_XOR: 14674 /* bitwise ops on pointers are troublesome, prohibit. */ 14675 verbose(env, "R%d bitwise operator %s on pointer prohibited\n", 14676 dst, bpf_alu_string[opcode >> 4]); 14677 return -EACCES; 14678 default: 14679 /* other operators (e.g. MUL,LSH) produce non-pointer results */ 14680 verbose(env, "R%d pointer arithmetic with %s operator prohibited\n", 14681 dst, bpf_alu_string[opcode >> 4]); 14682 return -EACCES; 14683 } 14684 14685 if (!check_reg_sane_offset(env, dst_reg, ptr_reg->type)) 14686 return -EINVAL; 14687 reg_bounds_sync(dst_reg); 14688 bounds_ret = sanitize_check_bounds(env, insn, dst_reg); 14689 if (bounds_ret == -EACCES) 14690 return bounds_ret; 14691 if (sanitize_needed(opcode)) { 14692 ret = sanitize_ptr_alu(env, insn, dst_reg, off_reg, dst_reg, 14693 &info, true); 14694 if (verifier_bug_if(!can_skip_alu_sanitation(env, insn) 14695 && !env->cur_state->speculative 14696 && bounds_ret 14697 && !ret, 14698 env, "Pointer type unsupported by sanitize_check_bounds() not rejected by retrieve_ptr_limit() as required")) { 14699 return -EFAULT; 14700 } 14701 if (ret < 0) 14702 return sanitize_err(env, insn, ret, off_reg, dst_reg); 14703 } 14704 14705 return 0; 14706 } 14707 14708 static void scalar32_min_max_add(struct bpf_reg_state *dst_reg, 14709 struct bpf_reg_state *src_reg) 14710 { 14711 s32 *dst_smin = &dst_reg->s32_min_value; 14712 s32 *dst_smax = &dst_reg->s32_max_value; 14713 u32 *dst_umin = &dst_reg->u32_min_value; 14714 u32 *dst_umax = &dst_reg->u32_max_value; 14715 u32 umin_val = src_reg->u32_min_value; 14716 u32 umax_val = src_reg->u32_max_value; 14717 bool min_overflow, max_overflow; 14718 14719 if (check_add_overflow(*dst_smin, src_reg->s32_min_value, dst_smin) || 14720 check_add_overflow(*dst_smax, src_reg->s32_max_value, dst_smax)) { 14721 *dst_smin = S32_MIN; 14722 *dst_smax = S32_MAX; 14723 } 14724 14725 /* If either all additions overflow or no additions overflow, then 14726 * it is okay to set: dst_umin = dst_umin + src_umin, dst_umax = 14727 * dst_umax + src_umax. Otherwise (some additions overflow), set 14728 * the output bounds to unbounded. 14729 */ 14730 min_overflow = check_add_overflow(*dst_umin, umin_val, dst_umin); 14731 max_overflow = check_add_overflow(*dst_umax, umax_val, dst_umax); 14732 14733 if (!min_overflow && max_overflow) { 14734 *dst_umin = 0; 14735 *dst_umax = U32_MAX; 14736 } 14737 } 14738 14739 static void scalar_min_max_add(struct bpf_reg_state *dst_reg, 14740 struct bpf_reg_state *src_reg) 14741 { 14742 s64 *dst_smin = &dst_reg->smin_value; 14743 s64 *dst_smax = &dst_reg->smax_value; 14744 u64 *dst_umin = &dst_reg->umin_value; 14745 u64 *dst_umax = &dst_reg->umax_value; 14746 u64 umin_val = src_reg->umin_value; 14747 u64 umax_val = src_reg->umax_value; 14748 bool min_overflow, max_overflow; 14749 14750 if (check_add_overflow(*dst_smin, src_reg->smin_value, dst_smin) || 14751 check_add_overflow(*dst_smax, src_reg->smax_value, dst_smax)) { 14752 *dst_smin = S64_MIN; 14753 *dst_smax = S64_MAX; 14754 } 14755 14756 /* If either all additions overflow or no additions overflow, then 14757 * it is okay to set: dst_umin = dst_umin + src_umin, dst_umax = 14758 * dst_umax + src_umax. Otherwise (some additions overflow), set 14759 * the output bounds to unbounded. 14760 */ 14761 min_overflow = check_add_overflow(*dst_umin, umin_val, dst_umin); 14762 max_overflow = check_add_overflow(*dst_umax, umax_val, dst_umax); 14763 14764 if (!min_overflow && max_overflow) { 14765 *dst_umin = 0; 14766 *dst_umax = U64_MAX; 14767 } 14768 } 14769 14770 static void scalar32_min_max_sub(struct bpf_reg_state *dst_reg, 14771 struct bpf_reg_state *src_reg) 14772 { 14773 s32 *dst_smin = &dst_reg->s32_min_value; 14774 s32 *dst_smax = &dst_reg->s32_max_value; 14775 u32 *dst_umin = &dst_reg->u32_min_value; 14776 u32 *dst_umax = &dst_reg->u32_max_value; 14777 u32 umin_val = src_reg->u32_min_value; 14778 u32 umax_val = src_reg->u32_max_value; 14779 bool min_underflow, max_underflow; 14780 14781 if (check_sub_overflow(*dst_smin, src_reg->s32_max_value, dst_smin) || 14782 check_sub_overflow(*dst_smax, src_reg->s32_min_value, dst_smax)) { 14783 /* Overflow possible, we know nothing */ 14784 *dst_smin = S32_MIN; 14785 *dst_smax = S32_MAX; 14786 } 14787 14788 /* If either all subtractions underflow or no subtractions 14789 * underflow, it is okay to set: dst_umin = dst_umin - src_umax, 14790 * dst_umax = dst_umax - src_umin. Otherwise (some subtractions 14791 * underflow), set the output bounds to unbounded. 14792 */ 14793 min_underflow = check_sub_overflow(*dst_umin, umax_val, dst_umin); 14794 max_underflow = check_sub_overflow(*dst_umax, umin_val, dst_umax); 14795 14796 if (min_underflow && !max_underflow) { 14797 *dst_umin = 0; 14798 *dst_umax = U32_MAX; 14799 } 14800 } 14801 14802 static void scalar_min_max_sub(struct bpf_reg_state *dst_reg, 14803 struct bpf_reg_state *src_reg) 14804 { 14805 s64 *dst_smin = &dst_reg->smin_value; 14806 s64 *dst_smax = &dst_reg->smax_value; 14807 u64 *dst_umin = &dst_reg->umin_value; 14808 u64 *dst_umax = &dst_reg->umax_value; 14809 u64 umin_val = src_reg->umin_value; 14810 u64 umax_val = src_reg->umax_value; 14811 bool min_underflow, max_underflow; 14812 14813 if (check_sub_overflow(*dst_smin, src_reg->smax_value, dst_smin) || 14814 check_sub_overflow(*dst_smax, src_reg->smin_value, dst_smax)) { 14815 /* Overflow possible, we know nothing */ 14816 *dst_smin = S64_MIN; 14817 *dst_smax = S64_MAX; 14818 } 14819 14820 /* If either all subtractions underflow or no subtractions 14821 * underflow, it is okay to set: dst_umin = dst_umin - src_umax, 14822 * dst_umax = dst_umax - src_umin. Otherwise (some subtractions 14823 * underflow), set the output bounds to unbounded. 14824 */ 14825 min_underflow = check_sub_overflow(*dst_umin, umax_val, dst_umin); 14826 max_underflow = check_sub_overflow(*dst_umax, umin_val, dst_umax); 14827 14828 if (min_underflow && !max_underflow) { 14829 *dst_umin = 0; 14830 *dst_umax = U64_MAX; 14831 } 14832 } 14833 14834 static void scalar32_min_max_mul(struct bpf_reg_state *dst_reg, 14835 struct bpf_reg_state *src_reg) 14836 { 14837 s32 *dst_smin = &dst_reg->s32_min_value; 14838 s32 *dst_smax = &dst_reg->s32_max_value; 14839 u32 *dst_umin = &dst_reg->u32_min_value; 14840 u32 *dst_umax = &dst_reg->u32_max_value; 14841 s32 tmp_prod[4]; 14842 14843 if (check_mul_overflow(*dst_umax, src_reg->u32_max_value, dst_umax) || 14844 check_mul_overflow(*dst_umin, src_reg->u32_min_value, dst_umin)) { 14845 /* Overflow possible, we know nothing */ 14846 *dst_umin = 0; 14847 *dst_umax = U32_MAX; 14848 } 14849 if (check_mul_overflow(*dst_smin, src_reg->s32_min_value, &tmp_prod[0]) || 14850 check_mul_overflow(*dst_smin, src_reg->s32_max_value, &tmp_prod[1]) || 14851 check_mul_overflow(*dst_smax, src_reg->s32_min_value, &tmp_prod[2]) || 14852 check_mul_overflow(*dst_smax, src_reg->s32_max_value, &tmp_prod[3])) { 14853 /* Overflow possible, we know nothing */ 14854 *dst_smin = S32_MIN; 14855 *dst_smax = S32_MAX; 14856 } else { 14857 *dst_smin = min_array(tmp_prod, 4); 14858 *dst_smax = max_array(tmp_prod, 4); 14859 } 14860 } 14861 14862 static void scalar_min_max_mul(struct bpf_reg_state *dst_reg, 14863 struct bpf_reg_state *src_reg) 14864 { 14865 s64 *dst_smin = &dst_reg->smin_value; 14866 s64 *dst_smax = &dst_reg->smax_value; 14867 u64 *dst_umin = &dst_reg->umin_value; 14868 u64 *dst_umax = &dst_reg->umax_value; 14869 s64 tmp_prod[4]; 14870 14871 if (check_mul_overflow(*dst_umax, src_reg->umax_value, dst_umax) || 14872 check_mul_overflow(*dst_umin, src_reg->umin_value, dst_umin)) { 14873 /* Overflow possible, we know nothing */ 14874 *dst_umin = 0; 14875 *dst_umax = U64_MAX; 14876 } 14877 if (check_mul_overflow(*dst_smin, src_reg->smin_value, &tmp_prod[0]) || 14878 check_mul_overflow(*dst_smin, src_reg->smax_value, &tmp_prod[1]) || 14879 check_mul_overflow(*dst_smax, src_reg->smin_value, &tmp_prod[2]) || 14880 check_mul_overflow(*dst_smax, src_reg->smax_value, &tmp_prod[3])) { 14881 /* Overflow possible, we know nothing */ 14882 *dst_smin = S64_MIN; 14883 *dst_smax = S64_MAX; 14884 } else { 14885 *dst_smin = min_array(tmp_prod, 4); 14886 *dst_smax = max_array(tmp_prod, 4); 14887 } 14888 } 14889 14890 static void scalar32_min_max_and(struct bpf_reg_state *dst_reg, 14891 struct bpf_reg_state *src_reg) 14892 { 14893 bool src_known = tnum_subreg_is_const(src_reg->var_off); 14894 bool dst_known = tnum_subreg_is_const(dst_reg->var_off); 14895 struct tnum var32_off = tnum_subreg(dst_reg->var_off); 14896 u32 umax_val = src_reg->u32_max_value; 14897 14898 if (src_known && dst_known) { 14899 __mark_reg32_known(dst_reg, var32_off.value); 14900 return; 14901 } 14902 14903 /* We get our minimum from the var_off, since that's inherently 14904 * bitwise. Our maximum is the minimum of the operands' maxima. 14905 */ 14906 dst_reg->u32_min_value = var32_off.value; 14907 dst_reg->u32_max_value = min(dst_reg->u32_max_value, umax_val); 14908 14909 /* Safe to set s32 bounds by casting u32 result into s32 when u32 14910 * doesn't cross sign boundary. Otherwise set s32 bounds to unbounded. 14911 */ 14912 if ((s32)dst_reg->u32_min_value <= (s32)dst_reg->u32_max_value) { 14913 dst_reg->s32_min_value = dst_reg->u32_min_value; 14914 dst_reg->s32_max_value = dst_reg->u32_max_value; 14915 } else { 14916 dst_reg->s32_min_value = S32_MIN; 14917 dst_reg->s32_max_value = S32_MAX; 14918 } 14919 } 14920 14921 static void scalar_min_max_and(struct bpf_reg_state *dst_reg, 14922 struct bpf_reg_state *src_reg) 14923 { 14924 bool src_known = tnum_is_const(src_reg->var_off); 14925 bool dst_known = tnum_is_const(dst_reg->var_off); 14926 u64 umax_val = src_reg->umax_value; 14927 14928 if (src_known && dst_known) { 14929 __mark_reg_known(dst_reg, dst_reg->var_off.value); 14930 return; 14931 } 14932 14933 /* We get our minimum from the var_off, since that's inherently 14934 * bitwise. Our maximum is the minimum of the operands' maxima. 14935 */ 14936 dst_reg->umin_value = dst_reg->var_off.value; 14937 dst_reg->umax_value = min(dst_reg->umax_value, umax_val); 14938 14939 /* Safe to set s64 bounds by casting u64 result into s64 when u64 14940 * doesn't cross sign boundary. Otherwise set s64 bounds to unbounded. 14941 */ 14942 if ((s64)dst_reg->umin_value <= (s64)dst_reg->umax_value) { 14943 dst_reg->smin_value = dst_reg->umin_value; 14944 dst_reg->smax_value = dst_reg->umax_value; 14945 } else { 14946 dst_reg->smin_value = S64_MIN; 14947 dst_reg->smax_value = S64_MAX; 14948 } 14949 /* We may learn something more from the var_off */ 14950 __update_reg_bounds(dst_reg); 14951 } 14952 14953 static void scalar32_min_max_or(struct bpf_reg_state *dst_reg, 14954 struct bpf_reg_state *src_reg) 14955 { 14956 bool src_known = tnum_subreg_is_const(src_reg->var_off); 14957 bool dst_known = tnum_subreg_is_const(dst_reg->var_off); 14958 struct tnum var32_off = tnum_subreg(dst_reg->var_off); 14959 u32 umin_val = src_reg->u32_min_value; 14960 14961 if (src_known && dst_known) { 14962 __mark_reg32_known(dst_reg, var32_off.value); 14963 return; 14964 } 14965 14966 /* We get our maximum from the var_off, and our minimum is the 14967 * maximum of the operands' minima 14968 */ 14969 dst_reg->u32_min_value = max(dst_reg->u32_min_value, umin_val); 14970 dst_reg->u32_max_value = var32_off.value | var32_off.mask; 14971 14972 /* Safe to set s32 bounds by casting u32 result into s32 when u32 14973 * doesn't cross sign boundary. Otherwise set s32 bounds to unbounded. 14974 */ 14975 if ((s32)dst_reg->u32_min_value <= (s32)dst_reg->u32_max_value) { 14976 dst_reg->s32_min_value = dst_reg->u32_min_value; 14977 dst_reg->s32_max_value = dst_reg->u32_max_value; 14978 } else { 14979 dst_reg->s32_min_value = S32_MIN; 14980 dst_reg->s32_max_value = S32_MAX; 14981 } 14982 } 14983 14984 static void scalar_min_max_or(struct bpf_reg_state *dst_reg, 14985 struct bpf_reg_state *src_reg) 14986 { 14987 bool src_known = tnum_is_const(src_reg->var_off); 14988 bool dst_known = tnum_is_const(dst_reg->var_off); 14989 u64 umin_val = src_reg->umin_value; 14990 14991 if (src_known && dst_known) { 14992 __mark_reg_known(dst_reg, dst_reg->var_off.value); 14993 return; 14994 } 14995 14996 /* We get our maximum from the var_off, and our minimum is the 14997 * maximum of the operands' minima 14998 */ 14999 dst_reg->umin_value = max(dst_reg->umin_value, umin_val); 15000 dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask; 15001 15002 /* Safe to set s64 bounds by casting u64 result into s64 when u64 15003 * doesn't cross sign boundary. Otherwise set s64 bounds to unbounded. 15004 */ 15005 if ((s64)dst_reg->umin_value <= (s64)dst_reg->umax_value) { 15006 dst_reg->smin_value = dst_reg->umin_value; 15007 dst_reg->smax_value = dst_reg->umax_value; 15008 } else { 15009 dst_reg->smin_value = S64_MIN; 15010 dst_reg->smax_value = S64_MAX; 15011 } 15012 /* We may learn something more from the var_off */ 15013 __update_reg_bounds(dst_reg); 15014 } 15015 15016 static void scalar32_min_max_xor(struct bpf_reg_state *dst_reg, 15017 struct bpf_reg_state *src_reg) 15018 { 15019 bool src_known = tnum_subreg_is_const(src_reg->var_off); 15020 bool dst_known = tnum_subreg_is_const(dst_reg->var_off); 15021 struct tnum var32_off = tnum_subreg(dst_reg->var_off); 15022 15023 if (src_known && dst_known) { 15024 __mark_reg32_known(dst_reg, var32_off.value); 15025 return; 15026 } 15027 15028 /* We get both minimum and maximum from the var32_off. */ 15029 dst_reg->u32_min_value = var32_off.value; 15030 dst_reg->u32_max_value = var32_off.value | var32_off.mask; 15031 15032 /* Safe to set s32 bounds by casting u32 result into s32 when u32 15033 * doesn't cross sign boundary. Otherwise set s32 bounds to unbounded. 15034 */ 15035 if ((s32)dst_reg->u32_min_value <= (s32)dst_reg->u32_max_value) { 15036 dst_reg->s32_min_value = dst_reg->u32_min_value; 15037 dst_reg->s32_max_value = dst_reg->u32_max_value; 15038 } else { 15039 dst_reg->s32_min_value = S32_MIN; 15040 dst_reg->s32_max_value = S32_MAX; 15041 } 15042 } 15043 15044 static void scalar_min_max_xor(struct bpf_reg_state *dst_reg, 15045 struct bpf_reg_state *src_reg) 15046 { 15047 bool src_known = tnum_is_const(src_reg->var_off); 15048 bool dst_known = tnum_is_const(dst_reg->var_off); 15049 15050 if (src_known && dst_known) { 15051 /* dst_reg->var_off.value has been updated earlier */ 15052 __mark_reg_known(dst_reg, dst_reg->var_off.value); 15053 return; 15054 } 15055 15056 /* We get both minimum and maximum from the var_off. */ 15057 dst_reg->umin_value = dst_reg->var_off.value; 15058 dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask; 15059 15060 /* Safe to set s64 bounds by casting u64 result into s64 when u64 15061 * doesn't cross sign boundary. Otherwise set s64 bounds to unbounded. 15062 */ 15063 if ((s64)dst_reg->umin_value <= (s64)dst_reg->umax_value) { 15064 dst_reg->smin_value = dst_reg->umin_value; 15065 dst_reg->smax_value = dst_reg->umax_value; 15066 } else { 15067 dst_reg->smin_value = S64_MIN; 15068 dst_reg->smax_value = S64_MAX; 15069 } 15070 15071 __update_reg_bounds(dst_reg); 15072 } 15073 15074 static void __scalar32_min_max_lsh(struct bpf_reg_state *dst_reg, 15075 u64 umin_val, u64 umax_val) 15076 { 15077 /* We lose all sign bit information (except what we can pick 15078 * up from var_off) 15079 */ 15080 dst_reg->s32_min_value = S32_MIN; 15081 dst_reg->s32_max_value = S32_MAX; 15082 /* If we might shift our top bit out, then we know nothing */ 15083 if (umax_val > 31 || dst_reg->u32_max_value > 1ULL << (31 - umax_val)) { 15084 dst_reg->u32_min_value = 0; 15085 dst_reg->u32_max_value = U32_MAX; 15086 } else { 15087 dst_reg->u32_min_value <<= umin_val; 15088 dst_reg->u32_max_value <<= umax_val; 15089 } 15090 } 15091 15092 static void scalar32_min_max_lsh(struct bpf_reg_state *dst_reg, 15093 struct bpf_reg_state *src_reg) 15094 { 15095 u32 umax_val = src_reg->u32_max_value; 15096 u32 umin_val = src_reg->u32_min_value; 15097 /* u32 alu operation will zext upper bits */ 15098 struct tnum subreg = tnum_subreg(dst_reg->var_off); 15099 15100 __scalar32_min_max_lsh(dst_reg, umin_val, umax_val); 15101 dst_reg->var_off = tnum_subreg(tnum_lshift(subreg, umin_val)); 15102 /* Not required but being careful mark reg64 bounds as unknown so 15103 * that we are forced to pick them up from tnum and zext later and 15104 * if some path skips this step we are still safe. 15105 */ 15106 __mark_reg64_unbounded(dst_reg); 15107 __update_reg32_bounds(dst_reg); 15108 } 15109 15110 static void __scalar64_min_max_lsh(struct bpf_reg_state *dst_reg, 15111 u64 umin_val, u64 umax_val) 15112 { 15113 /* Special case <<32 because it is a common compiler pattern to sign 15114 * extend subreg by doing <<32 s>>32. In this case if 32bit bounds are 15115 * positive we know this shift will also be positive so we can track 15116 * bounds correctly. Otherwise we lose all sign bit information except 15117 * what we can pick up from var_off. Perhaps we can generalize this 15118 * later to shifts of any length. 15119 */ 15120 if (umin_val == 32 && umax_val == 32 && dst_reg->s32_max_value >= 0) 15121 dst_reg->smax_value = (s64)dst_reg->s32_max_value << 32; 15122 else 15123 dst_reg->smax_value = S64_MAX; 15124 15125 if (umin_val == 32 && umax_val == 32 && dst_reg->s32_min_value >= 0) 15126 dst_reg->smin_value = (s64)dst_reg->s32_min_value << 32; 15127 else 15128 dst_reg->smin_value = S64_MIN; 15129 15130 /* If we might shift our top bit out, then we know nothing */ 15131 if (dst_reg->umax_value > 1ULL << (63 - umax_val)) { 15132 dst_reg->umin_value = 0; 15133 dst_reg->umax_value = U64_MAX; 15134 } else { 15135 dst_reg->umin_value <<= umin_val; 15136 dst_reg->umax_value <<= umax_val; 15137 } 15138 } 15139 15140 static void scalar_min_max_lsh(struct bpf_reg_state *dst_reg, 15141 struct bpf_reg_state *src_reg) 15142 { 15143 u64 umax_val = src_reg->umax_value; 15144 u64 umin_val = src_reg->umin_value; 15145 15146 /* scalar64 calc uses 32bit unshifted bounds so must be called first */ 15147 __scalar64_min_max_lsh(dst_reg, umin_val, umax_val); 15148 __scalar32_min_max_lsh(dst_reg, umin_val, umax_val); 15149 15150 dst_reg->var_off = tnum_lshift(dst_reg->var_off, umin_val); 15151 /* We may learn something more from the var_off */ 15152 __update_reg_bounds(dst_reg); 15153 } 15154 15155 static void scalar32_min_max_rsh(struct bpf_reg_state *dst_reg, 15156 struct bpf_reg_state *src_reg) 15157 { 15158 struct tnum subreg = tnum_subreg(dst_reg->var_off); 15159 u32 umax_val = src_reg->u32_max_value; 15160 u32 umin_val = src_reg->u32_min_value; 15161 15162 /* BPF_RSH is an unsigned shift. If the value in dst_reg might 15163 * be negative, then either: 15164 * 1) src_reg might be zero, so the sign bit of the result is 15165 * unknown, so we lose our signed bounds 15166 * 2) it's known negative, thus the unsigned bounds capture the 15167 * signed bounds 15168 * 3) the signed bounds cross zero, so they tell us nothing 15169 * about the result 15170 * If the value in dst_reg is known nonnegative, then again the 15171 * unsigned bounds capture the signed bounds. 15172 * Thus, in all cases it suffices to blow away our signed bounds 15173 * and rely on inferring new ones from the unsigned bounds and 15174 * var_off of the result. 15175 */ 15176 dst_reg->s32_min_value = S32_MIN; 15177 dst_reg->s32_max_value = S32_MAX; 15178 15179 dst_reg->var_off = tnum_rshift(subreg, umin_val); 15180 dst_reg->u32_min_value >>= umax_val; 15181 dst_reg->u32_max_value >>= umin_val; 15182 15183 __mark_reg64_unbounded(dst_reg); 15184 __update_reg32_bounds(dst_reg); 15185 } 15186 15187 static void scalar_min_max_rsh(struct bpf_reg_state *dst_reg, 15188 struct bpf_reg_state *src_reg) 15189 { 15190 u64 umax_val = src_reg->umax_value; 15191 u64 umin_val = src_reg->umin_value; 15192 15193 /* BPF_RSH is an unsigned shift. If the value in dst_reg might 15194 * be negative, then either: 15195 * 1) src_reg might be zero, so the sign bit of the result is 15196 * unknown, so we lose our signed bounds 15197 * 2) it's known negative, thus the unsigned bounds capture the 15198 * signed bounds 15199 * 3) the signed bounds cross zero, so they tell us nothing 15200 * about the result 15201 * If the value in dst_reg is known nonnegative, then again the 15202 * unsigned bounds capture the signed bounds. 15203 * Thus, in all cases it suffices to blow away our signed bounds 15204 * and rely on inferring new ones from the unsigned bounds and 15205 * var_off of the result. 15206 */ 15207 dst_reg->smin_value = S64_MIN; 15208 dst_reg->smax_value = S64_MAX; 15209 dst_reg->var_off = tnum_rshift(dst_reg->var_off, umin_val); 15210 dst_reg->umin_value >>= umax_val; 15211 dst_reg->umax_value >>= umin_val; 15212 15213 /* Its not easy to operate on alu32 bounds here because it depends 15214 * on bits being shifted in. Take easy way out and mark unbounded 15215 * so we can recalculate later from tnum. 15216 */ 15217 __mark_reg32_unbounded(dst_reg); 15218 __update_reg_bounds(dst_reg); 15219 } 15220 15221 static void scalar32_min_max_arsh(struct bpf_reg_state *dst_reg, 15222 struct bpf_reg_state *src_reg) 15223 { 15224 u64 umin_val = src_reg->u32_min_value; 15225 15226 /* Upon reaching here, src_known is true and 15227 * umax_val is equal to umin_val. 15228 */ 15229 dst_reg->s32_min_value = (u32)(((s32)dst_reg->s32_min_value) >> umin_val); 15230 dst_reg->s32_max_value = (u32)(((s32)dst_reg->s32_max_value) >> umin_val); 15231 15232 dst_reg->var_off = tnum_arshift(tnum_subreg(dst_reg->var_off), umin_val, 32); 15233 15234 /* blow away the dst_reg umin_value/umax_value and rely on 15235 * dst_reg var_off to refine the result. 15236 */ 15237 dst_reg->u32_min_value = 0; 15238 dst_reg->u32_max_value = U32_MAX; 15239 15240 __mark_reg64_unbounded(dst_reg); 15241 __update_reg32_bounds(dst_reg); 15242 } 15243 15244 static void scalar_min_max_arsh(struct bpf_reg_state *dst_reg, 15245 struct bpf_reg_state *src_reg) 15246 { 15247 u64 umin_val = src_reg->umin_value; 15248 15249 /* Upon reaching here, src_known is true and umax_val is equal 15250 * to umin_val. 15251 */ 15252 dst_reg->smin_value >>= umin_val; 15253 dst_reg->smax_value >>= umin_val; 15254 15255 dst_reg->var_off = tnum_arshift(dst_reg->var_off, umin_val, 64); 15256 15257 /* blow away the dst_reg umin_value/umax_value and rely on 15258 * dst_reg var_off to refine the result. 15259 */ 15260 dst_reg->umin_value = 0; 15261 dst_reg->umax_value = U64_MAX; 15262 15263 /* Its not easy to operate on alu32 bounds here because it depends 15264 * on bits being shifted in from upper 32-bits. Take easy way out 15265 * and mark unbounded so we can recalculate later from tnum. 15266 */ 15267 __mark_reg32_unbounded(dst_reg); 15268 __update_reg_bounds(dst_reg); 15269 } 15270 15271 static bool is_safe_to_compute_dst_reg_range(struct bpf_insn *insn, 15272 const struct bpf_reg_state *src_reg) 15273 { 15274 bool src_is_const = false; 15275 u64 insn_bitness = (BPF_CLASS(insn->code) == BPF_ALU64) ? 64 : 32; 15276 15277 if (insn_bitness == 32) { 15278 if (tnum_subreg_is_const(src_reg->var_off) 15279 && src_reg->s32_min_value == src_reg->s32_max_value 15280 && src_reg->u32_min_value == src_reg->u32_max_value) 15281 src_is_const = true; 15282 } else { 15283 if (tnum_is_const(src_reg->var_off) 15284 && src_reg->smin_value == src_reg->smax_value 15285 && src_reg->umin_value == src_reg->umax_value) 15286 src_is_const = true; 15287 } 15288 15289 switch (BPF_OP(insn->code)) { 15290 case BPF_ADD: 15291 case BPF_SUB: 15292 case BPF_NEG: 15293 case BPF_AND: 15294 case BPF_XOR: 15295 case BPF_OR: 15296 case BPF_MUL: 15297 return true; 15298 15299 /* Shift operators range is only computable if shift dimension operand 15300 * is a constant. Shifts greater than 31 or 63 are undefined. This 15301 * includes shifts by a negative number. 15302 */ 15303 case BPF_LSH: 15304 case BPF_RSH: 15305 case BPF_ARSH: 15306 return (src_is_const && src_reg->umax_value < insn_bitness); 15307 default: 15308 return false; 15309 } 15310 } 15311 15312 /* WARNING: This function does calculations on 64-bit values, but the actual 15313 * execution may occur on 32-bit values. Therefore, things like bitshifts 15314 * need extra checks in the 32-bit case. 15315 */ 15316 static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env, 15317 struct bpf_insn *insn, 15318 struct bpf_reg_state *dst_reg, 15319 struct bpf_reg_state src_reg) 15320 { 15321 u8 opcode = BPF_OP(insn->code); 15322 bool alu32 = (BPF_CLASS(insn->code) != BPF_ALU64); 15323 int ret; 15324 15325 if (!is_safe_to_compute_dst_reg_range(insn, &src_reg)) { 15326 __mark_reg_unknown(env, dst_reg); 15327 return 0; 15328 } 15329 15330 if (sanitize_needed(opcode)) { 15331 ret = sanitize_val_alu(env, insn); 15332 if (ret < 0) 15333 return sanitize_err(env, insn, ret, NULL, NULL); 15334 } 15335 15336 /* Calculate sign/unsigned bounds and tnum for alu32 and alu64 bit ops. 15337 * There are two classes of instructions: The first class we track both 15338 * alu32 and alu64 sign/unsigned bounds independently this provides the 15339 * greatest amount of precision when alu operations are mixed with jmp32 15340 * operations. These operations are BPF_ADD, BPF_SUB, BPF_MUL, BPF_ADD, 15341 * and BPF_OR. This is possible because these ops have fairly easy to 15342 * understand and calculate behavior in both 32-bit and 64-bit alu ops. 15343 * See alu32 verifier tests for examples. The second class of 15344 * operations, BPF_LSH, BPF_RSH, and BPF_ARSH, however are not so easy 15345 * with regards to tracking sign/unsigned bounds because the bits may 15346 * cross subreg boundaries in the alu64 case. When this happens we mark 15347 * the reg unbounded in the subreg bound space and use the resulting 15348 * tnum to calculate an approximation of the sign/unsigned bounds. 15349 */ 15350 switch (opcode) { 15351 case BPF_ADD: 15352 scalar32_min_max_add(dst_reg, &src_reg); 15353 scalar_min_max_add(dst_reg, &src_reg); 15354 dst_reg->var_off = tnum_add(dst_reg->var_off, src_reg.var_off); 15355 break; 15356 case BPF_SUB: 15357 scalar32_min_max_sub(dst_reg, &src_reg); 15358 scalar_min_max_sub(dst_reg, &src_reg); 15359 dst_reg->var_off = tnum_sub(dst_reg->var_off, src_reg.var_off); 15360 break; 15361 case BPF_NEG: 15362 env->fake_reg[0] = *dst_reg; 15363 __mark_reg_known(dst_reg, 0); 15364 scalar32_min_max_sub(dst_reg, &env->fake_reg[0]); 15365 scalar_min_max_sub(dst_reg, &env->fake_reg[0]); 15366 dst_reg->var_off = tnum_neg(env->fake_reg[0].var_off); 15367 break; 15368 case BPF_MUL: 15369 dst_reg->var_off = tnum_mul(dst_reg->var_off, src_reg.var_off); 15370 scalar32_min_max_mul(dst_reg, &src_reg); 15371 scalar_min_max_mul(dst_reg, &src_reg); 15372 break; 15373 case BPF_AND: 15374 dst_reg->var_off = tnum_and(dst_reg->var_off, src_reg.var_off); 15375 scalar32_min_max_and(dst_reg, &src_reg); 15376 scalar_min_max_and(dst_reg, &src_reg); 15377 break; 15378 case BPF_OR: 15379 dst_reg->var_off = tnum_or(dst_reg->var_off, src_reg.var_off); 15380 scalar32_min_max_or(dst_reg, &src_reg); 15381 scalar_min_max_or(dst_reg, &src_reg); 15382 break; 15383 case BPF_XOR: 15384 dst_reg->var_off = tnum_xor(dst_reg->var_off, src_reg.var_off); 15385 scalar32_min_max_xor(dst_reg, &src_reg); 15386 scalar_min_max_xor(dst_reg, &src_reg); 15387 break; 15388 case BPF_LSH: 15389 if (alu32) 15390 scalar32_min_max_lsh(dst_reg, &src_reg); 15391 else 15392 scalar_min_max_lsh(dst_reg, &src_reg); 15393 break; 15394 case BPF_RSH: 15395 if (alu32) 15396 scalar32_min_max_rsh(dst_reg, &src_reg); 15397 else 15398 scalar_min_max_rsh(dst_reg, &src_reg); 15399 break; 15400 case BPF_ARSH: 15401 if (alu32) 15402 scalar32_min_max_arsh(dst_reg, &src_reg); 15403 else 15404 scalar_min_max_arsh(dst_reg, &src_reg); 15405 break; 15406 default: 15407 break; 15408 } 15409 15410 /* ALU32 ops are zero extended into 64bit register */ 15411 if (alu32) 15412 zext_32_to_64(dst_reg); 15413 reg_bounds_sync(dst_reg); 15414 return 0; 15415 } 15416 15417 /* Handles ALU ops other than BPF_END, BPF_NEG and BPF_MOV: computes new min/max 15418 * and var_off. 15419 */ 15420 static int adjust_reg_min_max_vals(struct bpf_verifier_env *env, 15421 struct bpf_insn *insn) 15422 { 15423 struct bpf_verifier_state *vstate = env->cur_state; 15424 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 15425 struct bpf_reg_state *regs = state->regs, *dst_reg, *src_reg; 15426 struct bpf_reg_state *ptr_reg = NULL, off_reg = {0}; 15427 bool alu32 = (BPF_CLASS(insn->code) != BPF_ALU64); 15428 u8 opcode = BPF_OP(insn->code); 15429 int err; 15430 15431 dst_reg = ®s[insn->dst_reg]; 15432 src_reg = NULL; 15433 15434 if (dst_reg->type == PTR_TO_ARENA) { 15435 struct bpf_insn_aux_data *aux = cur_aux(env); 15436 15437 if (BPF_CLASS(insn->code) == BPF_ALU64) 15438 /* 15439 * 32-bit operations zero upper bits automatically. 15440 * 64-bit operations need to be converted to 32. 15441 */ 15442 aux->needs_zext = true; 15443 15444 /* Any arithmetic operations are allowed on arena pointers */ 15445 return 0; 15446 } 15447 15448 if (dst_reg->type != SCALAR_VALUE) 15449 ptr_reg = dst_reg; 15450 15451 if (BPF_SRC(insn->code) == BPF_X) { 15452 src_reg = ®s[insn->src_reg]; 15453 if (src_reg->type != SCALAR_VALUE) { 15454 if (dst_reg->type != SCALAR_VALUE) { 15455 /* Combining two pointers by any ALU op yields 15456 * an arbitrary scalar. Disallow all math except 15457 * pointer subtraction 15458 */ 15459 if (opcode == BPF_SUB && env->allow_ptr_leaks) { 15460 mark_reg_unknown(env, regs, insn->dst_reg); 15461 return 0; 15462 } 15463 verbose(env, "R%d pointer %s pointer prohibited\n", 15464 insn->dst_reg, 15465 bpf_alu_string[opcode >> 4]); 15466 return -EACCES; 15467 } else { 15468 /* scalar += pointer 15469 * This is legal, but we have to reverse our 15470 * src/dest handling in computing the range 15471 */ 15472 err = mark_chain_precision(env, insn->dst_reg); 15473 if (err) 15474 return err; 15475 return adjust_ptr_min_max_vals(env, insn, 15476 src_reg, dst_reg); 15477 } 15478 } else if (ptr_reg) { 15479 /* pointer += scalar */ 15480 err = mark_chain_precision(env, insn->src_reg); 15481 if (err) 15482 return err; 15483 return adjust_ptr_min_max_vals(env, insn, 15484 dst_reg, src_reg); 15485 } else if (dst_reg->precise) { 15486 /* if dst_reg is precise, src_reg should be precise as well */ 15487 err = mark_chain_precision(env, insn->src_reg); 15488 if (err) 15489 return err; 15490 } 15491 } else { 15492 /* Pretend the src is a reg with a known value, since we only 15493 * need to be able to read from this state. 15494 */ 15495 off_reg.type = SCALAR_VALUE; 15496 __mark_reg_known(&off_reg, insn->imm); 15497 src_reg = &off_reg; 15498 if (ptr_reg) /* pointer += K */ 15499 return adjust_ptr_min_max_vals(env, insn, 15500 ptr_reg, src_reg); 15501 } 15502 15503 /* Got here implies adding two SCALAR_VALUEs */ 15504 if (WARN_ON_ONCE(ptr_reg)) { 15505 print_verifier_state(env, vstate, vstate->curframe, true); 15506 verbose(env, "verifier internal error: unexpected ptr_reg\n"); 15507 return -EFAULT; 15508 } 15509 if (WARN_ON(!src_reg)) { 15510 print_verifier_state(env, vstate, vstate->curframe, true); 15511 verbose(env, "verifier internal error: no src_reg\n"); 15512 return -EFAULT; 15513 } 15514 err = adjust_scalar_min_max_vals(env, insn, dst_reg, *src_reg); 15515 if (err) 15516 return err; 15517 /* 15518 * Compilers can generate the code 15519 * r1 = r2 15520 * r1 += 0x1 15521 * if r2 < 1000 goto ... 15522 * use r1 in memory access 15523 * So for 64-bit alu remember constant delta between r2 and r1 and 15524 * update r1 after 'if' condition. 15525 */ 15526 if (env->bpf_capable && 15527 BPF_OP(insn->code) == BPF_ADD && !alu32 && 15528 dst_reg->id && is_reg_const(src_reg, false)) { 15529 u64 val = reg_const_value(src_reg, false); 15530 15531 if ((dst_reg->id & BPF_ADD_CONST) || 15532 /* prevent overflow in sync_linked_regs() later */ 15533 val > (u32)S32_MAX) { 15534 /* 15535 * If the register already went through rX += val 15536 * we cannot accumulate another val into rx->off. 15537 */ 15538 dst_reg->off = 0; 15539 dst_reg->id = 0; 15540 } else { 15541 dst_reg->id |= BPF_ADD_CONST; 15542 dst_reg->off = val; 15543 } 15544 } else { 15545 /* 15546 * Make sure ID is cleared otherwise dst_reg min/max could be 15547 * incorrectly propagated into other registers by sync_linked_regs() 15548 */ 15549 dst_reg->id = 0; 15550 } 15551 return 0; 15552 } 15553 15554 /* check validity of 32-bit and 64-bit arithmetic operations */ 15555 static int check_alu_op(struct bpf_verifier_env *env, struct bpf_insn *insn) 15556 { 15557 struct bpf_reg_state *regs = cur_regs(env); 15558 u8 opcode = BPF_OP(insn->code); 15559 int err; 15560 15561 if (opcode == BPF_END || opcode == BPF_NEG) { 15562 if (opcode == BPF_NEG) { 15563 if (BPF_SRC(insn->code) != BPF_K || 15564 insn->src_reg != BPF_REG_0 || 15565 insn->off != 0 || insn->imm != 0) { 15566 verbose(env, "BPF_NEG uses reserved fields\n"); 15567 return -EINVAL; 15568 } 15569 } else { 15570 if (insn->src_reg != BPF_REG_0 || insn->off != 0 || 15571 (insn->imm != 16 && insn->imm != 32 && insn->imm != 64) || 15572 (BPF_CLASS(insn->code) == BPF_ALU64 && 15573 BPF_SRC(insn->code) != BPF_TO_LE)) { 15574 verbose(env, "BPF_END uses reserved fields\n"); 15575 return -EINVAL; 15576 } 15577 } 15578 15579 /* check src operand */ 15580 err = check_reg_arg(env, insn->dst_reg, SRC_OP); 15581 if (err) 15582 return err; 15583 15584 if (is_pointer_value(env, insn->dst_reg)) { 15585 verbose(env, "R%d pointer arithmetic prohibited\n", 15586 insn->dst_reg); 15587 return -EACCES; 15588 } 15589 15590 /* check dest operand */ 15591 if (opcode == BPF_NEG) { 15592 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK); 15593 err = err ?: adjust_scalar_min_max_vals(env, insn, 15594 ®s[insn->dst_reg], 15595 regs[insn->dst_reg]); 15596 } else { 15597 err = check_reg_arg(env, insn->dst_reg, DST_OP); 15598 } 15599 if (err) 15600 return err; 15601 15602 } else if (opcode == BPF_MOV) { 15603 15604 if (BPF_SRC(insn->code) == BPF_X) { 15605 if (BPF_CLASS(insn->code) == BPF_ALU) { 15606 if ((insn->off != 0 && insn->off != 8 && insn->off != 16) || 15607 insn->imm) { 15608 verbose(env, "BPF_MOV uses reserved fields\n"); 15609 return -EINVAL; 15610 } 15611 } else if (insn->off == BPF_ADDR_SPACE_CAST) { 15612 if (insn->imm != 1 && insn->imm != 1u << 16) { 15613 verbose(env, "addr_space_cast insn can only convert between address space 1 and 0\n"); 15614 return -EINVAL; 15615 } 15616 if (!env->prog->aux->arena) { 15617 verbose(env, "addr_space_cast insn can only be used in a program that has an associated arena\n"); 15618 return -EINVAL; 15619 } 15620 } else { 15621 if ((insn->off != 0 && insn->off != 8 && insn->off != 16 && 15622 insn->off != 32) || insn->imm) { 15623 verbose(env, "BPF_MOV uses reserved fields\n"); 15624 return -EINVAL; 15625 } 15626 } 15627 15628 /* check src operand */ 15629 err = check_reg_arg(env, insn->src_reg, SRC_OP); 15630 if (err) 15631 return err; 15632 } else { 15633 if (insn->src_reg != BPF_REG_0 || insn->off != 0) { 15634 verbose(env, "BPF_MOV uses reserved fields\n"); 15635 return -EINVAL; 15636 } 15637 } 15638 15639 /* check dest operand, mark as required later */ 15640 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK); 15641 if (err) 15642 return err; 15643 15644 if (BPF_SRC(insn->code) == BPF_X) { 15645 struct bpf_reg_state *src_reg = regs + insn->src_reg; 15646 struct bpf_reg_state *dst_reg = regs + insn->dst_reg; 15647 15648 if (BPF_CLASS(insn->code) == BPF_ALU64) { 15649 if (insn->imm) { 15650 /* off == BPF_ADDR_SPACE_CAST */ 15651 mark_reg_unknown(env, regs, insn->dst_reg); 15652 if (insn->imm == 1) { /* cast from as(1) to as(0) */ 15653 dst_reg->type = PTR_TO_ARENA; 15654 /* PTR_TO_ARENA is 32-bit */ 15655 dst_reg->subreg_def = env->insn_idx + 1; 15656 } 15657 } else if (insn->off == 0) { 15658 /* case: R1 = R2 15659 * copy register state to dest reg 15660 */ 15661 assign_scalar_id_before_mov(env, src_reg); 15662 copy_register_state(dst_reg, src_reg); 15663 dst_reg->live |= REG_LIVE_WRITTEN; 15664 dst_reg->subreg_def = DEF_NOT_SUBREG; 15665 } else { 15666 /* case: R1 = (s8, s16 s32)R2 */ 15667 if (is_pointer_value(env, insn->src_reg)) { 15668 verbose(env, 15669 "R%d sign-extension part of pointer\n", 15670 insn->src_reg); 15671 return -EACCES; 15672 } else if (src_reg->type == SCALAR_VALUE) { 15673 bool no_sext; 15674 15675 no_sext = src_reg->umax_value < (1ULL << (insn->off - 1)); 15676 if (no_sext) 15677 assign_scalar_id_before_mov(env, src_reg); 15678 copy_register_state(dst_reg, src_reg); 15679 if (!no_sext) 15680 dst_reg->id = 0; 15681 coerce_reg_to_size_sx(dst_reg, insn->off >> 3); 15682 dst_reg->live |= REG_LIVE_WRITTEN; 15683 dst_reg->subreg_def = DEF_NOT_SUBREG; 15684 } else { 15685 mark_reg_unknown(env, regs, insn->dst_reg); 15686 } 15687 } 15688 } else { 15689 /* R1 = (u32) R2 */ 15690 if (is_pointer_value(env, insn->src_reg)) { 15691 verbose(env, 15692 "R%d partial copy of pointer\n", 15693 insn->src_reg); 15694 return -EACCES; 15695 } else if (src_reg->type == SCALAR_VALUE) { 15696 if (insn->off == 0) { 15697 bool is_src_reg_u32 = get_reg_width(src_reg) <= 32; 15698 15699 if (is_src_reg_u32) 15700 assign_scalar_id_before_mov(env, src_reg); 15701 copy_register_state(dst_reg, src_reg); 15702 /* Make sure ID is cleared if src_reg is not in u32 15703 * range otherwise dst_reg min/max could be incorrectly 15704 * propagated into src_reg by sync_linked_regs() 15705 */ 15706 if (!is_src_reg_u32) 15707 dst_reg->id = 0; 15708 dst_reg->live |= REG_LIVE_WRITTEN; 15709 dst_reg->subreg_def = env->insn_idx + 1; 15710 } else { 15711 /* case: W1 = (s8, s16)W2 */ 15712 bool no_sext = src_reg->umax_value < (1ULL << (insn->off - 1)); 15713 15714 if (no_sext) 15715 assign_scalar_id_before_mov(env, src_reg); 15716 copy_register_state(dst_reg, src_reg); 15717 if (!no_sext) 15718 dst_reg->id = 0; 15719 dst_reg->live |= REG_LIVE_WRITTEN; 15720 dst_reg->subreg_def = env->insn_idx + 1; 15721 coerce_subreg_to_size_sx(dst_reg, insn->off >> 3); 15722 } 15723 } else { 15724 mark_reg_unknown(env, regs, 15725 insn->dst_reg); 15726 } 15727 zext_32_to_64(dst_reg); 15728 reg_bounds_sync(dst_reg); 15729 } 15730 } else { 15731 /* case: R = imm 15732 * remember the value we stored into this reg 15733 */ 15734 /* clear any state __mark_reg_known doesn't set */ 15735 mark_reg_unknown(env, regs, insn->dst_reg); 15736 regs[insn->dst_reg].type = SCALAR_VALUE; 15737 if (BPF_CLASS(insn->code) == BPF_ALU64) { 15738 __mark_reg_known(regs + insn->dst_reg, 15739 insn->imm); 15740 } else { 15741 __mark_reg_known(regs + insn->dst_reg, 15742 (u32)insn->imm); 15743 } 15744 } 15745 15746 } else if (opcode > BPF_END) { 15747 verbose(env, "invalid BPF_ALU opcode %x\n", opcode); 15748 return -EINVAL; 15749 15750 } else { /* all other ALU ops: and, sub, xor, add, ... */ 15751 15752 if (BPF_SRC(insn->code) == BPF_X) { 15753 if (insn->imm != 0 || insn->off > 1 || 15754 (insn->off == 1 && opcode != BPF_MOD && opcode != BPF_DIV)) { 15755 verbose(env, "BPF_ALU uses reserved fields\n"); 15756 return -EINVAL; 15757 } 15758 /* check src1 operand */ 15759 err = check_reg_arg(env, insn->src_reg, SRC_OP); 15760 if (err) 15761 return err; 15762 } else { 15763 if (insn->src_reg != BPF_REG_0 || insn->off > 1 || 15764 (insn->off == 1 && opcode != BPF_MOD && opcode != BPF_DIV)) { 15765 verbose(env, "BPF_ALU uses reserved fields\n"); 15766 return -EINVAL; 15767 } 15768 } 15769 15770 /* check src2 operand */ 15771 err = check_reg_arg(env, insn->dst_reg, SRC_OP); 15772 if (err) 15773 return err; 15774 15775 if ((opcode == BPF_MOD || opcode == BPF_DIV) && 15776 BPF_SRC(insn->code) == BPF_K && insn->imm == 0) { 15777 verbose(env, "div by zero\n"); 15778 return -EINVAL; 15779 } 15780 15781 if ((opcode == BPF_LSH || opcode == BPF_RSH || 15782 opcode == BPF_ARSH) && BPF_SRC(insn->code) == BPF_K) { 15783 int size = BPF_CLASS(insn->code) == BPF_ALU64 ? 64 : 32; 15784 15785 if (insn->imm < 0 || insn->imm >= size) { 15786 verbose(env, "invalid shift %d\n", insn->imm); 15787 return -EINVAL; 15788 } 15789 } 15790 15791 /* check dest operand */ 15792 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK); 15793 err = err ?: adjust_reg_min_max_vals(env, insn); 15794 if (err) 15795 return err; 15796 } 15797 15798 return reg_bounds_sanity_check(env, ®s[insn->dst_reg], "alu"); 15799 } 15800 15801 static void find_good_pkt_pointers(struct bpf_verifier_state *vstate, 15802 struct bpf_reg_state *dst_reg, 15803 enum bpf_reg_type type, 15804 bool range_right_open) 15805 { 15806 struct bpf_func_state *state; 15807 struct bpf_reg_state *reg; 15808 int new_range; 15809 15810 if (dst_reg->off < 0 || 15811 (dst_reg->off == 0 && range_right_open)) 15812 /* This doesn't give us any range */ 15813 return; 15814 15815 if (dst_reg->umax_value > MAX_PACKET_OFF || 15816 dst_reg->umax_value + dst_reg->off > MAX_PACKET_OFF) 15817 /* Risk of overflow. For instance, ptr + (1<<63) may be less 15818 * than pkt_end, but that's because it's also less than pkt. 15819 */ 15820 return; 15821 15822 new_range = dst_reg->off; 15823 if (range_right_open) 15824 new_range++; 15825 15826 /* Examples for register markings: 15827 * 15828 * pkt_data in dst register: 15829 * 15830 * r2 = r3; 15831 * r2 += 8; 15832 * if (r2 > pkt_end) goto <handle exception> 15833 * <access okay> 15834 * 15835 * r2 = r3; 15836 * r2 += 8; 15837 * if (r2 < pkt_end) goto <access okay> 15838 * <handle exception> 15839 * 15840 * Where: 15841 * r2 == dst_reg, pkt_end == src_reg 15842 * r2=pkt(id=n,off=8,r=0) 15843 * r3=pkt(id=n,off=0,r=0) 15844 * 15845 * pkt_data in src register: 15846 * 15847 * r2 = r3; 15848 * r2 += 8; 15849 * if (pkt_end >= r2) goto <access okay> 15850 * <handle exception> 15851 * 15852 * r2 = r3; 15853 * r2 += 8; 15854 * if (pkt_end <= r2) goto <handle exception> 15855 * <access okay> 15856 * 15857 * Where: 15858 * pkt_end == dst_reg, r2 == src_reg 15859 * r2=pkt(id=n,off=8,r=0) 15860 * r3=pkt(id=n,off=0,r=0) 15861 * 15862 * Find register r3 and mark its range as r3=pkt(id=n,off=0,r=8) 15863 * or r3=pkt(id=n,off=0,r=8-1), so that range of bytes [r3, r3 + 8) 15864 * and [r3, r3 + 8-1) respectively is safe to access depending on 15865 * the check. 15866 */ 15867 15868 /* If our ids match, then we must have the same max_value. And we 15869 * don't care about the other reg's fixed offset, since if it's too big 15870 * the range won't allow anything. 15871 * dst_reg->off is known < MAX_PACKET_OFF, therefore it fits in a u16. 15872 */ 15873 bpf_for_each_reg_in_vstate(vstate, state, reg, ({ 15874 if (reg->type == type && reg->id == dst_reg->id) 15875 /* keep the maximum range already checked */ 15876 reg->range = max(reg->range, new_range); 15877 })); 15878 } 15879 15880 /* 15881 * <reg1> <op> <reg2>, currently assuming reg2 is a constant 15882 */ 15883 static int is_scalar_branch_taken(struct bpf_reg_state *reg1, struct bpf_reg_state *reg2, 15884 u8 opcode, bool is_jmp32) 15885 { 15886 struct tnum t1 = is_jmp32 ? tnum_subreg(reg1->var_off) : reg1->var_off; 15887 struct tnum t2 = is_jmp32 ? tnum_subreg(reg2->var_off) : reg2->var_off; 15888 u64 umin1 = is_jmp32 ? (u64)reg1->u32_min_value : reg1->umin_value; 15889 u64 umax1 = is_jmp32 ? (u64)reg1->u32_max_value : reg1->umax_value; 15890 s64 smin1 = is_jmp32 ? (s64)reg1->s32_min_value : reg1->smin_value; 15891 s64 smax1 = is_jmp32 ? (s64)reg1->s32_max_value : reg1->smax_value; 15892 u64 umin2 = is_jmp32 ? (u64)reg2->u32_min_value : reg2->umin_value; 15893 u64 umax2 = is_jmp32 ? (u64)reg2->u32_max_value : reg2->umax_value; 15894 s64 smin2 = is_jmp32 ? (s64)reg2->s32_min_value : reg2->smin_value; 15895 s64 smax2 = is_jmp32 ? (s64)reg2->s32_max_value : reg2->smax_value; 15896 15897 switch (opcode) { 15898 case BPF_JEQ: 15899 /* constants, umin/umax and smin/smax checks would be 15900 * redundant in this case because they all should match 15901 */ 15902 if (tnum_is_const(t1) && tnum_is_const(t2)) 15903 return t1.value == t2.value; 15904 /* non-overlapping ranges */ 15905 if (umin1 > umax2 || umax1 < umin2) 15906 return 0; 15907 if (smin1 > smax2 || smax1 < smin2) 15908 return 0; 15909 if (!is_jmp32) { 15910 /* if 64-bit ranges are inconclusive, see if we can 15911 * utilize 32-bit subrange knowledge to eliminate 15912 * branches that can't be taken a priori 15913 */ 15914 if (reg1->u32_min_value > reg2->u32_max_value || 15915 reg1->u32_max_value < reg2->u32_min_value) 15916 return 0; 15917 if (reg1->s32_min_value > reg2->s32_max_value || 15918 reg1->s32_max_value < reg2->s32_min_value) 15919 return 0; 15920 } 15921 break; 15922 case BPF_JNE: 15923 /* constants, umin/umax and smin/smax checks would be 15924 * redundant in this case because they all should match 15925 */ 15926 if (tnum_is_const(t1) && tnum_is_const(t2)) 15927 return t1.value != t2.value; 15928 /* non-overlapping ranges */ 15929 if (umin1 > umax2 || umax1 < umin2) 15930 return 1; 15931 if (smin1 > smax2 || smax1 < smin2) 15932 return 1; 15933 if (!is_jmp32) { 15934 /* if 64-bit ranges are inconclusive, see if we can 15935 * utilize 32-bit subrange knowledge to eliminate 15936 * branches that can't be taken a priori 15937 */ 15938 if (reg1->u32_min_value > reg2->u32_max_value || 15939 reg1->u32_max_value < reg2->u32_min_value) 15940 return 1; 15941 if (reg1->s32_min_value > reg2->s32_max_value || 15942 reg1->s32_max_value < reg2->s32_min_value) 15943 return 1; 15944 } 15945 break; 15946 case BPF_JSET: 15947 if (!is_reg_const(reg2, is_jmp32)) { 15948 swap(reg1, reg2); 15949 swap(t1, t2); 15950 } 15951 if (!is_reg_const(reg2, is_jmp32)) 15952 return -1; 15953 if ((~t1.mask & t1.value) & t2.value) 15954 return 1; 15955 if (!((t1.mask | t1.value) & t2.value)) 15956 return 0; 15957 break; 15958 case BPF_JGT: 15959 if (umin1 > umax2) 15960 return 1; 15961 else if (umax1 <= umin2) 15962 return 0; 15963 break; 15964 case BPF_JSGT: 15965 if (smin1 > smax2) 15966 return 1; 15967 else if (smax1 <= smin2) 15968 return 0; 15969 break; 15970 case BPF_JLT: 15971 if (umax1 < umin2) 15972 return 1; 15973 else if (umin1 >= umax2) 15974 return 0; 15975 break; 15976 case BPF_JSLT: 15977 if (smax1 < smin2) 15978 return 1; 15979 else if (smin1 >= smax2) 15980 return 0; 15981 break; 15982 case BPF_JGE: 15983 if (umin1 >= umax2) 15984 return 1; 15985 else if (umax1 < umin2) 15986 return 0; 15987 break; 15988 case BPF_JSGE: 15989 if (smin1 >= smax2) 15990 return 1; 15991 else if (smax1 < smin2) 15992 return 0; 15993 break; 15994 case BPF_JLE: 15995 if (umax1 <= umin2) 15996 return 1; 15997 else if (umin1 > umax2) 15998 return 0; 15999 break; 16000 case BPF_JSLE: 16001 if (smax1 <= smin2) 16002 return 1; 16003 else if (smin1 > smax2) 16004 return 0; 16005 break; 16006 } 16007 16008 return -1; 16009 } 16010 16011 static int flip_opcode(u32 opcode) 16012 { 16013 /* How can we transform "a <op> b" into "b <op> a"? */ 16014 static const u8 opcode_flip[16] = { 16015 /* these stay the same */ 16016 [BPF_JEQ >> 4] = BPF_JEQ, 16017 [BPF_JNE >> 4] = BPF_JNE, 16018 [BPF_JSET >> 4] = BPF_JSET, 16019 /* these swap "lesser" and "greater" (L and G in the opcodes) */ 16020 [BPF_JGE >> 4] = BPF_JLE, 16021 [BPF_JGT >> 4] = BPF_JLT, 16022 [BPF_JLE >> 4] = BPF_JGE, 16023 [BPF_JLT >> 4] = BPF_JGT, 16024 [BPF_JSGE >> 4] = BPF_JSLE, 16025 [BPF_JSGT >> 4] = BPF_JSLT, 16026 [BPF_JSLE >> 4] = BPF_JSGE, 16027 [BPF_JSLT >> 4] = BPF_JSGT 16028 }; 16029 return opcode_flip[opcode >> 4]; 16030 } 16031 16032 static int is_pkt_ptr_branch_taken(struct bpf_reg_state *dst_reg, 16033 struct bpf_reg_state *src_reg, 16034 u8 opcode) 16035 { 16036 struct bpf_reg_state *pkt; 16037 16038 if (src_reg->type == PTR_TO_PACKET_END) { 16039 pkt = dst_reg; 16040 } else if (dst_reg->type == PTR_TO_PACKET_END) { 16041 pkt = src_reg; 16042 opcode = flip_opcode(opcode); 16043 } else { 16044 return -1; 16045 } 16046 16047 if (pkt->range >= 0) 16048 return -1; 16049 16050 switch (opcode) { 16051 case BPF_JLE: 16052 /* pkt <= pkt_end */ 16053 fallthrough; 16054 case BPF_JGT: 16055 /* pkt > pkt_end */ 16056 if (pkt->range == BEYOND_PKT_END) 16057 /* pkt has at last one extra byte beyond pkt_end */ 16058 return opcode == BPF_JGT; 16059 break; 16060 case BPF_JLT: 16061 /* pkt < pkt_end */ 16062 fallthrough; 16063 case BPF_JGE: 16064 /* pkt >= pkt_end */ 16065 if (pkt->range == BEYOND_PKT_END || pkt->range == AT_PKT_END) 16066 return opcode == BPF_JGE; 16067 break; 16068 } 16069 return -1; 16070 } 16071 16072 /* compute branch direction of the expression "if (<reg1> opcode <reg2>) goto target;" 16073 * and return: 16074 * 1 - branch will be taken and "goto target" will be executed 16075 * 0 - branch will not be taken and fall-through to next insn 16076 * -1 - unknown. Example: "if (reg1 < 5)" is unknown when register value 16077 * range [0,10] 16078 */ 16079 static int is_branch_taken(struct bpf_reg_state *reg1, struct bpf_reg_state *reg2, 16080 u8 opcode, bool is_jmp32) 16081 { 16082 if (reg_is_pkt_pointer_any(reg1) && reg_is_pkt_pointer_any(reg2) && !is_jmp32) 16083 return is_pkt_ptr_branch_taken(reg1, reg2, opcode); 16084 16085 if (__is_pointer_value(false, reg1) || __is_pointer_value(false, reg2)) { 16086 u64 val; 16087 16088 /* arrange that reg2 is a scalar, and reg1 is a pointer */ 16089 if (!is_reg_const(reg2, is_jmp32)) { 16090 opcode = flip_opcode(opcode); 16091 swap(reg1, reg2); 16092 } 16093 /* and ensure that reg2 is a constant */ 16094 if (!is_reg_const(reg2, is_jmp32)) 16095 return -1; 16096 16097 if (!reg_not_null(reg1)) 16098 return -1; 16099 16100 /* If pointer is valid tests against zero will fail so we can 16101 * use this to direct branch taken. 16102 */ 16103 val = reg_const_value(reg2, is_jmp32); 16104 if (val != 0) 16105 return -1; 16106 16107 switch (opcode) { 16108 case BPF_JEQ: 16109 return 0; 16110 case BPF_JNE: 16111 return 1; 16112 default: 16113 return -1; 16114 } 16115 } 16116 16117 /* now deal with two scalars, but not necessarily constants */ 16118 return is_scalar_branch_taken(reg1, reg2, opcode, is_jmp32); 16119 } 16120 16121 /* Opcode that corresponds to a *false* branch condition. 16122 * E.g., if r1 < r2, then reverse (false) condition is r1 >= r2 16123 */ 16124 static u8 rev_opcode(u8 opcode) 16125 { 16126 switch (opcode) { 16127 case BPF_JEQ: return BPF_JNE; 16128 case BPF_JNE: return BPF_JEQ; 16129 /* JSET doesn't have it's reverse opcode in BPF, so add 16130 * BPF_X flag to denote the reverse of that operation 16131 */ 16132 case BPF_JSET: return BPF_JSET | BPF_X; 16133 case BPF_JSET | BPF_X: return BPF_JSET; 16134 case BPF_JGE: return BPF_JLT; 16135 case BPF_JGT: return BPF_JLE; 16136 case BPF_JLE: return BPF_JGT; 16137 case BPF_JLT: return BPF_JGE; 16138 case BPF_JSGE: return BPF_JSLT; 16139 case BPF_JSGT: return BPF_JSLE; 16140 case BPF_JSLE: return BPF_JSGT; 16141 case BPF_JSLT: return BPF_JSGE; 16142 default: return 0; 16143 } 16144 } 16145 16146 /* Refine range knowledge for <reg1> <op> <reg>2 conditional operation. */ 16147 static void regs_refine_cond_op(struct bpf_reg_state *reg1, struct bpf_reg_state *reg2, 16148 u8 opcode, bool is_jmp32) 16149 { 16150 struct tnum t; 16151 u64 val; 16152 16153 /* In case of GE/GT/SGE/JST, reuse LE/LT/SLE/SLT logic from below */ 16154 switch (opcode) { 16155 case BPF_JGE: 16156 case BPF_JGT: 16157 case BPF_JSGE: 16158 case BPF_JSGT: 16159 opcode = flip_opcode(opcode); 16160 swap(reg1, reg2); 16161 break; 16162 default: 16163 break; 16164 } 16165 16166 switch (opcode) { 16167 case BPF_JEQ: 16168 if (is_jmp32) { 16169 reg1->u32_min_value = max(reg1->u32_min_value, reg2->u32_min_value); 16170 reg1->u32_max_value = min(reg1->u32_max_value, reg2->u32_max_value); 16171 reg1->s32_min_value = max(reg1->s32_min_value, reg2->s32_min_value); 16172 reg1->s32_max_value = min(reg1->s32_max_value, reg2->s32_max_value); 16173 reg2->u32_min_value = reg1->u32_min_value; 16174 reg2->u32_max_value = reg1->u32_max_value; 16175 reg2->s32_min_value = reg1->s32_min_value; 16176 reg2->s32_max_value = reg1->s32_max_value; 16177 16178 t = tnum_intersect(tnum_subreg(reg1->var_off), tnum_subreg(reg2->var_off)); 16179 reg1->var_off = tnum_with_subreg(reg1->var_off, t); 16180 reg2->var_off = tnum_with_subreg(reg2->var_off, t); 16181 } else { 16182 reg1->umin_value = max(reg1->umin_value, reg2->umin_value); 16183 reg1->umax_value = min(reg1->umax_value, reg2->umax_value); 16184 reg1->smin_value = max(reg1->smin_value, reg2->smin_value); 16185 reg1->smax_value = min(reg1->smax_value, reg2->smax_value); 16186 reg2->umin_value = reg1->umin_value; 16187 reg2->umax_value = reg1->umax_value; 16188 reg2->smin_value = reg1->smin_value; 16189 reg2->smax_value = reg1->smax_value; 16190 16191 reg1->var_off = tnum_intersect(reg1->var_off, reg2->var_off); 16192 reg2->var_off = reg1->var_off; 16193 } 16194 break; 16195 case BPF_JNE: 16196 if (!is_reg_const(reg2, is_jmp32)) 16197 swap(reg1, reg2); 16198 if (!is_reg_const(reg2, is_jmp32)) 16199 break; 16200 16201 /* try to recompute the bound of reg1 if reg2 is a const and 16202 * is exactly the edge of reg1. 16203 */ 16204 val = reg_const_value(reg2, is_jmp32); 16205 if (is_jmp32) { 16206 /* u32_min_value is not equal to 0xffffffff at this point, 16207 * because otherwise u32_max_value is 0xffffffff as well, 16208 * in such a case both reg1 and reg2 would be constants, 16209 * jump would be predicted and reg_set_min_max() won't 16210 * be called. 16211 * 16212 * Same reasoning works for all {u,s}{min,max}{32,64} cases 16213 * below. 16214 */ 16215 if (reg1->u32_min_value == (u32)val) 16216 reg1->u32_min_value++; 16217 if (reg1->u32_max_value == (u32)val) 16218 reg1->u32_max_value--; 16219 if (reg1->s32_min_value == (s32)val) 16220 reg1->s32_min_value++; 16221 if (reg1->s32_max_value == (s32)val) 16222 reg1->s32_max_value--; 16223 } else { 16224 if (reg1->umin_value == (u64)val) 16225 reg1->umin_value++; 16226 if (reg1->umax_value == (u64)val) 16227 reg1->umax_value--; 16228 if (reg1->smin_value == (s64)val) 16229 reg1->smin_value++; 16230 if (reg1->smax_value == (s64)val) 16231 reg1->smax_value--; 16232 } 16233 break; 16234 case BPF_JSET: 16235 if (!is_reg_const(reg2, is_jmp32)) 16236 swap(reg1, reg2); 16237 if (!is_reg_const(reg2, is_jmp32)) 16238 break; 16239 val = reg_const_value(reg2, is_jmp32); 16240 /* BPF_JSET (i.e., TRUE branch, *not* BPF_JSET | BPF_X) 16241 * requires single bit to learn something useful. E.g., if we 16242 * know that `r1 & 0x3` is true, then which bits (0, 1, or both) 16243 * are actually set? We can learn something definite only if 16244 * it's a single-bit value to begin with. 16245 * 16246 * BPF_JSET | BPF_X (i.e., negation of BPF_JSET) doesn't have 16247 * this restriction. I.e., !(r1 & 0x3) means neither bit 0 nor 16248 * bit 1 is set, which we can readily use in adjustments. 16249 */ 16250 if (!is_power_of_2(val)) 16251 break; 16252 if (is_jmp32) { 16253 t = tnum_or(tnum_subreg(reg1->var_off), tnum_const(val)); 16254 reg1->var_off = tnum_with_subreg(reg1->var_off, t); 16255 } else { 16256 reg1->var_off = tnum_or(reg1->var_off, tnum_const(val)); 16257 } 16258 break; 16259 case BPF_JSET | BPF_X: /* reverse of BPF_JSET, see rev_opcode() */ 16260 if (!is_reg_const(reg2, is_jmp32)) 16261 swap(reg1, reg2); 16262 if (!is_reg_const(reg2, is_jmp32)) 16263 break; 16264 val = reg_const_value(reg2, is_jmp32); 16265 /* Forget the ranges before narrowing tnums, to avoid invariant 16266 * violations if we're on a dead branch. 16267 */ 16268 __mark_reg_unbounded(reg1); 16269 if (is_jmp32) { 16270 t = tnum_and(tnum_subreg(reg1->var_off), tnum_const(~val)); 16271 reg1->var_off = tnum_with_subreg(reg1->var_off, t); 16272 } else { 16273 reg1->var_off = tnum_and(reg1->var_off, tnum_const(~val)); 16274 } 16275 break; 16276 case BPF_JLE: 16277 if (is_jmp32) { 16278 reg1->u32_max_value = min(reg1->u32_max_value, reg2->u32_max_value); 16279 reg2->u32_min_value = max(reg1->u32_min_value, reg2->u32_min_value); 16280 } else { 16281 reg1->umax_value = min(reg1->umax_value, reg2->umax_value); 16282 reg2->umin_value = max(reg1->umin_value, reg2->umin_value); 16283 } 16284 break; 16285 case BPF_JLT: 16286 if (is_jmp32) { 16287 reg1->u32_max_value = min(reg1->u32_max_value, reg2->u32_max_value - 1); 16288 reg2->u32_min_value = max(reg1->u32_min_value + 1, reg2->u32_min_value); 16289 } else { 16290 reg1->umax_value = min(reg1->umax_value, reg2->umax_value - 1); 16291 reg2->umin_value = max(reg1->umin_value + 1, reg2->umin_value); 16292 } 16293 break; 16294 case BPF_JSLE: 16295 if (is_jmp32) { 16296 reg1->s32_max_value = min(reg1->s32_max_value, reg2->s32_max_value); 16297 reg2->s32_min_value = max(reg1->s32_min_value, reg2->s32_min_value); 16298 } else { 16299 reg1->smax_value = min(reg1->smax_value, reg2->smax_value); 16300 reg2->smin_value = max(reg1->smin_value, reg2->smin_value); 16301 } 16302 break; 16303 case BPF_JSLT: 16304 if (is_jmp32) { 16305 reg1->s32_max_value = min(reg1->s32_max_value, reg2->s32_max_value - 1); 16306 reg2->s32_min_value = max(reg1->s32_min_value + 1, reg2->s32_min_value); 16307 } else { 16308 reg1->smax_value = min(reg1->smax_value, reg2->smax_value - 1); 16309 reg2->smin_value = max(reg1->smin_value + 1, reg2->smin_value); 16310 } 16311 break; 16312 default: 16313 return; 16314 } 16315 } 16316 16317 /* Adjusts the register min/max values in the case that the dst_reg and 16318 * src_reg are both SCALAR_VALUE registers (or we are simply doing a BPF_K 16319 * check, in which case we have a fake SCALAR_VALUE representing insn->imm). 16320 * Technically we can do similar adjustments for pointers to the same object, 16321 * but we don't support that right now. 16322 */ 16323 static int reg_set_min_max(struct bpf_verifier_env *env, 16324 struct bpf_reg_state *true_reg1, 16325 struct bpf_reg_state *true_reg2, 16326 struct bpf_reg_state *false_reg1, 16327 struct bpf_reg_state *false_reg2, 16328 u8 opcode, bool is_jmp32) 16329 { 16330 int err; 16331 16332 /* If either register is a pointer, we can't learn anything about its 16333 * variable offset from the compare (unless they were a pointer into 16334 * the same object, but we don't bother with that). 16335 */ 16336 if (false_reg1->type != SCALAR_VALUE || false_reg2->type != SCALAR_VALUE) 16337 return 0; 16338 16339 /* fallthrough (FALSE) branch */ 16340 regs_refine_cond_op(false_reg1, false_reg2, rev_opcode(opcode), is_jmp32); 16341 reg_bounds_sync(false_reg1); 16342 reg_bounds_sync(false_reg2); 16343 16344 /* jump (TRUE) branch */ 16345 regs_refine_cond_op(true_reg1, true_reg2, opcode, is_jmp32); 16346 reg_bounds_sync(true_reg1); 16347 reg_bounds_sync(true_reg2); 16348 16349 err = reg_bounds_sanity_check(env, true_reg1, "true_reg1"); 16350 err = err ?: reg_bounds_sanity_check(env, true_reg2, "true_reg2"); 16351 err = err ?: reg_bounds_sanity_check(env, false_reg1, "false_reg1"); 16352 err = err ?: reg_bounds_sanity_check(env, false_reg2, "false_reg2"); 16353 return err; 16354 } 16355 16356 static void mark_ptr_or_null_reg(struct bpf_func_state *state, 16357 struct bpf_reg_state *reg, u32 id, 16358 bool is_null) 16359 { 16360 if (type_may_be_null(reg->type) && reg->id == id && 16361 (is_rcu_reg(reg) || !WARN_ON_ONCE(!reg->id))) { 16362 /* Old offset (both fixed and variable parts) should have been 16363 * known-zero, because we don't allow pointer arithmetic on 16364 * pointers that might be NULL. If we see this happening, don't 16365 * convert the register. 16366 * 16367 * But in some cases, some helpers that return local kptrs 16368 * advance offset for the returned pointer. In those cases, it 16369 * is fine to expect to see reg->off. 16370 */ 16371 if (WARN_ON_ONCE(reg->smin_value || reg->smax_value || !tnum_equals_const(reg->var_off, 0))) 16372 return; 16373 if (!(type_is_ptr_alloc_obj(reg->type) || type_is_non_owning_ref(reg->type)) && 16374 WARN_ON_ONCE(reg->off)) 16375 return; 16376 16377 if (is_null) { 16378 reg->type = SCALAR_VALUE; 16379 /* We don't need id and ref_obj_id from this point 16380 * onwards anymore, thus we should better reset it, 16381 * so that state pruning has chances to take effect. 16382 */ 16383 reg->id = 0; 16384 reg->ref_obj_id = 0; 16385 16386 return; 16387 } 16388 16389 mark_ptr_not_null_reg(reg); 16390 16391 if (!reg_may_point_to_spin_lock(reg)) { 16392 /* For not-NULL ptr, reg->ref_obj_id will be reset 16393 * in release_reference(). 16394 * 16395 * reg->id is still used by spin_lock ptr. Other 16396 * than spin_lock ptr type, reg->id can be reset. 16397 */ 16398 reg->id = 0; 16399 } 16400 } 16401 } 16402 16403 /* The logic is similar to find_good_pkt_pointers(), both could eventually 16404 * be folded together at some point. 16405 */ 16406 static void mark_ptr_or_null_regs(struct bpf_verifier_state *vstate, u32 regno, 16407 bool is_null) 16408 { 16409 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 16410 struct bpf_reg_state *regs = state->regs, *reg; 16411 u32 ref_obj_id = regs[regno].ref_obj_id; 16412 u32 id = regs[regno].id; 16413 16414 if (ref_obj_id && ref_obj_id == id && is_null) 16415 /* regs[regno] is in the " == NULL" branch. 16416 * No one could have freed the reference state before 16417 * doing the NULL check. 16418 */ 16419 WARN_ON_ONCE(release_reference_nomark(vstate, id)); 16420 16421 bpf_for_each_reg_in_vstate(vstate, state, reg, ({ 16422 mark_ptr_or_null_reg(state, reg, id, is_null); 16423 })); 16424 } 16425 16426 static bool try_match_pkt_pointers(const struct bpf_insn *insn, 16427 struct bpf_reg_state *dst_reg, 16428 struct bpf_reg_state *src_reg, 16429 struct bpf_verifier_state *this_branch, 16430 struct bpf_verifier_state *other_branch) 16431 { 16432 if (BPF_SRC(insn->code) != BPF_X) 16433 return false; 16434 16435 /* Pointers are always 64-bit. */ 16436 if (BPF_CLASS(insn->code) == BPF_JMP32) 16437 return false; 16438 16439 switch (BPF_OP(insn->code)) { 16440 case BPF_JGT: 16441 if ((dst_reg->type == PTR_TO_PACKET && 16442 src_reg->type == PTR_TO_PACKET_END) || 16443 (dst_reg->type == PTR_TO_PACKET_META && 16444 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) { 16445 /* pkt_data' > pkt_end, pkt_meta' > pkt_data */ 16446 find_good_pkt_pointers(this_branch, dst_reg, 16447 dst_reg->type, false); 16448 mark_pkt_end(other_branch, insn->dst_reg, true); 16449 } else if ((dst_reg->type == PTR_TO_PACKET_END && 16450 src_reg->type == PTR_TO_PACKET) || 16451 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) && 16452 src_reg->type == PTR_TO_PACKET_META)) { 16453 /* pkt_end > pkt_data', pkt_data > pkt_meta' */ 16454 find_good_pkt_pointers(other_branch, src_reg, 16455 src_reg->type, true); 16456 mark_pkt_end(this_branch, insn->src_reg, false); 16457 } else { 16458 return false; 16459 } 16460 break; 16461 case BPF_JLT: 16462 if ((dst_reg->type == PTR_TO_PACKET && 16463 src_reg->type == PTR_TO_PACKET_END) || 16464 (dst_reg->type == PTR_TO_PACKET_META && 16465 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) { 16466 /* pkt_data' < pkt_end, pkt_meta' < pkt_data */ 16467 find_good_pkt_pointers(other_branch, dst_reg, 16468 dst_reg->type, true); 16469 mark_pkt_end(this_branch, insn->dst_reg, false); 16470 } else if ((dst_reg->type == PTR_TO_PACKET_END && 16471 src_reg->type == PTR_TO_PACKET) || 16472 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) && 16473 src_reg->type == PTR_TO_PACKET_META)) { 16474 /* pkt_end < pkt_data', pkt_data > pkt_meta' */ 16475 find_good_pkt_pointers(this_branch, src_reg, 16476 src_reg->type, false); 16477 mark_pkt_end(other_branch, insn->src_reg, true); 16478 } else { 16479 return false; 16480 } 16481 break; 16482 case BPF_JGE: 16483 if ((dst_reg->type == PTR_TO_PACKET && 16484 src_reg->type == PTR_TO_PACKET_END) || 16485 (dst_reg->type == PTR_TO_PACKET_META && 16486 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) { 16487 /* pkt_data' >= pkt_end, pkt_meta' >= pkt_data */ 16488 find_good_pkt_pointers(this_branch, dst_reg, 16489 dst_reg->type, true); 16490 mark_pkt_end(other_branch, insn->dst_reg, false); 16491 } else if ((dst_reg->type == PTR_TO_PACKET_END && 16492 src_reg->type == PTR_TO_PACKET) || 16493 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) && 16494 src_reg->type == PTR_TO_PACKET_META)) { 16495 /* pkt_end >= pkt_data', pkt_data >= pkt_meta' */ 16496 find_good_pkt_pointers(other_branch, src_reg, 16497 src_reg->type, false); 16498 mark_pkt_end(this_branch, insn->src_reg, true); 16499 } else { 16500 return false; 16501 } 16502 break; 16503 case BPF_JLE: 16504 if ((dst_reg->type == PTR_TO_PACKET && 16505 src_reg->type == PTR_TO_PACKET_END) || 16506 (dst_reg->type == PTR_TO_PACKET_META && 16507 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) { 16508 /* pkt_data' <= pkt_end, pkt_meta' <= pkt_data */ 16509 find_good_pkt_pointers(other_branch, dst_reg, 16510 dst_reg->type, false); 16511 mark_pkt_end(this_branch, insn->dst_reg, true); 16512 } else if ((dst_reg->type == PTR_TO_PACKET_END && 16513 src_reg->type == PTR_TO_PACKET) || 16514 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) && 16515 src_reg->type == PTR_TO_PACKET_META)) { 16516 /* pkt_end <= pkt_data', pkt_data <= pkt_meta' */ 16517 find_good_pkt_pointers(this_branch, src_reg, 16518 src_reg->type, true); 16519 mark_pkt_end(other_branch, insn->src_reg, false); 16520 } else { 16521 return false; 16522 } 16523 break; 16524 default: 16525 return false; 16526 } 16527 16528 return true; 16529 } 16530 16531 static void __collect_linked_regs(struct linked_regs *reg_set, struct bpf_reg_state *reg, 16532 u32 id, u32 frameno, u32 spi_or_reg, bool is_reg) 16533 { 16534 struct linked_reg *e; 16535 16536 if (reg->type != SCALAR_VALUE || (reg->id & ~BPF_ADD_CONST) != id) 16537 return; 16538 16539 e = linked_regs_push(reg_set); 16540 if (e) { 16541 e->frameno = frameno; 16542 e->is_reg = is_reg; 16543 e->regno = spi_or_reg; 16544 } else { 16545 reg->id = 0; 16546 } 16547 } 16548 16549 /* For all R being scalar registers or spilled scalar registers 16550 * in verifier state, save R in linked_regs if R->id == id. 16551 * If there are too many Rs sharing same id, reset id for leftover Rs. 16552 */ 16553 static void collect_linked_regs(struct bpf_verifier_state *vstate, u32 id, 16554 struct linked_regs *linked_regs) 16555 { 16556 struct bpf_func_state *func; 16557 struct bpf_reg_state *reg; 16558 int i, j; 16559 16560 id = id & ~BPF_ADD_CONST; 16561 for (i = vstate->curframe; i >= 0; i--) { 16562 func = vstate->frame[i]; 16563 for (j = 0; j < BPF_REG_FP; j++) { 16564 reg = &func->regs[j]; 16565 __collect_linked_regs(linked_regs, reg, id, i, j, true); 16566 } 16567 for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) { 16568 if (!is_spilled_reg(&func->stack[j])) 16569 continue; 16570 reg = &func->stack[j].spilled_ptr; 16571 __collect_linked_regs(linked_regs, reg, id, i, j, false); 16572 } 16573 } 16574 } 16575 16576 /* For all R in linked_regs, copy known_reg range into R 16577 * if R->id == known_reg->id. 16578 */ 16579 static void sync_linked_regs(struct bpf_verifier_state *vstate, struct bpf_reg_state *known_reg, 16580 struct linked_regs *linked_regs) 16581 { 16582 struct bpf_reg_state fake_reg; 16583 struct bpf_reg_state *reg; 16584 struct linked_reg *e; 16585 int i; 16586 16587 for (i = 0; i < linked_regs->cnt; ++i) { 16588 e = &linked_regs->entries[i]; 16589 reg = e->is_reg ? &vstate->frame[e->frameno]->regs[e->regno] 16590 : &vstate->frame[e->frameno]->stack[e->spi].spilled_ptr; 16591 if (reg->type != SCALAR_VALUE || reg == known_reg) 16592 continue; 16593 if ((reg->id & ~BPF_ADD_CONST) != (known_reg->id & ~BPF_ADD_CONST)) 16594 continue; 16595 if ((!(reg->id & BPF_ADD_CONST) && !(known_reg->id & BPF_ADD_CONST)) || 16596 reg->off == known_reg->off) { 16597 s32 saved_subreg_def = reg->subreg_def; 16598 16599 copy_register_state(reg, known_reg); 16600 reg->subreg_def = saved_subreg_def; 16601 } else { 16602 s32 saved_subreg_def = reg->subreg_def; 16603 s32 saved_off = reg->off; 16604 16605 fake_reg.type = SCALAR_VALUE; 16606 __mark_reg_known(&fake_reg, (s32)reg->off - (s32)known_reg->off); 16607 16608 /* reg = known_reg; reg += delta */ 16609 copy_register_state(reg, known_reg); 16610 /* 16611 * Must preserve off, id and add_const flag, 16612 * otherwise another sync_linked_regs() will be incorrect. 16613 */ 16614 reg->off = saved_off; 16615 reg->subreg_def = saved_subreg_def; 16616 16617 scalar32_min_max_add(reg, &fake_reg); 16618 scalar_min_max_add(reg, &fake_reg); 16619 reg->var_off = tnum_add(reg->var_off, fake_reg.var_off); 16620 } 16621 } 16622 } 16623 16624 static int check_cond_jmp_op(struct bpf_verifier_env *env, 16625 struct bpf_insn *insn, int *insn_idx) 16626 { 16627 struct bpf_verifier_state *this_branch = env->cur_state; 16628 struct bpf_verifier_state *other_branch; 16629 struct bpf_reg_state *regs = this_branch->frame[this_branch->curframe]->regs; 16630 struct bpf_reg_state *dst_reg, *other_branch_regs, *src_reg = NULL; 16631 struct bpf_reg_state *eq_branch_regs; 16632 struct linked_regs linked_regs = {}; 16633 u8 opcode = BPF_OP(insn->code); 16634 int insn_flags = 0; 16635 bool is_jmp32; 16636 int pred = -1; 16637 int err; 16638 16639 /* Only conditional jumps are expected to reach here. */ 16640 if (opcode == BPF_JA || opcode > BPF_JCOND) { 16641 verbose(env, "invalid BPF_JMP/JMP32 opcode %x\n", opcode); 16642 return -EINVAL; 16643 } 16644 16645 if (opcode == BPF_JCOND) { 16646 struct bpf_verifier_state *cur_st = env->cur_state, *queued_st, *prev_st; 16647 int idx = *insn_idx; 16648 16649 if (insn->code != (BPF_JMP | BPF_JCOND) || 16650 insn->src_reg != BPF_MAY_GOTO || 16651 insn->dst_reg || insn->imm) { 16652 verbose(env, "invalid may_goto imm %d\n", insn->imm); 16653 return -EINVAL; 16654 } 16655 prev_st = find_prev_entry(env, cur_st->parent, idx); 16656 16657 /* branch out 'fallthrough' insn as a new state to explore */ 16658 queued_st = push_stack(env, idx + 1, idx, false); 16659 if (!queued_st) 16660 return -ENOMEM; 16661 16662 queued_st->may_goto_depth++; 16663 if (prev_st) 16664 widen_imprecise_scalars(env, prev_st, queued_st); 16665 *insn_idx += insn->off; 16666 return 0; 16667 } 16668 16669 /* check src2 operand */ 16670 err = check_reg_arg(env, insn->dst_reg, SRC_OP); 16671 if (err) 16672 return err; 16673 16674 dst_reg = ®s[insn->dst_reg]; 16675 if (BPF_SRC(insn->code) == BPF_X) { 16676 if (insn->imm != 0) { 16677 verbose(env, "BPF_JMP/JMP32 uses reserved fields\n"); 16678 return -EINVAL; 16679 } 16680 16681 /* check src1 operand */ 16682 err = check_reg_arg(env, insn->src_reg, SRC_OP); 16683 if (err) 16684 return err; 16685 16686 src_reg = ®s[insn->src_reg]; 16687 if (!(reg_is_pkt_pointer_any(dst_reg) && reg_is_pkt_pointer_any(src_reg)) && 16688 is_pointer_value(env, insn->src_reg)) { 16689 verbose(env, "R%d pointer comparison prohibited\n", 16690 insn->src_reg); 16691 return -EACCES; 16692 } 16693 16694 if (src_reg->type == PTR_TO_STACK) 16695 insn_flags |= INSN_F_SRC_REG_STACK; 16696 if (dst_reg->type == PTR_TO_STACK) 16697 insn_flags |= INSN_F_DST_REG_STACK; 16698 } else { 16699 if (insn->src_reg != BPF_REG_0) { 16700 verbose(env, "BPF_JMP/JMP32 uses reserved fields\n"); 16701 return -EINVAL; 16702 } 16703 src_reg = &env->fake_reg[0]; 16704 memset(src_reg, 0, sizeof(*src_reg)); 16705 src_reg->type = SCALAR_VALUE; 16706 __mark_reg_known(src_reg, insn->imm); 16707 16708 if (dst_reg->type == PTR_TO_STACK) 16709 insn_flags |= INSN_F_DST_REG_STACK; 16710 } 16711 16712 if (insn_flags) { 16713 err = push_jmp_history(env, this_branch, insn_flags, 0); 16714 if (err) 16715 return err; 16716 } 16717 16718 is_jmp32 = BPF_CLASS(insn->code) == BPF_JMP32; 16719 pred = is_branch_taken(dst_reg, src_reg, opcode, is_jmp32); 16720 if (pred >= 0) { 16721 /* If we get here with a dst_reg pointer type it is because 16722 * above is_branch_taken() special cased the 0 comparison. 16723 */ 16724 if (!__is_pointer_value(false, dst_reg)) 16725 err = mark_chain_precision(env, insn->dst_reg); 16726 if (BPF_SRC(insn->code) == BPF_X && !err && 16727 !__is_pointer_value(false, src_reg)) 16728 err = mark_chain_precision(env, insn->src_reg); 16729 if (err) 16730 return err; 16731 } 16732 16733 if (pred == 1) { 16734 /* Only follow the goto, ignore fall-through. If needed, push 16735 * the fall-through branch for simulation under speculative 16736 * execution. 16737 */ 16738 if (!env->bypass_spec_v1 && 16739 !sanitize_speculative_path(env, insn, *insn_idx + 1, 16740 *insn_idx)) 16741 return -EFAULT; 16742 if (env->log.level & BPF_LOG_LEVEL) 16743 print_insn_state(env, this_branch, this_branch->curframe); 16744 *insn_idx += insn->off; 16745 return 0; 16746 } else if (pred == 0) { 16747 /* Only follow the fall-through branch, since that's where the 16748 * program will go. If needed, push the goto branch for 16749 * simulation under speculative execution. 16750 */ 16751 if (!env->bypass_spec_v1 && 16752 !sanitize_speculative_path(env, insn, 16753 *insn_idx + insn->off + 1, 16754 *insn_idx)) 16755 return -EFAULT; 16756 if (env->log.level & BPF_LOG_LEVEL) 16757 print_insn_state(env, this_branch, this_branch->curframe); 16758 return 0; 16759 } 16760 16761 /* Push scalar registers sharing same ID to jump history, 16762 * do this before creating 'other_branch', so that both 16763 * 'this_branch' and 'other_branch' share this history 16764 * if parent state is created. 16765 */ 16766 if (BPF_SRC(insn->code) == BPF_X && src_reg->type == SCALAR_VALUE && src_reg->id) 16767 collect_linked_regs(this_branch, src_reg->id, &linked_regs); 16768 if (dst_reg->type == SCALAR_VALUE && dst_reg->id) 16769 collect_linked_regs(this_branch, dst_reg->id, &linked_regs); 16770 if (linked_regs.cnt > 1) { 16771 err = push_jmp_history(env, this_branch, 0, linked_regs_pack(&linked_regs)); 16772 if (err) 16773 return err; 16774 } 16775 16776 other_branch = push_stack(env, *insn_idx + insn->off + 1, *insn_idx, 16777 false); 16778 if (!other_branch) 16779 return -EFAULT; 16780 other_branch_regs = other_branch->frame[other_branch->curframe]->regs; 16781 16782 if (BPF_SRC(insn->code) == BPF_X) { 16783 err = reg_set_min_max(env, 16784 &other_branch_regs[insn->dst_reg], 16785 &other_branch_regs[insn->src_reg], 16786 dst_reg, src_reg, opcode, is_jmp32); 16787 } else /* BPF_SRC(insn->code) == BPF_K */ { 16788 /* reg_set_min_max() can mangle the fake_reg. Make a copy 16789 * so that these are two different memory locations. The 16790 * src_reg is not used beyond here in context of K. 16791 */ 16792 memcpy(&env->fake_reg[1], &env->fake_reg[0], 16793 sizeof(env->fake_reg[0])); 16794 err = reg_set_min_max(env, 16795 &other_branch_regs[insn->dst_reg], 16796 &env->fake_reg[0], 16797 dst_reg, &env->fake_reg[1], 16798 opcode, is_jmp32); 16799 } 16800 if (err) 16801 return err; 16802 16803 if (BPF_SRC(insn->code) == BPF_X && 16804 src_reg->type == SCALAR_VALUE && src_reg->id && 16805 !WARN_ON_ONCE(src_reg->id != other_branch_regs[insn->src_reg].id)) { 16806 sync_linked_regs(this_branch, src_reg, &linked_regs); 16807 sync_linked_regs(other_branch, &other_branch_regs[insn->src_reg], &linked_regs); 16808 } 16809 if (dst_reg->type == SCALAR_VALUE && dst_reg->id && 16810 !WARN_ON_ONCE(dst_reg->id != other_branch_regs[insn->dst_reg].id)) { 16811 sync_linked_regs(this_branch, dst_reg, &linked_regs); 16812 sync_linked_regs(other_branch, &other_branch_regs[insn->dst_reg], &linked_regs); 16813 } 16814 16815 /* if one pointer register is compared to another pointer 16816 * register check if PTR_MAYBE_NULL could be lifted. 16817 * E.g. register A - maybe null 16818 * register B - not null 16819 * for JNE A, B, ... - A is not null in the false branch; 16820 * for JEQ A, B, ... - A is not null in the true branch. 16821 * 16822 * Since PTR_TO_BTF_ID points to a kernel struct that does 16823 * not need to be null checked by the BPF program, i.e., 16824 * could be null even without PTR_MAYBE_NULL marking, so 16825 * only propagate nullness when neither reg is that type. 16826 */ 16827 if (!is_jmp32 && BPF_SRC(insn->code) == BPF_X && 16828 __is_pointer_value(false, src_reg) && __is_pointer_value(false, dst_reg) && 16829 type_may_be_null(src_reg->type) != type_may_be_null(dst_reg->type) && 16830 base_type(src_reg->type) != PTR_TO_BTF_ID && 16831 base_type(dst_reg->type) != PTR_TO_BTF_ID) { 16832 eq_branch_regs = NULL; 16833 switch (opcode) { 16834 case BPF_JEQ: 16835 eq_branch_regs = other_branch_regs; 16836 break; 16837 case BPF_JNE: 16838 eq_branch_regs = regs; 16839 break; 16840 default: 16841 /* do nothing */ 16842 break; 16843 } 16844 if (eq_branch_regs) { 16845 if (type_may_be_null(src_reg->type)) 16846 mark_ptr_not_null_reg(&eq_branch_regs[insn->src_reg]); 16847 else 16848 mark_ptr_not_null_reg(&eq_branch_regs[insn->dst_reg]); 16849 } 16850 } 16851 16852 /* detect if R == 0 where R is returned from bpf_map_lookup_elem(). 16853 * NOTE: these optimizations below are related with pointer comparison 16854 * which will never be JMP32. 16855 */ 16856 if (!is_jmp32 && BPF_SRC(insn->code) == BPF_K && 16857 insn->imm == 0 && (opcode == BPF_JEQ || opcode == BPF_JNE) && 16858 type_may_be_null(dst_reg->type)) { 16859 /* Mark all identical registers in each branch as either 16860 * safe or unknown depending R == 0 or R != 0 conditional. 16861 */ 16862 mark_ptr_or_null_regs(this_branch, insn->dst_reg, 16863 opcode == BPF_JNE); 16864 mark_ptr_or_null_regs(other_branch, insn->dst_reg, 16865 opcode == BPF_JEQ); 16866 } else if (!try_match_pkt_pointers(insn, dst_reg, ®s[insn->src_reg], 16867 this_branch, other_branch) && 16868 is_pointer_value(env, insn->dst_reg)) { 16869 verbose(env, "R%d pointer comparison prohibited\n", 16870 insn->dst_reg); 16871 return -EACCES; 16872 } 16873 if (env->log.level & BPF_LOG_LEVEL) 16874 print_insn_state(env, this_branch, this_branch->curframe); 16875 return 0; 16876 } 16877 16878 /* verify BPF_LD_IMM64 instruction */ 16879 static int check_ld_imm(struct bpf_verifier_env *env, struct bpf_insn *insn) 16880 { 16881 struct bpf_insn_aux_data *aux = cur_aux(env); 16882 struct bpf_reg_state *regs = cur_regs(env); 16883 struct bpf_reg_state *dst_reg; 16884 struct bpf_map *map; 16885 int err; 16886 16887 if (BPF_SIZE(insn->code) != BPF_DW) { 16888 verbose(env, "invalid BPF_LD_IMM insn\n"); 16889 return -EINVAL; 16890 } 16891 if (insn->off != 0) { 16892 verbose(env, "BPF_LD_IMM64 uses reserved fields\n"); 16893 return -EINVAL; 16894 } 16895 16896 err = check_reg_arg(env, insn->dst_reg, DST_OP); 16897 if (err) 16898 return err; 16899 16900 dst_reg = ®s[insn->dst_reg]; 16901 if (insn->src_reg == 0) { 16902 u64 imm = ((u64)(insn + 1)->imm << 32) | (u32)insn->imm; 16903 16904 dst_reg->type = SCALAR_VALUE; 16905 __mark_reg_known(®s[insn->dst_reg], imm); 16906 return 0; 16907 } 16908 16909 /* All special src_reg cases are listed below. From this point onwards 16910 * we either succeed and assign a corresponding dst_reg->type after 16911 * zeroing the offset, or fail and reject the program. 16912 */ 16913 mark_reg_known_zero(env, regs, insn->dst_reg); 16914 16915 if (insn->src_reg == BPF_PSEUDO_BTF_ID) { 16916 dst_reg->type = aux->btf_var.reg_type; 16917 switch (base_type(dst_reg->type)) { 16918 case PTR_TO_MEM: 16919 dst_reg->mem_size = aux->btf_var.mem_size; 16920 break; 16921 case PTR_TO_BTF_ID: 16922 dst_reg->btf = aux->btf_var.btf; 16923 dst_reg->btf_id = aux->btf_var.btf_id; 16924 break; 16925 default: 16926 verifier_bug(env, "pseudo btf id: unexpected dst reg type"); 16927 return -EFAULT; 16928 } 16929 return 0; 16930 } 16931 16932 if (insn->src_reg == BPF_PSEUDO_FUNC) { 16933 struct bpf_prog_aux *aux = env->prog->aux; 16934 u32 subprogno = find_subprog(env, 16935 env->insn_idx + insn->imm + 1); 16936 16937 if (!aux->func_info) { 16938 verbose(env, "missing btf func_info\n"); 16939 return -EINVAL; 16940 } 16941 if (aux->func_info_aux[subprogno].linkage != BTF_FUNC_STATIC) { 16942 verbose(env, "callback function not static\n"); 16943 return -EINVAL; 16944 } 16945 16946 dst_reg->type = PTR_TO_FUNC; 16947 dst_reg->subprogno = subprogno; 16948 return 0; 16949 } 16950 16951 map = env->used_maps[aux->map_index]; 16952 dst_reg->map_ptr = map; 16953 16954 if (insn->src_reg == BPF_PSEUDO_MAP_VALUE || 16955 insn->src_reg == BPF_PSEUDO_MAP_IDX_VALUE) { 16956 if (map->map_type == BPF_MAP_TYPE_ARENA) { 16957 __mark_reg_unknown(env, dst_reg); 16958 return 0; 16959 } 16960 dst_reg->type = PTR_TO_MAP_VALUE; 16961 dst_reg->off = aux->map_off; 16962 WARN_ON_ONCE(map->max_entries != 1); 16963 /* We want reg->id to be same (0) as map_value is not distinct */ 16964 } else if (insn->src_reg == BPF_PSEUDO_MAP_FD || 16965 insn->src_reg == BPF_PSEUDO_MAP_IDX) { 16966 dst_reg->type = CONST_PTR_TO_MAP; 16967 } else { 16968 verifier_bug(env, "unexpected src reg value for ldimm64"); 16969 return -EFAULT; 16970 } 16971 16972 return 0; 16973 } 16974 16975 static bool may_access_skb(enum bpf_prog_type type) 16976 { 16977 switch (type) { 16978 case BPF_PROG_TYPE_SOCKET_FILTER: 16979 case BPF_PROG_TYPE_SCHED_CLS: 16980 case BPF_PROG_TYPE_SCHED_ACT: 16981 return true; 16982 default: 16983 return false; 16984 } 16985 } 16986 16987 /* verify safety of LD_ABS|LD_IND instructions: 16988 * - they can only appear in the programs where ctx == skb 16989 * - since they are wrappers of function calls, they scratch R1-R5 registers, 16990 * preserve R6-R9, and store return value into R0 16991 * 16992 * Implicit input: 16993 * ctx == skb == R6 == CTX 16994 * 16995 * Explicit input: 16996 * SRC == any register 16997 * IMM == 32-bit immediate 16998 * 16999 * Output: 17000 * R0 - 8/16/32-bit skb data converted to cpu endianness 17001 */ 17002 static int check_ld_abs(struct bpf_verifier_env *env, struct bpf_insn *insn) 17003 { 17004 struct bpf_reg_state *regs = cur_regs(env); 17005 static const int ctx_reg = BPF_REG_6; 17006 u8 mode = BPF_MODE(insn->code); 17007 int i, err; 17008 17009 if (!may_access_skb(resolve_prog_type(env->prog))) { 17010 verbose(env, "BPF_LD_[ABS|IND] instructions not allowed for this program type\n"); 17011 return -EINVAL; 17012 } 17013 17014 if (!env->ops->gen_ld_abs) { 17015 verifier_bug(env, "gen_ld_abs is null"); 17016 return -EFAULT; 17017 } 17018 17019 if (insn->dst_reg != BPF_REG_0 || insn->off != 0 || 17020 BPF_SIZE(insn->code) == BPF_DW || 17021 (mode == BPF_ABS && insn->src_reg != BPF_REG_0)) { 17022 verbose(env, "BPF_LD_[ABS|IND] uses reserved fields\n"); 17023 return -EINVAL; 17024 } 17025 17026 /* check whether implicit source operand (register R6) is readable */ 17027 err = check_reg_arg(env, ctx_reg, SRC_OP); 17028 if (err) 17029 return err; 17030 17031 /* Disallow usage of BPF_LD_[ABS|IND] with reference tracking, as 17032 * gen_ld_abs() may terminate the program at runtime, leading to 17033 * reference leak. 17034 */ 17035 err = check_resource_leak(env, false, true, "BPF_LD_[ABS|IND]"); 17036 if (err) 17037 return err; 17038 17039 if (regs[ctx_reg].type != PTR_TO_CTX) { 17040 verbose(env, 17041 "at the time of BPF_LD_ABS|IND R6 != pointer to skb\n"); 17042 return -EINVAL; 17043 } 17044 17045 if (mode == BPF_IND) { 17046 /* check explicit source operand */ 17047 err = check_reg_arg(env, insn->src_reg, SRC_OP); 17048 if (err) 17049 return err; 17050 } 17051 17052 err = check_ptr_off_reg(env, ®s[ctx_reg], ctx_reg); 17053 if (err < 0) 17054 return err; 17055 17056 /* reset caller saved regs to unreadable */ 17057 for (i = 0; i < CALLER_SAVED_REGS; i++) { 17058 mark_reg_not_init(env, regs, caller_saved[i]); 17059 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK); 17060 } 17061 17062 /* mark destination R0 register as readable, since it contains 17063 * the value fetched from the packet. 17064 * Already marked as written above. 17065 */ 17066 mark_reg_unknown(env, regs, BPF_REG_0); 17067 /* ld_abs load up to 32-bit skb data. */ 17068 regs[BPF_REG_0].subreg_def = env->insn_idx + 1; 17069 return 0; 17070 } 17071 17072 static int check_return_code(struct bpf_verifier_env *env, int regno, const char *reg_name) 17073 { 17074 const char *exit_ctx = "At program exit"; 17075 struct tnum enforce_attach_type_range = tnum_unknown; 17076 const struct bpf_prog *prog = env->prog; 17077 struct bpf_reg_state *reg = reg_state(env, regno); 17078 struct bpf_retval_range range = retval_range(0, 1); 17079 enum bpf_prog_type prog_type = resolve_prog_type(env->prog); 17080 int err; 17081 struct bpf_func_state *frame = env->cur_state->frame[0]; 17082 const bool is_subprog = frame->subprogno; 17083 bool return_32bit = false; 17084 const struct btf_type *reg_type, *ret_type = NULL; 17085 17086 /* LSM and struct_ops func-ptr's return type could be "void" */ 17087 if (!is_subprog || frame->in_exception_callback_fn) { 17088 switch (prog_type) { 17089 case BPF_PROG_TYPE_LSM: 17090 if (prog->expected_attach_type == BPF_LSM_CGROUP) 17091 /* See below, can be 0 or 0-1 depending on hook. */ 17092 break; 17093 if (!prog->aux->attach_func_proto->type) 17094 return 0; 17095 break; 17096 case BPF_PROG_TYPE_STRUCT_OPS: 17097 if (!prog->aux->attach_func_proto->type) 17098 return 0; 17099 17100 if (frame->in_exception_callback_fn) 17101 break; 17102 17103 /* Allow a struct_ops program to return a referenced kptr if it 17104 * matches the operator's return type and is in its unmodified 17105 * form. A scalar zero (i.e., a null pointer) is also allowed. 17106 */ 17107 reg_type = reg->btf ? btf_type_by_id(reg->btf, reg->btf_id) : NULL; 17108 ret_type = btf_type_resolve_ptr(prog->aux->attach_btf, 17109 prog->aux->attach_func_proto->type, 17110 NULL); 17111 if (ret_type && ret_type == reg_type && reg->ref_obj_id) 17112 return __check_ptr_off_reg(env, reg, regno, false); 17113 break; 17114 default: 17115 break; 17116 } 17117 } 17118 17119 /* eBPF calling convention is such that R0 is used 17120 * to return the value from eBPF program. 17121 * Make sure that it's readable at this time 17122 * of bpf_exit, which means that program wrote 17123 * something into it earlier 17124 */ 17125 err = check_reg_arg(env, regno, SRC_OP); 17126 if (err) 17127 return err; 17128 17129 if (is_pointer_value(env, regno)) { 17130 verbose(env, "R%d leaks addr as return value\n", regno); 17131 return -EACCES; 17132 } 17133 17134 if (frame->in_async_callback_fn) { 17135 /* enforce return zero from async callbacks like timer */ 17136 exit_ctx = "At async callback return"; 17137 range = retval_range(0, 0); 17138 goto enforce_retval; 17139 } 17140 17141 if (is_subprog && !frame->in_exception_callback_fn) { 17142 if (reg->type != SCALAR_VALUE) { 17143 verbose(env, "At subprogram exit the register R%d is not a scalar value (%s)\n", 17144 regno, reg_type_str(env, reg->type)); 17145 return -EINVAL; 17146 } 17147 return 0; 17148 } 17149 17150 switch (prog_type) { 17151 case BPF_PROG_TYPE_CGROUP_SOCK_ADDR: 17152 if (env->prog->expected_attach_type == BPF_CGROUP_UDP4_RECVMSG || 17153 env->prog->expected_attach_type == BPF_CGROUP_UDP6_RECVMSG || 17154 env->prog->expected_attach_type == BPF_CGROUP_UNIX_RECVMSG || 17155 env->prog->expected_attach_type == BPF_CGROUP_INET4_GETPEERNAME || 17156 env->prog->expected_attach_type == BPF_CGROUP_INET6_GETPEERNAME || 17157 env->prog->expected_attach_type == BPF_CGROUP_UNIX_GETPEERNAME || 17158 env->prog->expected_attach_type == BPF_CGROUP_INET4_GETSOCKNAME || 17159 env->prog->expected_attach_type == BPF_CGROUP_INET6_GETSOCKNAME || 17160 env->prog->expected_attach_type == BPF_CGROUP_UNIX_GETSOCKNAME) 17161 range = retval_range(1, 1); 17162 if (env->prog->expected_attach_type == BPF_CGROUP_INET4_BIND || 17163 env->prog->expected_attach_type == BPF_CGROUP_INET6_BIND) 17164 range = retval_range(0, 3); 17165 break; 17166 case BPF_PROG_TYPE_CGROUP_SKB: 17167 if (env->prog->expected_attach_type == BPF_CGROUP_INET_EGRESS) { 17168 range = retval_range(0, 3); 17169 enforce_attach_type_range = tnum_range(2, 3); 17170 } 17171 break; 17172 case BPF_PROG_TYPE_CGROUP_SOCK: 17173 case BPF_PROG_TYPE_SOCK_OPS: 17174 case BPF_PROG_TYPE_CGROUP_DEVICE: 17175 case BPF_PROG_TYPE_CGROUP_SYSCTL: 17176 case BPF_PROG_TYPE_CGROUP_SOCKOPT: 17177 break; 17178 case BPF_PROG_TYPE_RAW_TRACEPOINT: 17179 if (!env->prog->aux->attach_btf_id) 17180 return 0; 17181 range = retval_range(0, 0); 17182 break; 17183 case BPF_PROG_TYPE_TRACING: 17184 switch (env->prog->expected_attach_type) { 17185 case BPF_TRACE_FENTRY: 17186 case BPF_TRACE_FEXIT: 17187 range = retval_range(0, 0); 17188 break; 17189 case BPF_TRACE_RAW_TP: 17190 case BPF_MODIFY_RETURN: 17191 return 0; 17192 case BPF_TRACE_ITER: 17193 break; 17194 default: 17195 return -ENOTSUPP; 17196 } 17197 break; 17198 case BPF_PROG_TYPE_KPROBE: 17199 switch (env->prog->expected_attach_type) { 17200 case BPF_TRACE_KPROBE_SESSION: 17201 case BPF_TRACE_UPROBE_SESSION: 17202 range = retval_range(0, 1); 17203 break; 17204 default: 17205 return 0; 17206 } 17207 break; 17208 case BPF_PROG_TYPE_SK_LOOKUP: 17209 range = retval_range(SK_DROP, SK_PASS); 17210 break; 17211 17212 case BPF_PROG_TYPE_LSM: 17213 if (env->prog->expected_attach_type != BPF_LSM_CGROUP) { 17214 /* no range found, any return value is allowed */ 17215 if (!get_func_retval_range(env->prog, &range)) 17216 return 0; 17217 /* no restricted range, any return value is allowed */ 17218 if (range.minval == S32_MIN && range.maxval == S32_MAX) 17219 return 0; 17220 return_32bit = true; 17221 } else if (!env->prog->aux->attach_func_proto->type) { 17222 /* Make sure programs that attach to void 17223 * hooks don't try to modify return value. 17224 */ 17225 range = retval_range(1, 1); 17226 } 17227 break; 17228 17229 case BPF_PROG_TYPE_NETFILTER: 17230 range = retval_range(NF_DROP, NF_ACCEPT); 17231 break; 17232 case BPF_PROG_TYPE_STRUCT_OPS: 17233 if (!ret_type) 17234 return 0; 17235 range = retval_range(0, 0); 17236 break; 17237 case BPF_PROG_TYPE_EXT: 17238 /* freplace program can return anything as its return value 17239 * depends on the to-be-replaced kernel func or bpf program. 17240 */ 17241 default: 17242 return 0; 17243 } 17244 17245 enforce_retval: 17246 if (reg->type != SCALAR_VALUE) { 17247 verbose(env, "%s the register R%d is not a known value (%s)\n", 17248 exit_ctx, regno, reg_type_str(env, reg->type)); 17249 return -EINVAL; 17250 } 17251 17252 err = mark_chain_precision(env, regno); 17253 if (err) 17254 return err; 17255 17256 if (!retval_range_within(range, reg, return_32bit)) { 17257 verbose_invalid_scalar(env, reg, range, exit_ctx, reg_name); 17258 if (!is_subprog && 17259 prog->expected_attach_type == BPF_LSM_CGROUP && 17260 prog_type == BPF_PROG_TYPE_LSM && 17261 !prog->aux->attach_func_proto->type) 17262 verbose(env, "Note, BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n"); 17263 return -EINVAL; 17264 } 17265 17266 if (!tnum_is_unknown(enforce_attach_type_range) && 17267 tnum_in(enforce_attach_type_range, reg->var_off)) 17268 env->prog->enforce_expected_attach_type = 1; 17269 return 0; 17270 } 17271 17272 static void mark_subprog_changes_pkt_data(struct bpf_verifier_env *env, int off) 17273 { 17274 struct bpf_subprog_info *subprog; 17275 17276 subprog = find_containing_subprog(env, off); 17277 subprog->changes_pkt_data = true; 17278 } 17279 17280 static void mark_subprog_might_sleep(struct bpf_verifier_env *env, int off) 17281 { 17282 struct bpf_subprog_info *subprog; 17283 17284 subprog = find_containing_subprog(env, off); 17285 subprog->might_sleep = true; 17286 } 17287 17288 /* 't' is an index of a call-site. 17289 * 'w' is a callee entry point. 17290 * Eventually this function would be called when env->cfg.insn_state[w] == EXPLORED. 17291 * Rely on DFS traversal order and absence of recursive calls to guarantee that 17292 * callee's change_pkt_data marks would be correct at that moment. 17293 */ 17294 static void merge_callee_effects(struct bpf_verifier_env *env, int t, int w) 17295 { 17296 struct bpf_subprog_info *caller, *callee; 17297 17298 caller = find_containing_subprog(env, t); 17299 callee = find_containing_subprog(env, w); 17300 caller->changes_pkt_data |= callee->changes_pkt_data; 17301 caller->might_sleep |= callee->might_sleep; 17302 } 17303 17304 /* non-recursive DFS pseudo code 17305 * 1 procedure DFS-iterative(G,v): 17306 * 2 label v as discovered 17307 * 3 let S be a stack 17308 * 4 S.push(v) 17309 * 5 while S is not empty 17310 * 6 t <- S.peek() 17311 * 7 if t is what we're looking for: 17312 * 8 return t 17313 * 9 for all edges e in G.adjacentEdges(t) do 17314 * 10 if edge e is already labelled 17315 * 11 continue with the next edge 17316 * 12 w <- G.adjacentVertex(t,e) 17317 * 13 if vertex w is not discovered and not explored 17318 * 14 label e as tree-edge 17319 * 15 label w as discovered 17320 * 16 S.push(w) 17321 * 17 continue at 5 17322 * 18 else if vertex w is discovered 17323 * 19 label e as back-edge 17324 * 20 else 17325 * 21 // vertex w is explored 17326 * 22 label e as forward- or cross-edge 17327 * 23 label t as explored 17328 * 24 S.pop() 17329 * 17330 * convention: 17331 * 0x10 - discovered 17332 * 0x11 - discovered and fall-through edge labelled 17333 * 0x12 - discovered and fall-through and branch edges labelled 17334 * 0x20 - explored 17335 */ 17336 17337 enum { 17338 DISCOVERED = 0x10, 17339 EXPLORED = 0x20, 17340 FALLTHROUGH = 1, 17341 BRANCH = 2, 17342 }; 17343 17344 static void mark_prune_point(struct bpf_verifier_env *env, int idx) 17345 { 17346 env->insn_aux_data[idx].prune_point = true; 17347 } 17348 17349 static bool is_prune_point(struct bpf_verifier_env *env, int insn_idx) 17350 { 17351 return env->insn_aux_data[insn_idx].prune_point; 17352 } 17353 17354 static void mark_force_checkpoint(struct bpf_verifier_env *env, int idx) 17355 { 17356 env->insn_aux_data[idx].force_checkpoint = true; 17357 } 17358 17359 static bool is_force_checkpoint(struct bpf_verifier_env *env, int insn_idx) 17360 { 17361 return env->insn_aux_data[insn_idx].force_checkpoint; 17362 } 17363 17364 static void mark_calls_callback(struct bpf_verifier_env *env, int idx) 17365 { 17366 env->insn_aux_data[idx].calls_callback = true; 17367 } 17368 17369 static bool calls_callback(struct bpf_verifier_env *env, int insn_idx) 17370 { 17371 return env->insn_aux_data[insn_idx].calls_callback; 17372 } 17373 17374 enum { 17375 DONE_EXPLORING = 0, 17376 KEEP_EXPLORING = 1, 17377 }; 17378 17379 /* t, w, e - match pseudo-code above: 17380 * t - index of current instruction 17381 * w - next instruction 17382 * e - edge 17383 */ 17384 static int push_insn(int t, int w, int e, struct bpf_verifier_env *env) 17385 { 17386 int *insn_stack = env->cfg.insn_stack; 17387 int *insn_state = env->cfg.insn_state; 17388 17389 if (e == FALLTHROUGH && insn_state[t] >= (DISCOVERED | FALLTHROUGH)) 17390 return DONE_EXPLORING; 17391 17392 if (e == BRANCH && insn_state[t] >= (DISCOVERED | BRANCH)) 17393 return DONE_EXPLORING; 17394 17395 if (w < 0 || w >= env->prog->len) { 17396 verbose_linfo(env, t, "%d: ", t); 17397 verbose(env, "jump out of range from insn %d to %d\n", t, w); 17398 return -EINVAL; 17399 } 17400 17401 if (e == BRANCH) { 17402 /* mark branch target for state pruning */ 17403 mark_prune_point(env, w); 17404 mark_jmp_point(env, w); 17405 } 17406 17407 if (insn_state[w] == 0) { 17408 /* tree-edge */ 17409 insn_state[t] = DISCOVERED | e; 17410 insn_state[w] = DISCOVERED; 17411 if (env->cfg.cur_stack >= env->prog->len) 17412 return -E2BIG; 17413 insn_stack[env->cfg.cur_stack++] = w; 17414 return KEEP_EXPLORING; 17415 } else if ((insn_state[w] & 0xF0) == DISCOVERED) { 17416 if (env->bpf_capable) 17417 return DONE_EXPLORING; 17418 verbose_linfo(env, t, "%d: ", t); 17419 verbose_linfo(env, w, "%d: ", w); 17420 verbose(env, "back-edge from insn %d to %d\n", t, w); 17421 return -EINVAL; 17422 } else if (insn_state[w] == EXPLORED) { 17423 /* forward- or cross-edge */ 17424 insn_state[t] = DISCOVERED | e; 17425 } else { 17426 verifier_bug(env, "insn state internal bug"); 17427 return -EFAULT; 17428 } 17429 return DONE_EXPLORING; 17430 } 17431 17432 static int visit_func_call_insn(int t, struct bpf_insn *insns, 17433 struct bpf_verifier_env *env, 17434 bool visit_callee) 17435 { 17436 int ret, insn_sz; 17437 int w; 17438 17439 insn_sz = bpf_is_ldimm64(&insns[t]) ? 2 : 1; 17440 ret = push_insn(t, t + insn_sz, FALLTHROUGH, env); 17441 if (ret) 17442 return ret; 17443 17444 mark_prune_point(env, t + insn_sz); 17445 /* when we exit from subprog, we need to record non-linear history */ 17446 mark_jmp_point(env, t + insn_sz); 17447 17448 if (visit_callee) { 17449 w = t + insns[t].imm + 1; 17450 mark_prune_point(env, t); 17451 merge_callee_effects(env, t, w); 17452 ret = push_insn(t, w, BRANCH, env); 17453 } 17454 return ret; 17455 } 17456 17457 /* Bitmask with 1s for all caller saved registers */ 17458 #define ALL_CALLER_SAVED_REGS ((1u << CALLER_SAVED_REGS) - 1) 17459 17460 /* True if do_misc_fixups() replaces calls to helper number 'imm', 17461 * replacement patch is presumed to follow bpf_fastcall contract 17462 * (see mark_fastcall_pattern_for_call() below). 17463 */ 17464 static bool verifier_inlines_helper_call(struct bpf_verifier_env *env, s32 imm) 17465 { 17466 switch (imm) { 17467 #ifdef CONFIG_X86_64 17468 case BPF_FUNC_get_smp_processor_id: 17469 return env->prog->jit_requested && bpf_jit_supports_percpu_insn(); 17470 #endif 17471 default: 17472 return false; 17473 } 17474 } 17475 17476 struct call_summary { 17477 u8 num_params; 17478 bool is_void; 17479 bool fastcall; 17480 }; 17481 17482 /* If @call is a kfunc or helper call, fills @cs and returns true, 17483 * otherwise returns false. 17484 */ 17485 static bool get_call_summary(struct bpf_verifier_env *env, struct bpf_insn *call, 17486 struct call_summary *cs) 17487 { 17488 struct bpf_kfunc_call_arg_meta meta; 17489 const struct bpf_func_proto *fn; 17490 int i; 17491 17492 if (bpf_helper_call(call)) { 17493 17494 if (get_helper_proto(env, call->imm, &fn) < 0) 17495 /* error would be reported later */ 17496 return false; 17497 cs->fastcall = fn->allow_fastcall && 17498 (verifier_inlines_helper_call(env, call->imm) || 17499 bpf_jit_inlines_helper_call(call->imm)); 17500 cs->is_void = fn->ret_type == RET_VOID; 17501 cs->num_params = 0; 17502 for (i = 0; i < ARRAY_SIZE(fn->arg_type); ++i) { 17503 if (fn->arg_type[i] == ARG_DONTCARE) 17504 break; 17505 cs->num_params++; 17506 } 17507 return true; 17508 } 17509 17510 if (bpf_pseudo_kfunc_call(call)) { 17511 int err; 17512 17513 err = fetch_kfunc_meta(env, call, &meta, NULL); 17514 if (err < 0) 17515 /* error would be reported later */ 17516 return false; 17517 cs->num_params = btf_type_vlen(meta.func_proto); 17518 cs->fastcall = meta.kfunc_flags & KF_FASTCALL; 17519 cs->is_void = btf_type_is_void(btf_type_by_id(meta.btf, meta.func_proto->type)); 17520 return true; 17521 } 17522 17523 return false; 17524 } 17525 17526 /* LLVM define a bpf_fastcall function attribute. 17527 * This attribute means that function scratches only some of 17528 * the caller saved registers defined by ABI. 17529 * For BPF the set of such registers could be defined as follows: 17530 * - R0 is scratched only if function is non-void; 17531 * - R1-R5 are scratched only if corresponding parameter type is defined 17532 * in the function prototype. 17533 * 17534 * The contract between kernel and clang allows to simultaneously use 17535 * such functions and maintain backwards compatibility with old 17536 * kernels that don't understand bpf_fastcall calls: 17537 * 17538 * - for bpf_fastcall calls clang allocates registers as-if relevant r0-r5 17539 * registers are not scratched by the call; 17540 * 17541 * - as a post-processing step, clang visits each bpf_fastcall call and adds 17542 * spill/fill for every live r0-r5; 17543 * 17544 * - stack offsets used for the spill/fill are allocated as lowest 17545 * stack offsets in whole function and are not used for any other 17546 * purposes; 17547 * 17548 * - when kernel loads a program, it looks for such patterns 17549 * (bpf_fastcall function surrounded by spills/fills) and checks if 17550 * spill/fill stack offsets are used exclusively in fastcall patterns; 17551 * 17552 * - if so, and if verifier or current JIT inlines the call to the 17553 * bpf_fastcall function (e.g. a helper call), kernel removes unnecessary 17554 * spill/fill pairs; 17555 * 17556 * - when old kernel loads a program, presence of spill/fill pairs 17557 * keeps BPF program valid, albeit slightly less efficient. 17558 * 17559 * For example: 17560 * 17561 * r1 = 1; 17562 * r2 = 2; 17563 * *(u64 *)(r10 - 8) = r1; r1 = 1; 17564 * *(u64 *)(r10 - 16) = r2; r2 = 2; 17565 * call %[to_be_inlined] --> call %[to_be_inlined] 17566 * r2 = *(u64 *)(r10 - 16); r0 = r1; 17567 * r1 = *(u64 *)(r10 - 8); r0 += r2; 17568 * r0 = r1; exit; 17569 * r0 += r2; 17570 * exit; 17571 * 17572 * The purpose of mark_fastcall_pattern_for_call is to: 17573 * - look for such patterns; 17574 * - mark spill and fill instructions in env->insn_aux_data[*].fastcall_pattern; 17575 * - mark set env->insn_aux_data[*].fastcall_spills_num for call instruction; 17576 * - update env->subprog_info[*]->fastcall_stack_off to find an offset 17577 * at which bpf_fastcall spill/fill stack slots start; 17578 * - update env->subprog_info[*]->keep_fastcall_stack. 17579 * 17580 * The .fastcall_pattern and .fastcall_stack_off are used by 17581 * check_fastcall_stack_contract() to check if every stack access to 17582 * fastcall spill/fill stack slot originates from spill/fill 17583 * instructions, members of fastcall patterns. 17584 * 17585 * If such condition holds true for a subprogram, fastcall patterns could 17586 * be rewritten by remove_fastcall_spills_fills(). 17587 * Otherwise bpf_fastcall patterns are not changed in the subprogram 17588 * (code, presumably, generated by an older clang version). 17589 * 17590 * For example, it is *not* safe to remove spill/fill below: 17591 * 17592 * r1 = 1; 17593 * *(u64 *)(r10 - 8) = r1; r1 = 1; 17594 * call %[to_be_inlined] --> call %[to_be_inlined] 17595 * r1 = *(u64 *)(r10 - 8); r0 = *(u64 *)(r10 - 8); <---- wrong !!! 17596 * r0 = *(u64 *)(r10 - 8); r0 += r1; 17597 * r0 += r1; exit; 17598 * exit; 17599 */ 17600 static void mark_fastcall_pattern_for_call(struct bpf_verifier_env *env, 17601 struct bpf_subprog_info *subprog, 17602 int insn_idx, s16 lowest_off) 17603 { 17604 struct bpf_insn *insns = env->prog->insnsi, *stx, *ldx; 17605 struct bpf_insn *call = &env->prog->insnsi[insn_idx]; 17606 u32 clobbered_regs_mask; 17607 struct call_summary cs; 17608 u32 expected_regs_mask; 17609 s16 off; 17610 int i; 17611 17612 if (!get_call_summary(env, call, &cs)) 17613 return; 17614 17615 /* A bitmask specifying which caller saved registers are clobbered 17616 * by a call to a helper/kfunc *as if* this helper/kfunc follows 17617 * bpf_fastcall contract: 17618 * - includes R0 if function is non-void; 17619 * - includes R1-R5 if corresponding parameter has is described 17620 * in the function prototype. 17621 */ 17622 clobbered_regs_mask = GENMASK(cs.num_params, cs.is_void ? 1 : 0); 17623 /* e.g. if helper call clobbers r{0,1}, expect r{2,3,4,5} in the pattern */ 17624 expected_regs_mask = ~clobbered_regs_mask & ALL_CALLER_SAVED_REGS; 17625 17626 /* match pairs of form: 17627 * 17628 * *(u64 *)(r10 - Y) = rX (where Y % 8 == 0) 17629 * ... 17630 * call %[to_be_inlined] 17631 * ... 17632 * rX = *(u64 *)(r10 - Y) 17633 */ 17634 for (i = 1, off = lowest_off; i <= ARRAY_SIZE(caller_saved); ++i, off += BPF_REG_SIZE) { 17635 if (insn_idx - i < 0 || insn_idx + i >= env->prog->len) 17636 break; 17637 stx = &insns[insn_idx - i]; 17638 ldx = &insns[insn_idx + i]; 17639 /* must be a stack spill/fill pair */ 17640 if (stx->code != (BPF_STX | BPF_MEM | BPF_DW) || 17641 ldx->code != (BPF_LDX | BPF_MEM | BPF_DW) || 17642 stx->dst_reg != BPF_REG_10 || 17643 ldx->src_reg != BPF_REG_10) 17644 break; 17645 /* must be a spill/fill for the same reg */ 17646 if (stx->src_reg != ldx->dst_reg) 17647 break; 17648 /* must be one of the previously unseen registers */ 17649 if ((BIT(stx->src_reg) & expected_regs_mask) == 0) 17650 break; 17651 /* must be a spill/fill for the same expected offset, 17652 * no need to check offset alignment, BPF_DW stack access 17653 * is always 8-byte aligned. 17654 */ 17655 if (stx->off != off || ldx->off != off) 17656 break; 17657 expected_regs_mask &= ~BIT(stx->src_reg); 17658 env->insn_aux_data[insn_idx - i].fastcall_pattern = 1; 17659 env->insn_aux_data[insn_idx + i].fastcall_pattern = 1; 17660 } 17661 if (i == 1) 17662 return; 17663 17664 /* Conditionally set 'fastcall_spills_num' to allow forward 17665 * compatibility when more helper functions are marked as 17666 * bpf_fastcall at compile time than current kernel supports, e.g: 17667 * 17668 * 1: *(u64 *)(r10 - 8) = r1 17669 * 2: call A ;; assume A is bpf_fastcall for current kernel 17670 * 3: r1 = *(u64 *)(r10 - 8) 17671 * 4: *(u64 *)(r10 - 8) = r1 17672 * 5: call B ;; assume B is not bpf_fastcall for current kernel 17673 * 6: r1 = *(u64 *)(r10 - 8) 17674 * 17675 * There is no need to block bpf_fastcall rewrite for such program. 17676 * Set 'fastcall_pattern' for both calls to keep check_fastcall_stack_contract() happy, 17677 * don't set 'fastcall_spills_num' for call B so that remove_fastcall_spills_fills() 17678 * does not remove spill/fill pair {4,6}. 17679 */ 17680 if (cs.fastcall) 17681 env->insn_aux_data[insn_idx].fastcall_spills_num = i - 1; 17682 else 17683 subprog->keep_fastcall_stack = 1; 17684 subprog->fastcall_stack_off = min(subprog->fastcall_stack_off, off); 17685 } 17686 17687 static int mark_fastcall_patterns(struct bpf_verifier_env *env) 17688 { 17689 struct bpf_subprog_info *subprog = env->subprog_info; 17690 struct bpf_insn *insn; 17691 s16 lowest_off; 17692 int s, i; 17693 17694 for (s = 0; s < env->subprog_cnt; ++s, ++subprog) { 17695 /* find lowest stack spill offset used in this subprog */ 17696 lowest_off = 0; 17697 for (i = subprog->start; i < (subprog + 1)->start; ++i) { 17698 insn = env->prog->insnsi + i; 17699 if (insn->code != (BPF_STX | BPF_MEM | BPF_DW) || 17700 insn->dst_reg != BPF_REG_10) 17701 continue; 17702 lowest_off = min(lowest_off, insn->off); 17703 } 17704 /* use this offset to find fastcall patterns */ 17705 for (i = subprog->start; i < (subprog + 1)->start; ++i) { 17706 insn = env->prog->insnsi + i; 17707 if (insn->code != (BPF_JMP | BPF_CALL)) 17708 continue; 17709 mark_fastcall_pattern_for_call(env, subprog, i, lowest_off); 17710 } 17711 } 17712 return 0; 17713 } 17714 17715 /* Visits the instruction at index t and returns one of the following: 17716 * < 0 - an error occurred 17717 * DONE_EXPLORING - the instruction was fully explored 17718 * KEEP_EXPLORING - there is still work to be done before it is fully explored 17719 */ 17720 static int visit_insn(int t, struct bpf_verifier_env *env) 17721 { 17722 struct bpf_insn *insns = env->prog->insnsi, *insn = &insns[t]; 17723 int ret, off, insn_sz; 17724 17725 if (bpf_pseudo_func(insn)) 17726 return visit_func_call_insn(t, insns, env, true); 17727 17728 /* All non-branch instructions have a single fall-through edge. */ 17729 if (BPF_CLASS(insn->code) != BPF_JMP && 17730 BPF_CLASS(insn->code) != BPF_JMP32) { 17731 insn_sz = bpf_is_ldimm64(insn) ? 2 : 1; 17732 return push_insn(t, t + insn_sz, FALLTHROUGH, env); 17733 } 17734 17735 switch (BPF_OP(insn->code)) { 17736 case BPF_EXIT: 17737 return DONE_EXPLORING; 17738 17739 case BPF_CALL: 17740 if (is_async_callback_calling_insn(insn)) 17741 /* Mark this call insn as a prune point to trigger 17742 * is_state_visited() check before call itself is 17743 * processed by __check_func_call(). Otherwise new 17744 * async state will be pushed for further exploration. 17745 */ 17746 mark_prune_point(env, t); 17747 /* For functions that invoke callbacks it is not known how many times 17748 * callback would be called. Verifier models callback calling functions 17749 * by repeatedly visiting callback bodies and returning to origin call 17750 * instruction. 17751 * In order to stop such iteration verifier needs to identify when a 17752 * state identical some state from a previous iteration is reached. 17753 * Check below forces creation of checkpoint before callback calling 17754 * instruction to allow search for such identical states. 17755 */ 17756 if (is_sync_callback_calling_insn(insn)) { 17757 mark_calls_callback(env, t); 17758 mark_force_checkpoint(env, t); 17759 mark_prune_point(env, t); 17760 mark_jmp_point(env, t); 17761 } 17762 if (bpf_helper_call(insn)) { 17763 const struct bpf_func_proto *fp; 17764 17765 ret = get_helper_proto(env, insn->imm, &fp); 17766 /* If called in a non-sleepable context program will be 17767 * rejected anyway, so we should end up with precise 17768 * sleepable marks on subprogs, except for dead code 17769 * elimination. 17770 */ 17771 if (ret == 0 && fp->might_sleep) 17772 mark_subprog_might_sleep(env, t); 17773 if (bpf_helper_changes_pkt_data(insn->imm)) 17774 mark_subprog_changes_pkt_data(env, t); 17775 } else if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) { 17776 struct bpf_kfunc_call_arg_meta meta; 17777 17778 ret = fetch_kfunc_meta(env, insn, &meta, NULL); 17779 if (ret == 0 && is_iter_next_kfunc(&meta)) { 17780 mark_prune_point(env, t); 17781 /* Checking and saving state checkpoints at iter_next() call 17782 * is crucial for fast convergence of open-coded iterator loop 17783 * logic, so we need to force it. If we don't do that, 17784 * is_state_visited() might skip saving a checkpoint, causing 17785 * unnecessarily long sequence of not checkpointed 17786 * instructions and jumps, leading to exhaustion of jump 17787 * history buffer, and potentially other undesired outcomes. 17788 * It is expected that with correct open-coded iterators 17789 * convergence will happen quickly, so we don't run a risk of 17790 * exhausting memory. 17791 */ 17792 mark_force_checkpoint(env, t); 17793 } 17794 /* Same as helpers, if called in a non-sleepable context 17795 * program will be rejected anyway, so we should end up 17796 * with precise sleepable marks on subprogs, except for 17797 * dead code elimination. 17798 */ 17799 if (ret == 0 && is_kfunc_sleepable(&meta)) 17800 mark_subprog_might_sleep(env, t); 17801 } 17802 return visit_func_call_insn(t, insns, env, insn->src_reg == BPF_PSEUDO_CALL); 17803 17804 case BPF_JA: 17805 if (BPF_SRC(insn->code) != BPF_K) 17806 return -EINVAL; 17807 17808 if (BPF_CLASS(insn->code) == BPF_JMP) 17809 off = insn->off; 17810 else 17811 off = insn->imm; 17812 17813 /* unconditional jump with single edge */ 17814 ret = push_insn(t, t + off + 1, FALLTHROUGH, env); 17815 if (ret) 17816 return ret; 17817 17818 mark_prune_point(env, t + off + 1); 17819 mark_jmp_point(env, t + off + 1); 17820 17821 return ret; 17822 17823 default: 17824 /* conditional jump with two edges */ 17825 mark_prune_point(env, t); 17826 if (is_may_goto_insn(insn)) 17827 mark_force_checkpoint(env, t); 17828 17829 ret = push_insn(t, t + 1, FALLTHROUGH, env); 17830 if (ret) 17831 return ret; 17832 17833 return push_insn(t, t + insn->off + 1, BRANCH, env); 17834 } 17835 } 17836 17837 /* non-recursive depth-first-search to detect loops in BPF program 17838 * loop == back-edge in directed graph 17839 */ 17840 static int check_cfg(struct bpf_verifier_env *env) 17841 { 17842 int insn_cnt = env->prog->len; 17843 int *insn_stack, *insn_state, *insn_postorder; 17844 int ex_insn_beg, i, ret = 0; 17845 17846 insn_state = env->cfg.insn_state = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL_ACCOUNT); 17847 if (!insn_state) 17848 return -ENOMEM; 17849 17850 insn_stack = env->cfg.insn_stack = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL_ACCOUNT); 17851 if (!insn_stack) { 17852 kvfree(insn_state); 17853 return -ENOMEM; 17854 } 17855 17856 insn_postorder = env->cfg.insn_postorder = 17857 kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL_ACCOUNT); 17858 if (!insn_postorder) { 17859 kvfree(insn_state); 17860 kvfree(insn_stack); 17861 return -ENOMEM; 17862 } 17863 17864 ex_insn_beg = env->exception_callback_subprog 17865 ? env->subprog_info[env->exception_callback_subprog].start 17866 : 0; 17867 17868 insn_state[0] = DISCOVERED; /* mark 1st insn as discovered */ 17869 insn_stack[0] = 0; /* 0 is the first instruction */ 17870 env->cfg.cur_stack = 1; 17871 17872 walk_cfg: 17873 while (env->cfg.cur_stack > 0) { 17874 int t = insn_stack[env->cfg.cur_stack - 1]; 17875 17876 ret = visit_insn(t, env); 17877 switch (ret) { 17878 case DONE_EXPLORING: 17879 insn_state[t] = EXPLORED; 17880 env->cfg.cur_stack--; 17881 insn_postorder[env->cfg.cur_postorder++] = t; 17882 break; 17883 case KEEP_EXPLORING: 17884 break; 17885 default: 17886 if (ret > 0) { 17887 verifier_bug(env, "visit_insn internal bug"); 17888 ret = -EFAULT; 17889 } 17890 goto err_free; 17891 } 17892 } 17893 17894 if (env->cfg.cur_stack < 0) { 17895 verifier_bug(env, "pop stack internal bug"); 17896 ret = -EFAULT; 17897 goto err_free; 17898 } 17899 17900 if (ex_insn_beg && insn_state[ex_insn_beg] != EXPLORED) { 17901 insn_state[ex_insn_beg] = DISCOVERED; 17902 insn_stack[0] = ex_insn_beg; 17903 env->cfg.cur_stack = 1; 17904 goto walk_cfg; 17905 } 17906 17907 for (i = 0; i < insn_cnt; i++) { 17908 struct bpf_insn *insn = &env->prog->insnsi[i]; 17909 17910 if (insn_state[i] != EXPLORED) { 17911 verbose(env, "unreachable insn %d\n", i); 17912 ret = -EINVAL; 17913 goto err_free; 17914 } 17915 if (bpf_is_ldimm64(insn)) { 17916 if (insn_state[i + 1] != 0) { 17917 verbose(env, "jump into the middle of ldimm64 insn %d\n", i); 17918 ret = -EINVAL; 17919 goto err_free; 17920 } 17921 i++; /* skip second half of ldimm64 */ 17922 } 17923 } 17924 ret = 0; /* cfg looks good */ 17925 env->prog->aux->changes_pkt_data = env->subprog_info[0].changes_pkt_data; 17926 env->prog->aux->might_sleep = env->subprog_info[0].might_sleep; 17927 17928 err_free: 17929 kvfree(insn_state); 17930 kvfree(insn_stack); 17931 env->cfg.insn_state = env->cfg.insn_stack = NULL; 17932 return ret; 17933 } 17934 17935 static int check_abnormal_return(struct bpf_verifier_env *env) 17936 { 17937 int i; 17938 17939 for (i = 1; i < env->subprog_cnt; i++) { 17940 if (env->subprog_info[i].has_ld_abs) { 17941 verbose(env, "LD_ABS is not allowed in subprogs without BTF\n"); 17942 return -EINVAL; 17943 } 17944 if (env->subprog_info[i].has_tail_call) { 17945 verbose(env, "tail_call is not allowed in subprogs without BTF\n"); 17946 return -EINVAL; 17947 } 17948 } 17949 return 0; 17950 } 17951 17952 /* The minimum supported BTF func info size */ 17953 #define MIN_BPF_FUNCINFO_SIZE 8 17954 #define MAX_FUNCINFO_REC_SIZE 252 17955 17956 static int check_btf_func_early(struct bpf_verifier_env *env, 17957 const union bpf_attr *attr, 17958 bpfptr_t uattr) 17959 { 17960 u32 krec_size = sizeof(struct bpf_func_info); 17961 const struct btf_type *type, *func_proto; 17962 u32 i, nfuncs, urec_size, min_size; 17963 struct bpf_func_info *krecord; 17964 struct bpf_prog *prog; 17965 const struct btf *btf; 17966 u32 prev_offset = 0; 17967 bpfptr_t urecord; 17968 int ret = -ENOMEM; 17969 17970 nfuncs = attr->func_info_cnt; 17971 if (!nfuncs) { 17972 if (check_abnormal_return(env)) 17973 return -EINVAL; 17974 return 0; 17975 } 17976 17977 urec_size = attr->func_info_rec_size; 17978 if (urec_size < MIN_BPF_FUNCINFO_SIZE || 17979 urec_size > MAX_FUNCINFO_REC_SIZE || 17980 urec_size % sizeof(u32)) { 17981 verbose(env, "invalid func info rec size %u\n", urec_size); 17982 return -EINVAL; 17983 } 17984 17985 prog = env->prog; 17986 btf = prog->aux->btf; 17987 17988 urecord = make_bpfptr(attr->func_info, uattr.is_kernel); 17989 min_size = min_t(u32, krec_size, urec_size); 17990 17991 krecord = kvcalloc(nfuncs, krec_size, GFP_KERNEL_ACCOUNT | __GFP_NOWARN); 17992 if (!krecord) 17993 return -ENOMEM; 17994 17995 for (i = 0; i < nfuncs; i++) { 17996 ret = bpf_check_uarg_tail_zero(urecord, krec_size, urec_size); 17997 if (ret) { 17998 if (ret == -E2BIG) { 17999 verbose(env, "nonzero tailing record in func info"); 18000 /* set the size kernel expects so loader can zero 18001 * out the rest of the record. 18002 */ 18003 if (copy_to_bpfptr_offset(uattr, 18004 offsetof(union bpf_attr, func_info_rec_size), 18005 &min_size, sizeof(min_size))) 18006 ret = -EFAULT; 18007 } 18008 goto err_free; 18009 } 18010 18011 if (copy_from_bpfptr(&krecord[i], urecord, min_size)) { 18012 ret = -EFAULT; 18013 goto err_free; 18014 } 18015 18016 /* check insn_off */ 18017 ret = -EINVAL; 18018 if (i == 0) { 18019 if (krecord[i].insn_off) { 18020 verbose(env, 18021 "nonzero insn_off %u for the first func info record", 18022 krecord[i].insn_off); 18023 goto err_free; 18024 } 18025 } else if (krecord[i].insn_off <= prev_offset) { 18026 verbose(env, 18027 "same or smaller insn offset (%u) than previous func info record (%u)", 18028 krecord[i].insn_off, prev_offset); 18029 goto err_free; 18030 } 18031 18032 /* check type_id */ 18033 type = btf_type_by_id(btf, krecord[i].type_id); 18034 if (!type || !btf_type_is_func(type)) { 18035 verbose(env, "invalid type id %d in func info", 18036 krecord[i].type_id); 18037 goto err_free; 18038 } 18039 18040 func_proto = btf_type_by_id(btf, type->type); 18041 if (unlikely(!func_proto || !btf_type_is_func_proto(func_proto))) 18042 /* btf_func_check() already verified it during BTF load */ 18043 goto err_free; 18044 18045 prev_offset = krecord[i].insn_off; 18046 bpfptr_add(&urecord, urec_size); 18047 } 18048 18049 prog->aux->func_info = krecord; 18050 prog->aux->func_info_cnt = nfuncs; 18051 return 0; 18052 18053 err_free: 18054 kvfree(krecord); 18055 return ret; 18056 } 18057 18058 static int check_btf_func(struct bpf_verifier_env *env, 18059 const union bpf_attr *attr, 18060 bpfptr_t uattr) 18061 { 18062 const struct btf_type *type, *func_proto, *ret_type; 18063 u32 i, nfuncs, urec_size; 18064 struct bpf_func_info *krecord; 18065 struct bpf_func_info_aux *info_aux = NULL; 18066 struct bpf_prog *prog; 18067 const struct btf *btf; 18068 bpfptr_t urecord; 18069 bool scalar_return; 18070 int ret = -ENOMEM; 18071 18072 nfuncs = attr->func_info_cnt; 18073 if (!nfuncs) { 18074 if (check_abnormal_return(env)) 18075 return -EINVAL; 18076 return 0; 18077 } 18078 if (nfuncs != env->subprog_cnt) { 18079 verbose(env, "number of funcs in func_info doesn't match number of subprogs\n"); 18080 return -EINVAL; 18081 } 18082 18083 urec_size = attr->func_info_rec_size; 18084 18085 prog = env->prog; 18086 btf = prog->aux->btf; 18087 18088 urecord = make_bpfptr(attr->func_info, uattr.is_kernel); 18089 18090 krecord = prog->aux->func_info; 18091 info_aux = kcalloc(nfuncs, sizeof(*info_aux), GFP_KERNEL_ACCOUNT | __GFP_NOWARN); 18092 if (!info_aux) 18093 return -ENOMEM; 18094 18095 for (i = 0; i < nfuncs; i++) { 18096 /* check insn_off */ 18097 ret = -EINVAL; 18098 18099 if (env->subprog_info[i].start != krecord[i].insn_off) { 18100 verbose(env, "func_info BTF section doesn't match subprog layout in BPF program\n"); 18101 goto err_free; 18102 } 18103 18104 /* Already checked type_id */ 18105 type = btf_type_by_id(btf, krecord[i].type_id); 18106 info_aux[i].linkage = BTF_INFO_VLEN(type->info); 18107 /* Already checked func_proto */ 18108 func_proto = btf_type_by_id(btf, type->type); 18109 18110 ret_type = btf_type_skip_modifiers(btf, func_proto->type, NULL); 18111 scalar_return = 18112 btf_type_is_small_int(ret_type) || btf_is_any_enum(ret_type); 18113 if (i && !scalar_return && env->subprog_info[i].has_ld_abs) { 18114 verbose(env, "LD_ABS is only allowed in functions that return 'int'.\n"); 18115 goto err_free; 18116 } 18117 if (i && !scalar_return && env->subprog_info[i].has_tail_call) { 18118 verbose(env, "tail_call is only allowed in functions that return 'int'.\n"); 18119 goto err_free; 18120 } 18121 18122 bpfptr_add(&urecord, urec_size); 18123 } 18124 18125 prog->aux->func_info_aux = info_aux; 18126 return 0; 18127 18128 err_free: 18129 kfree(info_aux); 18130 return ret; 18131 } 18132 18133 static void adjust_btf_func(struct bpf_verifier_env *env) 18134 { 18135 struct bpf_prog_aux *aux = env->prog->aux; 18136 int i; 18137 18138 if (!aux->func_info) 18139 return; 18140 18141 /* func_info is not available for hidden subprogs */ 18142 for (i = 0; i < env->subprog_cnt - env->hidden_subprog_cnt; i++) 18143 aux->func_info[i].insn_off = env->subprog_info[i].start; 18144 } 18145 18146 #define MIN_BPF_LINEINFO_SIZE offsetofend(struct bpf_line_info, line_col) 18147 #define MAX_LINEINFO_REC_SIZE MAX_FUNCINFO_REC_SIZE 18148 18149 static int check_btf_line(struct bpf_verifier_env *env, 18150 const union bpf_attr *attr, 18151 bpfptr_t uattr) 18152 { 18153 u32 i, s, nr_linfo, ncopy, expected_size, rec_size, prev_offset = 0; 18154 struct bpf_subprog_info *sub; 18155 struct bpf_line_info *linfo; 18156 struct bpf_prog *prog; 18157 const struct btf *btf; 18158 bpfptr_t ulinfo; 18159 int err; 18160 18161 nr_linfo = attr->line_info_cnt; 18162 if (!nr_linfo) 18163 return 0; 18164 if (nr_linfo > INT_MAX / sizeof(struct bpf_line_info)) 18165 return -EINVAL; 18166 18167 rec_size = attr->line_info_rec_size; 18168 if (rec_size < MIN_BPF_LINEINFO_SIZE || 18169 rec_size > MAX_LINEINFO_REC_SIZE || 18170 rec_size & (sizeof(u32) - 1)) 18171 return -EINVAL; 18172 18173 /* Need to zero it in case the userspace may 18174 * pass in a smaller bpf_line_info object. 18175 */ 18176 linfo = kvcalloc(nr_linfo, sizeof(struct bpf_line_info), 18177 GFP_KERNEL_ACCOUNT | __GFP_NOWARN); 18178 if (!linfo) 18179 return -ENOMEM; 18180 18181 prog = env->prog; 18182 btf = prog->aux->btf; 18183 18184 s = 0; 18185 sub = env->subprog_info; 18186 ulinfo = make_bpfptr(attr->line_info, uattr.is_kernel); 18187 expected_size = sizeof(struct bpf_line_info); 18188 ncopy = min_t(u32, expected_size, rec_size); 18189 for (i = 0; i < nr_linfo; i++) { 18190 err = bpf_check_uarg_tail_zero(ulinfo, expected_size, rec_size); 18191 if (err) { 18192 if (err == -E2BIG) { 18193 verbose(env, "nonzero tailing record in line_info"); 18194 if (copy_to_bpfptr_offset(uattr, 18195 offsetof(union bpf_attr, line_info_rec_size), 18196 &expected_size, sizeof(expected_size))) 18197 err = -EFAULT; 18198 } 18199 goto err_free; 18200 } 18201 18202 if (copy_from_bpfptr(&linfo[i], ulinfo, ncopy)) { 18203 err = -EFAULT; 18204 goto err_free; 18205 } 18206 18207 /* 18208 * Check insn_off to ensure 18209 * 1) strictly increasing AND 18210 * 2) bounded by prog->len 18211 * 18212 * The linfo[0].insn_off == 0 check logically falls into 18213 * the later "missing bpf_line_info for func..." case 18214 * because the first linfo[0].insn_off must be the 18215 * first sub also and the first sub must have 18216 * subprog_info[0].start == 0. 18217 */ 18218 if ((i && linfo[i].insn_off <= prev_offset) || 18219 linfo[i].insn_off >= prog->len) { 18220 verbose(env, "Invalid line_info[%u].insn_off:%u (prev_offset:%u prog->len:%u)\n", 18221 i, linfo[i].insn_off, prev_offset, 18222 prog->len); 18223 err = -EINVAL; 18224 goto err_free; 18225 } 18226 18227 if (!prog->insnsi[linfo[i].insn_off].code) { 18228 verbose(env, 18229 "Invalid insn code at line_info[%u].insn_off\n", 18230 i); 18231 err = -EINVAL; 18232 goto err_free; 18233 } 18234 18235 if (!btf_name_by_offset(btf, linfo[i].line_off) || 18236 !btf_name_by_offset(btf, linfo[i].file_name_off)) { 18237 verbose(env, "Invalid line_info[%u].line_off or .file_name_off\n", i); 18238 err = -EINVAL; 18239 goto err_free; 18240 } 18241 18242 if (s != env->subprog_cnt) { 18243 if (linfo[i].insn_off == sub[s].start) { 18244 sub[s].linfo_idx = i; 18245 s++; 18246 } else if (sub[s].start < linfo[i].insn_off) { 18247 verbose(env, "missing bpf_line_info for func#%u\n", s); 18248 err = -EINVAL; 18249 goto err_free; 18250 } 18251 } 18252 18253 prev_offset = linfo[i].insn_off; 18254 bpfptr_add(&ulinfo, rec_size); 18255 } 18256 18257 if (s != env->subprog_cnt) { 18258 verbose(env, "missing bpf_line_info for %u funcs starting from func#%u\n", 18259 env->subprog_cnt - s, s); 18260 err = -EINVAL; 18261 goto err_free; 18262 } 18263 18264 prog->aux->linfo = linfo; 18265 prog->aux->nr_linfo = nr_linfo; 18266 18267 return 0; 18268 18269 err_free: 18270 kvfree(linfo); 18271 return err; 18272 } 18273 18274 #define MIN_CORE_RELO_SIZE sizeof(struct bpf_core_relo) 18275 #define MAX_CORE_RELO_SIZE MAX_FUNCINFO_REC_SIZE 18276 18277 static int check_core_relo(struct bpf_verifier_env *env, 18278 const union bpf_attr *attr, 18279 bpfptr_t uattr) 18280 { 18281 u32 i, nr_core_relo, ncopy, expected_size, rec_size; 18282 struct bpf_core_relo core_relo = {}; 18283 struct bpf_prog *prog = env->prog; 18284 const struct btf *btf = prog->aux->btf; 18285 struct bpf_core_ctx ctx = { 18286 .log = &env->log, 18287 .btf = btf, 18288 }; 18289 bpfptr_t u_core_relo; 18290 int err; 18291 18292 nr_core_relo = attr->core_relo_cnt; 18293 if (!nr_core_relo) 18294 return 0; 18295 if (nr_core_relo > INT_MAX / sizeof(struct bpf_core_relo)) 18296 return -EINVAL; 18297 18298 rec_size = attr->core_relo_rec_size; 18299 if (rec_size < MIN_CORE_RELO_SIZE || 18300 rec_size > MAX_CORE_RELO_SIZE || 18301 rec_size % sizeof(u32)) 18302 return -EINVAL; 18303 18304 u_core_relo = make_bpfptr(attr->core_relos, uattr.is_kernel); 18305 expected_size = sizeof(struct bpf_core_relo); 18306 ncopy = min_t(u32, expected_size, rec_size); 18307 18308 /* Unlike func_info and line_info, copy and apply each CO-RE 18309 * relocation record one at a time. 18310 */ 18311 for (i = 0; i < nr_core_relo; i++) { 18312 /* future proofing when sizeof(bpf_core_relo) changes */ 18313 err = bpf_check_uarg_tail_zero(u_core_relo, expected_size, rec_size); 18314 if (err) { 18315 if (err == -E2BIG) { 18316 verbose(env, "nonzero tailing record in core_relo"); 18317 if (copy_to_bpfptr_offset(uattr, 18318 offsetof(union bpf_attr, core_relo_rec_size), 18319 &expected_size, sizeof(expected_size))) 18320 err = -EFAULT; 18321 } 18322 break; 18323 } 18324 18325 if (copy_from_bpfptr(&core_relo, u_core_relo, ncopy)) { 18326 err = -EFAULT; 18327 break; 18328 } 18329 18330 if (core_relo.insn_off % 8 || core_relo.insn_off / 8 >= prog->len) { 18331 verbose(env, "Invalid core_relo[%u].insn_off:%u prog->len:%u\n", 18332 i, core_relo.insn_off, prog->len); 18333 err = -EINVAL; 18334 break; 18335 } 18336 18337 err = bpf_core_apply(&ctx, &core_relo, i, 18338 &prog->insnsi[core_relo.insn_off / 8]); 18339 if (err) 18340 break; 18341 bpfptr_add(&u_core_relo, rec_size); 18342 } 18343 return err; 18344 } 18345 18346 static int check_btf_info_early(struct bpf_verifier_env *env, 18347 const union bpf_attr *attr, 18348 bpfptr_t uattr) 18349 { 18350 struct btf *btf; 18351 int err; 18352 18353 if (!attr->func_info_cnt && !attr->line_info_cnt) { 18354 if (check_abnormal_return(env)) 18355 return -EINVAL; 18356 return 0; 18357 } 18358 18359 btf = btf_get_by_fd(attr->prog_btf_fd); 18360 if (IS_ERR(btf)) 18361 return PTR_ERR(btf); 18362 if (btf_is_kernel(btf)) { 18363 btf_put(btf); 18364 return -EACCES; 18365 } 18366 env->prog->aux->btf = btf; 18367 18368 err = check_btf_func_early(env, attr, uattr); 18369 if (err) 18370 return err; 18371 return 0; 18372 } 18373 18374 static int check_btf_info(struct bpf_verifier_env *env, 18375 const union bpf_attr *attr, 18376 bpfptr_t uattr) 18377 { 18378 int err; 18379 18380 if (!attr->func_info_cnt && !attr->line_info_cnt) { 18381 if (check_abnormal_return(env)) 18382 return -EINVAL; 18383 return 0; 18384 } 18385 18386 err = check_btf_func(env, attr, uattr); 18387 if (err) 18388 return err; 18389 18390 err = check_btf_line(env, attr, uattr); 18391 if (err) 18392 return err; 18393 18394 err = check_core_relo(env, attr, uattr); 18395 if (err) 18396 return err; 18397 18398 return 0; 18399 } 18400 18401 /* check %cur's range satisfies %old's */ 18402 static bool range_within(const struct bpf_reg_state *old, 18403 const struct bpf_reg_state *cur) 18404 { 18405 return old->umin_value <= cur->umin_value && 18406 old->umax_value >= cur->umax_value && 18407 old->smin_value <= cur->smin_value && 18408 old->smax_value >= cur->smax_value && 18409 old->u32_min_value <= cur->u32_min_value && 18410 old->u32_max_value >= cur->u32_max_value && 18411 old->s32_min_value <= cur->s32_min_value && 18412 old->s32_max_value >= cur->s32_max_value; 18413 } 18414 18415 /* If in the old state two registers had the same id, then they need to have 18416 * the same id in the new state as well. But that id could be different from 18417 * the old state, so we need to track the mapping from old to new ids. 18418 * Once we have seen that, say, a reg with old id 5 had new id 9, any subsequent 18419 * regs with old id 5 must also have new id 9 for the new state to be safe. But 18420 * regs with a different old id could still have new id 9, we don't care about 18421 * that. 18422 * So we look through our idmap to see if this old id has been seen before. If 18423 * so, we require the new id to match; otherwise, we add the id pair to the map. 18424 */ 18425 static bool check_ids(u32 old_id, u32 cur_id, struct bpf_idmap *idmap) 18426 { 18427 struct bpf_id_pair *map = idmap->map; 18428 unsigned int i; 18429 18430 /* either both IDs should be set or both should be zero */ 18431 if (!!old_id != !!cur_id) 18432 return false; 18433 18434 if (old_id == 0) /* cur_id == 0 as well */ 18435 return true; 18436 18437 for (i = 0; i < BPF_ID_MAP_SIZE; i++) { 18438 if (!map[i].old) { 18439 /* Reached an empty slot; haven't seen this id before */ 18440 map[i].old = old_id; 18441 map[i].cur = cur_id; 18442 return true; 18443 } 18444 if (map[i].old == old_id) 18445 return map[i].cur == cur_id; 18446 if (map[i].cur == cur_id) 18447 return false; 18448 } 18449 /* We ran out of idmap slots, which should be impossible */ 18450 WARN_ON_ONCE(1); 18451 return false; 18452 } 18453 18454 /* Similar to check_ids(), but allocate a unique temporary ID 18455 * for 'old_id' or 'cur_id' of zero. 18456 * This makes pairs like '0 vs unique ID', 'unique ID vs 0' valid. 18457 */ 18458 static bool check_scalar_ids(u32 old_id, u32 cur_id, struct bpf_idmap *idmap) 18459 { 18460 old_id = old_id ? old_id : ++idmap->tmp_id_gen; 18461 cur_id = cur_id ? cur_id : ++idmap->tmp_id_gen; 18462 18463 return check_ids(old_id, cur_id, idmap); 18464 } 18465 18466 static void clean_func_state(struct bpf_verifier_env *env, 18467 struct bpf_func_state *st) 18468 { 18469 enum bpf_reg_liveness live; 18470 int i, j; 18471 18472 for (i = 0; i < BPF_REG_FP; i++) { 18473 live = st->regs[i].live; 18474 /* liveness must not touch this register anymore */ 18475 st->regs[i].live |= REG_LIVE_DONE; 18476 if (!(live & REG_LIVE_READ)) 18477 /* since the register is unused, clear its state 18478 * to make further comparison simpler 18479 */ 18480 __mark_reg_not_init(env, &st->regs[i]); 18481 } 18482 18483 for (i = 0; i < st->allocated_stack / BPF_REG_SIZE; i++) { 18484 live = st->stack[i].spilled_ptr.live; 18485 /* liveness must not touch this stack slot anymore */ 18486 st->stack[i].spilled_ptr.live |= REG_LIVE_DONE; 18487 if (!(live & REG_LIVE_READ)) { 18488 __mark_reg_not_init(env, &st->stack[i].spilled_ptr); 18489 for (j = 0; j < BPF_REG_SIZE; j++) 18490 st->stack[i].slot_type[j] = STACK_INVALID; 18491 } 18492 } 18493 } 18494 18495 static void clean_verifier_state(struct bpf_verifier_env *env, 18496 struct bpf_verifier_state *st) 18497 { 18498 int i; 18499 18500 for (i = 0; i <= st->curframe; i++) 18501 clean_func_state(env, st->frame[i]); 18502 } 18503 18504 /* the parentage chains form a tree. 18505 * the verifier states are added to state lists at given insn and 18506 * pushed into state stack for future exploration. 18507 * when the verifier reaches bpf_exit insn some of the verifier states 18508 * stored in the state lists have their final liveness state already, 18509 * but a lot of states will get revised from liveness point of view when 18510 * the verifier explores other branches. 18511 * Example: 18512 * 1: r0 = 1 18513 * 2: if r1 == 100 goto pc+1 18514 * 3: r0 = 2 18515 * 4: exit 18516 * when the verifier reaches exit insn the register r0 in the state list of 18517 * insn 2 will be seen as !REG_LIVE_READ. Then the verifier pops the other_branch 18518 * of insn 2 and goes exploring further. At the insn 4 it will walk the 18519 * parentage chain from insn 4 into insn 2 and will mark r0 as REG_LIVE_READ. 18520 * 18521 * Since the verifier pushes the branch states as it sees them while exploring 18522 * the program the condition of walking the branch instruction for the second 18523 * time means that all states below this branch were already explored and 18524 * their final liveness marks are already propagated. 18525 * Hence when the verifier completes the search of state list in is_state_visited() 18526 * we can call this clean_live_states() function to mark all liveness states 18527 * as REG_LIVE_DONE to indicate that 'parent' pointers of 'struct bpf_reg_state' 18528 * will not be used. 18529 * This function also clears the registers and stack for states that !READ 18530 * to simplify state merging. 18531 * 18532 * Important note here that walking the same branch instruction in the callee 18533 * doesn't meant that the states are DONE. The verifier has to compare 18534 * the callsites 18535 */ 18536 static void clean_live_states(struct bpf_verifier_env *env, int insn, 18537 struct bpf_verifier_state *cur) 18538 { 18539 struct bpf_verifier_state_list *sl; 18540 struct list_head *pos, *head; 18541 18542 head = explored_state(env, insn); 18543 list_for_each(pos, head) { 18544 sl = container_of(pos, struct bpf_verifier_state_list, node); 18545 if (sl->state.branches) 18546 continue; 18547 if (sl->state.insn_idx != insn || 18548 !same_callsites(&sl->state, cur)) 18549 continue; 18550 if (sl->state.frame[0]->regs[0].live & REG_LIVE_DONE) 18551 /* all regs in this state in all frames were already marked */ 18552 continue; 18553 if (incomplete_read_marks(env, &sl->state)) 18554 continue; 18555 clean_verifier_state(env, &sl->state); 18556 } 18557 } 18558 18559 static bool regs_exact(const struct bpf_reg_state *rold, 18560 const struct bpf_reg_state *rcur, 18561 struct bpf_idmap *idmap) 18562 { 18563 return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 && 18564 check_ids(rold->id, rcur->id, idmap) && 18565 check_ids(rold->ref_obj_id, rcur->ref_obj_id, idmap); 18566 } 18567 18568 enum exact_level { 18569 NOT_EXACT, 18570 EXACT, 18571 RANGE_WITHIN 18572 }; 18573 18574 /* Returns true if (rold safe implies rcur safe) */ 18575 static bool regsafe(struct bpf_verifier_env *env, struct bpf_reg_state *rold, 18576 struct bpf_reg_state *rcur, struct bpf_idmap *idmap, 18577 enum exact_level exact) 18578 { 18579 if (exact == EXACT) 18580 return regs_exact(rold, rcur, idmap); 18581 18582 if (!(rold->live & REG_LIVE_READ) && exact == NOT_EXACT) 18583 /* explored state didn't use this */ 18584 return true; 18585 if (rold->type == NOT_INIT) { 18586 if (exact == NOT_EXACT || rcur->type == NOT_INIT) 18587 /* explored state can't have used this */ 18588 return true; 18589 } 18590 18591 /* Enforce that register types have to match exactly, including their 18592 * modifiers (like PTR_MAYBE_NULL, MEM_RDONLY, etc), as a general 18593 * rule. 18594 * 18595 * One can make a point that using a pointer register as unbounded 18596 * SCALAR would be technically acceptable, but this could lead to 18597 * pointer leaks because scalars are allowed to leak while pointers 18598 * are not. We could make this safe in special cases if root is 18599 * calling us, but it's probably not worth the hassle. 18600 * 18601 * Also, register types that are *not* MAYBE_NULL could technically be 18602 * safe to use as their MAYBE_NULL variants (e.g., PTR_TO_MAP_VALUE 18603 * is safe to be used as PTR_TO_MAP_VALUE_OR_NULL, provided both point 18604 * to the same map). 18605 * However, if the old MAYBE_NULL register then got NULL checked, 18606 * doing so could have affected others with the same id, and we can't 18607 * check for that because we lost the id when we converted to 18608 * a non-MAYBE_NULL variant. 18609 * So, as a general rule we don't allow mixing MAYBE_NULL and 18610 * non-MAYBE_NULL registers as well. 18611 */ 18612 if (rold->type != rcur->type) 18613 return false; 18614 18615 switch (base_type(rold->type)) { 18616 case SCALAR_VALUE: 18617 if (env->explore_alu_limits) { 18618 /* explore_alu_limits disables tnum_in() and range_within() 18619 * logic and requires everything to be strict 18620 */ 18621 return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 && 18622 check_scalar_ids(rold->id, rcur->id, idmap); 18623 } 18624 if (!rold->precise && exact == NOT_EXACT) 18625 return true; 18626 if ((rold->id & BPF_ADD_CONST) != (rcur->id & BPF_ADD_CONST)) 18627 return false; 18628 if ((rold->id & BPF_ADD_CONST) && (rold->off != rcur->off)) 18629 return false; 18630 /* Why check_ids() for scalar registers? 18631 * 18632 * Consider the following BPF code: 18633 * 1: r6 = ... unbound scalar, ID=a ... 18634 * 2: r7 = ... unbound scalar, ID=b ... 18635 * 3: if (r6 > r7) goto +1 18636 * 4: r6 = r7 18637 * 5: if (r6 > X) goto ... 18638 * 6: ... memory operation using r7 ... 18639 * 18640 * First verification path is [1-6]: 18641 * - at (4) same bpf_reg_state::id (b) would be assigned to r6 and r7; 18642 * - at (5) r6 would be marked <= X, sync_linked_regs() would also mark 18643 * r7 <= X, because r6 and r7 share same id. 18644 * Next verification path is [1-4, 6]. 18645 * 18646 * Instruction (6) would be reached in two states: 18647 * I. r6{.id=b}, r7{.id=b} via path 1-6; 18648 * II. r6{.id=a}, r7{.id=b} via path 1-4, 6. 18649 * 18650 * Use check_ids() to distinguish these states. 18651 * --- 18652 * Also verify that new value satisfies old value range knowledge. 18653 */ 18654 return range_within(rold, rcur) && 18655 tnum_in(rold->var_off, rcur->var_off) && 18656 check_scalar_ids(rold->id, rcur->id, idmap); 18657 case PTR_TO_MAP_KEY: 18658 case PTR_TO_MAP_VALUE: 18659 case PTR_TO_MEM: 18660 case PTR_TO_BUF: 18661 case PTR_TO_TP_BUFFER: 18662 /* If the new min/max/var_off satisfy the old ones and 18663 * everything else matches, we are OK. 18664 */ 18665 return memcmp(rold, rcur, offsetof(struct bpf_reg_state, var_off)) == 0 && 18666 range_within(rold, rcur) && 18667 tnum_in(rold->var_off, rcur->var_off) && 18668 check_ids(rold->id, rcur->id, idmap) && 18669 check_ids(rold->ref_obj_id, rcur->ref_obj_id, idmap); 18670 case PTR_TO_PACKET_META: 18671 case PTR_TO_PACKET: 18672 /* We must have at least as much range as the old ptr 18673 * did, so that any accesses which were safe before are 18674 * still safe. This is true even if old range < old off, 18675 * since someone could have accessed through (ptr - k), or 18676 * even done ptr -= k in a register, to get a safe access. 18677 */ 18678 if (rold->range > rcur->range) 18679 return false; 18680 /* If the offsets don't match, we can't trust our alignment; 18681 * nor can we be sure that we won't fall out of range. 18682 */ 18683 if (rold->off != rcur->off) 18684 return false; 18685 /* id relations must be preserved */ 18686 if (!check_ids(rold->id, rcur->id, idmap)) 18687 return false; 18688 /* new val must satisfy old val knowledge */ 18689 return range_within(rold, rcur) && 18690 tnum_in(rold->var_off, rcur->var_off); 18691 case PTR_TO_STACK: 18692 /* two stack pointers are equal only if they're pointing to 18693 * the same stack frame, since fp-8 in foo != fp-8 in bar 18694 */ 18695 return regs_exact(rold, rcur, idmap) && rold->frameno == rcur->frameno; 18696 case PTR_TO_ARENA: 18697 return true; 18698 default: 18699 return regs_exact(rold, rcur, idmap); 18700 } 18701 } 18702 18703 static struct bpf_reg_state unbound_reg; 18704 18705 static __init int unbound_reg_init(void) 18706 { 18707 __mark_reg_unknown_imprecise(&unbound_reg); 18708 unbound_reg.live |= REG_LIVE_READ; 18709 return 0; 18710 } 18711 late_initcall(unbound_reg_init); 18712 18713 static bool is_stack_all_misc(struct bpf_verifier_env *env, 18714 struct bpf_stack_state *stack) 18715 { 18716 u32 i; 18717 18718 for (i = 0; i < ARRAY_SIZE(stack->slot_type); ++i) { 18719 if ((stack->slot_type[i] == STACK_MISC) || 18720 (stack->slot_type[i] == STACK_INVALID && env->allow_uninit_stack)) 18721 continue; 18722 return false; 18723 } 18724 18725 return true; 18726 } 18727 18728 static struct bpf_reg_state *scalar_reg_for_stack(struct bpf_verifier_env *env, 18729 struct bpf_stack_state *stack) 18730 { 18731 if (is_spilled_scalar_reg64(stack)) 18732 return &stack->spilled_ptr; 18733 18734 if (is_stack_all_misc(env, stack)) 18735 return &unbound_reg; 18736 18737 return NULL; 18738 } 18739 18740 static bool stacksafe(struct bpf_verifier_env *env, struct bpf_func_state *old, 18741 struct bpf_func_state *cur, struct bpf_idmap *idmap, 18742 enum exact_level exact) 18743 { 18744 int i, spi; 18745 18746 /* walk slots of the explored stack and ignore any additional 18747 * slots in the current stack, since explored(safe) state 18748 * didn't use them 18749 */ 18750 for (i = 0; i < old->allocated_stack; i++) { 18751 struct bpf_reg_state *old_reg, *cur_reg; 18752 18753 spi = i / BPF_REG_SIZE; 18754 18755 if (exact != NOT_EXACT && 18756 (i >= cur->allocated_stack || 18757 old->stack[spi].slot_type[i % BPF_REG_SIZE] != 18758 cur->stack[spi].slot_type[i % BPF_REG_SIZE])) 18759 return false; 18760 18761 if (!(old->stack[spi].spilled_ptr.live & REG_LIVE_READ) 18762 && exact == NOT_EXACT) { 18763 i += BPF_REG_SIZE - 1; 18764 /* explored state didn't use this */ 18765 continue; 18766 } 18767 18768 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_INVALID) 18769 continue; 18770 18771 if (env->allow_uninit_stack && 18772 old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC) 18773 continue; 18774 18775 /* explored stack has more populated slots than current stack 18776 * and these slots were used 18777 */ 18778 if (i >= cur->allocated_stack) 18779 return false; 18780 18781 /* 64-bit scalar spill vs all slots MISC and vice versa. 18782 * Load from all slots MISC produces unbound scalar. 18783 * Construct a fake register for such stack and call 18784 * regsafe() to ensure scalar ids are compared. 18785 */ 18786 old_reg = scalar_reg_for_stack(env, &old->stack[spi]); 18787 cur_reg = scalar_reg_for_stack(env, &cur->stack[spi]); 18788 if (old_reg && cur_reg) { 18789 if (!regsafe(env, old_reg, cur_reg, idmap, exact)) 18790 return false; 18791 i += BPF_REG_SIZE - 1; 18792 continue; 18793 } 18794 18795 /* if old state was safe with misc data in the stack 18796 * it will be safe with zero-initialized stack. 18797 * The opposite is not true 18798 */ 18799 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC && 18800 cur->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_ZERO) 18801 continue; 18802 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] != 18803 cur->stack[spi].slot_type[i % BPF_REG_SIZE]) 18804 /* Ex: old explored (safe) state has STACK_SPILL in 18805 * this stack slot, but current has STACK_MISC -> 18806 * this verifier states are not equivalent, 18807 * return false to continue verification of this path 18808 */ 18809 return false; 18810 if (i % BPF_REG_SIZE != BPF_REG_SIZE - 1) 18811 continue; 18812 /* Both old and cur are having same slot_type */ 18813 switch (old->stack[spi].slot_type[BPF_REG_SIZE - 1]) { 18814 case STACK_SPILL: 18815 /* when explored and current stack slot are both storing 18816 * spilled registers, check that stored pointers types 18817 * are the same as well. 18818 * Ex: explored safe path could have stored 18819 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -8} 18820 * but current path has stored: 18821 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -16} 18822 * such verifier states are not equivalent. 18823 * return false to continue verification of this path 18824 */ 18825 if (!regsafe(env, &old->stack[spi].spilled_ptr, 18826 &cur->stack[spi].spilled_ptr, idmap, exact)) 18827 return false; 18828 break; 18829 case STACK_DYNPTR: 18830 old_reg = &old->stack[spi].spilled_ptr; 18831 cur_reg = &cur->stack[spi].spilled_ptr; 18832 if (old_reg->dynptr.type != cur_reg->dynptr.type || 18833 old_reg->dynptr.first_slot != cur_reg->dynptr.first_slot || 18834 !check_ids(old_reg->ref_obj_id, cur_reg->ref_obj_id, idmap)) 18835 return false; 18836 break; 18837 case STACK_ITER: 18838 old_reg = &old->stack[spi].spilled_ptr; 18839 cur_reg = &cur->stack[spi].spilled_ptr; 18840 /* iter.depth is not compared between states as it 18841 * doesn't matter for correctness and would otherwise 18842 * prevent convergence; we maintain it only to prevent 18843 * infinite loop check triggering, see 18844 * iter_active_depths_differ() 18845 */ 18846 if (old_reg->iter.btf != cur_reg->iter.btf || 18847 old_reg->iter.btf_id != cur_reg->iter.btf_id || 18848 old_reg->iter.state != cur_reg->iter.state || 18849 /* ignore {old_reg,cur_reg}->iter.depth, see above */ 18850 !check_ids(old_reg->ref_obj_id, cur_reg->ref_obj_id, idmap)) 18851 return false; 18852 break; 18853 case STACK_IRQ_FLAG: 18854 old_reg = &old->stack[spi].spilled_ptr; 18855 cur_reg = &cur->stack[spi].spilled_ptr; 18856 if (!check_ids(old_reg->ref_obj_id, cur_reg->ref_obj_id, idmap) || 18857 old_reg->irq.kfunc_class != cur_reg->irq.kfunc_class) 18858 return false; 18859 break; 18860 case STACK_MISC: 18861 case STACK_ZERO: 18862 case STACK_INVALID: 18863 continue; 18864 /* Ensure that new unhandled slot types return false by default */ 18865 default: 18866 return false; 18867 } 18868 } 18869 return true; 18870 } 18871 18872 static bool refsafe(struct bpf_verifier_state *old, struct bpf_verifier_state *cur, 18873 struct bpf_idmap *idmap) 18874 { 18875 int i; 18876 18877 if (old->acquired_refs != cur->acquired_refs) 18878 return false; 18879 18880 if (old->active_locks != cur->active_locks) 18881 return false; 18882 18883 if (old->active_preempt_locks != cur->active_preempt_locks) 18884 return false; 18885 18886 if (old->active_rcu_lock != cur->active_rcu_lock) 18887 return false; 18888 18889 if (!check_ids(old->active_irq_id, cur->active_irq_id, idmap)) 18890 return false; 18891 18892 if (!check_ids(old->active_lock_id, cur->active_lock_id, idmap) || 18893 old->active_lock_ptr != cur->active_lock_ptr) 18894 return false; 18895 18896 for (i = 0; i < old->acquired_refs; i++) { 18897 if (!check_ids(old->refs[i].id, cur->refs[i].id, idmap) || 18898 old->refs[i].type != cur->refs[i].type) 18899 return false; 18900 switch (old->refs[i].type) { 18901 case REF_TYPE_PTR: 18902 case REF_TYPE_IRQ: 18903 break; 18904 case REF_TYPE_LOCK: 18905 case REF_TYPE_RES_LOCK: 18906 case REF_TYPE_RES_LOCK_IRQ: 18907 if (old->refs[i].ptr != cur->refs[i].ptr) 18908 return false; 18909 break; 18910 default: 18911 WARN_ONCE(1, "Unhandled enum type for reference state: %d\n", old->refs[i].type); 18912 return false; 18913 } 18914 } 18915 18916 return true; 18917 } 18918 18919 /* compare two verifier states 18920 * 18921 * all states stored in state_list are known to be valid, since 18922 * verifier reached 'bpf_exit' instruction through them 18923 * 18924 * this function is called when verifier exploring different branches of 18925 * execution popped from the state stack. If it sees an old state that has 18926 * more strict register state and more strict stack state then this execution 18927 * branch doesn't need to be explored further, since verifier already 18928 * concluded that more strict state leads to valid finish. 18929 * 18930 * Therefore two states are equivalent if register state is more conservative 18931 * and explored stack state is more conservative than the current one. 18932 * Example: 18933 * explored current 18934 * (slot1=INV slot2=MISC) == (slot1=MISC slot2=MISC) 18935 * (slot1=MISC slot2=MISC) != (slot1=INV slot2=MISC) 18936 * 18937 * In other words if current stack state (one being explored) has more 18938 * valid slots than old one that already passed validation, it means 18939 * the verifier can stop exploring and conclude that current state is valid too 18940 * 18941 * Similarly with registers. If explored state has register type as invalid 18942 * whereas register type in current state is meaningful, it means that 18943 * the current state will reach 'bpf_exit' instruction safely 18944 */ 18945 static bool func_states_equal(struct bpf_verifier_env *env, struct bpf_func_state *old, 18946 struct bpf_func_state *cur, u32 insn_idx, enum exact_level exact) 18947 { 18948 u16 live_regs = env->insn_aux_data[insn_idx].live_regs_before; 18949 u16 i; 18950 18951 if (old->callback_depth > cur->callback_depth) 18952 return false; 18953 18954 for (i = 0; i < MAX_BPF_REG; i++) 18955 if (((1 << i) & live_regs) && 18956 !regsafe(env, &old->regs[i], &cur->regs[i], 18957 &env->idmap_scratch, exact)) 18958 return false; 18959 18960 if (!stacksafe(env, old, cur, &env->idmap_scratch, exact)) 18961 return false; 18962 18963 return true; 18964 } 18965 18966 static void reset_idmap_scratch(struct bpf_verifier_env *env) 18967 { 18968 env->idmap_scratch.tmp_id_gen = env->id_gen; 18969 memset(&env->idmap_scratch.map, 0, sizeof(env->idmap_scratch.map)); 18970 } 18971 18972 static bool states_equal(struct bpf_verifier_env *env, 18973 struct bpf_verifier_state *old, 18974 struct bpf_verifier_state *cur, 18975 enum exact_level exact) 18976 { 18977 u32 insn_idx; 18978 int i; 18979 18980 if (old->curframe != cur->curframe) 18981 return false; 18982 18983 reset_idmap_scratch(env); 18984 18985 /* Verification state from speculative execution simulation 18986 * must never prune a non-speculative execution one. 18987 */ 18988 if (old->speculative && !cur->speculative) 18989 return false; 18990 18991 if (old->in_sleepable != cur->in_sleepable) 18992 return false; 18993 18994 if (!refsafe(old, cur, &env->idmap_scratch)) 18995 return false; 18996 18997 /* for states to be equal callsites have to be the same 18998 * and all frame states need to be equivalent 18999 */ 19000 for (i = 0; i <= old->curframe; i++) { 19001 insn_idx = frame_insn_idx(old, i); 19002 if (old->frame[i]->callsite != cur->frame[i]->callsite) 19003 return false; 19004 if (!func_states_equal(env, old->frame[i], cur->frame[i], insn_idx, exact)) 19005 return false; 19006 } 19007 return true; 19008 } 19009 19010 /* Return 0 if no propagation happened. Return negative error code if error 19011 * happened. Otherwise, return the propagated bit. 19012 */ 19013 static int propagate_liveness_reg(struct bpf_verifier_env *env, 19014 struct bpf_reg_state *reg, 19015 struct bpf_reg_state *parent_reg) 19016 { 19017 u8 parent_flag = parent_reg->live & REG_LIVE_READ; 19018 u8 flag = reg->live & REG_LIVE_READ; 19019 int err; 19020 19021 /* When comes here, read flags of PARENT_REG or REG could be any of 19022 * REG_LIVE_READ64, REG_LIVE_READ32, REG_LIVE_NONE. There is no need 19023 * of propagation if PARENT_REG has strongest REG_LIVE_READ64. 19024 */ 19025 if (parent_flag == REG_LIVE_READ64 || 19026 /* Or if there is no read flag from REG. */ 19027 !flag || 19028 /* Or if the read flag from REG is the same as PARENT_REG. */ 19029 parent_flag == flag) 19030 return 0; 19031 19032 err = mark_reg_read(env, reg, parent_reg, flag); 19033 if (err) 19034 return err; 19035 19036 return flag; 19037 } 19038 19039 /* A write screens off any subsequent reads; but write marks come from the 19040 * straight-line code between a state and its parent. When we arrive at an 19041 * equivalent state (jump target or such) we didn't arrive by the straight-line 19042 * code, so read marks in the state must propagate to the parent regardless 19043 * of the state's write marks. That's what 'parent == state->parent' comparison 19044 * in mark_reg_read() is for. 19045 */ 19046 static int propagate_liveness(struct bpf_verifier_env *env, 19047 const struct bpf_verifier_state *vstate, 19048 struct bpf_verifier_state *vparent, 19049 bool *changed) 19050 { 19051 struct bpf_reg_state *state_reg, *parent_reg; 19052 struct bpf_func_state *state, *parent; 19053 int i, frame, err = 0; 19054 bool tmp = false; 19055 19056 changed = changed ?: &tmp; 19057 if (vparent->curframe != vstate->curframe) { 19058 WARN(1, "propagate_live: parent frame %d current frame %d\n", 19059 vparent->curframe, vstate->curframe); 19060 return -EFAULT; 19061 } 19062 /* Propagate read liveness of registers... */ 19063 BUILD_BUG_ON(BPF_REG_FP + 1 != MAX_BPF_REG); 19064 for (frame = 0; frame <= vstate->curframe; frame++) { 19065 parent = vparent->frame[frame]; 19066 state = vstate->frame[frame]; 19067 parent_reg = parent->regs; 19068 state_reg = state->regs; 19069 /* We don't need to worry about FP liveness, it's read-only */ 19070 for (i = frame < vstate->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++) { 19071 err = propagate_liveness_reg(env, &state_reg[i], 19072 &parent_reg[i]); 19073 if (err < 0) 19074 return err; 19075 *changed |= err > 0; 19076 if (err == REG_LIVE_READ64) 19077 mark_insn_zext(env, &parent_reg[i]); 19078 } 19079 19080 /* Propagate stack slots. */ 19081 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE && 19082 i < parent->allocated_stack / BPF_REG_SIZE; i++) { 19083 parent_reg = &parent->stack[i].spilled_ptr; 19084 state_reg = &state->stack[i].spilled_ptr; 19085 err = propagate_liveness_reg(env, state_reg, 19086 parent_reg); 19087 *changed |= err > 0; 19088 if (err < 0) 19089 return err; 19090 } 19091 } 19092 return 0; 19093 } 19094 19095 /* find precise scalars in the previous equivalent state and 19096 * propagate them into the current state 19097 */ 19098 static int propagate_precision(struct bpf_verifier_env *env, 19099 const struct bpf_verifier_state *old, 19100 struct bpf_verifier_state *cur, 19101 bool *changed) 19102 { 19103 struct bpf_reg_state *state_reg; 19104 struct bpf_func_state *state; 19105 int i, err = 0, fr; 19106 bool first; 19107 19108 for (fr = old->curframe; fr >= 0; fr--) { 19109 state = old->frame[fr]; 19110 state_reg = state->regs; 19111 first = true; 19112 for (i = 0; i < BPF_REG_FP; i++, state_reg++) { 19113 if (state_reg->type != SCALAR_VALUE || 19114 !state_reg->precise || 19115 !(state_reg->live & REG_LIVE_READ)) 19116 continue; 19117 if (env->log.level & BPF_LOG_LEVEL2) { 19118 if (first) 19119 verbose(env, "frame %d: propagating r%d", fr, i); 19120 else 19121 verbose(env, ",r%d", i); 19122 } 19123 bt_set_frame_reg(&env->bt, fr, i); 19124 first = false; 19125 } 19126 19127 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) { 19128 if (!is_spilled_reg(&state->stack[i])) 19129 continue; 19130 state_reg = &state->stack[i].spilled_ptr; 19131 if (state_reg->type != SCALAR_VALUE || 19132 !state_reg->precise || 19133 !(state_reg->live & REG_LIVE_READ)) 19134 continue; 19135 if (env->log.level & BPF_LOG_LEVEL2) { 19136 if (first) 19137 verbose(env, "frame %d: propagating fp%d", 19138 fr, (-i - 1) * BPF_REG_SIZE); 19139 else 19140 verbose(env, ",fp%d", (-i - 1) * BPF_REG_SIZE); 19141 } 19142 bt_set_frame_slot(&env->bt, fr, i); 19143 first = false; 19144 } 19145 if (!first) 19146 verbose(env, "\n"); 19147 } 19148 19149 err = __mark_chain_precision(env, cur, -1, changed); 19150 if (err < 0) 19151 return err; 19152 19153 return 0; 19154 } 19155 19156 #define MAX_BACKEDGE_ITERS 64 19157 19158 /* Propagate read and precision marks from visit->backedges[*].state->equal_state 19159 * to corresponding parent states of visit->backedges[*].state until fixed point is reached, 19160 * then free visit->backedges. 19161 * After execution of this function incomplete_read_marks() will return false 19162 * for all states corresponding to @visit->callchain. 19163 */ 19164 static int propagate_backedges(struct bpf_verifier_env *env, struct bpf_scc_visit *visit) 19165 { 19166 struct bpf_scc_backedge *backedge; 19167 struct bpf_verifier_state *st; 19168 bool changed; 19169 int i, err; 19170 19171 i = 0; 19172 do { 19173 if (i++ > MAX_BACKEDGE_ITERS) { 19174 if (env->log.level & BPF_LOG_LEVEL2) 19175 verbose(env, "%s: too many iterations\n", __func__); 19176 for (backedge = visit->backedges; backedge; backedge = backedge->next) 19177 mark_all_scalars_precise(env, &backedge->state); 19178 break; 19179 } 19180 changed = false; 19181 for (backedge = visit->backedges; backedge; backedge = backedge->next) { 19182 st = &backedge->state; 19183 err = propagate_liveness(env, st->equal_state, st, &changed); 19184 if (err) 19185 return err; 19186 err = propagate_precision(env, st->equal_state, st, &changed); 19187 if (err) 19188 return err; 19189 } 19190 } while (changed); 19191 19192 free_backedges(visit); 19193 return 0; 19194 } 19195 19196 static bool states_maybe_looping(struct bpf_verifier_state *old, 19197 struct bpf_verifier_state *cur) 19198 { 19199 struct bpf_func_state *fold, *fcur; 19200 int i, fr = cur->curframe; 19201 19202 if (old->curframe != fr) 19203 return false; 19204 19205 fold = old->frame[fr]; 19206 fcur = cur->frame[fr]; 19207 for (i = 0; i < MAX_BPF_REG; i++) 19208 if (memcmp(&fold->regs[i], &fcur->regs[i], 19209 offsetof(struct bpf_reg_state, parent))) 19210 return false; 19211 return true; 19212 } 19213 19214 static bool is_iter_next_insn(struct bpf_verifier_env *env, int insn_idx) 19215 { 19216 return env->insn_aux_data[insn_idx].is_iter_next; 19217 } 19218 19219 /* is_state_visited() handles iter_next() (see process_iter_next_call() for 19220 * terminology) calls specially: as opposed to bounded BPF loops, it *expects* 19221 * states to match, which otherwise would look like an infinite loop. So while 19222 * iter_next() calls are taken care of, we still need to be careful and 19223 * prevent erroneous and too eager declaration of "infinite loop", when 19224 * iterators are involved. 19225 * 19226 * Here's a situation in pseudo-BPF assembly form: 19227 * 19228 * 0: again: ; set up iter_next() call args 19229 * 1: r1 = &it ; <CHECKPOINT HERE> 19230 * 2: call bpf_iter_num_next ; this is iter_next() call 19231 * 3: if r0 == 0 goto done 19232 * 4: ... something useful here ... 19233 * 5: goto again ; another iteration 19234 * 6: done: 19235 * 7: r1 = &it 19236 * 8: call bpf_iter_num_destroy ; clean up iter state 19237 * 9: exit 19238 * 19239 * This is a typical loop. Let's assume that we have a prune point at 1:, 19240 * before we get to `call bpf_iter_num_next` (e.g., because of that `goto 19241 * again`, assuming other heuristics don't get in a way). 19242 * 19243 * When we first time come to 1:, let's say we have some state X. We proceed 19244 * to 2:, fork states, enqueue ACTIVE, validate NULL case successfully, exit. 19245 * Now we come back to validate that forked ACTIVE state. We proceed through 19246 * 3-5, come to goto, jump to 1:. Let's assume our state didn't change, so we 19247 * are converging. But the problem is that we don't know that yet, as this 19248 * convergence has to happen at iter_next() call site only. So if nothing is 19249 * done, at 1: verifier will use bounded loop logic and declare infinite 19250 * looping (and would be *technically* correct, if not for iterator's 19251 * "eventual sticky NULL" contract, see process_iter_next_call()). But we 19252 * don't want that. So what we do in process_iter_next_call() when we go on 19253 * another ACTIVE iteration, we bump slot->iter.depth, to mark that it's 19254 * a different iteration. So when we suspect an infinite loop, we additionally 19255 * check if any of the *ACTIVE* iterator states depths differ. If yes, we 19256 * pretend we are not looping and wait for next iter_next() call. 19257 * 19258 * This only applies to ACTIVE state. In DRAINED state we don't expect to 19259 * loop, because that would actually mean infinite loop, as DRAINED state is 19260 * "sticky", and so we'll keep returning into the same instruction with the 19261 * same state (at least in one of possible code paths). 19262 * 19263 * This approach allows to keep infinite loop heuristic even in the face of 19264 * active iterator. E.g., C snippet below is and will be detected as 19265 * infinitely looping: 19266 * 19267 * struct bpf_iter_num it; 19268 * int *p, x; 19269 * 19270 * bpf_iter_num_new(&it, 0, 10); 19271 * while ((p = bpf_iter_num_next(&t))) { 19272 * x = p; 19273 * while (x--) {} // <<-- infinite loop here 19274 * } 19275 * 19276 */ 19277 static bool iter_active_depths_differ(struct bpf_verifier_state *old, struct bpf_verifier_state *cur) 19278 { 19279 struct bpf_reg_state *slot, *cur_slot; 19280 struct bpf_func_state *state; 19281 int i, fr; 19282 19283 for (fr = old->curframe; fr >= 0; fr--) { 19284 state = old->frame[fr]; 19285 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) { 19286 if (state->stack[i].slot_type[0] != STACK_ITER) 19287 continue; 19288 19289 slot = &state->stack[i].spilled_ptr; 19290 if (slot->iter.state != BPF_ITER_STATE_ACTIVE) 19291 continue; 19292 19293 cur_slot = &cur->frame[fr]->stack[i].spilled_ptr; 19294 if (cur_slot->iter.depth != slot->iter.depth) 19295 return true; 19296 } 19297 } 19298 return false; 19299 } 19300 19301 static int is_state_visited(struct bpf_verifier_env *env, int insn_idx) 19302 { 19303 struct bpf_verifier_state_list *new_sl; 19304 struct bpf_verifier_state_list *sl; 19305 struct bpf_verifier_state *cur = env->cur_state, *new; 19306 bool force_new_state, add_new_state, loop; 19307 int i, j, n, err, states_cnt = 0; 19308 struct list_head *pos, *tmp, *head; 19309 19310 force_new_state = env->test_state_freq || is_force_checkpoint(env, insn_idx) || 19311 /* Avoid accumulating infinitely long jmp history */ 19312 cur->jmp_history_cnt > 40; 19313 19314 /* bpf progs typically have pruning point every 4 instructions 19315 * http://vger.kernel.org/bpfconf2019.html#session-1 19316 * Do not add new state for future pruning if the verifier hasn't seen 19317 * at least 2 jumps and at least 8 instructions. 19318 * This heuristics helps decrease 'total_states' and 'peak_states' metric. 19319 * In tests that amounts to up to 50% reduction into total verifier 19320 * memory consumption and 20% verifier time speedup. 19321 */ 19322 add_new_state = force_new_state; 19323 if (env->jmps_processed - env->prev_jmps_processed >= 2 && 19324 env->insn_processed - env->prev_insn_processed >= 8) 19325 add_new_state = true; 19326 19327 clean_live_states(env, insn_idx, cur); 19328 19329 loop = false; 19330 head = explored_state(env, insn_idx); 19331 list_for_each_safe(pos, tmp, head) { 19332 sl = container_of(pos, struct bpf_verifier_state_list, node); 19333 states_cnt++; 19334 if (sl->state.insn_idx != insn_idx) 19335 continue; 19336 19337 if (sl->state.branches) { 19338 struct bpf_func_state *frame = sl->state.frame[sl->state.curframe]; 19339 19340 if (frame->in_async_callback_fn && 19341 frame->async_entry_cnt != cur->frame[cur->curframe]->async_entry_cnt) { 19342 /* Different async_entry_cnt means that the verifier is 19343 * processing another entry into async callback. 19344 * Seeing the same state is not an indication of infinite 19345 * loop or infinite recursion. 19346 * But finding the same state doesn't mean that it's safe 19347 * to stop processing the current state. The previous state 19348 * hasn't yet reached bpf_exit, since state.branches > 0. 19349 * Checking in_async_callback_fn alone is not enough either. 19350 * Since the verifier still needs to catch infinite loops 19351 * inside async callbacks. 19352 */ 19353 goto skip_inf_loop_check; 19354 } 19355 /* BPF open-coded iterators loop detection is special. 19356 * states_maybe_looping() logic is too simplistic in detecting 19357 * states that *might* be equivalent, because it doesn't know 19358 * about ID remapping, so don't even perform it. 19359 * See process_iter_next_call() and iter_active_depths_differ() 19360 * for overview of the logic. When current and one of parent 19361 * states are detected as equivalent, it's a good thing: we prove 19362 * convergence and can stop simulating further iterations. 19363 * It's safe to assume that iterator loop will finish, taking into 19364 * account iter_next() contract of eventually returning 19365 * sticky NULL result. 19366 * 19367 * Note, that states have to be compared exactly in this case because 19368 * read and precision marks might not be finalized inside the loop. 19369 * E.g. as in the program below: 19370 * 19371 * 1. r7 = -16 19372 * 2. r6 = bpf_get_prandom_u32() 19373 * 3. while (bpf_iter_num_next(&fp[-8])) { 19374 * 4. if (r6 != 42) { 19375 * 5. r7 = -32 19376 * 6. r6 = bpf_get_prandom_u32() 19377 * 7. continue 19378 * 8. } 19379 * 9. r0 = r10 19380 * 10. r0 += r7 19381 * 11. r8 = *(u64 *)(r0 + 0) 19382 * 12. r6 = bpf_get_prandom_u32() 19383 * 13. } 19384 * 19385 * Here verifier would first visit path 1-3, create a checkpoint at 3 19386 * with r7=-16, continue to 4-7,3. Existing checkpoint at 3 does 19387 * not have read or precision mark for r7 yet, thus inexact states 19388 * comparison would discard current state with r7=-32 19389 * => unsafe memory access at 11 would not be caught. 19390 */ 19391 if (is_iter_next_insn(env, insn_idx)) { 19392 if (states_equal(env, &sl->state, cur, RANGE_WITHIN)) { 19393 struct bpf_func_state *cur_frame; 19394 struct bpf_reg_state *iter_state, *iter_reg; 19395 int spi; 19396 19397 cur_frame = cur->frame[cur->curframe]; 19398 /* btf_check_iter_kfuncs() enforces that 19399 * iter state pointer is always the first arg 19400 */ 19401 iter_reg = &cur_frame->regs[BPF_REG_1]; 19402 /* current state is valid due to states_equal(), 19403 * so we can assume valid iter and reg state, 19404 * no need for extra (re-)validations 19405 */ 19406 spi = __get_spi(iter_reg->off + iter_reg->var_off.value); 19407 iter_state = &func(env, iter_reg)->stack[spi].spilled_ptr; 19408 if (iter_state->iter.state == BPF_ITER_STATE_ACTIVE) { 19409 loop = true; 19410 goto hit; 19411 } 19412 } 19413 goto skip_inf_loop_check; 19414 } 19415 if (is_may_goto_insn_at(env, insn_idx)) { 19416 if (sl->state.may_goto_depth != cur->may_goto_depth && 19417 states_equal(env, &sl->state, cur, RANGE_WITHIN)) { 19418 loop = true; 19419 goto hit; 19420 } 19421 } 19422 if (calls_callback(env, insn_idx)) { 19423 if (states_equal(env, &sl->state, cur, RANGE_WITHIN)) 19424 goto hit; 19425 goto skip_inf_loop_check; 19426 } 19427 /* attempt to detect infinite loop to avoid unnecessary doomed work */ 19428 if (states_maybe_looping(&sl->state, cur) && 19429 states_equal(env, &sl->state, cur, EXACT) && 19430 !iter_active_depths_differ(&sl->state, cur) && 19431 sl->state.may_goto_depth == cur->may_goto_depth && 19432 sl->state.callback_unroll_depth == cur->callback_unroll_depth) { 19433 verbose_linfo(env, insn_idx, "; "); 19434 verbose(env, "infinite loop detected at insn %d\n", insn_idx); 19435 verbose(env, "cur state:"); 19436 print_verifier_state(env, cur, cur->curframe, true); 19437 verbose(env, "old state:"); 19438 print_verifier_state(env, &sl->state, cur->curframe, true); 19439 return -EINVAL; 19440 } 19441 /* if the verifier is processing a loop, avoid adding new state 19442 * too often, since different loop iterations have distinct 19443 * states and may not help future pruning. 19444 * This threshold shouldn't be too low to make sure that 19445 * a loop with large bound will be rejected quickly. 19446 * The most abusive loop will be: 19447 * r1 += 1 19448 * if r1 < 1000000 goto pc-2 19449 * 1M insn_procssed limit / 100 == 10k peak states. 19450 * This threshold shouldn't be too high either, since states 19451 * at the end of the loop are likely to be useful in pruning. 19452 */ 19453 skip_inf_loop_check: 19454 if (!force_new_state && 19455 env->jmps_processed - env->prev_jmps_processed < 20 && 19456 env->insn_processed - env->prev_insn_processed < 100) 19457 add_new_state = false; 19458 goto miss; 19459 } 19460 /* See comments for mark_all_regs_read_and_precise() */ 19461 loop = incomplete_read_marks(env, &sl->state); 19462 if (states_equal(env, &sl->state, cur, loop ? RANGE_WITHIN : NOT_EXACT)) { 19463 hit: 19464 sl->hit_cnt++; 19465 /* reached equivalent register/stack state, 19466 * prune the search. 19467 * Registers read by the continuation are read by us. 19468 * If we have any write marks in env->cur_state, they 19469 * will prevent corresponding reads in the continuation 19470 * from reaching our parent (an explored_state). Our 19471 * own state will get the read marks recorded, but 19472 * they'll be immediately forgotten as we're pruning 19473 * this state and will pop a new one. 19474 */ 19475 err = propagate_liveness(env, &sl->state, cur, NULL); 19476 19477 /* if previous state reached the exit with precision and 19478 * current state is equivalent to it (except precision marks) 19479 * the precision needs to be propagated back in 19480 * the current state. 19481 */ 19482 if (is_jmp_point(env, env->insn_idx)) 19483 err = err ? : push_jmp_history(env, cur, 0, 0); 19484 err = err ? : propagate_precision(env, &sl->state, cur, NULL); 19485 if (err) 19486 return err; 19487 /* When processing iterator based loops above propagate_liveness and 19488 * propagate_precision calls are not sufficient to transfer all relevant 19489 * read and precision marks. E.g. consider the following case: 19490 * 19491 * .-> A --. Assume the states are visited in the order A, B, C. 19492 * | | | Assume that state B reaches a state equivalent to state A. 19493 * | v v At this point, state C is not processed yet, so state A 19494 * '-- B C has not received any read or precision marks from C. 19495 * Thus, marks propagated from A to B are incomplete. 19496 * 19497 * The verifier mitigates this by performing the following steps: 19498 * 19499 * - Prior to the main verification pass, strongly connected components 19500 * (SCCs) are computed over the program's control flow graph, 19501 * intraprocedurally. 19502 * 19503 * - During the main verification pass, `maybe_enter_scc()` checks 19504 * whether the current verifier state is entering an SCC. If so, an 19505 * instance of a `bpf_scc_visit` object is created, and the state 19506 * entering the SCC is recorded as the entry state. 19507 * 19508 * - This instance is associated not with the SCC itself, but with a 19509 * `bpf_scc_callchain`: a tuple consisting of the call sites leading to 19510 * the SCC and the SCC id. See `compute_scc_callchain()`. 19511 * 19512 * - When a verification path encounters a `states_equal(..., 19513 * RANGE_WITHIN)` condition, there exists a call chain describing the 19514 * current state and a corresponding `bpf_scc_visit` instance. A copy 19515 * of the current state is created and added to 19516 * `bpf_scc_visit->backedges`. 19517 * 19518 * - When a verification path terminates, `maybe_exit_scc()` is called 19519 * from `update_branch_counts()`. For states with `branches == 0`, it 19520 * checks whether the state is the entry state of any `bpf_scc_visit` 19521 * instance. If it is, this indicates that all paths originating from 19522 * this SCC visit have been explored. `propagate_backedges()` is then 19523 * called, which propagates read and precision marks through the 19524 * backedges until a fixed point is reached. 19525 * (In the earlier example, this would propagate marks from A to B, 19526 * from C to A, and then again from A to B.) 19527 * 19528 * A note on callchains 19529 * -------------------- 19530 * 19531 * Consider the following example: 19532 * 19533 * void foo() { loop { ... SCC#1 ... } } 19534 * void main() { 19535 * A: foo(); 19536 * B: ... 19537 * C: foo(); 19538 * } 19539 * 19540 * Here, there are two distinct callchains leading to SCC#1: 19541 * - (A, SCC#1) 19542 * - (C, SCC#1) 19543 * 19544 * Each callchain identifies a separate `bpf_scc_visit` instance that 19545 * accumulates backedge states. The `propagate_{liveness,precision}()` 19546 * functions traverse the parent state of each backedge state, which 19547 * means these parent states must remain valid (i.e., not freed) while 19548 * the corresponding `bpf_scc_visit` instance exists. 19549 * 19550 * Associating `bpf_scc_visit` instances directly with SCCs instead of 19551 * callchains would break this invariant: 19552 * - States explored during `C: foo()` would contribute backedges to 19553 * SCC#1, but SCC#1 would only be exited once the exploration of 19554 * `A: foo()` completes. 19555 * - By that time, the states explored between `A: foo()` and `C: foo()` 19556 * (i.e., `B: ...`) may have already been freed, causing the parent 19557 * links for states from `C: foo()` to become invalid. 19558 */ 19559 if (loop) { 19560 struct bpf_scc_backedge *backedge; 19561 19562 backedge = kzalloc(sizeof(*backedge), GFP_KERNEL_ACCOUNT); 19563 if (!backedge) 19564 return -ENOMEM; 19565 err = copy_verifier_state(&backedge->state, cur); 19566 backedge->state.equal_state = &sl->state; 19567 backedge->state.insn_idx = insn_idx; 19568 err = err ?: add_scc_backedge(env, &sl->state, backedge); 19569 if (err) { 19570 free_verifier_state(&backedge->state, false); 19571 kvfree(backedge); 19572 return err; 19573 } 19574 } 19575 return 1; 19576 } 19577 miss: 19578 /* when new state is not going to be added do not increase miss count. 19579 * Otherwise several loop iterations will remove the state 19580 * recorded earlier. The goal of these heuristics is to have 19581 * states from some iterations of the loop (some in the beginning 19582 * and some at the end) to help pruning. 19583 */ 19584 if (add_new_state) 19585 sl->miss_cnt++; 19586 /* heuristic to determine whether this state is beneficial 19587 * to keep checking from state equivalence point of view. 19588 * Higher numbers increase max_states_per_insn and verification time, 19589 * but do not meaningfully decrease insn_processed. 19590 * 'n' controls how many times state could miss before eviction. 19591 * Use bigger 'n' for checkpoints because evicting checkpoint states 19592 * too early would hinder iterator convergence. 19593 */ 19594 n = is_force_checkpoint(env, insn_idx) && sl->state.branches > 0 ? 64 : 3; 19595 if (sl->miss_cnt > sl->hit_cnt * n + n) { 19596 /* the state is unlikely to be useful. Remove it to 19597 * speed up verification 19598 */ 19599 sl->in_free_list = true; 19600 list_del(&sl->node); 19601 list_add(&sl->node, &env->free_list); 19602 env->free_list_size++; 19603 env->explored_states_size--; 19604 maybe_free_verifier_state(env, sl); 19605 } 19606 } 19607 19608 if (env->max_states_per_insn < states_cnt) 19609 env->max_states_per_insn = states_cnt; 19610 19611 if (!env->bpf_capable && states_cnt > BPF_COMPLEXITY_LIMIT_STATES) 19612 return 0; 19613 19614 if (!add_new_state) 19615 return 0; 19616 19617 /* There were no equivalent states, remember the current one. 19618 * Technically the current state is not proven to be safe yet, 19619 * but it will either reach outer most bpf_exit (which means it's safe) 19620 * or it will be rejected. When there are no loops the verifier won't be 19621 * seeing this tuple (frame[0].callsite, frame[1].callsite, .. insn_idx) 19622 * again on the way to bpf_exit. 19623 * When looping the sl->state.branches will be > 0 and this state 19624 * will not be considered for equivalence until branches == 0. 19625 */ 19626 new_sl = kzalloc(sizeof(struct bpf_verifier_state_list), GFP_KERNEL_ACCOUNT); 19627 if (!new_sl) 19628 return -ENOMEM; 19629 env->total_states++; 19630 env->explored_states_size++; 19631 update_peak_states(env); 19632 env->prev_jmps_processed = env->jmps_processed; 19633 env->prev_insn_processed = env->insn_processed; 19634 19635 /* forget precise markings we inherited, see __mark_chain_precision */ 19636 if (env->bpf_capable) 19637 mark_all_scalars_imprecise(env, cur); 19638 19639 /* add new state to the head of linked list */ 19640 new = &new_sl->state; 19641 err = copy_verifier_state(new, cur); 19642 if (err) { 19643 free_verifier_state(new, false); 19644 kfree(new_sl); 19645 return err; 19646 } 19647 new->insn_idx = insn_idx; 19648 verifier_bug_if(new->branches != 1, env, 19649 "%s:branches_to_explore=%d insn %d", 19650 __func__, new->branches, insn_idx); 19651 err = maybe_enter_scc(env, new); 19652 if (err) { 19653 free_verifier_state(new, false); 19654 kvfree(new_sl); 19655 return err; 19656 } 19657 19658 cur->parent = new; 19659 cur->first_insn_idx = insn_idx; 19660 cur->dfs_depth = new->dfs_depth + 1; 19661 clear_jmp_history(cur); 19662 list_add(&new_sl->node, head); 19663 19664 /* connect new state to parentage chain. Current frame needs all 19665 * registers connected. Only r6 - r9 of the callers are alive (pushed 19666 * to the stack implicitly by JITs) so in callers' frames connect just 19667 * r6 - r9 as an optimization. Callers will have r1 - r5 connected to 19668 * the state of the call instruction (with WRITTEN set), and r0 comes 19669 * from callee with its full parentage chain, anyway. 19670 */ 19671 /* clear write marks in current state: the writes we did are not writes 19672 * our child did, so they don't screen off its reads from us. 19673 * (There are no read marks in current state, because reads always mark 19674 * their parent and current state never has children yet. Only 19675 * explored_states can get read marks.) 19676 */ 19677 for (j = 0; j <= cur->curframe; j++) { 19678 for (i = j < cur->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++) 19679 cur->frame[j]->regs[i].parent = &new->frame[j]->regs[i]; 19680 for (i = 0; i < BPF_REG_FP; i++) 19681 cur->frame[j]->regs[i].live = REG_LIVE_NONE; 19682 } 19683 19684 /* all stack frames are accessible from callee, clear them all */ 19685 for (j = 0; j <= cur->curframe; j++) { 19686 struct bpf_func_state *frame = cur->frame[j]; 19687 struct bpf_func_state *newframe = new->frame[j]; 19688 19689 for (i = 0; i < frame->allocated_stack / BPF_REG_SIZE; i++) { 19690 frame->stack[i].spilled_ptr.live = REG_LIVE_NONE; 19691 frame->stack[i].spilled_ptr.parent = 19692 &newframe->stack[i].spilled_ptr; 19693 } 19694 } 19695 return 0; 19696 } 19697 19698 /* Return true if it's OK to have the same insn return a different type. */ 19699 static bool reg_type_mismatch_ok(enum bpf_reg_type type) 19700 { 19701 switch (base_type(type)) { 19702 case PTR_TO_CTX: 19703 case PTR_TO_SOCKET: 19704 case PTR_TO_SOCK_COMMON: 19705 case PTR_TO_TCP_SOCK: 19706 case PTR_TO_XDP_SOCK: 19707 case PTR_TO_BTF_ID: 19708 case PTR_TO_ARENA: 19709 return false; 19710 default: 19711 return true; 19712 } 19713 } 19714 19715 /* If an instruction was previously used with particular pointer types, then we 19716 * need to be careful to avoid cases such as the below, where it may be ok 19717 * for one branch accessing the pointer, but not ok for the other branch: 19718 * 19719 * R1 = sock_ptr 19720 * goto X; 19721 * ... 19722 * R1 = some_other_valid_ptr; 19723 * goto X; 19724 * ... 19725 * R2 = *(u32 *)(R1 + 0); 19726 */ 19727 static bool reg_type_mismatch(enum bpf_reg_type src, enum bpf_reg_type prev) 19728 { 19729 return src != prev && (!reg_type_mismatch_ok(src) || 19730 !reg_type_mismatch_ok(prev)); 19731 } 19732 19733 static bool is_ptr_to_mem_or_btf_id(enum bpf_reg_type type) 19734 { 19735 switch (base_type(type)) { 19736 case PTR_TO_MEM: 19737 case PTR_TO_BTF_ID: 19738 return true; 19739 default: 19740 return false; 19741 } 19742 } 19743 19744 static bool is_ptr_to_mem(enum bpf_reg_type type) 19745 { 19746 return base_type(type) == PTR_TO_MEM; 19747 } 19748 19749 static int save_aux_ptr_type(struct bpf_verifier_env *env, enum bpf_reg_type type, 19750 bool allow_trust_mismatch) 19751 { 19752 enum bpf_reg_type *prev_type = &env->insn_aux_data[env->insn_idx].ptr_type; 19753 enum bpf_reg_type merged_type; 19754 19755 if (*prev_type == NOT_INIT) { 19756 /* Saw a valid insn 19757 * dst_reg = *(u32 *)(src_reg + off) 19758 * save type to validate intersecting paths 19759 */ 19760 *prev_type = type; 19761 } else if (reg_type_mismatch(type, *prev_type)) { 19762 /* Abuser program is trying to use the same insn 19763 * dst_reg = *(u32*) (src_reg + off) 19764 * with different pointer types: 19765 * src_reg == ctx in one branch and 19766 * src_reg == stack|map in some other branch. 19767 * Reject it. 19768 */ 19769 if (allow_trust_mismatch && 19770 is_ptr_to_mem_or_btf_id(type) && 19771 is_ptr_to_mem_or_btf_id(*prev_type)) { 19772 /* 19773 * Have to support a use case when one path through 19774 * the program yields TRUSTED pointer while another 19775 * is UNTRUSTED. Fallback to UNTRUSTED to generate 19776 * BPF_PROBE_MEM/BPF_PROBE_MEMSX. 19777 * Same behavior of MEM_RDONLY flag. 19778 */ 19779 if (is_ptr_to_mem(type) || is_ptr_to_mem(*prev_type)) 19780 merged_type = PTR_TO_MEM; 19781 else 19782 merged_type = PTR_TO_BTF_ID; 19783 if ((type & PTR_UNTRUSTED) || (*prev_type & PTR_UNTRUSTED)) 19784 merged_type |= PTR_UNTRUSTED; 19785 if ((type & MEM_RDONLY) || (*prev_type & MEM_RDONLY)) 19786 merged_type |= MEM_RDONLY; 19787 *prev_type = merged_type; 19788 } else { 19789 verbose(env, "same insn cannot be used with different pointers\n"); 19790 return -EINVAL; 19791 } 19792 } 19793 19794 return 0; 19795 } 19796 19797 enum { 19798 PROCESS_BPF_EXIT = 1 19799 }; 19800 19801 static int process_bpf_exit_full(struct bpf_verifier_env *env, 19802 bool *do_print_state, 19803 bool exception_exit) 19804 { 19805 /* We must do check_reference_leak here before 19806 * prepare_func_exit to handle the case when 19807 * state->curframe > 0, it may be a callback function, 19808 * for which reference_state must match caller reference 19809 * state when it exits. 19810 */ 19811 int err = check_resource_leak(env, exception_exit, 19812 !env->cur_state->curframe, 19813 "BPF_EXIT instruction in main prog"); 19814 if (err) 19815 return err; 19816 19817 /* The side effect of the prepare_func_exit which is 19818 * being skipped is that it frees bpf_func_state. 19819 * Typically, process_bpf_exit will only be hit with 19820 * outermost exit. copy_verifier_state in pop_stack will 19821 * handle freeing of any extra bpf_func_state left over 19822 * from not processing all nested function exits. We 19823 * also skip return code checks as they are not needed 19824 * for exceptional exits. 19825 */ 19826 if (exception_exit) 19827 return PROCESS_BPF_EXIT; 19828 19829 if (env->cur_state->curframe) { 19830 /* exit from nested function */ 19831 err = prepare_func_exit(env, &env->insn_idx); 19832 if (err) 19833 return err; 19834 *do_print_state = true; 19835 return 0; 19836 } 19837 19838 err = check_return_code(env, BPF_REG_0, "R0"); 19839 if (err) 19840 return err; 19841 return PROCESS_BPF_EXIT; 19842 } 19843 19844 static int do_check_insn(struct bpf_verifier_env *env, bool *do_print_state) 19845 { 19846 int err; 19847 struct bpf_insn *insn = &env->prog->insnsi[env->insn_idx]; 19848 u8 class = BPF_CLASS(insn->code); 19849 19850 if (class == BPF_ALU || class == BPF_ALU64) { 19851 err = check_alu_op(env, insn); 19852 if (err) 19853 return err; 19854 19855 } else if (class == BPF_LDX) { 19856 bool is_ldsx = BPF_MODE(insn->code) == BPF_MEMSX; 19857 19858 /* Check for reserved fields is already done in 19859 * resolve_pseudo_ldimm64(). 19860 */ 19861 err = check_load_mem(env, insn, false, is_ldsx, true, "ldx"); 19862 if (err) 19863 return err; 19864 } else if (class == BPF_STX) { 19865 if (BPF_MODE(insn->code) == BPF_ATOMIC) { 19866 err = check_atomic(env, insn); 19867 if (err) 19868 return err; 19869 env->insn_idx++; 19870 return 0; 19871 } 19872 19873 if (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0) { 19874 verbose(env, "BPF_STX uses reserved fields\n"); 19875 return -EINVAL; 19876 } 19877 19878 err = check_store_reg(env, insn, false); 19879 if (err) 19880 return err; 19881 } else if (class == BPF_ST) { 19882 enum bpf_reg_type dst_reg_type; 19883 19884 if (BPF_MODE(insn->code) != BPF_MEM || 19885 insn->src_reg != BPF_REG_0) { 19886 verbose(env, "BPF_ST uses reserved fields\n"); 19887 return -EINVAL; 19888 } 19889 /* check src operand */ 19890 err = check_reg_arg(env, insn->dst_reg, SRC_OP); 19891 if (err) 19892 return err; 19893 19894 dst_reg_type = cur_regs(env)[insn->dst_reg].type; 19895 19896 /* check that memory (dst_reg + off) is writeable */ 19897 err = check_mem_access(env, env->insn_idx, insn->dst_reg, 19898 insn->off, BPF_SIZE(insn->code), 19899 BPF_WRITE, -1, false, false); 19900 if (err) 19901 return err; 19902 19903 err = save_aux_ptr_type(env, dst_reg_type, false); 19904 if (err) 19905 return err; 19906 } else if (class == BPF_JMP || class == BPF_JMP32) { 19907 u8 opcode = BPF_OP(insn->code); 19908 19909 env->jmps_processed++; 19910 if (opcode == BPF_CALL) { 19911 if (BPF_SRC(insn->code) != BPF_K || 19912 (insn->src_reg != BPF_PSEUDO_KFUNC_CALL && 19913 insn->off != 0) || 19914 (insn->src_reg != BPF_REG_0 && 19915 insn->src_reg != BPF_PSEUDO_CALL && 19916 insn->src_reg != BPF_PSEUDO_KFUNC_CALL) || 19917 insn->dst_reg != BPF_REG_0 || class == BPF_JMP32) { 19918 verbose(env, "BPF_CALL uses reserved fields\n"); 19919 return -EINVAL; 19920 } 19921 19922 if (env->cur_state->active_locks) { 19923 if ((insn->src_reg == BPF_REG_0 && 19924 insn->imm != BPF_FUNC_spin_unlock) || 19925 (insn->src_reg == BPF_PSEUDO_KFUNC_CALL && 19926 (insn->off != 0 || !kfunc_spin_allowed(insn->imm)))) { 19927 verbose(env, 19928 "function calls are not allowed while holding a lock\n"); 19929 return -EINVAL; 19930 } 19931 } 19932 if (insn->src_reg == BPF_PSEUDO_CALL) { 19933 err = check_func_call(env, insn, &env->insn_idx); 19934 } else if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) { 19935 err = check_kfunc_call(env, insn, &env->insn_idx); 19936 if (!err && is_bpf_throw_kfunc(insn)) 19937 return process_bpf_exit_full(env, do_print_state, true); 19938 } else { 19939 err = check_helper_call(env, insn, &env->insn_idx); 19940 } 19941 if (err) 19942 return err; 19943 19944 mark_reg_scratched(env, BPF_REG_0); 19945 } else if (opcode == BPF_JA) { 19946 if (BPF_SRC(insn->code) != BPF_K || 19947 insn->src_reg != BPF_REG_0 || 19948 insn->dst_reg != BPF_REG_0 || 19949 (class == BPF_JMP && insn->imm != 0) || 19950 (class == BPF_JMP32 && insn->off != 0)) { 19951 verbose(env, "BPF_JA uses reserved fields\n"); 19952 return -EINVAL; 19953 } 19954 19955 if (class == BPF_JMP) 19956 env->insn_idx += insn->off + 1; 19957 else 19958 env->insn_idx += insn->imm + 1; 19959 return 0; 19960 } else if (opcode == BPF_EXIT) { 19961 if (BPF_SRC(insn->code) != BPF_K || 19962 insn->imm != 0 || 19963 insn->src_reg != BPF_REG_0 || 19964 insn->dst_reg != BPF_REG_0 || 19965 class == BPF_JMP32) { 19966 verbose(env, "BPF_EXIT uses reserved fields\n"); 19967 return -EINVAL; 19968 } 19969 return process_bpf_exit_full(env, do_print_state, false); 19970 } else { 19971 err = check_cond_jmp_op(env, insn, &env->insn_idx); 19972 if (err) 19973 return err; 19974 } 19975 } else if (class == BPF_LD) { 19976 u8 mode = BPF_MODE(insn->code); 19977 19978 if (mode == BPF_ABS || mode == BPF_IND) { 19979 err = check_ld_abs(env, insn); 19980 if (err) 19981 return err; 19982 19983 } else if (mode == BPF_IMM) { 19984 err = check_ld_imm(env, insn); 19985 if (err) 19986 return err; 19987 19988 env->insn_idx++; 19989 sanitize_mark_insn_seen(env); 19990 } else { 19991 verbose(env, "invalid BPF_LD mode\n"); 19992 return -EINVAL; 19993 } 19994 } else { 19995 verbose(env, "unknown insn class %d\n", class); 19996 return -EINVAL; 19997 } 19998 19999 env->insn_idx++; 20000 return 0; 20001 } 20002 20003 static int do_check(struct bpf_verifier_env *env) 20004 { 20005 bool pop_log = !(env->log.level & BPF_LOG_LEVEL2); 20006 struct bpf_verifier_state *state = env->cur_state; 20007 struct bpf_insn *insns = env->prog->insnsi; 20008 int insn_cnt = env->prog->len; 20009 bool do_print_state = false; 20010 int prev_insn_idx = -1; 20011 20012 for (;;) { 20013 struct bpf_insn *insn; 20014 struct bpf_insn_aux_data *insn_aux; 20015 int err; 20016 20017 /* reset current history entry on each new instruction */ 20018 env->cur_hist_ent = NULL; 20019 20020 env->prev_insn_idx = prev_insn_idx; 20021 if (env->insn_idx >= insn_cnt) { 20022 verbose(env, "invalid insn idx %d insn_cnt %d\n", 20023 env->insn_idx, insn_cnt); 20024 return -EFAULT; 20025 } 20026 20027 insn = &insns[env->insn_idx]; 20028 insn_aux = &env->insn_aux_data[env->insn_idx]; 20029 20030 if (++env->insn_processed > BPF_COMPLEXITY_LIMIT_INSNS) { 20031 verbose(env, 20032 "BPF program is too large. Processed %d insn\n", 20033 env->insn_processed); 20034 return -E2BIG; 20035 } 20036 20037 state->last_insn_idx = env->prev_insn_idx; 20038 state->insn_idx = env->insn_idx; 20039 20040 if (is_prune_point(env, env->insn_idx)) { 20041 err = is_state_visited(env, env->insn_idx); 20042 if (err < 0) 20043 return err; 20044 if (err == 1) { 20045 /* found equivalent state, can prune the search */ 20046 if (env->log.level & BPF_LOG_LEVEL) { 20047 if (do_print_state) 20048 verbose(env, "\nfrom %d to %d%s: safe\n", 20049 env->prev_insn_idx, env->insn_idx, 20050 env->cur_state->speculative ? 20051 " (speculative execution)" : ""); 20052 else 20053 verbose(env, "%d: safe\n", env->insn_idx); 20054 } 20055 goto process_bpf_exit; 20056 } 20057 } 20058 20059 if (is_jmp_point(env, env->insn_idx)) { 20060 err = push_jmp_history(env, state, 0, 0); 20061 if (err) 20062 return err; 20063 } 20064 20065 if (signal_pending(current)) 20066 return -EAGAIN; 20067 20068 if (need_resched()) 20069 cond_resched(); 20070 20071 if (env->log.level & BPF_LOG_LEVEL2 && do_print_state) { 20072 verbose(env, "\nfrom %d to %d%s:", 20073 env->prev_insn_idx, env->insn_idx, 20074 env->cur_state->speculative ? 20075 " (speculative execution)" : ""); 20076 print_verifier_state(env, state, state->curframe, true); 20077 do_print_state = false; 20078 } 20079 20080 if (env->log.level & BPF_LOG_LEVEL) { 20081 if (verifier_state_scratched(env)) 20082 print_insn_state(env, state, state->curframe); 20083 20084 verbose_linfo(env, env->insn_idx, "; "); 20085 env->prev_log_pos = env->log.end_pos; 20086 verbose(env, "%d: ", env->insn_idx); 20087 verbose_insn(env, insn); 20088 env->prev_insn_print_pos = env->log.end_pos - env->prev_log_pos; 20089 env->prev_log_pos = env->log.end_pos; 20090 } 20091 20092 if (bpf_prog_is_offloaded(env->prog->aux)) { 20093 err = bpf_prog_offload_verify_insn(env, env->insn_idx, 20094 env->prev_insn_idx); 20095 if (err) 20096 return err; 20097 } 20098 20099 sanitize_mark_insn_seen(env); 20100 prev_insn_idx = env->insn_idx; 20101 20102 /* Reduce verification complexity by stopping speculative path 20103 * verification when a nospec is encountered. 20104 */ 20105 if (state->speculative && insn_aux->nospec) 20106 goto process_bpf_exit; 20107 20108 err = do_check_insn(env, &do_print_state); 20109 if (error_recoverable_with_nospec(err) && state->speculative) { 20110 /* Prevent this speculative path from ever reaching the 20111 * insn that would have been unsafe to execute. 20112 */ 20113 insn_aux->nospec = true; 20114 /* If it was an ADD/SUB insn, potentially remove any 20115 * markings for alu sanitization. 20116 */ 20117 insn_aux->alu_state = 0; 20118 goto process_bpf_exit; 20119 } else if (err < 0) { 20120 return err; 20121 } else if (err == PROCESS_BPF_EXIT) { 20122 goto process_bpf_exit; 20123 } 20124 WARN_ON_ONCE(err); 20125 20126 if (state->speculative && insn_aux->nospec_result) { 20127 /* If we are on a path that performed a jump-op, this 20128 * may skip a nospec patched-in after the jump. This can 20129 * currently never happen because nospec_result is only 20130 * used for the write-ops 20131 * `*(size*)(dst_reg+off)=src_reg|imm32` which must 20132 * never skip the following insn. Still, add a warning 20133 * to document this in case nospec_result is used 20134 * elsewhere in the future. 20135 * 20136 * All non-branch instructions have a single 20137 * fall-through edge. For these, nospec_result should 20138 * already work. 20139 */ 20140 if (verifier_bug_if(BPF_CLASS(insn->code) == BPF_JMP || 20141 BPF_CLASS(insn->code) == BPF_JMP32, env, 20142 "speculation barrier after jump instruction may not have the desired effect")) 20143 return -EFAULT; 20144 process_bpf_exit: 20145 mark_verifier_state_scratched(env); 20146 err = update_branch_counts(env, env->cur_state); 20147 if (err) 20148 return err; 20149 err = pop_stack(env, &prev_insn_idx, &env->insn_idx, 20150 pop_log); 20151 if (err < 0) { 20152 if (err != -ENOENT) 20153 return err; 20154 break; 20155 } else { 20156 do_print_state = true; 20157 continue; 20158 } 20159 } 20160 } 20161 20162 return 0; 20163 } 20164 20165 static int find_btf_percpu_datasec(struct btf *btf) 20166 { 20167 const struct btf_type *t; 20168 const char *tname; 20169 int i, n; 20170 20171 /* 20172 * Both vmlinux and module each have their own ".data..percpu" 20173 * DATASECs in BTF. So for module's case, we need to skip vmlinux BTF 20174 * types to look at only module's own BTF types. 20175 */ 20176 n = btf_nr_types(btf); 20177 if (btf_is_module(btf)) 20178 i = btf_nr_types(btf_vmlinux); 20179 else 20180 i = 1; 20181 20182 for(; i < n; i++) { 20183 t = btf_type_by_id(btf, i); 20184 if (BTF_INFO_KIND(t->info) != BTF_KIND_DATASEC) 20185 continue; 20186 20187 tname = btf_name_by_offset(btf, t->name_off); 20188 if (!strcmp(tname, ".data..percpu")) 20189 return i; 20190 } 20191 20192 return -ENOENT; 20193 } 20194 20195 /* 20196 * Add btf to the used_btfs array and return the index. (If the btf was 20197 * already added, then just return the index.) Upon successful insertion 20198 * increase btf refcnt, and, if present, also refcount the corresponding 20199 * kernel module. 20200 */ 20201 static int __add_used_btf(struct bpf_verifier_env *env, struct btf *btf) 20202 { 20203 struct btf_mod_pair *btf_mod; 20204 int i; 20205 20206 /* check whether we recorded this BTF (and maybe module) already */ 20207 for (i = 0; i < env->used_btf_cnt; i++) 20208 if (env->used_btfs[i].btf == btf) 20209 return i; 20210 20211 if (env->used_btf_cnt >= MAX_USED_BTFS) 20212 return -E2BIG; 20213 20214 btf_get(btf); 20215 20216 btf_mod = &env->used_btfs[env->used_btf_cnt]; 20217 btf_mod->btf = btf; 20218 btf_mod->module = NULL; 20219 20220 /* if we reference variables from kernel module, bump its refcount */ 20221 if (btf_is_module(btf)) { 20222 btf_mod->module = btf_try_get_module(btf); 20223 if (!btf_mod->module) { 20224 btf_put(btf); 20225 return -ENXIO; 20226 } 20227 } 20228 20229 return env->used_btf_cnt++; 20230 } 20231 20232 /* replace pseudo btf_id with kernel symbol address */ 20233 static int __check_pseudo_btf_id(struct bpf_verifier_env *env, 20234 struct bpf_insn *insn, 20235 struct bpf_insn_aux_data *aux, 20236 struct btf *btf) 20237 { 20238 const struct btf_var_secinfo *vsi; 20239 const struct btf_type *datasec; 20240 const struct btf_type *t; 20241 const char *sym_name; 20242 bool percpu = false; 20243 u32 type, id = insn->imm; 20244 s32 datasec_id; 20245 u64 addr; 20246 int i; 20247 20248 t = btf_type_by_id(btf, id); 20249 if (!t) { 20250 verbose(env, "ldimm64 insn specifies invalid btf_id %d.\n", id); 20251 return -ENOENT; 20252 } 20253 20254 if (!btf_type_is_var(t) && !btf_type_is_func(t)) { 20255 verbose(env, "pseudo btf_id %d in ldimm64 isn't KIND_VAR or KIND_FUNC\n", id); 20256 return -EINVAL; 20257 } 20258 20259 sym_name = btf_name_by_offset(btf, t->name_off); 20260 addr = kallsyms_lookup_name(sym_name); 20261 if (!addr) { 20262 verbose(env, "ldimm64 failed to find the address for kernel symbol '%s'.\n", 20263 sym_name); 20264 return -ENOENT; 20265 } 20266 insn[0].imm = (u32)addr; 20267 insn[1].imm = addr >> 32; 20268 20269 if (btf_type_is_func(t)) { 20270 aux->btf_var.reg_type = PTR_TO_MEM | MEM_RDONLY; 20271 aux->btf_var.mem_size = 0; 20272 return 0; 20273 } 20274 20275 datasec_id = find_btf_percpu_datasec(btf); 20276 if (datasec_id > 0) { 20277 datasec = btf_type_by_id(btf, datasec_id); 20278 for_each_vsi(i, datasec, vsi) { 20279 if (vsi->type == id) { 20280 percpu = true; 20281 break; 20282 } 20283 } 20284 } 20285 20286 type = t->type; 20287 t = btf_type_skip_modifiers(btf, type, NULL); 20288 if (percpu) { 20289 aux->btf_var.reg_type = PTR_TO_BTF_ID | MEM_PERCPU; 20290 aux->btf_var.btf = btf; 20291 aux->btf_var.btf_id = type; 20292 } else if (!btf_type_is_struct(t)) { 20293 const struct btf_type *ret; 20294 const char *tname; 20295 u32 tsize; 20296 20297 /* resolve the type size of ksym. */ 20298 ret = btf_resolve_size(btf, t, &tsize); 20299 if (IS_ERR(ret)) { 20300 tname = btf_name_by_offset(btf, t->name_off); 20301 verbose(env, "ldimm64 unable to resolve the size of type '%s': %ld\n", 20302 tname, PTR_ERR(ret)); 20303 return -EINVAL; 20304 } 20305 aux->btf_var.reg_type = PTR_TO_MEM | MEM_RDONLY; 20306 aux->btf_var.mem_size = tsize; 20307 } else { 20308 aux->btf_var.reg_type = PTR_TO_BTF_ID; 20309 aux->btf_var.btf = btf; 20310 aux->btf_var.btf_id = type; 20311 } 20312 20313 return 0; 20314 } 20315 20316 static int check_pseudo_btf_id(struct bpf_verifier_env *env, 20317 struct bpf_insn *insn, 20318 struct bpf_insn_aux_data *aux) 20319 { 20320 struct btf *btf; 20321 int btf_fd; 20322 int err; 20323 20324 btf_fd = insn[1].imm; 20325 if (btf_fd) { 20326 CLASS(fd, f)(btf_fd); 20327 20328 btf = __btf_get_by_fd(f); 20329 if (IS_ERR(btf)) { 20330 verbose(env, "invalid module BTF object FD specified.\n"); 20331 return -EINVAL; 20332 } 20333 } else { 20334 if (!btf_vmlinux) { 20335 verbose(env, "kernel is missing BTF, make sure CONFIG_DEBUG_INFO_BTF=y is specified in Kconfig.\n"); 20336 return -EINVAL; 20337 } 20338 btf = btf_vmlinux; 20339 } 20340 20341 err = __check_pseudo_btf_id(env, insn, aux, btf); 20342 if (err) 20343 return err; 20344 20345 err = __add_used_btf(env, btf); 20346 if (err < 0) 20347 return err; 20348 return 0; 20349 } 20350 20351 static bool is_tracing_prog_type(enum bpf_prog_type type) 20352 { 20353 switch (type) { 20354 case BPF_PROG_TYPE_KPROBE: 20355 case BPF_PROG_TYPE_TRACEPOINT: 20356 case BPF_PROG_TYPE_PERF_EVENT: 20357 case BPF_PROG_TYPE_RAW_TRACEPOINT: 20358 case BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE: 20359 return true; 20360 default: 20361 return false; 20362 } 20363 } 20364 20365 static bool bpf_map_is_cgroup_storage(struct bpf_map *map) 20366 { 20367 return (map->map_type == BPF_MAP_TYPE_CGROUP_STORAGE || 20368 map->map_type == BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE); 20369 } 20370 20371 static int check_map_prog_compatibility(struct bpf_verifier_env *env, 20372 struct bpf_map *map, 20373 struct bpf_prog *prog) 20374 20375 { 20376 enum bpf_prog_type prog_type = resolve_prog_type(prog); 20377 20378 if (btf_record_has_field(map->record, BPF_LIST_HEAD) || 20379 btf_record_has_field(map->record, BPF_RB_ROOT)) { 20380 if (is_tracing_prog_type(prog_type)) { 20381 verbose(env, "tracing progs cannot use bpf_{list_head,rb_root} yet\n"); 20382 return -EINVAL; 20383 } 20384 } 20385 20386 if (btf_record_has_field(map->record, BPF_SPIN_LOCK | BPF_RES_SPIN_LOCK)) { 20387 if (prog_type == BPF_PROG_TYPE_SOCKET_FILTER) { 20388 verbose(env, "socket filter progs cannot use bpf_spin_lock yet\n"); 20389 return -EINVAL; 20390 } 20391 20392 if (is_tracing_prog_type(prog_type)) { 20393 verbose(env, "tracing progs cannot use bpf_spin_lock yet\n"); 20394 return -EINVAL; 20395 } 20396 } 20397 20398 if (btf_record_has_field(map->record, BPF_TIMER)) { 20399 if (is_tracing_prog_type(prog_type)) { 20400 verbose(env, "tracing progs cannot use bpf_timer yet\n"); 20401 return -EINVAL; 20402 } 20403 } 20404 20405 if (btf_record_has_field(map->record, BPF_WORKQUEUE)) { 20406 if (is_tracing_prog_type(prog_type)) { 20407 verbose(env, "tracing progs cannot use bpf_wq yet\n"); 20408 return -EINVAL; 20409 } 20410 } 20411 20412 if ((bpf_prog_is_offloaded(prog->aux) || bpf_map_is_offloaded(map)) && 20413 !bpf_offload_prog_map_match(prog, map)) { 20414 verbose(env, "offload device mismatch between prog and map\n"); 20415 return -EINVAL; 20416 } 20417 20418 if (map->map_type == BPF_MAP_TYPE_STRUCT_OPS) { 20419 verbose(env, "bpf_struct_ops map cannot be used in prog\n"); 20420 return -EINVAL; 20421 } 20422 20423 if (prog->sleepable) 20424 switch (map->map_type) { 20425 case BPF_MAP_TYPE_HASH: 20426 case BPF_MAP_TYPE_LRU_HASH: 20427 case BPF_MAP_TYPE_ARRAY: 20428 case BPF_MAP_TYPE_PERCPU_HASH: 20429 case BPF_MAP_TYPE_PERCPU_ARRAY: 20430 case BPF_MAP_TYPE_LRU_PERCPU_HASH: 20431 case BPF_MAP_TYPE_ARRAY_OF_MAPS: 20432 case BPF_MAP_TYPE_HASH_OF_MAPS: 20433 case BPF_MAP_TYPE_RINGBUF: 20434 case BPF_MAP_TYPE_USER_RINGBUF: 20435 case BPF_MAP_TYPE_INODE_STORAGE: 20436 case BPF_MAP_TYPE_SK_STORAGE: 20437 case BPF_MAP_TYPE_TASK_STORAGE: 20438 case BPF_MAP_TYPE_CGRP_STORAGE: 20439 case BPF_MAP_TYPE_QUEUE: 20440 case BPF_MAP_TYPE_STACK: 20441 case BPF_MAP_TYPE_ARENA: 20442 break; 20443 default: 20444 verbose(env, 20445 "Sleepable programs can only use array, hash, ringbuf and local storage maps\n"); 20446 return -EINVAL; 20447 } 20448 20449 if (bpf_map_is_cgroup_storage(map) && 20450 bpf_cgroup_storage_assign(env->prog->aux, map)) { 20451 verbose(env, "only one cgroup storage of each type is allowed\n"); 20452 return -EBUSY; 20453 } 20454 20455 if (map->map_type == BPF_MAP_TYPE_ARENA) { 20456 if (env->prog->aux->arena) { 20457 verbose(env, "Only one arena per program\n"); 20458 return -EBUSY; 20459 } 20460 if (!env->allow_ptr_leaks || !env->bpf_capable) { 20461 verbose(env, "CAP_BPF and CAP_PERFMON are required to use arena\n"); 20462 return -EPERM; 20463 } 20464 if (!env->prog->jit_requested) { 20465 verbose(env, "JIT is required to use arena\n"); 20466 return -EOPNOTSUPP; 20467 } 20468 if (!bpf_jit_supports_arena()) { 20469 verbose(env, "JIT doesn't support arena\n"); 20470 return -EOPNOTSUPP; 20471 } 20472 env->prog->aux->arena = (void *)map; 20473 if (!bpf_arena_get_user_vm_start(env->prog->aux->arena)) { 20474 verbose(env, "arena's user address must be set via map_extra or mmap()\n"); 20475 return -EINVAL; 20476 } 20477 } 20478 20479 return 0; 20480 } 20481 20482 static int __add_used_map(struct bpf_verifier_env *env, struct bpf_map *map) 20483 { 20484 int i, err; 20485 20486 /* check whether we recorded this map already */ 20487 for (i = 0; i < env->used_map_cnt; i++) 20488 if (env->used_maps[i] == map) 20489 return i; 20490 20491 if (env->used_map_cnt >= MAX_USED_MAPS) { 20492 verbose(env, "The total number of maps per program has reached the limit of %u\n", 20493 MAX_USED_MAPS); 20494 return -E2BIG; 20495 } 20496 20497 err = check_map_prog_compatibility(env, map, env->prog); 20498 if (err) 20499 return err; 20500 20501 if (env->prog->sleepable) 20502 atomic64_inc(&map->sleepable_refcnt); 20503 20504 /* hold the map. If the program is rejected by verifier, 20505 * the map will be released by release_maps() or it 20506 * will be used by the valid program until it's unloaded 20507 * and all maps are released in bpf_free_used_maps() 20508 */ 20509 bpf_map_inc(map); 20510 20511 env->used_maps[env->used_map_cnt++] = map; 20512 20513 return env->used_map_cnt - 1; 20514 } 20515 20516 /* Add map behind fd to used maps list, if it's not already there, and return 20517 * its index. 20518 * Returns <0 on error, or >= 0 index, on success. 20519 */ 20520 static int add_used_map(struct bpf_verifier_env *env, int fd) 20521 { 20522 struct bpf_map *map; 20523 CLASS(fd, f)(fd); 20524 20525 map = __bpf_map_get(f); 20526 if (IS_ERR(map)) { 20527 verbose(env, "fd %d is not pointing to valid bpf_map\n", fd); 20528 return PTR_ERR(map); 20529 } 20530 20531 return __add_used_map(env, map); 20532 } 20533 20534 /* find and rewrite pseudo imm in ld_imm64 instructions: 20535 * 20536 * 1. if it accesses map FD, replace it with actual map pointer. 20537 * 2. if it accesses btf_id of a VAR, replace it with pointer to the var. 20538 * 20539 * NOTE: btf_vmlinux is required for converting pseudo btf_id. 20540 */ 20541 static int resolve_pseudo_ldimm64(struct bpf_verifier_env *env) 20542 { 20543 struct bpf_insn *insn = env->prog->insnsi; 20544 int insn_cnt = env->prog->len; 20545 int i, err; 20546 20547 err = bpf_prog_calc_tag(env->prog); 20548 if (err) 20549 return err; 20550 20551 for (i = 0; i < insn_cnt; i++, insn++) { 20552 if (BPF_CLASS(insn->code) == BPF_LDX && 20553 ((BPF_MODE(insn->code) != BPF_MEM && BPF_MODE(insn->code) != BPF_MEMSX) || 20554 insn->imm != 0)) { 20555 verbose(env, "BPF_LDX uses reserved fields\n"); 20556 return -EINVAL; 20557 } 20558 20559 if (insn[0].code == (BPF_LD | BPF_IMM | BPF_DW)) { 20560 struct bpf_insn_aux_data *aux; 20561 struct bpf_map *map; 20562 int map_idx; 20563 u64 addr; 20564 u32 fd; 20565 20566 if (i == insn_cnt - 1 || insn[1].code != 0 || 20567 insn[1].dst_reg != 0 || insn[1].src_reg != 0 || 20568 insn[1].off != 0) { 20569 verbose(env, "invalid bpf_ld_imm64 insn\n"); 20570 return -EINVAL; 20571 } 20572 20573 if (insn[0].src_reg == 0) 20574 /* valid generic load 64-bit imm */ 20575 goto next_insn; 20576 20577 if (insn[0].src_reg == BPF_PSEUDO_BTF_ID) { 20578 aux = &env->insn_aux_data[i]; 20579 err = check_pseudo_btf_id(env, insn, aux); 20580 if (err) 20581 return err; 20582 goto next_insn; 20583 } 20584 20585 if (insn[0].src_reg == BPF_PSEUDO_FUNC) { 20586 aux = &env->insn_aux_data[i]; 20587 aux->ptr_type = PTR_TO_FUNC; 20588 goto next_insn; 20589 } 20590 20591 /* In final convert_pseudo_ld_imm64() step, this is 20592 * converted into regular 64-bit imm load insn. 20593 */ 20594 switch (insn[0].src_reg) { 20595 case BPF_PSEUDO_MAP_VALUE: 20596 case BPF_PSEUDO_MAP_IDX_VALUE: 20597 break; 20598 case BPF_PSEUDO_MAP_FD: 20599 case BPF_PSEUDO_MAP_IDX: 20600 if (insn[1].imm == 0) 20601 break; 20602 fallthrough; 20603 default: 20604 verbose(env, "unrecognized bpf_ld_imm64 insn\n"); 20605 return -EINVAL; 20606 } 20607 20608 switch (insn[0].src_reg) { 20609 case BPF_PSEUDO_MAP_IDX_VALUE: 20610 case BPF_PSEUDO_MAP_IDX: 20611 if (bpfptr_is_null(env->fd_array)) { 20612 verbose(env, "fd_idx without fd_array is invalid\n"); 20613 return -EPROTO; 20614 } 20615 if (copy_from_bpfptr_offset(&fd, env->fd_array, 20616 insn[0].imm * sizeof(fd), 20617 sizeof(fd))) 20618 return -EFAULT; 20619 break; 20620 default: 20621 fd = insn[0].imm; 20622 break; 20623 } 20624 20625 map_idx = add_used_map(env, fd); 20626 if (map_idx < 0) 20627 return map_idx; 20628 map = env->used_maps[map_idx]; 20629 20630 aux = &env->insn_aux_data[i]; 20631 aux->map_index = map_idx; 20632 20633 if (insn[0].src_reg == BPF_PSEUDO_MAP_FD || 20634 insn[0].src_reg == BPF_PSEUDO_MAP_IDX) { 20635 addr = (unsigned long)map; 20636 } else { 20637 u32 off = insn[1].imm; 20638 20639 if (off >= BPF_MAX_VAR_OFF) { 20640 verbose(env, "direct value offset of %u is not allowed\n", off); 20641 return -EINVAL; 20642 } 20643 20644 if (!map->ops->map_direct_value_addr) { 20645 verbose(env, "no direct value access support for this map type\n"); 20646 return -EINVAL; 20647 } 20648 20649 err = map->ops->map_direct_value_addr(map, &addr, off); 20650 if (err) { 20651 verbose(env, "invalid access to map value pointer, value_size=%u off=%u\n", 20652 map->value_size, off); 20653 return err; 20654 } 20655 20656 aux->map_off = off; 20657 addr += off; 20658 } 20659 20660 insn[0].imm = (u32)addr; 20661 insn[1].imm = addr >> 32; 20662 20663 next_insn: 20664 insn++; 20665 i++; 20666 continue; 20667 } 20668 20669 /* Basic sanity check before we invest more work here. */ 20670 if (!bpf_opcode_in_insntable(insn->code)) { 20671 verbose(env, "unknown opcode %02x\n", insn->code); 20672 return -EINVAL; 20673 } 20674 } 20675 20676 /* now all pseudo BPF_LD_IMM64 instructions load valid 20677 * 'struct bpf_map *' into a register instead of user map_fd. 20678 * These pointers will be used later by verifier to validate map access. 20679 */ 20680 return 0; 20681 } 20682 20683 /* drop refcnt of maps used by the rejected program */ 20684 static void release_maps(struct bpf_verifier_env *env) 20685 { 20686 __bpf_free_used_maps(env->prog->aux, env->used_maps, 20687 env->used_map_cnt); 20688 } 20689 20690 /* drop refcnt of maps used by the rejected program */ 20691 static void release_btfs(struct bpf_verifier_env *env) 20692 { 20693 __bpf_free_used_btfs(env->used_btfs, env->used_btf_cnt); 20694 } 20695 20696 /* convert pseudo BPF_LD_IMM64 into generic BPF_LD_IMM64 */ 20697 static void convert_pseudo_ld_imm64(struct bpf_verifier_env *env) 20698 { 20699 struct bpf_insn *insn = env->prog->insnsi; 20700 int insn_cnt = env->prog->len; 20701 int i; 20702 20703 for (i = 0; i < insn_cnt; i++, insn++) { 20704 if (insn->code != (BPF_LD | BPF_IMM | BPF_DW)) 20705 continue; 20706 if (insn->src_reg == BPF_PSEUDO_FUNC) 20707 continue; 20708 insn->src_reg = 0; 20709 } 20710 } 20711 20712 /* single env->prog->insni[off] instruction was replaced with the range 20713 * insni[off, off + cnt). Adjust corresponding insn_aux_data by copying 20714 * [0, off) and [off, end) to new locations, so the patched range stays zero 20715 */ 20716 static void adjust_insn_aux_data(struct bpf_verifier_env *env, 20717 struct bpf_insn_aux_data *new_data, 20718 struct bpf_prog *new_prog, u32 off, u32 cnt) 20719 { 20720 struct bpf_insn_aux_data *old_data = env->insn_aux_data; 20721 struct bpf_insn *insn = new_prog->insnsi; 20722 u32 old_seen = old_data[off].seen; 20723 u32 prog_len; 20724 int i; 20725 20726 /* aux info at OFF always needs adjustment, no matter fast path 20727 * (cnt == 1) is taken or not. There is no guarantee INSN at OFF is the 20728 * original insn at old prog. 20729 */ 20730 old_data[off].zext_dst = insn_has_def32(env, insn + off + cnt - 1); 20731 20732 if (cnt == 1) 20733 return; 20734 prog_len = new_prog->len; 20735 20736 memcpy(new_data, old_data, sizeof(struct bpf_insn_aux_data) * off); 20737 memcpy(new_data + off + cnt - 1, old_data + off, 20738 sizeof(struct bpf_insn_aux_data) * (prog_len - off - cnt + 1)); 20739 for (i = off; i < off + cnt - 1; i++) { 20740 /* Expand insni[off]'s seen count to the patched range. */ 20741 new_data[i].seen = old_seen; 20742 new_data[i].zext_dst = insn_has_def32(env, insn + i); 20743 } 20744 env->insn_aux_data = new_data; 20745 vfree(old_data); 20746 } 20747 20748 static void adjust_subprog_starts(struct bpf_verifier_env *env, u32 off, u32 len) 20749 { 20750 int i; 20751 20752 if (len == 1) 20753 return; 20754 /* NOTE: fake 'exit' subprog should be updated as well. */ 20755 for (i = 0; i <= env->subprog_cnt; i++) { 20756 if (env->subprog_info[i].start <= off) 20757 continue; 20758 env->subprog_info[i].start += len - 1; 20759 } 20760 } 20761 20762 static void adjust_poke_descs(struct bpf_prog *prog, u32 off, u32 len) 20763 { 20764 struct bpf_jit_poke_descriptor *tab = prog->aux->poke_tab; 20765 int i, sz = prog->aux->size_poke_tab; 20766 struct bpf_jit_poke_descriptor *desc; 20767 20768 for (i = 0; i < sz; i++) { 20769 desc = &tab[i]; 20770 if (desc->insn_idx <= off) 20771 continue; 20772 desc->insn_idx += len - 1; 20773 } 20774 } 20775 20776 static struct bpf_prog *bpf_patch_insn_data(struct bpf_verifier_env *env, u32 off, 20777 const struct bpf_insn *patch, u32 len) 20778 { 20779 struct bpf_prog *new_prog; 20780 struct bpf_insn_aux_data *new_data = NULL; 20781 20782 if (len > 1) { 20783 new_data = vzalloc(array_size(env->prog->len + len - 1, 20784 sizeof(struct bpf_insn_aux_data))); 20785 if (!new_data) 20786 return NULL; 20787 } 20788 20789 new_prog = bpf_patch_insn_single(env->prog, off, patch, len); 20790 if (IS_ERR(new_prog)) { 20791 if (PTR_ERR(new_prog) == -ERANGE) 20792 verbose(env, 20793 "insn %d cannot be patched due to 16-bit range\n", 20794 env->insn_aux_data[off].orig_idx); 20795 vfree(new_data); 20796 return NULL; 20797 } 20798 adjust_insn_aux_data(env, new_data, new_prog, off, len); 20799 adjust_subprog_starts(env, off, len); 20800 adjust_poke_descs(new_prog, off, len); 20801 return new_prog; 20802 } 20803 20804 /* 20805 * For all jmp insns in a given 'prog' that point to 'tgt_idx' insn adjust the 20806 * jump offset by 'delta'. 20807 */ 20808 static int adjust_jmp_off(struct bpf_prog *prog, u32 tgt_idx, u32 delta) 20809 { 20810 struct bpf_insn *insn = prog->insnsi; 20811 u32 insn_cnt = prog->len, i; 20812 s32 imm; 20813 s16 off; 20814 20815 for (i = 0; i < insn_cnt; i++, insn++) { 20816 u8 code = insn->code; 20817 20818 if (tgt_idx <= i && i < tgt_idx + delta) 20819 continue; 20820 20821 if ((BPF_CLASS(code) != BPF_JMP && BPF_CLASS(code) != BPF_JMP32) || 20822 BPF_OP(code) == BPF_CALL || BPF_OP(code) == BPF_EXIT) 20823 continue; 20824 20825 if (insn->code == (BPF_JMP32 | BPF_JA)) { 20826 if (i + 1 + insn->imm != tgt_idx) 20827 continue; 20828 if (check_add_overflow(insn->imm, delta, &imm)) 20829 return -ERANGE; 20830 insn->imm = imm; 20831 } else { 20832 if (i + 1 + insn->off != tgt_idx) 20833 continue; 20834 if (check_add_overflow(insn->off, delta, &off)) 20835 return -ERANGE; 20836 insn->off = off; 20837 } 20838 } 20839 return 0; 20840 } 20841 20842 static int adjust_subprog_starts_after_remove(struct bpf_verifier_env *env, 20843 u32 off, u32 cnt) 20844 { 20845 int i, j; 20846 20847 /* find first prog starting at or after off (first to remove) */ 20848 for (i = 0; i < env->subprog_cnt; i++) 20849 if (env->subprog_info[i].start >= off) 20850 break; 20851 /* find first prog starting at or after off + cnt (first to stay) */ 20852 for (j = i; j < env->subprog_cnt; j++) 20853 if (env->subprog_info[j].start >= off + cnt) 20854 break; 20855 /* if j doesn't start exactly at off + cnt, we are just removing 20856 * the front of previous prog 20857 */ 20858 if (env->subprog_info[j].start != off + cnt) 20859 j--; 20860 20861 if (j > i) { 20862 struct bpf_prog_aux *aux = env->prog->aux; 20863 int move; 20864 20865 /* move fake 'exit' subprog as well */ 20866 move = env->subprog_cnt + 1 - j; 20867 20868 memmove(env->subprog_info + i, 20869 env->subprog_info + j, 20870 sizeof(*env->subprog_info) * move); 20871 env->subprog_cnt -= j - i; 20872 20873 /* remove func_info */ 20874 if (aux->func_info) { 20875 move = aux->func_info_cnt - j; 20876 20877 memmove(aux->func_info + i, 20878 aux->func_info + j, 20879 sizeof(*aux->func_info) * move); 20880 aux->func_info_cnt -= j - i; 20881 /* func_info->insn_off is set after all code rewrites, 20882 * in adjust_btf_func() - no need to adjust 20883 */ 20884 } 20885 } else { 20886 /* convert i from "first prog to remove" to "first to adjust" */ 20887 if (env->subprog_info[i].start == off) 20888 i++; 20889 } 20890 20891 /* update fake 'exit' subprog as well */ 20892 for (; i <= env->subprog_cnt; i++) 20893 env->subprog_info[i].start -= cnt; 20894 20895 return 0; 20896 } 20897 20898 static int bpf_adj_linfo_after_remove(struct bpf_verifier_env *env, u32 off, 20899 u32 cnt) 20900 { 20901 struct bpf_prog *prog = env->prog; 20902 u32 i, l_off, l_cnt, nr_linfo; 20903 struct bpf_line_info *linfo; 20904 20905 nr_linfo = prog->aux->nr_linfo; 20906 if (!nr_linfo) 20907 return 0; 20908 20909 linfo = prog->aux->linfo; 20910 20911 /* find first line info to remove, count lines to be removed */ 20912 for (i = 0; i < nr_linfo; i++) 20913 if (linfo[i].insn_off >= off) 20914 break; 20915 20916 l_off = i; 20917 l_cnt = 0; 20918 for (; i < nr_linfo; i++) 20919 if (linfo[i].insn_off < off + cnt) 20920 l_cnt++; 20921 else 20922 break; 20923 20924 /* First live insn doesn't match first live linfo, it needs to "inherit" 20925 * last removed linfo. prog is already modified, so prog->len == off 20926 * means no live instructions after (tail of the program was removed). 20927 */ 20928 if (prog->len != off && l_cnt && 20929 (i == nr_linfo || linfo[i].insn_off != off + cnt)) { 20930 l_cnt--; 20931 linfo[--i].insn_off = off + cnt; 20932 } 20933 20934 /* remove the line info which refer to the removed instructions */ 20935 if (l_cnt) { 20936 memmove(linfo + l_off, linfo + i, 20937 sizeof(*linfo) * (nr_linfo - i)); 20938 20939 prog->aux->nr_linfo -= l_cnt; 20940 nr_linfo = prog->aux->nr_linfo; 20941 } 20942 20943 /* pull all linfo[i].insn_off >= off + cnt in by cnt */ 20944 for (i = l_off; i < nr_linfo; i++) 20945 linfo[i].insn_off -= cnt; 20946 20947 /* fix up all subprogs (incl. 'exit') which start >= off */ 20948 for (i = 0; i <= env->subprog_cnt; i++) 20949 if (env->subprog_info[i].linfo_idx > l_off) { 20950 /* program may have started in the removed region but 20951 * may not be fully removed 20952 */ 20953 if (env->subprog_info[i].linfo_idx >= l_off + l_cnt) 20954 env->subprog_info[i].linfo_idx -= l_cnt; 20955 else 20956 env->subprog_info[i].linfo_idx = l_off; 20957 } 20958 20959 return 0; 20960 } 20961 20962 static int verifier_remove_insns(struct bpf_verifier_env *env, u32 off, u32 cnt) 20963 { 20964 struct bpf_insn_aux_data *aux_data = env->insn_aux_data; 20965 unsigned int orig_prog_len = env->prog->len; 20966 int err; 20967 20968 if (bpf_prog_is_offloaded(env->prog->aux)) 20969 bpf_prog_offload_remove_insns(env, off, cnt); 20970 20971 err = bpf_remove_insns(env->prog, off, cnt); 20972 if (err) 20973 return err; 20974 20975 err = adjust_subprog_starts_after_remove(env, off, cnt); 20976 if (err) 20977 return err; 20978 20979 err = bpf_adj_linfo_after_remove(env, off, cnt); 20980 if (err) 20981 return err; 20982 20983 memmove(aux_data + off, aux_data + off + cnt, 20984 sizeof(*aux_data) * (orig_prog_len - off - cnt)); 20985 20986 return 0; 20987 } 20988 20989 /* The verifier does more data flow analysis than llvm and will not 20990 * explore branches that are dead at run time. Malicious programs can 20991 * have dead code too. Therefore replace all dead at-run-time code 20992 * with 'ja -1'. 20993 * 20994 * Just nops are not optimal, e.g. if they would sit at the end of the 20995 * program and through another bug we would manage to jump there, then 20996 * we'd execute beyond program memory otherwise. Returning exception 20997 * code also wouldn't work since we can have subprogs where the dead 20998 * code could be located. 20999 */ 21000 static void sanitize_dead_code(struct bpf_verifier_env *env) 21001 { 21002 struct bpf_insn_aux_data *aux_data = env->insn_aux_data; 21003 struct bpf_insn trap = BPF_JMP_IMM(BPF_JA, 0, 0, -1); 21004 struct bpf_insn *insn = env->prog->insnsi; 21005 const int insn_cnt = env->prog->len; 21006 int i; 21007 21008 for (i = 0; i < insn_cnt; i++) { 21009 if (aux_data[i].seen) 21010 continue; 21011 memcpy(insn + i, &trap, sizeof(trap)); 21012 aux_data[i].zext_dst = false; 21013 } 21014 } 21015 21016 static bool insn_is_cond_jump(u8 code) 21017 { 21018 u8 op; 21019 21020 op = BPF_OP(code); 21021 if (BPF_CLASS(code) == BPF_JMP32) 21022 return op != BPF_JA; 21023 21024 if (BPF_CLASS(code) != BPF_JMP) 21025 return false; 21026 21027 return op != BPF_JA && op != BPF_EXIT && op != BPF_CALL; 21028 } 21029 21030 static void opt_hard_wire_dead_code_branches(struct bpf_verifier_env *env) 21031 { 21032 struct bpf_insn_aux_data *aux_data = env->insn_aux_data; 21033 struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0); 21034 struct bpf_insn *insn = env->prog->insnsi; 21035 const int insn_cnt = env->prog->len; 21036 int i; 21037 21038 for (i = 0; i < insn_cnt; i++, insn++) { 21039 if (!insn_is_cond_jump(insn->code)) 21040 continue; 21041 21042 if (!aux_data[i + 1].seen) 21043 ja.off = insn->off; 21044 else if (!aux_data[i + 1 + insn->off].seen) 21045 ja.off = 0; 21046 else 21047 continue; 21048 21049 if (bpf_prog_is_offloaded(env->prog->aux)) 21050 bpf_prog_offload_replace_insn(env, i, &ja); 21051 21052 memcpy(insn, &ja, sizeof(ja)); 21053 } 21054 } 21055 21056 static int opt_remove_dead_code(struct bpf_verifier_env *env) 21057 { 21058 struct bpf_insn_aux_data *aux_data = env->insn_aux_data; 21059 int insn_cnt = env->prog->len; 21060 int i, err; 21061 21062 for (i = 0; i < insn_cnt; i++) { 21063 int j; 21064 21065 j = 0; 21066 while (i + j < insn_cnt && !aux_data[i + j].seen) 21067 j++; 21068 if (!j) 21069 continue; 21070 21071 err = verifier_remove_insns(env, i, j); 21072 if (err) 21073 return err; 21074 insn_cnt = env->prog->len; 21075 } 21076 21077 return 0; 21078 } 21079 21080 static const struct bpf_insn NOP = BPF_JMP_IMM(BPF_JA, 0, 0, 0); 21081 static const struct bpf_insn MAY_GOTO_0 = BPF_RAW_INSN(BPF_JMP | BPF_JCOND, 0, 0, 0, 0); 21082 21083 static int opt_remove_nops(struct bpf_verifier_env *env) 21084 { 21085 struct bpf_insn *insn = env->prog->insnsi; 21086 int insn_cnt = env->prog->len; 21087 bool is_may_goto_0, is_ja; 21088 int i, err; 21089 21090 for (i = 0; i < insn_cnt; i++) { 21091 is_may_goto_0 = !memcmp(&insn[i], &MAY_GOTO_0, sizeof(MAY_GOTO_0)); 21092 is_ja = !memcmp(&insn[i], &NOP, sizeof(NOP)); 21093 21094 if (!is_may_goto_0 && !is_ja) 21095 continue; 21096 21097 err = verifier_remove_insns(env, i, 1); 21098 if (err) 21099 return err; 21100 insn_cnt--; 21101 /* Go back one insn to catch may_goto +1; may_goto +0 sequence */ 21102 i -= (is_may_goto_0 && i > 0) ? 2 : 1; 21103 } 21104 21105 return 0; 21106 } 21107 21108 static int opt_subreg_zext_lo32_rnd_hi32(struct bpf_verifier_env *env, 21109 const union bpf_attr *attr) 21110 { 21111 struct bpf_insn *patch; 21112 /* use env->insn_buf as two independent buffers */ 21113 struct bpf_insn *zext_patch = env->insn_buf; 21114 struct bpf_insn *rnd_hi32_patch = &env->insn_buf[2]; 21115 struct bpf_insn_aux_data *aux = env->insn_aux_data; 21116 int i, patch_len, delta = 0, len = env->prog->len; 21117 struct bpf_insn *insns = env->prog->insnsi; 21118 struct bpf_prog *new_prog; 21119 bool rnd_hi32; 21120 21121 rnd_hi32 = attr->prog_flags & BPF_F_TEST_RND_HI32; 21122 zext_patch[1] = BPF_ZEXT_REG(0); 21123 rnd_hi32_patch[1] = BPF_ALU64_IMM(BPF_MOV, BPF_REG_AX, 0); 21124 rnd_hi32_patch[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_AX, 32); 21125 rnd_hi32_patch[3] = BPF_ALU64_REG(BPF_OR, 0, BPF_REG_AX); 21126 for (i = 0; i < len; i++) { 21127 int adj_idx = i + delta; 21128 struct bpf_insn insn; 21129 int load_reg; 21130 21131 insn = insns[adj_idx]; 21132 load_reg = insn_def_regno(&insn); 21133 if (!aux[adj_idx].zext_dst) { 21134 u8 code, class; 21135 u32 imm_rnd; 21136 21137 if (!rnd_hi32) 21138 continue; 21139 21140 code = insn.code; 21141 class = BPF_CLASS(code); 21142 if (load_reg == -1) 21143 continue; 21144 21145 /* NOTE: arg "reg" (the fourth one) is only used for 21146 * BPF_STX + SRC_OP, so it is safe to pass NULL 21147 * here. 21148 */ 21149 if (is_reg64(env, &insn, load_reg, NULL, DST_OP)) { 21150 if (class == BPF_LD && 21151 BPF_MODE(code) == BPF_IMM) 21152 i++; 21153 continue; 21154 } 21155 21156 /* ctx load could be transformed into wider load. */ 21157 if (class == BPF_LDX && 21158 aux[adj_idx].ptr_type == PTR_TO_CTX) 21159 continue; 21160 21161 imm_rnd = get_random_u32(); 21162 rnd_hi32_patch[0] = insn; 21163 rnd_hi32_patch[1].imm = imm_rnd; 21164 rnd_hi32_patch[3].dst_reg = load_reg; 21165 patch = rnd_hi32_patch; 21166 patch_len = 4; 21167 goto apply_patch_buffer; 21168 } 21169 21170 /* Add in an zero-extend instruction if a) the JIT has requested 21171 * it or b) it's a CMPXCHG. 21172 * 21173 * The latter is because: BPF_CMPXCHG always loads a value into 21174 * R0, therefore always zero-extends. However some archs' 21175 * equivalent instruction only does this load when the 21176 * comparison is successful. This detail of CMPXCHG is 21177 * orthogonal to the general zero-extension behaviour of the 21178 * CPU, so it's treated independently of bpf_jit_needs_zext. 21179 */ 21180 if (!bpf_jit_needs_zext() && !is_cmpxchg_insn(&insn)) 21181 continue; 21182 21183 /* Zero-extension is done by the caller. */ 21184 if (bpf_pseudo_kfunc_call(&insn)) 21185 continue; 21186 21187 if (verifier_bug_if(load_reg == -1, env, 21188 "zext_dst is set, but no reg is defined")) 21189 return -EFAULT; 21190 21191 zext_patch[0] = insn; 21192 zext_patch[1].dst_reg = load_reg; 21193 zext_patch[1].src_reg = load_reg; 21194 patch = zext_patch; 21195 patch_len = 2; 21196 apply_patch_buffer: 21197 new_prog = bpf_patch_insn_data(env, adj_idx, patch, patch_len); 21198 if (!new_prog) 21199 return -ENOMEM; 21200 env->prog = new_prog; 21201 insns = new_prog->insnsi; 21202 aux = env->insn_aux_data; 21203 delta += patch_len - 1; 21204 } 21205 21206 return 0; 21207 } 21208 21209 /* convert load instructions that access fields of a context type into a 21210 * sequence of instructions that access fields of the underlying structure: 21211 * struct __sk_buff -> struct sk_buff 21212 * struct bpf_sock_ops -> struct sock 21213 */ 21214 static int convert_ctx_accesses(struct bpf_verifier_env *env) 21215 { 21216 struct bpf_subprog_info *subprogs = env->subprog_info; 21217 const struct bpf_verifier_ops *ops = env->ops; 21218 int i, cnt, size, ctx_field_size, ret, delta = 0, epilogue_cnt = 0; 21219 const int insn_cnt = env->prog->len; 21220 struct bpf_insn *epilogue_buf = env->epilogue_buf; 21221 struct bpf_insn *insn_buf = env->insn_buf; 21222 struct bpf_insn *insn; 21223 u32 target_size, size_default, off; 21224 struct bpf_prog *new_prog; 21225 enum bpf_access_type type; 21226 bool is_narrower_load; 21227 int epilogue_idx = 0; 21228 21229 if (ops->gen_epilogue) { 21230 epilogue_cnt = ops->gen_epilogue(epilogue_buf, env->prog, 21231 -(subprogs[0].stack_depth + 8)); 21232 if (epilogue_cnt >= INSN_BUF_SIZE) { 21233 verifier_bug(env, "epilogue is too long"); 21234 return -EFAULT; 21235 } else if (epilogue_cnt) { 21236 /* Save the ARG_PTR_TO_CTX for the epilogue to use */ 21237 cnt = 0; 21238 subprogs[0].stack_depth += 8; 21239 insn_buf[cnt++] = BPF_STX_MEM(BPF_DW, BPF_REG_FP, BPF_REG_1, 21240 -subprogs[0].stack_depth); 21241 insn_buf[cnt++] = env->prog->insnsi[0]; 21242 new_prog = bpf_patch_insn_data(env, 0, insn_buf, cnt); 21243 if (!new_prog) 21244 return -ENOMEM; 21245 env->prog = new_prog; 21246 delta += cnt - 1; 21247 21248 ret = add_kfunc_in_insns(env, epilogue_buf, epilogue_cnt - 1); 21249 if (ret < 0) 21250 return ret; 21251 } 21252 } 21253 21254 if (ops->gen_prologue || env->seen_direct_write) { 21255 if (!ops->gen_prologue) { 21256 verifier_bug(env, "gen_prologue is null"); 21257 return -EFAULT; 21258 } 21259 cnt = ops->gen_prologue(insn_buf, env->seen_direct_write, 21260 env->prog); 21261 if (cnt >= INSN_BUF_SIZE) { 21262 verifier_bug(env, "prologue is too long"); 21263 return -EFAULT; 21264 } else if (cnt) { 21265 new_prog = bpf_patch_insn_data(env, 0, insn_buf, cnt); 21266 if (!new_prog) 21267 return -ENOMEM; 21268 21269 env->prog = new_prog; 21270 delta += cnt - 1; 21271 21272 ret = add_kfunc_in_insns(env, insn_buf, cnt - 1); 21273 if (ret < 0) 21274 return ret; 21275 } 21276 } 21277 21278 if (delta) 21279 WARN_ON(adjust_jmp_off(env->prog, 0, delta)); 21280 21281 if (bpf_prog_is_offloaded(env->prog->aux)) 21282 return 0; 21283 21284 insn = env->prog->insnsi + delta; 21285 21286 for (i = 0; i < insn_cnt; i++, insn++) { 21287 bpf_convert_ctx_access_t convert_ctx_access; 21288 u8 mode; 21289 21290 if (env->insn_aux_data[i + delta].nospec) { 21291 WARN_ON_ONCE(env->insn_aux_data[i + delta].alu_state); 21292 struct bpf_insn *patch = insn_buf; 21293 21294 *patch++ = BPF_ST_NOSPEC(); 21295 *patch++ = *insn; 21296 cnt = patch - insn_buf; 21297 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 21298 if (!new_prog) 21299 return -ENOMEM; 21300 21301 delta += cnt - 1; 21302 env->prog = new_prog; 21303 insn = new_prog->insnsi + i + delta; 21304 /* This can not be easily merged with the 21305 * nospec_result-case, because an insn may require a 21306 * nospec before and after itself. Therefore also do not 21307 * 'continue' here but potentially apply further 21308 * patching to insn. *insn should equal patch[1] now. 21309 */ 21310 } 21311 21312 if (insn->code == (BPF_LDX | BPF_MEM | BPF_B) || 21313 insn->code == (BPF_LDX | BPF_MEM | BPF_H) || 21314 insn->code == (BPF_LDX | BPF_MEM | BPF_W) || 21315 insn->code == (BPF_LDX | BPF_MEM | BPF_DW) || 21316 insn->code == (BPF_LDX | BPF_MEMSX | BPF_B) || 21317 insn->code == (BPF_LDX | BPF_MEMSX | BPF_H) || 21318 insn->code == (BPF_LDX | BPF_MEMSX | BPF_W)) { 21319 type = BPF_READ; 21320 } else if (insn->code == (BPF_STX | BPF_MEM | BPF_B) || 21321 insn->code == (BPF_STX | BPF_MEM | BPF_H) || 21322 insn->code == (BPF_STX | BPF_MEM | BPF_W) || 21323 insn->code == (BPF_STX | BPF_MEM | BPF_DW) || 21324 insn->code == (BPF_ST | BPF_MEM | BPF_B) || 21325 insn->code == (BPF_ST | BPF_MEM | BPF_H) || 21326 insn->code == (BPF_ST | BPF_MEM | BPF_W) || 21327 insn->code == (BPF_ST | BPF_MEM | BPF_DW)) { 21328 type = BPF_WRITE; 21329 } else if ((insn->code == (BPF_STX | BPF_ATOMIC | BPF_B) || 21330 insn->code == (BPF_STX | BPF_ATOMIC | BPF_H) || 21331 insn->code == (BPF_STX | BPF_ATOMIC | BPF_W) || 21332 insn->code == (BPF_STX | BPF_ATOMIC | BPF_DW)) && 21333 env->insn_aux_data[i + delta].ptr_type == PTR_TO_ARENA) { 21334 insn->code = BPF_STX | BPF_PROBE_ATOMIC | BPF_SIZE(insn->code); 21335 env->prog->aux->num_exentries++; 21336 continue; 21337 } else if (insn->code == (BPF_JMP | BPF_EXIT) && 21338 epilogue_cnt && 21339 i + delta < subprogs[1].start) { 21340 /* Generate epilogue for the main prog */ 21341 if (epilogue_idx) { 21342 /* jump back to the earlier generated epilogue */ 21343 insn_buf[0] = BPF_JMP32_A(epilogue_idx - i - delta - 1); 21344 cnt = 1; 21345 } else { 21346 memcpy(insn_buf, epilogue_buf, 21347 epilogue_cnt * sizeof(*epilogue_buf)); 21348 cnt = epilogue_cnt; 21349 /* epilogue_idx cannot be 0. It must have at 21350 * least one ctx ptr saving insn before the 21351 * epilogue. 21352 */ 21353 epilogue_idx = i + delta; 21354 } 21355 goto patch_insn_buf; 21356 } else { 21357 continue; 21358 } 21359 21360 if (type == BPF_WRITE && 21361 env->insn_aux_data[i + delta].nospec_result) { 21362 /* nospec_result is only used to mitigate Spectre v4 and 21363 * to limit verification-time for Spectre v1. 21364 */ 21365 struct bpf_insn *patch = insn_buf; 21366 21367 *patch++ = *insn; 21368 *patch++ = BPF_ST_NOSPEC(); 21369 cnt = patch - insn_buf; 21370 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 21371 if (!new_prog) 21372 return -ENOMEM; 21373 21374 delta += cnt - 1; 21375 env->prog = new_prog; 21376 insn = new_prog->insnsi + i + delta; 21377 continue; 21378 } 21379 21380 switch ((int)env->insn_aux_data[i + delta].ptr_type) { 21381 case PTR_TO_CTX: 21382 if (!ops->convert_ctx_access) 21383 continue; 21384 convert_ctx_access = ops->convert_ctx_access; 21385 break; 21386 case PTR_TO_SOCKET: 21387 case PTR_TO_SOCK_COMMON: 21388 convert_ctx_access = bpf_sock_convert_ctx_access; 21389 break; 21390 case PTR_TO_TCP_SOCK: 21391 convert_ctx_access = bpf_tcp_sock_convert_ctx_access; 21392 break; 21393 case PTR_TO_XDP_SOCK: 21394 convert_ctx_access = bpf_xdp_sock_convert_ctx_access; 21395 break; 21396 case PTR_TO_BTF_ID: 21397 case PTR_TO_BTF_ID | PTR_UNTRUSTED: 21398 /* PTR_TO_BTF_ID | MEM_ALLOC always has a valid lifetime, unlike 21399 * PTR_TO_BTF_ID, and an active ref_obj_id, but the same cannot 21400 * be said once it is marked PTR_UNTRUSTED, hence we must handle 21401 * any faults for loads into such types. BPF_WRITE is disallowed 21402 * for this case. 21403 */ 21404 case PTR_TO_BTF_ID | MEM_ALLOC | PTR_UNTRUSTED: 21405 case PTR_TO_MEM | MEM_RDONLY | PTR_UNTRUSTED: 21406 if (type == BPF_READ) { 21407 if (BPF_MODE(insn->code) == BPF_MEM) 21408 insn->code = BPF_LDX | BPF_PROBE_MEM | 21409 BPF_SIZE((insn)->code); 21410 else 21411 insn->code = BPF_LDX | BPF_PROBE_MEMSX | 21412 BPF_SIZE((insn)->code); 21413 env->prog->aux->num_exentries++; 21414 } 21415 continue; 21416 case PTR_TO_ARENA: 21417 if (BPF_MODE(insn->code) == BPF_MEMSX) { 21418 verbose(env, "sign extending loads from arena are not supported yet\n"); 21419 return -EOPNOTSUPP; 21420 } 21421 insn->code = BPF_CLASS(insn->code) | BPF_PROBE_MEM32 | BPF_SIZE(insn->code); 21422 env->prog->aux->num_exentries++; 21423 continue; 21424 default: 21425 continue; 21426 } 21427 21428 ctx_field_size = env->insn_aux_data[i + delta].ctx_field_size; 21429 size = BPF_LDST_BYTES(insn); 21430 mode = BPF_MODE(insn->code); 21431 21432 /* If the read access is a narrower load of the field, 21433 * convert to a 4/8-byte load, to minimum program type specific 21434 * convert_ctx_access changes. If conversion is successful, 21435 * we will apply proper mask to the result. 21436 */ 21437 is_narrower_load = size < ctx_field_size; 21438 size_default = bpf_ctx_off_adjust_machine(ctx_field_size); 21439 off = insn->off; 21440 if (is_narrower_load) { 21441 u8 size_code; 21442 21443 if (type == BPF_WRITE) { 21444 verifier_bug(env, "narrow ctx access misconfigured"); 21445 return -EFAULT; 21446 } 21447 21448 size_code = BPF_H; 21449 if (ctx_field_size == 4) 21450 size_code = BPF_W; 21451 else if (ctx_field_size == 8) 21452 size_code = BPF_DW; 21453 21454 insn->off = off & ~(size_default - 1); 21455 insn->code = BPF_LDX | BPF_MEM | size_code; 21456 } 21457 21458 target_size = 0; 21459 cnt = convert_ctx_access(type, insn, insn_buf, env->prog, 21460 &target_size); 21461 if (cnt == 0 || cnt >= INSN_BUF_SIZE || 21462 (ctx_field_size && !target_size)) { 21463 verifier_bug(env, "error during ctx access conversion (%d)", cnt); 21464 return -EFAULT; 21465 } 21466 21467 if (is_narrower_load && size < target_size) { 21468 u8 shift = bpf_ctx_narrow_access_offset( 21469 off, size, size_default) * 8; 21470 if (shift && cnt + 1 >= INSN_BUF_SIZE) { 21471 verifier_bug(env, "narrow ctx load misconfigured"); 21472 return -EFAULT; 21473 } 21474 if (ctx_field_size <= 4) { 21475 if (shift) 21476 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_RSH, 21477 insn->dst_reg, 21478 shift); 21479 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg, 21480 (1 << size * 8) - 1); 21481 } else { 21482 if (shift) 21483 insn_buf[cnt++] = BPF_ALU64_IMM(BPF_RSH, 21484 insn->dst_reg, 21485 shift); 21486 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg, 21487 (1ULL << size * 8) - 1); 21488 } 21489 } 21490 if (mode == BPF_MEMSX) 21491 insn_buf[cnt++] = BPF_RAW_INSN(BPF_ALU64 | BPF_MOV | BPF_X, 21492 insn->dst_reg, insn->dst_reg, 21493 size * 8, 0); 21494 21495 patch_insn_buf: 21496 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 21497 if (!new_prog) 21498 return -ENOMEM; 21499 21500 delta += cnt - 1; 21501 21502 /* keep walking new program and skip insns we just inserted */ 21503 env->prog = new_prog; 21504 insn = new_prog->insnsi + i + delta; 21505 } 21506 21507 return 0; 21508 } 21509 21510 static int jit_subprogs(struct bpf_verifier_env *env) 21511 { 21512 struct bpf_prog *prog = env->prog, **func, *tmp; 21513 int i, j, subprog_start, subprog_end = 0, len, subprog; 21514 struct bpf_map *map_ptr; 21515 struct bpf_insn *insn; 21516 void *old_bpf_func; 21517 int err, num_exentries; 21518 21519 if (env->subprog_cnt <= 1) 21520 return 0; 21521 21522 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) { 21523 if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn)) 21524 continue; 21525 21526 /* Upon error here we cannot fall back to interpreter but 21527 * need a hard reject of the program. Thus -EFAULT is 21528 * propagated in any case. 21529 */ 21530 subprog = find_subprog(env, i + insn->imm + 1); 21531 if (verifier_bug_if(subprog < 0, env, "No program to jit at insn %d", 21532 i + insn->imm + 1)) 21533 return -EFAULT; 21534 /* temporarily remember subprog id inside insn instead of 21535 * aux_data, since next loop will split up all insns into funcs 21536 */ 21537 insn->off = subprog; 21538 /* remember original imm in case JIT fails and fallback 21539 * to interpreter will be needed 21540 */ 21541 env->insn_aux_data[i].call_imm = insn->imm; 21542 /* point imm to __bpf_call_base+1 from JITs point of view */ 21543 insn->imm = 1; 21544 if (bpf_pseudo_func(insn)) { 21545 #if defined(MODULES_VADDR) 21546 u64 addr = MODULES_VADDR; 21547 #else 21548 u64 addr = VMALLOC_START; 21549 #endif 21550 /* jit (e.g. x86_64) may emit fewer instructions 21551 * if it learns a u32 imm is the same as a u64 imm. 21552 * Set close enough to possible prog address. 21553 */ 21554 insn[0].imm = (u32)addr; 21555 insn[1].imm = addr >> 32; 21556 } 21557 } 21558 21559 err = bpf_prog_alloc_jited_linfo(prog); 21560 if (err) 21561 goto out_undo_insn; 21562 21563 err = -ENOMEM; 21564 func = kcalloc(env->subprog_cnt, sizeof(prog), GFP_KERNEL); 21565 if (!func) 21566 goto out_undo_insn; 21567 21568 for (i = 0; i < env->subprog_cnt; i++) { 21569 subprog_start = subprog_end; 21570 subprog_end = env->subprog_info[i + 1].start; 21571 21572 len = subprog_end - subprog_start; 21573 /* bpf_prog_run() doesn't call subprogs directly, 21574 * hence main prog stats include the runtime of subprogs. 21575 * subprogs don't have IDs and not reachable via prog_get_next_id 21576 * func[i]->stats will never be accessed and stays NULL 21577 */ 21578 func[i] = bpf_prog_alloc_no_stats(bpf_prog_size(len), GFP_USER); 21579 if (!func[i]) 21580 goto out_free; 21581 memcpy(func[i]->insnsi, &prog->insnsi[subprog_start], 21582 len * sizeof(struct bpf_insn)); 21583 func[i]->type = prog->type; 21584 func[i]->len = len; 21585 if (bpf_prog_calc_tag(func[i])) 21586 goto out_free; 21587 func[i]->is_func = 1; 21588 func[i]->sleepable = prog->sleepable; 21589 func[i]->aux->func_idx = i; 21590 /* Below members will be freed only at prog->aux */ 21591 func[i]->aux->btf = prog->aux->btf; 21592 func[i]->aux->func_info = prog->aux->func_info; 21593 func[i]->aux->func_info_cnt = prog->aux->func_info_cnt; 21594 func[i]->aux->poke_tab = prog->aux->poke_tab; 21595 func[i]->aux->size_poke_tab = prog->aux->size_poke_tab; 21596 21597 for (j = 0; j < prog->aux->size_poke_tab; j++) { 21598 struct bpf_jit_poke_descriptor *poke; 21599 21600 poke = &prog->aux->poke_tab[j]; 21601 if (poke->insn_idx < subprog_end && 21602 poke->insn_idx >= subprog_start) 21603 poke->aux = func[i]->aux; 21604 } 21605 21606 func[i]->aux->name[0] = 'F'; 21607 func[i]->aux->stack_depth = env->subprog_info[i].stack_depth; 21608 if (env->subprog_info[i].priv_stack_mode == PRIV_STACK_ADAPTIVE) 21609 func[i]->aux->jits_use_priv_stack = true; 21610 21611 func[i]->jit_requested = 1; 21612 func[i]->blinding_requested = prog->blinding_requested; 21613 func[i]->aux->kfunc_tab = prog->aux->kfunc_tab; 21614 func[i]->aux->kfunc_btf_tab = prog->aux->kfunc_btf_tab; 21615 func[i]->aux->linfo = prog->aux->linfo; 21616 func[i]->aux->nr_linfo = prog->aux->nr_linfo; 21617 func[i]->aux->jited_linfo = prog->aux->jited_linfo; 21618 func[i]->aux->linfo_idx = env->subprog_info[i].linfo_idx; 21619 func[i]->aux->arena = prog->aux->arena; 21620 num_exentries = 0; 21621 insn = func[i]->insnsi; 21622 for (j = 0; j < func[i]->len; j++, insn++) { 21623 if (BPF_CLASS(insn->code) == BPF_LDX && 21624 (BPF_MODE(insn->code) == BPF_PROBE_MEM || 21625 BPF_MODE(insn->code) == BPF_PROBE_MEM32 || 21626 BPF_MODE(insn->code) == BPF_PROBE_MEMSX)) 21627 num_exentries++; 21628 if ((BPF_CLASS(insn->code) == BPF_STX || 21629 BPF_CLASS(insn->code) == BPF_ST) && 21630 BPF_MODE(insn->code) == BPF_PROBE_MEM32) 21631 num_exentries++; 21632 if (BPF_CLASS(insn->code) == BPF_STX && 21633 BPF_MODE(insn->code) == BPF_PROBE_ATOMIC) 21634 num_exentries++; 21635 } 21636 func[i]->aux->num_exentries = num_exentries; 21637 func[i]->aux->tail_call_reachable = env->subprog_info[i].tail_call_reachable; 21638 func[i]->aux->exception_cb = env->subprog_info[i].is_exception_cb; 21639 func[i]->aux->changes_pkt_data = env->subprog_info[i].changes_pkt_data; 21640 func[i]->aux->might_sleep = env->subprog_info[i].might_sleep; 21641 if (!i) 21642 func[i]->aux->exception_boundary = env->seen_exception; 21643 func[i] = bpf_int_jit_compile(func[i]); 21644 if (!func[i]->jited) { 21645 err = -ENOTSUPP; 21646 goto out_free; 21647 } 21648 cond_resched(); 21649 } 21650 21651 /* at this point all bpf functions were successfully JITed 21652 * now populate all bpf_calls with correct addresses and 21653 * run last pass of JIT 21654 */ 21655 for (i = 0; i < env->subprog_cnt; i++) { 21656 insn = func[i]->insnsi; 21657 for (j = 0; j < func[i]->len; j++, insn++) { 21658 if (bpf_pseudo_func(insn)) { 21659 subprog = insn->off; 21660 insn[0].imm = (u32)(long)func[subprog]->bpf_func; 21661 insn[1].imm = ((u64)(long)func[subprog]->bpf_func) >> 32; 21662 continue; 21663 } 21664 if (!bpf_pseudo_call(insn)) 21665 continue; 21666 subprog = insn->off; 21667 insn->imm = BPF_CALL_IMM(func[subprog]->bpf_func); 21668 } 21669 21670 /* we use the aux data to keep a list of the start addresses 21671 * of the JITed images for each function in the program 21672 * 21673 * for some architectures, such as powerpc64, the imm field 21674 * might not be large enough to hold the offset of the start 21675 * address of the callee's JITed image from __bpf_call_base 21676 * 21677 * in such cases, we can lookup the start address of a callee 21678 * by using its subprog id, available from the off field of 21679 * the call instruction, as an index for this list 21680 */ 21681 func[i]->aux->func = func; 21682 func[i]->aux->func_cnt = env->subprog_cnt - env->hidden_subprog_cnt; 21683 func[i]->aux->real_func_cnt = env->subprog_cnt; 21684 } 21685 for (i = 0; i < env->subprog_cnt; i++) { 21686 old_bpf_func = func[i]->bpf_func; 21687 tmp = bpf_int_jit_compile(func[i]); 21688 if (tmp != func[i] || func[i]->bpf_func != old_bpf_func) { 21689 verbose(env, "JIT doesn't support bpf-to-bpf calls\n"); 21690 err = -ENOTSUPP; 21691 goto out_free; 21692 } 21693 cond_resched(); 21694 } 21695 21696 /* finally lock prog and jit images for all functions and 21697 * populate kallsysm. Begin at the first subprogram, since 21698 * bpf_prog_load will add the kallsyms for the main program. 21699 */ 21700 for (i = 1; i < env->subprog_cnt; i++) { 21701 err = bpf_prog_lock_ro(func[i]); 21702 if (err) 21703 goto out_free; 21704 } 21705 21706 for (i = 1; i < env->subprog_cnt; i++) 21707 bpf_prog_kallsyms_add(func[i]); 21708 21709 /* Last step: make now unused interpreter insns from main 21710 * prog consistent for later dump requests, so they can 21711 * later look the same as if they were interpreted only. 21712 */ 21713 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) { 21714 if (bpf_pseudo_func(insn)) { 21715 insn[0].imm = env->insn_aux_data[i].call_imm; 21716 insn[1].imm = insn->off; 21717 insn->off = 0; 21718 continue; 21719 } 21720 if (!bpf_pseudo_call(insn)) 21721 continue; 21722 insn->off = env->insn_aux_data[i].call_imm; 21723 subprog = find_subprog(env, i + insn->off + 1); 21724 insn->imm = subprog; 21725 } 21726 21727 prog->jited = 1; 21728 prog->bpf_func = func[0]->bpf_func; 21729 prog->jited_len = func[0]->jited_len; 21730 prog->aux->extable = func[0]->aux->extable; 21731 prog->aux->num_exentries = func[0]->aux->num_exentries; 21732 prog->aux->func = func; 21733 prog->aux->func_cnt = env->subprog_cnt - env->hidden_subprog_cnt; 21734 prog->aux->real_func_cnt = env->subprog_cnt; 21735 prog->aux->bpf_exception_cb = (void *)func[env->exception_callback_subprog]->bpf_func; 21736 prog->aux->exception_boundary = func[0]->aux->exception_boundary; 21737 bpf_prog_jit_attempt_done(prog); 21738 return 0; 21739 out_free: 21740 /* We failed JIT'ing, so at this point we need to unregister poke 21741 * descriptors from subprogs, so that kernel is not attempting to 21742 * patch it anymore as we're freeing the subprog JIT memory. 21743 */ 21744 for (i = 0; i < prog->aux->size_poke_tab; i++) { 21745 map_ptr = prog->aux->poke_tab[i].tail_call.map; 21746 map_ptr->ops->map_poke_untrack(map_ptr, prog->aux); 21747 } 21748 /* At this point we're guaranteed that poke descriptors are not 21749 * live anymore. We can just unlink its descriptor table as it's 21750 * released with the main prog. 21751 */ 21752 for (i = 0; i < env->subprog_cnt; i++) { 21753 if (!func[i]) 21754 continue; 21755 func[i]->aux->poke_tab = NULL; 21756 bpf_jit_free(func[i]); 21757 } 21758 kfree(func); 21759 out_undo_insn: 21760 /* cleanup main prog to be interpreted */ 21761 prog->jit_requested = 0; 21762 prog->blinding_requested = 0; 21763 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) { 21764 if (!bpf_pseudo_call(insn)) 21765 continue; 21766 insn->off = 0; 21767 insn->imm = env->insn_aux_data[i].call_imm; 21768 } 21769 bpf_prog_jit_attempt_done(prog); 21770 return err; 21771 } 21772 21773 static int fixup_call_args(struct bpf_verifier_env *env) 21774 { 21775 #ifndef CONFIG_BPF_JIT_ALWAYS_ON 21776 struct bpf_prog *prog = env->prog; 21777 struct bpf_insn *insn = prog->insnsi; 21778 bool has_kfunc_call = bpf_prog_has_kfunc_call(prog); 21779 int i, depth; 21780 #endif 21781 int err = 0; 21782 21783 if (env->prog->jit_requested && 21784 !bpf_prog_is_offloaded(env->prog->aux)) { 21785 err = jit_subprogs(env); 21786 if (err == 0) 21787 return 0; 21788 if (err == -EFAULT) 21789 return err; 21790 } 21791 #ifndef CONFIG_BPF_JIT_ALWAYS_ON 21792 if (has_kfunc_call) { 21793 verbose(env, "calling kernel functions are not allowed in non-JITed programs\n"); 21794 return -EINVAL; 21795 } 21796 if (env->subprog_cnt > 1 && env->prog->aux->tail_call_reachable) { 21797 /* When JIT fails the progs with bpf2bpf calls and tail_calls 21798 * have to be rejected, since interpreter doesn't support them yet. 21799 */ 21800 verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n"); 21801 return -EINVAL; 21802 } 21803 for (i = 0; i < prog->len; i++, insn++) { 21804 if (bpf_pseudo_func(insn)) { 21805 /* When JIT fails the progs with callback calls 21806 * have to be rejected, since interpreter doesn't support them yet. 21807 */ 21808 verbose(env, "callbacks are not allowed in non-JITed programs\n"); 21809 return -EINVAL; 21810 } 21811 21812 if (!bpf_pseudo_call(insn)) 21813 continue; 21814 depth = get_callee_stack_depth(env, insn, i); 21815 if (depth < 0) 21816 return depth; 21817 bpf_patch_call_args(insn, depth); 21818 } 21819 err = 0; 21820 #endif 21821 return err; 21822 } 21823 21824 /* replace a generic kfunc with a specialized version if necessary */ 21825 static void specialize_kfunc(struct bpf_verifier_env *env, 21826 u32 func_id, u16 offset, unsigned long *addr) 21827 { 21828 struct bpf_prog *prog = env->prog; 21829 bool seen_direct_write; 21830 void *xdp_kfunc; 21831 bool is_rdonly; 21832 21833 if (bpf_dev_bound_kfunc_id(func_id)) { 21834 xdp_kfunc = bpf_dev_bound_resolve_kfunc(prog, func_id); 21835 if (xdp_kfunc) { 21836 *addr = (unsigned long)xdp_kfunc; 21837 return; 21838 } 21839 /* fallback to default kfunc when not supported by netdev */ 21840 } 21841 21842 if (offset) 21843 return; 21844 21845 if (func_id == special_kfunc_list[KF_bpf_dynptr_from_skb]) { 21846 seen_direct_write = env->seen_direct_write; 21847 is_rdonly = !may_access_direct_pkt_data(env, NULL, BPF_WRITE); 21848 21849 if (is_rdonly) 21850 *addr = (unsigned long)bpf_dynptr_from_skb_rdonly; 21851 21852 /* restore env->seen_direct_write to its original value, since 21853 * may_access_direct_pkt_data mutates it 21854 */ 21855 env->seen_direct_write = seen_direct_write; 21856 } 21857 21858 if (func_id == special_kfunc_list[KF_bpf_set_dentry_xattr] && 21859 bpf_lsm_has_d_inode_locked(prog)) 21860 *addr = (unsigned long)bpf_set_dentry_xattr_locked; 21861 21862 if (func_id == special_kfunc_list[KF_bpf_remove_dentry_xattr] && 21863 bpf_lsm_has_d_inode_locked(prog)) 21864 *addr = (unsigned long)bpf_remove_dentry_xattr_locked; 21865 } 21866 21867 static void __fixup_collection_insert_kfunc(struct bpf_insn_aux_data *insn_aux, 21868 u16 struct_meta_reg, 21869 u16 node_offset_reg, 21870 struct bpf_insn *insn, 21871 struct bpf_insn *insn_buf, 21872 int *cnt) 21873 { 21874 struct btf_struct_meta *kptr_struct_meta = insn_aux->kptr_struct_meta; 21875 struct bpf_insn addr[2] = { BPF_LD_IMM64(struct_meta_reg, (long)kptr_struct_meta) }; 21876 21877 insn_buf[0] = addr[0]; 21878 insn_buf[1] = addr[1]; 21879 insn_buf[2] = BPF_MOV64_IMM(node_offset_reg, insn_aux->insert_off); 21880 insn_buf[3] = *insn; 21881 *cnt = 4; 21882 } 21883 21884 static int fixup_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn, 21885 struct bpf_insn *insn_buf, int insn_idx, int *cnt) 21886 { 21887 const struct bpf_kfunc_desc *desc; 21888 21889 if (!insn->imm) { 21890 verbose(env, "invalid kernel function call not eliminated in verifier pass\n"); 21891 return -EINVAL; 21892 } 21893 21894 *cnt = 0; 21895 21896 /* insn->imm has the btf func_id. Replace it with an offset relative to 21897 * __bpf_call_base, unless the JIT needs to call functions that are 21898 * further than 32 bits away (bpf_jit_supports_far_kfunc_call()). 21899 */ 21900 desc = find_kfunc_desc(env->prog, insn->imm, insn->off); 21901 if (!desc) { 21902 verifier_bug(env, "kernel function descriptor not found for func_id %u", 21903 insn->imm); 21904 return -EFAULT; 21905 } 21906 21907 if (!bpf_jit_supports_far_kfunc_call()) 21908 insn->imm = BPF_CALL_IMM(desc->addr); 21909 if (insn->off) 21910 return 0; 21911 if (desc->func_id == special_kfunc_list[KF_bpf_obj_new_impl] || 21912 desc->func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl]) { 21913 struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta; 21914 struct bpf_insn addr[2] = { BPF_LD_IMM64(BPF_REG_2, (long)kptr_struct_meta) }; 21915 u64 obj_new_size = env->insn_aux_data[insn_idx].obj_new_size; 21916 21917 if (desc->func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl] && kptr_struct_meta) { 21918 verifier_bug(env, "NULL kptr_struct_meta expected at insn_idx %d", 21919 insn_idx); 21920 return -EFAULT; 21921 } 21922 21923 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_1, obj_new_size); 21924 insn_buf[1] = addr[0]; 21925 insn_buf[2] = addr[1]; 21926 insn_buf[3] = *insn; 21927 *cnt = 4; 21928 } else if (desc->func_id == special_kfunc_list[KF_bpf_obj_drop_impl] || 21929 desc->func_id == special_kfunc_list[KF_bpf_percpu_obj_drop_impl] || 21930 desc->func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl]) { 21931 struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta; 21932 struct bpf_insn addr[2] = { BPF_LD_IMM64(BPF_REG_2, (long)kptr_struct_meta) }; 21933 21934 if (desc->func_id == special_kfunc_list[KF_bpf_percpu_obj_drop_impl] && kptr_struct_meta) { 21935 verifier_bug(env, "NULL kptr_struct_meta expected at insn_idx %d", 21936 insn_idx); 21937 return -EFAULT; 21938 } 21939 21940 if (desc->func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl] && 21941 !kptr_struct_meta) { 21942 verifier_bug(env, "kptr_struct_meta expected at insn_idx %d", 21943 insn_idx); 21944 return -EFAULT; 21945 } 21946 21947 insn_buf[0] = addr[0]; 21948 insn_buf[1] = addr[1]; 21949 insn_buf[2] = *insn; 21950 *cnt = 3; 21951 } else if (desc->func_id == special_kfunc_list[KF_bpf_list_push_back_impl] || 21952 desc->func_id == special_kfunc_list[KF_bpf_list_push_front_impl] || 21953 desc->func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) { 21954 struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta; 21955 int struct_meta_reg = BPF_REG_3; 21956 int node_offset_reg = BPF_REG_4; 21957 21958 /* rbtree_add has extra 'less' arg, so args-to-fixup are in diff regs */ 21959 if (desc->func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) { 21960 struct_meta_reg = BPF_REG_4; 21961 node_offset_reg = BPF_REG_5; 21962 } 21963 21964 if (!kptr_struct_meta) { 21965 verifier_bug(env, "kptr_struct_meta expected at insn_idx %d", 21966 insn_idx); 21967 return -EFAULT; 21968 } 21969 21970 __fixup_collection_insert_kfunc(&env->insn_aux_data[insn_idx], struct_meta_reg, 21971 node_offset_reg, insn, insn_buf, cnt); 21972 } else if (desc->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx] || 21973 desc->func_id == special_kfunc_list[KF_bpf_rdonly_cast]) { 21974 insn_buf[0] = BPF_MOV64_REG(BPF_REG_0, BPF_REG_1); 21975 *cnt = 1; 21976 } 21977 21978 if (env->insn_aux_data[insn_idx].arg_prog) { 21979 u32 regno = env->insn_aux_data[insn_idx].arg_prog; 21980 struct bpf_insn ld_addrs[2] = { BPF_LD_IMM64(regno, (long)env->prog->aux) }; 21981 int idx = *cnt; 21982 21983 insn_buf[idx++] = ld_addrs[0]; 21984 insn_buf[idx++] = ld_addrs[1]; 21985 insn_buf[idx++] = *insn; 21986 *cnt = idx; 21987 } 21988 return 0; 21989 } 21990 21991 /* The function requires that first instruction in 'patch' is insnsi[prog->len - 1] */ 21992 static int add_hidden_subprog(struct bpf_verifier_env *env, struct bpf_insn *patch, int len) 21993 { 21994 struct bpf_subprog_info *info = env->subprog_info; 21995 int cnt = env->subprog_cnt; 21996 struct bpf_prog *prog; 21997 21998 /* We only reserve one slot for hidden subprogs in subprog_info. */ 21999 if (env->hidden_subprog_cnt) { 22000 verifier_bug(env, "only one hidden subprog supported"); 22001 return -EFAULT; 22002 } 22003 /* We're not patching any existing instruction, just appending the new 22004 * ones for the hidden subprog. Hence all of the adjustment operations 22005 * in bpf_patch_insn_data are no-ops. 22006 */ 22007 prog = bpf_patch_insn_data(env, env->prog->len - 1, patch, len); 22008 if (!prog) 22009 return -ENOMEM; 22010 env->prog = prog; 22011 info[cnt + 1].start = info[cnt].start; 22012 info[cnt].start = prog->len - len + 1; 22013 env->subprog_cnt++; 22014 env->hidden_subprog_cnt++; 22015 return 0; 22016 } 22017 22018 /* Do various post-verification rewrites in a single program pass. 22019 * These rewrites simplify JIT and interpreter implementations. 22020 */ 22021 static int do_misc_fixups(struct bpf_verifier_env *env) 22022 { 22023 struct bpf_prog *prog = env->prog; 22024 enum bpf_attach_type eatype = prog->expected_attach_type; 22025 enum bpf_prog_type prog_type = resolve_prog_type(prog); 22026 struct bpf_insn *insn = prog->insnsi; 22027 const struct bpf_func_proto *fn; 22028 const int insn_cnt = prog->len; 22029 const struct bpf_map_ops *ops; 22030 struct bpf_insn_aux_data *aux; 22031 struct bpf_insn *insn_buf = env->insn_buf; 22032 struct bpf_prog *new_prog; 22033 struct bpf_map *map_ptr; 22034 int i, ret, cnt, delta = 0, cur_subprog = 0; 22035 struct bpf_subprog_info *subprogs = env->subprog_info; 22036 u16 stack_depth = subprogs[cur_subprog].stack_depth; 22037 u16 stack_depth_extra = 0; 22038 22039 if (env->seen_exception && !env->exception_callback_subprog) { 22040 struct bpf_insn *patch = insn_buf; 22041 22042 *patch++ = env->prog->insnsi[insn_cnt - 1]; 22043 *patch++ = BPF_MOV64_REG(BPF_REG_0, BPF_REG_1); 22044 *patch++ = BPF_EXIT_INSN(); 22045 ret = add_hidden_subprog(env, insn_buf, patch - insn_buf); 22046 if (ret < 0) 22047 return ret; 22048 prog = env->prog; 22049 insn = prog->insnsi; 22050 22051 env->exception_callback_subprog = env->subprog_cnt - 1; 22052 /* Don't update insn_cnt, as add_hidden_subprog always appends insns */ 22053 mark_subprog_exc_cb(env, env->exception_callback_subprog); 22054 } 22055 22056 for (i = 0; i < insn_cnt;) { 22057 if (insn->code == (BPF_ALU64 | BPF_MOV | BPF_X) && insn->imm) { 22058 if ((insn->off == BPF_ADDR_SPACE_CAST && insn->imm == 1) || 22059 (((struct bpf_map *)env->prog->aux->arena)->map_flags & BPF_F_NO_USER_CONV)) { 22060 /* convert to 32-bit mov that clears upper 32-bit */ 22061 insn->code = BPF_ALU | BPF_MOV | BPF_X; 22062 /* clear off and imm, so it's a normal 'wX = wY' from JIT pov */ 22063 insn->off = 0; 22064 insn->imm = 0; 22065 } /* cast from as(0) to as(1) should be handled by JIT */ 22066 goto next_insn; 22067 } 22068 22069 if (env->insn_aux_data[i + delta].needs_zext) 22070 /* Convert BPF_CLASS(insn->code) == BPF_ALU64 to 32-bit ALU */ 22071 insn->code = BPF_ALU | BPF_OP(insn->code) | BPF_SRC(insn->code); 22072 22073 /* Make sdiv/smod divide-by-minus-one exceptions impossible. */ 22074 if ((insn->code == (BPF_ALU64 | BPF_MOD | BPF_K) || 22075 insn->code == (BPF_ALU64 | BPF_DIV | BPF_K) || 22076 insn->code == (BPF_ALU | BPF_MOD | BPF_K) || 22077 insn->code == (BPF_ALU | BPF_DIV | BPF_K)) && 22078 insn->off == 1 && insn->imm == -1) { 22079 bool is64 = BPF_CLASS(insn->code) == BPF_ALU64; 22080 bool isdiv = BPF_OP(insn->code) == BPF_DIV; 22081 struct bpf_insn *patch = insn_buf; 22082 22083 if (isdiv) 22084 *patch++ = BPF_RAW_INSN((is64 ? BPF_ALU64 : BPF_ALU) | 22085 BPF_NEG | BPF_K, insn->dst_reg, 22086 0, 0, 0); 22087 else 22088 *patch++ = BPF_MOV32_IMM(insn->dst_reg, 0); 22089 22090 cnt = patch - insn_buf; 22091 22092 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 22093 if (!new_prog) 22094 return -ENOMEM; 22095 22096 delta += cnt - 1; 22097 env->prog = prog = new_prog; 22098 insn = new_prog->insnsi + i + delta; 22099 goto next_insn; 22100 } 22101 22102 /* Make divide-by-zero and divide-by-minus-one exceptions impossible. */ 22103 if (insn->code == (BPF_ALU64 | BPF_MOD | BPF_X) || 22104 insn->code == (BPF_ALU64 | BPF_DIV | BPF_X) || 22105 insn->code == (BPF_ALU | BPF_MOD | BPF_X) || 22106 insn->code == (BPF_ALU | BPF_DIV | BPF_X)) { 22107 bool is64 = BPF_CLASS(insn->code) == BPF_ALU64; 22108 bool isdiv = BPF_OP(insn->code) == BPF_DIV; 22109 bool is_sdiv = isdiv && insn->off == 1; 22110 bool is_smod = !isdiv && insn->off == 1; 22111 struct bpf_insn *patch = insn_buf; 22112 22113 if (is_sdiv) { 22114 /* [R,W]x sdiv 0 -> 0 22115 * LLONG_MIN sdiv -1 -> LLONG_MIN 22116 * INT_MIN sdiv -1 -> INT_MIN 22117 */ 22118 *patch++ = BPF_MOV64_REG(BPF_REG_AX, insn->src_reg); 22119 *patch++ = BPF_RAW_INSN((is64 ? BPF_ALU64 : BPF_ALU) | 22120 BPF_ADD | BPF_K, BPF_REG_AX, 22121 0, 0, 1); 22122 *patch++ = BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) | 22123 BPF_JGT | BPF_K, BPF_REG_AX, 22124 0, 4, 1); 22125 *patch++ = BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) | 22126 BPF_JEQ | BPF_K, BPF_REG_AX, 22127 0, 1, 0); 22128 *patch++ = BPF_RAW_INSN((is64 ? BPF_ALU64 : BPF_ALU) | 22129 BPF_MOV | BPF_K, insn->dst_reg, 22130 0, 0, 0); 22131 /* BPF_NEG(LLONG_MIN) == -LLONG_MIN == LLONG_MIN */ 22132 *patch++ = BPF_RAW_INSN((is64 ? BPF_ALU64 : BPF_ALU) | 22133 BPF_NEG | BPF_K, insn->dst_reg, 22134 0, 0, 0); 22135 *patch++ = BPF_JMP_IMM(BPF_JA, 0, 0, 1); 22136 *patch++ = *insn; 22137 cnt = patch - insn_buf; 22138 } else if (is_smod) { 22139 /* [R,W]x mod 0 -> [R,W]x */ 22140 /* [R,W]x mod -1 -> 0 */ 22141 *patch++ = BPF_MOV64_REG(BPF_REG_AX, insn->src_reg); 22142 *patch++ = BPF_RAW_INSN((is64 ? BPF_ALU64 : BPF_ALU) | 22143 BPF_ADD | BPF_K, BPF_REG_AX, 22144 0, 0, 1); 22145 *patch++ = BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) | 22146 BPF_JGT | BPF_K, BPF_REG_AX, 22147 0, 3, 1); 22148 *patch++ = BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) | 22149 BPF_JEQ | BPF_K, BPF_REG_AX, 22150 0, 3 + (is64 ? 0 : 1), 1); 22151 *patch++ = BPF_MOV32_IMM(insn->dst_reg, 0); 22152 *patch++ = BPF_JMP_IMM(BPF_JA, 0, 0, 1); 22153 *patch++ = *insn; 22154 22155 if (!is64) { 22156 *patch++ = BPF_JMP_IMM(BPF_JA, 0, 0, 1); 22157 *patch++ = BPF_MOV32_REG(insn->dst_reg, insn->dst_reg); 22158 } 22159 cnt = patch - insn_buf; 22160 } else if (isdiv) { 22161 /* [R,W]x div 0 -> 0 */ 22162 *patch++ = BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) | 22163 BPF_JNE | BPF_K, insn->src_reg, 22164 0, 2, 0); 22165 *patch++ = BPF_ALU32_REG(BPF_XOR, insn->dst_reg, insn->dst_reg); 22166 *patch++ = BPF_JMP_IMM(BPF_JA, 0, 0, 1); 22167 *patch++ = *insn; 22168 cnt = patch - insn_buf; 22169 } else { 22170 /* [R,W]x mod 0 -> [R,W]x */ 22171 *patch++ = BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) | 22172 BPF_JEQ | BPF_K, insn->src_reg, 22173 0, 1 + (is64 ? 0 : 1), 0); 22174 *patch++ = *insn; 22175 22176 if (!is64) { 22177 *patch++ = BPF_JMP_IMM(BPF_JA, 0, 0, 1); 22178 *patch++ = BPF_MOV32_REG(insn->dst_reg, insn->dst_reg); 22179 } 22180 cnt = patch - insn_buf; 22181 } 22182 22183 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 22184 if (!new_prog) 22185 return -ENOMEM; 22186 22187 delta += cnt - 1; 22188 env->prog = prog = new_prog; 22189 insn = new_prog->insnsi + i + delta; 22190 goto next_insn; 22191 } 22192 22193 /* Make it impossible to de-reference a userspace address */ 22194 if (BPF_CLASS(insn->code) == BPF_LDX && 22195 (BPF_MODE(insn->code) == BPF_PROBE_MEM || 22196 BPF_MODE(insn->code) == BPF_PROBE_MEMSX)) { 22197 struct bpf_insn *patch = insn_buf; 22198 u64 uaddress_limit = bpf_arch_uaddress_limit(); 22199 22200 if (!uaddress_limit) 22201 goto next_insn; 22202 22203 *patch++ = BPF_MOV64_REG(BPF_REG_AX, insn->src_reg); 22204 if (insn->off) 22205 *patch++ = BPF_ALU64_IMM(BPF_ADD, BPF_REG_AX, insn->off); 22206 *patch++ = BPF_ALU64_IMM(BPF_RSH, BPF_REG_AX, 32); 22207 *patch++ = BPF_JMP_IMM(BPF_JLE, BPF_REG_AX, uaddress_limit >> 32, 2); 22208 *patch++ = *insn; 22209 *patch++ = BPF_JMP_IMM(BPF_JA, 0, 0, 1); 22210 *patch++ = BPF_MOV64_IMM(insn->dst_reg, 0); 22211 22212 cnt = patch - insn_buf; 22213 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 22214 if (!new_prog) 22215 return -ENOMEM; 22216 22217 delta += cnt - 1; 22218 env->prog = prog = new_prog; 22219 insn = new_prog->insnsi + i + delta; 22220 goto next_insn; 22221 } 22222 22223 /* Implement LD_ABS and LD_IND with a rewrite, if supported by the program type. */ 22224 if (BPF_CLASS(insn->code) == BPF_LD && 22225 (BPF_MODE(insn->code) == BPF_ABS || 22226 BPF_MODE(insn->code) == BPF_IND)) { 22227 cnt = env->ops->gen_ld_abs(insn, insn_buf); 22228 if (cnt == 0 || cnt >= INSN_BUF_SIZE) { 22229 verifier_bug(env, "%d insns generated for ld_abs", cnt); 22230 return -EFAULT; 22231 } 22232 22233 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 22234 if (!new_prog) 22235 return -ENOMEM; 22236 22237 delta += cnt - 1; 22238 env->prog = prog = new_prog; 22239 insn = new_prog->insnsi + i + delta; 22240 goto next_insn; 22241 } 22242 22243 /* Rewrite pointer arithmetic to mitigate speculation attacks. */ 22244 if (insn->code == (BPF_ALU64 | BPF_ADD | BPF_X) || 22245 insn->code == (BPF_ALU64 | BPF_SUB | BPF_X)) { 22246 const u8 code_add = BPF_ALU64 | BPF_ADD | BPF_X; 22247 const u8 code_sub = BPF_ALU64 | BPF_SUB | BPF_X; 22248 struct bpf_insn *patch = insn_buf; 22249 bool issrc, isneg, isimm; 22250 u32 off_reg; 22251 22252 aux = &env->insn_aux_data[i + delta]; 22253 if (!aux->alu_state || 22254 aux->alu_state == BPF_ALU_NON_POINTER) 22255 goto next_insn; 22256 22257 isneg = aux->alu_state & BPF_ALU_NEG_VALUE; 22258 issrc = (aux->alu_state & BPF_ALU_SANITIZE) == 22259 BPF_ALU_SANITIZE_SRC; 22260 isimm = aux->alu_state & BPF_ALU_IMMEDIATE; 22261 22262 off_reg = issrc ? insn->src_reg : insn->dst_reg; 22263 if (isimm) { 22264 *patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit); 22265 } else { 22266 if (isneg) 22267 *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1); 22268 *patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit); 22269 *patch++ = BPF_ALU64_REG(BPF_SUB, BPF_REG_AX, off_reg); 22270 *patch++ = BPF_ALU64_REG(BPF_OR, BPF_REG_AX, off_reg); 22271 *patch++ = BPF_ALU64_IMM(BPF_NEG, BPF_REG_AX, 0); 22272 *patch++ = BPF_ALU64_IMM(BPF_ARSH, BPF_REG_AX, 63); 22273 *patch++ = BPF_ALU64_REG(BPF_AND, BPF_REG_AX, off_reg); 22274 } 22275 if (!issrc) 22276 *patch++ = BPF_MOV64_REG(insn->dst_reg, insn->src_reg); 22277 insn->src_reg = BPF_REG_AX; 22278 if (isneg) 22279 insn->code = insn->code == code_add ? 22280 code_sub : code_add; 22281 *patch++ = *insn; 22282 if (issrc && isneg && !isimm) 22283 *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1); 22284 cnt = patch - insn_buf; 22285 22286 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 22287 if (!new_prog) 22288 return -ENOMEM; 22289 22290 delta += cnt - 1; 22291 env->prog = prog = new_prog; 22292 insn = new_prog->insnsi + i + delta; 22293 goto next_insn; 22294 } 22295 22296 if (is_may_goto_insn(insn) && bpf_jit_supports_timed_may_goto()) { 22297 int stack_off_cnt = -stack_depth - 16; 22298 22299 /* 22300 * Two 8 byte slots, depth-16 stores the count, and 22301 * depth-8 stores the start timestamp of the loop. 22302 * 22303 * The starting value of count is BPF_MAX_TIMED_LOOPS 22304 * (0xffff). Every iteration loads it and subs it by 1, 22305 * until the value becomes 0 in AX (thus, 1 in stack), 22306 * after which we call arch_bpf_timed_may_goto, which 22307 * either sets AX to 0xffff to keep looping, or to 0 22308 * upon timeout. AX is then stored into the stack. In 22309 * the next iteration, we either see 0 and break out, or 22310 * continue iterating until the next time value is 0 22311 * after subtraction, rinse and repeat. 22312 */ 22313 stack_depth_extra = 16; 22314 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_AX, BPF_REG_10, stack_off_cnt); 22315 if (insn->off >= 0) 22316 insn_buf[1] = BPF_JMP_IMM(BPF_JEQ, BPF_REG_AX, 0, insn->off + 5); 22317 else 22318 insn_buf[1] = BPF_JMP_IMM(BPF_JEQ, BPF_REG_AX, 0, insn->off - 1); 22319 insn_buf[2] = BPF_ALU64_IMM(BPF_SUB, BPF_REG_AX, 1); 22320 insn_buf[3] = BPF_JMP_IMM(BPF_JNE, BPF_REG_AX, 0, 2); 22321 /* 22322 * AX is used as an argument to pass in stack_off_cnt 22323 * (to add to r10/fp), and also as the return value of 22324 * the call to arch_bpf_timed_may_goto. 22325 */ 22326 insn_buf[4] = BPF_MOV64_IMM(BPF_REG_AX, stack_off_cnt); 22327 insn_buf[5] = BPF_EMIT_CALL(arch_bpf_timed_may_goto); 22328 insn_buf[6] = BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_AX, stack_off_cnt); 22329 cnt = 7; 22330 22331 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 22332 if (!new_prog) 22333 return -ENOMEM; 22334 22335 delta += cnt - 1; 22336 env->prog = prog = new_prog; 22337 insn = new_prog->insnsi + i + delta; 22338 goto next_insn; 22339 } else if (is_may_goto_insn(insn)) { 22340 int stack_off = -stack_depth - 8; 22341 22342 stack_depth_extra = 8; 22343 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_AX, BPF_REG_10, stack_off); 22344 if (insn->off >= 0) 22345 insn_buf[1] = BPF_JMP_IMM(BPF_JEQ, BPF_REG_AX, 0, insn->off + 2); 22346 else 22347 insn_buf[1] = BPF_JMP_IMM(BPF_JEQ, BPF_REG_AX, 0, insn->off - 1); 22348 insn_buf[2] = BPF_ALU64_IMM(BPF_SUB, BPF_REG_AX, 1); 22349 insn_buf[3] = BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_AX, stack_off); 22350 cnt = 4; 22351 22352 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 22353 if (!new_prog) 22354 return -ENOMEM; 22355 22356 delta += cnt - 1; 22357 env->prog = prog = new_prog; 22358 insn = new_prog->insnsi + i + delta; 22359 goto next_insn; 22360 } 22361 22362 if (insn->code != (BPF_JMP | BPF_CALL)) 22363 goto next_insn; 22364 if (insn->src_reg == BPF_PSEUDO_CALL) 22365 goto next_insn; 22366 if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) { 22367 ret = fixup_kfunc_call(env, insn, insn_buf, i + delta, &cnt); 22368 if (ret) 22369 return ret; 22370 if (cnt == 0) 22371 goto next_insn; 22372 22373 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 22374 if (!new_prog) 22375 return -ENOMEM; 22376 22377 delta += cnt - 1; 22378 env->prog = prog = new_prog; 22379 insn = new_prog->insnsi + i + delta; 22380 goto next_insn; 22381 } 22382 22383 /* Skip inlining the helper call if the JIT does it. */ 22384 if (bpf_jit_inlines_helper_call(insn->imm)) 22385 goto next_insn; 22386 22387 if (insn->imm == BPF_FUNC_get_route_realm) 22388 prog->dst_needed = 1; 22389 if (insn->imm == BPF_FUNC_get_prandom_u32) 22390 bpf_user_rnd_init_once(); 22391 if (insn->imm == BPF_FUNC_override_return) 22392 prog->kprobe_override = 1; 22393 if (insn->imm == BPF_FUNC_tail_call) { 22394 /* If we tail call into other programs, we 22395 * cannot make any assumptions since they can 22396 * be replaced dynamically during runtime in 22397 * the program array. 22398 */ 22399 prog->cb_access = 1; 22400 if (!allow_tail_call_in_subprogs(env)) 22401 prog->aux->stack_depth = MAX_BPF_STACK; 22402 prog->aux->max_pkt_offset = MAX_PACKET_OFF; 22403 22404 /* mark bpf_tail_call as different opcode to avoid 22405 * conditional branch in the interpreter for every normal 22406 * call and to prevent accidental JITing by JIT compiler 22407 * that doesn't support bpf_tail_call yet 22408 */ 22409 insn->imm = 0; 22410 insn->code = BPF_JMP | BPF_TAIL_CALL; 22411 22412 aux = &env->insn_aux_data[i + delta]; 22413 if (env->bpf_capable && !prog->blinding_requested && 22414 prog->jit_requested && 22415 !bpf_map_key_poisoned(aux) && 22416 !bpf_map_ptr_poisoned(aux) && 22417 !bpf_map_ptr_unpriv(aux)) { 22418 struct bpf_jit_poke_descriptor desc = { 22419 .reason = BPF_POKE_REASON_TAIL_CALL, 22420 .tail_call.map = aux->map_ptr_state.map_ptr, 22421 .tail_call.key = bpf_map_key_immediate(aux), 22422 .insn_idx = i + delta, 22423 }; 22424 22425 ret = bpf_jit_add_poke_descriptor(prog, &desc); 22426 if (ret < 0) { 22427 verbose(env, "adding tail call poke descriptor failed\n"); 22428 return ret; 22429 } 22430 22431 insn->imm = ret + 1; 22432 goto next_insn; 22433 } 22434 22435 if (!bpf_map_ptr_unpriv(aux)) 22436 goto next_insn; 22437 22438 /* instead of changing every JIT dealing with tail_call 22439 * emit two extra insns: 22440 * if (index >= max_entries) goto out; 22441 * index &= array->index_mask; 22442 * to avoid out-of-bounds cpu speculation 22443 */ 22444 if (bpf_map_ptr_poisoned(aux)) { 22445 verbose(env, "tail_call abusing map_ptr\n"); 22446 return -EINVAL; 22447 } 22448 22449 map_ptr = aux->map_ptr_state.map_ptr; 22450 insn_buf[0] = BPF_JMP_IMM(BPF_JGE, BPF_REG_3, 22451 map_ptr->max_entries, 2); 22452 insn_buf[1] = BPF_ALU32_IMM(BPF_AND, BPF_REG_3, 22453 container_of(map_ptr, 22454 struct bpf_array, 22455 map)->index_mask); 22456 insn_buf[2] = *insn; 22457 cnt = 3; 22458 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 22459 if (!new_prog) 22460 return -ENOMEM; 22461 22462 delta += cnt - 1; 22463 env->prog = prog = new_prog; 22464 insn = new_prog->insnsi + i + delta; 22465 goto next_insn; 22466 } 22467 22468 if (insn->imm == BPF_FUNC_timer_set_callback) { 22469 /* The verifier will process callback_fn as many times as necessary 22470 * with different maps and the register states prepared by 22471 * set_timer_callback_state will be accurate. 22472 * 22473 * The following use case is valid: 22474 * map1 is shared by prog1, prog2, prog3. 22475 * prog1 calls bpf_timer_init for some map1 elements 22476 * prog2 calls bpf_timer_set_callback for some map1 elements. 22477 * Those that were not bpf_timer_init-ed will return -EINVAL. 22478 * prog3 calls bpf_timer_start for some map1 elements. 22479 * Those that were not both bpf_timer_init-ed and 22480 * bpf_timer_set_callback-ed will return -EINVAL. 22481 */ 22482 struct bpf_insn ld_addrs[2] = { 22483 BPF_LD_IMM64(BPF_REG_3, (long)prog->aux), 22484 }; 22485 22486 insn_buf[0] = ld_addrs[0]; 22487 insn_buf[1] = ld_addrs[1]; 22488 insn_buf[2] = *insn; 22489 cnt = 3; 22490 22491 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 22492 if (!new_prog) 22493 return -ENOMEM; 22494 22495 delta += cnt - 1; 22496 env->prog = prog = new_prog; 22497 insn = new_prog->insnsi + i + delta; 22498 goto patch_call_imm; 22499 } 22500 22501 if (is_storage_get_function(insn->imm)) { 22502 if (!in_sleepable(env) || 22503 env->insn_aux_data[i + delta].storage_get_func_atomic) 22504 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_5, (__force __s32)GFP_ATOMIC); 22505 else 22506 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_5, (__force __s32)GFP_KERNEL); 22507 insn_buf[1] = *insn; 22508 cnt = 2; 22509 22510 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 22511 if (!new_prog) 22512 return -ENOMEM; 22513 22514 delta += cnt - 1; 22515 env->prog = prog = new_prog; 22516 insn = new_prog->insnsi + i + delta; 22517 goto patch_call_imm; 22518 } 22519 22520 /* bpf_per_cpu_ptr() and bpf_this_cpu_ptr() */ 22521 if (env->insn_aux_data[i + delta].call_with_percpu_alloc_ptr) { 22522 /* patch with 'r1 = *(u64 *)(r1 + 0)' since for percpu data, 22523 * bpf_mem_alloc() returns a ptr to the percpu data ptr. 22524 */ 22525 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_1, BPF_REG_1, 0); 22526 insn_buf[1] = *insn; 22527 cnt = 2; 22528 22529 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 22530 if (!new_prog) 22531 return -ENOMEM; 22532 22533 delta += cnt - 1; 22534 env->prog = prog = new_prog; 22535 insn = new_prog->insnsi + i + delta; 22536 goto patch_call_imm; 22537 } 22538 22539 /* BPF_EMIT_CALL() assumptions in some of the map_gen_lookup 22540 * and other inlining handlers are currently limited to 64 bit 22541 * only. 22542 */ 22543 if (prog->jit_requested && BITS_PER_LONG == 64 && 22544 (insn->imm == BPF_FUNC_map_lookup_elem || 22545 insn->imm == BPF_FUNC_map_update_elem || 22546 insn->imm == BPF_FUNC_map_delete_elem || 22547 insn->imm == BPF_FUNC_map_push_elem || 22548 insn->imm == BPF_FUNC_map_pop_elem || 22549 insn->imm == BPF_FUNC_map_peek_elem || 22550 insn->imm == BPF_FUNC_redirect_map || 22551 insn->imm == BPF_FUNC_for_each_map_elem || 22552 insn->imm == BPF_FUNC_map_lookup_percpu_elem)) { 22553 aux = &env->insn_aux_data[i + delta]; 22554 if (bpf_map_ptr_poisoned(aux)) 22555 goto patch_call_imm; 22556 22557 map_ptr = aux->map_ptr_state.map_ptr; 22558 ops = map_ptr->ops; 22559 if (insn->imm == BPF_FUNC_map_lookup_elem && 22560 ops->map_gen_lookup) { 22561 cnt = ops->map_gen_lookup(map_ptr, insn_buf); 22562 if (cnt == -EOPNOTSUPP) 22563 goto patch_map_ops_generic; 22564 if (cnt <= 0 || cnt >= INSN_BUF_SIZE) { 22565 verifier_bug(env, "%d insns generated for map lookup", cnt); 22566 return -EFAULT; 22567 } 22568 22569 new_prog = bpf_patch_insn_data(env, i + delta, 22570 insn_buf, cnt); 22571 if (!new_prog) 22572 return -ENOMEM; 22573 22574 delta += cnt - 1; 22575 env->prog = prog = new_prog; 22576 insn = new_prog->insnsi + i + delta; 22577 goto next_insn; 22578 } 22579 22580 BUILD_BUG_ON(!__same_type(ops->map_lookup_elem, 22581 (void *(*)(struct bpf_map *map, void *key))NULL)); 22582 BUILD_BUG_ON(!__same_type(ops->map_delete_elem, 22583 (long (*)(struct bpf_map *map, void *key))NULL)); 22584 BUILD_BUG_ON(!__same_type(ops->map_update_elem, 22585 (long (*)(struct bpf_map *map, void *key, void *value, 22586 u64 flags))NULL)); 22587 BUILD_BUG_ON(!__same_type(ops->map_push_elem, 22588 (long (*)(struct bpf_map *map, void *value, 22589 u64 flags))NULL)); 22590 BUILD_BUG_ON(!__same_type(ops->map_pop_elem, 22591 (long (*)(struct bpf_map *map, void *value))NULL)); 22592 BUILD_BUG_ON(!__same_type(ops->map_peek_elem, 22593 (long (*)(struct bpf_map *map, void *value))NULL)); 22594 BUILD_BUG_ON(!__same_type(ops->map_redirect, 22595 (long (*)(struct bpf_map *map, u64 index, u64 flags))NULL)); 22596 BUILD_BUG_ON(!__same_type(ops->map_for_each_callback, 22597 (long (*)(struct bpf_map *map, 22598 bpf_callback_t callback_fn, 22599 void *callback_ctx, 22600 u64 flags))NULL)); 22601 BUILD_BUG_ON(!__same_type(ops->map_lookup_percpu_elem, 22602 (void *(*)(struct bpf_map *map, void *key, u32 cpu))NULL)); 22603 22604 patch_map_ops_generic: 22605 switch (insn->imm) { 22606 case BPF_FUNC_map_lookup_elem: 22607 insn->imm = BPF_CALL_IMM(ops->map_lookup_elem); 22608 goto next_insn; 22609 case BPF_FUNC_map_update_elem: 22610 insn->imm = BPF_CALL_IMM(ops->map_update_elem); 22611 goto next_insn; 22612 case BPF_FUNC_map_delete_elem: 22613 insn->imm = BPF_CALL_IMM(ops->map_delete_elem); 22614 goto next_insn; 22615 case BPF_FUNC_map_push_elem: 22616 insn->imm = BPF_CALL_IMM(ops->map_push_elem); 22617 goto next_insn; 22618 case BPF_FUNC_map_pop_elem: 22619 insn->imm = BPF_CALL_IMM(ops->map_pop_elem); 22620 goto next_insn; 22621 case BPF_FUNC_map_peek_elem: 22622 insn->imm = BPF_CALL_IMM(ops->map_peek_elem); 22623 goto next_insn; 22624 case BPF_FUNC_redirect_map: 22625 insn->imm = BPF_CALL_IMM(ops->map_redirect); 22626 goto next_insn; 22627 case BPF_FUNC_for_each_map_elem: 22628 insn->imm = BPF_CALL_IMM(ops->map_for_each_callback); 22629 goto next_insn; 22630 case BPF_FUNC_map_lookup_percpu_elem: 22631 insn->imm = BPF_CALL_IMM(ops->map_lookup_percpu_elem); 22632 goto next_insn; 22633 } 22634 22635 goto patch_call_imm; 22636 } 22637 22638 /* Implement bpf_jiffies64 inline. */ 22639 if (prog->jit_requested && BITS_PER_LONG == 64 && 22640 insn->imm == BPF_FUNC_jiffies64) { 22641 struct bpf_insn ld_jiffies_addr[2] = { 22642 BPF_LD_IMM64(BPF_REG_0, 22643 (unsigned long)&jiffies), 22644 }; 22645 22646 insn_buf[0] = ld_jiffies_addr[0]; 22647 insn_buf[1] = ld_jiffies_addr[1]; 22648 insn_buf[2] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, 22649 BPF_REG_0, 0); 22650 cnt = 3; 22651 22652 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 22653 cnt); 22654 if (!new_prog) 22655 return -ENOMEM; 22656 22657 delta += cnt - 1; 22658 env->prog = prog = new_prog; 22659 insn = new_prog->insnsi + i + delta; 22660 goto next_insn; 22661 } 22662 22663 #if defined(CONFIG_X86_64) && !defined(CONFIG_UML) 22664 /* Implement bpf_get_smp_processor_id() inline. */ 22665 if (insn->imm == BPF_FUNC_get_smp_processor_id && 22666 verifier_inlines_helper_call(env, insn->imm)) { 22667 /* BPF_FUNC_get_smp_processor_id inlining is an 22668 * optimization, so if cpu_number is ever 22669 * changed in some incompatible and hard to support 22670 * way, it's fine to back out this inlining logic 22671 */ 22672 #ifdef CONFIG_SMP 22673 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_0, (u32)(unsigned long)&cpu_number); 22674 insn_buf[1] = BPF_MOV64_PERCPU_REG(BPF_REG_0, BPF_REG_0); 22675 insn_buf[2] = BPF_LDX_MEM(BPF_W, BPF_REG_0, BPF_REG_0, 0); 22676 cnt = 3; 22677 #else 22678 insn_buf[0] = BPF_ALU32_REG(BPF_XOR, BPF_REG_0, BPF_REG_0); 22679 cnt = 1; 22680 #endif 22681 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 22682 if (!new_prog) 22683 return -ENOMEM; 22684 22685 delta += cnt - 1; 22686 env->prog = prog = new_prog; 22687 insn = new_prog->insnsi + i + delta; 22688 goto next_insn; 22689 } 22690 #endif 22691 /* Implement bpf_get_func_arg inline. */ 22692 if (prog_type == BPF_PROG_TYPE_TRACING && 22693 insn->imm == BPF_FUNC_get_func_arg) { 22694 /* Load nr_args from ctx - 8 */ 22695 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8); 22696 insn_buf[1] = BPF_JMP32_REG(BPF_JGE, BPF_REG_2, BPF_REG_0, 6); 22697 insn_buf[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_2, 3); 22698 insn_buf[3] = BPF_ALU64_REG(BPF_ADD, BPF_REG_2, BPF_REG_1); 22699 insn_buf[4] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_2, 0); 22700 insn_buf[5] = BPF_STX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0); 22701 insn_buf[6] = BPF_MOV64_IMM(BPF_REG_0, 0); 22702 insn_buf[7] = BPF_JMP_A(1); 22703 insn_buf[8] = BPF_MOV64_IMM(BPF_REG_0, -EINVAL); 22704 cnt = 9; 22705 22706 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 22707 if (!new_prog) 22708 return -ENOMEM; 22709 22710 delta += cnt - 1; 22711 env->prog = prog = new_prog; 22712 insn = new_prog->insnsi + i + delta; 22713 goto next_insn; 22714 } 22715 22716 /* Implement bpf_get_func_ret inline. */ 22717 if (prog_type == BPF_PROG_TYPE_TRACING && 22718 insn->imm == BPF_FUNC_get_func_ret) { 22719 if (eatype == BPF_TRACE_FEXIT || 22720 eatype == BPF_MODIFY_RETURN) { 22721 /* Load nr_args from ctx - 8 */ 22722 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8); 22723 insn_buf[1] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_0, 3); 22724 insn_buf[2] = BPF_ALU64_REG(BPF_ADD, BPF_REG_0, BPF_REG_1); 22725 insn_buf[3] = BPF_LDX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0); 22726 insn_buf[4] = BPF_STX_MEM(BPF_DW, BPF_REG_2, BPF_REG_3, 0); 22727 insn_buf[5] = BPF_MOV64_IMM(BPF_REG_0, 0); 22728 cnt = 6; 22729 } else { 22730 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_0, -EOPNOTSUPP); 22731 cnt = 1; 22732 } 22733 22734 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 22735 if (!new_prog) 22736 return -ENOMEM; 22737 22738 delta += cnt - 1; 22739 env->prog = prog = new_prog; 22740 insn = new_prog->insnsi + i + delta; 22741 goto next_insn; 22742 } 22743 22744 /* Implement get_func_arg_cnt inline. */ 22745 if (prog_type == BPF_PROG_TYPE_TRACING && 22746 insn->imm == BPF_FUNC_get_func_arg_cnt) { 22747 /* Load nr_args from ctx - 8 */ 22748 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8); 22749 22750 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1); 22751 if (!new_prog) 22752 return -ENOMEM; 22753 22754 env->prog = prog = new_prog; 22755 insn = new_prog->insnsi + i + delta; 22756 goto next_insn; 22757 } 22758 22759 /* Implement bpf_get_func_ip inline. */ 22760 if (prog_type == BPF_PROG_TYPE_TRACING && 22761 insn->imm == BPF_FUNC_get_func_ip) { 22762 /* Load IP address from ctx - 16 */ 22763 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -16); 22764 22765 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1); 22766 if (!new_prog) 22767 return -ENOMEM; 22768 22769 env->prog = prog = new_prog; 22770 insn = new_prog->insnsi + i + delta; 22771 goto next_insn; 22772 } 22773 22774 /* Implement bpf_get_branch_snapshot inline. */ 22775 if (IS_ENABLED(CONFIG_PERF_EVENTS) && 22776 prog->jit_requested && BITS_PER_LONG == 64 && 22777 insn->imm == BPF_FUNC_get_branch_snapshot) { 22778 /* We are dealing with the following func protos: 22779 * u64 bpf_get_branch_snapshot(void *buf, u32 size, u64 flags); 22780 * int perf_snapshot_branch_stack(struct perf_branch_entry *entries, u32 cnt); 22781 */ 22782 const u32 br_entry_size = sizeof(struct perf_branch_entry); 22783 22784 /* struct perf_branch_entry is part of UAPI and is 22785 * used as an array element, so extremely unlikely to 22786 * ever grow or shrink 22787 */ 22788 BUILD_BUG_ON(br_entry_size != 24); 22789 22790 /* if (unlikely(flags)) return -EINVAL */ 22791 insn_buf[0] = BPF_JMP_IMM(BPF_JNE, BPF_REG_3, 0, 7); 22792 22793 /* Transform size (bytes) into number of entries (cnt = size / 24). 22794 * But to avoid expensive division instruction, we implement 22795 * divide-by-3 through multiplication, followed by further 22796 * division by 8 through 3-bit right shift. 22797 * Refer to book "Hacker's Delight, 2nd ed." by Henry S. Warren, Jr., 22798 * p. 227, chapter "Unsigned Division by 3" for details and proofs. 22799 * 22800 * N / 3 <=> M * N / 2^33, where M = (2^33 + 1) / 3 = 0xaaaaaaab. 22801 */ 22802 insn_buf[1] = BPF_MOV32_IMM(BPF_REG_0, 0xaaaaaaab); 22803 insn_buf[2] = BPF_ALU64_REG(BPF_MUL, BPF_REG_2, BPF_REG_0); 22804 insn_buf[3] = BPF_ALU64_IMM(BPF_RSH, BPF_REG_2, 36); 22805 22806 /* call perf_snapshot_branch_stack implementation */ 22807 insn_buf[4] = BPF_EMIT_CALL(static_call_query(perf_snapshot_branch_stack)); 22808 /* if (entry_cnt == 0) return -ENOENT */ 22809 insn_buf[5] = BPF_JMP_IMM(BPF_JEQ, BPF_REG_0, 0, 4); 22810 /* return entry_cnt * sizeof(struct perf_branch_entry) */ 22811 insn_buf[6] = BPF_ALU32_IMM(BPF_MUL, BPF_REG_0, br_entry_size); 22812 insn_buf[7] = BPF_JMP_A(3); 22813 /* return -EINVAL; */ 22814 insn_buf[8] = BPF_MOV64_IMM(BPF_REG_0, -EINVAL); 22815 insn_buf[9] = BPF_JMP_A(1); 22816 /* return -ENOENT; */ 22817 insn_buf[10] = BPF_MOV64_IMM(BPF_REG_0, -ENOENT); 22818 cnt = 11; 22819 22820 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 22821 if (!new_prog) 22822 return -ENOMEM; 22823 22824 delta += cnt - 1; 22825 env->prog = prog = new_prog; 22826 insn = new_prog->insnsi + i + delta; 22827 goto next_insn; 22828 } 22829 22830 /* Implement bpf_kptr_xchg inline */ 22831 if (prog->jit_requested && BITS_PER_LONG == 64 && 22832 insn->imm == BPF_FUNC_kptr_xchg && 22833 bpf_jit_supports_ptr_xchg()) { 22834 insn_buf[0] = BPF_MOV64_REG(BPF_REG_0, BPF_REG_2); 22835 insn_buf[1] = BPF_ATOMIC_OP(BPF_DW, BPF_XCHG, BPF_REG_1, BPF_REG_0, 0); 22836 cnt = 2; 22837 22838 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 22839 if (!new_prog) 22840 return -ENOMEM; 22841 22842 delta += cnt - 1; 22843 env->prog = prog = new_prog; 22844 insn = new_prog->insnsi + i + delta; 22845 goto next_insn; 22846 } 22847 patch_call_imm: 22848 fn = env->ops->get_func_proto(insn->imm, env->prog); 22849 /* all functions that have prototype and verifier allowed 22850 * programs to call them, must be real in-kernel functions 22851 */ 22852 if (!fn->func) { 22853 verifier_bug(env, 22854 "not inlined functions %s#%d is missing func", 22855 func_id_name(insn->imm), insn->imm); 22856 return -EFAULT; 22857 } 22858 insn->imm = fn->func - __bpf_call_base; 22859 next_insn: 22860 if (subprogs[cur_subprog + 1].start == i + delta + 1) { 22861 subprogs[cur_subprog].stack_depth += stack_depth_extra; 22862 subprogs[cur_subprog].stack_extra = stack_depth_extra; 22863 22864 stack_depth = subprogs[cur_subprog].stack_depth; 22865 if (stack_depth > MAX_BPF_STACK && !prog->jit_requested) { 22866 verbose(env, "stack size %d(extra %d) is too large\n", 22867 stack_depth, stack_depth_extra); 22868 return -EINVAL; 22869 } 22870 cur_subprog++; 22871 stack_depth = subprogs[cur_subprog].stack_depth; 22872 stack_depth_extra = 0; 22873 } 22874 i++; 22875 insn++; 22876 } 22877 22878 env->prog->aux->stack_depth = subprogs[0].stack_depth; 22879 for (i = 0; i < env->subprog_cnt; i++) { 22880 int delta = bpf_jit_supports_timed_may_goto() ? 2 : 1; 22881 int subprog_start = subprogs[i].start; 22882 int stack_slots = subprogs[i].stack_extra / 8; 22883 int slots = delta, cnt = 0; 22884 22885 if (!stack_slots) 22886 continue; 22887 /* We need two slots in case timed may_goto is supported. */ 22888 if (stack_slots > slots) { 22889 verifier_bug(env, "stack_slots supports may_goto only"); 22890 return -EFAULT; 22891 } 22892 22893 stack_depth = subprogs[i].stack_depth; 22894 if (bpf_jit_supports_timed_may_goto()) { 22895 insn_buf[cnt++] = BPF_ST_MEM(BPF_DW, BPF_REG_FP, -stack_depth, 22896 BPF_MAX_TIMED_LOOPS); 22897 insn_buf[cnt++] = BPF_ST_MEM(BPF_DW, BPF_REG_FP, -stack_depth + 8, 0); 22898 } else { 22899 /* Add ST insn to subprog prologue to init extra stack */ 22900 insn_buf[cnt++] = BPF_ST_MEM(BPF_DW, BPF_REG_FP, -stack_depth, 22901 BPF_MAX_LOOPS); 22902 } 22903 /* Copy first actual insn to preserve it */ 22904 insn_buf[cnt++] = env->prog->insnsi[subprog_start]; 22905 22906 new_prog = bpf_patch_insn_data(env, subprog_start, insn_buf, cnt); 22907 if (!new_prog) 22908 return -ENOMEM; 22909 env->prog = prog = new_prog; 22910 /* 22911 * If may_goto is a first insn of a prog there could be a jmp 22912 * insn that points to it, hence adjust all such jmps to point 22913 * to insn after BPF_ST that inits may_goto count. 22914 * Adjustment will succeed because bpf_patch_insn_data() didn't fail. 22915 */ 22916 WARN_ON(adjust_jmp_off(env->prog, subprog_start, delta)); 22917 } 22918 22919 /* Since poke tab is now finalized, publish aux to tracker. */ 22920 for (i = 0; i < prog->aux->size_poke_tab; i++) { 22921 map_ptr = prog->aux->poke_tab[i].tail_call.map; 22922 if (!map_ptr->ops->map_poke_track || 22923 !map_ptr->ops->map_poke_untrack || 22924 !map_ptr->ops->map_poke_run) { 22925 verifier_bug(env, "poke tab is misconfigured"); 22926 return -EFAULT; 22927 } 22928 22929 ret = map_ptr->ops->map_poke_track(map_ptr, prog->aux); 22930 if (ret < 0) { 22931 verbose(env, "tracking tail call prog failed\n"); 22932 return ret; 22933 } 22934 } 22935 22936 sort_kfunc_descs_by_imm_off(env->prog); 22937 22938 return 0; 22939 } 22940 22941 static struct bpf_prog *inline_bpf_loop(struct bpf_verifier_env *env, 22942 int position, 22943 s32 stack_base, 22944 u32 callback_subprogno, 22945 u32 *total_cnt) 22946 { 22947 s32 r6_offset = stack_base + 0 * BPF_REG_SIZE; 22948 s32 r7_offset = stack_base + 1 * BPF_REG_SIZE; 22949 s32 r8_offset = stack_base + 2 * BPF_REG_SIZE; 22950 int reg_loop_max = BPF_REG_6; 22951 int reg_loop_cnt = BPF_REG_7; 22952 int reg_loop_ctx = BPF_REG_8; 22953 22954 struct bpf_insn *insn_buf = env->insn_buf; 22955 struct bpf_prog *new_prog; 22956 u32 callback_start; 22957 u32 call_insn_offset; 22958 s32 callback_offset; 22959 u32 cnt = 0; 22960 22961 /* This represents an inlined version of bpf_iter.c:bpf_loop, 22962 * be careful to modify this code in sync. 22963 */ 22964 22965 /* Return error and jump to the end of the patch if 22966 * expected number of iterations is too big. 22967 */ 22968 insn_buf[cnt++] = BPF_JMP_IMM(BPF_JLE, BPF_REG_1, BPF_MAX_LOOPS, 2); 22969 insn_buf[cnt++] = BPF_MOV32_IMM(BPF_REG_0, -E2BIG); 22970 insn_buf[cnt++] = BPF_JMP_IMM(BPF_JA, 0, 0, 16); 22971 /* spill R6, R7, R8 to use these as loop vars */ 22972 insn_buf[cnt++] = BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_6, r6_offset); 22973 insn_buf[cnt++] = BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_7, r7_offset); 22974 insn_buf[cnt++] = BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_8, r8_offset); 22975 /* initialize loop vars */ 22976 insn_buf[cnt++] = BPF_MOV64_REG(reg_loop_max, BPF_REG_1); 22977 insn_buf[cnt++] = BPF_MOV32_IMM(reg_loop_cnt, 0); 22978 insn_buf[cnt++] = BPF_MOV64_REG(reg_loop_ctx, BPF_REG_3); 22979 /* loop header, 22980 * if reg_loop_cnt >= reg_loop_max skip the loop body 22981 */ 22982 insn_buf[cnt++] = BPF_JMP_REG(BPF_JGE, reg_loop_cnt, reg_loop_max, 5); 22983 /* callback call, 22984 * correct callback offset would be set after patching 22985 */ 22986 insn_buf[cnt++] = BPF_MOV64_REG(BPF_REG_1, reg_loop_cnt); 22987 insn_buf[cnt++] = BPF_MOV64_REG(BPF_REG_2, reg_loop_ctx); 22988 insn_buf[cnt++] = BPF_CALL_REL(0); 22989 /* increment loop counter */ 22990 insn_buf[cnt++] = BPF_ALU64_IMM(BPF_ADD, reg_loop_cnt, 1); 22991 /* jump to loop header if callback returned 0 */ 22992 insn_buf[cnt++] = BPF_JMP_IMM(BPF_JEQ, BPF_REG_0, 0, -6); 22993 /* return value of bpf_loop, 22994 * set R0 to the number of iterations 22995 */ 22996 insn_buf[cnt++] = BPF_MOV64_REG(BPF_REG_0, reg_loop_cnt); 22997 /* restore original values of R6, R7, R8 */ 22998 insn_buf[cnt++] = BPF_LDX_MEM(BPF_DW, BPF_REG_6, BPF_REG_10, r6_offset); 22999 insn_buf[cnt++] = BPF_LDX_MEM(BPF_DW, BPF_REG_7, BPF_REG_10, r7_offset); 23000 insn_buf[cnt++] = BPF_LDX_MEM(BPF_DW, BPF_REG_8, BPF_REG_10, r8_offset); 23001 23002 *total_cnt = cnt; 23003 new_prog = bpf_patch_insn_data(env, position, insn_buf, cnt); 23004 if (!new_prog) 23005 return new_prog; 23006 23007 /* callback start is known only after patching */ 23008 callback_start = env->subprog_info[callback_subprogno].start; 23009 /* Note: insn_buf[12] is an offset of BPF_CALL_REL instruction */ 23010 call_insn_offset = position + 12; 23011 callback_offset = callback_start - call_insn_offset - 1; 23012 new_prog->insnsi[call_insn_offset].imm = callback_offset; 23013 23014 return new_prog; 23015 } 23016 23017 static bool is_bpf_loop_call(struct bpf_insn *insn) 23018 { 23019 return insn->code == (BPF_JMP | BPF_CALL) && 23020 insn->src_reg == 0 && 23021 insn->imm == BPF_FUNC_loop; 23022 } 23023 23024 /* For all sub-programs in the program (including main) check 23025 * insn_aux_data to see if there are bpf_loop calls that require 23026 * inlining. If such calls are found the calls are replaced with a 23027 * sequence of instructions produced by `inline_bpf_loop` function and 23028 * subprog stack_depth is increased by the size of 3 registers. 23029 * This stack space is used to spill values of the R6, R7, R8. These 23030 * registers are used to store the loop bound, counter and context 23031 * variables. 23032 */ 23033 static int optimize_bpf_loop(struct bpf_verifier_env *env) 23034 { 23035 struct bpf_subprog_info *subprogs = env->subprog_info; 23036 int i, cur_subprog = 0, cnt, delta = 0; 23037 struct bpf_insn *insn = env->prog->insnsi; 23038 int insn_cnt = env->prog->len; 23039 u16 stack_depth = subprogs[cur_subprog].stack_depth; 23040 u16 stack_depth_roundup = round_up(stack_depth, 8) - stack_depth; 23041 u16 stack_depth_extra = 0; 23042 23043 for (i = 0; i < insn_cnt; i++, insn++) { 23044 struct bpf_loop_inline_state *inline_state = 23045 &env->insn_aux_data[i + delta].loop_inline_state; 23046 23047 if (is_bpf_loop_call(insn) && inline_state->fit_for_inline) { 23048 struct bpf_prog *new_prog; 23049 23050 stack_depth_extra = BPF_REG_SIZE * 3 + stack_depth_roundup; 23051 new_prog = inline_bpf_loop(env, 23052 i + delta, 23053 -(stack_depth + stack_depth_extra), 23054 inline_state->callback_subprogno, 23055 &cnt); 23056 if (!new_prog) 23057 return -ENOMEM; 23058 23059 delta += cnt - 1; 23060 env->prog = new_prog; 23061 insn = new_prog->insnsi + i + delta; 23062 } 23063 23064 if (subprogs[cur_subprog + 1].start == i + delta + 1) { 23065 subprogs[cur_subprog].stack_depth += stack_depth_extra; 23066 cur_subprog++; 23067 stack_depth = subprogs[cur_subprog].stack_depth; 23068 stack_depth_roundup = round_up(stack_depth, 8) - stack_depth; 23069 stack_depth_extra = 0; 23070 } 23071 } 23072 23073 env->prog->aux->stack_depth = env->subprog_info[0].stack_depth; 23074 23075 return 0; 23076 } 23077 23078 /* Remove unnecessary spill/fill pairs, members of fastcall pattern, 23079 * adjust subprograms stack depth when possible. 23080 */ 23081 static int remove_fastcall_spills_fills(struct bpf_verifier_env *env) 23082 { 23083 struct bpf_subprog_info *subprog = env->subprog_info; 23084 struct bpf_insn_aux_data *aux = env->insn_aux_data; 23085 struct bpf_insn *insn = env->prog->insnsi; 23086 int insn_cnt = env->prog->len; 23087 u32 spills_num; 23088 bool modified = false; 23089 int i, j; 23090 23091 for (i = 0; i < insn_cnt; i++, insn++) { 23092 if (aux[i].fastcall_spills_num > 0) { 23093 spills_num = aux[i].fastcall_spills_num; 23094 /* NOPs would be removed by opt_remove_nops() */ 23095 for (j = 1; j <= spills_num; ++j) { 23096 *(insn - j) = NOP; 23097 *(insn + j) = NOP; 23098 } 23099 modified = true; 23100 } 23101 if ((subprog + 1)->start == i + 1) { 23102 if (modified && !subprog->keep_fastcall_stack) 23103 subprog->stack_depth = -subprog->fastcall_stack_off; 23104 subprog++; 23105 modified = false; 23106 } 23107 } 23108 23109 return 0; 23110 } 23111 23112 static void free_states(struct bpf_verifier_env *env) 23113 { 23114 struct bpf_verifier_state_list *sl; 23115 struct list_head *head, *pos, *tmp; 23116 struct bpf_scc_info *info; 23117 int i, j; 23118 23119 free_verifier_state(env->cur_state, true); 23120 env->cur_state = NULL; 23121 while (!pop_stack(env, NULL, NULL, false)); 23122 23123 list_for_each_safe(pos, tmp, &env->free_list) { 23124 sl = container_of(pos, struct bpf_verifier_state_list, node); 23125 free_verifier_state(&sl->state, false); 23126 kfree(sl); 23127 } 23128 INIT_LIST_HEAD(&env->free_list); 23129 23130 for (i = 0; i < env->scc_cnt; ++i) { 23131 info = env->scc_info[i]; 23132 if (!info) 23133 continue; 23134 for (j = 0; j < info->num_visits; j++) 23135 free_backedges(&info->visits[j]); 23136 kvfree(info); 23137 env->scc_info[i] = NULL; 23138 } 23139 23140 if (!env->explored_states) 23141 return; 23142 23143 for (i = 0; i < state_htab_size(env); i++) { 23144 head = &env->explored_states[i]; 23145 23146 list_for_each_safe(pos, tmp, head) { 23147 sl = container_of(pos, struct bpf_verifier_state_list, node); 23148 free_verifier_state(&sl->state, false); 23149 kfree(sl); 23150 } 23151 INIT_LIST_HEAD(&env->explored_states[i]); 23152 } 23153 } 23154 23155 static int do_check_common(struct bpf_verifier_env *env, int subprog) 23156 { 23157 bool pop_log = !(env->log.level & BPF_LOG_LEVEL2); 23158 struct bpf_subprog_info *sub = subprog_info(env, subprog); 23159 struct bpf_prog_aux *aux = env->prog->aux; 23160 struct bpf_verifier_state *state; 23161 struct bpf_reg_state *regs; 23162 int ret, i; 23163 23164 env->prev_linfo = NULL; 23165 env->pass_cnt++; 23166 23167 state = kzalloc(sizeof(struct bpf_verifier_state), GFP_KERNEL_ACCOUNT); 23168 if (!state) 23169 return -ENOMEM; 23170 state->curframe = 0; 23171 state->speculative = false; 23172 state->branches = 1; 23173 state->frame[0] = kzalloc(sizeof(struct bpf_func_state), GFP_KERNEL_ACCOUNT); 23174 if (!state->frame[0]) { 23175 kfree(state); 23176 return -ENOMEM; 23177 } 23178 env->cur_state = state; 23179 init_func_state(env, state->frame[0], 23180 BPF_MAIN_FUNC /* callsite */, 23181 0 /* frameno */, 23182 subprog); 23183 state->first_insn_idx = env->subprog_info[subprog].start; 23184 state->last_insn_idx = -1; 23185 23186 regs = state->frame[state->curframe]->regs; 23187 if (subprog || env->prog->type == BPF_PROG_TYPE_EXT) { 23188 const char *sub_name = subprog_name(env, subprog); 23189 struct bpf_subprog_arg_info *arg; 23190 struct bpf_reg_state *reg; 23191 23192 verbose(env, "Validating %s() func#%d...\n", sub_name, subprog); 23193 ret = btf_prepare_func_args(env, subprog); 23194 if (ret) 23195 goto out; 23196 23197 if (subprog_is_exc_cb(env, subprog)) { 23198 state->frame[0]->in_exception_callback_fn = true; 23199 /* We have already ensured that the callback returns an integer, just 23200 * like all global subprogs. We need to determine it only has a single 23201 * scalar argument. 23202 */ 23203 if (sub->arg_cnt != 1 || sub->args[0].arg_type != ARG_ANYTHING) { 23204 verbose(env, "exception cb only supports single integer argument\n"); 23205 ret = -EINVAL; 23206 goto out; 23207 } 23208 } 23209 for (i = BPF_REG_1; i <= sub->arg_cnt; i++) { 23210 arg = &sub->args[i - BPF_REG_1]; 23211 reg = ®s[i]; 23212 23213 if (arg->arg_type == ARG_PTR_TO_CTX) { 23214 reg->type = PTR_TO_CTX; 23215 mark_reg_known_zero(env, regs, i); 23216 } else if (arg->arg_type == ARG_ANYTHING) { 23217 reg->type = SCALAR_VALUE; 23218 mark_reg_unknown(env, regs, i); 23219 } else if (arg->arg_type == (ARG_PTR_TO_DYNPTR | MEM_RDONLY)) { 23220 /* assume unspecial LOCAL dynptr type */ 23221 __mark_dynptr_reg(reg, BPF_DYNPTR_TYPE_LOCAL, true, ++env->id_gen); 23222 } else if (base_type(arg->arg_type) == ARG_PTR_TO_MEM) { 23223 reg->type = PTR_TO_MEM; 23224 reg->type |= arg->arg_type & 23225 (PTR_MAYBE_NULL | PTR_UNTRUSTED | MEM_RDONLY); 23226 mark_reg_known_zero(env, regs, i); 23227 reg->mem_size = arg->mem_size; 23228 if (arg->arg_type & PTR_MAYBE_NULL) 23229 reg->id = ++env->id_gen; 23230 } else if (base_type(arg->arg_type) == ARG_PTR_TO_BTF_ID) { 23231 reg->type = PTR_TO_BTF_ID; 23232 if (arg->arg_type & PTR_MAYBE_NULL) 23233 reg->type |= PTR_MAYBE_NULL; 23234 if (arg->arg_type & PTR_UNTRUSTED) 23235 reg->type |= PTR_UNTRUSTED; 23236 if (arg->arg_type & PTR_TRUSTED) 23237 reg->type |= PTR_TRUSTED; 23238 mark_reg_known_zero(env, regs, i); 23239 reg->btf = bpf_get_btf_vmlinux(); /* can't fail at this point */ 23240 reg->btf_id = arg->btf_id; 23241 reg->id = ++env->id_gen; 23242 } else if (base_type(arg->arg_type) == ARG_PTR_TO_ARENA) { 23243 /* caller can pass either PTR_TO_ARENA or SCALAR */ 23244 mark_reg_unknown(env, regs, i); 23245 } else { 23246 verifier_bug(env, "unhandled arg#%d type %d", 23247 i - BPF_REG_1, arg->arg_type); 23248 ret = -EFAULT; 23249 goto out; 23250 } 23251 } 23252 } else { 23253 /* if main BPF program has associated BTF info, validate that 23254 * it's matching expected signature, and otherwise mark BTF 23255 * info for main program as unreliable 23256 */ 23257 if (env->prog->aux->func_info_aux) { 23258 ret = btf_prepare_func_args(env, 0); 23259 if (ret || sub->arg_cnt != 1 || sub->args[0].arg_type != ARG_PTR_TO_CTX) 23260 env->prog->aux->func_info_aux[0].unreliable = true; 23261 } 23262 23263 /* 1st arg to a function */ 23264 regs[BPF_REG_1].type = PTR_TO_CTX; 23265 mark_reg_known_zero(env, regs, BPF_REG_1); 23266 } 23267 23268 /* Acquire references for struct_ops program arguments tagged with "__ref" */ 23269 if (!subprog && env->prog->type == BPF_PROG_TYPE_STRUCT_OPS) { 23270 for (i = 0; i < aux->ctx_arg_info_size; i++) 23271 aux->ctx_arg_info[i].ref_obj_id = aux->ctx_arg_info[i].refcounted ? 23272 acquire_reference(env, 0) : 0; 23273 } 23274 23275 ret = do_check(env); 23276 out: 23277 if (!ret && pop_log) 23278 bpf_vlog_reset(&env->log, 0); 23279 free_states(env); 23280 return ret; 23281 } 23282 23283 /* Lazily verify all global functions based on their BTF, if they are called 23284 * from main BPF program or any of subprograms transitively. 23285 * BPF global subprogs called from dead code are not validated. 23286 * All callable global functions must pass verification. 23287 * Otherwise the whole program is rejected. 23288 * Consider: 23289 * int bar(int); 23290 * int foo(int f) 23291 * { 23292 * return bar(f); 23293 * } 23294 * int bar(int b) 23295 * { 23296 * ... 23297 * } 23298 * foo() will be verified first for R1=any_scalar_value. During verification it 23299 * will be assumed that bar() already verified successfully and call to bar() 23300 * from foo() will be checked for type match only. Later bar() will be verified 23301 * independently to check that it's safe for R1=any_scalar_value. 23302 */ 23303 static int do_check_subprogs(struct bpf_verifier_env *env) 23304 { 23305 struct bpf_prog_aux *aux = env->prog->aux; 23306 struct bpf_func_info_aux *sub_aux; 23307 int i, ret, new_cnt; 23308 23309 if (!aux->func_info) 23310 return 0; 23311 23312 /* exception callback is presumed to be always called */ 23313 if (env->exception_callback_subprog) 23314 subprog_aux(env, env->exception_callback_subprog)->called = true; 23315 23316 again: 23317 new_cnt = 0; 23318 for (i = 1; i < env->subprog_cnt; i++) { 23319 if (!subprog_is_global(env, i)) 23320 continue; 23321 23322 sub_aux = subprog_aux(env, i); 23323 if (!sub_aux->called || sub_aux->verified) 23324 continue; 23325 23326 env->insn_idx = env->subprog_info[i].start; 23327 WARN_ON_ONCE(env->insn_idx == 0); 23328 ret = do_check_common(env, i); 23329 if (ret) { 23330 return ret; 23331 } else if (env->log.level & BPF_LOG_LEVEL) { 23332 verbose(env, "Func#%d ('%s') is safe for any args that match its prototype\n", 23333 i, subprog_name(env, i)); 23334 } 23335 23336 /* We verified new global subprog, it might have called some 23337 * more global subprogs that we haven't verified yet, so we 23338 * need to do another pass over subprogs to verify those. 23339 */ 23340 sub_aux->verified = true; 23341 new_cnt++; 23342 } 23343 23344 /* We can't loop forever as we verify at least one global subprog on 23345 * each pass. 23346 */ 23347 if (new_cnt) 23348 goto again; 23349 23350 return 0; 23351 } 23352 23353 static int do_check_main(struct bpf_verifier_env *env) 23354 { 23355 int ret; 23356 23357 env->insn_idx = 0; 23358 ret = do_check_common(env, 0); 23359 if (!ret) 23360 env->prog->aux->stack_depth = env->subprog_info[0].stack_depth; 23361 return ret; 23362 } 23363 23364 23365 static void print_verification_stats(struct bpf_verifier_env *env) 23366 { 23367 int i; 23368 23369 if (env->log.level & BPF_LOG_STATS) { 23370 verbose(env, "verification time %lld usec\n", 23371 div_u64(env->verification_time, 1000)); 23372 verbose(env, "stack depth "); 23373 for (i = 0; i < env->subprog_cnt; i++) { 23374 u32 depth = env->subprog_info[i].stack_depth; 23375 23376 verbose(env, "%d", depth); 23377 if (i + 1 < env->subprog_cnt) 23378 verbose(env, "+"); 23379 } 23380 verbose(env, "\n"); 23381 } 23382 verbose(env, "processed %d insns (limit %d) max_states_per_insn %d " 23383 "total_states %d peak_states %d mark_read %d\n", 23384 env->insn_processed, BPF_COMPLEXITY_LIMIT_INSNS, 23385 env->max_states_per_insn, env->total_states, 23386 env->peak_states, env->longest_mark_read_walk); 23387 } 23388 23389 int bpf_prog_ctx_arg_info_init(struct bpf_prog *prog, 23390 const struct bpf_ctx_arg_aux *info, u32 cnt) 23391 { 23392 prog->aux->ctx_arg_info = kmemdup_array(info, cnt, sizeof(*info), GFP_KERNEL_ACCOUNT); 23393 prog->aux->ctx_arg_info_size = cnt; 23394 23395 return prog->aux->ctx_arg_info ? 0 : -ENOMEM; 23396 } 23397 23398 static int check_struct_ops_btf_id(struct bpf_verifier_env *env) 23399 { 23400 const struct btf_type *t, *func_proto; 23401 const struct bpf_struct_ops_desc *st_ops_desc; 23402 const struct bpf_struct_ops *st_ops; 23403 const struct btf_member *member; 23404 struct bpf_prog *prog = env->prog; 23405 bool has_refcounted_arg = false; 23406 u32 btf_id, member_idx, member_off; 23407 struct btf *btf; 23408 const char *mname; 23409 int i, err; 23410 23411 if (!prog->gpl_compatible) { 23412 verbose(env, "struct ops programs must have a GPL compatible license\n"); 23413 return -EINVAL; 23414 } 23415 23416 if (!prog->aux->attach_btf_id) 23417 return -ENOTSUPP; 23418 23419 btf = prog->aux->attach_btf; 23420 if (btf_is_module(btf)) { 23421 /* Make sure st_ops is valid through the lifetime of env */ 23422 env->attach_btf_mod = btf_try_get_module(btf); 23423 if (!env->attach_btf_mod) { 23424 verbose(env, "struct_ops module %s is not found\n", 23425 btf_get_name(btf)); 23426 return -ENOTSUPP; 23427 } 23428 } 23429 23430 btf_id = prog->aux->attach_btf_id; 23431 st_ops_desc = bpf_struct_ops_find(btf, btf_id); 23432 if (!st_ops_desc) { 23433 verbose(env, "attach_btf_id %u is not a supported struct\n", 23434 btf_id); 23435 return -ENOTSUPP; 23436 } 23437 st_ops = st_ops_desc->st_ops; 23438 23439 t = st_ops_desc->type; 23440 member_idx = prog->expected_attach_type; 23441 if (member_idx >= btf_type_vlen(t)) { 23442 verbose(env, "attach to invalid member idx %u of struct %s\n", 23443 member_idx, st_ops->name); 23444 return -EINVAL; 23445 } 23446 23447 member = &btf_type_member(t)[member_idx]; 23448 mname = btf_name_by_offset(btf, member->name_off); 23449 func_proto = btf_type_resolve_func_ptr(btf, member->type, 23450 NULL); 23451 if (!func_proto) { 23452 verbose(env, "attach to invalid member %s(@idx %u) of struct %s\n", 23453 mname, member_idx, st_ops->name); 23454 return -EINVAL; 23455 } 23456 23457 member_off = __btf_member_bit_offset(t, member) / 8; 23458 err = bpf_struct_ops_supported(st_ops, member_off); 23459 if (err) { 23460 verbose(env, "attach to unsupported member %s of struct %s\n", 23461 mname, st_ops->name); 23462 return err; 23463 } 23464 23465 if (st_ops->check_member) { 23466 err = st_ops->check_member(t, member, prog); 23467 23468 if (err) { 23469 verbose(env, "attach to unsupported member %s of struct %s\n", 23470 mname, st_ops->name); 23471 return err; 23472 } 23473 } 23474 23475 if (prog->aux->priv_stack_requested && !bpf_jit_supports_private_stack()) { 23476 verbose(env, "Private stack not supported by jit\n"); 23477 return -EACCES; 23478 } 23479 23480 for (i = 0; i < st_ops_desc->arg_info[member_idx].cnt; i++) { 23481 if (st_ops_desc->arg_info[member_idx].info->refcounted) { 23482 has_refcounted_arg = true; 23483 break; 23484 } 23485 } 23486 23487 /* Tail call is not allowed for programs with refcounted arguments since we 23488 * cannot guarantee that valid refcounted kptrs will be passed to the callee. 23489 */ 23490 for (i = 0; i < env->subprog_cnt; i++) { 23491 if (has_refcounted_arg && env->subprog_info[i].has_tail_call) { 23492 verbose(env, "program with __ref argument cannot tail call\n"); 23493 return -EINVAL; 23494 } 23495 } 23496 23497 prog->aux->st_ops = st_ops; 23498 prog->aux->attach_st_ops_member_off = member_off; 23499 23500 prog->aux->attach_func_proto = func_proto; 23501 prog->aux->attach_func_name = mname; 23502 env->ops = st_ops->verifier_ops; 23503 23504 return bpf_prog_ctx_arg_info_init(prog, st_ops_desc->arg_info[member_idx].info, 23505 st_ops_desc->arg_info[member_idx].cnt); 23506 } 23507 #define SECURITY_PREFIX "security_" 23508 23509 static int check_attach_modify_return(unsigned long addr, const char *func_name) 23510 { 23511 if (within_error_injection_list(addr) || 23512 !strncmp(SECURITY_PREFIX, func_name, sizeof(SECURITY_PREFIX) - 1)) 23513 return 0; 23514 23515 return -EINVAL; 23516 } 23517 23518 /* list of non-sleepable functions that are otherwise on 23519 * ALLOW_ERROR_INJECTION list 23520 */ 23521 BTF_SET_START(btf_non_sleepable_error_inject) 23522 /* Three functions below can be called from sleepable and non-sleepable context. 23523 * Assume non-sleepable from bpf safety point of view. 23524 */ 23525 BTF_ID(func, __filemap_add_folio) 23526 #ifdef CONFIG_FAIL_PAGE_ALLOC 23527 BTF_ID(func, should_fail_alloc_page) 23528 #endif 23529 #ifdef CONFIG_FAILSLAB 23530 BTF_ID(func, should_failslab) 23531 #endif 23532 BTF_SET_END(btf_non_sleepable_error_inject) 23533 23534 static int check_non_sleepable_error_inject(u32 btf_id) 23535 { 23536 return btf_id_set_contains(&btf_non_sleepable_error_inject, btf_id); 23537 } 23538 23539 int bpf_check_attach_target(struct bpf_verifier_log *log, 23540 const struct bpf_prog *prog, 23541 const struct bpf_prog *tgt_prog, 23542 u32 btf_id, 23543 struct bpf_attach_target_info *tgt_info) 23544 { 23545 bool prog_extension = prog->type == BPF_PROG_TYPE_EXT; 23546 bool prog_tracing = prog->type == BPF_PROG_TYPE_TRACING; 23547 char trace_symbol[KSYM_SYMBOL_LEN]; 23548 const char prefix[] = "btf_trace_"; 23549 struct bpf_raw_event_map *btp; 23550 int ret = 0, subprog = -1, i; 23551 const struct btf_type *t; 23552 bool conservative = true; 23553 const char *tname, *fname; 23554 struct btf *btf; 23555 long addr = 0; 23556 struct module *mod = NULL; 23557 23558 if (!btf_id) { 23559 bpf_log(log, "Tracing programs must provide btf_id\n"); 23560 return -EINVAL; 23561 } 23562 btf = tgt_prog ? tgt_prog->aux->btf : prog->aux->attach_btf; 23563 if (!btf) { 23564 bpf_log(log, 23565 "FENTRY/FEXIT program can only be attached to another program annotated with BTF\n"); 23566 return -EINVAL; 23567 } 23568 t = btf_type_by_id(btf, btf_id); 23569 if (!t) { 23570 bpf_log(log, "attach_btf_id %u is invalid\n", btf_id); 23571 return -EINVAL; 23572 } 23573 tname = btf_name_by_offset(btf, t->name_off); 23574 if (!tname) { 23575 bpf_log(log, "attach_btf_id %u doesn't have a name\n", btf_id); 23576 return -EINVAL; 23577 } 23578 if (tgt_prog) { 23579 struct bpf_prog_aux *aux = tgt_prog->aux; 23580 bool tgt_changes_pkt_data; 23581 bool tgt_might_sleep; 23582 23583 if (bpf_prog_is_dev_bound(prog->aux) && 23584 !bpf_prog_dev_bound_match(prog, tgt_prog)) { 23585 bpf_log(log, "Target program bound device mismatch"); 23586 return -EINVAL; 23587 } 23588 23589 for (i = 0; i < aux->func_info_cnt; i++) 23590 if (aux->func_info[i].type_id == btf_id) { 23591 subprog = i; 23592 break; 23593 } 23594 if (subprog == -1) { 23595 bpf_log(log, "Subprog %s doesn't exist\n", tname); 23596 return -EINVAL; 23597 } 23598 if (aux->func && aux->func[subprog]->aux->exception_cb) { 23599 bpf_log(log, 23600 "%s programs cannot attach to exception callback\n", 23601 prog_extension ? "Extension" : "FENTRY/FEXIT"); 23602 return -EINVAL; 23603 } 23604 conservative = aux->func_info_aux[subprog].unreliable; 23605 if (prog_extension) { 23606 if (conservative) { 23607 bpf_log(log, 23608 "Cannot replace static functions\n"); 23609 return -EINVAL; 23610 } 23611 if (!prog->jit_requested) { 23612 bpf_log(log, 23613 "Extension programs should be JITed\n"); 23614 return -EINVAL; 23615 } 23616 tgt_changes_pkt_data = aux->func 23617 ? aux->func[subprog]->aux->changes_pkt_data 23618 : aux->changes_pkt_data; 23619 if (prog->aux->changes_pkt_data && !tgt_changes_pkt_data) { 23620 bpf_log(log, 23621 "Extension program changes packet data, while original does not\n"); 23622 return -EINVAL; 23623 } 23624 23625 tgt_might_sleep = aux->func 23626 ? aux->func[subprog]->aux->might_sleep 23627 : aux->might_sleep; 23628 if (prog->aux->might_sleep && !tgt_might_sleep) { 23629 bpf_log(log, 23630 "Extension program may sleep, while original does not\n"); 23631 return -EINVAL; 23632 } 23633 } 23634 if (!tgt_prog->jited) { 23635 bpf_log(log, "Can attach to only JITed progs\n"); 23636 return -EINVAL; 23637 } 23638 if (prog_tracing) { 23639 if (aux->attach_tracing_prog) { 23640 /* 23641 * Target program is an fentry/fexit which is already attached 23642 * to another tracing program. More levels of nesting 23643 * attachment are not allowed. 23644 */ 23645 bpf_log(log, "Cannot nest tracing program attach more than once\n"); 23646 return -EINVAL; 23647 } 23648 } else if (tgt_prog->type == prog->type) { 23649 /* 23650 * To avoid potential call chain cycles, prevent attaching of a 23651 * program extension to another extension. It's ok to attach 23652 * fentry/fexit to extension program. 23653 */ 23654 bpf_log(log, "Cannot recursively attach\n"); 23655 return -EINVAL; 23656 } 23657 if (tgt_prog->type == BPF_PROG_TYPE_TRACING && 23658 prog_extension && 23659 (tgt_prog->expected_attach_type == BPF_TRACE_FENTRY || 23660 tgt_prog->expected_attach_type == BPF_TRACE_FEXIT)) { 23661 /* Program extensions can extend all program types 23662 * except fentry/fexit. The reason is the following. 23663 * The fentry/fexit programs are used for performance 23664 * analysis, stats and can be attached to any program 23665 * type. When extension program is replacing XDP function 23666 * it is necessary to allow performance analysis of all 23667 * functions. Both original XDP program and its program 23668 * extension. Hence attaching fentry/fexit to 23669 * BPF_PROG_TYPE_EXT is allowed. If extending of 23670 * fentry/fexit was allowed it would be possible to create 23671 * long call chain fentry->extension->fentry->extension 23672 * beyond reasonable stack size. Hence extending fentry 23673 * is not allowed. 23674 */ 23675 bpf_log(log, "Cannot extend fentry/fexit\n"); 23676 return -EINVAL; 23677 } 23678 } else { 23679 if (prog_extension) { 23680 bpf_log(log, "Cannot replace kernel functions\n"); 23681 return -EINVAL; 23682 } 23683 } 23684 23685 switch (prog->expected_attach_type) { 23686 case BPF_TRACE_RAW_TP: 23687 if (tgt_prog) { 23688 bpf_log(log, 23689 "Only FENTRY/FEXIT progs are attachable to another BPF prog\n"); 23690 return -EINVAL; 23691 } 23692 if (!btf_type_is_typedef(t)) { 23693 bpf_log(log, "attach_btf_id %u is not a typedef\n", 23694 btf_id); 23695 return -EINVAL; 23696 } 23697 if (strncmp(prefix, tname, sizeof(prefix) - 1)) { 23698 bpf_log(log, "attach_btf_id %u points to wrong type name %s\n", 23699 btf_id, tname); 23700 return -EINVAL; 23701 } 23702 tname += sizeof(prefix) - 1; 23703 23704 /* The func_proto of "btf_trace_##tname" is generated from typedef without argument 23705 * names. Thus using bpf_raw_event_map to get argument names. 23706 */ 23707 btp = bpf_get_raw_tracepoint(tname); 23708 if (!btp) 23709 return -EINVAL; 23710 fname = kallsyms_lookup((unsigned long)btp->bpf_func, NULL, NULL, NULL, 23711 trace_symbol); 23712 bpf_put_raw_tracepoint(btp); 23713 23714 if (fname) 23715 ret = btf_find_by_name_kind(btf, fname, BTF_KIND_FUNC); 23716 23717 if (!fname || ret < 0) { 23718 bpf_log(log, "Cannot find btf of tracepoint template, fall back to %s%s.\n", 23719 prefix, tname); 23720 t = btf_type_by_id(btf, t->type); 23721 if (!btf_type_is_ptr(t)) 23722 /* should never happen in valid vmlinux build */ 23723 return -EINVAL; 23724 } else { 23725 t = btf_type_by_id(btf, ret); 23726 if (!btf_type_is_func(t)) 23727 /* should never happen in valid vmlinux build */ 23728 return -EINVAL; 23729 } 23730 23731 t = btf_type_by_id(btf, t->type); 23732 if (!btf_type_is_func_proto(t)) 23733 /* should never happen in valid vmlinux build */ 23734 return -EINVAL; 23735 23736 break; 23737 case BPF_TRACE_ITER: 23738 if (!btf_type_is_func(t)) { 23739 bpf_log(log, "attach_btf_id %u is not a function\n", 23740 btf_id); 23741 return -EINVAL; 23742 } 23743 t = btf_type_by_id(btf, t->type); 23744 if (!btf_type_is_func_proto(t)) 23745 return -EINVAL; 23746 ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel); 23747 if (ret) 23748 return ret; 23749 break; 23750 default: 23751 if (!prog_extension) 23752 return -EINVAL; 23753 fallthrough; 23754 case BPF_MODIFY_RETURN: 23755 case BPF_LSM_MAC: 23756 case BPF_LSM_CGROUP: 23757 case BPF_TRACE_FENTRY: 23758 case BPF_TRACE_FEXIT: 23759 if (!btf_type_is_func(t)) { 23760 bpf_log(log, "attach_btf_id %u is not a function\n", 23761 btf_id); 23762 return -EINVAL; 23763 } 23764 if (prog_extension && 23765 btf_check_type_match(log, prog, btf, t)) 23766 return -EINVAL; 23767 t = btf_type_by_id(btf, t->type); 23768 if (!btf_type_is_func_proto(t)) 23769 return -EINVAL; 23770 23771 if ((prog->aux->saved_dst_prog_type || prog->aux->saved_dst_attach_type) && 23772 (!tgt_prog || prog->aux->saved_dst_prog_type != tgt_prog->type || 23773 prog->aux->saved_dst_attach_type != tgt_prog->expected_attach_type)) 23774 return -EINVAL; 23775 23776 if (tgt_prog && conservative) 23777 t = NULL; 23778 23779 ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel); 23780 if (ret < 0) 23781 return ret; 23782 23783 if (tgt_prog) { 23784 if (subprog == 0) 23785 addr = (long) tgt_prog->bpf_func; 23786 else 23787 addr = (long) tgt_prog->aux->func[subprog]->bpf_func; 23788 } else { 23789 if (btf_is_module(btf)) { 23790 mod = btf_try_get_module(btf); 23791 if (mod) 23792 addr = find_kallsyms_symbol_value(mod, tname); 23793 else 23794 addr = 0; 23795 } else { 23796 addr = kallsyms_lookup_name(tname); 23797 } 23798 if (!addr) { 23799 module_put(mod); 23800 bpf_log(log, 23801 "The address of function %s cannot be found\n", 23802 tname); 23803 return -ENOENT; 23804 } 23805 } 23806 23807 if (prog->sleepable) { 23808 ret = -EINVAL; 23809 switch (prog->type) { 23810 case BPF_PROG_TYPE_TRACING: 23811 23812 /* fentry/fexit/fmod_ret progs can be sleepable if they are 23813 * attached to ALLOW_ERROR_INJECTION and are not in denylist. 23814 */ 23815 if (!check_non_sleepable_error_inject(btf_id) && 23816 within_error_injection_list(addr)) 23817 ret = 0; 23818 /* fentry/fexit/fmod_ret progs can also be sleepable if they are 23819 * in the fmodret id set with the KF_SLEEPABLE flag. 23820 */ 23821 else { 23822 u32 *flags = btf_kfunc_is_modify_return(btf, btf_id, 23823 prog); 23824 23825 if (flags && (*flags & KF_SLEEPABLE)) 23826 ret = 0; 23827 } 23828 break; 23829 case BPF_PROG_TYPE_LSM: 23830 /* LSM progs check that they are attached to bpf_lsm_*() funcs. 23831 * Only some of them are sleepable. 23832 */ 23833 if (bpf_lsm_is_sleepable_hook(btf_id)) 23834 ret = 0; 23835 break; 23836 default: 23837 break; 23838 } 23839 if (ret) { 23840 module_put(mod); 23841 bpf_log(log, "%s is not sleepable\n", tname); 23842 return ret; 23843 } 23844 } else if (prog->expected_attach_type == BPF_MODIFY_RETURN) { 23845 if (tgt_prog) { 23846 module_put(mod); 23847 bpf_log(log, "can't modify return codes of BPF programs\n"); 23848 return -EINVAL; 23849 } 23850 ret = -EINVAL; 23851 if (btf_kfunc_is_modify_return(btf, btf_id, prog) || 23852 !check_attach_modify_return(addr, tname)) 23853 ret = 0; 23854 if (ret) { 23855 module_put(mod); 23856 bpf_log(log, "%s() is not modifiable\n", tname); 23857 return ret; 23858 } 23859 } 23860 23861 break; 23862 } 23863 tgt_info->tgt_addr = addr; 23864 tgt_info->tgt_name = tname; 23865 tgt_info->tgt_type = t; 23866 tgt_info->tgt_mod = mod; 23867 return 0; 23868 } 23869 23870 BTF_SET_START(btf_id_deny) 23871 BTF_ID_UNUSED 23872 #ifdef CONFIG_SMP 23873 BTF_ID(func, migrate_disable) 23874 BTF_ID(func, migrate_enable) 23875 #endif 23876 #if !defined CONFIG_PREEMPT_RCU && !defined CONFIG_TINY_RCU 23877 BTF_ID(func, rcu_read_unlock_strict) 23878 #endif 23879 #if defined(CONFIG_DEBUG_PREEMPT) || defined(CONFIG_TRACE_PREEMPT_TOGGLE) 23880 BTF_ID(func, preempt_count_add) 23881 BTF_ID(func, preempt_count_sub) 23882 #endif 23883 #ifdef CONFIG_PREEMPT_RCU 23884 BTF_ID(func, __rcu_read_lock) 23885 BTF_ID(func, __rcu_read_unlock) 23886 #endif 23887 BTF_SET_END(btf_id_deny) 23888 23889 /* fexit and fmod_ret can't be used to attach to __noreturn functions. 23890 * Currently, we must manually list all __noreturn functions here. Once a more 23891 * robust solution is implemented, this workaround can be removed. 23892 */ 23893 BTF_SET_START(noreturn_deny) 23894 #ifdef CONFIG_IA32_EMULATION 23895 BTF_ID(func, __ia32_sys_exit) 23896 BTF_ID(func, __ia32_sys_exit_group) 23897 #endif 23898 #ifdef CONFIG_KUNIT 23899 BTF_ID(func, __kunit_abort) 23900 BTF_ID(func, kunit_try_catch_throw) 23901 #endif 23902 #ifdef CONFIG_MODULES 23903 BTF_ID(func, __module_put_and_kthread_exit) 23904 #endif 23905 #ifdef CONFIG_X86_64 23906 BTF_ID(func, __x64_sys_exit) 23907 BTF_ID(func, __x64_sys_exit_group) 23908 #endif 23909 BTF_ID(func, do_exit) 23910 BTF_ID(func, do_group_exit) 23911 BTF_ID(func, kthread_complete_and_exit) 23912 BTF_ID(func, kthread_exit) 23913 BTF_ID(func, make_task_dead) 23914 BTF_SET_END(noreturn_deny) 23915 23916 static bool can_be_sleepable(struct bpf_prog *prog) 23917 { 23918 if (prog->type == BPF_PROG_TYPE_TRACING) { 23919 switch (prog->expected_attach_type) { 23920 case BPF_TRACE_FENTRY: 23921 case BPF_TRACE_FEXIT: 23922 case BPF_MODIFY_RETURN: 23923 case BPF_TRACE_ITER: 23924 return true; 23925 default: 23926 return false; 23927 } 23928 } 23929 return prog->type == BPF_PROG_TYPE_LSM || 23930 prog->type == BPF_PROG_TYPE_KPROBE /* only for uprobes */ || 23931 prog->type == BPF_PROG_TYPE_STRUCT_OPS; 23932 } 23933 23934 static int check_attach_btf_id(struct bpf_verifier_env *env) 23935 { 23936 struct bpf_prog *prog = env->prog; 23937 struct bpf_prog *tgt_prog = prog->aux->dst_prog; 23938 struct bpf_attach_target_info tgt_info = {}; 23939 u32 btf_id = prog->aux->attach_btf_id; 23940 struct bpf_trampoline *tr; 23941 int ret; 23942 u64 key; 23943 23944 if (prog->type == BPF_PROG_TYPE_SYSCALL) { 23945 if (prog->sleepable) 23946 /* attach_btf_id checked to be zero already */ 23947 return 0; 23948 verbose(env, "Syscall programs can only be sleepable\n"); 23949 return -EINVAL; 23950 } 23951 23952 if (prog->sleepable && !can_be_sleepable(prog)) { 23953 verbose(env, "Only fentry/fexit/fmod_ret, lsm, iter, uprobe, and struct_ops programs can be sleepable\n"); 23954 return -EINVAL; 23955 } 23956 23957 if (prog->type == BPF_PROG_TYPE_STRUCT_OPS) 23958 return check_struct_ops_btf_id(env); 23959 23960 if (prog->type != BPF_PROG_TYPE_TRACING && 23961 prog->type != BPF_PROG_TYPE_LSM && 23962 prog->type != BPF_PROG_TYPE_EXT) 23963 return 0; 23964 23965 ret = bpf_check_attach_target(&env->log, prog, tgt_prog, btf_id, &tgt_info); 23966 if (ret) 23967 return ret; 23968 23969 if (tgt_prog && prog->type == BPF_PROG_TYPE_EXT) { 23970 /* to make freplace equivalent to their targets, they need to 23971 * inherit env->ops and expected_attach_type for the rest of the 23972 * verification 23973 */ 23974 env->ops = bpf_verifier_ops[tgt_prog->type]; 23975 prog->expected_attach_type = tgt_prog->expected_attach_type; 23976 } 23977 23978 /* store info about the attachment target that will be used later */ 23979 prog->aux->attach_func_proto = tgt_info.tgt_type; 23980 prog->aux->attach_func_name = tgt_info.tgt_name; 23981 prog->aux->mod = tgt_info.tgt_mod; 23982 23983 if (tgt_prog) { 23984 prog->aux->saved_dst_prog_type = tgt_prog->type; 23985 prog->aux->saved_dst_attach_type = tgt_prog->expected_attach_type; 23986 } 23987 23988 if (prog->expected_attach_type == BPF_TRACE_RAW_TP) { 23989 prog->aux->attach_btf_trace = true; 23990 return 0; 23991 } else if (prog->expected_attach_type == BPF_TRACE_ITER) { 23992 return bpf_iter_prog_supported(prog); 23993 } 23994 23995 if (prog->type == BPF_PROG_TYPE_LSM) { 23996 ret = bpf_lsm_verify_prog(&env->log, prog); 23997 if (ret < 0) 23998 return ret; 23999 } else if (prog->type == BPF_PROG_TYPE_TRACING && 24000 btf_id_set_contains(&btf_id_deny, btf_id)) { 24001 verbose(env, "Attaching tracing programs to function '%s' is rejected.\n", 24002 tgt_info.tgt_name); 24003 return -EINVAL; 24004 } else if ((prog->expected_attach_type == BPF_TRACE_FEXIT || 24005 prog->expected_attach_type == BPF_MODIFY_RETURN) && 24006 btf_id_set_contains(&noreturn_deny, btf_id)) { 24007 verbose(env, "Attaching fexit/fmod_ret to __noreturn function '%s' is rejected.\n", 24008 tgt_info.tgt_name); 24009 return -EINVAL; 24010 } 24011 24012 key = bpf_trampoline_compute_key(tgt_prog, prog->aux->attach_btf, btf_id); 24013 tr = bpf_trampoline_get(key, &tgt_info); 24014 if (!tr) 24015 return -ENOMEM; 24016 24017 if (tgt_prog && tgt_prog->aux->tail_call_reachable) 24018 tr->flags = BPF_TRAMP_F_TAIL_CALL_CTX; 24019 24020 prog->aux->dst_trampoline = tr; 24021 return 0; 24022 } 24023 24024 struct btf *bpf_get_btf_vmlinux(void) 24025 { 24026 if (!btf_vmlinux && IS_ENABLED(CONFIG_DEBUG_INFO_BTF)) { 24027 mutex_lock(&bpf_verifier_lock); 24028 if (!btf_vmlinux) 24029 btf_vmlinux = btf_parse_vmlinux(); 24030 mutex_unlock(&bpf_verifier_lock); 24031 } 24032 return btf_vmlinux; 24033 } 24034 24035 /* 24036 * The add_fd_from_fd_array() is executed only if fd_array_cnt is non-zero. In 24037 * this case expect that every file descriptor in the array is either a map or 24038 * a BTF. Everything else is considered to be trash. 24039 */ 24040 static int add_fd_from_fd_array(struct bpf_verifier_env *env, int fd) 24041 { 24042 struct bpf_map *map; 24043 struct btf *btf; 24044 CLASS(fd, f)(fd); 24045 int err; 24046 24047 map = __bpf_map_get(f); 24048 if (!IS_ERR(map)) { 24049 err = __add_used_map(env, map); 24050 if (err < 0) 24051 return err; 24052 return 0; 24053 } 24054 24055 btf = __btf_get_by_fd(f); 24056 if (!IS_ERR(btf)) { 24057 err = __add_used_btf(env, btf); 24058 if (err < 0) 24059 return err; 24060 return 0; 24061 } 24062 24063 verbose(env, "fd %d is not pointing to valid bpf_map or btf\n", fd); 24064 return PTR_ERR(map); 24065 } 24066 24067 static int process_fd_array(struct bpf_verifier_env *env, union bpf_attr *attr, bpfptr_t uattr) 24068 { 24069 size_t size = sizeof(int); 24070 int ret; 24071 int fd; 24072 u32 i; 24073 24074 env->fd_array = make_bpfptr(attr->fd_array, uattr.is_kernel); 24075 24076 /* 24077 * The only difference between old (no fd_array_cnt is given) and new 24078 * APIs is that in the latter case the fd_array is expected to be 24079 * continuous and is scanned for map fds right away 24080 */ 24081 if (!attr->fd_array_cnt) 24082 return 0; 24083 24084 /* Check for integer overflow */ 24085 if (attr->fd_array_cnt >= (U32_MAX / size)) { 24086 verbose(env, "fd_array_cnt is too big (%u)\n", attr->fd_array_cnt); 24087 return -EINVAL; 24088 } 24089 24090 for (i = 0; i < attr->fd_array_cnt; i++) { 24091 if (copy_from_bpfptr_offset(&fd, env->fd_array, i * size, size)) 24092 return -EFAULT; 24093 24094 ret = add_fd_from_fd_array(env, fd); 24095 if (ret) 24096 return ret; 24097 } 24098 24099 return 0; 24100 } 24101 24102 static bool can_fallthrough(struct bpf_insn *insn) 24103 { 24104 u8 class = BPF_CLASS(insn->code); 24105 u8 opcode = BPF_OP(insn->code); 24106 24107 if (class != BPF_JMP && class != BPF_JMP32) 24108 return true; 24109 24110 if (opcode == BPF_EXIT || opcode == BPF_JA) 24111 return false; 24112 24113 return true; 24114 } 24115 24116 static bool can_jump(struct bpf_insn *insn) 24117 { 24118 u8 class = BPF_CLASS(insn->code); 24119 u8 opcode = BPF_OP(insn->code); 24120 24121 if (class != BPF_JMP && class != BPF_JMP32) 24122 return false; 24123 24124 switch (opcode) { 24125 case BPF_JA: 24126 case BPF_JEQ: 24127 case BPF_JNE: 24128 case BPF_JLT: 24129 case BPF_JLE: 24130 case BPF_JGT: 24131 case BPF_JGE: 24132 case BPF_JSGT: 24133 case BPF_JSGE: 24134 case BPF_JSLT: 24135 case BPF_JSLE: 24136 case BPF_JCOND: 24137 case BPF_JSET: 24138 return true; 24139 } 24140 24141 return false; 24142 } 24143 24144 static int insn_successors(struct bpf_prog *prog, u32 idx, u32 succ[2]) 24145 { 24146 struct bpf_insn *insn = &prog->insnsi[idx]; 24147 int i = 0, insn_sz; 24148 u32 dst; 24149 24150 insn_sz = bpf_is_ldimm64(insn) ? 2 : 1; 24151 if (can_fallthrough(insn) && idx + 1 < prog->len) 24152 succ[i++] = idx + insn_sz; 24153 24154 if (can_jump(insn)) { 24155 dst = idx + jmp_offset(insn) + 1; 24156 if (i == 0 || succ[0] != dst) 24157 succ[i++] = dst; 24158 } 24159 24160 return i; 24161 } 24162 24163 /* Each field is a register bitmask */ 24164 struct insn_live_regs { 24165 u16 use; /* registers read by instruction */ 24166 u16 def; /* registers written by instruction */ 24167 u16 in; /* registers that may be alive before instruction */ 24168 u16 out; /* registers that may be alive after instruction */ 24169 }; 24170 24171 /* Bitmask with 1s for all caller saved registers */ 24172 #define ALL_CALLER_SAVED_REGS ((1u << CALLER_SAVED_REGS) - 1) 24173 24174 /* Compute info->{use,def} fields for the instruction */ 24175 static void compute_insn_live_regs(struct bpf_verifier_env *env, 24176 struct bpf_insn *insn, 24177 struct insn_live_regs *info) 24178 { 24179 struct call_summary cs; 24180 u8 class = BPF_CLASS(insn->code); 24181 u8 code = BPF_OP(insn->code); 24182 u8 mode = BPF_MODE(insn->code); 24183 u16 src = BIT(insn->src_reg); 24184 u16 dst = BIT(insn->dst_reg); 24185 u16 r0 = BIT(0); 24186 u16 def = 0; 24187 u16 use = 0xffff; 24188 24189 switch (class) { 24190 case BPF_LD: 24191 switch (mode) { 24192 case BPF_IMM: 24193 if (BPF_SIZE(insn->code) == BPF_DW) { 24194 def = dst; 24195 use = 0; 24196 } 24197 break; 24198 case BPF_LD | BPF_ABS: 24199 case BPF_LD | BPF_IND: 24200 /* stick with defaults */ 24201 break; 24202 } 24203 break; 24204 case BPF_LDX: 24205 switch (mode) { 24206 case BPF_MEM: 24207 case BPF_MEMSX: 24208 def = dst; 24209 use = src; 24210 break; 24211 } 24212 break; 24213 case BPF_ST: 24214 switch (mode) { 24215 case BPF_MEM: 24216 def = 0; 24217 use = dst; 24218 break; 24219 } 24220 break; 24221 case BPF_STX: 24222 switch (mode) { 24223 case BPF_MEM: 24224 def = 0; 24225 use = dst | src; 24226 break; 24227 case BPF_ATOMIC: 24228 switch (insn->imm) { 24229 case BPF_CMPXCHG: 24230 use = r0 | dst | src; 24231 def = r0; 24232 break; 24233 case BPF_LOAD_ACQ: 24234 def = dst; 24235 use = src; 24236 break; 24237 case BPF_STORE_REL: 24238 def = 0; 24239 use = dst | src; 24240 break; 24241 default: 24242 use = dst | src; 24243 if (insn->imm & BPF_FETCH) 24244 def = src; 24245 else 24246 def = 0; 24247 } 24248 break; 24249 } 24250 break; 24251 case BPF_ALU: 24252 case BPF_ALU64: 24253 switch (code) { 24254 case BPF_END: 24255 use = dst; 24256 def = dst; 24257 break; 24258 case BPF_MOV: 24259 def = dst; 24260 if (BPF_SRC(insn->code) == BPF_K) 24261 use = 0; 24262 else 24263 use = src; 24264 break; 24265 default: 24266 def = dst; 24267 if (BPF_SRC(insn->code) == BPF_K) 24268 use = dst; 24269 else 24270 use = dst | src; 24271 } 24272 break; 24273 case BPF_JMP: 24274 case BPF_JMP32: 24275 switch (code) { 24276 case BPF_JA: 24277 case BPF_JCOND: 24278 def = 0; 24279 use = 0; 24280 break; 24281 case BPF_EXIT: 24282 def = 0; 24283 use = r0; 24284 break; 24285 case BPF_CALL: 24286 def = ALL_CALLER_SAVED_REGS; 24287 use = def & ~BIT(BPF_REG_0); 24288 if (get_call_summary(env, insn, &cs)) 24289 use = GENMASK(cs.num_params, 1); 24290 break; 24291 default: 24292 def = 0; 24293 if (BPF_SRC(insn->code) == BPF_K) 24294 use = dst; 24295 else 24296 use = dst | src; 24297 } 24298 break; 24299 } 24300 24301 info->def = def; 24302 info->use = use; 24303 } 24304 24305 /* Compute may-live registers after each instruction in the program. 24306 * The register is live after the instruction I if it is read by some 24307 * instruction S following I during program execution and is not 24308 * overwritten between I and S. 24309 * 24310 * Store result in env->insn_aux_data[i].live_regs. 24311 */ 24312 static int compute_live_registers(struct bpf_verifier_env *env) 24313 { 24314 struct bpf_insn_aux_data *insn_aux = env->insn_aux_data; 24315 struct bpf_insn *insns = env->prog->insnsi; 24316 struct insn_live_regs *state; 24317 int insn_cnt = env->prog->len; 24318 int err = 0, i, j; 24319 bool changed; 24320 24321 /* Use the following algorithm: 24322 * - define the following: 24323 * - I.use : a set of all registers read by instruction I; 24324 * - I.def : a set of all registers written by instruction I; 24325 * - I.in : a set of all registers that may be alive before I execution; 24326 * - I.out : a set of all registers that may be alive after I execution; 24327 * - insn_successors(I): a set of instructions S that might immediately 24328 * follow I for some program execution; 24329 * - associate separate empty sets 'I.in' and 'I.out' with each instruction; 24330 * - visit each instruction in a postorder and update 24331 * state[i].in, state[i].out as follows: 24332 * 24333 * state[i].out = U [state[s].in for S in insn_successors(i)] 24334 * state[i].in = (state[i].out / state[i].def) U state[i].use 24335 * 24336 * (where U stands for set union, / stands for set difference) 24337 * - repeat the computation while {in,out} fields changes for 24338 * any instruction. 24339 */ 24340 state = kvcalloc(insn_cnt, sizeof(*state), GFP_KERNEL_ACCOUNT); 24341 if (!state) { 24342 err = -ENOMEM; 24343 goto out; 24344 } 24345 24346 for (i = 0; i < insn_cnt; ++i) 24347 compute_insn_live_regs(env, &insns[i], &state[i]); 24348 24349 changed = true; 24350 while (changed) { 24351 changed = false; 24352 for (i = 0; i < env->cfg.cur_postorder; ++i) { 24353 int insn_idx = env->cfg.insn_postorder[i]; 24354 struct insn_live_regs *live = &state[insn_idx]; 24355 int succ_num; 24356 u32 succ[2]; 24357 u16 new_out = 0; 24358 u16 new_in = 0; 24359 24360 succ_num = insn_successors(env->prog, insn_idx, succ); 24361 for (int s = 0; s < succ_num; ++s) 24362 new_out |= state[succ[s]].in; 24363 new_in = (new_out & ~live->def) | live->use; 24364 if (new_out != live->out || new_in != live->in) { 24365 live->in = new_in; 24366 live->out = new_out; 24367 changed = true; 24368 } 24369 } 24370 } 24371 24372 for (i = 0; i < insn_cnt; ++i) 24373 insn_aux[i].live_regs_before = state[i].in; 24374 24375 if (env->log.level & BPF_LOG_LEVEL2) { 24376 verbose(env, "Live regs before insn:\n"); 24377 for (i = 0; i < insn_cnt; ++i) { 24378 if (env->insn_aux_data[i].scc) 24379 verbose(env, "%3d ", env->insn_aux_data[i].scc); 24380 else 24381 verbose(env, " "); 24382 verbose(env, "%3d: ", i); 24383 for (j = BPF_REG_0; j < BPF_REG_10; ++j) 24384 if (insn_aux[i].live_regs_before & BIT(j)) 24385 verbose(env, "%d", j); 24386 else 24387 verbose(env, "."); 24388 verbose(env, " "); 24389 verbose_insn(env, &insns[i]); 24390 if (bpf_is_ldimm64(&insns[i])) 24391 i++; 24392 } 24393 } 24394 24395 out: 24396 kvfree(state); 24397 kvfree(env->cfg.insn_postorder); 24398 env->cfg.insn_postorder = NULL; 24399 env->cfg.cur_postorder = 0; 24400 return err; 24401 } 24402 24403 /* 24404 * Compute strongly connected components (SCCs) on the CFG. 24405 * Assign an SCC number to each instruction, recorded in env->insn_aux[*].scc. 24406 * If instruction is a sole member of its SCC and there are no self edges, 24407 * assign it SCC number of zero. 24408 * Uses a non-recursive adaptation of Tarjan's algorithm for SCC computation. 24409 */ 24410 static int compute_scc(struct bpf_verifier_env *env) 24411 { 24412 const u32 NOT_ON_STACK = U32_MAX; 24413 24414 struct bpf_insn_aux_data *aux = env->insn_aux_data; 24415 const u32 insn_cnt = env->prog->len; 24416 int stack_sz, dfs_sz, err = 0; 24417 u32 *stack, *pre, *low, *dfs; 24418 u32 succ_cnt, i, j, t, w; 24419 u32 next_preorder_num; 24420 u32 next_scc_id; 24421 bool assign_scc; 24422 u32 succ[2]; 24423 24424 next_preorder_num = 1; 24425 next_scc_id = 1; 24426 /* 24427 * - 'stack' accumulates vertices in DFS order, see invariant comment below; 24428 * - 'pre[t] == p' => preorder number of vertex 't' is 'p'; 24429 * - 'low[t] == n' => smallest preorder number of the vertex reachable from 't' is 'n'; 24430 * - 'dfs' DFS traversal stack, used to emulate explicit recursion. 24431 */ 24432 stack = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL_ACCOUNT); 24433 pre = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL_ACCOUNT); 24434 low = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL_ACCOUNT); 24435 dfs = kvcalloc(insn_cnt, sizeof(*dfs), GFP_KERNEL_ACCOUNT); 24436 if (!stack || !pre || !low || !dfs) { 24437 err = -ENOMEM; 24438 goto exit; 24439 } 24440 /* 24441 * References: 24442 * [1] R. Tarjan "Depth-First Search and Linear Graph Algorithms" 24443 * [2] D. J. Pearce "A Space-Efficient Algorithm for Finding Strongly Connected Components" 24444 * 24445 * The algorithm maintains the following invariant: 24446 * - suppose there is a path 'u' ~> 'v', such that 'pre[v] < pre[u]'; 24447 * - then, vertex 'u' remains on stack while vertex 'v' is on stack. 24448 * 24449 * Consequently: 24450 * - If 'low[v] < pre[v]', there is a path from 'v' to some vertex 'u', 24451 * such that 'pre[u] == low[v]'; vertex 'u' is currently on the stack, 24452 * and thus there is an SCC (loop) containing both 'u' and 'v'. 24453 * - If 'low[v] == pre[v]', loops containing 'v' have been explored, 24454 * and 'v' can be considered the root of some SCC. 24455 * 24456 * Here is a pseudo-code for an explicitly recursive version of the algorithm: 24457 * 24458 * NOT_ON_STACK = insn_cnt + 1 24459 * pre = [0] * insn_cnt 24460 * low = [0] * insn_cnt 24461 * scc = [0] * insn_cnt 24462 * stack = [] 24463 * 24464 * next_preorder_num = 1 24465 * next_scc_id = 1 24466 * 24467 * def recur(w): 24468 * nonlocal next_preorder_num 24469 * nonlocal next_scc_id 24470 * 24471 * pre[w] = next_preorder_num 24472 * low[w] = next_preorder_num 24473 * next_preorder_num += 1 24474 * stack.append(w) 24475 * for s in successors(w): 24476 * # Note: for classic algorithm the block below should look as: 24477 * # 24478 * # if pre[s] == 0: 24479 * # recur(s) 24480 * # low[w] = min(low[w], low[s]) 24481 * # elif low[s] != NOT_ON_STACK: 24482 * # low[w] = min(low[w], pre[s]) 24483 * # 24484 * # But replacing both 'min' instructions with 'low[w] = min(low[w], low[s])' 24485 * # does not break the invariant and makes itartive version of the algorithm 24486 * # simpler. See 'Algorithm #3' from [2]. 24487 * 24488 * # 's' not yet visited 24489 * if pre[s] == 0: 24490 * recur(s) 24491 * # if 's' is on stack, pick lowest reachable preorder number from it; 24492 * # if 's' is not on stack 'low[s] == NOT_ON_STACK > low[w]', 24493 * # so 'min' would be a noop. 24494 * low[w] = min(low[w], low[s]) 24495 * 24496 * if low[w] == pre[w]: 24497 * # 'w' is the root of an SCC, pop all vertices 24498 * # below 'w' on stack and assign same SCC to them. 24499 * while True: 24500 * t = stack.pop() 24501 * low[t] = NOT_ON_STACK 24502 * scc[t] = next_scc_id 24503 * if t == w: 24504 * break 24505 * next_scc_id += 1 24506 * 24507 * for i in range(0, insn_cnt): 24508 * if pre[i] == 0: 24509 * recur(i) 24510 * 24511 * Below implementation replaces explicit recursion with array 'dfs'. 24512 */ 24513 for (i = 0; i < insn_cnt; i++) { 24514 if (pre[i]) 24515 continue; 24516 stack_sz = 0; 24517 dfs_sz = 1; 24518 dfs[0] = i; 24519 dfs_continue: 24520 while (dfs_sz) { 24521 w = dfs[dfs_sz - 1]; 24522 if (pre[w] == 0) { 24523 low[w] = next_preorder_num; 24524 pre[w] = next_preorder_num; 24525 next_preorder_num++; 24526 stack[stack_sz++] = w; 24527 } 24528 /* Visit 'w' successors */ 24529 succ_cnt = insn_successors(env->prog, w, succ); 24530 for (j = 0; j < succ_cnt; ++j) { 24531 if (pre[succ[j]]) { 24532 low[w] = min(low[w], low[succ[j]]); 24533 } else { 24534 dfs[dfs_sz++] = succ[j]; 24535 goto dfs_continue; 24536 } 24537 } 24538 /* 24539 * Preserve the invariant: if some vertex above in the stack 24540 * is reachable from 'w', keep 'w' on the stack. 24541 */ 24542 if (low[w] < pre[w]) { 24543 dfs_sz--; 24544 goto dfs_continue; 24545 } 24546 /* 24547 * Assign SCC number only if component has two or more elements, 24548 * or if component has a self reference. 24549 */ 24550 assign_scc = stack[stack_sz - 1] != w; 24551 for (j = 0; j < succ_cnt; ++j) { 24552 if (succ[j] == w) { 24553 assign_scc = true; 24554 break; 24555 } 24556 } 24557 /* Pop component elements from stack */ 24558 do { 24559 t = stack[--stack_sz]; 24560 low[t] = NOT_ON_STACK; 24561 if (assign_scc) 24562 aux[t].scc = next_scc_id; 24563 } while (t != w); 24564 if (assign_scc) 24565 next_scc_id++; 24566 dfs_sz--; 24567 } 24568 } 24569 env->scc_info = kvcalloc(next_scc_id, sizeof(*env->scc_info), GFP_KERNEL_ACCOUNT); 24570 if (!env->scc_info) { 24571 err = -ENOMEM; 24572 goto exit; 24573 } 24574 env->scc_cnt = next_scc_id; 24575 exit: 24576 kvfree(stack); 24577 kvfree(pre); 24578 kvfree(low); 24579 kvfree(dfs); 24580 return err; 24581 } 24582 24583 int bpf_check(struct bpf_prog **prog, union bpf_attr *attr, bpfptr_t uattr, __u32 uattr_size) 24584 { 24585 u64 start_time = ktime_get_ns(); 24586 struct bpf_verifier_env *env; 24587 int i, len, ret = -EINVAL, err; 24588 u32 log_true_size; 24589 bool is_priv; 24590 24591 BTF_TYPE_EMIT(enum bpf_features); 24592 24593 /* no program is valid */ 24594 if (ARRAY_SIZE(bpf_verifier_ops) == 0) 24595 return -EINVAL; 24596 24597 /* 'struct bpf_verifier_env' can be global, but since it's not small, 24598 * allocate/free it every time bpf_check() is called 24599 */ 24600 env = kvzalloc(sizeof(struct bpf_verifier_env), GFP_KERNEL_ACCOUNT); 24601 if (!env) 24602 return -ENOMEM; 24603 24604 env->bt.env = env; 24605 24606 len = (*prog)->len; 24607 env->insn_aux_data = 24608 vzalloc(array_size(sizeof(struct bpf_insn_aux_data), len)); 24609 ret = -ENOMEM; 24610 if (!env->insn_aux_data) 24611 goto err_free_env; 24612 for (i = 0; i < len; i++) 24613 env->insn_aux_data[i].orig_idx = i; 24614 env->prog = *prog; 24615 env->ops = bpf_verifier_ops[env->prog->type]; 24616 24617 env->allow_ptr_leaks = bpf_allow_ptr_leaks(env->prog->aux->token); 24618 env->allow_uninit_stack = bpf_allow_uninit_stack(env->prog->aux->token); 24619 env->bypass_spec_v1 = bpf_bypass_spec_v1(env->prog->aux->token); 24620 env->bypass_spec_v4 = bpf_bypass_spec_v4(env->prog->aux->token); 24621 env->bpf_capable = is_priv = bpf_token_capable(env->prog->aux->token, CAP_BPF); 24622 24623 bpf_get_btf_vmlinux(); 24624 24625 /* grab the mutex to protect few globals used by verifier */ 24626 if (!is_priv) 24627 mutex_lock(&bpf_verifier_lock); 24628 24629 /* user could have requested verbose verifier output 24630 * and supplied buffer to store the verification trace 24631 */ 24632 ret = bpf_vlog_init(&env->log, attr->log_level, 24633 (char __user *) (unsigned long) attr->log_buf, 24634 attr->log_size); 24635 if (ret) 24636 goto err_unlock; 24637 24638 ret = process_fd_array(env, attr, uattr); 24639 if (ret) 24640 goto skip_full_check; 24641 24642 mark_verifier_state_clean(env); 24643 24644 if (IS_ERR(btf_vmlinux)) { 24645 /* Either gcc or pahole or kernel are broken. */ 24646 verbose(env, "in-kernel BTF is malformed\n"); 24647 ret = PTR_ERR(btf_vmlinux); 24648 goto skip_full_check; 24649 } 24650 24651 env->strict_alignment = !!(attr->prog_flags & BPF_F_STRICT_ALIGNMENT); 24652 if (!IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS)) 24653 env->strict_alignment = true; 24654 if (attr->prog_flags & BPF_F_ANY_ALIGNMENT) 24655 env->strict_alignment = false; 24656 24657 if (is_priv) 24658 env->test_state_freq = attr->prog_flags & BPF_F_TEST_STATE_FREQ; 24659 env->test_reg_invariants = attr->prog_flags & BPF_F_TEST_REG_INVARIANTS; 24660 24661 env->explored_states = kvcalloc(state_htab_size(env), 24662 sizeof(struct list_head), 24663 GFP_KERNEL_ACCOUNT); 24664 ret = -ENOMEM; 24665 if (!env->explored_states) 24666 goto skip_full_check; 24667 24668 for (i = 0; i < state_htab_size(env); i++) 24669 INIT_LIST_HEAD(&env->explored_states[i]); 24670 INIT_LIST_HEAD(&env->free_list); 24671 24672 ret = check_btf_info_early(env, attr, uattr); 24673 if (ret < 0) 24674 goto skip_full_check; 24675 24676 ret = add_subprog_and_kfunc(env); 24677 if (ret < 0) 24678 goto skip_full_check; 24679 24680 ret = check_subprogs(env); 24681 if (ret < 0) 24682 goto skip_full_check; 24683 24684 ret = check_btf_info(env, attr, uattr); 24685 if (ret < 0) 24686 goto skip_full_check; 24687 24688 ret = resolve_pseudo_ldimm64(env); 24689 if (ret < 0) 24690 goto skip_full_check; 24691 24692 if (bpf_prog_is_offloaded(env->prog->aux)) { 24693 ret = bpf_prog_offload_verifier_prep(env->prog); 24694 if (ret) 24695 goto skip_full_check; 24696 } 24697 24698 ret = check_cfg(env); 24699 if (ret < 0) 24700 goto skip_full_check; 24701 24702 ret = check_attach_btf_id(env); 24703 if (ret) 24704 goto skip_full_check; 24705 24706 ret = compute_scc(env); 24707 if (ret < 0) 24708 goto skip_full_check; 24709 24710 ret = compute_live_registers(env); 24711 if (ret < 0) 24712 goto skip_full_check; 24713 24714 ret = mark_fastcall_patterns(env); 24715 if (ret < 0) 24716 goto skip_full_check; 24717 24718 ret = do_check_main(env); 24719 ret = ret ?: do_check_subprogs(env); 24720 24721 if (ret == 0 && bpf_prog_is_offloaded(env->prog->aux)) 24722 ret = bpf_prog_offload_finalize(env); 24723 24724 skip_full_check: 24725 kvfree(env->explored_states); 24726 24727 /* might decrease stack depth, keep it before passes that 24728 * allocate additional slots. 24729 */ 24730 if (ret == 0) 24731 ret = remove_fastcall_spills_fills(env); 24732 24733 if (ret == 0) 24734 ret = check_max_stack_depth(env); 24735 24736 /* instruction rewrites happen after this point */ 24737 if (ret == 0) 24738 ret = optimize_bpf_loop(env); 24739 24740 if (is_priv) { 24741 if (ret == 0) 24742 opt_hard_wire_dead_code_branches(env); 24743 if (ret == 0) 24744 ret = opt_remove_dead_code(env); 24745 if (ret == 0) 24746 ret = opt_remove_nops(env); 24747 } else { 24748 if (ret == 0) 24749 sanitize_dead_code(env); 24750 } 24751 24752 if (ret == 0) 24753 /* program is valid, convert *(u32*)(ctx + off) accesses */ 24754 ret = convert_ctx_accesses(env); 24755 24756 if (ret == 0) 24757 ret = do_misc_fixups(env); 24758 24759 /* do 32-bit optimization after insn patching has done so those patched 24760 * insns could be handled correctly. 24761 */ 24762 if (ret == 0 && !bpf_prog_is_offloaded(env->prog->aux)) { 24763 ret = opt_subreg_zext_lo32_rnd_hi32(env, attr); 24764 env->prog->aux->verifier_zext = bpf_jit_needs_zext() ? !ret 24765 : false; 24766 } 24767 24768 if (ret == 0) 24769 ret = fixup_call_args(env); 24770 24771 env->verification_time = ktime_get_ns() - start_time; 24772 print_verification_stats(env); 24773 env->prog->aux->verified_insns = env->insn_processed; 24774 24775 /* preserve original error even if log finalization is successful */ 24776 err = bpf_vlog_finalize(&env->log, &log_true_size); 24777 if (err) 24778 ret = err; 24779 24780 if (uattr_size >= offsetofend(union bpf_attr, log_true_size) && 24781 copy_to_bpfptr_offset(uattr, offsetof(union bpf_attr, log_true_size), 24782 &log_true_size, sizeof(log_true_size))) { 24783 ret = -EFAULT; 24784 goto err_release_maps; 24785 } 24786 24787 if (ret) 24788 goto err_release_maps; 24789 24790 if (env->used_map_cnt) { 24791 /* if program passed verifier, update used_maps in bpf_prog_info */ 24792 env->prog->aux->used_maps = kmalloc_array(env->used_map_cnt, 24793 sizeof(env->used_maps[0]), 24794 GFP_KERNEL_ACCOUNT); 24795 24796 if (!env->prog->aux->used_maps) { 24797 ret = -ENOMEM; 24798 goto err_release_maps; 24799 } 24800 24801 memcpy(env->prog->aux->used_maps, env->used_maps, 24802 sizeof(env->used_maps[0]) * env->used_map_cnt); 24803 env->prog->aux->used_map_cnt = env->used_map_cnt; 24804 } 24805 if (env->used_btf_cnt) { 24806 /* if program passed verifier, update used_btfs in bpf_prog_aux */ 24807 env->prog->aux->used_btfs = kmalloc_array(env->used_btf_cnt, 24808 sizeof(env->used_btfs[0]), 24809 GFP_KERNEL_ACCOUNT); 24810 if (!env->prog->aux->used_btfs) { 24811 ret = -ENOMEM; 24812 goto err_release_maps; 24813 } 24814 24815 memcpy(env->prog->aux->used_btfs, env->used_btfs, 24816 sizeof(env->used_btfs[0]) * env->used_btf_cnt); 24817 env->prog->aux->used_btf_cnt = env->used_btf_cnt; 24818 } 24819 if (env->used_map_cnt || env->used_btf_cnt) { 24820 /* program is valid. Convert pseudo bpf_ld_imm64 into generic 24821 * bpf_ld_imm64 instructions 24822 */ 24823 convert_pseudo_ld_imm64(env); 24824 } 24825 24826 adjust_btf_func(env); 24827 24828 err_release_maps: 24829 if (!env->prog->aux->used_maps) 24830 /* if we didn't copy map pointers into bpf_prog_info, release 24831 * them now. Otherwise free_used_maps() will release them. 24832 */ 24833 release_maps(env); 24834 if (!env->prog->aux->used_btfs) 24835 release_btfs(env); 24836 24837 /* extension progs temporarily inherit the attach_type of their targets 24838 for verification purposes, so set it back to zero before returning 24839 */ 24840 if (env->prog->type == BPF_PROG_TYPE_EXT) 24841 env->prog->expected_attach_type = 0; 24842 24843 *prog = env->prog; 24844 24845 module_put(env->attach_btf_mod); 24846 err_unlock: 24847 if (!is_priv) 24848 mutex_unlock(&bpf_verifier_lock); 24849 vfree(env->insn_aux_data); 24850 err_free_env: 24851 kvfree(env->cfg.insn_postorder); 24852 kvfree(env->scc_info); 24853 kvfree(env); 24854 return ret; 24855 } 24856