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 <net/xdp.h> 30 31 #include "disasm.h" 32 33 static const struct bpf_verifier_ops * const bpf_verifier_ops[] = { 34 #define BPF_PROG_TYPE(_id, _name, prog_ctx_type, kern_ctx_type) \ 35 [_id] = & _name ## _verifier_ops, 36 #define BPF_MAP_TYPE(_id, _ops) 37 #define BPF_LINK_TYPE(_id, _name) 38 #include <linux/bpf_types.h> 39 #undef BPF_PROG_TYPE 40 #undef BPF_MAP_TYPE 41 #undef BPF_LINK_TYPE 42 }; 43 44 /* bpf_check() is a static code analyzer that walks eBPF program 45 * instruction by instruction and updates register/stack state. 46 * All paths of conditional branches are analyzed until 'bpf_exit' insn. 47 * 48 * The first pass is depth-first-search to check that the program is a DAG. 49 * It rejects the following programs: 50 * - larger than BPF_MAXINSNS insns 51 * - if loop is present (detected via back-edge) 52 * - unreachable insns exist (shouldn't be a forest. program = one function) 53 * - out of bounds or malformed jumps 54 * The second pass is all possible path descent from the 1st insn. 55 * Since it's analyzing all paths through the program, the length of the 56 * analysis is limited to 64k insn, which may be hit even if total number of 57 * insn is less then 4K, but there are too many branches that change stack/regs. 58 * Number of 'branches to be analyzed' is limited to 1k 59 * 60 * On entry to each instruction, each register has a type, and the instruction 61 * changes the types of the registers depending on instruction semantics. 62 * If instruction is BPF_MOV64_REG(BPF_REG_1, BPF_REG_5), then type of R5 is 63 * copied to R1. 64 * 65 * All registers are 64-bit. 66 * R0 - return register 67 * R1-R5 argument passing registers 68 * R6-R9 callee saved registers 69 * R10 - frame pointer read-only 70 * 71 * At the start of BPF program the register R1 contains a pointer to bpf_context 72 * and has type PTR_TO_CTX. 73 * 74 * Verifier tracks arithmetic operations on pointers in case: 75 * BPF_MOV64_REG(BPF_REG_1, BPF_REG_10), 76 * BPF_ALU64_IMM(BPF_ADD, BPF_REG_1, -20), 77 * 1st insn copies R10 (which has FRAME_PTR) type into R1 78 * and 2nd arithmetic instruction is pattern matched to recognize 79 * that it wants to construct a pointer to some element within stack. 80 * So after 2nd insn, the register R1 has type PTR_TO_STACK 81 * (and -20 constant is saved for further stack bounds checking). 82 * Meaning that this reg is a pointer to stack plus known immediate constant. 83 * 84 * Most of the time the registers have SCALAR_VALUE type, which 85 * means the register has some value, but it's not a valid pointer. 86 * (like pointer plus pointer becomes SCALAR_VALUE type) 87 * 88 * When verifier sees load or store instructions the type of base register 89 * can be: PTR_TO_MAP_VALUE, PTR_TO_CTX, PTR_TO_STACK, PTR_TO_SOCKET. These are 90 * four pointer types recognized by check_mem_access() function. 91 * 92 * PTR_TO_MAP_VALUE means that this register is pointing to 'map element value' 93 * and the range of [ptr, ptr + map's value_size) is accessible. 94 * 95 * registers used to pass values to function calls are checked against 96 * function argument constraints. 97 * 98 * ARG_PTR_TO_MAP_KEY is one of such argument constraints. 99 * It means that the register type passed to this function must be 100 * PTR_TO_STACK and it will be used inside the function as 101 * 'pointer to map element key' 102 * 103 * For example the argument constraints for bpf_map_lookup_elem(): 104 * .ret_type = RET_PTR_TO_MAP_VALUE_OR_NULL, 105 * .arg1_type = ARG_CONST_MAP_PTR, 106 * .arg2_type = ARG_PTR_TO_MAP_KEY, 107 * 108 * ret_type says that this function returns 'pointer to map elem value or null' 109 * function expects 1st argument to be a const pointer to 'struct bpf_map' and 110 * 2nd argument should be a pointer to stack, which will be used inside 111 * the helper function as a pointer to map element key. 112 * 113 * On the kernel side the helper function looks like: 114 * u64 bpf_map_lookup_elem(u64 r1, u64 r2, u64 r3, u64 r4, u64 r5) 115 * { 116 * struct bpf_map *map = (struct bpf_map *) (unsigned long) r1; 117 * void *key = (void *) (unsigned long) r2; 118 * void *value; 119 * 120 * here kernel can access 'key' and 'map' pointers safely, knowing that 121 * [key, key + map->key_size) bytes are valid and were initialized on 122 * the stack of eBPF program. 123 * } 124 * 125 * Corresponding eBPF program may look like: 126 * BPF_MOV64_REG(BPF_REG_2, BPF_REG_10), // after this insn R2 type is FRAME_PTR 127 * BPF_ALU64_IMM(BPF_ADD, BPF_REG_2, -4), // after this insn R2 type is PTR_TO_STACK 128 * BPF_LD_MAP_FD(BPF_REG_1, map_fd), // after this insn R1 type is CONST_PTR_TO_MAP 129 * BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0, BPF_FUNC_map_lookup_elem), 130 * here verifier looks at prototype of map_lookup_elem() and sees: 131 * .arg1_type == ARG_CONST_MAP_PTR and R1->type == CONST_PTR_TO_MAP, which is ok, 132 * Now verifier knows that this map has key of R1->map_ptr->key_size bytes 133 * 134 * Then .arg2_type == ARG_PTR_TO_MAP_KEY and R2->type == PTR_TO_STACK, ok so far, 135 * Now verifier checks that [R2, R2 + map's key_size) are within stack limits 136 * and were initialized prior to this call. 137 * If it's ok, then verifier allows this BPF_CALL insn and looks at 138 * .ret_type which is RET_PTR_TO_MAP_VALUE_OR_NULL, so it sets 139 * R0->type = PTR_TO_MAP_VALUE_OR_NULL which means bpf_map_lookup_elem() function 140 * returns either pointer to map value or NULL. 141 * 142 * When type PTR_TO_MAP_VALUE_OR_NULL passes through 'if (reg != 0) goto +off' 143 * insn, the register holding that pointer in the true branch changes state to 144 * PTR_TO_MAP_VALUE and the same register changes state to CONST_IMM in the false 145 * branch. See check_cond_jmp_op(). 146 * 147 * After the call R0 is set to return type of the function and registers R1-R5 148 * are set to NOT_INIT to indicate that they are no longer readable. 149 * 150 * The following reference types represent a potential reference to a kernel 151 * resource which, after first being allocated, must be checked and freed by 152 * the BPF program: 153 * - PTR_TO_SOCKET_OR_NULL, PTR_TO_SOCKET 154 * 155 * When the verifier sees a helper call return a reference type, it allocates a 156 * pointer id for the reference and stores it in the current function state. 157 * Similar to the way that PTR_TO_MAP_VALUE_OR_NULL is converted into 158 * PTR_TO_MAP_VALUE, PTR_TO_SOCKET_OR_NULL becomes PTR_TO_SOCKET when the type 159 * passes through a NULL-check conditional. For the branch wherein the state is 160 * changed to CONST_IMM, the verifier releases the reference. 161 * 162 * For each helper function that allocates a reference, such as 163 * bpf_sk_lookup_tcp(), there is a corresponding release function, such as 164 * bpf_sk_release(). When a reference type passes into the release function, 165 * the verifier also releases the reference. If any unchecked or unreleased 166 * reference remains at the end of the program, the verifier rejects it. 167 */ 168 169 /* verifier_state + insn_idx are pushed to stack when branch is encountered */ 170 struct bpf_verifier_stack_elem { 171 /* verifer state is 'st' 172 * before processing instruction 'insn_idx' 173 * and after processing instruction 'prev_insn_idx' 174 */ 175 struct bpf_verifier_state st; 176 int insn_idx; 177 int prev_insn_idx; 178 struct bpf_verifier_stack_elem *next; 179 /* length of verifier log at the time this state was pushed on stack */ 180 u32 log_pos; 181 }; 182 183 #define BPF_COMPLEXITY_LIMIT_JMP_SEQ 8192 184 #define BPF_COMPLEXITY_LIMIT_STATES 64 185 186 #define BPF_MAP_KEY_POISON (1ULL << 63) 187 #define BPF_MAP_KEY_SEEN (1ULL << 62) 188 189 #define BPF_MAP_PTR_UNPRIV 1UL 190 #define BPF_MAP_PTR_POISON ((void *)((0xeB9FUL << 1) + \ 191 POISON_POINTER_DELTA)) 192 #define BPF_MAP_PTR(X) ((struct bpf_map *)((X) & ~BPF_MAP_PTR_UNPRIV)) 193 194 static int acquire_reference_state(struct bpf_verifier_env *env, int insn_idx); 195 static int release_reference(struct bpf_verifier_env *env, int ref_obj_id); 196 static void invalidate_non_owning_refs(struct bpf_verifier_env *env); 197 static bool in_rbtree_lock_required_cb(struct bpf_verifier_env *env); 198 static int ref_set_non_owning(struct bpf_verifier_env *env, 199 struct bpf_reg_state *reg); 200 static void specialize_kfunc(struct bpf_verifier_env *env, 201 u32 func_id, u16 offset, unsigned long *addr); 202 static bool is_trusted_reg(const struct bpf_reg_state *reg); 203 204 static bool bpf_map_ptr_poisoned(const struct bpf_insn_aux_data *aux) 205 { 206 return BPF_MAP_PTR(aux->map_ptr_state) == BPF_MAP_PTR_POISON; 207 } 208 209 static bool bpf_map_ptr_unpriv(const struct bpf_insn_aux_data *aux) 210 { 211 return aux->map_ptr_state & BPF_MAP_PTR_UNPRIV; 212 } 213 214 static void bpf_map_ptr_store(struct bpf_insn_aux_data *aux, 215 const struct bpf_map *map, bool unpriv) 216 { 217 BUILD_BUG_ON((unsigned long)BPF_MAP_PTR_POISON & BPF_MAP_PTR_UNPRIV); 218 unpriv |= bpf_map_ptr_unpriv(aux); 219 aux->map_ptr_state = (unsigned long)map | 220 (unpriv ? BPF_MAP_PTR_UNPRIV : 0UL); 221 } 222 223 static bool bpf_map_key_poisoned(const struct bpf_insn_aux_data *aux) 224 { 225 return aux->map_key_state & BPF_MAP_KEY_POISON; 226 } 227 228 static bool bpf_map_key_unseen(const struct bpf_insn_aux_data *aux) 229 { 230 return !(aux->map_key_state & BPF_MAP_KEY_SEEN); 231 } 232 233 static u64 bpf_map_key_immediate(const struct bpf_insn_aux_data *aux) 234 { 235 return aux->map_key_state & ~(BPF_MAP_KEY_SEEN | BPF_MAP_KEY_POISON); 236 } 237 238 static void bpf_map_key_store(struct bpf_insn_aux_data *aux, u64 state) 239 { 240 bool poisoned = bpf_map_key_poisoned(aux); 241 242 aux->map_key_state = state | BPF_MAP_KEY_SEEN | 243 (poisoned ? BPF_MAP_KEY_POISON : 0ULL); 244 } 245 246 static bool bpf_helper_call(const struct bpf_insn *insn) 247 { 248 return insn->code == (BPF_JMP | BPF_CALL) && 249 insn->src_reg == 0; 250 } 251 252 static bool bpf_pseudo_call(const struct bpf_insn *insn) 253 { 254 return insn->code == (BPF_JMP | BPF_CALL) && 255 insn->src_reg == BPF_PSEUDO_CALL; 256 } 257 258 static bool bpf_pseudo_kfunc_call(const struct bpf_insn *insn) 259 { 260 return insn->code == (BPF_JMP | BPF_CALL) && 261 insn->src_reg == BPF_PSEUDO_KFUNC_CALL; 262 } 263 264 struct bpf_call_arg_meta { 265 struct bpf_map *map_ptr; 266 bool raw_mode; 267 bool pkt_access; 268 u8 release_regno; 269 int regno; 270 int access_size; 271 int mem_size; 272 u64 msize_max_value; 273 int ref_obj_id; 274 int dynptr_id; 275 int map_uid; 276 int func_id; 277 struct btf *btf; 278 u32 btf_id; 279 struct btf *ret_btf; 280 u32 ret_btf_id; 281 u32 subprogno; 282 struct btf_field *kptr_field; 283 }; 284 285 struct bpf_kfunc_call_arg_meta { 286 /* In parameters */ 287 struct btf *btf; 288 u32 func_id; 289 u32 kfunc_flags; 290 const struct btf_type *func_proto; 291 const char *func_name; 292 /* Out parameters */ 293 u32 ref_obj_id; 294 u8 release_regno; 295 bool r0_rdonly; 296 u32 ret_btf_id; 297 u64 r0_size; 298 u32 subprogno; 299 struct { 300 u64 value; 301 bool found; 302 } arg_constant; 303 304 /* arg_{btf,btf_id,owning_ref} are used by kfunc-specific handling, 305 * generally to pass info about user-defined local kptr types to later 306 * verification logic 307 * bpf_obj_drop 308 * Record the local kptr type to be drop'd 309 * bpf_refcount_acquire (via KF_ARG_PTR_TO_REFCOUNTED_KPTR arg type) 310 * Record the local kptr type to be refcount_incr'd and use 311 * arg_owning_ref to determine whether refcount_acquire should be 312 * fallible 313 */ 314 struct btf *arg_btf; 315 u32 arg_btf_id; 316 bool arg_owning_ref; 317 318 struct { 319 struct btf_field *field; 320 } arg_list_head; 321 struct { 322 struct btf_field *field; 323 } arg_rbtree_root; 324 struct { 325 enum bpf_dynptr_type type; 326 u32 id; 327 u32 ref_obj_id; 328 } initialized_dynptr; 329 struct { 330 u8 spi; 331 u8 frameno; 332 } iter; 333 u64 mem_size; 334 }; 335 336 struct btf *btf_vmlinux; 337 338 static DEFINE_MUTEX(bpf_verifier_lock); 339 340 static const struct bpf_line_info * 341 find_linfo(const struct bpf_verifier_env *env, u32 insn_off) 342 { 343 const struct bpf_line_info *linfo; 344 const struct bpf_prog *prog; 345 u32 i, nr_linfo; 346 347 prog = env->prog; 348 nr_linfo = prog->aux->nr_linfo; 349 350 if (!nr_linfo || insn_off >= prog->len) 351 return NULL; 352 353 linfo = prog->aux->linfo; 354 for (i = 1; i < nr_linfo; i++) 355 if (insn_off < linfo[i].insn_off) 356 break; 357 358 return &linfo[i - 1]; 359 } 360 361 __printf(2, 3) static void verbose(void *private_data, const char *fmt, ...) 362 { 363 struct bpf_verifier_env *env = private_data; 364 va_list args; 365 366 if (!bpf_verifier_log_needed(&env->log)) 367 return; 368 369 va_start(args, fmt); 370 bpf_verifier_vlog(&env->log, fmt, args); 371 va_end(args); 372 } 373 374 static const char *ltrim(const char *s) 375 { 376 while (isspace(*s)) 377 s++; 378 379 return s; 380 } 381 382 __printf(3, 4) static void verbose_linfo(struct bpf_verifier_env *env, 383 u32 insn_off, 384 const char *prefix_fmt, ...) 385 { 386 const struct bpf_line_info *linfo; 387 388 if (!bpf_verifier_log_needed(&env->log)) 389 return; 390 391 linfo = find_linfo(env, insn_off); 392 if (!linfo || linfo == env->prev_linfo) 393 return; 394 395 if (prefix_fmt) { 396 va_list args; 397 398 va_start(args, prefix_fmt); 399 bpf_verifier_vlog(&env->log, prefix_fmt, args); 400 va_end(args); 401 } 402 403 verbose(env, "%s\n", 404 ltrim(btf_name_by_offset(env->prog->aux->btf, 405 linfo->line_off))); 406 407 env->prev_linfo = linfo; 408 } 409 410 static void verbose_invalid_scalar(struct bpf_verifier_env *env, 411 struct bpf_reg_state *reg, 412 struct tnum *range, const char *ctx, 413 const char *reg_name) 414 { 415 char tn_buf[48]; 416 417 verbose(env, "At %s the register %s ", ctx, reg_name); 418 if (!tnum_is_unknown(reg->var_off)) { 419 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 420 verbose(env, "has value %s", tn_buf); 421 } else { 422 verbose(env, "has unknown scalar value"); 423 } 424 tnum_strn(tn_buf, sizeof(tn_buf), *range); 425 verbose(env, " should have been in %s\n", tn_buf); 426 } 427 428 static bool type_is_pkt_pointer(enum bpf_reg_type type) 429 { 430 type = base_type(type); 431 return type == PTR_TO_PACKET || 432 type == PTR_TO_PACKET_META; 433 } 434 435 static bool type_is_sk_pointer(enum bpf_reg_type type) 436 { 437 return type == PTR_TO_SOCKET || 438 type == PTR_TO_SOCK_COMMON || 439 type == PTR_TO_TCP_SOCK || 440 type == PTR_TO_XDP_SOCK; 441 } 442 443 static bool type_may_be_null(u32 type) 444 { 445 return type & PTR_MAYBE_NULL; 446 } 447 448 static bool reg_not_null(const struct bpf_reg_state *reg) 449 { 450 enum bpf_reg_type type; 451 452 type = reg->type; 453 if (type_may_be_null(type)) 454 return false; 455 456 type = base_type(type); 457 return type == PTR_TO_SOCKET || 458 type == PTR_TO_TCP_SOCK || 459 type == PTR_TO_MAP_VALUE || 460 type == PTR_TO_MAP_KEY || 461 type == PTR_TO_SOCK_COMMON || 462 (type == PTR_TO_BTF_ID && is_trusted_reg(reg)) || 463 type == PTR_TO_MEM; 464 } 465 466 static bool type_is_ptr_alloc_obj(u32 type) 467 { 468 return base_type(type) == PTR_TO_BTF_ID && type_flag(type) & MEM_ALLOC; 469 } 470 471 static bool type_is_non_owning_ref(u32 type) 472 { 473 return type_is_ptr_alloc_obj(type) && type_flag(type) & NON_OWN_REF; 474 } 475 476 static struct btf_record *reg_btf_record(const struct bpf_reg_state *reg) 477 { 478 struct btf_record *rec = NULL; 479 struct btf_struct_meta *meta; 480 481 if (reg->type == PTR_TO_MAP_VALUE) { 482 rec = reg->map_ptr->record; 483 } else if (type_is_ptr_alloc_obj(reg->type)) { 484 meta = btf_find_struct_meta(reg->btf, reg->btf_id); 485 if (meta) 486 rec = meta->record; 487 } 488 return rec; 489 } 490 491 static bool subprog_is_global(const struct bpf_verifier_env *env, int subprog) 492 { 493 struct bpf_func_info_aux *aux = env->prog->aux->func_info_aux; 494 495 return aux && aux[subprog].linkage == BTF_FUNC_GLOBAL; 496 } 497 498 static bool reg_may_point_to_spin_lock(const struct bpf_reg_state *reg) 499 { 500 return btf_record_has_field(reg_btf_record(reg), BPF_SPIN_LOCK); 501 } 502 503 static bool type_is_rdonly_mem(u32 type) 504 { 505 return type & MEM_RDONLY; 506 } 507 508 static bool is_acquire_function(enum bpf_func_id func_id, 509 const struct bpf_map *map) 510 { 511 enum bpf_map_type map_type = map ? map->map_type : BPF_MAP_TYPE_UNSPEC; 512 513 if (func_id == BPF_FUNC_sk_lookup_tcp || 514 func_id == BPF_FUNC_sk_lookup_udp || 515 func_id == BPF_FUNC_skc_lookup_tcp || 516 func_id == BPF_FUNC_ringbuf_reserve || 517 func_id == BPF_FUNC_kptr_xchg) 518 return true; 519 520 if (func_id == BPF_FUNC_map_lookup_elem && 521 (map_type == BPF_MAP_TYPE_SOCKMAP || 522 map_type == BPF_MAP_TYPE_SOCKHASH)) 523 return true; 524 525 return false; 526 } 527 528 static bool is_ptr_cast_function(enum bpf_func_id func_id) 529 { 530 return func_id == BPF_FUNC_tcp_sock || 531 func_id == BPF_FUNC_sk_fullsock || 532 func_id == BPF_FUNC_skc_to_tcp_sock || 533 func_id == BPF_FUNC_skc_to_tcp6_sock || 534 func_id == BPF_FUNC_skc_to_udp6_sock || 535 func_id == BPF_FUNC_skc_to_mptcp_sock || 536 func_id == BPF_FUNC_skc_to_tcp_timewait_sock || 537 func_id == BPF_FUNC_skc_to_tcp_request_sock; 538 } 539 540 static bool is_dynptr_ref_function(enum bpf_func_id func_id) 541 { 542 return func_id == BPF_FUNC_dynptr_data; 543 } 544 545 static bool is_callback_calling_kfunc(u32 btf_id); 546 547 static bool is_callback_calling_function(enum bpf_func_id func_id) 548 { 549 return func_id == BPF_FUNC_for_each_map_elem || 550 func_id == BPF_FUNC_timer_set_callback || 551 func_id == BPF_FUNC_find_vma || 552 func_id == BPF_FUNC_loop || 553 func_id == BPF_FUNC_user_ringbuf_drain; 554 } 555 556 static bool is_async_callback_calling_function(enum bpf_func_id func_id) 557 { 558 return func_id == BPF_FUNC_timer_set_callback; 559 } 560 561 static bool is_storage_get_function(enum bpf_func_id func_id) 562 { 563 return func_id == BPF_FUNC_sk_storage_get || 564 func_id == BPF_FUNC_inode_storage_get || 565 func_id == BPF_FUNC_task_storage_get || 566 func_id == BPF_FUNC_cgrp_storage_get; 567 } 568 569 static bool helper_multiple_ref_obj_use(enum bpf_func_id func_id, 570 const struct bpf_map *map) 571 { 572 int ref_obj_uses = 0; 573 574 if (is_ptr_cast_function(func_id)) 575 ref_obj_uses++; 576 if (is_acquire_function(func_id, map)) 577 ref_obj_uses++; 578 if (is_dynptr_ref_function(func_id)) 579 ref_obj_uses++; 580 581 return ref_obj_uses > 1; 582 } 583 584 static bool is_cmpxchg_insn(const struct bpf_insn *insn) 585 { 586 return BPF_CLASS(insn->code) == BPF_STX && 587 BPF_MODE(insn->code) == BPF_ATOMIC && 588 insn->imm == BPF_CMPXCHG; 589 } 590 591 /* string representation of 'enum bpf_reg_type' 592 * 593 * Note that reg_type_str() can not appear more than once in a single verbose() 594 * statement. 595 */ 596 static const char *reg_type_str(struct bpf_verifier_env *env, 597 enum bpf_reg_type type) 598 { 599 char postfix[16] = {0}, prefix[64] = {0}; 600 static const char * const str[] = { 601 [NOT_INIT] = "?", 602 [SCALAR_VALUE] = "scalar", 603 [PTR_TO_CTX] = "ctx", 604 [CONST_PTR_TO_MAP] = "map_ptr", 605 [PTR_TO_MAP_VALUE] = "map_value", 606 [PTR_TO_STACK] = "fp", 607 [PTR_TO_PACKET] = "pkt", 608 [PTR_TO_PACKET_META] = "pkt_meta", 609 [PTR_TO_PACKET_END] = "pkt_end", 610 [PTR_TO_FLOW_KEYS] = "flow_keys", 611 [PTR_TO_SOCKET] = "sock", 612 [PTR_TO_SOCK_COMMON] = "sock_common", 613 [PTR_TO_TCP_SOCK] = "tcp_sock", 614 [PTR_TO_TP_BUFFER] = "tp_buffer", 615 [PTR_TO_XDP_SOCK] = "xdp_sock", 616 [PTR_TO_BTF_ID] = "ptr_", 617 [PTR_TO_MEM] = "mem", 618 [PTR_TO_BUF] = "buf", 619 [PTR_TO_FUNC] = "func", 620 [PTR_TO_MAP_KEY] = "map_key", 621 [CONST_PTR_TO_DYNPTR] = "dynptr_ptr", 622 }; 623 624 if (type & PTR_MAYBE_NULL) { 625 if (base_type(type) == PTR_TO_BTF_ID) 626 strncpy(postfix, "or_null_", 16); 627 else 628 strncpy(postfix, "_or_null", 16); 629 } 630 631 snprintf(prefix, sizeof(prefix), "%s%s%s%s%s%s%s", 632 type & MEM_RDONLY ? "rdonly_" : "", 633 type & MEM_RINGBUF ? "ringbuf_" : "", 634 type & MEM_USER ? "user_" : "", 635 type & MEM_PERCPU ? "percpu_" : "", 636 type & MEM_RCU ? "rcu_" : "", 637 type & PTR_UNTRUSTED ? "untrusted_" : "", 638 type & PTR_TRUSTED ? "trusted_" : "" 639 ); 640 641 snprintf(env->tmp_str_buf, TMP_STR_BUF_LEN, "%s%s%s", 642 prefix, str[base_type(type)], postfix); 643 return env->tmp_str_buf; 644 } 645 646 static char slot_type_char[] = { 647 [STACK_INVALID] = '?', 648 [STACK_SPILL] = 'r', 649 [STACK_MISC] = 'm', 650 [STACK_ZERO] = '0', 651 [STACK_DYNPTR] = 'd', 652 [STACK_ITER] = 'i', 653 }; 654 655 static void print_liveness(struct bpf_verifier_env *env, 656 enum bpf_reg_liveness live) 657 { 658 if (live & (REG_LIVE_READ | REG_LIVE_WRITTEN | REG_LIVE_DONE)) 659 verbose(env, "_"); 660 if (live & REG_LIVE_READ) 661 verbose(env, "r"); 662 if (live & REG_LIVE_WRITTEN) 663 verbose(env, "w"); 664 if (live & REG_LIVE_DONE) 665 verbose(env, "D"); 666 } 667 668 static int __get_spi(s32 off) 669 { 670 return (-off - 1) / BPF_REG_SIZE; 671 } 672 673 static struct bpf_func_state *func(struct bpf_verifier_env *env, 674 const struct bpf_reg_state *reg) 675 { 676 struct bpf_verifier_state *cur = env->cur_state; 677 678 return cur->frame[reg->frameno]; 679 } 680 681 static bool is_spi_bounds_valid(struct bpf_func_state *state, int spi, int nr_slots) 682 { 683 int allocated_slots = state->allocated_stack / BPF_REG_SIZE; 684 685 /* We need to check that slots between [spi - nr_slots + 1, spi] are 686 * within [0, allocated_stack). 687 * 688 * Please note that the spi grows downwards. For example, a dynptr 689 * takes the size of two stack slots; the first slot will be at 690 * spi and the second slot will be at spi - 1. 691 */ 692 return spi - nr_slots + 1 >= 0 && spi < allocated_slots; 693 } 694 695 static int stack_slot_obj_get_spi(struct bpf_verifier_env *env, struct bpf_reg_state *reg, 696 const char *obj_kind, int nr_slots) 697 { 698 int off, spi; 699 700 if (!tnum_is_const(reg->var_off)) { 701 verbose(env, "%s has to be at a constant offset\n", obj_kind); 702 return -EINVAL; 703 } 704 705 off = reg->off + reg->var_off.value; 706 if (off % BPF_REG_SIZE) { 707 verbose(env, "cannot pass in %s at an offset=%d\n", obj_kind, off); 708 return -EINVAL; 709 } 710 711 spi = __get_spi(off); 712 if (spi + 1 < nr_slots) { 713 verbose(env, "cannot pass in %s at an offset=%d\n", obj_kind, off); 714 return -EINVAL; 715 } 716 717 if (!is_spi_bounds_valid(func(env, reg), spi, nr_slots)) 718 return -ERANGE; 719 return spi; 720 } 721 722 static int dynptr_get_spi(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 723 { 724 return stack_slot_obj_get_spi(env, reg, "dynptr", BPF_DYNPTR_NR_SLOTS); 725 } 726 727 static int iter_get_spi(struct bpf_verifier_env *env, struct bpf_reg_state *reg, int nr_slots) 728 { 729 return stack_slot_obj_get_spi(env, reg, "iter", nr_slots); 730 } 731 732 static const char *btf_type_name(const struct btf *btf, u32 id) 733 { 734 return btf_name_by_offset(btf, btf_type_by_id(btf, id)->name_off); 735 } 736 737 static const char *dynptr_type_str(enum bpf_dynptr_type type) 738 { 739 switch (type) { 740 case BPF_DYNPTR_TYPE_LOCAL: 741 return "local"; 742 case BPF_DYNPTR_TYPE_RINGBUF: 743 return "ringbuf"; 744 case BPF_DYNPTR_TYPE_SKB: 745 return "skb"; 746 case BPF_DYNPTR_TYPE_XDP: 747 return "xdp"; 748 case BPF_DYNPTR_TYPE_INVALID: 749 return "<invalid>"; 750 default: 751 WARN_ONCE(1, "unknown dynptr type %d\n", type); 752 return "<unknown>"; 753 } 754 } 755 756 static const char *iter_type_str(const struct btf *btf, u32 btf_id) 757 { 758 if (!btf || btf_id == 0) 759 return "<invalid>"; 760 761 /* we already validated that type is valid and has conforming name */ 762 return btf_type_name(btf, btf_id) + sizeof(ITER_PREFIX) - 1; 763 } 764 765 static const char *iter_state_str(enum bpf_iter_state state) 766 { 767 switch (state) { 768 case BPF_ITER_STATE_ACTIVE: 769 return "active"; 770 case BPF_ITER_STATE_DRAINED: 771 return "drained"; 772 case BPF_ITER_STATE_INVALID: 773 return "<invalid>"; 774 default: 775 WARN_ONCE(1, "unknown iter state %d\n", state); 776 return "<unknown>"; 777 } 778 } 779 780 static void mark_reg_scratched(struct bpf_verifier_env *env, u32 regno) 781 { 782 env->scratched_regs |= 1U << regno; 783 } 784 785 static void mark_stack_slot_scratched(struct bpf_verifier_env *env, u32 spi) 786 { 787 env->scratched_stack_slots |= 1ULL << spi; 788 } 789 790 static bool reg_scratched(const struct bpf_verifier_env *env, u32 regno) 791 { 792 return (env->scratched_regs >> regno) & 1; 793 } 794 795 static bool stack_slot_scratched(const struct bpf_verifier_env *env, u64 regno) 796 { 797 return (env->scratched_stack_slots >> regno) & 1; 798 } 799 800 static bool verifier_state_scratched(const struct bpf_verifier_env *env) 801 { 802 return env->scratched_regs || env->scratched_stack_slots; 803 } 804 805 static void mark_verifier_state_clean(struct bpf_verifier_env *env) 806 { 807 env->scratched_regs = 0U; 808 env->scratched_stack_slots = 0ULL; 809 } 810 811 /* Used for printing the entire verifier state. */ 812 static void mark_verifier_state_scratched(struct bpf_verifier_env *env) 813 { 814 env->scratched_regs = ~0U; 815 env->scratched_stack_slots = ~0ULL; 816 } 817 818 static enum bpf_dynptr_type arg_to_dynptr_type(enum bpf_arg_type arg_type) 819 { 820 switch (arg_type & DYNPTR_TYPE_FLAG_MASK) { 821 case DYNPTR_TYPE_LOCAL: 822 return BPF_DYNPTR_TYPE_LOCAL; 823 case DYNPTR_TYPE_RINGBUF: 824 return BPF_DYNPTR_TYPE_RINGBUF; 825 case DYNPTR_TYPE_SKB: 826 return BPF_DYNPTR_TYPE_SKB; 827 case DYNPTR_TYPE_XDP: 828 return BPF_DYNPTR_TYPE_XDP; 829 default: 830 return BPF_DYNPTR_TYPE_INVALID; 831 } 832 } 833 834 static enum bpf_type_flag get_dynptr_type_flag(enum bpf_dynptr_type type) 835 { 836 switch (type) { 837 case BPF_DYNPTR_TYPE_LOCAL: 838 return DYNPTR_TYPE_LOCAL; 839 case BPF_DYNPTR_TYPE_RINGBUF: 840 return DYNPTR_TYPE_RINGBUF; 841 case BPF_DYNPTR_TYPE_SKB: 842 return DYNPTR_TYPE_SKB; 843 case BPF_DYNPTR_TYPE_XDP: 844 return DYNPTR_TYPE_XDP; 845 default: 846 return 0; 847 } 848 } 849 850 static bool dynptr_type_refcounted(enum bpf_dynptr_type type) 851 { 852 return type == BPF_DYNPTR_TYPE_RINGBUF; 853 } 854 855 static void __mark_dynptr_reg(struct bpf_reg_state *reg, 856 enum bpf_dynptr_type type, 857 bool first_slot, int dynptr_id); 858 859 static void __mark_reg_not_init(const struct bpf_verifier_env *env, 860 struct bpf_reg_state *reg); 861 862 static void mark_dynptr_stack_regs(struct bpf_verifier_env *env, 863 struct bpf_reg_state *sreg1, 864 struct bpf_reg_state *sreg2, 865 enum bpf_dynptr_type type) 866 { 867 int id = ++env->id_gen; 868 869 __mark_dynptr_reg(sreg1, type, true, id); 870 __mark_dynptr_reg(sreg2, type, false, id); 871 } 872 873 static void mark_dynptr_cb_reg(struct bpf_verifier_env *env, 874 struct bpf_reg_state *reg, 875 enum bpf_dynptr_type type) 876 { 877 __mark_dynptr_reg(reg, type, true, ++env->id_gen); 878 } 879 880 static int destroy_if_dynptr_stack_slot(struct bpf_verifier_env *env, 881 struct bpf_func_state *state, int spi); 882 883 static int mark_stack_slots_dynptr(struct bpf_verifier_env *env, struct bpf_reg_state *reg, 884 enum bpf_arg_type arg_type, int insn_idx, int clone_ref_obj_id) 885 { 886 struct bpf_func_state *state = func(env, reg); 887 enum bpf_dynptr_type type; 888 int spi, i, err; 889 890 spi = dynptr_get_spi(env, reg); 891 if (spi < 0) 892 return spi; 893 894 /* We cannot assume both spi and spi - 1 belong to the same dynptr, 895 * hence we need to call destroy_if_dynptr_stack_slot twice for both, 896 * to ensure that for the following example: 897 * [d1][d1][d2][d2] 898 * spi 3 2 1 0 899 * So marking spi = 2 should lead to destruction of both d1 and d2. In 900 * case they do belong to same dynptr, second call won't see slot_type 901 * as STACK_DYNPTR and will simply skip destruction. 902 */ 903 err = destroy_if_dynptr_stack_slot(env, state, spi); 904 if (err) 905 return err; 906 err = destroy_if_dynptr_stack_slot(env, state, spi - 1); 907 if (err) 908 return err; 909 910 for (i = 0; i < BPF_REG_SIZE; i++) { 911 state->stack[spi].slot_type[i] = STACK_DYNPTR; 912 state->stack[spi - 1].slot_type[i] = STACK_DYNPTR; 913 } 914 915 type = arg_to_dynptr_type(arg_type); 916 if (type == BPF_DYNPTR_TYPE_INVALID) 917 return -EINVAL; 918 919 mark_dynptr_stack_regs(env, &state->stack[spi].spilled_ptr, 920 &state->stack[spi - 1].spilled_ptr, type); 921 922 if (dynptr_type_refcounted(type)) { 923 /* The id is used to track proper releasing */ 924 int id; 925 926 if (clone_ref_obj_id) 927 id = clone_ref_obj_id; 928 else 929 id = acquire_reference_state(env, insn_idx); 930 931 if (id < 0) 932 return id; 933 934 state->stack[spi].spilled_ptr.ref_obj_id = id; 935 state->stack[spi - 1].spilled_ptr.ref_obj_id = id; 936 } 937 938 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN; 939 state->stack[spi - 1].spilled_ptr.live |= REG_LIVE_WRITTEN; 940 941 return 0; 942 } 943 944 static void invalidate_dynptr(struct bpf_verifier_env *env, struct bpf_func_state *state, int spi) 945 { 946 int i; 947 948 for (i = 0; i < BPF_REG_SIZE; i++) { 949 state->stack[spi].slot_type[i] = STACK_INVALID; 950 state->stack[spi - 1].slot_type[i] = STACK_INVALID; 951 } 952 953 __mark_reg_not_init(env, &state->stack[spi].spilled_ptr); 954 __mark_reg_not_init(env, &state->stack[spi - 1].spilled_ptr); 955 956 /* Why do we need to set REG_LIVE_WRITTEN for STACK_INVALID slot? 957 * 958 * While we don't allow reading STACK_INVALID, it is still possible to 959 * do <8 byte writes marking some but not all slots as STACK_MISC. Then, 960 * helpers or insns can do partial read of that part without failing, 961 * but check_stack_range_initialized, check_stack_read_var_off, and 962 * check_stack_read_fixed_off will do mark_reg_read for all 8-bytes of 963 * the slot conservatively. Hence we need to prevent those liveness 964 * marking walks. 965 * 966 * This was not a problem before because STACK_INVALID is only set by 967 * default (where the default reg state has its reg->parent as NULL), or 968 * in clean_live_states after REG_LIVE_DONE (at which point 969 * mark_reg_read won't walk reg->parent chain), but not randomly during 970 * verifier state exploration (like we did above). Hence, for our case 971 * parentage chain will still be live (i.e. reg->parent may be 972 * non-NULL), while earlier reg->parent was NULL, so we need 973 * REG_LIVE_WRITTEN to screen off read marker propagation when it is 974 * done later on reads or by mark_dynptr_read as well to unnecessary 975 * mark registers in verifier state. 976 */ 977 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN; 978 state->stack[spi - 1].spilled_ptr.live |= REG_LIVE_WRITTEN; 979 } 980 981 static int unmark_stack_slots_dynptr(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 982 { 983 struct bpf_func_state *state = func(env, reg); 984 int spi, ref_obj_id, i; 985 986 spi = dynptr_get_spi(env, reg); 987 if (spi < 0) 988 return spi; 989 990 if (!dynptr_type_refcounted(state->stack[spi].spilled_ptr.dynptr.type)) { 991 invalidate_dynptr(env, state, spi); 992 return 0; 993 } 994 995 ref_obj_id = state->stack[spi].spilled_ptr.ref_obj_id; 996 997 /* If the dynptr has a ref_obj_id, then we need to invalidate 998 * two things: 999 * 1000 * 1) Any dynptrs with a matching ref_obj_id (clones) 1001 * 2) Any slices derived from this dynptr. 1002 */ 1003 1004 /* Invalidate any slices associated with this dynptr */ 1005 WARN_ON_ONCE(release_reference(env, ref_obj_id)); 1006 1007 /* Invalidate any dynptr clones */ 1008 for (i = 1; i < state->allocated_stack / BPF_REG_SIZE; i++) { 1009 if (state->stack[i].spilled_ptr.ref_obj_id != ref_obj_id) 1010 continue; 1011 1012 /* it should always be the case that if the ref obj id 1013 * matches then the stack slot also belongs to a 1014 * dynptr 1015 */ 1016 if (state->stack[i].slot_type[0] != STACK_DYNPTR) { 1017 verbose(env, "verifier internal error: misconfigured ref_obj_id\n"); 1018 return -EFAULT; 1019 } 1020 if (state->stack[i].spilled_ptr.dynptr.first_slot) 1021 invalidate_dynptr(env, state, i); 1022 } 1023 1024 return 0; 1025 } 1026 1027 static void __mark_reg_unknown(const struct bpf_verifier_env *env, 1028 struct bpf_reg_state *reg); 1029 1030 static void mark_reg_invalid(const struct bpf_verifier_env *env, struct bpf_reg_state *reg) 1031 { 1032 if (!env->allow_ptr_leaks) 1033 __mark_reg_not_init(env, reg); 1034 else 1035 __mark_reg_unknown(env, reg); 1036 } 1037 1038 static int destroy_if_dynptr_stack_slot(struct bpf_verifier_env *env, 1039 struct bpf_func_state *state, int spi) 1040 { 1041 struct bpf_func_state *fstate; 1042 struct bpf_reg_state *dreg; 1043 int i, dynptr_id; 1044 1045 /* We always ensure that STACK_DYNPTR is never set partially, 1046 * hence just checking for slot_type[0] is enough. This is 1047 * different for STACK_SPILL, where it may be only set for 1048 * 1 byte, so code has to use is_spilled_reg. 1049 */ 1050 if (state->stack[spi].slot_type[0] != STACK_DYNPTR) 1051 return 0; 1052 1053 /* Reposition spi to first slot */ 1054 if (!state->stack[spi].spilled_ptr.dynptr.first_slot) 1055 spi = spi + 1; 1056 1057 if (dynptr_type_refcounted(state->stack[spi].spilled_ptr.dynptr.type)) { 1058 verbose(env, "cannot overwrite referenced dynptr\n"); 1059 return -EINVAL; 1060 } 1061 1062 mark_stack_slot_scratched(env, spi); 1063 mark_stack_slot_scratched(env, spi - 1); 1064 1065 /* Writing partially to one dynptr stack slot destroys both. */ 1066 for (i = 0; i < BPF_REG_SIZE; i++) { 1067 state->stack[spi].slot_type[i] = STACK_INVALID; 1068 state->stack[spi - 1].slot_type[i] = STACK_INVALID; 1069 } 1070 1071 dynptr_id = state->stack[spi].spilled_ptr.id; 1072 /* Invalidate any slices associated with this dynptr */ 1073 bpf_for_each_reg_in_vstate(env->cur_state, fstate, dreg, ({ 1074 /* Dynptr slices are only PTR_TO_MEM_OR_NULL and PTR_TO_MEM */ 1075 if (dreg->type != (PTR_TO_MEM | PTR_MAYBE_NULL) && dreg->type != PTR_TO_MEM) 1076 continue; 1077 if (dreg->dynptr_id == dynptr_id) 1078 mark_reg_invalid(env, dreg); 1079 })); 1080 1081 /* Do not release reference state, we are destroying dynptr on stack, 1082 * not using some helper to release it. Just reset register. 1083 */ 1084 __mark_reg_not_init(env, &state->stack[spi].spilled_ptr); 1085 __mark_reg_not_init(env, &state->stack[spi - 1].spilled_ptr); 1086 1087 /* Same reason as unmark_stack_slots_dynptr above */ 1088 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN; 1089 state->stack[spi - 1].spilled_ptr.live |= REG_LIVE_WRITTEN; 1090 1091 return 0; 1092 } 1093 1094 static bool is_dynptr_reg_valid_uninit(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 1095 { 1096 int spi; 1097 1098 if (reg->type == CONST_PTR_TO_DYNPTR) 1099 return false; 1100 1101 spi = dynptr_get_spi(env, reg); 1102 1103 /* -ERANGE (i.e. spi not falling into allocated stack slots) isn't an 1104 * error because this just means the stack state hasn't been updated yet. 1105 * We will do check_mem_access to check and update stack bounds later. 1106 */ 1107 if (spi < 0 && spi != -ERANGE) 1108 return false; 1109 1110 /* We don't need to check if the stack slots are marked by previous 1111 * dynptr initializations because we allow overwriting existing unreferenced 1112 * STACK_DYNPTR slots, see mark_stack_slots_dynptr which calls 1113 * destroy_if_dynptr_stack_slot to ensure dynptr objects at the slots we are 1114 * touching are completely destructed before we reinitialize them for a new 1115 * one. For referenced ones, destroy_if_dynptr_stack_slot returns an error early 1116 * instead of delaying it until the end where the user will get "Unreleased 1117 * reference" error. 1118 */ 1119 return true; 1120 } 1121 1122 static bool is_dynptr_reg_valid_init(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 1123 { 1124 struct bpf_func_state *state = func(env, reg); 1125 int i, spi; 1126 1127 /* This already represents first slot of initialized bpf_dynptr. 1128 * 1129 * CONST_PTR_TO_DYNPTR already has fixed and var_off as 0 due to 1130 * check_func_arg_reg_off's logic, so we don't need to check its 1131 * offset and alignment. 1132 */ 1133 if (reg->type == CONST_PTR_TO_DYNPTR) 1134 return true; 1135 1136 spi = dynptr_get_spi(env, reg); 1137 if (spi < 0) 1138 return false; 1139 if (!state->stack[spi].spilled_ptr.dynptr.first_slot) 1140 return false; 1141 1142 for (i = 0; i < BPF_REG_SIZE; i++) { 1143 if (state->stack[spi].slot_type[i] != STACK_DYNPTR || 1144 state->stack[spi - 1].slot_type[i] != STACK_DYNPTR) 1145 return false; 1146 } 1147 1148 return true; 1149 } 1150 1151 static bool is_dynptr_type_expected(struct bpf_verifier_env *env, struct bpf_reg_state *reg, 1152 enum bpf_arg_type arg_type) 1153 { 1154 struct bpf_func_state *state = func(env, reg); 1155 enum bpf_dynptr_type dynptr_type; 1156 int spi; 1157 1158 /* ARG_PTR_TO_DYNPTR takes any type of dynptr */ 1159 if (arg_type == ARG_PTR_TO_DYNPTR) 1160 return true; 1161 1162 dynptr_type = arg_to_dynptr_type(arg_type); 1163 if (reg->type == CONST_PTR_TO_DYNPTR) { 1164 return reg->dynptr.type == dynptr_type; 1165 } else { 1166 spi = dynptr_get_spi(env, reg); 1167 if (spi < 0) 1168 return false; 1169 return state->stack[spi].spilled_ptr.dynptr.type == dynptr_type; 1170 } 1171 } 1172 1173 static void __mark_reg_known_zero(struct bpf_reg_state *reg); 1174 1175 static int mark_stack_slots_iter(struct bpf_verifier_env *env, 1176 struct bpf_reg_state *reg, int insn_idx, 1177 struct btf *btf, u32 btf_id, int nr_slots) 1178 { 1179 struct bpf_func_state *state = func(env, reg); 1180 int spi, i, j, id; 1181 1182 spi = iter_get_spi(env, reg, nr_slots); 1183 if (spi < 0) 1184 return spi; 1185 1186 id = acquire_reference_state(env, insn_idx); 1187 if (id < 0) 1188 return id; 1189 1190 for (i = 0; i < nr_slots; i++) { 1191 struct bpf_stack_state *slot = &state->stack[spi - i]; 1192 struct bpf_reg_state *st = &slot->spilled_ptr; 1193 1194 __mark_reg_known_zero(st); 1195 st->type = PTR_TO_STACK; /* we don't have dedicated reg type */ 1196 st->live |= REG_LIVE_WRITTEN; 1197 st->ref_obj_id = i == 0 ? id : 0; 1198 st->iter.btf = btf; 1199 st->iter.btf_id = btf_id; 1200 st->iter.state = BPF_ITER_STATE_ACTIVE; 1201 st->iter.depth = 0; 1202 1203 for (j = 0; j < BPF_REG_SIZE; j++) 1204 slot->slot_type[j] = STACK_ITER; 1205 1206 mark_stack_slot_scratched(env, spi - i); 1207 } 1208 1209 return 0; 1210 } 1211 1212 static int unmark_stack_slots_iter(struct bpf_verifier_env *env, 1213 struct bpf_reg_state *reg, int nr_slots) 1214 { 1215 struct bpf_func_state *state = func(env, reg); 1216 int spi, i, j; 1217 1218 spi = iter_get_spi(env, reg, nr_slots); 1219 if (spi < 0) 1220 return spi; 1221 1222 for (i = 0; i < nr_slots; i++) { 1223 struct bpf_stack_state *slot = &state->stack[spi - i]; 1224 struct bpf_reg_state *st = &slot->spilled_ptr; 1225 1226 if (i == 0) 1227 WARN_ON_ONCE(release_reference(env, st->ref_obj_id)); 1228 1229 __mark_reg_not_init(env, st); 1230 1231 /* see unmark_stack_slots_dynptr() for why we need to set REG_LIVE_WRITTEN */ 1232 st->live |= REG_LIVE_WRITTEN; 1233 1234 for (j = 0; j < BPF_REG_SIZE; j++) 1235 slot->slot_type[j] = STACK_INVALID; 1236 1237 mark_stack_slot_scratched(env, spi - i); 1238 } 1239 1240 return 0; 1241 } 1242 1243 static bool is_iter_reg_valid_uninit(struct bpf_verifier_env *env, 1244 struct bpf_reg_state *reg, int nr_slots) 1245 { 1246 struct bpf_func_state *state = func(env, reg); 1247 int spi, i, j; 1248 1249 /* For -ERANGE (i.e. spi not falling into allocated stack slots), we 1250 * will do check_mem_access to check and update stack bounds later, so 1251 * return true for that case. 1252 */ 1253 spi = iter_get_spi(env, reg, nr_slots); 1254 if (spi == -ERANGE) 1255 return true; 1256 if (spi < 0) 1257 return false; 1258 1259 for (i = 0; i < nr_slots; i++) { 1260 struct bpf_stack_state *slot = &state->stack[spi - i]; 1261 1262 for (j = 0; j < BPF_REG_SIZE; j++) 1263 if (slot->slot_type[j] == STACK_ITER) 1264 return false; 1265 } 1266 1267 return true; 1268 } 1269 1270 static bool is_iter_reg_valid_init(struct bpf_verifier_env *env, struct bpf_reg_state *reg, 1271 struct btf *btf, u32 btf_id, int nr_slots) 1272 { 1273 struct bpf_func_state *state = func(env, reg); 1274 int spi, i, j; 1275 1276 spi = iter_get_spi(env, reg, nr_slots); 1277 if (spi < 0) 1278 return false; 1279 1280 for (i = 0; i < nr_slots; i++) { 1281 struct bpf_stack_state *slot = &state->stack[spi - i]; 1282 struct bpf_reg_state *st = &slot->spilled_ptr; 1283 1284 /* only main (first) slot has ref_obj_id set */ 1285 if (i == 0 && !st->ref_obj_id) 1286 return false; 1287 if (i != 0 && st->ref_obj_id) 1288 return false; 1289 if (st->iter.btf != btf || st->iter.btf_id != btf_id) 1290 return false; 1291 1292 for (j = 0; j < BPF_REG_SIZE; j++) 1293 if (slot->slot_type[j] != STACK_ITER) 1294 return false; 1295 } 1296 1297 return true; 1298 } 1299 1300 /* Check if given stack slot is "special": 1301 * - spilled register state (STACK_SPILL); 1302 * - dynptr state (STACK_DYNPTR); 1303 * - iter state (STACK_ITER). 1304 */ 1305 static bool is_stack_slot_special(const struct bpf_stack_state *stack) 1306 { 1307 enum bpf_stack_slot_type type = stack->slot_type[BPF_REG_SIZE - 1]; 1308 1309 switch (type) { 1310 case STACK_SPILL: 1311 case STACK_DYNPTR: 1312 case STACK_ITER: 1313 return true; 1314 case STACK_INVALID: 1315 case STACK_MISC: 1316 case STACK_ZERO: 1317 return false; 1318 default: 1319 WARN_ONCE(1, "unknown stack slot type %d\n", type); 1320 return true; 1321 } 1322 } 1323 1324 /* The reg state of a pointer or a bounded scalar was saved when 1325 * it was spilled to the stack. 1326 */ 1327 static bool is_spilled_reg(const struct bpf_stack_state *stack) 1328 { 1329 return stack->slot_type[BPF_REG_SIZE - 1] == STACK_SPILL; 1330 } 1331 1332 static bool is_spilled_scalar_reg(const struct bpf_stack_state *stack) 1333 { 1334 return stack->slot_type[BPF_REG_SIZE - 1] == STACK_SPILL && 1335 stack->spilled_ptr.type == SCALAR_VALUE; 1336 } 1337 1338 static void scrub_spilled_slot(u8 *stype) 1339 { 1340 if (*stype != STACK_INVALID) 1341 *stype = STACK_MISC; 1342 } 1343 1344 static void print_verifier_state(struct bpf_verifier_env *env, 1345 const struct bpf_func_state *state, 1346 bool print_all) 1347 { 1348 const struct bpf_reg_state *reg; 1349 enum bpf_reg_type t; 1350 int i; 1351 1352 if (state->frameno) 1353 verbose(env, " frame%d:", state->frameno); 1354 for (i = 0; i < MAX_BPF_REG; i++) { 1355 reg = &state->regs[i]; 1356 t = reg->type; 1357 if (t == NOT_INIT) 1358 continue; 1359 if (!print_all && !reg_scratched(env, i)) 1360 continue; 1361 verbose(env, " R%d", i); 1362 print_liveness(env, reg->live); 1363 verbose(env, "="); 1364 if (t == SCALAR_VALUE && reg->precise) 1365 verbose(env, "P"); 1366 if ((t == SCALAR_VALUE || t == PTR_TO_STACK) && 1367 tnum_is_const(reg->var_off)) { 1368 /* reg->off should be 0 for SCALAR_VALUE */ 1369 verbose(env, "%s", t == SCALAR_VALUE ? "" : reg_type_str(env, t)); 1370 verbose(env, "%lld", reg->var_off.value + reg->off); 1371 } else { 1372 const char *sep = ""; 1373 1374 verbose(env, "%s", reg_type_str(env, t)); 1375 if (base_type(t) == PTR_TO_BTF_ID) 1376 verbose(env, "%s", btf_type_name(reg->btf, reg->btf_id)); 1377 verbose(env, "("); 1378 /* 1379 * _a stands for append, was shortened to avoid multiline statements below. 1380 * This macro is used to output a comma separated list of attributes. 1381 */ 1382 #define verbose_a(fmt, ...) ({ verbose(env, "%s" fmt, sep, __VA_ARGS__); sep = ","; }) 1383 1384 if (reg->id) 1385 verbose_a("id=%d", reg->id); 1386 if (reg->ref_obj_id) 1387 verbose_a("ref_obj_id=%d", reg->ref_obj_id); 1388 if (type_is_non_owning_ref(reg->type)) 1389 verbose_a("%s", "non_own_ref"); 1390 if (t != SCALAR_VALUE) 1391 verbose_a("off=%d", reg->off); 1392 if (type_is_pkt_pointer(t)) 1393 verbose_a("r=%d", reg->range); 1394 else if (base_type(t) == CONST_PTR_TO_MAP || 1395 base_type(t) == PTR_TO_MAP_KEY || 1396 base_type(t) == PTR_TO_MAP_VALUE) 1397 verbose_a("ks=%d,vs=%d", 1398 reg->map_ptr->key_size, 1399 reg->map_ptr->value_size); 1400 if (tnum_is_const(reg->var_off)) { 1401 /* Typically an immediate SCALAR_VALUE, but 1402 * could be a pointer whose offset is too big 1403 * for reg->off 1404 */ 1405 verbose_a("imm=%llx", reg->var_off.value); 1406 } else { 1407 if (reg->smin_value != reg->umin_value && 1408 reg->smin_value != S64_MIN) 1409 verbose_a("smin=%lld", (long long)reg->smin_value); 1410 if (reg->smax_value != reg->umax_value && 1411 reg->smax_value != S64_MAX) 1412 verbose_a("smax=%lld", (long long)reg->smax_value); 1413 if (reg->umin_value != 0) 1414 verbose_a("umin=%llu", (unsigned long long)reg->umin_value); 1415 if (reg->umax_value != U64_MAX) 1416 verbose_a("umax=%llu", (unsigned long long)reg->umax_value); 1417 if (!tnum_is_unknown(reg->var_off)) { 1418 char tn_buf[48]; 1419 1420 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 1421 verbose_a("var_off=%s", tn_buf); 1422 } 1423 if (reg->s32_min_value != reg->smin_value && 1424 reg->s32_min_value != S32_MIN) 1425 verbose_a("s32_min=%d", (int)(reg->s32_min_value)); 1426 if (reg->s32_max_value != reg->smax_value && 1427 reg->s32_max_value != S32_MAX) 1428 verbose_a("s32_max=%d", (int)(reg->s32_max_value)); 1429 if (reg->u32_min_value != reg->umin_value && 1430 reg->u32_min_value != U32_MIN) 1431 verbose_a("u32_min=%d", (int)(reg->u32_min_value)); 1432 if (reg->u32_max_value != reg->umax_value && 1433 reg->u32_max_value != U32_MAX) 1434 verbose_a("u32_max=%d", (int)(reg->u32_max_value)); 1435 } 1436 #undef verbose_a 1437 1438 verbose(env, ")"); 1439 } 1440 } 1441 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) { 1442 char types_buf[BPF_REG_SIZE + 1]; 1443 bool valid = false; 1444 int j; 1445 1446 for (j = 0; j < BPF_REG_SIZE; j++) { 1447 if (state->stack[i].slot_type[j] != STACK_INVALID) 1448 valid = true; 1449 types_buf[j] = slot_type_char[state->stack[i].slot_type[j]]; 1450 } 1451 types_buf[BPF_REG_SIZE] = 0; 1452 if (!valid) 1453 continue; 1454 if (!print_all && !stack_slot_scratched(env, i)) 1455 continue; 1456 switch (state->stack[i].slot_type[BPF_REG_SIZE - 1]) { 1457 case STACK_SPILL: 1458 reg = &state->stack[i].spilled_ptr; 1459 t = reg->type; 1460 1461 verbose(env, " fp%d", (-i - 1) * BPF_REG_SIZE); 1462 print_liveness(env, reg->live); 1463 verbose(env, "=%s", t == SCALAR_VALUE ? "" : reg_type_str(env, t)); 1464 if (t == SCALAR_VALUE && reg->precise) 1465 verbose(env, "P"); 1466 if (t == SCALAR_VALUE && tnum_is_const(reg->var_off)) 1467 verbose(env, "%lld", reg->var_off.value + reg->off); 1468 break; 1469 case STACK_DYNPTR: 1470 i += BPF_DYNPTR_NR_SLOTS - 1; 1471 reg = &state->stack[i].spilled_ptr; 1472 1473 verbose(env, " fp%d", (-i - 1) * BPF_REG_SIZE); 1474 print_liveness(env, reg->live); 1475 verbose(env, "=dynptr_%s", dynptr_type_str(reg->dynptr.type)); 1476 if (reg->ref_obj_id) 1477 verbose(env, "(ref_id=%d)", reg->ref_obj_id); 1478 break; 1479 case STACK_ITER: 1480 /* only main slot has ref_obj_id set; skip others */ 1481 reg = &state->stack[i].spilled_ptr; 1482 if (!reg->ref_obj_id) 1483 continue; 1484 1485 verbose(env, " fp%d", (-i - 1) * BPF_REG_SIZE); 1486 print_liveness(env, reg->live); 1487 verbose(env, "=iter_%s(ref_id=%d,state=%s,depth=%u)", 1488 iter_type_str(reg->iter.btf, reg->iter.btf_id), 1489 reg->ref_obj_id, iter_state_str(reg->iter.state), 1490 reg->iter.depth); 1491 break; 1492 case STACK_MISC: 1493 case STACK_ZERO: 1494 default: 1495 reg = &state->stack[i].spilled_ptr; 1496 1497 for (j = 0; j < BPF_REG_SIZE; j++) 1498 types_buf[j] = slot_type_char[state->stack[i].slot_type[j]]; 1499 types_buf[BPF_REG_SIZE] = 0; 1500 1501 verbose(env, " fp%d", (-i - 1) * BPF_REG_SIZE); 1502 print_liveness(env, reg->live); 1503 verbose(env, "=%s", types_buf); 1504 break; 1505 } 1506 } 1507 if (state->acquired_refs && state->refs[0].id) { 1508 verbose(env, " refs=%d", state->refs[0].id); 1509 for (i = 1; i < state->acquired_refs; i++) 1510 if (state->refs[i].id) 1511 verbose(env, ",%d", state->refs[i].id); 1512 } 1513 if (state->in_callback_fn) 1514 verbose(env, " cb"); 1515 if (state->in_async_callback_fn) 1516 verbose(env, " async_cb"); 1517 verbose(env, "\n"); 1518 if (!print_all) 1519 mark_verifier_state_clean(env); 1520 } 1521 1522 static inline u32 vlog_alignment(u32 pos) 1523 { 1524 return round_up(max(pos + BPF_LOG_MIN_ALIGNMENT / 2, BPF_LOG_ALIGNMENT), 1525 BPF_LOG_MIN_ALIGNMENT) - pos - 1; 1526 } 1527 1528 static void print_insn_state(struct bpf_verifier_env *env, 1529 const struct bpf_func_state *state) 1530 { 1531 if (env->prev_log_pos && env->prev_log_pos == env->log.end_pos) { 1532 /* remove new line character */ 1533 bpf_vlog_reset(&env->log, env->prev_log_pos - 1); 1534 verbose(env, "%*c;", vlog_alignment(env->prev_insn_print_pos), ' '); 1535 } else { 1536 verbose(env, "%d:", env->insn_idx); 1537 } 1538 print_verifier_state(env, state, false); 1539 } 1540 1541 /* copy array src of length n * size bytes to dst. dst is reallocated if it's too 1542 * small to hold src. This is different from krealloc since we don't want to preserve 1543 * the contents of dst. 1544 * 1545 * Leaves dst untouched if src is NULL or length is zero. Returns NULL if memory could 1546 * not be allocated. 1547 */ 1548 static void *copy_array(void *dst, const void *src, size_t n, size_t size, gfp_t flags) 1549 { 1550 size_t alloc_bytes; 1551 void *orig = dst; 1552 size_t bytes; 1553 1554 if (ZERO_OR_NULL_PTR(src)) 1555 goto out; 1556 1557 if (unlikely(check_mul_overflow(n, size, &bytes))) 1558 return NULL; 1559 1560 alloc_bytes = max(ksize(orig), kmalloc_size_roundup(bytes)); 1561 dst = krealloc(orig, alloc_bytes, flags); 1562 if (!dst) { 1563 kfree(orig); 1564 return NULL; 1565 } 1566 1567 memcpy(dst, src, bytes); 1568 out: 1569 return dst ? dst : ZERO_SIZE_PTR; 1570 } 1571 1572 /* resize an array from old_n items to new_n items. the array is reallocated if it's too 1573 * small to hold new_n items. new items are zeroed out if the array grows. 1574 * 1575 * Contrary to krealloc_array, does not free arr if new_n is zero. 1576 */ 1577 static void *realloc_array(void *arr, size_t old_n, size_t new_n, size_t size) 1578 { 1579 size_t alloc_size; 1580 void *new_arr; 1581 1582 if (!new_n || old_n == new_n) 1583 goto out; 1584 1585 alloc_size = kmalloc_size_roundup(size_mul(new_n, size)); 1586 new_arr = krealloc(arr, alloc_size, GFP_KERNEL); 1587 if (!new_arr) { 1588 kfree(arr); 1589 return NULL; 1590 } 1591 arr = new_arr; 1592 1593 if (new_n > old_n) 1594 memset(arr + old_n * size, 0, (new_n - old_n) * size); 1595 1596 out: 1597 return arr ? arr : ZERO_SIZE_PTR; 1598 } 1599 1600 static int copy_reference_state(struct bpf_func_state *dst, const struct bpf_func_state *src) 1601 { 1602 dst->refs = copy_array(dst->refs, src->refs, src->acquired_refs, 1603 sizeof(struct bpf_reference_state), GFP_KERNEL); 1604 if (!dst->refs) 1605 return -ENOMEM; 1606 1607 dst->acquired_refs = src->acquired_refs; 1608 return 0; 1609 } 1610 1611 static int copy_stack_state(struct bpf_func_state *dst, const struct bpf_func_state *src) 1612 { 1613 size_t n = src->allocated_stack / BPF_REG_SIZE; 1614 1615 dst->stack = copy_array(dst->stack, src->stack, n, sizeof(struct bpf_stack_state), 1616 GFP_KERNEL); 1617 if (!dst->stack) 1618 return -ENOMEM; 1619 1620 dst->allocated_stack = src->allocated_stack; 1621 return 0; 1622 } 1623 1624 static int resize_reference_state(struct bpf_func_state *state, size_t n) 1625 { 1626 state->refs = realloc_array(state->refs, state->acquired_refs, n, 1627 sizeof(struct bpf_reference_state)); 1628 if (!state->refs) 1629 return -ENOMEM; 1630 1631 state->acquired_refs = n; 1632 return 0; 1633 } 1634 1635 /* Possibly update state->allocated_stack to be at least size bytes. Also 1636 * possibly update the function's high-water mark in its bpf_subprog_info. 1637 */ 1638 static int grow_stack_state(struct bpf_verifier_env *env, struct bpf_func_state *state, int size) 1639 { 1640 size_t old_n = state->allocated_stack / BPF_REG_SIZE, n = size / BPF_REG_SIZE; 1641 1642 if (old_n >= n) 1643 return 0; 1644 1645 state->stack = realloc_array(state->stack, old_n, n, sizeof(struct bpf_stack_state)); 1646 if (!state->stack) 1647 return -ENOMEM; 1648 1649 state->allocated_stack = size; 1650 1651 /* update known max for given subprogram */ 1652 if (env->subprog_info[state->subprogno].stack_depth < size) 1653 env->subprog_info[state->subprogno].stack_depth = size; 1654 1655 return 0; 1656 } 1657 1658 /* Acquire a pointer id from the env and update the state->refs to include 1659 * this new pointer reference. 1660 * On success, returns a valid pointer id to associate with the register 1661 * On failure, returns a negative errno. 1662 */ 1663 static int acquire_reference_state(struct bpf_verifier_env *env, int insn_idx) 1664 { 1665 struct bpf_func_state *state = cur_func(env); 1666 int new_ofs = state->acquired_refs; 1667 int id, err; 1668 1669 err = resize_reference_state(state, state->acquired_refs + 1); 1670 if (err) 1671 return err; 1672 id = ++env->id_gen; 1673 state->refs[new_ofs].id = id; 1674 state->refs[new_ofs].insn_idx = insn_idx; 1675 state->refs[new_ofs].callback_ref = state->in_callback_fn ? state->frameno : 0; 1676 1677 return id; 1678 } 1679 1680 /* release function corresponding to acquire_reference_state(). Idempotent. */ 1681 static int release_reference_state(struct bpf_func_state *state, int ptr_id) 1682 { 1683 int i, last_idx; 1684 1685 last_idx = state->acquired_refs - 1; 1686 for (i = 0; i < state->acquired_refs; i++) { 1687 if (state->refs[i].id == ptr_id) { 1688 /* Cannot release caller references in callbacks */ 1689 if (state->in_callback_fn && state->refs[i].callback_ref != state->frameno) 1690 return -EINVAL; 1691 if (last_idx && i != last_idx) 1692 memcpy(&state->refs[i], &state->refs[last_idx], 1693 sizeof(*state->refs)); 1694 memset(&state->refs[last_idx], 0, sizeof(*state->refs)); 1695 state->acquired_refs--; 1696 return 0; 1697 } 1698 } 1699 return -EINVAL; 1700 } 1701 1702 static void free_func_state(struct bpf_func_state *state) 1703 { 1704 if (!state) 1705 return; 1706 kfree(state->refs); 1707 kfree(state->stack); 1708 kfree(state); 1709 } 1710 1711 static void clear_jmp_history(struct bpf_verifier_state *state) 1712 { 1713 kfree(state->jmp_history); 1714 state->jmp_history = NULL; 1715 state->jmp_history_cnt = 0; 1716 } 1717 1718 static void free_verifier_state(struct bpf_verifier_state *state, 1719 bool free_self) 1720 { 1721 int i; 1722 1723 for (i = 0; i <= state->curframe; i++) { 1724 free_func_state(state->frame[i]); 1725 state->frame[i] = NULL; 1726 } 1727 clear_jmp_history(state); 1728 if (free_self) 1729 kfree(state); 1730 } 1731 1732 /* copy verifier state from src to dst growing dst stack space 1733 * when necessary to accommodate larger src stack 1734 */ 1735 static int copy_func_state(struct bpf_func_state *dst, 1736 const struct bpf_func_state *src) 1737 { 1738 int err; 1739 1740 memcpy(dst, src, offsetof(struct bpf_func_state, acquired_refs)); 1741 err = copy_reference_state(dst, src); 1742 if (err) 1743 return err; 1744 return copy_stack_state(dst, src); 1745 } 1746 1747 static int copy_verifier_state(struct bpf_verifier_state *dst_state, 1748 const struct bpf_verifier_state *src) 1749 { 1750 struct bpf_func_state *dst; 1751 int i, err; 1752 1753 dst_state->jmp_history = copy_array(dst_state->jmp_history, src->jmp_history, 1754 src->jmp_history_cnt, sizeof(struct bpf_idx_pair), 1755 GFP_USER); 1756 if (!dst_state->jmp_history) 1757 return -ENOMEM; 1758 dst_state->jmp_history_cnt = src->jmp_history_cnt; 1759 1760 /* if dst has more stack frames then src frame, free them */ 1761 for (i = src->curframe + 1; i <= dst_state->curframe; i++) { 1762 free_func_state(dst_state->frame[i]); 1763 dst_state->frame[i] = NULL; 1764 } 1765 dst_state->speculative = src->speculative; 1766 dst_state->active_rcu_lock = src->active_rcu_lock; 1767 dst_state->curframe = src->curframe; 1768 dst_state->active_lock.ptr = src->active_lock.ptr; 1769 dst_state->active_lock.id = src->active_lock.id; 1770 dst_state->branches = src->branches; 1771 dst_state->parent = src->parent; 1772 dst_state->first_insn_idx = src->first_insn_idx; 1773 dst_state->last_insn_idx = src->last_insn_idx; 1774 for (i = 0; i <= src->curframe; i++) { 1775 dst = dst_state->frame[i]; 1776 if (!dst) { 1777 dst = kzalloc(sizeof(*dst), GFP_KERNEL); 1778 if (!dst) 1779 return -ENOMEM; 1780 dst_state->frame[i] = dst; 1781 } 1782 err = copy_func_state(dst, src->frame[i]); 1783 if (err) 1784 return err; 1785 } 1786 return 0; 1787 } 1788 1789 static void update_branch_counts(struct bpf_verifier_env *env, struct bpf_verifier_state *st) 1790 { 1791 while (st) { 1792 u32 br = --st->branches; 1793 1794 /* WARN_ON(br > 1) technically makes sense here, 1795 * but see comment in push_stack(), hence: 1796 */ 1797 WARN_ONCE((int)br < 0, 1798 "BUG update_branch_counts:branches_to_explore=%d\n", 1799 br); 1800 if (br) 1801 break; 1802 st = st->parent; 1803 } 1804 } 1805 1806 static int pop_stack(struct bpf_verifier_env *env, int *prev_insn_idx, 1807 int *insn_idx, bool pop_log) 1808 { 1809 struct bpf_verifier_state *cur = env->cur_state; 1810 struct bpf_verifier_stack_elem *elem, *head = env->head; 1811 int err; 1812 1813 if (env->head == NULL) 1814 return -ENOENT; 1815 1816 if (cur) { 1817 err = copy_verifier_state(cur, &head->st); 1818 if (err) 1819 return err; 1820 } 1821 if (pop_log) 1822 bpf_vlog_reset(&env->log, head->log_pos); 1823 if (insn_idx) 1824 *insn_idx = head->insn_idx; 1825 if (prev_insn_idx) 1826 *prev_insn_idx = head->prev_insn_idx; 1827 elem = head->next; 1828 free_verifier_state(&head->st, false); 1829 kfree(head); 1830 env->head = elem; 1831 env->stack_size--; 1832 return 0; 1833 } 1834 1835 static struct bpf_verifier_state *push_stack(struct bpf_verifier_env *env, 1836 int insn_idx, int prev_insn_idx, 1837 bool speculative) 1838 { 1839 struct bpf_verifier_state *cur = env->cur_state; 1840 struct bpf_verifier_stack_elem *elem; 1841 int err; 1842 1843 elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL); 1844 if (!elem) 1845 goto err; 1846 1847 elem->insn_idx = insn_idx; 1848 elem->prev_insn_idx = prev_insn_idx; 1849 elem->next = env->head; 1850 elem->log_pos = env->log.end_pos; 1851 env->head = elem; 1852 env->stack_size++; 1853 err = copy_verifier_state(&elem->st, cur); 1854 if (err) 1855 goto err; 1856 elem->st.speculative |= speculative; 1857 if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) { 1858 verbose(env, "The sequence of %d jumps is too complex.\n", 1859 env->stack_size); 1860 goto err; 1861 } 1862 if (elem->st.parent) { 1863 ++elem->st.parent->branches; 1864 /* WARN_ON(branches > 2) technically makes sense here, 1865 * but 1866 * 1. speculative states will bump 'branches' for non-branch 1867 * instructions 1868 * 2. is_state_visited() heuristics may decide not to create 1869 * a new state for a sequence of branches and all such current 1870 * and cloned states will be pointing to a single parent state 1871 * which might have large 'branches' count. 1872 */ 1873 } 1874 return &elem->st; 1875 err: 1876 free_verifier_state(env->cur_state, true); 1877 env->cur_state = NULL; 1878 /* pop all elements and return */ 1879 while (!pop_stack(env, NULL, NULL, false)); 1880 return NULL; 1881 } 1882 1883 #define CALLER_SAVED_REGS 6 1884 static const int caller_saved[CALLER_SAVED_REGS] = { 1885 BPF_REG_0, BPF_REG_1, BPF_REG_2, BPF_REG_3, BPF_REG_4, BPF_REG_5 1886 }; 1887 1888 /* This helper doesn't clear reg->id */ 1889 static void ___mark_reg_known(struct bpf_reg_state *reg, u64 imm) 1890 { 1891 reg->var_off = tnum_const(imm); 1892 reg->smin_value = (s64)imm; 1893 reg->smax_value = (s64)imm; 1894 reg->umin_value = imm; 1895 reg->umax_value = imm; 1896 1897 reg->s32_min_value = (s32)imm; 1898 reg->s32_max_value = (s32)imm; 1899 reg->u32_min_value = (u32)imm; 1900 reg->u32_max_value = (u32)imm; 1901 } 1902 1903 /* Mark the unknown part of a register (variable offset or scalar value) as 1904 * known to have the value @imm. 1905 */ 1906 static void __mark_reg_known(struct bpf_reg_state *reg, u64 imm) 1907 { 1908 /* Clear off and union(map_ptr, range) */ 1909 memset(((u8 *)reg) + sizeof(reg->type), 0, 1910 offsetof(struct bpf_reg_state, var_off) - sizeof(reg->type)); 1911 reg->id = 0; 1912 reg->ref_obj_id = 0; 1913 ___mark_reg_known(reg, imm); 1914 } 1915 1916 static void __mark_reg32_known(struct bpf_reg_state *reg, u64 imm) 1917 { 1918 reg->var_off = tnum_const_subreg(reg->var_off, imm); 1919 reg->s32_min_value = (s32)imm; 1920 reg->s32_max_value = (s32)imm; 1921 reg->u32_min_value = (u32)imm; 1922 reg->u32_max_value = (u32)imm; 1923 } 1924 1925 /* Mark the 'variable offset' part of a register as zero. This should be 1926 * used only on registers holding a pointer type. 1927 */ 1928 static void __mark_reg_known_zero(struct bpf_reg_state *reg) 1929 { 1930 __mark_reg_known(reg, 0); 1931 } 1932 1933 static void __mark_reg_const_zero(struct bpf_reg_state *reg) 1934 { 1935 __mark_reg_known(reg, 0); 1936 reg->type = SCALAR_VALUE; 1937 } 1938 1939 static void mark_reg_known_zero(struct bpf_verifier_env *env, 1940 struct bpf_reg_state *regs, u32 regno) 1941 { 1942 if (WARN_ON(regno >= MAX_BPF_REG)) { 1943 verbose(env, "mark_reg_known_zero(regs, %u)\n", regno); 1944 /* Something bad happened, let's kill all regs */ 1945 for (regno = 0; regno < MAX_BPF_REG; regno++) 1946 __mark_reg_not_init(env, regs + regno); 1947 return; 1948 } 1949 __mark_reg_known_zero(regs + regno); 1950 } 1951 1952 static void __mark_dynptr_reg(struct bpf_reg_state *reg, enum bpf_dynptr_type type, 1953 bool first_slot, int dynptr_id) 1954 { 1955 /* reg->type has no meaning for STACK_DYNPTR, but when we set reg for 1956 * callback arguments, it does need to be CONST_PTR_TO_DYNPTR, so simply 1957 * set it unconditionally as it is ignored for STACK_DYNPTR anyway. 1958 */ 1959 __mark_reg_known_zero(reg); 1960 reg->type = CONST_PTR_TO_DYNPTR; 1961 /* Give each dynptr a unique id to uniquely associate slices to it. */ 1962 reg->id = dynptr_id; 1963 reg->dynptr.type = type; 1964 reg->dynptr.first_slot = first_slot; 1965 } 1966 1967 static void mark_ptr_not_null_reg(struct bpf_reg_state *reg) 1968 { 1969 if (base_type(reg->type) == PTR_TO_MAP_VALUE) { 1970 const struct bpf_map *map = reg->map_ptr; 1971 1972 if (map->inner_map_meta) { 1973 reg->type = CONST_PTR_TO_MAP; 1974 reg->map_ptr = map->inner_map_meta; 1975 /* transfer reg's id which is unique for every map_lookup_elem 1976 * as UID of the inner map. 1977 */ 1978 if (btf_record_has_field(map->inner_map_meta->record, BPF_TIMER)) 1979 reg->map_uid = reg->id; 1980 } else if (map->map_type == BPF_MAP_TYPE_XSKMAP) { 1981 reg->type = PTR_TO_XDP_SOCK; 1982 } else if (map->map_type == BPF_MAP_TYPE_SOCKMAP || 1983 map->map_type == BPF_MAP_TYPE_SOCKHASH) { 1984 reg->type = PTR_TO_SOCKET; 1985 } else { 1986 reg->type = PTR_TO_MAP_VALUE; 1987 } 1988 return; 1989 } 1990 1991 reg->type &= ~PTR_MAYBE_NULL; 1992 } 1993 1994 static void mark_reg_graph_node(struct bpf_reg_state *regs, u32 regno, 1995 struct btf_field_graph_root *ds_head) 1996 { 1997 __mark_reg_known_zero(®s[regno]); 1998 regs[regno].type = PTR_TO_BTF_ID | MEM_ALLOC; 1999 regs[regno].btf = ds_head->btf; 2000 regs[regno].btf_id = ds_head->value_btf_id; 2001 regs[regno].off = ds_head->node_offset; 2002 } 2003 2004 static bool reg_is_pkt_pointer(const struct bpf_reg_state *reg) 2005 { 2006 return type_is_pkt_pointer(reg->type); 2007 } 2008 2009 static bool reg_is_pkt_pointer_any(const struct bpf_reg_state *reg) 2010 { 2011 return reg_is_pkt_pointer(reg) || 2012 reg->type == PTR_TO_PACKET_END; 2013 } 2014 2015 static bool reg_is_dynptr_slice_pkt(const struct bpf_reg_state *reg) 2016 { 2017 return base_type(reg->type) == PTR_TO_MEM && 2018 (reg->type & DYNPTR_TYPE_SKB || reg->type & DYNPTR_TYPE_XDP); 2019 } 2020 2021 /* Unmodified PTR_TO_PACKET[_META,_END] register from ctx access. */ 2022 static bool reg_is_init_pkt_pointer(const struct bpf_reg_state *reg, 2023 enum bpf_reg_type which) 2024 { 2025 /* The register can already have a range from prior markings. 2026 * This is fine as long as it hasn't been advanced from its 2027 * origin. 2028 */ 2029 return reg->type == which && 2030 reg->id == 0 && 2031 reg->off == 0 && 2032 tnum_equals_const(reg->var_off, 0); 2033 } 2034 2035 /* Reset the min/max bounds of a register */ 2036 static void __mark_reg_unbounded(struct bpf_reg_state *reg) 2037 { 2038 reg->smin_value = S64_MIN; 2039 reg->smax_value = S64_MAX; 2040 reg->umin_value = 0; 2041 reg->umax_value = U64_MAX; 2042 2043 reg->s32_min_value = S32_MIN; 2044 reg->s32_max_value = S32_MAX; 2045 reg->u32_min_value = 0; 2046 reg->u32_max_value = U32_MAX; 2047 } 2048 2049 static void __mark_reg64_unbounded(struct bpf_reg_state *reg) 2050 { 2051 reg->smin_value = S64_MIN; 2052 reg->smax_value = S64_MAX; 2053 reg->umin_value = 0; 2054 reg->umax_value = U64_MAX; 2055 } 2056 2057 static void __mark_reg32_unbounded(struct bpf_reg_state *reg) 2058 { 2059 reg->s32_min_value = S32_MIN; 2060 reg->s32_max_value = S32_MAX; 2061 reg->u32_min_value = 0; 2062 reg->u32_max_value = U32_MAX; 2063 } 2064 2065 static void __update_reg32_bounds(struct bpf_reg_state *reg) 2066 { 2067 struct tnum var32_off = tnum_subreg(reg->var_off); 2068 2069 /* min signed is max(sign bit) | min(other bits) */ 2070 reg->s32_min_value = max_t(s32, reg->s32_min_value, 2071 var32_off.value | (var32_off.mask & S32_MIN)); 2072 /* max signed is min(sign bit) | max(other bits) */ 2073 reg->s32_max_value = min_t(s32, reg->s32_max_value, 2074 var32_off.value | (var32_off.mask & S32_MAX)); 2075 reg->u32_min_value = max_t(u32, reg->u32_min_value, (u32)var32_off.value); 2076 reg->u32_max_value = min(reg->u32_max_value, 2077 (u32)(var32_off.value | var32_off.mask)); 2078 } 2079 2080 static void __update_reg64_bounds(struct bpf_reg_state *reg) 2081 { 2082 /* min signed is max(sign bit) | min(other bits) */ 2083 reg->smin_value = max_t(s64, reg->smin_value, 2084 reg->var_off.value | (reg->var_off.mask & S64_MIN)); 2085 /* max signed is min(sign bit) | max(other bits) */ 2086 reg->smax_value = min_t(s64, reg->smax_value, 2087 reg->var_off.value | (reg->var_off.mask & S64_MAX)); 2088 reg->umin_value = max(reg->umin_value, reg->var_off.value); 2089 reg->umax_value = min(reg->umax_value, 2090 reg->var_off.value | reg->var_off.mask); 2091 } 2092 2093 static void __update_reg_bounds(struct bpf_reg_state *reg) 2094 { 2095 __update_reg32_bounds(reg); 2096 __update_reg64_bounds(reg); 2097 } 2098 2099 /* Uses signed min/max values to inform unsigned, and vice-versa */ 2100 static void __reg32_deduce_bounds(struct bpf_reg_state *reg) 2101 { 2102 /* Learn sign from signed bounds. 2103 * If we cannot cross the sign boundary, then signed and unsigned bounds 2104 * are the same, so combine. This works even in the negative case, e.g. 2105 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff. 2106 */ 2107 if (reg->s32_min_value >= 0 || reg->s32_max_value < 0) { 2108 reg->s32_min_value = reg->u32_min_value = 2109 max_t(u32, reg->s32_min_value, reg->u32_min_value); 2110 reg->s32_max_value = reg->u32_max_value = 2111 min_t(u32, reg->s32_max_value, reg->u32_max_value); 2112 return; 2113 } 2114 /* Learn sign from unsigned bounds. Signed bounds cross the sign 2115 * boundary, so we must be careful. 2116 */ 2117 if ((s32)reg->u32_max_value >= 0) { 2118 /* Positive. We can't learn anything from the smin, but smax 2119 * is positive, hence safe. 2120 */ 2121 reg->s32_min_value = reg->u32_min_value; 2122 reg->s32_max_value = reg->u32_max_value = 2123 min_t(u32, reg->s32_max_value, reg->u32_max_value); 2124 } else if ((s32)reg->u32_min_value < 0) { 2125 /* Negative. We can't learn anything from the smax, but smin 2126 * is negative, hence safe. 2127 */ 2128 reg->s32_min_value = reg->u32_min_value = 2129 max_t(u32, reg->s32_min_value, reg->u32_min_value); 2130 reg->s32_max_value = reg->u32_max_value; 2131 } 2132 } 2133 2134 static void __reg64_deduce_bounds(struct bpf_reg_state *reg) 2135 { 2136 /* Learn sign from signed bounds. 2137 * If we cannot cross the sign boundary, then signed and unsigned bounds 2138 * are the same, so combine. This works even in the negative case, e.g. 2139 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff. 2140 */ 2141 if (reg->smin_value >= 0 || reg->smax_value < 0) { 2142 reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value, 2143 reg->umin_value); 2144 reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value, 2145 reg->umax_value); 2146 return; 2147 } 2148 /* Learn sign from unsigned bounds. Signed bounds cross the sign 2149 * boundary, so we must be careful. 2150 */ 2151 if ((s64)reg->umax_value >= 0) { 2152 /* Positive. We can't learn anything from the smin, but smax 2153 * is positive, hence safe. 2154 */ 2155 reg->smin_value = reg->umin_value; 2156 reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value, 2157 reg->umax_value); 2158 } else if ((s64)reg->umin_value < 0) { 2159 /* Negative. We can't learn anything from the smax, but smin 2160 * is negative, hence safe. 2161 */ 2162 reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value, 2163 reg->umin_value); 2164 reg->smax_value = reg->umax_value; 2165 } 2166 } 2167 2168 static void __reg_deduce_bounds(struct bpf_reg_state *reg) 2169 { 2170 __reg32_deduce_bounds(reg); 2171 __reg64_deduce_bounds(reg); 2172 } 2173 2174 /* Attempts to improve var_off based on unsigned min/max information */ 2175 static void __reg_bound_offset(struct bpf_reg_state *reg) 2176 { 2177 struct tnum var64_off = tnum_intersect(reg->var_off, 2178 tnum_range(reg->umin_value, 2179 reg->umax_value)); 2180 struct tnum var32_off = tnum_intersect(tnum_subreg(var64_off), 2181 tnum_range(reg->u32_min_value, 2182 reg->u32_max_value)); 2183 2184 reg->var_off = tnum_or(tnum_clear_subreg(var64_off), var32_off); 2185 } 2186 2187 static void reg_bounds_sync(struct bpf_reg_state *reg) 2188 { 2189 /* We might have learned new bounds from the var_off. */ 2190 __update_reg_bounds(reg); 2191 /* We might have learned something about the sign bit. */ 2192 __reg_deduce_bounds(reg); 2193 /* We might have learned some bits from the bounds. */ 2194 __reg_bound_offset(reg); 2195 /* Intersecting with the old var_off might have improved our bounds 2196 * slightly, e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc), 2197 * then new var_off is (0; 0x7f...fc) which improves our umax. 2198 */ 2199 __update_reg_bounds(reg); 2200 } 2201 2202 static bool __reg32_bound_s64(s32 a) 2203 { 2204 return a >= 0 && a <= S32_MAX; 2205 } 2206 2207 static void __reg_assign_32_into_64(struct bpf_reg_state *reg) 2208 { 2209 reg->umin_value = reg->u32_min_value; 2210 reg->umax_value = reg->u32_max_value; 2211 2212 /* Attempt to pull 32-bit signed bounds into 64-bit bounds but must 2213 * be positive otherwise set to worse case bounds and refine later 2214 * from tnum. 2215 */ 2216 if (__reg32_bound_s64(reg->s32_min_value) && 2217 __reg32_bound_s64(reg->s32_max_value)) { 2218 reg->smin_value = reg->s32_min_value; 2219 reg->smax_value = reg->s32_max_value; 2220 } else { 2221 reg->smin_value = 0; 2222 reg->smax_value = U32_MAX; 2223 } 2224 } 2225 2226 static void __reg_combine_32_into_64(struct bpf_reg_state *reg) 2227 { 2228 /* special case when 64-bit register has upper 32-bit register 2229 * zeroed. Typically happens after zext or <<32, >>32 sequence 2230 * allowing us to use 32-bit bounds directly, 2231 */ 2232 if (tnum_equals_const(tnum_clear_subreg(reg->var_off), 0)) { 2233 __reg_assign_32_into_64(reg); 2234 } else { 2235 /* Otherwise the best we can do is push lower 32bit known and 2236 * unknown bits into register (var_off set from jmp logic) 2237 * then learn as much as possible from the 64-bit tnum 2238 * known and unknown bits. The previous smin/smax bounds are 2239 * invalid here because of jmp32 compare so mark them unknown 2240 * so they do not impact tnum bounds calculation. 2241 */ 2242 __mark_reg64_unbounded(reg); 2243 } 2244 reg_bounds_sync(reg); 2245 } 2246 2247 static bool __reg64_bound_s32(s64 a) 2248 { 2249 return a >= S32_MIN && a <= S32_MAX; 2250 } 2251 2252 static bool __reg64_bound_u32(u64 a) 2253 { 2254 return a >= U32_MIN && a <= U32_MAX; 2255 } 2256 2257 static void __reg_combine_64_into_32(struct bpf_reg_state *reg) 2258 { 2259 __mark_reg32_unbounded(reg); 2260 if (__reg64_bound_s32(reg->smin_value) && __reg64_bound_s32(reg->smax_value)) { 2261 reg->s32_min_value = (s32)reg->smin_value; 2262 reg->s32_max_value = (s32)reg->smax_value; 2263 } 2264 if (__reg64_bound_u32(reg->umin_value) && __reg64_bound_u32(reg->umax_value)) { 2265 reg->u32_min_value = (u32)reg->umin_value; 2266 reg->u32_max_value = (u32)reg->umax_value; 2267 } 2268 reg_bounds_sync(reg); 2269 } 2270 2271 /* Mark a register as having a completely unknown (scalar) value. */ 2272 static void __mark_reg_unknown(const struct bpf_verifier_env *env, 2273 struct bpf_reg_state *reg) 2274 { 2275 /* 2276 * Clear type, off, and union(map_ptr, range) and 2277 * padding between 'type' and union 2278 */ 2279 memset(reg, 0, offsetof(struct bpf_reg_state, var_off)); 2280 reg->type = SCALAR_VALUE; 2281 reg->id = 0; 2282 reg->ref_obj_id = 0; 2283 reg->var_off = tnum_unknown; 2284 reg->frameno = 0; 2285 reg->precise = !env->bpf_capable; 2286 __mark_reg_unbounded(reg); 2287 } 2288 2289 static void mark_reg_unknown(struct bpf_verifier_env *env, 2290 struct bpf_reg_state *regs, u32 regno) 2291 { 2292 if (WARN_ON(regno >= MAX_BPF_REG)) { 2293 verbose(env, "mark_reg_unknown(regs, %u)\n", regno); 2294 /* Something bad happened, let's kill all regs except FP */ 2295 for (regno = 0; regno < BPF_REG_FP; regno++) 2296 __mark_reg_not_init(env, regs + regno); 2297 return; 2298 } 2299 __mark_reg_unknown(env, regs + regno); 2300 } 2301 2302 static void __mark_reg_not_init(const struct bpf_verifier_env *env, 2303 struct bpf_reg_state *reg) 2304 { 2305 __mark_reg_unknown(env, reg); 2306 reg->type = NOT_INIT; 2307 } 2308 2309 static void mark_reg_not_init(struct bpf_verifier_env *env, 2310 struct bpf_reg_state *regs, u32 regno) 2311 { 2312 if (WARN_ON(regno >= MAX_BPF_REG)) { 2313 verbose(env, "mark_reg_not_init(regs, %u)\n", regno); 2314 /* Something bad happened, let's kill all regs except FP */ 2315 for (regno = 0; regno < BPF_REG_FP; regno++) 2316 __mark_reg_not_init(env, regs + regno); 2317 return; 2318 } 2319 __mark_reg_not_init(env, regs + regno); 2320 } 2321 2322 static void mark_btf_ld_reg(struct bpf_verifier_env *env, 2323 struct bpf_reg_state *regs, u32 regno, 2324 enum bpf_reg_type reg_type, 2325 struct btf *btf, u32 btf_id, 2326 enum bpf_type_flag flag) 2327 { 2328 if (reg_type == SCALAR_VALUE) { 2329 mark_reg_unknown(env, regs, regno); 2330 return; 2331 } 2332 mark_reg_known_zero(env, regs, regno); 2333 regs[regno].type = PTR_TO_BTF_ID | flag; 2334 regs[regno].btf = btf; 2335 regs[regno].btf_id = btf_id; 2336 } 2337 2338 #define DEF_NOT_SUBREG (0) 2339 static void init_reg_state(struct bpf_verifier_env *env, 2340 struct bpf_func_state *state) 2341 { 2342 struct bpf_reg_state *regs = state->regs; 2343 int i; 2344 2345 for (i = 0; i < MAX_BPF_REG; i++) { 2346 mark_reg_not_init(env, regs, i); 2347 regs[i].live = REG_LIVE_NONE; 2348 regs[i].parent = NULL; 2349 regs[i].subreg_def = DEF_NOT_SUBREG; 2350 } 2351 2352 /* frame pointer */ 2353 regs[BPF_REG_FP].type = PTR_TO_STACK; 2354 mark_reg_known_zero(env, regs, BPF_REG_FP); 2355 regs[BPF_REG_FP].frameno = state->frameno; 2356 } 2357 2358 #define BPF_MAIN_FUNC (-1) 2359 static void init_func_state(struct bpf_verifier_env *env, 2360 struct bpf_func_state *state, 2361 int callsite, int frameno, int subprogno) 2362 { 2363 state->callsite = callsite; 2364 state->frameno = frameno; 2365 state->subprogno = subprogno; 2366 state->callback_ret_range = tnum_range(0, 0); 2367 init_reg_state(env, state); 2368 mark_verifier_state_scratched(env); 2369 } 2370 2371 /* Similar to push_stack(), but for async callbacks */ 2372 static struct bpf_verifier_state *push_async_cb(struct bpf_verifier_env *env, 2373 int insn_idx, int prev_insn_idx, 2374 int subprog) 2375 { 2376 struct bpf_verifier_stack_elem *elem; 2377 struct bpf_func_state *frame; 2378 2379 elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL); 2380 if (!elem) 2381 goto err; 2382 2383 elem->insn_idx = insn_idx; 2384 elem->prev_insn_idx = prev_insn_idx; 2385 elem->next = env->head; 2386 elem->log_pos = env->log.end_pos; 2387 env->head = elem; 2388 env->stack_size++; 2389 if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) { 2390 verbose(env, 2391 "The sequence of %d jumps is too complex for async cb.\n", 2392 env->stack_size); 2393 goto err; 2394 } 2395 /* Unlike push_stack() do not copy_verifier_state(). 2396 * The caller state doesn't matter. 2397 * This is async callback. It starts in a fresh stack. 2398 * Initialize it similar to do_check_common(). 2399 */ 2400 elem->st.branches = 1; 2401 frame = kzalloc(sizeof(*frame), GFP_KERNEL); 2402 if (!frame) 2403 goto err; 2404 init_func_state(env, frame, 2405 BPF_MAIN_FUNC /* callsite */, 2406 0 /* frameno within this callchain */, 2407 subprog /* subprog number within this prog */); 2408 elem->st.frame[0] = frame; 2409 return &elem->st; 2410 err: 2411 free_verifier_state(env->cur_state, true); 2412 env->cur_state = NULL; 2413 /* pop all elements and return */ 2414 while (!pop_stack(env, NULL, NULL, false)); 2415 return NULL; 2416 } 2417 2418 2419 enum reg_arg_type { 2420 SRC_OP, /* register is used as source operand */ 2421 DST_OP, /* register is used as destination operand */ 2422 DST_OP_NO_MARK /* same as above, check only, don't mark */ 2423 }; 2424 2425 static int cmp_subprogs(const void *a, const void *b) 2426 { 2427 return ((struct bpf_subprog_info *)a)->start - 2428 ((struct bpf_subprog_info *)b)->start; 2429 } 2430 2431 static int find_subprog(struct bpf_verifier_env *env, int off) 2432 { 2433 struct bpf_subprog_info *p; 2434 2435 p = bsearch(&off, env->subprog_info, env->subprog_cnt, 2436 sizeof(env->subprog_info[0]), cmp_subprogs); 2437 if (!p) 2438 return -ENOENT; 2439 return p - env->subprog_info; 2440 2441 } 2442 2443 static int add_subprog(struct bpf_verifier_env *env, int off) 2444 { 2445 int insn_cnt = env->prog->len; 2446 int ret; 2447 2448 if (off >= insn_cnt || off < 0) { 2449 verbose(env, "call to invalid destination\n"); 2450 return -EINVAL; 2451 } 2452 ret = find_subprog(env, off); 2453 if (ret >= 0) 2454 return ret; 2455 if (env->subprog_cnt >= BPF_MAX_SUBPROGS) { 2456 verbose(env, "too many subprograms\n"); 2457 return -E2BIG; 2458 } 2459 /* determine subprog starts. The end is one before the next starts */ 2460 env->subprog_info[env->subprog_cnt++].start = off; 2461 sort(env->subprog_info, env->subprog_cnt, 2462 sizeof(env->subprog_info[0]), cmp_subprogs, NULL); 2463 return env->subprog_cnt - 1; 2464 } 2465 2466 #define MAX_KFUNC_DESCS 256 2467 #define MAX_KFUNC_BTFS 256 2468 2469 struct bpf_kfunc_desc { 2470 struct btf_func_model func_model; 2471 u32 func_id; 2472 s32 imm; 2473 u16 offset; 2474 unsigned long addr; 2475 }; 2476 2477 struct bpf_kfunc_btf { 2478 struct btf *btf; 2479 struct module *module; 2480 u16 offset; 2481 }; 2482 2483 struct bpf_kfunc_desc_tab { 2484 /* Sorted by func_id (BTF ID) and offset (fd_array offset) during 2485 * verification. JITs do lookups by bpf_insn, where func_id may not be 2486 * available, therefore at the end of verification do_misc_fixups() 2487 * sorts this by imm and offset. 2488 */ 2489 struct bpf_kfunc_desc descs[MAX_KFUNC_DESCS]; 2490 u32 nr_descs; 2491 }; 2492 2493 struct bpf_kfunc_btf_tab { 2494 struct bpf_kfunc_btf descs[MAX_KFUNC_BTFS]; 2495 u32 nr_descs; 2496 }; 2497 2498 static int kfunc_desc_cmp_by_id_off(const void *a, const void *b) 2499 { 2500 const struct bpf_kfunc_desc *d0 = a; 2501 const struct bpf_kfunc_desc *d1 = b; 2502 2503 /* func_id is not greater than BTF_MAX_TYPE */ 2504 return d0->func_id - d1->func_id ?: d0->offset - d1->offset; 2505 } 2506 2507 static int kfunc_btf_cmp_by_off(const void *a, const void *b) 2508 { 2509 const struct bpf_kfunc_btf *d0 = a; 2510 const struct bpf_kfunc_btf *d1 = b; 2511 2512 return d0->offset - d1->offset; 2513 } 2514 2515 static const struct bpf_kfunc_desc * 2516 find_kfunc_desc(const struct bpf_prog *prog, u32 func_id, u16 offset) 2517 { 2518 struct bpf_kfunc_desc desc = { 2519 .func_id = func_id, 2520 .offset = offset, 2521 }; 2522 struct bpf_kfunc_desc_tab *tab; 2523 2524 tab = prog->aux->kfunc_tab; 2525 return bsearch(&desc, tab->descs, tab->nr_descs, 2526 sizeof(tab->descs[0]), kfunc_desc_cmp_by_id_off); 2527 } 2528 2529 int bpf_get_kfunc_addr(const struct bpf_prog *prog, u32 func_id, 2530 u16 btf_fd_idx, u8 **func_addr) 2531 { 2532 const struct bpf_kfunc_desc *desc; 2533 2534 desc = find_kfunc_desc(prog, func_id, btf_fd_idx); 2535 if (!desc) 2536 return -EFAULT; 2537 2538 *func_addr = (u8 *)desc->addr; 2539 return 0; 2540 } 2541 2542 static struct btf *__find_kfunc_desc_btf(struct bpf_verifier_env *env, 2543 s16 offset) 2544 { 2545 struct bpf_kfunc_btf kf_btf = { .offset = offset }; 2546 struct bpf_kfunc_btf_tab *tab; 2547 struct bpf_kfunc_btf *b; 2548 struct module *mod; 2549 struct btf *btf; 2550 int btf_fd; 2551 2552 tab = env->prog->aux->kfunc_btf_tab; 2553 b = bsearch(&kf_btf, tab->descs, tab->nr_descs, 2554 sizeof(tab->descs[0]), kfunc_btf_cmp_by_off); 2555 if (!b) { 2556 if (tab->nr_descs == MAX_KFUNC_BTFS) { 2557 verbose(env, "too many different module BTFs\n"); 2558 return ERR_PTR(-E2BIG); 2559 } 2560 2561 if (bpfptr_is_null(env->fd_array)) { 2562 verbose(env, "kfunc offset > 0 without fd_array is invalid\n"); 2563 return ERR_PTR(-EPROTO); 2564 } 2565 2566 if (copy_from_bpfptr_offset(&btf_fd, env->fd_array, 2567 offset * sizeof(btf_fd), 2568 sizeof(btf_fd))) 2569 return ERR_PTR(-EFAULT); 2570 2571 btf = btf_get_by_fd(btf_fd); 2572 if (IS_ERR(btf)) { 2573 verbose(env, "invalid module BTF fd specified\n"); 2574 return btf; 2575 } 2576 2577 if (!btf_is_module(btf)) { 2578 verbose(env, "BTF fd for kfunc is not a module BTF\n"); 2579 btf_put(btf); 2580 return ERR_PTR(-EINVAL); 2581 } 2582 2583 mod = btf_try_get_module(btf); 2584 if (!mod) { 2585 btf_put(btf); 2586 return ERR_PTR(-ENXIO); 2587 } 2588 2589 b = &tab->descs[tab->nr_descs++]; 2590 b->btf = btf; 2591 b->module = mod; 2592 b->offset = offset; 2593 2594 sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]), 2595 kfunc_btf_cmp_by_off, NULL); 2596 } 2597 return b->btf; 2598 } 2599 2600 void bpf_free_kfunc_btf_tab(struct bpf_kfunc_btf_tab *tab) 2601 { 2602 if (!tab) 2603 return; 2604 2605 while (tab->nr_descs--) { 2606 module_put(tab->descs[tab->nr_descs].module); 2607 btf_put(tab->descs[tab->nr_descs].btf); 2608 } 2609 kfree(tab); 2610 } 2611 2612 static struct btf *find_kfunc_desc_btf(struct bpf_verifier_env *env, s16 offset) 2613 { 2614 if (offset) { 2615 if (offset < 0) { 2616 /* In the future, this can be allowed to increase limit 2617 * of fd index into fd_array, interpreted as u16. 2618 */ 2619 verbose(env, "negative offset disallowed for kernel module function call\n"); 2620 return ERR_PTR(-EINVAL); 2621 } 2622 2623 return __find_kfunc_desc_btf(env, offset); 2624 } 2625 return btf_vmlinux ?: ERR_PTR(-ENOENT); 2626 } 2627 2628 static int add_kfunc_call(struct bpf_verifier_env *env, u32 func_id, s16 offset) 2629 { 2630 const struct btf_type *func, *func_proto; 2631 struct bpf_kfunc_btf_tab *btf_tab; 2632 struct bpf_kfunc_desc_tab *tab; 2633 struct bpf_prog_aux *prog_aux; 2634 struct bpf_kfunc_desc *desc; 2635 const char *func_name; 2636 struct btf *desc_btf; 2637 unsigned long call_imm; 2638 unsigned long addr; 2639 int err; 2640 2641 prog_aux = env->prog->aux; 2642 tab = prog_aux->kfunc_tab; 2643 btf_tab = prog_aux->kfunc_btf_tab; 2644 if (!tab) { 2645 if (!btf_vmlinux) { 2646 verbose(env, "calling kernel function is not supported without CONFIG_DEBUG_INFO_BTF\n"); 2647 return -ENOTSUPP; 2648 } 2649 2650 if (!env->prog->jit_requested) { 2651 verbose(env, "JIT is required for calling kernel function\n"); 2652 return -ENOTSUPP; 2653 } 2654 2655 if (!bpf_jit_supports_kfunc_call()) { 2656 verbose(env, "JIT does not support calling kernel function\n"); 2657 return -ENOTSUPP; 2658 } 2659 2660 if (!env->prog->gpl_compatible) { 2661 verbose(env, "cannot call kernel function from non-GPL compatible program\n"); 2662 return -EINVAL; 2663 } 2664 2665 tab = kzalloc(sizeof(*tab), GFP_KERNEL); 2666 if (!tab) 2667 return -ENOMEM; 2668 prog_aux->kfunc_tab = tab; 2669 } 2670 2671 /* func_id == 0 is always invalid, but instead of returning an error, be 2672 * conservative and wait until the code elimination pass before returning 2673 * error, so that invalid calls that get pruned out can be in BPF programs 2674 * loaded from userspace. It is also required that offset be untouched 2675 * for such calls. 2676 */ 2677 if (!func_id && !offset) 2678 return 0; 2679 2680 if (!btf_tab && offset) { 2681 btf_tab = kzalloc(sizeof(*btf_tab), GFP_KERNEL); 2682 if (!btf_tab) 2683 return -ENOMEM; 2684 prog_aux->kfunc_btf_tab = btf_tab; 2685 } 2686 2687 desc_btf = find_kfunc_desc_btf(env, offset); 2688 if (IS_ERR(desc_btf)) { 2689 verbose(env, "failed to find BTF for kernel function\n"); 2690 return PTR_ERR(desc_btf); 2691 } 2692 2693 if (find_kfunc_desc(env->prog, func_id, offset)) 2694 return 0; 2695 2696 if (tab->nr_descs == MAX_KFUNC_DESCS) { 2697 verbose(env, "too many different kernel function calls\n"); 2698 return -E2BIG; 2699 } 2700 2701 func = btf_type_by_id(desc_btf, func_id); 2702 if (!func || !btf_type_is_func(func)) { 2703 verbose(env, "kernel btf_id %u is not a function\n", 2704 func_id); 2705 return -EINVAL; 2706 } 2707 func_proto = btf_type_by_id(desc_btf, func->type); 2708 if (!func_proto || !btf_type_is_func_proto(func_proto)) { 2709 verbose(env, "kernel function btf_id %u does not have a valid func_proto\n", 2710 func_id); 2711 return -EINVAL; 2712 } 2713 2714 func_name = btf_name_by_offset(desc_btf, func->name_off); 2715 addr = kallsyms_lookup_name(func_name); 2716 if (!addr) { 2717 verbose(env, "cannot find address for kernel function %s\n", 2718 func_name); 2719 return -EINVAL; 2720 } 2721 specialize_kfunc(env, func_id, offset, &addr); 2722 2723 if (bpf_jit_supports_far_kfunc_call()) { 2724 call_imm = func_id; 2725 } else { 2726 call_imm = BPF_CALL_IMM(addr); 2727 /* Check whether the relative offset overflows desc->imm */ 2728 if ((unsigned long)(s32)call_imm != call_imm) { 2729 verbose(env, "address of kernel function %s is out of range\n", 2730 func_name); 2731 return -EINVAL; 2732 } 2733 } 2734 2735 if (bpf_dev_bound_kfunc_id(func_id)) { 2736 err = bpf_dev_bound_kfunc_check(&env->log, prog_aux); 2737 if (err) 2738 return err; 2739 } 2740 2741 desc = &tab->descs[tab->nr_descs++]; 2742 desc->func_id = func_id; 2743 desc->imm = call_imm; 2744 desc->offset = offset; 2745 desc->addr = addr; 2746 err = btf_distill_func_proto(&env->log, desc_btf, 2747 func_proto, func_name, 2748 &desc->func_model); 2749 if (!err) 2750 sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]), 2751 kfunc_desc_cmp_by_id_off, NULL); 2752 return err; 2753 } 2754 2755 static int kfunc_desc_cmp_by_imm_off(const void *a, const void *b) 2756 { 2757 const struct bpf_kfunc_desc *d0 = a; 2758 const struct bpf_kfunc_desc *d1 = b; 2759 2760 if (d0->imm != d1->imm) 2761 return d0->imm < d1->imm ? -1 : 1; 2762 if (d0->offset != d1->offset) 2763 return d0->offset < d1->offset ? -1 : 1; 2764 return 0; 2765 } 2766 2767 static void sort_kfunc_descs_by_imm_off(struct bpf_prog *prog) 2768 { 2769 struct bpf_kfunc_desc_tab *tab; 2770 2771 tab = prog->aux->kfunc_tab; 2772 if (!tab) 2773 return; 2774 2775 sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]), 2776 kfunc_desc_cmp_by_imm_off, NULL); 2777 } 2778 2779 bool bpf_prog_has_kfunc_call(const struct bpf_prog *prog) 2780 { 2781 return !!prog->aux->kfunc_tab; 2782 } 2783 2784 const struct btf_func_model * 2785 bpf_jit_find_kfunc_model(const struct bpf_prog *prog, 2786 const struct bpf_insn *insn) 2787 { 2788 const struct bpf_kfunc_desc desc = { 2789 .imm = insn->imm, 2790 .offset = insn->off, 2791 }; 2792 const struct bpf_kfunc_desc *res; 2793 struct bpf_kfunc_desc_tab *tab; 2794 2795 tab = prog->aux->kfunc_tab; 2796 res = bsearch(&desc, tab->descs, tab->nr_descs, 2797 sizeof(tab->descs[0]), kfunc_desc_cmp_by_imm_off); 2798 2799 return res ? &res->func_model : NULL; 2800 } 2801 2802 static int add_subprog_and_kfunc(struct bpf_verifier_env *env) 2803 { 2804 struct bpf_subprog_info *subprog = env->subprog_info; 2805 struct bpf_insn *insn = env->prog->insnsi; 2806 int i, ret, insn_cnt = env->prog->len; 2807 2808 /* Add entry function. */ 2809 ret = add_subprog(env, 0); 2810 if (ret) 2811 return ret; 2812 2813 for (i = 0; i < insn_cnt; i++, insn++) { 2814 if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn) && 2815 !bpf_pseudo_kfunc_call(insn)) 2816 continue; 2817 2818 if (!env->bpf_capable) { 2819 verbose(env, "loading/calling other bpf or kernel functions are allowed for CAP_BPF and CAP_SYS_ADMIN\n"); 2820 return -EPERM; 2821 } 2822 2823 if (bpf_pseudo_func(insn) || bpf_pseudo_call(insn)) 2824 ret = add_subprog(env, i + insn->imm + 1); 2825 else 2826 ret = add_kfunc_call(env, insn->imm, insn->off); 2827 2828 if (ret < 0) 2829 return ret; 2830 } 2831 2832 /* Add a fake 'exit' subprog which could simplify subprog iteration 2833 * logic. 'subprog_cnt' should not be increased. 2834 */ 2835 subprog[env->subprog_cnt].start = insn_cnt; 2836 2837 if (env->log.level & BPF_LOG_LEVEL2) 2838 for (i = 0; i < env->subprog_cnt; i++) 2839 verbose(env, "func#%d @%d\n", i, subprog[i].start); 2840 2841 return 0; 2842 } 2843 2844 static int check_subprogs(struct bpf_verifier_env *env) 2845 { 2846 int i, subprog_start, subprog_end, off, cur_subprog = 0; 2847 struct bpf_subprog_info *subprog = env->subprog_info; 2848 struct bpf_insn *insn = env->prog->insnsi; 2849 int insn_cnt = env->prog->len; 2850 2851 /* now check that all jumps are within the same subprog */ 2852 subprog_start = subprog[cur_subprog].start; 2853 subprog_end = subprog[cur_subprog + 1].start; 2854 for (i = 0; i < insn_cnt; i++) { 2855 u8 code = insn[i].code; 2856 2857 if (code == (BPF_JMP | BPF_CALL) && 2858 insn[i].src_reg == 0 && 2859 insn[i].imm == BPF_FUNC_tail_call) 2860 subprog[cur_subprog].has_tail_call = true; 2861 if (BPF_CLASS(code) == BPF_LD && 2862 (BPF_MODE(code) == BPF_ABS || BPF_MODE(code) == BPF_IND)) 2863 subprog[cur_subprog].has_ld_abs = true; 2864 if (BPF_CLASS(code) != BPF_JMP && BPF_CLASS(code) != BPF_JMP32) 2865 goto next; 2866 if (BPF_OP(code) == BPF_EXIT || BPF_OP(code) == BPF_CALL) 2867 goto next; 2868 if (code == (BPF_JMP32 | BPF_JA)) 2869 off = i + insn[i].imm + 1; 2870 else 2871 off = i + insn[i].off + 1; 2872 if (off < subprog_start || off >= subprog_end) { 2873 verbose(env, "jump out of range from insn %d to %d\n", i, off); 2874 return -EINVAL; 2875 } 2876 next: 2877 if (i == subprog_end - 1) { 2878 /* to avoid fall-through from one subprog into another 2879 * the last insn of the subprog should be either exit 2880 * or unconditional jump back 2881 */ 2882 if (code != (BPF_JMP | BPF_EXIT) && 2883 code != (BPF_JMP32 | BPF_JA) && 2884 code != (BPF_JMP | BPF_JA)) { 2885 verbose(env, "last insn is not an exit or jmp\n"); 2886 return -EINVAL; 2887 } 2888 subprog_start = subprog_end; 2889 cur_subprog++; 2890 if (cur_subprog < env->subprog_cnt) 2891 subprog_end = subprog[cur_subprog + 1].start; 2892 } 2893 } 2894 return 0; 2895 } 2896 2897 /* Parentage chain of this register (or stack slot) should take care of all 2898 * issues like callee-saved registers, stack slot allocation time, etc. 2899 */ 2900 static int mark_reg_read(struct bpf_verifier_env *env, 2901 const struct bpf_reg_state *state, 2902 struct bpf_reg_state *parent, u8 flag) 2903 { 2904 bool writes = parent == state->parent; /* Observe write marks */ 2905 int cnt = 0; 2906 2907 while (parent) { 2908 /* if read wasn't screened by an earlier write ... */ 2909 if (writes && state->live & REG_LIVE_WRITTEN) 2910 break; 2911 if (parent->live & REG_LIVE_DONE) { 2912 verbose(env, "verifier BUG type %s var_off %lld off %d\n", 2913 reg_type_str(env, parent->type), 2914 parent->var_off.value, parent->off); 2915 return -EFAULT; 2916 } 2917 /* The first condition is more likely to be true than the 2918 * second, checked it first. 2919 */ 2920 if ((parent->live & REG_LIVE_READ) == flag || 2921 parent->live & REG_LIVE_READ64) 2922 /* The parentage chain never changes and 2923 * this parent was already marked as LIVE_READ. 2924 * There is no need to keep walking the chain again and 2925 * keep re-marking all parents as LIVE_READ. 2926 * This case happens when the same register is read 2927 * multiple times without writes into it in-between. 2928 * Also, if parent has the stronger REG_LIVE_READ64 set, 2929 * then no need to set the weak REG_LIVE_READ32. 2930 */ 2931 break; 2932 /* ... then we depend on parent's value */ 2933 parent->live |= flag; 2934 /* REG_LIVE_READ64 overrides REG_LIVE_READ32. */ 2935 if (flag == REG_LIVE_READ64) 2936 parent->live &= ~REG_LIVE_READ32; 2937 state = parent; 2938 parent = state->parent; 2939 writes = true; 2940 cnt++; 2941 } 2942 2943 if (env->longest_mark_read_walk < cnt) 2944 env->longest_mark_read_walk = cnt; 2945 return 0; 2946 } 2947 2948 static int mark_dynptr_read(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 2949 { 2950 struct bpf_func_state *state = func(env, reg); 2951 int spi, ret; 2952 2953 /* For CONST_PTR_TO_DYNPTR, it must have already been done by 2954 * check_reg_arg in check_helper_call and mark_btf_func_reg_size in 2955 * check_kfunc_call. 2956 */ 2957 if (reg->type == CONST_PTR_TO_DYNPTR) 2958 return 0; 2959 spi = dynptr_get_spi(env, reg); 2960 if (spi < 0) 2961 return spi; 2962 /* Caller ensures dynptr is valid and initialized, which means spi is in 2963 * bounds and spi is the first dynptr slot. Simply mark stack slot as 2964 * read. 2965 */ 2966 ret = mark_reg_read(env, &state->stack[spi].spilled_ptr, 2967 state->stack[spi].spilled_ptr.parent, REG_LIVE_READ64); 2968 if (ret) 2969 return ret; 2970 return mark_reg_read(env, &state->stack[spi - 1].spilled_ptr, 2971 state->stack[spi - 1].spilled_ptr.parent, REG_LIVE_READ64); 2972 } 2973 2974 static int mark_iter_read(struct bpf_verifier_env *env, struct bpf_reg_state *reg, 2975 int spi, int nr_slots) 2976 { 2977 struct bpf_func_state *state = func(env, reg); 2978 int err, i; 2979 2980 for (i = 0; i < nr_slots; i++) { 2981 struct bpf_reg_state *st = &state->stack[spi - i].spilled_ptr; 2982 2983 err = mark_reg_read(env, st, st->parent, REG_LIVE_READ64); 2984 if (err) 2985 return err; 2986 2987 mark_stack_slot_scratched(env, spi - i); 2988 } 2989 2990 return 0; 2991 } 2992 2993 /* This function is supposed to be used by the following 32-bit optimization 2994 * code only. It returns TRUE if the source or destination register operates 2995 * on 64-bit, otherwise return FALSE. 2996 */ 2997 static bool is_reg64(struct bpf_verifier_env *env, struct bpf_insn *insn, 2998 u32 regno, struct bpf_reg_state *reg, enum reg_arg_type t) 2999 { 3000 u8 code, class, op; 3001 3002 code = insn->code; 3003 class = BPF_CLASS(code); 3004 op = BPF_OP(code); 3005 if (class == BPF_JMP) { 3006 /* BPF_EXIT for "main" will reach here. Return TRUE 3007 * conservatively. 3008 */ 3009 if (op == BPF_EXIT) 3010 return true; 3011 if (op == BPF_CALL) { 3012 /* BPF to BPF call will reach here because of marking 3013 * caller saved clobber with DST_OP_NO_MARK for which we 3014 * don't care the register def because they are anyway 3015 * marked as NOT_INIT already. 3016 */ 3017 if (insn->src_reg == BPF_PSEUDO_CALL) 3018 return false; 3019 /* Helper call will reach here because of arg type 3020 * check, conservatively return TRUE. 3021 */ 3022 if (t == SRC_OP) 3023 return true; 3024 3025 return false; 3026 } 3027 } 3028 3029 if (class == BPF_ALU64 && op == BPF_END && (insn->imm == 16 || insn->imm == 32)) 3030 return false; 3031 3032 if (class == BPF_ALU64 || class == BPF_JMP || 3033 (class == BPF_ALU && op == BPF_END && insn->imm == 64)) 3034 return true; 3035 3036 if (class == BPF_ALU || class == BPF_JMP32) 3037 return false; 3038 3039 if (class == BPF_LDX) { 3040 if (t != SRC_OP) 3041 return BPF_SIZE(code) == BPF_DW; 3042 /* LDX source must be ptr. */ 3043 return true; 3044 } 3045 3046 if (class == BPF_STX) { 3047 /* BPF_STX (including atomic variants) has multiple source 3048 * operands, one of which is a ptr. Check whether the caller is 3049 * asking about it. 3050 */ 3051 if (t == SRC_OP && reg->type != SCALAR_VALUE) 3052 return true; 3053 return BPF_SIZE(code) == BPF_DW; 3054 } 3055 3056 if (class == BPF_LD) { 3057 u8 mode = BPF_MODE(code); 3058 3059 /* LD_IMM64 */ 3060 if (mode == BPF_IMM) 3061 return true; 3062 3063 /* Both LD_IND and LD_ABS return 32-bit data. */ 3064 if (t != SRC_OP) 3065 return false; 3066 3067 /* Implicit ctx ptr. */ 3068 if (regno == BPF_REG_6) 3069 return true; 3070 3071 /* Explicit source could be any width. */ 3072 return true; 3073 } 3074 3075 if (class == BPF_ST) 3076 /* The only source register for BPF_ST is a ptr. */ 3077 return true; 3078 3079 /* Conservatively return true at default. */ 3080 return true; 3081 } 3082 3083 /* Return the regno defined by the insn, or -1. */ 3084 static int insn_def_regno(const struct bpf_insn *insn) 3085 { 3086 switch (BPF_CLASS(insn->code)) { 3087 case BPF_JMP: 3088 case BPF_JMP32: 3089 case BPF_ST: 3090 return -1; 3091 case BPF_STX: 3092 if (BPF_MODE(insn->code) == BPF_ATOMIC && 3093 (insn->imm & BPF_FETCH)) { 3094 if (insn->imm == BPF_CMPXCHG) 3095 return BPF_REG_0; 3096 else 3097 return insn->src_reg; 3098 } else { 3099 return -1; 3100 } 3101 default: 3102 return insn->dst_reg; 3103 } 3104 } 3105 3106 /* Return TRUE if INSN has defined any 32-bit value explicitly. */ 3107 static bool insn_has_def32(struct bpf_verifier_env *env, struct bpf_insn *insn) 3108 { 3109 int dst_reg = insn_def_regno(insn); 3110 3111 if (dst_reg == -1) 3112 return false; 3113 3114 return !is_reg64(env, insn, dst_reg, NULL, DST_OP); 3115 } 3116 3117 static void mark_insn_zext(struct bpf_verifier_env *env, 3118 struct bpf_reg_state *reg) 3119 { 3120 s32 def_idx = reg->subreg_def; 3121 3122 if (def_idx == DEF_NOT_SUBREG) 3123 return; 3124 3125 env->insn_aux_data[def_idx - 1].zext_dst = true; 3126 /* The dst will be zero extended, so won't be sub-register anymore. */ 3127 reg->subreg_def = DEF_NOT_SUBREG; 3128 } 3129 3130 static int check_reg_arg(struct bpf_verifier_env *env, u32 regno, 3131 enum reg_arg_type t) 3132 { 3133 struct bpf_verifier_state *vstate = env->cur_state; 3134 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 3135 struct bpf_insn *insn = env->prog->insnsi + env->insn_idx; 3136 struct bpf_reg_state *reg, *regs = state->regs; 3137 bool rw64; 3138 3139 if (regno >= MAX_BPF_REG) { 3140 verbose(env, "R%d is invalid\n", regno); 3141 return -EINVAL; 3142 } 3143 3144 mark_reg_scratched(env, regno); 3145 3146 reg = ®s[regno]; 3147 rw64 = is_reg64(env, insn, regno, reg, t); 3148 if (t == SRC_OP) { 3149 /* check whether register used as source operand can be read */ 3150 if (reg->type == NOT_INIT) { 3151 verbose(env, "R%d !read_ok\n", regno); 3152 return -EACCES; 3153 } 3154 /* We don't need to worry about FP liveness because it's read-only */ 3155 if (regno == BPF_REG_FP) 3156 return 0; 3157 3158 if (rw64) 3159 mark_insn_zext(env, reg); 3160 3161 return mark_reg_read(env, reg, reg->parent, 3162 rw64 ? REG_LIVE_READ64 : REG_LIVE_READ32); 3163 } else { 3164 /* check whether register used as dest operand can be written to */ 3165 if (regno == BPF_REG_FP) { 3166 verbose(env, "frame pointer is read only\n"); 3167 return -EACCES; 3168 } 3169 reg->live |= REG_LIVE_WRITTEN; 3170 reg->subreg_def = rw64 ? DEF_NOT_SUBREG : env->insn_idx + 1; 3171 if (t == DST_OP) 3172 mark_reg_unknown(env, regs, regno); 3173 } 3174 return 0; 3175 } 3176 3177 static void mark_jmp_point(struct bpf_verifier_env *env, int idx) 3178 { 3179 env->insn_aux_data[idx].jmp_point = true; 3180 } 3181 3182 static bool is_jmp_point(struct bpf_verifier_env *env, int insn_idx) 3183 { 3184 return env->insn_aux_data[insn_idx].jmp_point; 3185 } 3186 3187 /* for any branch, call, exit record the history of jmps in the given state */ 3188 static int push_jmp_history(struct bpf_verifier_env *env, 3189 struct bpf_verifier_state *cur) 3190 { 3191 u32 cnt = cur->jmp_history_cnt; 3192 struct bpf_idx_pair *p; 3193 size_t alloc_size; 3194 3195 if (!is_jmp_point(env, env->insn_idx)) 3196 return 0; 3197 3198 cnt++; 3199 alloc_size = kmalloc_size_roundup(size_mul(cnt, sizeof(*p))); 3200 p = krealloc(cur->jmp_history, alloc_size, GFP_USER); 3201 if (!p) 3202 return -ENOMEM; 3203 p[cnt - 1].idx = env->insn_idx; 3204 p[cnt - 1].prev_idx = env->prev_insn_idx; 3205 cur->jmp_history = p; 3206 cur->jmp_history_cnt = cnt; 3207 return 0; 3208 } 3209 3210 /* Backtrack one insn at a time. If idx is not at the top of recorded 3211 * history then previous instruction came from straight line execution. 3212 * Return -ENOENT if we exhausted all instructions within given state. 3213 * 3214 * It's legal to have a bit of a looping with the same starting and ending 3215 * insn index within the same state, e.g.: 3->4->5->3, so just because current 3216 * instruction index is the same as state's first_idx doesn't mean we are 3217 * done. If there is still some jump history left, we should keep going. We 3218 * need to take into account that we might have a jump history between given 3219 * state's parent and itself, due to checkpointing. In this case, we'll have 3220 * history entry recording a jump from last instruction of parent state and 3221 * first instruction of given state. 3222 */ 3223 static int get_prev_insn_idx(struct bpf_verifier_state *st, int i, 3224 u32 *history) 3225 { 3226 u32 cnt = *history; 3227 3228 if (i == st->first_insn_idx) { 3229 if (cnt == 0) 3230 return -ENOENT; 3231 if (cnt == 1 && st->jmp_history[0].idx == i) 3232 return -ENOENT; 3233 } 3234 3235 if (cnt && st->jmp_history[cnt - 1].idx == i) { 3236 i = st->jmp_history[cnt - 1].prev_idx; 3237 (*history)--; 3238 } else { 3239 i--; 3240 } 3241 return i; 3242 } 3243 3244 static const char *disasm_kfunc_name(void *data, const struct bpf_insn *insn) 3245 { 3246 const struct btf_type *func; 3247 struct btf *desc_btf; 3248 3249 if (insn->src_reg != BPF_PSEUDO_KFUNC_CALL) 3250 return NULL; 3251 3252 desc_btf = find_kfunc_desc_btf(data, insn->off); 3253 if (IS_ERR(desc_btf)) 3254 return "<error>"; 3255 3256 func = btf_type_by_id(desc_btf, insn->imm); 3257 return btf_name_by_offset(desc_btf, func->name_off); 3258 } 3259 3260 static inline void bt_init(struct backtrack_state *bt, u32 frame) 3261 { 3262 bt->frame = frame; 3263 } 3264 3265 static inline void bt_reset(struct backtrack_state *bt) 3266 { 3267 struct bpf_verifier_env *env = bt->env; 3268 3269 memset(bt, 0, sizeof(*bt)); 3270 bt->env = env; 3271 } 3272 3273 static inline u32 bt_empty(struct backtrack_state *bt) 3274 { 3275 u64 mask = 0; 3276 int i; 3277 3278 for (i = 0; i <= bt->frame; i++) 3279 mask |= bt->reg_masks[i] | bt->stack_masks[i]; 3280 3281 return mask == 0; 3282 } 3283 3284 static inline int bt_subprog_enter(struct backtrack_state *bt) 3285 { 3286 if (bt->frame == MAX_CALL_FRAMES - 1) { 3287 verbose(bt->env, "BUG subprog enter from frame %d\n", bt->frame); 3288 WARN_ONCE(1, "verifier backtracking bug"); 3289 return -EFAULT; 3290 } 3291 bt->frame++; 3292 return 0; 3293 } 3294 3295 static inline int bt_subprog_exit(struct backtrack_state *bt) 3296 { 3297 if (bt->frame == 0) { 3298 verbose(bt->env, "BUG subprog exit from frame 0\n"); 3299 WARN_ONCE(1, "verifier backtracking bug"); 3300 return -EFAULT; 3301 } 3302 bt->frame--; 3303 return 0; 3304 } 3305 3306 static inline void bt_set_frame_reg(struct backtrack_state *bt, u32 frame, u32 reg) 3307 { 3308 bt->reg_masks[frame] |= 1 << reg; 3309 } 3310 3311 static inline void bt_clear_frame_reg(struct backtrack_state *bt, u32 frame, u32 reg) 3312 { 3313 bt->reg_masks[frame] &= ~(1 << reg); 3314 } 3315 3316 static inline void bt_set_reg(struct backtrack_state *bt, u32 reg) 3317 { 3318 bt_set_frame_reg(bt, bt->frame, reg); 3319 } 3320 3321 static inline void bt_clear_reg(struct backtrack_state *bt, u32 reg) 3322 { 3323 bt_clear_frame_reg(bt, bt->frame, reg); 3324 } 3325 3326 static inline void bt_set_frame_slot(struct backtrack_state *bt, u32 frame, u32 slot) 3327 { 3328 bt->stack_masks[frame] |= 1ull << slot; 3329 } 3330 3331 static inline void bt_clear_frame_slot(struct backtrack_state *bt, u32 frame, u32 slot) 3332 { 3333 bt->stack_masks[frame] &= ~(1ull << slot); 3334 } 3335 3336 static inline void bt_set_slot(struct backtrack_state *bt, u32 slot) 3337 { 3338 bt_set_frame_slot(bt, bt->frame, slot); 3339 } 3340 3341 static inline void bt_clear_slot(struct backtrack_state *bt, u32 slot) 3342 { 3343 bt_clear_frame_slot(bt, bt->frame, slot); 3344 } 3345 3346 static inline u32 bt_frame_reg_mask(struct backtrack_state *bt, u32 frame) 3347 { 3348 return bt->reg_masks[frame]; 3349 } 3350 3351 static inline u32 bt_reg_mask(struct backtrack_state *bt) 3352 { 3353 return bt->reg_masks[bt->frame]; 3354 } 3355 3356 static inline u64 bt_frame_stack_mask(struct backtrack_state *bt, u32 frame) 3357 { 3358 return bt->stack_masks[frame]; 3359 } 3360 3361 static inline u64 bt_stack_mask(struct backtrack_state *bt) 3362 { 3363 return bt->stack_masks[bt->frame]; 3364 } 3365 3366 static inline bool bt_is_reg_set(struct backtrack_state *bt, u32 reg) 3367 { 3368 return bt->reg_masks[bt->frame] & (1 << reg); 3369 } 3370 3371 static inline bool bt_is_slot_set(struct backtrack_state *bt, u32 slot) 3372 { 3373 return bt->stack_masks[bt->frame] & (1ull << slot); 3374 } 3375 3376 /* format registers bitmask, e.g., "r0,r2,r4" for 0x15 mask */ 3377 static void fmt_reg_mask(char *buf, ssize_t buf_sz, u32 reg_mask) 3378 { 3379 DECLARE_BITMAP(mask, 64); 3380 bool first = true; 3381 int i, n; 3382 3383 buf[0] = '\0'; 3384 3385 bitmap_from_u64(mask, reg_mask); 3386 for_each_set_bit(i, mask, 32) { 3387 n = snprintf(buf, buf_sz, "%sr%d", first ? "" : ",", i); 3388 first = false; 3389 buf += n; 3390 buf_sz -= n; 3391 if (buf_sz < 0) 3392 break; 3393 } 3394 } 3395 /* format stack slots bitmask, e.g., "-8,-24,-40" for 0x15 mask */ 3396 static void fmt_stack_mask(char *buf, ssize_t buf_sz, u64 stack_mask) 3397 { 3398 DECLARE_BITMAP(mask, 64); 3399 bool first = true; 3400 int i, n; 3401 3402 buf[0] = '\0'; 3403 3404 bitmap_from_u64(mask, stack_mask); 3405 for_each_set_bit(i, mask, 64) { 3406 n = snprintf(buf, buf_sz, "%s%d", first ? "" : ",", -(i + 1) * 8); 3407 first = false; 3408 buf += n; 3409 buf_sz -= n; 3410 if (buf_sz < 0) 3411 break; 3412 } 3413 } 3414 3415 /* For given verifier state backtrack_insn() is called from the last insn to 3416 * the first insn. Its purpose is to compute a bitmask of registers and 3417 * stack slots that needs precision in the parent verifier state. 3418 * 3419 * @idx is an index of the instruction we are currently processing; 3420 * @subseq_idx is an index of the subsequent instruction that: 3421 * - *would be* executed next, if jump history is viewed in forward order; 3422 * - *was* processed previously during backtracking. 3423 */ 3424 static int backtrack_insn(struct bpf_verifier_env *env, int idx, int subseq_idx, 3425 struct backtrack_state *bt) 3426 { 3427 const struct bpf_insn_cbs cbs = { 3428 .cb_call = disasm_kfunc_name, 3429 .cb_print = verbose, 3430 .private_data = env, 3431 }; 3432 struct bpf_insn *insn = env->prog->insnsi + idx; 3433 u8 class = BPF_CLASS(insn->code); 3434 u8 opcode = BPF_OP(insn->code); 3435 u8 mode = BPF_MODE(insn->code); 3436 u32 dreg = insn->dst_reg; 3437 u32 sreg = insn->src_reg; 3438 u32 spi, i; 3439 3440 if (insn->code == 0) 3441 return 0; 3442 if (env->log.level & BPF_LOG_LEVEL2) { 3443 fmt_reg_mask(env->tmp_str_buf, TMP_STR_BUF_LEN, bt_reg_mask(bt)); 3444 verbose(env, "mark_precise: frame%d: regs=%s ", 3445 bt->frame, env->tmp_str_buf); 3446 fmt_stack_mask(env->tmp_str_buf, TMP_STR_BUF_LEN, bt_stack_mask(bt)); 3447 verbose(env, "stack=%s before ", env->tmp_str_buf); 3448 verbose(env, "%d: ", idx); 3449 print_bpf_insn(&cbs, insn, env->allow_ptr_leaks); 3450 } 3451 3452 if (class == BPF_ALU || class == BPF_ALU64) { 3453 if (!bt_is_reg_set(bt, dreg)) 3454 return 0; 3455 if (opcode == BPF_END || opcode == BPF_NEG) { 3456 /* sreg is reserved and unused 3457 * dreg still need precision before this insn 3458 */ 3459 return 0; 3460 } else if (opcode == BPF_MOV) { 3461 if (BPF_SRC(insn->code) == BPF_X) { 3462 /* dreg = sreg or dreg = (s8, s16, s32)sreg 3463 * dreg needs precision after this insn 3464 * sreg needs precision before this insn 3465 */ 3466 bt_clear_reg(bt, dreg); 3467 bt_set_reg(bt, sreg); 3468 } else { 3469 /* dreg = K 3470 * dreg needs precision after this insn. 3471 * Corresponding register is already marked 3472 * as precise=true in this verifier state. 3473 * No further markings in parent are necessary 3474 */ 3475 bt_clear_reg(bt, dreg); 3476 } 3477 } else { 3478 if (BPF_SRC(insn->code) == BPF_X) { 3479 /* dreg += sreg 3480 * both dreg and sreg need precision 3481 * before this insn 3482 */ 3483 bt_set_reg(bt, sreg); 3484 } /* else dreg += K 3485 * dreg still needs precision before this insn 3486 */ 3487 } 3488 } else if (class == BPF_LDX) { 3489 if (!bt_is_reg_set(bt, dreg)) 3490 return 0; 3491 bt_clear_reg(bt, dreg); 3492 3493 /* scalars can only be spilled into stack w/o losing precision. 3494 * Load from any other memory can be zero extended. 3495 * The desire to keep that precision is already indicated 3496 * by 'precise' mark in corresponding register of this state. 3497 * No further tracking necessary. 3498 */ 3499 if (insn->src_reg != BPF_REG_FP) 3500 return 0; 3501 3502 /* dreg = *(u64 *)[fp - off] was a fill from the stack. 3503 * that [fp - off] slot contains scalar that needs to be 3504 * tracked with precision 3505 */ 3506 spi = (-insn->off - 1) / BPF_REG_SIZE; 3507 if (spi >= 64) { 3508 verbose(env, "BUG spi %d\n", spi); 3509 WARN_ONCE(1, "verifier backtracking bug"); 3510 return -EFAULT; 3511 } 3512 bt_set_slot(bt, spi); 3513 } else if (class == BPF_STX || class == BPF_ST) { 3514 if (bt_is_reg_set(bt, dreg)) 3515 /* stx & st shouldn't be using _scalar_ dst_reg 3516 * to access memory. It means backtracking 3517 * encountered a case of pointer subtraction. 3518 */ 3519 return -ENOTSUPP; 3520 /* scalars can only be spilled into stack */ 3521 if (insn->dst_reg != BPF_REG_FP) 3522 return 0; 3523 spi = (-insn->off - 1) / BPF_REG_SIZE; 3524 if (spi >= 64) { 3525 verbose(env, "BUG spi %d\n", spi); 3526 WARN_ONCE(1, "verifier backtracking bug"); 3527 return -EFAULT; 3528 } 3529 if (!bt_is_slot_set(bt, spi)) 3530 return 0; 3531 bt_clear_slot(bt, spi); 3532 if (class == BPF_STX) 3533 bt_set_reg(bt, sreg); 3534 } else if (class == BPF_JMP || class == BPF_JMP32) { 3535 if (bpf_pseudo_call(insn)) { 3536 int subprog_insn_idx, subprog; 3537 3538 subprog_insn_idx = idx + insn->imm + 1; 3539 subprog = find_subprog(env, subprog_insn_idx); 3540 if (subprog < 0) 3541 return -EFAULT; 3542 3543 if (subprog_is_global(env, subprog)) { 3544 /* check that jump history doesn't have any 3545 * extra instructions from subprog; the next 3546 * instruction after call to global subprog 3547 * should be literally next instruction in 3548 * caller program 3549 */ 3550 WARN_ONCE(idx + 1 != subseq_idx, "verifier backtracking bug"); 3551 /* r1-r5 are invalidated after subprog call, 3552 * so for global func call it shouldn't be set 3553 * anymore 3554 */ 3555 if (bt_reg_mask(bt) & BPF_REGMASK_ARGS) { 3556 verbose(env, "BUG regs %x\n", bt_reg_mask(bt)); 3557 WARN_ONCE(1, "verifier backtracking bug"); 3558 return -EFAULT; 3559 } 3560 /* global subprog always sets R0 */ 3561 bt_clear_reg(bt, BPF_REG_0); 3562 return 0; 3563 } else { 3564 /* static subprog call instruction, which 3565 * means that we are exiting current subprog, 3566 * so only r1-r5 could be still requested as 3567 * precise, r0 and r6-r10 or any stack slot in 3568 * the current frame should be zero by now 3569 */ 3570 if (bt_reg_mask(bt) & ~BPF_REGMASK_ARGS) { 3571 verbose(env, "BUG regs %x\n", bt_reg_mask(bt)); 3572 WARN_ONCE(1, "verifier backtracking bug"); 3573 return -EFAULT; 3574 } 3575 /* we don't track register spills perfectly, 3576 * so fallback to force-precise instead of failing */ 3577 if (bt_stack_mask(bt) != 0) 3578 return -ENOTSUPP; 3579 /* propagate r1-r5 to the caller */ 3580 for (i = BPF_REG_1; i <= BPF_REG_5; i++) { 3581 if (bt_is_reg_set(bt, i)) { 3582 bt_clear_reg(bt, i); 3583 bt_set_frame_reg(bt, bt->frame - 1, i); 3584 } 3585 } 3586 if (bt_subprog_exit(bt)) 3587 return -EFAULT; 3588 return 0; 3589 } 3590 } else if ((bpf_helper_call(insn) && 3591 is_callback_calling_function(insn->imm) && 3592 !is_async_callback_calling_function(insn->imm)) || 3593 (bpf_pseudo_kfunc_call(insn) && is_callback_calling_kfunc(insn->imm))) { 3594 /* callback-calling helper or kfunc call, which means 3595 * we are exiting from subprog, but unlike the subprog 3596 * call handling above, we shouldn't propagate 3597 * precision of r1-r5 (if any requested), as they are 3598 * not actually arguments passed directly to callback 3599 * subprogs 3600 */ 3601 if (bt_reg_mask(bt) & ~BPF_REGMASK_ARGS) { 3602 verbose(env, "BUG regs %x\n", bt_reg_mask(bt)); 3603 WARN_ONCE(1, "verifier backtracking bug"); 3604 return -EFAULT; 3605 } 3606 if (bt_stack_mask(bt) != 0) 3607 return -ENOTSUPP; 3608 /* clear r1-r5 in callback subprog's mask */ 3609 for (i = BPF_REG_1; i <= BPF_REG_5; i++) 3610 bt_clear_reg(bt, i); 3611 if (bt_subprog_exit(bt)) 3612 return -EFAULT; 3613 return 0; 3614 } else if (opcode == BPF_CALL) { 3615 /* kfunc with imm==0 is invalid and fixup_kfunc_call will 3616 * catch this error later. Make backtracking conservative 3617 * with ENOTSUPP. 3618 */ 3619 if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL && insn->imm == 0) 3620 return -ENOTSUPP; 3621 /* regular helper call sets R0 */ 3622 bt_clear_reg(bt, BPF_REG_0); 3623 if (bt_reg_mask(bt) & BPF_REGMASK_ARGS) { 3624 /* if backtracing was looking for registers R1-R5 3625 * they should have been found already. 3626 */ 3627 verbose(env, "BUG regs %x\n", bt_reg_mask(bt)); 3628 WARN_ONCE(1, "verifier backtracking bug"); 3629 return -EFAULT; 3630 } 3631 } else if (opcode == BPF_EXIT) { 3632 bool r0_precise; 3633 3634 if (bt_reg_mask(bt) & BPF_REGMASK_ARGS) { 3635 /* if backtracing was looking for registers R1-R5 3636 * they should have been found already. 3637 */ 3638 verbose(env, "BUG regs %x\n", bt_reg_mask(bt)); 3639 WARN_ONCE(1, "verifier backtracking bug"); 3640 return -EFAULT; 3641 } 3642 3643 /* BPF_EXIT in subprog or callback always returns 3644 * right after the call instruction, so by checking 3645 * whether the instruction at subseq_idx-1 is subprog 3646 * call or not we can distinguish actual exit from 3647 * *subprog* from exit from *callback*. In the former 3648 * case, we need to propagate r0 precision, if 3649 * necessary. In the former we never do that. 3650 */ 3651 r0_precise = subseq_idx - 1 >= 0 && 3652 bpf_pseudo_call(&env->prog->insnsi[subseq_idx - 1]) && 3653 bt_is_reg_set(bt, BPF_REG_0); 3654 3655 bt_clear_reg(bt, BPF_REG_0); 3656 if (bt_subprog_enter(bt)) 3657 return -EFAULT; 3658 3659 if (r0_precise) 3660 bt_set_reg(bt, BPF_REG_0); 3661 /* r6-r9 and stack slots will stay set in caller frame 3662 * bitmasks until we return back from callee(s) 3663 */ 3664 return 0; 3665 } else if (BPF_SRC(insn->code) == BPF_X) { 3666 if (!bt_is_reg_set(bt, dreg) && !bt_is_reg_set(bt, sreg)) 3667 return 0; 3668 /* dreg <cond> sreg 3669 * Both dreg and sreg need precision before 3670 * this insn. If only sreg was marked precise 3671 * before it would be equally necessary to 3672 * propagate it to dreg. 3673 */ 3674 bt_set_reg(bt, dreg); 3675 bt_set_reg(bt, sreg); 3676 /* else dreg <cond> K 3677 * Only dreg still needs precision before 3678 * this insn, so for the K-based conditional 3679 * there is nothing new to be marked. 3680 */ 3681 } 3682 } else if (class == BPF_LD) { 3683 if (!bt_is_reg_set(bt, dreg)) 3684 return 0; 3685 bt_clear_reg(bt, dreg); 3686 /* It's ld_imm64 or ld_abs or ld_ind. 3687 * For ld_imm64 no further tracking of precision 3688 * into parent is necessary 3689 */ 3690 if (mode == BPF_IND || mode == BPF_ABS) 3691 /* to be analyzed */ 3692 return -ENOTSUPP; 3693 } 3694 return 0; 3695 } 3696 3697 /* the scalar precision tracking algorithm: 3698 * . at the start all registers have precise=false. 3699 * . scalar ranges are tracked as normal through alu and jmp insns. 3700 * . once precise value of the scalar register is used in: 3701 * . ptr + scalar alu 3702 * . if (scalar cond K|scalar) 3703 * . helper_call(.., scalar, ...) where ARG_CONST is expected 3704 * backtrack through the verifier states and mark all registers and 3705 * stack slots with spilled constants that these scalar regisers 3706 * should be precise. 3707 * . during state pruning two registers (or spilled stack slots) 3708 * are equivalent if both are not precise. 3709 * 3710 * Note the verifier cannot simply walk register parentage chain, 3711 * since many different registers and stack slots could have been 3712 * used to compute single precise scalar. 3713 * 3714 * The approach of starting with precise=true for all registers and then 3715 * backtrack to mark a register as not precise when the verifier detects 3716 * that program doesn't care about specific value (e.g., when helper 3717 * takes register as ARG_ANYTHING parameter) is not safe. 3718 * 3719 * It's ok to walk single parentage chain of the verifier states. 3720 * It's possible that this backtracking will go all the way till 1st insn. 3721 * All other branches will be explored for needing precision later. 3722 * 3723 * The backtracking needs to deal with cases like: 3724 * 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) 3725 * r9 -= r8 3726 * r5 = r9 3727 * if r5 > 0x79f goto pc+7 3728 * R5_w=inv(id=0,umax_value=1951,var_off=(0x0; 0x7ff)) 3729 * r5 += 1 3730 * ... 3731 * call bpf_perf_event_output#25 3732 * where .arg5_type = ARG_CONST_SIZE_OR_ZERO 3733 * 3734 * and this case: 3735 * r6 = 1 3736 * call foo // uses callee's r6 inside to compute r0 3737 * r0 += r6 3738 * if r0 == 0 goto 3739 * 3740 * to track above reg_mask/stack_mask needs to be independent for each frame. 3741 * 3742 * Also if parent's curframe > frame where backtracking started, 3743 * the verifier need to mark registers in both frames, otherwise callees 3744 * may incorrectly prune callers. This is similar to 3745 * commit 7640ead93924 ("bpf: verifier: make sure callees don't prune with caller differences") 3746 * 3747 * For now backtracking falls back into conservative marking. 3748 */ 3749 static void mark_all_scalars_precise(struct bpf_verifier_env *env, 3750 struct bpf_verifier_state *st) 3751 { 3752 struct bpf_func_state *func; 3753 struct bpf_reg_state *reg; 3754 int i, j; 3755 3756 if (env->log.level & BPF_LOG_LEVEL2) { 3757 verbose(env, "mark_precise: frame%d: falling back to forcing all scalars precise\n", 3758 st->curframe); 3759 } 3760 3761 /* big hammer: mark all scalars precise in this path. 3762 * pop_stack may still get !precise scalars. 3763 * We also skip current state and go straight to first parent state, 3764 * because precision markings in current non-checkpointed state are 3765 * not needed. See why in the comment in __mark_chain_precision below. 3766 */ 3767 for (st = st->parent; st; st = st->parent) { 3768 for (i = 0; i <= st->curframe; i++) { 3769 func = st->frame[i]; 3770 for (j = 0; j < BPF_REG_FP; j++) { 3771 reg = &func->regs[j]; 3772 if (reg->type != SCALAR_VALUE || reg->precise) 3773 continue; 3774 reg->precise = true; 3775 if (env->log.level & BPF_LOG_LEVEL2) { 3776 verbose(env, "force_precise: frame%d: forcing r%d to be precise\n", 3777 i, j); 3778 } 3779 } 3780 for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) { 3781 if (!is_spilled_reg(&func->stack[j])) 3782 continue; 3783 reg = &func->stack[j].spilled_ptr; 3784 if (reg->type != SCALAR_VALUE || reg->precise) 3785 continue; 3786 reg->precise = true; 3787 if (env->log.level & BPF_LOG_LEVEL2) { 3788 verbose(env, "force_precise: frame%d: forcing fp%d to be precise\n", 3789 i, -(j + 1) * 8); 3790 } 3791 } 3792 } 3793 } 3794 } 3795 3796 static void mark_all_scalars_imprecise(struct bpf_verifier_env *env, struct bpf_verifier_state *st) 3797 { 3798 struct bpf_func_state *func; 3799 struct bpf_reg_state *reg; 3800 int i, j; 3801 3802 for (i = 0; i <= st->curframe; i++) { 3803 func = st->frame[i]; 3804 for (j = 0; j < BPF_REG_FP; j++) { 3805 reg = &func->regs[j]; 3806 if (reg->type != SCALAR_VALUE) 3807 continue; 3808 reg->precise = false; 3809 } 3810 for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) { 3811 if (!is_spilled_reg(&func->stack[j])) 3812 continue; 3813 reg = &func->stack[j].spilled_ptr; 3814 if (reg->type != SCALAR_VALUE) 3815 continue; 3816 reg->precise = false; 3817 } 3818 } 3819 } 3820 3821 static bool idset_contains(struct bpf_idset *s, u32 id) 3822 { 3823 u32 i; 3824 3825 for (i = 0; i < s->count; ++i) 3826 if (s->ids[i] == id) 3827 return true; 3828 3829 return false; 3830 } 3831 3832 static int idset_push(struct bpf_idset *s, u32 id) 3833 { 3834 if (WARN_ON_ONCE(s->count >= ARRAY_SIZE(s->ids))) 3835 return -EFAULT; 3836 s->ids[s->count++] = id; 3837 return 0; 3838 } 3839 3840 static void idset_reset(struct bpf_idset *s) 3841 { 3842 s->count = 0; 3843 } 3844 3845 /* Collect a set of IDs for all registers currently marked as precise in env->bt. 3846 * Mark all registers with these IDs as precise. 3847 */ 3848 static int mark_precise_scalar_ids(struct bpf_verifier_env *env, struct bpf_verifier_state *st) 3849 { 3850 struct bpf_idset *precise_ids = &env->idset_scratch; 3851 struct backtrack_state *bt = &env->bt; 3852 struct bpf_func_state *func; 3853 struct bpf_reg_state *reg; 3854 DECLARE_BITMAP(mask, 64); 3855 int i, fr; 3856 3857 idset_reset(precise_ids); 3858 3859 for (fr = bt->frame; fr >= 0; fr--) { 3860 func = st->frame[fr]; 3861 3862 bitmap_from_u64(mask, bt_frame_reg_mask(bt, fr)); 3863 for_each_set_bit(i, mask, 32) { 3864 reg = &func->regs[i]; 3865 if (!reg->id || reg->type != SCALAR_VALUE) 3866 continue; 3867 if (idset_push(precise_ids, reg->id)) 3868 return -EFAULT; 3869 } 3870 3871 bitmap_from_u64(mask, bt_frame_stack_mask(bt, fr)); 3872 for_each_set_bit(i, mask, 64) { 3873 if (i >= func->allocated_stack / BPF_REG_SIZE) 3874 break; 3875 if (!is_spilled_scalar_reg(&func->stack[i])) 3876 continue; 3877 reg = &func->stack[i].spilled_ptr; 3878 if (!reg->id) 3879 continue; 3880 if (idset_push(precise_ids, reg->id)) 3881 return -EFAULT; 3882 } 3883 } 3884 3885 for (fr = 0; fr <= st->curframe; ++fr) { 3886 func = st->frame[fr]; 3887 3888 for (i = BPF_REG_0; i < BPF_REG_10; ++i) { 3889 reg = &func->regs[i]; 3890 if (!reg->id) 3891 continue; 3892 if (!idset_contains(precise_ids, reg->id)) 3893 continue; 3894 bt_set_frame_reg(bt, fr, i); 3895 } 3896 for (i = 0; i < func->allocated_stack / BPF_REG_SIZE; ++i) { 3897 if (!is_spilled_scalar_reg(&func->stack[i])) 3898 continue; 3899 reg = &func->stack[i].spilled_ptr; 3900 if (!reg->id) 3901 continue; 3902 if (!idset_contains(precise_ids, reg->id)) 3903 continue; 3904 bt_set_frame_slot(bt, fr, i); 3905 } 3906 } 3907 3908 return 0; 3909 } 3910 3911 /* 3912 * __mark_chain_precision() backtracks BPF program instruction sequence and 3913 * chain of verifier states making sure that register *regno* (if regno >= 0) 3914 * and/or stack slot *spi* (if spi >= 0) are marked as precisely tracked 3915 * SCALARS, as well as any other registers and slots that contribute to 3916 * a tracked state of given registers/stack slots, depending on specific BPF 3917 * assembly instructions (see backtrack_insns() for exact instruction handling 3918 * logic). This backtracking relies on recorded jmp_history and is able to 3919 * traverse entire chain of parent states. This process ends only when all the 3920 * necessary registers/slots and their transitive dependencies are marked as 3921 * precise. 3922 * 3923 * One important and subtle aspect is that precise marks *do not matter* in 3924 * the currently verified state (current state). It is important to understand 3925 * why this is the case. 3926 * 3927 * First, note that current state is the state that is not yet "checkpointed", 3928 * i.e., it is not yet put into env->explored_states, and it has no children 3929 * states as well. It's ephemeral, and can end up either a) being discarded if 3930 * compatible explored state is found at some point or BPF_EXIT instruction is 3931 * reached or b) checkpointed and put into env->explored_states, branching out 3932 * into one or more children states. 3933 * 3934 * In the former case, precise markings in current state are completely 3935 * ignored by state comparison code (see regsafe() for details). Only 3936 * checkpointed ("old") state precise markings are important, and if old 3937 * state's register/slot is precise, regsafe() assumes current state's 3938 * register/slot as precise and checks value ranges exactly and precisely. If 3939 * states turn out to be compatible, current state's necessary precise 3940 * markings and any required parent states' precise markings are enforced 3941 * after the fact with propagate_precision() logic, after the fact. But it's 3942 * important to realize that in this case, even after marking current state 3943 * registers/slots as precise, we immediately discard current state. So what 3944 * actually matters is any of the precise markings propagated into current 3945 * state's parent states, which are always checkpointed (due to b) case above). 3946 * As such, for scenario a) it doesn't matter if current state has precise 3947 * markings set or not. 3948 * 3949 * Now, for the scenario b), checkpointing and forking into child(ren) 3950 * state(s). Note that before current state gets to checkpointing step, any 3951 * processed instruction always assumes precise SCALAR register/slot 3952 * knowledge: if precise value or range is useful to prune jump branch, BPF 3953 * verifier takes this opportunity enthusiastically. Similarly, when 3954 * register's value is used to calculate offset or memory address, exact 3955 * knowledge of SCALAR range is assumed, checked, and enforced. So, similar to 3956 * what we mentioned above about state comparison ignoring precise markings 3957 * during state comparison, BPF verifier ignores and also assumes precise 3958 * markings *at will* during instruction verification process. But as verifier 3959 * assumes precision, it also propagates any precision dependencies across 3960 * parent states, which are not yet finalized, so can be further restricted 3961 * based on new knowledge gained from restrictions enforced by their children 3962 * states. This is so that once those parent states are finalized, i.e., when 3963 * they have no more active children state, state comparison logic in 3964 * is_state_visited() would enforce strict and precise SCALAR ranges, if 3965 * required for correctness. 3966 * 3967 * To build a bit more intuition, note also that once a state is checkpointed, 3968 * the path we took to get to that state is not important. This is crucial 3969 * property for state pruning. When state is checkpointed and finalized at 3970 * some instruction index, it can be correctly and safely used to "short 3971 * circuit" any *compatible* state that reaches exactly the same instruction 3972 * index. I.e., if we jumped to that instruction from a completely different 3973 * code path than original finalized state was derived from, it doesn't 3974 * matter, current state can be discarded because from that instruction 3975 * forward having a compatible state will ensure we will safely reach the 3976 * exit. States describe preconditions for further exploration, but completely 3977 * forget the history of how we got here. 3978 * 3979 * This also means that even if we needed precise SCALAR range to get to 3980 * finalized state, but from that point forward *that same* SCALAR register is 3981 * never used in a precise context (i.e., it's precise value is not needed for 3982 * correctness), it's correct and safe to mark such register as "imprecise" 3983 * (i.e., precise marking set to false). This is what we rely on when we do 3984 * not set precise marking in current state. If no child state requires 3985 * precision for any given SCALAR register, it's safe to dictate that it can 3986 * be imprecise. If any child state does require this register to be precise, 3987 * we'll mark it precise later retroactively during precise markings 3988 * propagation from child state to parent states. 3989 * 3990 * Skipping precise marking setting in current state is a mild version of 3991 * relying on the above observation. But we can utilize this property even 3992 * more aggressively by proactively forgetting any precise marking in the 3993 * current state (which we inherited from the parent state), right before we 3994 * checkpoint it and branch off into new child state. This is done by 3995 * mark_all_scalars_imprecise() to hopefully get more permissive and generic 3996 * finalized states which help in short circuiting more future states. 3997 */ 3998 static int __mark_chain_precision(struct bpf_verifier_env *env, int regno) 3999 { 4000 struct backtrack_state *bt = &env->bt; 4001 struct bpf_verifier_state *st = env->cur_state; 4002 int first_idx = st->first_insn_idx; 4003 int last_idx = env->insn_idx; 4004 int subseq_idx = -1; 4005 struct bpf_func_state *func; 4006 struct bpf_reg_state *reg; 4007 bool skip_first = true; 4008 int i, fr, err; 4009 4010 if (!env->bpf_capable) 4011 return 0; 4012 4013 /* set frame number from which we are starting to backtrack */ 4014 bt_init(bt, env->cur_state->curframe); 4015 4016 /* Do sanity checks against current state of register and/or stack 4017 * slot, but don't set precise flag in current state, as precision 4018 * tracking in the current state is unnecessary. 4019 */ 4020 func = st->frame[bt->frame]; 4021 if (regno >= 0) { 4022 reg = &func->regs[regno]; 4023 if (reg->type != SCALAR_VALUE) { 4024 WARN_ONCE(1, "backtracing misuse"); 4025 return -EFAULT; 4026 } 4027 bt_set_reg(bt, regno); 4028 } 4029 4030 if (bt_empty(bt)) 4031 return 0; 4032 4033 for (;;) { 4034 DECLARE_BITMAP(mask, 64); 4035 u32 history = st->jmp_history_cnt; 4036 4037 if (env->log.level & BPF_LOG_LEVEL2) { 4038 verbose(env, "mark_precise: frame%d: last_idx %d first_idx %d subseq_idx %d \n", 4039 bt->frame, last_idx, first_idx, subseq_idx); 4040 } 4041 4042 /* If some register with scalar ID is marked as precise, 4043 * make sure that all registers sharing this ID are also precise. 4044 * This is needed to estimate effect of find_equal_scalars(). 4045 * Do this at the last instruction of each state, 4046 * bpf_reg_state::id fields are valid for these instructions. 4047 * 4048 * Allows to track precision in situation like below: 4049 * 4050 * r2 = unknown value 4051 * ... 4052 * --- state #0 --- 4053 * ... 4054 * r1 = r2 // r1 and r2 now share the same ID 4055 * ... 4056 * --- state #1 {r1.id = A, r2.id = A} --- 4057 * ... 4058 * if (r2 > 10) goto exit; // find_equal_scalars() assigns range to r1 4059 * ... 4060 * --- state #2 {r1.id = A, r2.id = A} --- 4061 * r3 = r10 4062 * r3 += r1 // need to mark both r1 and r2 4063 */ 4064 if (mark_precise_scalar_ids(env, st)) 4065 return -EFAULT; 4066 4067 if (last_idx < 0) { 4068 /* we are at the entry into subprog, which 4069 * is expected for global funcs, but only if 4070 * requested precise registers are R1-R5 4071 * (which are global func's input arguments) 4072 */ 4073 if (st->curframe == 0 && 4074 st->frame[0]->subprogno > 0 && 4075 st->frame[0]->callsite == BPF_MAIN_FUNC && 4076 bt_stack_mask(bt) == 0 && 4077 (bt_reg_mask(bt) & ~BPF_REGMASK_ARGS) == 0) { 4078 bitmap_from_u64(mask, bt_reg_mask(bt)); 4079 for_each_set_bit(i, mask, 32) { 4080 reg = &st->frame[0]->regs[i]; 4081 bt_clear_reg(bt, i); 4082 if (reg->type == SCALAR_VALUE) 4083 reg->precise = true; 4084 } 4085 return 0; 4086 } 4087 4088 verbose(env, "BUG backtracking func entry subprog %d reg_mask %x stack_mask %llx\n", 4089 st->frame[0]->subprogno, bt_reg_mask(bt), bt_stack_mask(bt)); 4090 WARN_ONCE(1, "verifier backtracking bug"); 4091 return -EFAULT; 4092 } 4093 4094 for (i = last_idx;;) { 4095 if (skip_first) { 4096 err = 0; 4097 skip_first = false; 4098 } else { 4099 err = backtrack_insn(env, i, subseq_idx, bt); 4100 } 4101 if (err == -ENOTSUPP) { 4102 mark_all_scalars_precise(env, env->cur_state); 4103 bt_reset(bt); 4104 return 0; 4105 } else if (err) { 4106 return err; 4107 } 4108 if (bt_empty(bt)) 4109 /* Found assignment(s) into tracked register in this state. 4110 * Since this state is already marked, just return. 4111 * Nothing to be tracked further in the parent state. 4112 */ 4113 return 0; 4114 subseq_idx = i; 4115 i = get_prev_insn_idx(st, i, &history); 4116 if (i == -ENOENT) 4117 break; 4118 if (i >= env->prog->len) { 4119 /* This can happen if backtracking reached insn 0 4120 * and there are still reg_mask or stack_mask 4121 * to backtrack. 4122 * It means the backtracking missed the spot where 4123 * particular register was initialized with a constant. 4124 */ 4125 verbose(env, "BUG backtracking idx %d\n", i); 4126 WARN_ONCE(1, "verifier backtracking bug"); 4127 return -EFAULT; 4128 } 4129 } 4130 st = st->parent; 4131 if (!st) 4132 break; 4133 4134 for (fr = bt->frame; fr >= 0; fr--) { 4135 func = st->frame[fr]; 4136 bitmap_from_u64(mask, bt_frame_reg_mask(bt, fr)); 4137 for_each_set_bit(i, mask, 32) { 4138 reg = &func->regs[i]; 4139 if (reg->type != SCALAR_VALUE) { 4140 bt_clear_frame_reg(bt, fr, i); 4141 continue; 4142 } 4143 if (reg->precise) 4144 bt_clear_frame_reg(bt, fr, i); 4145 else 4146 reg->precise = true; 4147 } 4148 4149 bitmap_from_u64(mask, bt_frame_stack_mask(bt, fr)); 4150 for_each_set_bit(i, mask, 64) { 4151 if (i >= func->allocated_stack / BPF_REG_SIZE) { 4152 /* the sequence of instructions: 4153 * 2: (bf) r3 = r10 4154 * 3: (7b) *(u64 *)(r3 -8) = r0 4155 * 4: (79) r4 = *(u64 *)(r10 -8) 4156 * doesn't contain jmps. It's backtracked 4157 * as a single block. 4158 * During backtracking insn 3 is not recognized as 4159 * stack access, so at the end of backtracking 4160 * stack slot fp-8 is still marked in stack_mask. 4161 * However the parent state may not have accessed 4162 * fp-8 and it's "unallocated" stack space. 4163 * In such case fallback to conservative. 4164 */ 4165 mark_all_scalars_precise(env, env->cur_state); 4166 bt_reset(bt); 4167 return 0; 4168 } 4169 4170 if (!is_spilled_scalar_reg(&func->stack[i])) { 4171 bt_clear_frame_slot(bt, fr, i); 4172 continue; 4173 } 4174 reg = &func->stack[i].spilled_ptr; 4175 if (reg->precise) 4176 bt_clear_frame_slot(bt, fr, i); 4177 else 4178 reg->precise = true; 4179 } 4180 if (env->log.level & BPF_LOG_LEVEL2) { 4181 fmt_reg_mask(env->tmp_str_buf, TMP_STR_BUF_LEN, 4182 bt_frame_reg_mask(bt, fr)); 4183 verbose(env, "mark_precise: frame%d: parent state regs=%s ", 4184 fr, env->tmp_str_buf); 4185 fmt_stack_mask(env->tmp_str_buf, TMP_STR_BUF_LEN, 4186 bt_frame_stack_mask(bt, fr)); 4187 verbose(env, "stack=%s: ", env->tmp_str_buf); 4188 print_verifier_state(env, func, true); 4189 } 4190 } 4191 4192 if (bt_empty(bt)) 4193 return 0; 4194 4195 subseq_idx = first_idx; 4196 last_idx = st->last_insn_idx; 4197 first_idx = st->first_insn_idx; 4198 } 4199 4200 /* if we still have requested precise regs or slots, we missed 4201 * something (e.g., stack access through non-r10 register), so 4202 * fallback to marking all precise 4203 */ 4204 if (!bt_empty(bt)) { 4205 mark_all_scalars_precise(env, env->cur_state); 4206 bt_reset(bt); 4207 } 4208 4209 return 0; 4210 } 4211 4212 int mark_chain_precision(struct bpf_verifier_env *env, int regno) 4213 { 4214 return __mark_chain_precision(env, regno); 4215 } 4216 4217 /* mark_chain_precision_batch() assumes that env->bt is set in the caller to 4218 * desired reg and stack masks across all relevant frames 4219 */ 4220 static int mark_chain_precision_batch(struct bpf_verifier_env *env) 4221 { 4222 return __mark_chain_precision(env, -1); 4223 } 4224 4225 static bool is_spillable_regtype(enum bpf_reg_type type) 4226 { 4227 switch (base_type(type)) { 4228 case PTR_TO_MAP_VALUE: 4229 case PTR_TO_STACK: 4230 case PTR_TO_CTX: 4231 case PTR_TO_PACKET: 4232 case PTR_TO_PACKET_META: 4233 case PTR_TO_PACKET_END: 4234 case PTR_TO_FLOW_KEYS: 4235 case CONST_PTR_TO_MAP: 4236 case PTR_TO_SOCKET: 4237 case PTR_TO_SOCK_COMMON: 4238 case PTR_TO_TCP_SOCK: 4239 case PTR_TO_XDP_SOCK: 4240 case PTR_TO_BTF_ID: 4241 case PTR_TO_BUF: 4242 case PTR_TO_MEM: 4243 case PTR_TO_FUNC: 4244 case PTR_TO_MAP_KEY: 4245 return true; 4246 default: 4247 return false; 4248 } 4249 } 4250 4251 /* Does this register contain a constant zero? */ 4252 static bool register_is_null(struct bpf_reg_state *reg) 4253 { 4254 return reg->type == SCALAR_VALUE && tnum_equals_const(reg->var_off, 0); 4255 } 4256 4257 static bool register_is_const(struct bpf_reg_state *reg) 4258 { 4259 return reg->type == SCALAR_VALUE && tnum_is_const(reg->var_off); 4260 } 4261 4262 static bool __is_scalar_unbounded(struct bpf_reg_state *reg) 4263 { 4264 return tnum_is_unknown(reg->var_off) && 4265 reg->smin_value == S64_MIN && reg->smax_value == S64_MAX && 4266 reg->umin_value == 0 && reg->umax_value == U64_MAX && 4267 reg->s32_min_value == S32_MIN && reg->s32_max_value == S32_MAX && 4268 reg->u32_min_value == 0 && reg->u32_max_value == U32_MAX; 4269 } 4270 4271 static bool register_is_bounded(struct bpf_reg_state *reg) 4272 { 4273 return reg->type == SCALAR_VALUE && !__is_scalar_unbounded(reg); 4274 } 4275 4276 static bool __is_pointer_value(bool allow_ptr_leaks, 4277 const struct bpf_reg_state *reg) 4278 { 4279 if (allow_ptr_leaks) 4280 return false; 4281 4282 return reg->type != SCALAR_VALUE; 4283 } 4284 4285 /* Copy src state preserving dst->parent and dst->live fields */ 4286 static void copy_register_state(struct bpf_reg_state *dst, const struct bpf_reg_state *src) 4287 { 4288 struct bpf_reg_state *parent = dst->parent; 4289 enum bpf_reg_liveness live = dst->live; 4290 4291 *dst = *src; 4292 dst->parent = parent; 4293 dst->live = live; 4294 } 4295 4296 static void save_register_state(struct bpf_func_state *state, 4297 int spi, struct bpf_reg_state *reg, 4298 int size) 4299 { 4300 int i; 4301 4302 copy_register_state(&state->stack[spi].spilled_ptr, reg); 4303 if (size == BPF_REG_SIZE) 4304 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN; 4305 4306 for (i = BPF_REG_SIZE; i > BPF_REG_SIZE - size; i--) 4307 state->stack[spi].slot_type[i - 1] = STACK_SPILL; 4308 4309 /* size < 8 bytes spill */ 4310 for (; i; i--) 4311 scrub_spilled_slot(&state->stack[spi].slot_type[i - 1]); 4312 } 4313 4314 static bool is_bpf_st_mem(struct bpf_insn *insn) 4315 { 4316 return BPF_CLASS(insn->code) == BPF_ST && BPF_MODE(insn->code) == BPF_MEM; 4317 } 4318 4319 /* check_stack_{read,write}_fixed_off functions track spill/fill of registers, 4320 * stack boundary and alignment are checked in check_mem_access() 4321 */ 4322 static int check_stack_write_fixed_off(struct bpf_verifier_env *env, 4323 /* stack frame we're writing to */ 4324 struct bpf_func_state *state, 4325 int off, int size, int value_regno, 4326 int insn_idx) 4327 { 4328 struct bpf_func_state *cur; /* state of the current function */ 4329 int i, slot = -off - 1, spi = slot / BPF_REG_SIZE, err; 4330 struct bpf_insn *insn = &env->prog->insnsi[insn_idx]; 4331 struct bpf_reg_state *reg = NULL; 4332 u32 dst_reg = insn->dst_reg; 4333 4334 /* caller checked that off % size == 0 and -MAX_BPF_STACK <= off < 0, 4335 * so it's aligned access and [off, off + size) are within stack limits 4336 */ 4337 if (!env->allow_ptr_leaks && 4338 is_spilled_reg(&state->stack[spi]) && 4339 size != BPF_REG_SIZE) { 4340 verbose(env, "attempt to corrupt spilled pointer on stack\n"); 4341 return -EACCES; 4342 } 4343 4344 cur = env->cur_state->frame[env->cur_state->curframe]; 4345 if (value_regno >= 0) 4346 reg = &cur->regs[value_regno]; 4347 if (!env->bypass_spec_v4) { 4348 bool sanitize = reg && is_spillable_regtype(reg->type); 4349 4350 for (i = 0; i < size; i++) { 4351 u8 type = state->stack[spi].slot_type[i]; 4352 4353 if (type != STACK_MISC && type != STACK_ZERO) { 4354 sanitize = true; 4355 break; 4356 } 4357 } 4358 4359 if (sanitize) 4360 env->insn_aux_data[insn_idx].sanitize_stack_spill = true; 4361 } 4362 4363 err = destroy_if_dynptr_stack_slot(env, state, spi); 4364 if (err) 4365 return err; 4366 4367 mark_stack_slot_scratched(env, spi); 4368 if (reg && !(off % BPF_REG_SIZE) && register_is_bounded(reg) && 4369 !register_is_null(reg) && env->bpf_capable) { 4370 if (dst_reg != BPF_REG_FP) { 4371 /* The backtracking logic can only recognize explicit 4372 * stack slot address like [fp - 8]. Other spill of 4373 * scalar via different register has to be conservative. 4374 * Backtrack from here and mark all registers as precise 4375 * that contributed into 'reg' being a constant. 4376 */ 4377 err = mark_chain_precision(env, value_regno); 4378 if (err) 4379 return err; 4380 } 4381 save_register_state(state, spi, reg, size); 4382 /* Break the relation on a narrowing spill. */ 4383 if (fls64(reg->umax_value) > BITS_PER_BYTE * size) 4384 state->stack[spi].spilled_ptr.id = 0; 4385 } else if (!reg && !(off % BPF_REG_SIZE) && is_bpf_st_mem(insn) && 4386 insn->imm != 0 && env->bpf_capable) { 4387 struct bpf_reg_state fake_reg = {}; 4388 4389 __mark_reg_known(&fake_reg, insn->imm); 4390 fake_reg.type = SCALAR_VALUE; 4391 save_register_state(state, spi, &fake_reg, size); 4392 } else if (reg && is_spillable_regtype(reg->type)) { 4393 /* register containing pointer is being spilled into stack */ 4394 if (size != BPF_REG_SIZE) { 4395 verbose_linfo(env, insn_idx, "; "); 4396 verbose(env, "invalid size of register spill\n"); 4397 return -EACCES; 4398 } 4399 if (state != cur && reg->type == PTR_TO_STACK) { 4400 verbose(env, "cannot spill pointers to stack into stack frame of the caller\n"); 4401 return -EINVAL; 4402 } 4403 save_register_state(state, spi, reg, size); 4404 } else { 4405 u8 type = STACK_MISC; 4406 4407 /* regular write of data into stack destroys any spilled ptr */ 4408 state->stack[spi].spilled_ptr.type = NOT_INIT; 4409 /* Mark slots as STACK_MISC if they belonged to spilled ptr/dynptr/iter. */ 4410 if (is_stack_slot_special(&state->stack[spi])) 4411 for (i = 0; i < BPF_REG_SIZE; i++) 4412 scrub_spilled_slot(&state->stack[spi].slot_type[i]); 4413 4414 /* only mark the slot as written if all 8 bytes were written 4415 * otherwise read propagation may incorrectly stop too soon 4416 * when stack slots are partially written. 4417 * This heuristic means that read propagation will be 4418 * conservative, since it will add reg_live_read marks 4419 * to stack slots all the way to first state when programs 4420 * writes+reads less than 8 bytes 4421 */ 4422 if (size == BPF_REG_SIZE) 4423 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN; 4424 4425 /* when we zero initialize stack slots mark them as such */ 4426 if ((reg && register_is_null(reg)) || 4427 (!reg && is_bpf_st_mem(insn) && insn->imm == 0)) { 4428 /* backtracking doesn't work for STACK_ZERO yet. */ 4429 err = mark_chain_precision(env, value_regno); 4430 if (err) 4431 return err; 4432 type = STACK_ZERO; 4433 } 4434 4435 /* Mark slots affected by this stack write. */ 4436 for (i = 0; i < size; i++) 4437 state->stack[spi].slot_type[(slot - i) % BPF_REG_SIZE] = 4438 type; 4439 } 4440 return 0; 4441 } 4442 4443 /* Write the stack: 'stack[ptr_regno + off] = value_regno'. 'ptr_regno' is 4444 * known to contain a variable offset. 4445 * This function checks whether the write is permitted and conservatively 4446 * tracks the effects of the write, considering that each stack slot in the 4447 * dynamic range is potentially written to. 4448 * 4449 * 'off' includes 'regno->off'. 4450 * 'value_regno' can be -1, meaning that an unknown value is being written to 4451 * the stack. 4452 * 4453 * Spilled pointers in range are not marked as written because we don't know 4454 * what's going to be actually written. This means that read propagation for 4455 * future reads cannot be terminated by this write. 4456 * 4457 * For privileged programs, uninitialized stack slots are considered 4458 * initialized by this write (even though we don't know exactly what offsets 4459 * are going to be written to). The idea is that we don't want the verifier to 4460 * reject future reads that access slots written to through variable offsets. 4461 */ 4462 static int check_stack_write_var_off(struct bpf_verifier_env *env, 4463 /* func where register points to */ 4464 struct bpf_func_state *state, 4465 int ptr_regno, int off, int size, 4466 int value_regno, int insn_idx) 4467 { 4468 struct bpf_func_state *cur; /* state of the current function */ 4469 int min_off, max_off; 4470 int i, err; 4471 struct bpf_reg_state *ptr_reg = NULL, *value_reg = NULL; 4472 struct bpf_insn *insn = &env->prog->insnsi[insn_idx]; 4473 bool writing_zero = false; 4474 /* set if the fact that we're writing a zero is used to let any 4475 * stack slots remain STACK_ZERO 4476 */ 4477 bool zero_used = false; 4478 4479 cur = env->cur_state->frame[env->cur_state->curframe]; 4480 ptr_reg = &cur->regs[ptr_regno]; 4481 min_off = ptr_reg->smin_value + off; 4482 max_off = ptr_reg->smax_value + off + size; 4483 if (value_regno >= 0) 4484 value_reg = &cur->regs[value_regno]; 4485 if ((value_reg && register_is_null(value_reg)) || 4486 (!value_reg && is_bpf_st_mem(insn) && insn->imm == 0)) 4487 writing_zero = true; 4488 4489 for (i = min_off; i < max_off; i++) { 4490 int spi; 4491 4492 spi = __get_spi(i); 4493 err = destroy_if_dynptr_stack_slot(env, state, spi); 4494 if (err) 4495 return err; 4496 } 4497 4498 /* Variable offset writes destroy any spilled pointers in range. */ 4499 for (i = min_off; i < max_off; i++) { 4500 u8 new_type, *stype; 4501 int slot, spi; 4502 4503 slot = -i - 1; 4504 spi = slot / BPF_REG_SIZE; 4505 stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE]; 4506 mark_stack_slot_scratched(env, spi); 4507 4508 if (!env->allow_ptr_leaks && *stype != STACK_MISC && *stype != STACK_ZERO) { 4509 /* Reject the write if range we may write to has not 4510 * been initialized beforehand. If we didn't reject 4511 * here, the ptr status would be erased below (even 4512 * though not all slots are actually overwritten), 4513 * possibly opening the door to leaks. 4514 * 4515 * We do however catch STACK_INVALID case below, and 4516 * only allow reading possibly uninitialized memory 4517 * later for CAP_PERFMON, as the write may not happen to 4518 * that slot. 4519 */ 4520 verbose(env, "spilled ptr in range of var-offset stack write; insn %d, ptr off: %d", 4521 insn_idx, i); 4522 return -EINVAL; 4523 } 4524 4525 /* Erase all spilled pointers. */ 4526 state->stack[spi].spilled_ptr.type = NOT_INIT; 4527 4528 /* Update the slot type. */ 4529 new_type = STACK_MISC; 4530 if (writing_zero && *stype == STACK_ZERO) { 4531 new_type = STACK_ZERO; 4532 zero_used = true; 4533 } 4534 /* If the slot is STACK_INVALID, we check whether it's OK to 4535 * pretend that it will be initialized by this write. The slot 4536 * might not actually be written to, and so if we mark it as 4537 * initialized future reads might leak uninitialized memory. 4538 * For privileged programs, we will accept such reads to slots 4539 * that may or may not be written because, if we're reject 4540 * them, the error would be too confusing. 4541 */ 4542 if (*stype == STACK_INVALID && !env->allow_uninit_stack) { 4543 verbose(env, "uninit stack in range of var-offset write prohibited for !root; insn %d, off: %d", 4544 insn_idx, i); 4545 return -EINVAL; 4546 } 4547 *stype = new_type; 4548 } 4549 if (zero_used) { 4550 /* backtracking doesn't work for STACK_ZERO yet. */ 4551 err = mark_chain_precision(env, value_regno); 4552 if (err) 4553 return err; 4554 } 4555 return 0; 4556 } 4557 4558 /* When register 'dst_regno' is assigned some values from stack[min_off, 4559 * max_off), we set the register's type according to the types of the 4560 * respective stack slots. If all the stack values are known to be zeros, then 4561 * so is the destination reg. Otherwise, the register is considered to be 4562 * SCALAR. This function does not deal with register filling; the caller must 4563 * ensure that all spilled registers in the stack range have been marked as 4564 * read. 4565 */ 4566 static void mark_reg_stack_read(struct bpf_verifier_env *env, 4567 /* func where src register points to */ 4568 struct bpf_func_state *ptr_state, 4569 int min_off, int max_off, int dst_regno) 4570 { 4571 struct bpf_verifier_state *vstate = env->cur_state; 4572 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 4573 int i, slot, spi; 4574 u8 *stype; 4575 int zeros = 0; 4576 4577 for (i = min_off; i < max_off; i++) { 4578 slot = -i - 1; 4579 spi = slot / BPF_REG_SIZE; 4580 mark_stack_slot_scratched(env, spi); 4581 stype = ptr_state->stack[spi].slot_type; 4582 if (stype[slot % BPF_REG_SIZE] != STACK_ZERO) 4583 break; 4584 zeros++; 4585 } 4586 if (zeros == max_off - min_off) { 4587 /* any access_size read into register is zero extended, 4588 * so the whole register == const_zero 4589 */ 4590 __mark_reg_const_zero(&state->regs[dst_regno]); 4591 /* backtracking doesn't support STACK_ZERO yet, 4592 * so mark it precise here, so that later 4593 * backtracking can stop here. 4594 * Backtracking may not need this if this register 4595 * doesn't participate in pointer adjustment. 4596 * Forward propagation of precise flag is not 4597 * necessary either. This mark is only to stop 4598 * backtracking. Any register that contributed 4599 * to const 0 was marked precise before spill. 4600 */ 4601 state->regs[dst_regno].precise = true; 4602 } else { 4603 /* have read misc data from the stack */ 4604 mark_reg_unknown(env, state->regs, dst_regno); 4605 } 4606 state->regs[dst_regno].live |= REG_LIVE_WRITTEN; 4607 } 4608 4609 /* Read the stack at 'off' and put the results into the register indicated by 4610 * 'dst_regno'. It handles reg filling if the addressed stack slot is a 4611 * spilled reg. 4612 * 4613 * 'dst_regno' can be -1, meaning that the read value is not going to a 4614 * register. 4615 * 4616 * The access is assumed to be within the current stack bounds. 4617 */ 4618 static int check_stack_read_fixed_off(struct bpf_verifier_env *env, 4619 /* func where src register points to */ 4620 struct bpf_func_state *reg_state, 4621 int off, int size, int dst_regno) 4622 { 4623 struct bpf_verifier_state *vstate = env->cur_state; 4624 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 4625 int i, slot = -off - 1, spi = slot / BPF_REG_SIZE; 4626 struct bpf_reg_state *reg; 4627 u8 *stype, type; 4628 4629 stype = reg_state->stack[spi].slot_type; 4630 reg = ®_state->stack[spi].spilled_ptr; 4631 4632 mark_stack_slot_scratched(env, spi); 4633 4634 if (is_spilled_reg(®_state->stack[spi])) { 4635 u8 spill_size = 1; 4636 4637 for (i = BPF_REG_SIZE - 1; i > 0 && stype[i - 1] == STACK_SPILL; i--) 4638 spill_size++; 4639 4640 if (size != BPF_REG_SIZE || spill_size != BPF_REG_SIZE) { 4641 if (reg->type != SCALAR_VALUE) { 4642 verbose_linfo(env, env->insn_idx, "; "); 4643 verbose(env, "invalid size of register fill\n"); 4644 return -EACCES; 4645 } 4646 4647 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64); 4648 if (dst_regno < 0) 4649 return 0; 4650 4651 if (!(off % BPF_REG_SIZE) && size == spill_size) { 4652 /* The earlier check_reg_arg() has decided the 4653 * subreg_def for this insn. Save it first. 4654 */ 4655 s32 subreg_def = state->regs[dst_regno].subreg_def; 4656 4657 copy_register_state(&state->regs[dst_regno], reg); 4658 state->regs[dst_regno].subreg_def = subreg_def; 4659 } else { 4660 for (i = 0; i < size; i++) { 4661 type = stype[(slot - i) % BPF_REG_SIZE]; 4662 if (type == STACK_SPILL) 4663 continue; 4664 if (type == STACK_MISC) 4665 continue; 4666 if (type == STACK_INVALID && env->allow_uninit_stack) 4667 continue; 4668 verbose(env, "invalid read from stack off %d+%d size %d\n", 4669 off, i, size); 4670 return -EACCES; 4671 } 4672 mark_reg_unknown(env, state->regs, dst_regno); 4673 } 4674 state->regs[dst_regno].live |= REG_LIVE_WRITTEN; 4675 return 0; 4676 } 4677 4678 if (dst_regno >= 0) { 4679 /* restore register state from stack */ 4680 copy_register_state(&state->regs[dst_regno], reg); 4681 /* mark reg as written since spilled pointer state likely 4682 * has its liveness marks cleared by is_state_visited() 4683 * which resets stack/reg liveness for state transitions 4684 */ 4685 state->regs[dst_regno].live |= REG_LIVE_WRITTEN; 4686 } else if (__is_pointer_value(env->allow_ptr_leaks, reg)) { 4687 /* If dst_regno==-1, the caller is asking us whether 4688 * it is acceptable to use this value as a SCALAR_VALUE 4689 * (e.g. for XADD). 4690 * We must not allow unprivileged callers to do that 4691 * with spilled pointers. 4692 */ 4693 verbose(env, "leaking pointer from stack off %d\n", 4694 off); 4695 return -EACCES; 4696 } 4697 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64); 4698 } else { 4699 for (i = 0; i < size; i++) { 4700 type = stype[(slot - i) % BPF_REG_SIZE]; 4701 if (type == STACK_MISC) 4702 continue; 4703 if (type == STACK_ZERO) 4704 continue; 4705 if (type == STACK_INVALID && env->allow_uninit_stack) 4706 continue; 4707 verbose(env, "invalid read from stack off %d+%d size %d\n", 4708 off, i, size); 4709 return -EACCES; 4710 } 4711 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64); 4712 if (dst_regno >= 0) 4713 mark_reg_stack_read(env, reg_state, off, off + size, dst_regno); 4714 } 4715 return 0; 4716 } 4717 4718 enum bpf_access_src { 4719 ACCESS_DIRECT = 1, /* the access is performed by an instruction */ 4720 ACCESS_HELPER = 2, /* the access is performed by a helper */ 4721 }; 4722 4723 static int check_stack_range_initialized(struct bpf_verifier_env *env, 4724 int regno, int off, int access_size, 4725 bool zero_size_allowed, 4726 enum bpf_access_src type, 4727 struct bpf_call_arg_meta *meta); 4728 4729 static struct bpf_reg_state *reg_state(struct bpf_verifier_env *env, int regno) 4730 { 4731 return cur_regs(env) + regno; 4732 } 4733 4734 /* Read the stack at 'ptr_regno + off' and put the result into the register 4735 * 'dst_regno'. 4736 * 'off' includes the pointer register's fixed offset(i.e. 'ptr_regno.off'), 4737 * but not its variable offset. 4738 * 'size' is assumed to be <= reg size and the access is assumed to be aligned. 4739 * 4740 * As opposed to check_stack_read_fixed_off, this function doesn't deal with 4741 * filling registers (i.e. reads of spilled register cannot be detected when 4742 * the offset is not fixed). We conservatively mark 'dst_regno' as containing 4743 * SCALAR_VALUE. That's why we assert that the 'ptr_regno' has a variable 4744 * offset; for a fixed offset check_stack_read_fixed_off should be used 4745 * instead. 4746 */ 4747 static int check_stack_read_var_off(struct bpf_verifier_env *env, 4748 int ptr_regno, int off, int size, int dst_regno) 4749 { 4750 /* The state of the source register. */ 4751 struct bpf_reg_state *reg = reg_state(env, ptr_regno); 4752 struct bpf_func_state *ptr_state = func(env, reg); 4753 int err; 4754 int min_off, max_off; 4755 4756 /* Note that we pass a NULL meta, so raw access will not be permitted. 4757 */ 4758 err = check_stack_range_initialized(env, ptr_regno, off, size, 4759 false, ACCESS_DIRECT, NULL); 4760 if (err) 4761 return err; 4762 4763 min_off = reg->smin_value + off; 4764 max_off = reg->smax_value + off; 4765 mark_reg_stack_read(env, ptr_state, min_off, max_off + size, dst_regno); 4766 return 0; 4767 } 4768 4769 /* check_stack_read dispatches to check_stack_read_fixed_off or 4770 * check_stack_read_var_off. 4771 * 4772 * The caller must ensure that the offset falls within the allocated stack 4773 * bounds. 4774 * 4775 * 'dst_regno' is a register which will receive the value from the stack. It 4776 * can be -1, meaning that the read value is not going to a register. 4777 */ 4778 static int check_stack_read(struct bpf_verifier_env *env, 4779 int ptr_regno, int off, int size, 4780 int dst_regno) 4781 { 4782 struct bpf_reg_state *reg = reg_state(env, ptr_regno); 4783 struct bpf_func_state *state = func(env, reg); 4784 int err; 4785 /* Some accesses are only permitted with a static offset. */ 4786 bool var_off = !tnum_is_const(reg->var_off); 4787 4788 /* The offset is required to be static when reads don't go to a 4789 * register, in order to not leak pointers (see 4790 * check_stack_read_fixed_off). 4791 */ 4792 if (dst_regno < 0 && var_off) { 4793 char tn_buf[48]; 4794 4795 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 4796 verbose(env, "variable offset stack pointer cannot be passed into helper function; var_off=%s off=%d size=%d\n", 4797 tn_buf, off, size); 4798 return -EACCES; 4799 } 4800 /* Variable offset is prohibited for unprivileged mode for simplicity 4801 * since it requires corresponding support in Spectre masking for stack 4802 * ALU. See also retrieve_ptr_limit(). The check in 4803 * check_stack_access_for_ptr_arithmetic() called by 4804 * adjust_ptr_min_max_vals() prevents users from creating stack pointers 4805 * with variable offsets, therefore no check is required here. Further, 4806 * just checking it here would be insufficient as speculative stack 4807 * writes could still lead to unsafe speculative behaviour. 4808 */ 4809 if (!var_off) { 4810 off += reg->var_off.value; 4811 err = check_stack_read_fixed_off(env, state, off, size, 4812 dst_regno); 4813 } else { 4814 /* Variable offset stack reads need more conservative handling 4815 * than fixed offset ones. Note that dst_regno >= 0 on this 4816 * branch. 4817 */ 4818 err = check_stack_read_var_off(env, ptr_regno, off, size, 4819 dst_regno); 4820 } 4821 return err; 4822 } 4823 4824 4825 /* check_stack_write dispatches to check_stack_write_fixed_off or 4826 * check_stack_write_var_off. 4827 * 4828 * 'ptr_regno' is the register used as a pointer into the stack. 4829 * 'off' includes 'ptr_regno->off', but not its variable offset (if any). 4830 * 'value_regno' is the register whose value we're writing to the stack. It can 4831 * be -1, meaning that we're not writing from a register. 4832 * 4833 * The caller must ensure that the offset falls within the maximum stack size. 4834 */ 4835 static int check_stack_write(struct bpf_verifier_env *env, 4836 int ptr_regno, int off, int size, 4837 int value_regno, int insn_idx) 4838 { 4839 struct bpf_reg_state *reg = reg_state(env, ptr_regno); 4840 struct bpf_func_state *state = func(env, reg); 4841 int err; 4842 4843 if (tnum_is_const(reg->var_off)) { 4844 off += reg->var_off.value; 4845 err = check_stack_write_fixed_off(env, state, off, size, 4846 value_regno, insn_idx); 4847 } else { 4848 /* Variable offset stack reads need more conservative handling 4849 * than fixed offset ones. 4850 */ 4851 err = check_stack_write_var_off(env, state, 4852 ptr_regno, off, size, 4853 value_regno, insn_idx); 4854 } 4855 return err; 4856 } 4857 4858 static int check_map_access_type(struct bpf_verifier_env *env, u32 regno, 4859 int off, int size, enum bpf_access_type type) 4860 { 4861 struct bpf_reg_state *regs = cur_regs(env); 4862 struct bpf_map *map = regs[regno].map_ptr; 4863 u32 cap = bpf_map_flags_to_cap(map); 4864 4865 if (type == BPF_WRITE && !(cap & BPF_MAP_CAN_WRITE)) { 4866 verbose(env, "write into map forbidden, value_size=%d off=%d size=%d\n", 4867 map->value_size, off, size); 4868 return -EACCES; 4869 } 4870 4871 if (type == BPF_READ && !(cap & BPF_MAP_CAN_READ)) { 4872 verbose(env, "read from map forbidden, value_size=%d off=%d size=%d\n", 4873 map->value_size, off, size); 4874 return -EACCES; 4875 } 4876 4877 return 0; 4878 } 4879 4880 /* check read/write into memory region (e.g., map value, ringbuf sample, etc) */ 4881 static int __check_mem_access(struct bpf_verifier_env *env, int regno, 4882 int off, int size, u32 mem_size, 4883 bool zero_size_allowed) 4884 { 4885 bool size_ok = size > 0 || (size == 0 && zero_size_allowed); 4886 struct bpf_reg_state *reg; 4887 4888 if (off >= 0 && size_ok && (u64)off + size <= mem_size) 4889 return 0; 4890 4891 reg = &cur_regs(env)[regno]; 4892 switch (reg->type) { 4893 case PTR_TO_MAP_KEY: 4894 verbose(env, "invalid access to map key, key_size=%d off=%d size=%d\n", 4895 mem_size, off, size); 4896 break; 4897 case PTR_TO_MAP_VALUE: 4898 verbose(env, "invalid access to map value, value_size=%d off=%d size=%d\n", 4899 mem_size, off, size); 4900 break; 4901 case PTR_TO_PACKET: 4902 case PTR_TO_PACKET_META: 4903 case PTR_TO_PACKET_END: 4904 verbose(env, "invalid access to packet, off=%d size=%d, R%d(id=%d,off=%d,r=%d)\n", 4905 off, size, regno, reg->id, off, mem_size); 4906 break; 4907 case PTR_TO_MEM: 4908 default: 4909 verbose(env, "invalid access to memory, mem_size=%u off=%d size=%d\n", 4910 mem_size, off, size); 4911 } 4912 4913 return -EACCES; 4914 } 4915 4916 /* check read/write into a memory region with possible variable offset */ 4917 static int check_mem_region_access(struct bpf_verifier_env *env, u32 regno, 4918 int off, int size, u32 mem_size, 4919 bool zero_size_allowed) 4920 { 4921 struct bpf_verifier_state *vstate = env->cur_state; 4922 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 4923 struct bpf_reg_state *reg = &state->regs[regno]; 4924 int err; 4925 4926 /* We may have adjusted the register pointing to memory region, so we 4927 * need to try adding each of min_value and max_value to off 4928 * to make sure our theoretical access will be safe. 4929 * 4930 * The minimum value is only important with signed 4931 * comparisons where we can't assume the floor of a 4932 * value is 0. If we are using signed variables for our 4933 * index'es we need to make sure that whatever we use 4934 * will have a set floor within our range. 4935 */ 4936 if (reg->smin_value < 0 && 4937 (reg->smin_value == S64_MIN || 4938 (off + reg->smin_value != (s64)(s32)(off + reg->smin_value)) || 4939 reg->smin_value + off < 0)) { 4940 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n", 4941 regno); 4942 return -EACCES; 4943 } 4944 err = __check_mem_access(env, regno, reg->smin_value + off, size, 4945 mem_size, zero_size_allowed); 4946 if (err) { 4947 verbose(env, "R%d min value is outside of the allowed memory range\n", 4948 regno); 4949 return err; 4950 } 4951 4952 /* If we haven't set a max value then we need to bail since we can't be 4953 * sure we won't do bad things. 4954 * If reg->umax_value + off could overflow, treat that as unbounded too. 4955 */ 4956 if (reg->umax_value >= BPF_MAX_VAR_OFF) { 4957 verbose(env, "R%d unbounded memory access, make sure to bounds check any such access\n", 4958 regno); 4959 return -EACCES; 4960 } 4961 err = __check_mem_access(env, regno, reg->umax_value + off, size, 4962 mem_size, zero_size_allowed); 4963 if (err) { 4964 verbose(env, "R%d max value is outside of the allowed memory range\n", 4965 regno); 4966 return err; 4967 } 4968 4969 return 0; 4970 } 4971 4972 static int __check_ptr_off_reg(struct bpf_verifier_env *env, 4973 const struct bpf_reg_state *reg, int regno, 4974 bool fixed_off_ok) 4975 { 4976 /* Access to this pointer-typed register or passing it to a helper 4977 * is only allowed in its original, unmodified form. 4978 */ 4979 4980 if (reg->off < 0) { 4981 verbose(env, "negative offset %s ptr R%d off=%d disallowed\n", 4982 reg_type_str(env, reg->type), regno, reg->off); 4983 return -EACCES; 4984 } 4985 4986 if (!fixed_off_ok && reg->off) { 4987 verbose(env, "dereference of modified %s ptr R%d off=%d disallowed\n", 4988 reg_type_str(env, reg->type), regno, reg->off); 4989 return -EACCES; 4990 } 4991 4992 if (!tnum_is_const(reg->var_off) || reg->var_off.value) { 4993 char tn_buf[48]; 4994 4995 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 4996 verbose(env, "variable %s access var_off=%s disallowed\n", 4997 reg_type_str(env, reg->type), tn_buf); 4998 return -EACCES; 4999 } 5000 5001 return 0; 5002 } 5003 5004 int check_ptr_off_reg(struct bpf_verifier_env *env, 5005 const struct bpf_reg_state *reg, int regno) 5006 { 5007 return __check_ptr_off_reg(env, reg, regno, false); 5008 } 5009 5010 static int map_kptr_match_type(struct bpf_verifier_env *env, 5011 struct btf_field *kptr_field, 5012 struct bpf_reg_state *reg, u32 regno) 5013 { 5014 const char *targ_name = btf_type_name(kptr_field->kptr.btf, kptr_field->kptr.btf_id); 5015 int perm_flags; 5016 const char *reg_name = ""; 5017 5018 if (btf_is_kernel(reg->btf)) { 5019 perm_flags = PTR_MAYBE_NULL | PTR_TRUSTED | MEM_RCU; 5020 5021 /* Only unreferenced case accepts untrusted pointers */ 5022 if (kptr_field->type == BPF_KPTR_UNREF) 5023 perm_flags |= PTR_UNTRUSTED; 5024 } else { 5025 perm_flags = PTR_MAYBE_NULL | MEM_ALLOC; 5026 } 5027 5028 if (base_type(reg->type) != PTR_TO_BTF_ID || (type_flag(reg->type) & ~perm_flags)) 5029 goto bad_type; 5030 5031 /* We need to verify reg->type and reg->btf, before accessing reg->btf */ 5032 reg_name = btf_type_name(reg->btf, reg->btf_id); 5033 5034 /* For ref_ptr case, release function check should ensure we get one 5035 * referenced PTR_TO_BTF_ID, and that its fixed offset is 0. For the 5036 * normal store of unreferenced kptr, we must ensure var_off is zero. 5037 * Since ref_ptr cannot be accessed directly by BPF insns, checks for 5038 * reg->off and reg->ref_obj_id are not needed here. 5039 */ 5040 if (__check_ptr_off_reg(env, reg, regno, true)) 5041 return -EACCES; 5042 5043 /* A full type match is needed, as BTF can be vmlinux, module or prog BTF, and 5044 * we also need to take into account the reg->off. 5045 * 5046 * We want to support cases like: 5047 * 5048 * struct foo { 5049 * struct bar br; 5050 * struct baz bz; 5051 * }; 5052 * 5053 * struct foo *v; 5054 * v = func(); // PTR_TO_BTF_ID 5055 * val->foo = v; // reg->off is zero, btf and btf_id match type 5056 * val->bar = &v->br; // reg->off is still zero, but we need to retry with 5057 * // first member type of struct after comparison fails 5058 * val->baz = &v->bz; // reg->off is non-zero, so struct needs to be walked 5059 * // to match type 5060 * 5061 * In the kptr_ref case, check_func_arg_reg_off already ensures reg->off 5062 * is zero. We must also ensure that btf_struct_ids_match does not walk 5063 * the struct to match type against first member of struct, i.e. reject 5064 * second case from above. Hence, when type is BPF_KPTR_REF, we set 5065 * strict mode to true for type match. 5066 */ 5067 if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off, 5068 kptr_field->kptr.btf, kptr_field->kptr.btf_id, 5069 kptr_field->type == BPF_KPTR_REF)) 5070 goto bad_type; 5071 return 0; 5072 bad_type: 5073 verbose(env, "invalid kptr access, R%d type=%s%s ", regno, 5074 reg_type_str(env, reg->type), reg_name); 5075 verbose(env, "expected=%s%s", reg_type_str(env, PTR_TO_BTF_ID), targ_name); 5076 if (kptr_field->type == BPF_KPTR_UNREF) 5077 verbose(env, " or %s%s\n", reg_type_str(env, PTR_TO_BTF_ID | PTR_UNTRUSTED), 5078 targ_name); 5079 else 5080 verbose(env, "\n"); 5081 return -EINVAL; 5082 } 5083 5084 /* The non-sleepable programs and sleepable programs with explicit bpf_rcu_read_lock() 5085 * can dereference RCU protected pointers and result is PTR_TRUSTED. 5086 */ 5087 static bool in_rcu_cs(struct bpf_verifier_env *env) 5088 { 5089 return env->cur_state->active_rcu_lock || 5090 env->cur_state->active_lock.ptr || 5091 !env->prog->aux->sleepable; 5092 } 5093 5094 /* Once GCC supports btf_type_tag the following mechanism will be replaced with tag check */ 5095 BTF_SET_START(rcu_protected_types) 5096 BTF_ID(struct, prog_test_ref_kfunc) 5097 BTF_ID(struct, cgroup) 5098 BTF_ID(struct, bpf_cpumask) 5099 BTF_ID(struct, task_struct) 5100 BTF_SET_END(rcu_protected_types) 5101 5102 static bool rcu_protected_object(const struct btf *btf, u32 btf_id) 5103 { 5104 if (!btf_is_kernel(btf)) 5105 return false; 5106 return btf_id_set_contains(&rcu_protected_types, btf_id); 5107 } 5108 5109 static bool rcu_safe_kptr(const struct btf_field *field) 5110 { 5111 const struct btf_field_kptr *kptr = &field->kptr; 5112 5113 return field->type == BPF_KPTR_REF && rcu_protected_object(kptr->btf, kptr->btf_id); 5114 } 5115 5116 static int check_map_kptr_access(struct bpf_verifier_env *env, u32 regno, 5117 int value_regno, int insn_idx, 5118 struct btf_field *kptr_field) 5119 { 5120 struct bpf_insn *insn = &env->prog->insnsi[insn_idx]; 5121 int class = BPF_CLASS(insn->code); 5122 struct bpf_reg_state *val_reg; 5123 5124 /* Things we already checked for in check_map_access and caller: 5125 * - Reject cases where variable offset may touch kptr 5126 * - size of access (must be BPF_DW) 5127 * - tnum_is_const(reg->var_off) 5128 * - kptr_field->offset == off + reg->var_off.value 5129 */ 5130 /* Only BPF_[LDX,STX,ST] | BPF_MEM | BPF_DW is supported */ 5131 if (BPF_MODE(insn->code) != BPF_MEM) { 5132 verbose(env, "kptr in map can only be accessed using BPF_MEM instruction mode\n"); 5133 return -EACCES; 5134 } 5135 5136 /* We only allow loading referenced kptr, since it will be marked as 5137 * untrusted, similar to unreferenced kptr. 5138 */ 5139 if (class != BPF_LDX && kptr_field->type == BPF_KPTR_REF) { 5140 verbose(env, "store to referenced kptr disallowed\n"); 5141 return -EACCES; 5142 } 5143 5144 if (class == BPF_LDX) { 5145 val_reg = reg_state(env, value_regno); 5146 /* We can simply mark the value_regno receiving the pointer 5147 * value from map as PTR_TO_BTF_ID, with the correct type. 5148 */ 5149 mark_btf_ld_reg(env, cur_regs(env), value_regno, PTR_TO_BTF_ID, kptr_field->kptr.btf, 5150 kptr_field->kptr.btf_id, 5151 rcu_safe_kptr(kptr_field) && in_rcu_cs(env) ? 5152 PTR_MAYBE_NULL | MEM_RCU : 5153 PTR_MAYBE_NULL | PTR_UNTRUSTED); 5154 /* For mark_ptr_or_null_reg */ 5155 val_reg->id = ++env->id_gen; 5156 } else if (class == BPF_STX) { 5157 val_reg = reg_state(env, value_regno); 5158 if (!register_is_null(val_reg) && 5159 map_kptr_match_type(env, kptr_field, val_reg, value_regno)) 5160 return -EACCES; 5161 } else if (class == BPF_ST) { 5162 if (insn->imm) { 5163 verbose(env, "BPF_ST imm must be 0 when storing to kptr at off=%u\n", 5164 kptr_field->offset); 5165 return -EACCES; 5166 } 5167 } else { 5168 verbose(env, "kptr in map can only be accessed using BPF_LDX/BPF_STX/BPF_ST\n"); 5169 return -EACCES; 5170 } 5171 return 0; 5172 } 5173 5174 /* check read/write into a map element with possible variable offset */ 5175 static int check_map_access(struct bpf_verifier_env *env, u32 regno, 5176 int off, int size, bool zero_size_allowed, 5177 enum bpf_access_src src) 5178 { 5179 struct bpf_verifier_state *vstate = env->cur_state; 5180 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 5181 struct bpf_reg_state *reg = &state->regs[regno]; 5182 struct bpf_map *map = reg->map_ptr; 5183 struct btf_record *rec; 5184 int err, i; 5185 5186 err = check_mem_region_access(env, regno, off, size, map->value_size, 5187 zero_size_allowed); 5188 if (err) 5189 return err; 5190 5191 if (IS_ERR_OR_NULL(map->record)) 5192 return 0; 5193 rec = map->record; 5194 for (i = 0; i < rec->cnt; i++) { 5195 struct btf_field *field = &rec->fields[i]; 5196 u32 p = field->offset; 5197 5198 /* If any part of a field can be touched by load/store, reject 5199 * this program. To check that [x1, x2) overlaps with [y1, y2), 5200 * it is sufficient to check x1 < y2 && y1 < x2. 5201 */ 5202 if (reg->smin_value + off < p + btf_field_type_size(field->type) && 5203 p < reg->umax_value + off + size) { 5204 switch (field->type) { 5205 case BPF_KPTR_UNREF: 5206 case BPF_KPTR_REF: 5207 if (src != ACCESS_DIRECT) { 5208 verbose(env, "kptr cannot be accessed indirectly by helper\n"); 5209 return -EACCES; 5210 } 5211 if (!tnum_is_const(reg->var_off)) { 5212 verbose(env, "kptr access cannot have variable offset\n"); 5213 return -EACCES; 5214 } 5215 if (p != off + reg->var_off.value) { 5216 verbose(env, "kptr access misaligned expected=%u off=%llu\n", 5217 p, off + reg->var_off.value); 5218 return -EACCES; 5219 } 5220 if (size != bpf_size_to_bytes(BPF_DW)) { 5221 verbose(env, "kptr access size must be BPF_DW\n"); 5222 return -EACCES; 5223 } 5224 break; 5225 default: 5226 verbose(env, "%s cannot be accessed directly by load/store\n", 5227 btf_field_type_name(field->type)); 5228 return -EACCES; 5229 } 5230 } 5231 } 5232 return 0; 5233 } 5234 5235 #define MAX_PACKET_OFF 0xffff 5236 5237 static bool may_access_direct_pkt_data(struct bpf_verifier_env *env, 5238 const struct bpf_call_arg_meta *meta, 5239 enum bpf_access_type t) 5240 { 5241 enum bpf_prog_type prog_type = resolve_prog_type(env->prog); 5242 5243 switch (prog_type) { 5244 /* Program types only with direct read access go here! */ 5245 case BPF_PROG_TYPE_LWT_IN: 5246 case BPF_PROG_TYPE_LWT_OUT: 5247 case BPF_PROG_TYPE_LWT_SEG6LOCAL: 5248 case BPF_PROG_TYPE_SK_REUSEPORT: 5249 case BPF_PROG_TYPE_FLOW_DISSECTOR: 5250 case BPF_PROG_TYPE_CGROUP_SKB: 5251 if (t == BPF_WRITE) 5252 return false; 5253 fallthrough; 5254 5255 /* Program types with direct read + write access go here! */ 5256 case BPF_PROG_TYPE_SCHED_CLS: 5257 case BPF_PROG_TYPE_SCHED_ACT: 5258 case BPF_PROG_TYPE_XDP: 5259 case BPF_PROG_TYPE_LWT_XMIT: 5260 case BPF_PROG_TYPE_SK_SKB: 5261 case BPF_PROG_TYPE_SK_MSG: 5262 if (meta) 5263 return meta->pkt_access; 5264 5265 env->seen_direct_write = true; 5266 return true; 5267 5268 case BPF_PROG_TYPE_CGROUP_SOCKOPT: 5269 if (t == BPF_WRITE) 5270 env->seen_direct_write = true; 5271 5272 return true; 5273 5274 default: 5275 return false; 5276 } 5277 } 5278 5279 static int check_packet_access(struct bpf_verifier_env *env, u32 regno, int off, 5280 int size, bool zero_size_allowed) 5281 { 5282 struct bpf_reg_state *regs = cur_regs(env); 5283 struct bpf_reg_state *reg = ®s[regno]; 5284 int err; 5285 5286 /* We may have added a variable offset to the packet pointer; but any 5287 * reg->range we have comes after that. We are only checking the fixed 5288 * offset. 5289 */ 5290 5291 /* We don't allow negative numbers, because we aren't tracking enough 5292 * detail to prove they're safe. 5293 */ 5294 if (reg->smin_value < 0) { 5295 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n", 5296 regno); 5297 return -EACCES; 5298 } 5299 5300 err = reg->range < 0 ? -EINVAL : 5301 __check_mem_access(env, regno, off, size, reg->range, 5302 zero_size_allowed); 5303 if (err) { 5304 verbose(env, "R%d offset is outside of the packet\n", regno); 5305 return err; 5306 } 5307 5308 /* __check_mem_access has made sure "off + size - 1" is within u16. 5309 * reg->umax_value can't be bigger than MAX_PACKET_OFF which is 0xffff, 5310 * otherwise find_good_pkt_pointers would have refused to set range info 5311 * that __check_mem_access would have rejected this pkt access. 5312 * Therefore, "off + reg->umax_value + size - 1" won't overflow u32. 5313 */ 5314 env->prog->aux->max_pkt_offset = 5315 max_t(u32, env->prog->aux->max_pkt_offset, 5316 off + reg->umax_value + size - 1); 5317 5318 return err; 5319 } 5320 5321 /* check access to 'struct bpf_context' fields. Supports fixed offsets only */ 5322 static int check_ctx_access(struct bpf_verifier_env *env, int insn_idx, int off, int size, 5323 enum bpf_access_type t, enum bpf_reg_type *reg_type, 5324 struct btf **btf, u32 *btf_id) 5325 { 5326 struct bpf_insn_access_aux info = { 5327 .reg_type = *reg_type, 5328 .log = &env->log, 5329 }; 5330 5331 if (env->ops->is_valid_access && 5332 env->ops->is_valid_access(off, size, t, env->prog, &info)) { 5333 /* A non zero info.ctx_field_size indicates that this field is a 5334 * candidate for later verifier transformation to load the whole 5335 * field and then apply a mask when accessed with a narrower 5336 * access than actual ctx access size. A zero info.ctx_field_size 5337 * will only allow for whole field access and rejects any other 5338 * type of narrower access. 5339 */ 5340 *reg_type = info.reg_type; 5341 5342 if (base_type(*reg_type) == PTR_TO_BTF_ID) { 5343 *btf = info.btf; 5344 *btf_id = info.btf_id; 5345 } else { 5346 env->insn_aux_data[insn_idx].ctx_field_size = info.ctx_field_size; 5347 } 5348 /* remember the offset of last byte accessed in ctx */ 5349 if (env->prog->aux->max_ctx_offset < off + size) 5350 env->prog->aux->max_ctx_offset = off + size; 5351 return 0; 5352 } 5353 5354 verbose(env, "invalid bpf_context access off=%d size=%d\n", off, size); 5355 return -EACCES; 5356 } 5357 5358 static int check_flow_keys_access(struct bpf_verifier_env *env, int off, 5359 int size) 5360 { 5361 if (size < 0 || off < 0 || 5362 (u64)off + size > sizeof(struct bpf_flow_keys)) { 5363 verbose(env, "invalid access to flow keys off=%d size=%d\n", 5364 off, size); 5365 return -EACCES; 5366 } 5367 return 0; 5368 } 5369 5370 static int check_sock_access(struct bpf_verifier_env *env, int insn_idx, 5371 u32 regno, int off, int size, 5372 enum bpf_access_type t) 5373 { 5374 struct bpf_reg_state *regs = cur_regs(env); 5375 struct bpf_reg_state *reg = ®s[regno]; 5376 struct bpf_insn_access_aux info = {}; 5377 bool valid; 5378 5379 if (reg->smin_value < 0) { 5380 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n", 5381 regno); 5382 return -EACCES; 5383 } 5384 5385 switch (reg->type) { 5386 case PTR_TO_SOCK_COMMON: 5387 valid = bpf_sock_common_is_valid_access(off, size, t, &info); 5388 break; 5389 case PTR_TO_SOCKET: 5390 valid = bpf_sock_is_valid_access(off, size, t, &info); 5391 break; 5392 case PTR_TO_TCP_SOCK: 5393 valid = bpf_tcp_sock_is_valid_access(off, size, t, &info); 5394 break; 5395 case PTR_TO_XDP_SOCK: 5396 valid = bpf_xdp_sock_is_valid_access(off, size, t, &info); 5397 break; 5398 default: 5399 valid = false; 5400 } 5401 5402 5403 if (valid) { 5404 env->insn_aux_data[insn_idx].ctx_field_size = 5405 info.ctx_field_size; 5406 return 0; 5407 } 5408 5409 verbose(env, "R%d invalid %s access off=%d size=%d\n", 5410 regno, reg_type_str(env, reg->type), off, size); 5411 5412 return -EACCES; 5413 } 5414 5415 static bool is_pointer_value(struct bpf_verifier_env *env, int regno) 5416 { 5417 return __is_pointer_value(env->allow_ptr_leaks, reg_state(env, regno)); 5418 } 5419 5420 static bool is_ctx_reg(struct bpf_verifier_env *env, int regno) 5421 { 5422 const struct bpf_reg_state *reg = reg_state(env, regno); 5423 5424 return reg->type == PTR_TO_CTX; 5425 } 5426 5427 static bool is_sk_reg(struct bpf_verifier_env *env, int regno) 5428 { 5429 const struct bpf_reg_state *reg = reg_state(env, regno); 5430 5431 return type_is_sk_pointer(reg->type); 5432 } 5433 5434 static bool is_pkt_reg(struct bpf_verifier_env *env, int regno) 5435 { 5436 const struct bpf_reg_state *reg = reg_state(env, regno); 5437 5438 return type_is_pkt_pointer(reg->type); 5439 } 5440 5441 static bool is_flow_key_reg(struct bpf_verifier_env *env, int regno) 5442 { 5443 const struct bpf_reg_state *reg = reg_state(env, regno); 5444 5445 /* Separate to is_ctx_reg() since we still want to allow BPF_ST here. */ 5446 return reg->type == PTR_TO_FLOW_KEYS; 5447 } 5448 5449 static u32 *reg2btf_ids[__BPF_REG_TYPE_MAX] = { 5450 #ifdef CONFIG_NET 5451 [PTR_TO_SOCKET] = &btf_sock_ids[BTF_SOCK_TYPE_SOCK], 5452 [PTR_TO_SOCK_COMMON] = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON], 5453 [PTR_TO_TCP_SOCK] = &btf_sock_ids[BTF_SOCK_TYPE_TCP], 5454 #endif 5455 [CONST_PTR_TO_MAP] = btf_bpf_map_id, 5456 }; 5457 5458 static bool is_trusted_reg(const struct bpf_reg_state *reg) 5459 { 5460 /* A referenced register is always trusted. */ 5461 if (reg->ref_obj_id) 5462 return true; 5463 5464 /* Types listed in the reg2btf_ids are always trusted */ 5465 if (reg2btf_ids[base_type(reg->type)]) 5466 return true; 5467 5468 /* If a register is not referenced, it is trusted if it has the 5469 * MEM_ALLOC or PTR_TRUSTED type modifiers, and no others. Some of the 5470 * other type modifiers may be safe, but we elect to take an opt-in 5471 * approach here as some (e.g. PTR_UNTRUSTED and PTR_MAYBE_NULL) are 5472 * not. 5473 * 5474 * Eventually, we should make PTR_TRUSTED the single source of truth 5475 * for whether a register is trusted. 5476 */ 5477 return type_flag(reg->type) & BPF_REG_TRUSTED_MODIFIERS && 5478 !bpf_type_has_unsafe_modifiers(reg->type); 5479 } 5480 5481 static bool is_rcu_reg(const struct bpf_reg_state *reg) 5482 { 5483 return reg->type & MEM_RCU; 5484 } 5485 5486 static void clear_trusted_flags(enum bpf_type_flag *flag) 5487 { 5488 *flag &= ~(BPF_REG_TRUSTED_MODIFIERS | MEM_RCU); 5489 } 5490 5491 static int check_pkt_ptr_alignment(struct bpf_verifier_env *env, 5492 const struct bpf_reg_state *reg, 5493 int off, int size, bool strict) 5494 { 5495 struct tnum reg_off; 5496 int ip_align; 5497 5498 /* Byte size accesses are always allowed. */ 5499 if (!strict || size == 1) 5500 return 0; 5501 5502 /* For platforms that do not have a Kconfig enabling 5503 * CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS the value of 5504 * NET_IP_ALIGN is universally set to '2'. And on platforms 5505 * that do set CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS, we get 5506 * to this code only in strict mode where we want to emulate 5507 * the NET_IP_ALIGN==2 checking. Therefore use an 5508 * unconditional IP align value of '2'. 5509 */ 5510 ip_align = 2; 5511 5512 reg_off = tnum_add(reg->var_off, tnum_const(ip_align + reg->off + off)); 5513 if (!tnum_is_aligned(reg_off, size)) { 5514 char tn_buf[48]; 5515 5516 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 5517 verbose(env, 5518 "misaligned packet access off %d+%s+%d+%d size %d\n", 5519 ip_align, tn_buf, reg->off, off, size); 5520 return -EACCES; 5521 } 5522 5523 return 0; 5524 } 5525 5526 static int check_generic_ptr_alignment(struct bpf_verifier_env *env, 5527 const struct bpf_reg_state *reg, 5528 const char *pointer_desc, 5529 int off, int size, bool strict) 5530 { 5531 struct tnum reg_off; 5532 5533 /* Byte size accesses are always allowed. */ 5534 if (!strict || size == 1) 5535 return 0; 5536 5537 reg_off = tnum_add(reg->var_off, tnum_const(reg->off + off)); 5538 if (!tnum_is_aligned(reg_off, size)) { 5539 char tn_buf[48]; 5540 5541 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 5542 verbose(env, "misaligned %saccess off %s+%d+%d size %d\n", 5543 pointer_desc, tn_buf, reg->off, off, size); 5544 return -EACCES; 5545 } 5546 5547 return 0; 5548 } 5549 5550 static int check_ptr_alignment(struct bpf_verifier_env *env, 5551 const struct bpf_reg_state *reg, int off, 5552 int size, bool strict_alignment_once) 5553 { 5554 bool strict = env->strict_alignment || strict_alignment_once; 5555 const char *pointer_desc = ""; 5556 5557 switch (reg->type) { 5558 case PTR_TO_PACKET: 5559 case PTR_TO_PACKET_META: 5560 /* Special case, because of NET_IP_ALIGN. Given metadata sits 5561 * right in front, treat it the very same way. 5562 */ 5563 return check_pkt_ptr_alignment(env, reg, off, size, strict); 5564 case PTR_TO_FLOW_KEYS: 5565 pointer_desc = "flow keys "; 5566 break; 5567 case PTR_TO_MAP_KEY: 5568 pointer_desc = "key "; 5569 break; 5570 case PTR_TO_MAP_VALUE: 5571 pointer_desc = "value "; 5572 break; 5573 case PTR_TO_CTX: 5574 pointer_desc = "context "; 5575 break; 5576 case PTR_TO_STACK: 5577 pointer_desc = "stack "; 5578 /* The stack spill tracking logic in check_stack_write_fixed_off() 5579 * and check_stack_read_fixed_off() relies on stack accesses being 5580 * aligned. 5581 */ 5582 strict = true; 5583 break; 5584 case PTR_TO_SOCKET: 5585 pointer_desc = "sock "; 5586 break; 5587 case PTR_TO_SOCK_COMMON: 5588 pointer_desc = "sock_common "; 5589 break; 5590 case PTR_TO_TCP_SOCK: 5591 pointer_desc = "tcp_sock "; 5592 break; 5593 case PTR_TO_XDP_SOCK: 5594 pointer_desc = "xdp_sock "; 5595 break; 5596 default: 5597 break; 5598 } 5599 return check_generic_ptr_alignment(env, reg, pointer_desc, off, size, 5600 strict); 5601 } 5602 5603 /* starting from main bpf function walk all instructions of the function 5604 * and recursively walk all callees that given function can call. 5605 * Ignore jump and exit insns. 5606 * Since recursion is prevented by check_cfg() this algorithm 5607 * only needs a local stack of MAX_CALL_FRAMES to remember callsites 5608 */ 5609 static int check_max_stack_depth_subprog(struct bpf_verifier_env *env, int idx) 5610 { 5611 struct bpf_subprog_info *subprog = env->subprog_info; 5612 struct bpf_insn *insn = env->prog->insnsi; 5613 int depth = 0, frame = 0, i, subprog_end; 5614 bool tail_call_reachable = false; 5615 int ret_insn[MAX_CALL_FRAMES]; 5616 int ret_prog[MAX_CALL_FRAMES]; 5617 int j; 5618 5619 i = subprog[idx].start; 5620 process_func: 5621 /* protect against potential stack overflow that might happen when 5622 * bpf2bpf calls get combined with tailcalls. Limit the caller's stack 5623 * depth for such case down to 256 so that the worst case scenario 5624 * would result in 8k stack size (32 which is tailcall limit * 256 = 5625 * 8k). 5626 * 5627 * To get the idea what might happen, see an example: 5628 * func1 -> sub rsp, 128 5629 * subfunc1 -> sub rsp, 256 5630 * tailcall1 -> add rsp, 256 5631 * func2 -> sub rsp, 192 (total stack size = 128 + 192 = 320) 5632 * subfunc2 -> sub rsp, 64 5633 * subfunc22 -> sub rsp, 128 5634 * tailcall2 -> add rsp, 128 5635 * func3 -> sub rsp, 32 (total stack size 128 + 192 + 64 + 32 = 416) 5636 * 5637 * tailcall will unwind the current stack frame but it will not get rid 5638 * of caller's stack as shown on the example above. 5639 */ 5640 if (idx && subprog[idx].has_tail_call && depth >= 256) { 5641 verbose(env, 5642 "tail_calls are not allowed when call stack of previous frames is %d bytes. Too large\n", 5643 depth); 5644 return -EACCES; 5645 } 5646 /* round up to 32-bytes, since this is granularity 5647 * of interpreter stack size 5648 */ 5649 depth += round_up(max_t(u32, subprog[idx].stack_depth, 1), 32); 5650 if (depth > MAX_BPF_STACK) { 5651 verbose(env, "combined stack size of %d calls is %d. Too large\n", 5652 frame + 1, depth); 5653 return -EACCES; 5654 } 5655 continue_func: 5656 subprog_end = subprog[idx + 1].start; 5657 for (; i < subprog_end; i++) { 5658 int next_insn, sidx; 5659 5660 if (!bpf_pseudo_call(insn + i) && !bpf_pseudo_func(insn + i)) 5661 continue; 5662 /* remember insn and function to return to */ 5663 ret_insn[frame] = i + 1; 5664 ret_prog[frame] = idx; 5665 5666 /* find the callee */ 5667 next_insn = i + insn[i].imm + 1; 5668 sidx = find_subprog(env, next_insn); 5669 if (sidx < 0) { 5670 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n", 5671 next_insn); 5672 return -EFAULT; 5673 } 5674 if (subprog[sidx].is_async_cb) { 5675 if (subprog[sidx].has_tail_call) { 5676 verbose(env, "verifier bug. subprog has tail_call and async cb\n"); 5677 return -EFAULT; 5678 } 5679 /* async callbacks don't increase bpf prog stack size unless called directly */ 5680 if (!bpf_pseudo_call(insn + i)) 5681 continue; 5682 } 5683 i = next_insn; 5684 idx = sidx; 5685 5686 if (subprog[idx].has_tail_call) 5687 tail_call_reachable = true; 5688 5689 frame++; 5690 if (frame >= MAX_CALL_FRAMES) { 5691 verbose(env, "the call stack of %d frames is too deep !\n", 5692 frame); 5693 return -E2BIG; 5694 } 5695 goto process_func; 5696 } 5697 /* if tail call got detected across bpf2bpf calls then mark each of the 5698 * currently present subprog frames as tail call reachable subprogs; 5699 * this info will be utilized by JIT so that we will be preserving the 5700 * tail call counter throughout bpf2bpf calls combined with tailcalls 5701 */ 5702 if (tail_call_reachable) 5703 for (j = 0; j < frame; j++) 5704 subprog[ret_prog[j]].tail_call_reachable = true; 5705 if (subprog[0].tail_call_reachable) 5706 env->prog->aux->tail_call_reachable = true; 5707 5708 /* end of for() loop means the last insn of the 'subprog' 5709 * was reached. Doesn't matter whether it was JA or EXIT 5710 */ 5711 if (frame == 0) 5712 return 0; 5713 depth -= round_up(max_t(u32, subprog[idx].stack_depth, 1), 32); 5714 frame--; 5715 i = ret_insn[frame]; 5716 idx = ret_prog[frame]; 5717 goto continue_func; 5718 } 5719 5720 static int check_max_stack_depth(struct bpf_verifier_env *env) 5721 { 5722 struct bpf_subprog_info *si = env->subprog_info; 5723 int ret; 5724 5725 for (int i = 0; i < env->subprog_cnt; i++) { 5726 if (!i || si[i].is_async_cb) { 5727 ret = check_max_stack_depth_subprog(env, i); 5728 if (ret < 0) 5729 return ret; 5730 } 5731 continue; 5732 } 5733 return 0; 5734 } 5735 5736 #ifndef CONFIG_BPF_JIT_ALWAYS_ON 5737 static int get_callee_stack_depth(struct bpf_verifier_env *env, 5738 const struct bpf_insn *insn, int idx) 5739 { 5740 int start = idx + insn->imm + 1, subprog; 5741 5742 subprog = find_subprog(env, start); 5743 if (subprog < 0) { 5744 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n", 5745 start); 5746 return -EFAULT; 5747 } 5748 return env->subprog_info[subprog].stack_depth; 5749 } 5750 #endif 5751 5752 static int __check_buffer_access(struct bpf_verifier_env *env, 5753 const char *buf_info, 5754 const struct bpf_reg_state *reg, 5755 int regno, int off, int size) 5756 { 5757 if (off < 0) { 5758 verbose(env, 5759 "R%d invalid %s buffer access: off=%d, size=%d\n", 5760 regno, buf_info, off, size); 5761 return -EACCES; 5762 } 5763 if (!tnum_is_const(reg->var_off) || reg->var_off.value) { 5764 char tn_buf[48]; 5765 5766 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 5767 verbose(env, 5768 "R%d invalid variable buffer offset: off=%d, var_off=%s\n", 5769 regno, off, tn_buf); 5770 return -EACCES; 5771 } 5772 5773 return 0; 5774 } 5775 5776 static int check_tp_buffer_access(struct bpf_verifier_env *env, 5777 const struct bpf_reg_state *reg, 5778 int regno, int off, int size) 5779 { 5780 int err; 5781 5782 err = __check_buffer_access(env, "tracepoint", reg, regno, off, size); 5783 if (err) 5784 return err; 5785 5786 if (off + size > env->prog->aux->max_tp_access) 5787 env->prog->aux->max_tp_access = off + size; 5788 5789 return 0; 5790 } 5791 5792 static int check_buffer_access(struct bpf_verifier_env *env, 5793 const struct bpf_reg_state *reg, 5794 int regno, int off, int size, 5795 bool zero_size_allowed, 5796 u32 *max_access) 5797 { 5798 const char *buf_info = type_is_rdonly_mem(reg->type) ? "rdonly" : "rdwr"; 5799 int err; 5800 5801 err = __check_buffer_access(env, buf_info, reg, regno, off, size); 5802 if (err) 5803 return err; 5804 5805 if (off + size > *max_access) 5806 *max_access = off + size; 5807 5808 return 0; 5809 } 5810 5811 /* BPF architecture zero extends alu32 ops into 64-bit registesr */ 5812 static void zext_32_to_64(struct bpf_reg_state *reg) 5813 { 5814 reg->var_off = tnum_subreg(reg->var_off); 5815 __reg_assign_32_into_64(reg); 5816 } 5817 5818 /* truncate register to smaller size (in bytes) 5819 * must be called with size < BPF_REG_SIZE 5820 */ 5821 static void coerce_reg_to_size(struct bpf_reg_state *reg, int size) 5822 { 5823 u64 mask; 5824 5825 /* clear high bits in bit representation */ 5826 reg->var_off = tnum_cast(reg->var_off, size); 5827 5828 /* fix arithmetic bounds */ 5829 mask = ((u64)1 << (size * 8)) - 1; 5830 if ((reg->umin_value & ~mask) == (reg->umax_value & ~mask)) { 5831 reg->umin_value &= mask; 5832 reg->umax_value &= mask; 5833 } else { 5834 reg->umin_value = 0; 5835 reg->umax_value = mask; 5836 } 5837 reg->smin_value = reg->umin_value; 5838 reg->smax_value = reg->umax_value; 5839 5840 /* If size is smaller than 32bit register the 32bit register 5841 * values are also truncated so we push 64-bit bounds into 5842 * 32-bit bounds. Above were truncated < 32-bits already. 5843 */ 5844 if (size >= 4) 5845 return; 5846 __reg_combine_64_into_32(reg); 5847 } 5848 5849 static void set_sext64_default_val(struct bpf_reg_state *reg, int size) 5850 { 5851 if (size == 1) { 5852 reg->smin_value = reg->s32_min_value = S8_MIN; 5853 reg->smax_value = reg->s32_max_value = S8_MAX; 5854 } else if (size == 2) { 5855 reg->smin_value = reg->s32_min_value = S16_MIN; 5856 reg->smax_value = reg->s32_max_value = S16_MAX; 5857 } else { 5858 /* size == 4 */ 5859 reg->smin_value = reg->s32_min_value = S32_MIN; 5860 reg->smax_value = reg->s32_max_value = S32_MAX; 5861 } 5862 reg->umin_value = reg->u32_min_value = 0; 5863 reg->umax_value = U64_MAX; 5864 reg->u32_max_value = U32_MAX; 5865 reg->var_off = tnum_unknown; 5866 } 5867 5868 static void coerce_reg_to_size_sx(struct bpf_reg_state *reg, int size) 5869 { 5870 s64 init_s64_max, init_s64_min, s64_max, s64_min, u64_cval; 5871 u64 top_smax_value, top_smin_value; 5872 u64 num_bits = size * 8; 5873 5874 if (tnum_is_const(reg->var_off)) { 5875 u64_cval = reg->var_off.value; 5876 if (size == 1) 5877 reg->var_off = tnum_const((s8)u64_cval); 5878 else if (size == 2) 5879 reg->var_off = tnum_const((s16)u64_cval); 5880 else 5881 /* size == 4 */ 5882 reg->var_off = tnum_const((s32)u64_cval); 5883 5884 u64_cval = reg->var_off.value; 5885 reg->smax_value = reg->smin_value = u64_cval; 5886 reg->umax_value = reg->umin_value = u64_cval; 5887 reg->s32_max_value = reg->s32_min_value = u64_cval; 5888 reg->u32_max_value = reg->u32_min_value = u64_cval; 5889 return; 5890 } 5891 5892 top_smax_value = ((u64)reg->smax_value >> num_bits) << num_bits; 5893 top_smin_value = ((u64)reg->smin_value >> num_bits) << num_bits; 5894 5895 if (top_smax_value != top_smin_value) 5896 goto out; 5897 5898 /* find the s64_min and s64_min after sign extension */ 5899 if (size == 1) { 5900 init_s64_max = (s8)reg->smax_value; 5901 init_s64_min = (s8)reg->smin_value; 5902 } else if (size == 2) { 5903 init_s64_max = (s16)reg->smax_value; 5904 init_s64_min = (s16)reg->smin_value; 5905 } else { 5906 init_s64_max = (s32)reg->smax_value; 5907 init_s64_min = (s32)reg->smin_value; 5908 } 5909 5910 s64_max = max(init_s64_max, init_s64_min); 5911 s64_min = min(init_s64_max, init_s64_min); 5912 5913 /* both of s64_max/s64_min positive or negative */ 5914 if ((s64_max >= 0) == (s64_min >= 0)) { 5915 reg->smin_value = reg->s32_min_value = s64_min; 5916 reg->smax_value = reg->s32_max_value = s64_max; 5917 reg->umin_value = reg->u32_min_value = s64_min; 5918 reg->umax_value = reg->u32_max_value = s64_max; 5919 reg->var_off = tnum_range(s64_min, s64_max); 5920 return; 5921 } 5922 5923 out: 5924 set_sext64_default_val(reg, size); 5925 } 5926 5927 static void set_sext32_default_val(struct bpf_reg_state *reg, int size) 5928 { 5929 if (size == 1) { 5930 reg->s32_min_value = S8_MIN; 5931 reg->s32_max_value = S8_MAX; 5932 } else { 5933 /* size == 2 */ 5934 reg->s32_min_value = S16_MIN; 5935 reg->s32_max_value = S16_MAX; 5936 } 5937 reg->u32_min_value = 0; 5938 reg->u32_max_value = U32_MAX; 5939 } 5940 5941 static void coerce_subreg_to_size_sx(struct bpf_reg_state *reg, int size) 5942 { 5943 s32 init_s32_max, init_s32_min, s32_max, s32_min, u32_val; 5944 u32 top_smax_value, top_smin_value; 5945 u32 num_bits = size * 8; 5946 5947 if (tnum_is_const(reg->var_off)) { 5948 u32_val = reg->var_off.value; 5949 if (size == 1) 5950 reg->var_off = tnum_const((s8)u32_val); 5951 else 5952 reg->var_off = tnum_const((s16)u32_val); 5953 5954 u32_val = reg->var_off.value; 5955 reg->s32_min_value = reg->s32_max_value = u32_val; 5956 reg->u32_min_value = reg->u32_max_value = u32_val; 5957 return; 5958 } 5959 5960 top_smax_value = ((u32)reg->s32_max_value >> num_bits) << num_bits; 5961 top_smin_value = ((u32)reg->s32_min_value >> num_bits) << num_bits; 5962 5963 if (top_smax_value != top_smin_value) 5964 goto out; 5965 5966 /* find the s32_min and s32_min after sign extension */ 5967 if (size == 1) { 5968 init_s32_max = (s8)reg->s32_max_value; 5969 init_s32_min = (s8)reg->s32_min_value; 5970 } else { 5971 /* size == 2 */ 5972 init_s32_max = (s16)reg->s32_max_value; 5973 init_s32_min = (s16)reg->s32_min_value; 5974 } 5975 s32_max = max(init_s32_max, init_s32_min); 5976 s32_min = min(init_s32_max, init_s32_min); 5977 5978 if ((s32_min >= 0) == (s32_max >= 0)) { 5979 reg->s32_min_value = s32_min; 5980 reg->s32_max_value = s32_max; 5981 reg->u32_min_value = (u32)s32_min; 5982 reg->u32_max_value = (u32)s32_max; 5983 return; 5984 } 5985 5986 out: 5987 set_sext32_default_val(reg, size); 5988 } 5989 5990 static bool bpf_map_is_rdonly(const struct bpf_map *map) 5991 { 5992 /* A map is considered read-only if the following condition are true: 5993 * 5994 * 1) BPF program side cannot change any of the map content. The 5995 * BPF_F_RDONLY_PROG flag is throughout the lifetime of a map 5996 * and was set at map creation time. 5997 * 2) The map value(s) have been initialized from user space by a 5998 * loader and then "frozen", such that no new map update/delete 5999 * operations from syscall side are possible for the rest of 6000 * the map's lifetime from that point onwards. 6001 * 3) Any parallel/pending map update/delete operations from syscall 6002 * side have been completed. Only after that point, it's safe to 6003 * assume that map value(s) are immutable. 6004 */ 6005 return (map->map_flags & BPF_F_RDONLY_PROG) && 6006 READ_ONCE(map->frozen) && 6007 !bpf_map_write_active(map); 6008 } 6009 6010 static int bpf_map_direct_read(struct bpf_map *map, int off, int size, u64 *val, 6011 bool is_ldsx) 6012 { 6013 void *ptr; 6014 u64 addr; 6015 int err; 6016 6017 err = map->ops->map_direct_value_addr(map, &addr, off); 6018 if (err) 6019 return err; 6020 ptr = (void *)(long)addr + off; 6021 6022 switch (size) { 6023 case sizeof(u8): 6024 *val = is_ldsx ? (s64)*(s8 *)ptr : (u64)*(u8 *)ptr; 6025 break; 6026 case sizeof(u16): 6027 *val = is_ldsx ? (s64)*(s16 *)ptr : (u64)*(u16 *)ptr; 6028 break; 6029 case sizeof(u32): 6030 *val = is_ldsx ? (s64)*(s32 *)ptr : (u64)*(u32 *)ptr; 6031 break; 6032 case sizeof(u64): 6033 *val = *(u64 *)ptr; 6034 break; 6035 default: 6036 return -EINVAL; 6037 } 6038 return 0; 6039 } 6040 6041 #define BTF_TYPE_SAFE_RCU(__type) __PASTE(__type, __safe_rcu) 6042 #define BTF_TYPE_SAFE_RCU_OR_NULL(__type) __PASTE(__type, __safe_rcu_or_null) 6043 #define BTF_TYPE_SAFE_TRUSTED(__type) __PASTE(__type, __safe_trusted) 6044 6045 /* 6046 * Allow list few fields as RCU trusted or full trusted. 6047 * This logic doesn't allow mix tagging and will be removed once GCC supports 6048 * btf_type_tag. 6049 */ 6050 6051 /* RCU trusted: these fields are trusted in RCU CS and never NULL */ 6052 BTF_TYPE_SAFE_RCU(struct task_struct) { 6053 const cpumask_t *cpus_ptr; 6054 struct css_set __rcu *cgroups; 6055 struct task_struct __rcu *real_parent; 6056 struct task_struct *group_leader; 6057 }; 6058 6059 BTF_TYPE_SAFE_RCU(struct cgroup) { 6060 /* cgrp->kn is always accessible as documented in kernel/cgroup/cgroup.c */ 6061 struct kernfs_node *kn; 6062 }; 6063 6064 BTF_TYPE_SAFE_RCU(struct css_set) { 6065 struct cgroup *dfl_cgrp; 6066 }; 6067 6068 /* RCU trusted: these fields are trusted in RCU CS and can be NULL */ 6069 BTF_TYPE_SAFE_RCU_OR_NULL(struct mm_struct) { 6070 struct file __rcu *exe_file; 6071 }; 6072 6073 /* skb->sk, req->sk are not RCU protected, but we mark them as such 6074 * because bpf prog accessible sockets are SOCK_RCU_FREE. 6075 */ 6076 BTF_TYPE_SAFE_RCU_OR_NULL(struct sk_buff) { 6077 struct sock *sk; 6078 }; 6079 6080 BTF_TYPE_SAFE_RCU_OR_NULL(struct request_sock) { 6081 struct sock *sk; 6082 }; 6083 6084 /* full trusted: these fields are trusted even outside of RCU CS and never NULL */ 6085 BTF_TYPE_SAFE_TRUSTED(struct bpf_iter_meta) { 6086 struct seq_file *seq; 6087 }; 6088 6089 BTF_TYPE_SAFE_TRUSTED(struct bpf_iter__task) { 6090 struct bpf_iter_meta *meta; 6091 struct task_struct *task; 6092 }; 6093 6094 BTF_TYPE_SAFE_TRUSTED(struct linux_binprm) { 6095 struct file *file; 6096 }; 6097 6098 BTF_TYPE_SAFE_TRUSTED(struct file) { 6099 struct inode *f_inode; 6100 }; 6101 6102 BTF_TYPE_SAFE_TRUSTED(struct dentry) { 6103 /* no negative dentry-s in places where bpf can see it */ 6104 struct inode *d_inode; 6105 }; 6106 6107 BTF_TYPE_SAFE_TRUSTED(struct socket) { 6108 struct sock *sk; 6109 }; 6110 6111 static bool type_is_rcu(struct bpf_verifier_env *env, 6112 struct bpf_reg_state *reg, 6113 const char *field_name, u32 btf_id) 6114 { 6115 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct task_struct)); 6116 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct cgroup)); 6117 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct css_set)); 6118 6119 return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_rcu"); 6120 } 6121 6122 static bool type_is_rcu_or_null(struct bpf_verifier_env *env, 6123 struct bpf_reg_state *reg, 6124 const char *field_name, u32 btf_id) 6125 { 6126 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct mm_struct)); 6127 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct sk_buff)); 6128 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct request_sock)); 6129 6130 return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_rcu_or_null"); 6131 } 6132 6133 static bool type_is_trusted(struct bpf_verifier_env *env, 6134 struct bpf_reg_state *reg, 6135 const char *field_name, u32 btf_id) 6136 { 6137 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct bpf_iter_meta)); 6138 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct bpf_iter__task)); 6139 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct linux_binprm)); 6140 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct file)); 6141 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct dentry)); 6142 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct socket)); 6143 6144 return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_trusted"); 6145 } 6146 6147 static int check_ptr_to_btf_access(struct bpf_verifier_env *env, 6148 struct bpf_reg_state *regs, 6149 int regno, int off, int size, 6150 enum bpf_access_type atype, 6151 int value_regno) 6152 { 6153 struct bpf_reg_state *reg = regs + regno; 6154 const struct btf_type *t = btf_type_by_id(reg->btf, reg->btf_id); 6155 const char *tname = btf_name_by_offset(reg->btf, t->name_off); 6156 const char *field_name = NULL; 6157 enum bpf_type_flag flag = 0; 6158 u32 btf_id = 0; 6159 int ret; 6160 6161 if (!env->allow_ptr_leaks) { 6162 verbose(env, 6163 "'struct %s' access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n", 6164 tname); 6165 return -EPERM; 6166 } 6167 if (!env->prog->gpl_compatible && btf_is_kernel(reg->btf)) { 6168 verbose(env, 6169 "Cannot access kernel 'struct %s' from non-GPL compatible program\n", 6170 tname); 6171 return -EINVAL; 6172 } 6173 if (off < 0) { 6174 verbose(env, 6175 "R%d is ptr_%s invalid negative access: off=%d\n", 6176 regno, tname, off); 6177 return -EACCES; 6178 } 6179 if (!tnum_is_const(reg->var_off) || reg->var_off.value) { 6180 char tn_buf[48]; 6181 6182 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 6183 verbose(env, 6184 "R%d is ptr_%s invalid variable offset: off=%d, var_off=%s\n", 6185 regno, tname, off, tn_buf); 6186 return -EACCES; 6187 } 6188 6189 if (reg->type & MEM_USER) { 6190 verbose(env, 6191 "R%d is ptr_%s access user memory: off=%d\n", 6192 regno, tname, off); 6193 return -EACCES; 6194 } 6195 6196 if (reg->type & MEM_PERCPU) { 6197 verbose(env, 6198 "R%d is ptr_%s access percpu memory: off=%d\n", 6199 regno, tname, off); 6200 return -EACCES; 6201 } 6202 6203 if (env->ops->btf_struct_access && !type_is_alloc(reg->type) && atype == BPF_WRITE) { 6204 if (!btf_is_kernel(reg->btf)) { 6205 verbose(env, "verifier internal error: reg->btf must be kernel btf\n"); 6206 return -EFAULT; 6207 } 6208 ret = env->ops->btf_struct_access(&env->log, reg, off, size); 6209 } else { 6210 /* Writes are permitted with default btf_struct_access for 6211 * program allocated objects (which always have ref_obj_id > 0), 6212 * but not for untrusted PTR_TO_BTF_ID | MEM_ALLOC. 6213 */ 6214 if (atype != BPF_READ && !type_is_ptr_alloc_obj(reg->type)) { 6215 verbose(env, "only read is supported\n"); 6216 return -EACCES; 6217 } 6218 6219 if (type_is_alloc(reg->type) && !type_is_non_owning_ref(reg->type) && 6220 !reg->ref_obj_id) { 6221 verbose(env, "verifier internal error: ref_obj_id for allocated object must be non-zero\n"); 6222 return -EFAULT; 6223 } 6224 6225 ret = btf_struct_access(&env->log, reg, off, size, atype, &btf_id, &flag, &field_name); 6226 } 6227 6228 if (ret < 0) 6229 return ret; 6230 6231 if (ret != PTR_TO_BTF_ID) { 6232 /* just mark; */ 6233 6234 } else if (type_flag(reg->type) & PTR_UNTRUSTED) { 6235 /* If this is an untrusted pointer, all pointers formed by walking it 6236 * also inherit the untrusted flag. 6237 */ 6238 flag = PTR_UNTRUSTED; 6239 6240 } else if (is_trusted_reg(reg) || is_rcu_reg(reg)) { 6241 /* By default any pointer obtained from walking a trusted pointer is no 6242 * longer trusted, unless the field being accessed has explicitly been 6243 * marked as inheriting its parent's state of trust (either full or RCU). 6244 * For example: 6245 * 'cgroups' pointer is untrusted if task->cgroups dereference 6246 * happened in a sleepable program outside of bpf_rcu_read_lock() 6247 * section. In a non-sleepable program it's trusted while in RCU CS (aka MEM_RCU). 6248 * Note bpf_rcu_read_unlock() converts MEM_RCU pointers to PTR_UNTRUSTED. 6249 * 6250 * A regular RCU-protected pointer with __rcu tag can also be deemed 6251 * trusted if we are in an RCU CS. Such pointer can be NULL. 6252 */ 6253 if (type_is_trusted(env, reg, field_name, btf_id)) { 6254 flag |= PTR_TRUSTED; 6255 } else if (in_rcu_cs(env) && !type_may_be_null(reg->type)) { 6256 if (type_is_rcu(env, reg, field_name, btf_id)) { 6257 /* ignore __rcu tag and mark it MEM_RCU */ 6258 flag |= MEM_RCU; 6259 } else if (flag & MEM_RCU || 6260 type_is_rcu_or_null(env, reg, field_name, btf_id)) { 6261 /* __rcu tagged pointers can be NULL */ 6262 flag |= MEM_RCU | PTR_MAYBE_NULL; 6263 6264 /* We always trust them */ 6265 if (type_is_rcu_or_null(env, reg, field_name, btf_id) && 6266 flag & PTR_UNTRUSTED) 6267 flag &= ~PTR_UNTRUSTED; 6268 } else if (flag & (MEM_PERCPU | MEM_USER)) { 6269 /* keep as-is */ 6270 } else { 6271 /* walking unknown pointers yields old deprecated PTR_TO_BTF_ID */ 6272 clear_trusted_flags(&flag); 6273 } 6274 } else { 6275 /* 6276 * If not in RCU CS or MEM_RCU pointer can be NULL then 6277 * aggressively mark as untrusted otherwise such 6278 * pointers will be plain PTR_TO_BTF_ID without flags 6279 * and will be allowed to be passed into helpers for 6280 * compat reasons. 6281 */ 6282 flag = PTR_UNTRUSTED; 6283 } 6284 } else { 6285 /* Old compat. Deprecated */ 6286 clear_trusted_flags(&flag); 6287 } 6288 6289 if (atype == BPF_READ && value_regno >= 0) 6290 mark_btf_ld_reg(env, regs, value_regno, ret, reg->btf, btf_id, flag); 6291 6292 return 0; 6293 } 6294 6295 static int check_ptr_to_map_access(struct bpf_verifier_env *env, 6296 struct bpf_reg_state *regs, 6297 int regno, int off, int size, 6298 enum bpf_access_type atype, 6299 int value_regno) 6300 { 6301 struct bpf_reg_state *reg = regs + regno; 6302 struct bpf_map *map = reg->map_ptr; 6303 struct bpf_reg_state map_reg; 6304 enum bpf_type_flag flag = 0; 6305 const struct btf_type *t; 6306 const char *tname; 6307 u32 btf_id; 6308 int ret; 6309 6310 if (!btf_vmlinux) { 6311 verbose(env, "map_ptr access not supported without CONFIG_DEBUG_INFO_BTF\n"); 6312 return -ENOTSUPP; 6313 } 6314 6315 if (!map->ops->map_btf_id || !*map->ops->map_btf_id) { 6316 verbose(env, "map_ptr access not supported for map type %d\n", 6317 map->map_type); 6318 return -ENOTSUPP; 6319 } 6320 6321 t = btf_type_by_id(btf_vmlinux, *map->ops->map_btf_id); 6322 tname = btf_name_by_offset(btf_vmlinux, t->name_off); 6323 6324 if (!env->allow_ptr_leaks) { 6325 verbose(env, 6326 "'struct %s' access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n", 6327 tname); 6328 return -EPERM; 6329 } 6330 6331 if (off < 0) { 6332 verbose(env, "R%d is %s invalid negative access: off=%d\n", 6333 regno, tname, off); 6334 return -EACCES; 6335 } 6336 6337 if (atype != BPF_READ) { 6338 verbose(env, "only read from %s is supported\n", tname); 6339 return -EACCES; 6340 } 6341 6342 /* Simulate access to a PTR_TO_BTF_ID */ 6343 memset(&map_reg, 0, sizeof(map_reg)); 6344 mark_btf_ld_reg(env, &map_reg, 0, PTR_TO_BTF_ID, btf_vmlinux, *map->ops->map_btf_id, 0); 6345 ret = btf_struct_access(&env->log, &map_reg, off, size, atype, &btf_id, &flag, NULL); 6346 if (ret < 0) 6347 return ret; 6348 6349 if (value_regno >= 0) 6350 mark_btf_ld_reg(env, regs, value_regno, ret, btf_vmlinux, btf_id, flag); 6351 6352 return 0; 6353 } 6354 6355 /* Check that the stack access at the given offset is within bounds. The 6356 * maximum valid offset is -1. 6357 * 6358 * The minimum valid offset is -MAX_BPF_STACK for writes, and 6359 * -state->allocated_stack for reads. 6360 */ 6361 static int check_stack_slot_within_bounds(struct bpf_verifier_env *env, 6362 s64 off, 6363 struct bpf_func_state *state, 6364 enum bpf_access_type t) 6365 { 6366 int min_valid_off; 6367 6368 if (t == BPF_WRITE || env->allow_uninit_stack) 6369 min_valid_off = -MAX_BPF_STACK; 6370 else 6371 min_valid_off = -state->allocated_stack; 6372 6373 if (off < min_valid_off || off > -1) 6374 return -EACCES; 6375 return 0; 6376 } 6377 6378 /* Check that the stack access at 'regno + off' falls within the maximum stack 6379 * bounds. 6380 * 6381 * 'off' includes `regno->offset`, but not its dynamic part (if any). 6382 */ 6383 static int check_stack_access_within_bounds( 6384 struct bpf_verifier_env *env, 6385 int regno, int off, int access_size, 6386 enum bpf_access_src src, enum bpf_access_type type) 6387 { 6388 struct bpf_reg_state *regs = cur_regs(env); 6389 struct bpf_reg_state *reg = regs + regno; 6390 struct bpf_func_state *state = func(env, reg); 6391 s64 min_off, max_off; 6392 int err; 6393 char *err_extra; 6394 6395 if (src == ACCESS_HELPER) 6396 /* We don't know if helpers are reading or writing (or both). */ 6397 err_extra = " indirect access to"; 6398 else if (type == BPF_READ) 6399 err_extra = " read from"; 6400 else 6401 err_extra = " write to"; 6402 6403 if (tnum_is_const(reg->var_off)) { 6404 min_off = (s64)reg->var_off.value + off; 6405 max_off = min_off + access_size; 6406 } else { 6407 if (reg->smax_value >= BPF_MAX_VAR_OFF || 6408 reg->smin_value <= -BPF_MAX_VAR_OFF) { 6409 verbose(env, "invalid unbounded variable-offset%s stack R%d\n", 6410 err_extra, regno); 6411 return -EACCES; 6412 } 6413 min_off = reg->smin_value + off; 6414 max_off = reg->smax_value + off + access_size; 6415 } 6416 6417 err = check_stack_slot_within_bounds(env, min_off, state, type); 6418 if (!err && max_off > 0) 6419 err = -EINVAL; /* out of stack access into non-negative offsets */ 6420 6421 if (err) { 6422 if (tnum_is_const(reg->var_off)) { 6423 verbose(env, "invalid%s stack R%d off=%d size=%d\n", 6424 err_extra, regno, off, access_size); 6425 } else { 6426 char tn_buf[48]; 6427 6428 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 6429 verbose(env, "invalid variable-offset%s stack R%d var_off=%s size=%d\n", 6430 err_extra, regno, tn_buf, access_size); 6431 } 6432 return err; 6433 } 6434 6435 return grow_stack_state(env, state, round_up(-min_off, BPF_REG_SIZE)); 6436 } 6437 6438 /* check whether memory at (regno + off) is accessible for t = (read | write) 6439 * if t==write, value_regno is a register which value is stored into memory 6440 * if t==read, value_regno is a register which will receive the value from memory 6441 * if t==write && value_regno==-1, some unknown value is stored into memory 6442 * if t==read && value_regno==-1, don't care what we read from memory 6443 */ 6444 static int check_mem_access(struct bpf_verifier_env *env, int insn_idx, u32 regno, 6445 int off, int bpf_size, enum bpf_access_type t, 6446 int value_regno, bool strict_alignment_once, bool is_ldsx) 6447 { 6448 struct bpf_reg_state *regs = cur_regs(env); 6449 struct bpf_reg_state *reg = regs + regno; 6450 int size, err = 0; 6451 6452 size = bpf_size_to_bytes(bpf_size); 6453 if (size < 0) 6454 return size; 6455 6456 /* alignment checks will add in reg->off themselves */ 6457 err = check_ptr_alignment(env, reg, off, size, strict_alignment_once); 6458 if (err) 6459 return err; 6460 6461 /* for access checks, reg->off is just part of off */ 6462 off += reg->off; 6463 6464 if (reg->type == PTR_TO_MAP_KEY) { 6465 if (t == BPF_WRITE) { 6466 verbose(env, "write to change key R%d not allowed\n", regno); 6467 return -EACCES; 6468 } 6469 6470 err = check_mem_region_access(env, regno, off, size, 6471 reg->map_ptr->key_size, false); 6472 if (err) 6473 return err; 6474 if (value_regno >= 0) 6475 mark_reg_unknown(env, regs, value_regno); 6476 } else if (reg->type == PTR_TO_MAP_VALUE) { 6477 struct btf_field *kptr_field = NULL; 6478 6479 if (t == BPF_WRITE && value_regno >= 0 && 6480 is_pointer_value(env, value_regno)) { 6481 verbose(env, "R%d leaks addr into map\n", value_regno); 6482 return -EACCES; 6483 } 6484 err = check_map_access_type(env, regno, off, size, t); 6485 if (err) 6486 return err; 6487 err = check_map_access(env, regno, off, size, false, ACCESS_DIRECT); 6488 if (err) 6489 return err; 6490 if (tnum_is_const(reg->var_off)) 6491 kptr_field = btf_record_find(reg->map_ptr->record, 6492 off + reg->var_off.value, BPF_KPTR); 6493 if (kptr_field) { 6494 err = check_map_kptr_access(env, regno, value_regno, insn_idx, kptr_field); 6495 } else if (t == BPF_READ && value_regno >= 0) { 6496 struct bpf_map *map = reg->map_ptr; 6497 6498 /* if map is read-only, track its contents as scalars */ 6499 if (tnum_is_const(reg->var_off) && 6500 bpf_map_is_rdonly(map) && 6501 map->ops->map_direct_value_addr) { 6502 int map_off = off + reg->var_off.value; 6503 u64 val = 0; 6504 6505 err = bpf_map_direct_read(map, map_off, size, 6506 &val, is_ldsx); 6507 if (err) 6508 return err; 6509 6510 regs[value_regno].type = SCALAR_VALUE; 6511 __mark_reg_known(®s[value_regno], val); 6512 } else { 6513 mark_reg_unknown(env, regs, value_regno); 6514 } 6515 } 6516 } else if (base_type(reg->type) == PTR_TO_MEM) { 6517 bool rdonly_mem = type_is_rdonly_mem(reg->type); 6518 6519 if (type_may_be_null(reg->type)) { 6520 verbose(env, "R%d invalid mem access '%s'\n", regno, 6521 reg_type_str(env, reg->type)); 6522 return -EACCES; 6523 } 6524 6525 if (t == BPF_WRITE && rdonly_mem) { 6526 verbose(env, "R%d cannot write into %s\n", 6527 regno, reg_type_str(env, reg->type)); 6528 return -EACCES; 6529 } 6530 6531 if (t == BPF_WRITE && value_regno >= 0 && 6532 is_pointer_value(env, value_regno)) { 6533 verbose(env, "R%d leaks addr into mem\n", value_regno); 6534 return -EACCES; 6535 } 6536 6537 err = check_mem_region_access(env, regno, off, size, 6538 reg->mem_size, false); 6539 if (!err && value_regno >= 0 && (t == BPF_READ || rdonly_mem)) 6540 mark_reg_unknown(env, regs, value_regno); 6541 } else if (reg->type == PTR_TO_CTX) { 6542 enum bpf_reg_type reg_type = SCALAR_VALUE; 6543 struct btf *btf = NULL; 6544 u32 btf_id = 0; 6545 6546 if (t == BPF_WRITE && value_regno >= 0 && 6547 is_pointer_value(env, value_regno)) { 6548 verbose(env, "R%d leaks addr into ctx\n", value_regno); 6549 return -EACCES; 6550 } 6551 6552 err = check_ptr_off_reg(env, reg, regno); 6553 if (err < 0) 6554 return err; 6555 6556 err = check_ctx_access(env, insn_idx, off, size, t, ®_type, &btf, 6557 &btf_id); 6558 if (err) 6559 verbose_linfo(env, insn_idx, "; "); 6560 if (!err && t == BPF_READ && value_regno >= 0) { 6561 /* ctx access returns either a scalar, or a 6562 * PTR_TO_PACKET[_META,_END]. In the latter 6563 * case, we know the offset is zero. 6564 */ 6565 if (reg_type == SCALAR_VALUE) { 6566 mark_reg_unknown(env, regs, value_regno); 6567 } else { 6568 mark_reg_known_zero(env, regs, 6569 value_regno); 6570 if (type_may_be_null(reg_type)) 6571 regs[value_regno].id = ++env->id_gen; 6572 /* A load of ctx field could have different 6573 * actual load size with the one encoded in the 6574 * insn. When the dst is PTR, it is for sure not 6575 * a sub-register. 6576 */ 6577 regs[value_regno].subreg_def = DEF_NOT_SUBREG; 6578 if (base_type(reg_type) == PTR_TO_BTF_ID) { 6579 regs[value_regno].btf = btf; 6580 regs[value_regno].btf_id = btf_id; 6581 } 6582 } 6583 regs[value_regno].type = reg_type; 6584 } 6585 6586 } else if (reg->type == PTR_TO_STACK) { 6587 /* Basic bounds checks. */ 6588 err = check_stack_access_within_bounds(env, regno, off, size, ACCESS_DIRECT, t); 6589 if (err) 6590 return err; 6591 6592 if (t == BPF_READ) 6593 err = check_stack_read(env, regno, off, size, 6594 value_regno); 6595 else 6596 err = check_stack_write(env, regno, off, size, 6597 value_regno, insn_idx); 6598 } else if (reg_is_pkt_pointer(reg)) { 6599 if (t == BPF_WRITE && !may_access_direct_pkt_data(env, NULL, t)) { 6600 verbose(env, "cannot write into packet\n"); 6601 return -EACCES; 6602 } 6603 if (t == BPF_WRITE && value_regno >= 0 && 6604 is_pointer_value(env, value_regno)) { 6605 verbose(env, "R%d leaks addr into packet\n", 6606 value_regno); 6607 return -EACCES; 6608 } 6609 err = check_packet_access(env, regno, off, size, false); 6610 if (!err && t == BPF_READ && value_regno >= 0) 6611 mark_reg_unknown(env, regs, value_regno); 6612 } else if (reg->type == PTR_TO_FLOW_KEYS) { 6613 if (t == BPF_WRITE && value_regno >= 0 && 6614 is_pointer_value(env, value_regno)) { 6615 verbose(env, "R%d leaks addr into flow keys\n", 6616 value_regno); 6617 return -EACCES; 6618 } 6619 6620 err = check_flow_keys_access(env, off, size); 6621 if (!err && t == BPF_READ && value_regno >= 0) 6622 mark_reg_unknown(env, regs, value_regno); 6623 } else if (type_is_sk_pointer(reg->type)) { 6624 if (t == BPF_WRITE) { 6625 verbose(env, "R%d cannot write into %s\n", 6626 regno, reg_type_str(env, reg->type)); 6627 return -EACCES; 6628 } 6629 err = check_sock_access(env, insn_idx, regno, off, size, t); 6630 if (!err && value_regno >= 0) 6631 mark_reg_unknown(env, regs, value_regno); 6632 } else if (reg->type == PTR_TO_TP_BUFFER) { 6633 err = check_tp_buffer_access(env, reg, regno, off, size); 6634 if (!err && t == BPF_READ && value_regno >= 0) 6635 mark_reg_unknown(env, regs, value_regno); 6636 } else if (base_type(reg->type) == PTR_TO_BTF_ID && 6637 !type_may_be_null(reg->type)) { 6638 err = check_ptr_to_btf_access(env, regs, regno, off, size, t, 6639 value_regno); 6640 } else if (reg->type == CONST_PTR_TO_MAP) { 6641 err = check_ptr_to_map_access(env, regs, regno, off, size, t, 6642 value_regno); 6643 } else if (base_type(reg->type) == PTR_TO_BUF) { 6644 bool rdonly_mem = type_is_rdonly_mem(reg->type); 6645 u32 *max_access; 6646 6647 if (rdonly_mem) { 6648 if (t == BPF_WRITE) { 6649 verbose(env, "R%d cannot write into %s\n", 6650 regno, reg_type_str(env, reg->type)); 6651 return -EACCES; 6652 } 6653 max_access = &env->prog->aux->max_rdonly_access; 6654 } else { 6655 max_access = &env->prog->aux->max_rdwr_access; 6656 } 6657 6658 err = check_buffer_access(env, reg, regno, off, size, false, 6659 max_access); 6660 6661 if (!err && value_regno >= 0 && (rdonly_mem || t == BPF_READ)) 6662 mark_reg_unknown(env, regs, value_regno); 6663 } else { 6664 verbose(env, "R%d invalid mem access '%s'\n", regno, 6665 reg_type_str(env, reg->type)); 6666 return -EACCES; 6667 } 6668 6669 if (!err && size < BPF_REG_SIZE && value_regno >= 0 && t == BPF_READ && 6670 regs[value_regno].type == SCALAR_VALUE) { 6671 if (!is_ldsx) 6672 /* b/h/w load zero-extends, mark upper bits as known 0 */ 6673 coerce_reg_to_size(®s[value_regno], size); 6674 else 6675 coerce_reg_to_size_sx(®s[value_regno], size); 6676 } 6677 return err; 6678 } 6679 6680 static int check_atomic(struct bpf_verifier_env *env, int insn_idx, struct bpf_insn *insn) 6681 { 6682 int load_reg; 6683 int err; 6684 6685 switch (insn->imm) { 6686 case BPF_ADD: 6687 case BPF_ADD | BPF_FETCH: 6688 case BPF_AND: 6689 case BPF_AND | BPF_FETCH: 6690 case BPF_OR: 6691 case BPF_OR | BPF_FETCH: 6692 case BPF_XOR: 6693 case BPF_XOR | BPF_FETCH: 6694 case BPF_XCHG: 6695 case BPF_CMPXCHG: 6696 break; 6697 default: 6698 verbose(env, "BPF_ATOMIC uses invalid atomic opcode %02x\n", insn->imm); 6699 return -EINVAL; 6700 } 6701 6702 if (BPF_SIZE(insn->code) != BPF_W && BPF_SIZE(insn->code) != BPF_DW) { 6703 verbose(env, "invalid atomic operand size\n"); 6704 return -EINVAL; 6705 } 6706 6707 /* check src1 operand */ 6708 err = check_reg_arg(env, insn->src_reg, SRC_OP); 6709 if (err) 6710 return err; 6711 6712 /* check src2 operand */ 6713 err = check_reg_arg(env, insn->dst_reg, SRC_OP); 6714 if (err) 6715 return err; 6716 6717 if (insn->imm == BPF_CMPXCHG) { 6718 /* Check comparison of R0 with memory location */ 6719 const u32 aux_reg = BPF_REG_0; 6720 6721 err = check_reg_arg(env, aux_reg, SRC_OP); 6722 if (err) 6723 return err; 6724 6725 if (is_pointer_value(env, aux_reg)) { 6726 verbose(env, "R%d leaks addr into mem\n", aux_reg); 6727 return -EACCES; 6728 } 6729 } 6730 6731 if (is_pointer_value(env, insn->src_reg)) { 6732 verbose(env, "R%d leaks addr into mem\n", insn->src_reg); 6733 return -EACCES; 6734 } 6735 6736 if (is_ctx_reg(env, insn->dst_reg) || 6737 is_pkt_reg(env, insn->dst_reg) || 6738 is_flow_key_reg(env, insn->dst_reg) || 6739 is_sk_reg(env, insn->dst_reg)) { 6740 verbose(env, "BPF_ATOMIC stores into R%d %s is not allowed\n", 6741 insn->dst_reg, 6742 reg_type_str(env, reg_state(env, insn->dst_reg)->type)); 6743 return -EACCES; 6744 } 6745 6746 if (insn->imm & BPF_FETCH) { 6747 if (insn->imm == BPF_CMPXCHG) 6748 load_reg = BPF_REG_0; 6749 else 6750 load_reg = insn->src_reg; 6751 6752 /* check and record load of old value */ 6753 err = check_reg_arg(env, load_reg, DST_OP); 6754 if (err) 6755 return err; 6756 } else { 6757 /* This instruction accesses a memory location but doesn't 6758 * actually load it into a register. 6759 */ 6760 load_reg = -1; 6761 } 6762 6763 /* Check whether we can read the memory, with second call for fetch 6764 * case to simulate the register fill. 6765 */ 6766 err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off, 6767 BPF_SIZE(insn->code), BPF_READ, -1, true, false); 6768 if (!err && load_reg >= 0) 6769 err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off, 6770 BPF_SIZE(insn->code), BPF_READ, load_reg, 6771 true, false); 6772 if (err) 6773 return err; 6774 6775 /* Check whether we can write into the same memory. */ 6776 err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off, 6777 BPF_SIZE(insn->code), BPF_WRITE, -1, true, false); 6778 if (err) 6779 return err; 6780 6781 return 0; 6782 } 6783 6784 /* When register 'regno' is used to read the stack (either directly or through 6785 * a helper function) make sure that it's within stack boundary and, depending 6786 * on the access type and privileges, that all elements of the stack are 6787 * initialized. 6788 * 6789 * 'off' includes 'regno->off', but not its dynamic part (if any). 6790 * 6791 * All registers that have been spilled on the stack in the slots within the 6792 * read offsets are marked as read. 6793 */ 6794 static int check_stack_range_initialized( 6795 struct bpf_verifier_env *env, int regno, int off, 6796 int access_size, bool zero_size_allowed, 6797 enum bpf_access_src type, struct bpf_call_arg_meta *meta) 6798 { 6799 struct bpf_reg_state *reg = reg_state(env, regno); 6800 struct bpf_func_state *state = func(env, reg); 6801 int err, min_off, max_off, i, j, slot, spi; 6802 char *err_extra = type == ACCESS_HELPER ? " indirect" : ""; 6803 enum bpf_access_type bounds_check_type; 6804 /* Some accesses can write anything into the stack, others are 6805 * read-only. 6806 */ 6807 bool clobber = false; 6808 6809 if (access_size == 0 && !zero_size_allowed) { 6810 verbose(env, "invalid zero-sized read\n"); 6811 return -EACCES; 6812 } 6813 6814 if (type == ACCESS_HELPER) { 6815 /* The bounds checks for writes are more permissive than for 6816 * reads. However, if raw_mode is not set, we'll do extra 6817 * checks below. 6818 */ 6819 bounds_check_type = BPF_WRITE; 6820 clobber = true; 6821 } else { 6822 bounds_check_type = BPF_READ; 6823 } 6824 err = check_stack_access_within_bounds(env, regno, off, access_size, 6825 type, bounds_check_type); 6826 if (err) 6827 return err; 6828 6829 6830 if (tnum_is_const(reg->var_off)) { 6831 min_off = max_off = reg->var_off.value + off; 6832 } else { 6833 /* Variable offset is prohibited for unprivileged mode for 6834 * simplicity since it requires corresponding support in 6835 * Spectre masking for stack ALU. 6836 * See also retrieve_ptr_limit(). 6837 */ 6838 if (!env->bypass_spec_v1) { 6839 char tn_buf[48]; 6840 6841 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 6842 verbose(env, "R%d%s variable offset stack access prohibited for !root, var_off=%s\n", 6843 regno, err_extra, tn_buf); 6844 return -EACCES; 6845 } 6846 /* Only initialized buffer on stack is allowed to be accessed 6847 * with variable offset. With uninitialized buffer it's hard to 6848 * guarantee that whole memory is marked as initialized on 6849 * helper return since specific bounds are unknown what may 6850 * cause uninitialized stack leaking. 6851 */ 6852 if (meta && meta->raw_mode) 6853 meta = NULL; 6854 6855 min_off = reg->smin_value + off; 6856 max_off = reg->smax_value + off; 6857 } 6858 6859 if (meta && meta->raw_mode) { 6860 /* Ensure we won't be overwriting dynptrs when simulating byte 6861 * by byte access in check_helper_call using meta.access_size. 6862 * This would be a problem if we have a helper in the future 6863 * which takes: 6864 * 6865 * helper(uninit_mem, len, dynptr) 6866 * 6867 * Now, uninint_mem may overlap with dynptr pointer. Hence, it 6868 * may end up writing to dynptr itself when touching memory from 6869 * arg 1. This can be relaxed on a case by case basis for known 6870 * safe cases, but reject due to the possibilitiy of aliasing by 6871 * default. 6872 */ 6873 for (i = min_off; i < max_off + access_size; i++) { 6874 int stack_off = -i - 1; 6875 6876 spi = __get_spi(i); 6877 /* raw_mode may write past allocated_stack */ 6878 if (state->allocated_stack <= stack_off) 6879 continue; 6880 if (state->stack[spi].slot_type[stack_off % BPF_REG_SIZE] == STACK_DYNPTR) { 6881 verbose(env, "potential write to dynptr at off=%d disallowed\n", i); 6882 return -EACCES; 6883 } 6884 } 6885 meta->access_size = access_size; 6886 meta->regno = regno; 6887 return 0; 6888 } 6889 6890 for (i = min_off; i < max_off + access_size; i++) { 6891 u8 *stype; 6892 6893 slot = -i - 1; 6894 spi = slot / BPF_REG_SIZE; 6895 if (state->allocated_stack <= slot) { 6896 verbose(env, "verifier bug: allocated_stack too small"); 6897 return -EFAULT; 6898 } 6899 6900 stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE]; 6901 if (*stype == STACK_MISC) 6902 goto mark; 6903 if ((*stype == STACK_ZERO) || 6904 (*stype == STACK_INVALID && env->allow_uninit_stack)) { 6905 if (clobber) { 6906 /* helper can write anything into the stack */ 6907 *stype = STACK_MISC; 6908 } 6909 goto mark; 6910 } 6911 6912 if (is_spilled_reg(&state->stack[spi]) && 6913 (state->stack[spi].spilled_ptr.type == SCALAR_VALUE || 6914 env->allow_ptr_leaks)) { 6915 if (clobber) { 6916 __mark_reg_unknown(env, &state->stack[spi].spilled_ptr); 6917 for (j = 0; j < BPF_REG_SIZE; j++) 6918 scrub_spilled_slot(&state->stack[spi].slot_type[j]); 6919 } 6920 goto mark; 6921 } 6922 6923 if (tnum_is_const(reg->var_off)) { 6924 verbose(env, "invalid%s read from stack R%d off %d+%d size %d\n", 6925 err_extra, regno, min_off, i - min_off, access_size); 6926 } else { 6927 char tn_buf[48]; 6928 6929 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 6930 verbose(env, "invalid%s read from stack R%d var_off %s+%d size %d\n", 6931 err_extra, regno, tn_buf, i - min_off, access_size); 6932 } 6933 return -EACCES; 6934 mark: 6935 /* reading any byte out of 8-byte 'spill_slot' will cause 6936 * the whole slot to be marked as 'read' 6937 */ 6938 mark_reg_read(env, &state->stack[spi].spilled_ptr, 6939 state->stack[spi].spilled_ptr.parent, 6940 REG_LIVE_READ64); 6941 /* We do not set REG_LIVE_WRITTEN for stack slot, as we can not 6942 * be sure that whether stack slot is written to or not. Hence, 6943 * we must still conservatively propagate reads upwards even if 6944 * helper may write to the entire memory range. 6945 */ 6946 } 6947 return 0; 6948 } 6949 6950 static int check_helper_mem_access(struct bpf_verifier_env *env, int regno, 6951 int access_size, bool zero_size_allowed, 6952 struct bpf_call_arg_meta *meta) 6953 { 6954 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno]; 6955 u32 *max_access; 6956 6957 switch (base_type(reg->type)) { 6958 case PTR_TO_PACKET: 6959 case PTR_TO_PACKET_META: 6960 return check_packet_access(env, regno, reg->off, access_size, 6961 zero_size_allowed); 6962 case PTR_TO_MAP_KEY: 6963 if (meta && meta->raw_mode) { 6964 verbose(env, "R%d cannot write into %s\n", regno, 6965 reg_type_str(env, reg->type)); 6966 return -EACCES; 6967 } 6968 return check_mem_region_access(env, regno, reg->off, access_size, 6969 reg->map_ptr->key_size, false); 6970 case PTR_TO_MAP_VALUE: 6971 if (check_map_access_type(env, regno, reg->off, access_size, 6972 meta && meta->raw_mode ? BPF_WRITE : 6973 BPF_READ)) 6974 return -EACCES; 6975 return check_map_access(env, regno, reg->off, access_size, 6976 zero_size_allowed, ACCESS_HELPER); 6977 case PTR_TO_MEM: 6978 if (type_is_rdonly_mem(reg->type)) { 6979 if (meta && meta->raw_mode) { 6980 verbose(env, "R%d cannot write into %s\n", regno, 6981 reg_type_str(env, reg->type)); 6982 return -EACCES; 6983 } 6984 } 6985 return check_mem_region_access(env, regno, reg->off, 6986 access_size, reg->mem_size, 6987 zero_size_allowed); 6988 case PTR_TO_BUF: 6989 if (type_is_rdonly_mem(reg->type)) { 6990 if (meta && meta->raw_mode) { 6991 verbose(env, "R%d cannot write into %s\n", regno, 6992 reg_type_str(env, reg->type)); 6993 return -EACCES; 6994 } 6995 6996 max_access = &env->prog->aux->max_rdonly_access; 6997 } else { 6998 max_access = &env->prog->aux->max_rdwr_access; 6999 } 7000 return check_buffer_access(env, reg, regno, reg->off, 7001 access_size, zero_size_allowed, 7002 max_access); 7003 case PTR_TO_STACK: 7004 return check_stack_range_initialized( 7005 env, 7006 regno, reg->off, access_size, 7007 zero_size_allowed, ACCESS_HELPER, meta); 7008 case PTR_TO_BTF_ID: 7009 return check_ptr_to_btf_access(env, regs, regno, reg->off, 7010 access_size, BPF_READ, -1); 7011 case PTR_TO_CTX: 7012 /* in case the function doesn't know how to access the context, 7013 * (because we are in a program of type SYSCALL for example), we 7014 * can not statically check its size. 7015 * Dynamically check it now. 7016 */ 7017 if (!env->ops->convert_ctx_access) { 7018 enum bpf_access_type atype = meta && meta->raw_mode ? BPF_WRITE : BPF_READ; 7019 int offset = access_size - 1; 7020 7021 /* Allow zero-byte read from PTR_TO_CTX */ 7022 if (access_size == 0) 7023 return zero_size_allowed ? 0 : -EACCES; 7024 7025 return check_mem_access(env, env->insn_idx, regno, offset, BPF_B, 7026 atype, -1, false, false); 7027 } 7028 7029 fallthrough; 7030 default: /* scalar_value or invalid ptr */ 7031 /* Allow zero-byte read from NULL, regardless of pointer type */ 7032 if (zero_size_allowed && access_size == 0 && 7033 register_is_null(reg)) 7034 return 0; 7035 7036 verbose(env, "R%d type=%s ", regno, 7037 reg_type_str(env, reg->type)); 7038 verbose(env, "expected=%s\n", reg_type_str(env, PTR_TO_STACK)); 7039 return -EACCES; 7040 } 7041 } 7042 7043 static int check_mem_size_reg(struct bpf_verifier_env *env, 7044 struct bpf_reg_state *reg, u32 regno, 7045 bool zero_size_allowed, 7046 struct bpf_call_arg_meta *meta) 7047 { 7048 int err; 7049 7050 /* This is used to refine r0 return value bounds for helpers 7051 * that enforce this value as an upper bound on return values. 7052 * See do_refine_retval_range() for helpers that can refine 7053 * the return value. C type of helper is u32 so we pull register 7054 * bound from umax_value however, if negative verifier errors 7055 * out. Only upper bounds can be learned because retval is an 7056 * int type and negative retvals are allowed. 7057 */ 7058 meta->msize_max_value = reg->umax_value; 7059 7060 /* The register is SCALAR_VALUE; the access check 7061 * happens using its boundaries. 7062 */ 7063 if (!tnum_is_const(reg->var_off)) 7064 /* For unprivileged variable accesses, disable raw 7065 * mode so that the program is required to 7066 * initialize all the memory that the helper could 7067 * just partially fill up. 7068 */ 7069 meta = NULL; 7070 7071 if (reg->smin_value < 0) { 7072 verbose(env, "R%d min value is negative, either use unsigned or 'var &= const'\n", 7073 regno); 7074 return -EACCES; 7075 } 7076 7077 if (reg->umin_value == 0) { 7078 err = check_helper_mem_access(env, regno - 1, 0, 7079 zero_size_allowed, 7080 meta); 7081 if (err) 7082 return err; 7083 } 7084 7085 if (reg->umax_value >= BPF_MAX_VAR_SIZ) { 7086 verbose(env, "R%d unbounded memory access, use 'var &= const' or 'if (var < const)'\n", 7087 regno); 7088 return -EACCES; 7089 } 7090 err = check_helper_mem_access(env, regno - 1, 7091 reg->umax_value, 7092 zero_size_allowed, meta); 7093 if (!err) 7094 err = mark_chain_precision(env, regno); 7095 return err; 7096 } 7097 7098 int check_mem_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg, 7099 u32 regno, u32 mem_size) 7100 { 7101 bool may_be_null = type_may_be_null(reg->type); 7102 struct bpf_reg_state saved_reg; 7103 struct bpf_call_arg_meta meta; 7104 int err; 7105 7106 if (register_is_null(reg)) 7107 return 0; 7108 7109 memset(&meta, 0, sizeof(meta)); 7110 /* Assuming that the register contains a value check if the memory 7111 * access is safe. Temporarily save and restore the register's state as 7112 * the conversion shouldn't be visible to a caller. 7113 */ 7114 if (may_be_null) { 7115 saved_reg = *reg; 7116 mark_ptr_not_null_reg(reg); 7117 } 7118 7119 err = check_helper_mem_access(env, regno, mem_size, true, &meta); 7120 /* Check access for BPF_WRITE */ 7121 meta.raw_mode = true; 7122 err = err ?: check_helper_mem_access(env, regno, mem_size, true, &meta); 7123 7124 if (may_be_null) 7125 *reg = saved_reg; 7126 7127 return err; 7128 } 7129 7130 static int check_kfunc_mem_size_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg, 7131 u32 regno) 7132 { 7133 struct bpf_reg_state *mem_reg = &cur_regs(env)[regno - 1]; 7134 bool may_be_null = type_may_be_null(mem_reg->type); 7135 struct bpf_reg_state saved_reg; 7136 struct bpf_call_arg_meta meta; 7137 int err; 7138 7139 WARN_ON_ONCE(regno < BPF_REG_2 || regno > BPF_REG_5); 7140 7141 memset(&meta, 0, sizeof(meta)); 7142 7143 if (may_be_null) { 7144 saved_reg = *mem_reg; 7145 mark_ptr_not_null_reg(mem_reg); 7146 } 7147 7148 err = check_mem_size_reg(env, reg, regno, true, &meta); 7149 /* Check access for BPF_WRITE */ 7150 meta.raw_mode = true; 7151 err = err ?: check_mem_size_reg(env, reg, regno, true, &meta); 7152 7153 if (may_be_null) 7154 *mem_reg = saved_reg; 7155 return err; 7156 } 7157 7158 /* Implementation details: 7159 * bpf_map_lookup returns PTR_TO_MAP_VALUE_OR_NULL. 7160 * bpf_obj_new returns PTR_TO_BTF_ID | MEM_ALLOC | PTR_MAYBE_NULL. 7161 * Two bpf_map_lookups (even with the same key) will have different reg->id. 7162 * Two separate bpf_obj_new will also have different reg->id. 7163 * For traditional PTR_TO_MAP_VALUE or PTR_TO_BTF_ID | MEM_ALLOC, the verifier 7164 * clears reg->id after value_or_null->value transition, since the verifier only 7165 * cares about the range of access to valid map value pointer and doesn't care 7166 * about actual address of the map element. 7167 * For maps with 'struct bpf_spin_lock' inside map value the verifier keeps 7168 * reg->id > 0 after value_or_null->value transition. By doing so 7169 * two bpf_map_lookups will be considered two different pointers that 7170 * point to different bpf_spin_locks. Likewise for pointers to allocated objects 7171 * returned from bpf_obj_new. 7172 * The verifier allows taking only one bpf_spin_lock at a time to avoid 7173 * dead-locks. 7174 * Since only one bpf_spin_lock is allowed the checks are simpler than 7175 * reg_is_refcounted() logic. The verifier needs to remember only 7176 * one spin_lock instead of array of acquired_refs. 7177 * cur_state->active_lock remembers which map value element or allocated 7178 * object got locked and clears it after bpf_spin_unlock. 7179 */ 7180 static int process_spin_lock(struct bpf_verifier_env *env, int regno, 7181 bool is_lock) 7182 { 7183 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno]; 7184 struct bpf_verifier_state *cur = env->cur_state; 7185 bool is_const = tnum_is_const(reg->var_off); 7186 u64 val = reg->var_off.value; 7187 struct bpf_map *map = NULL; 7188 struct btf *btf = NULL; 7189 struct btf_record *rec; 7190 7191 if (!is_const) { 7192 verbose(env, 7193 "R%d doesn't have constant offset. bpf_spin_lock has to be at the constant offset\n", 7194 regno); 7195 return -EINVAL; 7196 } 7197 if (reg->type == PTR_TO_MAP_VALUE) { 7198 map = reg->map_ptr; 7199 if (!map->btf) { 7200 verbose(env, 7201 "map '%s' has to have BTF in order to use bpf_spin_lock\n", 7202 map->name); 7203 return -EINVAL; 7204 } 7205 } else { 7206 btf = reg->btf; 7207 } 7208 7209 rec = reg_btf_record(reg); 7210 if (!btf_record_has_field(rec, BPF_SPIN_LOCK)) { 7211 verbose(env, "%s '%s' has no valid bpf_spin_lock\n", map ? "map" : "local", 7212 map ? map->name : "kptr"); 7213 return -EINVAL; 7214 } 7215 if (rec->spin_lock_off != val + reg->off) { 7216 verbose(env, "off %lld doesn't point to 'struct bpf_spin_lock' that is at %d\n", 7217 val + reg->off, rec->spin_lock_off); 7218 return -EINVAL; 7219 } 7220 if (is_lock) { 7221 if (cur->active_lock.ptr) { 7222 verbose(env, 7223 "Locking two bpf_spin_locks are not allowed\n"); 7224 return -EINVAL; 7225 } 7226 if (map) 7227 cur->active_lock.ptr = map; 7228 else 7229 cur->active_lock.ptr = btf; 7230 cur->active_lock.id = reg->id; 7231 } else { 7232 void *ptr; 7233 7234 if (map) 7235 ptr = map; 7236 else 7237 ptr = btf; 7238 7239 if (!cur->active_lock.ptr) { 7240 verbose(env, "bpf_spin_unlock without taking a lock\n"); 7241 return -EINVAL; 7242 } 7243 if (cur->active_lock.ptr != ptr || 7244 cur->active_lock.id != reg->id) { 7245 verbose(env, "bpf_spin_unlock of different lock\n"); 7246 return -EINVAL; 7247 } 7248 7249 invalidate_non_owning_refs(env); 7250 7251 cur->active_lock.ptr = NULL; 7252 cur->active_lock.id = 0; 7253 } 7254 return 0; 7255 } 7256 7257 static int process_timer_func(struct bpf_verifier_env *env, int regno, 7258 struct bpf_call_arg_meta *meta) 7259 { 7260 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno]; 7261 bool is_const = tnum_is_const(reg->var_off); 7262 struct bpf_map *map = reg->map_ptr; 7263 u64 val = reg->var_off.value; 7264 7265 if (!is_const) { 7266 verbose(env, 7267 "R%d doesn't have constant offset. bpf_timer has to be at the constant offset\n", 7268 regno); 7269 return -EINVAL; 7270 } 7271 if (!map->btf) { 7272 verbose(env, "map '%s' has to have BTF in order to use bpf_timer\n", 7273 map->name); 7274 return -EINVAL; 7275 } 7276 if (!btf_record_has_field(map->record, BPF_TIMER)) { 7277 verbose(env, "map '%s' has no valid bpf_timer\n", map->name); 7278 return -EINVAL; 7279 } 7280 if (map->record->timer_off != val + reg->off) { 7281 verbose(env, "off %lld doesn't point to 'struct bpf_timer' that is at %d\n", 7282 val + reg->off, map->record->timer_off); 7283 return -EINVAL; 7284 } 7285 if (meta->map_ptr) { 7286 verbose(env, "verifier bug. Two map pointers in a timer helper\n"); 7287 return -EFAULT; 7288 } 7289 meta->map_uid = reg->map_uid; 7290 meta->map_ptr = map; 7291 return 0; 7292 } 7293 7294 static int process_kptr_func(struct bpf_verifier_env *env, int regno, 7295 struct bpf_call_arg_meta *meta) 7296 { 7297 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno]; 7298 struct bpf_map *map_ptr = reg->map_ptr; 7299 struct btf_field *kptr_field; 7300 u32 kptr_off; 7301 7302 if (!tnum_is_const(reg->var_off)) { 7303 verbose(env, 7304 "R%d doesn't have constant offset. kptr has to be at the constant offset\n", 7305 regno); 7306 return -EINVAL; 7307 } 7308 if (!map_ptr->btf) { 7309 verbose(env, "map '%s' has to have BTF in order to use bpf_kptr_xchg\n", 7310 map_ptr->name); 7311 return -EINVAL; 7312 } 7313 if (!btf_record_has_field(map_ptr->record, BPF_KPTR)) { 7314 verbose(env, "map '%s' has no valid kptr\n", map_ptr->name); 7315 return -EINVAL; 7316 } 7317 7318 meta->map_ptr = map_ptr; 7319 kptr_off = reg->off + reg->var_off.value; 7320 kptr_field = btf_record_find(map_ptr->record, kptr_off, BPF_KPTR); 7321 if (!kptr_field) { 7322 verbose(env, "off=%d doesn't point to kptr\n", kptr_off); 7323 return -EACCES; 7324 } 7325 if (kptr_field->type != BPF_KPTR_REF) { 7326 verbose(env, "off=%d kptr isn't referenced kptr\n", kptr_off); 7327 return -EACCES; 7328 } 7329 meta->kptr_field = kptr_field; 7330 return 0; 7331 } 7332 7333 /* There are two register types representing a bpf_dynptr, one is PTR_TO_STACK 7334 * which points to a stack slot, and the other is CONST_PTR_TO_DYNPTR. 7335 * 7336 * In both cases we deal with the first 8 bytes, but need to mark the next 8 7337 * bytes as STACK_DYNPTR in case of PTR_TO_STACK. In case of 7338 * CONST_PTR_TO_DYNPTR, we are guaranteed to get the beginning of the object. 7339 * 7340 * Mutability of bpf_dynptr is at two levels, one is at the level of struct 7341 * bpf_dynptr itself, i.e. whether the helper is receiving a pointer to struct 7342 * bpf_dynptr or pointer to const struct bpf_dynptr. In the former case, it can 7343 * mutate the view of the dynptr and also possibly destroy it. In the latter 7344 * case, it cannot mutate the bpf_dynptr itself but it can still mutate the 7345 * memory that dynptr points to. 7346 * 7347 * The verifier will keep track both levels of mutation (bpf_dynptr's in 7348 * reg->type and the memory's in reg->dynptr.type), but there is no support for 7349 * readonly dynptr view yet, hence only the first case is tracked and checked. 7350 * 7351 * This is consistent with how C applies the const modifier to a struct object, 7352 * where the pointer itself inside bpf_dynptr becomes const but not what it 7353 * points to. 7354 * 7355 * Helpers which do not mutate the bpf_dynptr set MEM_RDONLY in their argument 7356 * type, and declare it as 'const struct bpf_dynptr *' in their prototype. 7357 */ 7358 static int process_dynptr_func(struct bpf_verifier_env *env, int regno, int insn_idx, 7359 enum bpf_arg_type arg_type, int clone_ref_obj_id) 7360 { 7361 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno]; 7362 int err; 7363 7364 /* MEM_UNINIT and MEM_RDONLY are exclusive, when applied to an 7365 * ARG_PTR_TO_DYNPTR (or ARG_PTR_TO_DYNPTR | DYNPTR_TYPE_*): 7366 */ 7367 if ((arg_type & (MEM_UNINIT | MEM_RDONLY)) == (MEM_UNINIT | MEM_RDONLY)) { 7368 verbose(env, "verifier internal error: misconfigured dynptr helper type flags\n"); 7369 return -EFAULT; 7370 } 7371 7372 /* MEM_UNINIT - Points to memory that is an appropriate candidate for 7373 * constructing a mutable bpf_dynptr object. 7374 * 7375 * Currently, this is only possible with PTR_TO_STACK 7376 * pointing to a region of at least 16 bytes which doesn't 7377 * contain an existing bpf_dynptr. 7378 * 7379 * MEM_RDONLY - Points to a initialized bpf_dynptr that will not be 7380 * mutated or destroyed. However, the memory it points to 7381 * may be mutated. 7382 * 7383 * None - Points to a initialized dynptr that can be mutated and 7384 * destroyed, including mutation of the memory it points 7385 * to. 7386 */ 7387 if (arg_type & MEM_UNINIT) { 7388 int i; 7389 7390 if (!is_dynptr_reg_valid_uninit(env, reg)) { 7391 verbose(env, "Dynptr has to be an uninitialized dynptr\n"); 7392 return -EINVAL; 7393 } 7394 7395 /* we write BPF_DW bits (8 bytes) at a time */ 7396 for (i = 0; i < BPF_DYNPTR_SIZE; i += 8) { 7397 err = check_mem_access(env, insn_idx, regno, 7398 i, BPF_DW, BPF_WRITE, -1, false, false); 7399 if (err) 7400 return err; 7401 } 7402 7403 err = mark_stack_slots_dynptr(env, reg, arg_type, insn_idx, clone_ref_obj_id); 7404 } else /* MEM_RDONLY and None case from above */ { 7405 /* For the reg->type == PTR_TO_STACK case, bpf_dynptr is never const */ 7406 if (reg->type == CONST_PTR_TO_DYNPTR && !(arg_type & MEM_RDONLY)) { 7407 verbose(env, "cannot pass pointer to const bpf_dynptr, the helper mutates it\n"); 7408 return -EINVAL; 7409 } 7410 7411 if (!is_dynptr_reg_valid_init(env, reg)) { 7412 verbose(env, 7413 "Expected an initialized dynptr as arg #%d\n", 7414 regno); 7415 return -EINVAL; 7416 } 7417 7418 /* Fold modifiers (in this case, MEM_RDONLY) when checking expected type */ 7419 if (!is_dynptr_type_expected(env, reg, arg_type & ~MEM_RDONLY)) { 7420 verbose(env, 7421 "Expected a dynptr of type %s as arg #%d\n", 7422 dynptr_type_str(arg_to_dynptr_type(arg_type)), regno); 7423 return -EINVAL; 7424 } 7425 7426 err = mark_dynptr_read(env, reg); 7427 } 7428 return err; 7429 } 7430 7431 static u32 iter_ref_obj_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg, int spi) 7432 { 7433 struct bpf_func_state *state = func(env, reg); 7434 7435 return state->stack[spi].spilled_ptr.ref_obj_id; 7436 } 7437 7438 static bool is_iter_kfunc(struct bpf_kfunc_call_arg_meta *meta) 7439 { 7440 return meta->kfunc_flags & (KF_ITER_NEW | KF_ITER_NEXT | KF_ITER_DESTROY); 7441 } 7442 7443 static bool is_iter_new_kfunc(struct bpf_kfunc_call_arg_meta *meta) 7444 { 7445 return meta->kfunc_flags & KF_ITER_NEW; 7446 } 7447 7448 static bool is_iter_next_kfunc(struct bpf_kfunc_call_arg_meta *meta) 7449 { 7450 return meta->kfunc_flags & KF_ITER_NEXT; 7451 } 7452 7453 static bool is_iter_destroy_kfunc(struct bpf_kfunc_call_arg_meta *meta) 7454 { 7455 return meta->kfunc_flags & KF_ITER_DESTROY; 7456 } 7457 7458 static bool is_kfunc_arg_iter(struct bpf_kfunc_call_arg_meta *meta, int arg) 7459 { 7460 /* btf_check_iter_kfuncs() guarantees that first argument of any iter 7461 * kfunc is iter state pointer 7462 */ 7463 return arg == 0 && is_iter_kfunc(meta); 7464 } 7465 7466 static int process_iter_arg(struct bpf_verifier_env *env, int regno, int insn_idx, 7467 struct bpf_kfunc_call_arg_meta *meta) 7468 { 7469 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno]; 7470 const struct btf_type *t; 7471 const struct btf_param *arg; 7472 int spi, err, i, nr_slots; 7473 u32 btf_id; 7474 7475 /* btf_check_iter_kfuncs() ensures we don't need to validate anything here */ 7476 arg = &btf_params(meta->func_proto)[0]; 7477 t = btf_type_skip_modifiers(meta->btf, arg->type, NULL); /* PTR */ 7478 t = btf_type_skip_modifiers(meta->btf, t->type, &btf_id); /* STRUCT */ 7479 nr_slots = t->size / BPF_REG_SIZE; 7480 7481 if (is_iter_new_kfunc(meta)) { 7482 /* bpf_iter_<type>_new() expects pointer to uninit iter state */ 7483 if (!is_iter_reg_valid_uninit(env, reg, nr_slots)) { 7484 verbose(env, "expected uninitialized iter_%s as arg #%d\n", 7485 iter_type_str(meta->btf, btf_id), regno); 7486 return -EINVAL; 7487 } 7488 7489 for (i = 0; i < nr_slots * 8; i += BPF_REG_SIZE) { 7490 err = check_mem_access(env, insn_idx, regno, 7491 i, BPF_DW, BPF_WRITE, -1, false, false); 7492 if (err) 7493 return err; 7494 } 7495 7496 err = mark_stack_slots_iter(env, reg, insn_idx, meta->btf, btf_id, nr_slots); 7497 if (err) 7498 return err; 7499 } else { 7500 /* iter_next() or iter_destroy() expect initialized iter state*/ 7501 if (!is_iter_reg_valid_init(env, reg, meta->btf, btf_id, nr_slots)) { 7502 verbose(env, "expected an initialized iter_%s as arg #%d\n", 7503 iter_type_str(meta->btf, btf_id), regno); 7504 return -EINVAL; 7505 } 7506 7507 spi = iter_get_spi(env, reg, nr_slots); 7508 if (spi < 0) 7509 return spi; 7510 7511 err = mark_iter_read(env, reg, spi, nr_slots); 7512 if (err) 7513 return err; 7514 7515 /* remember meta->iter info for process_iter_next_call() */ 7516 meta->iter.spi = spi; 7517 meta->iter.frameno = reg->frameno; 7518 meta->ref_obj_id = iter_ref_obj_id(env, reg, spi); 7519 7520 if (is_iter_destroy_kfunc(meta)) { 7521 err = unmark_stack_slots_iter(env, reg, nr_slots); 7522 if (err) 7523 return err; 7524 } 7525 } 7526 7527 return 0; 7528 } 7529 7530 /* process_iter_next_call() is called when verifier gets to iterator's next 7531 * "method" (e.g., bpf_iter_num_next() for numbers iterator) call. We'll refer 7532 * to it as just "iter_next()" in comments below. 7533 * 7534 * BPF verifier relies on a crucial contract for any iter_next() 7535 * implementation: it should *eventually* return NULL, and once that happens 7536 * it should keep returning NULL. That is, once iterator exhausts elements to 7537 * iterate, it should never reset or spuriously return new elements. 7538 * 7539 * With the assumption of such contract, process_iter_next_call() simulates 7540 * a fork in the verifier state to validate loop logic correctness and safety 7541 * without having to simulate infinite amount of iterations. 7542 * 7543 * In current state, we first assume that iter_next() returned NULL and 7544 * iterator state is set to DRAINED (BPF_ITER_STATE_DRAINED). In such 7545 * conditions we should not form an infinite loop and should eventually reach 7546 * exit. 7547 * 7548 * Besides that, we also fork current state and enqueue it for later 7549 * verification. In a forked state we keep iterator state as ACTIVE 7550 * (BPF_ITER_STATE_ACTIVE) and assume non-NULL return from iter_next(). We 7551 * also bump iteration depth to prevent erroneous infinite loop detection 7552 * later on (see iter_active_depths_differ() comment for details). In this 7553 * state we assume that we'll eventually loop back to another iter_next() 7554 * calls (it could be in exactly same location or in some other instruction, 7555 * it doesn't matter, we don't make any unnecessary assumptions about this, 7556 * everything revolves around iterator state in a stack slot, not which 7557 * instruction is calling iter_next()). When that happens, we either will come 7558 * to iter_next() with equivalent state and can conclude that next iteration 7559 * will proceed in exactly the same way as we just verified, so it's safe to 7560 * assume that loop converges. If not, we'll go on another iteration 7561 * simulation with a different input state, until all possible starting states 7562 * are validated or we reach maximum number of instructions limit. 7563 * 7564 * This way, we will either exhaustively discover all possible input states 7565 * that iterator loop can start with and eventually will converge, or we'll 7566 * effectively regress into bounded loop simulation logic and either reach 7567 * maximum number of instructions if loop is not provably convergent, or there 7568 * is some statically known limit on number of iterations (e.g., if there is 7569 * an explicit `if n > 100 then break;` statement somewhere in the loop). 7570 * 7571 * One very subtle but very important aspect is that we *always* simulate NULL 7572 * condition first (as the current state) before we simulate non-NULL case. 7573 * This has to do with intricacies of scalar precision tracking. By simulating 7574 * "exit condition" of iter_next() returning NULL first, we make sure all the 7575 * relevant precision marks *that will be set **after** we exit iterator loop* 7576 * are propagated backwards to common parent state of NULL and non-NULL 7577 * branches. Thanks to that, state equivalence checks done later in forked 7578 * state, when reaching iter_next() for ACTIVE iterator, can assume that 7579 * precision marks are finalized and won't change. Because simulating another 7580 * ACTIVE iterator iteration won't change them (because given same input 7581 * states we'll end up with exactly same output states which we are currently 7582 * comparing; and verification after the loop already propagated back what 7583 * needs to be **additionally** tracked as precise). It's subtle, grok 7584 * precision tracking for more intuitive understanding. 7585 */ 7586 static int process_iter_next_call(struct bpf_verifier_env *env, int insn_idx, 7587 struct bpf_kfunc_call_arg_meta *meta) 7588 { 7589 struct bpf_verifier_state *cur_st = env->cur_state, *queued_st; 7590 struct bpf_func_state *cur_fr = cur_st->frame[cur_st->curframe], *queued_fr; 7591 struct bpf_reg_state *cur_iter, *queued_iter; 7592 int iter_frameno = meta->iter.frameno; 7593 int iter_spi = meta->iter.spi; 7594 7595 BTF_TYPE_EMIT(struct bpf_iter); 7596 7597 cur_iter = &env->cur_state->frame[iter_frameno]->stack[iter_spi].spilled_ptr; 7598 7599 if (cur_iter->iter.state != BPF_ITER_STATE_ACTIVE && 7600 cur_iter->iter.state != BPF_ITER_STATE_DRAINED) { 7601 verbose(env, "verifier internal error: unexpected iterator state %d (%s)\n", 7602 cur_iter->iter.state, iter_state_str(cur_iter->iter.state)); 7603 return -EFAULT; 7604 } 7605 7606 if (cur_iter->iter.state == BPF_ITER_STATE_ACTIVE) { 7607 /* branch out active iter state */ 7608 queued_st = push_stack(env, insn_idx + 1, insn_idx, false); 7609 if (!queued_st) 7610 return -ENOMEM; 7611 7612 queued_iter = &queued_st->frame[iter_frameno]->stack[iter_spi].spilled_ptr; 7613 queued_iter->iter.state = BPF_ITER_STATE_ACTIVE; 7614 queued_iter->iter.depth++; 7615 7616 queued_fr = queued_st->frame[queued_st->curframe]; 7617 mark_ptr_not_null_reg(&queued_fr->regs[BPF_REG_0]); 7618 } 7619 7620 /* switch to DRAINED state, but keep the depth unchanged */ 7621 /* mark current iter state as drained and assume returned NULL */ 7622 cur_iter->iter.state = BPF_ITER_STATE_DRAINED; 7623 __mark_reg_const_zero(&cur_fr->regs[BPF_REG_0]); 7624 7625 return 0; 7626 } 7627 7628 static bool arg_type_is_mem_size(enum bpf_arg_type type) 7629 { 7630 return type == ARG_CONST_SIZE || 7631 type == ARG_CONST_SIZE_OR_ZERO; 7632 } 7633 7634 static bool arg_type_is_release(enum bpf_arg_type type) 7635 { 7636 return type & OBJ_RELEASE; 7637 } 7638 7639 static bool arg_type_is_dynptr(enum bpf_arg_type type) 7640 { 7641 return base_type(type) == ARG_PTR_TO_DYNPTR; 7642 } 7643 7644 static int int_ptr_type_to_size(enum bpf_arg_type type) 7645 { 7646 if (type == ARG_PTR_TO_INT) 7647 return sizeof(u32); 7648 else if (type == ARG_PTR_TO_LONG) 7649 return sizeof(u64); 7650 7651 return -EINVAL; 7652 } 7653 7654 static int resolve_map_arg_type(struct bpf_verifier_env *env, 7655 const struct bpf_call_arg_meta *meta, 7656 enum bpf_arg_type *arg_type) 7657 { 7658 if (!meta->map_ptr) { 7659 /* kernel subsystem misconfigured verifier */ 7660 verbose(env, "invalid map_ptr to access map->type\n"); 7661 return -EACCES; 7662 } 7663 7664 switch (meta->map_ptr->map_type) { 7665 case BPF_MAP_TYPE_SOCKMAP: 7666 case BPF_MAP_TYPE_SOCKHASH: 7667 if (*arg_type == ARG_PTR_TO_MAP_VALUE) { 7668 *arg_type = ARG_PTR_TO_BTF_ID_SOCK_COMMON; 7669 } else { 7670 verbose(env, "invalid arg_type for sockmap/sockhash\n"); 7671 return -EINVAL; 7672 } 7673 break; 7674 case BPF_MAP_TYPE_BLOOM_FILTER: 7675 if (meta->func_id == BPF_FUNC_map_peek_elem) 7676 *arg_type = ARG_PTR_TO_MAP_VALUE; 7677 break; 7678 default: 7679 break; 7680 } 7681 return 0; 7682 } 7683 7684 struct bpf_reg_types { 7685 const enum bpf_reg_type types[10]; 7686 u32 *btf_id; 7687 }; 7688 7689 static const struct bpf_reg_types sock_types = { 7690 .types = { 7691 PTR_TO_SOCK_COMMON, 7692 PTR_TO_SOCKET, 7693 PTR_TO_TCP_SOCK, 7694 PTR_TO_XDP_SOCK, 7695 }, 7696 }; 7697 7698 #ifdef CONFIG_NET 7699 static const struct bpf_reg_types btf_id_sock_common_types = { 7700 .types = { 7701 PTR_TO_SOCK_COMMON, 7702 PTR_TO_SOCKET, 7703 PTR_TO_TCP_SOCK, 7704 PTR_TO_XDP_SOCK, 7705 PTR_TO_BTF_ID, 7706 PTR_TO_BTF_ID | PTR_TRUSTED, 7707 }, 7708 .btf_id = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON], 7709 }; 7710 #endif 7711 7712 static const struct bpf_reg_types mem_types = { 7713 .types = { 7714 PTR_TO_STACK, 7715 PTR_TO_PACKET, 7716 PTR_TO_PACKET_META, 7717 PTR_TO_MAP_KEY, 7718 PTR_TO_MAP_VALUE, 7719 PTR_TO_MEM, 7720 PTR_TO_MEM | MEM_RINGBUF, 7721 PTR_TO_BUF, 7722 PTR_TO_BTF_ID | PTR_TRUSTED, 7723 }, 7724 }; 7725 7726 static const struct bpf_reg_types int_ptr_types = { 7727 .types = { 7728 PTR_TO_STACK, 7729 PTR_TO_PACKET, 7730 PTR_TO_PACKET_META, 7731 PTR_TO_MAP_KEY, 7732 PTR_TO_MAP_VALUE, 7733 }, 7734 }; 7735 7736 static const struct bpf_reg_types spin_lock_types = { 7737 .types = { 7738 PTR_TO_MAP_VALUE, 7739 PTR_TO_BTF_ID | MEM_ALLOC, 7740 } 7741 }; 7742 7743 static const struct bpf_reg_types fullsock_types = { .types = { PTR_TO_SOCKET } }; 7744 static const struct bpf_reg_types scalar_types = { .types = { SCALAR_VALUE } }; 7745 static const struct bpf_reg_types context_types = { .types = { PTR_TO_CTX } }; 7746 static const struct bpf_reg_types ringbuf_mem_types = { .types = { PTR_TO_MEM | MEM_RINGBUF } }; 7747 static const struct bpf_reg_types const_map_ptr_types = { .types = { CONST_PTR_TO_MAP } }; 7748 static const struct bpf_reg_types btf_ptr_types = { 7749 .types = { 7750 PTR_TO_BTF_ID, 7751 PTR_TO_BTF_ID | PTR_TRUSTED, 7752 PTR_TO_BTF_ID | MEM_RCU, 7753 }, 7754 }; 7755 static const struct bpf_reg_types percpu_btf_ptr_types = { 7756 .types = { 7757 PTR_TO_BTF_ID | MEM_PERCPU, 7758 PTR_TO_BTF_ID | MEM_PERCPU | PTR_TRUSTED, 7759 } 7760 }; 7761 static const struct bpf_reg_types func_ptr_types = { .types = { PTR_TO_FUNC } }; 7762 static const struct bpf_reg_types stack_ptr_types = { .types = { PTR_TO_STACK } }; 7763 static const struct bpf_reg_types const_str_ptr_types = { .types = { PTR_TO_MAP_VALUE } }; 7764 static const struct bpf_reg_types timer_types = { .types = { PTR_TO_MAP_VALUE } }; 7765 static const struct bpf_reg_types kptr_types = { .types = { PTR_TO_MAP_VALUE } }; 7766 static const struct bpf_reg_types dynptr_types = { 7767 .types = { 7768 PTR_TO_STACK, 7769 CONST_PTR_TO_DYNPTR, 7770 } 7771 }; 7772 7773 static const struct bpf_reg_types *compatible_reg_types[__BPF_ARG_TYPE_MAX] = { 7774 [ARG_PTR_TO_MAP_KEY] = &mem_types, 7775 [ARG_PTR_TO_MAP_VALUE] = &mem_types, 7776 [ARG_CONST_SIZE] = &scalar_types, 7777 [ARG_CONST_SIZE_OR_ZERO] = &scalar_types, 7778 [ARG_CONST_ALLOC_SIZE_OR_ZERO] = &scalar_types, 7779 [ARG_CONST_MAP_PTR] = &const_map_ptr_types, 7780 [ARG_PTR_TO_CTX] = &context_types, 7781 [ARG_PTR_TO_SOCK_COMMON] = &sock_types, 7782 #ifdef CONFIG_NET 7783 [ARG_PTR_TO_BTF_ID_SOCK_COMMON] = &btf_id_sock_common_types, 7784 #endif 7785 [ARG_PTR_TO_SOCKET] = &fullsock_types, 7786 [ARG_PTR_TO_BTF_ID] = &btf_ptr_types, 7787 [ARG_PTR_TO_SPIN_LOCK] = &spin_lock_types, 7788 [ARG_PTR_TO_MEM] = &mem_types, 7789 [ARG_PTR_TO_RINGBUF_MEM] = &ringbuf_mem_types, 7790 [ARG_PTR_TO_INT] = &int_ptr_types, 7791 [ARG_PTR_TO_LONG] = &int_ptr_types, 7792 [ARG_PTR_TO_PERCPU_BTF_ID] = &percpu_btf_ptr_types, 7793 [ARG_PTR_TO_FUNC] = &func_ptr_types, 7794 [ARG_PTR_TO_STACK] = &stack_ptr_types, 7795 [ARG_PTR_TO_CONST_STR] = &const_str_ptr_types, 7796 [ARG_PTR_TO_TIMER] = &timer_types, 7797 [ARG_PTR_TO_KPTR] = &kptr_types, 7798 [ARG_PTR_TO_DYNPTR] = &dynptr_types, 7799 }; 7800 7801 static int check_reg_type(struct bpf_verifier_env *env, u32 regno, 7802 enum bpf_arg_type arg_type, 7803 const u32 *arg_btf_id, 7804 struct bpf_call_arg_meta *meta) 7805 { 7806 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno]; 7807 enum bpf_reg_type expected, type = reg->type; 7808 const struct bpf_reg_types *compatible; 7809 int i, j; 7810 7811 compatible = compatible_reg_types[base_type(arg_type)]; 7812 if (!compatible) { 7813 verbose(env, "verifier internal error: unsupported arg type %d\n", arg_type); 7814 return -EFAULT; 7815 } 7816 7817 /* ARG_PTR_TO_MEM + RDONLY is compatible with PTR_TO_MEM and PTR_TO_MEM + RDONLY, 7818 * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM and NOT with PTR_TO_MEM + RDONLY 7819 * 7820 * Same for MAYBE_NULL: 7821 * 7822 * ARG_PTR_TO_MEM + MAYBE_NULL is compatible with PTR_TO_MEM and PTR_TO_MEM + MAYBE_NULL, 7823 * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM but NOT with PTR_TO_MEM + MAYBE_NULL 7824 * 7825 * ARG_PTR_TO_MEM is compatible with PTR_TO_MEM that is tagged with a dynptr type. 7826 * 7827 * Therefore we fold these flags depending on the arg_type before comparison. 7828 */ 7829 if (arg_type & MEM_RDONLY) 7830 type &= ~MEM_RDONLY; 7831 if (arg_type & PTR_MAYBE_NULL) 7832 type &= ~PTR_MAYBE_NULL; 7833 if (base_type(arg_type) == ARG_PTR_TO_MEM) 7834 type &= ~DYNPTR_TYPE_FLAG_MASK; 7835 7836 if (meta->func_id == BPF_FUNC_kptr_xchg && type_is_alloc(type)) 7837 type &= ~MEM_ALLOC; 7838 7839 for (i = 0; i < ARRAY_SIZE(compatible->types); i++) { 7840 expected = compatible->types[i]; 7841 if (expected == NOT_INIT) 7842 break; 7843 7844 if (type == expected) 7845 goto found; 7846 } 7847 7848 verbose(env, "R%d type=%s expected=", regno, reg_type_str(env, reg->type)); 7849 for (j = 0; j + 1 < i; j++) 7850 verbose(env, "%s, ", reg_type_str(env, compatible->types[j])); 7851 verbose(env, "%s\n", reg_type_str(env, compatible->types[j])); 7852 return -EACCES; 7853 7854 found: 7855 if (base_type(reg->type) != PTR_TO_BTF_ID) 7856 return 0; 7857 7858 if (compatible == &mem_types) { 7859 if (!(arg_type & MEM_RDONLY)) { 7860 verbose(env, 7861 "%s() may write into memory pointed by R%d type=%s\n", 7862 func_id_name(meta->func_id), 7863 regno, reg_type_str(env, reg->type)); 7864 return -EACCES; 7865 } 7866 return 0; 7867 } 7868 7869 switch ((int)reg->type) { 7870 case PTR_TO_BTF_ID: 7871 case PTR_TO_BTF_ID | PTR_TRUSTED: 7872 case PTR_TO_BTF_ID | MEM_RCU: 7873 case PTR_TO_BTF_ID | PTR_MAYBE_NULL: 7874 case PTR_TO_BTF_ID | PTR_MAYBE_NULL | MEM_RCU: 7875 { 7876 /* For bpf_sk_release, it needs to match against first member 7877 * 'struct sock_common', hence make an exception for it. This 7878 * allows bpf_sk_release to work for multiple socket types. 7879 */ 7880 bool strict_type_match = arg_type_is_release(arg_type) && 7881 meta->func_id != BPF_FUNC_sk_release; 7882 7883 if (type_may_be_null(reg->type) && 7884 (!type_may_be_null(arg_type) || arg_type_is_release(arg_type))) { 7885 verbose(env, "Possibly NULL pointer passed to helper arg%d\n", regno); 7886 return -EACCES; 7887 } 7888 7889 if (!arg_btf_id) { 7890 if (!compatible->btf_id) { 7891 verbose(env, "verifier internal error: missing arg compatible BTF ID\n"); 7892 return -EFAULT; 7893 } 7894 arg_btf_id = compatible->btf_id; 7895 } 7896 7897 if (meta->func_id == BPF_FUNC_kptr_xchg) { 7898 if (map_kptr_match_type(env, meta->kptr_field, reg, regno)) 7899 return -EACCES; 7900 } else { 7901 if (arg_btf_id == BPF_PTR_POISON) { 7902 verbose(env, "verifier internal error:"); 7903 verbose(env, "R%d has non-overwritten BPF_PTR_POISON type\n", 7904 regno); 7905 return -EACCES; 7906 } 7907 7908 if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off, 7909 btf_vmlinux, *arg_btf_id, 7910 strict_type_match)) { 7911 verbose(env, "R%d is of type %s but %s is expected\n", 7912 regno, btf_type_name(reg->btf, reg->btf_id), 7913 btf_type_name(btf_vmlinux, *arg_btf_id)); 7914 return -EACCES; 7915 } 7916 } 7917 break; 7918 } 7919 case PTR_TO_BTF_ID | MEM_ALLOC: 7920 if (meta->func_id != BPF_FUNC_spin_lock && meta->func_id != BPF_FUNC_spin_unlock && 7921 meta->func_id != BPF_FUNC_kptr_xchg) { 7922 verbose(env, "verifier internal error: unimplemented handling of MEM_ALLOC\n"); 7923 return -EFAULT; 7924 } 7925 if (meta->func_id == BPF_FUNC_kptr_xchg) { 7926 if (map_kptr_match_type(env, meta->kptr_field, reg, regno)) 7927 return -EACCES; 7928 } 7929 break; 7930 case PTR_TO_BTF_ID | MEM_PERCPU: 7931 case PTR_TO_BTF_ID | MEM_PERCPU | PTR_TRUSTED: 7932 /* Handled by helper specific checks */ 7933 break; 7934 default: 7935 verbose(env, "verifier internal error: invalid PTR_TO_BTF_ID register for type match\n"); 7936 return -EFAULT; 7937 } 7938 return 0; 7939 } 7940 7941 static struct btf_field * 7942 reg_find_field_offset(const struct bpf_reg_state *reg, s32 off, u32 fields) 7943 { 7944 struct btf_field *field; 7945 struct btf_record *rec; 7946 7947 rec = reg_btf_record(reg); 7948 if (!rec) 7949 return NULL; 7950 7951 field = btf_record_find(rec, off, fields); 7952 if (!field) 7953 return NULL; 7954 7955 return field; 7956 } 7957 7958 int check_func_arg_reg_off(struct bpf_verifier_env *env, 7959 const struct bpf_reg_state *reg, int regno, 7960 enum bpf_arg_type arg_type) 7961 { 7962 u32 type = reg->type; 7963 7964 /* When referenced register is passed to release function, its fixed 7965 * offset must be 0. 7966 * 7967 * We will check arg_type_is_release reg has ref_obj_id when storing 7968 * meta->release_regno. 7969 */ 7970 if (arg_type_is_release(arg_type)) { 7971 /* ARG_PTR_TO_DYNPTR with OBJ_RELEASE is a bit special, as it 7972 * may not directly point to the object being released, but to 7973 * dynptr pointing to such object, which might be at some offset 7974 * on the stack. In that case, we simply to fallback to the 7975 * default handling. 7976 */ 7977 if (arg_type_is_dynptr(arg_type) && type == PTR_TO_STACK) 7978 return 0; 7979 7980 /* Doing check_ptr_off_reg check for the offset will catch this 7981 * because fixed_off_ok is false, but checking here allows us 7982 * to give the user a better error message. 7983 */ 7984 if (reg->off) { 7985 verbose(env, "R%d must have zero offset when passed to release func or trusted arg to kfunc\n", 7986 regno); 7987 return -EINVAL; 7988 } 7989 return __check_ptr_off_reg(env, reg, regno, false); 7990 } 7991 7992 switch (type) { 7993 /* Pointer types where both fixed and variable offset is explicitly allowed: */ 7994 case PTR_TO_STACK: 7995 case PTR_TO_PACKET: 7996 case PTR_TO_PACKET_META: 7997 case PTR_TO_MAP_KEY: 7998 case PTR_TO_MAP_VALUE: 7999 case PTR_TO_MEM: 8000 case PTR_TO_MEM | MEM_RDONLY: 8001 case PTR_TO_MEM | MEM_RINGBUF: 8002 case PTR_TO_BUF: 8003 case PTR_TO_BUF | MEM_RDONLY: 8004 case SCALAR_VALUE: 8005 return 0; 8006 /* All the rest must be rejected, except PTR_TO_BTF_ID which allows 8007 * fixed offset. 8008 */ 8009 case PTR_TO_BTF_ID: 8010 case PTR_TO_BTF_ID | MEM_ALLOC: 8011 case PTR_TO_BTF_ID | PTR_TRUSTED: 8012 case PTR_TO_BTF_ID | MEM_RCU: 8013 case PTR_TO_BTF_ID | MEM_ALLOC | NON_OWN_REF: 8014 case PTR_TO_BTF_ID | MEM_ALLOC | NON_OWN_REF | MEM_RCU: 8015 /* When referenced PTR_TO_BTF_ID is passed to release function, 8016 * its fixed offset must be 0. In the other cases, fixed offset 8017 * can be non-zero. This was already checked above. So pass 8018 * fixed_off_ok as true to allow fixed offset for all other 8019 * cases. var_off always must be 0 for PTR_TO_BTF_ID, hence we 8020 * still need to do checks instead of returning. 8021 */ 8022 return __check_ptr_off_reg(env, reg, regno, true); 8023 default: 8024 return __check_ptr_off_reg(env, reg, regno, false); 8025 } 8026 } 8027 8028 static struct bpf_reg_state *get_dynptr_arg_reg(struct bpf_verifier_env *env, 8029 const struct bpf_func_proto *fn, 8030 struct bpf_reg_state *regs) 8031 { 8032 struct bpf_reg_state *state = NULL; 8033 int i; 8034 8035 for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++) 8036 if (arg_type_is_dynptr(fn->arg_type[i])) { 8037 if (state) { 8038 verbose(env, "verifier internal error: multiple dynptr args\n"); 8039 return NULL; 8040 } 8041 state = ®s[BPF_REG_1 + i]; 8042 } 8043 8044 if (!state) 8045 verbose(env, "verifier internal error: no dynptr arg found\n"); 8046 8047 return state; 8048 } 8049 8050 static int dynptr_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 8051 { 8052 struct bpf_func_state *state = func(env, reg); 8053 int spi; 8054 8055 if (reg->type == CONST_PTR_TO_DYNPTR) 8056 return reg->id; 8057 spi = dynptr_get_spi(env, reg); 8058 if (spi < 0) 8059 return spi; 8060 return state->stack[spi].spilled_ptr.id; 8061 } 8062 8063 static int dynptr_ref_obj_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 8064 { 8065 struct bpf_func_state *state = func(env, reg); 8066 int spi; 8067 8068 if (reg->type == CONST_PTR_TO_DYNPTR) 8069 return reg->ref_obj_id; 8070 spi = dynptr_get_spi(env, reg); 8071 if (spi < 0) 8072 return spi; 8073 return state->stack[spi].spilled_ptr.ref_obj_id; 8074 } 8075 8076 static enum bpf_dynptr_type dynptr_get_type(struct bpf_verifier_env *env, 8077 struct bpf_reg_state *reg) 8078 { 8079 struct bpf_func_state *state = func(env, reg); 8080 int spi; 8081 8082 if (reg->type == CONST_PTR_TO_DYNPTR) 8083 return reg->dynptr.type; 8084 8085 spi = __get_spi(reg->off); 8086 if (spi < 0) { 8087 verbose(env, "verifier internal error: invalid spi when querying dynptr type\n"); 8088 return BPF_DYNPTR_TYPE_INVALID; 8089 } 8090 8091 return state->stack[spi].spilled_ptr.dynptr.type; 8092 } 8093 8094 static int check_func_arg(struct bpf_verifier_env *env, u32 arg, 8095 struct bpf_call_arg_meta *meta, 8096 const struct bpf_func_proto *fn, 8097 int insn_idx) 8098 { 8099 u32 regno = BPF_REG_1 + arg; 8100 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno]; 8101 enum bpf_arg_type arg_type = fn->arg_type[arg]; 8102 enum bpf_reg_type type = reg->type; 8103 u32 *arg_btf_id = NULL; 8104 int err = 0; 8105 8106 if (arg_type == ARG_DONTCARE) 8107 return 0; 8108 8109 err = check_reg_arg(env, regno, SRC_OP); 8110 if (err) 8111 return err; 8112 8113 if (arg_type == ARG_ANYTHING) { 8114 if (is_pointer_value(env, regno)) { 8115 verbose(env, "R%d leaks addr into helper function\n", 8116 regno); 8117 return -EACCES; 8118 } 8119 return 0; 8120 } 8121 8122 if (type_is_pkt_pointer(type) && 8123 !may_access_direct_pkt_data(env, meta, BPF_READ)) { 8124 verbose(env, "helper access to the packet is not allowed\n"); 8125 return -EACCES; 8126 } 8127 8128 if (base_type(arg_type) == ARG_PTR_TO_MAP_VALUE) { 8129 err = resolve_map_arg_type(env, meta, &arg_type); 8130 if (err) 8131 return err; 8132 } 8133 8134 if (register_is_null(reg) && type_may_be_null(arg_type)) 8135 /* A NULL register has a SCALAR_VALUE type, so skip 8136 * type checking. 8137 */ 8138 goto skip_type_check; 8139 8140 /* arg_btf_id and arg_size are in a union. */ 8141 if (base_type(arg_type) == ARG_PTR_TO_BTF_ID || 8142 base_type(arg_type) == ARG_PTR_TO_SPIN_LOCK) 8143 arg_btf_id = fn->arg_btf_id[arg]; 8144 8145 err = check_reg_type(env, regno, arg_type, arg_btf_id, meta); 8146 if (err) 8147 return err; 8148 8149 err = check_func_arg_reg_off(env, reg, regno, arg_type); 8150 if (err) 8151 return err; 8152 8153 skip_type_check: 8154 if (arg_type_is_release(arg_type)) { 8155 if (arg_type_is_dynptr(arg_type)) { 8156 struct bpf_func_state *state = func(env, reg); 8157 int spi; 8158 8159 /* Only dynptr created on stack can be released, thus 8160 * the get_spi and stack state checks for spilled_ptr 8161 * should only be done before process_dynptr_func for 8162 * PTR_TO_STACK. 8163 */ 8164 if (reg->type == PTR_TO_STACK) { 8165 spi = dynptr_get_spi(env, reg); 8166 if (spi < 0 || !state->stack[spi].spilled_ptr.ref_obj_id) { 8167 verbose(env, "arg %d is an unacquired reference\n", regno); 8168 return -EINVAL; 8169 } 8170 } else { 8171 verbose(env, "cannot release unowned const bpf_dynptr\n"); 8172 return -EINVAL; 8173 } 8174 } else if (!reg->ref_obj_id && !register_is_null(reg)) { 8175 verbose(env, "R%d must be referenced when passed to release function\n", 8176 regno); 8177 return -EINVAL; 8178 } 8179 if (meta->release_regno) { 8180 verbose(env, "verifier internal error: more than one release argument\n"); 8181 return -EFAULT; 8182 } 8183 meta->release_regno = regno; 8184 } 8185 8186 if (reg->ref_obj_id) { 8187 if (meta->ref_obj_id) { 8188 verbose(env, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n", 8189 regno, reg->ref_obj_id, 8190 meta->ref_obj_id); 8191 return -EFAULT; 8192 } 8193 meta->ref_obj_id = reg->ref_obj_id; 8194 } 8195 8196 switch (base_type(arg_type)) { 8197 case ARG_CONST_MAP_PTR: 8198 /* bpf_map_xxx(map_ptr) call: remember that map_ptr */ 8199 if (meta->map_ptr) { 8200 /* Use map_uid (which is unique id of inner map) to reject: 8201 * inner_map1 = bpf_map_lookup_elem(outer_map, key1) 8202 * inner_map2 = bpf_map_lookup_elem(outer_map, key2) 8203 * if (inner_map1 && inner_map2) { 8204 * timer = bpf_map_lookup_elem(inner_map1); 8205 * if (timer) 8206 * // mismatch would have been allowed 8207 * bpf_timer_init(timer, inner_map2); 8208 * } 8209 * 8210 * Comparing map_ptr is enough to distinguish normal and outer maps. 8211 */ 8212 if (meta->map_ptr != reg->map_ptr || 8213 meta->map_uid != reg->map_uid) { 8214 verbose(env, 8215 "timer pointer in R1 map_uid=%d doesn't match map pointer in R2 map_uid=%d\n", 8216 meta->map_uid, reg->map_uid); 8217 return -EINVAL; 8218 } 8219 } 8220 meta->map_ptr = reg->map_ptr; 8221 meta->map_uid = reg->map_uid; 8222 break; 8223 case ARG_PTR_TO_MAP_KEY: 8224 /* bpf_map_xxx(..., map_ptr, ..., key) call: 8225 * check that [key, key + map->key_size) are within 8226 * stack limits and initialized 8227 */ 8228 if (!meta->map_ptr) { 8229 /* in function declaration map_ptr must come before 8230 * map_key, so that it's verified and known before 8231 * we have to check map_key here. Otherwise it means 8232 * that kernel subsystem misconfigured verifier 8233 */ 8234 verbose(env, "invalid map_ptr to access map->key\n"); 8235 return -EACCES; 8236 } 8237 err = check_helper_mem_access(env, regno, 8238 meta->map_ptr->key_size, false, 8239 NULL); 8240 break; 8241 case ARG_PTR_TO_MAP_VALUE: 8242 if (type_may_be_null(arg_type) && register_is_null(reg)) 8243 return 0; 8244 8245 /* bpf_map_xxx(..., map_ptr, ..., value) call: 8246 * check [value, value + map->value_size) validity 8247 */ 8248 if (!meta->map_ptr) { 8249 /* kernel subsystem misconfigured verifier */ 8250 verbose(env, "invalid map_ptr to access map->value\n"); 8251 return -EACCES; 8252 } 8253 meta->raw_mode = arg_type & MEM_UNINIT; 8254 err = check_helper_mem_access(env, regno, 8255 meta->map_ptr->value_size, false, 8256 meta); 8257 break; 8258 case ARG_PTR_TO_PERCPU_BTF_ID: 8259 if (!reg->btf_id) { 8260 verbose(env, "Helper has invalid btf_id in R%d\n", regno); 8261 return -EACCES; 8262 } 8263 meta->ret_btf = reg->btf; 8264 meta->ret_btf_id = reg->btf_id; 8265 break; 8266 case ARG_PTR_TO_SPIN_LOCK: 8267 if (in_rbtree_lock_required_cb(env)) { 8268 verbose(env, "can't spin_{lock,unlock} in rbtree cb\n"); 8269 return -EACCES; 8270 } 8271 if (meta->func_id == BPF_FUNC_spin_lock) { 8272 err = process_spin_lock(env, regno, true); 8273 if (err) 8274 return err; 8275 } else if (meta->func_id == BPF_FUNC_spin_unlock) { 8276 err = process_spin_lock(env, regno, false); 8277 if (err) 8278 return err; 8279 } else { 8280 verbose(env, "verifier internal error\n"); 8281 return -EFAULT; 8282 } 8283 break; 8284 case ARG_PTR_TO_TIMER: 8285 err = process_timer_func(env, regno, meta); 8286 if (err) 8287 return err; 8288 break; 8289 case ARG_PTR_TO_FUNC: 8290 meta->subprogno = reg->subprogno; 8291 break; 8292 case ARG_PTR_TO_MEM: 8293 /* The access to this pointer is only checked when we hit the 8294 * next is_mem_size argument below. 8295 */ 8296 meta->raw_mode = arg_type & MEM_UNINIT; 8297 if (arg_type & MEM_FIXED_SIZE) { 8298 err = check_helper_mem_access(env, regno, 8299 fn->arg_size[arg], false, 8300 meta); 8301 } 8302 break; 8303 case ARG_CONST_SIZE: 8304 err = check_mem_size_reg(env, reg, regno, false, meta); 8305 break; 8306 case ARG_CONST_SIZE_OR_ZERO: 8307 err = check_mem_size_reg(env, reg, regno, true, meta); 8308 break; 8309 case ARG_PTR_TO_DYNPTR: 8310 err = process_dynptr_func(env, regno, insn_idx, arg_type, 0); 8311 if (err) 8312 return err; 8313 break; 8314 case ARG_CONST_ALLOC_SIZE_OR_ZERO: 8315 if (!tnum_is_const(reg->var_off)) { 8316 verbose(env, "R%d is not a known constant'\n", 8317 regno); 8318 return -EACCES; 8319 } 8320 meta->mem_size = reg->var_off.value; 8321 err = mark_chain_precision(env, regno); 8322 if (err) 8323 return err; 8324 break; 8325 case ARG_PTR_TO_INT: 8326 case ARG_PTR_TO_LONG: 8327 { 8328 int size = int_ptr_type_to_size(arg_type); 8329 8330 err = check_helper_mem_access(env, regno, size, false, meta); 8331 if (err) 8332 return err; 8333 err = check_ptr_alignment(env, reg, 0, size, true); 8334 break; 8335 } 8336 case ARG_PTR_TO_CONST_STR: 8337 { 8338 struct bpf_map *map = reg->map_ptr; 8339 int map_off; 8340 u64 map_addr; 8341 char *str_ptr; 8342 8343 if (!bpf_map_is_rdonly(map)) { 8344 verbose(env, "R%d does not point to a readonly map'\n", regno); 8345 return -EACCES; 8346 } 8347 8348 if (!tnum_is_const(reg->var_off)) { 8349 verbose(env, "R%d is not a constant address'\n", regno); 8350 return -EACCES; 8351 } 8352 8353 if (!map->ops->map_direct_value_addr) { 8354 verbose(env, "no direct value access support for this map type\n"); 8355 return -EACCES; 8356 } 8357 8358 err = check_map_access(env, regno, reg->off, 8359 map->value_size - reg->off, false, 8360 ACCESS_HELPER); 8361 if (err) 8362 return err; 8363 8364 map_off = reg->off + reg->var_off.value; 8365 err = map->ops->map_direct_value_addr(map, &map_addr, map_off); 8366 if (err) { 8367 verbose(env, "direct value access on string failed\n"); 8368 return err; 8369 } 8370 8371 str_ptr = (char *)(long)(map_addr); 8372 if (!strnchr(str_ptr + map_off, map->value_size - map_off, 0)) { 8373 verbose(env, "string is not zero-terminated\n"); 8374 return -EINVAL; 8375 } 8376 break; 8377 } 8378 case ARG_PTR_TO_KPTR: 8379 err = process_kptr_func(env, regno, meta); 8380 if (err) 8381 return err; 8382 break; 8383 } 8384 8385 return err; 8386 } 8387 8388 static bool may_update_sockmap(struct bpf_verifier_env *env, int func_id) 8389 { 8390 enum bpf_attach_type eatype = env->prog->expected_attach_type; 8391 enum bpf_prog_type type = resolve_prog_type(env->prog); 8392 8393 if (func_id != BPF_FUNC_map_update_elem) 8394 return false; 8395 8396 /* It's not possible to get access to a locked struct sock in these 8397 * contexts, so updating is safe. 8398 */ 8399 switch (type) { 8400 case BPF_PROG_TYPE_TRACING: 8401 if (eatype == BPF_TRACE_ITER) 8402 return true; 8403 break; 8404 case BPF_PROG_TYPE_SOCKET_FILTER: 8405 case BPF_PROG_TYPE_SCHED_CLS: 8406 case BPF_PROG_TYPE_SCHED_ACT: 8407 case BPF_PROG_TYPE_XDP: 8408 case BPF_PROG_TYPE_SK_REUSEPORT: 8409 case BPF_PROG_TYPE_FLOW_DISSECTOR: 8410 case BPF_PROG_TYPE_SK_LOOKUP: 8411 return true; 8412 default: 8413 break; 8414 } 8415 8416 verbose(env, "cannot update sockmap in this context\n"); 8417 return false; 8418 } 8419 8420 static bool allow_tail_call_in_subprogs(struct bpf_verifier_env *env) 8421 { 8422 return env->prog->jit_requested && 8423 bpf_jit_supports_subprog_tailcalls(); 8424 } 8425 8426 static int check_map_func_compatibility(struct bpf_verifier_env *env, 8427 struct bpf_map *map, int func_id) 8428 { 8429 if (!map) 8430 return 0; 8431 8432 /* We need a two way check, first is from map perspective ... */ 8433 switch (map->map_type) { 8434 case BPF_MAP_TYPE_PROG_ARRAY: 8435 if (func_id != BPF_FUNC_tail_call) 8436 goto error; 8437 break; 8438 case BPF_MAP_TYPE_PERF_EVENT_ARRAY: 8439 if (func_id != BPF_FUNC_perf_event_read && 8440 func_id != BPF_FUNC_perf_event_output && 8441 func_id != BPF_FUNC_skb_output && 8442 func_id != BPF_FUNC_perf_event_read_value && 8443 func_id != BPF_FUNC_xdp_output) 8444 goto error; 8445 break; 8446 case BPF_MAP_TYPE_RINGBUF: 8447 if (func_id != BPF_FUNC_ringbuf_output && 8448 func_id != BPF_FUNC_ringbuf_reserve && 8449 func_id != BPF_FUNC_ringbuf_query && 8450 func_id != BPF_FUNC_ringbuf_reserve_dynptr && 8451 func_id != BPF_FUNC_ringbuf_submit_dynptr && 8452 func_id != BPF_FUNC_ringbuf_discard_dynptr) 8453 goto error; 8454 break; 8455 case BPF_MAP_TYPE_USER_RINGBUF: 8456 if (func_id != BPF_FUNC_user_ringbuf_drain) 8457 goto error; 8458 break; 8459 case BPF_MAP_TYPE_STACK_TRACE: 8460 if (func_id != BPF_FUNC_get_stackid) 8461 goto error; 8462 break; 8463 case BPF_MAP_TYPE_CGROUP_ARRAY: 8464 if (func_id != BPF_FUNC_skb_under_cgroup && 8465 func_id != BPF_FUNC_current_task_under_cgroup) 8466 goto error; 8467 break; 8468 case BPF_MAP_TYPE_CGROUP_STORAGE: 8469 case BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE: 8470 if (func_id != BPF_FUNC_get_local_storage) 8471 goto error; 8472 break; 8473 case BPF_MAP_TYPE_DEVMAP: 8474 case BPF_MAP_TYPE_DEVMAP_HASH: 8475 if (func_id != BPF_FUNC_redirect_map && 8476 func_id != BPF_FUNC_map_lookup_elem) 8477 goto error; 8478 break; 8479 /* Restrict bpf side of cpumap and xskmap, open when use-cases 8480 * appear. 8481 */ 8482 case BPF_MAP_TYPE_CPUMAP: 8483 if (func_id != BPF_FUNC_redirect_map) 8484 goto error; 8485 break; 8486 case BPF_MAP_TYPE_XSKMAP: 8487 if (func_id != BPF_FUNC_redirect_map && 8488 func_id != BPF_FUNC_map_lookup_elem) 8489 goto error; 8490 break; 8491 case BPF_MAP_TYPE_ARRAY_OF_MAPS: 8492 case BPF_MAP_TYPE_HASH_OF_MAPS: 8493 if (func_id != BPF_FUNC_map_lookup_elem) 8494 goto error; 8495 break; 8496 case BPF_MAP_TYPE_SOCKMAP: 8497 if (func_id != BPF_FUNC_sk_redirect_map && 8498 func_id != BPF_FUNC_sock_map_update && 8499 func_id != BPF_FUNC_map_delete_elem && 8500 func_id != BPF_FUNC_msg_redirect_map && 8501 func_id != BPF_FUNC_sk_select_reuseport && 8502 func_id != BPF_FUNC_map_lookup_elem && 8503 !may_update_sockmap(env, func_id)) 8504 goto error; 8505 break; 8506 case BPF_MAP_TYPE_SOCKHASH: 8507 if (func_id != BPF_FUNC_sk_redirect_hash && 8508 func_id != BPF_FUNC_sock_hash_update && 8509 func_id != BPF_FUNC_map_delete_elem && 8510 func_id != BPF_FUNC_msg_redirect_hash && 8511 func_id != BPF_FUNC_sk_select_reuseport && 8512 func_id != BPF_FUNC_map_lookup_elem && 8513 !may_update_sockmap(env, func_id)) 8514 goto error; 8515 break; 8516 case BPF_MAP_TYPE_REUSEPORT_SOCKARRAY: 8517 if (func_id != BPF_FUNC_sk_select_reuseport) 8518 goto error; 8519 break; 8520 case BPF_MAP_TYPE_QUEUE: 8521 case BPF_MAP_TYPE_STACK: 8522 if (func_id != BPF_FUNC_map_peek_elem && 8523 func_id != BPF_FUNC_map_pop_elem && 8524 func_id != BPF_FUNC_map_push_elem) 8525 goto error; 8526 break; 8527 case BPF_MAP_TYPE_SK_STORAGE: 8528 if (func_id != BPF_FUNC_sk_storage_get && 8529 func_id != BPF_FUNC_sk_storage_delete && 8530 func_id != BPF_FUNC_kptr_xchg) 8531 goto error; 8532 break; 8533 case BPF_MAP_TYPE_INODE_STORAGE: 8534 if (func_id != BPF_FUNC_inode_storage_get && 8535 func_id != BPF_FUNC_inode_storage_delete && 8536 func_id != BPF_FUNC_kptr_xchg) 8537 goto error; 8538 break; 8539 case BPF_MAP_TYPE_TASK_STORAGE: 8540 if (func_id != BPF_FUNC_task_storage_get && 8541 func_id != BPF_FUNC_task_storage_delete && 8542 func_id != BPF_FUNC_kptr_xchg) 8543 goto error; 8544 break; 8545 case BPF_MAP_TYPE_CGRP_STORAGE: 8546 if (func_id != BPF_FUNC_cgrp_storage_get && 8547 func_id != BPF_FUNC_cgrp_storage_delete && 8548 func_id != BPF_FUNC_kptr_xchg) 8549 goto error; 8550 break; 8551 case BPF_MAP_TYPE_BLOOM_FILTER: 8552 if (func_id != BPF_FUNC_map_peek_elem && 8553 func_id != BPF_FUNC_map_push_elem) 8554 goto error; 8555 break; 8556 default: 8557 break; 8558 } 8559 8560 /* ... and second from the function itself. */ 8561 switch (func_id) { 8562 case BPF_FUNC_tail_call: 8563 if (map->map_type != BPF_MAP_TYPE_PROG_ARRAY) 8564 goto error; 8565 if (env->subprog_cnt > 1 && !allow_tail_call_in_subprogs(env)) { 8566 verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n"); 8567 return -EINVAL; 8568 } 8569 break; 8570 case BPF_FUNC_perf_event_read: 8571 case BPF_FUNC_perf_event_output: 8572 case BPF_FUNC_perf_event_read_value: 8573 case BPF_FUNC_skb_output: 8574 case BPF_FUNC_xdp_output: 8575 if (map->map_type != BPF_MAP_TYPE_PERF_EVENT_ARRAY) 8576 goto error; 8577 break; 8578 case BPF_FUNC_ringbuf_output: 8579 case BPF_FUNC_ringbuf_reserve: 8580 case BPF_FUNC_ringbuf_query: 8581 case BPF_FUNC_ringbuf_reserve_dynptr: 8582 case BPF_FUNC_ringbuf_submit_dynptr: 8583 case BPF_FUNC_ringbuf_discard_dynptr: 8584 if (map->map_type != BPF_MAP_TYPE_RINGBUF) 8585 goto error; 8586 break; 8587 case BPF_FUNC_user_ringbuf_drain: 8588 if (map->map_type != BPF_MAP_TYPE_USER_RINGBUF) 8589 goto error; 8590 break; 8591 case BPF_FUNC_get_stackid: 8592 if (map->map_type != BPF_MAP_TYPE_STACK_TRACE) 8593 goto error; 8594 break; 8595 case BPF_FUNC_current_task_under_cgroup: 8596 case BPF_FUNC_skb_under_cgroup: 8597 if (map->map_type != BPF_MAP_TYPE_CGROUP_ARRAY) 8598 goto error; 8599 break; 8600 case BPF_FUNC_redirect_map: 8601 if (map->map_type != BPF_MAP_TYPE_DEVMAP && 8602 map->map_type != BPF_MAP_TYPE_DEVMAP_HASH && 8603 map->map_type != BPF_MAP_TYPE_CPUMAP && 8604 map->map_type != BPF_MAP_TYPE_XSKMAP) 8605 goto error; 8606 break; 8607 case BPF_FUNC_sk_redirect_map: 8608 case BPF_FUNC_msg_redirect_map: 8609 case BPF_FUNC_sock_map_update: 8610 if (map->map_type != BPF_MAP_TYPE_SOCKMAP) 8611 goto error; 8612 break; 8613 case BPF_FUNC_sk_redirect_hash: 8614 case BPF_FUNC_msg_redirect_hash: 8615 case BPF_FUNC_sock_hash_update: 8616 if (map->map_type != BPF_MAP_TYPE_SOCKHASH) 8617 goto error; 8618 break; 8619 case BPF_FUNC_get_local_storage: 8620 if (map->map_type != BPF_MAP_TYPE_CGROUP_STORAGE && 8621 map->map_type != BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE) 8622 goto error; 8623 break; 8624 case BPF_FUNC_sk_select_reuseport: 8625 if (map->map_type != BPF_MAP_TYPE_REUSEPORT_SOCKARRAY && 8626 map->map_type != BPF_MAP_TYPE_SOCKMAP && 8627 map->map_type != BPF_MAP_TYPE_SOCKHASH) 8628 goto error; 8629 break; 8630 case BPF_FUNC_map_pop_elem: 8631 if (map->map_type != BPF_MAP_TYPE_QUEUE && 8632 map->map_type != BPF_MAP_TYPE_STACK) 8633 goto error; 8634 break; 8635 case BPF_FUNC_map_peek_elem: 8636 case BPF_FUNC_map_push_elem: 8637 if (map->map_type != BPF_MAP_TYPE_QUEUE && 8638 map->map_type != BPF_MAP_TYPE_STACK && 8639 map->map_type != BPF_MAP_TYPE_BLOOM_FILTER) 8640 goto error; 8641 break; 8642 case BPF_FUNC_map_lookup_percpu_elem: 8643 if (map->map_type != BPF_MAP_TYPE_PERCPU_ARRAY && 8644 map->map_type != BPF_MAP_TYPE_PERCPU_HASH && 8645 map->map_type != BPF_MAP_TYPE_LRU_PERCPU_HASH) 8646 goto error; 8647 break; 8648 case BPF_FUNC_sk_storage_get: 8649 case BPF_FUNC_sk_storage_delete: 8650 if (map->map_type != BPF_MAP_TYPE_SK_STORAGE) 8651 goto error; 8652 break; 8653 case BPF_FUNC_inode_storage_get: 8654 case BPF_FUNC_inode_storage_delete: 8655 if (map->map_type != BPF_MAP_TYPE_INODE_STORAGE) 8656 goto error; 8657 break; 8658 case BPF_FUNC_task_storage_get: 8659 case BPF_FUNC_task_storage_delete: 8660 if (map->map_type != BPF_MAP_TYPE_TASK_STORAGE) 8661 goto error; 8662 break; 8663 case BPF_FUNC_cgrp_storage_get: 8664 case BPF_FUNC_cgrp_storage_delete: 8665 if (map->map_type != BPF_MAP_TYPE_CGRP_STORAGE) 8666 goto error; 8667 break; 8668 default: 8669 break; 8670 } 8671 8672 return 0; 8673 error: 8674 verbose(env, "cannot pass map_type %d into func %s#%d\n", 8675 map->map_type, func_id_name(func_id), func_id); 8676 return -EINVAL; 8677 } 8678 8679 static bool check_raw_mode_ok(const struct bpf_func_proto *fn) 8680 { 8681 int count = 0; 8682 8683 if (fn->arg1_type == ARG_PTR_TO_UNINIT_MEM) 8684 count++; 8685 if (fn->arg2_type == ARG_PTR_TO_UNINIT_MEM) 8686 count++; 8687 if (fn->arg3_type == ARG_PTR_TO_UNINIT_MEM) 8688 count++; 8689 if (fn->arg4_type == ARG_PTR_TO_UNINIT_MEM) 8690 count++; 8691 if (fn->arg5_type == ARG_PTR_TO_UNINIT_MEM) 8692 count++; 8693 8694 /* We only support one arg being in raw mode at the moment, 8695 * which is sufficient for the helper functions we have 8696 * right now. 8697 */ 8698 return count <= 1; 8699 } 8700 8701 static bool check_args_pair_invalid(const struct bpf_func_proto *fn, int arg) 8702 { 8703 bool is_fixed = fn->arg_type[arg] & MEM_FIXED_SIZE; 8704 bool has_size = fn->arg_size[arg] != 0; 8705 bool is_next_size = false; 8706 8707 if (arg + 1 < ARRAY_SIZE(fn->arg_type)) 8708 is_next_size = arg_type_is_mem_size(fn->arg_type[arg + 1]); 8709 8710 if (base_type(fn->arg_type[arg]) != ARG_PTR_TO_MEM) 8711 return is_next_size; 8712 8713 return has_size == is_next_size || is_next_size == is_fixed; 8714 } 8715 8716 static bool check_arg_pair_ok(const struct bpf_func_proto *fn) 8717 { 8718 /* bpf_xxx(..., buf, len) call will access 'len' 8719 * bytes from memory 'buf'. Both arg types need 8720 * to be paired, so make sure there's no buggy 8721 * helper function specification. 8722 */ 8723 if (arg_type_is_mem_size(fn->arg1_type) || 8724 check_args_pair_invalid(fn, 0) || 8725 check_args_pair_invalid(fn, 1) || 8726 check_args_pair_invalid(fn, 2) || 8727 check_args_pair_invalid(fn, 3) || 8728 check_args_pair_invalid(fn, 4)) 8729 return false; 8730 8731 return true; 8732 } 8733 8734 static bool check_btf_id_ok(const struct bpf_func_proto *fn) 8735 { 8736 int i; 8737 8738 for (i = 0; i < ARRAY_SIZE(fn->arg_type); i++) { 8739 if (base_type(fn->arg_type[i]) == ARG_PTR_TO_BTF_ID) 8740 return !!fn->arg_btf_id[i]; 8741 if (base_type(fn->arg_type[i]) == ARG_PTR_TO_SPIN_LOCK) 8742 return fn->arg_btf_id[i] == BPF_PTR_POISON; 8743 if (base_type(fn->arg_type[i]) != ARG_PTR_TO_BTF_ID && fn->arg_btf_id[i] && 8744 /* arg_btf_id and arg_size are in a union. */ 8745 (base_type(fn->arg_type[i]) != ARG_PTR_TO_MEM || 8746 !(fn->arg_type[i] & MEM_FIXED_SIZE))) 8747 return false; 8748 } 8749 8750 return true; 8751 } 8752 8753 static int check_func_proto(const struct bpf_func_proto *fn, int func_id) 8754 { 8755 return check_raw_mode_ok(fn) && 8756 check_arg_pair_ok(fn) && 8757 check_btf_id_ok(fn) ? 0 : -EINVAL; 8758 } 8759 8760 /* Packet data might have moved, any old PTR_TO_PACKET[_META,_END] 8761 * are now invalid, so turn them into unknown SCALAR_VALUE. 8762 * 8763 * This also applies to dynptr slices belonging to skb and xdp dynptrs, 8764 * since these slices point to packet data. 8765 */ 8766 static void clear_all_pkt_pointers(struct bpf_verifier_env *env) 8767 { 8768 struct bpf_func_state *state; 8769 struct bpf_reg_state *reg; 8770 8771 bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({ 8772 if (reg_is_pkt_pointer_any(reg) || reg_is_dynptr_slice_pkt(reg)) 8773 mark_reg_invalid(env, reg); 8774 })); 8775 } 8776 8777 enum { 8778 AT_PKT_END = -1, 8779 BEYOND_PKT_END = -2, 8780 }; 8781 8782 static void mark_pkt_end(struct bpf_verifier_state *vstate, int regn, bool range_open) 8783 { 8784 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 8785 struct bpf_reg_state *reg = &state->regs[regn]; 8786 8787 if (reg->type != PTR_TO_PACKET) 8788 /* PTR_TO_PACKET_META is not supported yet */ 8789 return; 8790 8791 /* The 'reg' is pkt > pkt_end or pkt >= pkt_end. 8792 * How far beyond pkt_end it goes is unknown. 8793 * if (!range_open) it's the case of pkt >= pkt_end 8794 * if (range_open) it's the case of pkt > pkt_end 8795 * hence this pointer is at least 1 byte bigger than pkt_end 8796 */ 8797 if (range_open) 8798 reg->range = BEYOND_PKT_END; 8799 else 8800 reg->range = AT_PKT_END; 8801 } 8802 8803 /* The pointer with the specified id has released its reference to kernel 8804 * resources. Identify all copies of the same pointer and clear the reference. 8805 */ 8806 static int release_reference(struct bpf_verifier_env *env, 8807 int ref_obj_id) 8808 { 8809 struct bpf_func_state *state; 8810 struct bpf_reg_state *reg; 8811 int err; 8812 8813 err = release_reference_state(cur_func(env), ref_obj_id); 8814 if (err) 8815 return err; 8816 8817 bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({ 8818 if (reg->ref_obj_id == ref_obj_id) 8819 mark_reg_invalid(env, reg); 8820 })); 8821 8822 return 0; 8823 } 8824 8825 static void invalidate_non_owning_refs(struct bpf_verifier_env *env) 8826 { 8827 struct bpf_func_state *unused; 8828 struct bpf_reg_state *reg; 8829 8830 bpf_for_each_reg_in_vstate(env->cur_state, unused, reg, ({ 8831 if (type_is_non_owning_ref(reg->type)) 8832 mark_reg_invalid(env, reg); 8833 })); 8834 } 8835 8836 static void clear_caller_saved_regs(struct bpf_verifier_env *env, 8837 struct bpf_reg_state *regs) 8838 { 8839 int i; 8840 8841 /* after the call registers r0 - r5 were scratched */ 8842 for (i = 0; i < CALLER_SAVED_REGS; i++) { 8843 mark_reg_not_init(env, regs, caller_saved[i]); 8844 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK); 8845 } 8846 } 8847 8848 typedef int (*set_callee_state_fn)(struct bpf_verifier_env *env, 8849 struct bpf_func_state *caller, 8850 struct bpf_func_state *callee, 8851 int insn_idx); 8852 8853 static int set_callee_state(struct bpf_verifier_env *env, 8854 struct bpf_func_state *caller, 8855 struct bpf_func_state *callee, int insn_idx); 8856 8857 static int __check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn, 8858 int *insn_idx, int subprog, 8859 set_callee_state_fn set_callee_state_cb) 8860 { 8861 struct bpf_verifier_state *state = env->cur_state; 8862 struct bpf_func_state *caller, *callee; 8863 int err; 8864 8865 if (state->curframe + 1 >= MAX_CALL_FRAMES) { 8866 verbose(env, "the call stack of %d frames is too deep\n", 8867 state->curframe + 2); 8868 return -E2BIG; 8869 } 8870 8871 caller = state->frame[state->curframe]; 8872 if (state->frame[state->curframe + 1]) { 8873 verbose(env, "verifier bug. Frame %d already allocated\n", 8874 state->curframe + 1); 8875 return -EFAULT; 8876 } 8877 8878 err = btf_check_subprog_call(env, subprog, caller->regs); 8879 if (err == -EFAULT) 8880 return err; 8881 if (subprog_is_global(env, subprog)) { 8882 if (err) { 8883 verbose(env, "Caller passes invalid args into func#%d\n", 8884 subprog); 8885 return err; 8886 } else { 8887 if (env->log.level & BPF_LOG_LEVEL) 8888 verbose(env, 8889 "Func#%d is global and valid. Skipping.\n", 8890 subprog); 8891 clear_caller_saved_regs(env, caller->regs); 8892 8893 /* All global functions return a 64-bit SCALAR_VALUE */ 8894 mark_reg_unknown(env, caller->regs, BPF_REG_0); 8895 caller->regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG; 8896 8897 /* continue with next insn after call */ 8898 return 0; 8899 } 8900 } 8901 8902 /* set_callee_state is used for direct subprog calls, but we are 8903 * interested in validating only BPF helpers that can call subprogs as 8904 * callbacks 8905 */ 8906 if (set_callee_state_cb != set_callee_state) { 8907 if (bpf_pseudo_kfunc_call(insn) && 8908 !is_callback_calling_kfunc(insn->imm)) { 8909 verbose(env, "verifier bug: kfunc %s#%d not marked as callback-calling\n", 8910 func_id_name(insn->imm), insn->imm); 8911 return -EFAULT; 8912 } else if (!bpf_pseudo_kfunc_call(insn) && 8913 !is_callback_calling_function(insn->imm)) { /* helper */ 8914 verbose(env, "verifier bug: helper %s#%d not marked as callback-calling\n", 8915 func_id_name(insn->imm), insn->imm); 8916 return -EFAULT; 8917 } 8918 } 8919 8920 if (insn->code == (BPF_JMP | BPF_CALL) && 8921 insn->src_reg == 0 && 8922 insn->imm == BPF_FUNC_timer_set_callback) { 8923 struct bpf_verifier_state *async_cb; 8924 8925 /* there is no real recursion here. timer callbacks are async */ 8926 env->subprog_info[subprog].is_async_cb = true; 8927 async_cb = push_async_cb(env, env->subprog_info[subprog].start, 8928 *insn_idx, subprog); 8929 if (!async_cb) 8930 return -EFAULT; 8931 callee = async_cb->frame[0]; 8932 callee->async_entry_cnt = caller->async_entry_cnt + 1; 8933 8934 /* Convert bpf_timer_set_callback() args into timer callback args */ 8935 err = set_callee_state_cb(env, caller, callee, *insn_idx); 8936 if (err) 8937 return err; 8938 8939 clear_caller_saved_regs(env, caller->regs); 8940 mark_reg_unknown(env, caller->regs, BPF_REG_0); 8941 caller->regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG; 8942 /* continue with next insn after call */ 8943 return 0; 8944 } 8945 8946 callee = kzalloc(sizeof(*callee), GFP_KERNEL); 8947 if (!callee) 8948 return -ENOMEM; 8949 state->frame[state->curframe + 1] = callee; 8950 8951 /* callee cannot access r0, r6 - r9 for reading and has to write 8952 * into its own stack before reading from it. 8953 * callee can read/write into caller's stack 8954 */ 8955 init_func_state(env, callee, 8956 /* remember the callsite, it will be used by bpf_exit */ 8957 *insn_idx /* callsite */, 8958 state->curframe + 1 /* frameno within this callchain */, 8959 subprog /* subprog number within this prog */); 8960 8961 /* Transfer references to the callee */ 8962 err = copy_reference_state(callee, caller); 8963 if (err) 8964 goto err_out; 8965 8966 err = set_callee_state_cb(env, caller, callee, *insn_idx); 8967 if (err) 8968 goto err_out; 8969 8970 clear_caller_saved_regs(env, caller->regs); 8971 8972 /* only increment it after check_reg_arg() finished */ 8973 state->curframe++; 8974 8975 /* and go analyze first insn of the callee */ 8976 *insn_idx = env->subprog_info[subprog].start - 1; 8977 8978 if (env->log.level & BPF_LOG_LEVEL) { 8979 verbose(env, "caller:\n"); 8980 print_verifier_state(env, caller, true); 8981 verbose(env, "callee:\n"); 8982 print_verifier_state(env, callee, true); 8983 } 8984 return 0; 8985 8986 err_out: 8987 free_func_state(callee); 8988 state->frame[state->curframe + 1] = NULL; 8989 return err; 8990 } 8991 8992 int map_set_for_each_callback_args(struct bpf_verifier_env *env, 8993 struct bpf_func_state *caller, 8994 struct bpf_func_state *callee) 8995 { 8996 /* bpf_for_each_map_elem(struct bpf_map *map, void *callback_fn, 8997 * void *callback_ctx, u64 flags); 8998 * callback_fn(struct bpf_map *map, void *key, void *value, 8999 * void *callback_ctx); 9000 */ 9001 callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1]; 9002 9003 callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY; 9004 __mark_reg_known_zero(&callee->regs[BPF_REG_2]); 9005 callee->regs[BPF_REG_2].map_ptr = caller->regs[BPF_REG_1].map_ptr; 9006 9007 callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE; 9008 __mark_reg_known_zero(&callee->regs[BPF_REG_3]); 9009 callee->regs[BPF_REG_3].map_ptr = caller->regs[BPF_REG_1].map_ptr; 9010 9011 /* pointer to stack or null */ 9012 callee->regs[BPF_REG_4] = caller->regs[BPF_REG_3]; 9013 9014 /* unused */ 9015 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]); 9016 return 0; 9017 } 9018 9019 static int set_callee_state(struct bpf_verifier_env *env, 9020 struct bpf_func_state *caller, 9021 struct bpf_func_state *callee, int insn_idx) 9022 { 9023 int i; 9024 9025 /* copy r1 - r5 args that callee can access. The copy includes parent 9026 * pointers, which connects us up to the liveness chain 9027 */ 9028 for (i = BPF_REG_1; i <= BPF_REG_5; i++) 9029 callee->regs[i] = caller->regs[i]; 9030 return 0; 9031 } 9032 9033 static int check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn, 9034 int *insn_idx) 9035 { 9036 int subprog, target_insn; 9037 9038 target_insn = *insn_idx + insn->imm + 1; 9039 subprog = find_subprog(env, target_insn); 9040 if (subprog < 0) { 9041 verbose(env, "verifier bug. No program starts at insn %d\n", 9042 target_insn); 9043 return -EFAULT; 9044 } 9045 9046 return __check_func_call(env, insn, insn_idx, subprog, set_callee_state); 9047 } 9048 9049 static int set_map_elem_callback_state(struct bpf_verifier_env *env, 9050 struct bpf_func_state *caller, 9051 struct bpf_func_state *callee, 9052 int insn_idx) 9053 { 9054 struct bpf_insn_aux_data *insn_aux = &env->insn_aux_data[insn_idx]; 9055 struct bpf_map *map; 9056 int err; 9057 9058 if (bpf_map_ptr_poisoned(insn_aux)) { 9059 verbose(env, "tail_call abusing map_ptr\n"); 9060 return -EINVAL; 9061 } 9062 9063 map = BPF_MAP_PTR(insn_aux->map_ptr_state); 9064 if (!map->ops->map_set_for_each_callback_args || 9065 !map->ops->map_for_each_callback) { 9066 verbose(env, "callback function not allowed for map\n"); 9067 return -ENOTSUPP; 9068 } 9069 9070 err = map->ops->map_set_for_each_callback_args(env, caller, callee); 9071 if (err) 9072 return err; 9073 9074 callee->in_callback_fn = true; 9075 callee->callback_ret_range = tnum_range(0, 1); 9076 return 0; 9077 } 9078 9079 static int set_loop_callback_state(struct bpf_verifier_env *env, 9080 struct bpf_func_state *caller, 9081 struct bpf_func_state *callee, 9082 int insn_idx) 9083 { 9084 /* bpf_loop(u32 nr_loops, void *callback_fn, void *callback_ctx, 9085 * u64 flags); 9086 * callback_fn(u32 index, void *callback_ctx); 9087 */ 9088 callee->regs[BPF_REG_1].type = SCALAR_VALUE; 9089 callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3]; 9090 9091 /* unused */ 9092 __mark_reg_not_init(env, &callee->regs[BPF_REG_3]); 9093 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]); 9094 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]); 9095 9096 callee->in_callback_fn = true; 9097 callee->callback_ret_range = tnum_range(0, 1); 9098 return 0; 9099 } 9100 9101 static int set_timer_callback_state(struct bpf_verifier_env *env, 9102 struct bpf_func_state *caller, 9103 struct bpf_func_state *callee, 9104 int insn_idx) 9105 { 9106 struct bpf_map *map_ptr = caller->regs[BPF_REG_1].map_ptr; 9107 9108 /* bpf_timer_set_callback(struct bpf_timer *timer, void *callback_fn); 9109 * callback_fn(struct bpf_map *map, void *key, void *value); 9110 */ 9111 callee->regs[BPF_REG_1].type = CONST_PTR_TO_MAP; 9112 __mark_reg_known_zero(&callee->regs[BPF_REG_1]); 9113 callee->regs[BPF_REG_1].map_ptr = map_ptr; 9114 9115 callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY; 9116 __mark_reg_known_zero(&callee->regs[BPF_REG_2]); 9117 callee->regs[BPF_REG_2].map_ptr = map_ptr; 9118 9119 callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE; 9120 __mark_reg_known_zero(&callee->regs[BPF_REG_3]); 9121 callee->regs[BPF_REG_3].map_ptr = map_ptr; 9122 9123 /* unused */ 9124 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]); 9125 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]); 9126 callee->in_async_callback_fn = true; 9127 callee->callback_ret_range = tnum_range(0, 1); 9128 return 0; 9129 } 9130 9131 static int set_find_vma_callback_state(struct bpf_verifier_env *env, 9132 struct bpf_func_state *caller, 9133 struct bpf_func_state *callee, 9134 int insn_idx) 9135 { 9136 /* bpf_find_vma(struct task_struct *task, u64 addr, 9137 * void *callback_fn, void *callback_ctx, u64 flags) 9138 * (callback_fn)(struct task_struct *task, 9139 * struct vm_area_struct *vma, void *callback_ctx); 9140 */ 9141 callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1]; 9142 9143 callee->regs[BPF_REG_2].type = PTR_TO_BTF_ID; 9144 __mark_reg_known_zero(&callee->regs[BPF_REG_2]); 9145 callee->regs[BPF_REG_2].btf = btf_vmlinux; 9146 callee->regs[BPF_REG_2].btf_id = btf_tracing_ids[BTF_TRACING_TYPE_VMA], 9147 9148 /* pointer to stack or null */ 9149 callee->regs[BPF_REG_3] = caller->regs[BPF_REG_4]; 9150 9151 /* unused */ 9152 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]); 9153 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]); 9154 callee->in_callback_fn = true; 9155 callee->callback_ret_range = tnum_range(0, 1); 9156 return 0; 9157 } 9158 9159 static int set_user_ringbuf_callback_state(struct bpf_verifier_env *env, 9160 struct bpf_func_state *caller, 9161 struct bpf_func_state *callee, 9162 int insn_idx) 9163 { 9164 /* bpf_user_ringbuf_drain(struct bpf_map *map, void *callback_fn, void 9165 * callback_ctx, u64 flags); 9166 * callback_fn(const struct bpf_dynptr_t* dynptr, void *callback_ctx); 9167 */ 9168 __mark_reg_not_init(env, &callee->regs[BPF_REG_0]); 9169 mark_dynptr_cb_reg(env, &callee->regs[BPF_REG_1], BPF_DYNPTR_TYPE_LOCAL); 9170 callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3]; 9171 9172 /* unused */ 9173 __mark_reg_not_init(env, &callee->regs[BPF_REG_3]); 9174 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]); 9175 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]); 9176 9177 callee->in_callback_fn = true; 9178 callee->callback_ret_range = tnum_range(0, 1); 9179 return 0; 9180 } 9181 9182 static int set_rbtree_add_callback_state(struct bpf_verifier_env *env, 9183 struct bpf_func_state *caller, 9184 struct bpf_func_state *callee, 9185 int insn_idx) 9186 { 9187 /* void bpf_rbtree_add_impl(struct bpf_rb_root *root, struct bpf_rb_node *node, 9188 * bool (less)(struct bpf_rb_node *a, const struct bpf_rb_node *b)); 9189 * 9190 * 'struct bpf_rb_node *node' arg to bpf_rbtree_add_impl is the same PTR_TO_BTF_ID w/ offset 9191 * that 'less' callback args will be receiving. However, 'node' arg was release_reference'd 9192 * by this point, so look at 'root' 9193 */ 9194 struct btf_field *field; 9195 9196 field = reg_find_field_offset(&caller->regs[BPF_REG_1], caller->regs[BPF_REG_1].off, 9197 BPF_RB_ROOT); 9198 if (!field || !field->graph_root.value_btf_id) 9199 return -EFAULT; 9200 9201 mark_reg_graph_node(callee->regs, BPF_REG_1, &field->graph_root); 9202 ref_set_non_owning(env, &callee->regs[BPF_REG_1]); 9203 mark_reg_graph_node(callee->regs, BPF_REG_2, &field->graph_root); 9204 ref_set_non_owning(env, &callee->regs[BPF_REG_2]); 9205 9206 __mark_reg_not_init(env, &callee->regs[BPF_REG_3]); 9207 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]); 9208 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]); 9209 callee->in_callback_fn = true; 9210 callee->callback_ret_range = tnum_range(0, 1); 9211 return 0; 9212 } 9213 9214 static bool is_rbtree_lock_required_kfunc(u32 btf_id); 9215 9216 /* Are we currently verifying the callback for a rbtree helper that must 9217 * be called with lock held? If so, no need to complain about unreleased 9218 * lock 9219 */ 9220 static bool in_rbtree_lock_required_cb(struct bpf_verifier_env *env) 9221 { 9222 struct bpf_verifier_state *state = env->cur_state; 9223 struct bpf_insn *insn = env->prog->insnsi; 9224 struct bpf_func_state *callee; 9225 int kfunc_btf_id; 9226 9227 if (!state->curframe) 9228 return false; 9229 9230 callee = state->frame[state->curframe]; 9231 9232 if (!callee->in_callback_fn) 9233 return false; 9234 9235 kfunc_btf_id = insn[callee->callsite].imm; 9236 return is_rbtree_lock_required_kfunc(kfunc_btf_id); 9237 } 9238 9239 static int prepare_func_exit(struct bpf_verifier_env *env, int *insn_idx) 9240 { 9241 struct bpf_verifier_state *state = env->cur_state; 9242 struct bpf_func_state *caller, *callee; 9243 struct bpf_reg_state *r0; 9244 int err; 9245 9246 callee = state->frame[state->curframe]; 9247 r0 = &callee->regs[BPF_REG_0]; 9248 if (r0->type == PTR_TO_STACK) { 9249 /* technically it's ok to return caller's stack pointer 9250 * (or caller's caller's pointer) back to the caller, 9251 * since these pointers are valid. Only current stack 9252 * pointer will be invalid as soon as function exits, 9253 * but let's be conservative 9254 */ 9255 verbose(env, "cannot return stack pointer to the caller\n"); 9256 return -EINVAL; 9257 } 9258 9259 caller = state->frame[state->curframe - 1]; 9260 if (callee->in_callback_fn) { 9261 /* enforce R0 return value range [0, 1]. */ 9262 struct tnum range = callee->callback_ret_range; 9263 9264 if (r0->type != SCALAR_VALUE) { 9265 verbose(env, "R0 not a scalar value\n"); 9266 return -EACCES; 9267 } 9268 9269 /* we are going to rely on register's precise value */ 9270 err = mark_reg_read(env, r0, r0->parent, REG_LIVE_READ64); 9271 err = err ?: mark_chain_precision(env, BPF_REG_0); 9272 if (err) 9273 return err; 9274 9275 if (!tnum_in(range, r0->var_off)) { 9276 verbose_invalid_scalar(env, r0, &range, "callback return", "R0"); 9277 return -EINVAL; 9278 } 9279 } else { 9280 /* return to the caller whatever r0 had in the callee */ 9281 caller->regs[BPF_REG_0] = *r0; 9282 } 9283 9284 /* callback_fn frame should have released its own additions to parent's 9285 * reference state at this point, or check_reference_leak would 9286 * complain, hence it must be the same as the caller. There is no need 9287 * to copy it back. 9288 */ 9289 if (!callee->in_callback_fn) { 9290 /* Transfer references to the caller */ 9291 err = copy_reference_state(caller, callee); 9292 if (err) 9293 return err; 9294 } 9295 9296 *insn_idx = callee->callsite + 1; 9297 if (env->log.level & BPF_LOG_LEVEL) { 9298 verbose(env, "returning from callee:\n"); 9299 print_verifier_state(env, callee, true); 9300 verbose(env, "to caller at %d:\n", *insn_idx); 9301 print_verifier_state(env, caller, true); 9302 } 9303 /* clear everything in the callee */ 9304 free_func_state(callee); 9305 state->frame[state->curframe--] = NULL; 9306 return 0; 9307 } 9308 9309 static void do_refine_retval_range(struct bpf_reg_state *regs, int ret_type, 9310 int func_id, 9311 struct bpf_call_arg_meta *meta) 9312 { 9313 struct bpf_reg_state *ret_reg = ®s[BPF_REG_0]; 9314 9315 if (ret_type != RET_INTEGER) 9316 return; 9317 9318 switch (func_id) { 9319 case BPF_FUNC_get_stack: 9320 case BPF_FUNC_get_task_stack: 9321 case BPF_FUNC_probe_read_str: 9322 case BPF_FUNC_probe_read_kernel_str: 9323 case BPF_FUNC_probe_read_user_str: 9324 ret_reg->smax_value = meta->msize_max_value; 9325 ret_reg->s32_max_value = meta->msize_max_value; 9326 ret_reg->smin_value = -MAX_ERRNO; 9327 ret_reg->s32_min_value = -MAX_ERRNO; 9328 reg_bounds_sync(ret_reg); 9329 break; 9330 case BPF_FUNC_get_smp_processor_id: 9331 ret_reg->umax_value = nr_cpu_ids - 1; 9332 ret_reg->u32_max_value = nr_cpu_ids - 1; 9333 ret_reg->smax_value = nr_cpu_ids - 1; 9334 ret_reg->s32_max_value = nr_cpu_ids - 1; 9335 ret_reg->umin_value = 0; 9336 ret_reg->u32_min_value = 0; 9337 ret_reg->smin_value = 0; 9338 ret_reg->s32_min_value = 0; 9339 reg_bounds_sync(ret_reg); 9340 break; 9341 } 9342 } 9343 9344 static int 9345 record_func_map(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta, 9346 int func_id, int insn_idx) 9347 { 9348 struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx]; 9349 struct bpf_map *map = meta->map_ptr; 9350 9351 if (func_id != BPF_FUNC_tail_call && 9352 func_id != BPF_FUNC_map_lookup_elem && 9353 func_id != BPF_FUNC_map_update_elem && 9354 func_id != BPF_FUNC_map_delete_elem && 9355 func_id != BPF_FUNC_map_push_elem && 9356 func_id != BPF_FUNC_map_pop_elem && 9357 func_id != BPF_FUNC_map_peek_elem && 9358 func_id != BPF_FUNC_for_each_map_elem && 9359 func_id != BPF_FUNC_redirect_map && 9360 func_id != BPF_FUNC_map_lookup_percpu_elem) 9361 return 0; 9362 9363 if (map == NULL) { 9364 verbose(env, "kernel subsystem misconfigured verifier\n"); 9365 return -EINVAL; 9366 } 9367 9368 /* In case of read-only, some additional restrictions 9369 * need to be applied in order to prevent altering the 9370 * state of the map from program side. 9371 */ 9372 if ((map->map_flags & BPF_F_RDONLY_PROG) && 9373 (func_id == BPF_FUNC_map_delete_elem || 9374 func_id == BPF_FUNC_map_update_elem || 9375 func_id == BPF_FUNC_map_push_elem || 9376 func_id == BPF_FUNC_map_pop_elem)) { 9377 verbose(env, "write into map forbidden\n"); 9378 return -EACCES; 9379 } 9380 9381 if (!BPF_MAP_PTR(aux->map_ptr_state)) 9382 bpf_map_ptr_store(aux, meta->map_ptr, 9383 !meta->map_ptr->bypass_spec_v1); 9384 else if (BPF_MAP_PTR(aux->map_ptr_state) != meta->map_ptr) 9385 bpf_map_ptr_store(aux, BPF_MAP_PTR_POISON, 9386 !meta->map_ptr->bypass_spec_v1); 9387 return 0; 9388 } 9389 9390 static int 9391 record_func_key(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta, 9392 int func_id, int insn_idx) 9393 { 9394 struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx]; 9395 struct bpf_reg_state *regs = cur_regs(env), *reg; 9396 struct bpf_map *map = meta->map_ptr; 9397 u64 val, max; 9398 int err; 9399 9400 if (func_id != BPF_FUNC_tail_call) 9401 return 0; 9402 if (!map || map->map_type != BPF_MAP_TYPE_PROG_ARRAY) { 9403 verbose(env, "kernel subsystem misconfigured verifier\n"); 9404 return -EINVAL; 9405 } 9406 9407 reg = ®s[BPF_REG_3]; 9408 val = reg->var_off.value; 9409 max = map->max_entries; 9410 9411 if (!(register_is_const(reg) && val < max)) { 9412 bpf_map_key_store(aux, BPF_MAP_KEY_POISON); 9413 return 0; 9414 } 9415 9416 err = mark_chain_precision(env, BPF_REG_3); 9417 if (err) 9418 return err; 9419 if (bpf_map_key_unseen(aux)) 9420 bpf_map_key_store(aux, val); 9421 else if (!bpf_map_key_poisoned(aux) && 9422 bpf_map_key_immediate(aux) != val) 9423 bpf_map_key_store(aux, BPF_MAP_KEY_POISON); 9424 return 0; 9425 } 9426 9427 static int check_reference_leak(struct bpf_verifier_env *env) 9428 { 9429 struct bpf_func_state *state = cur_func(env); 9430 bool refs_lingering = false; 9431 int i; 9432 9433 if (state->frameno && !state->in_callback_fn) 9434 return 0; 9435 9436 for (i = 0; i < state->acquired_refs; i++) { 9437 if (state->in_callback_fn && state->refs[i].callback_ref != state->frameno) 9438 continue; 9439 verbose(env, "Unreleased reference id=%d alloc_insn=%d\n", 9440 state->refs[i].id, state->refs[i].insn_idx); 9441 refs_lingering = true; 9442 } 9443 return refs_lingering ? -EINVAL : 0; 9444 } 9445 9446 static int check_bpf_snprintf_call(struct bpf_verifier_env *env, 9447 struct bpf_reg_state *regs) 9448 { 9449 struct bpf_reg_state *fmt_reg = ®s[BPF_REG_3]; 9450 struct bpf_reg_state *data_len_reg = ®s[BPF_REG_5]; 9451 struct bpf_map *fmt_map = fmt_reg->map_ptr; 9452 struct bpf_bprintf_data data = {}; 9453 int err, fmt_map_off, num_args; 9454 u64 fmt_addr; 9455 char *fmt; 9456 9457 /* data must be an array of u64 */ 9458 if (data_len_reg->var_off.value % 8) 9459 return -EINVAL; 9460 num_args = data_len_reg->var_off.value / 8; 9461 9462 /* fmt being ARG_PTR_TO_CONST_STR guarantees that var_off is const 9463 * and map_direct_value_addr is set. 9464 */ 9465 fmt_map_off = fmt_reg->off + fmt_reg->var_off.value; 9466 err = fmt_map->ops->map_direct_value_addr(fmt_map, &fmt_addr, 9467 fmt_map_off); 9468 if (err) { 9469 verbose(env, "verifier bug\n"); 9470 return -EFAULT; 9471 } 9472 fmt = (char *)(long)fmt_addr + fmt_map_off; 9473 9474 /* We are also guaranteed that fmt+fmt_map_off is NULL terminated, we 9475 * can focus on validating the format specifiers. 9476 */ 9477 err = bpf_bprintf_prepare(fmt, UINT_MAX, NULL, num_args, &data); 9478 if (err < 0) 9479 verbose(env, "Invalid format string\n"); 9480 9481 return err; 9482 } 9483 9484 static int check_get_func_ip(struct bpf_verifier_env *env) 9485 { 9486 enum bpf_prog_type type = resolve_prog_type(env->prog); 9487 int func_id = BPF_FUNC_get_func_ip; 9488 9489 if (type == BPF_PROG_TYPE_TRACING) { 9490 if (!bpf_prog_has_trampoline(env->prog)) { 9491 verbose(env, "func %s#%d supported only for fentry/fexit/fmod_ret programs\n", 9492 func_id_name(func_id), func_id); 9493 return -ENOTSUPP; 9494 } 9495 return 0; 9496 } else if (type == BPF_PROG_TYPE_KPROBE) { 9497 return 0; 9498 } 9499 9500 verbose(env, "func %s#%d not supported for program type %d\n", 9501 func_id_name(func_id), func_id, type); 9502 return -ENOTSUPP; 9503 } 9504 9505 static struct bpf_insn_aux_data *cur_aux(struct bpf_verifier_env *env) 9506 { 9507 return &env->insn_aux_data[env->insn_idx]; 9508 } 9509 9510 static bool loop_flag_is_zero(struct bpf_verifier_env *env) 9511 { 9512 struct bpf_reg_state *regs = cur_regs(env); 9513 struct bpf_reg_state *reg = ®s[BPF_REG_4]; 9514 bool reg_is_null = register_is_null(reg); 9515 9516 if (reg_is_null) 9517 mark_chain_precision(env, BPF_REG_4); 9518 9519 return reg_is_null; 9520 } 9521 9522 static void update_loop_inline_state(struct bpf_verifier_env *env, u32 subprogno) 9523 { 9524 struct bpf_loop_inline_state *state = &cur_aux(env)->loop_inline_state; 9525 9526 if (!state->initialized) { 9527 state->initialized = 1; 9528 state->fit_for_inline = loop_flag_is_zero(env); 9529 state->callback_subprogno = subprogno; 9530 return; 9531 } 9532 9533 if (!state->fit_for_inline) 9534 return; 9535 9536 state->fit_for_inline = (loop_flag_is_zero(env) && 9537 state->callback_subprogno == subprogno); 9538 } 9539 9540 static int check_helper_call(struct bpf_verifier_env *env, struct bpf_insn *insn, 9541 int *insn_idx_p) 9542 { 9543 enum bpf_prog_type prog_type = resolve_prog_type(env->prog); 9544 const struct bpf_func_proto *fn = NULL; 9545 enum bpf_return_type ret_type; 9546 enum bpf_type_flag ret_flag; 9547 struct bpf_reg_state *regs; 9548 struct bpf_call_arg_meta meta; 9549 int insn_idx = *insn_idx_p; 9550 bool changes_data; 9551 int i, err, func_id; 9552 9553 /* find function prototype */ 9554 func_id = insn->imm; 9555 if (func_id < 0 || func_id >= __BPF_FUNC_MAX_ID) { 9556 verbose(env, "invalid func %s#%d\n", func_id_name(func_id), 9557 func_id); 9558 return -EINVAL; 9559 } 9560 9561 if (env->ops->get_func_proto) 9562 fn = env->ops->get_func_proto(func_id, env->prog); 9563 if (!fn) { 9564 verbose(env, "unknown func %s#%d\n", func_id_name(func_id), 9565 func_id); 9566 return -EINVAL; 9567 } 9568 9569 /* eBPF programs must be GPL compatible to use GPL-ed functions */ 9570 if (!env->prog->gpl_compatible && fn->gpl_only) { 9571 verbose(env, "cannot call GPL-restricted function from non-GPL compatible program\n"); 9572 return -EINVAL; 9573 } 9574 9575 if (fn->allowed && !fn->allowed(env->prog)) { 9576 verbose(env, "helper call is not allowed in probe\n"); 9577 return -EINVAL; 9578 } 9579 9580 if (!env->prog->aux->sleepable && fn->might_sleep) { 9581 verbose(env, "helper call might sleep in a non-sleepable prog\n"); 9582 return -EINVAL; 9583 } 9584 9585 /* With LD_ABS/IND some JITs save/restore skb from r1. */ 9586 changes_data = bpf_helper_changes_pkt_data(fn->func); 9587 if (changes_data && fn->arg1_type != ARG_PTR_TO_CTX) { 9588 verbose(env, "kernel subsystem misconfigured func %s#%d: r1 != ctx\n", 9589 func_id_name(func_id), func_id); 9590 return -EINVAL; 9591 } 9592 9593 memset(&meta, 0, sizeof(meta)); 9594 meta.pkt_access = fn->pkt_access; 9595 9596 err = check_func_proto(fn, func_id); 9597 if (err) { 9598 verbose(env, "kernel subsystem misconfigured func %s#%d\n", 9599 func_id_name(func_id), func_id); 9600 return err; 9601 } 9602 9603 if (env->cur_state->active_rcu_lock) { 9604 if (fn->might_sleep) { 9605 verbose(env, "sleepable helper %s#%d in rcu_read_lock region\n", 9606 func_id_name(func_id), func_id); 9607 return -EINVAL; 9608 } 9609 9610 if (env->prog->aux->sleepable && is_storage_get_function(func_id)) 9611 env->insn_aux_data[insn_idx].storage_get_func_atomic = true; 9612 } 9613 9614 meta.func_id = func_id; 9615 /* check args */ 9616 for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++) { 9617 err = check_func_arg(env, i, &meta, fn, insn_idx); 9618 if (err) 9619 return err; 9620 } 9621 9622 err = record_func_map(env, &meta, func_id, insn_idx); 9623 if (err) 9624 return err; 9625 9626 err = record_func_key(env, &meta, func_id, insn_idx); 9627 if (err) 9628 return err; 9629 9630 /* Mark slots with STACK_MISC in case of raw mode, stack offset 9631 * is inferred from register state. 9632 */ 9633 for (i = 0; i < meta.access_size; i++) { 9634 err = check_mem_access(env, insn_idx, meta.regno, i, BPF_B, 9635 BPF_WRITE, -1, false, false); 9636 if (err) 9637 return err; 9638 } 9639 9640 regs = cur_regs(env); 9641 9642 if (meta.release_regno) { 9643 err = -EINVAL; 9644 /* This can only be set for PTR_TO_STACK, as CONST_PTR_TO_DYNPTR cannot 9645 * be released by any dynptr helper. Hence, unmark_stack_slots_dynptr 9646 * is safe to do directly. 9647 */ 9648 if (arg_type_is_dynptr(fn->arg_type[meta.release_regno - BPF_REG_1])) { 9649 if (regs[meta.release_regno].type == CONST_PTR_TO_DYNPTR) { 9650 verbose(env, "verifier internal error: CONST_PTR_TO_DYNPTR cannot be released\n"); 9651 return -EFAULT; 9652 } 9653 err = unmark_stack_slots_dynptr(env, ®s[meta.release_regno]); 9654 } else if (meta.ref_obj_id) { 9655 err = release_reference(env, meta.ref_obj_id); 9656 } else if (register_is_null(®s[meta.release_regno])) { 9657 /* meta.ref_obj_id can only be 0 if register that is meant to be 9658 * released is NULL, which must be > R0. 9659 */ 9660 err = 0; 9661 } 9662 if (err) { 9663 verbose(env, "func %s#%d reference has not been acquired before\n", 9664 func_id_name(func_id), func_id); 9665 return err; 9666 } 9667 } 9668 9669 switch (func_id) { 9670 case BPF_FUNC_tail_call: 9671 err = check_reference_leak(env); 9672 if (err) { 9673 verbose(env, "tail_call would lead to reference leak\n"); 9674 return err; 9675 } 9676 break; 9677 case BPF_FUNC_get_local_storage: 9678 /* check that flags argument in get_local_storage(map, flags) is 0, 9679 * this is required because get_local_storage() can't return an error. 9680 */ 9681 if (!register_is_null(®s[BPF_REG_2])) { 9682 verbose(env, "get_local_storage() doesn't support non-zero flags\n"); 9683 return -EINVAL; 9684 } 9685 break; 9686 case BPF_FUNC_for_each_map_elem: 9687 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno, 9688 set_map_elem_callback_state); 9689 break; 9690 case BPF_FUNC_timer_set_callback: 9691 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno, 9692 set_timer_callback_state); 9693 break; 9694 case BPF_FUNC_find_vma: 9695 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno, 9696 set_find_vma_callback_state); 9697 break; 9698 case BPF_FUNC_snprintf: 9699 err = check_bpf_snprintf_call(env, regs); 9700 break; 9701 case BPF_FUNC_loop: 9702 update_loop_inline_state(env, meta.subprogno); 9703 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno, 9704 set_loop_callback_state); 9705 break; 9706 case BPF_FUNC_dynptr_from_mem: 9707 if (regs[BPF_REG_1].type != PTR_TO_MAP_VALUE) { 9708 verbose(env, "Unsupported reg type %s for bpf_dynptr_from_mem data\n", 9709 reg_type_str(env, regs[BPF_REG_1].type)); 9710 return -EACCES; 9711 } 9712 break; 9713 case BPF_FUNC_set_retval: 9714 if (prog_type == BPF_PROG_TYPE_LSM && 9715 env->prog->expected_attach_type == BPF_LSM_CGROUP) { 9716 if (!env->prog->aux->attach_func_proto->type) { 9717 /* Make sure programs that attach to void 9718 * hooks don't try to modify return value. 9719 */ 9720 verbose(env, "BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n"); 9721 return -EINVAL; 9722 } 9723 } 9724 break; 9725 case BPF_FUNC_dynptr_data: 9726 { 9727 struct bpf_reg_state *reg; 9728 int id, ref_obj_id; 9729 9730 reg = get_dynptr_arg_reg(env, fn, regs); 9731 if (!reg) 9732 return -EFAULT; 9733 9734 9735 if (meta.dynptr_id) { 9736 verbose(env, "verifier internal error: meta.dynptr_id already set\n"); 9737 return -EFAULT; 9738 } 9739 if (meta.ref_obj_id) { 9740 verbose(env, "verifier internal error: meta.ref_obj_id already set\n"); 9741 return -EFAULT; 9742 } 9743 9744 id = dynptr_id(env, reg); 9745 if (id < 0) { 9746 verbose(env, "verifier internal error: failed to obtain dynptr id\n"); 9747 return id; 9748 } 9749 9750 ref_obj_id = dynptr_ref_obj_id(env, reg); 9751 if (ref_obj_id < 0) { 9752 verbose(env, "verifier internal error: failed to obtain dynptr ref_obj_id\n"); 9753 return ref_obj_id; 9754 } 9755 9756 meta.dynptr_id = id; 9757 meta.ref_obj_id = ref_obj_id; 9758 9759 break; 9760 } 9761 case BPF_FUNC_dynptr_write: 9762 { 9763 enum bpf_dynptr_type dynptr_type; 9764 struct bpf_reg_state *reg; 9765 9766 reg = get_dynptr_arg_reg(env, fn, regs); 9767 if (!reg) 9768 return -EFAULT; 9769 9770 dynptr_type = dynptr_get_type(env, reg); 9771 if (dynptr_type == BPF_DYNPTR_TYPE_INVALID) 9772 return -EFAULT; 9773 9774 if (dynptr_type == BPF_DYNPTR_TYPE_SKB) 9775 /* this will trigger clear_all_pkt_pointers(), which will 9776 * invalidate all dynptr slices associated with the skb 9777 */ 9778 changes_data = true; 9779 9780 break; 9781 } 9782 case BPF_FUNC_user_ringbuf_drain: 9783 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno, 9784 set_user_ringbuf_callback_state); 9785 break; 9786 } 9787 9788 if (err) 9789 return err; 9790 9791 /* reset caller saved regs */ 9792 for (i = 0; i < CALLER_SAVED_REGS; i++) { 9793 mark_reg_not_init(env, regs, caller_saved[i]); 9794 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK); 9795 } 9796 9797 /* helper call returns 64-bit value. */ 9798 regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG; 9799 9800 /* update return register (already marked as written above) */ 9801 ret_type = fn->ret_type; 9802 ret_flag = type_flag(ret_type); 9803 9804 switch (base_type(ret_type)) { 9805 case RET_INTEGER: 9806 /* sets type to SCALAR_VALUE */ 9807 mark_reg_unknown(env, regs, BPF_REG_0); 9808 break; 9809 case RET_VOID: 9810 regs[BPF_REG_0].type = NOT_INIT; 9811 break; 9812 case RET_PTR_TO_MAP_VALUE: 9813 /* There is no offset yet applied, variable or fixed */ 9814 mark_reg_known_zero(env, regs, BPF_REG_0); 9815 /* remember map_ptr, so that check_map_access() 9816 * can check 'value_size' boundary of memory access 9817 * to map element returned from bpf_map_lookup_elem() 9818 */ 9819 if (meta.map_ptr == NULL) { 9820 verbose(env, 9821 "kernel subsystem misconfigured verifier\n"); 9822 return -EINVAL; 9823 } 9824 regs[BPF_REG_0].map_ptr = meta.map_ptr; 9825 regs[BPF_REG_0].map_uid = meta.map_uid; 9826 regs[BPF_REG_0].type = PTR_TO_MAP_VALUE | ret_flag; 9827 if (!type_may_be_null(ret_type) && 9828 btf_record_has_field(meta.map_ptr->record, BPF_SPIN_LOCK)) { 9829 regs[BPF_REG_0].id = ++env->id_gen; 9830 } 9831 break; 9832 case RET_PTR_TO_SOCKET: 9833 mark_reg_known_zero(env, regs, BPF_REG_0); 9834 regs[BPF_REG_0].type = PTR_TO_SOCKET | ret_flag; 9835 break; 9836 case RET_PTR_TO_SOCK_COMMON: 9837 mark_reg_known_zero(env, regs, BPF_REG_0); 9838 regs[BPF_REG_0].type = PTR_TO_SOCK_COMMON | ret_flag; 9839 break; 9840 case RET_PTR_TO_TCP_SOCK: 9841 mark_reg_known_zero(env, regs, BPF_REG_0); 9842 regs[BPF_REG_0].type = PTR_TO_TCP_SOCK | ret_flag; 9843 break; 9844 case RET_PTR_TO_MEM: 9845 mark_reg_known_zero(env, regs, BPF_REG_0); 9846 regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag; 9847 regs[BPF_REG_0].mem_size = meta.mem_size; 9848 break; 9849 case RET_PTR_TO_MEM_OR_BTF_ID: 9850 { 9851 const struct btf_type *t; 9852 9853 mark_reg_known_zero(env, regs, BPF_REG_0); 9854 t = btf_type_skip_modifiers(meta.ret_btf, meta.ret_btf_id, NULL); 9855 if (!btf_type_is_struct(t)) { 9856 u32 tsize; 9857 const struct btf_type *ret; 9858 const char *tname; 9859 9860 /* resolve the type size of ksym. */ 9861 ret = btf_resolve_size(meta.ret_btf, t, &tsize); 9862 if (IS_ERR(ret)) { 9863 tname = btf_name_by_offset(meta.ret_btf, t->name_off); 9864 verbose(env, "unable to resolve the size of type '%s': %ld\n", 9865 tname, PTR_ERR(ret)); 9866 return -EINVAL; 9867 } 9868 regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag; 9869 regs[BPF_REG_0].mem_size = tsize; 9870 } else { 9871 /* MEM_RDONLY may be carried from ret_flag, but it 9872 * doesn't apply on PTR_TO_BTF_ID. Fold it, otherwise 9873 * it will confuse the check of PTR_TO_BTF_ID in 9874 * check_mem_access(). 9875 */ 9876 ret_flag &= ~MEM_RDONLY; 9877 9878 regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag; 9879 regs[BPF_REG_0].btf = meta.ret_btf; 9880 regs[BPF_REG_0].btf_id = meta.ret_btf_id; 9881 } 9882 break; 9883 } 9884 case RET_PTR_TO_BTF_ID: 9885 { 9886 struct btf *ret_btf; 9887 int ret_btf_id; 9888 9889 mark_reg_known_zero(env, regs, BPF_REG_0); 9890 regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag; 9891 if (func_id == BPF_FUNC_kptr_xchg) { 9892 ret_btf = meta.kptr_field->kptr.btf; 9893 ret_btf_id = meta.kptr_field->kptr.btf_id; 9894 if (!btf_is_kernel(ret_btf)) 9895 regs[BPF_REG_0].type |= MEM_ALLOC; 9896 } else { 9897 if (fn->ret_btf_id == BPF_PTR_POISON) { 9898 verbose(env, "verifier internal error:"); 9899 verbose(env, "func %s has non-overwritten BPF_PTR_POISON return type\n", 9900 func_id_name(func_id)); 9901 return -EINVAL; 9902 } 9903 ret_btf = btf_vmlinux; 9904 ret_btf_id = *fn->ret_btf_id; 9905 } 9906 if (ret_btf_id == 0) { 9907 verbose(env, "invalid return type %u of func %s#%d\n", 9908 base_type(ret_type), func_id_name(func_id), 9909 func_id); 9910 return -EINVAL; 9911 } 9912 regs[BPF_REG_0].btf = ret_btf; 9913 regs[BPF_REG_0].btf_id = ret_btf_id; 9914 break; 9915 } 9916 default: 9917 verbose(env, "unknown return type %u of func %s#%d\n", 9918 base_type(ret_type), func_id_name(func_id), func_id); 9919 return -EINVAL; 9920 } 9921 9922 if (type_may_be_null(regs[BPF_REG_0].type)) 9923 regs[BPF_REG_0].id = ++env->id_gen; 9924 9925 if (helper_multiple_ref_obj_use(func_id, meta.map_ptr)) { 9926 verbose(env, "verifier internal error: func %s#%d sets ref_obj_id more than once\n", 9927 func_id_name(func_id), func_id); 9928 return -EFAULT; 9929 } 9930 9931 if (is_dynptr_ref_function(func_id)) 9932 regs[BPF_REG_0].dynptr_id = meta.dynptr_id; 9933 9934 if (is_ptr_cast_function(func_id) || is_dynptr_ref_function(func_id)) { 9935 /* For release_reference() */ 9936 regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id; 9937 } else if (is_acquire_function(func_id, meta.map_ptr)) { 9938 int id = acquire_reference_state(env, insn_idx); 9939 9940 if (id < 0) 9941 return id; 9942 /* For mark_ptr_or_null_reg() */ 9943 regs[BPF_REG_0].id = id; 9944 /* For release_reference() */ 9945 regs[BPF_REG_0].ref_obj_id = id; 9946 } 9947 9948 do_refine_retval_range(regs, fn->ret_type, func_id, &meta); 9949 9950 err = check_map_func_compatibility(env, meta.map_ptr, func_id); 9951 if (err) 9952 return err; 9953 9954 if ((func_id == BPF_FUNC_get_stack || 9955 func_id == BPF_FUNC_get_task_stack) && 9956 !env->prog->has_callchain_buf) { 9957 const char *err_str; 9958 9959 #ifdef CONFIG_PERF_EVENTS 9960 err = get_callchain_buffers(sysctl_perf_event_max_stack); 9961 err_str = "cannot get callchain buffer for func %s#%d\n"; 9962 #else 9963 err = -ENOTSUPP; 9964 err_str = "func %s#%d not supported without CONFIG_PERF_EVENTS\n"; 9965 #endif 9966 if (err) { 9967 verbose(env, err_str, func_id_name(func_id), func_id); 9968 return err; 9969 } 9970 9971 env->prog->has_callchain_buf = true; 9972 } 9973 9974 if (func_id == BPF_FUNC_get_stackid || func_id == BPF_FUNC_get_stack) 9975 env->prog->call_get_stack = true; 9976 9977 if (func_id == BPF_FUNC_get_func_ip) { 9978 if (check_get_func_ip(env)) 9979 return -ENOTSUPP; 9980 env->prog->call_get_func_ip = true; 9981 } 9982 9983 if (changes_data) 9984 clear_all_pkt_pointers(env); 9985 return 0; 9986 } 9987 9988 /* mark_btf_func_reg_size() is used when the reg size is determined by 9989 * the BTF func_proto's return value size and argument. 9990 */ 9991 static void mark_btf_func_reg_size(struct bpf_verifier_env *env, u32 regno, 9992 size_t reg_size) 9993 { 9994 struct bpf_reg_state *reg = &cur_regs(env)[regno]; 9995 9996 if (regno == BPF_REG_0) { 9997 /* Function return value */ 9998 reg->live |= REG_LIVE_WRITTEN; 9999 reg->subreg_def = reg_size == sizeof(u64) ? 10000 DEF_NOT_SUBREG : env->insn_idx + 1; 10001 } else { 10002 /* Function argument */ 10003 if (reg_size == sizeof(u64)) { 10004 mark_insn_zext(env, reg); 10005 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64); 10006 } else { 10007 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ32); 10008 } 10009 } 10010 } 10011 10012 static bool is_kfunc_acquire(struct bpf_kfunc_call_arg_meta *meta) 10013 { 10014 return meta->kfunc_flags & KF_ACQUIRE; 10015 } 10016 10017 static bool is_kfunc_release(struct bpf_kfunc_call_arg_meta *meta) 10018 { 10019 return meta->kfunc_flags & KF_RELEASE; 10020 } 10021 10022 static bool is_kfunc_trusted_args(struct bpf_kfunc_call_arg_meta *meta) 10023 { 10024 return (meta->kfunc_flags & KF_TRUSTED_ARGS) || is_kfunc_release(meta); 10025 } 10026 10027 static bool is_kfunc_sleepable(struct bpf_kfunc_call_arg_meta *meta) 10028 { 10029 return meta->kfunc_flags & KF_SLEEPABLE; 10030 } 10031 10032 static bool is_kfunc_destructive(struct bpf_kfunc_call_arg_meta *meta) 10033 { 10034 return meta->kfunc_flags & KF_DESTRUCTIVE; 10035 } 10036 10037 static bool is_kfunc_rcu(struct bpf_kfunc_call_arg_meta *meta) 10038 { 10039 return meta->kfunc_flags & KF_RCU; 10040 } 10041 10042 static bool __kfunc_param_match_suffix(const struct btf *btf, 10043 const struct btf_param *arg, 10044 const char *suffix) 10045 { 10046 int suffix_len = strlen(suffix), len; 10047 const char *param_name; 10048 10049 /* In the future, this can be ported to use BTF tagging */ 10050 param_name = btf_name_by_offset(btf, arg->name_off); 10051 if (str_is_empty(param_name)) 10052 return false; 10053 len = strlen(param_name); 10054 if (len < suffix_len) 10055 return false; 10056 param_name += len - suffix_len; 10057 return !strncmp(param_name, suffix, suffix_len); 10058 } 10059 10060 static bool is_kfunc_arg_mem_size(const struct btf *btf, 10061 const struct btf_param *arg, 10062 const struct bpf_reg_state *reg) 10063 { 10064 const struct btf_type *t; 10065 10066 t = btf_type_skip_modifiers(btf, arg->type, NULL); 10067 if (!btf_type_is_scalar(t) || reg->type != SCALAR_VALUE) 10068 return false; 10069 10070 return __kfunc_param_match_suffix(btf, arg, "__sz"); 10071 } 10072 10073 static bool is_kfunc_arg_const_mem_size(const struct btf *btf, 10074 const struct btf_param *arg, 10075 const struct bpf_reg_state *reg) 10076 { 10077 const struct btf_type *t; 10078 10079 t = btf_type_skip_modifiers(btf, arg->type, NULL); 10080 if (!btf_type_is_scalar(t) || reg->type != SCALAR_VALUE) 10081 return false; 10082 10083 return __kfunc_param_match_suffix(btf, arg, "__szk"); 10084 } 10085 10086 static bool is_kfunc_arg_optional(const struct btf *btf, const struct btf_param *arg) 10087 { 10088 return __kfunc_param_match_suffix(btf, arg, "__opt"); 10089 } 10090 10091 static bool is_kfunc_arg_constant(const struct btf *btf, const struct btf_param *arg) 10092 { 10093 return __kfunc_param_match_suffix(btf, arg, "__k"); 10094 } 10095 10096 static bool is_kfunc_arg_ignore(const struct btf *btf, const struct btf_param *arg) 10097 { 10098 return __kfunc_param_match_suffix(btf, arg, "__ign"); 10099 } 10100 10101 static bool is_kfunc_arg_alloc_obj(const struct btf *btf, const struct btf_param *arg) 10102 { 10103 return __kfunc_param_match_suffix(btf, arg, "__alloc"); 10104 } 10105 10106 static bool is_kfunc_arg_uninit(const struct btf *btf, const struct btf_param *arg) 10107 { 10108 return __kfunc_param_match_suffix(btf, arg, "__uninit"); 10109 } 10110 10111 static bool is_kfunc_arg_refcounted_kptr(const struct btf *btf, const struct btf_param *arg) 10112 { 10113 return __kfunc_param_match_suffix(btf, arg, "__refcounted_kptr"); 10114 } 10115 10116 static bool is_kfunc_arg_scalar_with_name(const struct btf *btf, 10117 const struct btf_param *arg, 10118 const char *name) 10119 { 10120 int len, target_len = strlen(name); 10121 const char *param_name; 10122 10123 param_name = btf_name_by_offset(btf, arg->name_off); 10124 if (str_is_empty(param_name)) 10125 return false; 10126 len = strlen(param_name); 10127 if (len != target_len) 10128 return false; 10129 if (strcmp(param_name, name)) 10130 return false; 10131 10132 return true; 10133 } 10134 10135 enum { 10136 KF_ARG_DYNPTR_ID, 10137 KF_ARG_LIST_HEAD_ID, 10138 KF_ARG_LIST_NODE_ID, 10139 KF_ARG_RB_ROOT_ID, 10140 KF_ARG_RB_NODE_ID, 10141 }; 10142 10143 BTF_ID_LIST(kf_arg_btf_ids) 10144 BTF_ID(struct, bpf_dynptr_kern) 10145 BTF_ID(struct, bpf_list_head) 10146 BTF_ID(struct, bpf_list_node) 10147 BTF_ID(struct, bpf_rb_root) 10148 BTF_ID(struct, bpf_rb_node) 10149 10150 static bool __is_kfunc_ptr_arg_type(const struct btf *btf, 10151 const struct btf_param *arg, int type) 10152 { 10153 const struct btf_type *t; 10154 u32 res_id; 10155 10156 t = btf_type_skip_modifiers(btf, arg->type, NULL); 10157 if (!t) 10158 return false; 10159 if (!btf_type_is_ptr(t)) 10160 return false; 10161 t = btf_type_skip_modifiers(btf, t->type, &res_id); 10162 if (!t) 10163 return false; 10164 return btf_types_are_same(btf, res_id, btf_vmlinux, kf_arg_btf_ids[type]); 10165 } 10166 10167 static bool is_kfunc_arg_dynptr(const struct btf *btf, const struct btf_param *arg) 10168 { 10169 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_DYNPTR_ID); 10170 } 10171 10172 static bool is_kfunc_arg_list_head(const struct btf *btf, const struct btf_param *arg) 10173 { 10174 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_LIST_HEAD_ID); 10175 } 10176 10177 static bool is_kfunc_arg_list_node(const struct btf *btf, const struct btf_param *arg) 10178 { 10179 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_LIST_NODE_ID); 10180 } 10181 10182 static bool is_kfunc_arg_rbtree_root(const struct btf *btf, const struct btf_param *arg) 10183 { 10184 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_RB_ROOT_ID); 10185 } 10186 10187 static bool is_kfunc_arg_rbtree_node(const struct btf *btf, const struct btf_param *arg) 10188 { 10189 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_RB_NODE_ID); 10190 } 10191 10192 static bool is_kfunc_arg_callback(struct bpf_verifier_env *env, const struct btf *btf, 10193 const struct btf_param *arg) 10194 { 10195 const struct btf_type *t; 10196 10197 t = btf_type_resolve_func_ptr(btf, arg->type, NULL); 10198 if (!t) 10199 return false; 10200 10201 return true; 10202 } 10203 10204 /* Returns true if struct is composed of scalars, 4 levels of nesting allowed */ 10205 static bool __btf_type_is_scalar_struct(struct bpf_verifier_env *env, 10206 const struct btf *btf, 10207 const struct btf_type *t, int rec) 10208 { 10209 const struct btf_type *member_type; 10210 const struct btf_member *member; 10211 u32 i; 10212 10213 if (!btf_type_is_struct(t)) 10214 return false; 10215 10216 for_each_member(i, t, member) { 10217 const struct btf_array *array; 10218 10219 member_type = btf_type_skip_modifiers(btf, member->type, NULL); 10220 if (btf_type_is_struct(member_type)) { 10221 if (rec >= 3) { 10222 verbose(env, "max struct nesting depth exceeded\n"); 10223 return false; 10224 } 10225 if (!__btf_type_is_scalar_struct(env, btf, member_type, rec + 1)) 10226 return false; 10227 continue; 10228 } 10229 if (btf_type_is_array(member_type)) { 10230 array = btf_array(member_type); 10231 if (!array->nelems) 10232 return false; 10233 member_type = btf_type_skip_modifiers(btf, array->type, NULL); 10234 if (!btf_type_is_scalar(member_type)) 10235 return false; 10236 continue; 10237 } 10238 if (!btf_type_is_scalar(member_type)) 10239 return false; 10240 } 10241 return true; 10242 } 10243 10244 enum kfunc_ptr_arg_type { 10245 KF_ARG_PTR_TO_CTX, 10246 KF_ARG_PTR_TO_ALLOC_BTF_ID, /* Allocated object */ 10247 KF_ARG_PTR_TO_REFCOUNTED_KPTR, /* Refcounted local kptr */ 10248 KF_ARG_PTR_TO_DYNPTR, 10249 KF_ARG_PTR_TO_ITER, 10250 KF_ARG_PTR_TO_LIST_HEAD, 10251 KF_ARG_PTR_TO_LIST_NODE, 10252 KF_ARG_PTR_TO_BTF_ID, /* Also covers reg2btf_ids conversions */ 10253 KF_ARG_PTR_TO_MEM, 10254 KF_ARG_PTR_TO_MEM_SIZE, /* Size derived from next argument, skip it */ 10255 KF_ARG_PTR_TO_CALLBACK, 10256 KF_ARG_PTR_TO_RB_ROOT, 10257 KF_ARG_PTR_TO_RB_NODE, 10258 }; 10259 10260 enum special_kfunc_type { 10261 KF_bpf_obj_new_impl, 10262 KF_bpf_obj_drop_impl, 10263 KF_bpf_refcount_acquire_impl, 10264 KF_bpf_list_push_front_impl, 10265 KF_bpf_list_push_back_impl, 10266 KF_bpf_list_pop_front, 10267 KF_bpf_list_pop_back, 10268 KF_bpf_cast_to_kern_ctx, 10269 KF_bpf_rdonly_cast, 10270 KF_bpf_rcu_read_lock, 10271 KF_bpf_rcu_read_unlock, 10272 KF_bpf_rbtree_remove, 10273 KF_bpf_rbtree_add_impl, 10274 KF_bpf_rbtree_first, 10275 KF_bpf_dynptr_from_skb, 10276 KF_bpf_dynptr_from_xdp, 10277 KF_bpf_dynptr_slice, 10278 KF_bpf_dynptr_slice_rdwr, 10279 KF_bpf_dynptr_clone, 10280 }; 10281 10282 BTF_SET_START(special_kfunc_set) 10283 BTF_ID(func, bpf_obj_new_impl) 10284 BTF_ID(func, bpf_obj_drop_impl) 10285 BTF_ID(func, bpf_refcount_acquire_impl) 10286 BTF_ID(func, bpf_list_push_front_impl) 10287 BTF_ID(func, bpf_list_push_back_impl) 10288 BTF_ID(func, bpf_list_pop_front) 10289 BTF_ID(func, bpf_list_pop_back) 10290 BTF_ID(func, bpf_cast_to_kern_ctx) 10291 BTF_ID(func, bpf_rdonly_cast) 10292 BTF_ID(func, bpf_rbtree_remove) 10293 BTF_ID(func, bpf_rbtree_add_impl) 10294 BTF_ID(func, bpf_rbtree_first) 10295 BTF_ID(func, bpf_dynptr_from_skb) 10296 BTF_ID(func, bpf_dynptr_from_xdp) 10297 BTF_ID(func, bpf_dynptr_slice) 10298 BTF_ID(func, bpf_dynptr_slice_rdwr) 10299 BTF_ID(func, bpf_dynptr_clone) 10300 BTF_SET_END(special_kfunc_set) 10301 10302 BTF_ID_LIST(special_kfunc_list) 10303 BTF_ID(func, bpf_obj_new_impl) 10304 BTF_ID(func, bpf_obj_drop_impl) 10305 BTF_ID(func, bpf_refcount_acquire_impl) 10306 BTF_ID(func, bpf_list_push_front_impl) 10307 BTF_ID(func, bpf_list_push_back_impl) 10308 BTF_ID(func, bpf_list_pop_front) 10309 BTF_ID(func, bpf_list_pop_back) 10310 BTF_ID(func, bpf_cast_to_kern_ctx) 10311 BTF_ID(func, bpf_rdonly_cast) 10312 BTF_ID(func, bpf_rcu_read_lock) 10313 BTF_ID(func, bpf_rcu_read_unlock) 10314 BTF_ID(func, bpf_rbtree_remove) 10315 BTF_ID(func, bpf_rbtree_add_impl) 10316 BTF_ID(func, bpf_rbtree_first) 10317 BTF_ID(func, bpf_dynptr_from_skb) 10318 BTF_ID(func, bpf_dynptr_from_xdp) 10319 BTF_ID(func, bpf_dynptr_slice) 10320 BTF_ID(func, bpf_dynptr_slice_rdwr) 10321 BTF_ID(func, bpf_dynptr_clone) 10322 10323 static bool is_kfunc_ret_null(struct bpf_kfunc_call_arg_meta *meta) 10324 { 10325 if (meta->func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl] && 10326 meta->arg_owning_ref) { 10327 return false; 10328 } 10329 10330 return meta->kfunc_flags & KF_RET_NULL; 10331 } 10332 10333 static bool is_kfunc_bpf_rcu_read_lock(struct bpf_kfunc_call_arg_meta *meta) 10334 { 10335 return meta->func_id == special_kfunc_list[KF_bpf_rcu_read_lock]; 10336 } 10337 10338 static bool is_kfunc_bpf_rcu_read_unlock(struct bpf_kfunc_call_arg_meta *meta) 10339 { 10340 return meta->func_id == special_kfunc_list[KF_bpf_rcu_read_unlock]; 10341 } 10342 10343 static enum kfunc_ptr_arg_type 10344 get_kfunc_ptr_arg_type(struct bpf_verifier_env *env, 10345 struct bpf_kfunc_call_arg_meta *meta, 10346 const struct btf_type *t, const struct btf_type *ref_t, 10347 const char *ref_tname, const struct btf_param *args, 10348 int argno, int nargs) 10349 { 10350 u32 regno = argno + 1; 10351 struct bpf_reg_state *regs = cur_regs(env); 10352 struct bpf_reg_state *reg = ®s[regno]; 10353 bool arg_mem_size = false; 10354 10355 if (meta->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx]) 10356 return KF_ARG_PTR_TO_CTX; 10357 10358 /* In this function, we verify the kfunc's BTF as per the argument type, 10359 * leaving the rest of the verification with respect to the register 10360 * type to our caller. When a set of conditions hold in the BTF type of 10361 * arguments, we resolve it to a known kfunc_ptr_arg_type. 10362 */ 10363 if (btf_get_prog_ctx_type(&env->log, meta->btf, t, resolve_prog_type(env->prog), argno)) 10364 return KF_ARG_PTR_TO_CTX; 10365 10366 if (is_kfunc_arg_alloc_obj(meta->btf, &args[argno])) 10367 return KF_ARG_PTR_TO_ALLOC_BTF_ID; 10368 10369 if (is_kfunc_arg_refcounted_kptr(meta->btf, &args[argno])) 10370 return KF_ARG_PTR_TO_REFCOUNTED_KPTR; 10371 10372 if (is_kfunc_arg_dynptr(meta->btf, &args[argno])) 10373 return KF_ARG_PTR_TO_DYNPTR; 10374 10375 if (is_kfunc_arg_iter(meta, argno)) 10376 return KF_ARG_PTR_TO_ITER; 10377 10378 if (is_kfunc_arg_list_head(meta->btf, &args[argno])) 10379 return KF_ARG_PTR_TO_LIST_HEAD; 10380 10381 if (is_kfunc_arg_list_node(meta->btf, &args[argno])) 10382 return KF_ARG_PTR_TO_LIST_NODE; 10383 10384 if (is_kfunc_arg_rbtree_root(meta->btf, &args[argno])) 10385 return KF_ARG_PTR_TO_RB_ROOT; 10386 10387 if (is_kfunc_arg_rbtree_node(meta->btf, &args[argno])) 10388 return KF_ARG_PTR_TO_RB_NODE; 10389 10390 if ((base_type(reg->type) == PTR_TO_BTF_ID || reg2btf_ids[base_type(reg->type)])) { 10391 if (!btf_type_is_struct(ref_t)) { 10392 verbose(env, "kernel function %s args#%d pointer type %s %s is not supported\n", 10393 meta->func_name, argno, btf_type_str(ref_t), ref_tname); 10394 return -EINVAL; 10395 } 10396 return KF_ARG_PTR_TO_BTF_ID; 10397 } 10398 10399 if (is_kfunc_arg_callback(env, meta->btf, &args[argno])) 10400 return KF_ARG_PTR_TO_CALLBACK; 10401 10402 10403 if (argno + 1 < nargs && 10404 (is_kfunc_arg_mem_size(meta->btf, &args[argno + 1], ®s[regno + 1]) || 10405 is_kfunc_arg_const_mem_size(meta->btf, &args[argno + 1], ®s[regno + 1]))) 10406 arg_mem_size = true; 10407 10408 /* This is the catch all argument type of register types supported by 10409 * check_helper_mem_access. However, we only allow when argument type is 10410 * pointer to scalar, or struct composed (recursively) of scalars. When 10411 * arg_mem_size is true, the pointer can be void *. 10412 */ 10413 if (!btf_type_is_scalar(ref_t) && !__btf_type_is_scalar_struct(env, meta->btf, ref_t, 0) && 10414 (arg_mem_size ? !btf_type_is_void(ref_t) : 1)) { 10415 verbose(env, "arg#%d pointer type %s %s must point to %sscalar, or struct with scalar\n", 10416 argno, btf_type_str(ref_t), ref_tname, arg_mem_size ? "void, " : ""); 10417 return -EINVAL; 10418 } 10419 return arg_mem_size ? KF_ARG_PTR_TO_MEM_SIZE : KF_ARG_PTR_TO_MEM; 10420 } 10421 10422 static int process_kf_arg_ptr_to_btf_id(struct bpf_verifier_env *env, 10423 struct bpf_reg_state *reg, 10424 const struct btf_type *ref_t, 10425 const char *ref_tname, u32 ref_id, 10426 struct bpf_kfunc_call_arg_meta *meta, 10427 int argno) 10428 { 10429 const struct btf_type *reg_ref_t; 10430 bool strict_type_match = false; 10431 const struct btf *reg_btf; 10432 const char *reg_ref_tname; 10433 u32 reg_ref_id; 10434 10435 if (base_type(reg->type) == PTR_TO_BTF_ID) { 10436 reg_btf = reg->btf; 10437 reg_ref_id = reg->btf_id; 10438 } else { 10439 reg_btf = btf_vmlinux; 10440 reg_ref_id = *reg2btf_ids[base_type(reg->type)]; 10441 } 10442 10443 /* Enforce strict type matching for calls to kfuncs that are acquiring 10444 * or releasing a reference, or are no-cast aliases. We do _not_ 10445 * enforce strict matching for plain KF_TRUSTED_ARGS kfuncs by default, 10446 * as we want to enable BPF programs to pass types that are bitwise 10447 * equivalent without forcing them to explicitly cast with something 10448 * like bpf_cast_to_kern_ctx(). 10449 * 10450 * For example, say we had a type like the following: 10451 * 10452 * struct bpf_cpumask { 10453 * cpumask_t cpumask; 10454 * refcount_t usage; 10455 * }; 10456 * 10457 * Note that as specified in <linux/cpumask.h>, cpumask_t is typedef'ed 10458 * to a struct cpumask, so it would be safe to pass a struct 10459 * bpf_cpumask * to a kfunc expecting a struct cpumask *. 10460 * 10461 * The philosophy here is similar to how we allow scalars of different 10462 * types to be passed to kfuncs as long as the size is the same. The 10463 * only difference here is that we're simply allowing 10464 * btf_struct_ids_match() to walk the struct at the 0th offset, and 10465 * resolve types. 10466 */ 10467 if (is_kfunc_acquire(meta) || 10468 (is_kfunc_release(meta) && reg->ref_obj_id) || 10469 btf_type_ids_nocast_alias(&env->log, reg_btf, reg_ref_id, meta->btf, ref_id)) 10470 strict_type_match = true; 10471 10472 WARN_ON_ONCE(is_kfunc_trusted_args(meta) && reg->off); 10473 10474 reg_ref_t = btf_type_skip_modifiers(reg_btf, reg_ref_id, ®_ref_id); 10475 reg_ref_tname = btf_name_by_offset(reg_btf, reg_ref_t->name_off); 10476 if (!btf_struct_ids_match(&env->log, reg_btf, reg_ref_id, reg->off, meta->btf, ref_id, strict_type_match)) { 10477 verbose(env, "kernel function %s args#%d expected pointer to %s %s but R%d has a pointer to %s %s\n", 10478 meta->func_name, argno, btf_type_str(ref_t), ref_tname, argno + 1, 10479 btf_type_str(reg_ref_t), reg_ref_tname); 10480 return -EINVAL; 10481 } 10482 return 0; 10483 } 10484 10485 static int ref_set_non_owning(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 10486 { 10487 struct bpf_verifier_state *state = env->cur_state; 10488 struct btf_record *rec = reg_btf_record(reg); 10489 10490 if (!state->active_lock.ptr) { 10491 verbose(env, "verifier internal error: ref_set_non_owning w/o active lock\n"); 10492 return -EFAULT; 10493 } 10494 10495 if (type_flag(reg->type) & NON_OWN_REF) { 10496 verbose(env, "verifier internal error: NON_OWN_REF already set\n"); 10497 return -EFAULT; 10498 } 10499 10500 reg->type |= NON_OWN_REF; 10501 if (rec->refcount_off >= 0) 10502 reg->type |= MEM_RCU; 10503 10504 return 0; 10505 } 10506 10507 static int ref_convert_owning_non_owning(struct bpf_verifier_env *env, u32 ref_obj_id) 10508 { 10509 struct bpf_func_state *state, *unused; 10510 struct bpf_reg_state *reg; 10511 int i; 10512 10513 state = cur_func(env); 10514 10515 if (!ref_obj_id) { 10516 verbose(env, "verifier internal error: ref_obj_id is zero for " 10517 "owning -> non-owning conversion\n"); 10518 return -EFAULT; 10519 } 10520 10521 for (i = 0; i < state->acquired_refs; i++) { 10522 if (state->refs[i].id != ref_obj_id) 10523 continue; 10524 10525 /* Clear ref_obj_id here so release_reference doesn't clobber 10526 * the whole reg 10527 */ 10528 bpf_for_each_reg_in_vstate(env->cur_state, unused, reg, ({ 10529 if (reg->ref_obj_id == ref_obj_id) { 10530 reg->ref_obj_id = 0; 10531 ref_set_non_owning(env, reg); 10532 } 10533 })); 10534 return 0; 10535 } 10536 10537 verbose(env, "verifier internal error: ref state missing for ref_obj_id\n"); 10538 return -EFAULT; 10539 } 10540 10541 /* Implementation details: 10542 * 10543 * Each register points to some region of memory, which we define as an 10544 * allocation. Each allocation may embed a bpf_spin_lock which protects any 10545 * special BPF objects (bpf_list_head, bpf_rb_root, etc.) part of the same 10546 * allocation. The lock and the data it protects are colocated in the same 10547 * memory region. 10548 * 10549 * Hence, everytime a register holds a pointer value pointing to such 10550 * allocation, the verifier preserves a unique reg->id for it. 10551 * 10552 * The verifier remembers the lock 'ptr' and the lock 'id' whenever 10553 * bpf_spin_lock is called. 10554 * 10555 * To enable this, lock state in the verifier captures two values: 10556 * active_lock.ptr = Register's type specific pointer 10557 * active_lock.id = A unique ID for each register pointer value 10558 * 10559 * Currently, PTR_TO_MAP_VALUE and PTR_TO_BTF_ID | MEM_ALLOC are the two 10560 * supported register types. 10561 * 10562 * The active_lock.ptr in case of map values is the reg->map_ptr, and in case of 10563 * allocated objects is the reg->btf pointer. 10564 * 10565 * The active_lock.id is non-unique for maps supporting direct_value_addr, as we 10566 * can establish the provenance of the map value statically for each distinct 10567 * lookup into such maps. They always contain a single map value hence unique 10568 * IDs for each pseudo load pessimizes the algorithm and rejects valid programs. 10569 * 10570 * So, in case of global variables, they use array maps with max_entries = 1, 10571 * hence their active_lock.ptr becomes map_ptr and id = 0 (since they all point 10572 * into the same map value as max_entries is 1, as described above). 10573 * 10574 * In case of inner map lookups, the inner map pointer has same map_ptr as the 10575 * outer map pointer (in verifier context), but each lookup into an inner map 10576 * assigns a fresh reg->id to the lookup, so while lookups into distinct inner 10577 * maps from the same outer map share the same map_ptr as active_lock.ptr, they 10578 * will get different reg->id assigned to each lookup, hence different 10579 * active_lock.id. 10580 * 10581 * In case of allocated objects, active_lock.ptr is the reg->btf, and the 10582 * reg->id is a unique ID preserved after the NULL pointer check on the pointer 10583 * returned from bpf_obj_new. Each allocation receives a new reg->id. 10584 */ 10585 static int check_reg_allocation_locked(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 10586 { 10587 void *ptr; 10588 u32 id; 10589 10590 switch ((int)reg->type) { 10591 case PTR_TO_MAP_VALUE: 10592 ptr = reg->map_ptr; 10593 break; 10594 case PTR_TO_BTF_ID | MEM_ALLOC: 10595 ptr = reg->btf; 10596 break; 10597 default: 10598 verbose(env, "verifier internal error: unknown reg type for lock check\n"); 10599 return -EFAULT; 10600 } 10601 id = reg->id; 10602 10603 if (!env->cur_state->active_lock.ptr) 10604 return -EINVAL; 10605 if (env->cur_state->active_lock.ptr != ptr || 10606 env->cur_state->active_lock.id != id) { 10607 verbose(env, "held lock and object are not in the same allocation\n"); 10608 return -EINVAL; 10609 } 10610 return 0; 10611 } 10612 10613 static bool is_bpf_list_api_kfunc(u32 btf_id) 10614 { 10615 return btf_id == special_kfunc_list[KF_bpf_list_push_front_impl] || 10616 btf_id == special_kfunc_list[KF_bpf_list_push_back_impl] || 10617 btf_id == special_kfunc_list[KF_bpf_list_pop_front] || 10618 btf_id == special_kfunc_list[KF_bpf_list_pop_back]; 10619 } 10620 10621 static bool is_bpf_rbtree_api_kfunc(u32 btf_id) 10622 { 10623 return btf_id == special_kfunc_list[KF_bpf_rbtree_add_impl] || 10624 btf_id == special_kfunc_list[KF_bpf_rbtree_remove] || 10625 btf_id == special_kfunc_list[KF_bpf_rbtree_first]; 10626 } 10627 10628 static bool is_bpf_graph_api_kfunc(u32 btf_id) 10629 { 10630 return is_bpf_list_api_kfunc(btf_id) || is_bpf_rbtree_api_kfunc(btf_id) || 10631 btf_id == special_kfunc_list[KF_bpf_refcount_acquire_impl]; 10632 } 10633 10634 static bool is_callback_calling_kfunc(u32 btf_id) 10635 { 10636 return btf_id == special_kfunc_list[KF_bpf_rbtree_add_impl]; 10637 } 10638 10639 static bool is_rbtree_lock_required_kfunc(u32 btf_id) 10640 { 10641 return is_bpf_rbtree_api_kfunc(btf_id); 10642 } 10643 10644 static bool check_kfunc_is_graph_root_api(struct bpf_verifier_env *env, 10645 enum btf_field_type head_field_type, 10646 u32 kfunc_btf_id) 10647 { 10648 bool ret; 10649 10650 switch (head_field_type) { 10651 case BPF_LIST_HEAD: 10652 ret = is_bpf_list_api_kfunc(kfunc_btf_id); 10653 break; 10654 case BPF_RB_ROOT: 10655 ret = is_bpf_rbtree_api_kfunc(kfunc_btf_id); 10656 break; 10657 default: 10658 verbose(env, "verifier internal error: unexpected graph root argument type %s\n", 10659 btf_field_type_name(head_field_type)); 10660 return false; 10661 } 10662 10663 if (!ret) 10664 verbose(env, "verifier internal error: %s head arg for unknown kfunc\n", 10665 btf_field_type_name(head_field_type)); 10666 return ret; 10667 } 10668 10669 static bool check_kfunc_is_graph_node_api(struct bpf_verifier_env *env, 10670 enum btf_field_type node_field_type, 10671 u32 kfunc_btf_id) 10672 { 10673 bool ret; 10674 10675 switch (node_field_type) { 10676 case BPF_LIST_NODE: 10677 ret = (kfunc_btf_id == special_kfunc_list[KF_bpf_list_push_front_impl] || 10678 kfunc_btf_id == special_kfunc_list[KF_bpf_list_push_back_impl]); 10679 break; 10680 case BPF_RB_NODE: 10681 ret = (kfunc_btf_id == special_kfunc_list[KF_bpf_rbtree_remove] || 10682 kfunc_btf_id == special_kfunc_list[KF_bpf_rbtree_add_impl]); 10683 break; 10684 default: 10685 verbose(env, "verifier internal error: unexpected graph node argument type %s\n", 10686 btf_field_type_name(node_field_type)); 10687 return false; 10688 } 10689 10690 if (!ret) 10691 verbose(env, "verifier internal error: %s node arg for unknown kfunc\n", 10692 btf_field_type_name(node_field_type)); 10693 return ret; 10694 } 10695 10696 static int 10697 __process_kf_arg_ptr_to_graph_root(struct bpf_verifier_env *env, 10698 struct bpf_reg_state *reg, u32 regno, 10699 struct bpf_kfunc_call_arg_meta *meta, 10700 enum btf_field_type head_field_type, 10701 struct btf_field **head_field) 10702 { 10703 const char *head_type_name; 10704 struct btf_field *field; 10705 struct btf_record *rec; 10706 u32 head_off; 10707 10708 if (meta->btf != btf_vmlinux) { 10709 verbose(env, "verifier internal error: unexpected btf mismatch in kfunc call\n"); 10710 return -EFAULT; 10711 } 10712 10713 if (!check_kfunc_is_graph_root_api(env, head_field_type, meta->func_id)) 10714 return -EFAULT; 10715 10716 head_type_name = btf_field_type_name(head_field_type); 10717 if (!tnum_is_const(reg->var_off)) { 10718 verbose(env, 10719 "R%d doesn't have constant offset. %s has to be at the constant offset\n", 10720 regno, head_type_name); 10721 return -EINVAL; 10722 } 10723 10724 rec = reg_btf_record(reg); 10725 head_off = reg->off + reg->var_off.value; 10726 field = btf_record_find(rec, head_off, head_field_type); 10727 if (!field) { 10728 verbose(env, "%s not found at offset=%u\n", head_type_name, head_off); 10729 return -EINVAL; 10730 } 10731 10732 /* All functions require bpf_list_head to be protected using a bpf_spin_lock */ 10733 if (check_reg_allocation_locked(env, reg)) { 10734 verbose(env, "bpf_spin_lock at off=%d must be held for %s\n", 10735 rec->spin_lock_off, head_type_name); 10736 return -EINVAL; 10737 } 10738 10739 if (*head_field) { 10740 verbose(env, "verifier internal error: repeating %s arg\n", head_type_name); 10741 return -EFAULT; 10742 } 10743 *head_field = field; 10744 return 0; 10745 } 10746 10747 static int process_kf_arg_ptr_to_list_head(struct bpf_verifier_env *env, 10748 struct bpf_reg_state *reg, u32 regno, 10749 struct bpf_kfunc_call_arg_meta *meta) 10750 { 10751 return __process_kf_arg_ptr_to_graph_root(env, reg, regno, meta, BPF_LIST_HEAD, 10752 &meta->arg_list_head.field); 10753 } 10754 10755 static int process_kf_arg_ptr_to_rbtree_root(struct bpf_verifier_env *env, 10756 struct bpf_reg_state *reg, u32 regno, 10757 struct bpf_kfunc_call_arg_meta *meta) 10758 { 10759 return __process_kf_arg_ptr_to_graph_root(env, reg, regno, meta, BPF_RB_ROOT, 10760 &meta->arg_rbtree_root.field); 10761 } 10762 10763 static int 10764 __process_kf_arg_ptr_to_graph_node(struct bpf_verifier_env *env, 10765 struct bpf_reg_state *reg, u32 regno, 10766 struct bpf_kfunc_call_arg_meta *meta, 10767 enum btf_field_type head_field_type, 10768 enum btf_field_type node_field_type, 10769 struct btf_field **node_field) 10770 { 10771 const char *node_type_name; 10772 const struct btf_type *et, *t; 10773 struct btf_field *field; 10774 u32 node_off; 10775 10776 if (meta->btf != btf_vmlinux) { 10777 verbose(env, "verifier internal error: unexpected btf mismatch in kfunc call\n"); 10778 return -EFAULT; 10779 } 10780 10781 if (!check_kfunc_is_graph_node_api(env, node_field_type, meta->func_id)) 10782 return -EFAULT; 10783 10784 node_type_name = btf_field_type_name(node_field_type); 10785 if (!tnum_is_const(reg->var_off)) { 10786 verbose(env, 10787 "R%d doesn't have constant offset. %s has to be at the constant offset\n", 10788 regno, node_type_name); 10789 return -EINVAL; 10790 } 10791 10792 node_off = reg->off + reg->var_off.value; 10793 field = reg_find_field_offset(reg, node_off, node_field_type); 10794 if (!field || field->offset != node_off) { 10795 verbose(env, "%s not found at offset=%u\n", node_type_name, node_off); 10796 return -EINVAL; 10797 } 10798 10799 field = *node_field; 10800 10801 et = btf_type_by_id(field->graph_root.btf, field->graph_root.value_btf_id); 10802 t = btf_type_by_id(reg->btf, reg->btf_id); 10803 if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, 0, field->graph_root.btf, 10804 field->graph_root.value_btf_id, true)) { 10805 verbose(env, "operation on %s expects arg#1 %s at offset=%d " 10806 "in struct %s, but arg is at offset=%d in struct %s\n", 10807 btf_field_type_name(head_field_type), 10808 btf_field_type_name(node_field_type), 10809 field->graph_root.node_offset, 10810 btf_name_by_offset(field->graph_root.btf, et->name_off), 10811 node_off, btf_name_by_offset(reg->btf, t->name_off)); 10812 return -EINVAL; 10813 } 10814 meta->arg_btf = reg->btf; 10815 meta->arg_btf_id = reg->btf_id; 10816 10817 if (node_off != field->graph_root.node_offset) { 10818 verbose(env, "arg#1 offset=%d, but expected %s at offset=%d in struct %s\n", 10819 node_off, btf_field_type_name(node_field_type), 10820 field->graph_root.node_offset, 10821 btf_name_by_offset(field->graph_root.btf, et->name_off)); 10822 return -EINVAL; 10823 } 10824 10825 return 0; 10826 } 10827 10828 static int process_kf_arg_ptr_to_list_node(struct bpf_verifier_env *env, 10829 struct bpf_reg_state *reg, u32 regno, 10830 struct bpf_kfunc_call_arg_meta *meta) 10831 { 10832 return __process_kf_arg_ptr_to_graph_node(env, reg, regno, meta, 10833 BPF_LIST_HEAD, BPF_LIST_NODE, 10834 &meta->arg_list_head.field); 10835 } 10836 10837 static int process_kf_arg_ptr_to_rbtree_node(struct bpf_verifier_env *env, 10838 struct bpf_reg_state *reg, u32 regno, 10839 struct bpf_kfunc_call_arg_meta *meta) 10840 { 10841 return __process_kf_arg_ptr_to_graph_node(env, reg, regno, meta, 10842 BPF_RB_ROOT, BPF_RB_NODE, 10843 &meta->arg_rbtree_root.field); 10844 } 10845 10846 static int check_kfunc_args(struct bpf_verifier_env *env, struct bpf_kfunc_call_arg_meta *meta, 10847 int insn_idx) 10848 { 10849 const char *func_name = meta->func_name, *ref_tname; 10850 const struct btf *btf = meta->btf; 10851 const struct btf_param *args; 10852 struct btf_record *rec; 10853 u32 i, nargs; 10854 int ret; 10855 10856 args = (const struct btf_param *)(meta->func_proto + 1); 10857 nargs = btf_type_vlen(meta->func_proto); 10858 if (nargs > MAX_BPF_FUNC_REG_ARGS) { 10859 verbose(env, "Function %s has %d > %d args\n", func_name, nargs, 10860 MAX_BPF_FUNC_REG_ARGS); 10861 return -EINVAL; 10862 } 10863 10864 /* Check that BTF function arguments match actual types that the 10865 * verifier sees. 10866 */ 10867 for (i = 0; i < nargs; i++) { 10868 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[i + 1]; 10869 const struct btf_type *t, *ref_t, *resolve_ret; 10870 enum bpf_arg_type arg_type = ARG_DONTCARE; 10871 u32 regno = i + 1, ref_id, type_size; 10872 bool is_ret_buf_sz = false; 10873 int kf_arg_type; 10874 10875 t = btf_type_skip_modifiers(btf, args[i].type, NULL); 10876 10877 if (is_kfunc_arg_ignore(btf, &args[i])) 10878 continue; 10879 10880 if (btf_type_is_scalar(t)) { 10881 if (reg->type != SCALAR_VALUE) { 10882 verbose(env, "R%d is not a scalar\n", regno); 10883 return -EINVAL; 10884 } 10885 10886 if (is_kfunc_arg_constant(meta->btf, &args[i])) { 10887 if (meta->arg_constant.found) { 10888 verbose(env, "verifier internal error: only one constant argument permitted\n"); 10889 return -EFAULT; 10890 } 10891 if (!tnum_is_const(reg->var_off)) { 10892 verbose(env, "R%d must be a known constant\n", regno); 10893 return -EINVAL; 10894 } 10895 ret = mark_chain_precision(env, regno); 10896 if (ret < 0) 10897 return ret; 10898 meta->arg_constant.found = true; 10899 meta->arg_constant.value = reg->var_off.value; 10900 } else if (is_kfunc_arg_scalar_with_name(btf, &args[i], "rdonly_buf_size")) { 10901 meta->r0_rdonly = true; 10902 is_ret_buf_sz = true; 10903 } else if (is_kfunc_arg_scalar_with_name(btf, &args[i], "rdwr_buf_size")) { 10904 is_ret_buf_sz = true; 10905 } 10906 10907 if (is_ret_buf_sz) { 10908 if (meta->r0_size) { 10909 verbose(env, "2 or more rdonly/rdwr_buf_size parameters for kfunc"); 10910 return -EINVAL; 10911 } 10912 10913 if (!tnum_is_const(reg->var_off)) { 10914 verbose(env, "R%d is not a const\n", regno); 10915 return -EINVAL; 10916 } 10917 10918 meta->r0_size = reg->var_off.value; 10919 ret = mark_chain_precision(env, regno); 10920 if (ret) 10921 return ret; 10922 } 10923 continue; 10924 } 10925 10926 if (!btf_type_is_ptr(t)) { 10927 verbose(env, "Unrecognized arg#%d type %s\n", i, btf_type_str(t)); 10928 return -EINVAL; 10929 } 10930 10931 if ((is_kfunc_trusted_args(meta) || is_kfunc_rcu(meta)) && 10932 (register_is_null(reg) || type_may_be_null(reg->type))) { 10933 verbose(env, "Possibly NULL pointer passed to trusted arg%d\n", i); 10934 return -EACCES; 10935 } 10936 10937 if (reg->ref_obj_id) { 10938 if (is_kfunc_release(meta) && meta->ref_obj_id) { 10939 verbose(env, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n", 10940 regno, reg->ref_obj_id, 10941 meta->ref_obj_id); 10942 return -EFAULT; 10943 } 10944 meta->ref_obj_id = reg->ref_obj_id; 10945 if (is_kfunc_release(meta)) 10946 meta->release_regno = regno; 10947 } 10948 10949 ref_t = btf_type_skip_modifiers(btf, t->type, &ref_id); 10950 ref_tname = btf_name_by_offset(btf, ref_t->name_off); 10951 10952 kf_arg_type = get_kfunc_ptr_arg_type(env, meta, t, ref_t, ref_tname, args, i, nargs); 10953 if (kf_arg_type < 0) 10954 return kf_arg_type; 10955 10956 switch (kf_arg_type) { 10957 case KF_ARG_PTR_TO_ALLOC_BTF_ID: 10958 case KF_ARG_PTR_TO_BTF_ID: 10959 if (!is_kfunc_trusted_args(meta) && !is_kfunc_rcu(meta)) 10960 break; 10961 10962 if (!is_trusted_reg(reg)) { 10963 if (!is_kfunc_rcu(meta)) { 10964 verbose(env, "R%d must be referenced or trusted\n", regno); 10965 return -EINVAL; 10966 } 10967 if (!is_rcu_reg(reg)) { 10968 verbose(env, "R%d must be a rcu pointer\n", regno); 10969 return -EINVAL; 10970 } 10971 } 10972 10973 fallthrough; 10974 case KF_ARG_PTR_TO_CTX: 10975 /* Trusted arguments have the same offset checks as release arguments */ 10976 arg_type |= OBJ_RELEASE; 10977 break; 10978 case KF_ARG_PTR_TO_DYNPTR: 10979 case KF_ARG_PTR_TO_ITER: 10980 case KF_ARG_PTR_TO_LIST_HEAD: 10981 case KF_ARG_PTR_TO_LIST_NODE: 10982 case KF_ARG_PTR_TO_RB_ROOT: 10983 case KF_ARG_PTR_TO_RB_NODE: 10984 case KF_ARG_PTR_TO_MEM: 10985 case KF_ARG_PTR_TO_MEM_SIZE: 10986 case KF_ARG_PTR_TO_CALLBACK: 10987 case KF_ARG_PTR_TO_REFCOUNTED_KPTR: 10988 /* Trusted by default */ 10989 break; 10990 default: 10991 WARN_ON_ONCE(1); 10992 return -EFAULT; 10993 } 10994 10995 if (is_kfunc_release(meta) && reg->ref_obj_id) 10996 arg_type |= OBJ_RELEASE; 10997 ret = check_func_arg_reg_off(env, reg, regno, arg_type); 10998 if (ret < 0) 10999 return ret; 11000 11001 switch (kf_arg_type) { 11002 case KF_ARG_PTR_TO_CTX: 11003 if (reg->type != PTR_TO_CTX) { 11004 verbose(env, "arg#%d expected pointer to ctx, but got %s\n", i, btf_type_str(t)); 11005 return -EINVAL; 11006 } 11007 11008 if (meta->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx]) { 11009 ret = get_kern_ctx_btf_id(&env->log, resolve_prog_type(env->prog)); 11010 if (ret < 0) 11011 return -EINVAL; 11012 meta->ret_btf_id = ret; 11013 } 11014 break; 11015 case KF_ARG_PTR_TO_ALLOC_BTF_ID: 11016 if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) { 11017 verbose(env, "arg#%d expected pointer to allocated object\n", i); 11018 return -EINVAL; 11019 } 11020 if (!reg->ref_obj_id) { 11021 verbose(env, "allocated object must be referenced\n"); 11022 return -EINVAL; 11023 } 11024 if (meta->btf == btf_vmlinux && 11025 meta->func_id == special_kfunc_list[KF_bpf_obj_drop_impl]) { 11026 meta->arg_btf = reg->btf; 11027 meta->arg_btf_id = reg->btf_id; 11028 } 11029 break; 11030 case KF_ARG_PTR_TO_DYNPTR: 11031 { 11032 enum bpf_arg_type dynptr_arg_type = ARG_PTR_TO_DYNPTR; 11033 int clone_ref_obj_id = 0; 11034 11035 if (reg->type != PTR_TO_STACK && 11036 reg->type != CONST_PTR_TO_DYNPTR) { 11037 verbose(env, "arg#%d expected pointer to stack or dynptr_ptr\n", i); 11038 return -EINVAL; 11039 } 11040 11041 if (reg->type == CONST_PTR_TO_DYNPTR) 11042 dynptr_arg_type |= MEM_RDONLY; 11043 11044 if (is_kfunc_arg_uninit(btf, &args[i])) 11045 dynptr_arg_type |= MEM_UNINIT; 11046 11047 if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_from_skb]) { 11048 dynptr_arg_type |= DYNPTR_TYPE_SKB; 11049 } else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_from_xdp]) { 11050 dynptr_arg_type |= DYNPTR_TYPE_XDP; 11051 } else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_clone] && 11052 (dynptr_arg_type & MEM_UNINIT)) { 11053 enum bpf_dynptr_type parent_type = meta->initialized_dynptr.type; 11054 11055 if (parent_type == BPF_DYNPTR_TYPE_INVALID) { 11056 verbose(env, "verifier internal error: no dynptr type for parent of clone\n"); 11057 return -EFAULT; 11058 } 11059 11060 dynptr_arg_type |= (unsigned int)get_dynptr_type_flag(parent_type); 11061 clone_ref_obj_id = meta->initialized_dynptr.ref_obj_id; 11062 if (dynptr_type_refcounted(parent_type) && !clone_ref_obj_id) { 11063 verbose(env, "verifier internal error: missing ref obj id for parent of clone\n"); 11064 return -EFAULT; 11065 } 11066 } 11067 11068 ret = process_dynptr_func(env, regno, insn_idx, dynptr_arg_type, clone_ref_obj_id); 11069 if (ret < 0) 11070 return ret; 11071 11072 if (!(dynptr_arg_type & MEM_UNINIT)) { 11073 int id = dynptr_id(env, reg); 11074 11075 if (id < 0) { 11076 verbose(env, "verifier internal error: failed to obtain dynptr id\n"); 11077 return id; 11078 } 11079 meta->initialized_dynptr.id = id; 11080 meta->initialized_dynptr.type = dynptr_get_type(env, reg); 11081 meta->initialized_dynptr.ref_obj_id = dynptr_ref_obj_id(env, reg); 11082 } 11083 11084 break; 11085 } 11086 case KF_ARG_PTR_TO_ITER: 11087 ret = process_iter_arg(env, regno, insn_idx, meta); 11088 if (ret < 0) 11089 return ret; 11090 break; 11091 case KF_ARG_PTR_TO_LIST_HEAD: 11092 if (reg->type != PTR_TO_MAP_VALUE && 11093 reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) { 11094 verbose(env, "arg#%d expected pointer to map value or allocated object\n", i); 11095 return -EINVAL; 11096 } 11097 if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC) && !reg->ref_obj_id) { 11098 verbose(env, "allocated object must be referenced\n"); 11099 return -EINVAL; 11100 } 11101 ret = process_kf_arg_ptr_to_list_head(env, reg, regno, meta); 11102 if (ret < 0) 11103 return ret; 11104 break; 11105 case KF_ARG_PTR_TO_RB_ROOT: 11106 if (reg->type != PTR_TO_MAP_VALUE && 11107 reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) { 11108 verbose(env, "arg#%d expected pointer to map value or allocated object\n", i); 11109 return -EINVAL; 11110 } 11111 if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC) && !reg->ref_obj_id) { 11112 verbose(env, "allocated object must be referenced\n"); 11113 return -EINVAL; 11114 } 11115 ret = process_kf_arg_ptr_to_rbtree_root(env, reg, regno, meta); 11116 if (ret < 0) 11117 return ret; 11118 break; 11119 case KF_ARG_PTR_TO_LIST_NODE: 11120 if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) { 11121 verbose(env, "arg#%d expected pointer to allocated object\n", i); 11122 return -EINVAL; 11123 } 11124 if (!reg->ref_obj_id) { 11125 verbose(env, "allocated object must be referenced\n"); 11126 return -EINVAL; 11127 } 11128 ret = process_kf_arg_ptr_to_list_node(env, reg, regno, meta); 11129 if (ret < 0) 11130 return ret; 11131 break; 11132 case KF_ARG_PTR_TO_RB_NODE: 11133 if (meta->func_id == special_kfunc_list[KF_bpf_rbtree_remove]) { 11134 if (!type_is_non_owning_ref(reg->type) || reg->ref_obj_id) { 11135 verbose(env, "rbtree_remove node input must be non-owning ref\n"); 11136 return -EINVAL; 11137 } 11138 if (in_rbtree_lock_required_cb(env)) { 11139 verbose(env, "rbtree_remove not allowed in rbtree cb\n"); 11140 return -EINVAL; 11141 } 11142 } else { 11143 if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) { 11144 verbose(env, "arg#%d expected pointer to allocated object\n", i); 11145 return -EINVAL; 11146 } 11147 if (!reg->ref_obj_id) { 11148 verbose(env, "allocated object must be referenced\n"); 11149 return -EINVAL; 11150 } 11151 } 11152 11153 ret = process_kf_arg_ptr_to_rbtree_node(env, reg, regno, meta); 11154 if (ret < 0) 11155 return ret; 11156 break; 11157 case KF_ARG_PTR_TO_BTF_ID: 11158 /* Only base_type is checked, further checks are done here */ 11159 if ((base_type(reg->type) != PTR_TO_BTF_ID || 11160 (bpf_type_has_unsafe_modifiers(reg->type) && !is_rcu_reg(reg))) && 11161 !reg2btf_ids[base_type(reg->type)]) { 11162 verbose(env, "arg#%d is %s ", i, reg_type_str(env, reg->type)); 11163 verbose(env, "expected %s or socket\n", 11164 reg_type_str(env, base_type(reg->type) | 11165 (type_flag(reg->type) & BPF_REG_TRUSTED_MODIFIERS))); 11166 return -EINVAL; 11167 } 11168 ret = process_kf_arg_ptr_to_btf_id(env, reg, ref_t, ref_tname, ref_id, meta, i); 11169 if (ret < 0) 11170 return ret; 11171 break; 11172 case KF_ARG_PTR_TO_MEM: 11173 resolve_ret = btf_resolve_size(btf, ref_t, &type_size); 11174 if (IS_ERR(resolve_ret)) { 11175 verbose(env, "arg#%d reference type('%s %s') size cannot be determined: %ld\n", 11176 i, btf_type_str(ref_t), ref_tname, PTR_ERR(resolve_ret)); 11177 return -EINVAL; 11178 } 11179 ret = check_mem_reg(env, reg, regno, type_size); 11180 if (ret < 0) 11181 return ret; 11182 break; 11183 case KF_ARG_PTR_TO_MEM_SIZE: 11184 { 11185 struct bpf_reg_state *buff_reg = ®s[regno]; 11186 const struct btf_param *buff_arg = &args[i]; 11187 struct bpf_reg_state *size_reg = ®s[regno + 1]; 11188 const struct btf_param *size_arg = &args[i + 1]; 11189 11190 if (!register_is_null(buff_reg) || !is_kfunc_arg_optional(meta->btf, buff_arg)) { 11191 ret = check_kfunc_mem_size_reg(env, size_reg, regno + 1); 11192 if (ret < 0) { 11193 verbose(env, "arg#%d arg#%d memory, len pair leads to invalid memory access\n", i, i + 1); 11194 return ret; 11195 } 11196 } 11197 11198 if (is_kfunc_arg_const_mem_size(meta->btf, size_arg, size_reg)) { 11199 if (meta->arg_constant.found) { 11200 verbose(env, "verifier internal error: only one constant argument permitted\n"); 11201 return -EFAULT; 11202 } 11203 if (!tnum_is_const(size_reg->var_off)) { 11204 verbose(env, "R%d must be a known constant\n", regno + 1); 11205 return -EINVAL; 11206 } 11207 meta->arg_constant.found = true; 11208 meta->arg_constant.value = size_reg->var_off.value; 11209 } 11210 11211 /* Skip next '__sz' or '__szk' argument */ 11212 i++; 11213 break; 11214 } 11215 case KF_ARG_PTR_TO_CALLBACK: 11216 if (reg->type != PTR_TO_FUNC) { 11217 verbose(env, "arg%d expected pointer to func\n", i); 11218 return -EINVAL; 11219 } 11220 meta->subprogno = reg->subprogno; 11221 break; 11222 case KF_ARG_PTR_TO_REFCOUNTED_KPTR: 11223 if (!type_is_ptr_alloc_obj(reg->type)) { 11224 verbose(env, "arg#%d is neither owning or non-owning ref\n", i); 11225 return -EINVAL; 11226 } 11227 if (!type_is_non_owning_ref(reg->type)) 11228 meta->arg_owning_ref = true; 11229 11230 rec = reg_btf_record(reg); 11231 if (!rec) { 11232 verbose(env, "verifier internal error: Couldn't find btf_record\n"); 11233 return -EFAULT; 11234 } 11235 11236 if (rec->refcount_off < 0) { 11237 verbose(env, "arg#%d doesn't point to a type with bpf_refcount field\n", i); 11238 return -EINVAL; 11239 } 11240 11241 meta->arg_btf = reg->btf; 11242 meta->arg_btf_id = reg->btf_id; 11243 break; 11244 } 11245 } 11246 11247 if (is_kfunc_release(meta) && !meta->release_regno) { 11248 verbose(env, "release kernel function %s expects refcounted PTR_TO_BTF_ID\n", 11249 func_name); 11250 return -EINVAL; 11251 } 11252 11253 return 0; 11254 } 11255 11256 static int fetch_kfunc_meta(struct bpf_verifier_env *env, 11257 struct bpf_insn *insn, 11258 struct bpf_kfunc_call_arg_meta *meta, 11259 const char **kfunc_name) 11260 { 11261 const struct btf_type *func, *func_proto; 11262 u32 func_id, *kfunc_flags; 11263 const char *func_name; 11264 struct btf *desc_btf; 11265 11266 if (kfunc_name) 11267 *kfunc_name = NULL; 11268 11269 if (!insn->imm) 11270 return -EINVAL; 11271 11272 desc_btf = find_kfunc_desc_btf(env, insn->off); 11273 if (IS_ERR(desc_btf)) 11274 return PTR_ERR(desc_btf); 11275 11276 func_id = insn->imm; 11277 func = btf_type_by_id(desc_btf, func_id); 11278 func_name = btf_name_by_offset(desc_btf, func->name_off); 11279 if (kfunc_name) 11280 *kfunc_name = func_name; 11281 func_proto = btf_type_by_id(desc_btf, func->type); 11282 11283 kfunc_flags = btf_kfunc_id_set_contains(desc_btf, func_id, env->prog); 11284 if (!kfunc_flags) { 11285 return -EACCES; 11286 } 11287 11288 memset(meta, 0, sizeof(*meta)); 11289 meta->btf = desc_btf; 11290 meta->func_id = func_id; 11291 meta->kfunc_flags = *kfunc_flags; 11292 meta->func_proto = func_proto; 11293 meta->func_name = func_name; 11294 11295 return 0; 11296 } 11297 11298 static int check_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn, 11299 int *insn_idx_p) 11300 { 11301 const struct btf_type *t, *ptr_type; 11302 u32 i, nargs, ptr_type_id, release_ref_obj_id; 11303 struct bpf_reg_state *regs = cur_regs(env); 11304 const char *func_name, *ptr_type_name; 11305 bool sleepable, rcu_lock, rcu_unlock; 11306 struct bpf_kfunc_call_arg_meta meta; 11307 struct bpf_insn_aux_data *insn_aux; 11308 int err, insn_idx = *insn_idx_p; 11309 const struct btf_param *args; 11310 const struct btf_type *ret_t; 11311 struct btf *desc_btf; 11312 11313 /* skip for now, but return error when we find this in fixup_kfunc_call */ 11314 if (!insn->imm) 11315 return 0; 11316 11317 err = fetch_kfunc_meta(env, insn, &meta, &func_name); 11318 if (err == -EACCES && func_name) 11319 verbose(env, "calling kernel function %s is not allowed\n", func_name); 11320 if (err) 11321 return err; 11322 desc_btf = meta.btf; 11323 insn_aux = &env->insn_aux_data[insn_idx]; 11324 11325 insn_aux->is_iter_next = is_iter_next_kfunc(&meta); 11326 11327 if (is_kfunc_destructive(&meta) && !capable(CAP_SYS_BOOT)) { 11328 verbose(env, "destructive kfunc calls require CAP_SYS_BOOT capability\n"); 11329 return -EACCES; 11330 } 11331 11332 sleepable = is_kfunc_sleepable(&meta); 11333 if (sleepable && !env->prog->aux->sleepable) { 11334 verbose(env, "program must be sleepable to call sleepable kfunc %s\n", func_name); 11335 return -EACCES; 11336 } 11337 11338 rcu_lock = is_kfunc_bpf_rcu_read_lock(&meta); 11339 rcu_unlock = is_kfunc_bpf_rcu_read_unlock(&meta); 11340 11341 if (env->cur_state->active_rcu_lock) { 11342 struct bpf_func_state *state; 11343 struct bpf_reg_state *reg; 11344 11345 if (in_rbtree_lock_required_cb(env) && (rcu_lock || rcu_unlock)) { 11346 verbose(env, "Calling bpf_rcu_read_{lock,unlock} in unnecessary rbtree callback\n"); 11347 return -EACCES; 11348 } 11349 11350 if (rcu_lock) { 11351 verbose(env, "nested rcu read lock (kernel function %s)\n", func_name); 11352 return -EINVAL; 11353 } else if (rcu_unlock) { 11354 bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({ 11355 if (reg->type & MEM_RCU) { 11356 reg->type &= ~(MEM_RCU | PTR_MAYBE_NULL); 11357 reg->type |= PTR_UNTRUSTED; 11358 } 11359 })); 11360 env->cur_state->active_rcu_lock = false; 11361 } else if (sleepable) { 11362 verbose(env, "kernel func %s is sleepable within rcu_read_lock region\n", func_name); 11363 return -EACCES; 11364 } 11365 } else if (rcu_lock) { 11366 env->cur_state->active_rcu_lock = true; 11367 } else if (rcu_unlock) { 11368 verbose(env, "unmatched rcu read unlock (kernel function %s)\n", func_name); 11369 return -EINVAL; 11370 } 11371 11372 /* Check the arguments */ 11373 err = check_kfunc_args(env, &meta, insn_idx); 11374 if (err < 0) 11375 return err; 11376 /* In case of release function, we get register number of refcounted 11377 * PTR_TO_BTF_ID in bpf_kfunc_arg_meta, do the release now. 11378 */ 11379 if (meta.release_regno) { 11380 err = release_reference(env, regs[meta.release_regno].ref_obj_id); 11381 if (err) { 11382 verbose(env, "kfunc %s#%d reference has not been acquired before\n", 11383 func_name, meta.func_id); 11384 return err; 11385 } 11386 } 11387 11388 if (meta.func_id == special_kfunc_list[KF_bpf_list_push_front_impl] || 11389 meta.func_id == special_kfunc_list[KF_bpf_list_push_back_impl] || 11390 meta.func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) { 11391 release_ref_obj_id = regs[BPF_REG_2].ref_obj_id; 11392 insn_aux->insert_off = regs[BPF_REG_2].off; 11393 insn_aux->kptr_struct_meta = btf_find_struct_meta(meta.arg_btf, meta.arg_btf_id); 11394 err = ref_convert_owning_non_owning(env, release_ref_obj_id); 11395 if (err) { 11396 verbose(env, "kfunc %s#%d conversion of owning ref to non-owning failed\n", 11397 func_name, meta.func_id); 11398 return err; 11399 } 11400 11401 err = release_reference(env, release_ref_obj_id); 11402 if (err) { 11403 verbose(env, "kfunc %s#%d reference has not been acquired before\n", 11404 func_name, meta.func_id); 11405 return err; 11406 } 11407 } 11408 11409 if (meta.func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) { 11410 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno, 11411 set_rbtree_add_callback_state); 11412 if (err) { 11413 verbose(env, "kfunc %s#%d failed callback verification\n", 11414 func_name, meta.func_id); 11415 return err; 11416 } 11417 } 11418 11419 for (i = 0; i < CALLER_SAVED_REGS; i++) 11420 mark_reg_not_init(env, regs, caller_saved[i]); 11421 11422 /* Check return type */ 11423 t = btf_type_skip_modifiers(desc_btf, meta.func_proto->type, NULL); 11424 11425 if (is_kfunc_acquire(&meta) && !btf_type_is_struct_ptr(meta.btf, t)) { 11426 /* Only exception is bpf_obj_new_impl */ 11427 if (meta.btf != btf_vmlinux || 11428 (meta.func_id != special_kfunc_list[KF_bpf_obj_new_impl] && 11429 meta.func_id != special_kfunc_list[KF_bpf_refcount_acquire_impl])) { 11430 verbose(env, "acquire kernel function does not return PTR_TO_BTF_ID\n"); 11431 return -EINVAL; 11432 } 11433 } 11434 11435 if (btf_type_is_scalar(t)) { 11436 mark_reg_unknown(env, regs, BPF_REG_0); 11437 mark_btf_func_reg_size(env, BPF_REG_0, t->size); 11438 } else if (btf_type_is_ptr(t)) { 11439 ptr_type = btf_type_skip_modifiers(desc_btf, t->type, &ptr_type_id); 11440 11441 if (meta.btf == btf_vmlinux && btf_id_set_contains(&special_kfunc_set, meta.func_id)) { 11442 if (meta.func_id == special_kfunc_list[KF_bpf_obj_new_impl]) { 11443 struct btf *ret_btf; 11444 u32 ret_btf_id; 11445 11446 if (unlikely(!bpf_global_ma_set)) 11447 return -ENOMEM; 11448 11449 if (((u64)(u32)meta.arg_constant.value) != meta.arg_constant.value) { 11450 verbose(env, "local type ID argument must be in range [0, U32_MAX]\n"); 11451 return -EINVAL; 11452 } 11453 11454 ret_btf = env->prog->aux->btf; 11455 ret_btf_id = meta.arg_constant.value; 11456 11457 /* This may be NULL due to user not supplying a BTF */ 11458 if (!ret_btf) { 11459 verbose(env, "bpf_obj_new requires prog BTF\n"); 11460 return -EINVAL; 11461 } 11462 11463 ret_t = btf_type_by_id(ret_btf, ret_btf_id); 11464 if (!ret_t || !__btf_type_is_struct(ret_t)) { 11465 verbose(env, "bpf_obj_new type ID argument must be of a struct\n"); 11466 return -EINVAL; 11467 } 11468 11469 mark_reg_known_zero(env, regs, BPF_REG_0); 11470 regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC; 11471 regs[BPF_REG_0].btf = ret_btf; 11472 regs[BPF_REG_0].btf_id = ret_btf_id; 11473 11474 insn_aux->obj_new_size = ret_t->size; 11475 insn_aux->kptr_struct_meta = 11476 btf_find_struct_meta(ret_btf, ret_btf_id); 11477 } else if (meta.func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl]) { 11478 mark_reg_known_zero(env, regs, BPF_REG_0); 11479 regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC; 11480 regs[BPF_REG_0].btf = meta.arg_btf; 11481 regs[BPF_REG_0].btf_id = meta.arg_btf_id; 11482 11483 insn_aux->kptr_struct_meta = 11484 btf_find_struct_meta(meta.arg_btf, 11485 meta.arg_btf_id); 11486 } else if (meta.func_id == special_kfunc_list[KF_bpf_list_pop_front] || 11487 meta.func_id == special_kfunc_list[KF_bpf_list_pop_back]) { 11488 struct btf_field *field = meta.arg_list_head.field; 11489 11490 mark_reg_graph_node(regs, BPF_REG_0, &field->graph_root); 11491 } else if (meta.func_id == special_kfunc_list[KF_bpf_rbtree_remove] || 11492 meta.func_id == special_kfunc_list[KF_bpf_rbtree_first]) { 11493 struct btf_field *field = meta.arg_rbtree_root.field; 11494 11495 mark_reg_graph_node(regs, BPF_REG_0, &field->graph_root); 11496 } else if (meta.func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx]) { 11497 mark_reg_known_zero(env, regs, BPF_REG_0); 11498 regs[BPF_REG_0].type = PTR_TO_BTF_ID | PTR_TRUSTED; 11499 regs[BPF_REG_0].btf = desc_btf; 11500 regs[BPF_REG_0].btf_id = meta.ret_btf_id; 11501 } else if (meta.func_id == special_kfunc_list[KF_bpf_rdonly_cast]) { 11502 ret_t = btf_type_by_id(desc_btf, meta.arg_constant.value); 11503 if (!ret_t || !btf_type_is_struct(ret_t)) { 11504 verbose(env, 11505 "kfunc bpf_rdonly_cast type ID argument must be of a struct\n"); 11506 return -EINVAL; 11507 } 11508 11509 mark_reg_known_zero(env, regs, BPF_REG_0); 11510 regs[BPF_REG_0].type = PTR_TO_BTF_ID | PTR_UNTRUSTED; 11511 regs[BPF_REG_0].btf = desc_btf; 11512 regs[BPF_REG_0].btf_id = meta.arg_constant.value; 11513 } else if (meta.func_id == special_kfunc_list[KF_bpf_dynptr_slice] || 11514 meta.func_id == special_kfunc_list[KF_bpf_dynptr_slice_rdwr]) { 11515 enum bpf_type_flag type_flag = get_dynptr_type_flag(meta.initialized_dynptr.type); 11516 11517 mark_reg_known_zero(env, regs, BPF_REG_0); 11518 11519 if (!meta.arg_constant.found) { 11520 verbose(env, "verifier internal error: bpf_dynptr_slice(_rdwr) no constant size\n"); 11521 return -EFAULT; 11522 } 11523 11524 regs[BPF_REG_0].mem_size = meta.arg_constant.value; 11525 11526 /* PTR_MAYBE_NULL will be added when is_kfunc_ret_null is checked */ 11527 regs[BPF_REG_0].type = PTR_TO_MEM | type_flag; 11528 11529 if (meta.func_id == special_kfunc_list[KF_bpf_dynptr_slice]) { 11530 regs[BPF_REG_0].type |= MEM_RDONLY; 11531 } else { 11532 /* this will set env->seen_direct_write to true */ 11533 if (!may_access_direct_pkt_data(env, NULL, BPF_WRITE)) { 11534 verbose(env, "the prog does not allow writes to packet data\n"); 11535 return -EINVAL; 11536 } 11537 } 11538 11539 if (!meta.initialized_dynptr.id) { 11540 verbose(env, "verifier internal error: no dynptr id\n"); 11541 return -EFAULT; 11542 } 11543 regs[BPF_REG_0].dynptr_id = meta.initialized_dynptr.id; 11544 11545 /* we don't need to set BPF_REG_0's ref obj id 11546 * because packet slices are not refcounted (see 11547 * dynptr_type_refcounted) 11548 */ 11549 } else { 11550 verbose(env, "kernel function %s unhandled dynamic return type\n", 11551 meta.func_name); 11552 return -EFAULT; 11553 } 11554 } else if (!__btf_type_is_struct(ptr_type)) { 11555 if (!meta.r0_size) { 11556 __u32 sz; 11557 11558 if (!IS_ERR(btf_resolve_size(desc_btf, ptr_type, &sz))) { 11559 meta.r0_size = sz; 11560 meta.r0_rdonly = true; 11561 } 11562 } 11563 if (!meta.r0_size) { 11564 ptr_type_name = btf_name_by_offset(desc_btf, 11565 ptr_type->name_off); 11566 verbose(env, 11567 "kernel function %s returns pointer type %s %s is not supported\n", 11568 func_name, 11569 btf_type_str(ptr_type), 11570 ptr_type_name); 11571 return -EINVAL; 11572 } 11573 11574 mark_reg_known_zero(env, regs, BPF_REG_0); 11575 regs[BPF_REG_0].type = PTR_TO_MEM; 11576 regs[BPF_REG_0].mem_size = meta.r0_size; 11577 11578 if (meta.r0_rdonly) 11579 regs[BPF_REG_0].type |= MEM_RDONLY; 11580 11581 /* Ensures we don't access the memory after a release_reference() */ 11582 if (meta.ref_obj_id) 11583 regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id; 11584 } else { 11585 mark_reg_known_zero(env, regs, BPF_REG_0); 11586 regs[BPF_REG_0].btf = desc_btf; 11587 regs[BPF_REG_0].type = PTR_TO_BTF_ID; 11588 regs[BPF_REG_0].btf_id = ptr_type_id; 11589 } 11590 11591 if (is_kfunc_ret_null(&meta)) { 11592 regs[BPF_REG_0].type |= PTR_MAYBE_NULL; 11593 /* For mark_ptr_or_null_reg, see 93c230e3f5bd6 */ 11594 regs[BPF_REG_0].id = ++env->id_gen; 11595 } 11596 mark_btf_func_reg_size(env, BPF_REG_0, sizeof(void *)); 11597 if (is_kfunc_acquire(&meta)) { 11598 int id = acquire_reference_state(env, insn_idx); 11599 11600 if (id < 0) 11601 return id; 11602 if (is_kfunc_ret_null(&meta)) 11603 regs[BPF_REG_0].id = id; 11604 regs[BPF_REG_0].ref_obj_id = id; 11605 } else if (meta.func_id == special_kfunc_list[KF_bpf_rbtree_first]) { 11606 ref_set_non_owning(env, ®s[BPF_REG_0]); 11607 } 11608 11609 if (reg_may_point_to_spin_lock(®s[BPF_REG_0]) && !regs[BPF_REG_0].id) 11610 regs[BPF_REG_0].id = ++env->id_gen; 11611 } else if (btf_type_is_void(t)) { 11612 if (meta.btf == btf_vmlinux && btf_id_set_contains(&special_kfunc_set, meta.func_id)) { 11613 if (meta.func_id == special_kfunc_list[KF_bpf_obj_drop_impl]) { 11614 insn_aux->kptr_struct_meta = 11615 btf_find_struct_meta(meta.arg_btf, 11616 meta.arg_btf_id); 11617 } 11618 } 11619 } 11620 11621 nargs = btf_type_vlen(meta.func_proto); 11622 args = (const struct btf_param *)(meta.func_proto + 1); 11623 for (i = 0; i < nargs; i++) { 11624 u32 regno = i + 1; 11625 11626 t = btf_type_skip_modifiers(desc_btf, args[i].type, NULL); 11627 if (btf_type_is_ptr(t)) 11628 mark_btf_func_reg_size(env, regno, sizeof(void *)); 11629 else 11630 /* scalar. ensured by btf_check_kfunc_arg_match() */ 11631 mark_btf_func_reg_size(env, regno, t->size); 11632 } 11633 11634 if (is_iter_next_kfunc(&meta)) { 11635 err = process_iter_next_call(env, insn_idx, &meta); 11636 if (err) 11637 return err; 11638 } 11639 11640 return 0; 11641 } 11642 11643 static bool signed_add_overflows(s64 a, s64 b) 11644 { 11645 /* Do the add in u64, where overflow is well-defined */ 11646 s64 res = (s64)((u64)a + (u64)b); 11647 11648 if (b < 0) 11649 return res > a; 11650 return res < a; 11651 } 11652 11653 static bool signed_add32_overflows(s32 a, s32 b) 11654 { 11655 /* Do the add in u32, where overflow is well-defined */ 11656 s32 res = (s32)((u32)a + (u32)b); 11657 11658 if (b < 0) 11659 return res > a; 11660 return res < a; 11661 } 11662 11663 static bool signed_sub_overflows(s64 a, s64 b) 11664 { 11665 /* Do the sub in u64, where overflow is well-defined */ 11666 s64 res = (s64)((u64)a - (u64)b); 11667 11668 if (b < 0) 11669 return res < a; 11670 return res > a; 11671 } 11672 11673 static bool signed_sub32_overflows(s32 a, s32 b) 11674 { 11675 /* Do the sub in u32, where overflow is well-defined */ 11676 s32 res = (s32)((u32)a - (u32)b); 11677 11678 if (b < 0) 11679 return res < a; 11680 return res > a; 11681 } 11682 11683 static bool check_reg_sane_offset(struct bpf_verifier_env *env, 11684 const struct bpf_reg_state *reg, 11685 enum bpf_reg_type type) 11686 { 11687 bool known = tnum_is_const(reg->var_off); 11688 s64 val = reg->var_off.value; 11689 s64 smin = reg->smin_value; 11690 11691 if (known && (val >= BPF_MAX_VAR_OFF || val <= -BPF_MAX_VAR_OFF)) { 11692 verbose(env, "math between %s pointer and %lld is not allowed\n", 11693 reg_type_str(env, type), val); 11694 return false; 11695 } 11696 11697 if (reg->off >= BPF_MAX_VAR_OFF || reg->off <= -BPF_MAX_VAR_OFF) { 11698 verbose(env, "%s pointer offset %d is not allowed\n", 11699 reg_type_str(env, type), reg->off); 11700 return false; 11701 } 11702 11703 if (smin == S64_MIN) { 11704 verbose(env, "math between %s pointer and register with unbounded min value is not allowed\n", 11705 reg_type_str(env, type)); 11706 return false; 11707 } 11708 11709 if (smin >= BPF_MAX_VAR_OFF || smin <= -BPF_MAX_VAR_OFF) { 11710 verbose(env, "value %lld makes %s pointer be out of bounds\n", 11711 smin, reg_type_str(env, type)); 11712 return false; 11713 } 11714 11715 return true; 11716 } 11717 11718 enum { 11719 REASON_BOUNDS = -1, 11720 REASON_TYPE = -2, 11721 REASON_PATHS = -3, 11722 REASON_LIMIT = -4, 11723 REASON_STACK = -5, 11724 }; 11725 11726 static int retrieve_ptr_limit(const struct bpf_reg_state *ptr_reg, 11727 u32 *alu_limit, bool mask_to_left) 11728 { 11729 u32 max = 0, ptr_limit = 0; 11730 11731 switch (ptr_reg->type) { 11732 case PTR_TO_STACK: 11733 /* Offset 0 is out-of-bounds, but acceptable start for the 11734 * left direction, see BPF_REG_FP. Also, unknown scalar 11735 * offset where we would need to deal with min/max bounds is 11736 * currently prohibited for unprivileged. 11737 */ 11738 max = MAX_BPF_STACK + mask_to_left; 11739 ptr_limit = -(ptr_reg->var_off.value + ptr_reg->off); 11740 break; 11741 case PTR_TO_MAP_VALUE: 11742 max = ptr_reg->map_ptr->value_size; 11743 ptr_limit = (mask_to_left ? 11744 ptr_reg->smin_value : 11745 ptr_reg->umax_value) + ptr_reg->off; 11746 break; 11747 default: 11748 return REASON_TYPE; 11749 } 11750 11751 if (ptr_limit >= max) 11752 return REASON_LIMIT; 11753 *alu_limit = ptr_limit; 11754 return 0; 11755 } 11756 11757 static bool can_skip_alu_sanitation(const struct bpf_verifier_env *env, 11758 const struct bpf_insn *insn) 11759 { 11760 return env->bypass_spec_v1 || BPF_SRC(insn->code) == BPF_K; 11761 } 11762 11763 static int update_alu_sanitation_state(struct bpf_insn_aux_data *aux, 11764 u32 alu_state, u32 alu_limit) 11765 { 11766 /* If we arrived here from different branches with different 11767 * state or limits to sanitize, then this won't work. 11768 */ 11769 if (aux->alu_state && 11770 (aux->alu_state != alu_state || 11771 aux->alu_limit != alu_limit)) 11772 return REASON_PATHS; 11773 11774 /* Corresponding fixup done in do_misc_fixups(). */ 11775 aux->alu_state = alu_state; 11776 aux->alu_limit = alu_limit; 11777 return 0; 11778 } 11779 11780 static int sanitize_val_alu(struct bpf_verifier_env *env, 11781 struct bpf_insn *insn) 11782 { 11783 struct bpf_insn_aux_data *aux = cur_aux(env); 11784 11785 if (can_skip_alu_sanitation(env, insn)) 11786 return 0; 11787 11788 return update_alu_sanitation_state(aux, BPF_ALU_NON_POINTER, 0); 11789 } 11790 11791 static bool sanitize_needed(u8 opcode) 11792 { 11793 return opcode == BPF_ADD || opcode == BPF_SUB; 11794 } 11795 11796 struct bpf_sanitize_info { 11797 struct bpf_insn_aux_data aux; 11798 bool mask_to_left; 11799 }; 11800 11801 static struct bpf_verifier_state * 11802 sanitize_speculative_path(struct bpf_verifier_env *env, 11803 const struct bpf_insn *insn, 11804 u32 next_idx, u32 curr_idx) 11805 { 11806 struct bpf_verifier_state *branch; 11807 struct bpf_reg_state *regs; 11808 11809 branch = push_stack(env, next_idx, curr_idx, true); 11810 if (branch && insn) { 11811 regs = branch->frame[branch->curframe]->regs; 11812 if (BPF_SRC(insn->code) == BPF_K) { 11813 mark_reg_unknown(env, regs, insn->dst_reg); 11814 } else if (BPF_SRC(insn->code) == BPF_X) { 11815 mark_reg_unknown(env, regs, insn->dst_reg); 11816 mark_reg_unknown(env, regs, insn->src_reg); 11817 } 11818 } 11819 return branch; 11820 } 11821 11822 static int sanitize_ptr_alu(struct bpf_verifier_env *env, 11823 struct bpf_insn *insn, 11824 const struct bpf_reg_state *ptr_reg, 11825 const struct bpf_reg_state *off_reg, 11826 struct bpf_reg_state *dst_reg, 11827 struct bpf_sanitize_info *info, 11828 const bool commit_window) 11829 { 11830 struct bpf_insn_aux_data *aux = commit_window ? cur_aux(env) : &info->aux; 11831 struct bpf_verifier_state *vstate = env->cur_state; 11832 bool off_is_imm = tnum_is_const(off_reg->var_off); 11833 bool off_is_neg = off_reg->smin_value < 0; 11834 bool ptr_is_dst_reg = ptr_reg == dst_reg; 11835 u8 opcode = BPF_OP(insn->code); 11836 u32 alu_state, alu_limit; 11837 struct bpf_reg_state tmp; 11838 bool ret; 11839 int err; 11840 11841 if (can_skip_alu_sanitation(env, insn)) 11842 return 0; 11843 11844 /* We already marked aux for masking from non-speculative 11845 * paths, thus we got here in the first place. We only care 11846 * to explore bad access from here. 11847 */ 11848 if (vstate->speculative) 11849 goto do_sim; 11850 11851 if (!commit_window) { 11852 if (!tnum_is_const(off_reg->var_off) && 11853 (off_reg->smin_value < 0) != (off_reg->smax_value < 0)) 11854 return REASON_BOUNDS; 11855 11856 info->mask_to_left = (opcode == BPF_ADD && off_is_neg) || 11857 (opcode == BPF_SUB && !off_is_neg); 11858 } 11859 11860 err = retrieve_ptr_limit(ptr_reg, &alu_limit, info->mask_to_left); 11861 if (err < 0) 11862 return err; 11863 11864 if (commit_window) { 11865 /* In commit phase we narrow the masking window based on 11866 * the observed pointer move after the simulated operation. 11867 */ 11868 alu_state = info->aux.alu_state; 11869 alu_limit = abs(info->aux.alu_limit - alu_limit); 11870 } else { 11871 alu_state = off_is_neg ? BPF_ALU_NEG_VALUE : 0; 11872 alu_state |= off_is_imm ? BPF_ALU_IMMEDIATE : 0; 11873 alu_state |= ptr_is_dst_reg ? 11874 BPF_ALU_SANITIZE_SRC : BPF_ALU_SANITIZE_DST; 11875 11876 /* Limit pruning on unknown scalars to enable deep search for 11877 * potential masking differences from other program paths. 11878 */ 11879 if (!off_is_imm) 11880 env->explore_alu_limits = true; 11881 } 11882 11883 err = update_alu_sanitation_state(aux, alu_state, alu_limit); 11884 if (err < 0) 11885 return err; 11886 do_sim: 11887 /* If we're in commit phase, we're done here given we already 11888 * pushed the truncated dst_reg into the speculative verification 11889 * stack. 11890 * 11891 * Also, when register is a known constant, we rewrite register-based 11892 * operation to immediate-based, and thus do not need masking (and as 11893 * a consequence, do not need to simulate the zero-truncation either). 11894 */ 11895 if (commit_window || off_is_imm) 11896 return 0; 11897 11898 /* Simulate and find potential out-of-bounds access under 11899 * speculative execution from truncation as a result of 11900 * masking when off was not within expected range. If off 11901 * sits in dst, then we temporarily need to move ptr there 11902 * to simulate dst (== 0) +/-= ptr. Needed, for example, 11903 * for cases where we use K-based arithmetic in one direction 11904 * and truncated reg-based in the other in order to explore 11905 * bad access. 11906 */ 11907 if (!ptr_is_dst_reg) { 11908 tmp = *dst_reg; 11909 copy_register_state(dst_reg, ptr_reg); 11910 } 11911 ret = sanitize_speculative_path(env, NULL, env->insn_idx + 1, 11912 env->insn_idx); 11913 if (!ptr_is_dst_reg && ret) 11914 *dst_reg = tmp; 11915 return !ret ? REASON_STACK : 0; 11916 } 11917 11918 static void sanitize_mark_insn_seen(struct bpf_verifier_env *env) 11919 { 11920 struct bpf_verifier_state *vstate = env->cur_state; 11921 11922 /* If we simulate paths under speculation, we don't update the 11923 * insn as 'seen' such that when we verify unreachable paths in 11924 * the non-speculative domain, sanitize_dead_code() can still 11925 * rewrite/sanitize them. 11926 */ 11927 if (!vstate->speculative) 11928 env->insn_aux_data[env->insn_idx].seen = env->pass_cnt; 11929 } 11930 11931 static int sanitize_err(struct bpf_verifier_env *env, 11932 const struct bpf_insn *insn, int reason, 11933 const struct bpf_reg_state *off_reg, 11934 const struct bpf_reg_state *dst_reg) 11935 { 11936 static const char *err = "pointer arithmetic with it prohibited for !root"; 11937 const char *op = BPF_OP(insn->code) == BPF_ADD ? "add" : "sub"; 11938 u32 dst = insn->dst_reg, src = insn->src_reg; 11939 11940 switch (reason) { 11941 case REASON_BOUNDS: 11942 verbose(env, "R%d has unknown scalar with mixed signed bounds, %s\n", 11943 off_reg == dst_reg ? dst : src, err); 11944 break; 11945 case REASON_TYPE: 11946 verbose(env, "R%d has pointer with unsupported alu operation, %s\n", 11947 off_reg == dst_reg ? src : dst, err); 11948 break; 11949 case REASON_PATHS: 11950 verbose(env, "R%d tried to %s from different maps, paths or scalars, %s\n", 11951 dst, op, err); 11952 break; 11953 case REASON_LIMIT: 11954 verbose(env, "R%d tried to %s beyond pointer bounds, %s\n", 11955 dst, op, err); 11956 break; 11957 case REASON_STACK: 11958 verbose(env, "R%d could not be pushed for speculative verification, %s\n", 11959 dst, err); 11960 break; 11961 default: 11962 verbose(env, "verifier internal error: unknown reason (%d)\n", 11963 reason); 11964 break; 11965 } 11966 11967 return -EACCES; 11968 } 11969 11970 /* check that stack access falls within stack limits and that 'reg' doesn't 11971 * have a variable offset. 11972 * 11973 * Variable offset is prohibited for unprivileged mode for simplicity since it 11974 * requires corresponding support in Spectre masking for stack ALU. See also 11975 * retrieve_ptr_limit(). 11976 * 11977 * 11978 * 'off' includes 'reg->off'. 11979 */ 11980 static int check_stack_access_for_ptr_arithmetic( 11981 struct bpf_verifier_env *env, 11982 int regno, 11983 const struct bpf_reg_state *reg, 11984 int off) 11985 { 11986 if (!tnum_is_const(reg->var_off)) { 11987 char tn_buf[48]; 11988 11989 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 11990 verbose(env, "R%d variable stack access prohibited for !root, var_off=%s off=%d\n", 11991 regno, tn_buf, off); 11992 return -EACCES; 11993 } 11994 11995 if (off >= 0 || off < -MAX_BPF_STACK) { 11996 verbose(env, "R%d stack pointer arithmetic goes out of range, " 11997 "prohibited for !root; off=%d\n", regno, off); 11998 return -EACCES; 11999 } 12000 12001 return 0; 12002 } 12003 12004 static int sanitize_check_bounds(struct bpf_verifier_env *env, 12005 const struct bpf_insn *insn, 12006 const struct bpf_reg_state *dst_reg) 12007 { 12008 u32 dst = insn->dst_reg; 12009 12010 /* For unprivileged we require that resulting offset must be in bounds 12011 * in order to be able to sanitize access later on. 12012 */ 12013 if (env->bypass_spec_v1) 12014 return 0; 12015 12016 switch (dst_reg->type) { 12017 case PTR_TO_STACK: 12018 if (check_stack_access_for_ptr_arithmetic(env, dst, dst_reg, 12019 dst_reg->off + dst_reg->var_off.value)) 12020 return -EACCES; 12021 break; 12022 case PTR_TO_MAP_VALUE: 12023 if (check_map_access(env, dst, dst_reg->off, 1, false, ACCESS_HELPER)) { 12024 verbose(env, "R%d pointer arithmetic of map value goes out of range, " 12025 "prohibited for !root\n", dst); 12026 return -EACCES; 12027 } 12028 break; 12029 default: 12030 break; 12031 } 12032 12033 return 0; 12034 } 12035 12036 /* Handles arithmetic on a pointer and a scalar: computes new min/max and var_off. 12037 * Caller should also handle BPF_MOV case separately. 12038 * If we return -EACCES, caller may want to try again treating pointer as a 12039 * scalar. So we only emit a diagnostic if !env->allow_ptr_leaks. 12040 */ 12041 static int adjust_ptr_min_max_vals(struct bpf_verifier_env *env, 12042 struct bpf_insn *insn, 12043 const struct bpf_reg_state *ptr_reg, 12044 const struct bpf_reg_state *off_reg) 12045 { 12046 struct bpf_verifier_state *vstate = env->cur_state; 12047 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 12048 struct bpf_reg_state *regs = state->regs, *dst_reg; 12049 bool known = tnum_is_const(off_reg->var_off); 12050 s64 smin_val = off_reg->smin_value, smax_val = off_reg->smax_value, 12051 smin_ptr = ptr_reg->smin_value, smax_ptr = ptr_reg->smax_value; 12052 u64 umin_val = off_reg->umin_value, umax_val = off_reg->umax_value, 12053 umin_ptr = ptr_reg->umin_value, umax_ptr = ptr_reg->umax_value; 12054 struct bpf_sanitize_info info = {}; 12055 u8 opcode = BPF_OP(insn->code); 12056 u32 dst = insn->dst_reg; 12057 int ret; 12058 12059 dst_reg = ®s[dst]; 12060 12061 if ((known && (smin_val != smax_val || umin_val != umax_val)) || 12062 smin_val > smax_val || umin_val > umax_val) { 12063 /* Taint dst register if offset had invalid bounds derived from 12064 * e.g. dead branches. 12065 */ 12066 __mark_reg_unknown(env, dst_reg); 12067 return 0; 12068 } 12069 12070 if (BPF_CLASS(insn->code) != BPF_ALU64) { 12071 /* 32-bit ALU ops on pointers produce (meaningless) scalars */ 12072 if (opcode == BPF_SUB && env->allow_ptr_leaks) { 12073 __mark_reg_unknown(env, dst_reg); 12074 return 0; 12075 } 12076 12077 verbose(env, 12078 "R%d 32-bit pointer arithmetic prohibited\n", 12079 dst); 12080 return -EACCES; 12081 } 12082 12083 if (ptr_reg->type & PTR_MAYBE_NULL) { 12084 verbose(env, "R%d pointer arithmetic on %s prohibited, null-check it first\n", 12085 dst, reg_type_str(env, ptr_reg->type)); 12086 return -EACCES; 12087 } 12088 12089 switch (base_type(ptr_reg->type)) { 12090 case PTR_TO_FLOW_KEYS: 12091 if (known) 12092 break; 12093 fallthrough; 12094 case CONST_PTR_TO_MAP: 12095 /* smin_val represents the known value */ 12096 if (known && smin_val == 0 && opcode == BPF_ADD) 12097 break; 12098 fallthrough; 12099 case PTR_TO_PACKET_END: 12100 case PTR_TO_SOCKET: 12101 case PTR_TO_SOCK_COMMON: 12102 case PTR_TO_TCP_SOCK: 12103 case PTR_TO_XDP_SOCK: 12104 verbose(env, "R%d pointer arithmetic on %s prohibited\n", 12105 dst, reg_type_str(env, ptr_reg->type)); 12106 return -EACCES; 12107 default: 12108 break; 12109 } 12110 12111 /* In case of 'scalar += pointer', dst_reg inherits pointer type and id. 12112 * The id may be overwritten later if we create a new variable offset. 12113 */ 12114 dst_reg->type = ptr_reg->type; 12115 dst_reg->id = ptr_reg->id; 12116 12117 if (!check_reg_sane_offset(env, off_reg, ptr_reg->type) || 12118 !check_reg_sane_offset(env, ptr_reg, ptr_reg->type)) 12119 return -EINVAL; 12120 12121 /* pointer types do not carry 32-bit bounds at the moment. */ 12122 __mark_reg32_unbounded(dst_reg); 12123 12124 if (sanitize_needed(opcode)) { 12125 ret = sanitize_ptr_alu(env, insn, ptr_reg, off_reg, dst_reg, 12126 &info, false); 12127 if (ret < 0) 12128 return sanitize_err(env, insn, ret, off_reg, dst_reg); 12129 } 12130 12131 switch (opcode) { 12132 case BPF_ADD: 12133 /* We can take a fixed offset as long as it doesn't overflow 12134 * the s32 'off' field 12135 */ 12136 if (known && (ptr_reg->off + smin_val == 12137 (s64)(s32)(ptr_reg->off + smin_val))) { 12138 /* pointer += K. Accumulate it into fixed offset */ 12139 dst_reg->smin_value = smin_ptr; 12140 dst_reg->smax_value = smax_ptr; 12141 dst_reg->umin_value = umin_ptr; 12142 dst_reg->umax_value = umax_ptr; 12143 dst_reg->var_off = ptr_reg->var_off; 12144 dst_reg->off = ptr_reg->off + smin_val; 12145 dst_reg->raw = ptr_reg->raw; 12146 break; 12147 } 12148 /* A new variable offset is created. Note that off_reg->off 12149 * == 0, since it's a scalar. 12150 * dst_reg gets the pointer type and since some positive 12151 * integer value was added to the pointer, give it a new 'id' 12152 * if it's a PTR_TO_PACKET. 12153 * this creates a new 'base' pointer, off_reg (variable) gets 12154 * added into the variable offset, and we copy the fixed offset 12155 * from ptr_reg. 12156 */ 12157 if (signed_add_overflows(smin_ptr, smin_val) || 12158 signed_add_overflows(smax_ptr, smax_val)) { 12159 dst_reg->smin_value = S64_MIN; 12160 dst_reg->smax_value = S64_MAX; 12161 } else { 12162 dst_reg->smin_value = smin_ptr + smin_val; 12163 dst_reg->smax_value = smax_ptr + smax_val; 12164 } 12165 if (umin_ptr + umin_val < umin_ptr || 12166 umax_ptr + umax_val < umax_ptr) { 12167 dst_reg->umin_value = 0; 12168 dst_reg->umax_value = U64_MAX; 12169 } else { 12170 dst_reg->umin_value = umin_ptr + umin_val; 12171 dst_reg->umax_value = umax_ptr + umax_val; 12172 } 12173 dst_reg->var_off = tnum_add(ptr_reg->var_off, off_reg->var_off); 12174 dst_reg->off = ptr_reg->off; 12175 dst_reg->raw = ptr_reg->raw; 12176 if (reg_is_pkt_pointer(ptr_reg)) { 12177 dst_reg->id = ++env->id_gen; 12178 /* something was added to pkt_ptr, set range to zero */ 12179 memset(&dst_reg->raw, 0, sizeof(dst_reg->raw)); 12180 } 12181 break; 12182 case BPF_SUB: 12183 if (dst_reg == off_reg) { 12184 /* scalar -= pointer. Creates an unknown scalar */ 12185 verbose(env, "R%d tried to subtract pointer from scalar\n", 12186 dst); 12187 return -EACCES; 12188 } 12189 /* We don't allow subtraction from FP, because (according to 12190 * test_verifier.c test "invalid fp arithmetic", JITs might not 12191 * be able to deal with it. 12192 */ 12193 if (ptr_reg->type == PTR_TO_STACK) { 12194 verbose(env, "R%d subtraction from stack pointer prohibited\n", 12195 dst); 12196 return -EACCES; 12197 } 12198 if (known && (ptr_reg->off - smin_val == 12199 (s64)(s32)(ptr_reg->off - smin_val))) { 12200 /* pointer -= K. Subtract it from fixed offset */ 12201 dst_reg->smin_value = smin_ptr; 12202 dst_reg->smax_value = smax_ptr; 12203 dst_reg->umin_value = umin_ptr; 12204 dst_reg->umax_value = umax_ptr; 12205 dst_reg->var_off = ptr_reg->var_off; 12206 dst_reg->id = ptr_reg->id; 12207 dst_reg->off = ptr_reg->off - smin_val; 12208 dst_reg->raw = ptr_reg->raw; 12209 break; 12210 } 12211 /* A new variable offset is created. If the subtrahend is known 12212 * nonnegative, then any reg->range we had before is still good. 12213 */ 12214 if (signed_sub_overflows(smin_ptr, smax_val) || 12215 signed_sub_overflows(smax_ptr, smin_val)) { 12216 /* Overflow possible, we know nothing */ 12217 dst_reg->smin_value = S64_MIN; 12218 dst_reg->smax_value = S64_MAX; 12219 } else { 12220 dst_reg->smin_value = smin_ptr - smax_val; 12221 dst_reg->smax_value = smax_ptr - smin_val; 12222 } 12223 if (umin_ptr < umax_val) { 12224 /* Overflow possible, we know nothing */ 12225 dst_reg->umin_value = 0; 12226 dst_reg->umax_value = U64_MAX; 12227 } else { 12228 /* Cannot overflow (as long as bounds are consistent) */ 12229 dst_reg->umin_value = umin_ptr - umax_val; 12230 dst_reg->umax_value = umax_ptr - umin_val; 12231 } 12232 dst_reg->var_off = tnum_sub(ptr_reg->var_off, off_reg->var_off); 12233 dst_reg->off = ptr_reg->off; 12234 dst_reg->raw = ptr_reg->raw; 12235 if (reg_is_pkt_pointer(ptr_reg)) { 12236 dst_reg->id = ++env->id_gen; 12237 /* something was added to pkt_ptr, set range to zero */ 12238 if (smin_val < 0) 12239 memset(&dst_reg->raw, 0, sizeof(dst_reg->raw)); 12240 } 12241 break; 12242 case BPF_AND: 12243 case BPF_OR: 12244 case BPF_XOR: 12245 /* bitwise ops on pointers are troublesome, prohibit. */ 12246 verbose(env, "R%d bitwise operator %s on pointer prohibited\n", 12247 dst, bpf_alu_string[opcode >> 4]); 12248 return -EACCES; 12249 default: 12250 /* other operators (e.g. MUL,LSH) produce non-pointer results */ 12251 verbose(env, "R%d pointer arithmetic with %s operator prohibited\n", 12252 dst, bpf_alu_string[opcode >> 4]); 12253 return -EACCES; 12254 } 12255 12256 if (!check_reg_sane_offset(env, dst_reg, ptr_reg->type)) 12257 return -EINVAL; 12258 reg_bounds_sync(dst_reg); 12259 if (sanitize_check_bounds(env, insn, dst_reg) < 0) 12260 return -EACCES; 12261 if (sanitize_needed(opcode)) { 12262 ret = sanitize_ptr_alu(env, insn, dst_reg, off_reg, dst_reg, 12263 &info, true); 12264 if (ret < 0) 12265 return sanitize_err(env, insn, ret, off_reg, dst_reg); 12266 } 12267 12268 return 0; 12269 } 12270 12271 static void scalar32_min_max_add(struct bpf_reg_state *dst_reg, 12272 struct bpf_reg_state *src_reg) 12273 { 12274 s32 smin_val = src_reg->s32_min_value; 12275 s32 smax_val = src_reg->s32_max_value; 12276 u32 umin_val = src_reg->u32_min_value; 12277 u32 umax_val = src_reg->u32_max_value; 12278 12279 if (signed_add32_overflows(dst_reg->s32_min_value, smin_val) || 12280 signed_add32_overflows(dst_reg->s32_max_value, smax_val)) { 12281 dst_reg->s32_min_value = S32_MIN; 12282 dst_reg->s32_max_value = S32_MAX; 12283 } else { 12284 dst_reg->s32_min_value += smin_val; 12285 dst_reg->s32_max_value += smax_val; 12286 } 12287 if (dst_reg->u32_min_value + umin_val < umin_val || 12288 dst_reg->u32_max_value + umax_val < umax_val) { 12289 dst_reg->u32_min_value = 0; 12290 dst_reg->u32_max_value = U32_MAX; 12291 } else { 12292 dst_reg->u32_min_value += umin_val; 12293 dst_reg->u32_max_value += umax_val; 12294 } 12295 } 12296 12297 static void scalar_min_max_add(struct bpf_reg_state *dst_reg, 12298 struct bpf_reg_state *src_reg) 12299 { 12300 s64 smin_val = src_reg->smin_value; 12301 s64 smax_val = src_reg->smax_value; 12302 u64 umin_val = src_reg->umin_value; 12303 u64 umax_val = src_reg->umax_value; 12304 12305 if (signed_add_overflows(dst_reg->smin_value, smin_val) || 12306 signed_add_overflows(dst_reg->smax_value, smax_val)) { 12307 dst_reg->smin_value = S64_MIN; 12308 dst_reg->smax_value = S64_MAX; 12309 } else { 12310 dst_reg->smin_value += smin_val; 12311 dst_reg->smax_value += smax_val; 12312 } 12313 if (dst_reg->umin_value + umin_val < umin_val || 12314 dst_reg->umax_value + umax_val < umax_val) { 12315 dst_reg->umin_value = 0; 12316 dst_reg->umax_value = U64_MAX; 12317 } else { 12318 dst_reg->umin_value += umin_val; 12319 dst_reg->umax_value += umax_val; 12320 } 12321 } 12322 12323 static void scalar32_min_max_sub(struct bpf_reg_state *dst_reg, 12324 struct bpf_reg_state *src_reg) 12325 { 12326 s32 smin_val = src_reg->s32_min_value; 12327 s32 smax_val = src_reg->s32_max_value; 12328 u32 umin_val = src_reg->u32_min_value; 12329 u32 umax_val = src_reg->u32_max_value; 12330 12331 if (signed_sub32_overflows(dst_reg->s32_min_value, smax_val) || 12332 signed_sub32_overflows(dst_reg->s32_max_value, smin_val)) { 12333 /* Overflow possible, we know nothing */ 12334 dst_reg->s32_min_value = S32_MIN; 12335 dst_reg->s32_max_value = S32_MAX; 12336 } else { 12337 dst_reg->s32_min_value -= smax_val; 12338 dst_reg->s32_max_value -= smin_val; 12339 } 12340 if (dst_reg->u32_min_value < umax_val) { 12341 /* Overflow possible, we know nothing */ 12342 dst_reg->u32_min_value = 0; 12343 dst_reg->u32_max_value = U32_MAX; 12344 } else { 12345 /* Cannot overflow (as long as bounds are consistent) */ 12346 dst_reg->u32_min_value -= umax_val; 12347 dst_reg->u32_max_value -= umin_val; 12348 } 12349 } 12350 12351 static void scalar_min_max_sub(struct bpf_reg_state *dst_reg, 12352 struct bpf_reg_state *src_reg) 12353 { 12354 s64 smin_val = src_reg->smin_value; 12355 s64 smax_val = src_reg->smax_value; 12356 u64 umin_val = src_reg->umin_value; 12357 u64 umax_val = src_reg->umax_value; 12358 12359 if (signed_sub_overflows(dst_reg->smin_value, smax_val) || 12360 signed_sub_overflows(dst_reg->smax_value, smin_val)) { 12361 /* Overflow possible, we know nothing */ 12362 dst_reg->smin_value = S64_MIN; 12363 dst_reg->smax_value = S64_MAX; 12364 } else { 12365 dst_reg->smin_value -= smax_val; 12366 dst_reg->smax_value -= smin_val; 12367 } 12368 if (dst_reg->umin_value < umax_val) { 12369 /* Overflow possible, we know nothing */ 12370 dst_reg->umin_value = 0; 12371 dst_reg->umax_value = U64_MAX; 12372 } else { 12373 /* Cannot overflow (as long as bounds are consistent) */ 12374 dst_reg->umin_value -= umax_val; 12375 dst_reg->umax_value -= umin_val; 12376 } 12377 } 12378 12379 static void scalar32_min_max_mul(struct bpf_reg_state *dst_reg, 12380 struct bpf_reg_state *src_reg) 12381 { 12382 s32 smin_val = src_reg->s32_min_value; 12383 u32 umin_val = src_reg->u32_min_value; 12384 u32 umax_val = src_reg->u32_max_value; 12385 12386 if (smin_val < 0 || dst_reg->s32_min_value < 0) { 12387 /* Ain't nobody got time to multiply that sign */ 12388 __mark_reg32_unbounded(dst_reg); 12389 return; 12390 } 12391 /* Both values are positive, so we can work with unsigned and 12392 * copy the result to signed (unless it exceeds S32_MAX). 12393 */ 12394 if (umax_val > U16_MAX || dst_reg->u32_max_value > U16_MAX) { 12395 /* Potential overflow, we know nothing */ 12396 __mark_reg32_unbounded(dst_reg); 12397 return; 12398 } 12399 dst_reg->u32_min_value *= umin_val; 12400 dst_reg->u32_max_value *= umax_val; 12401 if (dst_reg->u32_max_value > S32_MAX) { 12402 /* Overflow possible, we know nothing */ 12403 dst_reg->s32_min_value = S32_MIN; 12404 dst_reg->s32_max_value = S32_MAX; 12405 } else { 12406 dst_reg->s32_min_value = dst_reg->u32_min_value; 12407 dst_reg->s32_max_value = dst_reg->u32_max_value; 12408 } 12409 } 12410 12411 static void scalar_min_max_mul(struct bpf_reg_state *dst_reg, 12412 struct bpf_reg_state *src_reg) 12413 { 12414 s64 smin_val = src_reg->smin_value; 12415 u64 umin_val = src_reg->umin_value; 12416 u64 umax_val = src_reg->umax_value; 12417 12418 if (smin_val < 0 || dst_reg->smin_value < 0) { 12419 /* Ain't nobody got time to multiply that sign */ 12420 __mark_reg64_unbounded(dst_reg); 12421 return; 12422 } 12423 /* Both values are positive, so we can work with unsigned and 12424 * copy the result to signed (unless it exceeds S64_MAX). 12425 */ 12426 if (umax_val > U32_MAX || dst_reg->umax_value > U32_MAX) { 12427 /* Potential overflow, we know nothing */ 12428 __mark_reg64_unbounded(dst_reg); 12429 return; 12430 } 12431 dst_reg->umin_value *= umin_val; 12432 dst_reg->umax_value *= umax_val; 12433 if (dst_reg->umax_value > S64_MAX) { 12434 /* Overflow possible, we know nothing */ 12435 dst_reg->smin_value = S64_MIN; 12436 dst_reg->smax_value = S64_MAX; 12437 } else { 12438 dst_reg->smin_value = dst_reg->umin_value; 12439 dst_reg->smax_value = dst_reg->umax_value; 12440 } 12441 } 12442 12443 static void scalar32_min_max_and(struct bpf_reg_state *dst_reg, 12444 struct bpf_reg_state *src_reg) 12445 { 12446 bool src_known = tnum_subreg_is_const(src_reg->var_off); 12447 bool dst_known = tnum_subreg_is_const(dst_reg->var_off); 12448 struct tnum var32_off = tnum_subreg(dst_reg->var_off); 12449 s32 smin_val = src_reg->s32_min_value; 12450 u32 umax_val = src_reg->u32_max_value; 12451 12452 if (src_known && dst_known) { 12453 __mark_reg32_known(dst_reg, var32_off.value); 12454 return; 12455 } 12456 12457 /* We get our minimum from the var_off, since that's inherently 12458 * bitwise. Our maximum is the minimum of the operands' maxima. 12459 */ 12460 dst_reg->u32_min_value = var32_off.value; 12461 dst_reg->u32_max_value = min(dst_reg->u32_max_value, umax_val); 12462 if (dst_reg->s32_min_value < 0 || smin_val < 0) { 12463 /* Lose signed bounds when ANDing negative numbers, 12464 * ain't nobody got time for that. 12465 */ 12466 dst_reg->s32_min_value = S32_MIN; 12467 dst_reg->s32_max_value = S32_MAX; 12468 } else { 12469 /* ANDing two positives gives a positive, so safe to 12470 * cast result into s64. 12471 */ 12472 dst_reg->s32_min_value = dst_reg->u32_min_value; 12473 dst_reg->s32_max_value = dst_reg->u32_max_value; 12474 } 12475 } 12476 12477 static void scalar_min_max_and(struct bpf_reg_state *dst_reg, 12478 struct bpf_reg_state *src_reg) 12479 { 12480 bool src_known = tnum_is_const(src_reg->var_off); 12481 bool dst_known = tnum_is_const(dst_reg->var_off); 12482 s64 smin_val = src_reg->smin_value; 12483 u64 umax_val = src_reg->umax_value; 12484 12485 if (src_known && dst_known) { 12486 __mark_reg_known(dst_reg, dst_reg->var_off.value); 12487 return; 12488 } 12489 12490 /* We get our minimum from the var_off, since that's inherently 12491 * bitwise. Our maximum is the minimum of the operands' maxima. 12492 */ 12493 dst_reg->umin_value = dst_reg->var_off.value; 12494 dst_reg->umax_value = min(dst_reg->umax_value, umax_val); 12495 if (dst_reg->smin_value < 0 || smin_val < 0) { 12496 /* Lose signed bounds when ANDing negative numbers, 12497 * ain't nobody got time for that. 12498 */ 12499 dst_reg->smin_value = S64_MIN; 12500 dst_reg->smax_value = S64_MAX; 12501 } else { 12502 /* ANDing two positives gives a positive, so safe to 12503 * cast result into s64. 12504 */ 12505 dst_reg->smin_value = dst_reg->umin_value; 12506 dst_reg->smax_value = dst_reg->umax_value; 12507 } 12508 /* We may learn something more from the var_off */ 12509 __update_reg_bounds(dst_reg); 12510 } 12511 12512 static void scalar32_min_max_or(struct bpf_reg_state *dst_reg, 12513 struct bpf_reg_state *src_reg) 12514 { 12515 bool src_known = tnum_subreg_is_const(src_reg->var_off); 12516 bool dst_known = tnum_subreg_is_const(dst_reg->var_off); 12517 struct tnum var32_off = tnum_subreg(dst_reg->var_off); 12518 s32 smin_val = src_reg->s32_min_value; 12519 u32 umin_val = src_reg->u32_min_value; 12520 12521 if (src_known && dst_known) { 12522 __mark_reg32_known(dst_reg, var32_off.value); 12523 return; 12524 } 12525 12526 /* We get our maximum from the var_off, and our minimum is the 12527 * maximum of the operands' minima 12528 */ 12529 dst_reg->u32_min_value = max(dst_reg->u32_min_value, umin_val); 12530 dst_reg->u32_max_value = var32_off.value | var32_off.mask; 12531 if (dst_reg->s32_min_value < 0 || smin_val < 0) { 12532 /* Lose signed bounds when ORing negative numbers, 12533 * ain't nobody got time for that. 12534 */ 12535 dst_reg->s32_min_value = S32_MIN; 12536 dst_reg->s32_max_value = S32_MAX; 12537 } else { 12538 /* ORing two positives gives a positive, so safe to 12539 * cast result into s64. 12540 */ 12541 dst_reg->s32_min_value = dst_reg->u32_min_value; 12542 dst_reg->s32_max_value = dst_reg->u32_max_value; 12543 } 12544 } 12545 12546 static void scalar_min_max_or(struct bpf_reg_state *dst_reg, 12547 struct bpf_reg_state *src_reg) 12548 { 12549 bool src_known = tnum_is_const(src_reg->var_off); 12550 bool dst_known = tnum_is_const(dst_reg->var_off); 12551 s64 smin_val = src_reg->smin_value; 12552 u64 umin_val = src_reg->umin_value; 12553 12554 if (src_known && dst_known) { 12555 __mark_reg_known(dst_reg, dst_reg->var_off.value); 12556 return; 12557 } 12558 12559 /* We get our maximum from the var_off, and our minimum is the 12560 * maximum of the operands' minima 12561 */ 12562 dst_reg->umin_value = max(dst_reg->umin_value, umin_val); 12563 dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask; 12564 if (dst_reg->smin_value < 0 || smin_val < 0) { 12565 /* Lose signed bounds when ORing negative numbers, 12566 * ain't nobody got time for that. 12567 */ 12568 dst_reg->smin_value = S64_MIN; 12569 dst_reg->smax_value = S64_MAX; 12570 } else { 12571 /* ORing two positives gives a positive, so safe to 12572 * cast result into s64. 12573 */ 12574 dst_reg->smin_value = dst_reg->umin_value; 12575 dst_reg->smax_value = dst_reg->umax_value; 12576 } 12577 /* We may learn something more from the var_off */ 12578 __update_reg_bounds(dst_reg); 12579 } 12580 12581 static void scalar32_min_max_xor(struct bpf_reg_state *dst_reg, 12582 struct bpf_reg_state *src_reg) 12583 { 12584 bool src_known = tnum_subreg_is_const(src_reg->var_off); 12585 bool dst_known = tnum_subreg_is_const(dst_reg->var_off); 12586 struct tnum var32_off = tnum_subreg(dst_reg->var_off); 12587 s32 smin_val = src_reg->s32_min_value; 12588 12589 if (src_known && dst_known) { 12590 __mark_reg32_known(dst_reg, var32_off.value); 12591 return; 12592 } 12593 12594 /* We get both minimum and maximum from the var32_off. */ 12595 dst_reg->u32_min_value = var32_off.value; 12596 dst_reg->u32_max_value = var32_off.value | var32_off.mask; 12597 12598 if (dst_reg->s32_min_value >= 0 && smin_val >= 0) { 12599 /* XORing two positive sign numbers gives a positive, 12600 * so safe to cast u32 result into s32. 12601 */ 12602 dst_reg->s32_min_value = dst_reg->u32_min_value; 12603 dst_reg->s32_max_value = dst_reg->u32_max_value; 12604 } else { 12605 dst_reg->s32_min_value = S32_MIN; 12606 dst_reg->s32_max_value = S32_MAX; 12607 } 12608 } 12609 12610 static void scalar_min_max_xor(struct bpf_reg_state *dst_reg, 12611 struct bpf_reg_state *src_reg) 12612 { 12613 bool src_known = tnum_is_const(src_reg->var_off); 12614 bool dst_known = tnum_is_const(dst_reg->var_off); 12615 s64 smin_val = src_reg->smin_value; 12616 12617 if (src_known && dst_known) { 12618 /* dst_reg->var_off.value has been updated earlier */ 12619 __mark_reg_known(dst_reg, dst_reg->var_off.value); 12620 return; 12621 } 12622 12623 /* We get both minimum and maximum from the var_off. */ 12624 dst_reg->umin_value = dst_reg->var_off.value; 12625 dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask; 12626 12627 if (dst_reg->smin_value >= 0 && smin_val >= 0) { 12628 /* XORing two positive sign numbers gives a positive, 12629 * so safe to cast u64 result into s64. 12630 */ 12631 dst_reg->smin_value = dst_reg->umin_value; 12632 dst_reg->smax_value = dst_reg->umax_value; 12633 } else { 12634 dst_reg->smin_value = S64_MIN; 12635 dst_reg->smax_value = S64_MAX; 12636 } 12637 12638 __update_reg_bounds(dst_reg); 12639 } 12640 12641 static void __scalar32_min_max_lsh(struct bpf_reg_state *dst_reg, 12642 u64 umin_val, u64 umax_val) 12643 { 12644 /* We lose all sign bit information (except what we can pick 12645 * up from var_off) 12646 */ 12647 dst_reg->s32_min_value = S32_MIN; 12648 dst_reg->s32_max_value = S32_MAX; 12649 /* If we might shift our top bit out, then we know nothing */ 12650 if (umax_val > 31 || dst_reg->u32_max_value > 1ULL << (31 - umax_val)) { 12651 dst_reg->u32_min_value = 0; 12652 dst_reg->u32_max_value = U32_MAX; 12653 } else { 12654 dst_reg->u32_min_value <<= umin_val; 12655 dst_reg->u32_max_value <<= umax_val; 12656 } 12657 } 12658 12659 static void scalar32_min_max_lsh(struct bpf_reg_state *dst_reg, 12660 struct bpf_reg_state *src_reg) 12661 { 12662 u32 umax_val = src_reg->u32_max_value; 12663 u32 umin_val = src_reg->u32_min_value; 12664 /* u32 alu operation will zext upper bits */ 12665 struct tnum subreg = tnum_subreg(dst_reg->var_off); 12666 12667 __scalar32_min_max_lsh(dst_reg, umin_val, umax_val); 12668 dst_reg->var_off = tnum_subreg(tnum_lshift(subreg, umin_val)); 12669 /* Not required but being careful mark reg64 bounds as unknown so 12670 * that we are forced to pick them up from tnum and zext later and 12671 * if some path skips this step we are still safe. 12672 */ 12673 __mark_reg64_unbounded(dst_reg); 12674 __update_reg32_bounds(dst_reg); 12675 } 12676 12677 static void __scalar64_min_max_lsh(struct bpf_reg_state *dst_reg, 12678 u64 umin_val, u64 umax_val) 12679 { 12680 /* Special case <<32 because it is a common compiler pattern to sign 12681 * extend subreg by doing <<32 s>>32. In this case if 32bit bounds are 12682 * positive we know this shift will also be positive so we can track 12683 * bounds correctly. Otherwise we lose all sign bit information except 12684 * what we can pick up from var_off. Perhaps we can generalize this 12685 * later to shifts of any length. 12686 */ 12687 if (umin_val == 32 && umax_val == 32 && dst_reg->s32_max_value >= 0) 12688 dst_reg->smax_value = (s64)dst_reg->s32_max_value << 32; 12689 else 12690 dst_reg->smax_value = S64_MAX; 12691 12692 if (umin_val == 32 && umax_val == 32 && dst_reg->s32_min_value >= 0) 12693 dst_reg->smin_value = (s64)dst_reg->s32_min_value << 32; 12694 else 12695 dst_reg->smin_value = S64_MIN; 12696 12697 /* If we might shift our top bit out, then we know nothing */ 12698 if (dst_reg->umax_value > 1ULL << (63 - umax_val)) { 12699 dst_reg->umin_value = 0; 12700 dst_reg->umax_value = U64_MAX; 12701 } else { 12702 dst_reg->umin_value <<= umin_val; 12703 dst_reg->umax_value <<= umax_val; 12704 } 12705 } 12706 12707 static void scalar_min_max_lsh(struct bpf_reg_state *dst_reg, 12708 struct bpf_reg_state *src_reg) 12709 { 12710 u64 umax_val = src_reg->umax_value; 12711 u64 umin_val = src_reg->umin_value; 12712 12713 /* scalar64 calc uses 32bit unshifted bounds so must be called first */ 12714 __scalar64_min_max_lsh(dst_reg, umin_val, umax_val); 12715 __scalar32_min_max_lsh(dst_reg, umin_val, umax_val); 12716 12717 dst_reg->var_off = tnum_lshift(dst_reg->var_off, umin_val); 12718 /* We may learn something more from the var_off */ 12719 __update_reg_bounds(dst_reg); 12720 } 12721 12722 static void scalar32_min_max_rsh(struct bpf_reg_state *dst_reg, 12723 struct bpf_reg_state *src_reg) 12724 { 12725 struct tnum subreg = tnum_subreg(dst_reg->var_off); 12726 u32 umax_val = src_reg->u32_max_value; 12727 u32 umin_val = src_reg->u32_min_value; 12728 12729 /* BPF_RSH is an unsigned shift. If the value in dst_reg might 12730 * be negative, then either: 12731 * 1) src_reg might be zero, so the sign bit of the result is 12732 * unknown, so we lose our signed bounds 12733 * 2) it's known negative, thus the unsigned bounds capture the 12734 * signed bounds 12735 * 3) the signed bounds cross zero, so they tell us nothing 12736 * about the result 12737 * If the value in dst_reg is known nonnegative, then again the 12738 * unsigned bounds capture the signed bounds. 12739 * Thus, in all cases it suffices to blow away our signed bounds 12740 * and rely on inferring new ones from the unsigned bounds and 12741 * var_off of the result. 12742 */ 12743 dst_reg->s32_min_value = S32_MIN; 12744 dst_reg->s32_max_value = S32_MAX; 12745 12746 dst_reg->var_off = tnum_rshift(subreg, umin_val); 12747 dst_reg->u32_min_value >>= umax_val; 12748 dst_reg->u32_max_value >>= umin_val; 12749 12750 __mark_reg64_unbounded(dst_reg); 12751 __update_reg32_bounds(dst_reg); 12752 } 12753 12754 static void scalar_min_max_rsh(struct bpf_reg_state *dst_reg, 12755 struct bpf_reg_state *src_reg) 12756 { 12757 u64 umax_val = src_reg->umax_value; 12758 u64 umin_val = src_reg->umin_value; 12759 12760 /* BPF_RSH is an unsigned shift. If the value in dst_reg might 12761 * be negative, then either: 12762 * 1) src_reg might be zero, so the sign bit of the result is 12763 * unknown, so we lose our signed bounds 12764 * 2) it's known negative, thus the unsigned bounds capture the 12765 * signed bounds 12766 * 3) the signed bounds cross zero, so they tell us nothing 12767 * about the result 12768 * If the value in dst_reg is known nonnegative, then again the 12769 * unsigned bounds capture the signed bounds. 12770 * Thus, in all cases it suffices to blow away our signed bounds 12771 * and rely on inferring new ones from the unsigned bounds and 12772 * var_off of the result. 12773 */ 12774 dst_reg->smin_value = S64_MIN; 12775 dst_reg->smax_value = S64_MAX; 12776 dst_reg->var_off = tnum_rshift(dst_reg->var_off, umin_val); 12777 dst_reg->umin_value >>= umax_val; 12778 dst_reg->umax_value >>= umin_val; 12779 12780 /* Its not easy to operate on alu32 bounds here because it depends 12781 * on bits being shifted in. Take easy way out and mark unbounded 12782 * so we can recalculate later from tnum. 12783 */ 12784 __mark_reg32_unbounded(dst_reg); 12785 __update_reg_bounds(dst_reg); 12786 } 12787 12788 static void scalar32_min_max_arsh(struct bpf_reg_state *dst_reg, 12789 struct bpf_reg_state *src_reg) 12790 { 12791 u64 umin_val = src_reg->u32_min_value; 12792 12793 /* Upon reaching here, src_known is true and 12794 * umax_val is equal to umin_val. 12795 */ 12796 dst_reg->s32_min_value = (u32)(((s32)dst_reg->s32_min_value) >> umin_val); 12797 dst_reg->s32_max_value = (u32)(((s32)dst_reg->s32_max_value) >> umin_val); 12798 12799 dst_reg->var_off = tnum_arshift(tnum_subreg(dst_reg->var_off), umin_val, 32); 12800 12801 /* blow away the dst_reg umin_value/umax_value and rely on 12802 * dst_reg var_off to refine the result. 12803 */ 12804 dst_reg->u32_min_value = 0; 12805 dst_reg->u32_max_value = U32_MAX; 12806 12807 __mark_reg64_unbounded(dst_reg); 12808 __update_reg32_bounds(dst_reg); 12809 } 12810 12811 static void scalar_min_max_arsh(struct bpf_reg_state *dst_reg, 12812 struct bpf_reg_state *src_reg) 12813 { 12814 u64 umin_val = src_reg->umin_value; 12815 12816 /* Upon reaching here, src_known is true and umax_val is equal 12817 * to umin_val. 12818 */ 12819 dst_reg->smin_value >>= umin_val; 12820 dst_reg->smax_value >>= umin_val; 12821 12822 dst_reg->var_off = tnum_arshift(dst_reg->var_off, umin_val, 64); 12823 12824 /* blow away the dst_reg umin_value/umax_value and rely on 12825 * dst_reg var_off to refine the result. 12826 */ 12827 dst_reg->umin_value = 0; 12828 dst_reg->umax_value = U64_MAX; 12829 12830 /* Its not easy to operate on alu32 bounds here because it depends 12831 * on bits being shifted in from upper 32-bits. Take easy way out 12832 * and mark unbounded so we can recalculate later from tnum. 12833 */ 12834 __mark_reg32_unbounded(dst_reg); 12835 __update_reg_bounds(dst_reg); 12836 } 12837 12838 /* WARNING: This function does calculations on 64-bit values, but the actual 12839 * execution may occur on 32-bit values. Therefore, things like bitshifts 12840 * need extra checks in the 32-bit case. 12841 */ 12842 static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env, 12843 struct bpf_insn *insn, 12844 struct bpf_reg_state *dst_reg, 12845 struct bpf_reg_state src_reg) 12846 { 12847 struct bpf_reg_state *regs = cur_regs(env); 12848 u8 opcode = BPF_OP(insn->code); 12849 bool src_known; 12850 s64 smin_val, smax_val; 12851 u64 umin_val, umax_val; 12852 s32 s32_min_val, s32_max_val; 12853 u32 u32_min_val, u32_max_val; 12854 u64 insn_bitness = (BPF_CLASS(insn->code) == BPF_ALU64) ? 64 : 32; 12855 bool alu32 = (BPF_CLASS(insn->code) != BPF_ALU64); 12856 int ret; 12857 12858 smin_val = src_reg.smin_value; 12859 smax_val = src_reg.smax_value; 12860 umin_val = src_reg.umin_value; 12861 umax_val = src_reg.umax_value; 12862 12863 s32_min_val = src_reg.s32_min_value; 12864 s32_max_val = src_reg.s32_max_value; 12865 u32_min_val = src_reg.u32_min_value; 12866 u32_max_val = src_reg.u32_max_value; 12867 12868 if (alu32) { 12869 src_known = tnum_subreg_is_const(src_reg.var_off); 12870 if ((src_known && 12871 (s32_min_val != s32_max_val || u32_min_val != u32_max_val)) || 12872 s32_min_val > s32_max_val || u32_min_val > u32_max_val) { 12873 /* Taint dst register if offset had invalid bounds 12874 * derived from e.g. dead branches. 12875 */ 12876 __mark_reg_unknown(env, dst_reg); 12877 return 0; 12878 } 12879 } else { 12880 src_known = tnum_is_const(src_reg.var_off); 12881 if ((src_known && 12882 (smin_val != smax_val || umin_val != umax_val)) || 12883 smin_val > smax_val || umin_val > umax_val) { 12884 /* Taint dst register if offset had invalid bounds 12885 * derived from e.g. dead branches. 12886 */ 12887 __mark_reg_unknown(env, dst_reg); 12888 return 0; 12889 } 12890 } 12891 12892 if (!src_known && 12893 opcode != BPF_ADD && opcode != BPF_SUB && opcode != BPF_AND) { 12894 __mark_reg_unknown(env, dst_reg); 12895 return 0; 12896 } 12897 12898 if (sanitize_needed(opcode)) { 12899 ret = sanitize_val_alu(env, insn); 12900 if (ret < 0) 12901 return sanitize_err(env, insn, ret, NULL, NULL); 12902 } 12903 12904 /* Calculate sign/unsigned bounds and tnum for alu32 and alu64 bit ops. 12905 * There are two classes of instructions: The first class we track both 12906 * alu32 and alu64 sign/unsigned bounds independently this provides the 12907 * greatest amount of precision when alu operations are mixed with jmp32 12908 * operations. These operations are BPF_ADD, BPF_SUB, BPF_MUL, BPF_ADD, 12909 * and BPF_OR. This is possible because these ops have fairly easy to 12910 * understand and calculate behavior in both 32-bit and 64-bit alu ops. 12911 * See alu32 verifier tests for examples. The second class of 12912 * operations, BPF_LSH, BPF_RSH, and BPF_ARSH, however are not so easy 12913 * with regards to tracking sign/unsigned bounds because the bits may 12914 * cross subreg boundaries in the alu64 case. When this happens we mark 12915 * the reg unbounded in the subreg bound space and use the resulting 12916 * tnum to calculate an approximation of the sign/unsigned bounds. 12917 */ 12918 switch (opcode) { 12919 case BPF_ADD: 12920 scalar32_min_max_add(dst_reg, &src_reg); 12921 scalar_min_max_add(dst_reg, &src_reg); 12922 dst_reg->var_off = tnum_add(dst_reg->var_off, src_reg.var_off); 12923 break; 12924 case BPF_SUB: 12925 scalar32_min_max_sub(dst_reg, &src_reg); 12926 scalar_min_max_sub(dst_reg, &src_reg); 12927 dst_reg->var_off = tnum_sub(dst_reg->var_off, src_reg.var_off); 12928 break; 12929 case BPF_MUL: 12930 dst_reg->var_off = tnum_mul(dst_reg->var_off, src_reg.var_off); 12931 scalar32_min_max_mul(dst_reg, &src_reg); 12932 scalar_min_max_mul(dst_reg, &src_reg); 12933 break; 12934 case BPF_AND: 12935 dst_reg->var_off = tnum_and(dst_reg->var_off, src_reg.var_off); 12936 scalar32_min_max_and(dst_reg, &src_reg); 12937 scalar_min_max_and(dst_reg, &src_reg); 12938 break; 12939 case BPF_OR: 12940 dst_reg->var_off = tnum_or(dst_reg->var_off, src_reg.var_off); 12941 scalar32_min_max_or(dst_reg, &src_reg); 12942 scalar_min_max_or(dst_reg, &src_reg); 12943 break; 12944 case BPF_XOR: 12945 dst_reg->var_off = tnum_xor(dst_reg->var_off, src_reg.var_off); 12946 scalar32_min_max_xor(dst_reg, &src_reg); 12947 scalar_min_max_xor(dst_reg, &src_reg); 12948 break; 12949 case BPF_LSH: 12950 if (umax_val >= insn_bitness) { 12951 /* Shifts greater than 31 or 63 are undefined. 12952 * This includes shifts by a negative number. 12953 */ 12954 mark_reg_unknown(env, regs, insn->dst_reg); 12955 break; 12956 } 12957 if (alu32) 12958 scalar32_min_max_lsh(dst_reg, &src_reg); 12959 else 12960 scalar_min_max_lsh(dst_reg, &src_reg); 12961 break; 12962 case BPF_RSH: 12963 if (umax_val >= insn_bitness) { 12964 /* Shifts greater than 31 or 63 are undefined. 12965 * This includes shifts by a negative number. 12966 */ 12967 mark_reg_unknown(env, regs, insn->dst_reg); 12968 break; 12969 } 12970 if (alu32) 12971 scalar32_min_max_rsh(dst_reg, &src_reg); 12972 else 12973 scalar_min_max_rsh(dst_reg, &src_reg); 12974 break; 12975 case BPF_ARSH: 12976 if (umax_val >= insn_bitness) { 12977 /* Shifts greater than 31 or 63 are undefined. 12978 * This includes shifts by a negative number. 12979 */ 12980 mark_reg_unknown(env, regs, insn->dst_reg); 12981 break; 12982 } 12983 if (alu32) 12984 scalar32_min_max_arsh(dst_reg, &src_reg); 12985 else 12986 scalar_min_max_arsh(dst_reg, &src_reg); 12987 break; 12988 default: 12989 mark_reg_unknown(env, regs, insn->dst_reg); 12990 break; 12991 } 12992 12993 /* ALU32 ops are zero extended into 64bit register */ 12994 if (alu32) 12995 zext_32_to_64(dst_reg); 12996 reg_bounds_sync(dst_reg); 12997 return 0; 12998 } 12999 13000 /* Handles ALU ops other than BPF_END, BPF_NEG and BPF_MOV: computes new min/max 13001 * and var_off. 13002 */ 13003 static int adjust_reg_min_max_vals(struct bpf_verifier_env *env, 13004 struct bpf_insn *insn) 13005 { 13006 struct bpf_verifier_state *vstate = env->cur_state; 13007 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 13008 struct bpf_reg_state *regs = state->regs, *dst_reg, *src_reg; 13009 struct bpf_reg_state *ptr_reg = NULL, off_reg = {0}; 13010 u8 opcode = BPF_OP(insn->code); 13011 int err; 13012 13013 dst_reg = ®s[insn->dst_reg]; 13014 src_reg = NULL; 13015 if (dst_reg->type != SCALAR_VALUE) 13016 ptr_reg = dst_reg; 13017 else 13018 /* Make sure ID is cleared otherwise dst_reg min/max could be 13019 * incorrectly propagated into other registers by find_equal_scalars() 13020 */ 13021 dst_reg->id = 0; 13022 if (BPF_SRC(insn->code) == BPF_X) { 13023 src_reg = ®s[insn->src_reg]; 13024 if (src_reg->type != SCALAR_VALUE) { 13025 if (dst_reg->type != SCALAR_VALUE) { 13026 /* Combining two pointers by any ALU op yields 13027 * an arbitrary scalar. Disallow all math except 13028 * pointer subtraction 13029 */ 13030 if (opcode == BPF_SUB && env->allow_ptr_leaks) { 13031 mark_reg_unknown(env, regs, insn->dst_reg); 13032 return 0; 13033 } 13034 verbose(env, "R%d pointer %s pointer prohibited\n", 13035 insn->dst_reg, 13036 bpf_alu_string[opcode >> 4]); 13037 return -EACCES; 13038 } else { 13039 /* scalar += pointer 13040 * This is legal, but we have to reverse our 13041 * src/dest handling in computing the range 13042 */ 13043 err = mark_chain_precision(env, insn->dst_reg); 13044 if (err) 13045 return err; 13046 return adjust_ptr_min_max_vals(env, insn, 13047 src_reg, dst_reg); 13048 } 13049 } else if (ptr_reg) { 13050 /* pointer += scalar */ 13051 err = mark_chain_precision(env, insn->src_reg); 13052 if (err) 13053 return err; 13054 return adjust_ptr_min_max_vals(env, insn, 13055 dst_reg, src_reg); 13056 } else if (dst_reg->precise) { 13057 /* if dst_reg is precise, src_reg should be precise as well */ 13058 err = mark_chain_precision(env, insn->src_reg); 13059 if (err) 13060 return err; 13061 } 13062 } else { 13063 /* Pretend the src is a reg with a known value, since we only 13064 * need to be able to read from this state. 13065 */ 13066 off_reg.type = SCALAR_VALUE; 13067 __mark_reg_known(&off_reg, insn->imm); 13068 src_reg = &off_reg; 13069 if (ptr_reg) /* pointer += K */ 13070 return adjust_ptr_min_max_vals(env, insn, 13071 ptr_reg, src_reg); 13072 } 13073 13074 /* Got here implies adding two SCALAR_VALUEs */ 13075 if (WARN_ON_ONCE(ptr_reg)) { 13076 print_verifier_state(env, state, true); 13077 verbose(env, "verifier internal error: unexpected ptr_reg\n"); 13078 return -EINVAL; 13079 } 13080 if (WARN_ON(!src_reg)) { 13081 print_verifier_state(env, state, true); 13082 verbose(env, "verifier internal error: no src_reg\n"); 13083 return -EINVAL; 13084 } 13085 return adjust_scalar_min_max_vals(env, insn, dst_reg, *src_reg); 13086 } 13087 13088 /* check validity of 32-bit and 64-bit arithmetic operations */ 13089 static int check_alu_op(struct bpf_verifier_env *env, struct bpf_insn *insn) 13090 { 13091 struct bpf_reg_state *regs = cur_regs(env); 13092 u8 opcode = BPF_OP(insn->code); 13093 int err; 13094 13095 if (opcode == BPF_END || opcode == BPF_NEG) { 13096 if (opcode == BPF_NEG) { 13097 if (BPF_SRC(insn->code) != BPF_K || 13098 insn->src_reg != BPF_REG_0 || 13099 insn->off != 0 || insn->imm != 0) { 13100 verbose(env, "BPF_NEG uses reserved fields\n"); 13101 return -EINVAL; 13102 } 13103 } else { 13104 if (insn->src_reg != BPF_REG_0 || insn->off != 0 || 13105 (insn->imm != 16 && insn->imm != 32 && insn->imm != 64) || 13106 (BPF_CLASS(insn->code) == BPF_ALU64 && 13107 BPF_SRC(insn->code) != BPF_TO_LE)) { 13108 verbose(env, "BPF_END uses reserved fields\n"); 13109 return -EINVAL; 13110 } 13111 } 13112 13113 /* check src operand */ 13114 err = check_reg_arg(env, insn->dst_reg, SRC_OP); 13115 if (err) 13116 return err; 13117 13118 if (is_pointer_value(env, insn->dst_reg)) { 13119 verbose(env, "R%d pointer arithmetic prohibited\n", 13120 insn->dst_reg); 13121 return -EACCES; 13122 } 13123 13124 /* check dest operand */ 13125 err = check_reg_arg(env, insn->dst_reg, DST_OP); 13126 if (err) 13127 return err; 13128 13129 } else if (opcode == BPF_MOV) { 13130 13131 if (BPF_SRC(insn->code) == BPF_X) { 13132 if (insn->imm != 0) { 13133 verbose(env, "BPF_MOV uses reserved fields\n"); 13134 return -EINVAL; 13135 } 13136 13137 if (BPF_CLASS(insn->code) == BPF_ALU) { 13138 if (insn->off != 0 && insn->off != 8 && insn->off != 16) { 13139 verbose(env, "BPF_MOV uses reserved fields\n"); 13140 return -EINVAL; 13141 } 13142 } else { 13143 if (insn->off != 0 && insn->off != 8 && insn->off != 16 && 13144 insn->off != 32) { 13145 verbose(env, "BPF_MOV uses reserved fields\n"); 13146 return -EINVAL; 13147 } 13148 } 13149 13150 /* check src operand */ 13151 err = check_reg_arg(env, insn->src_reg, SRC_OP); 13152 if (err) 13153 return err; 13154 } else { 13155 if (insn->src_reg != BPF_REG_0 || insn->off != 0) { 13156 verbose(env, "BPF_MOV uses reserved fields\n"); 13157 return -EINVAL; 13158 } 13159 } 13160 13161 /* check dest operand, mark as required later */ 13162 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK); 13163 if (err) 13164 return err; 13165 13166 if (BPF_SRC(insn->code) == BPF_X) { 13167 struct bpf_reg_state *src_reg = regs + insn->src_reg; 13168 struct bpf_reg_state *dst_reg = regs + insn->dst_reg; 13169 bool need_id = src_reg->type == SCALAR_VALUE && !src_reg->id && 13170 !tnum_is_const(src_reg->var_off); 13171 13172 if (BPF_CLASS(insn->code) == BPF_ALU64) { 13173 if (insn->off == 0) { 13174 /* case: R1 = R2 13175 * copy register state to dest reg 13176 */ 13177 if (need_id) 13178 /* Assign src and dst registers the same ID 13179 * that will be used by find_equal_scalars() 13180 * to propagate min/max range. 13181 */ 13182 src_reg->id = ++env->id_gen; 13183 copy_register_state(dst_reg, src_reg); 13184 dst_reg->live |= REG_LIVE_WRITTEN; 13185 dst_reg->subreg_def = DEF_NOT_SUBREG; 13186 } else { 13187 /* case: R1 = (s8, s16 s32)R2 */ 13188 if (is_pointer_value(env, insn->src_reg)) { 13189 verbose(env, 13190 "R%d sign-extension part of pointer\n", 13191 insn->src_reg); 13192 return -EACCES; 13193 } else if (src_reg->type == SCALAR_VALUE) { 13194 bool no_sext; 13195 13196 no_sext = src_reg->umax_value < (1ULL << (insn->off - 1)); 13197 if (no_sext && need_id) 13198 src_reg->id = ++env->id_gen; 13199 copy_register_state(dst_reg, src_reg); 13200 if (!no_sext) 13201 dst_reg->id = 0; 13202 coerce_reg_to_size_sx(dst_reg, insn->off >> 3); 13203 dst_reg->live |= REG_LIVE_WRITTEN; 13204 dst_reg->subreg_def = DEF_NOT_SUBREG; 13205 } else { 13206 mark_reg_unknown(env, regs, insn->dst_reg); 13207 } 13208 } 13209 } else { 13210 /* R1 = (u32) R2 */ 13211 if (is_pointer_value(env, insn->src_reg)) { 13212 verbose(env, 13213 "R%d partial copy of pointer\n", 13214 insn->src_reg); 13215 return -EACCES; 13216 } else if (src_reg->type == SCALAR_VALUE) { 13217 if (insn->off == 0) { 13218 bool is_src_reg_u32 = src_reg->umax_value <= U32_MAX; 13219 13220 if (is_src_reg_u32 && need_id) 13221 src_reg->id = ++env->id_gen; 13222 copy_register_state(dst_reg, src_reg); 13223 /* Make sure ID is cleared if src_reg is not in u32 13224 * range otherwise dst_reg min/max could be incorrectly 13225 * propagated into src_reg by find_equal_scalars() 13226 */ 13227 if (!is_src_reg_u32) 13228 dst_reg->id = 0; 13229 dst_reg->live |= REG_LIVE_WRITTEN; 13230 dst_reg->subreg_def = env->insn_idx + 1; 13231 } else { 13232 /* case: W1 = (s8, s16)W2 */ 13233 bool no_sext = src_reg->umax_value < (1ULL << (insn->off - 1)); 13234 13235 if (no_sext && need_id) 13236 src_reg->id = ++env->id_gen; 13237 copy_register_state(dst_reg, src_reg); 13238 if (!no_sext) 13239 dst_reg->id = 0; 13240 dst_reg->live |= REG_LIVE_WRITTEN; 13241 dst_reg->subreg_def = env->insn_idx + 1; 13242 coerce_subreg_to_size_sx(dst_reg, insn->off >> 3); 13243 } 13244 } else { 13245 mark_reg_unknown(env, regs, 13246 insn->dst_reg); 13247 } 13248 zext_32_to_64(dst_reg); 13249 reg_bounds_sync(dst_reg); 13250 } 13251 } else { 13252 /* case: R = imm 13253 * remember the value we stored into this reg 13254 */ 13255 /* clear any state __mark_reg_known doesn't set */ 13256 mark_reg_unknown(env, regs, insn->dst_reg); 13257 regs[insn->dst_reg].type = SCALAR_VALUE; 13258 if (BPF_CLASS(insn->code) == BPF_ALU64) { 13259 __mark_reg_known(regs + insn->dst_reg, 13260 insn->imm); 13261 } else { 13262 __mark_reg_known(regs + insn->dst_reg, 13263 (u32)insn->imm); 13264 } 13265 } 13266 13267 } else if (opcode > BPF_END) { 13268 verbose(env, "invalid BPF_ALU opcode %x\n", opcode); 13269 return -EINVAL; 13270 13271 } else { /* all other ALU ops: and, sub, xor, add, ... */ 13272 13273 if (BPF_SRC(insn->code) == BPF_X) { 13274 if (insn->imm != 0 || insn->off > 1 || 13275 (insn->off == 1 && opcode != BPF_MOD && opcode != BPF_DIV)) { 13276 verbose(env, "BPF_ALU uses reserved fields\n"); 13277 return -EINVAL; 13278 } 13279 /* check src1 operand */ 13280 err = check_reg_arg(env, insn->src_reg, SRC_OP); 13281 if (err) 13282 return err; 13283 } else { 13284 if (insn->src_reg != BPF_REG_0 || insn->off > 1 || 13285 (insn->off == 1 && opcode != BPF_MOD && opcode != BPF_DIV)) { 13286 verbose(env, "BPF_ALU uses reserved fields\n"); 13287 return -EINVAL; 13288 } 13289 } 13290 13291 /* check src2 operand */ 13292 err = check_reg_arg(env, insn->dst_reg, SRC_OP); 13293 if (err) 13294 return err; 13295 13296 if ((opcode == BPF_MOD || opcode == BPF_DIV) && 13297 BPF_SRC(insn->code) == BPF_K && insn->imm == 0) { 13298 verbose(env, "div by zero\n"); 13299 return -EINVAL; 13300 } 13301 13302 if ((opcode == BPF_LSH || opcode == BPF_RSH || 13303 opcode == BPF_ARSH) && BPF_SRC(insn->code) == BPF_K) { 13304 int size = BPF_CLASS(insn->code) == BPF_ALU64 ? 64 : 32; 13305 13306 if (insn->imm < 0 || insn->imm >= size) { 13307 verbose(env, "invalid shift %d\n", insn->imm); 13308 return -EINVAL; 13309 } 13310 } 13311 13312 /* check dest operand */ 13313 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK); 13314 if (err) 13315 return err; 13316 13317 return adjust_reg_min_max_vals(env, insn); 13318 } 13319 13320 return 0; 13321 } 13322 13323 static void find_good_pkt_pointers(struct bpf_verifier_state *vstate, 13324 struct bpf_reg_state *dst_reg, 13325 enum bpf_reg_type type, 13326 bool range_right_open) 13327 { 13328 struct bpf_func_state *state; 13329 struct bpf_reg_state *reg; 13330 int new_range; 13331 13332 if (dst_reg->off < 0 || 13333 (dst_reg->off == 0 && range_right_open)) 13334 /* This doesn't give us any range */ 13335 return; 13336 13337 if (dst_reg->umax_value > MAX_PACKET_OFF || 13338 dst_reg->umax_value + dst_reg->off > MAX_PACKET_OFF) 13339 /* Risk of overflow. For instance, ptr + (1<<63) may be less 13340 * than pkt_end, but that's because it's also less than pkt. 13341 */ 13342 return; 13343 13344 new_range = dst_reg->off; 13345 if (range_right_open) 13346 new_range++; 13347 13348 /* Examples for register markings: 13349 * 13350 * pkt_data in dst register: 13351 * 13352 * r2 = r3; 13353 * r2 += 8; 13354 * if (r2 > pkt_end) goto <handle exception> 13355 * <access okay> 13356 * 13357 * r2 = r3; 13358 * r2 += 8; 13359 * if (r2 < pkt_end) goto <access okay> 13360 * <handle exception> 13361 * 13362 * Where: 13363 * r2 == dst_reg, pkt_end == src_reg 13364 * r2=pkt(id=n,off=8,r=0) 13365 * r3=pkt(id=n,off=0,r=0) 13366 * 13367 * pkt_data in src register: 13368 * 13369 * r2 = r3; 13370 * r2 += 8; 13371 * if (pkt_end >= r2) goto <access okay> 13372 * <handle exception> 13373 * 13374 * r2 = r3; 13375 * r2 += 8; 13376 * if (pkt_end <= r2) goto <handle exception> 13377 * <access okay> 13378 * 13379 * Where: 13380 * pkt_end == dst_reg, r2 == src_reg 13381 * r2=pkt(id=n,off=8,r=0) 13382 * r3=pkt(id=n,off=0,r=0) 13383 * 13384 * Find register r3 and mark its range as r3=pkt(id=n,off=0,r=8) 13385 * or r3=pkt(id=n,off=0,r=8-1), so that range of bytes [r3, r3 + 8) 13386 * and [r3, r3 + 8-1) respectively is safe to access depending on 13387 * the check. 13388 */ 13389 13390 /* If our ids match, then we must have the same max_value. And we 13391 * don't care about the other reg's fixed offset, since if it's too big 13392 * the range won't allow anything. 13393 * dst_reg->off is known < MAX_PACKET_OFF, therefore it fits in a u16. 13394 */ 13395 bpf_for_each_reg_in_vstate(vstate, state, reg, ({ 13396 if (reg->type == type && reg->id == dst_reg->id) 13397 /* keep the maximum range already checked */ 13398 reg->range = max(reg->range, new_range); 13399 })); 13400 } 13401 13402 static int is_branch32_taken(struct bpf_reg_state *reg, u32 val, u8 opcode) 13403 { 13404 struct tnum subreg = tnum_subreg(reg->var_off); 13405 s32 sval = (s32)val; 13406 13407 switch (opcode) { 13408 case BPF_JEQ: 13409 if (tnum_is_const(subreg)) 13410 return !!tnum_equals_const(subreg, val); 13411 else if (val < reg->u32_min_value || val > reg->u32_max_value) 13412 return 0; 13413 break; 13414 case BPF_JNE: 13415 if (tnum_is_const(subreg)) 13416 return !tnum_equals_const(subreg, val); 13417 else if (val < reg->u32_min_value || val > reg->u32_max_value) 13418 return 1; 13419 break; 13420 case BPF_JSET: 13421 if ((~subreg.mask & subreg.value) & val) 13422 return 1; 13423 if (!((subreg.mask | subreg.value) & val)) 13424 return 0; 13425 break; 13426 case BPF_JGT: 13427 if (reg->u32_min_value > val) 13428 return 1; 13429 else if (reg->u32_max_value <= val) 13430 return 0; 13431 break; 13432 case BPF_JSGT: 13433 if (reg->s32_min_value > sval) 13434 return 1; 13435 else if (reg->s32_max_value <= sval) 13436 return 0; 13437 break; 13438 case BPF_JLT: 13439 if (reg->u32_max_value < val) 13440 return 1; 13441 else if (reg->u32_min_value >= val) 13442 return 0; 13443 break; 13444 case BPF_JSLT: 13445 if (reg->s32_max_value < sval) 13446 return 1; 13447 else if (reg->s32_min_value >= sval) 13448 return 0; 13449 break; 13450 case BPF_JGE: 13451 if (reg->u32_min_value >= val) 13452 return 1; 13453 else if (reg->u32_max_value < val) 13454 return 0; 13455 break; 13456 case BPF_JSGE: 13457 if (reg->s32_min_value >= sval) 13458 return 1; 13459 else if (reg->s32_max_value < sval) 13460 return 0; 13461 break; 13462 case BPF_JLE: 13463 if (reg->u32_max_value <= val) 13464 return 1; 13465 else if (reg->u32_min_value > val) 13466 return 0; 13467 break; 13468 case BPF_JSLE: 13469 if (reg->s32_max_value <= sval) 13470 return 1; 13471 else if (reg->s32_min_value > sval) 13472 return 0; 13473 break; 13474 } 13475 13476 return -1; 13477 } 13478 13479 13480 static int is_branch64_taken(struct bpf_reg_state *reg, u64 val, u8 opcode) 13481 { 13482 s64 sval = (s64)val; 13483 13484 switch (opcode) { 13485 case BPF_JEQ: 13486 if (tnum_is_const(reg->var_off)) 13487 return !!tnum_equals_const(reg->var_off, val); 13488 else if (val < reg->umin_value || val > reg->umax_value) 13489 return 0; 13490 break; 13491 case BPF_JNE: 13492 if (tnum_is_const(reg->var_off)) 13493 return !tnum_equals_const(reg->var_off, val); 13494 else if (val < reg->umin_value || val > reg->umax_value) 13495 return 1; 13496 break; 13497 case BPF_JSET: 13498 if ((~reg->var_off.mask & reg->var_off.value) & val) 13499 return 1; 13500 if (!((reg->var_off.mask | reg->var_off.value) & val)) 13501 return 0; 13502 break; 13503 case BPF_JGT: 13504 if (reg->umin_value > val) 13505 return 1; 13506 else if (reg->umax_value <= val) 13507 return 0; 13508 break; 13509 case BPF_JSGT: 13510 if (reg->smin_value > sval) 13511 return 1; 13512 else if (reg->smax_value <= sval) 13513 return 0; 13514 break; 13515 case BPF_JLT: 13516 if (reg->umax_value < val) 13517 return 1; 13518 else if (reg->umin_value >= val) 13519 return 0; 13520 break; 13521 case BPF_JSLT: 13522 if (reg->smax_value < sval) 13523 return 1; 13524 else if (reg->smin_value >= sval) 13525 return 0; 13526 break; 13527 case BPF_JGE: 13528 if (reg->umin_value >= val) 13529 return 1; 13530 else if (reg->umax_value < val) 13531 return 0; 13532 break; 13533 case BPF_JSGE: 13534 if (reg->smin_value >= sval) 13535 return 1; 13536 else if (reg->smax_value < sval) 13537 return 0; 13538 break; 13539 case BPF_JLE: 13540 if (reg->umax_value <= val) 13541 return 1; 13542 else if (reg->umin_value > val) 13543 return 0; 13544 break; 13545 case BPF_JSLE: 13546 if (reg->smax_value <= sval) 13547 return 1; 13548 else if (reg->smin_value > sval) 13549 return 0; 13550 break; 13551 } 13552 13553 return -1; 13554 } 13555 13556 /* compute branch direction of the expression "if (reg opcode val) goto target;" 13557 * and return: 13558 * 1 - branch will be taken and "goto target" will be executed 13559 * 0 - branch will not be taken and fall-through to next insn 13560 * -1 - unknown. Example: "if (reg < 5)" is unknown when register value 13561 * range [0,10] 13562 */ 13563 static int is_branch_taken(struct bpf_reg_state *reg, u64 val, u8 opcode, 13564 bool is_jmp32) 13565 { 13566 if (__is_pointer_value(false, reg)) { 13567 if (!reg_not_null(reg)) 13568 return -1; 13569 13570 /* If pointer is valid tests against zero will fail so we can 13571 * use this to direct branch taken. 13572 */ 13573 if (val != 0) 13574 return -1; 13575 13576 switch (opcode) { 13577 case BPF_JEQ: 13578 return 0; 13579 case BPF_JNE: 13580 return 1; 13581 default: 13582 return -1; 13583 } 13584 } 13585 13586 if (is_jmp32) 13587 return is_branch32_taken(reg, val, opcode); 13588 return is_branch64_taken(reg, val, opcode); 13589 } 13590 13591 static int flip_opcode(u32 opcode) 13592 { 13593 /* How can we transform "a <op> b" into "b <op> a"? */ 13594 static const u8 opcode_flip[16] = { 13595 /* these stay the same */ 13596 [BPF_JEQ >> 4] = BPF_JEQ, 13597 [BPF_JNE >> 4] = BPF_JNE, 13598 [BPF_JSET >> 4] = BPF_JSET, 13599 /* these swap "lesser" and "greater" (L and G in the opcodes) */ 13600 [BPF_JGE >> 4] = BPF_JLE, 13601 [BPF_JGT >> 4] = BPF_JLT, 13602 [BPF_JLE >> 4] = BPF_JGE, 13603 [BPF_JLT >> 4] = BPF_JGT, 13604 [BPF_JSGE >> 4] = BPF_JSLE, 13605 [BPF_JSGT >> 4] = BPF_JSLT, 13606 [BPF_JSLE >> 4] = BPF_JSGE, 13607 [BPF_JSLT >> 4] = BPF_JSGT 13608 }; 13609 return opcode_flip[opcode >> 4]; 13610 } 13611 13612 static int is_pkt_ptr_branch_taken(struct bpf_reg_state *dst_reg, 13613 struct bpf_reg_state *src_reg, 13614 u8 opcode) 13615 { 13616 struct bpf_reg_state *pkt; 13617 13618 if (src_reg->type == PTR_TO_PACKET_END) { 13619 pkt = dst_reg; 13620 } else if (dst_reg->type == PTR_TO_PACKET_END) { 13621 pkt = src_reg; 13622 opcode = flip_opcode(opcode); 13623 } else { 13624 return -1; 13625 } 13626 13627 if (pkt->range >= 0) 13628 return -1; 13629 13630 switch (opcode) { 13631 case BPF_JLE: 13632 /* pkt <= pkt_end */ 13633 fallthrough; 13634 case BPF_JGT: 13635 /* pkt > pkt_end */ 13636 if (pkt->range == BEYOND_PKT_END) 13637 /* pkt has at last one extra byte beyond pkt_end */ 13638 return opcode == BPF_JGT; 13639 break; 13640 case BPF_JLT: 13641 /* pkt < pkt_end */ 13642 fallthrough; 13643 case BPF_JGE: 13644 /* pkt >= pkt_end */ 13645 if (pkt->range == BEYOND_PKT_END || pkt->range == AT_PKT_END) 13646 return opcode == BPF_JGE; 13647 break; 13648 } 13649 return -1; 13650 } 13651 13652 /* Adjusts the register min/max values in the case that the dst_reg is the 13653 * variable register that we are working on, and src_reg is a constant or we're 13654 * simply doing a BPF_K check. 13655 * In JEQ/JNE cases we also adjust the var_off values. 13656 */ 13657 static void reg_set_min_max(struct bpf_reg_state *true_reg, 13658 struct bpf_reg_state *false_reg, 13659 u64 val, u32 val32, 13660 u8 opcode, bool is_jmp32) 13661 { 13662 struct tnum false_32off = tnum_subreg(false_reg->var_off); 13663 struct tnum false_64off = false_reg->var_off; 13664 struct tnum true_32off = tnum_subreg(true_reg->var_off); 13665 struct tnum true_64off = true_reg->var_off; 13666 s64 sval = (s64)val; 13667 s32 sval32 = (s32)val32; 13668 13669 /* If the dst_reg is a pointer, we can't learn anything about its 13670 * variable offset from the compare (unless src_reg were a pointer into 13671 * the same object, but we don't bother with that. 13672 * Since false_reg and true_reg have the same type by construction, we 13673 * only need to check one of them for pointerness. 13674 */ 13675 if (__is_pointer_value(false, false_reg)) 13676 return; 13677 13678 switch (opcode) { 13679 /* JEQ/JNE comparison doesn't change the register equivalence. 13680 * 13681 * r1 = r2; 13682 * if (r1 == 42) goto label; 13683 * ... 13684 * label: // here both r1 and r2 are known to be 42. 13685 * 13686 * Hence when marking register as known preserve it's ID. 13687 */ 13688 case BPF_JEQ: 13689 if (is_jmp32) { 13690 __mark_reg32_known(true_reg, val32); 13691 true_32off = tnum_subreg(true_reg->var_off); 13692 } else { 13693 ___mark_reg_known(true_reg, val); 13694 true_64off = true_reg->var_off; 13695 } 13696 break; 13697 case BPF_JNE: 13698 if (is_jmp32) { 13699 __mark_reg32_known(false_reg, val32); 13700 false_32off = tnum_subreg(false_reg->var_off); 13701 } else { 13702 ___mark_reg_known(false_reg, val); 13703 false_64off = false_reg->var_off; 13704 } 13705 break; 13706 case BPF_JSET: 13707 if (is_jmp32) { 13708 false_32off = tnum_and(false_32off, tnum_const(~val32)); 13709 if (is_power_of_2(val32)) 13710 true_32off = tnum_or(true_32off, 13711 tnum_const(val32)); 13712 } else { 13713 false_64off = tnum_and(false_64off, tnum_const(~val)); 13714 if (is_power_of_2(val)) 13715 true_64off = tnum_or(true_64off, 13716 tnum_const(val)); 13717 } 13718 break; 13719 case BPF_JGE: 13720 case BPF_JGT: 13721 { 13722 if (is_jmp32) { 13723 u32 false_umax = opcode == BPF_JGT ? val32 : val32 - 1; 13724 u32 true_umin = opcode == BPF_JGT ? val32 + 1 : val32; 13725 13726 false_reg->u32_max_value = min(false_reg->u32_max_value, 13727 false_umax); 13728 true_reg->u32_min_value = max(true_reg->u32_min_value, 13729 true_umin); 13730 } else { 13731 u64 false_umax = opcode == BPF_JGT ? val : val - 1; 13732 u64 true_umin = opcode == BPF_JGT ? val + 1 : val; 13733 13734 false_reg->umax_value = min(false_reg->umax_value, false_umax); 13735 true_reg->umin_value = max(true_reg->umin_value, true_umin); 13736 } 13737 break; 13738 } 13739 case BPF_JSGE: 13740 case BPF_JSGT: 13741 { 13742 if (is_jmp32) { 13743 s32 false_smax = opcode == BPF_JSGT ? sval32 : sval32 - 1; 13744 s32 true_smin = opcode == BPF_JSGT ? sval32 + 1 : sval32; 13745 13746 false_reg->s32_max_value = min(false_reg->s32_max_value, false_smax); 13747 true_reg->s32_min_value = max(true_reg->s32_min_value, true_smin); 13748 } else { 13749 s64 false_smax = opcode == BPF_JSGT ? sval : sval - 1; 13750 s64 true_smin = opcode == BPF_JSGT ? sval + 1 : sval; 13751 13752 false_reg->smax_value = min(false_reg->smax_value, false_smax); 13753 true_reg->smin_value = max(true_reg->smin_value, true_smin); 13754 } 13755 break; 13756 } 13757 case BPF_JLE: 13758 case BPF_JLT: 13759 { 13760 if (is_jmp32) { 13761 u32 false_umin = opcode == BPF_JLT ? val32 : val32 + 1; 13762 u32 true_umax = opcode == BPF_JLT ? val32 - 1 : val32; 13763 13764 false_reg->u32_min_value = max(false_reg->u32_min_value, 13765 false_umin); 13766 true_reg->u32_max_value = min(true_reg->u32_max_value, 13767 true_umax); 13768 } else { 13769 u64 false_umin = opcode == BPF_JLT ? val : val + 1; 13770 u64 true_umax = opcode == BPF_JLT ? val - 1 : val; 13771 13772 false_reg->umin_value = max(false_reg->umin_value, false_umin); 13773 true_reg->umax_value = min(true_reg->umax_value, true_umax); 13774 } 13775 break; 13776 } 13777 case BPF_JSLE: 13778 case BPF_JSLT: 13779 { 13780 if (is_jmp32) { 13781 s32 false_smin = opcode == BPF_JSLT ? sval32 : sval32 + 1; 13782 s32 true_smax = opcode == BPF_JSLT ? sval32 - 1 : sval32; 13783 13784 false_reg->s32_min_value = max(false_reg->s32_min_value, false_smin); 13785 true_reg->s32_max_value = min(true_reg->s32_max_value, true_smax); 13786 } else { 13787 s64 false_smin = opcode == BPF_JSLT ? sval : sval + 1; 13788 s64 true_smax = opcode == BPF_JSLT ? sval - 1 : sval; 13789 13790 false_reg->smin_value = max(false_reg->smin_value, false_smin); 13791 true_reg->smax_value = min(true_reg->smax_value, true_smax); 13792 } 13793 break; 13794 } 13795 default: 13796 return; 13797 } 13798 13799 if (is_jmp32) { 13800 false_reg->var_off = tnum_or(tnum_clear_subreg(false_64off), 13801 tnum_subreg(false_32off)); 13802 true_reg->var_off = tnum_or(tnum_clear_subreg(true_64off), 13803 tnum_subreg(true_32off)); 13804 __reg_combine_32_into_64(false_reg); 13805 __reg_combine_32_into_64(true_reg); 13806 } else { 13807 false_reg->var_off = false_64off; 13808 true_reg->var_off = true_64off; 13809 __reg_combine_64_into_32(false_reg); 13810 __reg_combine_64_into_32(true_reg); 13811 } 13812 } 13813 13814 /* Same as above, but for the case that dst_reg holds a constant and src_reg is 13815 * the variable reg. 13816 */ 13817 static void reg_set_min_max_inv(struct bpf_reg_state *true_reg, 13818 struct bpf_reg_state *false_reg, 13819 u64 val, u32 val32, 13820 u8 opcode, bool is_jmp32) 13821 { 13822 opcode = flip_opcode(opcode); 13823 /* This uses zero as "not present in table"; luckily the zero opcode, 13824 * BPF_JA, can't get here. 13825 */ 13826 if (opcode) 13827 reg_set_min_max(true_reg, false_reg, val, val32, opcode, is_jmp32); 13828 } 13829 13830 /* Regs are known to be equal, so intersect their min/max/var_off */ 13831 static void __reg_combine_min_max(struct bpf_reg_state *src_reg, 13832 struct bpf_reg_state *dst_reg) 13833 { 13834 src_reg->umin_value = dst_reg->umin_value = max(src_reg->umin_value, 13835 dst_reg->umin_value); 13836 src_reg->umax_value = dst_reg->umax_value = min(src_reg->umax_value, 13837 dst_reg->umax_value); 13838 src_reg->smin_value = dst_reg->smin_value = max(src_reg->smin_value, 13839 dst_reg->smin_value); 13840 src_reg->smax_value = dst_reg->smax_value = min(src_reg->smax_value, 13841 dst_reg->smax_value); 13842 src_reg->var_off = dst_reg->var_off = tnum_intersect(src_reg->var_off, 13843 dst_reg->var_off); 13844 reg_bounds_sync(src_reg); 13845 reg_bounds_sync(dst_reg); 13846 } 13847 13848 static void reg_combine_min_max(struct bpf_reg_state *true_src, 13849 struct bpf_reg_state *true_dst, 13850 struct bpf_reg_state *false_src, 13851 struct bpf_reg_state *false_dst, 13852 u8 opcode) 13853 { 13854 switch (opcode) { 13855 case BPF_JEQ: 13856 __reg_combine_min_max(true_src, true_dst); 13857 break; 13858 case BPF_JNE: 13859 __reg_combine_min_max(false_src, false_dst); 13860 break; 13861 } 13862 } 13863 13864 static void mark_ptr_or_null_reg(struct bpf_func_state *state, 13865 struct bpf_reg_state *reg, u32 id, 13866 bool is_null) 13867 { 13868 if (type_may_be_null(reg->type) && reg->id == id && 13869 (is_rcu_reg(reg) || !WARN_ON_ONCE(!reg->id))) { 13870 /* Old offset (both fixed and variable parts) should have been 13871 * known-zero, because we don't allow pointer arithmetic on 13872 * pointers that might be NULL. If we see this happening, don't 13873 * convert the register. 13874 * 13875 * But in some cases, some helpers that return local kptrs 13876 * advance offset for the returned pointer. In those cases, it 13877 * is fine to expect to see reg->off. 13878 */ 13879 if (WARN_ON_ONCE(reg->smin_value || reg->smax_value || !tnum_equals_const(reg->var_off, 0))) 13880 return; 13881 if (!(type_is_ptr_alloc_obj(reg->type) || type_is_non_owning_ref(reg->type)) && 13882 WARN_ON_ONCE(reg->off)) 13883 return; 13884 13885 if (is_null) { 13886 reg->type = SCALAR_VALUE; 13887 /* We don't need id and ref_obj_id from this point 13888 * onwards anymore, thus we should better reset it, 13889 * so that state pruning has chances to take effect. 13890 */ 13891 reg->id = 0; 13892 reg->ref_obj_id = 0; 13893 13894 return; 13895 } 13896 13897 mark_ptr_not_null_reg(reg); 13898 13899 if (!reg_may_point_to_spin_lock(reg)) { 13900 /* For not-NULL ptr, reg->ref_obj_id will be reset 13901 * in release_reference(). 13902 * 13903 * reg->id is still used by spin_lock ptr. Other 13904 * than spin_lock ptr type, reg->id can be reset. 13905 */ 13906 reg->id = 0; 13907 } 13908 } 13909 } 13910 13911 /* The logic is similar to find_good_pkt_pointers(), both could eventually 13912 * be folded together at some point. 13913 */ 13914 static void mark_ptr_or_null_regs(struct bpf_verifier_state *vstate, u32 regno, 13915 bool is_null) 13916 { 13917 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 13918 struct bpf_reg_state *regs = state->regs, *reg; 13919 u32 ref_obj_id = regs[regno].ref_obj_id; 13920 u32 id = regs[regno].id; 13921 13922 if (ref_obj_id && ref_obj_id == id && is_null) 13923 /* regs[regno] is in the " == NULL" branch. 13924 * No one could have freed the reference state before 13925 * doing the NULL check. 13926 */ 13927 WARN_ON_ONCE(release_reference_state(state, id)); 13928 13929 bpf_for_each_reg_in_vstate(vstate, state, reg, ({ 13930 mark_ptr_or_null_reg(state, reg, id, is_null); 13931 })); 13932 } 13933 13934 static bool try_match_pkt_pointers(const struct bpf_insn *insn, 13935 struct bpf_reg_state *dst_reg, 13936 struct bpf_reg_state *src_reg, 13937 struct bpf_verifier_state *this_branch, 13938 struct bpf_verifier_state *other_branch) 13939 { 13940 if (BPF_SRC(insn->code) != BPF_X) 13941 return false; 13942 13943 /* Pointers are always 64-bit. */ 13944 if (BPF_CLASS(insn->code) == BPF_JMP32) 13945 return false; 13946 13947 switch (BPF_OP(insn->code)) { 13948 case BPF_JGT: 13949 if ((dst_reg->type == PTR_TO_PACKET && 13950 src_reg->type == PTR_TO_PACKET_END) || 13951 (dst_reg->type == PTR_TO_PACKET_META && 13952 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) { 13953 /* pkt_data' > pkt_end, pkt_meta' > pkt_data */ 13954 find_good_pkt_pointers(this_branch, dst_reg, 13955 dst_reg->type, false); 13956 mark_pkt_end(other_branch, insn->dst_reg, true); 13957 } else if ((dst_reg->type == PTR_TO_PACKET_END && 13958 src_reg->type == PTR_TO_PACKET) || 13959 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) && 13960 src_reg->type == PTR_TO_PACKET_META)) { 13961 /* pkt_end > pkt_data', pkt_data > pkt_meta' */ 13962 find_good_pkt_pointers(other_branch, src_reg, 13963 src_reg->type, true); 13964 mark_pkt_end(this_branch, insn->src_reg, false); 13965 } else { 13966 return false; 13967 } 13968 break; 13969 case BPF_JLT: 13970 if ((dst_reg->type == PTR_TO_PACKET && 13971 src_reg->type == PTR_TO_PACKET_END) || 13972 (dst_reg->type == PTR_TO_PACKET_META && 13973 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) { 13974 /* pkt_data' < pkt_end, pkt_meta' < pkt_data */ 13975 find_good_pkt_pointers(other_branch, dst_reg, 13976 dst_reg->type, true); 13977 mark_pkt_end(this_branch, insn->dst_reg, false); 13978 } else if ((dst_reg->type == PTR_TO_PACKET_END && 13979 src_reg->type == PTR_TO_PACKET) || 13980 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) && 13981 src_reg->type == PTR_TO_PACKET_META)) { 13982 /* pkt_end < pkt_data', pkt_data > pkt_meta' */ 13983 find_good_pkt_pointers(this_branch, src_reg, 13984 src_reg->type, false); 13985 mark_pkt_end(other_branch, insn->src_reg, true); 13986 } else { 13987 return false; 13988 } 13989 break; 13990 case BPF_JGE: 13991 if ((dst_reg->type == PTR_TO_PACKET && 13992 src_reg->type == PTR_TO_PACKET_END) || 13993 (dst_reg->type == PTR_TO_PACKET_META && 13994 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) { 13995 /* pkt_data' >= pkt_end, pkt_meta' >= pkt_data */ 13996 find_good_pkt_pointers(this_branch, dst_reg, 13997 dst_reg->type, true); 13998 mark_pkt_end(other_branch, insn->dst_reg, false); 13999 } else if ((dst_reg->type == PTR_TO_PACKET_END && 14000 src_reg->type == PTR_TO_PACKET) || 14001 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) && 14002 src_reg->type == PTR_TO_PACKET_META)) { 14003 /* pkt_end >= pkt_data', pkt_data >= pkt_meta' */ 14004 find_good_pkt_pointers(other_branch, src_reg, 14005 src_reg->type, false); 14006 mark_pkt_end(this_branch, insn->src_reg, true); 14007 } else { 14008 return false; 14009 } 14010 break; 14011 case BPF_JLE: 14012 if ((dst_reg->type == PTR_TO_PACKET && 14013 src_reg->type == PTR_TO_PACKET_END) || 14014 (dst_reg->type == PTR_TO_PACKET_META && 14015 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) { 14016 /* pkt_data' <= pkt_end, pkt_meta' <= pkt_data */ 14017 find_good_pkt_pointers(other_branch, dst_reg, 14018 dst_reg->type, false); 14019 mark_pkt_end(this_branch, insn->dst_reg, true); 14020 } else if ((dst_reg->type == PTR_TO_PACKET_END && 14021 src_reg->type == PTR_TO_PACKET) || 14022 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) && 14023 src_reg->type == PTR_TO_PACKET_META)) { 14024 /* pkt_end <= pkt_data', pkt_data <= pkt_meta' */ 14025 find_good_pkt_pointers(this_branch, src_reg, 14026 src_reg->type, true); 14027 mark_pkt_end(other_branch, insn->src_reg, false); 14028 } else { 14029 return false; 14030 } 14031 break; 14032 default: 14033 return false; 14034 } 14035 14036 return true; 14037 } 14038 14039 static void find_equal_scalars(struct bpf_verifier_state *vstate, 14040 struct bpf_reg_state *known_reg) 14041 { 14042 struct bpf_func_state *state; 14043 struct bpf_reg_state *reg; 14044 14045 bpf_for_each_reg_in_vstate(vstate, state, reg, ({ 14046 if (reg->type == SCALAR_VALUE && reg->id == known_reg->id) 14047 copy_register_state(reg, known_reg); 14048 })); 14049 } 14050 14051 static int check_cond_jmp_op(struct bpf_verifier_env *env, 14052 struct bpf_insn *insn, int *insn_idx) 14053 { 14054 struct bpf_verifier_state *this_branch = env->cur_state; 14055 struct bpf_verifier_state *other_branch; 14056 struct bpf_reg_state *regs = this_branch->frame[this_branch->curframe]->regs; 14057 struct bpf_reg_state *dst_reg, *other_branch_regs, *src_reg = NULL; 14058 struct bpf_reg_state *eq_branch_regs; 14059 u8 opcode = BPF_OP(insn->code); 14060 bool is_jmp32; 14061 int pred = -1; 14062 int err; 14063 14064 /* Only conditional jumps are expected to reach here. */ 14065 if (opcode == BPF_JA || opcode > BPF_JSLE) { 14066 verbose(env, "invalid BPF_JMP/JMP32 opcode %x\n", opcode); 14067 return -EINVAL; 14068 } 14069 14070 /* check src2 operand */ 14071 err = check_reg_arg(env, insn->dst_reg, SRC_OP); 14072 if (err) 14073 return err; 14074 14075 dst_reg = ®s[insn->dst_reg]; 14076 if (BPF_SRC(insn->code) == BPF_X) { 14077 if (insn->imm != 0) { 14078 verbose(env, "BPF_JMP/JMP32 uses reserved fields\n"); 14079 return -EINVAL; 14080 } 14081 14082 /* check src1 operand */ 14083 err = check_reg_arg(env, insn->src_reg, SRC_OP); 14084 if (err) 14085 return err; 14086 14087 src_reg = ®s[insn->src_reg]; 14088 if (!(reg_is_pkt_pointer_any(dst_reg) && reg_is_pkt_pointer_any(src_reg)) && 14089 is_pointer_value(env, insn->src_reg)) { 14090 verbose(env, "R%d pointer comparison prohibited\n", 14091 insn->src_reg); 14092 return -EACCES; 14093 } 14094 } else { 14095 if (insn->src_reg != BPF_REG_0) { 14096 verbose(env, "BPF_JMP/JMP32 uses reserved fields\n"); 14097 return -EINVAL; 14098 } 14099 } 14100 14101 is_jmp32 = BPF_CLASS(insn->code) == BPF_JMP32; 14102 14103 if (BPF_SRC(insn->code) == BPF_K) { 14104 pred = is_branch_taken(dst_reg, insn->imm, opcode, is_jmp32); 14105 } else if (src_reg->type == SCALAR_VALUE && 14106 is_jmp32 && tnum_is_const(tnum_subreg(src_reg->var_off))) { 14107 pred = is_branch_taken(dst_reg, 14108 tnum_subreg(src_reg->var_off).value, 14109 opcode, 14110 is_jmp32); 14111 } else if (src_reg->type == SCALAR_VALUE && 14112 !is_jmp32 && tnum_is_const(src_reg->var_off)) { 14113 pred = is_branch_taken(dst_reg, 14114 src_reg->var_off.value, 14115 opcode, 14116 is_jmp32); 14117 } else if (dst_reg->type == SCALAR_VALUE && 14118 is_jmp32 && tnum_is_const(tnum_subreg(dst_reg->var_off))) { 14119 pred = is_branch_taken(src_reg, 14120 tnum_subreg(dst_reg->var_off).value, 14121 flip_opcode(opcode), 14122 is_jmp32); 14123 } else if (dst_reg->type == SCALAR_VALUE && 14124 !is_jmp32 && tnum_is_const(dst_reg->var_off)) { 14125 pred = is_branch_taken(src_reg, 14126 dst_reg->var_off.value, 14127 flip_opcode(opcode), 14128 is_jmp32); 14129 } else if (reg_is_pkt_pointer_any(dst_reg) && 14130 reg_is_pkt_pointer_any(src_reg) && 14131 !is_jmp32) { 14132 pred = is_pkt_ptr_branch_taken(dst_reg, src_reg, opcode); 14133 } 14134 14135 if (pred >= 0) { 14136 /* If we get here with a dst_reg pointer type it is because 14137 * above is_branch_taken() special cased the 0 comparison. 14138 */ 14139 if (!__is_pointer_value(false, dst_reg)) 14140 err = mark_chain_precision(env, insn->dst_reg); 14141 if (BPF_SRC(insn->code) == BPF_X && !err && 14142 !__is_pointer_value(false, src_reg)) 14143 err = mark_chain_precision(env, insn->src_reg); 14144 if (err) 14145 return err; 14146 } 14147 14148 if (pred == 1) { 14149 /* Only follow the goto, ignore fall-through. If needed, push 14150 * the fall-through branch for simulation under speculative 14151 * execution. 14152 */ 14153 if (!env->bypass_spec_v1 && 14154 !sanitize_speculative_path(env, insn, *insn_idx + 1, 14155 *insn_idx)) 14156 return -EFAULT; 14157 if (env->log.level & BPF_LOG_LEVEL) 14158 print_insn_state(env, this_branch->frame[this_branch->curframe]); 14159 *insn_idx += insn->off; 14160 return 0; 14161 } else if (pred == 0) { 14162 /* Only follow the fall-through branch, since that's where the 14163 * program will go. If needed, push the goto branch for 14164 * simulation under speculative execution. 14165 */ 14166 if (!env->bypass_spec_v1 && 14167 !sanitize_speculative_path(env, insn, 14168 *insn_idx + insn->off + 1, 14169 *insn_idx)) 14170 return -EFAULT; 14171 if (env->log.level & BPF_LOG_LEVEL) 14172 print_insn_state(env, this_branch->frame[this_branch->curframe]); 14173 return 0; 14174 } 14175 14176 other_branch = push_stack(env, *insn_idx + insn->off + 1, *insn_idx, 14177 false); 14178 if (!other_branch) 14179 return -EFAULT; 14180 other_branch_regs = other_branch->frame[other_branch->curframe]->regs; 14181 14182 /* detect if we are comparing against a constant value so we can adjust 14183 * our min/max values for our dst register. 14184 * this is only legit if both are scalars (or pointers to the same 14185 * object, I suppose, see the PTR_MAYBE_NULL related if block below), 14186 * because otherwise the different base pointers mean the offsets aren't 14187 * comparable. 14188 */ 14189 if (BPF_SRC(insn->code) == BPF_X) { 14190 struct bpf_reg_state *src_reg = ®s[insn->src_reg]; 14191 14192 if (dst_reg->type == SCALAR_VALUE && 14193 src_reg->type == SCALAR_VALUE) { 14194 if (tnum_is_const(src_reg->var_off) || 14195 (is_jmp32 && 14196 tnum_is_const(tnum_subreg(src_reg->var_off)))) 14197 reg_set_min_max(&other_branch_regs[insn->dst_reg], 14198 dst_reg, 14199 src_reg->var_off.value, 14200 tnum_subreg(src_reg->var_off).value, 14201 opcode, is_jmp32); 14202 else if (tnum_is_const(dst_reg->var_off) || 14203 (is_jmp32 && 14204 tnum_is_const(tnum_subreg(dst_reg->var_off)))) 14205 reg_set_min_max_inv(&other_branch_regs[insn->src_reg], 14206 src_reg, 14207 dst_reg->var_off.value, 14208 tnum_subreg(dst_reg->var_off).value, 14209 opcode, is_jmp32); 14210 else if (!is_jmp32 && 14211 (opcode == BPF_JEQ || opcode == BPF_JNE)) 14212 /* Comparing for equality, we can combine knowledge */ 14213 reg_combine_min_max(&other_branch_regs[insn->src_reg], 14214 &other_branch_regs[insn->dst_reg], 14215 src_reg, dst_reg, opcode); 14216 if (src_reg->id && 14217 !WARN_ON_ONCE(src_reg->id != other_branch_regs[insn->src_reg].id)) { 14218 find_equal_scalars(this_branch, src_reg); 14219 find_equal_scalars(other_branch, &other_branch_regs[insn->src_reg]); 14220 } 14221 14222 } 14223 } else if (dst_reg->type == SCALAR_VALUE) { 14224 reg_set_min_max(&other_branch_regs[insn->dst_reg], 14225 dst_reg, insn->imm, (u32)insn->imm, 14226 opcode, is_jmp32); 14227 } 14228 14229 if (dst_reg->type == SCALAR_VALUE && dst_reg->id && 14230 !WARN_ON_ONCE(dst_reg->id != other_branch_regs[insn->dst_reg].id)) { 14231 find_equal_scalars(this_branch, dst_reg); 14232 find_equal_scalars(other_branch, &other_branch_regs[insn->dst_reg]); 14233 } 14234 14235 /* if one pointer register is compared to another pointer 14236 * register check if PTR_MAYBE_NULL could be lifted. 14237 * E.g. register A - maybe null 14238 * register B - not null 14239 * for JNE A, B, ... - A is not null in the false branch; 14240 * for JEQ A, B, ... - A is not null in the true branch. 14241 * 14242 * Since PTR_TO_BTF_ID points to a kernel struct that does 14243 * not need to be null checked by the BPF program, i.e., 14244 * could be null even without PTR_MAYBE_NULL marking, so 14245 * only propagate nullness when neither reg is that type. 14246 */ 14247 if (!is_jmp32 && BPF_SRC(insn->code) == BPF_X && 14248 __is_pointer_value(false, src_reg) && __is_pointer_value(false, dst_reg) && 14249 type_may_be_null(src_reg->type) != type_may_be_null(dst_reg->type) && 14250 base_type(src_reg->type) != PTR_TO_BTF_ID && 14251 base_type(dst_reg->type) != PTR_TO_BTF_ID) { 14252 eq_branch_regs = NULL; 14253 switch (opcode) { 14254 case BPF_JEQ: 14255 eq_branch_regs = other_branch_regs; 14256 break; 14257 case BPF_JNE: 14258 eq_branch_regs = regs; 14259 break; 14260 default: 14261 /* do nothing */ 14262 break; 14263 } 14264 if (eq_branch_regs) { 14265 if (type_may_be_null(src_reg->type)) 14266 mark_ptr_not_null_reg(&eq_branch_regs[insn->src_reg]); 14267 else 14268 mark_ptr_not_null_reg(&eq_branch_regs[insn->dst_reg]); 14269 } 14270 } 14271 14272 /* detect if R == 0 where R is returned from bpf_map_lookup_elem(). 14273 * NOTE: these optimizations below are related with pointer comparison 14274 * which will never be JMP32. 14275 */ 14276 if (!is_jmp32 && BPF_SRC(insn->code) == BPF_K && 14277 insn->imm == 0 && (opcode == BPF_JEQ || opcode == BPF_JNE) && 14278 type_may_be_null(dst_reg->type)) { 14279 /* Mark all identical registers in each branch as either 14280 * safe or unknown depending R == 0 or R != 0 conditional. 14281 */ 14282 mark_ptr_or_null_regs(this_branch, insn->dst_reg, 14283 opcode == BPF_JNE); 14284 mark_ptr_or_null_regs(other_branch, insn->dst_reg, 14285 opcode == BPF_JEQ); 14286 } else if (!try_match_pkt_pointers(insn, dst_reg, ®s[insn->src_reg], 14287 this_branch, other_branch) && 14288 is_pointer_value(env, insn->dst_reg)) { 14289 verbose(env, "R%d pointer comparison prohibited\n", 14290 insn->dst_reg); 14291 return -EACCES; 14292 } 14293 if (env->log.level & BPF_LOG_LEVEL) 14294 print_insn_state(env, this_branch->frame[this_branch->curframe]); 14295 return 0; 14296 } 14297 14298 /* verify BPF_LD_IMM64 instruction */ 14299 static int check_ld_imm(struct bpf_verifier_env *env, struct bpf_insn *insn) 14300 { 14301 struct bpf_insn_aux_data *aux = cur_aux(env); 14302 struct bpf_reg_state *regs = cur_regs(env); 14303 struct bpf_reg_state *dst_reg; 14304 struct bpf_map *map; 14305 int err; 14306 14307 if (BPF_SIZE(insn->code) != BPF_DW) { 14308 verbose(env, "invalid BPF_LD_IMM insn\n"); 14309 return -EINVAL; 14310 } 14311 if (insn->off != 0) { 14312 verbose(env, "BPF_LD_IMM64 uses reserved fields\n"); 14313 return -EINVAL; 14314 } 14315 14316 err = check_reg_arg(env, insn->dst_reg, DST_OP); 14317 if (err) 14318 return err; 14319 14320 dst_reg = ®s[insn->dst_reg]; 14321 if (insn->src_reg == 0) { 14322 u64 imm = ((u64)(insn + 1)->imm << 32) | (u32)insn->imm; 14323 14324 dst_reg->type = SCALAR_VALUE; 14325 __mark_reg_known(®s[insn->dst_reg], imm); 14326 return 0; 14327 } 14328 14329 /* All special src_reg cases are listed below. From this point onwards 14330 * we either succeed and assign a corresponding dst_reg->type after 14331 * zeroing the offset, or fail and reject the program. 14332 */ 14333 mark_reg_known_zero(env, regs, insn->dst_reg); 14334 14335 if (insn->src_reg == BPF_PSEUDO_BTF_ID) { 14336 dst_reg->type = aux->btf_var.reg_type; 14337 switch (base_type(dst_reg->type)) { 14338 case PTR_TO_MEM: 14339 dst_reg->mem_size = aux->btf_var.mem_size; 14340 break; 14341 case PTR_TO_BTF_ID: 14342 dst_reg->btf = aux->btf_var.btf; 14343 dst_reg->btf_id = aux->btf_var.btf_id; 14344 break; 14345 default: 14346 verbose(env, "bpf verifier is misconfigured\n"); 14347 return -EFAULT; 14348 } 14349 return 0; 14350 } 14351 14352 if (insn->src_reg == BPF_PSEUDO_FUNC) { 14353 struct bpf_prog_aux *aux = env->prog->aux; 14354 u32 subprogno = find_subprog(env, 14355 env->insn_idx + insn->imm + 1); 14356 14357 if (!aux->func_info) { 14358 verbose(env, "missing btf func_info\n"); 14359 return -EINVAL; 14360 } 14361 if (aux->func_info_aux[subprogno].linkage != BTF_FUNC_STATIC) { 14362 verbose(env, "callback function not static\n"); 14363 return -EINVAL; 14364 } 14365 14366 dst_reg->type = PTR_TO_FUNC; 14367 dst_reg->subprogno = subprogno; 14368 return 0; 14369 } 14370 14371 map = env->used_maps[aux->map_index]; 14372 dst_reg->map_ptr = map; 14373 14374 if (insn->src_reg == BPF_PSEUDO_MAP_VALUE || 14375 insn->src_reg == BPF_PSEUDO_MAP_IDX_VALUE) { 14376 dst_reg->type = PTR_TO_MAP_VALUE; 14377 dst_reg->off = aux->map_off; 14378 WARN_ON_ONCE(map->max_entries != 1); 14379 /* We want reg->id to be same (0) as map_value is not distinct */ 14380 } else if (insn->src_reg == BPF_PSEUDO_MAP_FD || 14381 insn->src_reg == BPF_PSEUDO_MAP_IDX) { 14382 dst_reg->type = CONST_PTR_TO_MAP; 14383 } else { 14384 verbose(env, "bpf verifier is misconfigured\n"); 14385 return -EINVAL; 14386 } 14387 14388 return 0; 14389 } 14390 14391 static bool may_access_skb(enum bpf_prog_type type) 14392 { 14393 switch (type) { 14394 case BPF_PROG_TYPE_SOCKET_FILTER: 14395 case BPF_PROG_TYPE_SCHED_CLS: 14396 case BPF_PROG_TYPE_SCHED_ACT: 14397 return true; 14398 default: 14399 return false; 14400 } 14401 } 14402 14403 /* verify safety of LD_ABS|LD_IND instructions: 14404 * - they can only appear in the programs where ctx == skb 14405 * - since they are wrappers of function calls, they scratch R1-R5 registers, 14406 * preserve R6-R9, and store return value into R0 14407 * 14408 * Implicit input: 14409 * ctx == skb == R6 == CTX 14410 * 14411 * Explicit input: 14412 * SRC == any register 14413 * IMM == 32-bit immediate 14414 * 14415 * Output: 14416 * R0 - 8/16/32-bit skb data converted to cpu endianness 14417 */ 14418 static int check_ld_abs(struct bpf_verifier_env *env, struct bpf_insn *insn) 14419 { 14420 struct bpf_reg_state *regs = cur_regs(env); 14421 static const int ctx_reg = BPF_REG_6; 14422 u8 mode = BPF_MODE(insn->code); 14423 int i, err; 14424 14425 if (!may_access_skb(resolve_prog_type(env->prog))) { 14426 verbose(env, "BPF_LD_[ABS|IND] instructions not allowed for this program type\n"); 14427 return -EINVAL; 14428 } 14429 14430 if (!env->ops->gen_ld_abs) { 14431 verbose(env, "bpf verifier is misconfigured\n"); 14432 return -EINVAL; 14433 } 14434 14435 if (insn->dst_reg != BPF_REG_0 || insn->off != 0 || 14436 BPF_SIZE(insn->code) == BPF_DW || 14437 (mode == BPF_ABS && insn->src_reg != BPF_REG_0)) { 14438 verbose(env, "BPF_LD_[ABS|IND] uses reserved fields\n"); 14439 return -EINVAL; 14440 } 14441 14442 /* check whether implicit source operand (register R6) is readable */ 14443 err = check_reg_arg(env, ctx_reg, SRC_OP); 14444 if (err) 14445 return err; 14446 14447 /* Disallow usage of BPF_LD_[ABS|IND] with reference tracking, as 14448 * gen_ld_abs() may terminate the program at runtime, leading to 14449 * reference leak. 14450 */ 14451 err = check_reference_leak(env); 14452 if (err) { 14453 verbose(env, "BPF_LD_[ABS|IND] cannot be mixed with socket references\n"); 14454 return err; 14455 } 14456 14457 if (env->cur_state->active_lock.ptr) { 14458 verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_spin_lock-ed region\n"); 14459 return -EINVAL; 14460 } 14461 14462 if (env->cur_state->active_rcu_lock) { 14463 verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_rcu_read_lock-ed region\n"); 14464 return -EINVAL; 14465 } 14466 14467 if (regs[ctx_reg].type != PTR_TO_CTX) { 14468 verbose(env, 14469 "at the time of BPF_LD_ABS|IND R6 != pointer to skb\n"); 14470 return -EINVAL; 14471 } 14472 14473 if (mode == BPF_IND) { 14474 /* check explicit source operand */ 14475 err = check_reg_arg(env, insn->src_reg, SRC_OP); 14476 if (err) 14477 return err; 14478 } 14479 14480 err = check_ptr_off_reg(env, ®s[ctx_reg], ctx_reg); 14481 if (err < 0) 14482 return err; 14483 14484 /* reset caller saved regs to unreadable */ 14485 for (i = 0; i < CALLER_SAVED_REGS; i++) { 14486 mark_reg_not_init(env, regs, caller_saved[i]); 14487 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK); 14488 } 14489 14490 /* mark destination R0 register as readable, since it contains 14491 * the value fetched from the packet. 14492 * Already marked as written above. 14493 */ 14494 mark_reg_unknown(env, regs, BPF_REG_0); 14495 /* ld_abs load up to 32-bit skb data. */ 14496 regs[BPF_REG_0].subreg_def = env->insn_idx + 1; 14497 return 0; 14498 } 14499 14500 static int check_return_code(struct bpf_verifier_env *env) 14501 { 14502 struct tnum enforce_attach_type_range = tnum_unknown; 14503 const struct bpf_prog *prog = env->prog; 14504 struct bpf_reg_state *reg; 14505 struct tnum range = tnum_range(0, 1), const_0 = tnum_const(0); 14506 enum bpf_prog_type prog_type = resolve_prog_type(env->prog); 14507 int err; 14508 struct bpf_func_state *frame = env->cur_state->frame[0]; 14509 const bool is_subprog = frame->subprogno; 14510 14511 /* LSM and struct_ops func-ptr's return type could be "void" */ 14512 if (!is_subprog) { 14513 switch (prog_type) { 14514 case BPF_PROG_TYPE_LSM: 14515 if (prog->expected_attach_type == BPF_LSM_CGROUP) 14516 /* See below, can be 0 or 0-1 depending on hook. */ 14517 break; 14518 fallthrough; 14519 case BPF_PROG_TYPE_STRUCT_OPS: 14520 if (!prog->aux->attach_func_proto->type) 14521 return 0; 14522 break; 14523 default: 14524 break; 14525 } 14526 } 14527 14528 /* eBPF calling convention is such that R0 is used 14529 * to return the value from eBPF program. 14530 * Make sure that it's readable at this time 14531 * of bpf_exit, which means that program wrote 14532 * something into it earlier 14533 */ 14534 err = check_reg_arg(env, BPF_REG_0, SRC_OP); 14535 if (err) 14536 return err; 14537 14538 if (is_pointer_value(env, BPF_REG_0)) { 14539 verbose(env, "R0 leaks addr as return value\n"); 14540 return -EACCES; 14541 } 14542 14543 reg = cur_regs(env) + BPF_REG_0; 14544 14545 if (frame->in_async_callback_fn) { 14546 /* enforce return zero from async callbacks like timer */ 14547 if (reg->type != SCALAR_VALUE) { 14548 verbose(env, "In async callback the register R0 is not a known value (%s)\n", 14549 reg_type_str(env, reg->type)); 14550 return -EINVAL; 14551 } 14552 14553 if (!tnum_in(const_0, reg->var_off)) { 14554 verbose_invalid_scalar(env, reg, &const_0, "async callback", "R0"); 14555 return -EINVAL; 14556 } 14557 return 0; 14558 } 14559 14560 if (is_subprog) { 14561 if (reg->type != SCALAR_VALUE) { 14562 verbose(env, "At subprogram exit the register R0 is not a scalar value (%s)\n", 14563 reg_type_str(env, reg->type)); 14564 return -EINVAL; 14565 } 14566 return 0; 14567 } 14568 14569 switch (prog_type) { 14570 case BPF_PROG_TYPE_CGROUP_SOCK_ADDR: 14571 if (env->prog->expected_attach_type == BPF_CGROUP_UDP4_RECVMSG || 14572 env->prog->expected_attach_type == BPF_CGROUP_UDP6_RECVMSG || 14573 env->prog->expected_attach_type == BPF_CGROUP_INET4_GETPEERNAME || 14574 env->prog->expected_attach_type == BPF_CGROUP_INET6_GETPEERNAME || 14575 env->prog->expected_attach_type == BPF_CGROUP_INET4_GETSOCKNAME || 14576 env->prog->expected_attach_type == BPF_CGROUP_INET6_GETSOCKNAME) 14577 range = tnum_range(1, 1); 14578 if (env->prog->expected_attach_type == BPF_CGROUP_INET4_BIND || 14579 env->prog->expected_attach_type == BPF_CGROUP_INET6_BIND) 14580 range = tnum_range(0, 3); 14581 break; 14582 case BPF_PROG_TYPE_CGROUP_SKB: 14583 if (env->prog->expected_attach_type == BPF_CGROUP_INET_EGRESS) { 14584 range = tnum_range(0, 3); 14585 enforce_attach_type_range = tnum_range(2, 3); 14586 } 14587 break; 14588 case BPF_PROG_TYPE_CGROUP_SOCK: 14589 case BPF_PROG_TYPE_SOCK_OPS: 14590 case BPF_PROG_TYPE_CGROUP_DEVICE: 14591 case BPF_PROG_TYPE_CGROUP_SYSCTL: 14592 case BPF_PROG_TYPE_CGROUP_SOCKOPT: 14593 break; 14594 case BPF_PROG_TYPE_RAW_TRACEPOINT: 14595 if (!env->prog->aux->attach_btf_id) 14596 return 0; 14597 range = tnum_const(0); 14598 break; 14599 case BPF_PROG_TYPE_TRACING: 14600 switch (env->prog->expected_attach_type) { 14601 case BPF_TRACE_FENTRY: 14602 case BPF_TRACE_FEXIT: 14603 range = tnum_const(0); 14604 break; 14605 case BPF_TRACE_RAW_TP: 14606 case BPF_MODIFY_RETURN: 14607 return 0; 14608 case BPF_TRACE_ITER: 14609 break; 14610 default: 14611 return -ENOTSUPP; 14612 } 14613 break; 14614 case BPF_PROG_TYPE_SK_LOOKUP: 14615 range = tnum_range(SK_DROP, SK_PASS); 14616 break; 14617 14618 case BPF_PROG_TYPE_LSM: 14619 if (env->prog->expected_attach_type != BPF_LSM_CGROUP) { 14620 /* Regular BPF_PROG_TYPE_LSM programs can return 14621 * any value. 14622 */ 14623 return 0; 14624 } 14625 if (!env->prog->aux->attach_func_proto->type) { 14626 /* Make sure programs that attach to void 14627 * hooks don't try to modify return value. 14628 */ 14629 range = tnum_range(1, 1); 14630 } 14631 break; 14632 14633 case BPF_PROG_TYPE_NETFILTER: 14634 range = tnum_range(NF_DROP, NF_ACCEPT); 14635 break; 14636 case BPF_PROG_TYPE_EXT: 14637 /* freplace program can return anything as its return value 14638 * depends on the to-be-replaced kernel func or bpf program. 14639 */ 14640 default: 14641 return 0; 14642 } 14643 14644 if (reg->type != SCALAR_VALUE) { 14645 verbose(env, "At program exit the register R0 is not a known value (%s)\n", 14646 reg_type_str(env, reg->type)); 14647 return -EINVAL; 14648 } 14649 14650 if (!tnum_in(range, reg->var_off)) { 14651 verbose_invalid_scalar(env, reg, &range, "program exit", "R0"); 14652 if (prog->expected_attach_type == BPF_LSM_CGROUP && 14653 prog_type == BPF_PROG_TYPE_LSM && 14654 !prog->aux->attach_func_proto->type) 14655 verbose(env, "Note, BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n"); 14656 return -EINVAL; 14657 } 14658 14659 if (!tnum_is_unknown(enforce_attach_type_range) && 14660 tnum_in(enforce_attach_type_range, reg->var_off)) 14661 env->prog->enforce_expected_attach_type = 1; 14662 return 0; 14663 } 14664 14665 /* non-recursive DFS pseudo code 14666 * 1 procedure DFS-iterative(G,v): 14667 * 2 label v as discovered 14668 * 3 let S be a stack 14669 * 4 S.push(v) 14670 * 5 while S is not empty 14671 * 6 t <- S.peek() 14672 * 7 if t is what we're looking for: 14673 * 8 return t 14674 * 9 for all edges e in G.adjacentEdges(t) do 14675 * 10 if edge e is already labelled 14676 * 11 continue with the next edge 14677 * 12 w <- G.adjacentVertex(t,e) 14678 * 13 if vertex w is not discovered and not explored 14679 * 14 label e as tree-edge 14680 * 15 label w as discovered 14681 * 16 S.push(w) 14682 * 17 continue at 5 14683 * 18 else if vertex w is discovered 14684 * 19 label e as back-edge 14685 * 20 else 14686 * 21 // vertex w is explored 14687 * 22 label e as forward- or cross-edge 14688 * 23 label t as explored 14689 * 24 S.pop() 14690 * 14691 * convention: 14692 * 0x10 - discovered 14693 * 0x11 - discovered and fall-through edge labelled 14694 * 0x12 - discovered and fall-through and branch edges labelled 14695 * 0x20 - explored 14696 */ 14697 14698 enum { 14699 DISCOVERED = 0x10, 14700 EXPLORED = 0x20, 14701 FALLTHROUGH = 1, 14702 BRANCH = 2, 14703 }; 14704 14705 static u32 state_htab_size(struct bpf_verifier_env *env) 14706 { 14707 return env->prog->len; 14708 } 14709 14710 static struct bpf_verifier_state_list **explored_state( 14711 struct bpf_verifier_env *env, 14712 int idx) 14713 { 14714 struct bpf_verifier_state *cur = env->cur_state; 14715 struct bpf_func_state *state = cur->frame[cur->curframe]; 14716 14717 return &env->explored_states[(idx ^ state->callsite) % state_htab_size(env)]; 14718 } 14719 14720 static void mark_prune_point(struct bpf_verifier_env *env, int idx) 14721 { 14722 env->insn_aux_data[idx].prune_point = true; 14723 } 14724 14725 static bool is_prune_point(struct bpf_verifier_env *env, int insn_idx) 14726 { 14727 return env->insn_aux_data[insn_idx].prune_point; 14728 } 14729 14730 static void mark_force_checkpoint(struct bpf_verifier_env *env, int idx) 14731 { 14732 env->insn_aux_data[idx].force_checkpoint = true; 14733 } 14734 14735 static bool is_force_checkpoint(struct bpf_verifier_env *env, int insn_idx) 14736 { 14737 return env->insn_aux_data[insn_idx].force_checkpoint; 14738 } 14739 14740 14741 enum { 14742 DONE_EXPLORING = 0, 14743 KEEP_EXPLORING = 1, 14744 }; 14745 14746 /* t, w, e - match pseudo-code above: 14747 * t - index of current instruction 14748 * w - next instruction 14749 * e - edge 14750 */ 14751 static int push_insn(int t, int w, int e, struct bpf_verifier_env *env) 14752 { 14753 int *insn_stack = env->cfg.insn_stack; 14754 int *insn_state = env->cfg.insn_state; 14755 14756 if (e == FALLTHROUGH && insn_state[t] >= (DISCOVERED | FALLTHROUGH)) 14757 return DONE_EXPLORING; 14758 14759 if (e == BRANCH && insn_state[t] >= (DISCOVERED | BRANCH)) 14760 return DONE_EXPLORING; 14761 14762 if (w < 0 || w >= env->prog->len) { 14763 verbose_linfo(env, t, "%d: ", t); 14764 verbose(env, "jump out of range from insn %d to %d\n", t, w); 14765 return -EINVAL; 14766 } 14767 14768 if (e == BRANCH) { 14769 /* mark branch target for state pruning */ 14770 mark_prune_point(env, w); 14771 mark_jmp_point(env, w); 14772 } 14773 14774 if (insn_state[w] == 0) { 14775 /* tree-edge */ 14776 insn_state[t] = DISCOVERED | e; 14777 insn_state[w] = DISCOVERED; 14778 if (env->cfg.cur_stack >= env->prog->len) 14779 return -E2BIG; 14780 insn_stack[env->cfg.cur_stack++] = w; 14781 return KEEP_EXPLORING; 14782 } else if ((insn_state[w] & 0xF0) == DISCOVERED) { 14783 if (env->bpf_capable) 14784 return DONE_EXPLORING; 14785 verbose_linfo(env, t, "%d: ", t); 14786 verbose_linfo(env, w, "%d: ", w); 14787 verbose(env, "back-edge from insn %d to %d\n", t, w); 14788 return -EINVAL; 14789 } else if (insn_state[w] == EXPLORED) { 14790 /* forward- or cross-edge */ 14791 insn_state[t] = DISCOVERED | e; 14792 } else { 14793 verbose(env, "insn state internal bug\n"); 14794 return -EFAULT; 14795 } 14796 return DONE_EXPLORING; 14797 } 14798 14799 static int visit_func_call_insn(int t, struct bpf_insn *insns, 14800 struct bpf_verifier_env *env, 14801 bool visit_callee) 14802 { 14803 int ret, insn_sz; 14804 14805 insn_sz = bpf_is_ldimm64(&insns[t]) ? 2 : 1; 14806 ret = push_insn(t, t + insn_sz, FALLTHROUGH, env); 14807 if (ret) 14808 return ret; 14809 14810 mark_prune_point(env, t + insn_sz); 14811 /* when we exit from subprog, we need to record non-linear history */ 14812 mark_jmp_point(env, t + insn_sz); 14813 14814 if (visit_callee) { 14815 mark_prune_point(env, t); 14816 ret = push_insn(t, t + insns[t].imm + 1, BRANCH, env); 14817 } 14818 return ret; 14819 } 14820 14821 /* Visits the instruction at index t and returns one of the following: 14822 * < 0 - an error occurred 14823 * DONE_EXPLORING - the instruction was fully explored 14824 * KEEP_EXPLORING - there is still work to be done before it is fully explored 14825 */ 14826 static int visit_insn(int t, struct bpf_verifier_env *env) 14827 { 14828 struct bpf_insn *insns = env->prog->insnsi, *insn = &insns[t]; 14829 int ret, off, insn_sz; 14830 14831 if (bpf_pseudo_func(insn)) 14832 return visit_func_call_insn(t, insns, env, true); 14833 14834 /* All non-branch instructions have a single fall-through edge. */ 14835 if (BPF_CLASS(insn->code) != BPF_JMP && 14836 BPF_CLASS(insn->code) != BPF_JMP32) { 14837 insn_sz = bpf_is_ldimm64(insn) ? 2 : 1; 14838 return push_insn(t, t + insn_sz, FALLTHROUGH, env); 14839 } 14840 14841 switch (BPF_OP(insn->code)) { 14842 case BPF_EXIT: 14843 return DONE_EXPLORING; 14844 14845 case BPF_CALL: 14846 if (insn->src_reg == 0 && insn->imm == BPF_FUNC_timer_set_callback) 14847 /* Mark this call insn as a prune point to trigger 14848 * is_state_visited() check before call itself is 14849 * processed by __check_func_call(). Otherwise new 14850 * async state will be pushed for further exploration. 14851 */ 14852 mark_prune_point(env, t); 14853 if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) { 14854 struct bpf_kfunc_call_arg_meta meta; 14855 14856 ret = fetch_kfunc_meta(env, insn, &meta, NULL); 14857 if (ret == 0 && is_iter_next_kfunc(&meta)) { 14858 mark_prune_point(env, t); 14859 /* Checking and saving state checkpoints at iter_next() call 14860 * is crucial for fast convergence of open-coded iterator loop 14861 * logic, so we need to force it. If we don't do that, 14862 * is_state_visited() might skip saving a checkpoint, causing 14863 * unnecessarily long sequence of not checkpointed 14864 * instructions and jumps, leading to exhaustion of jump 14865 * history buffer, and potentially other undesired outcomes. 14866 * It is expected that with correct open-coded iterators 14867 * convergence will happen quickly, so we don't run a risk of 14868 * exhausting memory. 14869 */ 14870 mark_force_checkpoint(env, t); 14871 } 14872 } 14873 return visit_func_call_insn(t, insns, env, insn->src_reg == BPF_PSEUDO_CALL); 14874 14875 case BPF_JA: 14876 if (BPF_SRC(insn->code) != BPF_K) 14877 return -EINVAL; 14878 14879 if (BPF_CLASS(insn->code) == BPF_JMP) 14880 off = insn->off; 14881 else 14882 off = insn->imm; 14883 14884 /* unconditional jump with single edge */ 14885 ret = push_insn(t, t + off + 1, FALLTHROUGH, env); 14886 if (ret) 14887 return ret; 14888 14889 mark_prune_point(env, t + off + 1); 14890 mark_jmp_point(env, t + off + 1); 14891 14892 return ret; 14893 14894 default: 14895 /* conditional jump with two edges */ 14896 mark_prune_point(env, t); 14897 14898 ret = push_insn(t, t + 1, FALLTHROUGH, env); 14899 if (ret) 14900 return ret; 14901 14902 return push_insn(t, t + insn->off + 1, BRANCH, env); 14903 } 14904 } 14905 14906 /* non-recursive depth-first-search to detect loops in BPF program 14907 * loop == back-edge in directed graph 14908 */ 14909 static int check_cfg(struct bpf_verifier_env *env) 14910 { 14911 int insn_cnt = env->prog->len; 14912 int *insn_stack, *insn_state; 14913 int ret = 0; 14914 int i; 14915 14916 insn_state = env->cfg.insn_state = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL); 14917 if (!insn_state) 14918 return -ENOMEM; 14919 14920 insn_stack = env->cfg.insn_stack = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL); 14921 if (!insn_stack) { 14922 kvfree(insn_state); 14923 return -ENOMEM; 14924 } 14925 14926 insn_state[0] = DISCOVERED; /* mark 1st insn as discovered */ 14927 insn_stack[0] = 0; /* 0 is the first instruction */ 14928 env->cfg.cur_stack = 1; 14929 14930 while (env->cfg.cur_stack > 0) { 14931 int t = insn_stack[env->cfg.cur_stack - 1]; 14932 14933 ret = visit_insn(t, env); 14934 switch (ret) { 14935 case DONE_EXPLORING: 14936 insn_state[t] = EXPLORED; 14937 env->cfg.cur_stack--; 14938 break; 14939 case KEEP_EXPLORING: 14940 break; 14941 default: 14942 if (ret > 0) { 14943 verbose(env, "visit_insn internal bug\n"); 14944 ret = -EFAULT; 14945 } 14946 goto err_free; 14947 } 14948 } 14949 14950 if (env->cfg.cur_stack < 0) { 14951 verbose(env, "pop stack internal bug\n"); 14952 ret = -EFAULT; 14953 goto err_free; 14954 } 14955 14956 for (i = 0; i < insn_cnt; i++) { 14957 struct bpf_insn *insn = &env->prog->insnsi[i]; 14958 14959 if (insn_state[i] != EXPLORED) { 14960 verbose(env, "unreachable insn %d\n", i); 14961 ret = -EINVAL; 14962 goto err_free; 14963 } 14964 if (bpf_is_ldimm64(insn)) { 14965 if (insn_state[i + 1] != 0) { 14966 verbose(env, "jump into the middle of ldimm64 insn %d\n", i); 14967 ret = -EINVAL; 14968 goto err_free; 14969 } 14970 i++; /* skip second half of ldimm64 */ 14971 } 14972 } 14973 ret = 0; /* cfg looks good */ 14974 14975 err_free: 14976 kvfree(insn_state); 14977 kvfree(insn_stack); 14978 env->cfg.insn_state = env->cfg.insn_stack = NULL; 14979 return ret; 14980 } 14981 14982 static int check_abnormal_return(struct bpf_verifier_env *env) 14983 { 14984 int i; 14985 14986 for (i = 1; i < env->subprog_cnt; i++) { 14987 if (env->subprog_info[i].has_ld_abs) { 14988 verbose(env, "LD_ABS is not allowed in subprogs without BTF\n"); 14989 return -EINVAL; 14990 } 14991 if (env->subprog_info[i].has_tail_call) { 14992 verbose(env, "tail_call is not allowed in subprogs without BTF\n"); 14993 return -EINVAL; 14994 } 14995 } 14996 return 0; 14997 } 14998 14999 /* The minimum supported BTF func info size */ 15000 #define MIN_BPF_FUNCINFO_SIZE 8 15001 #define MAX_FUNCINFO_REC_SIZE 252 15002 15003 static int check_btf_func(struct bpf_verifier_env *env, 15004 const union bpf_attr *attr, 15005 bpfptr_t uattr) 15006 { 15007 const struct btf_type *type, *func_proto, *ret_type; 15008 u32 i, nfuncs, urec_size, min_size; 15009 u32 krec_size = sizeof(struct bpf_func_info); 15010 struct bpf_func_info *krecord; 15011 struct bpf_func_info_aux *info_aux = NULL; 15012 struct bpf_prog *prog; 15013 const struct btf *btf; 15014 bpfptr_t urecord; 15015 u32 prev_offset = 0; 15016 bool scalar_return; 15017 int ret = -ENOMEM; 15018 15019 nfuncs = attr->func_info_cnt; 15020 if (!nfuncs) { 15021 if (check_abnormal_return(env)) 15022 return -EINVAL; 15023 return 0; 15024 } 15025 15026 if (nfuncs != env->subprog_cnt) { 15027 verbose(env, "number of funcs in func_info doesn't match number of subprogs\n"); 15028 return -EINVAL; 15029 } 15030 15031 urec_size = attr->func_info_rec_size; 15032 if (urec_size < MIN_BPF_FUNCINFO_SIZE || 15033 urec_size > MAX_FUNCINFO_REC_SIZE || 15034 urec_size % sizeof(u32)) { 15035 verbose(env, "invalid func info rec size %u\n", urec_size); 15036 return -EINVAL; 15037 } 15038 15039 prog = env->prog; 15040 btf = prog->aux->btf; 15041 15042 urecord = make_bpfptr(attr->func_info, uattr.is_kernel); 15043 min_size = min_t(u32, krec_size, urec_size); 15044 15045 krecord = kvcalloc(nfuncs, krec_size, GFP_KERNEL | __GFP_NOWARN); 15046 if (!krecord) 15047 return -ENOMEM; 15048 info_aux = kcalloc(nfuncs, sizeof(*info_aux), GFP_KERNEL | __GFP_NOWARN); 15049 if (!info_aux) 15050 goto err_free; 15051 15052 for (i = 0; i < nfuncs; i++) { 15053 ret = bpf_check_uarg_tail_zero(urecord, krec_size, urec_size); 15054 if (ret) { 15055 if (ret == -E2BIG) { 15056 verbose(env, "nonzero tailing record in func info"); 15057 /* set the size kernel expects so loader can zero 15058 * out the rest of the record. 15059 */ 15060 if (copy_to_bpfptr_offset(uattr, 15061 offsetof(union bpf_attr, func_info_rec_size), 15062 &min_size, sizeof(min_size))) 15063 ret = -EFAULT; 15064 } 15065 goto err_free; 15066 } 15067 15068 if (copy_from_bpfptr(&krecord[i], urecord, min_size)) { 15069 ret = -EFAULT; 15070 goto err_free; 15071 } 15072 15073 /* check insn_off */ 15074 ret = -EINVAL; 15075 if (i == 0) { 15076 if (krecord[i].insn_off) { 15077 verbose(env, 15078 "nonzero insn_off %u for the first func info record", 15079 krecord[i].insn_off); 15080 goto err_free; 15081 } 15082 } else if (krecord[i].insn_off <= prev_offset) { 15083 verbose(env, 15084 "same or smaller insn offset (%u) than previous func info record (%u)", 15085 krecord[i].insn_off, prev_offset); 15086 goto err_free; 15087 } 15088 15089 if (env->subprog_info[i].start != krecord[i].insn_off) { 15090 verbose(env, "func_info BTF section doesn't match subprog layout in BPF program\n"); 15091 goto err_free; 15092 } 15093 15094 /* check type_id */ 15095 type = btf_type_by_id(btf, krecord[i].type_id); 15096 if (!type || !btf_type_is_func(type)) { 15097 verbose(env, "invalid type id %d in func info", 15098 krecord[i].type_id); 15099 goto err_free; 15100 } 15101 info_aux[i].linkage = BTF_INFO_VLEN(type->info); 15102 15103 func_proto = btf_type_by_id(btf, type->type); 15104 if (unlikely(!func_proto || !btf_type_is_func_proto(func_proto))) 15105 /* btf_func_check() already verified it during BTF load */ 15106 goto err_free; 15107 ret_type = btf_type_skip_modifiers(btf, func_proto->type, NULL); 15108 scalar_return = 15109 btf_type_is_small_int(ret_type) || btf_is_any_enum(ret_type); 15110 if (i && !scalar_return && env->subprog_info[i].has_ld_abs) { 15111 verbose(env, "LD_ABS is only allowed in functions that return 'int'.\n"); 15112 goto err_free; 15113 } 15114 if (i && !scalar_return && env->subprog_info[i].has_tail_call) { 15115 verbose(env, "tail_call is only allowed in functions that return 'int'.\n"); 15116 goto err_free; 15117 } 15118 15119 prev_offset = krecord[i].insn_off; 15120 bpfptr_add(&urecord, urec_size); 15121 } 15122 15123 prog->aux->func_info = krecord; 15124 prog->aux->func_info_cnt = nfuncs; 15125 prog->aux->func_info_aux = info_aux; 15126 return 0; 15127 15128 err_free: 15129 kvfree(krecord); 15130 kfree(info_aux); 15131 return ret; 15132 } 15133 15134 static void adjust_btf_func(struct bpf_verifier_env *env) 15135 { 15136 struct bpf_prog_aux *aux = env->prog->aux; 15137 int i; 15138 15139 if (!aux->func_info) 15140 return; 15141 15142 for (i = 0; i < env->subprog_cnt; i++) 15143 aux->func_info[i].insn_off = env->subprog_info[i].start; 15144 } 15145 15146 #define MIN_BPF_LINEINFO_SIZE offsetofend(struct bpf_line_info, line_col) 15147 #define MAX_LINEINFO_REC_SIZE MAX_FUNCINFO_REC_SIZE 15148 15149 static int check_btf_line(struct bpf_verifier_env *env, 15150 const union bpf_attr *attr, 15151 bpfptr_t uattr) 15152 { 15153 u32 i, s, nr_linfo, ncopy, expected_size, rec_size, prev_offset = 0; 15154 struct bpf_subprog_info *sub; 15155 struct bpf_line_info *linfo; 15156 struct bpf_prog *prog; 15157 const struct btf *btf; 15158 bpfptr_t ulinfo; 15159 int err; 15160 15161 nr_linfo = attr->line_info_cnt; 15162 if (!nr_linfo) 15163 return 0; 15164 if (nr_linfo > INT_MAX / sizeof(struct bpf_line_info)) 15165 return -EINVAL; 15166 15167 rec_size = attr->line_info_rec_size; 15168 if (rec_size < MIN_BPF_LINEINFO_SIZE || 15169 rec_size > MAX_LINEINFO_REC_SIZE || 15170 rec_size & (sizeof(u32) - 1)) 15171 return -EINVAL; 15172 15173 /* Need to zero it in case the userspace may 15174 * pass in a smaller bpf_line_info object. 15175 */ 15176 linfo = kvcalloc(nr_linfo, sizeof(struct bpf_line_info), 15177 GFP_KERNEL | __GFP_NOWARN); 15178 if (!linfo) 15179 return -ENOMEM; 15180 15181 prog = env->prog; 15182 btf = prog->aux->btf; 15183 15184 s = 0; 15185 sub = env->subprog_info; 15186 ulinfo = make_bpfptr(attr->line_info, uattr.is_kernel); 15187 expected_size = sizeof(struct bpf_line_info); 15188 ncopy = min_t(u32, expected_size, rec_size); 15189 for (i = 0; i < nr_linfo; i++) { 15190 err = bpf_check_uarg_tail_zero(ulinfo, expected_size, rec_size); 15191 if (err) { 15192 if (err == -E2BIG) { 15193 verbose(env, "nonzero tailing record in line_info"); 15194 if (copy_to_bpfptr_offset(uattr, 15195 offsetof(union bpf_attr, line_info_rec_size), 15196 &expected_size, sizeof(expected_size))) 15197 err = -EFAULT; 15198 } 15199 goto err_free; 15200 } 15201 15202 if (copy_from_bpfptr(&linfo[i], ulinfo, ncopy)) { 15203 err = -EFAULT; 15204 goto err_free; 15205 } 15206 15207 /* 15208 * Check insn_off to ensure 15209 * 1) strictly increasing AND 15210 * 2) bounded by prog->len 15211 * 15212 * The linfo[0].insn_off == 0 check logically falls into 15213 * the later "missing bpf_line_info for func..." case 15214 * because the first linfo[0].insn_off must be the 15215 * first sub also and the first sub must have 15216 * subprog_info[0].start == 0. 15217 */ 15218 if ((i && linfo[i].insn_off <= prev_offset) || 15219 linfo[i].insn_off >= prog->len) { 15220 verbose(env, "Invalid line_info[%u].insn_off:%u (prev_offset:%u prog->len:%u)\n", 15221 i, linfo[i].insn_off, prev_offset, 15222 prog->len); 15223 err = -EINVAL; 15224 goto err_free; 15225 } 15226 15227 if (!prog->insnsi[linfo[i].insn_off].code) { 15228 verbose(env, 15229 "Invalid insn code at line_info[%u].insn_off\n", 15230 i); 15231 err = -EINVAL; 15232 goto err_free; 15233 } 15234 15235 if (!btf_name_by_offset(btf, linfo[i].line_off) || 15236 !btf_name_by_offset(btf, linfo[i].file_name_off)) { 15237 verbose(env, "Invalid line_info[%u].line_off or .file_name_off\n", i); 15238 err = -EINVAL; 15239 goto err_free; 15240 } 15241 15242 if (s != env->subprog_cnt) { 15243 if (linfo[i].insn_off == sub[s].start) { 15244 sub[s].linfo_idx = i; 15245 s++; 15246 } else if (sub[s].start < linfo[i].insn_off) { 15247 verbose(env, "missing bpf_line_info for func#%u\n", s); 15248 err = -EINVAL; 15249 goto err_free; 15250 } 15251 } 15252 15253 prev_offset = linfo[i].insn_off; 15254 bpfptr_add(&ulinfo, rec_size); 15255 } 15256 15257 if (s != env->subprog_cnt) { 15258 verbose(env, "missing bpf_line_info for %u funcs starting from func#%u\n", 15259 env->subprog_cnt - s, s); 15260 err = -EINVAL; 15261 goto err_free; 15262 } 15263 15264 prog->aux->linfo = linfo; 15265 prog->aux->nr_linfo = nr_linfo; 15266 15267 return 0; 15268 15269 err_free: 15270 kvfree(linfo); 15271 return err; 15272 } 15273 15274 #define MIN_CORE_RELO_SIZE sizeof(struct bpf_core_relo) 15275 #define MAX_CORE_RELO_SIZE MAX_FUNCINFO_REC_SIZE 15276 15277 static int check_core_relo(struct bpf_verifier_env *env, 15278 const union bpf_attr *attr, 15279 bpfptr_t uattr) 15280 { 15281 u32 i, nr_core_relo, ncopy, expected_size, rec_size; 15282 struct bpf_core_relo core_relo = {}; 15283 struct bpf_prog *prog = env->prog; 15284 const struct btf *btf = prog->aux->btf; 15285 struct bpf_core_ctx ctx = { 15286 .log = &env->log, 15287 .btf = btf, 15288 }; 15289 bpfptr_t u_core_relo; 15290 int err; 15291 15292 nr_core_relo = attr->core_relo_cnt; 15293 if (!nr_core_relo) 15294 return 0; 15295 if (nr_core_relo > INT_MAX / sizeof(struct bpf_core_relo)) 15296 return -EINVAL; 15297 15298 rec_size = attr->core_relo_rec_size; 15299 if (rec_size < MIN_CORE_RELO_SIZE || 15300 rec_size > MAX_CORE_RELO_SIZE || 15301 rec_size % sizeof(u32)) 15302 return -EINVAL; 15303 15304 u_core_relo = make_bpfptr(attr->core_relos, uattr.is_kernel); 15305 expected_size = sizeof(struct bpf_core_relo); 15306 ncopy = min_t(u32, expected_size, rec_size); 15307 15308 /* Unlike func_info and line_info, copy and apply each CO-RE 15309 * relocation record one at a time. 15310 */ 15311 for (i = 0; i < nr_core_relo; i++) { 15312 /* future proofing when sizeof(bpf_core_relo) changes */ 15313 err = bpf_check_uarg_tail_zero(u_core_relo, expected_size, rec_size); 15314 if (err) { 15315 if (err == -E2BIG) { 15316 verbose(env, "nonzero tailing record in core_relo"); 15317 if (copy_to_bpfptr_offset(uattr, 15318 offsetof(union bpf_attr, core_relo_rec_size), 15319 &expected_size, sizeof(expected_size))) 15320 err = -EFAULT; 15321 } 15322 break; 15323 } 15324 15325 if (copy_from_bpfptr(&core_relo, u_core_relo, ncopy)) { 15326 err = -EFAULT; 15327 break; 15328 } 15329 15330 if (core_relo.insn_off % 8 || core_relo.insn_off / 8 >= prog->len) { 15331 verbose(env, "Invalid core_relo[%u].insn_off:%u prog->len:%u\n", 15332 i, core_relo.insn_off, prog->len); 15333 err = -EINVAL; 15334 break; 15335 } 15336 15337 err = bpf_core_apply(&ctx, &core_relo, i, 15338 &prog->insnsi[core_relo.insn_off / 8]); 15339 if (err) 15340 break; 15341 bpfptr_add(&u_core_relo, rec_size); 15342 } 15343 return err; 15344 } 15345 15346 static int check_btf_info(struct bpf_verifier_env *env, 15347 const union bpf_attr *attr, 15348 bpfptr_t uattr) 15349 { 15350 struct btf *btf; 15351 int err; 15352 15353 if (!attr->func_info_cnt && !attr->line_info_cnt) { 15354 if (check_abnormal_return(env)) 15355 return -EINVAL; 15356 return 0; 15357 } 15358 15359 btf = btf_get_by_fd(attr->prog_btf_fd); 15360 if (IS_ERR(btf)) 15361 return PTR_ERR(btf); 15362 if (btf_is_kernel(btf)) { 15363 btf_put(btf); 15364 return -EACCES; 15365 } 15366 env->prog->aux->btf = btf; 15367 15368 err = check_btf_func(env, attr, uattr); 15369 if (err) 15370 return err; 15371 15372 err = check_btf_line(env, attr, uattr); 15373 if (err) 15374 return err; 15375 15376 err = check_core_relo(env, attr, uattr); 15377 if (err) 15378 return err; 15379 15380 return 0; 15381 } 15382 15383 /* check %cur's range satisfies %old's */ 15384 static bool range_within(struct bpf_reg_state *old, 15385 struct bpf_reg_state *cur) 15386 { 15387 return old->umin_value <= cur->umin_value && 15388 old->umax_value >= cur->umax_value && 15389 old->smin_value <= cur->smin_value && 15390 old->smax_value >= cur->smax_value && 15391 old->u32_min_value <= cur->u32_min_value && 15392 old->u32_max_value >= cur->u32_max_value && 15393 old->s32_min_value <= cur->s32_min_value && 15394 old->s32_max_value >= cur->s32_max_value; 15395 } 15396 15397 /* If in the old state two registers had the same id, then they need to have 15398 * the same id in the new state as well. But that id could be different from 15399 * the old state, so we need to track the mapping from old to new ids. 15400 * Once we have seen that, say, a reg with old id 5 had new id 9, any subsequent 15401 * regs with old id 5 must also have new id 9 for the new state to be safe. But 15402 * regs with a different old id could still have new id 9, we don't care about 15403 * that. 15404 * So we look through our idmap to see if this old id has been seen before. If 15405 * so, we require the new id to match; otherwise, we add the id pair to the map. 15406 */ 15407 static bool check_ids(u32 old_id, u32 cur_id, struct bpf_idmap *idmap) 15408 { 15409 struct bpf_id_pair *map = idmap->map; 15410 unsigned int i; 15411 15412 /* either both IDs should be set or both should be zero */ 15413 if (!!old_id != !!cur_id) 15414 return false; 15415 15416 if (old_id == 0) /* cur_id == 0 as well */ 15417 return true; 15418 15419 for (i = 0; i < BPF_ID_MAP_SIZE; i++) { 15420 if (!map[i].old) { 15421 /* Reached an empty slot; haven't seen this id before */ 15422 map[i].old = old_id; 15423 map[i].cur = cur_id; 15424 return true; 15425 } 15426 if (map[i].old == old_id) 15427 return map[i].cur == cur_id; 15428 if (map[i].cur == cur_id) 15429 return false; 15430 } 15431 /* We ran out of idmap slots, which should be impossible */ 15432 WARN_ON_ONCE(1); 15433 return false; 15434 } 15435 15436 /* Similar to check_ids(), but allocate a unique temporary ID 15437 * for 'old_id' or 'cur_id' of zero. 15438 * This makes pairs like '0 vs unique ID', 'unique ID vs 0' valid. 15439 */ 15440 static bool check_scalar_ids(u32 old_id, u32 cur_id, struct bpf_idmap *idmap) 15441 { 15442 old_id = old_id ? old_id : ++idmap->tmp_id_gen; 15443 cur_id = cur_id ? cur_id : ++idmap->tmp_id_gen; 15444 15445 return check_ids(old_id, cur_id, idmap); 15446 } 15447 15448 static void clean_func_state(struct bpf_verifier_env *env, 15449 struct bpf_func_state *st) 15450 { 15451 enum bpf_reg_liveness live; 15452 int i, j; 15453 15454 for (i = 0; i < BPF_REG_FP; i++) { 15455 live = st->regs[i].live; 15456 /* liveness must not touch this register anymore */ 15457 st->regs[i].live |= REG_LIVE_DONE; 15458 if (!(live & REG_LIVE_READ)) 15459 /* since the register is unused, clear its state 15460 * to make further comparison simpler 15461 */ 15462 __mark_reg_not_init(env, &st->regs[i]); 15463 } 15464 15465 for (i = 0; i < st->allocated_stack / BPF_REG_SIZE; i++) { 15466 live = st->stack[i].spilled_ptr.live; 15467 /* liveness must not touch this stack slot anymore */ 15468 st->stack[i].spilled_ptr.live |= REG_LIVE_DONE; 15469 if (!(live & REG_LIVE_READ)) { 15470 __mark_reg_not_init(env, &st->stack[i].spilled_ptr); 15471 for (j = 0; j < BPF_REG_SIZE; j++) 15472 st->stack[i].slot_type[j] = STACK_INVALID; 15473 } 15474 } 15475 } 15476 15477 static void clean_verifier_state(struct bpf_verifier_env *env, 15478 struct bpf_verifier_state *st) 15479 { 15480 int i; 15481 15482 if (st->frame[0]->regs[0].live & REG_LIVE_DONE) 15483 /* all regs in this state in all frames were already marked */ 15484 return; 15485 15486 for (i = 0; i <= st->curframe; i++) 15487 clean_func_state(env, st->frame[i]); 15488 } 15489 15490 /* the parentage chains form a tree. 15491 * the verifier states are added to state lists at given insn and 15492 * pushed into state stack for future exploration. 15493 * when the verifier reaches bpf_exit insn some of the verifer states 15494 * stored in the state lists have their final liveness state already, 15495 * but a lot of states will get revised from liveness point of view when 15496 * the verifier explores other branches. 15497 * Example: 15498 * 1: r0 = 1 15499 * 2: if r1 == 100 goto pc+1 15500 * 3: r0 = 2 15501 * 4: exit 15502 * when the verifier reaches exit insn the register r0 in the state list of 15503 * insn 2 will be seen as !REG_LIVE_READ. Then the verifier pops the other_branch 15504 * of insn 2 and goes exploring further. At the insn 4 it will walk the 15505 * parentage chain from insn 4 into insn 2 and will mark r0 as REG_LIVE_READ. 15506 * 15507 * Since the verifier pushes the branch states as it sees them while exploring 15508 * the program the condition of walking the branch instruction for the second 15509 * time means that all states below this branch were already explored and 15510 * their final liveness marks are already propagated. 15511 * Hence when the verifier completes the search of state list in is_state_visited() 15512 * we can call this clean_live_states() function to mark all liveness states 15513 * as REG_LIVE_DONE to indicate that 'parent' pointers of 'struct bpf_reg_state' 15514 * will not be used. 15515 * This function also clears the registers and stack for states that !READ 15516 * to simplify state merging. 15517 * 15518 * Important note here that walking the same branch instruction in the callee 15519 * doesn't meant that the states are DONE. The verifier has to compare 15520 * the callsites 15521 */ 15522 static void clean_live_states(struct bpf_verifier_env *env, int insn, 15523 struct bpf_verifier_state *cur) 15524 { 15525 struct bpf_verifier_state_list *sl; 15526 int i; 15527 15528 sl = *explored_state(env, insn); 15529 while (sl) { 15530 if (sl->state.branches) 15531 goto next; 15532 if (sl->state.insn_idx != insn || 15533 sl->state.curframe != cur->curframe) 15534 goto next; 15535 for (i = 0; i <= cur->curframe; i++) 15536 if (sl->state.frame[i]->callsite != cur->frame[i]->callsite) 15537 goto next; 15538 clean_verifier_state(env, &sl->state); 15539 next: 15540 sl = sl->next; 15541 } 15542 } 15543 15544 static bool regs_exact(const struct bpf_reg_state *rold, 15545 const struct bpf_reg_state *rcur, 15546 struct bpf_idmap *idmap) 15547 { 15548 return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 && 15549 check_ids(rold->id, rcur->id, idmap) && 15550 check_ids(rold->ref_obj_id, rcur->ref_obj_id, idmap); 15551 } 15552 15553 /* Returns true if (rold safe implies rcur safe) */ 15554 static bool regsafe(struct bpf_verifier_env *env, struct bpf_reg_state *rold, 15555 struct bpf_reg_state *rcur, struct bpf_idmap *idmap) 15556 { 15557 if (!(rold->live & REG_LIVE_READ)) 15558 /* explored state didn't use this */ 15559 return true; 15560 if (rold->type == NOT_INIT) 15561 /* explored state can't have used this */ 15562 return true; 15563 if (rcur->type == NOT_INIT) 15564 return false; 15565 15566 /* Enforce that register types have to match exactly, including their 15567 * modifiers (like PTR_MAYBE_NULL, MEM_RDONLY, etc), as a general 15568 * rule. 15569 * 15570 * One can make a point that using a pointer register as unbounded 15571 * SCALAR would be technically acceptable, but this could lead to 15572 * pointer leaks because scalars are allowed to leak while pointers 15573 * are not. We could make this safe in special cases if root is 15574 * calling us, but it's probably not worth the hassle. 15575 * 15576 * Also, register types that are *not* MAYBE_NULL could technically be 15577 * safe to use as their MAYBE_NULL variants (e.g., PTR_TO_MAP_VALUE 15578 * is safe to be used as PTR_TO_MAP_VALUE_OR_NULL, provided both point 15579 * to the same map). 15580 * However, if the old MAYBE_NULL register then got NULL checked, 15581 * doing so could have affected others with the same id, and we can't 15582 * check for that because we lost the id when we converted to 15583 * a non-MAYBE_NULL variant. 15584 * So, as a general rule we don't allow mixing MAYBE_NULL and 15585 * non-MAYBE_NULL registers as well. 15586 */ 15587 if (rold->type != rcur->type) 15588 return false; 15589 15590 switch (base_type(rold->type)) { 15591 case SCALAR_VALUE: 15592 if (env->explore_alu_limits) { 15593 /* explore_alu_limits disables tnum_in() and range_within() 15594 * logic and requires everything to be strict 15595 */ 15596 return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 && 15597 check_scalar_ids(rold->id, rcur->id, idmap); 15598 } 15599 if (!rold->precise) 15600 return true; 15601 /* Why check_ids() for scalar registers? 15602 * 15603 * Consider the following BPF code: 15604 * 1: r6 = ... unbound scalar, ID=a ... 15605 * 2: r7 = ... unbound scalar, ID=b ... 15606 * 3: if (r6 > r7) goto +1 15607 * 4: r6 = r7 15608 * 5: if (r6 > X) goto ... 15609 * 6: ... memory operation using r7 ... 15610 * 15611 * First verification path is [1-6]: 15612 * - at (4) same bpf_reg_state::id (b) would be assigned to r6 and r7; 15613 * - at (5) r6 would be marked <= X, find_equal_scalars() would also mark 15614 * r7 <= X, because r6 and r7 share same id. 15615 * Next verification path is [1-4, 6]. 15616 * 15617 * Instruction (6) would be reached in two states: 15618 * I. r6{.id=b}, r7{.id=b} via path 1-6; 15619 * II. r6{.id=a}, r7{.id=b} via path 1-4, 6. 15620 * 15621 * Use check_ids() to distinguish these states. 15622 * --- 15623 * Also verify that new value satisfies old value range knowledge. 15624 */ 15625 return range_within(rold, rcur) && 15626 tnum_in(rold->var_off, rcur->var_off) && 15627 check_scalar_ids(rold->id, rcur->id, idmap); 15628 case PTR_TO_MAP_KEY: 15629 case PTR_TO_MAP_VALUE: 15630 case PTR_TO_MEM: 15631 case PTR_TO_BUF: 15632 case PTR_TO_TP_BUFFER: 15633 /* If the new min/max/var_off satisfy the old ones and 15634 * everything else matches, we are OK. 15635 */ 15636 return memcmp(rold, rcur, offsetof(struct bpf_reg_state, var_off)) == 0 && 15637 range_within(rold, rcur) && 15638 tnum_in(rold->var_off, rcur->var_off) && 15639 check_ids(rold->id, rcur->id, idmap) && 15640 check_ids(rold->ref_obj_id, rcur->ref_obj_id, idmap); 15641 case PTR_TO_PACKET_META: 15642 case PTR_TO_PACKET: 15643 /* We must have at least as much range as the old ptr 15644 * did, so that any accesses which were safe before are 15645 * still safe. This is true even if old range < old off, 15646 * since someone could have accessed through (ptr - k), or 15647 * even done ptr -= k in a register, to get a safe access. 15648 */ 15649 if (rold->range > rcur->range) 15650 return false; 15651 /* If the offsets don't match, we can't trust our alignment; 15652 * nor can we be sure that we won't fall out of range. 15653 */ 15654 if (rold->off != rcur->off) 15655 return false; 15656 /* id relations must be preserved */ 15657 if (!check_ids(rold->id, rcur->id, idmap)) 15658 return false; 15659 /* new val must satisfy old val knowledge */ 15660 return range_within(rold, rcur) && 15661 tnum_in(rold->var_off, rcur->var_off); 15662 case PTR_TO_STACK: 15663 /* two stack pointers are equal only if they're pointing to 15664 * the same stack frame, since fp-8 in foo != fp-8 in bar 15665 */ 15666 return regs_exact(rold, rcur, idmap) && rold->frameno == rcur->frameno; 15667 default: 15668 return regs_exact(rold, rcur, idmap); 15669 } 15670 } 15671 15672 static bool stacksafe(struct bpf_verifier_env *env, struct bpf_func_state *old, 15673 struct bpf_func_state *cur, struct bpf_idmap *idmap) 15674 { 15675 int i, spi; 15676 15677 /* walk slots of the explored stack and ignore any additional 15678 * slots in the current stack, since explored(safe) state 15679 * didn't use them 15680 */ 15681 for (i = 0; i < old->allocated_stack; i++) { 15682 struct bpf_reg_state *old_reg, *cur_reg; 15683 15684 spi = i / BPF_REG_SIZE; 15685 15686 if (!(old->stack[spi].spilled_ptr.live & REG_LIVE_READ)) { 15687 i += BPF_REG_SIZE - 1; 15688 /* explored state didn't use this */ 15689 continue; 15690 } 15691 15692 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_INVALID) 15693 continue; 15694 15695 if (env->allow_uninit_stack && 15696 old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC) 15697 continue; 15698 15699 /* explored stack has more populated slots than current stack 15700 * and these slots were used 15701 */ 15702 if (i >= cur->allocated_stack) 15703 return false; 15704 15705 /* if old state was safe with misc data in the stack 15706 * it will be safe with zero-initialized stack. 15707 * The opposite is not true 15708 */ 15709 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC && 15710 cur->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_ZERO) 15711 continue; 15712 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] != 15713 cur->stack[spi].slot_type[i % BPF_REG_SIZE]) 15714 /* Ex: old explored (safe) state has STACK_SPILL in 15715 * this stack slot, but current has STACK_MISC -> 15716 * this verifier states are not equivalent, 15717 * return false to continue verification of this path 15718 */ 15719 return false; 15720 if (i % BPF_REG_SIZE != BPF_REG_SIZE - 1) 15721 continue; 15722 /* Both old and cur are having same slot_type */ 15723 switch (old->stack[spi].slot_type[BPF_REG_SIZE - 1]) { 15724 case STACK_SPILL: 15725 /* when explored and current stack slot are both storing 15726 * spilled registers, check that stored pointers types 15727 * are the same as well. 15728 * Ex: explored safe path could have stored 15729 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -8} 15730 * but current path has stored: 15731 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -16} 15732 * such verifier states are not equivalent. 15733 * return false to continue verification of this path 15734 */ 15735 if (!regsafe(env, &old->stack[spi].spilled_ptr, 15736 &cur->stack[spi].spilled_ptr, idmap)) 15737 return false; 15738 break; 15739 case STACK_DYNPTR: 15740 old_reg = &old->stack[spi].spilled_ptr; 15741 cur_reg = &cur->stack[spi].spilled_ptr; 15742 if (old_reg->dynptr.type != cur_reg->dynptr.type || 15743 old_reg->dynptr.first_slot != cur_reg->dynptr.first_slot || 15744 !check_ids(old_reg->ref_obj_id, cur_reg->ref_obj_id, idmap)) 15745 return false; 15746 break; 15747 case STACK_ITER: 15748 old_reg = &old->stack[spi].spilled_ptr; 15749 cur_reg = &cur->stack[spi].spilled_ptr; 15750 /* iter.depth is not compared between states as it 15751 * doesn't matter for correctness and would otherwise 15752 * prevent convergence; we maintain it only to prevent 15753 * infinite loop check triggering, see 15754 * iter_active_depths_differ() 15755 */ 15756 if (old_reg->iter.btf != cur_reg->iter.btf || 15757 old_reg->iter.btf_id != cur_reg->iter.btf_id || 15758 old_reg->iter.state != cur_reg->iter.state || 15759 /* ignore {old_reg,cur_reg}->iter.depth, see above */ 15760 !check_ids(old_reg->ref_obj_id, cur_reg->ref_obj_id, idmap)) 15761 return false; 15762 break; 15763 case STACK_MISC: 15764 case STACK_ZERO: 15765 case STACK_INVALID: 15766 continue; 15767 /* Ensure that new unhandled slot types return false by default */ 15768 default: 15769 return false; 15770 } 15771 } 15772 return true; 15773 } 15774 15775 static bool refsafe(struct bpf_func_state *old, struct bpf_func_state *cur, 15776 struct bpf_idmap *idmap) 15777 { 15778 int i; 15779 15780 if (old->acquired_refs != cur->acquired_refs) 15781 return false; 15782 15783 for (i = 0; i < old->acquired_refs; i++) { 15784 if (!check_ids(old->refs[i].id, cur->refs[i].id, idmap)) 15785 return false; 15786 } 15787 15788 return true; 15789 } 15790 15791 /* compare two verifier states 15792 * 15793 * all states stored in state_list are known to be valid, since 15794 * verifier reached 'bpf_exit' instruction through them 15795 * 15796 * this function is called when verifier exploring different branches of 15797 * execution popped from the state stack. If it sees an old state that has 15798 * more strict register state and more strict stack state then this execution 15799 * branch doesn't need to be explored further, since verifier already 15800 * concluded that more strict state leads to valid finish. 15801 * 15802 * Therefore two states are equivalent if register state is more conservative 15803 * and explored stack state is more conservative than the current one. 15804 * Example: 15805 * explored current 15806 * (slot1=INV slot2=MISC) == (slot1=MISC slot2=MISC) 15807 * (slot1=MISC slot2=MISC) != (slot1=INV slot2=MISC) 15808 * 15809 * In other words if current stack state (one being explored) has more 15810 * valid slots than old one that already passed validation, it means 15811 * the verifier can stop exploring and conclude that current state is valid too 15812 * 15813 * Similarly with registers. If explored state has register type as invalid 15814 * whereas register type in current state is meaningful, it means that 15815 * the current state will reach 'bpf_exit' instruction safely 15816 */ 15817 static bool func_states_equal(struct bpf_verifier_env *env, struct bpf_func_state *old, 15818 struct bpf_func_state *cur) 15819 { 15820 int i; 15821 15822 for (i = 0; i < MAX_BPF_REG; i++) 15823 if (!regsafe(env, &old->regs[i], &cur->regs[i], 15824 &env->idmap_scratch)) 15825 return false; 15826 15827 if (!stacksafe(env, old, cur, &env->idmap_scratch)) 15828 return false; 15829 15830 if (!refsafe(old, cur, &env->idmap_scratch)) 15831 return false; 15832 15833 return true; 15834 } 15835 15836 static bool states_equal(struct bpf_verifier_env *env, 15837 struct bpf_verifier_state *old, 15838 struct bpf_verifier_state *cur) 15839 { 15840 int i; 15841 15842 if (old->curframe != cur->curframe) 15843 return false; 15844 15845 env->idmap_scratch.tmp_id_gen = env->id_gen; 15846 memset(&env->idmap_scratch.map, 0, sizeof(env->idmap_scratch.map)); 15847 15848 /* Verification state from speculative execution simulation 15849 * must never prune a non-speculative execution one. 15850 */ 15851 if (old->speculative && !cur->speculative) 15852 return false; 15853 15854 if (old->active_lock.ptr != cur->active_lock.ptr) 15855 return false; 15856 15857 /* Old and cur active_lock's have to be either both present 15858 * or both absent. 15859 */ 15860 if (!!old->active_lock.id != !!cur->active_lock.id) 15861 return false; 15862 15863 if (old->active_lock.id && 15864 !check_ids(old->active_lock.id, cur->active_lock.id, &env->idmap_scratch)) 15865 return false; 15866 15867 if (old->active_rcu_lock != cur->active_rcu_lock) 15868 return false; 15869 15870 /* for states to be equal callsites have to be the same 15871 * and all frame states need to be equivalent 15872 */ 15873 for (i = 0; i <= old->curframe; i++) { 15874 if (old->frame[i]->callsite != cur->frame[i]->callsite) 15875 return false; 15876 if (!func_states_equal(env, old->frame[i], cur->frame[i])) 15877 return false; 15878 } 15879 return true; 15880 } 15881 15882 /* Return 0 if no propagation happened. Return negative error code if error 15883 * happened. Otherwise, return the propagated bit. 15884 */ 15885 static int propagate_liveness_reg(struct bpf_verifier_env *env, 15886 struct bpf_reg_state *reg, 15887 struct bpf_reg_state *parent_reg) 15888 { 15889 u8 parent_flag = parent_reg->live & REG_LIVE_READ; 15890 u8 flag = reg->live & REG_LIVE_READ; 15891 int err; 15892 15893 /* When comes here, read flags of PARENT_REG or REG could be any of 15894 * REG_LIVE_READ64, REG_LIVE_READ32, REG_LIVE_NONE. There is no need 15895 * of propagation if PARENT_REG has strongest REG_LIVE_READ64. 15896 */ 15897 if (parent_flag == REG_LIVE_READ64 || 15898 /* Or if there is no read flag from REG. */ 15899 !flag || 15900 /* Or if the read flag from REG is the same as PARENT_REG. */ 15901 parent_flag == flag) 15902 return 0; 15903 15904 err = mark_reg_read(env, reg, parent_reg, flag); 15905 if (err) 15906 return err; 15907 15908 return flag; 15909 } 15910 15911 /* A write screens off any subsequent reads; but write marks come from the 15912 * straight-line code between a state and its parent. When we arrive at an 15913 * equivalent state (jump target or such) we didn't arrive by the straight-line 15914 * code, so read marks in the state must propagate to the parent regardless 15915 * of the state's write marks. That's what 'parent == state->parent' comparison 15916 * in mark_reg_read() is for. 15917 */ 15918 static int propagate_liveness(struct bpf_verifier_env *env, 15919 const struct bpf_verifier_state *vstate, 15920 struct bpf_verifier_state *vparent) 15921 { 15922 struct bpf_reg_state *state_reg, *parent_reg; 15923 struct bpf_func_state *state, *parent; 15924 int i, frame, err = 0; 15925 15926 if (vparent->curframe != vstate->curframe) { 15927 WARN(1, "propagate_live: parent frame %d current frame %d\n", 15928 vparent->curframe, vstate->curframe); 15929 return -EFAULT; 15930 } 15931 /* Propagate read liveness of registers... */ 15932 BUILD_BUG_ON(BPF_REG_FP + 1 != MAX_BPF_REG); 15933 for (frame = 0; frame <= vstate->curframe; frame++) { 15934 parent = vparent->frame[frame]; 15935 state = vstate->frame[frame]; 15936 parent_reg = parent->regs; 15937 state_reg = state->regs; 15938 /* We don't need to worry about FP liveness, it's read-only */ 15939 for (i = frame < vstate->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++) { 15940 err = propagate_liveness_reg(env, &state_reg[i], 15941 &parent_reg[i]); 15942 if (err < 0) 15943 return err; 15944 if (err == REG_LIVE_READ64) 15945 mark_insn_zext(env, &parent_reg[i]); 15946 } 15947 15948 /* Propagate stack slots. */ 15949 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE && 15950 i < parent->allocated_stack / BPF_REG_SIZE; i++) { 15951 parent_reg = &parent->stack[i].spilled_ptr; 15952 state_reg = &state->stack[i].spilled_ptr; 15953 err = propagate_liveness_reg(env, state_reg, 15954 parent_reg); 15955 if (err < 0) 15956 return err; 15957 } 15958 } 15959 return 0; 15960 } 15961 15962 /* find precise scalars in the previous equivalent state and 15963 * propagate them into the current state 15964 */ 15965 static int propagate_precision(struct bpf_verifier_env *env, 15966 const struct bpf_verifier_state *old) 15967 { 15968 struct bpf_reg_state *state_reg; 15969 struct bpf_func_state *state; 15970 int i, err = 0, fr; 15971 bool first; 15972 15973 for (fr = old->curframe; fr >= 0; fr--) { 15974 state = old->frame[fr]; 15975 state_reg = state->regs; 15976 first = true; 15977 for (i = 0; i < BPF_REG_FP; i++, state_reg++) { 15978 if (state_reg->type != SCALAR_VALUE || 15979 !state_reg->precise || 15980 !(state_reg->live & REG_LIVE_READ)) 15981 continue; 15982 if (env->log.level & BPF_LOG_LEVEL2) { 15983 if (first) 15984 verbose(env, "frame %d: propagating r%d", fr, i); 15985 else 15986 verbose(env, ",r%d", i); 15987 } 15988 bt_set_frame_reg(&env->bt, fr, i); 15989 first = false; 15990 } 15991 15992 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) { 15993 if (!is_spilled_reg(&state->stack[i])) 15994 continue; 15995 state_reg = &state->stack[i].spilled_ptr; 15996 if (state_reg->type != SCALAR_VALUE || 15997 !state_reg->precise || 15998 !(state_reg->live & REG_LIVE_READ)) 15999 continue; 16000 if (env->log.level & BPF_LOG_LEVEL2) { 16001 if (first) 16002 verbose(env, "frame %d: propagating fp%d", 16003 fr, (-i - 1) * BPF_REG_SIZE); 16004 else 16005 verbose(env, ",fp%d", (-i - 1) * BPF_REG_SIZE); 16006 } 16007 bt_set_frame_slot(&env->bt, fr, i); 16008 first = false; 16009 } 16010 if (!first) 16011 verbose(env, "\n"); 16012 } 16013 16014 err = mark_chain_precision_batch(env); 16015 if (err < 0) 16016 return err; 16017 16018 return 0; 16019 } 16020 16021 static bool states_maybe_looping(struct bpf_verifier_state *old, 16022 struct bpf_verifier_state *cur) 16023 { 16024 struct bpf_func_state *fold, *fcur; 16025 int i, fr = cur->curframe; 16026 16027 if (old->curframe != fr) 16028 return false; 16029 16030 fold = old->frame[fr]; 16031 fcur = cur->frame[fr]; 16032 for (i = 0; i < MAX_BPF_REG; i++) 16033 if (memcmp(&fold->regs[i], &fcur->regs[i], 16034 offsetof(struct bpf_reg_state, parent))) 16035 return false; 16036 return true; 16037 } 16038 16039 static bool is_iter_next_insn(struct bpf_verifier_env *env, int insn_idx) 16040 { 16041 return env->insn_aux_data[insn_idx].is_iter_next; 16042 } 16043 16044 /* is_state_visited() handles iter_next() (see process_iter_next_call() for 16045 * terminology) calls specially: as opposed to bounded BPF loops, it *expects* 16046 * states to match, which otherwise would look like an infinite loop. So while 16047 * iter_next() calls are taken care of, we still need to be careful and 16048 * prevent erroneous and too eager declaration of "ininite loop", when 16049 * iterators are involved. 16050 * 16051 * Here's a situation in pseudo-BPF assembly form: 16052 * 16053 * 0: again: ; set up iter_next() call args 16054 * 1: r1 = &it ; <CHECKPOINT HERE> 16055 * 2: call bpf_iter_num_next ; this is iter_next() call 16056 * 3: if r0 == 0 goto done 16057 * 4: ... something useful here ... 16058 * 5: goto again ; another iteration 16059 * 6: done: 16060 * 7: r1 = &it 16061 * 8: call bpf_iter_num_destroy ; clean up iter state 16062 * 9: exit 16063 * 16064 * This is a typical loop. Let's assume that we have a prune point at 1:, 16065 * before we get to `call bpf_iter_num_next` (e.g., because of that `goto 16066 * again`, assuming other heuristics don't get in a way). 16067 * 16068 * When we first time come to 1:, let's say we have some state X. We proceed 16069 * to 2:, fork states, enqueue ACTIVE, validate NULL case successfully, exit. 16070 * Now we come back to validate that forked ACTIVE state. We proceed through 16071 * 3-5, come to goto, jump to 1:. Let's assume our state didn't change, so we 16072 * are converging. But the problem is that we don't know that yet, as this 16073 * convergence has to happen at iter_next() call site only. So if nothing is 16074 * done, at 1: verifier will use bounded loop logic and declare infinite 16075 * looping (and would be *technically* correct, if not for iterator's 16076 * "eventual sticky NULL" contract, see process_iter_next_call()). But we 16077 * don't want that. So what we do in process_iter_next_call() when we go on 16078 * another ACTIVE iteration, we bump slot->iter.depth, to mark that it's 16079 * a different iteration. So when we suspect an infinite loop, we additionally 16080 * check if any of the *ACTIVE* iterator states depths differ. If yes, we 16081 * pretend we are not looping and wait for next iter_next() call. 16082 * 16083 * This only applies to ACTIVE state. In DRAINED state we don't expect to 16084 * loop, because that would actually mean infinite loop, as DRAINED state is 16085 * "sticky", and so we'll keep returning into the same instruction with the 16086 * same state (at least in one of possible code paths). 16087 * 16088 * This approach allows to keep infinite loop heuristic even in the face of 16089 * active iterator. E.g., C snippet below is and will be detected as 16090 * inifintely looping: 16091 * 16092 * struct bpf_iter_num it; 16093 * int *p, x; 16094 * 16095 * bpf_iter_num_new(&it, 0, 10); 16096 * while ((p = bpf_iter_num_next(&t))) { 16097 * x = p; 16098 * while (x--) {} // <<-- infinite loop here 16099 * } 16100 * 16101 */ 16102 static bool iter_active_depths_differ(struct bpf_verifier_state *old, struct bpf_verifier_state *cur) 16103 { 16104 struct bpf_reg_state *slot, *cur_slot; 16105 struct bpf_func_state *state; 16106 int i, fr; 16107 16108 for (fr = old->curframe; fr >= 0; fr--) { 16109 state = old->frame[fr]; 16110 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) { 16111 if (state->stack[i].slot_type[0] != STACK_ITER) 16112 continue; 16113 16114 slot = &state->stack[i].spilled_ptr; 16115 if (slot->iter.state != BPF_ITER_STATE_ACTIVE) 16116 continue; 16117 16118 cur_slot = &cur->frame[fr]->stack[i].spilled_ptr; 16119 if (cur_slot->iter.depth != slot->iter.depth) 16120 return true; 16121 } 16122 } 16123 return false; 16124 } 16125 16126 static int is_state_visited(struct bpf_verifier_env *env, int insn_idx) 16127 { 16128 struct bpf_verifier_state_list *new_sl; 16129 struct bpf_verifier_state_list *sl, **pprev; 16130 struct bpf_verifier_state *cur = env->cur_state, *new; 16131 int i, j, err, states_cnt = 0; 16132 bool force_new_state = env->test_state_freq || is_force_checkpoint(env, insn_idx); 16133 bool add_new_state = force_new_state; 16134 16135 /* bpf progs typically have pruning point every 4 instructions 16136 * http://vger.kernel.org/bpfconf2019.html#session-1 16137 * Do not add new state for future pruning if the verifier hasn't seen 16138 * at least 2 jumps and at least 8 instructions. 16139 * This heuristics helps decrease 'total_states' and 'peak_states' metric. 16140 * In tests that amounts to up to 50% reduction into total verifier 16141 * memory consumption and 20% verifier time speedup. 16142 */ 16143 if (env->jmps_processed - env->prev_jmps_processed >= 2 && 16144 env->insn_processed - env->prev_insn_processed >= 8) 16145 add_new_state = true; 16146 16147 pprev = explored_state(env, insn_idx); 16148 sl = *pprev; 16149 16150 clean_live_states(env, insn_idx, cur); 16151 16152 while (sl) { 16153 states_cnt++; 16154 if (sl->state.insn_idx != insn_idx) 16155 goto next; 16156 16157 if (sl->state.branches) { 16158 struct bpf_func_state *frame = sl->state.frame[sl->state.curframe]; 16159 16160 if (frame->in_async_callback_fn && 16161 frame->async_entry_cnt != cur->frame[cur->curframe]->async_entry_cnt) { 16162 /* Different async_entry_cnt means that the verifier is 16163 * processing another entry into async callback. 16164 * Seeing the same state is not an indication of infinite 16165 * loop or infinite recursion. 16166 * But finding the same state doesn't mean that it's safe 16167 * to stop processing the current state. The previous state 16168 * hasn't yet reached bpf_exit, since state.branches > 0. 16169 * Checking in_async_callback_fn alone is not enough either. 16170 * Since the verifier still needs to catch infinite loops 16171 * inside async callbacks. 16172 */ 16173 goto skip_inf_loop_check; 16174 } 16175 /* BPF open-coded iterators loop detection is special. 16176 * states_maybe_looping() logic is too simplistic in detecting 16177 * states that *might* be equivalent, because it doesn't know 16178 * about ID remapping, so don't even perform it. 16179 * See process_iter_next_call() and iter_active_depths_differ() 16180 * for overview of the logic. When current and one of parent 16181 * states are detected as equivalent, it's a good thing: we prove 16182 * convergence and can stop simulating further iterations. 16183 * It's safe to assume that iterator loop will finish, taking into 16184 * account iter_next() contract of eventually returning 16185 * sticky NULL result. 16186 */ 16187 if (is_iter_next_insn(env, insn_idx)) { 16188 if (states_equal(env, &sl->state, cur)) { 16189 struct bpf_func_state *cur_frame; 16190 struct bpf_reg_state *iter_state, *iter_reg; 16191 int spi; 16192 16193 cur_frame = cur->frame[cur->curframe]; 16194 /* btf_check_iter_kfuncs() enforces that 16195 * iter state pointer is always the first arg 16196 */ 16197 iter_reg = &cur_frame->regs[BPF_REG_1]; 16198 /* current state is valid due to states_equal(), 16199 * so we can assume valid iter and reg state, 16200 * no need for extra (re-)validations 16201 */ 16202 spi = __get_spi(iter_reg->off + iter_reg->var_off.value); 16203 iter_state = &func(env, iter_reg)->stack[spi].spilled_ptr; 16204 if (iter_state->iter.state == BPF_ITER_STATE_ACTIVE) 16205 goto hit; 16206 } 16207 goto skip_inf_loop_check; 16208 } 16209 /* attempt to detect infinite loop to avoid unnecessary doomed work */ 16210 if (states_maybe_looping(&sl->state, cur) && 16211 states_equal(env, &sl->state, cur) && 16212 !iter_active_depths_differ(&sl->state, cur)) { 16213 verbose_linfo(env, insn_idx, "; "); 16214 verbose(env, "infinite loop detected at insn %d\n", insn_idx); 16215 return -EINVAL; 16216 } 16217 /* if the verifier is processing a loop, avoid adding new state 16218 * too often, since different loop iterations have distinct 16219 * states and may not help future pruning. 16220 * This threshold shouldn't be too low to make sure that 16221 * a loop with large bound will be rejected quickly. 16222 * The most abusive loop will be: 16223 * r1 += 1 16224 * if r1 < 1000000 goto pc-2 16225 * 1M insn_procssed limit / 100 == 10k peak states. 16226 * This threshold shouldn't be too high either, since states 16227 * at the end of the loop are likely to be useful in pruning. 16228 */ 16229 skip_inf_loop_check: 16230 if (!force_new_state && 16231 env->jmps_processed - env->prev_jmps_processed < 20 && 16232 env->insn_processed - env->prev_insn_processed < 100) 16233 add_new_state = false; 16234 goto miss; 16235 } 16236 if (states_equal(env, &sl->state, cur)) { 16237 hit: 16238 sl->hit_cnt++; 16239 /* reached equivalent register/stack state, 16240 * prune the search. 16241 * Registers read by the continuation are read by us. 16242 * If we have any write marks in env->cur_state, they 16243 * will prevent corresponding reads in the continuation 16244 * from reaching our parent (an explored_state). Our 16245 * own state will get the read marks recorded, but 16246 * they'll be immediately forgotten as we're pruning 16247 * this state and will pop a new one. 16248 */ 16249 err = propagate_liveness(env, &sl->state, cur); 16250 16251 /* if previous state reached the exit with precision and 16252 * current state is equivalent to it (except precsion marks) 16253 * the precision needs to be propagated back in 16254 * the current state. 16255 */ 16256 err = err ? : push_jmp_history(env, cur); 16257 err = err ? : propagate_precision(env, &sl->state); 16258 if (err) 16259 return err; 16260 return 1; 16261 } 16262 miss: 16263 /* when new state is not going to be added do not increase miss count. 16264 * Otherwise several loop iterations will remove the state 16265 * recorded earlier. The goal of these heuristics is to have 16266 * states from some iterations of the loop (some in the beginning 16267 * and some at the end) to help pruning. 16268 */ 16269 if (add_new_state) 16270 sl->miss_cnt++; 16271 /* heuristic to determine whether this state is beneficial 16272 * to keep checking from state equivalence point of view. 16273 * Higher numbers increase max_states_per_insn and verification time, 16274 * but do not meaningfully decrease insn_processed. 16275 */ 16276 if (sl->miss_cnt > sl->hit_cnt * 3 + 3) { 16277 /* the state is unlikely to be useful. Remove it to 16278 * speed up verification 16279 */ 16280 *pprev = sl->next; 16281 if (sl->state.frame[0]->regs[0].live & REG_LIVE_DONE) { 16282 u32 br = sl->state.branches; 16283 16284 WARN_ONCE(br, 16285 "BUG live_done but branches_to_explore %d\n", 16286 br); 16287 free_verifier_state(&sl->state, false); 16288 kfree(sl); 16289 env->peak_states--; 16290 } else { 16291 /* cannot free this state, since parentage chain may 16292 * walk it later. Add it for free_list instead to 16293 * be freed at the end of verification 16294 */ 16295 sl->next = env->free_list; 16296 env->free_list = sl; 16297 } 16298 sl = *pprev; 16299 continue; 16300 } 16301 next: 16302 pprev = &sl->next; 16303 sl = *pprev; 16304 } 16305 16306 if (env->max_states_per_insn < states_cnt) 16307 env->max_states_per_insn = states_cnt; 16308 16309 if (!env->bpf_capable && states_cnt > BPF_COMPLEXITY_LIMIT_STATES) 16310 return 0; 16311 16312 if (!add_new_state) 16313 return 0; 16314 16315 /* There were no equivalent states, remember the current one. 16316 * Technically the current state is not proven to be safe yet, 16317 * but it will either reach outer most bpf_exit (which means it's safe) 16318 * or it will be rejected. When there are no loops the verifier won't be 16319 * seeing this tuple (frame[0].callsite, frame[1].callsite, .. insn_idx) 16320 * again on the way to bpf_exit. 16321 * When looping the sl->state.branches will be > 0 and this state 16322 * will not be considered for equivalence until branches == 0. 16323 */ 16324 new_sl = kzalloc(sizeof(struct bpf_verifier_state_list), GFP_KERNEL); 16325 if (!new_sl) 16326 return -ENOMEM; 16327 env->total_states++; 16328 env->peak_states++; 16329 env->prev_jmps_processed = env->jmps_processed; 16330 env->prev_insn_processed = env->insn_processed; 16331 16332 /* forget precise markings we inherited, see __mark_chain_precision */ 16333 if (env->bpf_capable) 16334 mark_all_scalars_imprecise(env, cur); 16335 16336 /* add new state to the head of linked list */ 16337 new = &new_sl->state; 16338 err = copy_verifier_state(new, cur); 16339 if (err) { 16340 free_verifier_state(new, false); 16341 kfree(new_sl); 16342 return err; 16343 } 16344 new->insn_idx = insn_idx; 16345 WARN_ONCE(new->branches != 1, 16346 "BUG is_state_visited:branches_to_explore=%d insn %d\n", new->branches, insn_idx); 16347 16348 cur->parent = new; 16349 cur->first_insn_idx = insn_idx; 16350 clear_jmp_history(cur); 16351 new_sl->next = *explored_state(env, insn_idx); 16352 *explored_state(env, insn_idx) = new_sl; 16353 /* connect new state to parentage chain. Current frame needs all 16354 * registers connected. Only r6 - r9 of the callers are alive (pushed 16355 * to the stack implicitly by JITs) so in callers' frames connect just 16356 * r6 - r9 as an optimization. Callers will have r1 - r5 connected to 16357 * the state of the call instruction (with WRITTEN set), and r0 comes 16358 * from callee with its full parentage chain, anyway. 16359 */ 16360 /* clear write marks in current state: the writes we did are not writes 16361 * our child did, so they don't screen off its reads from us. 16362 * (There are no read marks in current state, because reads always mark 16363 * their parent and current state never has children yet. Only 16364 * explored_states can get read marks.) 16365 */ 16366 for (j = 0; j <= cur->curframe; j++) { 16367 for (i = j < cur->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++) 16368 cur->frame[j]->regs[i].parent = &new->frame[j]->regs[i]; 16369 for (i = 0; i < BPF_REG_FP; i++) 16370 cur->frame[j]->regs[i].live = REG_LIVE_NONE; 16371 } 16372 16373 /* all stack frames are accessible from callee, clear them all */ 16374 for (j = 0; j <= cur->curframe; j++) { 16375 struct bpf_func_state *frame = cur->frame[j]; 16376 struct bpf_func_state *newframe = new->frame[j]; 16377 16378 for (i = 0; i < frame->allocated_stack / BPF_REG_SIZE; i++) { 16379 frame->stack[i].spilled_ptr.live = REG_LIVE_NONE; 16380 frame->stack[i].spilled_ptr.parent = 16381 &newframe->stack[i].spilled_ptr; 16382 } 16383 } 16384 return 0; 16385 } 16386 16387 /* Return true if it's OK to have the same insn return a different type. */ 16388 static bool reg_type_mismatch_ok(enum bpf_reg_type type) 16389 { 16390 switch (base_type(type)) { 16391 case PTR_TO_CTX: 16392 case PTR_TO_SOCKET: 16393 case PTR_TO_SOCK_COMMON: 16394 case PTR_TO_TCP_SOCK: 16395 case PTR_TO_XDP_SOCK: 16396 case PTR_TO_BTF_ID: 16397 return false; 16398 default: 16399 return true; 16400 } 16401 } 16402 16403 /* If an instruction was previously used with particular pointer types, then we 16404 * need to be careful to avoid cases such as the below, where it may be ok 16405 * for one branch accessing the pointer, but not ok for the other branch: 16406 * 16407 * R1 = sock_ptr 16408 * goto X; 16409 * ... 16410 * R1 = some_other_valid_ptr; 16411 * goto X; 16412 * ... 16413 * R2 = *(u32 *)(R1 + 0); 16414 */ 16415 static bool reg_type_mismatch(enum bpf_reg_type src, enum bpf_reg_type prev) 16416 { 16417 return src != prev && (!reg_type_mismatch_ok(src) || 16418 !reg_type_mismatch_ok(prev)); 16419 } 16420 16421 static int save_aux_ptr_type(struct bpf_verifier_env *env, enum bpf_reg_type type, 16422 bool allow_trust_missmatch) 16423 { 16424 enum bpf_reg_type *prev_type = &env->insn_aux_data[env->insn_idx].ptr_type; 16425 16426 if (*prev_type == NOT_INIT) { 16427 /* Saw a valid insn 16428 * dst_reg = *(u32 *)(src_reg + off) 16429 * save type to validate intersecting paths 16430 */ 16431 *prev_type = type; 16432 } else if (reg_type_mismatch(type, *prev_type)) { 16433 /* Abuser program is trying to use the same insn 16434 * dst_reg = *(u32*) (src_reg + off) 16435 * with different pointer types: 16436 * src_reg == ctx in one branch and 16437 * src_reg == stack|map in some other branch. 16438 * Reject it. 16439 */ 16440 if (allow_trust_missmatch && 16441 base_type(type) == PTR_TO_BTF_ID && 16442 base_type(*prev_type) == PTR_TO_BTF_ID) { 16443 /* 16444 * Have to support a use case when one path through 16445 * the program yields TRUSTED pointer while another 16446 * is UNTRUSTED. Fallback to UNTRUSTED to generate 16447 * BPF_PROBE_MEM/BPF_PROBE_MEMSX. 16448 */ 16449 *prev_type = PTR_TO_BTF_ID | PTR_UNTRUSTED; 16450 } else { 16451 verbose(env, "same insn cannot be used with different pointers\n"); 16452 return -EINVAL; 16453 } 16454 } 16455 16456 return 0; 16457 } 16458 16459 static int do_check(struct bpf_verifier_env *env) 16460 { 16461 bool pop_log = !(env->log.level & BPF_LOG_LEVEL2); 16462 struct bpf_verifier_state *state = env->cur_state; 16463 struct bpf_insn *insns = env->prog->insnsi; 16464 struct bpf_reg_state *regs; 16465 int insn_cnt = env->prog->len; 16466 bool do_print_state = false; 16467 int prev_insn_idx = -1; 16468 16469 for (;;) { 16470 struct bpf_insn *insn; 16471 u8 class; 16472 int err; 16473 16474 env->prev_insn_idx = prev_insn_idx; 16475 if (env->insn_idx >= insn_cnt) { 16476 verbose(env, "invalid insn idx %d insn_cnt %d\n", 16477 env->insn_idx, insn_cnt); 16478 return -EFAULT; 16479 } 16480 16481 insn = &insns[env->insn_idx]; 16482 class = BPF_CLASS(insn->code); 16483 16484 if (++env->insn_processed > BPF_COMPLEXITY_LIMIT_INSNS) { 16485 verbose(env, 16486 "BPF program is too large. Processed %d insn\n", 16487 env->insn_processed); 16488 return -E2BIG; 16489 } 16490 16491 state->last_insn_idx = env->prev_insn_idx; 16492 16493 if (is_prune_point(env, env->insn_idx)) { 16494 err = is_state_visited(env, env->insn_idx); 16495 if (err < 0) 16496 return err; 16497 if (err == 1) { 16498 /* found equivalent state, can prune the search */ 16499 if (env->log.level & BPF_LOG_LEVEL) { 16500 if (do_print_state) 16501 verbose(env, "\nfrom %d to %d%s: safe\n", 16502 env->prev_insn_idx, env->insn_idx, 16503 env->cur_state->speculative ? 16504 " (speculative execution)" : ""); 16505 else 16506 verbose(env, "%d: safe\n", env->insn_idx); 16507 } 16508 goto process_bpf_exit; 16509 } 16510 } 16511 16512 if (is_jmp_point(env, env->insn_idx)) { 16513 err = push_jmp_history(env, state); 16514 if (err) 16515 return err; 16516 } 16517 16518 if (signal_pending(current)) 16519 return -EAGAIN; 16520 16521 if (need_resched()) 16522 cond_resched(); 16523 16524 if (env->log.level & BPF_LOG_LEVEL2 && do_print_state) { 16525 verbose(env, "\nfrom %d to %d%s:", 16526 env->prev_insn_idx, env->insn_idx, 16527 env->cur_state->speculative ? 16528 " (speculative execution)" : ""); 16529 print_verifier_state(env, state->frame[state->curframe], true); 16530 do_print_state = false; 16531 } 16532 16533 if (env->log.level & BPF_LOG_LEVEL) { 16534 const struct bpf_insn_cbs cbs = { 16535 .cb_call = disasm_kfunc_name, 16536 .cb_print = verbose, 16537 .private_data = env, 16538 }; 16539 16540 if (verifier_state_scratched(env)) 16541 print_insn_state(env, state->frame[state->curframe]); 16542 16543 verbose_linfo(env, env->insn_idx, "; "); 16544 env->prev_log_pos = env->log.end_pos; 16545 verbose(env, "%d: ", env->insn_idx); 16546 print_bpf_insn(&cbs, insn, env->allow_ptr_leaks); 16547 env->prev_insn_print_pos = env->log.end_pos - env->prev_log_pos; 16548 env->prev_log_pos = env->log.end_pos; 16549 } 16550 16551 if (bpf_prog_is_offloaded(env->prog->aux)) { 16552 err = bpf_prog_offload_verify_insn(env, env->insn_idx, 16553 env->prev_insn_idx); 16554 if (err) 16555 return err; 16556 } 16557 16558 regs = cur_regs(env); 16559 sanitize_mark_insn_seen(env); 16560 prev_insn_idx = env->insn_idx; 16561 16562 if (class == BPF_ALU || class == BPF_ALU64) { 16563 err = check_alu_op(env, insn); 16564 if (err) 16565 return err; 16566 16567 } else if (class == BPF_LDX) { 16568 enum bpf_reg_type src_reg_type; 16569 16570 /* check for reserved fields is already done */ 16571 16572 /* check src operand */ 16573 err = check_reg_arg(env, insn->src_reg, SRC_OP); 16574 if (err) 16575 return err; 16576 16577 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK); 16578 if (err) 16579 return err; 16580 16581 src_reg_type = regs[insn->src_reg].type; 16582 16583 /* check that memory (src_reg + off) is readable, 16584 * the state of dst_reg will be updated by this func 16585 */ 16586 err = check_mem_access(env, env->insn_idx, insn->src_reg, 16587 insn->off, BPF_SIZE(insn->code), 16588 BPF_READ, insn->dst_reg, false, 16589 BPF_MODE(insn->code) == BPF_MEMSX); 16590 if (err) 16591 return err; 16592 16593 err = save_aux_ptr_type(env, src_reg_type, true); 16594 if (err) 16595 return err; 16596 } else if (class == BPF_STX) { 16597 enum bpf_reg_type dst_reg_type; 16598 16599 if (BPF_MODE(insn->code) == BPF_ATOMIC) { 16600 err = check_atomic(env, env->insn_idx, insn); 16601 if (err) 16602 return err; 16603 env->insn_idx++; 16604 continue; 16605 } 16606 16607 if (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0) { 16608 verbose(env, "BPF_STX uses reserved fields\n"); 16609 return -EINVAL; 16610 } 16611 16612 /* check src1 operand */ 16613 err = check_reg_arg(env, insn->src_reg, SRC_OP); 16614 if (err) 16615 return err; 16616 /* check src2 operand */ 16617 err = check_reg_arg(env, insn->dst_reg, SRC_OP); 16618 if (err) 16619 return err; 16620 16621 dst_reg_type = regs[insn->dst_reg].type; 16622 16623 /* check that memory (dst_reg + off) is writeable */ 16624 err = check_mem_access(env, env->insn_idx, insn->dst_reg, 16625 insn->off, BPF_SIZE(insn->code), 16626 BPF_WRITE, insn->src_reg, false, false); 16627 if (err) 16628 return err; 16629 16630 err = save_aux_ptr_type(env, dst_reg_type, false); 16631 if (err) 16632 return err; 16633 } else if (class == BPF_ST) { 16634 enum bpf_reg_type dst_reg_type; 16635 16636 if (BPF_MODE(insn->code) != BPF_MEM || 16637 insn->src_reg != BPF_REG_0) { 16638 verbose(env, "BPF_ST uses reserved fields\n"); 16639 return -EINVAL; 16640 } 16641 /* check src operand */ 16642 err = check_reg_arg(env, insn->dst_reg, SRC_OP); 16643 if (err) 16644 return err; 16645 16646 dst_reg_type = regs[insn->dst_reg].type; 16647 16648 /* check that memory (dst_reg + off) is writeable */ 16649 err = check_mem_access(env, env->insn_idx, insn->dst_reg, 16650 insn->off, BPF_SIZE(insn->code), 16651 BPF_WRITE, -1, false, false); 16652 if (err) 16653 return err; 16654 16655 err = save_aux_ptr_type(env, dst_reg_type, false); 16656 if (err) 16657 return err; 16658 } else if (class == BPF_JMP || class == BPF_JMP32) { 16659 u8 opcode = BPF_OP(insn->code); 16660 16661 env->jmps_processed++; 16662 if (opcode == BPF_CALL) { 16663 if (BPF_SRC(insn->code) != BPF_K || 16664 (insn->src_reg != BPF_PSEUDO_KFUNC_CALL 16665 && insn->off != 0) || 16666 (insn->src_reg != BPF_REG_0 && 16667 insn->src_reg != BPF_PSEUDO_CALL && 16668 insn->src_reg != BPF_PSEUDO_KFUNC_CALL) || 16669 insn->dst_reg != BPF_REG_0 || 16670 class == BPF_JMP32) { 16671 verbose(env, "BPF_CALL uses reserved fields\n"); 16672 return -EINVAL; 16673 } 16674 16675 if (env->cur_state->active_lock.ptr) { 16676 if ((insn->src_reg == BPF_REG_0 && insn->imm != BPF_FUNC_spin_unlock) || 16677 (insn->src_reg == BPF_PSEUDO_CALL) || 16678 (insn->src_reg == BPF_PSEUDO_KFUNC_CALL && 16679 (insn->off != 0 || !is_bpf_graph_api_kfunc(insn->imm)))) { 16680 verbose(env, "function calls are not allowed while holding a lock\n"); 16681 return -EINVAL; 16682 } 16683 } 16684 if (insn->src_reg == BPF_PSEUDO_CALL) 16685 err = check_func_call(env, insn, &env->insn_idx); 16686 else if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) 16687 err = check_kfunc_call(env, insn, &env->insn_idx); 16688 else 16689 err = check_helper_call(env, insn, &env->insn_idx); 16690 if (err) 16691 return err; 16692 16693 mark_reg_scratched(env, BPF_REG_0); 16694 } else if (opcode == BPF_JA) { 16695 if (BPF_SRC(insn->code) != BPF_K || 16696 insn->src_reg != BPF_REG_0 || 16697 insn->dst_reg != BPF_REG_0 || 16698 (class == BPF_JMP && insn->imm != 0) || 16699 (class == BPF_JMP32 && insn->off != 0)) { 16700 verbose(env, "BPF_JA uses reserved fields\n"); 16701 return -EINVAL; 16702 } 16703 16704 if (class == BPF_JMP) 16705 env->insn_idx += insn->off + 1; 16706 else 16707 env->insn_idx += insn->imm + 1; 16708 continue; 16709 16710 } else if (opcode == BPF_EXIT) { 16711 if (BPF_SRC(insn->code) != BPF_K || 16712 insn->imm != 0 || 16713 insn->src_reg != BPF_REG_0 || 16714 insn->dst_reg != BPF_REG_0 || 16715 class == BPF_JMP32) { 16716 verbose(env, "BPF_EXIT uses reserved fields\n"); 16717 return -EINVAL; 16718 } 16719 16720 if (env->cur_state->active_lock.ptr && 16721 !in_rbtree_lock_required_cb(env)) { 16722 verbose(env, "bpf_spin_unlock is missing\n"); 16723 return -EINVAL; 16724 } 16725 16726 if (env->cur_state->active_rcu_lock && 16727 !in_rbtree_lock_required_cb(env)) { 16728 verbose(env, "bpf_rcu_read_unlock is missing\n"); 16729 return -EINVAL; 16730 } 16731 16732 /* We must do check_reference_leak here before 16733 * prepare_func_exit to handle the case when 16734 * state->curframe > 0, it may be a callback 16735 * function, for which reference_state must 16736 * match caller reference state when it exits. 16737 */ 16738 err = check_reference_leak(env); 16739 if (err) 16740 return err; 16741 16742 if (state->curframe) { 16743 /* exit from nested function */ 16744 err = prepare_func_exit(env, &env->insn_idx); 16745 if (err) 16746 return err; 16747 do_print_state = true; 16748 continue; 16749 } 16750 16751 err = check_return_code(env); 16752 if (err) 16753 return err; 16754 process_bpf_exit: 16755 mark_verifier_state_scratched(env); 16756 update_branch_counts(env, env->cur_state); 16757 err = pop_stack(env, &prev_insn_idx, 16758 &env->insn_idx, pop_log); 16759 if (err < 0) { 16760 if (err != -ENOENT) 16761 return err; 16762 break; 16763 } else { 16764 do_print_state = true; 16765 continue; 16766 } 16767 } else { 16768 err = check_cond_jmp_op(env, insn, &env->insn_idx); 16769 if (err) 16770 return err; 16771 } 16772 } else if (class == BPF_LD) { 16773 u8 mode = BPF_MODE(insn->code); 16774 16775 if (mode == BPF_ABS || mode == BPF_IND) { 16776 err = check_ld_abs(env, insn); 16777 if (err) 16778 return err; 16779 16780 } else if (mode == BPF_IMM) { 16781 err = check_ld_imm(env, insn); 16782 if (err) 16783 return err; 16784 16785 env->insn_idx++; 16786 sanitize_mark_insn_seen(env); 16787 } else { 16788 verbose(env, "invalid BPF_LD mode\n"); 16789 return -EINVAL; 16790 } 16791 } else { 16792 verbose(env, "unknown insn class %d\n", class); 16793 return -EINVAL; 16794 } 16795 16796 env->insn_idx++; 16797 } 16798 16799 return 0; 16800 } 16801 16802 static int find_btf_percpu_datasec(struct btf *btf) 16803 { 16804 const struct btf_type *t; 16805 const char *tname; 16806 int i, n; 16807 16808 /* 16809 * Both vmlinux and module each have their own ".data..percpu" 16810 * DATASECs in BTF. So for module's case, we need to skip vmlinux BTF 16811 * types to look at only module's own BTF types. 16812 */ 16813 n = btf_nr_types(btf); 16814 if (btf_is_module(btf)) 16815 i = btf_nr_types(btf_vmlinux); 16816 else 16817 i = 1; 16818 16819 for(; i < n; i++) { 16820 t = btf_type_by_id(btf, i); 16821 if (BTF_INFO_KIND(t->info) != BTF_KIND_DATASEC) 16822 continue; 16823 16824 tname = btf_name_by_offset(btf, t->name_off); 16825 if (!strcmp(tname, ".data..percpu")) 16826 return i; 16827 } 16828 16829 return -ENOENT; 16830 } 16831 16832 /* replace pseudo btf_id with kernel symbol address */ 16833 static int check_pseudo_btf_id(struct bpf_verifier_env *env, 16834 struct bpf_insn *insn, 16835 struct bpf_insn_aux_data *aux) 16836 { 16837 const struct btf_var_secinfo *vsi; 16838 const struct btf_type *datasec; 16839 struct btf_mod_pair *btf_mod; 16840 const struct btf_type *t; 16841 const char *sym_name; 16842 bool percpu = false; 16843 u32 type, id = insn->imm; 16844 struct btf *btf; 16845 s32 datasec_id; 16846 u64 addr; 16847 int i, btf_fd, err; 16848 16849 btf_fd = insn[1].imm; 16850 if (btf_fd) { 16851 btf = btf_get_by_fd(btf_fd); 16852 if (IS_ERR(btf)) { 16853 verbose(env, "invalid module BTF object FD specified.\n"); 16854 return -EINVAL; 16855 } 16856 } else { 16857 if (!btf_vmlinux) { 16858 verbose(env, "kernel is missing BTF, make sure CONFIG_DEBUG_INFO_BTF=y is specified in Kconfig.\n"); 16859 return -EINVAL; 16860 } 16861 btf = btf_vmlinux; 16862 btf_get(btf); 16863 } 16864 16865 t = btf_type_by_id(btf, id); 16866 if (!t) { 16867 verbose(env, "ldimm64 insn specifies invalid btf_id %d.\n", id); 16868 err = -ENOENT; 16869 goto err_put; 16870 } 16871 16872 if (!btf_type_is_var(t) && !btf_type_is_func(t)) { 16873 verbose(env, "pseudo btf_id %d in ldimm64 isn't KIND_VAR or KIND_FUNC\n", id); 16874 err = -EINVAL; 16875 goto err_put; 16876 } 16877 16878 sym_name = btf_name_by_offset(btf, t->name_off); 16879 addr = kallsyms_lookup_name(sym_name); 16880 if (!addr) { 16881 verbose(env, "ldimm64 failed to find the address for kernel symbol '%s'.\n", 16882 sym_name); 16883 err = -ENOENT; 16884 goto err_put; 16885 } 16886 insn[0].imm = (u32)addr; 16887 insn[1].imm = addr >> 32; 16888 16889 if (btf_type_is_func(t)) { 16890 aux->btf_var.reg_type = PTR_TO_MEM | MEM_RDONLY; 16891 aux->btf_var.mem_size = 0; 16892 goto check_btf; 16893 } 16894 16895 datasec_id = find_btf_percpu_datasec(btf); 16896 if (datasec_id > 0) { 16897 datasec = btf_type_by_id(btf, datasec_id); 16898 for_each_vsi(i, datasec, vsi) { 16899 if (vsi->type == id) { 16900 percpu = true; 16901 break; 16902 } 16903 } 16904 } 16905 16906 type = t->type; 16907 t = btf_type_skip_modifiers(btf, type, NULL); 16908 if (percpu) { 16909 aux->btf_var.reg_type = PTR_TO_BTF_ID | MEM_PERCPU; 16910 aux->btf_var.btf = btf; 16911 aux->btf_var.btf_id = type; 16912 } else if (!btf_type_is_struct(t)) { 16913 const struct btf_type *ret; 16914 const char *tname; 16915 u32 tsize; 16916 16917 /* resolve the type size of ksym. */ 16918 ret = btf_resolve_size(btf, t, &tsize); 16919 if (IS_ERR(ret)) { 16920 tname = btf_name_by_offset(btf, t->name_off); 16921 verbose(env, "ldimm64 unable to resolve the size of type '%s': %ld\n", 16922 tname, PTR_ERR(ret)); 16923 err = -EINVAL; 16924 goto err_put; 16925 } 16926 aux->btf_var.reg_type = PTR_TO_MEM | MEM_RDONLY; 16927 aux->btf_var.mem_size = tsize; 16928 } else { 16929 aux->btf_var.reg_type = PTR_TO_BTF_ID; 16930 aux->btf_var.btf = btf; 16931 aux->btf_var.btf_id = type; 16932 } 16933 check_btf: 16934 /* check whether we recorded this BTF (and maybe module) already */ 16935 for (i = 0; i < env->used_btf_cnt; i++) { 16936 if (env->used_btfs[i].btf == btf) { 16937 btf_put(btf); 16938 return 0; 16939 } 16940 } 16941 16942 if (env->used_btf_cnt >= MAX_USED_BTFS) { 16943 err = -E2BIG; 16944 goto err_put; 16945 } 16946 16947 btf_mod = &env->used_btfs[env->used_btf_cnt]; 16948 btf_mod->btf = btf; 16949 btf_mod->module = NULL; 16950 16951 /* if we reference variables from kernel module, bump its refcount */ 16952 if (btf_is_module(btf)) { 16953 btf_mod->module = btf_try_get_module(btf); 16954 if (!btf_mod->module) { 16955 err = -ENXIO; 16956 goto err_put; 16957 } 16958 } 16959 16960 env->used_btf_cnt++; 16961 16962 return 0; 16963 err_put: 16964 btf_put(btf); 16965 return err; 16966 } 16967 16968 static bool is_tracing_prog_type(enum bpf_prog_type type) 16969 { 16970 switch (type) { 16971 case BPF_PROG_TYPE_KPROBE: 16972 case BPF_PROG_TYPE_TRACEPOINT: 16973 case BPF_PROG_TYPE_PERF_EVENT: 16974 case BPF_PROG_TYPE_RAW_TRACEPOINT: 16975 case BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE: 16976 return true; 16977 default: 16978 return false; 16979 } 16980 } 16981 16982 static int check_map_prog_compatibility(struct bpf_verifier_env *env, 16983 struct bpf_map *map, 16984 struct bpf_prog *prog) 16985 16986 { 16987 enum bpf_prog_type prog_type = resolve_prog_type(prog); 16988 16989 if (btf_record_has_field(map->record, BPF_LIST_HEAD) || 16990 btf_record_has_field(map->record, BPF_RB_ROOT)) { 16991 if (is_tracing_prog_type(prog_type)) { 16992 verbose(env, "tracing progs cannot use bpf_{list_head,rb_root} yet\n"); 16993 return -EINVAL; 16994 } 16995 } 16996 16997 if (btf_record_has_field(map->record, BPF_SPIN_LOCK)) { 16998 if (prog_type == BPF_PROG_TYPE_SOCKET_FILTER) { 16999 verbose(env, "socket filter progs cannot use bpf_spin_lock yet\n"); 17000 return -EINVAL; 17001 } 17002 17003 if (is_tracing_prog_type(prog_type)) { 17004 verbose(env, "tracing progs cannot use bpf_spin_lock yet\n"); 17005 return -EINVAL; 17006 } 17007 } 17008 17009 if (btf_record_has_field(map->record, BPF_TIMER)) { 17010 if (is_tracing_prog_type(prog_type)) { 17011 verbose(env, "tracing progs cannot use bpf_timer yet\n"); 17012 return -EINVAL; 17013 } 17014 } 17015 17016 if ((bpf_prog_is_offloaded(prog->aux) || bpf_map_is_offloaded(map)) && 17017 !bpf_offload_prog_map_match(prog, map)) { 17018 verbose(env, "offload device mismatch between prog and map\n"); 17019 return -EINVAL; 17020 } 17021 17022 if (map->map_type == BPF_MAP_TYPE_STRUCT_OPS) { 17023 verbose(env, "bpf_struct_ops map cannot be used in prog\n"); 17024 return -EINVAL; 17025 } 17026 17027 if (prog->aux->sleepable) 17028 switch (map->map_type) { 17029 case BPF_MAP_TYPE_HASH: 17030 case BPF_MAP_TYPE_LRU_HASH: 17031 case BPF_MAP_TYPE_ARRAY: 17032 case BPF_MAP_TYPE_PERCPU_HASH: 17033 case BPF_MAP_TYPE_PERCPU_ARRAY: 17034 case BPF_MAP_TYPE_LRU_PERCPU_HASH: 17035 case BPF_MAP_TYPE_ARRAY_OF_MAPS: 17036 case BPF_MAP_TYPE_HASH_OF_MAPS: 17037 case BPF_MAP_TYPE_RINGBUF: 17038 case BPF_MAP_TYPE_USER_RINGBUF: 17039 case BPF_MAP_TYPE_INODE_STORAGE: 17040 case BPF_MAP_TYPE_SK_STORAGE: 17041 case BPF_MAP_TYPE_TASK_STORAGE: 17042 case BPF_MAP_TYPE_CGRP_STORAGE: 17043 break; 17044 default: 17045 verbose(env, 17046 "Sleepable programs can only use array, hash, ringbuf and local storage maps\n"); 17047 return -EINVAL; 17048 } 17049 17050 return 0; 17051 } 17052 17053 static bool bpf_map_is_cgroup_storage(struct bpf_map *map) 17054 { 17055 return (map->map_type == BPF_MAP_TYPE_CGROUP_STORAGE || 17056 map->map_type == BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE); 17057 } 17058 17059 /* find and rewrite pseudo imm in ld_imm64 instructions: 17060 * 17061 * 1. if it accesses map FD, replace it with actual map pointer. 17062 * 2. if it accesses btf_id of a VAR, replace it with pointer to the var. 17063 * 17064 * NOTE: btf_vmlinux is required for converting pseudo btf_id. 17065 */ 17066 static int resolve_pseudo_ldimm64(struct bpf_verifier_env *env) 17067 { 17068 struct bpf_insn *insn = env->prog->insnsi; 17069 int insn_cnt = env->prog->len; 17070 int i, j, err; 17071 17072 err = bpf_prog_calc_tag(env->prog); 17073 if (err) 17074 return err; 17075 17076 for (i = 0; i < insn_cnt; i++, insn++) { 17077 if (BPF_CLASS(insn->code) == BPF_LDX && 17078 ((BPF_MODE(insn->code) != BPF_MEM && BPF_MODE(insn->code) != BPF_MEMSX) || 17079 insn->imm != 0)) { 17080 verbose(env, "BPF_LDX uses reserved fields\n"); 17081 return -EINVAL; 17082 } 17083 17084 if (insn[0].code == (BPF_LD | BPF_IMM | BPF_DW)) { 17085 struct bpf_insn_aux_data *aux; 17086 struct bpf_map *map; 17087 struct fd f; 17088 u64 addr; 17089 u32 fd; 17090 17091 if (i == insn_cnt - 1 || insn[1].code != 0 || 17092 insn[1].dst_reg != 0 || insn[1].src_reg != 0 || 17093 insn[1].off != 0) { 17094 verbose(env, "invalid bpf_ld_imm64 insn\n"); 17095 return -EINVAL; 17096 } 17097 17098 if (insn[0].src_reg == 0) 17099 /* valid generic load 64-bit imm */ 17100 goto next_insn; 17101 17102 if (insn[0].src_reg == BPF_PSEUDO_BTF_ID) { 17103 aux = &env->insn_aux_data[i]; 17104 err = check_pseudo_btf_id(env, insn, aux); 17105 if (err) 17106 return err; 17107 goto next_insn; 17108 } 17109 17110 if (insn[0].src_reg == BPF_PSEUDO_FUNC) { 17111 aux = &env->insn_aux_data[i]; 17112 aux->ptr_type = PTR_TO_FUNC; 17113 goto next_insn; 17114 } 17115 17116 /* In final convert_pseudo_ld_imm64() step, this is 17117 * converted into regular 64-bit imm load insn. 17118 */ 17119 switch (insn[0].src_reg) { 17120 case BPF_PSEUDO_MAP_VALUE: 17121 case BPF_PSEUDO_MAP_IDX_VALUE: 17122 break; 17123 case BPF_PSEUDO_MAP_FD: 17124 case BPF_PSEUDO_MAP_IDX: 17125 if (insn[1].imm == 0) 17126 break; 17127 fallthrough; 17128 default: 17129 verbose(env, "unrecognized bpf_ld_imm64 insn\n"); 17130 return -EINVAL; 17131 } 17132 17133 switch (insn[0].src_reg) { 17134 case BPF_PSEUDO_MAP_IDX_VALUE: 17135 case BPF_PSEUDO_MAP_IDX: 17136 if (bpfptr_is_null(env->fd_array)) { 17137 verbose(env, "fd_idx without fd_array is invalid\n"); 17138 return -EPROTO; 17139 } 17140 if (copy_from_bpfptr_offset(&fd, env->fd_array, 17141 insn[0].imm * sizeof(fd), 17142 sizeof(fd))) 17143 return -EFAULT; 17144 break; 17145 default: 17146 fd = insn[0].imm; 17147 break; 17148 } 17149 17150 f = fdget(fd); 17151 map = __bpf_map_get(f); 17152 if (IS_ERR(map)) { 17153 verbose(env, "fd %d is not pointing to valid bpf_map\n", 17154 insn[0].imm); 17155 return PTR_ERR(map); 17156 } 17157 17158 err = check_map_prog_compatibility(env, map, env->prog); 17159 if (err) { 17160 fdput(f); 17161 return err; 17162 } 17163 17164 aux = &env->insn_aux_data[i]; 17165 if (insn[0].src_reg == BPF_PSEUDO_MAP_FD || 17166 insn[0].src_reg == BPF_PSEUDO_MAP_IDX) { 17167 addr = (unsigned long)map; 17168 } else { 17169 u32 off = insn[1].imm; 17170 17171 if (off >= BPF_MAX_VAR_OFF) { 17172 verbose(env, "direct value offset of %u is not allowed\n", off); 17173 fdput(f); 17174 return -EINVAL; 17175 } 17176 17177 if (!map->ops->map_direct_value_addr) { 17178 verbose(env, "no direct value access support for this map type\n"); 17179 fdput(f); 17180 return -EINVAL; 17181 } 17182 17183 err = map->ops->map_direct_value_addr(map, &addr, off); 17184 if (err) { 17185 verbose(env, "invalid access to map value pointer, value_size=%u off=%u\n", 17186 map->value_size, off); 17187 fdput(f); 17188 return err; 17189 } 17190 17191 aux->map_off = off; 17192 addr += off; 17193 } 17194 17195 insn[0].imm = (u32)addr; 17196 insn[1].imm = addr >> 32; 17197 17198 /* check whether we recorded this map already */ 17199 for (j = 0; j < env->used_map_cnt; j++) { 17200 if (env->used_maps[j] == map) { 17201 aux->map_index = j; 17202 fdput(f); 17203 goto next_insn; 17204 } 17205 } 17206 17207 if (env->used_map_cnt >= MAX_USED_MAPS) { 17208 fdput(f); 17209 return -E2BIG; 17210 } 17211 17212 /* hold the map. If the program is rejected by verifier, 17213 * the map will be released by release_maps() or it 17214 * will be used by the valid program until it's unloaded 17215 * and all maps are released in free_used_maps() 17216 */ 17217 bpf_map_inc(map); 17218 17219 aux->map_index = env->used_map_cnt; 17220 env->used_maps[env->used_map_cnt++] = map; 17221 17222 if (bpf_map_is_cgroup_storage(map) && 17223 bpf_cgroup_storage_assign(env->prog->aux, map)) { 17224 verbose(env, "only one cgroup storage of each type is allowed\n"); 17225 fdput(f); 17226 return -EBUSY; 17227 } 17228 17229 fdput(f); 17230 next_insn: 17231 insn++; 17232 i++; 17233 continue; 17234 } 17235 17236 /* Basic sanity check before we invest more work here. */ 17237 if (!bpf_opcode_in_insntable(insn->code)) { 17238 verbose(env, "unknown opcode %02x\n", insn->code); 17239 return -EINVAL; 17240 } 17241 } 17242 17243 /* now all pseudo BPF_LD_IMM64 instructions load valid 17244 * 'struct bpf_map *' into a register instead of user map_fd. 17245 * These pointers will be used later by verifier to validate map access. 17246 */ 17247 return 0; 17248 } 17249 17250 /* drop refcnt of maps used by the rejected program */ 17251 static void release_maps(struct bpf_verifier_env *env) 17252 { 17253 __bpf_free_used_maps(env->prog->aux, env->used_maps, 17254 env->used_map_cnt); 17255 } 17256 17257 /* drop refcnt of maps used by the rejected program */ 17258 static void release_btfs(struct bpf_verifier_env *env) 17259 { 17260 __bpf_free_used_btfs(env->prog->aux, env->used_btfs, 17261 env->used_btf_cnt); 17262 } 17263 17264 /* convert pseudo BPF_LD_IMM64 into generic BPF_LD_IMM64 */ 17265 static void convert_pseudo_ld_imm64(struct bpf_verifier_env *env) 17266 { 17267 struct bpf_insn *insn = env->prog->insnsi; 17268 int insn_cnt = env->prog->len; 17269 int i; 17270 17271 for (i = 0; i < insn_cnt; i++, insn++) { 17272 if (insn->code != (BPF_LD | BPF_IMM | BPF_DW)) 17273 continue; 17274 if (insn->src_reg == BPF_PSEUDO_FUNC) 17275 continue; 17276 insn->src_reg = 0; 17277 } 17278 } 17279 17280 /* single env->prog->insni[off] instruction was replaced with the range 17281 * insni[off, off + cnt). Adjust corresponding insn_aux_data by copying 17282 * [0, off) and [off, end) to new locations, so the patched range stays zero 17283 */ 17284 static void adjust_insn_aux_data(struct bpf_verifier_env *env, 17285 struct bpf_insn_aux_data *new_data, 17286 struct bpf_prog *new_prog, u32 off, u32 cnt) 17287 { 17288 struct bpf_insn_aux_data *old_data = env->insn_aux_data; 17289 struct bpf_insn *insn = new_prog->insnsi; 17290 u32 old_seen = old_data[off].seen; 17291 u32 prog_len; 17292 int i; 17293 17294 /* aux info at OFF always needs adjustment, no matter fast path 17295 * (cnt == 1) is taken or not. There is no guarantee INSN at OFF is the 17296 * original insn at old prog. 17297 */ 17298 old_data[off].zext_dst = insn_has_def32(env, insn + off + cnt - 1); 17299 17300 if (cnt == 1) 17301 return; 17302 prog_len = new_prog->len; 17303 17304 memcpy(new_data, old_data, sizeof(struct bpf_insn_aux_data) * off); 17305 memcpy(new_data + off + cnt - 1, old_data + off, 17306 sizeof(struct bpf_insn_aux_data) * (prog_len - off - cnt + 1)); 17307 for (i = off; i < off + cnt - 1; i++) { 17308 /* Expand insni[off]'s seen count to the patched range. */ 17309 new_data[i].seen = old_seen; 17310 new_data[i].zext_dst = insn_has_def32(env, insn + i); 17311 } 17312 env->insn_aux_data = new_data; 17313 vfree(old_data); 17314 } 17315 17316 static void adjust_subprog_starts(struct bpf_verifier_env *env, u32 off, u32 len) 17317 { 17318 int i; 17319 17320 if (len == 1) 17321 return; 17322 /* NOTE: fake 'exit' subprog should be updated as well. */ 17323 for (i = 0; i <= env->subprog_cnt; i++) { 17324 if (env->subprog_info[i].start <= off) 17325 continue; 17326 env->subprog_info[i].start += len - 1; 17327 } 17328 } 17329 17330 static void adjust_poke_descs(struct bpf_prog *prog, u32 off, u32 len) 17331 { 17332 struct bpf_jit_poke_descriptor *tab = prog->aux->poke_tab; 17333 int i, sz = prog->aux->size_poke_tab; 17334 struct bpf_jit_poke_descriptor *desc; 17335 17336 for (i = 0; i < sz; i++) { 17337 desc = &tab[i]; 17338 if (desc->insn_idx <= off) 17339 continue; 17340 desc->insn_idx += len - 1; 17341 } 17342 } 17343 17344 static struct bpf_prog *bpf_patch_insn_data(struct bpf_verifier_env *env, u32 off, 17345 const struct bpf_insn *patch, u32 len) 17346 { 17347 struct bpf_prog *new_prog; 17348 struct bpf_insn_aux_data *new_data = NULL; 17349 17350 if (len > 1) { 17351 new_data = vzalloc(array_size(env->prog->len + len - 1, 17352 sizeof(struct bpf_insn_aux_data))); 17353 if (!new_data) 17354 return NULL; 17355 } 17356 17357 new_prog = bpf_patch_insn_single(env->prog, off, patch, len); 17358 if (IS_ERR(new_prog)) { 17359 if (PTR_ERR(new_prog) == -ERANGE) 17360 verbose(env, 17361 "insn %d cannot be patched due to 16-bit range\n", 17362 env->insn_aux_data[off].orig_idx); 17363 vfree(new_data); 17364 return NULL; 17365 } 17366 adjust_insn_aux_data(env, new_data, new_prog, off, len); 17367 adjust_subprog_starts(env, off, len); 17368 adjust_poke_descs(new_prog, off, len); 17369 return new_prog; 17370 } 17371 17372 static int adjust_subprog_starts_after_remove(struct bpf_verifier_env *env, 17373 u32 off, u32 cnt) 17374 { 17375 int i, j; 17376 17377 /* find first prog starting at or after off (first to remove) */ 17378 for (i = 0; i < env->subprog_cnt; i++) 17379 if (env->subprog_info[i].start >= off) 17380 break; 17381 /* find first prog starting at or after off + cnt (first to stay) */ 17382 for (j = i; j < env->subprog_cnt; j++) 17383 if (env->subprog_info[j].start >= off + cnt) 17384 break; 17385 /* if j doesn't start exactly at off + cnt, we are just removing 17386 * the front of previous prog 17387 */ 17388 if (env->subprog_info[j].start != off + cnt) 17389 j--; 17390 17391 if (j > i) { 17392 struct bpf_prog_aux *aux = env->prog->aux; 17393 int move; 17394 17395 /* move fake 'exit' subprog as well */ 17396 move = env->subprog_cnt + 1 - j; 17397 17398 memmove(env->subprog_info + i, 17399 env->subprog_info + j, 17400 sizeof(*env->subprog_info) * move); 17401 env->subprog_cnt -= j - i; 17402 17403 /* remove func_info */ 17404 if (aux->func_info) { 17405 move = aux->func_info_cnt - j; 17406 17407 memmove(aux->func_info + i, 17408 aux->func_info + j, 17409 sizeof(*aux->func_info) * move); 17410 aux->func_info_cnt -= j - i; 17411 /* func_info->insn_off is set after all code rewrites, 17412 * in adjust_btf_func() - no need to adjust 17413 */ 17414 } 17415 } else { 17416 /* convert i from "first prog to remove" to "first to adjust" */ 17417 if (env->subprog_info[i].start == off) 17418 i++; 17419 } 17420 17421 /* update fake 'exit' subprog as well */ 17422 for (; i <= env->subprog_cnt; i++) 17423 env->subprog_info[i].start -= cnt; 17424 17425 return 0; 17426 } 17427 17428 static int bpf_adj_linfo_after_remove(struct bpf_verifier_env *env, u32 off, 17429 u32 cnt) 17430 { 17431 struct bpf_prog *prog = env->prog; 17432 u32 i, l_off, l_cnt, nr_linfo; 17433 struct bpf_line_info *linfo; 17434 17435 nr_linfo = prog->aux->nr_linfo; 17436 if (!nr_linfo) 17437 return 0; 17438 17439 linfo = prog->aux->linfo; 17440 17441 /* find first line info to remove, count lines to be removed */ 17442 for (i = 0; i < nr_linfo; i++) 17443 if (linfo[i].insn_off >= off) 17444 break; 17445 17446 l_off = i; 17447 l_cnt = 0; 17448 for (; i < nr_linfo; i++) 17449 if (linfo[i].insn_off < off + cnt) 17450 l_cnt++; 17451 else 17452 break; 17453 17454 /* First live insn doesn't match first live linfo, it needs to "inherit" 17455 * last removed linfo. prog is already modified, so prog->len == off 17456 * means no live instructions after (tail of the program was removed). 17457 */ 17458 if (prog->len != off && l_cnt && 17459 (i == nr_linfo || linfo[i].insn_off != off + cnt)) { 17460 l_cnt--; 17461 linfo[--i].insn_off = off + cnt; 17462 } 17463 17464 /* remove the line info which refer to the removed instructions */ 17465 if (l_cnt) { 17466 memmove(linfo + l_off, linfo + i, 17467 sizeof(*linfo) * (nr_linfo - i)); 17468 17469 prog->aux->nr_linfo -= l_cnt; 17470 nr_linfo = prog->aux->nr_linfo; 17471 } 17472 17473 /* pull all linfo[i].insn_off >= off + cnt in by cnt */ 17474 for (i = l_off; i < nr_linfo; i++) 17475 linfo[i].insn_off -= cnt; 17476 17477 /* fix up all subprogs (incl. 'exit') which start >= off */ 17478 for (i = 0; i <= env->subprog_cnt; i++) 17479 if (env->subprog_info[i].linfo_idx > l_off) { 17480 /* program may have started in the removed region but 17481 * may not be fully removed 17482 */ 17483 if (env->subprog_info[i].linfo_idx >= l_off + l_cnt) 17484 env->subprog_info[i].linfo_idx -= l_cnt; 17485 else 17486 env->subprog_info[i].linfo_idx = l_off; 17487 } 17488 17489 return 0; 17490 } 17491 17492 static int verifier_remove_insns(struct bpf_verifier_env *env, u32 off, u32 cnt) 17493 { 17494 struct bpf_insn_aux_data *aux_data = env->insn_aux_data; 17495 unsigned int orig_prog_len = env->prog->len; 17496 int err; 17497 17498 if (bpf_prog_is_offloaded(env->prog->aux)) 17499 bpf_prog_offload_remove_insns(env, off, cnt); 17500 17501 err = bpf_remove_insns(env->prog, off, cnt); 17502 if (err) 17503 return err; 17504 17505 err = adjust_subprog_starts_after_remove(env, off, cnt); 17506 if (err) 17507 return err; 17508 17509 err = bpf_adj_linfo_after_remove(env, off, cnt); 17510 if (err) 17511 return err; 17512 17513 memmove(aux_data + off, aux_data + off + cnt, 17514 sizeof(*aux_data) * (orig_prog_len - off - cnt)); 17515 17516 return 0; 17517 } 17518 17519 /* The verifier does more data flow analysis than llvm and will not 17520 * explore branches that are dead at run time. Malicious programs can 17521 * have dead code too. Therefore replace all dead at-run-time code 17522 * with 'ja -1'. 17523 * 17524 * Just nops are not optimal, e.g. if they would sit at the end of the 17525 * program and through another bug we would manage to jump there, then 17526 * we'd execute beyond program memory otherwise. Returning exception 17527 * code also wouldn't work since we can have subprogs where the dead 17528 * code could be located. 17529 */ 17530 static void sanitize_dead_code(struct bpf_verifier_env *env) 17531 { 17532 struct bpf_insn_aux_data *aux_data = env->insn_aux_data; 17533 struct bpf_insn trap = BPF_JMP_IMM(BPF_JA, 0, 0, -1); 17534 struct bpf_insn *insn = env->prog->insnsi; 17535 const int insn_cnt = env->prog->len; 17536 int i; 17537 17538 for (i = 0; i < insn_cnt; i++) { 17539 if (aux_data[i].seen) 17540 continue; 17541 memcpy(insn + i, &trap, sizeof(trap)); 17542 aux_data[i].zext_dst = false; 17543 } 17544 } 17545 17546 static bool insn_is_cond_jump(u8 code) 17547 { 17548 u8 op; 17549 17550 op = BPF_OP(code); 17551 if (BPF_CLASS(code) == BPF_JMP32) 17552 return op != BPF_JA; 17553 17554 if (BPF_CLASS(code) != BPF_JMP) 17555 return false; 17556 17557 return op != BPF_JA && op != BPF_EXIT && op != BPF_CALL; 17558 } 17559 17560 static void opt_hard_wire_dead_code_branches(struct bpf_verifier_env *env) 17561 { 17562 struct bpf_insn_aux_data *aux_data = env->insn_aux_data; 17563 struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0); 17564 struct bpf_insn *insn = env->prog->insnsi; 17565 const int insn_cnt = env->prog->len; 17566 int i; 17567 17568 for (i = 0; i < insn_cnt; i++, insn++) { 17569 if (!insn_is_cond_jump(insn->code)) 17570 continue; 17571 17572 if (!aux_data[i + 1].seen) 17573 ja.off = insn->off; 17574 else if (!aux_data[i + 1 + insn->off].seen) 17575 ja.off = 0; 17576 else 17577 continue; 17578 17579 if (bpf_prog_is_offloaded(env->prog->aux)) 17580 bpf_prog_offload_replace_insn(env, i, &ja); 17581 17582 memcpy(insn, &ja, sizeof(ja)); 17583 } 17584 } 17585 17586 static int opt_remove_dead_code(struct bpf_verifier_env *env) 17587 { 17588 struct bpf_insn_aux_data *aux_data = env->insn_aux_data; 17589 int insn_cnt = env->prog->len; 17590 int i, err; 17591 17592 for (i = 0; i < insn_cnt; i++) { 17593 int j; 17594 17595 j = 0; 17596 while (i + j < insn_cnt && !aux_data[i + j].seen) 17597 j++; 17598 if (!j) 17599 continue; 17600 17601 err = verifier_remove_insns(env, i, j); 17602 if (err) 17603 return err; 17604 insn_cnt = env->prog->len; 17605 } 17606 17607 return 0; 17608 } 17609 17610 static int opt_remove_nops(struct bpf_verifier_env *env) 17611 { 17612 const struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0); 17613 struct bpf_insn *insn = env->prog->insnsi; 17614 int insn_cnt = env->prog->len; 17615 int i, err; 17616 17617 for (i = 0; i < insn_cnt; i++) { 17618 if (memcmp(&insn[i], &ja, sizeof(ja))) 17619 continue; 17620 17621 err = verifier_remove_insns(env, i, 1); 17622 if (err) 17623 return err; 17624 insn_cnt--; 17625 i--; 17626 } 17627 17628 return 0; 17629 } 17630 17631 static int opt_subreg_zext_lo32_rnd_hi32(struct bpf_verifier_env *env, 17632 const union bpf_attr *attr) 17633 { 17634 struct bpf_insn *patch, zext_patch[2], rnd_hi32_patch[4]; 17635 struct bpf_insn_aux_data *aux = env->insn_aux_data; 17636 int i, patch_len, delta = 0, len = env->prog->len; 17637 struct bpf_insn *insns = env->prog->insnsi; 17638 struct bpf_prog *new_prog; 17639 bool rnd_hi32; 17640 17641 rnd_hi32 = attr->prog_flags & BPF_F_TEST_RND_HI32; 17642 zext_patch[1] = BPF_ZEXT_REG(0); 17643 rnd_hi32_patch[1] = BPF_ALU64_IMM(BPF_MOV, BPF_REG_AX, 0); 17644 rnd_hi32_patch[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_AX, 32); 17645 rnd_hi32_patch[3] = BPF_ALU64_REG(BPF_OR, 0, BPF_REG_AX); 17646 for (i = 0; i < len; i++) { 17647 int adj_idx = i + delta; 17648 struct bpf_insn insn; 17649 int load_reg; 17650 17651 insn = insns[adj_idx]; 17652 load_reg = insn_def_regno(&insn); 17653 if (!aux[adj_idx].zext_dst) { 17654 u8 code, class; 17655 u32 imm_rnd; 17656 17657 if (!rnd_hi32) 17658 continue; 17659 17660 code = insn.code; 17661 class = BPF_CLASS(code); 17662 if (load_reg == -1) 17663 continue; 17664 17665 /* NOTE: arg "reg" (the fourth one) is only used for 17666 * BPF_STX + SRC_OP, so it is safe to pass NULL 17667 * here. 17668 */ 17669 if (is_reg64(env, &insn, load_reg, NULL, DST_OP)) { 17670 if (class == BPF_LD && 17671 BPF_MODE(code) == BPF_IMM) 17672 i++; 17673 continue; 17674 } 17675 17676 /* ctx load could be transformed into wider load. */ 17677 if (class == BPF_LDX && 17678 aux[adj_idx].ptr_type == PTR_TO_CTX) 17679 continue; 17680 17681 imm_rnd = get_random_u32(); 17682 rnd_hi32_patch[0] = insn; 17683 rnd_hi32_patch[1].imm = imm_rnd; 17684 rnd_hi32_patch[3].dst_reg = load_reg; 17685 patch = rnd_hi32_patch; 17686 patch_len = 4; 17687 goto apply_patch_buffer; 17688 } 17689 17690 /* Add in an zero-extend instruction if a) the JIT has requested 17691 * it or b) it's a CMPXCHG. 17692 * 17693 * The latter is because: BPF_CMPXCHG always loads a value into 17694 * R0, therefore always zero-extends. However some archs' 17695 * equivalent instruction only does this load when the 17696 * comparison is successful. This detail of CMPXCHG is 17697 * orthogonal to the general zero-extension behaviour of the 17698 * CPU, so it's treated independently of bpf_jit_needs_zext. 17699 */ 17700 if (!bpf_jit_needs_zext() && !is_cmpxchg_insn(&insn)) 17701 continue; 17702 17703 /* Zero-extension is done by the caller. */ 17704 if (bpf_pseudo_kfunc_call(&insn)) 17705 continue; 17706 17707 if (WARN_ON(load_reg == -1)) { 17708 verbose(env, "verifier bug. zext_dst is set, but no reg is defined\n"); 17709 return -EFAULT; 17710 } 17711 17712 zext_patch[0] = insn; 17713 zext_patch[1].dst_reg = load_reg; 17714 zext_patch[1].src_reg = load_reg; 17715 patch = zext_patch; 17716 patch_len = 2; 17717 apply_patch_buffer: 17718 new_prog = bpf_patch_insn_data(env, adj_idx, patch, patch_len); 17719 if (!new_prog) 17720 return -ENOMEM; 17721 env->prog = new_prog; 17722 insns = new_prog->insnsi; 17723 aux = env->insn_aux_data; 17724 delta += patch_len - 1; 17725 } 17726 17727 return 0; 17728 } 17729 17730 /* convert load instructions that access fields of a context type into a 17731 * sequence of instructions that access fields of the underlying structure: 17732 * struct __sk_buff -> struct sk_buff 17733 * struct bpf_sock_ops -> struct sock 17734 */ 17735 static int convert_ctx_accesses(struct bpf_verifier_env *env) 17736 { 17737 const struct bpf_verifier_ops *ops = env->ops; 17738 int i, cnt, size, ctx_field_size, delta = 0; 17739 const int insn_cnt = env->prog->len; 17740 struct bpf_insn insn_buf[16], *insn; 17741 u32 target_size, size_default, off; 17742 struct bpf_prog *new_prog; 17743 enum bpf_access_type type; 17744 bool is_narrower_load; 17745 17746 if (ops->gen_prologue || env->seen_direct_write) { 17747 if (!ops->gen_prologue) { 17748 verbose(env, "bpf verifier is misconfigured\n"); 17749 return -EINVAL; 17750 } 17751 cnt = ops->gen_prologue(insn_buf, env->seen_direct_write, 17752 env->prog); 17753 if (cnt >= ARRAY_SIZE(insn_buf)) { 17754 verbose(env, "bpf verifier is misconfigured\n"); 17755 return -EINVAL; 17756 } else if (cnt) { 17757 new_prog = bpf_patch_insn_data(env, 0, insn_buf, cnt); 17758 if (!new_prog) 17759 return -ENOMEM; 17760 17761 env->prog = new_prog; 17762 delta += cnt - 1; 17763 } 17764 } 17765 17766 if (bpf_prog_is_offloaded(env->prog->aux)) 17767 return 0; 17768 17769 insn = env->prog->insnsi + delta; 17770 17771 for (i = 0; i < insn_cnt; i++, insn++) { 17772 bpf_convert_ctx_access_t convert_ctx_access; 17773 u8 mode; 17774 17775 if (insn->code == (BPF_LDX | BPF_MEM | BPF_B) || 17776 insn->code == (BPF_LDX | BPF_MEM | BPF_H) || 17777 insn->code == (BPF_LDX | BPF_MEM | BPF_W) || 17778 insn->code == (BPF_LDX | BPF_MEM | BPF_DW) || 17779 insn->code == (BPF_LDX | BPF_MEMSX | BPF_B) || 17780 insn->code == (BPF_LDX | BPF_MEMSX | BPF_H) || 17781 insn->code == (BPF_LDX | BPF_MEMSX | BPF_W)) { 17782 type = BPF_READ; 17783 } else if (insn->code == (BPF_STX | BPF_MEM | BPF_B) || 17784 insn->code == (BPF_STX | BPF_MEM | BPF_H) || 17785 insn->code == (BPF_STX | BPF_MEM | BPF_W) || 17786 insn->code == (BPF_STX | BPF_MEM | BPF_DW) || 17787 insn->code == (BPF_ST | BPF_MEM | BPF_B) || 17788 insn->code == (BPF_ST | BPF_MEM | BPF_H) || 17789 insn->code == (BPF_ST | BPF_MEM | BPF_W) || 17790 insn->code == (BPF_ST | BPF_MEM | BPF_DW)) { 17791 type = BPF_WRITE; 17792 } else { 17793 continue; 17794 } 17795 17796 if (type == BPF_WRITE && 17797 env->insn_aux_data[i + delta].sanitize_stack_spill) { 17798 struct bpf_insn patch[] = { 17799 *insn, 17800 BPF_ST_NOSPEC(), 17801 }; 17802 17803 cnt = ARRAY_SIZE(patch); 17804 new_prog = bpf_patch_insn_data(env, i + delta, patch, cnt); 17805 if (!new_prog) 17806 return -ENOMEM; 17807 17808 delta += cnt - 1; 17809 env->prog = new_prog; 17810 insn = new_prog->insnsi + i + delta; 17811 continue; 17812 } 17813 17814 switch ((int)env->insn_aux_data[i + delta].ptr_type) { 17815 case PTR_TO_CTX: 17816 if (!ops->convert_ctx_access) 17817 continue; 17818 convert_ctx_access = ops->convert_ctx_access; 17819 break; 17820 case PTR_TO_SOCKET: 17821 case PTR_TO_SOCK_COMMON: 17822 convert_ctx_access = bpf_sock_convert_ctx_access; 17823 break; 17824 case PTR_TO_TCP_SOCK: 17825 convert_ctx_access = bpf_tcp_sock_convert_ctx_access; 17826 break; 17827 case PTR_TO_XDP_SOCK: 17828 convert_ctx_access = bpf_xdp_sock_convert_ctx_access; 17829 break; 17830 case PTR_TO_BTF_ID: 17831 case PTR_TO_BTF_ID | PTR_UNTRUSTED: 17832 /* PTR_TO_BTF_ID | MEM_ALLOC always has a valid lifetime, unlike 17833 * PTR_TO_BTF_ID, and an active ref_obj_id, but the same cannot 17834 * be said once it is marked PTR_UNTRUSTED, hence we must handle 17835 * any faults for loads into such types. BPF_WRITE is disallowed 17836 * for this case. 17837 */ 17838 case PTR_TO_BTF_ID | MEM_ALLOC | PTR_UNTRUSTED: 17839 if (type == BPF_READ) { 17840 if (BPF_MODE(insn->code) == BPF_MEM) 17841 insn->code = BPF_LDX | BPF_PROBE_MEM | 17842 BPF_SIZE((insn)->code); 17843 else 17844 insn->code = BPF_LDX | BPF_PROBE_MEMSX | 17845 BPF_SIZE((insn)->code); 17846 env->prog->aux->num_exentries++; 17847 } 17848 continue; 17849 default: 17850 continue; 17851 } 17852 17853 ctx_field_size = env->insn_aux_data[i + delta].ctx_field_size; 17854 size = BPF_LDST_BYTES(insn); 17855 mode = BPF_MODE(insn->code); 17856 17857 /* If the read access is a narrower load of the field, 17858 * convert to a 4/8-byte load, to minimum program type specific 17859 * convert_ctx_access changes. If conversion is successful, 17860 * we will apply proper mask to the result. 17861 */ 17862 is_narrower_load = size < ctx_field_size; 17863 size_default = bpf_ctx_off_adjust_machine(ctx_field_size); 17864 off = insn->off; 17865 if (is_narrower_load) { 17866 u8 size_code; 17867 17868 if (type == BPF_WRITE) { 17869 verbose(env, "bpf verifier narrow ctx access misconfigured\n"); 17870 return -EINVAL; 17871 } 17872 17873 size_code = BPF_H; 17874 if (ctx_field_size == 4) 17875 size_code = BPF_W; 17876 else if (ctx_field_size == 8) 17877 size_code = BPF_DW; 17878 17879 insn->off = off & ~(size_default - 1); 17880 insn->code = BPF_LDX | BPF_MEM | size_code; 17881 } 17882 17883 target_size = 0; 17884 cnt = convert_ctx_access(type, insn, insn_buf, env->prog, 17885 &target_size); 17886 if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf) || 17887 (ctx_field_size && !target_size)) { 17888 verbose(env, "bpf verifier is misconfigured\n"); 17889 return -EINVAL; 17890 } 17891 17892 if (is_narrower_load && size < target_size) { 17893 u8 shift = bpf_ctx_narrow_access_offset( 17894 off, size, size_default) * 8; 17895 if (shift && cnt + 1 >= ARRAY_SIZE(insn_buf)) { 17896 verbose(env, "bpf verifier narrow ctx load misconfigured\n"); 17897 return -EINVAL; 17898 } 17899 if (ctx_field_size <= 4) { 17900 if (shift) 17901 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_RSH, 17902 insn->dst_reg, 17903 shift); 17904 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg, 17905 (1 << size * 8) - 1); 17906 } else { 17907 if (shift) 17908 insn_buf[cnt++] = BPF_ALU64_IMM(BPF_RSH, 17909 insn->dst_reg, 17910 shift); 17911 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg, 17912 (1ULL << size * 8) - 1); 17913 } 17914 } 17915 if (mode == BPF_MEMSX) 17916 insn_buf[cnt++] = BPF_RAW_INSN(BPF_ALU64 | BPF_MOV | BPF_X, 17917 insn->dst_reg, insn->dst_reg, 17918 size * 8, 0); 17919 17920 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 17921 if (!new_prog) 17922 return -ENOMEM; 17923 17924 delta += cnt - 1; 17925 17926 /* keep walking new program and skip insns we just inserted */ 17927 env->prog = new_prog; 17928 insn = new_prog->insnsi + i + delta; 17929 } 17930 17931 return 0; 17932 } 17933 17934 static int jit_subprogs(struct bpf_verifier_env *env) 17935 { 17936 struct bpf_prog *prog = env->prog, **func, *tmp; 17937 int i, j, subprog_start, subprog_end = 0, len, subprog; 17938 struct bpf_map *map_ptr; 17939 struct bpf_insn *insn; 17940 void *old_bpf_func; 17941 int err, num_exentries; 17942 17943 if (env->subprog_cnt <= 1) 17944 return 0; 17945 17946 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) { 17947 if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn)) 17948 continue; 17949 17950 /* Upon error here we cannot fall back to interpreter but 17951 * need a hard reject of the program. Thus -EFAULT is 17952 * propagated in any case. 17953 */ 17954 subprog = find_subprog(env, i + insn->imm + 1); 17955 if (subprog < 0) { 17956 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n", 17957 i + insn->imm + 1); 17958 return -EFAULT; 17959 } 17960 /* temporarily remember subprog id inside insn instead of 17961 * aux_data, since next loop will split up all insns into funcs 17962 */ 17963 insn->off = subprog; 17964 /* remember original imm in case JIT fails and fallback 17965 * to interpreter will be needed 17966 */ 17967 env->insn_aux_data[i].call_imm = insn->imm; 17968 /* point imm to __bpf_call_base+1 from JITs point of view */ 17969 insn->imm = 1; 17970 if (bpf_pseudo_func(insn)) 17971 /* jit (e.g. x86_64) may emit fewer instructions 17972 * if it learns a u32 imm is the same as a u64 imm. 17973 * Force a non zero here. 17974 */ 17975 insn[1].imm = 1; 17976 } 17977 17978 err = bpf_prog_alloc_jited_linfo(prog); 17979 if (err) 17980 goto out_undo_insn; 17981 17982 err = -ENOMEM; 17983 func = kcalloc(env->subprog_cnt, sizeof(prog), GFP_KERNEL); 17984 if (!func) 17985 goto out_undo_insn; 17986 17987 for (i = 0; i < env->subprog_cnt; i++) { 17988 subprog_start = subprog_end; 17989 subprog_end = env->subprog_info[i + 1].start; 17990 17991 len = subprog_end - subprog_start; 17992 /* bpf_prog_run() doesn't call subprogs directly, 17993 * hence main prog stats include the runtime of subprogs. 17994 * subprogs don't have IDs and not reachable via prog_get_next_id 17995 * func[i]->stats will never be accessed and stays NULL 17996 */ 17997 func[i] = bpf_prog_alloc_no_stats(bpf_prog_size(len), GFP_USER); 17998 if (!func[i]) 17999 goto out_free; 18000 memcpy(func[i]->insnsi, &prog->insnsi[subprog_start], 18001 len * sizeof(struct bpf_insn)); 18002 func[i]->type = prog->type; 18003 func[i]->len = len; 18004 if (bpf_prog_calc_tag(func[i])) 18005 goto out_free; 18006 func[i]->is_func = 1; 18007 func[i]->aux->func_idx = i; 18008 /* Below members will be freed only at prog->aux */ 18009 func[i]->aux->btf = prog->aux->btf; 18010 func[i]->aux->func_info = prog->aux->func_info; 18011 func[i]->aux->func_info_cnt = prog->aux->func_info_cnt; 18012 func[i]->aux->poke_tab = prog->aux->poke_tab; 18013 func[i]->aux->size_poke_tab = prog->aux->size_poke_tab; 18014 18015 for (j = 0; j < prog->aux->size_poke_tab; j++) { 18016 struct bpf_jit_poke_descriptor *poke; 18017 18018 poke = &prog->aux->poke_tab[j]; 18019 if (poke->insn_idx < subprog_end && 18020 poke->insn_idx >= subprog_start) 18021 poke->aux = func[i]->aux; 18022 } 18023 18024 func[i]->aux->name[0] = 'F'; 18025 func[i]->aux->stack_depth = env->subprog_info[i].stack_depth; 18026 func[i]->jit_requested = 1; 18027 func[i]->blinding_requested = prog->blinding_requested; 18028 func[i]->aux->kfunc_tab = prog->aux->kfunc_tab; 18029 func[i]->aux->kfunc_btf_tab = prog->aux->kfunc_btf_tab; 18030 func[i]->aux->linfo = prog->aux->linfo; 18031 func[i]->aux->nr_linfo = prog->aux->nr_linfo; 18032 func[i]->aux->jited_linfo = prog->aux->jited_linfo; 18033 func[i]->aux->linfo_idx = env->subprog_info[i].linfo_idx; 18034 num_exentries = 0; 18035 insn = func[i]->insnsi; 18036 for (j = 0; j < func[i]->len; j++, insn++) { 18037 if (BPF_CLASS(insn->code) == BPF_LDX && 18038 (BPF_MODE(insn->code) == BPF_PROBE_MEM || 18039 BPF_MODE(insn->code) == BPF_PROBE_MEMSX)) 18040 num_exentries++; 18041 } 18042 func[i]->aux->num_exentries = num_exentries; 18043 func[i]->aux->tail_call_reachable = env->subprog_info[i].tail_call_reachable; 18044 func[i] = bpf_int_jit_compile(func[i]); 18045 if (!func[i]->jited) { 18046 err = -ENOTSUPP; 18047 goto out_free; 18048 } 18049 cond_resched(); 18050 } 18051 18052 /* at this point all bpf functions were successfully JITed 18053 * now populate all bpf_calls with correct addresses and 18054 * run last pass of JIT 18055 */ 18056 for (i = 0; i < env->subprog_cnt; i++) { 18057 insn = func[i]->insnsi; 18058 for (j = 0; j < func[i]->len; j++, insn++) { 18059 if (bpf_pseudo_func(insn)) { 18060 subprog = insn->off; 18061 insn[0].imm = (u32)(long)func[subprog]->bpf_func; 18062 insn[1].imm = ((u64)(long)func[subprog]->bpf_func) >> 32; 18063 continue; 18064 } 18065 if (!bpf_pseudo_call(insn)) 18066 continue; 18067 subprog = insn->off; 18068 insn->imm = BPF_CALL_IMM(func[subprog]->bpf_func); 18069 } 18070 18071 /* we use the aux data to keep a list of the start addresses 18072 * of the JITed images for each function in the program 18073 * 18074 * for some architectures, such as powerpc64, the imm field 18075 * might not be large enough to hold the offset of the start 18076 * address of the callee's JITed image from __bpf_call_base 18077 * 18078 * in such cases, we can lookup the start address of a callee 18079 * by using its subprog id, available from the off field of 18080 * the call instruction, as an index for this list 18081 */ 18082 func[i]->aux->func = func; 18083 func[i]->aux->func_cnt = env->subprog_cnt; 18084 } 18085 for (i = 0; i < env->subprog_cnt; i++) { 18086 old_bpf_func = func[i]->bpf_func; 18087 tmp = bpf_int_jit_compile(func[i]); 18088 if (tmp != func[i] || func[i]->bpf_func != old_bpf_func) { 18089 verbose(env, "JIT doesn't support bpf-to-bpf calls\n"); 18090 err = -ENOTSUPP; 18091 goto out_free; 18092 } 18093 cond_resched(); 18094 } 18095 18096 /* finally lock prog and jit images for all functions and 18097 * populate kallsysm. Begin at the first subprogram, since 18098 * bpf_prog_load will add the kallsyms for the main program. 18099 */ 18100 for (i = 1; i < env->subprog_cnt; i++) { 18101 bpf_prog_lock_ro(func[i]); 18102 bpf_prog_kallsyms_add(func[i]); 18103 } 18104 18105 /* Last step: make now unused interpreter insns from main 18106 * prog consistent for later dump requests, so they can 18107 * later look the same as if they were interpreted only. 18108 */ 18109 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) { 18110 if (bpf_pseudo_func(insn)) { 18111 insn[0].imm = env->insn_aux_data[i].call_imm; 18112 insn[1].imm = insn->off; 18113 insn->off = 0; 18114 continue; 18115 } 18116 if (!bpf_pseudo_call(insn)) 18117 continue; 18118 insn->off = env->insn_aux_data[i].call_imm; 18119 subprog = find_subprog(env, i + insn->off + 1); 18120 insn->imm = subprog; 18121 } 18122 18123 prog->jited = 1; 18124 prog->bpf_func = func[0]->bpf_func; 18125 prog->jited_len = func[0]->jited_len; 18126 prog->aux->extable = func[0]->aux->extable; 18127 prog->aux->num_exentries = func[0]->aux->num_exentries; 18128 prog->aux->func = func; 18129 prog->aux->func_cnt = env->subprog_cnt; 18130 bpf_prog_jit_attempt_done(prog); 18131 return 0; 18132 out_free: 18133 /* We failed JIT'ing, so at this point we need to unregister poke 18134 * descriptors from subprogs, so that kernel is not attempting to 18135 * patch it anymore as we're freeing the subprog JIT memory. 18136 */ 18137 for (i = 0; i < prog->aux->size_poke_tab; i++) { 18138 map_ptr = prog->aux->poke_tab[i].tail_call.map; 18139 map_ptr->ops->map_poke_untrack(map_ptr, prog->aux); 18140 } 18141 /* At this point we're guaranteed that poke descriptors are not 18142 * live anymore. We can just unlink its descriptor table as it's 18143 * released with the main prog. 18144 */ 18145 for (i = 0; i < env->subprog_cnt; i++) { 18146 if (!func[i]) 18147 continue; 18148 func[i]->aux->poke_tab = NULL; 18149 bpf_jit_free(func[i]); 18150 } 18151 kfree(func); 18152 out_undo_insn: 18153 /* cleanup main prog to be interpreted */ 18154 prog->jit_requested = 0; 18155 prog->blinding_requested = 0; 18156 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) { 18157 if (!bpf_pseudo_call(insn)) 18158 continue; 18159 insn->off = 0; 18160 insn->imm = env->insn_aux_data[i].call_imm; 18161 } 18162 bpf_prog_jit_attempt_done(prog); 18163 return err; 18164 } 18165 18166 static int fixup_call_args(struct bpf_verifier_env *env) 18167 { 18168 #ifndef CONFIG_BPF_JIT_ALWAYS_ON 18169 struct bpf_prog *prog = env->prog; 18170 struct bpf_insn *insn = prog->insnsi; 18171 bool has_kfunc_call = bpf_prog_has_kfunc_call(prog); 18172 int i, depth; 18173 #endif 18174 int err = 0; 18175 18176 if (env->prog->jit_requested && 18177 !bpf_prog_is_offloaded(env->prog->aux)) { 18178 err = jit_subprogs(env); 18179 if (err == 0) 18180 return 0; 18181 if (err == -EFAULT) 18182 return err; 18183 } 18184 #ifndef CONFIG_BPF_JIT_ALWAYS_ON 18185 if (has_kfunc_call) { 18186 verbose(env, "calling kernel functions are not allowed in non-JITed programs\n"); 18187 return -EINVAL; 18188 } 18189 if (env->subprog_cnt > 1 && env->prog->aux->tail_call_reachable) { 18190 /* When JIT fails the progs with bpf2bpf calls and tail_calls 18191 * have to be rejected, since interpreter doesn't support them yet. 18192 */ 18193 verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n"); 18194 return -EINVAL; 18195 } 18196 for (i = 0; i < prog->len; i++, insn++) { 18197 if (bpf_pseudo_func(insn)) { 18198 /* When JIT fails the progs with callback calls 18199 * have to be rejected, since interpreter doesn't support them yet. 18200 */ 18201 verbose(env, "callbacks are not allowed in non-JITed programs\n"); 18202 return -EINVAL; 18203 } 18204 18205 if (!bpf_pseudo_call(insn)) 18206 continue; 18207 depth = get_callee_stack_depth(env, insn, i); 18208 if (depth < 0) 18209 return depth; 18210 bpf_patch_call_args(insn, depth); 18211 } 18212 err = 0; 18213 #endif 18214 return err; 18215 } 18216 18217 /* replace a generic kfunc with a specialized version if necessary */ 18218 static void specialize_kfunc(struct bpf_verifier_env *env, 18219 u32 func_id, u16 offset, unsigned long *addr) 18220 { 18221 struct bpf_prog *prog = env->prog; 18222 bool seen_direct_write; 18223 void *xdp_kfunc; 18224 bool is_rdonly; 18225 18226 if (bpf_dev_bound_kfunc_id(func_id)) { 18227 xdp_kfunc = bpf_dev_bound_resolve_kfunc(prog, func_id); 18228 if (xdp_kfunc) { 18229 *addr = (unsigned long)xdp_kfunc; 18230 return; 18231 } 18232 /* fallback to default kfunc when not supported by netdev */ 18233 } 18234 18235 if (offset) 18236 return; 18237 18238 if (func_id == special_kfunc_list[KF_bpf_dynptr_from_skb]) { 18239 seen_direct_write = env->seen_direct_write; 18240 is_rdonly = !may_access_direct_pkt_data(env, NULL, BPF_WRITE); 18241 18242 if (is_rdonly) 18243 *addr = (unsigned long)bpf_dynptr_from_skb_rdonly; 18244 18245 /* restore env->seen_direct_write to its original value, since 18246 * may_access_direct_pkt_data mutates it 18247 */ 18248 env->seen_direct_write = seen_direct_write; 18249 } 18250 } 18251 18252 static void __fixup_collection_insert_kfunc(struct bpf_insn_aux_data *insn_aux, 18253 u16 struct_meta_reg, 18254 u16 node_offset_reg, 18255 struct bpf_insn *insn, 18256 struct bpf_insn *insn_buf, 18257 int *cnt) 18258 { 18259 struct btf_struct_meta *kptr_struct_meta = insn_aux->kptr_struct_meta; 18260 struct bpf_insn addr[2] = { BPF_LD_IMM64(struct_meta_reg, (long)kptr_struct_meta) }; 18261 18262 insn_buf[0] = addr[0]; 18263 insn_buf[1] = addr[1]; 18264 insn_buf[2] = BPF_MOV64_IMM(node_offset_reg, insn_aux->insert_off); 18265 insn_buf[3] = *insn; 18266 *cnt = 4; 18267 } 18268 18269 static int fixup_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn, 18270 struct bpf_insn *insn_buf, int insn_idx, int *cnt) 18271 { 18272 const struct bpf_kfunc_desc *desc; 18273 18274 if (!insn->imm) { 18275 verbose(env, "invalid kernel function call not eliminated in verifier pass\n"); 18276 return -EINVAL; 18277 } 18278 18279 *cnt = 0; 18280 18281 /* insn->imm has the btf func_id. Replace it with an offset relative to 18282 * __bpf_call_base, unless the JIT needs to call functions that are 18283 * further than 32 bits away (bpf_jit_supports_far_kfunc_call()). 18284 */ 18285 desc = find_kfunc_desc(env->prog, insn->imm, insn->off); 18286 if (!desc) { 18287 verbose(env, "verifier internal error: kernel function descriptor not found for func_id %u\n", 18288 insn->imm); 18289 return -EFAULT; 18290 } 18291 18292 if (!bpf_jit_supports_far_kfunc_call()) 18293 insn->imm = BPF_CALL_IMM(desc->addr); 18294 if (insn->off) 18295 return 0; 18296 if (desc->func_id == special_kfunc_list[KF_bpf_obj_new_impl]) { 18297 struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta; 18298 struct bpf_insn addr[2] = { BPF_LD_IMM64(BPF_REG_2, (long)kptr_struct_meta) }; 18299 u64 obj_new_size = env->insn_aux_data[insn_idx].obj_new_size; 18300 18301 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_1, obj_new_size); 18302 insn_buf[1] = addr[0]; 18303 insn_buf[2] = addr[1]; 18304 insn_buf[3] = *insn; 18305 *cnt = 4; 18306 } else if (desc->func_id == special_kfunc_list[KF_bpf_obj_drop_impl] || 18307 desc->func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl]) { 18308 struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta; 18309 struct bpf_insn addr[2] = { BPF_LD_IMM64(BPF_REG_2, (long)kptr_struct_meta) }; 18310 18311 if (desc->func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl] && 18312 !kptr_struct_meta) { 18313 verbose(env, "verifier internal error: kptr_struct_meta expected at insn_idx %d\n", 18314 insn_idx); 18315 return -EFAULT; 18316 } 18317 18318 insn_buf[0] = addr[0]; 18319 insn_buf[1] = addr[1]; 18320 insn_buf[2] = *insn; 18321 *cnt = 3; 18322 } else if (desc->func_id == special_kfunc_list[KF_bpf_list_push_back_impl] || 18323 desc->func_id == special_kfunc_list[KF_bpf_list_push_front_impl] || 18324 desc->func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) { 18325 struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta; 18326 int struct_meta_reg = BPF_REG_3; 18327 int node_offset_reg = BPF_REG_4; 18328 18329 /* rbtree_add has extra 'less' arg, so args-to-fixup are in diff regs */ 18330 if (desc->func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) { 18331 struct_meta_reg = BPF_REG_4; 18332 node_offset_reg = BPF_REG_5; 18333 } 18334 18335 if (!kptr_struct_meta) { 18336 verbose(env, "verifier internal error: kptr_struct_meta expected at insn_idx %d\n", 18337 insn_idx); 18338 return -EFAULT; 18339 } 18340 18341 __fixup_collection_insert_kfunc(&env->insn_aux_data[insn_idx], struct_meta_reg, 18342 node_offset_reg, insn, insn_buf, cnt); 18343 } else if (desc->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx] || 18344 desc->func_id == special_kfunc_list[KF_bpf_rdonly_cast]) { 18345 insn_buf[0] = BPF_MOV64_REG(BPF_REG_0, BPF_REG_1); 18346 *cnt = 1; 18347 } 18348 return 0; 18349 } 18350 18351 /* Do various post-verification rewrites in a single program pass. 18352 * These rewrites simplify JIT and interpreter implementations. 18353 */ 18354 static int do_misc_fixups(struct bpf_verifier_env *env) 18355 { 18356 struct bpf_prog *prog = env->prog; 18357 enum bpf_attach_type eatype = prog->expected_attach_type; 18358 enum bpf_prog_type prog_type = resolve_prog_type(prog); 18359 struct bpf_insn *insn = prog->insnsi; 18360 const struct bpf_func_proto *fn; 18361 const int insn_cnt = prog->len; 18362 const struct bpf_map_ops *ops; 18363 struct bpf_insn_aux_data *aux; 18364 struct bpf_insn insn_buf[16]; 18365 struct bpf_prog *new_prog; 18366 struct bpf_map *map_ptr; 18367 int i, ret, cnt, delta = 0; 18368 18369 for (i = 0; i < insn_cnt; i++, insn++) { 18370 /* Make divide-by-zero exceptions impossible. */ 18371 if (insn->code == (BPF_ALU64 | BPF_MOD | BPF_X) || 18372 insn->code == (BPF_ALU64 | BPF_DIV | BPF_X) || 18373 insn->code == (BPF_ALU | BPF_MOD | BPF_X) || 18374 insn->code == (BPF_ALU | BPF_DIV | BPF_X)) { 18375 bool is64 = BPF_CLASS(insn->code) == BPF_ALU64; 18376 bool isdiv = BPF_OP(insn->code) == BPF_DIV; 18377 struct bpf_insn *patchlet; 18378 struct bpf_insn chk_and_div[] = { 18379 /* [R,W]x div 0 -> 0 */ 18380 BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) | 18381 BPF_JNE | BPF_K, insn->src_reg, 18382 0, 2, 0), 18383 BPF_ALU32_REG(BPF_XOR, insn->dst_reg, insn->dst_reg), 18384 BPF_JMP_IMM(BPF_JA, 0, 0, 1), 18385 *insn, 18386 }; 18387 struct bpf_insn chk_and_mod[] = { 18388 /* [R,W]x mod 0 -> [R,W]x */ 18389 BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) | 18390 BPF_JEQ | BPF_K, insn->src_reg, 18391 0, 1 + (is64 ? 0 : 1), 0), 18392 *insn, 18393 BPF_JMP_IMM(BPF_JA, 0, 0, 1), 18394 BPF_MOV32_REG(insn->dst_reg, insn->dst_reg), 18395 }; 18396 18397 patchlet = isdiv ? chk_and_div : chk_and_mod; 18398 cnt = isdiv ? ARRAY_SIZE(chk_and_div) : 18399 ARRAY_SIZE(chk_and_mod) - (is64 ? 2 : 0); 18400 18401 new_prog = bpf_patch_insn_data(env, i + delta, patchlet, cnt); 18402 if (!new_prog) 18403 return -ENOMEM; 18404 18405 delta += cnt - 1; 18406 env->prog = prog = new_prog; 18407 insn = new_prog->insnsi + i + delta; 18408 continue; 18409 } 18410 18411 /* Implement LD_ABS and LD_IND with a rewrite, if supported by the program type. */ 18412 if (BPF_CLASS(insn->code) == BPF_LD && 18413 (BPF_MODE(insn->code) == BPF_ABS || 18414 BPF_MODE(insn->code) == BPF_IND)) { 18415 cnt = env->ops->gen_ld_abs(insn, insn_buf); 18416 if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf)) { 18417 verbose(env, "bpf verifier is misconfigured\n"); 18418 return -EINVAL; 18419 } 18420 18421 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 18422 if (!new_prog) 18423 return -ENOMEM; 18424 18425 delta += cnt - 1; 18426 env->prog = prog = new_prog; 18427 insn = new_prog->insnsi + i + delta; 18428 continue; 18429 } 18430 18431 /* Rewrite pointer arithmetic to mitigate speculation attacks. */ 18432 if (insn->code == (BPF_ALU64 | BPF_ADD | BPF_X) || 18433 insn->code == (BPF_ALU64 | BPF_SUB | BPF_X)) { 18434 const u8 code_add = BPF_ALU64 | BPF_ADD | BPF_X; 18435 const u8 code_sub = BPF_ALU64 | BPF_SUB | BPF_X; 18436 struct bpf_insn *patch = &insn_buf[0]; 18437 bool issrc, isneg, isimm; 18438 u32 off_reg; 18439 18440 aux = &env->insn_aux_data[i + delta]; 18441 if (!aux->alu_state || 18442 aux->alu_state == BPF_ALU_NON_POINTER) 18443 continue; 18444 18445 isneg = aux->alu_state & BPF_ALU_NEG_VALUE; 18446 issrc = (aux->alu_state & BPF_ALU_SANITIZE) == 18447 BPF_ALU_SANITIZE_SRC; 18448 isimm = aux->alu_state & BPF_ALU_IMMEDIATE; 18449 18450 off_reg = issrc ? insn->src_reg : insn->dst_reg; 18451 if (isimm) { 18452 *patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit); 18453 } else { 18454 if (isneg) 18455 *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1); 18456 *patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit); 18457 *patch++ = BPF_ALU64_REG(BPF_SUB, BPF_REG_AX, off_reg); 18458 *patch++ = BPF_ALU64_REG(BPF_OR, BPF_REG_AX, off_reg); 18459 *patch++ = BPF_ALU64_IMM(BPF_NEG, BPF_REG_AX, 0); 18460 *patch++ = BPF_ALU64_IMM(BPF_ARSH, BPF_REG_AX, 63); 18461 *patch++ = BPF_ALU64_REG(BPF_AND, BPF_REG_AX, off_reg); 18462 } 18463 if (!issrc) 18464 *patch++ = BPF_MOV64_REG(insn->dst_reg, insn->src_reg); 18465 insn->src_reg = BPF_REG_AX; 18466 if (isneg) 18467 insn->code = insn->code == code_add ? 18468 code_sub : code_add; 18469 *patch++ = *insn; 18470 if (issrc && isneg && !isimm) 18471 *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1); 18472 cnt = patch - insn_buf; 18473 18474 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 18475 if (!new_prog) 18476 return -ENOMEM; 18477 18478 delta += cnt - 1; 18479 env->prog = prog = new_prog; 18480 insn = new_prog->insnsi + i + delta; 18481 continue; 18482 } 18483 18484 if (insn->code != (BPF_JMP | BPF_CALL)) 18485 continue; 18486 if (insn->src_reg == BPF_PSEUDO_CALL) 18487 continue; 18488 if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) { 18489 ret = fixup_kfunc_call(env, insn, insn_buf, i + delta, &cnt); 18490 if (ret) 18491 return ret; 18492 if (cnt == 0) 18493 continue; 18494 18495 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 18496 if (!new_prog) 18497 return -ENOMEM; 18498 18499 delta += cnt - 1; 18500 env->prog = prog = new_prog; 18501 insn = new_prog->insnsi + i + delta; 18502 continue; 18503 } 18504 18505 if (insn->imm == BPF_FUNC_get_route_realm) 18506 prog->dst_needed = 1; 18507 if (insn->imm == BPF_FUNC_get_prandom_u32) 18508 bpf_user_rnd_init_once(); 18509 if (insn->imm == BPF_FUNC_override_return) 18510 prog->kprobe_override = 1; 18511 if (insn->imm == BPF_FUNC_tail_call) { 18512 /* If we tail call into other programs, we 18513 * cannot make any assumptions since they can 18514 * be replaced dynamically during runtime in 18515 * the program array. 18516 */ 18517 prog->cb_access = 1; 18518 if (!allow_tail_call_in_subprogs(env)) 18519 prog->aux->stack_depth = MAX_BPF_STACK; 18520 prog->aux->max_pkt_offset = MAX_PACKET_OFF; 18521 18522 /* mark bpf_tail_call as different opcode to avoid 18523 * conditional branch in the interpreter for every normal 18524 * call and to prevent accidental JITing by JIT compiler 18525 * that doesn't support bpf_tail_call yet 18526 */ 18527 insn->imm = 0; 18528 insn->code = BPF_JMP | BPF_TAIL_CALL; 18529 18530 aux = &env->insn_aux_data[i + delta]; 18531 if (env->bpf_capable && !prog->blinding_requested && 18532 prog->jit_requested && 18533 !bpf_map_key_poisoned(aux) && 18534 !bpf_map_ptr_poisoned(aux) && 18535 !bpf_map_ptr_unpriv(aux)) { 18536 struct bpf_jit_poke_descriptor desc = { 18537 .reason = BPF_POKE_REASON_TAIL_CALL, 18538 .tail_call.map = BPF_MAP_PTR(aux->map_ptr_state), 18539 .tail_call.key = bpf_map_key_immediate(aux), 18540 .insn_idx = i + delta, 18541 }; 18542 18543 ret = bpf_jit_add_poke_descriptor(prog, &desc); 18544 if (ret < 0) { 18545 verbose(env, "adding tail call poke descriptor failed\n"); 18546 return ret; 18547 } 18548 18549 insn->imm = ret + 1; 18550 continue; 18551 } 18552 18553 if (!bpf_map_ptr_unpriv(aux)) 18554 continue; 18555 18556 /* instead of changing every JIT dealing with tail_call 18557 * emit two extra insns: 18558 * if (index >= max_entries) goto out; 18559 * index &= array->index_mask; 18560 * to avoid out-of-bounds cpu speculation 18561 */ 18562 if (bpf_map_ptr_poisoned(aux)) { 18563 verbose(env, "tail_call abusing map_ptr\n"); 18564 return -EINVAL; 18565 } 18566 18567 map_ptr = BPF_MAP_PTR(aux->map_ptr_state); 18568 insn_buf[0] = BPF_JMP_IMM(BPF_JGE, BPF_REG_3, 18569 map_ptr->max_entries, 2); 18570 insn_buf[1] = BPF_ALU32_IMM(BPF_AND, BPF_REG_3, 18571 container_of(map_ptr, 18572 struct bpf_array, 18573 map)->index_mask); 18574 insn_buf[2] = *insn; 18575 cnt = 3; 18576 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 18577 if (!new_prog) 18578 return -ENOMEM; 18579 18580 delta += cnt - 1; 18581 env->prog = prog = new_prog; 18582 insn = new_prog->insnsi + i + delta; 18583 continue; 18584 } 18585 18586 if (insn->imm == BPF_FUNC_timer_set_callback) { 18587 /* The verifier will process callback_fn as many times as necessary 18588 * with different maps and the register states prepared by 18589 * set_timer_callback_state will be accurate. 18590 * 18591 * The following use case is valid: 18592 * map1 is shared by prog1, prog2, prog3. 18593 * prog1 calls bpf_timer_init for some map1 elements 18594 * prog2 calls bpf_timer_set_callback for some map1 elements. 18595 * Those that were not bpf_timer_init-ed will return -EINVAL. 18596 * prog3 calls bpf_timer_start for some map1 elements. 18597 * Those that were not both bpf_timer_init-ed and 18598 * bpf_timer_set_callback-ed will return -EINVAL. 18599 */ 18600 struct bpf_insn ld_addrs[2] = { 18601 BPF_LD_IMM64(BPF_REG_3, (long)prog->aux), 18602 }; 18603 18604 insn_buf[0] = ld_addrs[0]; 18605 insn_buf[1] = ld_addrs[1]; 18606 insn_buf[2] = *insn; 18607 cnt = 3; 18608 18609 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 18610 if (!new_prog) 18611 return -ENOMEM; 18612 18613 delta += cnt - 1; 18614 env->prog = prog = new_prog; 18615 insn = new_prog->insnsi + i + delta; 18616 goto patch_call_imm; 18617 } 18618 18619 if (is_storage_get_function(insn->imm)) { 18620 if (!env->prog->aux->sleepable || 18621 env->insn_aux_data[i + delta].storage_get_func_atomic) 18622 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_5, (__force __s32)GFP_ATOMIC); 18623 else 18624 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_5, (__force __s32)GFP_KERNEL); 18625 insn_buf[1] = *insn; 18626 cnt = 2; 18627 18628 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 18629 if (!new_prog) 18630 return -ENOMEM; 18631 18632 delta += cnt - 1; 18633 env->prog = prog = new_prog; 18634 insn = new_prog->insnsi + i + delta; 18635 goto patch_call_imm; 18636 } 18637 18638 /* BPF_EMIT_CALL() assumptions in some of the map_gen_lookup 18639 * and other inlining handlers are currently limited to 64 bit 18640 * only. 18641 */ 18642 if (prog->jit_requested && BITS_PER_LONG == 64 && 18643 (insn->imm == BPF_FUNC_map_lookup_elem || 18644 insn->imm == BPF_FUNC_map_update_elem || 18645 insn->imm == BPF_FUNC_map_delete_elem || 18646 insn->imm == BPF_FUNC_map_push_elem || 18647 insn->imm == BPF_FUNC_map_pop_elem || 18648 insn->imm == BPF_FUNC_map_peek_elem || 18649 insn->imm == BPF_FUNC_redirect_map || 18650 insn->imm == BPF_FUNC_for_each_map_elem || 18651 insn->imm == BPF_FUNC_map_lookup_percpu_elem)) { 18652 aux = &env->insn_aux_data[i + delta]; 18653 if (bpf_map_ptr_poisoned(aux)) 18654 goto patch_call_imm; 18655 18656 map_ptr = BPF_MAP_PTR(aux->map_ptr_state); 18657 ops = map_ptr->ops; 18658 if (insn->imm == BPF_FUNC_map_lookup_elem && 18659 ops->map_gen_lookup) { 18660 cnt = ops->map_gen_lookup(map_ptr, insn_buf); 18661 if (cnt == -EOPNOTSUPP) 18662 goto patch_map_ops_generic; 18663 if (cnt <= 0 || cnt >= ARRAY_SIZE(insn_buf)) { 18664 verbose(env, "bpf verifier is misconfigured\n"); 18665 return -EINVAL; 18666 } 18667 18668 new_prog = bpf_patch_insn_data(env, i + delta, 18669 insn_buf, cnt); 18670 if (!new_prog) 18671 return -ENOMEM; 18672 18673 delta += cnt - 1; 18674 env->prog = prog = new_prog; 18675 insn = new_prog->insnsi + i + delta; 18676 continue; 18677 } 18678 18679 BUILD_BUG_ON(!__same_type(ops->map_lookup_elem, 18680 (void *(*)(struct bpf_map *map, void *key))NULL)); 18681 BUILD_BUG_ON(!__same_type(ops->map_delete_elem, 18682 (long (*)(struct bpf_map *map, void *key))NULL)); 18683 BUILD_BUG_ON(!__same_type(ops->map_update_elem, 18684 (long (*)(struct bpf_map *map, void *key, void *value, 18685 u64 flags))NULL)); 18686 BUILD_BUG_ON(!__same_type(ops->map_push_elem, 18687 (long (*)(struct bpf_map *map, void *value, 18688 u64 flags))NULL)); 18689 BUILD_BUG_ON(!__same_type(ops->map_pop_elem, 18690 (long (*)(struct bpf_map *map, void *value))NULL)); 18691 BUILD_BUG_ON(!__same_type(ops->map_peek_elem, 18692 (long (*)(struct bpf_map *map, void *value))NULL)); 18693 BUILD_BUG_ON(!__same_type(ops->map_redirect, 18694 (long (*)(struct bpf_map *map, u64 index, u64 flags))NULL)); 18695 BUILD_BUG_ON(!__same_type(ops->map_for_each_callback, 18696 (long (*)(struct bpf_map *map, 18697 bpf_callback_t callback_fn, 18698 void *callback_ctx, 18699 u64 flags))NULL)); 18700 BUILD_BUG_ON(!__same_type(ops->map_lookup_percpu_elem, 18701 (void *(*)(struct bpf_map *map, void *key, u32 cpu))NULL)); 18702 18703 patch_map_ops_generic: 18704 switch (insn->imm) { 18705 case BPF_FUNC_map_lookup_elem: 18706 insn->imm = BPF_CALL_IMM(ops->map_lookup_elem); 18707 continue; 18708 case BPF_FUNC_map_update_elem: 18709 insn->imm = BPF_CALL_IMM(ops->map_update_elem); 18710 continue; 18711 case BPF_FUNC_map_delete_elem: 18712 insn->imm = BPF_CALL_IMM(ops->map_delete_elem); 18713 continue; 18714 case BPF_FUNC_map_push_elem: 18715 insn->imm = BPF_CALL_IMM(ops->map_push_elem); 18716 continue; 18717 case BPF_FUNC_map_pop_elem: 18718 insn->imm = BPF_CALL_IMM(ops->map_pop_elem); 18719 continue; 18720 case BPF_FUNC_map_peek_elem: 18721 insn->imm = BPF_CALL_IMM(ops->map_peek_elem); 18722 continue; 18723 case BPF_FUNC_redirect_map: 18724 insn->imm = BPF_CALL_IMM(ops->map_redirect); 18725 continue; 18726 case BPF_FUNC_for_each_map_elem: 18727 insn->imm = BPF_CALL_IMM(ops->map_for_each_callback); 18728 continue; 18729 case BPF_FUNC_map_lookup_percpu_elem: 18730 insn->imm = BPF_CALL_IMM(ops->map_lookup_percpu_elem); 18731 continue; 18732 } 18733 18734 goto patch_call_imm; 18735 } 18736 18737 /* Implement bpf_jiffies64 inline. */ 18738 if (prog->jit_requested && BITS_PER_LONG == 64 && 18739 insn->imm == BPF_FUNC_jiffies64) { 18740 struct bpf_insn ld_jiffies_addr[2] = { 18741 BPF_LD_IMM64(BPF_REG_0, 18742 (unsigned long)&jiffies), 18743 }; 18744 18745 insn_buf[0] = ld_jiffies_addr[0]; 18746 insn_buf[1] = ld_jiffies_addr[1]; 18747 insn_buf[2] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, 18748 BPF_REG_0, 0); 18749 cnt = 3; 18750 18751 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 18752 cnt); 18753 if (!new_prog) 18754 return -ENOMEM; 18755 18756 delta += cnt - 1; 18757 env->prog = prog = new_prog; 18758 insn = new_prog->insnsi + i + delta; 18759 continue; 18760 } 18761 18762 /* Implement bpf_get_func_arg inline. */ 18763 if (prog_type == BPF_PROG_TYPE_TRACING && 18764 insn->imm == BPF_FUNC_get_func_arg) { 18765 /* Load nr_args from ctx - 8 */ 18766 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8); 18767 insn_buf[1] = BPF_JMP32_REG(BPF_JGE, BPF_REG_2, BPF_REG_0, 6); 18768 insn_buf[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_2, 3); 18769 insn_buf[3] = BPF_ALU64_REG(BPF_ADD, BPF_REG_2, BPF_REG_1); 18770 insn_buf[4] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_2, 0); 18771 insn_buf[5] = BPF_STX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0); 18772 insn_buf[6] = BPF_MOV64_IMM(BPF_REG_0, 0); 18773 insn_buf[7] = BPF_JMP_A(1); 18774 insn_buf[8] = BPF_MOV64_IMM(BPF_REG_0, -EINVAL); 18775 cnt = 9; 18776 18777 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 18778 if (!new_prog) 18779 return -ENOMEM; 18780 18781 delta += cnt - 1; 18782 env->prog = prog = new_prog; 18783 insn = new_prog->insnsi + i + delta; 18784 continue; 18785 } 18786 18787 /* Implement bpf_get_func_ret inline. */ 18788 if (prog_type == BPF_PROG_TYPE_TRACING && 18789 insn->imm == BPF_FUNC_get_func_ret) { 18790 if (eatype == BPF_TRACE_FEXIT || 18791 eatype == BPF_MODIFY_RETURN) { 18792 /* Load nr_args from ctx - 8 */ 18793 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8); 18794 insn_buf[1] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_0, 3); 18795 insn_buf[2] = BPF_ALU64_REG(BPF_ADD, BPF_REG_0, BPF_REG_1); 18796 insn_buf[3] = BPF_LDX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0); 18797 insn_buf[4] = BPF_STX_MEM(BPF_DW, BPF_REG_2, BPF_REG_3, 0); 18798 insn_buf[5] = BPF_MOV64_IMM(BPF_REG_0, 0); 18799 cnt = 6; 18800 } else { 18801 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_0, -EOPNOTSUPP); 18802 cnt = 1; 18803 } 18804 18805 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 18806 if (!new_prog) 18807 return -ENOMEM; 18808 18809 delta += cnt - 1; 18810 env->prog = prog = new_prog; 18811 insn = new_prog->insnsi + i + delta; 18812 continue; 18813 } 18814 18815 /* Implement get_func_arg_cnt inline. */ 18816 if (prog_type == BPF_PROG_TYPE_TRACING && 18817 insn->imm == BPF_FUNC_get_func_arg_cnt) { 18818 /* Load nr_args from ctx - 8 */ 18819 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8); 18820 18821 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1); 18822 if (!new_prog) 18823 return -ENOMEM; 18824 18825 env->prog = prog = new_prog; 18826 insn = new_prog->insnsi + i + delta; 18827 continue; 18828 } 18829 18830 /* Implement bpf_get_func_ip inline. */ 18831 if (prog_type == BPF_PROG_TYPE_TRACING && 18832 insn->imm == BPF_FUNC_get_func_ip) { 18833 /* Load IP address from ctx - 16 */ 18834 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -16); 18835 18836 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1); 18837 if (!new_prog) 18838 return -ENOMEM; 18839 18840 env->prog = prog = new_prog; 18841 insn = new_prog->insnsi + i + delta; 18842 continue; 18843 } 18844 18845 patch_call_imm: 18846 fn = env->ops->get_func_proto(insn->imm, env->prog); 18847 /* all functions that have prototype and verifier allowed 18848 * programs to call them, must be real in-kernel functions 18849 */ 18850 if (!fn->func) { 18851 verbose(env, 18852 "kernel subsystem misconfigured func %s#%d\n", 18853 func_id_name(insn->imm), insn->imm); 18854 return -EFAULT; 18855 } 18856 insn->imm = fn->func - __bpf_call_base; 18857 } 18858 18859 /* Since poke tab is now finalized, publish aux to tracker. */ 18860 for (i = 0; i < prog->aux->size_poke_tab; i++) { 18861 map_ptr = prog->aux->poke_tab[i].tail_call.map; 18862 if (!map_ptr->ops->map_poke_track || 18863 !map_ptr->ops->map_poke_untrack || 18864 !map_ptr->ops->map_poke_run) { 18865 verbose(env, "bpf verifier is misconfigured\n"); 18866 return -EINVAL; 18867 } 18868 18869 ret = map_ptr->ops->map_poke_track(map_ptr, prog->aux); 18870 if (ret < 0) { 18871 verbose(env, "tracking tail call prog failed\n"); 18872 return ret; 18873 } 18874 } 18875 18876 sort_kfunc_descs_by_imm_off(env->prog); 18877 18878 return 0; 18879 } 18880 18881 static struct bpf_prog *inline_bpf_loop(struct bpf_verifier_env *env, 18882 int position, 18883 s32 stack_base, 18884 u32 callback_subprogno, 18885 u32 *cnt) 18886 { 18887 s32 r6_offset = stack_base + 0 * BPF_REG_SIZE; 18888 s32 r7_offset = stack_base + 1 * BPF_REG_SIZE; 18889 s32 r8_offset = stack_base + 2 * BPF_REG_SIZE; 18890 int reg_loop_max = BPF_REG_6; 18891 int reg_loop_cnt = BPF_REG_7; 18892 int reg_loop_ctx = BPF_REG_8; 18893 18894 struct bpf_prog *new_prog; 18895 u32 callback_start; 18896 u32 call_insn_offset; 18897 s32 callback_offset; 18898 18899 /* This represents an inlined version of bpf_iter.c:bpf_loop, 18900 * be careful to modify this code in sync. 18901 */ 18902 struct bpf_insn insn_buf[] = { 18903 /* Return error and jump to the end of the patch if 18904 * expected number of iterations is too big. 18905 */ 18906 BPF_JMP_IMM(BPF_JLE, BPF_REG_1, BPF_MAX_LOOPS, 2), 18907 BPF_MOV32_IMM(BPF_REG_0, -E2BIG), 18908 BPF_JMP_IMM(BPF_JA, 0, 0, 16), 18909 /* spill R6, R7, R8 to use these as loop vars */ 18910 BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_6, r6_offset), 18911 BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_7, r7_offset), 18912 BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_8, r8_offset), 18913 /* initialize loop vars */ 18914 BPF_MOV64_REG(reg_loop_max, BPF_REG_1), 18915 BPF_MOV32_IMM(reg_loop_cnt, 0), 18916 BPF_MOV64_REG(reg_loop_ctx, BPF_REG_3), 18917 /* loop header, 18918 * if reg_loop_cnt >= reg_loop_max skip the loop body 18919 */ 18920 BPF_JMP_REG(BPF_JGE, reg_loop_cnt, reg_loop_max, 5), 18921 /* callback call, 18922 * correct callback offset would be set after patching 18923 */ 18924 BPF_MOV64_REG(BPF_REG_1, reg_loop_cnt), 18925 BPF_MOV64_REG(BPF_REG_2, reg_loop_ctx), 18926 BPF_CALL_REL(0), 18927 /* increment loop counter */ 18928 BPF_ALU64_IMM(BPF_ADD, reg_loop_cnt, 1), 18929 /* jump to loop header if callback returned 0 */ 18930 BPF_JMP_IMM(BPF_JEQ, BPF_REG_0, 0, -6), 18931 /* return value of bpf_loop, 18932 * set R0 to the number of iterations 18933 */ 18934 BPF_MOV64_REG(BPF_REG_0, reg_loop_cnt), 18935 /* restore original values of R6, R7, R8 */ 18936 BPF_LDX_MEM(BPF_DW, BPF_REG_6, BPF_REG_10, r6_offset), 18937 BPF_LDX_MEM(BPF_DW, BPF_REG_7, BPF_REG_10, r7_offset), 18938 BPF_LDX_MEM(BPF_DW, BPF_REG_8, BPF_REG_10, r8_offset), 18939 }; 18940 18941 *cnt = ARRAY_SIZE(insn_buf); 18942 new_prog = bpf_patch_insn_data(env, position, insn_buf, *cnt); 18943 if (!new_prog) 18944 return new_prog; 18945 18946 /* callback start is known only after patching */ 18947 callback_start = env->subprog_info[callback_subprogno].start; 18948 /* Note: insn_buf[12] is an offset of BPF_CALL_REL instruction */ 18949 call_insn_offset = position + 12; 18950 callback_offset = callback_start - call_insn_offset - 1; 18951 new_prog->insnsi[call_insn_offset].imm = callback_offset; 18952 18953 return new_prog; 18954 } 18955 18956 static bool is_bpf_loop_call(struct bpf_insn *insn) 18957 { 18958 return insn->code == (BPF_JMP | BPF_CALL) && 18959 insn->src_reg == 0 && 18960 insn->imm == BPF_FUNC_loop; 18961 } 18962 18963 /* For all sub-programs in the program (including main) check 18964 * insn_aux_data to see if there are bpf_loop calls that require 18965 * inlining. If such calls are found the calls are replaced with a 18966 * sequence of instructions produced by `inline_bpf_loop` function and 18967 * subprog stack_depth is increased by the size of 3 registers. 18968 * This stack space is used to spill values of the R6, R7, R8. These 18969 * registers are used to store the loop bound, counter and context 18970 * variables. 18971 */ 18972 static int optimize_bpf_loop(struct bpf_verifier_env *env) 18973 { 18974 struct bpf_subprog_info *subprogs = env->subprog_info; 18975 int i, cur_subprog = 0, cnt, delta = 0; 18976 struct bpf_insn *insn = env->prog->insnsi; 18977 int insn_cnt = env->prog->len; 18978 u16 stack_depth = subprogs[cur_subprog].stack_depth; 18979 u16 stack_depth_roundup = round_up(stack_depth, 8) - stack_depth; 18980 u16 stack_depth_extra = 0; 18981 18982 for (i = 0; i < insn_cnt; i++, insn++) { 18983 struct bpf_loop_inline_state *inline_state = 18984 &env->insn_aux_data[i + delta].loop_inline_state; 18985 18986 if (is_bpf_loop_call(insn) && inline_state->fit_for_inline) { 18987 struct bpf_prog *new_prog; 18988 18989 stack_depth_extra = BPF_REG_SIZE * 3 + stack_depth_roundup; 18990 new_prog = inline_bpf_loop(env, 18991 i + delta, 18992 -(stack_depth + stack_depth_extra), 18993 inline_state->callback_subprogno, 18994 &cnt); 18995 if (!new_prog) 18996 return -ENOMEM; 18997 18998 delta += cnt - 1; 18999 env->prog = new_prog; 19000 insn = new_prog->insnsi + i + delta; 19001 } 19002 19003 if (subprogs[cur_subprog + 1].start == i + delta + 1) { 19004 subprogs[cur_subprog].stack_depth += stack_depth_extra; 19005 cur_subprog++; 19006 stack_depth = subprogs[cur_subprog].stack_depth; 19007 stack_depth_roundup = round_up(stack_depth, 8) - stack_depth; 19008 stack_depth_extra = 0; 19009 } 19010 } 19011 19012 env->prog->aux->stack_depth = env->subprog_info[0].stack_depth; 19013 19014 return 0; 19015 } 19016 19017 static void free_states(struct bpf_verifier_env *env) 19018 { 19019 struct bpf_verifier_state_list *sl, *sln; 19020 int i; 19021 19022 sl = env->free_list; 19023 while (sl) { 19024 sln = sl->next; 19025 free_verifier_state(&sl->state, false); 19026 kfree(sl); 19027 sl = sln; 19028 } 19029 env->free_list = NULL; 19030 19031 if (!env->explored_states) 19032 return; 19033 19034 for (i = 0; i < state_htab_size(env); i++) { 19035 sl = env->explored_states[i]; 19036 19037 while (sl) { 19038 sln = sl->next; 19039 free_verifier_state(&sl->state, false); 19040 kfree(sl); 19041 sl = sln; 19042 } 19043 env->explored_states[i] = NULL; 19044 } 19045 } 19046 19047 static int do_check_common(struct bpf_verifier_env *env, int subprog) 19048 { 19049 bool pop_log = !(env->log.level & BPF_LOG_LEVEL2); 19050 struct bpf_verifier_state *state; 19051 struct bpf_reg_state *regs; 19052 int ret, i; 19053 19054 env->prev_linfo = NULL; 19055 env->pass_cnt++; 19056 19057 state = kzalloc(sizeof(struct bpf_verifier_state), GFP_KERNEL); 19058 if (!state) 19059 return -ENOMEM; 19060 state->curframe = 0; 19061 state->speculative = false; 19062 state->branches = 1; 19063 state->frame[0] = kzalloc(sizeof(struct bpf_func_state), GFP_KERNEL); 19064 if (!state->frame[0]) { 19065 kfree(state); 19066 return -ENOMEM; 19067 } 19068 env->cur_state = state; 19069 init_func_state(env, state->frame[0], 19070 BPF_MAIN_FUNC /* callsite */, 19071 0 /* frameno */, 19072 subprog); 19073 state->first_insn_idx = env->subprog_info[subprog].start; 19074 state->last_insn_idx = -1; 19075 19076 regs = state->frame[state->curframe]->regs; 19077 if (subprog || env->prog->type == BPF_PROG_TYPE_EXT) { 19078 ret = btf_prepare_func_args(env, subprog, regs); 19079 if (ret) 19080 goto out; 19081 for (i = BPF_REG_1; i <= BPF_REG_5; i++) { 19082 if (regs[i].type == PTR_TO_CTX) 19083 mark_reg_known_zero(env, regs, i); 19084 else if (regs[i].type == SCALAR_VALUE) 19085 mark_reg_unknown(env, regs, i); 19086 else if (base_type(regs[i].type) == PTR_TO_MEM) { 19087 const u32 mem_size = regs[i].mem_size; 19088 19089 mark_reg_known_zero(env, regs, i); 19090 regs[i].mem_size = mem_size; 19091 regs[i].id = ++env->id_gen; 19092 } 19093 } 19094 } else { 19095 /* 1st arg to a function */ 19096 regs[BPF_REG_1].type = PTR_TO_CTX; 19097 mark_reg_known_zero(env, regs, BPF_REG_1); 19098 ret = btf_check_subprog_arg_match(env, subprog, regs); 19099 if (ret == -EFAULT) 19100 /* unlikely verifier bug. abort. 19101 * ret == 0 and ret < 0 are sadly acceptable for 19102 * main() function due to backward compatibility. 19103 * Like socket filter program may be written as: 19104 * int bpf_prog(struct pt_regs *ctx) 19105 * and never dereference that ctx in the program. 19106 * 'struct pt_regs' is a type mismatch for socket 19107 * filter that should be using 'struct __sk_buff'. 19108 */ 19109 goto out; 19110 } 19111 19112 ret = do_check(env); 19113 out: 19114 /* check for NULL is necessary, since cur_state can be freed inside 19115 * do_check() under memory pressure. 19116 */ 19117 if (env->cur_state) { 19118 free_verifier_state(env->cur_state, true); 19119 env->cur_state = NULL; 19120 } 19121 while (!pop_stack(env, NULL, NULL, false)); 19122 if (!ret && pop_log) 19123 bpf_vlog_reset(&env->log, 0); 19124 free_states(env); 19125 return ret; 19126 } 19127 19128 /* Verify all global functions in a BPF program one by one based on their BTF. 19129 * All global functions must pass verification. Otherwise the whole program is rejected. 19130 * Consider: 19131 * int bar(int); 19132 * int foo(int f) 19133 * { 19134 * return bar(f); 19135 * } 19136 * int bar(int b) 19137 * { 19138 * ... 19139 * } 19140 * foo() will be verified first for R1=any_scalar_value. During verification it 19141 * will be assumed that bar() already verified successfully and call to bar() 19142 * from foo() will be checked for type match only. Later bar() will be verified 19143 * independently to check that it's safe for R1=any_scalar_value. 19144 */ 19145 static int do_check_subprogs(struct bpf_verifier_env *env) 19146 { 19147 struct bpf_prog_aux *aux = env->prog->aux; 19148 int i, ret; 19149 19150 if (!aux->func_info) 19151 return 0; 19152 19153 for (i = 1; i < env->subprog_cnt; i++) { 19154 if (aux->func_info_aux[i].linkage != BTF_FUNC_GLOBAL) 19155 continue; 19156 env->insn_idx = env->subprog_info[i].start; 19157 WARN_ON_ONCE(env->insn_idx == 0); 19158 ret = do_check_common(env, i); 19159 if (ret) { 19160 return ret; 19161 } else if (env->log.level & BPF_LOG_LEVEL) { 19162 verbose(env, 19163 "Func#%d is safe for any args that match its prototype\n", 19164 i); 19165 } 19166 } 19167 return 0; 19168 } 19169 19170 static int do_check_main(struct bpf_verifier_env *env) 19171 { 19172 int ret; 19173 19174 env->insn_idx = 0; 19175 ret = do_check_common(env, 0); 19176 if (!ret) 19177 env->prog->aux->stack_depth = env->subprog_info[0].stack_depth; 19178 return ret; 19179 } 19180 19181 19182 static void print_verification_stats(struct bpf_verifier_env *env) 19183 { 19184 int i; 19185 19186 if (env->log.level & BPF_LOG_STATS) { 19187 verbose(env, "verification time %lld usec\n", 19188 div_u64(env->verification_time, 1000)); 19189 verbose(env, "stack depth "); 19190 for (i = 0; i < env->subprog_cnt; i++) { 19191 u32 depth = env->subprog_info[i].stack_depth; 19192 19193 verbose(env, "%d", depth); 19194 if (i + 1 < env->subprog_cnt) 19195 verbose(env, "+"); 19196 } 19197 verbose(env, "\n"); 19198 } 19199 verbose(env, "processed %d insns (limit %d) max_states_per_insn %d " 19200 "total_states %d peak_states %d mark_read %d\n", 19201 env->insn_processed, BPF_COMPLEXITY_LIMIT_INSNS, 19202 env->max_states_per_insn, env->total_states, 19203 env->peak_states, env->longest_mark_read_walk); 19204 } 19205 19206 static int check_struct_ops_btf_id(struct bpf_verifier_env *env) 19207 { 19208 const struct btf_type *t, *func_proto; 19209 const struct bpf_struct_ops *st_ops; 19210 const struct btf_member *member; 19211 struct bpf_prog *prog = env->prog; 19212 u32 btf_id, member_idx; 19213 const char *mname; 19214 19215 if (!prog->gpl_compatible) { 19216 verbose(env, "struct ops programs must have a GPL compatible license\n"); 19217 return -EINVAL; 19218 } 19219 19220 btf_id = prog->aux->attach_btf_id; 19221 st_ops = bpf_struct_ops_find(btf_id); 19222 if (!st_ops) { 19223 verbose(env, "attach_btf_id %u is not a supported struct\n", 19224 btf_id); 19225 return -ENOTSUPP; 19226 } 19227 19228 t = st_ops->type; 19229 member_idx = prog->expected_attach_type; 19230 if (member_idx >= btf_type_vlen(t)) { 19231 verbose(env, "attach to invalid member idx %u of struct %s\n", 19232 member_idx, st_ops->name); 19233 return -EINVAL; 19234 } 19235 19236 member = &btf_type_member(t)[member_idx]; 19237 mname = btf_name_by_offset(btf_vmlinux, member->name_off); 19238 func_proto = btf_type_resolve_func_ptr(btf_vmlinux, member->type, 19239 NULL); 19240 if (!func_proto) { 19241 verbose(env, "attach to invalid member %s(@idx %u) of struct %s\n", 19242 mname, member_idx, st_ops->name); 19243 return -EINVAL; 19244 } 19245 19246 if (st_ops->check_member) { 19247 int err = st_ops->check_member(t, member, prog); 19248 19249 if (err) { 19250 verbose(env, "attach to unsupported member %s of struct %s\n", 19251 mname, st_ops->name); 19252 return err; 19253 } 19254 } 19255 19256 prog->aux->attach_func_proto = func_proto; 19257 prog->aux->attach_func_name = mname; 19258 env->ops = st_ops->verifier_ops; 19259 19260 return 0; 19261 } 19262 #define SECURITY_PREFIX "security_" 19263 19264 static int check_attach_modify_return(unsigned long addr, const char *func_name) 19265 { 19266 if (within_error_injection_list(addr) || 19267 !strncmp(SECURITY_PREFIX, func_name, sizeof(SECURITY_PREFIX) - 1)) 19268 return 0; 19269 19270 return -EINVAL; 19271 } 19272 19273 /* list of non-sleepable functions that are otherwise on 19274 * ALLOW_ERROR_INJECTION list 19275 */ 19276 BTF_SET_START(btf_non_sleepable_error_inject) 19277 /* Three functions below can be called from sleepable and non-sleepable context. 19278 * Assume non-sleepable from bpf safety point of view. 19279 */ 19280 BTF_ID(func, __filemap_add_folio) 19281 BTF_ID(func, should_fail_alloc_page) 19282 BTF_ID(func, should_failslab) 19283 BTF_SET_END(btf_non_sleepable_error_inject) 19284 19285 static int check_non_sleepable_error_inject(u32 btf_id) 19286 { 19287 return btf_id_set_contains(&btf_non_sleepable_error_inject, btf_id); 19288 } 19289 19290 int bpf_check_attach_target(struct bpf_verifier_log *log, 19291 const struct bpf_prog *prog, 19292 const struct bpf_prog *tgt_prog, 19293 u32 btf_id, 19294 struct bpf_attach_target_info *tgt_info) 19295 { 19296 bool prog_extension = prog->type == BPF_PROG_TYPE_EXT; 19297 const char prefix[] = "btf_trace_"; 19298 int ret = 0, subprog = -1, i; 19299 const struct btf_type *t; 19300 bool conservative = true; 19301 const char *tname; 19302 struct btf *btf; 19303 long addr = 0; 19304 struct module *mod = NULL; 19305 19306 if (!btf_id) { 19307 bpf_log(log, "Tracing programs must provide btf_id\n"); 19308 return -EINVAL; 19309 } 19310 btf = tgt_prog ? tgt_prog->aux->btf : prog->aux->attach_btf; 19311 if (!btf) { 19312 bpf_log(log, 19313 "FENTRY/FEXIT program can only be attached to another program annotated with BTF\n"); 19314 return -EINVAL; 19315 } 19316 t = btf_type_by_id(btf, btf_id); 19317 if (!t) { 19318 bpf_log(log, "attach_btf_id %u is invalid\n", btf_id); 19319 return -EINVAL; 19320 } 19321 tname = btf_name_by_offset(btf, t->name_off); 19322 if (!tname) { 19323 bpf_log(log, "attach_btf_id %u doesn't have a name\n", btf_id); 19324 return -EINVAL; 19325 } 19326 if (tgt_prog) { 19327 struct bpf_prog_aux *aux = tgt_prog->aux; 19328 19329 if (bpf_prog_is_dev_bound(prog->aux) && 19330 !bpf_prog_dev_bound_match(prog, tgt_prog)) { 19331 bpf_log(log, "Target program bound device mismatch"); 19332 return -EINVAL; 19333 } 19334 19335 for (i = 0; i < aux->func_info_cnt; i++) 19336 if (aux->func_info[i].type_id == btf_id) { 19337 subprog = i; 19338 break; 19339 } 19340 if (subprog == -1) { 19341 bpf_log(log, "Subprog %s doesn't exist\n", tname); 19342 return -EINVAL; 19343 } 19344 conservative = aux->func_info_aux[subprog].unreliable; 19345 if (prog_extension) { 19346 if (conservative) { 19347 bpf_log(log, 19348 "Cannot replace static functions\n"); 19349 return -EINVAL; 19350 } 19351 if (!prog->jit_requested) { 19352 bpf_log(log, 19353 "Extension programs should be JITed\n"); 19354 return -EINVAL; 19355 } 19356 } 19357 if (!tgt_prog->jited) { 19358 bpf_log(log, "Can attach to only JITed progs\n"); 19359 return -EINVAL; 19360 } 19361 if (tgt_prog->type == prog->type) { 19362 /* Cannot fentry/fexit another fentry/fexit program. 19363 * Cannot attach program extension to another extension. 19364 * It's ok to attach fentry/fexit to extension program. 19365 */ 19366 bpf_log(log, "Cannot recursively attach\n"); 19367 return -EINVAL; 19368 } 19369 if (tgt_prog->type == BPF_PROG_TYPE_TRACING && 19370 prog_extension && 19371 (tgt_prog->expected_attach_type == BPF_TRACE_FENTRY || 19372 tgt_prog->expected_attach_type == BPF_TRACE_FEXIT)) { 19373 /* Program extensions can extend all program types 19374 * except fentry/fexit. The reason is the following. 19375 * The fentry/fexit programs are used for performance 19376 * analysis, stats and can be attached to any program 19377 * type except themselves. When extension program is 19378 * replacing XDP function it is necessary to allow 19379 * performance analysis of all functions. Both original 19380 * XDP program and its program extension. Hence 19381 * attaching fentry/fexit to BPF_PROG_TYPE_EXT is 19382 * allowed. If extending of fentry/fexit was allowed it 19383 * would be possible to create long call chain 19384 * fentry->extension->fentry->extension beyond 19385 * reasonable stack size. Hence extending fentry is not 19386 * allowed. 19387 */ 19388 bpf_log(log, "Cannot extend fentry/fexit\n"); 19389 return -EINVAL; 19390 } 19391 } else { 19392 if (prog_extension) { 19393 bpf_log(log, "Cannot replace kernel functions\n"); 19394 return -EINVAL; 19395 } 19396 } 19397 19398 switch (prog->expected_attach_type) { 19399 case BPF_TRACE_RAW_TP: 19400 if (tgt_prog) { 19401 bpf_log(log, 19402 "Only FENTRY/FEXIT progs are attachable to another BPF prog\n"); 19403 return -EINVAL; 19404 } 19405 if (!btf_type_is_typedef(t)) { 19406 bpf_log(log, "attach_btf_id %u is not a typedef\n", 19407 btf_id); 19408 return -EINVAL; 19409 } 19410 if (strncmp(prefix, tname, sizeof(prefix) - 1)) { 19411 bpf_log(log, "attach_btf_id %u points to wrong type name %s\n", 19412 btf_id, tname); 19413 return -EINVAL; 19414 } 19415 tname += sizeof(prefix) - 1; 19416 t = btf_type_by_id(btf, t->type); 19417 if (!btf_type_is_ptr(t)) 19418 /* should never happen in valid vmlinux build */ 19419 return -EINVAL; 19420 t = btf_type_by_id(btf, t->type); 19421 if (!btf_type_is_func_proto(t)) 19422 /* should never happen in valid vmlinux build */ 19423 return -EINVAL; 19424 19425 break; 19426 case BPF_TRACE_ITER: 19427 if (!btf_type_is_func(t)) { 19428 bpf_log(log, "attach_btf_id %u is not a function\n", 19429 btf_id); 19430 return -EINVAL; 19431 } 19432 t = btf_type_by_id(btf, t->type); 19433 if (!btf_type_is_func_proto(t)) 19434 return -EINVAL; 19435 ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel); 19436 if (ret) 19437 return ret; 19438 break; 19439 default: 19440 if (!prog_extension) 19441 return -EINVAL; 19442 fallthrough; 19443 case BPF_MODIFY_RETURN: 19444 case BPF_LSM_MAC: 19445 case BPF_LSM_CGROUP: 19446 case BPF_TRACE_FENTRY: 19447 case BPF_TRACE_FEXIT: 19448 if (!btf_type_is_func(t)) { 19449 bpf_log(log, "attach_btf_id %u is not a function\n", 19450 btf_id); 19451 return -EINVAL; 19452 } 19453 if (prog_extension && 19454 btf_check_type_match(log, prog, btf, t)) 19455 return -EINVAL; 19456 t = btf_type_by_id(btf, t->type); 19457 if (!btf_type_is_func_proto(t)) 19458 return -EINVAL; 19459 19460 if ((prog->aux->saved_dst_prog_type || prog->aux->saved_dst_attach_type) && 19461 (!tgt_prog || prog->aux->saved_dst_prog_type != tgt_prog->type || 19462 prog->aux->saved_dst_attach_type != tgt_prog->expected_attach_type)) 19463 return -EINVAL; 19464 19465 if (tgt_prog && conservative) 19466 t = NULL; 19467 19468 ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel); 19469 if (ret < 0) 19470 return ret; 19471 19472 if (tgt_prog) { 19473 if (subprog == 0) 19474 addr = (long) tgt_prog->bpf_func; 19475 else 19476 addr = (long) tgt_prog->aux->func[subprog]->bpf_func; 19477 } else { 19478 if (btf_is_module(btf)) { 19479 mod = btf_try_get_module(btf); 19480 if (mod) 19481 addr = find_kallsyms_symbol_value(mod, tname); 19482 else 19483 addr = 0; 19484 } else { 19485 addr = kallsyms_lookup_name(tname); 19486 } 19487 if (!addr) { 19488 module_put(mod); 19489 bpf_log(log, 19490 "The address of function %s cannot be found\n", 19491 tname); 19492 return -ENOENT; 19493 } 19494 } 19495 19496 if (prog->aux->sleepable) { 19497 ret = -EINVAL; 19498 switch (prog->type) { 19499 case BPF_PROG_TYPE_TRACING: 19500 19501 /* fentry/fexit/fmod_ret progs can be sleepable if they are 19502 * attached to ALLOW_ERROR_INJECTION and are not in denylist. 19503 */ 19504 if (!check_non_sleepable_error_inject(btf_id) && 19505 within_error_injection_list(addr)) 19506 ret = 0; 19507 /* fentry/fexit/fmod_ret progs can also be sleepable if they are 19508 * in the fmodret id set with the KF_SLEEPABLE flag. 19509 */ 19510 else { 19511 u32 *flags = btf_kfunc_is_modify_return(btf, btf_id, 19512 prog); 19513 19514 if (flags && (*flags & KF_SLEEPABLE)) 19515 ret = 0; 19516 } 19517 break; 19518 case BPF_PROG_TYPE_LSM: 19519 /* LSM progs check that they are attached to bpf_lsm_*() funcs. 19520 * Only some of them are sleepable. 19521 */ 19522 if (bpf_lsm_is_sleepable_hook(btf_id)) 19523 ret = 0; 19524 break; 19525 default: 19526 break; 19527 } 19528 if (ret) { 19529 module_put(mod); 19530 bpf_log(log, "%s is not sleepable\n", tname); 19531 return ret; 19532 } 19533 } else if (prog->expected_attach_type == BPF_MODIFY_RETURN) { 19534 if (tgt_prog) { 19535 module_put(mod); 19536 bpf_log(log, "can't modify return codes of BPF programs\n"); 19537 return -EINVAL; 19538 } 19539 ret = -EINVAL; 19540 if (btf_kfunc_is_modify_return(btf, btf_id, prog) || 19541 !check_attach_modify_return(addr, tname)) 19542 ret = 0; 19543 if (ret) { 19544 module_put(mod); 19545 bpf_log(log, "%s() is not modifiable\n", tname); 19546 return ret; 19547 } 19548 } 19549 19550 break; 19551 } 19552 tgt_info->tgt_addr = addr; 19553 tgt_info->tgt_name = tname; 19554 tgt_info->tgt_type = t; 19555 tgt_info->tgt_mod = mod; 19556 return 0; 19557 } 19558 19559 BTF_SET_START(btf_id_deny) 19560 BTF_ID_UNUSED 19561 #ifdef CONFIG_SMP 19562 BTF_ID(func, migrate_disable) 19563 BTF_ID(func, migrate_enable) 19564 #endif 19565 #if !defined CONFIG_PREEMPT_RCU && !defined CONFIG_TINY_RCU 19566 BTF_ID(func, rcu_read_unlock_strict) 19567 #endif 19568 #if defined(CONFIG_DEBUG_PREEMPT) || defined(CONFIG_TRACE_PREEMPT_TOGGLE) 19569 BTF_ID(func, preempt_count_add) 19570 BTF_ID(func, preempt_count_sub) 19571 #endif 19572 #ifdef CONFIG_PREEMPT_RCU 19573 BTF_ID(func, __rcu_read_lock) 19574 BTF_ID(func, __rcu_read_unlock) 19575 #endif 19576 BTF_SET_END(btf_id_deny) 19577 19578 static bool can_be_sleepable(struct bpf_prog *prog) 19579 { 19580 if (prog->type == BPF_PROG_TYPE_TRACING) { 19581 switch (prog->expected_attach_type) { 19582 case BPF_TRACE_FENTRY: 19583 case BPF_TRACE_FEXIT: 19584 case BPF_MODIFY_RETURN: 19585 case BPF_TRACE_ITER: 19586 return true; 19587 default: 19588 return false; 19589 } 19590 } 19591 return prog->type == BPF_PROG_TYPE_LSM || 19592 prog->type == BPF_PROG_TYPE_KPROBE /* only for uprobes */ || 19593 prog->type == BPF_PROG_TYPE_STRUCT_OPS; 19594 } 19595 19596 static int check_attach_btf_id(struct bpf_verifier_env *env) 19597 { 19598 struct bpf_prog *prog = env->prog; 19599 struct bpf_prog *tgt_prog = prog->aux->dst_prog; 19600 struct bpf_attach_target_info tgt_info = {}; 19601 u32 btf_id = prog->aux->attach_btf_id; 19602 struct bpf_trampoline *tr; 19603 int ret; 19604 u64 key; 19605 19606 if (prog->type == BPF_PROG_TYPE_SYSCALL) { 19607 if (prog->aux->sleepable) 19608 /* attach_btf_id checked to be zero already */ 19609 return 0; 19610 verbose(env, "Syscall programs can only be sleepable\n"); 19611 return -EINVAL; 19612 } 19613 19614 if (prog->aux->sleepable && !can_be_sleepable(prog)) { 19615 verbose(env, "Only fentry/fexit/fmod_ret, lsm, iter, uprobe, and struct_ops programs can be sleepable\n"); 19616 return -EINVAL; 19617 } 19618 19619 if (prog->type == BPF_PROG_TYPE_STRUCT_OPS) 19620 return check_struct_ops_btf_id(env); 19621 19622 if (prog->type != BPF_PROG_TYPE_TRACING && 19623 prog->type != BPF_PROG_TYPE_LSM && 19624 prog->type != BPF_PROG_TYPE_EXT) 19625 return 0; 19626 19627 ret = bpf_check_attach_target(&env->log, prog, tgt_prog, btf_id, &tgt_info); 19628 if (ret) 19629 return ret; 19630 19631 if (tgt_prog && prog->type == BPF_PROG_TYPE_EXT) { 19632 /* to make freplace equivalent to their targets, they need to 19633 * inherit env->ops and expected_attach_type for the rest of the 19634 * verification 19635 */ 19636 env->ops = bpf_verifier_ops[tgt_prog->type]; 19637 prog->expected_attach_type = tgt_prog->expected_attach_type; 19638 } 19639 19640 /* store info about the attachment target that will be used later */ 19641 prog->aux->attach_func_proto = tgt_info.tgt_type; 19642 prog->aux->attach_func_name = tgt_info.tgt_name; 19643 prog->aux->mod = tgt_info.tgt_mod; 19644 19645 if (tgt_prog) { 19646 prog->aux->saved_dst_prog_type = tgt_prog->type; 19647 prog->aux->saved_dst_attach_type = tgt_prog->expected_attach_type; 19648 } 19649 19650 if (prog->expected_attach_type == BPF_TRACE_RAW_TP) { 19651 prog->aux->attach_btf_trace = true; 19652 return 0; 19653 } else if (prog->expected_attach_type == BPF_TRACE_ITER) { 19654 if (!bpf_iter_prog_supported(prog)) 19655 return -EINVAL; 19656 return 0; 19657 } 19658 19659 if (prog->type == BPF_PROG_TYPE_LSM) { 19660 ret = bpf_lsm_verify_prog(&env->log, prog); 19661 if (ret < 0) 19662 return ret; 19663 } else if (prog->type == BPF_PROG_TYPE_TRACING && 19664 btf_id_set_contains(&btf_id_deny, btf_id)) { 19665 return -EINVAL; 19666 } 19667 19668 key = bpf_trampoline_compute_key(tgt_prog, prog->aux->attach_btf, btf_id); 19669 tr = bpf_trampoline_get(key, &tgt_info); 19670 if (!tr) 19671 return -ENOMEM; 19672 19673 if (tgt_prog && tgt_prog->aux->tail_call_reachable) 19674 tr->flags = BPF_TRAMP_F_TAIL_CALL_CTX; 19675 19676 prog->aux->dst_trampoline = tr; 19677 return 0; 19678 } 19679 19680 struct btf *bpf_get_btf_vmlinux(void) 19681 { 19682 if (!btf_vmlinux && IS_ENABLED(CONFIG_DEBUG_INFO_BTF)) { 19683 mutex_lock(&bpf_verifier_lock); 19684 if (!btf_vmlinux) 19685 btf_vmlinux = btf_parse_vmlinux(); 19686 mutex_unlock(&bpf_verifier_lock); 19687 } 19688 return btf_vmlinux; 19689 } 19690 19691 int bpf_check(struct bpf_prog **prog, union bpf_attr *attr, bpfptr_t uattr, __u32 uattr_size) 19692 { 19693 u64 start_time = ktime_get_ns(); 19694 struct bpf_verifier_env *env; 19695 int i, len, ret = -EINVAL, err; 19696 u32 log_true_size; 19697 bool is_priv; 19698 19699 /* no program is valid */ 19700 if (ARRAY_SIZE(bpf_verifier_ops) == 0) 19701 return -EINVAL; 19702 19703 /* 'struct bpf_verifier_env' can be global, but since it's not small, 19704 * allocate/free it every time bpf_check() is called 19705 */ 19706 env = kzalloc(sizeof(struct bpf_verifier_env), GFP_KERNEL); 19707 if (!env) 19708 return -ENOMEM; 19709 19710 env->bt.env = env; 19711 19712 len = (*prog)->len; 19713 env->insn_aux_data = 19714 vzalloc(array_size(sizeof(struct bpf_insn_aux_data), len)); 19715 ret = -ENOMEM; 19716 if (!env->insn_aux_data) 19717 goto err_free_env; 19718 for (i = 0; i < len; i++) 19719 env->insn_aux_data[i].orig_idx = i; 19720 env->prog = *prog; 19721 env->ops = bpf_verifier_ops[env->prog->type]; 19722 env->fd_array = make_bpfptr(attr->fd_array, uattr.is_kernel); 19723 is_priv = bpf_capable(); 19724 19725 bpf_get_btf_vmlinux(); 19726 19727 /* grab the mutex to protect few globals used by verifier */ 19728 if (!is_priv) 19729 mutex_lock(&bpf_verifier_lock); 19730 19731 /* user could have requested verbose verifier output 19732 * and supplied buffer to store the verification trace 19733 */ 19734 ret = bpf_vlog_init(&env->log, attr->log_level, 19735 (char __user *) (unsigned long) attr->log_buf, 19736 attr->log_size); 19737 if (ret) 19738 goto err_unlock; 19739 19740 mark_verifier_state_clean(env); 19741 19742 if (IS_ERR(btf_vmlinux)) { 19743 /* Either gcc or pahole or kernel are broken. */ 19744 verbose(env, "in-kernel BTF is malformed\n"); 19745 ret = PTR_ERR(btf_vmlinux); 19746 goto skip_full_check; 19747 } 19748 19749 env->strict_alignment = !!(attr->prog_flags & BPF_F_STRICT_ALIGNMENT); 19750 if (!IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS)) 19751 env->strict_alignment = true; 19752 if (attr->prog_flags & BPF_F_ANY_ALIGNMENT) 19753 env->strict_alignment = false; 19754 19755 env->allow_ptr_leaks = bpf_allow_ptr_leaks(); 19756 env->allow_uninit_stack = bpf_allow_uninit_stack(); 19757 env->bypass_spec_v1 = bpf_bypass_spec_v1(); 19758 env->bypass_spec_v4 = bpf_bypass_spec_v4(); 19759 env->bpf_capable = bpf_capable(); 19760 19761 if (is_priv) 19762 env->test_state_freq = attr->prog_flags & BPF_F_TEST_STATE_FREQ; 19763 19764 env->explored_states = kvcalloc(state_htab_size(env), 19765 sizeof(struct bpf_verifier_state_list *), 19766 GFP_USER); 19767 ret = -ENOMEM; 19768 if (!env->explored_states) 19769 goto skip_full_check; 19770 19771 ret = add_subprog_and_kfunc(env); 19772 if (ret < 0) 19773 goto skip_full_check; 19774 19775 ret = check_subprogs(env); 19776 if (ret < 0) 19777 goto skip_full_check; 19778 19779 ret = check_btf_info(env, attr, uattr); 19780 if (ret < 0) 19781 goto skip_full_check; 19782 19783 ret = check_attach_btf_id(env); 19784 if (ret) 19785 goto skip_full_check; 19786 19787 ret = resolve_pseudo_ldimm64(env); 19788 if (ret < 0) 19789 goto skip_full_check; 19790 19791 if (bpf_prog_is_offloaded(env->prog->aux)) { 19792 ret = bpf_prog_offload_verifier_prep(env->prog); 19793 if (ret) 19794 goto skip_full_check; 19795 } 19796 19797 ret = check_cfg(env); 19798 if (ret < 0) 19799 goto skip_full_check; 19800 19801 ret = do_check_subprogs(env); 19802 ret = ret ?: do_check_main(env); 19803 19804 if (ret == 0 && bpf_prog_is_offloaded(env->prog->aux)) 19805 ret = bpf_prog_offload_finalize(env); 19806 19807 skip_full_check: 19808 kvfree(env->explored_states); 19809 19810 if (ret == 0) 19811 ret = check_max_stack_depth(env); 19812 19813 /* instruction rewrites happen after this point */ 19814 if (ret == 0) 19815 ret = optimize_bpf_loop(env); 19816 19817 if (is_priv) { 19818 if (ret == 0) 19819 opt_hard_wire_dead_code_branches(env); 19820 if (ret == 0) 19821 ret = opt_remove_dead_code(env); 19822 if (ret == 0) 19823 ret = opt_remove_nops(env); 19824 } else { 19825 if (ret == 0) 19826 sanitize_dead_code(env); 19827 } 19828 19829 if (ret == 0) 19830 /* program is valid, convert *(u32*)(ctx + off) accesses */ 19831 ret = convert_ctx_accesses(env); 19832 19833 if (ret == 0) 19834 ret = do_misc_fixups(env); 19835 19836 /* do 32-bit optimization after insn patching has done so those patched 19837 * insns could be handled correctly. 19838 */ 19839 if (ret == 0 && !bpf_prog_is_offloaded(env->prog->aux)) { 19840 ret = opt_subreg_zext_lo32_rnd_hi32(env, attr); 19841 env->prog->aux->verifier_zext = bpf_jit_needs_zext() ? !ret 19842 : false; 19843 } 19844 19845 if (ret == 0) 19846 ret = fixup_call_args(env); 19847 19848 env->verification_time = ktime_get_ns() - start_time; 19849 print_verification_stats(env); 19850 env->prog->aux->verified_insns = env->insn_processed; 19851 19852 /* preserve original error even if log finalization is successful */ 19853 err = bpf_vlog_finalize(&env->log, &log_true_size); 19854 if (err) 19855 ret = err; 19856 19857 if (uattr_size >= offsetofend(union bpf_attr, log_true_size) && 19858 copy_to_bpfptr_offset(uattr, offsetof(union bpf_attr, log_true_size), 19859 &log_true_size, sizeof(log_true_size))) { 19860 ret = -EFAULT; 19861 goto err_release_maps; 19862 } 19863 19864 if (ret) 19865 goto err_release_maps; 19866 19867 if (env->used_map_cnt) { 19868 /* if program passed verifier, update used_maps in bpf_prog_info */ 19869 env->prog->aux->used_maps = kmalloc_array(env->used_map_cnt, 19870 sizeof(env->used_maps[0]), 19871 GFP_KERNEL); 19872 19873 if (!env->prog->aux->used_maps) { 19874 ret = -ENOMEM; 19875 goto err_release_maps; 19876 } 19877 19878 memcpy(env->prog->aux->used_maps, env->used_maps, 19879 sizeof(env->used_maps[0]) * env->used_map_cnt); 19880 env->prog->aux->used_map_cnt = env->used_map_cnt; 19881 } 19882 if (env->used_btf_cnt) { 19883 /* if program passed verifier, update used_btfs in bpf_prog_aux */ 19884 env->prog->aux->used_btfs = kmalloc_array(env->used_btf_cnt, 19885 sizeof(env->used_btfs[0]), 19886 GFP_KERNEL); 19887 if (!env->prog->aux->used_btfs) { 19888 ret = -ENOMEM; 19889 goto err_release_maps; 19890 } 19891 19892 memcpy(env->prog->aux->used_btfs, env->used_btfs, 19893 sizeof(env->used_btfs[0]) * env->used_btf_cnt); 19894 env->prog->aux->used_btf_cnt = env->used_btf_cnt; 19895 } 19896 if (env->used_map_cnt || env->used_btf_cnt) { 19897 /* program is valid. Convert pseudo bpf_ld_imm64 into generic 19898 * bpf_ld_imm64 instructions 19899 */ 19900 convert_pseudo_ld_imm64(env); 19901 } 19902 19903 adjust_btf_func(env); 19904 19905 err_release_maps: 19906 if (!env->prog->aux->used_maps) 19907 /* if we didn't copy map pointers into bpf_prog_info, release 19908 * them now. Otherwise free_used_maps() will release them. 19909 */ 19910 release_maps(env); 19911 if (!env->prog->aux->used_btfs) 19912 release_btfs(env); 19913 19914 /* extension progs temporarily inherit the attach_type of their targets 19915 for verification purposes, so set it back to zero before returning 19916 */ 19917 if (env->prog->type == BPF_PROG_TYPE_EXT) 19918 env->prog->expected_attach_type = 0; 19919 19920 *prog = env->prog; 19921 err_unlock: 19922 if (!is_priv) 19923 mutex_unlock(&bpf_verifier_lock); 19924 vfree(env->insn_aux_data); 19925 err_free_env: 19926 kfree(env); 19927 return ret; 19928 } 19929