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/bpf_percpu_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 static bool is_bpf_throw_kfunc(struct bpf_insn *insn); 547 548 static bool is_callback_calling_function(enum bpf_func_id func_id) 549 { 550 return func_id == BPF_FUNC_for_each_map_elem || 551 func_id == BPF_FUNC_timer_set_callback || 552 func_id == BPF_FUNC_find_vma || 553 func_id == BPF_FUNC_loop || 554 func_id == BPF_FUNC_user_ringbuf_drain; 555 } 556 557 static bool is_async_callback_calling_function(enum bpf_func_id func_id) 558 { 559 return func_id == BPF_FUNC_timer_set_callback; 560 } 561 562 static bool is_storage_get_function(enum bpf_func_id func_id) 563 { 564 return func_id == BPF_FUNC_sk_storage_get || 565 func_id == BPF_FUNC_inode_storage_get || 566 func_id == BPF_FUNC_task_storage_get || 567 func_id == BPF_FUNC_cgrp_storage_get; 568 } 569 570 static bool helper_multiple_ref_obj_use(enum bpf_func_id func_id, 571 const struct bpf_map *map) 572 { 573 int ref_obj_uses = 0; 574 575 if (is_ptr_cast_function(func_id)) 576 ref_obj_uses++; 577 if (is_acquire_function(func_id, map)) 578 ref_obj_uses++; 579 if (is_dynptr_ref_function(func_id)) 580 ref_obj_uses++; 581 582 return ref_obj_uses > 1; 583 } 584 585 static bool is_cmpxchg_insn(const struct bpf_insn *insn) 586 { 587 return BPF_CLASS(insn->code) == BPF_STX && 588 BPF_MODE(insn->code) == BPF_ATOMIC && 589 insn->imm == BPF_CMPXCHG; 590 } 591 592 /* string representation of 'enum bpf_reg_type' 593 * 594 * Note that reg_type_str() can not appear more than once in a single verbose() 595 * statement. 596 */ 597 static const char *reg_type_str(struct bpf_verifier_env *env, 598 enum bpf_reg_type type) 599 { 600 char postfix[16] = {0}, prefix[64] = {0}; 601 static const char * const str[] = { 602 [NOT_INIT] = "?", 603 [SCALAR_VALUE] = "scalar", 604 [PTR_TO_CTX] = "ctx", 605 [CONST_PTR_TO_MAP] = "map_ptr", 606 [PTR_TO_MAP_VALUE] = "map_value", 607 [PTR_TO_STACK] = "fp", 608 [PTR_TO_PACKET] = "pkt", 609 [PTR_TO_PACKET_META] = "pkt_meta", 610 [PTR_TO_PACKET_END] = "pkt_end", 611 [PTR_TO_FLOW_KEYS] = "flow_keys", 612 [PTR_TO_SOCKET] = "sock", 613 [PTR_TO_SOCK_COMMON] = "sock_common", 614 [PTR_TO_TCP_SOCK] = "tcp_sock", 615 [PTR_TO_TP_BUFFER] = "tp_buffer", 616 [PTR_TO_XDP_SOCK] = "xdp_sock", 617 [PTR_TO_BTF_ID] = "ptr_", 618 [PTR_TO_MEM] = "mem", 619 [PTR_TO_BUF] = "buf", 620 [PTR_TO_FUNC] = "func", 621 [PTR_TO_MAP_KEY] = "map_key", 622 [CONST_PTR_TO_DYNPTR] = "dynptr_ptr", 623 }; 624 625 if (type & PTR_MAYBE_NULL) { 626 if (base_type(type) == PTR_TO_BTF_ID) 627 strncpy(postfix, "or_null_", 16); 628 else 629 strncpy(postfix, "_or_null", 16); 630 } 631 632 snprintf(prefix, sizeof(prefix), "%s%s%s%s%s%s%s", 633 type & MEM_RDONLY ? "rdonly_" : "", 634 type & MEM_RINGBUF ? "ringbuf_" : "", 635 type & MEM_USER ? "user_" : "", 636 type & MEM_PERCPU ? "percpu_" : "", 637 type & MEM_RCU ? "rcu_" : "", 638 type & PTR_UNTRUSTED ? "untrusted_" : "", 639 type & PTR_TRUSTED ? "trusted_" : "" 640 ); 641 642 snprintf(env->tmp_str_buf, TMP_STR_BUF_LEN, "%s%s%s", 643 prefix, str[base_type(type)], postfix); 644 return env->tmp_str_buf; 645 } 646 647 static char slot_type_char[] = { 648 [STACK_INVALID] = '?', 649 [STACK_SPILL] = 'r', 650 [STACK_MISC] = 'm', 651 [STACK_ZERO] = '0', 652 [STACK_DYNPTR] = 'd', 653 [STACK_ITER] = 'i', 654 }; 655 656 static void print_liveness(struct bpf_verifier_env *env, 657 enum bpf_reg_liveness live) 658 { 659 if (live & (REG_LIVE_READ | REG_LIVE_WRITTEN | REG_LIVE_DONE)) 660 verbose(env, "_"); 661 if (live & REG_LIVE_READ) 662 verbose(env, "r"); 663 if (live & REG_LIVE_WRITTEN) 664 verbose(env, "w"); 665 if (live & REG_LIVE_DONE) 666 verbose(env, "D"); 667 } 668 669 static int __get_spi(s32 off) 670 { 671 return (-off - 1) / BPF_REG_SIZE; 672 } 673 674 static struct bpf_func_state *func(struct bpf_verifier_env *env, 675 const struct bpf_reg_state *reg) 676 { 677 struct bpf_verifier_state *cur = env->cur_state; 678 679 return cur->frame[reg->frameno]; 680 } 681 682 static bool is_spi_bounds_valid(struct bpf_func_state *state, int spi, int nr_slots) 683 { 684 int allocated_slots = state->allocated_stack / BPF_REG_SIZE; 685 686 /* We need to check that slots between [spi - nr_slots + 1, spi] are 687 * within [0, allocated_stack). 688 * 689 * Please note that the spi grows downwards. For example, a dynptr 690 * takes the size of two stack slots; the first slot will be at 691 * spi and the second slot will be at spi - 1. 692 */ 693 return spi - nr_slots + 1 >= 0 && spi < allocated_slots; 694 } 695 696 static int stack_slot_obj_get_spi(struct bpf_verifier_env *env, struct bpf_reg_state *reg, 697 const char *obj_kind, int nr_slots) 698 { 699 int off, spi; 700 701 if (!tnum_is_const(reg->var_off)) { 702 verbose(env, "%s has to be at a constant offset\n", obj_kind); 703 return -EINVAL; 704 } 705 706 off = reg->off + reg->var_off.value; 707 if (off % BPF_REG_SIZE) { 708 verbose(env, "cannot pass in %s at an offset=%d\n", obj_kind, off); 709 return -EINVAL; 710 } 711 712 spi = __get_spi(off); 713 if (spi + 1 < nr_slots) { 714 verbose(env, "cannot pass in %s at an offset=%d\n", obj_kind, off); 715 return -EINVAL; 716 } 717 718 if (!is_spi_bounds_valid(func(env, reg), spi, nr_slots)) 719 return -ERANGE; 720 return spi; 721 } 722 723 static int dynptr_get_spi(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 724 { 725 return stack_slot_obj_get_spi(env, reg, "dynptr", BPF_DYNPTR_NR_SLOTS); 726 } 727 728 static int iter_get_spi(struct bpf_verifier_env *env, struct bpf_reg_state *reg, int nr_slots) 729 { 730 return stack_slot_obj_get_spi(env, reg, "iter", nr_slots); 731 } 732 733 static const char *btf_type_name(const struct btf *btf, u32 id) 734 { 735 return btf_name_by_offset(btf, btf_type_by_id(btf, id)->name_off); 736 } 737 738 static const char *dynptr_type_str(enum bpf_dynptr_type type) 739 { 740 switch (type) { 741 case BPF_DYNPTR_TYPE_LOCAL: 742 return "local"; 743 case BPF_DYNPTR_TYPE_RINGBUF: 744 return "ringbuf"; 745 case BPF_DYNPTR_TYPE_SKB: 746 return "skb"; 747 case BPF_DYNPTR_TYPE_XDP: 748 return "xdp"; 749 case BPF_DYNPTR_TYPE_INVALID: 750 return "<invalid>"; 751 default: 752 WARN_ONCE(1, "unknown dynptr type %d\n", type); 753 return "<unknown>"; 754 } 755 } 756 757 static const char *iter_type_str(const struct btf *btf, u32 btf_id) 758 { 759 if (!btf || btf_id == 0) 760 return "<invalid>"; 761 762 /* we already validated that type is valid and has conforming name */ 763 return btf_type_name(btf, btf_id) + sizeof(ITER_PREFIX) - 1; 764 } 765 766 static const char *iter_state_str(enum bpf_iter_state state) 767 { 768 switch (state) { 769 case BPF_ITER_STATE_ACTIVE: 770 return "active"; 771 case BPF_ITER_STATE_DRAINED: 772 return "drained"; 773 case BPF_ITER_STATE_INVALID: 774 return "<invalid>"; 775 default: 776 WARN_ONCE(1, "unknown iter state %d\n", state); 777 return "<unknown>"; 778 } 779 } 780 781 static void mark_reg_scratched(struct bpf_verifier_env *env, u32 regno) 782 { 783 env->scratched_regs |= 1U << regno; 784 } 785 786 static void mark_stack_slot_scratched(struct bpf_verifier_env *env, u32 spi) 787 { 788 env->scratched_stack_slots |= 1ULL << spi; 789 } 790 791 static bool reg_scratched(const struct bpf_verifier_env *env, u32 regno) 792 { 793 return (env->scratched_regs >> regno) & 1; 794 } 795 796 static bool stack_slot_scratched(const struct bpf_verifier_env *env, u64 regno) 797 { 798 return (env->scratched_stack_slots >> regno) & 1; 799 } 800 801 static bool verifier_state_scratched(const struct bpf_verifier_env *env) 802 { 803 return env->scratched_regs || env->scratched_stack_slots; 804 } 805 806 static void mark_verifier_state_clean(struct bpf_verifier_env *env) 807 { 808 env->scratched_regs = 0U; 809 env->scratched_stack_slots = 0ULL; 810 } 811 812 /* Used for printing the entire verifier state. */ 813 static void mark_verifier_state_scratched(struct bpf_verifier_env *env) 814 { 815 env->scratched_regs = ~0U; 816 env->scratched_stack_slots = ~0ULL; 817 } 818 819 static enum bpf_dynptr_type arg_to_dynptr_type(enum bpf_arg_type arg_type) 820 { 821 switch (arg_type & DYNPTR_TYPE_FLAG_MASK) { 822 case DYNPTR_TYPE_LOCAL: 823 return BPF_DYNPTR_TYPE_LOCAL; 824 case DYNPTR_TYPE_RINGBUF: 825 return BPF_DYNPTR_TYPE_RINGBUF; 826 case DYNPTR_TYPE_SKB: 827 return BPF_DYNPTR_TYPE_SKB; 828 case DYNPTR_TYPE_XDP: 829 return BPF_DYNPTR_TYPE_XDP; 830 default: 831 return BPF_DYNPTR_TYPE_INVALID; 832 } 833 } 834 835 static enum bpf_type_flag get_dynptr_type_flag(enum bpf_dynptr_type type) 836 { 837 switch (type) { 838 case BPF_DYNPTR_TYPE_LOCAL: 839 return DYNPTR_TYPE_LOCAL; 840 case BPF_DYNPTR_TYPE_RINGBUF: 841 return DYNPTR_TYPE_RINGBUF; 842 case BPF_DYNPTR_TYPE_SKB: 843 return DYNPTR_TYPE_SKB; 844 case BPF_DYNPTR_TYPE_XDP: 845 return DYNPTR_TYPE_XDP; 846 default: 847 return 0; 848 } 849 } 850 851 static bool dynptr_type_refcounted(enum bpf_dynptr_type type) 852 { 853 return type == BPF_DYNPTR_TYPE_RINGBUF; 854 } 855 856 static void __mark_dynptr_reg(struct bpf_reg_state *reg, 857 enum bpf_dynptr_type type, 858 bool first_slot, int dynptr_id); 859 860 static void __mark_reg_not_init(const struct bpf_verifier_env *env, 861 struct bpf_reg_state *reg); 862 863 static void mark_dynptr_stack_regs(struct bpf_verifier_env *env, 864 struct bpf_reg_state *sreg1, 865 struct bpf_reg_state *sreg2, 866 enum bpf_dynptr_type type) 867 { 868 int id = ++env->id_gen; 869 870 __mark_dynptr_reg(sreg1, type, true, id); 871 __mark_dynptr_reg(sreg2, type, false, id); 872 } 873 874 static void mark_dynptr_cb_reg(struct bpf_verifier_env *env, 875 struct bpf_reg_state *reg, 876 enum bpf_dynptr_type type) 877 { 878 __mark_dynptr_reg(reg, type, true, ++env->id_gen); 879 } 880 881 static int destroy_if_dynptr_stack_slot(struct bpf_verifier_env *env, 882 struct bpf_func_state *state, int spi); 883 884 static int mark_stack_slots_dynptr(struct bpf_verifier_env *env, struct bpf_reg_state *reg, 885 enum bpf_arg_type arg_type, int insn_idx, int clone_ref_obj_id) 886 { 887 struct bpf_func_state *state = func(env, reg); 888 enum bpf_dynptr_type type; 889 int spi, i, err; 890 891 spi = dynptr_get_spi(env, reg); 892 if (spi < 0) 893 return spi; 894 895 /* We cannot assume both spi and spi - 1 belong to the same dynptr, 896 * hence we need to call destroy_if_dynptr_stack_slot twice for both, 897 * to ensure that for the following example: 898 * [d1][d1][d2][d2] 899 * spi 3 2 1 0 900 * So marking spi = 2 should lead to destruction of both d1 and d2. In 901 * case they do belong to same dynptr, second call won't see slot_type 902 * as STACK_DYNPTR and will simply skip destruction. 903 */ 904 err = destroy_if_dynptr_stack_slot(env, state, spi); 905 if (err) 906 return err; 907 err = destroy_if_dynptr_stack_slot(env, state, spi - 1); 908 if (err) 909 return err; 910 911 for (i = 0; i < BPF_REG_SIZE; i++) { 912 state->stack[spi].slot_type[i] = STACK_DYNPTR; 913 state->stack[spi - 1].slot_type[i] = STACK_DYNPTR; 914 } 915 916 type = arg_to_dynptr_type(arg_type); 917 if (type == BPF_DYNPTR_TYPE_INVALID) 918 return -EINVAL; 919 920 mark_dynptr_stack_regs(env, &state->stack[spi].spilled_ptr, 921 &state->stack[spi - 1].spilled_ptr, type); 922 923 if (dynptr_type_refcounted(type)) { 924 /* The id is used to track proper releasing */ 925 int id; 926 927 if (clone_ref_obj_id) 928 id = clone_ref_obj_id; 929 else 930 id = acquire_reference_state(env, insn_idx); 931 932 if (id < 0) 933 return id; 934 935 state->stack[spi].spilled_ptr.ref_obj_id = id; 936 state->stack[spi - 1].spilled_ptr.ref_obj_id = id; 937 } 938 939 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN; 940 state->stack[spi - 1].spilled_ptr.live |= REG_LIVE_WRITTEN; 941 942 return 0; 943 } 944 945 static void invalidate_dynptr(struct bpf_verifier_env *env, struct bpf_func_state *state, int spi) 946 { 947 int i; 948 949 for (i = 0; i < BPF_REG_SIZE; i++) { 950 state->stack[spi].slot_type[i] = STACK_INVALID; 951 state->stack[spi - 1].slot_type[i] = STACK_INVALID; 952 } 953 954 __mark_reg_not_init(env, &state->stack[spi].spilled_ptr); 955 __mark_reg_not_init(env, &state->stack[spi - 1].spilled_ptr); 956 957 /* Why do we need to set REG_LIVE_WRITTEN for STACK_INVALID slot? 958 * 959 * While we don't allow reading STACK_INVALID, it is still possible to 960 * do <8 byte writes marking some but not all slots as STACK_MISC. Then, 961 * helpers or insns can do partial read of that part without failing, 962 * but check_stack_range_initialized, check_stack_read_var_off, and 963 * check_stack_read_fixed_off will do mark_reg_read for all 8-bytes of 964 * the slot conservatively. Hence we need to prevent those liveness 965 * marking walks. 966 * 967 * This was not a problem before because STACK_INVALID is only set by 968 * default (where the default reg state has its reg->parent as NULL), or 969 * in clean_live_states after REG_LIVE_DONE (at which point 970 * mark_reg_read won't walk reg->parent chain), but not randomly during 971 * verifier state exploration (like we did above). Hence, for our case 972 * parentage chain will still be live (i.e. reg->parent may be 973 * non-NULL), while earlier reg->parent was NULL, so we need 974 * REG_LIVE_WRITTEN to screen off read marker propagation when it is 975 * done later on reads or by mark_dynptr_read as well to unnecessary 976 * mark registers in verifier state. 977 */ 978 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN; 979 state->stack[spi - 1].spilled_ptr.live |= REG_LIVE_WRITTEN; 980 } 981 982 static int unmark_stack_slots_dynptr(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 983 { 984 struct bpf_func_state *state = func(env, reg); 985 int spi, ref_obj_id, i; 986 987 spi = dynptr_get_spi(env, reg); 988 if (spi < 0) 989 return spi; 990 991 if (!dynptr_type_refcounted(state->stack[spi].spilled_ptr.dynptr.type)) { 992 invalidate_dynptr(env, state, spi); 993 return 0; 994 } 995 996 ref_obj_id = state->stack[spi].spilled_ptr.ref_obj_id; 997 998 /* If the dynptr has a ref_obj_id, then we need to invalidate 999 * two things: 1000 * 1001 * 1) Any dynptrs with a matching ref_obj_id (clones) 1002 * 2) Any slices derived from this dynptr. 1003 */ 1004 1005 /* Invalidate any slices associated with this dynptr */ 1006 WARN_ON_ONCE(release_reference(env, ref_obj_id)); 1007 1008 /* Invalidate any dynptr clones */ 1009 for (i = 1; i < state->allocated_stack / BPF_REG_SIZE; i++) { 1010 if (state->stack[i].spilled_ptr.ref_obj_id != ref_obj_id) 1011 continue; 1012 1013 /* it should always be the case that if the ref obj id 1014 * matches then the stack slot also belongs to a 1015 * dynptr 1016 */ 1017 if (state->stack[i].slot_type[0] != STACK_DYNPTR) { 1018 verbose(env, "verifier internal error: misconfigured ref_obj_id\n"); 1019 return -EFAULT; 1020 } 1021 if (state->stack[i].spilled_ptr.dynptr.first_slot) 1022 invalidate_dynptr(env, state, i); 1023 } 1024 1025 return 0; 1026 } 1027 1028 static void __mark_reg_unknown(const struct bpf_verifier_env *env, 1029 struct bpf_reg_state *reg); 1030 1031 static void mark_reg_invalid(const struct bpf_verifier_env *env, struct bpf_reg_state *reg) 1032 { 1033 if (!env->allow_ptr_leaks) 1034 __mark_reg_not_init(env, reg); 1035 else 1036 __mark_reg_unknown(env, reg); 1037 } 1038 1039 static int destroy_if_dynptr_stack_slot(struct bpf_verifier_env *env, 1040 struct bpf_func_state *state, int spi) 1041 { 1042 struct bpf_func_state *fstate; 1043 struct bpf_reg_state *dreg; 1044 int i, dynptr_id; 1045 1046 /* We always ensure that STACK_DYNPTR is never set partially, 1047 * hence just checking for slot_type[0] is enough. This is 1048 * different for STACK_SPILL, where it may be only set for 1049 * 1 byte, so code has to use is_spilled_reg. 1050 */ 1051 if (state->stack[spi].slot_type[0] != STACK_DYNPTR) 1052 return 0; 1053 1054 /* Reposition spi to first slot */ 1055 if (!state->stack[spi].spilled_ptr.dynptr.first_slot) 1056 spi = spi + 1; 1057 1058 if (dynptr_type_refcounted(state->stack[spi].spilled_ptr.dynptr.type)) { 1059 verbose(env, "cannot overwrite referenced dynptr\n"); 1060 return -EINVAL; 1061 } 1062 1063 mark_stack_slot_scratched(env, spi); 1064 mark_stack_slot_scratched(env, spi - 1); 1065 1066 /* Writing partially to one dynptr stack slot destroys both. */ 1067 for (i = 0; i < BPF_REG_SIZE; i++) { 1068 state->stack[spi].slot_type[i] = STACK_INVALID; 1069 state->stack[spi - 1].slot_type[i] = STACK_INVALID; 1070 } 1071 1072 dynptr_id = state->stack[spi].spilled_ptr.id; 1073 /* Invalidate any slices associated with this dynptr */ 1074 bpf_for_each_reg_in_vstate(env->cur_state, fstate, dreg, ({ 1075 /* Dynptr slices are only PTR_TO_MEM_OR_NULL and PTR_TO_MEM */ 1076 if (dreg->type != (PTR_TO_MEM | PTR_MAYBE_NULL) && dreg->type != PTR_TO_MEM) 1077 continue; 1078 if (dreg->dynptr_id == dynptr_id) 1079 mark_reg_invalid(env, dreg); 1080 })); 1081 1082 /* Do not release reference state, we are destroying dynptr on stack, 1083 * not using some helper to release it. Just reset register. 1084 */ 1085 __mark_reg_not_init(env, &state->stack[spi].spilled_ptr); 1086 __mark_reg_not_init(env, &state->stack[spi - 1].spilled_ptr); 1087 1088 /* Same reason as unmark_stack_slots_dynptr above */ 1089 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN; 1090 state->stack[spi - 1].spilled_ptr.live |= REG_LIVE_WRITTEN; 1091 1092 return 0; 1093 } 1094 1095 static bool is_dynptr_reg_valid_uninit(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 1096 { 1097 int spi; 1098 1099 if (reg->type == CONST_PTR_TO_DYNPTR) 1100 return false; 1101 1102 spi = dynptr_get_spi(env, reg); 1103 1104 /* -ERANGE (i.e. spi not falling into allocated stack slots) isn't an 1105 * error because this just means the stack state hasn't been updated yet. 1106 * We will do check_mem_access to check and update stack bounds later. 1107 */ 1108 if (spi < 0 && spi != -ERANGE) 1109 return false; 1110 1111 /* We don't need to check if the stack slots are marked by previous 1112 * dynptr initializations because we allow overwriting existing unreferenced 1113 * STACK_DYNPTR slots, see mark_stack_slots_dynptr which calls 1114 * destroy_if_dynptr_stack_slot to ensure dynptr objects at the slots we are 1115 * touching are completely destructed before we reinitialize them for a new 1116 * one. For referenced ones, destroy_if_dynptr_stack_slot returns an error early 1117 * instead of delaying it until the end where the user will get "Unreleased 1118 * reference" error. 1119 */ 1120 return true; 1121 } 1122 1123 static bool is_dynptr_reg_valid_init(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 1124 { 1125 struct bpf_func_state *state = func(env, reg); 1126 int i, spi; 1127 1128 /* This already represents first slot of initialized bpf_dynptr. 1129 * 1130 * CONST_PTR_TO_DYNPTR already has fixed and var_off as 0 due to 1131 * check_func_arg_reg_off's logic, so we don't need to check its 1132 * offset and alignment. 1133 */ 1134 if (reg->type == CONST_PTR_TO_DYNPTR) 1135 return true; 1136 1137 spi = dynptr_get_spi(env, reg); 1138 if (spi < 0) 1139 return false; 1140 if (!state->stack[spi].spilled_ptr.dynptr.first_slot) 1141 return false; 1142 1143 for (i = 0; i < BPF_REG_SIZE; i++) { 1144 if (state->stack[spi].slot_type[i] != STACK_DYNPTR || 1145 state->stack[spi - 1].slot_type[i] != STACK_DYNPTR) 1146 return false; 1147 } 1148 1149 return true; 1150 } 1151 1152 static bool is_dynptr_type_expected(struct bpf_verifier_env *env, struct bpf_reg_state *reg, 1153 enum bpf_arg_type arg_type) 1154 { 1155 struct bpf_func_state *state = func(env, reg); 1156 enum bpf_dynptr_type dynptr_type; 1157 int spi; 1158 1159 /* ARG_PTR_TO_DYNPTR takes any type of dynptr */ 1160 if (arg_type == ARG_PTR_TO_DYNPTR) 1161 return true; 1162 1163 dynptr_type = arg_to_dynptr_type(arg_type); 1164 if (reg->type == CONST_PTR_TO_DYNPTR) { 1165 return reg->dynptr.type == dynptr_type; 1166 } else { 1167 spi = dynptr_get_spi(env, reg); 1168 if (spi < 0) 1169 return false; 1170 return state->stack[spi].spilled_ptr.dynptr.type == dynptr_type; 1171 } 1172 } 1173 1174 static void __mark_reg_known_zero(struct bpf_reg_state *reg); 1175 1176 static int mark_stack_slots_iter(struct bpf_verifier_env *env, 1177 struct bpf_reg_state *reg, int insn_idx, 1178 struct btf *btf, u32 btf_id, int nr_slots) 1179 { 1180 struct bpf_func_state *state = func(env, reg); 1181 int spi, i, j, id; 1182 1183 spi = iter_get_spi(env, reg, nr_slots); 1184 if (spi < 0) 1185 return spi; 1186 1187 id = acquire_reference_state(env, insn_idx); 1188 if (id < 0) 1189 return id; 1190 1191 for (i = 0; i < nr_slots; i++) { 1192 struct bpf_stack_state *slot = &state->stack[spi - i]; 1193 struct bpf_reg_state *st = &slot->spilled_ptr; 1194 1195 __mark_reg_known_zero(st); 1196 st->type = PTR_TO_STACK; /* we don't have dedicated reg type */ 1197 st->live |= REG_LIVE_WRITTEN; 1198 st->ref_obj_id = i == 0 ? id : 0; 1199 st->iter.btf = btf; 1200 st->iter.btf_id = btf_id; 1201 st->iter.state = BPF_ITER_STATE_ACTIVE; 1202 st->iter.depth = 0; 1203 1204 for (j = 0; j < BPF_REG_SIZE; j++) 1205 slot->slot_type[j] = STACK_ITER; 1206 1207 mark_stack_slot_scratched(env, spi - i); 1208 } 1209 1210 return 0; 1211 } 1212 1213 static int unmark_stack_slots_iter(struct bpf_verifier_env *env, 1214 struct bpf_reg_state *reg, int nr_slots) 1215 { 1216 struct bpf_func_state *state = func(env, reg); 1217 int spi, i, j; 1218 1219 spi = iter_get_spi(env, reg, nr_slots); 1220 if (spi < 0) 1221 return spi; 1222 1223 for (i = 0; i < nr_slots; i++) { 1224 struct bpf_stack_state *slot = &state->stack[spi - i]; 1225 struct bpf_reg_state *st = &slot->spilled_ptr; 1226 1227 if (i == 0) 1228 WARN_ON_ONCE(release_reference(env, st->ref_obj_id)); 1229 1230 __mark_reg_not_init(env, st); 1231 1232 /* see unmark_stack_slots_dynptr() for why we need to set REG_LIVE_WRITTEN */ 1233 st->live |= REG_LIVE_WRITTEN; 1234 1235 for (j = 0; j < BPF_REG_SIZE; j++) 1236 slot->slot_type[j] = STACK_INVALID; 1237 1238 mark_stack_slot_scratched(env, spi - i); 1239 } 1240 1241 return 0; 1242 } 1243 1244 static bool is_iter_reg_valid_uninit(struct bpf_verifier_env *env, 1245 struct bpf_reg_state *reg, int nr_slots) 1246 { 1247 struct bpf_func_state *state = func(env, reg); 1248 int spi, i, j; 1249 1250 /* For -ERANGE (i.e. spi not falling into allocated stack slots), we 1251 * will do check_mem_access to check and update stack bounds later, so 1252 * return true for that case. 1253 */ 1254 spi = iter_get_spi(env, reg, nr_slots); 1255 if (spi == -ERANGE) 1256 return true; 1257 if (spi < 0) 1258 return false; 1259 1260 for (i = 0; i < nr_slots; i++) { 1261 struct bpf_stack_state *slot = &state->stack[spi - i]; 1262 1263 for (j = 0; j < BPF_REG_SIZE; j++) 1264 if (slot->slot_type[j] == STACK_ITER) 1265 return false; 1266 } 1267 1268 return true; 1269 } 1270 1271 static bool is_iter_reg_valid_init(struct bpf_verifier_env *env, struct bpf_reg_state *reg, 1272 struct btf *btf, u32 btf_id, int nr_slots) 1273 { 1274 struct bpf_func_state *state = func(env, reg); 1275 int spi, i, j; 1276 1277 spi = iter_get_spi(env, reg, nr_slots); 1278 if (spi < 0) 1279 return false; 1280 1281 for (i = 0; i < nr_slots; i++) { 1282 struct bpf_stack_state *slot = &state->stack[spi - i]; 1283 struct bpf_reg_state *st = &slot->spilled_ptr; 1284 1285 /* only main (first) slot has ref_obj_id set */ 1286 if (i == 0 && !st->ref_obj_id) 1287 return false; 1288 if (i != 0 && st->ref_obj_id) 1289 return false; 1290 if (st->iter.btf != btf || st->iter.btf_id != btf_id) 1291 return false; 1292 1293 for (j = 0; j < BPF_REG_SIZE; j++) 1294 if (slot->slot_type[j] != STACK_ITER) 1295 return false; 1296 } 1297 1298 return true; 1299 } 1300 1301 /* Check if given stack slot is "special": 1302 * - spilled register state (STACK_SPILL); 1303 * - dynptr state (STACK_DYNPTR); 1304 * - iter state (STACK_ITER). 1305 */ 1306 static bool is_stack_slot_special(const struct bpf_stack_state *stack) 1307 { 1308 enum bpf_stack_slot_type type = stack->slot_type[BPF_REG_SIZE - 1]; 1309 1310 switch (type) { 1311 case STACK_SPILL: 1312 case STACK_DYNPTR: 1313 case STACK_ITER: 1314 return true; 1315 case STACK_INVALID: 1316 case STACK_MISC: 1317 case STACK_ZERO: 1318 return false; 1319 default: 1320 WARN_ONCE(1, "unknown stack slot type %d\n", type); 1321 return true; 1322 } 1323 } 1324 1325 /* The reg state of a pointer or a bounded scalar was saved when 1326 * it was spilled to the stack. 1327 */ 1328 static bool is_spilled_reg(const struct bpf_stack_state *stack) 1329 { 1330 return stack->slot_type[BPF_REG_SIZE - 1] == STACK_SPILL; 1331 } 1332 1333 static bool is_spilled_scalar_reg(const struct bpf_stack_state *stack) 1334 { 1335 return stack->slot_type[BPF_REG_SIZE - 1] == STACK_SPILL && 1336 stack->spilled_ptr.type == SCALAR_VALUE; 1337 } 1338 1339 static void scrub_spilled_slot(u8 *stype) 1340 { 1341 if (*stype != STACK_INVALID) 1342 *stype = STACK_MISC; 1343 } 1344 1345 static void print_scalar_ranges(struct bpf_verifier_env *env, 1346 const struct bpf_reg_state *reg, 1347 const char **sep) 1348 { 1349 struct { 1350 const char *name; 1351 u64 val; 1352 bool omit; 1353 } minmaxs[] = { 1354 {"smin", reg->smin_value, reg->smin_value == S64_MIN}, 1355 {"smax", reg->smax_value, reg->smax_value == S64_MAX}, 1356 {"umin", reg->umin_value, reg->umin_value == 0}, 1357 {"umax", reg->umax_value, reg->umax_value == U64_MAX}, 1358 {"smin32", (s64)reg->s32_min_value, reg->s32_min_value == S32_MIN}, 1359 {"smax32", (s64)reg->s32_max_value, reg->s32_max_value == S32_MAX}, 1360 {"umin32", reg->u32_min_value, reg->u32_min_value == 0}, 1361 {"umax32", reg->u32_max_value, reg->u32_max_value == U32_MAX}, 1362 }, *m1, *m2, *mend = &minmaxs[ARRAY_SIZE(minmaxs)]; 1363 bool neg1, neg2; 1364 1365 for (m1 = &minmaxs[0]; m1 < mend; m1++) { 1366 if (m1->omit) 1367 continue; 1368 1369 neg1 = m1->name[0] == 's' && (s64)m1->val < 0; 1370 1371 verbose(env, "%s%s=", *sep, m1->name); 1372 *sep = ","; 1373 1374 for (m2 = m1 + 2; m2 < mend; m2 += 2) { 1375 if (m2->omit || m2->val != m1->val) 1376 continue; 1377 /* don't mix negatives with positives */ 1378 neg2 = m2->name[0] == 's' && (s64)m2->val < 0; 1379 if (neg2 != neg1) 1380 continue; 1381 m2->omit = true; 1382 verbose(env, "%s=", m2->name); 1383 } 1384 1385 verbose(env, m1->name[0] == 's' ? "%lld" : "%llu", m1->val); 1386 } 1387 } 1388 1389 static void print_verifier_state(struct bpf_verifier_env *env, 1390 const struct bpf_func_state *state, 1391 bool print_all) 1392 { 1393 const struct bpf_reg_state *reg; 1394 enum bpf_reg_type t; 1395 int i; 1396 1397 if (state->frameno) 1398 verbose(env, " frame%d:", state->frameno); 1399 for (i = 0; i < MAX_BPF_REG; i++) { 1400 reg = &state->regs[i]; 1401 t = reg->type; 1402 if (t == NOT_INIT) 1403 continue; 1404 if (!print_all && !reg_scratched(env, i)) 1405 continue; 1406 verbose(env, " R%d", i); 1407 print_liveness(env, reg->live); 1408 verbose(env, "="); 1409 if (t == SCALAR_VALUE && reg->precise) 1410 verbose(env, "P"); 1411 if ((t == SCALAR_VALUE || t == PTR_TO_STACK) && 1412 tnum_is_const(reg->var_off)) { 1413 /* reg->off should be 0 for SCALAR_VALUE */ 1414 verbose(env, "%s", t == SCALAR_VALUE ? "" : reg_type_str(env, t)); 1415 verbose(env, "%lld", reg->var_off.value + reg->off); 1416 } else { 1417 const char *sep = ""; 1418 1419 verbose(env, "%s", reg_type_str(env, t)); 1420 if (base_type(t) == PTR_TO_BTF_ID) 1421 verbose(env, "%s", btf_type_name(reg->btf, reg->btf_id)); 1422 verbose(env, "("); 1423 /* 1424 * _a stands for append, was shortened to avoid multiline statements below. 1425 * This macro is used to output a comma separated list of attributes. 1426 */ 1427 #define verbose_a(fmt, ...) ({ verbose(env, "%s" fmt, sep, __VA_ARGS__); sep = ","; }) 1428 1429 if (reg->id) 1430 verbose_a("id=%d", reg->id); 1431 if (reg->ref_obj_id) 1432 verbose_a("ref_obj_id=%d", reg->ref_obj_id); 1433 if (type_is_non_owning_ref(reg->type)) 1434 verbose_a("%s", "non_own_ref"); 1435 if (t != SCALAR_VALUE) 1436 verbose_a("off=%d", reg->off); 1437 if (type_is_pkt_pointer(t)) 1438 verbose_a("r=%d", reg->range); 1439 else if (base_type(t) == CONST_PTR_TO_MAP || 1440 base_type(t) == PTR_TO_MAP_KEY || 1441 base_type(t) == PTR_TO_MAP_VALUE) 1442 verbose_a("ks=%d,vs=%d", 1443 reg->map_ptr->key_size, 1444 reg->map_ptr->value_size); 1445 if (tnum_is_const(reg->var_off)) { 1446 /* Typically an immediate SCALAR_VALUE, but 1447 * could be a pointer whose offset is too big 1448 * for reg->off 1449 */ 1450 verbose_a("imm=%llx", reg->var_off.value); 1451 } else { 1452 print_scalar_ranges(env, reg, &sep); 1453 if (!tnum_is_unknown(reg->var_off)) { 1454 char tn_buf[48]; 1455 1456 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 1457 verbose_a("var_off=%s", tn_buf); 1458 } 1459 } 1460 #undef verbose_a 1461 1462 verbose(env, ")"); 1463 } 1464 } 1465 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) { 1466 char types_buf[BPF_REG_SIZE + 1]; 1467 bool valid = false; 1468 int j; 1469 1470 for (j = 0; j < BPF_REG_SIZE; j++) { 1471 if (state->stack[i].slot_type[j] != STACK_INVALID) 1472 valid = true; 1473 types_buf[j] = slot_type_char[state->stack[i].slot_type[j]]; 1474 } 1475 types_buf[BPF_REG_SIZE] = 0; 1476 if (!valid) 1477 continue; 1478 if (!print_all && !stack_slot_scratched(env, i)) 1479 continue; 1480 switch (state->stack[i].slot_type[BPF_REG_SIZE - 1]) { 1481 case STACK_SPILL: 1482 reg = &state->stack[i].spilled_ptr; 1483 t = reg->type; 1484 1485 verbose(env, " fp%d", (-i - 1) * BPF_REG_SIZE); 1486 print_liveness(env, reg->live); 1487 verbose(env, "=%s", t == SCALAR_VALUE ? "" : reg_type_str(env, t)); 1488 if (t == SCALAR_VALUE && reg->precise) 1489 verbose(env, "P"); 1490 if (t == SCALAR_VALUE && tnum_is_const(reg->var_off)) 1491 verbose(env, "%lld", reg->var_off.value + reg->off); 1492 break; 1493 case STACK_DYNPTR: 1494 i += BPF_DYNPTR_NR_SLOTS - 1; 1495 reg = &state->stack[i].spilled_ptr; 1496 1497 verbose(env, " fp%d", (-i - 1) * BPF_REG_SIZE); 1498 print_liveness(env, reg->live); 1499 verbose(env, "=dynptr_%s", dynptr_type_str(reg->dynptr.type)); 1500 if (reg->ref_obj_id) 1501 verbose(env, "(ref_id=%d)", reg->ref_obj_id); 1502 break; 1503 case STACK_ITER: 1504 /* only main slot has ref_obj_id set; skip others */ 1505 reg = &state->stack[i].spilled_ptr; 1506 if (!reg->ref_obj_id) 1507 continue; 1508 1509 verbose(env, " fp%d", (-i - 1) * BPF_REG_SIZE); 1510 print_liveness(env, reg->live); 1511 verbose(env, "=iter_%s(ref_id=%d,state=%s,depth=%u)", 1512 iter_type_str(reg->iter.btf, reg->iter.btf_id), 1513 reg->ref_obj_id, iter_state_str(reg->iter.state), 1514 reg->iter.depth); 1515 break; 1516 case STACK_MISC: 1517 case STACK_ZERO: 1518 default: 1519 reg = &state->stack[i].spilled_ptr; 1520 1521 for (j = 0; j < BPF_REG_SIZE; j++) 1522 types_buf[j] = slot_type_char[state->stack[i].slot_type[j]]; 1523 types_buf[BPF_REG_SIZE] = 0; 1524 1525 verbose(env, " fp%d", (-i - 1) * BPF_REG_SIZE); 1526 print_liveness(env, reg->live); 1527 verbose(env, "=%s", types_buf); 1528 break; 1529 } 1530 } 1531 if (state->acquired_refs && state->refs[0].id) { 1532 verbose(env, " refs=%d", state->refs[0].id); 1533 for (i = 1; i < state->acquired_refs; i++) 1534 if (state->refs[i].id) 1535 verbose(env, ",%d", state->refs[i].id); 1536 } 1537 if (state->in_callback_fn) 1538 verbose(env, " cb"); 1539 if (state->in_async_callback_fn) 1540 verbose(env, " async_cb"); 1541 verbose(env, "\n"); 1542 if (!print_all) 1543 mark_verifier_state_clean(env); 1544 } 1545 1546 static inline u32 vlog_alignment(u32 pos) 1547 { 1548 return round_up(max(pos + BPF_LOG_MIN_ALIGNMENT / 2, BPF_LOG_ALIGNMENT), 1549 BPF_LOG_MIN_ALIGNMENT) - pos - 1; 1550 } 1551 1552 static void print_insn_state(struct bpf_verifier_env *env, 1553 const struct bpf_func_state *state) 1554 { 1555 if (env->prev_log_pos && env->prev_log_pos == env->log.end_pos) { 1556 /* remove new line character */ 1557 bpf_vlog_reset(&env->log, env->prev_log_pos - 1); 1558 verbose(env, "%*c;", vlog_alignment(env->prev_insn_print_pos), ' '); 1559 } else { 1560 verbose(env, "%d:", env->insn_idx); 1561 } 1562 print_verifier_state(env, state, false); 1563 } 1564 1565 /* copy array src of length n * size bytes to dst. dst is reallocated if it's too 1566 * small to hold src. This is different from krealloc since we don't want to preserve 1567 * the contents of dst. 1568 * 1569 * Leaves dst untouched if src is NULL or length is zero. Returns NULL if memory could 1570 * not be allocated. 1571 */ 1572 static void *copy_array(void *dst, const void *src, size_t n, size_t size, gfp_t flags) 1573 { 1574 size_t alloc_bytes; 1575 void *orig = dst; 1576 size_t bytes; 1577 1578 if (ZERO_OR_NULL_PTR(src)) 1579 goto out; 1580 1581 if (unlikely(check_mul_overflow(n, size, &bytes))) 1582 return NULL; 1583 1584 alloc_bytes = max(ksize(orig), kmalloc_size_roundup(bytes)); 1585 dst = krealloc(orig, alloc_bytes, flags); 1586 if (!dst) { 1587 kfree(orig); 1588 return NULL; 1589 } 1590 1591 memcpy(dst, src, bytes); 1592 out: 1593 return dst ? dst : ZERO_SIZE_PTR; 1594 } 1595 1596 /* resize an array from old_n items to new_n items. the array is reallocated if it's too 1597 * small to hold new_n items. new items are zeroed out if the array grows. 1598 * 1599 * Contrary to krealloc_array, does not free arr if new_n is zero. 1600 */ 1601 static void *realloc_array(void *arr, size_t old_n, size_t new_n, size_t size) 1602 { 1603 size_t alloc_size; 1604 void *new_arr; 1605 1606 if (!new_n || old_n == new_n) 1607 goto out; 1608 1609 alloc_size = kmalloc_size_roundup(size_mul(new_n, size)); 1610 new_arr = krealloc(arr, alloc_size, GFP_KERNEL); 1611 if (!new_arr) { 1612 kfree(arr); 1613 return NULL; 1614 } 1615 arr = new_arr; 1616 1617 if (new_n > old_n) 1618 memset(arr + old_n * size, 0, (new_n - old_n) * size); 1619 1620 out: 1621 return arr ? arr : ZERO_SIZE_PTR; 1622 } 1623 1624 static int copy_reference_state(struct bpf_func_state *dst, const struct bpf_func_state *src) 1625 { 1626 dst->refs = copy_array(dst->refs, src->refs, src->acquired_refs, 1627 sizeof(struct bpf_reference_state), GFP_KERNEL); 1628 if (!dst->refs) 1629 return -ENOMEM; 1630 1631 dst->acquired_refs = src->acquired_refs; 1632 return 0; 1633 } 1634 1635 static int copy_stack_state(struct bpf_func_state *dst, const struct bpf_func_state *src) 1636 { 1637 size_t n = src->allocated_stack / BPF_REG_SIZE; 1638 1639 dst->stack = copy_array(dst->stack, src->stack, n, sizeof(struct bpf_stack_state), 1640 GFP_KERNEL); 1641 if (!dst->stack) 1642 return -ENOMEM; 1643 1644 dst->allocated_stack = src->allocated_stack; 1645 return 0; 1646 } 1647 1648 static int resize_reference_state(struct bpf_func_state *state, size_t n) 1649 { 1650 state->refs = realloc_array(state->refs, state->acquired_refs, n, 1651 sizeof(struct bpf_reference_state)); 1652 if (!state->refs) 1653 return -ENOMEM; 1654 1655 state->acquired_refs = n; 1656 return 0; 1657 } 1658 1659 static int grow_stack_state(struct bpf_func_state *state, int size) 1660 { 1661 size_t old_n = state->allocated_stack / BPF_REG_SIZE, n = size / BPF_REG_SIZE; 1662 1663 if (old_n >= n) 1664 return 0; 1665 1666 state->stack = realloc_array(state->stack, old_n, n, sizeof(struct bpf_stack_state)); 1667 if (!state->stack) 1668 return -ENOMEM; 1669 1670 state->allocated_stack = size; 1671 return 0; 1672 } 1673 1674 /* Acquire a pointer id from the env and update the state->refs to include 1675 * this new pointer reference. 1676 * On success, returns a valid pointer id to associate with the register 1677 * On failure, returns a negative errno. 1678 */ 1679 static int acquire_reference_state(struct bpf_verifier_env *env, int insn_idx) 1680 { 1681 struct bpf_func_state *state = cur_func(env); 1682 int new_ofs = state->acquired_refs; 1683 int id, err; 1684 1685 err = resize_reference_state(state, state->acquired_refs + 1); 1686 if (err) 1687 return err; 1688 id = ++env->id_gen; 1689 state->refs[new_ofs].id = id; 1690 state->refs[new_ofs].insn_idx = insn_idx; 1691 state->refs[new_ofs].callback_ref = state->in_callback_fn ? state->frameno : 0; 1692 1693 return id; 1694 } 1695 1696 /* release function corresponding to acquire_reference_state(). Idempotent. */ 1697 static int release_reference_state(struct bpf_func_state *state, int ptr_id) 1698 { 1699 int i, last_idx; 1700 1701 last_idx = state->acquired_refs - 1; 1702 for (i = 0; i < state->acquired_refs; i++) { 1703 if (state->refs[i].id == ptr_id) { 1704 /* Cannot release caller references in callbacks */ 1705 if (state->in_callback_fn && state->refs[i].callback_ref != state->frameno) 1706 return -EINVAL; 1707 if (last_idx && i != last_idx) 1708 memcpy(&state->refs[i], &state->refs[last_idx], 1709 sizeof(*state->refs)); 1710 memset(&state->refs[last_idx], 0, sizeof(*state->refs)); 1711 state->acquired_refs--; 1712 return 0; 1713 } 1714 } 1715 return -EINVAL; 1716 } 1717 1718 static void free_func_state(struct bpf_func_state *state) 1719 { 1720 if (!state) 1721 return; 1722 kfree(state->refs); 1723 kfree(state->stack); 1724 kfree(state); 1725 } 1726 1727 static void clear_jmp_history(struct bpf_verifier_state *state) 1728 { 1729 kfree(state->jmp_history); 1730 state->jmp_history = NULL; 1731 state->jmp_history_cnt = 0; 1732 } 1733 1734 static void free_verifier_state(struct bpf_verifier_state *state, 1735 bool free_self) 1736 { 1737 int i; 1738 1739 for (i = 0; i <= state->curframe; i++) { 1740 free_func_state(state->frame[i]); 1741 state->frame[i] = NULL; 1742 } 1743 clear_jmp_history(state); 1744 if (free_self) 1745 kfree(state); 1746 } 1747 1748 /* copy verifier state from src to dst growing dst stack space 1749 * when necessary to accommodate larger src stack 1750 */ 1751 static int copy_func_state(struct bpf_func_state *dst, 1752 const struct bpf_func_state *src) 1753 { 1754 int err; 1755 1756 memcpy(dst, src, offsetof(struct bpf_func_state, acquired_refs)); 1757 err = copy_reference_state(dst, src); 1758 if (err) 1759 return err; 1760 return copy_stack_state(dst, src); 1761 } 1762 1763 static int copy_verifier_state(struct bpf_verifier_state *dst_state, 1764 const struct bpf_verifier_state *src) 1765 { 1766 struct bpf_func_state *dst; 1767 int i, err; 1768 1769 dst_state->jmp_history = copy_array(dst_state->jmp_history, src->jmp_history, 1770 src->jmp_history_cnt, sizeof(struct bpf_idx_pair), 1771 GFP_USER); 1772 if (!dst_state->jmp_history) 1773 return -ENOMEM; 1774 dst_state->jmp_history_cnt = src->jmp_history_cnt; 1775 1776 /* if dst has more stack frames then src frame, free them, this is also 1777 * necessary in case of exceptional exits using bpf_throw. 1778 */ 1779 for (i = src->curframe + 1; i <= dst_state->curframe; i++) { 1780 free_func_state(dst_state->frame[i]); 1781 dst_state->frame[i] = NULL; 1782 } 1783 dst_state->speculative = src->speculative; 1784 dst_state->active_rcu_lock = src->active_rcu_lock; 1785 dst_state->curframe = src->curframe; 1786 dst_state->active_lock.ptr = src->active_lock.ptr; 1787 dst_state->active_lock.id = src->active_lock.id; 1788 dst_state->branches = src->branches; 1789 dst_state->parent = src->parent; 1790 dst_state->first_insn_idx = src->first_insn_idx; 1791 dst_state->last_insn_idx = src->last_insn_idx; 1792 for (i = 0; i <= src->curframe; i++) { 1793 dst = dst_state->frame[i]; 1794 if (!dst) { 1795 dst = kzalloc(sizeof(*dst), GFP_KERNEL); 1796 if (!dst) 1797 return -ENOMEM; 1798 dst_state->frame[i] = dst; 1799 } 1800 err = copy_func_state(dst, src->frame[i]); 1801 if (err) 1802 return err; 1803 } 1804 return 0; 1805 } 1806 1807 static void update_branch_counts(struct bpf_verifier_env *env, struct bpf_verifier_state *st) 1808 { 1809 while (st) { 1810 u32 br = --st->branches; 1811 1812 /* WARN_ON(br > 1) technically makes sense here, 1813 * but see comment in push_stack(), hence: 1814 */ 1815 WARN_ONCE((int)br < 0, 1816 "BUG update_branch_counts:branches_to_explore=%d\n", 1817 br); 1818 if (br) 1819 break; 1820 st = st->parent; 1821 } 1822 } 1823 1824 static int pop_stack(struct bpf_verifier_env *env, int *prev_insn_idx, 1825 int *insn_idx, bool pop_log) 1826 { 1827 struct bpf_verifier_state *cur = env->cur_state; 1828 struct bpf_verifier_stack_elem *elem, *head = env->head; 1829 int err; 1830 1831 if (env->head == NULL) 1832 return -ENOENT; 1833 1834 if (cur) { 1835 err = copy_verifier_state(cur, &head->st); 1836 if (err) 1837 return err; 1838 } 1839 if (pop_log) 1840 bpf_vlog_reset(&env->log, head->log_pos); 1841 if (insn_idx) 1842 *insn_idx = head->insn_idx; 1843 if (prev_insn_idx) 1844 *prev_insn_idx = head->prev_insn_idx; 1845 elem = head->next; 1846 free_verifier_state(&head->st, false); 1847 kfree(head); 1848 env->head = elem; 1849 env->stack_size--; 1850 return 0; 1851 } 1852 1853 static struct bpf_verifier_state *push_stack(struct bpf_verifier_env *env, 1854 int insn_idx, int prev_insn_idx, 1855 bool speculative) 1856 { 1857 struct bpf_verifier_state *cur = env->cur_state; 1858 struct bpf_verifier_stack_elem *elem; 1859 int err; 1860 1861 elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL); 1862 if (!elem) 1863 goto err; 1864 1865 elem->insn_idx = insn_idx; 1866 elem->prev_insn_idx = prev_insn_idx; 1867 elem->next = env->head; 1868 elem->log_pos = env->log.end_pos; 1869 env->head = elem; 1870 env->stack_size++; 1871 err = copy_verifier_state(&elem->st, cur); 1872 if (err) 1873 goto err; 1874 elem->st.speculative |= speculative; 1875 if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) { 1876 verbose(env, "The sequence of %d jumps is too complex.\n", 1877 env->stack_size); 1878 goto err; 1879 } 1880 if (elem->st.parent) { 1881 ++elem->st.parent->branches; 1882 /* WARN_ON(branches > 2) technically makes sense here, 1883 * but 1884 * 1. speculative states will bump 'branches' for non-branch 1885 * instructions 1886 * 2. is_state_visited() heuristics may decide not to create 1887 * a new state for a sequence of branches and all such current 1888 * and cloned states will be pointing to a single parent state 1889 * which might have large 'branches' count. 1890 */ 1891 } 1892 return &elem->st; 1893 err: 1894 free_verifier_state(env->cur_state, true); 1895 env->cur_state = NULL; 1896 /* pop all elements and return */ 1897 while (!pop_stack(env, NULL, NULL, false)); 1898 return NULL; 1899 } 1900 1901 #define CALLER_SAVED_REGS 6 1902 static const int caller_saved[CALLER_SAVED_REGS] = { 1903 BPF_REG_0, BPF_REG_1, BPF_REG_2, BPF_REG_3, BPF_REG_4, BPF_REG_5 1904 }; 1905 1906 /* This helper doesn't clear reg->id */ 1907 static void ___mark_reg_known(struct bpf_reg_state *reg, u64 imm) 1908 { 1909 reg->var_off = tnum_const(imm); 1910 reg->smin_value = (s64)imm; 1911 reg->smax_value = (s64)imm; 1912 reg->umin_value = imm; 1913 reg->umax_value = imm; 1914 1915 reg->s32_min_value = (s32)imm; 1916 reg->s32_max_value = (s32)imm; 1917 reg->u32_min_value = (u32)imm; 1918 reg->u32_max_value = (u32)imm; 1919 } 1920 1921 /* Mark the unknown part of a register (variable offset or scalar value) as 1922 * known to have the value @imm. 1923 */ 1924 static void __mark_reg_known(struct bpf_reg_state *reg, u64 imm) 1925 { 1926 /* Clear off and union(map_ptr, range) */ 1927 memset(((u8 *)reg) + sizeof(reg->type), 0, 1928 offsetof(struct bpf_reg_state, var_off) - sizeof(reg->type)); 1929 reg->id = 0; 1930 reg->ref_obj_id = 0; 1931 ___mark_reg_known(reg, imm); 1932 } 1933 1934 static void __mark_reg32_known(struct bpf_reg_state *reg, u64 imm) 1935 { 1936 reg->var_off = tnum_const_subreg(reg->var_off, imm); 1937 reg->s32_min_value = (s32)imm; 1938 reg->s32_max_value = (s32)imm; 1939 reg->u32_min_value = (u32)imm; 1940 reg->u32_max_value = (u32)imm; 1941 } 1942 1943 /* Mark the 'variable offset' part of a register as zero. This should be 1944 * used only on registers holding a pointer type. 1945 */ 1946 static void __mark_reg_known_zero(struct bpf_reg_state *reg) 1947 { 1948 __mark_reg_known(reg, 0); 1949 } 1950 1951 static void __mark_reg_const_zero(struct bpf_reg_state *reg) 1952 { 1953 __mark_reg_known(reg, 0); 1954 reg->type = SCALAR_VALUE; 1955 } 1956 1957 static void mark_reg_known_zero(struct bpf_verifier_env *env, 1958 struct bpf_reg_state *regs, u32 regno) 1959 { 1960 if (WARN_ON(regno >= MAX_BPF_REG)) { 1961 verbose(env, "mark_reg_known_zero(regs, %u)\n", regno); 1962 /* Something bad happened, let's kill all regs */ 1963 for (regno = 0; regno < MAX_BPF_REG; regno++) 1964 __mark_reg_not_init(env, regs + regno); 1965 return; 1966 } 1967 __mark_reg_known_zero(regs + regno); 1968 } 1969 1970 static void __mark_dynptr_reg(struct bpf_reg_state *reg, enum bpf_dynptr_type type, 1971 bool first_slot, int dynptr_id) 1972 { 1973 /* reg->type has no meaning for STACK_DYNPTR, but when we set reg for 1974 * callback arguments, it does need to be CONST_PTR_TO_DYNPTR, so simply 1975 * set it unconditionally as it is ignored for STACK_DYNPTR anyway. 1976 */ 1977 __mark_reg_known_zero(reg); 1978 reg->type = CONST_PTR_TO_DYNPTR; 1979 /* Give each dynptr a unique id to uniquely associate slices to it. */ 1980 reg->id = dynptr_id; 1981 reg->dynptr.type = type; 1982 reg->dynptr.first_slot = first_slot; 1983 } 1984 1985 static void mark_ptr_not_null_reg(struct bpf_reg_state *reg) 1986 { 1987 if (base_type(reg->type) == PTR_TO_MAP_VALUE) { 1988 const struct bpf_map *map = reg->map_ptr; 1989 1990 if (map->inner_map_meta) { 1991 reg->type = CONST_PTR_TO_MAP; 1992 reg->map_ptr = map->inner_map_meta; 1993 /* transfer reg's id which is unique for every map_lookup_elem 1994 * as UID of the inner map. 1995 */ 1996 if (btf_record_has_field(map->inner_map_meta->record, BPF_TIMER)) 1997 reg->map_uid = reg->id; 1998 } else if (map->map_type == BPF_MAP_TYPE_XSKMAP) { 1999 reg->type = PTR_TO_XDP_SOCK; 2000 } else if (map->map_type == BPF_MAP_TYPE_SOCKMAP || 2001 map->map_type == BPF_MAP_TYPE_SOCKHASH) { 2002 reg->type = PTR_TO_SOCKET; 2003 } else { 2004 reg->type = PTR_TO_MAP_VALUE; 2005 } 2006 return; 2007 } 2008 2009 reg->type &= ~PTR_MAYBE_NULL; 2010 } 2011 2012 static void mark_reg_graph_node(struct bpf_reg_state *regs, u32 regno, 2013 struct btf_field_graph_root *ds_head) 2014 { 2015 __mark_reg_known_zero(®s[regno]); 2016 regs[regno].type = PTR_TO_BTF_ID | MEM_ALLOC; 2017 regs[regno].btf = ds_head->btf; 2018 regs[regno].btf_id = ds_head->value_btf_id; 2019 regs[regno].off = ds_head->node_offset; 2020 } 2021 2022 static bool reg_is_pkt_pointer(const struct bpf_reg_state *reg) 2023 { 2024 return type_is_pkt_pointer(reg->type); 2025 } 2026 2027 static bool reg_is_pkt_pointer_any(const struct bpf_reg_state *reg) 2028 { 2029 return reg_is_pkt_pointer(reg) || 2030 reg->type == PTR_TO_PACKET_END; 2031 } 2032 2033 static bool reg_is_dynptr_slice_pkt(const struct bpf_reg_state *reg) 2034 { 2035 return base_type(reg->type) == PTR_TO_MEM && 2036 (reg->type & DYNPTR_TYPE_SKB || reg->type & DYNPTR_TYPE_XDP); 2037 } 2038 2039 /* Unmodified PTR_TO_PACKET[_META,_END] register from ctx access. */ 2040 static bool reg_is_init_pkt_pointer(const struct bpf_reg_state *reg, 2041 enum bpf_reg_type which) 2042 { 2043 /* The register can already have a range from prior markings. 2044 * This is fine as long as it hasn't been advanced from its 2045 * origin. 2046 */ 2047 return reg->type == which && 2048 reg->id == 0 && 2049 reg->off == 0 && 2050 tnum_equals_const(reg->var_off, 0); 2051 } 2052 2053 /* Reset the min/max bounds of a register */ 2054 static void __mark_reg_unbounded(struct bpf_reg_state *reg) 2055 { 2056 reg->smin_value = S64_MIN; 2057 reg->smax_value = S64_MAX; 2058 reg->umin_value = 0; 2059 reg->umax_value = U64_MAX; 2060 2061 reg->s32_min_value = S32_MIN; 2062 reg->s32_max_value = S32_MAX; 2063 reg->u32_min_value = 0; 2064 reg->u32_max_value = U32_MAX; 2065 } 2066 2067 static void __mark_reg64_unbounded(struct bpf_reg_state *reg) 2068 { 2069 reg->smin_value = S64_MIN; 2070 reg->smax_value = S64_MAX; 2071 reg->umin_value = 0; 2072 reg->umax_value = U64_MAX; 2073 } 2074 2075 static void __mark_reg32_unbounded(struct bpf_reg_state *reg) 2076 { 2077 reg->s32_min_value = S32_MIN; 2078 reg->s32_max_value = S32_MAX; 2079 reg->u32_min_value = 0; 2080 reg->u32_max_value = U32_MAX; 2081 } 2082 2083 static void __update_reg32_bounds(struct bpf_reg_state *reg) 2084 { 2085 struct tnum var32_off = tnum_subreg(reg->var_off); 2086 2087 /* min signed is max(sign bit) | min(other bits) */ 2088 reg->s32_min_value = max_t(s32, reg->s32_min_value, 2089 var32_off.value | (var32_off.mask & S32_MIN)); 2090 /* max signed is min(sign bit) | max(other bits) */ 2091 reg->s32_max_value = min_t(s32, reg->s32_max_value, 2092 var32_off.value | (var32_off.mask & S32_MAX)); 2093 reg->u32_min_value = max_t(u32, reg->u32_min_value, (u32)var32_off.value); 2094 reg->u32_max_value = min(reg->u32_max_value, 2095 (u32)(var32_off.value | var32_off.mask)); 2096 } 2097 2098 static void __update_reg64_bounds(struct bpf_reg_state *reg) 2099 { 2100 /* min signed is max(sign bit) | min(other bits) */ 2101 reg->smin_value = max_t(s64, reg->smin_value, 2102 reg->var_off.value | (reg->var_off.mask & S64_MIN)); 2103 /* max signed is min(sign bit) | max(other bits) */ 2104 reg->smax_value = min_t(s64, reg->smax_value, 2105 reg->var_off.value | (reg->var_off.mask & S64_MAX)); 2106 reg->umin_value = max(reg->umin_value, reg->var_off.value); 2107 reg->umax_value = min(reg->umax_value, 2108 reg->var_off.value | reg->var_off.mask); 2109 } 2110 2111 static void __update_reg_bounds(struct bpf_reg_state *reg) 2112 { 2113 __update_reg32_bounds(reg); 2114 __update_reg64_bounds(reg); 2115 } 2116 2117 /* Uses signed min/max values to inform unsigned, and vice-versa */ 2118 static void __reg32_deduce_bounds(struct bpf_reg_state *reg) 2119 { 2120 /* Learn sign from signed bounds. 2121 * If we cannot cross the sign boundary, then signed and unsigned bounds 2122 * are the same, so combine. This works even in the negative case, e.g. 2123 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff. 2124 */ 2125 if (reg->s32_min_value >= 0 || reg->s32_max_value < 0) { 2126 reg->s32_min_value = reg->u32_min_value = 2127 max_t(u32, reg->s32_min_value, reg->u32_min_value); 2128 reg->s32_max_value = reg->u32_max_value = 2129 min_t(u32, reg->s32_max_value, reg->u32_max_value); 2130 return; 2131 } 2132 /* Learn sign from unsigned bounds. Signed bounds cross the sign 2133 * boundary, so we must be careful. 2134 */ 2135 if ((s32)reg->u32_max_value >= 0) { 2136 /* Positive. We can't learn anything from the smin, but smax 2137 * is positive, hence safe. 2138 */ 2139 reg->s32_min_value = reg->u32_min_value; 2140 reg->s32_max_value = reg->u32_max_value = 2141 min_t(u32, reg->s32_max_value, reg->u32_max_value); 2142 } else if ((s32)reg->u32_min_value < 0) { 2143 /* Negative. We can't learn anything from the smax, but smin 2144 * is negative, hence safe. 2145 */ 2146 reg->s32_min_value = reg->u32_min_value = 2147 max_t(u32, reg->s32_min_value, reg->u32_min_value); 2148 reg->s32_max_value = reg->u32_max_value; 2149 } 2150 } 2151 2152 static void __reg64_deduce_bounds(struct bpf_reg_state *reg) 2153 { 2154 /* Learn sign from signed bounds. 2155 * If we cannot cross the sign boundary, then signed and unsigned bounds 2156 * are the same, so combine. This works even in the negative case, e.g. 2157 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff. 2158 */ 2159 if (reg->smin_value >= 0 || reg->smax_value < 0) { 2160 reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value, 2161 reg->umin_value); 2162 reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value, 2163 reg->umax_value); 2164 return; 2165 } 2166 /* Learn sign from unsigned bounds. Signed bounds cross the sign 2167 * boundary, so we must be careful. 2168 */ 2169 if ((s64)reg->umax_value >= 0) { 2170 /* Positive. We can't learn anything from the smin, but smax 2171 * is positive, hence safe. 2172 */ 2173 reg->smin_value = reg->umin_value; 2174 reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value, 2175 reg->umax_value); 2176 } else if ((s64)reg->umin_value < 0) { 2177 /* Negative. We can't learn anything from the smax, but smin 2178 * is negative, hence safe. 2179 */ 2180 reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value, 2181 reg->umin_value); 2182 reg->smax_value = reg->umax_value; 2183 } 2184 } 2185 2186 static void __reg_deduce_bounds(struct bpf_reg_state *reg) 2187 { 2188 __reg32_deduce_bounds(reg); 2189 __reg64_deduce_bounds(reg); 2190 } 2191 2192 /* Attempts to improve var_off based on unsigned min/max information */ 2193 static void __reg_bound_offset(struct bpf_reg_state *reg) 2194 { 2195 struct tnum var64_off = tnum_intersect(reg->var_off, 2196 tnum_range(reg->umin_value, 2197 reg->umax_value)); 2198 struct tnum var32_off = tnum_intersect(tnum_subreg(var64_off), 2199 tnum_range(reg->u32_min_value, 2200 reg->u32_max_value)); 2201 2202 reg->var_off = tnum_or(tnum_clear_subreg(var64_off), var32_off); 2203 } 2204 2205 static void reg_bounds_sync(struct bpf_reg_state *reg) 2206 { 2207 /* We might have learned new bounds from the var_off. */ 2208 __update_reg_bounds(reg); 2209 /* We might have learned something about the sign bit. */ 2210 __reg_deduce_bounds(reg); 2211 /* We might have learned some bits from the bounds. */ 2212 __reg_bound_offset(reg); 2213 /* Intersecting with the old var_off might have improved our bounds 2214 * slightly, e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc), 2215 * then new var_off is (0; 0x7f...fc) which improves our umax. 2216 */ 2217 __update_reg_bounds(reg); 2218 } 2219 2220 static bool __reg32_bound_s64(s32 a) 2221 { 2222 return a >= 0 && a <= S32_MAX; 2223 } 2224 2225 static void __reg_assign_32_into_64(struct bpf_reg_state *reg) 2226 { 2227 reg->umin_value = reg->u32_min_value; 2228 reg->umax_value = reg->u32_max_value; 2229 2230 /* Attempt to pull 32-bit signed bounds into 64-bit bounds but must 2231 * be positive otherwise set to worse case bounds and refine later 2232 * from tnum. 2233 */ 2234 if (__reg32_bound_s64(reg->s32_min_value) && 2235 __reg32_bound_s64(reg->s32_max_value)) { 2236 reg->smin_value = reg->s32_min_value; 2237 reg->smax_value = reg->s32_max_value; 2238 } else { 2239 reg->smin_value = 0; 2240 reg->smax_value = U32_MAX; 2241 } 2242 } 2243 2244 static void __reg_combine_32_into_64(struct bpf_reg_state *reg) 2245 { 2246 /* special case when 64-bit register has upper 32-bit register 2247 * zeroed. Typically happens after zext or <<32, >>32 sequence 2248 * allowing us to use 32-bit bounds directly, 2249 */ 2250 if (tnum_equals_const(tnum_clear_subreg(reg->var_off), 0)) { 2251 __reg_assign_32_into_64(reg); 2252 } else { 2253 /* Otherwise the best we can do is push lower 32bit known and 2254 * unknown bits into register (var_off set from jmp logic) 2255 * then learn as much as possible from the 64-bit tnum 2256 * known and unknown bits. The previous smin/smax bounds are 2257 * invalid here because of jmp32 compare so mark them unknown 2258 * so they do not impact tnum bounds calculation. 2259 */ 2260 __mark_reg64_unbounded(reg); 2261 } 2262 reg_bounds_sync(reg); 2263 } 2264 2265 static bool __reg64_bound_s32(s64 a) 2266 { 2267 return a >= S32_MIN && a <= S32_MAX; 2268 } 2269 2270 static bool __reg64_bound_u32(u64 a) 2271 { 2272 return a >= U32_MIN && a <= U32_MAX; 2273 } 2274 2275 static void __reg_combine_64_into_32(struct bpf_reg_state *reg) 2276 { 2277 __mark_reg32_unbounded(reg); 2278 if (__reg64_bound_s32(reg->smin_value) && __reg64_bound_s32(reg->smax_value)) { 2279 reg->s32_min_value = (s32)reg->smin_value; 2280 reg->s32_max_value = (s32)reg->smax_value; 2281 } 2282 if (__reg64_bound_u32(reg->umin_value) && __reg64_bound_u32(reg->umax_value)) { 2283 reg->u32_min_value = (u32)reg->umin_value; 2284 reg->u32_max_value = (u32)reg->umax_value; 2285 } 2286 reg_bounds_sync(reg); 2287 } 2288 2289 /* Mark a register as having a completely unknown (scalar) value. */ 2290 static void __mark_reg_unknown(const struct bpf_verifier_env *env, 2291 struct bpf_reg_state *reg) 2292 { 2293 /* 2294 * Clear type, off, and union(map_ptr, range) and 2295 * padding between 'type' and union 2296 */ 2297 memset(reg, 0, offsetof(struct bpf_reg_state, var_off)); 2298 reg->type = SCALAR_VALUE; 2299 reg->id = 0; 2300 reg->ref_obj_id = 0; 2301 reg->var_off = tnum_unknown; 2302 reg->frameno = 0; 2303 reg->precise = !env->bpf_capable; 2304 __mark_reg_unbounded(reg); 2305 } 2306 2307 static void mark_reg_unknown(struct bpf_verifier_env *env, 2308 struct bpf_reg_state *regs, u32 regno) 2309 { 2310 if (WARN_ON(regno >= MAX_BPF_REG)) { 2311 verbose(env, "mark_reg_unknown(regs, %u)\n", regno); 2312 /* Something bad happened, let's kill all regs except FP */ 2313 for (regno = 0; regno < BPF_REG_FP; regno++) 2314 __mark_reg_not_init(env, regs + regno); 2315 return; 2316 } 2317 __mark_reg_unknown(env, regs + regno); 2318 } 2319 2320 static void __mark_reg_not_init(const struct bpf_verifier_env *env, 2321 struct bpf_reg_state *reg) 2322 { 2323 __mark_reg_unknown(env, reg); 2324 reg->type = NOT_INIT; 2325 } 2326 2327 static void mark_reg_not_init(struct bpf_verifier_env *env, 2328 struct bpf_reg_state *regs, u32 regno) 2329 { 2330 if (WARN_ON(regno >= MAX_BPF_REG)) { 2331 verbose(env, "mark_reg_not_init(regs, %u)\n", regno); 2332 /* Something bad happened, let's kill all regs except FP */ 2333 for (regno = 0; regno < BPF_REG_FP; regno++) 2334 __mark_reg_not_init(env, regs + regno); 2335 return; 2336 } 2337 __mark_reg_not_init(env, regs + regno); 2338 } 2339 2340 static void mark_btf_ld_reg(struct bpf_verifier_env *env, 2341 struct bpf_reg_state *regs, u32 regno, 2342 enum bpf_reg_type reg_type, 2343 struct btf *btf, u32 btf_id, 2344 enum bpf_type_flag flag) 2345 { 2346 if (reg_type == SCALAR_VALUE) { 2347 mark_reg_unknown(env, regs, regno); 2348 return; 2349 } 2350 mark_reg_known_zero(env, regs, regno); 2351 regs[regno].type = PTR_TO_BTF_ID | flag; 2352 regs[regno].btf = btf; 2353 regs[regno].btf_id = btf_id; 2354 } 2355 2356 #define DEF_NOT_SUBREG (0) 2357 static void init_reg_state(struct bpf_verifier_env *env, 2358 struct bpf_func_state *state) 2359 { 2360 struct bpf_reg_state *regs = state->regs; 2361 int i; 2362 2363 for (i = 0; i < MAX_BPF_REG; i++) { 2364 mark_reg_not_init(env, regs, i); 2365 regs[i].live = REG_LIVE_NONE; 2366 regs[i].parent = NULL; 2367 regs[i].subreg_def = DEF_NOT_SUBREG; 2368 } 2369 2370 /* frame pointer */ 2371 regs[BPF_REG_FP].type = PTR_TO_STACK; 2372 mark_reg_known_zero(env, regs, BPF_REG_FP); 2373 regs[BPF_REG_FP].frameno = state->frameno; 2374 } 2375 2376 #define BPF_MAIN_FUNC (-1) 2377 static void init_func_state(struct bpf_verifier_env *env, 2378 struct bpf_func_state *state, 2379 int callsite, int frameno, int subprogno) 2380 { 2381 state->callsite = callsite; 2382 state->frameno = frameno; 2383 state->subprogno = subprogno; 2384 state->callback_ret_range = tnum_range(0, 0); 2385 init_reg_state(env, state); 2386 mark_verifier_state_scratched(env); 2387 } 2388 2389 /* Similar to push_stack(), but for async callbacks */ 2390 static struct bpf_verifier_state *push_async_cb(struct bpf_verifier_env *env, 2391 int insn_idx, int prev_insn_idx, 2392 int subprog) 2393 { 2394 struct bpf_verifier_stack_elem *elem; 2395 struct bpf_func_state *frame; 2396 2397 elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL); 2398 if (!elem) 2399 goto err; 2400 2401 elem->insn_idx = insn_idx; 2402 elem->prev_insn_idx = prev_insn_idx; 2403 elem->next = env->head; 2404 elem->log_pos = env->log.end_pos; 2405 env->head = elem; 2406 env->stack_size++; 2407 if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) { 2408 verbose(env, 2409 "The sequence of %d jumps is too complex for async cb.\n", 2410 env->stack_size); 2411 goto err; 2412 } 2413 /* Unlike push_stack() do not copy_verifier_state(). 2414 * The caller state doesn't matter. 2415 * This is async callback. It starts in a fresh stack. 2416 * Initialize it similar to do_check_common(). 2417 */ 2418 elem->st.branches = 1; 2419 frame = kzalloc(sizeof(*frame), GFP_KERNEL); 2420 if (!frame) 2421 goto err; 2422 init_func_state(env, frame, 2423 BPF_MAIN_FUNC /* callsite */, 2424 0 /* frameno within this callchain */, 2425 subprog /* subprog number within this prog */); 2426 elem->st.frame[0] = frame; 2427 return &elem->st; 2428 err: 2429 free_verifier_state(env->cur_state, true); 2430 env->cur_state = NULL; 2431 /* pop all elements and return */ 2432 while (!pop_stack(env, NULL, NULL, false)); 2433 return NULL; 2434 } 2435 2436 2437 enum reg_arg_type { 2438 SRC_OP, /* register is used as source operand */ 2439 DST_OP, /* register is used as destination operand */ 2440 DST_OP_NO_MARK /* same as above, check only, don't mark */ 2441 }; 2442 2443 static int cmp_subprogs(const void *a, const void *b) 2444 { 2445 return ((struct bpf_subprog_info *)a)->start - 2446 ((struct bpf_subprog_info *)b)->start; 2447 } 2448 2449 static int find_subprog(struct bpf_verifier_env *env, int off) 2450 { 2451 struct bpf_subprog_info *p; 2452 2453 p = bsearch(&off, env->subprog_info, env->subprog_cnt, 2454 sizeof(env->subprog_info[0]), cmp_subprogs); 2455 if (!p) 2456 return -ENOENT; 2457 return p - env->subprog_info; 2458 2459 } 2460 2461 static int add_subprog(struct bpf_verifier_env *env, int off) 2462 { 2463 int insn_cnt = env->prog->len; 2464 int ret; 2465 2466 if (off >= insn_cnt || off < 0) { 2467 verbose(env, "call to invalid destination\n"); 2468 return -EINVAL; 2469 } 2470 ret = find_subprog(env, off); 2471 if (ret >= 0) 2472 return ret; 2473 if (env->subprog_cnt >= BPF_MAX_SUBPROGS) { 2474 verbose(env, "too many subprograms\n"); 2475 return -E2BIG; 2476 } 2477 /* determine subprog starts. The end is one before the next starts */ 2478 env->subprog_info[env->subprog_cnt++].start = off; 2479 sort(env->subprog_info, env->subprog_cnt, 2480 sizeof(env->subprog_info[0]), cmp_subprogs, NULL); 2481 return env->subprog_cnt - 1; 2482 } 2483 2484 static int bpf_find_exception_callback_insn_off(struct bpf_verifier_env *env) 2485 { 2486 struct bpf_prog_aux *aux = env->prog->aux; 2487 struct btf *btf = aux->btf; 2488 const struct btf_type *t; 2489 u32 main_btf_id, id; 2490 const char *name; 2491 int ret, i; 2492 2493 /* Non-zero func_info_cnt implies valid btf */ 2494 if (!aux->func_info_cnt) 2495 return 0; 2496 main_btf_id = aux->func_info[0].type_id; 2497 2498 t = btf_type_by_id(btf, main_btf_id); 2499 if (!t) { 2500 verbose(env, "invalid btf id for main subprog in func_info\n"); 2501 return -EINVAL; 2502 } 2503 2504 name = btf_find_decl_tag_value(btf, t, -1, "exception_callback:"); 2505 if (IS_ERR(name)) { 2506 ret = PTR_ERR(name); 2507 /* If there is no tag present, there is no exception callback */ 2508 if (ret == -ENOENT) 2509 ret = 0; 2510 else if (ret == -EEXIST) 2511 verbose(env, "multiple exception callback tags for main subprog\n"); 2512 return ret; 2513 } 2514 2515 ret = btf_find_by_name_kind(btf, name, BTF_KIND_FUNC); 2516 if (ret < 0) { 2517 verbose(env, "exception callback '%s' could not be found in BTF\n", name); 2518 return ret; 2519 } 2520 id = ret; 2521 t = btf_type_by_id(btf, id); 2522 if (btf_func_linkage(t) != BTF_FUNC_GLOBAL) { 2523 verbose(env, "exception callback '%s' must have global linkage\n", name); 2524 return -EINVAL; 2525 } 2526 ret = 0; 2527 for (i = 0; i < aux->func_info_cnt; i++) { 2528 if (aux->func_info[i].type_id != id) 2529 continue; 2530 ret = aux->func_info[i].insn_off; 2531 /* Further func_info and subprog checks will also happen 2532 * later, so assume this is the right insn_off for now. 2533 */ 2534 if (!ret) { 2535 verbose(env, "invalid exception callback insn_off in func_info: 0\n"); 2536 ret = -EINVAL; 2537 } 2538 } 2539 if (!ret) { 2540 verbose(env, "exception callback type id not found in func_info\n"); 2541 ret = -EINVAL; 2542 } 2543 return ret; 2544 } 2545 2546 #define MAX_KFUNC_DESCS 256 2547 #define MAX_KFUNC_BTFS 256 2548 2549 struct bpf_kfunc_desc { 2550 struct btf_func_model func_model; 2551 u32 func_id; 2552 s32 imm; 2553 u16 offset; 2554 unsigned long addr; 2555 }; 2556 2557 struct bpf_kfunc_btf { 2558 struct btf *btf; 2559 struct module *module; 2560 u16 offset; 2561 }; 2562 2563 struct bpf_kfunc_desc_tab { 2564 /* Sorted by func_id (BTF ID) and offset (fd_array offset) during 2565 * verification. JITs do lookups by bpf_insn, where func_id may not be 2566 * available, therefore at the end of verification do_misc_fixups() 2567 * sorts this by imm and offset. 2568 */ 2569 struct bpf_kfunc_desc descs[MAX_KFUNC_DESCS]; 2570 u32 nr_descs; 2571 }; 2572 2573 struct bpf_kfunc_btf_tab { 2574 struct bpf_kfunc_btf descs[MAX_KFUNC_BTFS]; 2575 u32 nr_descs; 2576 }; 2577 2578 static int kfunc_desc_cmp_by_id_off(const void *a, const void *b) 2579 { 2580 const struct bpf_kfunc_desc *d0 = a; 2581 const struct bpf_kfunc_desc *d1 = b; 2582 2583 /* func_id is not greater than BTF_MAX_TYPE */ 2584 return d0->func_id - d1->func_id ?: d0->offset - d1->offset; 2585 } 2586 2587 static int kfunc_btf_cmp_by_off(const void *a, const void *b) 2588 { 2589 const struct bpf_kfunc_btf *d0 = a; 2590 const struct bpf_kfunc_btf *d1 = b; 2591 2592 return d0->offset - d1->offset; 2593 } 2594 2595 static const struct bpf_kfunc_desc * 2596 find_kfunc_desc(const struct bpf_prog *prog, u32 func_id, u16 offset) 2597 { 2598 struct bpf_kfunc_desc desc = { 2599 .func_id = func_id, 2600 .offset = offset, 2601 }; 2602 struct bpf_kfunc_desc_tab *tab; 2603 2604 tab = prog->aux->kfunc_tab; 2605 return bsearch(&desc, tab->descs, tab->nr_descs, 2606 sizeof(tab->descs[0]), kfunc_desc_cmp_by_id_off); 2607 } 2608 2609 int bpf_get_kfunc_addr(const struct bpf_prog *prog, u32 func_id, 2610 u16 btf_fd_idx, u8 **func_addr) 2611 { 2612 const struct bpf_kfunc_desc *desc; 2613 2614 desc = find_kfunc_desc(prog, func_id, btf_fd_idx); 2615 if (!desc) 2616 return -EFAULT; 2617 2618 *func_addr = (u8 *)desc->addr; 2619 return 0; 2620 } 2621 2622 static struct btf *__find_kfunc_desc_btf(struct bpf_verifier_env *env, 2623 s16 offset) 2624 { 2625 struct bpf_kfunc_btf kf_btf = { .offset = offset }; 2626 struct bpf_kfunc_btf_tab *tab; 2627 struct bpf_kfunc_btf *b; 2628 struct module *mod; 2629 struct btf *btf; 2630 int btf_fd; 2631 2632 tab = env->prog->aux->kfunc_btf_tab; 2633 b = bsearch(&kf_btf, tab->descs, tab->nr_descs, 2634 sizeof(tab->descs[0]), kfunc_btf_cmp_by_off); 2635 if (!b) { 2636 if (tab->nr_descs == MAX_KFUNC_BTFS) { 2637 verbose(env, "too many different module BTFs\n"); 2638 return ERR_PTR(-E2BIG); 2639 } 2640 2641 if (bpfptr_is_null(env->fd_array)) { 2642 verbose(env, "kfunc offset > 0 without fd_array is invalid\n"); 2643 return ERR_PTR(-EPROTO); 2644 } 2645 2646 if (copy_from_bpfptr_offset(&btf_fd, env->fd_array, 2647 offset * sizeof(btf_fd), 2648 sizeof(btf_fd))) 2649 return ERR_PTR(-EFAULT); 2650 2651 btf = btf_get_by_fd(btf_fd); 2652 if (IS_ERR(btf)) { 2653 verbose(env, "invalid module BTF fd specified\n"); 2654 return btf; 2655 } 2656 2657 if (!btf_is_module(btf)) { 2658 verbose(env, "BTF fd for kfunc is not a module BTF\n"); 2659 btf_put(btf); 2660 return ERR_PTR(-EINVAL); 2661 } 2662 2663 mod = btf_try_get_module(btf); 2664 if (!mod) { 2665 btf_put(btf); 2666 return ERR_PTR(-ENXIO); 2667 } 2668 2669 b = &tab->descs[tab->nr_descs++]; 2670 b->btf = btf; 2671 b->module = mod; 2672 b->offset = offset; 2673 2674 sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]), 2675 kfunc_btf_cmp_by_off, NULL); 2676 } 2677 return b->btf; 2678 } 2679 2680 void bpf_free_kfunc_btf_tab(struct bpf_kfunc_btf_tab *tab) 2681 { 2682 if (!tab) 2683 return; 2684 2685 while (tab->nr_descs--) { 2686 module_put(tab->descs[tab->nr_descs].module); 2687 btf_put(tab->descs[tab->nr_descs].btf); 2688 } 2689 kfree(tab); 2690 } 2691 2692 static struct btf *find_kfunc_desc_btf(struct bpf_verifier_env *env, s16 offset) 2693 { 2694 if (offset) { 2695 if (offset < 0) { 2696 /* In the future, this can be allowed to increase limit 2697 * of fd index into fd_array, interpreted as u16. 2698 */ 2699 verbose(env, "negative offset disallowed for kernel module function call\n"); 2700 return ERR_PTR(-EINVAL); 2701 } 2702 2703 return __find_kfunc_desc_btf(env, offset); 2704 } 2705 return btf_vmlinux ?: ERR_PTR(-ENOENT); 2706 } 2707 2708 static int add_kfunc_call(struct bpf_verifier_env *env, u32 func_id, s16 offset) 2709 { 2710 const struct btf_type *func, *func_proto; 2711 struct bpf_kfunc_btf_tab *btf_tab; 2712 struct bpf_kfunc_desc_tab *tab; 2713 struct bpf_prog_aux *prog_aux; 2714 struct bpf_kfunc_desc *desc; 2715 const char *func_name; 2716 struct btf *desc_btf; 2717 unsigned long call_imm; 2718 unsigned long addr; 2719 int err; 2720 2721 prog_aux = env->prog->aux; 2722 tab = prog_aux->kfunc_tab; 2723 btf_tab = prog_aux->kfunc_btf_tab; 2724 if (!tab) { 2725 if (!btf_vmlinux) { 2726 verbose(env, "calling kernel function is not supported without CONFIG_DEBUG_INFO_BTF\n"); 2727 return -ENOTSUPP; 2728 } 2729 2730 if (!env->prog->jit_requested) { 2731 verbose(env, "JIT is required for calling kernel function\n"); 2732 return -ENOTSUPP; 2733 } 2734 2735 if (!bpf_jit_supports_kfunc_call()) { 2736 verbose(env, "JIT does not support calling kernel function\n"); 2737 return -ENOTSUPP; 2738 } 2739 2740 if (!env->prog->gpl_compatible) { 2741 verbose(env, "cannot call kernel function from non-GPL compatible program\n"); 2742 return -EINVAL; 2743 } 2744 2745 tab = kzalloc(sizeof(*tab), GFP_KERNEL); 2746 if (!tab) 2747 return -ENOMEM; 2748 prog_aux->kfunc_tab = tab; 2749 } 2750 2751 /* func_id == 0 is always invalid, but instead of returning an error, be 2752 * conservative and wait until the code elimination pass before returning 2753 * error, so that invalid calls that get pruned out can be in BPF programs 2754 * loaded from userspace. It is also required that offset be untouched 2755 * for such calls. 2756 */ 2757 if (!func_id && !offset) 2758 return 0; 2759 2760 if (!btf_tab && offset) { 2761 btf_tab = kzalloc(sizeof(*btf_tab), GFP_KERNEL); 2762 if (!btf_tab) 2763 return -ENOMEM; 2764 prog_aux->kfunc_btf_tab = btf_tab; 2765 } 2766 2767 desc_btf = find_kfunc_desc_btf(env, offset); 2768 if (IS_ERR(desc_btf)) { 2769 verbose(env, "failed to find BTF for kernel function\n"); 2770 return PTR_ERR(desc_btf); 2771 } 2772 2773 if (find_kfunc_desc(env->prog, func_id, offset)) 2774 return 0; 2775 2776 if (tab->nr_descs == MAX_KFUNC_DESCS) { 2777 verbose(env, "too many different kernel function calls\n"); 2778 return -E2BIG; 2779 } 2780 2781 func = btf_type_by_id(desc_btf, func_id); 2782 if (!func || !btf_type_is_func(func)) { 2783 verbose(env, "kernel btf_id %u is not a function\n", 2784 func_id); 2785 return -EINVAL; 2786 } 2787 func_proto = btf_type_by_id(desc_btf, func->type); 2788 if (!func_proto || !btf_type_is_func_proto(func_proto)) { 2789 verbose(env, "kernel function btf_id %u does not have a valid func_proto\n", 2790 func_id); 2791 return -EINVAL; 2792 } 2793 2794 func_name = btf_name_by_offset(desc_btf, func->name_off); 2795 addr = kallsyms_lookup_name(func_name); 2796 if (!addr) { 2797 verbose(env, "cannot find address for kernel function %s\n", 2798 func_name); 2799 return -EINVAL; 2800 } 2801 specialize_kfunc(env, func_id, offset, &addr); 2802 2803 if (bpf_jit_supports_far_kfunc_call()) { 2804 call_imm = func_id; 2805 } else { 2806 call_imm = BPF_CALL_IMM(addr); 2807 /* Check whether the relative offset overflows desc->imm */ 2808 if ((unsigned long)(s32)call_imm != call_imm) { 2809 verbose(env, "address of kernel function %s is out of range\n", 2810 func_name); 2811 return -EINVAL; 2812 } 2813 } 2814 2815 if (bpf_dev_bound_kfunc_id(func_id)) { 2816 err = bpf_dev_bound_kfunc_check(&env->log, prog_aux); 2817 if (err) 2818 return err; 2819 } 2820 2821 desc = &tab->descs[tab->nr_descs++]; 2822 desc->func_id = func_id; 2823 desc->imm = call_imm; 2824 desc->offset = offset; 2825 desc->addr = addr; 2826 err = btf_distill_func_proto(&env->log, desc_btf, 2827 func_proto, func_name, 2828 &desc->func_model); 2829 if (!err) 2830 sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]), 2831 kfunc_desc_cmp_by_id_off, NULL); 2832 return err; 2833 } 2834 2835 static int kfunc_desc_cmp_by_imm_off(const void *a, const void *b) 2836 { 2837 const struct bpf_kfunc_desc *d0 = a; 2838 const struct bpf_kfunc_desc *d1 = b; 2839 2840 if (d0->imm != d1->imm) 2841 return d0->imm < d1->imm ? -1 : 1; 2842 if (d0->offset != d1->offset) 2843 return d0->offset < d1->offset ? -1 : 1; 2844 return 0; 2845 } 2846 2847 static void sort_kfunc_descs_by_imm_off(struct bpf_prog *prog) 2848 { 2849 struct bpf_kfunc_desc_tab *tab; 2850 2851 tab = prog->aux->kfunc_tab; 2852 if (!tab) 2853 return; 2854 2855 sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]), 2856 kfunc_desc_cmp_by_imm_off, NULL); 2857 } 2858 2859 bool bpf_prog_has_kfunc_call(const struct bpf_prog *prog) 2860 { 2861 return !!prog->aux->kfunc_tab; 2862 } 2863 2864 const struct btf_func_model * 2865 bpf_jit_find_kfunc_model(const struct bpf_prog *prog, 2866 const struct bpf_insn *insn) 2867 { 2868 const struct bpf_kfunc_desc desc = { 2869 .imm = insn->imm, 2870 .offset = insn->off, 2871 }; 2872 const struct bpf_kfunc_desc *res; 2873 struct bpf_kfunc_desc_tab *tab; 2874 2875 tab = prog->aux->kfunc_tab; 2876 res = bsearch(&desc, tab->descs, tab->nr_descs, 2877 sizeof(tab->descs[0]), kfunc_desc_cmp_by_imm_off); 2878 2879 return res ? &res->func_model : NULL; 2880 } 2881 2882 static int add_subprog_and_kfunc(struct bpf_verifier_env *env) 2883 { 2884 struct bpf_subprog_info *subprog = env->subprog_info; 2885 int i, ret, insn_cnt = env->prog->len, ex_cb_insn; 2886 struct bpf_insn *insn = env->prog->insnsi; 2887 2888 /* Add entry function. */ 2889 ret = add_subprog(env, 0); 2890 if (ret) 2891 return ret; 2892 2893 for (i = 0; i < insn_cnt; i++, insn++) { 2894 if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn) && 2895 !bpf_pseudo_kfunc_call(insn)) 2896 continue; 2897 2898 if (!env->bpf_capable) { 2899 verbose(env, "loading/calling other bpf or kernel functions are allowed for CAP_BPF and CAP_SYS_ADMIN\n"); 2900 return -EPERM; 2901 } 2902 2903 if (bpf_pseudo_func(insn) || bpf_pseudo_call(insn)) 2904 ret = add_subprog(env, i + insn->imm + 1); 2905 else 2906 ret = add_kfunc_call(env, insn->imm, insn->off); 2907 2908 if (ret < 0) 2909 return ret; 2910 } 2911 2912 ret = bpf_find_exception_callback_insn_off(env); 2913 if (ret < 0) 2914 return ret; 2915 ex_cb_insn = ret; 2916 2917 /* If ex_cb_insn > 0, this means that the main program has a subprog 2918 * marked using BTF decl tag to serve as the exception callback. 2919 */ 2920 if (ex_cb_insn) { 2921 ret = add_subprog(env, ex_cb_insn); 2922 if (ret < 0) 2923 return ret; 2924 for (i = 1; i < env->subprog_cnt; i++) { 2925 if (env->subprog_info[i].start != ex_cb_insn) 2926 continue; 2927 env->exception_callback_subprog = i; 2928 break; 2929 } 2930 } 2931 2932 /* Add a fake 'exit' subprog which could simplify subprog iteration 2933 * logic. 'subprog_cnt' should not be increased. 2934 */ 2935 subprog[env->subprog_cnt].start = insn_cnt; 2936 2937 if (env->log.level & BPF_LOG_LEVEL2) 2938 for (i = 0; i < env->subprog_cnt; i++) 2939 verbose(env, "func#%d @%d\n", i, subprog[i].start); 2940 2941 return 0; 2942 } 2943 2944 static int check_subprogs(struct bpf_verifier_env *env) 2945 { 2946 int i, subprog_start, subprog_end, off, cur_subprog = 0; 2947 struct bpf_subprog_info *subprog = env->subprog_info; 2948 struct bpf_insn *insn = env->prog->insnsi; 2949 int insn_cnt = env->prog->len; 2950 2951 /* now check that all jumps are within the same subprog */ 2952 subprog_start = subprog[cur_subprog].start; 2953 subprog_end = subprog[cur_subprog + 1].start; 2954 for (i = 0; i < insn_cnt; i++) { 2955 u8 code = insn[i].code; 2956 2957 if (code == (BPF_JMP | BPF_CALL) && 2958 insn[i].src_reg == 0 && 2959 insn[i].imm == BPF_FUNC_tail_call) 2960 subprog[cur_subprog].has_tail_call = true; 2961 if (BPF_CLASS(code) == BPF_LD && 2962 (BPF_MODE(code) == BPF_ABS || BPF_MODE(code) == BPF_IND)) 2963 subprog[cur_subprog].has_ld_abs = true; 2964 if (BPF_CLASS(code) != BPF_JMP && BPF_CLASS(code) != BPF_JMP32) 2965 goto next; 2966 if (BPF_OP(code) == BPF_EXIT || BPF_OP(code) == BPF_CALL) 2967 goto next; 2968 if (code == (BPF_JMP32 | BPF_JA)) 2969 off = i + insn[i].imm + 1; 2970 else 2971 off = i + insn[i].off + 1; 2972 if (off < subprog_start || off >= subprog_end) { 2973 verbose(env, "jump out of range from insn %d to %d\n", i, off); 2974 return -EINVAL; 2975 } 2976 next: 2977 if (i == subprog_end - 1) { 2978 /* to avoid fall-through from one subprog into another 2979 * the last insn of the subprog should be either exit 2980 * or unconditional jump back or bpf_throw call 2981 */ 2982 if (code != (BPF_JMP | BPF_EXIT) && 2983 code != (BPF_JMP32 | BPF_JA) && 2984 code != (BPF_JMP | BPF_JA)) { 2985 verbose(env, "last insn is not an exit or jmp\n"); 2986 return -EINVAL; 2987 } 2988 subprog_start = subprog_end; 2989 cur_subprog++; 2990 if (cur_subprog < env->subprog_cnt) 2991 subprog_end = subprog[cur_subprog + 1].start; 2992 } 2993 } 2994 return 0; 2995 } 2996 2997 /* Parentage chain of this register (or stack slot) should take care of all 2998 * issues like callee-saved registers, stack slot allocation time, etc. 2999 */ 3000 static int mark_reg_read(struct bpf_verifier_env *env, 3001 const struct bpf_reg_state *state, 3002 struct bpf_reg_state *parent, u8 flag) 3003 { 3004 bool writes = parent == state->parent; /* Observe write marks */ 3005 int cnt = 0; 3006 3007 while (parent) { 3008 /* if read wasn't screened by an earlier write ... */ 3009 if (writes && state->live & REG_LIVE_WRITTEN) 3010 break; 3011 if (parent->live & REG_LIVE_DONE) { 3012 verbose(env, "verifier BUG type %s var_off %lld off %d\n", 3013 reg_type_str(env, parent->type), 3014 parent->var_off.value, parent->off); 3015 return -EFAULT; 3016 } 3017 /* The first condition is more likely to be true than the 3018 * second, checked it first. 3019 */ 3020 if ((parent->live & REG_LIVE_READ) == flag || 3021 parent->live & REG_LIVE_READ64) 3022 /* The parentage chain never changes and 3023 * this parent was already marked as LIVE_READ. 3024 * There is no need to keep walking the chain again and 3025 * keep re-marking all parents as LIVE_READ. 3026 * This case happens when the same register is read 3027 * multiple times without writes into it in-between. 3028 * Also, if parent has the stronger REG_LIVE_READ64 set, 3029 * then no need to set the weak REG_LIVE_READ32. 3030 */ 3031 break; 3032 /* ... then we depend on parent's value */ 3033 parent->live |= flag; 3034 /* REG_LIVE_READ64 overrides REG_LIVE_READ32. */ 3035 if (flag == REG_LIVE_READ64) 3036 parent->live &= ~REG_LIVE_READ32; 3037 state = parent; 3038 parent = state->parent; 3039 writes = true; 3040 cnt++; 3041 } 3042 3043 if (env->longest_mark_read_walk < cnt) 3044 env->longest_mark_read_walk = cnt; 3045 return 0; 3046 } 3047 3048 static int mark_dynptr_read(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 3049 { 3050 struct bpf_func_state *state = func(env, reg); 3051 int spi, ret; 3052 3053 /* For CONST_PTR_TO_DYNPTR, it must have already been done by 3054 * check_reg_arg in check_helper_call and mark_btf_func_reg_size in 3055 * check_kfunc_call. 3056 */ 3057 if (reg->type == CONST_PTR_TO_DYNPTR) 3058 return 0; 3059 spi = dynptr_get_spi(env, reg); 3060 if (spi < 0) 3061 return spi; 3062 /* Caller ensures dynptr is valid and initialized, which means spi is in 3063 * bounds and spi is the first dynptr slot. Simply mark stack slot as 3064 * read. 3065 */ 3066 ret = mark_reg_read(env, &state->stack[spi].spilled_ptr, 3067 state->stack[spi].spilled_ptr.parent, REG_LIVE_READ64); 3068 if (ret) 3069 return ret; 3070 return mark_reg_read(env, &state->stack[spi - 1].spilled_ptr, 3071 state->stack[spi - 1].spilled_ptr.parent, REG_LIVE_READ64); 3072 } 3073 3074 static int mark_iter_read(struct bpf_verifier_env *env, struct bpf_reg_state *reg, 3075 int spi, int nr_slots) 3076 { 3077 struct bpf_func_state *state = func(env, reg); 3078 int err, i; 3079 3080 for (i = 0; i < nr_slots; i++) { 3081 struct bpf_reg_state *st = &state->stack[spi - i].spilled_ptr; 3082 3083 err = mark_reg_read(env, st, st->parent, REG_LIVE_READ64); 3084 if (err) 3085 return err; 3086 3087 mark_stack_slot_scratched(env, spi - i); 3088 } 3089 3090 return 0; 3091 } 3092 3093 /* This function is supposed to be used by the following 32-bit optimization 3094 * code only. It returns TRUE if the source or destination register operates 3095 * on 64-bit, otherwise return FALSE. 3096 */ 3097 static bool is_reg64(struct bpf_verifier_env *env, struct bpf_insn *insn, 3098 u32 regno, struct bpf_reg_state *reg, enum reg_arg_type t) 3099 { 3100 u8 code, class, op; 3101 3102 code = insn->code; 3103 class = BPF_CLASS(code); 3104 op = BPF_OP(code); 3105 if (class == BPF_JMP) { 3106 /* BPF_EXIT for "main" will reach here. Return TRUE 3107 * conservatively. 3108 */ 3109 if (op == BPF_EXIT) 3110 return true; 3111 if (op == BPF_CALL) { 3112 /* BPF to BPF call will reach here because of marking 3113 * caller saved clobber with DST_OP_NO_MARK for which we 3114 * don't care the register def because they are anyway 3115 * marked as NOT_INIT already. 3116 */ 3117 if (insn->src_reg == BPF_PSEUDO_CALL) 3118 return false; 3119 /* Helper call will reach here because of arg type 3120 * check, conservatively return TRUE. 3121 */ 3122 if (t == SRC_OP) 3123 return true; 3124 3125 return false; 3126 } 3127 } 3128 3129 if (class == BPF_ALU64 && op == BPF_END && (insn->imm == 16 || insn->imm == 32)) 3130 return false; 3131 3132 if (class == BPF_ALU64 || class == BPF_JMP || 3133 (class == BPF_ALU && op == BPF_END && insn->imm == 64)) 3134 return true; 3135 3136 if (class == BPF_ALU || class == BPF_JMP32) 3137 return false; 3138 3139 if (class == BPF_LDX) { 3140 if (t != SRC_OP) 3141 return BPF_SIZE(code) == BPF_DW || BPF_MODE(code) == BPF_MEMSX; 3142 /* LDX source must be ptr. */ 3143 return true; 3144 } 3145 3146 if (class == BPF_STX) { 3147 /* BPF_STX (including atomic variants) has multiple source 3148 * operands, one of which is a ptr. Check whether the caller is 3149 * asking about it. 3150 */ 3151 if (t == SRC_OP && reg->type != SCALAR_VALUE) 3152 return true; 3153 return BPF_SIZE(code) == BPF_DW; 3154 } 3155 3156 if (class == BPF_LD) { 3157 u8 mode = BPF_MODE(code); 3158 3159 /* LD_IMM64 */ 3160 if (mode == BPF_IMM) 3161 return true; 3162 3163 /* Both LD_IND and LD_ABS return 32-bit data. */ 3164 if (t != SRC_OP) 3165 return false; 3166 3167 /* Implicit ctx ptr. */ 3168 if (regno == BPF_REG_6) 3169 return true; 3170 3171 /* Explicit source could be any width. */ 3172 return true; 3173 } 3174 3175 if (class == BPF_ST) 3176 /* The only source register for BPF_ST is a ptr. */ 3177 return true; 3178 3179 /* Conservatively return true at default. */ 3180 return true; 3181 } 3182 3183 /* Return the regno defined by the insn, or -1. */ 3184 static int insn_def_regno(const struct bpf_insn *insn) 3185 { 3186 switch (BPF_CLASS(insn->code)) { 3187 case BPF_JMP: 3188 case BPF_JMP32: 3189 case BPF_ST: 3190 return -1; 3191 case BPF_STX: 3192 if (BPF_MODE(insn->code) == BPF_ATOMIC && 3193 (insn->imm & BPF_FETCH)) { 3194 if (insn->imm == BPF_CMPXCHG) 3195 return BPF_REG_0; 3196 else 3197 return insn->src_reg; 3198 } else { 3199 return -1; 3200 } 3201 default: 3202 return insn->dst_reg; 3203 } 3204 } 3205 3206 /* Return TRUE if INSN has defined any 32-bit value explicitly. */ 3207 static bool insn_has_def32(struct bpf_verifier_env *env, struct bpf_insn *insn) 3208 { 3209 int dst_reg = insn_def_regno(insn); 3210 3211 if (dst_reg == -1) 3212 return false; 3213 3214 return !is_reg64(env, insn, dst_reg, NULL, DST_OP); 3215 } 3216 3217 static void mark_insn_zext(struct bpf_verifier_env *env, 3218 struct bpf_reg_state *reg) 3219 { 3220 s32 def_idx = reg->subreg_def; 3221 3222 if (def_idx == DEF_NOT_SUBREG) 3223 return; 3224 3225 env->insn_aux_data[def_idx - 1].zext_dst = true; 3226 /* The dst will be zero extended, so won't be sub-register anymore. */ 3227 reg->subreg_def = DEF_NOT_SUBREG; 3228 } 3229 3230 static int check_reg_arg(struct bpf_verifier_env *env, u32 regno, 3231 enum reg_arg_type t) 3232 { 3233 struct bpf_verifier_state *vstate = env->cur_state; 3234 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 3235 struct bpf_insn *insn = env->prog->insnsi + env->insn_idx; 3236 struct bpf_reg_state *reg, *regs = state->regs; 3237 bool rw64; 3238 3239 if (regno >= MAX_BPF_REG) { 3240 verbose(env, "R%d is invalid\n", regno); 3241 return -EINVAL; 3242 } 3243 3244 mark_reg_scratched(env, regno); 3245 3246 reg = ®s[regno]; 3247 rw64 = is_reg64(env, insn, regno, reg, t); 3248 if (t == SRC_OP) { 3249 /* check whether register used as source operand can be read */ 3250 if (reg->type == NOT_INIT) { 3251 verbose(env, "R%d !read_ok\n", regno); 3252 return -EACCES; 3253 } 3254 /* We don't need to worry about FP liveness because it's read-only */ 3255 if (regno == BPF_REG_FP) 3256 return 0; 3257 3258 if (rw64) 3259 mark_insn_zext(env, reg); 3260 3261 return mark_reg_read(env, reg, reg->parent, 3262 rw64 ? REG_LIVE_READ64 : REG_LIVE_READ32); 3263 } else { 3264 /* check whether register used as dest operand can be written to */ 3265 if (regno == BPF_REG_FP) { 3266 verbose(env, "frame pointer is read only\n"); 3267 return -EACCES; 3268 } 3269 reg->live |= REG_LIVE_WRITTEN; 3270 reg->subreg_def = rw64 ? DEF_NOT_SUBREG : env->insn_idx + 1; 3271 if (t == DST_OP) 3272 mark_reg_unknown(env, regs, regno); 3273 } 3274 return 0; 3275 } 3276 3277 static void mark_jmp_point(struct bpf_verifier_env *env, int idx) 3278 { 3279 env->insn_aux_data[idx].jmp_point = true; 3280 } 3281 3282 static bool is_jmp_point(struct bpf_verifier_env *env, int insn_idx) 3283 { 3284 return env->insn_aux_data[insn_idx].jmp_point; 3285 } 3286 3287 /* for any branch, call, exit record the history of jmps in the given state */ 3288 static int push_jmp_history(struct bpf_verifier_env *env, 3289 struct bpf_verifier_state *cur) 3290 { 3291 u32 cnt = cur->jmp_history_cnt; 3292 struct bpf_idx_pair *p; 3293 size_t alloc_size; 3294 3295 if (!is_jmp_point(env, env->insn_idx)) 3296 return 0; 3297 3298 cnt++; 3299 alloc_size = kmalloc_size_roundup(size_mul(cnt, sizeof(*p))); 3300 p = krealloc(cur->jmp_history, alloc_size, GFP_USER); 3301 if (!p) 3302 return -ENOMEM; 3303 p[cnt - 1].idx = env->insn_idx; 3304 p[cnt - 1].prev_idx = env->prev_insn_idx; 3305 cur->jmp_history = p; 3306 cur->jmp_history_cnt = cnt; 3307 return 0; 3308 } 3309 3310 /* Backtrack one insn at a time. If idx is not at the top of recorded 3311 * history then previous instruction came from straight line execution. 3312 */ 3313 static int get_prev_insn_idx(struct bpf_verifier_state *st, int i, 3314 u32 *history) 3315 { 3316 u32 cnt = *history; 3317 3318 if (cnt && st->jmp_history[cnt - 1].idx == i) { 3319 i = st->jmp_history[cnt - 1].prev_idx; 3320 (*history)--; 3321 } else { 3322 i--; 3323 } 3324 return i; 3325 } 3326 3327 static const char *disasm_kfunc_name(void *data, const struct bpf_insn *insn) 3328 { 3329 const struct btf_type *func; 3330 struct btf *desc_btf; 3331 3332 if (insn->src_reg != BPF_PSEUDO_KFUNC_CALL) 3333 return NULL; 3334 3335 desc_btf = find_kfunc_desc_btf(data, insn->off); 3336 if (IS_ERR(desc_btf)) 3337 return "<error>"; 3338 3339 func = btf_type_by_id(desc_btf, insn->imm); 3340 return btf_name_by_offset(desc_btf, func->name_off); 3341 } 3342 3343 static inline void bt_init(struct backtrack_state *bt, u32 frame) 3344 { 3345 bt->frame = frame; 3346 } 3347 3348 static inline void bt_reset(struct backtrack_state *bt) 3349 { 3350 struct bpf_verifier_env *env = bt->env; 3351 3352 memset(bt, 0, sizeof(*bt)); 3353 bt->env = env; 3354 } 3355 3356 static inline u32 bt_empty(struct backtrack_state *bt) 3357 { 3358 u64 mask = 0; 3359 int i; 3360 3361 for (i = 0; i <= bt->frame; i++) 3362 mask |= bt->reg_masks[i] | bt->stack_masks[i]; 3363 3364 return mask == 0; 3365 } 3366 3367 static inline int bt_subprog_enter(struct backtrack_state *bt) 3368 { 3369 if (bt->frame == MAX_CALL_FRAMES - 1) { 3370 verbose(bt->env, "BUG subprog enter from frame %d\n", bt->frame); 3371 WARN_ONCE(1, "verifier backtracking bug"); 3372 return -EFAULT; 3373 } 3374 bt->frame++; 3375 return 0; 3376 } 3377 3378 static inline int bt_subprog_exit(struct backtrack_state *bt) 3379 { 3380 if (bt->frame == 0) { 3381 verbose(bt->env, "BUG subprog exit from frame 0\n"); 3382 WARN_ONCE(1, "verifier backtracking bug"); 3383 return -EFAULT; 3384 } 3385 bt->frame--; 3386 return 0; 3387 } 3388 3389 static inline void bt_set_frame_reg(struct backtrack_state *bt, u32 frame, u32 reg) 3390 { 3391 bt->reg_masks[frame] |= 1 << reg; 3392 } 3393 3394 static inline void bt_clear_frame_reg(struct backtrack_state *bt, u32 frame, u32 reg) 3395 { 3396 bt->reg_masks[frame] &= ~(1 << reg); 3397 } 3398 3399 static inline void bt_set_reg(struct backtrack_state *bt, u32 reg) 3400 { 3401 bt_set_frame_reg(bt, bt->frame, reg); 3402 } 3403 3404 static inline void bt_clear_reg(struct backtrack_state *bt, u32 reg) 3405 { 3406 bt_clear_frame_reg(bt, bt->frame, reg); 3407 } 3408 3409 static inline void bt_set_frame_slot(struct backtrack_state *bt, u32 frame, u32 slot) 3410 { 3411 bt->stack_masks[frame] |= 1ull << slot; 3412 } 3413 3414 static inline void bt_clear_frame_slot(struct backtrack_state *bt, u32 frame, u32 slot) 3415 { 3416 bt->stack_masks[frame] &= ~(1ull << slot); 3417 } 3418 3419 static inline void bt_set_slot(struct backtrack_state *bt, u32 slot) 3420 { 3421 bt_set_frame_slot(bt, bt->frame, slot); 3422 } 3423 3424 static inline void bt_clear_slot(struct backtrack_state *bt, u32 slot) 3425 { 3426 bt_clear_frame_slot(bt, bt->frame, slot); 3427 } 3428 3429 static inline u32 bt_frame_reg_mask(struct backtrack_state *bt, u32 frame) 3430 { 3431 return bt->reg_masks[frame]; 3432 } 3433 3434 static inline u32 bt_reg_mask(struct backtrack_state *bt) 3435 { 3436 return bt->reg_masks[bt->frame]; 3437 } 3438 3439 static inline u64 bt_frame_stack_mask(struct backtrack_state *bt, u32 frame) 3440 { 3441 return bt->stack_masks[frame]; 3442 } 3443 3444 static inline u64 bt_stack_mask(struct backtrack_state *bt) 3445 { 3446 return bt->stack_masks[bt->frame]; 3447 } 3448 3449 static inline bool bt_is_reg_set(struct backtrack_state *bt, u32 reg) 3450 { 3451 return bt->reg_masks[bt->frame] & (1 << reg); 3452 } 3453 3454 static inline bool bt_is_slot_set(struct backtrack_state *bt, u32 slot) 3455 { 3456 return bt->stack_masks[bt->frame] & (1ull << slot); 3457 } 3458 3459 /* format registers bitmask, e.g., "r0,r2,r4" for 0x15 mask */ 3460 static void fmt_reg_mask(char *buf, ssize_t buf_sz, u32 reg_mask) 3461 { 3462 DECLARE_BITMAP(mask, 64); 3463 bool first = true; 3464 int i, n; 3465 3466 buf[0] = '\0'; 3467 3468 bitmap_from_u64(mask, reg_mask); 3469 for_each_set_bit(i, mask, 32) { 3470 n = snprintf(buf, buf_sz, "%sr%d", first ? "" : ",", i); 3471 first = false; 3472 buf += n; 3473 buf_sz -= n; 3474 if (buf_sz < 0) 3475 break; 3476 } 3477 } 3478 /* format stack slots bitmask, e.g., "-8,-24,-40" for 0x15 mask */ 3479 static void fmt_stack_mask(char *buf, ssize_t buf_sz, u64 stack_mask) 3480 { 3481 DECLARE_BITMAP(mask, 64); 3482 bool first = true; 3483 int i, n; 3484 3485 buf[0] = '\0'; 3486 3487 bitmap_from_u64(mask, stack_mask); 3488 for_each_set_bit(i, mask, 64) { 3489 n = snprintf(buf, buf_sz, "%s%d", first ? "" : ",", -(i + 1) * 8); 3490 first = false; 3491 buf += n; 3492 buf_sz -= n; 3493 if (buf_sz < 0) 3494 break; 3495 } 3496 } 3497 3498 /* For given verifier state backtrack_insn() is called from the last insn to 3499 * the first insn. Its purpose is to compute a bitmask of registers and 3500 * stack slots that needs precision in the parent verifier state. 3501 * 3502 * @idx is an index of the instruction we are currently processing; 3503 * @subseq_idx is an index of the subsequent instruction that: 3504 * - *would be* executed next, if jump history is viewed in forward order; 3505 * - *was* processed previously during backtracking. 3506 */ 3507 static int backtrack_insn(struct bpf_verifier_env *env, int idx, int subseq_idx, 3508 struct backtrack_state *bt) 3509 { 3510 const struct bpf_insn_cbs cbs = { 3511 .cb_call = disasm_kfunc_name, 3512 .cb_print = verbose, 3513 .private_data = env, 3514 }; 3515 struct bpf_insn *insn = env->prog->insnsi + idx; 3516 u8 class = BPF_CLASS(insn->code); 3517 u8 opcode = BPF_OP(insn->code); 3518 u8 mode = BPF_MODE(insn->code); 3519 u32 dreg = insn->dst_reg; 3520 u32 sreg = insn->src_reg; 3521 u32 spi, i; 3522 3523 if (insn->code == 0) 3524 return 0; 3525 if (env->log.level & BPF_LOG_LEVEL2) { 3526 fmt_reg_mask(env->tmp_str_buf, TMP_STR_BUF_LEN, bt_reg_mask(bt)); 3527 verbose(env, "mark_precise: frame%d: regs=%s ", 3528 bt->frame, env->tmp_str_buf); 3529 fmt_stack_mask(env->tmp_str_buf, TMP_STR_BUF_LEN, bt_stack_mask(bt)); 3530 verbose(env, "stack=%s before ", env->tmp_str_buf); 3531 verbose(env, "%d: ", idx); 3532 print_bpf_insn(&cbs, insn, env->allow_ptr_leaks); 3533 } 3534 3535 if (class == BPF_ALU || class == BPF_ALU64) { 3536 if (!bt_is_reg_set(bt, dreg)) 3537 return 0; 3538 if (opcode == BPF_MOV) { 3539 if (BPF_SRC(insn->code) == BPF_X) { 3540 /* dreg = sreg or dreg = (s8, s16, s32)sreg 3541 * dreg needs precision after this insn 3542 * sreg needs precision before this insn 3543 */ 3544 bt_clear_reg(bt, dreg); 3545 bt_set_reg(bt, sreg); 3546 } else { 3547 /* dreg = K 3548 * dreg needs precision after this insn. 3549 * Corresponding register is already marked 3550 * as precise=true in this verifier state. 3551 * No further markings in parent are necessary 3552 */ 3553 bt_clear_reg(bt, dreg); 3554 } 3555 } else { 3556 if (BPF_SRC(insn->code) == BPF_X) { 3557 /* dreg += sreg 3558 * both dreg and sreg need precision 3559 * before this insn 3560 */ 3561 bt_set_reg(bt, sreg); 3562 } /* else dreg += K 3563 * dreg still needs precision before this insn 3564 */ 3565 } 3566 } else if (class == BPF_LDX) { 3567 if (!bt_is_reg_set(bt, dreg)) 3568 return 0; 3569 bt_clear_reg(bt, dreg); 3570 3571 /* scalars can only be spilled into stack w/o losing precision. 3572 * Load from any other memory can be zero extended. 3573 * The desire to keep that precision is already indicated 3574 * by 'precise' mark in corresponding register of this state. 3575 * No further tracking necessary. 3576 */ 3577 if (insn->src_reg != BPF_REG_FP) 3578 return 0; 3579 3580 /* dreg = *(u64 *)[fp - off] was a fill from the stack. 3581 * that [fp - off] slot contains scalar that needs to be 3582 * tracked with precision 3583 */ 3584 spi = (-insn->off - 1) / BPF_REG_SIZE; 3585 if (spi >= 64) { 3586 verbose(env, "BUG spi %d\n", spi); 3587 WARN_ONCE(1, "verifier backtracking bug"); 3588 return -EFAULT; 3589 } 3590 bt_set_slot(bt, spi); 3591 } else if (class == BPF_STX || class == BPF_ST) { 3592 if (bt_is_reg_set(bt, dreg)) 3593 /* stx & st shouldn't be using _scalar_ dst_reg 3594 * to access memory. It means backtracking 3595 * encountered a case of pointer subtraction. 3596 */ 3597 return -ENOTSUPP; 3598 /* scalars can only be spilled into stack */ 3599 if (insn->dst_reg != BPF_REG_FP) 3600 return 0; 3601 spi = (-insn->off - 1) / BPF_REG_SIZE; 3602 if (spi >= 64) { 3603 verbose(env, "BUG spi %d\n", spi); 3604 WARN_ONCE(1, "verifier backtracking bug"); 3605 return -EFAULT; 3606 } 3607 if (!bt_is_slot_set(bt, spi)) 3608 return 0; 3609 bt_clear_slot(bt, spi); 3610 if (class == BPF_STX) 3611 bt_set_reg(bt, sreg); 3612 } else if (class == BPF_JMP || class == BPF_JMP32) { 3613 if (bpf_pseudo_call(insn)) { 3614 int subprog_insn_idx, subprog; 3615 3616 subprog_insn_idx = idx + insn->imm + 1; 3617 subprog = find_subprog(env, subprog_insn_idx); 3618 if (subprog < 0) 3619 return -EFAULT; 3620 3621 if (subprog_is_global(env, subprog)) { 3622 /* check that jump history doesn't have any 3623 * extra instructions from subprog; the next 3624 * instruction after call to global subprog 3625 * should be literally next instruction in 3626 * caller program 3627 */ 3628 WARN_ONCE(idx + 1 != subseq_idx, "verifier backtracking bug"); 3629 /* r1-r5 are invalidated after subprog call, 3630 * so for global func call it shouldn't be set 3631 * anymore 3632 */ 3633 if (bt_reg_mask(bt) & BPF_REGMASK_ARGS) { 3634 verbose(env, "BUG regs %x\n", bt_reg_mask(bt)); 3635 WARN_ONCE(1, "verifier backtracking bug"); 3636 return -EFAULT; 3637 } 3638 /* global subprog always sets R0 */ 3639 bt_clear_reg(bt, BPF_REG_0); 3640 return 0; 3641 } else { 3642 /* static subprog call instruction, which 3643 * means that we are exiting current subprog, 3644 * so only r1-r5 could be still requested as 3645 * precise, r0 and r6-r10 or any stack slot in 3646 * the current frame should be zero by now 3647 */ 3648 if (bt_reg_mask(bt) & ~BPF_REGMASK_ARGS) { 3649 verbose(env, "BUG regs %x\n", bt_reg_mask(bt)); 3650 WARN_ONCE(1, "verifier backtracking bug"); 3651 return -EFAULT; 3652 } 3653 /* we don't track register spills perfectly, 3654 * so fallback to force-precise instead of failing */ 3655 if (bt_stack_mask(bt) != 0) 3656 return -ENOTSUPP; 3657 /* propagate r1-r5 to the caller */ 3658 for (i = BPF_REG_1; i <= BPF_REG_5; i++) { 3659 if (bt_is_reg_set(bt, i)) { 3660 bt_clear_reg(bt, i); 3661 bt_set_frame_reg(bt, bt->frame - 1, i); 3662 } 3663 } 3664 if (bt_subprog_exit(bt)) 3665 return -EFAULT; 3666 return 0; 3667 } 3668 } else if ((bpf_helper_call(insn) && 3669 is_callback_calling_function(insn->imm) && 3670 !is_async_callback_calling_function(insn->imm)) || 3671 (bpf_pseudo_kfunc_call(insn) && is_callback_calling_kfunc(insn->imm))) { 3672 /* callback-calling helper or kfunc call, which means 3673 * we are exiting from subprog, but unlike the subprog 3674 * call handling above, we shouldn't propagate 3675 * precision of r1-r5 (if any requested), as they are 3676 * not actually arguments passed directly to callback 3677 * subprogs 3678 */ 3679 if (bt_reg_mask(bt) & ~BPF_REGMASK_ARGS) { 3680 verbose(env, "BUG regs %x\n", bt_reg_mask(bt)); 3681 WARN_ONCE(1, "verifier backtracking bug"); 3682 return -EFAULT; 3683 } 3684 if (bt_stack_mask(bt) != 0) 3685 return -ENOTSUPP; 3686 /* clear r1-r5 in callback subprog's mask */ 3687 for (i = BPF_REG_1; i <= BPF_REG_5; i++) 3688 bt_clear_reg(bt, i); 3689 if (bt_subprog_exit(bt)) 3690 return -EFAULT; 3691 return 0; 3692 } else if (opcode == BPF_CALL) { 3693 /* kfunc with imm==0 is invalid and fixup_kfunc_call will 3694 * catch this error later. Make backtracking conservative 3695 * with ENOTSUPP. 3696 */ 3697 if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL && insn->imm == 0) 3698 return -ENOTSUPP; 3699 /* regular helper call sets R0 */ 3700 bt_clear_reg(bt, BPF_REG_0); 3701 if (bt_reg_mask(bt) & BPF_REGMASK_ARGS) { 3702 /* if backtracing was looking for registers R1-R5 3703 * they should have been found already. 3704 */ 3705 verbose(env, "BUG regs %x\n", bt_reg_mask(bt)); 3706 WARN_ONCE(1, "verifier backtracking bug"); 3707 return -EFAULT; 3708 } 3709 } else if (opcode == BPF_EXIT) { 3710 bool r0_precise; 3711 3712 if (bt_reg_mask(bt) & BPF_REGMASK_ARGS) { 3713 /* if backtracing was looking for registers R1-R5 3714 * they should have been found already. 3715 */ 3716 verbose(env, "BUG regs %x\n", bt_reg_mask(bt)); 3717 WARN_ONCE(1, "verifier backtracking bug"); 3718 return -EFAULT; 3719 } 3720 3721 /* BPF_EXIT in subprog or callback always returns 3722 * right after the call instruction, so by checking 3723 * whether the instruction at subseq_idx-1 is subprog 3724 * call or not we can distinguish actual exit from 3725 * *subprog* from exit from *callback*. In the former 3726 * case, we need to propagate r0 precision, if 3727 * necessary. In the former we never do that. 3728 */ 3729 r0_precise = subseq_idx - 1 >= 0 && 3730 bpf_pseudo_call(&env->prog->insnsi[subseq_idx - 1]) && 3731 bt_is_reg_set(bt, BPF_REG_0); 3732 3733 bt_clear_reg(bt, BPF_REG_0); 3734 if (bt_subprog_enter(bt)) 3735 return -EFAULT; 3736 3737 if (r0_precise) 3738 bt_set_reg(bt, BPF_REG_0); 3739 /* r6-r9 and stack slots will stay set in caller frame 3740 * bitmasks until we return back from callee(s) 3741 */ 3742 return 0; 3743 } else if (BPF_SRC(insn->code) == BPF_X) { 3744 if (!bt_is_reg_set(bt, dreg) && !bt_is_reg_set(bt, sreg)) 3745 return 0; 3746 /* dreg <cond> sreg 3747 * Both dreg and sreg need precision before 3748 * this insn. If only sreg was marked precise 3749 * before it would be equally necessary to 3750 * propagate it to dreg. 3751 */ 3752 bt_set_reg(bt, dreg); 3753 bt_set_reg(bt, sreg); 3754 /* else dreg <cond> K 3755 * Only dreg still needs precision before 3756 * this insn, so for the K-based conditional 3757 * there is nothing new to be marked. 3758 */ 3759 } 3760 } else if (class == BPF_LD) { 3761 if (!bt_is_reg_set(bt, dreg)) 3762 return 0; 3763 bt_clear_reg(bt, dreg); 3764 /* It's ld_imm64 or ld_abs or ld_ind. 3765 * For ld_imm64 no further tracking of precision 3766 * into parent is necessary 3767 */ 3768 if (mode == BPF_IND || mode == BPF_ABS) 3769 /* to be analyzed */ 3770 return -ENOTSUPP; 3771 } 3772 return 0; 3773 } 3774 3775 /* the scalar precision tracking algorithm: 3776 * . at the start all registers have precise=false. 3777 * . scalar ranges are tracked as normal through alu and jmp insns. 3778 * . once precise value of the scalar register is used in: 3779 * . ptr + scalar alu 3780 * . if (scalar cond K|scalar) 3781 * . helper_call(.., scalar, ...) where ARG_CONST is expected 3782 * backtrack through the verifier states and mark all registers and 3783 * stack slots with spilled constants that these scalar regisers 3784 * should be precise. 3785 * . during state pruning two registers (or spilled stack slots) 3786 * are equivalent if both are not precise. 3787 * 3788 * Note the verifier cannot simply walk register parentage chain, 3789 * since many different registers and stack slots could have been 3790 * used to compute single precise scalar. 3791 * 3792 * The approach of starting with precise=true for all registers and then 3793 * backtrack to mark a register as not precise when the verifier detects 3794 * that program doesn't care about specific value (e.g., when helper 3795 * takes register as ARG_ANYTHING parameter) is not safe. 3796 * 3797 * It's ok to walk single parentage chain of the verifier states. 3798 * It's possible that this backtracking will go all the way till 1st insn. 3799 * All other branches will be explored for needing precision later. 3800 * 3801 * The backtracking needs to deal with cases like: 3802 * 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) 3803 * r9 -= r8 3804 * r5 = r9 3805 * if r5 > 0x79f goto pc+7 3806 * R5_w=inv(id=0,umax_value=1951,var_off=(0x0; 0x7ff)) 3807 * r5 += 1 3808 * ... 3809 * call bpf_perf_event_output#25 3810 * where .arg5_type = ARG_CONST_SIZE_OR_ZERO 3811 * 3812 * and this case: 3813 * r6 = 1 3814 * call foo // uses callee's r6 inside to compute r0 3815 * r0 += r6 3816 * if r0 == 0 goto 3817 * 3818 * to track above reg_mask/stack_mask needs to be independent for each frame. 3819 * 3820 * Also if parent's curframe > frame where backtracking started, 3821 * the verifier need to mark registers in both frames, otherwise callees 3822 * may incorrectly prune callers. This is similar to 3823 * commit 7640ead93924 ("bpf: verifier: make sure callees don't prune with caller differences") 3824 * 3825 * For now backtracking falls back into conservative marking. 3826 */ 3827 static void mark_all_scalars_precise(struct bpf_verifier_env *env, 3828 struct bpf_verifier_state *st) 3829 { 3830 struct bpf_func_state *func; 3831 struct bpf_reg_state *reg; 3832 int i, j; 3833 3834 if (env->log.level & BPF_LOG_LEVEL2) { 3835 verbose(env, "mark_precise: frame%d: falling back to forcing all scalars precise\n", 3836 st->curframe); 3837 } 3838 3839 /* big hammer: mark all scalars precise in this path. 3840 * pop_stack may still get !precise scalars. 3841 * We also skip current state and go straight to first parent state, 3842 * because precision markings in current non-checkpointed state are 3843 * not needed. See why in the comment in __mark_chain_precision below. 3844 */ 3845 for (st = st->parent; st; st = st->parent) { 3846 for (i = 0; i <= st->curframe; i++) { 3847 func = st->frame[i]; 3848 for (j = 0; j < BPF_REG_FP; j++) { 3849 reg = &func->regs[j]; 3850 if (reg->type != SCALAR_VALUE || reg->precise) 3851 continue; 3852 reg->precise = true; 3853 if (env->log.level & BPF_LOG_LEVEL2) { 3854 verbose(env, "force_precise: frame%d: forcing r%d to be precise\n", 3855 i, j); 3856 } 3857 } 3858 for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) { 3859 if (!is_spilled_reg(&func->stack[j])) 3860 continue; 3861 reg = &func->stack[j].spilled_ptr; 3862 if (reg->type != SCALAR_VALUE || reg->precise) 3863 continue; 3864 reg->precise = true; 3865 if (env->log.level & BPF_LOG_LEVEL2) { 3866 verbose(env, "force_precise: frame%d: forcing fp%d to be precise\n", 3867 i, -(j + 1) * 8); 3868 } 3869 } 3870 } 3871 } 3872 } 3873 3874 static void mark_all_scalars_imprecise(struct bpf_verifier_env *env, struct bpf_verifier_state *st) 3875 { 3876 struct bpf_func_state *func; 3877 struct bpf_reg_state *reg; 3878 int i, j; 3879 3880 for (i = 0; i <= st->curframe; i++) { 3881 func = st->frame[i]; 3882 for (j = 0; j < BPF_REG_FP; j++) { 3883 reg = &func->regs[j]; 3884 if (reg->type != SCALAR_VALUE) 3885 continue; 3886 reg->precise = false; 3887 } 3888 for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) { 3889 if (!is_spilled_reg(&func->stack[j])) 3890 continue; 3891 reg = &func->stack[j].spilled_ptr; 3892 if (reg->type != SCALAR_VALUE) 3893 continue; 3894 reg->precise = false; 3895 } 3896 } 3897 } 3898 3899 static bool idset_contains(struct bpf_idset *s, u32 id) 3900 { 3901 u32 i; 3902 3903 for (i = 0; i < s->count; ++i) 3904 if (s->ids[i] == id) 3905 return true; 3906 3907 return false; 3908 } 3909 3910 static int idset_push(struct bpf_idset *s, u32 id) 3911 { 3912 if (WARN_ON_ONCE(s->count >= ARRAY_SIZE(s->ids))) 3913 return -EFAULT; 3914 s->ids[s->count++] = id; 3915 return 0; 3916 } 3917 3918 static void idset_reset(struct bpf_idset *s) 3919 { 3920 s->count = 0; 3921 } 3922 3923 /* Collect a set of IDs for all registers currently marked as precise in env->bt. 3924 * Mark all registers with these IDs as precise. 3925 */ 3926 static int mark_precise_scalar_ids(struct bpf_verifier_env *env, struct bpf_verifier_state *st) 3927 { 3928 struct bpf_idset *precise_ids = &env->idset_scratch; 3929 struct backtrack_state *bt = &env->bt; 3930 struct bpf_func_state *func; 3931 struct bpf_reg_state *reg; 3932 DECLARE_BITMAP(mask, 64); 3933 int i, fr; 3934 3935 idset_reset(precise_ids); 3936 3937 for (fr = bt->frame; fr >= 0; fr--) { 3938 func = st->frame[fr]; 3939 3940 bitmap_from_u64(mask, bt_frame_reg_mask(bt, fr)); 3941 for_each_set_bit(i, mask, 32) { 3942 reg = &func->regs[i]; 3943 if (!reg->id || reg->type != SCALAR_VALUE) 3944 continue; 3945 if (idset_push(precise_ids, reg->id)) 3946 return -EFAULT; 3947 } 3948 3949 bitmap_from_u64(mask, bt_frame_stack_mask(bt, fr)); 3950 for_each_set_bit(i, mask, 64) { 3951 if (i >= func->allocated_stack / BPF_REG_SIZE) 3952 break; 3953 if (!is_spilled_scalar_reg(&func->stack[i])) 3954 continue; 3955 reg = &func->stack[i].spilled_ptr; 3956 if (!reg->id) 3957 continue; 3958 if (idset_push(precise_ids, reg->id)) 3959 return -EFAULT; 3960 } 3961 } 3962 3963 for (fr = 0; fr <= st->curframe; ++fr) { 3964 func = st->frame[fr]; 3965 3966 for (i = BPF_REG_0; i < BPF_REG_10; ++i) { 3967 reg = &func->regs[i]; 3968 if (!reg->id) 3969 continue; 3970 if (!idset_contains(precise_ids, reg->id)) 3971 continue; 3972 bt_set_frame_reg(bt, fr, i); 3973 } 3974 for (i = 0; i < func->allocated_stack / BPF_REG_SIZE; ++i) { 3975 if (!is_spilled_scalar_reg(&func->stack[i])) 3976 continue; 3977 reg = &func->stack[i].spilled_ptr; 3978 if (!reg->id) 3979 continue; 3980 if (!idset_contains(precise_ids, reg->id)) 3981 continue; 3982 bt_set_frame_slot(bt, fr, i); 3983 } 3984 } 3985 3986 return 0; 3987 } 3988 3989 /* 3990 * __mark_chain_precision() backtracks BPF program instruction sequence and 3991 * chain of verifier states making sure that register *regno* (if regno >= 0) 3992 * and/or stack slot *spi* (if spi >= 0) are marked as precisely tracked 3993 * SCALARS, as well as any other registers and slots that contribute to 3994 * a tracked state of given registers/stack slots, depending on specific BPF 3995 * assembly instructions (see backtrack_insns() for exact instruction handling 3996 * logic). This backtracking relies on recorded jmp_history and is able to 3997 * traverse entire chain of parent states. This process ends only when all the 3998 * necessary registers/slots and their transitive dependencies are marked as 3999 * precise. 4000 * 4001 * One important and subtle aspect is that precise marks *do not matter* in 4002 * the currently verified state (current state). It is important to understand 4003 * why this is the case. 4004 * 4005 * First, note that current state is the state that is not yet "checkpointed", 4006 * i.e., it is not yet put into env->explored_states, and it has no children 4007 * states as well. It's ephemeral, and can end up either a) being discarded if 4008 * compatible explored state is found at some point or BPF_EXIT instruction is 4009 * reached or b) checkpointed and put into env->explored_states, branching out 4010 * into one or more children states. 4011 * 4012 * In the former case, precise markings in current state are completely 4013 * ignored by state comparison code (see regsafe() for details). Only 4014 * checkpointed ("old") state precise markings are important, and if old 4015 * state's register/slot is precise, regsafe() assumes current state's 4016 * register/slot as precise and checks value ranges exactly and precisely. If 4017 * states turn out to be compatible, current state's necessary precise 4018 * markings and any required parent states' precise markings are enforced 4019 * after the fact with propagate_precision() logic, after the fact. But it's 4020 * important to realize that in this case, even after marking current state 4021 * registers/slots as precise, we immediately discard current state. So what 4022 * actually matters is any of the precise markings propagated into current 4023 * state's parent states, which are always checkpointed (due to b) case above). 4024 * As such, for scenario a) it doesn't matter if current state has precise 4025 * markings set or not. 4026 * 4027 * Now, for the scenario b), checkpointing and forking into child(ren) 4028 * state(s). Note that before current state gets to checkpointing step, any 4029 * processed instruction always assumes precise SCALAR register/slot 4030 * knowledge: if precise value or range is useful to prune jump branch, BPF 4031 * verifier takes this opportunity enthusiastically. Similarly, when 4032 * register's value is used to calculate offset or memory address, exact 4033 * knowledge of SCALAR range is assumed, checked, and enforced. So, similar to 4034 * what we mentioned above about state comparison ignoring precise markings 4035 * during state comparison, BPF verifier ignores and also assumes precise 4036 * markings *at will* during instruction verification process. But as verifier 4037 * assumes precision, it also propagates any precision dependencies across 4038 * parent states, which are not yet finalized, so can be further restricted 4039 * based on new knowledge gained from restrictions enforced by their children 4040 * states. This is so that once those parent states are finalized, i.e., when 4041 * they have no more active children state, state comparison logic in 4042 * is_state_visited() would enforce strict and precise SCALAR ranges, if 4043 * required for correctness. 4044 * 4045 * To build a bit more intuition, note also that once a state is checkpointed, 4046 * the path we took to get to that state is not important. This is crucial 4047 * property for state pruning. When state is checkpointed and finalized at 4048 * some instruction index, it can be correctly and safely used to "short 4049 * circuit" any *compatible* state that reaches exactly the same instruction 4050 * index. I.e., if we jumped to that instruction from a completely different 4051 * code path than original finalized state was derived from, it doesn't 4052 * matter, current state can be discarded because from that instruction 4053 * forward having a compatible state will ensure we will safely reach the 4054 * exit. States describe preconditions for further exploration, but completely 4055 * forget the history of how we got here. 4056 * 4057 * This also means that even if we needed precise SCALAR range to get to 4058 * finalized state, but from that point forward *that same* SCALAR register is 4059 * never used in a precise context (i.e., it's precise value is not needed for 4060 * correctness), it's correct and safe to mark such register as "imprecise" 4061 * (i.e., precise marking set to false). This is what we rely on when we do 4062 * not set precise marking in current state. If no child state requires 4063 * precision for any given SCALAR register, it's safe to dictate that it can 4064 * be imprecise. If any child state does require this register to be precise, 4065 * we'll mark it precise later retroactively during precise markings 4066 * propagation from child state to parent states. 4067 * 4068 * Skipping precise marking setting in current state is a mild version of 4069 * relying on the above observation. But we can utilize this property even 4070 * more aggressively by proactively forgetting any precise marking in the 4071 * current state (which we inherited from the parent state), right before we 4072 * checkpoint it and branch off into new child state. This is done by 4073 * mark_all_scalars_imprecise() to hopefully get more permissive and generic 4074 * finalized states which help in short circuiting more future states. 4075 */ 4076 static int __mark_chain_precision(struct bpf_verifier_env *env, int regno) 4077 { 4078 struct backtrack_state *bt = &env->bt; 4079 struct bpf_verifier_state *st = env->cur_state; 4080 int first_idx = st->first_insn_idx; 4081 int last_idx = env->insn_idx; 4082 int subseq_idx = -1; 4083 struct bpf_func_state *func; 4084 struct bpf_reg_state *reg; 4085 bool skip_first = true; 4086 int i, fr, err; 4087 4088 if (!env->bpf_capable) 4089 return 0; 4090 4091 /* set frame number from which we are starting to backtrack */ 4092 bt_init(bt, env->cur_state->curframe); 4093 4094 /* Do sanity checks against current state of register and/or stack 4095 * slot, but don't set precise flag in current state, as precision 4096 * tracking in the current state is unnecessary. 4097 */ 4098 func = st->frame[bt->frame]; 4099 if (regno >= 0) { 4100 reg = &func->regs[regno]; 4101 if (reg->type != SCALAR_VALUE) { 4102 WARN_ONCE(1, "backtracing misuse"); 4103 return -EFAULT; 4104 } 4105 bt_set_reg(bt, regno); 4106 } 4107 4108 if (bt_empty(bt)) 4109 return 0; 4110 4111 for (;;) { 4112 DECLARE_BITMAP(mask, 64); 4113 u32 history = st->jmp_history_cnt; 4114 4115 if (env->log.level & BPF_LOG_LEVEL2) { 4116 verbose(env, "mark_precise: frame%d: last_idx %d first_idx %d subseq_idx %d \n", 4117 bt->frame, last_idx, first_idx, subseq_idx); 4118 } 4119 4120 /* If some register with scalar ID is marked as precise, 4121 * make sure that all registers sharing this ID are also precise. 4122 * This is needed to estimate effect of find_equal_scalars(). 4123 * Do this at the last instruction of each state, 4124 * bpf_reg_state::id fields are valid for these instructions. 4125 * 4126 * Allows to track precision in situation like below: 4127 * 4128 * r2 = unknown value 4129 * ... 4130 * --- state #0 --- 4131 * ... 4132 * r1 = r2 // r1 and r2 now share the same ID 4133 * ... 4134 * --- state #1 {r1.id = A, r2.id = A} --- 4135 * ... 4136 * if (r2 > 10) goto exit; // find_equal_scalars() assigns range to r1 4137 * ... 4138 * --- state #2 {r1.id = A, r2.id = A} --- 4139 * r3 = r10 4140 * r3 += r1 // need to mark both r1 and r2 4141 */ 4142 if (mark_precise_scalar_ids(env, st)) 4143 return -EFAULT; 4144 4145 if (last_idx < 0) { 4146 /* we are at the entry into subprog, which 4147 * is expected for global funcs, but only if 4148 * requested precise registers are R1-R5 4149 * (which are global func's input arguments) 4150 */ 4151 if (st->curframe == 0 && 4152 st->frame[0]->subprogno > 0 && 4153 st->frame[0]->callsite == BPF_MAIN_FUNC && 4154 bt_stack_mask(bt) == 0 && 4155 (bt_reg_mask(bt) & ~BPF_REGMASK_ARGS) == 0) { 4156 bitmap_from_u64(mask, bt_reg_mask(bt)); 4157 for_each_set_bit(i, mask, 32) { 4158 reg = &st->frame[0]->regs[i]; 4159 bt_clear_reg(bt, i); 4160 if (reg->type == SCALAR_VALUE) 4161 reg->precise = true; 4162 } 4163 return 0; 4164 } 4165 4166 verbose(env, "BUG backtracking func entry subprog %d reg_mask %x stack_mask %llx\n", 4167 st->frame[0]->subprogno, bt_reg_mask(bt), bt_stack_mask(bt)); 4168 WARN_ONCE(1, "verifier backtracking bug"); 4169 return -EFAULT; 4170 } 4171 4172 for (i = last_idx;;) { 4173 if (skip_first) { 4174 err = 0; 4175 skip_first = false; 4176 } else { 4177 err = backtrack_insn(env, i, subseq_idx, bt); 4178 } 4179 if (err == -ENOTSUPP) { 4180 mark_all_scalars_precise(env, env->cur_state); 4181 bt_reset(bt); 4182 return 0; 4183 } else if (err) { 4184 return err; 4185 } 4186 if (bt_empty(bt)) 4187 /* Found assignment(s) into tracked register in this state. 4188 * Since this state is already marked, just return. 4189 * Nothing to be tracked further in the parent state. 4190 */ 4191 return 0; 4192 if (i == first_idx) 4193 break; 4194 subseq_idx = i; 4195 i = get_prev_insn_idx(st, i, &history); 4196 if (i >= env->prog->len) { 4197 /* This can happen if backtracking reached insn 0 4198 * and there are still reg_mask or stack_mask 4199 * to backtrack. 4200 * It means the backtracking missed the spot where 4201 * particular register was initialized with a constant. 4202 */ 4203 verbose(env, "BUG backtracking idx %d\n", i); 4204 WARN_ONCE(1, "verifier backtracking bug"); 4205 return -EFAULT; 4206 } 4207 } 4208 st = st->parent; 4209 if (!st) 4210 break; 4211 4212 for (fr = bt->frame; fr >= 0; fr--) { 4213 func = st->frame[fr]; 4214 bitmap_from_u64(mask, bt_frame_reg_mask(bt, fr)); 4215 for_each_set_bit(i, mask, 32) { 4216 reg = &func->regs[i]; 4217 if (reg->type != SCALAR_VALUE) { 4218 bt_clear_frame_reg(bt, fr, i); 4219 continue; 4220 } 4221 if (reg->precise) 4222 bt_clear_frame_reg(bt, fr, i); 4223 else 4224 reg->precise = true; 4225 } 4226 4227 bitmap_from_u64(mask, bt_frame_stack_mask(bt, fr)); 4228 for_each_set_bit(i, mask, 64) { 4229 if (i >= func->allocated_stack / BPF_REG_SIZE) { 4230 /* the sequence of instructions: 4231 * 2: (bf) r3 = r10 4232 * 3: (7b) *(u64 *)(r3 -8) = r0 4233 * 4: (79) r4 = *(u64 *)(r10 -8) 4234 * doesn't contain jmps. It's backtracked 4235 * as a single block. 4236 * During backtracking insn 3 is not recognized as 4237 * stack access, so at the end of backtracking 4238 * stack slot fp-8 is still marked in stack_mask. 4239 * However the parent state may not have accessed 4240 * fp-8 and it's "unallocated" stack space. 4241 * In such case fallback to conservative. 4242 */ 4243 mark_all_scalars_precise(env, env->cur_state); 4244 bt_reset(bt); 4245 return 0; 4246 } 4247 4248 if (!is_spilled_scalar_reg(&func->stack[i])) { 4249 bt_clear_frame_slot(bt, fr, i); 4250 continue; 4251 } 4252 reg = &func->stack[i].spilled_ptr; 4253 if (reg->precise) 4254 bt_clear_frame_slot(bt, fr, i); 4255 else 4256 reg->precise = true; 4257 } 4258 if (env->log.level & BPF_LOG_LEVEL2) { 4259 fmt_reg_mask(env->tmp_str_buf, TMP_STR_BUF_LEN, 4260 bt_frame_reg_mask(bt, fr)); 4261 verbose(env, "mark_precise: frame%d: parent state regs=%s ", 4262 fr, env->tmp_str_buf); 4263 fmt_stack_mask(env->tmp_str_buf, TMP_STR_BUF_LEN, 4264 bt_frame_stack_mask(bt, fr)); 4265 verbose(env, "stack=%s: ", env->tmp_str_buf); 4266 print_verifier_state(env, func, true); 4267 } 4268 } 4269 4270 if (bt_empty(bt)) 4271 return 0; 4272 4273 subseq_idx = first_idx; 4274 last_idx = st->last_insn_idx; 4275 first_idx = st->first_insn_idx; 4276 } 4277 4278 /* if we still have requested precise regs or slots, we missed 4279 * something (e.g., stack access through non-r10 register), so 4280 * fallback to marking all precise 4281 */ 4282 if (!bt_empty(bt)) { 4283 mark_all_scalars_precise(env, env->cur_state); 4284 bt_reset(bt); 4285 } 4286 4287 return 0; 4288 } 4289 4290 int mark_chain_precision(struct bpf_verifier_env *env, int regno) 4291 { 4292 return __mark_chain_precision(env, regno); 4293 } 4294 4295 /* mark_chain_precision_batch() assumes that env->bt is set in the caller to 4296 * desired reg and stack masks across all relevant frames 4297 */ 4298 static int mark_chain_precision_batch(struct bpf_verifier_env *env) 4299 { 4300 return __mark_chain_precision(env, -1); 4301 } 4302 4303 static bool is_spillable_regtype(enum bpf_reg_type type) 4304 { 4305 switch (base_type(type)) { 4306 case PTR_TO_MAP_VALUE: 4307 case PTR_TO_STACK: 4308 case PTR_TO_CTX: 4309 case PTR_TO_PACKET: 4310 case PTR_TO_PACKET_META: 4311 case PTR_TO_PACKET_END: 4312 case PTR_TO_FLOW_KEYS: 4313 case CONST_PTR_TO_MAP: 4314 case PTR_TO_SOCKET: 4315 case PTR_TO_SOCK_COMMON: 4316 case PTR_TO_TCP_SOCK: 4317 case PTR_TO_XDP_SOCK: 4318 case PTR_TO_BTF_ID: 4319 case PTR_TO_BUF: 4320 case PTR_TO_MEM: 4321 case PTR_TO_FUNC: 4322 case PTR_TO_MAP_KEY: 4323 return true; 4324 default: 4325 return false; 4326 } 4327 } 4328 4329 /* Does this register contain a constant zero? */ 4330 static bool register_is_null(struct bpf_reg_state *reg) 4331 { 4332 return reg->type == SCALAR_VALUE && tnum_equals_const(reg->var_off, 0); 4333 } 4334 4335 static bool register_is_const(struct bpf_reg_state *reg) 4336 { 4337 return reg->type == SCALAR_VALUE && tnum_is_const(reg->var_off); 4338 } 4339 4340 static bool __is_scalar_unbounded(struct bpf_reg_state *reg) 4341 { 4342 return tnum_is_unknown(reg->var_off) && 4343 reg->smin_value == S64_MIN && reg->smax_value == S64_MAX && 4344 reg->umin_value == 0 && reg->umax_value == U64_MAX && 4345 reg->s32_min_value == S32_MIN && reg->s32_max_value == S32_MAX && 4346 reg->u32_min_value == 0 && reg->u32_max_value == U32_MAX; 4347 } 4348 4349 static bool register_is_bounded(struct bpf_reg_state *reg) 4350 { 4351 return reg->type == SCALAR_VALUE && !__is_scalar_unbounded(reg); 4352 } 4353 4354 static bool __is_pointer_value(bool allow_ptr_leaks, 4355 const struct bpf_reg_state *reg) 4356 { 4357 if (allow_ptr_leaks) 4358 return false; 4359 4360 return reg->type != SCALAR_VALUE; 4361 } 4362 4363 /* Copy src state preserving dst->parent and dst->live fields */ 4364 static void copy_register_state(struct bpf_reg_state *dst, const struct bpf_reg_state *src) 4365 { 4366 struct bpf_reg_state *parent = dst->parent; 4367 enum bpf_reg_liveness live = dst->live; 4368 4369 *dst = *src; 4370 dst->parent = parent; 4371 dst->live = live; 4372 } 4373 4374 static void save_register_state(struct bpf_func_state *state, 4375 int spi, struct bpf_reg_state *reg, 4376 int size) 4377 { 4378 int i; 4379 4380 copy_register_state(&state->stack[spi].spilled_ptr, reg); 4381 if (size == BPF_REG_SIZE) 4382 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN; 4383 4384 for (i = BPF_REG_SIZE; i > BPF_REG_SIZE - size; i--) 4385 state->stack[spi].slot_type[i - 1] = STACK_SPILL; 4386 4387 /* size < 8 bytes spill */ 4388 for (; i; i--) 4389 scrub_spilled_slot(&state->stack[spi].slot_type[i - 1]); 4390 } 4391 4392 static bool is_bpf_st_mem(struct bpf_insn *insn) 4393 { 4394 return BPF_CLASS(insn->code) == BPF_ST && BPF_MODE(insn->code) == BPF_MEM; 4395 } 4396 4397 /* check_stack_{read,write}_fixed_off functions track spill/fill of registers, 4398 * stack boundary and alignment are checked in check_mem_access() 4399 */ 4400 static int check_stack_write_fixed_off(struct bpf_verifier_env *env, 4401 /* stack frame we're writing to */ 4402 struct bpf_func_state *state, 4403 int off, int size, int value_regno, 4404 int insn_idx) 4405 { 4406 struct bpf_func_state *cur; /* state of the current function */ 4407 int i, slot = -off - 1, spi = slot / BPF_REG_SIZE, err; 4408 struct bpf_insn *insn = &env->prog->insnsi[insn_idx]; 4409 struct bpf_reg_state *reg = NULL; 4410 u32 dst_reg = insn->dst_reg; 4411 4412 err = grow_stack_state(state, round_up(slot + 1, BPF_REG_SIZE)); 4413 if (err) 4414 return err; 4415 /* caller checked that off % size == 0 and -MAX_BPF_STACK <= off < 0, 4416 * so it's aligned access and [off, off + size) are within stack limits 4417 */ 4418 if (!env->allow_ptr_leaks && 4419 state->stack[spi].slot_type[0] == STACK_SPILL && 4420 size != BPF_REG_SIZE) { 4421 verbose(env, "attempt to corrupt spilled pointer on stack\n"); 4422 return -EACCES; 4423 } 4424 4425 cur = env->cur_state->frame[env->cur_state->curframe]; 4426 if (value_regno >= 0) 4427 reg = &cur->regs[value_regno]; 4428 if (!env->bypass_spec_v4) { 4429 bool sanitize = reg && is_spillable_regtype(reg->type); 4430 4431 for (i = 0; i < size; i++) { 4432 u8 type = state->stack[spi].slot_type[i]; 4433 4434 if (type != STACK_MISC && type != STACK_ZERO) { 4435 sanitize = true; 4436 break; 4437 } 4438 } 4439 4440 if (sanitize) 4441 env->insn_aux_data[insn_idx].sanitize_stack_spill = true; 4442 } 4443 4444 err = destroy_if_dynptr_stack_slot(env, state, spi); 4445 if (err) 4446 return err; 4447 4448 mark_stack_slot_scratched(env, spi); 4449 if (reg && !(off % BPF_REG_SIZE) && register_is_bounded(reg) && 4450 !register_is_null(reg) && env->bpf_capable) { 4451 if (dst_reg != BPF_REG_FP) { 4452 /* The backtracking logic can only recognize explicit 4453 * stack slot address like [fp - 8]. Other spill of 4454 * scalar via different register has to be conservative. 4455 * Backtrack from here and mark all registers as precise 4456 * that contributed into 'reg' being a constant. 4457 */ 4458 err = mark_chain_precision(env, value_regno); 4459 if (err) 4460 return err; 4461 } 4462 save_register_state(state, spi, reg, size); 4463 /* Break the relation on a narrowing spill. */ 4464 if (fls64(reg->umax_value) > BITS_PER_BYTE * size) 4465 state->stack[spi].spilled_ptr.id = 0; 4466 } else if (!reg && !(off % BPF_REG_SIZE) && is_bpf_st_mem(insn) && 4467 insn->imm != 0 && env->bpf_capable) { 4468 struct bpf_reg_state fake_reg = {}; 4469 4470 __mark_reg_known(&fake_reg, (u32)insn->imm); 4471 fake_reg.type = SCALAR_VALUE; 4472 save_register_state(state, spi, &fake_reg, size); 4473 } else if (reg && is_spillable_regtype(reg->type)) { 4474 /* register containing pointer is being spilled into stack */ 4475 if (size != BPF_REG_SIZE) { 4476 verbose_linfo(env, insn_idx, "; "); 4477 verbose(env, "invalid size of register spill\n"); 4478 return -EACCES; 4479 } 4480 if (state != cur && reg->type == PTR_TO_STACK) { 4481 verbose(env, "cannot spill pointers to stack into stack frame of the caller\n"); 4482 return -EINVAL; 4483 } 4484 save_register_state(state, spi, reg, size); 4485 } else { 4486 u8 type = STACK_MISC; 4487 4488 /* regular write of data into stack destroys any spilled ptr */ 4489 state->stack[spi].spilled_ptr.type = NOT_INIT; 4490 /* Mark slots as STACK_MISC if they belonged to spilled ptr/dynptr/iter. */ 4491 if (is_stack_slot_special(&state->stack[spi])) 4492 for (i = 0; i < BPF_REG_SIZE; i++) 4493 scrub_spilled_slot(&state->stack[spi].slot_type[i]); 4494 4495 /* only mark the slot as written if all 8 bytes were written 4496 * otherwise read propagation may incorrectly stop too soon 4497 * when stack slots are partially written. 4498 * This heuristic means that read propagation will be 4499 * conservative, since it will add reg_live_read marks 4500 * to stack slots all the way to first state when programs 4501 * writes+reads less than 8 bytes 4502 */ 4503 if (size == BPF_REG_SIZE) 4504 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN; 4505 4506 /* when we zero initialize stack slots mark them as such */ 4507 if ((reg && register_is_null(reg)) || 4508 (!reg && is_bpf_st_mem(insn) && insn->imm == 0)) { 4509 /* backtracking doesn't work for STACK_ZERO yet. */ 4510 err = mark_chain_precision(env, value_regno); 4511 if (err) 4512 return err; 4513 type = STACK_ZERO; 4514 } 4515 4516 /* Mark slots affected by this stack write. */ 4517 for (i = 0; i < size; i++) 4518 state->stack[spi].slot_type[(slot - i) % BPF_REG_SIZE] = 4519 type; 4520 } 4521 return 0; 4522 } 4523 4524 /* Write the stack: 'stack[ptr_regno + off] = value_regno'. 'ptr_regno' is 4525 * known to contain a variable offset. 4526 * This function checks whether the write is permitted and conservatively 4527 * tracks the effects of the write, considering that each stack slot in the 4528 * dynamic range is potentially written to. 4529 * 4530 * 'off' includes 'regno->off'. 4531 * 'value_regno' can be -1, meaning that an unknown value is being written to 4532 * the stack. 4533 * 4534 * Spilled pointers in range are not marked as written because we don't know 4535 * what's going to be actually written. This means that read propagation for 4536 * future reads cannot be terminated by this write. 4537 * 4538 * For privileged programs, uninitialized stack slots are considered 4539 * initialized by this write (even though we don't know exactly what offsets 4540 * are going to be written to). The idea is that we don't want the verifier to 4541 * reject future reads that access slots written to through variable offsets. 4542 */ 4543 static int check_stack_write_var_off(struct bpf_verifier_env *env, 4544 /* func where register points to */ 4545 struct bpf_func_state *state, 4546 int ptr_regno, int off, int size, 4547 int value_regno, int insn_idx) 4548 { 4549 struct bpf_func_state *cur; /* state of the current function */ 4550 int min_off, max_off; 4551 int i, err; 4552 struct bpf_reg_state *ptr_reg = NULL, *value_reg = NULL; 4553 struct bpf_insn *insn = &env->prog->insnsi[insn_idx]; 4554 bool writing_zero = false; 4555 /* set if the fact that we're writing a zero is used to let any 4556 * stack slots remain STACK_ZERO 4557 */ 4558 bool zero_used = false; 4559 4560 cur = env->cur_state->frame[env->cur_state->curframe]; 4561 ptr_reg = &cur->regs[ptr_regno]; 4562 min_off = ptr_reg->smin_value + off; 4563 max_off = ptr_reg->smax_value + off + size; 4564 if (value_regno >= 0) 4565 value_reg = &cur->regs[value_regno]; 4566 if ((value_reg && register_is_null(value_reg)) || 4567 (!value_reg && is_bpf_st_mem(insn) && insn->imm == 0)) 4568 writing_zero = true; 4569 4570 err = grow_stack_state(state, round_up(-min_off, BPF_REG_SIZE)); 4571 if (err) 4572 return err; 4573 4574 for (i = min_off; i < max_off; i++) { 4575 int spi; 4576 4577 spi = __get_spi(i); 4578 err = destroy_if_dynptr_stack_slot(env, state, spi); 4579 if (err) 4580 return err; 4581 } 4582 4583 /* Variable offset writes destroy any spilled pointers in range. */ 4584 for (i = min_off; i < max_off; i++) { 4585 u8 new_type, *stype; 4586 int slot, spi; 4587 4588 slot = -i - 1; 4589 spi = slot / BPF_REG_SIZE; 4590 stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE]; 4591 mark_stack_slot_scratched(env, spi); 4592 4593 if (!env->allow_ptr_leaks && *stype != STACK_MISC && *stype != STACK_ZERO) { 4594 /* Reject the write if range we may write to has not 4595 * been initialized beforehand. If we didn't reject 4596 * here, the ptr status would be erased below (even 4597 * though not all slots are actually overwritten), 4598 * possibly opening the door to leaks. 4599 * 4600 * We do however catch STACK_INVALID case below, and 4601 * only allow reading possibly uninitialized memory 4602 * later for CAP_PERFMON, as the write may not happen to 4603 * that slot. 4604 */ 4605 verbose(env, "spilled ptr in range of var-offset stack write; insn %d, ptr off: %d", 4606 insn_idx, i); 4607 return -EINVAL; 4608 } 4609 4610 /* Erase all spilled pointers. */ 4611 state->stack[spi].spilled_ptr.type = NOT_INIT; 4612 4613 /* Update the slot type. */ 4614 new_type = STACK_MISC; 4615 if (writing_zero && *stype == STACK_ZERO) { 4616 new_type = STACK_ZERO; 4617 zero_used = true; 4618 } 4619 /* If the slot is STACK_INVALID, we check whether it's OK to 4620 * pretend that it will be initialized by this write. The slot 4621 * might not actually be written to, and so if we mark it as 4622 * initialized future reads might leak uninitialized memory. 4623 * For privileged programs, we will accept such reads to slots 4624 * that may or may not be written because, if we're reject 4625 * them, the error would be too confusing. 4626 */ 4627 if (*stype == STACK_INVALID && !env->allow_uninit_stack) { 4628 verbose(env, "uninit stack in range of var-offset write prohibited for !root; insn %d, off: %d", 4629 insn_idx, i); 4630 return -EINVAL; 4631 } 4632 *stype = new_type; 4633 } 4634 if (zero_used) { 4635 /* backtracking doesn't work for STACK_ZERO yet. */ 4636 err = mark_chain_precision(env, value_regno); 4637 if (err) 4638 return err; 4639 } 4640 return 0; 4641 } 4642 4643 /* When register 'dst_regno' is assigned some values from stack[min_off, 4644 * max_off), we set the register's type according to the types of the 4645 * respective stack slots. If all the stack values are known to be zeros, then 4646 * so is the destination reg. Otherwise, the register is considered to be 4647 * SCALAR. This function does not deal with register filling; the caller must 4648 * ensure that all spilled registers in the stack range have been marked as 4649 * read. 4650 */ 4651 static void mark_reg_stack_read(struct bpf_verifier_env *env, 4652 /* func where src register points to */ 4653 struct bpf_func_state *ptr_state, 4654 int min_off, int max_off, int dst_regno) 4655 { 4656 struct bpf_verifier_state *vstate = env->cur_state; 4657 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 4658 int i, slot, spi; 4659 u8 *stype; 4660 int zeros = 0; 4661 4662 for (i = min_off; i < max_off; i++) { 4663 slot = -i - 1; 4664 spi = slot / BPF_REG_SIZE; 4665 mark_stack_slot_scratched(env, spi); 4666 stype = ptr_state->stack[spi].slot_type; 4667 if (stype[slot % BPF_REG_SIZE] != STACK_ZERO) 4668 break; 4669 zeros++; 4670 } 4671 if (zeros == max_off - min_off) { 4672 /* any access_size read into register is zero extended, 4673 * so the whole register == const_zero 4674 */ 4675 __mark_reg_const_zero(&state->regs[dst_regno]); 4676 /* backtracking doesn't support STACK_ZERO yet, 4677 * so mark it precise here, so that later 4678 * backtracking can stop here. 4679 * Backtracking may not need this if this register 4680 * doesn't participate in pointer adjustment. 4681 * Forward propagation of precise flag is not 4682 * necessary either. This mark is only to stop 4683 * backtracking. Any register that contributed 4684 * to const 0 was marked precise before spill. 4685 */ 4686 state->regs[dst_regno].precise = true; 4687 } else { 4688 /* have read misc data from the stack */ 4689 mark_reg_unknown(env, state->regs, dst_regno); 4690 } 4691 state->regs[dst_regno].live |= REG_LIVE_WRITTEN; 4692 } 4693 4694 /* Read the stack at 'off' and put the results into the register indicated by 4695 * 'dst_regno'. It handles reg filling if the addressed stack slot is a 4696 * spilled reg. 4697 * 4698 * 'dst_regno' can be -1, meaning that the read value is not going to a 4699 * register. 4700 * 4701 * The access is assumed to be within the current stack bounds. 4702 */ 4703 static int check_stack_read_fixed_off(struct bpf_verifier_env *env, 4704 /* func where src register points to */ 4705 struct bpf_func_state *reg_state, 4706 int off, int size, int dst_regno) 4707 { 4708 struct bpf_verifier_state *vstate = env->cur_state; 4709 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 4710 int i, slot = -off - 1, spi = slot / BPF_REG_SIZE; 4711 struct bpf_reg_state *reg; 4712 u8 *stype, type; 4713 4714 stype = reg_state->stack[spi].slot_type; 4715 reg = ®_state->stack[spi].spilled_ptr; 4716 4717 mark_stack_slot_scratched(env, spi); 4718 4719 if (is_spilled_reg(®_state->stack[spi])) { 4720 u8 spill_size = 1; 4721 4722 for (i = BPF_REG_SIZE - 1; i > 0 && stype[i - 1] == STACK_SPILL; i--) 4723 spill_size++; 4724 4725 if (size != BPF_REG_SIZE || spill_size != BPF_REG_SIZE) { 4726 if (reg->type != SCALAR_VALUE) { 4727 verbose_linfo(env, env->insn_idx, "; "); 4728 verbose(env, "invalid size of register fill\n"); 4729 return -EACCES; 4730 } 4731 4732 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64); 4733 if (dst_regno < 0) 4734 return 0; 4735 4736 if (!(off % BPF_REG_SIZE) && size == spill_size) { 4737 /* The earlier check_reg_arg() has decided the 4738 * subreg_def for this insn. Save it first. 4739 */ 4740 s32 subreg_def = state->regs[dst_regno].subreg_def; 4741 4742 copy_register_state(&state->regs[dst_regno], reg); 4743 state->regs[dst_regno].subreg_def = subreg_def; 4744 } else { 4745 for (i = 0; i < size; i++) { 4746 type = stype[(slot - i) % BPF_REG_SIZE]; 4747 if (type == STACK_SPILL) 4748 continue; 4749 if (type == STACK_MISC) 4750 continue; 4751 if (type == STACK_INVALID && env->allow_uninit_stack) 4752 continue; 4753 verbose(env, "invalid read from stack off %d+%d size %d\n", 4754 off, i, size); 4755 return -EACCES; 4756 } 4757 mark_reg_unknown(env, state->regs, dst_regno); 4758 } 4759 state->regs[dst_regno].live |= REG_LIVE_WRITTEN; 4760 return 0; 4761 } 4762 4763 if (dst_regno >= 0) { 4764 /* restore register state from stack */ 4765 copy_register_state(&state->regs[dst_regno], reg); 4766 /* mark reg as written since spilled pointer state likely 4767 * has its liveness marks cleared by is_state_visited() 4768 * which resets stack/reg liveness for state transitions 4769 */ 4770 state->regs[dst_regno].live |= REG_LIVE_WRITTEN; 4771 } else if (__is_pointer_value(env->allow_ptr_leaks, reg)) { 4772 /* If dst_regno==-1, the caller is asking us whether 4773 * it is acceptable to use this value as a SCALAR_VALUE 4774 * (e.g. for XADD). 4775 * We must not allow unprivileged callers to do that 4776 * with spilled pointers. 4777 */ 4778 verbose(env, "leaking pointer from stack off %d\n", 4779 off); 4780 return -EACCES; 4781 } 4782 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64); 4783 } else { 4784 for (i = 0; i < size; i++) { 4785 type = stype[(slot - i) % BPF_REG_SIZE]; 4786 if (type == STACK_MISC) 4787 continue; 4788 if (type == STACK_ZERO) 4789 continue; 4790 if (type == STACK_INVALID && env->allow_uninit_stack) 4791 continue; 4792 verbose(env, "invalid read from stack off %d+%d size %d\n", 4793 off, i, size); 4794 return -EACCES; 4795 } 4796 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64); 4797 if (dst_regno >= 0) 4798 mark_reg_stack_read(env, reg_state, off, off + size, dst_regno); 4799 } 4800 return 0; 4801 } 4802 4803 enum bpf_access_src { 4804 ACCESS_DIRECT = 1, /* the access is performed by an instruction */ 4805 ACCESS_HELPER = 2, /* the access is performed by a helper */ 4806 }; 4807 4808 static int check_stack_range_initialized(struct bpf_verifier_env *env, 4809 int regno, int off, int access_size, 4810 bool zero_size_allowed, 4811 enum bpf_access_src type, 4812 struct bpf_call_arg_meta *meta); 4813 4814 static struct bpf_reg_state *reg_state(struct bpf_verifier_env *env, int regno) 4815 { 4816 return cur_regs(env) + regno; 4817 } 4818 4819 /* Read the stack at 'ptr_regno + off' and put the result into the register 4820 * 'dst_regno'. 4821 * 'off' includes the pointer register's fixed offset(i.e. 'ptr_regno.off'), 4822 * but not its variable offset. 4823 * 'size' is assumed to be <= reg size and the access is assumed to be aligned. 4824 * 4825 * As opposed to check_stack_read_fixed_off, this function doesn't deal with 4826 * filling registers (i.e. reads of spilled register cannot be detected when 4827 * the offset is not fixed). We conservatively mark 'dst_regno' as containing 4828 * SCALAR_VALUE. That's why we assert that the 'ptr_regno' has a variable 4829 * offset; for a fixed offset check_stack_read_fixed_off should be used 4830 * instead. 4831 */ 4832 static int check_stack_read_var_off(struct bpf_verifier_env *env, 4833 int ptr_regno, int off, int size, int dst_regno) 4834 { 4835 /* The state of the source register. */ 4836 struct bpf_reg_state *reg = reg_state(env, ptr_regno); 4837 struct bpf_func_state *ptr_state = func(env, reg); 4838 int err; 4839 int min_off, max_off; 4840 4841 /* Note that we pass a NULL meta, so raw access will not be permitted. 4842 */ 4843 err = check_stack_range_initialized(env, ptr_regno, off, size, 4844 false, ACCESS_DIRECT, NULL); 4845 if (err) 4846 return err; 4847 4848 min_off = reg->smin_value + off; 4849 max_off = reg->smax_value + off; 4850 mark_reg_stack_read(env, ptr_state, min_off, max_off + size, dst_regno); 4851 return 0; 4852 } 4853 4854 /* check_stack_read dispatches to check_stack_read_fixed_off or 4855 * check_stack_read_var_off. 4856 * 4857 * The caller must ensure that the offset falls within the allocated stack 4858 * bounds. 4859 * 4860 * 'dst_regno' is a register which will receive the value from the stack. It 4861 * can be -1, meaning that the read value is not going to a register. 4862 */ 4863 static int check_stack_read(struct bpf_verifier_env *env, 4864 int ptr_regno, int off, int size, 4865 int dst_regno) 4866 { 4867 struct bpf_reg_state *reg = reg_state(env, ptr_regno); 4868 struct bpf_func_state *state = func(env, reg); 4869 int err; 4870 /* Some accesses are only permitted with a static offset. */ 4871 bool var_off = !tnum_is_const(reg->var_off); 4872 4873 /* The offset is required to be static when reads don't go to a 4874 * register, in order to not leak pointers (see 4875 * check_stack_read_fixed_off). 4876 */ 4877 if (dst_regno < 0 && var_off) { 4878 char tn_buf[48]; 4879 4880 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 4881 verbose(env, "variable offset stack pointer cannot be passed into helper function; var_off=%s off=%d size=%d\n", 4882 tn_buf, off, size); 4883 return -EACCES; 4884 } 4885 /* Variable offset is prohibited for unprivileged mode for simplicity 4886 * since it requires corresponding support in Spectre masking for stack 4887 * ALU. See also retrieve_ptr_limit(). The check in 4888 * check_stack_access_for_ptr_arithmetic() called by 4889 * adjust_ptr_min_max_vals() prevents users from creating stack pointers 4890 * with variable offsets, therefore no check is required here. Further, 4891 * just checking it here would be insufficient as speculative stack 4892 * writes could still lead to unsafe speculative behaviour. 4893 */ 4894 if (!var_off) { 4895 off += reg->var_off.value; 4896 err = check_stack_read_fixed_off(env, state, off, size, 4897 dst_regno); 4898 } else { 4899 /* Variable offset stack reads need more conservative handling 4900 * than fixed offset ones. Note that dst_regno >= 0 on this 4901 * branch. 4902 */ 4903 err = check_stack_read_var_off(env, ptr_regno, off, size, 4904 dst_regno); 4905 } 4906 return err; 4907 } 4908 4909 4910 /* check_stack_write dispatches to check_stack_write_fixed_off or 4911 * check_stack_write_var_off. 4912 * 4913 * 'ptr_regno' is the register used as a pointer into the stack. 4914 * 'off' includes 'ptr_regno->off', but not its variable offset (if any). 4915 * 'value_regno' is the register whose value we're writing to the stack. It can 4916 * be -1, meaning that we're not writing from a register. 4917 * 4918 * The caller must ensure that the offset falls within the maximum stack size. 4919 */ 4920 static int check_stack_write(struct bpf_verifier_env *env, 4921 int ptr_regno, int off, int size, 4922 int value_regno, int insn_idx) 4923 { 4924 struct bpf_reg_state *reg = reg_state(env, ptr_regno); 4925 struct bpf_func_state *state = func(env, reg); 4926 int err; 4927 4928 if (tnum_is_const(reg->var_off)) { 4929 off += reg->var_off.value; 4930 err = check_stack_write_fixed_off(env, state, off, size, 4931 value_regno, insn_idx); 4932 } else { 4933 /* Variable offset stack reads need more conservative handling 4934 * than fixed offset ones. 4935 */ 4936 err = check_stack_write_var_off(env, state, 4937 ptr_regno, off, size, 4938 value_regno, insn_idx); 4939 } 4940 return err; 4941 } 4942 4943 static int check_map_access_type(struct bpf_verifier_env *env, u32 regno, 4944 int off, int size, enum bpf_access_type type) 4945 { 4946 struct bpf_reg_state *regs = cur_regs(env); 4947 struct bpf_map *map = regs[regno].map_ptr; 4948 u32 cap = bpf_map_flags_to_cap(map); 4949 4950 if (type == BPF_WRITE && !(cap & BPF_MAP_CAN_WRITE)) { 4951 verbose(env, "write into map forbidden, value_size=%d off=%d size=%d\n", 4952 map->value_size, off, size); 4953 return -EACCES; 4954 } 4955 4956 if (type == BPF_READ && !(cap & BPF_MAP_CAN_READ)) { 4957 verbose(env, "read from map forbidden, value_size=%d off=%d size=%d\n", 4958 map->value_size, off, size); 4959 return -EACCES; 4960 } 4961 4962 return 0; 4963 } 4964 4965 /* check read/write into memory region (e.g., map value, ringbuf sample, etc) */ 4966 static int __check_mem_access(struct bpf_verifier_env *env, int regno, 4967 int off, int size, u32 mem_size, 4968 bool zero_size_allowed) 4969 { 4970 bool size_ok = size > 0 || (size == 0 && zero_size_allowed); 4971 struct bpf_reg_state *reg; 4972 4973 if (off >= 0 && size_ok && (u64)off + size <= mem_size) 4974 return 0; 4975 4976 reg = &cur_regs(env)[regno]; 4977 switch (reg->type) { 4978 case PTR_TO_MAP_KEY: 4979 verbose(env, "invalid access to map key, key_size=%d off=%d size=%d\n", 4980 mem_size, off, size); 4981 break; 4982 case PTR_TO_MAP_VALUE: 4983 verbose(env, "invalid access to map value, value_size=%d off=%d size=%d\n", 4984 mem_size, off, size); 4985 break; 4986 case PTR_TO_PACKET: 4987 case PTR_TO_PACKET_META: 4988 case PTR_TO_PACKET_END: 4989 verbose(env, "invalid access to packet, off=%d size=%d, R%d(id=%d,off=%d,r=%d)\n", 4990 off, size, regno, reg->id, off, mem_size); 4991 break; 4992 case PTR_TO_MEM: 4993 default: 4994 verbose(env, "invalid access to memory, mem_size=%u off=%d size=%d\n", 4995 mem_size, off, size); 4996 } 4997 4998 return -EACCES; 4999 } 5000 5001 /* check read/write into a memory region with possible variable offset */ 5002 static int check_mem_region_access(struct bpf_verifier_env *env, u32 regno, 5003 int off, int size, u32 mem_size, 5004 bool zero_size_allowed) 5005 { 5006 struct bpf_verifier_state *vstate = env->cur_state; 5007 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 5008 struct bpf_reg_state *reg = &state->regs[regno]; 5009 int err; 5010 5011 /* We may have adjusted the register pointing to memory region, so we 5012 * need to try adding each of min_value and max_value to off 5013 * to make sure our theoretical access will be safe. 5014 * 5015 * The minimum value is only important with signed 5016 * comparisons where we can't assume the floor of a 5017 * value is 0. If we are using signed variables for our 5018 * index'es we need to make sure that whatever we use 5019 * will have a set floor within our range. 5020 */ 5021 if (reg->smin_value < 0 && 5022 (reg->smin_value == S64_MIN || 5023 (off + reg->smin_value != (s64)(s32)(off + reg->smin_value)) || 5024 reg->smin_value + off < 0)) { 5025 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n", 5026 regno); 5027 return -EACCES; 5028 } 5029 err = __check_mem_access(env, regno, reg->smin_value + off, size, 5030 mem_size, zero_size_allowed); 5031 if (err) { 5032 verbose(env, "R%d min value is outside of the allowed memory range\n", 5033 regno); 5034 return err; 5035 } 5036 5037 /* If we haven't set a max value then we need to bail since we can't be 5038 * sure we won't do bad things. 5039 * If reg->umax_value + off could overflow, treat that as unbounded too. 5040 */ 5041 if (reg->umax_value >= BPF_MAX_VAR_OFF) { 5042 verbose(env, "R%d unbounded memory access, make sure to bounds check any such access\n", 5043 regno); 5044 return -EACCES; 5045 } 5046 err = __check_mem_access(env, regno, reg->umax_value + off, size, 5047 mem_size, zero_size_allowed); 5048 if (err) { 5049 verbose(env, "R%d max value is outside of the allowed memory range\n", 5050 regno); 5051 return err; 5052 } 5053 5054 return 0; 5055 } 5056 5057 static int __check_ptr_off_reg(struct bpf_verifier_env *env, 5058 const struct bpf_reg_state *reg, int regno, 5059 bool fixed_off_ok) 5060 { 5061 /* Access to this pointer-typed register or passing it to a helper 5062 * is only allowed in its original, unmodified form. 5063 */ 5064 5065 if (reg->off < 0) { 5066 verbose(env, "negative offset %s ptr R%d off=%d disallowed\n", 5067 reg_type_str(env, reg->type), regno, reg->off); 5068 return -EACCES; 5069 } 5070 5071 if (!fixed_off_ok && reg->off) { 5072 verbose(env, "dereference of modified %s ptr R%d off=%d disallowed\n", 5073 reg_type_str(env, reg->type), regno, reg->off); 5074 return -EACCES; 5075 } 5076 5077 if (!tnum_is_const(reg->var_off) || reg->var_off.value) { 5078 char tn_buf[48]; 5079 5080 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 5081 verbose(env, "variable %s access var_off=%s disallowed\n", 5082 reg_type_str(env, reg->type), tn_buf); 5083 return -EACCES; 5084 } 5085 5086 return 0; 5087 } 5088 5089 int check_ptr_off_reg(struct bpf_verifier_env *env, 5090 const struct bpf_reg_state *reg, int regno) 5091 { 5092 return __check_ptr_off_reg(env, reg, regno, false); 5093 } 5094 5095 static int map_kptr_match_type(struct bpf_verifier_env *env, 5096 struct btf_field *kptr_field, 5097 struct bpf_reg_state *reg, u32 regno) 5098 { 5099 const char *targ_name = btf_type_name(kptr_field->kptr.btf, kptr_field->kptr.btf_id); 5100 int perm_flags; 5101 const char *reg_name = ""; 5102 5103 if (btf_is_kernel(reg->btf)) { 5104 perm_flags = PTR_MAYBE_NULL | PTR_TRUSTED | MEM_RCU; 5105 5106 /* Only unreferenced case accepts untrusted pointers */ 5107 if (kptr_field->type == BPF_KPTR_UNREF) 5108 perm_flags |= PTR_UNTRUSTED; 5109 } else { 5110 perm_flags = PTR_MAYBE_NULL | MEM_ALLOC; 5111 if (kptr_field->type == BPF_KPTR_PERCPU) 5112 perm_flags |= MEM_PERCPU; 5113 } 5114 5115 if (base_type(reg->type) != PTR_TO_BTF_ID || (type_flag(reg->type) & ~perm_flags)) 5116 goto bad_type; 5117 5118 /* We need to verify reg->type and reg->btf, before accessing reg->btf */ 5119 reg_name = btf_type_name(reg->btf, reg->btf_id); 5120 5121 /* For ref_ptr case, release function check should ensure we get one 5122 * referenced PTR_TO_BTF_ID, and that its fixed offset is 0. For the 5123 * normal store of unreferenced kptr, we must ensure var_off is zero. 5124 * Since ref_ptr cannot be accessed directly by BPF insns, checks for 5125 * reg->off and reg->ref_obj_id are not needed here. 5126 */ 5127 if (__check_ptr_off_reg(env, reg, regno, true)) 5128 return -EACCES; 5129 5130 /* A full type match is needed, as BTF can be vmlinux, module or prog BTF, and 5131 * we also need to take into account the reg->off. 5132 * 5133 * We want to support cases like: 5134 * 5135 * struct foo { 5136 * struct bar br; 5137 * struct baz bz; 5138 * }; 5139 * 5140 * struct foo *v; 5141 * v = func(); // PTR_TO_BTF_ID 5142 * val->foo = v; // reg->off is zero, btf and btf_id match type 5143 * val->bar = &v->br; // reg->off is still zero, but we need to retry with 5144 * // first member type of struct after comparison fails 5145 * val->baz = &v->bz; // reg->off is non-zero, so struct needs to be walked 5146 * // to match type 5147 * 5148 * In the kptr_ref case, check_func_arg_reg_off already ensures reg->off 5149 * is zero. We must also ensure that btf_struct_ids_match does not walk 5150 * the struct to match type against first member of struct, i.e. reject 5151 * second case from above. Hence, when type is BPF_KPTR_REF, we set 5152 * strict mode to true for type match. 5153 */ 5154 if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off, 5155 kptr_field->kptr.btf, kptr_field->kptr.btf_id, 5156 kptr_field->type != BPF_KPTR_UNREF)) 5157 goto bad_type; 5158 return 0; 5159 bad_type: 5160 verbose(env, "invalid kptr access, R%d type=%s%s ", regno, 5161 reg_type_str(env, reg->type), reg_name); 5162 verbose(env, "expected=%s%s", reg_type_str(env, PTR_TO_BTF_ID), targ_name); 5163 if (kptr_field->type == BPF_KPTR_UNREF) 5164 verbose(env, " or %s%s\n", reg_type_str(env, PTR_TO_BTF_ID | PTR_UNTRUSTED), 5165 targ_name); 5166 else 5167 verbose(env, "\n"); 5168 return -EINVAL; 5169 } 5170 5171 /* The non-sleepable programs and sleepable programs with explicit bpf_rcu_read_lock() 5172 * can dereference RCU protected pointers and result is PTR_TRUSTED. 5173 */ 5174 static bool in_rcu_cs(struct bpf_verifier_env *env) 5175 { 5176 return env->cur_state->active_rcu_lock || 5177 env->cur_state->active_lock.ptr || 5178 !env->prog->aux->sleepable; 5179 } 5180 5181 /* Once GCC supports btf_type_tag the following mechanism will be replaced with tag check */ 5182 BTF_SET_START(rcu_protected_types) 5183 BTF_ID(struct, prog_test_ref_kfunc) 5184 BTF_ID(struct, cgroup) 5185 BTF_ID(struct, bpf_cpumask) 5186 BTF_ID(struct, task_struct) 5187 BTF_SET_END(rcu_protected_types) 5188 5189 static bool rcu_protected_object(const struct btf *btf, u32 btf_id) 5190 { 5191 if (!btf_is_kernel(btf)) 5192 return false; 5193 return btf_id_set_contains(&rcu_protected_types, btf_id); 5194 } 5195 5196 static bool rcu_safe_kptr(const struct btf_field *field) 5197 { 5198 const struct btf_field_kptr *kptr = &field->kptr; 5199 5200 return field->type == BPF_KPTR_PERCPU || 5201 (field->type == BPF_KPTR_REF && rcu_protected_object(kptr->btf, kptr->btf_id)); 5202 } 5203 5204 static u32 btf_ld_kptr_type(struct bpf_verifier_env *env, struct btf_field *kptr_field) 5205 { 5206 if (rcu_safe_kptr(kptr_field) && in_rcu_cs(env)) { 5207 if (kptr_field->type != BPF_KPTR_PERCPU) 5208 return PTR_MAYBE_NULL | MEM_RCU; 5209 return PTR_MAYBE_NULL | MEM_RCU | MEM_PERCPU; 5210 } 5211 return PTR_MAYBE_NULL | PTR_UNTRUSTED; 5212 } 5213 5214 static int check_map_kptr_access(struct bpf_verifier_env *env, u32 regno, 5215 int value_regno, int insn_idx, 5216 struct btf_field *kptr_field) 5217 { 5218 struct bpf_insn *insn = &env->prog->insnsi[insn_idx]; 5219 int class = BPF_CLASS(insn->code); 5220 struct bpf_reg_state *val_reg; 5221 5222 /* Things we already checked for in check_map_access and caller: 5223 * - Reject cases where variable offset may touch kptr 5224 * - size of access (must be BPF_DW) 5225 * - tnum_is_const(reg->var_off) 5226 * - kptr_field->offset == off + reg->var_off.value 5227 */ 5228 /* Only BPF_[LDX,STX,ST] | BPF_MEM | BPF_DW is supported */ 5229 if (BPF_MODE(insn->code) != BPF_MEM) { 5230 verbose(env, "kptr in map can only be accessed using BPF_MEM instruction mode\n"); 5231 return -EACCES; 5232 } 5233 5234 /* We only allow loading referenced kptr, since it will be marked as 5235 * untrusted, similar to unreferenced kptr. 5236 */ 5237 if (class != BPF_LDX && 5238 (kptr_field->type == BPF_KPTR_REF || kptr_field->type == BPF_KPTR_PERCPU)) { 5239 verbose(env, "store to referenced kptr disallowed\n"); 5240 return -EACCES; 5241 } 5242 5243 if (class == BPF_LDX) { 5244 val_reg = reg_state(env, value_regno); 5245 /* We can simply mark the value_regno receiving the pointer 5246 * value from map as PTR_TO_BTF_ID, with the correct type. 5247 */ 5248 mark_btf_ld_reg(env, cur_regs(env), value_regno, PTR_TO_BTF_ID, kptr_field->kptr.btf, 5249 kptr_field->kptr.btf_id, btf_ld_kptr_type(env, kptr_field)); 5250 /* For mark_ptr_or_null_reg */ 5251 val_reg->id = ++env->id_gen; 5252 } else if (class == BPF_STX) { 5253 val_reg = reg_state(env, value_regno); 5254 if (!register_is_null(val_reg) && 5255 map_kptr_match_type(env, kptr_field, val_reg, value_regno)) 5256 return -EACCES; 5257 } else if (class == BPF_ST) { 5258 if (insn->imm) { 5259 verbose(env, "BPF_ST imm must be 0 when storing to kptr at off=%u\n", 5260 kptr_field->offset); 5261 return -EACCES; 5262 } 5263 } else { 5264 verbose(env, "kptr in map can only be accessed using BPF_LDX/BPF_STX/BPF_ST\n"); 5265 return -EACCES; 5266 } 5267 return 0; 5268 } 5269 5270 /* check read/write into a map element with possible variable offset */ 5271 static int check_map_access(struct bpf_verifier_env *env, u32 regno, 5272 int off, int size, bool zero_size_allowed, 5273 enum bpf_access_src src) 5274 { 5275 struct bpf_verifier_state *vstate = env->cur_state; 5276 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 5277 struct bpf_reg_state *reg = &state->regs[regno]; 5278 struct bpf_map *map = reg->map_ptr; 5279 struct btf_record *rec; 5280 int err, i; 5281 5282 err = check_mem_region_access(env, regno, off, size, map->value_size, 5283 zero_size_allowed); 5284 if (err) 5285 return err; 5286 5287 if (IS_ERR_OR_NULL(map->record)) 5288 return 0; 5289 rec = map->record; 5290 for (i = 0; i < rec->cnt; i++) { 5291 struct btf_field *field = &rec->fields[i]; 5292 u32 p = field->offset; 5293 5294 /* If any part of a field can be touched by load/store, reject 5295 * this program. To check that [x1, x2) overlaps with [y1, y2), 5296 * it is sufficient to check x1 < y2 && y1 < x2. 5297 */ 5298 if (reg->smin_value + off < p + btf_field_type_size(field->type) && 5299 p < reg->umax_value + off + size) { 5300 switch (field->type) { 5301 case BPF_KPTR_UNREF: 5302 case BPF_KPTR_REF: 5303 case BPF_KPTR_PERCPU: 5304 if (src != ACCESS_DIRECT) { 5305 verbose(env, "kptr cannot be accessed indirectly by helper\n"); 5306 return -EACCES; 5307 } 5308 if (!tnum_is_const(reg->var_off)) { 5309 verbose(env, "kptr access cannot have variable offset\n"); 5310 return -EACCES; 5311 } 5312 if (p != off + reg->var_off.value) { 5313 verbose(env, "kptr access misaligned expected=%u off=%llu\n", 5314 p, off + reg->var_off.value); 5315 return -EACCES; 5316 } 5317 if (size != bpf_size_to_bytes(BPF_DW)) { 5318 verbose(env, "kptr access size must be BPF_DW\n"); 5319 return -EACCES; 5320 } 5321 break; 5322 default: 5323 verbose(env, "%s cannot be accessed directly by load/store\n", 5324 btf_field_type_name(field->type)); 5325 return -EACCES; 5326 } 5327 } 5328 } 5329 return 0; 5330 } 5331 5332 #define MAX_PACKET_OFF 0xffff 5333 5334 static bool may_access_direct_pkt_data(struct bpf_verifier_env *env, 5335 const struct bpf_call_arg_meta *meta, 5336 enum bpf_access_type t) 5337 { 5338 enum bpf_prog_type prog_type = resolve_prog_type(env->prog); 5339 5340 switch (prog_type) { 5341 /* Program types only with direct read access go here! */ 5342 case BPF_PROG_TYPE_LWT_IN: 5343 case BPF_PROG_TYPE_LWT_OUT: 5344 case BPF_PROG_TYPE_LWT_SEG6LOCAL: 5345 case BPF_PROG_TYPE_SK_REUSEPORT: 5346 case BPF_PROG_TYPE_FLOW_DISSECTOR: 5347 case BPF_PROG_TYPE_CGROUP_SKB: 5348 if (t == BPF_WRITE) 5349 return false; 5350 fallthrough; 5351 5352 /* Program types with direct read + write access go here! */ 5353 case BPF_PROG_TYPE_SCHED_CLS: 5354 case BPF_PROG_TYPE_SCHED_ACT: 5355 case BPF_PROG_TYPE_XDP: 5356 case BPF_PROG_TYPE_LWT_XMIT: 5357 case BPF_PROG_TYPE_SK_SKB: 5358 case BPF_PROG_TYPE_SK_MSG: 5359 if (meta) 5360 return meta->pkt_access; 5361 5362 env->seen_direct_write = true; 5363 return true; 5364 5365 case BPF_PROG_TYPE_CGROUP_SOCKOPT: 5366 if (t == BPF_WRITE) 5367 env->seen_direct_write = true; 5368 5369 return true; 5370 5371 default: 5372 return false; 5373 } 5374 } 5375 5376 static int check_packet_access(struct bpf_verifier_env *env, u32 regno, int off, 5377 int size, bool zero_size_allowed) 5378 { 5379 struct bpf_reg_state *regs = cur_regs(env); 5380 struct bpf_reg_state *reg = ®s[regno]; 5381 int err; 5382 5383 /* We may have added a variable offset to the packet pointer; but any 5384 * reg->range we have comes after that. We are only checking the fixed 5385 * offset. 5386 */ 5387 5388 /* We don't allow negative numbers, because we aren't tracking enough 5389 * detail to prove they're safe. 5390 */ 5391 if (reg->smin_value < 0) { 5392 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n", 5393 regno); 5394 return -EACCES; 5395 } 5396 5397 err = reg->range < 0 ? -EINVAL : 5398 __check_mem_access(env, regno, off, size, reg->range, 5399 zero_size_allowed); 5400 if (err) { 5401 verbose(env, "R%d offset is outside of the packet\n", regno); 5402 return err; 5403 } 5404 5405 /* __check_mem_access has made sure "off + size - 1" is within u16. 5406 * reg->umax_value can't be bigger than MAX_PACKET_OFF which is 0xffff, 5407 * otherwise find_good_pkt_pointers would have refused to set range info 5408 * that __check_mem_access would have rejected this pkt access. 5409 * Therefore, "off + reg->umax_value + size - 1" won't overflow u32. 5410 */ 5411 env->prog->aux->max_pkt_offset = 5412 max_t(u32, env->prog->aux->max_pkt_offset, 5413 off + reg->umax_value + size - 1); 5414 5415 return err; 5416 } 5417 5418 /* check access to 'struct bpf_context' fields. Supports fixed offsets only */ 5419 static int check_ctx_access(struct bpf_verifier_env *env, int insn_idx, int off, int size, 5420 enum bpf_access_type t, enum bpf_reg_type *reg_type, 5421 struct btf **btf, u32 *btf_id) 5422 { 5423 struct bpf_insn_access_aux info = { 5424 .reg_type = *reg_type, 5425 .log = &env->log, 5426 }; 5427 5428 if (env->ops->is_valid_access && 5429 env->ops->is_valid_access(off, size, t, env->prog, &info)) { 5430 /* A non zero info.ctx_field_size indicates that this field is a 5431 * candidate for later verifier transformation to load the whole 5432 * field and then apply a mask when accessed with a narrower 5433 * access than actual ctx access size. A zero info.ctx_field_size 5434 * will only allow for whole field access and rejects any other 5435 * type of narrower access. 5436 */ 5437 *reg_type = info.reg_type; 5438 5439 if (base_type(*reg_type) == PTR_TO_BTF_ID) { 5440 *btf = info.btf; 5441 *btf_id = info.btf_id; 5442 } else { 5443 env->insn_aux_data[insn_idx].ctx_field_size = info.ctx_field_size; 5444 } 5445 /* remember the offset of last byte accessed in ctx */ 5446 if (env->prog->aux->max_ctx_offset < off + size) 5447 env->prog->aux->max_ctx_offset = off + size; 5448 return 0; 5449 } 5450 5451 verbose(env, "invalid bpf_context access off=%d size=%d\n", off, size); 5452 return -EACCES; 5453 } 5454 5455 static int check_flow_keys_access(struct bpf_verifier_env *env, int off, 5456 int size) 5457 { 5458 if (size < 0 || off < 0 || 5459 (u64)off + size > sizeof(struct bpf_flow_keys)) { 5460 verbose(env, "invalid access to flow keys off=%d size=%d\n", 5461 off, size); 5462 return -EACCES; 5463 } 5464 return 0; 5465 } 5466 5467 static int check_sock_access(struct bpf_verifier_env *env, int insn_idx, 5468 u32 regno, int off, int size, 5469 enum bpf_access_type t) 5470 { 5471 struct bpf_reg_state *regs = cur_regs(env); 5472 struct bpf_reg_state *reg = ®s[regno]; 5473 struct bpf_insn_access_aux info = {}; 5474 bool valid; 5475 5476 if (reg->smin_value < 0) { 5477 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n", 5478 regno); 5479 return -EACCES; 5480 } 5481 5482 switch (reg->type) { 5483 case PTR_TO_SOCK_COMMON: 5484 valid = bpf_sock_common_is_valid_access(off, size, t, &info); 5485 break; 5486 case PTR_TO_SOCKET: 5487 valid = bpf_sock_is_valid_access(off, size, t, &info); 5488 break; 5489 case PTR_TO_TCP_SOCK: 5490 valid = bpf_tcp_sock_is_valid_access(off, size, t, &info); 5491 break; 5492 case PTR_TO_XDP_SOCK: 5493 valid = bpf_xdp_sock_is_valid_access(off, size, t, &info); 5494 break; 5495 default: 5496 valid = false; 5497 } 5498 5499 5500 if (valid) { 5501 env->insn_aux_data[insn_idx].ctx_field_size = 5502 info.ctx_field_size; 5503 return 0; 5504 } 5505 5506 verbose(env, "R%d invalid %s access off=%d size=%d\n", 5507 regno, reg_type_str(env, reg->type), off, size); 5508 5509 return -EACCES; 5510 } 5511 5512 static bool is_pointer_value(struct bpf_verifier_env *env, int regno) 5513 { 5514 return __is_pointer_value(env->allow_ptr_leaks, reg_state(env, regno)); 5515 } 5516 5517 static bool is_ctx_reg(struct bpf_verifier_env *env, int regno) 5518 { 5519 const struct bpf_reg_state *reg = reg_state(env, regno); 5520 5521 return reg->type == PTR_TO_CTX; 5522 } 5523 5524 static bool is_sk_reg(struct bpf_verifier_env *env, int regno) 5525 { 5526 const struct bpf_reg_state *reg = reg_state(env, regno); 5527 5528 return type_is_sk_pointer(reg->type); 5529 } 5530 5531 static bool is_pkt_reg(struct bpf_verifier_env *env, int regno) 5532 { 5533 const struct bpf_reg_state *reg = reg_state(env, regno); 5534 5535 return type_is_pkt_pointer(reg->type); 5536 } 5537 5538 static bool is_flow_key_reg(struct bpf_verifier_env *env, int regno) 5539 { 5540 const struct bpf_reg_state *reg = reg_state(env, regno); 5541 5542 /* Separate to is_ctx_reg() since we still want to allow BPF_ST here. */ 5543 return reg->type == PTR_TO_FLOW_KEYS; 5544 } 5545 5546 static u32 *reg2btf_ids[__BPF_REG_TYPE_MAX] = { 5547 #ifdef CONFIG_NET 5548 [PTR_TO_SOCKET] = &btf_sock_ids[BTF_SOCK_TYPE_SOCK], 5549 [PTR_TO_SOCK_COMMON] = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON], 5550 [PTR_TO_TCP_SOCK] = &btf_sock_ids[BTF_SOCK_TYPE_TCP], 5551 #endif 5552 [CONST_PTR_TO_MAP] = btf_bpf_map_id, 5553 }; 5554 5555 static bool is_trusted_reg(const struct bpf_reg_state *reg) 5556 { 5557 /* A referenced register is always trusted. */ 5558 if (reg->ref_obj_id) 5559 return true; 5560 5561 /* Types listed in the reg2btf_ids are always trusted */ 5562 if (reg2btf_ids[base_type(reg->type)]) 5563 return true; 5564 5565 /* If a register is not referenced, it is trusted if it has the 5566 * MEM_ALLOC or PTR_TRUSTED type modifiers, and no others. Some of the 5567 * other type modifiers may be safe, but we elect to take an opt-in 5568 * approach here as some (e.g. PTR_UNTRUSTED and PTR_MAYBE_NULL) are 5569 * not. 5570 * 5571 * Eventually, we should make PTR_TRUSTED the single source of truth 5572 * for whether a register is trusted. 5573 */ 5574 return type_flag(reg->type) & BPF_REG_TRUSTED_MODIFIERS && 5575 !bpf_type_has_unsafe_modifiers(reg->type); 5576 } 5577 5578 static bool is_rcu_reg(const struct bpf_reg_state *reg) 5579 { 5580 return reg->type & MEM_RCU; 5581 } 5582 5583 static void clear_trusted_flags(enum bpf_type_flag *flag) 5584 { 5585 *flag &= ~(BPF_REG_TRUSTED_MODIFIERS | MEM_RCU); 5586 } 5587 5588 static int check_pkt_ptr_alignment(struct bpf_verifier_env *env, 5589 const struct bpf_reg_state *reg, 5590 int off, int size, bool strict) 5591 { 5592 struct tnum reg_off; 5593 int ip_align; 5594 5595 /* Byte size accesses are always allowed. */ 5596 if (!strict || size == 1) 5597 return 0; 5598 5599 /* For platforms that do not have a Kconfig enabling 5600 * CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS the value of 5601 * NET_IP_ALIGN is universally set to '2'. And on platforms 5602 * that do set CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS, we get 5603 * to this code only in strict mode where we want to emulate 5604 * the NET_IP_ALIGN==2 checking. Therefore use an 5605 * unconditional IP align value of '2'. 5606 */ 5607 ip_align = 2; 5608 5609 reg_off = tnum_add(reg->var_off, tnum_const(ip_align + reg->off + off)); 5610 if (!tnum_is_aligned(reg_off, size)) { 5611 char tn_buf[48]; 5612 5613 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 5614 verbose(env, 5615 "misaligned packet access off %d+%s+%d+%d size %d\n", 5616 ip_align, tn_buf, reg->off, off, size); 5617 return -EACCES; 5618 } 5619 5620 return 0; 5621 } 5622 5623 static int check_generic_ptr_alignment(struct bpf_verifier_env *env, 5624 const struct bpf_reg_state *reg, 5625 const char *pointer_desc, 5626 int off, int size, bool strict) 5627 { 5628 struct tnum reg_off; 5629 5630 /* Byte size accesses are always allowed. */ 5631 if (!strict || size == 1) 5632 return 0; 5633 5634 reg_off = tnum_add(reg->var_off, tnum_const(reg->off + off)); 5635 if (!tnum_is_aligned(reg_off, size)) { 5636 char tn_buf[48]; 5637 5638 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 5639 verbose(env, "misaligned %saccess off %s+%d+%d size %d\n", 5640 pointer_desc, tn_buf, reg->off, off, size); 5641 return -EACCES; 5642 } 5643 5644 return 0; 5645 } 5646 5647 static int check_ptr_alignment(struct bpf_verifier_env *env, 5648 const struct bpf_reg_state *reg, int off, 5649 int size, bool strict_alignment_once) 5650 { 5651 bool strict = env->strict_alignment || strict_alignment_once; 5652 const char *pointer_desc = ""; 5653 5654 switch (reg->type) { 5655 case PTR_TO_PACKET: 5656 case PTR_TO_PACKET_META: 5657 /* Special case, because of NET_IP_ALIGN. Given metadata sits 5658 * right in front, treat it the very same way. 5659 */ 5660 return check_pkt_ptr_alignment(env, reg, off, size, strict); 5661 case PTR_TO_FLOW_KEYS: 5662 pointer_desc = "flow keys "; 5663 break; 5664 case PTR_TO_MAP_KEY: 5665 pointer_desc = "key "; 5666 break; 5667 case PTR_TO_MAP_VALUE: 5668 pointer_desc = "value "; 5669 break; 5670 case PTR_TO_CTX: 5671 pointer_desc = "context "; 5672 break; 5673 case PTR_TO_STACK: 5674 pointer_desc = "stack "; 5675 /* The stack spill tracking logic in check_stack_write_fixed_off() 5676 * and check_stack_read_fixed_off() relies on stack accesses being 5677 * aligned. 5678 */ 5679 strict = true; 5680 break; 5681 case PTR_TO_SOCKET: 5682 pointer_desc = "sock "; 5683 break; 5684 case PTR_TO_SOCK_COMMON: 5685 pointer_desc = "sock_common "; 5686 break; 5687 case PTR_TO_TCP_SOCK: 5688 pointer_desc = "tcp_sock "; 5689 break; 5690 case PTR_TO_XDP_SOCK: 5691 pointer_desc = "xdp_sock "; 5692 break; 5693 default: 5694 break; 5695 } 5696 return check_generic_ptr_alignment(env, reg, pointer_desc, off, size, 5697 strict); 5698 } 5699 5700 static int update_stack_depth(struct bpf_verifier_env *env, 5701 const struct bpf_func_state *func, 5702 int off) 5703 { 5704 u16 stack = env->subprog_info[func->subprogno].stack_depth; 5705 5706 if (stack >= -off) 5707 return 0; 5708 5709 /* update known max for given subprogram */ 5710 env->subprog_info[func->subprogno].stack_depth = -off; 5711 return 0; 5712 } 5713 5714 /* starting from main bpf function walk all instructions of the function 5715 * and recursively walk all callees that given function can call. 5716 * Ignore jump and exit insns. 5717 * Since recursion is prevented by check_cfg() this algorithm 5718 * only needs a local stack of MAX_CALL_FRAMES to remember callsites 5719 */ 5720 static int check_max_stack_depth_subprog(struct bpf_verifier_env *env, int idx) 5721 { 5722 struct bpf_subprog_info *subprog = env->subprog_info; 5723 struct bpf_insn *insn = env->prog->insnsi; 5724 int depth = 0, frame = 0, i, subprog_end; 5725 bool tail_call_reachable = false; 5726 int ret_insn[MAX_CALL_FRAMES]; 5727 int ret_prog[MAX_CALL_FRAMES]; 5728 int j; 5729 5730 i = subprog[idx].start; 5731 process_func: 5732 /* protect against potential stack overflow that might happen when 5733 * bpf2bpf calls get combined with tailcalls. Limit the caller's stack 5734 * depth for such case down to 256 so that the worst case scenario 5735 * would result in 8k stack size (32 which is tailcall limit * 256 = 5736 * 8k). 5737 * 5738 * To get the idea what might happen, see an example: 5739 * func1 -> sub rsp, 128 5740 * subfunc1 -> sub rsp, 256 5741 * tailcall1 -> add rsp, 256 5742 * func2 -> sub rsp, 192 (total stack size = 128 + 192 = 320) 5743 * subfunc2 -> sub rsp, 64 5744 * subfunc22 -> sub rsp, 128 5745 * tailcall2 -> add rsp, 128 5746 * func3 -> sub rsp, 32 (total stack size 128 + 192 + 64 + 32 = 416) 5747 * 5748 * tailcall will unwind the current stack frame but it will not get rid 5749 * of caller's stack as shown on the example above. 5750 */ 5751 if (idx && subprog[idx].has_tail_call && depth >= 256) { 5752 verbose(env, 5753 "tail_calls are not allowed when call stack of previous frames is %d bytes. Too large\n", 5754 depth); 5755 return -EACCES; 5756 } 5757 /* round up to 32-bytes, since this is granularity 5758 * of interpreter stack size 5759 */ 5760 depth += round_up(max_t(u32, subprog[idx].stack_depth, 1), 32); 5761 if (depth > MAX_BPF_STACK) { 5762 verbose(env, "combined stack size of %d calls is %d. Too large\n", 5763 frame + 1, depth); 5764 return -EACCES; 5765 } 5766 continue_func: 5767 subprog_end = subprog[idx + 1].start; 5768 for (; i < subprog_end; i++) { 5769 int next_insn, sidx; 5770 5771 if (bpf_pseudo_kfunc_call(insn + i) && !insn[i].off) { 5772 bool err = false; 5773 5774 if (!is_bpf_throw_kfunc(insn + i)) 5775 continue; 5776 if (subprog[idx].is_cb) 5777 err = true; 5778 for (int c = 0; c < frame && !err; c++) { 5779 if (subprog[ret_prog[c]].is_cb) { 5780 err = true; 5781 break; 5782 } 5783 } 5784 if (!err) 5785 continue; 5786 verbose(env, 5787 "bpf_throw kfunc (insn %d) cannot be called from callback subprog %d\n", 5788 i, idx); 5789 return -EINVAL; 5790 } 5791 5792 if (!bpf_pseudo_call(insn + i) && !bpf_pseudo_func(insn + i)) 5793 continue; 5794 /* remember insn and function to return to */ 5795 ret_insn[frame] = i + 1; 5796 ret_prog[frame] = idx; 5797 5798 /* find the callee */ 5799 next_insn = i + insn[i].imm + 1; 5800 sidx = find_subprog(env, next_insn); 5801 if (sidx < 0) { 5802 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n", 5803 next_insn); 5804 return -EFAULT; 5805 } 5806 if (subprog[sidx].is_async_cb) { 5807 if (subprog[sidx].has_tail_call) { 5808 verbose(env, "verifier bug. subprog has tail_call and async cb\n"); 5809 return -EFAULT; 5810 } 5811 /* async callbacks don't increase bpf prog stack size unless called directly */ 5812 if (!bpf_pseudo_call(insn + i)) 5813 continue; 5814 if (subprog[sidx].is_exception_cb) { 5815 verbose(env, "insn %d cannot call exception cb directly\n", i); 5816 return -EINVAL; 5817 } 5818 } 5819 i = next_insn; 5820 idx = sidx; 5821 5822 if (subprog[idx].has_tail_call) 5823 tail_call_reachable = true; 5824 5825 frame++; 5826 if (frame >= MAX_CALL_FRAMES) { 5827 verbose(env, "the call stack of %d frames is too deep !\n", 5828 frame); 5829 return -E2BIG; 5830 } 5831 goto process_func; 5832 } 5833 /* if tail call got detected across bpf2bpf calls then mark each of the 5834 * currently present subprog frames as tail call reachable subprogs; 5835 * this info will be utilized by JIT so that we will be preserving the 5836 * tail call counter throughout bpf2bpf calls combined with tailcalls 5837 */ 5838 if (tail_call_reachable) 5839 for (j = 0; j < frame; j++) { 5840 if (subprog[ret_prog[j]].is_exception_cb) { 5841 verbose(env, "cannot tail call within exception cb\n"); 5842 return -EINVAL; 5843 } 5844 subprog[ret_prog[j]].tail_call_reachable = true; 5845 } 5846 if (subprog[0].tail_call_reachable) 5847 env->prog->aux->tail_call_reachable = true; 5848 5849 /* end of for() loop means the last insn of the 'subprog' 5850 * was reached. Doesn't matter whether it was JA or EXIT 5851 */ 5852 if (frame == 0) 5853 return 0; 5854 depth -= round_up(max_t(u32, subprog[idx].stack_depth, 1), 32); 5855 frame--; 5856 i = ret_insn[frame]; 5857 idx = ret_prog[frame]; 5858 goto continue_func; 5859 } 5860 5861 static int check_max_stack_depth(struct bpf_verifier_env *env) 5862 { 5863 struct bpf_subprog_info *si = env->subprog_info; 5864 int ret; 5865 5866 for (int i = 0; i < env->subprog_cnt; i++) { 5867 if (!i || si[i].is_async_cb) { 5868 ret = check_max_stack_depth_subprog(env, i); 5869 if (ret < 0) 5870 return ret; 5871 } 5872 continue; 5873 } 5874 return 0; 5875 } 5876 5877 #ifndef CONFIG_BPF_JIT_ALWAYS_ON 5878 static int get_callee_stack_depth(struct bpf_verifier_env *env, 5879 const struct bpf_insn *insn, int idx) 5880 { 5881 int start = idx + insn->imm + 1, subprog; 5882 5883 subprog = find_subprog(env, start); 5884 if (subprog < 0) { 5885 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n", 5886 start); 5887 return -EFAULT; 5888 } 5889 return env->subprog_info[subprog].stack_depth; 5890 } 5891 #endif 5892 5893 static int __check_buffer_access(struct bpf_verifier_env *env, 5894 const char *buf_info, 5895 const struct bpf_reg_state *reg, 5896 int regno, int off, int size) 5897 { 5898 if (off < 0) { 5899 verbose(env, 5900 "R%d invalid %s buffer access: off=%d, size=%d\n", 5901 regno, buf_info, off, size); 5902 return -EACCES; 5903 } 5904 if (!tnum_is_const(reg->var_off) || reg->var_off.value) { 5905 char tn_buf[48]; 5906 5907 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 5908 verbose(env, 5909 "R%d invalid variable buffer offset: off=%d, var_off=%s\n", 5910 regno, off, tn_buf); 5911 return -EACCES; 5912 } 5913 5914 return 0; 5915 } 5916 5917 static int check_tp_buffer_access(struct bpf_verifier_env *env, 5918 const struct bpf_reg_state *reg, 5919 int regno, int off, int size) 5920 { 5921 int err; 5922 5923 err = __check_buffer_access(env, "tracepoint", reg, regno, off, size); 5924 if (err) 5925 return err; 5926 5927 if (off + size > env->prog->aux->max_tp_access) 5928 env->prog->aux->max_tp_access = off + size; 5929 5930 return 0; 5931 } 5932 5933 static int check_buffer_access(struct bpf_verifier_env *env, 5934 const struct bpf_reg_state *reg, 5935 int regno, int off, int size, 5936 bool zero_size_allowed, 5937 u32 *max_access) 5938 { 5939 const char *buf_info = type_is_rdonly_mem(reg->type) ? "rdonly" : "rdwr"; 5940 int err; 5941 5942 err = __check_buffer_access(env, buf_info, reg, regno, off, size); 5943 if (err) 5944 return err; 5945 5946 if (off + size > *max_access) 5947 *max_access = off + size; 5948 5949 return 0; 5950 } 5951 5952 /* BPF architecture zero extends alu32 ops into 64-bit registesr */ 5953 static void zext_32_to_64(struct bpf_reg_state *reg) 5954 { 5955 reg->var_off = tnum_subreg(reg->var_off); 5956 __reg_assign_32_into_64(reg); 5957 } 5958 5959 /* truncate register to smaller size (in bytes) 5960 * must be called with size < BPF_REG_SIZE 5961 */ 5962 static void coerce_reg_to_size(struct bpf_reg_state *reg, int size) 5963 { 5964 u64 mask; 5965 5966 /* clear high bits in bit representation */ 5967 reg->var_off = tnum_cast(reg->var_off, size); 5968 5969 /* fix arithmetic bounds */ 5970 mask = ((u64)1 << (size * 8)) - 1; 5971 if ((reg->umin_value & ~mask) == (reg->umax_value & ~mask)) { 5972 reg->umin_value &= mask; 5973 reg->umax_value &= mask; 5974 } else { 5975 reg->umin_value = 0; 5976 reg->umax_value = mask; 5977 } 5978 reg->smin_value = reg->umin_value; 5979 reg->smax_value = reg->umax_value; 5980 5981 /* If size is smaller than 32bit register the 32bit register 5982 * values are also truncated so we push 64-bit bounds into 5983 * 32-bit bounds. Above were truncated < 32-bits already. 5984 */ 5985 if (size >= 4) 5986 return; 5987 __reg_combine_64_into_32(reg); 5988 } 5989 5990 static void set_sext64_default_val(struct bpf_reg_state *reg, int size) 5991 { 5992 if (size == 1) { 5993 reg->smin_value = reg->s32_min_value = S8_MIN; 5994 reg->smax_value = reg->s32_max_value = S8_MAX; 5995 } else if (size == 2) { 5996 reg->smin_value = reg->s32_min_value = S16_MIN; 5997 reg->smax_value = reg->s32_max_value = S16_MAX; 5998 } else { 5999 /* size == 4 */ 6000 reg->smin_value = reg->s32_min_value = S32_MIN; 6001 reg->smax_value = reg->s32_max_value = S32_MAX; 6002 } 6003 reg->umin_value = reg->u32_min_value = 0; 6004 reg->umax_value = U64_MAX; 6005 reg->u32_max_value = U32_MAX; 6006 reg->var_off = tnum_unknown; 6007 } 6008 6009 static void coerce_reg_to_size_sx(struct bpf_reg_state *reg, int size) 6010 { 6011 s64 init_s64_max, init_s64_min, s64_max, s64_min, u64_cval; 6012 u64 top_smax_value, top_smin_value; 6013 u64 num_bits = size * 8; 6014 6015 if (tnum_is_const(reg->var_off)) { 6016 u64_cval = reg->var_off.value; 6017 if (size == 1) 6018 reg->var_off = tnum_const((s8)u64_cval); 6019 else if (size == 2) 6020 reg->var_off = tnum_const((s16)u64_cval); 6021 else 6022 /* size == 4 */ 6023 reg->var_off = tnum_const((s32)u64_cval); 6024 6025 u64_cval = reg->var_off.value; 6026 reg->smax_value = reg->smin_value = u64_cval; 6027 reg->umax_value = reg->umin_value = u64_cval; 6028 reg->s32_max_value = reg->s32_min_value = u64_cval; 6029 reg->u32_max_value = reg->u32_min_value = u64_cval; 6030 return; 6031 } 6032 6033 top_smax_value = ((u64)reg->smax_value >> num_bits) << num_bits; 6034 top_smin_value = ((u64)reg->smin_value >> num_bits) << num_bits; 6035 6036 if (top_smax_value != top_smin_value) 6037 goto out; 6038 6039 /* find the s64_min and s64_min after sign extension */ 6040 if (size == 1) { 6041 init_s64_max = (s8)reg->smax_value; 6042 init_s64_min = (s8)reg->smin_value; 6043 } else if (size == 2) { 6044 init_s64_max = (s16)reg->smax_value; 6045 init_s64_min = (s16)reg->smin_value; 6046 } else { 6047 init_s64_max = (s32)reg->smax_value; 6048 init_s64_min = (s32)reg->smin_value; 6049 } 6050 6051 s64_max = max(init_s64_max, init_s64_min); 6052 s64_min = min(init_s64_max, init_s64_min); 6053 6054 /* both of s64_max/s64_min positive or negative */ 6055 if ((s64_max >= 0) == (s64_min >= 0)) { 6056 reg->smin_value = reg->s32_min_value = s64_min; 6057 reg->smax_value = reg->s32_max_value = s64_max; 6058 reg->umin_value = reg->u32_min_value = s64_min; 6059 reg->umax_value = reg->u32_max_value = s64_max; 6060 reg->var_off = tnum_range(s64_min, s64_max); 6061 return; 6062 } 6063 6064 out: 6065 set_sext64_default_val(reg, size); 6066 } 6067 6068 static void set_sext32_default_val(struct bpf_reg_state *reg, int size) 6069 { 6070 if (size == 1) { 6071 reg->s32_min_value = S8_MIN; 6072 reg->s32_max_value = S8_MAX; 6073 } else { 6074 /* size == 2 */ 6075 reg->s32_min_value = S16_MIN; 6076 reg->s32_max_value = S16_MAX; 6077 } 6078 reg->u32_min_value = 0; 6079 reg->u32_max_value = U32_MAX; 6080 } 6081 6082 static void coerce_subreg_to_size_sx(struct bpf_reg_state *reg, int size) 6083 { 6084 s32 init_s32_max, init_s32_min, s32_max, s32_min, u32_val; 6085 u32 top_smax_value, top_smin_value; 6086 u32 num_bits = size * 8; 6087 6088 if (tnum_is_const(reg->var_off)) { 6089 u32_val = reg->var_off.value; 6090 if (size == 1) 6091 reg->var_off = tnum_const((s8)u32_val); 6092 else 6093 reg->var_off = tnum_const((s16)u32_val); 6094 6095 u32_val = reg->var_off.value; 6096 reg->s32_min_value = reg->s32_max_value = u32_val; 6097 reg->u32_min_value = reg->u32_max_value = u32_val; 6098 return; 6099 } 6100 6101 top_smax_value = ((u32)reg->s32_max_value >> num_bits) << num_bits; 6102 top_smin_value = ((u32)reg->s32_min_value >> num_bits) << num_bits; 6103 6104 if (top_smax_value != top_smin_value) 6105 goto out; 6106 6107 /* find the s32_min and s32_min after sign extension */ 6108 if (size == 1) { 6109 init_s32_max = (s8)reg->s32_max_value; 6110 init_s32_min = (s8)reg->s32_min_value; 6111 } else { 6112 /* size == 2 */ 6113 init_s32_max = (s16)reg->s32_max_value; 6114 init_s32_min = (s16)reg->s32_min_value; 6115 } 6116 s32_max = max(init_s32_max, init_s32_min); 6117 s32_min = min(init_s32_max, init_s32_min); 6118 6119 if ((s32_min >= 0) == (s32_max >= 0)) { 6120 reg->s32_min_value = s32_min; 6121 reg->s32_max_value = s32_max; 6122 reg->u32_min_value = (u32)s32_min; 6123 reg->u32_max_value = (u32)s32_max; 6124 return; 6125 } 6126 6127 out: 6128 set_sext32_default_val(reg, size); 6129 } 6130 6131 static bool bpf_map_is_rdonly(const struct bpf_map *map) 6132 { 6133 /* A map is considered read-only if the following condition are true: 6134 * 6135 * 1) BPF program side cannot change any of the map content. The 6136 * BPF_F_RDONLY_PROG flag is throughout the lifetime of a map 6137 * and was set at map creation time. 6138 * 2) The map value(s) have been initialized from user space by a 6139 * loader and then "frozen", such that no new map update/delete 6140 * operations from syscall side are possible for the rest of 6141 * the map's lifetime from that point onwards. 6142 * 3) Any parallel/pending map update/delete operations from syscall 6143 * side have been completed. Only after that point, it's safe to 6144 * assume that map value(s) are immutable. 6145 */ 6146 return (map->map_flags & BPF_F_RDONLY_PROG) && 6147 READ_ONCE(map->frozen) && 6148 !bpf_map_write_active(map); 6149 } 6150 6151 static int bpf_map_direct_read(struct bpf_map *map, int off, int size, u64 *val, 6152 bool is_ldsx) 6153 { 6154 void *ptr; 6155 u64 addr; 6156 int err; 6157 6158 err = map->ops->map_direct_value_addr(map, &addr, off); 6159 if (err) 6160 return err; 6161 ptr = (void *)(long)addr + off; 6162 6163 switch (size) { 6164 case sizeof(u8): 6165 *val = is_ldsx ? (s64)*(s8 *)ptr : (u64)*(u8 *)ptr; 6166 break; 6167 case sizeof(u16): 6168 *val = is_ldsx ? (s64)*(s16 *)ptr : (u64)*(u16 *)ptr; 6169 break; 6170 case sizeof(u32): 6171 *val = is_ldsx ? (s64)*(s32 *)ptr : (u64)*(u32 *)ptr; 6172 break; 6173 case sizeof(u64): 6174 *val = *(u64 *)ptr; 6175 break; 6176 default: 6177 return -EINVAL; 6178 } 6179 return 0; 6180 } 6181 6182 #define BTF_TYPE_SAFE_RCU(__type) __PASTE(__type, __safe_rcu) 6183 #define BTF_TYPE_SAFE_RCU_OR_NULL(__type) __PASTE(__type, __safe_rcu_or_null) 6184 #define BTF_TYPE_SAFE_TRUSTED(__type) __PASTE(__type, __safe_trusted) 6185 6186 /* 6187 * Allow list few fields as RCU trusted or full trusted. 6188 * This logic doesn't allow mix tagging and will be removed once GCC supports 6189 * btf_type_tag. 6190 */ 6191 6192 /* RCU trusted: these fields are trusted in RCU CS and never NULL */ 6193 BTF_TYPE_SAFE_RCU(struct task_struct) { 6194 const cpumask_t *cpus_ptr; 6195 struct css_set __rcu *cgroups; 6196 struct task_struct __rcu *real_parent; 6197 struct task_struct *group_leader; 6198 }; 6199 6200 BTF_TYPE_SAFE_RCU(struct cgroup) { 6201 /* cgrp->kn is always accessible as documented in kernel/cgroup/cgroup.c */ 6202 struct kernfs_node *kn; 6203 }; 6204 6205 BTF_TYPE_SAFE_RCU(struct css_set) { 6206 struct cgroup *dfl_cgrp; 6207 }; 6208 6209 /* RCU trusted: these fields are trusted in RCU CS and can be NULL */ 6210 BTF_TYPE_SAFE_RCU_OR_NULL(struct mm_struct) { 6211 struct file __rcu *exe_file; 6212 }; 6213 6214 /* skb->sk, req->sk are not RCU protected, but we mark them as such 6215 * because bpf prog accessible sockets are SOCK_RCU_FREE. 6216 */ 6217 BTF_TYPE_SAFE_RCU_OR_NULL(struct sk_buff) { 6218 struct sock *sk; 6219 }; 6220 6221 BTF_TYPE_SAFE_RCU_OR_NULL(struct request_sock) { 6222 struct sock *sk; 6223 }; 6224 6225 /* full trusted: these fields are trusted even outside of RCU CS and never NULL */ 6226 BTF_TYPE_SAFE_TRUSTED(struct bpf_iter_meta) { 6227 struct seq_file *seq; 6228 }; 6229 6230 BTF_TYPE_SAFE_TRUSTED(struct bpf_iter__task) { 6231 struct bpf_iter_meta *meta; 6232 struct task_struct *task; 6233 }; 6234 6235 BTF_TYPE_SAFE_TRUSTED(struct linux_binprm) { 6236 struct file *file; 6237 }; 6238 6239 BTF_TYPE_SAFE_TRUSTED(struct file) { 6240 struct inode *f_inode; 6241 }; 6242 6243 BTF_TYPE_SAFE_TRUSTED(struct dentry) { 6244 /* no negative dentry-s in places where bpf can see it */ 6245 struct inode *d_inode; 6246 }; 6247 6248 BTF_TYPE_SAFE_TRUSTED(struct socket) { 6249 struct sock *sk; 6250 }; 6251 6252 static bool type_is_rcu(struct bpf_verifier_env *env, 6253 struct bpf_reg_state *reg, 6254 const char *field_name, u32 btf_id) 6255 { 6256 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct task_struct)); 6257 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct cgroup)); 6258 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct css_set)); 6259 6260 return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_rcu"); 6261 } 6262 6263 static bool type_is_rcu_or_null(struct bpf_verifier_env *env, 6264 struct bpf_reg_state *reg, 6265 const char *field_name, u32 btf_id) 6266 { 6267 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct mm_struct)); 6268 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct sk_buff)); 6269 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct request_sock)); 6270 6271 return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_rcu_or_null"); 6272 } 6273 6274 static bool type_is_trusted(struct bpf_verifier_env *env, 6275 struct bpf_reg_state *reg, 6276 const char *field_name, u32 btf_id) 6277 { 6278 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct bpf_iter_meta)); 6279 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct bpf_iter__task)); 6280 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct linux_binprm)); 6281 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct file)); 6282 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct dentry)); 6283 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct socket)); 6284 6285 return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_trusted"); 6286 } 6287 6288 static int check_ptr_to_btf_access(struct bpf_verifier_env *env, 6289 struct bpf_reg_state *regs, 6290 int regno, int off, int size, 6291 enum bpf_access_type atype, 6292 int value_regno) 6293 { 6294 struct bpf_reg_state *reg = regs + regno; 6295 const struct btf_type *t = btf_type_by_id(reg->btf, reg->btf_id); 6296 const char *tname = btf_name_by_offset(reg->btf, t->name_off); 6297 const char *field_name = NULL; 6298 enum bpf_type_flag flag = 0; 6299 u32 btf_id = 0; 6300 int ret; 6301 6302 if (!env->allow_ptr_leaks) { 6303 verbose(env, 6304 "'struct %s' access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n", 6305 tname); 6306 return -EPERM; 6307 } 6308 if (!env->prog->gpl_compatible && btf_is_kernel(reg->btf)) { 6309 verbose(env, 6310 "Cannot access kernel 'struct %s' from non-GPL compatible program\n", 6311 tname); 6312 return -EINVAL; 6313 } 6314 if (off < 0) { 6315 verbose(env, 6316 "R%d is ptr_%s invalid negative access: off=%d\n", 6317 regno, tname, off); 6318 return -EACCES; 6319 } 6320 if (!tnum_is_const(reg->var_off) || reg->var_off.value) { 6321 char tn_buf[48]; 6322 6323 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 6324 verbose(env, 6325 "R%d is ptr_%s invalid variable offset: off=%d, var_off=%s\n", 6326 regno, tname, off, tn_buf); 6327 return -EACCES; 6328 } 6329 6330 if (reg->type & MEM_USER) { 6331 verbose(env, 6332 "R%d is ptr_%s access user memory: off=%d\n", 6333 regno, tname, off); 6334 return -EACCES; 6335 } 6336 6337 if (reg->type & MEM_PERCPU) { 6338 verbose(env, 6339 "R%d is ptr_%s access percpu memory: off=%d\n", 6340 regno, tname, off); 6341 return -EACCES; 6342 } 6343 6344 if (env->ops->btf_struct_access && !type_is_alloc(reg->type) && atype == BPF_WRITE) { 6345 if (!btf_is_kernel(reg->btf)) { 6346 verbose(env, "verifier internal error: reg->btf must be kernel btf\n"); 6347 return -EFAULT; 6348 } 6349 ret = env->ops->btf_struct_access(&env->log, reg, off, size); 6350 } else { 6351 /* Writes are permitted with default btf_struct_access for 6352 * program allocated objects (which always have ref_obj_id > 0), 6353 * but not for untrusted PTR_TO_BTF_ID | MEM_ALLOC. 6354 */ 6355 if (atype != BPF_READ && !type_is_ptr_alloc_obj(reg->type)) { 6356 verbose(env, "only read is supported\n"); 6357 return -EACCES; 6358 } 6359 6360 if (type_is_alloc(reg->type) && !type_is_non_owning_ref(reg->type) && 6361 !(reg->type & MEM_RCU) && !reg->ref_obj_id) { 6362 verbose(env, "verifier internal error: ref_obj_id for allocated object must be non-zero\n"); 6363 return -EFAULT; 6364 } 6365 6366 ret = btf_struct_access(&env->log, reg, off, size, atype, &btf_id, &flag, &field_name); 6367 } 6368 6369 if (ret < 0) 6370 return ret; 6371 6372 if (ret != PTR_TO_BTF_ID) { 6373 /* just mark; */ 6374 6375 } else if (type_flag(reg->type) & PTR_UNTRUSTED) { 6376 /* If this is an untrusted pointer, all pointers formed by walking it 6377 * also inherit the untrusted flag. 6378 */ 6379 flag = PTR_UNTRUSTED; 6380 6381 } else if (is_trusted_reg(reg) || is_rcu_reg(reg)) { 6382 /* By default any pointer obtained from walking a trusted pointer is no 6383 * longer trusted, unless the field being accessed has explicitly been 6384 * marked as inheriting its parent's state of trust (either full or RCU). 6385 * For example: 6386 * 'cgroups' pointer is untrusted if task->cgroups dereference 6387 * happened in a sleepable program outside of bpf_rcu_read_lock() 6388 * section. In a non-sleepable program it's trusted while in RCU CS (aka MEM_RCU). 6389 * Note bpf_rcu_read_unlock() converts MEM_RCU pointers to PTR_UNTRUSTED. 6390 * 6391 * A regular RCU-protected pointer with __rcu tag can also be deemed 6392 * trusted if we are in an RCU CS. Such pointer can be NULL. 6393 */ 6394 if (type_is_trusted(env, reg, field_name, btf_id)) { 6395 flag |= PTR_TRUSTED; 6396 } else if (in_rcu_cs(env) && !type_may_be_null(reg->type)) { 6397 if (type_is_rcu(env, reg, field_name, btf_id)) { 6398 /* ignore __rcu tag and mark it MEM_RCU */ 6399 flag |= MEM_RCU; 6400 } else if (flag & MEM_RCU || 6401 type_is_rcu_or_null(env, reg, field_name, btf_id)) { 6402 /* __rcu tagged pointers can be NULL */ 6403 flag |= MEM_RCU | PTR_MAYBE_NULL; 6404 6405 /* We always trust them */ 6406 if (type_is_rcu_or_null(env, reg, field_name, btf_id) && 6407 flag & PTR_UNTRUSTED) 6408 flag &= ~PTR_UNTRUSTED; 6409 } else if (flag & (MEM_PERCPU | MEM_USER)) { 6410 /* keep as-is */ 6411 } else { 6412 /* walking unknown pointers yields old deprecated PTR_TO_BTF_ID */ 6413 clear_trusted_flags(&flag); 6414 } 6415 } else { 6416 /* 6417 * If not in RCU CS or MEM_RCU pointer can be NULL then 6418 * aggressively mark as untrusted otherwise such 6419 * pointers will be plain PTR_TO_BTF_ID without flags 6420 * and will be allowed to be passed into helpers for 6421 * compat reasons. 6422 */ 6423 flag = PTR_UNTRUSTED; 6424 } 6425 } else { 6426 /* Old compat. Deprecated */ 6427 clear_trusted_flags(&flag); 6428 } 6429 6430 if (atype == BPF_READ && value_regno >= 0) 6431 mark_btf_ld_reg(env, regs, value_regno, ret, reg->btf, btf_id, flag); 6432 6433 return 0; 6434 } 6435 6436 static int check_ptr_to_map_access(struct bpf_verifier_env *env, 6437 struct bpf_reg_state *regs, 6438 int regno, int off, int size, 6439 enum bpf_access_type atype, 6440 int value_regno) 6441 { 6442 struct bpf_reg_state *reg = regs + regno; 6443 struct bpf_map *map = reg->map_ptr; 6444 struct bpf_reg_state map_reg; 6445 enum bpf_type_flag flag = 0; 6446 const struct btf_type *t; 6447 const char *tname; 6448 u32 btf_id; 6449 int ret; 6450 6451 if (!btf_vmlinux) { 6452 verbose(env, "map_ptr access not supported without CONFIG_DEBUG_INFO_BTF\n"); 6453 return -ENOTSUPP; 6454 } 6455 6456 if (!map->ops->map_btf_id || !*map->ops->map_btf_id) { 6457 verbose(env, "map_ptr access not supported for map type %d\n", 6458 map->map_type); 6459 return -ENOTSUPP; 6460 } 6461 6462 t = btf_type_by_id(btf_vmlinux, *map->ops->map_btf_id); 6463 tname = btf_name_by_offset(btf_vmlinux, t->name_off); 6464 6465 if (!env->allow_ptr_leaks) { 6466 verbose(env, 6467 "'struct %s' access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n", 6468 tname); 6469 return -EPERM; 6470 } 6471 6472 if (off < 0) { 6473 verbose(env, "R%d is %s invalid negative access: off=%d\n", 6474 regno, tname, off); 6475 return -EACCES; 6476 } 6477 6478 if (atype != BPF_READ) { 6479 verbose(env, "only read from %s is supported\n", tname); 6480 return -EACCES; 6481 } 6482 6483 /* Simulate access to a PTR_TO_BTF_ID */ 6484 memset(&map_reg, 0, sizeof(map_reg)); 6485 mark_btf_ld_reg(env, &map_reg, 0, PTR_TO_BTF_ID, btf_vmlinux, *map->ops->map_btf_id, 0); 6486 ret = btf_struct_access(&env->log, &map_reg, off, size, atype, &btf_id, &flag, NULL); 6487 if (ret < 0) 6488 return ret; 6489 6490 if (value_regno >= 0) 6491 mark_btf_ld_reg(env, regs, value_regno, ret, btf_vmlinux, btf_id, flag); 6492 6493 return 0; 6494 } 6495 6496 /* Check that the stack access at the given offset is within bounds. The 6497 * maximum valid offset is -1. 6498 * 6499 * The minimum valid offset is -MAX_BPF_STACK for writes, and 6500 * -state->allocated_stack for reads. 6501 */ 6502 static int check_stack_slot_within_bounds(int off, 6503 struct bpf_func_state *state, 6504 enum bpf_access_type t) 6505 { 6506 int min_valid_off; 6507 6508 if (t == BPF_WRITE) 6509 min_valid_off = -MAX_BPF_STACK; 6510 else 6511 min_valid_off = -state->allocated_stack; 6512 6513 if (off < min_valid_off || off > -1) 6514 return -EACCES; 6515 return 0; 6516 } 6517 6518 /* Check that the stack access at 'regno + off' falls within the maximum stack 6519 * bounds. 6520 * 6521 * 'off' includes `regno->offset`, but not its dynamic part (if any). 6522 */ 6523 static int check_stack_access_within_bounds( 6524 struct bpf_verifier_env *env, 6525 int regno, int off, int access_size, 6526 enum bpf_access_src src, enum bpf_access_type type) 6527 { 6528 struct bpf_reg_state *regs = cur_regs(env); 6529 struct bpf_reg_state *reg = regs + regno; 6530 struct bpf_func_state *state = func(env, reg); 6531 int min_off, max_off; 6532 int err; 6533 char *err_extra; 6534 6535 if (src == ACCESS_HELPER) 6536 /* We don't know if helpers are reading or writing (or both). */ 6537 err_extra = " indirect access to"; 6538 else if (type == BPF_READ) 6539 err_extra = " read from"; 6540 else 6541 err_extra = " write to"; 6542 6543 if (tnum_is_const(reg->var_off)) { 6544 min_off = reg->var_off.value + off; 6545 if (access_size > 0) 6546 max_off = min_off + access_size - 1; 6547 else 6548 max_off = min_off; 6549 } else { 6550 if (reg->smax_value >= BPF_MAX_VAR_OFF || 6551 reg->smin_value <= -BPF_MAX_VAR_OFF) { 6552 verbose(env, "invalid unbounded variable-offset%s stack R%d\n", 6553 err_extra, regno); 6554 return -EACCES; 6555 } 6556 min_off = reg->smin_value + off; 6557 if (access_size > 0) 6558 max_off = reg->smax_value + off + access_size - 1; 6559 else 6560 max_off = min_off; 6561 } 6562 6563 err = check_stack_slot_within_bounds(min_off, state, type); 6564 if (!err) 6565 err = check_stack_slot_within_bounds(max_off, state, type); 6566 6567 if (err) { 6568 if (tnum_is_const(reg->var_off)) { 6569 verbose(env, "invalid%s stack R%d off=%d size=%d\n", 6570 err_extra, regno, off, access_size); 6571 } else { 6572 char tn_buf[48]; 6573 6574 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 6575 verbose(env, "invalid variable-offset%s stack R%d var_off=%s size=%d\n", 6576 err_extra, regno, tn_buf, access_size); 6577 } 6578 } 6579 return err; 6580 } 6581 6582 /* check whether memory at (regno + off) is accessible for t = (read | write) 6583 * if t==write, value_regno is a register which value is stored into memory 6584 * if t==read, value_regno is a register which will receive the value from memory 6585 * if t==write && value_regno==-1, some unknown value is stored into memory 6586 * if t==read && value_regno==-1, don't care what we read from memory 6587 */ 6588 static int check_mem_access(struct bpf_verifier_env *env, int insn_idx, u32 regno, 6589 int off, int bpf_size, enum bpf_access_type t, 6590 int value_regno, bool strict_alignment_once, bool is_ldsx) 6591 { 6592 struct bpf_reg_state *regs = cur_regs(env); 6593 struct bpf_reg_state *reg = regs + regno; 6594 struct bpf_func_state *state; 6595 int size, err = 0; 6596 6597 size = bpf_size_to_bytes(bpf_size); 6598 if (size < 0) 6599 return size; 6600 6601 /* alignment checks will add in reg->off themselves */ 6602 err = check_ptr_alignment(env, reg, off, size, strict_alignment_once); 6603 if (err) 6604 return err; 6605 6606 /* for access checks, reg->off is just part of off */ 6607 off += reg->off; 6608 6609 if (reg->type == PTR_TO_MAP_KEY) { 6610 if (t == BPF_WRITE) { 6611 verbose(env, "write to change key R%d not allowed\n", regno); 6612 return -EACCES; 6613 } 6614 6615 err = check_mem_region_access(env, regno, off, size, 6616 reg->map_ptr->key_size, false); 6617 if (err) 6618 return err; 6619 if (value_regno >= 0) 6620 mark_reg_unknown(env, regs, value_regno); 6621 } else if (reg->type == PTR_TO_MAP_VALUE) { 6622 struct btf_field *kptr_field = NULL; 6623 6624 if (t == BPF_WRITE && value_regno >= 0 && 6625 is_pointer_value(env, value_regno)) { 6626 verbose(env, "R%d leaks addr into map\n", value_regno); 6627 return -EACCES; 6628 } 6629 err = check_map_access_type(env, regno, off, size, t); 6630 if (err) 6631 return err; 6632 err = check_map_access(env, regno, off, size, false, ACCESS_DIRECT); 6633 if (err) 6634 return err; 6635 if (tnum_is_const(reg->var_off)) 6636 kptr_field = btf_record_find(reg->map_ptr->record, 6637 off + reg->var_off.value, BPF_KPTR); 6638 if (kptr_field) { 6639 err = check_map_kptr_access(env, regno, value_regno, insn_idx, kptr_field); 6640 } else if (t == BPF_READ && value_regno >= 0) { 6641 struct bpf_map *map = reg->map_ptr; 6642 6643 /* if map is read-only, track its contents as scalars */ 6644 if (tnum_is_const(reg->var_off) && 6645 bpf_map_is_rdonly(map) && 6646 map->ops->map_direct_value_addr) { 6647 int map_off = off + reg->var_off.value; 6648 u64 val = 0; 6649 6650 err = bpf_map_direct_read(map, map_off, size, 6651 &val, is_ldsx); 6652 if (err) 6653 return err; 6654 6655 regs[value_regno].type = SCALAR_VALUE; 6656 __mark_reg_known(®s[value_regno], val); 6657 } else { 6658 mark_reg_unknown(env, regs, value_regno); 6659 } 6660 } 6661 } else if (base_type(reg->type) == PTR_TO_MEM) { 6662 bool rdonly_mem = type_is_rdonly_mem(reg->type); 6663 6664 if (type_may_be_null(reg->type)) { 6665 verbose(env, "R%d invalid mem access '%s'\n", regno, 6666 reg_type_str(env, reg->type)); 6667 return -EACCES; 6668 } 6669 6670 if (t == BPF_WRITE && rdonly_mem) { 6671 verbose(env, "R%d cannot write into %s\n", 6672 regno, reg_type_str(env, reg->type)); 6673 return -EACCES; 6674 } 6675 6676 if (t == BPF_WRITE && value_regno >= 0 && 6677 is_pointer_value(env, value_regno)) { 6678 verbose(env, "R%d leaks addr into mem\n", value_regno); 6679 return -EACCES; 6680 } 6681 6682 err = check_mem_region_access(env, regno, off, size, 6683 reg->mem_size, false); 6684 if (!err && value_regno >= 0 && (t == BPF_READ || rdonly_mem)) 6685 mark_reg_unknown(env, regs, value_regno); 6686 } else if (reg->type == PTR_TO_CTX) { 6687 enum bpf_reg_type reg_type = SCALAR_VALUE; 6688 struct btf *btf = NULL; 6689 u32 btf_id = 0; 6690 6691 if (t == BPF_WRITE && value_regno >= 0 && 6692 is_pointer_value(env, value_regno)) { 6693 verbose(env, "R%d leaks addr into ctx\n", value_regno); 6694 return -EACCES; 6695 } 6696 6697 err = check_ptr_off_reg(env, reg, regno); 6698 if (err < 0) 6699 return err; 6700 6701 err = check_ctx_access(env, insn_idx, off, size, t, ®_type, &btf, 6702 &btf_id); 6703 if (err) 6704 verbose_linfo(env, insn_idx, "; "); 6705 if (!err && t == BPF_READ && value_regno >= 0) { 6706 /* ctx access returns either a scalar, or a 6707 * PTR_TO_PACKET[_META,_END]. In the latter 6708 * case, we know the offset is zero. 6709 */ 6710 if (reg_type == SCALAR_VALUE) { 6711 mark_reg_unknown(env, regs, value_regno); 6712 } else { 6713 mark_reg_known_zero(env, regs, 6714 value_regno); 6715 if (type_may_be_null(reg_type)) 6716 regs[value_regno].id = ++env->id_gen; 6717 /* A load of ctx field could have different 6718 * actual load size with the one encoded in the 6719 * insn. When the dst is PTR, it is for sure not 6720 * a sub-register. 6721 */ 6722 regs[value_regno].subreg_def = DEF_NOT_SUBREG; 6723 if (base_type(reg_type) == PTR_TO_BTF_ID) { 6724 regs[value_regno].btf = btf; 6725 regs[value_regno].btf_id = btf_id; 6726 } 6727 } 6728 regs[value_regno].type = reg_type; 6729 } 6730 6731 } else if (reg->type == PTR_TO_STACK) { 6732 /* Basic bounds checks. */ 6733 err = check_stack_access_within_bounds(env, regno, off, size, ACCESS_DIRECT, t); 6734 if (err) 6735 return err; 6736 6737 state = func(env, reg); 6738 err = update_stack_depth(env, state, off); 6739 if (err) 6740 return err; 6741 6742 if (t == BPF_READ) 6743 err = check_stack_read(env, regno, off, size, 6744 value_regno); 6745 else 6746 err = check_stack_write(env, regno, off, size, 6747 value_regno, insn_idx); 6748 } else if (reg_is_pkt_pointer(reg)) { 6749 if (t == BPF_WRITE && !may_access_direct_pkt_data(env, NULL, t)) { 6750 verbose(env, "cannot write into packet\n"); 6751 return -EACCES; 6752 } 6753 if (t == BPF_WRITE && value_regno >= 0 && 6754 is_pointer_value(env, value_regno)) { 6755 verbose(env, "R%d leaks addr into packet\n", 6756 value_regno); 6757 return -EACCES; 6758 } 6759 err = check_packet_access(env, regno, off, size, false); 6760 if (!err && t == BPF_READ && value_regno >= 0) 6761 mark_reg_unknown(env, regs, value_regno); 6762 } else if (reg->type == PTR_TO_FLOW_KEYS) { 6763 if (t == BPF_WRITE && value_regno >= 0 && 6764 is_pointer_value(env, value_regno)) { 6765 verbose(env, "R%d leaks addr into flow keys\n", 6766 value_regno); 6767 return -EACCES; 6768 } 6769 6770 err = check_flow_keys_access(env, off, size); 6771 if (!err && t == BPF_READ && value_regno >= 0) 6772 mark_reg_unknown(env, regs, value_regno); 6773 } else if (type_is_sk_pointer(reg->type)) { 6774 if (t == BPF_WRITE) { 6775 verbose(env, "R%d cannot write into %s\n", 6776 regno, reg_type_str(env, reg->type)); 6777 return -EACCES; 6778 } 6779 err = check_sock_access(env, insn_idx, regno, off, size, t); 6780 if (!err && value_regno >= 0) 6781 mark_reg_unknown(env, regs, value_regno); 6782 } else if (reg->type == PTR_TO_TP_BUFFER) { 6783 err = check_tp_buffer_access(env, reg, regno, off, size); 6784 if (!err && t == BPF_READ && value_regno >= 0) 6785 mark_reg_unknown(env, regs, value_regno); 6786 } else if (base_type(reg->type) == PTR_TO_BTF_ID && 6787 !type_may_be_null(reg->type)) { 6788 err = check_ptr_to_btf_access(env, regs, regno, off, size, t, 6789 value_regno); 6790 } else if (reg->type == CONST_PTR_TO_MAP) { 6791 err = check_ptr_to_map_access(env, regs, regno, off, size, t, 6792 value_regno); 6793 } else if (base_type(reg->type) == PTR_TO_BUF) { 6794 bool rdonly_mem = type_is_rdonly_mem(reg->type); 6795 u32 *max_access; 6796 6797 if (rdonly_mem) { 6798 if (t == BPF_WRITE) { 6799 verbose(env, "R%d cannot write into %s\n", 6800 regno, reg_type_str(env, reg->type)); 6801 return -EACCES; 6802 } 6803 max_access = &env->prog->aux->max_rdonly_access; 6804 } else { 6805 max_access = &env->prog->aux->max_rdwr_access; 6806 } 6807 6808 err = check_buffer_access(env, reg, regno, off, size, false, 6809 max_access); 6810 6811 if (!err && value_regno >= 0 && (rdonly_mem || t == BPF_READ)) 6812 mark_reg_unknown(env, regs, value_regno); 6813 } else { 6814 verbose(env, "R%d invalid mem access '%s'\n", regno, 6815 reg_type_str(env, reg->type)); 6816 return -EACCES; 6817 } 6818 6819 if (!err && size < BPF_REG_SIZE && value_regno >= 0 && t == BPF_READ && 6820 regs[value_regno].type == SCALAR_VALUE) { 6821 if (!is_ldsx) 6822 /* b/h/w load zero-extends, mark upper bits as known 0 */ 6823 coerce_reg_to_size(®s[value_regno], size); 6824 else 6825 coerce_reg_to_size_sx(®s[value_regno], size); 6826 } 6827 return err; 6828 } 6829 6830 static int check_atomic(struct bpf_verifier_env *env, int insn_idx, struct bpf_insn *insn) 6831 { 6832 int load_reg; 6833 int err; 6834 6835 switch (insn->imm) { 6836 case BPF_ADD: 6837 case BPF_ADD | BPF_FETCH: 6838 case BPF_AND: 6839 case BPF_AND | BPF_FETCH: 6840 case BPF_OR: 6841 case BPF_OR | BPF_FETCH: 6842 case BPF_XOR: 6843 case BPF_XOR | BPF_FETCH: 6844 case BPF_XCHG: 6845 case BPF_CMPXCHG: 6846 break; 6847 default: 6848 verbose(env, "BPF_ATOMIC uses invalid atomic opcode %02x\n", insn->imm); 6849 return -EINVAL; 6850 } 6851 6852 if (BPF_SIZE(insn->code) != BPF_W && BPF_SIZE(insn->code) != BPF_DW) { 6853 verbose(env, "invalid atomic operand size\n"); 6854 return -EINVAL; 6855 } 6856 6857 /* check src1 operand */ 6858 err = check_reg_arg(env, insn->src_reg, SRC_OP); 6859 if (err) 6860 return err; 6861 6862 /* check src2 operand */ 6863 err = check_reg_arg(env, insn->dst_reg, SRC_OP); 6864 if (err) 6865 return err; 6866 6867 if (insn->imm == BPF_CMPXCHG) { 6868 /* Check comparison of R0 with memory location */ 6869 const u32 aux_reg = BPF_REG_0; 6870 6871 err = check_reg_arg(env, aux_reg, SRC_OP); 6872 if (err) 6873 return err; 6874 6875 if (is_pointer_value(env, aux_reg)) { 6876 verbose(env, "R%d leaks addr into mem\n", aux_reg); 6877 return -EACCES; 6878 } 6879 } 6880 6881 if (is_pointer_value(env, insn->src_reg)) { 6882 verbose(env, "R%d leaks addr into mem\n", insn->src_reg); 6883 return -EACCES; 6884 } 6885 6886 if (is_ctx_reg(env, insn->dst_reg) || 6887 is_pkt_reg(env, insn->dst_reg) || 6888 is_flow_key_reg(env, insn->dst_reg) || 6889 is_sk_reg(env, insn->dst_reg)) { 6890 verbose(env, "BPF_ATOMIC stores into R%d %s is not allowed\n", 6891 insn->dst_reg, 6892 reg_type_str(env, reg_state(env, insn->dst_reg)->type)); 6893 return -EACCES; 6894 } 6895 6896 if (insn->imm & BPF_FETCH) { 6897 if (insn->imm == BPF_CMPXCHG) 6898 load_reg = BPF_REG_0; 6899 else 6900 load_reg = insn->src_reg; 6901 6902 /* check and record load of old value */ 6903 err = check_reg_arg(env, load_reg, DST_OP); 6904 if (err) 6905 return err; 6906 } else { 6907 /* This instruction accesses a memory location but doesn't 6908 * actually load it into a register. 6909 */ 6910 load_reg = -1; 6911 } 6912 6913 /* Check whether we can read the memory, with second call for fetch 6914 * case to simulate the register fill. 6915 */ 6916 err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off, 6917 BPF_SIZE(insn->code), BPF_READ, -1, true, false); 6918 if (!err && load_reg >= 0) 6919 err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off, 6920 BPF_SIZE(insn->code), BPF_READ, load_reg, 6921 true, false); 6922 if (err) 6923 return err; 6924 6925 /* Check whether we can write into the same memory. */ 6926 err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off, 6927 BPF_SIZE(insn->code), BPF_WRITE, -1, true, false); 6928 if (err) 6929 return err; 6930 6931 return 0; 6932 } 6933 6934 /* When register 'regno' is used to read the stack (either directly or through 6935 * a helper function) make sure that it's within stack boundary and, depending 6936 * on the access type, that all elements of the stack are initialized. 6937 * 6938 * 'off' includes 'regno->off', but not its dynamic part (if any). 6939 * 6940 * All registers that have been spilled on the stack in the slots within the 6941 * read offsets are marked as read. 6942 */ 6943 static int check_stack_range_initialized( 6944 struct bpf_verifier_env *env, int regno, int off, 6945 int access_size, bool zero_size_allowed, 6946 enum bpf_access_src type, struct bpf_call_arg_meta *meta) 6947 { 6948 struct bpf_reg_state *reg = reg_state(env, regno); 6949 struct bpf_func_state *state = func(env, reg); 6950 int err, min_off, max_off, i, j, slot, spi; 6951 char *err_extra = type == ACCESS_HELPER ? " indirect" : ""; 6952 enum bpf_access_type bounds_check_type; 6953 /* Some accesses can write anything into the stack, others are 6954 * read-only. 6955 */ 6956 bool clobber = false; 6957 6958 if (access_size == 0 && !zero_size_allowed) { 6959 verbose(env, "invalid zero-sized read\n"); 6960 return -EACCES; 6961 } 6962 6963 if (type == ACCESS_HELPER) { 6964 /* The bounds checks for writes are more permissive than for 6965 * reads. However, if raw_mode is not set, we'll do extra 6966 * checks below. 6967 */ 6968 bounds_check_type = BPF_WRITE; 6969 clobber = true; 6970 } else { 6971 bounds_check_type = BPF_READ; 6972 } 6973 err = check_stack_access_within_bounds(env, regno, off, access_size, 6974 type, bounds_check_type); 6975 if (err) 6976 return err; 6977 6978 6979 if (tnum_is_const(reg->var_off)) { 6980 min_off = max_off = reg->var_off.value + off; 6981 } else { 6982 /* Variable offset is prohibited for unprivileged mode for 6983 * simplicity since it requires corresponding support in 6984 * Spectre masking for stack ALU. 6985 * See also retrieve_ptr_limit(). 6986 */ 6987 if (!env->bypass_spec_v1) { 6988 char tn_buf[48]; 6989 6990 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 6991 verbose(env, "R%d%s variable offset stack access prohibited for !root, var_off=%s\n", 6992 regno, err_extra, tn_buf); 6993 return -EACCES; 6994 } 6995 /* Only initialized buffer on stack is allowed to be accessed 6996 * with variable offset. With uninitialized buffer it's hard to 6997 * guarantee that whole memory is marked as initialized on 6998 * helper return since specific bounds are unknown what may 6999 * cause uninitialized stack leaking. 7000 */ 7001 if (meta && meta->raw_mode) 7002 meta = NULL; 7003 7004 min_off = reg->smin_value + off; 7005 max_off = reg->smax_value + off; 7006 } 7007 7008 if (meta && meta->raw_mode) { 7009 /* Ensure we won't be overwriting dynptrs when simulating byte 7010 * by byte access in check_helper_call using meta.access_size. 7011 * This would be a problem if we have a helper in the future 7012 * which takes: 7013 * 7014 * helper(uninit_mem, len, dynptr) 7015 * 7016 * Now, uninint_mem may overlap with dynptr pointer. Hence, it 7017 * may end up writing to dynptr itself when touching memory from 7018 * arg 1. This can be relaxed on a case by case basis for known 7019 * safe cases, but reject due to the possibilitiy of aliasing by 7020 * default. 7021 */ 7022 for (i = min_off; i < max_off + access_size; i++) { 7023 int stack_off = -i - 1; 7024 7025 spi = __get_spi(i); 7026 /* raw_mode may write past allocated_stack */ 7027 if (state->allocated_stack <= stack_off) 7028 continue; 7029 if (state->stack[spi].slot_type[stack_off % BPF_REG_SIZE] == STACK_DYNPTR) { 7030 verbose(env, "potential write to dynptr at off=%d disallowed\n", i); 7031 return -EACCES; 7032 } 7033 } 7034 meta->access_size = access_size; 7035 meta->regno = regno; 7036 return 0; 7037 } 7038 7039 for (i = min_off; i < max_off + access_size; i++) { 7040 u8 *stype; 7041 7042 slot = -i - 1; 7043 spi = slot / BPF_REG_SIZE; 7044 if (state->allocated_stack <= slot) 7045 goto err; 7046 stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE]; 7047 if (*stype == STACK_MISC) 7048 goto mark; 7049 if ((*stype == STACK_ZERO) || 7050 (*stype == STACK_INVALID && env->allow_uninit_stack)) { 7051 if (clobber) { 7052 /* helper can write anything into the stack */ 7053 *stype = STACK_MISC; 7054 } 7055 goto mark; 7056 } 7057 7058 if (is_spilled_reg(&state->stack[spi]) && 7059 (state->stack[spi].spilled_ptr.type == SCALAR_VALUE || 7060 env->allow_ptr_leaks)) { 7061 if (clobber) { 7062 __mark_reg_unknown(env, &state->stack[spi].spilled_ptr); 7063 for (j = 0; j < BPF_REG_SIZE; j++) 7064 scrub_spilled_slot(&state->stack[spi].slot_type[j]); 7065 } 7066 goto mark; 7067 } 7068 7069 err: 7070 if (tnum_is_const(reg->var_off)) { 7071 verbose(env, "invalid%s read from stack R%d off %d+%d size %d\n", 7072 err_extra, regno, min_off, i - min_off, access_size); 7073 } else { 7074 char tn_buf[48]; 7075 7076 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 7077 verbose(env, "invalid%s read from stack R%d var_off %s+%d size %d\n", 7078 err_extra, regno, tn_buf, i - min_off, access_size); 7079 } 7080 return -EACCES; 7081 mark: 7082 /* reading any byte out of 8-byte 'spill_slot' will cause 7083 * the whole slot to be marked as 'read' 7084 */ 7085 mark_reg_read(env, &state->stack[spi].spilled_ptr, 7086 state->stack[spi].spilled_ptr.parent, 7087 REG_LIVE_READ64); 7088 /* We do not set REG_LIVE_WRITTEN for stack slot, as we can not 7089 * be sure that whether stack slot is written to or not. Hence, 7090 * we must still conservatively propagate reads upwards even if 7091 * helper may write to the entire memory range. 7092 */ 7093 } 7094 return update_stack_depth(env, state, min_off); 7095 } 7096 7097 static int check_helper_mem_access(struct bpf_verifier_env *env, int regno, 7098 int access_size, bool zero_size_allowed, 7099 struct bpf_call_arg_meta *meta) 7100 { 7101 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno]; 7102 u32 *max_access; 7103 7104 switch (base_type(reg->type)) { 7105 case PTR_TO_PACKET: 7106 case PTR_TO_PACKET_META: 7107 return check_packet_access(env, regno, reg->off, access_size, 7108 zero_size_allowed); 7109 case PTR_TO_MAP_KEY: 7110 if (meta && meta->raw_mode) { 7111 verbose(env, "R%d cannot write into %s\n", regno, 7112 reg_type_str(env, reg->type)); 7113 return -EACCES; 7114 } 7115 return check_mem_region_access(env, regno, reg->off, access_size, 7116 reg->map_ptr->key_size, false); 7117 case PTR_TO_MAP_VALUE: 7118 if (check_map_access_type(env, regno, reg->off, access_size, 7119 meta && meta->raw_mode ? BPF_WRITE : 7120 BPF_READ)) 7121 return -EACCES; 7122 return check_map_access(env, regno, reg->off, access_size, 7123 zero_size_allowed, ACCESS_HELPER); 7124 case PTR_TO_MEM: 7125 if (type_is_rdonly_mem(reg->type)) { 7126 if (meta && meta->raw_mode) { 7127 verbose(env, "R%d cannot write into %s\n", regno, 7128 reg_type_str(env, reg->type)); 7129 return -EACCES; 7130 } 7131 } 7132 return check_mem_region_access(env, regno, reg->off, 7133 access_size, reg->mem_size, 7134 zero_size_allowed); 7135 case PTR_TO_BUF: 7136 if (type_is_rdonly_mem(reg->type)) { 7137 if (meta && meta->raw_mode) { 7138 verbose(env, "R%d cannot write into %s\n", regno, 7139 reg_type_str(env, reg->type)); 7140 return -EACCES; 7141 } 7142 7143 max_access = &env->prog->aux->max_rdonly_access; 7144 } else { 7145 max_access = &env->prog->aux->max_rdwr_access; 7146 } 7147 return check_buffer_access(env, reg, regno, reg->off, 7148 access_size, zero_size_allowed, 7149 max_access); 7150 case PTR_TO_STACK: 7151 return check_stack_range_initialized( 7152 env, 7153 regno, reg->off, access_size, 7154 zero_size_allowed, ACCESS_HELPER, meta); 7155 case PTR_TO_BTF_ID: 7156 return check_ptr_to_btf_access(env, regs, regno, reg->off, 7157 access_size, BPF_READ, -1); 7158 case PTR_TO_CTX: 7159 /* in case the function doesn't know how to access the context, 7160 * (because we are in a program of type SYSCALL for example), we 7161 * can not statically check its size. 7162 * Dynamically check it now. 7163 */ 7164 if (!env->ops->convert_ctx_access) { 7165 enum bpf_access_type atype = meta && meta->raw_mode ? BPF_WRITE : BPF_READ; 7166 int offset = access_size - 1; 7167 7168 /* Allow zero-byte read from PTR_TO_CTX */ 7169 if (access_size == 0) 7170 return zero_size_allowed ? 0 : -EACCES; 7171 7172 return check_mem_access(env, env->insn_idx, regno, offset, BPF_B, 7173 atype, -1, false, false); 7174 } 7175 7176 fallthrough; 7177 default: /* scalar_value or invalid ptr */ 7178 /* Allow zero-byte read from NULL, regardless of pointer type */ 7179 if (zero_size_allowed && access_size == 0 && 7180 register_is_null(reg)) 7181 return 0; 7182 7183 verbose(env, "R%d type=%s ", regno, 7184 reg_type_str(env, reg->type)); 7185 verbose(env, "expected=%s\n", reg_type_str(env, PTR_TO_STACK)); 7186 return -EACCES; 7187 } 7188 } 7189 7190 static int check_mem_size_reg(struct bpf_verifier_env *env, 7191 struct bpf_reg_state *reg, u32 regno, 7192 bool zero_size_allowed, 7193 struct bpf_call_arg_meta *meta) 7194 { 7195 int err; 7196 7197 /* This is used to refine r0 return value bounds for helpers 7198 * that enforce this value as an upper bound on return values. 7199 * See do_refine_retval_range() for helpers that can refine 7200 * the return value. C type of helper is u32 so we pull register 7201 * bound from umax_value however, if negative verifier errors 7202 * out. Only upper bounds can be learned because retval is an 7203 * int type and negative retvals are allowed. 7204 */ 7205 meta->msize_max_value = reg->umax_value; 7206 7207 /* The register is SCALAR_VALUE; the access check 7208 * happens using its boundaries. 7209 */ 7210 if (!tnum_is_const(reg->var_off)) 7211 /* For unprivileged variable accesses, disable raw 7212 * mode so that the program is required to 7213 * initialize all the memory that the helper could 7214 * just partially fill up. 7215 */ 7216 meta = NULL; 7217 7218 if (reg->smin_value < 0) { 7219 verbose(env, "R%d min value is negative, either use unsigned or 'var &= const'\n", 7220 regno); 7221 return -EACCES; 7222 } 7223 7224 if (reg->umin_value == 0) { 7225 err = check_helper_mem_access(env, regno - 1, 0, 7226 zero_size_allowed, 7227 meta); 7228 if (err) 7229 return err; 7230 } 7231 7232 if (reg->umax_value >= BPF_MAX_VAR_SIZ) { 7233 verbose(env, "R%d unbounded memory access, use 'var &= const' or 'if (var < const)'\n", 7234 regno); 7235 return -EACCES; 7236 } 7237 err = check_helper_mem_access(env, regno - 1, 7238 reg->umax_value, 7239 zero_size_allowed, meta); 7240 if (!err) 7241 err = mark_chain_precision(env, regno); 7242 return err; 7243 } 7244 7245 int check_mem_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg, 7246 u32 regno, u32 mem_size) 7247 { 7248 bool may_be_null = type_may_be_null(reg->type); 7249 struct bpf_reg_state saved_reg; 7250 struct bpf_call_arg_meta meta; 7251 int err; 7252 7253 if (register_is_null(reg)) 7254 return 0; 7255 7256 memset(&meta, 0, sizeof(meta)); 7257 /* Assuming that the register contains a value check if the memory 7258 * access is safe. Temporarily save and restore the register's state as 7259 * the conversion shouldn't be visible to a caller. 7260 */ 7261 if (may_be_null) { 7262 saved_reg = *reg; 7263 mark_ptr_not_null_reg(reg); 7264 } 7265 7266 err = check_helper_mem_access(env, regno, mem_size, true, &meta); 7267 /* Check access for BPF_WRITE */ 7268 meta.raw_mode = true; 7269 err = err ?: check_helper_mem_access(env, regno, mem_size, true, &meta); 7270 7271 if (may_be_null) 7272 *reg = saved_reg; 7273 7274 return err; 7275 } 7276 7277 static int check_kfunc_mem_size_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg, 7278 u32 regno) 7279 { 7280 struct bpf_reg_state *mem_reg = &cur_regs(env)[regno - 1]; 7281 bool may_be_null = type_may_be_null(mem_reg->type); 7282 struct bpf_reg_state saved_reg; 7283 struct bpf_call_arg_meta meta; 7284 int err; 7285 7286 WARN_ON_ONCE(regno < BPF_REG_2 || regno > BPF_REG_5); 7287 7288 memset(&meta, 0, sizeof(meta)); 7289 7290 if (may_be_null) { 7291 saved_reg = *mem_reg; 7292 mark_ptr_not_null_reg(mem_reg); 7293 } 7294 7295 err = check_mem_size_reg(env, reg, regno, true, &meta); 7296 /* Check access for BPF_WRITE */ 7297 meta.raw_mode = true; 7298 err = err ?: check_mem_size_reg(env, reg, regno, true, &meta); 7299 7300 if (may_be_null) 7301 *mem_reg = saved_reg; 7302 return err; 7303 } 7304 7305 /* Implementation details: 7306 * bpf_map_lookup returns PTR_TO_MAP_VALUE_OR_NULL. 7307 * bpf_obj_new returns PTR_TO_BTF_ID | MEM_ALLOC | PTR_MAYBE_NULL. 7308 * Two bpf_map_lookups (even with the same key) will have different reg->id. 7309 * Two separate bpf_obj_new will also have different reg->id. 7310 * For traditional PTR_TO_MAP_VALUE or PTR_TO_BTF_ID | MEM_ALLOC, the verifier 7311 * clears reg->id after value_or_null->value transition, since the verifier only 7312 * cares about the range of access to valid map value pointer and doesn't care 7313 * about actual address of the map element. 7314 * For maps with 'struct bpf_spin_lock' inside map value the verifier keeps 7315 * reg->id > 0 after value_or_null->value transition. By doing so 7316 * two bpf_map_lookups will be considered two different pointers that 7317 * point to different bpf_spin_locks. Likewise for pointers to allocated objects 7318 * returned from bpf_obj_new. 7319 * The verifier allows taking only one bpf_spin_lock at a time to avoid 7320 * dead-locks. 7321 * Since only one bpf_spin_lock is allowed the checks are simpler than 7322 * reg_is_refcounted() logic. The verifier needs to remember only 7323 * one spin_lock instead of array of acquired_refs. 7324 * cur_state->active_lock remembers which map value element or allocated 7325 * object got locked and clears it after bpf_spin_unlock. 7326 */ 7327 static int process_spin_lock(struct bpf_verifier_env *env, int regno, 7328 bool is_lock) 7329 { 7330 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno]; 7331 struct bpf_verifier_state *cur = env->cur_state; 7332 bool is_const = tnum_is_const(reg->var_off); 7333 u64 val = reg->var_off.value; 7334 struct bpf_map *map = NULL; 7335 struct btf *btf = NULL; 7336 struct btf_record *rec; 7337 7338 if (!is_const) { 7339 verbose(env, 7340 "R%d doesn't have constant offset. bpf_spin_lock has to be at the constant offset\n", 7341 regno); 7342 return -EINVAL; 7343 } 7344 if (reg->type == PTR_TO_MAP_VALUE) { 7345 map = reg->map_ptr; 7346 if (!map->btf) { 7347 verbose(env, 7348 "map '%s' has to have BTF in order to use bpf_spin_lock\n", 7349 map->name); 7350 return -EINVAL; 7351 } 7352 } else { 7353 btf = reg->btf; 7354 } 7355 7356 rec = reg_btf_record(reg); 7357 if (!btf_record_has_field(rec, BPF_SPIN_LOCK)) { 7358 verbose(env, "%s '%s' has no valid bpf_spin_lock\n", map ? "map" : "local", 7359 map ? map->name : "kptr"); 7360 return -EINVAL; 7361 } 7362 if (rec->spin_lock_off != val + reg->off) { 7363 verbose(env, "off %lld doesn't point to 'struct bpf_spin_lock' that is at %d\n", 7364 val + reg->off, rec->spin_lock_off); 7365 return -EINVAL; 7366 } 7367 if (is_lock) { 7368 if (cur->active_lock.ptr) { 7369 verbose(env, 7370 "Locking two bpf_spin_locks are not allowed\n"); 7371 return -EINVAL; 7372 } 7373 if (map) 7374 cur->active_lock.ptr = map; 7375 else 7376 cur->active_lock.ptr = btf; 7377 cur->active_lock.id = reg->id; 7378 } else { 7379 void *ptr; 7380 7381 if (map) 7382 ptr = map; 7383 else 7384 ptr = btf; 7385 7386 if (!cur->active_lock.ptr) { 7387 verbose(env, "bpf_spin_unlock without taking a lock\n"); 7388 return -EINVAL; 7389 } 7390 if (cur->active_lock.ptr != ptr || 7391 cur->active_lock.id != reg->id) { 7392 verbose(env, "bpf_spin_unlock of different lock\n"); 7393 return -EINVAL; 7394 } 7395 7396 invalidate_non_owning_refs(env); 7397 7398 cur->active_lock.ptr = NULL; 7399 cur->active_lock.id = 0; 7400 } 7401 return 0; 7402 } 7403 7404 static int process_timer_func(struct bpf_verifier_env *env, int regno, 7405 struct bpf_call_arg_meta *meta) 7406 { 7407 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno]; 7408 bool is_const = tnum_is_const(reg->var_off); 7409 struct bpf_map *map = reg->map_ptr; 7410 u64 val = reg->var_off.value; 7411 7412 if (!is_const) { 7413 verbose(env, 7414 "R%d doesn't have constant offset. bpf_timer has to be at the constant offset\n", 7415 regno); 7416 return -EINVAL; 7417 } 7418 if (!map->btf) { 7419 verbose(env, "map '%s' has to have BTF in order to use bpf_timer\n", 7420 map->name); 7421 return -EINVAL; 7422 } 7423 if (!btf_record_has_field(map->record, BPF_TIMER)) { 7424 verbose(env, "map '%s' has no valid bpf_timer\n", map->name); 7425 return -EINVAL; 7426 } 7427 if (map->record->timer_off != val + reg->off) { 7428 verbose(env, "off %lld doesn't point to 'struct bpf_timer' that is at %d\n", 7429 val + reg->off, map->record->timer_off); 7430 return -EINVAL; 7431 } 7432 if (meta->map_ptr) { 7433 verbose(env, "verifier bug. Two map pointers in a timer helper\n"); 7434 return -EFAULT; 7435 } 7436 meta->map_uid = reg->map_uid; 7437 meta->map_ptr = map; 7438 return 0; 7439 } 7440 7441 static int process_kptr_func(struct bpf_verifier_env *env, int regno, 7442 struct bpf_call_arg_meta *meta) 7443 { 7444 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno]; 7445 struct bpf_map *map_ptr = reg->map_ptr; 7446 struct btf_field *kptr_field; 7447 u32 kptr_off; 7448 7449 if (!tnum_is_const(reg->var_off)) { 7450 verbose(env, 7451 "R%d doesn't have constant offset. kptr has to be at the constant offset\n", 7452 regno); 7453 return -EINVAL; 7454 } 7455 if (!map_ptr->btf) { 7456 verbose(env, "map '%s' has to have BTF in order to use bpf_kptr_xchg\n", 7457 map_ptr->name); 7458 return -EINVAL; 7459 } 7460 if (!btf_record_has_field(map_ptr->record, BPF_KPTR)) { 7461 verbose(env, "map '%s' has no valid kptr\n", map_ptr->name); 7462 return -EINVAL; 7463 } 7464 7465 meta->map_ptr = map_ptr; 7466 kptr_off = reg->off + reg->var_off.value; 7467 kptr_field = btf_record_find(map_ptr->record, kptr_off, BPF_KPTR); 7468 if (!kptr_field) { 7469 verbose(env, "off=%d doesn't point to kptr\n", kptr_off); 7470 return -EACCES; 7471 } 7472 if (kptr_field->type != BPF_KPTR_REF && kptr_field->type != BPF_KPTR_PERCPU) { 7473 verbose(env, "off=%d kptr isn't referenced kptr\n", kptr_off); 7474 return -EACCES; 7475 } 7476 meta->kptr_field = kptr_field; 7477 return 0; 7478 } 7479 7480 /* There are two register types representing a bpf_dynptr, one is PTR_TO_STACK 7481 * which points to a stack slot, and the other is CONST_PTR_TO_DYNPTR. 7482 * 7483 * In both cases we deal with the first 8 bytes, but need to mark the next 8 7484 * bytes as STACK_DYNPTR in case of PTR_TO_STACK. In case of 7485 * CONST_PTR_TO_DYNPTR, we are guaranteed to get the beginning of the object. 7486 * 7487 * Mutability of bpf_dynptr is at two levels, one is at the level of struct 7488 * bpf_dynptr itself, i.e. whether the helper is receiving a pointer to struct 7489 * bpf_dynptr or pointer to const struct bpf_dynptr. In the former case, it can 7490 * mutate the view of the dynptr and also possibly destroy it. In the latter 7491 * case, it cannot mutate the bpf_dynptr itself but it can still mutate the 7492 * memory that dynptr points to. 7493 * 7494 * The verifier will keep track both levels of mutation (bpf_dynptr's in 7495 * reg->type and the memory's in reg->dynptr.type), but there is no support for 7496 * readonly dynptr view yet, hence only the first case is tracked and checked. 7497 * 7498 * This is consistent with how C applies the const modifier to a struct object, 7499 * where the pointer itself inside bpf_dynptr becomes const but not what it 7500 * points to. 7501 * 7502 * Helpers which do not mutate the bpf_dynptr set MEM_RDONLY in their argument 7503 * type, and declare it as 'const struct bpf_dynptr *' in their prototype. 7504 */ 7505 static int process_dynptr_func(struct bpf_verifier_env *env, int regno, int insn_idx, 7506 enum bpf_arg_type arg_type, int clone_ref_obj_id) 7507 { 7508 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno]; 7509 int err; 7510 7511 /* MEM_UNINIT and MEM_RDONLY are exclusive, when applied to an 7512 * ARG_PTR_TO_DYNPTR (or ARG_PTR_TO_DYNPTR | DYNPTR_TYPE_*): 7513 */ 7514 if ((arg_type & (MEM_UNINIT | MEM_RDONLY)) == (MEM_UNINIT | MEM_RDONLY)) { 7515 verbose(env, "verifier internal error: misconfigured dynptr helper type flags\n"); 7516 return -EFAULT; 7517 } 7518 7519 /* MEM_UNINIT - Points to memory that is an appropriate candidate for 7520 * constructing a mutable bpf_dynptr object. 7521 * 7522 * Currently, this is only possible with PTR_TO_STACK 7523 * pointing to a region of at least 16 bytes which doesn't 7524 * contain an existing bpf_dynptr. 7525 * 7526 * MEM_RDONLY - Points to a initialized bpf_dynptr that will not be 7527 * mutated or destroyed. However, the memory it points to 7528 * may be mutated. 7529 * 7530 * None - Points to a initialized dynptr that can be mutated and 7531 * destroyed, including mutation of the memory it points 7532 * to. 7533 */ 7534 if (arg_type & MEM_UNINIT) { 7535 int i; 7536 7537 if (!is_dynptr_reg_valid_uninit(env, reg)) { 7538 verbose(env, "Dynptr has to be an uninitialized dynptr\n"); 7539 return -EINVAL; 7540 } 7541 7542 /* we write BPF_DW bits (8 bytes) at a time */ 7543 for (i = 0; i < BPF_DYNPTR_SIZE; i += 8) { 7544 err = check_mem_access(env, insn_idx, regno, 7545 i, BPF_DW, BPF_WRITE, -1, false, false); 7546 if (err) 7547 return err; 7548 } 7549 7550 err = mark_stack_slots_dynptr(env, reg, arg_type, insn_idx, clone_ref_obj_id); 7551 } else /* MEM_RDONLY and None case from above */ { 7552 /* For the reg->type == PTR_TO_STACK case, bpf_dynptr is never const */ 7553 if (reg->type == CONST_PTR_TO_DYNPTR && !(arg_type & MEM_RDONLY)) { 7554 verbose(env, "cannot pass pointer to const bpf_dynptr, the helper mutates it\n"); 7555 return -EINVAL; 7556 } 7557 7558 if (!is_dynptr_reg_valid_init(env, reg)) { 7559 verbose(env, 7560 "Expected an initialized dynptr as arg #%d\n", 7561 regno); 7562 return -EINVAL; 7563 } 7564 7565 /* Fold modifiers (in this case, MEM_RDONLY) when checking expected type */ 7566 if (!is_dynptr_type_expected(env, reg, arg_type & ~MEM_RDONLY)) { 7567 verbose(env, 7568 "Expected a dynptr of type %s as arg #%d\n", 7569 dynptr_type_str(arg_to_dynptr_type(arg_type)), regno); 7570 return -EINVAL; 7571 } 7572 7573 err = mark_dynptr_read(env, reg); 7574 } 7575 return err; 7576 } 7577 7578 static u32 iter_ref_obj_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg, int spi) 7579 { 7580 struct bpf_func_state *state = func(env, reg); 7581 7582 return state->stack[spi].spilled_ptr.ref_obj_id; 7583 } 7584 7585 static bool is_iter_kfunc(struct bpf_kfunc_call_arg_meta *meta) 7586 { 7587 return meta->kfunc_flags & (KF_ITER_NEW | KF_ITER_NEXT | KF_ITER_DESTROY); 7588 } 7589 7590 static bool is_iter_new_kfunc(struct bpf_kfunc_call_arg_meta *meta) 7591 { 7592 return meta->kfunc_flags & KF_ITER_NEW; 7593 } 7594 7595 static bool is_iter_next_kfunc(struct bpf_kfunc_call_arg_meta *meta) 7596 { 7597 return meta->kfunc_flags & KF_ITER_NEXT; 7598 } 7599 7600 static bool is_iter_destroy_kfunc(struct bpf_kfunc_call_arg_meta *meta) 7601 { 7602 return meta->kfunc_flags & KF_ITER_DESTROY; 7603 } 7604 7605 static bool is_kfunc_arg_iter(struct bpf_kfunc_call_arg_meta *meta, int arg) 7606 { 7607 /* btf_check_iter_kfuncs() guarantees that first argument of any iter 7608 * kfunc is iter state pointer 7609 */ 7610 return arg == 0 && is_iter_kfunc(meta); 7611 } 7612 7613 static int process_iter_arg(struct bpf_verifier_env *env, int regno, int insn_idx, 7614 struct bpf_kfunc_call_arg_meta *meta) 7615 { 7616 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno]; 7617 const struct btf_type *t; 7618 const struct btf_param *arg; 7619 int spi, err, i, nr_slots; 7620 u32 btf_id; 7621 7622 /* btf_check_iter_kfuncs() ensures we don't need to validate anything here */ 7623 arg = &btf_params(meta->func_proto)[0]; 7624 t = btf_type_skip_modifiers(meta->btf, arg->type, NULL); /* PTR */ 7625 t = btf_type_skip_modifiers(meta->btf, t->type, &btf_id); /* STRUCT */ 7626 nr_slots = t->size / BPF_REG_SIZE; 7627 7628 if (is_iter_new_kfunc(meta)) { 7629 /* bpf_iter_<type>_new() expects pointer to uninit iter state */ 7630 if (!is_iter_reg_valid_uninit(env, reg, nr_slots)) { 7631 verbose(env, "expected uninitialized iter_%s as arg #%d\n", 7632 iter_type_str(meta->btf, btf_id), regno); 7633 return -EINVAL; 7634 } 7635 7636 for (i = 0; i < nr_slots * 8; i += BPF_REG_SIZE) { 7637 err = check_mem_access(env, insn_idx, regno, 7638 i, BPF_DW, BPF_WRITE, -1, false, false); 7639 if (err) 7640 return err; 7641 } 7642 7643 err = mark_stack_slots_iter(env, reg, insn_idx, meta->btf, btf_id, nr_slots); 7644 if (err) 7645 return err; 7646 } else { 7647 /* iter_next() or iter_destroy() expect initialized iter state*/ 7648 if (!is_iter_reg_valid_init(env, reg, meta->btf, btf_id, nr_slots)) { 7649 verbose(env, "expected an initialized iter_%s as arg #%d\n", 7650 iter_type_str(meta->btf, btf_id), regno); 7651 return -EINVAL; 7652 } 7653 7654 spi = iter_get_spi(env, reg, nr_slots); 7655 if (spi < 0) 7656 return spi; 7657 7658 err = mark_iter_read(env, reg, spi, nr_slots); 7659 if (err) 7660 return err; 7661 7662 /* remember meta->iter info for process_iter_next_call() */ 7663 meta->iter.spi = spi; 7664 meta->iter.frameno = reg->frameno; 7665 meta->ref_obj_id = iter_ref_obj_id(env, reg, spi); 7666 7667 if (is_iter_destroy_kfunc(meta)) { 7668 err = unmark_stack_slots_iter(env, reg, nr_slots); 7669 if (err) 7670 return err; 7671 } 7672 } 7673 7674 return 0; 7675 } 7676 7677 /* process_iter_next_call() is called when verifier gets to iterator's next 7678 * "method" (e.g., bpf_iter_num_next() for numbers iterator) call. We'll refer 7679 * to it as just "iter_next()" in comments below. 7680 * 7681 * BPF verifier relies on a crucial contract for any iter_next() 7682 * implementation: it should *eventually* return NULL, and once that happens 7683 * it should keep returning NULL. That is, once iterator exhausts elements to 7684 * iterate, it should never reset or spuriously return new elements. 7685 * 7686 * With the assumption of such contract, process_iter_next_call() simulates 7687 * a fork in the verifier state to validate loop logic correctness and safety 7688 * without having to simulate infinite amount of iterations. 7689 * 7690 * In current state, we first assume that iter_next() returned NULL and 7691 * iterator state is set to DRAINED (BPF_ITER_STATE_DRAINED). In such 7692 * conditions we should not form an infinite loop and should eventually reach 7693 * exit. 7694 * 7695 * Besides that, we also fork current state and enqueue it for later 7696 * verification. In a forked state we keep iterator state as ACTIVE 7697 * (BPF_ITER_STATE_ACTIVE) and assume non-NULL return from iter_next(). We 7698 * also bump iteration depth to prevent erroneous infinite loop detection 7699 * later on (see iter_active_depths_differ() comment for details). In this 7700 * state we assume that we'll eventually loop back to another iter_next() 7701 * calls (it could be in exactly same location or in some other instruction, 7702 * it doesn't matter, we don't make any unnecessary assumptions about this, 7703 * everything revolves around iterator state in a stack slot, not which 7704 * instruction is calling iter_next()). When that happens, we either will come 7705 * to iter_next() with equivalent state and can conclude that next iteration 7706 * will proceed in exactly the same way as we just verified, so it's safe to 7707 * assume that loop converges. If not, we'll go on another iteration 7708 * simulation with a different input state, until all possible starting states 7709 * are validated or we reach maximum number of instructions limit. 7710 * 7711 * This way, we will either exhaustively discover all possible input states 7712 * that iterator loop can start with and eventually will converge, or we'll 7713 * effectively regress into bounded loop simulation logic and either reach 7714 * maximum number of instructions if loop is not provably convergent, or there 7715 * is some statically known limit on number of iterations (e.g., if there is 7716 * an explicit `if n > 100 then break;` statement somewhere in the loop). 7717 * 7718 * One very subtle but very important aspect is that we *always* simulate NULL 7719 * condition first (as the current state) before we simulate non-NULL case. 7720 * This has to do with intricacies of scalar precision tracking. By simulating 7721 * "exit condition" of iter_next() returning NULL first, we make sure all the 7722 * relevant precision marks *that will be set **after** we exit iterator loop* 7723 * are propagated backwards to common parent state of NULL and non-NULL 7724 * branches. Thanks to that, state equivalence checks done later in forked 7725 * state, when reaching iter_next() for ACTIVE iterator, can assume that 7726 * precision marks are finalized and won't change. Because simulating another 7727 * ACTIVE iterator iteration won't change them (because given same input 7728 * states we'll end up with exactly same output states which we are currently 7729 * comparing; and verification after the loop already propagated back what 7730 * needs to be **additionally** tracked as precise). It's subtle, grok 7731 * precision tracking for more intuitive understanding. 7732 */ 7733 static int process_iter_next_call(struct bpf_verifier_env *env, int insn_idx, 7734 struct bpf_kfunc_call_arg_meta *meta) 7735 { 7736 struct bpf_verifier_state *cur_st = env->cur_state, *queued_st; 7737 struct bpf_func_state *cur_fr = cur_st->frame[cur_st->curframe], *queued_fr; 7738 struct bpf_reg_state *cur_iter, *queued_iter; 7739 int iter_frameno = meta->iter.frameno; 7740 int iter_spi = meta->iter.spi; 7741 7742 BTF_TYPE_EMIT(struct bpf_iter); 7743 7744 cur_iter = &env->cur_state->frame[iter_frameno]->stack[iter_spi].spilled_ptr; 7745 7746 if (cur_iter->iter.state != BPF_ITER_STATE_ACTIVE && 7747 cur_iter->iter.state != BPF_ITER_STATE_DRAINED) { 7748 verbose(env, "verifier internal error: unexpected iterator state %d (%s)\n", 7749 cur_iter->iter.state, iter_state_str(cur_iter->iter.state)); 7750 return -EFAULT; 7751 } 7752 7753 if (cur_iter->iter.state == BPF_ITER_STATE_ACTIVE) { 7754 /* branch out active iter state */ 7755 queued_st = push_stack(env, insn_idx + 1, insn_idx, false); 7756 if (!queued_st) 7757 return -ENOMEM; 7758 7759 queued_iter = &queued_st->frame[iter_frameno]->stack[iter_spi].spilled_ptr; 7760 queued_iter->iter.state = BPF_ITER_STATE_ACTIVE; 7761 queued_iter->iter.depth++; 7762 7763 queued_fr = queued_st->frame[queued_st->curframe]; 7764 mark_ptr_not_null_reg(&queued_fr->regs[BPF_REG_0]); 7765 } 7766 7767 /* switch to DRAINED state, but keep the depth unchanged */ 7768 /* mark current iter state as drained and assume returned NULL */ 7769 cur_iter->iter.state = BPF_ITER_STATE_DRAINED; 7770 __mark_reg_const_zero(&cur_fr->regs[BPF_REG_0]); 7771 7772 return 0; 7773 } 7774 7775 static bool arg_type_is_mem_size(enum bpf_arg_type type) 7776 { 7777 return type == ARG_CONST_SIZE || 7778 type == ARG_CONST_SIZE_OR_ZERO; 7779 } 7780 7781 static bool arg_type_is_release(enum bpf_arg_type type) 7782 { 7783 return type & OBJ_RELEASE; 7784 } 7785 7786 static bool arg_type_is_dynptr(enum bpf_arg_type type) 7787 { 7788 return base_type(type) == ARG_PTR_TO_DYNPTR; 7789 } 7790 7791 static int int_ptr_type_to_size(enum bpf_arg_type type) 7792 { 7793 if (type == ARG_PTR_TO_INT) 7794 return sizeof(u32); 7795 else if (type == ARG_PTR_TO_LONG) 7796 return sizeof(u64); 7797 7798 return -EINVAL; 7799 } 7800 7801 static int resolve_map_arg_type(struct bpf_verifier_env *env, 7802 const struct bpf_call_arg_meta *meta, 7803 enum bpf_arg_type *arg_type) 7804 { 7805 if (!meta->map_ptr) { 7806 /* kernel subsystem misconfigured verifier */ 7807 verbose(env, "invalid map_ptr to access map->type\n"); 7808 return -EACCES; 7809 } 7810 7811 switch (meta->map_ptr->map_type) { 7812 case BPF_MAP_TYPE_SOCKMAP: 7813 case BPF_MAP_TYPE_SOCKHASH: 7814 if (*arg_type == ARG_PTR_TO_MAP_VALUE) { 7815 *arg_type = ARG_PTR_TO_BTF_ID_SOCK_COMMON; 7816 } else { 7817 verbose(env, "invalid arg_type for sockmap/sockhash\n"); 7818 return -EINVAL; 7819 } 7820 break; 7821 case BPF_MAP_TYPE_BLOOM_FILTER: 7822 if (meta->func_id == BPF_FUNC_map_peek_elem) 7823 *arg_type = ARG_PTR_TO_MAP_VALUE; 7824 break; 7825 default: 7826 break; 7827 } 7828 return 0; 7829 } 7830 7831 struct bpf_reg_types { 7832 const enum bpf_reg_type types[10]; 7833 u32 *btf_id; 7834 }; 7835 7836 static const struct bpf_reg_types sock_types = { 7837 .types = { 7838 PTR_TO_SOCK_COMMON, 7839 PTR_TO_SOCKET, 7840 PTR_TO_TCP_SOCK, 7841 PTR_TO_XDP_SOCK, 7842 }, 7843 }; 7844 7845 #ifdef CONFIG_NET 7846 static const struct bpf_reg_types btf_id_sock_common_types = { 7847 .types = { 7848 PTR_TO_SOCK_COMMON, 7849 PTR_TO_SOCKET, 7850 PTR_TO_TCP_SOCK, 7851 PTR_TO_XDP_SOCK, 7852 PTR_TO_BTF_ID, 7853 PTR_TO_BTF_ID | PTR_TRUSTED, 7854 }, 7855 .btf_id = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON], 7856 }; 7857 #endif 7858 7859 static const struct bpf_reg_types mem_types = { 7860 .types = { 7861 PTR_TO_STACK, 7862 PTR_TO_PACKET, 7863 PTR_TO_PACKET_META, 7864 PTR_TO_MAP_KEY, 7865 PTR_TO_MAP_VALUE, 7866 PTR_TO_MEM, 7867 PTR_TO_MEM | MEM_RINGBUF, 7868 PTR_TO_BUF, 7869 PTR_TO_BTF_ID | PTR_TRUSTED, 7870 }, 7871 }; 7872 7873 static const struct bpf_reg_types int_ptr_types = { 7874 .types = { 7875 PTR_TO_STACK, 7876 PTR_TO_PACKET, 7877 PTR_TO_PACKET_META, 7878 PTR_TO_MAP_KEY, 7879 PTR_TO_MAP_VALUE, 7880 }, 7881 }; 7882 7883 static const struct bpf_reg_types spin_lock_types = { 7884 .types = { 7885 PTR_TO_MAP_VALUE, 7886 PTR_TO_BTF_ID | MEM_ALLOC, 7887 } 7888 }; 7889 7890 static const struct bpf_reg_types fullsock_types = { .types = { PTR_TO_SOCKET } }; 7891 static const struct bpf_reg_types scalar_types = { .types = { SCALAR_VALUE } }; 7892 static const struct bpf_reg_types context_types = { .types = { PTR_TO_CTX } }; 7893 static const struct bpf_reg_types ringbuf_mem_types = { .types = { PTR_TO_MEM | MEM_RINGBUF } }; 7894 static const struct bpf_reg_types const_map_ptr_types = { .types = { CONST_PTR_TO_MAP } }; 7895 static const struct bpf_reg_types btf_ptr_types = { 7896 .types = { 7897 PTR_TO_BTF_ID, 7898 PTR_TO_BTF_ID | PTR_TRUSTED, 7899 PTR_TO_BTF_ID | MEM_RCU, 7900 }, 7901 }; 7902 static const struct bpf_reg_types percpu_btf_ptr_types = { 7903 .types = { 7904 PTR_TO_BTF_ID | MEM_PERCPU, 7905 PTR_TO_BTF_ID | MEM_PERCPU | MEM_RCU, 7906 PTR_TO_BTF_ID | MEM_PERCPU | PTR_TRUSTED, 7907 } 7908 }; 7909 static const struct bpf_reg_types func_ptr_types = { .types = { PTR_TO_FUNC } }; 7910 static const struct bpf_reg_types stack_ptr_types = { .types = { PTR_TO_STACK } }; 7911 static const struct bpf_reg_types const_str_ptr_types = { .types = { PTR_TO_MAP_VALUE } }; 7912 static const struct bpf_reg_types timer_types = { .types = { PTR_TO_MAP_VALUE } }; 7913 static const struct bpf_reg_types kptr_types = { .types = { PTR_TO_MAP_VALUE } }; 7914 static const struct bpf_reg_types dynptr_types = { 7915 .types = { 7916 PTR_TO_STACK, 7917 CONST_PTR_TO_DYNPTR, 7918 } 7919 }; 7920 7921 static const struct bpf_reg_types *compatible_reg_types[__BPF_ARG_TYPE_MAX] = { 7922 [ARG_PTR_TO_MAP_KEY] = &mem_types, 7923 [ARG_PTR_TO_MAP_VALUE] = &mem_types, 7924 [ARG_CONST_SIZE] = &scalar_types, 7925 [ARG_CONST_SIZE_OR_ZERO] = &scalar_types, 7926 [ARG_CONST_ALLOC_SIZE_OR_ZERO] = &scalar_types, 7927 [ARG_CONST_MAP_PTR] = &const_map_ptr_types, 7928 [ARG_PTR_TO_CTX] = &context_types, 7929 [ARG_PTR_TO_SOCK_COMMON] = &sock_types, 7930 #ifdef CONFIG_NET 7931 [ARG_PTR_TO_BTF_ID_SOCK_COMMON] = &btf_id_sock_common_types, 7932 #endif 7933 [ARG_PTR_TO_SOCKET] = &fullsock_types, 7934 [ARG_PTR_TO_BTF_ID] = &btf_ptr_types, 7935 [ARG_PTR_TO_SPIN_LOCK] = &spin_lock_types, 7936 [ARG_PTR_TO_MEM] = &mem_types, 7937 [ARG_PTR_TO_RINGBUF_MEM] = &ringbuf_mem_types, 7938 [ARG_PTR_TO_INT] = &int_ptr_types, 7939 [ARG_PTR_TO_LONG] = &int_ptr_types, 7940 [ARG_PTR_TO_PERCPU_BTF_ID] = &percpu_btf_ptr_types, 7941 [ARG_PTR_TO_FUNC] = &func_ptr_types, 7942 [ARG_PTR_TO_STACK] = &stack_ptr_types, 7943 [ARG_PTR_TO_CONST_STR] = &const_str_ptr_types, 7944 [ARG_PTR_TO_TIMER] = &timer_types, 7945 [ARG_PTR_TO_KPTR] = &kptr_types, 7946 [ARG_PTR_TO_DYNPTR] = &dynptr_types, 7947 }; 7948 7949 static int check_reg_type(struct bpf_verifier_env *env, u32 regno, 7950 enum bpf_arg_type arg_type, 7951 const u32 *arg_btf_id, 7952 struct bpf_call_arg_meta *meta) 7953 { 7954 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno]; 7955 enum bpf_reg_type expected, type = reg->type; 7956 const struct bpf_reg_types *compatible; 7957 int i, j; 7958 7959 compatible = compatible_reg_types[base_type(arg_type)]; 7960 if (!compatible) { 7961 verbose(env, "verifier internal error: unsupported arg type %d\n", arg_type); 7962 return -EFAULT; 7963 } 7964 7965 /* ARG_PTR_TO_MEM + RDONLY is compatible with PTR_TO_MEM and PTR_TO_MEM + RDONLY, 7966 * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM and NOT with PTR_TO_MEM + RDONLY 7967 * 7968 * Same for MAYBE_NULL: 7969 * 7970 * ARG_PTR_TO_MEM + MAYBE_NULL is compatible with PTR_TO_MEM and PTR_TO_MEM + MAYBE_NULL, 7971 * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM but NOT with PTR_TO_MEM + MAYBE_NULL 7972 * 7973 * ARG_PTR_TO_MEM is compatible with PTR_TO_MEM that is tagged with a dynptr type. 7974 * 7975 * Therefore we fold these flags depending on the arg_type before comparison. 7976 */ 7977 if (arg_type & MEM_RDONLY) 7978 type &= ~MEM_RDONLY; 7979 if (arg_type & PTR_MAYBE_NULL) 7980 type &= ~PTR_MAYBE_NULL; 7981 if (base_type(arg_type) == ARG_PTR_TO_MEM) 7982 type &= ~DYNPTR_TYPE_FLAG_MASK; 7983 7984 if (meta->func_id == BPF_FUNC_kptr_xchg && type_is_alloc(type)) { 7985 type &= ~MEM_ALLOC; 7986 type &= ~MEM_PERCPU; 7987 } 7988 7989 for (i = 0; i < ARRAY_SIZE(compatible->types); i++) { 7990 expected = compatible->types[i]; 7991 if (expected == NOT_INIT) 7992 break; 7993 7994 if (type == expected) 7995 goto found; 7996 } 7997 7998 verbose(env, "R%d type=%s expected=", regno, reg_type_str(env, reg->type)); 7999 for (j = 0; j + 1 < i; j++) 8000 verbose(env, "%s, ", reg_type_str(env, compatible->types[j])); 8001 verbose(env, "%s\n", reg_type_str(env, compatible->types[j])); 8002 return -EACCES; 8003 8004 found: 8005 if (base_type(reg->type) != PTR_TO_BTF_ID) 8006 return 0; 8007 8008 if (compatible == &mem_types) { 8009 if (!(arg_type & MEM_RDONLY)) { 8010 verbose(env, 8011 "%s() may write into memory pointed by R%d type=%s\n", 8012 func_id_name(meta->func_id), 8013 regno, reg_type_str(env, reg->type)); 8014 return -EACCES; 8015 } 8016 return 0; 8017 } 8018 8019 switch ((int)reg->type) { 8020 case PTR_TO_BTF_ID: 8021 case PTR_TO_BTF_ID | PTR_TRUSTED: 8022 case PTR_TO_BTF_ID | MEM_RCU: 8023 case PTR_TO_BTF_ID | PTR_MAYBE_NULL: 8024 case PTR_TO_BTF_ID | PTR_MAYBE_NULL | MEM_RCU: 8025 { 8026 /* For bpf_sk_release, it needs to match against first member 8027 * 'struct sock_common', hence make an exception for it. This 8028 * allows bpf_sk_release to work for multiple socket types. 8029 */ 8030 bool strict_type_match = arg_type_is_release(arg_type) && 8031 meta->func_id != BPF_FUNC_sk_release; 8032 8033 if (type_may_be_null(reg->type) && 8034 (!type_may_be_null(arg_type) || arg_type_is_release(arg_type))) { 8035 verbose(env, "Possibly NULL pointer passed to helper arg%d\n", regno); 8036 return -EACCES; 8037 } 8038 8039 if (!arg_btf_id) { 8040 if (!compatible->btf_id) { 8041 verbose(env, "verifier internal error: missing arg compatible BTF ID\n"); 8042 return -EFAULT; 8043 } 8044 arg_btf_id = compatible->btf_id; 8045 } 8046 8047 if (meta->func_id == BPF_FUNC_kptr_xchg) { 8048 if (map_kptr_match_type(env, meta->kptr_field, reg, regno)) 8049 return -EACCES; 8050 } else { 8051 if (arg_btf_id == BPF_PTR_POISON) { 8052 verbose(env, "verifier internal error:"); 8053 verbose(env, "R%d has non-overwritten BPF_PTR_POISON type\n", 8054 regno); 8055 return -EACCES; 8056 } 8057 8058 if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off, 8059 btf_vmlinux, *arg_btf_id, 8060 strict_type_match)) { 8061 verbose(env, "R%d is of type %s but %s is expected\n", 8062 regno, btf_type_name(reg->btf, reg->btf_id), 8063 btf_type_name(btf_vmlinux, *arg_btf_id)); 8064 return -EACCES; 8065 } 8066 } 8067 break; 8068 } 8069 case PTR_TO_BTF_ID | MEM_ALLOC: 8070 case PTR_TO_BTF_ID | MEM_PERCPU | MEM_ALLOC: 8071 if (meta->func_id != BPF_FUNC_spin_lock && meta->func_id != BPF_FUNC_spin_unlock && 8072 meta->func_id != BPF_FUNC_kptr_xchg) { 8073 verbose(env, "verifier internal error: unimplemented handling of MEM_ALLOC\n"); 8074 return -EFAULT; 8075 } 8076 if (meta->func_id == BPF_FUNC_kptr_xchg) { 8077 if (map_kptr_match_type(env, meta->kptr_field, reg, regno)) 8078 return -EACCES; 8079 } 8080 break; 8081 case PTR_TO_BTF_ID | MEM_PERCPU: 8082 case PTR_TO_BTF_ID | MEM_PERCPU | MEM_RCU: 8083 case PTR_TO_BTF_ID | MEM_PERCPU | PTR_TRUSTED: 8084 /* Handled by helper specific checks */ 8085 break; 8086 default: 8087 verbose(env, "verifier internal error: invalid PTR_TO_BTF_ID register for type match\n"); 8088 return -EFAULT; 8089 } 8090 return 0; 8091 } 8092 8093 static struct btf_field * 8094 reg_find_field_offset(const struct bpf_reg_state *reg, s32 off, u32 fields) 8095 { 8096 struct btf_field *field; 8097 struct btf_record *rec; 8098 8099 rec = reg_btf_record(reg); 8100 if (!rec) 8101 return NULL; 8102 8103 field = btf_record_find(rec, off, fields); 8104 if (!field) 8105 return NULL; 8106 8107 return field; 8108 } 8109 8110 int check_func_arg_reg_off(struct bpf_verifier_env *env, 8111 const struct bpf_reg_state *reg, int regno, 8112 enum bpf_arg_type arg_type) 8113 { 8114 u32 type = reg->type; 8115 8116 /* When referenced register is passed to release function, its fixed 8117 * offset must be 0. 8118 * 8119 * We will check arg_type_is_release reg has ref_obj_id when storing 8120 * meta->release_regno. 8121 */ 8122 if (arg_type_is_release(arg_type)) { 8123 /* ARG_PTR_TO_DYNPTR with OBJ_RELEASE is a bit special, as it 8124 * may not directly point to the object being released, but to 8125 * dynptr pointing to such object, which might be at some offset 8126 * on the stack. In that case, we simply to fallback to the 8127 * default handling. 8128 */ 8129 if (arg_type_is_dynptr(arg_type) && type == PTR_TO_STACK) 8130 return 0; 8131 8132 /* Doing check_ptr_off_reg check for the offset will catch this 8133 * because fixed_off_ok is false, but checking here allows us 8134 * to give the user a better error message. 8135 */ 8136 if (reg->off) { 8137 verbose(env, "R%d must have zero offset when passed to release func or trusted arg to kfunc\n", 8138 regno); 8139 return -EINVAL; 8140 } 8141 return __check_ptr_off_reg(env, reg, regno, false); 8142 } 8143 8144 switch (type) { 8145 /* Pointer types where both fixed and variable offset is explicitly allowed: */ 8146 case PTR_TO_STACK: 8147 case PTR_TO_PACKET: 8148 case PTR_TO_PACKET_META: 8149 case PTR_TO_MAP_KEY: 8150 case PTR_TO_MAP_VALUE: 8151 case PTR_TO_MEM: 8152 case PTR_TO_MEM | MEM_RDONLY: 8153 case PTR_TO_MEM | MEM_RINGBUF: 8154 case PTR_TO_BUF: 8155 case PTR_TO_BUF | MEM_RDONLY: 8156 case SCALAR_VALUE: 8157 return 0; 8158 /* All the rest must be rejected, except PTR_TO_BTF_ID which allows 8159 * fixed offset. 8160 */ 8161 case PTR_TO_BTF_ID: 8162 case PTR_TO_BTF_ID | MEM_ALLOC: 8163 case PTR_TO_BTF_ID | PTR_TRUSTED: 8164 case PTR_TO_BTF_ID | MEM_RCU: 8165 case PTR_TO_BTF_ID | MEM_ALLOC | NON_OWN_REF: 8166 case PTR_TO_BTF_ID | MEM_ALLOC | NON_OWN_REF | MEM_RCU: 8167 /* When referenced PTR_TO_BTF_ID is passed to release function, 8168 * its fixed offset must be 0. In the other cases, fixed offset 8169 * can be non-zero. This was already checked above. So pass 8170 * fixed_off_ok as true to allow fixed offset for all other 8171 * cases. var_off always must be 0 for PTR_TO_BTF_ID, hence we 8172 * still need to do checks instead of returning. 8173 */ 8174 return __check_ptr_off_reg(env, reg, regno, true); 8175 default: 8176 return __check_ptr_off_reg(env, reg, regno, false); 8177 } 8178 } 8179 8180 static struct bpf_reg_state *get_dynptr_arg_reg(struct bpf_verifier_env *env, 8181 const struct bpf_func_proto *fn, 8182 struct bpf_reg_state *regs) 8183 { 8184 struct bpf_reg_state *state = NULL; 8185 int i; 8186 8187 for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++) 8188 if (arg_type_is_dynptr(fn->arg_type[i])) { 8189 if (state) { 8190 verbose(env, "verifier internal error: multiple dynptr args\n"); 8191 return NULL; 8192 } 8193 state = ®s[BPF_REG_1 + i]; 8194 } 8195 8196 if (!state) 8197 verbose(env, "verifier internal error: no dynptr arg found\n"); 8198 8199 return state; 8200 } 8201 8202 static int dynptr_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 8203 { 8204 struct bpf_func_state *state = func(env, reg); 8205 int spi; 8206 8207 if (reg->type == CONST_PTR_TO_DYNPTR) 8208 return reg->id; 8209 spi = dynptr_get_spi(env, reg); 8210 if (spi < 0) 8211 return spi; 8212 return state->stack[spi].spilled_ptr.id; 8213 } 8214 8215 static int dynptr_ref_obj_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 8216 { 8217 struct bpf_func_state *state = func(env, reg); 8218 int spi; 8219 8220 if (reg->type == CONST_PTR_TO_DYNPTR) 8221 return reg->ref_obj_id; 8222 spi = dynptr_get_spi(env, reg); 8223 if (spi < 0) 8224 return spi; 8225 return state->stack[spi].spilled_ptr.ref_obj_id; 8226 } 8227 8228 static enum bpf_dynptr_type dynptr_get_type(struct bpf_verifier_env *env, 8229 struct bpf_reg_state *reg) 8230 { 8231 struct bpf_func_state *state = func(env, reg); 8232 int spi; 8233 8234 if (reg->type == CONST_PTR_TO_DYNPTR) 8235 return reg->dynptr.type; 8236 8237 spi = __get_spi(reg->off); 8238 if (spi < 0) { 8239 verbose(env, "verifier internal error: invalid spi when querying dynptr type\n"); 8240 return BPF_DYNPTR_TYPE_INVALID; 8241 } 8242 8243 return state->stack[spi].spilled_ptr.dynptr.type; 8244 } 8245 8246 static int check_func_arg(struct bpf_verifier_env *env, u32 arg, 8247 struct bpf_call_arg_meta *meta, 8248 const struct bpf_func_proto *fn, 8249 int insn_idx) 8250 { 8251 u32 regno = BPF_REG_1 + arg; 8252 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno]; 8253 enum bpf_arg_type arg_type = fn->arg_type[arg]; 8254 enum bpf_reg_type type = reg->type; 8255 u32 *arg_btf_id = NULL; 8256 int err = 0; 8257 8258 if (arg_type == ARG_DONTCARE) 8259 return 0; 8260 8261 err = check_reg_arg(env, regno, SRC_OP); 8262 if (err) 8263 return err; 8264 8265 if (arg_type == ARG_ANYTHING) { 8266 if (is_pointer_value(env, regno)) { 8267 verbose(env, "R%d leaks addr into helper function\n", 8268 regno); 8269 return -EACCES; 8270 } 8271 return 0; 8272 } 8273 8274 if (type_is_pkt_pointer(type) && 8275 !may_access_direct_pkt_data(env, meta, BPF_READ)) { 8276 verbose(env, "helper access to the packet is not allowed\n"); 8277 return -EACCES; 8278 } 8279 8280 if (base_type(arg_type) == ARG_PTR_TO_MAP_VALUE) { 8281 err = resolve_map_arg_type(env, meta, &arg_type); 8282 if (err) 8283 return err; 8284 } 8285 8286 if (register_is_null(reg) && type_may_be_null(arg_type)) 8287 /* A NULL register has a SCALAR_VALUE type, so skip 8288 * type checking. 8289 */ 8290 goto skip_type_check; 8291 8292 /* arg_btf_id and arg_size are in a union. */ 8293 if (base_type(arg_type) == ARG_PTR_TO_BTF_ID || 8294 base_type(arg_type) == ARG_PTR_TO_SPIN_LOCK) 8295 arg_btf_id = fn->arg_btf_id[arg]; 8296 8297 err = check_reg_type(env, regno, arg_type, arg_btf_id, meta); 8298 if (err) 8299 return err; 8300 8301 err = check_func_arg_reg_off(env, reg, regno, arg_type); 8302 if (err) 8303 return err; 8304 8305 skip_type_check: 8306 if (arg_type_is_release(arg_type)) { 8307 if (arg_type_is_dynptr(arg_type)) { 8308 struct bpf_func_state *state = func(env, reg); 8309 int spi; 8310 8311 /* Only dynptr created on stack can be released, thus 8312 * the get_spi and stack state checks for spilled_ptr 8313 * should only be done before process_dynptr_func for 8314 * PTR_TO_STACK. 8315 */ 8316 if (reg->type == PTR_TO_STACK) { 8317 spi = dynptr_get_spi(env, reg); 8318 if (spi < 0 || !state->stack[spi].spilled_ptr.ref_obj_id) { 8319 verbose(env, "arg %d is an unacquired reference\n", regno); 8320 return -EINVAL; 8321 } 8322 } else { 8323 verbose(env, "cannot release unowned const bpf_dynptr\n"); 8324 return -EINVAL; 8325 } 8326 } else if (!reg->ref_obj_id && !register_is_null(reg)) { 8327 verbose(env, "R%d must be referenced when passed to release function\n", 8328 regno); 8329 return -EINVAL; 8330 } 8331 if (meta->release_regno) { 8332 verbose(env, "verifier internal error: more than one release argument\n"); 8333 return -EFAULT; 8334 } 8335 meta->release_regno = regno; 8336 } 8337 8338 if (reg->ref_obj_id) { 8339 if (meta->ref_obj_id) { 8340 verbose(env, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n", 8341 regno, reg->ref_obj_id, 8342 meta->ref_obj_id); 8343 return -EFAULT; 8344 } 8345 meta->ref_obj_id = reg->ref_obj_id; 8346 } 8347 8348 switch (base_type(arg_type)) { 8349 case ARG_CONST_MAP_PTR: 8350 /* bpf_map_xxx(map_ptr) call: remember that map_ptr */ 8351 if (meta->map_ptr) { 8352 /* Use map_uid (which is unique id of inner map) to reject: 8353 * inner_map1 = bpf_map_lookup_elem(outer_map, key1) 8354 * inner_map2 = bpf_map_lookup_elem(outer_map, key2) 8355 * if (inner_map1 && inner_map2) { 8356 * timer = bpf_map_lookup_elem(inner_map1); 8357 * if (timer) 8358 * // mismatch would have been allowed 8359 * bpf_timer_init(timer, inner_map2); 8360 * } 8361 * 8362 * Comparing map_ptr is enough to distinguish normal and outer maps. 8363 */ 8364 if (meta->map_ptr != reg->map_ptr || 8365 meta->map_uid != reg->map_uid) { 8366 verbose(env, 8367 "timer pointer in R1 map_uid=%d doesn't match map pointer in R2 map_uid=%d\n", 8368 meta->map_uid, reg->map_uid); 8369 return -EINVAL; 8370 } 8371 } 8372 meta->map_ptr = reg->map_ptr; 8373 meta->map_uid = reg->map_uid; 8374 break; 8375 case ARG_PTR_TO_MAP_KEY: 8376 /* bpf_map_xxx(..., map_ptr, ..., key) call: 8377 * check that [key, key + map->key_size) are within 8378 * stack limits and initialized 8379 */ 8380 if (!meta->map_ptr) { 8381 /* in function declaration map_ptr must come before 8382 * map_key, so that it's verified and known before 8383 * we have to check map_key here. Otherwise it means 8384 * that kernel subsystem misconfigured verifier 8385 */ 8386 verbose(env, "invalid map_ptr to access map->key\n"); 8387 return -EACCES; 8388 } 8389 err = check_helper_mem_access(env, regno, 8390 meta->map_ptr->key_size, false, 8391 NULL); 8392 break; 8393 case ARG_PTR_TO_MAP_VALUE: 8394 if (type_may_be_null(arg_type) && register_is_null(reg)) 8395 return 0; 8396 8397 /* bpf_map_xxx(..., map_ptr, ..., value) call: 8398 * check [value, value + map->value_size) validity 8399 */ 8400 if (!meta->map_ptr) { 8401 /* kernel subsystem misconfigured verifier */ 8402 verbose(env, "invalid map_ptr to access map->value\n"); 8403 return -EACCES; 8404 } 8405 meta->raw_mode = arg_type & MEM_UNINIT; 8406 err = check_helper_mem_access(env, regno, 8407 meta->map_ptr->value_size, false, 8408 meta); 8409 break; 8410 case ARG_PTR_TO_PERCPU_BTF_ID: 8411 if (!reg->btf_id) { 8412 verbose(env, "Helper has invalid btf_id in R%d\n", regno); 8413 return -EACCES; 8414 } 8415 meta->ret_btf = reg->btf; 8416 meta->ret_btf_id = reg->btf_id; 8417 break; 8418 case ARG_PTR_TO_SPIN_LOCK: 8419 if (in_rbtree_lock_required_cb(env)) { 8420 verbose(env, "can't spin_{lock,unlock} in rbtree cb\n"); 8421 return -EACCES; 8422 } 8423 if (meta->func_id == BPF_FUNC_spin_lock) { 8424 err = process_spin_lock(env, regno, true); 8425 if (err) 8426 return err; 8427 } else if (meta->func_id == BPF_FUNC_spin_unlock) { 8428 err = process_spin_lock(env, regno, false); 8429 if (err) 8430 return err; 8431 } else { 8432 verbose(env, "verifier internal error\n"); 8433 return -EFAULT; 8434 } 8435 break; 8436 case ARG_PTR_TO_TIMER: 8437 err = process_timer_func(env, regno, meta); 8438 if (err) 8439 return err; 8440 break; 8441 case ARG_PTR_TO_FUNC: 8442 meta->subprogno = reg->subprogno; 8443 break; 8444 case ARG_PTR_TO_MEM: 8445 /* The access to this pointer is only checked when we hit the 8446 * next is_mem_size argument below. 8447 */ 8448 meta->raw_mode = arg_type & MEM_UNINIT; 8449 if (arg_type & MEM_FIXED_SIZE) { 8450 err = check_helper_mem_access(env, regno, 8451 fn->arg_size[arg], false, 8452 meta); 8453 } 8454 break; 8455 case ARG_CONST_SIZE: 8456 err = check_mem_size_reg(env, reg, regno, false, meta); 8457 break; 8458 case ARG_CONST_SIZE_OR_ZERO: 8459 err = check_mem_size_reg(env, reg, regno, true, meta); 8460 break; 8461 case ARG_PTR_TO_DYNPTR: 8462 err = process_dynptr_func(env, regno, insn_idx, arg_type, 0); 8463 if (err) 8464 return err; 8465 break; 8466 case ARG_CONST_ALLOC_SIZE_OR_ZERO: 8467 if (!tnum_is_const(reg->var_off)) { 8468 verbose(env, "R%d is not a known constant'\n", 8469 regno); 8470 return -EACCES; 8471 } 8472 meta->mem_size = reg->var_off.value; 8473 err = mark_chain_precision(env, regno); 8474 if (err) 8475 return err; 8476 break; 8477 case ARG_PTR_TO_INT: 8478 case ARG_PTR_TO_LONG: 8479 { 8480 int size = int_ptr_type_to_size(arg_type); 8481 8482 err = check_helper_mem_access(env, regno, size, false, meta); 8483 if (err) 8484 return err; 8485 err = check_ptr_alignment(env, reg, 0, size, true); 8486 break; 8487 } 8488 case ARG_PTR_TO_CONST_STR: 8489 { 8490 struct bpf_map *map = reg->map_ptr; 8491 int map_off; 8492 u64 map_addr; 8493 char *str_ptr; 8494 8495 if (!bpf_map_is_rdonly(map)) { 8496 verbose(env, "R%d does not point to a readonly map'\n", regno); 8497 return -EACCES; 8498 } 8499 8500 if (!tnum_is_const(reg->var_off)) { 8501 verbose(env, "R%d is not a constant address'\n", regno); 8502 return -EACCES; 8503 } 8504 8505 if (!map->ops->map_direct_value_addr) { 8506 verbose(env, "no direct value access support for this map type\n"); 8507 return -EACCES; 8508 } 8509 8510 err = check_map_access(env, regno, reg->off, 8511 map->value_size - reg->off, false, 8512 ACCESS_HELPER); 8513 if (err) 8514 return err; 8515 8516 map_off = reg->off + reg->var_off.value; 8517 err = map->ops->map_direct_value_addr(map, &map_addr, map_off); 8518 if (err) { 8519 verbose(env, "direct value access on string failed\n"); 8520 return err; 8521 } 8522 8523 str_ptr = (char *)(long)(map_addr); 8524 if (!strnchr(str_ptr + map_off, map->value_size - map_off, 0)) { 8525 verbose(env, "string is not zero-terminated\n"); 8526 return -EINVAL; 8527 } 8528 break; 8529 } 8530 case ARG_PTR_TO_KPTR: 8531 err = process_kptr_func(env, regno, meta); 8532 if (err) 8533 return err; 8534 break; 8535 } 8536 8537 return err; 8538 } 8539 8540 static bool may_update_sockmap(struct bpf_verifier_env *env, int func_id) 8541 { 8542 enum bpf_attach_type eatype = env->prog->expected_attach_type; 8543 enum bpf_prog_type type = resolve_prog_type(env->prog); 8544 8545 if (func_id != BPF_FUNC_map_update_elem) 8546 return false; 8547 8548 /* It's not possible to get access to a locked struct sock in these 8549 * contexts, so updating is safe. 8550 */ 8551 switch (type) { 8552 case BPF_PROG_TYPE_TRACING: 8553 if (eatype == BPF_TRACE_ITER) 8554 return true; 8555 break; 8556 case BPF_PROG_TYPE_SOCKET_FILTER: 8557 case BPF_PROG_TYPE_SCHED_CLS: 8558 case BPF_PROG_TYPE_SCHED_ACT: 8559 case BPF_PROG_TYPE_XDP: 8560 case BPF_PROG_TYPE_SK_REUSEPORT: 8561 case BPF_PROG_TYPE_FLOW_DISSECTOR: 8562 case BPF_PROG_TYPE_SK_LOOKUP: 8563 return true; 8564 default: 8565 break; 8566 } 8567 8568 verbose(env, "cannot update sockmap in this context\n"); 8569 return false; 8570 } 8571 8572 static bool allow_tail_call_in_subprogs(struct bpf_verifier_env *env) 8573 { 8574 return env->prog->jit_requested && 8575 bpf_jit_supports_subprog_tailcalls(); 8576 } 8577 8578 static int check_map_func_compatibility(struct bpf_verifier_env *env, 8579 struct bpf_map *map, int func_id) 8580 { 8581 if (!map) 8582 return 0; 8583 8584 /* We need a two way check, first is from map perspective ... */ 8585 switch (map->map_type) { 8586 case BPF_MAP_TYPE_PROG_ARRAY: 8587 if (func_id != BPF_FUNC_tail_call) 8588 goto error; 8589 break; 8590 case BPF_MAP_TYPE_PERF_EVENT_ARRAY: 8591 if (func_id != BPF_FUNC_perf_event_read && 8592 func_id != BPF_FUNC_perf_event_output && 8593 func_id != BPF_FUNC_skb_output && 8594 func_id != BPF_FUNC_perf_event_read_value && 8595 func_id != BPF_FUNC_xdp_output) 8596 goto error; 8597 break; 8598 case BPF_MAP_TYPE_RINGBUF: 8599 if (func_id != BPF_FUNC_ringbuf_output && 8600 func_id != BPF_FUNC_ringbuf_reserve && 8601 func_id != BPF_FUNC_ringbuf_query && 8602 func_id != BPF_FUNC_ringbuf_reserve_dynptr && 8603 func_id != BPF_FUNC_ringbuf_submit_dynptr && 8604 func_id != BPF_FUNC_ringbuf_discard_dynptr) 8605 goto error; 8606 break; 8607 case BPF_MAP_TYPE_USER_RINGBUF: 8608 if (func_id != BPF_FUNC_user_ringbuf_drain) 8609 goto error; 8610 break; 8611 case BPF_MAP_TYPE_STACK_TRACE: 8612 if (func_id != BPF_FUNC_get_stackid) 8613 goto error; 8614 break; 8615 case BPF_MAP_TYPE_CGROUP_ARRAY: 8616 if (func_id != BPF_FUNC_skb_under_cgroup && 8617 func_id != BPF_FUNC_current_task_under_cgroup) 8618 goto error; 8619 break; 8620 case BPF_MAP_TYPE_CGROUP_STORAGE: 8621 case BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE: 8622 if (func_id != BPF_FUNC_get_local_storage) 8623 goto error; 8624 break; 8625 case BPF_MAP_TYPE_DEVMAP: 8626 case BPF_MAP_TYPE_DEVMAP_HASH: 8627 if (func_id != BPF_FUNC_redirect_map && 8628 func_id != BPF_FUNC_map_lookup_elem) 8629 goto error; 8630 break; 8631 /* Restrict bpf side of cpumap and xskmap, open when use-cases 8632 * appear. 8633 */ 8634 case BPF_MAP_TYPE_CPUMAP: 8635 if (func_id != BPF_FUNC_redirect_map) 8636 goto error; 8637 break; 8638 case BPF_MAP_TYPE_XSKMAP: 8639 if (func_id != BPF_FUNC_redirect_map && 8640 func_id != BPF_FUNC_map_lookup_elem) 8641 goto error; 8642 break; 8643 case BPF_MAP_TYPE_ARRAY_OF_MAPS: 8644 case BPF_MAP_TYPE_HASH_OF_MAPS: 8645 if (func_id != BPF_FUNC_map_lookup_elem) 8646 goto error; 8647 break; 8648 case BPF_MAP_TYPE_SOCKMAP: 8649 if (func_id != BPF_FUNC_sk_redirect_map && 8650 func_id != BPF_FUNC_sock_map_update && 8651 func_id != BPF_FUNC_map_delete_elem && 8652 func_id != BPF_FUNC_msg_redirect_map && 8653 func_id != BPF_FUNC_sk_select_reuseport && 8654 func_id != BPF_FUNC_map_lookup_elem && 8655 !may_update_sockmap(env, func_id)) 8656 goto error; 8657 break; 8658 case BPF_MAP_TYPE_SOCKHASH: 8659 if (func_id != BPF_FUNC_sk_redirect_hash && 8660 func_id != BPF_FUNC_sock_hash_update && 8661 func_id != BPF_FUNC_map_delete_elem && 8662 func_id != BPF_FUNC_msg_redirect_hash && 8663 func_id != BPF_FUNC_sk_select_reuseport && 8664 func_id != BPF_FUNC_map_lookup_elem && 8665 !may_update_sockmap(env, func_id)) 8666 goto error; 8667 break; 8668 case BPF_MAP_TYPE_REUSEPORT_SOCKARRAY: 8669 if (func_id != BPF_FUNC_sk_select_reuseport) 8670 goto error; 8671 break; 8672 case BPF_MAP_TYPE_QUEUE: 8673 case BPF_MAP_TYPE_STACK: 8674 if (func_id != BPF_FUNC_map_peek_elem && 8675 func_id != BPF_FUNC_map_pop_elem && 8676 func_id != BPF_FUNC_map_push_elem) 8677 goto error; 8678 break; 8679 case BPF_MAP_TYPE_SK_STORAGE: 8680 if (func_id != BPF_FUNC_sk_storage_get && 8681 func_id != BPF_FUNC_sk_storage_delete && 8682 func_id != BPF_FUNC_kptr_xchg) 8683 goto error; 8684 break; 8685 case BPF_MAP_TYPE_INODE_STORAGE: 8686 if (func_id != BPF_FUNC_inode_storage_get && 8687 func_id != BPF_FUNC_inode_storage_delete && 8688 func_id != BPF_FUNC_kptr_xchg) 8689 goto error; 8690 break; 8691 case BPF_MAP_TYPE_TASK_STORAGE: 8692 if (func_id != BPF_FUNC_task_storage_get && 8693 func_id != BPF_FUNC_task_storage_delete && 8694 func_id != BPF_FUNC_kptr_xchg) 8695 goto error; 8696 break; 8697 case BPF_MAP_TYPE_CGRP_STORAGE: 8698 if (func_id != BPF_FUNC_cgrp_storage_get && 8699 func_id != BPF_FUNC_cgrp_storage_delete && 8700 func_id != BPF_FUNC_kptr_xchg) 8701 goto error; 8702 break; 8703 case BPF_MAP_TYPE_BLOOM_FILTER: 8704 if (func_id != BPF_FUNC_map_peek_elem && 8705 func_id != BPF_FUNC_map_push_elem) 8706 goto error; 8707 break; 8708 default: 8709 break; 8710 } 8711 8712 /* ... and second from the function itself. */ 8713 switch (func_id) { 8714 case BPF_FUNC_tail_call: 8715 if (map->map_type != BPF_MAP_TYPE_PROG_ARRAY) 8716 goto error; 8717 if (env->subprog_cnt > 1 && !allow_tail_call_in_subprogs(env)) { 8718 verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n"); 8719 return -EINVAL; 8720 } 8721 break; 8722 case BPF_FUNC_perf_event_read: 8723 case BPF_FUNC_perf_event_output: 8724 case BPF_FUNC_perf_event_read_value: 8725 case BPF_FUNC_skb_output: 8726 case BPF_FUNC_xdp_output: 8727 if (map->map_type != BPF_MAP_TYPE_PERF_EVENT_ARRAY) 8728 goto error; 8729 break; 8730 case BPF_FUNC_ringbuf_output: 8731 case BPF_FUNC_ringbuf_reserve: 8732 case BPF_FUNC_ringbuf_query: 8733 case BPF_FUNC_ringbuf_reserve_dynptr: 8734 case BPF_FUNC_ringbuf_submit_dynptr: 8735 case BPF_FUNC_ringbuf_discard_dynptr: 8736 if (map->map_type != BPF_MAP_TYPE_RINGBUF) 8737 goto error; 8738 break; 8739 case BPF_FUNC_user_ringbuf_drain: 8740 if (map->map_type != BPF_MAP_TYPE_USER_RINGBUF) 8741 goto error; 8742 break; 8743 case BPF_FUNC_get_stackid: 8744 if (map->map_type != BPF_MAP_TYPE_STACK_TRACE) 8745 goto error; 8746 break; 8747 case BPF_FUNC_current_task_under_cgroup: 8748 case BPF_FUNC_skb_under_cgroup: 8749 if (map->map_type != BPF_MAP_TYPE_CGROUP_ARRAY) 8750 goto error; 8751 break; 8752 case BPF_FUNC_redirect_map: 8753 if (map->map_type != BPF_MAP_TYPE_DEVMAP && 8754 map->map_type != BPF_MAP_TYPE_DEVMAP_HASH && 8755 map->map_type != BPF_MAP_TYPE_CPUMAP && 8756 map->map_type != BPF_MAP_TYPE_XSKMAP) 8757 goto error; 8758 break; 8759 case BPF_FUNC_sk_redirect_map: 8760 case BPF_FUNC_msg_redirect_map: 8761 case BPF_FUNC_sock_map_update: 8762 if (map->map_type != BPF_MAP_TYPE_SOCKMAP) 8763 goto error; 8764 break; 8765 case BPF_FUNC_sk_redirect_hash: 8766 case BPF_FUNC_msg_redirect_hash: 8767 case BPF_FUNC_sock_hash_update: 8768 if (map->map_type != BPF_MAP_TYPE_SOCKHASH) 8769 goto error; 8770 break; 8771 case BPF_FUNC_get_local_storage: 8772 if (map->map_type != BPF_MAP_TYPE_CGROUP_STORAGE && 8773 map->map_type != BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE) 8774 goto error; 8775 break; 8776 case BPF_FUNC_sk_select_reuseport: 8777 if (map->map_type != BPF_MAP_TYPE_REUSEPORT_SOCKARRAY && 8778 map->map_type != BPF_MAP_TYPE_SOCKMAP && 8779 map->map_type != BPF_MAP_TYPE_SOCKHASH) 8780 goto error; 8781 break; 8782 case BPF_FUNC_map_pop_elem: 8783 if (map->map_type != BPF_MAP_TYPE_QUEUE && 8784 map->map_type != BPF_MAP_TYPE_STACK) 8785 goto error; 8786 break; 8787 case BPF_FUNC_map_peek_elem: 8788 case BPF_FUNC_map_push_elem: 8789 if (map->map_type != BPF_MAP_TYPE_QUEUE && 8790 map->map_type != BPF_MAP_TYPE_STACK && 8791 map->map_type != BPF_MAP_TYPE_BLOOM_FILTER) 8792 goto error; 8793 break; 8794 case BPF_FUNC_map_lookup_percpu_elem: 8795 if (map->map_type != BPF_MAP_TYPE_PERCPU_ARRAY && 8796 map->map_type != BPF_MAP_TYPE_PERCPU_HASH && 8797 map->map_type != BPF_MAP_TYPE_LRU_PERCPU_HASH) 8798 goto error; 8799 break; 8800 case BPF_FUNC_sk_storage_get: 8801 case BPF_FUNC_sk_storage_delete: 8802 if (map->map_type != BPF_MAP_TYPE_SK_STORAGE) 8803 goto error; 8804 break; 8805 case BPF_FUNC_inode_storage_get: 8806 case BPF_FUNC_inode_storage_delete: 8807 if (map->map_type != BPF_MAP_TYPE_INODE_STORAGE) 8808 goto error; 8809 break; 8810 case BPF_FUNC_task_storage_get: 8811 case BPF_FUNC_task_storage_delete: 8812 if (map->map_type != BPF_MAP_TYPE_TASK_STORAGE) 8813 goto error; 8814 break; 8815 case BPF_FUNC_cgrp_storage_get: 8816 case BPF_FUNC_cgrp_storage_delete: 8817 if (map->map_type != BPF_MAP_TYPE_CGRP_STORAGE) 8818 goto error; 8819 break; 8820 default: 8821 break; 8822 } 8823 8824 return 0; 8825 error: 8826 verbose(env, "cannot pass map_type %d into func %s#%d\n", 8827 map->map_type, func_id_name(func_id), func_id); 8828 return -EINVAL; 8829 } 8830 8831 static bool check_raw_mode_ok(const struct bpf_func_proto *fn) 8832 { 8833 int count = 0; 8834 8835 if (fn->arg1_type == ARG_PTR_TO_UNINIT_MEM) 8836 count++; 8837 if (fn->arg2_type == ARG_PTR_TO_UNINIT_MEM) 8838 count++; 8839 if (fn->arg3_type == ARG_PTR_TO_UNINIT_MEM) 8840 count++; 8841 if (fn->arg4_type == ARG_PTR_TO_UNINIT_MEM) 8842 count++; 8843 if (fn->arg5_type == ARG_PTR_TO_UNINIT_MEM) 8844 count++; 8845 8846 /* We only support one arg being in raw mode at the moment, 8847 * which is sufficient for the helper functions we have 8848 * right now. 8849 */ 8850 return count <= 1; 8851 } 8852 8853 static bool check_args_pair_invalid(const struct bpf_func_proto *fn, int arg) 8854 { 8855 bool is_fixed = fn->arg_type[arg] & MEM_FIXED_SIZE; 8856 bool has_size = fn->arg_size[arg] != 0; 8857 bool is_next_size = false; 8858 8859 if (arg + 1 < ARRAY_SIZE(fn->arg_type)) 8860 is_next_size = arg_type_is_mem_size(fn->arg_type[arg + 1]); 8861 8862 if (base_type(fn->arg_type[arg]) != ARG_PTR_TO_MEM) 8863 return is_next_size; 8864 8865 return has_size == is_next_size || is_next_size == is_fixed; 8866 } 8867 8868 static bool check_arg_pair_ok(const struct bpf_func_proto *fn) 8869 { 8870 /* bpf_xxx(..., buf, len) call will access 'len' 8871 * bytes from memory 'buf'. Both arg types need 8872 * to be paired, so make sure there's no buggy 8873 * helper function specification. 8874 */ 8875 if (arg_type_is_mem_size(fn->arg1_type) || 8876 check_args_pair_invalid(fn, 0) || 8877 check_args_pair_invalid(fn, 1) || 8878 check_args_pair_invalid(fn, 2) || 8879 check_args_pair_invalid(fn, 3) || 8880 check_args_pair_invalid(fn, 4)) 8881 return false; 8882 8883 return true; 8884 } 8885 8886 static bool check_btf_id_ok(const struct bpf_func_proto *fn) 8887 { 8888 int i; 8889 8890 for (i = 0; i < ARRAY_SIZE(fn->arg_type); i++) { 8891 if (base_type(fn->arg_type[i]) == ARG_PTR_TO_BTF_ID) 8892 return !!fn->arg_btf_id[i]; 8893 if (base_type(fn->arg_type[i]) == ARG_PTR_TO_SPIN_LOCK) 8894 return fn->arg_btf_id[i] == BPF_PTR_POISON; 8895 if (base_type(fn->arg_type[i]) != ARG_PTR_TO_BTF_ID && fn->arg_btf_id[i] && 8896 /* arg_btf_id and arg_size are in a union. */ 8897 (base_type(fn->arg_type[i]) != ARG_PTR_TO_MEM || 8898 !(fn->arg_type[i] & MEM_FIXED_SIZE))) 8899 return false; 8900 } 8901 8902 return true; 8903 } 8904 8905 static int check_func_proto(const struct bpf_func_proto *fn, int func_id) 8906 { 8907 return check_raw_mode_ok(fn) && 8908 check_arg_pair_ok(fn) && 8909 check_btf_id_ok(fn) ? 0 : -EINVAL; 8910 } 8911 8912 /* Packet data might have moved, any old PTR_TO_PACKET[_META,_END] 8913 * are now invalid, so turn them into unknown SCALAR_VALUE. 8914 * 8915 * This also applies to dynptr slices belonging to skb and xdp dynptrs, 8916 * since these slices point to packet data. 8917 */ 8918 static void clear_all_pkt_pointers(struct bpf_verifier_env *env) 8919 { 8920 struct bpf_func_state *state; 8921 struct bpf_reg_state *reg; 8922 8923 bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({ 8924 if (reg_is_pkt_pointer_any(reg) || reg_is_dynptr_slice_pkt(reg)) 8925 mark_reg_invalid(env, reg); 8926 })); 8927 } 8928 8929 enum { 8930 AT_PKT_END = -1, 8931 BEYOND_PKT_END = -2, 8932 }; 8933 8934 static void mark_pkt_end(struct bpf_verifier_state *vstate, int regn, bool range_open) 8935 { 8936 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 8937 struct bpf_reg_state *reg = &state->regs[regn]; 8938 8939 if (reg->type != PTR_TO_PACKET) 8940 /* PTR_TO_PACKET_META is not supported yet */ 8941 return; 8942 8943 /* The 'reg' is pkt > pkt_end or pkt >= pkt_end. 8944 * How far beyond pkt_end it goes is unknown. 8945 * if (!range_open) it's the case of pkt >= pkt_end 8946 * if (range_open) it's the case of pkt > pkt_end 8947 * hence this pointer is at least 1 byte bigger than pkt_end 8948 */ 8949 if (range_open) 8950 reg->range = BEYOND_PKT_END; 8951 else 8952 reg->range = AT_PKT_END; 8953 } 8954 8955 /* The pointer with the specified id has released its reference to kernel 8956 * resources. Identify all copies of the same pointer and clear the reference. 8957 */ 8958 static int release_reference(struct bpf_verifier_env *env, 8959 int ref_obj_id) 8960 { 8961 struct bpf_func_state *state; 8962 struct bpf_reg_state *reg; 8963 int err; 8964 8965 err = release_reference_state(cur_func(env), ref_obj_id); 8966 if (err) 8967 return err; 8968 8969 bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({ 8970 if (reg->ref_obj_id == ref_obj_id) 8971 mark_reg_invalid(env, reg); 8972 })); 8973 8974 return 0; 8975 } 8976 8977 static void invalidate_non_owning_refs(struct bpf_verifier_env *env) 8978 { 8979 struct bpf_func_state *unused; 8980 struct bpf_reg_state *reg; 8981 8982 bpf_for_each_reg_in_vstate(env->cur_state, unused, reg, ({ 8983 if (type_is_non_owning_ref(reg->type)) 8984 mark_reg_invalid(env, reg); 8985 })); 8986 } 8987 8988 static void clear_caller_saved_regs(struct bpf_verifier_env *env, 8989 struct bpf_reg_state *regs) 8990 { 8991 int i; 8992 8993 /* after the call registers r0 - r5 were scratched */ 8994 for (i = 0; i < CALLER_SAVED_REGS; i++) { 8995 mark_reg_not_init(env, regs, caller_saved[i]); 8996 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK); 8997 } 8998 } 8999 9000 typedef int (*set_callee_state_fn)(struct bpf_verifier_env *env, 9001 struct bpf_func_state *caller, 9002 struct bpf_func_state *callee, 9003 int insn_idx); 9004 9005 static int set_callee_state(struct bpf_verifier_env *env, 9006 struct bpf_func_state *caller, 9007 struct bpf_func_state *callee, int insn_idx); 9008 9009 static int __check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn, 9010 int *insn_idx, int subprog, 9011 set_callee_state_fn set_callee_state_cb) 9012 { 9013 struct bpf_verifier_state *state = env->cur_state; 9014 struct bpf_func_state *caller, *callee; 9015 int err; 9016 9017 if (state->curframe + 1 >= MAX_CALL_FRAMES) { 9018 verbose(env, "the call stack of %d frames is too deep\n", 9019 state->curframe + 2); 9020 return -E2BIG; 9021 } 9022 9023 caller = state->frame[state->curframe]; 9024 if (state->frame[state->curframe + 1]) { 9025 verbose(env, "verifier bug. Frame %d already allocated\n", 9026 state->curframe + 1); 9027 return -EFAULT; 9028 } 9029 9030 err = btf_check_subprog_call(env, subprog, caller->regs); 9031 if (err == -EFAULT) 9032 return err; 9033 if (subprog_is_global(env, subprog)) { 9034 if (err) { 9035 verbose(env, "Caller passes invalid args into func#%d\n", 9036 subprog); 9037 return err; 9038 } else { 9039 if (env->log.level & BPF_LOG_LEVEL) 9040 verbose(env, 9041 "Func#%d is global and valid. Skipping.\n", 9042 subprog); 9043 clear_caller_saved_regs(env, caller->regs); 9044 9045 /* All global functions return a 64-bit SCALAR_VALUE */ 9046 mark_reg_unknown(env, caller->regs, BPF_REG_0); 9047 caller->regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG; 9048 9049 /* continue with next insn after call */ 9050 return 0; 9051 } 9052 } 9053 9054 /* set_callee_state is used for direct subprog calls, but we are 9055 * interested in validating only BPF helpers that can call subprogs as 9056 * callbacks 9057 */ 9058 if (set_callee_state_cb != set_callee_state) { 9059 env->subprog_info[subprog].is_cb = true; 9060 if (bpf_pseudo_kfunc_call(insn) && 9061 !is_callback_calling_kfunc(insn->imm)) { 9062 verbose(env, "verifier bug: kfunc %s#%d not marked as callback-calling\n", 9063 func_id_name(insn->imm), insn->imm); 9064 return -EFAULT; 9065 } else if (!bpf_pseudo_kfunc_call(insn) && 9066 !is_callback_calling_function(insn->imm)) { /* helper */ 9067 verbose(env, "verifier bug: helper %s#%d not marked as callback-calling\n", 9068 func_id_name(insn->imm), insn->imm); 9069 return -EFAULT; 9070 } 9071 } 9072 9073 if (insn->code == (BPF_JMP | BPF_CALL) && 9074 insn->src_reg == 0 && 9075 insn->imm == BPF_FUNC_timer_set_callback) { 9076 struct bpf_verifier_state *async_cb; 9077 9078 /* there is no real recursion here. timer callbacks are async */ 9079 env->subprog_info[subprog].is_async_cb = true; 9080 async_cb = push_async_cb(env, env->subprog_info[subprog].start, 9081 *insn_idx, subprog); 9082 if (!async_cb) 9083 return -EFAULT; 9084 callee = async_cb->frame[0]; 9085 callee->async_entry_cnt = caller->async_entry_cnt + 1; 9086 9087 /* Convert bpf_timer_set_callback() args into timer callback args */ 9088 err = set_callee_state_cb(env, caller, callee, *insn_idx); 9089 if (err) 9090 return err; 9091 9092 clear_caller_saved_regs(env, caller->regs); 9093 mark_reg_unknown(env, caller->regs, BPF_REG_0); 9094 caller->regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG; 9095 /* continue with next insn after call */ 9096 return 0; 9097 } 9098 9099 callee = kzalloc(sizeof(*callee), GFP_KERNEL); 9100 if (!callee) 9101 return -ENOMEM; 9102 state->frame[state->curframe + 1] = callee; 9103 9104 /* callee cannot access r0, r6 - r9 for reading and has to write 9105 * into its own stack before reading from it. 9106 * callee can read/write into caller's stack 9107 */ 9108 init_func_state(env, callee, 9109 /* remember the callsite, it will be used by bpf_exit */ 9110 *insn_idx /* callsite */, 9111 state->curframe + 1 /* frameno within this callchain */, 9112 subprog /* subprog number within this prog */); 9113 9114 /* Transfer references to the callee */ 9115 err = copy_reference_state(callee, caller); 9116 if (err) 9117 goto err_out; 9118 9119 err = set_callee_state_cb(env, caller, callee, *insn_idx); 9120 if (err) 9121 goto err_out; 9122 9123 clear_caller_saved_regs(env, caller->regs); 9124 9125 /* only increment it after check_reg_arg() finished */ 9126 state->curframe++; 9127 9128 /* and go analyze first insn of the callee */ 9129 *insn_idx = env->subprog_info[subprog].start - 1; 9130 9131 if (env->log.level & BPF_LOG_LEVEL) { 9132 verbose(env, "caller:\n"); 9133 print_verifier_state(env, caller, true); 9134 verbose(env, "callee:\n"); 9135 print_verifier_state(env, callee, true); 9136 } 9137 return 0; 9138 9139 err_out: 9140 free_func_state(callee); 9141 state->frame[state->curframe + 1] = NULL; 9142 return err; 9143 } 9144 9145 int map_set_for_each_callback_args(struct bpf_verifier_env *env, 9146 struct bpf_func_state *caller, 9147 struct bpf_func_state *callee) 9148 { 9149 /* bpf_for_each_map_elem(struct bpf_map *map, void *callback_fn, 9150 * void *callback_ctx, u64 flags); 9151 * callback_fn(struct bpf_map *map, void *key, void *value, 9152 * void *callback_ctx); 9153 */ 9154 callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1]; 9155 9156 callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY; 9157 __mark_reg_known_zero(&callee->regs[BPF_REG_2]); 9158 callee->regs[BPF_REG_2].map_ptr = caller->regs[BPF_REG_1].map_ptr; 9159 9160 callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE; 9161 __mark_reg_known_zero(&callee->regs[BPF_REG_3]); 9162 callee->regs[BPF_REG_3].map_ptr = caller->regs[BPF_REG_1].map_ptr; 9163 9164 /* pointer to stack or null */ 9165 callee->regs[BPF_REG_4] = caller->regs[BPF_REG_3]; 9166 9167 /* unused */ 9168 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]); 9169 return 0; 9170 } 9171 9172 static int set_callee_state(struct bpf_verifier_env *env, 9173 struct bpf_func_state *caller, 9174 struct bpf_func_state *callee, int insn_idx) 9175 { 9176 int i; 9177 9178 /* copy r1 - r5 args that callee can access. The copy includes parent 9179 * pointers, which connects us up to the liveness chain 9180 */ 9181 for (i = BPF_REG_1; i <= BPF_REG_5; i++) 9182 callee->regs[i] = caller->regs[i]; 9183 return 0; 9184 } 9185 9186 static int check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn, 9187 int *insn_idx) 9188 { 9189 int subprog, target_insn; 9190 9191 target_insn = *insn_idx + insn->imm + 1; 9192 subprog = find_subprog(env, target_insn); 9193 if (subprog < 0) { 9194 verbose(env, "verifier bug. No program starts at insn %d\n", 9195 target_insn); 9196 return -EFAULT; 9197 } 9198 9199 return __check_func_call(env, insn, insn_idx, subprog, set_callee_state); 9200 } 9201 9202 static int set_map_elem_callback_state(struct bpf_verifier_env *env, 9203 struct bpf_func_state *caller, 9204 struct bpf_func_state *callee, 9205 int insn_idx) 9206 { 9207 struct bpf_insn_aux_data *insn_aux = &env->insn_aux_data[insn_idx]; 9208 struct bpf_map *map; 9209 int err; 9210 9211 if (bpf_map_ptr_poisoned(insn_aux)) { 9212 verbose(env, "tail_call abusing map_ptr\n"); 9213 return -EINVAL; 9214 } 9215 9216 map = BPF_MAP_PTR(insn_aux->map_ptr_state); 9217 if (!map->ops->map_set_for_each_callback_args || 9218 !map->ops->map_for_each_callback) { 9219 verbose(env, "callback function not allowed for map\n"); 9220 return -ENOTSUPP; 9221 } 9222 9223 err = map->ops->map_set_for_each_callback_args(env, caller, callee); 9224 if (err) 9225 return err; 9226 9227 callee->in_callback_fn = true; 9228 callee->callback_ret_range = tnum_range(0, 1); 9229 return 0; 9230 } 9231 9232 static int set_loop_callback_state(struct bpf_verifier_env *env, 9233 struct bpf_func_state *caller, 9234 struct bpf_func_state *callee, 9235 int insn_idx) 9236 { 9237 /* bpf_loop(u32 nr_loops, void *callback_fn, void *callback_ctx, 9238 * u64 flags); 9239 * callback_fn(u32 index, void *callback_ctx); 9240 */ 9241 callee->regs[BPF_REG_1].type = SCALAR_VALUE; 9242 callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3]; 9243 9244 /* unused */ 9245 __mark_reg_not_init(env, &callee->regs[BPF_REG_3]); 9246 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]); 9247 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]); 9248 9249 callee->in_callback_fn = true; 9250 callee->callback_ret_range = tnum_range(0, 1); 9251 return 0; 9252 } 9253 9254 static int set_timer_callback_state(struct bpf_verifier_env *env, 9255 struct bpf_func_state *caller, 9256 struct bpf_func_state *callee, 9257 int insn_idx) 9258 { 9259 struct bpf_map *map_ptr = caller->regs[BPF_REG_1].map_ptr; 9260 9261 /* bpf_timer_set_callback(struct bpf_timer *timer, void *callback_fn); 9262 * callback_fn(struct bpf_map *map, void *key, void *value); 9263 */ 9264 callee->regs[BPF_REG_1].type = CONST_PTR_TO_MAP; 9265 __mark_reg_known_zero(&callee->regs[BPF_REG_1]); 9266 callee->regs[BPF_REG_1].map_ptr = map_ptr; 9267 9268 callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY; 9269 __mark_reg_known_zero(&callee->regs[BPF_REG_2]); 9270 callee->regs[BPF_REG_2].map_ptr = map_ptr; 9271 9272 callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE; 9273 __mark_reg_known_zero(&callee->regs[BPF_REG_3]); 9274 callee->regs[BPF_REG_3].map_ptr = map_ptr; 9275 9276 /* unused */ 9277 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]); 9278 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]); 9279 callee->in_async_callback_fn = true; 9280 callee->callback_ret_range = tnum_range(0, 1); 9281 return 0; 9282 } 9283 9284 static int set_find_vma_callback_state(struct bpf_verifier_env *env, 9285 struct bpf_func_state *caller, 9286 struct bpf_func_state *callee, 9287 int insn_idx) 9288 { 9289 /* bpf_find_vma(struct task_struct *task, u64 addr, 9290 * void *callback_fn, void *callback_ctx, u64 flags) 9291 * (callback_fn)(struct task_struct *task, 9292 * struct vm_area_struct *vma, void *callback_ctx); 9293 */ 9294 callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1]; 9295 9296 callee->regs[BPF_REG_2].type = PTR_TO_BTF_ID; 9297 __mark_reg_known_zero(&callee->regs[BPF_REG_2]); 9298 callee->regs[BPF_REG_2].btf = btf_vmlinux; 9299 callee->regs[BPF_REG_2].btf_id = btf_tracing_ids[BTF_TRACING_TYPE_VMA], 9300 9301 /* pointer to stack or null */ 9302 callee->regs[BPF_REG_3] = caller->regs[BPF_REG_4]; 9303 9304 /* unused */ 9305 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]); 9306 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]); 9307 callee->in_callback_fn = true; 9308 callee->callback_ret_range = tnum_range(0, 1); 9309 return 0; 9310 } 9311 9312 static int set_user_ringbuf_callback_state(struct bpf_verifier_env *env, 9313 struct bpf_func_state *caller, 9314 struct bpf_func_state *callee, 9315 int insn_idx) 9316 { 9317 /* bpf_user_ringbuf_drain(struct bpf_map *map, void *callback_fn, void 9318 * callback_ctx, u64 flags); 9319 * callback_fn(const struct bpf_dynptr_t* dynptr, void *callback_ctx); 9320 */ 9321 __mark_reg_not_init(env, &callee->regs[BPF_REG_0]); 9322 mark_dynptr_cb_reg(env, &callee->regs[BPF_REG_1], BPF_DYNPTR_TYPE_LOCAL); 9323 callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3]; 9324 9325 /* unused */ 9326 __mark_reg_not_init(env, &callee->regs[BPF_REG_3]); 9327 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]); 9328 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]); 9329 9330 callee->in_callback_fn = true; 9331 callee->callback_ret_range = tnum_range(0, 1); 9332 return 0; 9333 } 9334 9335 static int set_rbtree_add_callback_state(struct bpf_verifier_env *env, 9336 struct bpf_func_state *caller, 9337 struct bpf_func_state *callee, 9338 int insn_idx) 9339 { 9340 /* void bpf_rbtree_add_impl(struct bpf_rb_root *root, struct bpf_rb_node *node, 9341 * bool (less)(struct bpf_rb_node *a, const struct bpf_rb_node *b)); 9342 * 9343 * 'struct bpf_rb_node *node' arg to bpf_rbtree_add_impl is the same PTR_TO_BTF_ID w/ offset 9344 * that 'less' callback args will be receiving. However, 'node' arg was release_reference'd 9345 * by this point, so look at 'root' 9346 */ 9347 struct btf_field *field; 9348 9349 field = reg_find_field_offset(&caller->regs[BPF_REG_1], caller->regs[BPF_REG_1].off, 9350 BPF_RB_ROOT); 9351 if (!field || !field->graph_root.value_btf_id) 9352 return -EFAULT; 9353 9354 mark_reg_graph_node(callee->regs, BPF_REG_1, &field->graph_root); 9355 ref_set_non_owning(env, &callee->regs[BPF_REG_1]); 9356 mark_reg_graph_node(callee->regs, BPF_REG_2, &field->graph_root); 9357 ref_set_non_owning(env, &callee->regs[BPF_REG_2]); 9358 9359 __mark_reg_not_init(env, &callee->regs[BPF_REG_3]); 9360 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]); 9361 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]); 9362 callee->in_callback_fn = true; 9363 callee->callback_ret_range = tnum_range(0, 1); 9364 return 0; 9365 } 9366 9367 static bool is_rbtree_lock_required_kfunc(u32 btf_id); 9368 9369 /* Are we currently verifying the callback for a rbtree helper that must 9370 * be called with lock held? If so, no need to complain about unreleased 9371 * lock 9372 */ 9373 static bool in_rbtree_lock_required_cb(struct bpf_verifier_env *env) 9374 { 9375 struct bpf_verifier_state *state = env->cur_state; 9376 struct bpf_insn *insn = env->prog->insnsi; 9377 struct bpf_func_state *callee; 9378 int kfunc_btf_id; 9379 9380 if (!state->curframe) 9381 return false; 9382 9383 callee = state->frame[state->curframe]; 9384 9385 if (!callee->in_callback_fn) 9386 return false; 9387 9388 kfunc_btf_id = insn[callee->callsite].imm; 9389 return is_rbtree_lock_required_kfunc(kfunc_btf_id); 9390 } 9391 9392 static int prepare_func_exit(struct bpf_verifier_env *env, int *insn_idx) 9393 { 9394 struct bpf_verifier_state *state = env->cur_state; 9395 struct bpf_func_state *caller, *callee; 9396 struct bpf_reg_state *r0; 9397 int err; 9398 9399 callee = state->frame[state->curframe]; 9400 r0 = &callee->regs[BPF_REG_0]; 9401 if (r0->type == PTR_TO_STACK) { 9402 /* technically it's ok to return caller's stack pointer 9403 * (or caller's caller's pointer) back to the caller, 9404 * since these pointers are valid. Only current stack 9405 * pointer will be invalid as soon as function exits, 9406 * but let's be conservative 9407 */ 9408 verbose(env, "cannot return stack pointer to the caller\n"); 9409 return -EINVAL; 9410 } 9411 9412 caller = state->frame[state->curframe - 1]; 9413 if (callee->in_callback_fn) { 9414 /* enforce R0 return value range [0, 1]. */ 9415 struct tnum range = callee->callback_ret_range; 9416 9417 if (r0->type != SCALAR_VALUE) { 9418 verbose(env, "R0 not a scalar value\n"); 9419 return -EACCES; 9420 } 9421 if (!tnum_in(range, r0->var_off)) { 9422 verbose_invalid_scalar(env, r0, &range, "callback return", "R0"); 9423 return -EINVAL; 9424 } 9425 } else { 9426 /* return to the caller whatever r0 had in the callee */ 9427 caller->regs[BPF_REG_0] = *r0; 9428 } 9429 9430 /* callback_fn frame should have released its own additions to parent's 9431 * reference state at this point, or check_reference_leak would 9432 * complain, hence it must be the same as the caller. There is no need 9433 * to copy it back. 9434 */ 9435 if (!callee->in_callback_fn) { 9436 /* Transfer references to the caller */ 9437 err = copy_reference_state(caller, callee); 9438 if (err) 9439 return err; 9440 } 9441 9442 *insn_idx = callee->callsite + 1; 9443 if (env->log.level & BPF_LOG_LEVEL) { 9444 verbose(env, "returning from callee:\n"); 9445 print_verifier_state(env, callee, true); 9446 verbose(env, "to caller at %d:\n", *insn_idx); 9447 print_verifier_state(env, caller, true); 9448 } 9449 /* clear everything in the callee. In case of exceptional exits using 9450 * bpf_throw, this will be done by copy_verifier_state for extra frames. */ 9451 free_func_state(callee); 9452 state->frame[state->curframe--] = NULL; 9453 return 0; 9454 } 9455 9456 static void do_refine_retval_range(struct bpf_reg_state *regs, int ret_type, 9457 int func_id, 9458 struct bpf_call_arg_meta *meta) 9459 { 9460 struct bpf_reg_state *ret_reg = ®s[BPF_REG_0]; 9461 9462 if (ret_type != RET_INTEGER) 9463 return; 9464 9465 switch (func_id) { 9466 case BPF_FUNC_get_stack: 9467 case BPF_FUNC_get_task_stack: 9468 case BPF_FUNC_probe_read_str: 9469 case BPF_FUNC_probe_read_kernel_str: 9470 case BPF_FUNC_probe_read_user_str: 9471 ret_reg->smax_value = meta->msize_max_value; 9472 ret_reg->s32_max_value = meta->msize_max_value; 9473 ret_reg->smin_value = -MAX_ERRNO; 9474 ret_reg->s32_min_value = -MAX_ERRNO; 9475 reg_bounds_sync(ret_reg); 9476 break; 9477 case BPF_FUNC_get_smp_processor_id: 9478 ret_reg->umax_value = nr_cpu_ids - 1; 9479 ret_reg->u32_max_value = nr_cpu_ids - 1; 9480 ret_reg->smax_value = nr_cpu_ids - 1; 9481 ret_reg->s32_max_value = nr_cpu_ids - 1; 9482 ret_reg->umin_value = 0; 9483 ret_reg->u32_min_value = 0; 9484 ret_reg->smin_value = 0; 9485 ret_reg->s32_min_value = 0; 9486 reg_bounds_sync(ret_reg); 9487 break; 9488 } 9489 } 9490 9491 static int 9492 record_func_map(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta, 9493 int func_id, int insn_idx) 9494 { 9495 struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx]; 9496 struct bpf_map *map = meta->map_ptr; 9497 9498 if (func_id != BPF_FUNC_tail_call && 9499 func_id != BPF_FUNC_map_lookup_elem && 9500 func_id != BPF_FUNC_map_update_elem && 9501 func_id != BPF_FUNC_map_delete_elem && 9502 func_id != BPF_FUNC_map_push_elem && 9503 func_id != BPF_FUNC_map_pop_elem && 9504 func_id != BPF_FUNC_map_peek_elem && 9505 func_id != BPF_FUNC_for_each_map_elem && 9506 func_id != BPF_FUNC_redirect_map && 9507 func_id != BPF_FUNC_map_lookup_percpu_elem) 9508 return 0; 9509 9510 if (map == NULL) { 9511 verbose(env, "kernel subsystem misconfigured verifier\n"); 9512 return -EINVAL; 9513 } 9514 9515 /* In case of read-only, some additional restrictions 9516 * need to be applied in order to prevent altering the 9517 * state of the map from program side. 9518 */ 9519 if ((map->map_flags & BPF_F_RDONLY_PROG) && 9520 (func_id == BPF_FUNC_map_delete_elem || 9521 func_id == BPF_FUNC_map_update_elem || 9522 func_id == BPF_FUNC_map_push_elem || 9523 func_id == BPF_FUNC_map_pop_elem)) { 9524 verbose(env, "write into map forbidden\n"); 9525 return -EACCES; 9526 } 9527 9528 if (!BPF_MAP_PTR(aux->map_ptr_state)) 9529 bpf_map_ptr_store(aux, meta->map_ptr, 9530 !meta->map_ptr->bypass_spec_v1); 9531 else if (BPF_MAP_PTR(aux->map_ptr_state) != meta->map_ptr) 9532 bpf_map_ptr_store(aux, BPF_MAP_PTR_POISON, 9533 !meta->map_ptr->bypass_spec_v1); 9534 return 0; 9535 } 9536 9537 static int 9538 record_func_key(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta, 9539 int func_id, int insn_idx) 9540 { 9541 struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx]; 9542 struct bpf_reg_state *regs = cur_regs(env), *reg; 9543 struct bpf_map *map = meta->map_ptr; 9544 u64 val, max; 9545 int err; 9546 9547 if (func_id != BPF_FUNC_tail_call) 9548 return 0; 9549 if (!map || map->map_type != BPF_MAP_TYPE_PROG_ARRAY) { 9550 verbose(env, "kernel subsystem misconfigured verifier\n"); 9551 return -EINVAL; 9552 } 9553 9554 reg = ®s[BPF_REG_3]; 9555 val = reg->var_off.value; 9556 max = map->max_entries; 9557 9558 if (!(register_is_const(reg) && val < max)) { 9559 bpf_map_key_store(aux, BPF_MAP_KEY_POISON); 9560 return 0; 9561 } 9562 9563 err = mark_chain_precision(env, BPF_REG_3); 9564 if (err) 9565 return err; 9566 if (bpf_map_key_unseen(aux)) 9567 bpf_map_key_store(aux, val); 9568 else if (!bpf_map_key_poisoned(aux) && 9569 bpf_map_key_immediate(aux) != val) 9570 bpf_map_key_store(aux, BPF_MAP_KEY_POISON); 9571 return 0; 9572 } 9573 9574 static int check_reference_leak(struct bpf_verifier_env *env, bool exception_exit) 9575 { 9576 struct bpf_func_state *state = cur_func(env); 9577 bool refs_lingering = false; 9578 int i; 9579 9580 if (!exception_exit && state->frameno && !state->in_callback_fn) 9581 return 0; 9582 9583 for (i = 0; i < state->acquired_refs; i++) { 9584 if (!exception_exit && state->in_callback_fn && state->refs[i].callback_ref != state->frameno) 9585 continue; 9586 verbose(env, "Unreleased reference id=%d alloc_insn=%d\n", 9587 state->refs[i].id, state->refs[i].insn_idx); 9588 refs_lingering = true; 9589 } 9590 return refs_lingering ? -EINVAL : 0; 9591 } 9592 9593 static int check_bpf_snprintf_call(struct bpf_verifier_env *env, 9594 struct bpf_reg_state *regs) 9595 { 9596 struct bpf_reg_state *fmt_reg = ®s[BPF_REG_3]; 9597 struct bpf_reg_state *data_len_reg = ®s[BPF_REG_5]; 9598 struct bpf_map *fmt_map = fmt_reg->map_ptr; 9599 struct bpf_bprintf_data data = {}; 9600 int err, fmt_map_off, num_args; 9601 u64 fmt_addr; 9602 char *fmt; 9603 9604 /* data must be an array of u64 */ 9605 if (data_len_reg->var_off.value % 8) 9606 return -EINVAL; 9607 num_args = data_len_reg->var_off.value / 8; 9608 9609 /* fmt being ARG_PTR_TO_CONST_STR guarantees that var_off is const 9610 * and map_direct_value_addr is set. 9611 */ 9612 fmt_map_off = fmt_reg->off + fmt_reg->var_off.value; 9613 err = fmt_map->ops->map_direct_value_addr(fmt_map, &fmt_addr, 9614 fmt_map_off); 9615 if (err) { 9616 verbose(env, "verifier bug\n"); 9617 return -EFAULT; 9618 } 9619 fmt = (char *)(long)fmt_addr + fmt_map_off; 9620 9621 /* We are also guaranteed that fmt+fmt_map_off is NULL terminated, we 9622 * can focus on validating the format specifiers. 9623 */ 9624 err = bpf_bprintf_prepare(fmt, UINT_MAX, NULL, num_args, &data); 9625 if (err < 0) 9626 verbose(env, "Invalid format string\n"); 9627 9628 return err; 9629 } 9630 9631 static int check_get_func_ip(struct bpf_verifier_env *env) 9632 { 9633 enum bpf_prog_type type = resolve_prog_type(env->prog); 9634 int func_id = BPF_FUNC_get_func_ip; 9635 9636 if (type == BPF_PROG_TYPE_TRACING) { 9637 if (!bpf_prog_has_trampoline(env->prog)) { 9638 verbose(env, "func %s#%d supported only for fentry/fexit/fmod_ret programs\n", 9639 func_id_name(func_id), func_id); 9640 return -ENOTSUPP; 9641 } 9642 return 0; 9643 } else if (type == BPF_PROG_TYPE_KPROBE) { 9644 return 0; 9645 } 9646 9647 verbose(env, "func %s#%d not supported for program type %d\n", 9648 func_id_name(func_id), func_id, type); 9649 return -ENOTSUPP; 9650 } 9651 9652 static struct bpf_insn_aux_data *cur_aux(struct bpf_verifier_env *env) 9653 { 9654 return &env->insn_aux_data[env->insn_idx]; 9655 } 9656 9657 static bool loop_flag_is_zero(struct bpf_verifier_env *env) 9658 { 9659 struct bpf_reg_state *regs = cur_regs(env); 9660 struct bpf_reg_state *reg = ®s[BPF_REG_4]; 9661 bool reg_is_null = register_is_null(reg); 9662 9663 if (reg_is_null) 9664 mark_chain_precision(env, BPF_REG_4); 9665 9666 return reg_is_null; 9667 } 9668 9669 static void update_loop_inline_state(struct bpf_verifier_env *env, u32 subprogno) 9670 { 9671 struct bpf_loop_inline_state *state = &cur_aux(env)->loop_inline_state; 9672 9673 if (!state->initialized) { 9674 state->initialized = 1; 9675 state->fit_for_inline = loop_flag_is_zero(env); 9676 state->callback_subprogno = subprogno; 9677 return; 9678 } 9679 9680 if (!state->fit_for_inline) 9681 return; 9682 9683 state->fit_for_inline = (loop_flag_is_zero(env) && 9684 state->callback_subprogno == subprogno); 9685 } 9686 9687 static int check_helper_call(struct bpf_verifier_env *env, struct bpf_insn *insn, 9688 int *insn_idx_p) 9689 { 9690 enum bpf_prog_type prog_type = resolve_prog_type(env->prog); 9691 bool returns_cpu_specific_alloc_ptr = false; 9692 const struct bpf_func_proto *fn = NULL; 9693 enum bpf_return_type ret_type; 9694 enum bpf_type_flag ret_flag; 9695 struct bpf_reg_state *regs; 9696 struct bpf_call_arg_meta meta; 9697 int insn_idx = *insn_idx_p; 9698 bool changes_data; 9699 int i, err, func_id; 9700 9701 /* find function prototype */ 9702 func_id = insn->imm; 9703 if (func_id < 0 || func_id >= __BPF_FUNC_MAX_ID) { 9704 verbose(env, "invalid func %s#%d\n", func_id_name(func_id), 9705 func_id); 9706 return -EINVAL; 9707 } 9708 9709 if (env->ops->get_func_proto) 9710 fn = env->ops->get_func_proto(func_id, env->prog); 9711 if (!fn) { 9712 verbose(env, "unknown func %s#%d\n", func_id_name(func_id), 9713 func_id); 9714 return -EINVAL; 9715 } 9716 9717 /* eBPF programs must be GPL compatible to use GPL-ed functions */ 9718 if (!env->prog->gpl_compatible && fn->gpl_only) { 9719 verbose(env, "cannot call GPL-restricted function from non-GPL compatible program\n"); 9720 return -EINVAL; 9721 } 9722 9723 if (fn->allowed && !fn->allowed(env->prog)) { 9724 verbose(env, "helper call is not allowed in probe\n"); 9725 return -EINVAL; 9726 } 9727 9728 if (!env->prog->aux->sleepable && fn->might_sleep) { 9729 verbose(env, "helper call might sleep in a non-sleepable prog\n"); 9730 return -EINVAL; 9731 } 9732 9733 /* With LD_ABS/IND some JITs save/restore skb from r1. */ 9734 changes_data = bpf_helper_changes_pkt_data(fn->func); 9735 if (changes_data && fn->arg1_type != ARG_PTR_TO_CTX) { 9736 verbose(env, "kernel subsystem misconfigured func %s#%d: r1 != ctx\n", 9737 func_id_name(func_id), func_id); 9738 return -EINVAL; 9739 } 9740 9741 memset(&meta, 0, sizeof(meta)); 9742 meta.pkt_access = fn->pkt_access; 9743 9744 err = check_func_proto(fn, func_id); 9745 if (err) { 9746 verbose(env, "kernel subsystem misconfigured func %s#%d\n", 9747 func_id_name(func_id), func_id); 9748 return err; 9749 } 9750 9751 if (env->cur_state->active_rcu_lock) { 9752 if (fn->might_sleep) { 9753 verbose(env, "sleepable helper %s#%d in rcu_read_lock region\n", 9754 func_id_name(func_id), func_id); 9755 return -EINVAL; 9756 } 9757 9758 if (env->prog->aux->sleepable && is_storage_get_function(func_id)) 9759 env->insn_aux_data[insn_idx].storage_get_func_atomic = true; 9760 } 9761 9762 meta.func_id = func_id; 9763 /* check args */ 9764 for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++) { 9765 err = check_func_arg(env, i, &meta, fn, insn_idx); 9766 if (err) 9767 return err; 9768 } 9769 9770 err = record_func_map(env, &meta, func_id, insn_idx); 9771 if (err) 9772 return err; 9773 9774 err = record_func_key(env, &meta, func_id, insn_idx); 9775 if (err) 9776 return err; 9777 9778 /* Mark slots with STACK_MISC in case of raw mode, stack offset 9779 * is inferred from register state. 9780 */ 9781 for (i = 0; i < meta.access_size; i++) { 9782 err = check_mem_access(env, insn_idx, meta.regno, i, BPF_B, 9783 BPF_WRITE, -1, false, false); 9784 if (err) 9785 return err; 9786 } 9787 9788 regs = cur_regs(env); 9789 9790 if (meta.release_regno) { 9791 err = -EINVAL; 9792 /* This can only be set for PTR_TO_STACK, as CONST_PTR_TO_DYNPTR cannot 9793 * be released by any dynptr helper. Hence, unmark_stack_slots_dynptr 9794 * is safe to do directly. 9795 */ 9796 if (arg_type_is_dynptr(fn->arg_type[meta.release_regno - BPF_REG_1])) { 9797 if (regs[meta.release_regno].type == CONST_PTR_TO_DYNPTR) { 9798 verbose(env, "verifier internal error: CONST_PTR_TO_DYNPTR cannot be released\n"); 9799 return -EFAULT; 9800 } 9801 err = unmark_stack_slots_dynptr(env, ®s[meta.release_regno]); 9802 } else if (func_id == BPF_FUNC_kptr_xchg && meta.ref_obj_id) { 9803 u32 ref_obj_id = meta.ref_obj_id; 9804 bool in_rcu = in_rcu_cs(env); 9805 struct bpf_func_state *state; 9806 struct bpf_reg_state *reg; 9807 9808 err = release_reference_state(cur_func(env), ref_obj_id); 9809 if (!err) { 9810 bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({ 9811 if (reg->ref_obj_id == ref_obj_id) { 9812 if (in_rcu && (reg->type & MEM_ALLOC) && (reg->type & MEM_PERCPU)) { 9813 reg->ref_obj_id = 0; 9814 reg->type &= ~MEM_ALLOC; 9815 reg->type |= MEM_RCU; 9816 } else { 9817 mark_reg_invalid(env, reg); 9818 } 9819 } 9820 })); 9821 } 9822 } else if (meta.ref_obj_id) { 9823 err = release_reference(env, meta.ref_obj_id); 9824 } else if (register_is_null(®s[meta.release_regno])) { 9825 /* meta.ref_obj_id can only be 0 if register that is meant to be 9826 * released is NULL, which must be > R0. 9827 */ 9828 err = 0; 9829 } 9830 if (err) { 9831 verbose(env, "func %s#%d reference has not been acquired before\n", 9832 func_id_name(func_id), func_id); 9833 return err; 9834 } 9835 } 9836 9837 switch (func_id) { 9838 case BPF_FUNC_tail_call: 9839 err = check_reference_leak(env, false); 9840 if (err) { 9841 verbose(env, "tail_call would lead to reference leak\n"); 9842 return err; 9843 } 9844 break; 9845 case BPF_FUNC_get_local_storage: 9846 /* check that flags argument in get_local_storage(map, flags) is 0, 9847 * this is required because get_local_storage() can't return an error. 9848 */ 9849 if (!register_is_null(®s[BPF_REG_2])) { 9850 verbose(env, "get_local_storage() doesn't support non-zero flags\n"); 9851 return -EINVAL; 9852 } 9853 break; 9854 case BPF_FUNC_for_each_map_elem: 9855 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno, 9856 set_map_elem_callback_state); 9857 break; 9858 case BPF_FUNC_timer_set_callback: 9859 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno, 9860 set_timer_callback_state); 9861 break; 9862 case BPF_FUNC_find_vma: 9863 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno, 9864 set_find_vma_callback_state); 9865 break; 9866 case BPF_FUNC_snprintf: 9867 err = check_bpf_snprintf_call(env, regs); 9868 break; 9869 case BPF_FUNC_loop: 9870 update_loop_inline_state(env, meta.subprogno); 9871 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno, 9872 set_loop_callback_state); 9873 break; 9874 case BPF_FUNC_dynptr_from_mem: 9875 if (regs[BPF_REG_1].type != PTR_TO_MAP_VALUE) { 9876 verbose(env, "Unsupported reg type %s for bpf_dynptr_from_mem data\n", 9877 reg_type_str(env, regs[BPF_REG_1].type)); 9878 return -EACCES; 9879 } 9880 break; 9881 case BPF_FUNC_set_retval: 9882 if (prog_type == BPF_PROG_TYPE_LSM && 9883 env->prog->expected_attach_type == BPF_LSM_CGROUP) { 9884 if (!env->prog->aux->attach_func_proto->type) { 9885 /* Make sure programs that attach to void 9886 * hooks don't try to modify return value. 9887 */ 9888 verbose(env, "BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n"); 9889 return -EINVAL; 9890 } 9891 } 9892 break; 9893 case BPF_FUNC_dynptr_data: 9894 { 9895 struct bpf_reg_state *reg; 9896 int id, ref_obj_id; 9897 9898 reg = get_dynptr_arg_reg(env, fn, regs); 9899 if (!reg) 9900 return -EFAULT; 9901 9902 9903 if (meta.dynptr_id) { 9904 verbose(env, "verifier internal error: meta.dynptr_id already set\n"); 9905 return -EFAULT; 9906 } 9907 if (meta.ref_obj_id) { 9908 verbose(env, "verifier internal error: meta.ref_obj_id already set\n"); 9909 return -EFAULT; 9910 } 9911 9912 id = dynptr_id(env, reg); 9913 if (id < 0) { 9914 verbose(env, "verifier internal error: failed to obtain dynptr id\n"); 9915 return id; 9916 } 9917 9918 ref_obj_id = dynptr_ref_obj_id(env, reg); 9919 if (ref_obj_id < 0) { 9920 verbose(env, "verifier internal error: failed to obtain dynptr ref_obj_id\n"); 9921 return ref_obj_id; 9922 } 9923 9924 meta.dynptr_id = id; 9925 meta.ref_obj_id = ref_obj_id; 9926 9927 break; 9928 } 9929 case BPF_FUNC_dynptr_write: 9930 { 9931 enum bpf_dynptr_type dynptr_type; 9932 struct bpf_reg_state *reg; 9933 9934 reg = get_dynptr_arg_reg(env, fn, regs); 9935 if (!reg) 9936 return -EFAULT; 9937 9938 dynptr_type = dynptr_get_type(env, reg); 9939 if (dynptr_type == BPF_DYNPTR_TYPE_INVALID) 9940 return -EFAULT; 9941 9942 if (dynptr_type == BPF_DYNPTR_TYPE_SKB) 9943 /* this will trigger clear_all_pkt_pointers(), which will 9944 * invalidate all dynptr slices associated with the skb 9945 */ 9946 changes_data = true; 9947 9948 break; 9949 } 9950 case BPF_FUNC_per_cpu_ptr: 9951 case BPF_FUNC_this_cpu_ptr: 9952 { 9953 struct bpf_reg_state *reg = ®s[BPF_REG_1]; 9954 const struct btf_type *type; 9955 9956 if (reg->type & MEM_RCU) { 9957 type = btf_type_by_id(reg->btf, reg->btf_id); 9958 if (!type || !btf_type_is_struct(type)) { 9959 verbose(env, "Helper has invalid btf/btf_id in R1\n"); 9960 return -EFAULT; 9961 } 9962 returns_cpu_specific_alloc_ptr = true; 9963 env->insn_aux_data[insn_idx].call_with_percpu_alloc_ptr = true; 9964 } 9965 break; 9966 } 9967 case BPF_FUNC_user_ringbuf_drain: 9968 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno, 9969 set_user_ringbuf_callback_state); 9970 break; 9971 } 9972 9973 if (err) 9974 return err; 9975 9976 /* reset caller saved regs */ 9977 for (i = 0; i < CALLER_SAVED_REGS; i++) { 9978 mark_reg_not_init(env, regs, caller_saved[i]); 9979 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK); 9980 } 9981 9982 /* helper call returns 64-bit value. */ 9983 regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG; 9984 9985 /* update return register (already marked as written above) */ 9986 ret_type = fn->ret_type; 9987 ret_flag = type_flag(ret_type); 9988 9989 switch (base_type(ret_type)) { 9990 case RET_INTEGER: 9991 /* sets type to SCALAR_VALUE */ 9992 mark_reg_unknown(env, regs, BPF_REG_0); 9993 break; 9994 case RET_VOID: 9995 regs[BPF_REG_0].type = NOT_INIT; 9996 break; 9997 case RET_PTR_TO_MAP_VALUE: 9998 /* There is no offset yet applied, variable or fixed */ 9999 mark_reg_known_zero(env, regs, BPF_REG_0); 10000 /* remember map_ptr, so that check_map_access() 10001 * can check 'value_size' boundary of memory access 10002 * to map element returned from bpf_map_lookup_elem() 10003 */ 10004 if (meta.map_ptr == NULL) { 10005 verbose(env, 10006 "kernel subsystem misconfigured verifier\n"); 10007 return -EINVAL; 10008 } 10009 regs[BPF_REG_0].map_ptr = meta.map_ptr; 10010 regs[BPF_REG_0].map_uid = meta.map_uid; 10011 regs[BPF_REG_0].type = PTR_TO_MAP_VALUE | ret_flag; 10012 if (!type_may_be_null(ret_type) && 10013 btf_record_has_field(meta.map_ptr->record, BPF_SPIN_LOCK)) { 10014 regs[BPF_REG_0].id = ++env->id_gen; 10015 } 10016 break; 10017 case RET_PTR_TO_SOCKET: 10018 mark_reg_known_zero(env, regs, BPF_REG_0); 10019 regs[BPF_REG_0].type = PTR_TO_SOCKET | ret_flag; 10020 break; 10021 case RET_PTR_TO_SOCK_COMMON: 10022 mark_reg_known_zero(env, regs, BPF_REG_0); 10023 regs[BPF_REG_0].type = PTR_TO_SOCK_COMMON | ret_flag; 10024 break; 10025 case RET_PTR_TO_TCP_SOCK: 10026 mark_reg_known_zero(env, regs, BPF_REG_0); 10027 regs[BPF_REG_0].type = PTR_TO_TCP_SOCK | ret_flag; 10028 break; 10029 case RET_PTR_TO_MEM: 10030 mark_reg_known_zero(env, regs, BPF_REG_0); 10031 regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag; 10032 regs[BPF_REG_0].mem_size = meta.mem_size; 10033 break; 10034 case RET_PTR_TO_MEM_OR_BTF_ID: 10035 { 10036 const struct btf_type *t; 10037 10038 mark_reg_known_zero(env, regs, BPF_REG_0); 10039 t = btf_type_skip_modifiers(meta.ret_btf, meta.ret_btf_id, NULL); 10040 if (!btf_type_is_struct(t)) { 10041 u32 tsize; 10042 const struct btf_type *ret; 10043 const char *tname; 10044 10045 /* resolve the type size of ksym. */ 10046 ret = btf_resolve_size(meta.ret_btf, t, &tsize); 10047 if (IS_ERR(ret)) { 10048 tname = btf_name_by_offset(meta.ret_btf, t->name_off); 10049 verbose(env, "unable to resolve the size of type '%s': %ld\n", 10050 tname, PTR_ERR(ret)); 10051 return -EINVAL; 10052 } 10053 regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag; 10054 regs[BPF_REG_0].mem_size = tsize; 10055 } else { 10056 if (returns_cpu_specific_alloc_ptr) { 10057 regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC | MEM_RCU; 10058 } else { 10059 /* MEM_RDONLY may be carried from ret_flag, but it 10060 * doesn't apply on PTR_TO_BTF_ID. Fold it, otherwise 10061 * it will confuse the check of PTR_TO_BTF_ID in 10062 * check_mem_access(). 10063 */ 10064 ret_flag &= ~MEM_RDONLY; 10065 regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag; 10066 } 10067 10068 regs[BPF_REG_0].btf = meta.ret_btf; 10069 regs[BPF_REG_0].btf_id = meta.ret_btf_id; 10070 } 10071 break; 10072 } 10073 case RET_PTR_TO_BTF_ID: 10074 { 10075 struct btf *ret_btf; 10076 int ret_btf_id; 10077 10078 mark_reg_known_zero(env, regs, BPF_REG_0); 10079 regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag; 10080 if (func_id == BPF_FUNC_kptr_xchg) { 10081 ret_btf = meta.kptr_field->kptr.btf; 10082 ret_btf_id = meta.kptr_field->kptr.btf_id; 10083 if (!btf_is_kernel(ret_btf)) { 10084 regs[BPF_REG_0].type |= MEM_ALLOC; 10085 if (meta.kptr_field->type == BPF_KPTR_PERCPU) 10086 regs[BPF_REG_0].type |= MEM_PERCPU; 10087 } 10088 } else { 10089 if (fn->ret_btf_id == BPF_PTR_POISON) { 10090 verbose(env, "verifier internal error:"); 10091 verbose(env, "func %s has non-overwritten BPF_PTR_POISON return type\n", 10092 func_id_name(func_id)); 10093 return -EINVAL; 10094 } 10095 ret_btf = btf_vmlinux; 10096 ret_btf_id = *fn->ret_btf_id; 10097 } 10098 if (ret_btf_id == 0) { 10099 verbose(env, "invalid return type %u of func %s#%d\n", 10100 base_type(ret_type), func_id_name(func_id), 10101 func_id); 10102 return -EINVAL; 10103 } 10104 regs[BPF_REG_0].btf = ret_btf; 10105 regs[BPF_REG_0].btf_id = ret_btf_id; 10106 break; 10107 } 10108 default: 10109 verbose(env, "unknown return type %u of func %s#%d\n", 10110 base_type(ret_type), func_id_name(func_id), func_id); 10111 return -EINVAL; 10112 } 10113 10114 if (type_may_be_null(regs[BPF_REG_0].type)) 10115 regs[BPF_REG_0].id = ++env->id_gen; 10116 10117 if (helper_multiple_ref_obj_use(func_id, meta.map_ptr)) { 10118 verbose(env, "verifier internal error: func %s#%d sets ref_obj_id more than once\n", 10119 func_id_name(func_id), func_id); 10120 return -EFAULT; 10121 } 10122 10123 if (is_dynptr_ref_function(func_id)) 10124 regs[BPF_REG_0].dynptr_id = meta.dynptr_id; 10125 10126 if (is_ptr_cast_function(func_id) || is_dynptr_ref_function(func_id)) { 10127 /* For release_reference() */ 10128 regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id; 10129 } else if (is_acquire_function(func_id, meta.map_ptr)) { 10130 int id = acquire_reference_state(env, insn_idx); 10131 10132 if (id < 0) 10133 return id; 10134 /* For mark_ptr_or_null_reg() */ 10135 regs[BPF_REG_0].id = id; 10136 /* For release_reference() */ 10137 regs[BPF_REG_0].ref_obj_id = id; 10138 } 10139 10140 do_refine_retval_range(regs, fn->ret_type, func_id, &meta); 10141 10142 err = check_map_func_compatibility(env, meta.map_ptr, func_id); 10143 if (err) 10144 return err; 10145 10146 if ((func_id == BPF_FUNC_get_stack || 10147 func_id == BPF_FUNC_get_task_stack) && 10148 !env->prog->has_callchain_buf) { 10149 const char *err_str; 10150 10151 #ifdef CONFIG_PERF_EVENTS 10152 err = get_callchain_buffers(sysctl_perf_event_max_stack); 10153 err_str = "cannot get callchain buffer for func %s#%d\n"; 10154 #else 10155 err = -ENOTSUPP; 10156 err_str = "func %s#%d not supported without CONFIG_PERF_EVENTS\n"; 10157 #endif 10158 if (err) { 10159 verbose(env, err_str, func_id_name(func_id), func_id); 10160 return err; 10161 } 10162 10163 env->prog->has_callchain_buf = true; 10164 } 10165 10166 if (func_id == BPF_FUNC_get_stackid || func_id == BPF_FUNC_get_stack) 10167 env->prog->call_get_stack = true; 10168 10169 if (func_id == BPF_FUNC_get_func_ip) { 10170 if (check_get_func_ip(env)) 10171 return -ENOTSUPP; 10172 env->prog->call_get_func_ip = true; 10173 } 10174 10175 if (changes_data) 10176 clear_all_pkt_pointers(env); 10177 return 0; 10178 } 10179 10180 /* mark_btf_func_reg_size() is used when the reg size is determined by 10181 * the BTF func_proto's return value size and argument. 10182 */ 10183 static void mark_btf_func_reg_size(struct bpf_verifier_env *env, u32 regno, 10184 size_t reg_size) 10185 { 10186 struct bpf_reg_state *reg = &cur_regs(env)[regno]; 10187 10188 if (regno == BPF_REG_0) { 10189 /* Function return value */ 10190 reg->live |= REG_LIVE_WRITTEN; 10191 reg->subreg_def = reg_size == sizeof(u64) ? 10192 DEF_NOT_SUBREG : env->insn_idx + 1; 10193 } else { 10194 /* Function argument */ 10195 if (reg_size == sizeof(u64)) { 10196 mark_insn_zext(env, reg); 10197 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64); 10198 } else { 10199 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ32); 10200 } 10201 } 10202 } 10203 10204 static bool is_kfunc_acquire(struct bpf_kfunc_call_arg_meta *meta) 10205 { 10206 return meta->kfunc_flags & KF_ACQUIRE; 10207 } 10208 10209 static bool is_kfunc_release(struct bpf_kfunc_call_arg_meta *meta) 10210 { 10211 return meta->kfunc_flags & KF_RELEASE; 10212 } 10213 10214 static bool is_kfunc_trusted_args(struct bpf_kfunc_call_arg_meta *meta) 10215 { 10216 return (meta->kfunc_flags & KF_TRUSTED_ARGS) || is_kfunc_release(meta); 10217 } 10218 10219 static bool is_kfunc_sleepable(struct bpf_kfunc_call_arg_meta *meta) 10220 { 10221 return meta->kfunc_flags & KF_SLEEPABLE; 10222 } 10223 10224 static bool is_kfunc_destructive(struct bpf_kfunc_call_arg_meta *meta) 10225 { 10226 return meta->kfunc_flags & KF_DESTRUCTIVE; 10227 } 10228 10229 static bool is_kfunc_rcu(struct bpf_kfunc_call_arg_meta *meta) 10230 { 10231 return meta->kfunc_flags & KF_RCU; 10232 } 10233 10234 static bool __kfunc_param_match_suffix(const struct btf *btf, 10235 const struct btf_param *arg, 10236 const char *suffix) 10237 { 10238 int suffix_len = strlen(suffix), len; 10239 const char *param_name; 10240 10241 /* In the future, this can be ported to use BTF tagging */ 10242 param_name = btf_name_by_offset(btf, arg->name_off); 10243 if (str_is_empty(param_name)) 10244 return false; 10245 len = strlen(param_name); 10246 if (len < suffix_len) 10247 return false; 10248 param_name += len - suffix_len; 10249 return !strncmp(param_name, suffix, suffix_len); 10250 } 10251 10252 static bool is_kfunc_arg_mem_size(const struct btf *btf, 10253 const struct btf_param *arg, 10254 const struct bpf_reg_state *reg) 10255 { 10256 const struct btf_type *t; 10257 10258 t = btf_type_skip_modifiers(btf, arg->type, NULL); 10259 if (!btf_type_is_scalar(t) || reg->type != SCALAR_VALUE) 10260 return false; 10261 10262 return __kfunc_param_match_suffix(btf, arg, "__sz"); 10263 } 10264 10265 static bool is_kfunc_arg_const_mem_size(const struct btf *btf, 10266 const struct btf_param *arg, 10267 const struct bpf_reg_state *reg) 10268 { 10269 const struct btf_type *t; 10270 10271 t = btf_type_skip_modifiers(btf, arg->type, NULL); 10272 if (!btf_type_is_scalar(t) || reg->type != SCALAR_VALUE) 10273 return false; 10274 10275 return __kfunc_param_match_suffix(btf, arg, "__szk"); 10276 } 10277 10278 static bool is_kfunc_arg_optional(const struct btf *btf, const struct btf_param *arg) 10279 { 10280 return __kfunc_param_match_suffix(btf, arg, "__opt"); 10281 } 10282 10283 static bool is_kfunc_arg_constant(const struct btf *btf, const struct btf_param *arg) 10284 { 10285 return __kfunc_param_match_suffix(btf, arg, "__k"); 10286 } 10287 10288 static bool is_kfunc_arg_ignore(const struct btf *btf, const struct btf_param *arg) 10289 { 10290 return __kfunc_param_match_suffix(btf, arg, "__ign"); 10291 } 10292 10293 static bool is_kfunc_arg_alloc_obj(const struct btf *btf, const struct btf_param *arg) 10294 { 10295 return __kfunc_param_match_suffix(btf, arg, "__alloc"); 10296 } 10297 10298 static bool is_kfunc_arg_uninit(const struct btf *btf, const struct btf_param *arg) 10299 { 10300 return __kfunc_param_match_suffix(btf, arg, "__uninit"); 10301 } 10302 10303 static bool is_kfunc_arg_refcounted_kptr(const struct btf *btf, const struct btf_param *arg) 10304 { 10305 return __kfunc_param_match_suffix(btf, arg, "__refcounted_kptr"); 10306 } 10307 10308 static bool is_kfunc_arg_scalar_with_name(const struct btf *btf, 10309 const struct btf_param *arg, 10310 const char *name) 10311 { 10312 int len, target_len = strlen(name); 10313 const char *param_name; 10314 10315 param_name = btf_name_by_offset(btf, arg->name_off); 10316 if (str_is_empty(param_name)) 10317 return false; 10318 len = strlen(param_name); 10319 if (len != target_len) 10320 return false; 10321 if (strcmp(param_name, name)) 10322 return false; 10323 10324 return true; 10325 } 10326 10327 enum { 10328 KF_ARG_DYNPTR_ID, 10329 KF_ARG_LIST_HEAD_ID, 10330 KF_ARG_LIST_NODE_ID, 10331 KF_ARG_RB_ROOT_ID, 10332 KF_ARG_RB_NODE_ID, 10333 }; 10334 10335 BTF_ID_LIST(kf_arg_btf_ids) 10336 BTF_ID(struct, bpf_dynptr_kern) 10337 BTF_ID(struct, bpf_list_head) 10338 BTF_ID(struct, bpf_list_node) 10339 BTF_ID(struct, bpf_rb_root) 10340 BTF_ID(struct, bpf_rb_node) 10341 10342 static bool __is_kfunc_ptr_arg_type(const struct btf *btf, 10343 const struct btf_param *arg, int type) 10344 { 10345 const struct btf_type *t; 10346 u32 res_id; 10347 10348 t = btf_type_skip_modifiers(btf, arg->type, NULL); 10349 if (!t) 10350 return false; 10351 if (!btf_type_is_ptr(t)) 10352 return false; 10353 t = btf_type_skip_modifiers(btf, t->type, &res_id); 10354 if (!t) 10355 return false; 10356 return btf_types_are_same(btf, res_id, btf_vmlinux, kf_arg_btf_ids[type]); 10357 } 10358 10359 static bool is_kfunc_arg_dynptr(const struct btf *btf, const struct btf_param *arg) 10360 { 10361 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_DYNPTR_ID); 10362 } 10363 10364 static bool is_kfunc_arg_list_head(const struct btf *btf, const struct btf_param *arg) 10365 { 10366 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_LIST_HEAD_ID); 10367 } 10368 10369 static bool is_kfunc_arg_list_node(const struct btf *btf, const struct btf_param *arg) 10370 { 10371 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_LIST_NODE_ID); 10372 } 10373 10374 static bool is_kfunc_arg_rbtree_root(const struct btf *btf, const struct btf_param *arg) 10375 { 10376 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_RB_ROOT_ID); 10377 } 10378 10379 static bool is_kfunc_arg_rbtree_node(const struct btf *btf, const struct btf_param *arg) 10380 { 10381 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_RB_NODE_ID); 10382 } 10383 10384 static bool is_kfunc_arg_callback(struct bpf_verifier_env *env, const struct btf *btf, 10385 const struct btf_param *arg) 10386 { 10387 const struct btf_type *t; 10388 10389 t = btf_type_resolve_func_ptr(btf, arg->type, NULL); 10390 if (!t) 10391 return false; 10392 10393 return true; 10394 } 10395 10396 /* Returns true if struct is composed of scalars, 4 levels of nesting allowed */ 10397 static bool __btf_type_is_scalar_struct(struct bpf_verifier_env *env, 10398 const struct btf *btf, 10399 const struct btf_type *t, int rec) 10400 { 10401 const struct btf_type *member_type; 10402 const struct btf_member *member; 10403 u32 i; 10404 10405 if (!btf_type_is_struct(t)) 10406 return false; 10407 10408 for_each_member(i, t, member) { 10409 const struct btf_array *array; 10410 10411 member_type = btf_type_skip_modifiers(btf, member->type, NULL); 10412 if (btf_type_is_struct(member_type)) { 10413 if (rec >= 3) { 10414 verbose(env, "max struct nesting depth exceeded\n"); 10415 return false; 10416 } 10417 if (!__btf_type_is_scalar_struct(env, btf, member_type, rec + 1)) 10418 return false; 10419 continue; 10420 } 10421 if (btf_type_is_array(member_type)) { 10422 array = btf_array(member_type); 10423 if (!array->nelems) 10424 return false; 10425 member_type = btf_type_skip_modifiers(btf, array->type, NULL); 10426 if (!btf_type_is_scalar(member_type)) 10427 return false; 10428 continue; 10429 } 10430 if (!btf_type_is_scalar(member_type)) 10431 return false; 10432 } 10433 return true; 10434 } 10435 10436 enum kfunc_ptr_arg_type { 10437 KF_ARG_PTR_TO_CTX, 10438 KF_ARG_PTR_TO_ALLOC_BTF_ID, /* Allocated object */ 10439 KF_ARG_PTR_TO_REFCOUNTED_KPTR, /* Refcounted local kptr */ 10440 KF_ARG_PTR_TO_DYNPTR, 10441 KF_ARG_PTR_TO_ITER, 10442 KF_ARG_PTR_TO_LIST_HEAD, 10443 KF_ARG_PTR_TO_LIST_NODE, 10444 KF_ARG_PTR_TO_BTF_ID, /* Also covers reg2btf_ids conversions */ 10445 KF_ARG_PTR_TO_MEM, 10446 KF_ARG_PTR_TO_MEM_SIZE, /* Size derived from next argument, skip it */ 10447 KF_ARG_PTR_TO_CALLBACK, 10448 KF_ARG_PTR_TO_RB_ROOT, 10449 KF_ARG_PTR_TO_RB_NODE, 10450 }; 10451 10452 enum special_kfunc_type { 10453 KF_bpf_obj_new_impl, 10454 KF_bpf_obj_drop_impl, 10455 KF_bpf_refcount_acquire_impl, 10456 KF_bpf_list_push_front_impl, 10457 KF_bpf_list_push_back_impl, 10458 KF_bpf_list_pop_front, 10459 KF_bpf_list_pop_back, 10460 KF_bpf_cast_to_kern_ctx, 10461 KF_bpf_rdonly_cast, 10462 KF_bpf_rcu_read_lock, 10463 KF_bpf_rcu_read_unlock, 10464 KF_bpf_rbtree_remove, 10465 KF_bpf_rbtree_add_impl, 10466 KF_bpf_rbtree_first, 10467 KF_bpf_dynptr_from_skb, 10468 KF_bpf_dynptr_from_xdp, 10469 KF_bpf_dynptr_slice, 10470 KF_bpf_dynptr_slice_rdwr, 10471 KF_bpf_dynptr_clone, 10472 KF_bpf_percpu_obj_new_impl, 10473 KF_bpf_percpu_obj_drop_impl, 10474 KF_bpf_throw, 10475 }; 10476 10477 BTF_SET_START(special_kfunc_set) 10478 BTF_ID(func, bpf_obj_new_impl) 10479 BTF_ID(func, bpf_obj_drop_impl) 10480 BTF_ID(func, bpf_refcount_acquire_impl) 10481 BTF_ID(func, bpf_list_push_front_impl) 10482 BTF_ID(func, bpf_list_push_back_impl) 10483 BTF_ID(func, bpf_list_pop_front) 10484 BTF_ID(func, bpf_list_pop_back) 10485 BTF_ID(func, bpf_cast_to_kern_ctx) 10486 BTF_ID(func, bpf_rdonly_cast) 10487 BTF_ID(func, bpf_rbtree_remove) 10488 BTF_ID(func, bpf_rbtree_add_impl) 10489 BTF_ID(func, bpf_rbtree_first) 10490 BTF_ID(func, bpf_dynptr_from_skb) 10491 BTF_ID(func, bpf_dynptr_from_xdp) 10492 BTF_ID(func, bpf_dynptr_slice) 10493 BTF_ID(func, bpf_dynptr_slice_rdwr) 10494 BTF_ID(func, bpf_dynptr_clone) 10495 BTF_ID(func, bpf_percpu_obj_new_impl) 10496 BTF_ID(func, bpf_percpu_obj_drop_impl) 10497 BTF_ID(func, bpf_throw) 10498 BTF_SET_END(special_kfunc_set) 10499 10500 BTF_ID_LIST(special_kfunc_list) 10501 BTF_ID(func, bpf_obj_new_impl) 10502 BTF_ID(func, bpf_obj_drop_impl) 10503 BTF_ID(func, bpf_refcount_acquire_impl) 10504 BTF_ID(func, bpf_list_push_front_impl) 10505 BTF_ID(func, bpf_list_push_back_impl) 10506 BTF_ID(func, bpf_list_pop_front) 10507 BTF_ID(func, bpf_list_pop_back) 10508 BTF_ID(func, bpf_cast_to_kern_ctx) 10509 BTF_ID(func, bpf_rdonly_cast) 10510 BTF_ID(func, bpf_rcu_read_lock) 10511 BTF_ID(func, bpf_rcu_read_unlock) 10512 BTF_ID(func, bpf_rbtree_remove) 10513 BTF_ID(func, bpf_rbtree_add_impl) 10514 BTF_ID(func, bpf_rbtree_first) 10515 BTF_ID(func, bpf_dynptr_from_skb) 10516 BTF_ID(func, bpf_dynptr_from_xdp) 10517 BTF_ID(func, bpf_dynptr_slice) 10518 BTF_ID(func, bpf_dynptr_slice_rdwr) 10519 BTF_ID(func, bpf_dynptr_clone) 10520 BTF_ID(func, bpf_percpu_obj_new_impl) 10521 BTF_ID(func, bpf_percpu_obj_drop_impl) 10522 BTF_ID(func, bpf_throw) 10523 10524 static bool is_kfunc_ret_null(struct bpf_kfunc_call_arg_meta *meta) 10525 { 10526 if (meta->func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl] && 10527 meta->arg_owning_ref) { 10528 return false; 10529 } 10530 10531 return meta->kfunc_flags & KF_RET_NULL; 10532 } 10533 10534 static bool is_kfunc_bpf_rcu_read_lock(struct bpf_kfunc_call_arg_meta *meta) 10535 { 10536 return meta->func_id == special_kfunc_list[KF_bpf_rcu_read_lock]; 10537 } 10538 10539 static bool is_kfunc_bpf_rcu_read_unlock(struct bpf_kfunc_call_arg_meta *meta) 10540 { 10541 return meta->func_id == special_kfunc_list[KF_bpf_rcu_read_unlock]; 10542 } 10543 10544 static enum kfunc_ptr_arg_type 10545 get_kfunc_ptr_arg_type(struct bpf_verifier_env *env, 10546 struct bpf_kfunc_call_arg_meta *meta, 10547 const struct btf_type *t, const struct btf_type *ref_t, 10548 const char *ref_tname, const struct btf_param *args, 10549 int argno, int nargs) 10550 { 10551 u32 regno = argno + 1; 10552 struct bpf_reg_state *regs = cur_regs(env); 10553 struct bpf_reg_state *reg = ®s[regno]; 10554 bool arg_mem_size = false; 10555 10556 if (meta->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx]) 10557 return KF_ARG_PTR_TO_CTX; 10558 10559 /* In this function, we verify the kfunc's BTF as per the argument type, 10560 * leaving the rest of the verification with respect to the register 10561 * type to our caller. When a set of conditions hold in the BTF type of 10562 * arguments, we resolve it to a known kfunc_ptr_arg_type. 10563 */ 10564 if (btf_get_prog_ctx_type(&env->log, meta->btf, t, resolve_prog_type(env->prog), argno)) 10565 return KF_ARG_PTR_TO_CTX; 10566 10567 if (is_kfunc_arg_alloc_obj(meta->btf, &args[argno])) 10568 return KF_ARG_PTR_TO_ALLOC_BTF_ID; 10569 10570 if (is_kfunc_arg_refcounted_kptr(meta->btf, &args[argno])) 10571 return KF_ARG_PTR_TO_REFCOUNTED_KPTR; 10572 10573 if (is_kfunc_arg_dynptr(meta->btf, &args[argno])) 10574 return KF_ARG_PTR_TO_DYNPTR; 10575 10576 if (is_kfunc_arg_iter(meta, argno)) 10577 return KF_ARG_PTR_TO_ITER; 10578 10579 if (is_kfunc_arg_list_head(meta->btf, &args[argno])) 10580 return KF_ARG_PTR_TO_LIST_HEAD; 10581 10582 if (is_kfunc_arg_list_node(meta->btf, &args[argno])) 10583 return KF_ARG_PTR_TO_LIST_NODE; 10584 10585 if (is_kfunc_arg_rbtree_root(meta->btf, &args[argno])) 10586 return KF_ARG_PTR_TO_RB_ROOT; 10587 10588 if (is_kfunc_arg_rbtree_node(meta->btf, &args[argno])) 10589 return KF_ARG_PTR_TO_RB_NODE; 10590 10591 if ((base_type(reg->type) == PTR_TO_BTF_ID || reg2btf_ids[base_type(reg->type)])) { 10592 if (!btf_type_is_struct(ref_t)) { 10593 verbose(env, "kernel function %s args#%d pointer type %s %s is not supported\n", 10594 meta->func_name, argno, btf_type_str(ref_t), ref_tname); 10595 return -EINVAL; 10596 } 10597 return KF_ARG_PTR_TO_BTF_ID; 10598 } 10599 10600 if (is_kfunc_arg_callback(env, meta->btf, &args[argno])) 10601 return KF_ARG_PTR_TO_CALLBACK; 10602 10603 10604 if (argno + 1 < nargs && 10605 (is_kfunc_arg_mem_size(meta->btf, &args[argno + 1], ®s[regno + 1]) || 10606 is_kfunc_arg_const_mem_size(meta->btf, &args[argno + 1], ®s[regno + 1]))) 10607 arg_mem_size = true; 10608 10609 /* This is the catch all argument type of register types supported by 10610 * check_helper_mem_access. However, we only allow when argument type is 10611 * pointer to scalar, or struct composed (recursively) of scalars. When 10612 * arg_mem_size is true, the pointer can be void *. 10613 */ 10614 if (!btf_type_is_scalar(ref_t) && !__btf_type_is_scalar_struct(env, meta->btf, ref_t, 0) && 10615 (arg_mem_size ? !btf_type_is_void(ref_t) : 1)) { 10616 verbose(env, "arg#%d pointer type %s %s must point to %sscalar, or struct with scalar\n", 10617 argno, btf_type_str(ref_t), ref_tname, arg_mem_size ? "void, " : ""); 10618 return -EINVAL; 10619 } 10620 return arg_mem_size ? KF_ARG_PTR_TO_MEM_SIZE : KF_ARG_PTR_TO_MEM; 10621 } 10622 10623 static int process_kf_arg_ptr_to_btf_id(struct bpf_verifier_env *env, 10624 struct bpf_reg_state *reg, 10625 const struct btf_type *ref_t, 10626 const char *ref_tname, u32 ref_id, 10627 struct bpf_kfunc_call_arg_meta *meta, 10628 int argno) 10629 { 10630 const struct btf_type *reg_ref_t; 10631 bool strict_type_match = false; 10632 const struct btf *reg_btf; 10633 const char *reg_ref_tname; 10634 u32 reg_ref_id; 10635 10636 if (base_type(reg->type) == PTR_TO_BTF_ID) { 10637 reg_btf = reg->btf; 10638 reg_ref_id = reg->btf_id; 10639 } else { 10640 reg_btf = btf_vmlinux; 10641 reg_ref_id = *reg2btf_ids[base_type(reg->type)]; 10642 } 10643 10644 /* Enforce strict type matching for calls to kfuncs that are acquiring 10645 * or releasing a reference, or are no-cast aliases. We do _not_ 10646 * enforce strict matching for plain KF_TRUSTED_ARGS kfuncs by default, 10647 * as we want to enable BPF programs to pass types that are bitwise 10648 * equivalent without forcing them to explicitly cast with something 10649 * like bpf_cast_to_kern_ctx(). 10650 * 10651 * For example, say we had a type like the following: 10652 * 10653 * struct bpf_cpumask { 10654 * cpumask_t cpumask; 10655 * refcount_t usage; 10656 * }; 10657 * 10658 * Note that as specified in <linux/cpumask.h>, cpumask_t is typedef'ed 10659 * to a struct cpumask, so it would be safe to pass a struct 10660 * bpf_cpumask * to a kfunc expecting a struct cpumask *. 10661 * 10662 * The philosophy here is similar to how we allow scalars of different 10663 * types to be passed to kfuncs as long as the size is the same. The 10664 * only difference here is that we're simply allowing 10665 * btf_struct_ids_match() to walk the struct at the 0th offset, and 10666 * resolve types. 10667 */ 10668 if (is_kfunc_acquire(meta) || 10669 (is_kfunc_release(meta) && reg->ref_obj_id) || 10670 btf_type_ids_nocast_alias(&env->log, reg_btf, reg_ref_id, meta->btf, ref_id)) 10671 strict_type_match = true; 10672 10673 WARN_ON_ONCE(is_kfunc_trusted_args(meta) && reg->off); 10674 10675 reg_ref_t = btf_type_skip_modifiers(reg_btf, reg_ref_id, ®_ref_id); 10676 reg_ref_tname = btf_name_by_offset(reg_btf, reg_ref_t->name_off); 10677 if (!btf_struct_ids_match(&env->log, reg_btf, reg_ref_id, reg->off, meta->btf, ref_id, strict_type_match)) { 10678 verbose(env, "kernel function %s args#%d expected pointer to %s %s but R%d has a pointer to %s %s\n", 10679 meta->func_name, argno, btf_type_str(ref_t), ref_tname, argno + 1, 10680 btf_type_str(reg_ref_t), reg_ref_tname); 10681 return -EINVAL; 10682 } 10683 return 0; 10684 } 10685 10686 static int ref_set_non_owning(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 10687 { 10688 struct bpf_verifier_state *state = env->cur_state; 10689 struct btf_record *rec = reg_btf_record(reg); 10690 10691 if (!state->active_lock.ptr) { 10692 verbose(env, "verifier internal error: ref_set_non_owning w/o active lock\n"); 10693 return -EFAULT; 10694 } 10695 10696 if (type_flag(reg->type) & NON_OWN_REF) { 10697 verbose(env, "verifier internal error: NON_OWN_REF already set\n"); 10698 return -EFAULT; 10699 } 10700 10701 reg->type |= NON_OWN_REF; 10702 if (rec->refcount_off >= 0) 10703 reg->type |= MEM_RCU; 10704 10705 return 0; 10706 } 10707 10708 static int ref_convert_owning_non_owning(struct bpf_verifier_env *env, u32 ref_obj_id) 10709 { 10710 struct bpf_func_state *state, *unused; 10711 struct bpf_reg_state *reg; 10712 int i; 10713 10714 state = cur_func(env); 10715 10716 if (!ref_obj_id) { 10717 verbose(env, "verifier internal error: ref_obj_id is zero for " 10718 "owning -> non-owning conversion\n"); 10719 return -EFAULT; 10720 } 10721 10722 for (i = 0; i < state->acquired_refs; i++) { 10723 if (state->refs[i].id != ref_obj_id) 10724 continue; 10725 10726 /* Clear ref_obj_id here so release_reference doesn't clobber 10727 * the whole reg 10728 */ 10729 bpf_for_each_reg_in_vstate(env->cur_state, unused, reg, ({ 10730 if (reg->ref_obj_id == ref_obj_id) { 10731 reg->ref_obj_id = 0; 10732 ref_set_non_owning(env, reg); 10733 } 10734 })); 10735 return 0; 10736 } 10737 10738 verbose(env, "verifier internal error: ref state missing for ref_obj_id\n"); 10739 return -EFAULT; 10740 } 10741 10742 /* Implementation details: 10743 * 10744 * Each register points to some region of memory, which we define as an 10745 * allocation. Each allocation may embed a bpf_spin_lock which protects any 10746 * special BPF objects (bpf_list_head, bpf_rb_root, etc.) part of the same 10747 * allocation. The lock and the data it protects are colocated in the same 10748 * memory region. 10749 * 10750 * Hence, everytime a register holds a pointer value pointing to such 10751 * allocation, the verifier preserves a unique reg->id for it. 10752 * 10753 * The verifier remembers the lock 'ptr' and the lock 'id' whenever 10754 * bpf_spin_lock is called. 10755 * 10756 * To enable this, lock state in the verifier captures two values: 10757 * active_lock.ptr = Register's type specific pointer 10758 * active_lock.id = A unique ID for each register pointer value 10759 * 10760 * Currently, PTR_TO_MAP_VALUE and PTR_TO_BTF_ID | MEM_ALLOC are the two 10761 * supported register types. 10762 * 10763 * The active_lock.ptr in case of map values is the reg->map_ptr, and in case of 10764 * allocated objects is the reg->btf pointer. 10765 * 10766 * The active_lock.id is non-unique for maps supporting direct_value_addr, as we 10767 * can establish the provenance of the map value statically for each distinct 10768 * lookup into such maps. They always contain a single map value hence unique 10769 * IDs for each pseudo load pessimizes the algorithm and rejects valid programs. 10770 * 10771 * So, in case of global variables, they use array maps with max_entries = 1, 10772 * hence their active_lock.ptr becomes map_ptr and id = 0 (since they all point 10773 * into the same map value as max_entries is 1, as described above). 10774 * 10775 * In case of inner map lookups, the inner map pointer has same map_ptr as the 10776 * outer map pointer (in verifier context), but each lookup into an inner map 10777 * assigns a fresh reg->id to the lookup, so while lookups into distinct inner 10778 * maps from the same outer map share the same map_ptr as active_lock.ptr, they 10779 * will get different reg->id assigned to each lookup, hence different 10780 * active_lock.id. 10781 * 10782 * In case of allocated objects, active_lock.ptr is the reg->btf, and the 10783 * reg->id is a unique ID preserved after the NULL pointer check on the pointer 10784 * returned from bpf_obj_new. Each allocation receives a new reg->id. 10785 */ 10786 static int check_reg_allocation_locked(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 10787 { 10788 void *ptr; 10789 u32 id; 10790 10791 switch ((int)reg->type) { 10792 case PTR_TO_MAP_VALUE: 10793 ptr = reg->map_ptr; 10794 break; 10795 case PTR_TO_BTF_ID | MEM_ALLOC: 10796 ptr = reg->btf; 10797 break; 10798 default: 10799 verbose(env, "verifier internal error: unknown reg type for lock check\n"); 10800 return -EFAULT; 10801 } 10802 id = reg->id; 10803 10804 if (!env->cur_state->active_lock.ptr) 10805 return -EINVAL; 10806 if (env->cur_state->active_lock.ptr != ptr || 10807 env->cur_state->active_lock.id != id) { 10808 verbose(env, "held lock and object are not in the same allocation\n"); 10809 return -EINVAL; 10810 } 10811 return 0; 10812 } 10813 10814 static bool is_bpf_list_api_kfunc(u32 btf_id) 10815 { 10816 return btf_id == special_kfunc_list[KF_bpf_list_push_front_impl] || 10817 btf_id == special_kfunc_list[KF_bpf_list_push_back_impl] || 10818 btf_id == special_kfunc_list[KF_bpf_list_pop_front] || 10819 btf_id == special_kfunc_list[KF_bpf_list_pop_back]; 10820 } 10821 10822 static bool is_bpf_rbtree_api_kfunc(u32 btf_id) 10823 { 10824 return btf_id == special_kfunc_list[KF_bpf_rbtree_add_impl] || 10825 btf_id == special_kfunc_list[KF_bpf_rbtree_remove] || 10826 btf_id == special_kfunc_list[KF_bpf_rbtree_first]; 10827 } 10828 10829 static bool is_bpf_graph_api_kfunc(u32 btf_id) 10830 { 10831 return is_bpf_list_api_kfunc(btf_id) || is_bpf_rbtree_api_kfunc(btf_id) || 10832 btf_id == special_kfunc_list[KF_bpf_refcount_acquire_impl]; 10833 } 10834 10835 static bool is_callback_calling_kfunc(u32 btf_id) 10836 { 10837 return btf_id == special_kfunc_list[KF_bpf_rbtree_add_impl]; 10838 } 10839 10840 static bool is_bpf_throw_kfunc(struct bpf_insn *insn) 10841 { 10842 return bpf_pseudo_kfunc_call(insn) && insn->off == 0 && 10843 insn->imm == special_kfunc_list[KF_bpf_throw]; 10844 } 10845 10846 static bool is_rbtree_lock_required_kfunc(u32 btf_id) 10847 { 10848 return is_bpf_rbtree_api_kfunc(btf_id); 10849 } 10850 10851 static bool check_kfunc_is_graph_root_api(struct bpf_verifier_env *env, 10852 enum btf_field_type head_field_type, 10853 u32 kfunc_btf_id) 10854 { 10855 bool ret; 10856 10857 switch (head_field_type) { 10858 case BPF_LIST_HEAD: 10859 ret = is_bpf_list_api_kfunc(kfunc_btf_id); 10860 break; 10861 case BPF_RB_ROOT: 10862 ret = is_bpf_rbtree_api_kfunc(kfunc_btf_id); 10863 break; 10864 default: 10865 verbose(env, "verifier internal error: unexpected graph root argument type %s\n", 10866 btf_field_type_name(head_field_type)); 10867 return false; 10868 } 10869 10870 if (!ret) 10871 verbose(env, "verifier internal error: %s head arg for unknown kfunc\n", 10872 btf_field_type_name(head_field_type)); 10873 return ret; 10874 } 10875 10876 static bool check_kfunc_is_graph_node_api(struct bpf_verifier_env *env, 10877 enum btf_field_type node_field_type, 10878 u32 kfunc_btf_id) 10879 { 10880 bool ret; 10881 10882 switch (node_field_type) { 10883 case BPF_LIST_NODE: 10884 ret = (kfunc_btf_id == special_kfunc_list[KF_bpf_list_push_front_impl] || 10885 kfunc_btf_id == special_kfunc_list[KF_bpf_list_push_back_impl]); 10886 break; 10887 case BPF_RB_NODE: 10888 ret = (kfunc_btf_id == special_kfunc_list[KF_bpf_rbtree_remove] || 10889 kfunc_btf_id == special_kfunc_list[KF_bpf_rbtree_add_impl]); 10890 break; 10891 default: 10892 verbose(env, "verifier internal error: unexpected graph node argument type %s\n", 10893 btf_field_type_name(node_field_type)); 10894 return false; 10895 } 10896 10897 if (!ret) 10898 verbose(env, "verifier internal error: %s node arg for unknown kfunc\n", 10899 btf_field_type_name(node_field_type)); 10900 return ret; 10901 } 10902 10903 static int 10904 __process_kf_arg_ptr_to_graph_root(struct bpf_verifier_env *env, 10905 struct bpf_reg_state *reg, u32 regno, 10906 struct bpf_kfunc_call_arg_meta *meta, 10907 enum btf_field_type head_field_type, 10908 struct btf_field **head_field) 10909 { 10910 const char *head_type_name; 10911 struct btf_field *field; 10912 struct btf_record *rec; 10913 u32 head_off; 10914 10915 if (meta->btf != btf_vmlinux) { 10916 verbose(env, "verifier internal error: unexpected btf mismatch in kfunc call\n"); 10917 return -EFAULT; 10918 } 10919 10920 if (!check_kfunc_is_graph_root_api(env, head_field_type, meta->func_id)) 10921 return -EFAULT; 10922 10923 head_type_name = btf_field_type_name(head_field_type); 10924 if (!tnum_is_const(reg->var_off)) { 10925 verbose(env, 10926 "R%d doesn't have constant offset. %s has to be at the constant offset\n", 10927 regno, head_type_name); 10928 return -EINVAL; 10929 } 10930 10931 rec = reg_btf_record(reg); 10932 head_off = reg->off + reg->var_off.value; 10933 field = btf_record_find(rec, head_off, head_field_type); 10934 if (!field) { 10935 verbose(env, "%s not found at offset=%u\n", head_type_name, head_off); 10936 return -EINVAL; 10937 } 10938 10939 /* All functions require bpf_list_head to be protected using a bpf_spin_lock */ 10940 if (check_reg_allocation_locked(env, reg)) { 10941 verbose(env, "bpf_spin_lock at off=%d must be held for %s\n", 10942 rec->spin_lock_off, head_type_name); 10943 return -EINVAL; 10944 } 10945 10946 if (*head_field) { 10947 verbose(env, "verifier internal error: repeating %s arg\n", head_type_name); 10948 return -EFAULT; 10949 } 10950 *head_field = field; 10951 return 0; 10952 } 10953 10954 static int process_kf_arg_ptr_to_list_head(struct bpf_verifier_env *env, 10955 struct bpf_reg_state *reg, u32 regno, 10956 struct bpf_kfunc_call_arg_meta *meta) 10957 { 10958 return __process_kf_arg_ptr_to_graph_root(env, reg, regno, meta, BPF_LIST_HEAD, 10959 &meta->arg_list_head.field); 10960 } 10961 10962 static int process_kf_arg_ptr_to_rbtree_root(struct bpf_verifier_env *env, 10963 struct bpf_reg_state *reg, u32 regno, 10964 struct bpf_kfunc_call_arg_meta *meta) 10965 { 10966 return __process_kf_arg_ptr_to_graph_root(env, reg, regno, meta, BPF_RB_ROOT, 10967 &meta->arg_rbtree_root.field); 10968 } 10969 10970 static int 10971 __process_kf_arg_ptr_to_graph_node(struct bpf_verifier_env *env, 10972 struct bpf_reg_state *reg, u32 regno, 10973 struct bpf_kfunc_call_arg_meta *meta, 10974 enum btf_field_type head_field_type, 10975 enum btf_field_type node_field_type, 10976 struct btf_field **node_field) 10977 { 10978 const char *node_type_name; 10979 const struct btf_type *et, *t; 10980 struct btf_field *field; 10981 u32 node_off; 10982 10983 if (meta->btf != btf_vmlinux) { 10984 verbose(env, "verifier internal error: unexpected btf mismatch in kfunc call\n"); 10985 return -EFAULT; 10986 } 10987 10988 if (!check_kfunc_is_graph_node_api(env, node_field_type, meta->func_id)) 10989 return -EFAULT; 10990 10991 node_type_name = btf_field_type_name(node_field_type); 10992 if (!tnum_is_const(reg->var_off)) { 10993 verbose(env, 10994 "R%d doesn't have constant offset. %s has to be at the constant offset\n", 10995 regno, node_type_name); 10996 return -EINVAL; 10997 } 10998 10999 node_off = reg->off + reg->var_off.value; 11000 field = reg_find_field_offset(reg, node_off, node_field_type); 11001 if (!field || field->offset != node_off) { 11002 verbose(env, "%s not found at offset=%u\n", node_type_name, node_off); 11003 return -EINVAL; 11004 } 11005 11006 field = *node_field; 11007 11008 et = btf_type_by_id(field->graph_root.btf, field->graph_root.value_btf_id); 11009 t = btf_type_by_id(reg->btf, reg->btf_id); 11010 if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, 0, field->graph_root.btf, 11011 field->graph_root.value_btf_id, true)) { 11012 verbose(env, "operation on %s expects arg#1 %s at offset=%d " 11013 "in struct %s, but arg is at offset=%d in struct %s\n", 11014 btf_field_type_name(head_field_type), 11015 btf_field_type_name(node_field_type), 11016 field->graph_root.node_offset, 11017 btf_name_by_offset(field->graph_root.btf, et->name_off), 11018 node_off, btf_name_by_offset(reg->btf, t->name_off)); 11019 return -EINVAL; 11020 } 11021 meta->arg_btf = reg->btf; 11022 meta->arg_btf_id = reg->btf_id; 11023 11024 if (node_off != field->graph_root.node_offset) { 11025 verbose(env, "arg#1 offset=%d, but expected %s at offset=%d in struct %s\n", 11026 node_off, btf_field_type_name(node_field_type), 11027 field->graph_root.node_offset, 11028 btf_name_by_offset(field->graph_root.btf, et->name_off)); 11029 return -EINVAL; 11030 } 11031 11032 return 0; 11033 } 11034 11035 static int process_kf_arg_ptr_to_list_node(struct bpf_verifier_env *env, 11036 struct bpf_reg_state *reg, u32 regno, 11037 struct bpf_kfunc_call_arg_meta *meta) 11038 { 11039 return __process_kf_arg_ptr_to_graph_node(env, reg, regno, meta, 11040 BPF_LIST_HEAD, BPF_LIST_NODE, 11041 &meta->arg_list_head.field); 11042 } 11043 11044 static int process_kf_arg_ptr_to_rbtree_node(struct bpf_verifier_env *env, 11045 struct bpf_reg_state *reg, u32 regno, 11046 struct bpf_kfunc_call_arg_meta *meta) 11047 { 11048 return __process_kf_arg_ptr_to_graph_node(env, reg, regno, meta, 11049 BPF_RB_ROOT, BPF_RB_NODE, 11050 &meta->arg_rbtree_root.field); 11051 } 11052 11053 static int check_kfunc_args(struct bpf_verifier_env *env, struct bpf_kfunc_call_arg_meta *meta, 11054 int insn_idx) 11055 { 11056 const char *func_name = meta->func_name, *ref_tname; 11057 const struct btf *btf = meta->btf; 11058 const struct btf_param *args; 11059 struct btf_record *rec; 11060 u32 i, nargs; 11061 int ret; 11062 11063 args = (const struct btf_param *)(meta->func_proto + 1); 11064 nargs = btf_type_vlen(meta->func_proto); 11065 if (nargs > MAX_BPF_FUNC_REG_ARGS) { 11066 verbose(env, "Function %s has %d > %d args\n", func_name, nargs, 11067 MAX_BPF_FUNC_REG_ARGS); 11068 return -EINVAL; 11069 } 11070 11071 /* Check that BTF function arguments match actual types that the 11072 * verifier sees. 11073 */ 11074 for (i = 0; i < nargs; i++) { 11075 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[i + 1]; 11076 const struct btf_type *t, *ref_t, *resolve_ret; 11077 enum bpf_arg_type arg_type = ARG_DONTCARE; 11078 u32 regno = i + 1, ref_id, type_size; 11079 bool is_ret_buf_sz = false; 11080 int kf_arg_type; 11081 11082 t = btf_type_skip_modifiers(btf, args[i].type, NULL); 11083 11084 if (is_kfunc_arg_ignore(btf, &args[i])) 11085 continue; 11086 11087 if (btf_type_is_scalar(t)) { 11088 if (reg->type != SCALAR_VALUE) { 11089 verbose(env, "R%d is not a scalar\n", regno); 11090 return -EINVAL; 11091 } 11092 11093 if (is_kfunc_arg_constant(meta->btf, &args[i])) { 11094 if (meta->arg_constant.found) { 11095 verbose(env, "verifier internal error: only one constant argument permitted\n"); 11096 return -EFAULT; 11097 } 11098 if (!tnum_is_const(reg->var_off)) { 11099 verbose(env, "R%d must be a known constant\n", regno); 11100 return -EINVAL; 11101 } 11102 ret = mark_chain_precision(env, regno); 11103 if (ret < 0) 11104 return ret; 11105 meta->arg_constant.found = true; 11106 meta->arg_constant.value = reg->var_off.value; 11107 } else if (is_kfunc_arg_scalar_with_name(btf, &args[i], "rdonly_buf_size")) { 11108 meta->r0_rdonly = true; 11109 is_ret_buf_sz = true; 11110 } else if (is_kfunc_arg_scalar_with_name(btf, &args[i], "rdwr_buf_size")) { 11111 is_ret_buf_sz = true; 11112 } 11113 11114 if (is_ret_buf_sz) { 11115 if (meta->r0_size) { 11116 verbose(env, "2 or more rdonly/rdwr_buf_size parameters for kfunc"); 11117 return -EINVAL; 11118 } 11119 11120 if (!tnum_is_const(reg->var_off)) { 11121 verbose(env, "R%d is not a const\n", regno); 11122 return -EINVAL; 11123 } 11124 11125 meta->r0_size = reg->var_off.value; 11126 ret = mark_chain_precision(env, regno); 11127 if (ret) 11128 return ret; 11129 } 11130 continue; 11131 } 11132 11133 if (!btf_type_is_ptr(t)) { 11134 verbose(env, "Unrecognized arg#%d type %s\n", i, btf_type_str(t)); 11135 return -EINVAL; 11136 } 11137 11138 if ((is_kfunc_trusted_args(meta) || is_kfunc_rcu(meta)) && 11139 (register_is_null(reg) || type_may_be_null(reg->type))) { 11140 verbose(env, "Possibly NULL pointer passed to trusted arg%d\n", i); 11141 return -EACCES; 11142 } 11143 11144 if (reg->ref_obj_id) { 11145 if (is_kfunc_release(meta) && meta->ref_obj_id) { 11146 verbose(env, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n", 11147 regno, reg->ref_obj_id, 11148 meta->ref_obj_id); 11149 return -EFAULT; 11150 } 11151 meta->ref_obj_id = reg->ref_obj_id; 11152 if (is_kfunc_release(meta)) 11153 meta->release_regno = regno; 11154 } 11155 11156 ref_t = btf_type_skip_modifiers(btf, t->type, &ref_id); 11157 ref_tname = btf_name_by_offset(btf, ref_t->name_off); 11158 11159 kf_arg_type = get_kfunc_ptr_arg_type(env, meta, t, ref_t, ref_tname, args, i, nargs); 11160 if (kf_arg_type < 0) 11161 return kf_arg_type; 11162 11163 switch (kf_arg_type) { 11164 case KF_ARG_PTR_TO_ALLOC_BTF_ID: 11165 case KF_ARG_PTR_TO_BTF_ID: 11166 if (!is_kfunc_trusted_args(meta) && !is_kfunc_rcu(meta)) 11167 break; 11168 11169 if (!is_trusted_reg(reg)) { 11170 if (!is_kfunc_rcu(meta)) { 11171 verbose(env, "R%d must be referenced or trusted\n", regno); 11172 return -EINVAL; 11173 } 11174 if (!is_rcu_reg(reg)) { 11175 verbose(env, "R%d must be a rcu pointer\n", regno); 11176 return -EINVAL; 11177 } 11178 } 11179 11180 fallthrough; 11181 case KF_ARG_PTR_TO_CTX: 11182 /* Trusted arguments have the same offset checks as release arguments */ 11183 arg_type |= OBJ_RELEASE; 11184 break; 11185 case KF_ARG_PTR_TO_DYNPTR: 11186 case KF_ARG_PTR_TO_ITER: 11187 case KF_ARG_PTR_TO_LIST_HEAD: 11188 case KF_ARG_PTR_TO_LIST_NODE: 11189 case KF_ARG_PTR_TO_RB_ROOT: 11190 case KF_ARG_PTR_TO_RB_NODE: 11191 case KF_ARG_PTR_TO_MEM: 11192 case KF_ARG_PTR_TO_MEM_SIZE: 11193 case KF_ARG_PTR_TO_CALLBACK: 11194 case KF_ARG_PTR_TO_REFCOUNTED_KPTR: 11195 /* Trusted by default */ 11196 break; 11197 default: 11198 WARN_ON_ONCE(1); 11199 return -EFAULT; 11200 } 11201 11202 if (is_kfunc_release(meta) && reg->ref_obj_id) 11203 arg_type |= OBJ_RELEASE; 11204 ret = check_func_arg_reg_off(env, reg, regno, arg_type); 11205 if (ret < 0) 11206 return ret; 11207 11208 switch (kf_arg_type) { 11209 case KF_ARG_PTR_TO_CTX: 11210 if (reg->type != PTR_TO_CTX) { 11211 verbose(env, "arg#%d expected pointer to ctx, but got %s\n", i, btf_type_str(t)); 11212 return -EINVAL; 11213 } 11214 11215 if (meta->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx]) { 11216 ret = get_kern_ctx_btf_id(&env->log, resolve_prog_type(env->prog)); 11217 if (ret < 0) 11218 return -EINVAL; 11219 meta->ret_btf_id = ret; 11220 } 11221 break; 11222 case KF_ARG_PTR_TO_ALLOC_BTF_ID: 11223 if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC)) { 11224 if (meta->func_id != special_kfunc_list[KF_bpf_obj_drop_impl]) { 11225 verbose(env, "arg#%d expected for bpf_obj_drop_impl()\n", i); 11226 return -EINVAL; 11227 } 11228 } else if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC | MEM_PERCPU)) { 11229 if (meta->func_id != special_kfunc_list[KF_bpf_percpu_obj_drop_impl]) { 11230 verbose(env, "arg#%d expected for bpf_percpu_obj_drop_impl()\n", i); 11231 return -EINVAL; 11232 } 11233 } else { 11234 verbose(env, "arg#%d expected pointer to allocated object\n", i); 11235 return -EINVAL; 11236 } 11237 if (!reg->ref_obj_id) { 11238 verbose(env, "allocated object must be referenced\n"); 11239 return -EINVAL; 11240 } 11241 if (meta->btf == btf_vmlinux) { 11242 meta->arg_btf = reg->btf; 11243 meta->arg_btf_id = reg->btf_id; 11244 } 11245 break; 11246 case KF_ARG_PTR_TO_DYNPTR: 11247 { 11248 enum bpf_arg_type dynptr_arg_type = ARG_PTR_TO_DYNPTR; 11249 int clone_ref_obj_id = 0; 11250 11251 if (reg->type != PTR_TO_STACK && 11252 reg->type != CONST_PTR_TO_DYNPTR) { 11253 verbose(env, "arg#%d expected pointer to stack or dynptr_ptr\n", i); 11254 return -EINVAL; 11255 } 11256 11257 if (reg->type == CONST_PTR_TO_DYNPTR) 11258 dynptr_arg_type |= MEM_RDONLY; 11259 11260 if (is_kfunc_arg_uninit(btf, &args[i])) 11261 dynptr_arg_type |= MEM_UNINIT; 11262 11263 if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_from_skb]) { 11264 dynptr_arg_type |= DYNPTR_TYPE_SKB; 11265 } else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_from_xdp]) { 11266 dynptr_arg_type |= DYNPTR_TYPE_XDP; 11267 } else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_clone] && 11268 (dynptr_arg_type & MEM_UNINIT)) { 11269 enum bpf_dynptr_type parent_type = meta->initialized_dynptr.type; 11270 11271 if (parent_type == BPF_DYNPTR_TYPE_INVALID) { 11272 verbose(env, "verifier internal error: no dynptr type for parent of clone\n"); 11273 return -EFAULT; 11274 } 11275 11276 dynptr_arg_type |= (unsigned int)get_dynptr_type_flag(parent_type); 11277 clone_ref_obj_id = meta->initialized_dynptr.ref_obj_id; 11278 if (dynptr_type_refcounted(parent_type) && !clone_ref_obj_id) { 11279 verbose(env, "verifier internal error: missing ref obj id for parent of clone\n"); 11280 return -EFAULT; 11281 } 11282 } 11283 11284 ret = process_dynptr_func(env, regno, insn_idx, dynptr_arg_type, clone_ref_obj_id); 11285 if (ret < 0) 11286 return ret; 11287 11288 if (!(dynptr_arg_type & MEM_UNINIT)) { 11289 int id = dynptr_id(env, reg); 11290 11291 if (id < 0) { 11292 verbose(env, "verifier internal error: failed to obtain dynptr id\n"); 11293 return id; 11294 } 11295 meta->initialized_dynptr.id = id; 11296 meta->initialized_dynptr.type = dynptr_get_type(env, reg); 11297 meta->initialized_dynptr.ref_obj_id = dynptr_ref_obj_id(env, reg); 11298 } 11299 11300 break; 11301 } 11302 case KF_ARG_PTR_TO_ITER: 11303 ret = process_iter_arg(env, regno, insn_idx, meta); 11304 if (ret < 0) 11305 return ret; 11306 break; 11307 case KF_ARG_PTR_TO_LIST_HEAD: 11308 if (reg->type != PTR_TO_MAP_VALUE && 11309 reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) { 11310 verbose(env, "arg#%d expected pointer to map value or allocated object\n", i); 11311 return -EINVAL; 11312 } 11313 if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC) && !reg->ref_obj_id) { 11314 verbose(env, "allocated object must be referenced\n"); 11315 return -EINVAL; 11316 } 11317 ret = process_kf_arg_ptr_to_list_head(env, reg, regno, meta); 11318 if (ret < 0) 11319 return ret; 11320 break; 11321 case KF_ARG_PTR_TO_RB_ROOT: 11322 if (reg->type != PTR_TO_MAP_VALUE && 11323 reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) { 11324 verbose(env, "arg#%d expected pointer to map value or allocated object\n", i); 11325 return -EINVAL; 11326 } 11327 if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC) && !reg->ref_obj_id) { 11328 verbose(env, "allocated object must be referenced\n"); 11329 return -EINVAL; 11330 } 11331 ret = process_kf_arg_ptr_to_rbtree_root(env, reg, regno, meta); 11332 if (ret < 0) 11333 return ret; 11334 break; 11335 case KF_ARG_PTR_TO_LIST_NODE: 11336 if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) { 11337 verbose(env, "arg#%d expected pointer to allocated object\n", i); 11338 return -EINVAL; 11339 } 11340 if (!reg->ref_obj_id) { 11341 verbose(env, "allocated object must be referenced\n"); 11342 return -EINVAL; 11343 } 11344 ret = process_kf_arg_ptr_to_list_node(env, reg, regno, meta); 11345 if (ret < 0) 11346 return ret; 11347 break; 11348 case KF_ARG_PTR_TO_RB_NODE: 11349 if (meta->func_id == special_kfunc_list[KF_bpf_rbtree_remove]) { 11350 if (!type_is_non_owning_ref(reg->type) || reg->ref_obj_id) { 11351 verbose(env, "rbtree_remove node input must be non-owning ref\n"); 11352 return -EINVAL; 11353 } 11354 if (in_rbtree_lock_required_cb(env)) { 11355 verbose(env, "rbtree_remove not allowed in rbtree cb\n"); 11356 return -EINVAL; 11357 } 11358 } else { 11359 if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) { 11360 verbose(env, "arg#%d expected pointer to allocated object\n", i); 11361 return -EINVAL; 11362 } 11363 if (!reg->ref_obj_id) { 11364 verbose(env, "allocated object must be referenced\n"); 11365 return -EINVAL; 11366 } 11367 } 11368 11369 ret = process_kf_arg_ptr_to_rbtree_node(env, reg, regno, meta); 11370 if (ret < 0) 11371 return ret; 11372 break; 11373 case KF_ARG_PTR_TO_BTF_ID: 11374 /* Only base_type is checked, further checks are done here */ 11375 if ((base_type(reg->type) != PTR_TO_BTF_ID || 11376 (bpf_type_has_unsafe_modifiers(reg->type) && !is_rcu_reg(reg))) && 11377 !reg2btf_ids[base_type(reg->type)]) { 11378 verbose(env, "arg#%d is %s ", i, reg_type_str(env, reg->type)); 11379 verbose(env, "expected %s or socket\n", 11380 reg_type_str(env, base_type(reg->type) | 11381 (type_flag(reg->type) & BPF_REG_TRUSTED_MODIFIERS))); 11382 return -EINVAL; 11383 } 11384 ret = process_kf_arg_ptr_to_btf_id(env, reg, ref_t, ref_tname, ref_id, meta, i); 11385 if (ret < 0) 11386 return ret; 11387 break; 11388 case KF_ARG_PTR_TO_MEM: 11389 resolve_ret = btf_resolve_size(btf, ref_t, &type_size); 11390 if (IS_ERR(resolve_ret)) { 11391 verbose(env, "arg#%d reference type('%s %s') size cannot be determined: %ld\n", 11392 i, btf_type_str(ref_t), ref_tname, PTR_ERR(resolve_ret)); 11393 return -EINVAL; 11394 } 11395 ret = check_mem_reg(env, reg, regno, type_size); 11396 if (ret < 0) 11397 return ret; 11398 break; 11399 case KF_ARG_PTR_TO_MEM_SIZE: 11400 { 11401 struct bpf_reg_state *buff_reg = ®s[regno]; 11402 const struct btf_param *buff_arg = &args[i]; 11403 struct bpf_reg_state *size_reg = ®s[regno + 1]; 11404 const struct btf_param *size_arg = &args[i + 1]; 11405 11406 if (!register_is_null(buff_reg) || !is_kfunc_arg_optional(meta->btf, buff_arg)) { 11407 ret = check_kfunc_mem_size_reg(env, size_reg, regno + 1); 11408 if (ret < 0) { 11409 verbose(env, "arg#%d arg#%d memory, len pair leads to invalid memory access\n", i, i + 1); 11410 return ret; 11411 } 11412 } 11413 11414 if (is_kfunc_arg_const_mem_size(meta->btf, size_arg, size_reg)) { 11415 if (meta->arg_constant.found) { 11416 verbose(env, "verifier internal error: only one constant argument permitted\n"); 11417 return -EFAULT; 11418 } 11419 if (!tnum_is_const(size_reg->var_off)) { 11420 verbose(env, "R%d must be a known constant\n", regno + 1); 11421 return -EINVAL; 11422 } 11423 meta->arg_constant.found = true; 11424 meta->arg_constant.value = size_reg->var_off.value; 11425 } 11426 11427 /* Skip next '__sz' or '__szk' argument */ 11428 i++; 11429 break; 11430 } 11431 case KF_ARG_PTR_TO_CALLBACK: 11432 if (reg->type != PTR_TO_FUNC) { 11433 verbose(env, "arg%d expected pointer to func\n", i); 11434 return -EINVAL; 11435 } 11436 meta->subprogno = reg->subprogno; 11437 break; 11438 case KF_ARG_PTR_TO_REFCOUNTED_KPTR: 11439 if (!type_is_ptr_alloc_obj(reg->type)) { 11440 verbose(env, "arg#%d is neither owning or non-owning ref\n", i); 11441 return -EINVAL; 11442 } 11443 if (!type_is_non_owning_ref(reg->type)) 11444 meta->arg_owning_ref = true; 11445 11446 rec = reg_btf_record(reg); 11447 if (!rec) { 11448 verbose(env, "verifier internal error: Couldn't find btf_record\n"); 11449 return -EFAULT; 11450 } 11451 11452 if (rec->refcount_off < 0) { 11453 verbose(env, "arg#%d doesn't point to a type with bpf_refcount field\n", i); 11454 return -EINVAL; 11455 } 11456 11457 meta->arg_btf = reg->btf; 11458 meta->arg_btf_id = reg->btf_id; 11459 break; 11460 } 11461 } 11462 11463 if (is_kfunc_release(meta) && !meta->release_regno) { 11464 verbose(env, "release kernel function %s expects refcounted PTR_TO_BTF_ID\n", 11465 func_name); 11466 return -EINVAL; 11467 } 11468 11469 return 0; 11470 } 11471 11472 static int fetch_kfunc_meta(struct bpf_verifier_env *env, 11473 struct bpf_insn *insn, 11474 struct bpf_kfunc_call_arg_meta *meta, 11475 const char **kfunc_name) 11476 { 11477 const struct btf_type *func, *func_proto; 11478 u32 func_id, *kfunc_flags; 11479 const char *func_name; 11480 struct btf *desc_btf; 11481 11482 if (kfunc_name) 11483 *kfunc_name = NULL; 11484 11485 if (!insn->imm) 11486 return -EINVAL; 11487 11488 desc_btf = find_kfunc_desc_btf(env, insn->off); 11489 if (IS_ERR(desc_btf)) 11490 return PTR_ERR(desc_btf); 11491 11492 func_id = insn->imm; 11493 func = btf_type_by_id(desc_btf, func_id); 11494 func_name = btf_name_by_offset(desc_btf, func->name_off); 11495 if (kfunc_name) 11496 *kfunc_name = func_name; 11497 func_proto = btf_type_by_id(desc_btf, func->type); 11498 11499 kfunc_flags = btf_kfunc_id_set_contains(desc_btf, func_id, env->prog); 11500 if (!kfunc_flags) { 11501 return -EACCES; 11502 } 11503 11504 memset(meta, 0, sizeof(*meta)); 11505 meta->btf = desc_btf; 11506 meta->func_id = func_id; 11507 meta->kfunc_flags = *kfunc_flags; 11508 meta->func_proto = func_proto; 11509 meta->func_name = func_name; 11510 11511 return 0; 11512 } 11513 11514 static int check_return_code(struct bpf_verifier_env *env, int regno); 11515 11516 static int check_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn, 11517 int *insn_idx_p) 11518 { 11519 const struct btf_type *t, *ptr_type; 11520 u32 i, nargs, ptr_type_id, release_ref_obj_id; 11521 struct bpf_reg_state *regs = cur_regs(env); 11522 const char *func_name, *ptr_type_name; 11523 bool sleepable, rcu_lock, rcu_unlock; 11524 struct bpf_kfunc_call_arg_meta meta; 11525 struct bpf_insn_aux_data *insn_aux; 11526 int err, insn_idx = *insn_idx_p; 11527 const struct btf_param *args; 11528 const struct btf_type *ret_t; 11529 struct btf *desc_btf; 11530 11531 /* skip for now, but return error when we find this in fixup_kfunc_call */ 11532 if (!insn->imm) 11533 return 0; 11534 11535 err = fetch_kfunc_meta(env, insn, &meta, &func_name); 11536 if (err == -EACCES && func_name) 11537 verbose(env, "calling kernel function %s is not allowed\n", func_name); 11538 if (err) 11539 return err; 11540 desc_btf = meta.btf; 11541 insn_aux = &env->insn_aux_data[insn_idx]; 11542 11543 insn_aux->is_iter_next = is_iter_next_kfunc(&meta); 11544 11545 if (is_kfunc_destructive(&meta) && !capable(CAP_SYS_BOOT)) { 11546 verbose(env, "destructive kfunc calls require CAP_SYS_BOOT capability\n"); 11547 return -EACCES; 11548 } 11549 11550 sleepable = is_kfunc_sleepable(&meta); 11551 if (sleepable && !env->prog->aux->sleepable) { 11552 verbose(env, "program must be sleepable to call sleepable kfunc %s\n", func_name); 11553 return -EACCES; 11554 } 11555 11556 rcu_lock = is_kfunc_bpf_rcu_read_lock(&meta); 11557 rcu_unlock = is_kfunc_bpf_rcu_read_unlock(&meta); 11558 11559 if (env->cur_state->active_rcu_lock) { 11560 struct bpf_func_state *state; 11561 struct bpf_reg_state *reg; 11562 11563 if (in_rbtree_lock_required_cb(env) && (rcu_lock || rcu_unlock)) { 11564 verbose(env, "Calling bpf_rcu_read_{lock,unlock} in unnecessary rbtree callback\n"); 11565 return -EACCES; 11566 } 11567 11568 if (rcu_lock) { 11569 verbose(env, "nested rcu read lock (kernel function %s)\n", func_name); 11570 return -EINVAL; 11571 } else if (rcu_unlock) { 11572 bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({ 11573 if (reg->type & MEM_RCU) { 11574 reg->type &= ~(MEM_RCU | PTR_MAYBE_NULL); 11575 reg->type |= PTR_UNTRUSTED; 11576 } 11577 })); 11578 env->cur_state->active_rcu_lock = false; 11579 } else if (sleepable) { 11580 verbose(env, "kernel func %s is sleepable within rcu_read_lock region\n", func_name); 11581 return -EACCES; 11582 } 11583 } else if (rcu_lock) { 11584 env->cur_state->active_rcu_lock = true; 11585 } else if (rcu_unlock) { 11586 verbose(env, "unmatched rcu read unlock (kernel function %s)\n", func_name); 11587 return -EINVAL; 11588 } 11589 11590 /* Check the arguments */ 11591 err = check_kfunc_args(env, &meta, insn_idx); 11592 if (err < 0) 11593 return err; 11594 /* In case of release function, we get register number of refcounted 11595 * PTR_TO_BTF_ID in bpf_kfunc_arg_meta, do the release now. 11596 */ 11597 if (meta.release_regno) { 11598 err = release_reference(env, regs[meta.release_regno].ref_obj_id); 11599 if (err) { 11600 verbose(env, "kfunc %s#%d reference has not been acquired before\n", 11601 func_name, meta.func_id); 11602 return err; 11603 } 11604 } 11605 11606 if (meta.func_id == special_kfunc_list[KF_bpf_list_push_front_impl] || 11607 meta.func_id == special_kfunc_list[KF_bpf_list_push_back_impl] || 11608 meta.func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) { 11609 release_ref_obj_id = regs[BPF_REG_2].ref_obj_id; 11610 insn_aux->insert_off = regs[BPF_REG_2].off; 11611 insn_aux->kptr_struct_meta = btf_find_struct_meta(meta.arg_btf, meta.arg_btf_id); 11612 err = ref_convert_owning_non_owning(env, release_ref_obj_id); 11613 if (err) { 11614 verbose(env, "kfunc %s#%d conversion of owning ref to non-owning failed\n", 11615 func_name, meta.func_id); 11616 return err; 11617 } 11618 11619 err = release_reference(env, release_ref_obj_id); 11620 if (err) { 11621 verbose(env, "kfunc %s#%d reference has not been acquired before\n", 11622 func_name, meta.func_id); 11623 return err; 11624 } 11625 } 11626 11627 if (meta.func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) { 11628 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno, 11629 set_rbtree_add_callback_state); 11630 if (err) { 11631 verbose(env, "kfunc %s#%d failed callback verification\n", 11632 func_name, meta.func_id); 11633 return err; 11634 } 11635 } 11636 11637 if (meta.func_id == special_kfunc_list[KF_bpf_throw]) { 11638 if (!bpf_jit_supports_exceptions()) { 11639 verbose(env, "JIT does not support calling kfunc %s#%d\n", 11640 func_name, meta.func_id); 11641 return -ENOTSUPP; 11642 } 11643 env->seen_exception = true; 11644 11645 /* In the case of the default callback, the cookie value passed 11646 * to bpf_throw becomes the return value of the program. 11647 */ 11648 if (!env->exception_callback_subprog) { 11649 err = check_return_code(env, BPF_REG_1); 11650 if (err < 0) 11651 return err; 11652 } 11653 } 11654 11655 for (i = 0; i < CALLER_SAVED_REGS; i++) 11656 mark_reg_not_init(env, regs, caller_saved[i]); 11657 11658 /* Check return type */ 11659 t = btf_type_skip_modifiers(desc_btf, meta.func_proto->type, NULL); 11660 11661 if (is_kfunc_acquire(&meta) && !btf_type_is_struct_ptr(meta.btf, t)) { 11662 /* Only exception is bpf_obj_new_impl */ 11663 if (meta.btf != btf_vmlinux || 11664 (meta.func_id != special_kfunc_list[KF_bpf_obj_new_impl] && 11665 meta.func_id != special_kfunc_list[KF_bpf_percpu_obj_new_impl] && 11666 meta.func_id != special_kfunc_list[KF_bpf_refcount_acquire_impl])) { 11667 verbose(env, "acquire kernel function does not return PTR_TO_BTF_ID\n"); 11668 return -EINVAL; 11669 } 11670 } 11671 11672 if (btf_type_is_scalar(t)) { 11673 mark_reg_unknown(env, regs, BPF_REG_0); 11674 mark_btf_func_reg_size(env, BPF_REG_0, t->size); 11675 } else if (btf_type_is_ptr(t)) { 11676 ptr_type = btf_type_skip_modifiers(desc_btf, t->type, &ptr_type_id); 11677 11678 if (meta.btf == btf_vmlinux && btf_id_set_contains(&special_kfunc_set, meta.func_id)) { 11679 if (meta.func_id == special_kfunc_list[KF_bpf_obj_new_impl] || 11680 meta.func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl]) { 11681 struct btf_struct_meta *struct_meta; 11682 struct btf *ret_btf; 11683 u32 ret_btf_id; 11684 11685 if (meta.func_id == special_kfunc_list[KF_bpf_obj_new_impl] && !bpf_global_ma_set) 11686 return -ENOMEM; 11687 11688 if (meta.func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl] && !bpf_global_percpu_ma_set) 11689 return -ENOMEM; 11690 11691 if (((u64)(u32)meta.arg_constant.value) != meta.arg_constant.value) { 11692 verbose(env, "local type ID argument must be in range [0, U32_MAX]\n"); 11693 return -EINVAL; 11694 } 11695 11696 ret_btf = env->prog->aux->btf; 11697 ret_btf_id = meta.arg_constant.value; 11698 11699 /* This may be NULL due to user not supplying a BTF */ 11700 if (!ret_btf) { 11701 verbose(env, "bpf_obj_new/bpf_percpu_obj_new requires prog BTF\n"); 11702 return -EINVAL; 11703 } 11704 11705 ret_t = btf_type_by_id(ret_btf, ret_btf_id); 11706 if (!ret_t || !__btf_type_is_struct(ret_t)) { 11707 verbose(env, "bpf_obj_new/bpf_percpu_obj_new type ID argument must be of a struct\n"); 11708 return -EINVAL; 11709 } 11710 11711 struct_meta = btf_find_struct_meta(ret_btf, ret_btf_id); 11712 if (meta.func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl]) { 11713 if (!__btf_type_is_scalar_struct(env, ret_btf, ret_t, 0)) { 11714 verbose(env, "bpf_percpu_obj_new type ID argument must be of a struct of scalars\n"); 11715 return -EINVAL; 11716 } 11717 11718 if (struct_meta) { 11719 verbose(env, "bpf_percpu_obj_new type ID argument must not contain special fields\n"); 11720 return -EINVAL; 11721 } 11722 } 11723 11724 mark_reg_known_zero(env, regs, BPF_REG_0); 11725 regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC; 11726 regs[BPF_REG_0].btf = ret_btf; 11727 regs[BPF_REG_0].btf_id = ret_btf_id; 11728 if (meta.func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl]) 11729 regs[BPF_REG_0].type |= MEM_PERCPU; 11730 11731 insn_aux->obj_new_size = ret_t->size; 11732 insn_aux->kptr_struct_meta = struct_meta; 11733 } else if (meta.func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl]) { 11734 mark_reg_known_zero(env, regs, BPF_REG_0); 11735 regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC; 11736 regs[BPF_REG_0].btf = meta.arg_btf; 11737 regs[BPF_REG_0].btf_id = meta.arg_btf_id; 11738 11739 insn_aux->kptr_struct_meta = 11740 btf_find_struct_meta(meta.arg_btf, 11741 meta.arg_btf_id); 11742 } else if (meta.func_id == special_kfunc_list[KF_bpf_list_pop_front] || 11743 meta.func_id == special_kfunc_list[KF_bpf_list_pop_back]) { 11744 struct btf_field *field = meta.arg_list_head.field; 11745 11746 mark_reg_graph_node(regs, BPF_REG_0, &field->graph_root); 11747 } else if (meta.func_id == special_kfunc_list[KF_bpf_rbtree_remove] || 11748 meta.func_id == special_kfunc_list[KF_bpf_rbtree_first]) { 11749 struct btf_field *field = meta.arg_rbtree_root.field; 11750 11751 mark_reg_graph_node(regs, BPF_REG_0, &field->graph_root); 11752 } else if (meta.func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx]) { 11753 mark_reg_known_zero(env, regs, BPF_REG_0); 11754 regs[BPF_REG_0].type = PTR_TO_BTF_ID | PTR_TRUSTED; 11755 regs[BPF_REG_0].btf = desc_btf; 11756 regs[BPF_REG_0].btf_id = meta.ret_btf_id; 11757 } else if (meta.func_id == special_kfunc_list[KF_bpf_rdonly_cast]) { 11758 ret_t = btf_type_by_id(desc_btf, meta.arg_constant.value); 11759 if (!ret_t || !btf_type_is_struct(ret_t)) { 11760 verbose(env, 11761 "kfunc bpf_rdonly_cast type ID argument must be of a struct\n"); 11762 return -EINVAL; 11763 } 11764 11765 mark_reg_known_zero(env, regs, BPF_REG_0); 11766 regs[BPF_REG_0].type = PTR_TO_BTF_ID | PTR_UNTRUSTED; 11767 regs[BPF_REG_0].btf = desc_btf; 11768 regs[BPF_REG_0].btf_id = meta.arg_constant.value; 11769 } else if (meta.func_id == special_kfunc_list[KF_bpf_dynptr_slice] || 11770 meta.func_id == special_kfunc_list[KF_bpf_dynptr_slice_rdwr]) { 11771 enum bpf_type_flag type_flag = get_dynptr_type_flag(meta.initialized_dynptr.type); 11772 11773 mark_reg_known_zero(env, regs, BPF_REG_0); 11774 11775 if (!meta.arg_constant.found) { 11776 verbose(env, "verifier internal error: bpf_dynptr_slice(_rdwr) no constant size\n"); 11777 return -EFAULT; 11778 } 11779 11780 regs[BPF_REG_0].mem_size = meta.arg_constant.value; 11781 11782 /* PTR_MAYBE_NULL will be added when is_kfunc_ret_null is checked */ 11783 regs[BPF_REG_0].type = PTR_TO_MEM | type_flag; 11784 11785 if (meta.func_id == special_kfunc_list[KF_bpf_dynptr_slice]) { 11786 regs[BPF_REG_0].type |= MEM_RDONLY; 11787 } else { 11788 /* this will set env->seen_direct_write to true */ 11789 if (!may_access_direct_pkt_data(env, NULL, BPF_WRITE)) { 11790 verbose(env, "the prog does not allow writes to packet data\n"); 11791 return -EINVAL; 11792 } 11793 } 11794 11795 if (!meta.initialized_dynptr.id) { 11796 verbose(env, "verifier internal error: no dynptr id\n"); 11797 return -EFAULT; 11798 } 11799 regs[BPF_REG_0].dynptr_id = meta.initialized_dynptr.id; 11800 11801 /* we don't need to set BPF_REG_0's ref obj id 11802 * because packet slices are not refcounted (see 11803 * dynptr_type_refcounted) 11804 */ 11805 } else { 11806 verbose(env, "kernel function %s unhandled dynamic return type\n", 11807 meta.func_name); 11808 return -EFAULT; 11809 } 11810 } else if (!__btf_type_is_struct(ptr_type)) { 11811 if (!meta.r0_size) { 11812 __u32 sz; 11813 11814 if (!IS_ERR(btf_resolve_size(desc_btf, ptr_type, &sz))) { 11815 meta.r0_size = sz; 11816 meta.r0_rdonly = true; 11817 } 11818 } 11819 if (!meta.r0_size) { 11820 ptr_type_name = btf_name_by_offset(desc_btf, 11821 ptr_type->name_off); 11822 verbose(env, 11823 "kernel function %s returns pointer type %s %s is not supported\n", 11824 func_name, 11825 btf_type_str(ptr_type), 11826 ptr_type_name); 11827 return -EINVAL; 11828 } 11829 11830 mark_reg_known_zero(env, regs, BPF_REG_0); 11831 regs[BPF_REG_0].type = PTR_TO_MEM; 11832 regs[BPF_REG_0].mem_size = meta.r0_size; 11833 11834 if (meta.r0_rdonly) 11835 regs[BPF_REG_0].type |= MEM_RDONLY; 11836 11837 /* Ensures we don't access the memory after a release_reference() */ 11838 if (meta.ref_obj_id) 11839 regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id; 11840 } else { 11841 mark_reg_known_zero(env, regs, BPF_REG_0); 11842 regs[BPF_REG_0].btf = desc_btf; 11843 regs[BPF_REG_0].type = PTR_TO_BTF_ID; 11844 regs[BPF_REG_0].btf_id = ptr_type_id; 11845 } 11846 11847 if (is_kfunc_ret_null(&meta)) { 11848 regs[BPF_REG_0].type |= PTR_MAYBE_NULL; 11849 /* For mark_ptr_or_null_reg, see 93c230e3f5bd6 */ 11850 regs[BPF_REG_0].id = ++env->id_gen; 11851 } 11852 mark_btf_func_reg_size(env, BPF_REG_0, sizeof(void *)); 11853 if (is_kfunc_acquire(&meta)) { 11854 int id = acquire_reference_state(env, insn_idx); 11855 11856 if (id < 0) 11857 return id; 11858 if (is_kfunc_ret_null(&meta)) 11859 regs[BPF_REG_0].id = id; 11860 regs[BPF_REG_0].ref_obj_id = id; 11861 } else if (meta.func_id == special_kfunc_list[KF_bpf_rbtree_first]) { 11862 ref_set_non_owning(env, ®s[BPF_REG_0]); 11863 } 11864 11865 if (reg_may_point_to_spin_lock(®s[BPF_REG_0]) && !regs[BPF_REG_0].id) 11866 regs[BPF_REG_0].id = ++env->id_gen; 11867 } else if (btf_type_is_void(t)) { 11868 if (meta.btf == btf_vmlinux && btf_id_set_contains(&special_kfunc_set, meta.func_id)) { 11869 if (meta.func_id == special_kfunc_list[KF_bpf_obj_drop_impl] || 11870 meta.func_id == special_kfunc_list[KF_bpf_percpu_obj_drop_impl]) { 11871 insn_aux->kptr_struct_meta = 11872 btf_find_struct_meta(meta.arg_btf, 11873 meta.arg_btf_id); 11874 } 11875 } 11876 } 11877 11878 nargs = btf_type_vlen(meta.func_proto); 11879 args = (const struct btf_param *)(meta.func_proto + 1); 11880 for (i = 0; i < nargs; i++) { 11881 u32 regno = i + 1; 11882 11883 t = btf_type_skip_modifiers(desc_btf, args[i].type, NULL); 11884 if (btf_type_is_ptr(t)) 11885 mark_btf_func_reg_size(env, regno, sizeof(void *)); 11886 else 11887 /* scalar. ensured by btf_check_kfunc_arg_match() */ 11888 mark_btf_func_reg_size(env, regno, t->size); 11889 } 11890 11891 if (is_iter_next_kfunc(&meta)) { 11892 err = process_iter_next_call(env, insn_idx, &meta); 11893 if (err) 11894 return err; 11895 } 11896 11897 return 0; 11898 } 11899 11900 static bool signed_add_overflows(s64 a, s64 b) 11901 { 11902 /* Do the add in u64, where overflow is well-defined */ 11903 s64 res = (s64)((u64)a + (u64)b); 11904 11905 if (b < 0) 11906 return res > a; 11907 return res < a; 11908 } 11909 11910 static bool signed_add32_overflows(s32 a, s32 b) 11911 { 11912 /* Do the add in u32, where overflow is well-defined */ 11913 s32 res = (s32)((u32)a + (u32)b); 11914 11915 if (b < 0) 11916 return res > a; 11917 return res < a; 11918 } 11919 11920 static bool signed_sub_overflows(s64 a, s64 b) 11921 { 11922 /* Do the sub in u64, where overflow is well-defined */ 11923 s64 res = (s64)((u64)a - (u64)b); 11924 11925 if (b < 0) 11926 return res < a; 11927 return res > a; 11928 } 11929 11930 static bool signed_sub32_overflows(s32 a, s32 b) 11931 { 11932 /* Do the sub in u32, where overflow is well-defined */ 11933 s32 res = (s32)((u32)a - (u32)b); 11934 11935 if (b < 0) 11936 return res < a; 11937 return res > a; 11938 } 11939 11940 static bool check_reg_sane_offset(struct bpf_verifier_env *env, 11941 const struct bpf_reg_state *reg, 11942 enum bpf_reg_type type) 11943 { 11944 bool known = tnum_is_const(reg->var_off); 11945 s64 val = reg->var_off.value; 11946 s64 smin = reg->smin_value; 11947 11948 if (known && (val >= BPF_MAX_VAR_OFF || val <= -BPF_MAX_VAR_OFF)) { 11949 verbose(env, "math between %s pointer and %lld is not allowed\n", 11950 reg_type_str(env, type), val); 11951 return false; 11952 } 11953 11954 if (reg->off >= BPF_MAX_VAR_OFF || reg->off <= -BPF_MAX_VAR_OFF) { 11955 verbose(env, "%s pointer offset %d is not allowed\n", 11956 reg_type_str(env, type), reg->off); 11957 return false; 11958 } 11959 11960 if (smin == S64_MIN) { 11961 verbose(env, "math between %s pointer and register with unbounded min value is not allowed\n", 11962 reg_type_str(env, type)); 11963 return false; 11964 } 11965 11966 if (smin >= BPF_MAX_VAR_OFF || smin <= -BPF_MAX_VAR_OFF) { 11967 verbose(env, "value %lld makes %s pointer be out of bounds\n", 11968 smin, reg_type_str(env, type)); 11969 return false; 11970 } 11971 11972 return true; 11973 } 11974 11975 enum { 11976 REASON_BOUNDS = -1, 11977 REASON_TYPE = -2, 11978 REASON_PATHS = -3, 11979 REASON_LIMIT = -4, 11980 REASON_STACK = -5, 11981 }; 11982 11983 static int retrieve_ptr_limit(const struct bpf_reg_state *ptr_reg, 11984 u32 *alu_limit, bool mask_to_left) 11985 { 11986 u32 max = 0, ptr_limit = 0; 11987 11988 switch (ptr_reg->type) { 11989 case PTR_TO_STACK: 11990 /* Offset 0 is out-of-bounds, but acceptable start for the 11991 * left direction, see BPF_REG_FP. Also, unknown scalar 11992 * offset where we would need to deal with min/max bounds is 11993 * currently prohibited for unprivileged. 11994 */ 11995 max = MAX_BPF_STACK + mask_to_left; 11996 ptr_limit = -(ptr_reg->var_off.value + ptr_reg->off); 11997 break; 11998 case PTR_TO_MAP_VALUE: 11999 max = ptr_reg->map_ptr->value_size; 12000 ptr_limit = (mask_to_left ? 12001 ptr_reg->smin_value : 12002 ptr_reg->umax_value) + ptr_reg->off; 12003 break; 12004 default: 12005 return REASON_TYPE; 12006 } 12007 12008 if (ptr_limit >= max) 12009 return REASON_LIMIT; 12010 *alu_limit = ptr_limit; 12011 return 0; 12012 } 12013 12014 static bool can_skip_alu_sanitation(const struct bpf_verifier_env *env, 12015 const struct bpf_insn *insn) 12016 { 12017 return env->bypass_spec_v1 || BPF_SRC(insn->code) == BPF_K; 12018 } 12019 12020 static int update_alu_sanitation_state(struct bpf_insn_aux_data *aux, 12021 u32 alu_state, u32 alu_limit) 12022 { 12023 /* If we arrived here from different branches with different 12024 * state or limits to sanitize, then this won't work. 12025 */ 12026 if (aux->alu_state && 12027 (aux->alu_state != alu_state || 12028 aux->alu_limit != alu_limit)) 12029 return REASON_PATHS; 12030 12031 /* Corresponding fixup done in do_misc_fixups(). */ 12032 aux->alu_state = alu_state; 12033 aux->alu_limit = alu_limit; 12034 return 0; 12035 } 12036 12037 static int sanitize_val_alu(struct bpf_verifier_env *env, 12038 struct bpf_insn *insn) 12039 { 12040 struct bpf_insn_aux_data *aux = cur_aux(env); 12041 12042 if (can_skip_alu_sanitation(env, insn)) 12043 return 0; 12044 12045 return update_alu_sanitation_state(aux, BPF_ALU_NON_POINTER, 0); 12046 } 12047 12048 static bool sanitize_needed(u8 opcode) 12049 { 12050 return opcode == BPF_ADD || opcode == BPF_SUB; 12051 } 12052 12053 struct bpf_sanitize_info { 12054 struct bpf_insn_aux_data aux; 12055 bool mask_to_left; 12056 }; 12057 12058 static struct bpf_verifier_state * 12059 sanitize_speculative_path(struct bpf_verifier_env *env, 12060 const struct bpf_insn *insn, 12061 u32 next_idx, u32 curr_idx) 12062 { 12063 struct bpf_verifier_state *branch; 12064 struct bpf_reg_state *regs; 12065 12066 branch = push_stack(env, next_idx, curr_idx, true); 12067 if (branch && insn) { 12068 regs = branch->frame[branch->curframe]->regs; 12069 if (BPF_SRC(insn->code) == BPF_K) { 12070 mark_reg_unknown(env, regs, insn->dst_reg); 12071 } else if (BPF_SRC(insn->code) == BPF_X) { 12072 mark_reg_unknown(env, regs, insn->dst_reg); 12073 mark_reg_unknown(env, regs, insn->src_reg); 12074 } 12075 } 12076 return branch; 12077 } 12078 12079 static int sanitize_ptr_alu(struct bpf_verifier_env *env, 12080 struct bpf_insn *insn, 12081 const struct bpf_reg_state *ptr_reg, 12082 const struct bpf_reg_state *off_reg, 12083 struct bpf_reg_state *dst_reg, 12084 struct bpf_sanitize_info *info, 12085 const bool commit_window) 12086 { 12087 struct bpf_insn_aux_data *aux = commit_window ? cur_aux(env) : &info->aux; 12088 struct bpf_verifier_state *vstate = env->cur_state; 12089 bool off_is_imm = tnum_is_const(off_reg->var_off); 12090 bool off_is_neg = off_reg->smin_value < 0; 12091 bool ptr_is_dst_reg = ptr_reg == dst_reg; 12092 u8 opcode = BPF_OP(insn->code); 12093 u32 alu_state, alu_limit; 12094 struct bpf_reg_state tmp; 12095 bool ret; 12096 int err; 12097 12098 if (can_skip_alu_sanitation(env, insn)) 12099 return 0; 12100 12101 /* We already marked aux for masking from non-speculative 12102 * paths, thus we got here in the first place. We only care 12103 * to explore bad access from here. 12104 */ 12105 if (vstate->speculative) 12106 goto do_sim; 12107 12108 if (!commit_window) { 12109 if (!tnum_is_const(off_reg->var_off) && 12110 (off_reg->smin_value < 0) != (off_reg->smax_value < 0)) 12111 return REASON_BOUNDS; 12112 12113 info->mask_to_left = (opcode == BPF_ADD && off_is_neg) || 12114 (opcode == BPF_SUB && !off_is_neg); 12115 } 12116 12117 err = retrieve_ptr_limit(ptr_reg, &alu_limit, info->mask_to_left); 12118 if (err < 0) 12119 return err; 12120 12121 if (commit_window) { 12122 /* In commit phase we narrow the masking window based on 12123 * the observed pointer move after the simulated operation. 12124 */ 12125 alu_state = info->aux.alu_state; 12126 alu_limit = abs(info->aux.alu_limit - alu_limit); 12127 } else { 12128 alu_state = off_is_neg ? BPF_ALU_NEG_VALUE : 0; 12129 alu_state |= off_is_imm ? BPF_ALU_IMMEDIATE : 0; 12130 alu_state |= ptr_is_dst_reg ? 12131 BPF_ALU_SANITIZE_SRC : BPF_ALU_SANITIZE_DST; 12132 12133 /* Limit pruning on unknown scalars to enable deep search for 12134 * potential masking differences from other program paths. 12135 */ 12136 if (!off_is_imm) 12137 env->explore_alu_limits = true; 12138 } 12139 12140 err = update_alu_sanitation_state(aux, alu_state, alu_limit); 12141 if (err < 0) 12142 return err; 12143 do_sim: 12144 /* If we're in commit phase, we're done here given we already 12145 * pushed the truncated dst_reg into the speculative verification 12146 * stack. 12147 * 12148 * Also, when register is a known constant, we rewrite register-based 12149 * operation to immediate-based, and thus do not need masking (and as 12150 * a consequence, do not need to simulate the zero-truncation either). 12151 */ 12152 if (commit_window || off_is_imm) 12153 return 0; 12154 12155 /* Simulate and find potential out-of-bounds access under 12156 * speculative execution from truncation as a result of 12157 * masking when off was not within expected range. If off 12158 * sits in dst, then we temporarily need to move ptr there 12159 * to simulate dst (== 0) +/-= ptr. Needed, for example, 12160 * for cases where we use K-based arithmetic in one direction 12161 * and truncated reg-based in the other in order to explore 12162 * bad access. 12163 */ 12164 if (!ptr_is_dst_reg) { 12165 tmp = *dst_reg; 12166 copy_register_state(dst_reg, ptr_reg); 12167 } 12168 ret = sanitize_speculative_path(env, NULL, env->insn_idx + 1, 12169 env->insn_idx); 12170 if (!ptr_is_dst_reg && ret) 12171 *dst_reg = tmp; 12172 return !ret ? REASON_STACK : 0; 12173 } 12174 12175 static void sanitize_mark_insn_seen(struct bpf_verifier_env *env) 12176 { 12177 struct bpf_verifier_state *vstate = env->cur_state; 12178 12179 /* If we simulate paths under speculation, we don't update the 12180 * insn as 'seen' such that when we verify unreachable paths in 12181 * the non-speculative domain, sanitize_dead_code() can still 12182 * rewrite/sanitize them. 12183 */ 12184 if (!vstate->speculative) 12185 env->insn_aux_data[env->insn_idx].seen = env->pass_cnt; 12186 } 12187 12188 static int sanitize_err(struct bpf_verifier_env *env, 12189 const struct bpf_insn *insn, int reason, 12190 const struct bpf_reg_state *off_reg, 12191 const struct bpf_reg_state *dst_reg) 12192 { 12193 static const char *err = "pointer arithmetic with it prohibited for !root"; 12194 const char *op = BPF_OP(insn->code) == BPF_ADD ? "add" : "sub"; 12195 u32 dst = insn->dst_reg, src = insn->src_reg; 12196 12197 switch (reason) { 12198 case REASON_BOUNDS: 12199 verbose(env, "R%d has unknown scalar with mixed signed bounds, %s\n", 12200 off_reg == dst_reg ? dst : src, err); 12201 break; 12202 case REASON_TYPE: 12203 verbose(env, "R%d has pointer with unsupported alu operation, %s\n", 12204 off_reg == dst_reg ? src : dst, err); 12205 break; 12206 case REASON_PATHS: 12207 verbose(env, "R%d tried to %s from different maps, paths or scalars, %s\n", 12208 dst, op, err); 12209 break; 12210 case REASON_LIMIT: 12211 verbose(env, "R%d tried to %s beyond pointer bounds, %s\n", 12212 dst, op, err); 12213 break; 12214 case REASON_STACK: 12215 verbose(env, "R%d could not be pushed for speculative verification, %s\n", 12216 dst, err); 12217 break; 12218 default: 12219 verbose(env, "verifier internal error: unknown reason (%d)\n", 12220 reason); 12221 break; 12222 } 12223 12224 return -EACCES; 12225 } 12226 12227 /* check that stack access falls within stack limits and that 'reg' doesn't 12228 * have a variable offset. 12229 * 12230 * Variable offset is prohibited for unprivileged mode for simplicity since it 12231 * requires corresponding support in Spectre masking for stack ALU. See also 12232 * retrieve_ptr_limit(). 12233 * 12234 * 12235 * 'off' includes 'reg->off'. 12236 */ 12237 static int check_stack_access_for_ptr_arithmetic( 12238 struct bpf_verifier_env *env, 12239 int regno, 12240 const struct bpf_reg_state *reg, 12241 int off) 12242 { 12243 if (!tnum_is_const(reg->var_off)) { 12244 char tn_buf[48]; 12245 12246 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 12247 verbose(env, "R%d variable stack access prohibited for !root, var_off=%s off=%d\n", 12248 regno, tn_buf, off); 12249 return -EACCES; 12250 } 12251 12252 if (off >= 0 || off < -MAX_BPF_STACK) { 12253 verbose(env, "R%d stack pointer arithmetic goes out of range, " 12254 "prohibited for !root; off=%d\n", regno, off); 12255 return -EACCES; 12256 } 12257 12258 return 0; 12259 } 12260 12261 static int sanitize_check_bounds(struct bpf_verifier_env *env, 12262 const struct bpf_insn *insn, 12263 const struct bpf_reg_state *dst_reg) 12264 { 12265 u32 dst = insn->dst_reg; 12266 12267 /* For unprivileged we require that resulting offset must be in bounds 12268 * in order to be able to sanitize access later on. 12269 */ 12270 if (env->bypass_spec_v1) 12271 return 0; 12272 12273 switch (dst_reg->type) { 12274 case PTR_TO_STACK: 12275 if (check_stack_access_for_ptr_arithmetic(env, dst, dst_reg, 12276 dst_reg->off + dst_reg->var_off.value)) 12277 return -EACCES; 12278 break; 12279 case PTR_TO_MAP_VALUE: 12280 if (check_map_access(env, dst, dst_reg->off, 1, false, ACCESS_HELPER)) { 12281 verbose(env, "R%d pointer arithmetic of map value goes out of range, " 12282 "prohibited for !root\n", dst); 12283 return -EACCES; 12284 } 12285 break; 12286 default: 12287 break; 12288 } 12289 12290 return 0; 12291 } 12292 12293 /* Handles arithmetic on a pointer and a scalar: computes new min/max and var_off. 12294 * Caller should also handle BPF_MOV case separately. 12295 * If we return -EACCES, caller may want to try again treating pointer as a 12296 * scalar. So we only emit a diagnostic if !env->allow_ptr_leaks. 12297 */ 12298 static int adjust_ptr_min_max_vals(struct bpf_verifier_env *env, 12299 struct bpf_insn *insn, 12300 const struct bpf_reg_state *ptr_reg, 12301 const struct bpf_reg_state *off_reg) 12302 { 12303 struct bpf_verifier_state *vstate = env->cur_state; 12304 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 12305 struct bpf_reg_state *regs = state->regs, *dst_reg; 12306 bool known = tnum_is_const(off_reg->var_off); 12307 s64 smin_val = off_reg->smin_value, smax_val = off_reg->smax_value, 12308 smin_ptr = ptr_reg->smin_value, smax_ptr = ptr_reg->smax_value; 12309 u64 umin_val = off_reg->umin_value, umax_val = off_reg->umax_value, 12310 umin_ptr = ptr_reg->umin_value, umax_ptr = ptr_reg->umax_value; 12311 struct bpf_sanitize_info info = {}; 12312 u8 opcode = BPF_OP(insn->code); 12313 u32 dst = insn->dst_reg; 12314 int ret; 12315 12316 dst_reg = ®s[dst]; 12317 12318 if ((known && (smin_val != smax_val || umin_val != umax_val)) || 12319 smin_val > smax_val || umin_val > umax_val) { 12320 /* Taint dst register if offset had invalid bounds derived from 12321 * e.g. dead branches. 12322 */ 12323 __mark_reg_unknown(env, dst_reg); 12324 return 0; 12325 } 12326 12327 if (BPF_CLASS(insn->code) != BPF_ALU64) { 12328 /* 32-bit ALU ops on pointers produce (meaningless) scalars */ 12329 if (opcode == BPF_SUB && env->allow_ptr_leaks) { 12330 __mark_reg_unknown(env, dst_reg); 12331 return 0; 12332 } 12333 12334 verbose(env, 12335 "R%d 32-bit pointer arithmetic prohibited\n", 12336 dst); 12337 return -EACCES; 12338 } 12339 12340 if (ptr_reg->type & PTR_MAYBE_NULL) { 12341 verbose(env, "R%d pointer arithmetic on %s prohibited, null-check it first\n", 12342 dst, reg_type_str(env, ptr_reg->type)); 12343 return -EACCES; 12344 } 12345 12346 switch (base_type(ptr_reg->type)) { 12347 case CONST_PTR_TO_MAP: 12348 /* smin_val represents the known value */ 12349 if (known && smin_val == 0 && opcode == BPF_ADD) 12350 break; 12351 fallthrough; 12352 case PTR_TO_PACKET_END: 12353 case PTR_TO_SOCKET: 12354 case PTR_TO_SOCK_COMMON: 12355 case PTR_TO_TCP_SOCK: 12356 case PTR_TO_XDP_SOCK: 12357 verbose(env, "R%d pointer arithmetic on %s prohibited\n", 12358 dst, reg_type_str(env, ptr_reg->type)); 12359 return -EACCES; 12360 default: 12361 break; 12362 } 12363 12364 /* In case of 'scalar += pointer', dst_reg inherits pointer type and id. 12365 * The id may be overwritten later if we create a new variable offset. 12366 */ 12367 dst_reg->type = ptr_reg->type; 12368 dst_reg->id = ptr_reg->id; 12369 12370 if (!check_reg_sane_offset(env, off_reg, ptr_reg->type) || 12371 !check_reg_sane_offset(env, ptr_reg, ptr_reg->type)) 12372 return -EINVAL; 12373 12374 /* pointer types do not carry 32-bit bounds at the moment. */ 12375 __mark_reg32_unbounded(dst_reg); 12376 12377 if (sanitize_needed(opcode)) { 12378 ret = sanitize_ptr_alu(env, insn, ptr_reg, off_reg, dst_reg, 12379 &info, false); 12380 if (ret < 0) 12381 return sanitize_err(env, insn, ret, off_reg, dst_reg); 12382 } 12383 12384 switch (opcode) { 12385 case BPF_ADD: 12386 /* We can take a fixed offset as long as it doesn't overflow 12387 * the s32 'off' field 12388 */ 12389 if (known && (ptr_reg->off + smin_val == 12390 (s64)(s32)(ptr_reg->off + smin_val))) { 12391 /* pointer += K. Accumulate it into fixed offset */ 12392 dst_reg->smin_value = smin_ptr; 12393 dst_reg->smax_value = smax_ptr; 12394 dst_reg->umin_value = umin_ptr; 12395 dst_reg->umax_value = umax_ptr; 12396 dst_reg->var_off = ptr_reg->var_off; 12397 dst_reg->off = ptr_reg->off + smin_val; 12398 dst_reg->raw = ptr_reg->raw; 12399 break; 12400 } 12401 /* A new variable offset is created. Note that off_reg->off 12402 * == 0, since it's a scalar. 12403 * dst_reg gets the pointer type and since some positive 12404 * integer value was added to the pointer, give it a new 'id' 12405 * if it's a PTR_TO_PACKET. 12406 * this creates a new 'base' pointer, off_reg (variable) gets 12407 * added into the variable offset, and we copy the fixed offset 12408 * from ptr_reg. 12409 */ 12410 if (signed_add_overflows(smin_ptr, smin_val) || 12411 signed_add_overflows(smax_ptr, smax_val)) { 12412 dst_reg->smin_value = S64_MIN; 12413 dst_reg->smax_value = S64_MAX; 12414 } else { 12415 dst_reg->smin_value = smin_ptr + smin_val; 12416 dst_reg->smax_value = smax_ptr + smax_val; 12417 } 12418 if (umin_ptr + umin_val < umin_ptr || 12419 umax_ptr + umax_val < umax_ptr) { 12420 dst_reg->umin_value = 0; 12421 dst_reg->umax_value = U64_MAX; 12422 } else { 12423 dst_reg->umin_value = umin_ptr + umin_val; 12424 dst_reg->umax_value = umax_ptr + umax_val; 12425 } 12426 dst_reg->var_off = tnum_add(ptr_reg->var_off, off_reg->var_off); 12427 dst_reg->off = ptr_reg->off; 12428 dst_reg->raw = ptr_reg->raw; 12429 if (reg_is_pkt_pointer(ptr_reg)) { 12430 dst_reg->id = ++env->id_gen; 12431 /* something was added to pkt_ptr, set range to zero */ 12432 memset(&dst_reg->raw, 0, sizeof(dst_reg->raw)); 12433 } 12434 break; 12435 case BPF_SUB: 12436 if (dst_reg == off_reg) { 12437 /* scalar -= pointer. Creates an unknown scalar */ 12438 verbose(env, "R%d tried to subtract pointer from scalar\n", 12439 dst); 12440 return -EACCES; 12441 } 12442 /* We don't allow subtraction from FP, because (according to 12443 * test_verifier.c test "invalid fp arithmetic", JITs might not 12444 * be able to deal with it. 12445 */ 12446 if (ptr_reg->type == PTR_TO_STACK) { 12447 verbose(env, "R%d subtraction from stack pointer prohibited\n", 12448 dst); 12449 return -EACCES; 12450 } 12451 if (known && (ptr_reg->off - smin_val == 12452 (s64)(s32)(ptr_reg->off - smin_val))) { 12453 /* pointer -= K. Subtract it from fixed offset */ 12454 dst_reg->smin_value = smin_ptr; 12455 dst_reg->smax_value = smax_ptr; 12456 dst_reg->umin_value = umin_ptr; 12457 dst_reg->umax_value = umax_ptr; 12458 dst_reg->var_off = ptr_reg->var_off; 12459 dst_reg->id = ptr_reg->id; 12460 dst_reg->off = ptr_reg->off - smin_val; 12461 dst_reg->raw = ptr_reg->raw; 12462 break; 12463 } 12464 /* A new variable offset is created. If the subtrahend is known 12465 * nonnegative, then any reg->range we had before is still good. 12466 */ 12467 if (signed_sub_overflows(smin_ptr, smax_val) || 12468 signed_sub_overflows(smax_ptr, smin_val)) { 12469 /* Overflow possible, we know nothing */ 12470 dst_reg->smin_value = S64_MIN; 12471 dst_reg->smax_value = S64_MAX; 12472 } else { 12473 dst_reg->smin_value = smin_ptr - smax_val; 12474 dst_reg->smax_value = smax_ptr - smin_val; 12475 } 12476 if (umin_ptr < umax_val) { 12477 /* Overflow possible, we know nothing */ 12478 dst_reg->umin_value = 0; 12479 dst_reg->umax_value = U64_MAX; 12480 } else { 12481 /* Cannot overflow (as long as bounds are consistent) */ 12482 dst_reg->umin_value = umin_ptr - umax_val; 12483 dst_reg->umax_value = umax_ptr - umin_val; 12484 } 12485 dst_reg->var_off = tnum_sub(ptr_reg->var_off, off_reg->var_off); 12486 dst_reg->off = ptr_reg->off; 12487 dst_reg->raw = ptr_reg->raw; 12488 if (reg_is_pkt_pointer(ptr_reg)) { 12489 dst_reg->id = ++env->id_gen; 12490 /* something was added to pkt_ptr, set range to zero */ 12491 if (smin_val < 0) 12492 memset(&dst_reg->raw, 0, sizeof(dst_reg->raw)); 12493 } 12494 break; 12495 case BPF_AND: 12496 case BPF_OR: 12497 case BPF_XOR: 12498 /* bitwise ops on pointers are troublesome, prohibit. */ 12499 verbose(env, "R%d bitwise operator %s on pointer prohibited\n", 12500 dst, bpf_alu_string[opcode >> 4]); 12501 return -EACCES; 12502 default: 12503 /* other operators (e.g. MUL,LSH) produce non-pointer results */ 12504 verbose(env, "R%d pointer arithmetic with %s operator prohibited\n", 12505 dst, bpf_alu_string[opcode >> 4]); 12506 return -EACCES; 12507 } 12508 12509 if (!check_reg_sane_offset(env, dst_reg, ptr_reg->type)) 12510 return -EINVAL; 12511 reg_bounds_sync(dst_reg); 12512 if (sanitize_check_bounds(env, insn, dst_reg) < 0) 12513 return -EACCES; 12514 if (sanitize_needed(opcode)) { 12515 ret = sanitize_ptr_alu(env, insn, dst_reg, off_reg, dst_reg, 12516 &info, true); 12517 if (ret < 0) 12518 return sanitize_err(env, insn, ret, off_reg, dst_reg); 12519 } 12520 12521 return 0; 12522 } 12523 12524 static void scalar32_min_max_add(struct bpf_reg_state *dst_reg, 12525 struct bpf_reg_state *src_reg) 12526 { 12527 s32 smin_val = src_reg->s32_min_value; 12528 s32 smax_val = src_reg->s32_max_value; 12529 u32 umin_val = src_reg->u32_min_value; 12530 u32 umax_val = src_reg->u32_max_value; 12531 12532 if (signed_add32_overflows(dst_reg->s32_min_value, smin_val) || 12533 signed_add32_overflows(dst_reg->s32_max_value, smax_val)) { 12534 dst_reg->s32_min_value = S32_MIN; 12535 dst_reg->s32_max_value = S32_MAX; 12536 } else { 12537 dst_reg->s32_min_value += smin_val; 12538 dst_reg->s32_max_value += smax_val; 12539 } 12540 if (dst_reg->u32_min_value + umin_val < umin_val || 12541 dst_reg->u32_max_value + umax_val < umax_val) { 12542 dst_reg->u32_min_value = 0; 12543 dst_reg->u32_max_value = U32_MAX; 12544 } else { 12545 dst_reg->u32_min_value += umin_val; 12546 dst_reg->u32_max_value += umax_val; 12547 } 12548 } 12549 12550 static void scalar_min_max_add(struct bpf_reg_state *dst_reg, 12551 struct bpf_reg_state *src_reg) 12552 { 12553 s64 smin_val = src_reg->smin_value; 12554 s64 smax_val = src_reg->smax_value; 12555 u64 umin_val = src_reg->umin_value; 12556 u64 umax_val = src_reg->umax_value; 12557 12558 if (signed_add_overflows(dst_reg->smin_value, smin_val) || 12559 signed_add_overflows(dst_reg->smax_value, smax_val)) { 12560 dst_reg->smin_value = S64_MIN; 12561 dst_reg->smax_value = S64_MAX; 12562 } else { 12563 dst_reg->smin_value += smin_val; 12564 dst_reg->smax_value += smax_val; 12565 } 12566 if (dst_reg->umin_value + umin_val < umin_val || 12567 dst_reg->umax_value + umax_val < umax_val) { 12568 dst_reg->umin_value = 0; 12569 dst_reg->umax_value = U64_MAX; 12570 } else { 12571 dst_reg->umin_value += umin_val; 12572 dst_reg->umax_value += umax_val; 12573 } 12574 } 12575 12576 static void scalar32_min_max_sub(struct bpf_reg_state *dst_reg, 12577 struct bpf_reg_state *src_reg) 12578 { 12579 s32 smin_val = src_reg->s32_min_value; 12580 s32 smax_val = src_reg->s32_max_value; 12581 u32 umin_val = src_reg->u32_min_value; 12582 u32 umax_val = src_reg->u32_max_value; 12583 12584 if (signed_sub32_overflows(dst_reg->s32_min_value, smax_val) || 12585 signed_sub32_overflows(dst_reg->s32_max_value, smin_val)) { 12586 /* Overflow possible, we know nothing */ 12587 dst_reg->s32_min_value = S32_MIN; 12588 dst_reg->s32_max_value = S32_MAX; 12589 } else { 12590 dst_reg->s32_min_value -= smax_val; 12591 dst_reg->s32_max_value -= smin_val; 12592 } 12593 if (dst_reg->u32_min_value < umax_val) { 12594 /* Overflow possible, we know nothing */ 12595 dst_reg->u32_min_value = 0; 12596 dst_reg->u32_max_value = U32_MAX; 12597 } else { 12598 /* Cannot overflow (as long as bounds are consistent) */ 12599 dst_reg->u32_min_value -= umax_val; 12600 dst_reg->u32_max_value -= umin_val; 12601 } 12602 } 12603 12604 static void scalar_min_max_sub(struct bpf_reg_state *dst_reg, 12605 struct bpf_reg_state *src_reg) 12606 { 12607 s64 smin_val = src_reg->smin_value; 12608 s64 smax_val = src_reg->smax_value; 12609 u64 umin_val = src_reg->umin_value; 12610 u64 umax_val = src_reg->umax_value; 12611 12612 if (signed_sub_overflows(dst_reg->smin_value, smax_val) || 12613 signed_sub_overflows(dst_reg->smax_value, smin_val)) { 12614 /* Overflow possible, we know nothing */ 12615 dst_reg->smin_value = S64_MIN; 12616 dst_reg->smax_value = S64_MAX; 12617 } else { 12618 dst_reg->smin_value -= smax_val; 12619 dst_reg->smax_value -= smin_val; 12620 } 12621 if (dst_reg->umin_value < umax_val) { 12622 /* Overflow possible, we know nothing */ 12623 dst_reg->umin_value = 0; 12624 dst_reg->umax_value = U64_MAX; 12625 } else { 12626 /* Cannot overflow (as long as bounds are consistent) */ 12627 dst_reg->umin_value -= umax_val; 12628 dst_reg->umax_value -= umin_val; 12629 } 12630 } 12631 12632 static void scalar32_min_max_mul(struct bpf_reg_state *dst_reg, 12633 struct bpf_reg_state *src_reg) 12634 { 12635 s32 smin_val = src_reg->s32_min_value; 12636 u32 umin_val = src_reg->u32_min_value; 12637 u32 umax_val = src_reg->u32_max_value; 12638 12639 if (smin_val < 0 || dst_reg->s32_min_value < 0) { 12640 /* Ain't nobody got time to multiply that sign */ 12641 __mark_reg32_unbounded(dst_reg); 12642 return; 12643 } 12644 /* Both values are positive, so we can work with unsigned and 12645 * copy the result to signed (unless it exceeds S32_MAX). 12646 */ 12647 if (umax_val > U16_MAX || dst_reg->u32_max_value > U16_MAX) { 12648 /* Potential overflow, we know nothing */ 12649 __mark_reg32_unbounded(dst_reg); 12650 return; 12651 } 12652 dst_reg->u32_min_value *= umin_val; 12653 dst_reg->u32_max_value *= umax_val; 12654 if (dst_reg->u32_max_value > S32_MAX) { 12655 /* Overflow possible, we know nothing */ 12656 dst_reg->s32_min_value = S32_MIN; 12657 dst_reg->s32_max_value = S32_MAX; 12658 } else { 12659 dst_reg->s32_min_value = dst_reg->u32_min_value; 12660 dst_reg->s32_max_value = dst_reg->u32_max_value; 12661 } 12662 } 12663 12664 static void scalar_min_max_mul(struct bpf_reg_state *dst_reg, 12665 struct bpf_reg_state *src_reg) 12666 { 12667 s64 smin_val = src_reg->smin_value; 12668 u64 umin_val = src_reg->umin_value; 12669 u64 umax_val = src_reg->umax_value; 12670 12671 if (smin_val < 0 || dst_reg->smin_value < 0) { 12672 /* Ain't nobody got time to multiply that sign */ 12673 __mark_reg64_unbounded(dst_reg); 12674 return; 12675 } 12676 /* Both values are positive, so we can work with unsigned and 12677 * copy the result to signed (unless it exceeds S64_MAX). 12678 */ 12679 if (umax_val > U32_MAX || dst_reg->umax_value > U32_MAX) { 12680 /* Potential overflow, we know nothing */ 12681 __mark_reg64_unbounded(dst_reg); 12682 return; 12683 } 12684 dst_reg->umin_value *= umin_val; 12685 dst_reg->umax_value *= umax_val; 12686 if (dst_reg->umax_value > S64_MAX) { 12687 /* Overflow possible, we know nothing */ 12688 dst_reg->smin_value = S64_MIN; 12689 dst_reg->smax_value = S64_MAX; 12690 } else { 12691 dst_reg->smin_value = dst_reg->umin_value; 12692 dst_reg->smax_value = dst_reg->umax_value; 12693 } 12694 } 12695 12696 static void scalar32_min_max_and(struct bpf_reg_state *dst_reg, 12697 struct bpf_reg_state *src_reg) 12698 { 12699 bool src_known = tnum_subreg_is_const(src_reg->var_off); 12700 bool dst_known = tnum_subreg_is_const(dst_reg->var_off); 12701 struct tnum var32_off = tnum_subreg(dst_reg->var_off); 12702 s32 smin_val = src_reg->s32_min_value; 12703 u32 umax_val = src_reg->u32_max_value; 12704 12705 if (src_known && dst_known) { 12706 __mark_reg32_known(dst_reg, var32_off.value); 12707 return; 12708 } 12709 12710 /* We get our minimum from the var_off, since that's inherently 12711 * bitwise. Our maximum is the minimum of the operands' maxima. 12712 */ 12713 dst_reg->u32_min_value = var32_off.value; 12714 dst_reg->u32_max_value = min(dst_reg->u32_max_value, umax_val); 12715 if (dst_reg->s32_min_value < 0 || smin_val < 0) { 12716 /* Lose signed bounds when ANDing negative numbers, 12717 * ain't nobody got time for that. 12718 */ 12719 dst_reg->s32_min_value = S32_MIN; 12720 dst_reg->s32_max_value = S32_MAX; 12721 } else { 12722 /* ANDing two positives gives a positive, so safe to 12723 * cast result into s64. 12724 */ 12725 dst_reg->s32_min_value = dst_reg->u32_min_value; 12726 dst_reg->s32_max_value = dst_reg->u32_max_value; 12727 } 12728 } 12729 12730 static void scalar_min_max_and(struct bpf_reg_state *dst_reg, 12731 struct bpf_reg_state *src_reg) 12732 { 12733 bool src_known = tnum_is_const(src_reg->var_off); 12734 bool dst_known = tnum_is_const(dst_reg->var_off); 12735 s64 smin_val = src_reg->smin_value; 12736 u64 umax_val = src_reg->umax_value; 12737 12738 if (src_known && dst_known) { 12739 __mark_reg_known(dst_reg, dst_reg->var_off.value); 12740 return; 12741 } 12742 12743 /* We get our minimum from the var_off, since that's inherently 12744 * bitwise. Our maximum is the minimum of the operands' maxima. 12745 */ 12746 dst_reg->umin_value = dst_reg->var_off.value; 12747 dst_reg->umax_value = min(dst_reg->umax_value, umax_val); 12748 if (dst_reg->smin_value < 0 || smin_val < 0) { 12749 /* Lose signed bounds when ANDing negative numbers, 12750 * ain't nobody got time for that. 12751 */ 12752 dst_reg->smin_value = S64_MIN; 12753 dst_reg->smax_value = S64_MAX; 12754 } else { 12755 /* ANDing two positives gives a positive, so safe to 12756 * cast result into s64. 12757 */ 12758 dst_reg->smin_value = dst_reg->umin_value; 12759 dst_reg->smax_value = dst_reg->umax_value; 12760 } 12761 /* We may learn something more from the var_off */ 12762 __update_reg_bounds(dst_reg); 12763 } 12764 12765 static void scalar32_min_max_or(struct bpf_reg_state *dst_reg, 12766 struct bpf_reg_state *src_reg) 12767 { 12768 bool src_known = tnum_subreg_is_const(src_reg->var_off); 12769 bool dst_known = tnum_subreg_is_const(dst_reg->var_off); 12770 struct tnum var32_off = tnum_subreg(dst_reg->var_off); 12771 s32 smin_val = src_reg->s32_min_value; 12772 u32 umin_val = src_reg->u32_min_value; 12773 12774 if (src_known && dst_known) { 12775 __mark_reg32_known(dst_reg, var32_off.value); 12776 return; 12777 } 12778 12779 /* We get our maximum from the var_off, and our minimum is the 12780 * maximum of the operands' minima 12781 */ 12782 dst_reg->u32_min_value = max(dst_reg->u32_min_value, umin_val); 12783 dst_reg->u32_max_value = var32_off.value | var32_off.mask; 12784 if (dst_reg->s32_min_value < 0 || smin_val < 0) { 12785 /* Lose signed bounds when ORing negative numbers, 12786 * ain't nobody got time for that. 12787 */ 12788 dst_reg->s32_min_value = S32_MIN; 12789 dst_reg->s32_max_value = S32_MAX; 12790 } else { 12791 /* ORing two positives gives a positive, so safe to 12792 * cast result into s64. 12793 */ 12794 dst_reg->s32_min_value = dst_reg->u32_min_value; 12795 dst_reg->s32_max_value = dst_reg->u32_max_value; 12796 } 12797 } 12798 12799 static void scalar_min_max_or(struct bpf_reg_state *dst_reg, 12800 struct bpf_reg_state *src_reg) 12801 { 12802 bool src_known = tnum_is_const(src_reg->var_off); 12803 bool dst_known = tnum_is_const(dst_reg->var_off); 12804 s64 smin_val = src_reg->smin_value; 12805 u64 umin_val = src_reg->umin_value; 12806 12807 if (src_known && dst_known) { 12808 __mark_reg_known(dst_reg, dst_reg->var_off.value); 12809 return; 12810 } 12811 12812 /* We get our maximum from the var_off, and our minimum is the 12813 * maximum of the operands' minima 12814 */ 12815 dst_reg->umin_value = max(dst_reg->umin_value, umin_val); 12816 dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask; 12817 if (dst_reg->smin_value < 0 || smin_val < 0) { 12818 /* Lose signed bounds when ORing negative numbers, 12819 * ain't nobody got time for that. 12820 */ 12821 dst_reg->smin_value = S64_MIN; 12822 dst_reg->smax_value = S64_MAX; 12823 } else { 12824 /* ORing two positives gives a positive, so safe to 12825 * cast result into s64. 12826 */ 12827 dst_reg->smin_value = dst_reg->umin_value; 12828 dst_reg->smax_value = dst_reg->umax_value; 12829 } 12830 /* We may learn something more from the var_off */ 12831 __update_reg_bounds(dst_reg); 12832 } 12833 12834 static void scalar32_min_max_xor(struct bpf_reg_state *dst_reg, 12835 struct bpf_reg_state *src_reg) 12836 { 12837 bool src_known = tnum_subreg_is_const(src_reg->var_off); 12838 bool dst_known = tnum_subreg_is_const(dst_reg->var_off); 12839 struct tnum var32_off = tnum_subreg(dst_reg->var_off); 12840 s32 smin_val = src_reg->s32_min_value; 12841 12842 if (src_known && dst_known) { 12843 __mark_reg32_known(dst_reg, var32_off.value); 12844 return; 12845 } 12846 12847 /* We get both minimum and maximum from the var32_off. */ 12848 dst_reg->u32_min_value = var32_off.value; 12849 dst_reg->u32_max_value = var32_off.value | var32_off.mask; 12850 12851 if (dst_reg->s32_min_value >= 0 && smin_val >= 0) { 12852 /* XORing two positive sign numbers gives a positive, 12853 * so safe to cast u32 result into s32. 12854 */ 12855 dst_reg->s32_min_value = dst_reg->u32_min_value; 12856 dst_reg->s32_max_value = dst_reg->u32_max_value; 12857 } else { 12858 dst_reg->s32_min_value = S32_MIN; 12859 dst_reg->s32_max_value = S32_MAX; 12860 } 12861 } 12862 12863 static void scalar_min_max_xor(struct bpf_reg_state *dst_reg, 12864 struct bpf_reg_state *src_reg) 12865 { 12866 bool src_known = tnum_is_const(src_reg->var_off); 12867 bool dst_known = tnum_is_const(dst_reg->var_off); 12868 s64 smin_val = src_reg->smin_value; 12869 12870 if (src_known && dst_known) { 12871 /* dst_reg->var_off.value has been updated earlier */ 12872 __mark_reg_known(dst_reg, dst_reg->var_off.value); 12873 return; 12874 } 12875 12876 /* We get both minimum and maximum from the var_off. */ 12877 dst_reg->umin_value = dst_reg->var_off.value; 12878 dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask; 12879 12880 if (dst_reg->smin_value >= 0 && smin_val >= 0) { 12881 /* XORing two positive sign numbers gives a positive, 12882 * so safe to cast u64 result into s64. 12883 */ 12884 dst_reg->smin_value = dst_reg->umin_value; 12885 dst_reg->smax_value = dst_reg->umax_value; 12886 } else { 12887 dst_reg->smin_value = S64_MIN; 12888 dst_reg->smax_value = S64_MAX; 12889 } 12890 12891 __update_reg_bounds(dst_reg); 12892 } 12893 12894 static void __scalar32_min_max_lsh(struct bpf_reg_state *dst_reg, 12895 u64 umin_val, u64 umax_val) 12896 { 12897 /* We lose all sign bit information (except what we can pick 12898 * up from var_off) 12899 */ 12900 dst_reg->s32_min_value = S32_MIN; 12901 dst_reg->s32_max_value = S32_MAX; 12902 /* If we might shift our top bit out, then we know nothing */ 12903 if (umax_val > 31 || dst_reg->u32_max_value > 1ULL << (31 - umax_val)) { 12904 dst_reg->u32_min_value = 0; 12905 dst_reg->u32_max_value = U32_MAX; 12906 } else { 12907 dst_reg->u32_min_value <<= umin_val; 12908 dst_reg->u32_max_value <<= umax_val; 12909 } 12910 } 12911 12912 static void scalar32_min_max_lsh(struct bpf_reg_state *dst_reg, 12913 struct bpf_reg_state *src_reg) 12914 { 12915 u32 umax_val = src_reg->u32_max_value; 12916 u32 umin_val = src_reg->u32_min_value; 12917 /* u32 alu operation will zext upper bits */ 12918 struct tnum subreg = tnum_subreg(dst_reg->var_off); 12919 12920 __scalar32_min_max_lsh(dst_reg, umin_val, umax_val); 12921 dst_reg->var_off = tnum_subreg(tnum_lshift(subreg, umin_val)); 12922 /* Not required but being careful mark reg64 bounds as unknown so 12923 * that we are forced to pick them up from tnum and zext later and 12924 * if some path skips this step we are still safe. 12925 */ 12926 __mark_reg64_unbounded(dst_reg); 12927 __update_reg32_bounds(dst_reg); 12928 } 12929 12930 static void __scalar64_min_max_lsh(struct bpf_reg_state *dst_reg, 12931 u64 umin_val, u64 umax_val) 12932 { 12933 /* Special case <<32 because it is a common compiler pattern to sign 12934 * extend subreg by doing <<32 s>>32. In this case if 32bit bounds are 12935 * positive we know this shift will also be positive so we can track 12936 * bounds correctly. Otherwise we lose all sign bit information except 12937 * what we can pick up from var_off. Perhaps we can generalize this 12938 * later to shifts of any length. 12939 */ 12940 if (umin_val == 32 && umax_val == 32 && dst_reg->s32_max_value >= 0) 12941 dst_reg->smax_value = (s64)dst_reg->s32_max_value << 32; 12942 else 12943 dst_reg->smax_value = S64_MAX; 12944 12945 if (umin_val == 32 && umax_val == 32 && dst_reg->s32_min_value >= 0) 12946 dst_reg->smin_value = (s64)dst_reg->s32_min_value << 32; 12947 else 12948 dst_reg->smin_value = S64_MIN; 12949 12950 /* If we might shift our top bit out, then we know nothing */ 12951 if (dst_reg->umax_value > 1ULL << (63 - umax_val)) { 12952 dst_reg->umin_value = 0; 12953 dst_reg->umax_value = U64_MAX; 12954 } else { 12955 dst_reg->umin_value <<= umin_val; 12956 dst_reg->umax_value <<= umax_val; 12957 } 12958 } 12959 12960 static void scalar_min_max_lsh(struct bpf_reg_state *dst_reg, 12961 struct bpf_reg_state *src_reg) 12962 { 12963 u64 umax_val = src_reg->umax_value; 12964 u64 umin_val = src_reg->umin_value; 12965 12966 /* scalar64 calc uses 32bit unshifted bounds so must be called first */ 12967 __scalar64_min_max_lsh(dst_reg, umin_val, umax_val); 12968 __scalar32_min_max_lsh(dst_reg, umin_val, umax_val); 12969 12970 dst_reg->var_off = tnum_lshift(dst_reg->var_off, umin_val); 12971 /* We may learn something more from the var_off */ 12972 __update_reg_bounds(dst_reg); 12973 } 12974 12975 static void scalar32_min_max_rsh(struct bpf_reg_state *dst_reg, 12976 struct bpf_reg_state *src_reg) 12977 { 12978 struct tnum subreg = tnum_subreg(dst_reg->var_off); 12979 u32 umax_val = src_reg->u32_max_value; 12980 u32 umin_val = src_reg->u32_min_value; 12981 12982 /* BPF_RSH is an unsigned shift. If the value in dst_reg might 12983 * be negative, then either: 12984 * 1) src_reg might be zero, so the sign bit of the result is 12985 * unknown, so we lose our signed bounds 12986 * 2) it's known negative, thus the unsigned bounds capture the 12987 * signed bounds 12988 * 3) the signed bounds cross zero, so they tell us nothing 12989 * about the result 12990 * If the value in dst_reg is known nonnegative, then again the 12991 * unsigned bounds capture the signed bounds. 12992 * Thus, in all cases it suffices to blow away our signed bounds 12993 * and rely on inferring new ones from the unsigned bounds and 12994 * var_off of the result. 12995 */ 12996 dst_reg->s32_min_value = S32_MIN; 12997 dst_reg->s32_max_value = S32_MAX; 12998 12999 dst_reg->var_off = tnum_rshift(subreg, umin_val); 13000 dst_reg->u32_min_value >>= umax_val; 13001 dst_reg->u32_max_value >>= umin_val; 13002 13003 __mark_reg64_unbounded(dst_reg); 13004 __update_reg32_bounds(dst_reg); 13005 } 13006 13007 static void scalar_min_max_rsh(struct bpf_reg_state *dst_reg, 13008 struct bpf_reg_state *src_reg) 13009 { 13010 u64 umax_val = src_reg->umax_value; 13011 u64 umin_val = src_reg->umin_value; 13012 13013 /* BPF_RSH is an unsigned shift. If the value in dst_reg might 13014 * be negative, then either: 13015 * 1) src_reg might be zero, so the sign bit of the result is 13016 * unknown, so we lose our signed bounds 13017 * 2) it's known negative, thus the unsigned bounds capture the 13018 * signed bounds 13019 * 3) the signed bounds cross zero, so they tell us nothing 13020 * about the result 13021 * If the value in dst_reg is known nonnegative, then again the 13022 * unsigned bounds capture the signed bounds. 13023 * Thus, in all cases it suffices to blow away our signed bounds 13024 * and rely on inferring new ones from the unsigned bounds and 13025 * var_off of the result. 13026 */ 13027 dst_reg->smin_value = S64_MIN; 13028 dst_reg->smax_value = S64_MAX; 13029 dst_reg->var_off = tnum_rshift(dst_reg->var_off, umin_val); 13030 dst_reg->umin_value >>= umax_val; 13031 dst_reg->umax_value >>= umin_val; 13032 13033 /* Its not easy to operate on alu32 bounds here because it depends 13034 * on bits being shifted in. Take easy way out and mark unbounded 13035 * so we can recalculate later from tnum. 13036 */ 13037 __mark_reg32_unbounded(dst_reg); 13038 __update_reg_bounds(dst_reg); 13039 } 13040 13041 static void scalar32_min_max_arsh(struct bpf_reg_state *dst_reg, 13042 struct bpf_reg_state *src_reg) 13043 { 13044 u64 umin_val = src_reg->u32_min_value; 13045 13046 /* Upon reaching here, src_known is true and 13047 * umax_val is equal to umin_val. 13048 */ 13049 dst_reg->s32_min_value = (u32)(((s32)dst_reg->s32_min_value) >> umin_val); 13050 dst_reg->s32_max_value = (u32)(((s32)dst_reg->s32_max_value) >> umin_val); 13051 13052 dst_reg->var_off = tnum_arshift(tnum_subreg(dst_reg->var_off), umin_val, 32); 13053 13054 /* blow away the dst_reg umin_value/umax_value and rely on 13055 * dst_reg var_off to refine the result. 13056 */ 13057 dst_reg->u32_min_value = 0; 13058 dst_reg->u32_max_value = U32_MAX; 13059 13060 __mark_reg64_unbounded(dst_reg); 13061 __update_reg32_bounds(dst_reg); 13062 } 13063 13064 static void scalar_min_max_arsh(struct bpf_reg_state *dst_reg, 13065 struct bpf_reg_state *src_reg) 13066 { 13067 u64 umin_val = src_reg->umin_value; 13068 13069 /* Upon reaching here, src_known is true and umax_val is equal 13070 * to umin_val. 13071 */ 13072 dst_reg->smin_value >>= umin_val; 13073 dst_reg->smax_value >>= umin_val; 13074 13075 dst_reg->var_off = tnum_arshift(dst_reg->var_off, umin_val, 64); 13076 13077 /* blow away the dst_reg umin_value/umax_value and rely on 13078 * dst_reg var_off to refine the result. 13079 */ 13080 dst_reg->umin_value = 0; 13081 dst_reg->umax_value = U64_MAX; 13082 13083 /* Its not easy to operate on alu32 bounds here because it depends 13084 * on bits being shifted in from upper 32-bits. Take easy way out 13085 * and mark unbounded so we can recalculate later from tnum. 13086 */ 13087 __mark_reg32_unbounded(dst_reg); 13088 __update_reg_bounds(dst_reg); 13089 } 13090 13091 /* WARNING: This function does calculations on 64-bit values, but the actual 13092 * execution may occur on 32-bit values. Therefore, things like bitshifts 13093 * need extra checks in the 32-bit case. 13094 */ 13095 static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env, 13096 struct bpf_insn *insn, 13097 struct bpf_reg_state *dst_reg, 13098 struct bpf_reg_state src_reg) 13099 { 13100 struct bpf_reg_state *regs = cur_regs(env); 13101 u8 opcode = BPF_OP(insn->code); 13102 bool src_known; 13103 s64 smin_val, smax_val; 13104 u64 umin_val, umax_val; 13105 s32 s32_min_val, s32_max_val; 13106 u32 u32_min_val, u32_max_val; 13107 u64 insn_bitness = (BPF_CLASS(insn->code) == BPF_ALU64) ? 64 : 32; 13108 bool alu32 = (BPF_CLASS(insn->code) != BPF_ALU64); 13109 int ret; 13110 13111 smin_val = src_reg.smin_value; 13112 smax_val = src_reg.smax_value; 13113 umin_val = src_reg.umin_value; 13114 umax_val = src_reg.umax_value; 13115 13116 s32_min_val = src_reg.s32_min_value; 13117 s32_max_val = src_reg.s32_max_value; 13118 u32_min_val = src_reg.u32_min_value; 13119 u32_max_val = src_reg.u32_max_value; 13120 13121 if (alu32) { 13122 src_known = tnum_subreg_is_const(src_reg.var_off); 13123 if ((src_known && 13124 (s32_min_val != s32_max_val || u32_min_val != u32_max_val)) || 13125 s32_min_val > s32_max_val || u32_min_val > u32_max_val) { 13126 /* Taint dst register if offset had invalid bounds 13127 * derived from e.g. dead branches. 13128 */ 13129 __mark_reg_unknown(env, dst_reg); 13130 return 0; 13131 } 13132 } else { 13133 src_known = tnum_is_const(src_reg.var_off); 13134 if ((src_known && 13135 (smin_val != smax_val || umin_val != umax_val)) || 13136 smin_val > smax_val || umin_val > umax_val) { 13137 /* Taint dst register if offset had invalid bounds 13138 * derived from e.g. dead branches. 13139 */ 13140 __mark_reg_unknown(env, dst_reg); 13141 return 0; 13142 } 13143 } 13144 13145 if (!src_known && 13146 opcode != BPF_ADD && opcode != BPF_SUB && opcode != BPF_AND) { 13147 __mark_reg_unknown(env, dst_reg); 13148 return 0; 13149 } 13150 13151 if (sanitize_needed(opcode)) { 13152 ret = sanitize_val_alu(env, insn); 13153 if (ret < 0) 13154 return sanitize_err(env, insn, ret, NULL, NULL); 13155 } 13156 13157 /* Calculate sign/unsigned bounds and tnum for alu32 and alu64 bit ops. 13158 * There are two classes of instructions: The first class we track both 13159 * alu32 and alu64 sign/unsigned bounds independently this provides the 13160 * greatest amount of precision when alu operations are mixed with jmp32 13161 * operations. These operations are BPF_ADD, BPF_SUB, BPF_MUL, BPF_ADD, 13162 * and BPF_OR. This is possible because these ops have fairly easy to 13163 * understand and calculate behavior in both 32-bit and 64-bit alu ops. 13164 * See alu32 verifier tests for examples. The second class of 13165 * operations, BPF_LSH, BPF_RSH, and BPF_ARSH, however are not so easy 13166 * with regards to tracking sign/unsigned bounds because the bits may 13167 * cross subreg boundaries in the alu64 case. When this happens we mark 13168 * the reg unbounded in the subreg bound space and use the resulting 13169 * tnum to calculate an approximation of the sign/unsigned bounds. 13170 */ 13171 switch (opcode) { 13172 case BPF_ADD: 13173 scalar32_min_max_add(dst_reg, &src_reg); 13174 scalar_min_max_add(dst_reg, &src_reg); 13175 dst_reg->var_off = tnum_add(dst_reg->var_off, src_reg.var_off); 13176 break; 13177 case BPF_SUB: 13178 scalar32_min_max_sub(dst_reg, &src_reg); 13179 scalar_min_max_sub(dst_reg, &src_reg); 13180 dst_reg->var_off = tnum_sub(dst_reg->var_off, src_reg.var_off); 13181 break; 13182 case BPF_MUL: 13183 dst_reg->var_off = tnum_mul(dst_reg->var_off, src_reg.var_off); 13184 scalar32_min_max_mul(dst_reg, &src_reg); 13185 scalar_min_max_mul(dst_reg, &src_reg); 13186 break; 13187 case BPF_AND: 13188 dst_reg->var_off = tnum_and(dst_reg->var_off, src_reg.var_off); 13189 scalar32_min_max_and(dst_reg, &src_reg); 13190 scalar_min_max_and(dst_reg, &src_reg); 13191 break; 13192 case BPF_OR: 13193 dst_reg->var_off = tnum_or(dst_reg->var_off, src_reg.var_off); 13194 scalar32_min_max_or(dst_reg, &src_reg); 13195 scalar_min_max_or(dst_reg, &src_reg); 13196 break; 13197 case BPF_XOR: 13198 dst_reg->var_off = tnum_xor(dst_reg->var_off, src_reg.var_off); 13199 scalar32_min_max_xor(dst_reg, &src_reg); 13200 scalar_min_max_xor(dst_reg, &src_reg); 13201 break; 13202 case BPF_LSH: 13203 if (umax_val >= insn_bitness) { 13204 /* Shifts greater than 31 or 63 are undefined. 13205 * This includes shifts by a negative number. 13206 */ 13207 mark_reg_unknown(env, regs, insn->dst_reg); 13208 break; 13209 } 13210 if (alu32) 13211 scalar32_min_max_lsh(dst_reg, &src_reg); 13212 else 13213 scalar_min_max_lsh(dst_reg, &src_reg); 13214 break; 13215 case BPF_RSH: 13216 if (umax_val >= insn_bitness) { 13217 /* Shifts greater than 31 or 63 are undefined. 13218 * This includes shifts by a negative number. 13219 */ 13220 mark_reg_unknown(env, regs, insn->dst_reg); 13221 break; 13222 } 13223 if (alu32) 13224 scalar32_min_max_rsh(dst_reg, &src_reg); 13225 else 13226 scalar_min_max_rsh(dst_reg, &src_reg); 13227 break; 13228 case BPF_ARSH: 13229 if (umax_val >= insn_bitness) { 13230 /* Shifts greater than 31 or 63 are undefined. 13231 * This includes shifts by a negative number. 13232 */ 13233 mark_reg_unknown(env, regs, insn->dst_reg); 13234 break; 13235 } 13236 if (alu32) 13237 scalar32_min_max_arsh(dst_reg, &src_reg); 13238 else 13239 scalar_min_max_arsh(dst_reg, &src_reg); 13240 break; 13241 default: 13242 mark_reg_unknown(env, regs, insn->dst_reg); 13243 break; 13244 } 13245 13246 /* ALU32 ops are zero extended into 64bit register */ 13247 if (alu32) 13248 zext_32_to_64(dst_reg); 13249 reg_bounds_sync(dst_reg); 13250 return 0; 13251 } 13252 13253 /* Handles ALU ops other than BPF_END, BPF_NEG and BPF_MOV: computes new min/max 13254 * and var_off. 13255 */ 13256 static int adjust_reg_min_max_vals(struct bpf_verifier_env *env, 13257 struct bpf_insn *insn) 13258 { 13259 struct bpf_verifier_state *vstate = env->cur_state; 13260 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 13261 struct bpf_reg_state *regs = state->regs, *dst_reg, *src_reg; 13262 struct bpf_reg_state *ptr_reg = NULL, off_reg = {0}; 13263 u8 opcode = BPF_OP(insn->code); 13264 int err; 13265 13266 dst_reg = ®s[insn->dst_reg]; 13267 src_reg = NULL; 13268 if (dst_reg->type != SCALAR_VALUE) 13269 ptr_reg = dst_reg; 13270 else 13271 /* Make sure ID is cleared otherwise dst_reg min/max could be 13272 * incorrectly propagated into other registers by find_equal_scalars() 13273 */ 13274 dst_reg->id = 0; 13275 if (BPF_SRC(insn->code) == BPF_X) { 13276 src_reg = ®s[insn->src_reg]; 13277 if (src_reg->type != SCALAR_VALUE) { 13278 if (dst_reg->type != SCALAR_VALUE) { 13279 /* Combining two pointers by any ALU op yields 13280 * an arbitrary scalar. Disallow all math except 13281 * pointer subtraction 13282 */ 13283 if (opcode == BPF_SUB && env->allow_ptr_leaks) { 13284 mark_reg_unknown(env, regs, insn->dst_reg); 13285 return 0; 13286 } 13287 verbose(env, "R%d pointer %s pointer prohibited\n", 13288 insn->dst_reg, 13289 bpf_alu_string[opcode >> 4]); 13290 return -EACCES; 13291 } else { 13292 /* scalar += pointer 13293 * This is legal, but we have to reverse our 13294 * src/dest handling in computing the range 13295 */ 13296 err = mark_chain_precision(env, insn->dst_reg); 13297 if (err) 13298 return err; 13299 return adjust_ptr_min_max_vals(env, insn, 13300 src_reg, dst_reg); 13301 } 13302 } else if (ptr_reg) { 13303 /* pointer += scalar */ 13304 err = mark_chain_precision(env, insn->src_reg); 13305 if (err) 13306 return err; 13307 return adjust_ptr_min_max_vals(env, insn, 13308 dst_reg, src_reg); 13309 } else if (dst_reg->precise) { 13310 /* if dst_reg is precise, src_reg should be precise as well */ 13311 err = mark_chain_precision(env, insn->src_reg); 13312 if (err) 13313 return err; 13314 } 13315 } else { 13316 /* Pretend the src is a reg with a known value, since we only 13317 * need to be able to read from this state. 13318 */ 13319 off_reg.type = SCALAR_VALUE; 13320 __mark_reg_known(&off_reg, insn->imm); 13321 src_reg = &off_reg; 13322 if (ptr_reg) /* pointer += K */ 13323 return adjust_ptr_min_max_vals(env, insn, 13324 ptr_reg, src_reg); 13325 } 13326 13327 /* Got here implies adding two SCALAR_VALUEs */ 13328 if (WARN_ON_ONCE(ptr_reg)) { 13329 print_verifier_state(env, state, true); 13330 verbose(env, "verifier internal error: unexpected ptr_reg\n"); 13331 return -EINVAL; 13332 } 13333 if (WARN_ON(!src_reg)) { 13334 print_verifier_state(env, state, true); 13335 verbose(env, "verifier internal error: no src_reg\n"); 13336 return -EINVAL; 13337 } 13338 return adjust_scalar_min_max_vals(env, insn, dst_reg, *src_reg); 13339 } 13340 13341 /* check validity of 32-bit and 64-bit arithmetic operations */ 13342 static int check_alu_op(struct bpf_verifier_env *env, struct bpf_insn *insn) 13343 { 13344 struct bpf_reg_state *regs = cur_regs(env); 13345 u8 opcode = BPF_OP(insn->code); 13346 int err; 13347 13348 if (opcode == BPF_END || opcode == BPF_NEG) { 13349 if (opcode == BPF_NEG) { 13350 if (BPF_SRC(insn->code) != BPF_K || 13351 insn->src_reg != BPF_REG_0 || 13352 insn->off != 0 || insn->imm != 0) { 13353 verbose(env, "BPF_NEG uses reserved fields\n"); 13354 return -EINVAL; 13355 } 13356 } else { 13357 if (insn->src_reg != BPF_REG_0 || insn->off != 0 || 13358 (insn->imm != 16 && insn->imm != 32 && insn->imm != 64) || 13359 (BPF_CLASS(insn->code) == BPF_ALU64 && 13360 BPF_SRC(insn->code) != BPF_TO_LE)) { 13361 verbose(env, "BPF_END uses reserved fields\n"); 13362 return -EINVAL; 13363 } 13364 } 13365 13366 /* check src operand */ 13367 err = check_reg_arg(env, insn->dst_reg, SRC_OP); 13368 if (err) 13369 return err; 13370 13371 if (is_pointer_value(env, insn->dst_reg)) { 13372 verbose(env, "R%d pointer arithmetic prohibited\n", 13373 insn->dst_reg); 13374 return -EACCES; 13375 } 13376 13377 /* check dest operand */ 13378 err = check_reg_arg(env, insn->dst_reg, DST_OP); 13379 if (err) 13380 return err; 13381 13382 } else if (opcode == BPF_MOV) { 13383 13384 if (BPF_SRC(insn->code) == BPF_X) { 13385 if (insn->imm != 0) { 13386 verbose(env, "BPF_MOV uses reserved fields\n"); 13387 return -EINVAL; 13388 } 13389 13390 if (BPF_CLASS(insn->code) == BPF_ALU) { 13391 if (insn->off != 0 && insn->off != 8 && insn->off != 16) { 13392 verbose(env, "BPF_MOV uses reserved fields\n"); 13393 return -EINVAL; 13394 } 13395 } else { 13396 if (insn->off != 0 && insn->off != 8 && insn->off != 16 && 13397 insn->off != 32) { 13398 verbose(env, "BPF_MOV uses reserved fields\n"); 13399 return -EINVAL; 13400 } 13401 } 13402 13403 /* check src operand */ 13404 err = check_reg_arg(env, insn->src_reg, SRC_OP); 13405 if (err) 13406 return err; 13407 } else { 13408 if (insn->src_reg != BPF_REG_0 || insn->off != 0) { 13409 verbose(env, "BPF_MOV uses reserved fields\n"); 13410 return -EINVAL; 13411 } 13412 } 13413 13414 /* check dest operand, mark as required later */ 13415 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK); 13416 if (err) 13417 return err; 13418 13419 if (BPF_SRC(insn->code) == BPF_X) { 13420 struct bpf_reg_state *src_reg = regs + insn->src_reg; 13421 struct bpf_reg_state *dst_reg = regs + insn->dst_reg; 13422 bool need_id = src_reg->type == SCALAR_VALUE && !src_reg->id && 13423 !tnum_is_const(src_reg->var_off); 13424 13425 if (BPF_CLASS(insn->code) == BPF_ALU64) { 13426 if (insn->off == 0) { 13427 /* case: R1 = R2 13428 * copy register state to dest reg 13429 */ 13430 if (need_id) 13431 /* Assign src and dst registers the same ID 13432 * that will be used by find_equal_scalars() 13433 * to propagate min/max range. 13434 */ 13435 src_reg->id = ++env->id_gen; 13436 copy_register_state(dst_reg, src_reg); 13437 dst_reg->live |= REG_LIVE_WRITTEN; 13438 dst_reg->subreg_def = DEF_NOT_SUBREG; 13439 } else { 13440 /* case: R1 = (s8, s16 s32)R2 */ 13441 if (is_pointer_value(env, insn->src_reg)) { 13442 verbose(env, 13443 "R%d sign-extension part of pointer\n", 13444 insn->src_reg); 13445 return -EACCES; 13446 } else if (src_reg->type == SCALAR_VALUE) { 13447 bool no_sext; 13448 13449 no_sext = src_reg->umax_value < (1ULL << (insn->off - 1)); 13450 if (no_sext && need_id) 13451 src_reg->id = ++env->id_gen; 13452 copy_register_state(dst_reg, src_reg); 13453 if (!no_sext) 13454 dst_reg->id = 0; 13455 coerce_reg_to_size_sx(dst_reg, insn->off >> 3); 13456 dst_reg->live |= REG_LIVE_WRITTEN; 13457 dst_reg->subreg_def = DEF_NOT_SUBREG; 13458 } else { 13459 mark_reg_unknown(env, regs, insn->dst_reg); 13460 } 13461 } 13462 } else { 13463 /* R1 = (u32) R2 */ 13464 if (is_pointer_value(env, insn->src_reg)) { 13465 verbose(env, 13466 "R%d partial copy of pointer\n", 13467 insn->src_reg); 13468 return -EACCES; 13469 } else if (src_reg->type == SCALAR_VALUE) { 13470 if (insn->off == 0) { 13471 bool is_src_reg_u32 = src_reg->umax_value <= U32_MAX; 13472 13473 if (is_src_reg_u32 && need_id) 13474 src_reg->id = ++env->id_gen; 13475 copy_register_state(dst_reg, src_reg); 13476 /* Make sure ID is cleared if src_reg is not in u32 13477 * range otherwise dst_reg min/max could be incorrectly 13478 * propagated into src_reg by find_equal_scalars() 13479 */ 13480 if (!is_src_reg_u32) 13481 dst_reg->id = 0; 13482 dst_reg->live |= REG_LIVE_WRITTEN; 13483 dst_reg->subreg_def = env->insn_idx + 1; 13484 } else { 13485 /* case: W1 = (s8, s16)W2 */ 13486 bool no_sext = src_reg->umax_value < (1ULL << (insn->off - 1)); 13487 13488 if (no_sext && need_id) 13489 src_reg->id = ++env->id_gen; 13490 copy_register_state(dst_reg, src_reg); 13491 if (!no_sext) 13492 dst_reg->id = 0; 13493 dst_reg->live |= REG_LIVE_WRITTEN; 13494 dst_reg->subreg_def = env->insn_idx + 1; 13495 coerce_subreg_to_size_sx(dst_reg, insn->off >> 3); 13496 } 13497 } else { 13498 mark_reg_unknown(env, regs, 13499 insn->dst_reg); 13500 } 13501 zext_32_to_64(dst_reg); 13502 reg_bounds_sync(dst_reg); 13503 } 13504 } else { 13505 /* case: R = imm 13506 * remember the value we stored into this reg 13507 */ 13508 /* clear any state __mark_reg_known doesn't set */ 13509 mark_reg_unknown(env, regs, insn->dst_reg); 13510 regs[insn->dst_reg].type = SCALAR_VALUE; 13511 if (BPF_CLASS(insn->code) == BPF_ALU64) { 13512 __mark_reg_known(regs + insn->dst_reg, 13513 insn->imm); 13514 } else { 13515 __mark_reg_known(regs + insn->dst_reg, 13516 (u32)insn->imm); 13517 } 13518 } 13519 13520 } else if (opcode > BPF_END) { 13521 verbose(env, "invalid BPF_ALU opcode %x\n", opcode); 13522 return -EINVAL; 13523 13524 } else { /* all other ALU ops: and, sub, xor, add, ... */ 13525 13526 if (BPF_SRC(insn->code) == BPF_X) { 13527 if (insn->imm != 0 || insn->off > 1 || 13528 (insn->off == 1 && opcode != BPF_MOD && opcode != BPF_DIV)) { 13529 verbose(env, "BPF_ALU uses reserved fields\n"); 13530 return -EINVAL; 13531 } 13532 /* check src1 operand */ 13533 err = check_reg_arg(env, insn->src_reg, SRC_OP); 13534 if (err) 13535 return err; 13536 } else { 13537 if (insn->src_reg != BPF_REG_0 || insn->off > 1 || 13538 (insn->off == 1 && opcode != BPF_MOD && opcode != BPF_DIV)) { 13539 verbose(env, "BPF_ALU uses reserved fields\n"); 13540 return -EINVAL; 13541 } 13542 } 13543 13544 /* check src2 operand */ 13545 err = check_reg_arg(env, insn->dst_reg, SRC_OP); 13546 if (err) 13547 return err; 13548 13549 if ((opcode == BPF_MOD || opcode == BPF_DIV) && 13550 BPF_SRC(insn->code) == BPF_K && insn->imm == 0) { 13551 verbose(env, "div by zero\n"); 13552 return -EINVAL; 13553 } 13554 13555 if ((opcode == BPF_LSH || opcode == BPF_RSH || 13556 opcode == BPF_ARSH) && BPF_SRC(insn->code) == BPF_K) { 13557 int size = BPF_CLASS(insn->code) == BPF_ALU64 ? 64 : 32; 13558 13559 if (insn->imm < 0 || insn->imm >= size) { 13560 verbose(env, "invalid shift %d\n", insn->imm); 13561 return -EINVAL; 13562 } 13563 } 13564 13565 /* check dest operand */ 13566 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK); 13567 if (err) 13568 return err; 13569 13570 return adjust_reg_min_max_vals(env, insn); 13571 } 13572 13573 return 0; 13574 } 13575 13576 static void find_good_pkt_pointers(struct bpf_verifier_state *vstate, 13577 struct bpf_reg_state *dst_reg, 13578 enum bpf_reg_type type, 13579 bool range_right_open) 13580 { 13581 struct bpf_func_state *state; 13582 struct bpf_reg_state *reg; 13583 int new_range; 13584 13585 if (dst_reg->off < 0 || 13586 (dst_reg->off == 0 && range_right_open)) 13587 /* This doesn't give us any range */ 13588 return; 13589 13590 if (dst_reg->umax_value > MAX_PACKET_OFF || 13591 dst_reg->umax_value + dst_reg->off > MAX_PACKET_OFF) 13592 /* Risk of overflow. For instance, ptr + (1<<63) may be less 13593 * than pkt_end, but that's because it's also less than pkt. 13594 */ 13595 return; 13596 13597 new_range = dst_reg->off; 13598 if (range_right_open) 13599 new_range++; 13600 13601 /* Examples for register markings: 13602 * 13603 * pkt_data in dst register: 13604 * 13605 * r2 = r3; 13606 * r2 += 8; 13607 * if (r2 > pkt_end) goto <handle exception> 13608 * <access okay> 13609 * 13610 * r2 = r3; 13611 * r2 += 8; 13612 * if (r2 < pkt_end) goto <access okay> 13613 * <handle exception> 13614 * 13615 * Where: 13616 * r2 == dst_reg, pkt_end == src_reg 13617 * r2=pkt(id=n,off=8,r=0) 13618 * r3=pkt(id=n,off=0,r=0) 13619 * 13620 * pkt_data in src register: 13621 * 13622 * r2 = r3; 13623 * r2 += 8; 13624 * if (pkt_end >= r2) goto <access okay> 13625 * <handle exception> 13626 * 13627 * r2 = r3; 13628 * r2 += 8; 13629 * if (pkt_end <= r2) goto <handle exception> 13630 * <access okay> 13631 * 13632 * Where: 13633 * pkt_end == dst_reg, r2 == src_reg 13634 * r2=pkt(id=n,off=8,r=0) 13635 * r3=pkt(id=n,off=0,r=0) 13636 * 13637 * Find register r3 and mark its range as r3=pkt(id=n,off=0,r=8) 13638 * or r3=pkt(id=n,off=0,r=8-1), so that range of bytes [r3, r3 + 8) 13639 * and [r3, r3 + 8-1) respectively is safe to access depending on 13640 * the check. 13641 */ 13642 13643 /* If our ids match, then we must have the same max_value. And we 13644 * don't care about the other reg's fixed offset, since if it's too big 13645 * the range won't allow anything. 13646 * dst_reg->off is known < MAX_PACKET_OFF, therefore it fits in a u16. 13647 */ 13648 bpf_for_each_reg_in_vstate(vstate, state, reg, ({ 13649 if (reg->type == type && reg->id == dst_reg->id) 13650 /* keep the maximum range already checked */ 13651 reg->range = max(reg->range, new_range); 13652 })); 13653 } 13654 13655 static int is_branch32_taken(struct bpf_reg_state *reg, u32 val, u8 opcode) 13656 { 13657 struct tnum subreg = tnum_subreg(reg->var_off); 13658 s32 sval = (s32)val; 13659 13660 switch (opcode) { 13661 case BPF_JEQ: 13662 if (tnum_is_const(subreg)) 13663 return !!tnum_equals_const(subreg, val); 13664 else if (val < reg->u32_min_value || val > reg->u32_max_value) 13665 return 0; 13666 break; 13667 case BPF_JNE: 13668 if (tnum_is_const(subreg)) 13669 return !tnum_equals_const(subreg, val); 13670 else if (val < reg->u32_min_value || val > reg->u32_max_value) 13671 return 1; 13672 break; 13673 case BPF_JSET: 13674 if ((~subreg.mask & subreg.value) & val) 13675 return 1; 13676 if (!((subreg.mask | subreg.value) & val)) 13677 return 0; 13678 break; 13679 case BPF_JGT: 13680 if (reg->u32_min_value > val) 13681 return 1; 13682 else if (reg->u32_max_value <= val) 13683 return 0; 13684 break; 13685 case BPF_JSGT: 13686 if (reg->s32_min_value > sval) 13687 return 1; 13688 else if (reg->s32_max_value <= sval) 13689 return 0; 13690 break; 13691 case BPF_JLT: 13692 if (reg->u32_max_value < val) 13693 return 1; 13694 else if (reg->u32_min_value >= val) 13695 return 0; 13696 break; 13697 case BPF_JSLT: 13698 if (reg->s32_max_value < sval) 13699 return 1; 13700 else if (reg->s32_min_value >= sval) 13701 return 0; 13702 break; 13703 case BPF_JGE: 13704 if (reg->u32_min_value >= val) 13705 return 1; 13706 else if (reg->u32_max_value < val) 13707 return 0; 13708 break; 13709 case BPF_JSGE: 13710 if (reg->s32_min_value >= sval) 13711 return 1; 13712 else if (reg->s32_max_value < sval) 13713 return 0; 13714 break; 13715 case BPF_JLE: 13716 if (reg->u32_max_value <= val) 13717 return 1; 13718 else if (reg->u32_min_value > val) 13719 return 0; 13720 break; 13721 case BPF_JSLE: 13722 if (reg->s32_max_value <= sval) 13723 return 1; 13724 else if (reg->s32_min_value > sval) 13725 return 0; 13726 break; 13727 } 13728 13729 return -1; 13730 } 13731 13732 13733 static int is_branch64_taken(struct bpf_reg_state *reg, u64 val, u8 opcode) 13734 { 13735 s64 sval = (s64)val; 13736 13737 switch (opcode) { 13738 case BPF_JEQ: 13739 if (tnum_is_const(reg->var_off)) 13740 return !!tnum_equals_const(reg->var_off, val); 13741 else if (val < reg->umin_value || val > reg->umax_value) 13742 return 0; 13743 break; 13744 case BPF_JNE: 13745 if (tnum_is_const(reg->var_off)) 13746 return !tnum_equals_const(reg->var_off, val); 13747 else if (val < reg->umin_value || val > reg->umax_value) 13748 return 1; 13749 break; 13750 case BPF_JSET: 13751 if ((~reg->var_off.mask & reg->var_off.value) & val) 13752 return 1; 13753 if (!((reg->var_off.mask | reg->var_off.value) & val)) 13754 return 0; 13755 break; 13756 case BPF_JGT: 13757 if (reg->umin_value > val) 13758 return 1; 13759 else if (reg->umax_value <= val) 13760 return 0; 13761 break; 13762 case BPF_JSGT: 13763 if (reg->smin_value > sval) 13764 return 1; 13765 else if (reg->smax_value <= sval) 13766 return 0; 13767 break; 13768 case BPF_JLT: 13769 if (reg->umax_value < val) 13770 return 1; 13771 else if (reg->umin_value >= val) 13772 return 0; 13773 break; 13774 case BPF_JSLT: 13775 if (reg->smax_value < sval) 13776 return 1; 13777 else if (reg->smin_value >= sval) 13778 return 0; 13779 break; 13780 case BPF_JGE: 13781 if (reg->umin_value >= val) 13782 return 1; 13783 else if (reg->umax_value < val) 13784 return 0; 13785 break; 13786 case BPF_JSGE: 13787 if (reg->smin_value >= sval) 13788 return 1; 13789 else if (reg->smax_value < sval) 13790 return 0; 13791 break; 13792 case BPF_JLE: 13793 if (reg->umax_value <= val) 13794 return 1; 13795 else if (reg->umin_value > val) 13796 return 0; 13797 break; 13798 case BPF_JSLE: 13799 if (reg->smax_value <= sval) 13800 return 1; 13801 else if (reg->smin_value > sval) 13802 return 0; 13803 break; 13804 } 13805 13806 return -1; 13807 } 13808 13809 /* compute branch direction of the expression "if (reg opcode val) goto target;" 13810 * and return: 13811 * 1 - branch will be taken and "goto target" will be executed 13812 * 0 - branch will not be taken and fall-through to next insn 13813 * -1 - unknown. Example: "if (reg < 5)" is unknown when register value 13814 * range [0,10] 13815 */ 13816 static int is_branch_taken(struct bpf_reg_state *reg, u64 val, u8 opcode, 13817 bool is_jmp32) 13818 { 13819 if (__is_pointer_value(false, reg)) { 13820 if (!reg_not_null(reg)) 13821 return -1; 13822 13823 /* If pointer is valid tests against zero will fail so we can 13824 * use this to direct branch taken. 13825 */ 13826 if (val != 0) 13827 return -1; 13828 13829 switch (opcode) { 13830 case BPF_JEQ: 13831 return 0; 13832 case BPF_JNE: 13833 return 1; 13834 default: 13835 return -1; 13836 } 13837 } 13838 13839 if (is_jmp32) 13840 return is_branch32_taken(reg, val, opcode); 13841 return is_branch64_taken(reg, val, opcode); 13842 } 13843 13844 static int flip_opcode(u32 opcode) 13845 { 13846 /* How can we transform "a <op> b" into "b <op> a"? */ 13847 static const u8 opcode_flip[16] = { 13848 /* these stay the same */ 13849 [BPF_JEQ >> 4] = BPF_JEQ, 13850 [BPF_JNE >> 4] = BPF_JNE, 13851 [BPF_JSET >> 4] = BPF_JSET, 13852 /* these swap "lesser" and "greater" (L and G in the opcodes) */ 13853 [BPF_JGE >> 4] = BPF_JLE, 13854 [BPF_JGT >> 4] = BPF_JLT, 13855 [BPF_JLE >> 4] = BPF_JGE, 13856 [BPF_JLT >> 4] = BPF_JGT, 13857 [BPF_JSGE >> 4] = BPF_JSLE, 13858 [BPF_JSGT >> 4] = BPF_JSLT, 13859 [BPF_JSLE >> 4] = BPF_JSGE, 13860 [BPF_JSLT >> 4] = BPF_JSGT 13861 }; 13862 return opcode_flip[opcode >> 4]; 13863 } 13864 13865 static int is_pkt_ptr_branch_taken(struct bpf_reg_state *dst_reg, 13866 struct bpf_reg_state *src_reg, 13867 u8 opcode) 13868 { 13869 struct bpf_reg_state *pkt; 13870 13871 if (src_reg->type == PTR_TO_PACKET_END) { 13872 pkt = dst_reg; 13873 } else if (dst_reg->type == PTR_TO_PACKET_END) { 13874 pkt = src_reg; 13875 opcode = flip_opcode(opcode); 13876 } else { 13877 return -1; 13878 } 13879 13880 if (pkt->range >= 0) 13881 return -1; 13882 13883 switch (opcode) { 13884 case BPF_JLE: 13885 /* pkt <= pkt_end */ 13886 fallthrough; 13887 case BPF_JGT: 13888 /* pkt > pkt_end */ 13889 if (pkt->range == BEYOND_PKT_END) 13890 /* pkt has at last one extra byte beyond pkt_end */ 13891 return opcode == BPF_JGT; 13892 break; 13893 case BPF_JLT: 13894 /* pkt < pkt_end */ 13895 fallthrough; 13896 case BPF_JGE: 13897 /* pkt >= pkt_end */ 13898 if (pkt->range == BEYOND_PKT_END || pkt->range == AT_PKT_END) 13899 return opcode == BPF_JGE; 13900 break; 13901 } 13902 return -1; 13903 } 13904 13905 /* Adjusts the register min/max values in the case that the dst_reg is the 13906 * variable register that we are working on, and src_reg is a constant or we're 13907 * simply doing a BPF_K check. 13908 * In JEQ/JNE cases we also adjust the var_off values. 13909 */ 13910 static void reg_set_min_max(struct bpf_reg_state *true_reg, 13911 struct bpf_reg_state *false_reg, 13912 u64 val, u32 val32, 13913 u8 opcode, bool is_jmp32) 13914 { 13915 struct tnum false_32off = tnum_subreg(false_reg->var_off); 13916 struct tnum false_64off = false_reg->var_off; 13917 struct tnum true_32off = tnum_subreg(true_reg->var_off); 13918 struct tnum true_64off = true_reg->var_off; 13919 s64 sval = (s64)val; 13920 s32 sval32 = (s32)val32; 13921 13922 /* If the dst_reg is a pointer, we can't learn anything about its 13923 * variable offset from the compare (unless src_reg were a pointer into 13924 * the same object, but we don't bother with that. 13925 * Since false_reg and true_reg have the same type by construction, we 13926 * only need to check one of them for pointerness. 13927 */ 13928 if (__is_pointer_value(false, false_reg)) 13929 return; 13930 13931 switch (opcode) { 13932 /* JEQ/JNE comparison doesn't change the register equivalence. 13933 * 13934 * r1 = r2; 13935 * if (r1 == 42) goto label; 13936 * ... 13937 * label: // here both r1 and r2 are known to be 42. 13938 * 13939 * Hence when marking register as known preserve it's ID. 13940 */ 13941 case BPF_JEQ: 13942 if (is_jmp32) { 13943 __mark_reg32_known(true_reg, val32); 13944 true_32off = tnum_subreg(true_reg->var_off); 13945 } else { 13946 ___mark_reg_known(true_reg, val); 13947 true_64off = true_reg->var_off; 13948 } 13949 break; 13950 case BPF_JNE: 13951 if (is_jmp32) { 13952 __mark_reg32_known(false_reg, val32); 13953 false_32off = tnum_subreg(false_reg->var_off); 13954 } else { 13955 ___mark_reg_known(false_reg, val); 13956 false_64off = false_reg->var_off; 13957 } 13958 break; 13959 case BPF_JSET: 13960 if (is_jmp32) { 13961 false_32off = tnum_and(false_32off, tnum_const(~val32)); 13962 if (is_power_of_2(val32)) 13963 true_32off = tnum_or(true_32off, 13964 tnum_const(val32)); 13965 } else { 13966 false_64off = tnum_and(false_64off, tnum_const(~val)); 13967 if (is_power_of_2(val)) 13968 true_64off = tnum_or(true_64off, 13969 tnum_const(val)); 13970 } 13971 break; 13972 case BPF_JGE: 13973 case BPF_JGT: 13974 { 13975 if (is_jmp32) { 13976 u32 false_umax = opcode == BPF_JGT ? val32 : val32 - 1; 13977 u32 true_umin = opcode == BPF_JGT ? val32 + 1 : val32; 13978 13979 false_reg->u32_max_value = min(false_reg->u32_max_value, 13980 false_umax); 13981 true_reg->u32_min_value = max(true_reg->u32_min_value, 13982 true_umin); 13983 } else { 13984 u64 false_umax = opcode == BPF_JGT ? val : val - 1; 13985 u64 true_umin = opcode == BPF_JGT ? val + 1 : val; 13986 13987 false_reg->umax_value = min(false_reg->umax_value, false_umax); 13988 true_reg->umin_value = max(true_reg->umin_value, true_umin); 13989 } 13990 break; 13991 } 13992 case BPF_JSGE: 13993 case BPF_JSGT: 13994 { 13995 if (is_jmp32) { 13996 s32 false_smax = opcode == BPF_JSGT ? sval32 : sval32 - 1; 13997 s32 true_smin = opcode == BPF_JSGT ? sval32 + 1 : sval32; 13998 13999 false_reg->s32_max_value = min(false_reg->s32_max_value, false_smax); 14000 true_reg->s32_min_value = max(true_reg->s32_min_value, true_smin); 14001 } else { 14002 s64 false_smax = opcode == BPF_JSGT ? sval : sval - 1; 14003 s64 true_smin = opcode == BPF_JSGT ? sval + 1 : sval; 14004 14005 false_reg->smax_value = min(false_reg->smax_value, false_smax); 14006 true_reg->smin_value = max(true_reg->smin_value, true_smin); 14007 } 14008 break; 14009 } 14010 case BPF_JLE: 14011 case BPF_JLT: 14012 { 14013 if (is_jmp32) { 14014 u32 false_umin = opcode == BPF_JLT ? val32 : val32 + 1; 14015 u32 true_umax = opcode == BPF_JLT ? val32 - 1 : val32; 14016 14017 false_reg->u32_min_value = max(false_reg->u32_min_value, 14018 false_umin); 14019 true_reg->u32_max_value = min(true_reg->u32_max_value, 14020 true_umax); 14021 } else { 14022 u64 false_umin = opcode == BPF_JLT ? val : val + 1; 14023 u64 true_umax = opcode == BPF_JLT ? val - 1 : val; 14024 14025 false_reg->umin_value = max(false_reg->umin_value, false_umin); 14026 true_reg->umax_value = min(true_reg->umax_value, true_umax); 14027 } 14028 break; 14029 } 14030 case BPF_JSLE: 14031 case BPF_JSLT: 14032 { 14033 if (is_jmp32) { 14034 s32 false_smin = opcode == BPF_JSLT ? sval32 : sval32 + 1; 14035 s32 true_smax = opcode == BPF_JSLT ? sval32 - 1 : sval32; 14036 14037 false_reg->s32_min_value = max(false_reg->s32_min_value, false_smin); 14038 true_reg->s32_max_value = min(true_reg->s32_max_value, true_smax); 14039 } else { 14040 s64 false_smin = opcode == BPF_JSLT ? sval : sval + 1; 14041 s64 true_smax = opcode == BPF_JSLT ? sval - 1 : sval; 14042 14043 false_reg->smin_value = max(false_reg->smin_value, false_smin); 14044 true_reg->smax_value = min(true_reg->smax_value, true_smax); 14045 } 14046 break; 14047 } 14048 default: 14049 return; 14050 } 14051 14052 if (is_jmp32) { 14053 false_reg->var_off = tnum_or(tnum_clear_subreg(false_64off), 14054 tnum_subreg(false_32off)); 14055 true_reg->var_off = tnum_or(tnum_clear_subreg(true_64off), 14056 tnum_subreg(true_32off)); 14057 __reg_combine_32_into_64(false_reg); 14058 __reg_combine_32_into_64(true_reg); 14059 } else { 14060 false_reg->var_off = false_64off; 14061 true_reg->var_off = true_64off; 14062 __reg_combine_64_into_32(false_reg); 14063 __reg_combine_64_into_32(true_reg); 14064 } 14065 } 14066 14067 /* Same as above, but for the case that dst_reg holds a constant and src_reg is 14068 * the variable reg. 14069 */ 14070 static void reg_set_min_max_inv(struct bpf_reg_state *true_reg, 14071 struct bpf_reg_state *false_reg, 14072 u64 val, u32 val32, 14073 u8 opcode, bool is_jmp32) 14074 { 14075 opcode = flip_opcode(opcode); 14076 /* This uses zero as "not present in table"; luckily the zero opcode, 14077 * BPF_JA, can't get here. 14078 */ 14079 if (opcode) 14080 reg_set_min_max(true_reg, false_reg, val, val32, opcode, is_jmp32); 14081 } 14082 14083 /* Regs are known to be equal, so intersect their min/max/var_off */ 14084 static void __reg_combine_min_max(struct bpf_reg_state *src_reg, 14085 struct bpf_reg_state *dst_reg) 14086 { 14087 src_reg->umin_value = dst_reg->umin_value = max(src_reg->umin_value, 14088 dst_reg->umin_value); 14089 src_reg->umax_value = dst_reg->umax_value = min(src_reg->umax_value, 14090 dst_reg->umax_value); 14091 src_reg->smin_value = dst_reg->smin_value = max(src_reg->smin_value, 14092 dst_reg->smin_value); 14093 src_reg->smax_value = dst_reg->smax_value = min(src_reg->smax_value, 14094 dst_reg->smax_value); 14095 src_reg->var_off = dst_reg->var_off = tnum_intersect(src_reg->var_off, 14096 dst_reg->var_off); 14097 reg_bounds_sync(src_reg); 14098 reg_bounds_sync(dst_reg); 14099 } 14100 14101 static void reg_combine_min_max(struct bpf_reg_state *true_src, 14102 struct bpf_reg_state *true_dst, 14103 struct bpf_reg_state *false_src, 14104 struct bpf_reg_state *false_dst, 14105 u8 opcode) 14106 { 14107 switch (opcode) { 14108 case BPF_JEQ: 14109 __reg_combine_min_max(true_src, true_dst); 14110 break; 14111 case BPF_JNE: 14112 __reg_combine_min_max(false_src, false_dst); 14113 break; 14114 } 14115 } 14116 14117 static void mark_ptr_or_null_reg(struct bpf_func_state *state, 14118 struct bpf_reg_state *reg, u32 id, 14119 bool is_null) 14120 { 14121 if (type_may_be_null(reg->type) && reg->id == id && 14122 (is_rcu_reg(reg) || !WARN_ON_ONCE(!reg->id))) { 14123 /* Old offset (both fixed and variable parts) should have been 14124 * known-zero, because we don't allow pointer arithmetic on 14125 * pointers that might be NULL. If we see this happening, don't 14126 * convert the register. 14127 * 14128 * But in some cases, some helpers that return local kptrs 14129 * advance offset for the returned pointer. In those cases, it 14130 * is fine to expect to see reg->off. 14131 */ 14132 if (WARN_ON_ONCE(reg->smin_value || reg->smax_value || !tnum_equals_const(reg->var_off, 0))) 14133 return; 14134 if (!(type_is_ptr_alloc_obj(reg->type) || type_is_non_owning_ref(reg->type)) && 14135 WARN_ON_ONCE(reg->off)) 14136 return; 14137 14138 if (is_null) { 14139 reg->type = SCALAR_VALUE; 14140 /* We don't need id and ref_obj_id from this point 14141 * onwards anymore, thus we should better reset it, 14142 * so that state pruning has chances to take effect. 14143 */ 14144 reg->id = 0; 14145 reg->ref_obj_id = 0; 14146 14147 return; 14148 } 14149 14150 mark_ptr_not_null_reg(reg); 14151 14152 if (!reg_may_point_to_spin_lock(reg)) { 14153 /* For not-NULL ptr, reg->ref_obj_id will be reset 14154 * in release_reference(). 14155 * 14156 * reg->id is still used by spin_lock ptr. Other 14157 * than spin_lock ptr type, reg->id can be reset. 14158 */ 14159 reg->id = 0; 14160 } 14161 } 14162 } 14163 14164 /* The logic is similar to find_good_pkt_pointers(), both could eventually 14165 * be folded together at some point. 14166 */ 14167 static void mark_ptr_or_null_regs(struct bpf_verifier_state *vstate, u32 regno, 14168 bool is_null) 14169 { 14170 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 14171 struct bpf_reg_state *regs = state->regs, *reg; 14172 u32 ref_obj_id = regs[regno].ref_obj_id; 14173 u32 id = regs[regno].id; 14174 14175 if (ref_obj_id && ref_obj_id == id && is_null) 14176 /* regs[regno] is in the " == NULL" branch. 14177 * No one could have freed the reference state before 14178 * doing the NULL check. 14179 */ 14180 WARN_ON_ONCE(release_reference_state(state, id)); 14181 14182 bpf_for_each_reg_in_vstate(vstate, state, reg, ({ 14183 mark_ptr_or_null_reg(state, reg, id, is_null); 14184 })); 14185 } 14186 14187 static bool try_match_pkt_pointers(const struct bpf_insn *insn, 14188 struct bpf_reg_state *dst_reg, 14189 struct bpf_reg_state *src_reg, 14190 struct bpf_verifier_state *this_branch, 14191 struct bpf_verifier_state *other_branch) 14192 { 14193 if (BPF_SRC(insn->code) != BPF_X) 14194 return false; 14195 14196 /* Pointers are always 64-bit. */ 14197 if (BPF_CLASS(insn->code) == BPF_JMP32) 14198 return false; 14199 14200 switch (BPF_OP(insn->code)) { 14201 case BPF_JGT: 14202 if ((dst_reg->type == PTR_TO_PACKET && 14203 src_reg->type == PTR_TO_PACKET_END) || 14204 (dst_reg->type == PTR_TO_PACKET_META && 14205 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) { 14206 /* pkt_data' > pkt_end, pkt_meta' > pkt_data */ 14207 find_good_pkt_pointers(this_branch, dst_reg, 14208 dst_reg->type, false); 14209 mark_pkt_end(other_branch, insn->dst_reg, true); 14210 } else if ((dst_reg->type == PTR_TO_PACKET_END && 14211 src_reg->type == PTR_TO_PACKET) || 14212 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) && 14213 src_reg->type == PTR_TO_PACKET_META)) { 14214 /* pkt_end > pkt_data', pkt_data > pkt_meta' */ 14215 find_good_pkt_pointers(other_branch, src_reg, 14216 src_reg->type, true); 14217 mark_pkt_end(this_branch, insn->src_reg, false); 14218 } else { 14219 return false; 14220 } 14221 break; 14222 case BPF_JLT: 14223 if ((dst_reg->type == PTR_TO_PACKET && 14224 src_reg->type == PTR_TO_PACKET_END) || 14225 (dst_reg->type == PTR_TO_PACKET_META && 14226 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) { 14227 /* pkt_data' < pkt_end, pkt_meta' < pkt_data */ 14228 find_good_pkt_pointers(other_branch, dst_reg, 14229 dst_reg->type, true); 14230 mark_pkt_end(this_branch, insn->dst_reg, false); 14231 } else if ((dst_reg->type == PTR_TO_PACKET_END && 14232 src_reg->type == PTR_TO_PACKET) || 14233 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) && 14234 src_reg->type == PTR_TO_PACKET_META)) { 14235 /* pkt_end < pkt_data', pkt_data > pkt_meta' */ 14236 find_good_pkt_pointers(this_branch, src_reg, 14237 src_reg->type, false); 14238 mark_pkt_end(other_branch, insn->src_reg, true); 14239 } else { 14240 return false; 14241 } 14242 break; 14243 case BPF_JGE: 14244 if ((dst_reg->type == PTR_TO_PACKET && 14245 src_reg->type == PTR_TO_PACKET_END) || 14246 (dst_reg->type == PTR_TO_PACKET_META && 14247 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) { 14248 /* pkt_data' >= pkt_end, pkt_meta' >= pkt_data */ 14249 find_good_pkt_pointers(this_branch, dst_reg, 14250 dst_reg->type, true); 14251 mark_pkt_end(other_branch, insn->dst_reg, false); 14252 } else if ((dst_reg->type == PTR_TO_PACKET_END && 14253 src_reg->type == PTR_TO_PACKET) || 14254 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) && 14255 src_reg->type == PTR_TO_PACKET_META)) { 14256 /* pkt_end >= pkt_data', pkt_data >= pkt_meta' */ 14257 find_good_pkt_pointers(other_branch, src_reg, 14258 src_reg->type, false); 14259 mark_pkt_end(this_branch, insn->src_reg, true); 14260 } else { 14261 return false; 14262 } 14263 break; 14264 case BPF_JLE: 14265 if ((dst_reg->type == PTR_TO_PACKET && 14266 src_reg->type == PTR_TO_PACKET_END) || 14267 (dst_reg->type == PTR_TO_PACKET_META && 14268 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) { 14269 /* pkt_data' <= pkt_end, pkt_meta' <= pkt_data */ 14270 find_good_pkt_pointers(other_branch, dst_reg, 14271 dst_reg->type, false); 14272 mark_pkt_end(this_branch, insn->dst_reg, true); 14273 } else if ((dst_reg->type == PTR_TO_PACKET_END && 14274 src_reg->type == PTR_TO_PACKET) || 14275 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) && 14276 src_reg->type == PTR_TO_PACKET_META)) { 14277 /* pkt_end <= pkt_data', pkt_data <= pkt_meta' */ 14278 find_good_pkt_pointers(this_branch, src_reg, 14279 src_reg->type, true); 14280 mark_pkt_end(other_branch, insn->src_reg, false); 14281 } else { 14282 return false; 14283 } 14284 break; 14285 default: 14286 return false; 14287 } 14288 14289 return true; 14290 } 14291 14292 static void find_equal_scalars(struct bpf_verifier_state *vstate, 14293 struct bpf_reg_state *known_reg) 14294 { 14295 struct bpf_func_state *state; 14296 struct bpf_reg_state *reg; 14297 14298 bpf_for_each_reg_in_vstate(vstate, state, reg, ({ 14299 if (reg->type == SCALAR_VALUE && reg->id == known_reg->id) 14300 copy_register_state(reg, known_reg); 14301 })); 14302 } 14303 14304 static int check_cond_jmp_op(struct bpf_verifier_env *env, 14305 struct bpf_insn *insn, int *insn_idx) 14306 { 14307 struct bpf_verifier_state *this_branch = env->cur_state; 14308 struct bpf_verifier_state *other_branch; 14309 struct bpf_reg_state *regs = this_branch->frame[this_branch->curframe]->regs; 14310 struct bpf_reg_state *dst_reg, *other_branch_regs, *src_reg = NULL; 14311 struct bpf_reg_state *eq_branch_regs; 14312 u8 opcode = BPF_OP(insn->code); 14313 bool is_jmp32; 14314 int pred = -1; 14315 int err; 14316 14317 /* Only conditional jumps are expected to reach here. */ 14318 if (opcode == BPF_JA || opcode > BPF_JSLE) { 14319 verbose(env, "invalid BPF_JMP/JMP32 opcode %x\n", opcode); 14320 return -EINVAL; 14321 } 14322 14323 /* check src2 operand */ 14324 err = check_reg_arg(env, insn->dst_reg, SRC_OP); 14325 if (err) 14326 return err; 14327 14328 dst_reg = ®s[insn->dst_reg]; 14329 if (BPF_SRC(insn->code) == BPF_X) { 14330 if (insn->imm != 0) { 14331 verbose(env, "BPF_JMP/JMP32 uses reserved fields\n"); 14332 return -EINVAL; 14333 } 14334 14335 /* check src1 operand */ 14336 err = check_reg_arg(env, insn->src_reg, SRC_OP); 14337 if (err) 14338 return err; 14339 14340 src_reg = ®s[insn->src_reg]; 14341 if (!(reg_is_pkt_pointer_any(dst_reg) && reg_is_pkt_pointer_any(src_reg)) && 14342 is_pointer_value(env, insn->src_reg)) { 14343 verbose(env, "R%d pointer comparison prohibited\n", 14344 insn->src_reg); 14345 return -EACCES; 14346 } 14347 } else { 14348 if (insn->src_reg != BPF_REG_0) { 14349 verbose(env, "BPF_JMP/JMP32 uses reserved fields\n"); 14350 return -EINVAL; 14351 } 14352 } 14353 14354 is_jmp32 = BPF_CLASS(insn->code) == BPF_JMP32; 14355 14356 if (BPF_SRC(insn->code) == BPF_K) { 14357 pred = is_branch_taken(dst_reg, insn->imm, opcode, is_jmp32); 14358 } else if (src_reg->type == SCALAR_VALUE && 14359 is_jmp32 && tnum_is_const(tnum_subreg(src_reg->var_off))) { 14360 pred = is_branch_taken(dst_reg, 14361 tnum_subreg(src_reg->var_off).value, 14362 opcode, 14363 is_jmp32); 14364 } else if (src_reg->type == SCALAR_VALUE && 14365 !is_jmp32 && tnum_is_const(src_reg->var_off)) { 14366 pred = is_branch_taken(dst_reg, 14367 src_reg->var_off.value, 14368 opcode, 14369 is_jmp32); 14370 } else if (dst_reg->type == SCALAR_VALUE && 14371 is_jmp32 && tnum_is_const(tnum_subreg(dst_reg->var_off))) { 14372 pred = is_branch_taken(src_reg, 14373 tnum_subreg(dst_reg->var_off).value, 14374 flip_opcode(opcode), 14375 is_jmp32); 14376 } else if (dst_reg->type == SCALAR_VALUE && 14377 !is_jmp32 && tnum_is_const(dst_reg->var_off)) { 14378 pred = is_branch_taken(src_reg, 14379 dst_reg->var_off.value, 14380 flip_opcode(opcode), 14381 is_jmp32); 14382 } else if (reg_is_pkt_pointer_any(dst_reg) && 14383 reg_is_pkt_pointer_any(src_reg) && 14384 !is_jmp32) { 14385 pred = is_pkt_ptr_branch_taken(dst_reg, src_reg, opcode); 14386 } 14387 14388 if (pred >= 0) { 14389 /* If we get here with a dst_reg pointer type it is because 14390 * above is_branch_taken() special cased the 0 comparison. 14391 */ 14392 if (!__is_pointer_value(false, dst_reg)) 14393 err = mark_chain_precision(env, insn->dst_reg); 14394 if (BPF_SRC(insn->code) == BPF_X && !err && 14395 !__is_pointer_value(false, src_reg)) 14396 err = mark_chain_precision(env, insn->src_reg); 14397 if (err) 14398 return err; 14399 } 14400 14401 if (pred == 1) { 14402 /* Only follow the goto, ignore fall-through. If needed, push 14403 * the fall-through branch for simulation under speculative 14404 * execution. 14405 */ 14406 if (!env->bypass_spec_v1 && 14407 !sanitize_speculative_path(env, insn, *insn_idx + 1, 14408 *insn_idx)) 14409 return -EFAULT; 14410 if (env->log.level & BPF_LOG_LEVEL) 14411 print_insn_state(env, this_branch->frame[this_branch->curframe]); 14412 *insn_idx += insn->off; 14413 return 0; 14414 } else if (pred == 0) { 14415 /* Only follow the fall-through branch, since that's where the 14416 * program will go. If needed, push the goto branch for 14417 * simulation under speculative execution. 14418 */ 14419 if (!env->bypass_spec_v1 && 14420 !sanitize_speculative_path(env, insn, 14421 *insn_idx + insn->off + 1, 14422 *insn_idx)) 14423 return -EFAULT; 14424 if (env->log.level & BPF_LOG_LEVEL) 14425 print_insn_state(env, this_branch->frame[this_branch->curframe]); 14426 return 0; 14427 } 14428 14429 other_branch = push_stack(env, *insn_idx + insn->off + 1, *insn_idx, 14430 false); 14431 if (!other_branch) 14432 return -EFAULT; 14433 other_branch_regs = other_branch->frame[other_branch->curframe]->regs; 14434 14435 /* detect if we are comparing against a constant value so we can adjust 14436 * our min/max values for our dst register. 14437 * this is only legit if both are scalars (or pointers to the same 14438 * object, I suppose, see the PTR_MAYBE_NULL related if block below), 14439 * because otherwise the different base pointers mean the offsets aren't 14440 * comparable. 14441 */ 14442 if (BPF_SRC(insn->code) == BPF_X) { 14443 struct bpf_reg_state *src_reg = ®s[insn->src_reg]; 14444 14445 if (dst_reg->type == SCALAR_VALUE && 14446 src_reg->type == SCALAR_VALUE) { 14447 if (tnum_is_const(src_reg->var_off) || 14448 (is_jmp32 && 14449 tnum_is_const(tnum_subreg(src_reg->var_off)))) 14450 reg_set_min_max(&other_branch_regs[insn->dst_reg], 14451 dst_reg, 14452 src_reg->var_off.value, 14453 tnum_subreg(src_reg->var_off).value, 14454 opcode, is_jmp32); 14455 else if (tnum_is_const(dst_reg->var_off) || 14456 (is_jmp32 && 14457 tnum_is_const(tnum_subreg(dst_reg->var_off)))) 14458 reg_set_min_max_inv(&other_branch_regs[insn->src_reg], 14459 src_reg, 14460 dst_reg->var_off.value, 14461 tnum_subreg(dst_reg->var_off).value, 14462 opcode, is_jmp32); 14463 else if (!is_jmp32 && 14464 (opcode == BPF_JEQ || opcode == BPF_JNE)) 14465 /* Comparing for equality, we can combine knowledge */ 14466 reg_combine_min_max(&other_branch_regs[insn->src_reg], 14467 &other_branch_regs[insn->dst_reg], 14468 src_reg, dst_reg, opcode); 14469 if (src_reg->id && 14470 !WARN_ON_ONCE(src_reg->id != other_branch_regs[insn->src_reg].id)) { 14471 find_equal_scalars(this_branch, src_reg); 14472 find_equal_scalars(other_branch, &other_branch_regs[insn->src_reg]); 14473 } 14474 14475 } 14476 } else if (dst_reg->type == SCALAR_VALUE) { 14477 reg_set_min_max(&other_branch_regs[insn->dst_reg], 14478 dst_reg, insn->imm, (u32)insn->imm, 14479 opcode, is_jmp32); 14480 } 14481 14482 if (dst_reg->type == SCALAR_VALUE && dst_reg->id && 14483 !WARN_ON_ONCE(dst_reg->id != other_branch_regs[insn->dst_reg].id)) { 14484 find_equal_scalars(this_branch, dst_reg); 14485 find_equal_scalars(other_branch, &other_branch_regs[insn->dst_reg]); 14486 } 14487 14488 /* if one pointer register is compared to another pointer 14489 * register check if PTR_MAYBE_NULL could be lifted. 14490 * E.g. register A - maybe null 14491 * register B - not null 14492 * for JNE A, B, ... - A is not null in the false branch; 14493 * for JEQ A, B, ... - A is not null in the true branch. 14494 * 14495 * Since PTR_TO_BTF_ID points to a kernel struct that does 14496 * not need to be null checked by the BPF program, i.e., 14497 * could be null even without PTR_MAYBE_NULL marking, so 14498 * only propagate nullness when neither reg is that type. 14499 */ 14500 if (!is_jmp32 && BPF_SRC(insn->code) == BPF_X && 14501 __is_pointer_value(false, src_reg) && __is_pointer_value(false, dst_reg) && 14502 type_may_be_null(src_reg->type) != type_may_be_null(dst_reg->type) && 14503 base_type(src_reg->type) != PTR_TO_BTF_ID && 14504 base_type(dst_reg->type) != PTR_TO_BTF_ID) { 14505 eq_branch_regs = NULL; 14506 switch (opcode) { 14507 case BPF_JEQ: 14508 eq_branch_regs = other_branch_regs; 14509 break; 14510 case BPF_JNE: 14511 eq_branch_regs = regs; 14512 break; 14513 default: 14514 /* do nothing */ 14515 break; 14516 } 14517 if (eq_branch_regs) { 14518 if (type_may_be_null(src_reg->type)) 14519 mark_ptr_not_null_reg(&eq_branch_regs[insn->src_reg]); 14520 else 14521 mark_ptr_not_null_reg(&eq_branch_regs[insn->dst_reg]); 14522 } 14523 } 14524 14525 /* detect if R == 0 where R is returned from bpf_map_lookup_elem(). 14526 * NOTE: these optimizations below are related with pointer comparison 14527 * which will never be JMP32. 14528 */ 14529 if (!is_jmp32 && BPF_SRC(insn->code) == BPF_K && 14530 insn->imm == 0 && (opcode == BPF_JEQ || opcode == BPF_JNE) && 14531 type_may_be_null(dst_reg->type)) { 14532 /* Mark all identical registers in each branch as either 14533 * safe or unknown depending R == 0 or R != 0 conditional. 14534 */ 14535 mark_ptr_or_null_regs(this_branch, insn->dst_reg, 14536 opcode == BPF_JNE); 14537 mark_ptr_or_null_regs(other_branch, insn->dst_reg, 14538 opcode == BPF_JEQ); 14539 } else if (!try_match_pkt_pointers(insn, dst_reg, ®s[insn->src_reg], 14540 this_branch, other_branch) && 14541 is_pointer_value(env, insn->dst_reg)) { 14542 verbose(env, "R%d pointer comparison prohibited\n", 14543 insn->dst_reg); 14544 return -EACCES; 14545 } 14546 if (env->log.level & BPF_LOG_LEVEL) 14547 print_insn_state(env, this_branch->frame[this_branch->curframe]); 14548 return 0; 14549 } 14550 14551 /* verify BPF_LD_IMM64 instruction */ 14552 static int check_ld_imm(struct bpf_verifier_env *env, struct bpf_insn *insn) 14553 { 14554 struct bpf_insn_aux_data *aux = cur_aux(env); 14555 struct bpf_reg_state *regs = cur_regs(env); 14556 struct bpf_reg_state *dst_reg; 14557 struct bpf_map *map; 14558 int err; 14559 14560 if (BPF_SIZE(insn->code) != BPF_DW) { 14561 verbose(env, "invalid BPF_LD_IMM insn\n"); 14562 return -EINVAL; 14563 } 14564 if (insn->off != 0) { 14565 verbose(env, "BPF_LD_IMM64 uses reserved fields\n"); 14566 return -EINVAL; 14567 } 14568 14569 err = check_reg_arg(env, insn->dst_reg, DST_OP); 14570 if (err) 14571 return err; 14572 14573 dst_reg = ®s[insn->dst_reg]; 14574 if (insn->src_reg == 0) { 14575 u64 imm = ((u64)(insn + 1)->imm << 32) | (u32)insn->imm; 14576 14577 dst_reg->type = SCALAR_VALUE; 14578 __mark_reg_known(®s[insn->dst_reg], imm); 14579 return 0; 14580 } 14581 14582 /* All special src_reg cases are listed below. From this point onwards 14583 * we either succeed and assign a corresponding dst_reg->type after 14584 * zeroing the offset, or fail and reject the program. 14585 */ 14586 mark_reg_known_zero(env, regs, insn->dst_reg); 14587 14588 if (insn->src_reg == BPF_PSEUDO_BTF_ID) { 14589 dst_reg->type = aux->btf_var.reg_type; 14590 switch (base_type(dst_reg->type)) { 14591 case PTR_TO_MEM: 14592 dst_reg->mem_size = aux->btf_var.mem_size; 14593 break; 14594 case PTR_TO_BTF_ID: 14595 dst_reg->btf = aux->btf_var.btf; 14596 dst_reg->btf_id = aux->btf_var.btf_id; 14597 break; 14598 default: 14599 verbose(env, "bpf verifier is misconfigured\n"); 14600 return -EFAULT; 14601 } 14602 return 0; 14603 } 14604 14605 if (insn->src_reg == BPF_PSEUDO_FUNC) { 14606 struct bpf_prog_aux *aux = env->prog->aux; 14607 u32 subprogno = find_subprog(env, 14608 env->insn_idx + insn->imm + 1); 14609 14610 if (!aux->func_info) { 14611 verbose(env, "missing btf func_info\n"); 14612 return -EINVAL; 14613 } 14614 if (aux->func_info_aux[subprogno].linkage != BTF_FUNC_STATIC) { 14615 verbose(env, "callback function not static\n"); 14616 return -EINVAL; 14617 } 14618 14619 dst_reg->type = PTR_TO_FUNC; 14620 dst_reg->subprogno = subprogno; 14621 return 0; 14622 } 14623 14624 map = env->used_maps[aux->map_index]; 14625 dst_reg->map_ptr = map; 14626 14627 if (insn->src_reg == BPF_PSEUDO_MAP_VALUE || 14628 insn->src_reg == BPF_PSEUDO_MAP_IDX_VALUE) { 14629 dst_reg->type = PTR_TO_MAP_VALUE; 14630 dst_reg->off = aux->map_off; 14631 WARN_ON_ONCE(map->max_entries != 1); 14632 /* We want reg->id to be same (0) as map_value is not distinct */ 14633 } else if (insn->src_reg == BPF_PSEUDO_MAP_FD || 14634 insn->src_reg == BPF_PSEUDO_MAP_IDX) { 14635 dst_reg->type = CONST_PTR_TO_MAP; 14636 } else { 14637 verbose(env, "bpf verifier is misconfigured\n"); 14638 return -EINVAL; 14639 } 14640 14641 return 0; 14642 } 14643 14644 static bool may_access_skb(enum bpf_prog_type type) 14645 { 14646 switch (type) { 14647 case BPF_PROG_TYPE_SOCKET_FILTER: 14648 case BPF_PROG_TYPE_SCHED_CLS: 14649 case BPF_PROG_TYPE_SCHED_ACT: 14650 return true; 14651 default: 14652 return false; 14653 } 14654 } 14655 14656 /* verify safety of LD_ABS|LD_IND instructions: 14657 * - they can only appear in the programs where ctx == skb 14658 * - since they are wrappers of function calls, they scratch R1-R5 registers, 14659 * preserve R6-R9, and store return value into R0 14660 * 14661 * Implicit input: 14662 * ctx == skb == R6 == CTX 14663 * 14664 * Explicit input: 14665 * SRC == any register 14666 * IMM == 32-bit immediate 14667 * 14668 * Output: 14669 * R0 - 8/16/32-bit skb data converted to cpu endianness 14670 */ 14671 static int check_ld_abs(struct bpf_verifier_env *env, struct bpf_insn *insn) 14672 { 14673 struct bpf_reg_state *regs = cur_regs(env); 14674 static const int ctx_reg = BPF_REG_6; 14675 u8 mode = BPF_MODE(insn->code); 14676 int i, err; 14677 14678 if (!may_access_skb(resolve_prog_type(env->prog))) { 14679 verbose(env, "BPF_LD_[ABS|IND] instructions not allowed for this program type\n"); 14680 return -EINVAL; 14681 } 14682 14683 if (!env->ops->gen_ld_abs) { 14684 verbose(env, "bpf verifier is misconfigured\n"); 14685 return -EINVAL; 14686 } 14687 14688 if (insn->dst_reg != BPF_REG_0 || insn->off != 0 || 14689 BPF_SIZE(insn->code) == BPF_DW || 14690 (mode == BPF_ABS && insn->src_reg != BPF_REG_0)) { 14691 verbose(env, "BPF_LD_[ABS|IND] uses reserved fields\n"); 14692 return -EINVAL; 14693 } 14694 14695 /* check whether implicit source operand (register R6) is readable */ 14696 err = check_reg_arg(env, ctx_reg, SRC_OP); 14697 if (err) 14698 return err; 14699 14700 /* Disallow usage of BPF_LD_[ABS|IND] with reference tracking, as 14701 * gen_ld_abs() may terminate the program at runtime, leading to 14702 * reference leak. 14703 */ 14704 err = check_reference_leak(env, false); 14705 if (err) { 14706 verbose(env, "BPF_LD_[ABS|IND] cannot be mixed with socket references\n"); 14707 return err; 14708 } 14709 14710 if (env->cur_state->active_lock.ptr) { 14711 verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_spin_lock-ed region\n"); 14712 return -EINVAL; 14713 } 14714 14715 if (env->cur_state->active_rcu_lock) { 14716 verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_rcu_read_lock-ed region\n"); 14717 return -EINVAL; 14718 } 14719 14720 if (regs[ctx_reg].type != PTR_TO_CTX) { 14721 verbose(env, 14722 "at the time of BPF_LD_ABS|IND R6 != pointer to skb\n"); 14723 return -EINVAL; 14724 } 14725 14726 if (mode == BPF_IND) { 14727 /* check explicit source operand */ 14728 err = check_reg_arg(env, insn->src_reg, SRC_OP); 14729 if (err) 14730 return err; 14731 } 14732 14733 err = check_ptr_off_reg(env, ®s[ctx_reg], ctx_reg); 14734 if (err < 0) 14735 return err; 14736 14737 /* reset caller saved regs to unreadable */ 14738 for (i = 0; i < CALLER_SAVED_REGS; i++) { 14739 mark_reg_not_init(env, regs, caller_saved[i]); 14740 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK); 14741 } 14742 14743 /* mark destination R0 register as readable, since it contains 14744 * the value fetched from the packet. 14745 * Already marked as written above. 14746 */ 14747 mark_reg_unknown(env, regs, BPF_REG_0); 14748 /* ld_abs load up to 32-bit skb data. */ 14749 regs[BPF_REG_0].subreg_def = env->insn_idx + 1; 14750 return 0; 14751 } 14752 14753 static int check_return_code(struct bpf_verifier_env *env, int regno) 14754 { 14755 struct tnum enforce_attach_type_range = tnum_unknown; 14756 const struct bpf_prog *prog = env->prog; 14757 struct bpf_reg_state *reg; 14758 struct tnum range = tnum_range(0, 1), const_0 = tnum_const(0); 14759 enum bpf_prog_type prog_type = resolve_prog_type(env->prog); 14760 int err; 14761 struct bpf_func_state *frame = env->cur_state->frame[0]; 14762 const bool is_subprog = frame->subprogno; 14763 14764 /* LSM and struct_ops func-ptr's return type could be "void" */ 14765 if (!is_subprog || frame->in_exception_callback_fn) { 14766 switch (prog_type) { 14767 case BPF_PROG_TYPE_LSM: 14768 if (prog->expected_attach_type == BPF_LSM_CGROUP) 14769 /* See below, can be 0 or 0-1 depending on hook. */ 14770 break; 14771 fallthrough; 14772 case BPF_PROG_TYPE_STRUCT_OPS: 14773 if (!prog->aux->attach_func_proto->type) 14774 return 0; 14775 break; 14776 default: 14777 break; 14778 } 14779 } 14780 14781 /* eBPF calling convention is such that R0 is used 14782 * to return the value from eBPF program. 14783 * Make sure that it's readable at this time 14784 * of bpf_exit, which means that program wrote 14785 * something into it earlier 14786 */ 14787 err = check_reg_arg(env, regno, SRC_OP); 14788 if (err) 14789 return err; 14790 14791 if (is_pointer_value(env, regno)) { 14792 verbose(env, "R%d leaks addr as return value\n", regno); 14793 return -EACCES; 14794 } 14795 14796 reg = cur_regs(env) + regno; 14797 14798 if (frame->in_async_callback_fn) { 14799 /* enforce return zero from async callbacks like timer */ 14800 if (reg->type != SCALAR_VALUE) { 14801 verbose(env, "In async callback the register R%d is not a known value (%s)\n", 14802 regno, reg_type_str(env, reg->type)); 14803 return -EINVAL; 14804 } 14805 14806 if (!tnum_in(const_0, reg->var_off)) { 14807 verbose_invalid_scalar(env, reg, &const_0, "async callback", "R0"); 14808 return -EINVAL; 14809 } 14810 return 0; 14811 } 14812 14813 if (is_subprog && !frame->in_exception_callback_fn) { 14814 if (reg->type != SCALAR_VALUE) { 14815 verbose(env, "At subprogram exit the register R%d is not a scalar value (%s)\n", 14816 regno, reg_type_str(env, reg->type)); 14817 return -EINVAL; 14818 } 14819 return 0; 14820 } 14821 14822 switch (prog_type) { 14823 case BPF_PROG_TYPE_CGROUP_SOCK_ADDR: 14824 if (env->prog->expected_attach_type == BPF_CGROUP_UDP4_RECVMSG || 14825 env->prog->expected_attach_type == BPF_CGROUP_UDP6_RECVMSG || 14826 env->prog->expected_attach_type == BPF_CGROUP_UNIX_RECVMSG || 14827 env->prog->expected_attach_type == BPF_CGROUP_INET4_GETPEERNAME || 14828 env->prog->expected_attach_type == BPF_CGROUP_INET6_GETPEERNAME || 14829 env->prog->expected_attach_type == BPF_CGROUP_UNIX_GETPEERNAME || 14830 env->prog->expected_attach_type == BPF_CGROUP_INET4_GETSOCKNAME || 14831 env->prog->expected_attach_type == BPF_CGROUP_INET6_GETSOCKNAME || 14832 env->prog->expected_attach_type == BPF_CGROUP_UNIX_GETSOCKNAME) 14833 range = tnum_range(1, 1); 14834 if (env->prog->expected_attach_type == BPF_CGROUP_INET4_BIND || 14835 env->prog->expected_attach_type == BPF_CGROUP_INET6_BIND) 14836 range = tnum_range(0, 3); 14837 break; 14838 case BPF_PROG_TYPE_CGROUP_SKB: 14839 if (env->prog->expected_attach_type == BPF_CGROUP_INET_EGRESS) { 14840 range = tnum_range(0, 3); 14841 enforce_attach_type_range = tnum_range(2, 3); 14842 } 14843 break; 14844 case BPF_PROG_TYPE_CGROUP_SOCK: 14845 case BPF_PROG_TYPE_SOCK_OPS: 14846 case BPF_PROG_TYPE_CGROUP_DEVICE: 14847 case BPF_PROG_TYPE_CGROUP_SYSCTL: 14848 case BPF_PROG_TYPE_CGROUP_SOCKOPT: 14849 break; 14850 case BPF_PROG_TYPE_RAW_TRACEPOINT: 14851 if (!env->prog->aux->attach_btf_id) 14852 return 0; 14853 range = tnum_const(0); 14854 break; 14855 case BPF_PROG_TYPE_TRACING: 14856 switch (env->prog->expected_attach_type) { 14857 case BPF_TRACE_FENTRY: 14858 case BPF_TRACE_FEXIT: 14859 range = tnum_const(0); 14860 break; 14861 case BPF_TRACE_RAW_TP: 14862 case BPF_MODIFY_RETURN: 14863 return 0; 14864 case BPF_TRACE_ITER: 14865 break; 14866 default: 14867 return -ENOTSUPP; 14868 } 14869 break; 14870 case BPF_PROG_TYPE_SK_LOOKUP: 14871 range = tnum_range(SK_DROP, SK_PASS); 14872 break; 14873 14874 case BPF_PROG_TYPE_LSM: 14875 if (env->prog->expected_attach_type != BPF_LSM_CGROUP) { 14876 /* Regular BPF_PROG_TYPE_LSM programs can return 14877 * any value. 14878 */ 14879 return 0; 14880 } 14881 if (!env->prog->aux->attach_func_proto->type) { 14882 /* Make sure programs that attach to void 14883 * hooks don't try to modify return value. 14884 */ 14885 range = tnum_range(1, 1); 14886 } 14887 break; 14888 14889 case BPF_PROG_TYPE_NETFILTER: 14890 range = tnum_range(NF_DROP, NF_ACCEPT); 14891 break; 14892 case BPF_PROG_TYPE_EXT: 14893 /* freplace program can return anything as its return value 14894 * depends on the to-be-replaced kernel func or bpf program. 14895 */ 14896 default: 14897 return 0; 14898 } 14899 14900 if (reg->type != SCALAR_VALUE) { 14901 verbose(env, "At program exit the register R%d is not a known value (%s)\n", 14902 regno, reg_type_str(env, reg->type)); 14903 return -EINVAL; 14904 } 14905 14906 if (!tnum_in(range, reg->var_off)) { 14907 verbose_invalid_scalar(env, reg, &range, "program exit", "R0"); 14908 if (prog->expected_attach_type == BPF_LSM_CGROUP && 14909 prog_type == BPF_PROG_TYPE_LSM && 14910 !prog->aux->attach_func_proto->type) 14911 verbose(env, "Note, BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n"); 14912 return -EINVAL; 14913 } 14914 14915 if (!tnum_is_unknown(enforce_attach_type_range) && 14916 tnum_in(enforce_attach_type_range, reg->var_off)) 14917 env->prog->enforce_expected_attach_type = 1; 14918 return 0; 14919 } 14920 14921 /* non-recursive DFS pseudo code 14922 * 1 procedure DFS-iterative(G,v): 14923 * 2 label v as discovered 14924 * 3 let S be a stack 14925 * 4 S.push(v) 14926 * 5 while S is not empty 14927 * 6 t <- S.peek() 14928 * 7 if t is what we're looking for: 14929 * 8 return t 14930 * 9 for all edges e in G.adjacentEdges(t) do 14931 * 10 if edge e is already labelled 14932 * 11 continue with the next edge 14933 * 12 w <- G.adjacentVertex(t,e) 14934 * 13 if vertex w is not discovered and not explored 14935 * 14 label e as tree-edge 14936 * 15 label w as discovered 14937 * 16 S.push(w) 14938 * 17 continue at 5 14939 * 18 else if vertex w is discovered 14940 * 19 label e as back-edge 14941 * 20 else 14942 * 21 // vertex w is explored 14943 * 22 label e as forward- or cross-edge 14944 * 23 label t as explored 14945 * 24 S.pop() 14946 * 14947 * convention: 14948 * 0x10 - discovered 14949 * 0x11 - discovered and fall-through edge labelled 14950 * 0x12 - discovered and fall-through and branch edges labelled 14951 * 0x20 - explored 14952 */ 14953 14954 enum { 14955 DISCOVERED = 0x10, 14956 EXPLORED = 0x20, 14957 FALLTHROUGH = 1, 14958 BRANCH = 2, 14959 }; 14960 14961 static u32 state_htab_size(struct bpf_verifier_env *env) 14962 { 14963 return env->prog->len; 14964 } 14965 14966 static struct bpf_verifier_state_list **explored_state( 14967 struct bpf_verifier_env *env, 14968 int idx) 14969 { 14970 struct bpf_verifier_state *cur = env->cur_state; 14971 struct bpf_func_state *state = cur->frame[cur->curframe]; 14972 14973 return &env->explored_states[(idx ^ state->callsite) % state_htab_size(env)]; 14974 } 14975 14976 static void mark_prune_point(struct bpf_verifier_env *env, int idx) 14977 { 14978 env->insn_aux_data[idx].prune_point = true; 14979 } 14980 14981 static bool is_prune_point(struct bpf_verifier_env *env, int insn_idx) 14982 { 14983 return env->insn_aux_data[insn_idx].prune_point; 14984 } 14985 14986 static void mark_force_checkpoint(struct bpf_verifier_env *env, int idx) 14987 { 14988 env->insn_aux_data[idx].force_checkpoint = true; 14989 } 14990 14991 static bool is_force_checkpoint(struct bpf_verifier_env *env, int insn_idx) 14992 { 14993 return env->insn_aux_data[insn_idx].force_checkpoint; 14994 } 14995 14996 14997 enum { 14998 DONE_EXPLORING = 0, 14999 KEEP_EXPLORING = 1, 15000 }; 15001 15002 /* t, w, e - match pseudo-code above: 15003 * t - index of current instruction 15004 * w - next instruction 15005 * e - edge 15006 */ 15007 static int push_insn(int t, int w, int e, struct bpf_verifier_env *env, 15008 bool loop_ok) 15009 { 15010 int *insn_stack = env->cfg.insn_stack; 15011 int *insn_state = env->cfg.insn_state; 15012 15013 if (e == FALLTHROUGH && insn_state[t] >= (DISCOVERED | FALLTHROUGH)) 15014 return DONE_EXPLORING; 15015 15016 if (e == BRANCH && insn_state[t] >= (DISCOVERED | BRANCH)) 15017 return DONE_EXPLORING; 15018 15019 if (w < 0 || w >= env->prog->len) { 15020 verbose_linfo(env, t, "%d: ", t); 15021 verbose(env, "jump out of range from insn %d to %d\n", t, w); 15022 return -EINVAL; 15023 } 15024 15025 if (e == BRANCH) { 15026 /* mark branch target for state pruning */ 15027 mark_prune_point(env, w); 15028 mark_jmp_point(env, w); 15029 } 15030 15031 if (insn_state[w] == 0) { 15032 /* tree-edge */ 15033 insn_state[t] = DISCOVERED | e; 15034 insn_state[w] = DISCOVERED; 15035 if (env->cfg.cur_stack >= env->prog->len) 15036 return -E2BIG; 15037 insn_stack[env->cfg.cur_stack++] = w; 15038 return KEEP_EXPLORING; 15039 } else if ((insn_state[w] & 0xF0) == DISCOVERED) { 15040 if (loop_ok && env->bpf_capable) 15041 return DONE_EXPLORING; 15042 verbose_linfo(env, t, "%d: ", t); 15043 verbose_linfo(env, w, "%d: ", w); 15044 verbose(env, "back-edge from insn %d to %d\n", t, w); 15045 return -EINVAL; 15046 } else if (insn_state[w] == EXPLORED) { 15047 /* forward- or cross-edge */ 15048 insn_state[t] = DISCOVERED | e; 15049 } else { 15050 verbose(env, "insn state internal bug\n"); 15051 return -EFAULT; 15052 } 15053 return DONE_EXPLORING; 15054 } 15055 15056 static int visit_func_call_insn(int t, struct bpf_insn *insns, 15057 struct bpf_verifier_env *env, 15058 bool visit_callee) 15059 { 15060 int ret; 15061 15062 ret = push_insn(t, t + 1, FALLTHROUGH, env, false); 15063 if (ret) 15064 return ret; 15065 15066 mark_prune_point(env, t + 1); 15067 /* when we exit from subprog, we need to record non-linear history */ 15068 mark_jmp_point(env, t + 1); 15069 15070 if (visit_callee) { 15071 mark_prune_point(env, t); 15072 ret = push_insn(t, t + insns[t].imm + 1, BRANCH, env, 15073 /* It's ok to allow recursion from CFG point of 15074 * view. __check_func_call() will do the actual 15075 * check. 15076 */ 15077 bpf_pseudo_func(insns + t)); 15078 } 15079 return ret; 15080 } 15081 15082 /* Visits the instruction at index t and returns one of the following: 15083 * < 0 - an error occurred 15084 * DONE_EXPLORING - the instruction was fully explored 15085 * KEEP_EXPLORING - there is still work to be done before it is fully explored 15086 */ 15087 static int visit_insn(int t, struct bpf_verifier_env *env) 15088 { 15089 struct bpf_insn *insns = env->prog->insnsi, *insn = &insns[t]; 15090 int ret, off; 15091 15092 if (bpf_pseudo_func(insn)) 15093 return visit_func_call_insn(t, insns, env, true); 15094 15095 /* All non-branch instructions have a single fall-through edge. */ 15096 if (BPF_CLASS(insn->code) != BPF_JMP && 15097 BPF_CLASS(insn->code) != BPF_JMP32) 15098 return push_insn(t, t + 1, FALLTHROUGH, env, false); 15099 15100 switch (BPF_OP(insn->code)) { 15101 case BPF_EXIT: 15102 return DONE_EXPLORING; 15103 15104 case BPF_CALL: 15105 if (insn->src_reg == 0 && insn->imm == BPF_FUNC_timer_set_callback) 15106 /* Mark this call insn as a prune point to trigger 15107 * is_state_visited() check before call itself is 15108 * processed by __check_func_call(). Otherwise new 15109 * async state will be pushed for further exploration. 15110 */ 15111 mark_prune_point(env, t); 15112 if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) { 15113 struct bpf_kfunc_call_arg_meta meta; 15114 15115 ret = fetch_kfunc_meta(env, insn, &meta, NULL); 15116 if (ret == 0 && is_iter_next_kfunc(&meta)) { 15117 mark_prune_point(env, t); 15118 /* Checking and saving state checkpoints at iter_next() call 15119 * is crucial for fast convergence of open-coded iterator loop 15120 * logic, so we need to force it. If we don't do that, 15121 * is_state_visited() might skip saving a checkpoint, causing 15122 * unnecessarily long sequence of not checkpointed 15123 * instructions and jumps, leading to exhaustion of jump 15124 * history buffer, and potentially other undesired outcomes. 15125 * It is expected that with correct open-coded iterators 15126 * convergence will happen quickly, so we don't run a risk of 15127 * exhausting memory. 15128 */ 15129 mark_force_checkpoint(env, t); 15130 } 15131 } 15132 return visit_func_call_insn(t, insns, env, insn->src_reg == BPF_PSEUDO_CALL); 15133 15134 case BPF_JA: 15135 if (BPF_SRC(insn->code) != BPF_K) 15136 return -EINVAL; 15137 15138 if (BPF_CLASS(insn->code) == BPF_JMP) 15139 off = insn->off; 15140 else 15141 off = insn->imm; 15142 15143 /* unconditional jump with single edge */ 15144 ret = push_insn(t, t + off + 1, FALLTHROUGH, env, 15145 true); 15146 if (ret) 15147 return ret; 15148 15149 mark_prune_point(env, t + off + 1); 15150 mark_jmp_point(env, t + off + 1); 15151 15152 return ret; 15153 15154 default: 15155 /* conditional jump with two edges */ 15156 mark_prune_point(env, t); 15157 15158 ret = push_insn(t, t + 1, FALLTHROUGH, env, true); 15159 if (ret) 15160 return ret; 15161 15162 return push_insn(t, t + insn->off + 1, BRANCH, env, true); 15163 } 15164 } 15165 15166 /* non-recursive depth-first-search to detect loops in BPF program 15167 * loop == back-edge in directed graph 15168 */ 15169 static int check_cfg(struct bpf_verifier_env *env) 15170 { 15171 int insn_cnt = env->prog->len; 15172 int *insn_stack, *insn_state; 15173 int ex_insn_beg, i, ret = 0; 15174 bool ex_done = false; 15175 15176 insn_state = env->cfg.insn_state = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL); 15177 if (!insn_state) 15178 return -ENOMEM; 15179 15180 insn_stack = env->cfg.insn_stack = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL); 15181 if (!insn_stack) { 15182 kvfree(insn_state); 15183 return -ENOMEM; 15184 } 15185 15186 insn_state[0] = DISCOVERED; /* mark 1st insn as discovered */ 15187 insn_stack[0] = 0; /* 0 is the first instruction */ 15188 env->cfg.cur_stack = 1; 15189 15190 walk_cfg: 15191 while (env->cfg.cur_stack > 0) { 15192 int t = insn_stack[env->cfg.cur_stack - 1]; 15193 15194 ret = visit_insn(t, env); 15195 switch (ret) { 15196 case DONE_EXPLORING: 15197 insn_state[t] = EXPLORED; 15198 env->cfg.cur_stack--; 15199 break; 15200 case KEEP_EXPLORING: 15201 break; 15202 default: 15203 if (ret > 0) { 15204 verbose(env, "visit_insn internal bug\n"); 15205 ret = -EFAULT; 15206 } 15207 goto err_free; 15208 } 15209 } 15210 15211 if (env->cfg.cur_stack < 0) { 15212 verbose(env, "pop stack internal bug\n"); 15213 ret = -EFAULT; 15214 goto err_free; 15215 } 15216 15217 if (env->exception_callback_subprog && !ex_done) { 15218 ex_insn_beg = env->subprog_info[env->exception_callback_subprog].start; 15219 15220 insn_state[ex_insn_beg] = DISCOVERED; 15221 insn_stack[0] = ex_insn_beg; 15222 env->cfg.cur_stack = 1; 15223 ex_done = true; 15224 goto walk_cfg; 15225 } 15226 15227 for (i = 0; i < insn_cnt; i++) { 15228 if (insn_state[i] != EXPLORED) { 15229 verbose(env, "unreachable insn %d\n", i); 15230 ret = -EINVAL; 15231 goto err_free; 15232 } 15233 } 15234 ret = 0; /* cfg looks good */ 15235 15236 err_free: 15237 kvfree(insn_state); 15238 kvfree(insn_stack); 15239 env->cfg.insn_state = env->cfg.insn_stack = NULL; 15240 return ret; 15241 } 15242 15243 static int check_abnormal_return(struct bpf_verifier_env *env) 15244 { 15245 int i; 15246 15247 for (i = 1; i < env->subprog_cnt; i++) { 15248 if (env->subprog_info[i].has_ld_abs) { 15249 verbose(env, "LD_ABS is not allowed in subprogs without BTF\n"); 15250 return -EINVAL; 15251 } 15252 if (env->subprog_info[i].has_tail_call) { 15253 verbose(env, "tail_call is not allowed in subprogs without BTF\n"); 15254 return -EINVAL; 15255 } 15256 } 15257 return 0; 15258 } 15259 15260 /* The minimum supported BTF func info size */ 15261 #define MIN_BPF_FUNCINFO_SIZE 8 15262 #define MAX_FUNCINFO_REC_SIZE 252 15263 15264 static int check_btf_func_early(struct bpf_verifier_env *env, 15265 const union bpf_attr *attr, 15266 bpfptr_t uattr) 15267 { 15268 u32 krec_size = sizeof(struct bpf_func_info); 15269 const struct btf_type *type, *func_proto; 15270 u32 i, nfuncs, urec_size, min_size; 15271 struct bpf_func_info *krecord; 15272 struct bpf_prog *prog; 15273 const struct btf *btf; 15274 u32 prev_offset = 0; 15275 bpfptr_t urecord; 15276 int ret = -ENOMEM; 15277 15278 nfuncs = attr->func_info_cnt; 15279 if (!nfuncs) { 15280 if (check_abnormal_return(env)) 15281 return -EINVAL; 15282 return 0; 15283 } 15284 15285 urec_size = attr->func_info_rec_size; 15286 if (urec_size < MIN_BPF_FUNCINFO_SIZE || 15287 urec_size > MAX_FUNCINFO_REC_SIZE || 15288 urec_size % sizeof(u32)) { 15289 verbose(env, "invalid func info rec size %u\n", urec_size); 15290 return -EINVAL; 15291 } 15292 15293 prog = env->prog; 15294 btf = prog->aux->btf; 15295 15296 urecord = make_bpfptr(attr->func_info, uattr.is_kernel); 15297 min_size = min_t(u32, krec_size, urec_size); 15298 15299 krecord = kvcalloc(nfuncs, krec_size, GFP_KERNEL | __GFP_NOWARN); 15300 if (!krecord) 15301 return -ENOMEM; 15302 15303 for (i = 0; i < nfuncs; i++) { 15304 ret = bpf_check_uarg_tail_zero(urecord, krec_size, urec_size); 15305 if (ret) { 15306 if (ret == -E2BIG) { 15307 verbose(env, "nonzero tailing record in func info"); 15308 /* set the size kernel expects so loader can zero 15309 * out the rest of the record. 15310 */ 15311 if (copy_to_bpfptr_offset(uattr, 15312 offsetof(union bpf_attr, func_info_rec_size), 15313 &min_size, sizeof(min_size))) 15314 ret = -EFAULT; 15315 } 15316 goto err_free; 15317 } 15318 15319 if (copy_from_bpfptr(&krecord[i], urecord, min_size)) { 15320 ret = -EFAULT; 15321 goto err_free; 15322 } 15323 15324 /* check insn_off */ 15325 ret = -EINVAL; 15326 if (i == 0) { 15327 if (krecord[i].insn_off) { 15328 verbose(env, 15329 "nonzero insn_off %u for the first func info record", 15330 krecord[i].insn_off); 15331 goto err_free; 15332 } 15333 } else if (krecord[i].insn_off <= prev_offset) { 15334 verbose(env, 15335 "same or smaller insn offset (%u) than previous func info record (%u)", 15336 krecord[i].insn_off, prev_offset); 15337 goto err_free; 15338 } 15339 15340 /* check type_id */ 15341 type = btf_type_by_id(btf, krecord[i].type_id); 15342 if (!type || !btf_type_is_func(type)) { 15343 verbose(env, "invalid type id %d in func info", 15344 krecord[i].type_id); 15345 goto err_free; 15346 } 15347 15348 func_proto = btf_type_by_id(btf, type->type); 15349 if (unlikely(!func_proto || !btf_type_is_func_proto(func_proto))) 15350 /* btf_func_check() already verified it during BTF load */ 15351 goto err_free; 15352 15353 prev_offset = krecord[i].insn_off; 15354 bpfptr_add(&urecord, urec_size); 15355 } 15356 15357 prog->aux->func_info = krecord; 15358 prog->aux->func_info_cnt = nfuncs; 15359 return 0; 15360 15361 err_free: 15362 kvfree(krecord); 15363 return ret; 15364 } 15365 15366 static int check_btf_func(struct bpf_verifier_env *env, 15367 const union bpf_attr *attr, 15368 bpfptr_t uattr) 15369 { 15370 const struct btf_type *type, *func_proto, *ret_type; 15371 u32 i, nfuncs, urec_size; 15372 struct bpf_func_info *krecord; 15373 struct bpf_func_info_aux *info_aux = NULL; 15374 struct bpf_prog *prog; 15375 const struct btf *btf; 15376 bpfptr_t urecord; 15377 bool scalar_return; 15378 int ret = -ENOMEM; 15379 15380 nfuncs = attr->func_info_cnt; 15381 if (!nfuncs) { 15382 if (check_abnormal_return(env)) 15383 return -EINVAL; 15384 return 0; 15385 } 15386 if (nfuncs != env->subprog_cnt) { 15387 verbose(env, "number of funcs in func_info doesn't match number of subprogs\n"); 15388 return -EINVAL; 15389 } 15390 15391 urec_size = attr->func_info_rec_size; 15392 15393 prog = env->prog; 15394 btf = prog->aux->btf; 15395 15396 urecord = make_bpfptr(attr->func_info, uattr.is_kernel); 15397 15398 krecord = prog->aux->func_info; 15399 info_aux = kcalloc(nfuncs, sizeof(*info_aux), GFP_KERNEL | __GFP_NOWARN); 15400 if (!info_aux) 15401 return -ENOMEM; 15402 15403 for (i = 0; i < nfuncs; i++) { 15404 /* check insn_off */ 15405 ret = -EINVAL; 15406 15407 if (env->subprog_info[i].start != krecord[i].insn_off) { 15408 verbose(env, "func_info BTF section doesn't match subprog layout in BPF program\n"); 15409 goto err_free; 15410 } 15411 15412 /* Already checked type_id */ 15413 type = btf_type_by_id(btf, krecord[i].type_id); 15414 info_aux[i].linkage = BTF_INFO_VLEN(type->info); 15415 /* Already checked func_proto */ 15416 func_proto = btf_type_by_id(btf, type->type); 15417 15418 ret_type = btf_type_skip_modifiers(btf, func_proto->type, NULL); 15419 scalar_return = 15420 btf_type_is_small_int(ret_type) || btf_is_any_enum(ret_type); 15421 if (i && !scalar_return && env->subprog_info[i].has_ld_abs) { 15422 verbose(env, "LD_ABS is only allowed in functions that return 'int'.\n"); 15423 goto err_free; 15424 } 15425 if (i && !scalar_return && env->subprog_info[i].has_tail_call) { 15426 verbose(env, "tail_call is only allowed in functions that return 'int'.\n"); 15427 goto err_free; 15428 } 15429 15430 bpfptr_add(&urecord, urec_size); 15431 } 15432 15433 prog->aux->func_info_aux = info_aux; 15434 return 0; 15435 15436 err_free: 15437 kfree(info_aux); 15438 return ret; 15439 } 15440 15441 static void adjust_btf_func(struct bpf_verifier_env *env) 15442 { 15443 struct bpf_prog_aux *aux = env->prog->aux; 15444 int i; 15445 15446 if (!aux->func_info) 15447 return; 15448 15449 /* func_info is not available for hidden subprogs */ 15450 for (i = 0; i < env->subprog_cnt - env->hidden_subprog_cnt; i++) 15451 aux->func_info[i].insn_off = env->subprog_info[i].start; 15452 } 15453 15454 #define MIN_BPF_LINEINFO_SIZE offsetofend(struct bpf_line_info, line_col) 15455 #define MAX_LINEINFO_REC_SIZE MAX_FUNCINFO_REC_SIZE 15456 15457 static int check_btf_line(struct bpf_verifier_env *env, 15458 const union bpf_attr *attr, 15459 bpfptr_t uattr) 15460 { 15461 u32 i, s, nr_linfo, ncopy, expected_size, rec_size, prev_offset = 0; 15462 struct bpf_subprog_info *sub; 15463 struct bpf_line_info *linfo; 15464 struct bpf_prog *prog; 15465 const struct btf *btf; 15466 bpfptr_t ulinfo; 15467 int err; 15468 15469 nr_linfo = attr->line_info_cnt; 15470 if (!nr_linfo) 15471 return 0; 15472 if (nr_linfo > INT_MAX / sizeof(struct bpf_line_info)) 15473 return -EINVAL; 15474 15475 rec_size = attr->line_info_rec_size; 15476 if (rec_size < MIN_BPF_LINEINFO_SIZE || 15477 rec_size > MAX_LINEINFO_REC_SIZE || 15478 rec_size & (sizeof(u32) - 1)) 15479 return -EINVAL; 15480 15481 /* Need to zero it in case the userspace may 15482 * pass in a smaller bpf_line_info object. 15483 */ 15484 linfo = kvcalloc(nr_linfo, sizeof(struct bpf_line_info), 15485 GFP_KERNEL | __GFP_NOWARN); 15486 if (!linfo) 15487 return -ENOMEM; 15488 15489 prog = env->prog; 15490 btf = prog->aux->btf; 15491 15492 s = 0; 15493 sub = env->subprog_info; 15494 ulinfo = make_bpfptr(attr->line_info, uattr.is_kernel); 15495 expected_size = sizeof(struct bpf_line_info); 15496 ncopy = min_t(u32, expected_size, rec_size); 15497 for (i = 0; i < nr_linfo; i++) { 15498 err = bpf_check_uarg_tail_zero(ulinfo, expected_size, rec_size); 15499 if (err) { 15500 if (err == -E2BIG) { 15501 verbose(env, "nonzero tailing record in line_info"); 15502 if (copy_to_bpfptr_offset(uattr, 15503 offsetof(union bpf_attr, line_info_rec_size), 15504 &expected_size, sizeof(expected_size))) 15505 err = -EFAULT; 15506 } 15507 goto err_free; 15508 } 15509 15510 if (copy_from_bpfptr(&linfo[i], ulinfo, ncopy)) { 15511 err = -EFAULT; 15512 goto err_free; 15513 } 15514 15515 /* 15516 * Check insn_off to ensure 15517 * 1) strictly increasing AND 15518 * 2) bounded by prog->len 15519 * 15520 * The linfo[0].insn_off == 0 check logically falls into 15521 * the later "missing bpf_line_info for func..." case 15522 * because the first linfo[0].insn_off must be the 15523 * first sub also and the first sub must have 15524 * subprog_info[0].start == 0. 15525 */ 15526 if ((i && linfo[i].insn_off <= prev_offset) || 15527 linfo[i].insn_off >= prog->len) { 15528 verbose(env, "Invalid line_info[%u].insn_off:%u (prev_offset:%u prog->len:%u)\n", 15529 i, linfo[i].insn_off, prev_offset, 15530 prog->len); 15531 err = -EINVAL; 15532 goto err_free; 15533 } 15534 15535 if (!prog->insnsi[linfo[i].insn_off].code) { 15536 verbose(env, 15537 "Invalid insn code at line_info[%u].insn_off\n", 15538 i); 15539 err = -EINVAL; 15540 goto err_free; 15541 } 15542 15543 if (!btf_name_by_offset(btf, linfo[i].line_off) || 15544 !btf_name_by_offset(btf, linfo[i].file_name_off)) { 15545 verbose(env, "Invalid line_info[%u].line_off or .file_name_off\n", i); 15546 err = -EINVAL; 15547 goto err_free; 15548 } 15549 15550 if (s != env->subprog_cnt) { 15551 if (linfo[i].insn_off == sub[s].start) { 15552 sub[s].linfo_idx = i; 15553 s++; 15554 } else if (sub[s].start < linfo[i].insn_off) { 15555 verbose(env, "missing bpf_line_info for func#%u\n", s); 15556 err = -EINVAL; 15557 goto err_free; 15558 } 15559 } 15560 15561 prev_offset = linfo[i].insn_off; 15562 bpfptr_add(&ulinfo, rec_size); 15563 } 15564 15565 if (s != env->subprog_cnt) { 15566 verbose(env, "missing bpf_line_info for %u funcs starting from func#%u\n", 15567 env->subprog_cnt - s, s); 15568 err = -EINVAL; 15569 goto err_free; 15570 } 15571 15572 prog->aux->linfo = linfo; 15573 prog->aux->nr_linfo = nr_linfo; 15574 15575 return 0; 15576 15577 err_free: 15578 kvfree(linfo); 15579 return err; 15580 } 15581 15582 #define MIN_CORE_RELO_SIZE sizeof(struct bpf_core_relo) 15583 #define MAX_CORE_RELO_SIZE MAX_FUNCINFO_REC_SIZE 15584 15585 static int check_core_relo(struct bpf_verifier_env *env, 15586 const union bpf_attr *attr, 15587 bpfptr_t uattr) 15588 { 15589 u32 i, nr_core_relo, ncopy, expected_size, rec_size; 15590 struct bpf_core_relo core_relo = {}; 15591 struct bpf_prog *prog = env->prog; 15592 const struct btf *btf = prog->aux->btf; 15593 struct bpf_core_ctx ctx = { 15594 .log = &env->log, 15595 .btf = btf, 15596 }; 15597 bpfptr_t u_core_relo; 15598 int err; 15599 15600 nr_core_relo = attr->core_relo_cnt; 15601 if (!nr_core_relo) 15602 return 0; 15603 if (nr_core_relo > INT_MAX / sizeof(struct bpf_core_relo)) 15604 return -EINVAL; 15605 15606 rec_size = attr->core_relo_rec_size; 15607 if (rec_size < MIN_CORE_RELO_SIZE || 15608 rec_size > MAX_CORE_RELO_SIZE || 15609 rec_size % sizeof(u32)) 15610 return -EINVAL; 15611 15612 u_core_relo = make_bpfptr(attr->core_relos, uattr.is_kernel); 15613 expected_size = sizeof(struct bpf_core_relo); 15614 ncopy = min_t(u32, expected_size, rec_size); 15615 15616 /* Unlike func_info and line_info, copy and apply each CO-RE 15617 * relocation record one at a time. 15618 */ 15619 for (i = 0; i < nr_core_relo; i++) { 15620 /* future proofing when sizeof(bpf_core_relo) changes */ 15621 err = bpf_check_uarg_tail_zero(u_core_relo, expected_size, rec_size); 15622 if (err) { 15623 if (err == -E2BIG) { 15624 verbose(env, "nonzero tailing record in core_relo"); 15625 if (copy_to_bpfptr_offset(uattr, 15626 offsetof(union bpf_attr, core_relo_rec_size), 15627 &expected_size, sizeof(expected_size))) 15628 err = -EFAULT; 15629 } 15630 break; 15631 } 15632 15633 if (copy_from_bpfptr(&core_relo, u_core_relo, ncopy)) { 15634 err = -EFAULT; 15635 break; 15636 } 15637 15638 if (core_relo.insn_off % 8 || core_relo.insn_off / 8 >= prog->len) { 15639 verbose(env, "Invalid core_relo[%u].insn_off:%u prog->len:%u\n", 15640 i, core_relo.insn_off, prog->len); 15641 err = -EINVAL; 15642 break; 15643 } 15644 15645 err = bpf_core_apply(&ctx, &core_relo, i, 15646 &prog->insnsi[core_relo.insn_off / 8]); 15647 if (err) 15648 break; 15649 bpfptr_add(&u_core_relo, rec_size); 15650 } 15651 return err; 15652 } 15653 15654 static int check_btf_info_early(struct bpf_verifier_env *env, 15655 const union bpf_attr *attr, 15656 bpfptr_t uattr) 15657 { 15658 struct btf *btf; 15659 int err; 15660 15661 if (!attr->func_info_cnt && !attr->line_info_cnt) { 15662 if (check_abnormal_return(env)) 15663 return -EINVAL; 15664 return 0; 15665 } 15666 15667 btf = btf_get_by_fd(attr->prog_btf_fd); 15668 if (IS_ERR(btf)) 15669 return PTR_ERR(btf); 15670 if (btf_is_kernel(btf)) { 15671 btf_put(btf); 15672 return -EACCES; 15673 } 15674 env->prog->aux->btf = btf; 15675 15676 err = check_btf_func_early(env, attr, uattr); 15677 if (err) 15678 return err; 15679 return 0; 15680 } 15681 15682 static int check_btf_info(struct bpf_verifier_env *env, 15683 const union bpf_attr *attr, 15684 bpfptr_t uattr) 15685 { 15686 int err; 15687 15688 if (!attr->func_info_cnt && !attr->line_info_cnt) { 15689 if (check_abnormal_return(env)) 15690 return -EINVAL; 15691 return 0; 15692 } 15693 15694 err = check_btf_func(env, attr, uattr); 15695 if (err) 15696 return err; 15697 15698 err = check_btf_line(env, attr, uattr); 15699 if (err) 15700 return err; 15701 15702 err = check_core_relo(env, attr, uattr); 15703 if (err) 15704 return err; 15705 15706 return 0; 15707 } 15708 15709 /* check %cur's range satisfies %old's */ 15710 static bool range_within(struct bpf_reg_state *old, 15711 struct bpf_reg_state *cur) 15712 { 15713 return old->umin_value <= cur->umin_value && 15714 old->umax_value >= cur->umax_value && 15715 old->smin_value <= cur->smin_value && 15716 old->smax_value >= cur->smax_value && 15717 old->u32_min_value <= cur->u32_min_value && 15718 old->u32_max_value >= cur->u32_max_value && 15719 old->s32_min_value <= cur->s32_min_value && 15720 old->s32_max_value >= cur->s32_max_value; 15721 } 15722 15723 /* If in the old state two registers had the same id, then they need to have 15724 * the same id in the new state as well. But that id could be different from 15725 * the old state, so we need to track the mapping from old to new ids. 15726 * Once we have seen that, say, a reg with old id 5 had new id 9, any subsequent 15727 * regs with old id 5 must also have new id 9 for the new state to be safe. But 15728 * regs with a different old id could still have new id 9, we don't care about 15729 * that. 15730 * So we look through our idmap to see if this old id has been seen before. If 15731 * so, we require the new id to match; otherwise, we add the id pair to the map. 15732 */ 15733 static bool check_ids(u32 old_id, u32 cur_id, struct bpf_idmap *idmap) 15734 { 15735 struct bpf_id_pair *map = idmap->map; 15736 unsigned int i; 15737 15738 /* either both IDs should be set or both should be zero */ 15739 if (!!old_id != !!cur_id) 15740 return false; 15741 15742 if (old_id == 0) /* cur_id == 0 as well */ 15743 return true; 15744 15745 for (i = 0; i < BPF_ID_MAP_SIZE; i++) { 15746 if (!map[i].old) { 15747 /* Reached an empty slot; haven't seen this id before */ 15748 map[i].old = old_id; 15749 map[i].cur = cur_id; 15750 return true; 15751 } 15752 if (map[i].old == old_id) 15753 return map[i].cur == cur_id; 15754 if (map[i].cur == cur_id) 15755 return false; 15756 } 15757 /* We ran out of idmap slots, which should be impossible */ 15758 WARN_ON_ONCE(1); 15759 return false; 15760 } 15761 15762 /* Similar to check_ids(), but allocate a unique temporary ID 15763 * for 'old_id' or 'cur_id' of zero. 15764 * This makes pairs like '0 vs unique ID', 'unique ID vs 0' valid. 15765 */ 15766 static bool check_scalar_ids(u32 old_id, u32 cur_id, struct bpf_idmap *idmap) 15767 { 15768 old_id = old_id ? old_id : ++idmap->tmp_id_gen; 15769 cur_id = cur_id ? cur_id : ++idmap->tmp_id_gen; 15770 15771 return check_ids(old_id, cur_id, idmap); 15772 } 15773 15774 static void clean_func_state(struct bpf_verifier_env *env, 15775 struct bpf_func_state *st) 15776 { 15777 enum bpf_reg_liveness live; 15778 int i, j; 15779 15780 for (i = 0; i < BPF_REG_FP; i++) { 15781 live = st->regs[i].live; 15782 /* liveness must not touch this register anymore */ 15783 st->regs[i].live |= REG_LIVE_DONE; 15784 if (!(live & REG_LIVE_READ)) 15785 /* since the register is unused, clear its state 15786 * to make further comparison simpler 15787 */ 15788 __mark_reg_not_init(env, &st->regs[i]); 15789 } 15790 15791 for (i = 0; i < st->allocated_stack / BPF_REG_SIZE; i++) { 15792 live = st->stack[i].spilled_ptr.live; 15793 /* liveness must not touch this stack slot anymore */ 15794 st->stack[i].spilled_ptr.live |= REG_LIVE_DONE; 15795 if (!(live & REG_LIVE_READ)) { 15796 __mark_reg_not_init(env, &st->stack[i].spilled_ptr); 15797 for (j = 0; j < BPF_REG_SIZE; j++) 15798 st->stack[i].slot_type[j] = STACK_INVALID; 15799 } 15800 } 15801 } 15802 15803 static void clean_verifier_state(struct bpf_verifier_env *env, 15804 struct bpf_verifier_state *st) 15805 { 15806 int i; 15807 15808 if (st->frame[0]->regs[0].live & REG_LIVE_DONE) 15809 /* all regs in this state in all frames were already marked */ 15810 return; 15811 15812 for (i = 0; i <= st->curframe; i++) 15813 clean_func_state(env, st->frame[i]); 15814 } 15815 15816 /* the parentage chains form a tree. 15817 * the verifier states are added to state lists at given insn and 15818 * pushed into state stack for future exploration. 15819 * when the verifier reaches bpf_exit insn some of the verifer states 15820 * stored in the state lists have their final liveness state already, 15821 * but a lot of states will get revised from liveness point of view when 15822 * the verifier explores other branches. 15823 * Example: 15824 * 1: r0 = 1 15825 * 2: if r1 == 100 goto pc+1 15826 * 3: r0 = 2 15827 * 4: exit 15828 * when the verifier reaches exit insn the register r0 in the state list of 15829 * insn 2 will be seen as !REG_LIVE_READ. Then the verifier pops the other_branch 15830 * of insn 2 and goes exploring further. At the insn 4 it will walk the 15831 * parentage chain from insn 4 into insn 2 and will mark r0 as REG_LIVE_READ. 15832 * 15833 * Since the verifier pushes the branch states as it sees them while exploring 15834 * the program the condition of walking the branch instruction for the second 15835 * time means that all states below this branch were already explored and 15836 * their final liveness marks are already propagated. 15837 * Hence when the verifier completes the search of state list in is_state_visited() 15838 * we can call this clean_live_states() function to mark all liveness states 15839 * as REG_LIVE_DONE to indicate that 'parent' pointers of 'struct bpf_reg_state' 15840 * will not be used. 15841 * This function also clears the registers and stack for states that !READ 15842 * to simplify state merging. 15843 * 15844 * Important note here that walking the same branch instruction in the callee 15845 * doesn't meant that the states are DONE. The verifier has to compare 15846 * the callsites 15847 */ 15848 static void clean_live_states(struct bpf_verifier_env *env, int insn, 15849 struct bpf_verifier_state *cur) 15850 { 15851 struct bpf_verifier_state_list *sl; 15852 int i; 15853 15854 sl = *explored_state(env, insn); 15855 while (sl) { 15856 if (sl->state.branches) 15857 goto next; 15858 if (sl->state.insn_idx != insn || 15859 sl->state.curframe != cur->curframe) 15860 goto next; 15861 for (i = 0; i <= cur->curframe; i++) 15862 if (sl->state.frame[i]->callsite != cur->frame[i]->callsite) 15863 goto next; 15864 clean_verifier_state(env, &sl->state); 15865 next: 15866 sl = sl->next; 15867 } 15868 } 15869 15870 static bool regs_exact(const struct bpf_reg_state *rold, 15871 const struct bpf_reg_state *rcur, 15872 struct bpf_idmap *idmap) 15873 { 15874 return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 && 15875 check_ids(rold->id, rcur->id, idmap) && 15876 check_ids(rold->ref_obj_id, rcur->ref_obj_id, idmap); 15877 } 15878 15879 /* Returns true if (rold safe implies rcur safe) */ 15880 static bool regsafe(struct bpf_verifier_env *env, struct bpf_reg_state *rold, 15881 struct bpf_reg_state *rcur, struct bpf_idmap *idmap) 15882 { 15883 if (!(rold->live & REG_LIVE_READ)) 15884 /* explored state didn't use this */ 15885 return true; 15886 if (rold->type == NOT_INIT) 15887 /* explored state can't have used this */ 15888 return true; 15889 if (rcur->type == NOT_INIT) 15890 return false; 15891 15892 /* Enforce that register types have to match exactly, including their 15893 * modifiers (like PTR_MAYBE_NULL, MEM_RDONLY, etc), as a general 15894 * rule. 15895 * 15896 * One can make a point that using a pointer register as unbounded 15897 * SCALAR would be technically acceptable, but this could lead to 15898 * pointer leaks because scalars are allowed to leak while pointers 15899 * are not. We could make this safe in special cases if root is 15900 * calling us, but it's probably not worth the hassle. 15901 * 15902 * Also, register types that are *not* MAYBE_NULL could technically be 15903 * safe to use as their MAYBE_NULL variants (e.g., PTR_TO_MAP_VALUE 15904 * is safe to be used as PTR_TO_MAP_VALUE_OR_NULL, provided both point 15905 * to the same map). 15906 * However, if the old MAYBE_NULL register then got NULL checked, 15907 * doing so could have affected others with the same id, and we can't 15908 * check for that because we lost the id when we converted to 15909 * a non-MAYBE_NULL variant. 15910 * So, as a general rule we don't allow mixing MAYBE_NULL and 15911 * non-MAYBE_NULL registers as well. 15912 */ 15913 if (rold->type != rcur->type) 15914 return false; 15915 15916 switch (base_type(rold->type)) { 15917 case SCALAR_VALUE: 15918 if (env->explore_alu_limits) { 15919 /* explore_alu_limits disables tnum_in() and range_within() 15920 * logic and requires everything to be strict 15921 */ 15922 return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 && 15923 check_scalar_ids(rold->id, rcur->id, idmap); 15924 } 15925 if (!rold->precise) 15926 return true; 15927 /* Why check_ids() for scalar registers? 15928 * 15929 * Consider the following BPF code: 15930 * 1: r6 = ... unbound scalar, ID=a ... 15931 * 2: r7 = ... unbound scalar, ID=b ... 15932 * 3: if (r6 > r7) goto +1 15933 * 4: r6 = r7 15934 * 5: if (r6 > X) goto ... 15935 * 6: ... memory operation using r7 ... 15936 * 15937 * First verification path is [1-6]: 15938 * - at (4) same bpf_reg_state::id (b) would be assigned to r6 and r7; 15939 * - at (5) r6 would be marked <= X, find_equal_scalars() would also mark 15940 * r7 <= X, because r6 and r7 share same id. 15941 * Next verification path is [1-4, 6]. 15942 * 15943 * Instruction (6) would be reached in two states: 15944 * I. r6{.id=b}, r7{.id=b} via path 1-6; 15945 * II. r6{.id=a}, r7{.id=b} via path 1-4, 6. 15946 * 15947 * Use check_ids() to distinguish these states. 15948 * --- 15949 * Also verify that new value satisfies old value range knowledge. 15950 */ 15951 return range_within(rold, rcur) && 15952 tnum_in(rold->var_off, rcur->var_off) && 15953 check_scalar_ids(rold->id, rcur->id, idmap); 15954 case PTR_TO_MAP_KEY: 15955 case PTR_TO_MAP_VALUE: 15956 case PTR_TO_MEM: 15957 case PTR_TO_BUF: 15958 case PTR_TO_TP_BUFFER: 15959 /* If the new min/max/var_off satisfy the old ones and 15960 * everything else matches, we are OK. 15961 */ 15962 return memcmp(rold, rcur, offsetof(struct bpf_reg_state, var_off)) == 0 && 15963 range_within(rold, rcur) && 15964 tnum_in(rold->var_off, rcur->var_off) && 15965 check_ids(rold->id, rcur->id, idmap) && 15966 check_ids(rold->ref_obj_id, rcur->ref_obj_id, idmap); 15967 case PTR_TO_PACKET_META: 15968 case PTR_TO_PACKET: 15969 /* We must have at least as much range as the old ptr 15970 * did, so that any accesses which were safe before are 15971 * still safe. This is true even if old range < old off, 15972 * since someone could have accessed through (ptr - k), or 15973 * even done ptr -= k in a register, to get a safe access. 15974 */ 15975 if (rold->range > rcur->range) 15976 return false; 15977 /* If the offsets don't match, we can't trust our alignment; 15978 * nor can we be sure that we won't fall out of range. 15979 */ 15980 if (rold->off != rcur->off) 15981 return false; 15982 /* id relations must be preserved */ 15983 if (!check_ids(rold->id, rcur->id, idmap)) 15984 return false; 15985 /* new val must satisfy old val knowledge */ 15986 return range_within(rold, rcur) && 15987 tnum_in(rold->var_off, rcur->var_off); 15988 case PTR_TO_STACK: 15989 /* two stack pointers are equal only if they're pointing to 15990 * the same stack frame, since fp-8 in foo != fp-8 in bar 15991 */ 15992 return regs_exact(rold, rcur, idmap) && rold->frameno == rcur->frameno; 15993 default: 15994 return regs_exact(rold, rcur, idmap); 15995 } 15996 } 15997 15998 static bool stacksafe(struct bpf_verifier_env *env, struct bpf_func_state *old, 15999 struct bpf_func_state *cur, struct bpf_idmap *idmap) 16000 { 16001 int i, spi; 16002 16003 /* walk slots of the explored stack and ignore any additional 16004 * slots in the current stack, since explored(safe) state 16005 * didn't use them 16006 */ 16007 for (i = 0; i < old->allocated_stack; i++) { 16008 struct bpf_reg_state *old_reg, *cur_reg; 16009 16010 spi = i / BPF_REG_SIZE; 16011 16012 if (!(old->stack[spi].spilled_ptr.live & REG_LIVE_READ)) { 16013 i += BPF_REG_SIZE - 1; 16014 /* explored state didn't use this */ 16015 continue; 16016 } 16017 16018 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_INVALID) 16019 continue; 16020 16021 if (env->allow_uninit_stack && 16022 old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC) 16023 continue; 16024 16025 /* explored stack has more populated slots than current stack 16026 * and these slots were used 16027 */ 16028 if (i >= cur->allocated_stack) 16029 return false; 16030 16031 /* if old state was safe with misc data in the stack 16032 * it will be safe with zero-initialized stack. 16033 * The opposite is not true 16034 */ 16035 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC && 16036 cur->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_ZERO) 16037 continue; 16038 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] != 16039 cur->stack[spi].slot_type[i % BPF_REG_SIZE]) 16040 /* Ex: old explored (safe) state has STACK_SPILL in 16041 * this stack slot, but current has STACK_MISC -> 16042 * this verifier states are not equivalent, 16043 * return false to continue verification of this path 16044 */ 16045 return false; 16046 if (i % BPF_REG_SIZE != BPF_REG_SIZE - 1) 16047 continue; 16048 /* Both old and cur are having same slot_type */ 16049 switch (old->stack[spi].slot_type[BPF_REG_SIZE - 1]) { 16050 case STACK_SPILL: 16051 /* when explored and current stack slot are both storing 16052 * spilled registers, check that stored pointers types 16053 * are the same as well. 16054 * Ex: explored safe path could have stored 16055 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -8} 16056 * but current path has stored: 16057 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -16} 16058 * such verifier states are not equivalent. 16059 * return false to continue verification of this path 16060 */ 16061 if (!regsafe(env, &old->stack[spi].spilled_ptr, 16062 &cur->stack[spi].spilled_ptr, idmap)) 16063 return false; 16064 break; 16065 case STACK_DYNPTR: 16066 old_reg = &old->stack[spi].spilled_ptr; 16067 cur_reg = &cur->stack[spi].spilled_ptr; 16068 if (old_reg->dynptr.type != cur_reg->dynptr.type || 16069 old_reg->dynptr.first_slot != cur_reg->dynptr.first_slot || 16070 !check_ids(old_reg->ref_obj_id, cur_reg->ref_obj_id, idmap)) 16071 return false; 16072 break; 16073 case STACK_ITER: 16074 old_reg = &old->stack[spi].spilled_ptr; 16075 cur_reg = &cur->stack[spi].spilled_ptr; 16076 /* iter.depth is not compared between states as it 16077 * doesn't matter for correctness and would otherwise 16078 * prevent convergence; we maintain it only to prevent 16079 * infinite loop check triggering, see 16080 * iter_active_depths_differ() 16081 */ 16082 if (old_reg->iter.btf != cur_reg->iter.btf || 16083 old_reg->iter.btf_id != cur_reg->iter.btf_id || 16084 old_reg->iter.state != cur_reg->iter.state || 16085 /* ignore {old_reg,cur_reg}->iter.depth, see above */ 16086 !check_ids(old_reg->ref_obj_id, cur_reg->ref_obj_id, idmap)) 16087 return false; 16088 break; 16089 case STACK_MISC: 16090 case STACK_ZERO: 16091 case STACK_INVALID: 16092 continue; 16093 /* Ensure that new unhandled slot types return false by default */ 16094 default: 16095 return false; 16096 } 16097 } 16098 return true; 16099 } 16100 16101 static bool refsafe(struct bpf_func_state *old, struct bpf_func_state *cur, 16102 struct bpf_idmap *idmap) 16103 { 16104 int i; 16105 16106 if (old->acquired_refs != cur->acquired_refs) 16107 return false; 16108 16109 for (i = 0; i < old->acquired_refs; i++) { 16110 if (!check_ids(old->refs[i].id, cur->refs[i].id, idmap)) 16111 return false; 16112 } 16113 16114 return true; 16115 } 16116 16117 /* compare two verifier states 16118 * 16119 * all states stored in state_list are known to be valid, since 16120 * verifier reached 'bpf_exit' instruction through them 16121 * 16122 * this function is called when verifier exploring different branches of 16123 * execution popped from the state stack. If it sees an old state that has 16124 * more strict register state and more strict stack state then this execution 16125 * branch doesn't need to be explored further, since verifier already 16126 * concluded that more strict state leads to valid finish. 16127 * 16128 * Therefore two states are equivalent if register state is more conservative 16129 * and explored stack state is more conservative than the current one. 16130 * Example: 16131 * explored current 16132 * (slot1=INV slot2=MISC) == (slot1=MISC slot2=MISC) 16133 * (slot1=MISC slot2=MISC) != (slot1=INV slot2=MISC) 16134 * 16135 * In other words if current stack state (one being explored) has more 16136 * valid slots than old one that already passed validation, it means 16137 * the verifier can stop exploring and conclude that current state is valid too 16138 * 16139 * Similarly with registers. If explored state has register type as invalid 16140 * whereas register type in current state is meaningful, it means that 16141 * the current state will reach 'bpf_exit' instruction safely 16142 */ 16143 static bool func_states_equal(struct bpf_verifier_env *env, struct bpf_func_state *old, 16144 struct bpf_func_state *cur) 16145 { 16146 int i; 16147 16148 for (i = 0; i < MAX_BPF_REG; i++) 16149 if (!regsafe(env, &old->regs[i], &cur->regs[i], 16150 &env->idmap_scratch)) 16151 return false; 16152 16153 if (!stacksafe(env, old, cur, &env->idmap_scratch)) 16154 return false; 16155 16156 if (!refsafe(old, cur, &env->idmap_scratch)) 16157 return false; 16158 16159 return true; 16160 } 16161 16162 static bool states_equal(struct bpf_verifier_env *env, 16163 struct bpf_verifier_state *old, 16164 struct bpf_verifier_state *cur) 16165 { 16166 int i; 16167 16168 if (old->curframe != cur->curframe) 16169 return false; 16170 16171 env->idmap_scratch.tmp_id_gen = env->id_gen; 16172 memset(&env->idmap_scratch.map, 0, sizeof(env->idmap_scratch.map)); 16173 16174 /* Verification state from speculative execution simulation 16175 * must never prune a non-speculative execution one. 16176 */ 16177 if (old->speculative && !cur->speculative) 16178 return false; 16179 16180 if (old->active_lock.ptr != cur->active_lock.ptr) 16181 return false; 16182 16183 /* Old and cur active_lock's have to be either both present 16184 * or both absent. 16185 */ 16186 if (!!old->active_lock.id != !!cur->active_lock.id) 16187 return false; 16188 16189 if (old->active_lock.id && 16190 !check_ids(old->active_lock.id, cur->active_lock.id, &env->idmap_scratch)) 16191 return false; 16192 16193 if (old->active_rcu_lock != cur->active_rcu_lock) 16194 return false; 16195 16196 /* for states to be equal callsites have to be the same 16197 * and all frame states need to be equivalent 16198 */ 16199 for (i = 0; i <= old->curframe; i++) { 16200 if (old->frame[i]->callsite != cur->frame[i]->callsite) 16201 return false; 16202 if (!func_states_equal(env, old->frame[i], cur->frame[i])) 16203 return false; 16204 } 16205 return true; 16206 } 16207 16208 /* Return 0 if no propagation happened. Return negative error code if error 16209 * happened. Otherwise, return the propagated bit. 16210 */ 16211 static int propagate_liveness_reg(struct bpf_verifier_env *env, 16212 struct bpf_reg_state *reg, 16213 struct bpf_reg_state *parent_reg) 16214 { 16215 u8 parent_flag = parent_reg->live & REG_LIVE_READ; 16216 u8 flag = reg->live & REG_LIVE_READ; 16217 int err; 16218 16219 /* When comes here, read flags of PARENT_REG or REG could be any of 16220 * REG_LIVE_READ64, REG_LIVE_READ32, REG_LIVE_NONE. There is no need 16221 * of propagation if PARENT_REG has strongest REG_LIVE_READ64. 16222 */ 16223 if (parent_flag == REG_LIVE_READ64 || 16224 /* Or if there is no read flag from REG. */ 16225 !flag || 16226 /* Or if the read flag from REG is the same as PARENT_REG. */ 16227 parent_flag == flag) 16228 return 0; 16229 16230 err = mark_reg_read(env, reg, parent_reg, flag); 16231 if (err) 16232 return err; 16233 16234 return flag; 16235 } 16236 16237 /* A write screens off any subsequent reads; but write marks come from the 16238 * straight-line code between a state and its parent. When we arrive at an 16239 * equivalent state (jump target or such) we didn't arrive by the straight-line 16240 * code, so read marks in the state must propagate to the parent regardless 16241 * of the state's write marks. That's what 'parent == state->parent' comparison 16242 * in mark_reg_read() is for. 16243 */ 16244 static int propagate_liveness(struct bpf_verifier_env *env, 16245 const struct bpf_verifier_state *vstate, 16246 struct bpf_verifier_state *vparent) 16247 { 16248 struct bpf_reg_state *state_reg, *parent_reg; 16249 struct bpf_func_state *state, *parent; 16250 int i, frame, err = 0; 16251 16252 if (vparent->curframe != vstate->curframe) { 16253 WARN(1, "propagate_live: parent frame %d current frame %d\n", 16254 vparent->curframe, vstate->curframe); 16255 return -EFAULT; 16256 } 16257 /* Propagate read liveness of registers... */ 16258 BUILD_BUG_ON(BPF_REG_FP + 1 != MAX_BPF_REG); 16259 for (frame = 0; frame <= vstate->curframe; frame++) { 16260 parent = vparent->frame[frame]; 16261 state = vstate->frame[frame]; 16262 parent_reg = parent->regs; 16263 state_reg = state->regs; 16264 /* We don't need to worry about FP liveness, it's read-only */ 16265 for (i = frame < vstate->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++) { 16266 err = propagate_liveness_reg(env, &state_reg[i], 16267 &parent_reg[i]); 16268 if (err < 0) 16269 return err; 16270 if (err == REG_LIVE_READ64) 16271 mark_insn_zext(env, &parent_reg[i]); 16272 } 16273 16274 /* Propagate stack slots. */ 16275 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE && 16276 i < parent->allocated_stack / BPF_REG_SIZE; i++) { 16277 parent_reg = &parent->stack[i].spilled_ptr; 16278 state_reg = &state->stack[i].spilled_ptr; 16279 err = propagate_liveness_reg(env, state_reg, 16280 parent_reg); 16281 if (err < 0) 16282 return err; 16283 } 16284 } 16285 return 0; 16286 } 16287 16288 /* find precise scalars in the previous equivalent state and 16289 * propagate them into the current state 16290 */ 16291 static int propagate_precision(struct bpf_verifier_env *env, 16292 const struct bpf_verifier_state *old) 16293 { 16294 struct bpf_reg_state *state_reg; 16295 struct bpf_func_state *state; 16296 int i, err = 0, fr; 16297 bool first; 16298 16299 for (fr = old->curframe; fr >= 0; fr--) { 16300 state = old->frame[fr]; 16301 state_reg = state->regs; 16302 first = true; 16303 for (i = 0; i < BPF_REG_FP; i++, state_reg++) { 16304 if (state_reg->type != SCALAR_VALUE || 16305 !state_reg->precise || 16306 !(state_reg->live & REG_LIVE_READ)) 16307 continue; 16308 if (env->log.level & BPF_LOG_LEVEL2) { 16309 if (first) 16310 verbose(env, "frame %d: propagating r%d", fr, i); 16311 else 16312 verbose(env, ",r%d", i); 16313 } 16314 bt_set_frame_reg(&env->bt, fr, i); 16315 first = false; 16316 } 16317 16318 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) { 16319 if (!is_spilled_reg(&state->stack[i])) 16320 continue; 16321 state_reg = &state->stack[i].spilled_ptr; 16322 if (state_reg->type != SCALAR_VALUE || 16323 !state_reg->precise || 16324 !(state_reg->live & REG_LIVE_READ)) 16325 continue; 16326 if (env->log.level & BPF_LOG_LEVEL2) { 16327 if (first) 16328 verbose(env, "frame %d: propagating fp%d", 16329 fr, (-i - 1) * BPF_REG_SIZE); 16330 else 16331 verbose(env, ",fp%d", (-i - 1) * BPF_REG_SIZE); 16332 } 16333 bt_set_frame_slot(&env->bt, fr, i); 16334 first = false; 16335 } 16336 if (!first) 16337 verbose(env, "\n"); 16338 } 16339 16340 err = mark_chain_precision_batch(env); 16341 if (err < 0) 16342 return err; 16343 16344 return 0; 16345 } 16346 16347 static bool states_maybe_looping(struct bpf_verifier_state *old, 16348 struct bpf_verifier_state *cur) 16349 { 16350 struct bpf_func_state *fold, *fcur; 16351 int i, fr = cur->curframe; 16352 16353 if (old->curframe != fr) 16354 return false; 16355 16356 fold = old->frame[fr]; 16357 fcur = cur->frame[fr]; 16358 for (i = 0; i < MAX_BPF_REG; i++) 16359 if (memcmp(&fold->regs[i], &fcur->regs[i], 16360 offsetof(struct bpf_reg_state, parent))) 16361 return false; 16362 return true; 16363 } 16364 16365 static bool is_iter_next_insn(struct bpf_verifier_env *env, int insn_idx) 16366 { 16367 return env->insn_aux_data[insn_idx].is_iter_next; 16368 } 16369 16370 /* is_state_visited() handles iter_next() (see process_iter_next_call() for 16371 * terminology) calls specially: as opposed to bounded BPF loops, it *expects* 16372 * states to match, which otherwise would look like an infinite loop. So while 16373 * iter_next() calls are taken care of, we still need to be careful and 16374 * prevent erroneous and too eager declaration of "ininite loop", when 16375 * iterators are involved. 16376 * 16377 * Here's a situation in pseudo-BPF assembly form: 16378 * 16379 * 0: again: ; set up iter_next() call args 16380 * 1: r1 = &it ; <CHECKPOINT HERE> 16381 * 2: call bpf_iter_num_next ; this is iter_next() call 16382 * 3: if r0 == 0 goto done 16383 * 4: ... something useful here ... 16384 * 5: goto again ; another iteration 16385 * 6: done: 16386 * 7: r1 = &it 16387 * 8: call bpf_iter_num_destroy ; clean up iter state 16388 * 9: exit 16389 * 16390 * This is a typical loop. Let's assume that we have a prune point at 1:, 16391 * before we get to `call bpf_iter_num_next` (e.g., because of that `goto 16392 * again`, assuming other heuristics don't get in a way). 16393 * 16394 * When we first time come to 1:, let's say we have some state X. We proceed 16395 * to 2:, fork states, enqueue ACTIVE, validate NULL case successfully, exit. 16396 * Now we come back to validate that forked ACTIVE state. We proceed through 16397 * 3-5, come to goto, jump to 1:. Let's assume our state didn't change, so we 16398 * are converging. But the problem is that we don't know that yet, as this 16399 * convergence has to happen at iter_next() call site only. So if nothing is 16400 * done, at 1: verifier will use bounded loop logic and declare infinite 16401 * looping (and would be *technically* correct, if not for iterator's 16402 * "eventual sticky NULL" contract, see process_iter_next_call()). But we 16403 * don't want that. So what we do in process_iter_next_call() when we go on 16404 * another ACTIVE iteration, we bump slot->iter.depth, to mark that it's 16405 * a different iteration. So when we suspect an infinite loop, we additionally 16406 * check if any of the *ACTIVE* iterator states depths differ. If yes, we 16407 * pretend we are not looping and wait for next iter_next() call. 16408 * 16409 * This only applies to ACTIVE state. In DRAINED state we don't expect to 16410 * loop, because that would actually mean infinite loop, as DRAINED state is 16411 * "sticky", and so we'll keep returning into the same instruction with the 16412 * same state (at least in one of possible code paths). 16413 * 16414 * This approach allows to keep infinite loop heuristic even in the face of 16415 * active iterator. E.g., C snippet below is and will be detected as 16416 * inifintely looping: 16417 * 16418 * struct bpf_iter_num it; 16419 * int *p, x; 16420 * 16421 * bpf_iter_num_new(&it, 0, 10); 16422 * while ((p = bpf_iter_num_next(&t))) { 16423 * x = p; 16424 * while (x--) {} // <<-- infinite loop here 16425 * } 16426 * 16427 */ 16428 static bool iter_active_depths_differ(struct bpf_verifier_state *old, struct bpf_verifier_state *cur) 16429 { 16430 struct bpf_reg_state *slot, *cur_slot; 16431 struct bpf_func_state *state; 16432 int i, fr; 16433 16434 for (fr = old->curframe; fr >= 0; fr--) { 16435 state = old->frame[fr]; 16436 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) { 16437 if (state->stack[i].slot_type[0] != STACK_ITER) 16438 continue; 16439 16440 slot = &state->stack[i].spilled_ptr; 16441 if (slot->iter.state != BPF_ITER_STATE_ACTIVE) 16442 continue; 16443 16444 cur_slot = &cur->frame[fr]->stack[i].spilled_ptr; 16445 if (cur_slot->iter.depth != slot->iter.depth) 16446 return true; 16447 } 16448 } 16449 return false; 16450 } 16451 16452 static int is_state_visited(struct bpf_verifier_env *env, int insn_idx) 16453 { 16454 struct bpf_verifier_state_list *new_sl; 16455 struct bpf_verifier_state_list *sl, **pprev; 16456 struct bpf_verifier_state *cur = env->cur_state, *new; 16457 int i, j, err, states_cnt = 0; 16458 bool force_new_state = env->test_state_freq || is_force_checkpoint(env, insn_idx); 16459 bool add_new_state = force_new_state; 16460 16461 /* bpf progs typically have pruning point every 4 instructions 16462 * http://vger.kernel.org/bpfconf2019.html#session-1 16463 * Do not add new state for future pruning if the verifier hasn't seen 16464 * at least 2 jumps and at least 8 instructions. 16465 * This heuristics helps decrease 'total_states' and 'peak_states' metric. 16466 * In tests that amounts to up to 50% reduction into total verifier 16467 * memory consumption and 20% verifier time speedup. 16468 */ 16469 if (env->jmps_processed - env->prev_jmps_processed >= 2 && 16470 env->insn_processed - env->prev_insn_processed >= 8) 16471 add_new_state = true; 16472 16473 pprev = explored_state(env, insn_idx); 16474 sl = *pprev; 16475 16476 clean_live_states(env, insn_idx, cur); 16477 16478 while (sl) { 16479 states_cnt++; 16480 if (sl->state.insn_idx != insn_idx) 16481 goto next; 16482 16483 if (sl->state.branches) { 16484 struct bpf_func_state *frame = sl->state.frame[sl->state.curframe]; 16485 16486 if (frame->in_async_callback_fn && 16487 frame->async_entry_cnt != cur->frame[cur->curframe]->async_entry_cnt) { 16488 /* Different async_entry_cnt means that the verifier is 16489 * processing another entry into async callback. 16490 * Seeing the same state is not an indication of infinite 16491 * loop or infinite recursion. 16492 * But finding the same state doesn't mean that it's safe 16493 * to stop processing the current state. The previous state 16494 * hasn't yet reached bpf_exit, since state.branches > 0. 16495 * Checking in_async_callback_fn alone is not enough either. 16496 * Since the verifier still needs to catch infinite loops 16497 * inside async callbacks. 16498 */ 16499 goto skip_inf_loop_check; 16500 } 16501 /* BPF open-coded iterators loop detection is special. 16502 * states_maybe_looping() logic is too simplistic in detecting 16503 * states that *might* be equivalent, because it doesn't know 16504 * about ID remapping, so don't even perform it. 16505 * See process_iter_next_call() and iter_active_depths_differ() 16506 * for overview of the logic. When current and one of parent 16507 * states are detected as equivalent, it's a good thing: we prove 16508 * convergence and can stop simulating further iterations. 16509 * It's safe to assume that iterator loop will finish, taking into 16510 * account iter_next() contract of eventually returning 16511 * sticky NULL result. 16512 */ 16513 if (is_iter_next_insn(env, insn_idx)) { 16514 if (states_equal(env, &sl->state, cur)) { 16515 struct bpf_func_state *cur_frame; 16516 struct bpf_reg_state *iter_state, *iter_reg; 16517 int spi; 16518 16519 cur_frame = cur->frame[cur->curframe]; 16520 /* btf_check_iter_kfuncs() enforces that 16521 * iter state pointer is always the first arg 16522 */ 16523 iter_reg = &cur_frame->regs[BPF_REG_1]; 16524 /* current state is valid due to states_equal(), 16525 * so we can assume valid iter and reg state, 16526 * no need for extra (re-)validations 16527 */ 16528 spi = __get_spi(iter_reg->off + iter_reg->var_off.value); 16529 iter_state = &func(env, iter_reg)->stack[spi].spilled_ptr; 16530 if (iter_state->iter.state == BPF_ITER_STATE_ACTIVE) 16531 goto hit; 16532 } 16533 goto skip_inf_loop_check; 16534 } 16535 /* attempt to detect infinite loop to avoid unnecessary doomed work */ 16536 if (states_maybe_looping(&sl->state, cur) && 16537 states_equal(env, &sl->state, cur) && 16538 !iter_active_depths_differ(&sl->state, cur)) { 16539 verbose_linfo(env, insn_idx, "; "); 16540 verbose(env, "infinite loop detected at insn %d\n", insn_idx); 16541 return -EINVAL; 16542 } 16543 /* if the verifier is processing a loop, avoid adding new state 16544 * too often, since different loop iterations have distinct 16545 * states and may not help future pruning. 16546 * This threshold shouldn't be too low to make sure that 16547 * a loop with large bound will be rejected quickly. 16548 * The most abusive loop will be: 16549 * r1 += 1 16550 * if r1 < 1000000 goto pc-2 16551 * 1M insn_procssed limit / 100 == 10k peak states. 16552 * This threshold shouldn't be too high either, since states 16553 * at the end of the loop are likely to be useful in pruning. 16554 */ 16555 skip_inf_loop_check: 16556 if (!force_new_state && 16557 env->jmps_processed - env->prev_jmps_processed < 20 && 16558 env->insn_processed - env->prev_insn_processed < 100) 16559 add_new_state = false; 16560 goto miss; 16561 } 16562 if (states_equal(env, &sl->state, cur)) { 16563 hit: 16564 sl->hit_cnt++; 16565 /* reached equivalent register/stack state, 16566 * prune the search. 16567 * Registers read by the continuation are read by us. 16568 * If we have any write marks in env->cur_state, they 16569 * will prevent corresponding reads in the continuation 16570 * from reaching our parent (an explored_state). Our 16571 * own state will get the read marks recorded, but 16572 * they'll be immediately forgotten as we're pruning 16573 * this state and will pop a new one. 16574 */ 16575 err = propagate_liveness(env, &sl->state, cur); 16576 16577 /* if previous state reached the exit with precision and 16578 * current state is equivalent to it (except precsion marks) 16579 * the precision needs to be propagated back in 16580 * the current state. 16581 */ 16582 err = err ? : push_jmp_history(env, cur); 16583 err = err ? : propagate_precision(env, &sl->state); 16584 if (err) 16585 return err; 16586 return 1; 16587 } 16588 miss: 16589 /* when new state is not going to be added do not increase miss count. 16590 * Otherwise several loop iterations will remove the state 16591 * recorded earlier. The goal of these heuristics is to have 16592 * states from some iterations of the loop (some in the beginning 16593 * and some at the end) to help pruning. 16594 */ 16595 if (add_new_state) 16596 sl->miss_cnt++; 16597 /* heuristic to determine whether this state is beneficial 16598 * to keep checking from state equivalence point of view. 16599 * Higher numbers increase max_states_per_insn and verification time, 16600 * but do not meaningfully decrease insn_processed. 16601 */ 16602 if (sl->miss_cnt > sl->hit_cnt * 3 + 3) { 16603 /* the state is unlikely to be useful. Remove it to 16604 * speed up verification 16605 */ 16606 *pprev = sl->next; 16607 if (sl->state.frame[0]->regs[0].live & REG_LIVE_DONE) { 16608 u32 br = sl->state.branches; 16609 16610 WARN_ONCE(br, 16611 "BUG live_done but branches_to_explore %d\n", 16612 br); 16613 free_verifier_state(&sl->state, false); 16614 kfree(sl); 16615 env->peak_states--; 16616 } else { 16617 /* cannot free this state, since parentage chain may 16618 * walk it later. Add it for free_list instead to 16619 * be freed at the end of verification 16620 */ 16621 sl->next = env->free_list; 16622 env->free_list = sl; 16623 } 16624 sl = *pprev; 16625 continue; 16626 } 16627 next: 16628 pprev = &sl->next; 16629 sl = *pprev; 16630 } 16631 16632 if (env->max_states_per_insn < states_cnt) 16633 env->max_states_per_insn = states_cnt; 16634 16635 if (!env->bpf_capable && states_cnt > BPF_COMPLEXITY_LIMIT_STATES) 16636 return 0; 16637 16638 if (!add_new_state) 16639 return 0; 16640 16641 /* There were no equivalent states, remember the current one. 16642 * Technically the current state is not proven to be safe yet, 16643 * but it will either reach outer most bpf_exit (which means it's safe) 16644 * or it will be rejected. When there are no loops the verifier won't be 16645 * seeing this tuple (frame[0].callsite, frame[1].callsite, .. insn_idx) 16646 * again on the way to bpf_exit. 16647 * When looping the sl->state.branches will be > 0 and this state 16648 * will not be considered for equivalence until branches == 0. 16649 */ 16650 new_sl = kzalloc(sizeof(struct bpf_verifier_state_list), GFP_KERNEL); 16651 if (!new_sl) 16652 return -ENOMEM; 16653 env->total_states++; 16654 env->peak_states++; 16655 env->prev_jmps_processed = env->jmps_processed; 16656 env->prev_insn_processed = env->insn_processed; 16657 16658 /* forget precise markings we inherited, see __mark_chain_precision */ 16659 if (env->bpf_capable) 16660 mark_all_scalars_imprecise(env, cur); 16661 16662 /* add new state to the head of linked list */ 16663 new = &new_sl->state; 16664 err = copy_verifier_state(new, cur); 16665 if (err) { 16666 free_verifier_state(new, false); 16667 kfree(new_sl); 16668 return err; 16669 } 16670 new->insn_idx = insn_idx; 16671 WARN_ONCE(new->branches != 1, 16672 "BUG is_state_visited:branches_to_explore=%d insn %d\n", new->branches, insn_idx); 16673 16674 cur->parent = new; 16675 cur->first_insn_idx = insn_idx; 16676 clear_jmp_history(cur); 16677 new_sl->next = *explored_state(env, insn_idx); 16678 *explored_state(env, insn_idx) = new_sl; 16679 /* connect new state to parentage chain. Current frame needs all 16680 * registers connected. Only r6 - r9 of the callers are alive (pushed 16681 * to the stack implicitly by JITs) so in callers' frames connect just 16682 * r6 - r9 as an optimization. Callers will have r1 - r5 connected to 16683 * the state of the call instruction (with WRITTEN set), and r0 comes 16684 * from callee with its full parentage chain, anyway. 16685 */ 16686 /* clear write marks in current state: the writes we did are not writes 16687 * our child did, so they don't screen off its reads from us. 16688 * (There are no read marks in current state, because reads always mark 16689 * their parent and current state never has children yet. Only 16690 * explored_states can get read marks.) 16691 */ 16692 for (j = 0; j <= cur->curframe; j++) { 16693 for (i = j < cur->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++) 16694 cur->frame[j]->regs[i].parent = &new->frame[j]->regs[i]; 16695 for (i = 0; i < BPF_REG_FP; i++) 16696 cur->frame[j]->regs[i].live = REG_LIVE_NONE; 16697 } 16698 16699 /* all stack frames are accessible from callee, clear them all */ 16700 for (j = 0; j <= cur->curframe; j++) { 16701 struct bpf_func_state *frame = cur->frame[j]; 16702 struct bpf_func_state *newframe = new->frame[j]; 16703 16704 for (i = 0; i < frame->allocated_stack / BPF_REG_SIZE; i++) { 16705 frame->stack[i].spilled_ptr.live = REG_LIVE_NONE; 16706 frame->stack[i].spilled_ptr.parent = 16707 &newframe->stack[i].spilled_ptr; 16708 } 16709 } 16710 return 0; 16711 } 16712 16713 /* Return true if it's OK to have the same insn return a different type. */ 16714 static bool reg_type_mismatch_ok(enum bpf_reg_type type) 16715 { 16716 switch (base_type(type)) { 16717 case PTR_TO_CTX: 16718 case PTR_TO_SOCKET: 16719 case PTR_TO_SOCK_COMMON: 16720 case PTR_TO_TCP_SOCK: 16721 case PTR_TO_XDP_SOCK: 16722 case PTR_TO_BTF_ID: 16723 return false; 16724 default: 16725 return true; 16726 } 16727 } 16728 16729 /* If an instruction was previously used with particular pointer types, then we 16730 * need to be careful to avoid cases such as the below, where it may be ok 16731 * for one branch accessing the pointer, but not ok for the other branch: 16732 * 16733 * R1 = sock_ptr 16734 * goto X; 16735 * ... 16736 * R1 = some_other_valid_ptr; 16737 * goto X; 16738 * ... 16739 * R2 = *(u32 *)(R1 + 0); 16740 */ 16741 static bool reg_type_mismatch(enum bpf_reg_type src, enum bpf_reg_type prev) 16742 { 16743 return src != prev && (!reg_type_mismatch_ok(src) || 16744 !reg_type_mismatch_ok(prev)); 16745 } 16746 16747 static int save_aux_ptr_type(struct bpf_verifier_env *env, enum bpf_reg_type type, 16748 bool allow_trust_missmatch) 16749 { 16750 enum bpf_reg_type *prev_type = &env->insn_aux_data[env->insn_idx].ptr_type; 16751 16752 if (*prev_type == NOT_INIT) { 16753 /* Saw a valid insn 16754 * dst_reg = *(u32 *)(src_reg + off) 16755 * save type to validate intersecting paths 16756 */ 16757 *prev_type = type; 16758 } else if (reg_type_mismatch(type, *prev_type)) { 16759 /* Abuser program is trying to use the same insn 16760 * dst_reg = *(u32*) (src_reg + off) 16761 * with different pointer types: 16762 * src_reg == ctx in one branch and 16763 * src_reg == stack|map in some other branch. 16764 * Reject it. 16765 */ 16766 if (allow_trust_missmatch && 16767 base_type(type) == PTR_TO_BTF_ID && 16768 base_type(*prev_type) == PTR_TO_BTF_ID) { 16769 /* 16770 * Have to support a use case when one path through 16771 * the program yields TRUSTED pointer while another 16772 * is UNTRUSTED. Fallback to UNTRUSTED to generate 16773 * BPF_PROBE_MEM/BPF_PROBE_MEMSX. 16774 */ 16775 *prev_type = PTR_TO_BTF_ID | PTR_UNTRUSTED; 16776 } else { 16777 verbose(env, "same insn cannot be used with different pointers\n"); 16778 return -EINVAL; 16779 } 16780 } 16781 16782 return 0; 16783 } 16784 16785 static int do_check(struct bpf_verifier_env *env) 16786 { 16787 bool pop_log = !(env->log.level & BPF_LOG_LEVEL2); 16788 struct bpf_verifier_state *state = env->cur_state; 16789 struct bpf_insn *insns = env->prog->insnsi; 16790 struct bpf_reg_state *regs; 16791 int insn_cnt = env->prog->len; 16792 bool do_print_state = false; 16793 int prev_insn_idx = -1; 16794 16795 for (;;) { 16796 bool exception_exit = false; 16797 struct bpf_insn *insn; 16798 u8 class; 16799 int err; 16800 16801 env->prev_insn_idx = prev_insn_idx; 16802 if (env->insn_idx >= insn_cnt) { 16803 verbose(env, "invalid insn idx %d insn_cnt %d\n", 16804 env->insn_idx, insn_cnt); 16805 return -EFAULT; 16806 } 16807 16808 insn = &insns[env->insn_idx]; 16809 class = BPF_CLASS(insn->code); 16810 16811 if (++env->insn_processed > BPF_COMPLEXITY_LIMIT_INSNS) { 16812 verbose(env, 16813 "BPF program is too large. Processed %d insn\n", 16814 env->insn_processed); 16815 return -E2BIG; 16816 } 16817 16818 state->last_insn_idx = env->prev_insn_idx; 16819 16820 if (is_prune_point(env, env->insn_idx)) { 16821 err = is_state_visited(env, env->insn_idx); 16822 if (err < 0) 16823 return err; 16824 if (err == 1) { 16825 /* found equivalent state, can prune the search */ 16826 if (env->log.level & BPF_LOG_LEVEL) { 16827 if (do_print_state) 16828 verbose(env, "\nfrom %d to %d%s: safe\n", 16829 env->prev_insn_idx, env->insn_idx, 16830 env->cur_state->speculative ? 16831 " (speculative execution)" : ""); 16832 else 16833 verbose(env, "%d: safe\n", env->insn_idx); 16834 } 16835 goto process_bpf_exit; 16836 } 16837 } 16838 16839 if (is_jmp_point(env, env->insn_idx)) { 16840 err = push_jmp_history(env, state); 16841 if (err) 16842 return err; 16843 } 16844 16845 if (signal_pending(current)) 16846 return -EAGAIN; 16847 16848 if (need_resched()) 16849 cond_resched(); 16850 16851 if (env->log.level & BPF_LOG_LEVEL2 && do_print_state) { 16852 verbose(env, "\nfrom %d to %d%s:", 16853 env->prev_insn_idx, env->insn_idx, 16854 env->cur_state->speculative ? 16855 " (speculative execution)" : ""); 16856 print_verifier_state(env, state->frame[state->curframe], true); 16857 do_print_state = false; 16858 } 16859 16860 if (env->log.level & BPF_LOG_LEVEL) { 16861 const struct bpf_insn_cbs cbs = { 16862 .cb_call = disasm_kfunc_name, 16863 .cb_print = verbose, 16864 .private_data = env, 16865 }; 16866 16867 if (verifier_state_scratched(env)) 16868 print_insn_state(env, state->frame[state->curframe]); 16869 16870 verbose_linfo(env, env->insn_idx, "; "); 16871 env->prev_log_pos = env->log.end_pos; 16872 verbose(env, "%d: ", env->insn_idx); 16873 print_bpf_insn(&cbs, insn, env->allow_ptr_leaks); 16874 env->prev_insn_print_pos = env->log.end_pos - env->prev_log_pos; 16875 env->prev_log_pos = env->log.end_pos; 16876 } 16877 16878 if (bpf_prog_is_offloaded(env->prog->aux)) { 16879 err = bpf_prog_offload_verify_insn(env, env->insn_idx, 16880 env->prev_insn_idx); 16881 if (err) 16882 return err; 16883 } 16884 16885 regs = cur_regs(env); 16886 sanitize_mark_insn_seen(env); 16887 prev_insn_idx = env->insn_idx; 16888 16889 if (class == BPF_ALU || class == BPF_ALU64) { 16890 err = check_alu_op(env, insn); 16891 if (err) 16892 return err; 16893 16894 } else if (class == BPF_LDX) { 16895 enum bpf_reg_type src_reg_type; 16896 16897 /* check for reserved fields is already done */ 16898 16899 /* check src operand */ 16900 err = check_reg_arg(env, insn->src_reg, SRC_OP); 16901 if (err) 16902 return err; 16903 16904 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK); 16905 if (err) 16906 return err; 16907 16908 src_reg_type = regs[insn->src_reg].type; 16909 16910 /* check that memory (src_reg + off) is readable, 16911 * the state of dst_reg will be updated by this func 16912 */ 16913 err = check_mem_access(env, env->insn_idx, insn->src_reg, 16914 insn->off, BPF_SIZE(insn->code), 16915 BPF_READ, insn->dst_reg, false, 16916 BPF_MODE(insn->code) == BPF_MEMSX); 16917 if (err) 16918 return err; 16919 16920 err = save_aux_ptr_type(env, src_reg_type, true); 16921 if (err) 16922 return err; 16923 } else if (class == BPF_STX) { 16924 enum bpf_reg_type dst_reg_type; 16925 16926 if (BPF_MODE(insn->code) == BPF_ATOMIC) { 16927 err = check_atomic(env, env->insn_idx, insn); 16928 if (err) 16929 return err; 16930 env->insn_idx++; 16931 continue; 16932 } 16933 16934 if (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0) { 16935 verbose(env, "BPF_STX uses reserved fields\n"); 16936 return -EINVAL; 16937 } 16938 16939 /* check src1 operand */ 16940 err = check_reg_arg(env, insn->src_reg, SRC_OP); 16941 if (err) 16942 return err; 16943 /* check src2 operand */ 16944 err = check_reg_arg(env, insn->dst_reg, SRC_OP); 16945 if (err) 16946 return err; 16947 16948 dst_reg_type = regs[insn->dst_reg].type; 16949 16950 /* check that memory (dst_reg + off) is writeable */ 16951 err = check_mem_access(env, env->insn_idx, insn->dst_reg, 16952 insn->off, BPF_SIZE(insn->code), 16953 BPF_WRITE, insn->src_reg, false, false); 16954 if (err) 16955 return err; 16956 16957 err = save_aux_ptr_type(env, dst_reg_type, false); 16958 if (err) 16959 return err; 16960 } else if (class == BPF_ST) { 16961 enum bpf_reg_type dst_reg_type; 16962 16963 if (BPF_MODE(insn->code) != BPF_MEM || 16964 insn->src_reg != BPF_REG_0) { 16965 verbose(env, "BPF_ST uses reserved fields\n"); 16966 return -EINVAL; 16967 } 16968 /* check src operand */ 16969 err = check_reg_arg(env, insn->dst_reg, SRC_OP); 16970 if (err) 16971 return err; 16972 16973 dst_reg_type = regs[insn->dst_reg].type; 16974 16975 /* check that memory (dst_reg + off) is writeable */ 16976 err = check_mem_access(env, env->insn_idx, insn->dst_reg, 16977 insn->off, BPF_SIZE(insn->code), 16978 BPF_WRITE, -1, false, false); 16979 if (err) 16980 return err; 16981 16982 err = save_aux_ptr_type(env, dst_reg_type, false); 16983 if (err) 16984 return err; 16985 } else if (class == BPF_JMP || class == BPF_JMP32) { 16986 u8 opcode = BPF_OP(insn->code); 16987 16988 env->jmps_processed++; 16989 if (opcode == BPF_CALL) { 16990 if (BPF_SRC(insn->code) != BPF_K || 16991 (insn->src_reg != BPF_PSEUDO_KFUNC_CALL 16992 && insn->off != 0) || 16993 (insn->src_reg != BPF_REG_0 && 16994 insn->src_reg != BPF_PSEUDO_CALL && 16995 insn->src_reg != BPF_PSEUDO_KFUNC_CALL) || 16996 insn->dst_reg != BPF_REG_0 || 16997 class == BPF_JMP32) { 16998 verbose(env, "BPF_CALL uses reserved fields\n"); 16999 return -EINVAL; 17000 } 17001 17002 if (env->cur_state->active_lock.ptr) { 17003 if ((insn->src_reg == BPF_REG_0 && insn->imm != BPF_FUNC_spin_unlock) || 17004 (insn->src_reg == BPF_PSEUDO_CALL) || 17005 (insn->src_reg == BPF_PSEUDO_KFUNC_CALL && 17006 (insn->off != 0 || !is_bpf_graph_api_kfunc(insn->imm)))) { 17007 verbose(env, "function calls are not allowed while holding a lock\n"); 17008 return -EINVAL; 17009 } 17010 } 17011 if (insn->src_reg == BPF_PSEUDO_CALL) { 17012 err = check_func_call(env, insn, &env->insn_idx); 17013 } else if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) { 17014 err = check_kfunc_call(env, insn, &env->insn_idx); 17015 if (!err && is_bpf_throw_kfunc(insn)) { 17016 exception_exit = true; 17017 goto process_bpf_exit_full; 17018 } 17019 } else { 17020 err = check_helper_call(env, insn, &env->insn_idx); 17021 } 17022 if (err) 17023 return err; 17024 17025 mark_reg_scratched(env, BPF_REG_0); 17026 } else if (opcode == BPF_JA) { 17027 if (BPF_SRC(insn->code) != BPF_K || 17028 insn->src_reg != BPF_REG_0 || 17029 insn->dst_reg != BPF_REG_0 || 17030 (class == BPF_JMP && insn->imm != 0) || 17031 (class == BPF_JMP32 && insn->off != 0)) { 17032 verbose(env, "BPF_JA uses reserved fields\n"); 17033 return -EINVAL; 17034 } 17035 17036 if (class == BPF_JMP) 17037 env->insn_idx += insn->off + 1; 17038 else 17039 env->insn_idx += insn->imm + 1; 17040 continue; 17041 17042 } else if (opcode == BPF_EXIT) { 17043 if (BPF_SRC(insn->code) != BPF_K || 17044 insn->imm != 0 || 17045 insn->src_reg != BPF_REG_0 || 17046 insn->dst_reg != BPF_REG_0 || 17047 class == BPF_JMP32) { 17048 verbose(env, "BPF_EXIT uses reserved fields\n"); 17049 return -EINVAL; 17050 } 17051 process_bpf_exit_full: 17052 if (env->cur_state->active_lock.ptr && 17053 !in_rbtree_lock_required_cb(env)) { 17054 verbose(env, "bpf_spin_unlock is missing\n"); 17055 return -EINVAL; 17056 } 17057 17058 if (env->cur_state->active_rcu_lock && 17059 !in_rbtree_lock_required_cb(env)) { 17060 verbose(env, "bpf_rcu_read_unlock is missing\n"); 17061 return -EINVAL; 17062 } 17063 17064 /* We must do check_reference_leak here before 17065 * prepare_func_exit to handle the case when 17066 * state->curframe > 0, it may be a callback 17067 * function, for which reference_state must 17068 * match caller reference state when it exits. 17069 */ 17070 err = check_reference_leak(env, exception_exit); 17071 if (err) 17072 return err; 17073 17074 /* The side effect of the prepare_func_exit 17075 * which is being skipped is that it frees 17076 * bpf_func_state. Typically, process_bpf_exit 17077 * will only be hit with outermost exit. 17078 * copy_verifier_state in pop_stack will handle 17079 * freeing of any extra bpf_func_state left over 17080 * from not processing all nested function 17081 * exits. We also skip return code checks as 17082 * they are not needed for exceptional exits. 17083 */ 17084 if (exception_exit) 17085 goto process_bpf_exit; 17086 17087 if (state->curframe) { 17088 /* exit from nested function */ 17089 err = prepare_func_exit(env, &env->insn_idx); 17090 if (err) 17091 return err; 17092 do_print_state = true; 17093 continue; 17094 } 17095 17096 err = check_return_code(env, BPF_REG_0); 17097 if (err) 17098 return err; 17099 process_bpf_exit: 17100 mark_verifier_state_scratched(env); 17101 update_branch_counts(env, env->cur_state); 17102 err = pop_stack(env, &prev_insn_idx, 17103 &env->insn_idx, pop_log); 17104 if (err < 0) { 17105 if (err != -ENOENT) 17106 return err; 17107 break; 17108 } else { 17109 do_print_state = true; 17110 continue; 17111 } 17112 } else { 17113 err = check_cond_jmp_op(env, insn, &env->insn_idx); 17114 if (err) 17115 return err; 17116 } 17117 } else if (class == BPF_LD) { 17118 u8 mode = BPF_MODE(insn->code); 17119 17120 if (mode == BPF_ABS || mode == BPF_IND) { 17121 err = check_ld_abs(env, insn); 17122 if (err) 17123 return err; 17124 17125 } else if (mode == BPF_IMM) { 17126 err = check_ld_imm(env, insn); 17127 if (err) 17128 return err; 17129 17130 env->insn_idx++; 17131 sanitize_mark_insn_seen(env); 17132 } else { 17133 verbose(env, "invalid BPF_LD mode\n"); 17134 return -EINVAL; 17135 } 17136 } else { 17137 verbose(env, "unknown insn class %d\n", class); 17138 return -EINVAL; 17139 } 17140 17141 env->insn_idx++; 17142 } 17143 17144 return 0; 17145 } 17146 17147 static int find_btf_percpu_datasec(struct btf *btf) 17148 { 17149 const struct btf_type *t; 17150 const char *tname; 17151 int i, n; 17152 17153 /* 17154 * Both vmlinux and module each have their own ".data..percpu" 17155 * DATASECs in BTF. So for module's case, we need to skip vmlinux BTF 17156 * types to look at only module's own BTF types. 17157 */ 17158 n = btf_nr_types(btf); 17159 if (btf_is_module(btf)) 17160 i = btf_nr_types(btf_vmlinux); 17161 else 17162 i = 1; 17163 17164 for(; i < n; i++) { 17165 t = btf_type_by_id(btf, i); 17166 if (BTF_INFO_KIND(t->info) != BTF_KIND_DATASEC) 17167 continue; 17168 17169 tname = btf_name_by_offset(btf, t->name_off); 17170 if (!strcmp(tname, ".data..percpu")) 17171 return i; 17172 } 17173 17174 return -ENOENT; 17175 } 17176 17177 /* replace pseudo btf_id with kernel symbol address */ 17178 static int check_pseudo_btf_id(struct bpf_verifier_env *env, 17179 struct bpf_insn *insn, 17180 struct bpf_insn_aux_data *aux) 17181 { 17182 const struct btf_var_secinfo *vsi; 17183 const struct btf_type *datasec; 17184 struct btf_mod_pair *btf_mod; 17185 const struct btf_type *t; 17186 const char *sym_name; 17187 bool percpu = false; 17188 u32 type, id = insn->imm; 17189 struct btf *btf; 17190 s32 datasec_id; 17191 u64 addr; 17192 int i, btf_fd, err; 17193 17194 btf_fd = insn[1].imm; 17195 if (btf_fd) { 17196 btf = btf_get_by_fd(btf_fd); 17197 if (IS_ERR(btf)) { 17198 verbose(env, "invalid module BTF object FD specified.\n"); 17199 return -EINVAL; 17200 } 17201 } else { 17202 if (!btf_vmlinux) { 17203 verbose(env, "kernel is missing BTF, make sure CONFIG_DEBUG_INFO_BTF=y is specified in Kconfig.\n"); 17204 return -EINVAL; 17205 } 17206 btf = btf_vmlinux; 17207 btf_get(btf); 17208 } 17209 17210 t = btf_type_by_id(btf, id); 17211 if (!t) { 17212 verbose(env, "ldimm64 insn specifies invalid btf_id %d.\n", id); 17213 err = -ENOENT; 17214 goto err_put; 17215 } 17216 17217 if (!btf_type_is_var(t) && !btf_type_is_func(t)) { 17218 verbose(env, "pseudo btf_id %d in ldimm64 isn't KIND_VAR or KIND_FUNC\n", id); 17219 err = -EINVAL; 17220 goto err_put; 17221 } 17222 17223 sym_name = btf_name_by_offset(btf, t->name_off); 17224 addr = kallsyms_lookup_name(sym_name); 17225 if (!addr) { 17226 verbose(env, "ldimm64 failed to find the address for kernel symbol '%s'.\n", 17227 sym_name); 17228 err = -ENOENT; 17229 goto err_put; 17230 } 17231 insn[0].imm = (u32)addr; 17232 insn[1].imm = addr >> 32; 17233 17234 if (btf_type_is_func(t)) { 17235 aux->btf_var.reg_type = PTR_TO_MEM | MEM_RDONLY; 17236 aux->btf_var.mem_size = 0; 17237 goto check_btf; 17238 } 17239 17240 datasec_id = find_btf_percpu_datasec(btf); 17241 if (datasec_id > 0) { 17242 datasec = btf_type_by_id(btf, datasec_id); 17243 for_each_vsi(i, datasec, vsi) { 17244 if (vsi->type == id) { 17245 percpu = true; 17246 break; 17247 } 17248 } 17249 } 17250 17251 type = t->type; 17252 t = btf_type_skip_modifiers(btf, type, NULL); 17253 if (percpu) { 17254 aux->btf_var.reg_type = PTR_TO_BTF_ID | MEM_PERCPU; 17255 aux->btf_var.btf = btf; 17256 aux->btf_var.btf_id = type; 17257 } else if (!btf_type_is_struct(t)) { 17258 const struct btf_type *ret; 17259 const char *tname; 17260 u32 tsize; 17261 17262 /* resolve the type size of ksym. */ 17263 ret = btf_resolve_size(btf, t, &tsize); 17264 if (IS_ERR(ret)) { 17265 tname = btf_name_by_offset(btf, t->name_off); 17266 verbose(env, "ldimm64 unable to resolve the size of type '%s': %ld\n", 17267 tname, PTR_ERR(ret)); 17268 err = -EINVAL; 17269 goto err_put; 17270 } 17271 aux->btf_var.reg_type = PTR_TO_MEM | MEM_RDONLY; 17272 aux->btf_var.mem_size = tsize; 17273 } else { 17274 aux->btf_var.reg_type = PTR_TO_BTF_ID; 17275 aux->btf_var.btf = btf; 17276 aux->btf_var.btf_id = type; 17277 } 17278 check_btf: 17279 /* check whether we recorded this BTF (and maybe module) already */ 17280 for (i = 0; i < env->used_btf_cnt; i++) { 17281 if (env->used_btfs[i].btf == btf) { 17282 btf_put(btf); 17283 return 0; 17284 } 17285 } 17286 17287 if (env->used_btf_cnt >= MAX_USED_BTFS) { 17288 err = -E2BIG; 17289 goto err_put; 17290 } 17291 17292 btf_mod = &env->used_btfs[env->used_btf_cnt]; 17293 btf_mod->btf = btf; 17294 btf_mod->module = NULL; 17295 17296 /* if we reference variables from kernel module, bump its refcount */ 17297 if (btf_is_module(btf)) { 17298 btf_mod->module = btf_try_get_module(btf); 17299 if (!btf_mod->module) { 17300 err = -ENXIO; 17301 goto err_put; 17302 } 17303 } 17304 17305 env->used_btf_cnt++; 17306 17307 return 0; 17308 err_put: 17309 btf_put(btf); 17310 return err; 17311 } 17312 17313 static bool is_tracing_prog_type(enum bpf_prog_type type) 17314 { 17315 switch (type) { 17316 case BPF_PROG_TYPE_KPROBE: 17317 case BPF_PROG_TYPE_TRACEPOINT: 17318 case BPF_PROG_TYPE_PERF_EVENT: 17319 case BPF_PROG_TYPE_RAW_TRACEPOINT: 17320 case BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE: 17321 return true; 17322 default: 17323 return false; 17324 } 17325 } 17326 17327 static int check_map_prog_compatibility(struct bpf_verifier_env *env, 17328 struct bpf_map *map, 17329 struct bpf_prog *prog) 17330 17331 { 17332 enum bpf_prog_type prog_type = resolve_prog_type(prog); 17333 17334 if (btf_record_has_field(map->record, BPF_LIST_HEAD) || 17335 btf_record_has_field(map->record, BPF_RB_ROOT)) { 17336 if (is_tracing_prog_type(prog_type)) { 17337 verbose(env, "tracing progs cannot use bpf_{list_head,rb_root} yet\n"); 17338 return -EINVAL; 17339 } 17340 } 17341 17342 if (btf_record_has_field(map->record, BPF_SPIN_LOCK)) { 17343 if (prog_type == BPF_PROG_TYPE_SOCKET_FILTER) { 17344 verbose(env, "socket filter progs cannot use bpf_spin_lock yet\n"); 17345 return -EINVAL; 17346 } 17347 17348 if (is_tracing_prog_type(prog_type)) { 17349 verbose(env, "tracing progs cannot use bpf_spin_lock yet\n"); 17350 return -EINVAL; 17351 } 17352 } 17353 17354 if (btf_record_has_field(map->record, BPF_TIMER)) { 17355 if (is_tracing_prog_type(prog_type)) { 17356 verbose(env, "tracing progs cannot use bpf_timer yet\n"); 17357 return -EINVAL; 17358 } 17359 } 17360 17361 if ((bpf_prog_is_offloaded(prog->aux) || bpf_map_is_offloaded(map)) && 17362 !bpf_offload_prog_map_match(prog, map)) { 17363 verbose(env, "offload device mismatch between prog and map\n"); 17364 return -EINVAL; 17365 } 17366 17367 if (map->map_type == BPF_MAP_TYPE_STRUCT_OPS) { 17368 verbose(env, "bpf_struct_ops map cannot be used in prog\n"); 17369 return -EINVAL; 17370 } 17371 17372 if (prog->aux->sleepable) 17373 switch (map->map_type) { 17374 case BPF_MAP_TYPE_HASH: 17375 case BPF_MAP_TYPE_LRU_HASH: 17376 case BPF_MAP_TYPE_ARRAY: 17377 case BPF_MAP_TYPE_PERCPU_HASH: 17378 case BPF_MAP_TYPE_PERCPU_ARRAY: 17379 case BPF_MAP_TYPE_LRU_PERCPU_HASH: 17380 case BPF_MAP_TYPE_ARRAY_OF_MAPS: 17381 case BPF_MAP_TYPE_HASH_OF_MAPS: 17382 case BPF_MAP_TYPE_RINGBUF: 17383 case BPF_MAP_TYPE_USER_RINGBUF: 17384 case BPF_MAP_TYPE_INODE_STORAGE: 17385 case BPF_MAP_TYPE_SK_STORAGE: 17386 case BPF_MAP_TYPE_TASK_STORAGE: 17387 case BPF_MAP_TYPE_CGRP_STORAGE: 17388 break; 17389 default: 17390 verbose(env, 17391 "Sleepable programs can only use array, hash, ringbuf and local storage maps\n"); 17392 return -EINVAL; 17393 } 17394 17395 return 0; 17396 } 17397 17398 static bool bpf_map_is_cgroup_storage(struct bpf_map *map) 17399 { 17400 return (map->map_type == BPF_MAP_TYPE_CGROUP_STORAGE || 17401 map->map_type == BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE); 17402 } 17403 17404 /* find and rewrite pseudo imm in ld_imm64 instructions: 17405 * 17406 * 1. if it accesses map FD, replace it with actual map pointer. 17407 * 2. if it accesses btf_id of a VAR, replace it with pointer to the var. 17408 * 17409 * NOTE: btf_vmlinux is required for converting pseudo btf_id. 17410 */ 17411 static int resolve_pseudo_ldimm64(struct bpf_verifier_env *env) 17412 { 17413 struct bpf_insn *insn = env->prog->insnsi; 17414 int insn_cnt = env->prog->len; 17415 int i, j, err; 17416 17417 err = bpf_prog_calc_tag(env->prog); 17418 if (err) 17419 return err; 17420 17421 for (i = 0; i < insn_cnt; i++, insn++) { 17422 if (BPF_CLASS(insn->code) == BPF_LDX && 17423 ((BPF_MODE(insn->code) != BPF_MEM && BPF_MODE(insn->code) != BPF_MEMSX) || 17424 insn->imm != 0)) { 17425 verbose(env, "BPF_LDX uses reserved fields\n"); 17426 return -EINVAL; 17427 } 17428 17429 if (insn[0].code == (BPF_LD | BPF_IMM | BPF_DW)) { 17430 struct bpf_insn_aux_data *aux; 17431 struct bpf_map *map; 17432 struct fd f; 17433 u64 addr; 17434 u32 fd; 17435 17436 if (i == insn_cnt - 1 || insn[1].code != 0 || 17437 insn[1].dst_reg != 0 || insn[1].src_reg != 0 || 17438 insn[1].off != 0) { 17439 verbose(env, "invalid bpf_ld_imm64 insn\n"); 17440 return -EINVAL; 17441 } 17442 17443 if (insn[0].src_reg == 0) 17444 /* valid generic load 64-bit imm */ 17445 goto next_insn; 17446 17447 if (insn[0].src_reg == BPF_PSEUDO_BTF_ID) { 17448 aux = &env->insn_aux_data[i]; 17449 err = check_pseudo_btf_id(env, insn, aux); 17450 if (err) 17451 return err; 17452 goto next_insn; 17453 } 17454 17455 if (insn[0].src_reg == BPF_PSEUDO_FUNC) { 17456 aux = &env->insn_aux_data[i]; 17457 aux->ptr_type = PTR_TO_FUNC; 17458 goto next_insn; 17459 } 17460 17461 /* In final convert_pseudo_ld_imm64() step, this is 17462 * converted into regular 64-bit imm load insn. 17463 */ 17464 switch (insn[0].src_reg) { 17465 case BPF_PSEUDO_MAP_VALUE: 17466 case BPF_PSEUDO_MAP_IDX_VALUE: 17467 break; 17468 case BPF_PSEUDO_MAP_FD: 17469 case BPF_PSEUDO_MAP_IDX: 17470 if (insn[1].imm == 0) 17471 break; 17472 fallthrough; 17473 default: 17474 verbose(env, "unrecognized bpf_ld_imm64 insn\n"); 17475 return -EINVAL; 17476 } 17477 17478 switch (insn[0].src_reg) { 17479 case BPF_PSEUDO_MAP_IDX_VALUE: 17480 case BPF_PSEUDO_MAP_IDX: 17481 if (bpfptr_is_null(env->fd_array)) { 17482 verbose(env, "fd_idx without fd_array is invalid\n"); 17483 return -EPROTO; 17484 } 17485 if (copy_from_bpfptr_offset(&fd, env->fd_array, 17486 insn[0].imm * sizeof(fd), 17487 sizeof(fd))) 17488 return -EFAULT; 17489 break; 17490 default: 17491 fd = insn[0].imm; 17492 break; 17493 } 17494 17495 f = fdget(fd); 17496 map = __bpf_map_get(f); 17497 if (IS_ERR(map)) { 17498 verbose(env, "fd %d is not pointing to valid bpf_map\n", 17499 insn[0].imm); 17500 return PTR_ERR(map); 17501 } 17502 17503 err = check_map_prog_compatibility(env, map, env->prog); 17504 if (err) { 17505 fdput(f); 17506 return err; 17507 } 17508 17509 aux = &env->insn_aux_data[i]; 17510 if (insn[0].src_reg == BPF_PSEUDO_MAP_FD || 17511 insn[0].src_reg == BPF_PSEUDO_MAP_IDX) { 17512 addr = (unsigned long)map; 17513 } else { 17514 u32 off = insn[1].imm; 17515 17516 if (off >= BPF_MAX_VAR_OFF) { 17517 verbose(env, "direct value offset of %u is not allowed\n", off); 17518 fdput(f); 17519 return -EINVAL; 17520 } 17521 17522 if (!map->ops->map_direct_value_addr) { 17523 verbose(env, "no direct value access support for this map type\n"); 17524 fdput(f); 17525 return -EINVAL; 17526 } 17527 17528 err = map->ops->map_direct_value_addr(map, &addr, off); 17529 if (err) { 17530 verbose(env, "invalid access to map value pointer, value_size=%u off=%u\n", 17531 map->value_size, off); 17532 fdput(f); 17533 return err; 17534 } 17535 17536 aux->map_off = off; 17537 addr += off; 17538 } 17539 17540 insn[0].imm = (u32)addr; 17541 insn[1].imm = addr >> 32; 17542 17543 /* check whether we recorded this map already */ 17544 for (j = 0; j < env->used_map_cnt; j++) { 17545 if (env->used_maps[j] == map) { 17546 aux->map_index = j; 17547 fdput(f); 17548 goto next_insn; 17549 } 17550 } 17551 17552 if (env->used_map_cnt >= MAX_USED_MAPS) { 17553 fdput(f); 17554 return -E2BIG; 17555 } 17556 17557 /* hold the map. If the program is rejected by verifier, 17558 * the map will be released by release_maps() or it 17559 * will be used by the valid program until it's unloaded 17560 * and all maps are released in free_used_maps() 17561 */ 17562 bpf_map_inc(map); 17563 17564 aux->map_index = env->used_map_cnt; 17565 env->used_maps[env->used_map_cnt++] = map; 17566 17567 if (bpf_map_is_cgroup_storage(map) && 17568 bpf_cgroup_storage_assign(env->prog->aux, map)) { 17569 verbose(env, "only one cgroup storage of each type is allowed\n"); 17570 fdput(f); 17571 return -EBUSY; 17572 } 17573 17574 fdput(f); 17575 next_insn: 17576 insn++; 17577 i++; 17578 continue; 17579 } 17580 17581 /* Basic sanity check before we invest more work here. */ 17582 if (!bpf_opcode_in_insntable(insn->code)) { 17583 verbose(env, "unknown opcode %02x\n", insn->code); 17584 return -EINVAL; 17585 } 17586 } 17587 17588 /* now all pseudo BPF_LD_IMM64 instructions load valid 17589 * 'struct bpf_map *' into a register instead of user map_fd. 17590 * These pointers will be used later by verifier to validate map access. 17591 */ 17592 return 0; 17593 } 17594 17595 /* drop refcnt of maps used by the rejected program */ 17596 static void release_maps(struct bpf_verifier_env *env) 17597 { 17598 __bpf_free_used_maps(env->prog->aux, env->used_maps, 17599 env->used_map_cnt); 17600 } 17601 17602 /* drop refcnt of maps used by the rejected program */ 17603 static void release_btfs(struct bpf_verifier_env *env) 17604 { 17605 __bpf_free_used_btfs(env->prog->aux, env->used_btfs, 17606 env->used_btf_cnt); 17607 } 17608 17609 /* convert pseudo BPF_LD_IMM64 into generic BPF_LD_IMM64 */ 17610 static void convert_pseudo_ld_imm64(struct bpf_verifier_env *env) 17611 { 17612 struct bpf_insn *insn = env->prog->insnsi; 17613 int insn_cnt = env->prog->len; 17614 int i; 17615 17616 for (i = 0; i < insn_cnt; i++, insn++) { 17617 if (insn->code != (BPF_LD | BPF_IMM | BPF_DW)) 17618 continue; 17619 if (insn->src_reg == BPF_PSEUDO_FUNC) 17620 continue; 17621 insn->src_reg = 0; 17622 } 17623 } 17624 17625 /* single env->prog->insni[off] instruction was replaced with the range 17626 * insni[off, off + cnt). Adjust corresponding insn_aux_data by copying 17627 * [0, off) and [off, end) to new locations, so the patched range stays zero 17628 */ 17629 static void adjust_insn_aux_data(struct bpf_verifier_env *env, 17630 struct bpf_insn_aux_data *new_data, 17631 struct bpf_prog *new_prog, u32 off, u32 cnt) 17632 { 17633 struct bpf_insn_aux_data *old_data = env->insn_aux_data; 17634 struct bpf_insn *insn = new_prog->insnsi; 17635 u32 old_seen = old_data[off].seen; 17636 u32 prog_len; 17637 int i; 17638 17639 /* aux info at OFF always needs adjustment, no matter fast path 17640 * (cnt == 1) is taken or not. There is no guarantee INSN at OFF is the 17641 * original insn at old prog. 17642 */ 17643 old_data[off].zext_dst = insn_has_def32(env, insn + off + cnt - 1); 17644 17645 if (cnt == 1) 17646 return; 17647 prog_len = new_prog->len; 17648 17649 memcpy(new_data, old_data, sizeof(struct bpf_insn_aux_data) * off); 17650 memcpy(new_data + off + cnt - 1, old_data + off, 17651 sizeof(struct bpf_insn_aux_data) * (prog_len - off - cnt + 1)); 17652 for (i = off; i < off + cnt - 1; i++) { 17653 /* Expand insni[off]'s seen count to the patched range. */ 17654 new_data[i].seen = old_seen; 17655 new_data[i].zext_dst = insn_has_def32(env, insn + i); 17656 } 17657 env->insn_aux_data = new_data; 17658 vfree(old_data); 17659 } 17660 17661 static void adjust_subprog_starts(struct bpf_verifier_env *env, u32 off, u32 len) 17662 { 17663 int i; 17664 17665 if (len == 1) 17666 return; 17667 /* NOTE: fake 'exit' subprog should be updated as well. */ 17668 for (i = 0; i <= env->subprog_cnt; i++) { 17669 if (env->subprog_info[i].start <= off) 17670 continue; 17671 env->subprog_info[i].start += len - 1; 17672 } 17673 } 17674 17675 static void adjust_poke_descs(struct bpf_prog *prog, u32 off, u32 len) 17676 { 17677 struct bpf_jit_poke_descriptor *tab = prog->aux->poke_tab; 17678 int i, sz = prog->aux->size_poke_tab; 17679 struct bpf_jit_poke_descriptor *desc; 17680 17681 for (i = 0; i < sz; i++) { 17682 desc = &tab[i]; 17683 if (desc->insn_idx <= off) 17684 continue; 17685 desc->insn_idx += len - 1; 17686 } 17687 } 17688 17689 static struct bpf_prog *bpf_patch_insn_data(struct bpf_verifier_env *env, u32 off, 17690 const struct bpf_insn *patch, u32 len) 17691 { 17692 struct bpf_prog *new_prog; 17693 struct bpf_insn_aux_data *new_data = NULL; 17694 17695 if (len > 1) { 17696 new_data = vzalloc(array_size(env->prog->len + len - 1, 17697 sizeof(struct bpf_insn_aux_data))); 17698 if (!new_data) 17699 return NULL; 17700 } 17701 17702 new_prog = bpf_patch_insn_single(env->prog, off, patch, len); 17703 if (IS_ERR(new_prog)) { 17704 if (PTR_ERR(new_prog) == -ERANGE) 17705 verbose(env, 17706 "insn %d cannot be patched due to 16-bit range\n", 17707 env->insn_aux_data[off].orig_idx); 17708 vfree(new_data); 17709 return NULL; 17710 } 17711 adjust_insn_aux_data(env, new_data, new_prog, off, len); 17712 adjust_subprog_starts(env, off, len); 17713 adjust_poke_descs(new_prog, off, len); 17714 return new_prog; 17715 } 17716 17717 static int adjust_subprog_starts_after_remove(struct bpf_verifier_env *env, 17718 u32 off, u32 cnt) 17719 { 17720 int i, j; 17721 17722 /* find first prog starting at or after off (first to remove) */ 17723 for (i = 0; i < env->subprog_cnt; i++) 17724 if (env->subprog_info[i].start >= off) 17725 break; 17726 /* find first prog starting at or after off + cnt (first to stay) */ 17727 for (j = i; j < env->subprog_cnt; j++) 17728 if (env->subprog_info[j].start >= off + cnt) 17729 break; 17730 /* if j doesn't start exactly at off + cnt, we are just removing 17731 * the front of previous prog 17732 */ 17733 if (env->subprog_info[j].start != off + cnt) 17734 j--; 17735 17736 if (j > i) { 17737 struct bpf_prog_aux *aux = env->prog->aux; 17738 int move; 17739 17740 /* move fake 'exit' subprog as well */ 17741 move = env->subprog_cnt + 1 - j; 17742 17743 memmove(env->subprog_info + i, 17744 env->subprog_info + j, 17745 sizeof(*env->subprog_info) * move); 17746 env->subprog_cnt -= j - i; 17747 17748 /* remove func_info */ 17749 if (aux->func_info) { 17750 move = aux->func_info_cnt - j; 17751 17752 memmove(aux->func_info + i, 17753 aux->func_info + j, 17754 sizeof(*aux->func_info) * move); 17755 aux->func_info_cnt -= j - i; 17756 /* func_info->insn_off is set after all code rewrites, 17757 * in adjust_btf_func() - no need to adjust 17758 */ 17759 } 17760 } else { 17761 /* convert i from "first prog to remove" to "first to adjust" */ 17762 if (env->subprog_info[i].start == off) 17763 i++; 17764 } 17765 17766 /* update fake 'exit' subprog as well */ 17767 for (; i <= env->subprog_cnt; i++) 17768 env->subprog_info[i].start -= cnt; 17769 17770 return 0; 17771 } 17772 17773 static int bpf_adj_linfo_after_remove(struct bpf_verifier_env *env, u32 off, 17774 u32 cnt) 17775 { 17776 struct bpf_prog *prog = env->prog; 17777 u32 i, l_off, l_cnt, nr_linfo; 17778 struct bpf_line_info *linfo; 17779 17780 nr_linfo = prog->aux->nr_linfo; 17781 if (!nr_linfo) 17782 return 0; 17783 17784 linfo = prog->aux->linfo; 17785 17786 /* find first line info to remove, count lines to be removed */ 17787 for (i = 0; i < nr_linfo; i++) 17788 if (linfo[i].insn_off >= off) 17789 break; 17790 17791 l_off = i; 17792 l_cnt = 0; 17793 for (; i < nr_linfo; i++) 17794 if (linfo[i].insn_off < off + cnt) 17795 l_cnt++; 17796 else 17797 break; 17798 17799 /* First live insn doesn't match first live linfo, it needs to "inherit" 17800 * last removed linfo. prog is already modified, so prog->len == off 17801 * means no live instructions after (tail of the program was removed). 17802 */ 17803 if (prog->len != off && l_cnt && 17804 (i == nr_linfo || linfo[i].insn_off != off + cnt)) { 17805 l_cnt--; 17806 linfo[--i].insn_off = off + cnt; 17807 } 17808 17809 /* remove the line info which refer to the removed instructions */ 17810 if (l_cnt) { 17811 memmove(linfo + l_off, linfo + i, 17812 sizeof(*linfo) * (nr_linfo - i)); 17813 17814 prog->aux->nr_linfo -= l_cnt; 17815 nr_linfo = prog->aux->nr_linfo; 17816 } 17817 17818 /* pull all linfo[i].insn_off >= off + cnt in by cnt */ 17819 for (i = l_off; i < nr_linfo; i++) 17820 linfo[i].insn_off -= cnt; 17821 17822 /* fix up all subprogs (incl. 'exit') which start >= off */ 17823 for (i = 0; i <= env->subprog_cnt; i++) 17824 if (env->subprog_info[i].linfo_idx > l_off) { 17825 /* program may have started in the removed region but 17826 * may not be fully removed 17827 */ 17828 if (env->subprog_info[i].linfo_idx >= l_off + l_cnt) 17829 env->subprog_info[i].linfo_idx -= l_cnt; 17830 else 17831 env->subprog_info[i].linfo_idx = l_off; 17832 } 17833 17834 return 0; 17835 } 17836 17837 static int verifier_remove_insns(struct bpf_verifier_env *env, u32 off, u32 cnt) 17838 { 17839 struct bpf_insn_aux_data *aux_data = env->insn_aux_data; 17840 unsigned int orig_prog_len = env->prog->len; 17841 int err; 17842 17843 if (bpf_prog_is_offloaded(env->prog->aux)) 17844 bpf_prog_offload_remove_insns(env, off, cnt); 17845 17846 err = bpf_remove_insns(env->prog, off, cnt); 17847 if (err) 17848 return err; 17849 17850 err = adjust_subprog_starts_after_remove(env, off, cnt); 17851 if (err) 17852 return err; 17853 17854 err = bpf_adj_linfo_after_remove(env, off, cnt); 17855 if (err) 17856 return err; 17857 17858 memmove(aux_data + off, aux_data + off + cnt, 17859 sizeof(*aux_data) * (orig_prog_len - off - cnt)); 17860 17861 return 0; 17862 } 17863 17864 /* The verifier does more data flow analysis than llvm and will not 17865 * explore branches that are dead at run time. Malicious programs can 17866 * have dead code too. Therefore replace all dead at-run-time code 17867 * with 'ja -1'. 17868 * 17869 * Just nops are not optimal, e.g. if they would sit at the end of the 17870 * program and through another bug we would manage to jump there, then 17871 * we'd execute beyond program memory otherwise. Returning exception 17872 * code also wouldn't work since we can have subprogs where the dead 17873 * code could be located. 17874 */ 17875 static void sanitize_dead_code(struct bpf_verifier_env *env) 17876 { 17877 struct bpf_insn_aux_data *aux_data = env->insn_aux_data; 17878 struct bpf_insn trap = BPF_JMP_IMM(BPF_JA, 0, 0, -1); 17879 struct bpf_insn *insn = env->prog->insnsi; 17880 const int insn_cnt = env->prog->len; 17881 int i; 17882 17883 for (i = 0; i < insn_cnt; i++) { 17884 if (aux_data[i].seen) 17885 continue; 17886 memcpy(insn + i, &trap, sizeof(trap)); 17887 aux_data[i].zext_dst = false; 17888 } 17889 } 17890 17891 static bool insn_is_cond_jump(u8 code) 17892 { 17893 u8 op; 17894 17895 op = BPF_OP(code); 17896 if (BPF_CLASS(code) == BPF_JMP32) 17897 return op != BPF_JA; 17898 17899 if (BPF_CLASS(code) != BPF_JMP) 17900 return false; 17901 17902 return op != BPF_JA && op != BPF_EXIT && op != BPF_CALL; 17903 } 17904 17905 static void opt_hard_wire_dead_code_branches(struct bpf_verifier_env *env) 17906 { 17907 struct bpf_insn_aux_data *aux_data = env->insn_aux_data; 17908 struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0); 17909 struct bpf_insn *insn = env->prog->insnsi; 17910 const int insn_cnt = env->prog->len; 17911 int i; 17912 17913 for (i = 0; i < insn_cnt; i++, insn++) { 17914 if (!insn_is_cond_jump(insn->code)) 17915 continue; 17916 17917 if (!aux_data[i + 1].seen) 17918 ja.off = insn->off; 17919 else if (!aux_data[i + 1 + insn->off].seen) 17920 ja.off = 0; 17921 else 17922 continue; 17923 17924 if (bpf_prog_is_offloaded(env->prog->aux)) 17925 bpf_prog_offload_replace_insn(env, i, &ja); 17926 17927 memcpy(insn, &ja, sizeof(ja)); 17928 } 17929 } 17930 17931 static int opt_remove_dead_code(struct bpf_verifier_env *env) 17932 { 17933 struct bpf_insn_aux_data *aux_data = env->insn_aux_data; 17934 int insn_cnt = env->prog->len; 17935 int i, err; 17936 17937 for (i = 0; i < insn_cnt; i++) { 17938 int j; 17939 17940 j = 0; 17941 while (i + j < insn_cnt && !aux_data[i + j].seen) 17942 j++; 17943 if (!j) 17944 continue; 17945 17946 err = verifier_remove_insns(env, i, j); 17947 if (err) 17948 return err; 17949 insn_cnt = env->prog->len; 17950 } 17951 17952 return 0; 17953 } 17954 17955 static int opt_remove_nops(struct bpf_verifier_env *env) 17956 { 17957 const struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0); 17958 struct bpf_insn *insn = env->prog->insnsi; 17959 int insn_cnt = env->prog->len; 17960 int i, err; 17961 17962 for (i = 0; i < insn_cnt; i++) { 17963 if (memcmp(&insn[i], &ja, sizeof(ja))) 17964 continue; 17965 17966 err = verifier_remove_insns(env, i, 1); 17967 if (err) 17968 return err; 17969 insn_cnt--; 17970 i--; 17971 } 17972 17973 return 0; 17974 } 17975 17976 static int opt_subreg_zext_lo32_rnd_hi32(struct bpf_verifier_env *env, 17977 const union bpf_attr *attr) 17978 { 17979 struct bpf_insn *patch, zext_patch[2], rnd_hi32_patch[4]; 17980 struct bpf_insn_aux_data *aux = env->insn_aux_data; 17981 int i, patch_len, delta = 0, len = env->prog->len; 17982 struct bpf_insn *insns = env->prog->insnsi; 17983 struct bpf_prog *new_prog; 17984 bool rnd_hi32; 17985 17986 rnd_hi32 = attr->prog_flags & BPF_F_TEST_RND_HI32; 17987 zext_patch[1] = BPF_ZEXT_REG(0); 17988 rnd_hi32_patch[1] = BPF_ALU64_IMM(BPF_MOV, BPF_REG_AX, 0); 17989 rnd_hi32_patch[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_AX, 32); 17990 rnd_hi32_patch[3] = BPF_ALU64_REG(BPF_OR, 0, BPF_REG_AX); 17991 for (i = 0; i < len; i++) { 17992 int adj_idx = i + delta; 17993 struct bpf_insn insn; 17994 int load_reg; 17995 17996 insn = insns[adj_idx]; 17997 load_reg = insn_def_regno(&insn); 17998 if (!aux[adj_idx].zext_dst) { 17999 u8 code, class; 18000 u32 imm_rnd; 18001 18002 if (!rnd_hi32) 18003 continue; 18004 18005 code = insn.code; 18006 class = BPF_CLASS(code); 18007 if (load_reg == -1) 18008 continue; 18009 18010 /* NOTE: arg "reg" (the fourth one) is only used for 18011 * BPF_STX + SRC_OP, so it is safe to pass NULL 18012 * here. 18013 */ 18014 if (is_reg64(env, &insn, load_reg, NULL, DST_OP)) { 18015 if (class == BPF_LD && 18016 BPF_MODE(code) == BPF_IMM) 18017 i++; 18018 continue; 18019 } 18020 18021 /* ctx load could be transformed into wider load. */ 18022 if (class == BPF_LDX && 18023 aux[adj_idx].ptr_type == PTR_TO_CTX) 18024 continue; 18025 18026 imm_rnd = get_random_u32(); 18027 rnd_hi32_patch[0] = insn; 18028 rnd_hi32_patch[1].imm = imm_rnd; 18029 rnd_hi32_patch[3].dst_reg = load_reg; 18030 patch = rnd_hi32_patch; 18031 patch_len = 4; 18032 goto apply_patch_buffer; 18033 } 18034 18035 /* Add in an zero-extend instruction if a) the JIT has requested 18036 * it or b) it's a CMPXCHG. 18037 * 18038 * The latter is because: BPF_CMPXCHG always loads a value into 18039 * R0, therefore always zero-extends. However some archs' 18040 * equivalent instruction only does this load when the 18041 * comparison is successful. This detail of CMPXCHG is 18042 * orthogonal to the general zero-extension behaviour of the 18043 * CPU, so it's treated independently of bpf_jit_needs_zext. 18044 */ 18045 if (!bpf_jit_needs_zext() && !is_cmpxchg_insn(&insn)) 18046 continue; 18047 18048 /* Zero-extension is done by the caller. */ 18049 if (bpf_pseudo_kfunc_call(&insn)) 18050 continue; 18051 18052 if (WARN_ON(load_reg == -1)) { 18053 verbose(env, "verifier bug. zext_dst is set, but no reg is defined\n"); 18054 return -EFAULT; 18055 } 18056 18057 zext_patch[0] = insn; 18058 zext_patch[1].dst_reg = load_reg; 18059 zext_patch[1].src_reg = load_reg; 18060 patch = zext_patch; 18061 patch_len = 2; 18062 apply_patch_buffer: 18063 new_prog = bpf_patch_insn_data(env, adj_idx, patch, patch_len); 18064 if (!new_prog) 18065 return -ENOMEM; 18066 env->prog = new_prog; 18067 insns = new_prog->insnsi; 18068 aux = env->insn_aux_data; 18069 delta += patch_len - 1; 18070 } 18071 18072 return 0; 18073 } 18074 18075 /* convert load instructions that access fields of a context type into a 18076 * sequence of instructions that access fields of the underlying structure: 18077 * struct __sk_buff -> struct sk_buff 18078 * struct bpf_sock_ops -> struct sock 18079 */ 18080 static int convert_ctx_accesses(struct bpf_verifier_env *env) 18081 { 18082 const struct bpf_verifier_ops *ops = env->ops; 18083 int i, cnt, size, ctx_field_size, delta = 0; 18084 const int insn_cnt = env->prog->len; 18085 struct bpf_insn insn_buf[16], *insn; 18086 u32 target_size, size_default, off; 18087 struct bpf_prog *new_prog; 18088 enum bpf_access_type type; 18089 bool is_narrower_load; 18090 18091 if (ops->gen_prologue || env->seen_direct_write) { 18092 if (!ops->gen_prologue) { 18093 verbose(env, "bpf verifier is misconfigured\n"); 18094 return -EINVAL; 18095 } 18096 cnt = ops->gen_prologue(insn_buf, env->seen_direct_write, 18097 env->prog); 18098 if (cnt >= ARRAY_SIZE(insn_buf)) { 18099 verbose(env, "bpf verifier is misconfigured\n"); 18100 return -EINVAL; 18101 } else if (cnt) { 18102 new_prog = bpf_patch_insn_data(env, 0, insn_buf, cnt); 18103 if (!new_prog) 18104 return -ENOMEM; 18105 18106 env->prog = new_prog; 18107 delta += cnt - 1; 18108 } 18109 } 18110 18111 if (bpf_prog_is_offloaded(env->prog->aux)) 18112 return 0; 18113 18114 insn = env->prog->insnsi + delta; 18115 18116 for (i = 0; i < insn_cnt; i++, insn++) { 18117 bpf_convert_ctx_access_t convert_ctx_access; 18118 u8 mode; 18119 18120 if (insn->code == (BPF_LDX | BPF_MEM | BPF_B) || 18121 insn->code == (BPF_LDX | BPF_MEM | BPF_H) || 18122 insn->code == (BPF_LDX | BPF_MEM | BPF_W) || 18123 insn->code == (BPF_LDX | BPF_MEM | BPF_DW) || 18124 insn->code == (BPF_LDX | BPF_MEMSX | BPF_B) || 18125 insn->code == (BPF_LDX | BPF_MEMSX | BPF_H) || 18126 insn->code == (BPF_LDX | BPF_MEMSX | BPF_W)) { 18127 type = BPF_READ; 18128 } else if (insn->code == (BPF_STX | BPF_MEM | BPF_B) || 18129 insn->code == (BPF_STX | BPF_MEM | BPF_H) || 18130 insn->code == (BPF_STX | BPF_MEM | BPF_W) || 18131 insn->code == (BPF_STX | BPF_MEM | BPF_DW) || 18132 insn->code == (BPF_ST | BPF_MEM | BPF_B) || 18133 insn->code == (BPF_ST | BPF_MEM | BPF_H) || 18134 insn->code == (BPF_ST | BPF_MEM | BPF_W) || 18135 insn->code == (BPF_ST | BPF_MEM | BPF_DW)) { 18136 type = BPF_WRITE; 18137 } else { 18138 continue; 18139 } 18140 18141 if (type == BPF_WRITE && 18142 env->insn_aux_data[i + delta].sanitize_stack_spill) { 18143 struct bpf_insn patch[] = { 18144 *insn, 18145 BPF_ST_NOSPEC(), 18146 }; 18147 18148 cnt = ARRAY_SIZE(patch); 18149 new_prog = bpf_patch_insn_data(env, i + delta, patch, cnt); 18150 if (!new_prog) 18151 return -ENOMEM; 18152 18153 delta += cnt - 1; 18154 env->prog = new_prog; 18155 insn = new_prog->insnsi + i + delta; 18156 continue; 18157 } 18158 18159 switch ((int)env->insn_aux_data[i + delta].ptr_type) { 18160 case PTR_TO_CTX: 18161 if (!ops->convert_ctx_access) 18162 continue; 18163 convert_ctx_access = ops->convert_ctx_access; 18164 break; 18165 case PTR_TO_SOCKET: 18166 case PTR_TO_SOCK_COMMON: 18167 convert_ctx_access = bpf_sock_convert_ctx_access; 18168 break; 18169 case PTR_TO_TCP_SOCK: 18170 convert_ctx_access = bpf_tcp_sock_convert_ctx_access; 18171 break; 18172 case PTR_TO_XDP_SOCK: 18173 convert_ctx_access = bpf_xdp_sock_convert_ctx_access; 18174 break; 18175 case PTR_TO_BTF_ID: 18176 case PTR_TO_BTF_ID | PTR_UNTRUSTED: 18177 /* PTR_TO_BTF_ID | MEM_ALLOC always has a valid lifetime, unlike 18178 * PTR_TO_BTF_ID, and an active ref_obj_id, but the same cannot 18179 * be said once it is marked PTR_UNTRUSTED, hence we must handle 18180 * any faults for loads into such types. BPF_WRITE is disallowed 18181 * for this case. 18182 */ 18183 case PTR_TO_BTF_ID | MEM_ALLOC | PTR_UNTRUSTED: 18184 if (type == BPF_READ) { 18185 if (BPF_MODE(insn->code) == BPF_MEM) 18186 insn->code = BPF_LDX | BPF_PROBE_MEM | 18187 BPF_SIZE((insn)->code); 18188 else 18189 insn->code = BPF_LDX | BPF_PROBE_MEMSX | 18190 BPF_SIZE((insn)->code); 18191 env->prog->aux->num_exentries++; 18192 } 18193 continue; 18194 default: 18195 continue; 18196 } 18197 18198 ctx_field_size = env->insn_aux_data[i + delta].ctx_field_size; 18199 size = BPF_LDST_BYTES(insn); 18200 mode = BPF_MODE(insn->code); 18201 18202 /* If the read access is a narrower load of the field, 18203 * convert to a 4/8-byte load, to minimum program type specific 18204 * convert_ctx_access changes. If conversion is successful, 18205 * we will apply proper mask to the result. 18206 */ 18207 is_narrower_load = size < ctx_field_size; 18208 size_default = bpf_ctx_off_adjust_machine(ctx_field_size); 18209 off = insn->off; 18210 if (is_narrower_load) { 18211 u8 size_code; 18212 18213 if (type == BPF_WRITE) { 18214 verbose(env, "bpf verifier narrow ctx access misconfigured\n"); 18215 return -EINVAL; 18216 } 18217 18218 size_code = BPF_H; 18219 if (ctx_field_size == 4) 18220 size_code = BPF_W; 18221 else if (ctx_field_size == 8) 18222 size_code = BPF_DW; 18223 18224 insn->off = off & ~(size_default - 1); 18225 insn->code = BPF_LDX | BPF_MEM | size_code; 18226 } 18227 18228 target_size = 0; 18229 cnt = convert_ctx_access(type, insn, insn_buf, env->prog, 18230 &target_size); 18231 if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf) || 18232 (ctx_field_size && !target_size)) { 18233 verbose(env, "bpf verifier is misconfigured\n"); 18234 return -EINVAL; 18235 } 18236 18237 if (is_narrower_load && size < target_size) { 18238 u8 shift = bpf_ctx_narrow_access_offset( 18239 off, size, size_default) * 8; 18240 if (shift && cnt + 1 >= ARRAY_SIZE(insn_buf)) { 18241 verbose(env, "bpf verifier narrow ctx load misconfigured\n"); 18242 return -EINVAL; 18243 } 18244 if (ctx_field_size <= 4) { 18245 if (shift) 18246 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_RSH, 18247 insn->dst_reg, 18248 shift); 18249 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg, 18250 (1 << size * 8) - 1); 18251 } else { 18252 if (shift) 18253 insn_buf[cnt++] = BPF_ALU64_IMM(BPF_RSH, 18254 insn->dst_reg, 18255 shift); 18256 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg, 18257 (1ULL << size * 8) - 1); 18258 } 18259 } 18260 if (mode == BPF_MEMSX) 18261 insn_buf[cnt++] = BPF_RAW_INSN(BPF_ALU64 | BPF_MOV | BPF_X, 18262 insn->dst_reg, insn->dst_reg, 18263 size * 8, 0); 18264 18265 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 18266 if (!new_prog) 18267 return -ENOMEM; 18268 18269 delta += cnt - 1; 18270 18271 /* keep walking new program and skip insns we just inserted */ 18272 env->prog = new_prog; 18273 insn = new_prog->insnsi + i + delta; 18274 } 18275 18276 return 0; 18277 } 18278 18279 static int jit_subprogs(struct bpf_verifier_env *env) 18280 { 18281 struct bpf_prog *prog = env->prog, **func, *tmp; 18282 int i, j, subprog_start, subprog_end = 0, len, subprog; 18283 struct bpf_map *map_ptr; 18284 struct bpf_insn *insn; 18285 void *old_bpf_func; 18286 int err, num_exentries; 18287 18288 if (env->subprog_cnt <= 1) 18289 return 0; 18290 18291 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) { 18292 if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn)) 18293 continue; 18294 18295 /* Upon error here we cannot fall back to interpreter but 18296 * need a hard reject of the program. Thus -EFAULT is 18297 * propagated in any case. 18298 */ 18299 subprog = find_subprog(env, i + insn->imm + 1); 18300 if (subprog < 0) { 18301 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n", 18302 i + insn->imm + 1); 18303 return -EFAULT; 18304 } 18305 /* temporarily remember subprog id inside insn instead of 18306 * aux_data, since next loop will split up all insns into funcs 18307 */ 18308 insn->off = subprog; 18309 /* remember original imm in case JIT fails and fallback 18310 * to interpreter will be needed 18311 */ 18312 env->insn_aux_data[i].call_imm = insn->imm; 18313 /* point imm to __bpf_call_base+1 from JITs point of view */ 18314 insn->imm = 1; 18315 if (bpf_pseudo_func(insn)) 18316 /* jit (e.g. x86_64) may emit fewer instructions 18317 * if it learns a u32 imm is the same as a u64 imm. 18318 * Force a non zero here. 18319 */ 18320 insn[1].imm = 1; 18321 } 18322 18323 err = bpf_prog_alloc_jited_linfo(prog); 18324 if (err) 18325 goto out_undo_insn; 18326 18327 err = -ENOMEM; 18328 func = kcalloc(env->subprog_cnt, sizeof(prog), GFP_KERNEL); 18329 if (!func) 18330 goto out_undo_insn; 18331 18332 for (i = 0; i < env->subprog_cnt; i++) { 18333 subprog_start = subprog_end; 18334 subprog_end = env->subprog_info[i + 1].start; 18335 18336 len = subprog_end - subprog_start; 18337 /* bpf_prog_run() doesn't call subprogs directly, 18338 * hence main prog stats include the runtime of subprogs. 18339 * subprogs don't have IDs and not reachable via prog_get_next_id 18340 * func[i]->stats will never be accessed and stays NULL 18341 */ 18342 func[i] = bpf_prog_alloc_no_stats(bpf_prog_size(len), GFP_USER); 18343 if (!func[i]) 18344 goto out_free; 18345 memcpy(func[i]->insnsi, &prog->insnsi[subprog_start], 18346 len * sizeof(struct bpf_insn)); 18347 func[i]->type = prog->type; 18348 func[i]->len = len; 18349 if (bpf_prog_calc_tag(func[i])) 18350 goto out_free; 18351 func[i]->is_func = 1; 18352 func[i]->aux->func_idx = i; 18353 /* Below members will be freed only at prog->aux */ 18354 func[i]->aux->btf = prog->aux->btf; 18355 func[i]->aux->func_info = prog->aux->func_info; 18356 func[i]->aux->func_info_cnt = prog->aux->func_info_cnt; 18357 func[i]->aux->poke_tab = prog->aux->poke_tab; 18358 func[i]->aux->size_poke_tab = prog->aux->size_poke_tab; 18359 18360 for (j = 0; j < prog->aux->size_poke_tab; j++) { 18361 struct bpf_jit_poke_descriptor *poke; 18362 18363 poke = &prog->aux->poke_tab[j]; 18364 if (poke->insn_idx < subprog_end && 18365 poke->insn_idx >= subprog_start) 18366 poke->aux = func[i]->aux; 18367 } 18368 18369 func[i]->aux->name[0] = 'F'; 18370 func[i]->aux->stack_depth = env->subprog_info[i].stack_depth; 18371 func[i]->jit_requested = 1; 18372 func[i]->blinding_requested = prog->blinding_requested; 18373 func[i]->aux->kfunc_tab = prog->aux->kfunc_tab; 18374 func[i]->aux->kfunc_btf_tab = prog->aux->kfunc_btf_tab; 18375 func[i]->aux->linfo = prog->aux->linfo; 18376 func[i]->aux->nr_linfo = prog->aux->nr_linfo; 18377 func[i]->aux->jited_linfo = prog->aux->jited_linfo; 18378 func[i]->aux->linfo_idx = env->subprog_info[i].linfo_idx; 18379 num_exentries = 0; 18380 insn = func[i]->insnsi; 18381 for (j = 0; j < func[i]->len; j++, insn++) { 18382 if (BPF_CLASS(insn->code) == BPF_LDX && 18383 (BPF_MODE(insn->code) == BPF_PROBE_MEM || 18384 BPF_MODE(insn->code) == BPF_PROBE_MEMSX)) 18385 num_exentries++; 18386 } 18387 func[i]->aux->num_exentries = num_exentries; 18388 func[i]->aux->tail_call_reachable = env->subprog_info[i].tail_call_reachable; 18389 func[i]->aux->exception_cb = env->subprog_info[i].is_exception_cb; 18390 if (!i) 18391 func[i]->aux->exception_boundary = env->seen_exception; 18392 func[i] = bpf_int_jit_compile(func[i]); 18393 if (!func[i]->jited) { 18394 err = -ENOTSUPP; 18395 goto out_free; 18396 } 18397 cond_resched(); 18398 } 18399 18400 /* at this point all bpf functions were successfully JITed 18401 * now populate all bpf_calls with correct addresses and 18402 * run last pass of JIT 18403 */ 18404 for (i = 0; i < env->subprog_cnt; i++) { 18405 insn = func[i]->insnsi; 18406 for (j = 0; j < func[i]->len; j++, insn++) { 18407 if (bpf_pseudo_func(insn)) { 18408 subprog = insn->off; 18409 insn[0].imm = (u32)(long)func[subprog]->bpf_func; 18410 insn[1].imm = ((u64)(long)func[subprog]->bpf_func) >> 32; 18411 continue; 18412 } 18413 if (!bpf_pseudo_call(insn)) 18414 continue; 18415 subprog = insn->off; 18416 insn->imm = BPF_CALL_IMM(func[subprog]->bpf_func); 18417 } 18418 18419 /* we use the aux data to keep a list of the start addresses 18420 * of the JITed images for each function in the program 18421 * 18422 * for some architectures, such as powerpc64, the imm field 18423 * might not be large enough to hold the offset of the start 18424 * address of the callee's JITed image from __bpf_call_base 18425 * 18426 * in such cases, we can lookup the start address of a callee 18427 * by using its subprog id, available from the off field of 18428 * the call instruction, as an index for this list 18429 */ 18430 func[i]->aux->func = func; 18431 func[i]->aux->func_cnt = env->subprog_cnt - env->hidden_subprog_cnt; 18432 func[i]->aux->real_func_cnt = env->subprog_cnt; 18433 } 18434 for (i = 0; i < env->subprog_cnt; i++) { 18435 old_bpf_func = func[i]->bpf_func; 18436 tmp = bpf_int_jit_compile(func[i]); 18437 if (tmp != func[i] || func[i]->bpf_func != old_bpf_func) { 18438 verbose(env, "JIT doesn't support bpf-to-bpf calls\n"); 18439 err = -ENOTSUPP; 18440 goto out_free; 18441 } 18442 cond_resched(); 18443 } 18444 18445 /* finally lock prog and jit images for all functions and 18446 * populate kallsysm. Begin at the first subprogram, since 18447 * bpf_prog_load will add the kallsyms for the main program. 18448 */ 18449 for (i = 1; i < env->subprog_cnt; i++) { 18450 bpf_prog_lock_ro(func[i]); 18451 bpf_prog_kallsyms_add(func[i]); 18452 } 18453 18454 /* Last step: make now unused interpreter insns from main 18455 * prog consistent for later dump requests, so they can 18456 * later look the same as if they were interpreted only. 18457 */ 18458 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) { 18459 if (bpf_pseudo_func(insn)) { 18460 insn[0].imm = env->insn_aux_data[i].call_imm; 18461 insn[1].imm = insn->off; 18462 insn->off = 0; 18463 continue; 18464 } 18465 if (!bpf_pseudo_call(insn)) 18466 continue; 18467 insn->off = env->insn_aux_data[i].call_imm; 18468 subprog = find_subprog(env, i + insn->off + 1); 18469 insn->imm = subprog; 18470 } 18471 18472 prog->jited = 1; 18473 prog->bpf_func = func[0]->bpf_func; 18474 prog->jited_len = func[0]->jited_len; 18475 prog->aux->extable = func[0]->aux->extable; 18476 prog->aux->num_exentries = func[0]->aux->num_exentries; 18477 prog->aux->func = func; 18478 prog->aux->func_cnt = env->subprog_cnt - env->hidden_subprog_cnt; 18479 prog->aux->real_func_cnt = env->subprog_cnt; 18480 prog->aux->bpf_exception_cb = (void *)func[env->exception_callback_subprog]->bpf_func; 18481 prog->aux->exception_boundary = func[0]->aux->exception_boundary; 18482 bpf_prog_jit_attempt_done(prog); 18483 return 0; 18484 out_free: 18485 /* We failed JIT'ing, so at this point we need to unregister poke 18486 * descriptors from subprogs, so that kernel is not attempting to 18487 * patch it anymore as we're freeing the subprog JIT memory. 18488 */ 18489 for (i = 0; i < prog->aux->size_poke_tab; i++) { 18490 map_ptr = prog->aux->poke_tab[i].tail_call.map; 18491 map_ptr->ops->map_poke_untrack(map_ptr, prog->aux); 18492 } 18493 /* At this point we're guaranteed that poke descriptors are not 18494 * live anymore. We can just unlink its descriptor table as it's 18495 * released with the main prog. 18496 */ 18497 for (i = 0; i < env->subprog_cnt; i++) { 18498 if (!func[i]) 18499 continue; 18500 func[i]->aux->poke_tab = NULL; 18501 bpf_jit_free(func[i]); 18502 } 18503 kfree(func); 18504 out_undo_insn: 18505 /* cleanup main prog to be interpreted */ 18506 prog->jit_requested = 0; 18507 prog->blinding_requested = 0; 18508 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) { 18509 if (!bpf_pseudo_call(insn)) 18510 continue; 18511 insn->off = 0; 18512 insn->imm = env->insn_aux_data[i].call_imm; 18513 } 18514 bpf_prog_jit_attempt_done(prog); 18515 return err; 18516 } 18517 18518 static int fixup_call_args(struct bpf_verifier_env *env) 18519 { 18520 #ifndef CONFIG_BPF_JIT_ALWAYS_ON 18521 struct bpf_prog *prog = env->prog; 18522 struct bpf_insn *insn = prog->insnsi; 18523 bool has_kfunc_call = bpf_prog_has_kfunc_call(prog); 18524 int i, depth; 18525 #endif 18526 int err = 0; 18527 18528 if (env->prog->jit_requested && 18529 !bpf_prog_is_offloaded(env->prog->aux)) { 18530 err = jit_subprogs(env); 18531 if (err == 0) 18532 return 0; 18533 if (err == -EFAULT) 18534 return err; 18535 } 18536 #ifndef CONFIG_BPF_JIT_ALWAYS_ON 18537 if (has_kfunc_call) { 18538 verbose(env, "calling kernel functions are not allowed in non-JITed programs\n"); 18539 return -EINVAL; 18540 } 18541 if (env->subprog_cnt > 1 && env->prog->aux->tail_call_reachable) { 18542 /* When JIT fails the progs with bpf2bpf calls and tail_calls 18543 * have to be rejected, since interpreter doesn't support them yet. 18544 */ 18545 verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n"); 18546 return -EINVAL; 18547 } 18548 for (i = 0; i < prog->len; i++, insn++) { 18549 if (bpf_pseudo_func(insn)) { 18550 /* When JIT fails the progs with callback calls 18551 * have to be rejected, since interpreter doesn't support them yet. 18552 */ 18553 verbose(env, "callbacks are not allowed in non-JITed programs\n"); 18554 return -EINVAL; 18555 } 18556 18557 if (!bpf_pseudo_call(insn)) 18558 continue; 18559 depth = get_callee_stack_depth(env, insn, i); 18560 if (depth < 0) 18561 return depth; 18562 bpf_patch_call_args(insn, depth); 18563 } 18564 err = 0; 18565 #endif 18566 return err; 18567 } 18568 18569 /* replace a generic kfunc with a specialized version if necessary */ 18570 static void specialize_kfunc(struct bpf_verifier_env *env, 18571 u32 func_id, u16 offset, unsigned long *addr) 18572 { 18573 struct bpf_prog *prog = env->prog; 18574 bool seen_direct_write; 18575 void *xdp_kfunc; 18576 bool is_rdonly; 18577 18578 if (bpf_dev_bound_kfunc_id(func_id)) { 18579 xdp_kfunc = bpf_dev_bound_resolve_kfunc(prog, func_id); 18580 if (xdp_kfunc) { 18581 *addr = (unsigned long)xdp_kfunc; 18582 return; 18583 } 18584 /* fallback to default kfunc when not supported by netdev */ 18585 } 18586 18587 if (offset) 18588 return; 18589 18590 if (func_id == special_kfunc_list[KF_bpf_dynptr_from_skb]) { 18591 seen_direct_write = env->seen_direct_write; 18592 is_rdonly = !may_access_direct_pkt_data(env, NULL, BPF_WRITE); 18593 18594 if (is_rdonly) 18595 *addr = (unsigned long)bpf_dynptr_from_skb_rdonly; 18596 18597 /* restore env->seen_direct_write to its original value, since 18598 * may_access_direct_pkt_data mutates it 18599 */ 18600 env->seen_direct_write = seen_direct_write; 18601 } 18602 } 18603 18604 static void __fixup_collection_insert_kfunc(struct bpf_insn_aux_data *insn_aux, 18605 u16 struct_meta_reg, 18606 u16 node_offset_reg, 18607 struct bpf_insn *insn, 18608 struct bpf_insn *insn_buf, 18609 int *cnt) 18610 { 18611 struct btf_struct_meta *kptr_struct_meta = insn_aux->kptr_struct_meta; 18612 struct bpf_insn addr[2] = { BPF_LD_IMM64(struct_meta_reg, (long)kptr_struct_meta) }; 18613 18614 insn_buf[0] = addr[0]; 18615 insn_buf[1] = addr[1]; 18616 insn_buf[2] = BPF_MOV64_IMM(node_offset_reg, insn_aux->insert_off); 18617 insn_buf[3] = *insn; 18618 *cnt = 4; 18619 } 18620 18621 static int fixup_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn, 18622 struct bpf_insn *insn_buf, int insn_idx, int *cnt) 18623 { 18624 const struct bpf_kfunc_desc *desc; 18625 18626 if (!insn->imm) { 18627 verbose(env, "invalid kernel function call not eliminated in verifier pass\n"); 18628 return -EINVAL; 18629 } 18630 18631 *cnt = 0; 18632 18633 /* insn->imm has the btf func_id. Replace it with an offset relative to 18634 * __bpf_call_base, unless the JIT needs to call functions that are 18635 * further than 32 bits away (bpf_jit_supports_far_kfunc_call()). 18636 */ 18637 desc = find_kfunc_desc(env->prog, insn->imm, insn->off); 18638 if (!desc) { 18639 verbose(env, "verifier internal error: kernel function descriptor not found for func_id %u\n", 18640 insn->imm); 18641 return -EFAULT; 18642 } 18643 18644 if (!bpf_jit_supports_far_kfunc_call()) 18645 insn->imm = BPF_CALL_IMM(desc->addr); 18646 if (insn->off) 18647 return 0; 18648 if (desc->func_id == special_kfunc_list[KF_bpf_obj_new_impl] || 18649 desc->func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl]) { 18650 struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta; 18651 struct bpf_insn addr[2] = { BPF_LD_IMM64(BPF_REG_2, (long)kptr_struct_meta) }; 18652 u64 obj_new_size = env->insn_aux_data[insn_idx].obj_new_size; 18653 18654 if (desc->func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl] && kptr_struct_meta) { 18655 verbose(env, "verifier internal error: NULL kptr_struct_meta expected at insn_idx %d\n", 18656 insn_idx); 18657 return -EFAULT; 18658 } 18659 18660 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_1, obj_new_size); 18661 insn_buf[1] = addr[0]; 18662 insn_buf[2] = addr[1]; 18663 insn_buf[3] = *insn; 18664 *cnt = 4; 18665 } else if (desc->func_id == special_kfunc_list[KF_bpf_obj_drop_impl] || 18666 desc->func_id == special_kfunc_list[KF_bpf_percpu_obj_drop_impl] || 18667 desc->func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl]) { 18668 struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta; 18669 struct bpf_insn addr[2] = { BPF_LD_IMM64(BPF_REG_2, (long)kptr_struct_meta) }; 18670 18671 if (desc->func_id == special_kfunc_list[KF_bpf_percpu_obj_drop_impl] && kptr_struct_meta) { 18672 verbose(env, "verifier internal error: NULL kptr_struct_meta expected at insn_idx %d\n", 18673 insn_idx); 18674 return -EFAULT; 18675 } 18676 18677 if (desc->func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl] && 18678 !kptr_struct_meta) { 18679 verbose(env, "verifier internal error: kptr_struct_meta expected at insn_idx %d\n", 18680 insn_idx); 18681 return -EFAULT; 18682 } 18683 18684 insn_buf[0] = addr[0]; 18685 insn_buf[1] = addr[1]; 18686 insn_buf[2] = *insn; 18687 *cnt = 3; 18688 } else if (desc->func_id == special_kfunc_list[KF_bpf_list_push_back_impl] || 18689 desc->func_id == special_kfunc_list[KF_bpf_list_push_front_impl] || 18690 desc->func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) { 18691 struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta; 18692 int struct_meta_reg = BPF_REG_3; 18693 int node_offset_reg = BPF_REG_4; 18694 18695 /* rbtree_add has extra 'less' arg, so args-to-fixup are in diff regs */ 18696 if (desc->func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) { 18697 struct_meta_reg = BPF_REG_4; 18698 node_offset_reg = BPF_REG_5; 18699 } 18700 18701 if (!kptr_struct_meta) { 18702 verbose(env, "verifier internal error: kptr_struct_meta expected at insn_idx %d\n", 18703 insn_idx); 18704 return -EFAULT; 18705 } 18706 18707 __fixup_collection_insert_kfunc(&env->insn_aux_data[insn_idx], struct_meta_reg, 18708 node_offset_reg, insn, insn_buf, cnt); 18709 } else if (desc->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx] || 18710 desc->func_id == special_kfunc_list[KF_bpf_rdonly_cast]) { 18711 insn_buf[0] = BPF_MOV64_REG(BPF_REG_0, BPF_REG_1); 18712 *cnt = 1; 18713 } 18714 return 0; 18715 } 18716 18717 /* The function requires that first instruction in 'patch' is insnsi[prog->len - 1] */ 18718 static int add_hidden_subprog(struct bpf_verifier_env *env, struct bpf_insn *patch, int len) 18719 { 18720 struct bpf_subprog_info *info = env->subprog_info; 18721 int cnt = env->subprog_cnt; 18722 struct bpf_prog *prog; 18723 18724 /* We only reserve one slot for hidden subprogs in subprog_info. */ 18725 if (env->hidden_subprog_cnt) { 18726 verbose(env, "verifier internal error: only one hidden subprog supported\n"); 18727 return -EFAULT; 18728 } 18729 /* We're not patching any existing instruction, just appending the new 18730 * ones for the hidden subprog. Hence all of the adjustment operations 18731 * in bpf_patch_insn_data are no-ops. 18732 */ 18733 prog = bpf_patch_insn_data(env, env->prog->len - 1, patch, len); 18734 if (!prog) 18735 return -ENOMEM; 18736 env->prog = prog; 18737 info[cnt + 1].start = info[cnt].start; 18738 info[cnt].start = prog->len - len + 1; 18739 env->subprog_cnt++; 18740 env->hidden_subprog_cnt++; 18741 return 0; 18742 } 18743 18744 /* Do various post-verification rewrites in a single program pass. 18745 * These rewrites simplify JIT and interpreter implementations. 18746 */ 18747 static int do_misc_fixups(struct bpf_verifier_env *env) 18748 { 18749 struct bpf_prog *prog = env->prog; 18750 enum bpf_attach_type eatype = prog->expected_attach_type; 18751 enum bpf_prog_type prog_type = resolve_prog_type(prog); 18752 struct bpf_insn *insn = prog->insnsi; 18753 const struct bpf_func_proto *fn; 18754 const int insn_cnt = prog->len; 18755 const struct bpf_map_ops *ops; 18756 struct bpf_insn_aux_data *aux; 18757 struct bpf_insn insn_buf[16]; 18758 struct bpf_prog *new_prog; 18759 struct bpf_map *map_ptr; 18760 int i, ret, cnt, delta = 0; 18761 18762 if (env->seen_exception && !env->exception_callback_subprog) { 18763 struct bpf_insn patch[] = { 18764 env->prog->insnsi[insn_cnt - 1], 18765 BPF_MOV64_REG(BPF_REG_0, BPF_REG_1), 18766 BPF_EXIT_INSN(), 18767 }; 18768 18769 ret = add_hidden_subprog(env, patch, ARRAY_SIZE(patch)); 18770 if (ret < 0) 18771 return ret; 18772 prog = env->prog; 18773 insn = prog->insnsi; 18774 18775 env->exception_callback_subprog = env->subprog_cnt - 1; 18776 /* Don't update insn_cnt, as add_hidden_subprog always appends insns */ 18777 env->subprog_info[env->exception_callback_subprog].is_cb = true; 18778 env->subprog_info[env->exception_callback_subprog].is_async_cb = true; 18779 env->subprog_info[env->exception_callback_subprog].is_exception_cb = true; 18780 } 18781 18782 for (i = 0; i < insn_cnt; i++, insn++) { 18783 /* Make divide-by-zero exceptions impossible. */ 18784 if (insn->code == (BPF_ALU64 | BPF_MOD | BPF_X) || 18785 insn->code == (BPF_ALU64 | BPF_DIV | BPF_X) || 18786 insn->code == (BPF_ALU | BPF_MOD | BPF_X) || 18787 insn->code == (BPF_ALU | BPF_DIV | BPF_X)) { 18788 bool is64 = BPF_CLASS(insn->code) == BPF_ALU64; 18789 bool isdiv = BPF_OP(insn->code) == BPF_DIV; 18790 struct bpf_insn *patchlet; 18791 struct bpf_insn chk_and_div[] = { 18792 /* [R,W]x div 0 -> 0 */ 18793 BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) | 18794 BPF_JNE | BPF_K, insn->src_reg, 18795 0, 2, 0), 18796 BPF_ALU32_REG(BPF_XOR, insn->dst_reg, insn->dst_reg), 18797 BPF_JMP_IMM(BPF_JA, 0, 0, 1), 18798 *insn, 18799 }; 18800 struct bpf_insn chk_and_mod[] = { 18801 /* [R,W]x mod 0 -> [R,W]x */ 18802 BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) | 18803 BPF_JEQ | BPF_K, insn->src_reg, 18804 0, 1 + (is64 ? 0 : 1), 0), 18805 *insn, 18806 BPF_JMP_IMM(BPF_JA, 0, 0, 1), 18807 BPF_MOV32_REG(insn->dst_reg, insn->dst_reg), 18808 }; 18809 18810 patchlet = isdiv ? chk_and_div : chk_and_mod; 18811 cnt = isdiv ? ARRAY_SIZE(chk_and_div) : 18812 ARRAY_SIZE(chk_and_mod) - (is64 ? 2 : 0); 18813 18814 new_prog = bpf_patch_insn_data(env, i + delta, patchlet, cnt); 18815 if (!new_prog) 18816 return -ENOMEM; 18817 18818 delta += cnt - 1; 18819 env->prog = prog = new_prog; 18820 insn = new_prog->insnsi + i + delta; 18821 continue; 18822 } 18823 18824 /* Implement LD_ABS and LD_IND with a rewrite, if supported by the program type. */ 18825 if (BPF_CLASS(insn->code) == BPF_LD && 18826 (BPF_MODE(insn->code) == BPF_ABS || 18827 BPF_MODE(insn->code) == BPF_IND)) { 18828 cnt = env->ops->gen_ld_abs(insn, insn_buf); 18829 if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf)) { 18830 verbose(env, "bpf verifier is misconfigured\n"); 18831 return -EINVAL; 18832 } 18833 18834 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 18835 if (!new_prog) 18836 return -ENOMEM; 18837 18838 delta += cnt - 1; 18839 env->prog = prog = new_prog; 18840 insn = new_prog->insnsi + i + delta; 18841 continue; 18842 } 18843 18844 /* Rewrite pointer arithmetic to mitigate speculation attacks. */ 18845 if (insn->code == (BPF_ALU64 | BPF_ADD | BPF_X) || 18846 insn->code == (BPF_ALU64 | BPF_SUB | BPF_X)) { 18847 const u8 code_add = BPF_ALU64 | BPF_ADD | BPF_X; 18848 const u8 code_sub = BPF_ALU64 | BPF_SUB | BPF_X; 18849 struct bpf_insn *patch = &insn_buf[0]; 18850 bool issrc, isneg, isimm; 18851 u32 off_reg; 18852 18853 aux = &env->insn_aux_data[i + delta]; 18854 if (!aux->alu_state || 18855 aux->alu_state == BPF_ALU_NON_POINTER) 18856 continue; 18857 18858 isneg = aux->alu_state & BPF_ALU_NEG_VALUE; 18859 issrc = (aux->alu_state & BPF_ALU_SANITIZE) == 18860 BPF_ALU_SANITIZE_SRC; 18861 isimm = aux->alu_state & BPF_ALU_IMMEDIATE; 18862 18863 off_reg = issrc ? insn->src_reg : insn->dst_reg; 18864 if (isimm) { 18865 *patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit); 18866 } else { 18867 if (isneg) 18868 *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1); 18869 *patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit); 18870 *patch++ = BPF_ALU64_REG(BPF_SUB, BPF_REG_AX, off_reg); 18871 *patch++ = BPF_ALU64_REG(BPF_OR, BPF_REG_AX, off_reg); 18872 *patch++ = BPF_ALU64_IMM(BPF_NEG, BPF_REG_AX, 0); 18873 *patch++ = BPF_ALU64_IMM(BPF_ARSH, BPF_REG_AX, 63); 18874 *patch++ = BPF_ALU64_REG(BPF_AND, BPF_REG_AX, off_reg); 18875 } 18876 if (!issrc) 18877 *patch++ = BPF_MOV64_REG(insn->dst_reg, insn->src_reg); 18878 insn->src_reg = BPF_REG_AX; 18879 if (isneg) 18880 insn->code = insn->code == code_add ? 18881 code_sub : code_add; 18882 *patch++ = *insn; 18883 if (issrc && isneg && !isimm) 18884 *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1); 18885 cnt = patch - insn_buf; 18886 18887 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 18888 if (!new_prog) 18889 return -ENOMEM; 18890 18891 delta += cnt - 1; 18892 env->prog = prog = new_prog; 18893 insn = new_prog->insnsi + i + delta; 18894 continue; 18895 } 18896 18897 if (insn->code != (BPF_JMP | BPF_CALL)) 18898 continue; 18899 if (insn->src_reg == BPF_PSEUDO_CALL) 18900 continue; 18901 if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) { 18902 ret = fixup_kfunc_call(env, insn, insn_buf, i + delta, &cnt); 18903 if (ret) 18904 return ret; 18905 if (cnt == 0) 18906 continue; 18907 18908 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 18909 if (!new_prog) 18910 return -ENOMEM; 18911 18912 delta += cnt - 1; 18913 env->prog = prog = new_prog; 18914 insn = new_prog->insnsi + i + delta; 18915 continue; 18916 } 18917 18918 if (insn->imm == BPF_FUNC_get_route_realm) 18919 prog->dst_needed = 1; 18920 if (insn->imm == BPF_FUNC_get_prandom_u32) 18921 bpf_user_rnd_init_once(); 18922 if (insn->imm == BPF_FUNC_override_return) 18923 prog->kprobe_override = 1; 18924 if (insn->imm == BPF_FUNC_tail_call) { 18925 /* If we tail call into other programs, we 18926 * cannot make any assumptions since they can 18927 * be replaced dynamically during runtime in 18928 * the program array. 18929 */ 18930 prog->cb_access = 1; 18931 if (!allow_tail_call_in_subprogs(env)) 18932 prog->aux->stack_depth = MAX_BPF_STACK; 18933 prog->aux->max_pkt_offset = MAX_PACKET_OFF; 18934 18935 /* mark bpf_tail_call as different opcode to avoid 18936 * conditional branch in the interpreter for every normal 18937 * call and to prevent accidental JITing by JIT compiler 18938 * that doesn't support bpf_tail_call yet 18939 */ 18940 insn->imm = 0; 18941 insn->code = BPF_JMP | BPF_TAIL_CALL; 18942 18943 aux = &env->insn_aux_data[i + delta]; 18944 if (env->bpf_capable && !prog->blinding_requested && 18945 prog->jit_requested && 18946 !bpf_map_key_poisoned(aux) && 18947 !bpf_map_ptr_poisoned(aux) && 18948 !bpf_map_ptr_unpriv(aux)) { 18949 struct bpf_jit_poke_descriptor desc = { 18950 .reason = BPF_POKE_REASON_TAIL_CALL, 18951 .tail_call.map = BPF_MAP_PTR(aux->map_ptr_state), 18952 .tail_call.key = bpf_map_key_immediate(aux), 18953 .insn_idx = i + delta, 18954 }; 18955 18956 ret = bpf_jit_add_poke_descriptor(prog, &desc); 18957 if (ret < 0) { 18958 verbose(env, "adding tail call poke descriptor failed\n"); 18959 return ret; 18960 } 18961 18962 insn->imm = ret + 1; 18963 continue; 18964 } 18965 18966 if (!bpf_map_ptr_unpriv(aux)) 18967 continue; 18968 18969 /* instead of changing every JIT dealing with tail_call 18970 * emit two extra insns: 18971 * if (index >= max_entries) goto out; 18972 * index &= array->index_mask; 18973 * to avoid out-of-bounds cpu speculation 18974 */ 18975 if (bpf_map_ptr_poisoned(aux)) { 18976 verbose(env, "tail_call abusing map_ptr\n"); 18977 return -EINVAL; 18978 } 18979 18980 map_ptr = BPF_MAP_PTR(aux->map_ptr_state); 18981 insn_buf[0] = BPF_JMP_IMM(BPF_JGE, BPF_REG_3, 18982 map_ptr->max_entries, 2); 18983 insn_buf[1] = BPF_ALU32_IMM(BPF_AND, BPF_REG_3, 18984 container_of(map_ptr, 18985 struct bpf_array, 18986 map)->index_mask); 18987 insn_buf[2] = *insn; 18988 cnt = 3; 18989 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 18990 if (!new_prog) 18991 return -ENOMEM; 18992 18993 delta += cnt - 1; 18994 env->prog = prog = new_prog; 18995 insn = new_prog->insnsi + i + delta; 18996 continue; 18997 } 18998 18999 if (insn->imm == BPF_FUNC_timer_set_callback) { 19000 /* The verifier will process callback_fn as many times as necessary 19001 * with different maps and the register states prepared by 19002 * set_timer_callback_state will be accurate. 19003 * 19004 * The following use case is valid: 19005 * map1 is shared by prog1, prog2, prog3. 19006 * prog1 calls bpf_timer_init for some map1 elements 19007 * prog2 calls bpf_timer_set_callback for some map1 elements. 19008 * Those that were not bpf_timer_init-ed will return -EINVAL. 19009 * prog3 calls bpf_timer_start for some map1 elements. 19010 * Those that were not both bpf_timer_init-ed and 19011 * bpf_timer_set_callback-ed will return -EINVAL. 19012 */ 19013 struct bpf_insn ld_addrs[2] = { 19014 BPF_LD_IMM64(BPF_REG_3, (long)prog->aux), 19015 }; 19016 19017 insn_buf[0] = ld_addrs[0]; 19018 insn_buf[1] = ld_addrs[1]; 19019 insn_buf[2] = *insn; 19020 cnt = 3; 19021 19022 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 19023 if (!new_prog) 19024 return -ENOMEM; 19025 19026 delta += cnt - 1; 19027 env->prog = prog = new_prog; 19028 insn = new_prog->insnsi + i + delta; 19029 goto patch_call_imm; 19030 } 19031 19032 if (is_storage_get_function(insn->imm)) { 19033 if (!env->prog->aux->sleepable || 19034 env->insn_aux_data[i + delta].storage_get_func_atomic) 19035 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_5, (__force __s32)GFP_ATOMIC); 19036 else 19037 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_5, (__force __s32)GFP_KERNEL); 19038 insn_buf[1] = *insn; 19039 cnt = 2; 19040 19041 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 19042 if (!new_prog) 19043 return -ENOMEM; 19044 19045 delta += cnt - 1; 19046 env->prog = prog = new_prog; 19047 insn = new_prog->insnsi + i + delta; 19048 goto patch_call_imm; 19049 } 19050 19051 /* bpf_per_cpu_ptr() and bpf_this_cpu_ptr() */ 19052 if (env->insn_aux_data[i + delta].call_with_percpu_alloc_ptr) { 19053 /* patch with 'r1 = *(u64 *)(r1 + 0)' since for percpu data, 19054 * bpf_mem_alloc() returns a ptr to the percpu data ptr. 19055 */ 19056 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_1, BPF_REG_1, 0); 19057 insn_buf[1] = *insn; 19058 cnt = 2; 19059 19060 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 19061 if (!new_prog) 19062 return -ENOMEM; 19063 19064 delta += cnt - 1; 19065 env->prog = prog = new_prog; 19066 insn = new_prog->insnsi + i + delta; 19067 goto patch_call_imm; 19068 } 19069 19070 /* BPF_EMIT_CALL() assumptions in some of the map_gen_lookup 19071 * and other inlining handlers are currently limited to 64 bit 19072 * only. 19073 */ 19074 if (prog->jit_requested && BITS_PER_LONG == 64 && 19075 (insn->imm == BPF_FUNC_map_lookup_elem || 19076 insn->imm == BPF_FUNC_map_update_elem || 19077 insn->imm == BPF_FUNC_map_delete_elem || 19078 insn->imm == BPF_FUNC_map_push_elem || 19079 insn->imm == BPF_FUNC_map_pop_elem || 19080 insn->imm == BPF_FUNC_map_peek_elem || 19081 insn->imm == BPF_FUNC_redirect_map || 19082 insn->imm == BPF_FUNC_for_each_map_elem || 19083 insn->imm == BPF_FUNC_map_lookup_percpu_elem)) { 19084 aux = &env->insn_aux_data[i + delta]; 19085 if (bpf_map_ptr_poisoned(aux)) 19086 goto patch_call_imm; 19087 19088 map_ptr = BPF_MAP_PTR(aux->map_ptr_state); 19089 ops = map_ptr->ops; 19090 if (insn->imm == BPF_FUNC_map_lookup_elem && 19091 ops->map_gen_lookup) { 19092 cnt = ops->map_gen_lookup(map_ptr, insn_buf); 19093 if (cnt == -EOPNOTSUPP) 19094 goto patch_map_ops_generic; 19095 if (cnt <= 0 || cnt >= ARRAY_SIZE(insn_buf)) { 19096 verbose(env, "bpf verifier is misconfigured\n"); 19097 return -EINVAL; 19098 } 19099 19100 new_prog = bpf_patch_insn_data(env, i + delta, 19101 insn_buf, cnt); 19102 if (!new_prog) 19103 return -ENOMEM; 19104 19105 delta += cnt - 1; 19106 env->prog = prog = new_prog; 19107 insn = new_prog->insnsi + i + delta; 19108 continue; 19109 } 19110 19111 BUILD_BUG_ON(!__same_type(ops->map_lookup_elem, 19112 (void *(*)(struct bpf_map *map, void *key))NULL)); 19113 BUILD_BUG_ON(!__same_type(ops->map_delete_elem, 19114 (long (*)(struct bpf_map *map, void *key))NULL)); 19115 BUILD_BUG_ON(!__same_type(ops->map_update_elem, 19116 (long (*)(struct bpf_map *map, void *key, void *value, 19117 u64 flags))NULL)); 19118 BUILD_BUG_ON(!__same_type(ops->map_push_elem, 19119 (long (*)(struct bpf_map *map, void *value, 19120 u64 flags))NULL)); 19121 BUILD_BUG_ON(!__same_type(ops->map_pop_elem, 19122 (long (*)(struct bpf_map *map, void *value))NULL)); 19123 BUILD_BUG_ON(!__same_type(ops->map_peek_elem, 19124 (long (*)(struct bpf_map *map, void *value))NULL)); 19125 BUILD_BUG_ON(!__same_type(ops->map_redirect, 19126 (long (*)(struct bpf_map *map, u64 index, u64 flags))NULL)); 19127 BUILD_BUG_ON(!__same_type(ops->map_for_each_callback, 19128 (long (*)(struct bpf_map *map, 19129 bpf_callback_t callback_fn, 19130 void *callback_ctx, 19131 u64 flags))NULL)); 19132 BUILD_BUG_ON(!__same_type(ops->map_lookup_percpu_elem, 19133 (void *(*)(struct bpf_map *map, void *key, u32 cpu))NULL)); 19134 19135 patch_map_ops_generic: 19136 switch (insn->imm) { 19137 case BPF_FUNC_map_lookup_elem: 19138 insn->imm = BPF_CALL_IMM(ops->map_lookup_elem); 19139 continue; 19140 case BPF_FUNC_map_update_elem: 19141 insn->imm = BPF_CALL_IMM(ops->map_update_elem); 19142 continue; 19143 case BPF_FUNC_map_delete_elem: 19144 insn->imm = BPF_CALL_IMM(ops->map_delete_elem); 19145 continue; 19146 case BPF_FUNC_map_push_elem: 19147 insn->imm = BPF_CALL_IMM(ops->map_push_elem); 19148 continue; 19149 case BPF_FUNC_map_pop_elem: 19150 insn->imm = BPF_CALL_IMM(ops->map_pop_elem); 19151 continue; 19152 case BPF_FUNC_map_peek_elem: 19153 insn->imm = BPF_CALL_IMM(ops->map_peek_elem); 19154 continue; 19155 case BPF_FUNC_redirect_map: 19156 insn->imm = BPF_CALL_IMM(ops->map_redirect); 19157 continue; 19158 case BPF_FUNC_for_each_map_elem: 19159 insn->imm = BPF_CALL_IMM(ops->map_for_each_callback); 19160 continue; 19161 case BPF_FUNC_map_lookup_percpu_elem: 19162 insn->imm = BPF_CALL_IMM(ops->map_lookup_percpu_elem); 19163 continue; 19164 } 19165 19166 goto patch_call_imm; 19167 } 19168 19169 /* Implement bpf_jiffies64 inline. */ 19170 if (prog->jit_requested && BITS_PER_LONG == 64 && 19171 insn->imm == BPF_FUNC_jiffies64) { 19172 struct bpf_insn ld_jiffies_addr[2] = { 19173 BPF_LD_IMM64(BPF_REG_0, 19174 (unsigned long)&jiffies), 19175 }; 19176 19177 insn_buf[0] = ld_jiffies_addr[0]; 19178 insn_buf[1] = ld_jiffies_addr[1]; 19179 insn_buf[2] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, 19180 BPF_REG_0, 0); 19181 cnt = 3; 19182 19183 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 19184 cnt); 19185 if (!new_prog) 19186 return -ENOMEM; 19187 19188 delta += cnt - 1; 19189 env->prog = prog = new_prog; 19190 insn = new_prog->insnsi + i + delta; 19191 continue; 19192 } 19193 19194 /* Implement bpf_get_func_arg inline. */ 19195 if (prog_type == BPF_PROG_TYPE_TRACING && 19196 insn->imm == BPF_FUNC_get_func_arg) { 19197 /* Load nr_args from ctx - 8 */ 19198 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8); 19199 insn_buf[1] = BPF_JMP32_REG(BPF_JGE, BPF_REG_2, BPF_REG_0, 6); 19200 insn_buf[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_2, 3); 19201 insn_buf[3] = BPF_ALU64_REG(BPF_ADD, BPF_REG_2, BPF_REG_1); 19202 insn_buf[4] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_2, 0); 19203 insn_buf[5] = BPF_STX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0); 19204 insn_buf[6] = BPF_MOV64_IMM(BPF_REG_0, 0); 19205 insn_buf[7] = BPF_JMP_A(1); 19206 insn_buf[8] = BPF_MOV64_IMM(BPF_REG_0, -EINVAL); 19207 cnt = 9; 19208 19209 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 19210 if (!new_prog) 19211 return -ENOMEM; 19212 19213 delta += cnt - 1; 19214 env->prog = prog = new_prog; 19215 insn = new_prog->insnsi + i + delta; 19216 continue; 19217 } 19218 19219 /* Implement bpf_get_func_ret inline. */ 19220 if (prog_type == BPF_PROG_TYPE_TRACING && 19221 insn->imm == BPF_FUNC_get_func_ret) { 19222 if (eatype == BPF_TRACE_FEXIT || 19223 eatype == BPF_MODIFY_RETURN) { 19224 /* Load nr_args from ctx - 8 */ 19225 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8); 19226 insn_buf[1] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_0, 3); 19227 insn_buf[2] = BPF_ALU64_REG(BPF_ADD, BPF_REG_0, BPF_REG_1); 19228 insn_buf[3] = BPF_LDX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0); 19229 insn_buf[4] = BPF_STX_MEM(BPF_DW, BPF_REG_2, BPF_REG_3, 0); 19230 insn_buf[5] = BPF_MOV64_IMM(BPF_REG_0, 0); 19231 cnt = 6; 19232 } else { 19233 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_0, -EOPNOTSUPP); 19234 cnt = 1; 19235 } 19236 19237 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 19238 if (!new_prog) 19239 return -ENOMEM; 19240 19241 delta += cnt - 1; 19242 env->prog = prog = new_prog; 19243 insn = new_prog->insnsi + i + delta; 19244 continue; 19245 } 19246 19247 /* Implement get_func_arg_cnt inline. */ 19248 if (prog_type == BPF_PROG_TYPE_TRACING && 19249 insn->imm == BPF_FUNC_get_func_arg_cnt) { 19250 /* Load nr_args from ctx - 8 */ 19251 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8); 19252 19253 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1); 19254 if (!new_prog) 19255 return -ENOMEM; 19256 19257 env->prog = prog = new_prog; 19258 insn = new_prog->insnsi + i + delta; 19259 continue; 19260 } 19261 19262 /* Implement bpf_get_func_ip inline. */ 19263 if (prog_type == BPF_PROG_TYPE_TRACING && 19264 insn->imm == BPF_FUNC_get_func_ip) { 19265 /* Load IP address from ctx - 16 */ 19266 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -16); 19267 19268 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1); 19269 if (!new_prog) 19270 return -ENOMEM; 19271 19272 env->prog = prog = new_prog; 19273 insn = new_prog->insnsi + i + delta; 19274 continue; 19275 } 19276 19277 patch_call_imm: 19278 fn = env->ops->get_func_proto(insn->imm, env->prog); 19279 /* all functions that have prototype and verifier allowed 19280 * programs to call them, must be real in-kernel functions 19281 */ 19282 if (!fn->func) { 19283 verbose(env, 19284 "kernel subsystem misconfigured func %s#%d\n", 19285 func_id_name(insn->imm), insn->imm); 19286 return -EFAULT; 19287 } 19288 insn->imm = fn->func - __bpf_call_base; 19289 } 19290 19291 /* Since poke tab is now finalized, publish aux to tracker. */ 19292 for (i = 0; i < prog->aux->size_poke_tab; i++) { 19293 map_ptr = prog->aux->poke_tab[i].tail_call.map; 19294 if (!map_ptr->ops->map_poke_track || 19295 !map_ptr->ops->map_poke_untrack || 19296 !map_ptr->ops->map_poke_run) { 19297 verbose(env, "bpf verifier is misconfigured\n"); 19298 return -EINVAL; 19299 } 19300 19301 ret = map_ptr->ops->map_poke_track(map_ptr, prog->aux); 19302 if (ret < 0) { 19303 verbose(env, "tracking tail call prog failed\n"); 19304 return ret; 19305 } 19306 } 19307 19308 sort_kfunc_descs_by_imm_off(env->prog); 19309 19310 return 0; 19311 } 19312 19313 static struct bpf_prog *inline_bpf_loop(struct bpf_verifier_env *env, 19314 int position, 19315 s32 stack_base, 19316 u32 callback_subprogno, 19317 u32 *cnt) 19318 { 19319 s32 r6_offset = stack_base + 0 * BPF_REG_SIZE; 19320 s32 r7_offset = stack_base + 1 * BPF_REG_SIZE; 19321 s32 r8_offset = stack_base + 2 * BPF_REG_SIZE; 19322 int reg_loop_max = BPF_REG_6; 19323 int reg_loop_cnt = BPF_REG_7; 19324 int reg_loop_ctx = BPF_REG_8; 19325 19326 struct bpf_prog *new_prog; 19327 u32 callback_start; 19328 u32 call_insn_offset; 19329 s32 callback_offset; 19330 19331 /* This represents an inlined version of bpf_iter.c:bpf_loop, 19332 * be careful to modify this code in sync. 19333 */ 19334 struct bpf_insn insn_buf[] = { 19335 /* Return error and jump to the end of the patch if 19336 * expected number of iterations is too big. 19337 */ 19338 BPF_JMP_IMM(BPF_JLE, BPF_REG_1, BPF_MAX_LOOPS, 2), 19339 BPF_MOV32_IMM(BPF_REG_0, -E2BIG), 19340 BPF_JMP_IMM(BPF_JA, 0, 0, 16), 19341 /* spill R6, R7, R8 to use these as loop vars */ 19342 BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_6, r6_offset), 19343 BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_7, r7_offset), 19344 BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_8, r8_offset), 19345 /* initialize loop vars */ 19346 BPF_MOV64_REG(reg_loop_max, BPF_REG_1), 19347 BPF_MOV32_IMM(reg_loop_cnt, 0), 19348 BPF_MOV64_REG(reg_loop_ctx, BPF_REG_3), 19349 /* loop header, 19350 * if reg_loop_cnt >= reg_loop_max skip the loop body 19351 */ 19352 BPF_JMP_REG(BPF_JGE, reg_loop_cnt, reg_loop_max, 5), 19353 /* callback call, 19354 * correct callback offset would be set after patching 19355 */ 19356 BPF_MOV64_REG(BPF_REG_1, reg_loop_cnt), 19357 BPF_MOV64_REG(BPF_REG_2, reg_loop_ctx), 19358 BPF_CALL_REL(0), 19359 /* increment loop counter */ 19360 BPF_ALU64_IMM(BPF_ADD, reg_loop_cnt, 1), 19361 /* jump to loop header if callback returned 0 */ 19362 BPF_JMP_IMM(BPF_JEQ, BPF_REG_0, 0, -6), 19363 /* return value of bpf_loop, 19364 * set R0 to the number of iterations 19365 */ 19366 BPF_MOV64_REG(BPF_REG_0, reg_loop_cnt), 19367 /* restore original values of R6, R7, R8 */ 19368 BPF_LDX_MEM(BPF_DW, BPF_REG_6, BPF_REG_10, r6_offset), 19369 BPF_LDX_MEM(BPF_DW, BPF_REG_7, BPF_REG_10, r7_offset), 19370 BPF_LDX_MEM(BPF_DW, BPF_REG_8, BPF_REG_10, r8_offset), 19371 }; 19372 19373 *cnt = ARRAY_SIZE(insn_buf); 19374 new_prog = bpf_patch_insn_data(env, position, insn_buf, *cnt); 19375 if (!new_prog) 19376 return new_prog; 19377 19378 /* callback start is known only after patching */ 19379 callback_start = env->subprog_info[callback_subprogno].start; 19380 /* Note: insn_buf[12] is an offset of BPF_CALL_REL instruction */ 19381 call_insn_offset = position + 12; 19382 callback_offset = callback_start - call_insn_offset - 1; 19383 new_prog->insnsi[call_insn_offset].imm = callback_offset; 19384 19385 return new_prog; 19386 } 19387 19388 static bool is_bpf_loop_call(struct bpf_insn *insn) 19389 { 19390 return insn->code == (BPF_JMP | BPF_CALL) && 19391 insn->src_reg == 0 && 19392 insn->imm == BPF_FUNC_loop; 19393 } 19394 19395 /* For all sub-programs in the program (including main) check 19396 * insn_aux_data to see if there are bpf_loop calls that require 19397 * inlining. If such calls are found the calls are replaced with a 19398 * sequence of instructions produced by `inline_bpf_loop` function and 19399 * subprog stack_depth is increased by the size of 3 registers. 19400 * This stack space is used to spill values of the R6, R7, R8. These 19401 * registers are used to store the loop bound, counter and context 19402 * variables. 19403 */ 19404 static int optimize_bpf_loop(struct bpf_verifier_env *env) 19405 { 19406 struct bpf_subprog_info *subprogs = env->subprog_info; 19407 int i, cur_subprog = 0, cnt, delta = 0; 19408 struct bpf_insn *insn = env->prog->insnsi; 19409 int insn_cnt = env->prog->len; 19410 u16 stack_depth = subprogs[cur_subprog].stack_depth; 19411 u16 stack_depth_roundup = round_up(stack_depth, 8) - stack_depth; 19412 u16 stack_depth_extra = 0; 19413 19414 for (i = 0; i < insn_cnt; i++, insn++) { 19415 struct bpf_loop_inline_state *inline_state = 19416 &env->insn_aux_data[i + delta].loop_inline_state; 19417 19418 if (is_bpf_loop_call(insn) && inline_state->fit_for_inline) { 19419 struct bpf_prog *new_prog; 19420 19421 stack_depth_extra = BPF_REG_SIZE * 3 + stack_depth_roundup; 19422 new_prog = inline_bpf_loop(env, 19423 i + delta, 19424 -(stack_depth + stack_depth_extra), 19425 inline_state->callback_subprogno, 19426 &cnt); 19427 if (!new_prog) 19428 return -ENOMEM; 19429 19430 delta += cnt - 1; 19431 env->prog = new_prog; 19432 insn = new_prog->insnsi + i + delta; 19433 } 19434 19435 if (subprogs[cur_subprog + 1].start == i + delta + 1) { 19436 subprogs[cur_subprog].stack_depth += stack_depth_extra; 19437 cur_subprog++; 19438 stack_depth = subprogs[cur_subprog].stack_depth; 19439 stack_depth_roundup = round_up(stack_depth, 8) - stack_depth; 19440 stack_depth_extra = 0; 19441 } 19442 } 19443 19444 env->prog->aux->stack_depth = env->subprog_info[0].stack_depth; 19445 19446 return 0; 19447 } 19448 19449 static void free_states(struct bpf_verifier_env *env) 19450 { 19451 struct bpf_verifier_state_list *sl, *sln; 19452 int i; 19453 19454 sl = env->free_list; 19455 while (sl) { 19456 sln = sl->next; 19457 free_verifier_state(&sl->state, false); 19458 kfree(sl); 19459 sl = sln; 19460 } 19461 env->free_list = NULL; 19462 19463 if (!env->explored_states) 19464 return; 19465 19466 for (i = 0; i < state_htab_size(env); i++) { 19467 sl = env->explored_states[i]; 19468 19469 while (sl) { 19470 sln = sl->next; 19471 free_verifier_state(&sl->state, false); 19472 kfree(sl); 19473 sl = sln; 19474 } 19475 env->explored_states[i] = NULL; 19476 } 19477 } 19478 19479 static int do_check_common(struct bpf_verifier_env *env, int subprog, bool is_ex_cb) 19480 { 19481 bool pop_log = !(env->log.level & BPF_LOG_LEVEL2); 19482 struct bpf_verifier_state *state; 19483 struct bpf_reg_state *regs; 19484 int ret, i; 19485 19486 env->prev_linfo = NULL; 19487 env->pass_cnt++; 19488 19489 state = kzalloc(sizeof(struct bpf_verifier_state), GFP_KERNEL); 19490 if (!state) 19491 return -ENOMEM; 19492 state->curframe = 0; 19493 state->speculative = false; 19494 state->branches = 1; 19495 state->frame[0] = kzalloc(sizeof(struct bpf_func_state), GFP_KERNEL); 19496 if (!state->frame[0]) { 19497 kfree(state); 19498 return -ENOMEM; 19499 } 19500 env->cur_state = state; 19501 init_func_state(env, state->frame[0], 19502 BPF_MAIN_FUNC /* callsite */, 19503 0 /* frameno */, 19504 subprog); 19505 state->first_insn_idx = env->subprog_info[subprog].start; 19506 state->last_insn_idx = -1; 19507 19508 regs = state->frame[state->curframe]->regs; 19509 if (subprog || env->prog->type == BPF_PROG_TYPE_EXT) { 19510 ret = btf_prepare_func_args(env, subprog, regs, is_ex_cb); 19511 if (ret) 19512 goto out; 19513 for (i = BPF_REG_1; i <= BPF_REG_5; i++) { 19514 if (regs[i].type == PTR_TO_CTX) 19515 mark_reg_known_zero(env, regs, i); 19516 else if (regs[i].type == SCALAR_VALUE) 19517 mark_reg_unknown(env, regs, i); 19518 else if (base_type(regs[i].type) == PTR_TO_MEM) { 19519 const u32 mem_size = regs[i].mem_size; 19520 19521 mark_reg_known_zero(env, regs, i); 19522 regs[i].mem_size = mem_size; 19523 regs[i].id = ++env->id_gen; 19524 } 19525 } 19526 if (is_ex_cb) { 19527 state->frame[0]->in_exception_callback_fn = true; 19528 env->subprog_info[subprog].is_cb = true; 19529 env->subprog_info[subprog].is_async_cb = true; 19530 env->subprog_info[subprog].is_exception_cb = true; 19531 } 19532 } else { 19533 /* 1st arg to a function */ 19534 regs[BPF_REG_1].type = PTR_TO_CTX; 19535 mark_reg_known_zero(env, regs, BPF_REG_1); 19536 ret = btf_check_subprog_arg_match(env, subprog, regs); 19537 if (ret == -EFAULT) 19538 /* unlikely verifier bug. abort. 19539 * ret == 0 and ret < 0 are sadly acceptable for 19540 * main() function due to backward compatibility. 19541 * Like socket filter program may be written as: 19542 * int bpf_prog(struct pt_regs *ctx) 19543 * and never dereference that ctx in the program. 19544 * 'struct pt_regs' is a type mismatch for socket 19545 * filter that should be using 'struct __sk_buff'. 19546 */ 19547 goto out; 19548 } 19549 19550 ret = do_check(env); 19551 out: 19552 /* check for NULL is necessary, since cur_state can be freed inside 19553 * do_check() under memory pressure. 19554 */ 19555 if (env->cur_state) { 19556 free_verifier_state(env->cur_state, true); 19557 env->cur_state = NULL; 19558 } 19559 while (!pop_stack(env, NULL, NULL, false)); 19560 if (!ret && pop_log) 19561 bpf_vlog_reset(&env->log, 0); 19562 free_states(env); 19563 return ret; 19564 } 19565 19566 /* Verify all global functions in a BPF program one by one based on their BTF. 19567 * All global functions must pass verification. Otherwise the whole program is rejected. 19568 * Consider: 19569 * int bar(int); 19570 * int foo(int f) 19571 * { 19572 * return bar(f); 19573 * } 19574 * int bar(int b) 19575 * { 19576 * ... 19577 * } 19578 * foo() will be verified first for R1=any_scalar_value. During verification it 19579 * will be assumed that bar() already verified successfully and call to bar() 19580 * from foo() will be checked for type match only. Later bar() will be verified 19581 * independently to check that it's safe for R1=any_scalar_value. 19582 */ 19583 static int do_check_subprogs(struct bpf_verifier_env *env) 19584 { 19585 struct bpf_prog_aux *aux = env->prog->aux; 19586 int i, ret; 19587 19588 if (!aux->func_info) 19589 return 0; 19590 19591 for (i = 1; i < env->subprog_cnt; i++) { 19592 if (aux->func_info_aux[i].linkage != BTF_FUNC_GLOBAL) 19593 continue; 19594 env->insn_idx = env->subprog_info[i].start; 19595 WARN_ON_ONCE(env->insn_idx == 0); 19596 ret = do_check_common(env, i, env->exception_callback_subprog == i); 19597 if (ret) { 19598 return ret; 19599 } else if (env->log.level & BPF_LOG_LEVEL) { 19600 verbose(env, 19601 "Func#%d is safe for any args that match its prototype\n", 19602 i); 19603 } 19604 } 19605 return 0; 19606 } 19607 19608 static int do_check_main(struct bpf_verifier_env *env) 19609 { 19610 int ret; 19611 19612 env->insn_idx = 0; 19613 ret = do_check_common(env, 0, false); 19614 if (!ret) 19615 env->prog->aux->stack_depth = env->subprog_info[0].stack_depth; 19616 return ret; 19617 } 19618 19619 19620 static void print_verification_stats(struct bpf_verifier_env *env) 19621 { 19622 int i; 19623 19624 if (env->log.level & BPF_LOG_STATS) { 19625 verbose(env, "verification time %lld usec\n", 19626 div_u64(env->verification_time, 1000)); 19627 verbose(env, "stack depth "); 19628 for (i = 0; i < env->subprog_cnt; i++) { 19629 u32 depth = env->subprog_info[i].stack_depth; 19630 19631 verbose(env, "%d", depth); 19632 if (i + 1 < env->subprog_cnt) 19633 verbose(env, "+"); 19634 } 19635 verbose(env, "\n"); 19636 } 19637 verbose(env, "processed %d insns (limit %d) max_states_per_insn %d " 19638 "total_states %d peak_states %d mark_read %d\n", 19639 env->insn_processed, BPF_COMPLEXITY_LIMIT_INSNS, 19640 env->max_states_per_insn, env->total_states, 19641 env->peak_states, env->longest_mark_read_walk); 19642 } 19643 19644 static int check_struct_ops_btf_id(struct bpf_verifier_env *env) 19645 { 19646 const struct btf_type *t, *func_proto; 19647 const struct bpf_struct_ops *st_ops; 19648 const struct btf_member *member; 19649 struct bpf_prog *prog = env->prog; 19650 u32 btf_id, member_idx; 19651 const char *mname; 19652 19653 if (!prog->gpl_compatible) { 19654 verbose(env, "struct ops programs must have a GPL compatible license\n"); 19655 return -EINVAL; 19656 } 19657 19658 btf_id = prog->aux->attach_btf_id; 19659 st_ops = bpf_struct_ops_find(btf_id); 19660 if (!st_ops) { 19661 verbose(env, "attach_btf_id %u is not a supported struct\n", 19662 btf_id); 19663 return -ENOTSUPP; 19664 } 19665 19666 t = st_ops->type; 19667 member_idx = prog->expected_attach_type; 19668 if (member_idx >= btf_type_vlen(t)) { 19669 verbose(env, "attach to invalid member idx %u of struct %s\n", 19670 member_idx, st_ops->name); 19671 return -EINVAL; 19672 } 19673 19674 member = &btf_type_member(t)[member_idx]; 19675 mname = btf_name_by_offset(btf_vmlinux, member->name_off); 19676 func_proto = btf_type_resolve_func_ptr(btf_vmlinux, member->type, 19677 NULL); 19678 if (!func_proto) { 19679 verbose(env, "attach to invalid member %s(@idx %u) of struct %s\n", 19680 mname, member_idx, st_ops->name); 19681 return -EINVAL; 19682 } 19683 19684 if (st_ops->check_member) { 19685 int err = st_ops->check_member(t, member, prog); 19686 19687 if (err) { 19688 verbose(env, "attach to unsupported member %s of struct %s\n", 19689 mname, st_ops->name); 19690 return err; 19691 } 19692 } 19693 19694 prog->aux->attach_func_proto = func_proto; 19695 prog->aux->attach_func_name = mname; 19696 env->ops = st_ops->verifier_ops; 19697 19698 return 0; 19699 } 19700 #define SECURITY_PREFIX "security_" 19701 19702 static int check_attach_modify_return(unsigned long addr, const char *func_name) 19703 { 19704 if (within_error_injection_list(addr) || 19705 !strncmp(SECURITY_PREFIX, func_name, sizeof(SECURITY_PREFIX) - 1)) 19706 return 0; 19707 19708 return -EINVAL; 19709 } 19710 19711 /* list of non-sleepable functions that are otherwise on 19712 * ALLOW_ERROR_INJECTION list 19713 */ 19714 BTF_SET_START(btf_non_sleepable_error_inject) 19715 /* Three functions below can be called from sleepable and non-sleepable context. 19716 * Assume non-sleepable from bpf safety point of view. 19717 */ 19718 BTF_ID(func, __filemap_add_folio) 19719 BTF_ID(func, should_fail_alloc_page) 19720 BTF_ID(func, should_failslab) 19721 BTF_SET_END(btf_non_sleepable_error_inject) 19722 19723 static int check_non_sleepable_error_inject(u32 btf_id) 19724 { 19725 return btf_id_set_contains(&btf_non_sleepable_error_inject, btf_id); 19726 } 19727 19728 int bpf_check_attach_target(struct bpf_verifier_log *log, 19729 const struct bpf_prog *prog, 19730 const struct bpf_prog *tgt_prog, 19731 u32 btf_id, 19732 struct bpf_attach_target_info *tgt_info) 19733 { 19734 bool prog_extension = prog->type == BPF_PROG_TYPE_EXT; 19735 const char prefix[] = "btf_trace_"; 19736 int ret = 0, subprog = -1, i; 19737 const struct btf_type *t; 19738 bool conservative = true; 19739 const char *tname; 19740 struct btf *btf; 19741 long addr = 0; 19742 struct module *mod = NULL; 19743 19744 if (!btf_id) { 19745 bpf_log(log, "Tracing programs must provide btf_id\n"); 19746 return -EINVAL; 19747 } 19748 btf = tgt_prog ? tgt_prog->aux->btf : prog->aux->attach_btf; 19749 if (!btf) { 19750 bpf_log(log, 19751 "FENTRY/FEXIT program can only be attached to another program annotated with BTF\n"); 19752 return -EINVAL; 19753 } 19754 t = btf_type_by_id(btf, btf_id); 19755 if (!t) { 19756 bpf_log(log, "attach_btf_id %u is invalid\n", btf_id); 19757 return -EINVAL; 19758 } 19759 tname = btf_name_by_offset(btf, t->name_off); 19760 if (!tname) { 19761 bpf_log(log, "attach_btf_id %u doesn't have a name\n", btf_id); 19762 return -EINVAL; 19763 } 19764 if (tgt_prog) { 19765 struct bpf_prog_aux *aux = tgt_prog->aux; 19766 19767 if (bpf_prog_is_dev_bound(prog->aux) && 19768 !bpf_prog_dev_bound_match(prog, tgt_prog)) { 19769 bpf_log(log, "Target program bound device mismatch"); 19770 return -EINVAL; 19771 } 19772 19773 for (i = 0; i < aux->func_info_cnt; i++) 19774 if (aux->func_info[i].type_id == btf_id) { 19775 subprog = i; 19776 break; 19777 } 19778 if (subprog == -1) { 19779 bpf_log(log, "Subprog %s doesn't exist\n", tname); 19780 return -EINVAL; 19781 } 19782 if (aux->func && aux->func[subprog]->aux->exception_cb) { 19783 bpf_log(log, 19784 "%s programs cannot attach to exception callback\n", 19785 prog_extension ? "Extension" : "FENTRY/FEXIT"); 19786 return -EINVAL; 19787 } 19788 conservative = aux->func_info_aux[subprog].unreliable; 19789 if (prog_extension) { 19790 if (conservative) { 19791 bpf_log(log, 19792 "Cannot replace static functions\n"); 19793 return -EINVAL; 19794 } 19795 if (!prog->jit_requested) { 19796 bpf_log(log, 19797 "Extension programs should be JITed\n"); 19798 return -EINVAL; 19799 } 19800 } 19801 if (!tgt_prog->jited) { 19802 bpf_log(log, "Can attach to only JITed progs\n"); 19803 return -EINVAL; 19804 } 19805 if (tgt_prog->type == prog->type) { 19806 /* Cannot fentry/fexit another fentry/fexit program. 19807 * Cannot attach program extension to another extension. 19808 * It's ok to attach fentry/fexit to extension program. 19809 */ 19810 bpf_log(log, "Cannot recursively attach\n"); 19811 return -EINVAL; 19812 } 19813 if (tgt_prog->type == BPF_PROG_TYPE_TRACING && 19814 prog_extension && 19815 (tgt_prog->expected_attach_type == BPF_TRACE_FENTRY || 19816 tgt_prog->expected_attach_type == BPF_TRACE_FEXIT)) { 19817 /* Program extensions can extend all program types 19818 * except fentry/fexit. The reason is the following. 19819 * The fentry/fexit programs are used for performance 19820 * analysis, stats and can be attached to any program 19821 * type except themselves. When extension program is 19822 * replacing XDP function it is necessary to allow 19823 * performance analysis of all functions. Both original 19824 * XDP program and its program extension. Hence 19825 * attaching fentry/fexit to BPF_PROG_TYPE_EXT is 19826 * allowed. If extending of fentry/fexit was allowed it 19827 * would be possible to create long call chain 19828 * fentry->extension->fentry->extension beyond 19829 * reasonable stack size. Hence extending fentry is not 19830 * allowed. 19831 */ 19832 bpf_log(log, "Cannot extend fentry/fexit\n"); 19833 return -EINVAL; 19834 } 19835 } else { 19836 if (prog_extension) { 19837 bpf_log(log, "Cannot replace kernel functions\n"); 19838 return -EINVAL; 19839 } 19840 } 19841 19842 switch (prog->expected_attach_type) { 19843 case BPF_TRACE_RAW_TP: 19844 if (tgt_prog) { 19845 bpf_log(log, 19846 "Only FENTRY/FEXIT progs are attachable to another BPF prog\n"); 19847 return -EINVAL; 19848 } 19849 if (!btf_type_is_typedef(t)) { 19850 bpf_log(log, "attach_btf_id %u is not a typedef\n", 19851 btf_id); 19852 return -EINVAL; 19853 } 19854 if (strncmp(prefix, tname, sizeof(prefix) - 1)) { 19855 bpf_log(log, "attach_btf_id %u points to wrong type name %s\n", 19856 btf_id, tname); 19857 return -EINVAL; 19858 } 19859 tname += sizeof(prefix) - 1; 19860 t = btf_type_by_id(btf, t->type); 19861 if (!btf_type_is_ptr(t)) 19862 /* should never happen in valid vmlinux build */ 19863 return -EINVAL; 19864 t = btf_type_by_id(btf, t->type); 19865 if (!btf_type_is_func_proto(t)) 19866 /* should never happen in valid vmlinux build */ 19867 return -EINVAL; 19868 19869 break; 19870 case BPF_TRACE_ITER: 19871 if (!btf_type_is_func(t)) { 19872 bpf_log(log, "attach_btf_id %u is not a function\n", 19873 btf_id); 19874 return -EINVAL; 19875 } 19876 t = btf_type_by_id(btf, t->type); 19877 if (!btf_type_is_func_proto(t)) 19878 return -EINVAL; 19879 ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel); 19880 if (ret) 19881 return ret; 19882 break; 19883 default: 19884 if (!prog_extension) 19885 return -EINVAL; 19886 fallthrough; 19887 case BPF_MODIFY_RETURN: 19888 case BPF_LSM_MAC: 19889 case BPF_LSM_CGROUP: 19890 case BPF_TRACE_FENTRY: 19891 case BPF_TRACE_FEXIT: 19892 if (!btf_type_is_func(t)) { 19893 bpf_log(log, "attach_btf_id %u is not a function\n", 19894 btf_id); 19895 return -EINVAL; 19896 } 19897 if (prog_extension && 19898 btf_check_type_match(log, prog, btf, t)) 19899 return -EINVAL; 19900 t = btf_type_by_id(btf, t->type); 19901 if (!btf_type_is_func_proto(t)) 19902 return -EINVAL; 19903 19904 if ((prog->aux->saved_dst_prog_type || prog->aux->saved_dst_attach_type) && 19905 (!tgt_prog || prog->aux->saved_dst_prog_type != tgt_prog->type || 19906 prog->aux->saved_dst_attach_type != tgt_prog->expected_attach_type)) 19907 return -EINVAL; 19908 19909 if (tgt_prog && conservative) 19910 t = NULL; 19911 19912 ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel); 19913 if (ret < 0) 19914 return ret; 19915 19916 if (tgt_prog) { 19917 if (subprog == 0) 19918 addr = (long) tgt_prog->bpf_func; 19919 else 19920 addr = (long) tgt_prog->aux->func[subprog]->bpf_func; 19921 } else { 19922 if (btf_is_module(btf)) { 19923 mod = btf_try_get_module(btf); 19924 if (mod) 19925 addr = find_kallsyms_symbol_value(mod, tname); 19926 else 19927 addr = 0; 19928 } else { 19929 addr = kallsyms_lookup_name(tname); 19930 } 19931 if (!addr) { 19932 module_put(mod); 19933 bpf_log(log, 19934 "The address of function %s cannot be found\n", 19935 tname); 19936 return -ENOENT; 19937 } 19938 } 19939 19940 if (prog->aux->sleepable) { 19941 ret = -EINVAL; 19942 switch (prog->type) { 19943 case BPF_PROG_TYPE_TRACING: 19944 19945 /* fentry/fexit/fmod_ret progs can be sleepable if they are 19946 * attached to ALLOW_ERROR_INJECTION and are not in denylist. 19947 */ 19948 if (!check_non_sleepable_error_inject(btf_id) && 19949 within_error_injection_list(addr)) 19950 ret = 0; 19951 /* fentry/fexit/fmod_ret progs can also be sleepable if they are 19952 * in the fmodret id set with the KF_SLEEPABLE flag. 19953 */ 19954 else { 19955 u32 *flags = btf_kfunc_is_modify_return(btf, btf_id, 19956 prog); 19957 19958 if (flags && (*flags & KF_SLEEPABLE)) 19959 ret = 0; 19960 } 19961 break; 19962 case BPF_PROG_TYPE_LSM: 19963 /* LSM progs check that they are attached to bpf_lsm_*() funcs. 19964 * Only some of them are sleepable. 19965 */ 19966 if (bpf_lsm_is_sleepable_hook(btf_id)) 19967 ret = 0; 19968 break; 19969 default: 19970 break; 19971 } 19972 if (ret) { 19973 module_put(mod); 19974 bpf_log(log, "%s is not sleepable\n", tname); 19975 return ret; 19976 } 19977 } else if (prog->expected_attach_type == BPF_MODIFY_RETURN) { 19978 if (tgt_prog) { 19979 module_put(mod); 19980 bpf_log(log, "can't modify return codes of BPF programs\n"); 19981 return -EINVAL; 19982 } 19983 ret = -EINVAL; 19984 if (btf_kfunc_is_modify_return(btf, btf_id, prog) || 19985 !check_attach_modify_return(addr, tname)) 19986 ret = 0; 19987 if (ret) { 19988 module_put(mod); 19989 bpf_log(log, "%s() is not modifiable\n", tname); 19990 return ret; 19991 } 19992 } 19993 19994 break; 19995 } 19996 tgt_info->tgt_addr = addr; 19997 tgt_info->tgt_name = tname; 19998 tgt_info->tgt_type = t; 19999 tgt_info->tgt_mod = mod; 20000 return 0; 20001 } 20002 20003 BTF_SET_START(btf_id_deny) 20004 BTF_ID_UNUSED 20005 #ifdef CONFIG_SMP 20006 BTF_ID(func, migrate_disable) 20007 BTF_ID(func, migrate_enable) 20008 #endif 20009 #if !defined CONFIG_PREEMPT_RCU && !defined CONFIG_TINY_RCU 20010 BTF_ID(func, rcu_read_unlock_strict) 20011 #endif 20012 #if defined(CONFIG_DEBUG_PREEMPT) || defined(CONFIG_TRACE_PREEMPT_TOGGLE) 20013 BTF_ID(func, preempt_count_add) 20014 BTF_ID(func, preempt_count_sub) 20015 #endif 20016 #ifdef CONFIG_PREEMPT_RCU 20017 BTF_ID(func, __rcu_read_lock) 20018 BTF_ID(func, __rcu_read_unlock) 20019 #endif 20020 BTF_SET_END(btf_id_deny) 20021 20022 static bool can_be_sleepable(struct bpf_prog *prog) 20023 { 20024 if (prog->type == BPF_PROG_TYPE_TRACING) { 20025 switch (prog->expected_attach_type) { 20026 case BPF_TRACE_FENTRY: 20027 case BPF_TRACE_FEXIT: 20028 case BPF_MODIFY_RETURN: 20029 case BPF_TRACE_ITER: 20030 return true; 20031 default: 20032 return false; 20033 } 20034 } 20035 return prog->type == BPF_PROG_TYPE_LSM || 20036 prog->type == BPF_PROG_TYPE_KPROBE /* only for uprobes */ || 20037 prog->type == BPF_PROG_TYPE_STRUCT_OPS; 20038 } 20039 20040 static int check_attach_btf_id(struct bpf_verifier_env *env) 20041 { 20042 struct bpf_prog *prog = env->prog; 20043 struct bpf_prog *tgt_prog = prog->aux->dst_prog; 20044 struct bpf_attach_target_info tgt_info = {}; 20045 u32 btf_id = prog->aux->attach_btf_id; 20046 struct bpf_trampoline *tr; 20047 int ret; 20048 u64 key; 20049 20050 if (prog->type == BPF_PROG_TYPE_SYSCALL) { 20051 if (prog->aux->sleepable) 20052 /* attach_btf_id checked to be zero already */ 20053 return 0; 20054 verbose(env, "Syscall programs can only be sleepable\n"); 20055 return -EINVAL; 20056 } 20057 20058 if (prog->aux->sleepable && !can_be_sleepable(prog)) { 20059 verbose(env, "Only fentry/fexit/fmod_ret, lsm, iter, uprobe, and struct_ops programs can be sleepable\n"); 20060 return -EINVAL; 20061 } 20062 20063 if (prog->type == BPF_PROG_TYPE_STRUCT_OPS) 20064 return check_struct_ops_btf_id(env); 20065 20066 if (prog->type != BPF_PROG_TYPE_TRACING && 20067 prog->type != BPF_PROG_TYPE_LSM && 20068 prog->type != BPF_PROG_TYPE_EXT) 20069 return 0; 20070 20071 ret = bpf_check_attach_target(&env->log, prog, tgt_prog, btf_id, &tgt_info); 20072 if (ret) 20073 return ret; 20074 20075 if (tgt_prog && prog->type == BPF_PROG_TYPE_EXT) { 20076 /* to make freplace equivalent to their targets, they need to 20077 * inherit env->ops and expected_attach_type for the rest of the 20078 * verification 20079 */ 20080 env->ops = bpf_verifier_ops[tgt_prog->type]; 20081 prog->expected_attach_type = tgt_prog->expected_attach_type; 20082 } 20083 20084 /* store info about the attachment target that will be used later */ 20085 prog->aux->attach_func_proto = tgt_info.tgt_type; 20086 prog->aux->attach_func_name = tgt_info.tgt_name; 20087 prog->aux->mod = tgt_info.tgt_mod; 20088 20089 if (tgt_prog) { 20090 prog->aux->saved_dst_prog_type = tgt_prog->type; 20091 prog->aux->saved_dst_attach_type = tgt_prog->expected_attach_type; 20092 } 20093 20094 if (prog->expected_attach_type == BPF_TRACE_RAW_TP) { 20095 prog->aux->attach_btf_trace = true; 20096 return 0; 20097 } else if (prog->expected_attach_type == BPF_TRACE_ITER) { 20098 if (!bpf_iter_prog_supported(prog)) 20099 return -EINVAL; 20100 return 0; 20101 } 20102 20103 if (prog->type == BPF_PROG_TYPE_LSM) { 20104 ret = bpf_lsm_verify_prog(&env->log, prog); 20105 if (ret < 0) 20106 return ret; 20107 } else if (prog->type == BPF_PROG_TYPE_TRACING && 20108 btf_id_set_contains(&btf_id_deny, btf_id)) { 20109 return -EINVAL; 20110 } 20111 20112 key = bpf_trampoline_compute_key(tgt_prog, prog->aux->attach_btf, btf_id); 20113 tr = bpf_trampoline_get(key, &tgt_info); 20114 if (!tr) 20115 return -ENOMEM; 20116 20117 if (tgt_prog && tgt_prog->aux->tail_call_reachable) 20118 tr->flags = BPF_TRAMP_F_TAIL_CALL_CTX; 20119 20120 prog->aux->dst_trampoline = tr; 20121 return 0; 20122 } 20123 20124 struct btf *bpf_get_btf_vmlinux(void) 20125 { 20126 if (!btf_vmlinux && IS_ENABLED(CONFIG_DEBUG_INFO_BTF)) { 20127 mutex_lock(&bpf_verifier_lock); 20128 if (!btf_vmlinux) 20129 btf_vmlinux = btf_parse_vmlinux(); 20130 mutex_unlock(&bpf_verifier_lock); 20131 } 20132 return btf_vmlinux; 20133 } 20134 20135 int bpf_check(struct bpf_prog **prog, union bpf_attr *attr, bpfptr_t uattr, __u32 uattr_size) 20136 { 20137 u64 start_time = ktime_get_ns(); 20138 struct bpf_verifier_env *env; 20139 int i, len, ret = -EINVAL, err; 20140 u32 log_true_size; 20141 bool is_priv; 20142 20143 /* no program is valid */ 20144 if (ARRAY_SIZE(bpf_verifier_ops) == 0) 20145 return -EINVAL; 20146 20147 /* 'struct bpf_verifier_env' can be global, but since it's not small, 20148 * allocate/free it every time bpf_check() is called 20149 */ 20150 env = kzalloc(sizeof(struct bpf_verifier_env), GFP_KERNEL); 20151 if (!env) 20152 return -ENOMEM; 20153 20154 env->bt.env = env; 20155 20156 len = (*prog)->len; 20157 env->insn_aux_data = 20158 vzalloc(array_size(sizeof(struct bpf_insn_aux_data), len)); 20159 ret = -ENOMEM; 20160 if (!env->insn_aux_data) 20161 goto err_free_env; 20162 for (i = 0; i < len; i++) 20163 env->insn_aux_data[i].orig_idx = i; 20164 env->prog = *prog; 20165 env->ops = bpf_verifier_ops[env->prog->type]; 20166 env->fd_array = make_bpfptr(attr->fd_array, uattr.is_kernel); 20167 is_priv = bpf_capable(); 20168 20169 bpf_get_btf_vmlinux(); 20170 20171 /* grab the mutex to protect few globals used by verifier */ 20172 if (!is_priv) 20173 mutex_lock(&bpf_verifier_lock); 20174 20175 /* user could have requested verbose verifier output 20176 * and supplied buffer to store the verification trace 20177 */ 20178 ret = bpf_vlog_init(&env->log, attr->log_level, 20179 (char __user *) (unsigned long) attr->log_buf, 20180 attr->log_size); 20181 if (ret) 20182 goto err_unlock; 20183 20184 mark_verifier_state_clean(env); 20185 20186 if (IS_ERR(btf_vmlinux)) { 20187 /* Either gcc or pahole or kernel are broken. */ 20188 verbose(env, "in-kernel BTF is malformed\n"); 20189 ret = PTR_ERR(btf_vmlinux); 20190 goto skip_full_check; 20191 } 20192 20193 env->strict_alignment = !!(attr->prog_flags & BPF_F_STRICT_ALIGNMENT); 20194 if (!IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS)) 20195 env->strict_alignment = true; 20196 if (attr->prog_flags & BPF_F_ANY_ALIGNMENT) 20197 env->strict_alignment = false; 20198 20199 env->allow_ptr_leaks = bpf_allow_ptr_leaks(); 20200 env->allow_uninit_stack = bpf_allow_uninit_stack(); 20201 env->bypass_spec_v1 = bpf_bypass_spec_v1(); 20202 env->bypass_spec_v4 = bpf_bypass_spec_v4(); 20203 env->bpf_capable = bpf_capable(); 20204 20205 if (is_priv) 20206 env->test_state_freq = attr->prog_flags & BPF_F_TEST_STATE_FREQ; 20207 20208 env->explored_states = kvcalloc(state_htab_size(env), 20209 sizeof(struct bpf_verifier_state_list *), 20210 GFP_USER); 20211 ret = -ENOMEM; 20212 if (!env->explored_states) 20213 goto skip_full_check; 20214 20215 ret = check_btf_info_early(env, attr, uattr); 20216 if (ret < 0) 20217 goto skip_full_check; 20218 20219 ret = add_subprog_and_kfunc(env); 20220 if (ret < 0) 20221 goto skip_full_check; 20222 20223 ret = check_subprogs(env); 20224 if (ret < 0) 20225 goto skip_full_check; 20226 20227 ret = check_btf_info(env, attr, uattr); 20228 if (ret < 0) 20229 goto skip_full_check; 20230 20231 ret = check_attach_btf_id(env); 20232 if (ret) 20233 goto skip_full_check; 20234 20235 ret = resolve_pseudo_ldimm64(env); 20236 if (ret < 0) 20237 goto skip_full_check; 20238 20239 if (bpf_prog_is_offloaded(env->prog->aux)) { 20240 ret = bpf_prog_offload_verifier_prep(env->prog); 20241 if (ret) 20242 goto skip_full_check; 20243 } 20244 20245 ret = check_cfg(env); 20246 if (ret < 0) 20247 goto skip_full_check; 20248 20249 ret = do_check_subprogs(env); 20250 ret = ret ?: do_check_main(env); 20251 20252 if (ret == 0 && bpf_prog_is_offloaded(env->prog->aux)) 20253 ret = bpf_prog_offload_finalize(env); 20254 20255 skip_full_check: 20256 kvfree(env->explored_states); 20257 20258 if (ret == 0) 20259 ret = check_max_stack_depth(env); 20260 20261 /* instruction rewrites happen after this point */ 20262 if (ret == 0) 20263 ret = optimize_bpf_loop(env); 20264 20265 if (is_priv) { 20266 if (ret == 0) 20267 opt_hard_wire_dead_code_branches(env); 20268 if (ret == 0) 20269 ret = opt_remove_dead_code(env); 20270 if (ret == 0) 20271 ret = opt_remove_nops(env); 20272 } else { 20273 if (ret == 0) 20274 sanitize_dead_code(env); 20275 } 20276 20277 if (ret == 0) 20278 /* program is valid, convert *(u32*)(ctx + off) accesses */ 20279 ret = convert_ctx_accesses(env); 20280 20281 if (ret == 0) 20282 ret = do_misc_fixups(env); 20283 20284 /* do 32-bit optimization after insn patching has done so those patched 20285 * insns could be handled correctly. 20286 */ 20287 if (ret == 0 && !bpf_prog_is_offloaded(env->prog->aux)) { 20288 ret = opt_subreg_zext_lo32_rnd_hi32(env, attr); 20289 env->prog->aux->verifier_zext = bpf_jit_needs_zext() ? !ret 20290 : false; 20291 } 20292 20293 if (ret == 0) 20294 ret = fixup_call_args(env); 20295 20296 env->verification_time = ktime_get_ns() - start_time; 20297 print_verification_stats(env); 20298 env->prog->aux->verified_insns = env->insn_processed; 20299 20300 /* preserve original error even if log finalization is successful */ 20301 err = bpf_vlog_finalize(&env->log, &log_true_size); 20302 if (err) 20303 ret = err; 20304 20305 if (uattr_size >= offsetofend(union bpf_attr, log_true_size) && 20306 copy_to_bpfptr_offset(uattr, offsetof(union bpf_attr, log_true_size), 20307 &log_true_size, sizeof(log_true_size))) { 20308 ret = -EFAULT; 20309 goto err_release_maps; 20310 } 20311 20312 if (ret) 20313 goto err_release_maps; 20314 20315 if (env->used_map_cnt) { 20316 /* if program passed verifier, update used_maps in bpf_prog_info */ 20317 env->prog->aux->used_maps = kmalloc_array(env->used_map_cnt, 20318 sizeof(env->used_maps[0]), 20319 GFP_KERNEL); 20320 20321 if (!env->prog->aux->used_maps) { 20322 ret = -ENOMEM; 20323 goto err_release_maps; 20324 } 20325 20326 memcpy(env->prog->aux->used_maps, env->used_maps, 20327 sizeof(env->used_maps[0]) * env->used_map_cnt); 20328 env->prog->aux->used_map_cnt = env->used_map_cnt; 20329 } 20330 if (env->used_btf_cnt) { 20331 /* if program passed verifier, update used_btfs in bpf_prog_aux */ 20332 env->prog->aux->used_btfs = kmalloc_array(env->used_btf_cnt, 20333 sizeof(env->used_btfs[0]), 20334 GFP_KERNEL); 20335 if (!env->prog->aux->used_btfs) { 20336 ret = -ENOMEM; 20337 goto err_release_maps; 20338 } 20339 20340 memcpy(env->prog->aux->used_btfs, env->used_btfs, 20341 sizeof(env->used_btfs[0]) * env->used_btf_cnt); 20342 env->prog->aux->used_btf_cnt = env->used_btf_cnt; 20343 } 20344 if (env->used_map_cnt || env->used_btf_cnt) { 20345 /* program is valid. Convert pseudo bpf_ld_imm64 into generic 20346 * bpf_ld_imm64 instructions 20347 */ 20348 convert_pseudo_ld_imm64(env); 20349 } 20350 20351 adjust_btf_func(env); 20352 20353 err_release_maps: 20354 if (!env->prog->aux->used_maps) 20355 /* if we didn't copy map pointers into bpf_prog_info, release 20356 * them now. Otherwise free_used_maps() will release them. 20357 */ 20358 release_maps(env); 20359 if (!env->prog->aux->used_btfs) 20360 release_btfs(env); 20361 20362 /* extension progs temporarily inherit the attach_type of their targets 20363 for verification purposes, so set it back to zero before returning 20364 */ 20365 if (env->prog->type == BPF_PROG_TYPE_EXT) 20366 env->prog->expected_attach_type = 0; 20367 20368 *prog = env->prog; 20369 err_unlock: 20370 if (!is_priv) 20371 mutex_unlock(&bpf_verifier_lock); 20372 vfree(env->insn_aux_data); 20373 err_free_env: 20374 kfree(env); 20375 return ret; 20376 } 20377