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_verifier_state(struct bpf_verifier_env *env, 1346 const struct bpf_func_state *state, 1347 bool print_all) 1348 { 1349 const struct bpf_reg_state *reg; 1350 enum bpf_reg_type t; 1351 int i; 1352 1353 if (state->frameno) 1354 verbose(env, " frame%d:", state->frameno); 1355 for (i = 0; i < MAX_BPF_REG; i++) { 1356 reg = &state->regs[i]; 1357 t = reg->type; 1358 if (t == NOT_INIT) 1359 continue; 1360 if (!print_all && !reg_scratched(env, i)) 1361 continue; 1362 verbose(env, " R%d", i); 1363 print_liveness(env, reg->live); 1364 verbose(env, "="); 1365 if (t == SCALAR_VALUE && reg->precise) 1366 verbose(env, "P"); 1367 if ((t == SCALAR_VALUE || t == PTR_TO_STACK) && 1368 tnum_is_const(reg->var_off)) { 1369 /* reg->off should be 0 for SCALAR_VALUE */ 1370 verbose(env, "%s", t == SCALAR_VALUE ? "" : reg_type_str(env, t)); 1371 verbose(env, "%lld", reg->var_off.value + reg->off); 1372 } else { 1373 const char *sep = ""; 1374 1375 verbose(env, "%s", reg_type_str(env, t)); 1376 if (base_type(t) == PTR_TO_BTF_ID) 1377 verbose(env, "%s", btf_type_name(reg->btf, reg->btf_id)); 1378 verbose(env, "("); 1379 /* 1380 * _a stands for append, was shortened to avoid multiline statements below. 1381 * This macro is used to output a comma separated list of attributes. 1382 */ 1383 #define verbose_a(fmt, ...) ({ verbose(env, "%s" fmt, sep, __VA_ARGS__); sep = ","; }) 1384 1385 if (reg->id) 1386 verbose_a("id=%d", reg->id); 1387 if (reg->ref_obj_id) 1388 verbose_a("ref_obj_id=%d", reg->ref_obj_id); 1389 if (type_is_non_owning_ref(reg->type)) 1390 verbose_a("%s", "non_own_ref"); 1391 if (t != SCALAR_VALUE) 1392 verbose_a("off=%d", reg->off); 1393 if (type_is_pkt_pointer(t)) 1394 verbose_a("r=%d", reg->range); 1395 else if (base_type(t) == CONST_PTR_TO_MAP || 1396 base_type(t) == PTR_TO_MAP_KEY || 1397 base_type(t) == PTR_TO_MAP_VALUE) 1398 verbose_a("ks=%d,vs=%d", 1399 reg->map_ptr->key_size, 1400 reg->map_ptr->value_size); 1401 if (tnum_is_const(reg->var_off)) { 1402 /* Typically an immediate SCALAR_VALUE, but 1403 * could be a pointer whose offset is too big 1404 * for reg->off 1405 */ 1406 verbose_a("imm=%llx", reg->var_off.value); 1407 } else { 1408 if (reg->smin_value != reg->umin_value && 1409 reg->smin_value != S64_MIN) 1410 verbose_a("smin=%lld", (long long)reg->smin_value); 1411 if (reg->smax_value != reg->umax_value && 1412 reg->smax_value != S64_MAX) 1413 verbose_a("smax=%lld", (long long)reg->smax_value); 1414 if (reg->umin_value != 0) 1415 verbose_a("umin=%llu", (unsigned long long)reg->umin_value); 1416 if (reg->umax_value != U64_MAX) 1417 verbose_a("umax=%llu", (unsigned long long)reg->umax_value); 1418 if (!tnum_is_unknown(reg->var_off)) { 1419 char tn_buf[48]; 1420 1421 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 1422 verbose_a("var_off=%s", tn_buf); 1423 } 1424 if (reg->s32_min_value != reg->smin_value && 1425 reg->s32_min_value != S32_MIN) 1426 verbose_a("s32_min=%d", (int)(reg->s32_min_value)); 1427 if (reg->s32_max_value != reg->smax_value && 1428 reg->s32_max_value != S32_MAX) 1429 verbose_a("s32_max=%d", (int)(reg->s32_max_value)); 1430 if (reg->u32_min_value != reg->umin_value && 1431 reg->u32_min_value != U32_MIN) 1432 verbose_a("u32_min=%d", (int)(reg->u32_min_value)); 1433 if (reg->u32_max_value != reg->umax_value && 1434 reg->u32_max_value != U32_MAX) 1435 verbose_a("u32_max=%d", (int)(reg->u32_max_value)); 1436 } 1437 #undef verbose_a 1438 1439 verbose(env, ")"); 1440 } 1441 } 1442 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) { 1443 char types_buf[BPF_REG_SIZE + 1]; 1444 bool valid = false; 1445 int j; 1446 1447 for (j = 0; j < BPF_REG_SIZE; j++) { 1448 if (state->stack[i].slot_type[j] != STACK_INVALID) 1449 valid = true; 1450 types_buf[j] = slot_type_char[state->stack[i].slot_type[j]]; 1451 } 1452 types_buf[BPF_REG_SIZE] = 0; 1453 if (!valid) 1454 continue; 1455 if (!print_all && !stack_slot_scratched(env, i)) 1456 continue; 1457 switch (state->stack[i].slot_type[BPF_REG_SIZE - 1]) { 1458 case STACK_SPILL: 1459 reg = &state->stack[i].spilled_ptr; 1460 t = reg->type; 1461 1462 verbose(env, " fp%d", (-i - 1) * BPF_REG_SIZE); 1463 print_liveness(env, reg->live); 1464 verbose(env, "=%s", t == SCALAR_VALUE ? "" : reg_type_str(env, t)); 1465 if (t == SCALAR_VALUE && reg->precise) 1466 verbose(env, "P"); 1467 if (t == SCALAR_VALUE && tnum_is_const(reg->var_off)) 1468 verbose(env, "%lld", reg->var_off.value + reg->off); 1469 break; 1470 case STACK_DYNPTR: 1471 i += BPF_DYNPTR_NR_SLOTS - 1; 1472 reg = &state->stack[i].spilled_ptr; 1473 1474 verbose(env, " fp%d", (-i - 1) * BPF_REG_SIZE); 1475 print_liveness(env, reg->live); 1476 verbose(env, "=dynptr_%s", dynptr_type_str(reg->dynptr.type)); 1477 if (reg->ref_obj_id) 1478 verbose(env, "(ref_id=%d)", reg->ref_obj_id); 1479 break; 1480 case STACK_ITER: 1481 /* only main slot has ref_obj_id set; skip others */ 1482 reg = &state->stack[i].spilled_ptr; 1483 if (!reg->ref_obj_id) 1484 continue; 1485 1486 verbose(env, " fp%d", (-i - 1) * BPF_REG_SIZE); 1487 print_liveness(env, reg->live); 1488 verbose(env, "=iter_%s(ref_id=%d,state=%s,depth=%u)", 1489 iter_type_str(reg->iter.btf, reg->iter.btf_id), 1490 reg->ref_obj_id, iter_state_str(reg->iter.state), 1491 reg->iter.depth); 1492 break; 1493 case STACK_MISC: 1494 case STACK_ZERO: 1495 default: 1496 reg = &state->stack[i].spilled_ptr; 1497 1498 for (j = 0; j < BPF_REG_SIZE; j++) 1499 types_buf[j] = slot_type_char[state->stack[i].slot_type[j]]; 1500 types_buf[BPF_REG_SIZE] = 0; 1501 1502 verbose(env, " fp%d", (-i - 1) * BPF_REG_SIZE); 1503 print_liveness(env, reg->live); 1504 verbose(env, "=%s", types_buf); 1505 break; 1506 } 1507 } 1508 if (state->acquired_refs && state->refs[0].id) { 1509 verbose(env, " refs=%d", state->refs[0].id); 1510 for (i = 1; i < state->acquired_refs; i++) 1511 if (state->refs[i].id) 1512 verbose(env, ",%d", state->refs[i].id); 1513 } 1514 if (state->in_callback_fn) 1515 verbose(env, " cb"); 1516 if (state->in_async_callback_fn) 1517 verbose(env, " async_cb"); 1518 verbose(env, "\n"); 1519 mark_verifier_state_clean(env); 1520 } 1521 1522 static inline u32 vlog_alignment(u32 pos) 1523 { 1524 return round_up(max(pos + BPF_LOG_MIN_ALIGNMENT / 2, BPF_LOG_ALIGNMENT), 1525 BPF_LOG_MIN_ALIGNMENT) - pos - 1; 1526 } 1527 1528 static void print_insn_state(struct bpf_verifier_env *env, 1529 const struct bpf_func_state *state) 1530 { 1531 if (env->prev_log_pos && env->prev_log_pos == env->log.end_pos) { 1532 /* remove new line character */ 1533 bpf_vlog_reset(&env->log, env->prev_log_pos - 1); 1534 verbose(env, "%*c;", vlog_alignment(env->prev_insn_print_pos), ' '); 1535 } else { 1536 verbose(env, "%d:", env->insn_idx); 1537 } 1538 print_verifier_state(env, state, false); 1539 } 1540 1541 /* copy array src of length n * size bytes to dst. dst is reallocated if it's too 1542 * small to hold src. This is different from krealloc since we don't want to preserve 1543 * the contents of dst. 1544 * 1545 * Leaves dst untouched if src is NULL or length is zero. Returns NULL if memory could 1546 * not be allocated. 1547 */ 1548 static void *copy_array(void *dst, const void *src, size_t n, size_t size, gfp_t flags) 1549 { 1550 size_t alloc_bytes; 1551 void *orig = dst; 1552 size_t bytes; 1553 1554 if (ZERO_OR_NULL_PTR(src)) 1555 goto out; 1556 1557 if (unlikely(check_mul_overflow(n, size, &bytes))) 1558 return NULL; 1559 1560 alloc_bytes = max(ksize(orig), kmalloc_size_roundup(bytes)); 1561 dst = krealloc(orig, alloc_bytes, flags); 1562 if (!dst) { 1563 kfree(orig); 1564 return NULL; 1565 } 1566 1567 memcpy(dst, src, bytes); 1568 out: 1569 return dst ? dst : ZERO_SIZE_PTR; 1570 } 1571 1572 /* resize an array from old_n items to new_n items. the array is reallocated if it's too 1573 * small to hold new_n items. new items are zeroed out if the array grows. 1574 * 1575 * Contrary to krealloc_array, does not free arr if new_n is zero. 1576 */ 1577 static void *realloc_array(void *arr, size_t old_n, size_t new_n, size_t size) 1578 { 1579 size_t alloc_size; 1580 void *new_arr; 1581 1582 if (!new_n || old_n == new_n) 1583 goto out; 1584 1585 alloc_size = kmalloc_size_roundup(size_mul(new_n, size)); 1586 new_arr = krealloc(arr, alloc_size, GFP_KERNEL); 1587 if (!new_arr) { 1588 kfree(arr); 1589 return NULL; 1590 } 1591 arr = new_arr; 1592 1593 if (new_n > old_n) 1594 memset(arr + old_n * size, 0, (new_n - old_n) * size); 1595 1596 out: 1597 return arr ? arr : ZERO_SIZE_PTR; 1598 } 1599 1600 static int copy_reference_state(struct bpf_func_state *dst, const struct bpf_func_state *src) 1601 { 1602 dst->refs = copy_array(dst->refs, src->refs, src->acquired_refs, 1603 sizeof(struct bpf_reference_state), GFP_KERNEL); 1604 if (!dst->refs) 1605 return -ENOMEM; 1606 1607 dst->acquired_refs = src->acquired_refs; 1608 return 0; 1609 } 1610 1611 static int copy_stack_state(struct bpf_func_state *dst, const struct bpf_func_state *src) 1612 { 1613 size_t n = src->allocated_stack / BPF_REG_SIZE; 1614 1615 dst->stack = copy_array(dst->stack, src->stack, n, sizeof(struct bpf_stack_state), 1616 GFP_KERNEL); 1617 if (!dst->stack) 1618 return -ENOMEM; 1619 1620 dst->allocated_stack = src->allocated_stack; 1621 return 0; 1622 } 1623 1624 static int resize_reference_state(struct bpf_func_state *state, size_t n) 1625 { 1626 state->refs = realloc_array(state->refs, state->acquired_refs, n, 1627 sizeof(struct bpf_reference_state)); 1628 if (!state->refs) 1629 return -ENOMEM; 1630 1631 state->acquired_refs = n; 1632 return 0; 1633 } 1634 1635 static int grow_stack_state(struct bpf_func_state *state, int size) 1636 { 1637 size_t old_n = state->allocated_stack / BPF_REG_SIZE, n = size / BPF_REG_SIZE; 1638 1639 if (old_n >= n) 1640 return 0; 1641 1642 state->stack = realloc_array(state->stack, old_n, n, sizeof(struct bpf_stack_state)); 1643 if (!state->stack) 1644 return -ENOMEM; 1645 1646 state->allocated_stack = size; 1647 return 0; 1648 } 1649 1650 /* Acquire a pointer id from the env and update the state->refs to include 1651 * this new pointer reference. 1652 * On success, returns a valid pointer id to associate with the register 1653 * On failure, returns a negative errno. 1654 */ 1655 static int acquire_reference_state(struct bpf_verifier_env *env, int insn_idx) 1656 { 1657 struct bpf_func_state *state = cur_func(env); 1658 int new_ofs = state->acquired_refs; 1659 int id, err; 1660 1661 err = resize_reference_state(state, state->acquired_refs + 1); 1662 if (err) 1663 return err; 1664 id = ++env->id_gen; 1665 state->refs[new_ofs].id = id; 1666 state->refs[new_ofs].insn_idx = insn_idx; 1667 state->refs[new_ofs].callback_ref = state->in_callback_fn ? state->frameno : 0; 1668 1669 return id; 1670 } 1671 1672 /* release function corresponding to acquire_reference_state(). Idempotent. */ 1673 static int release_reference_state(struct bpf_func_state *state, int ptr_id) 1674 { 1675 int i, last_idx; 1676 1677 last_idx = state->acquired_refs - 1; 1678 for (i = 0; i < state->acquired_refs; i++) { 1679 if (state->refs[i].id == ptr_id) { 1680 /* Cannot release caller references in callbacks */ 1681 if (state->in_callback_fn && state->refs[i].callback_ref != state->frameno) 1682 return -EINVAL; 1683 if (last_idx && i != last_idx) 1684 memcpy(&state->refs[i], &state->refs[last_idx], 1685 sizeof(*state->refs)); 1686 memset(&state->refs[last_idx], 0, sizeof(*state->refs)); 1687 state->acquired_refs--; 1688 return 0; 1689 } 1690 } 1691 return -EINVAL; 1692 } 1693 1694 static void free_func_state(struct bpf_func_state *state) 1695 { 1696 if (!state) 1697 return; 1698 kfree(state->refs); 1699 kfree(state->stack); 1700 kfree(state); 1701 } 1702 1703 static void clear_jmp_history(struct bpf_verifier_state *state) 1704 { 1705 kfree(state->jmp_history); 1706 state->jmp_history = NULL; 1707 state->jmp_history_cnt = 0; 1708 } 1709 1710 static void free_verifier_state(struct bpf_verifier_state *state, 1711 bool free_self) 1712 { 1713 int i; 1714 1715 for (i = 0; i <= state->curframe; i++) { 1716 free_func_state(state->frame[i]); 1717 state->frame[i] = NULL; 1718 } 1719 clear_jmp_history(state); 1720 if (free_self) 1721 kfree(state); 1722 } 1723 1724 /* copy verifier state from src to dst growing dst stack space 1725 * when necessary to accommodate larger src stack 1726 */ 1727 static int copy_func_state(struct bpf_func_state *dst, 1728 const struct bpf_func_state *src) 1729 { 1730 int err; 1731 1732 memcpy(dst, src, offsetof(struct bpf_func_state, acquired_refs)); 1733 err = copy_reference_state(dst, src); 1734 if (err) 1735 return err; 1736 return copy_stack_state(dst, src); 1737 } 1738 1739 static int copy_verifier_state(struct bpf_verifier_state *dst_state, 1740 const struct bpf_verifier_state *src) 1741 { 1742 struct bpf_func_state *dst; 1743 int i, err; 1744 1745 dst_state->jmp_history = copy_array(dst_state->jmp_history, src->jmp_history, 1746 src->jmp_history_cnt, sizeof(struct bpf_idx_pair), 1747 GFP_USER); 1748 if (!dst_state->jmp_history) 1749 return -ENOMEM; 1750 dst_state->jmp_history_cnt = src->jmp_history_cnt; 1751 1752 /* if dst has more stack frames then src frame, free them, this is also 1753 * necessary in case of exceptional exits using bpf_throw. 1754 */ 1755 for (i = src->curframe + 1; i <= dst_state->curframe; i++) { 1756 free_func_state(dst_state->frame[i]); 1757 dst_state->frame[i] = NULL; 1758 } 1759 dst_state->speculative = src->speculative; 1760 dst_state->active_rcu_lock = src->active_rcu_lock; 1761 dst_state->curframe = src->curframe; 1762 dst_state->active_lock.ptr = src->active_lock.ptr; 1763 dst_state->active_lock.id = src->active_lock.id; 1764 dst_state->branches = src->branches; 1765 dst_state->parent = src->parent; 1766 dst_state->first_insn_idx = src->first_insn_idx; 1767 dst_state->last_insn_idx = src->last_insn_idx; 1768 for (i = 0; i <= src->curframe; i++) { 1769 dst = dst_state->frame[i]; 1770 if (!dst) { 1771 dst = kzalloc(sizeof(*dst), GFP_KERNEL); 1772 if (!dst) 1773 return -ENOMEM; 1774 dst_state->frame[i] = dst; 1775 } 1776 err = copy_func_state(dst, src->frame[i]); 1777 if (err) 1778 return err; 1779 } 1780 return 0; 1781 } 1782 1783 static void update_branch_counts(struct bpf_verifier_env *env, struct bpf_verifier_state *st) 1784 { 1785 while (st) { 1786 u32 br = --st->branches; 1787 1788 /* WARN_ON(br > 1) technically makes sense here, 1789 * but see comment in push_stack(), hence: 1790 */ 1791 WARN_ONCE((int)br < 0, 1792 "BUG update_branch_counts:branches_to_explore=%d\n", 1793 br); 1794 if (br) 1795 break; 1796 st = st->parent; 1797 } 1798 } 1799 1800 static int pop_stack(struct bpf_verifier_env *env, int *prev_insn_idx, 1801 int *insn_idx, bool pop_log) 1802 { 1803 struct bpf_verifier_state *cur = env->cur_state; 1804 struct bpf_verifier_stack_elem *elem, *head = env->head; 1805 int err; 1806 1807 if (env->head == NULL) 1808 return -ENOENT; 1809 1810 if (cur) { 1811 err = copy_verifier_state(cur, &head->st); 1812 if (err) 1813 return err; 1814 } 1815 if (pop_log) 1816 bpf_vlog_reset(&env->log, head->log_pos); 1817 if (insn_idx) 1818 *insn_idx = head->insn_idx; 1819 if (prev_insn_idx) 1820 *prev_insn_idx = head->prev_insn_idx; 1821 elem = head->next; 1822 free_verifier_state(&head->st, false); 1823 kfree(head); 1824 env->head = elem; 1825 env->stack_size--; 1826 return 0; 1827 } 1828 1829 static struct bpf_verifier_state *push_stack(struct bpf_verifier_env *env, 1830 int insn_idx, int prev_insn_idx, 1831 bool speculative) 1832 { 1833 struct bpf_verifier_state *cur = env->cur_state; 1834 struct bpf_verifier_stack_elem *elem; 1835 int err; 1836 1837 elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL); 1838 if (!elem) 1839 goto err; 1840 1841 elem->insn_idx = insn_idx; 1842 elem->prev_insn_idx = prev_insn_idx; 1843 elem->next = env->head; 1844 elem->log_pos = env->log.end_pos; 1845 env->head = elem; 1846 env->stack_size++; 1847 err = copy_verifier_state(&elem->st, cur); 1848 if (err) 1849 goto err; 1850 elem->st.speculative |= speculative; 1851 if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) { 1852 verbose(env, "The sequence of %d jumps is too complex.\n", 1853 env->stack_size); 1854 goto err; 1855 } 1856 if (elem->st.parent) { 1857 ++elem->st.parent->branches; 1858 /* WARN_ON(branches > 2) technically makes sense here, 1859 * but 1860 * 1. speculative states will bump 'branches' for non-branch 1861 * instructions 1862 * 2. is_state_visited() heuristics may decide not to create 1863 * a new state for a sequence of branches and all such current 1864 * and cloned states will be pointing to a single parent state 1865 * which might have large 'branches' count. 1866 */ 1867 } 1868 return &elem->st; 1869 err: 1870 free_verifier_state(env->cur_state, true); 1871 env->cur_state = NULL; 1872 /* pop all elements and return */ 1873 while (!pop_stack(env, NULL, NULL, false)); 1874 return NULL; 1875 } 1876 1877 #define CALLER_SAVED_REGS 6 1878 static const int caller_saved[CALLER_SAVED_REGS] = { 1879 BPF_REG_0, BPF_REG_1, BPF_REG_2, BPF_REG_3, BPF_REG_4, BPF_REG_5 1880 }; 1881 1882 /* This helper doesn't clear reg->id */ 1883 static void ___mark_reg_known(struct bpf_reg_state *reg, u64 imm) 1884 { 1885 reg->var_off = tnum_const(imm); 1886 reg->smin_value = (s64)imm; 1887 reg->smax_value = (s64)imm; 1888 reg->umin_value = imm; 1889 reg->umax_value = imm; 1890 1891 reg->s32_min_value = (s32)imm; 1892 reg->s32_max_value = (s32)imm; 1893 reg->u32_min_value = (u32)imm; 1894 reg->u32_max_value = (u32)imm; 1895 } 1896 1897 /* Mark the unknown part of a register (variable offset or scalar value) as 1898 * known to have the value @imm. 1899 */ 1900 static void __mark_reg_known(struct bpf_reg_state *reg, u64 imm) 1901 { 1902 /* Clear off and union(map_ptr, range) */ 1903 memset(((u8 *)reg) + sizeof(reg->type), 0, 1904 offsetof(struct bpf_reg_state, var_off) - sizeof(reg->type)); 1905 reg->id = 0; 1906 reg->ref_obj_id = 0; 1907 ___mark_reg_known(reg, imm); 1908 } 1909 1910 static void __mark_reg32_known(struct bpf_reg_state *reg, u64 imm) 1911 { 1912 reg->var_off = tnum_const_subreg(reg->var_off, imm); 1913 reg->s32_min_value = (s32)imm; 1914 reg->s32_max_value = (s32)imm; 1915 reg->u32_min_value = (u32)imm; 1916 reg->u32_max_value = (u32)imm; 1917 } 1918 1919 /* Mark the 'variable offset' part of a register as zero. This should be 1920 * used only on registers holding a pointer type. 1921 */ 1922 static void __mark_reg_known_zero(struct bpf_reg_state *reg) 1923 { 1924 __mark_reg_known(reg, 0); 1925 } 1926 1927 static void __mark_reg_const_zero(struct bpf_reg_state *reg) 1928 { 1929 __mark_reg_known(reg, 0); 1930 reg->type = SCALAR_VALUE; 1931 } 1932 1933 static void mark_reg_known_zero(struct bpf_verifier_env *env, 1934 struct bpf_reg_state *regs, u32 regno) 1935 { 1936 if (WARN_ON(regno >= MAX_BPF_REG)) { 1937 verbose(env, "mark_reg_known_zero(regs, %u)\n", regno); 1938 /* Something bad happened, let's kill all regs */ 1939 for (regno = 0; regno < MAX_BPF_REG; regno++) 1940 __mark_reg_not_init(env, regs + regno); 1941 return; 1942 } 1943 __mark_reg_known_zero(regs + regno); 1944 } 1945 1946 static void __mark_dynptr_reg(struct bpf_reg_state *reg, enum bpf_dynptr_type type, 1947 bool first_slot, int dynptr_id) 1948 { 1949 /* reg->type has no meaning for STACK_DYNPTR, but when we set reg for 1950 * callback arguments, it does need to be CONST_PTR_TO_DYNPTR, so simply 1951 * set it unconditionally as it is ignored for STACK_DYNPTR anyway. 1952 */ 1953 __mark_reg_known_zero(reg); 1954 reg->type = CONST_PTR_TO_DYNPTR; 1955 /* Give each dynptr a unique id to uniquely associate slices to it. */ 1956 reg->id = dynptr_id; 1957 reg->dynptr.type = type; 1958 reg->dynptr.first_slot = first_slot; 1959 } 1960 1961 static void mark_ptr_not_null_reg(struct bpf_reg_state *reg) 1962 { 1963 if (base_type(reg->type) == PTR_TO_MAP_VALUE) { 1964 const struct bpf_map *map = reg->map_ptr; 1965 1966 if (map->inner_map_meta) { 1967 reg->type = CONST_PTR_TO_MAP; 1968 reg->map_ptr = map->inner_map_meta; 1969 /* transfer reg's id which is unique for every map_lookup_elem 1970 * as UID of the inner map. 1971 */ 1972 if (btf_record_has_field(map->inner_map_meta->record, BPF_TIMER)) 1973 reg->map_uid = reg->id; 1974 } else if (map->map_type == BPF_MAP_TYPE_XSKMAP) { 1975 reg->type = PTR_TO_XDP_SOCK; 1976 } else if (map->map_type == BPF_MAP_TYPE_SOCKMAP || 1977 map->map_type == BPF_MAP_TYPE_SOCKHASH) { 1978 reg->type = PTR_TO_SOCKET; 1979 } else { 1980 reg->type = PTR_TO_MAP_VALUE; 1981 } 1982 return; 1983 } 1984 1985 reg->type &= ~PTR_MAYBE_NULL; 1986 } 1987 1988 static void mark_reg_graph_node(struct bpf_reg_state *regs, u32 regno, 1989 struct btf_field_graph_root *ds_head) 1990 { 1991 __mark_reg_known_zero(®s[regno]); 1992 regs[regno].type = PTR_TO_BTF_ID | MEM_ALLOC; 1993 regs[regno].btf = ds_head->btf; 1994 regs[regno].btf_id = ds_head->value_btf_id; 1995 regs[regno].off = ds_head->node_offset; 1996 } 1997 1998 static bool reg_is_pkt_pointer(const struct bpf_reg_state *reg) 1999 { 2000 return type_is_pkt_pointer(reg->type); 2001 } 2002 2003 static bool reg_is_pkt_pointer_any(const struct bpf_reg_state *reg) 2004 { 2005 return reg_is_pkt_pointer(reg) || 2006 reg->type == PTR_TO_PACKET_END; 2007 } 2008 2009 static bool reg_is_dynptr_slice_pkt(const struct bpf_reg_state *reg) 2010 { 2011 return base_type(reg->type) == PTR_TO_MEM && 2012 (reg->type & DYNPTR_TYPE_SKB || reg->type & DYNPTR_TYPE_XDP); 2013 } 2014 2015 /* Unmodified PTR_TO_PACKET[_META,_END] register from ctx access. */ 2016 static bool reg_is_init_pkt_pointer(const struct bpf_reg_state *reg, 2017 enum bpf_reg_type which) 2018 { 2019 /* The register can already have a range from prior markings. 2020 * This is fine as long as it hasn't been advanced from its 2021 * origin. 2022 */ 2023 return reg->type == which && 2024 reg->id == 0 && 2025 reg->off == 0 && 2026 tnum_equals_const(reg->var_off, 0); 2027 } 2028 2029 /* Reset the min/max bounds of a register */ 2030 static void __mark_reg_unbounded(struct bpf_reg_state *reg) 2031 { 2032 reg->smin_value = S64_MIN; 2033 reg->smax_value = S64_MAX; 2034 reg->umin_value = 0; 2035 reg->umax_value = U64_MAX; 2036 2037 reg->s32_min_value = S32_MIN; 2038 reg->s32_max_value = S32_MAX; 2039 reg->u32_min_value = 0; 2040 reg->u32_max_value = U32_MAX; 2041 } 2042 2043 static void __mark_reg64_unbounded(struct bpf_reg_state *reg) 2044 { 2045 reg->smin_value = S64_MIN; 2046 reg->smax_value = S64_MAX; 2047 reg->umin_value = 0; 2048 reg->umax_value = U64_MAX; 2049 } 2050 2051 static void __mark_reg32_unbounded(struct bpf_reg_state *reg) 2052 { 2053 reg->s32_min_value = S32_MIN; 2054 reg->s32_max_value = S32_MAX; 2055 reg->u32_min_value = 0; 2056 reg->u32_max_value = U32_MAX; 2057 } 2058 2059 static void __update_reg32_bounds(struct bpf_reg_state *reg) 2060 { 2061 struct tnum var32_off = tnum_subreg(reg->var_off); 2062 2063 /* min signed is max(sign bit) | min(other bits) */ 2064 reg->s32_min_value = max_t(s32, reg->s32_min_value, 2065 var32_off.value | (var32_off.mask & S32_MIN)); 2066 /* max signed is min(sign bit) | max(other bits) */ 2067 reg->s32_max_value = min_t(s32, reg->s32_max_value, 2068 var32_off.value | (var32_off.mask & S32_MAX)); 2069 reg->u32_min_value = max_t(u32, reg->u32_min_value, (u32)var32_off.value); 2070 reg->u32_max_value = min(reg->u32_max_value, 2071 (u32)(var32_off.value | var32_off.mask)); 2072 } 2073 2074 static void __update_reg64_bounds(struct bpf_reg_state *reg) 2075 { 2076 /* min signed is max(sign bit) | min(other bits) */ 2077 reg->smin_value = max_t(s64, reg->smin_value, 2078 reg->var_off.value | (reg->var_off.mask & S64_MIN)); 2079 /* max signed is min(sign bit) | max(other bits) */ 2080 reg->smax_value = min_t(s64, reg->smax_value, 2081 reg->var_off.value | (reg->var_off.mask & S64_MAX)); 2082 reg->umin_value = max(reg->umin_value, reg->var_off.value); 2083 reg->umax_value = min(reg->umax_value, 2084 reg->var_off.value | reg->var_off.mask); 2085 } 2086 2087 static void __update_reg_bounds(struct bpf_reg_state *reg) 2088 { 2089 __update_reg32_bounds(reg); 2090 __update_reg64_bounds(reg); 2091 } 2092 2093 /* Uses signed min/max values to inform unsigned, and vice-versa */ 2094 static void __reg32_deduce_bounds(struct bpf_reg_state *reg) 2095 { 2096 /* Learn sign from signed bounds. 2097 * If we cannot cross the sign boundary, then signed and unsigned bounds 2098 * are the same, so combine. This works even in the negative case, e.g. 2099 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff. 2100 */ 2101 if (reg->s32_min_value >= 0 || reg->s32_max_value < 0) { 2102 reg->s32_min_value = reg->u32_min_value = 2103 max_t(u32, reg->s32_min_value, reg->u32_min_value); 2104 reg->s32_max_value = reg->u32_max_value = 2105 min_t(u32, reg->s32_max_value, reg->u32_max_value); 2106 return; 2107 } 2108 /* Learn sign from unsigned bounds. Signed bounds cross the sign 2109 * boundary, so we must be careful. 2110 */ 2111 if ((s32)reg->u32_max_value >= 0) { 2112 /* Positive. We can't learn anything from the smin, but smax 2113 * is positive, hence safe. 2114 */ 2115 reg->s32_min_value = reg->u32_min_value; 2116 reg->s32_max_value = reg->u32_max_value = 2117 min_t(u32, reg->s32_max_value, reg->u32_max_value); 2118 } else if ((s32)reg->u32_min_value < 0) { 2119 /* Negative. We can't learn anything from the smax, but smin 2120 * is negative, hence safe. 2121 */ 2122 reg->s32_min_value = reg->u32_min_value = 2123 max_t(u32, reg->s32_min_value, reg->u32_min_value); 2124 reg->s32_max_value = reg->u32_max_value; 2125 } 2126 } 2127 2128 static void __reg64_deduce_bounds(struct bpf_reg_state *reg) 2129 { 2130 /* Learn sign from signed bounds. 2131 * If we cannot cross the sign boundary, then signed and unsigned bounds 2132 * are the same, so combine. This works even in the negative case, e.g. 2133 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff. 2134 */ 2135 if (reg->smin_value >= 0 || reg->smax_value < 0) { 2136 reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value, 2137 reg->umin_value); 2138 reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value, 2139 reg->umax_value); 2140 return; 2141 } 2142 /* Learn sign from unsigned bounds. Signed bounds cross the sign 2143 * boundary, so we must be careful. 2144 */ 2145 if ((s64)reg->umax_value >= 0) { 2146 /* Positive. We can't learn anything from the smin, but smax 2147 * is positive, hence safe. 2148 */ 2149 reg->smin_value = reg->umin_value; 2150 reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value, 2151 reg->umax_value); 2152 } else if ((s64)reg->umin_value < 0) { 2153 /* Negative. We can't learn anything from the smax, but smin 2154 * is negative, hence safe. 2155 */ 2156 reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value, 2157 reg->umin_value); 2158 reg->smax_value = reg->umax_value; 2159 } 2160 } 2161 2162 static void __reg_deduce_bounds(struct bpf_reg_state *reg) 2163 { 2164 __reg32_deduce_bounds(reg); 2165 __reg64_deduce_bounds(reg); 2166 } 2167 2168 /* Attempts to improve var_off based on unsigned min/max information */ 2169 static void __reg_bound_offset(struct bpf_reg_state *reg) 2170 { 2171 struct tnum var64_off = tnum_intersect(reg->var_off, 2172 tnum_range(reg->umin_value, 2173 reg->umax_value)); 2174 struct tnum var32_off = tnum_intersect(tnum_subreg(var64_off), 2175 tnum_range(reg->u32_min_value, 2176 reg->u32_max_value)); 2177 2178 reg->var_off = tnum_or(tnum_clear_subreg(var64_off), var32_off); 2179 } 2180 2181 static void reg_bounds_sync(struct bpf_reg_state *reg) 2182 { 2183 /* We might have learned new bounds from the var_off. */ 2184 __update_reg_bounds(reg); 2185 /* We might have learned something about the sign bit. */ 2186 __reg_deduce_bounds(reg); 2187 /* We might have learned some bits from the bounds. */ 2188 __reg_bound_offset(reg); 2189 /* Intersecting with the old var_off might have improved our bounds 2190 * slightly, e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc), 2191 * then new var_off is (0; 0x7f...fc) which improves our umax. 2192 */ 2193 __update_reg_bounds(reg); 2194 } 2195 2196 static bool __reg32_bound_s64(s32 a) 2197 { 2198 return a >= 0 && a <= S32_MAX; 2199 } 2200 2201 static void __reg_assign_32_into_64(struct bpf_reg_state *reg) 2202 { 2203 reg->umin_value = reg->u32_min_value; 2204 reg->umax_value = reg->u32_max_value; 2205 2206 /* Attempt to pull 32-bit signed bounds into 64-bit bounds but must 2207 * be positive otherwise set to worse case bounds and refine later 2208 * from tnum. 2209 */ 2210 if (__reg32_bound_s64(reg->s32_min_value) && 2211 __reg32_bound_s64(reg->s32_max_value)) { 2212 reg->smin_value = reg->s32_min_value; 2213 reg->smax_value = reg->s32_max_value; 2214 } else { 2215 reg->smin_value = 0; 2216 reg->smax_value = U32_MAX; 2217 } 2218 } 2219 2220 static void __reg_combine_32_into_64(struct bpf_reg_state *reg) 2221 { 2222 /* special case when 64-bit register has upper 32-bit register 2223 * zeroed. Typically happens after zext or <<32, >>32 sequence 2224 * allowing us to use 32-bit bounds directly, 2225 */ 2226 if (tnum_equals_const(tnum_clear_subreg(reg->var_off), 0)) { 2227 __reg_assign_32_into_64(reg); 2228 } else { 2229 /* Otherwise the best we can do is push lower 32bit known and 2230 * unknown bits into register (var_off set from jmp logic) 2231 * then learn as much as possible from the 64-bit tnum 2232 * known and unknown bits. The previous smin/smax bounds are 2233 * invalid here because of jmp32 compare so mark them unknown 2234 * so they do not impact tnum bounds calculation. 2235 */ 2236 __mark_reg64_unbounded(reg); 2237 } 2238 reg_bounds_sync(reg); 2239 } 2240 2241 static bool __reg64_bound_s32(s64 a) 2242 { 2243 return a >= S32_MIN && a <= S32_MAX; 2244 } 2245 2246 static bool __reg64_bound_u32(u64 a) 2247 { 2248 return a >= U32_MIN && a <= U32_MAX; 2249 } 2250 2251 static void __reg_combine_64_into_32(struct bpf_reg_state *reg) 2252 { 2253 __mark_reg32_unbounded(reg); 2254 if (__reg64_bound_s32(reg->smin_value) && __reg64_bound_s32(reg->smax_value)) { 2255 reg->s32_min_value = (s32)reg->smin_value; 2256 reg->s32_max_value = (s32)reg->smax_value; 2257 } 2258 if (__reg64_bound_u32(reg->umin_value) && __reg64_bound_u32(reg->umax_value)) { 2259 reg->u32_min_value = (u32)reg->umin_value; 2260 reg->u32_max_value = (u32)reg->umax_value; 2261 } 2262 reg_bounds_sync(reg); 2263 } 2264 2265 /* Mark a register as having a completely unknown (scalar) value. */ 2266 static void __mark_reg_unknown(const struct bpf_verifier_env *env, 2267 struct bpf_reg_state *reg) 2268 { 2269 /* 2270 * Clear type, off, and union(map_ptr, range) and 2271 * padding between 'type' and union 2272 */ 2273 memset(reg, 0, offsetof(struct bpf_reg_state, var_off)); 2274 reg->type = SCALAR_VALUE; 2275 reg->id = 0; 2276 reg->ref_obj_id = 0; 2277 reg->var_off = tnum_unknown; 2278 reg->frameno = 0; 2279 reg->precise = !env->bpf_capable; 2280 __mark_reg_unbounded(reg); 2281 } 2282 2283 static void mark_reg_unknown(struct bpf_verifier_env *env, 2284 struct bpf_reg_state *regs, u32 regno) 2285 { 2286 if (WARN_ON(regno >= MAX_BPF_REG)) { 2287 verbose(env, "mark_reg_unknown(regs, %u)\n", regno); 2288 /* Something bad happened, let's kill all regs except FP */ 2289 for (regno = 0; regno < BPF_REG_FP; regno++) 2290 __mark_reg_not_init(env, regs + regno); 2291 return; 2292 } 2293 __mark_reg_unknown(env, regs + regno); 2294 } 2295 2296 static void __mark_reg_not_init(const struct bpf_verifier_env *env, 2297 struct bpf_reg_state *reg) 2298 { 2299 __mark_reg_unknown(env, reg); 2300 reg->type = NOT_INIT; 2301 } 2302 2303 static void mark_reg_not_init(struct bpf_verifier_env *env, 2304 struct bpf_reg_state *regs, u32 regno) 2305 { 2306 if (WARN_ON(regno >= MAX_BPF_REG)) { 2307 verbose(env, "mark_reg_not_init(regs, %u)\n", regno); 2308 /* Something bad happened, let's kill all regs except FP */ 2309 for (regno = 0; regno < BPF_REG_FP; regno++) 2310 __mark_reg_not_init(env, regs + regno); 2311 return; 2312 } 2313 __mark_reg_not_init(env, regs + regno); 2314 } 2315 2316 static void mark_btf_ld_reg(struct bpf_verifier_env *env, 2317 struct bpf_reg_state *regs, u32 regno, 2318 enum bpf_reg_type reg_type, 2319 struct btf *btf, u32 btf_id, 2320 enum bpf_type_flag flag) 2321 { 2322 if (reg_type == SCALAR_VALUE) { 2323 mark_reg_unknown(env, regs, regno); 2324 return; 2325 } 2326 mark_reg_known_zero(env, regs, regno); 2327 regs[regno].type = PTR_TO_BTF_ID | flag; 2328 regs[regno].btf = btf; 2329 regs[regno].btf_id = btf_id; 2330 } 2331 2332 #define DEF_NOT_SUBREG (0) 2333 static void init_reg_state(struct bpf_verifier_env *env, 2334 struct bpf_func_state *state) 2335 { 2336 struct bpf_reg_state *regs = state->regs; 2337 int i; 2338 2339 for (i = 0; i < MAX_BPF_REG; i++) { 2340 mark_reg_not_init(env, regs, i); 2341 regs[i].live = REG_LIVE_NONE; 2342 regs[i].parent = NULL; 2343 regs[i].subreg_def = DEF_NOT_SUBREG; 2344 } 2345 2346 /* frame pointer */ 2347 regs[BPF_REG_FP].type = PTR_TO_STACK; 2348 mark_reg_known_zero(env, regs, BPF_REG_FP); 2349 regs[BPF_REG_FP].frameno = state->frameno; 2350 } 2351 2352 #define BPF_MAIN_FUNC (-1) 2353 static void init_func_state(struct bpf_verifier_env *env, 2354 struct bpf_func_state *state, 2355 int callsite, int frameno, int subprogno) 2356 { 2357 state->callsite = callsite; 2358 state->frameno = frameno; 2359 state->subprogno = subprogno; 2360 state->callback_ret_range = tnum_range(0, 0); 2361 init_reg_state(env, state); 2362 mark_verifier_state_scratched(env); 2363 } 2364 2365 /* Similar to push_stack(), but for async callbacks */ 2366 static struct bpf_verifier_state *push_async_cb(struct bpf_verifier_env *env, 2367 int insn_idx, int prev_insn_idx, 2368 int subprog) 2369 { 2370 struct bpf_verifier_stack_elem *elem; 2371 struct bpf_func_state *frame; 2372 2373 elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL); 2374 if (!elem) 2375 goto err; 2376 2377 elem->insn_idx = insn_idx; 2378 elem->prev_insn_idx = prev_insn_idx; 2379 elem->next = env->head; 2380 elem->log_pos = env->log.end_pos; 2381 env->head = elem; 2382 env->stack_size++; 2383 if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) { 2384 verbose(env, 2385 "The sequence of %d jumps is too complex for async cb.\n", 2386 env->stack_size); 2387 goto err; 2388 } 2389 /* Unlike push_stack() do not copy_verifier_state(). 2390 * The caller state doesn't matter. 2391 * This is async callback. It starts in a fresh stack. 2392 * Initialize it similar to do_check_common(). 2393 */ 2394 elem->st.branches = 1; 2395 frame = kzalloc(sizeof(*frame), GFP_KERNEL); 2396 if (!frame) 2397 goto err; 2398 init_func_state(env, frame, 2399 BPF_MAIN_FUNC /* callsite */, 2400 0 /* frameno within this callchain */, 2401 subprog /* subprog number within this prog */); 2402 elem->st.frame[0] = frame; 2403 return &elem->st; 2404 err: 2405 free_verifier_state(env->cur_state, true); 2406 env->cur_state = NULL; 2407 /* pop all elements and return */ 2408 while (!pop_stack(env, NULL, NULL, false)); 2409 return NULL; 2410 } 2411 2412 2413 enum reg_arg_type { 2414 SRC_OP, /* register is used as source operand */ 2415 DST_OP, /* register is used as destination operand */ 2416 DST_OP_NO_MARK /* same as above, check only, don't mark */ 2417 }; 2418 2419 static int cmp_subprogs(const void *a, const void *b) 2420 { 2421 return ((struct bpf_subprog_info *)a)->start - 2422 ((struct bpf_subprog_info *)b)->start; 2423 } 2424 2425 static int find_subprog(struct bpf_verifier_env *env, int off) 2426 { 2427 struct bpf_subprog_info *p; 2428 2429 p = bsearch(&off, env->subprog_info, env->subprog_cnt, 2430 sizeof(env->subprog_info[0]), cmp_subprogs); 2431 if (!p) 2432 return -ENOENT; 2433 return p - env->subprog_info; 2434 2435 } 2436 2437 static int add_subprog(struct bpf_verifier_env *env, int off) 2438 { 2439 int insn_cnt = env->prog->len; 2440 int ret; 2441 2442 if (off >= insn_cnt || off < 0) { 2443 verbose(env, "call to invalid destination\n"); 2444 return -EINVAL; 2445 } 2446 ret = find_subprog(env, off); 2447 if (ret >= 0) 2448 return ret; 2449 if (env->subprog_cnt >= BPF_MAX_SUBPROGS) { 2450 verbose(env, "too many subprograms\n"); 2451 return -E2BIG; 2452 } 2453 /* determine subprog starts. The end is one before the next starts */ 2454 env->subprog_info[env->subprog_cnt++].start = off; 2455 sort(env->subprog_info, env->subprog_cnt, 2456 sizeof(env->subprog_info[0]), cmp_subprogs, NULL); 2457 return env->subprog_cnt - 1; 2458 } 2459 2460 static int bpf_find_exception_callback_insn_off(struct bpf_verifier_env *env) 2461 { 2462 struct bpf_prog_aux *aux = env->prog->aux; 2463 struct btf *btf = aux->btf; 2464 const struct btf_type *t; 2465 u32 main_btf_id, id; 2466 const char *name; 2467 int ret, i; 2468 2469 /* Non-zero func_info_cnt implies valid btf */ 2470 if (!aux->func_info_cnt) 2471 return 0; 2472 main_btf_id = aux->func_info[0].type_id; 2473 2474 t = btf_type_by_id(btf, main_btf_id); 2475 if (!t) { 2476 verbose(env, "invalid btf id for main subprog in func_info\n"); 2477 return -EINVAL; 2478 } 2479 2480 name = btf_find_decl_tag_value(btf, t, -1, "exception_callback:"); 2481 if (IS_ERR(name)) { 2482 ret = PTR_ERR(name); 2483 /* If there is no tag present, there is no exception callback */ 2484 if (ret == -ENOENT) 2485 ret = 0; 2486 else if (ret == -EEXIST) 2487 verbose(env, "multiple exception callback tags for main subprog\n"); 2488 return ret; 2489 } 2490 2491 ret = btf_find_by_name_kind(btf, name, BTF_KIND_FUNC); 2492 if (ret < 0) { 2493 verbose(env, "exception callback '%s' could not be found in BTF\n", name); 2494 return ret; 2495 } 2496 id = ret; 2497 t = btf_type_by_id(btf, id); 2498 if (btf_func_linkage(t) != BTF_FUNC_GLOBAL) { 2499 verbose(env, "exception callback '%s' must have global linkage\n", name); 2500 return -EINVAL; 2501 } 2502 ret = 0; 2503 for (i = 0; i < aux->func_info_cnt; i++) { 2504 if (aux->func_info[i].type_id != id) 2505 continue; 2506 ret = aux->func_info[i].insn_off; 2507 /* Further func_info and subprog checks will also happen 2508 * later, so assume this is the right insn_off for now. 2509 */ 2510 if (!ret) { 2511 verbose(env, "invalid exception callback insn_off in func_info: 0\n"); 2512 ret = -EINVAL; 2513 } 2514 } 2515 if (!ret) { 2516 verbose(env, "exception callback type id not found in func_info\n"); 2517 ret = -EINVAL; 2518 } 2519 return ret; 2520 } 2521 2522 #define MAX_KFUNC_DESCS 256 2523 #define MAX_KFUNC_BTFS 256 2524 2525 struct bpf_kfunc_desc { 2526 struct btf_func_model func_model; 2527 u32 func_id; 2528 s32 imm; 2529 u16 offset; 2530 unsigned long addr; 2531 }; 2532 2533 struct bpf_kfunc_btf { 2534 struct btf *btf; 2535 struct module *module; 2536 u16 offset; 2537 }; 2538 2539 struct bpf_kfunc_desc_tab { 2540 /* Sorted by func_id (BTF ID) and offset (fd_array offset) during 2541 * verification. JITs do lookups by bpf_insn, where func_id may not be 2542 * available, therefore at the end of verification do_misc_fixups() 2543 * sorts this by imm and offset. 2544 */ 2545 struct bpf_kfunc_desc descs[MAX_KFUNC_DESCS]; 2546 u32 nr_descs; 2547 }; 2548 2549 struct bpf_kfunc_btf_tab { 2550 struct bpf_kfunc_btf descs[MAX_KFUNC_BTFS]; 2551 u32 nr_descs; 2552 }; 2553 2554 static int kfunc_desc_cmp_by_id_off(const void *a, const void *b) 2555 { 2556 const struct bpf_kfunc_desc *d0 = a; 2557 const struct bpf_kfunc_desc *d1 = b; 2558 2559 /* func_id is not greater than BTF_MAX_TYPE */ 2560 return d0->func_id - d1->func_id ?: d0->offset - d1->offset; 2561 } 2562 2563 static int kfunc_btf_cmp_by_off(const void *a, const void *b) 2564 { 2565 const struct bpf_kfunc_btf *d0 = a; 2566 const struct bpf_kfunc_btf *d1 = b; 2567 2568 return d0->offset - d1->offset; 2569 } 2570 2571 static const struct bpf_kfunc_desc * 2572 find_kfunc_desc(const struct bpf_prog *prog, u32 func_id, u16 offset) 2573 { 2574 struct bpf_kfunc_desc desc = { 2575 .func_id = func_id, 2576 .offset = offset, 2577 }; 2578 struct bpf_kfunc_desc_tab *tab; 2579 2580 tab = prog->aux->kfunc_tab; 2581 return bsearch(&desc, tab->descs, tab->nr_descs, 2582 sizeof(tab->descs[0]), kfunc_desc_cmp_by_id_off); 2583 } 2584 2585 int bpf_get_kfunc_addr(const struct bpf_prog *prog, u32 func_id, 2586 u16 btf_fd_idx, u8 **func_addr) 2587 { 2588 const struct bpf_kfunc_desc *desc; 2589 2590 desc = find_kfunc_desc(prog, func_id, btf_fd_idx); 2591 if (!desc) 2592 return -EFAULT; 2593 2594 *func_addr = (u8 *)desc->addr; 2595 return 0; 2596 } 2597 2598 static struct btf *__find_kfunc_desc_btf(struct bpf_verifier_env *env, 2599 s16 offset) 2600 { 2601 struct bpf_kfunc_btf kf_btf = { .offset = offset }; 2602 struct bpf_kfunc_btf_tab *tab; 2603 struct bpf_kfunc_btf *b; 2604 struct module *mod; 2605 struct btf *btf; 2606 int btf_fd; 2607 2608 tab = env->prog->aux->kfunc_btf_tab; 2609 b = bsearch(&kf_btf, tab->descs, tab->nr_descs, 2610 sizeof(tab->descs[0]), kfunc_btf_cmp_by_off); 2611 if (!b) { 2612 if (tab->nr_descs == MAX_KFUNC_BTFS) { 2613 verbose(env, "too many different module BTFs\n"); 2614 return ERR_PTR(-E2BIG); 2615 } 2616 2617 if (bpfptr_is_null(env->fd_array)) { 2618 verbose(env, "kfunc offset > 0 without fd_array is invalid\n"); 2619 return ERR_PTR(-EPROTO); 2620 } 2621 2622 if (copy_from_bpfptr_offset(&btf_fd, env->fd_array, 2623 offset * sizeof(btf_fd), 2624 sizeof(btf_fd))) 2625 return ERR_PTR(-EFAULT); 2626 2627 btf = btf_get_by_fd(btf_fd); 2628 if (IS_ERR(btf)) { 2629 verbose(env, "invalid module BTF fd specified\n"); 2630 return btf; 2631 } 2632 2633 if (!btf_is_module(btf)) { 2634 verbose(env, "BTF fd for kfunc is not a module BTF\n"); 2635 btf_put(btf); 2636 return ERR_PTR(-EINVAL); 2637 } 2638 2639 mod = btf_try_get_module(btf); 2640 if (!mod) { 2641 btf_put(btf); 2642 return ERR_PTR(-ENXIO); 2643 } 2644 2645 b = &tab->descs[tab->nr_descs++]; 2646 b->btf = btf; 2647 b->module = mod; 2648 b->offset = offset; 2649 2650 sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]), 2651 kfunc_btf_cmp_by_off, NULL); 2652 } 2653 return b->btf; 2654 } 2655 2656 void bpf_free_kfunc_btf_tab(struct bpf_kfunc_btf_tab *tab) 2657 { 2658 if (!tab) 2659 return; 2660 2661 while (tab->nr_descs--) { 2662 module_put(tab->descs[tab->nr_descs].module); 2663 btf_put(tab->descs[tab->nr_descs].btf); 2664 } 2665 kfree(tab); 2666 } 2667 2668 static struct btf *find_kfunc_desc_btf(struct bpf_verifier_env *env, s16 offset) 2669 { 2670 if (offset) { 2671 if (offset < 0) { 2672 /* In the future, this can be allowed to increase limit 2673 * of fd index into fd_array, interpreted as u16. 2674 */ 2675 verbose(env, "negative offset disallowed for kernel module function call\n"); 2676 return ERR_PTR(-EINVAL); 2677 } 2678 2679 return __find_kfunc_desc_btf(env, offset); 2680 } 2681 return btf_vmlinux ?: ERR_PTR(-ENOENT); 2682 } 2683 2684 static int add_kfunc_call(struct bpf_verifier_env *env, u32 func_id, s16 offset) 2685 { 2686 const struct btf_type *func, *func_proto; 2687 struct bpf_kfunc_btf_tab *btf_tab; 2688 struct bpf_kfunc_desc_tab *tab; 2689 struct bpf_prog_aux *prog_aux; 2690 struct bpf_kfunc_desc *desc; 2691 const char *func_name; 2692 struct btf *desc_btf; 2693 unsigned long call_imm; 2694 unsigned long addr; 2695 int err; 2696 2697 prog_aux = env->prog->aux; 2698 tab = prog_aux->kfunc_tab; 2699 btf_tab = prog_aux->kfunc_btf_tab; 2700 if (!tab) { 2701 if (!btf_vmlinux) { 2702 verbose(env, "calling kernel function is not supported without CONFIG_DEBUG_INFO_BTF\n"); 2703 return -ENOTSUPP; 2704 } 2705 2706 if (!env->prog->jit_requested) { 2707 verbose(env, "JIT is required for calling kernel function\n"); 2708 return -ENOTSUPP; 2709 } 2710 2711 if (!bpf_jit_supports_kfunc_call()) { 2712 verbose(env, "JIT does not support calling kernel function\n"); 2713 return -ENOTSUPP; 2714 } 2715 2716 if (!env->prog->gpl_compatible) { 2717 verbose(env, "cannot call kernel function from non-GPL compatible program\n"); 2718 return -EINVAL; 2719 } 2720 2721 tab = kzalloc(sizeof(*tab), GFP_KERNEL); 2722 if (!tab) 2723 return -ENOMEM; 2724 prog_aux->kfunc_tab = tab; 2725 } 2726 2727 /* func_id == 0 is always invalid, but instead of returning an error, be 2728 * conservative and wait until the code elimination pass before returning 2729 * error, so that invalid calls that get pruned out can be in BPF programs 2730 * loaded from userspace. It is also required that offset be untouched 2731 * for such calls. 2732 */ 2733 if (!func_id && !offset) 2734 return 0; 2735 2736 if (!btf_tab && offset) { 2737 btf_tab = kzalloc(sizeof(*btf_tab), GFP_KERNEL); 2738 if (!btf_tab) 2739 return -ENOMEM; 2740 prog_aux->kfunc_btf_tab = btf_tab; 2741 } 2742 2743 desc_btf = find_kfunc_desc_btf(env, offset); 2744 if (IS_ERR(desc_btf)) { 2745 verbose(env, "failed to find BTF for kernel function\n"); 2746 return PTR_ERR(desc_btf); 2747 } 2748 2749 if (find_kfunc_desc(env->prog, func_id, offset)) 2750 return 0; 2751 2752 if (tab->nr_descs == MAX_KFUNC_DESCS) { 2753 verbose(env, "too many different kernel function calls\n"); 2754 return -E2BIG; 2755 } 2756 2757 func = btf_type_by_id(desc_btf, func_id); 2758 if (!func || !btf_type_is_func(func)) { 2759 verbose(env, "kernel btf_id %u is not a function\n", 2760 func_id); 2761 return -EINVAL; 2762 } 2763 func_proto = btf_type_by_id(desc_btf, func->type); 2764 if (!func_proto || !btf_type_is_func_proto(func_proto)) { 2765 verbose(env, "kernel function btf_id %u does not have a valid func_proto\n", 2766 func_id); 2767 return -EINVAL; 2768 } 2769 2770 func_name = btf_name_by_offset(desc_btf, func->name_off); 2771 addr = kallsyms_lookup_name(func_name); 2772 if (!addr) { 2773 verbose(env, "cannot find address for kernel function %s\n", 2774 func_name); 2775 return -EINVAL; 2776 } 2777 specialize_kfunc(env, func_id, offset, &addr); 2778 2779 if (bpf_jit_supports_far_kfunc_call()) { 2780 call_imm = func_id; 2781 } else { 2782 call_imm = BPF_CALL_IMM(addr); 2783 /* Check whether the relative offset overflows desc->imm */ 2784 if ((unsigned long)(s32)call_imm != call_imm) { 2785 verbose(env, "address of kernel function %s is out of range\n", 2786 func_name); 2787 return -EINVAL; 2788 } 2789 } 2790 2791 if (bpf_dev_bound_kfunc_id(func_id)) { 2792 err = bpf_dev_bound_kfunc_check(&env->log, prog_aux); 2793 if (err) 2794 return err; 2795 } 2796 2797 desc = &tab->descs[tab->nr_descs++]; 2798 desc->func_id = func_id; 2799 desc->imm = call_imm; 2800 desc->offset = offset; 2801 desc->addr = addr; 2802 err = btf_distill_func_proto(&env->log, desc_btf, 2803 func_proto, func_name, 2804 &desc->func_model); 2805 if (!err) 2806 sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]), 2807 kfunc_desc_cmp_by_id_off, NULL); 2808 return err; 2809 } 2810 2811 static int kfunc_desc_cmp_by_imm_off(const void *a, const void *b) 2812 { 2813 const struct bpf_kfunc_desc *d0 = a; 2814 const struct bpf_kfunc_desc *d1 = b; 2815 2816 if (d0->imm != d1->imm) 2817 return d0->imm < d1->imm ? -1 : 1; 2818 if (d0->offset != d1->offset) 2819 return d0->offset < d1->offset ? -1 : 1; 2820 return 0; 2821 } 2822 2823 static void sort_kfunc_descs_by_imm_off(struct bpf_prog *prog) 2824 { 2825 struct bpf_kfunc_desc_tab *tab; 2826 2827 tab = prog->aux->kfunc_tab; 2828 if (!tab) 2829 return; 2830 2831 sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]), 2832 kfunc_desc_cmp_by_imm_off, NULL); 2833 } 2834 2835 bool bpf_prog_has_kfunc_call(const struct bpf_prog *prog) 2836 { 2837 return !!prog->aux->kfunc_tab; 2838 } 2839 2840 const struct btf_func_model * 2841 bpf_jit_find_kfunc_model(const struct bpf_prog *prog, 2842 const struct bpf_insn *insn) 2843 { 2844 const struct bpf_kfunc_desc desc = { 2845 .imm = insn->imm, 2846 .offset = insn->off, 2847 }; 2848 const struct bpf_kfunc_desc *res; 2849 struct bpf_kfunc_desc_tab *tab; 2850 2851 tab = prog->aux->kfunc_tab; 2852 res = bsearch(&desc, tab->descs, tab->nr_descs, 2853 sizeof(tab->descs[0]), kfunc_desc_cmp_by_imm_off); 2854 2855 return res ? &res->func_model : NULL; 2856 } 2857 2858 static int add_subprog_and_kfunc(struct bpf_verifier_env *env) 2859 { 2860 struct bpf_subprog_info *subprog = env->subprog_info; 2861 int i, ret, insn_cnt = env->prog->len, ex_cb_insn; 2862 struct bpf_insn *insn = env->prog->insnsi; 2863 2864 /* Add entry function. */ 2865 ret = add_subprog(env, 0); 2866 if (ret) 2867 return ret; 2868 2869 for (i = 0; i < insn_cnt; i++, insn++) { 2870 if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn) && 2871 !bpf_pseudo_kfunc_call(insn)) 2872 continue; 2873 2874 if (!env->bpf_capable) { 2875 verbose(env, "loading/calling other bpf or kernel functions are allowed for CAP_BPF and CAP_SYS_ADMIN\n"); 2876 return -EPERM; 2877 } 2878 2879 if (bpf_pseudo_func(insn) || bpf_pseudo_call(insn)) 2880 ret = add_subprog(env, i + insn->imm + 1); 2881 else 2882 ret = add_kfunc_call(env, insn->imm, insn->off); 2883 2884 if (ret < 0) 2885 return ret; 2886 } 2887 2888 ret = bpf_find_exception_callback_insn_off(env); 2889 if (ret < 0) 2890 return ret; 2891 ex_cb_insn = ret; 2892 2893 /* If ex_cb_insn > 0, this means that the main program has a subprog 2894 * marked using BTF decl tag to serve as the exception callback. 2895 */ 2896 if (ex_cb_insn) { 2897 ret = add_subprog(env, ex_cb_insn); 2898 if (ret < 0) 2899 return ret; 2900 for (i = 1; i < env->subprog_cnt; i++) { 2901 if (env->subprog_info[i].start != ex_cb_insn) 2902 continue; 2903 env->exception_callback_subprog = i; 2904 break; 2905 } 2906 } 2907 2908 /* Add a fake 'exit' subprog which could simplify subprog iteration 2909 * logic. 'subprog_cnt' should not be increased. 2910 */ 2911 subprog[env->subprog_cnt].start = insn_cnt; 2912 2913 if (env->log.level & BPF_LOG_LEVEL2) 2914 for (i = 0; i < env->subprog_cnt; i++) 2915 verbose(env, "func#%d @%d\n", i, subprog[i].start); 2916 2917 return 0; 2918 } 2919 2920 static int check_subprogs(struct bpf_verifier_env *env) 2921 { 2922 int i, subprog_start, subprog_end, off, cur_subprog = 0; 2923 struct bpf_subprog_info *subprog = env->subprog_info; 2924 struct bpf_insn *insn = env->prog->insnsi; 2925 int insn_cnt = env->prog->len; 2926 2927 /* now check that all jumps are within the same subprog */ 2928 subprog_start = subprog[cur_subprog].start; 2929 subprog_end = subprog[cur_subprog + 1].start; 2930 for (i = 0; i < insn_cnt; i++) { 2931 u8 code = insn[i].code; 2932 2933 if (code == (BPF_JMP | BPF_CALL) && 2934 insn[i].src_reg == 0 && 2935 insn[i].imm == BPF_FUNC_tail_call) 2936 subprog[cur_subprog].has_tail_call = true; 2937 if (BPF_CLASS(code) == BPF_LD && 2938 (BPF_MODE(code) == BPF_ABS || BPF_MODE(code) == BPF_IND)) 2939 subprog[cur_subprog].has_ld_abs = true; 2940 if (BPF_CLASS(code) != BPF_JMP && BPF_CLASS(code) != BPF_JMP32) 2941 goto next; 2942 if (BPF_OP(code) == BPF_EXIT || BPF_OP(code) == BPF_CALL) 2943 goto next; 2944 if (code == (BPF_JMP32 | BPF_JA)) 2945 off = i + insn[i].imm + 1; 2946 else 2947 off = i + insn[i].off + 1; 2948 if (off < subprog_start || off >= subprog_end) { 2949 verbose(env, "jump out of range from insn %d to %d\n", i, off); 2950 return -EINVAL; 2951 } 2952 next: 2953 if (i == subprog_end - 1) { 2954 /* to avoid fall-through from one subprog into another 2955 * the last insn of the subprog should be either exit 2956 * or unconditional jump back or bpf_throw call 2957 */ 2958 if (code != (BPF_JMP | BPF_EXIT) && 2959 code != (BPF_JMP32 | BPF_JA) && 2960 code != (BPF_JMP | BPF_JA)) { 2961 verbose(env, "last insn is not an exit or jmp\n"); 2962 return -EINVAL; 2963 } 2964 subprog_start = subprog_end; 2965 cur_subprog++; 2966 if (cur_subprog < env->subprog_cnt) 2967 subprog_end = subprog[cur_subprog + 1].start; 2968 } 2969 } 2970 return 0; 2971 } 2972 2973 /* Parentage chain of this register (or stack slot) should take care of all 2974 * issues like callee-saved registers, stack slot allocation time, etc. 2975 */ 2976 static int mark_reg_read(struct bpf_verifier_env *env, 2977 const struct bpf_reg_state *state, 2978 struct bpf_reg_state *parent, u8 flag) 2979 { 2980 bool writes = parent == state->parent; /* Observe write marks */ 2981 int cnt = 0; 2982 2983 while (parent) { 2984 /* if read wasn't screened by an earlier write ... */ 2985 if (writes && state->live & REG_LIVE_WRITTEN) 2986 break; 2987 if (parent->live & REG_LIVE_DONE) { 2988 verbose(env, "verifier BUG type %s var_off %lld off %d\n", 2989 reg_type_str(env, parent->type), 2990 parent->var_off.value, parent->off); 2991 return -EFAULT; 2992 } 2993 /* The first condition is more likely to be true than the 2994 * second, checked it first. 2995 */ 2996 if ((parent->live & REG_LIVE_READ) == flag || 2997 parent->live & REG_LIVE_READ64) 2998 /* The parentage chain never changes and 2999 * this parent was already marked as LIVE_READ. 3000 * There is no need to keep walking the chain again and 3001 * keep re-marking all parents as LIVE_READ. 3002 * This case happens when the same register is read 3003 * multiple times without writes into it in-between. 3004 * Also, if parent has the stronger REG_LIVE_READ64 set, 3005 * then no need to set the weak REG_LIVE_READ32. 3006 */ 3007 break; 3008 /* ... then we depend on parent's value */ 3009 parent->live |= flag; 3010 /* REG_LIVE_READ64 overrides REG_LIVE_READ32. */ 3011 if (flag == REG_LIVE_READ64) 3012 parent->live &= ~REG_LIVE_READ32; 3013 state = parent; 3014 parent = state->parent; 3015 writes = true; 3016 cnt++; 3017 } 3018 3019 if (env->longest_mark_read_walk < cnt) 3020 env->longest_mark_read_walk = cnt; 3021 return 0; 3022 } 3023 3024 static int mark_dynptr_read(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 3025 { 3026 struct bpf_func_state *state = func(env, reg); 3027 int spi, ret; 3028 3029 /* For CONST_PTR_TO_DYNPTR, it must have already been done by 3030 * check_reg_arg in check_helper_call and mark_btf_func_reg_size in 3031 * check_kfunc_call. 3032 */ 3033 if (reg->type == CONST_PTR_TO_DYNPTR) 3034 return 0; 3035 spi = dynptr_get_spi(env, reg); 3036 if (spi < 0) 3037 return spi; 3038 /* Caller ensures dynptr is valid and initialized, which means spi is in 3039 * bounds and spi is the first dynptr slot. Simply mark stack slot as 3040 * read. 3041 */ 3042 ret = mark_reg_read(env, &state->stack[spi].spilled_ptr, 3043 state->stack[spi].spilled_ptr.parent, REG_LIVE_READ64); 3044 if (ret) 3045 return ret; 3046 return mark_reg_read(env, &state->stack[spi - 1].spilled_ptr, 3047 state->stack[spi - 1].spilled_ptr.parent, REG_LIVE_READ64); 3048 } 3049 3050 static int mark_iter_read(struct bpf_verifier_env *env, struct bpf_reg_state *reg, 3051 int spi, int nr_slots) 3052 { 3053 struct bpf_func_state *state = func(env, reg); 3054 int err, i; 3055 3056 for (i = 0; i < nr_slots; i++) { 3057 struct bpf_reg_state *st = &state->stack[spi - i].spilled_ptr; 3058 3059 err = mark_reg_read(env, st, st->parent, REG_LIVE_READ64); 3060 if (err) 3061 return err; 3062 3063 mark_stack_slot_scratched(env, spi - i); 3064 } 3065 3066 return 0; 3067 } 3068 3069 /* This function is supposed to be used by the following 32-bit optimization 3070 * code only. It returns TRUE if the source or destination register operates 3071 * on 64-bit, otherwise return FALSE. 3072 */ 3073 static bool is_reg64(struct bpf_verifier_env *env, struct bpf_insn *insn, 3074 u32 regno, struct bpf_reg_state *reg, enum reg_arg_type t) 3075 { 3076 u8 code, class, op; 3077 3078 code = insn->code; 3079 class = BPF_CLASS(code); 3080 op = BPF_OP(code); 3081 if (class == BPF_JMP) { 3082 /* BPF_EXIT for "main" will reach here. Return TRUE 3083 * conservatively. 3084 */ 3085 if (op == BPF_EXIT) 3086 return true; 3087 if (op == BPF_CALL) { 3088 /* BPF to BPF call will reach here because of marking 3089 * caller saved clobber with DST_OP_NO_MARK for which we 3090 * don't care the register def because they are anyway 3091 * marked as NOT_INIT already. 3092 */ 3093 if (insn->src_reg == BPF_PSEUDO_CALL) 3094 return false; 3095 /* Helper call will reach here because of arg type 3096 * check, conservatively return TRUE. 3097 */ 3098 if (t == SRC_OP) 3099 return true; 3100 3101 return false; 3102 } 3103 } 3104 3105 if (class == BPF_ALU64 && op == BPF_END && (insn->imm == 16 || insn->imm == 32)) 3106 return false; 3107 3108 if (class == BPF_ALU64 || class == BPF_JMP || 3109 (class == BPF_ALU && op == BPF_END && insn->imm == 64)) 3110 return true; 3111 3112 if (class == BPF_ALU || class == BPF_JMP32) 3113 return false; 3114 3115 if (class == BPF_LDX) { 3116 if (t != SRC_OP) 3117 return BPF_SIZE(code) == BPF_DW; 3118 /* LDX source must be ptr. */ 3119 return true; 3120 } 3121 3122 if (class == BPF_STX) { 3123 /* BPF_STX (including atomic variants) has multiple source 3124 * operands, one of which is a ptr. Check whether the caller is 3125 * asking about it. 3126 */ 3127 if (t == SRC_OP && reg->type != SCALAR_VALUE) 3128 return true; 3129 return BPF_SIZE(code) == BPF_DW; 3130 } 3131 3132 if (class == BPF_LD) { 3133 u8 mode = BPF_MODE(code); 3134 3135 /* LD_IMM64 */ 3136 if (mode == BPF_IMM) 3137 return true; 3138 3139 /* Both LD_IND and LD_ABS return 32-bit data. */ 3140 if (t != SRC_OP) 3141 return false; 3142 3143 /* Implicit ctx ptr. */ 3144 if (regno == BPF_REG_6) 3145 return true; 3146 3147 /* Explicit source could be any width. */ 3148 return true; 3149 } 3150 3151 if (class == BPF_ST) 3152 /* The only source register for BPF_ST is a ptr. */ 3153 return true; 3154 3155 /* Conservatively return true at default. */ 3156 return true; 3157 } 3158 3159 /* Return the regno defined by the insn, or -1. */ 3160 static int insn_def_regno(const struct bpf_insn *insn) 3161 { 3162 switch (BPF_CLASS(insn->code)) { 3163 case BPF_JMP: 3164 case BPF_JMP32: 3165 case BPF_ST: 3166 return -1; 3167 case BPF_STX: 3168 if (BPF_MODE(insn->code) == BPF_ATOMIC && 3169 (insn->imm & BPF_FETCH)) { 3170 if (insn->imm == BPF_CMPXCHG) 3171 return BPF_REG_0; 3172 else 3173 return insn->src_reg; 3174 } else { 3175 return -1; 3176 } 3177 default: 3178 return insn->dst_reg; 3179 } 3180 } 3181 3182 /* Return TRUE if INSN has defined any 32-bit value explicitly. */ 3183 static bool insn_has_def32(struct bpf_verifier_env *env, struct bpf_insn *insn) 3184 { 3185 int dst_reg = insn_def_regno(insn); 3186 3187 if (dst_reg == -1) 3188 return false; 3189 3190 return !is_reg64(env, insn, dst_reg, NULL, DST_OP); 3191 } 3192 3193 static void mark_insn_zext(struct bpf_verifier_env *env, 3194 struct bpf_reg_state *reg) 3195 { 3196 s32 def_idx = reg->subreg_def; 3197 3198 if (def_idx == DEF_NOT_SUBREG) 3199 return; 3200 3201 env->insn_aux_data[def_idx - 1].zext_dst = true; 3202 /* The dst will be zero extended, so won't be sub-register anymore. */ 3203 reg->subreg_def = DEF_NOT_SUBREG; 3204 } 3205 3206 static int check_reg_arg(struct bpf_verifier_env *env, u32 regno, 3207 enum reg_arg_type t) 3208 { 3209 struct bpf_verifier_state *vstate = env->cur_state; 3210 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 3211 struct bpf_insn *insn = env->prog->insnsi + env->insn_idx; 3212 struct bpf_reg_state *reg, *regs = state->regs; 3213 bool rw64; 3214 3215 if (regno >= MAX_BPF_REG) { 3216 verbose(env, "R%d is invalid\n", regno); 3217 return -EINVAL; 3218 } 3219 3220 mark_reg_scratched(env, regno); 3221 3222 reg = ®s[regno]; 3223 rw64 = is_reg64(env, insn, regno, reg, t); 3224 if (t == SRC_OP) { 3225 /* check whether register used as source operand can be read */ 3226 if (reg->type == NOT_INIT) { 3227 verbose(env, "R%d !read_ok\n", regno); 3228 return -EACCES; 3229 } 3230 /* We don't need to worry about FP liveness because it's read-only */ 3231 if (regno == BPF_REG_FP) 3232 return 0; 3233 3234 if (rw64) 3235 mark_insn_zext(env, reg); 3236 3237 return mark_reg_read(env, reg, reg->parent, 3238 rw64 ? REG_LIVE_READ64 : REG_LIVE_READ32); 3239 } else { 3240 /* check whether register used as dest operand can be written to */ 3241 if (regno == BPF_REG_FP) { 3242 verbose(env, "frame pointer is read only\n"); 3243 return -EACCES; 3244 } 3245 reg->live |= REG_LIVE_WRITTEN; 3246 reg->subreg_def = rw64 ? DEF_NOT_SUBREG : env->insn_idx + 1; 3247 if (t == DST_OP) 3248 mark_reg_unknown(env, regs, regno); 3249 } 3250 return 0; 3251 } 3252 3253 static void mark_jmp_point(struct bpf_verifier_env *env, int idx) 3254 { 3255 env->insn_aux_data[idx].jmp_point = true; 3256 } 3257 3258 static bool is_jmp_point(struct bpf_verifier_env *env, int insn_idx) 3259 { 3260 return env->insn_aux_data[insn_idx].jmp_point; 3261 } 3262 3263 /* for any branch, call, exit record the history of jmps in the given state */ 3264 static int push_jmp_history(struct bpf_verifier_env *env, 3265 struct bpf_verifier_state *cur) 3266 { 3267 u32 cnt = cur->jmp_history_cnt; 3268 struct bpf_idx_pair *p; 3269 size_t alloc_size; 3270 3271 if (!is_jmp_point(env, env->insn_idx)) 3272 return 0; 3273 3274 cnt++; 3275 alloc_size = kmalloc_size_roundup(size_mul(cnt, sizeof(*p))); 3276 p = krealloc(cur->jmp_history, alloc_size, GFP_USER); 3277 if (!p) 3278 return -ENOMEM; 3279 p[cnt - 1].idx = env->insn_idx; 3280 p[cnt - 1].prev_idx = env->prev_insn_idx; 3281 cur->jmp_history = p; 3282 cur->jmp_history_cnt = cnt; 3283 return 0; 3284 } 3285 3286 /* Backtrack one insn at a time. If idx is not at the top of recorded 3287 * history then previous instruction came from straight line execution. 3288 */ 3289 static int get_prev_insn_idx(struct bpf_verifier_state *st, int i, 3290 u32 *history) 3291 { 3292 u32 cnt = *history; 3293 3294 if (cnt && st->jmp_history[cnt - 1].idx == i) { 3295 i = st->jmp_history[cnt - 1].prev_idx; 3296 (*history)--; 3297 } else { 3298 i--; 3299 } 3300 return i; 3301 } 3302 3303 static const char *disasm_kfunc_name(void *data, const struct bpf_insn *insn) 3304 { 3305 const struct btf_type *func; 3306 struct btf *desc_btf; 3307 3308 if (insn->src_reg != BPF_PSEUDO_KFUNC_CALL) 3309 return NULL; 3310 3311 desc_btf = find_kfunc_desc_btf(data, insn->off); 3312 if (IS_ERR(desc_btf)) 3313 return "<error>"; 3314 3315 func = btf_type_by_id(desc_btf, insn->imm); 3316 return btf_name_by_offset(desc_btf, func->name_off); 3317 } 3318 3319 static inline void bt_init(struct backtrack_state *bt, u32 frame) 3320 { 3321 bt->frame = frame; 3322 } 3323 3324 static inline void bt_reset(struct backtrack_state *bt) 3325 { 3326 struct bpf_verifier_env *env = bt->env; 3327 3328 memset(bt, 0, sizeof(*bt)); 3329 bt->env = env; 3330 } 3331 3332 static inline u32 bt_empty(struct backtrack_state *bt) 3333 { 3334 u64 mask = 0; 3335 int i; 3336 3337 for (i = 0; i <= bt->frame; i++) 3338 mask |= bt->reg_masks[i] | bt->stack_masks[i]; 3339 3340 return mask == 0; 3341 } 3342 3343 static inline int bt_subprog_enter(struct backtrack_state *bt) 3344 { 3345 if (bt->frame == MAX_CALL_FRAMES - 1) { 3346 verbose(bt->env, "BUG subprog enter from frame %d\n", bt->frame); 3347 WARN_ONCE(1, "verifier backtracking bug"); 3348 return -EFAULT; 3349 } 3350 bt->frame++; 3351 return 0; 3352 } 3353 3354 static inline int bt_subprog_exit(struct backtrack_state *bt) 3355 { 3356 if (bt->frame == 0) { 3357 verbose(bt->env, "BUG subprog exit from frame 0\n"); 3358 WARN_ONCE(1, "verifier backtracking bug"); 3359 return -EFAULT; 3360 } 3361 bt->frame--; 3362 return 0; 3363 } 3364 3365 static inline void bt_set_frame_reg(struct backtrack_state *bt, u32 frame, u32 reg) 3366 { 3367 bt->reg_masks[frame] |= 1 << reg; 3368 } 3369 3370 static inline void bt_clear_frame_reg(struct backtrack_state *bt, u32 frame, u32 reg) 3371 { 3372 bt->reg_masks[frame] &= ~(1 << reg); 3373 } 3374 3375 static inline void bt_set_reg(struct backtrack_state *bt, u32 reg) 3376 { 3377 bt_set_frame_reg(bt, bt->frame, reg); 3378 } 3379 3380 static inline void bt_clear_reg(struct backtrack_state *bt, u32 reg) 3381 { 3382 bt_clear_frame_reg(bt, bt->frame, reg); 3383 } 3384 3385 static inline void bt_set_frame_slot(struct backtrack_state *bt, u32 frame, u32 slot) 3386 { 3387 bt->stack_masks[frame] |= 1ull << slot; 3388 } 3389 3390 static inline void bt_clear_frame_slot(struct backtrack_state *bt, u32 frame, u32 slot) 3391 { 3392 bt->stack_masks[frame] &= ~(1ull << slot); 3393 } 3394 3395 static inline void bt_set_slot(struct backtrack_state *bt, u32 slot) 3396 { 3397 bt_set_frame_slot(bt, bt->frame, slot); 3398 } 3399 3400 static inline void bt_clear_slot(struct backtrack_state *bt, u32 slot) 3401 { 3402 bt_clear_frame_slot(bt, bt->frame, slot); 3403 } 3404 3405 static inline u32 bt_frame_reg_mask(struct backtrack_state *bt, u32 frame) 3406 { 3407 return bt->reg_masks[frame]; 3408 } 3409 3410 static inline u32 bt_reg_mask(struct backtrack_state *bt) 3411 { 3412 return bt->reg_masks[bt->frame]; 3413 } 3414 3415 static inline u64 bt_frame_stack_mask(struct backtrack_state *bt, u32 frame) 3416 { 3417 return bt->stack_masks[frame]; 3418 } 3419 3420 static inline u64 bt_stack_mask(struct backtrack_state *bt) 3421 { 3422 return bt->stack_masks[bt->frame]; 3423 } 3424 3425 static inline bool bt_is_reg_set(struct backtrack_state *bt, u32 reg) 3426 { 3427 return bt->reg_masks[bt->frame] & (1 << reg); 3428 } 3429 3430 static inline bool bt_is_slot_set(struct backtrack_state *bt, u32 slot) 3431 { 3432 return bt->stack_masks[bt->frame] & (1ull << slot); 3433 } 3434 3435 /* format registers bitmask, e.g., "r0,r2,r4" for 0x15 mask */ 3436 static void fmt_reg_mask(char *buf, ssize_t buf_sz, u32 reg_mask) 3437 { 3438 DECLARE_BITMAP(mask, 64); 3439 bool first = true; 3440 int i, n; 3441 3442 buf[0] = '\0'; 3443 3444 bitmap_from_u64(mask, reg_mask); 3445 for_each_set_bit(i, mask, 32) { 3446 n = snprintf(buf, buf_sz, "%sr%d", first ? "" : ",", i); 3447 first = false; 3448 buf += n; 3449 buf_sz -= n; 3450 if (buf_sz < 0) 3451 break; 3452 } 3453 } 3454 /* format stack slots bitmask, e.g., "-8,-24,-40" for 0x15 mask */ 3455 static void fmt_stack_mask(char *buf, ssize_t buf_sz, u64 stack_mask) 3456 { 3457 DECLARE_BITMAP(mask, 64); 3458 bool first = true; 3459 int i, n; 3460 3461 buf[0] = '\0'; 3462 3463 bitmap_from_u64(mask, stack_mask); 3464 for_each_set_bit(i, mask, 64) { 3465 n = snprintf(buf, buf_sz, "%s%d", first ? "" : ",", -(i + 1) * 8); 3466 first = false; 3467 buf += n; 3468 buf_sz -= n; 3469 if (buf_sz < 0) 3470 break; 3471 } 3472 } 3473 3474 /* For given verifier state backtrack_insn() is called from the last insn to 3475 * the first insn. Its purpose is to compute a bitmask of registers and 3476 * stack slots that needs precision in the parent verifier state. 3477 * 3478 * @idx is an index of the instruction we are currently processing; 3479 * @subseq_idx is an index of the subsequent instruction that: 3480 * - *would be* executed next, if jump history is viewed in forward order; 3481 * - *was* processed previously during backtracking. 3482 */ 3483 static int backtrack_insn(struct bpf_verifier_env *env, int idx, int subseq_idx, 3484 struct backtrack_state *bt) 3485 { 3486 const struct bpf_insn_cbs cbs = { 3487 .cb_call = disasm_kfunc_name, 3488 .cb_print = verbose, 3489 .private_data = env, 3490 }; 3491 struct bpf_insn *insn = env->prog->insnsi + idx; 3492 u8 class = BPF_CLASS(insn->code); 3493 u8 opcode = BPF_OP(insn->code); 3494 u8 mode = BPF_MODE(insn->code); 3495 u32 dreg = insn->dst_reg; 3496 u32 sreg = insn->src_reg; 3497 u32 spi, i; 3498 3499 if (insn->code == 0) 3500 return 0; 3501 if (env->log.level & BPF_LOG_LEVEL2) { 3502 fmt_reg_mask(env->tmp_str_buf, TMP_STR_BUF_LEN, bt_reg_mask(bt)); 3503 verbose(env, "mark_precise: frame%d: regs=%s ", 3504 bt->frame, env->tmp_str_buf); 3505 fmt_stack_mask(env->tmp_str_buf, TMP_STR_BUF_LEN, bt_stack_mask(bt)); 3506 verbose(env, "stack=%s before ", env->tmp_str_buf); 3507 verbose(env, "%d: ", idx); 3508 print_bpf_insn(&cbs, insn, env->allow_ptr_leaks); 3509 } 3510 3511 if (class == BPF_ALU || class == BPF_ALU64) { 3512 if (!bt_is_reg_set(bt, dreg)) 3513 return 0; 3514 if (opcode == BPF_MOV) { 3515 if (BPF_SRC(insn->code) == BPF_X) { 3516 /* dreg = sreg or dreg = (s8, s16, s32)sreg 3517 * dreg needs precision after this insn 3518 * sreg needs precision before this insn 3519 */ 3520 bt_clear_reg(bt, dreg); 3521 bt_set_reg(bt, sreg); 3522 } else { 3523 /* dreg = K 3524 * dreg needs precision after this insn. 3525 * Corresponding register is already marked 3526 * as precise=true in this verifier state. 3527 * No further markings in parent are necessary 3528 */ 3529 bt_clear_reg(bt, dreg); 3530 } 3531 } else { 3532 if (BPF_SRC(insn->code) == BPF_X) { 3533 /* dreg += sreg 3534 * both dreg and sreg need precision 3535 * before this insn 3536 */ 3537 bt_set_reg(bt, sreg); 3538 } /* else dreg += K 3539 * dreg still needs precision before this insn 3540 */ 3541 } 3542 } else if (class == BPF_LDX) { 3543 if (!bt_is_reg_set(bt, dreg)) 3544 return 0; 3545 bt_clear_reg(bt, dreg); 3546 3547 /* scalars can only be spilled into stack w/o losing precision. 3548 * Load from any other memory can be zero extended. 3549 * The desire to keep that precision is already indicated 3550 * by 'precise' mark in corresponding register of this state. 3551 * No further tracking necessary. 3552 */ 3553 if (insn->src_reg != BPF_REG_FP) 3554 return 0; 3555 3556 /* dreg = *(u64 *)[fp - off] was a fill from the stack. 3557 * that [fp - off] slot contains scalar that needs to be 3558 * tracked with precision 3559 */ 3560 spi = (-insn->off - 1) / BPF_REG_SIZE; 3561 if (spi >= 64) { 3562 verbose(env, "BUG spi %d\n", spi); 3563 WARN_ONCE(1, "verifier backtracking bug"); 3564 return -EFAULT; 3565 } 3566 bt_set_slot(bt, spi); 3567 } else if (class == BPF_STX || class == BPF_ST) { 3568 if (bt_is_reg_set(bt, dreg)) 3569 /* stx & st shouldn't be using _scalar_ dst_reg 3570 * to access memory. It means backtracking 3571 * encountered a case of pointer subtraction. 3572 */ 3573 return -ENOTSUPP; 3574 /* scalars can only be spilled into stack */ 3575 if (insn->dst_reg != BPF_REG_FP) 3576 return 0; 3577 spi = (-insn->off - 1) / BPF_REG_SIZE; 3578 if (spi >= 64) { 3579 verbose(env, "BUG spi %d\n", spi); 3580 WARN_ONCE(1, "verifier backtracking bug"); 3581 return -EFAULT; 3582 } 3583 if (!bt_is_slot_set(bt, spi)) 3584 return 0; 3585 bt_clear_slot(bt, spi); 3586 if (class == BPF_STX) 3587 bt_set_reg(bt, sreg); 3588 } else if (class == BPF_JMP || class == BPF_JMP32) { 3589 if (bpf_pseudo_call(insn)) { 3590 int subprog_insn_idx, subprog; 3591 3592 subprog_insn_idx = idx + insn->imm + 1; 3593 subprog = find_subprog(env, subprog_insn_idx); 3594 if (subprog < 0) 3595 return -EFAULT; 3596 3597 if (subprog_is_global(env, subprog)) { 3598 /* check that jump history doesn't have any 3599 * extra instructions from subprog; the next 3600 * instruction after call to global subprog 3601 * should be literally next instruction in 3602 * caller program 3603 */ 3604 WARN_ONCE(idx + 1 != subseq_idx, "verifier backtracking bug"); 3605 /* r1-r5 are invalidated after subprog call, 3606 * so for global func call it shouldn't be set 3607 * anymore 3608 */ 3609 if (bt_reg_mask(bt) & BPF_REGMASK_ARGS) { 3610 verbose(env, "BUG regs %x\n", bt_reg_mask(bt)); 3611 WARN_ONCE(1, "verifier backtracking bug"); 3612 return -EFAULT; 3613 } 3614 /* global subprog always sets R0 */ 3615 bt_clear_reg(bt, BPF_REG_0); 3616 return 0; 3617 } else { 3618 /* static subprog call instruction, which 3619 * means that we are exiting current subprog, 3620 * so only r1-r5 could be still requested as 3621 * precise, r0 and r6-r10 or any stack slot in 3622 * the current frame should be zero by now 3623 */ 3624 if (bt_reg_mask(bt) & ~BPF_REGMASK_ARGS) { 3625 verbose(env, "BUG regs %x\n", bt_reg_mask(bt)); 3626 WARN_ONCE(1, "verifier backtracking bug"); 3627 return -EFAULT; 3628 } 3629 /* we don't track register spills perfectly, 3630 * so fallback to force-precise instead of failing */ 3631 if (bt_stack_mask(bt) != 0) 3632 return -ENOTSUPP; 3633 /* propagate r1-r5 to the caller */ 3634 for (i = BPF_REG_1; i <= BPF_REG_5; i++) { 3635 if (bt_is_reg_set(bt, i)) { 3636 bt_clear_reg(bt, i); 3637 bt_set_frame_reg(bt, bt->frame - 1, i); 3638 } 3639 } 3640 if (bt_subprog_exit(bt)) 3641 return -EFAULT; 3642 return 0; 3643 } 3644 } else if ((bpf_helper_call(insn) && 3645 is_callback_calling_function(insn->imm) && 3646 !is_async_callback_calling_function(insn->imm)) || 3647 (bpf_pseudo_kfunc_call(insn) && is_callback_calling_kfunc(insn->imm))) { 3648 /* callback-calling helper or kfunc call, which means 3649 * we are exiting from subprog, but unlike the subprog 3650 * call handling above, we shouldn't propagate 3651 * precision of r1-r5 (if any requested), as they are 3652 * not actually arguments passed directly to callback 3653 * subprogs 3654 */ 3655 if (bt_reg_mask(bt) & ~BPF_REGMASK_ARGS) { 3656 verbose(env, "BUG regs %x\n", bt_reg_mask(bt)); 3657 WARN_ONCE(1, "verifier backtracking bug"); 3658 return -EFAULT; 3659 } 3660 if (bt_stack_mask(bt) != 0) 3661 return -ENOTSUPP; 3662 /* clear r1-r5 in callback subprog's mask */ 3663 for (i = BPF_REG_1; i <= BPF_REG_5; i++) 3664 bt_clear_reg(bt, i); 3665 if (bt_subprog_exit(bt)) 3666 return -EFAULT; 3667 return 0; 3668 } else if (opcode == BPF_CALL) { 3669 /* kfunc with imm==0 is invalid and fixup_kfunc_call will 3670 * catch this error later. Make backtracking conservative 3671 * with ENOTSUPP. 3672 */ 3673 if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL && insn->imm == 0) 3674 return -ENOTSUPP; 3675 /* regular helper call sets R0 */ 3676 bt_clear_reg(bt, BPF_REG_0); 3677 if (bt_reg_mask(bt) & BPF_REGMASK_ARGS) { 3678 /* if backtracing was looking for registers R1-R5 3679 * they should have been found already. 3680 */ 3681 verbose(env, "BUG regs %x\n", bt_reg_mask(bt)); 3682 WARN_ONCE(1, "verifier backtracking bug"); 3683 return -EFAULT; 3684 } 3685 } else if (opcode == BPF_EXIT) { 3686 bool r0_precise; 3687 3688 if (bt_reg_mask(bt) & BPF_REGMASK_ARGS) { 3689 /* if backtracing was looking for registers R1-R5 3690 * they should have been found already. 3691 */ 3692 verbose(env, "BUG regs %x\n", bt_reg_mask(bt)); 3693 WARN_ONCE(1, "verifier backtracking bug"); 3694 return -EFAULT; 3695 } 3696 3697 /* BPF_EXIT in subprog or callback always returns 3698 * right after the call instruction, so by checking 3699 * whether the instruction at subseq_idx-1 is subprog 3700 * call or not we can distinguish actual exit from 3701 * *subprog* from exit from *callback*. In the former 3702 * case, we need to propagate r0 precision, if 3703 * necessary. In the former we never do that. 3704 */ 3705 r0_precise = subseq_idx - 1 >= 0 && 3706 bpf_pseudo_call(&env->prog->insnsi[subseq_idx - 1]) && 3707 bt_is_reg_set(bt, BPF_REG_0); 3708 3709 bt_clear_reg(bt, BPF_REG_0); 3710 if (bt_subprog_enter(bt)) 3711 return -EFAULT; 3712 3713 if (r0_precise) 3714 bt_set_reg(bt, BPF_REG_0); 3715 /* r6-r9 and stack slots will stay set in caller frame 3716 * bitmasks until we return back from callee(s) 3717 */ 3718 return 0; 3719 } else if (BPF_SRC(insn->code) == BPF_X) { 3720 if (!bt_is_reg_set(bt, dreg) && !bt_is_reg_set(bt, sreg)) 3721 return 0; 3722 /* dreg <cond> sreg 3723 * Both dreg and sreg need precision before 3724 * this insn. If only sreg was marked precise 3725 * before it would be equally necessary to 3726 * propagate it to dreg. 3727 */ 3728 bt_set_reg(bt, dreg); 3729 bt_set_reg(bt, sreg); 3730 /* else dreg <cond> K 3731 * Only dreg still needs precision before 3732 * this insn, so for the K-based conditional 3733 * there is nothing new to be marked. 3734 */ 3735 } 3736 } else if (class == BPF_LD) { 3737 if (!bt_is_reg_set(bt, dreg)) 3738 return 0; 3739 bt_clear_reg(bt, dreg); 3740 /* It's ld_imm64 or ld_abs or ld_ind. 3741 * For ld_imm64 no further tracking of precision 3742 * into parent is necessary 3743 */ 3744 if (mode == BPF_IND || mode == BPF_ABS) 3745 /* to be analyzed */ 3746 return -ENOTSUPP; 3747 } 3748 return 0; 3749 } 3750 3751 /* the scalar precision tracking algorithm: 3752 * . at the start all registers have precise=false. 3753 * . scalar ranges are tracked as normal through alu and jmp insns. 3754 * . once precise value of the scalar register is used in: 3755 * . ptr + scalar alu 3756 * . if (scalar cond K|scalar) 3757 * . helper_call(.., scalar, ...) where ARG_CONST is expected 3758 * backtrack through the verifier states and mark all registers and 3759 * stack slots with spilled constants that these scalar regisers 3760 * should be precise. 3761 * . during state pruning two registers (or spilled stack slots) 3762 * are equivalent if both are not precise. 3763 * 3764 * Note the verifier cannot simply walk register parentage chain, 3765 * since many different registers and stack slots could have been 3766 * used to compute single precise scalar. 3767 * 3768 * The approach of starting with precise=true for all registers and then 3769 * backtrack to mark a register as not precise when the verifier detects 3770 * that program doesn't care about specific value (e.g., when helper 3771 * takes register as ARG_ANYTHING parameter) is not safe. 3772 * 3773 * It's ok to walk single parentage chain of the verifier states. 3774 * It's possible that this backtracking will go all the way till 1st insn. 3775 * All other branches will be explored for needing precision later. 3776 * 3777 * The backtracking needs to deal with cases like: 3778 * 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) 3779 * r9 -= r8 3780 * r5 = r9 3781 * if r5 > 0x79f goto pc+7 3782 * R5_w=inv(id=0,umax_value=1951,var_off=(0x0; 0x7ff)) 3783 * r5 += 1 3784 * ... 3785 * call bpf_perf_event_output#25 3786 * where .arg5_type = ARG_CONST_SIZE_OR_ZERO 3787 * 3788 * and this case: 3789 * r6 = 1 3790 * call foo // uses callee's r6 inside to compute r0 3791 * r0 += r6 3792 * if r0 == 0 goto 3793 * 3794 * to track above reg_mask/stack_mask needs to be independent for each frame. 3795 * 3796 * Also if parent's curframe > frame where backtracking started, 3797 * the verifier need to mark registers in both frames, otherwise callees 3798 * may incorrectly prune callers. This is similar to 3799 * commit 7640ead93924 ("bpf: verifier: make sure callees don't prune with caller differences") 3800 * 3801 * For now backtracking falls back into conservative marking. 3802 */ 3803 static void mark_all_scalars_precise(struct bpf_verifier_env *env, 3804 struct bpf_verifier_state *st) 3805 { 3806 struct bpf_func_state *func; 3807 struct bpf_reg_state *reg; 3808 int i, j; 3809 3810 if (env->log.level & BPF_LOG_LEVEL2) { 3811 verbose(env, "mark_precise: frame%d: falling back to forcing all scalars precise\n", 3812 st->curframe); 3813 } 3814 3815 /* big hammer: mark all scalars precise in this path. 3816 * pop_stack may still get !precise scalars. 3817 * We also skip current state and go straight to first parent state, 3818 * because precision markings in current non-checkpointed state are 3819 * not needed. See why in the comment in __mark_chain_precision below. 3820 */ 3821 for (st = st->parent; st; st = st->parent) { 3822 for (i = 0; i <= st->curframe; i++) { 3823 func = st->frame[i]; 3824 for (j = 0; j < BPF_REG_FP; j++) { 3825 reg = &func->regs[j]; 3826 if (reg->type != SCALAR_VALUE || reg->precise) 3827 continue; 3828 reg->precise = true; 3829 if (env->log.level & BPF_LOG_LEVEL2) { 3830 verbose(env, "force_precise: frame%d: forcing r%d to be precise\n", 3831 i, j); 3832 } 3833 } 3834 for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) { 3835 if (!is_spilled_reg(&func->stack[j])) 3836 continue; 3837 reg = &func->stack[j].spilled_ptr; 3838 if (reg->type != SCALAR_VALUE || reg->precise) 3839 continue; 3840 reg->precise = true; 3841 if (env->log.level & BPF_LOG_LEVEL2) { 3842 verbose(env, "force_precise: frame%d: forcing fp%d to be precise\n", 3843 i, -(j + 1) * 8); 3844 } 3845 } 3846 } 3847 } 3848 } 3849 3850 static void mark_all_scalars_imprecise(struct bpf_verifier_env *env, struct bpf_verifier_state *st) 3851 { 3852 struct bpf_func_state *func; 3853 struct bpf_reg_state *reg; 3854 int i, j; 3855 3856 for (i = 0; i <= st->curframe; i++) { 3857 func = st->frame[i]; 3858 for (j = 0; j < BPF_REG_FP; j++) { 3859 reg = &func->regs[j]; 3860 if (reg->type != SCALAR_VALUE) 3861 continue; 3862 reg->precise = false; 3863 } 3864 for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) { 3865 if (!is_spilled_reg(&func->stack[j])) 3866 continue; 3867 reg = &func->stack[j].spilled_ptr; 3868 if (reg->type != SCALAR_VALUE) 3869 continue; 3870 reg->precise = false; 3871 } 3872 } 3873 } 3874 3875 static bool idset_contains(struct bpf_idset *s, u32 id) 3876 { 3877 u32 i; 3878 3879 for (i = 0; i < s->count; ++i) 3880 if (s->ids[i] == id) 3881 return true; 3882 3883 return false; 3884 } 3885 3886 static int idset_push(struct bpf_idset *s, u32 id) 3887 { 3888 if (WARN_ON_ONCE(s->count >= ARRAY_SIZE(s->ids))) 3889 return -EFAULT; 3890 s->ids[s->count++] = id; 3891 return 0; 3892 } 3893 3894 static void idset_reset(struct bpf_idset *s) 3895 { 3896 s->count = 0; 3897 } 3898 3899 /* Collect a set of IDs for all registers currently marked as precise in env->bt. 3900 * Mark all registers with these IDs as precise. 3901 */ 3902 static int mark_precise_scalar_ids(struct bpf_verifier_env *env, struct bpf_verifier_state *st) 3903 { 3904 struct bpf_idset *precise_ids = &env->idset_scratch; 3905 struct backtrack_state *bt = &env->bt; 3906 struct bpf_func_state *func; 3907 struct bpf_reg_state *reg; 3908 DECLARE_BITMAP(mask, 64); 3909 int i, fr; 3910 3911 idset_reset(precise_ids); 3912 3913 for (fr = bt->frame; fr >= 0; fr--) { 3914 func = st->frame[fr]; 3915 3916 bitmap_from_u64(mask, bt_frame_reg_mask(bt, fr)); 3917 for_each_set_bit(i, mask, 32) { 3918 reg = &func->regs[i]; 3919 if (!reg->id || reg->type != SCALAR_VALUE) 3920 continue; 3921 if (idset_push(precise_ids, reg->id)) 3922 return -EFAULT; 3923 } 3924 3925 bitmap_from_u64(mask, bt_frame_stack_mask(bt, fr)); 3926 for_each_set_bit(i, mask, 64) { 3927 if (i >= func->allocated_stack / BPF_REG_SIZE) 3928 break; 3929 if (!is_spilled_scalar_reg(&func->stack[i])) 3930 continue; 3931 reg = &func->stack[i].spilled_ptr; 3932 if (!reg->id) 3933 continue; 3934 if (idset_push(precise_ids, reg->id)) 3935 return -EFAULT; 3936 } 3937 } 3938 3939 for (fr = 0; fr <= st->curframe; ++fr) { 3940 func = st->frame[fr]; 3941 3942 for (i = BPF_REG_0; i < BPF_REG_10; ++i) { 3943 reg = &func->regs[i]; 3944 if (!reg->id) 3945 continue; 3946 if (!idset_contains(precise_ids, reg->id)) 3947 continue; 3948 bt_set_frame_reg(bt, fr, i); 3949 } 3950 for (i = 0; i < func->allocated_stack / BPF_REG_SIZE; ++i) { 3951 if (!is_spilled_scalar_reg(&func->stack[i])) 3952 continue; 3953 reg = &func->stack[i].spilled_ptr; 3954 if (!reg->id) 3955 continue; 3956 if (!idset_contains(precise_ids, reg->id)) 3957 continue; 3958 bt_set_frame_slot(bt, fr, i); 3959 } 3960 } 3961 3962 return 0; 3963 } 3964 3965 /* 3966 * __mark_chain_precision() backtracks BPF program instruction sequence and 3967 * chain of verifier states making sure that register *regno* (if regno >= 0) 3968 * and/or stack slot *spi* (if spi >= 0) are marked as precisely tracked 3969 * SCALARS, as well as any other registers and slots that contribute to 3970 * a tracked state of given registers/stack slots, depending on specific BPF 3971 * assembly instructions (see backtrack_insns() for exact instruction handling 3972 * logic). This backtracking relies on recorded jmp_history and is able to 3973 * traverse entire chain of parent states. This process ends only when all the 3974 * necessary registers/slots and their transitive dependencies are marked as 3975 * precise. 3976 * 3977 * One important and subtle aspect is that precise marks *do not matter* in 3978 * the currently verified state (current state). It is important to understand 3979 * why this is the case. 3980 * 3981 * First, note that current state is the state that is not yet "checkpointed", 3982 * i.e., it is not yet put into env->explored_states, and it has no children 3983 * states as well. It's ephemeral, and can end up either a) being discarded if 3984 * compatible explored state is found at some point or BPF_EXIT instruction is 3985 * reached or b) checkpointed and put into env->explored_states, branching out 3986 * into one or more children states. 3987 * 3988 * In the former case, precise markings in current state are completely 3989 * ignored by state comparison code (see regsafe() for details). Only 3990 * checkpointed ("old") state precise markings are important, and if old 3991 * state's register/slot is precise, regsafe() assumes current state's 3992 * register/slot as precise and checks value ranges exactly and precisely. If 3993 * states turn out to be compatible, current state's necessary precise 3994 * markings and any required parent states' precise markings are enforced 3995 * after the fact with propagate_precision() logic, after the fact. But it's 3996 * important to realize that in this case, even after marking current state 3997 * registers/slots as precise, we immediately discard current state. So what 3998 * actually matters is any of the precise markings propagated into current 3999 * state's parent states, which are always checkpointed (due to b) case above). 4000 * As such, for scenario a) it doesn't matter if current state has precise 4001 * markings set or not. 4002 * 4003 * Now, for the scenario b), checkpointing and forking into child(ren) 4004 * state(s). Note that before current state gets to checkpointing step, any 4005 * processed instruction always assumes precise SCALAR register/slot 4006 * knowledge: if precise value or range is useful to prune jump branch, BPF 4007 * verifier takes this opportunity enthusiastically. Similarly, when 4008 * register's value is used to calculate offset or memory address, exact 4009 * knowledge of SCALAR range is assumed, checked, and enforced. So, similar to 4010 * what we mentioned above about state comparison ignoring precise markings 4011 * during state comparison, BPF verifier ignores and also assumes precise 4012 * markings *at will* during instruction verification process. But as verifier 4013 * assumes precision, it also propagates any precision dependencies across 4014 * parent states, which are not yet finalized, so can be further restricted 4015 * based on new knowledge gained from restrictions enforced by their children 4016 * states. This is so that once those parent states are finalized, i.e., when 4017 * they have no more active children state, state comparison logic in 4018 * is_state_visited() would enforce strict and precise SCALAR ranges, if 4019 * required for correctness. 4020 * 4021 * To build a bit more intuition, note also that once a state is checkpointed, 4022 * the path we took to get to that state is not important. This is crucial 4023 * property for state pruning. When state is checkpointed and finalized at 4024 * some instruction index, it can be correctly and safely used to "short 4025 * circuit" any *compatible* state that reaches exactly the same instruction 4026 * index. I.e., if we jumped to that instruction from a completely different 4027 * code path than original finalized state was derived from, it doesn't 4028 * matter, current state can be discarded because from that instruction 4029 * forward having a compatible state will ensure we will safely reach the 4030 * exit. States describe preconditions for further exploration, but completely 4031 * forget the history of how we got here. 4032 * 4033 * This also means that even if we needed precise SCALAR range to get to 4034 * finalized state, but from that point forward *that same* SCALAR register is 4035 * never used in a precise context (i.e., it's precise value is not needed for 4036 * correctness), it's correct and safe to mark such register as "imprecise" 4037 * (i.e., precise marking set to false). This is what we rely on when we do 4038 * not set precise marking in current state. If no child state requires 4039 * precision for any given SCALAR register, it's safe to dictate that it can 4040 * be imprecise. If any child state does require this register to be precise, 4041 * we'll mark it precise later retroactively during precise markings 4042 * propagation from child state to parent states. 4043 * 4044 * Skipping precise marking setting in current state is a mild version of 4045 * relying on the above observation. But we can utilize this property even 4046 * more aggressively by proactively forgetting any precise marking in the 4047 * current state (which we inherited from the parent state), right before we 4048 * checkpoint it and branch off into new child state. This is done by 4049 * mark_all_scalars_imprecise() to hopefully get more permissive and generic 4050 * finalized states which help in short circuiting more future states. 4051 */ 4052 static int __mark_chain_precision(struct bpf_verifier_env *env, int regno) 4053 { 4054 struct backtrack_state *bt = &env->bt; 4055 struct bpf_verifier_state *st = env->cur_state; 4056 int first_idx = st->first_insn_idx; 4057 int last_idx = env->insn_idx; 4058 int subseq_idx = -1; 4059 struct bpf_func_state *func; 4060 struct bpf_reg_state *reg; 4061 bool skip_first = true; 4062 int i, fr, err; 4063 4064 if (!env->bpf_capable) 4065 return 0; 4066 4067 /* set frame number from which we are starting to backtrack */ 4068 bt_init(bt, env->cur_state->curframe); 4069 4070 /* Do sanity checks against current state of register and/or stack 4071 * slot, but don't set precise flag in current state, as precision 4072 * tracking in the current state is unnecessary. 4073 */ 4074 func = st->frame[bt->frame]; 4075 if (regno >= 0) { 4076 reg = &func->regs[regno]; 4077 if (reg->type != SCALAR_VALUE) { 4078 WARN_ONCE(1, "backtracing misuse"); 4079 return -EFAULT; 4080 } 4081 bt_set_reg(bt, regno); 4082 } 4083 4084 if (bt_empty(bt)) 4085 return 0; 4086 4087 for (;;) { 4088 DECLARE_BITMAP(mask, 64); 4089 u32 history = st->jmp_history_cnt; 4090 4091 if (env->log.level & BPF_LOG_LEVEL2) { 4092 verbose(env, "mark_precise: frame%d: last_idx %d first_idx %d subseq_idx %d \n", 4093 bt->frame, last_idx, first_idx, subseq_idx); 4094 } 4095 4096 /* If some register with scalar ID is marked as precise, 4097 * make sure that all registers sharing this ID are also precise. 4098 * This is needed to estimate effect of find_equal_scalars(). 4099 * Do this at the last instruction of each state, 4100 * bpf_reg_state::id fields are valid for these instructions. 4101 * 4102 * Allows to track precision in situation like below: 4103 * 4104 * r2 = unknown value 4105 * ... 4106 * --- state #0 --- 4107 * ... 4108 * r1 = r2 // r1 and r2 now share the same ID 4109 * ... 4110 * --- state #1 {r1.id = A, r2.id = A} --- 4111 * ... 4112 * if (r2 > 10) goto exit; // find_equal_scalars() assigns range to r1 4113 * ... 4114 * --- state #2 {r1.id = A, r2.id = A} --- 4115 * r3 = r10 4116 * r3 += r1 // need to mark both r1 and r2 4117 */ 4118 if (mark_precise_scalar_ids(env, st)) 4119 return -EFAULT; 4120 4121 if (last_idx < 0) { 4122 /* we are at the entry into subprog, which 4123 * is expected for global funcs, but only if 4124 * requested precise registers are R1-R5 4125 * (which are global func's input arguments) 4126 */ 4127 if (st->curframe == 0 && 4128 st->frame[0]->subprogno > 0 && 4129 st->frame[0]->callsite == BPF_MAIN_FUNC && 4130 bt_stack_mask(bt) == 0 && 4131 (bt_reg_mask(bt) & ~BPF_REGMASK_ARGS) == 0) { 4132 bitmap_from_u64(mask, bt_reg_mask(bt)); 4133 for_each_set_bit(i, mask, 32) { 4134 reg = &st->frame[0]->regs[i]; 4135 if (reg->type != SCALAR_VALUE) { 4136 bt_clear_reg(bt, i); 4137 continue; 4138 } 4139 reg->precise = true; 4140 } 4141 return 0; 4142 } 4143 4144 verbose(env, "BUG backtracking func entry subprog %d reg_mask %x stack_mask %llx\n", 4145 st->frame[0]->subprogno, bt_reg_mask(bt), bt_stack_mask(bt)); 4146 WARN_ONCE(1, "verifier backtracking bug"); 4147 return -EFAULT; 4148 } 4149 4150 for (i = last_idx;;) { 4151 if (skip_first) { 4152 err = 0; 4153 skip_first = false; 4154 } else { 4155 err = backtrack_insn(env, i, subseq_idx, bt); 4156 } 4157 if (err == -ENOTSUPP) { 4158 mark_all_scalars_precise(env, env->cur_state); 4159 bt_reset(bt); 4160 return 0; 4161 } else if (err) { 4162 return err; 4163 } 4164 if (bt_empty(bt)) 4165 /* Found assignment(s) into tracked register in this state. 4166 * Since this state is already marked, just return. 4167 * Nothing to be tracked further in the parent state. 4168 */ 4169 return 0; 4170 if (i == first_idx) 4171 break; 4172 subseq_idx = i; 4173 i = get_prev_insn_idx(st, i, &history); 4174 if (i >= env->prog->len) { 4175 /* This can happen if backtracking reached insn 0 4176 * and there are still reg_mask or stack_mask 4177 * to backtrack. 4178 * It means the backtracking missed the spot where 4179 * particular register was initialized with a constant. 4180 */ 4181 verbose(env, "BUG backtracking idx %d\n", i); 4182 WARN_ONCE(1, "verifier backtracking bug"); 4183 return -EFAULT; 4184 } 4185 } 4186 st = st->parent; 4187 if (!st) 4188 break; 4189 4190 for (fr = bt->frame; fr >= 0; fr--) { 4191 func = st->frame[fr]; 4192 bitmap_from_u64(mask, bt_frame_reg_mask(bt, fr)); 4193 for_each_set_bit(i, mask, 32) { 4194 reg = &func->regs[i]; 4195 if (reg->type != SCALAR_VALUE) { 4196 bt_clear_frame_reg(bt, fr, i); 4197 continue; 4198 } 4199 if (reg->precise) 4200 bt_clear_frame_reg(bt, fr, i); 4201 else 4202 reg->precise = true; 4203 } 4204 4205 bitmap_from_u64(mask, bt_frame_stack_mask(bt, fr)); 4206 for_each_set_bit(i, mask, 64) { 4207 if (i >= func->allocated_stack / BPF_REG_SIZE) { 4208 /* the sequence of instructions: 4209 * 2: (bf) r3 = r10 4210 * 3: (7b) *(u64 *)(r3 -8) = r0 4211 * 4: (79) r4 = *(u64 *)(r10 -8) 4212 * doesn't contain jmps. It's backtracked 4213 * as a single block. 4214 * During backtracking insn 3 is not recognized as 4215 * stack access, so at the end of backtracking 4216 * stack slot fp-8 is still marked in stack_mask. 4217 * However the parent state may not have accessed 4218 * fp-8 and it's "unallocated" stack space. 4219 * In such case fallback to conservative. 4220 */ 4221 mark_all_scalars_precise(env, env->cur_state); 4222 bt_reset(bt); 4223 return 0; 4224 } 4225 4226 if (!is_spilled_scalar_reg(&func->stack[i])) { 4227 bt_clear_frame_slot(bt, fr, i); 4228 continue; 4229 } 4230 reg = &func->stack[i].spilled_ptr; 4231 if (reg->precise) 4232 bt_clear_frame_slot(bt, fr, i); 4233 else 4234 reg->precise = true; 4235 } 4236 if (env->log.level & BPF_LOG_LEVEL2) { 4237 fmt_reg_mask(env->tmp_str_buf, TMP_STR_BUF_LEN, 4238 bt_frame_reg_mask(bt, fr)); 4239 verbose(env, "mark_precise: frame%d: parent state regs=%s ", 4240 fr, env->tmp_str_buf); 4241 fmt_stack_mask(env->tmp_str_buf, TMP_STR_BUF_LEN, 4242 bt_frame_stack_mask(bt, fr)); 4243 verbose(env, "stack=%s: ", env->tmp_str_buf); 4244 print_verifier_state(env, func, true); 4245 } 4246 } 4247 4248 if (bt_empty(bt)) 4249 return 0; 4250 4251 subseq_idx = first_idx; 4252 last_idx = st->last_insn_idx; 4253 first_idx = st->first_insn_idx; 4254 } 4255 4256 /* if we still have requested precise regs or slots, we missed 4257 * something (e.g., stack access through non-r10 register), so 4258 * fallback to marking all precise 4259 */ 4260 if (!bt_empty(bt)) { 4261 mark_all_scalars_precise(env, env->cur_state); 4262 bt_reset(bt); 4263 } 4264 4265 return 0; 4266 } 4267 4268 int mark_chain_precision(struct bpf_verifier_env *env, int regno) 4269 { 4270 return __mark_chain_precision(env, regno); 4271 } 4272 4273 /* mark_chain_precision_batch() assumes that env->bt is set in the caller to 4274 * desired reg and stack masks across all relevant frames 4275 */ 4276 static int mark_chain_precision_batch(struct bpf_verifier_env *env) 4277 { 4278 return __mark_chain_precision(env, -1); 4279 } 4280 4281 static bool is_spillable_regtype(enum bpf_reg_type type) 4282 { 4283 switch (base_type(type)) { 4284 case PTR_TO_MAP_VALUE: 4285 case PTR_TO_STACK: 4286 case PTR_TO_CTX: 4287 case PTR_TO_PACKET: 4288 case PTR_TO_PACKET_META: 4289 case PTR_TO_PACKET_END: 4290 case PTR_TO_FLOW_KEYS: 4291 case CONST_PTR_TO_MAP: 4292 case PTR_TO_SOCKET: 4293 case PTR_TO_SOCK_COMMON: 4294 case PTR_TO_TCP_SOCK: 4295 case PTR_TO_XDP_SOCK: 4296 case PTR_TO_BTF_ID: 4297 case PTR_TO_BUF: 4298 case PTR_TO_MEM: 4299 case PTR_TO_FUNC: 4300 case PTR_TO_MAP_KEY: 4301 return true; 4302 default: 4303 return false; 4304 } 4305 } 4306 4307 /* Does this register contain a constant zero? */ 4308 static bool register_is_null(struct bpf_reg_state *reg) 4309 { 4310 return reg->type == SCALAR_VALUE && tnum_equals_const(reg->var_off, 0); 4311 } 4312 4313 static bool register_is_const(struct bpf_reg_state *reg) 4314 { 4315 return reg->type == SCALAR_VALUE && tnum_is_const(reg->var_off); 4316 } 4317 4318 static bool __is_scalar_unbounded(struct bpf_reg_state *reg) 4319 { 4320 return tnum_is_unknown(reg->var_off) && 4321 reg->smin_value == S64_MIN && reg->smax_value == S64_MAX && 4322 reg->umin_value == 0 && reg->umax_value == U64_MAX && 4323 reg->s32_min_value == S32_MIN && reg->s32_max_value == S32_MAX && 4324 reg->u32_min_value == 0 && reg->u32_max_value == U32_MAX; 4325 } 4326 4327 static bool register_is_bounded(struct bpf_reg_state *reg) 4328 { 4329 return reg->type == SCALAR_VALUE && !__is_scalar_unbounded(reg); 4330 } 4331 4332 static bool __is_pointer_value(bool allow_ptr_leaks, 4333 const struct bpf_reg_state *reg) 4334 { 4335 if (allow_ptr_leaks) 4336 return false; 4337 4338 return reg->type != SCALAR_VALUE; 4339 } 4340 4341 /* Copy src state preserving dst->parent and dst->live fields */ 4342 static void copy_register_state(struct bpf_reg_state *dst, const struct bpf_reg_state *src) 4343 { 4344 struct bpf_reg_state *parent = dst->parent; 4345 enum bpf_reg_liveness live = dst->live; 4346 4347 *dst = *src; 4348 dst->parent = parent; 4349 dst->live = live; 4350 } 4351 4352 static void save_register_state(struct bpf_func_state *state, 4353 int spi, struct bpf_reg_state *reg, 4354 int size) 4355 { 4356 int i; 4357 4358 copy_register_state(&state->stack[spi].spilled_ptr, reg); 4359 if (size == BPF_REG_SIZE) 4360 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN; 4361 4362 for (i = BPF_REG_SIZE; i > BPF_REG_SIZE - size; i--) 4363 state->stack[spi].slot_type[i - 1] = STACK_SPILL; 4364 4365 /* size < 8 bytes spill */ 4366 for (; i; i--) 4367 scrub_spilled_slot(&state->stack[spi].slot_type[i - 1]); 4368 } 4369 4370 static bool is_bpf_st_mem(struct bpf_insn *insn) 4371 { 4372 return BPF_CLASS(insn->code) == BPF_ST && BPF_MODE(insn->code) == BPF_MEM; 4373 } 4374 4375 /* check_stack_{read,write}_fixed_off functions track spill/fill of registers, 4376 * stack boundary and alignment are checked in check_mem_access() 4377 */ 4378 static int check_stack_write_fixed_off(struct bpf_verifier_env *env, 4379 /* stack frame we're writing to */ 4380 struct bpf_func_state *state, 4381 int off, int size, int value_regno, 4382 int insn_idx) 4383 { 4384 struct bpf_func_state *cur; /* state of the current function */ 4385 int i, slot = -off - 1, spi = slot / BPF_REG_SIZE, err; 4386 struct bpf_insn *insn = &env->prog->insnsi[insn_idx]; 4387 struct bpf_reg_state *reg = NULL; 4388 u32 dst_reg = insn->dst_reg; 4389 4390 err = grow_stack_state(state, round_up(slot + 1, BPF_REG_SIZE)); 4391 if (err) 4392 return err; 4393 /* caller checked that off % size == 0 and -MAX_BPF_STACK <= off < 0, 4394 * so it's aligned access and [off, off + size) are within stack limits 4395 */ 4396 if (!env->allow_ptr_leaks && 4397 state->stack[spi].slot_type[0] == STACK_SPILL && 4398 size != BPF_REG_SIZE) { 4399 verbose(env, "attempt to corrupt spilled pointer on stack\n"); 4400 return -EACCES; 4401 } 4402 4403 cur = env->cur_state->frame[env->cur_state->curframe]; 4404 if (value_regno >= 0) 4405 reg = &cur->regs[value_regno]; 4406 if (!env->bypass_spec_v4) { 4407 bool sanitize = reg && is_spillable_regtype(reg->type); 4408 4409 for (i = 0; i < size; i++) { 4410 u8 type = state->stack[spi].slot_type[i]; 4411 4412 if (type != STACK_MISC && type != STACK_ZERO) { 4413 sanitize = true; 4414 break; 4415 } 4416 } 4417 4418 if (sanitize) 4419 env->insn_aux_data[insn_idx].sanitize_stack_spill = true; 4420 } 4421 4422 err = destroy_if_dynptr_stack_slot(env, state, spi); 4423 if (err) 4424 return err; 4425 4426 mark_stack_slot_scratched(env, spi); 4427 if (reg && !(off % BPF_REG_SIZE) && register_is_bounded(reg) && 4428 !register_is_null(reg) && env->bpf_capable) { 4429 if (dst_reg != BPF_REG_FP) { 4430 /* The backtracking logic can only recognize explicit 4431 * stack slot address like [fp - 8]. Other spill of 4432 * scalar via different register has to be conservative. 4433 * Backtrack from here and mark all registers as precise 4434 * that contributed into 'reg' being a constant. 4435 */ 4436 err = mark_chain_precision(env, value_regno); 4437 if (err) 4438 return err; 4439 } 4440 save_register_state(state, spi, reg, size); 4441 /* Break the relation on a narrowing spill. */ 4442 if (fls64(reg->umax_value) > BITS_PER_BYTE * size) 4443 state->stack[spi].spilled_ptr.id = 0; 4444 } else if (!reg && !(off % BPF_REG_SIZE) && is_bpf_st_mem(insn) && 4445 insn->imm != 0 && env->bpf_capable) { 4446 struct bpf_reg_state fake_reg = {}; 4447 4448 __mark_reg_known(&fake_reg, (u32)insn->imm); 4449 fake_reg.type = SCALAR_VALUE; 4450 save_register_state(state, spi, &fake_reg, size); 4451 } else if (reg && is_spillable_regtype(reg->type)) { 4452 /* register containing pointer is being spilled into stack */ 4453 if (size != BPF_REG_SIZE) { 4454 verbose_linfo(env, insn_idx, "; "); 4455 verbose(env, "invalid size of register spill\n"); 4456 return -EACCES; 4457 } 4458 if (state != cur && reg->type == PTR_TO_STACK) { 4459 verbose(env, "cannot spill pointers to stack into stack frame of the caller\n"); 4460 return -EINVAL; 4461 } 4462 save_register_state(state, spi, reg, size); 4463 } else { 4464 u8 type = STACK_MISC; 4465 4466 /* regular write of data into stack destroys any spilled ptr */ 4467 state->stack[spi].spilled_ptr.type = NOT_INIT; 4468 /* Mark slots as STACK_MISC if they belonged to spilled ptr/dynptr/iter. */ 4469 if (is_stack_slot_special(&state->stack[spi])) 4470 for (i = 0; i < BPF_REG_SIZE; i++) 4471 scrub_spilled_slot(&state->stack[spi].slot_type[i]); 4472 4473 /* only mark the slot as written if all 8 bytes were written 4474 * otherwise read propagation may incorrectly stop too soon 4475 * when stack slots are partially written. 4476 * This heuristic means that read propagation will be 4477 * conservative, since it will add reg_live_read marks 4478 * to stack slots all the way to first state when programs 4479 * writes+reads less than 8 bytes 4480 */ 4481 if (size == BPF_REG_SIZE) 4482 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN; 4483 4484 /* when we zero initialize stack slots mark them as such */ 4485 if ((reg && register_is_null(reg)) || 4486 (!reg && is_bpf_st_mem(insn) && insn->imm == 0)) { 4487 /* backtracking doesn't work for STACK_ZERO yet. */ 4488 err = mark_chain_precision(env, value_regno); 4489 if (err) 4490 return err; 4491 type = STACK_ZERO; 4492 } 4493 4494 /* Mark slots affected by this stack write. */ 4495 for (i = 0; i < size; i++) 4496 state->stack[spi].slot_type[(slot - i) % BPF_REG_SIZE] = 4497 type; 4498 } 4499 return 0; 4500 } 4501 4502 /* Write the stack: 'stack[ptr_regno + off] = value_regno'. 'ptr_regno' is 4503 * known to contain a variable offset. 4504 * This function checks whether the write is permitted and conservatively 4505 * tracks the effects of the write, considering that each stack slot in the 4506 * dynamic range is potentially written to. 4507 * 4508 * 'off' includes 'regno->off'. 4509 * 'value_regno' can be -1, meaning that an unknown value is being written to 4510 * the stack. 4511 * 4512 * Spilled pointers in range are not marked as written because we don't know 4513 * what's going to be actually written. This means that read propagation for 4514 * future reads cannot be terminated by this write. 4515 * 4516 * For privileged programs, uninitialized stack slots are considered 4517 * initialized by this write (even though we don't know exactly what offsets 4518 * are going to be written to). The idea is that we don't want the verifier to 4519 * reject future reads that access slots written to through variable offsets. 4520 */ 4521 static int check_stack_write_var_off(struct bpf_verifier_env *env, 4522 /* func where register points to */ 4523 struct bpf_func_state *state, 4524 int ptr_regno, int off, int size, 4525 int value_regno, int insn_idx) 4526 { 4527 struct bpf_func_state *cur; /* state of the current function */ 4528 int min_off, max_off; 4529 int i, err; 4530 struct bpf_reg_state *ptr_reg = NULL, *value_reg = NULL; 4531 struct bpf_insn *insn = &env->prog->insnsi[insn_idx]; 4532 bool writing_zero = false; 4533 /* set if the fact that we're writing a zero is used to let any 4534 * stack slots remain STACK_ZERO 4535 */ 4536 bool zero_used = false; 4537 4538 cur = env->cur_state->frame[env->cur_state->curframe]; 4539 ptr_reg = &cur->regs[ptr_regno]; 4540 min_off = ptr_reg->smin_value + off; 4541 max_off = ptr_reg->smax_value + off + size; 4542 if (value_regno >= 0) 4543 value_reg = &cur->regs[value_regno]; 4544 if ((value_reg && register_is_null(value_reg)) || 4545 (!value_reg && is_bpf_st_mem(insn) && insn->imm == 0)) 4546 writing_zero = true; 4547 4548 err = grow_stack_state(state, round_up(-min_off, BPF_REG_SIZE)); 4549 if (err) 4550 return err; 4551 4552 for (i = min_off; i < max_off; i++) { 4553 int spi; 4554 4555 spi = __get_spi(i); 4556 err = destroy_if_dynptr_stack_slot(env, state, spi); 4557 if (err) 4558 return err; 4559 } 4560 4561 /* Variable offset writes destroy any spilled pointers in range. */ 4562 for (i = min_off; i < max_off; i++) { 4563 u8 new_type, *stype; 4564 int slot, spi; 4565 4566 slot = -i - 1; 4567 spi = slot / BPF_REG_SIZE; 4568 stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE]; 4569 mark_stack_slot_scratched(env, spi); 4570 4571 if (!env->allow_ptr_leaks && *stype != STACK_MISC && *stype != STACK_ZERO) { 4572 /* Reject the write if range we may write to has not 4573 * been initialized beforehand. If we didn't reject 4574 * here, the ptr status would be erased below (even 4575 * though not all slots are actually overwritten), 4576 * possibly opening the door to leaks. 4577 * 4578 * We do however catch STACK_INVALID case below, and 4579 * only allow reading possibly uninitialized memory 4580 * later for CAP_PERFMON, as the write may not happen to 4581 * that slot. 4582 */ 4583 verbose(env, "spilled ptr in range of var-offset stack write; insn %d, ptr off: %d", 4584 insn_idx, i); 4585 return -EINVAL; 4586 } 4587 4588 /* Erase all spilled pointers. */ 4589 state->stack[spi].spilled_ptr.type = NOT_INIT; 4590 4591 /* Update the slot type. */ 4592 new_type = STACK_MISC; 4593 if (writing_zero && *stype == STACK_ZERO) { 4594 new_type = STACK_ZERO; 4595 zero_used = true; 4596 } 4597 /* If the slot is STACK_INVALID, we check whether it's OK to 4598 * pretend that it will be initialized by this write. The slot 4599 * might not actually be written to, and so if we mark it as 4600 * initialized future reads might leak uninitialized memory. 4601 * For privileged programs, we will accept such reads to slots 4602 * that may or may not be written because, if we're reject 4603 * them, the error would be too confusing. 4604 */ 4605 if (*stype == STACK_INVALID && !env->allow_uninit_stack) { 4606 verbose(env, "uninit stack in range of var-offset write prohibited for !root; insn %d, off: %d", 4607 insn_idx, i); 4608 return -EINVAL; 4609 } 4610 *stype = new_type; 4611 } 4612 if (zero_used) { 4613 /* backtracking doesn't work for STACK_ZERO yet. */ 4614 err = mark_chain_precision(env, value_regno); 4615 if (err) 4616 return err; 4617 } 4618 return 0; 4619 } 4620 4621 /* When register 'dst_regno' is assigned some values from stack[min_off, 4622 * max_off), we set the register's type according to the types of the 4623 * respective stack slots. If all the stack values are known to be zeros, then 4624 * so is the destination reg. Otherwise, the register is considered to be 4625 * SCALAR. This function does not deal with register filling; the caller must 4626 * ensure that all spilled registers in the stack range have been marked as 4627 * read. 4628 */ 4629 static void mark_reg_stack_read(struct bpf_verifier_env *env, 4630 /* func where src register points to */ 4631 struct bpf_func_state *ptr_state, 4632 int min_off, int max_off, int dst_regno) 4633 { 4634 struct bpf_verifier_state *vstate = env->cur_state; 4635 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 4636 int i, slot, spi; 4637 u8 *stype; 4638 int zeros = 0; 4639 4640 for (i = min_off; i < max_off; i++) { 4641 slot = -i - 1; 4642 spi = slot / BPF_REG_SIZE; 4643 mark_stack_slot_scratched(env, spi); 4644 stype = ptr_state->stack[spi].slot_type; 4645 if (stype[slot % BPF_REG_SIZE] != STACK_ZERO) 4646 break; 4647 zeros++; 4648 } 4649 if (zeros == max_off - min_off) { 4650 /* any access_size read into register is zero extended, 4651 * so the whole register == const_zero 4652 */ 4653 __mark_reg_const_zero(&state->regs[dst_regno]); 4654 /* backtracking doesn't support STACK_ZERO yet, 4655 * so mark it precise here, so that later 4656 * backtracking can stop here. 4657 * Backtracking may not need this if this register 4658 * doesn't participate in pointer adjustment. 4659 * Forward propagation of precise flag is not 4660 * necessary either. This mark is only to stop 4661 * backtracking. Any register that contributed 4662 * to const 0 was marked precise before spill. 4663 */ 4664 state->regs[dst_regno].precise = true; 4665 } else { 4666 /* have read misc data from the stack */ 4667 mark_reg_unknown(env, state->regs, dst_regno); 4668 } 4669 state->regs[dst_regno].live |= REG_LIVE_WRITTEN; 4670 } 4671 4672 /* Read the stack at 'off' and put the results into the register indicated by 4673 * 'dst_regno'. It handles reg filling if the addressed stack slot is a 4674 * spilled reg. 4675 * 4676 * 'dst_regno' can be -1, meaning that the read value is not going to a 4677 * register. 4678 * 4679 * The access is assumed to be within the current stack bounds. 4680 */ 4681 static int check_stack_read_fixed_off(struct bpf_verifier_env *env, 4682 /* func where src register points to */ 4683 struct bpf_func_state *reg_state, 4684 int off, int size, int dst_regno) 4685 { 4686 struct bpf_verifier_state *vstate = env->cur_state; 4687 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 4688 int i, slot = -off - 1, spi = slot / BPF_REG_SIZE; 4689 struct bpf_reg_state *reg; 4690 u8 *stype, type; 4691 4692 stype = reg_state->stack[spi].slot_type; 4693 reg = ®_state->stack[spi].spilled_ptr; 4694 4695 mark_stack_slot_scratched(env, spi); 4696 4697 if (is_spilled_reg(®_state->stack[spi])) { 4698 u8 spill_size = 1; 4699 4700 for (i = BPF_REG_SIZE - 1; i > 0 && stype[i - 1] == STACK_SPILL; i--) 4701 spill_size++; 4702 4703 if (size != BPF_REG_SIZE || spill_size != BPF_REG_SIZE) { 4704 if (reg->type != SCALAR_VALUE) { 4705 verbose_linfo(env, env->insn_idx, "; "); 4706 verbose(env, "invalid size of register fill\n"); 4707 return -EACCES; 4708 } 4709 4710 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64); 4711 if (dst_regno < 0) 4712 return 0; 4713 4714 if (!(off % BPF_REG_SIZE) && size == spill_size) { 4715 /* The earlier check_reg_arg() has decided the 4716 * subreg_def for this insn. Save it first. 4717 */ 4718 s32 subreg_def = state->regs[dst_regno].subreg_def; 4719 4720 copy_register_state(&state->regs[dst_regno], reg); 4721 state->regs[dst_regno].subreg_def = subreg_def; 4722 } else { 4723 for (i = 0; i < size; i++) { 4724 type = stype[(slot - i) % BPF_REG_SIZE]; 4725 if (type == STACK_SPILL) 4726 continue; 4727 if (type == STACK_MISC) 4728 continue; 4729 if (type == STACK_INVALID && env->allow_uninit_stack) 4730 continue; 4731 verbose(env, "invalid read from stack off %d+%d size %d\n", 4732 off, i, size); 4733 return -EACCES; 4734 } 4735 mark_reg_unknown(env, state->regs, dst_regno); 4736 } 4737 state->regs[dst_regno].live |= REG_LIVE_WRITTEN; 4738 return 0; 4739 } 4740 4741 if (dst_regno >= 0) { 4742 /* restore register state from stack */ 4743 copy_register_state(&state->regs[dst_regno], reg); 4744 /* mark reg as written since spilled pointer state likely 4745 * has its liveness marks cleared by is_state_visited() 4746 * which resets stack/reg liveness for state transitions 4747 */ 4748 state->regs[dst_regno].live |= REG_LIVE_WRITTEN; 4749 } else if (__is_pointer_value(env->allow_ptr_leaks, reg)) { 4750 /* If dst_regno==-1, the caller is asking us whether 4751 * it is acceptable to use this value as a SCALAR_VALUE 4752 * (e.g. for XADD). 4753 * We must not allow unprivileged callers to do that 4754 * with spilled pointers. 4755 */ 4756 verbose(env, "leaking pointer from stack off %d\n", 4757 off); 4758 return -EACCES; 4759 } 4760 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64); 4761 } else { 4762 for (i = 0; i < size; i++) { 4763 type = stype[(slot - i) % BPF_REG_SIZE]; 4764 if (type == STACK_MISC) 4765 continue; 4766 if (type == STACK_ZERO) 4767 continue; 4768 if (type == STACK_INVALID && env->allow_uninit_stack) 4769 continue; 4770 verbose(env, "invalid read from stack off %d+%d size %d\n", 4771 off, i, size); 4772 return -EACCES; 4773 } 4774 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64); 4775 if (dst_regno >= 0) 4776 mark_reg_stack_read(env, reg_state, off, off + size, dst_regno); 4777 } 4778 return 0; 4779 } 4780 4781 enum bpf_access_src { 4782 ACCESS_DIRECT = 1, /* the access is performed by an instruction */ 4783 ACCESS_HELPER = 2, /* the access is performed by a helper */ 4784 }; 4785 4786 static int check_stack_range_initialized(struct bpf_verifier_env *env, 4787 int regno, int off, int access_size, 4788 bool zero_size_allowed, 4789 enum bpf_access_src type, 4790 struct bpf_call_arg_meta *meta); 4791 4792 static struct bpf_reg_state *reg_state(struct bpf_verifier_env *env, int regno) 4793 { 4794 return cur_regs(env) + regno; 4795 } 4796 4797 /* Read the stack at 'ptr_regno + off' and put the result into the register 4798 * 'dst_regno'. 4799 * 'off' includes the pointer register's fixed offset(i.e. 'ptr_regno.off'), 4800 * but not its variable offset. 4801 * 'size' is assumed to be <= reg size and the access is assumed to be aligned. 4802 * 4803 * As opposed to check_stack_read_fixed_off, this function doesn't deal with 4804 * filling registers (i.e. reads of spilled register cannot be detected when 4805 * the offset is not fixed). We conservatively mark 'dst_regno' as containing 4806 * SCALAR_VALUE. That's why we assert that the 'ptr_regno' has a variable 4807 * offset; for a fixed offset check_stack_read_fixed_off should be used 4808 * instead. 4809 */ 4810 static int check_stack_read_var_off(struct bpf_verifier_env *env, 4811 int ptr_regno, int off, int size, int dst_regno) 4812 { 4813 /* The state of the source register. */ 4814 struct bpf_reg_state *reg = reg_state(env, ptr_regno); 4815 struct bpf_func_state *ptr_state = func(env, reg); 4816 int err; 4817 int min_off, max_off; 4818 4819 /* Note that we pass a NULL meta, so raw access will not be permitted. 4820 */ 4821 err = check_stack_range_initialized(env, ptr_regno, off, size, 4822 false, ACCESS_DIRECT, NULL); 4823 if (err) 4824 return err; 4825 4826 min_off = reg->smin_value + off; 4827 max_off = reg->smax_value + off; 4828 mark_reg_stack_read(env, ptr_state, min_off, max_off + size, dst_regno); 4829 return 0; 4830 } 4831 4832 /* check_stack_read dispatches to check_stack_read_fixed_off or 4833 * check_stack_read_var_off. 4834 * 4835 * The caller must ensure that the offset falls within the allocated stack 4836 * bounds. 4837 * 4838 * 'dst_regno' is a register which will receive the value from the stack. It 4839 * can be -1, meaning that the read value is not going to a register. 4840 */ 4841 static int check_stack_read(struct bpf_verifier_env *env, 4842 int ptr_regno, int off, int size, 4843 int dst_regno) 4844 { 4845 struct bpf_reg_state *reg = reg_state(env, ptr_regno); 4846 struct bpf_func_state *state = func(env, reg); 4847 int err; 4848 /* Some accesses are only permitted with a static offset. */ 4849 bool var_off = !tnum_is_const(reg->var_off); 4850 4851 /* The offset is required to be static when reads don't go to a 4852 * register, in order to not leak pointers (see 4853 * check_stack_read_fixed_off). 4854 */ 4855 if (dst_regno < 0 && var_off) { 4856 char tn_buf[48]; 4857 4858 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 4859 verbose(env, "variable offset stack pointer cannot be passed into helper function; var_off=%s off=%d size=%d\n", 4860 tn_buf, off, size); 4861 return -EACCES; 4862 } 4863 /* Variable offset is prohibited for unprivileged mode for simplicity 4864 * since it requires corresponding support in Spectre masking for stack 4865 * ALU. See also retrieve_ptr_limit(). The check in 4866 * check_stack_access_for_ptr_arithmetic() called by 4867 * adjust_ptr_min_max_vals() prevents users from creating stack pointers 4868 * with variable offsets, therefore no check is required here. Further, 4869 * just checking it here would be insufficient as speculative stack 4870 * writes could still lead to unsafe speculative behaviour. 4871 */ 4872 if (!var_off) { 4873 off += reg->var_off.value; 4874 err = check_stack_read_fixed_off(env, state, off, size, 4875 dst_regno); 4876 } else { 4877 /* Variable offset stack reads need more conservative handling 4878 * than fixed offset ones. Note that dst_regno >= 0 on this 4879 * branch. 4880 */ 4881 err = check_stack_read_var_off(env, ptr_regno, off, size, 4882 dst_regno); 4883 } 4884 return err; 4885 } 4886 4887 4888 /* check_stack_write dispatches to check_stack_write_fixed_off or 4889 * check_stack_write_var_off. 4890 * 4891 * 'ptr_regno' is the register used as a pointer into the stack. 4892 * 'off' includes 'ptr_regno->off', but not its variable offset (if any). 4893 * 'value_regno' is the register whose value we're writing to the stack. It can 4894 * be -1, meaning that we're not writing from a register. 4895 * 4896 * The caller must ensure that the offset falls within the maximum stack size. 4897 */ 4898 static int check_stack_write(struct bpf_verifier_env *env, 4899 int ptr_regno, int off, int size, 4900 int value_regno, int insn_idx) 4901 { 4902 struct bpf_reg_state *reg = reg_state(env, ptr_regno); 4903 struct bpf_func_state *state = func(env, reg); 4904 int err; 4905 4906 if (tnum_is_const(reg->var_off)) { 4907 off += reg->var_off.value; 4908 err = check_stack_write_fixed_off(env, state, off, size, 4909 value_regno, insn_idx); 4910 } else { 4911 /* Variable offset stack reads need more conservative handling 4912 * than fixed offset ones. 4913 */ 4914 err = check_stack_write_var_off(env, state, 4915 ptr_regno, off, size, 4916 value_regno, insn_idx); 4917 } 4918 return err; 4919 } 4920 4921 static int check_map_access_type(struct bpf_verifier_env *env, u32 regno, 4922 int off, int size, enum bpf_access_type type) 4923 { 4924 struct bpf_reg_state *regs = cur_regs(env); 4925 struct bpf_map *map = regs[regno].map_ptr; 4926 u32 cap = bpf_map_flags_to_cap(map); 4927 4928 if (type == BPF_WRITE && !(cap & BPF_MAP_CAN_WRITE)) { 4929 verbose(env, "write into map forbidden, value_size=%d off=%d size=%d\n", 4930 map->value_size, off, size); 4931 return -EACCES; 4932 } 4933 4934 if (type == BPF_READ && !(cap & BPF_MAP_CAN_READ)) { 4935 verbose(env, "read from map forbidden, value_size=%d off=%d size=%d\n", 4936 map->value_size, off, size); 4937 return -EACCES; 4938 } 4939 4940 return 0; 4941 } 4942 4943 /* check read/write into memory region (e.g., map value, ringbuf sample, etc) */ 4944 static int __check_mem_access(struct bpf_verifier_env *env, int regno, 4945 int off, int size, u32 mem_size, 4946 bool zero_size_allowed) 4947 { 4948 bool size_ok = size > 0 || (size == 0 && zero_size_allowed); 4949 struct bpf_reg_state *reg; 4950 4951 if (off >= 0 && size_ok && (u64)off + size <= mem_size) 4952 return 0; 4953 4954 reg = &cur_regs(env)[regno]; 4955 switch (reg->type) { 4956 case PTR_TO_MAP_KEY: 4957 verbose(env, "invalid access to map key, key_size=%d off=%d size=%d\n", 4958 mem_size, off, size); 4959 break; 4960 case PTR_TO_MAP_VALUE: 4961 verbose(env, "invalid access to map value, value_size=%d off=%d size=%d\n", 4962 mem_size, off, size); 4963 break; 4964 case PTR_TO_PACKET: 4965 case PTR_TO_PACKET_META: 4966 case PTR_TO_PACKET_END: 4967 verbose(env, "invalid access to packet, off=%d size=%d, R%d(id=%d,off=%d,r=%d)\n", 4968 off, size, regno, reg->id, off, mem_size); 4969 break; 4970 case PTR_TO_MEM: 4971 default: 4972 verbose(env, "invalid access to memory, mem_size=%u off=%d size=%d\n", 4973 mem_size, off, size); 4974 } 4975 4976 return -EACCES; 4977 } 4978 4979 /* check read/write into a memory region with possible variable offset */ 4980 static int check_mem_region_access(struct bpf_verifier_env *env, u32 regno, 4981 int off, int size, u32 mem_size, 4982 bool zero_size_allowed) 4983 { 4984 struct bpf_verifier_state *vstate = env->cur_state; 4985 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 4986 struct bpf_reg_state *reg = &state->regs[regno]; 4987 int err; 4988 4989 /* We may have adjusted the register pointing to memory region, so we 4990 * need to try adding each of min_value and max_value to off 4991 * to make sure our theoretical access will be safe. 4992 * 4993 * The minimum value is only important with signed 4994 * comparisons where we can't assume the floor of a 4995 * value is 0. If we are using signed variables for our 4996 * index'es we need to make sure that whatever we use 4997 * will have a set floor within our range. 4998 */ 4999 if (reg->smin_value < 0 && 5000 (reg->smin_value == S64_MIN || 5001 (off + reg->smin_value != (s64)(s32)(off + reg->smin_value)) || 5002 reg->smin_value + off < 0)) { 5003 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n", 5004 regno); 5005 return -EACCES; 5006 } 5007 err = __check_mem_access(env, regno, reg->smin_value + off, size, 5008 mem_size, zero_size_allowed); 5009 if (err) { 5010 verbose(env, "R%d min value is outside of the allowed memory range\n", 5011 regno); 5012 return err; 5013 } 5014 5015 /* If we haven't set a max value then we need to bail since we can't be 5016 * sure we won't do bad things. 5017 * If reg->umax_value + off could overflow, treat that as unbounded too. 5018 */ 5019 if (reg->umax_value >= BPF_MAX_VAR_OFF) { 5020 verbose(env, "R%d unbounded memory access, make sure to bounds check any such access\n", 5021 regno); 5022 return -EACCES; 5023 } 5024 err = __check_mem_access(env, regno, reg->umax_value + off, size, 5025 mem_size, zero_size_allowed); 5026 if (err) { 5027 verbose(env, "R%d max value is outside of the allowed memory range\n", 5028 regno); 5029 return err; 5030 } 5031 5032 return 0; 5033 } 5034 5035 static int __check_ptr_off_reg(struct bpf_verifier_env *env, 5036 const struct bpf_reg_state *reg, int regno, 5037 bool fixed_off_ok) 5038 { 5039 /* Access to this pointer-typed register or passing it to a helper 5040 * is only allowed in its original, unmodified form. 5041 */ 5042 5043 if (reg->off < 0) { 5044 verbose(env, "negative offset %s ptr R%d off=%d disallowed\n", 5045 reg_type_str(env, reg->type), regno, reg->off); 5046 return -EACCES; 5047 } 5048 5049 if (!fixed_off_ok && reg->off) { 5050 verbose(env, "dereference of modified %s ptr R%d off=%d disallowed\n", 5051 reg_type_str(env, reg->type), regno, reg->off); 5052 return -EACCES; 5053 } 5054 5055 if (!tnum_is_const(reg->var_off) || reg->var_off.value) { 5056 char tn_buf[48]; 5057 5058 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 5059 verbose(env, "variable %s access var_off=%s disallowed\n", 5060 reg_type_str(env, reg->type), tn_buf); 5061 return -EACCES; 5062 } 5063 5064 return 0; 5065 } 5066 5067 int check_ptr_off_reg(struct bpf_verifier_env *env, 5068 const struct bpf_reg_state *reg, int regno) 5069 { 5070 return __check_ptr_off_reg(env, reg, regno, false); 5071 } 5072 5073 static int map_kptr_match_type(struct bpf_verifier_env *env, 5074 struct btf_field *kptr_field, 5075 struct bpf_reg_state *reg, u32 regno) 5076 { 5077 const char *targ_name = btf_type_name(kptr_field->kptr.btf, kptr_field->kptr.btf_id); 5078 int perm_flags; 5079 const char *reg_name = ""; 5080 5081 if (btf_is_kernel(reg->btf)) { 5082 perm_flags = PTR_MAYBE_NULL | PTR_TRUSTED | MEM_RCU; 5083 5084 /* Only unreferenced case accepts untrusted pointers */ 5085 if (kptr_field->type == BPF_KPTR_UNREF) 5086 perm_flags |= PTR_UNTRUSTED; 5087 } else { 5088 perm_flags = PTR_MAYBE_NULL | MEM_ALLOC; 5089 if (kptr_field->type == BPF_KPTR_PERCPU) 5090 perm_flags |= MEM_PERCPU; 5091 } 5092 5093 if (base_type(reg->type) != PTR_TO_BTF_ID || (type_flag(reg->type) & ~perm_flags)) 5094 goto bad_type; 5095 5096 /* We need to verify reg->type and reg->btf, before accessing reg->btf */ 5097 reg_name = btf_type_name(reg->btf, reg->btf_id); 5098 5099 /* For ref_ptr case, release function check should ensure we get one 5100 * referenced PTR_TO_BTF_ID, and that its fixed offset is 0. For the 5101 * normal store of unreferenced kptr, we must ensure var_off is zero. 5102 * Since ref_ptr cannot be accessed directly by BPF insns, checks for 5103 * reg->off and reg->ref_obj_id are not needed here. 5104 */ 5105 if (__check_ptr_off_reg(env, reg, regno, true)) 5106 return -EACCES; 5107 5108 /* A full type match is needed, as BTF can be vmlinux, module or prog BTF, and 5109 * we also need to take into account the reg->off. 5110 * 5111 * We want to support cases like: 5112 * 5113 * struct foo { 5114 * struct bar br; 5115 * struct baz bz; 5116 * }; 5117 * 5118 * struct foo *v; 5119 * v = func(); // PTR_TO_BTF_ID 5120 * val->foo = v; // reg->off is zero, btf and btf_id match type 5121 * val->bar = &v->br; // reg->off is still zero, but we need to retry with 5122 * // first member type of struct after comparison fails 5123 * val->baz = &v->bz; // reg->off is non-zero, so struct needs to be walked 5124 * // to match type 5125 * 5126 * In the kptr_ref case, check_func_arg_reg_off already ensures reg->off 5127 * is zero. We must also ensure that btf_struct_ids_match does not walk 5128 * the struct to match type against first member of struct, i.e. reject 5129 * second case from above. Hence, when type is BPF_KPTR_REF, we set 5130 * strict mode to true for type match. 5131 */ 5132 if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off, 5133 kptr_field->kptr.btf, kptr_field->kptr.btf_id, 5134 kptr_field->type != BPF_KPTR_UNREF)) 5135 goto bad_type; 5136 return 0; 5137 bad_type: 5138 verbose(env, "invalid kptr access, R%d type=%s%s ", regno, 5139 reg_type_str(env, reg->type), reg_name); 5140 verbose(env, "expected=%s%s", reg_type_str(env, PTR_TO_BTF_ID), targ_name); 5141 if (kptr_field->type == BPF_KPTR_UNREF) 5142 verbose(env, " or %s%s\n", reg_type_str(env, PTR_TO_BTF_ID | PTR_UNTRUSTED), 5143 targ_name); 5144 else 5145 verbose(env, "\n"); 5146 return -EINVAL; 5147 } 5148 5149 /* The non-sleepable programs and sleepable programs with explicit bpf_rcu_read_lock() 5150 * can dereference RCU protected pointers and result is PTR_TRUSTED. 5151 */ 5152 static bool in_rcu_cs(struct bpf_verifier_env *env) 5153 { 5154 return env->cur_state->active_rcu_lock || 5155 env->cur_state->active_lock.ptr || 5156 !env->prog->aux->sleepable; 5157 } 5158 5159 /* Once GCC supports btf_type_tag the following mechanism will be replaced with tag check */ 5160 BTF_SET_START(rcu_protected_types) 5161 BTF_ID(struct, prog_test_ref_kfunc) 5162 BTF_ID(struct, cgroup) 5163 BTF_ID(struct, bpf_cpumask) 5164 BTF_ID(struct, task_struct) 5165 BTF_SET_END(rcu_protected_types) 5166 5167 static bool rcu_protected_object(const struct btf *btf, u32 btf_id) 5168 { 5169 if (!btf_is_kernel(btf)) 5170 return false; 5171 return btf_id_set_contains(&rcu_protected_types, btf_id); 5172 } 5173 5174 static bool rcu_safe_kptr(const struct btf_field *field) 5175 { 5176 const struct btf_field_kptr *kptr = &field->kptr; 5177 5178 return field->type == BPF_KPTR_PERCPU || 5179 (field->type == BPF_KPTR_REF && rcu_protected_object(kptr->btf, kptr->btf_id)); 5180 } 5181 5182 static u32 btf_ld_kptr_type(struct bpf_verifier_env *env, struct btf_field *kptr_field) 5183 { 5184 if (rcu_safe_kptr(kptr_field) && in_rcu_cs(env)) { 5185 if (kptr_field->type != BPF_KPTR_PERCPU) 5186 return PTR_MAYBE_NULL | MEM_RCU; 5187 return PTR_MAYBE_NULL | MEM_RCU | MEM_PERCPU; 5188 } 5189 return PTR_MAYBE_NULL | PTR_UNTRUSTED; 5190 } 5191 5192 static int check_map_kptr_access(struct bpf_verifier_env *env, u32 regno, 5193 int value_regno, int insn_idx, 5194 struct btf_field *kptr_field) 5195 { 5196 struct bpf_insn *insn = &env->prog->insnsi[insn_idx]; 5197 int class = BPF_CLASS(insn->code); 5198 struct bpf_reg_state *val_reg; 5199 5200 /* Things we already checked for in check_map_access and caller: 5201 * - Reject cases where variable offset may touch kptr 5202 * - size of access (must be BPF_DW) 5203 * - tnum_is_const(reg->var_off) 5204 * - kptr_field->offset == off + reg->var_off.value 5205 */ 5206 /* Only BPF_[LDX,STX,ST] | BPF_MEM | BPF_DW is supported */ 5207 if (BPF_MODE(insn->code) != BPF_MEM) { 5208 verbose(env, "kptr in map can only be accessed using BPF_MEM instruction mode\n"); 5209 return -EACCES; 5210 } 5211 5212 /* We only allow loading referenced kptr, since it will be marked as 5213 * untrusted, similar to unreferenced kptr. 5214 */ 5215 if (class != BPF_LDX && 5216 (kptr_field->type == BPF_KPTR_REF || kptr_field->type == BPF_KPTR_PERCPU)) { 5217 verbose(env, "store to referenced kptr disallowed\n"); 5218 return -EACCES; 5219 } 5220 5221 if (class == BPF_LDX) { 5222 val_reg = reg_state(env, value_regno); 5223 /* We can simply mark the value_regno receiving the pointer 5224 * value from map as PTR_TO_BTF_ID, with the correct type. 5225 */ 5226 mark_btf_ld_reg(env, cur_regs(env), value_regno, PTR_TO_BTF_ID, kptr_field->kptr.btf, 5227 kptr_field->kptr.btf_id, btf_ld_kptr_type(env, kptr_field)); 5228 /* For mark_ptr_or_null_reg */ 5229 val_reg->id = ++env->id_gen; 5230 } else if (class == BPF_STX) { 5231 val_reg = reg_state(env, value_regno); 5232 if (!register_is_null(val_reg) && 5233 map_kptr_match_type(env, kptr_field, val_reg, value_regno)) 5234 return -EACCES; 5235 } else if (class == BPF_ST) { 5236 if (insn->imm) { 5237 verbose(env, "BPF_ST imm must be 0 when storing to kptr at off=%u\n", 5238 kptr_field->offset); 5239 return -EACCES; 5240 } 5241 } else { 5242 verbose(env, "kptr in map can only be accessed using BPF_LDX/BPF_STX/BPF_ST\n"); 5243 return -EACCES; 5244 } 5245 return 0; 5246 } 5247 5248 /* check read/write into a map element with possible variable offset */ 5249 static int check_map_access(struct bpf_verifier_env *env, u32 regno, 5250 int off, int size, bool zero_size_allowed, 5251 enum bpf_access_src src) 5252 { 5253 struct bpf_verifier_state *vstate = env->cur_state; 5254 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 5255 struct bpf_reg_state *reg = &state->regs[regno]; 5256 struct bpf_map *map = reg->map_ptr; 5257 struct btf_record *rec; 5258 int err, i; 5259 5260 err = check_mem_region_access(env, regno, off, size, map->value_size, 5261 zero_size_allowed); 5262 if (err) 5263 return err; 5264 5265 if (IS_ERR_OR_NULL(map->record)) 5266 return 0; 5267 rec = map->record; 5268 for (i = 0; i < rec->cnt; i++) { 5269 struct btf_field *field = &rec->fields[i]; 5270 u32 p = field->offset; 5271 5272 /* If any part of a field can be touched by load/store, reject 5273 * this program. To check that [x1, x2) overlaps with [y1, y2), 5274 * it is sufficient to check x1 < y2 && y1 < x2. 5275 */ 5276 if (reg->smin_value + off < p + btf_field_type_size(field->type) && 5277 p < reg->umax_value + off + size) { 5278 switch (field->type) { 5279 case BPF_KPTR_UNREF: 5280 case BPF_KPTR_REF: 5281 case BPF_KPTR_PERCPU: 5282 if (src != ACCESS_DIRECT) { 5283 verbose(env, "kptr cannot be accessed indirectly by helper\n"); 5284 return -EACCES; 5285 } 5286 if (!tnum_is_const(reg->var_off)) { 5287 verbose(env, "kptr access cannot have variable offset\n"); 5288 return -EACCES; 5289 } 5290 if (p != off + reg->var_off.value) { 5291 verbose(env, "kptr access misaligned expected=%u off=%llu\n", 5292 p, off + reg->var_off.value); 5293 return -EACCES; 5294 } 5295 if (size != bpf_size_to_bytes(BPF_DW)) { 5296 verbose(env, "kptr access size must be BPF_DW\n"); 5297 return -EACCES; 5298 } 5299 break; 5300 default: 5301 verbose(env, "%s cannot be accessed directly by load/store\n", 5302 btf_field_type_name(field->type)); 5303 return -EACCES; 5304 } 5305 } 5306 } 5307 return 0; 5308 } 5309 5310 #define MAX_PACKET_OFF 0xffff 5311 5312 static bool may_access_direct_pkt_data(struct bpf_verifier_env *env, 5313 const struct bpf_call_arg_meta *meta, 5314 enum bpf_access_type t) 5315 { 5316 enum bpf_prog_type prog_type = resolve_prog_type(env->prog); 5317 5318 switch (prog_type) { 5319 /* Program types only with direct read access go here! */ 5320 case BPF_PROG_TYPE_LWT_IN: 5321 case BPF_PROG_TYPE_LWT_OUT: 5322 case BPF_PROG_TYPE_LWT_SEG6LOCAL: 5323 case BPF_PROG_TYPE_SK_REUSEPORT: 5324 case BPF_PROG_TYPE_FLOW_DISSECTOR: 5325 case BPF_PROG_TYPE_CGROUP_SKB: 5326 if (t == BPF_WRITE) 5327 return false; 5328 fallthrough; 5329 5330 /* Program types with direct read + write access go here! */ 5331 case BPF_PROG_TYPE_SCHED_CLS: 5332 case BPF_PROG_TYPE_SCHED_ACT: 5333 case BPF_PROG_TYPE_XDP: 5334 case BPF_PROG_TYPE_LWT_XMIT: 5335 case BPF_PROG_TYPE_SK_SKB: 5336 case BPF_PROG_TYPE_SK_MSG: 5337 if (meta) 5338 return meta->pkt_access; 5339 5340 env->seen_direct_write = true; 5341 return true; 5342 5343 case BPF_PROG_TYPE_CGROUP_SOCKOPT: 5344 if (t == BPF_WRITE) 5345 env->seen_direct_write = true; 5346 5347 return true; 5348 5349 default: 5350 return false; 5351 } 5352 } 5353 5354 static int check_packet_access(struct bpf_verifier_env *env, u32 regno, int off, 5355 int size, bool zero_size_allowed) 5356 { 5357 struct bpf_reg_state *regs = cur_regs(env); 5358 struct bpf_reg_state *reg = ®s[regno]; 5359 int err; 5360 5361 /* We may have added a variable offset to the packet pointer; but any 5362 * reg->range we have comes after that. We are only checking the fixed 5363 * offset. 5364 */ 5365 5366 /* We don't allow negative numbers, because we aren't tracking enough 5367 * detail to prove they're safe. 5368 */ 5369 if (reg->smin_value < 0) { 5370 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n", 5371 regno); 5372 return -EACCES; 5373 } 5374 5375 err = reg->range < 0 ? -EINVAL : 5376 __check_mem_access(env, regno, off, size, reg->range, 5377 zero_size_allowed); 5378 if (err) { 5379 verbose(env, "R%d offset is outside of the packet\n", regno); 5380 return err; 5381 } 5382 5383 /* __check_mem_access has made sure "off + size - 1" is within u16. 5384 * reg->umax_value can't be bigger than MAX_PACKET_OFF which is 0xffff, 5385 * otherwise find_good_pkt_pointers would have refused to set range info 5386 * that __check_mem_access would have rejected this pkt access. 5387 * Therefore, "off + reg->umax_value + size - 1" won't overflow u32. 5388 */ 5389 env->prog->aux->max_pkt_offset = 5390 max_t(u32, env->prog->aux->max_pkt_offset, 5391 off + reg->umax_value + size - 1); 5392 5393 return err; 5394 } 5395 5396 /* check access to 'struct bpf_context' fields. Supports fixed offsets only */ 5397 static int check_ctx_access(struct bpf_verifier_env *env, int insn_idx, int off, int size, 5398 enum bpf_access_type t, enum bpf_reg_type *reg_type, 5399 struct btf **btf, u32 *btf_id) 5400 { 5401 struct bpf_insn_access_aux info = { 5402 .reg_type = *reg_type, 5403 .log = &env->log, 5404 }; 5405 5406 if (env->ops->is_valid_access && 5407 env->ops->is_valid_access(off, size, t, env->prog, &info)) { 5408 /* A non zero info.ctx_field_size indicates that this field is a 5409 * candidate for later verifier transformation to load the whole 5410 * field and then apply a mask when accessed with a narrower 5411 * access than actual ctx access size. A zero info.ctx_field_size 5412 * will only allow for whole field access and rejects any other 5413 * type of narrower access. 5414 */ 5415 *reg_type = info.reg_type; 5416 5417 if (base_type(*reg_type) == PTR_TO_BTF_ID) { 5418 *btf = info.btf; 5419 *btf_id = info.btf_id; 5420 } else { 5421 env->insn_aux_data[insn_idx].ctx_field_size = info.ctx_field_size; 5422 } 5423 /* remember the offset of last byte accessed in ctx */ 5424 if (env->prog->aux->max_ctx_offset < off + size) 5425 env->prog->aux->max_ctx_offset = off + size; 5426 return 0; 5427 } 5428 5429 verbose(env, "invalid bpf_context access off=%d size=%d\n", off, size); 5430 return -EACCES; 5431 } 5432 5433 static int check_flow_keys_access(struct bpf_verifier_env *env, int off, 5434 int size) 5435 { 5436 if (size < 0 || off < 0 || 5437 (u64)off + size > sizeof(struct bpf_flow_keys)) { 5438 verbose(env, "invalid access to flow keys off=%d size=%d\n", 5439 off, size); 5440 return -EACCES; 5441 } 5442 return 0; 5443 } 5444 5445 static int check_sock_access(struct bpf_verifier_env *env, int insn_idx, 5446 u32 regno, int off, int size, 5447 enum bpf_access_type t) 5448 { 5449 struct bpf_reg_state *regs = cur_regs(env); 5450 struct bpf_reg_state *reg = ®s[regno]; 5451 struct bpf_insn_access_aux info = {}; 5452 bool valid; 5453 5454 if (reg->smin_value < 0) { 5455 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n", 5456 regno); 5457 return -EACCES; 5458 } 5459 5460 switch (reg->type) { 5461 case PTR_TO_SOCK_COMMON: 5462 valid = bpf_sock_common_is_valid_access(off, size, t, &info); 5463 break; 5464 case PTR_TO_SOCKET: 5465 valid = bpf_sock_is_valid_access(off, size, t, &info); 5466 break; 5467 case PTR_TO_TCP_SOCK: 5468 valid = bpf_tcp_sock_is_valid_access(off, size, t, &info); 5469 break; 5470 case PTR_TO_XDP_SOCK: 5471 valid = bpf_xdp_sock_is_valid_access(off, size, t, &info); 5472 break; 5473 default: 5474 valid = false; 5475 } 5476 5477 5478 if (valid) { 5479 env->insn_aux_data[insn_idx].ctx_field_size = 5480 info.ctx_field_size; 5481 return 0; 5482 } 5483 5484 verbose(env, "R%d invalid %s access off=%d size=%d\n", 5485 regno, reg_type_str(env, reg->type), off, size); 5486 5487 return -EACCES; 5488 } 5489 5490 static bool is_pointer_value(struct bpf_verifier_env *env, int regno) 5491 { 5492 return __is_pointer_value(env->allow_ptr_leaks, reg_state(env, regno)); 5493 } 5494 5495 static bool is_ctx_reg(struct bpf_verifier_env *env, int regno) 5496 { 5497 const struct bpf_reg_state *reg = reg_state(env, regno); 5498 5499 return reg->type == PTR_TO_CTX; 5500 } 5501 5502 static bool is_sk_reg(struct bpf_verifier_env *env, int regno) 5503 { 5504 const struct bpf_reg_state *reg = reg_state(env, regno); 5505 5506 return type_is_sk_pointer(reg->type); 5507 } 5508 5509 static bool is_pkt_reg(struct bpf_verifier_env *env, int regno) 5510 { 5511 const struct bpf_reg_state *reg = reg_state(env, regno); 5512 5513 return type_is_pkt_pointer(reg->type); 5514 } 5515 5516 static bool is_flow_key_reg(struct bpf_verifier_env *env, int regno) 5517 { 5518 const struct bpf_reg_state *reg = reg_state(env, regno); 5519 5520 /* Separate to is_ctx_reg() since we still want to allow BPF_ST here. */ 5521 return reg->type == PTR_TO_FLOW_KEYS; 5522 } 5523 5524 static u32 *reg2btf_ids[__BPF_REG_TYPE_MAX] = { 5525 #ifdef CONFIG_NET 5526 [PTR_TO_SOCKET] = &btf_sock_ids[BTF_SOCK_TYPE_SOCK], 5527 [PTR_TO_SOCK_COMMON] = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON], 5528 [PTR_TO_TCP_SOCK] = &btf_sock_ids[BTF_SOCK_TYPE_TCP], 5529 #endif 5530 [CONST_PTR_TO_MAP] = btf_bpf_map_id, 5531 }; 5532 5533 static bool is_trusted_reg(const struct bpf_reg_state *reg) 5534 { 5535 /* A referenced register is always trusted. */ 5536 if (reg->ref_obj_id) 5537 return true; 5538 5539 /* Types listed in the reg2btf_ids are always trusted */ 5540 if (reg2btf_ids[base_type(reg->type)]) 5541 return true; 5542 5543 /* If a register is not referenced, it is trusted if it has the 5544 * MEM_ALLOC or PTR_TRUSTED type modifiers, and no others. Some of the 5545 * other type modifiers may be safe, but we elect to take an opt-in 5546 * approach here as some (e.g. PTR_UNTRUSTED and PTR_MAYBE_NULL) are 5547 * not. 5548 * 5549 * Eventually, we should make PTR_TRUSTED the single source of truth 5550 * for whether a register is trusted. 5551 */ 5552 return type_flag(reg->type) & BPF_REG_TRUSTED_MODIFIERS && 5553 !bpf_type_has_unsafe_modifiers(reg->type); 5554 } 5555 5556 static bool is_rcu_reg(const struct bpf_reg_state *reg) 5557 { 5558 return reg->type & MEM_RCU; 5559 } 5560 5561 static void clear_trusted_flags(enum bpf_type_flag *flag) 5562 { 5563 *flag &= ~(BPF_REG_TRUSTED_MODIFIERS | MEM_RCU); 5564 } 5565 5566 static int check_pkt_ptr_alignment(struct bpf_verifier_env *env, 5567 const struct bpf_reg_state *reg, 5568 int off, int size, bool strict) 5569 { 5570 struct tnum reg_off; 5571 int ip_align; 5572 5573 /* Byte size accesses are always allowed. */ 5574 if (!strict || size == 1) 5575 return 0; 5576 5577 /* For platforms that do not have a Kconfig enabling 5578 * CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS the value of 5579 * NET_IP_ALIGN is universally set to '2'. And on platforms 5580 * that do set CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS, we get 5581 * to this code only in strict mode where we want to emulate 5582 * the NET_IP_ALIGN==2 checking. Therefore use an 5583 * unconditional IP align value of '2'. 5584 */ 5585 ip_align = 2; 5586 5587 reg_off = tnum_add(reg->var_off, tnum_const(ip_align + reg->off + off)); 5588 if (!tnum_is_aligned(reg_off, size)) { 5589 char tn_buf[48]; 5590 5591 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 5592 verbose(env, 5593 "misaligned packet access off %d+%s+%d+%d size %d\n", 5594 ip_align, tn_buf, reg->off, off, size); 5595 return -EACCES; 5596 } 5597 5598 return 0; 5599 } 5600 5601 static int check_generic_ptr_alignment(struct bpf_verifier_env *env, 5602 const struct bpf_reg_state *reg, 5603 const char *pointer_desc, 5604 int off, int size, bool strict) 5605 { 5606 struct tnum reg_off; 5607 5608 /* Byte size accesses are always allowed. */ 5609 if (!strict || size == 1) 5610 return 0; 5611 5612 reg_off = tnum_add(reg->var_off, tnum_const(reg->off + off)); 5613 if (!tnum_is_aligned(reg_off, size)) { 5614 char tn_buf[48]; 5615 5616 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 5617 verbose(env, "misaligned %saccess off %s+%d+%d size %d\n", 5618 pointer_desc, tn_buf, reg->off, off, size); 5619 return -EACCES; 5620 } 5621 5622 return 0; 5623 } 5624 5625 static int check_ptr_alignment(struct bpf_verifier_env *env, 5626 const struct bpf_reg_state *reg, int off, 5627 int size, bool strict_alignment_once) 5628 { 5629 bool strict = env->strict_alignment || strict_alignment_once; 5630 const char *pointer_desc = ""; 5631 5632 switch (reg->type) { 5633 case PTR_TO_PACKET: 5634 case PTR_TO_PACKET_META: 5635 /* Special case, because of NET_IP_ALIGN. Given metadata sits 5636 * right in front, treat it the very same way. 5637 */ 5638 return check_pkt_ptr_alignment(env, reg, off, size, strict); 5639 case PTR_TO_FLOW_KEYS: 5640 pointer_desc = "flow keys "; 5641 break; 5642 case PTR_TO_MAP_KEY: 5643 pointer_desc = "key "; 5644 break; 5645 case PTR_TO_MAP_VALUE: 5646 pointer_desc = "value "; 5647 break; 5648 case PTR_TO_CTX: 5649 pointer_desc = "context "; 5650 break; 5651 case PTR_TO_STACK: 5652 pointer_desc = "stack "; 5653 /* The stack spill tracking logic in check_stack_write_fixed_off() 5654 * and check_stack_read_fixed_off() relies on stack accesses being 5655 * aligned. 5656 */ 5657 strict = true; 5658 break; 5659 case PTR_TO_SOCKET: 5660 pointer_desc = "sock "; 5661 break; 5662 case PTR_TO_SOCK_COMMON: 5663 pointer_desc = "sock_common "; 5664 break; 5665 case PTR_TO_TCP_SOCK: 5666 pointer_desc = "tcp_sock "; 5667 break; 5668 case PTR_TO_XDP_SOCK: 5669 pointer_desc = "xdp_sock "; 5670 break; 5671 default: 5672 break; 5673 } 5674 return check_generic_ptr_alignment(env, reg, pointer_desc, off, size, 5675 strict); 5676 } 5677 5678 static int update_stack_depth(struct bpf_verifier_env *env, 5679 const struct bpf_func_state *func, 5680 int off) 5681 { 5682 u16 stack = env->subprog_info[func->subprogno].stack_depth; 5683 5684 if (stack >= -off) 5685 return 0; 5686 5687 /* update known max for given subprogram */ 5688 env->subprog_info[func->subprogno].stack_depth = -off; 5689 return 0; 5690 } 5691 5692 /* starting from main bpf function walk all instructions of the function 5693 * and recursively walk all callees that given function can call. 5694 * Ignore jump and exit insns. 5695 * Since recursion is prevented by check_cfg() this algorithm 5696 * only needs a local stack of MAX_CALL_FRAMES to remember callsites 5697 */ 5698 static int check_max_stack_depth_subprog(struct bpf_verifier_env *env, int idx) 5699 { 5700 struct bpf_subprog_info *subprog = env->subprog_info; 5701 struct bpf_insn *insn = env->prog->insnsi; 5702 int depth = 0, frame = 0, i, subprog_end; 5703 bool tail_call_reachable = false; 5704 int ret_insn[MAX_CALL_FRAMES]; 5705 int ret_prog[MAX_CALL_FRAMES]; 5706 int j; 5707 5708 i = subprog[idx].start; 5709 process_func: 5710 /* protect against potential stack overflow that might happen when 5711 * bpf2bpf calls get combined with tailcalls. Limit the caller's stack 5712 * depth for such case down to 256 so that the worst case scenario 5713 * would result in 8k stack size (32 which is tailcall limit * 256 = 5714 * 8k). 5715 * 5716 * To get the idea what might happen, see an example: 5717 * func1 -> sub rsp, 128 5718 * subfunc1 -> sub rsp, 256 5719 * tailcall1 -> add rsp, 256 5720 * func2 -> sub rsp, 192 (total stack size = 128 + 192 = 320) 5721 * subfunc2 -> sub rsp, 64 5722 * subfunc22 -> sub rsp, 128 5723 * tailcall2 -> add rsp, 128 5724 * func3 -> sub rsp, 32 (total stack size 128 + 192 + 64 + 32 = 416) 5725 * 5726 * tailcall will unwind the current stack frame but it will not get rid 5727 * of caller's stack as shown on the example above. 5728 */ 5729 if (idx && subprog[idx].has_tail_call && depth >= 256) { 5730 verbose(env, 5731 "tail_calls are not allowed when call stack of previous frames is %d bytes. Too large\n", 5732 depth); 5733 return -EACCES; 5734 } 5735 /* round up to 32-bytes, since this is granularity 5736 * of interpreter stack size 5737 */ 5738 depth += round_up(max_t(u32, subprog[idx].stack_depth, 1), 32); 5739 if (depth > MAX_BPF_STACK) { 5740 verbose(env, "combined stack size of %d calls is %d. Too large\n", 5741 frame + 1, depth); 5742 return -EACCES; 5743 } 5744 continue_func: 5745 subprog_end = subprog[idx + 1].start; 5746 for (; i < subprog_end; i++) { 5747 int next_insn, sidx; 5748 5749 if (bpf_pseudo_kfunc_call(insn + i) && !insn[i].off) { 5750 bool err = false; 5751 5752 if (!is_bpf_throw_kfunc(insn + i)) 5753 continue; 5754 if (subprog[idx].is_cb) 5755 err = true; 5756 for (int c = 0; c < frame && !err; c++) { 5757 if (subprog[ret_prog[c]].is_cb) { 5758 err = true; 5759 break; 5760 } 5761 } 5762 if (!err) 5763 continue; 5764 verbose(env, 5765 "bpf_throw kfunc (insn %d) cannot be called from callback subprog %d\n", 5766 i, idx); 5767 return -EINVAL; 5768 } 5769 5770 if (!bpf_pseudo_call(insn + i) && !bpf_pseudo_func(insn + i)) 5771 continue; 5772 /* remember insn and function to return to */ 5773 ret_insn[frame] = i + 1; 5774 ret_prog[frame] = idx; 5775 5776 /* find the callee */ 5777 next_insn = i + insn[i].imm + 1; 5778 sidx = find_subprog(env, next_insn); 5779 if (sidx < 0) { 5780 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n", 5781 next_insn); 5782 return -EFAULT; 5783 } 5784 if (subprog[sidx].is_async_cb) { 5785 if (subprog[sidx].has_tail_call) { 5786 verbose(env, "verifier bug. subprog has tail_call and async cb\n"); 5787 return -EFAULT; 5788 } 5789 /* async callbacks don't increase bpf prog stack size unless called directly */ 5790 if (!bpf_pseudo_call(insn + i)) 5791 continue; 5792 if (subprog[sidx].is_exception_cb) { 5793 verbose(env, "insn %d cannot call exception cb directly\n", i); 5794 return -EINVAL; 5795 } 5796 } 5797 i = next_insn; 5798 idx = sidx; 5799 5800 if (subprog[idx].has_tail_call) 5801 tail_call_reachable = true; 5802 5803 frame++; 5804 if (frame >= MAX_CALL_FRAMES) { 5805 verbose(env, "the call stack of %d frames is too deep !\n", 5806 frame); 5807 return -E2BIG; 5808 } 5809 goto process_func; 5810 } 5811 /* if tail call got detected across bpf2bpf calls then mark each of the 5812 * currently present subprog frames as tail call reachable subprogs; 5813 * this info will be utilized by JIT so that we will be preserving the 5814 * tail call counter throughout bpf2bpf calls combined with tailcalls 5815 */ 5816 if (tail_call_reachable) 5817 for (j = 0; j < frame; j++) { 5818 if (subprog[ret_prog[j]].is_exception_cb) { 5819 verbose(env, "cannot tail call within exception cb\n"); 5820 return -EINVAL; 5821 } 5822 subprog[ret_prog[j]].tail_call_reachable = true; 5823 } 5824 if (subprog[0].tail_call_reachable) 5825 env->prog->aux->tail_call_reachable = true; 5826 5827 /* end of for() loop means the last insn of the 'subprog' 5828 * was reached. Doesn't matter whether it was JA or EXIT 5829 */ 5830 if (frame == 0) 5831 return 0; 5832 depth -= round_up(max_t(u32, subprog[idx].stack_depth, 1), 32); 5833 frame--; 5834 i = ret_insn[frame]; 5835 idx = ret_prog[frame]; 5836 goto continue_func; 5837 } 5838 5839 static int check_max_stack_depth(struct bpf_verifier_env *env) 5840 { 5841 struct bpf_subprog_info *si = env->subprog_info; 5842 int ret; 5843 5844 for (int i = 0; i < env->subprog_cnt; i++) { 5845 if (!i || si[i].is_async_cb) { 5846 ret = check_max_stack_depth_subprog(env, i); 5847 if (ret < 0) 5848 return ret; 5849 } 5850 continue; 5851 } 5852 return 0; 5853 } 5854 5855 #ifndef CONFIG_BPF_JIT_ALWAYS_ON 5856 static int get_callee_stack_depth(struct bpf_verifier_env *env, 5857 const struct bpf_insn *insn, int idx) 5858 { 5859 int start = idx + insn->imm + 1, subprog; 5860 5861 subprog = find_subprog(env, start); 5862 if (subprog < 0) { 5863 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n", 5864 start); 5865 return -EFAULT; 5866 } 5867 return env->subprog_info[subprog].stack_depth; 5868 } 5869 #endif 5870 5871 static int __check_buffer_access(struct bpf_verifier_env *env, 5872 const char *buf_info, 5873 const struct bpf_reg_state *reg, 5874 int regno, int off, int size) 5875 { 5876 if (off < 0) { 5877 verbose(env, 5878 "R%d invalid %s buffer access: off=%d, size=%d\n", 5879 regno, buf_info, off, size); 5880 return -EACCES; 5881 } 5882 if (!tnum_is_const(reg->var_off) || reg->var_off.value) { 5883 char tn_buf[48]; 5884 5885 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 5886 verbose(env, 5887 "R%d invalid variable buffer offset: off=%d, var_off=%s\n", 5888 regno, off, tn_buf); 5889 return -EACCES; 5890 } 5891 5892 return 0; 5893 } 5894 5895 static int check_tp_buffer_access(struct bpf_verifier_env *env, 5896 const struct bpf_reg_state *reg, 5897 int regno, int off, int size) 5898 { 5899 int err; 5900 5901 err = __check_buffer_access(env, "tracepoint", reg, regno, off, size); 5902 if (err) 5903 return err; 5904 5905 if (off + size > env->prog->aux->max_tp_access) 5906 env->prog->aux->max_tp_access = off + size; 5907 5908 return 0; 5909 } 5910 5911 static int check_buffer_access(struct bpf_verifier_env *env, 5912 const struct bpf_reg_state *reg, 5913 int regno, int off, int size, 5914 bool zero_size_allowed, 5915 u32 *max_access) 5916 { 5917 const char *buf_info = type_is_rdonly_mem(reg->type) ? "rdonly" : "rdwr"; 5918 int err; 5919 5920 err = __check_buffer_access(env, buf_info, reg, regno, off, size); 5921 if (err) 5922 return err; 5923 5924 if (off + size > *max_access) 5925 *max_access = off + size; 5926 5927 return 0; 5928 } 5929 5930 /* BPF architecture zero extends alu32 ops into 64-bit registesr */ 5931 static void zext_32_to_64(struct bpf_reg_state *reg) 5932 { 5933 reg->var_off = tnum_subreg(reg->var_off); 5934 __reg_assign_32_into_64(reg); 5935 } 5936 5937 /* truncate register to smaller size (in bytes) 5938 * must be called with size < BPF_REG_SIZE 5939 */ 5940 static void coerce_reg_to_size(struct bpf_reg_state *reg, int size) 5941 { 5942 u64 mask; 5943 5944 /* clear high bits in bit representation */ 5945 reg->var_off = tnum_cast(reg->var_off, size); 5946 5947 /* fix arithmetic bounds */ 5948 mask = ((u64)1 << (size * 8)) - 1; 5949 if ((reg->umin_value & ~mask) == (reg->umax_value & ~mask)) { 5950 reg->umin_value &= mask; 5951 reg->umax_value &= mask; 5952 } else { 5953 reg->umin_value = 0; 5954 reg->umax_value = mask; 5955 } 5956 reg->smin_value = reg->umin_value; 5957 reg->smax_value = reg->umax_value; 5958 5959 /* If size is smaller than 32bit register the 32bit register 5960 * values are also truncated so we push 64-bit bounds into 5961 * 32-bit bounds. Above were truncated < 32-bits already. 5962 */ 5963 if (size >= 4) 5964 return; 5965 __reg_combine_64_into_32(reg); 5966 } 5967 5968 static void set_sext64_default_val(struct bpf_reg_state *reg, int size) 5969 { 5970 if (size == 1) { 5971 reg->smin_value = reg->s32_min_value = S8_MIN; 5972 reg->smax_value = reg->s32_max_value = S8_MAX; 5973 } else if (size == 2) { 5974 reg->smin_value = reg->s32_min_value = S16_MIN; 5975 reg->smax_value = reg->s32_max_value = S16_MAX; 5976 } else { 5977 /* size == 4 */ 5978 reg->smin_value = reg->s32_min_value = S32_MIN; 5979 reg->smax_value = reg->s32_max_value = S32_MAX; 5980 } 5981 reg->umin_value = reg->u32_min_value = 0; 5982 reg->umax_value = U64_MAX; 5983 reg->u32_max_value = U32_MAX; 5984 reg->var_off = tnum_unknown; 5985 } 5986 5987 static void coerce_reg_to_size_sx(struct bpf_reg_state *reg, int size) 5988 { 5989 s64 init_s64_max, init_s64_min, s64_max, s64_min, u64_cval; 5990 u64 top_smax_value, top_smin_value; 5991 u64 num_bits = size * 8; 5992 5993 if (tnum_is_const(reg->var_off)) { 5994 u64_cval = reg->var_off.value; 5995 if (size == 1) 5996 reg->var_off = tnum_const((s8)u64_cval); 5997 else if (size == 2) 5998 reg->var_off = tnum_const((s16)u64_cval); 5999 else 6000 /* size == 4 */ 6001 reg->var_off = tnum_const((s32)u64_cval); 6002 6003 u64_cval = reg->var_off.value; 6004 reg->smax_value = reg->smin_value = u64_cval; 6005 reg->umax_value = reg->umin_value = u64_cval; 6006 reg->s32_max_value = reg->s32_min_value = u64_cval; 6007 reg->u32_max_value = reg->u32_min_value = u64_cval; 6008 return; 6009 } 6010 6011 top_smax_value = ((u64)reg->smax_value >> num_bits) << num_bits; 6012 top_smin_value = ((u64)reg->smin_value >> num_bits) << num_bits; 6013 6014 if (top_smax_value != top_smin_value) 6015 goto out; 6016 6017 /* find the s64_min and s64_min after sign extension */ 6018 if (size == 1) { 6019 init_s64_max = (s8)reg->smax_value; 6020 init_s64_min = (s8)reg->smin_value; 6021 } else if (size == 2) { 6022 init_s64_max = (s16)reg->smax_value; 6023 init_s64_min = (s16)reg->smin_value; 6024 } else { 6025 init_s64_max = (s32)reg->smax_value; 6026 init_s64_min = (s32)reg->smin_value; 6027 } 6028 6029 s64_max = max(init_s64_max, init_s64_min); 6030 s64_min = min(init_s64_max, init_s64_min); 6031 6032 /* both of s64_max/s64_min positive or negative */ 6033 if ((s64_max >= 0) == (s64_min >= 0)) { 6034 reg->smin_value = reg->s32_min_value = s64_min; 6035 reg->smax_value = reg->s32_max_value = s64_max; 6036 reg->umin_value = reg->u32_min_value = s64_min; 6037 reg->umax_value = reg->u32_max_value = s64_max; 6038 reg->var_off = tnum_range(s64_min, s64_max); 6039 return; 6040 } 6041 6042 out: 6043 set_sext64_default_val(reg, size); 6044 } 6045 6046 static void set_sext32_default_val(struct bpf_reg_state *reg, int size) 6047 { 6048 if (size == 1) { 6049 reg->s32_min_value = S8_MIN; 6050 reg->s32_max_value = S8_MAX; 6051 } else { 6052 /* size == 2 */ 6053 reg->s32_min_value = S16_MIN; 6054 reg->s32_max_value = S16_MAX; 6055 } 6056 reg->u32_min_value = 0; 6057 reg->u32_max_value = U32_MAX; 6058 } 6059 6060 static void coerce_subreg_to_size_sx(struct bpf_reg_state *reg, int size) 6061 { 6062 s32 init_s32_max, init_s32_min, s32_max, s32_min, u32_val; 6063 u32 top_smax_value, top_smin_value; 6064 u32 num_bits = size * 8; 6065 6066 if (tnum_is_const(reg->var_off)) { 6067 u32_val = reg->var_off.value; 6068 if (size == 1) 6069 reg->var_off = tnum_const((s8)u32_val); 6070 else 6071 reg->var_off = tnum_const((s16)u32_val); 6072 6073 u32_val = reg->var_off.value; 6074 reg->s32_min_value = reg->s32_max_value = u32_val; 6075 reg->u32_min_value = reg->u32_max_value = u32_val; 6076 return; 6077 } 6078 6079 top_smax_value = ((u32)reg->s32_max_value >> num_bits) << num_bits; 6080 top_smin_value = ((u32)reg->s32_min_value >> num_bits) << num_bits; 6081 6082 if (top_smax_value != top_smin_value) 6083 goto out; 6084 6085 /* find the s32_min and s32_min after sign extension */ 6086 if (size == 1) { 6087 init_s32_max = (s8)reg->s32_max_value; 6088 init_s32_min = (s8)reg->s32_min_value; 6089 } else { 6090 /* size == 2 */ 6091 init_s32_max = (s16)reg->s32_max_value; 6092 init_s32_min = (s16)reg->s32_min_value; 6093 } 6094 s32_max = max(init_s32_max, init_s32_min); 6095 s32_min = min(init_s32_max, init_s32_min); 6096 6097 if ((s32_min >= 0) == (s32_max >= 0)) { 6098 reg->s32_min_value = s32_min; 6099 reg->s32_max_value = s32_max; 6100 reg->u32_min_value = (u32)s32_min; 6101 reg->u32_max_value = (u32)s32_max; 6102 return; 6103 } 6104 6105 out: 6106 set_sext32_default_val(reg, size); 6107 } 6108 6109 static bool bpf_map_is_rdonly(const struct bpf_map *map) 6110 { 6111 /* A map is considered read-only if the following condition are true: 6112 * 6113 * 1) BPF program side cannot change any of the map content. The 6114 * BPF_F_RDONLY_PROG flag is throughout the lifetime of a map 6115 * and was set at map creation time. 6116 * 2) The map value(s) have been initialized from user space by a 6117 * loader and then "frozen", such that no new map update/delete 6118 * operations from syscall side are possible for the rest of 6119 * the map's lifetime from that point onwards. 6120 * 3) Any parallel/pending map update/delete operations from syscall 6121 * side have been completed. Only after that point, it's safe to 6122 * assume that map value(s) are immutable. 6123 */ 6124 return (map->map_flags & BPF_F_RDONLY_PROG) && 6125 READ_ONCE(map->frozen) && 6126 !bpf_map_write_active(map); 6127 } 6128 6129 static int bpf_map_direct_read(struct bpf_map *map, int off, int size, u64 *val, 6130 bool is_ldsx) 6131 { 6132 void *ptr; 6133 u64 addr; 6134 int err; 6135 6136 err = map->ops->map_direct_value_addr(map, &addr, off); 6137 if (err) 6138 return err; 6139 ptr = (void *)(long)addr + off; 6140 6141 switch (size) { 6142 case sizeof(u8): 6143 *val = is_ldsx ? (s64)*(s8 *)ptr : (u64)*(u8 *)ptr; 6144 break; 6145 case sizeof(u16): 6146 *val = is_ldsx ? (s64)*(s16 *)ptr : (u64)*(u16 *)ptr; 6147 break; 6148 case sizeof(u32): 6149 *val = is_ldsx ? (s64)*(s32 *)ptr : (u64)*(u32 *)ptr; 6150 break; 6151 case sizeof(u64): 6152 *val = *(u64 *)ptr; 6153 break; 6154 default: 6155 return -EINVAL; 6156 } 6157 return 0; 6158 } 6159 6160 #define BTF_TYPE_SAFE_RCU(__type) __PASTE(__type, __safe_rcu) 6161 #define BTF_TYPE_SAFE_RCU_OR_NULL(__type) __PASTE(__type, __safe_rcu_or_null) 6162 #define BTF_TYPE_SAFE_TRUSTED(__type) __PASTE(__type, __safe_trusted) 6163 6164 /* 6165 * Allow list few fields as RCU trusted or full trusted. 6166 * This logic doesn't allow mix tagging and will be removed once GCC supports 6167 * btf_type_tag. 6168 */ 6169 6170 /* RCU trusted: these fields are trusted in RCU CS and never NULL */ 6171 BTF_TYPE_SAFE_RCU(struct task_struct) { 6172 const cpumask_t *cpus_ptr; 6173 struct css_set __rcu *cgroups; 6174 struct task_struct __rcu *real_parent; 6175 struct task_struct *group_leader; 6176 }; 6177 6178 BTF_TYPE_SAFE_RCU(struct cgroup) { 6179 /* cgrp->kn is always accessible as documented in kernel/cgroup/cgroup.c */ 6180 struct kernfs_node *kn; 6181 }; 6182 6183 BTF_TYPE_SAFE_RCU(struct css_set) { 6184 struct cgroup *dfl_cgrp; 6185 }; 6186 6187 /* RCU trusted: these fields are trusted in RCU CS and can be NULL */ 6188 BTF_TYPE_SAFE_RCU_OR_NULL(struct mm_struct) { 6189 struct file __rcu *exe_file; 6190 }; 6191 6192 /* skb->sk, req->sk are not RCU protected, but we mark them as such 6193 * because bpf prog accessible sockets are SOCK_RCU_FREE. 6194 */ 6195 BTF_TYPE_SAFE_RCU_OR_NULL(struct sk_buff) { 6196 struct sock *sk; 6197 }; 6198 6199 BTF_TYPE_SAFE_RCU_OR_NULL(struct request_sock) { 6200 struct sock *sk; 6201 }; 6202 6203 /* full trusted: these fields are trusted even outside of RCU CS and never NULL */ 6204 BTF_TYPE_SAFE_TRUSTED(struct bpf_iter_meta) { 6205 struct seq_file *seq; 6206 }; 6207 6208 BTF_TYPE_SAFE_TRUSTED(struct bpf_iter__task) { 6209 struct bpf_iter_meta *meta; 6210 struct task_struct *task; 6211 }; 6212 6213 BTF_TYPE_SAFE_TRUSTED(struct linux_binprm) { 6214 struct file *file; 6215 }; 6216 6217 BTF_TYPE_SAFE_TRUSTED(struct file) { 6218 struct inode *f_inode; 6219 }; 6220 6221 BTF_TYPE_SAFE_TRUSTED(struct dentry) { 6222 /* no negative dentry-s in places where bpf can see it */ 6223 struct inode *d_inode; 6224 }; 6225 6226 BTF_TYPE_SAFE_TRUSTED(struct socket) { 6227 struct sock *sk; 6228 }; 6229 6230 static bool type_is_rcu(struct bpf_verifier_env *env, 6231 struct bpf_reg_state *reg, 6232 const char *field_name, u32 btf_id) 6233 { 6234 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct task_struct)); 6235 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct cgroup)); 6236 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct css_set)); 6237 6238 return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_rcu"); 6239 } 6240 6241 static bool type_is_rcu_or_null(struct bpf_verifier_env *env, 6242 struct bpf_reg_state *reg, 6243 const char *field_name, u32 btf_id) 6244 { 6245 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct mm_struct)); 6246 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct sk_buff)); 6247 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct request_sock)); 6248 6249 return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_rcu_or_null"); 6250 } 6251 6252 static bool type_is_trusted(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_TRUSTED(struct bpf_iter_meta)); 6257 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct bpf_iter__task)); 6258 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct linux_binprm)); 6259 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct file)); 6260 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct dentry)); 6261 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct socket)); 6262 6263 return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_trusted"); 6264 } 6265 6266 static int check_ptr_to_btf_access(struct bpf_verifier_env *env, 6267 struct bpf_reg_state *regs, 6268 int regno, int off, int size, 6269 enum bpf_access_type atype, 6270 int value_regno) 6271 { 6272 struct bpf_reg_state *reg = regs + regno; 6273 const struct btf_type *t = btf_type_by_id(reg->btf, reg->btf_id); 6274 const char *tname = btf_name_by_offset(reg->btf, t->name_off); 6275 const char *field_name = NULL; 6276 enum bpf_type_flag flag = 0; 6277 u32 btf_id = 0; 6278 int ret; 6279 6280 if (!env->allow_ptr_leaks) { 6281 verbose(env, 6282 "'struct %s' access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n", 6283 tname); 6284 return -EPERM; 6285 } 6286 if (!env->prog->gpl_compatible && btf_is_kernel(reg->btf)) { 6287 verbose(env, 6288 "Cannot access kernel 'struct %s' from non-GPL compatible program\n", 6289 tname); 6290 return -EINVAL; 6291 } 6292 if (off < 0) { 6293 verbose(env, 6294 "R%d is ptr_%s invalid negative access: off=%d\n", 6295 regno, tname, off); 6296 return -EACCES; 6297 } 6298 if (!tnum_is_const(reg->var_off) || reg->var_off.value) { 6299 char tn_buf[48]; 6300 6301 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 6302 verbose(env, 6303 "R%d is ptr_%s invalid variable offset: off=%d, var_off=%s\n", 6304 regno, tname, off, tn_buf); 6305 return -EACCES; 6306 } 6307 6308 if (reg->type & MEM_USER) { 6309 verbose(env, 6310 "R%d is ptr_%s access user memory: off=%d\n", 6311 regno, tname, off); 6312 return -EACCES; 6313 } 6314 6315 if (reg->type & MEM_PERCPU) { 6316 verbose(env, 6317 "R%d is ptr_%s access percpu memory: off=%d\n", 6318 regno, tname, off); 6319 return -EACCES; 6320 } 6321 6322 if (env->ops->btf_struct_access && !type_is_alloc(reg->type) && atype == BPF_WRITE) { 6323 if (!btf_is_kernel(reg->btf)) { 6324 verbose(env, "verifier internal error: reg->btf must be kernel btf\n"); 6325 return -EFAULT; 6326 } 6327 ret = env->ops->btf_struct_access(&env->log, reg, off, size); 6328 } else { 6329 /* Writes are permitted with default btf_struct_access for 6330 * program allocated objects (which always have ref_obj_id > 0), 6331 * but not for untrusted PTR_TO_BTF_ID | MEM_ALLOC. 6332 */ 6333 if (atype != BPF_READ && !type_is_ptr_alloc_obj(reg->type)) { 6334 verbose(env, "only read is supported\n"); 6335 return -EACCES; 6336 } 6337 6338 if (type_is_alloc(reg->type) && !type_is_non_owning_ref(reg->type) && 6339 !(reg->type & MEM_RCU) && !reg->ref_obj_id) { 6340 verbose(env, "verifier internal error: ref_obj_id for allocated object must be non-zero\n"); 6341 return -EFAULT; 6342 } 6343 6344 ret = btf_struct_access(&env->log, reg, off, size, atype, &btf_id, &flag, &field_name); 6345 } 6346 6347 if (ret < 0) 6348 return ret; 6349 6350 if (ret != PTR_TO_BTF_ID) { 6351 /* just mark; */ 6352 6353 } else if (type_flag(reg->type) & PTR_UNTRUSTED) { 6354 /* If this is an untrusted pointer, all pointers formed by walking it 6355 * also inherit the untrusted flag. 6356 */ 6357 flag = PTR_UNTRUSTED; 6358 6359 } else if (is_trusted_reg(reg) || is_rcu_reg(reg)) { 6360 /* By default any pointer obtained from walking a trusted pointer is no 6361 * longer trusted, unless the field being accessed has explicitly been 6362 * marked as inheriting its parent's state of trust (either full or RCU). 6363 * For example: 6364 * 'cgroups' pointer is untrusted if task->cgroups dereference 6365 * happened in a sleepable program outside of bpf_rcu_read_lock() 6366 * section. In a non-sleepable program it's trusted while in RCU CS (aka MEM_RCU). 6367 * Note bpf_rcu_read_unlock() converts MEM_RCU pointers to PTR_UNTRUSTED. 6368 * 6369 * A regular RCU-protected pointer with __rcu tag can also be deemed 6370 * trusted if we are in an RCU CS. Such pointer can be NULL. 6371 */ 6372 if (type_is_trusted(env, reg, field_name, btf_id)) { 6373 flag |= PTR_TRUSTED; 6374 } else if (in_rcu_cs(env) && !type_may_be_null(reg->type)) { 6375 if (type_is_rcu(env, reg, field_name, btf_id)) { 6376 /* ignore __rcu tag and mark it MEM_RCU */ 6377 flag |= MEM_RCU; 6378 } else if (flag & MEM_RCU || 6379 type_is_rcu_or_null(env, reg, field_name, btf_id)) { 6380 /* __rcu tagged pointers can be NULL */ 6381 flag |= MEM_RCU | PTR_MAYBE_NULL; 6382 6383 /* We always trust them */ 6384 if (type_is_rcu_or_null(env, reg, field_name, btf_id) && 6385 flag & PTR_UNTRUSTED) 6386 flag &= ~PTR_UNTRUSTED; 6387 } else if (flag & (MEM_PERCPU | MEM_USER)) { 6388 /* keep as-is */ 6389 } else { 6390 /* walking unknown pointers yields old deprecated PTR_TO_BTF_ID */ 6391 clear_trusted_flags(&flag); 6392 } 6393 } else { 6394 /* 6395 * If not in RCU CS or MEM_RCU pointer can be NULL then 6396 * aggressively mark as untrusted otherwise such 6397 * pointers will be plain PTR_TO_BTF_ID without flags 6398 * and will be allowed to be passed into helpers for 6399 * compat reasons. 6400 */ 6401 flag = PTR_UNTRUSTED; 6402 } 6403 } else { 6404 /* Old compat. Deprecated */ 6405 clear_trusted_flags(&flag); 6406 } 6407 6408 if (atype == BPF_READ && value_regno >= 0) 6409 mark_btf_ld_reg(env, regs, value_regno, ret, reg->btf, btf_id, flag); 6410 6411 return 0; 6412 } 6413 6414 static int check_ptr_to_map_access(struct bpf_verifier_env *env, 6415 struct bpf_reg_state *regs, 6416 int regno, int off, int size, 6417 enum bpf_access_type atype, 6418 int value_regno) 6419 { 6420 struct bpf_reg_state *reg = regs + regno; 6421 struct bpf_map *map = reg->map_ptr; 6422 struct bpf_reg_state map_reg; 6423 enum bpf_type_flag flag = 0; 6424 const struct btf_type *t; 6425 const char *tname; 6426 u32 btf_id; 6427 int ret; 6428 6429 if (!btf_vmlinux) { 6430 verbose(env, "map_ptr access not supported without CONFIG_DEBUG_INFO_BTF\n"); 6431 return -ENOTSUPP; 6432 } 6433 6434 if (!map->ops->map_btf_id || !*map->ops->map_btf_id) { 6435 verbose(env, "map_ptr access not supported for map type %d\n", 6436 map->map_type); 6437 return -ENOTSUPP; 6438 } 6439 6440 t = btf_type_by_id(btf_vmlinux, *map->ops->map_btf_id); 6441 tname = btf_name_by_offset(btf_vmlinux, t->name_off); 6442 6443 if (!env->allow_ptr_leaks) { 6444 verbose(env, 6445 "'struct %s' access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n", 6446 tname); 6447 return -EPERM; 6448 } 6449 6450 if (off < 0) { 6451 verbose(env, "R%d is %s invalid negative access: off=%d\n", 6452 regno, tname, off); 6453 return -EACCES; 6454 } 6455 6456 if (atype != BPF_READ) { 6457 verbose(env, "only read from %s is supported\n", tname); 6458 return -EACCES; 6459 } 6460 6461 /* Simulate access to a PTR_TO_BTF_ID */ 6462 memset(&map_reg, 0, sizeof(map_reg)); 6463 mark_btf_ld_reg(env, &map_reg, 0, PTR_TO_BTF_ID, btf_vmlinux, *map->ops->map_btf_id, 0); 6464 ret = btf_struct_access(&env->log, &map_reg, off, size, atype, &btf_id, &flag, NULL); 6465 if (ret < 0) 6466 return ret; 6467 6468 if (value_regno >= 0) 6469 mark_btf_ld_reg(env, regs, value_regno, ret, btf_vmlinux, btf_id, flag); 6470 6471 return 0; 6472 } 6473 6474 /* Check that the stack access at the given offset is within bounds. The 6475 * maximum valid offset is -1. 6476 * 6477 * The minimum valid offset is -MAX_BPF_STACK for writes, and 6478 * -state->allocated_stack for reads. 6479 */ 6480 static int check_stack_slot_within_bounds(int off, 6481 struct bpf_func_state *state, 6482 enum bpf_access_type t) 6483 { 6484 int min_valid_off; 6485 6486 if (t == BPF_WRITE) 6487 min_valid_off = -MAX_BPF_STACK; 6488 else 6489 min_valid_off = -state->allocated_stack; 6490 6491 if (off < min_valid_off || off > -1) 6492 return -EACCES; 6493 return 0; 6494 } 6495 6496 /* Check that the stack access at 'regno + off' falls within the maximum stack 6497 * bounds. 6498 * 6499 * 'off' includes `regno->offset`, but not its dynamic part (if any). 6500 */ 6501 static int check_stack_access_within_bounds( 6502 struct bpf_verifier_env *env, 6503 int regno, int off, int access_size, 6504 enum bpf_access_src src, enum bpf_access_type type) 6505 { 6506 struct bpf_reg_state *regs = cur_regs(env); 6507 struct bpf_reg_state *reg = regs + regno; 6508 struct bpf_func_state *state = func(env, reg); 6509 int min_off, max_off; 6510 int err; 6511 char *err_extra; 6512 6513 if (src == ACCESS_HELPER) 6514 /* We don't know if helpers are reading or writing (or both). */ 6515 err_extra = " indirect access to"; 6516 else if (type == BPF_READ) 6517 err_extra = " read from"; 6518 else 6519 err_extra = " write to"; 6520 6521 if (tnum_is_const(reg->var_off)) { 6522 min_off = reg->var_off.value + off; 6523 if (access_size > 0) 6524 max_off = min_off + access_size - 1; 6525 else 6526 max_off = min_off; 6527 } else { 6528 if (reg->smax_value >= BPF_MAX_VAR_OFF || 6529 reg->smin_value <= -BPF_MAX_VAR_OFF) { 6530 verbose(env, "invalid unbounded variable-offset%s stack R%d\n", 6531 err_extra, regno); 6532 return -EACCES; 6533 } 6534 min_off = reg->smin_value + off; 6535 if (access_size > 0) 6536 max_off = reg->smax_value + off + access_size - 1; 6537 else 6538 max_off = min_off; 6539 } 6540 6541 err = check_stack_slot_within_bounds(min_off, state, type); 6542 if (!err) 6543 err = check_stack_slot_within_bounds(max_off, state, type); 6544 6545 if (err) { 6546 if (tnum_is_const(reg->var_off)) { 6547 verbose(env, "invalid%s stack R%d off=%d size=%d\n", 6548 err_extra, regno, off, access_size); 6549 } else { 6550 char tn_buf[48]; 6551 6552 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 6553 verbose(env, "invalid variable-offset%s stack R%d var_off=%s size=%d\n", 6554 err_extra, regno, tn_buf, access_size); 6555 } 6556 } 6557 return err; 6558 } 6559 6560 /* check whether memory at (regno + off) is accessible for t = (read | write) 6561 * if t==write, value_regno is a register which value is stored into memory 6562 * if t==read, value_regno is a register which will receive the value from memory 6563 * if t==write && value_regno==-1, some unknown value is stored into memory 6564 * if t==read && value_regno==-1, don't care what we read from memory 6565 */ 6566 static int check_mem_access(struct bpf_verifier_env *env, int insn_idx, u32 regno, 6567 int off, int bpf_size, enum bpf_access_type t, 6568 int value_regno, bool strict_alignment_once, bool is_ldsx) 6569 { 6570 struct bpf_reg_state *regs = cur_regs(env); 6571 struct bpf_reg_state *reg = regs + regno; 6572 struct bpf_func_state *state; 6573 int size, err = 0; 6574 6575 size = bpf_size_to_bytes(bpf_size); 6576 if (size < 0) 6577 return size; 6578 6579 /* alignment checks will add in reg->off themselves */ 6580 err = check_ptr_alignment(env, reg, off, size, strict_alignment_once); 6581 if (err) 6582 return err; 6583 6584 /* for access checks, reg->off is just part of off */ 6585 off += reg->off; 6586 6587 if (reg->type == PTR_TO_MAP_KEY) { 6588 if (t == BPF_WRITE) { 6589 verbose(env, "write to change key R%d not allowed\n", regno); 6590 return -EACCES; 6591 } 6592 6593 err = check_mem_region_access(env, regno, off, size, 6594 reg->map_ptr->key_size, false); 6595 if (err) 6596 return err; 6597 if (value_regno >= 0) 6598 mark_reg_unknown(env, regs, value_regno); 6599 } else if (reg->type == PTR_TO_MAP_VALUE) { 6600 struct btf_field *kptr_field = NULL; 6601 6602 if (t == BPF_WRITE && value_regno >= 0 && 6603 is_pointer_value(env, value_regno)) { 6604 verbose(env, "R%d leaks addr into map\n", value_regno); 6605 return -EACCES; 6606 } 6607 err = check_map_access_type(env, regno, off, size, t); 6608 if (err) 6609 return err; 6610 err = check_map_access(env, regno, off, size, false, ACCESS_DIRECT); 6611 if (err) 6612 return err; 6613 if (tnum_is_const(reg->var_off)) 6614 kptr_field = btf_record_find(reg->map_ptr->record, 6615 off + reg->var_off.value, BPF_KPTR); 6616 if (kptr_field) { 6617 err = check_map_kptr_access(env, regno, value_regno, insn_idx, kptr_field); 6618 } else if (t == BPF_READ && value_regno >= 0) { 6619 struct bpf_map *map = reg->map_ptr; 6620 6621 /* if map is read-only, track its contents as scalars */ 6622 if (tnum_is_const(reg->var_off) && 6623 bpf_map_is_rdonly(map) && 6624 map->ops->map_direct_value_addr) { 6625 int map_off = off + reg->var_off.value; 6626 u64 val = 0; 6627 6628 err = bpf_map_direct_read(map, map_off, size, 6629 &val, is_ldsx); 6630 if (err) 6631 return err; 6632 6633 regs[value_regno].type = SCALAR_VALUE; 6634 __mark_reg_known(®s[value_regno], val); 6635 } else { 6636 mark_reg_unknown(env, regs, value_regno); 6637 } 6638 } 6639 } else if (base_type(reg->type) == PTR_TO_MEM) { 6640 bool rdonly_mem = type_is_rdonly_mem(reg->type); 6641 6642 if (type_may_be_null(reg->type)) { 6643 verbose(env, "R%d invalid mem access '%s'\n", regno, 6644 reg_type_str(env, reg->type)); 6645 return -EACCES; 6646 } 6647 6648 if (t == BPF_WRITE && rdonly_mem) { 6649 verbose(env, "R%d cannot write into %s\n", 6650 regno, reg_type_str(env, reg->type)); 6651 return -EACCES; 6652 } 6653 6654 if (t == BPF_WRITE && value_regno >= 0 && 6655 is_pointer_value(env, value_regno)) { 6656 verbose(env, "R%d leaks addr into mem\n", value_regno); 6657 return -EACCES; 6658 } 6659 6660 err = check_mem_region_access(env, regno, off, size, 6661 reg->mem_size, false); 6662 if (!err && value_regno >= 0 && (t == BPF_READ || rdonly_mem)) 6663 mark_reg_unknown(env, regs, value_regno); 6664 } else if (reg->type == PTR_TO_CTX) { 6665 enum bpf_reg_type reg_type = SCALAR_VALUE; 6666 struct btf *btf = NULL; 6667 u32 btf_id = 0; 6668 6669 if (t == BPF_WRITE && value_regno >= 0 && 6670 is_pointer_value(env, value_regno)) { 6671 verbose(env, "R%d leaks addr into ctx\n", value_regno); 6672 return -EACCES; 6673 } 6674 6675 err = check_ptr_off_reg(env, reg, regno); 6676 if (err < 0) 6677 return err; 6678 6679 err = check_ctx_access(env, insn_idx, off, size, t, ®_type, &btf, 6680 &btf_id); 6681 if (err) 6682 verbose_linfo(env, insn_idx, "; "); 6683 if (!err && t == BPF_READ && value_regno >= 0) { 6684 /* ctx access returns either a scalar, or a 6685 * PTR_TO_PACKET[_META,_END]. In the latter 6686 * case, we know the offset is zero. 6687 */ 6688 if (reg_type == SCALAR_VALUE) { 6689 mark_reg_unknown(env, regs, value_regno); 6690 } else { 6691 mark_reg_known_zero(env, regs, 6692 value_regno); 6693 if (type_may_be_null(reg_type)) 6694 regs[value_regno].id = ++env->id_gen; 6695 /* A load of ctx field could have different 6696 * actual load size with the one encoded in the 6697 * insn. When the dst is PTR, it is for sure not 6698 * a sub-register. 6699 */ 6700 regs[value_regno].subreg_def = DEF_NOT_SUBREG; 6701 if (base_type(reg_type) == PTR_TO_BTF_ID) { 6702 regs[value_regno].btf = btf; 6703 regs[value_regno].btf_id = btf_id; 6704 } 6705 } 6706 regs[value_regno].type = reg_type; 6707 } 6708 6709 } else if (reg->type == PTR_TO_STACK) { 6710 /* Basic bounds checks. */ 6711 err = check_stack_access_within_bounds(env, regno, off, size, ACCESS_DIRECT, t); 6712 if (err) 6713 return err; 6714 6715 state = func(env, reg); 6716 err = update_stack_depth(env, state, off); 6717 if (err) 6718 return err; 6719 6720 if (t == BPF_READ) 6721 err = check_stack_read(env, regno, off, size, 6722 value_regno); 6723 else 6724 err = check_stack_write(env, regno, off, size, 6725 value_regno, insn_idx); 6726 } else if (reg_is_pkt_pointer(reg)) { 6727 if (t == BPF_WRITE && !may_access_direct_pkt_data(env, NULL, t)) { 6728 verbose(env, "cannot write into packet\n"); 6729 return -EACCES; 6730 } 6731 if (t == BPF_WRITE && value_regno >= 0 && 6732 is_pointer_value(env, value_regno)) { 6733 verbose(env, "R%d leaks addr into packet\n", 6734 value_regno); 6735 return -EACCES; 6736 } 6737 err = check_packet_access(env, regno, off, size, false); 6738 if (!err && t == BPF_READ && value_regno >= 0) 6739 mark_reg_unknown(env, regs, value_regno); 6740 } else if (reg->type == PTR_TO_FLOW_KEYS) { 6741 if (t == BPF_WRITE && value_regno >= 0 && 6742 is_pointer_value(env, value_regno)) { 6743 verbose(env, "R%d leaks addr into flow keys\n", 6744 value_regno); 6745 return -EACCES; 6746 } 6747 6748 err = check_flow_keys_access(env, off, size); 6749 if (!err && t == BPF_READ && value_regno >= 0) 6750 mark_reg_unknown(env, regs, value_regno); 6751 } else if (type_is_sk_pointer(reg->type)) { 6752 if (t == BPF_WRITE) { 6753 verbose(env, "R%d cannot write into %s\n", 6754 regno, reg_type_str(env, reg->type)); 6755 return -EACCES; 6756 } 6757 err = check_sock_access(env, insn_idx, regno, off, size, t); 6758 if (!err && value_regno >= 0) 6759 mark_reg_unknown(env, regs, value_regno); 6760 } else if (reg->type == PTR_TO_TP_BUFFER) { 6761 err = check_tp_buffer_access(env, reg, regno, off, size); 6762 if (!err && t == BPF_READ && value_regno >= 0) 6763 mark_reg_unknown(env, regs, value_regno); 6764 } else if (base_type(reg->type) == PTR_TO_BTF_ID && 6765 !type_may_be_null(reg->type)) { 6766 err = check_ptr_to_btf_access(env, regs, regno, off, size, t, 6767 value_regno); 6768 } else if (reg->type == CONST_PTR_TO_MAP) { 6769 err = check_ptr_to_map_access(env, regs, regno, off, size, t, 6770 value_regno); 6771 } else if (base_type(reg->type) == PTR_TO_BUF) { 6772 bool rdonly_mem = type_is_rdonly_mem(reg->type); 6773 u32 *max_access; 6774 6775 if (rdonly_mem) { 6776 if (t == BPF_WRITE) { 6777 verbose(env, "R%d cannot write into %s\n", 6778 regno, reg_type_str(env, reg->type)); 6779 return -EACCES; 6780 } 6781 max_access = &env->prog->aux->max_rdonly_access; 6782 } else { 6783 max_access = &env->prog->aux->max_rdwr_access; 6784 } 6785 6786 err = check_buffer_access(env, reg, regno, off, size, false, 6787 max_access); 6788 6789 if (!err && value_regno >= 0 && (rdonly_mem || t == BPF_READ)) 6790 mark_reg_unknown(env, regs, value_regno); 6791 } else { 6792 verbose(env, "R%d invalid mem access '%s'\n", regno, 6793 reg_type_str(env, reg->type)); 6794 return -EACCES; 6795 } 6796 6797 if (!err && size < BPF_REG_SIZE && value_regno >= 0 && t == BPF_READ && 6798 regs[value_regno].type == SCALAR_VALUE) { 6799 if (!is_ldsx) 6800 /* b/h/w load zero-extends, mark upper bits as known 0 */ 6801 coerce_reg_to_size(®s[value_regno], size); 6802 else 6803 coerce_reg_to_size_sx(®s[value_regno], size); 6804 } 6805 return err; 6806 } 6807 6808 static int check_atomic(struct bpf_verifier_env *env, int insn_idx, struct bpf_insn *insn) 6809 { 6810 int load_reg; 6811 int err; 6812 6813 switch (insn->imm) { 6814 case BPF_ADD: 6815 case BPF_ADD | BPF_FETCH: 6816 case BPF_AND: 6817 case BPF_AND | BPF_FETCH: 6818 case BPF_OR: 6819 case BPF_OR | BPF_FETCH: 6820 case BPF_XOR: 6821 case BPF_XOR | BPF_FETCH: 6822 case BPF_XCHG: 6823 case BPF_CMPXCHG: 6824 break; 6825 default: 6826 verbose(env, "BPF_ATOMIC uses invalid atomic opcode %02x\n", insn->imm); 6827 return -EINVAL; 6828 } 6829 6830 if (BPF_SIZE(insn->code) != BPF_W && BPF_SIZE(insn->code) != BPF_DW) { 6831 verbose(env, "invalid atomic operand size\n"); 6832 return -EINVAL; 6833 } 6834 6835 /* check src1 operand */ 6836 err = check_reg_arg(env, insn->src_reg, SRC_OP); 6837 if (err) 6838 return err; 6839 6840 /* check src2 operand */ 6841 err = check_reg_arg(env, insn->dst_reg, SRC_OP); 6842 if (err) 6843 return err; 6844 6845 if (insn->imm == BPF_CMPXCHG) { 6846 /* Check comparison of R0 with memory location */ 6847 const u32 aux_reg = BPF_REG_0; 6848 6849 err = check_reg_arg(env, aux_reg, SRC_OP); 6850 if (err) 6851 return err; 6852 6853 if (is_pointer_value(env, aux_reg)) { 6854 verbose(env, "R%d leaks addr into mem\n", aux_reg); 6855 return -EACCES; 6856 } 6857 } 6858 6859 if (is_pointer_value(env, insn->src_reg)) { 6860 verbose(env, "R%d leaks addr into mem\n", insn->src_reg); 6861 return -EACCES; 6862 } 6863 6864 if (is_ctx_reg(env, insn->dst_reg) || 6865 is_pkt_reg(env, insn->dst_reg) || 6866 is_flow_key_reg(env, insn->dst_reg) || 6867 is_sk_reg(env, insn->dst_reg)) { 6868 verbose(env, "BPF_ATOMIC stores into R%d %s is not allowed\n", 6869 insn->dst_reg, 6870 reg_type_str(env, reg_state(env, insn->dst_reg)->type)); 6871 return -EACCES; 6872 } 6873 6874 if (insn->imm & BPF_FETCH) { 6875 if (insn->imm == BPF_CMPXCHG) 6876 load_reg = BPF_REG_0; 6877 else 6878 load_reg = insn->src_reg; 6879 6880 /* check and record load of old value */ 6881 err = check_reg_arg(env, load_reg, DST_OP); 6882 if (err) 6883 return err; 6884 } else { 6885 /* This instruction accesses a memory location but doesn't 6886 * actually load it into a register. 6887 */ 6888 load_reg = -1; 6889 } 6890 6891 /* Check whether we can read the memory, with second call for fetch 6892 * case to simulate the register fill. 6893 */ 6894 err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off, 6895 BPF_SIZE(insn->code), BPF_READ, -1, true, false); 6896 if (!err && load_reg >= 0) 6897 err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off, 6898 BPF_SIZE(insn->code), BPF_READ, load_reg, 6899 true, false); 6900 if (err) 6901 return err; 6902 6903 /* Check whether we can write into the same memory. */ 6904 err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off, 6905 BPF_SIZE(insn->code), BPF_WRITE, -1, true, false); 6906 if (err) 6907 return err; 6908 6909 return 0; 6910 } 6911 6912 /* When register 'regno' is used to read the stack (either directly or through 6913 * a helper function) make sure that it's within stack boundary and, depending 6914 * on the access type, that all elements of the stack are initialized. 6915 * 6916 * 'off' includes 'regno->off', but not its dynamic part (if any). 6917 * 6918 * All registers that have been spilled on the stack in the slots within the 6919 * read offsets are marked as read. 6920 */ 6921 static int check_stack_range_initialized( 6922 struct bpf_verifier_env *env, int regno, int off, 6923 int access_size, bool zero_size_allowed, 6924 enum bpf_access_src type, struct bpf_call_arg_meta *meta) 6925 { 6926 struct bpf_reg_state *reg = reg_state(env, regno); 6927 struct bpf_func_state *state = func(env, reg); 6928 int err, min_off, max_off, i, j, slot, spi; 6929 char *err_extra = type == ACCESS_HELPER ? " indirect" : ""; 6930 enum bpf_access_type bounds_check_type; 6931 /* Some accesses can write anything into the stack, others are 6932 * read-only. 6933 */ 6934 bool clobber = false; 6935 6936 if (access_size == 0 && !zero_size_allowed) { 6937 verbose(env, "invalid zero-sized read\n"); 6938 return -EACCES; 6939 } 6940 6941 if (type == ACCESS_HELPER) { 6942 /* The bounds checks for writes are more permissive than for 6943 * reads. However, if raw_mode is not set, we'll do extra 6944 * checks below. 6945 */ 6946 bounds_check_type = BPF_WRITE; 6947 clobber = true; 6948 } else { 6949 bounds_check_type = BPF_READ; 6950 } 6951 err = check_stack_access_within_bounds(env, regno, off, access_size, 6952 type, bounds_check_type); 6953 if (err) 6954 return err; 6955 6956 6957 if (tnum_is_const(reg->var_off)) { 6958 min_off = max_off = reg->var_off.value + off; 6959 } else { 6960 /* Variable offset is prohibited for unprivileged mode for 6961 * simplicity since it requires corresponding support in 6962 * Spectre masking for stack ALU. 6963 * See also retrieve_ptr_limit(). 6964 */ 6965 if (!env->bypass_spec_v1) { 6966 char tn_buf[48]; 6967 6968 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 6969 verbose(env, "R%d%s variable offset stack access prohibited for !root, var_off=%s\n", 6970 regno, err_extra, tn_buf); 6971 return -EACCES; 6972 } 6973 /* Only initialized buffer on stack is allowed to be accessed 6974 * with variable offset. With uninitialized buffer it's hard to 6975 * guarantee that whole memory is marked as initialized on 6976 * helper return since specific bounds are unknown what may 6977 * cause uninitialized stack leaking. 6978 */ 6979 if (meta && meta->raw_mode) 6980 meta = NULL; 6981 6982 min_off = reg->smin_value + off; 6983 max_off = reg->smax_value + off; 6984 } 6985 6986 if (meta && meta->raw_mode) { 6987 /* Ensure we won't be overwriting dynptrs when simulating byte 6988 * by byte access in check_helper_call using meta.access_size. 6989 * This would be a problem if we have a helper in the future 6990 * which takes: 6991 * 6992 * helper(uninit_mem, len, dynptr) 6993 * 6994 * Now, uninint_mem may overlap with dynptr pointer. Hence, it 6995 * may end up writing to dynptr itself when touching memory from 6996 * arg 1. This can be relaxed on a case by case basis for known 6997 * safe cases, but reject due to the possibilitiy of aliasing by 6998 * default. 6999 */ 7000 for (i = min_off; i < max_off + access_size; i++) { 7001 int stack_off = -i - 1; 7002 7003 spi = __get_spi(i); 7004 /* raw_mode may write past allocated_stack */ 7005 if (state->allocated_stack <= stack_off) 7006 continue; 7007 if (state->stack[spi].slot_type[stack_off % BPF_REG_SIZE] == STACK_DYNPTR) { 7008 verbose(env, "potential write to dynptr at off=%d disallowed\n", i); 7009 return -EACCES; 7010 } 7011 } 7012 meta->access_size = access_size; 7013 meta->regno = regno; 7014 return 0; 7015 } 7016 7017 for (i = min_off; i < max_off + access_size; i++) { 7018 u8 *stype; 7019 7020 slot = -i - 1; 7021 spi = slot / BPF_REG_SIZE; 7022 if (state->allocated_stack <= slot) 7023 goto err; 7024 stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE]; 7025 if (*stype == STACK_MISC) 7026 goto mark; 7027 if ((*stype == STACK_ZERO) || 7028 (*stype == STACK_INVALID && env->allow_uninit_stack)) { 7029 if (clobber) { 7030 /* helper can write anything into the stack */ 7031 *stype = STACK_MISC; 7032 } 7033 goto mark; 7034 } 7035 7036 if (is_spilled_reg(&state->stack[spi]) && 7037 (state->stack[spi].spilled_ptr.type == SCALAR_VALUE || 7038 env->allow_ptr_leaks)) { 7039 if (clobber) { 7040 __mark_reg_unknown(env, &state->stack[spi].spilled_ptr); 7041 for (j = 0; j < BPF_REG_SIZE; j++) 7042 scrub_spilled_slot(&state->stack[spi].slot_type[j]); 7043 } 7044 goto mark; 7045 } 7046 7047 err: 7048 if (tnum_is_const(reg->var_off)) { 7049 verbose(env, "invalid%s read from stack R%d off %d+%d size %d\n", 7050 err_extra, regno, min_off, i - min_off, access_size); 7051 } else { 7052 char tn_buf[48]; 7053 7054 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 7055 verbose(env, "invalid%s read from stack R%d var_off %s+%d size %d\n", 7056 err_extra, regno, tn_buf, i - min_off, access_size); 7057 } 7058 return -EACCES; 7059 mark: 7060 /* reading any byte out of 8-byte 'spill_slot' will cause 7061 * the whole slot to be marked as 'read' 7062 */ 7063 mark_reg_read(env, &state->stack[spi].spilled_ptr, 7064 state->stack[spi].spilled_ptr.parent, 7065 REG_LIVE_READ64); 7066 /* We do not set REG_LIVE_WRITTEN for stack slot, as we can not 7067 * be sure that whether stack slot is written to or not. Hence, 7068 * we must still conservatively propagate reads upwards even if 7069 * helper may write to the entire memory range. 7070 */ 7071 } 7072 return update_stack_depth(env, state, min_off); 7073 } 7074 7075 static int check_helper_mem_access(struct bpf_verifier_env *env, int regno, 7076 int access_size, bool zero_size_allowed, 7077 struct bpf_call_arg_meta *meta) 7078 { 7079 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno]; 7080 u32 *max_access; 7081 7082 switch (base_type(reg->type)) { 7083 case PTR_TO_PACKET: 7084 case PTR_TO_PACKET_META: 7085 return check_packet_access(env, regno, reg->off, access_size, 7086 zero_size_allowed); 7087 case PTR_TO_MAP_KEY: 7088 if (meta && meta->raw_mode) { 7089 verbose(env, "R%d cannot write into %s\n", regno, 7090 reg_type_str(env, reg->type)); 7091 return -EACCES; 7092 } 7093 return check_mem_region_access(env, regno, reg->off, access_size, 7094 reg->map_ptr->key_size, false); 7095 case PTR_TO_MAP_VALUE: 7096 if (check_map_access_type(env, regno, reg->off, access_size, 7097 meta && meta->raw_mode ? BPF_WRITE : 7098 BPF_READ)) 7099 return -EACCES; 7100 return check_map_access(env, regno, reg->off, access_size, 7101 zero_size_allowed, ACCESS_HELPER); 7102 case PTR_TO_MEM: 7103 if (type_is_rdonly_mem(reg->type)) { 7104 if (meta && meta->raw_mode) { 7105 verbose(env, "R%d cannot write into %s\n", regno, 7106 reg_type_str(env, reg->type)); 7107 return -EACCES; 7108 } 7109 } 7110 return check_mem_region_access(env, regno, reg->off, 7111 access_size, reg->mem_size, 7112 zero_size_allowed); 7113 case PTR_TO_BUF: 7114 if (type_is_rdonly_mem(reg->type)) { 7115 if (meta && meta->raw_mode) { 7116 verbose(env, "R%d cannot write into %s\n", regno, 7117 reg_type_str(env, reg->type)); 7118 return -EACCES; 7119 } 7120 7121 max_access = &env->prog->aux->max_rdonly_access; 7122 } else { 7123 max_access = &env->prog->aux->max_rdwr_access; 7124 } 7125 return check_buffer_access(env, reg, regno, reg->off, 7126 access_size, zero_size_allowed, 7127 max_access); 7128 case PTR_TO_STACK: 7129 return check_stack_range_initialized( 7130 env, 7131 regno, reg->off, access_size, 7132 zero_size_allowed, ACCESS_HELPER, meta); 7133 case PTR_TO_BTF_ID: 7134 return check_ptr_to_btf_access(env, regs, regno, reg->off, 7135 access_size, BPF_READ, -1); 7136 case PTR_TO_CTX: 7137 /* in case the function doesn't know how to access the context, 7138 * (because we are in a program of type SYSCALL for example), we 7139 * can not statically check its size. 7140 * Dynamically check it now. 7141 */ 7142 if (!env->ops->convert_ctx_access) { 7143 enum bpf_access_type atype = meta && meta->raw_mode ? BPF_WRITE : BPF_READ; 7144 int offset = access_size - 1; 7145 7146 /* Allow zero-byte read from PTR_TO_CTX */ 7147 if (access_size == 0) 7148 return zero_size_allowed ? 0 : -EACCES; 7149 7150 return check_mem_access(env, env->insn_idx, regno, offset, BPF_B, 7151 atype, -1, false, false); 7152 } 7153 7154 fallthrough; 7155 default: /* scalar_value or invalid ptr */ 7156 /* Allow zero-byte read from NULL, regardless of pointer type */ 7157 if (zero_size_allowed && access_size == 0 && 7158 register_is_null(reg)) 7159 return 0; 7160 7161 verbose(env, "R%d type=%s ", regno, 7162 reg_type_str(env, reg->type)); 7163 verbose(env, "expected=%s\n", reg_type_str(env, PTR_TO_STACK)); 7164 return -EACCES; 7165 } 7166 } 7167 7168 static int check_mem_size_reg(struct bpf_verifier_env *env, 7169 struct bpf_reg_state *reg, u32 regno, 7170 bool zero_size_allowed, 7171 struct bpf_call_arg_meta *meta) 7172 { 7173 int err; 7174 7175 /* This is used to refine r0 return value bounds for helpers 7176 * that enforce this value as an upper bound on return values. 7177 * See do_refine_retval_range() for helpers that can refine 7178 * the return value. C type of helper is u32 so we pull register 7179 * bound from umax_value however, if negative verifier errors 7180 * out. Only upper bounds can be learned because retval is an 7181 * int type and negative retvals are allowed. 7182 */ 7183 meta->msize_max_value = reg->umax_value; 7184 7185 /* The register is SCALAR_VALUE; the access check 7186 * happens using its boundaries. 7187 */ 7188 if (!tnum_is_const(reg->var_off)) 7189 /* For unprivileged variable accesses, disable raw 7190 * mode so that the program is required to 7191 * initialize all the memory that the helper could 7192 * just partially fill up. 7193 */ 7194 meta = NULL; 7195 7196 if (reg->smin_value < 0) { 7197 verbose(env, "R%d min value is negative, either use unsigned or 'var &= const'\n", 7198 regno); 7199 return -EACCES; 7200 } 7201 7202 if (reg->umin_value == 0) { 7203 err = check_helper_mem_access(env, regno - 1, 0, 7204 zero_size_allowed, 7205 meta); 7206 if (err) 7207 return err; 7208 } 7209 7210 if (reg->umax_value >= BPF_MAX_VAR_SIZ) { 7211 verbose(env, "R%d unbounded memory access, use 'var &= const' or 'if (var < const)'\n", 7212 regno); 7213 return -EACCES; 7214 } 7215 err = check_helper_mem_access(env, regno - 1, 7216 reg->umax_value, 7217 zero_size_allowed, meta); 7218 if (!err) 7219 err = mark_chain_precision(env, regno); 7220 return err; 7221 } 7222 7223 int check_mem_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg, 7224 u32 regno, u32 mem_size) 7225 { 7226 bool may_be_null = type_may_be_null(reg->type); 7227 struct bpf_reg_state saved_reg; 7228 struct bpf_call_arg_meta meta; 7229 int err; 7230 7231 if (register_is_null(reg)) 7232 return 0; 7233 7234 memset(&meta, 0, sizeof(meta)); 7235 /* Assuming that the register contains a value check if the memory 7236 * access is safe. Temporarily save and restore the register's state as 7237 * the conversion shouldn't be visible to a caller. 7238 */ 7239 if (may_be_null) { 7240 saved_reg = *reg; 7241 mark_ptr_not_null_reg(reg); 7242 } 7243 7244 err = check_helper_mem_access(env, regno, mem_size, true, &meta); 7245 /* Check access for BPF_WRITE */ 7246 meta.raw_mode = true; 7247 err = err ?: check_helper_mem_access(env, regno, mem_size, true, &meta); 7248 7249 if (may_be_null) 7250 *reg = saved_reg; 7251 7252 return err; 7253 } 7254 7255 static int check_kfunc_mem_size_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg, 7256 u32 regno) 7257 { 7258 struct bpf_reg_state *mem_reg = &cur_regs(env)[regno - 1]; 7259 bool may_be_null = type_may_be_null(mem_reg->type); 7260 struct bpf_reg_state saved_reg; 7261 struct bpf_call_arg_meta meta; 7262 int err; 7263 7264 WARN_ON_ONCE(regno < BPF_REG_2 || regno > BPF_REG_5); 7265 7266 memset(&meta, 0, sizeof(meta)); 7267 7268 if (may_be_null) { 7269 saved_reg = *mem_reg; 7270 mark_ptr_not_null_reg(mem_reg); 7271 } 7272 7273 err = check_mem_size_reg(env, reg, regno, true, &meta); 7274 /* Check access for BPF_WRITE */ 7275 meta.raw_mode = true; 7276 err = err ?: check_mem_size_reg(env, reg, regno, true, &meta); 7277 7278 if (may_be_null) 7279 *mem_reg = saved_reg; 7280 return err; 7281 } 7282 7283 /* Implementation details: 7284 * bpf_map_lookup returns PTR_TO_MAP_VALUE_OR_NULL. 7285 * bpf_obj_new returns PTR_TO_BTF_ID | MEM_ALLOC | PTR_MAYBE_NULL. 7286 * Two bpf_map_lookups (even with the same key) will have different reg->id. 7287 * Two separate bpf_obj_new will also have different reg->id. 7288 * For traditional PTR_TO_MAP_VALUE or PTR_TO_BTF_ID | MEM_ALLOC, the verifier 7289 * clears reg->id after value_or_null->value transition, since the verifier only 7290 * cares about the range of access to valid map value pointer and doesn't care 7291 * about actual address of the map element. 7292 * For maps with 'struct bpf_spin_lock' inside map value the verifier keeps 7293 * reg->id > 0 after value_or_null->value transition. By doing so 7294 * two bpf_map_lookups will be considered two different pointers that 7295 * point to different bpf_spin_locks. Likewise for pointers to allocated objects 7296 * returned from bpf_obj_new. 7297 * The verifier allows taking only one bpf_spin_lock at a time to avoid 7298 * dead-locks. 7299 * Since only one bpf_spin_lock is allowed the checks are simpler than 7300 * reg_is_refcounted() logic. The verifier needs to remember only 7301 * one spin_lock instead of array of acquired_refs. 7302 * cur_state->active_lock remembers which map value element or allocated 7303 * object got locked and clears it after bpf_spin_unlock. 7304 */ 7305 static int process_spin_lock(struct bpf_verifier_env *env, int regno, 7306 bool is_lock) 7307 { 7308 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno]; 7309 struct bpf_verifier_state *cur = env->cur_state; 7310 bool is_const = tnum_is_const(reg->var_off); 7311 u64 val = reg->var_off.value; 7312 struct bpf_map *map = NULL; 7313 struct btf *btf = NULL; 7314 struct btf_record *rec; 7315 7316 if (!is_const) { 7317 verbose(env, 7318 "R%d doesn't have constant offset. bpf_spin_lock has to be at the constant offset\n", 7319 regno); 7320 return -EINVAL; 7321 } 7322 if (reg->type == PTR_TO_MAP_VALUE) { 7323 map = reg->map_ptr; 7324 if (!map->btf) { 7325 verbose(env, 7326 "map '%s' has to have BTF in order to use bpf_spin_lock\n", 7327 map->name); 7328 return -EINVAL; 7329 } 7330 } else { 7331 btf = reg->btf; 7332 } 7333 7334 rec = reg_btf_record(reg); 7335 if (!btf_record_has_field(rec, BPF_SPIN_LOCK)) { 7336 verbose(env, "%s '%s' has no valid bpf_spin_lock\n", map ? "map" : "local", 7337 map ? map->name : "kptr"); 7338 return -EINVAL; 7339 } 7340 if (rec->spin_lock_off != val + reg->off) { 7341 verbose(env, "off %lld doesn't point to 'struct bpf_spin_lock' that is at %d\n", 7342 val + reg->off, rec->spin_lock_off); 7343 return -EINVAL; 7344 } 7345 if (is_lock) { 7346 if (cur->active_lock.ptr) { 7347 verbose(env, 7348 "Locking two bpf_spin_locks are not allowed\n"); 7349 return -EINVAL; 7350 } 7351 if (map) 7352 cur->active_lock.ptr = map; 7353 else 7354 cur->active_lock.ptr = btf; 7355 cur->active_lock.id = reg->id; 7356 } else { 7357 void *ptr; 7358 7359 if (map) 7360 ptr = map; 7361 else 7362 ptr = btf; 7363 7364 if (!cur->active_lock.ptr) { 7365 verbose(env, "bpf_spin_unlock without taking a lock\n"); 7366 return -EINVAL; 7367 } 7368 if (cur->active_lock.ptr != ptr || 7369 cur->active_lock.id != reg->id) { 7370 verbose(env, "bpf_spin_unlock of different lock\n"); 7371 return -EINVAL; 7372 } 7373 7374 invalidate_non_owning_refs(env); 7375 7376 cur->active_lock.ptr = NULL; 7377 cur->active_lock.id = 0; 7378 } 7379 return 0; 7380 } 7381 7382 static int process_timer_func(struct bpf_verifier_env *env, int regno, 7383 struct bpf_call_arg_meta *meta) 7384 { 7385 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno]; 7386 bool is_const = tnum_is_const(reg->var_off); 7387 struct bpf_map *map = reg->map_ptr; 7388 u64 val = reg->var_off.value; 7389 7390 if (!is_const) { 7391 verbose(env, 7392 "R%d doesn't have constant offset. bpf_timer has to be at the constant offset\n", 7393 regno); 7394 return -EINVAL; 7395 } 7396 if (!map->btf) { 7397 verbose(env, "map '%s' has to have BTF in order to use bpf_timer\n", 7398 map->name); 7399 return -EINVAL; 7400 } 7401 if (!btf_record_has_field(map->record, BPF_TIMER)) { 7402 verbose(env, "map '%s' has no valid bpf_timer\n", map->name); 7403 return -EINVAL; 7404 } 7405 if (map->record->timer_off != val + reg->off) { 7406 verbose(env, "off %lld doesn't point to 'struct bpf_timer' that is at %d\n", 7407 val + reg->off, map->record->timer_off); 7408 return -EINVAL; 7409 } 7410 if (meta->map_ptr) { 7411 verbose(env, "verifier bug. Two map pointers in a timer helper\n"); 7412 return -EFAULT; 7413 } 7414 meta->map_uid = reg->map_uid; 7415 meta->map_ptr = map; 7416 return 0; 7417 } 7418 7419 static int process_kptr_func(struct bpf_verifier_env *env, int regno, 7420 struct bpf_call_arg_meta *meta) 7421 { 7422 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno]; 7423 struct bpf_map *map_ptr = reg->map_ptr; 7424 struct btf_field *kptr_field; 7425 u32 kptr_off; 7426 7427 if (!tnum_is_const(reg->var_off)) { 7428 verbose(env, 7429 "R%d doesn't have constant offset. kptr has to be at the constant offset\n", 7430 regno); 7431 return -EINVAL; 7432 } 7433 if (!map_ptr->btf) { 7434 verbose(env, "map '%s' has to have BTF in order to use bpf_kptr_xchg\n", 7435 map_ptr->name); 7436 return -EINVAL; 7437 } 7438 if (!btf_record_has_field(map_ptr->record, BPF_KPTR)) { 7439 verbose(env, "map '%s' has no valid kptr\n", map_ptr->name); 7440 return -EINVAL; 7441 } 7442 7443 meta->map_ptr = map_ptr; 7444 kptr_off = reg->off + reg->var_off.value; 7445 kptr_field = btf_record_find(map_ptr->record, kptr_off, BPF_KPTR); 7446 if (!kptr_field) { 7447 verbose(env, "off=%d doesn't point to kptr\n", kptr_off); 7448 return -EACCES; 7449 } 7450 if (kptr_field->type != BPF_KPTR_REF && kptr_field->type != BPF_KPTR_PERCPU) { 7451 verbose(env, "off=%d kptr isn't referenced kptr\n", kptr_off); 7452 return -EACCES; 7453 } 7454 meta->kptr_field = kptr_field; 7455 return 0; 7456 } 7457 7458 /* There are two register types representing a bpf_dynptr, one is PTR_TO_STACK 7459 * which points to a stack slot, and the other is CONST_PTR_TO_DYNPTR. 7460 * 7461 * In both cases we deal with the first 8 bytes, but need to mark the next 8 7462 * bytes as STACK_DYNPTR in case of PTR_TO_STACK. In case of 7463 * CONST_PTR_TO_DYNPTR, we are guaranteed to get the beginning of the object. 7464 * 7465 * Mutability of bpf_dynptr is at two levels, one is at the level of struct 7466 * bpf_dynptr itself, i.e. whether the helper is receiving a pointer to struct 7467 * bpf_dynptr or pointer to const struct bpf_dynptr. In the former case, it can 7468 * mutate the view of the dynptr and also possibly destroy it. In the latter 7469 * case, it cannot mutate the bpf_dynptr itself but it can still mutate the 7470 * memory that dynptr points to. 7471 * 7472 * The verifier will keep track both levels of mutation (bpf_dynptr's in 7473 * reg->type and the memory's in reg->dynptr.type), but there is no support for 7474 * readonly dynptr view yet, hence only the first case is tracked and checked. 7475 * 7476 * This is consistent with how C applies the const modifier to a struct object, 7477 * where the pointer itself inside bpf_dynptr becomes const but not what it 7478 * points to. 7479 * 7480 * Helpers which do not mutate the bpf_dynptr set MEM_RDONLY in their argument 7481 * type, and declare it as 'const struct bpf_dynptr *' in their prototype. 7482 */ 7483 static int process_dynptr_func(struct bpf_verifier_env *env, int regno, int insn_idx, 7484 enum bpf_arg_type arg_type, int clone_ref_obj_id) 7485 { 7486 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno]; 7487 int err; 7488 7489 /* MEM_UNINIT and MEM_RDONLY are exclusive, when applied to an 7490 * ARG_PTR_TO_DYNPTR (or ARG_PTR_TO_DYNPTR | DYNPTR_TYPE_*): 7491 */ 7492 if ((arg_type & (MEM_UNINIT | MEM_RDONLY)) == (MEM_UNINIT | MEM_RDONLY)) { 7493 verbose(env, "verifier internal error: misconfigured dynptr helper type flags\n"); 7494 return -EFAULT; 7495 } 7496 7497 /* MEM_UNINIT - Points to memory that is an appropriate candidate for 7498 * constructing a mutable bpf_dynptr object. 7499 * 7500 * Currently, this is only possible with PTR_TO_STACK 7501 * pointing to a region of at least 16 bytes which doesn't 7502 * contain an existing bpf_dynptr. 7503 * 7504 * MEM_RDONLY - Points to a initialized bpf_dynptr that will not be 7505 * mutated or destroyed. However, the memory it points to 7506 * may be mutated. 7507 * 7508 * None - Points to a initialized dynptr that can be mutated and 7509 * destroyed, including mutation of the memory it points 7510 * to. 7511 */ 7512 if (arg_type & MEM_UNINIT) { 7513 int i; 7514 7515 if (!is_dynptr_reg_valid_uninit(env, reg)) { 7516 verbose(env, "Dynptr has to be an uninitialized dynptr\n"); 7517 return -EINVAL; 7518 } 7519 7520 /* we write BPF_DW bits (8 bytes) at a time */ 7521 for (i = 0; i < BPF_DYNPTR_SIZE; i += 8) { 7522 err = check_mem_access(env, insn_idx, regno, 7523 i, BPF_DW, BPF_WRITE, -1, false, false); 7524 if (err) 7525 return err; 7526 } 7527 7528 err = mark_stack_slots_dynptr(env, reg, arg_type, insn_idx, clone_ref_obj_id); 7529 } else /* MEM_RDONLY and None case from above */ { 7530 /* For the reg->type == PTR_TO_STACK case, bpf_dynptr is never const */ 7531 if (reg->type == CONST_PTR_TO_DYNPTR && !(arg_type & MEM_RDONLY)) { 7532 verbose(env, "cannot pass pointer to const bpf_dynptr, the helper mutates it\n"); 7533 return -EINVAL; 7534 } 7535 7536 if (!is_dynptr_reg_valid_init(env, reg)) { 7537 verbose(env, 7538 "Expected an initialized dynptr as arg #%d\n", 7539 regno); 7540 return -EINVAL; 7541 } 7542 7543 /* Fold modifiers (in this case, MEM_RDONLY) when checking expected type */ 7544 if (!is_dynptr_type_expected(env, reg, arg_type & ~MEM_RDONLY)) { 7545 verbose(env, 7546 "Expected a dynptr of type %s as arg #%d\n", 7547 dynptr_type_str(arg_to_dynptr_type(arg_type)), regno); 7548 return -EINVAL; 7549 } 7550 7551 err = mark_dynptr_read(env, reg); 7552 } 7553 return err; 7554 } 7555 7556 static u32 iter_ref_obj_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg, int spi) 7557 { 7558 struct bpf_func_state *state = func(env, reg); 7559 7560 return state->stack[spi].spilled_ptr.ref_obj_id; 7561 } 7562 7563 static bool is_iter_kfunc(struct bpf_kfunc_call_arg_meta *meta) 7564 { 7565 return meta->kfunc_flags & (KF_ITER_NEW | KF_ITER_NEXT | KF_ITER_DESTROY); 7566 } 7567 7568 static bool is_iter_new_kfunc(struct bpf_kfunc_call_arg_meta *meta) 7569 { 7570 return meta->kfunc_flags & KF_ITER_NEW; 7571 } 7572 7573 static bool is_iter_next_kfunc(struct bpf_kfunc_call_arg_meta *meta) 7574 { 7575 return meta->kfunc_flags & KF_ITER_NEXT; 7576 } 7577 7578 static bool is_iter_destroy_kfunc(struct bpf_kfunc_call_arg_meta *meta) 7579 { 7580 return meta->kfunc_flags & KF_ITER_DESTROY; 7581 } 7582 7583 static bool is_kfunc_arg_iter(struct bpf_kfunc_call_arg_meta *meta, int arg) 7584 { 7585 /* btf_check_iter_kfuncs() guarantees that first argument of any iter 7586 * kfunc is iter state pointer 7587 */ 7588 return arg == 0 && is_iter_kfunc(meta); 7589 } 7590 7591 static int process_iter_arg(struct bpf_verifier_env *env, int regno, int insn_idx, 7592 struct bpf_kfunc_call_arg_meta *meta) 7593 { 7594 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno]; 7595 const struct btf_type *t; 7596 const struct btf_param *arg; 7597 int spi, err, i, nr_slots; 7598 u32 btf_id; 7599 7600 /* btf_check_iter_kfuncs() ensures we don't need to validate anything here */ 7601 arg = &btf_params(meta->func_proto)[0]; 7602 t = btf_type_skip_modifiers(meta->btf, arg->type, NULL); /* PTR */ 7603 t = btf_type_skip_modifiers(meta->btf, t->type, &btf_id); /* STRUCT */ 7604 nr_slots = t->size / BPF_REG_SIZE; 7605 7606 if (is_iter_new_kfunc(meta)) { 7607 /* bpf_iter_<type>_new() expects pointer to uninit iter state */ 7608 if (!is_iter_reg_valid_uninit(env, reg, nr_slots)) { 7609 verbose(env, "expected uninitialized iter_%s as arg #%d\n", 7610 iter_type_str(meta->btf, btf_id), regno); 7611 return -EINVAL; 7612 } 7613 7614 for (i = 0; i < nr_slots * 8; i += BPF_REG_SIZE) { 7615 err = check_mem_access(env, insn_idx, regno, 7616 i, BPF_DW, BPF_WRITE, -1, false, false); 7617 if (err) 7618 return err; 7619 } 7620 7621 err = mark_stack_slots_iter(env, reg, insn_idx, meta->btf, btf_id, nr_slots); 7622 if (err) 7623 return err; 7624 } else { 7625 /* iter_next() or iter_destroy() expect initialized iter state*/ 7626 if (!is_iter_reg_valid_init(env, reg, meta->btf, btf_id, nr_slots)) { 7627 verbose(env, "expected an initialized iter_%s as arg #%d\n", 7628 iter_type_str(meta->btf, btf_id), regno); 7629 return -EINVAL; 7630 } 7631 7632 spi = iter_get_spi(env, reg, nr_slots); 7633 if (spi < 0) 7634 return spi; 7635 7636 err = mark_iter_read(env, reg, spi, nr_slots); 7637 if (err) 7638 return err; 7639 7640 /* remember meta->iter info for process_iter_next_call() */ 7641 meta->iter.spi = spi; 7642 meta->iter.frameno = reg->frameno; 7643 meta->ref_obj_id = iter_ref_obj_id(env, reg, spi); 7644 7645 if (is_iter_destroy_kfunc(meta)) { 7646 err = unmark_stack_slots_iter(env, reg, nr_slots); 7647 if (err) 7648 return err; 7649 } 7650 } 7651 7652 return 0; 7653 } 7654 7655 /* process_iter_next_call() is called when verifier gets to iterator's next 7656 * "method" (e.g., bpf_iter_num_next() for numbers iterator) call. We'll refer 7657 * to it as just "iter_next()" in comments below. 7658 * 7659 * BPF verifier relies on a crucial contract for any iter_next() 7660 * implementation: it should *eventually* return NULL, and once that happens 7661 * it should keep returning NULL. That is, once iterator exhausts elements to 7662 * iterate, it should never reset or spuriously return new elements. 7663 * 7664 * With the assumption of such contract, process_iter_next_call() simulates 7665 * a fork in the verifier state to validate loop logic correctness and safety 7666 * without having to simulate infinite amount of iterations. 7667 * 7668 * In current state, we first assume that iter_next() returned NULL and 7669 * iterator state is set to DRAINED (BPF_ITER_STATE_DRAINED). In such 7670 * conditions we should not form an infinite loop and should eventually reach 7671 * exit. 7672 * 7673 * Besides that, we also fork current state and enqueue it for later 7674 * verification. In a forked state we keep iterator state as ACTIVE 7675 * (BPF_ITER_STATE_ACTIVE) and assume non-NULL return from iter_next(). We 7676 * also bump iteration depth to prevent erroneous infinite loop detection 7677 * later on (see iter_active_depths_differ() comment for details). In this 7678 * state we assume that we'll eventually loop back to another iter_next() 7679 * calls (it could be in exactly same location or in some other instruction, 7680 * it doesn't matter, we don't make any unnecessary assumptions about this, 7681 * everything revolves around iterator state in a stack slot, not which 7682 * instruction is calling iter_next()). When that happens, we either will come 7683 * to iter_next() with equivalent state and can conclude that next iteration 7684 * will proceed in exactly the same way as we just verified, so it's safe to 7685 * assume that loop converges. If not, we'll go on another iteration 7686 * simulation with a different input state, until all possible starting states 7687 * are validated or we reach maximum number of instructions limit. 7688 * 7689 * This way, we will either exhaustively discover all possible input states 7690 * that iterator loop can start with and eventually will converge, or we'll 7691 * effectively regress into bounded loop simulation logic and either reach 7692 * maximum number of instructions if loop is not provably convergent, or there 7693 * is some statically known limit on number of iterations (e.g., if there is 7694 * an explicit `if n > 100 then break;` statement somewhere in the loop). 7695 * 7696 * One very subtle but very important aspect is that we *always* simulate NULL 7697 * condition first (as the current state) before we simulate non-NULL case. 7698 * This has to do with intricacies of scalar precision tracking. By simulating 7699 * "exit condition" of iter_next() returning NULL first, we make sure all the 7700 * relevant precision marks *that will be set **after** we exit iterator loop* 7701 * are propagated backwards to common parent state of NULL and non-NULL 7702 * branches. Thanks to that, state equivalence checks done later in forked 7703 * state, when reaching iter_next() for ACTIVE iterator, can assume that 7704 * precision marks are finalized and won't change. Because simulating another 7705 * ACTIVE iterator iteration won't change them (because given same input 7706 * states we'll end up with exactly same output states which we are currently 7707 * comparing; and verification after the loop already propagated back what 7708 * needs to be **additionally** tracked as precise). It's subtle, grok 7709 * precision tracking for more intuitive understanding. 7710 */ 7711 static int process_iter_next_call(struct bpf_verifier_env *env, int insn_idx, 7712 struct bpf_kfunc_call_arg_meta *meta) 7713 { 7714 struct bpf_verifier_state *cur_st = env->cur_state, *queued_st; 7715 struct bpf_func_state *cur_fr = cur_st->frame[cur_st->curframe], *queued_fr; 7716 struct bpf_reg_state *cur_iter, *queued_iter; 7717 int iter_frameno = meta->iter.frameno; 7718 int iter_spi = meta->iter.spi; 7719 7720 BTF_TYPE_EMIT(struct bpf_iter); 7721 7722 cur_iter = &env->cur_state->frame[iter_frameno]->stack[iter_spi].spilled_ptr; 7723 7724 if (cur_iter->iter.state != BPF_ITER_STATE_ACTIVE && 7725 cur_iter->iter.state != BPF_ITER_STATE_DRAINED) { 7726 verbose(env, "verifier internal error: unexpected iterator state %d (%s)\n", 7727 cur_iter->iter.state, iter_state_str(cur_iter->iter.state)); 7728 return -EFAULT; 7729 } 7730 7731 if (cur_iter->iter.state == BPF_ITER_STATE_ACTIVE) { 7732 /* branch out active iter state */ 7733 queued_st = push_stack(env, insn_idx + 1, insn_idx, false); 7734 if (!queued_st) 7735 return -ENOMEM; 7736 7737 queued_iter = &queued_st->frame[iter_frameno]->stack[iter_spi].spilled_ptr; 7738 queued_iter->iter.state = BPF_ITER_STATE_ACTIVE; 7739 queued_iter->iter.depth++; 7740 7741 queued_fr = queued_st->frame[queued_st->curframe]; 7742 mark_ptr_not_null_reg(&queued_fr->regs[BPF_REG_0]); 7743 } 7744 7745 /* switch to DRAINED state, but keep the depth unchanged */ 7746 /* mark current iter state as drained and assume returned NULL */ 7747 cur_iter->iter.state = BPF_ITER_STATE_DRAINED; 7748 __mark_reg_const_zero(&cur_fr->regs[BPF_REG_0]); 7749 7750 return 0; 7751 } 7752 7753 static bool arg_type_is_mem_size(enum bpf_arg_type type) 7754 { 7755 return type == ARG_CONST_SIZE || 7756 type == ARG_CONST_SIZE_OR_ZERO; 7757 } 7758 7759 static bool arg_type_is_release(enum bpf_arg_type type) 7760 { 7761 return type & OBJ_RELEASE; 7762 } 7763 7764 static bool arg_type_is_dynptr(enum bpf_arg_type type) 7765 { 7766 return base_type(type) == ARG_PTR_TO_DYNPTR; 7767 } 7768 7769 static int int_ptr_type_to_size(enum bpf_arg_type type) 7770 { 7771 if (type == ARG_PTR_TO_INT) 7772 return sizeof(u32); 7773 else if (type == ARG_PTR_TO_LONG) 7774 return sizeof(u64); 7775 7776 return -EINVAL; 7777 } 7778 7779 static int resolve_map_arg_type(struct bpf_verifier_env *env, 7780 const struct bpf_call_arg_meta *meta, 7781 enum bpf_arg_type *arg_type) 7782 { 7783 if (!meta->map_ptr) { 7784 /* kernel subsystem misconfigured verifier */ 7785 verbose(env, "invalid map_ptr to access map->type\n"); 7786 return -EACCES; 7787 } 7788 7789 switch (meta->map_ptr->map_type) { 7790 case BPF_MAP_TYPE_SOCKMAP: 7791 case BPF_MAP_TYPE_SOCKHASH: 7792 if (*arg_type == ARG_PTR_TO_MAP_VALUE) { 7793 *arg_type = ARG_PTR_TO_BTF_ID_SOCK_COMMON; 7794 } else { 7795 verbose(env, "invalid arg_type for sockmap/sockhash\n"); 7796 return -EINVAL; 7797 } 7798 break; 7799 case BPF_MAP_TYPE_BLOOM_FILTER: 7800 if (meta->func_id == BPF_FUNC_map_peek_elem) 7801 *arg_type = ARG_PTR_TO_MAP_VALUE; 7802 break; 7803 default: 7804 break; 7805 } 7806 return 0; 7807 } 7808 7809 struct bpf_reg_types { 7810 const enum bpf_reg_type types[10]; 7811 u32 *btf_id; 7812 }; 7813 7814 static const struct bpf_reg_types sock_types = { 7815 .types = { 7816 PTR_TO_SOCK_COMMON, 7817 PTR_TO_SOCKET, 7818 PTR_TO_TCP_SOCK, 7819 PTR_TO_XDP_SOCK, 7820 }, 7821 }; 7822 7823 #ifdef CONFIG_NET 7824 static const struct bpf_reg_types btf_id_sock_common_types = { 7825 .types = { 7826 PTR_TO_SOCK_COMMON, 7827 PTR_TO_SOCKET, 7828 PTR_TO_TCP_SOCK, 7829 PTR_TO_XDP_SOCK, 7830 PTR_TO_BTF_ID, 7831 PTR_TO_BTF_ID | PTR_TRUSTED, 7832 }, 7833 .btf_id = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON], 7834 }; 7835 #endif 7836 7837 static const struct bpf_reg_types mem_types = { 7838 .types = { 7839 PTR_TO_STACK, 7840 PTR_TO_PACKET, 7841 PTR_TO_PACKET_META, 7842 PTR_TO_MAP_KEY, 7843 PTR_TO_MAP_VALUE, 7844 PTR_TO_MEM, 7845 PTR_TO_MEM | MEM_RINGBUF, 7846 PTR_TO_BUF, 7847 PTR_TO_BTF_ID | PTR_TRUSTED, 7848 }, 7849 }; 7850 7851 static const struct bpf_reg_types int_ptr_types = { 7852 .types = { 7853 PTR_TO_STACK, 7854 PTR_TO_PACKET, 7855 PTR_TO_PACKET_META, 7856 PTR_TO_MAP_KEY, 7857 PTR_TO_MAP_VALUE, 7858 }, 7859 }; 7860 7861 static const struct bpf_reg_types spin_lock_types = { 7862 .types = { 7863 PTR_TO_MAP_VALUE, 7864 PTR_TO_BTF_ID | MEM_ALLOC, 7865 } 7866 }; 7867 7868 static const struct bpf_reg_types fullsock_types = { .types = { PTR_TO_SOCKET } }; 7869 static const struct bpf_reg_types scalar_types = { .types = { SCALAR_VALUE } }; 7870 static const struct bpf_reg_types context_types = { .types = { PTR_TO_CTX } }; 7871 static const struct bpf_reg_types ringbuf_mem_types = { .types = { PTR_TO_MEM | MEM_RINGBUF } }; 7872 static const struct bpf_reg_types const_map_ptr_types = { .types = { CONST_PTR_TO_MAP } }; 7873 static const struct bpf_reg_types btf_ptr_types = { 7874 .types = { 7875 PTR_TO_BTF_ID, 7876 PTR_TO_BTF_ID | PTR_TRUSTED, 7877 PTR_TO_BTF_ID | MEM_RCU, 7878 }, 7879 }; 7880 static const struct bpf_reg_types percpu_btf_ptr_types = { 7881 .types = { 7882 PTR_TO_BTF_ID | MEM_PERCPU, 7883 PTR_TO_BTF_ID | MEM_PERCPU | MEM_RCU, 7884 PTR_TO_BTF_ID | MEM_PERCPU | PTR_TRUSTED, 7885 } 7886 }; 7887 static const struct bpf_reg_types func_ptr_types = { .types = { PTR_TO_FUNC } }; 7888 static const struct bpf_reg_types stack_ptr_types = { .types = { PTR_TO_STACK } }; 7889 static const struct bpf_reg_types const_str_ptr_types = { .types = { PTR_TO_MAP_VALUE } }; 7890 static const struct bpf_reg_types timer_types = { .types = { PTR_TO_MAP_VALUE } }; 7891 static const struct bpf_reg_types kptr_types = { .types = { PTR_TO_MAP_VALUE } }; 7892 static const struct bpf_reg_types dynptr_types = { 7893 .types = { 7894 PTR_TO_STACK, 7895 CONST_PTR_TO_DYNPTR, 7896 } 7897 }; 7898 7899 static const struct bpf_reg_types *compatible_reg_types[__BPF_ARG_TYPE_MAX] = { 7900 [ARG_PTR_TO_MAP_KEY] = &mem_types, 7901 [ARG_PTR_TO_MAP_VALUE] = &mem_types, 7902 [ARG_CONST_SIZE] = &scalar_types, 7903 [ARG_CONST_SIZE_OR_ZERO] = &scalar_types, 7904 [ARG_CONST_ALLOC_SIZE_OR_ZERO] = &scalar_types, 7905 [ARG_CONST_MAP_PTR] = &const_map_ptr_types, 7906 [ARG_PTR_TO_CTX] = &context_types, 7907 [ARG_PTR_TO_SOCK_COMMON] = &sock_types, 7908 #ifdef CONFIG_NET 7909 [ARG_PTR_TO_BTF_ID_SOCK_COMMON] = &btf_id_sock_common_types, 7910 #endif 7911 [ARG_PTR_TO_SOCKET] = &fullsock_types, 7912 [ARG_PTR_TO_BTF_ID] = &btf_ptr_types, 7913 [ARG_PTR_TO_SPIN_LOCK] = &spin_lock_types, 7914 [ARG_PTR_TO_MEM] = &mem_types, 7915 [ARG_PTR_TO_RINGBUF_MEM] = &ringbuf_mem_types, 7916 [ARG_PTR_TO_INT] = &int_ptr_types, 7917 [ARG_PTR_TO_LONG] = &int_ptr_types, 7918 [ARG_PTR_TO_PERCPU_BTF_ID] = &percpu_btf_ptr_types, 7919 [ARG_PTR_TO_FUNC] = &func_ptr_types, 7920 [ARG_PTR_TO_STACK] = &stack_ptr_types, 7921 [ARG_PTR_TO_CONST_STR] = &const_str_ptr_types, 7922 [ARG_PTR_TO_TIMER] = &timer_types, 7923 [ARG_PTR_TO_KPTR] = &kptr_types, 7924 [ARG_PTR_TO_DYNPTR] = &dynptr_types, 7925 }; 7926 7927 static int check_reg_type(struct bpf_verifier_env *env, u32 regno, 7928 enum bpf_arg_type arg_type, 7929 const u32 *arg_btf_id, 7930 struct bpf_call_arg_meta *meta) 7931 { 7932 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno]; 7933 enum bpf_reg_type expected, type = reg->type; 7934 const struct bpf_reg_types *compatible; 7935 int i, j; 7936 7937 compatible = compatible_reg_types[base_type(arg_type)]; 7938 if (!compatible) { 7939 verbose(env, "verifier internal error: unsupported arg type %d\n", arg_type); 7940 return -EFAULT; 7941 } 7942 7943 /* ARG_PTR_TO_MEM + RDONLY is compatible with PTR_TO_MEM and PTR_TO_MEM + RDONLY, 7944 * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM and NOT with PTR_TO_MEM + RDONLY 7945 * 7946 * Same for MAYBE_NULL: 7947 * 7948 * ARG_PTR_TO_MEM + MAYBE_NULL is compatible with PTR_TO_MEM and PTR_TO_MEM + MAYBE_NULL, 7949 * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM but NOT with PTR_TO_MEM + MAYBE_NULL 7950 * 7951 * ARG_PTR_TO_MEM is compatible with PTR_TO_MEM that is tagged with a dynptr type. 7952 * 7953 * Therefore we fold these flags depending on the arg_type before comparison. 7954 */ 7955 if (arg_type & MEM_RDONLY) 7956 type &= ~MEM_RDONLY; 7957 if (arg_type & PTR_MAYBE_NULL) 7958 type &= ~PTR_MAYBE_NULL; 7959 if (base_type(arg_type) == ARG_PTR_TO_MEM) 7960 type &= ~DYNPTR_TYPE_FLAG_MASK; 7961 7962 if (meta->func_id == BPF_FUNC_kptr_xchg && type_is_alloc(type)) { 7963 type &= ~MEM_ALLOC; 7964 type &= ~MEM_PERCPU; 7965 } 7966 7967 for (i = 0; i < ARRAY_SIZE(compatible->types); i++) { 7968 expected = compatible->types[i]; 7969 if (expected == NOT_INIT) 7970 break; 7971 7972 if (type == expected) 7973 goto found; 7974 } 7975 7976 verbose(env, "R%d type=%s expected=", regno, reg_type_str(env, reg->type)); 7977 for (j = 0; j + 1 < i; j++) 7978 verbose(env, "%s, ", reg_type_str(env, compatible->types[j])); 7979 verbose(env, "%s\n", reg_type_str(env, compatible->types[j])); 7980 return -EACCES; 7981 7982 found: 7983 if (base_type(reg->type) != PTR_TO_BTF_ID) 7984 return 0; 7985 7986 if (compatible == &mem_types) { 7987 if (!(arg_type & MEM_RDONLY)) { 7988 verbose(env, 7989 "%s() may write into memory pointed by R%d type=%s\n", 7990 func_id_name(meta->func_id), 7991 regno, reg_type_str(env, reg->type)); 7992 return -EACCES; 7993 } 7994 return 0; 7995 } 7996 7997 switch ((int)reg->type) { 7998 case PTR_TO_BTF_ID: 7999 case PTR_TO_BTF_ID | PTR_TRUSTED: 8000 case PTR_TO_BTF_ID | MEM_RCU: 8001 case PTR_TO_BTF_ID | PTR_MAYBE_NULL: 8002 case PTR_TO_BTF_ID | PTR_MAYBE_NULL | MEM_RCU: 8003 { 8004 /* For bpf_sk_release, it needs to match against first member 8005 * 'struct sock_common', hence make an exception for it. This 8006 * allows bpf_sk_release to work for multiple socket types. 8007 */ 8008 bool strict_type_match = arg_type_is_release(arg_type) && 8009 meta->func_id != BPF_FUNC_sk_release; 8010 8011 if (type_may_be_null(reg->type) && 8012 (!type_may_be_null(arg_type) || arg_type_is_release(arg_type))) { 8013 verbose(env, "Possibly NULL pointer passed to helper arg%d\n", regno); 8014 return -EACCES; 8015 } 8016 8017 if (!arg_btf_id) { 8018 if (!compatible->btf_id) { 8019 verbose(env, "verifier internal error: missing arg compatible BTF ID\n"); 8020 return -EFAULT; 8021 } 8022 arg_btf_id = compatible->btf_id; 8023 } 8024 8025 if (meta->func_id == BPF_FUNC_kptr_xchg) { 8026 if (map_kptr_match_type(env, meta->kptr_field, reg, regno)) 8027 return -EACCES; 8028 } else { 8029 if (arg_btf_id == BPF_PTR_POISON) { 8030 verbose(env, "verifier internal error:"); 8031 verbose(env, "R%d has non-overwritten BPF_PTR_POISON type\n", 8032 regno); 8033 return -EACCES; 8034 } 8035 8036 if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off, 8037 btf_vmlinux, *arg_btf_id, 8038 strict_type_match)) { 8039 verbose(env, "R%d is of type %s but %s is expected\n", 8040 regno, btf_type_name(reg->btf, reg->btf_id), 8041 btf_type_name(btf_vmlinux, *arg_btf_id)); 8042 return -EACCES; 8043 } 8044 } 8045 break; 8046 } 8047 case PTR_TO_BTF_ID | MEM_ALLOC: 8048 case PTR_TO_BTF_ID | MEM_PERCPU | MEM_ALLOC: 8049 if (meta->func_id != BPF_FUNC_spin_lock && meta->func_id != BPF_FUNC_spin_unlock && 8050 meta->func_id != BPF_FUNC_kptr_xchg) { 8051 verbose(env, "verifier internal error: unimplemented handling of MEM_ALLOC\n"); 8052 return -EFAULT; 8053 } 8054 if (meta->func_id == BPF_FUNC_kptr_xchg) { 8055 if (map_kptr_match_type(env, meta->kptr_field, reg, regno)) 8056 return -EACCES; 8057 } 8058 break; 8059 case PTR_TO_BTF_ID | MEM_PERCPU: 8060 case PTR_TO_BTF_ID | MEM_PERCPU | MEM_RCU: 8061 case PTR_TO_BTF_ID | MEM_PERCPU | PTR_TRUSTED: 8062 /* Handled by helper specific checks */ 8063 break; 8064 default: 8065 verbose(env, "verifier internal error: invalid PTR_TO_BTF_ID register for type match\n"); 8066 return -EFAULT; 8067 } 8068 return 0; 8069 } 8070 8071 static struct btf_field * 8072 reg_find_field_offset(const struct bpf_reg_state *reg, s32 off, u32 fields) 8073 { 8074 struct btf_field *field; 8075 struct btf_record *rec; 8076 8077 rec = reg_btf_record(reg); 8078 if (!rec) 8079 return NULL; 8080 8081 field = btf_record_find(rec, off, fields); 8082 if (!field) 8083 return NULL; 8084 8085 return field; 8086 } 8087 8088 int check_func_arg_reg_off(struct bpf_verifier_env *env, 8089 const struct bpf_reg_state *reg, int regno, 8090 enum bpf_arg_type arg_type) 8091 { 8092 u32 type = reg->type; 8093 8094 /* When referenced register is passed to release function, its fixed 8095 * offset must be 0. 8096 * 8097 * We will check arg_type_is_release reg has ref_obj_id when storing 8098 * meta->release_regno. 8099 */ 8100 if (arg_type_is_release(arg_type)) { 8101 /* ARG_PTR_TO_DYNPTR with OBJ_RELEASE is a bit special, as it 8102 * may not directly point to the object being released, but to 8103 * dynptr pointing to such object, which might be at some offset 8104 * on the stack. In that case, we simply to fallback to the 8105 * default handling. 8106 */ 8107 if (arg_type_is_dynptr(arg_type) && type == PTR_TO_STACK) 8108 return 0; 8109 8110 /* Doing check_ptr_off_reg check for the offset will catch this 8111 * because fixed_off_ok is false, but checking here allows us 8112 * to give the user a better error message. 8113 */ 8114 if (reg->off) { 8115 verbose(env, "R%d must have zero offset when passed to release func or trusted arg to kfunc\n", 8116 regno); 8117 return -EINVAL; 8118 } 8119 return __check_ptr_off_reg(env, reg, regno, false); 8120 } 8121 8122 switch (type) { 8123 /* Pointer types where both fixed and variable offset is explicitly allowed: */ 8124 case PTR_TO_STACK: 8125 case PTR_TO_PACKET: 8126 case PTR_TO_PACKET_META: 8127 case PTR_TO_MAP_KEY: 8128 case PTR_TO_MAP_VALUE: 8129 case PTR_TO_MEM: 8130 case PTR_TO_MEM | MEM_RDONLY: 8131 case PTR_TO_MEM | MEM_RINGBUF: 8132 case PTR_TO_BUF: 8133 case PTR_TO_BUF | MEM_RDONLY: 8134 case SCALAR_VALUE: 8135 return 0; 8136 /* All the rest must be rejected, except PTR_TO_BTF_ID which allows 8137 * fixed offset. 8138 */ 8139 case PTR_TO_BTF_ID: 8140 case PTR_TO_BTF_ID | MEM_ALLOC: 8141 case PTR_TO_BTF_ID | PTR_TRUSTED: 8142 case PTR_TO_BTF_ID | MEM_RCU: 8143 case PTR_TO_BTF_ID | MEM_ALLOC | NON_OWN_REF: 8144 case PTR_TO_BTF_ID | MEM_ALLOC | NON_OWN_REF | MEM_RCU: 8145 /* When referenced PTR_TO_BTF_ID is passed to release function, 8146 * its fixed offset must be 0. In the other cases, fixed offset 8147 * can be non-zero. This was already checked above. So pass 8148 * fixed_off_ok as true to allow fixed offset for all other 8149 * cases. var_off always must be 0 for PTR_TO_BTF_ID, hence we 8150 * still need to do checks instead of returning. 8151 */ 8152 return __check_ptr_off_reg(env, reg, regno, true); 8153 default: 8154 return __check_ptr_off_reg(env, reg, regno, false); 8155 } 8156 } 8157 8158 static struct bpf_reg_state *get_dynptr_arg_reg(struct bpf_verifier_env *env, 8159 const struct bpf_func_proto *fn, 8160 struct bpf_reg_state *regs) 8161 { 8162 struct bpf_reg_state *state = NULL; 8163 int i; 8164 8165 for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++) 8166 if (arg_type_is_dynptr(fn->arg_type[i])) { 8167 if (state) { 8168 verbose(env, "verifier internal error: multiple dynptr args\n"); 8169 return NULL; 8170 } 8171 state = ®s[BPF_REG_1 + i]; 8172 } 8173 8174 if (!state) 8175 verbose(env, "verifier internal error: no dynptr arg found\n"); 8176 8177 return state; 8178 } 8179 8180 static int dynptr_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 8181 { 8182 struct bpf_func_state *state = func(env, reg); 8183 int spi; 8184 8185 if (reg->type == CONST_PTR_TO_DYNPTR) 8186 return reg->id; 8187 spi = dynptr_get_spi(env, reg); 8188 if (spi < 0) 8189 return spi; 8190 return state->stack[spi].spilled_ptr.id; 8191 } 8192 8193 static int dynptr_ref_obj_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 8194 { 8195 struct bpf_func_state *state = func(env, reg); 8196 int spi; 8197 8198 if (reg->type == CONST_PTR_TO_DYNPTR) 8199 return reg->ref_obj_id; 8200 spi = dynptr_get_spi(env, reg); 8201 if (spi < 0) 8202 return spi; 8203 return state->stack[spi].spilled_ptr.ref_obj_id; 8204 } 8205 8206 static enum bpf_dynptr_type dynptr_get_type(struct bpf_verifier_env *env, 8207 struct bpf_reg_state *reg) 8208 { 8209 struct bpf_func_state *state = func(env, reg); 8210 int spi; 8211 8212 if (reg->type == CONST_PTR_TO_DYNPTR) 8213 return reg->dynptr.type; 8214 8215 spi = __get_spi(reg->off); 8216 if (spi < 0) { 8217 verbose(env, "verifier internal error: invalid spi when querying dynptr type\n"); 8218 return BPF_DYNPTR_TYPE_INVALID; 8219 } 8220 8221 return state->stack[spi].spilled_ptr.dynptr.type; 8222 } 8223 8224 static int check_func_arg(struct bpf_verifier_env *env, u32 arg, 8225 struct bpf_call_arg_meta *meta, 8226 const struct bpf_func_proto *fn, 8227 int insn_idx) 8228 { 8229 u32 regno = BPF_REG_1 + arg; 8230 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno]; 8231 enum bpf_arg_type arg_type = fn->arg_type[arg]; 8232 enum bpf_reg_type type = reg->type; 8233 u32 *arg_btf_id = NULL; 8234 int err = 0; 8235 8236 if (arg_type == ARG_DONTCARE) 8237 return 0; 8238 8239 err = check_reg_arg(env, regno, SRC_OP); 8240 if (err) 8241 return err; 8242 8243 if (arg_type == ARG_ANYTHING) { 8244 if (is_pointer_value(env, regno)) { 8245 verbose(env, "R%d leaks addr into helper function\n", 8246 regno); 8247 return -EACCES; 8248 } 8249 return 0; 8250 } 8251 8252 if (type_is_pkt_pointer(type) && 8253 !may_access_direct_pkt_data(env, meta, BPF_READ)) { 8254 verbose(env, "helper access to the packet is not allowed\n"); 8255 return -EACCES; 8256 } 8257 8258 if (base_type(arg_type) == ARG_PTR_TO_MAP_VALUE) { 8259 err = resolve_map_arg_type(env, meta, &arg_type); 8260 if (err) 8261 return err; 8262 } 8263 8264 if (register_is_null(reg) && type_may_be_null(arg_type)) 8265 /* A NULL register has a SCALAR_VALUE type, so skip 8266 * type checking. 8267 */ 8268 goto skip_type_check; 8269 8270 /* arg_btf_id and arg_size are in a union. */ 8271 if (base_type(arg_type) == ARG_PTR_TO_BTF_ID || 8272 base_type(arg_type) == ARG_PTR_TO_SPIN_LOCK) 8273 arg_btf_id = fn->arg_btf_id[arg]; 8274 8275 err = check_reg_type(env, regno, arg_type, arg_btf_id, meta); 8276 if (err) 8277 return err; 8278 8279 err = check_func_arg_reg_off(env, reg, regno, arg_type); 8280 if (err) 8281 return err; 8282 8283 skip_type_check: 8284 if (arg_type_is_release(arg_type)) { 8285 if (arg_type_is_dynptr(arg_type)) { 8286 struct bpf_func_state *state = func(env, reg); 8287 int spi; 8288 8289 /* Only dynptr created on stack can be released, thus 8290 * the get_spi and stack state checks for spilled_ptr 8291 * should only be done before process_dynptr_func for 8292 * PTR_TO_STACK. 8293 */ 8294 if (reg->type == PTR_TO_STACK) { 8295 spi = dynptr_get_spi(env, reg); 8296 if (spi < 0 || !state->stack[spi].spilled_ptr.ref_obj_id) { 8297 verbose(env, "arg %d is an unacquired reference\n", regno); 8298 return -EINVAL; 8299 } 8300 } else { 8301 verbose(env, "cannot release unowned const bpf_dynptr\n"); 8302 return -EINVAL; 8303 } 8304 } else if (!reg->ref_obj_id && !register_is_null(reg)) { 8305 verbose(env, "R%d must be referenced when passed to release function\n", 8306 regno); 8307 return -EINVAL; 8308 } 8309 if (meta->release_regno) { 8310 verbose(env, "verifier internal error: more than one release argument\n"); 8311 return -EFAULT; 8312 } 8313 meta->release_regno = regno; 8314 } 8315 8316 if (reg->ref_obj_id) { 8317 if (meta->ref_obj_id) { 8318 verbose(env, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n", 8319 regno, reg->ref_obj_id, 8320 meta->ref_obj_id); 8321 return -EFAULT; 8322 } 8323 meta->ref_obj_id = reg->ref_obj_id; 8324 } 8325 8326 switch (base_type(arg_type)) { 8327 case ARG_CONST_MAP_PTR: 8328 /* bpf_map_xxx(map_ptr) call: remember that map_ptr */ 8329 if (meta->map_ptr) { 8330 /* Use map_uid (which is unique id of inner map) to reject: 8331 * inner_map1 = bpf_map_lookup_elem(outer_map, key1) 8332 * inner_map2 = bpf_map_lookup_elem(outer_map, key2) 8333 * if (inner_map1 && inner_map2) { 8334 * timer = bpf_map_lookup_elem(inner_map1); 8335 * if (timer) 8336 * // mismatch would have been allowed 8337 * bpf_timer_init(timer, inner_map2); 8338 * } 8339 * 8340 * Comparing map_ptr is enough to distinguish normal and outer maps. 8341 */ 8342 if (meta->map_ptr != reg->map_ptr || 8343 meta->map_uid != reg->map_uid) { 8344 verbose(env, 8345 "timer pointer in R1 map_uid=%d doesn't match map pointer in R2 map_uid=%d\n", 8346 meta->map_uid, reg->map_uid); 8347 return -EINVAL; 8348 } 8349 } 8350 meta->map_ptr = reg->map_ptr; 8351 meta->map_uid = reg->map_uid; 8352 break; 8353 case ARG_PTR_TO_MAP_KEY: 8354 /* bpf_map_xxx(..., map_ptr, ..., key) call: 8355 * check that [key, key + map->key_size) are within 8356 * stack limits and initialized 8357 */ 8358 if (!meta->map_ptr) { 8359 /* in function declaration map_ptr must come before 8360 * map_key, so that it's verified and known before 8361 * we have to check map_key here. Otherwise it means 8362 * that kernel subsystem misconfigured verifier 8363 */ 8364 verbose(env, "invalid map_ptr to access map->key\n"); 8365 return -EACCES; 8366 } 8367 err = check_helper_mem_access(env, regno, 8368 meta->map_ptr->key_size, false, 8369 NULL); 8370 break; 8371 case ARG_PTR_TO_MAP_VALUE: 8372 if (type_may_be_null(arg_type) && register_is_null(reg)) 8373 return 0; 8374 8375 /* bpf_map_xxx(..., map_ptr, ..., value) call: 8376 * check [value, value + map->value_size) validity 8377 */ 8378 if (!meta->map_ptr) { 8379 /* kernel subsystem misconfigured verifier */ 8380 verbose(env, "invalid map_ptr to access map->value\n"); 8381 return -EACCES; 8382 } 8383 meta->raw_mode = arg_type & MEM_UNINIT; 8384 err = check_helper_mem_access(env, regno, 8385 meta->map_ptr->value_size, false, 8386 meta); 8387 break; 8388 case ARG_PTR_TO_PERCPU_BTF_ID: 8389 if (!reg->btf_id) { 8390 verbose(env, "Helper has invalid btf_id in R%d\n", regno); 8391 return -EACCES; 8392 } 8393 meta->ret_btf = reg->btf; 8394 meta->ret_btf_id = reg->btf_id; 8395 break; 8396 case ARG_PTR_TO_SPIN_LOCK: 8397 if (in_rbtree_lock_required_cb(env)) { 8398 verbose(env, "can't spin_{lock,unlock} in rbtree cb\n"); 8399 return -EACCES; 8400 } 8401 if (meta->func_id == BPF_FUNC_spin_lock) { 8402 err = process_spin_lock(env, regno, true); 8403 if (err) 8404 return err; 8405 } else if (meta->func_id == BPF_FUNC_spin_unlock) { 8406 err = process_spin_lock(env, regno, false); 8407 if (err) 8408 return err; 8409 } else { 8410 verbose(env, "verifier internal error\n"); 8411 return -EFAULT; 8412 } 8413 break; 8414 case ARG_PTR_TO_TIMER: 8415 err = process_timer_func(env, regno, meta); 8416 if (err) 8417 return err; 8418 break; 8419 case ARG_PTR_TO_FUNC: 8420 meta->subprogno = reg->subprogno; 8421 break; 8422 case ARG_PTR_TO_MEM: 8423 /* The access to this pointer is only checked when we hit the 8424 * next is_mem_size argument below. 8425 */ 8426 meta->raw_mode = arg_type & MEM_UNINIT; 8427 if (arg_type & MEM_FIXED_SIZE) { 8428 err = check_helper_mem_access(env, regno, 8429 fn->arg_size[arg], false, 8430 meta); 8431 } 8432 break; 8433 case ARG_CONST_SIZE: 8434 err = check_mem_size_reg(env, reg, regno, false, meta); 8435 break; 8436 case ARG_CONST_SIZE_OR_ZERO: 8437 err = check_mem_size_reg(env, reg, regno, true, meta); 8438 break; 8439 case ARG_PTR_TO_DYNPTR: 8440 err = process_dynptr_func(env, regno, insn_idx, arg_type, 0); 8441 if (err) 8442 return err; 8443 break; 8444 case ARG_CONST_ALLOC_SIZE_OR_ZERO: 8445 if (!tnum_is_const(reg->var_off)) { 8446 verbose(env, "R%d is not a known constant'\n", 8447 regno); 8448 return -EACCES; 8449 } 8450 meta->mem_size = reg->var_off.value; 8451 err = mark_chain_precision(env, regno); 8452 if (err) 8453 return err; 8454 break; 8455 case ARG_PTR_TO_INT: 8456 case ARG_PTR_TO_LONG: 8457 { 8458 int size = int_ptr_type_to_size(arg_type); 8459 8460 err = check_helper_mem_access(env, regno, size, false, meta); 8461 if (err) 8462 return err; 8463 err = check_ptr_alignment(env, reg, 0, size, true); 8464 break; 8465 } 8466 case ARG_PTR_TO_CONST_STR: 8467 { 8468 struct bpf_map *map = reg->map_ptr; 8469 int map_off; 8470 u64 map_addr; 8471 char *str_ptr; 8472 8473 if (!bpf_map_is_rdonly(map)) { 8474 verbose(env, "R%d does not point to a readonly map'\n", regno); 8475 return -EACCES; 8476 } 8477 8478 if (!tnum_is_const(reg->var_off)) { 8479 verbose(env, "R%d is not a constant address'\n", regno); 8480 return -EACCES; 8481 } 8482 8483 if (!map->ops->map_direct_value_addr) { 8484 verbose(env, "no direct value access support for this map type\n"); 8485 return -EACCES; 8486 } 8487 8488 err = check_map_access(env, regno, reg->off, 8489 map->value_size - reg->off, false, 8490 ACCESS_HELPER); 8491 if (err) 8492 return err; 8493 8494 map_off = reg->off + reg->var_off.value; 8495 err = map->ops->map_direct_value_addr(map, &map_addr, map_off); 8496 if (err) { 8497 verbose(env, "direct value access on string failed\n"); 8498 return err; 8499 } 8500 8501 str_ptr = (char *)(long)(map_addr); 8502 if (!strnchr(str_ptr + map_off, map->value_size - map_off, 0)) { 8503 verbose(env, "string is not zero-terminated\n"); 8504 return -EINVAL; 8505 } 8506 break; 8507 } 8508 case ARG_PTR_TO_KPTR: 8509 err = process_kptr_func(env, regno, meta); 8510 if (err) 8511 return err; 8512 break; 8513 } 8514 8515 return err; 8516 } 8517 8518 static bool may_update_sockmap(struct bpf_verifier_env *env, int func_id) 8519 { 8520 enum bpf_attach_type eatype = env->prog->expected_attach_type; 8521 enum bpf_prog_type type = resolve_prog_type(env->prog); 8522 8523 if (func_id != BPF_FUNC_map_update_elem) 8524 return false; 8525 8526 /* It's not possible to get access to a locked struct sock in these 8527 * contexts, so updating is safe. 8528 */ 8529 switch (type) { 8530 case BPF_PROG_TYPE_TRACING: 8531 if (eatype == BPF_TRACE_ITER) 8532 return true; 8533 break; 8534 case BPF_PROG_TYPE_SOCKET_FILTER: 8535 case BPF_PROG_TYPE_SCHED_CLS: 8536 case BPF_PROG_TYPE_SCHED_ACT: 8537 case BPF_PROG_TYPE_XDP: 8538 case BPF_PROG_TYPE_SK_REUSEPORT: 8539 case BPF_PROG_TYPE_FLOW_DISSECTOR: 8540 case BPF_PROG_TYPE_SK_LOOKUP: 8541 return true; 8542 default: 8543 break; 8544 } 8545 8546 verbose(env, "cannot update sockmap in this context\n"); 8547 return false; 8548 } 8549 8550 static bool allow_tail_call_in_subprogs(struct bpf_verifier_env *env) 8551 { 8552 return env->prog->jit_requested && 8553 bpf_jit_supports_subprog_tailcalls(); 8554 } 8555 8556 static int check_map_func_compatibility(struct bpf_verifier_env *env, 8557 struct bpf_map *map, int func_id) 8558 { 8559 if (!map) 8560 return 0; 8561 8562 /* We need a two way check, first is from map perspective ... */ 8563 switch (map->map_type) { 8564 case BPF_MAP_TYPE_PROG_ARRAY: 8565 if (func_id != BPF_FUNC_tail_call) 8566 goto error; 8567 break; 8568 case BPF_MAP_TYPE_PERF_EVENT_ARRAY: 8569 if (func_id != BPF_FUNC_perf_event_read && 8570 func_id != BPF_FUNC_perf_event_output && 8571 func_id != BPF_FUNC_skb_output && 8572 func_id != BPF_FUNC_perf_event_read_value && 8573 func_id != BPF_FUNC_xdp_output) 8574 goto error; 8575 break; 8576 case BPF_MAP_TYPE_RINGBUF: 8577 if (func_id != BPF_FUNC_ringbuf_output && 8578 func_id != BPF_FUNC_ringbuf_reserve && 8579 func_id != BPF_FUNC_ringbuf_query && 8580 func_id != BPF_FUNC_ringbuf_reserve_dynptr && 8581 func_id != BPF_FUNC_ringbuf_submit_dynptr && 8582 func_id != BPF_FUNC_ringbuf_discard_dynptr) 8583 goto error; 8584 break; 8585 case BPF_MAP_TYPE_USER_RINGBUF: 8586 if (func_id != BPF_FUNC_user_ringbuf_drain) 8587 goto error; 8588 break; 8589 case BPF_MAP_TYPE_STACK_TRACE: 8590 if (func_id != BPF_FUNC_get_stackid) 8591 goto error; 8592 break; 8593 case BPF_MAP_TYPE_CGROUP_ARRAY: 8594 if (func_id != BPF_FUNC_skb_under_cgroup && 8595 func_id != BPF_FUNC_current_task_under_cgroup) 8596 goto error; 8597 break; 8598 case BPF_MAP_TYPE_CGROUP_STORAGE: 8599 case BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE: 8600 if (func_id != BPF_FUNC_get_local_storage) 8601 goto error; 8602 break; 8603 case BPF_MAP_TYPE_DEVMAP: 8604 case BPF_MAP_TYPE_DEVMAP_HASH: 8605 if (func_id != BPF_FUNC_redirect_map && 8606 func_id != BPF_FUNC_map_lookup_elem) 8607 goto error; 8608 break; 8609 /* Restrict bpf side of cpumap and xskmap, open when use-cases 8610 * appear. 8611 */ 8612 case BPF_MAP_TYPE_CPUMAP: 8613 if (func_id != BPF_FUNC_redirect_map) 8614 goto error; 8615 break; 8616 case BPF_MAP_TYPE_XSKMAP: 8617 if (func_id != BPF_FUNC_redirect_map && 8618 func_id != BPF_FUNC_map_lookup_elem) 8619 goto error; 8620 break; 8621 case BPF_MAP_TYPE_ARRAY_OF_MAPS: 8622 case BPF_MAP_TYPE_HASH_OF_MAPS: 8623 if (func_id != BPF_FUNC_map_lookup_elem) 8624 goto error; 8625 break; 8626 case BPF_MAP_TYPE_SOCKMAP: 8627 if (func_id != BPF_FUNC_sk_redirect_map && 8628 func_id != BPF_FUNC_sock_map_update && 8629 func_id != BPF_FUNC_map_delete_elem && 8630 func_id != BPF_FUNC_msg_redirect_map && 8631 func_id != BPF_FUNC_sk_select_reuseport && 8632 func_id != BPF_FUNC_map_lookup_elem && 8633 !may_update_sockmap(env, func_id)) 8634 goto error; 8635 break; 8636 case BPF_MAP_TYPE_SOCKHASH: 8637 if (func_id != BPF_FUNC_sk_redirect_hash && 8638 func_id != BPF_FUNC_sock_hash_update && 8639 func_id != BPF_FUNC_map_delete_elem && 8640 func_id != BPF_FUNC_msg_redirect_hash && 8641 func_id != BPF_FUNC_sk_select_reuseport && 8642 func_id != BPF_FUNC_map_lookup_elem && 8643 !may_update_sockmap(env, func_id)) 8644 goto error; 8645 break; 8646 case BPF_MAP_TYPE_REUSEPORT_SOCKARRAY: 8647 if (func_id != BPF_FUNC_sk_select_reuseport) 8648 goto error; 8649 break; 8650 case BPF_MAP_TYPE_QUEUE: 8651 case BPF_MAP_TYPE_STACK: 8652 if (func_id != BPF_FUNC_map_peek_elem && 8653 func_id != BPF_FUNC_map_pop_elem && 8654 func_id != BPF_FUNC_map_push_elem) 8655 goto error; 8656 break; 8657 case BPF_MAP_TYPE_SK_STORAGE: 8658 if (func_id != BPF_FUNC_sk_storage_get && 8659 func_id != BPF_FUNC_sk_storage_delete && 8660 func_id != BPF_FUNC_kptr_xchg) 8661 goto error; 8662 break; 8663 case BPF_MAP_TYPE_INODE_STORAGE: 8664 if (func_id != BPF_FUNC_inode_storage_get && 8665 func_id != BPF_FUNC_inode_storage_delete && 8666 func_id != BPF_FUNC_kptr_xchg) 8667 goto error; 8668 break; 8669 case BPF_MAP_TYPE_TASK_STORAGE: 8670 if (func_id != BPF_FUNC_task_storage_get && 8671 func_id != BPF_FUNC_task_storage_delete && 8672 func_id != BPF_FUNC_kptr_xchg) 8673 goto error; 8674 break; 8675 case BPF_MAP_TYPE_CGRP_STORAGE: 8676 if (func_id != BPF_FUNC_cgrp_storage_get && 8677 func_id != BPF_FUNC_cgrp_storage_delete && 8678 func_id != BPF_FUNC_kptr_xchg) 8679 goto error; 8680 break; 8681 case BPF_MAP_TYPE_BLOOM_FILTER: 8682 if (func_id != BPF_FUNC_map_peek_elem && 8683 func_id != BPF_FUNC_map_push_elem) 8684 goto error; 8685 break; 8686 default: 8687 break; 8688 } 8689 8690 /* ... and second from the function itself. */ 8691 switch (func_id) { 8692 case BPF_FUNC_tail_call: 8693 if (map->map_type != BPF_MAP_TYPE_PROG_ARRAY) 8694 goto error; 8695 if (env->subprog_cnt > 1 && !allow_tail_call_in_subprogs(env)) { 8696 verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n"); 8697 return -EINVAL; 8698 } 8699 break; 8700 case BPF_FUNC_perf_event_read: 8701 case BPF_FUNC_perf_event_output: 8702 case BPF_FUNC_perf_event_read_value: 8703 case BPF_FUNC_skb_output: 8704 case BPF_FUNC_xdp_output: 8705 if (map->map_type != BPF_MAP_TYPE_PERF_EVENT_ARRAY) 8706 goto error; 8707 break; 8708 case BPF_FUNC_ringbuf_output: 8709 case BPF_FUNC_ringbuf_reserve: 8710 case BPF_FUNC_ringbuf_query: 8711 case BPF_FUNC_ringbuf_reserve_dynptr: 8712 case BPF_FUNC_ringbuf_submit_dynptr: 8713 case BPF_FUNC_ringbuf_discard_dynptr: 8714 if (map->map_type != BPF_MAP_TYPE_RINGBUF) 8715 goto error; 8716 break; 8717 case BPF_FUNC_user_ringbuf_drain: 8718 if (map->map_type != BPF_MAP_TYPE_USER_RINGBUF) 8719 goto error; 8720 break; 8721 case BPF_FUNC_get_stackid: 8722 if (map->map_type != BPF_MAP_TYPE_STACK_TRACE) 8723 goto error; 8724 break; 8725 case BPF_FUNC_current_task_under_cgroup: 8726 case BPF_FUNC_skb_under_cgroup: 8727 if (map->map_type != BPF_MAP_TYPE_CGROUP_ARRAY) 8728 goto error; 8729 break; 8730 case BPF_FUNC_redirect_map: 8731 if (map->map_type != BPF_MAP_TYPE_DEVMAP && 8732 map->map_type != BPF_MAP_TYPE_DEVMAP_HASH && 8733 map->map_type != BPF_MAP_TYPE_CPUMAP && 8734 map->map_type != BPF_MAP_TYPE_XSKMAP) 8735 goto error; 8736 break; 8737 case BPF_FUNC_sk_redirect_map: 8738 case BPF_FUNC_msg_redirect_map: 8739 case BPF_FUNC_sock_map_update: 8740 if (map->map_type != BPF_MAP_TYPE_SOCKMAP) 8741 goto error; 8742 break; 8743 case BPF_FUNC_sk_redirect_hash: 8744 case BPF_FUNC_msg_redirect_hash: 8745 case BPF_FUNC_sock_hash_update: 8746 if (map->map_type != BPF_MAP_TYPE_SOCKHASH) 8747 goto error; 8748 break; 8749 case BPF_FUNC_get_local_storage: 8750 if (map->map_type != BPF_MAP_TYPE_CGROUP_STORAGE && 8751 map->map_type != BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE) 8752 goto error; 8753 break; 8754 case BPF_FUNC_sk_select_reuseport: 8755 if (map->map_type != BPF_MAP_TYPE_REUSEPORT_SOCKARRAY && 8756 map->map_type != BPF_MAP_TYPE_SOCKMAP && 8757 map->map_type != BPF_MAP_TYPE_SOCKHASH) 8758 goto error; 8759 break; 8760 case BPF_FUNC_map_pop_elem: 8761 if (map->map_type != BPF_MAP_TYPE_QUEUE && 8762 map->map_type != BPF_MAP_TYPE_STACK) 8763 goto error; 8764 break; 8765 case BPF_FUNC_map_peek_elem: 8766 case BPF_FUNC_map_push_elem: 8767 if (map->map_type != BPF_MAP_TYPE_QUEUE && 8768 map->map_type != BPF_MAP_TYPE_STACK && 8769 map->map_type != BPF_MAP_TYPE_BLOOM_FILTER) 8770 goto error; 8771 break; 8772 case BPF_FUNC_map_lookup_percpu_elem: 8773 if (map->map_type != BPF_MAP_TYPE_PERCPU_ARRAY && 8774 map->map_type != BPF_MAP_TYPE_PERCPU_HASH && 8775 map->map_type != BPF_MAP_TYPE_LRU_PERCPU_HASH) 8776 goto error; 8777 break; 8778 case BPF_FUNC_sk_storage_get: 8779 case BPF_FUNC_sk_storage_delete: 8780 if (map->map_type != BPF_MAP_TYPE_SK_STORAGE) 8781 goto error; 8782 break; 8783 case BPF_FUNC_inode_storage_get: 8784 case BPF_FUNC_inode_storage_delete: 8785 if (map->map_type != BPF_MAP_TYPE_INODE_STORAGE) 8786 goto error; 8787 break; 8788 case BPF_FUNC_task_storage_get: 8789 case BPF_FUNC_task_storage_delete: 8790 if (map->map_type != BPF_MAP_TYPE_TASK_STORAGE) 8791 goto error; 8792 break; 8793 case BPF_FUNC_cgrp_storage_get: 8794 case BPF_FUNC_cgrp_storage_delete: 8795 if (map->map_type != BPF_MAP_TYPE_CGRP_STORAGE) 8796 goto error; 8797 break; 8798 default: 8799 break; 8800 } 8801 8802 return 0; 8803 error: 8804 verbose(env, "cannot pass map_type %d into func %s#%d\n", 8805 map->map_type, func_id_name(func_id), func_id); 8806 return -EINVAL; 8807 } 8808 8809 static bool check_raw_mode_ok(const struct bpf_func_proto *fn) 8810 { 8811 int count = 0; 8812 8813 if (fn->arg1_type == ARG_PTR_TO_UNINIT_MEM) 8814 count++; 8815 if (fn->arg2_type == ARG_PTR_TO_UNINIT_MEM) 8816 count++; 8817 if (fn->arg3_type == ARG_PTR_TO_UNINIT_MEM) 8818 count++; 8819 if (fn->arg4_type == ARG_PTR_TO_UNINIT_MEM) 8820 count++; 8821 if (fn->arg5_type == ARG_PTR_TO_UNINIT_MEM) 8822 count++; 8823 8824 /* We only support one arg being in raw mode at the moment, 8825 * which is sufficient for the helper functions we have 8826 * right now. 8827 */ 8828 return count <= 1; 8829 } 8830 8831 static bool check_args_pair_invalid(const struct bpf_func_proto *fn, int arg) 8832 { 8833 bool is_fixed = fn->arg_type[arg] & MEM_FIXED_SIZE; 8834 bool has_size = fn->arg_size[arg] != 0; 8835 bool is_next_size = false; 8836 8837 if (arg + 1 < ARRAY_SIZE(fn->arg_type)) 8838 is_next_size = arg_type_is_mem_size(fn->arg_type[arg + 1]); 8839 8840 if (base_type(fn->arg_type[arg]) != ARG_PTR_TO_MEM) 8841 return is_next_size; 8842 8843 return has_size == is_next_size || is_next_size == is_fixed; 8844 } 8845 8846 static bool check_arg_pair_ok(const struct bpf_func_proto *fn) 8847 { 8848 /* bpf_xxx(..., buf, len) call will access 'len' 8849 * bytes from memory 'buf'. Both arg types need 8850 * to be paired, so make sure there's no buggy 8851 * helper function specification. 8852 */ 8853 if (arg_type_is_mem_size(fn->arg1_type) || 8854 check_args_pair_invalid(fn, 0) || 8855 check_args_pair_invalid(fn, 1) || 8856 check_args_pair_invalid(fn, 2) || 8857 check_args_pair_invalid(fn, 3) || 8858 check_args_pair_invalid(fn, 4)) 8859 return false; 8860 8861 return true; 8862 } 8863 8864 static bool check_btf_id_ok(const struct bpf_func_proto *fn) 8865 { 8866 int i; 8867 8868 for (i = 0; i < ARRAY_SIZE(fn->arg_type); i++) { 8869 if (base_type(fn->arg_type[i]) == ARG_PTR_TO_BTF_ID) 8870 return !!fn->arg_btf_id[i]; 8871 if (base_type(fn->arg_type[i]) == ARG_PTR_TO_SPIN_LOCK) 8872 return fn->arg_btf_id[i] == BPF_PTR_POISON; 8873 if (base_type(fn->arg_type[i]) != ARG_PTR_TO_BTF_ID && fn->arg_btf_id[i] && 8874 /* arg_btf_id and arg_size are in a union. */ 8875 (base_type(fn->arg_type[i]) != ARG_PTR_TO_MEM || 8876 !(fn->arg_type[i] & MEM_FIXED_SIZE))) 8877 return false; 8878 } 8879 8880 return true; 8881 } 8882 8883 static int check_func_proto(const struct bpf_func_proto *fn, int func_id) 8884 { 8885 return check_raw_mode_ok(fn) && 8886 check_arg_pair_ok(fn) && 8887 check_btf_id_ok(fn) ? 0 : -EINVAL; 8888 } 8889 8890 /* Packet data might have moved, any old PTR_TO_PACKET[_META,_END] 8891 * are now invalid, so turn them into unknown SCALAR_VALUE. 8892 * 8893 * This also applies to dynptr slices belonging to skb and xdp dynptrs, 8894 * since these slices point to packet data. 8895 */ 8896 static void clear_all_pkt_pointers(struct bpf_verifier_env *env) 8897 { 8898 struct bpf_func_state *state; 8899 struct bpf_reg_state *reg; 8900 8901 bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({ 8902 if (reg_is_pkt_pointer_any(reg) || reg_is_dynptr_slice_pkt(reg)) 8903 mark_reg_invalid(env, reg); 8904 })); 8905 } 8906 8907 enum { 8908 AT_PKT_END = -1, 8909 BEYOND_PKT_END = -2, 8910 }; 8911 8912 static void mark_pkt_end(struct bpf_verifier_state *vstate, int regn, bool range_open) 8913 { 8914 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 8915 struct bpf_reg_state *reg = &state->regs[regn]; 8916 8917 if (reg->type != PTR_TO_PACKET) 8918 /* PTR_TO_PACKET_META is not supported yet */ 8919 return; 8920 8921 /* The 'reg' is pkt > pkt_end or pkt >= pkt_end. 8922 * How far beyond pkt_end it goes is unknown. 8923 * if (!range_open) it's the case of pkt >= pkt_end 8924 * if (range_open) it's the case of pkt > pkt_end 8925 * hence this pointer is at least 1 byte bigger than pkt_end 8926 */ 8927 if (range_open) 8928 reg->range = BEYOND_PKT_END; 8929 else 8930 reg->range = AT_PKT_END; 8931 } 8932 8933 /* The pointer with the specified id has released its reference to kernel 8934 * resources. Identify all copies of the same pointer and clear the reference. 8935 */ 8936 static int release_reference(struct bpf_verifier_env *env, 8937 int ref_obj_id) 8938 { 8939 struct bpf_func_state *state; 8940 struct bpf_reg_state *reg; 8941 int err; 8942 8943 err = release_reference_state(cur_func(env), ref_obj_id); 8944 if (err) 8945 return err; 8946 8947 bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({ 8948 if (reg->ref_obj_id == ref_obj_id) 8949 mark_reg_invalid(env, reg); 8950 })); 8951 8952 return 0; 8953 } 8954 8955 static void invalidate_non_owning_refs(struct bpf_verifier_env *env) 8956 { 8957 struct bpf_func_state *unused; 8958 struct bpf_reg_state *reg; 8959 8960 bpf_for_each_reg_in_vstate(env->cur_state, unused, reg, ({ 8961 if (type_is_non_owning_ref(reg->type)) 8962 mark_reg_invalid(env, reg); 8963 })); 8964 } 8965 8966 static void clear_caller_saved_regs(struct bpf_verifier_env *env, 8967 struct bpf_reg_state *regs) 8968 { 8969 int i; 8970 8971 /* after the call registers r0 - r5 were scratched */ 8972 for (i = 0; i < CALLER_SAVED_REGS; i++) { 8973 mark_reg_not_init(env, regs, caller_saved[i]); 8974 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK); 8975 } 8976 } 8977 8978 typedef int (*set_callee_state_fn)(struct bpf_verifier_env *env, 8979 struct bpf_func_state *caller, 8980 struct bpf_func_state *callee, 8981 int insn_idx); 8982 8983 static int set_callee_state(struct bpf_verifier_env *env, 8984 struct bpf_func_state *caller, 8985 struct bpf_func_state *callee, int insn_idx); 8986 8987 static int __check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn, 8988 int *insn_idx, int subprog, 8989 set_callee_state_fn set_callee_state_cb) 8990 { 8991 struct bpf_verifier_state *state = env->cur_state; 8992 struct bpf_func_state *caller, *callee; 8993 int err; 8994 8995 if (state->curframe + 1 >= MAX_CALL_FRAMES) { 8996 verbose(env, "the call stack of %d frames is too deep\n", 8997 state->curframe + 2); 8998 return -E2BIG; 8999 } 9000 9001 caller = state->frame[state->curframe]; 9002 if (state->frame[state->curframe + 1]) { 9003 verbose(env, "verifier bug. Frame %d already allocated\n", 9004 state->curframe + 1); 9005 return -EFAULT; 9006 } 9007 9008 err = btf_check_subprog_call(env, subprog, caller->regs); 9009 if (err == -EFAULT) 9010 return err; 9011 if (subprog_is_global(env, subprog)) { 9012 if (err) { 9013 verbose(env, "Caller passes invalid args into func#%d\n", 9014 subprog); 9015 return err; 9016 } else { 9017 if (env->log.level & BPF_LOG_LEVEL) 9018 verbose(env, 9019 "Func#%d is global and valid. Skipping.\n", 9020 subprog); 9021 clear_caller_saved_regs(env, caller->regs); 9022 9023 /* All global functions return a 64-bit SCALAR_VALUE */ 9024 mark_reg_unknown(env, caller->regs, BPF_REG_0); 9025 caller->regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG; 9026 9027 /* continue with next insn after call */ 9028 return 0; 9029 } 9030 } 9031 9032 /* set_callee_state is used for direct subprog calls, but we are 9033 * interested in validating only BPF helpers that can call subprogs as 9034 * callbacks 9035 */ 9036 if (set_callee_state_cb != set_callee_state) { 9037 env->subprog_info[subprog].is_cb = true; 9038 if (bpf_pseudo_kfunc_call(insn) && 9039 !is_callback_calling_kfunc(insn->imm)) { 9040 verbose(env, "verifier bug: kfunc %s#%d not marked as callback-calling\n", 9041 func_id_name(insn->imm), insn->imm); 9042 return -EFAULT; 9043 } else if (!bpf_pseudo_kfunc_call(insn) && 9044 !is_callback_calling_function(insn->imm)) { /* helper */ 9045 verbose(env, "verifier bug: helper %s#%d not marked as callback-calling\n", 9046 func_id_name(insn->imm), insn->imm); 9047 return -EFAULT; 9048 } 9049 } 9050 9051 if (insn->code == (BPF_JMP | BPF_CALL) && 9052 insn->src_reg == 0 && 9053 insn->imm == BPF_FUNC_timer_set_callback) { 9054 struct bpf_verifier_state *async_cb; 9055 9056 /* there is no real recursion here. timer callbacks are async */ 9057 env->subprog_info[subprog].is_async_cb = true; 9058 async_cb = push_async_cb(env, env->subprog_info[subprog].start, 9059 *insn_idx, subprog); 9060 if (!async_cb) 9061 return -EFAULT; 9062 callee = async_cb->frame[0]; 9063 callee->async_entry_cnt = caller->async_entry_cnt + 1; 9064 9065 /* Convert bpf_timer_set_callback() args into timer callback args */ 9066 err = set_callee_state_cb(env, caller, callee, *insn_idx); 9067 if (err) 9068 return err; 9069 9070 clear_caller_saved_regs(env, caller->regs); 9071 mark_reg_unknown(env, caller->regs, BPF_REG_0); 9072 caller->regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG; 9073 /* continue with next insn after call */ 9074 return 0; 9075 } 9076 9077 callee = kzalloc(sizeof(*callee), GFP_KERNEL); 9078 if (!callee) 9079 return -ENOMEM; 9080 state->frame[state->curframe + 1] = callee; 9081 9082 /* callee cannot access r0, r6 - r9 for reading and has to write 9083 * into its own stack before reading from it. 9084 * callee can read/write into caller's stack 9085 */ 9086 init_func_state(env, callee, 9087 /* remember the callsite, it will be used by bpf_exit */ 9088 *insn_idx /* callsite */, 9089 state->curframe + 1 /* frameno within this callchain */, 9090 subprog /* subprog number within this prog */); 9091 9092 /* Transfer references to the callee */ 9093 err = copy_reference_state(callee, caller); 9094 if (err) 9095 goto err_out; 9096 9097 err = set_callee_state_cb(env, caller, callee, *insn_idx); 9098 if (err) 9099 goto err_out; 9100 9101 clear_caller_saved_regs(env, caller->regs); 9102 9103 /* only increment it after check_reg_arg() finished */ 9104 state->curframe++; 9105 9106 /* and go analyze first insn of the callee */ 9107 *insn_idx = env->subprog_info[subprog].start - 1; 9108 9109 if (env->log.level & BPF_LOG_LEVEL) { 9110 verbose(env, "caller:\n"); 9111 print_verifier_state(env, caller, true); 9112 verbose(env, "callee:\n"); 9113 print_verifier_state(env, callee, true); 9114 } 9115 return 0; 9116 9117 err_out: 9118 free_func_state(callee); 9119 state->frame[state->curframe + 1] = NULL; 9120 return err; 9121 } 9122 9123 int map_set_for_each_callback_args(struct bpf_verifier_env *env, 9124 struct bpf_func_state *caller, 9125 struct bpf_func_state *callee) 9126 { 9127 /* bpf_for_each_map_elem(struct bpf_map *map, void *callback_fn, 9128 * void *callback_ctx, u64 flags); 9129 * callback_fn(struct bpf_map *map, void *key, void *value, 9130 * void *callback_ctx); 9131 */ 9132 callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1]; 9133 9134 callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY; 9135 __mark_reg_known_zero(&callee->regs[BPF_REG_2]); 9136 callee->regs[BPF_REG_2].map_ptr = caller->regs[BPF_REG_1].map_ptr; 9137 9138 callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE; 9139 __mark_reg_known_zero(&callee->regs[BPF_REG_3]); 9140 callee->regs[BPF_REG_3].map_ptr = caller->regs[BPF_REG_1].map_ptr; 9141 9142 /* pointer to stack or null */ 9143 callee->regs[BPF_REG_4] = caller->regs[BPF_REG_3]; 9144 9145 /* unused */ 9146 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]); 9147 return 0; 9148 } 9149 9150 static int set_callee_state(struct bpf_verifier_env *env, 9151 struct bpf_func_state *caller, 9152 struct bpf_func_state *callee, int insn_idx) 9153 { 9154 int i; 9155 9156 /* copy r1 - r5 args that callee can access. The copy includes parent 9157 * pointers, which connects us up to the liveness chain 9158 */ 9159 for (i = BPF_REG_1; i <= BPF_REG_5; i++) 9160 callee->regs[i] = caller->regs[i]; 9161 return 0; 9162 } 9163 9164 static int check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn, 9165 int *insn_idx) 9166 { 9167 int subprog, target_insn; 9168 9169 target_insn = *insn_idx + insn->imm + 1; 9170 subprog = find_subprog(env, target_insn); 9171 if (subprog < 0) { 9172 verbose(env, "verifier bug. No program starts at insn %d\n", 9173 target_insn); 9174 return -EFAULT; 9175 } 9176 9177 return __check_func_call(env, insn, insn_idx, subprog, set_callee_state); 9178 } 9179 9180 static int set_map_elem_callback_state(struct bpf_verifier_env *env, 9181 struct bpf_func_state *caller, 9182 struct bpf_func_state *callee, 9183 int insn_idx) 9184 { 9185 struct bpf_insn_aux_data *insn_aux = &env->insn_aux_data[insn_idx]; 9186 struct bpf_map *map; 9187 int err; 9188 9189 if (bpf_map_ptr_poisoned(insn_aux)) { 9190 verbose(env, "tail_call abusing map_ptr\n"); 9191 return -EINVAL; 9192 } 9193 9194 map = BPF_MAP_PTR(insn_aux->map_ptr_state); 9195 if (!map->ops->map_set_for_each_callback_args || 9196 !map->ops->map_for_each_callback) { 9197 verbose(env, "callback function not allowed for map\n"); 9198 return -ENOTSUPP; 9199 } 9200 9201 err = map->ops->map_set_for_each_callback_args(env, caller, callee); 9202 if (err) 9203 return err; 9204 9205 callee->in_callback_fn = true; 9206 callee->callback_ret_range = tnum_range(0, 1); 9207 return 0; 9208 } 9209 9210 static int set_loop_callback_state(struct bpf_verifier_env *env, 9211 struct bpf_func_state *caller, 9212 struct bpf_func_state *callee, 9213 int insn_idx) 9214 { 9215 /* bpf_loop(u32 nr_loops, void *callback_fn, void *callback_ctx, 9216 * u64 flags); 9217 * callback_fn(u32 index, void *callback_ctx); 9218 */ 9219 callee->regs[BPF_REG_1].type = SCALAR_VALUE; 9220 callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3]; 9221 9222 /* unused */ 9223 __mark_reg_not_init(env, &callee->regs[BPF_REG_3]); 9224 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]); 9225 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]); 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_timer_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 struct bpf_map *map_ptr = caller->regs[BPF_REG_1].map_ptr; 9238 9239 /* bpf_timer_set_callback(struct bpf_timer *timer, void *callback_fn); 9240 * callback_fn(struct bpf_map *map, void *key, void *value); 9241 */ 9242 callee->regs[BPF_REG_1].type = CONST_PTR_TO_MAP; 9243 __mark_reg_known_zero(&callee->regs[BPF_REG_1]); 9244 callee->regs[BPF_REG_1].map_ptr = map_ptr; 9245 9246 callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY; 9247 __mark_reg_known_zero(&callee->regs[BPF_REG_2]); 9248 callee->regs[BPF_REG_2].map_ptr = map_ptr; 9249 9250 callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE; 9251 __mark_reg_known_zero(&callee->regs[BPF_REG_3]); 9252 callee->regs[BPF_REG_3].map_ptr = map_ptr; 9253 9254 /* unused */ 9255 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]); 9256 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]); 9257 callee->in_async_callback_fn = true; 9258 callee->callback_ret_range = tnum_range(0, 1); 9259 return 0; 9260 } 9261 9262 static int set_find_vma_callback_state(struct bpf_verifier_env *env, 9263 struct bpf_func_state *caller, 9264 struct bpf_func_state *callee, 9265 int insn_idx) 9266 { 9267 /* bpf_find_vma(struct task_struct *task, u64 addr, 9268 * void *callback_fn, void *callback_ctx, u64 flags) 9269 * (callback_fn)(struct task_struct *task, 9270 * struct vm_area_struct *vma, void *callback_ctx); 9271 */ 9272 callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1]; 9273 9274 callee->regs[BPF_REG_2].type = PTR_TO_BTF_ID; 9275 __mark_reg_known_zero(&callee->regs[BPF_REG_2]); 9276 callee->regs[BPF_REG_2].btf = btf_vmlinux; 9277 callee->regs[BPF_REG_2].btf_id = btf_tracing_ids[BTF_TRACING_TYPE_VMA], 9278 9279 /* pointer to stack or null */ 9280 callee->regs[BPF_REG_3] = caller->regs[BPF_REG_4]; 9281 9282 /* unused */ 9283 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]); 9284 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]); 9285 callee->in_callback_fn = true; 9286 callee->callback_ret_range = tnum_range(0, 1); 9287 return 0; 9288 } 9289 9290 static int set_user_ringbuf_callback_state(struct bpf_verifier_env *env, 9291 struct bpf_func_state *caller, 9292 struct bpf_func_state *callee, 9293 int insn_idx) 9294 { 9295 /* bpf_user_ringbuf_drain(struct bpf_map *map, void *callback_fn, void 9296 * callback_ctx, u64 flags); 9297 * callback_fn(const struct bpf_dynptr_t* dynptr, void *callback_ctx); 9298 */ 9299 __mark_reg_not_init(env, &callee->regs[BPF_REG_0]); 9300 mark_dynptr_cb_reg(env, &callee->regs[BPF_REG_1], BPF_DYNPTR_TYPE_LOCAL); 9301 callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3]; 9302 9303 /* unused */ 9304 __mark_reg_not_init(env, &callee->regs[BPF_REG_3]); 9305 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]); 9306 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]); 9307 9308 callee->in_callback_fn = true; 9309 callee->callback_ret_range = tnum_range(0, 1); 9310 return 0; 9311 } 9312 9313 static int set_rbtree_add_callback_state(struct bpf_verifier_env *env, 9314 struct bpf_func_state *caller, 9315 struct bpf_func_state *callee, 9316 int insn_idx) 9317 { 9318 /* void bpf_rbtree_add_impl(struct bpf_rb_root *root, struct bpf_rb_node *node, 9319 * bool (less)(struct bpf_rb_node *a, const struct bpf_rb_node *b)); 9320 * 9321 * 'struct bpf_rb_node *node' arg to bpf_rbtree_add_impl is the same PTR_TO_BTF_ID w/ offset 9322 * that 'less' callback args will be receiving. However, 'node' arg was release_reference'd 9323 * by this point, so look at 'root' 9324 */ 9325 struct btf_field *field; 9326 9327 field = reg_find_field_offset(&caller->regs[BPF_REG_1], caller->regs[BPF_REG_1].off, 9328 BPF_RB_ROOT); 9329 if (!field || !field->graph_root.value_btf_id) 9330 return -EFAULT; 9331 9332 mark_reg_graph_node(callee->regs, BPF_REG_1, &field->graph_root); 9333 ref_set_non_owning(env, &callee->regs[BPF_REG_1]); 9334 mark_reg_graph_node(callee->regs, BPF_REG_2, &field->graph_root); 9335 ref_set_non_owning(env, &callee->regs[BPF_REG_2]); 9336 9337 __mark_reg_not_init(env, &callee->regs[BPF_REG_3]); 9338 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]); 9339 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]); 9340 callee->in_callback_fn = true; 9341 callee->callback_ret_range = tnum_range(0, 1); 9342 return 0; 9343 } 9344 9345 static bool is_rbtree_lock_required_kfunc(u32 btf_id); 9346 9347 /* Are we currently verifying the callback for a rbtree helper that must 9348 * be called with lock held? If so, no need to complain about unreleased 9349 * lock 9350 */ 9351 static bool in_rbtree_lock_required_cb(struct bpf_verifier_env *env) 9352 { 9353 struct bpf_verifier_state *state = env->cur_state; 9354 struct bpf_insn *insn = env->prog->insnsi; 9355 struct bpf_func_state *callee; 9356 int kfunc_btf_id; 9357 9358 if (!state->curframe) 9359 return false; 9360 9361 callee = state->frame[state->curframe]; 9362 9363 if (!callee->in_callback_fn) 9364 return false; 9365 9366 kfunc_btf_id = insn[callee->callsite].imm; 9367 return is_rbtree_lock_required_kfunc(kfunc_btf_id); 9368 } 9369 9370 static int prepare_func_exit(struct bpf_verifier_env *env, int *insn_idx) 9371 { 9372 struct bpf_verifier_state *state = env->cur_state; 9373 struct bpf_func_state *caller, *callee; 9374 struct bpf_reg_state *r0; 9375 int err; 9376 9377 callee = state->frame[state->curframe]; 9378 r0 = &callee->regs[BPF_REG_0]; 9379 if (r0->type == PTR_TO_STACK) { 9380 /* technically it's ok to return caller's stack pointer 9381 * (or caller's caller's pointer) back to the caller, 9382 * since these pointers are valid. Only current stack 9383 * pointer will be invalid as soon as function exits, 9384 * but let's be conservative 9385 */ 9386 verbose(env, "cannot return stack pointer to the caller\n"); 9387 return -EINVAL; 9388 } 9389 9390 caller = state->frame[state->curframe - 1]; 9391 if (callee->in_callback_fn) { 9392 /* enforce R0 return value range [0, 1]. */ 9393 struct tnum range = callee->callback_ret_range; 9394 9395 if (r0->type != SCALAR_VALUE) { 9396 verbose(env, "R0 not a scalar value\n"); 9397 return -EACCES; 9398 } 9399 if (!tnum_in(range, r0->var_off)) { 9400 verbose_invalid_scalar(env, r0, &range, "callback return", "R0"); 9401 return -EINVAL; 9402 } 9403 } else { 9404 /* return to the caller whatever r0 had in the callee */ 9405 caller->regs[BPF_REG_0] = *r0; 9406 } 9407 9408 /* callback_fn frame should have released its own additions to parent's 9409 * reference state at this point, or check_reference_leak would 9410 * complain, hence it must be the same as the caller. There is no need 9411 * to copy it back. 9412 */ 9413 if (!callee->in_callback_fn) { 9414 /* Transfer references to the caller */ 9415 err = copy_reference_state(caller, callee); 9416 if (err) 9417 return err; 9418 } 9419 9420 *insn_idx = callee->callsite + 1; 9421 if (env->log.level & BPF_LOG_LEVEL) { 9422 verbose(env, "returning from callee:\n"); 9423 print_verifier_state(env, callee, true); 9424 verbose(env, "to caller at %d:\n", *insn_idx); 9425 print_verifier_state(env, caller, true); 9426 } 9427 /* clear everything in the callee. In case of exceptional exits using 9428 * bpf_throw, this will be done by copy_verifier_state for extra frames. */ 9429 free_func_state(callee); 9430 state->frame[state->curframe--] = NULL; 9431 return 0; 9432 } 9433 9434 static void do_refine_retval_range(struct bpf_reg_state *regs, int ret_type, 9435 int func_id, 9436 struct bpf_call_arg_meta *meta) 9437 { 9438 struct bpf_reg_state *ret_reg = ®s[BPF_REG_0]; 9439 9440 if (ret_type != RET_INTEGER) 9441 return; 9442 9443 switch (func_id) { 9444 case BPF_FUNC_get_stack: 9445 case BPF_FUNC_get_task_stack: 9446 case BPF_FUNC_probe_read_str: 9447 case BPF_FUNC_probe_read_kernel_str: 9448 case BPF_FUNC_probe_read_user_str: 9449 ret_reg->smax_value = meta->msize_max_value; 9450 ret_reg->s32_max_value = meta->msize_max_value; 9451 ret_reg->smin_value = -MAX_ERRNO; 9452 ret_reg->s32_min_value = -MAX_ERRNO; 9453 reg_bounds_sync(ret_reg); 9454 break; 9455 case BPF_FUNC_get_smp_processor_id: 9456 ret_reg->umax_value = nr_cpu_ids - 1; 9457 ret_reg->u32_max_value = nr_cpu_ids - 1; 9458 ret_reg->smax_value = nr_cpu_ids - 1; 9459 ret_reg->s32_max_value = nr_cpu_ids - 1; 9460 ret_reg->umin_value = 0; 9461 ret_reg->u32_min_value = 0; 9462 ret_reg->smin_value = 0; 9463 ret_reg->s32_min_value = 0; 9464 reg_bounds_sync(ret_reg); 9465 break; 9466 } 9467 } 9468 9469 static int 9470 record_func_map(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta, 9471 int func_id, int insn_idx) 9472 { 9473 struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx]; 9474 struct bpf_map *map = meta->map_ptr; 9475 9476 if (func_id != BPF_FUNC_tail_call && 9477 func_id != BPF_FUNC_map_lookup_elem && 9478 func_id != BPF_FUNC_map_update_elem && 9479 func_id != BPF_FUNC_map_delete_elem && 9480 func_id != BPF_FUNC_map_push_elem && 9481 func_id != BPF_FUNC_map_pop_elem && 9482 func_id != BPF_FUNC_map_peek_elem && 9483 func_id != BPF_FUNC_for_each_map_elem && 9484 func_id != BPF_FUNC_redirect_map && 9485 func_id != BPF_FUNC_map_lookup_percpu_elem) 9486 return 0; 9487 9488 if (map == NULL) { 9489 verbose(env, "kernel subsystem misconfigured verifier\n"); 9490 return -EINVAL; 9491 } 9492 9493 /* In case of read-only, some additional restrictions 9494 * need to be applied in order to prevent altering the 9495 * state of the map from program side. 9496 */ 9497 if ((map->map_flags & BPF_F_RDONLY_PROG) && 9498 (func_id == BPF_FUNC_map_delete_elem || 9499 func_id == BPF_FUNC_map_update_elem || 9500 func_id == BPF_FUNC_map_push_elem || 9501 func_id == BPF_FUNC_map_pop_elem)) { 9502 verbose(env, "write into map forbidden\n"); 9503 return -EACCES; 9504 } 9505 9506 if (!BPF_MAP_PTR(aux->map_ptr_state)) 9507 bpf_map_ptr_store(aux, meta->map_ptr, 9508 !meta->map_ptr->bypass_spec_v1); 9509 else if (BPF_MAP_PTR(aux->map_ptr_state) != meta->map_ptr) 9510 bpf_map_ptr_store(aux, BPF_MAP_PTR_POISON, 9511 !meta->map_ptr->bypass_spec_v1); 9512 return 0; 9513 } 9514 9515 static int 9516 record_func_key(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta, 9517 int func_id, int insn_idx) 9518 { 9519 struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx]; 9520 struct bpf_reg_state *regs = cur_regs(env), *reg; 9521 struct bpf_map *map = meta->map_ptr; 9522 u64 val, max; 9523 int err; 9524 9525 if (func_id != BPF_FUNC_tail_call) 9526 return 0; 9527 if (!map || map->map_type != BPF_MAP_TYPE_PROG_ARRAY) { 9528 verbose(env, "kernel subsystem misconfigured verifier\n"); 9529 return -EINVAL; 9530 } 9531 9532 reg = ®s[BPF_REG_3]; 9533 val = reg->var_off.value; 9534 max = map->max_entries; 9535 9536 if (!(register_is_const(reg) && val < max)) { 9537 bpf_map_key_store(aux, BPF_MAP_KEY_POISON); 9538 return 0; 9539 } 9540 9541 err = mark_chain_precision(env, BPF_REG_3); 9542 if (err) 9543 return err; 9544 if (bpf_map_key_unseen(aux)) 9545 bpf_map_key_store(aux, val); 9546 else if (!bpf_map_key_poisoned(aux) && 9547 bpf_map_key_immediate(aux) != val) 9548 bpf_map_key_store(aux, BPF_MAP_KEY_POISON); 9549 return 0; 9550 } 9551 9552 static int check_reference_leak(struct bpf_verifier_env *env, bool exception_exit) 9553 { 9554 struct bpf_func_state *state = cur_func(env); 9555 bool refs_lingering = false; 9556 int i; 9557 9558 if (!exception_exit && state->frameno && !state->in_callback_fn) 9559 return 0; 9560 9561 for (i = 0; i < state->acquired_refs; i++) { 9562 if (!exception_exit && state->in_callback_fn && state->refs[i].callback_ref != state->frameno) 9563 continue; 9564 verbose(env, "Unreleased reference id=%d alloc_insn=%d\n", 9565 state->refs[i].id, state->refs[i].insn_idx); 9566 refs_lingering = true; 9567 } 9568 return refs_lingering ? -EINVAL : 0; 9569 } 9570 9571 static int check_bpf_snprintf_call(struct bpf_verifier_env *env, 9572 struct bpf_reg_state *regs) 9573 { 9574 struct bpf_reg_state *fmt_reg = ®s[BPF_REG_3]; 9575 struct bpf_reg_state *data_len_reg = ®s[BPF_REG_5]; 9576 struct bpf_map *fmt_map = fmt_reg->map_ptr; 9577 struct bpf_bprintf_data data = {}; 9578 int err, fmt_map_off, num_args; 9579 u64 fmt_addr; 9580 char *fmt; 9581 9582 /* data must be an array of u64 */ 9583 if (data_len_reg->var_off.value % 8) 9584 return -EINVAL; 9585 num_args = data_len_reg->var_off.value / 8; 9586 9587 /* fmt being ARG_PTR_TO_CONST_STR guarantees that var_off is const 9588 * and map_direct_value_addr is set. 9589 */ 9590 fmt_map_off = fmt_reg->off + fmt_reg->var_off.value; 9591 err = fmt_map->ops->map_direct_value_addr(fmt_map, &fmt_addr, 9592 fmt_map_off); 9593 if (err) { 9594 verbose(env, "verifier bug\n"); 9595 return -EFAULT; 9596 } 9597 fmt = (char *)(long)fmt_addr + fmt_map_off; 9598 9599 /* We are also guaranteed that fmt+fmt_map_off is NULL terminated, we 9600 * can focus on validating the format specifiers. 9601 */ 9602 err = bpf_bprintf_prepare(fmt, UINT_MAX, NULL, num_args, &data); 9603 if (err < 0) 9604 verbose(env, "Invalid format string\n"); 9605 9606 return err; 9607 } 9608 9609 static int check_get_func_ip(struct bpf_verifier_env *env) 9610 { 9611 enum bpf_prog_type type = resolve_prog_type(env->prog); 9612 int func_id = BPF_FUNC_get_func_ip; 9613 9614 if (type == BPF_PROG_TYPE_TRACING) { 9615 if (!bpf_prog_has_trampoline(env->prog)) { 9616 verbose(env, "func %s#%d supported only for fentry/fexit/fmod_ret programs\n", 9617 func_id_name(func_id), func_id); 9618 return -ENOTSUPP; 9619 } 9620 return 0; 9621 } else if (type == BPF_PROG_TYPE_KPROBE) { 9622 return 0; 9623 } 9624 9625 verbose(env, "func %s#%d not supported for program type %d\n", 9626 func_id_name(func_id), func_id, type); 9627 return -ENOTSUPP; 9628 } 9629 9630 static struct bpf_insn_aux_data *cur_aux(struct bpf_verifier_env *env) 9631 { 9632 return &env->insn_aux_data[env->insn_idx]; 9633 } 9634 9635 static bool loop_flag_is_zero(struct bpf_verifier_env *env) 9636 { 9637 struct bpf_reg_state *regs = cur_regs(env); 9638 struct bpf_reg_state *reg = ®s[BPF_REG_4]; 9639 bool reg_is_null = register_is_null(reg); 9640 9641 if (reg_is_null) 9642 mark_chain_precision(env, BPF_REG_4); 9643 9644 return reg_is_null; 9645 } 9646 9647 static void update_loop_inline_state(struct bpf_verifier_env *env, u32 subprogno) 9648 { 9649 struct bpf_loop_inline_state *state = &cur_aux(env)->loop_inline_state; 9650 9651 if (!state->initialized) { 9652 state->initialized = 1; 9653 state->fit_for_inline = loop_flag_is_zero(env); 9654 state->callback_subprogno = subprogno; 9655 return; 9656 } 9657 9658 if (!state->fit_for_inline) 9659 return; 9660 9661 state->fit_for_inline = (loop_flag_is_zero(env) && 9662 state->callback_subprogno == subprogno); 9663 } 9664 9665 static int check_helper_call(struct bpf_verifier_env *env, struct bpf_insn *insn, 9666 int *insn_idx_p) 9667 { 9668 enum bpf_prog_type prog_type = resolve_prog_type(env->prog); 9669 bool returns_cpu_specific_alloc_ptr = false; 9670 const struct bpf_func_proto *fn = NULL; 9671 enum bpf_return_type ret_type; 9672 enum bpf_type_flag ret_flag; 9673 struct bpf_reg_state *regs; 9674 struct bpf_call_arg_meta meta; 9675 int insn_idx = *insn_idx_p; 9676 bool changes_data; 9677 int i, err, func_id; 9678 9679 /* find function prototype */ 9680 func_id = insn->imm; 9681 if (func_id < 0 || func_id >= __BPF_FUNC_MAX_ID) { 9682 verbose(env, "invalid func %s#%d\n", func_id_name(func_id), 9683 func_id); 9684 return -EINVAL; 9685 } 9686 9687 if (env->ops->get_func_proto) 9688 fn = env->ops->get_func_proto(func_id, env->prog); 9689 if (!fn) { 9690 verbose(env, "unknown func %s#%d\n", func_id_name(func_id), 9691 func_id); 9692 return -EINVAL; 9693 } 9694 9695 /* eBPF programs must be GPL compatible to use GPL-ed functions */ 9696 if (!env->prog->gpl_compatible && fn->gpl_only) { 9697 verbose(env, "cannot call GPL-restricted function from non-GPL compatible program\n"); 9698 return -EINVAL; 9699 } 9700 9701 if (fn->allowed && !fn->allowed(env->prog)) { 9702 verbose(env, "helper call is not allowed in probe\n"); 9703 return -EINVAL; 9704 } 9705 9706 if (!env->prog->aux->sleepable && fn->might_sleep) { 9707 verbose(env, "helper call might sleep in a non-sleepable prog\n"); 9708 return -EINVAL; 9709 } 9710 9711 /* With LD_ABS/IND some JITs save/restore skb from r1. */ 9712 changes_data = bpf_helper_changes_pkt_data(fn->func); 9713 if (changes_data && fn->arg1_type != ARG_PTR_TO_CTX) { 9714 verbose(env, "kernel subsystem misconfigured func %s#%d: r1 != ctx\n", 9715 func_id_name(func_id), func_id); 9716 return -EINVAL; 9717 } 9718 9719 memset(&meta, 0, sizeof(meta)); 9720 meta.pkt_access = fn->pkt_access; 9721 9722 err = check_func_proto(fn, func_id); 9723 if (err) { 9724 verbose(env, "kernel subsystem misconfigured func %s#%d\n", 9725 func_id_name(func_id), func_id); 9726 return err; 9727 } 9728 9729 if (env->cur_state->active_rcu_lock) { 9730 if (fn->might_sleep) { 9731 verbose(env, "sleepable helper %s#%d in rcu_read_lock region\n", 9732 func_id_name(func_id), func_id); 9733 return -EINVAL; 9734 } 9735 9736 if (env->prog->aux->sleepable && is_storage_get_function(func_id)) 9737 env->insn_aux_data[insn_idx].storage_get_func_atomic = true; 9738 } 9739 9740 meta.func_id = func_id; 9741 /* check args */ 9742 for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++) { 9743 err = check_func_arg(env, i, &meta, fn, insn_idx); 9744 if (err) 9745 return err; 9746 } 9747 9748 err = record_func_map(env, &meta, func_id, insn_idx); 9749 if (err) 9750 return err; 9751 9752 err = record_func_key(env, &meta, func_id, insn_idx); 9753 if (err) 9754 return err; 9755 9756 /* Mark slots with STACK_MISC in case of raw mode, stack offset 9757 * is inferred from register state. 9758 */ 9759 for (i = 0; i < meta.access_size; i++) { 9760 err = check_mem_access(env, insn_idx, meta.regno, i, BPF_B, 9761 BPF_WRITE, -1, false, false); 9762 if (err) 9763 return err; 9764 } 9765 9766 regs = cur_regs(env); 9767 9768 if (meta.release_regno) { 9769 err = -EINVAL; 9770 /* This can only be set for PTR_TO_STACK, as CONST_PTR_TO_DYNPTR cannot 9771 * be released by any dynptr helper. Hence, unmark_stack_slots_dynptr 9772 * is safe to do directly. 9773 */ 9774 if (arg_type_is_dynptr(fn->arg_type[meta.release_regno - BPF_REG_1])) { 9775 if (regs[meta.release_regno].type == CONST_PTR_TO_DYNPTR) { 9776 verbose(env, "verifier internal error: CONST_PTR_TO_DYNPTR cannot be released\n"); 9777 return -EFAULT; 9778 } 9779 err = unmark_stack_slots_dynptr(env, ®s[meta.release_regno]); 9780 } else if (func_id == BPF_FUNC_kptr_xchg && meta.ref_obj_id) { 9781 u32 ref_obj_id = meta.ref_obj_id; 9782 bool in_rcu = in_rcu_cs(env); 9783 struct bpf_func_state *state; 9784 struct bpf_reg_state *reg; 9785 9786 err = release_reference_state(cur_func(env), ref_obj_id); 9787 if (!err) { 9788 bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({ 9789 if (reg->ref_obj_id == ref_obj_id) { 9790 if (in_rcu && (reg->type & MEM_ALLOC) && (reg->type & MEM_PERCPU)) { 9791 reg->ref_obj_id = 0; 9792 reg->type &= ~MEM_ALLOC; 9793 reg->type |= MEM_RCU; 9794 } else { 9795 mark_reg_invalid(env, reg); 9796 } 9797 } 9798 })); 9799 } 9800 } else if (meta.ref_obj_id) { 9801 err = release_reference(env, meta.ref_obj_id); 9802 } else if (register_is_null(®s[meta.release_regno])) { 9803 /* meta.ref_obj_id can only be 0 if register that is meant to be 9804 * released is NULL, which must be > R0. 9805 */ 9806 err = 0; 9807 } 9808 if (err) { 9809 verbose(env, "func %s#%d reference has not been acquired before\n", 9810 func_id_name(func_id), func_id); 9811 return err; 9812 } 9813 } 9814 9815 switch (func_id) { 9816 case BPF_FUNC_tail_call: 9817 err = check_reference_leak(env, false); 9818 if (err) { 9819 verbose(env, "tail_call would lead to reference leak\n"); 9820 return err; 9821 } 9822 break; 9823 case BPF_FUNC_get_local_storage: 9824 /* check that flags argument in get_local_storage(map, flags) is 0, 9825 * this is required because get_local_storage() can't return an error. 9826 */ 9827 if (!register_is_null(®s[BPF_REG_2])) { 9828 verbose(env, "get_local_storage() doesn't support non-zero flags\n"); 9829 return -EINVAL; 9830 } 9831 break; 9832 case BPF_FUNC_for_each_map_elem: 9833 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno, 9834 set_map_elem_callback_state); 9835 break; 9836 case BPF_FUNC_timer_set_callback: 9837 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno, 9838 set_timer_callback_state); 9839 break; 9840 case BPF_FUNC_find_vma: 9841 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno, 9842 set_find_vma_callback_state); 9843 break; 9844 case BPF_FUNC_snprintf: 9845 err = check_bpf_snprintf_call(env, regs); 9846 break; 9847 case BPF_FUNC_loop: 9848 update_loop_inline_state(env, meta.subprogno); 9849 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno, 9850 set_loop_callback_state); 9851 break; 9852 case BPF_FUNC_dynptr_from_mem: 9853 if (regs[BPF_REG_1].type != PTR_TO_MAP_VALUE) { 9854 verbose(env, "Unsupported reg type %s for bpf_dynptr_from_mem data\n", 9855 reg_type_str(env, regs[BPF_REG_1].type)); 9856 return -EACCES; 9857 } 9858 break; 9859 case BPF_FUNC_set_retval: 9860 if (prog_type == BPF_PROG_TYPE_LSM && 9861 env->prog->expected_attach_type == BPF_LSM_CGROUP) { 9862 if (!env->prog->aux->attach_func_proto->type) { 9863 /* Make sure programs that attach to void 9864 * hooks don't try to modify return value. 9865 */ 9866 verbose(env, "BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n"); 9867 return -EINVAL; 9868 } 9869 } 9870 break; 9871 case BPF_FUNC_dynptr_data: 9872 { 9873 struct bpf_reg_state *reg; 9874 int id, ref_obj_id; 9875 9876 reg = get_dynptr_arg_reg(env, fn, regs); 9877 if (!reg) 9878 return -EFAULT; 9879 9880 9881 if (meta.dynptr_id) { 9882 verbose(env, "verifier internal error: meta.dynptr_id already set\n"); 9883 return -EFAULT; 9884 } 9885 if (meta.ref_obj_id) { 9886 verbose(env, "verifier internal error: meta.ref_obj_id already set\n"); 9887 return -EFAULT; 9888 } 9889 9890 id = dynptr_id(env, reg); 9891 if (id < 0) { 9892 verbose(env, "verifier internal error: failed to obtain dynptr id\n"); 9893 return id; 9894 } 9895 9896 ref_obj_id = dynptr_ref_obj_id(env, reg); 9897 if (ref_obj_id < 0) { 9898 verbose(env, "verifier internal error: failed to obtain dynptr ref_obj_id\n"); 9899 return ref_obj_id; 9900 } 9901 9902 meta.dynptr_id = id; 9903 meta.ref_obj_id = ref_obj_id; 9904 9905 break; 9906 } 9907 case BPF_FUNC_dynptr_write: 9908 { 9909 enum bpf_dynptr_type dynptr_type; 9910 struct bpf_reg_state *reg; 9911 9912 reg = get_dynptr_arg_reg(env, fn, regs); 9913 if (!reg) 9914 return -EFAULT; 9915 9916 dynptr_type = dynptr_get_type(env, reg); 9917 if (dynptr_type == BPF_DYNPTR_TYPE_INVALID) 9918 return -EFAULT; 9919 9920 if (dynptr_type == BPF_DYNPTR_TYPE_SKB) 9921 /* this will trigger clear_all_pkt_pointers(), which will 9922 * invalidate all dynptr slices associated with the skb 9923 */ 9924 changes_data = true; 9925 9926 break; 9927 } 9928 case BPF_FUNC_per_cpu_ptr: 9929 case BPF_FUNC_this_cpu_ptr: 9930 { 9931 struct bpf_reg_state *reg = ®s[BPF_REG_1]; 9932 const struct btf_type *type; 9933 9934 if (reg->type & MEM_RCU) { 9935 type = btf_type_by_id(reg->btf, reg->btf_id); 9936 if (!type || !btf_type_is_struct(type)) { 9937 verbose(env, "Helper has invalid btf/btf_id in R1\n"); 9938 return -EFAULT; 9939 } 9940 returns_cpu_specific_alloc_ptr = true; 9941 env->insn_aux_data[insn_idx].call_with_percpu_alloc_ptr = true; 9942 } 9943 break; 9944 } 9945 case BPF_FUNC_user_ringbuf_drain: 9946 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno, 9947 set_user_ringbuf_callback_state); 9948 break; 9949 } 9950 9951 if (err) 9952 return err; 9953 9954 /* reset caller saved regs */ 9955 for (i = 0; i < CALLER_SAVED_REGS; i++) { 9956 mark_reg_not_init(env, regs, caller_saved[i]); 9957 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK); 9958 } 9959 9960 /* helper call returns 64-bit value. */ 9961 regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG; 9962 9963 /* update return register (already marked as written above) */ 9964 ret_type = fn->ret_type; 9965 ret_flag = type_flag(ret_type); 9966 9967 switch (base_type(ret_type)) { 9968 case RET_INTEGER: 9969 /* sets type to SCALAR_VALUE */ 9970 mark_reg_unknown(env, regs, BPF_REG_0); 9971 break; 9972 case RET_VOID: 9973 regs[BPF_REG_0].type = NOT_INIT; 9974 break; 9975 case RET_PTR_TO_MAP_VALUE: 9976 /* There is no offset yet applied, variable or fixed */ 9977 mark_reg_known_zero(env, regs, BPF_REG_0); 9978 /* remember map_ptr, so that check_map_access() 9979 * can check 'value_size' boundary of memory access 9980 * to map element returned from bpf_map_lookup_elem() 9981 */ 9982 if (meta.map_ptr == NULL) { 9983 verbose(env, 9984 "kernel subsystem misconfigured verifier\n"); 9985 return -EINVAL; 9986 } 9987 regs[BPF_REG_0].map_ptr = meta.map_ptr; 9988 regs[BPF_REG_0].map_uid = meta.map_uid; 9989 regs[BPF_REG_0].type = PTR_TO_MAP_VALUE | ret_flag; 9990 if (!type_may_be_null(ret_type) && 9991 btf_record_has_field(meta.map_ptr->record, BPF_SPIN_LOCK)) { 9992 regs[BPF_REG_0].id = ++env->id_gen; 9993 } 9994 break; 9995 case RET_PTR_TO_SOCKET: 9996 mark_reg_known_zero(env, regs, BPF_REG_0); 9997 regs[BPF_REG_0].type = PTR_TO_SOCKET | ret_flag; 9998 break; 9999 case RET_PTR_TO_SOCK_COMMON: 10000 mark_reg_known_zero(env, regs, BPF_REG_0); 10001 regs[BPF_REG_0].type = PTR_TO_SOCK_COMMON | ret_flag; 10002 break; 10003 case RET_PTR_TO_TCP_SOCK: 10004 mark_reg_known_zero(env, regs, BPF_REG_0); 10005 regs[BPF_REG_0].type = PTR_TO_TCP_SOCK | ret_flag; 10006 break; 10007 case RET_PTR_TO_MEM: 10008 mark_reg_known_zero(env, regs, BPF_REG_0); 10009 regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag; 10010 regs[BPF_REG_0].mem_size = meta.mem_size; 10011 break; 10012 case RET_PTR_TO_MEM_OR_BTF_ID: 10013 { 10014 const struct btf_type *t; 10015 10016 mark_reg_known_zero(env, regs, BPF_REG_0); 10017 t = btf_type_skip_modifiers(meta.ret_btf, meta.ret_btf_id, NULL); 10018 if (!btf_type_is_struct(t)) { 10019 u32 tsize; 10020 const struct btf_type *ret; 10021 const char *tname; 10022 10023 /* resolve the type size of ksym. */ 10024 ret = btf_resolve_size(meta.ret_btf, t, &tsize); 10025 if (IS_ERR(ret)) { 10026 tname = btf_name_by_offset(meta.ret_btf, t->name_off); 10027 verbose(env, "unable to resolve the size of type '%s': %ld\n", 10028 tname, PTR_ERR(ret)); 10029 return -EINVAL; 10030 } 10031 regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag; 10032 regs[BPF_REG_0].mem_size = tsize; 10033 } else { 10034 if (returns_cpu_specific_alloc_ptr) { 10035 regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC | MEM_RCU; 10036 } else { 10037 /* MEM_RDONLY may be carried from ret_flag, but it 10038 * doesn't apply on PTR_TO_BTF_ID. Fold it, otherwise 10039 * it will confuse the check of PTR_TO_BTF_ID in 10040 * check_mem_access(). 10041 */ 10042 ret_flag &= ~MEM_RDONLY; 10043 regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag; 10044 } 10045 10046 regs[BPF_REG_0].btf = meta.ret_btf; 10047 regs[BPF_REG_0].btf_id = meta.ret_btf_id; 10048 } 10049 break; 10050 } 10051 case RET_PTR_TO_BTF_ID: 10052 { 10053 struct btf *ret_btf; 10054 int ret_btf_id; 10055 10056 mark_reg_known_zero(env, regs, BPF_REG_0); 10057 regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag; 10058 if (func_id == BPF_FUNC_kptr_xchg) { 10059 ret_btf = meta.kptr_field->kptr.btf; 10060 ret_btf_id = meta.kptr_field->kptr.btf_id; 10061 if (!btf_is_kernel(ret_btf)) { 10062 regs[BPF_REG_0].type |= MEM_ALLOC; 10063 if (meta.kptr_field->type == BPF_KPTR_PERCPU) 10064 regs[BPF_REG_0].type |= MEM_PERCPU; 10065 } 10066 } else { 10067 if (fn->ret_btf_id == BPF_PTR_POISON) { 10068 verbose(env, "verifier internal error:"); 10069 verbose(env, "func %s has non-overwritten BPF_PTR_POISON return type\n", 10070 func_id_name(func_id)); 10071 return -EINVAL; 10072 } 10073 ret_btf = btf_vmlinux; 10074 ret_btf_id = *fn->ret_btf_id; 10075 } 10076 if (ret_btf_id == 0) { 10077 verbose(env, "invalid return type %u of func %s#%d\n", 10078 base_type(ret_type), func_id_name(func_id), 10079 func_id); 10080 return -EINVAL; 10081 } 10082 regs[BPF_REG_0].btf = ret_btf; 10083 regs[BPF_REG_0].btf_id = ret_btf_id; 10084 break; 10085 } 10086 default: 10087 verbose(env, "unknown return type %u of func %s#%d\n", 10088 base_type(ret_type), func_id_name(func_id), func_id); 10089 return -EINVAL; 10090 } 10091 10092 if (type_may_be_null(regs[BPF_REG_0].type)) 10093 regs[BPF_REG_0].id = ++env->id_gen; 10094 10095 if (helper_multiple_ref_obj_use(func_id, meta.map_ptr)) { 10096 verbose(env, "verifier internal error: func %s#%d sets ref_obj_id more than once\n", 10097 func_id_name(func_id), func_id); 10098 return -EFAULT; 10099 } 10100 10101 if (is_dynptr_ref_function(func_id)) 10102 regs[BPF_REG_0].dynptr_id = meta.dynptr_id; 10103 10104 if (is_ptr_cast_function(func_id) || is_dynptr_ref_function(func_id)) { 10105 /* For release_reference() */ 10106 regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id; 10107 } else if (is_acquire_function(func_id, meta.map_ptr)) { 10108 int id = acquire_reference_state(env, insn_idx); 10109 10110 if (id < 0) 10111 return id; 10112 /* For mark_ptr_or_null_reg() */ 10113 regs[BPF_REG_0].id = id; 10114 /* For release_reference() */ 10115 regs[BPF_REG_0].ref_obj_id = id; 10116 } 10117 10118 do_refine_retval_range(regs, fn->ret_type, func_id, &meta); 10119 10120 err = check_map_func_compatibility(env, meta.map_ptr, func_id); 10121 if (err) 10122 return err; 10123 10124 if ((func_id == BPF_FUNC_get_stack || 10125 func_id == BPF_FUNC_get_task_stack) && 10126 !env->prog->has_callchain_buf) { 10127 const char *err_str; 10128 10129 #ifdef CONFIG_PERF_EVENTS 10130 err = get_callchain_buffers(sysctl_perf_event_max_stack); 10131 err_str = "cannot get callchain buffer for func %s#%d\n"; 10132 #else 10133 err = -ENOTSUPP; 10134 err_str = "func %s#%d not supported without CONFIG_PERF_EVENTS\n"; 10135 #endif 10136 if (err) { 10137 verbose(env, err_str, func_id_name(func_id), func_id); 10138 return err; 10139 } 10140 10141 env->prog->has_callchain_buf = true; 10142 } 10143 10144 if (func_id == BPF_FUNC_get_stackid || func_id == BPF_FUNC_get_stack) 10145 env->prog->call_get_stack = true; 10146 10147 if (func_id == BPF_FUNC_get_func_ip) { 10148 if (check_get_func_ip(env)) 10149 return -ENOTSUPP; 10150 env->prog->call_get_func_ip = true; 10151 } 10152 10153 if (changes_data) 10154 clear_all_pkt_pointers(env); 10155 return 0; 10156 } 10157 10158 /* mark_btf_func_reg_size() is used when the reg size is determined by 10159 * the BTF func_proto's return value size and argument. 10160 */ 10161 static void mark_btf_func_reg_size(struct bpf_verifier_env *env, u32 regno, 10162 size_t reg_size) 10163 { 10164 struct bpf_reg_state *reg = &cur_regs(env)[regno]; 10165 10166 if (regno == BPF_REG_0) { 10167 /* Function return value */ 10168 reg->live |= REG_LIVE_WRITTEN; 10169 reg->subreg_def = reg_size == sizeof(u64) ? 10170 DEF_NOT_SUBREG : env->insn_idx + 1; 10171 } else { 10172 /* Function argument */ 10173 if (reg_size == sizeof(u64)) { 10174 mark_insn_zext(env, reg); 10175 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64); 10176 } else { 10177 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ32); 10178 } 10179 } 10180 } 10181 10182 static bool is_kfunc_acquire(struct bpf_kfunc_call_arg_meta *meta) 10183 { 10184 return meta->kfunc_flags & KF_ACQUIRE; 10185 } 10186 10187 static bool is_kfunc_release(struct bpf_kfunc_call_arg_meta *meta) 10188 { 10189 return meta->kfunc_flags & KF_RELEASE; 10190 } 10191 10192 static bool is_kfunc_trusted_args(struct bpf_kfunc_call_arg_meta *meta) 10193 { 10194 return (meta->kfunc_flags & KF_TRUSTED_ARGS) || is_kfunc_release(meta); 10195 } 10196 10197 static bool is_kfunc_sleepable(struct bpf_kfunc_call_arg_meta *meta) 10198 { 10199 return meta->kfunc_flags & KF_SLEEPABLE; 10200 } 10201 10202 static bool is_kfunc_destructive(struct bpf_kfunc_call_arg_meta *meta) 10203 { 10204 return meta->kfunc_flags & KF_DESTRUCTIVE; 10205 } 10206 10207 static bool is_kfunc_rcu(struct bpf_kfunc_call_arg_meta *meta) 10208 { 10209 return meta->kfunc_flags & KF_RCU; 10210 } 10211 10212 static bool __kfunc_param_match_suffix(const struct btf *btf, 10213 const struct btf_param *arg, 10214 const char *suffix) 10215 { 10216 int suffix_len = strlen(suffix), len; 10217 const char *param_name; 10218 10219 /* In the future, this can be ported to use BTF tagging */ 10220 param_name = btf_name_by_offset(btf, arg->name_off); 10221 if (str_is_empty(param_name)) 10222 return false; 10223 len = strlen(param_name); 10224 if (len < suffix_len) 10225 return false; 10226 param_name += len - suffix_len; 10227 return !strncmp(param_name, suffix, suffix_len); 10228 } 10229 10230 static bool is_kfunc_arg_mem_size(const struct btf *btf, 10231 const struct btf_param *arg, 10232 const struct bpf_reg_state *reg) 10233 { 10234 const struct btf_type *t; 10235 10236 t = btf_type_skip_modifiers(btf, arg->type, NULL); 10237 if (!btf_type_is_scalar(t) || reg->type != SCALAR_VALUE) 10238 return false; 10239 10240 return __kfunc_param_match_suffix(btf, arg, "__sz"); 10241 } 10242 10243 static bool is_kfunc_arg_const_mem_size(const struct btf *btf, 10244 const struct btf_param *arg, 10245 const struct bpf_reg_state *reg) 10246 { 10247 const struct btf_type *t; 10248 10249 t = btf_type_skip_modifiers(btf, arg->type, NULL); 10250 if (!btf_type_is_scalar(t) || reg->type != SCALAR_VALUE) 10251 return false; 10252 10253 return __kfunc_param_match_suffix(btf, arg, "__szk"); 10254 } 10255 10256 static bool is_kfunc_arg_optional(const struct btf *btf, const struct btf_param *arg) 10257 { 10258 return __kfunc_param_match_suffix(btf, arg, "__opt"); 10259 } 10260 10261 static bool is_kfunc_arg_constant(const struct btf *btf, const struct btf_param *arg) 10262 { 10263 return __kfunc_param_match_suffix(btf, arg, "__k"); 10264 } 10265 10266 static bool is_kfunc_arg_ignore(const struct btf *btf, const struct btf_param *arg) 10267 { 10268 return __kfunc_param_match_suffix(btf, arg, "__ign"); 10269 } 10270 10271 static bool is_kfunc_arg_alloc_obj(const struct btf *btf, const struct btf_param *arg) 10272 { 10273 return __kfunc_param_match_suffix(btf, arg, "__alloc"); 10274 } 10275 10276 static bool is_kfunc_arg_uninit(const struct btf *btf, const struct btf_param *arg) 10277 { 10278 return __kfunc_param_match_suffix(btf, arg, "__uninit"); 10279 } 10280 10281 static bool is_kfunc_arg_refcounted_kptr(const struct btf *btf, const struct btf_param *arg) 10282 { 10283 return __kfunc_param_match_suffix(btf, arg, "__refcounted_kptr"); 10284 } 10285 10286 static bool is_kfunc_arg_scalar_with_name(const struct btf *btf, 10287 const struct btf_param *arg, 10288 const char *name) 10289 { 10290 int len, target_len = strlen(name); 10291 const char *param_name; 10292 10293 param_name = btf_name_by_offset(btf, arg->name_off); 10294 if (str_is_empty(param_name)) 10295 return false; 10296 len = strlen(param_name); 10297 if (len != target_len) 10298 return false; 10299 if (strcmp(param_name, name)) 10300 return false; 10301 10302 return true; 10303 } 10304 10305 enum { 10306 KF_ARG_DYNPTR_ID, 10307 KF_ARG_LIST_HEAD_ID, 10308 KF_ARG_LIST_NODE_ID, 10309 KF_ARG_RB_ROOT_ID, 10310 KF_ARG_RB_NODE_ID, 10311 }; 10312 10313 BTF_ID_LIST(kf_arg_btf_ids) 10314 BTF_ID(struct, bpf_dynptr_kern) 10315 BTF_ID(struct, bpf_list_head) 10316 BTF_ID(struct, bpf_list_node) 10317 BTF_ID(struct, bpf_rb_root) 10318 BTF_ID(struct, bpf_rb_node) 10319 10320 static bool __is_kfunc_ptr_arg_type(const struct btf *btf, 10321 const struct btf_param *arg, int type) 10322 { 10323 const struct btf_type *t; 10324 u32 res_id; 10325 10326 t = btf_type_skip_modifiers(btf, arg->type, NULL); 10327 if (!t) 10328 return false; 10329 if (!btf_type_is_ptr(t)) 10330 return false; 10331 t = btf_type_skip_modifiers(btf, t->type, &res_id); 10332 if (!t) 10333 return false; 10334 return btf_types_are_same(btf, res_id, btf_vmlinux, kf_arg_btf_ids[type]); 10335 } 10336 10337 static bool is_kfunc_arg_dynptr(const struct btf *btf, const struct btf_param *arg) 10338 { 10339 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_DYNPTR_ID); 10340 } 10341 10342 static bool is_kfunc_arg_list_head(const struct btf *btf, const struct btf_param *arg) 10343 { 10344 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_LIST_HEAD_ID); 10345 } 10346 10347 static bool is_kfunc_arg_list_node(const struct btf *btf, const struct btf_param *arg) 10348 { 10349 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_LIST_NODE_ID); 10350 } 10351 10352 static bool is_kfunc_arg_rbtree_root(const struct btf *btf, const struct btf_param *arg) 10353 { 10354 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_RB_ROOT_ID); 10355 } 10356 10357 static bool is_kfunc_arg_rbtree_node(const struct btf *btf, const struct btf_param *arg) 10358 { 10359 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_RB_NODE_ID); 10360 } 10361 10362 static bool is_kfunc_arg_callback(struct bpf_verifier_env *env, const struct btf *btf, 10363 const struct btf_param *arg) 10364 { 10365 const struct btf_type *t; 10366 10367 t = btf_type_resolve_func_ptr(btf, arg->type, NULL); 10368 if (!t) 10369 return false; 10370 10371 return true; 10372 } 10373 10374 /* Returns true if struct is composed of scalars, 4 levels of nesting allowed */ 10375 static bool __btf_type_is_scalar_struct(struct bpf_verifier_env *env, 10376 const struct btf *btf, 10377 const struct btf_type *t, int rec) 10378 { 10379 const struct btf_type *member_type; 10380 const struct btf_member *member; 10381 u32 i; 10382 10383 if (!btf_type_is_struct(t)) 10384 return false; 10385 10386 for_each_member(i, t, member) { 10387 const struct btf_array *array; 10388 10389 member_type = btf_type_skip_modifiers(btf, member->type, NULL); 10390 if (btf_type_is_struct(member_type)) { 10391 if (rec >= 3) { 10392 verbose(env, "max struct nesting depth exceeded\n"); 10393 return false; 10394 } 10395 if (!__btf_type_is_scalar_struct(env, btf, member_type, rec + 1)) 10396 return false; 10397 continue; 10398 } 10399 if (btf_type_is_array(member_type)) { 10400 array = btf_array(member_type); 10401 if (!array->nelems) 10402 return false; 10403 member_type = btf_type_skip_modifiers(btf, array->type, NULL); 10404 if (!btf_type_is_scalar(member_type)) 10405 return false; 10406 continue; 10407 } 10408 if (!btf_type_is_scalar(member_type)) 10409 return false; 10410 } 10411 return true; 10412 } 10413 10414 enum kfunc_ptr_arg_type { 10415 KF_ARG_PTR_TO_CTX, 10416 KF_ARG_PTR_TO_ALLOC_BTF_ID, /* Allocated object */ 10417 KF_ARG_PTR_TO_REFCOUNTED_KPTR, /* Refcounted local kptr */ 10418 KF_ARG_PTR_TO_DYNPTR, 10419 KF_ARG_PTR_TO_ITER, 10420 KF_ARG_PTR_TO_LIST_HEAD, 10421 KF_ARG_PTR_TO_LIST_NODE, 10422 KF_ARG_PTR_TO_BTF_ID, /* Also covers reg2btf_ids conversions */ 10423 KF_ARG_PTR_TO_MEM, 10424 KF_ARG_PTR_TO_MEM_SIZE, /* Size derived from next argument, skip it */ 10425 KF_ARG_PTR_TO_CALLBACK, 10426 KF_ARG_PTR_TO_RB_ROOT, 10427 KF_ARG_PTR_TO_RB_NODE, 10428 }; 10429 10430 enum special_kfunc_type { 10431 KF_bpf_obj_new_impl, 10432 KF_bpf_obj_drop_impl, 10433 KF_bpf_refcount_acquire_impl, 10434 KF_bpf_list_push_front_impl, 10435 KF_bpf_list_push_back_impl, 10436 KF_bpf_list_pop_front, 10437 KF_bpf_list_pop_back, 10438 KF_bpf_cast_to_kern_ctx, 10439 KF_bpf_rdonly_cast, 10440 KF_bpf_rcu_read_lock, 10441 KF_bpf_rcu_read_unlock, 10442 KF_bpf_rbtree_remove, 10443 KF_bpf_rbtree_add_impl, 10444 KF_bpf_rbtree_first, 10445 KF_bpf_dynptr_from_skb, 10446 KF_bpf_dynptr_from_xdp, 10447 KF_bpf_dynptr_slice, 10448 KF_bpf_dynptr_slice_rdwr, 10449 KF_bpf_dynptr_clone, 10450 KF_bpf_percpu_obj_new_impl, 10451 KF_bpf_percpu_obj_drop_impl, 10452 KF_bpf_throw, 10453 }; 10454 10455 BTF_SET_START(special_kfunc_set) 10456 BTF_ID(func, bpf_obj_new_impl) 10457 BTF_ID(func, bpf_obj_drop_impl) 10458 BTF_ID(func, bpf_refcount_acquire_impl) 10459 BTF_ID(func, bpf_list_push_front_impl) 10460 BTF_ID(func, bpf_list_push_back_impl) 10461 BTF_ID(func, bpf_list_pop_front) 10462 BTF_ID(func, bpf_list_pop_back) 10463 BTF_ID(func, bpf_cast_to_kern_ctx) 10464 BTF_ID(func, bpf_rdonly_cast) 10465 BTF_ID(func, bpf_rbtree_remove) 10466 BTF_ID(func, bpf_rbtree_add_impl) 10467 BTF_ID(func, bpf_rbtree_first) 10468 BTF_ID(func, bpf_dynptr_from_skb) 10469 BTF_ID(func, bpf_dynptr_from_xdp) 10470 BTF_ID(func, bpf_dynptr_slice) 10471 BTF_ID(func, bpf_dynptr_slice_rdwr) 10472 BTF_ID(func, bpf_dynptr_clone) 10473 BTF_ID(func, bpf_percpu_obj_new_impl) 10474 BTF_ID(func, bpf_percpu_obj_drop_impl) 10475 BTF_ID(func, bpf_throw) 10476 BTF_SET_END(special_kfunc_set) 10477 10478 BTF_ID_LIST(special_kfunc_list) 10479 BTF_ID(func, bpf_obj_new_impl) 10480 BTF_ID(func, bpf_obj_drop_impl) 10481 BTF_ID(func, bpf_refcount_acquire_impl) 10482 BTF_ID(func, bpf_list_push_front_impl) 10483 BTF_ID(func, bpf_list_push_back_impl) 10484 BTF_ID(func, bpf_list_pop_front) 10485 BTF_ID(func, bpf_list_pop_back) 10486 BTF_ID(func, bpf_cast_to_kern_ctx) 10487 BTF_ID(func, bpf_rdonly_cast) 10488 BTF_ID(func, bpf_rcu_read_lock) 10489 BTF_ID(func, bpf_rcu_read_unlock) 10490 BTF_ID(func, bpf_rbtree_remove) 10491 BTF_ID(func, bpf_rbtree_add_impl) 10492 BTF_ID(func, bpf_rbtree_first) 10493 BTF_ID(func, bpf_dynptr_from_skb) 10494 BTF_ID(func, bpf_dynptr_from_xdp) 10495 BTF_ID(func, bpf_dynptr_slice) 10496 BTF_ID(func, bpf_dynptr_slice_rdwr) 10497 BTF_ID(func, bpf_dynptr_clone) 10498 BTF_ID(func, bpf_percpu_obj_new_impl) 10499 BTF_ID(func, bpf_percpu_obj_drop_impl) 10500 BTF_ID(func, bpf_throw) 10501 10502 static bool is_kfunc_ret_null(struct bpf_kfunc_call_arg_meta *meta) 10503 { 10504 if (meta->func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl] && 10505 meta->arg_owning_ref) { 10506 return false; 10507 } 10508 10509 return meta->kfunc_flags & KF_RET_NULL; 10510 } 10511 10512 static bool is_kfunc_bpf_rcu_read_lock(struct bpf_kfunc_call_arg_meta *meta) 10513 { 10514 return meta->func_id == special_kfunc_list[KF_bpf_rcu_read_lock]; 10515 } 10516 10517 static bool is_kfunc_bpf_rcu_read_unlock(struct bpf_kfunc_call_arg_meta *meta) 10518 { 10519 return meta->func_id == special_kfunc_list[KF_bpf_rcu_read_unlock]; 10520 } 10521 10522 static enum kfunc_ptr_arg_type 10523 get_kfunc_ptr_arg_type(struct bpf_verifier_env *env, 10524 struct bpf_kfunc_call_arg_meta *meta, 10525 const struct btf_type *t, const struct btf_type *ref_t, 10526 const char *ref_tname, const struct btf_param *args, 10527 int argno, int nargs) 10528 { 10529 u32 regno = argno + 1; 10530 struct bpf_reg_state *regs = cur_regs(env); 10531 struct bpf_reg_state *reg = ®s[regno]; 10532 bool arg_mem_size = false; 10533 10534 if (meta->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx]) 10535 return KF_ARG_PTR_TO_CTX; 10536 10537 /* In this function, we verify the kfunc's BTF as per the argument type, 10538 * leaving the rest of the verification with respect to the register 10539 * type to our caller. When a set of conditions hold in the BTF type of 10540 * arguments, we resolve it to a known kfunc_ptr_arg_type. 10541 */ 10542 if (btf_get_prog_ctx_type(&env->log, meta->btf, t, resolve_prog_type(env->prog), argno)) 10543 return KF_ARG_PTR_TO_CTX; 10544 10545 if (is_kfunc_arg_alloc_obj(meta->btf, &args[argno])) 10546 return KF_ARG_PTR_TO_ALLOC_BTF_ID; 10547 10548 if (is_kfunc_arg_refcounted_kptr(meta->btf, &args[argno])) 10549 return KF_ARG_PTR_TO_REFCOUNTED_KPTR; 10550 10551 if (is_kfunc_arg_dynptr(meta->btf, &args[argno])) 10552 return KF_ARG_PTR_TO_DYNPTR; 10553 10554 if (is_kfunc_arg_iter(meta, argno)) 10555 return KF_ARG_PTR_TO_ITER; 10556 10557 if (is_kfunc_arg_list_head(meta->btf, &args[argno])) 10558 return KF_ARG_PTR_TO_LIST_HEAD; 10559 10560 if (is_kfunc_arg_list_node(meta->btf, &args[argno])) 10561 return KF_ARG_PTR_TO_LIST_NODE; 10562 10563 if (is_kfunc_arg_rbtree_root(meta->btf, &args[argno])) 10564 return KF_ARG_PTR_TO_RB_ROOT; 10565 10566 if (is_kfunc_arg_rbtree_node(meta->btf, &args[argno])) 10567 return KF_ARG_PTR_TO_RB_NODE; 10568 10569 if ((base_type(reg->type) == PTR_TO_BTF_ID || reg2btf_ids[base_type(reg->type)])) { 10570 if (!btf_type_is_struct(ref_t)) { 10571 verbose(env, "kernel function %s args#%d pointer type %s %s is not supported\n", 10572 meta->func_name, argno, btf_type_str(ref_t), ref_tname); 10573 return -EINVAL; 10574 } 10575 return KF_ARG_PTR_TO_BTF_ID; 10576 } 10577 10578 if (is_kfunc_arg_callback(env, meta->btf, &args[argno])) 10579 return KF_ARG_PTR_TO_CALLBACK; 10580 10581 10582 if (argno + 1 < nargs && 10583 (is_kfunc_arg_mem_size(meta->btf, &args[argno + 1], ®s[regno + 1]) || 10584 is_kfunc_arg_const_mem_size(meta->btf, &args[argno + 1], ®s[regno + 1]))) 10585 arg_mem_size = true; 10586 10587 /* This is the catch all argument type of register types supported by 10588 * check_helper_mem_access. However, we only allow when argument type is 10589 * pointer to scalar, or struct composed (recursively) of scalars. When 10590 * arg_mem_size is true, the pointer can be void *. 10591 */ 10592 if (!btf_type_is_scalar(ref_t) && !__btf_type_is_scalar_struct(env, meta->btf, ref_t, 0) && 10593 (arg_mem_size ? !btf_type_is_void(ref_t) : 1)) { 10594 verbose(env, "arg#%d pointer type %s %s must point to %sscalar, or struct with scalar\n", 10595 argno, btf_type_str(ref_t), ref_tname, arg_mem_size ? "void, " : ""); 10596 return -EINVAL; 10597 } 10598 return arg_mem_size ? KF_ARG_PTR_TO_MEM_SIZE : KF_ARG_PTR_TO_MEM; 10599 } 10600 10601 static int process_kf_arg_ptr_to_btf_id(struct bpf_verifier_env *env, 10602 struct bpf_reg_state *reg, 10603 const struct btf_type *ref_t, 10604 const char *ref_tname, u32 ref_id, 10605 struct bpf_kfunc_call_arg_meta *meta, 10606 int argno) 10607 { 10608 const struct btf_type *reg_ref_t; 10609 bool strict_type_match = false; 10610 const struct btf *reg_btf; 10611 const char *reg_ref_tname; 10612 u32 reg_ref_id; 10613 10614 if (base_type(reg->type) == PTR_TO_BTF_ID) { 10615 reg_btf = reg->btf; 10616 reg_ref_id = reg->btf_id; 10617 } else { 10618 reg_btf = btf_vmlinux; 10619 reg_ref_id = *reg2btf_ids[base_type(reg->type)]; 10620 } 10621 10622 /* Enforce strict type matching for calls to kfuncs that are acquiring 10623 * or releasing a reference, or are no-cast aliases. We do _not_ 10624 * enforce strict matching for plain KF_TRUSTED_ARGS kfuncs by default, 10625 * as we want to enable BPF programs to pass types that are bitwise 10626 * equivalent without forcing them to explicitly cast with something 10627 * like bpf_cast_to_kern_ctx(). 10628 * 10629 * For example, say we had a type like the following: 10630 * 10631 * struct bpf_cpumask { 10632 * cpumask_t cpumask; 10633 * refcount_t usage; 10634 * }; 10635 * 10636 * Note that as specified in <linux/cpumask.h>, cpumask_t is typedef'ed 10637 * to a struct cpumask, so it would be safe to pass a struct 10638 * bpf_cpumask * to a kfunc expecting a struct cpumask *. 10639 * 10640 * The philosophy here is similar to how we allow scalars of different 10641 * types to be passed to kfuncs as long as the size is the same. The 10642 * only difference here is that we're simply allowing 10643 * btf_struct_ids_match() to walk the struct at the 0th offset, and 10644 * resolve types. 10645 */ 10646 if (is_kfunc_acquire(meta) || 10647 (is_kfunc_release(meta) && reg->ref_obj_id) || 10648 btf_type_ids_nocast_alias(&env->log, reg_btf, reg_ref_id, meta->btf, ref_id)) 10649 strict_type_match = true; 10650 10651 WARN_ON_ONCE(is_kfunc_trusted_args(meta) && reg->off); 10652 10653 reg_ref_t = btf_type_skip_modifiers(reg_btf, reg_ref_id, ®_ref_id); 10654 reg_ref_tname = btf_name_by_offset(reg_btf, reg_ref_t->name_off); 10655 if (!btf_struct_ids_match(&env->log, reg_btf, reg_ref_id, reg->off, meta->btf, ref_id, strict_type_match)) { 10656 verbose(env, "kernel function %s args#%d expected pointer to %s %s but R%d has a pointer to %s %s\n", 10657 meta->func_name, argno, btf_type_str(ref_t), ref_tname, argno + 1, 10658 btf_type_str(reg_ref_t), reg_ref_tname); 10659 return -EINVAL; 10660 } 10661 return 0; 10662 } 10663 10664 static int ref_set_non_owning(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 10665 { 10666 struct bpf_verifier_state *state = env->cur_state; 10667 struct btf_record *rec = reg_btf_record(reg); 10668 10669 if (!state->active_lock.ptr) { 10670 verbose(env, "verifier internal error: ref_set_non_owning w/o active lock\n"); 10671 return -EFAULT; 10672 } 10673 10674 if (type_flag(reg->type) & NON_OWN_REF) { 10675 verbose(env, "verifier internal error: NON_OWN_REF already set\n"); 10676 return -EFAULT; 10677 } 10678 10679 reg->type |= NON_OWN_REF; 10680 if (rec->refcount_off >= 0) 10681 reg->type |= MEM_RCU; 10682 10683 return 0; 10684 } 10685 10686 static int ref_convert_owning_non_owning(struct bpf_verifier_env *env, u32 ref_obj_id) 10687 { 10688 struct bpf_func_state *state, *unused; 10689 struct bpf_reg_state *reg; 10690 int i; 10691 10692 state = cur_func(env); 10693 10694 if (!ref_obj_id) { 10695 verbose(env, "verifier internal error: ref_obj_id is zero for " 10696 "owning -> non-owning conversion\n"); 10697 return -EFAULT; 10698 } 10699 10700 for (i = 0; i < state->acquired_refs; i++) { 10701 if (state->refs[i].id != ref_obj_id) 10702 continue; 10703 10704 /* Clear ref_obj_id here so release_reference doesn't clobber 10705 * the whole reg 10706 */ 10707 bpf_for_each_reg_in_vstate(env->cur_state, unused, reg, ({ 10708 if (reg->ref_obj_id == ref_obj_id) { 10709 reg->ref_obj_id = 0; 10710 ref_set_non_owning(env, reg); 10711 } 10712 })); 10713 return 0; 10714 } 10715 10716 verbose(env, "verifier internal error: ref state missing for ref_obj_id\n"); 10717 return -EFAULT; 10718 } 10719 10720 /* Implementation details: 10721 * 10722 * Each register points to some region of memory, which we define as an 10723 * allocation. Each allocation may embed a bpf_spin_lock which protects any 10724 * special BPF objects (bpf_list_head, bpf_rb_root, etc.) part of the same 10725 * allocation. The lock and the data it protects are colocated in the same 10726 * memory region. 10727 * 10728 * Hence, everytime a register holds a pointer value pointing to such 10729 * allocation, the verifier preserves a unique reg->id for it. 10730 * 10731 * The verifier remembers the lock 'ptr' and the lock 'id' whenever 10732 * bpf_spin_lock is called. 10733 * 10734 * To enable this, lock state in the verifier captures two values: 10735 * active_lock.ptr = Register's type specific pointer 10736 * active_lock.id = A unique ID for each register pointer value 10737 * 10738 * Currently, PTR_TO_MAP_VALUE and PTR_TO_BTF_ID | MEM_ALLOC are the two 10739 * supported register types. 10740 * 10741 * The active_lock.ptr in case of map values is the reg->map_ptr, and in case of 10742 * allocated objects is the reg->btf pointer. 10743 * 10744 * The active_lock.id is non-unique for maps supporting direct_value_addr, as we 10745 * can establish the provenance of the map value statically for each distinct 10746 * lookup into such maps. They always contain a single map value hence unique 10747 * IDs for each pseudo load pessimizes the algorithm and rejects valid programs. 10748 * 10749 * So, in case of global variables, they use array maps with max_entries = 1, 10750 * hence their active_lock.ptr becomes map_ptr and id = 0 (since they all point 10751 * into the same map value as max_entries is 1, as described above). 10752 * 10753 * In case of inner map lookups, the inner map pointer has same map_ptr as the 10754 * outer map pointer (in verifier context), but each lookup into an inner map 10755 * assigns a fresh reg->id to the lookup, so while lookups into distinct inner 10756 * maps from the same outer map share the same map_ptr as active_lock.ptr, they 10757 * will get different reg->id assigned to each lookup, hence different 10758 * active_lock.id. 10759 * 10760 * In case of allocated objects, active_lock.ptr is the reg->btf, and the 10761 * reg->id is a unique ID preserved after the NULL pointer check on the pointer 10762 * returned from bpf_obj_new. Each allocation receives a new reg->id. 10763 */ 10764 static int check_reg_allocation_locked(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 10765 { 10766 void *ptr; 10767 u32 id; 10768 10769 switch ((int)reg->type) { 10770 case PTR_TO_MAP_VALUE: 10771 ptr = reg->map_ptr; 10772 break; 10773 case PTR_TO_BTF_ID | MEM_ALLOC: 10774 ptr = reg->btf; 10775 break; 10776 default: 10777 verbose(env, "verifier internal error: unknown reg type for lock check\n"); 10778 return -EFAULT; 10779 } 10780 id = reg->id; 10781 10782 if (!env->cur_state->active_lock.ptr) 10783 return -EINVAL; 10784 if (env->cur_state->active_lock.ptr != ptr || 10785 env->cur_state->active_lock.id != id) { 10786 verbose(env, "held lock and object are not in the same allocation\n"); 10787 return -EINVAL; 10788 } 10789 return 0; 10790 } 10791 10792 static bool is_bpf_list_api_kfunc(u32 btf_id) 10793 { 10794 return btf_id == special_kfunc_list[KF_bpf_list_push_front_impl] || 10795 btf_id == special_kfunc_list[KF_bpf_list_push_back_impl] || 10796 btf_id == special_kfunc_list[KF_bpf_list_pop_front] || 10797 btf_id == special_kfunc_list[KF_bpf_list_pop_back]; 10798 } 10799 10800 static bool is_bpf_rbtree_api_kfunc(u32 btf_id) 10801 { 10802 return btf_id == special_kfunc_list[KF_bpf_rbtree_add_impl] || 10803 btf_id == special_kfunc_list[KF_bpf_rbtree_remove] || 10804 btf_id == special_kfunc_list[KF_bpf_rbtree_first]; 10805 } 10806 10807 static bool is_bpf_graph_api_kfunc(u32 btf_id) 10808 { 10809 return is_bpf_list_api_kfunc(btf_id) || is_bpf_rbtree_api_kfunc(btf_id) || 10810 btf_id == special_kfunc_list[KF_bpf_refcount_acquire_impl]; 10811 } 10812 10813 static bool is_callback_calling_kfunc(u32 btf_id) 10814 { 10815 return btf_id == special_kfunc_list[KF_bpf_rbtree_add_impl]; 10816 } 10817 10818 static bool is_bpf_throw_kfunc(struct bpf_insn *insn) 10819 { 10820 return bpf_pseudo_kfunc_call(insn) && insn->off == 0 && 10821 insn->imm == special_kfunc_list[KF_bpf_throw]; 10822 } 10823 10824 static bool is_rbtree_lock_required_kfunc(u32 btf_id) 10825 { 10826 return is_bpf_rbtree_api_kfunc(btf_id); 10827 } 10828 10829 static bool check_kfunc_is_graph_root_api(struct bpf_verifier_env *env, 10830 enum btf_field_type head_field_type, 10831 u32 kfunc_btf_id) 10832 { 10833 bool ret; 10834 10835 switch (head_field_type) { 10836 case BPF_LIST_HEAD: 10837 ret = is_bpf_list_api_kfunc(kfunc_btf_id); 10838 break; 10839 case BPF_RB_ROOT: 10840 ret = is_bpf_rbtree_api_kfunc(kfunc_btf_id); 10841 break; 10842 default: 10843 verbose(env, "verifier internal error: unexpected graph root argument type %s\n", 10844 btf_field_type_name(head_field_type)); 10845 return false; 10846 } 10847 10848 if (!ret) 10849 verbose(env, "verifier internal error: %s head arg for unknown kfunc\n", 10850 btf_field_type_name(head_field_type)); 10851 return ret; 10852 } 10853 10854 static bool check_kfunc_is_graph_node_api(struct bpf_verifier_env *env, 10855 enum btf_field_type node_field_type, 10856 u32 kfunc_btf_id) 10857 { 10858 bool ret; 10859 10860 switch (node_field_type) { 10861 case BPF_LIST_NODE: 10862 ret = (kfunc_btf_id == special_kfunc_list[KF_bpf_list_push_front_impl] || 10863 kfunc_btf_id == special_kfunc_list[KF_bpf_list_push_back_impl]); 10864 break; 10865 case BPF_RB_NODE: 10866 ret = (kfunc_btf_id == special_kfunc_list[KF_bpf_rbtree_remove] || 10867 kfunc_btf_id == special_kfunc_list[KF_bpf_rbtree_add_impl]); 10868 break; 10869 default: 10870 verbose(env, "verifier internal error: unexpected graph node argument type %s\n", 10871 btf_field_type_name(node_field_type)); 10872 return false; 10873 } 10874 10875 if (!ret) 10876 verbose(env, "verifier internal error: %s node arg for unknown kfunc\n", 10877 btf_field_type_name(node_field_type)); 10878 return ret; 10879 } 10880 10881 static int 10882 __process_kf_arg_ptr_to_graph_root(struct bpf_verifier_env *env, 10883 struct bpf_reg_state *reg, u32 regno, 10884 struct bpf_kfunc_call_arg_meta *meta, 10885 enum btf_field_type head_field_type, 10886 struct btf_field **head_field) 10887 { 10888 const char *head_type_name; 10889 struct btf_field *field; 10890 struct btf_record *rec; 10891 u32 head_off; 10892 10893 if (meta->btf != btf_vmlinux) { 10894 verbose(env, "verifier internal error: unexpected btf mismatch in kfunc call\n"); 10895 return -EFAULT; 10896 } 10897 10898 if (!check_kfunc_is_graph_root_api(env, head_field_type, meta->func_id)) 10899 return -EFAULT; 10900 10901 head_type_name = btf_field_type_name(head_field_type); 10902 if (!tnum_is_const(reg->var_off)) { 10903 verbose(env, 10904 "R%d doesn't have constant offset. %s has to be at the constant offset\n", 10905 regno, head_type_name); 10906 return -EINVAL; 10907 } 10908 10909 rec = reg_btf_record(reg); 10910 head_off = reg->off + reg->var_off.value; 10911 field = btf_record_find(rec, head_off, head_field_type); 10912 if (!field) { 10913 verbose(env, "%s not found at offset=%u\n", head_type_name, head_off); 10914 return -EINVAL; 10915 } 10916 10917 /* All functions require bpf_list_head to be protected using a bpf_spin_lock */ 10918 if (check_reg_allocation_locked(env, reg)) { 10919 verbose(env, "bpf_spin_lock at off=%d must be held for %s\n", 10920 rec->spin_lock_off, head_type_name); 10921 return -EINVAL; 10922 } 10923 10924 if (*head_field) { 10925 verbose(env, "verifier internal error: repeating %s arg\n", head_type_name); 10926 return -EFAULT; 10927 } 10928 *head_field = field; 10929 return 0; 10930 } 10931 10932 static int process_kf_arg_ptr_to_list_head(struct bpf_verifier_env *env, 10933 struct bpf_reg_state *reg, u32 regno, 10934 struct bpf_kfunc_call_arg_meta *meta) 10935 { 10936 return __process_kf_arg_ptr_to_graph_root(env, reg, regno, meta, BPF_LIST_HEAD, 10937 &meta->arg_list_head.field); 10938 } 10939 10940 static int process_kf_arg_ptr_to_rbtree_root(struct bpf_verifier_env *env, 10941 struct bpf_reg_state *reg, u32 regno, 10942 struct bpf_kfunc_call_arg_meta *meta) 10943 { 10944 return __process_kf_arg_ptr_to_graph_root(env, reg, regno, meta, BPF_RB_ROOT, 10945 &meta->arg_rbtree_root.field); 10946 } 10947 10948 static int 10949 __process_kf_arg_ptr_to_graph_node(struct bpf_verifier_env *env, 10950 struct bpf_reg_state *reg, u32 regno, 10951 struct bpf_kfunc_call_arg_meta *meta, 10952 enum btf_field_type head_field_type, 10953 enum btf_field_type node_field_type, 10954 struct btf_field **node_field) 10955 { 10956 const char *node_type_name; 10957 const struct btf_type *et, *t; 10958 struct btf_field *field; 10959 u32 node_off; 10960 10961 if (meta->btf != btf_vmlinux) { 10962 verbose(env, "verifier internal error: unexpected btf mismatch in kfunc call\n"); 10963 return -EFAULT; 10964 } 10965 10966 if (!check_kfunc_is_graph_node_api(env, node_field_type, meta->func_id)) 10967 return -EFAULT; 10968 10969 node_type_name = btf_field_type_name(node_field_type); 10970 if (!tnum_is_const(reg->var_off)) { 10971 verbose(env, 10972 "R%d doesn't have constant offset. %s has to be at the constant offset\n", 10973 regno, node_type_name); 10974 return -EINVAL; 10975 } 10976 10977 node_off = reg->off + reg->var_off.value; 10978 field = reg_find_field_offset(reg, node_off, node_field_type); 10979 if (!field || field->offset != node_off) { 10980 verbose(env, "%s not found at offset=%u\n", node_type_name, node_off); 10981 return -EINVAL; 10982 } 10983 10984 field = *node_field; 10985 10986 et = btf_type_by_id(field->graph_root.btf, field->graph_root.value_btf_id); 10987 t = btf_type_by_id(reg->btf, reg->btf_id); 10988 if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, 0, field->graph_root.btf, 10989 field->graph_root.value_btf_id, true)) { 10990 verbose(env, "operation on %s expects arg#1 %s at offset=%d " 10991 "in struct %s, but arg is at offset=%d in struct %s\n", 10992 btf_field_type_name(head_field_type), 10993 btf_field_type_name(node_field_type), 10994 field->graph_root.node_offset, 10995 btf_name_by_offset(field->graph_root.btf, et->name_off), 10996 node_off, btf_name_by_offset(reg->btf, t->name_off)); 10997 return -EINVAL; 10998 } 10999 meta->arg_btf = reg->btf; 11000 meta->arg_btf_id = reg->btf_id; 11001 11002 if (node_off != field->graph_root.node_offset) { 11003 verbose(env, "arg#1 offset=%d, but expected %s at offset=%d in struct %s\n", 11004 node_off, btf_field_type_name(node_field_type), 11005 field->graph_root.node_offset, 11006 btf_name_by_offset(field->graph_root.btf, et->name_off)); 11007 return -EINVAL; 11008 } 11009 11010 return 0; 11011 } 11012 11013 static int process_kf_arg_ptr_to_list_node(struct bpf_verifier_env *env, 11014 struct bpf_reg_state *reg, u32 regno, 11015 struct bpf_kfunc_call_arg_meta *meta) 11016 { 11017 return __process_kf_arg_ptr_to_graph_node(env, reg, regno, meta, 11018 BPF_LIST_HEAD, BPF_LIST_NODE, 11019 &meta->arg_list_head.field); 11020 } 11021 11022 static int process_kf_arg_ptr_to_rbtree_node(struct bpf_verifier_env *env, 11023 struct bpf_reg_state *reg, u32 regno, 11024 struct bpf_kfunc_call_arg_meta *meta) 11025 { 11026 return __process_kf_arg_ptr_to_graph_node(env, reg, regno, meta, 11027 BPF_RB_ROOT, BPF_RB_NODE, 11028 &meta->arg_rbtree_root.field); 11029 } 11030 11031 static int check_kfunc_args(struct bpf_verifier_env *env, struct bpf_kfunc_call_arg_meta *meta, 11032 int insn_idx) 11033 { 11034 const char *func_name = meta->func_name, *ref_tname; 11035 const struct btf *btf = meta->btf; 11036 const struct btf_param *args; 11037 struct btf_record *rec; 11038 u32 i, nargs; 11039 int ret; 11040 11041 args = (const struct btf_param *)(meta->func_proto + 1); 11042 nargs = btf_type_vlen(meta->func_proto); 11043 if (nargs > MAX_BPF_FUNC_REG_ARGS) { 11044 verbose(env, "Function %s has %d > %d args\n", func_name, nargs, 11045 MAX_BPF_FUNC_REG_ARGS); 11046 return -EINVAL; 11047 } 11048 11049 /* Check that BTF function arguments match actual types that the 11050 * verifier sees. 11051 */ 11052 for (i = 0; i < nargs; i++) { 11053 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[i + 1]; 11054 const struct btf_type *t, *ref_t, *resolve_ret; 11055 enum bpf_arg_type arg_type = ARG_DONTCARE; 11056 u32 regno = i + 1, ref_id, type_size; 11057 bool is_ret_buf_sz = false; 11058 int kf_arg_type; 11059 11060 t = btf_type_skip_modifiers(btf, args[i].type, NULL); 11061 11062 if (is_kfunc_arg_ignore(btf, &args[i])) 11063 continue; 11064 11065 if (btf_type_is_scalar(t)) { 11066 if (reg->type != SCALAR_VALUE) { 11067 verbose(env, "R%d is not a scalar\n", regno); 11068 return -EINVAL; 11069 } 11070 11071 if (is_kfunc_arg_constant(meta->btf, &args[i])) { 11072 if (meta->arg_constant.found) { 11073 verbose(env, "verifier internal error: only one constant argument permitted\n"); 11074 return -EFAULT; 11075 } 11076 if (!tnum_is_const(reg->var_off)) { 11077 verbose(env, "R%d must be a known constant\n", regno); 11078 return -EINVAL; 11079 } 11080 ret = mark_chain_precision(env, regno); 11081 if (ret < 0) 11082 return ret; 11083 meta->arg_constant.found = true; 11084 meta->arg_constant.value = reg->var_off.value; 11085 } else if (is_kfunc_arg_scalar_with_name(btf, &args[i], "rdonly_buf_size")) { 11086 meta->r0_rdonly = true; 11087 is_ret_buf_sz = true; 11088 } else if (is_kfunc_arg_scalar_with_name(btf, &args[i], "rdwr_buf_size")) { 11089 is_ret_buf_sz = true; 11090 } 11091 11092 if (is_ret_buf_sz) { 11093 if (meta->r0_size) { 11094 verbose(env, "2 or more rdonly/rdwr_buf_size parameters for kfunc"); 11095 return -EINVAL; 11096 } 11097 11098 if (!tnum_is_const(reg->var_off)) { 11099 verbose(env, "R%d is not a const\n", regno); 11100 return -EINVAL; 11101 } 11102 11103 meta->r0_size = reg->var_off.value; 11104 ret = mark_chain_precision(env, regno); 11105 if (ret) 11106 return ret; 11107 } 11108 continue; 11109 } 11110 11111 if (!btf_type_is_ptr(t)) { 11112 verbose(env, "Unrecognized arg#%d type %s\n", i, btf_type_str(t)); 11113 return -EINVAL; 11114 } 11115 11116 if ((is_kfunc_trusted_args(meta) || is_kfunc_rcu(meta)) && 11117 (register_is_null(reg) || type_may_be_null(reg->type))) { 11118 verbose(env, "Possibly NULL pointer passed to trusted arg%d\n", i); 11119 return -EACCES; 11120 } 11121 11122 if (reg->ref_obj_id) { 11123 if (is_kfunc_release(meta) && meta->ref_obj_id) { 11124 verbose(env, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n", 11125 regno, reg->ref_obj_id, 11126 meta->ref_obj_id); 11127 return -EFAULT; 11128 } 11129 meta->ref_obj_id = reg->ref_obj_id; 11130 if (is_kfunc_release(meta)) 11131 meta->release_regno = regno; 11132 } 11133 11134 ref_t = btf_type_skip_modifiers(btf, t->type, &ref_id); 11135 ref_tname = btf_name_by_offset(btf, ref_t->name_off); 11136 11137 kf_arg_type = get_kfunc_ptr_arg_type(env, meta, t, ref_t, ref_tname, args, i, nargs); 11138 if (kf_arg_type < 0) 11139 return kf_arg_type; 11140 11141 switch (kf_arg_type) { 11142 case KF_ARG_PTR_TO_ALLOC_BTF_ID: 11143 case KF_ARG_PTR_TO_BTF_ID: 11144 if (!is_kfunc_trusted_args(meta) && !is_kfunc_rcu(meta)) 11145 break; 11146 11147 if (!is_trusted_reg(reg)) { 11148 if (!is_kfunc_rcu(meta)) { 11149 verbose(env, "R%d must be referenced or trusted\n", regno); 11150 return -EINVAL; 11151 } 11152 if (!is_rcu_reg(reg)) { 11153 verbose(env, "R%d must be a rcu pointer\n", regno); 11154 return -EINVAL; 11155 } 11156 } 11157 11158 fallthrough; 11159 case KF_ARG_PTR_TO_CTX: 11160 /* Trusted arguments have the same offset checks as release arguments */ 11161 arg_type |= OBJ_RELEASE; 11162 break; 11163 case KF_ARG_PTR_TO_DYNPTR: 11164 case KF_ARG_PTR_TO_ITER: 11165 case KF_ARG_PTR_TO_LIST_HEAD: 11166 case KF_ARG_PTR_TO_LIST_NODE: 11167 case KF_ARG_PTR_TO_RB_ROOT: 11168 case KF_ARG_PTR_TO_RB_NODE: 11169 case KF_ARG_PTR_TO_MEM: 11170 case KF_ARG_PTR_TO_MEM_SIZE: 11171 case KF_ARG_PTR_TO_CALLBACK: 11172 case KF_ARG_PTR_TO_REFCOUNTED_KPTR: 11173 /* Trusted by default */ 11174 break; 11175 default: 11176 WARN_ON_ONCE(1); 11177 return -EFAULT; 11178 } 11179 11180 if (is_kfunc_release(meta) && reg->ref_obj_id) 11181 arg_type |= OBJ_RELEASE; 11182 ret = check_func_arg_reg_off(env, reg, regno, arg_type); 11183 if (ret < 0) 11184 return ret; 11185 11186 switch (kf_arg_type) { 11187 case KF_ARG_PTR_TO_CTX: 11188 if (reg->type != PTR_TO_CTX) { 11189 verbose(env, "arg#%d expected pointer to ctx, but got %s\n", i, btf_type_str(t)); 11190 return -EINVAL; 11191 } 11192 11193 if (meta->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx]) { 11194 ret = get_kern_ctx_btf_id(&env->log, resolve_prog_type(env->prog)); 11195 if (ret < 0) 11196 return -EINVAL; 11197 meta->ret_btf_id = ret; 11198 } 11199 break; 11200 case KF_ARG_PTR_TO_ALLOC_BTF_ID: 11201 if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC)) { 11202 if (meta->func_id != special_kfunc_list[KF_bpf_obj_drop_impl]) { 11203 verbose(env, "arg#%d expected for bpf_obj_drop_impl()\n", i); 11204 return -EINVAL; 11205 } 11206 } else if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC | MEM_PERCPU)) { 11207 if (meta->func_id != special_kfunc_list[KF_bpf_percpu_obj_drop_impl]) { 11208 verbose(env, "arg#%d expected for bpf_percpu_obj_drop_impl()\n", i); 11209 return -EINVAL; 11210 } 11211 } else { 11212 verbose(env, "arg#%d expected pointer to allocated object\n", i); 11213 return -EINVAL; 11214 } 11215 if (!reg->ref_obj_id) { 11216 verbose(env, "allocated object must be referenced\n"); 11217 return -EINVAL; 11218 } 11219 if (meta->btf == btf_vmlinux) { 11220 meta->arg_btf = reg->btf; 11221 meta->arg_btf_id = reg->btf_id; 11222 } 11223 break; 11224 case KF_ARG_PTR_TO_DYNPTR: 11225 { 11226 enum bpf_arg_type dynptr_arg_type = ARG_PTR_TO_DYNPTR; 11227 int clone_ref_obj_id = 0; 11228 11229 if (reg->type != PTR_TO_STACK && 11230 reg->type != CONST_PTR_TO_DYNPTR) { 11231 verbose(env, "arg#%d expected pointer to stack or dynptr_ptr\n", i); 11232 return -EINVAL; 11233 } 11234 11235 if (reg->type == CONST_PTR_TO_DYNPTR) 11236 dynptr_arg_type |= MEM_RDONLY; 11237 11238 if (is_kfunc_arg_uninit(btf, &args[i])) 11239 dynptr_arg_type |= MEM_UNINIT; 11240 11241 if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_from_skb]) { 11242 dynptr_arg_type |= DYNPTR_TYPE_SKB; 11243 } else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_from_xdp]) { 11244 dynptr_arg_type |= DYNPTR_TYPE_XDP; 11245 } else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_clone] && 11246 (dynptr_arg_type & MEM_UNINIT)) { 11247 enum bpf_dynptr_type parent_type = meta->initialized_dynptr.type; 11248 11249 if (parent_type == BPF_DYNPTR_TYPE_INVALID) { 11250 verbose(env, "verifier internal error: no dynptr type for parent of clone\n"); 11251 return -EFAULT; 11252 } 11253 11254 dynptr_arg_type |= (unsigned int)get_dynptr_type_flag(parent_type); 11255 clone_ref_obj_id = meta->initialized_dynptr.ref_obj_id; 11256 if (dynptr_type_refcounted(parent_type) && !clone_ref_obj_id) { 11257 verbose(env, "verifier internal error: missing ref obj id for parent of clone\n"); 11258 return -EFAULT; 11259 } 11260 } 11261 11262 ret = process_dynptr_func(env, regno, insn_idx, dynptr_arg_type, clone_ref_obj_id); 11263 if (ret < 0) 11264 return ret; 11265 11266 if (!(dynptr_arg_type & MEM_UNINIT)) { 11267 int id = dynptr_id(env, reg); 11268 11269 if (id < 0) { 11270 verbose(env, "verifier internal error: failed to obtain dynptr id\n"); 11271 return id; 11272 } 11273 meta->initialized_dynptr.id = id; 11274 meta->initialized_dynptr.type = dynptr_get_type(env, reg); 11275 meta->initialized_dynptr.ref_obj_id = dynptr_ref_obj_id(env, reg); 11276 } 11277 11278 break; 11279 } 11280 case KF_ARG_PTR_TO_ITER: 11281 ret = process_iter_arg(env, regno, insn_idx, meta); 11282 if (ret < 0) 11283 return ret; 11284 break; 11285 case KF_ARG_PTR_TO_LIST_HEAD: 11286 if (reg->type != PTR_TO_MAP_VALUE && 11287 reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) { 11288 verbose(env, "arg#%d expected pointer to map value or allocated object\n", i); 11289 return -EINVAL; 11290 } 11291 if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC) && !reg->ref_obj_id) { 11292 verbose(env, "allocated object must be referenced\n"); 11293 return -EINVAL; 11294 } 11295 ret = process_kf_arg_ptr_to_list_head(env, reg, regno, meta); 11296 if (ret < 0) 11297 return ret; 11298 break; 11299 case KF_ARG_PTR_TO_RB_ROOT: 11300 if (reg->type != PTR_TO_MAP_VALUE && 11301 reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) { 11302 verbose(env, "arg#%d expected pointer to map value or allocated object\n", i); 11303 return -EINVAL; 11304 } 11305 if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC) && !reg->ref_obj_id) { 11306 verbose(env, "allocated object must be referenced\n"); 11307 return -EINVAL; 11308 } 11309 ret = process_kf_arg_ptr_to_rbtree_root(env, reg, regno, meta); 11310 if (ret < 0) 11311 return ret; 11312 break; 11313 case KF_ARG_PTR_TO_LIST_NODE: 11314 if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) { 11315 verbose(env, "arg#%d expected pointer to allocated object\n", i); 11316 return -EINVAL; 11317 } 11318 if (!reg->ref_obj_id) { 11319 verbose(env, "allocated object must be referenced\n"); 11320 return -EINVAL; 11321 } 11322 ret = process_kf_arg_ptr_to_list_node(env, reg, regno, meta); 11323 if (ret < 0) 11324 return ret; 11325 break; 11326 case KF_ARG_PTR_TO_RB_NODE: 11327 if (meta->func_id == special_kfunc_list[KF_bpf_rbtree_remove]) { 11328 if (!type_is_non_owning_ref(reg->type) || reg->ref_obj_id) { 11329 verbose(env, "rbtree_remove node input must be non-owning ref\n"); 11330 return -EINVAL; 11331 } 11332 if (in_rbtree_lock_required_cb(env)) { 11333 verbose(env, "rbtree_remove not allowed in rbtree cb\n"); 11334 return -EINVAL; 11335 } 11336 } else { 11337 if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) { 11338 verbose(env, "arg#%d expected pointer to allocated object\n", i); 11339 return -EINVAL; 11340 } 11341 if (!reg->ref_obj_id) { 11342 verbose(env, "allocated object must be referenced\n"); 11343 return -EINVAL; 11344 } 11345 } 11346 11347 ret = process_kf_arg_ptr_to_rbtree_node(env, reg, regno, meta); 11348 if (ret < 0) 11349 return ret; 11350 break; 11351 case KF_ARG_PTR_TO_BTF_ID: 11352 /* Only base_type is checked, further checks are done here */ 11353 if ((base_type(reg->type) != PTR_TO_BTF_ID || 11354 (bpf_type_has_unsafe_modifiers(reg->type) && !is_rcu_reg(reg))) && 11355 !reg2btf_ids[base_type(reg->type)]) { 11356 verbose(env, "arg#%d is %s ", i, reg_type_str(env, reg->type)); 11357 verbose(env, "expected %s or socket\n", 11358 reg_type_str(env, base_type(reg->type) | 11359 (type_flag(reg->type) & BPF_REG_TRUSTED_MODIFIERS))); 11360 return -EINVAL; 11361 } 11362 ret = process_kf_arg_ptr_to_btf_id(env, reg, ref_t, ref_tname, ref_id, meta, i); 11363 if (ret < 0) 11364 return ret; 11365 break; 11366 case KF_ARG_PTR_TO_MEM: 11367 resolve_ret = btf_resolve_size(btf, ref_t, &type_size); 11368 if (IS_ERR(resolve_ret)) { 11369 verbose(env, "arg#%d reference type('%s %s') size cannot be determined: %ld\n", 11370 i, btf_type_str(ref_t), ref_tname, PTR_ERR(resolve_ret)); 11371 return -EINVAL; 11372 } 11373 ret = check_mem_reg(env, reg, regno, type_size); 11374 if (ret < 0) 11375 return ret; 11376 break; 11377 case KF_ARG_PTR_TO_MEM_SIZE: 11378 { 11379 struct bpf_reg_state *buff_reg = ®s[regno]; 11380 const struct btf_param *buff_arg = &args[i]; 11381 struct bpf_reg_state *size_reg = ®s[regno + 1]; 11382 const struct btf_param *size_arg = &args[i + 1]; 11383 11384 if (!register_is_null(buff_reg) || !is_kfunc_arg_optional(meta->btf, buff_arg)) { 11385 ret = check_kfunc_mem_size_reg(env, size_reg, regno + 1); 11386 if (ret < 0) { 11387 verbose(env, "arg#%d arg#%d memory, len pair leads to invalid memory access\n", i, i + 1); 11388 return ret; 11389 } 11390 } 11391 11392 if (is_kfunc_arg_const_mem_size(meta->btf, size_arg, size_reg)) { 11393 if (meta->arg_constant.found) { 11394 verbose(env, "verifier internal error: only one constant argument permitted\n"); 11395 return -EFAULT; 11396 } 11397 if (!tnum_is_const(size_reg->var_off)) { 11398 verbose(env, "R%d must be a known constant\n", regno + 1); 11399 return -EINVAL; 11400 } 11401 meta->arg_constant.found = true; 11402 meta->arg_constant.value = size_reg->var_off.value; 11403 } 11404 11405 /* Skip next '__sz' or '__szk' argument */ 11406 i++; 11407 break; 11408 } 11409 case KF_ARG_PTR_TO_CALLBACK: 11410 if (reg->type != PTR_TO_FUNC) { 11411 verbose(env, "arg%d expected pointer to func\n", i); 11412 return -EINVAL; 11413 } 11414 meta->subprogno = reg->subprogno; 11415 break; 11416 case KF_ARG_PTR_TO_REFCOUNTED_KPTR: 11417 if (!type_is_ptr_alloc_obj(reg->type)) { 11418 verbose(env, "arg#%d is neither owning or non-owning ref\n", i); 11419 return -EINVAL; 11420 } 11421 if (!type_is_non_owning_ref(reg->type)) 11422 meta->arg_owning_ref = true; 11423 11424 rec = reg_btf_record(reg); 11425 if (!rec) { 11426 verbose(env, "verifier internal error: Couldn't find btf_record\n"); 11427 return -EFAULT; 11428 } 11429 11430 if (rec->refcount_off < 0) { 11431 verbose(env, "arg#%d doesn't point to a type with bpf_refcount field\n", i); 11432 return -EINVAL; 11433 } 11434 11435 meta->arg_btf = reg->btf; 11436 meta->arg_btf_id = reg->btf_id; 11437 break; 11438 } 11439 } 11440 11441 if (is_kfunc_release(meta) && !meta->release_regno) { 11442 verbose(env, "release kernel function %s expects refcounted PTR_TO_BTF_ID\n", 11443 func_name); 11444 return -EINVAL; 11445 } 11446 11447 return 0; 11448 } 11449 11450 static int fetch_kfunc_meta(struct bpf_verifier_env *env, 11451 struct bpf_insn *insn, 11452 struct bpf_kfunc_call_arg_meta *meta, 11453 const char **kfunc_name) 11454 { 11455 const struct btf_type *func, *func_proto; 11456 u32 func_id, *kfunc_flags; 11457 const char *func_name; 11458 struct btf *desc_btf; 11459 11460 if (kfunc_name) 11461 *kfunc_name = NULL; 11462 11463 if (!insn->imm) 11464 return -EINVAL; 11465 11466 desc_btf = find_kfunc_desc_btf(env, insn->off); 11467 if (IS_ERR(desc_btf)) 11468 return PTR_ERR(desc_btf); 11469 11470 func_id = insn->imm; 11471 func = btf_type_by_id(desc_btf, func_id); 11472 func_name = btf_name_by_offset(desc_btf, func->name_off); 11473 if (kfunc_name) 11474 *kfunc_name = func_name; 11475 func_proto = btf_type_by_id(desc_btf, func->type); 11476 11477 kfunc_flags = btf_kfunc_id_set_contains(desc_btf, func_id, env->prog); 11478 if (!kfunc_flags) { 11479 return -EACCES; 11480 } 11481 11482 memset(meta, 0, sizeof(*meta)); 11483 meta->btf = desc_btf; 11484 meta->func_id = func_id; 11485 meta->kfunc_flags = *kfunc_flags; 11486 meta->func_proto = func_proto; 11487 meta->func_name = func_name; 11488 11489 return 0; 11490 } 11491 11492 static int check_return_code(struct bpf_verifier_env *env, int regno); 11493 11494 static int check_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn, 11495 int *insn_idx_p) 11496 { 11497 const struct btf_type *t, *ptr_type; 11498 u32 i, nargs, ptr_type_id, release_ref_obj_id; 11499 struct bpf_reg_state *regs = cur_regs(env); 11500 const char *func_name, *ptr_type_name; 11501 bool sleepable, rcu_lock, rcu_unlock; 11502 struct bpf_kfunc_call_arg_meta meta; 11503 struct bpf_insn_aux_data *insn_aux; 11504 int err, insn_idx = *insn_idx_p; 11505 const struct btf_param *args; 11506 const struct btf_type *ret_t; 11507 struct btf *desc_btf; 11508 11509 /* skip for now, but return error when we find this in fixup_kfunc_call */ 11510 if (!insn->imm) 11511 return 0; 11512 11513 err = fetch_kfunc_meta(env, insn, &meta, &func_name); 11514 if (err == -EACCES && func_name) 11515 verbose(env, "calling kernel function %s is not allowed\n", func_name); 11516 if (err) 11517 return err; 11518 desc_btf = meta.btf; 11519 insn_aux = &env->insn_aux_data[insn_idx]; 11520 11521 insn_aux->is_iter_next = is_iter_next_kfunc(&meta); 11522 11523 if (is_kfunc_destructive(&meta) && !capable(CAP_SYS_BOOT)) { 11524 verbose(env, "destructive kfunc calls require CAP_SYS_BOOT capability\n"); 11525 return -EACCES; 11526 } 11527 11528 sleepable = is_kfunc_sleepable(&meta); 11529 if (sleepable && !env->prog->aux->sleepable) { 11530 verbose(env, "program must be sleepable to call sleepable kfunc %s\n", func_name); 11531 return -EACCES; 11532 } 11533 11534 rcu_lock = is_kfunc_bpf_rcu_read_lock(&meta); 11535 rcu_unlock = is_kfunc_bpf_rcu_read_unlock(&meta); 11536 11537 if (env->cur_state->active_rcu_lock) { 11538 struct bpf_func_state *state; 11539 struct bpf_reg_state *reg; 11540 11541 if (in_rbtree_lock_required_cb(env) && (rcu_lock || rcu_unlock)) { 11542 verbose(env, "Calling bpf_rcu_read_{lock,unlock} in unnecessary rbtree callback\n"); 11543 return -EACCES; 11544 } 11545 11546 if (rcu_lock) { 11547 verbose(env, "nested rcu read lock (kernel function %s)\n", func_name); 11548 return -EINVAL; 11549 } else if (rcu_unlock) { 11550 bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({ 11551 if (reg->type & MEM_RCU) { 11552 reg->type &= ~(MEM_RCU | PTR_MAYBE_NULL); 11553 reg->type |= PTR_UNTRUSTED; 11554 } 11555 })); 11556 env->cur_state->active_rcu_lock = false; 11557 } else if (sleepable) { 11558 verbose(env, "kernel func %s is sleepable within rcu_read_lock region\n", func_name); 11559 return -EACCES; 11560 } 11561 } else if (rcu_lock) { 11562 env->cur_state->active_rcu_lock = true; 11563 } else if (rcu_unlock) { 11564 verbose(env, "unmatched rcu read unlock (kernel function %s)\n", func_name); 11565 return -EINVAL; 11566 } 11567 11568 /* Check the arguments */ 11569 err = check_kfunc_args(env, &meta, insn_idx); 11570 if (err < 0) 11571 return err; 11572 /* In case of release function, we get register number of refcounted 11573 * PTR_TO_BTF_ID in bpf_kfunc_arg_meta, do the release now. 11574 */ 11575 if (meta.release_regno) { 11576 err = release_reference(env, regs[meta.release_regno].ref_obj_id); 11577 if (err) { 11578 verbose(env, "kfunc %s#%d reference has not been acquired before\n", 11579 func_name, meta.func_id); 11580 return err; 11581 } 11582 } 11583 11584 if (meta.func_id == special_kfunc_list[KF_bpf_list_push_front_impl] || 11585 meta.func_id == special_kfunc_list[KF_bpf_list_push_back_impl] || 11586 meta.func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) { 11587 release_ref_obj_id = regs[BPF_REG_2].ref_obj_id; 11588 insn_aux->insert_off = regs[BPF_REG_2].off; 11589 insn_aux->kptr_struct_meta = btf_find_struct_meta(meta.arg_btf, meta.arg_btf_id); 11590 err = ref_convert_owning_non_owning(env, release_ref_obj_id); 11591 if (err) { 11592 verbose(env, "kfunc %s#%d conversion of owning ref to non-owning failed\n", 11593 func_name, meta.func_id); 11594 return err; 11595 } 11596 11597 err = release_reference(env, release_ref_obj_id); 11598 if (err) { 11599 verbose(env, "kfunc %s#%d reference has not been acquired before\n", 11600 func_name, meta.func_id); 11601 return err; 11602 } 11603 } 11604 11605 if (meta.func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) { 11606 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno, 11607 set_rbtree_add_callback_state); 11608 if (err) { 11609 verbose(env, "kfunc %s#%d failed callback verification\n", 11610 func_name, meta.func_id); 11611 return err; 11612 } 11613 } 11614 11615 if (meta.func_id == special_kfunc_list[KF_bpf_throw]) { 11616 if (!bpf_jit_supports_exceptions()) { 11617 verbose(env, "JIT does not support calling kfunc %s#%d\n", 11618 func_name, meta.func_id); 11619 return -ENOTSUPP; 11620 } 11621 env->seen_exception = true; 11622 11623 /* In the case of the default callback, the cookie value passed 11624 * to bpf_throw becomes the return value of the program. 11625 */ 11626 if (!env->exception_callback_subprog) { 11627 err = check_return_code(env, BPF_REG_1); 11628 if (err < 0) 11629 return err; 11630 } 11631 } 11632 11633 for (i = 0; i < CALLER_SAVED_REGS; i++) 11634 mark_reg_not_init(env, regs, caller_saved[i]); 11635 11636 /* Check return type */ 11637 t = btf_type_skip_modifiers(desc_btf, meta.func_proto->type, NULL); 11638 11639 if (is_kfunc_acquire(&meta) && !btf_type_is_struct_ptr(meta.btf, t)) { 11640 /* Only exception is bpf_obj_new_impl */ 11641 if (meta.btf != btf_vmlinux || 11642 (meta.func_id != special_kfunc_list[KF_bpf_obj_new_impl] && 11643 meta.func_id != special_kfunc_list[KF_bpf_percpu_obj_new_impl] && 11644 meta.func_id != special_kfunc_list[KF_bpf_refcount_acquire_impl])) { 11645 verbose(env, "acquire kernel function does not return PTR_TO_BTF_ID\n"); 11646 return -EINVAL; 11647 } 11648 } 11649 11650 if (btf_type_is_scalar(t)) { 11651 mark_reg_unknown(env, regs, BPF_REG_0); 11652 mark_btf_func_reg_size(env, BPF_REG_0, t->size); 11653 } else if (btf_type_is_ptr(t)) { 11654 ptr_type = btf_type_skip_modifiers(desc_btf, t->type, &ptr_type_id); 11655 11656 if (meta.btf == btf_vmlinux && btf_id_set_contains(&special_kfunc_set, meta.func_id)) { 11657 if (meta.func_id == special_kfunc_list[KF_bpf_obj_new_impl] || 11658 meta.func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl]) { 11659 struct btf_struct_meta *struct_meta; 11660 struct btf *ret_btf; 11661 u32 ret_btf_id; 11662 11663 if (meta.func_id == special_kfunc_list[KF_bpf_obj_new_impl] && !bpf_global_ma_set) 11664 return -ENOMEM; 11665 11666 if (meta.func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl] && !bpf_global_percpu_ma_set) 11667 return -ENOMEM; 11668 11669 if (((u64)(u32)meta.arg_constant.value) != meta.arg_constant.value) { 11670 verbose(env, "local type ID argument must be in range [0, U32_MAX]\n"); 11671 return -EINVAL; 11672 } 11673 11674 ret_btf = env->prog->aux->btf; 11675 ret_btf_id = meta.arg_constant.value; 11676 11677 /* This may be NULL due to user not supplying a BTF */ 11678 if (!ret_btf) { 11679 verbose(env, "bpf_obj_new/bpf_percpu_obj_new requires prog BTF\n"); 11680 return -EINVAL; 11681 } 11682 11683 ret_t = btf_type_by_id(ret_btf, ret_btf_id); 11684 if (!ret_t || !__btf_type_is_struct(ret_t)) { 11685 verbose(env, "bpf_obj_new/bpf_percpu_obj_new type ID argument must be of a struct\n"); 11686 return -EINVAL; 11687 } 11688 11689 struct_meta = btf_find_struct_meta(ret_btf, ret_btf_id); 11690 if (meta.func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl]) { 11691 if (!__btf_type_is_scalar_struct(env, ret_btf, ret_t, 0)) { 11692 verbose(env, "bpf_percpu_obj_new type ID argument must be of a struct of scalars\n"); 11693 return -EINVAL; 11694 } 11695 11696 if (struct_meta) { 11697 verbose(env, "bpf_percpu_obj_new type ID argument must not contain special fields\n"); 11698 return -EINVAL; 11699 } 11700 } 11701 11702 mark_reg_known_zero(env, regs, BPF_REG_0); 11703 regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC; 11704 regs[BPF_REG_0].btf = ret_btf; 11705 regs[BPF_REG_0].btf_id = ret_btf_id; 11706 if (meta.func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl]) 11707 regs[BPF_REG_0].type |= MEM_PERCPU; 11708 11709 insn_aux->obj_new_size = ret_t->size; 11710 insn_aux->kptr_struct_meta = struct_meta; 11711 } else if (meta.func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl]) { 11712 mark_reg_known_zero(env, regs, BPF_REG_0); 11713 regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC; 11714 regs[BPF_REG_0].btf = meta.arg_btf; 11715 regs[BPF_REG_0].btf_id = meta.arg_btf_id; 11716 11717 insn_aux->kptr_struct_meta = 11718 btf_find_struct_meta(meta.arg_btf, 11719 meta.arg_btf_id); 11720 } else if (meta.func_id == special_kfunc_list[KF_bpf_list_pop_front] || 11721 meta.func_id == special_kfunc_list[KF_bpf_list_pop_back]) { 11722 struct btf_field *field = meta.arg_list_head.field; 11723 11724 mark_reg_graph_node(regs, BPF_REG_0, &field->graph_root); 11725 } else if (meta.func_id == special_kfunc_list[KF_bpf_rbtree_remove] || 11726 meta.func_id == special_kfunc_list[KF_bpf_rbtree_first]) { 11727 struct btf_field *field = meta.arg_rbtree_root.field; 11728 11729 mark_reg_graph_node(regs, BPF_REG_0, &field->graph_root); 11730 } else if (meta.func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx]) { 11731 mark_reg_known_zero(env, regs, BPF_REG_0); 11732 regs[BPF_REG_0].type = PTR_TO_BTF_ID | PTR_TRUSTED; 11733 regs[BPF_REG_0].btf = desc_btf; 11734 regs[BPF_REG_0].btf_id = meta.ret_btf_id; 11735 } else if (meta.func_id == special_kfunc_list[KF_bpf_rdonly_cast]) { 11736 ret_t = btf_type_by_id(desc_btf, meta.arg_constant.value); 11737 if (!ret_t || !btf_type_is_struct(ret_t)) { 11738 verbose(env, 11739 "kfunc bpf_rdonly_cast type ID argument must be of a struct\n"); 11740 return -EINVAL; 11741 } 11742 11743 mark_reg_known_zero(env, regs, BPF_REG_0); 11744 regs[BPF_REG_0].type = PTR_TO_BTF_ID | PTR_UNTRUSTED; 11745 regs[BPF_REG_0].btf = desc_btf; 11746 regs[BPF_REG_0].btf_id = meta.arg_constant.value; 11747 } else if (meta.func_id == special_kfunc_list[KF_bpf_dynptr_slice] || 11748 meta.func_id == special_kfunc_list[KF_bpf_dynptr_slice_rdwr]) { 11749 enum bpf_type_flag type_flag = get_dynptr_type_flag(meta.initialized_dynptr.type); 11750 11751 mark_reg_known_zero(env, regs, BPF_REG_0); 11752 11753 if (!meta.arg_constant.found) { 11754 verbose(env, "verifier internal error: bpf_dynptr_slice(_rdwr) no constant size\n"); 11755 return -EFAULT; 11756 } 11757 11758 regs[BPF_REG_0].mem_size = meta.arg_constant.value; 11759 11760 /* PTR_MAYBE_NULL will be added when is_kfunc_ret_null is checked */ 11761 regs[BPF_REG_0].type = PTR_TO_MEM | type_flag; 11762 11763 if (meta.func_id == special_kfunc_list[KF_bpf_dynptr_slice]) { 11764 regs[BPF_REG_0].type |= MEM_RDONLY; 11765 } else { 11766 /* this will set env->seen_direct_write to true */ 11767 if (!may_access_direct_pkt_data(env, NULL, BPF_WRITE)) { 11768 verbose(env, "the prog does not allow writes to packet data\n"); 11769 return -EINVAL; 11770 } 11771 } 11772 11773 if (!meta.initialized_dynptr.id) { 11774 verbose(env, "verifier internal error: no dynptr id\n"); 11775 return -EFAULT; 11776 } 11777 regs[BPF_REG_0].dynptr_id = meta.initialized_dynptr.id; 11778 11779 /* we don't need to set BPF_REG_0's ref obj id 11780 * because packet slices are not refcounted (see 11781 * dynptr_type_refcounted) 11782 */ 11783 } else { 11784 verbose(env, "kernel function %s unhandled dynamic return type\n", 11785 meta.func_name); 11786 return -EFAULT; 11787 } 11788 } else if (!__btf_type_is_struct(ptr_type)) { 11789 if (!meta.r0_size) { 11790 __u32 sz; 11791 11792 if (!IS_ERR(btf_resolve_size(desc_btf, ptr_type, &sz))) { 11793 meta.r0_size = sz; 11794 meta.r0_rdonly = true; 11795 } 11796 } 11797 if (!meta.r0_size) { 11798 ptr_type_name = btf_name_by_offset(desc_btf, 11799 ptr_type->name_off); 11800 verbose(env, 11801 "kernel function %s returns pointer type %s %s is not supported\n", 11802 func_name, 11803 btf_type_str(ptr_type), 11804 ptr_type_name); 11805 return -EINVAL; 11806 } 11807 11808 mark_reg_known_zero(env, regs, BPF_REG_0); 11809 regs[BPF_REG_0].type = PTR_TO_MEM; 11810 regs[BPF_REG_0].mem_size = meta.r0_size; 11811 11812 if (meta.r0_rdonly) 11813 regs[BPF_REG_0].type |= MEM_RDONLY; 11814 11815 /* Ensures we don't access the memory after a release_reference() */ 11816 if (meta.ref_obj_id) 11817 regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id; 11818 } else { 11819 mark_reg_known_zero(env, regs, BPF_REG_0); 11820 regs[BPF_REG_0].btf = desc_btf; 11821 regs[BPF_REG_0].type = PTR_TO_BTF_ID; 11822 regs[BPF_REG_0].btf_id = ptr_type_id; 11823 } 11824 11825 if (is_kfunc_ret_null(&meta)) { 11826 regs[BPF_REG_0].type |= PTR_MAYBE_NULL; 11827 /* For mark_ptr_or_null_reg, see 93c230e3f5bd6 */ 11828 regs[BPF_REG_0].id = ++env->id_gen; 11829 } 11830 mark_btf_func_reg_size(env, BPF_REG_0, sizeof(void *)); 11831 if (is_kfunc_acquire(&meta)) { 11832 int id = acquire_reference_state(env, insn_idx); 11833 11834 if (id < 0) 11835 return id; 11836 if (is_kfunc_ret_null(&meta)) 11837 regs[BPF_REG_0].id = id; 11838 regs[BPF_REG_0].ref_obj_id = id; 11839 } else if (meta.func_id == special_kfunc_list[KF_bpf_rbtree_first]) { 11840 ref_set_non_owning(env, ®s[BPF_REG_0]); 11841 } 11842 11843 if (reg_may_point_to_spin_lock(®s[BPF_REG_0]) && !regs[BPF_REG_0].id) 11844 regs[BPF_REG_0].id = ++env->id_gen; 11845 } else if (btf_type_is_void(t)) { 11846 if (meta.btf == btf_vmlinux && btf_id_set_contains(&special_kfunc_set, meta.func_id)) { 11847 if (meta.func_id == special_kfunc_list[KF_bpf_obj_drop_impl] || 11848 meta.func_id == special_kfunc_list[KF_bpf_percpu_obj_drop_impl]) { 11849 insn_aux->kptr_struct_meta = 11850 btf_find_struct_meta(meta.arg_btf, 11851 meta.arg_btf_id); 11852 } 11853 } 11854 } 11855 11856 nargs = btf_type_vlen(meta.func_proto); 11857 args = (const struct btf_param *)(meta.func_proto + 1); 11858 for (i = 0; i < nargs; i++) { 11859 u32 regno = i + 1; 11860 11861 t = btf_type_skip_modifiers(desc_btf, args[i].type, NULL); 11862 if (btf_type_is_ptr(t)) 11863 mark_btf_func_reg_size(env, regno, sizeof(void *)); 11864 else 11865 /* scalar. ensured by btf_check_kfunc_arg_match() */ 11866 mark_btf_func_reg_size(env, regno, t->size); 11867 } 11868 11869 if (is_iter_next_kfunc(&meta)) { 11870 err = process_iter_next_call(env, insn_idx, &meta); 11871 if (err) 11872 return err; 11873 } 11874 11875 return 0; 11876 } 11877 11878 static bool signed_add_overflows(s64 a, s64 b) 11879 { 11880 /* Do the add in u64, where overflow is well-defined */ 11881 s64 res = (s64)((u64)a + (u64)b); 11882 11883 if (b < 0) 11884 return res > a; 11885 return res < a; 11886 } 11887 11888 static bool signed_add32_overflows(s32 a, s32 b) 11889 { 11890 /* Do the add in u32, where overflow is well-defined */ 11891 s32 res = (s32)((u32)a + (u32)b); 11892 11893 if (b < 0) 11894 return res > a; 11895 return res < a; 11896 } 11897 11898 static bool signed_sub_overflows(s64 a, s64 b) 11899 { 11900 /* Do the sub in u64, where overflow is well-defined */ 11901 s64 res = (s64)((u64)a - (u64)b); 11902 11903 if (b < 0) 11904 return res < a; 11905 return res > a; 11906 } 11907 11908 static bool signed_sub32_overflows(s32 a, s32 b) 11909 { 11910 /* Do the sub in u32, where overflow is well-defined */ 11911 s32 res = (s32)((u32)a - (u32)b); 11912 11913 if (b < 0) 11914 return res < a; 11915 return res > a; 11916 } 11917 11918 static bool check_reg_sane_offset(struct bpf_verifier_env *env, 11919 const struct bpf_reg_state *reg, 11920 enum bpf_reg_type type) 11921 { 11922 bool known = tnum_is_const(reg->var_off); 11923 s64 val = reg->var_off.value; 11924 s64 smin = reg->smin_value; 11925 11926 if (known && (val >= BPF_MAX_VAR_OFF || val <= -BPF_MAX_VAR_OFF)) { 11927 verbose(env, "math between %s pointer and %lld is not allowed\n", 11928 reg_type_str(env, type), val); 11929 return false; 11930 } 11931 11932 if (reg->off >= BPF_MAX_VAR_OFF || reg->off <= -BPF_MAX_VAR_OFF) { 11933 verbose(env, "%s pointer offset %d is not allowed\n", 11934 reg_type_str(env, type), reg->off); 11935 return false; 11936 } 11937 11938 if (smin == S64_MIN) { 11939 verbose(env, "math between %s pointer and register with unbounded min value is not allowed\n", 11940 reg_type_str(env, type)); 11941 return false; 11942 } 11943 11944 if (smin >= BPF_MAX_VAR_OFF || smin <= -BPF_MAX_VAR_OFF) { 11945 verbose(env, "value %lld makes %s pointer be out of bounds\n", 11946 smin, reg_type_str(env, type)); 11947 return false; 11948 } 11949 11950 return true; 11951 } 11952 11953 enum { 11954 REASON_BOUNDS = -1, 11955 REASON_TYPE = -2, 11956 REASON_PATHS = -3, 11957 REASON_LIMIT = -4, 11958 REASON_STACK = -5, 11959 }; 11960 11961 static int retrieve_ptr_limit(const struct bpf_reg_state *ptr_reg, 11962 u32 *alu_limit, bool mask_to_left) 11963 { 11964 u32 max = 0, ptr_limit = 0; 11965 11966 switch (ptr_reg->type) { 11967 case PTR_TO_STACK: 11968 /* Offset 0 is out-of-bounds, but acceptable start for the 11969 * left direction, see BPF_REG_FP. Also, unknown scalar 11970 * offset where we would need to deal with min/max bounds is 11971 * currently prohibited for unprivileged. 11972 */ 11973 max = MAX_BPF_STACK + mask_to_left; 11974 ptr_limit = -(ptr_reg->var_off.value + ptr_reg->off); 11975 break; 11976 case PTR_TO_MAP_VALUE: 11977 max = ptr_reg->map_ptr->value_size; 11978 ptr_limit = (mask_to_left ? 11979 ptr_reg->smin_value : 11980 ptr_reg->umax_value) + ptr_reg->off; 11981 break; 11982 default: 11983 return REASON_TYPE; 11984 } 11985 11986 if (ptr_limit >= max) 11987 return REASON_LIMIT; 11988 *alu_limit = ptr_limit; 11989 return 0; 11990 } 11991 11992 static bool can_skip_alu_sanitation(const struct bpf_verifier_env *env, 11993 const struct bpf_insn *insn) 11994 { 11995 return env->bypass_spec_v1 || BPF_SRC(insn->code) == BPF_K; 11996 } 11997 11998 static int update_alu_sanitation_state(struct bpf_insn_aux_data *aux, 11999 u32 alu_state, u32 alu_limit) 12000 { 12001 /* If we arrived here from different branches with different 12002 * state or limits to sanitize, then this won't work. 12003 */ 12004 if (aux->alu_state && 12005 (aux->alu_state != alu_state || 12006 aux->alu_limit != alu_limit)) 12007 return REASON_PATHS; 12008 12009 /* Corresponding fixup done in do_misc_fixups(). */ 12010 aux->alu_state = alu_state; 12011 aux->alu_limit = alu_limit; 12012 return 0; 12013 } 12014 12015 static int sanitize_val_alu(struct bpf_verifier_env *env, 12016 struct bpf_insn *insn) 12017 { 12018 struct bpf_insn_aux_data *aux = cur_aux(env); 12019 12020 if (can_skip_alu_sanitation(env, insn)) 12021 return 0; 12022 12023 return update_alu_sanitation_state(aux, BPF_ALU_NON_POINTER, 0); 12024 } 12025 12026 static bool sanitize_needed(u8 opcode) 12027 { 12028 return opcode == BPF_ADD || opcode == BPF_SUB; 12029 } 12030 12031 struct bpf_sanitize_info { 12032 struct bpf_insn_aux_data aux; 12033 bool mask_to_left; 12034 }; 12035 12036 static struct bpf_verifier_state * 12037 sanitize_speculative_path(struct bpf_verifier_env *env, 12038 const struct bpf_insn *insn, 12039 u32 next_idx, u32 curr_idx) 12040 { 12041 struct bpf_verifier_state *branch; 12042 struct bpf_reg_state *regs; 12043 12044 branch = push_stack(env, next_idx, curr_idx, true); 12045 if (branch && insn) { 12046 regs = branch->frame[branch->curframe]->regs; 12047 if (BPF_SRC(insn->code) == BPF_K) { 12048 mark_reg_unknown(env, regs, insn->dst_reg); 12049 } else if (BPF_SRC(insn->code) == BPF_X) { 12050 mark_reg_unknown(env, regs, insn->dst_reg); 12051 mark_reg_unknown(env, regs, insn->src_reg); 12052 } 12053 } 12054 return branch; 12055 } 12056 12057 static int sanitize_ptr_alu(struct bpf_verifier_env *env, 12058 struct bpf_insn *insn, 12059 const struct bpf_reg_state *ptr_reg, 12060 const struct bpf_reg_state *off_reg, 12061 struct bpf_reg_state *dst_reg, 12062 struct bpf_sanitize_info *info, 12063 const bool commit_window) 12064 { 12065 struct bpf_insn_aux_data *aux = commit_window ? cur_aux(env) : &info->aux; 12066 struct bpf_verifier_state *vstate = env->cur_state; 12067 bool off_is_imm = tnum_is_const(off_reg->var_off); 12068 bool off_is_neg = off_reg->smin_value < 0; 12069 bool ptr_is_dst_reg = ptr_reg == dst_reg; 12070 u8 opcode = BPF_OP(insn->code); 12071 u32 alu_state, alu_limit; 12072 struct bpf_reg_state tmp; 12073 bool ret; 12074 int err; 12075 12076 if (can_skip_alu_sanitation(env, insn)) 12077 return 0; 12078 12079 /* We already marked aux for masking from non-speculative 12080 * paths, thus we got here in the first place. We only care 12081 * to explore bad access from here. 12082 */ 12083 if (vstate->speculative) 12084 goto do_sim; 12085 12086 if (!commit_window) { 12087 if (!tnum_is_const(off_reg->var_off) && 12088 (off_reg->smin_value < 0) != (off_reg->smax_value < 0)) 12089 return REASON_BOUNDS; 12090 12091 info->mask_to_left = (opcode == BPF_ADD && off_is_neg) || 12092 (opcode == BPF_SUB && !off_is_neg); 12093 } 12094 12095 err = retrieve_ptr_limit(ptr_reg, &alu_limit, info->mask_to_left); 12096 if (err < 0) 12097 return err; 12098 12099 if (commit_window) { 12100 /* In commit phase we narrow the masking window based on 12101 * the observed pointer move after the simulated operation. 12102 */ 12103 alu_state = info->aux.alu_state; 12104 alu_limit = abs(info->aux.alu_limit - alu_limit); 12105 } else { 12106 alu_state = off_is_neg ? BPF_ALU_NEG_VALUE : 0; 12107 alu_state |= off_is_imm ? BPF_ALU_IMMEDIATE : 0; 12108 alu_state |= ptr_is_dst_reg ? 12109 BPF_ALU_SANITIZE_SRC : BPF_ALU_SANITIZE_DST; 12110 12111 /* Limit pruning on unknown scalars to enable deep search for 12112 * potential masking differences from other program paths. 12113 */ 12114 if (!off_is_imm) 12115 env->explore_alu_limits = true; 12116 } 12117 12118 err = update_alu_sanitation_state(aux, alu_state, alu_limit); 12119 if (err < 0) 12120 return err; 12121 do_sim: 12122 /* If we're in commit phase, we're done here given we already 12123 * pushed the truncated dst_reg into the speculative verification 12124 * stack. 12125 * 12126 * Also, when register is a known constant, we rewrite register-based 12127 * operation to immediate-based, and thus do not need masking (and as 12128 * a consequence, do not need to simulate the zero-truncation either). 12129 */ 12130 if (commit_window || off_is_imm) 12131 return 0; 12132 12133 /* Simulate and find potential out-of-bounds access under 12134 * speculative execution from truncation as a result of 12135 * masking when off was not within expected range. If off 12136 * sits in dst, then we temporarily need to move ptr there 12137 * to simulate dst (== 0) +/-= ptr. Needed, for example, 12138 * for cases where we use K-based arithmetic in one direction 12139 * and truncated reg-based in the other in order to explore 12140 * bad access. 12141 */ 12142 if (!ptr_is_dst_reg) { 12143 tmp = *dst_reg; 12144 copy_register_state(dst_reg, ptr_reg); 12145 } 12146 ret = sanitize_speculative_path(env, NULL, env->insn_idx + 1, 12147 env->insn_idx); 12148 if (!ptr_is_dst_reg && ret) 12149 *dst_reg = tmp; 12150 return !ret ? REASON_STACK : 0; 12151 } 12152 12153 static void sanitize_mark_insn_seen(struct bpf_verifier_env *env) 12154 { 12155 struct bpf_verifier_state *vstate = env->cur_state; 12156 12157 /* If we simulate paths under speculation, we don't update the 12158 * insn as 'seen' such that when we verify unreachable paths in 12159 * the non-speculative domain, sanitize_dead_code() can still 12160 * rewrite/sanitize them. 12161 */ 12162 if (!vstate->speculative) 12163 env->insn_aux_data[env->insn_idx].seen = env->pass_cnt; 12164 } 12165 12166 static int sanitize_err(struct bpf_verifier_env *env, 12167 const struct bpf_insn *insn, int reason, 12168 const struct bpf_reg_state *off_reg, 12169 const struct bpf_reg_state *dst_reg) 12170 { 12171 static const char *err = "pointer arithmetic with it prohibited for !root"; 12172 const char *op = BPF_OP(insn->code) == BPF_ADD ? "add" : "sub"; 12173 u32 dst = insn->dst_reg, src = insn->src_reg; 12174 12175 switch (reason) { 12176 case REASON_BOUNDS: 12177 verbose(env, "R%d has unknown scalar with mixed signed bounds, %s\n", 12178 off_reg == dst_reg ? dst : src, err); 12179 break; 12180 case REASON_TYPE: 12181 verbose(env, "R%d has pointer with unsupported alu operation, %s\n", 12182 off_reg == dst_reg ? src : dst, err); 12183 break; 12184 case REASON_PATHS: 12185 verbose(env, "R%d tried to %s from different maps, paths or scalars, %s\n", 12186 dst, op, err); 12187 break; 12188 case REASON_LIMIT: 12189 verbose(env, "R%d tried to %s beyond pointer bounds, %s\n", 12190 dst, op, err); 12191 break; 12192 case REASON_STACK: 12193 verbose(env, "R%d could not be pushed for speculative verification, %s\n", 12194 dst, err); 12195 break; 12196 default: 12197 verbose(env, "verifier internal error: unknown reason (%d)\n", 12198 reason); 12199 break; 12200 } 12201 12202 return -EACCES; 12203 } 12204 12205 /* check that stack access falls within stack limits and that 'reg' doesn't 12206 * have a variable offset. 12207 * 12208 * Variable offset is prohibited for unprivileged mode for simplicity since it 12209 * requires corresponding support in Spectre masking for stack ALU. See also 12210 * retrieve_ptr_limit(). 12211 * 12212 * 12213 * 'off' includes 'reg->off'. 12214 */ 12215 static int check_stack_access_for_ptr_arithmetic( 12216 struct bpf_verifier_env *env, 12217 int regno, 12218 const struct bpf_reg_state *reg, 12219 int off) 12220 { 12221 if (!tnum_is_const(reg->var_off)) { 12222 char tn_buf[48]; 12223 12224 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 12225 verbose(env, "R%d variable stack access prohibited for !root, var_off=%s off=%d\n", 12226 regno, tn_buf, off); 12227 return -EACCES; 12228 } 12229 12230 if (off >= 0 || off < -MAX_BPF_STACK) { 12231 verbose(env, "R%d stack pointer arithmetic goes out of range, " 12232 "prohibited for !root; off=%d\n", regno, off); 12233 return -EACCES; 12234 } 12235 12236 return 0; 12237 } 12238 12239 static int sanitize_check_bounds(struct bpf_verifier_env *env, 12240 const struct bpf_insn *insn, 12241 const struct bpf_reg_state *dst_reg) 12242 { 12243 u32 dst = insn->dst_reg; 12244 12245 /* For unprivileged we require that resulting offset must be in bounds 12246 * in order to be able to sanitize access later on. 12247 */ 12248 if (env->bypass_spec_v1) 12249 return 0; 12250 12251 switch (dst_reg->type) { 12252 case PTR_TO_STACK: 12253 if (check_stack_access_for_ptr_arithmetic(env, dst, dst_reg, 12254 dst_reg->off + dst_reg->var_off.value)) 12255 return -EACCES; 12256 break; 12257 case PTR_TO_MAP_VALUE: 12258 if (check_map_access(env, dst, dst_reg->off, 1, false, ACCESS_HELPER)) { 12259 verbose(env, "R%d pointer arithmetic of map value goes out of range, " 12260 "prohibited for !root\n", dst); 12261 return -EACCES; 12262 } 12263 break; 12264 default: 12265 break; 12266 } 12267 12268 return 0; 12269 } 12270 12271 /* Handles arithmetic on a pointer and a scalar: computes new min/max and var_off. 12272 * Caller should also handle BPF_MOV case separately. 12273 * If we return -EACCES, caller may want to try again treating pointer as a 12274 * scalar. So we only emit a diagnostic if !env->allow_ptr_leaks. 12275 */ 12276 static int adjust_ptr_min_max_vals(struct bpf_verifier_env *env, 12277 struct bpf_insn *insn, 12278 const struct bpf_reg_state *ptr_reg, 12279 const struct bpf_reg_state *off_reg) 12280 { 12281 struct bpf_verifier_state *vstate = env->cur_state; 12282 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 12283 struct bpf_reg_state *regs = state->regs, *dst_reg; 12284 bool known = tnum_is_const(off_reg->var_off); 12285 s64 smin_val = off_reg->smin_value, smax_val = off_reg->smax_value, 12286 smin_ptr = ptr_reg->smin_value, smax_ptr = ptr_reg->smax_value; 12287 u64 umin_val = off_reg->umin_value, umax_val = off_reg->umax_value, 12288 umin_ptr = ptr_reg->umin_value, umax_ptr = ptr_reg->umax_value; 12289 struct bpf_sanitize_info info = {}; 12290 u8 opcode = BPF_OP(insn->code); 12291 u32 dst = insn->dst_reg; 12292 int ret; 12293 12294 dst_reg = ®s[dst]; 12295 12296 if ((known && (smin_val != smax_val || umin_val != umax_val)) || 12297 smin_val > smax_val || umin_val > umax_val) { 12298 /* Taint dst register if offset had invalid bounds derived from 12299 * e.g. dead branches. 12300 */ 12301 __mark_reg_unknown(env, dst_reg); 12302 return 0; 12303 } 12304 12305 if (BPF_CLASS(insn->code) != BPF_ALU64) { 12306 /* 32-bit ALU ops on pointers produce (meaningless) scalars */ 12307 if (opcode == BPF_SUB && env->allow_ptr_leaks) { 12308 __mark_reg_unknown(env, dst_reg); 12309 return 0; 12310 } 12311 12312 verbose(env, 12313 "R%d 32-bit pointer arithmetic prohibited\n", 12314 dst); 12315 return -EACCES; 12316 } 12317 12318 if (ptr_reg->type & PTR_MAYBE_NULL) { 12319 verbose(env, "R%d pointer arithmetic on %s prohibited, null-check it first\n", 12320 dst, reg_type_str(env, ptr_reg->type)); 12321 return -EACCES; 12322 } 12323 12324 switch (base_type(ptr_reg->type)) { 12325 case CONST_PTR_TO_MAP: 12326 /* smin_val represents the known value */ 12327 if (known && smin_val == 0 && opcode == BPF_ADD) 12328 break; 12329 fallthrough; 12330 case PTR_TO_PACKET_END: 12331 case PTR_TO_SOCKET: 12332 case PTR_TO_SOCK_COMMON: 12333 case PTR_TO_TCP_SOCK: 12334 case PTR_TO_XDP_SOCK: 12335 verbose(env, "R%d pointer arithmetic on %s prohibited\n", 12336 dst, reg_type_str(env, ptr_reg->type)); 12337 return -EACCES; 12338 default: 12339 break; 12340 } 12341 12342 /* In case of 'scalar += pointer', dst_reg inherits pointer type and id. 12343 * The id may be overwritten later if we create a new variable offset. 12344 */ 12345 dst_reg->type = ptr_reg->type; 12346 dst_reg->id = ptr_reg->id; 12347 12348 if (!check_reg_sane_offset(env, off_reg, ptr_reg->type) || 12349 !check_reg_sane_offset(env, ptr_reg, ptr_reg->type)) 12350 return -EINVAL; 12351 12352 /* pointer types do not carry 32-bit bounds at the moment. */ 12353 __mark_reg32_unbounded(dst_reg); 12354 12355 if (sanitize_needed(opcode)) { 12356 ret = sanitize_ptr_alu(env, insn, ptr_reg, off_reg, dst_reg, 12357 &info, false); 12358 if (ret < 0) 12359 return sanitize_err(env, insn, ret, off_reg, dst_reg); 12360 } 12361 12362 switch (opcode) { 12363 case BPF_ADD: 12364 /* We can take a fixed offset as long as it doesn't overflow 12365 * the s32 'off' field 12366 */ 12367 if (known && (ptr_reg->off + smin_val == 12368 (s64)(s32)(ptr_reg->off + smin_val))) { 12369 /* pointer += K. Accumulate it into fixed offset */ 12370 dst_reg->smin_value = smin_ptr; 12371 dst_reg->smax_value = smax_ptr; 12372 dst_reg->umin_value = umin_ptr; 12373 dst_reg->umax_value = umax_ptr; 12374 dst_reg->var_off = ptr_reg->var_off; 12375 dst_reg->off = ptr_reg->off + smin_val; 12376 dst_reg->raw = ptr_reg->raw; 12377 break; 12378 } 12379 /* A new variable offset is created. Note that off_reg->off 12380 * == 0, since it's a scalar. 12381 * dst_reg gets the pointer type and since some positive 12382 * integer value was added to the pointer, give it a new 'id' 12383 * if it's a PTR_TO_PACKET. 12384 * this creates a new 'base' pointer, off_reg (variable) gets 12385 * added into the variable offset, and we copy the fixed offset 12386 * from ptr_reg. 12387 */ 12388 if (signed_add_overflows(smin_ptr, smin_val) || 12389 signed_add_overflows(smax_ptr, smax_val)) { 12390 dst_reg->smin_value = S64_MIN; 12391 dst_reg->smax_value = S64_MAX; 12392 } else { 12393 dst_reg->smin_value = smin_ptr + smin_val; 12394 dst_reg->smax_value = smax_ptr + smax_val; 12395 } 12396 if (umin_ptr + umin_val < umin_ptr || 12397 umax_ptr + umax_val < umax_ptr) { 12398 dst_reg->umin_value = 0; 12399 dst_reg->umax_value = U64_MAX; 12400 } else { 12401 dst_reg->umin_value = umin_ptr + umin_val; 12402 dst_reg->umax_value = umax_ptr + umax_val; 12403 } 12404 dst_reg->var_off = tnum_add(ptr_reg->var_off, off_reg->var_off); 12405 dst_reg->off = ptr_reg->off; 12406 dst_reg->raw = ptr_reg->raw; 12407 if (reg_is_pkt_pointer(ptr_reg)) { 12408 dst_reg->id = ++env->id_gen; 12409 /* something was added to pkt_ptr, set range to zero */ 12410 memset(&dst_reg->raw, 0, sizeof(dst_reg->raw)); 12411 } 12412 break; 12413 case BPF_SUB: 12414 if (dst_reg == off_reg) { 12415 /* scalar -= pointer. Creates an unknown scalar */ 12416 verbose(env, "R%d tried to subtract pointer from scalar\n", 12417 dst); 12418 return -EACCES; 12419 } 12420 /* We don't allow subtraction from FP, because (according to 12421 * test_verifier.c test "invalid fp arithmetic", JITs might not 12422 * be able to deal with it. 12423 */ 12424 if (ptr_reg->type == PTR_TO_STACK) { 12425 verbose(env, "R%d subtraction from stack pointer prohibited\n", 12426 dst); 12427 return -EACCES; 12428 } 12429 if (known && (ptr_reg->off - smin_val == 12430 (s64)(s32)(ptr_reg->off - smin_val))) { 12431 /* pointer -= K. Subtract it from fixed offset */ 12432 dst_reg->smin_value = smin_ptr; 12433 dst_reg->smax_value = smax_ptr; 12434 dst_reg->umin_value = umin_ptr; 12435 dst_reg->umax_value = umax_ptr; 12436 dst_reg->var_off = ptr_reg->var_off; 12437 dst_reg->id = ptr_reg->id; 12438 dst_reg->off = ptr_reg->off - smin_val; 12439 dst_reg->raw = ptr_reg->raw; 12440 break; 12441 } 12442 /* A new variable offset is created. If the subtrahend is known 12443 * nonnegative, then any reg->range we had before is still good. 12444 */ 12445 if (signed_sub_overflows(smin_ptr, smax_val) || 12446 signed_sub_overflows(smax_ptr, smin_val)) { 12447 /* Overflow possible, we know nothing */ 12448 dst_reg->smin_value = S64_MIN; 12449 dst_reg->smax_value = S64_MAX; 12450 } else { 12451 dst_reg->smin_value = smin_ptr - smax_val; 12452 dst_reg->smax_value = smax_ptr - smin_val; 12453 } 12454 if (umin_ptr < umax_val) { 12455 /* Overflow possible, we know nothing */ 12456 dst_reg->umin_value = 0; 12457 dst_reg->umax_value = U64_MAX; 12458 } else { 12459 /* Cannot overflow (as long as bounds are consistent) */ 12460 dst_reg->umin_value = umin_ptr - umax_val; 12461 dst_reg->umax_value = umax_ptr - umin_val; 12462 } 12463 dst_reg->var_off = tnum_sub(ptr_reg->var_off, off_reg->var_off); 12464 dst_reg->off = ptr_reg->off; 12465 dst_reg->raw = ptr_reg->raw; 12466 if (reg_is_pkt_pointer(ptr_reg)) { 12467 dst_reg->id = ++env->id_gen; 12468 /* something was added to pkt_ptr, set range to zero */ 12469 if (smin_val < 0) 12470 memset(&dst_reg->raw, 0, sizeof(dst_reg->raw)); 12471 } 12472 break; 12473 case BPF_AND: 12474 case BPF_OR: 12475 case BPF_XOR: 12476 /* bitwise ops on pointers are troublesome, prohibit. */ 12477 verbose(env, "R%d bitwise operator %s on pointer prohibited\n", 12478 dst, bpf_alu_string[opcode >> 4]); 12479 return -EACCES; 12480 default: 12481 /* other operators (e.g. MUL,LSH) produce non-pointer results */ 12482 verbose(env, "R%d pointer arithmetic with %s operator prohibited\n", 12483 dst, bpf_alu_string[opcode >> 4]); 12484 return -EACCES; 12485 } 12486 12487 if (!check_reg_sane_offset(env, dst_reg, ptr_reg->type)) 12488 return -EINVAL; 12489 reg_bounds_sync(dst_reg); 12490 if (sanitize_check_bounds(env, insn, dst_reg) < 0) 12491 return -EACCES; 12492 if (sanitize_needed(opcode)) { 12493 ret = sanitize_ptr_alu(env, insn, dst_reg, off_reg, dst_reg, 12494 &info, true); 12495 if (ret < 0) 12496 return sanitize_err(env, insn, ret, off_reg, dst_reg); 12497 } 12498 12499 return 0; 12500 } 12501 12502 static void scalar32_min_max_add(struct bpf_reg_state *dst_reg, 12503 struct bpf_reg_state *src_reg) 12504 { 12505 s32 smin_val = src_reg->s32_min_value; 12506 s32 smax_val = src_reg->s32_max_value; 12507 u32 umin_val = src_reg->u32_min_value; 12508 u32 umax_val = src_reg->u32_max_value; 12509 12510 if (signed_add32_overflows(dst_reg->s32_min_value, smin_val) || 12511 signed_add32_overflows(dst_reg->s32_max_value, smax_val)) { 12512 dst_reg->s32_min_value = S32_MIN; 12513 dst_reg->s32_max_value = S32_MAX; 12514 } else { 12515 dst_reg->s32_min_value += smin_val; 12516 dst_reg->s32_max_value += smax_val; 12517 } 12518 if (dst_reg->u32_min_value + umin_val < umin_val || 12519 dst_reg->u32_max_value + umax_val < umax_val) { 12520 dst_reg->u32_min_value = 0; 12521 dst_reg->u32_max_value = U32_MAX; 12522 } else { 12523 dst_reg->u32_min_value += umin_val; 12524 dst_reg->u32_max_value += umax_val; 12525 } 12526 } 12527 12528 static void scalar_min_max_add(struct bpf_reg_state *dst_reg, 12529 struct bpf_reg_state *src_reg) 12530 { 12531 s64 smin_val = src_reg->smin_value; 12532 s64 smax_val = src_reg->smax_value; 12533 u64 umin_val = src_reg->umin_value; 12534 u64 umax_val = src_reg->umax_value; 12535 12536 if (signed_add_overflows(dst_reg->smin_value, smin_val) || 12537 signed_add_overflows(dst_reg->smax_value, smax_val)) { 12538 dst_reg->smin_value = S64_MIN; 12539 dst_reg->smax_value = S64_MAX; 12540 } else { 12541 dst_reg->smin_value += smin_val; 12542 dst_reg->smax_value += smax_val; 12543 } 12544 if (dst_reg->umin_value + umin_val < umin_val || 12545 dst_reg->umax_value + umax_val < umax_val) { 12546 dst_reg->umin_value = 0; 12547 dst_reg->umax_value = U64_MAX; 12548 } else { 12549 dst_reg->umin_value += umin_val; 12550 dst_reg->umax_value += umax_val; 12551 } 12552 } 12553 12554 static void scalar32_min_max_sub(struct bpf_reg_state *dst_reg, 12555 struct bpf_reg_state *src_reg) 12556 { 12557 s32 smin_val = src_reg->s32_min_value; 12558 s32 smax_val = src_reg->s32_max_value; 12559 u32 umin_val = src_reg->u32_min_value; 12560 u32 umax_val = src_reg->u32_max_value; 12561 12562 if (signed_sub32_overflows(dst_reg->s32_min_value, smax_val) || 12563 signed_sub32_overflows(dst_reg->s32_max_value, smin_val)) { 12564 /* Overflow possible, we know nothing */ 12565 dst_reg->s32_min_value = S32_MIN; 12566 dst_reg->s32_max_value = S32_MAX; 12567 } else { 12568 dst_reg->s32_min_value -= smax_val; 12569 dst_reg->s32_max_value -= smin_val; 12570 } 12571 if (dst_reg->u32_min_value < umax_val) { 12572 /* Overflow possible, we know nothing */ 12573 dst_reg->u32_min_value = 0; 12574 dst_reg->u32_max_value = U32_MAX; 12575 } else { 12576 /* Cannot overflow (as long as bounds are consistent) */ 12577 dst_reg->u32_min_value -= umax_val; 12578 dst_reg->u32_max_value -= umin_val; 12579 } 12580 } 12581 12582 static void scalar_min_max_sub(struct bpf_reg_state *dst_reg, 12583 struct bpf_reg_state *src_reg) 12584 { 12585 s64 smin_val = src_reg->smin_value; 12586 s64 smax_val = src_reg->smax_value; 12587 u64 umin_val = src_reg->umin_value; 12588 u64 umax_val = src_reg->umax_value; 12589 12590 if (signed_sub_overflows(dst_reg->smin_value, smax_val) || 12591 signed_sub_overflows(dst_reg->smax_value, smin_val)) { 12592 /* Overflow possible, we know nothing */ 12593 dst_reg->smin_value = S64_MIN; 12594 dst_reg->smax_value = S64_MAX; 12595 } else { 12596 dst_reg->smin_value -= smax_val; 12597 dst_reg->smax_value -= smin_val; 12598 } 12599 if (dst_reg->umin_value < umax_val) { 12600 /* Overflow possible, we know nothing */ 12601 dst_reg->umin_value = 0; 12602 dst_reg->umax_value = U64_MAX; 12603 } else { 12604 /* Cannot overflow (as long as bounds are consistent) */ 12605 dst_reg->umin_value -= umax_val; 12606 dst_reg->umax_value -= umin_val; 12607 } 12608 } 12609 12610 static void scalar32_min_max_mul(struct bpf_reg_state *dst_reg, 12611 struct bpf_reg_state *src_reg) 12612 { 12613 s32 smin_val = src_reg->s32_min_value; 12614 u32 umin_val = src_reg->u32_min_value; 12615 u32 umax_val = src_reg->u32_max_value; 12616 12617 if (smin_val < 0 || dst_reg->s32_min_value < 0) { 12618 /* Ain't nobody got time to multiply that sign */ 12619 __mark_reg32_unbounded(dst_reg); 12620 return; 12621 } 12622 /* Both values are positive, so we can work with unsigned and 12623 * copy the result to signed (unless it exceeds S32_MAX). 12624 */ 12625 if (umax_val > U16_MAX || dst_reg->u32_max_value > U16_MAX) { 12626 /* Potential overflow, we know nothing */ 12627 __mark_reg32_unbounded(dst_reg); 12628 return; 12629 } 12630 dst_reg->u32_min_value *= umin_val; 12631 dst_reg->u32_max_value *= umax_val; 12632 if (dst_reg->u32_max_value > S32_MAX) { 12633 /* Overflow possible, we know nothing */ 12634 dst_reg->s32_min_value = S32_MIN; 12635 dst_reg->s32_max_value = S32_MAX; 12636 } else { 12637 dst_reg->s32_min_value = dst_reg->u32_min_value; 12638 dst_reg->s32_max_value = dst_reg->u32_max_value; 12639 } 12640 } 12641 12642 static void scalar_min_max_mul(struct bpf_reg_state *dst_reg, 12643 struct bpf_reg_state *src_reg) 12644 { 12645 s64 smin_val = src_reg->smin_value; 12646 u64 umin_val = src_reg->umin_value; 12647 u64 umax_val = src_reg->umax_value; 12648 12649 if (smin_val < 0 || dst_reg->smin_value < 0) { 12650 /* Ain't nobody got time to multiply that sign */ 12651 __mark_reg64_unbounded(dst_reg); 12652 return; 12653 } 12654 /* Both values are positive, so we can work with unsigned and 12655 * copy the result to signed (unless it exceeds S64_MAX). 12656 */ 12657 if (umax_val > U32_MAX || dst_reg->umax_value > U32_MAX) { 12658 /* Potential overflow, we know nothing */ 12659 __mark_reg64_unbounded(dst_reg); 12660 return; 12661 } 12662 dst_reg->umin_value *= umin_val; 12663 dst_reg->umax_value *= umax_val; 12664 if (dst_reg->umax_value > S64_MAX) { 12665 /* Overflow possible, we know nothing */ 12666 dst_reg->smin_value = S64_MIN; 12667 dst_reg->smax_value = S64_MAX; 12668 } else { 12669 dst_reg->smin_value = dst_reg->umin_value; 12670 dst_reg->smax_value = dst_reg->umax_value; 12671 } 12672 } 12673 12674 static void scalar32_min_max_and(struct bpf_reg_state *dst_reg, 12675 struct bpf_reg_state *src_reg) 12676 { 12677 bool src_known = tnum_subreg_is_const(src_reg->var_off); 12678 bool dst_known = tnum_subreg_is_const(dst_reg->var_off); 12679 struct tnum var32_off = tnum_subreg(dst_reg->var_off); 12680 s32 smin_val = src_reg->s32_min_value; 12681 u32 umax_val = src_reg->u32_max_value; 12682 12683 if (src_known && dst_known) { 12684 __mark_reg32_known(dst_reg, var32_off.value); 12685 return; 12686 } 12687 12688 /* We get our minimum from the var_off, since that's inherently 12689 * bitwise. Our maximum is the minimum of the operands' maxima. 12690 */ 12691 dst_reg->u32_min_value = var32_off.value; 12692 dst_reg->u32_max_value = min(dst_reg->u32_max_value, umax_val); 12693 if (dst_reg->s32_min_value < 0 || smin_val < 0) { 12694 /* Lose signed bounds when ANDing negative numbers, 12695 * ain't nobody got time for that. 12696 */ 12697 dst_reg->s32_min_value = S32_MIN; 12698 dst_reg->s32_max_value = S32_MAX; 12699 } else { 12700 /* ANDing two positives gives a positive, so safe to 12701 * cast result into s64. 12702 */ 12703 dst_reg->s32_min_value = dst_reg->u32_min_value; 12704 dst_reg->s32_max_value = dst_reg->u32_max_value; 12705 } 12706 } 12707 12708 static void scalar_min_max_and(struct bpf_reg_state *dst_reg, 12709 struct bpf_reg_state *src_reg) 12710 { 12711 bool src_known = tnum_is_const(src_reg->var_off); 12712 bool dst_known = tnum_is_const(dst_reg->var_off); 12713 s64 smin_val = src_reg->smin_value; 12714 u64 umax_val = src_reg->umax_value; 12715 12716 if (src_known && dst_known) { 12717 __mark_reg_known(dst_reg, dst_reg->var_off.value); 12718 return; 12719 } 12720 12721 /* We get our minimum from the var_off, since that's inherently 12722 * bitwise. Our maximum is the minimum of the operands' maxima. 12723 */ 12724 dst_reg->umin_value = dst_reg->var_off.value; 12725 dst_reg->umax_value = min(dst_reg->umax_value, umax_val); 12726 if (dst_reg->smin_value < 0 || smin_val < 0) { 12727 /* Lose signed bounds when ANDing negative numbers, 12728 * ain't nobody got time for that. 12729 */ 12730 dst_reg->smin_value = S64_MIN; 12731 dst_reg->smax_value = S64_MAX; 12732 } else { 12733 /* ANDing two positives gives a positive, so safe to 12734 * cast result into s64. 12735 */ 12736 dst_reg->smin_value = dst_reg->umin_value; 12737 dst_reg->smax_value = dst_reg->umax_value; 12738 } 12739 /* We may learn something more from the var_off */ 12740 __update_reg_bounds(dst_reg); 12741 } 12742 12743 static void scalar32_min_max_or(struct bpf_reg_state *dst_reg, 12744 struct bpf_reg_state *src_reg) 12745 { 12746 bool src_known = tnum_subreg_is_const(src_reg->var_off); 12747 bool dst_known = tnum_subreg_is_const(dst_reg->var_off); 12748 struct tnum var32_off = tnum_subreg(dst_reg->var_off); 12749 s32 smin_val = src_reg->s32_min_value; 12750 u32 umin_val = src_reg->u32_min_value; 12751 12752 if (src_known && dst_known) { 12753 __mark_reg32_known(dst_reg, var32_off.value); 12754 return; 12755 } 12756 12757 /* We get our maximum from the var_off, and our minimum is the 12758 * maximum of the operands' minima 12759 */ 12760 dst_reg->u32_min_value = max(dst_reg->u32_min_value, umin_val); 12761 dst_reg->u32_max_value = var32_off.value | var32_off.mask; 12762 if (dst_reg->s32_min_value < 0 || smin_val < 0) { 12763 /* Lose signed bounds when ORing negative numbers, 12764 * ain't nobody got time for that. 12765 */ 12766 dst_reg->s32_min_value = S32_MIN; 12767 dst_reg->s32_max_value = S32_MAX; 12768 } else { 12769 /* ORing two positives gives a positive, so safe to 12770 * cast result into s64. 12771 */ 12772 dst_reg->s32_min_value = dst_reg->u32_min_value; 12773 dst_reg->s32_max_value = dst_reg->u32_max_value; 12774 } 12775 } 12776 12777 static void scalar_min_max_or(struct bpf_reg_state *dst_reg, 12778 struct bpf_reg_state *src_reg) 12779 { 12780 bool src_known = tnum_is_const(src_reg->var_off); 12781 bool dst_known = tnum_is_const(dst_reg->var_off); 12782 s64 smin_val = src_reg->smin_value; 12783 u64 umin_val = src_reg->umin_value; 12784 12785 if (src_known && dst_known) { 12786 __mark_reg_known(dst_reg, dst_reg->var_off.value); 12787 return; 12788 } 12789 12790 /* We get our maximum from the var_off, and our minimum is the 12791 * maximum of the operands' minima 12792 */ 12793 dst_reg->umin_value = max(dst_reg->umin_value, umin_val); 12794 dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask; 12795 if (dst_reg->smin_value < 0 || smin_val < 0) { 12796 /* Lose signed bounds when ORing negative numbers, 12797 * ain't nobody got time for that. 12798 */ 12799 dst_reg->smin_value = S64_MIN; 12800 dst_reg->smax_value = S64_MAX; 12801 } else { 12802 /* ORing two positives gives a positive, so safe to 12803 * cast result into s64. 12804 */ 12805 dst_reg->smin_value = dst_reg->umin_value; 12806 dst_reg->smax_value = dst_reg->umax_value; 12807 } 12808 /* We may learn something more from the var_off */ 12809 __update_reg_bounds(dst_reg); 12810 } 12811 12812 static void scalar32_min_max_xor(struct bpf_reg_state *dst_reg, 12813 struct bpf_reg_state *src_reg) 12814 { 12815 bool src_known = tnum_subreg_is_const(src_reg->var_off); 12816 bool dst_known = tnum_subreg_is_const(dst_reg->var_off); 12817 struct tnum var32_off = tnum_subreg(dst_reg->var_off); 12818 s32 smin_val = src_reg->s32_min_value; 12819 12820 if (src_known && dst_known) { 12821 __mark_reg32_known(dst_reg, var32_off.value); 12822 return; 12823 } 12824 12825 /* We get both minimum and maximum from the var32_off. */ 12826 dst_reg->u32_min_value = var32_off.value; 12827 dst_reg->u32_max_value = var32_off.value | var32_off.mask; 12828 12829 if (dst_reg->s32_min_value >= 0 && smin_val >= 0) { 12830 /* XORing two positive sign numbers gives a positive, 12831 * so safe to cast u32 result into s32. 12832 */ 12833 dst_reg->s32_min_value = dst_reg->u32_min_value; 12834 dst_reg->s32_max_value = dst_reg->u32_max_value; 12835 } else { 12836 dst_reg->s32_min_value = S32_MIN; 12837 dst_reg->s32_max_value = S32_MAX; 12838 } 12839 } 12840 12841 static void scalar_min_max_xor(struct bpf_reg_state *dst_reg, 12842 struct bpf_reg_state *src_reg) 12843 { 12844 bool src_known = tnum_is_const(src_reg->var_off); 12845 bool dst_known = tnum_is_const(dst_reg->var_off); 12846 s64 smin_val = src_reg->smin_value; 12847 12848 if (src_known && dst_known) { 12849 /* dst_reg->var_off.value has been updated earlier */ 12850 __mark_reg_known(dst_reg, dst_reg->var_off.value); 12851 return; 12852 } 12853 12854 /* We get both minimum and maximum from the var_off. */ 12855 dst_reg->umin_value = dst_reg->var_off.value; 12856 dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask; 12857 12858 if (dst_reg->smin_value >= 0 && smin_val >= 0) { 12859 /* XORing two positive sign numbers gives a positive, 12860 * so safe to cast u64 result into s64. 12861 */ 12862 dst_reg->smin_value = dst_reg->umin_value; 12863 dst_reg->smax_value = dst_reg->umax_value; 12864 } else { 12865 dst_reg->smin_value = S64_MIN; 12866 dst_reg->smax_value = S64_MAX; 12867 } 12868 12869 __update_reg_bounds(dst_reg); 12870 } 12871 12872 static void __scalar32_min_max_lsh(struct bpf_reg_state *dst_reg, 12873 u64 umin_val, u64 umax_val) 12874 { 12875 /* We lose all sign bit information (except what we can pick 12876 * up from var_off) 12877 */ 12878 dst_reg->s32_min_value = S32_MIN; 12879 dst_reg->s32_max_value = S32_MAX; 12880 /* If we might shift our top bit out, then we know nothing */ 12881 if (umax_val > 31 || dst_reg->u32_max_value > 1ULL << (31 - umax_val)) { 12882 dst_reg->u32_min_value = 0; 12883 dst_reg->u32_max_value = U32_MAX; 12884 } else { 12885 dst_reg->u32_min_value <<= umin_val; 12886 dst_reg->u32_max_value <<= umax_val; 12887 } 12888 } 12889 12890 static void scalar32_min_max_lsh(struct bpf_reg_state *dst_reg, 12891 struct bpf_reg_state *src_reg) 12892 { 12893 u32 umax_val = src_reg->u32_max_value; 12894 u32 umin_val = src_reg->u32_min_value; 12895 /* u32 alu operation will zext upper bits */ 12896 struct tnum subreg = tnum_subreg(dst_reg->var_off); 12897 12898 __scalar32_min_max_lsh(dst_reg, umin_val, umax_val); 12899 dst_reg->var_off = tnum_subreg(tnum_lshift(subreg, umin_val)); 12900 /* Not required but being careful mark reg64 bounds as unknown so 12901 * that we are forced to pick them up from tnum and zext later and 12902 * if some path skips this step we are still safe. 12903 */ 12904 __mark_reg64_unbounded(dst_reg); 12905 __update_reg32_bounds(dst_reg); 12906 } 12907 12908 static void __scalar64_min_max_lsh(struct bpf_reg_state *dst_reg, 12909 u64 umin_val, u64 umax_val) 12910 { 12911 /* Special case <<32 because it is a common compiler pattern to sign 12912 * extend subreg by doing <<32 s>>32. In this case if 32bit bounds are 12913 * positive we know this shift will also be positive so we can track 12914 * bounds correctly. Otherwise we lose all sign bit information except 12915 * what we can pick up from var_off. Perhaps we can generalize this 12916 * later to shifts of any length. 12917 */ 12918 if (umin_val == 32 && umax_val == 32 && dst_reg->s32_max_value >= 0) 12919 dst_reg->smax_value = (s64)dst_reg->s32_max_value << 32; 12920 else 12921 dst_reg->smax_value = S64_MAX; 12922 12923 if (umin_val == 32 && umax_val == 32 && dst_reg->s32_min_value >= 0) 12924 dst_reg->smin_value = (s64)dst_reg->s32_min_value << 32; 12925 else 12926 dst_reg->smin_value = S64_MIN; 12927 12928 /* If we might shift our top bit out, then we know nothing */ 12929 if (dst_reg->umax_value > 1ULL << (63 - umax_val)) { 12930 dst_reg->umin_value = 0; 12931 dst_reg->umax_value = U64_MAX; 12932 } else { 12933 dst_reg->umin_value <<= umin_val; 12934 dst_reg->umax_value <<= umax_val; 12935 } 12936 } 12937 12938 static void scalar_min_max_lsh(struct bpf_reg_state *dst_reg, 12939 struct bpf_reg_state *src_reg) 12940 { 12941 u64 umax_val = src_reg->umax_value; 12942 u64 umin_val = src_reg->umin_value; 12943 12944 /* scalar64 calc uses 32bit unshifted bounds so must be called first */ 12945 __scalar64_min_max_lsh(dst_reg, umin_val, umax_val); 12946 __scalar32_min_max_lsh(dst_reg, umin_val, umax_val); 12947 12948 dst_reg->var_off = tnum_lshift(dst_reg->var_off, umin_val); 12949 /* We may learn something more from the var_off */ 12950 __update_reg_bounds(dst_reg); 12951 } 12952 12953 static void scalar32_min_max_rsh(struct bpf_reg_state *dst_reg, 12954 struct bpf_reg_state *src_reg) 12955 { 12956 struct tnum subreg = tnum_subreg(dst_reg->var_off); 12957 u32 umax_val = src_reg->u32_max_value; 12958 u32 umin_val = src_reg->u32_min_value; 12959 12960 /* BPF_RSH is an unsigned shift. If the value in dst_reg might 12961 * be negative, then either: 12962 * 1) src_reg might be zero, so the sign bit of the result is 12963 * unknown, so we lose our signed bounds 12964 * 2) it's known negative, thus the unsigned bounds capture the 12965 * signed bounds 12966 * 3) the signed bounds cross zero, so they tell us nothing 12967 * about the result 12968 * If the value in dst_reg is known nonnegative, then again the 12969 * unsigned bounds capture the signed bounds. 12970 * Thus, in all cases it suffices to blow away our signed bounds 12971 * and rely on inferring new ones from the unsigned bounds and 12972 * var_off of the result. 12973 */ 12974 dst_reg->s32_min_value = S32_MIN; 12975 dst_reg->s32_max_value = S32_MAX; 12976 12977 dst_reg->var_off = tnum_rshift(subreg, umin_val); 12978 dst_reg->u32_min_value >>= umax_val; 12979 dst_reg->u32_max_value >>= umin_val; 12980 12981 __mark_reg64_unbounded(dst_reg); 12982 __update_reg32_bounds(dst_reg); 12983 } 12984 12985 static void scalar_min_max_rsh(struct bpf_reg_state *dst_reg, 12986 struct bpf_reg_state *src_reg) 12987 { 12988 u64 umax_val = src_reg->umax_value; 12989 u64 umin_val = src_reg->umin_value; 12990 12991 /* BPF_RSH is an unsigned shift. If the value in dst_reg might 12992 * be negative, then either: 12993 * 1) src_reg might be zero, so the sign bit of the result is 12994 * unknown, so we lose our signed bounds 12995 * 2) it's known negative, thus the unsigned bounds capture the 12996 * signed bounds 12997 * 3) the signed bounds cross zero, so they tell us nothing 12998 * about the result 12999 * If the value in dst_reg is known nonnegative, then again the 13000 * unsigned bounds capture the signed bounds. 13001 * Thus, in all cases it suffices to blow away our signed bounds 13002 * and rely on inferring new ones from the unsigned bounds and 13003 * var_off of the result. 13004 */ 13005 dst_reg->smin_value = S64_MIN; 13006 dst_reg->smax_value = S64_MAX; 13007 dst_reg->var_off = tnum_rshift(dst_reg->var_off, umin_val); 13008 dst_reg->umin_value >>= umax_val; 13009 dst_reg->umax_value >>= umin_val; 13010 13011 /* Its not easy to operate on alu32 bounds here because it depends 13012 * on bits being shifted in. Take easy way out and mark unbounded 13013 * so we can recalculate later from tnum. 13014 */ 13015 __mark_reg32_unbounded(dst_reg); 13016 __update_reg_bounds(dst_reg); 13017 } 13018 13019 static void scalar32_min_max_arsh(struct bpf_reg_state *dst_reg, 13020 struct bpf_reg_state *src_reg) 13021 { 13022 u64 umin_val = src_reg->u32_min_value; 13023 13024 /* Upon reaching here, src_known is true and 13025 * umax_val is equal to umin_val. 13026 */ 13027 dst_reg->s32_min_value = (u32)(((s32)dst_reg->s32_min_value) >> umin_val); 13028 dst_reg->s32_max_value = (u32)(((s32)dst_reg->s32_max_value) >> umin_val); 13029 13030 dst_reg->var_off = tnum_arshift(tnum_subreg(dst_reg->var_off), umin_val, 32); 13031 13032 /* blow away the dst_reg umin_value/umax_value and rely on 13033 * dst_reg var_off to refine the result. 13034 */ 13035 dst_reg->u32_min_value = 0; 13036 dst_reg->u32_max_value = U32_MAX; 13037 13038 __mark_reg64_unbounded(dst_reg); 13039 __update_reg32_bounds(dst_reg); 13040 } 13041 13042 static void scalar_min_max_arsh(struct bpf_reg_state *dst_reg, 13043 struct bpf_reg_state *src_reg) 13044 { 13045 u64 umin_val = src_reg->umin_value; 13046 13047 /* Upon reaching here, src_known is true and umax_val is equal 13048 * to umin_val. 13049 */ 13050 dst_reg->smin_value >>= umin_val; 13051 dst_reg->smax_value >>= umin_val; 13052 13053 dst_reg->var_off = tnum_arshift(dst_reg->var_off, umin_val, 64); 13054 13055 /* blow away the dst_reg umin_value/umax_value and rely on 13056 * dst_reg var_off to refine the result. 13057 */ 13058 dst_reg->umin_value = 0; 13059 dst_reg->umax_value = U64_MAX; 13060 13061 /* Its not easy to operate on alu32 bounds here because it depends 13062 * on bits being shifted in from upper 32-bits. Take easy way out 13063 * and mark unbounded so we can recalculate later from tnum. 13064 */ 13065 __mark_reg32_unbounded(dst_reg); 13066 __update_reg_bounds(dst_reg); 13067 } 13068 13069 /* WARNING: This function does calculations on 64-bit values, but the actual 13070 * execution may occur on 32-bit values. Therefore, things like bitshifts 13071 * need extra checks in the 32-bit case. 13072 */ 13073 static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env, 13074 struct bpf_insn *insn, 13075 struct bpf_reg_state *dst_reg, 13076 struct bpf_reg_state src_reg) 13077 { 13078 struct bpf_reg_state *regs = cur_regs(env); 13079 u8 opcode = BPF_OP(insn->code); 13080 bool src_known; 13081 s64 smin_val, smax_val; 13082 u64 umin_val, umax_val; 13083 s32 s32_min_val, s32_max_val; 13084 u32 u32_min_val, u32_max_val; 13085 u64 insn_bitness = (BPF_CLASS(insn->code) == BPF_ALU64) ? 64 : 32; 13086 bool alu32 = (BPF_CLASS(insn->code) != BPF_ALU64); 13087 int ret; 13088 13089 smin_val = src_reg.smin_value; 13090 smax_val = src_reg.smax_value; 13091 umin_val = src_reg.umin_value; 13092 umax_val = src_reg.umax_value; 13093 13094 s32_min_val = src_reg.s32_min_value; 13095 s32_max_val = src_reg.s32_max_value; 13096 u32_min_val = src_reg.u32_min_value; 13097 u32_max_val = src_reg.u32_max_value; 13098 13099 if (alu32) { 13100 src_known = tnum_subreg_is_const(src_reg.var_off); 13101 if ((src_known && 13102 (s32_min_val != s32_max_val || u32_min_val != u32_max_val)) || 13103 s32_min_val > s32_max_val || u32_min_val > u32_max_val) { 13104 /* Taint dst register if offset had invalid bounds 13105 * derived from e.g. dead branches. 13106 */ 13107 __mark_reg_unknown(env, dst_reg); 13108 return 0; 13109 } 13110 } else { 13111 src_known = tnum_is_const(src_reg.var_off); 13112 if ((src_known && 13113 (smin_val != smax_val || umin_val != umax_val)) || 13114 smin_val > smax_val || umin_val > umax_val) { 13115 /* Taint dst register if offset had invalid bounds 13116 * derived from e.g. dead branches. 13117 */ 13118 __mark_reg_unknown(env, dst_reg); 13119 return 0; 13120 } 13121 } 13122 13123 if (!src_known && 13124 opcode != BPF_ADD && opcode != BPF_SUB && opcode != BPF_AND) { 13125 __mark_reg_unknown(env, dst_reg); 13126 return 0; 13127 } 13128 13129 if (sanitize_needed(opcode)) { 13130 ret = sanitize_val_alu(env, insn); 13131 if (ret < 0) 13132 return sanitize_err(env, insn, ret, NULL, NULL); 13133 } 13134 13135 /* Calculate sign/unsigned bounds and tnum for alu32 and alu64 bit ops. 13136 * There are two classes of instructions: The first class we track both 13137 * alu32 and alu64 sign/unsigned bounds independently this provides the 13138 * greatest amount of precision when alu operations are mixed with jmp32 13139 * operations. These operations are BPF_ADD, BPF_SUB, BPF_MUL, BPF_ADD, 13140 * and BPF_OR. This is possible because these ops have fairly easy to 13141 * understand and calculate behavior in both 32-bit and 64-bit alu ops. 13142 * See alu32 verifier tests for examples. The second class of 13143 * operations, BPF_LSH, BPF_RSH, and BPF_ARSH, however are not so easy 13144 * with regards to tracking sign/unsigned bounds because the bits may 13145 * cross subreg boundaries in the alu64 case. When this happens we mark 13146 * the reg unbounded in the subreg bound space and use the resulting 13147 * tnum to calculate an approximation of the sign/unsigned bounds. 13148 */ 13149 switch (opcode) { 13150 case BPF_ADD: 13151 scalar32_min_max_add(dst_reg, &src_reg); 13152 scalar_min_max_add(dst_reg, &src_reg); 13153 dst_reg->var_off = tnum_add(dst_reg->var_off, src_reg.var_off); 13154 break; 13155 case BPF_SUB: 13156 scalar32_min_max_sub(dst_reg, &src_reg); 13157 scalar_min_max_sub(dst_reg, &src_reg); 13158 dst_reg->var_off = tnum_sub(dst_reg->var_off, src_reg.var_off); 13159 break; 13160 case BPF_MUL: 13161 dst_reg->var_off = tnum_mul(dst_reg->var_off, src_reg.var_off); 13162 scalar32_min_max_mul(dst_reg, &src_reg); 13163 scalar_min_max_mul(dst_reg, &src_reg); 13164 break; 13165 case BPF_AND: 13166 dst_reg->var_off = tnum_and(dst_reg->var_off, src_reg.var_off); 13167 scalar32_min_max_and(dst_reg, &src_reg); 13168 scalar_min_max_and(dst_reg, &src_reg); 13169 break; 13170 case BPF_OR: 13171 dst_reg->var_off = tnum_or(dst_reg->var_off, src_reg.var_off); 13172 scalar32_min_max_or(dst_reg, &src_reg); 13173 scalar_min_max_or(dst_reg, &src_reg); 13174 break; 13175 case BPF_XOR: 13176 dst_reg->var_off = tnum_xor(dst_reg->var_off, src_reg.var_off); 13177 scalar32_min_max_xor(dst_reg, &src_reg); 13178 scalar_min_max_xor(dst_reg, &src_reg); 13179 break; 13180 case BPF_LSH: 13181 if (umax_val >= insn_bitness) { 13182 /* Shifts greater than 31 or 63 are undefined. 13183 * This includes shifts by a negative number. 13184 */ 13185 mark_reg_unknown(env, regs, insn->dst_reg); 13186 break; 13187 } 13188 if (alu32) 13189 scalar32_min_max_lsh(dst_reg, &src_reg); 13190 else 13191 scalar_min_max_lsh(dst_reg, &src_reg); 13192 break; 13193 case BPF_RSH: 13194 if (umax_val >= insn_bitness) { 13195 /* Shifts greater than 31 or 63 are undefined. 13196 * This includes shifts by a negative number. 13197 */ 13198 mark_reg_unknown(env, regs, insn->dst_reg); 13199 break; 13200 } 13201 if (alu32) 13202 scalar32_min_max_rsh(dst_reg, &src_reg); 13203 else 13204 scalar_min_max_rsh(dst_reg, &src_reg); 13205 break; 13206 case BPF_ARSH: 13207 if (umax_val >= insn_bitness) { 13208 /* Shifts greater than 31 or 63 are undefined. 13209 * This includes shifts by a negative number. 13210 */ 13211 mark_reg_unknown(env, regs, insn->dst_reg); 13212 break; 13213 } 13214 if (alu32) 13215 scalar32_min_max_arsh(dst_reg, &src_reg); 13216 else 13217 scalar_min_max_arsh(dst_reg, &src_reg); 13218 break; 13219 default: 13220 mark_reg_unknown(env, regs, insn->dst_reg); 13221 break; 13222 } 13223 13224 /* ALU32 ops are zero extended into 64bit register */ 13225 if (alu32) 13226 zext_32_to_64(dst_reg); 13227 reg_bounds_sync(dst_reg); 13228 return 0; 13229 } 13230 13231 /* Handles ALU ops other than BPF_END, BPF_NEG and BPF_MOV: computes new min/max 13232 * and var_off. 13233 */ 13234 static int adjust_reg_min_max_vals(struct bpf_verifier_env *env, 13235 struct bpf_insn *insn) 13236 { 13237 struct bpf_verifier_state *vstate = env->cur_state; 13238 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 13239 struct bpf_reg_state *regs = state->regs, *dst_reg, *src_reg; 13240 struct bpf_reg_state *ptr_reg = NULL, off_reg = {0}; 13241 u8 opcode = BPF_OP(insn->code); 13242 int err; 13243 13244 dst_reg = ®s[insn->dst_reg]; 13245 src_reg = NULL; 13246 if (dst_reg->type != SCALAR_VALUE) 13247 ptr_reg = dst_reg; 13248 else 13249 /* Make sure ID is cleared otherwise dst_reg min/max could be 13250 * incorrectly propagated into other registers by find_equal_scalars() 13251 */ 13252 dst_reg->id = 0; 13253 if (BPF_SRC(insn->code) == BPF_X) { 13254 src_reg = ®s[insn->src_reg]; 13255 if (src_reg->type != SCALAR_VALUE) { 13256 if (dst_reg->type != SCALAR_VALUE) { 13257 /* Combining two pointers by any ALU op yields 13258 * an arbitrary scalar. Disallow all math except 13259 * pointer subtraction 13260 */ 13261 if (opcode == BPF_SUB && env->allow_ptr_leaks) { 13262 mark_reg_unknown(env, regs, insn->dst_reg); 13263 return 0; 13264 } 13265 verbose(env, "R%d pointer %s pointer prohibited\n", 13266 insn->dst_reg, 13267 bpf_alu_string[opcode >> 4]); 13268 return -EACCES; 13269 } else { 13270 /* scalar += pointer 13271 * This is legal, but we have to reverse our 13272 * src/dest handling in computing the range 13273 */ 13274 err = mark_chain_precision(env, insn->dst_reg); 13275 if (err) 13276 return err; 13277 return adjust_ptr_min_max_vals(env, insn, 13278 src_reg, dst_reg); 13279 } 13280 } else if (ptr_reg) { 13281 /* pointer += scalar */ 13282 err = mark_chain_precision(env, insn->src_reg); 13283 if (err) 13284 return err; 13285 return adjust_ptr_min_max_vals(env, insn, 13286 dst_reg, src_reg); 13287 } else if (dst_reg->precise) { 13288 /* if dst_reg is precise, src_reg should be precise as well */ 13289 err = mark_chain_precision(env, insn->src_reg); 13290 if (err) 13291 return err; 13292 } 13293 } else { 13294 /* Pretend the src is a reg with a known value, since we only 13295 * need to be able to read from this state. 13296 */ 13297 off_reg.type = SCALAR_VALUE; 13298 __mark_reg_known(&off_reg, insn->imm); 13299 src_reg = &off_reg; 13300 if (ptr_reg) /* pointer += K */ 13301 return adjust_ptr_min_max_vals(env, insn, 13302 ptr_reg, src_reg); 13303 } 13304 13305 /* Got here implies adding two SCALAR_VALUEs */ 13306 if (WARN_ON_ONCE(ptr_reg)) { 13307 print_verifier_state(env, state, true); 13308 verbose(env, "verifier internal error: unexpected ptr_reg\n"); 13309 return -EINVAL; 13310 } 13311 if (WARN_ON(!src_reg)) { 13312 print_verifier_state(env, state, true); 13313 verbose(env, "verifier internal error: no src_reg\n"); 13314 return -EINVAL; 13315 } 13316 return adjust_scalar_min_max_vals(env, insn, dst_reg, *src_reg); 13317 } 13318 13319 /* check validity of 32-bit and 64-bit arithmetic operations */ 13320 static int check_alu_op(struct bpf_verifier_env *env, struct bpf_insn *insn) 13321 { 13322 struct bpf_reg_state *regs = cur_regs(env); 13323 u8 opcode = BPF_OP(insn->code); 13324 int err; 13325 13326 if (opcode == BPF_END || opcode == BPF_NEG) { 13327 if (opcode == BPF_NEG) { 13328 if (BPF_SRC(insn->code) != BPF_K || 13329 insn->src_reg != BPF_REG_0 || 13330 insn->off != 0 || insn->imm != 0) { 13331 verbose(env, "BPF_NEG uses reserved fields\n"); 13332 return -EINVAL; 13333 } 13334 } else { 13335 if (insn->src_reg != BPF_REG_0 || insn->off != 0 || 13336 (insn->imm != 16 && insn->imm != 32 && insn->imm != 64) || 13337 (BPF_CLASS(insn->code) == BPF_ALU64 && 13338 BPF_SRC(insn->code) != BPF_TO_LE)) { 13339 verbose(env, "BPF_END uses reserved fields\n"); 13340 return -EINVAL; 13341 } 13342 } 13343 13344 /* check src operand */ 13345 err = check_reg_arg(env, insn->dst_reg, SRC_OP); 13346 if (err) 13347 return err; 13348 13349 if (is_pointer_value(env, insn->dst_reg)) { 13350 verbose(env, "R%d pointer arithmetic prohibited\n", 13351 insn->dst_reg); 13352 return -EACCES; 13353 } 13354 13355 /* check dest operand */ 13356 err = check_reg_arg(env, insn->dst_reg, DST_OP); 13357 if (err) 13358 return err; 13359 13360 } else if (opcode == BPF_MOV) { 13361 13362 if (BPF_SRC(insn->code) == BPF_X) { 13363 if (insn->imm != 0) { 13364 verbose(env, "BPF_MOV uses reserved fields\n"); 13365 return -EINVAL; 13366 } 13367 13368 if (BPF_CLASS(insn->code) == BPF_ALU) { 13369 if (insn->off != 0 && insn->off != 8 && insn->off != 16) { 13370 verbose(env, "BPF_MOV uses reserved fields\n"); 13371 return -EINVAL; 13372 } 13373 } else { 13374 if (insn->off != 0 && insn->off != 8 && insn->off != 16 && 13375 insn->off != 32) { 13376 verbose(env, "BPF_MOV uses reserved fields\n"); 13377 return -EINVAL; 13378 } 13379 } 13380 13381 /* check src operand */ 13382 err = check_reg_arg(env, insn->src_reg, SRC_OP); 13383 if (err) 13384 return err; 13385 } else { 13386 if (insn->src_reg != BPF_REG_0 || insn->off != 0) { 13387 verbose(env, "BPF_MOV uses reserved fields\n"); 13388 return -EINVAL; 13389 } 13390 } 13391 13392 /* check dest operand, mark as required later */ 13393 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK); 13394 if (err) 13395 return err; 13396 13397 if (BPF_SRC(insn->code) == BPF_X) { 13398 struct bpf_reg_state *src_reg = regs + insn->src_reg; 13399 struct bpf_reg_state *dst_reg = regs + insn->dst_reg; 13400 bool need_id = src_reg->type == SCALAR_VALUE && !src_reg->id && 13401 !tnum_is_const(src_reg->var_off); 13402 13403 if (BPF_CLASS(insn->code) == BPF_ALU64) { 13404 if (insn->off == 0) { 13405 /* case: R1 = R2 13406 * copy register state to dest reg 13407 */ 13408 if (need_id) 13409 /* Assign src and dst registers the same ID 13410 * that will be used by find_equal_scalars() 13411 * to propagate min/max range. 13412 */ 13413 src_reg->id = ++env->id_gen; 13414 copy_register_state(dst_reg, src_reg); 13415 dst_reg->live |= REG_LIVE_WRITTEN; 13416 dst_reg->subreg_def = DEF_NOT_SUBREG; 13417 } else { 13418 /* case: R1 = (s8, s16 s32)R2 */ 13419 if (is_pointer_value(env, insn->src_reg)) { 13420 verbose(env, 13421 "R%d sign-extension part of pointer\n", 13422 insn->src_reg); 13423 return -EACCES; 13424 } else if (src_reg->type == SCALAR_VALUE) { 13425 bool no_sext; 13426 13427 no_sext = src_reg->umax_value < (1ULL << (insn->off - 1)); 13428 if (no_sext && need_id) 13429 src_reg->id = ++env->id_gen; 13430 copy_register_state(dst_reg, src_reg); 13431 if (!no_sext) 13432 dst_reg->id = 0; 13433 coerce_reg_to_size_sx(dst_reg, insn->off >> 3); 13434 dst_reg->live |= REG_LIVE_WRITTEN; 13435 dst_reg->subreg_def = DEF_NOT_SUBREG; 13436 } else { 13437 mark_reg_unknown(env, regs, insn->dst_reg); 13438 } 13439 } 13440 } else { 13441 /* R1 = (u32) R2 */ 13442 if (is_pointer_value(env, insn->src_reg)) { 13443 verbose(env, 13444 "R%d partial copy of pointer\n", 13445 insn->src_reg); 13446 return -EACCES; 13447 } else if (src_reg->type == SCALAR_VALUE) { 13448 if (insn->off == 0) { 13449 bool is_src_reg_u32 = src_reg->umax_value <= U32_MAX; 13450 13451 if (is_src_reg_u32 && need_id) 13452 src_reg->id = ++env->id_gen; 13453 copy_register_state(dst_reg, src_reg); 13454 /* Make sure ID is cleared if src_reg is not in u32 13455 * range otherwise dst_reg min/max could be incorrectly 13456 * propagated into src_reg by find_equal_scalars() 13457 */ 13458 if (!is_src_reg_u32) 13459 dst_reg->id = 0; 13460 dst_reg->live |= REG_LIVE_WRITTEN; 13461 dst_reg->subreg_def = env->insn_idx + 1; 13462 } else { 13463 /* case: W1 = (s8, s16)W2 */ 13464 bool no_sext = src_reg->umax_value < (1ULL << (insn->off - 1)); 13465 13466 if (no_sext && need_id) 13467 src_reg->id = ++env->id_gen; 13468 copy_register_state(dst_reg, src_reg); 13469 if (!no_sext) 13470 dst_reg->id = 0; 13471 dst_reg->live |= REG_LIVE_WRITTEN; 13472 dst_reg->subreg_def = env->insn_idx + 1; 13473 coerce_subreg_to_size_sx(dst_reg, insn->off >> 3); 13474 } 13475 } else { 13476 mark_reg_unknown(env, regs, 13477 insn->dst_reg); 13478 } 13479 zext_32_to_64(dst_reg); 13480 reg_bounds_sync(dst_reg); 13481 } 13482 } else { 13483 /* case: R = imm 13484 * remember the value we stored into this reg 13485 */ 13486 /* clear any state __mark_reg_known doesn't set */ 13487 mark_reg_unknown(env, regs, insn->dst_reg); 13488 regs[insn->dst_reg].type = SCALAR_VALUE; 13489 if (BPF_CLASS(insn->code) == BPF_ALU64) { 13490 __mark_reg_known(regs + insn->dst_reg, 13491 insn->imm); 13492 } else { 13493 __mark_reg_known(regs + insn->dst_reg, 13494 (u32)insn->imm); 13495 } 13496 } 13497 13498 } else if (opcode > BPF_END) { 13499 verbose(env, "invalid BPF_ALU opcode %x\n", opcode); 13500 return -EINVAL; 13501 13502 } else { /* all other ALU ops: and, sub, xor, add, ... */ 13503 13504 if (BPF_SRC(insn->code) == BPF_X) { 13505 if (insn->imm != 0 || insn->off > 1 || 13506 (insn->off == 1 && opcode != BPF_MOD && opcode != BPF_DIV)) { 13507 verbose(env, "BPF_ALU uses reserved fields\n"); 13508 return -EINVAL; 13509 } 13510 /* check src1 operand */ 13511 err = check_reg_arg(env, insn->src_reg, SRC_OP); 13512 if (err) 13513 return err; 13514 } else { 13515 if (insn->src_reg != BPF_REG_0 || insn->off > 1 || 13516 (insn->off == 1 && opcode != BPF_MOD && opcode != BPF_DIV)) { 13517 verbose(env, "BPF_ALU uses reserved fields\n"); 13518 return -EINVAL; 13519 } 13520 } 13521 13522 /* check src2 operand */ 13523 err = check_reg_arg(env, insn->dst_reg, SRC_OP); 13524 if (err) 13525 return err; 13526 13527 if ((opcode == BPF_MOD || opcode == BPF_DIV) && 13528 BPF_SRC(insn->code) == BPF_K && insn->imm == 0) { 13529 verbose(env, "div by zero\n"); 13530 return -EINVAL; 13531 } 13532 13533 if ((opcode == BPF_LSH || opcode == BPF_RSH || 13534 opcode == BPF_ARSH) && BPF_SRC(insn->code) == BPF_K) { 13535 int size = BPF_CLASS(insn->code) == BPF_ALU64 ? 64 : 32; 13536 13537 if (insn->imm < 0 || insn->imm >= size) { 13538 verbose(env, "invalid shift %d\n", insn->imm); 13539 return -EINVAL; 13540 } 13541 } 13542 13543 /* check dest operand */ 13544 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK); 13545 if (err) 13546 return err; 13547 13548 return adjust_reg_min_max_vals(env, insn); 13549 } 13550 13551 return 0; 13552 } 13553 13554 static void find_good_pkt_pointers(struct bpf_verifier_state *vstate, 13555 struct bpf_reg_state *dst_reg, 13556 enum bpf_reg_type type, 13557 bool range_right_open) 13558 { 13559 struct bpf_func_state *state; 13560 struct bpf_reg_state *reg; 13561 int new_range; 13562 13563 if (dst_reg->off < 0 || 13564 (dst_reg->off == 0 && range_right_open)) 13565 /* This doesn't give us any range */ 13566 return; 13567 13568 if (dst_reg->umax_value > MAX_PACKET_OFF || 13569 dst_reg->umax_value + dst_reg->off > MAX_PACKET_OFF) 13570 /* Risk of overflow. For instance, ptr + (1<<63) may be less 13571 * than pkt_end, but that's because it's also less than pkt. 13572 */ 13573 return; 13574 13575 new_range = dst_reg->off; 13576 if (range_right_open) 13577 new_range++; 13578 13579 /* Examples for register markings: 13580 * 13581 * pkt_data in dst register: 13582 * 13583 * r2 = r3; 13584 * r2 += 8; 13585 * if (r2 > pkt_end) goto <handle exception> 13586 * <access okay> 13587 * 13588 * r2 = r3; 13589 * r2 += 8; 13590 * if (r2 < pkt_end) goto <access okay> 13591 * <handle exception> 13592 * 13593 * Where: 13594 * r2 == dst_reg, pkt_end == src_reg 13595 * r2=pkt(id=n,off=8,r=0) 13596 * r3=pkt(id=n,off=0,r=0) 13597 * 13598 * pkt_data in src register: 13599 * 13600 * r2 = r3; 13601 * r2 += 8; 13602 * if (pkt_end >= r2) goto <access okay> 13603 * <handle exception> 13604 * 13605 * r2 = r3; 13606 * r2 += 8; 13607 * if (pkt_end <= r2) goto <handle exception> 13608 * <access okay> 13609 * 13610 * Where: 13611 * pkt_end == dst_reg, r2 == src_reg 13612 * r2=pkt(id=n,off=8,r=0) 13613 * r3=pkt(id=n,off=0,r=0) 13614 * 13615 * Find register r3 and mark its range as r3=pkt(id=n,off=0,r=8) 13616 * or r3=pkt(id=n,off=0,r=8-1), so that range of bytes [r3, r3 + 8) 13617 * and [r3, r3 + 8-1) respectively is safe to access depending on 13618 * the check. 13619 */ 13620 13621 /* If our ids match, then we must have the same max_value. And we 13622 * don't care about the other reg's fixed offset, since if it's too big 13623 * the range won't allow anything. 13624 * dst_reg->off is known < MAX_PACKET_OFF, therefore it fits in a u16. 13625 */ 13626 bpf_for_each_reg_in_vstate(vstate, state, reg, ({ 13627 if (reg->type == type && reg->id == dst_reg->id) 13628 /* keep the maximum range already checked */ 13629 reg->range = max(reg->range, new_range); 13630 })); 13631 } 13632 13633 static int is_branch32_taken(struct bpf_reg_state *reg, u32 val, u8 opcode) 13634 { 13635 struct tnum subreg = tnum_subreg(reg->var_off); 13636 s32 sval = (s32)val; 13637 13638 switch (opcode) { 13639 case BPF_JEQ: 13640 if (tnum_is_const(subreg)) 13641 return !!tnum_equals_const(subreg, val); 13642 else if (val < reg->u32_min_value || val > reg->u32_max_value) 13643 return 0; 13644 break; 13645 case BPF_JNE: 13646 if (tnum_is_const(subreg)) 13647 return !tnum_equals_const(subreg, val); 13648 else if (val < reg->u32_min_value || val > reg->u32_max_value) 13649 return 1; 13650 break; 13651 case BPF_JSET: 13652 if ((~subreg.mask & subreg.value) & val) 13653 return 1; 13654 if (!((subreg.mask | subreg.value) & val)) 13655 return 0; 13656 break; 13657 case BPF_JGT: 13658 if (reg->u32_min_value > val) 13659 return 1; 13660 else if (reg->u32_max_value <= val) 13661 return 0; 13662 break; 13663 case BPF_JSGT: 13664 if (reg->s32_min_value > sval) 13665 return 1; 13666 else if (reg->s32_max_value <= sval) 13667 return 0; 13668 break; 13669 case BPF_JLT: 13670 if (reg->u32_max_value < val) 13671 return 1; 13672 else if (reg->u32_min_value >= val) 13673 return 0; 13674 break; 13675 case BPF_JSLT: 13676 if (reg->s32_max_value < sval) 13677 return 1; 13678 else if (reg->s32_min_value >= sval) 13679 return 0; 13680 break; 13681 case BPF_JGE: 13682 if (reg->u32_min_value >= val) 13683 return 1; 13684 else if (reg->u32_max_value < val) 13685 return 0; 13686 break; 13687 case BPF_JSGE: 13688 if (reg->s32_min_value >= sval) 13689 return 1; 13690 else if (reg->s32_max_value < sval) 13691 return 0; 13692 break; 13693 case BPF_JLE: 13694 if (reg->u32_max_value <= val) 13695 return 1; 13696 else if (reg->u32_min_value > val) 13697 return 0; 13698 break; 13699 case BPF_JSLE: 13700 if (reg->s32_max_value <= sval) 13701 return 1; 13702 else if (reg->s32_min_value > sval) 13703 return 0; 13704 break; 13705 } 13706 13707 return -1; 13708 } 13709 13710 13711 static int is_branch64_taken(struct bpf_reg_state *reg, u64 val, u8 opcode) 13712 { 13713 s64 sval = (s64)val; 13714 13715 switch (opcode) { 13716 case BPF_JEQ: 13717 if (tnum_is_const(reg->var_off)) 13718 return !!tnum_equals_const(reg->var_off, val); 13719 else if (val < reg->umin_value || val > reg->umax_value) 13720 return 0; 13721 break; 13722 case BPF_JNE: 13723 if (tnum_is_const(reg->var_off)) 13724 return !tnum_equals_const(reg->var_off, val); 13725 else if (val < reg->umin_value || val > reg->umax_value) 13726 return 1; 13727 break; 13728 case BPF_JSET: 13729 if ((~reg->var_off.mask & reg->var_off.value) & val) 13730 return 1; 13731 if (!((reg->var_off.mask | reg->var_off.value) & val)) 13732 return 0; 13733 break; 13734 case BPF_JGT: 13735 if (reg->umin_value > val) 13736 return 1; 13737 else if (reg->umax_value <= val) 13738 return 0; 13739 break; 13740 case BPF_JSGT: 13741 if (reg->smin_value > sval) 13742 return 1; 13743 else if (reg->smax_value <= sval) 13744 return 0; 13745 break; 13746 case BPF_JLT: 13747 if (reg->umax_value < val) 13748 return 1; 13749 else if (reg->umin_value >= val) 13750 return 0; 13751 break; 13752 case BPF_JSLT: 13753 if (reg->smax_value < sval) 13754 return 1; 13755 else if (reg->smin_value >= sval) 13756 return 0; 13757 break; 13758 case BPF_JGE: 13759 if (reg->umin_value >= val) 13760 return 1; 13761 else if (reg->umax_value < val) 13762 return 0; 13763 break; 13764 case BPF_JSGE: 13765 if (reg->smin_value >= sval) 13766 return 1; 13767 else if (reg->smax_value < sval) 13768 return 0; 13769 break; 13770 case BPF_JLE: 13771 if (reg->umax_value <= val) 13772 return 1; 13773 else if (reg->umin_value > val) 13774 return 0; 13775 break; 13776 case BPF_JSLE: 13777 if (reg->smax_value <= sval) 13778 return 1; 13779 else if (reg->smin_value > sval) 13780 return 0; 13781 break; 13782 } 13783 13784 return -1; 13785 } 13786 13787 /* compute branch direction of the expression "if (reg opcode val) goto target;" 13788 * and return: 13789 * 1 - branch will be taken and "goto target" will be executed 13790 * 0 - branch will not be taken and fall-through to next insn 13791 * -1 - unknown. Example: "if (reg < 5)" is unknown when register value 13792 * range [0,10] 13793 */ 13794 static int is_branch_taken(struct bpf_reg_state *reg, u64 val, u8 opcode, 13795 bool is_jmp32) 13796 { 13797 if (__is_pointer_value(false, reg)) { 13798 if (!reg_not_null(reg)) 13799 return -1; 13800 13801 /* If pointer is valid tests against zero will fail so we can 13802 * use this to direct branch taken. 13803 */ 13804 if (val != 0) 13805 return -1; 13806 13807 switch (opcode) { 13808 case BPF_JEQ: 13809 return 0; 13810 case BPF_JNE: 13811 return 1; 13812 default: 13813 return -1; 13814 } 13815 } 13816 13817 if (is_jmp32) 13818 return is_branch32_taken(reg, val, opcode); 13819 return is_branch64_taken(reg, val, opcode); 13820 } 13821 13822 static int flip_opcode(u32 opcode) 13823 { 13824 /* How can we transform "a <op> b" into "b <op> a"? */ 13825 static const u8 opcode_flip[16] = { 13826 /* these stay the same */ 13827 [BPF_JEQ >> 4] = BPF_JEQ, 13828 [BPF_JNE >> 4] = BPF_JNE, 13829 [BPF_JSET >> 4] = BPF_JSET, 13830 /* these swap "lesser" and "greater" (L and G in the opcodes) */ 13831 [BPF_JGE >> 4] = BPF_JLE, 13832 [BPF_JGT >> 4] = BPF_JLT, 13833 [BPF_JLE >> 4] = BPF_JGE, 13834 [BPF_JLT >> 4] = BPF_JGT, 13835 [BPF_JSGE >> 4] = BPF_JSLE, 13836 [BPF_JSGT >> 4] = BPF_JSLT, 13837 [BPF_JSLE >> 4] = BPF_JSGE, 13838 [BPF_JSLT >> 4] = BPF_JSGT 13839 }; 13840 return opcode_flip[opcode >> 4]; 13841 } 13842 13843 static int is_pkt_ptr_branch_taken(struct bpf_reg_state *dst_reg, 13844 struct bpf_reg_state *src_reg, 13845 u8 opcode) 13846 { 13847 struct bpf_reg_state *pkt; 13848 13849 if (src_reg->type == PTR_TO_PACKET_END) { 13850 pkt = dst_reg; 13851 } else if (dst_reg->type == PTR_TO_PACKET_END) { 13852 pkt = src_reg; 13853 opcode = flip_opcode(opcode); 13854 } else { 13855 return -1; 13856 } 13857 13858 if (pkt->range >= 0) 13859 return -1; 13860 13861 switch (opcode) { 13862 case BPF_JLE: 13863 /* pkt <= pkt_end */ 13864 fallthrough; 13865 case BPF_JGT: 13866 /* pkt > pkt_end */ 13867 if (pkt->range == BEYOND_PKT_END) 13868 /* pkt has at last one extra byte beyond pkt_end */ 13869 return opcode == BPF_JGT; 13870 break; 13871 case BPF_JLT: 13872 /* pkt < pkt_end */ 13873 fallthrough; 13874 case BPF_JGE: 13875 /* pkt >= pkt_end */ 13876 if (pkt->range == BEYOND_PKT_END || pkt->range == AT_PKT_END) 13877 return opcode == BPF_JGE; 13878 break; 13879 } 13880 return -1; 13881 } 13882 13883 /* Adjusts the register min/max values in the case that the dst_reg is the 13884 * variable register that we are working on, and src_reg is a constant or we're 13885 * simply doing a BPF_K check. 13886 * In JEQ/JNE cases we also adjust the var_off values. 13887 */ 13888 static void reg_set_min_max(struct bpf_reg_state *true_reg, 13889 struct bpf_reg_state *false_reg, 13890 u64 val, u32 val32, 13891 u8 opcode, bool is_jmp32) 13892 { 13893 struct tnum false_32off = tnum_subreg(false_reg->var_off); 13894 struct tnum false_64off = false_reg->var_off; 13895 struct tnum true_32off = tnum_subreg(true_reg->var_off); 13896 struct tnum true_64off = true_reg->var_off; 13897 s64 sval = (s64)val; 13898 s32 sval32 = (s32)val32; 13899 13900 /* If the dst_reg is a pointer, we can't learn anything about its 13901 * variable offset from the compare (unless src_reg were a pointer into 13902 * the same object, but we don't bother with that. 13903 * Since false_reg and true_reg have the same type by construction, we 13904 * only need to check one of them for pointerness. 13905 */ 13906 if (__is_pointer_value(false, false_reg)) 13907 return; 13908 13909 switch (opcode) { 13910 /* JEQ/JNE comparison doesn't change the register equivalence. 13911 * 13912 * r1 = r2; 13913 * if (r1 == 42) goto label; 13914 * ... 13915 * label: // here both r1 and r2 are known to be 42. 13916 * 13917 * Hence when marking register as known preserve it's ID. 13918 */ 13919 case BPF_JEQ: 13920 if (is_jmp32) { 13921 __mark_reg32_known(true_reg, val32); 13922 true_32off = tnum_subreg(true_reg->var_off); 13923 } else { 13924 ___mark_reg_known(true_reg, val); 13925 true_64off = true_reg->var_off; 13926 } 13927 break; 13928 case BPF_JNE: 13929 if (is_jmp32) { 13930 __mark_reg32_known(false_reg, val32); 13931 false_32off = tnum_subreg(false_reg->var_off); 13932 } else { 13933 ___mark_reg_known(false_reg, val); 13934 false_64off = false_reg->var_off; 13935 } 13936 break; 13937 case BPF_JSET: 13938 if (is_jmp32) { 13939 false_32off = tnum_and(false_32off, tnum_const(~val32)); 13940 if (is_power_of_2(val32)) 13941 true_32off = tnum_or(true_32off, 13942 tnum_const(val32)); 13943 } else { 13944 false_64off = tnum_and(false_64off, tnum_const(~val)); 13945 if (is_power_of_2(val)) 13946 true_64off = tnum_or(true_64off, 13947 tnum_const(val)); 13948 } 13949 break; 13950 case BPF_JGE: 13951 case BPF_JGT: 13952 { 13953 if (is_jmp32) { 13954 u32 false_umax = opcode == BPF_JGT ? val32 : val32 - 1; 13955 u32 true_umin = opcode == BPF_JGT ? val32 + 1 : val32; 13956 13957 false_reg->u32_max_value = min(false_reg->u32_max_value, 13958 false_umax); 13959 true_reg->u32_min_value = max(true_reg->u32_min_value, 13960 true_umin); 13961 } else { 13962 u64 false_umax = opcode == BPF_JGT ? val : val - 1; 13963 u64 true_umin = opcode == BPF_JGT ? val + 1 : val; 13964 13965 false_reg->umax_value = min(false_reg->umax_value, false_umax); 13966 true_reg->umin_value = max(true_reg->umin_value, true_umin); 13967 } 13968 break; 13969 } 13970 case BPF_JSGE: 13971 case BPF_JSGT: 13972 { 13973 if (is_jmp32) { 13974 s32 false_smax = opcode == BPF_JSGT ? sval32 : sval32 - 1; 13975 s32 true_smin = opcode == BPF_JSGT ? sval32 + 1 : sval32; 13976 13977 false_reg->s32_max_value = min(false_reg->s32_max_value, false_smax); 13978 true_reg->s32_min_value = max(true_reg->s32_min_value, true_smin); 13979 } else { 13980 s64 false_smax = opcode == BPF_JSGT ? sval : sval - 1; 13981 s64 true_smin = opcode == BPF_JSGT ? sval + 1 : sval; 13982 13983 false_reg->smax_value = min(false_reg->smax_value, false_smax); 13984 true_reg->smin_value = max(true_reg->smin_value, true_smin); 13985 } 13986 break; 13987 } 13988 case BPF_JLE: 13989 case BPF_JLT: 13990 { 13991 if (is_jmp32) { 13992 u32 false_umin = opcode == BPF_JLT ? val32 : val32 + 1; 13993 u32 true_umax = opcode == BPF_JLT ? val32 - 1 : val32; 13994 13995 false_reg->u32_min_value = max(false_reg->u32_min_value, 13996 false_umin); 13997 true_reg->u32_max_value = min(true_reg->u32_max_value, 13998 true_umax); 13999 } else { 14000 u64 false_umin = opcode == BPF_JLT ? val : val + 1; 14001 u64 true_umax = opcode == BPF_JLT ? val - 1 : val; 14002 14003 false_reg->umin_value = max(false_reg->umin_value, false_umin); 14004 true_reg->umax_value = min(true_reg->umax_value, true_umax); 14005 } 14006 break; 14007 } 14008 case BPF_JSLE: 14009 case BPF_JSLT: 14010 { 14011 if (is_jmp32) { 14012 s32 false_smin = opcode == BPF_JSLT ? sval32 : sval32 + 1; 14013 s32 true_smax = opcode == BPF_JSLT ? sval32 - 1 : sval32; 14014 14015 false_reg->s32_min_value = max(false_reg->s32_min_value, false_smin); 14016 true_reg->s32_max_value = min(true_reg->s32_max_value, true_smax); 14017 } else { 14018 s64 false_smin = opcode == BPF_JSLT ? sval : sval + 1; 14019 s64 true_smax = opcode == BPF_JSLT ? sval - 1 : sval; 14020 14021 false_reg->smin_value = max(false_reg->smin_value, false_smin); 14022 true_reg->smax_value = min(true_reg->smax_value, true_smax); 14023 } 14024 break; 14025 } 14026 default: 14027 return; 14028 } 14029 14030 if (is_jmp32) { 14031 false_reg->var_off = tnum_or(tnum_clear_subreg(false_64off), 14032 tnum_subreg(false_32off)); 14033 true_reg->var_off = tnum_or(tnum_clear_subreg(true_64off), 14034 tnum_subreg(true_32off)); 14035 __reg_combine_32_into_64(false_reg); 14036 __reg_combine_32_into_64(true_reg); 14037 } else { 14038 false_reg->var_off = false_64off; 14039 true_reg->var_off = true_64off; 14040 __reg_combine_64_into_32(false_reg); 14041 __reg_combine_64_into_32(true_reg); 14042 } 14043 } 14044 14045 /* Same as above, but for the case that dst_reg holds a constant and src_reg is 14046 * the variable reg. 14047 */ 14048 static void reg_set_min_max_inv(struct bpf_reg_state *true_reg, 14049 struct bpf_reg_state *false_reg, 14050 u64 val, u32 val32, 14051 u8 opcode, bool is_jmp32) 14052 { 14053 opcode = flip_opcode(opcode); 14054 /* This uses zero as "not present in table"; luckily the zero opcode, 14055 * BPF_JA, can't get here. 14056 */ 14057 if (opcode) 14058 reg_set_min_max(true_reg, false_reg, val, val32, opcode, is_jmp32); 14059 } 14060 14061 /* Regs are known to be equal, so intersect their min/max/var_off */ 14062 static void __reg_combine_min_max(struct bpf_reg_state *src_reg, 14063 struct bpf_reg_state *dst_reg) 14064 { 14065 src_reg->umin_value = dst_reg->umin_value = max(src_reg->umin_value, 14066 dst_reg->umin_value); 14067 src_reg->umax_value = dst_reg->umax_value = min(src_reg->umax_value, 14068 dst_reg->umax_value); 14069 src_reg->smin_value = dst_reg->smin_value = max(src_reg->smin_value, 14070 dst_reg->smin_value); 14071 src_reg->smax_value = dst_reg->smax_value = min(src_reg->smax_value, 14072 dst_reg->smax_value); 14073 src_reg->var_off = dst_reg->var_off = tnum_intersect(src_reg->var_off, 14074 dst_reg->var_off); 14075 reg_bounds_sync(src_reg); 14076 reg_bounds_sync(dst_reg); 14077 } 14078 14079 static void reg_combine_min_max(struct bpf_reg_state *true_src, 14080 struct bpf_reg_state *true_dst, 14081 struct bpf_reg_state *false_src, 14082 struct bpf_reg_state *false_dst, 14083 u8 opcode) 14084 { 14085 switch (opcode) { 14086 case BPF_JEQ: 14087 __reg_combine_min_max(true_src, true_dst); 14088 break; 14089 case BPF_JNE: 14090 __reg_combine_min_max(false_src, false_dst); 14091 break; 14092 } 14093 } 14094 14095 static void mark_ptr_or_null_reg(struct bpf_func_state *state, 14096 struct bpf_reg_state *reg, u32 id, 14097 bool is_null) 14098 { 14099 if (type_may_be_null(reg->type) && reg->id == id && 14100 (is_rcu_reg(reg) || !WARN_ON_ONCE(!reg->id))) { 14101 /* Old offset (both fixed and variable parts) should have been 14102 * known-zero, because we don't allow pointer arithmetic on 14103 * pointers that might be NULL. If we see this happening, don't 14104 * convert the register. 14105 * 14106 * But in some cases, some helpers that return local kptrs 14107 * advance offset for the returned pointer. In those cases, it 14108 * is fine to expect to see reg->off. 14109 */ 14110 if (WARN_ON_ONCE(reg->smin_value || reg->smax_value || !tnum_equals_const(reg->var_off, 0))) 14111 return; 14112 if (!(type_is_ptr_alloc_obj(reg->type) || type_is_non_owning_ref(reg->type)) && 14113 WARN_ON_ONCE(reg->off)) 14114 return; 14115 14116 if (is_null) { 14117 reg->type = SCALAR_VALUE; 14118 /* We don't need id and ref_obj_id from this point 14119 * onwards anymore, thus we should better reset it, 14120 * so that state pruning has chances to take effect. 14121 */ 14122 reg->id = 0; 14123 reg->ref_obj_id = 0; 14124 14125 return; 14126 } 14127 14128 mark_ptr_not_null_reg(reg); 14129 14130 if (!reg_may_point_to_spin_lock(reg)) { 14131 /* For not-NULL ptr, reg->ref_obj_id will be reset 14132 * in release_reference(). 14133 * 14134 * reg->id is still used by spin_lock ptr. Other 14135 * than spin_lock ptr type, reg->id can be reset. 14136 */ 14137 reg->id = 0; 14138 } 14139 } 14140 } 14141 14142 /* The logic is similar to find_good_pkt_pointers(), both could eventually 14143 * be folded together at some point. 14144 */ 14145 static void mark_ptr_or_null_regs(struct bpf_verifier_state *vstate, u32 regno, 14146 bool is_null) 14147 { 14148 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 14149 struct bpf_reg_state *regs = state->regs, *reg; 14150 u32 ref_obj_id = regs[regno].ref_obj_id; 14151 u32 id = regs[regno].id; 14152 14153 if (ref_obj_id && ref_obj_id == id && is_null) 14154 /* regs[regno] is in the " == NULL" branch. 14155 * No one could have freed the reference state before 14156 * doing the NULL check. 14157 */ 14158 WARN_ON_ONCE(release_reference_state(state, id)); 14159 14160 bpf_for_each_reg_in_vstate(vstate, state, reg, ({ 14161 mark_ptr_or_null_reg(state, reg, id, is_null); 14162 })); 14163 } 14164 14165 static bool try_match_pkt_pointers(const struct bpf_insn *insn, 14166 struct bpf_reg_state *dst_reg, 14167 struct bpf_reg_state *src_reg, 14168 struct bpf_verifier_state *this_branch, 14169 struct bpf_verifier_state *other_branch) 14170 { 14171 if (BPF_SRC(insn->code) != BPF_X) 14172 return false; 14173 14174 /* Pointers are always 64-bit. */ 14175 if (BPF_CLASS(insn->code) == BPF_JMP32) 14176 return false; 14177 14178 switch (BPF_OP(insn->code)) { 14179 case BPF_JGT: 14180 if ((dst_reg->type == PTR_TO_PACKET && 14181 src_reg->type == PTR_TO_PACKET_END) || 14182 (dst_reg->type == PTR_TO_PACKET_META && 14183 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) { 14184 /* pkt_data' > pkt_end, pkt_meta' > pkt_data */ 14185 find_good_pkt_pointers(this_branch, dst_reg, 14186 dst_reg->type, false); 14187 mark_pkt_end(other_branch, insn->dst_reg, true); 14188 } else if ((dst_reg->type == PTR_TO_PACKET_END && 14189 src_reg->type == PTR_TO_PACKET) || 14190 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) && 14191 src_reg->type == PTR_TO_PACKET_META)) { 14192 /* pkt_end > pkt_data', pkt_data > pkt_meta' */ 14193 find_good_pkt_pointers(other_branch, src_reg, 14194 src_reg->type, true); 14195 mark_pkt_end(this_branch, insn->src_reg, false); 14196 } else { 14197 return false; 14198 } 14199 break; 14200 case BPF_JLT: 14201 if ((dst_reg->type == PTR_TO_PACKET && 14202 src_reg->type == PTR_TO_PACKET_END) || 14203 (dst_reg->type == PTR_TO_PACKET_META && 14204 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) { 14205 /* pkt_data' < pkt_end, pkt_meta' < pkt_data */ 14206 find_good_pkt_pointers(other_branch, dst_reg, 14207 dst_reg->type, true); 14208 mark_pkt_end(this_branch, insn->dst_reg, false); 14209 } else if ((dst_reg->type == PTR_TO_PACKET_END && 14210 src_reg->type == PTR_TO_PACKET) || 14211 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) && 14212 src_reg->type == PTR_TO_PACKET_META)) { 14213 /* pkt_end < pkt_data', pkt_data > pkt_meta' */ 14214 find_good_pkt_pointers(this_branch, src_reg, 14215 src_reg->type, false); 14216 mark_pkt_end(other_branch, insn->src_reg, true); 14217 } else { 14218 return false; 14219 } 14220 break; 14221 case BPF_JGE: 14222 if ((dst_reg->type == PTR_TO_PACKET && 14223 src_reg->type == PTR_TO_PACKET_END) || 14224 (dst_reg->type == PTR_TO_PACKET_META && 14225 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) { 14226 /* pkt_data' >= pkt_end, pkt_meta' >= pkt_data */ 14227 find_good_pkt_pointers(this_branch, dst_reg, 14228 dst_reg->type, true); 14229 mark_pkt_end(other_branch, insn->dst_reg, false); 14230 } else if ((dst_reg->type == PTR_TO_PACKET_END && 14231 src_reg->type == PTR_TO_PACKET) || 14232 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) && 14233 src_reg->type == PTR_TO_PACKET_META)) { 14234 /* pkt_end >= pkt_data', pkt_data >= pkt_meta' */ 14235 find_good_pkt_pointers(other_branch, src_reg, 14236 src_reg->type, false); 14237 mark_pkt_end(this_branch, insn->src_reg, true); 14238 } else { 14239 return false; 14240 } 14241 break; 14242 case BPF_JLE: 14243 if ((dst_reg->type == PTR_TO_PACKET && 14244 src_reg->type == PTR_TO_PACKET_END) || 14245 (dst_reg->type == PTR_TO_PACKET_META && 14246 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) { 14247 /* pkt_data' <= pkt_end, pkt_meta' <= pkt_data */ 14248 find_good_pkt_pointers(other_branch, dst_reg, 14249 dst_reg->type, false); 14250 mark_pkt_end(this_branch, insn->dst_reg, true); 14251 } else if ((dst_reg->type == PTR_TO_PACKET_END && 14252 src_reg->type == PTR_TO_PACKET) || 14253 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) && 14254 src_reg->type == PTR_TO_PACKET_META)) { 14255 /* pkt_end <= pkt_data', pkt_data <= pkt_meta' */ 14256 find_good_pkt_pointers(this_branch, src_reg, 14257 src_reg->type, true); 14258 mark_pkt_end(other_branch, insn->src_reg, false); 14259 } else { 14260 return false; 14261 } 14262 break; 14263 default: 14264 return false; 14265 } 14266 14267 return true; 14268 } 14269 14270 static void find_equal_scalars(struct bpf_verifier_state *vstate, 14271 struct bpf_reg_state *known_reg) 14272 { 14273 struct bpf_func_state *state; 14274 struct bpf_reg_state *reg; 14275 14276 bpf_for_each_reg_in_vstate(vstate, state, reg, ({ 14277 if (reg->type == SCALAR_VALUE && reg->id == known_reg->id) 14278 copy_register_state(reg, known_reg); 14279 })); 14280 } 14281 14282 static int check_cond_jmp_op(struct bpf_verifier_env *env, 14283 struct bpf_insn *insn, int *insn_idx) 14284 { 14285 struct bpf_verifier_state *this_branch = env->cur_state; 14286 struct bpf_verifier_state *other_branch; 14287 struct bpf_reg_state *regs = this_branch->frame[this_branch->curframe]->regs; 14288 struct bpf_reg_state *dst_reg, *other_branch_regs, *src_reg = NULL; 14289 struct bpf_reg_state *eq_branch_regs; 14290 u8 opcode = BPF_OP(insn->code); 14291 bool is_jmp32; 14292 int pred = -1; 14293 int err; 14294 14295 /* Only conditional jumps are expected to reach here. */ 14296 if (opcode == BPF_JA || opcode > BPF_JSLE) { 14297 verbose(env, "invalid BPF_JMP/JMP32 opcode %x\n", opcode); 14298 return -EINVAL; 14299 } 14300 14301 /* check src2 operand */ 14302 err = check_reg_arg(env, insn->dst_reg, SRC_OP); 14303 if (err) 14304 return err; 14305 14306 dst_reg = ®s[insn->dst_reg]; 14307 if (BPF_SRC(insn->code) == BPF_X) { 14308 if (insn->imm != 0) { 14309 verbose(env, "BPF_JMP/JMP32 uses reserved fields\n"); 14310 return -EINVAL; 14311 } 14312 14313 /* check src1 operand */ 14314 err = check_reg_arg(env, insn->src_reg, SRC_OP); 14315 if (err) 14316 return err; 14317 14318 src_reg = ®s[insn->src_reg]; 14319 if (!(reg_is_pkt_pointer_any(dst_reg) && reg_is_pkt_pointer_any(src_reg)) && 14320 is_pointer_value(env, insn->src_reg)) { 14321 verbose(env, "R%d pointer comparison prohibited\n", 14322 insn->src_reg); 14323 return -EACCES; 14324 } 14325 } else { 14326 if (insn->src_reg != BPF_REG_0) { 14327 verbose(env, "BPF_JMP/JMP32 uses reserved fields\n"); 14328 return -EINVAL; 14329 } 14330 } 14331 14332 is_jmp32 = BPF_CLASS(insn->code) == BPF_JMP32; 14333 14334 if (BPF_SRC(insn->code) == BPF_K) { 14335 pred = is_branch_taken(dst_reg, insn->imm, opcode, is_jmp32); 14336 } else if (src_reg->type == SCALAR_VALUE && 14337 is_jmp32 && tnum_is_const(tnum_subreg(src_reg->var_off))) { 14338 pred = is_branch_taken(dst_reg, 14339 tnum_subreg(src_reg->var_off).value, 14340 opcode, 14341 is_jmp32); 14342 } else if (src_reg->type == SCALAR_VALUE && 14343 !is_jmp32 && tnum_is_const(src_reg->var_off)) { 14344 pred = is_branch_taken(dst_reg, 14345 src_reg->var_off.value, 14346 opcode, 14347 is_jmp32); 14348 } else if (dst_reg->type == SCALAR_VALUE && 14349 is_jmp32 && tnum_is_const(tnum_subreg(dst_reg->var_off))) { 14350 pred = is_branch_taken(src_reg, 14351 tnum_subreg(dst_reg->var_off).value, 14352 flip_opcode(opcode), 14353 is_jmp32); 14354 } else if (dst_reg->type == SCALAR_VALUE && 14355 !is_jmp32 && tnum_is_const(dst_reg->var_off)) { 14356 pred = is_branch_taken(src_reg, 14357 dst_reg->var_off.value, 14358 flip_opcode(opcode), 14359 is_jmp32); 14360 } else if (reg_is_pkt_pointer_any(dst_reg) && 14361 reg_is_pkt_pointer_any(src_reg) && 14362 !is_jmp32) { 14363 pred = is_pkt_ptr_branch_taken(dst_reg, src_reg, opcode); 14364 } 14365 14366 if (pred >= 0) { 14367 /* If we get here with a dst_reg pointer type it is because 14368 * above is_branch_taken() special cased the 0 comparison. 14369 */ 14370 if (!__is_pointer_value(false, dst_reg)) 14371 err = mark_chain_precision(env, insn->dst_reg); 14372 if (BPF_SRC(insn->code) == BPF_X && !err && 14373 !__is_pointer_value(false, src_reg)) 14374 err = mark_chain_precision(env, insn->src_reg); 14375 if (err) 14376 return err; 14377 } 14378 14379 if (pred == 1) { 14380 /* Only follow the goto, ignore fall-through. If needed, push 14381 * the fall-through branch for simulation under speculative 14382 * execution. 14383 */ 14384 if (!env->bypass_spec_v1 && 14385 !sanitize_speculative_path(env, insn, *insn_idx + 1, 14386 *insn_idx)) 14387 return -EFAULT; 14388 *insn_idx += insn->off; 14389 return 0; 14390 } else if (pred == 0) { 14391 /* Only follow the fall-through branch, since that's where the 14392 * program will go. If needed, push the goto branch for 14393 * simulation under speculative execution. 14394 */ 14395 if (!env->bypass_spec_v1 && 14396 !sanitize_speculative_path(env, insn, 14397 *insn_idx + insn->off + 1, 14398 *insn_idx)) 14399 return -EFAULT; 14400 return 0; 14401 } 14402 14403 other_branch = push_stack(env, *insn_idx + insn->off + 1, *insn_idx, 14404 false); 14405 if (!other_branch) 14406 return -EFAULT; 14407 other_branch_regs = other_branch->frame[other_branch->curframe]->regs; 14408 14409 /* detect if we are comparing against a constant value so we can adjust 14410 * our min/max values for our dst register. 14411 * this is only legit if both are scalars (or pointers to the same 14412 * object, I suppose, see the PTR_MAYBE_NULL related if block below), 14413 * because otherwise the different base pointers mean the offsets aren't 14414 * comparable. 14415 */ 14416 if (BPF_SRC(insn->code) == BPF_X) { 14417 struct bpf_reg_state *src_reg = ®s[insn->src_reg]; 14418 14419 if (dst_reg->type == SCALAR_VALUE && 14420 src_reg->type == SCALAR_VALUE) { 14421 if (tnum_is_const(src_reg->var_off) || 14422 (is_jmp32 && 14423 tnum_is_const(tnum_subreg(src_reg->var_off)))) 14424 reg_set_min_max(&other_branch_regs[insn->dst_reg], 14425 dst_reg, 14426 src_reg->var_off.value, 14427 tnum_subreg(src_reg->var_off).value, 14428 opcode, is_jmp32); 14429 else if (tnum_is_const(dst_reg->var_off) || 14430 (is_jmp32 && 14431 tnum_is_const(tnum_subreg(dst_reg->var_off)))) 14432 reg_set_min_max_inv(&other_branch_regs[insn->src_reg], 14433 src_reg, 14434 dst_reg->var_off.value, 14435 tnum_subreg(dst_reg->var_off).value, 14436 opcode, is_jmp32); 14437 else if (!is_jmp32 && 14438 (opcode == BPF_JEQ || opcode == BPF_JNE)) 14439 /* Comparing for equality, we can combine knowledge */ 14440 reg_combine_min_max(&other_branch_regs[insn->src_reg], 14441 &other_branch_regs[insn->dst_reg], 14442 src_reg, dst_reg, opcode); 14443 if (src_reg->id && 14444 !WARN_ON_ONCE(src_reg->id != other_branch_regs[insn->src_reg].id)) { 14445 find_equal_scalars(this_branch, src_reg); 14446 find_equal_scalars(other_branch, &other_branch_regs[insn->src_reg]); 14447 } 14448 14449 } 14450 } else if (dst_reg->type == SCALAR_VALUE) { 14451 reg_set_min_max(&other_branch_regs[insn->dst_reg], 14452 dst_reg, insn->imm, (u32)insn->imm, 14453 opcode, is_jmp32); 14454 } 14455 14456 if (dst_reg->type == SCALAR_VALUE && dst_reg->id && 14457 !WARN_ON_ONCE(dst_reg->id != other_branch_regs[insn->dst_reg].id)) { 14458 find_equal_scalars(this_branch, dst_reg); 14459 find_equal_scalars(other_branch, &other_branch_regs[insn->dst_reg]); 14460 } 14461 14462 /* if one pointer register is compared to another pointer 14463 * register check if PTR_MAYBE_NULL could be lifted. 14464 * E.g. register A - maybe null 14465 * register B - not null 14466 * for JNE A, B, ... - A is not null in the false branch; 14467 * for JEQ A, B, ... - A is not null in the true branch. 14468 * 14469 * Since PTR_TO_BTF_ID points to a kernel struct that does 14470 * not need to be null checked by the BPF program, i.e., 14471 * could be null even without PTR_MAYBE_NULL marking, so 14472 * only propagate nullness when neither reg is that type. 14473 */ 14474 if (!is_jmp32 && BPF_SRC(insn->code) == BPF_X && 14475 __is_pointer_value(false, src_reg) && __is_pointer_value(false, dst_reg) && 14476 type_may_be_null(src_reg->type) != type_may_be_null(dst_reg->type) && 14477 base_type(src_reg->type) != PTR_TO_BTF_ID && 14478 base_type(dst_reg->type) != PTR_TO_BTF_ID) { 14479 eq_branch_regs = NULL; 14480 switch (opcode) { 14481 case BPF_JEQ: 14482 eq_branch_regs = other_branch_regs; 14483 break; 14484 case BPF_JNE: 14485 eq_branch_regs = regs; 14486 break; 14487 default: 14488 /* do nothing */ 14489 break; 14490 } 14491 if (eq_branch_regs) { 14492 if (type_may_be_null(src_reg->type)) 14493 mark_ptr_not_null_reg(&eq_branch_regs[insn->src_reg]); 14494 else 14495 mark_ptr_not_null_reg(&eq_branch_regs[insn->dst_reg]); 14496 } 14497 } 14498 14499 /* detect if R == 0 where R is returned from bpf_map_lookup_elem(). 14500 * NOTE: these optimizations below are related with pointer comparison 14501 * which will never be JMP32. 14502 */ 14503 if (!is_jmp32 && BPF_SRC(insn->code) == BPF_K && 14504 insn->imm == 0 && (opcode == BPF_JEQ || opcode == BPF_JNE) && 14505 type_may_be_null(dst_reg->type)) { 14506 /* Mark all identical registers in each branch as either 14507 * safe or unknown depending R == 0 or R != 0 conditional. 14508 */ 14509 mark_ptr_or_null_regs(this_branch, insn->dst_reg, 14510 opcode == BPF_JNE); 14511 mark_ptr_or_null_regs(other_branch, insn->dst_reg, 14512 opcode == BPF_JEQ); 14513 } else if (!try_match_pkt_pointers(insn, dst_reg, ®s[insn->src_reg], 14514 this_branch, other_branch) && 14515 is_pointer_value(env, insn->dst_reg)) { 14516 verbose(env, "R%d pointer comparison prohibited\n", 14517 insn->dst_reg); 14518 return -EACCES; 14519 } 14520 if (env->log.level & BPF_LOG_LEVEL) 14521 print_insn_state(env, this_branch->frame[this_branch->curframe]); 14522 return 0; 14523 } 14524 14525 /* verify BPF_LD_IMM64 instruction */ 14526 static int check_ld_imm(struct bpf_verifier_env *env, struct bpf_insn *insn) 14527 { 14528 struct bpf_insn_aux_data *aux = cur_aux(env); 14529 struct bpf_reg_state *regs = cur_regs(env); 14530 struct bpf_reg_state *dst_reg; 14531 struct bpf_map *map; 14532 int err; 14533 14534 if (BPF_SIZE(insn->code) != BPF_DW) { 14535 verbose(env, "invalid BPF_LD_IMM insn\n"); 14536 return -EINVAL; 14537 } 14538 if (insn->off != 0) { 14539 verbose(env, "BPF_LD_IMM64 uses reserved fields\n"); 14540 return -EINVAL; 14541 } 14542 14543 err = check_reg_arg(env, insn->dst_reg, DST_OP); 14544 if (err) 14545 return err; 14546 14547 dst_reg = ®s[insn->dst_reg]; 14548 if (insn->src_reg == 0) { 14549 u64 imm = ((u64)(insn + 1)->imm << 32) | (u32)insn->imm; 14550 14551 dst_reg->type = SCALAR_VALUE; 14552 __mark_reg_known(®s[insn->dst_reg], imm); 14553 return 0; 14554 } 14555 14556 /* All special src_reg cases are listed below. From this point onwards 14557 * we either succeed and assign a corresponding dst_reg->type after 14558 * zeroing the offset, or fail and reject the program. 14559 */ 14560 mark_reg_known_zero(env, regs, insn->dst_reg); 14561 14562 if (insn->src_reg == BPF_PSEUDO_BTF_ID) { 14563 dst_reg->type = aux->btf_var.reg_type; 14564 switch (base_type(dst_reg->type)) { 14565 case PTR_TO_MEM: 14566 dst_reg->mem_size = aux->btf_var.mem_size; 14567 break; 14568 case PTR_TO_BTF_ID: 14569 dst_reg->btf = aux->btf_var.btf; 14570 dst_reg->btf_id = aux->btf_var.btf_id; 14571 break; 14572 default: 14573 verbose(env, "bpf verifier is misconfigured\n"); 14574 return -EFAULT; 14575 } 14576 return 0; 14577 } 14578 14579 if (insn->src_reg == BPF_PSEUDO_FUNC) { 14580 struct bpf_prog_aux *aux = env->prog->aux; 14581 u32 subprogno = find_subprog(env, 14582 env->insn_idx + insn->imm + 1); 14583 14584 if (!aux->func_info) { 14585 verbose(env, "missing btf func_info\n"); 14586 return -EINVAL; 14587 } 14588 if (aux->func_info_aux[subprogno].linkage != BTF_FUNC_STATIC) { 14589 verbose(env, "callback function not static\n"); 14590 return -EINVAL; 14591 } 14592 14593 dst_reg->type = PTR_TO_FUNC; 14594 dst_reg->subprogno = subprogno; 14595 return 0; 14596 } 14597 14598 map = env->used_maps[aux->map_index]; 14599 dst_reg->map_ptr = map; 14600 14601 if (insn->src_reg == BPF_PSEUDO_MAP_VALUE || 14602 insn->src_reg == BPF_PSEUDO_MAP_IDX_VALUE) { 14603 dst_reg->type = PTR_TO_MAP_VALUE; 14604 dst_reg->off = aux->map_off; 14605 WARN_ON_ONCE(map->max_entries != 1); 14606 /* We want reg->id to be same (0) as map_value is not distinct */ 14607 } else if (insn->src_reg == BPF_PSEUDO_MAP_FD || 14608 insn->src_reg == BPF_PSEUDO_MAP_IDX) { 14609 dst_reg->type = CONST_PTR_TO_MAP; 14610 } else { 14611 verbose(env, "bpf verifier is misconfigured\n"); 14612 return -EINVAL; 14613 } 14614 14615 return 0; 14616 } 14617 14618 static bool may_access_skb(enum bpf_prog_type type) 14619 { 14620 switch (type) { 14621 case BPF_PROG_TYPE_SOCKET_FILTER: 14622 case BPF_PROG_TYPE_SCHED_CLS: 14623 case BPF_PROG_TYPE_SCHED_ACT: 14624 return true; 14625 default: 14626 return false; 14627 } 14628 } 14629 14630 /* verify safety of LD_ABS|LD_IND instructions: 14631 * - they can only appear in the programs where ctx == skb 14632 * - since they are wrappers of function calls, they scratch R1-R5 registers, 14633 * preserve R6-R9, and store return value into R0 14634 * 14635 * Implicit input: 14636 * ctx == skb == R6 == CTX 14637 * 14638 * Explicit input: 14639 * SRC == any register 14640 * IMM == 32-bit immediate 14641 * 14642 * Output: 14643 * R0 - 8/16/32-bit skb data converted to cpu endianness 14644 */ 14645 static int check_ld_abs(struct bpf_verifier_env *env, struct bpf_insn *insn) 14646 { 14647 struct bpf_reg_state *regs = cur_regs(env); 14648 static const int ctx_reg = BPF_REG_6; 14649 u8 mode = BPF_MODE(insn->code); 14650 int i, err; 14651 14652 if (!may_access_skb(resolve_prog_type(env->prog))) { 14653 verbose(env, "BPF_LD_[ABS|IND] instructions not allowed for this program type\n"); 14654 return -EINVAL; 14655 } 14656 14657 if (!env->ops->gen_ld_abs) { 14658 verbose(env, "bpf verifier is misconfigured\n"); 14659 return -EINVAL; 14660 } 14661 14662 if (insn->dst_reg != BPF_REG_0 || insn->off != 0 || 14663 BPF_SIZE(insn->code) == BPF_DW || 14664 (mode == BPF_ABS && insn->src_reg != BPF_REG_0)) { 14665 verbose(env, "BPF_LD_[ABS|IND] uses reserved fields\n"); 14666 return -EINVAL; 14667 } 14668 14669 /* check whether implicit source operand (register R6) is readable */ 14670 err = check_reg_arg(env, ctx_reg, SRC_OP); 14671 if (err) 14672 return err; 14673 14674 /* Disallow usage of BPF_LD_[ABS|IND] with reference tracking, as 14675 * gen_ld_abs() may terminate the program at runtime, leading to 14676 * reference leak. 14677 */ 14678 err = check_reference_leak(env, false); 14679 if (err) { 14680 verbose(env, "BPF_LD_[ABS|IND] cannot be mixed with socket references\n"); 14681 return err; 14682 } 14683 14684 if (env->cur_state->active_lock.ptr) { 14685 verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_spin_lock-ed region\n"); 14686 return -EINVAL; 14687 } 14688 14689 if (env->cur_state->active_rcu_lock) { 14690 verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_rcu_read_lock-ed region\n"); 14691 return -EINVAL; 14692 } 14693 14694 if (regs[ctx_reg].type != PTR_TO_CTX) { 14695 verbose(env, 14696 "at the time of BPF_LD_ABS|IND R6 != pointer to skb\n"); 14697 return -EINVAL; 14698 } 14699 14700 if (mode == BPF_IND) { 14701 /* check explicit source operand */ 14702 err = check_reg_arg(env, insn->src_reg, SRC_OP); 14703 if (err) 14704 return err; 14705 } 14706 14707 err = check_ptr_off_reg(env, ®s[ctx_reg], ctx_reg); 14708 if (err < 0) 14709 return err; 14710 14711 /* reset caller saved regs to unreadable */ 14712 for (i = 0; i < CALLER_SAVED_REGS; i++) { 14713 mark_reg_not_init(env, regs, caller_saved[i]); 14714 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK); 14715 } 14716 14717 /* mark destination R0 register as readable, since it contains 14718 * the value fetched from the packet. 14719 * Already marked as written above. 14720 */ 14721 mark_reg_unknown(env, regs, BPF_REG_0); 14722 /* ld_abs load up to 32-bit skb data. */ 14723 regs[BPF_REG_0].subreg_def = env->insn_idx + 1; 14724 return 0; 14725 } 14726 14727 static int check_return_code(struct bpf_verifier_env *env, int regno) 14728 { 14729 struct tnum enforce_attach_type_range = tnum_unknown; 14730 const struct bpf_prog *prog = env->prog; 14731 struct bpf_reg_state *reg; 14732 struct tnum range = tnum_range(0, 1); 14733 enum bpf_prog_type prog_type = resolve_prog_type(env->prog); 14734 int err; 14735 struct bpf_func_state *frame = env->cur_state->frame[0]; 14736 const bool is_subprog = frame->subprogno; 14737 14738 /* LSM and struct_ops func-ptr's return type could be "void" */ 14739 if (!is_subprog || frame->in_exception_callback_fn) { 14740 switch (prog_type) { 14741 case BPF_PROG_TYPE_LSM: 14742 if (prog->expected_attach_type == BPF_LSM_CGROUP) 14743 /* See below, can be 0 or 0-1 depending on hook. */ 14744 break; 14745 fallthrough; 14746 case BPF_PROG_TYPE_STRUCT_OPS: 14747 if (!prog->aux->attach_func_proto->type) 14748 return 0; 14749 break; 14750 default: 14751 break; 14752 } 14753 } 14754 14755 /* eBPF calling convention is such that R0 is used 14756 * to return the value from eBPF program. 14757 * Make sure that it's readable at this time 14758 * of bpf_exit, which means that program wrote 14759 * something into it earlier 14760 */ 14761 err = check_reg_arg(env, regno, SRC_OP); 14762 if (err) 14763 return err; 14764 14765 if (is_pointer_value(env, regno)) { 14766 verbose(env, "R%d leaks addr as return value\n", regno); 14767 return -EACCES; 14768 } 14769 14770 reg = cur_regs(env) + regno; 14771 14772 if (frame->in_async_callback_fn) { 14773 /* enforce return zero from async callbacks like timer */ 14774 if (reg->type != SCALAR_VALUE) { 14775 verbose(env, "In async callback the register R%d is not a known value (%s)\n", 14776 regno, reg_type_str(env, reg->type)); 14777 return -EINVAL; 14778 } 14779 14780 if (!tnum_in(tnum_const(0), reg->var_off)) { 14781 verbose_invalid_scalar(env, reg, &range, "async callback", "R0"); 14782 return -EINVAL; 14783 } 14784 return 0; 14785 } 14786 14787 if (is_subprog && !frame->in_exception_callback_fn) { 14788 if (reg->type != SCALAR_VALUE) { 14789 verbose(env, "At subprogram exit the register R%d is not a scalar value (%s)\n", 14790 regno, reg_type_str(env, reg->type)); 14791 return -EINVAL; 14792 } 14793 return 0; 14794 } 14795 14796 switch (prog_type) { 14797 case BPF_PROG_TYPE_CGROUP_SOCK_ADDR: 14798 if (env->prog->expected_attach_type == BPF_CGROUP_UDP4_RECVMSG || 14799 env->prog->expected_attach_type == BPF_CGROUP_UDP6_RECVMSG || 14800 env->prog->expected_attach_type == BPF_CGROUP_INET4_GETPEERNAME || 14801 env->prog->expected_attach_type == BPF_CGROUP_INET6_GETPEERNAME || 14802 env->prog->expected_attach_type == BPF_CGROUP_INET4_GETSOCKNAME || 14803 env->prog->expected_attach_type == BPF_CGROUP_INET6_GETSOCKNAME) 14804 range = tnum_range(1, 1); 14805 if (env->prog->expected_attach_type == BPF_CGROUP_INET4_BIND || 14806 env->prog->expected_attach_type == BPF_CGROUP_INET6_BIND) 14807 range = tnum_range(0, 3); 14808 break; 14809 case BPF_PROG_TYPE_CGROUP_SKB: 14810 if (env->prog->expected_attach_type == BPF_CGROUP_INET_EGRESS) { 14811 range = tnum_range(0, 3); 14812 enforce_attach_type_range = tnum_range(2, 3); 14813 } 14814 break; 14815 case BPF_PROG_TYPE_CGROUP_SOCK: 14816 case BPF_PROG_TYPE_SOCK_OPS: 14817 case BPF_PROG_TYPE_CGROUP_DEVICE: 14818 case BPF_PROG_TYPE_CGROUP_SYSCTL: 14819 case BPF_PROG_TYPE_CGROUP_SOCKOPT: 14820 break; 14821 case BPF_PROG_TYPE_RAW_TRACEPOINT: 14822 if (!env->prog->aux->attach_btf_id) 14823 return 0; 14824 range = tnum_const(0); 14825 break; 14826 case BPF_PROG_TYPE_TRACING: 14827 switch (env->prog->expected_attach_type) { 14828 case BPF_TRACE_FENTRY: 14829 case BPF_TRACE_FEXIT: 14830 range = tnum_const(0); 14831 break; 14832 case BPF_TRACE_RAW_TP: 14833 case BPF_MODIFY_RETURN: 14834 return 0; 14835 case BPF_TRACE_ITER: 14836 break; 14837 default: 14838 return -ENOTSUPP; 14839 } 14840 break; 14841 case BPF_PROG_TYPE_SK_LOOKUP: 14842 range = tnum_range(SK_DROP, SK_PASS); 14843 break; 14844 14845 case BPF_PROG_TYPE_LSM: 14846 if (env->prog->expected_attach_type != BPF_LSM_CGROUP) { 14847 /* Regular BPF_PROG_TYPE_LSM programs can return 14848 * any value. 14849 */ 14850 return 0; 14851 } 14852 if (!env->prog->aux->attach_func_proto->type) { 14853 /* Make sure programs that attach to void 14854 * hooks don't try to modify return value. 14855 */ 14856 range = tnum_range(1, 1); 14857 } 14858 break; 14859 14860 case BPF_PROG_TYPE_NETFILTER: 14861 range = tnum_range(NF_DROP, NF_ACCEPT); 14862 break; 14863 case BPF_PROG_TYPE_EXT: 14864 /* freplace program can return anything as its return value 14865 * depends on the to-be-replaced kernel func or bpf program. 14866 */ 14867 default: 14868 return 0; 14869 } 14870 14871 if (reg->type != SCALAR_VALUE) { 14872 verbose(env, "At program exit the register R%d is not a known value (%s)\n", 14873 regno, reg_type_str(env, reg->type)); 14874 return -EINVAL; 14875 } 14876 14877 if (!tnum_in(range, reg->var_off)) { 14878 verbose_invalid_scalar(env, reg, &range, "program exit", "R0"); 14879 if (prog->expected_attach_type == BPF_LSM_CGROUP && 14880 prog_type == BPF_PROG_TYPE_LSM && 14881 !prog->aux->attach_func_proto->type) 14882 verbose(env, "Note, BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n"); 14883 return -EINVAL; 14884 } 14885 14886 if (!tnum_is_unknown(enforce_attach_type_range) && 14887 tnum_in(enforce_attach_type_range, reg->var_off)) 14888 env->prog->enforce_expected_attach_type = 1; 14889 return 0; 14890 } 14891 14892 /* non-recursive DFS pseudo code 14893 * 1 procedure DFS-iterative(G,v): 14894 * 2 label v as discovered 14895 * 3 let S be a stack 14896 * 4 S.push(v) 14897 * 5 while S is not empty 14898 * 6 t <- S.peek() 14899 * 7 if t is what we're looking for: 14900 * 8 return t 14901 * 9 for all edges e in G.adjacentEdges(t) do 14902 * 10 if edge e is already labelled 14903 * 11 continue with the next edge 14904 * 12 w <- G.adjacentVertex(t,e) 14905 * 13 if vertex w is not discovered and not explored 14906 * 14 label e as tree-edge 14907 * 15 label w as discovered 14908 * 16 S.push(w) 14909 * 17 continue at 5 14910 * 18 else if vertex w is discovered 14911 * 19 label e as back-edge 14912 * 20 else 14913 * 21 // vertex w is explored 14914 * 22 label e as forward- or cross-edge 14915 * 23 label t as explored 14916 * 24 S.pop() 14917 * 14918 * convention: 14919 * 0x10 - discovered 14920 * 0x11 - discovered and fall-through edge labelled 14921 * 0x12 - discovered and fall-through and branch edges labelled 14922 * 0x20 - explored 14923 */ 14924 14925 enum { 14926 DISCOVERED = 0x10, 14927 EXPLORED = 0x20, 14928 FALLTHROUGH = 1, 14929 BRANCH = 2, 14930 }; 14931 14932 static u32 state_htab_size(struct bpf_verifier_env *env) 14933 { 14934 return env->prog->len; 14935 } 14936 14937 static struct bpf_verifier_state_list **explored_state( 14938 struct bpf_verifier_env *env, 14939 int idx) 14940 { 14941 struct bpf_verifier_state *cur = env->cur_state; 14942 struct bpf_func_state *state = cur->frame[cur->curframe]; 14943 14944 return &env->explored_states[(idx ^ state->callsite) % state_htab_size(env)]; 14945 } 14946 14947 static void mark_prune_point(struct bpf_verifier_env *env, int idx) 14948 { 14949 env->insn_aux_data[idx].prune_point = true; 14950 } 14951 14952 static bool is_prune_point(struct bpf_verifier_env *env, int insn_idx) 14953 { 14954 return env->insn_aux_data[insn_idx].prune_point; 14955 } 14956 14957 static void mark_force_checkpoint(struct bpf_verifier_env *env, int idx) 14958 { 14959 env->insn_aux_data[idx].force_checkpoint = true; 14960 } 14961 14962 static bool is_force_checkpoint(struct bpf_verifier_env *env, int insn_idx) 14963 { 14964 return env->insn_aux_data[insn_idx].force_checkpoint; 14965 } 14966 14967 14968 enum { 14969 DONE_EXPLORING = 0, 14970 KEEP_EXPLORING = 1, 14971 }; 14972 14973 /* t, w, e - match pseudo-code above: 14974 * t - index of current instruction 14975 * w - next instruction 14976 * e - edge 14977 */ 14978 static int push_insn(int t, int w, int e, struct bpf_verifier_env *env, 14979 bool loop_ok) 14980 { 14981 int *insn_stack = env->cfg.insn_stack; 14982 int *insn_state = env->cfg.insn_state; 14983 14984 if (e == FALLTHROUGH && insn_state[t] >= (DISCOVERED | FALLTHROUGH)) 14985 return DONE_EXPLORING; 14986 14987 if (e == BRANCH && insn_state[t] >= (DISCOVERED | BRANCH)) 14988 return DONE_EXPLORING; 14989 14990 if (w < 0 || w >= env->prog->len) { 14991 verbose_linfo(env, t, "%d: ", t); 14992 verbose(env, "jump out of range from insn %d to %d\n", t, w); 14993 return -EINVAL; 14994 } 14995 14996 if (e == BRANCH) { 14997 /* mark branch target for state pruning */ 14998 mark_prune_point(env, w); 14999 mark_jmp_point(env, w); 15000 } 15001 15002 if (insn_state[w] == 0) { 15003 /* tree-edge */ 15004 insn_state[t] = DISCOVERED | e; 15005 insn_state[w] = DISCOVERED; 15006 if (env->cfg.cur_stack >= env->prog->len) 15007 return -E2BIG; 15008 insn_stack[env->cfg.cur_stack++] = w; 15009 return KEEP_EXPLORING; 15010 } else if ((insn_state[w] & 0xF0) == DISCOVERED) { 15011 if (loop_ok && env->bpf_capable) 15012 return DONE_EXPLORING; 15013 verbose_linfo(env, t, "%d: ", t); 15014 verbose_linfo(env, w, "%d: ", w); 15015 verbose(env, "back-edge from insn %d to %d\n", t, w); 15016 return -EINVAL; 15017 } else if (insn_state[w] == EXPLORED) { 15018 /* forward- or cross-edge */ 15019 insn_state[t] = DISCOVERED | e; 15020 } else { 15021 verbose(env, "insn state internal bug\n"); 15022 return -EFAULT; 15023 } 15024 return DONE_EXPLORING; 15025 } 15026 15027 static int visit_func_call_insn(int t, struct bpf_insn *insns, 15028 struct bpf_verifier_env *env, 15029 bool visit_callee) 15030 { 15031 int ret; 15032 15033 ret = push_insn(t, t + 1, FALLTHROUGH, env, false); 15034 if (ret) 15035 return ret; 15036 15037 mark_prune_point(env, t + 1); 15038 /* when we exit from subprog, we need to record non-linear history */ 15039 mark_jmp_point(env, t + 1); 15040 15041 if (visit_callee) { 15042 mark_prune_point(env, t); 15043 ret = push_insn(t, t + insns[t].imm + 1, BRANCH, env, 15044 /* It's ok to allow recursion from CFG point of 15045 * view. __check_func_call() will do the actual 15046 * check. 15047 */ 15048 bpf_pseudo_func(insns + t)); 15049 } 15050 return ret; 15051 } 15052 15053 /* Visits the instruction at index t and returns one of the following: 15054 * < 0 - an error occurred 15055 * DONE_EXPLORING - the instruction was fully explored 15056 * KEEP_EXPLORING - there is still work to be done before it is fully explored 15057 */ 15058 static int visit_insn(int t, struct bpf_verifier_env *env) 15059 { 15060 struct bpf_insn *insns = env->prog->insnsi, *insn = &insns[t]; 15061 int ret, off; 15062 15063 if (bpf_pseudo_func(insn)) 15064 return visit_func_call_insn(t, insns, env, true); 15065 15066 /* All non-branch instructions have a single fall-through edge. */ 15067 if (BPF_CLASS(insn->code) != BPF_JMP && 15068 BPF_CLASS(insn->code) != BPF_JMP32) 15069 return push_insn(t, t + 1, FALLTHROUGH, env, false); 15070 15071 switch (BPF_OP(insn->code)) { 15072 case BPF_EXIT: 15073 return DONE_EXPLORING; 15074 15075 case BPF_CALL: 15076 if (insn->src_reg == 0 && insn->imm == BPF_FUNC_timer_set_callback) 15077 /* Mark this call insn as a prune point to trigger 15078 * is_state_visited() check before call itself is 15079 * processed by __check_func_call(). Otherwise new 15080 * async state will be pushed for further exploration. 15081 */ 15082 mark_prune_point(env, t); 15083 if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) { 15084 struct bpf_kfunc_call_arg_meta meta; 15085 15086 ret = fetch_kfunc_meta(env, insn, &meta, NULL); 15087 if (ret == 0 && is_iter_next_kfunc(&meta)) { 15088 mark_prune_point(env, t); 15089 /* Checking and saving state checkpoints at iter_next() call 15090 * is crucial for fast convergence of open-coded iterator loop 15091 * logic, so we need to force it. If we don't do that, 15092 * is_state_visited() might skip saving a checkpoint, causing 15093 * unnecessarily long sequence of not checkpointed 15094 * instructions and jumps, leading to exhaustion of jump 15095 * history buffer, and potentially other undesired outcomes. 15096 * It is expected that with correct open-coded iterators 15097 * convergence will happen quickly, so we don't run a risk of 15098 * exhausting memory. 15099 */ 15100 mark_force_checkpoint(env, t); 15101 } 15102 } 15103 return visit_func_call_insn(t, insns, env, insn->src_reg == BPF_PSEUDO_CALL); 15104 15105 case BPF_JA: 15106 if (BPF_SRC(insn->code) != BPF_K) 15107 return -EINVAL; 15108 15109 if (BPF_CLASS(insn->code) == BPF_JMP) 15110 off = insn->off; 15111 else 15112 off = insn->imm; 15113 15114 /* unconditional jump with single edge */ 15115 ret = push_insn(t, t + off + 1, FALLTHROUGH, env, 15116 true); 15117 if (ret) 15118 return ret; 15119 15120 mark_prune_point(env, t + off + 1); 15121 mark_jmp_point(env, t + off + 1); 15122 15123 return ret; 15124 15125 default: 15126 /* conditional jump with two edges */ 15127 mark_prune_point(env, t); 15128 15129 ret = push_insn(t, t + 1, FALLTHROUGH, env, true); 15130 if (ret) 15131 return ret; 15132 15133 return push_insn(t, t + insn->off + 1, BRANCH, env, true); 15134 } 15135 } 15136 15137 /* non-recursive depth-first-search to detect loops in BPF program 15138 * loop == back-edge in directed graph 15139 */ 15140 static int check_cfg(struct bpf_verifier_env *env) 15141 { 15142 int insn_cnt = env->prog->len; 15143 int *insn_stack, *insn_state; 15144 int ex_insn_beg, i, ret = 0; 15145 bool ex_done = false; 15146 15147 insn_state = env->cfg.insn_state = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL); 15148 if (!insn_state) 15149 return -ENOMEM; 15150 15151 insn_stack = env->cfg.insn_stack = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL); 15152 if (!insn_stack) { 15153 kvfree(insn_state); 15154 return -ENOMEM; 15155 } 15156 15157 insn_state[0] = DISCOVERED; /* mark 1st insn as discovered */ 15158 insn_stack[0] = 0; /* 0 is the first instruction */ 15159 env->cfg.cur_stack = 1; 15160 15161 walk_cfg: 15162 while (env->cfg.cur_stack > 0) { 15163 int t = insn_stack[env->cfg.cur_stack - 1]; 15164 15165 ret = visit_insn(t, env); 15166 switch (ret) { 15167 case DONE_EXPLORING: 15168 insn_state[t] = EXPLORED; 15169 env->cfg.cur_stack--; 15170 break; 15171 case KEEP_EXPLORING: 15172 break; 15173 default: 15174 if (ret > 0) { 15175 verbose(env, "visit_insn internal bug\n"); 15176 ret = -EFAULT; 15177 } 15178 goto err_free; 15179 } 15180 } 15181 15182 if (env->cfg.cur_stack < 0) { 15183 verbose(env, "pop stack internal bug\n"); 15184 ret = -EFAULT; 15185 goto err_free; 15186 } 15187 15188 if (env->exception_callback_subprog && !ex_done) { 15189 ex_insn_beg = env->subprog_info[env->exception_callback_subprog].start; 15190 15191 insn_state[ex_insn_beg] = DISCOVERED; 15192 insn_stack[0] = ex_insn_beg; 15193 env->cfg.cur_stack = 1; 15194 ex_done = true; 15195 goto walk_cfg; 15196 } 15197 15198 for (i = 0; i < insn_cnt; i++) { 15199 if (insn_state[i] != EXPLORED) { 15200 verbose(env, "unreachable insn %d\n", i); 15201 ret = -EINVAL; 15202 goto err_free; 15203 } 15204 } 15205 ret = 0; /* cfg looks good */ 15206 15207 err_free: 15208 kvfree(insn_state); 15209 kvfree(insn_stack); 15210 env->cfg.insn_state = env->cfg.insn_stack = NULL; 15211 return ret; 15212 } 15213 15214 static int check_abnormal_return(struct bpf_verifier_env *env) 15215 { 15216 int i; 15217 15218 for (i = 1; i < env->subprog_cnt; i++) { 15219 if (env->subprog_info[i].has_ld_abs) { 15220 verbose(env, "LD_ABS is not allowed in subprogs without BTF\n"); 15221 return -EINVAL; 15222 } 15223 if (env->subprog_info[i].has_tail_call) { 15224 verbose(env, "tail_call is not allowed in subprogs without BTF\n"); 15225 return -EINVAL; 15226 } 15227 } 15228 return 0; 15229 } 15230 15231 /* The minimum supported BTF func info size */ 15232 #define MIN_BPF_FUNCINFO_SIZE 8 15233 #define MAX_FUNCINFO_REC_SIZE 252 15234 15235 static int check_btf_func_early(struct bpf_verifier_env *env, 15236 const union bpf_attr *attr, 15237 bpfptr_t uattr) 15238 { 15239 u32 krec_size = sizeof(struct bpf_func_info); 15240 const struct btf_type *type, *func_proto; 15241 u32 i, nfuncs, urec_size, min_size; 15242 struct bpf_func_info *krecord; 15243 struct bpf_prog *prog; 15244 const struct btf *btf; 15245 u32 prev_offset = 0; 15246 bpfptr_t urecord; 15247 int ret = -ENOMEM; 15248 15249 nfuncs = attr->func_info_cnt; 15250 if (!nfuncs) { 15251 if (check_abnormal_return(env)) 15252 return -EINVAL; 15253 return 0; 15254 } 15255 15256 urec_size = attr->func_info_rec_size; 15257 if (urec_size < MIN_BPF_FUNCINFO_SIZE || 15258 urec_size > MAX_FUNCINFO_REC_SIZE || 15259 urec_size % sizeof(u32)) { 15260 verbose(env, "invalid func info rec size %u\n", urec_size); 15261 return -EINVAL; 15262 } 15263 15264 prog = env->prog; 15265 btf = prog->aux->btf; 15266 15267 urecord = make_bpfptr(attr->func_info, uattr.is_kernel); 15268 min_size = min_t(u32, krec_size, urec_size); 15269 15270 krecord = kvcalloc(nfuncs, krec_size, GFP_KERNEL | __GFP_NOWARN); 15271 if (!krecord) 15272 return -ENOMEM; 15273 15274 for (i = 0; i < nfuncs; i++) { 15275 ret = bpf_check_uarg_tail_zero(urecord, krec_size, urec_size); 15276 if (ret) { 15277 if (ret == -E2BIG) { 15278 verbose(env, "nonzero tailing record in func info"); 15279 /* set the size kernel expects so loader can zero 15280 * out the rest of the record. 15281 */ 15282 if (copy_to_bpfptr_offset(uattr, 15283 offsetof(union bpf_attr, func_info_rec_size), 15284 &min_size, sizeof(min_size))) 15285 ret = -EFAULT; 15286 } 15287 goto err_free; 15288 } 15289 15290 if (copy_from_bpfptr(&krecord[i], urecord, min_size)) { 15291 ret = -EFAULT; 15292 goto err_free; 15293 } 15294 15295 /* check insn_off */ 15296 ret = -EINVAL; 15297 if (i == 0) { 15298 if (krecord[i].insn_off) { 15299 verbose(env, 15300 "nonzero insn_off %u for the first func info record", 15301 krecord[i].insn_off); 15302 goto err_free; 15303 } 15304 } else if (krecord[i].insn_off <= prev_offset) { 15305 verbose(env, 15306 "same or smaller insn offset (%u) than previous func info record (%u)", 15307 krecord[i].insn_off, prev_offset); 15308 goto err_free; 15309 } 15310 15311 /* check type_id */ 15312 type = btf_type_by_id(btf, krecord[i].type_id); 15313 if (!type || !btf_type_is_func(type)) { 15314 verbose(env, "invalid type id %d in func info", 15315 krecord[i].type_id); 15316 goto err_free; 15317 } 15318 15319 func_proto = btf_type_by_id(btf, type->type); 15320 if (unlikely(!func_proto || !btf_type_is_func_proto(func_proto))) 15321 /* btf_func_check() already verified it during BTF load */ 15322 goto err_free; 15323 15324 prev_offset = krecord[i].insn_off; 15325 bpfptr_add(&urecord, urec_size); 15326 } 15327 15328 prog->aux->func_info = krecord; 15329 prog->aux->func_info_cnt = nfuncs; 15330 return 0; 15331 15332 err_free: 15333 kvfree(krecord); 15334 return ret; 15335 } 15336 15337 static int check_btf_func(struct bpf_verifier_env *env, 15338 const union bpf_attr *attr, 15339 bpfptr_t uattr) 15340 { 15341 const struct btf_type *type, *func_proto, *ret_type; 15342 u32 i, nfuncs, urec_size; 15343 struct bpf_func_info *krecord; 15344 struct bpf_func_info_aux *info_aux = NULL; 15345 struct bpf_prog *prog; 15346 const struct btf *btf; 15347 bpfptr_t urecord; 15348 bool scalar_return; 15349 int ret = -ENOMEM; 15350 15351 nfuncs = attr->func_info_cnt; 15352 if (!nfuncs) { 15353 if (check_abnormal_return(env)) 15354 return -EINVAL; 15355 return 0; 15356 } 15357 if (nfuncs != env->subprog_cnt) { 15358 verbose(env, "number of funcs in func_info doesn't match number of subprogs\n"); 15359 return -EINVAL; 15360 } 15361 15362 urec_size = attr->func_info_rec_size; 15363 15364 prog = env->prog; 15365 btf = prog->aux->btf; 15366 15367 urecord = make_bpfptr(attr->func_info, uattr.is_kernel); 15368 15369 krecord = prog->aux->func_info; 15370 info_aux = kcalloc(nfuncs, sizeof(*info_aux), GFP_KERNEL | __GFP_NOWARN); 15371 if (!info_aux) 15372 return -ENOMEM; 15373 15374 for (i = 0; i < nfuncs; i++) { 15375 /* check insn_off */ 15376 ret = -EINVAL; 15377 15378 if (env->subprog_info[i].start != krecord[i].insn_off) { 15379 verbose(env, "func_info BTF section doesn't match subprog layout in BPF program\n"); 15380 goto err_free; 15381 } 15382 15383 /* Already checked type_id */ 15384 type = btf_type_by_id(btf, krecord[i].type_id); 15385 info_aux[i].linkage = BTF_INFO_VLEN(type->info); 15386 /* Already checked func_proto */ 15387 func_proto = btf_type_by_id(btf, type->type); 15388 15389 ret_type = btf_type_skip_modifiers(btf, func_proto->type, NULL); 15390 scalar_return = 15391 btf_type_is_small_int(ret_type) || btf_is_any_enum(ret_type); 15392 if (i && !scalar_return && env->subprog_info[i].has_ld_abs) { 15393 verbose(env, "LD_ABS is only allowed in functions that return 'int'.\n"); 15394 goto err_free; 15395 } 15396 if (i && !scalar_return && env->subprog_info[i].has_tail_call) { 15397 verbose(env, "tail_call is only allowed in functions that return 'int'.\n"); 15398 goto err_free; 15399 } 15400 15401 bpfptr_add(&urecord, urec_size); 15402 } 15403 15404 prog->aux->func_info_aux = info_aux; 15405 return 0; 15406 15407 err_free: 15408 kfree(info_aux); 15409 return ret; 15410 } 15411 15412 static void adjust_btf_func(struct bpf_verifier_env *env) 15413 { 15414 struct bpf_prog_aux *aux = env->prog->aux; 15415 int i; 15416 15417 if (!aux->func_info) 15418 return; 15419 15420 /* func_info is not available for hidden subprogs */ 15421 for (i = 0; i < env->subprog_cnt - env->hidden_subprog_cnt; i++) 15422 aux->func_info[i].insn_off = env->subprog_info[i].start; 15423 } 15424 15425 #define MIN_BPF_LINEINFO_SIZE offsetofend(struct bpf_line_info, line_col) 15426 #define MAX_LINEINFO_REC_SIZE MAX_FUNCINFO_REC_SIZE 15427 15428 static int check_btf_line(struct bpf_verifier_env *env, 15429 const union bpf_attr *attr, 15430 bpfptr_t uattr) 15431 { 15432 u32 i, s, nr_linfo, ncopy, expected_size, rec_size, prev_offset = 0; 15433 struct bpf_subprog_info *sub; 15434 struct bpf_line_info *linfo; 15435 struct bpf_prog *prog; 15436 const struct btf *btf; 15437 bpfptr_t ulinfo; 15438 int err; 15439 15440 nr_linfo = attr->line_info_cnt; 15441 if (!nr_linfo) 15442 return 0; 15443 if (nr_linfo > INT_MAX / sizeof(struct bpf_line_info)) 15444 return -EINVAL; 15445 15446 rec_size = attr->line_info_rec_size; 15447 if (rec_size < MIN_BPF_LINEINFO_SIZE || 15448 rec_size > MAX_LINEINFO_REC_SIZE || 15449 rec_size & (sizeof(u32) - 1)) 15450 return -EINVAL; 15451 15452 /* Need to zero it in case the userspace may 15453 * pass in a smaller bpf_line_info object. 15454 */ 15455 linfo = kvcalloc(nr_linfo, sizeof(struct bpf_line_info), 15456 GFP_KERNEL | __GFP_NOWARN); 15457 if (!linfo) 15458 return -ENOMEM; 15459 15460 prog = env->prog; 15461 btf = prog->aux->btf; 15462 15463 s = 0; 15464 sub = env->subprog_info; 15465 ulinfo = make_bpfptr(attr->line_info, uattr.is_kernel); 15466 expected_size = sizeof(struct bpf_line_info); 15467 ncopy = min_t(u32, expected_size, rec_size); 15468 for (i = 0; i < nr_linfo; i++) { 15469 err = bpf_check_uarg_tail_zero(ulinfo, expected_size, rec_size); 15470 if (err) { 15471 if (err == -E2BIG) { 15472 verbose(env, "nonzero tailing record in line_info"); 15473 if (copy_to_bpfptr_offset(uattr, 15474 offsetof(union bpf_attr, line_info_rec_size), 15475 &expected_size, sizeof(expected_size))) 15476 err = -EFAULT; 15477 } 15478 goto err_free; 15479 } 15480 15481 if (copy_from_bpfptr(&linfo[i], ulinfo, ncopy)) { 15482 err = -EFAULT; 15483 goto err_free; 15484 } 15485 15486 /* 15487 * Check insn_off to ensure 15488 * 1) strictly increasing AND 15489 * 2) bounded by prog->len 15490 * 15491 * The linfo[0].insn_off == 0 check logically falls into 15492 * the later "missing bpf_line_info for func..." case 15493 * because the first linfo[0].insn_off must be the 15494 * first sub also and the first sub must have 15495 * subprog_info[0].start == 0. 15496 */ 15497 if ((i && linfo[i].insn_off <= prev_offset) || 15498 linfo[i].insn_off >= prog->len) { 15499 verbose(env, "Invalid line_info[%u].insn_off:%u (prev_offset:%u prog->len:%u)\n", 15500 i, linfo[i].insn_off, prev_offset, 15501 prog->len); 15502 err = -EINVAL; 15503 goto err_free; 15504 } 15505 15506 if (!prog->insnsi[linfo[i].insn_off].code) { 15507 verbose(env, 15508 "Invalid insn code at line_info[%u].insn_off\n", 15509 i); 15510 err = -EINVAL; 15511 goto err_free; 15512 } 15513 15514 if (!btf_name_by_offset(btf, linfo[i].line_off) || 15515 !btf_name_by_offset(btf, linfo[i].file_name_off)) { 15516 verbose(env, "Invalid line_info[%u].line_off or .file_name_off\n", i); 15517 err = -EINVAL; 15518 goto err_free; 15519 } 15520 15521 if (s != env->subprog_cnt) { 15522 if (linfo[i].insn_off == sub[s].start) { 15523 sub[s].linfo_idx = i; 15524 s++; 15525 } else if (sub[s].start < linfo[i].insn_off) { 15526 verbose(env, "missing bpf_line_info for func#%u\n", s); 15527 err = -EINVAL; 15528 goto err_free; 15529 } 15530 } 15531 15532 prev_offset = linfo[i].insn_off; 15533 bpfptr_add(&ulinfo, rec_size); 15534 } 15535 15536 if (s != env->subprog_cnt) { 15537 verbose(env, "missing bpf_line_info for %u funcs starting from func#%u\n", 15538 env->subprog_cnt - s, s); 15539 err = -EINVAL; 15540 goto err_free; 15541 } 15542 15543 prog->aux->linfo = linfo; 15544 prog->aux->nr_linfo = nr_linfo; 15545 15546 return 0; 15547 15548 err_free: 15549 kvfree(linfo); 15550 return err; 15551 } 15552 15553 #define MIN_CORE_RELO_SIZE sizeof(struct bpf_core_relo) 15554 #define MAX_CORE_RELO_SIZE MAX_FUNCINFO_REC_SIZE 15555 15556 static int check_core_relo(struct bpf_verifier_env *env, 15557 const union bpf_attr *attr, 15558 bpfptr_t uattr) 15559 { 15560 u32 i, nr_core_relo, ncopy, expected_size, rec_size; 15561 struct bpf_core_relo core_relo = {}; 15562 struct bpf_prog *prog = env->prog; 15563 const struct btf *btf = prog->aux->btf; 15564 struct bpf_core_ctx ctx = { 15565 .log = &env->log, 15566 .btf = btf, 15567 }; 15568 bpfptr_t u_core_relo; 15569 int err; 15570 15571 nr_core_relo = attr->core_relo_cnt; 15572 if (!nr_core_relo) 15573 return 0; 15574 if (nr_core_relo > INT_MAX / sizeof(struct bpf_core_relo)) 15575 return -EINVAL; 15576 15577 rec_size = attr->core_relo_rec_size; 15578 if (rec_size < MIN_CORE_RELO_SIZE || 15579 rec_size > MAX_CORE_RELO_SIZE || 15580 rec_size % sizeof(u32)) 15581 return -EINVAL; 15582 15583 u_core_relo = make_bpfptr(attr->core_relos, uattr.is_kernel); 15584 expected_size = sizeof(struct bpf_core_relo); 15585 ncopy = min_t(u32, expected_size, rec_size); 15586 15587 /* Unlike func_info and line_info, copy and apply each CO-RE 15588 * relocation record one at a time. 15589 */ 15590 for (i = 0; i < nr_core_relo; i++) { 15591 /* future proofing when sizeof(bpf_core_relo) changes */ 15592 err = bpf_check_uarg_tail_zero(u_core_relo, expected_size, rec_size); 15593 if (err) { 15594 if (err == -E2BIG) { 15595 verbose(env, "nonzero tailing record in core_relo"); 15596 if (copy_to_bpfptr_offset(uattr, 15597 offsetof(union bpf_attr, core_relo_rec_size), 15598 &expected_size, sizeof(expected_size))) 15599 err = -EFAULT; 15600 } 15601 break; 15602 } 15603 15604 if (copy_from_bpfptr(&core_relo, u_core_relo, ncopy)) { 15605 err = -EFAULT; 15606 break; 15607 } 15608 15609 if (core_relo.insn_off % 8 || core_relo.insn_off / 8 >= prog->len) { 15610 verbose(env, "Invalid core_relo[%u].insn_off:%u prog->len:%u\n", 15611 i, core_relo.insn_off, prog->len); 15612 err = -EINVAL; 15613 break; 15614 } 15615 15616 err = bpf_core_apply(&ctx, &core_relo, i, 15617 &prog->insnsi[core_relo.insn_off / 8]); 15618 if (err) 15619 break; 15620 bpfptr_add(&u_core_relo, rec_size); 15621 } 15622 return err; 15623 } 15624 15625 static int check_btf_info_early(struct bpf_verifier_env *env, 15626 const union bpf_attr *attr, 15627 bpfptr_t uattr) 15628 { 15629 struct btf *btf; 15630 int err; 15631 15632 if (!attr->func_info_cnt && !attr->line_info_cnt) { 15633 if (check_abnormal_return(env)) 15634 return -EINVAL; 15635 return 0; 15636 } 15637 15638 btf = btf_get_by_fd(attr->prog_btf_fd); 15639 if (IS_ERR(btf)) 15640 return PTR_ERR(btf); 15641 if (btf_is_kernel(btf)) { 15642 btf_put(btf); 15643 return -EACCES; 15644 } 15645 env->prog->aux->btf = btf; 15646 15647 err = check_btf_func_early(env, attr, uattr); 15648 if (err) 15649 return err; 15650 return 0; 15651 } 15652 15653 static int check_btf_info(struct bpf_verifier_env *env, 15654 const union bpf_attr *attr, 15655 bpfptr_t uattr) 15656 { 15657 int err; 15658 15659 if (!attr->func_info_cnt && !attr->line_info_cnt) { 15660 if (check_abnormal_return(env)) 15661 return -EINVAL; 15662 return 0; 15663 } 15664 15665 err = check_btf_func(env, attr, uattr); 15666 if (err) 15667 return err; 15668 15669 err = check_btf_line(env, attr, uattr); 15670 if (err) 15671 return err; 15672 15673 err = check_core_relo(env, attr, uattr); 15674 if (err) 15675 return err; 15676 15677 return 0; 15678 } 15679 15680 /* check %cur's range satisfies %old's */ 15681 static bool range_within(struct bpf_reg_state *old, 15682 struct bpf_reg_state *cur) 15683 { 15684 return old->umin_value <= cur->umin_value && 15685 old->umax_value >= cur->umax_value && 15686 old->smin_value <= cur->smin_value && 15687 old->smax_value >= cur->smax_value && 15688 old->u32_min_value <= cur->u32_min_value && 15689 old->u32_max_value >= cur->u32_max_value && 15690 old->s32_min_value <= cur->s32_min_value && 15691 old->s32_max_value >= cur->s32_max_value; 15692 } 15693 15694 /* If in the old state two registers had the same id, then they need to have 15695 * the same id in the new state as well. But that id could be different from 15696 * the old state, so we need to track the mapping from old to new ids. 15697 * Once we have seen that, say, a reg with old id 5 had new id 9, any subsequent 15698 * regs with old id 5 must also have new id 9 for the new state to be safe. But 15699 * regs with a different old id could still have new id 9, we don't care about 15700 * that. 15701 * So we look through our idmap to see if this old id has been seen before. If 15702 * so, we require the new id to match; otherwise, we add the id pair to the map. 15703 */ 15704 static bool check_ids(u32 old_id, u32 cur_id, struct bpf_idmap *idmap) 15705 { 15706 struct bpf_id_pair *map = idmap->map; 15707 unsigned int i; 15708 15709 /* either both IDs should be set or both should be zero */ 15710 if (!!old_id != !!cur_id) 15711 return false; 15712 15713 if (old_id == 0) /* cur_id == 0 as well */ 15714 return true; 15715 15716 for (i = 0; i < BPF_ID_MAP_SIZE; i++) { 15717 if (!map[i].old) { 15718 /* Reached an empty slot; haven't seen this id before */ 15719 map[i].old = old_id; 15720 map[i].cur = cur_id; 15721 return true; 15722 } 15723 if (map[i].old == old_id) 15724 return map[i].cur == cur_id; 15725 if (map[i].cur == cur_id) 15726 return false; 15727 } 15728 /* We ran out of idmap slots, which should be impossible */ 15729 WARN_ON_ONCE(1); 15730 return false; 15731 } 15732 15733 /* Similar to check_ids(), but allocate a unique temporary ID 15734 * for 'old_id' or 'cur_id' of zero. 15735 * This makes pairs like '0 vs unique ID', 'unique ID vs 0' valid. 15736 */ 15737 static bool check_scalar_ids(u32 old_id, u32 cur_id, struct bpf_idmap *idmap) 15738 { 15739 old_id = old_id ? old_id : ++idmap->tmp_id_gen; 15740 cur_id = cur_id ? cur_id : ++idmap->tmp_id_gen; 15741 15742 return check_ids(old_id, cur_id, idmap); 15743 } 15744 15745 static void clean_func_state(struct bpf_verifier_env *env, 15746 struct bpf_func_state *st) 15747 { 15748 enum bpf_reg_liveness live; 15749 int i, j; 15750 15751 for (i = 0; i < BPF_REG_FP; i++) { 15752 live = st->regs[i].live; 15753 /* liveness must not touch this register anymore */ 15754 st->regs[i].live |= REG_LIVE_DONE; 15755 if (!(live & REG_LIVE_READ)) 15756 /* since the register is unused, clear its state 15757 * to make further comparison simpler 15758 */ 15759 __mark_reg_not_init(env, &st->regs[i]); 15760 } 15761 15762 for (i = 0; i < st->allocated_stack / BPF_REG_SIZE; i++) { 15763 live = st->stack[i].spilled_ptr.live; 15764 /* liveness must not touch this stack slot anymore */ 15765 st->stack[i].spilled_ptr.live |= REG_LIVE_DONE; 15766 if (!(live & REG_LIVE_READ)) { 15767 __mark_reg_not_init(env, &st->stack[i].spilled_ptr); 15768 for (j = 0; j < BPF_REG_SIZE; j++) 15769 st->stack[i].slot_type[j] = STACK_INVALID; 15770 } 15771 } 15772 } 15773 15774 static void clean_verifier_state(struct bpf_verifier_env *env, 15775 struct bpf_verifier_state *st) 15776 { 15777 int i; 15778 15779 if (st->frame[0]->regs[0].live & REG_LIVE_DONE) 15780 /* all regs in this state in all frames were already marked */ 15781 return; 15782 15783 for (i = 0; i <= st->curframe; i++) 15784 clean_func_state(env, st->frame[i]); 15785 } 15786 15787 /* the parentage chains form a tree. 15788 * the verifier states are added to state lists at given insn and 15789 * pushed into state stack for future exploration. 15790 * when the verifier reaches bpf_exit insn some of the verifer states 15791 * stored in the state lists have their final liveness state already, 15792 * but a lot of states will get revised from liveness point of view when 15793 * the verifier explores other branches. 15794 * Example: 15795 * 1: r0 = 1 15796 * 2: if r1 == 100 goto pc+1 15797 * 3: r0 = 2 15798 * 4: exit 15799 * when the verifier reaches exit insn the register r0 in the state list of 15800 * insn 2 will be seen as !REG_LIVE_READ. Then the verifier pops the other_branch 15801 * of insn 2 and goes exploring further. At the insn 4 it will walk the 15802 * parentage chain from insn 4 into insn 2 and will mark r0 as REG_LIVE_READ. 15803 * 15804 * Since the verifier pushes the branch states as it sees them while exploring 15805 * the program the condition of walking the branch instruction for the second 15806 * time means that all states below this branch were already explored and 15807 * their final liveness marks are already propagated. 15808 * Hence when the verifier completes the search of state list in is_state_visited() 15809 * we can call this clean_live_states() function to mark all liveness states 15810 * as REG_LIVE_DONE to indicate that 'parent' pointers of 'struct bpf_reg_state' 15811 * will not be used. 15812 * This function also clears the registers and stack for states that !READ 15813 * to simplify state merging. 15814 * 15815 * Important note here that walking the same branch instruction in the callee 15816 * doesn't meant that the states are DONE. The verifier has to compare 15817 * the callsites 15818 */ 15819 static void clean_live_states(struct bpf_verifier_env *env, int insn, 15820 struct bpf_verifier_state *cur) 15821 { 15822 struct bpf_verifier_state_list *sl; 15823 int i; 15824 15825 sl = *explored_state(env, insn); 15826 while (sl) { 15827 if (sl->state.branches) 15828 goto next; 15829 if (sl->state.insn_idx != insn || 15830 sl->state.curframe != cur->curframe) 15831 goto next; 15832 for (i = 0; i <= cur->curframe; i++) 15833 if (sl->state.frame[i]->callsite != cur->frame[i]->callsite) 15834 goto next; 15835 clean_verifier_state(env, &sl->state); 15836 next: 15837 sl = sl->next; 15838 } 15839 } 15840 15841 static bool regs_exact(const struct bpf_reg_state *rold, 15842 const struct bpf_reg_state *rcur, 15843 struct bpf_idmap *idmap) 15844 { 15845 return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 && 15846 check_ids(rold->id, rcur->id, idmap) && 15847 check_ids(rold->ref_obj_id, rcur->ref_obj_id, idmap); 15848 } 15849 15850 /* Returns true if (rold safe implies rcur safe) */ 15851 static bool regsafe(struct bpf_verifier_env *env, struct bpf_reg_state *rold, 15852 struct bpf_reg_state *rcur, struct bpf_idmap *idmap) 15853 { 15854 if (!(rold->live & REG_LIVE_READ)) 15855 /* explored state didn't use this */ 15856 return true; 15857 if (rold->type == NOT_INIT) 15858 /* explored state can't have used this */ 15859 return true; 15860 if (rcur->type == NOT_INIT) 15861 return false; 15862 15863 /* Enforce that register types have to match exactly, including their 15864 * modifiers (like PTR_MAYBE_NULL, MEM_RDONLY, etc), as a general 15865 * rule. 15866 * 15867 * One can make a point that using a pointer register as unbounded 15868 * SCALAR would be technically acceptable, but this could lead to 15869 * pointer leaks because scalars are allowed to leak while pointers 15870 * are not. We could make this safe in special cases if root is 15871 * calling us, but it's probably not worth the hassle. 15872 * 15873 * Also, register types that are *not* MAYBE_NULL could technically be 15874 * safe to use as their MAYBE_NULL variants (e.g., PTR_TO_MAP_VALUE 15875 * is safe to be used as PTR_TO_MAP_VALUE_OR_NULL, provided both point 15876 * to the same map). 15877 * However, if the old MAYBE_NULL register then got NULL checked, 15878 * doing so could have affected others with the same id, and we can't 15879 * check for that because we lost the id when we converted to 15880 * a non-MAYBE_NULL variant. 15881 * So, as a general rule we don't allow mixing MAYBE_NULL and 15882 * non-MAYBE_NULL registers as well. 15883 */ 15884 if (rold->type != rcur->type) 15885 return false; 15886 15887 switch (base_type(rold->type)) { 15888 case SCALAR_VALUE: 15889 if (env->explore_alu_limits) { 15890 /* explore_alu_limits disables tnum_in() and range_within() 15891 * logic and requires everything to be strict 15892 */ 15893 return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 && 15894 check_scalar_ids(rold->id, rcur->id, idmap); 15895 } 15896 if (!rold->precise) 15897 return true; 15898 /* Why check_ids() for scalar registers? 15899 * 15900 * Consider the following BPF code: 15901 * 1: r6 = ... unbound scalar, ID=a ... 15902 * 2: r7 = ... unbound scalar, ID=b ... 15903 * 3: if (r6 > r7) goto +1 15904 * 4: r6 = r7 15905 * 5: if (r6 > X) goto ... 15906 * 6: ... memory operation using r7 ... 15907 * 15908 * First verification path is [1-6]: 15909 * - at (4) same bpf_reg_state::id (b) would be assigned to r6 and r7; 15910 * - at (5) r6 would be marked <= X, find_equal_scalars() would also mark 15911 * r7 <= X, because r6 and r7 share same id. 15912 * Next verification path is [1-4, 6]. 15913 * 15914 * Instruction (6) would be reached in two states: 15915 * I. r6{.id=b}, r7{.id=b} via path 1-6; 15916 * II. r6{.id=a}, r7{.id=b} via path 1-4, 6. 15917 * 15918 * Use check_ids() to distinguish these states. 15919 * --- 15920 * Also verify that new value satisfies old value range knowledge. 15921 */ 15922 return range_within(rold, rcur) && 15923 tnum_in(rold->var_off, rcur->var_off) && 15924 check_scalar_ids(rold->id, rcur->id, idmap); 15925 case PTR_TO_MAP_KEY: 15926 case PTR_TO_MAP_VALUE: 15927 case PTR_TO_MEM: 15928 case PTR_TO_BUF: 15929 case PTR_TO_TP_BUFFER: 15930 /* If the new min/max/var_off satisfy the old ones and 15931 * everything else matches, we are OK. 15932 */ 15933 return memcmp(rold, rcur, offsetof(struct bpf_reg_state, var_off)) == 0 && 15934 range_within(rold, rcur) && 15935 tnum_in(rold->var_off, rcur->var_off) && 15936 check_ids(rold->id, rcur->id, idmap) && 15937 check_ids(rold->ref_obj_id, rcur->ref_obj_id, idmap); 15938 case PTR_TO_PACKET_META: 15939 case PTR_TO_PACKET: 15940 /* We must have at least as much range as the old ptr 15941 * did, so that any accesses which were safe before are 15942 * still safe. This is true even if old range < old off, 15943 * since someone could have accessed through (ptr - k), or 15944 * even done ptr -= k in a register, to get a safe access. 15945 */ 15946 if (rold->range > rcur->range) 15947 return false; 15948 /* If the offsets don't match, we can't trust our alignment; 15949 * nor can we be sure that we won't fall out of range. 15950 */ 15951 if (rold->off != rcur->off) 15952 return false; 15953 /* id relations must be preserved */ 15954 if (!check_ids(rold->id, rcur->id, idmap)) 15955 return false; 15956 /* new val must satisfy old val knowledge */ 15957 return range_within(rold, rcur) && 15958 tnum_in(rold->var_off, rcur->var_off); 15959 case PTR_TO_STACK: 15960 /* two stack pointers are equal only if they're pointing to 15961 * the same stack frame, since fp-8 in foo != fp-8 in bar 15962 */ 15963 return regs_exact(rold, rcur, idmap) && rold->frameno == rcur->frameno; 15964 default: 15965 return regs_exact(rold, rcur, idmap); 15966 } 15967 } 15968 15969 static bool stacksafe(struct bpf_verifier_env *env, struct bpf_func_state *old, 15970 struct bpf_func_state *cur, struct bpf_idmap *idmap) 15971 { 15972 int i, spi; 15973 15974 /* walk slots of the explored stack and ignore any additional 15975 * slots in the current stack, since explored(safe) state 15976 * didn't use them 15977 */ 15978 for (i = 0; i < old->allocated_stack; i++) { 15979 struct bpf_reg_state *old_reg, *cur_reg; 15980 15981 spi = i / BPF_REG_SIZE; 15982 15983 if (!(old->stack[spi].spilled_ptr.live & REG_LIVE_READ)) { 15984 i += BPF_REG_SIZE - 1; 15985 /* explored state didn't use this */ 15986 continue; 15987 } 15988 15989 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_INVALID) 15990 continue; 15991 15992 if (env->allow_uninit_stack && 15993 old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC) 15994 continue; 15995 15996 /* explored stack has more populated slots than current stack 15997 * and these slots were used 15998 */ 15999 if (i >= cur->allocated_stack) 16000 return false; 16001 16002 /* if old state was safe with misc data in the stack 16003 * it will be safe with zero-initialized stack. 16004 * The opposite is not true 16005 */ 16006 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC && 16007 cur->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_ZERO) 16008 continue; 16009 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] != 16010 cur->stack[spi].slot_type[i % BPF_REG_SIZE]) 16011 /* Ex: old explored (safe) state has STACK_SPILL in 16012 * this stack slot, but current has STACK_MISC -> 16013 * this verifier states are not equivalent, 16014 * return false to continue verification of this path 16015 */ 16016 return false; 16017 if (i % BPF_REG_SIZE != BPF_REG_SIZE - 1) 16018 continue; 16019 /* Both old and cur are having same slot_type */ 16020 switch (old->stack[spi].slot_type[BPF_REG_SIZE - 1]) { 16021 case STACK_SPILL: 16022 /* when explored and current stack slot are both storing 16023 * spilled registers, check that stored pointers types 16024 * are the same as well. 16025 * Ex: explored safe path could have stored 16026 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -8} 16027 * but current path has stored: 16028 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -16} 16029 * such verifier states are not equivalent. 16030 * return false to continue verification of this path 16031 */ 16032 if (!regsafe(env, &old->stack[spi].spilled_ptr, 16033 &cur->stack[spi].spilled_ptr, idmap)) 16034 return false; 16035 break; 16036 case STACK_DYNPTR: 16037 old_reg = &old->stack[spi].spilled_ptr; 16038 cur_reg = &cur->stack[spi].spilled_ptr; 16039 if (old_reg->dynptr.type != cur_reg->dynptr.type || 16040 old_reg->dynptr.first_slot != cur_reg->dynptr.first_slot || 16041 !check_ids(old_reg->ref_obj_id, cur_reg->ref_obj_id, idmap)) 16042 return false; 16043 break; 16044 case STACK_ITER: 16045 old_reg = &old->stack[spi].spilled_ptr; 16046 cur_reg = &cur->stack[spi].spilled_ptr; 16047 /* iter.depth is not compared between states as it 16048 * doesn't matter for correctness and would otherwise 16049 * prevent convergence; we maintain it only to prevent 16050 * infinite loop check triggering, see 16051 * iter_active_depths_differ() 16052 */ 16053 if (old_reg->iter.btf != cur_reg->iter.btf || 16054 old_reg->iter.btf_id != cur_reg->iter.btf_id || 16055 old_reg->iter.state != cur_reg->iter.state || 16056 /* ignore {old_reg,cur_reg}->iter.depth, see above */ 16057 !check_ids(old_reg->ref_obj_id, cur_reg->ref_obj_id, idmap)) 16058 return false; 16059 break; 16060 case STACK_MISC: 16061 case STACK_ZERO: 16062 case STACK_INVALID: 16063 continue; 16064 /* Ensure that new unhandled slot types return false by default */ 16065 default: 16066 return false; 16067 } 16068 } 16069 return true; 16070 } 16071 16072 static bool refsafe(struct bpf_func_state *old, struct bpf_func_state *cur, 16073 struct bpf_idmap *idmap) 16074 { 16075 int i; 16076 16077 if (old->acquired_refs != cur->acquired_refs) 16078 return false; 16079 16080 for (i = 0; i < old->acquired_refs; i++) { 16081 if (!check_ids(old->refs[i].id, cur->refs[i].id, idmap)) 16082 return false; 16083 } 16084 16085 return true; 16086 } 16087 16088 /* compare two verifier states 16089 * 16090 * all states stored in state_list are known to be valid, since 16091 * verifier reached 'bpf_exit' instruction through them 16092 * 16093 * this function is called when verifier exploring different branches of 16094 * execution popped from the state stack. If it sees an old state that has 16095 * more strict register state and more strict stack state then this execution 16096 * branch doesn't need to be explored further, since verifier already 16097 * concluded that more strict state leads to valid finish. 16098 * 16099 * Therefore two states are equivalent if register state is more conservative 16100 * and explored stack state is more conservative than the current one. 16101 * Example: 16102 * explored current 16103 * (slot1=INV slot2=MISC) == (slot1=MISC slot2=MISC) 16104 * (slot1=MISC slot2=MISC) != (slot1=INV slot2=MISC) 16105 * 16106 * In other words if current stack state (one being explored) has more 16107 * valid slots than old one that already passed validation, it means 16108 * the verifier can stop exploring and conclude that current state is valid too 16109 * 16110 * Similarly with registers. If explored state has register type as invalid 16111 * whereas register type in current state is meaningful, it means that 16112 * the current state will reach 'bpf_exit' instruction safely 16113 */ 16114 static bool func_states_equal(struct bpf_verifier_env *env, struct bpf_func_state *old, 16115 struct bpf_func_state *cur) 16116 { 16117 int i; 16118 16119 for (i = 0; i < MAX_BPF_REG; i++) 16120 if (!regsafe(env, &old->regs[i], &cur->regs[i], 16121 &env->idmap_scratch)) 16122 return false; 16123 16124 if (!stacksafe(env, old, cur, &env->idmap_scratch)) 16125 return false; 16126 16127 if (!refsafe(old, cur, &env->idmap_scratch)) 16128 return false; 16129 16130 return true; 16131 } 16132 16133 static bool states_equal(struct bpf_verifier_env *env, 16134 struct bpf_verifier_state *old, 16135 struct bpf_verifier_state *cur) 16136 { 16137 int i; 16138 16139 if (old->curframe != cur->curframe) 16140 return false; 16141 16142 env->idmap_scratch.tmp_id_gen = env->id_gen; 16143 memset(&env->idmap_scratch.map, 0, sizeof(env->idmap_scratch.map)); 16144 16145 /* Verification state from speculative execution simulation 16146 * must never prune a non-speculative execution one. 16147 */ 16148 if (old->speculative && !cur->speculative) 16149 return false; 16150 16151 if (old->active_lock.ptr != cur->active_lock.ptr) 16152 return false; 16153 16154 /* Old and cur active_lock's have to be either both present 16155 * or both absent. 16156 */ 16157 if (!!old->active_lock.id != !!cur->active_lock.id) 16158 return false; 16159 16160 if (old->active_lock.id && 16161 !check_ids(old->active_lock.id, cur->active_lock.id, &env->idmap_scratch)) 16162 return false; 16163 16164 if (old->active_rcu_lock != cur->active_rcu_lock) 16165 return false; 16166 16167 /* for states to be equal callsites have to be the same 16168 * and all frame states need to be equivalent 16169 */ 16170 for (i = 0; i <= old->curframe; i++) { 16171 if (old->frame[i]->callsite != cur->frame[i]->callsite) 16172 return false; 16173 if (!func_states_equal(env, old->frame[i], cur->frame[i])) 16174 return false; 16175 } 16176 return true; 16177 } 16178 16179 /* Return 0 if no propagation happened. Return negative error code if error 16180 * happened. Otherwise, return the propagated bit. 16181 */ 16182 static int propagate_liveness_reg(struct bpf_verifier_env *env, 16183 struct bpf_reg_state *reg, 16184 struct bpf_reg_state *parent_reg) 16185 { 16186 u8 parent_flag = parent_reg->live & REG_LIVE_READ; 16187 u8 flag = reg->live & REG_LIVE_READ; 16188 int err; 16189 16190 /* When comes here, read flags of PARENT_REG or REG could be any of 16191 * REG_LIVE_READ64, REG_LIVE_READ32, REG_LIVE_NONE. There is no need 16192 * of propagation if PARENT_REG has strongest REG_LIVE_READ64. 16193 */ 16194 if (parent_flag == REG_LIVE_READ64 || 16195 /* Or if there is no read flag from REG. */ 16196 !flag || 16197 /* Or if the read flag from REG is the same as PARENT_REG. */ 16198 parent_flag == flag) 16199 return 0; 16200 16201 err = mark_reg_read(env, reg, parent_reg, flag); 16202 if (err) 16203 return err; 16204 16205 return flag; 16206 } 16207 16208 /* A write screens off any subsequent reads; but write marks come from the 16209 * straight-line code between a state and its parent. When we arrive at an 16210 * equivalent state (jump target or such) we didn't arrive by the straight-line 16211 * code, so read marks in the state must propagate to the parent regardless 16212 * of the state's write marks. That's what 'parent == state->parent' comparison 16213 * in mark_reg_read() is for. 16214 */ 16215 static int propagate_liveness(struct bpf_verifier_env *env, 16216 const struct bpf_verifier_state *vstate, 16217 struct bpf_verifier_state *vparent) 16218 { 16219 struct bpf_reg_state *state_reg, *parent_reg; 16220 struct bpf_func_state *state, *parent; 16221 int i, frame, err = 0; 16222 16223 if (vparent->curframe != vstate->curframe) { 16224 WARN(1, "propagate_live: parent frame %d current frame %d\n", 16225 vparent->curframe, vstate->curframe); 16226 return -EFAULT; 16227 } 16228 /* Propagate read liveness of registers... */ 16229 BUILD_BUG_ON(BPF_REG_FP + 1 != MAX_BPF_REG); 16230 for (frame = 0; frame <= vstate->curframe; frame++) { 16231 parent = vparent->frame[frame]; 16232 state = vstate->frame[frame]; 16233 parent_reg = parent->regs; 16234 state_reg = state->regs; 16235 /* We don't need to worry about FP liveness, it's read-only */ 16236 for (i = frame < vstate->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++) { 16237 err = propagate_liveness_reg(env, &state_reg[i], 16238 &parent_reg[i]); 16239 if (err < 0) 16240 return err; 16241 if (err == REG_LIVE_READ64) 16242 mark_insn_zext(env, &parent_reg[i]); 16243 } 16244 16245 /* Propagate stack slots. */ 16246 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE && 16247 i < parent->allocated_stack / BPF_REG_SIZE; i++) { 16248 parent_reg = &parent->stack[i].spilled_ptr; 16249 state_reg = &state->stack[i].spilled_ptr; 16250 err = propagate_liveness_reg(env, state_reg, 16251 parent_reg); 16252 if (err < 0) 16253 return err; 16254 } 16255 } 16256 return 0; 16257 } 16258 16259 /* find precise scalars in the previous equivalent state and 16260 * propagate them into the current state 16261 */ 16262 static int propagate_precision(struct bpf_verifier_env *env, 16263 const struct bpf_verifier_state *old) 16264 { 16265 struct bpf_reg_state *state_reg; 16266 struct bpf_func_state *state; 16267 int i, err = 0, fr; 16268 bool first; 16269 16270 for (fr = old->curframe; fr >= 0; fr--) { 16271 state = old->frame[fr]; 16272 state_reg = state->regs; 16273 first = true; 16274 for (i = 0; i < BPF_REG_FP; i++, state_reg++) { 16275 if (state_reg->type != SCALAR_VALUE || 16276 !state_reg->precise || 16277 !(state_reg->live & REG_LIVE_READ)) 16278 continue; 16279 if (env->log.level & BPF_LOG_LEVEL2) { 16280 if (first) 16281 verbose(env, "frame %d: propagating r%d", fr, i); 16282 else 16283 verbose(env, ",r%d", i); 16284 } 16285 bt_set_frame_reg(&env->bt, fr, i); 16286 first = false; 16287 } 16288 16289 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) { 16290 if (!is_spilled_reg(&state->stack[i])) 16291 continue; 16292 state_reg = &state->stack[i].spilled_ptr; 16293 if (state_reg->type != SCALAR_VALUE || 16294 !state_reg->precise || 16295 !(state_reg->live & REG_LIVE_READ)) 16296 continue; 16297 if (env->log.level & BPF_LOG_LEVEL2) { 16298 if (first) 16299 verbose(env, "frame %d: propagating fp%d", 16300 fr, (-i - 1) * BPF_REG_SIZE); 16301 else 16302 verbose(env, ",fp%d", (-i - 1) * BPF_REG_SIZE); 16303 } 16304 bt_set_frame_slot(&env->bt, fr, i); 16305 first = false; 16306 } 16307 if (!first) 16308 verbose(env, "\n"); 16309 } 16310 16311 err = mark_chain_precision_batch(env); 16312 if (err < 0) 16313 return err; 16314 16315 return 0; 16316 } 16317 16318 static bool states_maybe_looping(struct bpf_verifier_state *old, 16319 struct bpf_verifier_state *cur) 16320 { 16321 struct bpf_func_state *fold, *fcur; 16322 int i, fr = cur->curframe; 16323 16324 if (old->curframe != fr) 16325 return false; 16326 16327 fold = old->frame[fr]; 16328 fcur = cur->frame[fr]; 16329 for (i = 0; i < MAX_BPF_REG; i++) 16330 if (memcmp(&fold->regs[i], &fcur->regs[i], 16331 offsetof(struct bpf_reg_state, parent))) 16332 return false; 16333 return true; 16334 } 16335 16336 static bool is_iter_next_insn(struct bpf_verifier_env *env, int insn_idx) 16337 { 16338 return env->insn_aux_data[insn_idx].is_iter_next; 16339 } 16340 16341 /* is_state_visited() handles iter_next() (see process_iter_next_call() for 16342 * terminology) calls specially: as opposed to bounded BPF loops, it *expects* 16343 * states to match, which otherwise would look like an infinite loop. So while 16344 * iter_next() calls are taken care of, we still need to be careful and 16345 * prevent erroneous and too eager declaration of "ininite loop", when 16346 * iterators are involved. 16347 * 16348 * Here's a situation in pseudo-BPF assembly form: 16349 * 16350 * 0: again: ; set up iter_next() call args 16351 * 1: r1 = &it ; <CHECKPOINT HERE> 16352 * 2: call bpf_iter_num_next ; this is iter_next() call 16353 * 3: if r0 == 0 goto done 16354 * 4: ... something useful here ... 16355 * 5: goto again ; another iteration 16356 * 6: done: 16357 * 7: r1 = &it 16358 * 8: call bpf_iter_num_destroy ; clean up iter state 16359 * 9: exit 16360 * 16361 * This is a typical loop. Let's assume that we have a prune point at 1:, 16362 * before we get to `call bpf_iter_num_next` (e.g., because of that `goto 16363 * again`, assuming other heuristics don't get in a way). 16364 * 16365 * When we first time come to 1:, let's say we have some state X. We proceed 16366 * to 2:, fork states, enqueue ACTIVE, validate NULL case successfully, exit. 16367 * Now we come back to validate that forked ACTIVE state. We proceed through 16368 * 3-5, come to goto, jump to 1:. Let's assume our state didn't change, so we 16369 * are converging. But the problem is that we don't know that yet, as this 16370 * convergence has to happen at iter_next() call site only. So if nothing is 16371 * done, at 1: verifier will use bounded loop logic and declare infinite 16372 * looping (and would be *technically* correct, if not for iterator's 16373 * "eventual sticky NULL" contract, see process_iter_next_call()). But we 16374 * don't want that. So what we do in process_iter_next_call() when we go on 16375 * another ACTIVE iteration, we bump slot->iter.depth, to mark that it's 16376 * a different iteration. So when we suspect an infinite loop, we additionally 16377 * check if any of the *ACTIVE* iterator states depths differ. If yes, we 16378 * pretend we are not looping and wait for next iter_next() call. 16379 * 16380 * This only applies to ACTIVE state. In DRAINED state we don't expect to 16381 * loop, because that would actually mean infinite loop, as DRAINED state is 16382 * "sticky", and so we'll keep returning into the same instruction with the 16383 * same state (at least in one of possible code paths). 16384 * 16385 * This approach allows to keep infinite loop heuristic even in the face of 16386 * active iterator. E.g., C snippet below is and will be detected as 16387 * inifintely looping: 16388 * 16389 * struct bpf_iter_num it; 16390 * int *p, x; 16391 * 16392 * bpf_iter_num_new(&it, 0, 10); 16393 * while ((p = bpf_iter_num_next(&t))) { 16394 * x = p; 16395 * while (x--) {} // <<-- infinite loop here 16396 * } 16397 * 16398 */ 16399 static bool iter_active_depths_differ(struct bpf_verifier_state *old, struct bpf_verifier_state *cur) 16400 { 16401 struct bpf_reg_state *slot, *cur_slot; 16402 struct bpf_func_state *state; 16403 int i, fr; 16404 16405 for (fr = old->curframe; fr >= 0; fr--) { 16406 state = old->frame[fr]; 16407 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) { 16408 if (state->stack[i].slot_type[0] != STACK_ITER) 16409 continue; 16410 16411 slot = &state->stack[i].spilled_ptr; 16412 if (slot->iter.state != BPF_ITER_STATE_ACTIVE) 16413 continue; 16414 16415 cur_slot = &cur->frame[fr]->stack[i].spilled_ptr; 16416 if (cur_slot->iter.depth != slot->iter.depth) 16417 return true; 16418 } 16419 } 16420 return false; 16421 } 16422 16423 static int is_state_visited(struct bpf_verifier_env *env, int insn_idx) 16424 { 16425 struct bpf_verifier_state_list *new_sl; 16426 struct bpf_verifier_state_list *sl, **pprev; 16427 struct bpf_verifier_state *cur = env->cur_state, *new; 16428 int i, j, err, states_cnt = 0; 16429 bool force_new_state = env->test_state_freq || is_force_checkpoint(env, insn_idx); 16430 bool add_new_state = force_new_state; 16431 16432 /* bpf progs typically have pruning point every 4 instructions 16433 * http://vger.kernel.org/bpfconf2019.html#session-1 16434 * Do not add new state for future pruning if the verifier hasn't seen 16435 * at least 2 jumps and at least 8 instructions. 16436 * This heuristics helps decrease 'total_states' and 'peak_states' metric. 16437 * In tests that amounts to up to 50% reduction into total verifier 16438 * memory consumption and 20% verifier time speedup. 16439 */ 16440 if (env->jmps_processed - env->prev_jmps_processed >= 2 && 16441 env->insn_processed - env->prev_insn_processed >= 8) 16442 add_new_state = true; 16443 16444 pprev = explored_state(env, insn_idx); 16445 sl = *pprev; 16446 16447 clean_live_states(env, insn_idx, cur); 16448 16449 while (sl) { 16450 states_cnt++; 16451 if (sl->state.insn_idx != insn_idx) 16452 goto next; 16453 16454 if (sl->state.branches) { 16455 struct bpf_func_state *frame = sl->state.frame[sl->state.curframe]; 16456 16457 if (frame->in_async_callback_fn && 16458 frame->async_entry_cnt != cur->frame[cur->curframe]->async_entry_cnt) { 16459 /* Different async_entry_cnt means that the verifier is 16460 * processing another entry into async callback. 16461 * Seeing the same state is not an indication of infinite 16462 * loop or infinite recursion. 16463 * But finding the same state doesn't mean that it's safe 16464 * to stop processing the current state. The previous state 16465 * hasn't yet reached bpf_exit, since state.branches > 0. 16466 * Checking in_async_callback_fn alone is not enough either. 16467 * Since the verifier still needs to catch infinite loops 16468 * inside async callbacks. 16469 */ 16470 goto skip_inf_loop_check; 16471 } 16472 /* BPF open-coded iterators loop detection is special. 16473 * states_maybe_looping() logic is too simplistic in detecting 16474 * states that *might* be equivalent, because it doesn't know 16475 * about ID remapping, so don't even perform it. 16476 * See process_iter_next_call() and iter_active_depths_differ() 16477 * for overview of the logic. When current and one of parent 16478 * states are detected as equivalent, it's a good thing: we prove 16479 * convergence and can stop simulating further iterations. 16480 * It's safe to assume that iterator loop will finish, taking into 16481 * account iter_next() contract of eventually returning 16482 * sticky NULL result. 16483 */ 16484 if (is_iter_next_insn(env, insn_idx)) { 16485 if (states_equal(env, &sl->state, cur)) { 16486 struct bpf_func_state *cur_frame; 16487 struct bpf_reg_state *iter_state, *iter_reg; 16488 int spi; 16489 16490 cur_frame = cur->frame[cur->curframe]; 16491 /* btf_check_iter_kfuncs() enforces that 16492 * iter state pointer is always the first arg 16493 */ 16494 iter_reg = &cur_frame->regs[BPF_REG_1]; 16495 /* current state is valid due to states_equal(), 16496 * so we can assume valid iter and reg state, 16497 * no need for extra (re-)validations 16498 */ 16499 spi = __get_spi(iter_reg->off + iter_reg->var_off.value); 16500 iter_state = &func(env, iter_reg)->stack[spi].spilled_ptr; 16501 if (iter_state->iter.state == BPF_ITER_STATE_ACTIVE) 16502 goto hit; 16503 } 16504 goto skip_inf_loop_check; 16505 } 16506 /* attempt to detect infinite loop to avoid unnecessary doomed work */ 16507 if (states_maybe_looping(&sl->state, cur) && 16508 states_equal(env, &sl->state, cur) && 16509 !iter_active_depths_differ(&sl->state, cur)) { 16510 verbose_linfo(env, insn_idx, "; "); 16511 verbose(env, "infinite loop detected at insn %d\n", insn_idx); 16512 return -EINVAL; 16513 } 16514 /* if the verifier is processing a loop, avoid adding new state 16515 * too often, since different loop iterations have distinct 16516 * states and may not help future pruning. 16517 * This threshold shouldn't be too low to make sure that 16518 * a loop with large bound will be rejected quickly. 16519 * The most abusive loop will be: 16520 * r1 += 1 16521 * if r1 < 1000000 goto pc-2 16522 * 1M insn_procssed limit / 100 == 10k peak states. 16523 * This threshold shouldn't be too high either, since states 16524 * at the end of the loop are likely to be useful in pruning. 16525 */ 16526 skip_inf_loop_check: 16527 if (!force_new_state && 16528 env->jmps_processed - env->prev_jmps_processed < 20 && 16529 env->insn_processed - env->prev_insn_processed < 100) 16530 add_new_state = false; 16531 goto miss; 16532 } 16533 if (states_equal(env, &sl->state, cur)) { 16534 hit: 16535 sl->hit_cnt++; 16536 /* reached equivalent register/stack state, 16537 * prune the search. 16538 * Registers read by the continuation are read by us. 16539 * If we have any write marks in env->cur_state, they 16540 * will prevent corresponding reads in the continuation 16541 * from reaching our parent (an explored_state). Our 16542 * own state will get the read marks recorded, but 16543 * they'll be immediately forgotten as we're pruning 16544 * this state and will pop a new one. 16545 */ 16546 err = propagate_liveness(env, &sl->state, cur); 16547 16548 /* if previous state reached the exit with precision and 16549 * current state is equivalent to it (except precsion marks) 16550 * the precision needs to be propagated back in 16551 * the current state. 16552 */ 16553 err = err ? : push_jmp_history(env, cur); 16554 err = err ? : propagate_precision(env, &sl->state); 16555 if (err) 16556 return err; 16557 return 1; 16558 } 16559 miss: 16560 /* when new state is not going to be added do not increase miss count. 16561 * Otherwise several loop iterations will remove the state 16562 * recorded earlier. The goal of these heuristics is to have 16563 * states from some iterations of the loop (some in the beginning 16564 * and some at the end) to help pruning. 16565 */ 16566 if (add_new_state) 16567 sl->miss_cnt++; 16568 /* heuristic to determine whether this state is beneficial 16569 * to keep checking from state equivalence point of view. 16570 * Higher numbers increase max_states_per_insn and verification time, 16571 * but do not meaningfully decrease insn_processed. 16572 */ 16573 if (sl->miss_cnt > sl->hit_cnt * 3 + 3) { 16574 /* the state is unlikely to be useful. Remove it to 16575 * speed up verification 16576 */ 16577 *pprev = sl->next; 16578 if (sl->state.frame[0]->regs[0].live & REG_LIVE_DONE) { 16579 u32 br = sl->state.branches; 16580 16581 WARN_ONCE(br, 16582 "BUG live_done but branches_to_explore %d\n", 16583 br); 16584 free_verifier_state(&sl->state, false); 16585 kfree(sl); 16586 env->peak_states--; 16587 } else { 16588 /* cannot free this state, since parentage chain may 16589 * walk it later. Add it for free_list instead to 16590 * be freed at the end of verification 16591 */ 16592 sl->next = env->free_list; 16593 env->free_list = sl; 16594 } 16595 sl = *pprev; 16596 continue; 16597 } 16598 next: 16599 pprev = &sl->next; 16600 sl = *pprev; 16601 } 16602 16603 if (env->max_states_per_insn < states_cnt) 16604 env->max_states_per_insn = states_cnt; 16605 16606 if (!env->bpf_capable && states_cnt > BPF_COMPLEXITY_LIMIT_STATES) 16607 return 0; 16608 16609 if (!add_new_state) 16610 return 0; 16611 16612 /* There were no equivalent states, remember the current one. 16613 * Technically the current state is not proven to be safe yet, 16614 * but it will either reach outer most bpf_exit (which means it's safe) 16615 * or it will be rejected. When there are no loops the verifier won't be 16616 * seeing this tuple (frame[0].callsite, frame[1].callsite, .. insn_idx) 16617 * again on the way to bpf_exit. 16618 * When looping the sl->state.branches will be > 0 and this state 16619 * will not be considered for equivalence until branches == 0. 16620 */ 16621 new_sl = kzalloc(sizeof(struct bpf_verifier_state_list), GFP_KERNEL); 16622 if (!new_sl) 16623 return -ENOMEM; 16624 env->total_states++; 16625 env->peak_states++; 16626 env->prev_jmps_processed = env->jmps_processed; 16627 env->prev_insn_processed = env->insn_processed; 16628 16629 /* forget precise markings we inherited, see __mark_chain_precision */ 16630 if (env->bpf_capable) 16631 mark_all_scalars_imprecise(env, cur); 16632 16633 /* add new state to the head of linked list */ 16634 new = &new_sl->state; 16635 err = copy_verifier_state(new, cur); 16636 if (err) { 16637 free_verifier_state(new, false); 16638 kfree(new_sl); 16639 return err; 16640 } 16641 new->insn_idx = insn_idx; 16642 WARN_ONCE(new->branches != 1, 16643 "BUG is_state_visited:branches_to_explore=%d insn %d\n", new->branches, insn_idx); 16644 16645 cur->parent = new; 16646 cur->first_insn_idx = insn_idx; 16647 clear_jmp_history(cur); 16648 new_sl->next = *explored_state(env, insn_idx); 16649 *explored_state(env, insn_idx) = new_sl; 16650 /* connect new state to parentage chain. Current frame needs all 16651 * registers connected. Only r6 - r9 of the callers are alive (pushed 16652 * to the stack implicitly by JITs) so in callers' frames connect just 16653 * r6 - r9 as an optimization. Callers will have r1 - r5 connected to 16654 * the state of the call instruction (with WRITTEN set), and r0 comes 16655 * from callee with its full parentage chain, anyway. 16656 */ 16657 /* clear write marks in current state: the writes we did are not writes 16658 * our child did, so they don't screen off its reads from us. 16659 * (There are no read marks in current state, because reads always mark 16660 * their parent and current state never has children yet. Only 16661 * explored_states can get read marks.) 16662 */ 16663 for (j = 0; j <= cur->curframe; j++) { 16664 for (i = j < cur->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++) 16665 cur->frame[j]->regs[i].parent = &new->frame[j]->regs[i]; 16666 for (i = 0; i < BPF_REG_FP; i++) 16667 cur->frame[j]->regs[i].live = REG_LIVE_NONE; 16668 } 16669 16670 /* all stack frames are accessible from callee, clear them all */ 16671 for (j = 0; j <= cur->curframe; j++) { 16672 struct bpf_func_state *frame = cur->frame[j]; 16673 struct bpf_func_state *newframe = new->frame[j]; 16674 16675 for (i = 0; i < frame->allocated_stack / BPF_REG_SIZE; i++) { 16676 frame->stack[i].spilled_ptr.live = REG_LIVE_NONE; 16677 frame->stack[i].spilled_ptr.parent = 16678 &newframe->stack[i].spilled_ptr; 16679 } 16680 } 16681 return 0; 16682 } 16683 16684 /* Return true if it's OK to have the same insn return a different type. */ 16685 static bool reg_type_mismatch_ok(enum bpf_reg_type type) 16686 { 16687 switch (base_type(type)) { 16688 case PTR_TO_CTX: 16689 case PTR_TO_SOCKET: 16690 case PTR_TO_SOCK_COMMON: 16691 case PTR_TO_TCP_SOCK: 16692 case PTR_TO_XDP_SOCK: 16693 case PTR_TO_BTF_ID: 16694 return false; 16695 default: 16696 return true; 16697 } 16698 } 16699 16700 /* If an instruction was previously used with particular pointer types, then we 16701 * need to be careful to avoid cases such as the below, where it may be ok 16702 * for one branch accessing the pointer, but not ok for the other branch: 16703 * 16704 * R1 = sock_ptr 16705 * goto X; 16706 * ... 16707 * R1 = some_other_valid_ptr; 16708 * goto X; 16709 * ... 16710 * R2 = *(u32 *)(R1 + 0); 16711 */ 16712 static bool reg_type_mismatch(enum bpf_reg_type src, enum bpf_reg_type prev) 16713 { 16714 return src != prev && (!reg_type_mismatch_ok(src) || 16715 !reg_type_mismatch_ok(prev)); 16716 } 16717 16718 static int save_aux_ptr_type(struct bpf_verifier_env *env, enum bpf_reg_type type, 16719 bool allow_trust_missmatch) 16720 { 16721 enum bpf_reg_type *prev_type = &env->insn_aux_data[env->insn_idx].ptr_type; 16722 16723 if (*prev_type == NOT_INIT) { 16724 /* Saw a valid insn 16725 * dst_reg = *(u32 *)(src_reg + off) 16726 * save type to validate intersecting paths 16727 */ 16728 *prev_type = type; 16729 } else if (reg_type_mismatch(type, *prev_type)) { 16730 /* Abuser program is trying to use the same insn 16731 * dst_reg = *(u32*) (src_reg + off) 16732 * with different pointer types: 16733 * src_reg == ctx in one branch and 16734 * src_reg == stack|map in some other branch. 16735 * Reject it. 16736 */ 16737 if (allow_trust_missmatch && 16738 base_type(type) == PTR_TO_BTF_ID && 16739 base_type(*prev_type) == PTR_TO_BTF_ID) { 16740 /* 16741 * Have to support a use case when one path through 16742 * the program yields TRUSTED pointer while another 16743 * is UNTRUSTED. Fallback to UNTRUSTED to generate 16744 * BPF_PROBE_MEM/BPF_PROBE_MEMSX. 16745 */ 16746 *prev_type = PTR_TO_BTF_ID | PTR_UNTRUSTED; 16747 } else { 16748 verbose(env, "same insn cannot be used with different pointers\n"); 16749 return -EINVAL; 16750 } 16751 } 16752 16753 return 0; 16754 } 16755 16756 static int do_check(struct bpf_verifier_env *env) 16757 { 16758 bool pop_log = !(env->log.level & BPF_LOG_LEVEL2); 16759 struct bpf_verifier_state *state = env->cur_state; 16760 struct bpf_insn *insns = env->prog->insnsi; 16761 struct bpf_reg_state *regs; 16762 int insn_cnt = env->prog->len; 16763 bool do_print_state = false; 16764 int prev_insn_idx = -1; 16765 16766 for (;;) { 16767 bool exception_exit = false; 16768 struct bpf_insn *insn; 16769 u8 class; 16770 int err; 16771 16772 env->prev_insn_idx = prev_insn_idx; 16773 if (env->insn_idx >= insn_cnt) { 16774 verbose(env, "invalid insn idx %d insn_cnt %d\n", 16775 env->insn_idx, insn_cnt); 16776 return -EFAULT; 16777 } 16778 16779 insn = &insns[env->insn_idx]; 16780 class = BPF_CLASS(insn->code); 16781 16782 if (++env->insn_processed > BPF_COMPLEXITY_LIMIT_INSNS) { 16783 verbose(env, 16784 "BPF program is too large. Processed %d insn\n", 16785 env->insn_processed); 16786 return -E2BIG; 16787 } 16788 16789 state->last_insn_idx = env->prev_insn_idx; 16790 16791 if (is_prune_point(env, env->insn_idx)) { 16792 err = is_state_visited(env, env->insn_idx); 16793 if (err < 0) 16794 return err; 16795 if (err == 1) { 16796 /* found equivalent state, can prune the search */ 16797 if (env->log.level & BPF_LOG_LEVEL) { 16798 if (do_print_state) 16799 verbose(env, "\nfrom %d to %d%s: safe\n", 16800 env->prev_insn_idx, env->insn_idx, 16801 env->cur_state->speculative ? 16802 " (speculative execution)" : ""); 16803 else 16804 verbose(env, "%d: safe\n", env->insn_idx); 16805 } 16806 goto process_bpf_exit; 16807 } 16808 } 16809 16810 if (is_jmp_point(env, env->insn_idx)) { 16811 err = push_jmp_history(env, state); 16812 if (err) 16813 return err; 16814 } 16815 16816 if (signal_pending(current)) 16817 return -EAGAIN; 16818 16819 if (need_resched()) 16820 cond_resched(); 16821 16822 if (env->log.level & BPF_LOG_LEVEL2 && do_print_state) { 16823 verbose(env, "\nfrom %d to %d%s:", 16824 env->prev_insn_idx, env->insn_idx, 16825 env->cur_state->speculative ? 16826 " (speculative execution)" : ""); 16827 print_verifier_state(env, state->frame[state->curframe], true); 16828 do_print_state = false; 16829 } 16830 16831 if (env->log.level & BPF_LOG_LEVEL) { 16832 const struct bpf_insn_cbs cbs = { 16833 .cb_call = disasm_kfunc_name, 16834 .cb_print = verbose, 16835 .private_data = env, 16836 }; 16837 16838 if (verifier_state_scratched(env)) 16839 print_insn_state(env, state->frame[state->curframe]); 16840 16841 verbose_linfo(env, env->insn_idx, "; "); 16842 env->prev_log_pos = env->log.end_pos; 16843 verbose(env, "%d: ", env->insn_idx); 16844 print_bpf_insn(&cbs, insn, env->allow_ptr_leaks); 16845 env->prev_insn_print_pos = env->log.end_pos - env->prev_log_pos; 16846 env->prev_log_pos = env->log.end_pos; 16847 } 16848 16849 if (bpf_prog_is_offloaded(env->prog->aux)) { 16850 err = bpf_prog_offload_verify_insn(env, env->insn_idx, 16851 env->prev_insn_idx); 16852 if (err) 16853 return err; 16854 } 16855 16856 regs = cur_regs(env); 16857 sanitize_mark_insn_seen(env); 16858 prev_insn_idx = env->insn_idx; 16859 16860 if (class == BPF_ALU || class == BPF_ALU64) { 16861 err = check_alu_op(env, insn); 16862 if (err) 16863 return err; 16864 16865 } else if (class == BPF_LDX) { 16866 enum bpf_reg_type src_reg_type; 16867 16868 /* check for reserved fields is already done */ 16869 16870 /* check src operand */ 16871 err = check_reg_arg(env, insn->src_reg, SRC_OP); 16872 if (err) 16873 return err; 16874 16875 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK); 16876 if (err) 16877 return err; 16878 16879 src_reg_type = regs[insn->src_reg].type; 16880 16881 /* check that memory (src_reg + off) is readable, 16882 * the state of dst_reg will be updated by this func 16883 */ 16884 err = check_mem_access(env, env->insn_idx, insn->src_reg, 16885 insn->off, BPF_SIZE(insn->code), 16886 BPF_READ, insn->dst_reg, false, 16887 BPF_MODE(insn->code) == BPF_MEMSX); 16888 if (err) 16889 return err; 16890 16891 err = save_aux_ptr_type(env, src_reg_type, true); 16892 if (err) 16893 return err; 16894 } else if (class == BPF_STX) { 16895 enum bpf_reg_type dst_reg_type; 16896 16897 if (BPF_MODE(insn->code) == BPF_ATOMIC) { 16898 err = check_atomic(env, env->insn_idx, insn); 16899 if (err) 16900 return err; 16901 env->insn_idx++; 16902 continue; 16903 } 16904 16905 if (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0) { 16906 verbose(env, "BPF_STX uses reserved fields\n"); 16907 return -EINVAL; 16908 } 16909 16910 /* check src1 operand */ 16911 err = check_reg_arg(env, insn->src_reg, SRC_OP); 16912 if (err) 16913 return err; 16914 /* check src2 operand */ 16915 err = check_reg_arg(env, insn->dst_reg, SRC_OP); 16916 if (err) 16917 return err; 16918 16919 dst_reg_type = regs[insn->dst_reg].type; 16920 16921 /* check that memory (dst_reg + off) is writeable */ 16922 err = check_mem_access(env, env->insn_idx, insn->dst_reg, 16923 insn->off, BPF_SIZE(insn->code), 16924 BPF_WRITE, insn->src_reg, false, false); 16925 if (err) 16926 return err; 16927 16928 err = save_aux_ptr_type(env, dst_reg_type, false); 16929 if (err) 16930 return err; 16931 } else if (class == BPF_ST) { 16932 enum bpf_reg_type dst_reg_type; 16933 16934 if (BPF_MODE(insn->code) != BPF_MEM || 16935 insn->src_reg != BPF_REG_0) { 16936 verbose(env, "BPF_ST uses reserved fields\n"); 16937 return -EINVAL; 16938 } 16939 /* check src operand */ 16940 err = check_reg_arg(env, insn->dst_reg, SRC_OP); 16941 if (err) 16942 return err; 16943 16944 dst_reg_type = regs[insn->dst_reg].type; 16945 16946 /* check that memory (dst_reg + off) is writeable */ 16947 err = check_mem_access(env, env->insn_idx, insn->dst_reg, 16948 insn->off, BPF_SIZE(insn->code), 16949 BPF_WRITE, -1, false, false); 16950 if (err) 16951 return err; 16952 16953 err = save_aux_ptr_type(env, dst_reg_type, false); 16954 if (err) 16955 return err; 16956 } else if (class == BPF_JMP || class == BPF_JMP32) { 16957 u8 opcode = BPF_OP(insn->code); 16958 16959 env->jmps_processed++; 16960 if (opcode == BPF_CALL) { 16961 if (BPF_SRC(insn->code) != BPF_K || 16962 (insn->src_reg != BPF_PSEUDO_KFUNC_CALL 16963 && insn->off != 0) || 16964 (insn->src_reg != BPF_REG_0 && 16965 insn->src_reg != BPF_PSEUDO_CALL && 16966 insn->src_reg != BPF_PSEUDO_KFUNC_CALL) || 16967 insn->dst_reg != BPF_REG_0 || 16968 class == BPF_JMP32) { 16969 verbose(env, "BPF_CALL uses reserved fields\n"); 16970 return -EINVAL; 16971 } 16972 16973 if (env->cur_state->active_lock.ptr) { 16974 if ((insn->src_reg == BPF_REG_0 && insn->imm != BPF_FUNC_spin_unlock) || 16975 (insn->src_reg == BPF_PSEUDO_CALL) || 16976 (insn->src_reg == BPF_PSEUDO_KFUNC_CALL && 16977 (insn->off != 0 || !is_bpf_graph_api_kfunc(insn->imm)))) { 16978 verbose(env, "function calls are not allowed while holding a lock\n"); 16979 return -EINVAL; 16980 } 16981 } 16982 if (insn->src_reg == BPF_PSEUDO_CALL) { 16983 err = check_func_call(env, insn, &env->insn_idx); 16984 } else if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) { 16985 err = check_kfunc_call(env, insn, &env->insn_idx); 16986 if (!err && is_bpf_throw_kfunc(insn)) { 16987 exception_exit = true; 16988 goto process_bpf_exit_full; 16989 } 16990 } else { 16991 err = check_helper_call(env, insn, &env->insn_idx); 16992 } 16993 if (err) 16994 return err; 16995 16996 mark_reg_scratched(env, BPF_REG_0); 16997 } else if (opcode == BPF_JA) { 16998 if (BPF_SRC(insn->code) != BPF_K || 16999 insn->src_reg != BPF_REG_0 || 17000 insn->dst_reg != BPF_REG_0 || 17001 (class == BPF_JMP && insn->imm != 0) || 17002 (class == BPF_JMP32 && insn->off != 0)) { 17003 verbose(env, "BPF_JA uses reserved fields\n"); 17004 return -EINVAL; 17005 } 17006 17007 if (class == BPF_JMP) 17008 env->insn_idx += insn->off + 1; 17009 else 17010 env->insn_idx += insn->imm + 1; 17011 continue; 17012 17013 } else if (opcode == BPF_EXIT) { 17014 if (BPF_SRC(insn->code) != BPF_K || 17015 insn->imm != 0 || 17016 insn->src_reg != BPF_REG_0 || 17017 insn->dst_reg != BPF_REG_0 || 17018 class == BPF_JMP32) { 17019 verbose(env, "BPF_EXIT uses reserved fields\n"); 17020 return -EINVAL; 17021 } 17022 process_bpf_exit_full: 17023 if (env->cur_state->active_lock.ptr && 17024 !in_rbtree_lock_required_cb(env)) { 17025 verbose(env, "bpf_spin_unlock is missing\n"); 17026 return -EINVAL; 17027 } 17028 17029 if (env->cur_state->active_rcu_lock && 17030 !in_rbtree_lock_required_cb(env)) { 17031 verbose(env, "bpf_rcu_read_unlock is missing\n"); 17032 return -EINVAL; 17033 } 17034 17035 /* We must do check_reference_leak here before 17036 * prepare_func_exit to handle the case when 17037 * state->curframe > 0, it may be a callback 17038 * function, for which reference_state must 17039 * match caller reference state when it exits. 17040 */ 17041 err = check_reference_leak(env, exception_exit); 17042 if (err) 17043 return err; 17044 17045 /* The side effect of the prepare_func_exit 17046 * which is being skipped is that it frees 17047 * bpf_func_state. Typically, process_bpf_exit 17048 * will only be hit with outermost exit. 17049 * copy_verifier_state in pop_stack will handle 17050 * freeing of any extra bpf_func_state left over 17051 * from not processing all nested function 17052 * exits. We also skip return code checks as 17053 * they are not needed for exceptional exits. 17054 */ 17055 if (exception_exit) 17056 goto process_bpf_exit; 17057 17058 if (state->curframe) { 17059 /* exit from nested function */ 17060 err = prepare_func_exit(env, &env->insn_idx); 17061 if (err) 17062 return err; 17063 do_print_state = true; 17064 continue; 17065 } 17066 17067 err = check_return_code(env, BPF_REG_0); 17068 if (err) 17069 return err; 17070 process_bpf_exit: 17071 mark_verifier_state_scratched(env); 17072 update_branch_counts(env, env->cur_state); 17073 err = pop_stack(env, &prev_insn_idx, 17074 &env->insn_idx, pop_log); 17075 if (err < 0) { 17076 if (err != -ENOENT) 17077 return err; 17078 break; 17079 } else { 17080 do_print_state = true; 17081 continue; 17082 } 17083 } else { 17084 err = check_cond_jmp_op(env, insn, &env->insn_idx); 17085 if (err) 17086 return err; 17087 } 17088 } else if (class == BPF_LD) { 17089 u8 mode = BPF_MODE(insn->code); 17090 17091 if (mode == BPF_ABS || mode == BPF_IND) { 17092 err = check_ld_abs(env, insn); 17093 if (err) 17094 return err; 17095 17096 } else if (mode == BPF_IMM) { 17097 err = check_ld_imm(env, insn); 17098 if (err) 17099 return err; 17100 17101 env->insn_idx++; 17102 sanitize_mark_insn_seen(env); 17103 } else { 17104 verbose(env, "invalid BPF_LD mode\n"); 17105 return -EINVAL; 17106 } 17107 } else { 17108 verbose(env, "unknown insn class %d\n", class); 17109 return -EINVAL; 17110 } 17111 17112 env->insn_idx++; 17113 } 17114 17115 return 0; 17116 } 17117 17118 static int find_btf_percpu_datasec(struct btf *btf) 17119 { 17120 const struct btf_type *t; 17121 const char *tname; 17122 int i, n; 17123 17124 /* 17125 * Both vmlinux and module each have their own ".data..percpu" 17126 * DATASECs in BTF. So for module's case, we need to skip vmlinux BTF 17127 * types to look at only module's own BTF types. 17128 */ 17129 n = btf_nr_types(btf); 17130 if (btf_is_module(btf)) 17131 i = btf_nr_types(btf_vmlinux); 17132 else 17133 i = 1; 17134 17135 for(; i < n; i++) { 17136 t = btf_type_by_id(btf, i); 17137 if (BTF_INFO_KIND(t->info) != BTF_KIND_DATASEC) 17138 continue; 17139 17140 tname = btf_name_by_offset(btf, t->name_off); 17141 if (!strcmp(tname, ".data..percpu")) 17142 return i; 17143 } 17144 17145 return -ENOENT; 17146 } 17147 17148 /* replace pseudo btf_id with kernel symbol address */ 17149 static int check_pseudo_btf_id(struct bpf_verifier_env *env, 17150 struct bpf_insn *insn, 17151 struct bpf_insn_aux_data *aux) 17152 { 17153 const struct btf_var_secinfo *vsi; 17154 const struct btf_type *datasec; 17155 struct btf_mod_pair *btf_mod; 17156 const struct btf_type *t; 17157 const char *sym_name; 17158 bool percpu = false; 17159 u32 type, id = insn->imm; 17160 struct btf *btf; 17161 s32 datasec_id; 17162 u64 addr; 17163 int i, btf_fd, err; 17164 17165 btf_fd = insn[1].imm; 17166 if (btf_fd) { 17167 btf = btf_get_by_fd(btf_fd); 17168 if (IS_ERR(btf)) { 17169 verbose(env, "invalid module BTF object FD specified.\n"); 17170 return -EINVAL; 17171 } 17172 } else { 17173 if (!btf_vmlinux) { 17174 verbose(env, "kernel is missing BTF, make sure CONFIG_DEBUG_INFO_BTF=y is specified in Kconfig.\n"); 17175 return -EINVAL; 17176 } 17177 btf = btf_vmlinux; 17178 btf_get(btf); 17179 } 17180 17181 t = btf_type_by_id(btf, id); 17182 if (!t) { 17183 verbose(env, "ldimm64 insn specifies invalid btf_id %d.\n", id); 17184 err = -ENOENT; 17185 goto err_put; 17186 } 17187 17188 if (!btf_type_is_var(t) && !btf_type_is_func(t)) { 17189 verbose(env, "pseudo btf_id %d in ldimm64 isn't KIND_VAR or KIND_FUNC\n", id); 17190 err = -EINVAL; 17191 goto err_put; 17192 } 17193 17194 sym_name = btf_name_by_offset(btf, t->name_off); 17195 addr = kallsyms_lookup_name(sym_name); 17196 if (!addr) { 17197 verbose(env, "ldimm64 failed to find the address for kernel symbol '%s'.\n", 17198 sym_name); 17199 err = -ENOENT; 17200 goto err_put; 17201 } 17202 insn[0].imm = (u32)addr; 17203 insn[1].imm = addr >> 32; 17204 17205 if (btf_type_is_func(t)) { 17206 aux->btf_var.reg_type = PTR_TO_MEM | MEM_RDONLY; 17207 aux->btf_var.mem_size = 0; 17208 goto check_btf; 17209 } 17210 17211 datasec_id = find_btf_percpu_datasec(btf); 17212 if (datasec_id > 0) { 17213 datasec = btf_type_by_id(btf, datasec_id); 17214 for_each_vsi(i, datasec, vsi) { 17215 if (vsi->type == id) { 17216 percpu = true; 17217 break; 17218 } 17219 } 17220 } 17221 17222 type = t->type; 17223 t = btf_type_skip_modifiers(btf, type, NULL); 17224 if (percpu) { 17225 aux->btf_var.reg_type = PTR_TO_BTF_ID | MEM_PERCPU; 17226 aux->btf_var.btf = btf; 17227 aux->btf_var.btf_id = type; 17228 } else if (!btf_type_is_struct(t)) { 17229 const struct btf_type *ret; 17230 const char *tname; 17231 u32 tsize; 17232 17233 /* resolve the type size of ksym. */ 17234 ret = btf_resolve_size(btf, t, &tsize); 17235 if (IS_ERR(ret)) { 17236 tname = btf_name_by_offset(btf, t->name_off); 17237 verbose(env, "ldimm64 unable to resolve the size of type '%s': %ld\n", 17238 tname, PTR_ERR(ret)); 17239 err = -EINVAL; 17240 goto err_put; 17241 } 17242 aux->btf_var.reg_type = PTR_TO_MEM | MEM_RDONLY; 17243 aux->btf_var.mem_size = tsize; 17244 } else { 17245 aux->btf_var.reg_type = PTR_TO_BTF_ID; 17246 aux->btf_var.btf = btf; 17247 aux->btf_var.btf_id = type; 17248 } 17249 check_btf: 17250 /* check whether we recorded this BTF (and maybe module) already */ 17251 for (i = 0; i < env->used_btf_cnt; i++) { 17252 if (env->used_btfs[i].btf == btf) { 17253 btf_put(btf); 17254 return 0; 17255 } 17256 } 17257 17258 if (env->used_btf_cnt >= MAX_USED_BTFS) { 17259 err = -E2BIG; 17260 goto err_put; 17261 } 17262 17263 btf_mod = &env->used_btfs[env->used_btf_cnt]; 17264 btf_mod->btf = btf; 17265 btf_mod->module = NULL; 17266 17267 /* if we reference variables from kernel module, bump its refcount */ 17268 if (btf_is_module(btf)) { 17269 btf_mod->module = btf_try_get_module(btf); 17270 if (!btf_mod->module) { 17271 err = -ENXIO; 17272 goto err_put; 17273 } 17274 } 17275 17276 env->used_btf_cnt++; 17277 17278 return 0; 17279 err_put: 17280 btf_put(btf); 17281 return err; 17282 } 17283 17284 static bool is_tracing_prog_type(enum bpf_prog_type type) 17285 { 17286 switch (type) { 17287 case BPF_PROG_TYPE_KPROBE: 17288 case BPF_PROG_TYPE_TRACEPOINT: 17289 case BPF_PROG_TYPE_PERF_EVENT: 17290 case BPF_PROG_TYPE_RAW_TRACEPOINT: 17291 case BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE: 17292 return true; 17293 default: 17294 return false; 17295 } 17296 } 17297 17298 static int check_map_prog_compatibility(struct bpf_verifier_env *env, 17299 struct bpf_map *map, 17300 struct bpf_prog *prog) 17301 17302 { 17303 enum bpf_prog_type prog_type = resolve_prog_type(prog); 17304 17305 if (btf_record_has_field(map->record, BPF_LIST_HEAD) || 17306 btf_record_has_field(map->record, BPF_RB_ROOT)) { 17307 if (is_tracing_prog_type(prog_type)) { 17308 verbose(env, "tracing progs cannot use bpf_{list_head,rb_root} yet\n"); 17309 return -EINVAL; 17310 } 17311 } 17312 17313 if (btf_record_has_field(map->record, BPF_SPIN_LOCK)) { 17314 if (prog_type == BPF_PROG_TYPE_SOCKET_FILTER) { 17315 verbose(env, "socket filter progs cannot use bpf_spin_lock yet\n"); 17316 return -EINVAL; 17317 } 17318 17319 if (is_tracing_prog_type(prog_type)) { 17320 verbose(env, "tracing progs cannot use bpf_spin_lock yet\n"); 17321 return -EINVAL; 17322 } 17323 } 17324 17325 if (btf_record_has_field(map->record, BPF_TIMER)) { 17326 if (is_tracing_prog_type(prog_type)) { 17327 verbose(env, "tracing progs cannot use bpf_timer yet\n"); 17328 return -EINVAL; 17329 } 17330 } 17331 17332 if ((bpf_prog_is_offloaded(prog->aux) || bpf_map_is_offloaded(map)) && 17333 !bpf_offload_prog_map_match(prog, map)) { 17334 verbose(env, "offload device mismatch between prog and map\n"); 17335 return -EINVAL; 17336 } 17337 17338 if (map->map_type == BPF_MAP_TYPE_STRUCT_OPS) { 17339 verbose(env, "bpf_struct_ops map cannot be used in prog\n"); 17340 return -EINVAL; 17341 } 17342 17343 if (prog->aux->sleepable) 17344 switch (map->map_type) { 17345 case BPF_MAP_TYPE_HASH: 17346 case BPF_MAP_TYPE_LRU_HASH: 17347 case BPF_MAP_TYPE_ARRAY: 17348 case BPF_MAP_TYPE_PERCPU_HASH: 17349 case BPF_MAP_TYPE_PERCPU_ARRAY: 17350 case BPF_MAP_TYPE_LRU_PERCPU_HASH: 17351 case BPF_MAP_TYPE_ARRAY_OF_MAPS: 17352 case BPF_MAP_TYPE_HASH_OF_MAPS: 17353 case BPF_MAP_TYPE_RINGBUF: 17354 case BPF_MAP_TYPE_USER_RINGBUF: 17355 case BPF_MAP_TYPE_INODE_STORAGE: 17356 case BPF_MAP_TYPE_SK_STORAGE: 17357 case BPF_MAP_TYPE_TASK_STORAGE: 17358 case BPF_MAP_TYPE_CGRP_STORAGE: 17359 break; 17360 default: 17361 verbose(env, 17362 "Sleepable programs can only use array, hash, ringbuf and local storage maps\n"); 17363 return -EINVAL; 17364 } 17365 17366 return 0; 17367 } 17368 17369 static bool bpf_map_is_cgroup_storage(struct bpf_map *map) 17370 { 17371 return (map->map_type == BPF_MAP_TYPE_CGROUP_STORAGE || 17372 map->map_type == BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE); 17373 } 17374 17375 /* find and rewrite pseudo imm in ld_imm64 instructions: 17376 * 17377 * 1. if it accesses map FD, replace it with actual map pointer. 17378 * 2. if it accesses btf_id of a VAR, replace it with pointer to the var. 17379 * 17380 * NOTE: btf_vmlinux is required for converting pseudo btf_id. 17381 */ 17382 static int resolve_pseudo_ldimm64(struct bpf_verifier_env *env) 17383 { 17384 struct bpf_insn *insn = env->prog->insnsi; 17385 int insn_cnt = env->prog->len; 17386 int i, j, err; 17387 17388 err = bpf_prog_calc_tag(env->prog); 17389 if (err) 17390 return err; 17391 17392 for (i = 0; i < insn_cnt; i++, insn++) { 17393 if (BPF_CLASS(insn->code) == BPF_LDX && 17394 ((BPF_MODE(insn->code) != BPF_MEM && BPF_MODE(insn->code) != BPF_MEMSX) || 17395 insn->imm != 0)) { 17396 verbose(env, "BPF_LDX uses reserved fields\n"); 17397 return -EINVAL; 17398 } 17399 17400 if (insn[0].code == (BPF_LD | BPF_IMM | BPF_DW)) { 17401 struct bpf_insn_aux_data *aux; 17402 struct bpf_map *map; 17403 struct fd f; 17404 u64 addr; 17405 u32 fd; 17406 17407 if (i == insn_cnt - 1 || insn[1].code != 0 || 17408 insn[1].dst_reg != 0 || insn[1].src_reg != 0 || 17409 insn[1].off != 0) { 17410 verbose(env, "invalid bpf_ld_imm64 insn\n"); 17411 return -EINVAL; 17412 } 17413 17414 if (insn[0].src_reg == 0) 17415 /* valid generic load 64-bit imm */ 17416 goto next_insn; 17417 17418 if (insn[0].src_reg == BPF_PSEUDO_BTF_ID) { 17419 aux = &env->insn_aux_data[i]; 17420 err = check_pseudo_btf_id(env, insn, aux); 17421 if (err) 17422 return err; 17423 goto next_insn; 17424 } 17425 17426 if (insn[0].src_reg == BPF_PSEUDO_FUNC) { 17427 aux = &env->insn_aux_data[i]; 17428 aux->ptr_type = PTR_TO_FUNC; 17429 goto next_insn; 17430 } 17431 17432 /* In final convert_pseudo_ld_imm64() step, this is 17433 * converted into regular 64-bit imm load insn. 17434 */ 17435 switch (insn[0].src_reg) { 17436 case BPF_PSEUDO_MAP_VALUE: 17437 case BPF_PSEUDO_MAP_IDX_VALUE: 17438 break; 17439 case BPF_PSEUDO_MAP_FD: 17440 case BPF_PSEUDO_MAP_IDX: 17441 if (insn[1].imm == 0) 17442 break; 17443 fallthrough; 17444 default: 17445 verbose(env, "unrecognized bpf_ld_imm64 insn\n"); 17446 return -EINVAL; 17447 } 17448 17449 switch (insn[0].src_reg) { 17450 case BPF_PSEUDO_MAP_IDX_VALUE: 17451 case BPF_PSEUDO_MAP_IDX: 17452 if (bpfptr_is_null(env->fd_array)) { 17453 verbose(env, "fd_idx without fd_array is invalid\n"); 17454 return -EPROTO; 17455 } 17456 if (copy_from_bpfptr_offset(&fd, env->fd_array, 17457 insn[0].imm * sizeof(fd), 17458 sizeof(fd))) 17459 return -EFAULT; 17460 break; 17461 default: 17462 fd = insn[0].imm; 17463 break; 17464 } 17465 17466 f = fdget(fd); 17467 map = __bpf_map_get(f); 17468 if (IS_ERR(map)) { 17469 verbose(env, "fd %d is not pointing to valid bpf_map\n", 17470 insn[0].imm); 17471 return PTR_ERR(map); 17472 } 17473 17474 err = check_map_prog_compatibility(env, map, env->prog); 17475 if (err) { 17476 fdput(f); 17477 return err; 17478 } 17479 17480 aux = &env->insn_aux_data[i]; 17481 if (insn[0].src_reg == BPF_PSEUDO_MAP_FD || 17482 insn[0].src_reg == BPF_PSEUDO_MAP_IDX) { 17483 addr = (unsigned long)map; 17484 } else { 17485 u32 off = insn[1].imm; 17486 17487 if (off >= BPF_MAX_VAR_OFF) { 17488 verbose(env, "direct value offset of %u is not allowed\n", off); 17489 fdput(f); 17490 return -EINVAL; 17491 } 17492 17493 if (!map->ops->map_direct_value_addr) { 17494 verbose(env, "no direct value access support for this map type\n"); 17495 fdput(f); 17496 return -EINVAL; 17497 } 17498 17499 err = map->ops->map_direct_value_addr(map, &addr, off); 17500 if (err) { 17501 verbose(env, "invalid access to map value pointer, value_size=%u off=%u\n", 17502 map->value_size, off); 17503 fdput(f); 17504 return err; 17505 } 17506 17507 aux->map_off = off; 17508 addr += off; 17509 } 17510 17511 insn[0].imm = (u32)addr; 17512 insn[1].imm = addr >> 32; 17513 17514 /* check whether we recorded this map already */ 17515 for (j = 0; j < env->used_map_cnt; j++) { 17516 if (env->used_maps[j] == map) { 17517 aux->map_index = j; 17518 fdput(f); 17519 goto next_insn; 17520 } 17521 } 17522 17523 if (env->used_map_cnt >= MAX_USED_MAPS) { 17524 fdput(f); 17525 return -E2BIG; 17526 } 17527 17528 /* hold the map. If the program is rejected by verifier, 17529 * the map will be released by release_maps() or it 17530 * will be used by the valid program until it's unloaded 17531 * and all maps are released in free_used_maps() 17532 */ 17533 bpf_map_inc(map); 17534 17535 aux->map_index = env->used_map_cnt; 17536 env->used_maps[env->used_map_cnt++] = map; 17537 17538 if (bpf_map_is_cgroup_storage(map) && 17539 bpf_cgroup_storage_assign(env->prog->aux, map)) { 17540 verbose(env, "only one cgroup storage of each type is allowed\n"); 17541 fdput(f); 17542 return -EBUSY; 17543 } 17544 17545 fdput(f); 17546 next_insn: 17547 insn++; 17548 i++; 17549 continue; 17550 } 17551 17552 /* Basic sanity check before we invest more work here. */ 17553 if (!bpf_opcode_in_insntable(insn->code)) { 17554 verbose(env, "unknown opcode %02x\n", insn->code); 17555 return -EINVAL; 17556 } 17557 } 17558 17559 /* now all pseudo BPF_LD_IMM64 instructions load valid 17560 * 'struct bpf_map *' into a register instead of user map_fd. 17561 * These pointers will be used later by verifier to validate map access. 17562 */ 17563 return 0; 17564 } 17565 17566 /* drop refcnt of maps used by the rejected program */ 17567 static void release_maps(struct bpf_verifier_env *env) 17568 { 17569 __bpf_free_used_maps(env->prog->aux, env->used_maps, 17570 env->used_map_cnt); 17571 } 17572 17573 /* drop refcnt of maps used by the rejected program */ 17574 static void release_btfs(struct bpf_verifier_env *env) 17575 { 17576 __bpf_free_used_btfs(env->prog->aux, env->used_btfs, 17577 env->used_btf_cnt); 17578 } 17579 17580 /* convert pseudo BPF_LD_IMM64 into generic BPF_LD_IMM64 */ 17581 static void convert_pseudo_ld_imm64(struct bpf_verifier_env *env) 17582 { 17583 struct bpf_insn *insn = env->prog->insnsi; 17584 int insn_cnt = env->prog->len; 17585 int i; 17586 17587 for (i = 0; i < insn_cnt; i++, insn++) { 17588 if (insn->code != (BPF_LD | BPF_IMM | BPF_DW)) 17589 continue; 17590 if (insn->src_reg == BPF_PSEUDO_FUNC) 17591 continue; 17592 insn->src_reg = 0; 17593 } 17594 } 17595 17596 /* single env->prog->insni[off] instruction was replaced with the range 17597 * insni[off, off + cnt). Adjust corresponding insn_aux_data by copying 17598 * [0, off) and [off, end) to new locations, so the patched range stays zero 17599 */ 17600 static void adjust_insn_aux_data(struct bpf_verifier_env *env, 17601 struct bpf_insn_aux_data *new_data, 17602 struct bpf_prog *new_prog, u32 off, u32 cnt) 17603 { 17604 struct bpf_insn_aux_data *old_data = env->insn_aux_data; 17605 struct bpf_insn *insn = new_prog->insnsi; 17606 u32 old_seen = old_data[off].seen; 17607 u32 prog_len; 17608 int i; 17609 17610 /* aux info at OFF always needs adjustment, no matter fast path 17611 * (cnt == 1) is taken or not. There is no guarantee INSN at OFF is the 17612 * original insn at old prog. 17613 */ 17614 old_data[off].zext_dst = insn_has_def32(env, insn + off + cnt - 1); 17615 17616 if (cnt == 1) 17617 return; 17618 prog_len = new_prog->len; 17619 17620 memcpy(new_data, old_data, sizeof(struct bpf_insn_aux_data) * off); 17621 memcpy(new_data + off + cnt - 1, old_data + off, 17622 sizeof(struct bpf_insn_aux_data) * (prog_len - off - cnt + 1)); 17623 for (i = off; i < off + cnt - 1; i++) { 17624 /* Expand insni[off]'s seen count to the patched range. */ 17625 new_data[i].seen = old_seen; 17626 new_data[i].zext_dst = insn_has_def32(env, insn + i); 17627 } 17628 env->insn_aux_data = new_data; 17629 vfree(old_data); 17630 } 17631 17632 static void adjust_subprog_starts(struct bpf_verifier_env *env, u32 off, u32 len) 17633 { 17634 int i; 17635 17636 if (len == 1) 17637 return; 17638 /* NOTE: fake 'exit' subprog should be updated as well. */ 17639 for (i = 0; i <= env->subprog_cnt; i++) { 17640 if (env->subprog_info[i].start <= off) 17641 continue; 17642 env->subprog_info[i].start += len - 1; 17643 } 17644 } 17645 17646 static void adjust_poke_descs(struct bpf_prog *prog, u32 off, u32 len) 17647 { 17648 struct bpf_jit_poke_descriptor *tab = prog->aux->poke_tab; 17649 int i, sz = prog->aux->size_poke_tab; 17650 struct bpf_jit_poke_descriptor *desc; 17651 17652 for (i = 0; i < sz; i++) { 17653 desc = &tab[i]; 17654 if (desc->insn_idx <= off) 17655 continue; 17656 desc->insn_idx += len - 1; 17657 } 17658 } 17659 17660 static struct bpf_prog *bpf_patch_insn_data(struct bpf_verifier_env *env, u32 off, 17661 const struct bpf_insn *patch, u32 len) 17662 { 17663 struct bpf_prog *new_prog; 17664 struct bpf_insn_aux_data *new_data = NULL; 17665 17666 if (len > 1) { 17667 new_data = vzalloc(array_size(env->prog->len + len - 1, 17668 sizeof(struct bpf_insn_aux_data))); 17669 if (!new_data) 17670 return NULL; 17671 } 17672 17673 new_prog = bpf_patch_insn_single(env->prog, off, patch, len); 17674 if (IS_ERR(new_prog)) { 17675 if (PTR_ERR(new_prog) == -ERANGE) 17676 verbose(env, 17677 "insn %d cannot be patched due to 16-bit range\n", 17678 env->insn_aux_data[off].orig_idx); 17679 vfree(new_data); 17680 return NULL; 17681 } 17682 adjust_insn_aux_data(env, new_data, new_prog, off, len); 17683 adjust_subprog_starts(env, off, len); 17684 adjust_poke_descs(new_prog, off, len); 17685 return new_prog; 17686 } 17687 17688 static int adjust_subprog_starts_after_remove(struct bpf_verifier_env *env, 17689 u32 off, u32 cnt) 17690 { 17691 int i, j; 17692 17693 /* find first prog starting at or after off (first to remove) */ 17694 for (i = 0; i < env->subprog_cnt; i++) 17695 if (env->subprog_info[i].start >= off) 17696 break; 17697 /* find first prog starting at or after off + cnt (first to stay) */ 17698 for (j = i; j < env->subprog_cnt; j++) 17699 if (env->subprog_info[j].start >= off + cnt) 17700 break; 17701 /* if j doesn't start exactly at off + cnt, we are just removing 17702 * the front of previous prog 17703 */ 17704 if (env->subprog_info[j].start != off + cnt) 17705 j--; 17706 17707 if (j > i) { 17708 struct bpf_prog_aux *aux = env->prog->aux; 17709 int move; 17710 17711 /* move fake 'exit' subprog as well */ 17712 move = env->subprog_cnt + 1 - j; 17713 17714 memmove(env->subprog_info + i, 17715 env->subprog_info + j, 17716 sizeof(*env->subprog_info) * move); 17717 env->subprog_cnt -= j - i; 17718 17719 /* remove func_info */ 17720 if (aux->func_info) { 17721 move = aux->func_info_cnt - j; 17722 17723 memmove(aux->func_info + i, 17724 aux->func_info + j, 17725 sizeof(*aux->func_info) * move); 17726 aux->func_info_cnt -= j - i; 17727 /* func_info->insn_off is set after all code rewrites, 17728 * in adjust_btf_func() - no need to adjust 17729 */ 17730 } 17731 } else { 17732 /* convert i from "first prog to remove" to "first to adjust" */ 17733 if (env->subprog_info[i].start == off) 17734 i++; 17735 } 17736 17737 /* update fake 'exit' subprog as well */ 17738 for (; i <= env->subprog_cnt; i++) 17739 env->subprog_info[i].start -= cnt; 17740 17741 return 0; 17742 } 17743 17744 static int bpf_adj_linfo_after_remove(struct bpf_verifier_env *env, u32 off, 17745 u32 cnt) 17746 { 17747 struct bpf_prog *prog = env->prog; 17748 u32 i, l_off, l_cnt, nr_linfo; 17749 struct bpf_line_info *linfo; 17750 17751 nr_linfo = prog->aux->nr_linfo; 17752 if (!nr_linfo) 17753 return 0; 17754 17755 linfo = prog->aux->linfo; 17756 17757 /* find first line info to remove, count lines to be removed */ 17758 for (i = 0; i < nr_linfo; i++) 17759 if (linfo[i].insn_off >= off) 17760 break; 17761 17762 l_off = i; 17763 l_cnt = 0; 17764 for (; i < nr_linfo; i++) 17765 if (linfo[i].insn_off < off + cnt) 17766 l_cnt++; 17767 else 17768 break; 17769 17770 /* First live insn doesn't match first live linfo, it needs to "inherit" 17771 * last removed linfo. prog is already modified, so prog->len == off 17772 * means no live instructions after (tail of the program was removed). 17773 */ 17774 if (prog->len != off && l_cnt && 17775 (i == nr_linfo || linfo[i].insn_off != off + cnt)) { 17776 l_cnt--; 17777 linfo[--i].insn_off = off + cnt; 17778 } 17779 17780 /* remove the line info which refer to the removed instructions */ 17781 if (l_cnt) { 17782 memmove(linfo + l_off, linfo + i, 17783 sizeof(*linfo) * (nr_linfo - i)); 17784 17785 prog->aux->nr_linfo -= l_cnt; 17786 nr_linfo = prog->aux->nr_linfo; 17787 } 17788 17789 /* pull all linfo[i].insn_off >= off + cnt in by cnt */ 17790 for (i = l_off; i < nr_linfo; i++) 17791 linfo[i].insn_off -= cnt; 17792 17793 /* fix up all subprogs (incl. 'exit') which start >= off */ 17794 for (i = 0; i <= env->subprog_cnt; i++) 17795 if (env->subprog_info[i].linfo_idx > l_off) { 17796 /* program may have started in the removed region but 17797 * may not be fully removed 17798 */ 17799 if (env->subprog_info[i].linfo_idx >= l_off + l_cnt) 17800 env->subprog_info[i].linfo_idx -= l_cnt; 17801 else 17802 env->subprog_info[i].linfo_idx = l_off; 17803 } 17804 17805 return 0; 17806 } 17807 17808 static int verifier_remove_insns(struct bpf_verifier_env *env, u32 off, u32 cnt) 17809 { 17810 struct bpf_insn_aux_data *aux_data = env->insn_aux_data; 17811 unsigned int orig_prog_len = env->prog->len; 17812 int err; 17813 17814 if (bpf_prog_is_offloaded(env->prog->aux)) 17815 bpf_prog_offload_remove_insns(env, off, cnt); 17816 17817 err = bpf_remove_insns(env->prog, off, cnt); 17818 if (err) 17819 return err; 17820 17821 err = adjust_subprog_starts_after_remove(env, off, cnt); 17822 if (err) 17823 return err; 17824 17825 err = bpf_adj_linfo_after_remove(env, off, cnt); 17826 if (err) 17827 return err; 17828 17829 memmove(aux_data + off, aux_data + off + cnt, 17830 sizeof(*aux_data) * (orig_prog_len - off - cnt)); 17831 17832 return 0; 17833 } 17834 17835 /* The verifier does more data flow analysis than llvm and will not 17836 * explore branches that are dead at run time. Malicious programs can 17837 * have dead code too. Therefore replace all dead at-run-time code 17838 * with 'ja -1'. 17839 * 17840 * Just nops are not optimal, e.g. if they would sit at the end of the 17841 * program and through another bug we would manage to jump there, then 17842 * we'd execute beyond program memory otherwise. Returning exception 17843 * code also wouldn't work since we can have subprogs where the dead 17844 * code could be located. 17845 */ 17846 static void sanitize_dead_code(struct bpf_verifier_env *env) 17847 { 17848 struct bpf_insn_aux_data *aux_data = env->insn_aux_data; 17849 struct bpf_insn trap = BPF_JMP_IMM(BPF_JA, 0, 0, -1); 17850 struct bpf_insn *insn = env->prog->insnsi; 17851 const int insn_cnt = env->prog->len; 17852 int i; 17853 17854 for (i = 0; i < insn_cnt; i++) { 17855 if (aux_data[i].seen) 17856 continue; 17857 memcpy(insn + i, &trap, sizeof(trap)); 17858 aux_data[i].zext_dst = false; 17859 } 17860 } 17861 17862 static bool insn_is_cond_jump(u8 code) 17863 { 17864 u8 op; 17865 17866 op = BPF_OP(code); 17867 if (BPF_CLASS(code) == BPF_JMP32) 17868 return op != BPF_JA; 17869 17870 if (BPF_CLASS(code) != BPF_JMP) 17871 return false; 17872 17873 return op != BPF_JA && op != BPF_EXIT && op != BPF_CALL; 17874 } 17875 17876 static void opt_hard_wire_dead_code_branches(struct bpf_verifier_env *env) 17877 { 17878 struct bpf_insn_aux_data *aux_data = env->insn_aux_data; 17879 struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0); 17880 struct bpf_insn *insn = env->prog->insnsi; 17881 const int insn_cnt = env->prog->len; 17882 int i; 17883 17884 for (i = 0; i < insn_cnt; i++, insn++) { 17885 if (!insn_is_cond_jump(insn->code)) 17886 continue; 17887 17888 if (!aux_data[i + 1].seen) 17889 ja.off = insn->off; 17890 else if (!aux_data[i + 1 + insn->off].seen) 17891 ja.off = 0; 17892 else 17893 continue; 17894 17895 if (bpf_prog_is_offloaded(env->prog->aux)) 17896 bpf_prog_offload_replace_insn(env, i, &ja); 17897 17898 memcpy(insn, &ja, sizeof(ja)); 17899 } 17900 } 17901 17902 static int opt_remove_dead_code(struct bpf_verifier_env *env) 17903 { 17904 struct bpf_insn_aux_data *aux_data = env->insn_aux_data; 17905 int insn_cnt = env->prog->len; 17906 int i, err; 17907 17908 for (i = 0; i < insn_cnt; i++) { 17909 int j; 17910 17911 j = 0; 17912 while (i + j < insn_cnt && !aux_data[i + j].seen) 17913 j++; 17914 if (!j) 17915 continue; 17916 17917 err = verifier_remove_insns(env, i, j); 17918 if (err) 17919 return err; 17920 insn_cnt = env->prog->len; 17921 } 17922 17923 return 0; 17924 } 17925 17926 static int opt_remove_nops(struct bpf_verifier_env *env) 17927 { 17928 const struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0); 17929 struct bpf_insn *insn = env->prog->insnsi; 17930 int insn_cnt = env->prog->len; 17931 int i, err; 17932 17933 for (i = 0; i < insn_cnt; i++) { 17934 if (memcmp(&insn[i], &ja, sizeof(ja))) 17935 continue; 17936 17937 err = verifier_remove_insns(env, i, 1); 17938 if (err) 17939 return err; 17940 insn_cnt--; 17941 i--; 17942 } 17943 17944 return 0; 17945 } 17946 17947 static int opt_subreg_zext_lo32_rnd_hi32(struct bpf_verifier_env *env, 17948 const union bpf_attr *attr) 17949 { 17950 struct bpf_insn *patch, zext_patch[2], rnd_hi32_patch[4]; 17951 struct bpf_insn_aux_data *aux = env->insn_aux_data; 17952 int i, patch_len, delta = 0, len = env->prog->len; 17953 struct bpf_insn *insns = env->prog->insnsi; 17954 struct bpf_prog *new_prog; 17955 bool rnd_hi32; 17956 17957 rnd_hi32 = attr->prog_flags & BPF_F_TEST_RND_HI32; 17958 zext_patch[1] = BPF_ZEXT_REG(0); 17959 rnd_hi32_patch[1] = BPF_ALU64_IMM(BPF_MOV, BPF_REG_AX, 0); 17960 rnd_hi32_patch[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_AX, 32); 17961 rnd_hi32_patch[3] = BPF_ALU64_REG(BPF_OR, 0, BPF_REG_AX); 17962 for (i = 0; i < len; i++) { 17963 int adj_idx = i + delta; 17964 struct bpf_insn insn; 17965 int load_reg; 17966 17967 insn = insns[adj_idx]; 17968 load_reg = insn_def_regno(&insn); 17969 if (!aux[adj_idx].zext_dst) { 17970 u8 code, class; 17971 u32 imm_rnd; 17972 17973 if (!rnd_hi32) 17974 continue; 17975 17976 code = insn.code; 17977 class = BPF_CLASS(code); 17978 if (load_reg == -1) 17979 continue; 17980 17981 /* NOTE: arg "reg" (the fourth one) is only used for 17982 * BPF_STX + SRC_OP, so it is safe to pass NULL 17983 * here. 17984 */ 17985 if (is_reg64(env, &insn, load_reg, NULL, DST_OP)) { 17986 if (class == BPF_LD && 17987 BPF_MODE(code) == BPF_IMM) 17988 i++; 17989 continue; 17990 } 17991 17992 /* ctx load could be transformed into wider load. */ 17993 if (class == BPF_LDX && 17994 aux[adj_idx].ptr_type == PTR_TO_CTX) 17995 continue; 17996 17997 imm_rnd = get_random_u32(); 17998 rnd_hi32_patch[0] = insn; 17999 rnd_hi32_patch[1].imm = imm_rnd; 18000 rnd_hi32_patch[3].dst_reg = load_reg; 18001 patch = rnd_hi32_patch; 18002 patch_len = 4; 18003 goto apply_patch_buffer; 18004 } 18005 18006 /* Add in an zero-extend instruction if a) the JIT has requested 18007 * it or b) it's a CMPXCHG. 18008 * 18009 * The latter is because: BPF_CMPXCHG always loads a value into 18010 * R0, therefore always zero-extends. However some archs' 18011 * equivalent instruction only does this load when the 18012 * comparison is successful. This detail of CMPXCHG is 18013 * orthogonal to the general zero-extension behaviour of the 18014 * CPU, so it's treated independently of bpf_jit_needs_zext. 18015 */ 18016 if (!bpf_jit_needs_zext() && !is_cmpxchg_insn(&insn)) 18017 continue; 18018 18019 /* Zero-extension is done by the caller. */ 18020 if (bpf_pseudo_kfunc_call(&insn)) 18021 continue; 18022 18023 if (WARN_ON(load_reg == -1)) { 18024 verbose(env, "verifier bug. zext_dst is set, but no reg is defined\n"); 18025 return -EFAULT; 18026 } 18027 18028 zext_patch[0] = insn; 18029 zext_patch[1].dst_reg = load_reg; 18030 zext_patch[1].src_reg = load_reg; 18031 patch = zext_patch; 18032 patch_len = 2; 18033 apply_patch_buffer: 18034 new_prog = bpf_patch_insn_data(env, adj_idx, patch, patch_len); 18035 if (!new_prog) 18036 return -ENOMEM; 18037 env->prog = new_prog; 18038 insns = new_prog->insnsi; 18039 aux = env->insn_aux_data; 18040 delta += patch_len - 1; 18041 } 18042 18043 return 0; 18044 } 18045 18046 /* convert load instructions that access fields of a context type into a 18047 * sequence of instructions that access fields of the underlying structure: 18048 * struct __sk_buff -> struct sk_buff 18049 * struct bpf_sock_ops -> struct sock 18050 */ 18051 static int convert_ctx_accesses(struct bpf_verifier_env *env) 18052 { 18053 const struct bpf_verifier_ops *ops = env->ops; 18054 int i, cnt, size, ctx_field_size, delta = 0; 18055 const int insn_cnt = env->prog->len; 18056 struct bpf_insn insn_buf[16], *insn; 18057 u32 target_size, size_default, off; 18058 struct bpf_prog *new_prog; 18059 enum bpf_access_type type; 18060 bool is_narrower_load; 18061 18062 if (ops->gen_prologue || env->seen_direct_write) { 18063 if (!ops->gen_prologue) { 18064 verbose(env, "bpf verifier is misconfigured\n"); 18065 return -EINVAL; 18066 } 18067 cnt = ops->gen_prologue(insn_buf, env->seen_direct_write, 18068 env->prog); 18069 if (cnt >= ARRAY_SIZE(insn_buf)) { 18070 verbose(env, "bpf verifier is misconfigured\n"); 18071 return -EINVAL; 18072 } else if (cnt) { 18073 new_prog = bpf_patch_insn_data(env, 0, insn_buf, cnt); 18074 if (!new_prog) 18075 return -ENOMEM; 18076 18077 env->prog = new_prog; 18078 delta += cnt - 1; 18079 } 18080 } 18081 18082 if (bpf_prog_is_offloaded(env->prog->aux)) 18083 return 0; 18084 18085 insn = env->prog->insnsi + delta; 18086 18087 for (i = 0; i < insn_cnt; i++, insn++) { 18088 bpf_convert_ctx_access_t convert_ctx_access; 18089 u8 mode; 18090 18091 if (insn->code == (BPF_LDX | BPF_MEM | BPF_B) || 18092 insn->code == (BPF_LDX | BPF_MEM | BPF_H) || 18093 insn->code == (BPF_LDX | BPF_MEM | BPF_W) || 18094 insn->code == (BPF_LDX | BPF_MEM | BPF_DW) || 18095 insn->code == (BPF_LDX | BPF_MEMSX | BPF_B) || 18096 insn->code == (BPF_LDX | BPF_MEMSX | BPF_H) || 18097 insn->code == (BPF_LDX | BPF_MEMSX | BPF_W)) { 18098 type = BPF_READ; 18099 } else if (insn->code == (BPF_STX | BPF_MEM | BPF_B) || 18100 insn->code == (BPF_STX | BPF_MEM | BPF_H) || 18101 insn->code == (BPF_STX | BPF_MEM | BPF_W) || 18102 insn->code == (BPF_STX | BPF_MEM | BPF_DW) || 18103 insn->code == (BPF_ST | BPF_MEM | BPF_B) || 18104 insn->code == (BPF_ST | BPF_MEM | BPF_H) || 18105 insn->code == (BPF_ST | BPF_MEM | BPF_W) || 18106 insn->code == (BPF_ST | BPF_MEM | BPF_DW)) { 18107 type = BPF_WRITE; 18108 } else { 18109 continue; 18110 } 18111 18112 if (type == BPF_WRITE && 18113 env->insn_aux_data[i + delta].sanitize_stack_spill) { 18114 struct bpf_insn patch[] = { 18115 *insn, 18116 BPF_ST_NOSPEC(), 18117 }; 18118 18119 cnt = ARRAY_SIZE(patch); 18120 new_prog = bpf_patch_insn_data(env, i + delta, patch, cnt); 18121 if (!new_prog) 18122 return -ENOMEM; 18123 18124 delta += cnt - 1; 18125 env->prog = new_prog; 18126 insn = new_prog->insnsi + i + delta; 18127 continue; 18128 } 18129 18130 switch ((int)env->insn_aux_data[i + delta].ptr_type) { 18131 case PTR_TO_CTX: 18132 if (!ops->convert_ctx_access) 18133 continue; 18134 convert_ctx_access = ops->convert_ctx_access; 18135 break; 18136 case PTR_TO_SOCKET: 18137 case PTR_TO_SOCK_COMMON: 18138 convert_ctx_access = bpf_sock_convert_ctx_access; 18139 break; 18140 case PTR_TO_TCP_SOCK: 18141 convert_ctx_access = bpf_tcp_sock_convert_ctx_access; 18142 break; 18143 case PTR_TO_XDP_SOCK: 18144 convert_ctx_access = bpf_xdp_sock_convert_ctx_access; 18145 break; 18146 case PTR_TO_BTF_ID: 18147 case PTR_TO_BTF_ID | PTR_UNTRUSTED: 18148 /* PTR_TO_BTF_ID | MEM_ALLOC always has a valid lifetime, unlike 18149 * PTR_TO_BTF_ID, and an active ref_obj_id, but the same cannot 18150 * be said once it is marked PTR_UNTRUSTED, hence we must handle 18151 * any faults for loads into such types. BPF_WRITE is disallowed 18152 * for this case. 18153 */ 18154 case PTR_TO_BTF_ID | MEM_ALLOC | PTR_UNTRUSTED: 18155 if (type == BPF_READ) { 18156 if (BPF_MODE(insn->code) == BPF_MEM) 18157 insn->code = BPF_LDX | BPF_PROBE_MEM | 18158 BPF_SIZE((insn)->code); 18159 else 18160 insn->code = BPF_LDX | BPF_PROBE_MEMSX | 18161 BPF_SIZE((insn)->code); 18162 env->prog->aux->num_exentries++; 18163 } 18164 continue; 18165 default: 18166 continue; 18167 } 18168 18169 ctx_field_size = env->insn_aux_data[i + delta].ctx_field_size; 18170 size = BPF_LDST_BYTES(insn); 18171 mode = BPF_MODE(insn->code); 18172 18173 /* If the read access is a narrower load of the field, 18174 * convert to a 4/8-byte load, to minimum program type specific 18175 * convert_ctx_access changes. If conversion is successful, 18176 * we will apply proper mask to the result. 18177 */ 18178 is_narrower_load = size < ctx_field_size; 18179 size_default = bpf_ctx_off_adjust_machine(ctx_field_size); 18180 off = insn->off; 18181 if (is_narrower_load) { 18182 u8 size_code; 18183 18184 if (type == BPF_WRITE) { 18185 verbose(env, "bpf verifier narrow ctx access misconfigured\n"); 18186 return -EINVAL; 18187 } 18188 18189 size_code = BPF_H; 18190 if (ctx_field_size == 4) 18191 size_code = BPF_W; 18192 else if (ctx_field_size == 8) 18193 size_code = BPF_DW; 18194 18195 insn->off = off & ~(size_default - 1); 18196 insn->code = BPF_LDX | BPF_MEM | size_code; 18197 } 18198 18199 target_size = 0; 18200 cnt = convert_ctx_access(type, insn, insn_buf, env->prog, 18201 &target_size); 18202 if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf) || 18203 (ctx_field_size && !target_size)) { 18204 verbose(env, "bpf verifier is misconfigured\n"); 18205 return -EINVAL; 18206 } 18207 18208 if (is_narrower_load && size < target_size) { 18209 u8 shift = bpf_ctx_narrow_access_offset( 18210 off, size, size_default) * 8; 18211 if (shift && cnt + 1 >= ARRAY_SIZE(insn_buf)) { 18212 verbose(env, "bpf verifier narrow ctx load misconfigured\n"); 18213 return -EINVAL; 18214 } 18215 if (ctx_field_size <= 4) { 18216 if (shift) 18217 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_RSH, 18218 insn->dst_reg, 18219 shift); 18220 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg, 18221 (1 << size * 8) - 1); 18222 } else { 18223 if (shift) 18224 insn_buf[cnt++] = BPF_ALU64_IMM(BPF_RSH, 18225 insn->dst_reg, 18226 shift); 18227 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg, 18228 (1ULL << size * 8) - 1); 18229 } 18230 } 18231 if (mode == BPF_MEMSX) 18232 insn_buf[cnt++] = BPF_RAW_INSN(BPF_ALU64 | BPF_MOV | BPF_X, 18233 insn->dst_reg, insn->dst_reg, 18234 size * 8, 0); 18235 18236 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 18237 if (!new_prog) 18238 return -ENOMEM; 18239 18240 delta += cnt - 1; 18241 18242 /* keep walking new program and skip insns we just inserted */ 18243 env->prog = new_prog; 18244 insn = new_prog->insnsi + i + delta; 18245 } 18246 18247 return 0; 18248 } 18249 18250 static int jit_subprogs(struct bpf_verifier_env *env) 18251 { 18252 struct bpf_prog *prog = env->prog, **func, *tmp; 18253 int i, j, subprog_start, subprog_end = 0, len, subprog; 18254 struct bpf_map *map_ptr; 18255 struct bpf_insn *insn; 18256 void *old_bpf_func; 18257 int err, num_exentries; 18258 18259 if (env->subprog_cnt <= 1) 18260 return 0; 18261 18262 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) { 18263 if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn)) 18264 continue; 18265 18266 /* Upon error here we cannot fall back to interpreter but 18267 * need a hard reject of the program. Thus -EFAULT is 18268 * propagated in any case. 18269 */ 18270 subprog = find_subprog(env, i + insn->imm + 1); 18271 if (subprog < 0) { 18272 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n", 18273 i + insn->imm + 1); 18274 return -EFAULT; 18275 } 18276 /* temporarily remember subprog id inside insn instead of 18277 * aux_data, since next loop will split up all insns into funcs 18278 */ 18279 insn->off = subprog; 18280 /* remember original imm in case JIT fails and fallback 18281 * to interpreter will be needed 18282 */ 18283 env->insn_aux_data[i].call_imm = insn->imm; 18284 /* point imm to __bpf_call_base+1 from JITs point of view */ 18285 insn->imm = 1; 18286 if (bpf_pseudo_func(insn)) 18287 /* jit (e.g. x86_64) may emit fewer instructions 18288 * if it learns a u32 imm is the same as a u64 imm. 18289 * Force a non zero here. 18290 */ 18291 insn[1].imm = 1; 18292 } 18293 18294 err = bpf_prog_alloc_jited_linfo(prog); 18295 if (err) 18296 goto out_undo_insn; 18297 18298 err = -ENOMEM; 18299 func = kcalloc(env->subprog_cnt, sizeof(prog), GFP_KERNEL); 18300 if (!func) 18301 goto out_undo_insn; 18302 18303 for (i = 0; i < env->subprog_cnt; i++) { 18304 subprog_start = subprog_end; 18305 subprog_end = env->subprog_info[i + 1].start; 18306 18307 len = subprog_end - subprog_start; 18308 /* bpf_prog_run() doesn't call subprogs directly, 18309 * hence main prog stats include the runtime of subprogs. 18310 * subprogs don't have IDs and not reachable via prog_get_next_id 18311 * func[i]->stats will never be accessed and stays NULL 18312 */ 18313 func[i] = bpf_prog_alloc_no_stats(bpf_prog_size(len), GFP_USER); 18314 if (!func[i]) 18315 goto out_free; 18316 memcpy(func[i]->insnsi, &prog->insnsi[subprog_start], 18317 len * sizeof(struct bpf_insn)); 18318 func[i]->type = prog->type; 18319 func[i]->len = len; 18320 if (bpf_prog_calc_tag(func[i])) 18321 goto out_free; 18322 func[i]->is_func = 1; 18323 func[i]->aux->func_idx = i; 18324 /* Below members will be freed only at prog->aux */ 18325 func[i]->aux->btf = prog->aux->btf; 18326 func[i]->aux->func_info = prog->aux->func_info; 18327 func[i]->aux->func_info_cnt = prog->aux->func_info_cnt; 18328 func[i]->aux->poke_tab = prog->aux->poke_tab; 18329 func[i]->aux->size_poke_tab = prog->aux->size_poke_tab; 18330 18331 for (j = 0; j < prog->aux->size_poke_tab; j++) { 18332 struct bpf_jit_poke_descriptor *poke; 18333 18334 poke = &prog->aux->poke_tab[j]; 18335 if (poke->insn_idx < subprog_end && 18336 poke->insn_idx >= subprog_start) 18337 poke->aux = func[i]->aux; 18338 } 18339 18340 func[i]->aux->name[0] = 'F'; 18341 func[i]->aux->stack_depth = env->subprog_info[i].stack_depth; 18342 func[i]->jit_requested = 1; 18343 func[i]->blinding_requested = prog->blinding_requested; 18344 func[i]->aux->kfunc_tab = prog->aux->kfunc_tab; 18345 func[i]->aux->kfunc_btf_tab = prog->aux->kfunc_btf_tab; 18346 func[i]->aux->linfo = prog->aux->linfo; 18347 func[i]->aux->nr_linfo = prog->aux->nr_linfo; 18348 func[i]->aux->jited_linfo = prog->aux->jited_linfo; 18349 func[i]->aux->linfo_idx = env->subprog_info[i].linfo_idx; 18350 num_exentries = 0; 18351 insn = func[i]->insnsi; 18352 for (j = 0; j < func[i]->len; j++, insn++) { 18353 if (BPF_CLASS(insn->code) == BPF_LDX && 18354 (BPF_MODE(insn->code) == BPF_PROBE_MEM || 18355 BPF_MODE(insn->code) == BPF_PROBE_MEMSX)) 18356 num_exentries++; 18357 } 18358 func[i]->aux->num_exentries = num_exentries; 18359 func[i]->aux->tail_call_reachable = env->subprog_info[i].tail_call_reachable; 18360 func[i]->aux->exception_cb = env->subprog_info[i].is_exception_cb; 18361 if (!i) 18362 func[i]->aux->exception_boundary = env->seen_exception; 18363 func[i] = bpf_int_jit_compile(func[i]); 18364 if (!func[i]->jited) { 18365 err = -ENOTSUPP; 18366 goto out_free; 18367 } 18368 cond_resched(); 18369 } 18370 18371 /* at this point all bpf functions were successfully JITed 18372 * now populate all bpf_calls with correct addresses and 18373 * run last pass of JIT 18374 */ 18375 for (i = 0; i < env->subprog_cnt; i++) { 18376 insn = func[i]->insnsi; 18377 for (j = 0; j < func[i]->len; j++, insn++) { 18378 if (bpf_pseudo_func(insn)) { 18379 subprog = insn->off; 18380 insn[0].imm = (u32)(long)func[subprog]->bpf_func; 18381 insn[1].imm = ((u64)(long)func[subprog]->bpf_func) >> 32; 18382 continue; 18383 } 18384 if (!bpf_pseudo_call(insn)) 18385 continue; 18386 subprog = insn->off; 18387 insn->imm = BPF_CALL_IMM(func[subprog]->bpf_func); 18388 } 18389 18390 /* we use the aux data to keep a list of the start addresses 18391 * of the JITed images for each function in the program 18392 * 18393 * for some architectures, such as powerpc64, the imm field 18394 * might not be large enough to hold the offset of the start 18395 * address of the callee's JITed image from __bpf_call_base 18396 * 18397 * in such cases, we can lookup the start address of a callee 18398 * by using its subprog id, available from the off field of 18399 * the call instruction, as an index for this list 18400 */ 18401 func[i]->aux->func = func; 18402 func[i]->aux->func_cnt = env->subprog_cnt - env->hidden_subprog_cnt; 18403 func[i]->aux->real_func_cnt = env->subprog_cnt; 18404 } 18405 for (i = 0; i < env->subprog_cnt; i++) { 18406 old_bpf_func = func[i]->bpf_func; 18407 tmp = bpf_int_jit_compile(func[i]); 18408 if (tmp != func[i] || func[i]->bpf_func != old_bpf_func) { 18409 verbose(env, "JIT doesn't support bpf-to-bpf calls\n"); 18410 err = -ENOTSUPP; 18411 goto out_free; 18412 } 18413 cond_resched(); 18414 } 18415 18416 /* finally lock prog and jit images for all functions and 18417 * populate kallsysm. Begin at the first subprogram, since 18418 * bpf_prog_load will add the kallsyms for the main program. 18419 */ 18420 for (i = 1; i < env->subprog_cnt; i++) { 18421 bpf_prog_lock_ro(func[i]); 18422 bpf_prog_kallsyms_add(func[i]); 18423 } 18424 18425 /* Last step: make now unused interpreter insns from main 18426 * prog consistent for later dump requests, so they can 18427 * later look the same as if they were interpreted only. 18428 */ 18429 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) { 18430 if (bpf_pseudo_func(insn)) { 18431 insn[0].imm = env->insn_aux_data[i].call_imm; 18432 insn[1].imm = insn->off; 18433 insn->off = 0; 18434 continue; 18435 } 18436 if (!bpf_pseudo_call(insn)) 18437 continue; 18438 insn->off = env->insn_aux_data[i].call_imm; 18439 subprog = find_subprog(env, i + insn->off + 1); 18440 insn->imm = subprog; 18441 } 18442 18443 prog->jited = 1; 18444 prog->bpf_func = func[0]->bpf_func; 18445 prog->jited_len = func[0]->jited_len; 18446 prog->aux->extable = func[0]->aux->extable; 18447 prog->aux->num_exentries = func[0]->aux->num_exentries; 18448 prog->aux->func = func; 18449 prog->aux->func_cnt = env->subprog_cnt - env->hidden_subprog_cnt; 18450 prog->aux->real_func_cnt = env->subprog_cnt; 18451 prog->aux->bpf_exception_cb = (void *)func[env->exception_callback_subprog]->bpf_func; 18452 prog->aux->exception_boundary = func[0]->aux->exception_boundary; 18453 bpf_prog_jit_attempt_done(prog); 18454 return 0; 18455 out_free: 18456 /* We failed JIT'ing, so at this point we need to unregister poke 18457 * descriptors from subprogs, so that kernel is not attempting to 18458 * patch it anymore as we're freeing the subprog JIT memory. 18459 */ 18460 for (i = 0; i < prog->aux->size_poke_tab; i++) { 18461 map_ptr = prog->aux->poke_tab[i].tail_call.map; 18462 map_ptr->ops->map_poke_untrack(map_ptr, prog->aux); 18463 } 18464 /* At this point we're guaranteed that poke descriptors are not 18465 * live anymore. We can just unlink its descriptor table as it's 18466 * released with the main prog. 18467 */ 18468 for (i = 0; i < env->subprog_cnt; i++) { 18469 if (!func[i]) 18470 continue; 18471 func[i]->aux->poke_tab = NULL; 18472 bpf_jit_free(func[i]); 18473 } 18474 kfree(func); 18475 out_undo_insn: 18476 /* cleanup main prog to be interpreted */ 18477 prog->jit_requested = 0; 18478 prog->blinding_requested = 0; 18479 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) { 18480 if (!bpf_pseudo_call(insn)) 18481 continue; 18482 insn->off = 0; 18483 insn->imm = env->insn_aux_data[i].call_imm; 18484 } 18485 bpf_prog_jit_attempt_done(prog); 18486 return err; 18487 } 18488 18489 static int fixup_call_args(struct bpf_verifier_env *env) 18490 { 18491 #ifndef CONFIG_BPF_JIT_ALWAYS_ON 18492 struct bpf_prog *prog = env->prog; 18493 struct bpf_insn *insn = prog->insnsi; 18494 bool has_kfunc_call = bpf_prog_has_kfunc_call(prog); 18495 int i, depth; 18496 #endif 18497 int err = 0; 18498 18499 if (env->prog->jit_requested && 18500 !bpf_prog_is_offloaded(env->prog->aux)) { 18501 err = jit_subprogs(env); 18502 if (err == 0) 18503 return 0; 18504 if (err == -EFAULT) 18505 return err; 18506 } 18507 #ifndef CONFIG_BPF_JIT_ALWAYS_ON 18508 if (has_kfunc_call) { 18509 verbose(env, "calling kernel functions are not allowed in non-JITed programs\n"); 18510 return -EINVAL; 18511 } 18512 if (env->subprog_cnt > 1 && env->prog->aux->tail_call_reachable) { 18513 /* When JIT fails the progs with bpf2bpf calls and tail_calls 18514 * have to be rejected, since interpreter doesn't support them yet. 18515 */ 18516 verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n"); 18517 return -EINVAL; 18518 } 18519 for (i = 0; i < prog->len; i++, insn++) { 18520 if (bpf_pseudo_func(insn)) { 18521 /* When JIT fails the progs with callback calls 18522 * have to be rejected, since interpreter doesn't support them yet. 18523 */ 18524 verbose(env, "callbacks are not allowed in non-JITed programs\n"); 18525 return -EINVAL; 18526 } 18527 18528 if (!bpf_pseudo_call(insn)) 18529 continue; 18530 depth = get_callee_stack_depth(env, insn, i); 18531 if (depth < 0) 18532 return depth; 18533 bpf_patch_call_args(insn, depth); 18534 } 18535 err = 0; 18536 #endif 18537 return err; 18538 } 18539 18540 /* replace a generic kfunc with a specialized version if necessary */ 18541 static void specialize_kfunc(struct bpf_verifier_env *env, 18542 u32 func_id, u16 offset, unsigned long *addr) 18543 { 18544 struct bpf_prog *prog = env->prog; 18545 bool seen_direct_write; 18546 void *xdp_kfunc; 18547 bool is_rdonly; 18548 18549 if (bpf_dev_bound_kfunc_id(func_id)) { 18550 xdp_kfunc = bpf_dev_bound_resolve_kfunc(prog, func_id); 18551 if (xdp_kfunc) { 18552 *addr = (unsigned long)xdp_kfunc; 18553 return; 18554 } 18555 /* fallback to default kfunc when not supported by netdev */ 18556 } 18557 18558 if (offset) 18559 return; 18560 18561 if (func_id == special_kfunc_list[KF_bpf_dynptr_from_skb]) { 18562 seen_direct_write = env->seen_direct_write; 18563 is_rdonly = !may_access_direct_pkt_data(env, NULL, BPF_WRITE); 18564 18565 if (is_rdonly) 18566 *addr = (unsigned long)bpf_dynptr_from_skb_rdonly; 18567 18568 /* restore env->seen_direct_write to its original value, since 18569 * may_access_direct_pkt_data mutates it 18570 */ 18571 env->seen_direct_write = seen_direct_write; 18572 } 18573 } 18574 18575 static void __fixup_collection_insert_kfunc(struct bpf_insn_aux_data *insn_aux, 18576 u16 struct_meta_reg, 18577 u16 node_offset_reg, 18578 struct bpf_insn *insn, 18579 struct bpf_insn *insn_buf, 18580 int *cnt) 18581 { 18582 struct btf_struct_meta *kptr_struct_meta = insn_aux->kptr_struct_meta; 18583 struct bpf_insn addr[2] = { BPF_LD_IMM64(struct_meta_reg, (long)kptr_struct_meta) }; 18584 18585 insn_buf[0] = addr[0]; 18586 insn_buf[1] = addr[1]; 18587 insn_buf[2] = BPF_MOV64_IMM(node_offset_reg, insn_aux->insert_off); 18588 insn_buf[3] = *insn; 18589 *cnt = 4; 18590 } 18591 18592 static int fixup_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn, 18593 struct bpf_insn *insn_buf, int insn_idx, int *cnt) 18594 { 18595 const struct bpf_kfunc_desc *desc; 18596 18597 if (!insn->imm) { 18598 verbose(env, "invalid kernel function call not eliminated in verifier pass\n"); 18599 return -EINVAL; 18600 } 18601 18602 *cnt = 0; 18603 18604 /* insn->imm has the btf func_id. Replace it with an offset relative to 18605 * __bpf_call_base, unless the JIT needs to call functions that are 18606 * further than 32 bits away (bpf_jit_supports_far_kfunc_call()). 18607 */ 18608 desc = find_kfunc_desc(env->prog, insn->imm, insn->off); 18609 if (!desc) { 18610 verbose(env, "verifier internal error: kernel function descriptor not found for func_id %u\n", 18611 insn->imm); 18612 return -EFAULT; 18613 } 18614 18615 if (!bpf_jit_supports_far_kfunc_call()) 18616 insn->imm = BPF_CALL_IMM(desc->addr); 18617 if (insn->off) 18618 return 0; 18619 if (desc->func_id == special_kfunc_list[KF_bpf_obj_new_impl] || 18620 desc->func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl]) { 18621 struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta; 18622 struct bpf_insn addr[2] = { BPF_LD_IMM64(BPF_REG_2, (long)kptr_struct_meta) }; 18623 u64 obj_new_size = env->insn_aux_data[insn_idx].obj_new_size; 18624 18625 if (desc->func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl] && kptr_struct_meta) { 18626 verbose(env, "verifier internal error: NULL kptr_struct_meta expected at insn_idx %d\n", 18627 insn_idx); 18628 return -EFAULT; 18629 } 18630 18631 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_1, obj_new_size); 18632 insn_buf[1] = addr[0]; 18633 insn_buf[2] = addr[1]; 18634 insn_buf[3] = *insn; 18635 *cnt = 4; 18636 } else if (desc->func_id == special_kfunc_list[KF_bpf_obj_drop_impl] || 18637 desc->func_id == special_kfunc_list[KF_bpf_percpu_obj_drop_impl] || 18638 desc->func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl]) { 18639 struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta; 18640 struct bpf_insn addr[2] = { BPF_LD_IMM64(BPF_REG_2, (long)kptr_struct_meta) }; 18641 18642 if (desc->func_id == special_kfunc_list[KF_bpf_percpu_obj_drop_impl] && kptr_struct_meta) { 18643 verbose(env, "verifier internal error: NULL kptr_struct_meta expected at insn_idx %d\n", 18644 insn_idx); 18645 return -EFAULT; 18646 } 18647 18648 if (desc->func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl] && 18649 !kptr_struct_meta) { 18650 verbose(env, "verifier internal error: kptr_struct_meta expected at insn_idx %d\n", 18651 insn_idx); 18652 return -EFAULT; 18653 } 18654 18655 insn_buf[0] = addr[0]; 18656 insn_buf[1] = addr[1]; 18657 insn_buf[2] = *insn; 18658 *cnt = 3; 18659 } else if (desc->func_id == special_kfunc_list[KF_bpf_list_push_back_impl] || 18660 desc->func_id == special_kfunc_list[KF_bpf_list_push_front_impl] || 18661 desc->func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) { 18662 struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta; 18663 int struct_meta_reg = BPF_REG_3; 18664 int node_offset_reg = BPF_REG_4; 18665 18666 /* rbtree_add has extra 'less' arg, so args-to-fixup are in diff regs */ 18667 if (desc->func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) { 18668 struct_meta_reg = BPF_REG_4; 18669 node_offset_reg = BPF_REG_5; 18670 } 18671 18672 if (!kptr_struct_meta) { 18673 verbose(env, "verifier internal error: kptr_struct_meta expected at insn_idx %d\n", 18674 insn_idx); 18675 return -EFAULT; 18676 } 18677 18678 __fixup_collection_insert_kfunc(&env->insn_aux_data[insn_idx], struct_meta_reg, 18679 node_offset_reg, insn, insn_buf, cnt); 18680 } else if (desc->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx] || 18681 desc->func_id == special_kfunc_list[KF_bpf_rdonly_cast]) { 18682 insn_buf[0] = BPF_MOV64_REG(BPF_REG_0, BPF_REG_1); 18683 *cnt = 1; 18684 } 18685 return 0; 18686 } 18687 18688 /* The function requires that first instruction in 'patch' is insnsi[prog->len - 1] */ 18689 static int add_hidden_subprog(struct bpf_verifier_env *env, struct bpf_insn *patch, int len) 18690 { 18691 struct bpf_subprog_info *info = env->subprog_info; 18692 int cnt = env->subprog_cnt; 18693 struct bpf_prog *prog; 18694 18695 /* We only reserve one slot for hidden subprogs in subprog_info. */ 18696 if (env->hidden_subprog_cnt) { 18697 verbose(env, "verifier internal error: only one hidden subprog supported\n"); 18698 return -EFAULT; 18699 } 18700 /* We're not patching any existing instruction, just appending the new 18701 * ones for the hidden subprog. Hence all of the adjustment operations 18702 * in bpf_patch_insn_data are no-ops. 18703 */ 18704 prog = bpf_patch_insn_data(env, env->prog->len - 1, patch, len); 18705 if (!prog) 18706 return -ENOMEM; 18707 env->prog = prog; 18708 info[cnt + 1].start = info[cnt].start; 18709 info[cnt].start = prog->len - len + 1; 18710 env->subprog_cnt++; 18711 env->hidden_subprog_cnt++; 18712 return 0; 18713 } 18714 18715 /* Do various post-verification rewrites in a single program pass. 18716 * These rewrites simplify JIT and interpreter implementations. 18717 */ 18718 static int do_misc_fixups(struct bpf_verifier_env *env) 18719 { 18720 struct bpf_prog *prog = env->prog; 18721 enum bpf_attach_type eatype = prog->expected_attach_type; 18722 enum bpf_prog_type prog_type = resolve_prog_type(prog); 18723 struct bpf_insn *insn = prog->insnsi; 18724 const struct bpf_func_proto *fn; 18725 const int insn_cnt = prog->len; 18726 const struct bpf_map_ops *ops; 18727 struct bpf_insn_aux_data *aux; 18728 struct bpf_insn insn_buf[16]; 18729 struct bpf_prog *new_prog; 18730 struct bpf_map *map_ptr; 18731 int i, ret, cnt, delta = 0; 18732 18733 if (env->seen_exception && !env->exception_callback_subprog) { 18734 struct bpf_insn patch[] = { 18735 env->prog->insnsi[insn_cnt - 1], 18736 BPF_MOV64_REG(BPF_REG_0, BPF_REG_1), 18737 BPF_EXIT_INSN(), 18738 }; 18739 18740 ret = add_hidden_subprog(env, patch, ARRAY_SIZE(patch)); 18741 if (ret < 0) 18742 return ret; 18743 prog = env->prog; 18744 insn = prog->insnsi; 18745 18746 env->exception_callback_subprog = env->subprog_cnt - 1; 18747 /* Don't update insn_cnt, as add_hidden_subprog always appends insns */ 18748 env->subprog_info[env->exception_callback_subprog].is_cb = true; 18749 env->subprog_info[env->exception_callback_subprog].is_async_cb = true; 18750 env->subprog_info[env->exception_callback_subprog].is_exception_cb = true; 18751 } 18752 18753 for (i = 0; i < insn_cnt; i++, insn++) { 18754 /* Make divide-by-zero exceptions impossible. */ 18755 if (insn->code == (BPF_ALU64 | BPF_MOD | BPF_X) || 18756 insn->code == (BPF_ALU64 | BPF_DIV | BPF_X) || 18757 insn->code == (BPF_ALU | BPF_MOD | BPF_X) || 18758 insn->code == (BPF_ALU | BPF_DIV | BPF_X)) { 18759 bool is64 = BPF_CLASS(insn->code) == BPF_ALU64; 18760 bool isdiv = BPF_OP(insn->code) == BPF_DIV; 18761 struct bpf_insn *patchlet; 18762 struct bpf_insn chk_and_div[] = { 18763 /* [R,W]x div 0 -> 0 */ 18764 BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) | 18765 BPF_JNE | BPF_K, insn->src_reg, 18766 0, 2, 0), 18767 BPF_ALU32_REG(BPF_XOR, insn->dst_reg, insn->dst_reg), 18768 BPF_JMP_IMM(BPF_JA, 0, 0, 1), 18769 *insn, 18770 }; 18771 struct bpf_insn chk_and_mod[] = { 18772 /* [R,W]x mod 0 -> [R,W]x */ 18773 BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) | 18774 BPF_JEQ | BPF_K, insn->src_reg, 18775 0, 1 + (is64 ? 0 : 1), 0), 18776 *insn, 18777 BPF_JMP_IMM(BPF_JA, 0, 0, 1), 18778 BPF_MOV32_REG(insn->dst_reg, insn->dst_reg), 18779 }; 18780 18781 patchlet = isdiv ? chk_and_div : chk_and_mod; 18782 cnt = isdiv ? ARRAY_SIZE(chk_and_div) : 18783 ARRAY_SIZE(chk_and_mod) - (is64 ? 2 : 0); 18784 18785 new_prog = bpf_patch_insn_data(env, i + delta, patchlet, cnt); 18786 if (!new_prog) 18787 return -ENOMEM; 18788 18789 delta += cnt - 1; 18790 env->prog = prog = new_prog; 18791 insn = new_prog->insnsi + i + delta; 18792 continue; 18793 } 18794 18795 /* Implement LD_ABS and LD_IND with a rewrite, if supported by the program type. */ 18796 if (BPF_CLASS(insn->code) == BPF_LD && 18797 (BPF_MODE(insn->code) == BPF_ABS || 18798 BPF_MODE(insn->code) == BPF_IND)) { 18799 cnt = env->ops->gen_ld_abs(insn, insn_buf); 18800 if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf)) { 18801 verbose(env, "bpf verifier is misconfigured\n"); 18802 return -EINVAL; 18803 } 18804 18805 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 18806 if (!new_prog) 18807 return -ENOMEM; 18808 18809 delta += cnt - 1; 18810 env->prog = prog = new_prog; 18811 insn = new_prog->insnsi + i + delta; 18812 continue; 18813 } 18814 18815 /* Rewrite pointer arithmetic to mitigate speculation attacks. */ 18816 if (insn->code == (BPF_ALU64 | BPF_ADD | BPF_X) || 18817 insn->code == (BPF_ALU64 | BPF_SUB | BPF_X)) { 18818 const u8 code_add = BPF_ALU64 | BPF_ADD | BPF_X; 18819 const u8 code_sub = BPF_ALU64 | BPF_SUB | BPF_X; 18820 struct bpf_insn *patch = &insn_buf[0]; 18821 bool issrc, isneg, isimm; 18822 u32 off_reg; 18823 18824 aux = &env->insn_aux_data[i + delta]; 18825 if (!aux->alu_state || 18826 aux->alu_state == BPF_ALU_NON_POINTER) 18827 continue; 18828 18829 isneg = aux->alu_state & BPF_ALU_NEG_VALUE; 18830 issrc = (aux->alu_state & BPF_ALU_SANITIZE) == 18831 BPF_ALU_SANITIZE_SRC; 18832 isimm = aux->alu_state & BPF_ALU_IMMEDIATE; 18833 18834 off_reg = issrc ? insn->src_reg : insn->dst_reg; 18835 if (isimm) { 18836 *patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit); 18837 } else { 18838 if (isneg) 18839 *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1); 18840 *patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit); 18841 *patch++ = BPF_ALU64_REG(BPF_SUB, BPF_REG_AX, off_reg); 18842 *patch++ = BPF_ALU64_REG(BPF_OR, BPF_REG_AX, off_reg); 18843 *patch++ = BPF_ALU64_IMM(BPF_NEG, BPF_REG_AX, 0); 18844 *patch++ = BPF_ALU64_IMM(BPF_ARSH, BPF_REG_AX, 63); 18845 *patch++ = BPF_ALU64_REG(BPF_AND, BPF_REG_AX, off_reg); 18846 } 18847 if (!issrc) 18848 *patch++ = BPF_MOV64_REG(insn->dst_reg, insn->src_reg); 18849 insn->src_reg = BPF_REG_AX; 18850 if (isneg) 18851 insn->code = insn->code == code_add ? 18852 code_sub : code_add; 18853 *patch++ = *insn; 18854 if (issrc && isneg && !isimm) 18855 *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1); 18856 cnt = patch - insn_buf; 18857 18858 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 18859 if (!new_prog) 18860 return -ENOMEM; 18861 18862 delta += cnt - 1; 18863 env->prog = prog = new_prog; 18864 insn = new_prog->insnsi + i + delta; 18865 continue; 18866 } 18867 18868 if (insn->code != (BPF_JMP | BPF_CALL)) 18869 continue; 18870 if (insn->src_reg == BPF_PSEUDO_CALL) 18871 continue; 18872 if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) { 18873 ret = fixup_kfunc_call(env, insn, insn_buf, i + delta, &cnt); 18874 if (ret) 18875 return ret; 18876 if (cnt == 0) 18877 continue; 18878 18879 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 18880 if (!new_prog) 18881 return -ENOMEM; 18882 18883 delta += cnt - 1; 18884 env->prog = prog = new_prog; 18885 insn = new_prog->insnsi + i + delta; 18886 continue; 18887 } 18888 18889 if (insn->imm == BPF_FUNC_get_route_realm) 18890 prog->dst_needed = 1; 18891 if (insn->imm == BPF_FUNC_get_prandom_u32) 18892 bpf_user_rnd_init_once(); 18893 if (insn->imm == BPF_FUNC_override_return) 18894 prog->kprobe_override = 1; 18895 if (insn->imm == BPF_FUNC_tail_call) { 18896 /* If we tail call into other programs, we 18897 * cannot make any assumptions since they can 18898 * be replaced dynamically during runtime in 18899 * the program array. 18900 */ 18901 prog->cb_access = 1; 18902 if (!allow_tail_call_in_subprogs(env)) 18903 prog->aux->stack_depth = MAX_BPF_STACK; 18904 prog->aux->max_pkt_offset = MAX_PACKET_OFF; 18905 18906 /* mark bpf_tail_call as different opcode to avoid 18907 * conditional branch in the interpreter for every normal 18908 * call and to prevent accidental JITing by JIT compiler 18909 * that doesn't support bpf_tail_call yet 18910 */ 18911 insn->imm = 0; 18912 insn->code = BPF_JMP | BPF_TAIL_CALL; 18913 18914 aux = &env->insn_aux_data[i + delta]; 18915 if (env->bpf_capable && !prog->blinding_requested && 18916 prog->jit_requested && 18917 !bpf_map_key_poisoned(aux) && 18918 !bpf_map_ptr_poisoned(aux) && 18919 !bpf_map_ptr_unpriv(aux)) { 18920 struct bpf_jit_poke_descriptor desc = { 18921 .reason = BPF_POKE_REASON_TAIL_CALL, 18922 .tail_call.map = BPF_MAP_PTR(aux->map_ptr_state), 18923 .tail_call.key = bpf_map_key_immediate(aux), 18924 .insn_idx = i + delta, 18925 }; 18926 18927 ret = bpf_jit_add_poke_descriptor(prog, &desc); 18928 if (ret < 0) { 18929 verbose(env, "adding tail call poke descriptor failed\n"); 18930 return ret; 18931 } 18932 18933 insn->imm = ret + 1; 18934 continue; 18935 } 18936 18937 if (!bpf_map_ptr_unpriv(aux)) 18938 continue; 18939 18940 /* instead of changing every JIT dealing with tail_call 18941 * emit two extra insns: 18942 * if (index >= max_entries) goto out; 18943 * index &= array->index_mask; 18944 * to avoid out-of-bounds cpu speculation 18945 */ 18946 if (bpf_map_ptr_poisoned(aux)) { 18947 verbose(env, "tail_call abusing map_ptr\n"); 18948 return -EINVAL; 18949 } 18950 18951 map_ptr = BPF_MAP_PTR(aux->map_ptr_state); 18952 insn_buf[0] = BPF_JMP_IMM(BPF_JGE, BPF_REG_3, 18953 map_ptr->max_entries, 2); 18954 insn_buf[1] = BPF_ALU32_IMM(BPF_AND, BPF_REG_3, 18955 container_of(map_ptr, 18956 struct bpf_array, 18957 map)->index_mask); 18958 insn_buf[2] = *insn; 18959 cnt = 3; 18960 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 18961 if (!new_prog) 18962 return -ENOMEM; 18963 18964 delta += cnt - 1; 18965 env->prog = prog = new_prog; 18966 insn = new_prog->insnsi + i + delta; 18967 continue; 18968 } 18969 18970 if (insn->imm == BPF_FUNC_timer_set_callback) { 18971 /* The verifier will process callback_fn as many times as necessary 18972 * with different maps and the register states prepared by 18973 * set_timer_callback_state will be accurate. 18974 * 18975 * The following use case is valid: 18976 * map1 is shared by prog1, prog2, prog3. 18977 * prog1 calls bpf_timer_init for some map1 elements 18978 * prog2 calls bpf_timer_set_callback for some map1 elements. 18979 * Those that were not bpf_timer_init-ed will return -EINVAL. 18980 * prog3 calls bpf_timer_start for some map1 elements. 18981 * Those that were not both bpf_timer_init-ed and 18982 * bpf_timer_set_callback-ed will return -EINVAL. 18983 */ 18984 struct bpf_insn ld_addrs[2] = { 18985 BPF_LD_IMM64(BPF_REG_3, (long)prog->aux), 18986 }; 18987 18988 insn_buf[0] = ld_addrs[0]; 18989 insn_buf[1] = ld_addrs[1]; 18990 insn_buf[2] = *insn; 18991 cnt = 3; 18992 18993 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 18994 if (!new_prog) 18995 return -ENOMEM; 18996 18997 delta += cnt - 1; 18998 env->prog = prog = new_prog; 18999 insn = new_prog->insnsi + i + delta; 19000 goto patch_call_imm; 19001 } 19002 19003 if (is_storage_get_function(insn->imm)) { 19004 if (!env->prog->aux->sleepable || 19005 env->insn_aux_data[i + delta].storage_get_func_atomic) 19006 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_5, (__force __s32)GFP_ATOMIC); 19007 else 19008 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_5, (__force __s32)GFP_KERNEL); 19009 insn_buf[1] = *insn; 19010 cnt = 2; 19011 19012 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 19013 if (!new_prog) 19014 return -ENOMEM; 19015 19016 delta += cnt - 1; 19017 env->prog = prog = new_prog; 19018 insn = new_prog->insnsi + i + delta; 19019 goto patch_call_imm; 19020 } 19021 19022 /* bpf_per_cpu_ptr() and bpf_this_cpu_ptr() */ 19023 if (env->insn_aux_data[i + delta].call_with_percpu_alloc_ptr) { 19024 /* patch with 'r1 = *(u64 *)(r1 + 0)' since for percpu data, 19025 * bpf_mem_alloc() returns a ptr to the percpu data ptr. 19026 */ 19027 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_1, BPF_REG_1, 0); 19028 insn_buf[1] = *insn; 19029 cnt = 2; 19030 19031 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 19032 if (!new_prog) 19033 return -ENOMEM; 19034 19035 delta += cnt - 1; 19036 env->prog = prog = new_prog; 19037 insn = new_prog->insnsi + i + delta; 19038 goto patch_call_imm; 19039 } 19040 19041 /* BPF_EMIT_CALL() assumptions in some of the map_gen_lookup 19042 * and other inlining handlers are currently limited to 64 bit 19043 * only. 19044 */ 19045 if (prog->jit_requested && BITS_PER_LONG == 64 && 19046 (insn->imm == BPF_FUNC_map_lookup_elem || 19047 insn->imm == BPF_FUNC_map_update_elem || 19048 insn->imm == BPF_FUNC_map_delete_elem || 19049 insn->imm == BPF_FUNC_map_push_elem || 19050 insn->imm == BPF_FUNC_map_pop_elem || 19051 insn->imm == BPF_FUNC_map_peek_elem || 19052 insn->imm == BPF_FUNC_redirect_map || 19053 insn->imm == BPF_FUNC_for_each_map_elem || 19054 insn->imm == BPF_FUNC_map_lookup_percpu_elem)) { 19055 aux = &env->insn_aux_data[i + delta]; 19056 if (bpf_map_ptr_poisoned(aux)) 19057 goto patch_call_imm; 19058 19059 map_ptr = BPF_MAP_PTR(aux->map_ptr_state); 19060 ops = map_ptr->ops; 19061 if (insn->imm == BPF_FUNC_map_lookup_elem && 19062 ops->map_gen_lookup) { 19063 cnt = ops->map_gen_lookup(map_ptr, insn_buf); 19064 if (cnt == -EOPNOTSUPP) 19065 goto patch_map_ops_generic; 19066 if (cnt <= 0 || cnt >= ARRAY_SIZE(insn_buf)) { 19067 verbose(env, "bpf verifier is misconfigured\n"); 19068 return -EINVAL; 19069 } 19070 19071 new_prog = bpf_patch_insn_data(env, i + delta, 19072 insn_buf, cnt); 19073 if (!new_prog) 19074 return -ENOMEM; 19075 19076 delta += cnt - 1; 19077 env->prog = prog = new_prog; 19078 insn = new_prog->insnsi + i + delta; 19079 continue; 19080 } 19081 19082 BUILD_BUG_ON(!__same_type(ops->map_lookup_elem, 19083 (void *(*)(struct bpf_map *map, void *key))NULL)); 19084 BUILD_BUG_ON(!__same_type(ops->map_delete_elem, 19085 (long (*)(struct bpf_map *map, void *key))NULL)); 19086 BUILD_BUG_ON(!__same_type(ops->map_update_elem, 19087 (long (*)(struct bpf_map *map, void *key, void *value, 19088 u64 flags))NULL)); 19089 BUILD_BUG_ON(!__same_type(ops->map_push_elem, 19090 (long (*)(struct bpf_map *map, void *value, 19091 u64 flags))NULL)); 19092 BUILD_BUG_ON(!__same_type(ops->map_pop_elem, 19093 (long (*)(struct bpf_map *map, void *value))NULL)); 19094 BUILD_BUG_ON(!__same_type(ops->map_peek_elem, 19095 (long (*)(struct bpf_map *map, void *value))NULL)); 19096 BUILD_BUG_ON(!__same_type(ops->map_redirect, 19097 (long (*)(struct bpf_map *map, u64 index, u64 flags))NULL)); 19098 BUILD_BUG_ON(!__same_type(ops->map_for_each_callback, 19099 (long (*)(struct bpf_map *map, 19100 bpf_callback_t callback_fn, 19101 void *callback_ctx, 19102 u64 flags))NULL)); 19103 BUILD_BUG_ON(!__same_type(ops->map_lookup_percpu_elem, 19104 (void *(*)(struct bpf_map *map, void *key, u32 cpu))NULL)); 19105 19106 patch_map_ops_generic: 19107 switch (insn->imm) { 19108 case BPF_FUNC_map_lookup_elem: 19109 insn->imm = BPF_CALL_IMM(ops->map_lookup_elem); 19110 continue; 19111 case BPF_FUNC_map_update_elem: 19112 insn->imm = BPF_CALL_IMM(ops->map_update_elem); 19113 continue; 19114 case BPF_FUNC_map_delete_elem: 19115 insn->imm = BPF_CALL_IMM(ops->map_delete_elem); 19116 continue; 19117 case BPF_FUNC_map_push_elem: 19118 insn->imm = BPF_CALL_IMM(ops->map_push_elem); 19119 continue; 19120 case BPF_FUNC_map_pop_elem: 19121 insn->imm = BPF_CALL_IMM(ops->map_pop_elem); 19122 continue; 19123 case BPF_FUNC_map_peek_elem: 19124 insn->imm = BPF_CALL_IMM(ops->map_peek_elem); 19125 continue; 19126 case BPF_FUNC_redirect_map: 19127 insn->imm = BPF_CALL_IMM(ops->map_redirect); 19128 continue; 19129 case BPF_FUNC_for_each_map_elem: 19130 insn->imm = BPF_CALL_IMM(ops->map_for_each_callback); 19131 continue; 19132 case BPF_FUNC_map_lookup_percpu_elem: 19133 insn->imm = BPF_CALL_IMM(ops->map_lookup_percpu_elem); 19134 continue; 19135 } 19136 19137 goto patch_call_imm; 19138 } 19139 19140 /* Implement bpf_jiffies64 inline. */ 19141 if (prog->jit_requested && BITS_PER_LONG == 64 && 19142 insn->imm == BPF_FUNC_jiffies64) { 19143 struct bpf_insn ld_jiffies_addr[2] = { 19144 BPF_LD_IMM64(BPF_REG_0, 19145 (unsigned long)&jiffies), 19146 }; 19147 19148 insn_buf[0] = ld_jiffies_addr[0]; 19149 insn_buf[1] = ld_jiffies_addr[1]; 19150 insn_buf[2] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, 19151 BPF_REG_0, 0); 19152 cnt = 3; 19153 19154 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 19155 cnt); 19156 if (!new_prog) 19157 return -ENOMEM; 19158 19159 delta += cnt - 1; 19160 env->prog = prog = new_prog; 19161 insn = new_prog->insnsi + i + delta; 19162 continue; 19163 } 19164 19165 /* Implement bpf_get_func_arg inline. */ 19166 if (prog_type == BPF_PROG_TYPE_TRACING && 19167 insn->imm == BPF_FUNC_get_func_arg) { 19168 /* Load nr_args from ctx - 8 */ 19169 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8); 19170 insn_buf[1] = BPF_JMP32_REG(BPF_JGE, BPF_REG_2, BPF_REG_0, 6); 19171 insn_buf[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_2, 3); 19172 insn_buf[3] = BPF_ALU64_REG(BPF_ADD, BPF_REG_2, BPF_REG_1); 19173 insn_buf[4] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_2, 0); 19174 insn_buf[5] = BPF_STX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0); 19175 insn_buf[6] = BPF_MOV64_IMM(BPF_REG_0, 0); 19176 insn_buf[7] = BPF_JMP_A(1); 19177 insn_buf[8] = BPF_MOV64_IMM(BPF_REG_0, -EINVAL); 19178 cnt = 9; 19179 19180 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 19181 if (!new_prog) 19182 return -ENOMEM; 19183 19184 delta += cnt - 1; 19185 env->prog = prog = new_prog; 19186 insn = new_prog->insnsi + i + delta; 19187 continue; 19188 } 19189 19190 /* Implement bpf_get_func_ret inline. */ 19191 if (prog_type == BPF_PROG_TYPE_TRACING && 19192 insn->imm == BPF_FUNC_get_func_ret) { 19193 if (eatype == BPF_TRACE_FEXIT || 19194 eatype == BPF_MODIFY_RETURN) { 19195 /* Load nr_args from ctx - 8 */ 19196 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8); 19197 insn_buf[1] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_0, 3); 19198 insn_buf[2] = BPF_ALU64_REG(BPF_ADD, BPF_REG_0, BPF_REG_1); 19199 insn_buf[3] = BPF_LDX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0); 19200 insn_buf[4] = BPF_STX_MEM(BPF_DW, BPF_REG_2, BPF_REG_3, 0); 19201 insn_buf[5] = BPF_MOV64_IMM(BPF_REG_0, 0); 19202 cnt = 6; 19203 } else { 19204 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_0, -EOPNOTSUPP); 19205 cnt = 1; 19206 } 19207 19208 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 19209 if (!new_prog) 19210 return -ENOMEM; 19211 19212 delta += cnt - 1; 19213 env->prog = prog = new_prog; 19214 insn = new_prog->insnsi + i + delta; 19215 continue; 19216 } 19217 19218 /* Implement get_func_arg_cnt inline. */ 19219 if (prog_type == BPF_PROG_TYPE_TRACING && 19220 insn->imm == BPF_FUNC_get_func_arg_cnt) { 19221 /* Load nr_args from ctx - 8 */ 19222 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8); 19223 19224 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1); 19225 if (!new_prog) 19226 return -ENOMEM; 19227 19228 env->prog = prog = new_prog; 19229 insn = new_prog->insnsi + i + delta; 19230 continue; 19231 } 19232 19233 /* Implement bpf_get_func_ip inline. */ 19234 if (prog_type == BPF_PROG_TYPE_TRACING && 19235 insn->imm == BPF_FUNC_get_func_ip) { 19236 /* Load IP address from ctx - 16 */ 19237 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -16); 19238 19239 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1); 19240 if (!new_prog) 19241 return -ENOMEM; 19242 19243 env->prog = prog = new_prog; 19244 insn = new_prog->insnsi + i + delta; 19245 continue; 19246 } 19247 19248 patch_call_imm: 19249 fn = env->ops->get_func_proto(insn->imm, env->prog); 19250 /* all functions that have prototype and verifier allowed 19251 * programs to call them, must be real in-kernel functions 19252 */ 19253 if (!fn->func) { 19254 verbose(env, 19255 "kernel subsystem misconfigured func %s#%d\n", 19256 func_id_name(insn->imm), insn->imm); 19257 return -EFAULT; 19258 } 19259 insn->imm = fn->func - __bpf_call_base; 19260 } 19261 19262 /* Since poke tab is now finalized, publish aux to tracker. */ 19263 for (i = 0; i < prog->aux->size_poke_tab; i++) { 19264 map_ptr = prog->aux->poke_tab[i].tail_call.map; 19265 if (!map_ptr->ops->map_poke_track || 19266 !map_ptr->ops->map_poke_untrack || 19267 !map_ptr->ops->map_poke_run) { 19268 verbose(env, "bpf verifier is misconfigured\n"); 19269 return -EINVAL; 19270 } 19271 19272 ret = map_ptr->ops->map_poke_track(map_ptr, prog->aux); 19273 if (ret < 0) { 19274 verbose(env, "tracking tail call prog failed\n"); 19275 return ret; 19276 } 19277 } 19278 19279 sort_kfunc_descs_by_imm_off(env->prog); 19280 19281 return 0; 19282 } 19283 19284 static struct bpf_prog *inline_bpf_loop(struct bpf_verifier_env *env, 19285 int position, 19286 s32 stack_base, 19287 u32 callback_subprogno, 19288 u32 *cnt) 19289 { 19290 s32 r6_offset = stack_base + 0 * BPF_REG_SIZE; 19291 s32 r7_offset = stack_base + 1 * BPF_REG_SIZE; 19292 s32 r8_offset = stack_base + 2 * BPF_REG_SIZE; 19293 int reg_loop_max = BPF_REG_6; 19294 int reg_loop_cnt = BPF_REG_7; 19295 int reg_loop_ctx = BPF_REG_8; 19296 19297 struct bpf_prog *new_prog; 19298 u32 callback_start; 19299 u32 call_insn_offset; 19300 s32 callback_offset; 19301 19302 /* This represents an inlined version of bpf_iter.c:bpf_loop, 19303 * be careful to modify this code in sync. 19304 */ 19305 struct bpf_insn insn_buf[] = { 19306 /* Return error and jump to the end of the patch if 19307 * expected number of iterations is too big. 19308 */ 19309 BPF_JMP_IMM(BPF_JLE, BPF_REG_1, BPF_MAX_LOOPS, 2), 19310 BPF_MOV32_IMM(BPF_REG_0, -E2BIG), 19311 BPF_JMP_IMM(BPF_JA, 0, 0, 16), 19312 /* spill R6, R7, R8 to use these as loop vars */ 19313 BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_6, r6_offset), 19314 BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_7, r7_offset), 19315 BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_8, r8_offset), 19316 /* initialize loop vars */ 19317 BPF_MOV64_REG(reg_loop_max, BPF_REG_1), 19318 BPF_MOV32_IMM(reg_loop_cnt, 0), 19319 BPF_MOV64_REG(reg_loop_ctx, BPF_REG_3), 19320 /* loop header, 19321 * if reg_loop_cnt >= reg_loop_max skip the loop body 19322 */ 19323 BPF_JMP_REG(BPF_JGE, reg_loop_cnt, reg_loop_max, 5), 19324 /* callback call, 19325 * correct callback offset would be set after patching 19326 */ 19327 BPF_MOV64_REG(BPF_REG_1, reg_loop_cnt), 19328 BPF_MOV64_REG(BPF_REG_2, reg_loop_ctx), 19329 BPF_CALL_REL(0), 19330 /* increment loop counter */ 19331 BPF_ALU64_IMM(BPF_ADD, reg_loop_cnt, 1), 19332 /* jump to loop header if callback returned 0 */ 19333 BPF_JMP_IMM(BPF_JEQ, BPF_REG_0, 0, -6), 19334 /* return value of bpf_loop, 19335 * set R0 to the number of iterations 19336 */ 19337 BPF_MOV64_REG(BPF_REG_0, reg_loop_cnt), 19338 /* restore original values of R6, R7, R8 */ 19339 BPF_LDX_MEM(BPF_DW, BPF_REG_6, BPF_REG_10, r6_offset), 19340 BPF_LDX_MEM(BPF_DW, BPF_REG_7, BPF_REG_10, r7_offset), 19341 BPF_LDX_MEM(BPF_DW, BPF_REG_8, BPF_REG_10, r8_offset), 19342 }; 19343 19344 *cnt = ARRAY_SIZE(insn_buf); 19345 new_prog = bpf_patch_insn_data(env, position, insn_buf, *cnt); 19346 if (!new_prog) 19347 return new_prog; 19348 19349 /* callback start is known only after patching */ 19350 callback_start = env->subprog_info[callback_subprogno].start; 19351 /* Note: insn_buf[12] is an offset of BPF_CALL_REL instruction */ 19352 call_insn_offset = position + 12; 19353 callback_offset = callback_start - call_insn_offset - 1; 19354 new_prog->insnsi[call_insn_offset].imm = callback_offset; 19355 19356 return new_prog; 19357 } 19358 19359 static bool is_bpf_loop_call(struct bpf_insn *insn) 19360 { 19361 return insn->code == (BPF_JMP | BPF_CALL) && 19362 insn->src_reg == 0 && 19363 insn->imm == BPF_FUNC_loop; 19364 } 19365 19366 /* For all sub-programs in the program (including main) check 19367 * insn_aux_data to see if there are bpf_loop calls that require 19368 * inlining. If such calls are found the calls are replaced with a 19369 * sequence of instructions produced by `inline_bpf_loop` function and 19370 * subprog stack_depth is increased by the size of 3 registers. 19371 * This stack space is used to spill values of the R6, R7, R8. These 19372 * registers are used to store the loop bound, counter and context 19373 * variables. 19374 */ 19375 static int optimize_bpf_loop(struct bpf_verifier_env *env) 19376 { 19377 struct bpf_subprog_info *subprogs = env->subprog_info; 19378 int i, cur_subprog = 0, cnt, delta = 0; 19379 struct bpf_insn *insn = env->prog->insnsi; 19380 int insn_cnt = env->prog->len; 19381 u16 stack_depth = subprogs[cur_subprog].stack_depth; 19382 u16 stack_depth_roundup = round_up(stack_depth, 8) - stack_depth; 19383 u16 stack_depth_extra = 0; 19384 19385 for (i = 0; i < insn_cnt; i++, insn++) { 19386 struct bpf_loop_inline_state *inline_state = 19387 &env->insn_aux_data[i + delta].loop_inline_state; 19388 19389 if (is_bpf_loop_call(insn) && inline_state->fit_for_inline) { 19390 struct bpf_prog *new_prog; 19391 19392 stack_depth_extra = BPF_REG_SIZE * 3 + stack_depth_roundup; 19393 new_prog = inline_bpf_loop(env, 19394 i + delta, 19395 -(stack_depth + stack_depth_extra), 19396 inline_state->callback_subprogno, 19397 &cnt); 19398 if (!new_prog) 19399 return -ENOMEM; 19400 19401 delta += cnt - 1; 19402 env->prog = new_prog; 19403 insn = new_prog->insnsi + i + delta; 19404 } 19405 19406 if (subprogs[cur_subprog + 1].start == i + delta + 1) { 19407 subprogs[cur_subprog].stack_depth += stack_depth_extra; 19408 cur_subprog++; 19409 stack_depth = subprogs[cur_subprog].stack_depth; 19410 stack_depth_roundup = round_up(stack_depth, 8) - stack_depth; 19411 stack_depth_extra = 0; 19412 } 19413 } 19414 19415 env->prog->aux->stack_depth = env->subprog_info[0].stack_depth; 19416 19417 return 0; 19418 } 19419 19420 static void free_states(struct bpf_verifier_env *env) 19421 { 19422 struct bpf_verifier_state_list *sl, *sln; 19423 int i; 19424 19425 sl = env->free_list; 19426 while (sl) { 19427 sln = sl->next; 19428 free_verifier_state(&sl->state, false); 19429 kfree(sl); 19430 sl = sln; 19431 } 19432 env->free_list = NULL; 19433 19434 if (!env->explored_states) 19435 return; 19436 19437 for (i = 0; i < state_htab_size(env); i++) { 19438 sl = env->explored_states[i]; 19439 19440 while (sl) { 19441 sln = sl->next; 19442 free_verifier_state(&sl->state, false); 19443 kfree(sl); 19444 sl = sln; 19445 } 19446 env->explored_states[i] = NULL; 19447 } 19448 } 19449 19450 static int do_check_common(struct bpf_verifier_env *env, int subprog, bool is_ex_cb) 19451 { 19452 bool pop_log = !(env->log.level & BPF_LOG_LEVEL2); 19453 struct bpf_verifier_state *state; 19454 struct bpf_reg_state *regs; 19455 int ret, i; 19456 19457 env->prev_linfo = NULL; 19458 env->pass_cnt++; 19459 19460 state = kzalloc(sizeof(struct bpf_verifier_state), GFP_KERNEL); 19461 if (!state) 19462 return -ENOMEM; 19463 state->curframe = 0; 19464 state->speculative = false; 19465 state->branches = 1; 19466 state->frame[0] = kzalloc(sizeof(struct bpf_func_state), GFP_KERNEL); 19467 if (!state->frame[0]) { 19468 kfree(state); 19469 return -ENOMEM; 19470 } 19471 env->cur_state = state; 19472 init_func_state(env, state->frame[0], 19473 BPF_MAIN_FUNC /* callsite */, 19474 0 /* frameno */, 19475 subprog); 19476 state->first_insn_idx = env->subprog_info[subprog].start; 19477 state->last_insn_idx = -1; 19478 19479 regs = state->frame[state->curframe]->regs; 19480 if (subprog || env->prog->type == BPF_PROG_TYPE_EXT) { 19481 ret = btf_prepare_func_args(env, subprog, regs, is_ex_cb); 19482 if (ret) 19483 goto out; 19484 for (i = BPF_REG_1; i <= BPF_REG_5; i++) { 19485 if (regs[i].type == PTR_TO_CTX) 19486 mark_reg_known_zero(env, regs, i); 19487 else if (regs[i].type == SCALAR_VALUE) 19488 mark_reg_unknown(env, regs, i); 19489 else if (base_type(regs[i].type) == PTR_TO_MEM) { 19490 const u32 mem_size = regs[i].mem_size; 19491 19492 mark_reg_known_zero(env, regs, i); 19493 regs[i].mem_size = mem_size; 19494 regs[i].id = ++env->id_gen; 19495 } 19496 } 19497 if (is_ex_cb) { 19498 state->frame[0]->in_exception_callback_fn = true; 19499 env->subprog_info[subprog].is_cb = true; 19500 env->subprog_info[subprog].is_async_cb = true; 19501 env->subprog_info[subprog].is_exception_cb = true; 19502 } 19503 } else { 19504 /* 1st arg to a function */ 19505 regs[BPF_REG_1].type = PTR_TO_CTX; 19506 mark_reg_known_zero(env, regs, BPF_REG_1); 19507 ret = btf_check_subprog_arg_match(env, subprog, regs); 19508 if (ret == -EFAULT) 19509 /* unlikely verifier bug. abort. 19510 * ret == 0 and ret < 0 are sadly acceptable for 19511 * main() function due to backward compatibility. 19512 * Like socket filter program may be written as: 19513 * int bpf_prog(struct pt_regs *ctx) 19514 * and never dereference that ctx in the program. 19515 * 'struct pt_regs' is a type mismatch for socket 19516 * filter that should be using 'struct __sk_buff'. 19517 */ 19518 goto out; 19519 } 19520 19521 ret = do_check(env); 19522 out: 19523 /* check for NULL is necessary, since cur_state can be freed inside 19524 * do_check() under memory pressure. 19525 */ 19526 if (env->cur_state) { 19527 free_verifier_state(env->cur_state, true); 19528 env->cur_state = NULL; 19529 } 19530 while (!pop_stack(env, NULL, NULL, false)); 19531 if (!ret && pop_log) 19532 bpf_vlog_reset(&env->log, 0); 19533 free_states(env); 19534 return ret; 19535 } 19536 19537 /* Verify all global functions in a BPF program one by one based on their BTF. 19538 * All global functions must pass verification. Otherwise the whole program is rejected. 19539 * Consider: 19540 * int bar(int); 19541 * int foo(int f) 19542 * { 19543 * return bar(f); 19544 * } 19545 * int bar(int b) 19546 * { 19547 * ... 19548 * } 19549 * foo() will be verified first for R1=any_scalar_value. During verification it 19550 * will be assumed that bar() already verified successfully and call to bar() 19551 * from foo() will be checked for type match only. Later bar() will be verified 19552 * independently to check that it's safe for R1=any_scalar_value. 19553 */ 19554 static int do_check_subprogs(struct bpf_verifier_env *env) 19555 { 19556 struct bpf_prog_aux *aux = env->prog->aux; 19557 int i, ret; 19558 19559 if (!aux->func_info) 19560 return 0; 19561 19562 for (i = 1; i < env->subprog_cnt; i++) { 19563 if (aux->func_info_aux[i].linkage != BTF_FUNC_GLOBAL) 19564 continue; 19565 env->insn_idx = env->subprog_info[i].start; 19566 WARN_ON_ONCE(env->insn_idx == 0); 19567 ret = do_check_common(env, i, env->exception_callback_subprog == i); 19568 if (ret) { 19569 return ret; 19570 } else if (env->log.level & BPF_LOG_LEVEL) { 19571 verbose(env, 19572 "Func#%d is safe for any args that match its prototype\n", 19573 i); 19574 } 19575 } 19576 return 0; 19577 } 19578 19579 static int do_check_main(struct bpf_verifier_env *env) 19580 { 19581 int ret; 19582 19583 env->insn_idx = 0; 19584 ret = do_check_common(env, 0, false); 19585 if (!ret) 19586 env->prog->aux->stack_depth = env->subprog_info[0].stack_depth; 19587 return ret; 19588 } 19589 19590 19591 static void print_verification_stats(struct bpf_verifier_env *env) 19592 { 19593 int i; 19594 19595 if (env->log.level & BPF_LOG_STATS) { 19596 verbose(env, "verification time %lld usec\n", 19597 div_u64(env->verification_time, 1000)); 19598 verbose(env, "stack depth "); 19599 for (i = 0; i < env->subprog_cnt; i++) { 19600 u32 depth = env->subprog_info[i].stack_depth; 19601 19602 verbose(env, "%d", depth); 19603 if (i + 1 < env->subprog_cnt) 19604 verbose(env, "+"); 19605 } 19606 verbose(env, "\n"); 19607 } 19608 verbose(env, "processed %d insns (limit %d) max_states_per_insn %d " 19609 "total_states %d peak_states %d mark_read %d\n", 19610 env->insn_processed, BPF_COMPLEXITY_LIMIT_INSNS, 19611 env->max_states_per_insn, env->total_states, 19612 env->peak_states, env->longest_mark_read_walk); 19613 } 19614 19615 static int check_struct_ops_btf_id(struct bpf_verifier_env *env) 19616 { 19617 const struct btf_type *t, *func_proto; 19618 const struct bpf_struct_ops *st_ops; 19619 const struct btf_member *member; 19620 struct bpf_prog *prog = env->prog; 19621 u32 btf_id, member_idx; 19622 const char *mname; 19623 19624 if (!prog->gpl_compatible) { 19625 verbose(env, "struct ops programs must have a GPL compatible license\n"); 19626 return -EINVAL; 19627 } 19628 19629 btf_id = prog->aux->attach_btf_id; 19630 st_ops = bpf_struct_ops_find(btf_id); 19631 if (!st_ops) { 19632 verbose(env, "attach_btf_id %u is not a supported struct\n", 19633 btf_id); 19634 return -ENOTSUPP; 19635 } 19636 19637 t = st_ops->type; 19638 member_idx = prog->expected_attach_type; 19639 if (member_idx >= btf_type_vlen(t)) { 19640 verbose(env, "attach to invalid member idx %u of struct %s\n", 19641 member_idx, st_ops->name); 19642 return -EINVAL; 19643 } 19644 19645 member = &btf_type_member(t)[member_idx]; 19646 mname = btf_name_by_offset(btf_vmlinux, member->name_off); 19647 func_proto = btf_type_resolve_func_ptr(btf_vmlinux, member->type, 19648 NULL); 19649 if (!func_proto) { 19650 verbose(env, "attach to invalid member %s(@idx %u) of struct %s\n", 19651 mname, member_idx, st_ops->name); 19652 return -EINVAL; 19653 } 19654 19655 if (st_ops->check_member) { 19656 int err = st_ops->check_member(t, member, prog); 19657 19658 if (err) { 19659 verbose(env, "attach to unsupported member %s of struct %s\n", 19660 mname, st_ops->name); 19661 return err; 19662 } 19663 } 19664 19665 prog->aux->attach_func_proto = func_proto; 19666 prog->aux->attach_func_name = mname; 19667 env->ops = st_ops->verifier_ops; 19668 19669 return 0; 19670 } 19671 #define SECURITY_PREFIX "security_" 19672 19673 static int check_attach_modify_return(unsigned long addr, const char *func_name) 19674 { 19675 if (within_error_injection_list(addr) || 19676 !strncmp(SECURITY_PREFIX, func_name, sizeof(SECURITY_PREFIX) - 1)) 19677 return 0; 19678 19679 return -EINVAL; 19680 } 19681 19682 /* list of non-sleepable functions that are otherwise on 19683 * ALLOW_ERROR_INJECTION list 19684 */ 19685 BTF_SET_START(btf_non_sleepable_error_inject) 19686 /* Three functions below can be called from sleepable and non-sleepable context. 19687 * Assume non-sleepable from bpf safety point of view. 19688 */ 19689 BTF_ID(func, __filemap_add_folio) 19690 BTF_ID(func, should_fail_alloc_page) 19691 BTF_ID(func, should_failslab) 19692 BTF_SET_END(btf_non_sleepable_error_inject) 19693 19694 static int check_non_sleepable_error_inject(u32 btf_id) 19695 { 19696 return btf_id_set_contains(&btf_non_sleepable_error_inject, btf_id); 19697 } 19698 19699 int bpf_check_attach_target(struct bpf_verifier_log *log, 19700 const struct bpf_prog *prog, 19701 const struct bpf_prog *tgt_prog, 19702 u32 btf_id, 19703 struct bpf_attach_target_info *tgt_info) 19704 { 19705 bool prog_extension = prog->type == BPF_PROG_TYPE_EXT; 19706 const char prefix[] = "btf_trace_"; 19707 int ret = 0, subprog = -1, i; 19708 const struct btf_type *t; 19709 bool conservative = true; 19710 const char *tname; 19711 struct btf *btf; 19712 long addr = 0; 19713 struct module *mod = NULL; 19714 19715 if (!btf_id) { 19716 bpf_log(log, "Tracing programs must provide btf_id\n"); 19717 return -EINVAL; 19718 } 19719 btf = tgt_prog ? tgt_prog->aux->btf : prog->aux->attach_btf; 19720 if (!btf) { 19721 bpf_log(log, 19722 "FENTRY/FEXIT program can only be attached to another program annotated with BTF\n"); 19723 return -EINVAL; 19724 } 19725 t = btf_type_by_id(btf, btf_id); 19726 if (!t) { 19727 bpf_log(log, "attach_btf_id %u is invalid\n", btf_id); 19728 return -EINVAL; 19729 } 19730 tname = btf_name_by_offset(btf, t->name_off); 19731 if (!tname) { 19732 bpf_log(log, "attach_btf_id %u doesn't have a name\n", btf_id); 19733 return -EINVAL; 19734 } 19735 if (tgt_prog) { 19736 struct bpf_prog_aux *aux = tgt_prog->aux; 19737 19738 if (bpf_prog_is_dev_bound(prog->aux) && 19739 !bpf_prog_dev_bound_match(prog, tgt_prog)) { 19740 bpf_log(log, "Target program bound device mismatch"); 19741 return -EINVAL; 19742 } 19743 19744 for (i = 0; i < aux->func_info_cnt; i++) 19745 if (aux->func_info[i].type_id == btf_id) { 19746 subprog = i; 19747 break; 19748 } 19749 if (subprog == -1) { 19750 bpf_log(log, "Subprog %s doesn't exist\n", tname); 19751 return -EINVAL; 19752 } 19753 if (aux->func && aux->func[subprog]->aux->exception_cb) { 19754 bpf_log(log, 19755 "%s programs cannot attach to exception callback\n", 19756 prog_extension ? "Extension" : "FENTRY/FEXIT"); 19757 return -EINVAL; 19758 } 19759 conservative = aux->func_info_aux[subprog].unreliable; 19760 if (prog_extension) { 19761 if (conservative) { 19762 bpf_log(log, 19763 "Cannot replace static functions\n"); 19764 return -EINVAL; 19765 } 19766 if (!prog->jit_requested) { 19767 bpf_log(log, 19768 "Extension programs should be JITed\n"); 19769 return -EINVAL; 19770 } 19771 } 19772 if (!tgt_prog->jited) { 19773 bpf_log(log, "Can attach to only JITed progs\n"); 19774 return -EINVAL; 19775 } 19776 if (tgt_prog->type == prog->type) { 19777 /* Cannot fentry/fexit another fentry/fexit program. 19778 * Cannot attach program extension to another extension. 19779 * It's ok to attach fentry/fexit to extension program. 19780 */ 19781 bpf_log(log, "Cannot recursively attach\n"); 19782 return -EINVAL; 19783 } 19784 if (tgt_prog->type == BPF_PROG_TYPE_TRACING && 19785 prog_extension && 19786 (tgt_prog->expected_attach_type == BPF_TRACE_FENTRY || 19787 tgt_prog->expected_attach_type == BPF_TRACE_FEXIT)) { 19788 /* Program extensions can extend all program types 19789 * except fentry/fexit. The reason is the following. 19790 * The fentry/fexit programs are used for performance 19791 * analysis, stats and can be attached to any program 19792 * type except themselves. When extension program is 19793 * replacing XDP function it is necessary to allow 19794 * performance analysis of all functions. Both original 19795 * XDP program and its program extension. Hence 19796 * attaching fentry/fexit to BPF_PROG_TYPE_EXT is 19797 * allowed. If extending of fentry/fexit was allowed it 19798 * would be possible to create long call chain 19799 * fentry->extension->fentry->extension beyond 19800 * reasonable stack size. Hence extending fentry is not 19801 * allowed. 19802 */ 19803 bpf_log(log, "Cannot extend fentry/fexit\n"); 19804 return -EINVAL; 19805 } 19806 } else { 19807 if (prog_extension) { 19808 bpf_log(log, "Cannot replace kernel functions\n"); 19809 return -EINVAL; 19810 } 19811 } 19812 19813 switch (prog->expected_attach_type) { 19814 case BPF_TRACE_RAW_TP: 19815 if (tgt_prog) { 19816 bpf_log(log, 19817 "Only FENTRY/FEXIT progs are attachable to another BPF prog\n"); 19818 return -EINVAL; 19819 } 19820 if (!btf_type_is_typedef(t)) { 19821 bpf_log(log, "attach_btf_id %u is not a typedef\n", 19822 btf_id); 19823 return -EINVAL; 19824 } 19825 if (strncmp(prefix, tname, sizeof(prefix) - 1)) { 19826 bpf_log(log, "attach_btf_id %u points to wrong type name %s\n", 19827 btf_id, tname); 19828 return -EINVAL; 19829 } 19830 tname += sizeof(prefix) - 1; 19831 t = btf_type_by_id(btf, t->type); 19832 if (!btf_type_is_ptr(t)) 19833 /* should never happen in valid vmlinux build */ 19834 return -EINVAL; 19835 t = btf_type_by_id(btf, t->type); 19836 if (!btf_type_is_func_proto(t)) 19837 /* should never happen in valid vmlinux build */ 19838 return -EINVAL; 19839 19840 break; 19841 case BPF_TRACE_ITER: 19842 if (!btf_type_is_func(t)) { 19843 bpf_log(log, "attach_btf_id %u is not a function\n", 19844 btf_id); 19845 return -EINVAL; 19846 } 19847 t = btf_type_by_id(btf, t->type); 19848 if (!btf_type_is_func_proto(t)) 19849 return -EINVAL; 19850 ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel); 19851 if (ret) 19852 return ret; 19853 break; 19854 default: 19855 if (!prog_extension) 19856 return -EINVAL; 19857 fallthrough; 19858 case BPF_MODIFY_RETURN: 19859 case BPF_LSM_MAC: 19860 case BPF_LSM_CGROUP: 19861 case BPF_TRACE_FENTRY: 19862 case BPF_TRACE_FEXIT: 19863 if (!btf_type_is_func(t)) { 19864 bpf_log(log, "attach_btf_id %u is not a function\n", 19865 btf_id); 19866 return -EINVAL; 19867 } 19868 if (prog_extension && 19869 btf_check_type_match(log, prog, btf, t)) 19870 return -EINVAL; 19871 t = btf_type_by_id(btf, t->type); 19872 if (!btf_type_is_func_proto(t)) 19873 return -EINVAL; 19874 19875 if ((prog->aux->saved_dst_prog_type || prog->aux->saved_dst_attach_type) && 19876 (!tgt_prog || prog->aux->saved_dst_prog_type != tgt_prog->type || 19877 prog->aux->saved_dst_attach_type != tgt_prog->expected_attach_type)) 19878 return -EINVAL; 19879 19880 if (tgt_prog && conservative) 19881 t = NULL; 19882 19883 ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel); 19884 if (ret < 0) 19885 return ret; 19886 19887 if (tgt_prog) { 19888 if (subprog == 0) 19889 addr = (long) tgt_prog->bpf_func; 19890 else 19891 addr = (long) tgt_prog->aux->func[subprog]->bpf_func; 19892 } else { 19893 if (btf_is_module(btf)) { 19894 mod = btf_try_get_module(btf); 19895 if (mod) 19896 addr = find_kallsyms_symbol_value(mod, tname); 19897 else 19898 addr = 0; 19899 } else { 19900 addr = kallsyms_lookup_name(tname); 19901 } 19902 if (!addr) { 19903 module_put(mod); 19904 bpf_log(log, 19905 "The address of function %s cannot be found\n", 19906 tname); 19907 return -ENOENT; 19908 } 19909 } 19910 19911 if (prog->aux->sleepable) { 19912 ret = -EINVAL; 19913 switch (prog->type) { 19914 case BPF_PROG_TYPE_TRACING: 19915 19916 /* fentry/fexit/fmod_ret progs can be sleepable if they are 19917 * attached to ALLOW_ERROR_INJECTION and are not in denylist. 19918 */ 19919 if (!check_non_sleepable_error_inject(btf_id) && 19920 within_error_injection_list(addr)) 19921 ret = 0; 19922 /* fentry/fexit/fmod_ret progs can also be sleepable if they are 19923 * in the fmodret id set with the KF_SLEEPABLE flag. 19924 */ 19925 else { 19926 u32 *flags = btf_kfunc_is_modify_return(btf, btf_id, 19927 prog); 19928 19929 if (flags && (*flags & KF_SLEEPABLE)) 19930 ret = 0; 19931 } 19932 break; 19933 case BPF_PROG_TYPE_LSM: 19934 /* LSM progs check that they are attached to bpf_lsm_*() funcs. 19935 * Only some of them are sleepable. 19936 */ 19937 if (bpf_lsm_is_sleepable_hook(btf_id)) 19938 ret = 0; 19939 break; 19940 default: 19941 break; 19942 } 19943 if (ret) { 19944 module_put(mod); 19945 bpf_log(log, "%s is not sleepable\n", tname); 19946 return ret; 19947 } 19948 } else if (prog->expected_attach_type == BPF_MODIFY_RETURN) { 19949 if (tgt_prog) { 19950 module_put(mod); 19951 bpf_log(log, "can't modify return codes of BPF programs\n"); 19952 return -EINVAL; 19953 } 19954 ret = -EINVAL; 19955 if (btf_kfunc_is_modify_return(btf, btf_id, prog) || 19956 !check_attach_modify_return(addr, tname)) 19957 ret = 0; 19958 if (ret) { 19959 module_put(mod); 19960 bpf_log(log, "%s() is not modifiable\n", tname); 19961 return ret; 19962 } 19963 } 19964 19965 break; 19966 } 19967 tgt_info->tgt_addr = addr; 19968 tgt_info->tgt_name = tname; 19969 tgt_info->tgt_type = t; 19970 tgt_info->tgt_mod = mod; 19971 return 0; 19972 } 19973 19974 BTF_SET_START(btf_id_deny) 19975 BTF_ID_UNUSED 19976 #ifdef CONFIG_SMP 19977 BTF_ID(func, migrate_disable) 19978 BTF_ID(func, migrate_enable) 19979 #endif 19980 #if !defined CONFIG_PREEMPT_RCU && !defined CONFIG_TINY_RCU 19981 BTF_ID(func, rcu_read_unlock_strict) 19982 #endif 19983 #if defined(CONFIG_DEBUG_PREEMPT) || defined(CONFIG_TRACE_PREEMPT_TOGGLE) 19984 BTF_ID(func, preempt_count_add) 19985 BTF_ID(func, preempt_count_sub) 19986 #endif 19987 #ifdef CONFIG_PREEMPT_RCU 19988 BTF_ID(func, __rcu_read_lock) 19989 BTF_ID(func, __rcu_read_unlock) 19990 #endif 19991 BTF_SET_END(btf_id_deny) 19992 19993 static bool can_be_sleepable(struct bpf_prog *prog) 19994 { 19995 if (prog->type == BPF_PROG_TYPE_TRACING) { 19996 switch (prog->expected_attach_type) { 19997 case BPF_TRACE_FENTRY: 19998 case BPF_TRACE_FEXIT: 19999 case BPF_MODIFY_RETURN: 20000 case BPF_TRACE_ITER: 20001 return true; 20002 default: 20003 return false; 20004 } 20005 } 20006 return prog->type == BPF_PROG_TYPE_LSM || 20007 prog->type == BPF_PROG_TYPE_KPROBE /* only for uprobes */ || 20008 prog->type == BPF_PROG_TYPE_STRUCT_OPS; 20009 } 20010 20011 static int check_attach_btf_id(struct bpf_verifier_env *env) 20012 { 20013 struct bpf_prog *prog = env->prog; 20014 struct bpf_prog *tgt_prog = prog->aux->dst_prog; 20015 struct bpf_attach_target_info tgt_info = {}; 20016 u32 btf_id = prog->aux->attach_btf_id; 20017 struct bpf_trampoline *tr; 20018 int ret; 20019 u64 key; 20020 20021 if (prog->type == BPF_PROG_TYPE_SYSCALL) { 20022 if (prog->aux->sleepable) 20023 /* attach_btf_id checked to be zero already */ 20024 return 0; 20025 verbose(env, "Syscall programs can only be sleepable\n"); 20026 return -EINVAL; 20027 } 20028 20029 if (prog->aux->sleepable && !can_be_sleepable(prog)) { 20030 verbose(env, "Only fentry/fexit/fmod_ret, lsm, iter, uprobe, and struct_ops programs can be sleepable\n"); 20031 return -EINVAL; 20032 } 20033 20034 if (prog->type == BPF_PROG_TYPE_STRUCT_OPS) 20035 return check_struct_ops_btf_id(env); 20036 20037 if (prog->type != BPF_PROG_TYPE_TRACING && 20038 prog->type != BPF_PROG_TYPE_LSM && 20039 prog->type != BPF_PROG_TYPE_EXT) 20040 return 0; 20041 20042 ret = bpf_check_attach_target(&env->log, prog, tgt_prog, btf_id, &tgt_info); 20043 if (ret) 20044 return ret; 20045 20046 if (tgt_prog && prog->type == BPF_PROG_TYPE_EXT) { 20047 /* to make freplace equivalent to their targets, they need to 20048 * inherit env->ops and expected_attach_type for the rest of the 20049 * verification 20050 */ 20051 env->ops = bpf_verifier_ops[tgt_prog->type]; 20052 prog->expected_attach_type = tgt_prog->expected_attach_type; 20053 } 20054 20055 /* store info about the attachment target that will be used later */ 20056 prog->aux->attach_func_proto = tgt_info.tgt_type; 20057 prog->aux->attach_func_name = tgt_info.tgt_name; 20058 prog->aux->mod = tgt_info.tgt_mod; 20059 20060 if (tgt_prog) { 20061 prog->aux->saved_dst_prog_type = tgt_prog->type; 20062 prog->aux->saved_dst_attach_type = tgt_prog->expected_attach_type; 20063 } 20064 20065 if (prog->expected_attach_type == BPF_TRACE_RAW_TP) { 20066 prog->aux->attach_btf_trace = true; 20067 return 0; 20068 } else if (prog->expected_attach_type == BPF_TRACE_ITER) { 20069 if (!bpf_iter_prog_supported(prog)) 20070 return -EINVAL; 20071 return 0; 20072 } 20073 20074 if (prog->type == BPF_PROG_TYPE_LSM) { 20075 ret = bpf_lsm_verify_prog(&env->log, prog); 20076 if (ret < 0) 20077 return ret; 20078 } else if (prog->type == BPF_PROG_TYPE_TRACING && 20079 btf_id_set_contains(&btf_id_deny, btf_id)) { 20080 return -EINVAL; 20081 } 20082 20083 key = bpf_trampoline_compute_key(tgt_prog, prog->aux->attach_btf, btf_id); 20084 tr = bpf_trampoline_get(key, &tgt_info); 20085 if (!tr) 20086 return -ENOMEM; 20087 20088 if (tgt_prog && tgt_prog->aux->tail_call_reachable) 20089 tr->flags = BPF_TRAMP_F_TAIL_CALL_CTX; 20090 20091 prog->aux->dst_trampoline = tr; 20092 return 0; 20093 } 20094 20095 struct btf *bpf_get_btf_vmlinux(void) 20096 { 20097 if (!btf_vmlinux && IS_ENABLED(CONFIG_DEBUG_INFO_BTF)) { 20098 mutex_lock(&bpf_verifier_lock); 20099 if (!btf_vmlinux) 20100 btf_vmlinux = btf_parse_vmlinux(); 20101 mutex_unlock(&bpf_verifier_lock); 20102 } 20103 return btf_vmlinux; 20104 } 20105 20106 int bpf_check(struct bpf_prog **prog, union bpf_attr *attr, bpfptr_t uattr, __u32 uattr_size) 20107 { 20108 u64 start_time = ktime_get_ns(); 20109 struct bpf_verifier_env *env; 20110 int i, len, ret = -EINVAL, err; 20111 u32 log_true_size; 20112 bool is_priv; 20113 20114 /* no program is valid */ 20115 if (ARRAY_SIZE(bpf_verifier_ops) == 0) 20116 return -EINVAL; 20117 20118 /* 'struct bpf_verifier_env' can be global, but since it's not small, 20119 * allocate/free it every time bpf_check() is called 20120 */ 20121 env = kzalloc(sizeof(struct bpf_verifier_env), GFP_KERNEL); 20122 if (!env) 20123 return -ENOMEM; 20124 20125 env->bt.env = env; 20126 20127 len = (*prog)->len; 20128 env->insn_aux_data = 20129 vzalloc(array_size(sizeof(struct bpf_insn_aux_data), len)); 20130 ret = -ENOMEM; 20131 if (!env->insn_aux_data) 20132 goto err_free_env; 20133 for (i = 0; i < len; i++) 20134 env->insn_aux_data[i].orig_idx = i; 20135 env->prog = *prog; 20136 env->ops = bpf_verifier_ops[env->prog->type]; 20137 env->fd_array = make_bpfptr(attr->fd_array, uattr.is_kernel); 20138 is_priv = bpf_capable(); 20139 20140 bpf_get_btf_vmlinux(); 20141 20142 /* grab the mutex to protect few globals used by verifier */ 20143 if (!is_priv) 20144 mutex_lock(&bpf_verifier_lock); 20145 20146 /* user could have requested verbose verifier output 20147 * and supplied buffer to store the verification trace 20148 */ 20149 ret = bpf_vlog_init(&env->log, attr->log_level, 20150 (char __user *) (unsigned long) attr->log_buf, 20151 attr->log_size); 20152 if (ret) 20153 goto err_unlock; 20154 20155 mark_verifier_state_clean(env); 20156 20157 if (IS_ERR(btf_vmlinux)) { 20158 /* Either gcc or pahole or kernel are broken. */ 20159 verbose(env, "in-kernel BTF is malformed\n"); 20160 ret = PTR_ERR(btf_vmlinux); 20161 goto skip_full_check; 20162 } 20163 20164 env->strict_alignment = !!(attr->prog_flags & BPF_F_STRICT_ALIGNMENT); 20165 if (!IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS)) 20166 env->strict_alignment = true; 20167 if (attr->prog_flags & BPF_F_ANY_ALIGNMENT) 20168 env->strict_alignment = false; 20169 20170 env->allow_ptr_leaks = bpf_allow_ptr_leaks(); 20171 env->allow_uninit_stack = bpf_allow_uninit_stack(); 20172 env->bypass_spec_v1 = bpf_bypass_spec_v1(); 20173 env->bypass_spec_v4 = bpf_bypass_spec_v4(); 20174 env->bpf_capable = bpf_capable(); 20175 20176 if (is_priv) 20177 env->test_state_freq = attr->prog_flags & BPF_F_TEST_STATE_FREQ; 20178 20179 env->explored_states = kvcalloc(state_htab_size(env), 20180 sizeof(struct bpf_verifier_state_list *), 20181 GFP_USER); 20182 ret = -ENOMEM; 20183 if (!env->explored_states) 20184 goto skip_full_check; 20185 20186 ret = check_btf_info_early(env, attr, uattr); 20187 if (ret < 0) 20188 goto skip_full_check; 20189 20190 ret = add_subprog_and_kfunc(env); 20191 if (ret < 0) 20192 goto skip_full_check; 20193 20194 ret = check_subprogs(env); 20195 if (ret < 0) 20196 goto skip_full_check; 20197 20198 ret = check_btf_info(env, attr, uattr); 20199 if (ret < 0) 20200 goto skip_full_check; 20201 20202 ret = check_attach_btf_id(env); 20203 if (ret) 20204 goto skip_full_check; 20205 20206 ret = resolve_pseudo_ldimm64(env); 20207 if (ret < 0) 20208 goto skip_full_check; 20209 20210 if (bpf_prog_is_offloaded(env->prog->aux)) { 20211 ret = bpf_prog_offload_verifier_prep(env->prog); 20212 if (ret) 20213 goto skip_full_check; 20214 } 20215 20216 ret = check_cfg(env); 20217 if (ret < 0) 20218 goto skip_full_check; 20219 20220 ret = do_check_subprogs(env); 20221 ret = ret ?: do_check_main(env); 20222 20223 if (ret == 0 && bpf_prog_is_offloaded(env->prog->aux)) 20224 ret = bpf_prog_offload_finalize(env); 20225 20226 skip_full_check: 20227 kvfree(env->explored_states); 20228 20229 if (ret == 0) 20230 ret = check_max_stack_depth(env); 20231 20232 /* instruction rewrites happen after this point */ 20233 if (ret == 0) 20234 ret = optimize_bpf_loop(env); 20235 20236 if (is_priv) { 20237 if (ret == 0) 20238 opt_hard_wire_dead_code_branches(env); 20239 if (ret == 0) 20240 ret = opt_remove_dead_code(env); 20241 if (ret == 0) 20242 ret = opt_remove_nops(env); 20243 } else { 20244 if (ret == 0) 20245 sanitize_dead_code(env); 20246 } 20247 20248 if (ret == 0) 20249 /* program is valid, convert *(u32*)(ctx + off) accesses */ 20250 ret = convert_ctx_accesses(env); 20251 20252 if (ret == 0) 20253 ret = do_misc_fixups(env); 20254 20255 /* do 32-bit optimization after insn patching has done so those patched 20256 * insns could be handled correctly. 20257 */ 20258 if (ret == 0 && !bpf_prog_is_offloaded(env->prog->aux)) { 20259 ret = opt_subreg_zext_lo32_rnd_hi32(env, attr); 20260 env->prog->aux->verifier_zext = bpf_jit_needs_zext() ? !ret 20261 : false; 20262 } 20263 20264 if (ret == 0) 20265 ret = fixup_call_args(env); 20266 20267 env->verification_time = ktime_get_ns() - start_time; 20268 print_verification_stats(env); 20269 env->prog->aux->verified_insns = env->insn_processed; 20270 20271 /* preserve original error even if log finalization is successful */ 20272 err = bpf_vlog_finalize(&env->log, &log_true_size); 20273 if (err) 20274 ret = err; 20275 20276 if (uattr_size >= offsetofend(union bpf_attr, log_true_size) && 20277 copy_to_bpfptr_offset(uattr, offsetof(union bpf_attr, log_true_size), 20278 &log_true_size, sizeof(log_true_size))) { 20279 ret = -EFAULT; 20280 goto err_release_maps; 20281 } 20282 20283 if (ret) 20284 goto err_release_maps; 20285 20286 if (env->used_map_cnt) { 20287 /* if program passed verifier, update used_maps in bpf_prog_info */ 20288 env->prog->aux->used_maps = kmalloc_array(env->used_map_cnt, 20289 sizeof(env->used_maps[0]), 20290 GFP_KERNEL); 20291 20292 if (!env->prog->aux->used_maps) { 20293 ret = -ENOMEM; 20294 goto err_release_maps; 20295 } 20296 20297 memcpy(env->prog->aux->used_maps, env->used_maps, 20298 sizeof(env->used_maps[0]) * env->used_map_cnt); 20299 env->prog->aux->used_map_cnt = env->used_map_cnt; 20300 } 20301 if (env->used_btf_cnt) { 20302 /* if program passed verifier, update used_btfs in bpf_prog_aux */ 20303 env->prog->aux->used_btfs = kmalloc_array(env->used_btf_cnt, 20304 sizeof(env->used_btfs[0]), 20305 GFP_KERNEL); 20306 if (!env->prog->aux->used_btfs) { 20307 ret = -ENOMEM; 20308 goto err_release_maps; 20309 } 20310 20311 memcpy(env->prog->aux->used_btfs, env->used_btfs, 20312 sizeof(env->used_btfs[0]) * env->used_btf_cnt); 20313 env->prog->aux->used_btf_cnt = env->used_btf_cnt; 20314 } 20315 if (env->used_map_cnt || env->used_btf_cnt) { 20316 /* program is valid. Convert pseudo bpf_ld_imm64 into generic 20317 * bpf_ld_imm64 instructions 20318 */ 20319 convert_pseudo_ld_imm64(env); 20320 } 20321 20322 adjust_btf_func(env); 20323 20324 err_release_maps: 20325 if (!env->prog->aux->used_maps) 20326 /* if we didn't copy map pointers into bpf_prog_info, release 20327 * them now. Otherwise free_used_maps() will release them. 20328 */ 20329 release_maps(env); 20330 if (!env->prog->aux->used_btfs) 20331 release_btfs(env); 20332 20333 /* extension progs temporarily inherit the attach_type of their targets 20334 for verification purposes, so set it back to zero before returning 20335 */ 20336 if (env->prog->type == BPF_PROG_TYPE_EXT) 20337 env->prog->expected_attach_type = 0; 20338 20339 *prog = env->prog; 20340 err_unlock: 20341 if (!is_priv) 20342 mutex_unlock(&bpf_verifier_lock); 20343 vfree(env->insn_aux_data); 20344 err_free_env: 20345 kfree(env); 20346 return ret; 20347 } 20348