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 bt_clear_reg(bt, i); 4136 if (reg->type == SCALAR_VALUE) 4137 reg->precise = true; 4138 } 4139 return 0; 4140 } 4141 4142 verbose(env, "BUG backtracking func entry subprog %d reg_mask %x stack_mask %llx\n", 4143 st->frame[0]->subprogno, bt_reg_mask(bt), bt_stack_mask(bt)); 4144 WARN_ONCE(1, "verifier backtracking bug"); 4145 return -EFAULT; 4146 } 4147 4148 for (i = last_idx;;) { 4149 if (skip_first) { 4150 err = 0; 4151 skip_first = false; 4152 } else { 4153 err = backtrack_insn(env, i, subseq_idx, bt); 4154 } 4155 if (err == -ENOTSUPP) { 4156 mark_all_scalars_precise(env, env->cur_state); 4157 bt_reset(bt); 4158 return 0; 4159 } else if (err) { 4160 return err; 4161 } 4162 if (bt_empty(bt)) 4163 /* Found assignment(s) into tracked register in this state. 4164 * Since this state is already marked, just return. 4165 * Nothing to be tracked further in the parent state. 4166 */ 4167 return 0; 4168 if (i == first_idx) 4169 break; 4170 subseq_idx = i; 4171 i = get_prev_insn_idx(st, i, &history); 4172 if (i >= env->prog->len) { 4173 /* This can happen if backtracking reached insn 0 4174 * and there are still reg_mask or stack_mask 4175 * to backtrack. 4176 * It means the backtracking missed the spot where 4177 * particular register was initialized with a constant. 4178 */ 4179 verbose(env, "BUG backtracking idx %d\n", i); 4180 WARN_ONCE(1, "verifier backtracking bug"); 4181 return -EFAULT; 4182 } 4183 } 4184 st = st->parent; 4185 if (!st) 4186 break; 4187 4188 for (fr = bt->frame; fr >= 0; fr--) { 4189 func = st->frame[fr]; 4190 bitmap_from_u64(mask, bt_frame_reg_mask(bt, fr)); 4191 for_each_set_bit(i, mask, 32) { 4192 reg = &func->regs[i]; 4193 if (reg->type != SCALAR_VALUE) { 4194 bt_clear_frame_reg(bt, fr, i); 4195 continue; 4196 } 4197 if (reg->precise) 4198 bt_clear_frame_reg(bt, fr, i); 4199 else 4200 reg->precise = true; 4201 } 4202 4203 bitmap_from_u64(mask, bt_frame_stack_mask(bt, fr)); 4204 for_each_set_bit(i, mask, 64) { 4205 if (i >= func->allocated_stack / BPF_REG_SIZE) { 4206 /* the sequence of instructions: 4207 * 2: (bf) r3 = r10 4208 * 3: (7b) *(u64 *)(r3 -8) = r0 4209 * 4: (79) r4 = *(u64 *)(r10 -8) 4210 * doesn't contain jmps. It's backtracked 4211 * as a single block. 4212 * During backtracking insn 3 is not recognized as 4213 * stack access, so at the end of backtracking 4214 * stack slot fp-8 is still marked in stack_mask. 4215 * However the parent state may not have accessed 4216 * fp-8 and it's "unallocated" stack space. 4217 * In such case fallback to conservative. 4218 */ 4219 mark_all_scalars_precise(env, env->cur_state); 4220 bt_reset(bt); 4221 return 0; 4222 } 4223 4224 if (!is_spilled_scalar_reg(&func->stack[i])) { 4225 bt_clear_frame_slot(bt, fr, i); 4226 continue; 4227 } 4228 reg = &func->stack[i].spilled_ptr; 4229 if (reg->precise) 4230 bt_clear_frame_slot(bt, fr, i); 4231 else 4232 reg->precise = true; 4233 } 4234 if (env->log.level & BPF_LOG_LEVEL2) { 4235 fmt_reg_mask(env->tmp_str_buf, TMP_STR_BUF_LEN, 4236 bt_frame_reg_mask(bt, fr)); 4237 verbose(env, "mark_precise: frame%d: parent state regs=%s ", 4238 fr, env->tmp_str_buf); 4239 fmt_stack_mask(env->tmp_str_buf, TMP_STR_BUF_LEN, 4240 bt_frame_stack_mask(bt, fr)); 4241 verbose(env, "stack=%s: ", env->tmp_str_buf); 4242 print_verifier_state(env, func, true); 4243 } 4244 } 4245 4246 if (bt_empty(bt)) 4247 return 0; 4248 4249 subseq_idx = first_idx; 4250 last_idx = st->last_insn_idx; 4251 first_idx = st->first_insn_idx; 4252 } 4253 4254 /* if we still have requested precise regs or slots, we missed 4255 * something (e.g., stack access through non-r10 register), so 4256 * fallback to marking all precise 4257 */ 4258 if (!bt_empty(bt)) { 4259 mark_all_scalars_precise(env, env->cur_state); 4260 bt_reset(bt); 4261 } 4262 4263 return 0; 4264 } 4265 4266 int mark_chain_precision(struct bpf_verifier_env *env, int regno) 4267 { 4268 return __mark_chain_precision(env, regno); 4269 } 4270 4271 /* mark_chain_precision_batch() assumes that env->bt is set in the caller to 4272 * desired reg and stack masks across all relevant frames 4273 */ 4274 static int mark_chain_precision_batch(struct bpf_verifier_env *env) 4275 { 4276 return __mark_chain_precision(env, -1); 4277 } 4278 4279 static bool is_spillable_regtype(enum bpf_reg_type type) 4280 { 4281 switch (base_type(type)) { 4282 case PTR_TO_MAP_VALUE: 4283 case PTR_TO_STACK: 4284 case PTR_TO_CTX: 4285 case PTR_TO_PACKET: 4286 case PTR_TO_PACKET_META: 4287 case PTR_TO_PACKET_END: 4288 case PTR_TO_FLOW_KEYS: 4289 case CONST_PTR_TO_MAP: 4290 case PTR_TO_SOCKET: 4291 case PTR_TO_SOCK_COMMON: 4292 case PTR_TO_TCP_SOCK: 4293 case PTR_TO_XDP_SOCK: 4294 case PTR_TO_BTF_ID: 4295 case PTR_TO_BUF: 4296 case PTR_TO_MEM: 4297 case PTR_TO_FUNC: 4298 case PTR_TO_MAP_KEY: 4299 return true; 4300 default: 4301 return false; 4302 } 4303 } 4304 4305 /* Does this register contain a constant zero? */ 4306 static bool register_is_null(struct bpf_reg_state *reg) 4307 { 4308 return reg->type == SCALAR_VALUE && tnum_equals_const(reg->var_off, 0); 4309 } 4310 4311 static bool register_is_const(struct bpf_reg_state *reg) 4312 { 4313 return reg->type == SCALAR_VALUE && tnum_is_const(reg->var_off); 4314 } 4315 4316 static bool __is_scalar_unbounded(struct bpf_reg_state *reg) 4317 { 4318 return tnum_is_unknown(reg->var_off) && 4319 reg->smin_value == S64_MIN && reg->smax_value == S64_MAX && 4320 reg->umin_value == 0 && reg->umax_value == U64_MAX && 4321 reg->s32_min_value == S32_MIN && reg->s32_max_value == S32_MAX && 4322 reg->u32_min_value == 0 && reg->u32_max_value == U32_MAX; 4323 } 4324 4325 static bool register_is_bounded(struct bpf_reg_state *reg) 4326 { 4327 return reg->type == SCALAR_VALUE && !__is_scalar_unbounded(reg); 4328 } 4329 4330 static bool __is_pointer_value(bool allow_ptr_leaks, 4331 const struct bpf_reg_state *reg) 4332 { 4333 if (allow_ptr_leaks) 4334 return false; 4335 4336 return reg->type != SCALAR_VALUE; 4337 } 4338 4339 /* Copy src state preserving dst->parent and dst->live fields */ 4340 static void copy_register_state(struct bpf_reg_state *dst, const struct bpf_reg_state *src) 4341 { 4342 struct bpf_reg_state *parent = dst->parent; 4343 enum bpf_reg_liveness live = dst->live; 4344 4345 *dst = *src; 4346 dst->parent = parent; 4347 dst->live = live; 4348 } 4349 4350 static void save_register_state(struct bpf_func_state *state, 4351 int spi, struct bpf_reg_state *reg, 4352 int size) 4353 { 4354 int i; 4355 4356 copy_register_state(&state->stack[spi].spilled_ptr, reg); 4357 if (size == BPF_REG_SIZE) 4358 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN; 4359 4360 for (i = BPF_REG_SIZE; i > BPF_REG_SIZE - size; i--) 4361 state->stack[spi].slot_type[i - 1] = STACK_SPILL; 4362 4363 /* size < 8 bytes spill */ 4364 for (; i; i--) 4365 scrub_spilled_slot(&state->stack[spi].slot_type[i - 1]); 4366 } 4367 4368 static bool is_bpf_st_mem(struct bpf_insn *insn) 4369 { 4370 return BPF_CLASS(insn->code) == BPF_ST && BPF_MODE(insn->code) == BPF_MEM; 4371 } 4372 4373 /* check_stack_{read,write}_fixed_off functions track spill/fill of registers, 4374 * stack boundary and alignment are checked in check_mem_access() 4375 */ 4376 static int check_stack_write_fixed_off(struct bpf_verifier_env *env, 4377 /* stack frame we're writing to */ 4378 struct bpf_func_state *state, 4379 int off, int size, int value_regno, 4380 int insn_idx) 4381 { 4382 struct bpf_func_state *cur; /* state of the current function */ 4383 int i, slot = -off - 1, spi = slot / BPF_REG_SIZE, err; 4384 struct bpf_insn *insn = &env->prog->insnsi[insn_idx]; 4385 struct bpf_reg_state *reg = NULL; 4386 u32 dst_reg = insn->dst_reg; 4387 4388 err = grow_stack_state(state, round_up(slot + 1, BPF_REG_SIZE)); 4389 if (err) 4390 return err; 4391 /* caller checked that off % size == 0 and -MAX_BPF_STACK <= off < 0, 4392 * so it's aligned access and [off, off + size) are within stack limits 4393 */ 4394 if (!env->allow_ptr_leaks && 4395 state->stack[spi].slot_type[0] == STACK_SPILL && 4396 size != BPF_REG_SIZE) { 4397 verbose(env, "attempt to corrupt spilled pointer on stack\n"); 4398 return -EACCES; 4399 } 4400 4401 cur = env->cur_state->frame[env->cur_state->curframe]; 4402 if (value_regno >= 0) 4403 reg = &cur->regs[value_regno]; 4404 if (!env->bypass_spec_v4) { 4405 bool sanitize = reg && is_spillable_regtype(reg->type); 4406 4407 for (i = 0; i < size; i++) { 4408 u8 type = state->stack[spi].slot_type[i]; 4409 4410 if (type != STACK_MISC && type != STACK_ZERO) { 4411 sanitize = true; 4412 break; 4413 } 4414 } 4415 4416 if (sanitize) 4417 env->insn_aux_data[insn_idx].sanitize_stack_spill = true; 4418 } 4419 4420 err = destroy_if_dynptr_stack_slot(env, state, spi); 4421 if (err) 4422 return err; 4423 4424 mark_stack_slot_scratched(env, spi); 4425 if (reg && !(off % BPF_REG_SIZE) && register_is_bounded(reg) && 4426 !register_is_null(reg) && env->bpf_capable) { 4427 if (dst_reg != BPF_REG_FP) { 4428 /* The backtracking logic can only recognize explicit 4429 * stack slot address like [fp - 8]. Other spill of 4430 * scalar via different register has to be conservative. 4431 * Backtrack from here and mark all registers as precise 4432 * that contributed into 'reg' being a constant. 4433 */ 4434 err = mark_chain_precision(env, value_regno); 4435 if (err) 4436 return err; 4437 } 4438 save_register_state(state, spi, reg, size); 4439 /* Break the relation on a narrowing spill. */ 4440 if (fls64(reg->umax_value) > BITS_PER_BYTE * size) 4441 state->stack[spi].spilled_ptr.id = 0; 4442 } else if (!reg && !(off % BPF_REG_SIZE) && is_bpf_st_mem(insn) && 4443 insn->imm != 0 && env->bpf_capable) { 4444 struct bpf_reg_state fake_reg = {}; 4445 4446 __mark_reg_known(&fake_reg, (u32)insn->imm); 4447 fake_reg.type = SCALAR_VALUE; 4448 save_register_state(state, spi, &fake_reg, size); 4449 } else if (reg && is_spillable_regtype(reg->type)) { 4450 /* register containing pointer is being spilled into stack */ 4451 if (size != BPF_REG_SIZE) { 4452 verbose_linfo(env, insn_idx, "; "); 4453 verbose(env, "invalid size of register spill\n"); 4454 return -EACCES; 4455 } 4456 if (state != cur && reg->type == PTR_TO_STACK) { 4457 verbose(env, "cannot spill pointers to stack into stack frame of the caller\n"); 4458 return -EINVAL; 4459 } 4460 save_register_state(state, spi, reg, size); 4461 } else { 4462 u8 type = STACK_MISC; 4463 4464 /* regular write of data into stack destroys any spilled ptr */ 4465 state->stack[spi].spilled_ptr.type = NOT_INIT; 4466 /* Mark slots as STACK_MISC if they belonged to spilled ptr/dynptr/iter. */ 4467 if (is_stack_slot_special(&state->stack[spi])) 4468 for (i = 0; i < BPF_REG_SIZE; i++) 4469 scrub_spilled_slot(&state->stack[spi].slot_type[i]); 4470 4471 /* only mark the slot as written if all 8 bytes were written 4472 * otherwise read propagation may incorrectly stop too soon 4473 * when stack slots are partially written. 4474 * This heuristic means that read propagation will be 4475 * conservative, since it will add reg_live_read marks 4476 * to stack slots all the way to first state when programs 4477 * writes+reads less than 8 bytes 4478 */ 4479 if (size == BPF_REG_SIZE) 4480 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN; 4481 4482 /* when we zero initialize stack slots mark them as such */ 4483 if ((reg && register_is_null(reg)) || 4484 (!reg && is_bpf_st_mem(insn) && insn->imm == 0)) { 4485 /* backtracking doesn't work for STACK_ZERO yet. */ 4486 err = mark_chain_precision(env, value_regno); 4487 if (err) 4488 return err; 4489 type = STACK_ZERO; 4490 } 4491 4492 /* Mark slots affected by this stack write. */ 4493 for (i = 0; i < size; i++) 4494 state->stack[spi].slot_type[(slot - i) % BPF_REG_SIZE] = 4495 type; 4496 } 4497 return 0; 4498 } 4499 4500 /* Write the stack: 'stack[ptr_regno + off] = value_regno'. 'ptr_regno' is 4501 * known to contain a variable offset. 4502 * This function checks whether the write is permitted and conservatively 4503 * tracks the effects of the write, considering that each stack slot in the 4504 * dynamic range is potentially written to. 4505 * 4506 * 'off' includes 'regno->off'. 4507 * 'value_regno' can be -1, meaning that an unknown value is being written to 4508 * the stack. 4509 * 4510 * Spilled pointers in range are not marked as written because we don't know 4511 * what's going to be actually written. This means that read propagation for 4512 * future reads cannot be terminated by this write. 4513 * 4514 * For privileged programs, uninitialized stack slots are considered 4515 * initialized by this write (even though we don't know exactly what offsets 4516 * are going to be written to). The idea is that we don't want the verifier to 4517 * reject future reads that access slots written to through variable offsets. 4518 */ 4519 static int check_stack_write_var_off(struct bpf_verifier_env *env, 4520 /* func where register points to */ 4521 struct bpf_func_state *state, 4522 int ptr_regno, int off, int size, 4523 int value_regno, int insn_idx) 4524 { 4525 struct bpf_func_state *cur; /* state of the current function */ 4526 int min_off, max_off; 4527 int i, err; 4528 struct bpf_reg_state *ptr_reg = NULL, *value_reg = NULL; 4529 struct bpf_insn *insn = &env->prog->insnsi[insn_idx]; 4530 bool writing_zero = false; 4531 /* set if the fact that we're writing a zero is used to let any 4532 * stack slots remain STACK_ZERO 4533 */ 4534 bool zero_used = false; 4535 4536 cur = env->cur_state->frame[env->cur_state->curframe]; 4537 ptr_reg = &cur->regs[ptr_regno]; 4538 min_off = ptr_reg->smin_value + off; 4539 max_off = ptr_reg->smax_value + off + size; 4540 if (value_regno >= 0) 4541 value_reg = &cur->regs[value_regno]; 4542 if ((value_reg && register_is_null(value_reg)) || 4543 (!value_reg && is_bpf_st_mem(insn) && insn->imm == 0)) 4544 writing_zero = true; 4545 4546 err = grow_stack_state(state, round_up(-min_off, BPF_REG_SIZE)); 4547 if (err) 4548 return err; 4549 4550 for (i = min_off; i < max_off; i++) { 4551 int spi; 4552 4553 spi = __get_spi(i); 4554 err = destroy_if_dynptr_stack_slot(env, state, spi); 4555 if (err) 4556 return err; 4557 } 4558 4559 /* Variable offset writes destroy any spilled pointers in range. */ 4560 for (i = min_off; i < max_off; i++) { 4561 u8 new_type, *stype; 4562 int slot, spi; 4563 4564 slot = -i - 1; 4565 spi = slot / BPF_REG_SIZE; 4566 stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE]; 4567 mark_stack_slot_scratched(env, spi); 4568 4569 if (!env->allow_ptr_leaks && *stype != STACK_MISC && *stype != STACK_ZERO) { 4570 /* Reject the write if range we may write to has not 4571 * been initialized beforehand. If we didn't reject 4572 * here, the ptr status would be erased below (even 4573 * though not all slots are actually overwritten), 4574 * possibly opening the door to leaks. 4575 * 4576 * We do however catch STACK_INVALID case below, and 4577 * only allow reading possibly uninitialized memory 4578 * later for CAP_PERFMON, as the write may not happen to 4579 * that slot. 4580 */ 4581 verbose(env, "spilled ptr in range of var-offset stack write; insn %d, ptr off: %d", 4582 insn_idx, i); 4583 return -EINVAL; 4584 } 4585 4586 /* Erase all spilled pointers. */ 4587 state->stack[spi].spilled_ptr.type = NOT_INIT; 4588 4589 /* Update the slot type. */ 4590 new_type = STACK_MISC; 4591 if (writing_zero && *stype == STACK_ZERO) { 4592 new_type = STACK_ZERO; 4593 zero_used = true; 4594 } 4595 /* If the slot is STACK_INVALID, we check whether it's OK to 4596 * pretend that it will be initialized by this write. The slot 4597 * might not actually be written to, and so if we mark it as 4598 * initialized future reads might leak uninitialized memory. 4599 * For privileged programs, we will accept such reads to slots 4600 * that may or may not be written because, if we're reject 4601 * them, the error would be too confusing. 4602 */ 4603 if (*stype == STACK_INVALID && !env->allow_uninit_stack) { 4604 verbose(env, "uninit stack in range of var-offset write prohibited for !root; insn %d, off: %d", 4605 insn_idx, i); 4606 return -EINVAL; 4607 } 4608 *stype = new_type; 4609 } 4610 if (zero_used) { 4611 /* backtracking doesn't work for STACK_ZERO yet. */ 4612 err = mark_chain_precision(env, value_regno); 4613 if (err) 4614 return err; 4615 } 4616 return 0; 4617 } 4618 4619 /* When register 'dst_regno' is assigned some values from stack[min_off, 4620 * max_off), we set the register's type according to the types of the 4621 * respective stack slots. If all the stack values are known to be zeros, then 4622 * so is the destination reg. Otherwise, the register is considered to be 4623 * SCALAR. This function does not deal with register filling; the caller must 4624 * ensure that all spilled registers in the stack range have been marked as 4625 * read. 4626 */ 4627 static void mark_reg_stack_read(struct bpf_verifier_env *env, 4628 /* func where src register points to */ 4629 struct bpf_func_state *ptr_state, 4630 int min_off, int max_off, int dst_regno) 4631 { 4632 struct bpf_verifier_state *vstate = env->cur_state; 4633 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 4634 int i, slot, spi; 4635 u8 *stype; 4636 int zeros = 0; 4637 4638 for (i = min_off; i < max_off; i++) { 4639 slot = -i - 1; 4640 spi = slot / BPF_REG_SIZE; 4641 mark_stack_slot_scratched(env, spi); 4642 stype = ptr_state->stack[spi].slot_type; 4643 if (stype[slot % BPF_REG_SIZE] != STACK_ZERO) 4644 break; 4645 zeros++; 4646 } 4647 if (zeros == max_off - min_off) { 4648 /* any access_size read into register is zero extended, 4649 * so the whole register == const_zero 4650 */ 4651 __mark_reg_const_zero(&state->regs[dst_regno]); 4652 /* backtracking doesn't support STACK_ZERO yet, 4653 * so mark it precise here, so that later 4654 * backtracking can stop here. 4655 * Backtracking may not need this if this register 4656 * doesn't participate in pointer adjustment. 4657 * Forward propagation of precise flag is not 4658 * necessary either. This mark is only to stop 4659 * backtracking. Any register that contributed 4660 * to const 0 was marked precise before spill. 4661 */ 4662 state->regs[dst_regno].precise = true; 4663 } else { 4664 /* have read misc data from the stack */ 4665 mark_reg_unknown(env, state->regs, dst_regno); 4666 } 4667 state->regs[dst_regno].live |= REG_LIVE_WRITTEN; 4668 } 4669 4670 /* Read the stack at 'off' and put the results into the register indicated by 4671 * 'dst_regno'. It handles reg filling if the addressed stack slot is a 4672 * spilled reg. 4673 * 4674 * 'dst_regno' can be -1, meaning that the read value is not going to a 4675 * register. 4676 * 4677 * The access is assumed to be within the current stack bounds. 4678 */ 4679 static int check_stack_read_fixed_off(struct bpf_verifier_env *env, 4680 /* func where src register points to */ 4681 struct bpf_func_state *reg_state, 4682 int off, int size, int dst_regno) 4683 { 4684 struct bpf_verifier_state *vstate = env->cur_state; 4685 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 4686 int i, slot = -off - 1, spi = slot / BPF_REG_SIZE; 4687 struct bpf_reg_state *reg; 4688 u8 *stype, type; 4689 4690 stype = reg_state->stack[spi].slot_type; 4691 reg = ®_state->stack[spi].spilled_ptr; 4692 4693 mark_stack_slot_scratched(env, spi); 4694 4695 if (is_spilled_reg(®_state->stack[spi])) { 4696 u8 spill_size = 1; 4697 4698 for (i = BPF_REG_SIZE - 1; i > 0 && stype[i - 1] == STACK_SPILL; i--) 4699 spill_size++; 4700 4701 if (size != BPF_REG_SIZE || spill_size != BPF_REG_SIZE) { 4702 if (reg->type != SCALAR_VALUE) { 4703 verbose_linfo(env, env->insn_idx, "; "); 4704 verbose(env, "invalid size of register fill\n"); 4705 return -EACCES; 4706 } 4707 4708 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64); 4709 if (dst_regno < 0) 4710 return 0; 4711 4712 if (!(off % BPF_REG_SIZE) && size == spill_size) { 4713 /* The earlier check_reg_arg() has decided the 4714 * subreg_def for this insn. Save it first. 4715 */ 4716 s32 subreg_def = state->regs[dst_regno].subreg_def; 4717 4718 copy_register_state(&state->regs[dst_regno], reg); 4719 state->regs[dst_regno].subreg_def = subreg_def; 4720 } else { 4721 for (i = 0; i < size; i++) { 4722 type = stype[(slot - i) % BPF_REG_SIZE]; 4723 if (type == STACK_SPILL) 4724 continue; 4725 if (type == STACK_MISC) 4726 continue; 4727 if (type == STACK_INVALID && env->allow_uninit_stack) 4728 continue; 4729 verbose(env, "invalid read from stack off %d+%d size %d\n", 4730 off, i, size); 4731 return -EACCES; 4732 } 4733 mark_reg_unknown(env, state->regs, dst_regno); 4734 } 4735 state->regs[dst_regno].live |= REG_LIVE_WRITTEN; 4736 return 0; 4737 } 4738 4739 if (dst_regno >= 0) { 4740 /* restore register state from stack */ 4741 copy_register_state(&state->regs[dst_regno], reg); 4742 /* mark reg as written since spilled pointer state likely 4743 * has its liveness marks cleared by is_state_visited() 4744 * which resets stack/reg liveness for state transitions 4745 */ 4746 state->regs[dst_regno].live |= REG_LIVE_WRITTEN; 4747 } else if (__is_pointer_value(env->allow_ptr_leaks, reg)) { 4748 /* If dst_regno==-1, the caller is asking us whether 4749 * it is acceptable to use this value as a SCALAR_VALUE 4750 * (e.g. for XADD). 4751 * We must not allow unprivileged callers to do that 4752 * with spilled pointers. 4753 */ 4754 verbose(env, "leaking pointer from stack off %d\n", 4755 off); 4756 return -EACCES; 4757 } 4758 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64); 4759 } else { 4760 for (i = 0; i < size; i++) { 4761 type = stype[(slot - i) % BPF_REG_SIZE]; 4762 if (type == STACK_MISC) 4763 continue; 4764 if (type == STACK_ZERO) 4765 continue; 4766 if (type == STACK_INVALID && env->allow_uninit_stack) 4767 continue; 4768 verbose(env, "invalid read from stack off %d+%d size %d\n", 4769 off, i, size); 4770 return -EACCES; 4771 } 4772 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64); 4773 if (dst_regno >= 0) 4774 mark_reg_stack_read(env, reg_state, off, off + size, dst_regno); 4775 } 4776 return 0; 4777 } 4778 4779 enum bpf_access_src { 4780 ACCESS_DIRECT = 1, /* the access is performed by an instruction */ 4781 ACCESS_HELPER = 2, /* the access is performed by a helper */ 4782 }; 4783 4784 static int check_stack_range_initialized(struct bpf_verifier_env *env, 4785 int regno, int off, int access_size, 4786 bool zero_size_allowed, 4787 enum bpf_access_src type, 4788 struct bpf_call_arg_meta *meta); 4789 4790 static struct bpf_reg_state *reg_state(struct bpf_verifier_env *env, int regno) 4791 { 4792 return cur_regs(env) + regno; 4793 } 4794 4795 /* Read the stack at 'ptr_regno + off' and put the result into the register 4796 * 'dst_regno'. 4797 * 'off' includes the pointer register's fixed offset(i.e. 'ptr_regno.off'), 4798 * but not its variable offset. 4799 * 'size' is assumed to be <= reg size and the access is assumed to be aligned. 4800 * 4801 * As opposed to check_stack_read_fixed_off, this function doesn't deal with 4802 * filling registers (i.e. reads of spilled register cannot be detected when 4803 * the offset is not fixed). We conservatively mark 'dst_regno' as containing 4804 * SCALAR_VALUE. That's why we assert that the 'ptr_regno' has a variable 4805 * offset; for a fixed offset check_stack_read_fixed_off should be used 4806 * instead. 4807 */ 4808 static int check_stack_read_var_off(struct bpf_verifier_env *env, 4809 int ptr_regno, int off, int size, int dst_regno) 4810 { 4811 /* The state of the source register. */ 4812 struct bpf_reg_state *reg = reg_state(env, ptr_regno); 4813 struct bpf_func_state *ptr_state = func(env, reg); 4814 int err; 4815 int min_off, max_off; 4816 4817 /* Note that we pass a NULL meta, so raw access will not be permitted. 4818 */ 4819 err = check_stack_range_initialized(env, ptr_regno, off, size, 4820 false, ACCESS_DIRECT, NULL); 4821 if (err) 4822 return err; 4823 4824 min_off = reg->smin_value + off; 4825 max_off = reg->smax_value + off; 4826 mark_reg_stack_read(env, ptr_state, min_off, max_off + size, dst_regno); 4827 return 0; 4828 } 4829 4830 /* check_stack_read dispatches to check_stack_read_fixed_off or 4831 * check_stack_read_var_off. 4832 * 4833 * The caller must ensure that the offset falls within the allocated stack 4834 * bounds. 4835 * 4836 * 'dst_regno' is a register which will receive the value from the stack. It 4837 * can be -1, meaning that the read value is not going to a register. 4838 */ 4839 static int check_stack_read(struct bpf_verifier_env *env, 4840 int ptr_regno, int off, int size, 4841 int dst_regno) 4842 { 4843 struct bpf_reg_state *reg = reg_state(env, ptr_regno); 4844 struct bpf_func_state *state = func(env, reg); 4845 int err; 4846 /* Some accesses are only permitted with a static offset. */ 4847 bool var_off = !tnum_is_const(reg->var_off); 4848 4849 /* The offset is required to be static when reads don't go to a 4850 * register, in order to not leak pointers (see 4851 * check_stack_read_fixed_off). 4852 */ 4853 if (dst_regno < 0 && var_off) { 4854 char tn_buf[48]; 4855 4856 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 4857 verbose(env, "variable offset stack pointer cannot be passed into helper function; var_off=%s off=%d size=%d\n", 4858 tn_buf, off, size); 4859 return -EACCES; 4860 } 4861 /* Variable offset is prohibited for unprivileged mode for simplicity 4862 * since it requires corresponding support in Spectre masking for stack 4863 * ALU. See also retrieve_ptr_limit(). The check in 4864 * check_stack_access_for_ptr_arithmetic() called by 4865 * adjust_ptr_min_max_vals() prevents users from creating stack pointers 4866 * with variable offsets, therefore no check is required here. Further, 4867 * just checking it here would be insufficient as speculative stack 4868 * writes could still lead to unsafe speculative behaviour. 4869 */ 4870 if (!var_off) { 4871 off += reg->var_off.value; 4872 err = check_stack_read_fixed_off(env, state, off, size, 4873 dst_regno); 4874 } else { 4875 /* Variable offset stack reads need more conservative handling 4876 * than fixed offset ones. Note that dst_regno >= 0 on this 4877 * branch. 4878 */ 4879 err = check_stack_read_var_off(env, ptr_regno, off, size, 4880 dst_regno); 4881 } 4882 return err; 4883 } 4884 4885 4886 /* check_stack_write dispatches to check_stack_write_fixed_off or 4887 * check_stack_write_var_off. 4888 * 4889 * 'ptr_regno' is the register used as a pointer into the stack. 4890 * 'off' includes 'ptr_regno->off', but not its variable offset (if any). 4891 * 'value_regno' is the register whose value we're writing to the stack. It can 4892 * be -1, meaning that we're not writing from a register. 4893 * 4894 * The caller must ensure that the offset falls within the maximum stack size. 4895 */ 4896 static int check_stack_write(struct bpf_verifier_env *env, 4897 int ptr_regno, int off, int size, 4898 int value_regno, int insn_idx) 4899 { 4900 struct bpf_reg_state *reg = reg_state(env, ptr_regno); 4901 struct bpf_func_state *state = func(env, reg); 4902 int err; 4903 4904 if (tnum_is_const(reg->var_off)) { 4905 off += reg->var_off.value; 4906 err = check_stack_write_fixed_off(env, state, off, size, 4907 value_regno, insn_idx); 4908 } else { 4909 /* Variable offset stack reads need more conservative handling 4910 * than fixed offset ones. 4911 */ 4912 err = check_stack_write_var_off(env, state, 4913 ptr_regno, off, size, 4914 value_regno, insn_idx); 4915 } 4916 return err; 4917 } 4918 4919 static int check_map_access_type(struct bpf_verifier_env *env, u32 regno, 4920 int off, int size, enum bpf_access_type type) 4921 { 4922 struct bpf_reg_state *regs = cur_regs(env); 4923 struct bpf_map *map = regs[regno].map_ptr; 4924 u32 cap = bpf_map_flags_to_cap(map); 4925 4926 if (type == BPF_WRITE && !(cap & BPF_MAP_CAN_WRITE)) { 4927 verbose(env, "write into map forbidden, value_size=%d off=%d size=%d\n", 4928 map->value_size, off, size); 4929 return -EACCES; 4930 } 4931 4932 if (type == BPF_READ && !(cap & BPF_MAP_CAN_READ)) { 4933 verbose(env, "read from map forbidden, value_size=%d off=%d size=%d\n", 4934 map->value_size, off, size); 4935 return -EACCES; 4936 } 4937 4938 return 0; 4939 } 4940 4941 /* check read/write into memory region (e.g., map value, ringbuf sample, etc) */ 4942 static int __check_mem_access(struct bpf_verifier_env *env, int regno, 4943 int off, int size, u32 mem_size, 4944 bool zero_size_allowed) 4945 { 4946 bool size_ok = size > 0 || (size == 0 && zero_size_allowed); 4947 struct bpf_reg_state *reg; 4948 4949 if (off >= 0 && size_ok && (u64)off + size <= mem_size) 4950 return 0; 4951 4952 reg = &cur_regs(env)[regno]; 4953 switch (reg->type) { 4954 case PTR_TO_MAP_KEY: 4955 verbose(env, "invalid access to map key, key_size=%d off=%d size=%d\n", 4956 mem_size, off, size); 4957 break; 4958 case PTR_TO_MAP_VALUE: 4959 verbose(env, "invalid access to map value, value_size=%d off=%d size=%d\n", 4960 mem_size, off, size); 4961 break; 4962 case PTR_TO_PACKET: 4963 case PTR_TO_PACKET_META: 4964 case PTR_TO_PACKET_END: 4965 verbose(env, "invalid access to packet, off=%d size=%d, R%d(id=%d,off=%d,r=%d)\n", 4966 off, size, regno, reg->id, off, mem_size); 4967 break; 4968 case PTR_TO_MEM: 4969 default: 4970 verbose(env, "invalid access to memory, mem_size=%u off=%d size=%d\n", 4971 mem_size, off, size); 4972 } 4973 4974 return -EACCES; 4975 } 4976 4977 /* check read/write into a memory region with possible variable offset */ 4978 static int check_mem_region_access(struct bpf_verifier_env *env, u32 regno, 4979 int off, int size, u32 mem_size, 4980 bool zero_size_allowed) 4981 { 4982 struct bpf_verifier_state *vstate = env->cur_state; 4983 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 4984 struct bpf_reg_state *reg = &state->regs[regno]; 4985 int err; 4986 4987 /* We may have adjusted the register pointing to memory region, so we 4988 * need to try adding each of min_value and max_value to off 4989 * to make sure our theoretical access will be safe. 4990 * 4991 * The minimum value is only important with signed 4992 * comparisons where we can't assume the floor of a 4993 * value is 0. If we are using signed variables for our 4994 * index'es we need to make sure that whatever we use 4995 * will have a set floor within our range. 4996 */ 4997 if (reg->smin_value < 0 && 4998 (reg->smin_value == S64_MIN || 4999 (off + reg->smin_value != (s64)(s32)(off + reg->smin_value)) || 5000 reg->smin_value + off < 0)) { 5001 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n", 5002 regno); 5003 return -EACCES; 5004 } 5005 err = __check_mem_access(env, regno, reg->smin_value + off, size, 5006 mem_size, zero_size_allowed); 5007 if (err) { 5008 verbose(env, "R%d min value is outside of the allowed memory range\n", 5009 regno); 5010 return err; 5011 } 5012 5013 /* If we haven't set a max value then we need to bail since we can't be 5014 * sure we won't do bad things. 5015 * If reg->umax_value + off could overflow, treat that as unbounded too. 5016 */ 5017 if (reg->umax_value >= BPF_MAX_VAR_OFF) { 5018 verbose(env, "R%d unbounded memory access, make sure to bounds check any such access\n", 5019 regno); 5020 return -EACCES; 5021 } 5022 err = __check_mem_access(env, regno, reg->umax_value + off, size, 5023 mem_size, zero_size_allowed); 5024 if (err) { 5025 verbose(env, "R%d max value is outside of the allowed memory range\n", 5026 regno); 5027 return err; 5028 } 5029 5030 return 0; 5031 } 5032 5033 static int __check_ptr_off_reg(struct bpf_verifier_env *env, 5034 const struct bpf_reg_state *reg, int regno, 5035 bool fixed_off_ok) 5036 { 5037 /* Access to this pointer-typed register or passing it to a helper 5038 * is only allowed in its original, unmodified form. 5039 */ 5040 5041 if (reg->off < 0) { 5042 verbose(env, "negative offset %s ptr R%d off=%d disallowed\n", 5043 reg_type_str(env, reg->type), regno, reg->off); 5044 return -EACCES; 5045 } 5046 5047 if (!fixed_off_ok && reg->off) { 5048 verbose(env, "dereference of modified %s ptr R%d off=%d disallowed\n", 5049 reg_type_str(env, reg->type), regno, reg->off); 5050 return -EACCES; 5051 } 5052 5053 if (!tnum_is_const(reg->var_off) || reg->var_off.value) { 5054 char tn_buf[48]; 5055 5056 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 5057 verbose(env, "variable %s access var_off=%s disallowed\n", 5058 reg_type_str(env, reg->type), tn_buf); 5059 return -EACCES; 5060 } 5061 5062 return 0; 5063 } 5064 5065 int check_ptr_off_reg(struct bpf_verifier_env *env, 5066 const struct bpf_reg_state *reg, int regno) 5067 { 5068 return __check_ptr_off_reg(env, reg, regno, false); 5069 } 5070 5071 static int map_kptr_match_type(struct bpf_verifier_env *env, 5072 struct btf_field *kptr_field, 5073 struct bpf_reg_state *reg, u32 regno) 5074 { 5075 const char *targ_name = btf_type_name(kptr_field->kptr.btf, kptr_field->kptr.btf_id); 5076 int perm_flags; 5077 const char *reg_name = ""; 5078 5079 if (btf_is_kernel(reg->btf)) { 5080 perm_flags = PTR_MAYBE_NULL | PTR_TRUSTED | MEM_RCU; 5081 5082 /* Only unreferenced case accepts untrusted pointers */ 5083 if (kptr_field->type == BPF_KPTR_UNREF) 5084 perm_flags |= PTR_UNTRUSTED; 5085 } else { 5086 perm_flags = PTR_MAYBE_NULL | MEM_ALLOC; 5087 if (kptr_field->type == BPF_KPTR_PERCPU) 5088 perm_flags |= MEM_PERCPU; 5089 } 5090 5091 if (base_type(reg->type) != PTR_TO_BTF_ID || (type_flag(reg->type) & ~perm_flags)) 5092 goto bad_type; 5093 5094 /* We need to verify reg->type and reg->btf, before accessing reg->btf */ 5095 reg_name = btf_type_name(reg->btf, reg->btf_id); 5096 5097 /* For ref_ptr case, release function check should ensure we get one 5098 * referenced PTR_TO_BTF_ID, and that its fixed offset is 0. For the 5099 * normal store of unreferenced kptr, we must ensure var_off is zero. 5100 * Since ref_ptr cannot be accessed directly by BPF insns, checks for 5101 * reg->off and reg->ref_obj_id are not needed here. 5102 */ 5103 if (__check_ptr_off_reg(env, reg, regno, true)) 5104 return -EACCES; 5105 5106 /* A full type match is needed, as BTF can be vmlinux, module or prog BTF, and 5107 * we also need to take into account the reg->off. 5108 * 5109 * We want to support cases like: 5110 * 5111 * struct foo { 5112 * struct bar br; 5113 * struct baz bz; 5114 * }; 5115 * 5116 * struct foo *v; 5117 * v = func(); // PTR_TO_BTF_ID 5118 * val->foo = v; // reg->off is zero, btf and btf_id match type 5119 * val->bar = &v->br; // reg->off is still zero, but we need to retry with 5120 * // first member type of struct after comparison fails 5121 * val->baz = &v->bz; // reg->off is non-zero, so struct needs to be walked 5122 * // to match type 5123 * 5124 * In the kptr_ref case, check_func_arg_reg_off already ensures reg->off 5125 * is zero. We must also ensure that btf_struct_ids_match does not walk 5126 * the struct to match type against first member of struct, i.e. reject 5127 * second case from above. Hence, when type is BPF_KPTR_REF, we set 5128 * strict mode to true for type match. 5129 */ 5130 if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off, 5131 kptr_field->kptr.btf, kptr_field->kptr.btf_id, 5132 kptr_field->type != BPF_KPTR_UNREF)) 5133 goto bad_type; 5134 return 0; 5135 bad_type: 5136 verbose(env, "invalid kptr access, R%d type=%s%s ", regno, 5137 reg_type_str(env, reg->type), reg_name); 5138 verbose(env, "expected=%s%s", reg_type_str(env, PTR_TO_BTF_ID), targ_name); 5139 if (kptr_field->type == BPF_KPTR_UNREF) 5140 verbose(env, " or %s%s\n", reg_type_str(env, PTR_TO_BTF_ID | PTR_UNTRUSTED), 5141 targ_name); 5142 else 5143 verbose(env, "\n"); 5144 return -EINVAL; 5145 } 5146 5147 /* The non-sleepable programs and sleepable programs with explicit bpf_rcu_read_lock() 5148 * can dereference RCU protected pointers and result is PTR_TRUSTED. 5149 */ 5150 static bool in_rcu_cs(struct bpf_verifier_env *env) 5151 { 5152 return env->cur_state->active_rcu_lock || 5153 env->cur_state->active_lock.ptr || 5154 !env->prog->aux->sleepable; 5155 } 5156 5157 /* Once GCC supports btf_type_tag the following mechanism will be replaced with tag check */ 5158 BTF_SET_START(rcu_protected_types) 5159 BTF_ID(struct, prog_test_ref_kfunc) 5160 BTF_ID(struct, cgroup) 5161 BTF_ID(struct, bpf_cpumask) 5162 BTF_ID(struct, task_struct) 5163 BTF_SET_END(rcu_protected_types) 5164 5165 static bool rcu_protected_object(const struct btf *btf, u32 btf_id) 5166 { 5167 if (!btf_is_kernel(btf)) 5168 return false; 5169 return btf_id_set_contains(&rcu_protected_types, btf_id); 5170 } 5171 5172 static bool rcu_safe_kptr(const struct btf_field *field) 5173 { 5174 const struct btf_field_kptr *kptr = &field->kptr; 5175 5176 return field->type == BPF_KPTR_PERCPU || 5177 (field->type == BPF_KPTR_REF && rcu_protected_object(kptr->btf, kptr->btf_id)); 5178 } 5179 5180 static u32 btf_ld_kptr_type(struct bpf_verifier_env *env, struct btf_field *kptr_field) 5181 { 5182 if (rcu_safe_kptr(kptr_field) && in_rcu_cs(env)) { 5183 if (kptr_field->type != BPF_KPTR_PERCPU) 5184 return PTR_MAYBE_NULL | MEM_RCU; 5185 return PTR_MAYBE_NULL | MEM_RCU | MEM_PERCPU; 5186 } 5187 return PTR_MAYBE_NULL | PTR_UNTRUSTED; 5188 } 5189 5190 static int check_map_kptr_access(struct bpf_verifier_env *env, u32 regno, 5191 int value_regno, int insn_idx, 5192 struct btf_field *kptr_field) 5193 { 5194 struct bpf_insn *insn = &env->prog->insnsi[insn_idx]; 5195 int class = BPF_CLASS(insn->code); 5196 struct bpf_reg_state *val_reg; 5197 5198 /* Things we already checked for in check_map_access and caller: 5199 * - Reject cases where variable offset may touch kptr 5200 * - size of access (must be BPF_DW) 5201 * - tnum_is_const(reg->var_off) 5202 * - kptr_field->offset == off + reg->var_off.value 5203 */ 5204 /* Only BPF_[LDX,STX,ST] | BPF_MEM | BPF_DW is supported */ 5205 if (BPF_MODE(insn->code) != BPF_MEM) { 5206 verbose(env, "kptr in map can only be accessed using BPF_MEM instruction mode\n"); 5207 return -EACCES; 5208 } 5209 5210 /* We only allow loading referenced kptr, since it will be marked as 5211 * untrusted, similar to unreferenced kptr. 5212 */ 5213 if (class != BPF_LDX && 5214 (kptr_field->type == BPF_KPTR_REF || kptr_field->type == BPF_KPTR_PERCPU)) { 5215 verbose(env, "store to referenced kptr disallowed\n"); 5216 return -EACCES; 5217 } 5218 5219 if (class == BPF_LDX) { 5220 val_reg = reg_state(env, value_regno); 5221 /* We can simply mark the value_regno receiving the pointer 5222 * value from map as PTR_TO_BTF_ID, with the correct type. 5223 */ 5224 mark_btf_ld_reg(env, cur_regs(env), value_regno, PTR_TO_BTF_ID, kptr_field->kptr.btf, 5225 kptr_field->kptr.btf_id, btf_ld_kptr_type(env, kptr_field)); 5226 /* For mark_ptr_or_null_reg */ 5227 val_reg->id = ++env->id_gen; 5228 } else if (class == BPF_STX) { 5229 val_reg = reg_state(env, value_regno); 5230 if (!register_is_null(val_reg) && 5231 map_kptr_match_type(env, kptr_field, val_reg, value_regno)) 5232 return -EACCES; 5233 } else if (class == BPF_ST) { 5234 if (insn->imm) { 5235 verbose(env, "BPF_ST imm must be 0 when storing to kptr at off=%u\n", 5236 kptr_field->offset); 5237 return -EACCES; 5238 } 5239 } else { 5240 verbose(env, "kptr in map can only be accessed using BPF_LDX/BPF_STX/BPF_ST\n"); 5241 return -EACCES; 5242 } 5243 return 0; 5244 } 5245 5246 /* check read/write into a map element with possible variable offset */ 5247 static int check_map_access(struct bpf_verifier_env *env, u32 regno, 5248 int off, int size, bool zero_size_allowed, 5249 enum bpf_access_src src) 5250 { 5251 struct bpf_verifier_state *vstate = env->cur_state; 5252 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 5253 struct bpf_reg_state *reg = &state->regs[regno]; 5254 struct bpf_map *map = reg->map_ptr; 5255 struct btf_record *rec; 5256 int err, i; 5257 5258 err = check_mem_region_access(env, regno, off, size, map->value_size, 5259 zero_size_allowed); 5260 if (err) 5261 return err; 5262 5263 if (IS_ERR_OR_NULL(map->record)) 5264 return 0; 5265 rec = map->record; 5266 for (i = 0; i < rec->cnt; i++) { 5267 struct btf_field *field = &rec->fields[i]; 5268 u32 p = field->offset; 5269 5270 /* If any part of a field can be touched by load/store, reject 5271 * this program. To check that [x1, x2) overlaps with [y1, y2), 5272 * it is sufficient to check x1 < y2 && y1 < x2. 5273 */ 5274 if (reg->smin_value + off < p + btf_field_type_size(field->type) && 5275 p < reg->umax_value + off + size) { 5276 switch (field->type) { 5277 case BPF_KPTR_UNREF: 5278 case BPF_KPTR_REF: 5279 case BPF_KPTR_PERCPU: 5280 if (src != ACCESS_DIRECT) { 5281 verbose(env, "kptr cannot be accessed indirectly by helper\n"); 5282 return -EACCES; 5283 } 5284 if (!tnum_is_const(reg->var_off)) { 5285 verbose(env, "kptr access cannot have variable offset\n"); 5286 return -EACCES; 5287 } 5288 if (p != off + reg->var_off.value) { 5289 verbose(env, "kptr access misaligned expected=%u off=%llu\n", 5290 p, off + reg->var_off.value); 5291 return -EACCES; 5292 } 5293 if (size != bpf_size_to_bytes(BPF_DW)) { 5294 verbose(env, "kptr access size must be BPF_DW\n"); 5295 return -EACCES; 5296 } 5297 break; 5298 default: 5299 verbose(env, "%s cannot be accessed directly by load/store\n", 5300 btf_field_type_name(field->type)); 5301 return -EACCES; 5302 } 5303 } 5304 } 5305 return 0; 5306 } 5307 5308 #define MAX_PACKET_OFF 0xffff 5309 5310 static bool may_access_direct_pkt_data(struct bpf_verifier_env *env, 5311 const struct bpf_call_arg_meta *meta, 5312 enum bpf_access_type t) 5313 { 5314 enum bpf_prog_type prog_type = resolve_prog_type(env->prog); 5315 5316 switch (prog_type) { 5317 /* Program types only with direct read access go here! */ 5318 case BPF_PROG_TYPE_LWT_IN: 5319 case BPF_PROG_TYPE_LWT_OUT: 5320 case BPF_PROG_TYPE_LWT_SEG6LOCAL: 5321 case BPF_PROG_TYPE_SK_REUSEPORT: 5322 case BPF_PROG_TYPE_FLOW_DISSECTOR: 5323 case BPF_PROG_TYPE_CGROUP_SKB: 5324 if (t == BPF_WRITE) 5325 return false; 5326 fallthrough; 5327 5328 /* Program types with direct read + write access go here! */ 5329 case BPF_PROG_TYPE_SCHED_CLS: 5330 case BPF_PROG_TYPE_SCHED_ACT: 5331 case BPF_PROG_TYPE_XDP: 5332 case BPF_PROG_TYPE_LWT_XMIT: 5333 case BPF_PROG_TYPE_SK_SKB: 5334 case BPF_PROG_TYPE_SK_MSG: 5335 if (meta) 5336 return meta->pkt_access; 5337 5338 env->seen_direct_write = true; 5339 return true; 5340 5341 case BPF_PROG_TYPE_CGROUP_SOCKOPT: 5342 if (t == BPF_WRITE) 5343 env->seen_direct_write = true; 5344 5345 return true; 5346 5347 default: 5348 return false; 5349 } 5350 } 5351 5352 static int check_packet_access(struct bpf_verifier_env *env, u32 regno, int off, 5353 int size, bool zero_size_allowed) 5354 { 5355 struct bpf_reg_state *regs = cur_regs(env); 5356 struct bpf_reg_state *reg = ®s[regno]; 5357 int err; 5358 5359 /* We may have added a variable offset to the packet pointer; but any 5360 * reg->range we have comes after that. We are only checking the fixed 5361 * offset. 5362 */ 5363 5364 /* We don't allow negative numbers, because we aren't tracking enough 5365 * detail to prove they're safe. 5366 */ 5367 if (reg->smin_value < 0) { 5368 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n", 5369 regno); 5370 return -EACCES; 5371 } 5372 5373 err = reg->range < 0 ? -EINVAL : 5374 __check_mem_access(env, regno, off, size, reg->range, 5375 zero_size_allowed); 5376 if (err) { 5377 verbose(env, "R%d offset is outside of the packet\n", regno); 5378 return err; 5379 } 5380 5381 /* __check_mem_access has made sure "off + size - 1" is within u16. 5382 * reg->umax_value can't be bigger than MAX_PACKET_OFF which is 0xffff, 5383 * otherwise find_good_pkt_pointers would have refused to set range info 5384 * that __check_mem_access would have rejected this pkt access. 5385 * Therefore, "off + reg->umax_value + size - 1" won't overflow u32. 5386 */ 5387 env->prog->aux->max_pkt_offset = 5388 max_t(u32, env->prog->aux->max_pkt_offset, 5389 off + reg->umax_value + size - 1); 5390 5391 return err; 5392 } 5393 5394 /* check access to 'struct bpf_context' fields. Supports fixed offsets only */ 5395 static int check_ctx_access(struct bpf_verifier_env *env, int insn_idx, int off, int size, 5396 enum bpf_access_type t, enum bpf_reg_type *reg_type, 5397 struct btf **btf, u32 *btf_id) 5398 { 5399 struct bpf_insn_access_aux info = { 5400 .reg_type = *reg_type, 5401 .log = &env->log, 5402 }; 5403 5404 if (env->ops->is_valid_access && 5405 env->ops->is_valid_access(off, size, t, env->prog, &info)) { 5406 /* A non zero info.ctx_field_size indicates that this field is a 5407 * candidate for later verifier transformation to load the whole 5408 * field and then apply a mask when accessed with a narrower 5409 * access than actual ctx access size. A zero info.ctx_field_size 5410 * will only allow for whole field access and rejects any other 5411 * type of narrower access. 5412 */ 5413 *reg_type = info.reg_type; 5414 5415 if (base_type(*reg_type) == PTR_TO_BTF_ID) { 5416 *btf = info.btf; 5417 *btf_id = info.btf_id; 5418 } else { 5419 env->insn_aux_data[insn_idx].ctx_field_size = info.ctx_field_size; 5420 } 5421 /* remember the offset of last byte accessed in ctx */ 5422 if (env->prog->aux->max_ctx_offset < off + size) 5423 env->prog->aux->max_ctx_offset = off + size; 5424 return 0; 5425 } 5426 5427 verbose(env, "invalid bpf_context access off=%d size=%d\n", off, size); 5428 return -EACCES; 5429 } 5430 5431 static int check_flow_keys_access(struct bpf_verifier_env *env, int off, 5432 int size) 5433 { 5434 if (size < 0 || off < 0 || 5435 (u64)off + size > sizeof(struct bpf_flow_keys)) { 5436 verbose(env, "invalid access to flow keys off=%d size=%d\n", 5437 off, size); 5438 return -EACCES; 5439 } 5440 return 0; 5441 } 5442 5443 static int check_sock_access(struct bpf_verifier_env *env, int insn_idx, 5444 u32 regno, int off, int size, 5445 enum bpf_access_type t) 5446 { 5447 struct bpf_reg_state *regs = cur_regs(env); 5448 struct bpf_reg_state *reg = ®s[regno]; 5449 struct bpf_insn_access_aux info = {}; 5450 bool valid; 5451 5452 if (reg->smin_value < 0) { 5453 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n", 5454 regno); 5455 return -EACCES; 5456 } 5457 5458 switch (reg->type) { 5459 case PTR_TO_SOCK_COMMON: 5460 valid = bpf_sock_common_is_valid_access(off, size, t, &info); 5461 break; 5462 case PTR_TO_SOCKET: 5463 valid = bpf_sock_is_valid_access(off, size, t, &info); 5464 break; 5465 case PTR_TO_TCP_SOCK: 5466 valid = bpf_tcp_sock_is_valid_access(off, size, t, &info); 5467 break; 5468 case PTR_TO_XDP_SOCK: 5469 valid = bpf_xdp_sock_is_valid_access(off, size, t, &info); 5470 break; 5471 default: 5472 valid = false; 5473 } 5474 5475 5476 if (valid) { 5477 env->insn_aux_data[insn_idx].ctx_field_size = 5478 info.ctx_field_size; 5479 return 0; 5480 } 5481 5482 verbose(env, "R%d invalid %s access off=%d size=%d\n", 5483 regno, reg_type_str(env, reg->type), off, size); 5484 5485 return -EACCES; 5486 } 5487 5488 static bool is_pointer_value(struct bpf_verifier_env *env, int regno) 5489 { 5490 return __is_pointer_value(env->allow_ptr_leaks, reg_state(env, regno)); 5491 } 5492 5493 static bool is_ctx_reg(struct bpf_verifier_env *env, int regno) 5494 { 5495 const struct bpf_reg_state *reg = reg_state(env, regno); 5496 5497 return reg->type == PTR_TO_CTX; 5498 } 5499 5500 static bool is_sk_reg(struct bpf_verifier_env *env, int regno) 5501 { 5502 const struct bpf_reg_state *reg = reg_state(env, regno); 5503 5504 return type_is_sk_pointer(reg->type); 5505 } 5506 5507 static bool is_pkt_reg(struct bpf_verifier_env *env, int regno) 5508 { 5509 const struct bpf_reg_state *reg = reg_state(env, regno); 5510 5511 return type_is_pkt_pointer(reg->type); 5512 } 5513 5514 static bool is_flow_key_reg(struct bpf_verifier_env *env, int regno) 5515 { 5516 const struct bpf_reg_state *reg = reg_state(env, regno); 5517 5518 /* Separate to is_ctx_reg() since we still want to allow BPF_ST here. */ 5519 return reg->type == PTR_TO_FLOW_KEYS; 5520 } 5521 5522 static u32 *reg2btf_ids[__BPF_REG_TYPE_MAX] = { 5523 #ifdef CONFIG_NET 5524 [PTR_TO_SOCKET] = &btf_sock_ids[BTF_SOCK_TYPE_SOCK], 5525 [PTR_TO_SOCK_COMMON] = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON], 5526 [PTR_TO_TCP_SOCK] = &btf_sock_ids[BTF_SOCK_TYPE_TCP], 5527 #endif 5528 [CONST_PTR_TO_MAP] = btf_bpf_map_id, 5529 }; 5530 5531 static bool is_trusted_reg(const struct bpf_reg_state *reg) 5532 { 5533 /* A referenced register is always trusted. */ 5534 if (reg->ref_obj_id) 5535 return true; 5536 5537 /* Types listed in the reg2btf_ids are always trusted */ 5538 if (reg2btf_ids[base_type(reg->type)]) 5539 return true; 5540 5541 /* If a register is not referenced, it is trusted if it has the 5542 * MEM_ALLOC or PTR_TRUSTED type modifiers, and no others. Some of the 5543 * other type modifiers may be safe, but we elect to take an opt-in 5544 * approach here as some (e.g. PTR_UNTRUSTED and PTR_MAYBE_NULL) are 5545 * not. 5546 * 5547 * Eventually, we should make PTR_TRUSTED the single source of truth 5548 * for whether a register is trusted. 5549 */ 5550 return type_flag(reg->type) & BPF_REG_TRUSTED_MODIFIERS && 5551 !bpf_type_has_unsafe_modifiers(reg->type); 5552 } 5553 5554 static bool is_rcu_reg(const struct bpf_reg_state *reg) 5555 { 5556 return reg->type & MEM_RCU; 5557 } 5558 5559 static void clear_trusted_flags(enum bpf_type_flag *flag) 5560 { 5561 *flag &= ~(BPF_REG_TRUSTED_MODIFIERS | MEM_RCU); 5562 } 5563 5564 static int check_pkt_ptr_alignment(struct bpf_verifier_env *env, 5565 const struct bpf_reg_state *reg, 5566 int off, int size, bool strict) 5567 { 5568 struct tnum reg_off; 5569 int ip_align; 5570 5571 /* Byte size accesses are always allowed. */ 5572 if (!strict || size == 1) 5573 return 0; 5574 5575 /* For platforms that do not have a Kconfig enabling 5576 * CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS the value of 5577 * NET_IP_ALIGN is universally set to '2'. And on platforms 5578 * that do set CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS, we get 5579 * to this code only in strict mode where we want to emulate 5580 * the NET_IP_ALIGN==2 checking. Therefore use an 5581 * unconditional IP align value of '2'. 5582 */ 5583 ip_align = 2; 5584 5585 reg_off = tnum_add(reg->var_off, tnum_const(ip_align + reg->off + off)); 5586 if (!tnum_is_aligned(reg_off, size)) { 5587 char tn_buf[48]; 5588 5589 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 5590 verbose(env, 5591 "misaligned packet access off %d+%s+%d+%d size %d\n", 5592 ip_align, tn_buf, reg->off, off, size); 5593 return -EACCES; 5594 } 5595 5596 return 0; 5597 } 5598 5599 static int check_generic_ptr_alignment(struct bpf_verifier_env *env, 5600 const struct bpf_reg_state *reg, 5601 const char *pointer_desc, 5602 int off, int size, bool strict) 5603 { 5604 struct tnum reg_off; 5605 5606 /* Byte size accesses are always allowed. */ 5607 if (!strict || size == 1) 5608 return 0; 5609 5610 reg_off = tnum_add(reg->var_off, tnum_const(reg->off + off)); 5611 if (!tnum_is_aligned(reg_off, size)) { 5612 char tn_buf[48]; 5613 5614 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 5615 verbose(env, "misaligned %saccess off %s+%d+%d size %d\n", 5616 pointer_desc, tn_buf, reg->off, off, size); 5617 return -EACCES; 5618 } 5619 5620 return 0; 5621 } 5622 5623 static int check_ptr_alignment(struct bpf_verifier_env *env, 5624 const struct bpf_reg_state *reg, int off, 5625 int size, bool strict_alignment_once) 5626 { 5627 bool strict = env->strict_alignment || strict_alignment_once; 5628 const char *pointer_desc = ""; 5629 5630 switch (reg->type) { 5631 case PTR_TO_PACKET: 5632 case PTR_TO_PACKET_META: 5633 /* Special case, because of NET_IP_ALIGN. Given metadata sits 5634 * right in front, treat it the very same way. 5635 */ 5636 return check_pkt_ptr_alignment(env, reg, off, size, strict); 5637 case PTR_TO_FLOW_KEYS: 5638 pointer_desc = "flow keys "; 5639 break; 5640 case PTR_TO_MAP_KEY: 5641 pointer_desc = "key "; 5642 break; 5643 case PTR_TO_MAP_VALUE: 5644 pointer_desc = "value "; 5645 break; 5646 case PTR_TO_CTX: 5647 pointer_desc = "context "; 5648 break; 5649 case PTR_TO_STACK: 5650 pointer_desc = "stack "; 5651 /* The stack spill tracking logic in check_stack_write_fixed_off() 5652 * and check_stack_read_fixed_off() relies on stack accesses being 5653 * aligned. 5654 */ 5655 strict = true; 5656 break; 5657 case PTR_TO_SOCKET: 5658 pointer_desc = "sock "; 5659 break; 5660 case PTR_TO_SOCK_COMMON: 5661 pointer_desc = "sock_common "; 5662 break; 5663 case PTR_TO_TCP_SOCK: 5664 pointer_desc = "tcp_sock "; 5665 break; 5666 case PTR_TO_XDP_SOCK: 5667 pointer_desc = "xdp_sock "; 5668 break; 5669 default: 5670 break; 5671 } 5672 return check_generic_ptr_alignment(env, reg, pointer_desc, off, size, 5673 strict); 5674 } 5675 5676 static int update_stack_depth(struct bpf_verifier_env *env, 5677 const struct bpf_func_state *func, 5678 int off) 5679 { 5680 u16 stack = env->subprog_info[func->subprogno].stack_depth; 5681 5682 if (stack >= -off) 5683 return 0; 5684 5685 /* update known max for given subprogram */ 5686 env->subprog_info[func->subprogno].stack_depth = -off; 5687 return 0; 5688 } 5689 5690 /* starting from main bpf function walk all instructions of the function 5691 * and recursively walk all callees that given function can call. 5692 * Ignore jump and exit insns. 5693 * Since recursion is prevented by check_cfg() this algorithm 5694 * only needs a local stack of MAX_CALL_FRAMES to remember callsites 5695 */ 5696 static int check_max_stack_depth_subprog(struct bpf_verifier_env *env, int idx) 5697 { 5698 struct bpf_subprog_info *subprog = env->subprog_info; 5699 struct bpf_insn *insn = env->prog->insnsi; 5700 int depth = 0, frame = 0, i, subprog_end; 5701 bool tail_call_reachable = false; 5702 int ret_insn[MAX_CALL_FRAMES]; 5703 int ret_prog[MAX_CALL_FRAMES]; 5704 int j; 5705 5706 i = subprog[idx].start; 5707 process_func: 5708 /* protect against potential stack overflow that might happen when 5709 * bpf2bpf calls get combined with tailcalls. Limit the caller's stack 5710 * depth for such case down to 256 so that the worst case scenario 5711 * would result in 8k stack size (32 which is tailcall limit * 256 = 5712 * 8k). 5713 * 5714 * To get the idea what might happen, see an example: 5715 * func1 -> sub rsp, 128 5716 * subfunc1 -> sub rsp, 256 5717 * tailcall1 -> add rsp, 256 5718 * func2 -> sub rsp, 192 (total stack size = 128 + 192 = 320) 5719 * subfunc2 -> sub rsp, 64 5720 * subfunc22 -> sub rsp, 128 5721 * tailcall2 -> add rsp, 128 5722 * func3 -> sub rsp, 32 (total stack size 128 + 192 + 64 + 32 = 416) 5723 * 5724 * tailcall will unwind the current stack frame but it will not get rid 5725 * of caller's stack as shown on the example above. 5726 */ 5727 if (idx && subprog[idx].has_tail_call && depth >= 256) { 5728 verbose(env, 5729 "tail_calls are not allowed when call stack of previous frames is %d bytes. Too large\n", 5730 depth); 5731 return -EACCES; 5732 } 5733 /* round up to 32-bytes, since this is granularity 5734 * of interpreter stack size 5735 */ 5736 depth += round_up(max_t(u32, subprog[idx].stack_depth, 1), 32); 5737 if (depth > MAX_BPF_STACK) { 5738 verbose(env, "combined stack size of %d calls is %d. Too large\n", 5739 frame + 1, depth); 5740 return -EACCES; 5741 } 5742 continue_func: 5743 subprog_end = subprog[idx + 1].start; 5744 for (; i < subprog_end; i++) { 5745 int next_insn, sidx; 5746 5747 if (bpf_pseudo_kfunc_call(insn + i) && !insn[i].off) { 5748 bool err = false; 5749 5750 if (!is_bpf_throw_kfunc(insn + i)) 5751 continue; 5752 if (subprog[idx].is_cb) 5753 err = true; 5754 for (int c = 0; c < frame && !err; c++) { 5755 if (subprog[ret_prog[c]].is_cb) { 5756 err = true; 5757 break; 5758 } 5759 } 5760 if (!err) 5761 continue; 5762 verbose(env, 5763 "bpf_throw kfunc (insn %d) cannot be called from callback subprog %d\n", 5764 i, idx); 5765 return -EINVAL; 5766 } 5767 5768 if (!bpf_pseudo_call(insn + i) && !bpf_pseudo_func(insn + i)) 5769 continue; 5770 /* remember insn and function to return to */ 5771 ret_insn[frame] = i + 1; 5772 ret_prog[frame] = idx; 5773 5774 /* find the callee */ 5775 next_insn = i + insn[i].imm + 1; 5776 sidx = find_subprog(env, next_insn); 5777 if (sidx < 0) { 5778 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n", 5779 next_insn); 5780 return -EFAULT; 5781 } 5782 if (subprog[sidx].is_async_cb) { 5783 if (subprog[sidx].has_tail_call) { 5784 verbose(env, "verifier bug. subprog has tail_call and async cb\n"); 5785 return -EFAULT; 5786 } 5787 /* async callbacks don't increase bpf prog stack size unless called directly */ 5788 if (!bpf_pseudo_call(insn + i)) 5789 continue; 5790 if (subprog[sidx].is_exception_cb) { 5791 verbose(env, "insn %d cannot call exception cb directly\n", i); 5792 return -EINVAL; 5793 } 5794 } 5795 i = next_insn; 5796 idx = sidx; 5797 5798 if (subprog[idx].has_tail_call) 5799 tail_call_reachable = true; 5800 5801 frame++; 5802 if (frame >= MAX_CALL_FRAMES) { 5803 verbose(env, "the call stack of %d frames is too deep !\n", 5804 frame); 5805 return -E2BIG; 5806 } 5807 goto process_func; 5808 } 5809 /* if tail call got detected across bpf2bpf calls then mark each of the 5810 * currently present subprog frames as tail call reachable subprogs; 5811 * this info will be utilized by JIT so that we will be preserving the 5812 * tail call counter throughout bpf2bpf calls combined with tailcalls 5813 */ 5814 if (tail_call_reachable) 5815 for (j = 0; j < frame; j++) { 5816 if (subprog[ret_prog[j]].is_exception_cb) { 5817 verbose(env, "cannot tail call within exception cb\n"); 5818 return -EINVAL; 5819 } 5820 subprog[ret_prog[j]].tail_call_reachable = true; 5821 } 5822 if (subprog[0].tail_call_reachable) 5823 env->prog->aux->tail_call_reachable = true; 5824 5825 /* end of for() loop means the last insn of the 'subprog' 5826 * was reached. Doesn't matter whether it was JA or EXIT 5827 */ 5828 if (frame == 0) 5829 return 0; 5830 depth -= round_up(max_t(u32, subprog[idx].stack_depth, 1), 32); 5831 frame--; 5832 i = ret_insn[frame]; 5833 idx = ret_prog[frame]; 5834 goto continue_func; 5835 } 5836 5837 static int check_max_stack_depth(struct bpf_verifier_env *env) 5838 { 5839 struct bpf_subprog_info *si = env->subprog_info; 5840 int ret; 5841 5842 for (int i = 0; i < env->subprog_cnt; i++) { 5843 if (!i || si[i].is_async_cb) { 5844 ret = check_max_stack_depth_subprog(env, i); 5845 if (ret < 0) 5846 return ret; 5847 } 5848 continue; 5849 } 5850 return 0; 5851 } 5852 5853 #ifndef CONFIG_BPF_JIT_ALWAYS_ON 5854 static int get_callee_stack_depth(struct bpf_verifier_env *env, 5855 const struct bpf_insn *insn, int idx) 5856 { 5857 int start = idx + insn->imm + 1, subprog; 5858 5859 subprog = find_subprog(env, start); 5860 if (subprog < 0) { 5861 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n", 5862 start); 5863 return -EFAULT; 5864 } 5865 return env->subprog_info[subprog].stack_depth; 5866 } 5867 #endif 5868 5869 static int __check_buffer_access(struct bpf_verifier_env *env, 5870 const char *buf_info, 5871 const struct bpf_reg_state *reg, 5872 int regno, int off, int size) 5873 { 5874 if (off < 0) { 5875 verbose(env, 5876 "R%d invalid %s buffer access: off=%d, size=%d\n", 5877 regno, buf_info, off, size); 5878 return -EACCES; 5879 } 5880 if (!tnum_is_const(reg->var_off) || reg->var_off.value) { 5881 char tn_buf[48]; 5882 5883 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 5884 verbose(env, 5885 "R%d invalid variable buffer offset: off=%d, var_off=%s\n", 5886 regno, off, tn_buf); 5887 return -EACCES; 5888 } 5889 5890 return 0; 5891 } 5892 5893 static int check_tp_buffer_access(struct bpf_verifier_env *env, 5894 const struct bpf_reg_state *reg, 5895 int regno, int off, int size) 5896 { 5897 int err; 5898 5899 err = __check_buffer_access(env, "tracepoint", reg, regno, off, size); 5900 if (err) 5901 return err; 5902 5903 if (off + size > env->prog->aux->max_tp_access) 5904 env->prog->aux->max_tp_access = off + size; 5905 5906 return 0; 5907 } 5908 5909 static int check_buffer_access(struct bpf_verifier_env *env, 5910 const struct bpf_reg_state *reg, 5911 int regno, int off, int size, 5912 bool zero_size_allowed, 5913 u32 *max_access) 5914 { 5915 const char *buf_info = type_is_rdonly_mem(reg->type) ? "rdonly" : "rdwr"; 5916 int err; 5917 5918 err = __check_buffer_access(env, buf_info, reg, regno, off, size); 5919 if (err) 5920 return err; 5921 5922 if (off + size > *max_access) 5923 *max_access = off + size; 5924 5925 return 0; 5926 } 5927 5928 /* BPF architecture zero extends alu32 ops into 64-bit registesr */ 5929 static void zext_32_to_64(struct bpf_reg_state *reg) 5930 { 5931 reg->var_off = tnum_subreg(reg->var_off); 5932 __reg_assign_32_into_64(reg); 5933 } 5934 5935 /* truncate register to smaller size (in bytes) 5936 * must be called with size < BPF_REG_SIZE 5937 */ 5938 static void coerce_reg_to_size(struct bpf_reg_state *reg, int size) 5939 { 5940 u64 mask; 5941 5942 /* clear high bits in bit representation */ 5943 reg->var_off = tnum_cast(reg->var_off, size); 5944 5945 /* fix arithmetic bounds */ 5946 mask = ((u64)1 << (size * 8)) - 1; 5947 if ((reg->umin_value & ~mask) == (reg->umax_value & ~mask)) { 5948 reg->umin_value &= mask; 5949 reg->umax_value &= mask; 5950 } else { 5951 reg->umin_value = 0; 5952 reg->umax_value = mask; 5953 } 5954 reg->smin_value = reg->umin_value; 5955 reg->smax_value = reg->umax_value; 5956 5957 /* If size is smaller than 32bit register the 32bit register 5958 * values are also truncated so we push 64-bit bounds into 5959 * 32-bit bounds. Above were truncated < 32-bits already. 5960 */ 5961 if (size >= 4) 5962 return; 5963 __reg_combine_64_into_32(reg); 5964 } 5965 5966 static void set_sext64_default_val(struct bpf_reg_state *reg, int size) 5967 { 5968 if (size == 1) { 5969 reg->smin_value = reg->s32_min_value = S8_MIN; 5970 reg->smax_value = reg->s32_max_value = S8_MAX; 5971 } else if (size == 2) { 5972 reg->smin_value = reg->s32_min_value = S16_MIN; 5973 reg->smax_value = reg->s32_max_value = S16_MAX; 5974 } else { 5975 /* size == 4 */ 5976 reg->smin_value = reg->s32_min_value = S32_MIN; 5977 reg->smax_value = reg->s32_max_value = S32_MAX; 5978 } 5979 reg->umin_value = reg->u32_min_value = 0; 5980 reg->umax_value = U64_MAX; 5981 reg->u32_max_value = U32_MAX; 5982 reg->var_off = tnum_unknown; 5983 } 5984 5985 static void coerce_reg_to_size_sx(struct bpf_reg_state *reg, int size) 5986 { 5987 s64 init_s64_max, init_s64_min, s64_max, s64_min, u64_cval; 5988 u64 top_smax_value, top_smin_value; 5989 u64 num_bits = size * 8; 5990 5991 if (tnum_is_const(reg->var_off)) { 5992 u64_cval = reg->var_off.value; 5993 if (size == 1) 5994 reg->var_off = tnum_const((s8)u64_cval); 5995 else if (size == 2) 5996 reg->var_off = tnum_const((s16)u64_cval); 5997 else 5998 /* size == 4 */ 5999 reg->var_off = tnum_const((s32)u64_cval); 6000 6001 u64_cval = reg->var_off.value; 6002 reg->smax_value = reg->smin_value = u64_cval; 6003 reg->umax_value = reg->umin_value = u64_cval; 6004 reg->s32_max_value = reg->s32_min_value = u64_cval; 6005 reg->u32_max_value = reg->u32_min_value = u64_cval; 6006 return; 6007 } 6008 6009 top_smax_value = ((u64)reg->smax_value >> num_bits) << num_bits; 6010 top_smin_value = ((u64)reg->smin_value >> num_bits) << num_bits; 6011 6012 if (top_smax_value != top_smin_value) 6013 goto out; 6014 6015 /* find the s64_min and s64_min after sign extension */ 6016 if (size == 1) { 6017 init_s64_max = (s8)reg->smax_value; 6018 init_s64_min = (s8)reg->smin_value; 6019 } else if (size == 2) { 6020 init_s64_max = (s16)reg->smax_value; 6021 init_s64_min = (s16)reg->smin_value; 6022 } else { 6023 init_s64_max = (s32)reg->smax_value; 6024 init_s64_min = (s32)reg->smin_value; 6025 } 6026 6027 s64_max = max(init_s64_max, init_s64_min); 6028 s64_min = min(init_s64_max, init_s64_min); 6029 6030 /* both of s64_max/s64_min positive or negative */ 6031 if ((s64_max >= 0) == (s64_min >= 0)) { 6032 reg->smin_value = reg->s32_min_value = s64_min; 6033 reg->smax_value = reg->s32_max_value = s64_max; 6034 reg->umin_value = reg->u32_min_value = s64_min; 6035 reg->umax_value = reg->u32_max_value = s64_max; 6036 reg->var_off = tnum_range(s64_min, s64_max); 6037 return; 6038 } 6039 6040 out: 6041 set_sext64_default_val(reg, size); 6042 } 6043 6044 static void set_sext32_default_val(struct bpf_reg_state *reg, int size) 6045 { 6046 if (size == 1) { 6047 reg->s32_min_value = S8_MIN; 6048 reg->s32_max_value = S8_MAX; 6049 } else { 6050 /* size == 2 */ 6051 reg->s32_min_value = S16_MIN; 6052 reg->s32_max_value = S16_MAX; 6053 } 6054 reg->u32_min_value = 0; 6055 reg->u32_max_value = U32_MAX; 6056 } 6057 6058 static void coerce_subreg_to_size_sx(struct bpf_reg_state *reg, int size) 6059 { 6060 s32 init_s32_max, init_s32_min, s32_max, s32_min, u32_val; 6061 u32 top_smax_value, top_smin_value; 6062 u32 num_bits = size * 8; 6063 6064 if (tnum_is_const(reg->var_off)) { 6065 u32_val = reg->var_off.value; 6066 if (size == 1) 6067 reg->var_off = tnum_const((s8)u32_val); 6068 else 6069 reg->var_off = tnum_const((s16)u32_val); 6070 6071 u32_val = reg->var_off.value; 6072 reg->s32_min_value = reg->s32_max_value = u32_val; 6073 reg->u32_min_value = reg->u32_max_value = u32_val; 6074 return; 6075 } 6076 6077 top_smax_value = ((u32)reg->s32_max_value >> num_bits) << num_bits; 6078 top_smin_value = ((u32)reg->s32_min_value >> num_bits) << num_bits; 6079 6080 if (top_smax_value != top_smin_value) 6081 goto out; 6082 6083 /* find the s32_min and s32_min after sign extension */ 6084 if (size == 1) { 6085 init_s32_max = (s8)reg->s32_max_value; 6086 init_s32_min = (s8)reg->s32_min_value; 6087 } else { 6088 /* size == 2 */ 6089 init_s32_max = (s16)reg->s32_max_value; 6090 init_s32_min = (s16)reg->s32_min_value; 6091 } 6092 s32_max = max(init_s32_max, init_s32_min); 6093 s32_min = min(init_s32_max, init_s32_min); 6094 6095 if ((s32_min >= 0) == (s32_max >= 0)) { 6096 reg->s32_min_value = s32_min; 6097 reg->s32_max_value = s32_max; 6098 reg->u32_min_value = (u32)s32_min; 6099 reg->u32_max_value = (u32)s32_max; 6100 return; 6101 } 6102 6103 out: 6104 set_sext32_default_val(reg, size); 6105 } 6106 6107 static bool bpf_map_is_rdonly(const struct bpf_map *map) 6108 { 6109 /* A map is considered read-only if the following condition are true: 6110 * 6111 * 1) BPF program side cannot change any of the map content. The 6112 * BPF_F_RDONLY_PROG flag is throughout the lifetime of a map 6113 * and was set at map creation time. 6114 * 2) The map value(s) have been initialized from user space by a 6115 * loader and then "frozen", such that no new map update/delete 6116 * operations from syscall side are possible for the rest of 6117 * the map's lifetime from that point onwards. 6118 * 3) Any parallel/pending map update/delete operations from syscall 6119 * side have been completed. Only after that point, it's safe to 6120 * assume that map value(s) are immutable. 6121 */ 6122 return (map->map_flags & BPF_F_RDONLY_PROG) && 6123 READ_ONCE(map->frozen) && 6124 !bpf_map_write_active(map); 6125 } 6126 6127 static int bpf_map_direct_read(struct bpf_map *map, int off, int size, u64 *val, 6128 bool is_ldsx) 6129 { 6130 void *ptr; 6131 u64 addr; 6132 int err; 6133 6134 err = map->ops->map_direct_value_addr(map, &addr, off); 6135 if (err) 6136 return err; 6137 ptr = (void *)(long)addr + off; 6138 6139 switch (size) { 6140 case sizeof(u8): 6141 *val = is_ldsx ? (s64)*(s8 *)ptr : (u64)*(u8 *)ptr; 6142 break; 6143 case sizeof(u16): 6144 *val = is_ldsx ? (s64)*(s16 *)ptr : (u64)*(u16 *)ptr; 6145 break; 6146 case sizeof(u32): 6147 *val = is_ldsx ? (s64)*(s32 *)ptr : (u64)*(u32 *)ptr; 6148 break; 6149 case sizeof(u64): 6150 *val = *(u64 *)ptr; 6151 break; 6152 default: 6153 return -EINVAL; 6154 } 6155 return 0; 6156 } 6157 6158 #define BTF_TYPE_SAFE_RCU(__type) __PASTE(__type, __safe_rcu) 6159 #define BTF_TYPE_SAFE_RCU_OR_NULL(__type) __PASTE(__type, __safe_rcu_or_null) 6160 #define BTF_TYPE_SAFE_TRUSTED(__type) __PASTE(__type, __safe_trusted) 6161 6162 /* 6163 * Allow list few fields as RCU trusted or full trusted. 6164 * This logic doesn't allow mix tagging and will be removed once GCC supports 6165 * btf_type_tag. 6166 */ 6167 6168 /* RCU trusted: these fields are trusted in RCU CS and never NULL */ 6169 BTF_TYPE_SAFE_RCU(struct task_struct) { 6170 const cpumask_t *cpus_ptr; 6171 struct css_set __rcu *cgroups; 6172 struct task_struct __rcu *real_parent; 6173 struct task_struct *group_leader; 6174 }; 6175 6176 BTF_TYPE_SAFE_RCU(struct cgroup) { 6177 /* cgrp->kn is always accessible as documented in kernel/cgroup/cgroup.c */ 6178 struct kernfs_node *kn; 6179 }; 6180 6181 BTF_TYPE_SAFE_RCU(struct css_set) { 6182 struct cgroup *dfl_cgrp; 6183 }; 6184 6185 /* RCU trusted: these fields are trusted in RCU CS and can be NULL */ 6186 BTF_TYPE_SAFE_RCU_OR_NULL(struct mm_struct) { 6187 struct file __rcu *exe_file; 6188 }; 6189 6190 /* skb->sk, req->sk are not RCU protected, but we mark them as such 6191 * because bpf prog accessible sockets are SOCK_RCU_FREE. 6192 */ 6193 BTF_TYPE_SAFE_RCU_OR_NULL(struct sk_buff) { 6194 struct sock *sk; 6195 }; 6196 6197 BTF_TYPE_SAFE_RCU_OR_NULL(struct request_sock) { 6198 struct sock *sk; 6199 }; 6200 6201 /* full trusted: these fields are trusted even outside of RCU CS and never NULL */ 6202 BTF_TYPE_SAFE_TRUSTED(struct bpf_iter_meta) { 6203 struct seq_file *seq; 6204 }; 6205 6206 BTF_TYPE_SAFE_TRUSTED(struct bpf_iter__task) { 6207 struct bpf_iter_meta *meta; 6208 struct task_struct *task; 6209 }; 6210 6211 BTF_TYPE_SAFE_TRUSTED(struct linux_binprm) { 6212 struct file *file; 6213 }; 6214 6215 BTF_TYPE_SAFE_TRUSTED(struct file) { 6216 struct inode *f_inode; 6217 }; 6218 6219 BTF_TYPE_SAFE_TRUSTED(struct dentry) { 6220 /* no negative dentry-s in places where bpf can see it */ 6221 struct inode *d_inode; 6222 }; 6223 6224 BTF_TYPE_SAFE_TRUSTED(struct socket) { 6225 struct sock *sk; 6226 }; 6227 6228 static bool type_is_rcu(struct bpf_verifier_env *env, 6229 struct bpf_reg_state *reg, 6230 const char *field_name, u32 btf_id) 6231 { 6232 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct task_struct)); 6233 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct cgroup)); 6234 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct css_set)); 6235 6236 return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_rcu"); 6237 } 6238 6239 static bool type_is_rcu_or_null(struct bpf_verifier_env *env, 6240 struct bpf_reg_state *reg, 6241 const char *field_name, u32 btf_id) 6242 { 6243 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct mm_struct)); 6244 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct sk_buff)); 6245 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct request_sock)); 6246 6247 return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_rcu_or_null"); 6248 } 6249 6250 static bool type_is_trusted(struct bpf_verifier_env *env, 6251 struct bpf_reg_state *reg, 6252 const char *field_name, u32 btf_id) 6253 { 6254 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct bpf_iter_meta)); 6255 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct bpf_iter__task)); 6256 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct linux_binprm)); 6257 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct file)); 6258 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct dentry)); 6259 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct socket)); 6260 6261 return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_trusted"); 6262 } 6263 6264 static int check_ptr_to_btf_access(struct bpf_verifier_env *env, 6265 struct bpf_reg_state *regs, 6266 int regno, int off, int size, 6267 enum bpf_access_type atype, 6268 int value_regno) 6269 { 6270 struct bpf_reg_state *reg = regs + regno; 6271 const struct btf_type *t = btf_type_by_id(reg->btf, reg->btf_id); 6272 const char *tname = btf_name_by_offset(reg->btf, t->name_off); 6273 const char *field_name = NULL; 6274 enum bpf_type_flag flag = 0; 6275 u32 btf_id = 0; 6276 int ret; 6277 6278 if (!env->allow_ptr_leaks) { 6279 verbose(env, 6280 "'struct %s' access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n", 6281 tname); 6282 return -EPERM; 6283 } 6284 if (!env->prog->gpl_compatible && btf_is_kernel(reg->btf)) { 6285 verbose(env, 6286 "Cannot access kernel 'struct %s' from non-GPL compatible program\n", 6287 tname); 6288 return -EINVAL; 6289 } 6290 if (off < 0) { 6291 verbose(env, 6292 "R%d is ptr_%s invalid negative access: off=%d\n", 6293 regno, tname, off); 6294 return -EACCES; 6295 } 6296 if (!tnum_is_const(reg->var_off) || reg->var_off.value) { 6297 char tn_buf[48]; 6298 6299 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 6300 verbose(env, 6301 "R%d is ptr_%s invalid variable offset: off=%d, var_off=%s\n", 6302 regno, tname, off, tn_buf); 6303 return -EACCES; 6304 } 6305 6306 if (reg->type & MEM_USER) { 6307 verbose(env, 6308 "R%d is ptr_%s access user memory: off=%d\n", 6309 regno, tname, off); 6310 return -EACCES; 6311 } 6312 6313 if (reg->type & MEM_PERCPU) { 6314 verbose(env, 6315 "R%d is ptr_%s access percpu memory: off=%d\n", 6316 regno, tname, off); 6317 return -EACCES; 6318 } 6319 6320 if (env->ops->btf_struct_access && !type_is_alloc(reg->type) && atype == BPF_WRITE) { 6321 if (!btf_is_kernel(reg->btf)) { 6322 verbose(env, "verifier internal error: reg->btf must be kernel btf\n"); 6323 return -EFAULT; 6324 } 6325 ret = env->ops->btf_struct_access(&env->log, reg, off, size); 6326 } else { 6327 /* Writes are permitted with default btf_struct_access for 6328 * program allocated objects (which always have ref_obj_id > 0), 6329 * but not for untrusted PTR_TO_BTF_ID | MEM_ALLOC. 6330 */ 6331 if (atype != BPF_READ && !type_is_ptr_alloc_obj(reg->type)) { 6332 verbose(env, "only read is supported\n"); 6333 return -EACCES; 6334 } 6335 6336 if (type_is_alloc(reg->type) && !type_is_non_owning_ref(reg->type) && 6337 !(reg->type & MEM_RCU) && !reg->ref_obj_id) { 6338 verbose(env, "verifier internal error: ref_obj_id for allocated object must be non-zero\n"); 6339 return -EFAULT; 6340 } 6341 6342 ret = btf_struct_access(&env->log, reg, off, size, atype, &btf_id, &flag, &field_name); 6343 } 6344 6345 if (ret < 0) 6346 return ret; 6347 6348 if (ret != PTR_TO_BTF_ID) { 6349 /* just mark; */ 6350 6351 } else if (type_flag(reg->type) & PTR_UNTRUSTED) { 6352 /* If this is an untrusted pointer, all pointers formed by walking it 6353 * also inherit the untrusted flag. 6354 */ 6355 flag = PTR_UNTRUSTED; 6356 6357 } else if (is_trusted_reg(reg) || is_rcu_reg(reg)) { 6358 /* By default any pointer obtained from walking a trusted pointer is no 6359 * longer trusted, unless the field being accessed has explicitly been 6360 * marked as inheriting its parent's state of trust (either full or RCU). 6361 * For example: 6362 * 'cgroups' pointer is untrusted if task->cgroups dereference 6363 * happened in a sleepable program outside of bpf_rcu_read_lock() 6364 * section. In a non-sleepable program it's trusted while in RCU CS (aka MEM_RCU). 6365 * Note bpf_rcu_read_unlock() converts MEM_RCU pointers to PTR_UNTRUSTED. 6366 * 6367 * A regular RCU-protected pointer with __rcu tag can also be deemed 6368 * trusted if we are in an RCU CS. Such pointer can be NULL. 6369 */ 6370 if (type_is_trusted(env, reg, field_name, btf_id)) { 6371 flag |= PTR_TRUSTED; 6372 } else if (in_rcu_cs(env) && !type_may_be_null(reg->type)) { 6373 if (type_is_rcu(env, reg, field_name, btf_id)) { 6374 /* ignore __rcu tag and mark it MEM_RCU */ 6375 flag |= MEM_RCU; 6376 } else if (flag & MEM_RCU || 6377 type_is_rcu_or_null(env, reg, field_name, btf_id)) { 6378 /* __rcu tagged pointers can be NULL */ 6379 flag |= MEM_RCU | PTR_MAYBE_NULL; 6380 6381 /* We always trust them */ 6382 if (type_is_rcu_or_null(env, reg, field_name, btf_id) && 6383 flag & PTR_UNTRUSTED) 6384 flag &= ~PTR_UNTRUSTED; 6385 } else if (flag & (MEM_PERCPU | MEM_USER)) { 6386 /* keep as-is */ 6387 } else { 6388 /* walking unknown pointers yields old deprecated PTR_TO_BTF_ID */ 6389 clear_trusted_flags(&flag); 6390 } 6391 } else { 6392 /* 6393 * If not in RCU CS or MEM_RCU pointer can be NULL then 6394 * aggressively mark as untrusted otherwise such 6395 * pointers will be plain PTR_TO_BTF_ID without flags 6396 * and will be allowed to be passed into helpers for 6397 * compat reasons. 6398 */ 6399 flag = PTR_UNTRUSTED; 6400 } 6401 } else { 6402 /* Old compat. Deprecated */ 6403 clear_trusted_flags(&flag); 6404 } 6405 6406 if (atype == BPF_READ && value_regno >= 0) 6407 mark_btf_ld_reg(env, regs, value_regno, ret, reg->btf, btf_id, flag); 6408 6409 return 0; 6410 } 6411 6412 static int check_ptr_to_map_access(struct bpf_verifier_env *env, 6413 struct bpf_reg_state *regs, 6414 int regno, int off, int size, 6415 enum bpf_access_type atype, 6416 int value_regno) 6417 { 6418 struct bpf_reg_state *reg = regs + regno; 6419 struct bpf_map *map = reg->map_ptr; 6420 struct bpf_reg_state map_reg; 6421 enum bpf_type_flag flag = 0; 6422 const struct btf_type *t; 6423 const char *tname; 6424 u32 btf_id; 6425 int ret; 6426 6427 if (!btf_vmlinux) { 6428 verbose(env, "map_ptr access not supported without CONFIG_DEBUG_INFO_BTF\n"); 6429 return -ENOTSUPP; 6430 } 6431 6432 if (!map->ops->map_btf_id || !*map->ops->map_btf_id) { 6433 verbose(env, "map_ptr access not supported for map type %d\n", 6434 map->map_type); 6435 return -ENOTSUPP; 6436 } 6437 6438 t = btf_type_by_id(btf_vmlinux, *map->ops->map_btf_id); 6439 tname = btf_name_by_offset(btf_vmlinux, t->name_off); 6440 6441 if (!env->allow_ptr_leaks) { 6442 verbose(env, 6443 "'struct %s' access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n", 6444 tname); 6445 return -EPERM; 6446 } 6447 6448 if (off < 0) { 6449 verbose(env, "R%d is %s invalid negative access: off=%d\n", 6450 regno, tname, off); 6451 return -EACCES; 6452 } 6453 6454 if (atype != BPF_READ) { 6455 verbose(env, "only read from %s is supported\n", tname); 6456 return -EACCES; 6457 } 6458 6459 /* Simulate access to a PTR_TO_BTF_ID */ 6460 memset(&map_reg, 0, sizeof(map_reg)); 6461 mark_btf_ld_reg(env, &map_reg, 0, PTR_TO_BTF_ID, btf_vmlinux, *map->ops->map_btf_id, 0); 6462 ret = btf_struct_access(&env->log, &map_reg, off, size, atype, &btf_id, &flag, NULL); 6463 if (ret < 0) 6464 return ret; 6465 6466 if (value_regno >= 0) 6467 mark_btf_ld_reg(env, regs, value_regno, ret, btf_vmlinux, btf_id, flag); 6468 6469 return 0; 6470 } 6471 6472 /* Check that the stack access at the given offset is within bounds. The 6473 * maximum valid offset is -1. 6474 * 6475 * The minimum valid offset is -MAX_BPF_STACK for writes, and 6476 * -state->allocated_stack for reads. 6477 */ 6478 static int check_stack_slot_within_bounds(int off, 6479 struct bpf_func_state *state, 6480 enum bpf_access_type t) 6481 { 6482 int min_valid_off; 6483 6484 if (t == BPF_WRITE) 6485 min_valid_off = -MAX_BPF_STACK; 6486 else 6487 min_valid_off = -state->allocated_stack; 6488 6489 if (off < min_valid_off || off > -1) 6490 return -EACCES; 6491 return 0; 6492 } 6493 6494 /* Check that the stack access at 'regno + off' falls within the maximum stack 6495 * bounds. 6496 * 6497 * 'off' includes `regno->offset`, but not its dynamic part (if any). 6498 */ 6499 static int check_stack_access_within_bounds( 6500 struct bpf_verifier_env *env, 6501 int regno, int off, int access_size, 6502 enum bpf_access_src src, enum bpf_access_type type) 6503 { 6504 struct bpf_reg_state *regs = cur_regs(env); 6505 struct bpf_reg_state *reg = regs + regno; 6506 struct bpf_func_state *state = func(env, reg); 6507 int min_off, max_off; 6508 int err; 6509 char *err_extra; 6510 6511 if (src == ACCESS_HELPER) 6512 /* We don't know if helpers are reading or writing (or both). */ 6513 err_extra = " indirect access to"; 6514 else if (type == BPF_READ) 6515 err_extra = " read from"; 6516 else 6517 err_extra = " write to"; 6518 6519 if (tnum_is_const(reg->var_off)) { 6520 min_off = reg->var_off.value + off; 6521 if (access_size > 0) 6522 max_off = min_off + access_size - 1; 6523 else 6524 max_off = min_off; 6525 } else { 6526 if (reg->smax_value >= BPF_MAX_VAR_OFF || 6527 reg->smin_value <= -BPF_MAX_VAR_OFF) { 6528 verbose(env, "invalid unbounded variable-offset%s stack R%d\n", 6529 err_extra, regno); 6530 return -EACCES; 6531 } 6532 min_off = reg->smin_value + off; 6533 if (access_size > 0) 6534 max_off = reg->smax_value + off + access_size - 1; 6535 else 6536 max_off = min_off; 6537 } 6538 6539 err = check_stack_slot_within_bounds(min_off, state, type); 6540 if (!err) 6541 err = check_stack_slot_within_bounds(max_off, state, type); 6542 6543 if (err) { 6544 if (tnum_is_const(reg->var_off)) { 6545 verbose(env, "invalid%s stack R%d off=%d size=%d\n", 6546 err_extra, regno, off, access_size); 6547 } else { 6548 char tn_buf[48]; 6549 6550 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 6551 verbose(env, "invalid variable-offset%s stack R%d var_off=%s size=%d\n", 6552 err_extra, regno, tn_buf, access_size); 6553 } 6554 } 6555 return err; 6556 } 6557 6558 /* check whether memory at (regno + off) is accessible for t = (read | write) 6559 * if t==write, value_regno is a register which value is stored into memory 6560 * if t==read, value_regno is a register which will receive the value from memory 6561 * if t==write && value_regno==-1, some unknown value is stored into memory 6562 * if t==read && value_regno==-1, don't care what we read from memory 6563 */ 6564 static int check_mem_access(struct bpf_verifier_env *env, int insn_idx, u32 regno, 6565 int off, int bpf_size, enum bpf_access_type t, 6566 int value_regno, bool strict_alignment_once, bool is_ldsx) 6567 { 6568 struct bpf_reg_state *regs = cur_regs(env); 6569 struct bpf_reg_state *reg = regs + regno; 6570 struct bpf_func_state *state; 6571 int size, err = 0; 6572 6573 size = bpf_size_to_bytes(bpf_size); 6574 if (size < 0) 6575 return size; 6576 6577 /* alignment checks will add in reg->off themselves */ 6578 err = check_ptr_alignment(env, reg, off, size, strict_alignment_once); 6579 if (err) 6580 return err; 6581 6582 /* for access checks, reg->off is just part of off */ 6583 off += reg->off; 6584 6585 if (reg->type == PTR_TO_MAP_KEY) { 6586 if (t == BPF_WRITE) { 6587 verbose(env, "write to change key R%d not allowed\n", regno); 6588 return -EACCES; 6589 } 6590 6591 err = check_mem_region_access(env, regno, off, size, 6592 reg->map_ptr->key_size, false); 6593 if (err) 6594 return err; 6595 if (value_regno >= 0) 6596 mark_reg_unknown(env, regs, value_regno); 6597 } else if (reg->type == PTR_TO_MAP_VALUE) { 6598 struct btf_field *kptr_field = NULL; 6599 6600 if (t == BPF_WRITE && value_regno >= 0 && 6601 is_pointer_value(env, value_regno)) { 6602 verbose(env, "R%d leaks addr into map\n", value_regno); 6603 return -EACCES; 6604 } 6605 err = check_map_access_type(env, regno, off, size, t); 6606 if (err) 6607 return err; 6608 err = check_map_access(env, regno, off, size, false, ACCESS_DIRECT); 6609 if (err) 6610 return err; 6611 if (tnum_is_const(reg->var_off)) 6612 kptr_field = btf_record_find(reg->map_ptr->record, 6613 off + reg->var_off.value, BPF_KPTR); 6614 if (kptr_field) { 6615 err = check_map_kptr_access(env, regno, value_regno, insn_idx, kptr_field); 6616 } else if (t == BPF_READ && value_regno >= 0) { 6617 struct bpf_map *map = reg->map_ptr; 6618 6619 /* if map is read-only, track its contents as scalars */ 6620 if (tnum_is_const(reg->var_off) && 6621 bpf_map_is_rdonly(map) && 6622 map->ops->map_direct_value_addr) { 6623 int map_off = off + reg->var_off.value; 6624 u64 val = 0; 6625 6626 err = bpf_map_direct_read(map, map_off, size, 6627 &val, is_ldsx); 6628 if (err) 6629 return err; 6630 6631 regs[value_regno].type = SCALAR_VALUE; 6632 __mark_reg_known(®s[value_regno], val); 6633 } else { 6634 mark_reg_unknown(env, regs, value_regno); 6635 } 6636 } 6637 } else if (base_type(reg->type) == PTR_TO_MEM) { 6638 bool rdonly_mem = type_is_rdonly_mem(reg->type); 6639 6640 if (type_may_be_null(reg->type)) { 6641 verbose(env, "R%d invalid mem access '%s'\n", regno, 6642 reg_type_str(env, reg->type)); 6643 return -EACCES; 6644 } 6645 6646 if (t == BPF_WRITE && rdonly_mem) { 6647 verbose(env, "R%d cannot write into %s\n", 6648 regno, reg_type_str(env, reg->type)); 6649 return -EACCES; 6650 } 6651 6652 if (t == BPF_WRITE && value_regno >= 0 && 6653 is_pointer_value(env, value_regno)) { 6654 verbose(env, "R%d leaks addr into mem\n", value_regno); 6655 return -EACCES; 6656 } 6657 6658 err = check_mem_region_access(env, regno, off, size, 6659 reg->mem_size, false); 6660 if (!err && value_regno >= 0 && (t == BPF_READ || rdonly_mem)) 6661 mark_reg_unknown(env, regs, value_regno); 6662 } else if (reg->type == PTR_TO_CTX) { 6663 enum bpf_reg_type reg_type = SCALAR_VALUE; 6664 struct btf *btf = NULL; 6665 u32 btf_id = 0; 6666 6667 if (t == BPF_WRITE && value_regno >= 0 && 6668 is_pointer_value(env, value_regno)) { 6669 verbose(env, "R%d leaks addr into ctx\n", value_regno); 6670 return -EACCES; 6671 } 6672 6673 err = check_ptr_off_reg(env, reg, regno); 6674 if (err < 0) 6675 return err; 6676 6677 err = check_ctx_access(env, insn_idx, off, size, t, ®_type, &btf, 6678 &btf_id); 6679 if (err) 6680 verbose_linfo(env, insn_idx, "; "); 6681 if (!err && t == BPF_READ && value_regno >= 0) { 6682 /* ctx access returns either a scalar, or a 6683 * PTR_TO_PACKET[_META,_END]. In the latter 6684 * case, we know the offset is zero. 6685 */ 6686 if (reg_type == SCALAR_VALUE) { 6687 mark_reg_unknown(env, regs, value_regno); 6688 } else { 6689 mark_reg_known_zero(env, regs, 6690 value_regno); 6691 if (type_may_be_null(reg_type)) 6692 regs[value_regno].id = ++env->id_gen; 6693 /* A load of ctx field could have different 6694 * actual load size with the one encoded in the 6695 * insn. When the dst is PTR, it is for sure not 6696 * a sub-register. 6697 */ 6698 regs[value_regno].subreg_def = DEF_NOT_SUBREG; 6699 if (base_type(reg_type) == PTR_TO_BTF_ID) { 6700 regs[value_regno].btf = btf; 6701 regs[value_regno].btf_id = btf_id; 6702 } 6703 } 6704 regs[value_regno].type = reg_type; 6705 } 6706 6707 } else if (reg->type == PTR_TO_STACK) { 6708 /* Basic bounds checks. */ 6709 err = check_stack_access_within_bounds(env, regno, off, size, ACCESS_DIRECT, t); 6710 if (err) 6711 return err; 6712 6713 state = func(env, reg); 6714 err = update_stack_depth(env, state, off); 6715 if (err) 6716 return err; 6717 6718 if (t == BPF_READ) 6719 err = check_stack_read(env, regno, off, size, 6720 value_regno); 6721 else 6722 err = check_stack_write(env, regno, off, size, 6723 value_regno, insn_idx); 6724 } else if (reg_is_pkt_pointer(reg)) { 6725 if (t == BPF_WRITE && !may_access_direct_pkt_data(env, NULL, t)) { 6726 verbose(env, "cannot write into packet\n"); 6727 return -EACCES; 6728 } 6729 if (t == BPF_WRITE && value_regno >= 0 && 6730 is_pointer_value(env, value_regno)) { 6731 verbose(env, "R%d leaks addr into packet\n", 6732 value_regno); 6733 return -EACCES; 6734 } 6735 err = check_packet_access(env, regno, off, size, false); 6736 if (!err && t == BPF_READ && value_regno >= 0) 6737 mark_reg_unknown(env, regs, value_regno); 6738 } else if (reg->type == PTR_TO_FLOW_KEYS) { 6739 if (t == BPF_WRITE && value_regno >= 0 && 6740 is_pointer_value(env, value_regno)) { 6741 verbose(env, "R%d leaks addr into flow keys\n", 6742 value_regno); 6743 return -EACCES; 6744 } 6745 6746 err = check_flow_keys_access(env, off, size); 6747 if (!err && t == BPF_READ && value_regno >= 0) 6748 mark_reg_unknown(env, regs, value_regno); 6749 } else if (type_is_sk_pointer(reg->type)) { 6750 if (t == BPF_WRITE) { 6751 verbose(env, "R%d cannot write into %s\n", 6752 regno, reg_type_str(env, reg->type)); 6753 return -EACCES; 6754 } 6755 err = check_sock_access(env, insn_idx, regno, off, size, t); 6756 if (!err && value_regno >= 0) 6757 mark_reg_unknown(env, regs, value_regno); 6758 } else if (reg->type == PTR_TO_TP_BUFFER) { 6759 err = check_tp_buffer_access(env, reg, regno, off, size); 6760 if (!err && t == BPF_READ && value_regno >= 0) 6761 mark_reg_unknown(env, regs, value_regno); 6762 } else if (base_type(reg->type) == PTR_TO_BTF_ID && 6763 !type_may_be_null(reg->type)) { 6764 err = check_ptr_to_btf_access(env, regs, regno, off, size, t, 6765 value_regno); 6766 } else if (reg->type == CONST_PTR_TO_MAP) { 6767 err = check_ptr_to_map_access(env, regs, regno, off, size, t, 6768 value_regno); 6769 } else if (base_type(reg->type) == PTR_TO_BUF) { 6770 bool rdonly_mem = type_is_rdonly_mem(reg->type); 6771 u32 *max_access; 6772 6773 if (rdonly_mem) { 6774 if (t == BPF_WRITE) { 6775 verbose(env, "R%d cannot write into %s\n", 6776 regno, reg_type_str(env, reg->type)); 6777 return -EACCES; 6778 } 6779 max_access = &env->prog->aux->max_rdonly_access; 6780 } else { 6781 max_access = &env->prog->aux->max_rdwr_access; 6782 } 6783 6784 err = check_buffer_access(env, reg, regno, off, size, false, 6785 max_access); 6786 6787 if (!err && value_regno >= 0 && (rdonly_mem || t == BPF_READ)) 6788 mark_reg_unknown(env, regs, value_regno); 6789 } else { 6790 verbose(env, "R%d invalid mem access '%s'\n", regno, 6791 reg_type_str(env, reg->type)); 6792 return -EACCES; 6793 } 6794 6795 if (!err && size < BPF_REG_SIZE && value_regno >= 0 && t == BPF_READ && 6796 regs[value_regno].type == SCALAR_VALUE) { 6797 if (!is_ldsx) 6798 /* b/h/w load zero-extends, mark upper bits as known 0 */ 6799 coerce_reg_to_size(®s[value_regno], size); 6800 else 6801 coerce_reg_to_size_sx(®s[value_regno], size); 6802 } 6803 return err; 6804 } 6805 6806 static int check_atomic(struct bpf_verifier_env *env, int insn_idx, struct bpf_insn *insn) 6807 { 6808 int load_reg; 6809 int err; 6810 6811 switch (insn->imm) { 6812 case BPF_ADD: 6813 case BPF_ADD | BPF_FETCH: 6814 case BPF_AND: 6815 case BPF_AND | BPF_FETCH: 6816 case BPF_OR: 6817 case BPF_OR | BPF_FETCH: 6818 case BPF_XOR: 6819 case BPF_XOR | BPF_FETCH: 6820 case BPF_XCHG: 6821 case BPF_CMPXCHG: 6822 break; 6823 default: 6824 verbose(env, "BPF_ATOMIC uses invalid atomic opcode %02x\n", insn->imm); 6825 return -EINVAL; 6826 } 6827 6828 if (BPF_SIZE(insn->code) != BPF_W && BPF_SIZE(insn->code) != BPF_DW) { 6829 verbose(env, "invalid atomic operand size\n"); 6830 return -EINVAL; 6831 } 6832 6833 /* check src1 operand */ 6834 err = check_reg_arg(env, insn->src_reg, SRC_OP); 6835 if (err) 6836 return err; 6837 6838 /* check src2 operand */ 6839 err = check_reg_arg(env, insn->dst_reg, SRC_OP); 6840 if (err) 6841 return err; 6842 6843 if (insn->imm == BPF_CMPXCHG) { 6844 /* Check comparison of R0 with memory location */ 6845 const u32 aux_reg = BPF_REG_0; 6846 6847 err = check_reg_arg(env, aux_reg, SRC_OP); 6848 if (err) 6849 return err; 6850 6851 if (is_pointer_value(env, aux_reg)) { 6852 verbose(env, "R%d leaks addr into mem\n", aux_reg); 6853 return -EACCES; 6854 } 6855 } 6856 6857 if (is_pointer_value(env, insn->src_reg)) { 6858 verbose(env, "R%d leaks addr into mem\n", insn->src_reg); 6859 return -EACCES; 6860 } 6861 6862 if (is_ctx_reg(env, insn->dst_reg) || 6863 is_pkt_reg(env, insn->dst_reg) || 6864 is_flow_key_reg(env, insn->dst_reg) || 6865 is_sk_reg(env, insn->dst_reg)) { 6866 verbose(env, "BPF_ATOMIC stores into R%d %s is not allowed\n", 6867 insn->dst_reg, 6868 reg_type_str(env, reg_state(env, insn->dst_reg)->type)); 6869 return -EACCES; 6870 } 6871 6872 if (insn->imm & BPF_FETCH) { 6873 if (insn->imm == BPF_CMPXCHG) 6874 load_reg = BPF_REG_0; 6875 else 6876 load_reg = insn->src_reg; 6877 6878 /* check and record load of old value */ 6879 err = check_reg_arg(env, load_reg, DST_OP); 6880 if (err) 6881 return err; 6882 } else { 6883 /* This instruction accesses a memory location but doesn't 6884 * actually load it into a register. 6885 */ 6886 load_reg = -1; 6887 } 6888 6889 /* Check whether we can read the memory, with second call for fetch 6890 * case to simulate the register fill. 6891 */ 6892 err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off, 6893 BPF_SIZE(insn->code), BPF_READ, -1, true, false); 6894 if (!err && load_reg >= 0) 6895 err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off, 6896 BPF_SIZE(insn->code), BPF_READ, load_reg, 6897 true, false); 6898 if (err) 6899 return err; 6900 6901 /* Check whether we can write into the same memory. */ 6902 err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off, 6903 BPF_SIZE(insn->code), BPF_WRITE, -1, true, false); 6904 if (err) 6905 return err; 6906 6907 return 0; 6908 } 6909 6910 /* When register 'regno' is used to read the stack (either directly or through 6911 * a helper function) make sure that it's within stack boundary and, depending 6912 * on the access type, that all elements of the stack are initialized. 6913 * 6914 * 'off' includes 'regno->off', but not its dynamic part (if any). 6915 * 6916 * All registers that have been spilled on the stack in the slots within the 6917 * read offsets are marked as read. 6918 */ 6919 static int check_stack_range_initialized( 6920 struct bpf_verifier_env *env, int regno, int off, 6921 int access_size, bool zero_size_allowed, 6922 enum bpf_access_src type, struct bpf_call_arg_meta *meta) 6923 { 6924 struct bpf_reg_state *reg = reg_state(env, regno); 6925 struct bpf_func_state *state = func(env, reg); 6926 int err, min_off, max_off, i, j, slot, spi; 6927 char *err_extra = type == ACCESS_HELPER ? " indirect" : ""; 6928 enum bpf_access_type bounds_check_type; 6929 /* Some accesses can write anything into the stack, others are 6930 * read-only. 6931 */ 6932 bool clobber = false; 6933 6934 if (access_size == 0 && !zero_size_allowed) { 6935 verbose(env, "invalid zero-sized read\n"); 6936 return -EACCES; 6937 } 6938 6939 if (type == ACCESS_HELPER) { 6940 /* The bounds checks for writes are more permissive than for 6941 * reads. However, if raw_mode is not set, we'll do extra 6942 * checks below. 6943 */ 6944 bounds_check_type = BPF_WRITE; 6945 clobber = true; 6946 } else { 6947 bounds_check_type = BPF_READ; 6948 } 6949 err = check_stack_access_within_bounds(env, regno, off, access_size, 6950 type, bounds_check_type); 6951 if (err) 6952 return err; 6953 6954 6955 if (tnum_is_const(reg->var_off)) { 6956 min_off = max_off = reg->var_off.value + off; 6957 } else { 6958 /* Variable offset is prohibited for unprivileged mode for 6959 * simplicity since it requires corresponding support in 6960 * Spectre masking for stack ALU. 6961 * See also retrieve_ptr_limit(). 6962 */ 6963 if (!env->bypass_spec_v1) { 6964 char tn_buf[48]; 6965 6966 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 6967 verbose(env, "R%d%s variable offset stack access prohibited for !root, var_off=%s\n", 6968 regno, err_extra, tn_buf); 6969 return -EACCES; 6970 } 6971 /* Only initialized buffer on stack is allowed to be accessed 6972 * with variable offset. With uninitialized buffer it's hard to 6973 * guarantee that whole memory is marked as initialized on 6974 * helper return since specific bounds are unknown what may 6975 * cause uninitialized stack leaking. 6976 */ 6977 if (meta && meta->raw_mode) 6978 meta = NULL; 6979 6980 min_off = reg->smin_value + off; 6981 max_off = reg->smax_value + off; 6982 } 6983 6984 if (meta && meta->raw_mode) { 6985 /* Ensure we won't be overwriting dynptrs when simulating byte 6986 * by byte access in check_helper_call using meta.access_size. 6987 * This would be a problem if we have a helper in the future 6988 * which takes: 6989 * 6990 * helper(uninit_mem, len, dynptr) 6991 * 6992 * Now, uninint_mem may overlap with dynptr pointer. Hence, it 6993 * may end up writing to dynptr itself when touching memory from 6994 * arg 1. This can be relaxed on a case by case basis for known 6995 * safe cases, but reject due to the possibilitiy of aliasing by 6996 * default. 6997 */ 6998 for (i = min_off; i < max_off + access_size; i++) { 6999 int stack_off = -i - 1; 7000 7001 spi = __get_spi(i); 7002 /* raw_mode may write past allocated_stack */ 7003 if (state->allocated_stack <= stack_off) 7004 continue; 7005 if (state->stack[spi].slot_type[stack_off % BPF_REG_SIZE] == STACK_DYNPTR) { 7006 verbose(env, "potential write to dynptr at off=%d disallowed\n", i); 7007 return -EACCES; 7008 } 7009 } 7010 meta->access_size = access_size; 7011 meta->regno = regno; 7012 return 0; 7013 } 7014 7015 for (i = min_off; i < max_off + access_size; i++) { 7016 u8 *stype; 7017 7018 slot = -i - 1; 7019 spi = slot / BPF_REG_SIZE; 7020 if (state->allocated_stack <= slot) 7021 goto err; 7022 stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE]; 7023 if (*stype == STACK_MISC) 7024 goto mark; 7025 if ((*stype == STACK_ZERO) || 7026 (*stype == STACK_INVALID && env->allow_uninit_stack)) { 7027 if (clobber) { 7028 /* helper can write anything into the stack */ 7029 *stype = STACK_MISC; 7030 } 7031 goto mark; 7032 } 7033 7034 if (is_spilled_reg(&state->stack[spi]) && 7035 (state->stack[spi].spilled_ptr.type == SCALAR_VALUE || 7036 env->allow_ptr_leaks)) { 7037 if (clobber) { 7038 __mark_reg_unknown(env, &state->stack[spi].spilled_ptr); 7039 for (j = 0; j < BPF_REG_SIZE; j++) 7040 scrub_spilled_slot(&state->stack[spi].slot_type[j]); 7041 } 7042 goto mark; 7043 } 7044 7045 err: 7046 if (tnum_is_const(reg->var_off)) { 7047 verbose(env, "invalid%s read from stack R%d off %d+%d size %d\n", 7048 err_extra, regno, min_off, i - min_off, access_size); 7049 } else { 7050 char tn_buf[48]; 7051 7052 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 7053 verbose(env, "invalid%s read from stack R%d var_off %s+%d size %d\n", 7054 err_extra, regno, tn_buf, i - min_off, access_size); 7055 } 7056 return -EACCES; 7057 mark: 7058 /* reading any byte out of 8-byte 'spill_slot' will cause 7059 * the whole slot to be marked as 'read' 7060 */ 7061 mark_reg_read(env, &state->stack[spi].spilled_ptr, 7062 state->stack[spi].spilled_ptr.parent, 7063 REG_LIVE_READ64); 7064 /* We do not set REG_LIVE_WRITTEN for stack slot, as we can not 7065 * be sure that whether stack slot is written to or not. Hence, 7066 * we must still conservatively propagate reads upwards even if 7067 * helper may write to the entire memory range. 7068 */ 7069 } 7070 return update_stack_depth(env, state, min_off); 7071 } 7072 7073 static int check_helper_mem_access(struct bpf_verifier_env *env, int regno, 7074 int access_size, bool zero_size_allowed, 7075 struct bpf_call_arg_meta *meta) 7076 { 7077 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno]; 7078 u32 *max_access; 7079 7080 switch (base_type(reg->type)) { 7081 case PTR_TO_PACKET: 7082 case PTR_TO_PACKET_META: 7083 return check_packet_access(env, regno, reg->off, access_size, 7084 zero_size_allowed); 7085 case PTR_TO_MAP_KEY: 7086 if (meta && meta->raw_mode) { 7087 verbose(env, "R%d cannot write into %s\n", regno, 7088 reg_type_str(env, reg->type)); 7089 return -EACCES; 7090 } 7091 return check_mem_region_access(env, regno, reg->off, access_size, 7092 reg->map_ptr->key_size, false); 7093 case PTR_TO_MAP_VALUE: 7094 if (check_map_access_type(env, regno, reg->off, access_size, 7095 meta && meta->raw_mode ? BPF_WRITE : 7096 BPF_READ)) 7097 return -EACCES; 7098 return check_map_access(env, regno, reg->off, access_size, 7099 zero_size_allowed, ACCESS_HELPER); 7100 case PTR_TO_MEM: 7101 if (type_is_rdonly_mem(reg->type)) { 7102 if (meta && meta->raw_mode) { 7103 verbose(env, "R%d cannot write into %s\n", regno, 7104 reg_type_str(env, reg->type)); 7105 return -EACCES; 7106 } 7107 } 7108 return check_mem_region_access(env, regno, reg->off, 7109 access_size, reg->mem_size, 7110 zero_size_allowed); 7111 case PTR_TO_BUF: 7112 if (type_is_rdonly_mem(reg->type)) { 7113 if (meta && meta->raw_mode) { 7114 verbose(env, "R%d cannot write into %s\n", regno, 7115 reg_type_str(env, reg->type)); 7116 return -EACCES; 7117 } 7118 7119 max_access = &env->prog->aux->max_rdonly_access; 7120 } else { 7121 max_access = &env->prog->aux->max_rdwr_access; 7122 } 7123 return check_buffer_access(env, reg, regno, reg->off, 7124 access_size, zero_size_allowed, 7125 max_access); 7126 case PTR_TO_STACK: 7127 return check_stack_range_initialized( 7128 env, 7129 regno, reg->off, access_size, 7130 zero_size_allowed, ACCESS_HELPER, meta); 7131 case PTR_TO_BTF_ID: 7132 return check_ptr_to_btf_access(env, regs, regno, reg->off, 7133 access_size, BPF_READ, -1); 7134 case PTR_TO_CTX: 7135 /* in case the function doesn't know how to access the context, 7136 * (because we are in a program of type SYSCALL for example), we 7137 * can not statically check its size. 7138 * Dynamically check it now. 7139 */ 7140 if (!env->ops->convert_ctx_access) { 7141 enum bpf_access_type atype = meta && meta->raw_mode ? BPF_WRITE : BPF_READ; 7142 int offset = access_size - 1; 7143 7144 /* Allow zero-byte read from PTR_TO_CTX */ 7145 if (access_size == 0) 7146 return zero_size_allowed ? 0 : -EACCES; 7147 7148 return check_mem_access(env, env->insn_idx, regno, offset, BPF_B, 7149 atype, -1, false, false); 7150 } 7151 7152 fallthrough; 7153 default: /* scalar_value or invalid ptr */ 7154 /* Allow zero-byte read from NULL, regardless of pointer type */ 7155 if (zero_size_allowed && access_size == 0 && 7156 register_is_null(reg)) 7157 return 0; 7158 7159 verbose(env, "R%d type=%s ", regno, 7160 reg_type_str(env, reg->type)); 7161 verbose(env, "expected=%s\n", reg_type_str(env, PTR_TO_STACK)); 7162 return -EACCES; 7163 } 7164 } 7165 7166 static int check_mem_size_reg(struct bpf_verifier_env *env, 7167 struct bpf_reg_state *reg, u32 regno, 7168 bool zero_size_allowed, 7169 struct bpf_call_arg_meta *meta) 7170 { 7171 int err; 7172 7173 /* This is used to refine r0 return value bounds for helpers 7174 * that enforce this value as an upper bound on return values. 7175 * See do_refine_retval_range() for helpers that can refine 7176 * the return value. C type of helper is u32 so we pull register 7177 * bound from umax_value however, if negative verifier errors 7178 * out. Only upper bounds can be learned because retval is an 7179 * int type and negative retvals are allowed. 7180 */ 7181 meta->msize_max_value = reg->umax_value; 7182 7183 /* The register is SCALAR_VALUE; the access check 7184 * happens using its boundaries. 7185 */ 7186 if (!tnum_is_const(reg->var_off)) 7187 /* For unprivileged variable accesses, disable raw 7188 * mode so that the program is required to 7189 * initialize all the memory that the helper could 7190 * just partially fill up. 7191 */ 7192 meta = NULL; 7193 7194 if (reg->smin_value < 0) { 7195 verbose(env, "R%d min value is negative, either use unsigned or 'var &= const'\n", 7196 regno); 7197 return -EACCES; 7198 } 7199 7200 if (reg->umin_value == 0) { 7201 err = check_helper_mem_access(env, regno - 1, 0, 7202 zero_size_allowed, 7203 meta); 7204 if (err) 7205 return err; 7206 } 7207 7208 if (reg->umax_value >= BPF_MAX_VAR_SIZ) { 7209 verbose(env, "R%d unbounded memory access, use 'var &= const' or 'if (var < const)'\n", 7210 regno); 7211 return -EACCES; 7212 } 7213 err = check_helper_mem_access(env, regno - 1, 7214 reg->umax_value, 7215 zero_size_allowed, meta); 7216 if (!err) 7217 err = mark_chain_precision(env, regno); 7218 return err; 7219 } 7220 7221 int check_mem_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg, 7222 u32 regno, u32 mem_size) 7223 { 7224 bool may_be_null = type_may_be_null(reg->type); 7225 struct bpf_reg_state saved_reg; 7226 struct bpf_call_arg_meta meta; 7227 int err; 7228 7229 if (register_is_null(reg)) 7230 return 0; 7231 7232 memset(&meta, 0, sizeof(meta)); 7233 /* Assuming that the register contains a value check if the memory 7234 * access is safe. Temporarily save and restore the register's state as 7235 * the conversion shouldn't be visible to a caller. 7236 */ 7237 if (may_be_null) { 7238 saved_reg = *reg; 7239 mark_ptr_not_null_reg(reg); 7240 } 7241 7242 err = check_helper_mem_access(env, regno, mem_size, true, &meta); 7243 /* Check access for BPF_WRITE */ 7244 meta.raw_mode = true; 7245 err = err ?: check_helper_mem_access(env, regno, mem_size, true, &meta); 7246 7247 if (may_be_null) 7248 *reg = saved_reg; 7249 7250 return err; 7251 } 7252 7253 static int check_kfunc_mem_size_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg, 7254 u32 regno) 7255 { 7256 struct bpf_reg_state *mem_reg = &cur_regs(env)[regno - 1]; 7257 bool may_be_null = type_may_be_null(mem_reg->type); 7258 struct bpf_reg_state saved_reg; 7259 struct bpf_call_arg_meta meta; 7260 int err; 7261 7262 WARN_ON_ONCE(regno < BPF_REG_2 || regno > BPF_REG_5); 7263 7264 memset(&meta, 0, sizeof(meta)); 7265 7266 if (may_be_null) { 7267 saved_reg = *mem_reg; 7268 mark_ptr_not_null_reg(mem_reg); 7269 } 7270 7271 err = check_mem_size_reg(env, reg, regno, true, &meta); 7272 /* Check access for BPF_WRITE */ 7273 meta.raw_mode = true; 7274 err = err ?: check_mem_size_reg(env, reg, regno, true, &meta); 7275 7276 if (may_be_null) 7277 *mem_reg = saved_reg; 7278 return err; 7279 } 7280 7281 /* Implementation details: 7282 * bpf_map_lookup returns PTR_TO_MAP_VALUE_OR_NULL. 7283 * bpf_obj_new returns PTR_TO_BTF_ID | MEM_ALLOC | PTR_MAYBE_NULL. 7284 * Two bpf_map_lookups (even with the same key) will have different reg->id. 7285 * Two separate bpf_obj_new will also have different reg->id. 7286 * For traditional PTR_TO_MAP_VALUE or PTR_TO_BTF_ID | MEM_ALLOC, the verifier 7287 * clears reg->id after value_or_null->value transition, since the verifier only 7288 * cares about the range of access to valid map value pointer and doesn't care 7289 * about actual address of the map element. 7290 * For maps with 'struct bpf_spin_lock' inside map value the verifier keeps 7291 * reg->id > 0 after value_or_null->value transition. By doing so 7292 * two bpf_map_lookups will be considered two different pointers that 7293 * point to different bpf_spin_locks. Likewise for pointers to allocated objects 7294 * returned from bpf_obj_new. 7295 * The verifier allows taking only one bpf_spin_lock at a time to avoid 7296 * dead-locks. 7297 * Since only one bpf_spin_lock is allowed the checks are simpler than 7298 * reg_is_refcounted() logic. The verifier needs to remember only 7299 * one spin_lock instead of array of acquired_refs. 7300 * cur_state->active_lock remembers which map value element or allocated 7301 * object got locked and clears it after bpf_spin_unlock. 7302 */ 7303 static int process_spin_lock(struct bpf_verifier_env *env, int regno, 7304 bool is_lock) 7305 { 7306 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno]; 7307 struct bpf_verifier_state *cur = env->cur_state; 7308 bool is_const = tnum_is_const(reg->var_off); 7309 u64 val = reg->var_off.value; 7310 struct bpf_map *map = NULL; 7311 struct btf *btf = NULL; 7312 struct btf_record *rec; 7313 7314 if (!is_const) { 7315 verbose(env, 7316 "R%d doesn't have constant offset. bpf_spin_lock has to be at the constant offset\n", 7317 regno); 7318 return -EINVAL; 7319 } 7320 if (reg->type == PTR_TO_MAP_VALUE) { 7321 map = reg->map_ptr; 7322 if (!map->btf) { 7323 verbose(env, 7324 "map '%s' has to have BTF in order to use bpf_spin_lock\n", 7325 map->name); 7326 return -EINVAL; 7327 } 7328 } else { 7329 btf = reg->btf; 7330 } 7331 7332 rec = reg_btf_record(reg); 7333 if (!btf_record_has_field(rec, BPF_SPIN_LOCK)) { 7334 verbose(env, "%s '%s' has no valid bpf_spin_lock\n", map ? "map" : "local", 7335 map ? map->name : "kptr"); 7336 return -EINVAL; 7337 } 7338 if (rec->spin_lock_off != val + reg->off) { 7339 verbose(env, "off %lld doesn't point to 'struct bpf_spin_lock' that is at %d\n", 7340 val + reg->off, rec->spin_lock_off); 7341 return -EINVAL; 7342 } 7343 if (is_lock) { 7344 if (cur->active_lock.ptr) { 7345 verbose(env, 7346 "Locking two bpf_spin_locks are not allowed\n"); 7347 return -EINVAL; 7348 } 7349 if (map) 7350 cur->active_lock.ptr = map; 7351 else 7352 cur->active_lock.ptr = btf; 7353 cur->active_lock.id = reg->id; 7354 } else { 7355 void *ptr; 7356 7357 if (map) 7358 ptr = map; 7359 else 7360 ptr = btf; 7361 7362 if (!cur->active_lock.ptr) { 7363 verbose(env, "bpf_spin_unlock without taking a lock\n"); 7364 return -EINVAL; 7365 } 7366 if (cur->active_lock.ptr != ptr || 7367 cur->active_lock.id != reg->id) { 7368 verbose(env, "bpf_spin_unlock of different lock\n"); 7369 return -EINVAL; 7370 } 7371 7372 invalidate_non_owning_refs(env); 7373 7374 cur->active_lock.ptr = NULL; 7375 cur->active_lock.id = 0; 7376 } 7377 return 0; 7378 } 7379 7380 static int process_timer_func(struct bpf_verifier_env *env, int regno, 7381 struct bpf_call_arg_meta *meta) 7382 { 7383 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno]; 7384 bool is_const = tnum_is_const(reg->var_off); 7385 struct bpf_map *map = reg->map_ptr; 7386 u64 val = reg->var_off.value; 7387 7388 if (!is_const) { 7389 verbose(env, 7390 "R%d doesn't have constant offset. bpf_timer has to be at the constant offset\n", 7391 regno); 7392 return -EINVAL; 7393 } 7394 if (!map->btf) { 7395 verbose(env, "map '%s' has to have BTF in order to use bpf_timer\n", 7396 map->name); 7397 return -EINVAL; 7398 } 7399 if (!btf_record_has_field(map->record, BPF_TIMER)) { 7400 verbose(env, "map '%s' has no valid bpf_timer\n", map->name); 7401 return -EINVAL; 7402 } 7403 if (map->record->timer_off != val + reg->off) { 7404 verbose(env, "off %lld doesn't point to 'struct bpf_timer' that is at %d\n", 7405 val + reg->off, map->record->timer_off); 7406 return -EINVAL; 7407 } 7408 if (meta->map_ptr) { 7409 verbose(env, "verifier bug. Two map pointers in a timer helper\n"); 7410 return -EFAULT; 7411 } 7412 meta->map_uid = reg->map_uid; 7413 meta->map_ptr = map; 7414 return 0; 7415 } 7416 7417 static int process_kptr_func(struct bpf_verifier_env *env, int regno, 7418 struct bpf_call_arg_meta *meta) 7419 { 7420 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno]; 7421 struct bpf_map *map_ptr = reg->map_ptr; 7422 struct btf_field *kptr_field; 7423 u32 kptr_off; 7424 7425 if (!tnum_is_const(reg->var_off)) { 7426 verbose(env, 7427 "R%d doesn't have constant offset. kptr has to be at the constant offset\n", 7428 regno); 7429 return -EINVAL; 7430 } 7431 if (!map_ptr->btf) { 7432 verbose(env, "map '%s' has to have BTF in order to use bpf_kptr_xchg\n", 7433 map_ptr->name); 7434 return -EINVAL; 7435 } 7436 if (!btf_record_has_field(map_ptr->record, BPF_KPTR)) { 7437 verbose(env, "map '%s' has no valid kptr\n", map_ptr->name); 7438 return -EINVAL; 7439 } 7440 7441 meta->map_ptr = map_ptr; 7442 kptr_off = reg->off + reg->var_off.value; 7443 kptr_field = btf_record_find(map_ptr->record, kptr_off, BPF_KPTR); 7444 if (!kptr_field) { 7445 verbose(env, "off=%d doesn't point to kptr\n", kptr_off); 7446 return -EACCES; 7447 } 7448 if (kptr_field->type != BPF_KPTR_REF && kptr_field->type != BPF_KPTR_PERCPU) { 7449 verbose(env, "off=%d kptr isn't referenced kptr\n", kptr_off); 7450 return -EACCES; 7451 } 7452 meta->kptr_field = kptr_field; 7453 return 0; 7454 } 7455 7456 /* There are two register types representing a bpf_dynptr, one is PTR_TO_STACK 7457 * which points to a stack slot, and the other is CONST_PTR_TO_DYNPTR. 7458 * 7459 * In both cases we deal with the first 8 bytes, but need to mark the next 8 7460 * bytes as STACK_DYNPTR in case of PTR_TO_STACK. In case of 7461 * CONST_PTR_TO_DYNPTR, we are guaranteed to get the beginning of the object. 7462 * 7463 * Mutability of bpf_dynptr is at two levels, one is at the level of struct 7464 * bpf_dynptr itself, i.e. whether the helper is receiving a pointer to struct 7465 * bpf_dynptr or pointer to const struct bpf_dynptr. In the former case, it can 7466 * mutate the view of the dynptr and also possibly destroy it. In the latter 7467 * case, it cannot mutate the bpf_dynptr itself but it can still mutate the 7468 * memory that dynptr points to. 7469 * 7470 * The verifier will keep track both levels of mutation (bpf_dynptr's in 7471 * reg->type and the memory's in reg->dynptr.type), but there is no support for 7472 * readonly dynptr view yet, hence only the first case is tracked and checked. 7473 * 7474 * This is consistent with how C applies the const modifier to a struct object, 7475 * where the pointer itself inside bpf_dynptr becomes const but not what it 7476 * points to. 7477 * 7478 * Helpers which do not mutate the bpf_dynptr set MEM_RDONLY in their argument 7479 * type, and declare it as 'const struct bpf_dynptr *' in their prototype. 7480 */ 7481 static int process_dynptr_func(struct bpf_verifier_env *env, int regno, int insn_idx, 7482 enum bpf_arg_type arg_type, int clone_ref_obj_id) 7483 { 7484 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno]; 7485 int err; 7486 7487 /* MEM_UNINIT and MEM_RDONLY are exclusive, when applied to an 7488 * ARG_PTR_TO_DYNPTR (or ARG_PTR_TO_DYNPTR | DYNPTR_TYPE_*): 7489 */ 7490 if ((arg_type & (MEM_UNINIT | MEM_RDONLY)) == (MEM_UNINIT | MEM_RDONLY)) { 7491 verbose(env, "verifier internal error: misconfigured dynptr helper type flags\n"); 7492 return -EFAULT; 7493 } 7494 7495 /* MEM_UNINIT - Points to memory that is an appropriate candidate for 7496 * constructing a mutable bpf_dynptr object. 7497 * 7498 * Currently, this is only possible with PTR_TO_STACK 7499 * pointing to a region of at least 16 bytes which doesn't 7500 * contain an existing bpf_dynptr. 7501 * 7502 * MEM_RDONLY - Points to a initialized bpf_dynptr that will not be 7503 * mutated or destroyed. However, the memory it points to 7504 * may be mutated. 7505 * 7506 * None - Points to a initialized dynptr that can be mutated and 7507 * destroyed, including mutation of the memory it points 7508 * to. 7509 */ 7510 if (arg_type & MEM_UNINIT) { 7511 int i; 7512 7513 if (!is_dynptr_reg_valid_uninit(env, reg)) { 7514 verbose(env, "Dynptr has to be an uninitialized dynptr\n"); 7515 return -EINVAL; 7516 } 7517 7518 /* we write BPF_DW bits (8 bytes) at a time */ 7519 for (i = 0; i < BPF_DYNPTR_SIZE; i += 8) { 7520 err = check_mem_access(env, insn_idx, regno, 7521 i, BPF_DW, BPF_WRITE, -1, false, false); 7522 if (err) 7523 return err; 7524 } 7525 7526 err = mark_stack_slots_dynptr(env, reg, arg_type, insn_idx, clone_ref_obj_id); 7527 } else /* MEM_RDONLY and None case from above */ { 7528 /* For the reg->type == PTR_TO_STACK case, bpf_dynptr is never const */ 7529 if (reg->type == CONST_PTR_TO_DYNPTR && !(arg_type & MEM_RDONLY)) { 7530 verbose(env, "cannot pass pointer to const bpf_dynptr, the helper mutates it\n"); 7531 return -EINVAL; 7532 } 7533 7534 if (!is_dynptr_reg_valid_init(env, reg)) { 7535 verbose(env, 7536 "Expected an initialized dynptr as arg #%d\n", 7537 regno); 7538 return -EINVAL; 7539 } 7540 7541 /* Fold modifiers (in this case, MEM_RDONLY) when checking expected type */ 7542 if (!is_dynptr_type_expected(env, reg, arg_type & ~MEM_RDONLY)) { 7543 verbose(env, 7544 "Expected a dynptr of type %s as arg #%d\n", 7545 dynptr_type_str(arg_to_dynptr_type(arg_type)), regno); 7546 return -EINVAL; 7547 } 7548 7549 err = mark_dynptr_read(env, reg); 7550 } 7551 return err; 7552 } 7553 7554 static u32 iter_ref_obj_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg, int spi) 7555 { 7556 struct bpf_func_state *state = func(env, reg); 7557 7558 return state->stack[spi].spilled_ptr.ref_obj_id; 7559 } 7560 7561 static bool is_iter_kfunc(struct bpf_kfunc_call_arg_meta *meta) 7562 { 7563 return meta->kfunc_flags & (KF_ITER_NEW | KF_ITER_NEXT | KF_ITER_DESTROY); 7564 } 7565 7566 static bool is_iter_new_kfunc(struct bpf_kfunc_call_arg_meta *meta) 7567 { 7568 return meta->kfunc_flags & KF_ITER_NEW; 7569 } 7570 7571 static bool is_iter_next_kfunc(struct bpf_kfunc_call_arg_meta *meta) 7572 { 7573 return meta->kfunc_flags & KF_ITER_NEXT; 7574 } 7575 7576 static bool is_iter_destroy_kfunc(struct bpf_kfunc_call_arg_meta *meta) 7577 { 7578 return meta->kfunc_flags & KF_ITER_DESTROY; 7579 } 7580 7581 static bool is_kfunc_arg_iter(struct bpf_kfunc_call_arg_meta *meta, int arg) 7582 { 7583 /* btf_check_iter_kfuncs() guarantees that first argument of any iter 7584 * kfunc is iter state pointer 7585 */ 7586 return arg == 0 && is_iter_kfunc(meta); 7587 } 7588 7589 static int process_iter_arg(struct bpf_verifier_env *env, int regno, int insn_idx, 7590 struct bpf_kfunc_call_arg_meta *meta) 7591 { 7592 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno]; 7593 const struct btf_type *t; 7594 const struct btf_param *arg; 7595 int spi, err, i, nr_slots; 7596 u32 btf_id; 7597 7598 /* btf_check_iter_kfuncs() ensures we don't need to validate anything here */ 7599 arg = &btf_params(meta->func_proto)[0]; 7600 t = btf_type_skip_modifiers(meta->btf, arg->type, NULL); /* PTR */ 7601 t = btf_type_skip_modifiers(meta->btf, t->type, &btf_id); /* STRUCT */ 7602 nr_slots = t->size / BPF_REG_SIZE; 7603 7604 if (is_iter_new_kfunc(meta)) { 7605 /* bpf_iter_<type>_new() expects pointer to uninit iter state */ 7606 if (!is_iter_reg_valid_uninit(env, reg, nr_slots)) { 7607 verbose(env, "expected uninitialized iter_%s as arg #%d\n", 7608 iter_type_str(meta->btf, btf_id), regno); 7609 return -EINVAL; 7610 } 7611 7612 for (i = 0; i < nr_slots * 8; i += BPF_REG_SIZE) { 7613 err = check_mem_access(env, insn_idx, regno, 7614 i, BPF_DW, BPF_WRITE, -1, false, false); 7615 if (err) 7616 return err; 7617 } 7618 7619 err = mark_stack_slots_iter(env, reg, insn_idx, meta->btf, btf_id, nr_slots); 7620 if (err) 7621 return err; 7622 } else { 7623 /* iter_next() or iter_destroy() expect initialized iter state*/ 7624 if (!is_iter_reg_valid_init(env, reg, meta->btf, btf_id, nr_slots)) { 7625 verbose(env, "expected an initialized iter_%s as arg #%d\n", 7626 iter_type_str(meta->btf, btf_id), regno); 7627 return -EINVAL; 7628 } 7629 7630 spi = iter_get_spi(env, reg, nr_slots); 7631 if (spi < 0) 7632 return spi; 7633 7634 err = mark_iter_read(env, reg, spi, nr_slots); 7635 if (err) 7636 return err; 7637 7638 /* remember meta->iter info for process_iter_next_call() */ 7639 meta->iter.spi = spi; 7640 meta->iter.frameno = reg->frameno; 7641 meta->ref_obj_id = iter_ref_obj_id(env, reg, spi); 7642 7643 if (is_iter_destroy_kfunc(meta)) { 7644 err = unmark_stack_slots_iter(env, reg, nr_slots); 7645 if (err) 7646 return err; 7647 } 7648 } 7649 7650 return 0; 7651 } 7652 7653 /* process_iter_next_call() is called when verifier gets to iterator's next 7654 * "method" (e.g., bpf_iter_num_next() for numbers iterator) call. We'll refer 7655 * to it as just "iter_next()" in comments below. 7656 * 7657 * BPF verifier relies on a crucial contract for any iter_next() 7658 * implementation: it should *eventually* return NULL, and once that happens 7659 * it should keep returning NULL. That is, once iterator exhausts elements to 7660 * iterate, it should never reset or spuriously return new elements. 7661 * 7662 * With the assumption of such contract, process_iter_next_call() simulates 7663 * a fork in the verifier state to validate loop logic correctness and safety 7664 * without having to simulate infinite amount of iterations. 7665 * 7666 * In current state, we first assume that iter_next() returned NULL and 7667 * iterator state is set to DRAINED (BPF_ITER_STATE_DRAINED). In such 7668 * conditions we should not form an infinite loop and should eventually reach 7669 * exit. 7670 * 7671 * Besides that, we also fork current state and enqueue it for later 7672 * verification. In a forked state we keep iterator state as ACTIVE 7673 * (BPF_ITER_STATE_ACTIVE) and assume non-NULL return from iter_next(). We 7674 * also bump iteration depth to prevent erroneous infinite loop detection 7675 * later on (see iter_active_depths_differ() comment for details). In this 7676 * state we assume that we'll eventually loop back to another iter_next() 7677 * calls (it could be in exactly same location or in some other instruction, 7678 * it doesn't matter, we don't make any unnecessary assumptions about this, 7679 * everything revolves around iterator state in a stack slot, not which 7680 * instruction is calling iter_next()). When that happens, we either will come 7681 * to iter_next() with equivalent state and can conclude that next iteration 7682 * will proceed in exactly the same way as we just verified, so it's safe to 7683 * assume that loop converges. If not, we'll go on another iteration 7684 * simulation with a different input state, until all possible starting states 7685 * are validated or we reach maximum number of instructions limit. 7686 * 7687 * This way, we will either exhaustively discover all possible input states 7688 * that iterator loop can start with and eventually will converge, or we'll 7689 * effectively regress into bounded loop simulation logic and either reach 7690 * maximum number of instructions if loop is not provably convergent, or there 7691 * is some statically known limit on number of iterations (e.g., if there is 7692 * an explicit `if n > 100 then break;` statement somewhere in the loop). 7693 * 7694 * One very subtle but very important aspect is that we *always* simulate NULL 7695 * condition first (as the current state) before we simulate non-NULL case. 7696 * This has to do with intricacies of scalar precision tracking. By simulating 7697 * "exit condition" of iter_next() returning NULL first, we make sure all the 7698 * relevant precision marks *that will be set **after** we exit iterator loop* 7699 * are propagated backwards to common parent state of NULL and non-NULL 7700 * branches. Thanks to that, state equivalence checks done later in forked 7701 * state, when reaching iter_next() for ACTIVE iterator, can assume that 7702 * precision marks are finalized and won't change. Because simulating another 7703 * ACTIVE iterator iteration won't change them (because given same input 7704 * states we'll end up with exactly same output states which we are currently 7705 * comparing; and verification after the loop already propagated back what 7706 * needs to be **additionally** tracked as precise). It's subtle, grok 7707 * precision tracking for more intuitive understanding. 7708 */ 7709 static int process_iter_next_call(struct bpf_verifier_env *env, int insn_idx, 7710 struct bpf_kfunc_call_arg_meta *meta) 7711 { 7712 struct bpf_verifier_state *cur_st = env->cur_state, *queued_st; 7713 struct bpf_func_state *cur_fr = cur_st->frame[cur_st->curframe], *queued_fr; 7714 struct bpf_reg_state *cur_iter, *queued_iter; 7715 int iter_frameno = meta->iter.frameno; 7716 int iter_spi = meta->iter.spi; 7717 7718 BTF_TYPE_EMIT(struct bpf_iter); 7719 7720 cur_iter = &env->cur_state->frame[iter_frameno]->stack[iter_spi].spilled_ptr; 7721 7722 if (cur_iter->iter.state != BPF_ITER_STATE_ACTIVE && 7723 cur_iter->iter.state != BPF_ITER_STATE_DRAINED) { 7724 verbose(env, "verifier internal error: unexpected iterator state %d (%s)\n", 7725 cur_iter->iter.state, iter_state_str(cur_iter->iter.state)); 7726 return -EFAULT; 7727 } 7728 7729 if (cur_iter->iter.state == BPF_ITER_STATE_ACTIVE) { 7730 /* branch out active iter state */ 7731 queued_st = push_stack(env, insn_idx + 1, insn_idx, false); 7732 if (!queued_st) 7733 return -ENOMEM; 7734 7735 queued_iter = &queued_st->frame[iter_frameno]->stack[iter_spi].spilled_ptr; 7736 queued_iter->iter.state = BPF_ITER_STATE_ACTIVE; 7737 queued_iter->iter.depth++; 7738 7739 queued_fr = queued_st->frame[queued_st->curframe]; 7740 mark_ptr_not_null_reg(&queued_fr->regs[BPF_REG_0]); 7741 } 7742 7743 /* switch to DRAINED state, but keep the depth unchanged */ 7744 /* mark current iter state as drained and assume returned NULL */ 7745 cur_iter->iter.state = BPF_ITER_STATE_DRAINED; 7746 __mark_reg_const_zero(&cur_fr->regs[BPF_REG_0]); 7747 7748 return 0; 7749 } 7750 7751 static bool arg_type_is_mem_size(enum bpf_arg_type type) 7752 { 7753 return type == ARG_CONST_SIZE || 7754 type == ARG_CONST_SIZE_OR_ZERO; 7755 } 7756 7757 static bool arg_type_is_release(enum bpf_arg_type type) 7758 { 7759 return type & OBJ_RELEASE; 7760 } 7761 7762 static bool arg_type_is_dynptr(enum bpf_arg_type type) 7763 { 7764 return base_type(type) == ARG_PTR_TO_DYNPTR; 7765 } 7766 7767 static int int_ptr_type_to_size(enum bpf_arg_type type) 7768 { 7769 if (type == ARG_PTR_TO_INT) 7770 return sizeof(u32); 7771 else if (type == ARG_PTR_TO_LONG) 7772 return sizeof(u64); 7773 7774 return -EINVAL; 7775 } 7776 7777 static int resolve_map_arg_type(struct bpf_verifier_env *env, 7778 const struct bpf_call_arg_meta *meta, 7779 enum bpf_arg_type *arg_type) 7780 { 7781 if (!meta->map_ptr) { 7782 /* kernel subsystem misconfigured verifier */ 7783 verbose(env, "invalid map_ptr to access map->type\n"); 7784 return -EACCES; 7785 } 7786 7787 switch (meta->map_ptr->map_type) { 7788 case BPF_MAP_TYPE_SOCKMAP: 7789 case BPF_MAP_TYPE_SOCKHASH: 7790 if (*arg_type == ARG_PTR_TO_MAP_VALUE) { 7791 *arg_type = ARG_PTR_TO_BTF_ID_SOCK_COMMON; 7792 } else { 7793 verbose(env, "invalid arg_type for sockmap/sockhash\n"); 7794 return -EINVAL; 7795 } 7796 break; 7797 case BPF_MAP_TYPE_BLOOM_FILTER: 7798 if (meta->func_id == BPF_FUNC_map_peek_elem) 7799 *arg_type = ARG_PTR_TO_MAP_VALUE; 7800 break; 7801 default: 7802 break; 7803 } 7804 return 0; 7805 } 7806 7807 struct bpf_reg_types { 7808 const enum bpf_reg_type types[10]; 7809 u32 *btf_id; 7810 }; 7811 7812 static const struct bpf_reg_types sock_types = { 7813 .types = { 7814 PTR_TO_SOCK_COMMON, 7815 PTR_TO_SOCKET, 7816 PTR_TO_TCP_SOCK, 7817 PTR_TO_XDP_SOCK, 7818 }, 7819 }; 7820 7821 #ifdef CONFIG_NET 7822 static const struct bpf_reg_types btf_id_sock_common_types = { 7823 .types = { 7824 PTR_TO_SOCK_COMMON, 7825 PTR_TO_SOCKET, 7826 PTR_TO_TCP_SOCK, 7827 PTR_TO_XDP_SOCK, 7828 PTR_TO_BTF_ID, 7829 PTR_TO_BTF_ID | PTR_TRUSTED, 7830 }, 7831 .btf_id = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON], 7832 }; 7833 #endif 7834 7835 static const struct bpf_reg_types mem_types = { 7836 .types = { 7837 PTR_TO_STACK, 7838 PTR_TO_PACKET, 7839 PTR_TO_PACKET_META, 7840 PTR_TO_MAP_KEY, 7841 PTR_TO_MAP_VALUE, 7842 PTR_TO_MEM, 7843 PTR_TO_MEM | MEM_RINGBUF, 7844 PTR_TO_BUF, 7845 PTR_TO_BTF_ID | PTR_TRUSTED, 7846 }, 7847 }; 7848 7849 static const struct bpf_reg_types int_ptr_types = { 7850 .types = { 7851 PTR_TO_STACK, 7852 PTR_TO_PACKET, 7853 PTR_TO_PACKET_META, 7854 PTR_TO_MAP_KEY, 7855 PTR_TO_MAP_VALUE, 7856 }, 7857 }; 7858 7859 static const struct bpf_reg_types spin_lock_types = { 7860 .types = { 7861 PTR_TO_MAP_VALUE, 7862 PTR_TO_BTF_ID | MEM_ALLOC, 7863 } 7864 }; 7865 7866 static const struct bpf_reg_types fullsock_types = { .types = { PTR_TO_SOCKET } }; 7867 static const struct bpf_reg_types scalar_types = { .types = { SCALAR_VALUE } }; 7868 static const struct bpf_reg_types context_types = { .types = { PTR_TO_CTX } }; 7869 static const struct bpf_reg_types ringbuf_mem_types = { .types = { PTR_TO_MEM | MEM_RINGBUF } }; 7870 static const struct bpf_reg_types const_map_ptr_types = { .types = { CONST_PTR_TO_MAP } }; 7871 static const struct bpf_reg_types btf_ptr_types = { 7872 .types = { 7873 PTR_TO_BTF_ID, 7874 PTR_TO_BTF_ID | PTR_TRUSTED, 7875 PTR_TO_BTF_ID | MEM_RCU, 7876 }, 7877 }; 7878 static const struct bpf_reg_types percpu_btf_ptr_types = { 7879 .types = { 7880 PTR_TO_BTF_ID | MEM_PERCPU, 7881 PTR_TO_BTF_ID | MEM_PERCPU | MEM_RCU, 7882 PTR_TO_BTF_ID | MEM_PERCPU | PTR_TRUSTED, 7883 } 7884 }; 7885 static const struct bpf_reg_types func_ptr_types = { .types = { PTR_TO_FUNC } }; 7886 static const struct bpf_reg_types stack_ptr_types = { .types = { PTR_TO_STACK } }; 7887 static const struct bpf_reg_types const_str_ptr_types = { .types = { PTR_TO_MAP_VALUE } }; 7888 static const struct bpf_reg_types timer_types = { .types = { PTR_TO_MAP_VALUE } }; 7889 static const struct bpf_reg_types kptr_types = { .types = { PTR_TO_MAP_VALUE } }; 7890 static const struct bpf_reg_types dynptr_types = { 7891 .types = { 7892 PTR_TO_STACK, 7893 CONST_PTR_TO_DYNPTR, 7894 } 7895 }; 7896 7897 static const struct bpf_reg_types *compatible_reg_types[__BPF_ARG_TYPE_MAX] = { 7898 [ARG_PTR_TO_MAP_KEY] = &mem_types, 7899 [ARG_PTR_TO_MAP_VALUE] = &mem_types, 7900 [ARG_CONST_SIZE] = &scalar_types, 7901 [ARG_CONST_SIZE_OR_ZERO] = &scalar_types, 7902 [ARG_CONST_ALLOC_SIZE_OR_ZERO] = &scalar_types, 7903 [ARG_CONST_MAP_PTR] = &const_map_ptr_types, 7904 [ARG_PTR_TO_CTX] = &context_types, 7905 [ARG_PTR_TO_SOCK_COMMON] = &sock_types, 7906 #ifdef CONFIG_NET 7907 [ARG_PTR_TO_BTF_ID_SOCK_COMMON] = &btf_id_sock_common_types, 7908 #endif 7909 [ARG_PTR_TO_SOCKET] = &fullsock_types, 7910 [ARG_PTR_TO_BTF_ID] = &btf_ptr_types, 7911 [ARG_PTR_TO_SPIN_LOCK] = &spin_lock_types, 7912 [ARG_PTR_TO_MEM] = &mem_types, 7913 [ARG_PTR_TO_RINGBUF_MEM] = &ringbuf_mem_types, 7914 [ARG_PTR_TO_INT] = &int_ptr_types, 7915 [ARG_PTR_TO_LONG] = &int_ptr_types, 7916 [ARG_PTR_TO_PERCPU_BTF_ID] = &percpu_btf_ptr_types, 7917 [ARG_PTR_TO_FUNC] = &func_ptr_types, 7918 [ARG_PTR_TO_STACK] = &stack_ptr_types, 7919 [ARG_PTR_TO_CONST_STR] = &const_str_ptr_types, 7920 [ARG_PTR_TO_TIMER] = &timer_types, 7921 [ARG_PTR_TO_KPTR] = &kptr_types, 7922 [ARG_PTR_TO_DYNPTR] = &dynptr_types, 7923 }; 7924 7925 static int check_reg_type(struct bpf_verifier_env *env, u32 regno, 7926 enum bpf_arg_type arg_type, 7927 const u32 *arg_btf_id, 7928 struct bpf_call_arg_meta *meta) 7929 { 7930 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno]; 7931 enum bpf_reg_type expected, type = reg->type; 7932 const struct bpf_reg_types *compatible; 7933 int i, j; 7934 7935 compatible = compatible_reg_types[base_type(arg_type)]; 7936 if (!compatible) { 7937 verbose(env, "verifier internal error: unsupported arg type %d\n", arg_type); 7938 return -EFAULT; 7939 } 7940 7941 /* ARG_PTR_TO_MEM + RDONLY is compatible with PTR_TO_MEM and PTR_TO_MEM + RDONLY, 7942 * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM and NOT with PTR_TO_MEM + RDONLY 7943 * 7944 * Same for MAYBE_NULL: 7945 * 7946 * ARG_PTR_TO_MEM + MAYBE_NULL is compatible with PTR_TO_MEM and PTR_TO_MEM + MAYBE_NULL, 7947 * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM but NOT with PTR_TO_MEM + MAYBE_NULL 7948 * 7949 * ARG_PTR_TO_MEM is compatible with PTR_TO_MEM that is tagged with a dynptr type. 7950 * 7951 * Therefore we fold these flags depending on the arg_type before comparison. 7952 */ 7953 if (arg_type & MEM_RDONLY) 7954 type &= ~MEM_RDONLY; 7955 if (arg_type & PTR_MAYBE_NULL) 7956 type &= ~PTR_MAYBE_NULL; 7957 if (base_type(arg_type) == ARG_PTR_TO_MEM) 7958 type &= ~DYNPTR_TYPE_FLAG_MASK; 7959 7960 if (meta->func_id == BPF_FUNC_kptr_xchg && type_is_alloc(type)) { 7961 type &= ~MEM_ALLOC; 7962 type &= ~MEM_PERCPU; 7963 } 7964 7965 for (i = 0; i < ARRAY_SIZE(compatible->types); i++) { 7966 expected = compatible->types[i]; 7967 if (expected == NOT_INIT) 7968 break; 7969 7970 if (type == expected) 7971 goto found; 7972 } 7973 7974 verbose(env, "R%d type=%s expected=", regno, reg_type_str(env, reg->type)); 7975 for (j = 0; j + 1 < i; j++) 7976 verbose(env, "%s, ", reg_type_str(env, compatible->types[j])); 7977 verbose(env, "%s\n", reg_type_str(env, compatible->types[j])); 7978 return -EACCES; 7979 7980 found: 7981 if (base_type(reg->type) != PTR_TO_BTF_ID) 7982 return 0; 7983 7984 if (compatible == &mem_types) { 7985 if (!(arg_type & MEM_RDONLY)) { 7986 verbose(env, 7987 "%s() may write into memory pointed by R%d type=%s\n", 7988 func_id_name(meta->func_id), 7989 regno, reg_type_str(env, reg->type)); 7990 return -EACCES; 7991 } 7992 return 0; 7993 } 7994 7995 switch ((int)reg->type) { 7996 case PTR_TO_BTF_ID: 7997 case PTR_TO_BTF_ID | PTR_TRUSTED: 7998 case PTR_TO_BTF_ID | MEM_RCU: 7999 case PTR_TO_BTF_ID | PTR_MAYBE_NULL: 8000 case PTR_TO_BTF_ID | PTR_MAYBE_NULL | MEM_RCU: 8001 { 8002 /* For bpf_sk_release, it needs to match against first member 8003 * 'struct sock_common', hence make an exception for it. This 8004 * allows bpf_sk_release to work for multiple socket types. 8005 */ 8006 bool strict_type_match = arg_type_is_release(arg_type) && 8007 meta->func_id != BPF_FUNC_sk_release; 8008 8009 if (type_may_be_null(reg->type) && 8010 (!type_may_be_null(arg_type) || arg_type_is_release(arg_type))) { 8011 verbose(env, "Possibly NULL pointer passed to helper arg%d\n", regno); 8012 return -EACCES; 8013 } 8014 8015 if (!arg_btf_id) { 8016 if (!compatible->btf_id) { 8017 verbose(env, "verifier internal error: missing arg compatible BTF ID\n"); 8018 return -EFAULT; 8019 } 8020 arg_btf_id = compatible->btf_id; 8021 } 8022 8023 if (meta->func_id == BPF_FUNC_kptr_xchg) { 8024 if (map_kptr_match_type(env, meta->kptr_field, reg, regno)) 8025 return -EACCES; 8026 } else { 8027 if (arg_btf_id == BPF_PTR_POISON) { 8028 verbose(env, "verifier internal error:"); 8029 verbose(env, "R%d has non-overwritten BPF_PTR_POISON type\n", 8030 regno); 8031 return -EACCES; 8032 } 8033 8034 if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off, 8035 btf_vmlinux, *arg_btf_id, 8036 strict_type_match)) { 8037 verbose(env, "R%d is of type %s but %s is expected\n", 8038 regno, btf_type_name(reg->btf, reg->btf_id), 8039 btf_type_name(btf_vmlinux, *arg_btf_id)); 8040 return -EACCES; 8041 } 8042 } 8043 break; 8044 } 8045 case PTR_TO_BTF_ID | MEM_ALLOC: 8046 case PTR_TO_BTF_ID | MEM_PERCPU | MEM_ALLOC: 8047 if (meta->func_id != BPF_FUNC_spin_lock && meta->func_id != BPF_FUNC_spin_unlock && 8048 meta->func_id != BPF_FUNC_kptr_xchg) { 8049 verbose(env, "verifier internal error: unimplemented handling of MEM_ALLOC\n"); 8050 return -EFAULT; 8051 } 8052 if (meta->func_id == BPF_FUNC_kptr_xchg) { 8053 if (map_kptr_match_type(env, meta->kptr_field, reg, regno)) 8054 return -EACCES; 8055 } 8056 break; 8057 case PTR_TO_BTF_ID | MEM_PERCPU: 8058 case PTR_TO_BTF_ID | MEM_PERCPU | MEM_RCU: 8059 case PTR_TO_BTF_ID | MEM_PERCPU | PTR_TRUSTED: 8060 /* Handled by helper specific checks */ 8061 break; 8062 default: 8063 verbose(env, "verifier internal error: invalid PTR_TO_BTF_ID register for type match\n"); 8064 return -EFAULT; 8065 } 8066 return 0; 8067 } 8068 8069 static struct btf_field * 8070 reg_find_field_offset(const struct bpf_reg_state *reg, s32 off, u32 fields) 8071 { 8072 struct btf_field *field; 8073 struct btf_record *rec; 8074 8075 rec = reg_btf_record(reg); 8076 if (!rec) 8077 return NULL; 8078 8079 field = btf_record_find(rec, off, fields); 8080 if (!field) 8081 return NULL; 8082 8083 return field; 8084 } 8085 8086 int check_func_arg_reg_off(struct bpf_verifier_env *env, 8087 const struct bpf_reg_state *reg, int regno, 8088 enum bpf_arg_type arg_type) 8089 { 8090 u32 type = reg->type; 8091 8092 /* When referenced register is passed to release function, its fixed 8093 * offset must be 0. 8094 * 8095 * We will check arg_type_is_release reg has ref_obj_id when storing 8096 * meta->release_regno. 8097 */ 8098 if (arg_type_is_release(arg_type)) { 8099 /* ARG_PTR_TO_DYNPTR with OBJ_RELEASE is a bit special, as it 8100 * may not directly point to the object being released, but to 8101 * dynptr pointing to such object, which might be at some offset 8102 * on the stack. In that case, we simply to fallback to the 8103 * default handling. 8104 */ 8105 if (arg_type_is_dynptr(arg_type) && type == PTR_TO_STACK) 8106 return 0; 8107 8108 /* Doing check_ptr_off_reg check for the offset will catch this 8109 * because fixed_off_ok is false, but checking here allows us 8110 * to give the user a better error message. 8111 */ 8112 if (reg->off) { 8113 verbose(env, "R%d must have zero offset when passed to release func or trusted arg to kfunc\n", 8114 regno); 8115 return -EINVAL; 8116 } 8117 return __check_ptr_off_reg(env, reg, regno, false); 8118 } 8119 8120 switch (type) { 8121 /* Pointer types where both fixed and variable offset is explicitly allowed: */ 8122 case PTR_TO_STACK: 8123 case PTR_TO_PACKET: 8124 case PTR_TO_PACKET_META: 8125 case PTR_TO_MAP_KEY: 8126 case PTR_TO_MAP_VALUE: 8127 case PTR_TO_MEM: 8128 case PTR_TO_MEM | MEM_RDONLY: 8129 case PTR_TO_MEM | MEM_RINGBUF: 8130 case PTR_TO_BUF: 8131 case PTR_TO_BUF | MEM_RDONLY: 8132 case SCALAR_VALUE: 8133 return 0; 8134 /* All the rest must be rejected, except PTR_TO_BTF_ID which allows 8135 * fixed offset. 8136 */ 8137 case PTR_TO_BTF_ID: 8138 case PTR_TO_BTF_ID | MEM_ALLOC: 8139 case PTR_TO_BTF_ID | PTR_TRUSTED: 8140 case PTR_TO_BTF_ID | MEM_RCU: 8141 case PTR_TO_BTF_ID | MEM_ALLOC | NON_OWN_REF: 8142 case PTR_TO_BTF_ID | MEM_ALLOC | NON_OWN_REF | MEM_RCU: 8143 /* When referenced PTR_TO_BTF_ID is passed to release function, 8144 * its fixed offset must be 0. In the other cases, fixed offset 8145 * can be non-zero. This was already checked above. So pass 8146 * fixed_off_ok as true to allow fixed offset for all other 8147 * cases. var_off always must be 0 for PTR_TO_BTF_ID, hence we 8148 * still need to do checks instead of returning. 8149 */ 8150 return __check_ptr_off_reg(env, reg, regno, true); 8151 default: 8152 return __check_ptr_off_reg(env, reg, regno, false); 8153 } 8154 } 8155 8156 static struct bpf_reg_state *get_dynptr_arg_reg(struct bpf_verifier_env *env, 8157 const struct bpf_func_proto *fn, 8158 struct bpf_reg_state *regs) 8159 { 8160 struct bpf_reg_state *state = NULL; 8161 int i; 8162 8163 for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++) 8164 if (arg_type_is_dynptr(fn->arg_type[i])) { 8165 if (state) { 8166 verbose(env, "verifier internal error: multiple dynptr args\n"); 8167 return NULL; 8168 } 8169 state = ®s[BPF_REG_1 + i]; 8170 } 8171 8172 if (!state) 8173 verbose(env, "verifier internal error: no dynptr arg found\n"); 8174 8175 return state; 8176 } 8177 8178 static int dynptr_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 8179 { 8180 struct bpf_func_state *state = func(env, reg); 8181 int spi; 8182 8183 if (reg->type == CONST_PTR_TO_DYNPTR) 8184 return reg->id; 8185 spi = dynptr_get_spi(env, reg); 8186 if (spi < 0) 8187 return spi; 8188 return state->stack[spi].spilled_ptr.id; 8189 } 8190 8191 static int dynptr_ref_obj_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 8192 { 8193 struct bpf_func_state *state = func(env, reg); 8194 int spi; 8195 8196 if (reg->type == CONST_PTR_TO_DYNPTR) 8197 return reg->ref_obj_id; 8198 spi = dynptr_get_spi(env, reg); 8199 if (spi < 0) 8200 return spi; 8201 return state->stack[spi].spilled_ptr.ref_obj_id; 8202 } 8203 8204 static enum bpf_dynptr_type dynptr_get_type(struct bpf_verifier_env *env, 8205 struct bpf_reg_state *reg) 8206 { 8207 struct bpf_func_state *state = func(env, reg); 8208 int spi; 8209 8210 if (reg->type == CONST_PTR_TO_DYNPTR) 8211 return reg->dynptr.type; 8212 8213 spi = __get_spi(reg->off); 8214 if (spi < 0) { 8215 verbose(env, "verifier internal error: invalid spi when querying dynptr type\n"); 8216 return BPF_DYNPTR_TYPE_INVALID; 8217 } 8218 8219 return state->stack[spi].spilled_ptr.dynptr.type; 8220 } 8221 8222 static int check_func_arg(struct bpf_verifier_env *env, u32 arg, 8223 struct bpf_call_arg_meta *meta, 8224 const struct bpf_func_proto *fn, 8225 int insn_idx) 8226 { 8227 u32 regno = BPF_REG_1 + arg; 8228 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno]; 8229 enum bpf_arg_type arg_type = fn->arg_type[arg]; 8230 enum bpf_reg_type type = reg->type; 8231 u32 *arg_btf_id = NULL; 8232 int err = 0; 8233 8234 if (arg_type == ARG_DONTCARE) 8235 return 0; 8236 8237 err = check_reg_arg(env, regno, SRC_OP); 8238 if (err) 8239 return err; 8240 8241 if (arg_type == ARG_ANYTHING) { 8242 if (is_pointer_value(env, regno)) { 8243 verbose(env, "R%d leaks addr into helper function\n", 8244 regno); 8245 return -EACCES; 8246 } 8247 return 0; 8248 } 8249 8250 if (type_is_pkt_pointer(type) && 8251 !may_access_direct_pkt_data(env, meta, BPF_READ)) { 8252 verbose(env, "helper access to the packet is not allowed\n"); 8253 return -EACCES; 8254 } 8255 8256 if (base_type(arg_type) == ARG_PTR_TO_MAP_VALUE) { 8257 err = resolve_map_arg_type(env, meta, &arg_type); 8258 if (err) 8259 return err; 8260 } 8261 8262 if (register_is_null(reg) && type_may_be_null(arg_type)) 8263 /* A NULL register has a SCALAR_VALUE type, so skip 8264 * type checking. 8265 */ 8266 goto skip_type_check; 8267 8268 /* arg_btf_id and arg_size are in a union. */ 8269 if (base_type(arg_type) == ARG_PTR_TO_BTF_ID || 8270 base_type(arg_type) == ARG_PTR_TO_SPIN_LOCK) 8271 arg_btf_id = fn->arg_btf_id[arg]; 8272 8273 err = check_reg_type(env, regno, arg_type, arg_btf_id, meta); 8274 if (err) 8275 return err; 8276 8277 err = check_func_arg_reg_off(env, reg, regno, arg_type); 8278 if (err) 8279 return err; 8280 8281 skip_type_check: 8282 if (arg_type_is_release(arg_type)) { 8283 if (arg_type_is_dynptr(arg_type)) { 8284 struct bpf_func_state *state = func(env, reg); 8285 int spi; 8286 8287 /* Only dynptr created on stack can be released, thus 8288 * the get_spi and stack state checks for spilled_ptr 8289 * should only be done before process_dynptr_func for 8290 * PTR_TO_STACK. 8291 */ 8292 if (reg->type == PTR_TO_STACK) { 8293 spi = dynptr_get_spi(env, reg); 8294 if (spi < 0 || !state->stack[spi].spilled_ptr.ref_obj_id) { 8295 verbose(env, "arg %d is an unacquired reference\n", regno); 8296 return -EINVAL; 8297 } 8298 } else { 8299 verbose(env, "cannot release unowned const bpf_dynptr\n"); 8300 return -EINVAL; 8301 } 8302 } else if (!reg->ref_obj_id && !register_is_null(reg)) { 8303 verbose(env, "R%d must be referenced when passed to release function\n", 8304 regno); 8305 return -EINVAL; 8306 } 8307 if (meta->release_regno) { 8308 verbose(env, "verifier internal error: more than one release argument\n"); 8309 return -EFAULT; 8310 } 8311 meta->release_regno = regno; 8312 } 8313 8314 if (reg->ref_obj_id) { 8315 if (meta->ref_obj_id) { 8316 verbose(env, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n", 8317 regno, reg->ref_obj_id, 8318 meta->ref_obj_id); 8319 return -EFAULT; 8320 } 8321 meta->ref_obj_id = reg->ref_obj_id; 8322 } 8323 8324 switch (base_type(arg_type)) { 8325 case ARG_CONST_MAP_PTR: 8326 /* bpf_map_xxx(map_ptr) call: remember that map_ptr */ 8327 if (meta->map_ptr) { 8328 /* Use map_uid (which is unique id of inner map) to reject: 8329 * inner_map1 = bpf_map_lookup_elem(outer_map, key1) 8330 * inner_map2 = bpf_map_lookup_elem(outer_map, key2) 8331 * if (inner_map1 && inner_map2) { 8332 * timer = bpf_map_lookup_elem(inner_map1); 8333 * if (timer) 8334 * // mismatch would have been allowed 8335 * bpf_timer_init(timer, inner_map2); 8336 * } 8337 * 8338 * Comparing map_ptr is enough to distinguish normal and outer maps. 8339 */ 8340 if (meta->map_ptr != reg->map_ptr || 8341 meta->map_uid != reg->map_uid) { 8342 verbose(env, 8343 "timer pointer in R1 map_uid=%d doesn't match map pointer in R2 map_uid=%d\n", 8344 meta->map_uid, reg->map_uid); 8345 return -EINVAL; 8346 } 8347 } 8348 meta->map_ptr = reg->map_ptr; 8349 meta->map_uid = reg->map_uid; 8350 break; 8351 case ARG_PTR_TO_MAP_KEY: 8352 /* bpf_map_xxx(..., map_ptr, ..., key) call: 8353 * check that [key, key + map->key_size) are within 8354 * stack limits and initialized 8355 */ 8356 if (!meta->map_ptr) { 8357 /* in function declaration map_ptr must come before 8358 * map_key, so that it's verified and known before 8359 * we have to check map_key here. Otherwise it means 8360 * that kernel subsystem misconfigured verifier 8361 */ 8362 verbose(env, "invalid map_ptr to access map->key\n"); 8363 return -EACCES; 8364 } 8365 err = check_helper_mem_access(env, regno, 8366 meta->map_ptr->key_size, false, 8367 NULL); 8368 break; 8369 case ARG_PTR_TO_MAP_VALUE: 8370 if (type_may_be_null(arg_type) && register_is_null(reg)) 8371 return 0; 8372 8373 /* bpf_map_xxx(..., map_ptr, ..., value) call: 8374 * check [value, value + map->value_size) validity 8375 */ 8376 if (!meta->map_ptr) { 8377 /* kernel subsystem misconfigured verifier */ 8378 verbose(env, "invalid map_ptr to access map->value\n"); 8379 return -EACCES; 8380 } 8381 meta->raw_mode = arg_type & MEM_UNINIT; 8382 err = check_helper_mem_access(env, regno, 8383 meta->map_ptr->value_size, false, 8384 meta); 8385 break; 8386 case ARG_PTR_TO_PERCPU_BTF_ID: 8387 if (!reg->btf_id) { 8388 verbose(env, "Helper has invalid btf_id in R%d\n", regno); 8389 return -EACCES; 8390 } 8391 meta->ret_btf = reg->btf; 8392 meta->ret_btf_id = reg->btf_id; 8393 break; 8394 case ARG_PTR_TO_SPIN_LOCK: 8395 if (in_rbtree_lock_required_cb(env)) { 8396 verbose(env, "can't spin_{lock,unlock} in rbtree cb\n"); 8397 return -EACCES; 8398 } 8399 if (meta->func_id == BPF_FUNC_spin_lock) { 8400 err = process_spin_lock(env, regno, true); 8401 if (err) 8402 return err; 8403 } else if (meta->func_id == BPF_FUNC_spin_unlock) { 8404 err = process_spin_lock(env, regno, false); 8405 if (err) 8406 return err; 8407 } else { 8408 verbose(env, "verifier internal error\n"); 8409 return -EFAULT; 8410 } 8411 break; 8412 case ARG_PTR_TO_TIMER: 8413 err = process_timer_func(env, regno, meta); 8414 if (err) 8415 return err; 8416 break; 8417 case ARG_PTR_TO_FUNC: 8418 meta->subprogno = reg->subprogno; 8419 break; 8420 case ARG_PTR_TO_MEM: 8421 /* The access to this pointer is only checked when we hit the 8422 * next is_mem_size argument below. 8423 */ 8424 meta->raw_mode = arg_type & MEM_UNINIT; 8425 if (arg_type & MEM_FIXED_SIZE) { 8426 err = check_helper_mem_access(env, regno, 8427 fn->arg_size[arg], false, 8428 meta); 8429 } 8430 break; 8431 case ARG_CONST_SIZE: 8432 err = check_mem_size_reg(env, reg, regno, false, meta); 8433 break; 8434 case ARG_CONST_SIZE_OR_ZERO: 8435 err = check_mem_size_reg(env, reg, regno, true, meta); 8436 break; 8437 case ARG_PTR_TO_DYNPTR: 8438 err = process_dynptr_func(env, regno, insn_idx, arg_type, 0); 8439 if (err) 8440 return err; 8441 break; 8442 case ARG_CONST_ALLOC_SIZE_OR_ZERO: 8443 if (!tnum_is_const(reg->var_off)) { 8444 verbose(env, "R%d is not a known constant'\n", 8445 regno); 8446 return -EACCES; 8447 } 8448 meta->mem_size = reg->var_off.value; 8449 err = mark_chain_precision(env, regno); 8450 if (err) 8451 return err; 8452 break; 8453 case ARG_PTR_TO_INT: 8454 case ARG_PTR_TO_LONG: 8455 { 8456 int size = int_ptr_type_to_size(arg_type); 8457 8458 err = check_helper_mem_access(env, regno, size, false, meta); 8459 if (err) 8460 return err; 8461 err = check_ptr_alignment(env, reg, 0, size, true); 8462 break; 8463 } 8464 case ARG_PTR_TO_CONST_STR: 8465 { 8466 struct bpf_map *map = reg->map_ptr; 8467 int map_off; 8468 u64 map_addr; 8469 char *str_ptr; 8470 8471 if (!bpf_map_is_rdonly(map)) { 8472 verbose(env, "R%d does not point to a readonly map'\n", regno); 8473 return -EACCES; 8474 } 8475 8476 if (!tnum_is_const(reg->var_off)) { 8477 verbose(env, "R%d is not a constant address'\n", regno); 8478 return -EACCES; 8479 } 8480 8481 if (!map->ops->map_direct_value_addr) { 8482 verbose(env, "no direct value access support for this map type\n"); 8483 return -EACCES; 8484 } 8485 8486 err = check_map_access(env, regno, reg->off, 8487 map->value_size - reg->off, false, 8488 ACCESS_HELPER); 8489 if (err) 8490 return err; 8491 8492 map_off = reg->off + reg->var_off.value; 8493 err = map->ops->map_direct_value_addr(map, &map_addr, map_off); 8494 if (err) { 8495 verbose(env, "direct value access on string failed\n"); 8496 return err; 8497 } 8498 8499 str_ptr = (char *)(long)(map_addr); 8500 if (!strnchr(str_ptr + map_off, map->value_size - map_off, 0)) { 8501 verbose(env, "string is not zero-terminated\n"); 8502 return -EINVAL; 8503 } 8504 break; 8505 } 8506 case ARG_PTR_TO_KPTR: 8507 err = process_kptr_func(env, regno, meta); 8508 if (err) 8509 return err; 8510 break; 8511 } 8512 8513 return err; 8514 } 8515 8516 static bool may_update_sockmap(struct bpf_verifier_env *env, int func_id) 8517 { 8518 enum bpf_attach_type eatype = env->prog->expected_attach_type; 8519 enum bpf_prog_type type = resolve_prog_type(env->prog); 8520 8521 if (func_id != BPF_FUNC_map_update_elem) 8522 return false; 8523 8524 /* It's not possible to get access to a locked struct sock in these 8525 * contexts, so updating is safe. 8526 */ 8527 switch (type) { 8528 case BPF_PROG_TYPE_TRACING: 8529 if (eatype == BPF_TRACE_ITER) 8530 return true; 8531 break; 8532 case BPF_PROG_TYPE_SOCKET_FILTER: 8533 case BPF_PROG_TYPE_SCHED_CLS: 8534 case BPF_PROG_TYPE_SCHED_ACT: 8535 case BPF_PROG_TYPE_XDP: 8536 case BPF_PROG_TYPE_SK_REUSEPORT: 8537 case BPF_PROG_TYPE_FLOW_DISSECTOR: 8538 case BPF_PROG_TYPE_SK_LOOKUP: 8539 return true; 8540 default: 8541 break; 8542 } 8543 8544 verbose(env, "cannot update sockmap in this context\n"); 8545 return false; 8546 } 8547 8548 static bool allow_tail_call_in_subprogs(struct bpf_verifier_env *env) 8549 { 8550 return env->prog->jit_requested && 8551 bpf_jit_supports_subprog_tailcalls(); 8552 } 8553 8554 static int check_map_func_compatibility(struct bpf_verifier_env *env, 8555 struct bpf_map *map, int func_id) 8556 { 8557 if (!map) 8558 return 0; 8559 8560 /* We need a two way check, first is from map perspective ... */ 8561 switch (map->map_type) { 8562 case BPF_MAP_TYPE_PROG_ARRAY: 8563 if (func_id != BPF_FUNC_tail_call) 8564 goto error; 8565 break; 8566 case BPF_MAP_TYPE_PERF_EVENT_ARRAY: 8567 if (func_id != BPF_FUNC_perf_event_read && 8568 func_id != BPF_FUNC_perf_event_output && 8569 func_id != BPF_FUNC_skb_output && 8570 func_id != BPF_FUNC_perf_event_read_value && 8571 func_id != BPF_FUNC_xdp_output) 8572 goto error; 8573 break; 8574 case BPF_MAP_TYPE_RINGBUF: 8575 if (func_id != BPF_FUNC_ringbuf_output && 8576 func_id != BPF_FUNC_ringbuf_reserve && 8577 func_id != BPF_FUNC_ringbuf_query && 8578 func_id != BPF_FUNC_ringbuf_reserve_dynptr && 8579 func_id != BPF_FUNC_ringbuf_submit_dynptr && 8580 func_id != BPF_FUNC_ringbuf_discard_dynptr) 8581 goto error; 8582 break; 8583 case BPF_MAP_TYPE_USER_RINGBUF: 8584 if (func_id != BPF_FUNC_user_ringbuf_drain) 8585 goto error; 8586 break; 8587 case BPF_MAP_TYPE_STACK_TRACE: 8588 if (func_id != BPF_FUNC_get_stackid) 8589 goto error; 8590 break; 8591 case BPF_MAP_TYPE_CGROUP_ARRAY: 8592 if (func_id != BPF_FUNC_skb_under_cgroup && 8593 func_id != BPF_FUNC_current_task_under_cgroup) 8594 goto error; 8595 break; 8596 case BPF_MAP_TYPE_CGROUP_STORAGE: 8597 case BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE: 8598 if (func_id != BPF_FUNC_get_local_storage) 8599 goto error; 8600 break; 8601 case BPF_MAP_TYPE_DEVMAP: 8602 case BPF_MAP_TYPE_DEVMAP_HASH: 8603 if (func_id != BPF_FUNC_redirect_map && 8604 func_id != BPF_FUNC_map_lookup_elem) 8605 goto error; 8606 break; 8607 /* Restrict bpf side of cpumap and xskmap, open when use-cases 8608 * appear. 8609 */ 8610 case BPF_MAP_TYPE_CPUMAP: 8611 if (func_id != BPF_FUNC_redirect_map) 8612 goto error; 8613 break; 8614 case BPF_MAP_TYPE_XSKMAP: 8615 if (func_id != BPF_FUNC_redirect_map && 8616 func_id != BPF_FUNC_map_lookup_elem) 8617 goto error; 8618 break; 8619 case BPF_MAP_TYPE_ARRAY_OF_MAPS: 8620 case BPF_MAP_TYPE_HASH_OF_MAPS: 8621 if (func_id != BPF_FUNC_map_lookup_elem) 8622 goto error; 8623 break; 8624 case BPF_MAP_TYPE_SOCKMAP: 8625 if (func_id != BPF_FUNC_sk_redirect_map && 8626 func_id != BPF_FUNC_sock_map_update && 8627 func_id != BPF_FUNC_map_delete_elem && 8628 func_id != BPF_FUNC_msg_redirect_map && 8629 func_id != BPF_FUNC_sk_select_reuseport && 8630 func_id != BPF_FUNC_map_lookup_elem && 8631 !may_update_sockmap(env, func_id)) 8632 goto error; 8633 break; 8634 case BPF_MAP_TYPE_SOCKHASH: 8635 if (func_id != BPF_FUNC_sk_redirect_hash && 8636 func_id != BPF_FUNC_sock_hash_update && 8637 func_id != BPF_FUNC_map_delete_elem && 8638 func_id != BPF_FUNC_msg_redirect_hash && 8639 func_id != BPF_FUNC_sk_select_reuseport && 8640 func_id != BPF_FUNC_map_lookup_elem && 8641 !may_update_sockmap(env, func_id)) 8642 goto error; 8643 break; 8644 case BPF_MAP_TYPE_REUSEPORT_SOCKARRAY: 8645 if (func_id != BPF_FUNC_sk_select_reuseport) 8646 goto error; 8647 break; 8648 case BPF_MAP_TYPE_QUEUE: 8649 case BPF_MAP_TYPE_STACK: 8650 if (func_id != BPF_FUNC_map_peek_elem && 8651 func_id != BPF_FUNC_map_pop_elem && 8652 func_id != BPF_FUNC_map_push_elem) 8653 goto error; 8654 break; 8655 case BPF_MAP_TYPE_SK_STORAGE: 8656 if (func_id != BPF_FUNC_sk_storage_get && 8657 func_id != BPF_FUNC_sk_storage_delete && 8658 func_id != BPF_FUNC_kptr_xchg) 8659 goto error; 8660 break; 8661 case BPF_MAP_TYPE_INODE_STORAGE: 8662 if (func_id != BPF_FUNC_inode_storage_get && 8663 func_id != BPF_FUNC_inode_storage_delete && 8664 func_id != BPF_FUNC_kptr_xchg) 8665 goto error; 8666 break; 8667 case BPF_MAP_TYPE_TASK_STORAGE: 8668 if (func_id != BPF_FUNC_task_storage_get && 8669 func_id != BPF_FUNC_task_storage_delete && 8670 func_id != BPF_FUNC_kptr_xchg) 8671 goto error; 8672 break; 8673 case BPF_MAP_TYPE_CGRP_STORAGE: 8674 if (func_id != BPF_FUNC_cgrp_storage_get && 8675 func_id != BPF_FUNC_cgrp_storage_delete && 8676 func_id != BPF_FUNC_kptr_xchg) 8677 goto error; 8678 break; 8679 case BPF_MAP_TYPE_BLOOM_FILTER: 8680 if (func_id != BPF_FUNC_map_peek_elem && 8681 func_id != BPF_FUNC_map_push_elem) 8682 goto error; 8683 break; 8684 default: 8685 break; 8686 } 8687 8688 /* ... and second from the function itself. */ 8689 switch (func_id) { 8690 case BPF_FUNC_tail_call: 8691 if (map->map_type != BPF_MAP_TYPE_PROG_ARRAY) 8692 goto error; 8693 if (env->subprog_cnt > 1 && !allow_tail_call_in_subprogs(env)) { 8694 verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n"); 8695 return -EINVAL; 8696 } 8697 break; 8698 case BPF_FUNC_perf_event_read: 8699 case BPF_FUNC_perf_event_output: 8700 case BPF_FUNC_perf_event_read_value: 8701 case BPF_FUNC_skb_output: 8702 case BPF_FUNC_xdp_output: 8703 if (map->map_type != BPF_MAP_TYPE_PERF_EVENT_ARRAY) 8704 goto error; 8705 break; 8706 case BPF_FUNC_ringbuf_output: 8707 case BPF_FUNC_ringbuf_reserve: 8708 case BPF_FUNC_ringbuf_query: 8709 case BPF_FUNC_ringbuf_reserve_dynptr: 8710 case BPF_FUNC_ringbuf_submit_dynptr: 8711 case BPF_FUNC_ringbuf_discard_dynptr: 8712 if (map->map_type != BPF_MAP_TYPE_RINGBUF) 8713 goto error; 8714 break; 8715 case BPF_FUNC_user_ringbuf_drain: 8716 if (map->map_type != BPF_MAP_TYPE_USER_RINGBUF) 8717 goto error; 8718 break; 8719 case BPF_FUNC_get_stackid: 8720 if (map->map_type != BPF_MAP_TYPE_STACK_TRACE) 8721 goto error; 8722 break; 8723 case BPF_FUNC_current_task_under_cgroup: 8724 case BPF_FUNC_skb_under_cgroup: 8725 if (map->map_type != BPF_MAP_TYPE_CGROUP_ARRAY) 8726 goto error; 8727 break; 8728 case BPF_FUNC_redirect_map: 8729 if (map->map_type != BPF_MAP_TYPE_DEVMAP && 8730 map->map_type != BPF_MAP_TYPE_DEVMAP_HASH && 8731 map->map_type != BPF_MAP_TYPE_CPUMAP && 8732 map->map_type != BPF_MAP_TYPE_XSKMAP) 8733 goto error; 8734 break; 8735 case BPF_FUNC_sk_redirect_map: 8736 case BPF_FUNC_msg_redirect_map: 8737 case BPF_FUNC_sock_map_update: 8738 if (map->map_type != BPF_MAP_TYPE_SOCKMAP) 8739 goto error; 8740 break; 8741 case BPF_FUNC_sk_redirect_hash: 8742 case BPF_FUNC_msg_redirect_hash: 8743 case BPF_FUNC_sock_hash_update: 8744 if (map->map_type != BPF_MAP_TYPE_SOCKHASH) 8745 goto error; 8746 break; 8747 case BPF_FUNC_get_local_storage: 8748 if (map->map_type != BPF_MAP_TYPE_CGROUP_STORAGE && 8749 map->map_type != BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE) 8750 goto error; 8751 break; 8752 case BPF_FUNC_sk_select_reuseport: 8753 if (map->map_type != BPF_MAP_TYPE_REUSEPORT_SOCKARRAY && 8754 map->map_type != BPF_MAP_TYPE_SOCKMAP && 8755 map->map_type != BPF_MAP_TYPE_SOCKHASH) 8756 goto error; 8757 break; 8758 case BPF_FUNC_map_pop_elem: 8759 if (map->map_type != BPF_MAP_TYPE_QUEUE && 8760 map->map_type != BPF_MAP_TYPE_STACK) 8761 goto error; 8762 break; 8763 case BPF_FUNC_map_peek_elem: 8764 case BPF_FUNC_map_push_elem: 8765 if (map->map_type != BPF_MAP_TYPE_QUEUE && 8766 map->map_type != BPF_MAP_TYPE_STACK && 8767 map->map_type != BPF_MAP_TYPE_BLOOM_FILTER) 8768 goto error; 8769 break; 8770 case BPF_FUNC_map_lookup_percpu_elem: 8771 if (map->map_type != BPF_MAP_TYPE_PERCPU_ARRAY && 8772 map->map_type != BPF_MAP_TYPE_PERCPU_HASH && 8773 map->map_type != BPF_MAP_TYPE_LRU_PERCPU_HASH) 8774 goto error; 8775 break; 8776 case BPF_FUNC_sk_storage_get: 8777 case BPF_FUNC_sk_storage_delete: 8778 if (map->map_type != BPF_MAP_TYPE_SK_STORAGE) 8779 goto error; 8780 break; 8781 case BPF_FUNC_inode_storage_get: 8782 case BPF_FUNC_inode_storage_delete: 8783 if (map->map_type != BPF_MAP_TYPE_INODE_STORAGE) 8784 goto error; 8785 break; 8786 case BPF_FUNC_task_storage_get: 8787 case BPF_FUNC_task_storage_delete: 8788 if (map->map_type != BPF_MAP_TYPE_TASK_STORAGE) 8789 goto error; 8790 break; 8791 case BPF_FUNC_cgrp_storage_get: 8792 case BPF_FUNC_cgrp_storage_delete: 8793 if (map->map_type != BPF_MAP_TYPE_CGRP_STORAGE) 8794 goto error; 8795 break; 8796 default: 8797 break; 8798 } 8799 8800 return 0; 8801 error: 8802 verbose(env, "cannot pass map_type %d into func %s#%d\n", 8803 map->map_type, func_id_name(func_id), func_id); 8804 return -EINVAL; 8805 } 8806 8807 static bool check_raw_mode_ok(const struct bpf_func_proto *fn) 8808 { 8809 int count = 0; 8810 8811 if (fn->arg1_type == ARG_PTR_TO_UNINIT_MEM) 8812 count++; 8813 if (fn->arg2_type == ARG_PTR_TO_UNINIT_MEM) 8814 count++; 8815 if (fn->arg3_type == ARG_PTR_TO_UNINIT_MEM) 8816 count++; 8817 if (fn->arg4_type == ARG_PTR_TO_UNINIT_MEM) 8818 count++; 8819 if (fn->arg5_type == ARG_PTR_TO_UNINIT_MEM) 8820 count++; 8821 8822 /* We only support one arg being in raw mode at the moment, 8823 * which is sufficient for the helper functions we have 8824 * right now. 8825 */ 8826 return count <= 1; 8827 } 8828 8829 static bool check_args_pair_invalid(const struct bpf_func_proto *fn, int arg) 8830 { 8831 bool is_fixed = fn->arg_type[arg] & MEM_FIXED_SIZE; 8832 bool has_size = fn->arg_size[arg] != 0; 8833 bool is_next_size = false; 8834 8835 if (arg + 1 < ARRAY_SIZE(fn->arg_type)) 8836 is_next_size = arg_type_is_mem_size(fn->arg_type[arg + 1]); 8837 8838 if (base_type(fn->arg_type[arg]) != ARG_PTR_TO_MEM) 8839 return is_next_size; 8840 8841 return has_size == is_next_size || is_next_size == is_fixed; 8842 } 8843 8844 static bool check_arg_pair_ok(const struct bpf_func_proto *fn) 8845 { 8846 /* bpf_xxx(..., buf, len) call will access 'len' 8847 * bytes from memory 'buf'. Both arg types need 8848 * to be paired, so make sure there's no buggy 8849 * helper function specification. 8850 */ 8851 if (arg_type_is_mem_size(fn->arg1_type) || 8852 check_args_pair_invalid(fn, 0) || 8853 check_args_pair_invalid(fn, 1) || 8854 check_args_pair_invalid(fn, 2) || 8855 check_args_pair_invalid(fn, 3) || 8856 check_args_pair_invalid(fn, 4)) 8857 return false; 8858 8859 return true; 8860 } 8861 8862 static bool check_btf_id_ok(const struct bpf_func_proto *fn) 8863 { 8864 int i; 8865 8866 for (i = 0; i < ARRAY_SIZE(fn->arg_type); i++) { 8867 if (base_type(fn->arg_type[i]) == ARG_PTR_TO_BTF_ID) 8868 return !!fn->arg_btf_id[i]; 8869 if (base_type(fn->arg_type[i]) == ARG_PTR_TO_SPIN_LOCK) 8870 return fn->arg_btf_id[i] == BPF_PTR_POISON; 8871 if (base_type(fn->arg_type[i]) != ARG_PTR_TO_BTF_ID && fn->arg_btf_id[i] && 8872 /* arg_btf_id and arg_size are in a union. */ 8873 (base_type(fn->arg_type[i]) != ARG_PTR_TO_MEM || 8874 !(fn->arg_type[i] & MEM_FIXED_SIZE))) 8875 return false; 8876 } 8877 8878 return true; 8879 } 8880 8881 static int check_func_proto(const struct bpf_func_proto *fn, int func_id) 8882 { 8883 return check_raw_mode_ok(fn) && 8884 check_arg_pair_ok(fn) && 8885 check_btf_id_ok(fn) ? 0 : -EINVAL; 8886 } 8887 8888 /* Packet data might have moved, any old PTR_TO_PACKET[_META,_END] 8889 * are now invalid, so turn them into unknown SCALAR_VALUE. 8890 * 8891 * This also applies to dynptr slices belonging to skb and xdp dynptrs, 8892 * since these slices point to packet data. 8893 */ 8894 static void clear_all_pkt_pointers(struct bpf_verifier_env *env) 8895 { 8896 struct bpf_func_state *state; 8897 struct bpf_reg_state *reg; 8898 8899 bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({ 8900 if (reg_is_pkt_pointer_any(reg) || reg_is_dynptr_slice_pkt(reg)) 8901 mark_reg_invalid(env, reg); 8902 })); 8903 } 8904 8905 enum { 8906 AT_PKT_END = -1, 8907 BEYOND_PKT_END = -2, 8908 }; 8909 8910 static void mark_pkt_end(struct bpf_verifier_state *vstate, int regn, bool range_open) 8911 { 8912 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 8913 struct bpf_reg_state *reg = &state->regs[regn]; 8914 8915 if (reg->type != PTR_TO_PACKET) 8916 /* PTR_TO_PACKET_META is not supported yet */ 8917 return; 8918 8919 /* The 'reg' is pkt > pkt_end or pkt >= pkt_end. 8920 * How far beyond pkt_end it goes is unknown. 8921 * if (!range_open) it's the case of pkt >= pkt_end 8922 * if (range_open) it's the case of pkt > pkt_end 8923 * hence this pointer is at least 1 byte bigger than pkt_end 8924 */ 8925 if (range_open) 8926 reg->range = BEYOND_PKT_END; 8927 else 8928 reg->range = AT_PKT_END; 8929 } 8930 8931 /* The pointer with the specified id has released its reference to kernel 8932 * resources. Identify all copies of the same pointer and clear the reference. 8933 */ 8934 static int release_reference(struct bpf_verifier_env *env, 8935 int ref_obj_id) 8936 { 8937 struct bpf_func_state *state; 8938 struct bpf_reg_state *reg; 8939 int err; 8940 8941 err = release_reference_state(cur_func(env), ref_obj_id); 8942 if (err) 8943 return err; 8944 8945 bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({ 8946 if (reg->ref_obj_id == ref_obj_id) 8947 mark_reg_invalid(env, reg); 8948 })); 8949 8950 return 0; 8951 } 8952 8953 static void invalidate_non_owning_refs(struct bpf_verifier_env *env) 8954 { 8955 struct bpf_func_state *unused; 8956 struct bpf_reg_state *reg; 8957 8958 bpf_for_each_reg_in_vstate(env->cur_state, unused, reg, ({ 8959 if (type_is_non_owning_ref(reg->type)) 8960 mark_reg_invalid(env, reg); 8961 })); 8962 } 8963 8964 static void clear_caller_saved_regs(struct bpf_verifier_env *env, 8965 struct bpf_reg_state *regs) 8966 { 8967 int i; 8968 8969 /* after the call registers r0 - r5 were scratched */ 8970 for (i = 0; i < CALLER_SAVED_REGS; i++) { 8971 mark_reg_not_init(env, regs, caller_saved[i]); 8972 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK); 8973 } 8974 } 8975 8976 typedef int (*set_callee_state_fn)(struct bpf_verifier_env *env, 8977 struct bpf_func_state *caller, 8978 struct bpf_func_state *callee, 8979 int insn_idx); 8980 8981 static int set_callee_state(struct bpf_verifier_env *env, 8982 struct bpf_func_state *caller, 8983 struct bpf_func_state *callee, int insn_idx); 8984 8985 static int __check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn, 8986 int *insn_idx, int subprog, 8987 set_callee_state_fn set_callee_state_cb) 8988 { 8989 struct bpf_verifier_state *state = env->cur_state; 8990 struct bpf_func_state *caller, *callee; 8991 int err; 8992 8993 if (state->curframe + 1 >= MAX_CALL_FRAMES) { 8994 verbose(env, "the call stack of %d frames is too deep\n", 8995 state->curframe + 2); 8996 return -E2BIG; 8997 } 8998 8999 caller = state->frame[state->curframe]; 9000 if (state->frame[state->curframe + 1]) { 9001 verbose(env, "verifier bug. Frame %d already allocated\n", 9002 state->curframe + 1); 9003 return -EFAULT; 9004 } 9005 9006 err = btf_check_subprog_call(env, subprog, caller->regs); 9007 if (err == -EFAULT) 9008 return err; 9009 if (subprog_is_global(env, subprog)) { 9010 if (err) { 9011 verbose(env, "Caller passes invalid args into func#%d\n", 9012 subprog); 9013 return err; 9014 } else { 9015 if (env->log.level & BPF_LOG_LEVEL) 9016 verbose(env, 9017 "Func#%d is global and valid. Skipping.\n", 9018 subprog); 9019 clear_caller_saved_regs(env, caller->regs); 9020 9021 /* All global functions return a 64-bit SCALAR_VALUE */ 9022 mark_reg_unknown(env, caller->regs, BPF_REG_0); 9023 caller->regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG; 9024 9025 /* continue with next insn after call */ 9026 return 0; 9027 } 9028 } 9029 9030 /* set_callee_state is used for direct subprog calls, but we are 9031 * interested in validating only BPF helpers that can call subprogs as 9032 * callbacks 9033 */ 9034 if (set_callee_state_cb != set_callee_state) { 9035 env->subprog_info[subprog].is_cb = true; 9036 if (bpf_pseudo_kfunc_call(insn) && 9037 !is_callback_calling_kfunc(insn->imm)) { 9038 verbose(env, "verifier bug: kfunc %s#%d not marked as callback-calling\n", 9039 func_id_name(insn->imm), insn->imm); 9040 return -EFAULT; 9041 } else if (!bpf_pseudo_kfunc_call(insn) && 9042 !is_callback_calling_function(insn->imm)) { /* helper */ 9043 verbose(env, "verifier bug: helper %s#%d not marked as callback-calling\n", 9044 func_id_name(insn->imm), insn->imm); 9045 return -EFAULT; 9046 } 9047 } 9048 9049 if (insn->code == (BPF_JMP | BPF_CALL) && 9050 insn->src_reg == 0 && 9051 insn->imm == BPF_FUNC_timer_set_callback) { 9052 struct bpf_verifier_state *async_cb; 9053 9054 /* there is no real recursion here. timer callbacks are async */ 9055 env->subprog_info[subprog].is_async_cb = true; 9056 async_cb = push_async_cb(env, env->subprog_info[subprog].start, 9057 *insn_idx, subprog); 9058 if (!async_cb) 9059 return -EFAULT; 9060 callee = async_cb->frame[0]; 9061 callee->async_entry_cnt = caller->async_entry_cnt + 1; 9062 9063 /* Convert bpf_timer_set_callback() args into timer callback args */ 9064 err = set_callee_state_cb(env, caller, callee, *insn_idx); 9065 if (err) 9066 return err; 9067 9068 clear_caller_saved_regs(env, caller->regs); 9069 mark_reg_unknown(env, caller->regs, BPF_REG_0); 9070 caller->regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG; 9071 /* continue with next insn after call */ 9072 return 0; 9073 } 9074 9075 callee = kzalloc(sizeof(*callee), GFP_KERNEL); 9076 if (!callee) 9077 return -ENOMEM; 9078 state->frame[state->curframe + 1] = callee; 9079 9080 /* callee cannot access r0, r6 - r9 for reading and has to write 9081 * into its own stack before reading from it. 9082 * callee can read/write into caller's stack 9083 */ 9084 init_func_state(env, callee, 9085 /* remember the callsite, it will be used by bpf_exit */ 9086 *insn_idx /* callsite */, 9087 state->curframe + 1 /* frameno within this callchain */, 9088 subprog /* subprog number within this prog */); 9089 9090 /* Transfer references to the callee */ 9091 err = copy_reference_state(callee, caller); 9092 if (err) 9093 goto err_out; 9094 9095 err = set_callee_state_cb(env, caller, callee, *insn_idx); 9096 if (err) 9097 goto err_out; 9098 9099 clear_caller_saved_regs(env, caller->regs); 9100 9101 /* only increment it after check_reg_arg() finished */ 9102 state->curframe++; 9103 9104 /* and go analyze first insn of the callee */ 9105 *insn_idx = env->subprog_info[subprog].start - 1; 9106 9107 if (env->log.level & BPF_LOG_LEVEL) { 9108 verbose(env, "caller:\n"); 9109 print_verifier_state(env, caller, true); 9110 verbose(env, "callee:\n"); 9111 print_verifier_state(env, callee, true); 9112 } 9113 return 0; 9114 9115 err_out: 9116 free_func_state(callee); 9117 state->frame[state->curframe + 1] = NULL; 9118 return err; 9119 } 9120 9121 int map_set_for_each_callback_args(struct bpf_verifier_env *env, 9122 struct bpf_func_state *caller, 9123 struct bpf_func_state *callee) 9124 { 9125 /* bpf_for_each_map_elem(struct bpf_map *map, void *callback_fn, 9126 * void *callback_ctx, u64 flags); 9127 * callback_fn(struct bpf_map *map, void *key, void *value, 9128 * void *callback_ctx); 9129 */ 9130 callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1]; 9131 9132 callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY; 9133 __mark_reg_known_zero(&callee->regs[BPF_REG_2]); 9134 callee->regs[BPF_REG_2].map_ptr = caller->regs[BPF_REG_1].map_ptr; 9135 9136 callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE; 9137 __mark_reg_known_zero(&callee->regs[BPF_REG_3]); 9138 callee->regs[BPF_REG_3].map_ptr = caller->regs[BPF_REG_1].map_ptr; 9139 9140 /* pointer to stack or null */ 9141 callee->regs[BPF_REG_4] = caller->regs[BPF_REG_3]; 9142 9143 /* unused */ 9144 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]); 9145 return 0; 9146 } 9147 9148 static int set_callee_state(struct bpf_verifier_env *env, 9149 struct bpf_func_state *caller, 9150 struct bpf_func_state *callee, int insn_idx) 9151 { 9152 int i; 9153 9154 /* copy r1 - r5 args that callee can access. The copy includes parent 9155 * pointers, which connects us up to the liveness chain 9156 */ 9157 for (i = BPF_REG_1; i <= BPF_REG_5; i++) 9158 callee->regs[i] = caller->regs[i]; 9159 return 0; 9160 } 9161 9162 static int check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn, 9163 int *insn_idx) 9164 { 9165 int subprog, target_insn; 9166 9167 target_insn = *insn_idx + insn->imm + 1; 9168 subprog = find_subprog(env, target_insn); 9169 if (subprog < 0) { 9170 verbose(env, "verifier bug. No program starts at insn %d\n", 9171 target_insn); 9172 return -EFAULT; 9173 } 9174 9175 return __check_func_call(env, insn, insn_idx, subprog, set_callee_state); 9176 } 9177 9178 static int set_map_elem_callback_state(struct bpf_verifier_env *env, 9179 struct bpf_func_state *caller, 9180 struct bpf_func_state *callee, 9181 int insn_idx) 9182 { 9183 struct bpf_insn_aux_data *insn_aux = &env->insn_aux_data[insn_idx]; 9184 struct bpf_map *map; 9185 int err; 9186 9187 if (bpf_map_ptr_poisoned(insn_aux)) { 9188 verbose(env, "tail_call abusing map_ptr\n"); 9189 return -EINVAL; 9190 } 9191 9192 map = BPF_MAP_PTR(insn_aux->map_ptr_state); 9193 if (!map->ops->map_set_for_each_callback_args || 9194 !map->ops->map_for_each_callback) { 9195 verbose(env, "callback function not allowed for map\n"); 9196 return -ENOTSUPP; 9197 } 9198 9199 err = map->ops->map_set_for_each_callback_args(env, caller, callee); 9200 if (err) 9201 return err; 9202 9203 callee->in_callback_fn = true; 9204 callee->callback_ret_range = tnum_range(0, 1); 9205 return 0; 9206 } 9207 9208 static int set_loop_callback_state(struct bpf_verifier_env *env, 9209 struct bpf_func_state *caller, 9210 struct bpf_func_state *callee, 9211 int insn_idx) 9212 { 9213 /* bpf_loop(u32 nr_loops, void *callback_fn, void *callback_ctx, 9214 * u64 flags); 9215 * callback_fn(u32 index, void *callback_ctx); 9216 */ 9217 callee->regs[BPF_REG_1].type = SCALAR_VALUE; 9218 callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3]; 9219 9220 /* unused */ 9221 __mark_reg_not_init(env, &callee->regs[BPF_REG_3]); 9222 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]); 9223 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]); 9224 9225 callee->in_callback_fn = true; 9226 callee->callback_ret_range = tnum_range(0, 1); 9227 return 0; 9228 } 9229 9230 static int set_timer_callback_state(struct bpf_verifier_env *env, 9231 struct bpf_func_state *caller, 9232 struct bpf_func_state *callee, 9233 int insn_idx) 9234 { 9235 struct bpf_map *map_ptr = caller->regs[BPF_REG_1].map_ptr; 9236 9237 /* bpf_timer_set_callback(struct bpf_timer *timer, void *callback_fn); 9238 * callback_fn(struct bpf_map *map, void *key, void *value); 9239 */ 9240 callee->regs[BPF_REG_1].type = CONST_PTR_TO_MAP; 9241 __mark_reg_known_zero(&callee->regs[BPF_REG_1]); 9242 callee->regs[BPF_REG_1].map_ptr = map_ptr; 9243 9244 callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY; 9245 __mark_reg_known_zero(&callee->regs[BPF_REG_2]); 9246 callee->regs[BPF_REG_2].map_ptr = map_ptr; 9247 9248 callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE; 9249 __mark_reg_known_zero(&callee->regs[BPF_REG_3]); 9250 callee->regs[BPF_REG_3].map_ptr = map_ptr; 9251 9252 /* unused */ 9253 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]); 9254 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]); 9255 callee->in_async_callback_fn = true; 9256 callee->callback_ret_range = tnum_range(0, 1); 9257 return 0; 9258 } 9259 9260 static int set_find_vma_callback_state(struct bpf_verifier_env *env, 9261 struct bpf_func_state *caller, 9262 struct bpf_func_state *callee, 9263 int insn_idx) 9264 { 9265 /* bpf_find_vma(struct task_struct *task, u64 addr, 9266 * void *callback_fn, void *callback_ctx, u64 flags) 9267 * (callback_fn)(struct task_struct *task, 9268 * struct vm_area_struct *vma, void *callback_ctx); 9269 */ 9270 callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1]; 9271 9272 callee->regs[BPF_REG_2].type = PTR_TO_BTF_ID; 9273 __mark_reg_known_zero(&callee->regs[BPF_REG_2]); 9274 callee->regs[BPF_REG_2].btf = btf_vmlinux; 9275 callee->regs[BPF_REG_2].btf_id = btf_tracing_ids[BTF_TRACING_TYPE_VMA], 9276 9277 /* pointer to stack or null */ 9278 callee->regs[BPF_REG_3] = caller->regs[BPF_REG_4]; 9279 9280 /* unused */ 9281 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]); 9282 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]); 9283 callee->in_callback_fn = true; 9284 callee->callback_ret_range = tnum_range(0, 1); 9285 return 0; 9286 } 9287 9288 static int set_user_ringbuf_callback_state(struct bpf_verifier_env *env, 9289 struct bpf_func_state *caller, 9290 struct bpf_func_state *callee, 9291 int insn_idx) 9292 { 9293 /* bpf_user_ringbuf_drain(struct bpf_map *map, void *callback_fn, void 9294 * callback_ctx, u64 flags); 9295 * callback_fn(const struct bpf_dynptr_t* dynptr, void *callback_ctx); 9296 */ 9297 __mark_reg_not_init(env, &callee->regs[BPF_REG_0]); 9298 mark_dynptr_cb_reg(env, &callee->regs[BPF_REG_1], BPF_DYNPTR_TYPE_LOCAL); 9299 callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3]; 9300 9301 /* unused */ 9302 __mark_reg_not_init(env, &callee->regs[BPF_REG_3]); 9303 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]); 9304 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]); 9305 9306 callee->in_callback_fn = true; 9307 callee->callback_ret_range = tnum_range(0, 1); 9308 return 0; 9309 } 9310 9311 static int set_rbtree_add_callback_state(struct bpf_verifier_env *env, 9312 struct bpf_func_state *caller, 9313 struct bpf_func_state *callee, 9314 int insn_idx) 9315 { 9316 /* void bpf_rbtree_add_impl(struct bpf_rb_root *root, struct bpf_rb_node *node, 9317 * bool (less)(struct bpf_rb_node *a, const struct bpf_rb_node *b)); 9318 * 9319 * 'struct bpf_rb_node *node' arg to bpf_rbtree_add_impl is the same PTR_TO_BTF_ID w/ offset 9320 * that 'less' callback args will be receiving. However, 'node' arg was release_reference'd 9321 * by this point, so look at 'root' 9322 */ 9323 struct btf_field *field; 9324 9325 field = reg_find_field_offset(&caller->regs[BPF_REG_1], caller->regs[BPF_REG_1].off, 9326 BPF_RB_ROOT); 9327 if (!field || !field->graph_root.value_btf_id) 9328 return -EFAULT; 9329 9330 mark_reg_graph_node(callee->regs, BPF_REG_1, &field->graph_root); 9331 ref_set_non_owning(env, &callee->regs[BPF_REG_1]); 9332 mark_reg_graph_node(callee->regs, BPF_REG_2, &field->graph_root); 9333 ref_set_non_owning(env, &callee->regs[BPF_REG_2]); 9334 9335 __mark_reg_not_init(env, &callee->regs[BPF_REG_3]); 9336 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]); 9337 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]); 9338 callee->in_callback_fn = true; 9339 callee->callback_ret_range = tnum_range(0, 1); 9340 return 0; 9341 } 9342 9343 static bool is_rbtree_lock_required_kfunc(u32 btf_id); 9344 9345 /* Are we currently verifying the callback for a rbtree helper that must 9346 * be called with lock held? If so, no need to complain about unreleased 9347 * lock 9348 */ 9349 static bool in_rbtree_lock_required_cb(struct bpf_verifier_env *env) 9350 { 9351 struct bpf_verifier_state *state = env->cur_state; 9352 struct bpf_insn *insn = env->prog->insnsi; 9353 struct bpf_func_state *callee; 9354 int kfunc_btf_id; 9355 9356 if (!state->curframe) 9357 return false; 9358 9359 callee = state->frame[state->curframe]; 9360 9361 if (!callee->in_callback_fn) 9362 return false; 9363 9364 kfunc_btf_id = insn[callee->callsite].imm; 9365 return is_rbtree_lock_required_kfunc(kfunc_btf_id); 9366 } 9367 9368 static int prepare_func_exit(struct bpf_verifier_env *env, int *insn_idx) 9369 { 9370 struct bpf_verifier_state *state = env->cur_state; 9371 struct bpf_func_state *caller, *callee; 9372 struct bpf_reg_state *r0; 9373 int err; 9374 9375 callee = state->frame[state->curframe]; 9376 r0 = &callee->regs[BPF_REG_0]; 9377 if (r0->type == PTR_TO_STACK) { 9378 /* technically it's ok to return caller's stack pointer 9379 * (or caller's caller's pointer) back to the caller, 9380 * since these pointers are valid. Only current stack 9381 * pointer will be invalid as soon as function exits, 9382 * but let's be conservative 9383 */ 9384 verbose(env, "cannot return stack pointer to the caller\n"); 9385 return -EINVAL; 9386 } 9387 9388 caller = state->frame[state->curframe - 1]; 9389 if (callee->in_callback_fn) { 9390 /* enforce R0 return value range [0, 1]. */ 9391 struct tnum range = callee->callback_ret_range; 9392 9393 if (r0->type != SCALAR_VALUE) { 9394 verbose(env, "R0 not a scalar value\n"); 9395 return -EACCES; 9396 } 9397 if (!tnum_in(range, r0->var_off)) { 9398 verbose_invalid_scalar(env, r0, &range, "callback return", "R0"); 9399 return -EINVAL; 9400 } 9401 } else { 9402 /* return to the caller whatever r0 had in the callee */ 9403 caller->regs[BPF_REG_0] = *r0; 9404 } 9405 9406 /* callback_fn frame should have released its own additions to parent's 9407 * reference state at this point, or check_reference_leak would 9408 * complain, hence it must be the same as the caller. There is no need 9409 * to copy it back. 9410 */ 9411 if (!callee->in_callback_fn) { 9412 /* Transfer references to the caller */ 9413 err = copy_reference_state(caller, callee); 9414 if (err) 9415 return err; 9416 } 9417 9418 *insn_idx = callee->callsite + 1; 9419 if (env->log.level & BPF_LOG_LEVEL) { 9420 verbose(env, "returning from callee:\n"); 9421 print_verifier_state(env, callee, true); 9422 verbose(env, "to caller at %d:\n", *insn_idx); 9423 print_verifier_state(env, caller, true); 9424 } 9425 /* clear everything in the callee. In case of exceptional exits using 9426 * bpf_throw, this will be done by copy_verifier_state for extra frames. */ 9427 free_func_state(callee); 9428 state->frame[state->curframe--] = NULL; 9429 return 0; 9430 } 9431 9432 static void do_refine_retval_range(struct bpf_reg_state *regs, int ret_type, 9433 int func_id, 9434 struct bpf_call_arg_meta *meta) 9435 { 9436 struct bpf_reg_state *ret_reg = ®s[BPF_REG_0]; 9437 9438 if (ret_type != RET_INTEGER) 9439 return; 9440 9441 switch (func_id) { 9442 case BPF_FUNC_get_stack: 9443 case BPF_FUNC_get_task_stack: 9444 case BPF_FUNC_probe_read_str: 9445 case BPF_FUNC_probe_read_kernel_str: 9446 case BPF_FUNC_probe_read_user_str: 9447 ret_reg->smax_value = meta->msize_max_value; 9448 ret_reg->s32_max_value = meta->msize_max_value; 9449 ret_reg->smin_value = -MAX_ERRNO; 9450 ret_reg->s32_min_value = -MAX_ERRNO; 9451 reg_bounds_sync(ret_reg); 9452 break; 9453 case BPF_FUNC_get_smp_processor_id: 9454 ret_reg->umax_value = nr_cpu_ids - 1; 9455 ret_reg->u32_max_value = nr_cpu_ids - 1; 9456 ret_reg->smax_value = nr_cpu_ids - 1; 9457 ret_reg->s32_max_value = nr_cpu_ids - 1; 9458 ret_reg->umin_value = 0; 9459 ret_reg->u32_min_value = 0; 9460 ret_reg->smin_value = 0; 9461 ret_reg->s32_min_value = 0; 9462 reg_bounds_sync(ret_reg); 9463 break; 9464 } 9465 } 9466 9467 static int 9468 record_func_map(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta, 9469 int func_id, int insn_idx) 9470 { 9471 struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx]; 9472 struct bpf_map *map = meta->map_ptr; 9473 9474 if (func_id != BPF_FUNC_tail_call && 9475 func_id != BPF_FUNC_map_lookup_elem && 9476 func_id != BPF_FUNC_map_update_elem && 9477 func_id != BPF_FUNC_map_delete_elem && 9478 func_id != BPF_FUNC_map_push_elem && 9479 func_id != BPF_FUNC_map_pop_elem && 9480 func_id != BPF_FUNC_map_peek_elem && 9481 func_id != BPF_FUNC_for_each_map_elem && 9482 func_id != BPF_FUNC_redirect_map && 9483 func_id != BPF_FUNC_map_lookup_percpu_elem) 9484 return 0; 9485 9486 if (map == NULL) { 9487 verbose(env, "kernel subsystem misconfigured verifier\n"); 9488 return -EINVAL; 9489 } 9490 9491 /* In case of read-only, some additional restrictions 9492 * need to be applied in order to prevent altering the 9493 * state of the map from program side. 9494 */ 9495 if ((map->map_flags & BPF_F_RDONLY_PROG) && 9496 (func_id == BPF_FUNC_map_delete_elem || 9497 func_id == BPF_FUNC_map_update_elem || 9498 func_id == BPF_FUNC_map_push_elem || 9499 func_id == BPF_FUNC_map_pop_elem)) { 9500 verbose(env, "write into map forbidden\n"); 9501 return -EACCES; 9502 } 9503 9504 if (!BPF_MAP_PTR(aux->map_ptr_state)) 9505 bpf_map_ptr_store(aux, meta->map_ptr, 9506 !meta->map_ptr->bypass_spec_v1); 9507 else if (BPF_MAP_PTR(aux->map_ptr_state) != meta->map_ptr) 9508 bpf_map_ptr_store(aux, BPF_MAP_PTR_POISON, 9509 !meta->map_ptr->bypass_spec_v1); 9510 return 0; 9511 } 9512 9513 static int 9514 record_func_key(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta, 9515 int func_id, int insn_idx) 9516 { 9517 struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx]; 9518 struct bpf_reg_state *regs = cur_regs(env), *reg; 9519 struct bpf_map *map = meta->map_ptr; 9520 u64 val, max; 9521 int err; 9522 9523 if (func_id != BPF_FUNC_tail_call) 9524 return 0; 9525 if (!map || map->map_type != BPF_MAP_TYPE_PROG_ARRAY) { 9526 verbose(env, "kernel subsystem misconfigured verifier\n"); 9527 return -EINVAL; 9528 } 9529 9530 reg = ®s[BPF_REG_3]; 9531 val = reg->var_off.value; 9532 max = map->max_entries; 9533 9534 if (!(register_is_const(reg) && val < max)) { 9535 bpf_map_key_store(aux, BPF_MAP_KEY_POISON); 9536 return 0; 9537 } 9538 9539 err = mark_chain_precision(env, BPF_REG_3); 9540 if (err) 9541 return err; 9542 if (bpf_map_key_unseen(aux)) 9543 bpf_map_key_store(aux, val); 9544 else if (!bpf_map_key_poisoned(aux) && 9545 bpf_map_key_immediate(aux) != val) 9546 bpf_map_key_store(aux, BPF_MAP_KEY_POISON); 9547 return 0; 9548 } 9549 9550 static int check_reference_leak(struct bpf_verifier_env *env, bool exception_exit) 9551 { 9552 struct bpf_func_state *state = cur_func(env); 9553 bool refs_lingering = false; 9554 int i; 9555 9556 if (!exception_exit && state->frameno && !state->in_callback_fn) 9557 return 0; 9558 9559 for (i = 0; i < state->acquired_refs; i++) { 9560 if (!exception_exit && state->in_callback_fn && state->refs[i].callback_ref != state->frameno) 9561 continue; 9562 verbose(env, "Unreleased reference id=%d alloc_insn=%d\n", 9563 state->refs[i].id, state->refs[i].insn_idx); 9564 refs_lingering = true; 9565 } 9566 return refs_lingering ? -EINVAL : 0; 9567 } 9568 9569 static int check_bpf_snprintf_call(struct bpf_verifier_env *env, 9570 struct bpf_reg_state *regs) 9571 { 9572 struct bpf_reg_state *fmt_reg = ®s[BPF_REG_3]; 9573 struct bpf_reg_state *data_len_reg = ®s[BPF_REG_5]; 9574 struct bpf_map *fmt_map = fmt_reg->map_ptr; 9575 struct bpf_bprintf_data data = {}; 9576 int err, fmt_map_off, num_args; 9577 u64 fmt_addr; 9578 char *fmt; 9579 9580 /* data must be an array of u64 */ 9581 if (data_len_reg->var_off.value % 8) 9582 return -EINVAL; 9583 num_args = data_len_reg->var_off.value / 8; 9584 9585 /* fmt being ARG_PTR_TO_CONST_STR guarantees that var_off is const 9586 * and map_direct_value_addr is set. 9587 */ 9588 fmt_map_off = fmt_reg->off + fmt_reg->var_off.value; 9589 err = fmt_map->ops->map_direct_value_addr(fmt_map, &fmt_addr, 9590 fmt_map_off); 9591 if (err) { 9592 verbose(env, "verifier bug\n"); 9593 return -EFAULT; 9594 } 9595 fmt = (char *)(long)fmt_addr + fmt_map_off; 9596 9597 /* We are also guaranteed that fmt+fmt_map_off is NULL terminated, we 9598 * can focus on validating the format specifiers. 9599 */ 9600 err = bpf_bprintf_prepare(fmt, UINT_MAX, NULL, num_args, &data); 9601 if (err < 0) 9602 verbose(env, "Invalid format string\n"); 9603 9604 return err; 9605 } 9606 9607 static int check_get_func_ip(struct bpf_verifier_env *env) 9608 { 9609 enum bpf_prog_type type = resolve_prog_type(env->prog); 9610 int func_id = BPF_FUNC_get_func_ip; 9611 9612 if (type == BPF_PROG_TYPE_TRACING) { 9613 if (!bpf_prog_has_trampoline(env->prog)) { 9614 verbose(env, "func %s#%d supported only for fentry/fexit/fmod_ret programs\n", 9615 func_id_name(func_id), func_id); 9616 return -ENOTSUPP; 9617 } 9618 return 0; 9619 } else if (type == BPF_PROG_TYPE_KPROBE) { 9620 return 0; 9621 } 9622 9623 verbose(env, "func %s#%d not supported for program type %d\n", 9624 func_id_name(func_id), func_id, type); 9625 return -ENOTSUPP; 9626 } 9627 9628 static struct bpf_insn_aux_data *cur_aux(struct bpf_verifier_env *env) 9629 { 9630 return &env->insn_aux_data[env->insn_idx]; 9631 } 9632 9633 static bool loop_flag_is_zero(struct bpf_verifier_env *env) 9634 { 9635 struct bpf_reg_state *regs = cur_regs(env); 9636 struct bpf_reg_state *reg = ®s[BPF_REG_4]; 9637 bool reg_is_null = register_is_null(reg); 9638 9639 if (reg_is_null) 9640 mark_chain_precision(env, BPF_REG_4); 9641 9642 return reg_is_null; 9643 } 9644 9645 static void update_loop_inline_state(struct bpf_verifier_env *env, u32 subprogno) 9646 { 9647 struct bpf_loop_inline_state *state = &cur_aux(env)->loop_inline_state; 9648 9649 if (!state->initialized) { 9650 state->initialized = 1; 9651 state->fit_for_inline = loop_flag_is_zero(env); 9652 state->callback_subprogno = subprogno; 9653 return; 9654 } 9655 9656 if (!state->fit_for_inline) 9657 return; 9658 9659 state->fit_for_inline = (loop_flag_is_zero(env) && 9660 state->callback_subprogno == subprogno); 9661 } 9662 9663 static int check_helper_call(struct bpf_verifier_env *env, struct bpf_insn *insn, 9664 int *insn_idx_p) 9665 { 9666 enum bpf_prog_type prog_type = resolve_prog_type(env->prog); 9667 bool returns_cpu_specific_alloc_ptr = false; 9668 const struct bpf_func_proto *fn = NULL; 9669 enum bpf_return_type ret_type; 9670 enum bpf_type_flag ret_flag; 9671 struct bpf_reg_state *regs; 9672 struct bpf_call_arg_meta meta; 9673 int insn_idx = *insn_idx_p; 9674 bool changes_data; 9675 int i, err, func_id; 9676 9677 /* find function prototype */ 9678 func_id = insn->imm; 9679 if (func_id < 0 || func_id >= __BPF_FUNC_MAX_ID) { 9680 verbose(env, "invalid func %s#%d\n", func_id_name(func_id), 9681 func_id); 9682 return -EINVAL; 9683 } 9684 9685 if (env->ops->get_func_proto) 9686 fn = env->ops->get_func_proto(func_id, env->prog); 9687 if (!fn) { 9688 verbose(env, "unknown func %s#%d\n", func_id_name(func_id), 9689 func_id); 9690 return -EINVAL; 9691 } 9692 9693 /* eBPF programs must be GPL compatible to use GPL-ed functions */ 9694 if (!env->prog->gpl_compatible && fn->gpl_only) { 9695 verbose(env, "cannot call GPL-restricted function from non-GPL compatible program\n"); 9696 return -EINVAL; 9697 } 9698 9699 if (fn->allowed && !fn->allowed(env->prog)) { 9700 verbose(env, "helper call is not allowed in probe\n"); 9701 return -EINVAL; 9702 } 9703 9704 if (!env->prog->aux->sleepable && fn->might_sleep) { 9705 verbose(env, "helper call might sleep in a non-sleepable prog\n"); 9706 return -EINVAL; 9707 } 9708 9709 /* With LD_ABS/IND some JITs save/restore skb from r1. */ 9710 changes_data = bpf_helper_changes_pkt_data(fn->func); 9711 if (changes_data && fn->arg1_type != ARG_PTR_TO_CTX) { 9712 verbose(env, "kernel subsystem misconfigured func %s#%d: r1 != ctx\n", 9713 func_id_name(func_id), func_id); 9714 return -EINVAL; 9715 } 9716 9717 memset(&meta, 0, sizeof(meta)); 9718 meta.pkt_access = fn->pkt_access; 9719 9720 err = check_func_proto(fn, func_id); 9721 if (err) { 9722 verbose(env, "kernel subsystem misconfigured func %s#%d\n", 9723 func_id_name(func_id), func_id); 9724 return err; 9725 } 9726 9727 if (env->cur_state->active_rcu_lock) { 9728 if (fn->might_sleep) { 9729 verbose(env, "sleepable helper %s#%d in rcu_read_lock region\n", 9730 func_id_name(func_id), func_id); 9731 return -EINVAL; 9732 } 9733 9734 if (env->prog->aux->sleepable && is_storage_get_function(func_id)) 9735 env->insn_aux_data[insn_idx].storage_get_func_atomic = true; 9736 } 9737 9738 meta.func_id = func_id; 9739 /* check args */ 9740 for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++) { 9741 err = check_func_arg(env, i, &meta, fn, insn_idx); 9742 if (err) 9743 return err; 9744 } 9745 9746 err = record_func_map(env, &meta, func_id, insn_idx); 9747 if (err) 9748 return err; 9749 9750 err = record_func_key(env, &meta, func_id, insn_idx); 9751 if (err) 9752 return err; 9753 9754 /* Mark slots with STACK_MISC in case of raw mode, stack offset 9755 * is inferred from register state. 9756 */ 9757 for (i = 0; i < meta.access_size; i++) { 9758 err = check_mem_access(env, insn_idx, meta.regno, i, BPF_B, 9759 BPF_WRITE, -1, false, false); 9760 if (err) 9761 return err; 9762 } 9763 9764 regs = cur_regs(env); 9765 9766 if (meta.release_regno) { 9767 err = -EINVAL; 9768 /* This can only be set for PTR_TO_STACK, as CONST_PTR_TO_DYNPTR cannot 9769 * be released by any dynptr helper. Hence, unmark_stack_slots_dynptr 9770 * is safe to do directly. 9771 */ 9772 if (arg_type_is_dynptr(fn->arg_type[meta.release_regno - BPF_REG_1])) { 9773 if (regs[meta.release_regno].type == CONST_PTR_TO_DYNPTR) { 9774 verbose(env, "verifier internal error: CONST_PTR_TO_DYNPTR cannot be released\n"); 9775 return -EFAULT; 9776 } 9777 err = unmark_stack_slots_dynptr(env, ®s[meta.release_regno]); 9778 } else if (func_id == BPF_FUNC_kptr_xchg && meta.ref_obj_id) { 9779 u32 ref_obj_id = meta.ref_obj_id; 9780 bool in_rcu = in_rcu_cs(env); 9781 struct bpf_func_state *state; 9782 struct bpf_reg_state *reg; 9783 9784 err = release_reference_state(cur_func(env), ref_obj_id); 9785 if (!err) { 9786 bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({ 9787 if (reg->ref_obj_id == ref_obj_id) { 9788 if (in_rcu && (reg->type & MEM_ALLOC) && (reg->type & MEM_PERCPU)) { 9789 reg->ref_obj_id = 0; 9790 reg->type &= ~MEM_ALLOC; 9791 reg->type |= MEM_RCU; 9792 } else { 9793 mark_reg_invalid(env, reg); 9794 } 9795 } 9796 })); 9797 } 9798 } else if (meta.ref_obj_id) { 9799 err = release_reference(env, meta.ref_obj_id); 9800 } else if (register_is_null(®s[meta.release_regno])) { 9801 /* meta.ref_obj_id can only be 0 if register that is meant to be 9802 * released is NULL, which must be > R0. 9803 */ 9804 err = 0; 9805 } 9806 if (err) { 9807 verbose(env, "func %s#%d reference has not been acquired before\n", 9808 func_id_name(func_id), func_id); 9809 return err; 9810 } 9811 } 9812 9813 switch (func_id) { 9814 case BPF_FUNC_tail_call: 9815 err = check_reference_leak(env, false); 9816 if (err) { 9817 verbose(env, "tail_call would lead to reference leak\n"); 9818 return err; 9819 } 9820 break; 9821 case BPF_FUNC_get_local_storage: 9822 /* check that flags argument in get_local_storage(map, flags) is 0, 9823 * this is required because get_local_storage() can't return an error. 9824 */ 9825 if (!register_is_null(®s[BPF_REG_2])) { 9826 verbose(env, "get_local_storage() doesn't support non-zero flags\n"); 9827 return -EINVAL; 9828 } 9829 break; 9830 case BPF_FUNC_for_each_map_elem: 9831 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno, 9832 set_map_elem_callback_state); 9833 break; 9834 case BPF_FUNC_timer_set_callback: 9835 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno, 9836 set_timer_callback_state); 9837 break; 9838 case BPF_FUNC_find_vma: 9839 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno, 9840 set_find_vma_callback_state); 9841 break; 9842 case BPF_FUNC_snprintf: 9843 err = check_bpf_snprintf_call(env, regs); 9844 break; 9845 case BPF_FUNC_loop: 9846 update_loop_inline_state(env, meta.subprogno); 9847 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno, 9848 set_loop_callback_state); 9849 break; 9850 case BPF_FUNC_dynptr_from_mem: 9851 if (regs[BPF_REG_1].type != PTR_TO_MAP_VALUE) { 9852 verbose(env, "Unsupported reg type %s for bpf_dynptr_from_mem data\n", 9853 reg_type_str(env, regs[BPF_REG_1].type)); 9854 return -EACCES; 9855 } 9856 break; 9857 case BPF_FUNC_set_retval: 9858 if (prog_type == BPF_PROG_TYPE_LSM && 9859 env->prog->expected_attach_type == BPF_LSM_CGROUP) { 9860 if (!env->prog->aux->attach_func_proto->type) { 9861 /* Make sure programs that attach to void 9862 * hooks don't try to modify return value. 9863 */ 9864 verbose(env, "BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n"); 9865 return -EINVAL; 9866 } 9867 } 9868 break; 9869 case BPF_FUNC_dynptr_data: 9870 { 9871 struct bpf_reg_state *reg; 9872 int id, ref_obj_id; 9873 9874 reg = get_dynptr_arg_reg(env, fn, regs); 9875 if (!reg) 9876 return -EFAULT; 9877 9878 9879 if (meta.dynptr_id) { 9880 verbose(env, "verifier internal error: meta.dynptr_id already set\n"); 9881 return -EFAULT; 9882 } 9883 if (meta.ref_obj_id) { 9884 verbose(env, "verifier internal error: meta.ref_obj_id already set\n"); 9885 return -EFAULT; 9886 } 9887 9888 id = dynptr_id(env, reg); 9889 if (id < 0) { 9890 verbose(env, "verifier internal error: failed to obtain dynptr id\n"); 9891 return id; 9892 } 9893 9894 ref_obj_id = dynptr_ref_obj_id(env, reg); 9895 if (ref_obj_id < 0) { 9896 verbose(env, "verifier internal error: failed to obtain dynptr ref_obj_id\n"); 9897 return ref_obj_id; 9898 } 9899 9900 meta.dynptr_id = id; 9901 meta.ref_obj_id = ref_obj_id; 9902 9903 break; 9904 } 9905 case BPF_FUNC_dynptr_write: 9906 { 9907 enum bpf_dynptr_type dynptr_type; 9908 struct bpf_reg_state *reg; 9909 9910 reg = get_dynptr_arg_reg(env, fn, regs); 9911 if (!reg) 9912 return -EFAULT; 9913 9914 dynptr_type = dynptr_get_type(env, reg); 9915 if (dynptr_type == BPF_DYNPTR_TYPE_INVALID) 9916 return -EFAULT; 9917 9918 if (dynptr_type == BPF_DYNPTR_TYPE_SKB) 9919 /* this will trigger clear_all_pkt_pointers(), which will 9920 * invalidate all dynptr slices associated with the skb 9921 */ 9922 changes_data = true; 9923 9924 break; 9925 } 9926 case BPF_FUNC_per_cpu_ptr: 9927 case BPF_FUNC_this_cpu_ptr: 9928 { 9929 struct bpf_reg_state *reg = ®s[BPF_REG_1]; 9930 const struct btf_type *type; 9931 9932 if (reg->type & MEM_RCU) { 9933 type = btf_type_by_id(reg->btf, reg->btf_id); 9934 if (!type || !btf_type_is_struct(type)) { 9935 verbose(env, "Helper has invalid btf/btf_id in R1\n"); 9936 return -EFAULT; 9937 } 9938 returns_cpu_specific_alloc_ptr = true; 9939 env->insn_aux_data[insn_idx].call_with_percpu_alloc_ptr = true; 9940 } 9941 break; 9942 } 9943 case BPF_FUNC_user_ringbuf_drain: 9944 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno, 9945 set_user_ringbuf_callback_state); 9946 break; 9947 } 9948 9949 if (err) 9950 return err; 9951 9952 /* reset caller saved regs */ 9953 for (i = 0; i < CALLER_SAVED_REGS; i++) { 9954 mark_reg_not_init(env, regs, caller_saved[i]); 9955 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK); 9956 } 9957 9958 /* helper call returns 64-bit value. */ 9959 regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG; 9960 9961 /* update return register (already marked as written above) */ 9962 ret_type = fn->ret_type; 9963 ret_flag = type_flag(ret_type); 9964 9965 switch (base_type(ret_type)) { 9966 case RET_INTEGER: 9967 /* sets type to SCALAR_VALUE */ 9968 mark_reg_unknown(env, regs, BPF_REG_0); 9969 break; 9970 case RET_VOID: 9971 regs[BPF_REG_0].type = NOT_INIT; 9972 break; 9973 case RET_PTR_TO_MAP_VALUE: 9974 /* There is no offset yet applied, variable or fixed */ 9975 mark_reg_known_zero(env, regs, BPF_REG_0); 9976 /* remember map_ptr, so that check_map_access() 9977 * can check 'value_size' boundary of memory access 9978 * to map element returned from bpf_map_lookup_elem() 9979 */ 9980 if (meta.map_ptr == NULL) { 9981 verbose(env, 9982 "kernel subsystem misconfigured verifier\n"); 9983 return -EINVAL; 9984 } 9985 regs[BPF_REG_0].map_ptr = meta.map_ptr; 9986 regs[BPF_REG_0].map_uid = meta.map_uid; 9987 regs[BPF_REG_0].type = PTR_TO_MAP_VALUE | ret_flag; 9988 if (!type_may_be_null(ret_type) && 9989 btf_record_has_field(meta.map_ptr->record, BPF_SPIN_LOCK)) { 9990 regs[BPF_REG_0].id = ++env->id_gen; 9991 } 9992 break; 9993 case RET_PTR_TO_SOCKET: 9994 mark_reg_known_zero(env, regs, BPF_REG_0); 9995 regs[BPF_REG_0].type = PTR_TO_SOCKET | ret_flag; 9996 break; 9997 case RET_PTR_TO_SOCK_COMMON: 9998 mark_reg_known_zero(env, regs, BPF_REG_0); 9999 regs[BPF_REG_0].type = PTR_TO_SOCK_COMMON | ret_flag; 10000 break; 10001 case RET_PTR_TO_TCP_SOCK: 10002 mark_reg_known_zero(env, regs, BPF_REG_0); 10003 regs[BPF_REG_0].type = PTR_TO_TCP_SOCK | ret_flag; 10004 break; 10005 case RET_PTR_TO_MEM: 10006 mark_reg_known_zero(env, regs, BPF_REG_0); 10007 regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag; 10008 regs[BPF_REG_0].mem_size = meta.mem_size; 10009 break; 10010 case RET_PTR_TO_MEM_OR_BTF_ID: 10011 { 10012 const struct btf_type *t; 10013 10014 mark_reg_known_zero(env, regs, BPF_REG_0); 10015 t = btf_type_skip_modifiers(meta.ret_btf, meta.ret_btf_id, NULL); 10016 if (!btf_type_is_struct(t)) { 10017 u32 tsize; 10018 const struct btf_type *ret; 10019 const char *tname; 10020 10021 /* resolve the type size of ksym. */ 10022 ret = btf_resolve_size(meta.ret_btf, t, &tsize); 10023 if (IS_ERR(ret)) { 10024 tname = btf_name_by_offset(meta.ret_btf, t->name_off); 10025 verbose(env, "unable to resolve the size of type '%s': %ld\n", 10026 tname, PTR_ERR(ret)); 10027 return -EINVAL; 10028 } 10029 regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag; 10030 regs[BPF_REG_0].mem_size = tsize; 10031 } else { 10032 if (returns_cpu_specific_alloc_ptr) { 10033 regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC | MEM_RCU; 10034 } else { 10035 /* MEM_RDONLY may be carried from ret_flag, but it 10036 * doesn't apply on PTR_TO_BTF_ID. Fold it, otherwise 10037 * it will confuse the check of PTR_TO_BTF_ID in 10038 * check_mem_access(). 10039 */ 10040 ret_flag &= ~MEM_RDONLY; 10041 regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag; 10042 } 10043 10044 regs[BPF_REG_0].btf = meta.ret_btf; 10045 regs[BPF_REG_0].btf_id = meta.ret_btf_id; 10046 } 10047 break; 10048 } 10049 case RET_PTR_TO_BTF_ID: 10050 { 10051 struct btf *ret_btf; 10052 int ret_btf_id; 10053 10054 mark_reg_known_zero(env, regs, BPF_REG_0); 10055 regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag; 10056 if (func_id == BPF_FUNC_kptr_xchg) { 10057 ret_btf = meta.kptr_field->kptr.btf; 10058 ret_btf_id = meta.kptr_field->kptr.btf_id; 10059 if (!btf_is_kernel(ret_btf)) { 10060 regs[BPF_REG_0].type |= MEM_ALLOC; 10061 if (meta.kptr_field->type == BPF_KPTR_PERCPU) 10062 regs[BPF_REG_0].type |= MEM_PERCPU; 10063 } 10064 } else { 10065 if (fn->ret_btf_id == BPF_PTR_POISON) { 10066 verbose(env, "verifier internal error:"); 10067 verbose(env, "func %s has non-overwritten BPF_PTR_POISON return type\n", 10068 func_id_name(func_id)); 10069 return -EINVAL; 10070 } 10071 ret_btf = btf_vmlinux; 10072 ret_btf_id = *fn->ret_btf_id; 10073 } 10074 if (ret_btf_id == 0) { 10075 verbose(env, "invalid return type %u of func %s#%d\n", 10076 base_type(ret_type), func_id_name(func_id), 10077 func_id); 10078 return -EINVAL; 10079 } 10080 regs[BPF_REG_0].btf = ret_btf; 10081 regs[BPF_REG_0].btf_id = ret_btf_id; 10082 break; 10083 } 10084 default: 10085 verbose(env, "unknown return type %u of func %s#%d\n", 10086 base_type(ret_type), func_id_name(func_id), func_id); 10087 return -EINVAL; 10088 } 10089 10090 if (type_may_be_null(regs[BPF_REG_0].type)) 10091 regs[BPF_REG_0].id = ++env->id_gen; 10092 10093 if (helper_multiple_ref_obj_use(func_id, meta.map_ptr)) { 10094 verbose(env, "verifier internal error: func %s#%d sets ref_obj_id more than once\n", 10095 func_id_name(func_id), func_id); 10096 return -EFAULT; 10097 } 10098 10099 if (is_dynptr_ref_function(func_id)) 10100 regs[BPF_REG_0].dynptr_id = meta.dynptr_id; 10101 10102 if (is_ptr_cast_function(func_id) || is_dynptr_ref_function(func_id)) { 10103 /* For release_reference() */ 10104 regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id; 10105 } else if (is_acquire_function(func_id, meta.map_ptr)) { 10106 int id = acquire_reference_state(env, insn_idx); 10107 10108 if (id < 0) 10109 return id; 10110 /* For mark_ptr_or_null_reg() */ 10111 regs[BPF_REG_0].id = id; 10112 /* For release_reference() */ 10113 regs[BPF_REG_0].ref_obj_id = id; 10114 } 10115 10116 do_refine_retval_range(regs, fn->ret_type, func_id, &meta); 10117 10118 err = check_map_func_compatibility(env, meta.map_ptr, func_id); 10119 if (err) 10120 return err; 10121 10122 if ((func_id == BPF_FUNC_get_stack || 10123 func_id == BPF_FUNC_get_task_stack) && 10124 !env->prog->has_callchain_buf) { 10125 const char *err_str; 10126 10127 #ifdef CONFIG_PERF_EVENTS 10128 err = get_callchain_buffers(sysctl_perf_event_max_stack); 10129 err_str = "cannot get callchain buffer for func %s#%d\n"; 10130 #else 10131 err = -ENOTSUPP; 10132 err_str = "func %s#%d not supported without CONFIG_PERF_EVENTS\n"; 10133 #endif 10134 if (err) { 10135 verbose(env, err_str, func_id_name(func_id), func_id); 10136 return err; 10137 } 10138 10139 env->prog->has_callchain_buf = true; 10140 } 10141 10142 if (func_id == BPF_FUNC_get_stackid || func_id == BPF_FUNC_get_stack) 10143 env->prog->call_get_stack = true; 10144 10145 if (func_id == BPF_FUNC_get_func_ip) { 10146 if (check_get_func_ip(env)) 10147 return -ENOTSUPP; 10148 env->prog->call_get_func_ip = true; 10149 } 10150 10151 if (changes_data) 10152 clear_all_pkt_pointers(env); 10153 return 0; 10154 } 10155 10156 /* mark_btf_func_reg_size() is used when the reg size is determined by 10157 * the BTF func_proto's return value size and argument. 10158 */ 10159 static void mark_btf_func_reg_size(struct bpf_verifier_env *env, u32 regno, 10160 size_t reg_size) 10161 { 10162 struct bpf_reg_state *reg = &cur_regs(env)[regno]; 10163 10164 if (regno == BPF_REG_0) { 10165 /* Function return value */ 10166 reg->live |= REG_LIVE_WRITTEN; 10167 reg->subreg_def = reg_size == sizeof(u64) ? 10168 DEF_NOT_SUBREG : env->insn_idx + 1; 10169 } else { 10170 /* Function argument */ 10171 if (reg_size == sizeof(u64)) { 10172 mark_insn_zext(env, reg); 10173 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64); 10174 } else { 10175 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ32); 10176 } 10177 } 10178 } 10179 10180 static bool is_kfunc_acquire(struct bpf_kfunc_call_arg_meta *meta) 10181 { 10182 return meta->kfunc_flags & KF_ACQUIRE; 10183 } 10184 10185 static bool is_kfunc_release(struct bpf_kfunc_call_arg_meta *meta) 10186 { 10187 return meta->kfunc_flags & KF_RELEASE; 10188 } 10189 10190 static bool is_kfunc_trusted_args(struct bpf_kfunc_call_arg_meta *meta) 10191 { 10192 return (meta->kfunc_flags & KF_TRUSTED_ARGS) || is_kfunc_release(meta); 10193 } 10194 10195 static bool is_kfunc_sleepable(struct bpf_kfunc_call_arg_meta *meta) 10196 { 10197 return meta->kfunc_flags & KF_SLEEPABLE; 10198 } 10199 10200 static bool is_kfunc_destructive(struct bpf_kfunc_call_arg_meta *meta) 10201 { 10202 return meta->kfunc_flags & KF_DESTRUCTIVE; 10203 } 10204 10205 static bool is_kfunc_rcu(struct bpf_kfunc_call_arg_meta *meta) 10206 { 10207 return meta->kfunc_flags & KF_RCU; 10208 } 10209 10210 static bool __kfunc_param_match_suffix(const struct btf *btf, 10211 const struct btf_param *arg, 10212 const char *suffix) 10213 { 10214 int suffix_len = strlen(suffix), len; 10215 const char *param_name; 10216 10217 /* In the future, this can be ported to use BTF tagging */ 10218 param_name = btf_name_by_offset(btf, arg->name_off); 10219 if (str_is_empty(param_name)) 10220 return false; 10221 len = strlen(param_name); 10222 if (len < suffix_len) 10223 return false; 10224 param_name += len - suffix_len; 10225 return !strncmp(param_name, suffix, suffix_len); 10226 } 10227 10228 static bool is_kfunc_arg_mem_size(const struct btf *btf, 10229 const struct btf_param *arg, 10230 const struct bpf_reg_state *reg) 10231 { 10232 const struct btf_type *t; 10233 10234 t = btf_type_skip_modifiers(btf, arg->type, NULL); 10235 if (!btf_type_is_scalar(t) || reg->type != SCALAR_VALUE) 10236 return false; 10237 10238 return __kfunc_param_match_suffix(btf, arg, "__sz"); 10239 } 10240 10241 static bool is_kfunc_arg_const_mem_size(const struct btf *btf, 10242 const struct btf_param *arg, 10243 const struct bpf_reg_state *reg) 10244 { 10245 const struct btf_type *t; 10246 10247 t = btf_type_skip_modifiers(btf, arg->type, NULL); 10248 if (!btf_type_is_scalar(t) || reg->type != SCALAR_VALUE) 10249 return false; 10250 10251 return __kfunc_param_match_suffix(btf, arg, "__szk"); 10252 } 10253 10254 static bool is_kfunc_arg_optional(const struct btf *btf, const struct btf_param *arg) 10255 { 10256 return __kfunc_param_match_suffix(btf, arg, "__opt"); 10257 } 10258 10259 static bool is_kfunc_arg_constant(const struct btf *btf, const struct btf_param *arg) 10260 { 10261 return __kfunc_param_match_suffix(btf, arg, "__k"); 10262 } 10263 10264 static bool is_kfunc_arg_ignore(const struct btf *btf, const struct btf_param *arg) 10265 { 10266 return __kfunc_param_match_suffix(btf, arg, "__ign"); 10267 } 10268 10269 static bool is_kfunc_arg_alloc_obj(const struct btf *btf, const struct btf_param *arg) 10270 { 10271 return __kfunc_param_match_suffix(btf, arg, "__alloc"); 10272 } 10273 10274 static bool is_kfunc_arg_uninit(const struct btf *btf, const struct btf_param *arg) 10275 { 10276 return __kfunc_param_match_suffix(btf, arg, "__uninit"); 10277 } 10278 10279 static bool is_kfunc_arg_refcounted_kptr(const struct btf *btf, const struct btf_param *arg) 10280 { 10281 return __kfunc_param_match_suffix(btf, arg, "__refcounted_kptr"); 10282 } 10283 10284 static bool is_kfunc_arg_scalar_with_name(const struct btf *btf, 10285 const struct btf_param *arg, 10286 const char *name) 10287 { 10288 int len, target_len = strlen(name); 10289 const char *param_name; 10290 10291 param_name = btf_name_by_offset(btf, arg->name_off); 10292 if (str_is_empty(param_name)) 10293 return false; 10294 len = strlen(param_name); 10295 if (len != target_len) 10296 return false; 10297 if (strcmp(param_name, name)) 10298 return false; 10299 10300 return true; 10301 } 10302 10303 enum { 10304 KF_ARG_DYNPTR_ID, 10305 KF_ARG_LIST_HEAD_ID, 10306 KF_ARG_LIST_NODE_ID, 10307 KF_ARG_RB_ROOT_ID, 10308 KF_ARG_RB_NODE_ID, 10309 }; 10310 10311 BTF_ID_LIST(kf_arg_btf_ids) 10312 BTF_ID(struct, bpf_dynptr_kern) 10313 BTF_ID(struct, bpf_list_head) 10314 BTF_ID(struct, bpf_list_node) 10315 BTF_ID(struct, bpf_rb_root) 10316 BTF_ID(struct, bpf_rb_node) 10317 10318 static bool __is_kfunc_ptr_arg_type(const struct btf *btf, 10319 const struct btf_param *arg, int type) 10320 { 10321 const struct btf_type *t; 10322 u32 res_id; 10323 10324 t = btf_type_skip_modifiers(btf, arg->type, NULL); 10325 if (!t) 10326 return false; 10327 if (!btf_type_is_ptr(t)) 10328 return false; 10329 t = btf_type_skip_modifiers(btf, t->type, &res_id); 10330 if (!t) 10331 return false; 10332 return btf_types_are_same(btf, res_id, btf_vmlinux, kf_arg_btf_ids[type]); 10333 } 10334 10335 static bool is_kfunc_arg_dynptr(const struct btf *btf, const struct btf_param *arg) 10336 { 10337 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_DYNPTR_ID); 10338 } 10339 10340 static bool is_kfunc_arg_list_head(const struct btf *btf, const struct btf_param *arg) 10341 { 10342 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_LIST_HEAD_ID); 10343 } 10344 10345 static bool is_kfunc_arg_list_node(const struct btf *btf, const struct btf_param *arg) 10346 { 10347 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_LIST_NODE_ID); 10348 } 10349 10350 static bool is_kfunc_arg_rbtree_root(const struct btf *btf, const struct btf_param *arg) 10351 { 10352 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_RB_ROOT_ID); 10353 } 10354 10355 static bool is_kfunc_arg_rbtree_node(const struct btf *btf, const struct btf_param *arg) 10356 { 10357 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_RB_NODE_ID); 10358 } 10359 10360 static bool is_kfunc_arg_callback(struct bpf_verifier_env *env, const struct btf *btf, 10361 const struct btf_param *arg) 10362 { 10363 const struct btf_type *t; 10364 10365 t = btf_type_resolve_func_ptr(btf, arg->type, NULL); 10366 if (!t) 10367 return false; 10368 10369 return true; 10370 } 10371 10372 /* Returns true if struct is composed of scalars, 4 levels of nesting allowed */ 10373 static bool __btf_type_is_scalar_struct(struct bpf_verifier_env *env, 10374 const struct btf *btf, 10375 const struct btf_type *t, int rec) 10376 { 10377 const struct btf_type *member_type; 10378 const struct btf_member *member; 10379 u32 i; 10380 10381 if (!btf_type_is_struct(t)) 10382 return false; 10383 10384 for_each_member(i, t, member) { 10385 const struct btf_array *array; 10386 10387 member_type = btf_type_skip_modifiers(btf, member->type, NULL); 10388 if (btf_type_is_struct(member_type)) { 10389 if (rec >= 3) { 10390 verbose(env, "max struct nesting depth exceeded\n"); 10391 return false; 10392 } 10393 if (!__btf_type_is_scalar_struct(env, btf, member_type, rec + 1)) 10394 return false; 10395 continue; 10396 } 10397 if (btf_type_is_array(member_type)) { 10398 array = btf_array(member_type); 10399 if (!array->nelems) 10400 return false; 10401 member_type = btf_type_skip_modifiers(btf, array->type, NULL); 10402 if (!btf_type_is_scalar(member_type)) 10403 return false; 10404 continue; 10405 } 10406 if (!btf_type_is_scalar(member_type)) 10407 return false; 10408 } 10409 return true; 10410 } 10411 10412 enum kfunc_ptr_arg_type { 10413 KF_ARG_PTR_TO_CTX, 10414 KF_ARG_PTR_TO_ALLOC_BTF_ID, /* Allocated object */ 10415 KF_ARG_PTR_TO_REFCOUNTED_KPTR, /* Refcounted local kptr */ 10416 KF_ARG_PTR_TO_DYNPTR, 10417 KF_ARG_PTR_TO_ITER, 10418 KF_ARG_PTR_TO_LIST_HEAD, 10419 KF_ARG_PTR_TO_LIST_NODE, 10420 KF_ARG_PTR_TO_BTF_ID, /* Also covers reg2btf_ids conversions */ 10421 KF_ARG_PTR_TO_MEM, 10422 KF_ARG_PTR_TO_MEM_SIZE, /* Size derived from next argument, skip it */ 10423 KF_ARG_PTR_TO_CALLBACK, 10424 KF_ARG_PTR_TO_RB_ROOT, 10425 KF_ARG_PTR_TO_RB_NODE, 10426 }; 10427 10428 enum special_kfunc_type { 10429 KF_bpf_obj_new_impl, 10430 KF_bpf_obj_drop_impl, 10431 KF_bpf_refcount_acquire_impl, 10432 KF_bpf_list_push_front_impl, 10433 KF_bpf_list_push_back_impl, 10434 KF_bpf_list_pop_front, 10435 KF_bpf_list_pop_back, 10436 KF_bpf_cast_to_kern_ctx, 10437 KF_bpf_rdonly_cast, 10438 KF_bpf_rcu_read_lock, 10439 KF_bpf_rcu_read_unlock, 10440 KF_bpf_rbtree_remove, 10441 KF_bpf_rbtree_add_impl, 10442 KF_bpf_rbtree_first, 10443 KF_bpf_dynptr_from_skb, 10444 KF_bpf_dynptr_from_xdp, 10445 KF_bpf_dynptr_slice, 10446 KF_bpf_dynptr_slice_rdwr, 10447 KF_bpf_dynptr_clone, 10448 KF_bpf_percpu_obj_new_impl, 10449 KF_bpf_percpu_obj_drop_impl, 10450 KF_bpf_throw, 10451 }; 10452 10453 BTF_SET_START(special_kfunc_set) 10454 BTF_ID(func, bpf_obj_new_impl) 10455 BTF_ID(func, bpf_obj_drop_impl) 10456 BTF_ID(func, bpf_refcount_acquire_impl) 10457 BTF_ID(func, bpf_list_push_front_impl) 10458 BTF_ID(func, bpf_list_push_back_impl) 10459 BTF_ID(func, bpf_list_pop_front) 10460 BTF_ID(func, bpf_list_pop_back) 10461 BTF_ID(func, bpf_cast_to_kern_ctx) 10462 BTF_ID(func, bpf_rdonly_cast) 10463 BTF_ID(func, bpf_rbtree_remove) 10464 BTF_ID(func, bpf_rbtree_add_impl) 10465 BTF_ID(func, bpf_rbtree_first) 10466 BTF_ID(func, bpf_dynptr_from_skb) 10467 BTF_ID(func, bpf_dynptr_from_xdp) 10468 BTF_ID(func, bpf_dynptr_slice) 10469 BTF_ID(func, bpf_dynptr_slice_rdwr) 10470 BTF_ID(func, bpf_dynptr_clone) 10471 BTF_ID(func, bpf_percpu_obj_new_impl) 10472 BTF_ID(func, bpf_percpu_obj_drop_impl) 10473 BTF_ID(func, bpf_throw) 10474 BTF_SET_END(special_kfunc_set) 10475 10476 BTF_ID_LIST(special_kfunc_list) 10477 BTF_ID(func, bpf_obj_new_impl) 10478 BTF_ID(func, bpf_obj_drop_impl) 10479 BTF_ID(func, bpf_refcount_acquire_impl) 10480 BTF_ID(func, bpf_list_push_front_impl) 10481 BTF_ID(func, bpf_list_push_back_impl) 10482 BTF_ID(func, bpf_list_pop_front) 10483 BTF_ID(func, bpf_list_pop_back) 10484 BTF_ID(func, bpf_cast_to_kern_ctx) 10485 BTF_ID(func, bpf_rdonly_cast) 10486 BTF_ID(func, bpf_rcu_read_lock) 10487 BTF_ID(func, bpf_rcu_read_unlock) 10488 BTF_ID(func, bpf_rbtree_remove) 10489 BTF_ID(func, bpf_rbtree_add_impl) 10490 BTF_ID(func, bpf_rbtree_first) 10491 BTF_ID(func, bpf_dynptr_from_skb) 10492 BTF_ID(func, bpf_dynptr_from_xdp) 10493 BTF_ID(func, bpf_dynptr_slice) 10494 BTF_ID(func, bpf_dynptr_slice_rdwr) 10495 BTF_ID(func, bpf_dynptr_clone) 10496 BTF_ID(func, bpf_percpu_obj_new_impl) 10497 BTF_ID(func, bpf_percpu_obj_drop_impl) 10498 BTF_ID(func, bpf_throw) 10499 10500 static bool is_kfunc_ret_null(struct bpf_kfunc_call_arg_meta *meta) 10501 { 10502 if (meta->func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl] && 10503 meta->arg_owning_ref) { 10504 return false; 10505 } 10506 10507 return meta->kfunc_flags & KF_RET_NULL; 10508 } 10509 10510 static bool is_kfunc_bpf_rcu_read_lock(struct bpf_kfunc_call_arg_meta *meta) 10511 { 10512 return meta->func_id == special_kfunc_list[KF_bpf_rcu_read_lock]; 10513 } 10514 10515 static bool is_kfunc_bpf_rcu_read_unlock(struct bpf_kfunc_call_arg_meta *meta) 10516 { 10517 return meta->func_id == special_kfunc_list[KF_bpf_rcu_read_unlock]; 10518 } 10519 10520 static enum kfunc_ptr_arg_type 10521 get_kfunc_ptr_arg_type(struct bpf_verifier_env *env, 10522 struct bpf_kfunc_call_arg_meta *meta, 10523 const struct btf_type *t, const struct btf_type *ref_t, 10524 const char *ref_tname, const struct btf_param *args, 10525 int argno, int nargs) 10526 { 10527 u32 regno = argno + 1; 10528 struct bpf_reg_state *regs = cur_regs(env); 10529 struct bpf_reg_state *reg = ®s[regno]; 10530 bool arg_mem_size = false; 10531 10532 if (meta->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx]) 10533 return KF_ARG_PTR_TO_CTX; 10534 10535 /* In this function, we verify the kfunc's BTF as per the argument type, 10536 * leaving the rest of the verification with respect to the register 10537 * type to our caller. When a set of conditions hold in the BTF type of 10538 * arguments, we resolve it to a known kfunc_ptr_arg_type. 10539 */ 10540 if (btf_get_prog_ctx_type(&env->log, meta->btf, t, resolve_prog_type(env->prog), argno)) 10541 return KF_ARG_PTR_TO_CTX; 10542 10543 if (is_kfunc_arg_alloc_obj(meta->btf, &args[argno])) 10544 return KF_ARG_PTR_TO_ALLOC_BTF_ID; 10545 10546 if (is_kfunc_arg_refcounted_kptr(meta->btf, &args[argno])) 10547 return KF_ARG_PTR_TO_REFCOUNTED_KPTR; 10548 10549 if (is_kfunc_arg_dynptr(meta->btf, &args[argno])) 10550 return KF_ARG_PTR_TO_DYNPTR; 10551 10552 if (is_kfunc_arg_iter(meta, argno)) 10553 return KF_ARG_PTR_TO_ITER; 10554 10555 if (is_kfunc_arg_list_head(meta->btf, &args[argno])) 10556 return KF_ARG_PTR_TO_LIST_HEAD; 10557 10558 if (is_kfunc_arg_list_node(meta->btf, &args[argno])) 10559 return KF_ARG_PTR_TO_LIST_NODE; 10560 10561 if (is_kfunc_arg_rbtree_root(meta->btf, &args[argno])) 10562 return KF_ARG_PTR_TO_RB_ROOT; 10563 10564 if (is_kfunc_arg_rbtree_node(meta->btf, &args[argno])) 10565 return KF_ARG_PTR_TO_RB_NODE; 10566 10567 if ((base_type(reg->type) == PTR_TO_BTF_ID || reg2btf_ids[base_type(reg->type)])) { 10568 if (!btf_type_is_struct(ref_t)) { 10569 verbose(env, "kernel function %s args#%d pointer type %s %s is not supported\n", 10570 meta->func_name, argno, btf_type_str(ref_t), ref_tname); 10571 return -EINVAL; 10572 } 10573 return KF_ARG_PTR_TO_BTF_ID; 10574 } 10575 10576 if (is_kfunc_arg_callback(env, meta->btf, &args[argno])) 10577 return KF_ARG_PTR_TO_CALLBACK; 10578 10579 10580 if (argno + 1 < nargs && 10581 (is_kfunc_arg_mem_size(meta->btf, &args[argno + 1], ®s[regno + 1]) || 10582 is_kfunc_arg_const_mem_size(meta->btf, &args[argno + 1], ®s[regno + 1]))) 10583 arg_mem_size = true; 10584 10585 /* This is the catch all argument type of register types supported by 10586 * check_helper_mem_access. However, we only allow when argument type is 10587 * pointer to scalar, or struct composed (recursively) of scalars. When 10588 * arg_mem_size is true, the pointer can be void *. 10589 */ 10590 if (!btf_type_is_scalar(ref_t) && !__btf_type_is_scalar_struct(env, meta->btf, ref_t, 0) && 10591 (arg_mem_size ? !btf_type_is_void(ref_t) : 1)) { 10592 verbose(env, "arg#%d pointer type %s %s must point to %sscalar, or struct with scalar\n", 10593 argno, btf_type_str(ref_t), ref_tname, arg_mem_size ? "void, " : ""); 10594 return -EINVAL; 10595 } 10596 return arg_mem_size ? KF_ARG_PTR_TO_MEM_SIZE : KF_ARG_PTR_TO_MEM; 10597 } 10598 10599 static int process_kf_arg_ptr_to_btf_id(struct bpf_verifier_env *env, 10600 struct bpf_reg_state *reg, 10601 const struct btf_type *ref_t, 10602 const char *ref_tname, u32 ref_id, 10603 struct bpf_kfunc_call_arg_meta *meta, 10604 int argno) 10605 { 10606 const struct btf_type *reg_ref_t; 10607 bool strict_type_match = false; 10608 const struct btf *reg_btf; 10609 const char *reg_ref_tname; 10610 u32 reg_ref_id; 10611 10612 if (base_type(reg->type) == PTR_TO_BTF_ID) { 10613 reg_btf = reg->btf; 10614 reg_ref_id = reg->btf_id; 10615 } else { 10616 reg_btf = btf_vmlinux; 10617 reg_ref_id = *reg2btf_ids[base_type(reg->type)]; 10618 } 10619 10620 /* Enforce strict type matching for calls to kfuncs that are acquiring 10621 * or releasing a reference, or are no-cast aliases. We do _not_ 10622 * enforce strict matching for plain KF_TRUSTED_ARGS kfuncs by default, 10623 * as we want to enable BPF programs to pass types that are bitwise 10624 * equivalent without forcing them to explicitly cast with something 10625 * like bpf_cast_to_kern_ctx(). 10626 * 10627 * For example, say we had a type like the following: 10628 * 10629 * struct bpf_cpumask { 10630 * cpumask_t cpumask; 10631 * refcount_t usage; 10632 * }; 10633 * 10634 * Note that as specified in <linux/cpumask.h>, cpumask_t is typedef'ed 10635 * to a struct cpumask, so it would be safe to pass a struct 10636 * bpf_cpumask * to a kfunc expecting a struct cpumask *. 10637 * 10638 * The philosophy here is similar to how we allow scalars of different 10639 * types to be passed to kfuncs as long as the size is the same. The 10640 * only difference here is that we're simply allowing 10641 * btf_struct_ids_match() to walk the struct at the 0th offset, and 10642 * resolve types. 10643 */ 10644 if (is_kfunc_acquire(meta) || 10645 (is_kfunc_release(meta) && reg->ref_obj_id) || 10646 btf_type_ids_nocast_alias(&env->log, reg_btf, reg_ref_id, meta->btf, ref_id)) 10647 strict_type_match = true; 10648 10649 WARN_ON_ONCE(is_kfunc_trusted_args(meta) && reg->off); 10650 10651 reg_ref_t = btf_type_skip_modifiers(reg_btf, reg_ref_id, ®_ref_id); 10652 reg_ref_tname = btf_name_by_offset(reg_btf, reg_ref_t->name_off); 10653 if (!btf_struct_ids_match(&env->log, reg_btf, reg_ref_id, reg->off, meta->btf, ref_id, strict_type_match)) { 10654 verbose(env, "kernel function %s args#%d expected pointer to %s %s but R%d has a pointer to %s %s\n", 10655 meta->func_name, argno, btf_type_str(ref_t), ref_tname, argno + 1, 10656 btf_type_str(reg_ref_t), reg_ref_tname); 10657 return -EINVAL; 10658 } 10659 return 0; 10660 } 10661 10662 static int ref_set_non_owning(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 10663 { 10664 struct bpf_verifier_state *state = env->cur_state; 10665 struct btf_record *rec = reg_btf_record(reg); 10666 10667 if (!state->active_lock.ptr) { 10668 verbose(env, "verifier internal error: ref_set_non_owning w/o active lock\n"); 10669 return -EFAULT; 10670 } 10671 10672 if (type_flag(reg->type) & NON_OWN_REF) { 10673 verbose(env, "verifier internal error: NON_OWN_REF already set\n"); 10674 return -EFAULT; 10675 } 10676 10677 reg->type |= NON_OWN_REF; 10678 if (rec->refcount_off >= 0) 10679 reg->type |= MEM_RCU; 10680 10681 return 0; 10682 } 10683 10684 static int ref_convert_owning_non_owning(struct bpf_verifier_env *env, u32 ref_obj_id) 10685 { 10686 struct bpf_func_state *state, *unused; 10687 struct bpf_reg_state *reg; 10688 int i; 10689 10690 state = cur_func(env); 10691 10692 if (!ref_obj_id) { 10693 verbose(env, "verifier internal error: ref_obj_id is zero for " 10694 "owning -> non-owning conversion\n"); 10695 return -EFAULT; 10696 } 10697 10698 for (i = 0; i < state->acquired_refs; i++) { 10699 if (state->refs[i].id != ref_obj_id) 10700 continue; 10701 10702 /* Clear ref_obj_id here so release_reference doesn't clobber 10703 * the whole reg 10704 */ 10705 bpf_for_each_reg_in_vstate(env->cur_state, unused, reg, ({ 10706 if (reg->ref_obj_id == ref_obj_id) { 10707 reg->ref_obj_id = 0; 10708 ref_set_non_owning(env, reg); 10709 } 10710 })); 10711 return 0; 10712 } 10713 10714 verbose(env, "verifier internal error: ref state missing for ref_obj_id\n"); 10715 return -EFAULT; 10716 } 10717 10718 /* Implementation details: 10719 * 10720 * Each register points to some region of memory, which we define as an 10721 * allocation. Each allocation may embed a bpf_spin_lock which protects any 10722 * special BPF objects (bpf_list_head, bpf_rb_root, etc.) part of the same 10723 * allocation. The lock and the data it protects are colocated in the same 10724 * memory region. 10725 * 10726 * Hence, everytime a register holds a pointer value pointing to such 10727 * allocation, the verifier preserves a unique reg->id for it. 10728 * 10729 * The verifier remembers the lock 'ptr' and the lock 'id' whenever 10730 * bpf_spin_lock is called. 10731 * 10732 * To enable this, lock state in the verifier captures two values: 10733 * active_lock.ptr = Register's type specific pointer 10734 * active_lock.id = A unique ID for each register pointer value 10735 * 10736 * Currently, PTR_TO_MAP_VALUE and PTR_TO_BTF_ID | MEM_ALLOC are the two 10737 * supported register types. 10738 * 10739 * The active_lock.ptr in case of map values is the reg->map_ptr, and in case of 10740 * allocated objects is the reg->btf pointer. 10741 * 10742 * The active_lock.id is non-unique for maps supporting direct_value_addr, as we 10743 * can establish the provenance of the map value statically for each distinct 10744 * lookup into such maps. They always contain a single map value hence unique 10745 * IDs for each pseudo load pessimizes the algorithm and rejects valid programs. 10746 * 10747 * So, in case of global variables, they use array maps with max_entries = 1, 10748 * hence their active_lock.ptr becomes map_ptr and id = 0 (since they all point 10749 * into the same map value as max_entries is 1, as described above). 10750 * 10751 * In case of inner map lookups, the inner map pointer has same map_ptr as the 10752 * outer map pointer (in verifier context), but each lookup into an inner map 10753 * assigns a fresh reg->id to the lookup, so while lookups into distinct inner 10754 * maps from the same outer map share the same map_ptr as active_lock.ptr, they 10755 * will get different reg->id assigned to each lookup, hence different 10756 * active_lock.id. 10757 * 10758 * In case of allocated objects, active_lock.ptr is the reg->btf, and the 10759 * reg->id is a unique ID preserved after the NULL pointer check on the pointer 10760 * returned from bpf_obj_new. Each allocation receives a new reg->id. 10761 */ 10762 static int check_reg_allocation_locked(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 10763 { 10764 void *ptr; 10765 u32 id; 10766 10767 switch ((int)reg->type) { 10768 case PTR_TO_MAP_VALUE: 10769 ptr = reg->map_ptr; 10770 break; 10771 case PTR_TO_BTF_ID | MEM_ALLOC: 10772 ptr = reg->btf; 10773 break; 10774 default: 10775 verbose(env, "verifier internal error: unknown reg type for lock check\n"); 10776 return -EFAULT; 10777 } 10778 id = reg->id; 10779 10780 if (!env->cur_state->active_lock.ptr) 10781 return -EINVAL; 10782 if (env->cur_state->active_lock.ptr != ptr || 10783 env->cur_state->active_lock.id != id) { 10784 verbose(env, "held lock and object are not in the same allocation\n"); 10785 return -EINVAL; 10786 } 10787 return 0; 10788 } 10789 10790 static bool is_bpf_list_api_kfunc(u32 btf_id) 10791 { 10792 return btf_id == special_kfunc_list[KF_bpf_list_push_front_impl] || 10793 btf_id == special_kfunc_list[KF_bpf_list_push_back_impl] || 10794 btf_id == special_kfunc_list[KF_bpf_list_pop_front] || 10795 btf_id == special_kfunc_list[KF_bpf_list_pop_back]; 10796 } 10797 10798 static bool is_bpf_rbtree_api_kfunc(u32 btf_id) 10799 { 10800 return btf_id == special_kfunc_list[KF_bpf_rbtree_add_impl] || 10801 btf_id == special_kfunc_list[KF_bpf_rbtree_remove] || 10802 btf_id == special_kfunc_list[KF_bpf_rbtree_first]; 10803 } 10804 10805 static bool is_bpf_graph_api_kfunc(u32 btf_id) 10806 { 10807 return is_bpf_list_api_kfunc(btf_id) || is_bpf_rbtree_api_kfunc(btf_id) || 10808 btf_id == special_kfunc_list[KF_bpf_refcount_acquire_impl]; 10809 } 10810 10811 static bool is_callback_calling_kfunc(u32 btf_id) 10812 { 10813 return btf_id == special_kfunc_list[KF_bpf_rbtree_add_impl]; 10814 } 10815 10816 static bool is_bpf_throw_kfunc(struct bpf_insn *insn) 10817 { 10818 return bpf_pseudo_kfunc_call(insn) && insn->off == 0 && 10819 insn->imm == special_kfunc_list[KF_bpf_throw]; 10820 } 10821 10822 static bool is_rbtree_lock_required_kfunc(u32 btf_id) 10823 { 10824 return is_bpf_rbtree_api_kfunc(btf_id); 10825 } 10826 10827 static bool check_kfunc_is_graph_root_api(struct bpf_verifier_env *env, 10828 enum btf_field_type head_field_type, 10829 u32 kfunc_btf_id) 10830 { 10831 bool ret; 10832 10833 switch (head_field_type) { 10834 case BPF_LIST_HEAD: 10835 ret = is_bpf_list_api_kfunc(kfunc_btf_id); 10836 break; 10837 case BPF_RB_ROOT: 10838 ret = is_bpf_rbtree_api_kfunc(kfunc_btf_id); 10839 break; 10840 default: 10841 verbose(env, "verifier internal error: unexpected graph root argument type %s\n", 10842 btf_field_type_name(head_field_type)); 10843 return false; 10844 } 10845 10846 if (!ret) 10847 verbose(env, "verifier internal error: %s head arg for unknown kfunc\n", 10848 btf_field_type_name(head_field_type)); 10849 return ret; 10850 } 10851 10852 static bool check_kfunc_is_graph_node_api(struct bpf_verifier_env *env, 10853 enum btf_field_type node_field_type, 10854 u32 kfunc_btf_id) 10855 { 10856 bool ret; 10857 10858 switch (node_field_type) { 10859 case BPF_LIST_NODE: 10860 ret = (kfunc_btf_id == special_kfunc_list[KF_bpf_list_push_front_impl] || 10861 kfunc_btf_id == special_kfunc_list[KF_bpf_list_push_back_impl]); 10862 break; 10863 case BPF_RB_NODE: 10864 ret = (kfunc_btf_id == special_kfunc_list[KF_bpf_rbtree_remove] || 10865 kfunc_btf_id == special_kfunc_list[KF_bpf_rbtree_add_impl]); 10866 break; 10867 default: 10868 verbose(env, "verifier internal error: unexpected graph node argument type %s\n", 10869 btf_field_type_name(node_field_type)); 10870 return false; 10871 } 10872 10873 if (!ret) 10874 verbose(env, "verifier internal error: %s node arg for unknown kfunc\n", 10875 btf_field_type_name(node_field_type)); 10876 return ret; 10877 } 10878 10879 static int 10880 __process_kf_arg_ptr_to_graph_root(struct bpf_verifier_env *env, 10881 struct bpf_reg_state *reg, u32 regno, 10882 struct bpf_kfunc_call_arg_meta *meta, 10883 enum btf_field_type head_field_type, 10884 struct btf_field **head_field) 10885 { 10886 const char *head_type_name; 10887 struct btf_field *field; 10888 struct btf_record *rec; 10889 u32 head_off; 10890 10891 if (meta->btf != btf_vmlinux) { 10892 verbose(env, "verifier internal error: unexpected btf mismatch in kfunc call\n"); 10893 return -EFAULT; 10894 } 10895 10896 if (!check_kfunc_is_graph_root_api(env, head_field_type, meta->func_id)) 10897 return -EFAULT; 10898 10899 head_type_name = btf_field_type_name(head_field_type); 10900 if (!tnum_is_const(reg->var_off)) { 10901 verbose(env, 10902 "R%d doesn't have constant offset. %s has to be at the constant offset\n", 10903 regno, head_type_name); 10904 return -EINVAL; 10905 } 10906 10907 rec = reg_btf_record(reg); 10908 head_off = reg->off + reg->var_off.value; 10909 field = btf_record_find(rec, head_off, head_field_type); 10910 if (!field) { 10911 verbose(env, "%s not found at offset=%u\n", head_type_name, head_off); 10912 return -EINVAL; 10913 } 10914 10915 /* All functions require bpf_list_head to be protected using a bpf_spin_lock */ 10916 if (check_reg_allocation_locked(env, reg)) { 10917 verbose(env, "bpf_spin_lock at off=%d must be held for %s\n", 10918 rec->spin_lock_off, head_type_name); 10919 return -EINVAL; 10920 } 10921 10922 if (*head_field) { 10923 verbose(env, "verifier internal error: repeating %s arg\n", head_type_name); 10924 return -EFAULT; 10925 } 10926 *head_field = field; 10927 return 0; 10928 } 10929 10930 static int process_kf_arg_ptr_to_list_head(struct bpf_verifier_env *env, 10931 struct bpf_reg_state *reg, u32 regno, 10932 struct bpf_kfunc_call_arg_meta *meta) 10933 { 10934 return __process_kf_arg_ptr_to_graph_root(env, reg, regno, meta, BPF_LIST_HEAD, 10935 &meta->arg_list_head.field); 10936 } 10937 10938 static int process_kf_arg_ptr_to_rbtree_root(struct bpf_verifier_env *env, 10939 struct bpf_reg_state *reg, u32 regno, 10940 struct bpf_kfunc_call_arg_meta *meta) 10941 { 10942 return __process_kf_arg_ptr_to_graph_root(env, reg, regno, meta, BPF_RB_ROOT, 10943 &meta->arg_rbtree_root.field); 10944 } 10945 10946 static int 10947 __process_kf_arg_ptr_to_graph_node(struct bpf_verifier_env *env, 10948 struct bpf_reg_state *reg, u32 regno, 10949 struct bpf_kfunc_call_arg_meta *meta, 10950 enum btf_field_type head_field_type, 10951 enum btf_field_type node_field_type, 10952 struct btf_field **node_field) 10953 { 10954 const char *node_type_name; 10955 const struct btf_type *et, *t; 10956 struct btf_field *field; 10957 u32 node_off; 10958 10959 if (meta->btf != btf_vmlinux) { 10960 verbose(env, "verifier internal error: unexpected btf mismatch in kfunc call\n"); 10961 return -EFAULT; 10962 } 10963 10964 if (!check_kfunc_is_graph_node_api(env, node_field_type, meta->func_id)) 10965 return -EFAULT; 10966 10967 node_type_name = btf_field_type_name(node_field_type); 10968 if (!tnum_is_const(reg->var_off)) { 10969 verbose(env, 10970 "R%d doesn't have constant offset. %s has to be at the constant offset\n", 10971 regno, node_type_name); 10972 return -EINVAL; 10973 } 10974 10975 node_off = reg->off + reg->var_off.value; 10976 field = reg_find_field_offset(reg, node_off, node_field_type); 10977 if (!field || field->offset != node_off) { 10978 verbose(env, "%s not found at offset=%u\n", node_type_name, node_off); 10979 return -EINVAL; 10980 } 10981 10982 field = *node_field; 10983 10984 et = btf_type_by_id(field->graph_root.btf, field->graph_root.value_btf_id); 10985 t = btf_type_by_id(reg->btf, reg->btf_id); 10986 if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, 0, field->graph_root.btf, 10987 field->graph_root.value_btf_id, true)) { 10988 verbose(env, "operation on %s expects arg#1 %s at offset=%d " 10989 "in struct %s, but arg is at offset=%d in struct %s\n", 10990 btf_field_type_name(head_field_type), 10991 btf_field_type_name(node_field_type), 10992 field->graph_root.node_offset, 10993 btf_name_by_offset(field->graph_root.btf, et->name_off), 10994 node_off, btf_name_by_offset(reg->btf, t->name_off)); 10995 return -EINVAL; 10996 } 10997 meta->arg_btf = reg->btf; 10998 meta->arg_btf_id = reg->btf_id; 10999 11000 if (node_off != field->graph_root.node_offset) { 11001 verbose(env, "arg#1 offset=%d, but expected %s at offset=%d in struct %s\n", 11002 node_off, btf_field_type_name(node_field_type), 11003 field->graph_root.node_offset, 11004 btf_name_by_offset(field->graph_root.btf, et->name_off)); 11005 return -EINVAL; 11006 } 11007 11008 return 0; 11009 } 11010 11011 static int process_kf_arg_ptr_to_list_node(struct bpf_verifier_env *env, 11012 struct bpf_reg_state *reg, u32 regno, 11013 struct bpf_kfunc_call_arg_meta *meta) 11014 { 11015 return __process_kf_arg_ptr_to_graph_node(env, reg, regno, meta, 11016 BPF_LIST_HEAD, BPF_LIST_NODE, 11017 &meta->arg_list_head.field); 11018 } 11019 11020 static int process_kf_arg_ptr_to_rbtree_node(struct bpf_verifier_env *env, 11021 struct bpf_reg_state *reg, u32 regno, 11022 struct bpf_kfunc_call_arg_meta *meta) 11023 { 11024 return __process_kf_arg_ptr_to_graph_node(env, reg, regno, meta, 11025 BPF_RB_ROOT, BPF_RB_NODE, 11026 &meta->arg_rbtree_root.field); 11027 } 11028 11029 static int check_kfunc_args(struct bpf_verifier_env *env, struct bpf_kfunc_call_arg_meta *meta, 11030 int insn_idx) 11031 { 11032 const char *func_name = meta->func_name, *ref_tname; 11033 const struct btf *btf = meta->btf; 11034 const struct btf_param *args; 11035 struct btf_record *rec; 11036 u32 i, nargs; 11037 int ret; 11038 11039 args = (const struct btf_param *)(meta->func_proto + 1); 11040 nargs = btf_type_vlen(meta->func_proto); 11041 if (nargs > MAX_BPF_FUNC_REG_ARGS) { 11042 verbose(env, "Function %s has %d > %d args\n", func_name, nargs, 11043 MAX_BPF_FUNC_REG_ARGS); 11044 return -EINVAL; 11045 } 11046 11047 /* Check that BTF function arguments match actual types that the 11048 * verifier sees. 11049 */ 11050 for (i = 0; i < nargs; i++) { 11051 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[i + 1]; 11052 const struct btf_type *t, *ref_t, *resolve_ret; 11053 enum bpf_arg_type arg_type = ARG_DONTCARE; 11054 u32 regno = i + 1, ref_id, type_size; 11055 bool is_ret_buf_sz = false; 11056 int kf_arg_type; 11057 11058 t = btf_type_skip_modifiers(btf, args[i].type, NULL); 11059 11060 if (is_kfunc_arg_ignore(btf, &args[i])) 11061 continue; 11062 11063 if (btf_type_is_scalar(t)) { 11064 if (reg->type != SCALAR_VALUE) { 11065 verbose(env, "R%d is not a scalar\n", regno); 11066 return -EINVAL; 11067 } 11068 11069 if (is_kfunc_arg_constant(meta->btf, &args[i])) { 11070 if (meta->arg_constant.found) { 11071 verbose(env, "verifier internal error: only one constant argument permitted\n"); 11072 return -EFAULT; 11073 } 11074 if (!tnum_is_const(reg->var_off)) { 11075 verbose(env, "R%d must be a known constant\n", regno); 11076 return -EINVAL; 11077 } 11078 ret = mark_chain_precision(env, regno); 11079 if (ret < 0) 11080 return ret; 11081 meta->arg_constant.found = true; 11082 meta->arg_constant.value = reg->var_off.value; 11083 } else if (is_kfunc_arg_scalar_with_name(btf, &args[i], "rdonly_buf_size")) { 11084 meta->r0_rdonly = true; 11085 is_ret_buf_sz = true; 11086 } else if (is_kfunc_arg_scalar_with_name(btf, &args[i], "rdwr_buf_size")) { 11087 is_ret_buf_sz = true; 11088 } 11089 11090 if (is_ret_buf_sz) { 11091 if (meta->r0_size) { 11092 verbose(env, "2 or more rdonly/rdwr_buf_size parameters for kfunc"); 11093 return -EINVAL; 11094 } 11095 11096 if (!tnum_is_const(reg->var_off)) { 11097 verbose(env, "R%d is not a const\n", regno); 11098 return -EINVAL; 11099 } 11100 11101 meta->r0_size = reg->var_off.value; 11102 ret = mark_chain_precision(env, regno); 11103 if (ret) 11104 return ret; 11105 } 11106 continue; 11107 } 11108 11109 if (!btf_type_is_ptr(t)) { 11110 verbose(env, "Unrecognized arg#%d type %s\n", i, btf_type_str(t)); 11111 return -EINVAL; 11112 } 11113 11114 if ((is_kfunc_trusted_args(meta) || is_kfunc_rcu(meta)) && 11115 (register_is_null(reg) || type_may_be_null(reg->type))) { 11116 verbose(env, "Possibly NULL pointer passed to trusted arg%d\n", i); 11117 return -EACCES; 11118 } 11119 11120 if (reg->ref_obj_id) { 11121 if (is_kfunc_release(meta) && meta->ref_obj_id) { 11122 verbose(env, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n", 11123 regno, reg->ref_obj_id, 11124 meta->ref_obj_id); 11125 return -EFAULT; 11126 } 11127 meta->ref_obj_id = reg->ref_obj_id; 11128 if (is_kfunc_release(meta)) 11129 meta->release_regno = regno; 11130 } 11131 11132 ref_t = btf_type_skip_modifiers(btf, t->type, &ref_id); 11133 ref_tname = btf_name_by_offset(btf, ref_t->name_off); 11134 11135 kf_arg_type = get_kfunc_ptr_arg_type(env, meta, t, ref_t, ref_tname, args, i, nargs); 11136 if (kf_arg_type < 0) 11137 return kf_arg_type; 11138 11139 switch (kf_arg_type) { 11140 case KF_ARG_PTR_TO_ALLOC_BTF_ID: 11141 case KF_ARG_PTR_TO_BTF_ID: 11142 if (!is_kfunc_trusted_args(meta) && !is_kfunc_rcu(meta)) 11143 break; 11144 11145 if (!is_trusted_reg(reg)) { 11146 if (!is_kfunc_rcu(meta)) { 11147 verbose(env, "R%d must be referenced or trusted\n", regno); 11148 return -EINVAL; 11149 } 11150 if (!is_rcu_reg(reg)) { 11151 verbose(env, "R%d must be a rcu pointer\n", regno); 11152 return -EINVAL; 11153 } 11154 } 11155 11156 fallthrough; 11157 case KF_ARG_PTR_TO_CTX: 11158 /* Trusted arguments have the same offset checks as release arguments */ 11159 arg_type |= OBJ_RELEASE; 11160 break; 11161 case KF_ARG_PTR_TO_DYNPTR: 11162 case KF_ARG_PTR_TO_ITER: 11163 case KF_ARG_PTR_TO_LIST_HEAD: 11164 case KF_ARG_PTR_TO_LIST_NODE: 11165 case KF_ARG_PTR_TO_RB_ROOT: 11166 case KF_ARG_PTR_TO_RB_NODE: 11167 case KF_ARG_PTR_TO_MEM: 11168 case KF_ARG_PTR_TO_MEM_SIZE: 11169 case KF_ARG_PTR_TO_CALLBACK: 11170 case KF_ARG_PTR_TO_REFCOUNTED_KPTR: 11171 /* Trusted by default */ 11172 break; 11173 default: 11174 WARN_ON_ONCE(1); 11175 return -EFAULT; 11176 } 11177 11178 if (is_kfunc_release(meta) && reg->ref_obj_id) 11179 arg_type |= OBJ_RELEASE; 11180 ret = check_func_arg_reg_off(env, reg, regno, arg_type); 11181 if (ret < 0) 11182 return ret; 11183 11184 switch (kf_arg_type) { 11185 case KF_ARG_PTR_TO_CTX: 11186 if (reg->type != PTR_TO_CTX) { 11187 verbose(env, "arg#%d expected pointer to ctx, but got %s\n", i, btf_type_str(t)); 11188 return -EINVAL; 11189 } 11190 11191 if (meta->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx]) { 11192 ret = get_kern_ctx_btf_id(&env->log, resolve_prog_type(env->prog)); 11193 if (ret < 0) 11194 return -EINVAL; 11195 meta->ret_btf_id = ret; 11196 } 11197 break; 11198 case KF_ARG_PTR_TO_ALLOC_BTF_ID: 11199 if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC)) { 11200 if (meta->func_id != special_kfunc_list[KF_bpf_obj_drop_impl]) { 11201 verbose(env, "arg#%d expected for bpf_obj_drop_impl()\n", i); 11202 return -EINVAL; 11203 } 11204 } else if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC | MEM_PERCPU)) { 11205 if (meta->func_id != special_kfunc_list[KF_bpf_percpu_obj_drop_impl]) { 11206 verbose(env, "arg#%d expected for bpf_percpu_obj_drop_impl()\n", i); 11207 return -EINVAL; 11208 } 11209 } else { 11210 verbose(env, "arg#%d expected pointer to allocated object\n", i); 11211 return -EINVAL; 11212 } 11213 if (!reg->ref_obj_id) { 11214 verbose(env, "allocated object must be referenced\n"); 11215 return -EINVAL; 11216 } 11217 if (meta->btf == btf_vmlinux) { 11218 meta->arg_btf = reg->btf; 11219 meta->arg_btf_id = reg->btf_id; 11220 } 11221 break; 11222 case KF_ARG_PTR_TO_DYNPTR: 11223 { 11224 enum bpf_arg_type dynptr_arg_type = ARG_PTR_TO_DYNPTR; 11225 int clone_ref_obj_id = 0; 11226 11227 if (reg->type != PTR_TO_STACK && 11228 reg->type != CONST_PTR_TO_DYNPTR) { 11229 verbose(env, "arg#%d expected pointer to stack or dynptr_ptr\n", i); 11230 return -EINVAL; 11231 } 11232 11233 if (reg->type == CONST_PTR_TO_DYNPTR) 11234 dynptr_arg_type |= MEM_RDONLY; 11235 11236 if (is_kfunc_arg_uninit(btf, &args[i])) 11237 dynptr_arg_type |= MEM_UNINIT; 11238 11239 if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_from_skb]) { 11240 dynptr_arg_type |= DYNPTR_TYPE_SKB; 11241 } else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_from_xdp]) { 11242 dynptr_arg_type |= DYNPTR_TYPE_XDP; 11243 } else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_clone] && 11244 (dynptr_arg_type & MEM_UNINIT)) { 11245 enum bpf_dynptr_type parent_type = meta->initialized_dynptr.type; 11246 11247 if (parent_type == BPF_DYNPTR_TYPE_INVALID) { 11248 verbose(env, "verifier internal error: no dynptr type for parent of clone\n"); 11249 return -EFAULT; 11250 } 11251 11252 dynptr_arg_type |= (unsigned int)get_dynptr_type_flag(parent_type); 11253 clone_ref_obj_id = meta->initialized_dynptr.ref_obj_id; 11254 if (dynptr_type_refcounted(parent_type) && !clone_ref_obj_id) { 11255 verbose(env, "verifier internal error: missing ref obj id for parent of clone\n"); 11256 return -EFAULT; 11257 } 11258 } 11259 11260 ret = process_dynptr_func(env, regno, insn_idx, dynptr_arg_type, clone_ref_obj_id); 11261 if (ret < 0) 11262 return ret; 11263 11264 if (!(dynptr_arg_type & MEM_UNINIT)) { 11265 int id = dynptr_id(env, reg); 11266 11267 if (id < 0) { 11268 verbose(env, "verifier internal error: failed to obtain dynptr id\n"); 11269 return id; 11270 } 11271 meta->initialized_dynptr.id = id; 11272 meta->initialized_dynptr.type = dynptr_get_type(env, reg); 11273 meta->initialized_dynptr.ref_obj_id = dynptr_ref_obj_id(env, reg); 11274 } 11275 11276 break; 11277 } 11278 case KF_ARG_PTR_TO_ITER: 11279 ret = process_iter_arg(env, regno, insn_idx, meta); 11280 if (ret < 0) 11281 return ret; 11282 break; 11283 case KF_ARG_PTR_TO_LIST_HEAD: 11284 if (reg->type != PTR_TO_MAP_VALUE && 11285 reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) { 11286 verbose(env, "arg#%d expected pointer to map value or allocated object\n", i); 11287 return -EINVAL; 11288 } 11289 if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC) && !reg->ref_obj_id) { 11290 verbose(env, "allocated object must be referenced\n"); 11291 return -EINVAL; 11292 } 11293 ret = process_kf_arg_ptr_to_list_head(env, reg, regno, meta); 11294 if (ret < 0) 11295 return ret; 11296 break; 11297 case KF_ARG_PTR_TO_RB_ROOT: 11298 if (reg->type != PTR_TO_MAP_VALUE && 11299 reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) { 11300 verbose(env, "arg#%d expected pointer to map value or allocated object\n", i); 11301 return -EINVAL; 11302 } 11303 if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC) && !reg->ref_obj_id) { 11304 verbose(env, "allocated object must be referenced\n"); 11305 return -EINVAL; 11306 } 11307 ret = process_kf_arg_ptr_to_rbtree_root(env, reg, regno, meta); 11308 if (ret < 0) 11309 return ret; 11310 break; 11311 case KF_ARG_PTR_TO_LIST_NODE: 11312 if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) { 11313 verbose(env, "arg#%d expected pointer to allocated object\n", i); 11314 return -EINVAL; 11315 } 11316 if (!reg->ref_obj_id) { 11317 verbose(env, "allocated object must be referenced\n"); 11318 return -EINVAL; 11319 } 11320 ret = process_kf_arg_ptr_to_list_node(env, reg, regno, meta); 11321 if (ret < 0) 11322 return ret; 11323 break; 11324 case KF_ARG_PTR_TO_RB_NODE: 11325 if (meta->func_id == special_kfunc_list[KF_bpf_rbtree_remove]) { 11326 if (!type_is_non_owning_ref(reg->type) || reg->ref_obj_id) { 11327 verbose(env, "rbtree_remove node input must be non-owning ref\n"); 11328 return -EINVAL; 11329 } 11330 if (in_rbtree_lock_required_cb(env)) { 11331 verbose(env, "rbtree_remove not allowed in rbtree cb\n"); 11332 return -EINVAL; 11333 } 11334 } else { 11335 if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) { 11336 verbose(env, "arg#%d expected pointer to allocated object\n", i); 11337 return -EINVAL; 11338 } 11339 if (!reg->ref_obj_id) { 11340 verbose(env, "allocated object must be referenced\n"); 11341 return -EINVAL; 11342 } 11343 } 11344 11345 ret = process_kf_arg_ptr_to_rbtree_node(env, reg, regno, meta); 11346 if (ret < 0) 11347 return ret; 11348 break; 11349 case KF_ARG_PTR_TO_BTF_ID: 11350 /* Only base_type is checked, further checks are done here */ 11351 if ((base_type(reg->type) != PTR_TO_BTF_ID || 11352 (bpf_type_has_unsafe_modifiers(reg->type) && !is_rcu_reg(reg))) && 11353 !reg2btf_ids[base_type(reg->type)]) { 11354 verbose(env, "arg#%d is %s ", i, reg_type_str(env, reg->type)); 11355 verbose(env, "expected %s or socket\n", 11356 reg_type_str(env, base_type(reg->type) | 11357 (type_flag(reg->type) & BPF_REG_TRUSTED_MODIFIERS))); 11358 return -EINVAL; 11359 } 11360 ret = process_kf_arg_ptr_to_btf_id(env, reg, ref_t, ref_tname, ref_id, meta, i); 11361 if (ret < 0) 11362 return ret; 11363 break; 11364 case KF_ARG_PTR_TO_MEM: 11365 resolve_ret = btf_resolve_size(btf, ref_t, &type_size); 11366 if (IS_ERR(resolve_ret)) { 11367 verbose(env, "arg#%d reference type('%s %s') size cannot be determined: %ld\n", 11368 i, btf_type_str(ref_t), ref_tname, PTR_ERR(resolve_ret)); 11369 return -EINVAL; 11370 } 11371 ret = check_mem_reg(env, reg, regno, type_size); 11372 if (ret < 0) 11373 return ret; 11374 break; 11375 case KF_ARG_PTR_TO_MEM_SIZE: 11376 { 11377 struct bpf_reg_state *buff_reg = ®s[regno]; 11378 const struct btf_param *buff_arg = &args[i]; 11379 struct bpf_reg_state *size_reg = ®s[regno + 1]; 11380 const struct btf_param *size_arg = &args[i + 1]; 11381 11382 if (!register_is_null(buff_reg) || !is_kfunc_arg_optional(meta->btf, buff_arg)) { 11383 ret = check_kfunc_mem_size_reg(env, size_reg, regno + 1); 11384 if (ret < 0) { 11385 verbose(env, "arg#%d arg#%d memory, len pair leads to invalid memory access\n", i, i + 1); 11386 return ret; 11387 } 11388 } 11389 11390 if (is_kfunc_arg_const_mem_size(meta->btf, size_arg, size_reg)) { 11391 if (meta->arg_constant.found) { 11392 verbose(env, "verifier internal error: only one constant argument permitted\n"); 11393 return -EFAULT; 11394 } 11395 if (!tnum_is_const(size_reg->var_off)) { 11396 verbose(env, "R%d must be a known constant\n", regno + 1); 11397 return -EINVAL; 11398 } 11399 meta->arg_constant.found = true; 11400 meta->arg_constant.value = size_reg->var_off.value; 11401 } 11402 11403 /* Skip next '__sz' or '__szk' argument */ 11404 i++; 11405 break; 11406 } 11407 case KF_ARG_PTR_TO_CALLBACK: 11408 if (reg->type != PTR_TO_FUNC) { 11409 verbose(env, "arg%d expected pointer to func\n", i); 11410 return -EINVAL; 11411 } 11412 meta->subprogno = reg->subprogno; 11413 break; 11414 case KF_ARG_PTR_TO_REFCOUNTED_KPTR: 11415 if (!type_is_ptr_alloc_obj(reg->type)) { 11416 verbose(env, "arg#%d is neither owning or non-owning ref\n", i); 11417 return -EINVAL; 11418 } 11419 if (!type_is_non_owning_ref(reg->type)) 11420 meta->arg_owning_ref = true; 11421 11422 rec = reg_btf_record(reg); 11423 if (!rec) { 11424 verbose(env, "verifier internal error: Couldn't find btf_record\n"); 11425 return -EFAULT; 11426 } 11427 11428 if (rec->refcount_off < 0) { 11429 verbose(env, "arg#%d doesn't point to a type with bpf_refcount field\n", i); 11430 return -EINVAL; 11431 } 11432 11433 meta->arg_btf = reg->btf; 11434 meta->arg_btf_id = reg->btf_id; 11435 break; 11436 } 11437 } 11438 11439 if (is_kfunc_release(meta) && !meta->release_regno) { 11440 verbose(env, "release kernel function %s expects refcounted PTR_TO_BTF_ID\n", 11441 func_name); 11442 return -EINVAL; 11443 } 11444 11445 return 0; 11446 } 11447 11448 static int fetch_kfunc_meta(struct bpf_verifier_env *env, 11449 struct bpf_insn *insn, 11450 struct bpf_kfunc_call_arg_meta *meta, 11451 const char **kfunc_name) 11452 { 11453 const struct btf_type *func, *func_proto; 11454 u32 func_id, *kfunc_flags; 11455 const char *func_name; 11456 struct btf *desc_btf; 11457 11458 if (kfunc_name) 11459 *kfunc_name = NULL; 11460 11461 if (!insn->imm) 11462 return -EINVAL; 11463 11464 desc_btf = find_kfunc_desc_btf(env, insn->off); 11465 if (IS_ERR(desc_btf)) 11466 return PTR_ERR(desc_btf); 11467 11468 func_id = insn->imm; 11469 func = btf_type_by_id(desc_btf, func_id); 11470 func_name = btf_name_by_offset(desc_btf, func->name_off); 11471 if (kfunc_name) 11472 *kfunc_name = func_name; 11473 func_proto = btf_type_by_id(desc_btf, func->type); 11474 11475 kfunc_flags = btf_kfunc_id_set_contains(desc_btf, func_id, env->prog); 11476 if (!kfunc_flags) { 11477 return -EACCES; 11478 } 11479 11480 memset(meta, 0, sizeof(*meta)); 11481 meta->btf = desc_btf; 11482 meta->func_id = func_id; 11483 meta->kfunc_flags = *kfunc_flags; 11484 meta->func_proto = func_proto; 11485 meta->func_name = func_name; 11486 11487 return 0; 11488 } 11489 11490 static int check_return_code(struct bpf_verifier_env *env, int regno); 11491 11492 static int check_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn, 11493 int *insn_idx_p) 11494 { 11495 const struct btf_type *t, *ptr_type; 11496 u32 i, nargs, ptr_type_id, release_ref_obj_id; 11497 struct bpf_reg_state *regs = cur_regs(env); 11498 const char *func_name, *ptr_type_name; 11499 bool sleepable, rcu_lock, rcu_unlock; 11500 struct bpf_kfunc_call_arg_meta meta; 11501 struct bpf_insn_aux_data *insn_aux; 11502 int err, insn_idx = *insn_idx_p; 11503 const struct btf_param *args; 11504 const struct btf_type *ret_t; 11505 struct btf *desc_btf; 11506 11507 /* skip for now, but return error when we find this in fixup_kfunc_call */ 11508 if (!insn->imm) 11509 return 0; 11510 11511 err = fetch_kfunc_meta(env, insn, &meta, &func_name); 11512 if (err == -EACCES && func_name) 11513 verbose(env, "calling kernel function %s is not allowed\n", func_name); 11514 if (err) 11515 return err; 11516 desc_btf = meta.btf; 11517 insn_aux = &env->insn_aux_data[insn_idx]; 11518 11519 insn_aux->is_iter_next = is_iter_next_kfunc(&meta); 11520 11521 if (is_kfunc_destructive(&meta) && !capable(CAP_SYS_BOOT)) { 11522 verbose(env, "destructive kfunc calls require CAP_SYS_BOOT capability\n"); 11523 return -EACCES; 11524 } 11525 11526 sleepable = is_kfunc_sleepable(&meta); 11527 if (sleepable && !env->prog->aux->sleepable) { 11528 verbose(env, "program must be sleepable to call sleepable kfunc %s\n", func_name); 11529 return -EACCES; 11530 } 11531 11532 rcu_lock = is_kfunc_bpf_rcu_read_lock(&meta); 11533 rcu_unlock = is_kfunc_bpf_rcu_read_unlock(&meta); 11534 11535 if (env->cur_state->active_rcu_lock) { 11536 struct bpf_func_state *state; 11537 struct bpf_reg_state *reg; 11538 11539 if (in_rbtree_lock_required_cb(env) && (rcu_lock || rcu_unlock)) { 11540 verbose(env, "Calling bpf_rcu_read_{lock,unlock} in unnecessary rbtree callback\n"); 11541 return -EACCES; 11542 } 11543 11544 if (rcu_lock) { 11545 verbose(env, "nested rcu read lock (kernel function %s)\n", func_name); 11546 return -EINVAL; 11547 } else if (rcu_unlock) { 11548 bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({ 11549 if (reg->type & MEM_RCU) { 11550 reg->type &= ~(MEM_RCU | PTR_MAYBE_NULL); 11551 reg->type |= PTR_UNTRUSTED; 11552 } 11553 })); 11554 env->cur_state->active_rcu_lock = false; 11555 } else if (sleepable) { 11556 verbose(env, "kernel func %s is sleepable within rcu_read_lock region\n", func_name); 11557 return -EACCES; 11558 } 11559 } else if (rcu_lock) { 11560 env->cur_state->active_rcu_lock = true; 11561 } else if (rcu_unlock) { 11562 verbose(env, "unmatched rcu read unlock (kernel function %s)\n", func_name); 11563 return -EINVAL; 11564 } 11565 11566 /* Check the arguments */ 11567 err = check_kfunc_args(env, &meta, insn_idx); 11568 if (err < 0) 11569 return err; 11570 /* In case of release function, we get register number of refcounted 11571 * PTR_TO_BTF_ID in bpf_kfunc_arg_meta, do the release now. 11572 */ 11573 if (meta.release_regno) { 11574 err = release_reference(env, regs[meta.release_regno].ref_obj_id); 11575 if (err) { 11576 verbose(env, "kfunc %s#%d reference has not been acquired before\n", 11577 func_name, meta.func_id); 11578 return err; 11579 } 11580 } 11581 11582 if (meta.func_id == special_kfunc_list[KF_bpf_list_push_front_impl] || 11583 meta.func_id == special_kfunc_list[KF_bpf_list_push_back_impl] || 11584 meta.func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) { 11585 release_ref_obj_id = regs[BPF_REG_2].ref_obj_id; 11586 insn_aux->insert_off = regs[BPF_REG_2].off; 11587 insn_aux->kptr_struct_meta = btf_find_struct_meta(meta.arg_btf, meta.arg_btf_id); 11588 err = ref_convert_owning_non_owning(env, release_ref_obj_id); 11589 if (err) { 11590 verbose(env, "kfunc %s#%d conversion of owning ref to non-owning failed\n", 11591 func_name, meta.func_id); 11592 return err; 11593 } 11594 11595 err = release_reference(env, release_ref_obj_id); 11596 if (err) { 11597 verbose(env, "kfunc %s#%d reference has not been acquired before\n", 11598 func_name, meta.func_id); 11599 return err; 11600 } 11601 } 11602 11603 if (meta.func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) { 11604 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno, 11605 set_rbtree_add_callback_state); 11606 if (err) { 11607 verbose(env, "kfunc %s#%d failed callback verification\n", 11608 func_name, meta.func_id); 11609 return err; 11610 } 11611 } 11612 11613 if (meta.func_id == special_kfunc_list[KF_bpf_throw]) { 11614 if (!bpf_jit_supports_exceptions()) { 11615 verbose(env, "JIT does not support calling kfunc %s#%d\n", 11616 func_name, meta.func_id); 11617 return -ENOTSUPP; 11618 } 11619 env->seen_exception = true; 11620 11621 /* In the case of the default callback, the cookie value passed 11622 * to bpf_throw becomes the return value of the program. 11623 */ 11624 if (!env->exception_callback_subprog) { 11625 err = check_return_code(env, BPF_REG_1); 11626 if (err < 0) 11627 return err; 11628 } 11629 } 11630 11631 for (i = 0; i < CALLER_SAVED_REGS; i++) 11632 mark_reg_not_init(env, regs, caller_saved[i]); 11633 11634 /* Check return type */ 11635 t = btf_type_skip_modifiers(desc_btf, meta.func_proto->type, NULL); 11636 11637 if (is_kfunc_acquire(&meta) && !btf_type_is_struct_ptr(meta.btf, t)) { 11638 /* Only exception is bpf_obj_new_impl */ 11639 if (meta.btf != btf_vmlinux || 11640 (meta.func_id != special_kfunc_list[KF_bpf_obj_new_impl] && 11641 meta.func_id != special_kfunc_list[KF_bpf_percpu_obj_new_impl] && 11642 meta.func_id != special_kfunc_list[KF_bpf_refcount_acquire_impl])) { 11643 verbose(env, "acquire kernel function does not return PTR_TO_BTF_ID\n"); 11644 return -EINVAL; 11645 } 11646 } 11647 11648 if (btf_type_is_scalar(t)) { 11649 mark_reg_unknown(env, regs, BPF_REG_0); 11650 mark_btf_func_reg_size(env, BPF_REG_0, t->size); 11651 } else if (btf_type_is_ptr(t)) { 11652 ptr_type = btf_type_skip_modifiers(desc_btf, t->type, &ptr_type_id); 11653 11654 if (meta.btf == btf_vmlinux && btf_id_set_contains(&special_kfunc_set, meta.func_id)) { 11655 if (meta.func_id == special_kfunc_list[KF_bpf_obj_new_impl] || 11656 meta.func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl]) { 11657 struct btf_struct_meta *struct_meta; 11658 struct btf *ret_btf; 11659 u32 ret_btf_id; 11660 11661 if (meta.func_id == special_kfunc_list[KF_bpf_obj_new_impl] && !bpf_global_ma_set) 11662 return -ENOMEM; 11663 11664 if (meta.func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl] && !bpf_global_percpu_ma_set) 11665 return -ENOMEM; 11666 11667 if (((u64)(u32)meta.arg_constant.value) != meta.arg_constant.value) { 11668 verbose(env, "local type ID argument must be in range [0, U32_MAX]\n"); 11669 return -EINVAL; 11670 } 11671 11672 ret_btf = env->prog->aux->btf; 11673 ret_btf_id = meta.arg_constant.value; 11674 11675 /* This may be NULL due to user not supplying a BTF */ 11676 if (!ret_btf) { 11677 verbose(env, "bpf_obj_new/bpf_percpu_obj_new requires prog BTF\n"); 11678 return -EINVAL; 11679 } 11680 11681 ret_t = btf_type_by_id(ret_btf, ret_btf_id); 11682 if (!ret_t || !__btf_type_is_struct(ret_t)) { 11683 verbose(env, "bpf_obj_new/bpf_percpu_obj_new type ID argument must be of a struct\n"); 11684 return -EINVAL; 11685 } 11686 11687 struct_meta = btf_find_struct_meta(ret_btf, ret_btf_id); 11688 if (meta.func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl]) { 11689 if (!__btf_type_is_scalar_struct(env, ret_btf, ret_t, 0)) { 11690 verbose(env, "bpf_percpu_obj_new type ID argument must be of a struct of scalars\n"); 11691 return -EINVAL; 11692 } 11693 11694 if (struct_meta) { 11695 verbose(env, "bpf_percpu_obj_new type ID argument must not contain special fields\n"); 11696 return -EINVAL; 11697 } 11698 } 11699 11700 mark_reg_known_zero(env, regs, BPF_REG_0); 11701 regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC; 11702 regs[BPF_REG_0].btf = ret_btf; 11703 regs[BPF_REG_0].btf_id = ret_btf_id; 11704 if (meta.func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl]) 11705 regs[BPF_REG_0].type |= MEM_PERCPU; 11706 11707 insn_aux->obj_new_size = ret_t->size; 11708 insn_aux->kptr_struct_meta = struct_meta; 11709 } else if (meta.func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl]) { 11710 mark_reg_known_zero(env, regs, BPF_REG_0); 11711 regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC; 11712 regs[BPF_REG_0].btf = meta.arg_btf; 11713 regs[BPF_REG_0].btf_id = meta.arg_btf_id; 11714 11715 insn_aux->kptr_struct_meta = 11716 btf_find_struct_meta(meta.arg_btf, 11717 meta.arg_btf_id); 11718 } else if (meta.func_id == special_kfunc_list[KF_bpf_list_pop_front] || 11719 meta.func_id == special_kfunc_list[KF_bpf_list_pop_back]) { 11720 struct btf_field *field = meta.arg_list_head.field; 11721 11722 mark_reg_graph_node(regs, BPF_REG_0, &field->graph_root); 11723 } else if (meta.func_id == special_kfunc_list[KF_bpf_rbtree_remove] || 11724 meta.func_id == special_kfunc_list[KF_bpf_rbtree_first]) { 11725 struct btf_field *field = meta.arg_rbtree_root.field; 11726 11727 mark_reg_graph_node(regs, BPF_REG_0, &field->graph_root); 11728 } else if (meta.func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx]) { 11729 mark_reg_known_zero(env, regs, BPF_REG_0); 11730 regs[BPF_REG_0].type = PTR_TO_BTF_ID | PTR_TRUSTED; 11731 regs[BPF_REG_0].btf = desc_btf; 11732 regs[BPF_REG_0].btf_id = meta.ret_btf_id; 11733 } else if (meta.func_id == special_kfunc_list[KF_bpf_rdonly_cast]) { 11734 ret_t = btf_type_by_id(desc_btf, meta.arg_constant.value); 11735 if (!ret_t || !btf_type_is_struct(ret_t)) { 11736 verbose(env, 11737 "kfunc bpf_rdonly_cast type ID argument must be of a struct\n"); 11738 return -EINVAL; 11739 } 11740 11741 mark_reg_known_zero(env, regs, BPF_REG_0); 11742 regs[BPF_REG_0].type = PTR_TO_BTF_ID | PTR_UNTRUSTED; 11743 regs[BPF_REG_0].btf = desc_btf; 11744 regs[BPF_REG_0].btf_id = meta.arg_constant.value; 11745 } else if (meta.func_id == special_kfunc_list[KF_bpf_dynptr_slice] || 11746 meta.func_id == special_kfunc_list[KF_bpf_dynptr_slice_rdwr]) { 11747 enum bpf_type_flag type_flag = get_dynptr_type_flag(meta.initialized_dynptr.type); 11748 11749 mark_reg_known_zero(env, regs, BPF_REG_0); 11750 11751 if (!meta.arg_constant.found) { 11752 verbose(env, "verifier internal error: bpf_dynptr_slice(_rdwr) no constant size\n"); 11753 return -EFAULT; 11754 } 11755 11756 regs[BPF_REG_0].mem_size = meta.arg_constant.value; 11757 11758 /* PTR_MAYBE_NULL will be added when is_kfunc_ret_null is checked */ 11759 regs[BPF_REG_0].type = PTR_TO_MEM | type_flag; 11760 11761 if (meta.func_id == special_kfunc_list[KF_bpf_dynptr_slice]) { 11762 regs[BPF_REG_0].type |= MEM_RDONLY; 11763 } else { 11764 /* this will set env->seen_direct_write to true */ 11765 if (!may_access_direct_pkt_data(env, NULL, BPF_WRITE)) { 11766 verbose(env, "the prog does not allow writes to packet data\n"); 11767 return -EINVAL; 11768 } 11769 } 11770 11771 if (!meta.initialized_dynptr.id) { 11772 verbose(env, "verifier internal error: no dynptr id\n"); 11773 return -EFAULT; 11774 } 11775 regs[BPF_REG_0].dynptr_id = meta.initialized_dynptr.id; 11776 11777 /* we don't need to set BPF_REG_0's ref obj id 11778 * because packet slices are not refcounted (see 11779 * dynptr_type_refcounted) 11780 */ 11781 } else { 11782 verbose(env, "kernel function %s unhandled dynamic return type\n", 11783 meta.func_name); 11784 return -EFAULT; 11785 } 11786 } else if (!__btf_type_is_struct(ptr_type)) { 11787 if (!meta.r0_size) { 11788 __u32 sz; 11789 11790 if (!IS_ERR(btf_resolve_size(desc_btf, ptr_type, &sz))) { 11791 meta.r0_size = sz; 11792 meta.r0_rdonly = true; 11793 } 11794 } 11795 if (!meta.r0_size) { 11796 ptr_type_name = btf_name_by_offset(desc_btf, 11797 ptr_type->name_off); 11798 verbose(env, 11799 "kernel function %s returns pointer type %s %s is not supported\n", 11800 func_name, 11801 btf_type_str(ptr_type), 11802 ptr_type_name); 11803 return -EINVAL; 11804 } 11805 11806 mark_reg_known_zero(env, regs, BPF_REG_0); 11807 regs[BPF_REG_0].type = PTR_TO_MEM; 11808 regs[BPF_REG_0].mem_size = meta.r0_size; 11809 11810 if (meta.r0_rdonly) 11811 regs[BPF_REG_0].type |= MEM_RDONLY; 11812 11813 /* Ensures we don't access the memory after a release_reference() */ 11814 if (meta.ref_obj_id) 11815 regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id; 11816 } else { 11817 mark_reg_known_zero(env, regs, BPF_REG_0); 11818 regs[BPF_REG_0].btf = desc_btf; 11819 regs[BPF_REG_0].type = PTR_TO_BTF_ID; 11820 regs[BPF_REG_0].btf_id = ptr_type_id; 11821 } 11822 11823 if (is_kfunc_ret_null(&meta)) { 11824 regs[BPF_REG_0].type |= PTR_MAYBE_NULL; 11825 /* For mark_ptr_or_null_reg, see 93c230e3f5bd6 */ 11826 regs[BPF_REG_0].id = ++env->id_gen; 11827 } 11828 mark_btf_func_reg_size(env, BPF_REG_0, sizeof(void *)); 11829 if (is_kfunc_acquire(&meta)) { 11830 int id = acquire_reference_state(env, insn_idx); 11831 11832 if (id < 0) 11833 return id; 11834 if (is_kfunc_ret_null(&meta)) 11835 regs[BPF_REG_0].id = id; 11836 regs[BPF_REG_0].ref_obj_id = id; 11837 } else if (meta.func_id == special_kfunc_list[KF_bpf_rbtree_first]) { 11838 ref_set_non_owning(env, ®s[BPF_REG_0]); 11839 } 11840 11841 if (reg_may_point_to_spin_lock(®s[BPF_REG_0]) && !regs[BPF_REG_0].id) 11842 regs[BPF_REG_0].id = ++env->id_gen; 11843 } else if (btf_type_is_void(t)) { 11844 if (meta.btf == btf_vmlinux && btf_id_set_contains(&special_kfunc_set, meta.func_id)) { 11845 if (meta.func_id == special_kfunc_list[KF_bpf_obj_drop_impl] || 11846 meta.func_id == special_kfunc_list[KF_bpf_percpu_obj_drop_impl]) { 11847 insn_aux->kptr_struct_meta = 11848 btf_find_struct_meta(meta.arg_btf, 11849 meta.arg_btf_id); 11850 } 11851 } 11852 } 11853 11854 nargs = btf_type_vlen(meta.func_proto); 11855 args = (const struct btf_param *)(meta.func_proto + 1); 11856 for (i = 0; i < nargs; i++) { 11857 u32 regno = i + 1; 11858 11859 t = btf_type_skip_modifiers(desc_btf, args[i].type, NULL); 11860 if (btf_type_is_ptr(t)) 11861 mark_btf_func_reg_size(env, regno, sizeof(void *)); 11862 else 11863 /* scalar. ensured by btf_check_kfunc_arg_match() */ 11864 mark_btf_func_reg_size(env, regno, t->size); 11865 } 11866 11867 if (is_iter_next_kfunc(&meta)) { 11868 err = process_iter_next_call(env, insn_idx, &meta); 11869 if (err) 11870 return err; 11871 } 11872 11873 return 0; 11874 } 11875 11876 static bool signed_add_overflows(s64 a, s64 b) 11877 { 11878 /* Do the add in u64, where overflow is well-defined */ 11879 s64 res = (s64)((u64)a + (u64)b); 11880 11881 if (b < 0) 11882 return res > a; 11883 return res < a; 11884 } 11885 11886 static bool signed_add32_overflows(s32 a, s32 b) 11887 { 11888 /* Do the add in u32, where overflow is well-defined */ 11889 s32 res = (s32)((u32)a + (u32)b); 11890 11891 if (b < 0) 11892 return res > a; 11893 return res < a; 11894 } 11895 11896 static bool signed_sub_overflows(s64 a, s64 b) 11897 { 11898 /* Do the sub in u64, where overflow is well-defined */ 11899 s64 res = (s64)((u64)a - (u64)b); 11900 11901 if (b < 0) 11902 return res < a; 11903 return res > a; 11904 } 11905 11906 static bool signed_sub32_overflows(s32 a, s32 b) 11907 { 11908 /* Do the sub in u32, where overflow is well-defined */ 11909 s32 res = (s32)((u32)a - (u32)b); 11910 11911 if (b < 0) 11912 return res < a; 11913 return res > a; 11914 } 11915 11916 static bool check_reg_sane_offset(struct bpf_verifier_env *env, 11917 const struct bpf_reg_state *reg, 11918 enum bpf_reg_type type) 11919 { 11920 bool known = tnum_is_const(reg->var_off); 11921 s64 val = reg->var_off.value; 11922 s64 smin = reg->smin_value; 11923 11924 if (known && (val >= BPF_MAX_VAR_OFF || val <= -BPF_MAX_VAR_OFF)) { 11925 verbose(env, "math between %s pointer and %lld is not allowed\n", 11926 reg_type_str(env, type), val); 11927 return false; 11928 } 11929 11930 if (reg->off >= BPF_MAX_VAR_OFF || reg->off <= -BPF_MAX_VAR_OFF) { 11931 verbose(env, "%s pointer offset %d is not allowed\n", 11932 reg_type_str(env, type), reg->off); 11933 return false; 11934 } 11935 11936 if (smin == S64_MIN) { 11937 verbose(env, "math between %s pointer and register with unbounded min value is not allowed\n", 11938 reg_type_str(env, type)); 11939 return false; 11940 } 11941 11942 if (smin >= BPF_MAX_VAR_OFF || smin <= -BPF_MAX_VAR_OFF) { 11943 verbose(env, "value %lld makes %s pointer be out of bounds\n", 11944 smin, reg_type_str(env, type)); 11945 return false; 11946 } 11947 11948 return true; 11949 } 11950 11951 enum { 11952 REASON_BOUNDS = -1, 11953 REASON_TYPE = -2, 11954 REASON_PATHS = -3, 11955 REASON_LIMIT = -4, 11956 REASON_STACK = -5, 11957 }; 11958 11959 static int retrieve_ptr_limit(const struct bpf_reg_state *ptr_reg, 11960 u32 *alu_limit, bool mask_to_left) 11961 { 11962 u32 max = 0, ptr_limit = 0; 11963 11964 switch (ptr_reg->type) { 11965 case PTR_TO_STACK: 11966 /* Offset 0 is out-of-bounds, but acceptable start for the 11967 * left direction, see BPF_REG_FP. Also, unknown scalar 11968 * offset where we would need to deal with min/max bounds is 11969 * currently prohibited for unprivileged. 11970 */ 11971 max = MAX_BPF_STACK + mask_to_left; 11972 ptr_limit = -(ptr_reg->var_off.value + ptr_reg->off); 11973 break; 11974 case PTR_TO_MAP_VALUE: 11975 max = ptr_reg->map_ptr->value_size; 11976 ptr_limit = (mask_to_left ? 11977 ptr_reg->smin_value : 11978 ptr_reg->umax_value) + ptr_reg->off; 11979 break; 11980 default: 11981 return REASON_TYPE; 11982 } 11983 11984 if (ptr_limit >= max) 11985 return REASON_LIMIT; 11986 *alu_limit = ptr_limit; 11987 return 0; 11988 } 11989 11990 static bool can_skip_alu_sanitation(const struct bpf_verifier_env *env, 11991 const struct bpf_insn *insn) 11992 { 11993 return env->bypass_spec_v1 || BPF_SRC(insn->code) == BPF_K; 11994 } 11995 11996 static int update_alu_sanitation_state(struct bpf_insn_aux_data *aux, 11997 u32 alu_state, u32 alu_limit) 11998 { 11999 /* If we arrived here from different branches with different 12000 * state or limits to sanitize, then this won't work. 12001 */ 12002 if (aux->alu_state && 12003 (aux->alu_state != alu_state || 12004 aux->alu_limit != alu_limit)) 12005 return REASON_PATHS; 12006 12007 /* Corresponding fixup done in do_misc_fixups(). */ 12008 aux->alu_state = alu_state; 12009 aux->alu_limit = alu_limit; 12010 return 0; 12011 } 12012 12013 static int sanitize_val_alu(struct bpf_verifier_env *env, 12014 struct bpf_insn *insn) 12015 { 12016 struct bpf_insn_aux_data *aux = cur_aux(env); 12017 12018 if (can_skip_alu_sanitation(env, insn)) 12019 return 0; 12020 12021 return update_alu_sanitation_state(aux, BPF_ALU_NON_POINTER, 0); 12022 } 12023 12024 static bool sanitize_needed(u8 opcode) 12025 { 12026 return opcode == BPF_ADD || opcode == BPF_SUB; 12027 } 12028 12029 struct bpf_sanitize_info { 12030 struct bpf_insn_aux_data aux; 12031 bool mask_to_left; 12032 }; 12033 12034 static struct bpf_verifier_state * 12035 sanitize_speculative_path(struct bpf_verifier_env *env, 12036 const struct bpf_insn *insn, 12037 u32 next_idx, u32 curr_idx) 12038 { 12039 struct bpf_verifier_state *branch; 12040 struct bpf_reg_state *regs; 12041 12042 branch = push_stack(env, next_idx, curr_idx, true); 12043 if (branch && insn) { 12044 regs = branch->frame[branch->curframe]->regs; 12045 if (BPF_SRC(insn->code) == BPF_K) { 12046 mark_reg_unknown(env, regs, insn->dst_reg); 12047 } else if (BPF_SRC(insn->code) == BPF_X) { 12048 mark_reg_unknown(env, regs, insn->dst_reg); 12049 mark_reg_unknown(env, regs, insn->src_reg); 12050 } 12051 } 12052 return branch; 12053 } 12054 12055 static int sanitize_ptr_alu(struct bpf_verifier_env *env, 12056 struct bpf_insn *insn, 12057 const struct bpf_reg_state *ptr_reg, 12058 const struct bpf_reg_state *off_reg, 12059 struct bpf_reg_state *dst_reg, 12060 struct bpf_sanitize_info *info, 12061 const bool commit_window) 12062 { 12063 struct bpf_insn_aux_data *aux = commit_window ? cur_aux(env) : &info->aux; 12064 struct bpf_verifier_state *vstate = env->cur_state; 12065 bool off_is_imm = tnum_is_const(off_reg->var_off); 12066 bool off_is_neg = off_reg->smin_value < 0; 12067 bool ptr_is_dst_reg = ptr_reg == dst_reg; 12068 u8 opcode = BPF_OP(insn->code); 12069 u32 alu_state, alu_limit; 12070 struct bpf_reg_state tmp; 12071 bool ret; 12072 int err; 12073 12074 if (can_skip_alu_sanitation(env, insn)) 12075 return 0; 12076 12077 /* We already marked aux for masking from non-speculative 12078 * paths, thus we got here in the first place. We only care 12079 * to explore bad access from here. 12080 */ 12081 if (vstate->speculative) 12082 goto do_sim; 12083 12084 if (!commit_window) { 12085 if (!tnum_is_const(off_reg->var_off) && 12086 (off_reg->smin_value < 0) != (off_reg->smax_value < 0)) 12087 return REASON_BOUNDS; 12088 12089 info->mask_to_left = (opcode == BPF_ADD && off_is_neg) || 12090 (opcode == BPF_SUB && !off_is_neg); 12091 } 12092 12093 err = retrieve_ptr_limit(ptr_reg, &alu_limit, info->mask_to_left); 12094 if (err < 0) 12095 return err; 12096 12097 if (commit_window) { 12098 /* In commit phase we narrow the masking window based on 12099 * the observed pointer move after the simulated operation. 12100 */ 12101 alu_state = info->aux.alu_state; 12102 alu_limit = abs(info->aux.alu_limit - alu_limit); 12103 } else { 12104 alu_state = off_is_neg ? BPF_ALU_NEG_VALUE : 0; 12105 alu_state |= off_is_imm ? BPF_ALU_IMMEDIATE : 0; 12106 alu_state |= ptr_is_dst_reg ? 12107 BPF_ALU_SANITIZE_SRC : BPF_ALU_SANITIZE_DST; 12108 12109 /* Limit pruning on unknown scalars to enable deep search for 12110 * potential masking differences from other program paths. 12111 */ 12112 if (!off_is_imm) 12113 env->explore_alu_limits = true; 12114 } 12115 12116 err = update_alu_sanitation_state(aux, alu_state, alu_limit); 12117 if (err < 0) 12118 return err; 12119 do_sim: 12120 /* If we're in commit phase, we're done here given we already 12121 * pushed the truncated dst_reg into the speculative verification 12122 * stack. 12123 * 12124 * Also, when register is a known constant, we rewrite register-based 12125 * operation to immediate-based, and thus do not need masking (and as 12126 * a consequence, do not need to simulate the zero-truncation either). 12127 */ 12128 if (commit_window || off_is_imm) 12129 return 0; 12130 12131 /* Simulate and find potential out-of-bounds access under 12132 * speculative execution from truncation as a result of 12133 * masking when off was not within expected range. If off 12134 * sits in dst, then we temporarily need to move ptr there 12135 * to simulate dst (== 0) +/-= ptr. Needed, for example, 12136 * for cases where we use K-based arithmetic in one direction 12137 * and truncated reg-based in the other in order to explore 12138 * bad access. 12139 */ 12140 if (!ptr_is_dst_reg) { 12141 tmp = *dst_reg; 12142 copy_register_state(dst_reg, ptr_reg); 12143 } 12144 ret = sanitize_speculative_path(env, NULL, env->insn_idx + 1, 12145 env->insn_idx); 12146 if (!ptr_is_dst_reg && ret) 12147 *dst_reg = tmp; 12148 return !ret ? REASON_STACK : 0; 12149 } 12150 12151 static void sanitize_mark_insn_seen(struct bpf_verifier_env *env) 12152 { 12153 struct bpf_verifier_state *vstate = env->cur_state; 12154 12155 /* If we simulate paths under speculation, we don't update the 12156 * insn as 'seen' such that when we verify unreachable paths in 12157 * the non-speculative domain, sanitize_dead_code() can still 12158 * rewrite/sanitize them. 12159 */ 12160 if (!vstate->speculative) 12161 env->insn_aux_data[env->insn_idx].seen = env->pass_cnt; 12162 } 12163 12164 static int sanitize_err(struct bpf_verifier_env *env, 12165 const struct bpf_insn *insn, int reason, 12166 const struct bpf_reg_state *off_reg, 12167 const struct bpf_reg_state *dst_reg) 12168 { 12169 static const char *err = "pointer arithmetic with it prohibited for !root"; 12170 const char *op = BPF_OP(insn->code) == BPF_ADD ? "add" : "sub"; 12171 u32 dst = insn->dst_reg, src = insn->src_reg; 12172 12173 switch (reason) { 12174 case REASON_BOUNDS: 12175 verbose(env, "R%d has unknown scalar with mixed signed bounds, %s\n", 12176 off_reg == dst_reg ? dst : src, err); 12177 break; 12178 case REASON_TYPE: 12179 verbose(env, "R%d has pointer with unsupported alu operation, %s\n", 12180 off_reg == dst_reg ? src : dst, err); 12181 break; 12182 case REASON_PATHS: 12183 verbose(env, "R%d tried to %s from different maps, paths or scalars, %s\n", 12184 dst, op, err); 12185 break; 12186 case REASON_LIMIT: 12187 verbose(env, "R%d tried to %s beyond pointer bounds, %s\n", 12188 dst, op, err); 12189 break; 12190 case REASON_STACK: 12191 verbose(env, "R%d could not be pushed for speculative verification, %s\n", 12192 dst, err); 12193 break; 12194 default: 12195 verbose(env, "verifier internal error: unknown reason (%d)\n", 12196 reason); 12197 break; 12198 } 12199 12200 return -EACCES; 12201 } 12202 12203 /* check that stack access falls within stack limits and that 'reg' doesn't 12204 * have a variable offset. 12205 * 12206 * Variable offset is prohibited for unprivileged mode for simplicity since it 12207 * requires corresponding support in Spectre masking for stack ALU. See also 12208 * retrieve_ptr_limit(). 12209 * 12210 * 12211 * 'off' includes 'reg->off'. 12212 */ 12213 static int check_stack_access_for_ptr_arithmetic( 12214 struct bpf_verifier_env *env, 12215 int regno, 12216 const struct bpf_reg_state *reg, 12217 int off) 12218 { 12219 if (!tnum_is_const(reg->var_off)) { 12220 char tn_buf[48]; 12221 12222 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 12223 verbose(env, "R%d variable stack access prohibited for !root, var_off=%s off=%d\n", 12224 regno, tn_buf, off); 12225 return -EACCES; 12226 } 12227 12228 if (off >= 0 || off < -MAX_BPF_STACK) { 12229 verbose(env, "R%d stack pointer arithmetic goes out of range, " 12230 "prohibited for !root; off=%d\n", regno, off); 12231 return -EACCES; 12232 } 12233 12234 return 0; 12235 } 12236 12237 static int sanitize_check_bounds(struct bpf_verifier_env *env, 12238 const struct bpf_insn *insn, 12239 const struct bpf_reg_state *dst_reg) 12240 { 12241 u32 dst = insn->dst_reg; 12242 12243 /* For unprivileged we require that resulting offset must be in bounds 12244 * in order to be able to sanitize access later on. 12245 */ 12246 if (env->bypass_spec_v1) 12247 return 0; 12248 12249 switch (dst_reg->type) { 12250 case PTR_TO_STACK: 12251 if (check_stack_access_for_ptr_arithmetic(env, dst, dst_reg, 12252 dst_reg->off + dst_reg->var_off.value)) 12253 return -EACCES; 12254 break; 12255 case PTR_TO_MAP_VALUE: 12256 if (check_map_access(env, dst, dst_reg->off, 1, false, ACCESS_HELPER)) { 12257 verbose(env, "R%d pointer arithmetic of map value goes out of range, " 12258 "prohibited for !root\n", dst); 12259 return -EACCES; 12260 } 12261 break; 12262 default: 12263 break; 12264 } 12265 12266 return 0; 12267 } 12268 12269 /* Handles arithmetic on a pointer and a scalar: computes new min/max and var_off. 12270 * Caller should also handle BPF_MOV case separately. 12271 * If we return -EACCES, caller may want to try again treating pointer as a 12272 * scalar. So we only emit a diagnostic if !env->allow_ptr_leaks. 12273 */ 12274 static int adjust_ptr_min_max_vals(struct bpf_verifier_env *env, 12275 struct bpf_insn *insn, 12276 const struct bpf_reg_state *ptr_reg, 12277 const struct bpf_reg_state *off_reg) 12278 { 12279 struct bpf_verifier_state *vstate = env->cur_state; 12280 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 12281 struct bpf_reg_state *regs = state->regs, *dst_reg; 12282 bool known = tnum_is_const(off_reg->var_off); 12283 s64 smin_val = off_reg->smin_value, smax_val = off_reg->smax_value, 12284 smin_ptr = ptr_reg->smin_value, smax_ptr = ptr_reg->smax_value; 12285 u64 umin_val = off_reg->umin_value, umax_val = off_reg->umax_value, 12286 umin_ptr = ptr_reg->umin_value, umax_ptr = ptr_reg->umax_value; 12287 struct bpf_sanitize_info info = {}; 12288 u8 opcode = BPF_OP(insn->code); 12289 u32 dst = insn->dst_reg; 12290 int ret; 12291 12292 dst_reg = ®s[dst]; 12293 12294 if ((known && (smin_val != smax_val || umin_val != umax_val)) || 12295 smin_val > smax_val || umin_val > umax_val) { 12296 /* Taint dst register if offset had invalid bounds derived from 12297 * e.g. dead branches. 12298 */ 12299 __mark_reg_unknown(env, dst_reg); 12300 return 0; 12301 } 12302 12303 if (BPF_CLASS(insn->code) != BPF_ALU64) { 12304 /* 32-bit ALU ops on pointers produce (meaningless) scalars */ 12305 if (opcode == BPF_SUB && env->allow_ptr_leaks) { 12306 __mark_reg_unknown(env, dst_reg); 12307 return 0; 12308 } 12309 12310 verbose(env, 12311 "R%d 32-bit pointer arithmetic prohibited\n", 12312 dst); 12313 return -EACCES; 12314 } 12315 12316 if (ptr_reg->type & PTR_MAYBE_NULL) { 12317 verbose(env, "R%d pointer arithmetic on %s prohibited, null-check it first\n", 12318 dst, reg_type_str(env, ptr_reg->type)); 12319 return -EACCES; 12320 } 12321 12322 switch (base_type(ptr_reg->type)) { 12323 case CONST_PTR_TO_MAP: 12324 /* smin_val represents the known value */ 12325 if (known && smin_val == 0 && opcode == BPF_ADD) 12326 break; 12327 fallthrough; 12328 case PTR_TO_PACKET_END: 12329 case PTR_TO_SOCKET: 12330 case PTR_TO_SOCK_COMMON: 12331 case PTR_TO_TCP_SOCK: 12332 case PTR_TO_XDP_SOCK: 12333 verbose(env, "R%d pointer arithmetic on %s prohibited\n", 12334 dst, reg_type_str(env, ptr_reg->type)); 12335 return -EACCES; 12336 default: 12337 break; 12338 } 12339 12340 /* In case of 'scalar += pointer', dst_reg inherits pointer type and id. 12341 * The id may be overwritten later if we create a new variable offset. 12342 */ 12343 dst_reg->type = ptr_reg->type; 12344 dst_reg->id = ptr_reg->id; 12345 12346 if (!check_reg_sane_offset(env, off_reg, ptr_reg->type) || 12347 !check_reg_sane_offset(env, ptr_reg, ptr_reg->type)) 12348 return -EINVAL; 12349 12350 /* pointer types do not carry 32-bit bounds at the moment. */ 12351 __mark_reg32_unbounded(dst_reg); 12352 12353 if (sanitize_needed(opcode)) { 12354 ret = sanitize_ptr_alu(env, insn, ptr_reg, off_reg, dst_reg, 12355 &info, false); 12356 if (ret < 0) 12357 return sanitize_err(env, insn, ret, off_reg, dst_reg); 12358 } 12359 12360 switch (opcode) { 12361 case BPF_ADD: 12362 /* We can take a fixed offset as long as it doesn't overflow 12363 * the s32 'off' field 12364 */ 12365 if (known && (ptr_reg->off + smin_val == 12366 (s64)(s32)(ptr_reg->off + smin_val))) { 12367 /* pointer += K. Accumulate it into fixed offset */ 12368 dst_reg->smin_value = smin_ptr; 12369 dst_reg->smax_value = smax_ptr; 12370 dst_reg->umin_value = umin_ptr; 12371 dst_reg->umax_value = umax_ptr; 12372 dst_reg->var_off = ptr_reg->var_off; 12373 dst_reg->off = ptr_reg->off + smin_val; 12374 dst_reg->raw = ptr_reg->raw; 12375 break; 12376 } 12377 /* A new variable offset is created. Note that off_reg->off 12378 * == 0, since it's a scalar. 12379 * dst_reg gets the pointer type and since some positive 12380 * integer value was added to the pointer, give it a new 'id' 12381 * if it's a PTR_TO_PACKET. 12382 * this creates a new 'base' pointer, off_reg (variable) gets 12383 * added into the variable offset, and we copy the fixed offset 12384 * from ptr_reg. 12385 */ 12386 if (signed_add_overflows(smin_ptr, smin_val) || 12387 signed_add_overflows(smax_ptr, smax_val)) { 12388 dst_reg->smin_value = S64_MIN; 12389 dst_reg->smax_value = S64_MAX; 12390 } else { 12391 dst_reg->smin_value = smin_ptr + smin_val; 12392 dst_reg->smax_value = smax_ptr + smax_val; 12393 } 12394 if (umin_ptr + umin_val < umin_ptr || 12395 umax_ptr + umax_val < umax_ptr) { 12396 dst_reg->umin_value = 0; 12397 dst_reg->umax_value = U64_MAX; 12398 } else { 12399 dst_reg->umin_value = umin_ptr + umin_val; 12400 dst_reg->umax_value = umax_ptr + umax_val; 12401 } 12402 dst_reg->var_off = tnum_add(ptr_reg->var_off, off_reg->var_off); 12403 dst_reg->off = ptr_reg->off; 12404 dst_reg->raw = ptr_reg->raw; 12405 if (reg_is_pkt_pointer(ptr_reg)) { 12406 dst_reg->id = ++env->id_gen; 12407 /* something was added to pkt_ptr, set range to zero */ 12408 memset(&dst_reg->raw, 0, sizeof(dst_reg->raw)); 12409 } 12410 break; 12411 case BPF_SUB: 12412 if (dst_reg == off_reg) { 12413 /* scalar -= pointer. Creates an unknown scalar */ 12414 verbose(env, "R%d tried to subtract pointer from scalar\n", 12415 dst); 12416 return -EACCES; 12417 } 12418 /* We don't allow subtraction from FP, because (according to 12419 * test_verifier.c test "invalid fp arithmetic", JITs might not 12420 * be able to deal with it. 12421 */ 12422 if (ptr_reg->type == PTR_TO_STACK) { 12423 verbose(env, "R%d subtraction from stack pointer prohibited\n", 12424 dst); 12425 return -EACCES; 12426 } 12427 if (known && (ptr_reg->off - smin_val == 12428 (s64)(s32)(ptr_reg->off - smin_val))) { 12429 /* pointer -= K. Subtract it from fixed offset */ 12430 dst_reg->smin_value = smin_ptr; 12431 dst_reg->smax_value = smax_ptr; 12432 dst_reg->umin_value = umin_ptr; 12433 dst_reg->umax_value = umax_ptr; 12434 dst_reg->var_off = ptr_reg->var_off; 12435 dst_reg->id = ptr_reg->id; 12436 dst_reg->off = ptr_reg->off - smin_val; 12437 dst_reg->raw = ptr_reg->raw; 12438 break; 12439 } 12440 /* A new variable offset is created. If the subtrahend is known 12441 * nonnegative, then any reg->range we had before is still good. 12442 */ 12443 if (signed_sub_overflows(smin_ptr, smax_val) || 12444 signed_sub_overflows(smax_ptr, smin_val)) { 12445 /* Overflow possible, we know nothing */ 12446 dst_reg->smin_value = S64_MIN; 12447 dst_reg->smax_value = S64_MAX; 12448 } else { 12449 dst_reg->smin_value = smin_ptr - smax_val; 12450 dst_reg->smax_value = smax_ptr - smin_val; 12451 } 12452 if (umin_ptr < umax_val) { 12453 /* Overflow possible, we know nothing */ 12454 dst_reg->umin_value = 0; 12455 dst_reg->umax_value = U64_MAX; 12456 } else { 12457 /* Cannot overflow (as long as bounds are consistent) */ 12458 dst_reg->umin_value = umin_ptr - umax_val; 12459 dst_reg->umax_value = umax_ptr - umin_val; 12460 } 12461 dst_reg->var_off = tnum_sub(ptr_reg->var_off, off_reg->var_off); 12462 dst_reg->off = ptr_reg->off; 12463 dst_reg->raw = ptr_reg->raw; 12464 if (reg_is_pkt_pointer(ptr_reg)) { 12465 dst_reg->id = ++env->id_gen; 12466 /* something was added to pkt_ptr, set range to zero */ 12467 if (smin_val < 0) 12468 memset(&dst_reg->raw, 0, sizeof(dst_reg->raw)); 12469 } 12470 break; 12471 case BPF_AND: 12472 case BPF_OR: 12473 case BPF_XOR: 12474 /* bitwise ops on pointers are troublesome, prohibit. */ 12475 verbose(env, "R%d bitwise operator %s on pointer prohibited\n", 12476 dst, bpf_alu_string[opcode >> 4]); 12477 return -EACCES; 12478 default: 12479 /* other operators (e.g. MUL,LSH) produce non-pointer results */ 12480 verbose(env, "R%d pointer arithmetic with %s operator prohibited\n", 12481 dst, bpf_alu_string[opcode >> 4]); 12482 return -EACCES; 12483 } 12484 12485 if (!check_reg_sane_offset(env, dst_reg, ptr_reg->type)) 12486 return -EINVAL; 12487 reg_bounds_sync(dst_reg); 12488 if (sanitize_check_bounds(env, insn, dst_reg) < 0) 12489 return -EACCES; 12490 if (sanitize_needed(opcode)) { 12491 ret = sanitize_ptr_alu(env, insn, dst_reg, off_reg, dst_reg, 12492 &info, true); 12493 if (ret < 0) 12494 return sanitize_err(env, insn, ret, off_reg, dst_reg); 12495 } 12496 12497 return 0; 12498 } 12499 12500 static void scalar32_min_max_add(struct bpf_reg_state *dst_reg, 12501 struct bpf_reg_state *src_reg) 12502 { 12503 s32 smin_val = src_reg->s32_min_value; 12504 s32 smax_val = src_reg->s32_max_value; 12505 u32 umin_val = src_reg->u32_min_value; 12506 u32 umax_val = src_reg->u32_max_value; 12507 12508 if (signed_add32_overflows(dst_reg->s32_min_value, smin_val) || 12509 signed_add32_overflows(dst_reg->s32_max_value, smax_val)) { 12510 dst_reg->s32_min_value = S32_MIN; 12511 dst_reg->s32_max_value = S32_MAX; 12512 } else { 12513 dst_reg->s32_min_value += smin_val; 12514 dst_reg->s32_max_value += smax_val; 12515 } 12516 if (dst_reg->u32_min_value + umin_val < umin_val || 12517 dst_reg->u32_max_value + umax_val < umax_val) { 12518 dst_reg->u32_min_value = 0; 12519 dst_reg->u32_max_value = U32_MAX; 12520 } else { 12521 dst_reg->u32_min_value += umin_val; 12522 dst_reg->u32_max_value += umax_val; 12523 } 12524 } 12525 12526 static void scalar_min_max_add(struct bpf_reg_state *dst_reg, 12527 struct bpf_reg_state *src_reg) 12528 { 12529 s64 smin_val = src_reg->smin_value; 12530 s64 smax_val = src_reg->smax_value; 12531 u64 umin_val = src_reg->umin_value; 12532 u64 umax_val = src_reg->umax_value; 12533 12534 if (signed_add_overflows(dst_reg->smin_value, smin_val) || 12535 signed_add_overflows(dst_reg->smax_value, smax_val)) { 12536 dst_reg->smin_value = S64_MIN; 12537 dst_reg->smax_value = S64_MAX; 12538 } else { 12539 dst_reg->smin_value += smin_val; 12540 dst_reg->smax_value += smax_val; 12541 } 12542 if (dst_reg->umin_value + umin_val < umin_val || 12543 dst_reg->umax_value + umax_val < umax_val) { 12544 dst_reg->umin_value = 0; 12545 dst_reg->umax_value = U64_MAX; 12546 } else { 12547 dst_reg->umin_value += umin_val; 12548 dst_reg->umax_value += umax_val; 12549 } 12550 } 12551 12552 static void scalar32_min_max_sub(struct bpf_reg_state *dst_reg, 12553 struct bpf_reg_state *src_reg) 12554 { 12555 s32 smin_val = src_reg->s32_min_value; 12556 s32 smax_val = src_reg->s32_max_value; 12557 u32 umin_val = src_reg->u32_min_value; 12558 u32 umax_val = src_reg->u32_max_value; 12559 12560 if (signed_sub32_overflows(dst_reg->s32_min_value, smax_val) || 12561 signed_sub32_overflows(dst_reg->s32_max_value, smin_val)) { 12562 /* Overflow possible, we know nothing */ 12563 dst_reg->s32_min_value = S32_MIN; 12564 dst_reg->s32_max_value = S32_MAX; 12565 } else { 12566 dst_reg->s32_min_value -= smax_val; 12567 dst_reg->s32_max_value -= smin_val; 12568 } 12569 if (dst_reg->u32_min_value < umax_val) { 12570 /* Overflow possible, we know nothing */ 12571 dst_reg->u32_min_value = 0; 12572 dst_reg->u32_max_value = U32_MAX; 12573 } else { 12574 /* Cannot overflow (as long as bounds are consistent) */ 12575 dst_reg->u32_min_value -= umax_val; 12576 dst_reg->u32_max_value -= umin_val; 12577 } 12578 } 12579 12580 static void scalar_min_max_sub(struct bpf_reg_state *dst_reg, 12581 struct bpf_reg_state *src_reg) 12582 { 12583 s64 smin_val = src_reg->smin_value; 12584 s64 smax_val = src_reg->smax_value; 12585 u64 umin_val = src_reg->umin_value; 12586 u64 umax_val = src_reg->umax_value; 12587 12588 if (signed_sub_overflows(dst_reg->smin_value, smax_val) || 12589 signed_sub_overflows(dst_reg->smax_value, smin_val)) { 12590 /* Overflow possible, we know nothing */ 12591 dst_reg->smin_value = S64_MIN; 12592 dst_reg->smax_value = S64_MAX; 12593 } else { 12594 dst_reg->smin_value -= smax_val; 12595 dst_reg->smax_value -= smin_val; 12596 } 12597 if (dst_reg->umin_value < umax_val) { 12598 /* Overflow possible, we know nothing */ 12599 dst_reg->umin_value = 0; 12600 dst_reg->umax_value = U64_MAX; 12601 } else { 12602 /* Cannot overflow (as long as bounds are consistent) */ 12603 dst_reg->umin_value -= umax_val; 12604 dst_reg->umax_value -= umin_val; 12605 } 12606 } 12607 12608 static void scalar32_min_max_mul(struct bpf_reg_state *dst_reg, 12609 struct bpf_reg_state *src_reg) 12610 { 12611 s32 smin_val = src_reg->s32_min_value; 12612 u32 umin_val = src_reg->u32_min_value; 12613 u32 umax_val = src_reg->u32_max_value; 12614 12615 if (smin_val < 0 || dst_reg->s32_min_value < 0) { 12616 /* Ain't nobody got time to multiply that sign */ 12617 __mark_reg32_unbounded(dst_reg); 12618 return; 12619 } 12620 /* Both values are positive, so we can work with unsigned and 12621 * copy the result to signed (unless it exceeds S32_MAX). 12622 */ 12623 if (umax_val > U16_MAX || dst_reg->u32_max_value > U16_MAX) { 12624 /* Potential overflow, we know nothing */ 12625 __mark_reg32_unbounded(dst_reg); 12626 return; 12627 } 12628 dst_reg->u32_min_value *= umin_val; 12629 dst_reg->u32_max_value *= umax_val; 12630 if (dst_reg->u32_max_value > S32_MAX) { 12631 /* Overflow possible, we know nothing */ 12632 dst_reg->s32_min_value = S32_MIN; 12633 dst_reg->s32_max_value = S32_MAX; 12634 } else { 12635 dst_reg->s32_min_value = dst_reg->u32_min_value; 12636 dst_reg->s32_max_value = dst_reg->u32_max_value; 12637 } 12638 } 12639 12640 static void scalar_min_max_mul(struct bpf_reg_state *dst_reg, 12641 struct bpf_reg_state *src_reg) 12642 { 12643 s64 smin_val = src_reg->smin_value; 12644 u64 umin_val = src_reg->umin_value; 12645 u64 umax_val = src_reg->umax_value; 12646 12647 if (smin_val < 0 || dst_reg->smin_value < 0) { 12648 /* Ain't nobody got time to multiply that sign */ 12649 __mark_reg64_unbounded(dst_reg); 12650 return; 12651 } 12652 /* Both values are positive, so we can work with unsigned and 12653 * copy the result to signed (unless it exceeds S64_MAX). 12654 */ 12655 if (umax_val > U32_MAX || dst_reg->umax_value > U32_MAX) { 12656 /* Potential overflow, we know nothing */ 12657 __mark_reg64_unbounded(dst_reg); 12658 return; 12659 } 12660 dst_reg->umin_value *= umin_val; 12661 dst_reg->umax_value *= umax_val; 12662 if (dst_reg->umax_value > S64_MAX) { 12663 /* Overflow possible, we know nothing */ 12664 dst_reg->smin_value = S64_MIN; 12665 dst_reg->smax_value = S64_MAX; 12666 } else { 12667 dst_reg->smin_value = dst_reg->umin_value; 12668 dst_reg->smax_value = dst_reg->umax_value; 12669 } 12670 } 12671 12672 static void scalar32_min_max_and(struct bpf_reg_state *dst_reg, 12673 struct bpf_reg_state *src_reg) 12674 { 12675 bool src_known = tnum_subreg_is_const(src_reg->var_off); 12676 bool dst_known = tnum_subreg_is_const(dst_reg->var_off); 12677 struct tnum var32_off = tnum_subreg(dst_reg->var_off); 12678 s32 smin_val = src_reg->s32_min_value; 12679 u32 umax_val = src_reg->u32_max_value; 12680 12681 if (src_known && dst_known) { 12682 __mark_reg32_known(dst_reg, var32_off.value); 12683 return; 12684 } 12685 12686 /* We get our minimum from the var_off, since that's inherently 12687 * bitwise. Our maximum is the minimum of the operands' maxima. 12688 */ 12689 dst_reg->u32_min_value = var32_off.value; 12690 dst_reg->u32_max_value = min(dst_reg->u32_max_value, umax_val); 12691 if (dst_reg->s32_min_value < 0 || smin_val < 0) { 12692 /* Lose signed bounds when ANDing negative numbers, 12693 * ain't nobody got time for that. 12694 */ 12695 dst_reg->s32_min_value = S32_MIN; 12696 dst_reg->s32_max_value = S32_MAX; 12697 } else { 12698 /* ANDing two positives gives a positive, so safe to 12699 * cast result into s64. 12700 */ 12701 dst_reg->s32_min_value = dst_reg->u32_min_value; 12702 dst_reg->s32_max_value = dst_reg->u32_max_value; 12703 } 12704 } 12705 12706 static void scalar_min_max_and(struct bpf_reg_state *dst_reg, 12707 struct bpf_reg_state *src_reg) 12708 { 12709 bool src_known = tnum_is_const(src_reg->var_off); 12710 bool dst_known = tnum_is_const(dst_reg->var_off); 12711 s64 smin_val = src_reg->smin_value; 12712 u64 umax_val = src_reg->umax_value; 12713 12714 if (src_known && dst_known) { 12715 __mark_reg_known(dst_reg, dst_reg->var_off.value); 12716 return; 12717 } 12718 12719 /* We get our minimum from the var_off, since that's inherently 12720 * bitwise. Our maximum is the minimum of the operands' maxima. 12721 */ 12722 dst_reg->umin_value = dst_reg->var_off.value; 12723 dst_reg->umax_value = min(dst_reg->umax_value, umax_val); 12724 if (dst_reg->smin_value < 0 || smin_val < 0) { 12725 /* Lose signed bounds when ANDing negative numbers, 12726 * ain't nobody got time for that. 12727 */ 12728 dst_reg->smin_value = S64_MIN; 12729 dst_reg->smax_value = S64_MAX; 12730 } else { 12731 /* ANDing two positives gives a positive, so safe to 12732 * cast result into s64. 12733 */ 12734 dst_reg->smin_value = dst_reg->umin_value; 12735 dst_reg->smax_value = dst_reg->umax_value; 12736 } 12737 /* We may learn something more from the var_off */ 12738 __update_reg_bounds(dst_reg); 12739 } 12740 12741 static void scalar32_min_max_or(struct bpf_reg_state *dst_reg, 12742 struct bpf_reg_state *src_reg) 12743 { 12744 bool src_known = tnum_subreg_is_const(src_reg->var_off); 12745 bool dst_known = tnum_subreg_is_const(dst_reg->var_off); 12746 struct tnum var32_off = tnum_subreg(dst_reg->var_off); 12747 s32 smin_val = src_reg->s32_min_value; 12748 u32 umin_val = src_reg->u32_min_value; 12749 12750 if (src_known && dst_known) { 12751 __mark_reg32_known(dst_reg, var32_off.value); 12752 return; 12753 } 12754 12755 /* We get our maximum from the var_off, and our minimum is the 12756 * maximum of the operands' minima 12757 */ 12758 dst_reg->u32_min_value = max(dst_reg->u32_min_value, umin_val); 12759 dst_reg->u32_max_value = var32_off.value | var32_off.mask; 12760 if (dst_reg->s32_min_value < 0 || smin_val < 0) { 12761 /* Lose signed bounds when ORing negative numbers, 12762 * ain't nobody got time for that. 12763 */ 12764 dst_reg->s32_min_value = S32_MIN; 12765 dst_reg->s32_max_value = S32_MAX; 12766 } else { 12767 /* ORing two positives gives a positive, so safe to 12768 * cast result into s64. 12769 */ 12770 dst_reg->s32_min_value = dst_reg->u32_min_value; 12771 dst_reg->s32_max_value = dst_reg->u32_max_value; 12772 } 12773 } 12774 12775 static void scalar_min_max_or(struct bpf_reg_state *dst_reg, 12776 struct bpf_reg_state *src_reg) 12777 { 12778 bool src_known = tnum_is_const(src_reg->var_off); 12779 bool dst_known = tnum_is_const(dst_reg->var_off); 12780 s64 smin_val = src_reg->smin_value; 12781 u64 umin_val = src_reg->umin_value; 12782 12783 if (src_known && dst_known) { 12784 __mark_reg_known(dst_reg, dst_reg->var_off.value); 12785 return; 12786 } 12787 12788 /* We get our maximum from the var_off, and our minimum is the 12789 * maximum of the operands' minima 12790 */ 12791 dst_reg->umin_value = max(dst_reg->umin_value, umin_val); 12792 dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask; 12793 if (dst_reg->smin_value < 0 || smin_val < 0) { 12794 /* Lose signed bounds when ORing negative numbers, 12795 * ain't nobody got time for that. 12796 */ 12797 dst_reg->smin_value = S64_MIN; 12798 dst_reg->smax_value = S64_MAX; 12799 } else { 12800 /* ORing two positives gives a positive, so safe to 12801 * cast result into s64. 12802 */ 12803 dst_reg->smin_value = dst_reg->umin_value; 12804 dst_reg->smax_value = dst_reg->umax_value; 12805 } 12806 /* We may learn something more from the var_off */ 12807 __update_reg_bounds(dst_reg); 12808 } 12809 12810 static void scalar32_min_max_xor(struct bpf_reg_state *dst_reg, 12811 struct bpf_reg_state *src_reg) 12812 { 12813 bool src_known = tnum_subreg_is_const(src_reg->var_off); 12814 bool dst_known = tnum_subreg_is_const(dst_reg->var_off); 12815 struct tnum var32_off = tnum_subreg(dst_reg->var_off); 12816 s32 smin_val = src_reg->s32_min_value; 12817 12818 if (src_known && dst_known) { 12819 __mark_reg32_known(dst_reg, var32_off.value); 12820 return; 12821 } 12822 12823 /* We get both minimum and maximum from the var32_off. */ 12824 dst_reg->u32_min_value = var32_off.value; 12825 dst_reg->u32_max_value = var32_off.value | var32_off.mask; 12826 12827 if (dst_reg->s32_min_value >= 0 && smin_val >= 0) { 12828 /* XORing two positive sign numbers gives a positive, 12829 * so safe to cast u32 result into s32. 12830 */ 12831 dst_reg->s32_min_value = dst_reg->u32_min_value; 12832 dst_reg->s32_max_value = dst_reg->u32_max_value; 12833 } else { 12834 dst_reg->s32_min_value = S32_MIN; 12835 dst_reg->s32_max_value = S32_MAX; 12836 } 12837 } 12838 12839 static void scalar_min_max_xor(struct bpf_reg_state *dst_reg, 12840 struct bpf_reg_state *src_reg) 12841 { 12842 bool src_known = tnum_is_const(src_reg->var_off); 12843 bool dst_known = tnum_is_const(dst_reg->var_off); 12844 s64 smin_val = src_reg->smin_value; 12845 12846 if (src_known && dst_known) { 12847 /* dst_reg->var_off.value has been updated earlier */ 12848 __mark_reg_known(dst_reg, dst_reg->var_off.value); 12849 return; 12850 } 12851 12852 /* We get both minimum and maximum from the var_off. */ 12853 dst_reg->umin_value = dst_reg->var_off.value; 12854 dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask; 12855 12856 if (dst_reg->smin_value >= 0 && smin_val >= 0) { 12857 /* XORing two positive sign numbers gives a positive, 12858 * so safe to cast u64 result into s64. 12859 */ 12860 dst_reg->smin_value = dst_reg->umin_value; 12861 dst_reg->smax_value = dst_reg->umax_value; 12862 } else { 12863 dst_reg->smin_value = S64_MIN; 12864 dst_reg->smax_value = S64_MAX; 12865 } 12866 12867 __update_reg_bounds(dst_reg); 12868 } 12869 12870 static void __scalar32_min_max_lsh(struct bpf_reg_state *dst_reg, 12871 u64 umin_val, u64 umax_val) 12872 { 12873 /* We lose all sign bit information (except what we can pick 12874 * up from var_off) 12875 */ 12876 dst_reg->s32_min_value = S32_MIN; 12877 dst_reg->s32_max_value = S32_MAX; 12878 /* If we might shift our top bit out, then we know nothing */ 12879 if (umax_val > 31 || dst_reg->u32_max_value > 1ULL << (31 - umax_val)) { 12880 dst_reg->u32_min_value = 0; 12881 dst_reg->u32_max_value = U32_MAX; 12882 } else { 12883 dst_reg->u32_min_value <<= umin_val; 12884 dst_reg->u32_max_value <<= umax_val; 12885 } 12886 } 12887 12888 static void scalar32_min_max_lsh(struct bpf_reg_state *dst_reg, 12889 struct bpf_reg_state *src_reg) 12890 { 12891 u32 umax_val = src_reg->u32_max_value; 12892 u32 umin_val = src_reg->u32_min_value; 12893 /* u32 alu operation will zext upper bits */ 12894 struct tnum subreg = tnum_subreg(dst_reg->var_off); 12895 12896 __scalar32_min_max_lsh(dst_reg, umin_val, umax_val); 12897 dst_reg->var_off = tnum_subreg(tnum_lshift(subreg, umin_val)); 12898 /* Not required but being careful mark reg64 bounds as unknown so 12899 * that we are forced to pick them up from tnum and zext later and 12900 * if some path skips this step we are still safe. 12901 */ 12902 __mark_reg64_unbounded(dst_reg); 12903 __update_reg32_bounds(dst_reg); 12904 } 12905 12906 static void __scalar64_min_max_lsh(struct bpf_reg_state *dst_reg, 12907 u64 umin_val, u64 umax_val) 12908 { 12909 /* Special case <<32 because it is a common compiler pattern to sign 12910 * extend subreg by doing <<32 s>>32. In this case if 32bit bounds are 12911 * positive we know this shift will also be positive so we can track 12912 * bounds correctly. Otherwise we lose all sign bit information except 12913 * what we can pick up from var_off. Perhaps we can generalize this 12914 * later to shifts of any length. 12915 */ 12916 if (umin_val == 32 && umax_val == 32 && dst_reg->s32_max_value >= 0) 12917 dst_reg->smax_value = (s64)dst_reg->s32_max_value << 32; 12918 else 12919 dst_reg->smax_value = S64_MAX; 12920 12921 if (umin_val == 32 && umax_val == 32 && dst_reg->s32_min_value >= 0) 12922 dst_reg->smin_value = (s64)dst_reg->s32_min_value << 32; 12923 else 12924 dst_reg->smin_value = S64_MIN; 12925 12926 /* If we might shift our top bit out, then we know nothing */ 12927 if (dst_reg->umax_value > 1ULL << (63 - umax_val)) { 12928 dst_reg->umin_value = 0; 12929 dst_reg->umax_value = U64_MAX; 12930 } else { 12931 dst_reg->umin_value <<= umin_val; 12932 dst_reg->umax_value <<= umax_val; 12933 } 12934 } 12935 12936 static void scalar_min_max_lsh(struct bpf_reg_state *dst_reg, 12937 struct bpf_reg_state *src_reg) 12938 { 12939 u64 umax_val = src_reg->umax_value; 12940 u64 umin_val = src_reg->umin_value; 12941 12942 /* scalar64 calc uses 32bit unshifted bounds so must be called first */ 12943 __scalar64_min_max_lsh(dst_reg, umin_val, umax_val); 12944 __scalar32_min_max_lsh(dst_reg, umin_val, umax_val); 12945 12946 dst_reg->var_off = tnum_lshift(dst_reg->var_off, umin_val); 12947 /* We may learn something more from the var_off */ 12948 __update_reg_bounds(dst_reg); 12949 } 12950 12951 static void scalar32_min_max_rsh(struct bpf_reg_state *dst_reg, 12952 struct bpf_reg_state *src_reg) 12953 { 12954 struct tnum subreg = tnum_subreg(dst_reg->var_off); 12955 u32 umax_val = src_reg->u32_max_value; 12956 u32 umin_val = src_reg->u32_min_value; 12957 12958 /* BPF_RSH is an unsigned shift. If the value in dst_reg might 12959 * be negative, then either: 12960 * 1) src_reg might be zero, so the sign bit of the result is 12961 * unknown, so we lose our signed bounds 12962 * 2) it's known negative, thus the unsigned bounds capture the 12963 * signed bounds 12964 * 3) the signed bounds cross zero, so they tell us nothing 12965 * about the result 12966 * If the value in dst_reg is known nonnegative, then again the 12967 * unsigned bounds capture the signed bounds. 12968 * Thus, in all cases it suffices to blow away our signed bounds 12969 * and rely on inferring new ones from the unsigned bounds and 12970 * var_off of the result. 12971 */ 12972 dst_reg->s32_min_value = S32_MIN; 12973 dst_reg->s32_max_value = S32_MAX; 12974 12975 dst_reg->var_off = tnum_rshift(subreg, umin_val); 12976 dst_reg->u32_min_value >>= umax_val; 12977 dst_reg->u32_max_value >>= umin_val; 12978 12979 __mark_reg64_unbounded(dst_reg); 12980 __update_reg32_bounds(dst_reg); 12981 } 12982 12983 static void scalar_min_max_rsh(struct bpf_reg_state *dst_reg, 12984 struct bpf_reg_state *src_reg) 12985 { 12986 u64 umax_val = src_reg->umax_value; 12987 u64 umin_val = src_reg->umin_value; 12988 12989 /* BPF_RSH is an unsigned shift. If the value in dst_reg might 12990 * be negative, then either: 12991 * 1) src_reg might be zero, so the sign bit of the result is 12992 * unknown, so we lose our signed bounds 12993 * 2) it's known negative, thus the unsigned bounds capture the 12994 * signed bounds 12995 * 3) the signed bounds cross zero, so they tell us nothing 12996 * about the result 12997 * If the value in dst_reg is known nonnegative, then again the 12998 * unsigned bounds capture the signed bounds. 12999 * Thus, in all cases it suffices to blow away our signed bounds 13000 * and rely on inferring new ones from the unsigned bounds and 13001 * var_off of the result. 13002 */ 13003 dst_reg->smin_value = S64_MIN; 13004 dst_reg->smax_value = S64_MAX; 13005 dst_reg->var_off = tnum_rshift(dst_reg->var_off, umin_val); 13006 dst_reg->umin_value >>= umax_val; 13007 dst_reg->umax_value >>= umin_val; 13008 13009 /* Its not easy to operate on alu32 bounds here because it depends 13010 * on bits being shifted in. Take easy way out and mark unbounded 13011 * so we can recalculate later from tnum. 13012 */ 13013 __mark_reg32_unbounded(dst_reg); 13014 __update_reg_bounds(dst_reg); 13015 } 13016 13017 static void scalar32_min_max_arsh(struct bpf_reg_state *dst_reg, 13018 struct bpf_reg_state *src_reg) 13019 { 13020 u64 umin_val = src_reg->u32_min_value; 13021 13022 /* Upon reaching here, src_known is true and 13023 * umax_val is equal to umin_val. 13024 */ 13025 dst_reg->s32_min_value = (u32)(((s32)dst_reg->s32_min_value) >> umin_val); 13026 dst_reg->s32_max_value = (u32)(((s32)dst_reg->s32_max_value) >> umin_val); 13027 13028 dst_reg->var_off = tnum_arshift(tnum_subreg(dst_reg->var_off), umin_val, 32); 13029 13030 /* blow away the dst_reg umin_value/umax_value and rely on 13031 * dst_reg var_off to refine the result. 13032 */ 13033 dst_reg->u32_min_value = 0; 13034 dst_reg->u32_max_value = U32_MAX; 13035 13036 __mark_reg64_unbounded(dst_reg); 13037 __update_reg32_bounds(dst_reg); 13038 } 13039 13040 static void scalar_min_max_arsh(struct bpf_reg_state *dst_reg, 13041 struct bpf_reg_state *src_reg) 13042 { 13043 u64 umin_val = src_reg->umin_value; 13044 13045 /* Upon reaching here, src_known is true and umax_val is equal 13046 * to umin_val. 13047 */ 13048 dst_reg->smin_value >>= umin_val; 13049 dst_reg->smax_value >>= umin_val; 13050 13051 dst_reg->var_off = tnum_arshift(dst_reg->var_off, umin_val, 64); 13052 13053 /* blow away the dst_reg umin_value/umax_value and rely on 13054 * dst_reg var_off to refine the result. 13055 */ 13056 dst_reg->umin_value = 0; 13057 dst_reg->umax_value = U64_MAX; 13058 13059 /* Its not easy to operate on alu32 bounds here because it depends 13060 * on bits being shifted in from upper 32-bits. Take easy way out 13061 * and mark unbounded so we can recalculate later from tnum. 13062 */ 13063 __mark_reg32_unbounded(dst_reg); 13064 __update_reg_bounds(dst_reg); 13065 } 13066 13067 /* WARNING: This function does calculations on 64-bit values, but the actual 13068 * execution may occur on 32-bit values. Therefore, things like bitshifts 13069 * need extra checks in the 32-bit case. 13070 */ 13071 static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env, 13072 struct bpf_insn *insn, 13073 struct bpf_reg_state *dst_reg, 13074 struct bpf_reg_state src_reg) 13075 { 13076 struct bpf_reg_state *regs = cur_regs(env); 13077 u8 opcode = BPF_OP(insn->code); 13078 bool src_known; 13079 s64 smin_val, smax_val; 13080 u64 umin_val, umax_val; 13081 s32 s32_min_val, s32_max_val; 13082 u32 u32_min_val, u32_max_val; 13083 u64 insn_bitness = (BPF_CLASS(insn->code) == BPF_ALU64) ? 64 : 32; 13084 bool alu32 = (BPF_CLASS(insn->code) != BPF_ALU64); 13085 int ret; 13086 13087 smin_val = src_reg.smin_value; 13088 smax_val = src_reg.smax_value; 13089 umin_val = src_reg.umin_value; 13090 umax_val = src_reg.umax_value; 13091 13092 s32_min_val = src_reg.s32_min_value; 13093 s32_max_val = src_reg.s32_max_value; 13094 u32_min_val = src_reg.u32_min_value; 13095 u32_max_val = src_reg.u32_max_value; 13096 13097 if (alu32) { 13098 src_known = tnum_subreg_is_const(src_reg.var_off); 13099 if ((src_known && 13100 (s32_min_val != s32_max_val || u32_min_val != u32_max_val)) || 13101 s32_min_val > s32_max_val || u32_min_val > u32_max_val) { 13102 /* Taint dst register if offset had invalid bounds 13103 * derived from e.g. dead branches. 13104 */ 13105 __mark_reg_unknown(env, dst_reg); 13106 return 0; 13107 } 13108 } else { 13109 src_known = tnum_is_const(src_reg.var_off); 13110 if ((src_known && 13111 (smin_val != smax_val || umin_val != umax_val)) || 13112 smin_val > smax_val || umin_val > umax_val) { 13113 /* Taint dst register if offset had invalid bounds 13114 * derived from e.g. dead branches. 13115 */ 13116 __mark_reg_unknown(env, dst_reg); 13117 return 0; 13118 } 13119 } 13120 13121 if (!src_known && 13122 opcode != BPF_ADD && opcode != BPF_SUB && opcode != BPF_AND) { 13123 __mark_reg_unknown(env, dst_reg); 13124 return 0; 13125 } 13126 13127 if (sanitize_needed(opcode)) { 13128 ret = sanitize_val_alu(env, insn); 13129 if (ret < 0) 13130 return sanitize_err(env, insn, ret, NULL, NULL); 13131 } 13132 13133 /* Calculate sign/unsigned bounds and tnum for alu32 and alu64 bit ops. 13134 * There are two classes of instructions: The first class we track both 13135 * alu32 and alu64 sign/unsigned bounds independently this provides the 13136 * greatest amount of precision when alu operations are mixed with jmp32 13137 * operations. These operations are BPF_ADD, BPF_SUB, BPF_MUL, BPF_ADD, 13138 * and BPF_OR. This is possible because these ops have fairly easy to 13139 * understand and calculate behavior in both 32-bit and 64-bit alu ops. 13140 * See alu32 verifier tests for examples. The second class of 13141 * operations, BPF_LSH, BPF_RSH, and BPF_ARSH, however are not so easy 13142 * with regards to tracking sign/unsigned bounds because the bits may 13143 * cross subreg boundaries in the alu64 case. When this happens we mark 13144 * the reg unbounded in the subreg bound space and use the resulting 13145 * tnum to calculate an approximation of the sign/unsigned bounds. 13146 */ 13147 switch (opcode) { 13148 case BPF_ADD: 13149 scalar32_min_max_add(dst_reg, &src_reg); 13150 scalar_min_max_add(dst_reg, &src_reg); 13151 dst_reg->var_off = tnum_add(dst_reg->var_off, src_reg.var_off); 13152 break; 13153 case BPF_SUB: 13154 scalar32_min_max_sub(dst_reg, &src_reg); 13155 scalar_min_max_sub(dst_reg, &src_reg); 13156 dst_reg->var_off = tnum_sub(dst_reg->var_off, src_reg.var_off); 13157 break; 13158 case BPF_MUL: 13159 dst_reg->var_off = tnum_mul(dst_reg->var_off, src_reg.var_off); 13160 scalar32_min_max_mul(dst_reg, &src_reg); 13161 scalar_min_max_mul(dst_reg, &src_reg); 13162 break; 13163 case BPF_AND: 13164 dst_reg->var_off = tnum_and(dst_reg->var_off, src_reg.var_off); 13165 scalar32_min_max_and(dst_reg, &src_reg); 13166 scalar_min_max_and(dst_reg, &src_reg); 13167 break; 13168 case BPF_OR: 13169 dst_reg->var_off = tnum_or(dst_reg->var_off, src_reg.var_off); 13170 scalar32_min_max_or(dst_reg, &src_reg); 13171 scalar_min_max_or(dst_reg, &src_reg); 13172 break; 13173 case BPF_XOR: 13174 dst_reg->var_off = tnum_xor(dst_reg->var_off, src_reg.var_off); 13175 scalar32_min_max_xor(dst_reg, &src_reg); 13176 scalar_min_max_xor(dst_reg, &src_reg); 13177 break; 13178 case BPF_LSH: 13179 if (umax_val >= insn_bitness) { 13180 /* Shifts greater than 31 or 63 are undefined. 13181 * This includes shifts by a negative number. 13182 */ 13183 mark_reg_unknown(env, regs, insn->dst_reg); 13184 break; 13185 } 13186 if (alu32) 13187 scalar32_min_max_lsh(dst_reg, &src_reg); 13188 else 13189 scalar_min_max_lsh(dst_reg, &src_reg); 13190 break; 13191 case BPF_RSH: 13192 if (umax_val >= insn_bitness) { 13193 /* Shifts greater than 31 or 63 are undefined. 13194 * This includes shifts by a negative number. 13195 */ 13196 mark_reg_unknown(env, regs, insn->dst_reg); 13197 break; 13198 } 13199 if (alu32) 13200 scalar32_min_max_rsh(dst_reg, &src_reg); 13201 else 13202 scalar_min_max_rsh(dst_reg, &src_reg); 13203 break; 13204 case BPF_ARSH: 13205 if (umax_val >= insn_bitness) { 13206 /* Shifts greater than 31 or 63 are undefined. 13207 * This includes shifts by a negative number. 13208 */ 13209 mark_reg_unknown(env, regs, insn->dst_reg); 13210 break; 13211 } 13212 if (alu32) 13213 scalar32_min_max_arsh(dst_reg, &src_reg); 13214 else 13215 scalar_min_max_arsh(dst_reg, &src_reg); 13216 break; 13217 default: 13218 mark_reg_unknown(env, regs, insn->dst_reg); 13219 break; 13220 } 13221 13222 /* ALU32 ops are zero extended into 64bit register */ 13223 if (alu32) 13224 zext_32_to_64(dst_reg); 13225 reg_bounds_sync(dst_reg); 13226 return 0; 13227 } 13228 13229 /* Handles ALU ops other than BPF_END, BPF_NEG and BPF_MOV: computes new min/max 13230 * and var_off. 13231 */ 13232 static int adjust_reg_min_max_vals(struct bpf_verifier_env *env, 13233 struct bpf_insn *insn) 13234 { 13235 struct bpf_verifier_state *vstate = env->cur_state; 13236 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 13237 struct bpf_reg_state *regs = state->regs, *dst_reg, *src_reg; 13238 struct bpf_reg_state *ptr_reg = NULL, off_reg = {0}; 13239 u8 opcode = BPF_OP(insn->code); 13240 int err; 13241 13242 dst_reg = ®s[insn->dst_reg]; 13243 src_reg = NULL; 13244 if (dst_reg->type != SCALAR_VALUE) 13245 ptr_reg = dst_reg; 13246 else 13247 /* Make sure ID is cleared otherwise dst_reg min/max could be 13248 * incorrectly propagated into other registers by find_equal_scalars() 13249 */ 13250 dst_reg->id = 0; 13251 if (BPF_SRC(insn->code) == BPF_X) { 13252 src_reg = ®s[insn->src_reg]; 13253 if (src_reg->type != SCALAR_VALUE) { 13254 if (dst_reg->type != SCALAR_VALUE) { 13255 /* Combining two pointers by any ALU op yields 13256 * an arbitrary scalar. Disallow all math except 13257 * pointer subtraction 13258 */ 13259 if (opcode == BPF_SUB && env->allow_ptr_leaks) { 13260 mark_reg_unknown(env, regs, insn->dst_reg); 13261 return 0; 13262 } 13263 verbose(env, "R%d pointer %s pointer prohibited\n", 13264 insn->dst_reg, 13265 bpf_alu_string[opcode >> 4]); 13266 return -EACCES; 13267 } else { 13268 /* scalar += pointer 13269 * This is legal, but we have to reverse our 13270 * src/dest handling in computing the range 13271 */ 13272 err = mark_chain_precision(env, insn->dst_reg); 13273 if (err) 13274 return err; 13275 return adjust_ptr_min_max_vals(env, insn, 13276 src_reg, dst_reg); 13277 } 13278 } else if (ptr_reg) { 13279 /* pointer += scalar */ 13280 err = mark_chain_precision(env, insn->src_reg); 13281 if (err) 13282 return err; 13283 return adjust_ptr_min_max_vals(env, insn, 13284 dst_reg, src_reg); 13285 } else if (dst_reg->precise) { 13286 /* if dst_reg is precise, src_reg should be precise as well */ 13287 err = mark_chain_precision(env, insn->src_reg); 13288 if (err) 13289 return err; 13290 } 13291 } else { 13292 /* Pretend the src is a reg with a known value, since we only 13293 * need to be able to read from this state. 13294 */ 13295 off_reg.type = SCALAR_VALUE; 13296 __mark_reg_known(&off_reg, insn->imm); 13297 src_reg = &off_reg; 13298 if (ptr_reg) /* pointer += K */ 13299 return adjust_ptr_min_max_vals(env, insn, 13300 ptr_reg, src_reg); 13301 } 13302 13303 /* Got here implies adding two SCALAR_VALUEs */ 13304 if (WARN_ON_ONCE(ptr_reg)) { 13305 print_verifier_state(env, state, true); 13306 verbose(env, "verifier internal error: unexpected ptr_reg\n"); 13307 return -EINVAL; 13308 } 13309 if (WARN_ON(!src_reg)) { 13310 print_verifier_state(env, state, true); 13311 verbose(env, "verifier internal error: no src_reg\n"); 13312 return -EINVAL; 13313 } 13314 return adjust_scalar_min_max_vals(env, insn, dst_reg, *src_reg); 13315 } 13316 13317 /* check validity of 32-bit and 64-bit arithmetic operations */ 13318 static int check_alu_op(struct bpf_verifier_env *env, struct bpf_insn *insn) 13319 { 13320 struct bpf_reg_state *regs = cur_regs(env); 13321 u8 opcode = BPF_OP(insn->code); 13322 int err; 13323 13324 if (opcode == BPF_END || opcode == BPF_NEG) { 13325 if (opcode == BPF_NEG) { 13326 if (BPF_SRC(insn->code) != BPF_K || 13327 insn->src_reg != BPF_REG_0 || 13328 insn->off != 0 || insn->imm != 0) { 13329 verbose(env, "BPF_NEG uses reserved fields\n"); 13330 return -EINVAL; 13331 } 13332 } else { 13333 if (insn->src_reg != BPF_REG_0 || insn->off != 0 || 13334 (insn->imm != 16 && insn->imm != 32 && insn->imm != 64) || 13335 (BPF_CLASS(insn->code) == BPF_ALU64 && 13336 BPF_SRC(insn->code) != BPF_TO_LE)) { 13337 verbose(env, "BPF_END uses reserved fields\n"); 13338 return -EINVAL; 13339 } 13340 } 13341 13342 /* check src operand */ 13343 err = check_reg_arg(env, insn->dst_reg, SRC_OP); 13344 if (err) 13345 return err; 13346 13347 if (is_pointer_value(env, insn->dst_reg)) { 13348 verbose(env, "R%d pointer arithmetic prohibited\n", 13349 insn->dst_reg); 13350 return -EACCES; 13351 } 13352 13353 /* check dest operand */ 13354 err = check_reg_arg(env, insn->dst_reg, DST_OP); 13355 if (err) 13356 return err; 13357 13358 } else if (opcode == BPF_MOV) { 13359 13360 if (BPF_SRC(insn->code) == BPF_X) { 13361 if (insn->imm != 0) { 13362 verbose(env, "BPF_MOV uses reserved fields\n"); 13363 return -EINVAL; 13364 } 13365 13366 if (BPF_CLASS(insn->code) == BPF_ALU) { 13367 if (insn->off != 0 && insn->off != 8 && insn->off != 16) { 13368 verbose(env, "BPF_MOV uses reserved fields\n"); 13369 return -EINVAL; 13370 } 13371 } else { 13372 if (insn->off != 0 && insn->off != 8 && insn->off != 16 && 13373 insn->off != 32) { 13374 verbose(env, "BPF_MOV uses reserved fields\n"); 13375 return -EINVAL; 13376 } 13377 } 13378 13379 /* check src operand */ 13380 err = check_reg_arg(env, insn->src_reg, SRC_OP); 13381 if (err) 13382 return err; 13383 } else { 13384 if (insn->src_reg != BPF_REG_0 || insn->off != 0) { 13385 verbose(env, "BPF_MOV uses reserved fields\n"); 13386 return -EINVAL; 13387 } 13388 } 13389 13390 /* check dest operand, mark as required later */ 13391 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK); 13392 if (err) 13393 return err; 13394 13395 if (BPF_SRC(insn->code) == BPF_X) { 13396 struct bpf_reg_state *src_reg = regs + insn->src_reg; 13397 struct bpf_reg_state *dst_reg = regs + insn->dst_reg; 13398 bool need_id = src_reg->type == SCALAR_VALUE && !src_reg->id && 13399 !tnum_is_const(src_reg->var_off); 13400 13401 if (BPF_CLASS(insn->code) == BPF_ALU64) { 13402 if (insn->off == 0) { 13403 /* case: R1 = R2 13404 * copy register state to dest reg 13405 */ 13406 if (need_id) 13407 /* Assign src and dst registers the same ID 13408 * that will be used by find_equal_scalars() 13409 * to propagate min/max range. 13410 */ 13411 src_reg->id = ++env->id_gen; 13412 copy_register_state(dst_reg, src_reg); 13413 dst_reg->live |= REG_LIVE_WRITTEN; 13414 dst_reg->subreg_def = DEF_NOT_SUBREG; 13415 } else { 13416 /* case: R1 = (s8, s16 s32)R2 */ 13417 if (is_pointer_value(env, insn->src_reg)) { 13418 verbose(env, 13419 "R%d sign-extension part of pointer\n", 13420 insn->src_reg); 13421 return -EACCES; 13422 } else if (src_reg->type == SCALAR_VALUE) { 13423 bool no_sext; 13424 13425 no_sext = src_reg->umax_value < (1ULL << (insn->off - 1)); 13426 if (no_sext && need_id) 13427 src_reg->id = ++env->id_gen; 13428 copy_register_state(dst_reg, src_reg); 13429 if (!no_sext) 13430 dst_reg->id = 0; 13431 coerce_reg_to_size_sx(dst_reg, insn->off >> 3); 13432 dst_reg->live |= REG_LIVE_WRITTEN; 13433 dst_reg->subreg_def = DEF_NOT_SUBREG; 13434 } else { 13435 mark_reg_unknown(env, regs, insn->dst_reg); 13436 } 13437 } 13438 } else { 13439 /* R1 = (u32) R2 */ 13440 if (is_pointer_value(env, insn->src_reg)) { 13441 verbose(env, 13442 "R%d partial copy of pointer\n", 13443 insn->src_reg); 13444 return -EACCES; 13445 } else if (src_reg->type == SCALAR_VALUE) { 13446 if (insn->off == 0) { 13447 bool is_src_reg_u32 = src_reg->umax_value <= U32_MAX; 13448 13449 if (is_src_reg_u32 && need_id) 13450 src_reg->id = ++env->id_gen; 13451 copy_register_state(dst_reg, src_reg); 13452 /* Make sure ID is cleared if src_reg is not in u32 13453 * range otherwise dst_reg min/max could be incorrectly 13454 * propagated into src_reg by find_equal_scalars() 13455 */ 13456 if (!is_src_reg_u32) 13457 dst_reg->id = 0; 13458 dst_reg->live |= REG_LIVE_WRITTEN; 13459 dst_reg->subreg_def = env->insn_idx + 1; 13460 } else { 13461 /* case: W1 = (s8, s16)W2 */ 13462 bool no_sext = src_reg->umax_value < (1ULL << (insn->off - 1)); 13463 13464 if (no_sext && need_id) 13465 src_reg->id = ++env->id_gen; 13466 copy_register_state(dst_reg, src_reg); 13467 if (!no_sext) 13468 dst_reg->id = 0; 13469 dst_reg->live |= REG_LIVE_WRITTEN; 13470 dst_reg->subreg_def = env->insn_idx + 1; 13471 coerce_subreg_to_size_sx(dst_reg, insn->off >> 3); 13472 } 13473 } else { 13474 mark_reg_unknown(env, regs, 13475 insn->dst_reg); 13476 } 13477 zext_32_to_64(dst_reg); 13478 reg_bounds_sync(dst_reg); 13479 } 13480 } else { 13481 /* case: R = imm 13482 * remember the value we stored into this reg 13483 */ 13484 /* clear any state __mark_reg_known doesn't set */ 13485 mark_reg_unknown(env, regs, insn->dst_reg); 13486 regs[insn->dst_reg].type = SCALAR_VALUE; 13487 if (BPF_CLASS(insn->code) == BPF_ALU64) { 13488 __mark_reg_known(regs + insn->dst_reg, 13489 insn->imm); 13490 } else { 13491 __mark_reg_known(regs + insn->dst_reg, 13492 (u32)insn->imm); 13493 } 13494 } 13495 13496 } else if (opcode > BPF_END) { 13497 verbose(env, "invalid BPF_ALU opcode %x\n", opcode); 13498 return -EINVAL; 13499 13500 } else { /* all other ALU ops: and, sub, xor, add, ... */ 13501 13502 if (BPF_SRC(insn->code) == BPF_X) { 13503 if (insn->imm != 0 || insn->off > 1 || 13504 (insn->off == 1 && opcode != BPF_MOD && opcode != BPF_DIV)) { 13505 verbose(env, "BPF_ALU uses reserved fields\n"); 13506 return -EINVAL; 13507 } 13508 /* check src1 operand */ 13509 err = check_reg_arg(env, insn->src_reg, SRC_OP); 13510 if (err) 13511 return err; 13512 } else { 13513 if (insn->src_reg != BPF_REG_0 || insn->off > 1 || 13514 (insn->off == 1 && opcode != BPF_MOD && opcode != BPF_DIV)) { 13515 verbose(env, "BPF_ALU uses reserved fields\n"); 13516 return -EINVAL; 13517 } 13518 } 13519 13520 /* check src2 operand */ 13521 err = check_reg_arg(env, insn->dst_reg, SRC_OP); 13522 if (err) 13523 return err; 13524 13525 if ((opcode == BPF_MOD || opcode == BPF_DIV) && 13526 BPF_SRC(insn->code) == BPF_K && insn->imm == 0) { 13527 verbose(env, "div by zero\n"); 13528 return -EINVAL; 13529 } 13530 13531 if ((opcode == BPF_LSH || opcode == BPF_RSH || 13532 opcode == BPF_ARSH) && BPF_SRC(insn->code) == BPF_K) { 13533 int size = BPF_CLASS(insn->code) == BPF_ALU64 ? 64 : 32; 13534 13535 if (insn->imm < 0 || insn->imm >= size) { 13536 verbose(env, "invalid shift %d\n", insn->imm); 13537 return -EINVAL; 13538 } 13539 } 13540 13541 /* check dest operand */ 13542 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK); 13543 if (err) 13544 return err; 13545 13546 return adjust_reg_min_max_vals(env, insn); 13547 } 13548 13549 return 0; 13550 } 13551 13552 static void find_good_pkt_pointers(struct bpf_verifier_state *vstate, 13553 struct bpf_reg_state *dst_reg, 13554 enum bpf_reg_type type, 13555 bool range_right_open) 13556 { 13557 struct bpf_func_state *state; 13558 struct bpf_reg_state *reg; 13559 int new_range; 13560 13561 if (dst_reg->off < 0 || 13562 (dst_reg->off == 0 && range_right_open)) 13563 /* This doesn't give us any range */ 13564 return; 13565 13566 if (dst_reg->umax_value > MAX_PACKET_OFF || 13567 dst_reg->umax_value + dst_reg->off > MAX_PACKET_OFF) 13568 /* Risk of overflow. For instance, ptr + (1<<63) may be less 13569 * than pkt_end, but that's because it's also less than pkt. 13570 */ 13571 return; 13572 13573 new_range = dst_reg->off; 13574 if (range_right_open) 13575 new_range++; 13576 13577 /* Examples for register markings: 13578 * 13579 * pkt_data in dst register: 13580 * 13581 * r2 = r3; 13582 * r2 += 8; 13583 * if (r2 > pkt_end) goto <handle exception> 13584 * <access okay> 13585 * 13586 * r2 = r3; 13587 * r2 += 8; 13588 * if (r2 < pkt_end) goto <access okay> 13589 * <handle exception> 13590 * 13591 * Where: 13592 * r2 == dst_reg, pkt_end == src_reg 13593 * r2=pkt(id=n,off=8,r=0) 13594 * r3=pkt(id=n,off=0,r=0) 13595 * 13596 * pkt_data in src register: 13597 * 13598 * r2 = r3; 13599 * r2 += 8; 13600 * if (pkt_end >= r2) goto <access okay> 13601 * <handle exception> 13602 * 13603 * r2 = r3; 13604 * r2 += 8; 13605 * if (pkt_end <= r2) goto <handle exception> 13606 * <access okay> 13607 * 13608 * Where: 13609 * pkt_end == dst_reg, r2 == src_reg 13610 * r2=pkt(id=n,off=8,r=0) 13611 * r3=pkt(id=n,off=0,r=0) 13612 * 13613 * Find register r3 and mark its range as r3=pkt(id=n,off=0,r=8) 13614 * or r3=pkt(id=n,off=0,r=8-1), so that range of bytes [r3, r3 + 8) 13615 * and [r3, r3 + 8-1) respectively is safe to access depending on 13616 * the check. 13617 */ 13618 13619 /* If our ids match, then we must have the same max_value. And we 13620 * don't care about the other reg's fixed offset, since if it's too big 13621 * the range won't allow anything. 13622 * dst_reg->off is known < MAX_PACKET_OFF, therefore it fits in a u16. 13623 */ 13624 bpf_for_each_reg_in_vstate(vstate, state, reg, ({ 13625 if (reg->type == type && reg->id == dst_reg->id) 13626 /* keep the maximum range already checked */ 13627 reg->range = max(reg->range, new_range); 13628 })); 13629 } 13630 13631 static int is_branch32_taken(struct bpf_reg_state *reg, u32 val, u8 opcode) 13632 { 13633 struct tnum subreg = tnum_subreg(reg->var_off); 13634 s32 sval = (s32)val; 13635 13636 switch (opcode) { 13637 case BPF_JEQ: 13638 if (tnum_is_const(subreg)) 13639 return !!tnum_equals_const(subreg, val); 13640 else if (val < reg->u32_min_value || val > reg->u32_max_value) 13641 return 0; 13642 break; 13643 case BPF_JNE: 13644 if (tnum_is_const(subreg)) 13645 return !tnum_equals_const(subreg, val); 13646 else if (val < reg->u32_min_value || val > reg->u32_max_value) 13647 return 1; 13648 break; 13649 case BPF_JSET: 13650 if ((~subreg.mask & subreg.value) & val) 13651 return 1; 13652 if (!((subreg.mask | subreg.value) & val)) 13653 return 0; 13654 break; 13655 case BPF_JGT: 13656 if (reg->u32_min_value > val) 13657 return 1; 13658 else if (reg->u32_max_value <= val) 13659 return 0; 13660 break; 13661 case BPF_JSGT: 13662 if (reg->s32_min_value > sval) 13663 return 1; 13664 else if (reg->s32_max_value <= sval) 13665 return 0; 13666 break; 13667 case BPF_JLT: 13668 if (reg->u32_max_value < val) 13669 return 1; 13670 else if (reg->u32_min_value >= val) 13671 return 0; 13672 break; 13673 case BPF_JSLT: 13674 if (reg->s32_max_value < sval) 13675 return 1; 13676 else if (reg->s32_min_value >= sval) 13677 return 0; 13678 break; 13679 case BPF_JGE: 13680 if (reg->u32_min_value >= val) 13681 return 1; 13682 else if (reg->u32_max_value < val) 13683 return 0; 13684 break; 13685 case BPF_JSGE: 13686 if (reg->s32_min_value >= sval) 13687 return 1; 13688 else if (reg->s32_max_value < sval) 13689 return 0; 13690 break; 13691 case BPF_JLE: 13692 if (reg->u32_max_value <= val) 13693 return 1; 13694 else if (reg->u32_min_value > val) 13695 return 0; 13696 break; 13697 case BPF_JSLE: 13698 if (reg->s32_max_value <= sval) 13699 return 1; 13700 else if (reg->s32_min_value > sval) 13701 return 0; 13702 break; 13703 } 13704 13705 return -1; 13706 } 13707 13708 13709 static int is_branch64_taken(struct bpf_reg_state *reg, u64 val, u8 opcode) 13710 { 13711 s64 sval = (s64)val; 13712 13713 switch (opcode) { 13714 case BPF_JEQ: 13715 if (tnum_is_const(reg->var_off)) 13716 return !!tnum_equals_const(reg->var_off, val); 13717 else if (val < reg->umin_value || val > reg->umax_value) 13718 return 0; 13719 break; 13720 case BPF_JNE: 13721 if (tnum_is_const(reg->var_off)) 13722 return !tnum_equals_const(reg->var_off, val); 13723 else if (val < reg->umin_value || val > reg->umax_value) 13724 return 1; 13725 break; 13726 case BPF_JSET: 13727 if ((~reg->var_off.mask & reg->var_off.value) & val) 13728 return 1; 13729 if (!((reg->var_off.mask | reg->var_off.value) & val)) 13730 return 0; 13731 break; 13732 case BPF_JGT: 13733 if (reg->umin_value > val) 13734 return 1; 13735 else if (reg->umax_value <= val) 13736 return 0; 13737 break; 13738 case BPF_JSGT: 13739 if (reg->smin_value > sval) 13740 return 1; 13741 else if (reg->smax_value <= sval) 13742 return 0; 13743 break; 13744 case BPF_JLT: 13745 if (reg->umax_value < val) 13746 return 1; 13747 else if (reg->umin_value >= val) 13748 return 0; 13749 break; 13750 case BPF_JSLT: 13751 if (reg->smax_value < sval) 13752 return 1; 13753 else if (reg->smin_value >= sval) 13754 return 0; 13755 break; 13756 case BPF_JGE: 13757 if (reg->umin_value >= val) 13758 return 1; 13759 else if (reg->umax_value < val) 13760 return 0; 13761 break; 13762 case BPF_JSGE: 13763 if (reg->smin_value >= sval) 13764 return 1; 13765 else if (reg->smax_value < sval) 13766 return 0; 13767 break; 13768 case BPF_JLE: 13769 if (reg->umax_value <= val) 13770 return 1; 13771 else if (reg->umin_value > val) 13772 return 0; 13773 break; 13774 case BPF_JSLE: 13775 if (reg->smax_value <= sval) 13776 return 1; 13777 else if (reg->smin_value > sval) 13778 return 0; 13779 break; 13780 } 13781 13782 return -1; 13783 } 13784 13785 /* compute branch direction of the expression "if (reg opcode val) goto target;" 13786 * and return: 13787 * 1 - branch will be taken and "goto target" will be executed 13788 * 0 - branch will not be taken and fall-through to next insn 13789 * -1 - unknown. Example: "if (reg < 5)" is unknown when register value 13790 * range [0,10] 13791 */ 13792 static int is_branch_taken(struct bpf_reg_state *reg, u64 val, u8 opcode, 13793 bool is_jmp32) 13794 { 13795 if (__is_pointer_value(false, reg)) { 13796 if (!reg_not_null(reg)) 13797 return -1; 13798 13799 /* If pointer is valid tests against zero will fail so we can 13800 * use this to direct branch taken. 13801 */ 13802 if (val != 0) 13803 return -1; 13804 13805 switch (opcode) { 13806 case BPF_JEQ: 13807 return 0; 13808 case BPF_JNE: 13809 return 1; 13810 default: 13811 return -1; 13812 } 13813 } 13814 13815 if (is_jmp32) 13816 return is_branch32_taken(reg, val, opcode); 13817 return is_branch64_taken(reg, val, opcode); 13818 } 13819 13820 static int flip_opcode(u32 opcode) 13821 { 13822 /* How can we transform "a <op> b" into "b <op> a"? */ 13823 static const u8 opcode_flip[16] = { 13824 /* these stay the same */ 13825 [BPF_JEQ >> 4] = BPF_JEQ, 13826 [BPF_JNE >> 4] = BPF_JNE, 13827 [BPF_JSET >> 4] = BPF_JSET, 13828 /* these swap "lesser" and "greater" (L and G in the opcodes) */ 13829 [BPF_JGE >> 4] = BPF_JLE, 13830 [BPF_JGT >> 4] = BPF_JLT, 13831 [BPF_JLE >> 4] = BPF_JGE, 13832 [BPF_JLT >> 4] = BPF_JGT, 13833 [BPF_JSGE >> 4] = BPF_JSLE, 13834 [BPF_JSGT >> 4] = BPF_JSLT, 13835 [BPF_JSLE >> 4] = BPF_JSGE, 13836 [BPF_JSLT >> 4] = BPF_JSGT 13837 }; 13838 return opcode_flip[opcode >> 4]; 13839 } 13840 13841 static int is_pkt_ptr_branch_taken(struct bpf_reg_state *dst_reg, 13842 struct bpf_reg_state *src_reg, 13843 u8 opcode) 13844 { 13845 struct bpf_reg_state *pkt; 13846 13847 if (src_reg->type == PTR_TO_PACKET_END) { 13848 pkt = dst_reg; 13849 } else if (dst_reg->type == PTR_TO_PACKET_END) { 13850 pkt = src_reg; 13851 opcode = flip_opcode(opcode); 13852 } else { 13853 return -1; 13854 } 13855 13856 if (pkt->range >= 0) 13857 return -1; 13858 13859 switch (opcode) { 13860 case BPF_JLE: 13861 /* pkt <= pkt_end */ 13862 fallthrough; 13863 case BPF_JGT: 13864 /* pkt > pkt_end */ 13865 if (pkt->range == BEYOND_PKT_END) 13866 /* pkt has at last one extra byte beyond pkt_end */ 13867 return opcode == BPF_JGT; 13868 break; 13869 case BPF_JLT: 13870 /* pkt < pkt_end */ 13871 fallthrough; 13872 case BPF_JGE: 13873 /* pkt >= pkt_end */ 13874 if (pkt->range == BEYOND_PKT_END || pkt->range == AT_PKT_END) 13875 return opcode == BPF_JGE; 13876 break; 13877 } 13878 return -1; 13879 } 13880 13881 /* Adjusts the register min/max values in the case that the dst_reg is the 13882 * variable register that we are working on, and src_reg is a constant or we're 13883 * simply doing a BPF_K check. 13884 * In JEQ/JNE cases we also adjust the var_off values. 13885 */ 13886 static void reg_set_min_max(struct bpf_reg_state *true_reg, 13887 struct bpf_reg_state *false_reg, 13888 u64 val, u32 val32, 13889 u8 opcode, bool is_jmp32) 13890 { 13891 struct tnum false_32off = tnum_subreg(false_reg->var_off); 13892 struct tnum false_64off = false_reg->var_off; 13893 struct tnum true_32off = tnum_subreg(true_reg->var_off); 13894 struct tnum true_64off = true_reg->var_off; 13895 s64 sval = (s64)val; 13896 s32 sval32 = (s32)val32; 13897 13898 /* If the dst_reg is a pointer, we can't learn anything about its 13899 * variable offset from the compare (unless src_reg were a pointer into 13900 * the same object, but we don't bother with that. 13901 * Since false_reg and true_reg have the same type by construction, we 13902 * only need to check one of them for pointerness. 13903 */ 13904 if (__is_pointer_value(false, false_reg)) 13905 return; 13906 13907 switch (opcode) { 13908 /* JEQ/JNE comparison doesn't change the register equivalence. 13909 * 13910 * r1 = r2; 13911 * if (r1 == 42) goto label; 13912 * ... 13913 * label: // here both r1 and r2 are known to be 42. 13914 * 13915 * Hence when marking register as known preserve it's ID. 13916 */ 13917 case BPF_JEQ: 13918 if (is_jmp32) { 13919 __mark_reg32_known(true_reg, val32); 13920 true_32off = tnum_subreg(true_reg->var_off); 13921 } else { 13922 ___mark_reg_known(true_reg, val); 13923 true_64off = true_reg->var_off; 13924 } 13925 break; 13926 case BPF_JNE: 13927 if (is_jmp32) { 13928 __mark_reg32_known(false_reg, val32); 13929 false_32off = tnum_subreg(false_reg->var_off); 13930 } else { 13931 ___mark_reg_known(false_reg, val); 13932 false_64off = false_reg->var_off; 13933 } 13934 break; 13935 case BPF_JSET: 13936 if (is_jmp32) { 13937 false_32off = tnum_and(false_32off, tnum_const(~val32)); 13938 if (is_power_of_2(val32)) 13939 true_32off = tnum_or(true_32off, 13940 tnum_const(val32)); 13941 } else { 13942 false_64off = tnum_and(false_64off, tnum_const(~val)); 13943 if (is_power_of_2(val)) 13944 true_64off = tnum_or(true_64off, 13945 tnum_const(val)); 13946 } 13947 break; 13948 case BPF_JGE: 13949 case BPF_JGT: 13950 { 13951 if (is_jmp32) { 13952 u32 false_umax = opcode == BPF_JGT ? val32 : val32 - 1; 13953 u32 true_umin = opcode == BPF_JGT ? val32 + 1 : val32; 13954 13955 false_reg->u32_max_value = min(false_reg->u32_max_value, 13956 false_umax); 13957 true_reg->u32_min_value = max(true_reg->u32_min_value, 13958 true_umin); 13959 } else { 13960 u64 false_umax = opcode == BPF_JGT ? val : val - 1; 13961 u64 true_umin = opcode == BPF_JGT ? val + 1 : val; 13962 13963 false_reg->umax_value = min(false_reg->umax_value, false_umax); 13964 true_reg->umin_value = max(true_reg->umin_value, true_umin); 13965 } 13966 break; 13967 } 13968 case BPF_JSGE: 13969 case BPF_JSGT: 13970 { 13971 if (is_jmp32) { 13972 s32 false_smax = opcode == BPF_JSGT ? sval32 : sval32 - 1; 13973 s32 true_smin = opcode == BPF_JSGT ? sval32 + 1 : sval32; 13974 13975 false_reg->s32_max_value = min(false_reg->s32_max_value, false_smax); 13976 true_reg->s32_min_value = max(true_reg->s32_min_value, true_smin); 13977 } else { 13978 s64 false_smax = opcode == BPF_JSGT ? sval : sval - 1; 13979 s64 true_smin = opcode == BPF_JSGT ? sval + 1 : sval; 13980 13981 false_reg->smax_value = min(false_reg->smax_value, false_smax); 13982 true_reg->smin_value = max(true_reg->smin_value, true_smin); 13983 } 13984 break; 13985 } 13986 case BPF_JLE: 13987 case BPF_JLT: 13988 { 13989 if (is_jmp32) { 13990 u32 false_umin = opcode == BPF_JLT ? val32 : val32 + 1; 13991 u32 true_umax = opcode == BPF_JLT ? val32 - 1 : val32; 13992 13993 false_reg->u32_min_value = max(false_reg->u32_min_value, 13994 false_umin); 13995 true_reg->u32_max_value = min(true_reg->u32_max_value, 13996 true_umax); 13997 } else { 13998 u64 false_umin = opcode == BPF_JLT ? val : val + 1; 13999 u64 true_umax = opcode == BPF_JLT ? val - 1 : val; 14000 14001 false_reg->umin_value = max(false_reg->umin_value, false_umin); 14002 true_reg->umax_value = min(true_reg->umax_value, true_umax); 14003 } 14004 break; 14005 } 14006 case BPF_JSLE: 14007 case BPF_JSLT: 14008 { 14009 if (is_jmp32) { 14010 s32 false_smin = opcode == BPF_JSLT ? sval32 : sval32 + 1; 14011 s32 true_smax = opcode == BPF_JSLT ? sval32 - 1 : sval32; 14012 14013 false_reg->s32_min_value = max(false_reg->s32_min_value, false_smin); 14014 true_reg->s32_max_value = min(true_reg->s32_max_value, true_smax); 14015 } else { 14016 s64 false_smin = opcode == BPF_JSLT ? sval : sval + 1; 14017 s64 true_smax = opcode == BPF_JSLT ? sval - 1 : sval; 14018 14019 false_reg->smin_value = max(false_reg->smin_value, false_smin); 14020 true_reg->smax_value = min(true_reg->smax_value, true_smax); 14021 } 14022 break; 14023 } 14024 default: 14025 return; 14026 } 14027 14028 if (is_jmp32) { 14029 false_reg->var_off = tnum_or(tnum_clear_subreg(false_64off), 14030 tnum_subreg(false_32off)); 14031 true_reg->var_off = tnum_or(tnum_clear_subreg(true_64off), 14032 tnum_subreg(true_32off)); 14033 __reg_combine_32_into_64(false_reg); 14034 __reg_combine_32_into_64(true_reg); 14035 } else { 14036 false_reg->var_off = false_64off; 14037 true_reg->var_off = true_64off; 14038 __reg_combine_64_into_32(false_reg); 14039 __reg_combine_64_into_32(true_reg); 14040 } 14041 } 14042 14043 /* Same as above, but for the case that dst_reg holds a constant and src_reg is 14044 * the variable reg. 14045 */ 14046 static void reg_set_min_max_inv(struct bpf_reg_state *true_reg, 14047 struct bpf_reg_state *false_reg, 14048 u64 val, u32 val32, 14049 u8 opcode, bool is_jmp32) 14050 { 14051 opcode = flip_opcode(opcode); 14052 /* This uses zero as "not present in table"; luckily the zero opcode, 14053 * BPF_JA, can't get here. 14054 */ 14055 if (opcode) 14056 reg_set_min_max(true_reg, false_reg, val, val32, opcode, is_jmp32); 14057 } 14058 14059 /* Regs are known to be equal, so intersect their min/max/var_off */ 14060 static void __reg_combine_min_max(struct bpf_reg_state *src_reg, 14061 struct bpf_reg_state *dst_reg) 14062 { 14063 src_reg->umin_value = dst_reg->umin_value = max(src_reg->umin_value, 14064 dst_reg->umin_value); 14065 src_reg->umax_value = dst_reg->umax_value = min(src_reg->umax_value, 14066 dst_reg->umax_value); 14067 src_reg->smin_value = dst_reg->smin_value = max(src_reg->smin_value, 14068 dst_reg->smin_value); 14069 src_reg->smax_value = dst_reg->smax_value = min(src_reg->smax_value, 14070 dst_reg->smax_value); 14071 src_reg->var_off = dst_reg->var_off = tnum_intersect(src_reg->var_off, 14072 dst_reg->var_off); 14073 reg_bounds_sync(src_reg); 14074 reg_bounds_sync(dst_reg); 14075 } 14076 14077 static void reg_combine_min_max(struct bpf_reg_state *true_src, 14078 struct bpf_reg_state *true_dst, 14079 struct bpf_reg_state *false_src, 14080 struct bpf_reg_state *false_dst, 14081 u8 opcode) 14082 { 14083 switch (opcode) { 14084 case BPF_JEQ: 14085 __reg_combine_min_max(true_src, true_dst); 14086 break; 14087 case BPF_JNE: 14088 __reg_combine_min_max(false_src, false_dst); 14089 break; 14090 } 14091 } 14092 14093 static void mark_ptr_or_null_reg(struct bpf_func_state *state, 14094 struct bpf_reg_state *reg, u32 id, 14095 bool is_null) 14096 { 14097 if (type_may_be_null(reg->type) && reg->id == id && 14098 (is_rcu_reg(reg) || !WARN_ON_ONCE(!reg->id))) { 14099 /* Old offset (both fixed and variable parts) should have been 14100 * known-zero, because we don't allow pointer arithmetic on 14101 * pointers that might be NULL. If we see this happening, don't 14102 * convert the register. 14103 * 14104 * But in some cases, some helpers that return local kptrs 14105 * advance offset for the returned pointer. In those cases, it 14106 * is fine to expect to see reg->off. 14107 */ 14108 if (WARN_ON_ONCE(reg->smin_value || reg->smax_value || !tnum_equals_const(reg->var_off, 0))) 14109 return; 14110 if (!(type_is_ptr_alloc_obj(reg->type) || type_is_non_owning_ref(reg->type)) && 14111 WARN_ON_ONCE(reg->off)) 14112 return; 14113 14114 if (is_null) { 14115 reg->type = SCALAR_VALUE; 14116 /* We don't need id and ref_obj_id from this point 14117 * onwards anymore, thus we should better reset it, 14118 * so that state pruning has chances to take effect. 14119 */ 14120 reg->id = 0; 14121 reg->ref_obj_id = 0; 14122 14123 return; 14124 } 14125 14126 mark_ptr_not_null_reg(reg); 14127 14128 if (!reg_may_point_to_spin_lock(reg)) { 14129 /* For not-NULL ptr, reg->ref_obj_id will be reset 14130 * in release_reference(). 14131 * 14132 * reg->id is still used by spin_lock ptr. Other 14133 * than spin_lock ptr type, reg->id can be reset. 14134 */ 14135 reg->id = 0; 14136 } 14137 } 14138 } 14139 14140 /* The logic is similar to find_good_pkt_pointers(), both could eventually 14141 * be folded together at some point. 14142 */ 14143 static void mark_ptr_or_null_regs(struct bpf_verifier_state *vstate, u32 regno, 14144 bool is_null) 14145 { 14146 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 14147 struct bpf_reg_state *regs = state->regs, *reg; 14148 u32 ref_obj_id = regs[regno].ref_obj_id; 14149 u32 id = regs[regno].id; 14150 14151 if (ref_obj_id && ref_obj_id == id && is_null) 14152 /* regs[regno] is in the " == NULL" branch. 14153 * No one could have freed the reference state before 14154 * doing the NULL check. 14155 */ 14156 WARN_ON_ONCE(release_reference_state(state, id)); 14157 14158 bpf_for_each_reg_in_vstate(vstate, state, reg, ({ 14159 mark_ptr_or_null_reg(state, reg, id, is_null); 14160 })); 14161 } 14162 14163 static bool try_match_pkt_pointers(const struct bpf_insn *insn, 14164 struct bpf_reg_state *dst_reg, 14165 struct bpf_reg_state *src_reg, 14166 struct bpf_verifier_state *this_branch, 14167 struct bpf_verifier_state *other_branch) 14168 { 14169 if (BPF_SRC(insn->code) != BPF_X) 14170 return false; 14171 14172 /* Pointers are always 64-bit. */ 14173 if (BPF_CLASS(insn->code) == BPF_JMP32) 14174 return false; 14175 14176 switch (BPF_OP(insn->code)) { 14177 case BPF_JGT: 14178 if ((dst_reg->type == PTR_TO_PACKET && 14179 src_reg->type == PTR_TO_PACKET_END) || 14180 (dst_reg->type == PTR_TO_PACKET_META && 14181 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) { 14182 /* pkt_data' > pkt_end, pkt_meta' > pkt_data */ 14183 find_good_pkt_pointers(this_branch, dst_reg, 14184 dst_reg->type, false); 14185 mark_pkt_end(other_branch, insn->dst_reg, true); 14186 } else if ((dst_reg->type == PTR_TO_PACKET_END && 14187 src_reg->type == PTR_TO_PACKET) || 14188 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) && 14189 src_reg->type == PTR_TO_PACKET_META)) { 14190 /* pkt_end > pkt_data', pkt_data > pkt_meta' */ 14191 find_good_pkt_pointers(other_branch, src_reg, 14192 src_reg->type, true); 14193 mark_pkt_end(this_branch, insn->src_reg, false); 14194 } else { 14195 return false; 14196 } 14197 break; 14198 case BPF_JLT: 14199 if ((dst_reg->type == PTR_TO_PACKET && 14200 src_reg->type == PTR_TO_PACKET_END) || 14201 (dst_reg->type == PTR_TO_PACKET_META && 14202 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) { 14203 /* pkt_data' < pkt_end, pkt_meta' < pkt_data */ 14204 find_good_pkt_pointers(other_branch, dst_reg, 14205 dst_reg->type, true); 14206 mark_pkt_end(this_branch, insn->dst_reg, false); 14207 } else if ((dst_reg->type == PTR_TO_PACKET_END && 14208 src_reg->type == PTR_TO_PACKET) || 14209 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) && 14210 src_reg->type == PTR_TO_PACKET_META)) { 14211 /* pkt_end < pkt_data', pkt_data > pkt_meta' */ 14212 find_good_pkt_pointers(this_branch, src_reg, 14213 src_reg->type, false); 14214 mark_pkt_end(other_branch, insn->src_reg, true); 14215 } else { 14216 return false; 14217 } 14218 break; 14219 case BPF_JGE: 14220 if ((dst_reg->type == PTR_TO_PACKET && 14221 src_reg->type == PTR_TO_PACKET_END) || 14222 (dst_reg->type == PTR_TO_PACKET_META && 14223 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) { 14224 /* pkt_data' >= pkt_end, pkt_meta' >= pkt_data */ 14225 find_good_pkt_pointers(this_branch, dst_reg, 14226 dst_reg->type, true); 14227 mark_pkt_end(other_branch, insn->dst_reg, false); 14228 } else if ((dst_reg->type == PTR_TO_PACKET_END && 14229 src_reg->type == PTR_TO_PACKET) || 14230 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) && 14231 src_reg->type == PTR_TO_PACKET_META)) { 14232 /* pkt_end >= pkt_data', pkt_data >= pkt_meta' */ 14233 find_good_pkt_pointers(other_branch, src_reg, 14234 src_reg->type, false); 14235 mark_pkt_end(this_branch, insn->src_reg, true); 14236 } else { 14237 return false; 14238 } 14239 break; 14240 case BPF_JLE: 14241 if ((dst_reg->type == PTR_TO_PACKET && 14242 src_reg->type == PTR_TO_PACKET_END) || 14243 (dst_reg->type == PTR_TO_PACKET_META && 14244 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) { 14245 /* pkt_data' <= pkt_end, pkt_meta' <= pkt_data */ 14246 find_good_pkt_pointers(other_branch, dst_reg, 14247 dst_reg->type, false); 14248 mark_pkt_end(this_branch, insn->dst_reg, true); 14249 } else if ((dst_reg->type == PTR_TO_PACKET_END && 14250 src_reg->type == PTR_TO_PACKET) || 14251 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) && 14252 src_reg->type == PTR_TO_PACKET_META)) { 14253 /* pkt_end <= pkt_data', pkt_data <= pkt_meta' */ 14254 find_good_pkt_pointers(this_branch, src_reg, 14255 src_reg->type, true); 14256 mark_pkt_end(other_branch, insn->src_reg, false); 14257 } else { 14258 return false; 14259 } 14260 break; 14261 default: 14262 return false; 14263 } 14264 14265 return true; 14266 } 14267 14268 static void find_equal_scalars(struct bpf_verifier_state *vstate, 14269 struct bpf_reg_state *known_reg) 14270 { 14271 struct bpf_func_state *state; 14272 struct bpf_reg_state *reg; 14273 14274 bpf_for_each_reg_in_vstate(vstate, state, reg, ({ 14275 if (reg->type == SCALAR_VALUE && reg->id == known_reg->id) 14276 copy_register_state(reg, known_reg); 14277 })); 14278 } 14279 14280 static int check_cond_jmp_op(struct bpf_verifier_env *env, 14281 struct bpf_insn *insn, int *insn_idx) 14282 { 14283 struct bpf_verifier_state *this_branch = env->cur_state; 14284 struct bpf_verifier_state *other_branch; 14285 struct bpf_reg_state *regs = this_branch->frame[this_branch->curframe]->regs; 14286 struct bpf_reg_state *dst_reg, *other_branch_regs, *src_reg = NULL; 14287 struct bpf_reg_state *eq_branch_regs; 14288 u8 opcode = BPF_OP(insn->code); 14289 bool is_jmp32; 14290 int pred = -1; 14291 int err; 14292 14293 /* Only conditional jumps are expected to reach here. */ 14294 if (opcode == BPF_JA || opcode > BPF_JSLE) { 14295 verbose(env, "invalid BPF_JMP/JMP32 opcode %x\n", opcode); 14296 return -EINVAL; 14297 } 14298 14299 /* check src2 operand */ 14300 err = check_reg_arg(env, insn->dst_reg, SRC_OP); 14301 if (err) 14302 return err; 14303 14304 dst_reg = ®s[insn->dst_reg]; 14305 if (BPF_SRC(insn->code) == BPF_X) { 14306 if (insn->imm != 0) { 14307 verbose(env, "BPF_JMP/JMP32 uses reserved fields\n"); 14308 return -EINVAL; 14309 } 14310 14311 /* check src1 operand */ 14312 err = check_reg_arg(env, insn->src_reg, SRC_OP); 14313 if (err) 14314 return err; 14315 14316 src_reg = ®s[insn->src_reg]; 14317 if (!(reg_is_pkt_pointer_any(dst_reg) && reg_is_pkt_pointer_any(src_reg)) && 14318 is_pointer_value(env, insn->src_reg)) { 14319 verbose(env, "R%d pointer comparison prohibited\n", 14320 insn->src_reg); 14321 return -EACCES; 14322 } 14323 } else { 14324 if (insn->src_reg != BPF_REG_0) { 14325 verbose(env, "BPF_JMP/JMP32 uses reserved fields\n"); 14326 return -EINVAL; 14327 } 14328 } 14329 14330 is_jmp32 = BPF_CLASS(insn->code) == BPF_JMP32; 14331 14332 if (BPF_SRC(insn->code) == BPF_K) { 14333 pred = is_branch_taken(dst_reg, insn->imm, opcode, is_jmp32); 14334 } else if (src_reg->type == SCALAR_VALUE && 14335 is_jmp32 && tnum_is_const(tnum_subreg(src_reg->var_off))) { 14336 pred = is_branch_taken(dst_reg, 14337 tnum_subreg(src_reg->var_off).value, 14338 opcode, 14339 is_jmp32); 14340 } else if (src_reg->type == SCALAR_VALUE && 14341 !is_jmp32 && tnum_is_const(src_reg->var_off)) { 14342 pred = is_branch_taken(dst_reg, 14343 src_reg->var_off.value, 14344 opcode, 14345 is_jmp32); 14346 } else if (dst_reg->type == SCALAR_VALUE && 14347 is_jmp32 && tnum_is_const(tnum_subreg(dst_reg->var_off))) { 14348 pred = is_branch_taken(src_reg, 14349 tnum_subreg(dst_reg->var_off).value, 14350 flip_opcode(opcode), 14351 is_jmp32); 14352 } else if (dst_reg->type == SCALAR_VALUE && 14353 !is_jmp32 && tnum_is_const(dst_reg->var_off)) { 14354 pred = is_branch_taken(src_reg, 14355 dst_reg->var_off.value, 14356 flip_opcode(opcode), 14357 is_jmp32); 14358 } else if (reg_is_pkt_pointer_any(dst_reg) && 14359 reg_is_pkt_pointer_any(src_reg) && 14360 !is_jmp32) { 14361 pred = is_pkt_ptr_branch_taken(dst_reg, src_reg, opcode); 14362 } 14363 14364 if (pred >= 0) { 14365 /* If we get here with a dst_reg pointer type it is because 14366 * above is_branch_taken() special cased the 0 comparison. 14367 */ 14368 if (!__is_pointer_value(false, dst_reg)) 14369 err = mark_chain_precision(env, insn->dst_reg); 14370 if (BPF_SRC(insn->code) == BPF_X && !err && 14371 !__is_pointer_value(false, src_reg)) 14372 err = mark_chain_precision(env, insn->src_reg); 14373 if (err) 14374 return err; 14375 } 14376 14377 if (pred == 1) { 14378 /* Only follow the goto, ignore fall-through. If needed, push 14379 * the fall-through branch for simulation under speculative 14380 * execution. 14381 */ 14382 if (!env->bypass_spec_v1 && 14383 !sanitize_speculative_path(env, insn, *insn_idx + 1, 14384 *insn_idx)) 14385 return -EFAULT; 14386 *insn_idx += insn->off; 14387 return 0; 14388 } else if (pred == 0) { 14389 /* Only follow the fall-through branch, since that's where the 14390 * program will go. If needed, push the goto branch for 14391 * simulation under speculative execution. 14392 */ 14393 if (!env->bypass_spec_v1 && 14394 !sanitize_speculative_path(env, insn, 14395 *insn_idx + insn->off + 1, 14396 *insn_idx)) 14397 return -EFAULT; 14398 return 0; 14399 } 14400 14401 other_branch = push_stack(env, *insn_idx + insn->off + 1, *insn_idx, 14402 false); 14403 if (!other_branch) 14404 return -EFAULT; 14405 other_branch_regs = other_branch->frame[other_branch->curframe]->regs; 14406 14407 /* detect if we are comparing against a constant value so we can adjust 14408 * our min/max values for our dst register. 14409 * this is only legit if both are scalars (or pointers to the same 14410 * object, I suppose, see the PTR_MAYBE_NULL related if block below), 14411 * because otherwise the different base pointers mean the offsets aren't 14412 * comparable. 14413 */ 14414 if (BPF_SRC(insn->code) == BPF_X) { 14415 struct bpf_reg_state *src_reg = ®s[insn->src_reg]; 14416 14417 if (dst_reg->type == SCALAR_VALUE && 14418 src_reg->type == SCALAR_VALUE) { 14419 if (tnum_is_const(src_reg->var_off) || 14420 (is_jmp32 && 14421 tnum_is_const(tnum_subreg(src_reg->var_off)))) 14422 reg_set_min_max(&other_branch_regs[insn->dst_reg], 14423 dst_reg, 14424 src_reg->var_off.value, 14425 tnum_subreg(src_reg->var_off).value, 14426 opcode, is_jmp32); 14427 else if (tnum_is_const(dst_reg->var_off) || 14428 (is_jmp32 && 14429 tnum_is_const(tnum_subreg(dst_reg->var_off)))) 14430 reg_set_min_max_inv(&other_branch_regs[insn->src_reg], 14431 src_reg, 14432 dst_reg->var_off.value, 14433 tnum_subreg(dst_reg->var_off).value, 14434 opcode, is_jmp32); 14435 else if (!is_jmp32 && 14436 (opcode == BPF_JEQ || opcode == BPF_JNE)) 14437 /* Comparing for equality, we can combine knowledge */ 14438 reg_combine_min_max(&other_branch_regs[insn->src_reg], 14439 &other_branch_regs[insn->dst_reg], 14440 src_reg, dst_reg, opcode); 14441 if (src_reg->id && 14442 !WARN_ON_ONCE(src_reg->id != other_branch_regs[insn->src_reg].id)) { 14443 find_equal_scalars(this_branch, src_reg); 14444 find_equal_scalars(other_branch, &other_branch_regs[insn->src_reg]); 14445 } 14446 14447 } 14448 } else if (dst_reg->type == SCALAR_VALUE) { 14449 reg_set_min_max(&other_branch_regs[insn->dst_reg], 14450 dst_reg, insn->imm, (u32)insn->imm, 14451 opcode, is_jmp32); 14452 } 14453 14454 if (dst_reg->type == SCALAR_VALUE && dst_reg->id && 14455 !WARN_ON_ONCE(dst_reg->id != other_branch_regs[insn->dst_reg].id)) { 14456 find_equal_scalars(this_branch, dst_reg); 14457 find_equal_scalars(other_branch, &other_branch_regs[insn->dst_reg]); 14458 } 14459 14460 /* if one pointer register is compared to another pointer 14461 * register check if PTR_MAYBE_NULL could be lifted. 14462 * E.g. register A - maybe null 14463 * register B - not null 14464 * for JNE A, B, ... - A is not null in the false branch; 14465 * for JEQ A, B, ... - A is not null in the true branch. 14466 * 14467 * Since PTR_TO_BTF_ID points to a kernel struct that does 14468 * not need to be null checked by the BPF program, i.e., 14469 * could be null even without PTR_MAYBE_NULL marking, so 14470 * only propagate nullness when neither reg is that type. 14471 */ 14472 if (!is_jmp32 && BPF_SRC(insn->code) == BPF_X && 14473 __is_pointer_value(false, src_reg) && __is_pointer_value(false, dst_reg) && 14474 type_may_be_null(src_reg->type) != type_may_be_null(dst_reg->type) && 14475 base_type(src_reg->type) != PTR_TO_BTF_ID && 14476 base_type(dst_reg->type) != PTR_TO_BTF_ID) { 14477 eq_branch_regs = NULL; 14478 switch (opcode) { 14479 case BPF_JEQ: 14480 eq_branch_regs = other_branch_regs; 14481 break; 14482 case BPF_JNE: 14483 eq_branch_regs = regs; 14484 break; 14485 default: 14486 /* do nothing */ 14487 break; 14488 } 14489 if (eq_branch_regs) { 14490 if (type_may_be_null(src_reg->type)) 14491 mark_ptr_not_null_reg(&eq_branch_regs[insn->src_reg]); 14492 else 14493 mark_ptr_not_null_reg(&eq_branch_regs[insn->dst_reg]); 14494 } 14495 } 14496 14497 /* detect if R == 0 where R is returned from bpf_map_lookup_elem(). 14498 * NOTE: these optimizations below are related with pointer comparison 14499 * which will never be JMP32. 14500 */ 14501 if (!is_jmp32 && BPF_SRC(insn->code) == BPF_K && 14502 insn->imm == 0 && (opcode == BPF_JEQ || opcode == BPF_JNE) && 14503 type_may_be_null(dst_reg->type)) { 14504 /* Mark all identical registers in each branch as either 14505 * safe or unknown depending R == 0 or R != 0 conditional. 14506 */ 14507 mark_ptr_or_null_regs(this_branch, insn->dst_reg, 14508 opcode == BPF_JNE); 14509 mark_ptr_or_null_regs(other_branch, insn->dst_reg, 14510 opcode == BPF_JEQ); 14511 } else if (!try_match_pkt_pointers(insn, dst_reg, ®s[insn->src_reg], 14512 this_branch, other_branch) && 14513 is_pointer_value(env, insn->dst_reg)) { 14514 verbose(env, "R%d pointer comparison prohibited\n", 14515 insn->dst_reg); 14516 return -EACCES; 14517 } 14518 if (env->log.level & BPF_LOG_LEVEL) 14519 print_insn_state(env, this_branch->frame[this_branch->curframe]); 14520 return 0; 14521 } 14522 14523 /* verify BPF_LD_IMM64 instruction */ 14524 static int check_ld_imm(struct bpf_verifier_env *env, struct bpf_insn *insn) 14525 { 14526 struct bpf_insn_aux_data *aux = cur_aux(env); 14527 struct bpf_reg_state *regs = cur_regs(env); 14528 struct bpf_reg_state *dst_reg; 14529 struct bpf_map *map; 14530 int err; 14531 14532 if (BPF_SIZE(insn->code) != BPF_DW) { 14533 verbose(env, "invalid BPF_LD_IMM insn\n"); 14534 return -EINVAL; 14535 } 14536 if (insn->off != 0) { 14537 verbose(env, "BPF_LD_IMM64 uses reserved fields\n"); 14538 return -EINVAL; 14539 } 14540 14541 err = check_reg_arg(env, insn->dst_reg, DST_OP); 14542 if (err) 14543 return err; 14544 14545 dst_reg = ®s[insn->dst_reg]; 14546 if (insn->src_reg == 0) { 14547 u64 imm = ((u64)(insn + 1)->imm << 32) | (u32)insn->imm; 14548 14549 dst_reg->type = SCALAR_VALUE; 14550 __mark_reg_known(®s[insn->dst_reg], imm); 14551 return 0; 14552 } 14553 14554 /* All special src_reg cases are listed below. From this point onwards 14555 * we either succeed and assign a corresponding dst_reg->type after 14556 * zeroing the offset, or fail and reject the program. 14557 */ 14558 mark_reg_known_zero(env, regs, insn->dst_reg); 14559 14560 if (insn->src_reg == BPF_PSEUDO_BTF_ID) { 14561 dst_reg->type = aux->btf_var.reg_type; 14562 switch (base_type(dst_reg->type)) { 14563 case PTR_TO_MEM: 14564 dst_reg->mem_size = aux->btf_var.mem_size; 14565 break; 14566 case PTR_TO_BTF_ID: 14567 dst_reg->btf = aux->btf_var.btf; 14568 dst_reg->btf_id = aux->btf_var.btf_id; 14569 break; 14570 default: 14571 verbose(env, "bpf verifier is misconfigured\n"); 14572 return -EFAULT; 14573 } 14574 return 0; 14575 } 14576 14577 if (insn->src_reg == BPF_PSEUDO_FUNC) { 14578 struct bpf_prog_aux *aux = env->prog->aux; 14579 u32 subprogno = find_subprog(env, 14580 env->insn_idx + insn->imm + 1); 14581 14582 if (!aux->func_info) { 14583 verbose(env, "missing btf func_info\n"); 14584 return -EINVAL; 14585 } 14586 if (aux->func_info_aux[subprogno].linkage != BTF_FUNC_STATIC) { 14587 verbose(env, "callback function not static\n"); 14588 return -EINVAL; 14589 } 14590 14591 dst_reg->type = PTR_TO_FUNC; 14592 dst_reg->subprogno = subprogno; 14593 return 0; 14594 } 14595 14596 map = env->used_maps[aux->map_index]; 14597 dst_reg->map_ptr = map; 14598 14599 if (insn->src_reg == BPF_PSEUDO_MAP_VALUE || 14600 insn->src_reg == BPF_PSEUDO_MAP_IDX_VALUE) { 14601 dst_reg->type = PTR_TO_MAP_VALUE; 14602 dst_reg->off = aux->map_off; 14603 WARN_ON_ONCE(map->max_entries != 1); 14604 /* We want reg->id to be same (0) as map_value is not distinct */ 14605 } else if (insn->src_reg == BPF_PSEUDO_MAP_FD || 14606 insn->src_reg == BPF_PSEUDO_MAP_IDX) { 14607 dst_reg->type = CONST_PTR_TO_MAP; 14608 } else { 14609 verbose(env, "bpf verifier is misconfigured\n"); 14610 return -EINVAL; 14611 } 14612 14613 return 0; 14614 } 14615 14616 static bool may_access_skb(enum bpf_prog_type type) 14617 { 14618 switch (type) { 14619 case BPF_PROG_TYPE_SOCKET_FILTER: 14620 case BPF_PROG_TYPE_SCHED_CLS: 14621 case BPF_PROG_TYPE_SCHED_ACT: 14622 return true; 14623 default: 14624 return false; 14625 } 14626 } 14627 14628 /* verify safety of LD_ABS|LD_IND instructions: 14629 * - they can only appear in the programs where ctx == skb 14630 * - since they are wrappers of function calls, they scratch R1-R5 registers, 14631 * preserve R6-R9, and store return value into R0 14632 * 14633 * Implicit input: 14634 * ctx == skb == R6 == CTX 14635 * 14636 * Explicit input: 14637 * SRC == any register 14638 * IMM == 32-bit immediate 14639 * 14640 * Output: 14641 * R0 - 8/16/32-bit skb data converted to cpu endianness 14642 */ 14643 static int check_ld_abs(struct bpf_verifier_env *env, struct bpf_insn *insn) 14644 { 14645 struct bpf_reg_state *regs = cur_regs(env); 14646 static const int ctx_reg = BPF_REG_6; 14647 u8 mode = BPF_MODE(insn->code); 14648 int i, err; 14649 14650 if (!may_access_skb(resolve_prog_type(env->prog))) { 14651 verbose(env, "BPF_LD_[ABS|IND] instructions not allowed for this program type\n"); 14652 return -EINVAL; 14653 } 14654 14655 if (!env->ops->gen_ld_abs) { 14656 verbose(env, "bpf verifier is misconfigured\n"); 14657 return -EINVAL; 14658 } 14659 14660 if (insn->dst_reg != BPF_REG_0 || insn->off != 0 || 14661 BPF_SIZE(insn->code) == BPF_DW || 14662 (mode == BPF_ABS && insn->src_reg != BPF_REG_0)) { 14663 verbose(env, "BPF_LD_[ABS|IND] uses reserved fields\n"); 14664 return -EINVAL; 14665 } 14666 14667 /* check whether implicit source operand (register R6) is readable */ 14668 err = check_reg_arg(env, ctx_reg, SRC_OP); 14669 if (err) 14670 return err; 14671 14672 /* Disallow usage of BPF_LD_[ABS|IND] with reference tracking, as 14673 * gen_ld_abs() may terminate the program at runtime, leading to 14674 * reference leak. 14675 */ 14676 err = check_reference_leak(env, false); 14677 if (err) { 14678 verbose(env, "BPF_LD_[ABS|IND] cannot be mixed with socket references\n"); 14679 return err; 14680 } 14681 14682 if (env->cur_state->active_lock.ptr) { 14683 verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_spin_lock-ed region\n"); 14684 return -EINVAL; 14685 } 14686 14687 if (env->cur_state->active_rcu_lock) { 14688 verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_rcu_read_lock-ed region\n"); 14689 return -EINVAL; 14690 } 14691 14692 if (regs[ctx_reg].type != PTR_TO_CTX) { 14693 verbose(env, 14694 "at the time of BPF_LD_ABS|IND R6 != pointer to skb\n"); 14695 return -EINVAL; 14696 } 14697 14698 if (mode == BPF_IND) { 14699 /* check explicit source operand */ 14700 err = check_reg_arg(env, insn->src_reg, SRC_OP); 14701 if (err) 14702 return err; 14703 } 14704 14705 err = check_ptr_off_reg(env, ®s[ctx_reg], ctx_reg); 14706 if (err < 0) 14707 return err; 14708 14709 /* reset caller saved regs to unreadable */ 14710 for (i = 0; i < CALLER_SAVED_REGS; i++) { 14711 mark_reg_not_init(env, regs, caller_saved[i]); 14712 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK); 14713 } 14714 14715 /* mark destination R0 register as readable, since it contains 14716 * the value fetched from the packet. 14717 * Already marked as written above. 14718 */ 14719 mark_reg_unknown(env, regs, BPF_REG_0); 14720 /* ld_abs load up to 32-bit skb data. */ 14721 regs[BPF_REG_0].subreg_def = env->insn_idx + 1; 14722 return 0; 14723 } 14724 14725 static int check_return_code(struct bpf_verifier_env *env, int regno) 14726 { 14727 struct tnum enforce_attach_type_range = tnum_unknown; 14728 const struct bpf_prog *prog = env->prog; 14729 struct bpf_reg_state *reg; 14730 struct tnum range = tnum_range(0, 1); 14731 enum bpf_prog_type prog_type = resolve_prog_type(env->prog); 14732 int err; 14733 struct bpf_func_state *frame = env->cur_state->frame[0]; 14734 const bool is_subprog = frame->subprogno; 14735 14736 /* LSM and struct_ops func-ptr's return type could be "void" */ 14737 if (!is_subprog || frame->in_exception_callback_fn) { 14738 switch (prog_type) { 14739 case BPF_PROG_TYPE_LSM: 14740 if (prog->expected_attach_type == BPF_LSM_CGROUP) 14741 /* See below, can be 0 or 0-1 depending on hook. */ 14742 break; 14743 fallthrough; 14744 case BPF_PROG_TYPE_STRUCT_OPS: 14745 if (!prog->aux->attach_func_proto->type) 14746 return 0; 14747 break; 14748 default: 14749 break; 14750 } 14751 } 14752 14753 /* eBPF calling convention is such that R0 is used 14754 * to return the value from eBPF program. 14755 * Make sure that it's readable at this time 14756 * of bpf_exit, which means that program wrote 14757 * something into it earlier 14758 */ 14759 err = check_reg_arg(env, regno, SRC_OP); 14760 if (err) 14761 return err; 14762 14763 if (is_pointer_value(env, regno)) { 14764 verbose(env, "R%d leaks addr as return value\n", regno); 14765 return -EACCES; 14766 } 14767 14768 reg = cur_regs(env) + regno; 14769 14770 if (frame->in_async_callback_fn) { 14771 /* enforce return zero from async callbacks like timer */ 14772 if (reg->type != SCALAR_VALUE) { 14773 verbose(env, "In async callback the register R%d is not a known value (%s)\n", 14774 regno, reg_type_str(env, reg->type)); 14775 return -EINVAL; 14776 } 14777 14778 if (!tnum_in(tnum_const(0), reg->var_off)) { 14779 verbose_invalid_scalar(env, reg, &range, "async callback", "R0"); 14780 return -EINVAL; 14781 } 14782 return 0; 14783 } 14784 14785 if (is_subprog && !frame->in_exception_callback_fn) { 14786 if (reg->type != SCALAR_VALUE) { 14787 verbose(env, "At subprogram exit the register R%d is not a scalar value (%s)\n", 14788 regno, reg_type_str(env, reg->type)); 14789 return -EINVAL; 14790 } 14791 return 0; 14792 } 14793 14794 switch (prog_type) { 14795 case BPF_PROG_TYPE_CGROUP_SOCK_ADDR: 14796 if (env->prog->expected_attach_type == BPF_CGROUP_UDP4_RECVMSG || 14797 env->prog->expected_attach_type == BPF_CGROUP_UDP6_RECVMSG || 14798 env->prog->expected_attach_type == BPF_CGROUP_INET4_GETPEERNAME || 14799 env->prog->expected_attach_type == BPF_CGROUP_INET6_GETPEERNAME || 14800 env->prog->expected_attach_type == BPF_CGROUP_INET4_GETSOCKNAME || 14801 env->prog->expected_attach_type == BPF_CGROUP_INET6_GETSOCKNAME) 14802 range = tnum_range(1, 1); 14803 if (env->prog->expected_attach_type == BPF_CGROUP_INET4_BIND || 14804 env->prog->expected_attach_type == BPF_CGROUP_INET6_BIND) 14805 range = tnum_range(0, 3); 14806 break; 14807 case BPF_PROG_TYPE_CGROUP_SKB: 14808 if (env->prog->expected_attach_type == BPF_CGROUP_INET_EGRESS) { 14809 range = tnum_range(0, 3); 14810 enforce_attach_type_range = tnum_range(2, 3); 14811 } 14812 break; 14813 case BPF_PROG_TYPE_CGROUP_SOCK: 14814 case BPF_PROG_TYPE_SOCK_OPS: 14815 case BPF_PROG_TYPE_CGROUP_DEVICE: 14816 case BPF_PROG_TYPE_CGROUP_SYSCTL: 14817 case BPF_PROG_TYPE_CGROUP_SOCKOPT: 14818 break; 14819 case BPF_PROG_TYPE_RAW_TRACEPOINT: 14820 if (!env->prog->aux->attach_btf_id) 14821 return 0; 14822 range = tnum_const(0); 14823 break; 14824 case BPF_PROG_TYPE_TRACING: 14825 switch (env->prog->expected_attach_type) { 14826 case BPF_TRACE_FENTRY: 14827 case BPF_TRACE_FEXIT: 14828 range = tnum_const(0); 14829 break; 14830 case BPF_TRACE_RAW_TP: 14831 case BPF_MODIFY_RETURN: 14832 return 0; 14833 case BPF_TRACE_ITER: 14834 break; 14835 default: 14836 return -ENOTSUPP; 14837 } 14838 break; 14839 case BPF_PROG_TYPE_SK_LOOKUP: 14840 range = tnum_range(SK_DROP, SK_PASS); 14841 break; 14842 14843 case BPF_PROG_TYPE_LSM: 14844 if (env->prog->expected_attach_type != BPF_LSM_CGROUP) { 14845 /* Regular BPF_PROG_TYPE_LSM programs can return 14846 * any value. 14847 */ 14848 return 0; 14849 } 14850 if (!env->prog->aux->attach_func_proto->type) { 14851 /* Make sure programs that attach to void 14852 * hooks don't try to modify return value. 14853 */ 14854 range = tnum_range(1, 1); 14855 } 14856 break; 14857 14858 case BPF_PROG_TYPE_NETFILTER: 14859 range = tnum_range(NF_DROP, NF_ACCEPT); 14860 break; 14861 case BPF_PROG_TYPE_EXT: 14862 /* freplace program can return anything as its return value 14863 * depends on the to-be-replaced kernel func or bpf program. 14864 */ 14865 default: 14866 return 0; 14867 } 14868 14869 if (reg->type != SCALAR_VALUE) { 14870 verbose(env, "At program exit the register R%d is not a known value (%s)\n", 14871 regno, reg_type_str(env, reg->type)); 14872 return -EINVAL; 14873 } 14874 14875 if (!tnum_in(range, reg->var_off)) { 14876 verbose_invalid_scalar(env, reg, &range, "program exit", "R0"); 14877 if (prog->expected_attach_type == BPF_LSM_CGROUP && 14878 prog_type == BPF_PROG_TYPE_LSM && 14879 !prog->aux->attach_func_proto->type) 14880 verbose(env, "Note, BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n"); 14881 return -EINVAL; 14882 } 14883 14884 if (!tnum_is_unknown(enforce_attach_type_range) && 14885 tnum_in(enforce_attach_type_range, reg->var_off)) 14886 env->prog->enforce_expected_attach_type = 1; 14887 return 0; 14888 } 14889 14890 /* non-recursive DFS pseudo code 14891 * 1 procedure DFS-iterative(G,v): 14892 * 2 label v as discovered 14893 * 3 let S be a stack 14894 * 4 S.push(v) 14895 * 5 while S is not empty 14896 * 6 t <- S.peek() 14897 * 7 if t is what we're looking for: 14898 * 8 return t 14899 * 9 for all edges e in G.adjacentEdges(t) do 14900 * 10 if edge e is already labelled 14901 * 11 continue with the next edge 14902 * 12 w <- G.adjacentVertex(t,e) 14903 * 13 if vertex w is not discovered and not explored 14904 * 14 label e as tree-edge 14905 * 15 label w as discovered 14906 * 16 S.push(w) 14907 * 17 continue at 5 14908 * 18 else if vertex w is discovered 14909 * 19 label e as back-edge 14910 * 20 else 14911 * 21 // vertex w is explored 14912 * 22 label e as forward- or cross-edge 14913 * 23 label t as explored 14914 * 24 S.pop() 14915 * 14916 * convention: 14917 * 0x10 - discovered 14918 * 0x11 - discovered and fall-through edge labelled 14919 * 0x12 - discovered and fall-through and branch edges labelled 14920 * 0x20 - explored 14921 */ 14922 14923 enum { 14924 DISCOVERED = 0x10, 14925 EXPLORED = 0x20, 14926 FALLTHROUGH = 1, 14927 BRANCH = 2, 14928 }; 14929 14930 static u32 state_htab_size(struct bpf_verifier_env *env) 14931 { 14932 return env->prog->len; 14933 } 14934 14935 static struct bpf_verifier_state_list **explored_state( 14936 struct bpf_verifier_env *env, 14937 int idx) 14938 { 14939 struct bpf_verifier_state *cur = env->cur_state; 14940 struct bpf_func_state *state = cur->frame[cur->curframe]; 14941 14942 return &env->explored_states[(idx ^ state->callsite) % state_htab_size(env)]; 14943 } 14944 14945 static void mark_prune_point(struct bpf_verifier_env *env, int idx) 14946 { 14947 env->insn_aux_data[idx].prune_point = true; 14948 } 14949 14950 static bool is_prune_point(struct bpf_verifier_env *env, int insn_idx) 14951 { 14952 return env->insn_aux_data[insn_idx].prune_point; 14953 } 14954 14955 static void mark_force_checkpoint(struct bpf_verifier_env *env, int idx) 14956 { 14957 env->insn_aux_data[idx].force_checkpoint = true; 14958 } 14959 14960 static bool is_force_checkpoint(struct bpf_verifier_env *env, int insn_idx) 14961 { 14962 return env->insn_aux_data[insn_idx].force_checkpoint; 14963 } 14964 14965 14966 enum { 14967 DONE_EXPLORING = 0, 14968 KEEP_EXPLORING = 1, 14969 }; 14970 14971 /* t, w, e - match pseudo-code above: 14972 * t - index of current instruction 14973 * w - next instruction 14974 * e - edge 14975 */ 14976 static int push_insn(int t, int w, int e, struct bpf_verifier_env *env, 14977 bool loop_ok) 14978 { 14979 int *insn_stack = env->cfg.insn_stack; 14980 int *insn_state = env->cfg.insn_state; 14981 14982 if (e == FALLTHROUGH && insn_state[t] >= (DISCOVERED | FALLTHROUGH)) 14983 return DONE_EXPLORING; 14984 14985 if (e == BRANCH && insn_state[t] >= (DISCOVERED | BRANCH)) 14986 return DONE_EXPLORING; 14987 14988 if (w < 0 || w >= env->prog->len) { 14989 verbose_linfo(env, t, "%d: ", t); 14990 verbose(env, "jump out of range from insn %d to %d\n", t, w); 14991 return -EINVAL; 14992 } 14993 14994 if (e == BRANCH) { 14995 /* mark branch target for state pruning */ 14996 mark_prune_point(env, w); 14997 mark_jmp_point(env, w); 14998 } 14999 15000 if (insn_state[w] == 0) { 15001 /* tree-edge */ 15002 insn_state[t] = DISCOVERED | e; 15003 insn_state[w] = DISCOVERED; 15004 if (env->cfg.cur_stack >= env->prog->len) 15005 return -E2BIG; 15006 insn_stack[env->cfg.cur_stack++] = w; 15007 return KEEP_EXPLORING; 15008 } else if ((insn_state[w] & 0xF0) == DISCOVERED) { 15009 if (loop_ok && env->bpf_capable) 15010 return DONE_EXPLORING; 15011 verbose_linfo(env, t, "%d: ", t); 15012 verbose_linfo(env, w, "%d: ", w); 15013 verbose(env, "back-edge from insn %d to %d\n", t, w); 15014 return -EINVAL; 15015 } else if (insn_state[w] == EXPLORED) { 15016 /* forward- or cross-edge */ 15017 insn_state[t] = DISCOVERED | e; 15018 } else { 15019 verbose(env, "insn state internal bug\n"); 15020 return -EFAULT; 15021 } 15022 return DONE_EXPLORING; 15023 } 15024 15025 static int visit_func_call_insn(int t, struct bpf_insn *insns, 15026 struct bpf_verifier_env *env, 15027 bool visit_callee) 15028 { 15029 int ret; 15030 15031 ret = push_insn(t, t + 1, FALLTHROUGH, env, false); 15032 if (ret) 15033 return ret; 15034 15035 mark_prune_point(env, t + 1); 15036 /* when we exit from subprog, we need to record non-linear history */ 15037 mark_jmp_point(env, t + 1); 15038 15039 if (visit_callee) { 15040 mark_prune_point(env, t); 15041 ret = push_insn(t, t + insns[t].imm + 1, BRANCH, env, 15042 /* It's ok to allow recursion from CFG point of 15043 * view. __check_func_call() will do the actual 15044 * check. 15045 */ 15046 bpf_pseudo_func(insns + t)); 15047 } 15048 return ret; 15049 } 15050 15051 /* Visits the instruction at index t and returns one of the following: 15052 * < 0 - an error occurred 15053 * DONE_EXPLORING - the instruction was fully explored 15054 * KEEP_EXPLORING - there is still work to be done before it is fully explored 15055 */ 15056 static int visit_insn(int t, struct bpf_verifier_env *env) 15057 { 15058 struct bpf_insn *insns = env->prog->insnsi, *insn = &insns[t]; 15059 int ret, off; 15060 15061 if (bpf_pseudo_func(insn)) 15062 return visit_func_call_insn(t, insns, env, true); 15063 15064 /* All non-branch instructions have a single fall-through edge. */ 15065 if (BPF_CLASS(insn->code) != BPF_JMP && 15066 BPF_CLASS(insn->code) != BPF_JMP32) 15067 return push_insn(t, t + 1, FALLTHROUGH, env, false); 15068 15069 switch (BPF_OP(insn->code)) { 15070 case BPF_EXIT: 15071 return DONE_EXPLORING; 15072 15073 case BPF_CALL: 15074 if (insn->src_reg == 0 && insn->imm == BPF_FUNC_timer_set_callback) 15075 /* Mark this call insn as a prune point to trigger 15076 * is_state_visited() check before call itself is 15077 * processed by __check_func_call(). Otherwise new 15078 * async state will be pushed for further exploration. 15079 */ 15080 mark_prune_point(env, t); 15081 if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) { 15082 struct bpf_kfunc_call_arg_meta meta; 15083 15084 ret = fetch_kfunc_meta(env, insn, &meta, NULL); 15085 if (ret == 0 && is_iter_next_kfunc(&meta)) { 15086 mark_prune_point(env, t); 15087 /* Checking and saving state checkpoints at iter_next() call 15088 * is crucial for fast convergence of open-coded iterator loop 15089 * logic, so we need to force it. If we don't do that, 15090 * is_state_visited() might skip saving a checkpoint, causing 15091 * unnecessarily long sequence of not checkpointed 15092 * instructions and jumps, leading to exhaustion of jump 15093 * history buffer, and potentially other undesired outcomes. 15094 * It is expected that with correct open-coded iterators 15095 * convergence will happen quickly, so we don't run a risk of 15096 * exhausting memory. 15097 */ 15098 mark_force_checkpoint(env, t); 15099 } 15100 } 15101 return visit_func_call_insn(t, insns, env, insn->src_reg == BPF_PSEUDO_CALL); 15102 15103 case BPF_JA: 15104 if (BPF_SRC(insn->code) != BPF_K) 15105 return -EINVAL; 15106 15107 if (BPF_CLASS(insn->code) == BPF_JMP) 15108 off = insn->off; 15109 else 15110 off = insn->imm; 15111 15112 /* unconditional jump with single edge */ 15113 ret = push_insn(t, t + off + 1, FALLTHROUGH, env, 15114 true); 15115 if (ret) 15116 return ret; 15117 15118 mark_prune_point(env, t + off + 1); 15119 mark_jmp_point(env, t + off + 1); 15120 15121 return ret; 15122 15123 default: 15124 /* conditional jump with two edges */ 15125 mark_prune_point(env, t); 15126 15127 ret = push_insn(t, t + 1, FALLTHROUGH, env, true); 15128 if (ret) 15129 return ret; 15130 15131 return push_insn(t, t + insn->off + 1, BRANCH, env, true); 15132 } 15133 } 15134 15135 /* non-recursive depth-first-search to detect loops in BPF program 15136 * loop == back-edge in directed graph 15137 */ 15138 static int check_cfg(struct bpf_verifier_env *env) 15139 { 15140 int insn_cnt = env->prog->len; 15141 int *insn_stack, *insn_state; 15142 int ex_insn_beg, i, ret = 0; 15143 bool ex_done = false; 15144 15145 insn_state = env->cfg.insn_state = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL); 15146 if (!insn_state) 15147 return -ENOMEM; 15148 15149 insn_stack = env->cfg.insn_stack = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL); 15150 if (!insn_stack) { 15151 kvfree(insn_state); 15152 return -ENOMEM; 15153 } 15154 15155 insn_state[0] = DISCOVERED; /* mark 1st insn as discovered */ 15156 insn_stack[0] = 0; /* 0 is the first instruction */ 15157 env->cfg.cur_stack = 1; 15158 15159 walk_cfg: 15160 while (env->cfg.cur_stack > 0) { 15161 int t = insn_stack[env->cfg.cur_stack - 1]; 15162 15163 ret = visit_insn(t, env); 15164 switch (ret) { 15165 case DONE_EXPLORING: 15166 insn_state[t] = EXPLORED; 15167 env->cfg.cur_stack--; 15168 break; 15169 case KEEP_EXPLORING: 15170 break; 15171 default: 15172 if (ret > 0) { 15173 verbose(env, "visit_insn internal bug\n"); 15174 ret = -EFAULT; 15175 } 15176 goto err_free; 15177 } 15178 } 15179 15180 if (env->cfg.cur_stack < 0) { 15181 verbose(env, "pop stack internal bug\n"); 15182 ret = -EFAULT; 15183 goto err_free; 15184 } 15185 15186 if (env->exception_callback_subprog && !ex_done) { 15187 ex_insn_beg = env->subprog_info[env->exception_callback_subprog].start; 15188 15189 insn_state[ex_insn_beg] = DISCOVERED; 15190 insn_stack[0] = ex_insn_beg; 15191 env->cfg.cur_stack = 1; 15192 ex_done = true; 15193 goto walk_cfg; 15194 } 15195 15196 for (i = 0; i < insn_cnt; i++) { 15197 if (insn_state[i] != EXPLORED) { 15198 verbose(env, "unreachable insn %d\n", i); 15199 ret = -EINVAL; 15200 goto err_free; 15201 } 15202 } 15203 ret = 0; /* cfg looks good */ 15204 15205 err_free: 15206 kvfree(insn_state); 15207 kvfree(insn_stack); 15208 env->cfg.insn_state = env->cfg.insn_stack = NULL; 15209 return ret; 15210 } 15211 15212 static int check_abnormal_return(struct bpf_verifier_env *env) 15213 { 15214 int i; 15215 15216 for (i = 1; i < env->subprog_cnt; i++) { 15217 if (env->subprog_info[i].has_ld_abs) { 15218 verbose(env, "LD_ABS is not allowed in subprogs without BTF\n"); 15219 return -EINVAL; 15220 } 15221 if (env->subprog_info[i].has_tail_call) { 15222 verbose(env, "tail_call is not allowed in subprogs without BTF\n"); 15223 return -EINVAL; 15224 } 15225 } 15226 return 0; 15227 } 15228 15229 /* The minimum supported BTF func info size */ 15230 #define MIN_BPF_FUNCINFO_SIZE 8 15231 #define MAX_FUNCINFO_REC_SIZE 252 15232 15233 static int check_btf_func_early(struct bpf_verifier_env *env, 15234 const union bpf_attr *attr, 15235 bpfptr_t uattr) 15236 { 15237 u32 krec_size = sizeof(struct bpf_func_info); 15238 const struct btf_type *type, *func_proto; 15239 u32 i, nfuncs, urec_size, min_size; 15240 struct bpf_func_info *krecord; 15241 struct bpf_prog *prog; 15242 const struct btf *btf; 15243 u32 prev_offset = 0; 15244 bpfptr_t urecord; 15245 int ret = -ENOMEM; 15246 15247 nfuncs = attr->func_info_cnt; 15248 if (!nfuncs) { 15249 if (check_abnormal_return(env)) 15250 return -EINVAL; 15251 return 0; 15252 } 15253 15254 urec_size = attr->func_info_rec_size; 15255 if (urec_size < MIN_BPF_FUNCINFO_SIZE || 15256 urec_size > MAX_FUNCINFO_REC_SIZE || 15257 urec_size % sizeof(u32)) { 15258 verbose(env, "invalid func info rec size %u\n", urec_size); 15259 return -EINVAL; 15260 } 15261 15262 prog = env->prog; 15263 btf = prog->aux->btf; 15264 15265 urecord = make_bpfptr(attr->func_info, uattr.is_kernel); 15266 min_size = min_t(u32, krec_size, urec_size); 15267 15268 krecord = kvcalloc(nfuncs, krec_size, GFP_KERNEL | __GFP_NOWARN); 15269 if (!krecord) 15270 return -ENOMEM; 15271 15272 for (i = 0; i < nfuncs; i++) { 15273 ret = bpf_check_uarg_tail_zero(urecord, krec_size, urec_size); 15274 if (ret) { 15275 if (ret == -E2BIG) { 15276 verbose(env, "nonzero tailing record in func info"); 15277 /* set the size kernel expects so loader can zero 15278 * out the rest of the record. 15279 */ 15280 if (copy_to_bpfptr_offset(uattr, 15281 offsetof(union bpf_attr, func_info_rec_size), 15282 &min_size, sizeof(min_size))) 15283 ret = -EFAULT; 15284 } 15285 goto err_free; 15286 } 15287 15288 if (copy_from_bpfptr(&krecord[i], urecord, min_size)) { 15289 ret = -EFAULT; 15290 goto err_free; 15291 } 15292 15293 /* check insn_off */ 15294 ret = -EINVAL; 15295 if (i == 0) { 15296 if (krecord[i].insn_off) { 15297 verbose(env, 15298 "nonzero insn_off %u for the first func info record", 15299 krecord[i].insn_off); 15300 goto err_free; 15301 } 15302 } else if (krecord[i].insn_off <= prev_offset) { 15303 verbose(env, 15304 "same or smaller insn offset (%u) than previous func info record (%u)", 15305 krecord[i].insn_off, prev_offset); 15306 goto err_free; 15307 } 15308 15309 /* check type_id */ 15310 type = btf_type_by_id(btf, krecord[i].type_id); 15311 if (!type || !btf_type_is_func(type)) { 15312 verbose(env, "invalid type id %d in func info", 15313 krecord[i].type_id); 15314 goto err_free; 15315 } 15316 15317 func_proto = btf_type_by_id(btf, type->type); 15318 if (unlikely(!func_proto || !btf_type_is_func_proto(func_proto))) 15319 /* btf_func_check() already verified it during BTF load */ 15320 goto err_free; 15321 15322 prev_offset = krecord[i].insn_off; 15323 bpfptr_add(&urecord, urec_size); 15324 } 15325 15326 prog->aux->func_info = krecord; 15327 prog->aux->func_info_cnt = nfuncs; 15328 return 0; 15329 15330 err_free: 15331 kvfree(krecord); 15332 return ret; 15333 } 15334 15335 static int check_btf_func(struct bpf_verifier_env *env, 15336 const union bpf_attr *attr, 15337 bpfptr_t uattr) 15338 { 15339 const struct btf_type *type, *func_proto, *ret_type; 15340 u32 i, nfuncs, urec_size; 15341 struct bpf_func_info *krecord; 15342 struct bpf_func_info_aux *info_aux = NULL; 15343 struct bpf_prog *prog; 15344 const struct btf *btf; 15345 bpfptr_t urecord; 15346 bool scalar_return; 15347 int ret = -ENOMEM; 15348 15349 nfuncs = attr->func_info_cnt; 15350 if (!nfuncs) { 15351 if (check_abnormal_return(env)) 15352 return -EINVAL; 15353 return 0; 15354 } 15355 if (nfuncs != env->subprog_cnt) { 15356 verbose(env, "number of funcs in func_info doesn't match number of subprogs\n"); 15357 return -EINVAL; 15358 } 15359 15360 urec_size = attr->func_info_rec_size; 15361 15362 prog = env->prog; 15363 btf = prog->aux->btf; 15364 15365 urecord = make_bpfptr(attr->func_info, uattr.is_kernel); 15366 15367 krecord = prog->aux->func_info; 15368 info_aux = kcalloc(nfuncs, sizeof(*info_aux), GFP_KERNEL | __GFP_NOWARN); 15369 if (!info_aux) 15370 return -ENOMEM; 15371 15372 for (i = 0; i < nfuncs; i++) { 15373 /* check insn_off */ 15374 ret = -EINVAL; 15375 15376 if (env->subprog_info[i].start != krecord[i].insn_off) { 15377 verbose(env, "func_info BTF section doesn't match subprog layout in BPF program\n"); 15378 goto err_free; 15379 } 15380 15381 /* Already checked type_id */ 15382 type = btf_type_by_id(btf, krecord[i].type_id); 15383 info_aux[i].linkage = BTF_INFO_VLEN(type->info); 15384 /* Already checked func_proto */ 15385 func_proto = btf_type_by_id(btf, type->type); 15386 15387 ret_type = btf_type_skip_modifiers(btf, func_proto->type, NULL); 15388 scalar_return = 15389 btf_type_is_small_int(ret_type) || btf_is_any_enum(ret_type); 15390 if (i && !scalar_return && env->subprog_info[i].has_ld_abs) { 15391 verbose(env, "LD_ABS is only allowed in functions that return 'int'.\n"); 15392 goto err_free; 15393 } 15394 if (i && !scalar_return && env->subprog_info[i].has_tail_call) { 15395 verbose(env, "tail_call is only allowed in functions that return 'int'.\n"); 15396 goto err_free; 15397 } 15398 15399 bpfptr_add(&urecord, urec_size); 15400 } 15401 15402 prog->aux->func_info_aux = info_aux; 15403 return 0; 15404 15405 err_free: 15406 kfree(info_aux); 15407 return ret; 15408 } 15409 15410 static void adjust_btf_func(struct bpf_verifier_env *env) 15411 { 15412 struct bpf_prog_aux *aux = env->prog->aux; 15413 int i; 15414 15415 if (!aux->func_info) 15416 return; 15417 15418 /* func_info is not available for hidden subprogs */ 15419 for (i = 0; i < env->subprog_cnt - env->hidden_subprog_cnt; i++) 15420 aux->func_info[i].insn_off = env->subprog_info[i].start; 15421 } 15422 15423 #define MIN_BPF_LINEINFO_SIZE offsetofend(struct bpf_line_info, line_col) 15424 #define MAX_LINEINFO_REC_SIZE MAX_FUNCINFO_REC_SIZE 15425 15426 static int check_btf_line(struct bpf_verifier_env *env, 15427 const union bpf_attr *attr, 15428 bpfptr_t uattr) 15429 { 15430 u32 i, s, nr_linfo, ncopy, expected_size, rec_size, prev_offset = 0; 15431 struct bpf_subprog_info *sub; 15432 struct bpf_line_info *linfo; 15433 struct bpf_prog *prog; 15434 const struct btf *btf; 15435 bpfptr_t ulinfo; 15436 int err; 15437 15438 nr_linfo = attr->line_info_cnt; 15439 if (!nr_linfo) 15440 return 0; 15441 if (nr_linfo > INT_MAX / sizeof(struct bpf_line_info)) 15442 return -EINVAL; 15443 15444 rec_size = attr->line_info_rec_size; 15445 if (rec_size < MIN_BPF_LINEINFO_SIZE || 15446 rec_size > MAX_LINEINFO_REC_SIZE || 15447 rec_size & (sizeof(u32) - 1)) 15448 return -EINVAL; 15449 15450 /* Need to zero it in case the userspace may 15451 * pass in a smaller bpf_line_info object. 15452 */ 15453 linfo = kvcalloc(nr_linfo, sizeof(struct bpf_line_info), 15454 GFP_KERNEL | __GFP_NOWARN); 15455 if (!linfo) 15456 return -ENOMEM; 15457 15458 prog = env->prog; 15459 btf = prog->aux->btf; 15460 15461 s = 0; 15462 sub = env->subprog_info; 15463 ulinfo = make_bpfptr(attr->line_info, uattr.is_kernel); 15464 expected_size = sizeof(struct bpf_line_info); 15465 ncopy = min_t(u32, expected_size, rec_size); 15466 for (i = 0; i < nr_linfo; i++) { 15467 err = bpf_check_uarg_tail_zero(ulinfo, expected_size, rec_size); 15468 if (err) { 15469 if (err == -E2BIG) { 15470 verbose(env, "nonzero tailing record in line_info"); 15471 if (copy_to_bpfptr_offset(uattr, 15472 offsetof(union bpf_attr, line_info_rec_size), 15473 &expected_size, sizeof(expected_size))) 15474 err = -EFAULT; 15475 } 15476 goto err_free; 15477 } 15478 15479 if (copy_from_bpfptr(&linfo[i], ulinfo, ncopy)) { 15480 err = -EFAULT; 15481 goto err_free; 15482 } 15483 15484 /* 15485 * Check insn_off to ensure 15486 * 1) strictly increasing AND 15487 * 2) bounded by prog->len 15488 * 15489 * The linfo[0].insn_off == 0 check logically falls into 15490 * the later "missing bpf_line_info for func..." case 15491 * because the first linfo[0].insn_off must be the 15492 * first sub also and the first sub must have 15493 * subprog_info[0].start == 0. 15494 */ 15495 if ((i && linfo[i].insn_off <= prev_offset) || 15496 linfo[i].insn_off >= prog->len) { 15497 verbose(env, "Invalid line_info[%u].insn_off:%u (prev_offset:%u prog->len:%u)\n", 15498 i, linfo[i].insn_off, prev_offset, 15499 prog->len); 15500 err = -EINVAL; 15501 goto err_free; 15502 } 15503 15504 if (!prog->insnsi[linfo[i].insn_off].code) { 15505 verbose(env, 15506 "Invalid insn code at line_info[%u].insn_off\n", 15507 i); 15508 err = -EINVAL; 15509 goto err_free; 15510 } 15511 15512 if (!btf_name_by_offset(btf, linfo[i].line_off) || 15513 !btf_name_by_offset(btf, linfo[i].file_name_off)) { 15514 verbose(env, "Invalid line_info[%u].line_off or .file_name_off\n", i); 15515 err = -EINVAL; 15516 goto err_free; 15517 } 15518 15519 if (s != env->subprog_cnt) { 15520 if (linfo[i].insn_off == sub[s].start) { 15521 sub[s].linfo_idx = i; 15522 s++; 15523 } else if (sub[s].start < linfo[i].insn_off) { 15524 verbose(env, "missing bpf_line_info for func#%u\n", s); 15525 err = -EINVAL; 15526 goto err_free; 15527 } 15528 } 15529 15530 prev_offset = linfo[i].insn_off; 15531 bpfptr_add(&ulinfo, rec_size); 15532 } 15533 15534 if (s != env->subprog_cnt) { 15535 verbose(env, "missing bpf_line_info for %u funcs starting from func#%u\n", 15536 env->subprog_cnt - s, s); 15537 err = -EINVAL; 15538 goto err_free; 15539 } 15540 15541 prog->aux->linfo = linfo; 15542 prog->aux->nr_linfo = nr_linfo; 15543 15544 return 0; 15545 15546 err_free: 15547 kvfree(linfo); 15548 return err; 15549 } 15550 15551 #define MIN_CORE_RELO_SIZE sizeof(struct bpf_core_relo) 15552 #define MAX_CORE_RELO_SIZE MAX_FUNCINFO_REC_SIZE 15553 15554 static int check_core_relo(struct bpf_verifier_env *env, 15555 const union bpf_attr *attr, 15556 bpfptr_t uattr) 15557 { 15558 u32 i, nr_core_relo, ncopy, expected_size, rec_size; 15559 struct bpf_core_relo core_relo = {}; 15560 struct bpf_prog *prog = env->prog; 15561 const struct btf *btf = prog->aux->btf; 15562 struct bpf_core_ctx ctx = { 15563 .log = &env->log, 15564 .btf = btf, 15565 }; 15566 bpfptr_t u_core_relo; 15567 int err; 15568 15569 nr_core_relo = attr->core_relo_cnt; 15570 if (!nr_core_relo) 15571 return 0; 15572 if (nr_core_relo > INT_MAX / sizeof(struct bpf_core_relo)) 15573 return -EINVAL; 15574 15575 rec_size = attr->core_relo_rec_size; 15576 if (rec_size < MIN_CORE_RELO_SIZE || 15577 rec_size > MAX_CORE_RELO_SIZE || 15578 rec_size % sizeof(u32)) 15579 return -EINVAL; 15580 15581 u_core_relo = make_bpfptr(attr->core_relos, uattr.is_kernel); 15582 expected_size = sizeof(struct bpf_core_relo); 15583 ncopy = min_t(u32, expected_size, rec_size); 15584 15585 /* Unlike func_info and line_info, copy and apply each CO-RE 15586 * relocation record one at a time. 15587 */ 15588 for (i = 0; i < nr_core_relo; i++) { 15589 /* future proofing when sizeof(bpf_core_relo) changes */ 15590 err = bpf_check_uarg_tail_zero(u_core_relo, expected_size, rec_size); 15591 if (err) { 15592 if (err == -E2BIG) { 15593 verbose(env, "nonzero tailing record in core_relo"); 15594 if (copy_to_bpfptr_offset(uattr, 15595 offsetof(union bpf_attr, core_relo_rec_size), 15596 &expected_size, sizeof(expected_size))) 15597 err = -EFAULT; 15598 } 15599 break; 15600 } 15601 15602 if (copy_from_bpfptr(&core_relo, u_core_relo, ncopy)) { 15603 err = -EFAULT; 15604 break; 15605 } 15606 15607 if (core_relo.insn_off % 8 || core_relo.insn_off / 8 >= prog->len) { 15608 verbose(env, "Invalid core_relo[%u].insn_off:%u prog->len:%u\n", 15609 i, core_relo.insn_off, prog->len); 15610 err = -EINVAL; 15611 break; 15612 } 15613 15614 err = bpf_core_apply(&ctx, &core_relo, i, 15615 &prog->insnsi[core_relo.insn_off / 8]); 15616 if (err) 15617 break; 15618 bpfptr_add(&u_core_relo, rec_size); 15619 } 15620 return err; 15621 } 15622 15623 static int check_btf_info_early(struct bpf_verifier_env *env, 15624 const union bpf_attr *attr, 15625 bpfptr_t uattr) 15626 { 15627 struct btf *btf; 15628 int err; 15629 15630 if (!attr->func_info_cnt && !attr->line_info_cnt) { 15631 if (check_abnormal_return(env)) 15632 return -EINVAL; 15633 return 0; 15634 } 15635 15636 btf = btf_get_by_fd(attr->prog_btf_fd); 15637 if (IS_ERR(btf)) 15638 return PTR_ERR(btf); 15639 if (btf_is_kernel(btf)) { 15640 btf_put(btf); 15641 return -EACCES; 15642 } 15643 env->prog->aux->btf = btf; 15644 15645 err = check_btf_func_early(env, attr, uattr); 15646 if (err) 15647 return err; 15648 return 0; 15649 } 15650 15651 static int check_btf_info(struct bpf_verifier_env *env, 15652 const union bpf_attr *attr, 15653 bpfptr_t uattr) 15654 { 15655 int err; 15656 15657 if (!attr->func_info_cnt && !attr->line_info_cnt) { 15658 if (check_abnormal_return(env)) 15659 return -EINVAL; 15660 return 0; 15661 } 15662 15663 err = check_btf_func(env, attr, uattr); 15664 if (err) 15665 return err; 15666 15667 err = check_btf_line(env, attr, uattr); 15668 if (err) 15669 return err; 15670 15671 err = check_core_relo(env, attr, uattr); 15672 if (err) 15673 return err; 15674 15675 return 0; 15676 } 15677 15678 /* check %cur's range satisfies %old's */ 15679 static bool range_within(struct bpf_reg_state *old, 15680 struct bpf_reg_state *cur) 15681 { 15682 return old->umin_value <= cur->umin_value && 15683 old->umax_value >= cur->umax_value && 15684 old->smin_value <= cur->smin_value && 15685 old->smax_value >= cur->smax_value && 15686 old->u32_min_value <= cur->u32_min_value && 15687 old->u32_max_value >= cur->u32_max_value && 15688 old->s32_min_value <= cur->s32_min_value && 15689 old->s32_max_value >= cur->s32_max_value; 15690 } 15691 15692 /* If in the old state two registers had the same id, then they need to have 15693 * the same id in the new state as well. But that id could be different from 15694 * the old state, so we need to track the mapping from old to new ids. 15695 * Once we have seen that, say, a reg with old id 5 had new id 9, any subsequent 15696 * regs with old id 5 must also have new id 9 for the new state to be safe. But 15697 * regs with a different old id could still have new id 9, we don't care about 15698 * that. 15699 * So we look through our idmap to see if this old id has been seen before. If 15700 * so, we require the new id to match; otherwise, we add the id pair to the map. 15701 */ 15702 static bool check_ids(u32 old_id, u32 cur_id, struct bpf_idmap *idmap) 15703 { 15704 struct bpf_id_pair *map = idmap->map; 15705 unsigned int i; 15706 15707 /* either both IDs should be set or both should be zero */ 15708 if (!!old_id != !!cur_id) 15709 return false; 15710 15711 if (old_id == 0) /* cur_id == 0 as well */ 15712 return true; 15713 15714 for (i = 0; i < BPF_ID_MAP_SIZE; i++) { 15715 if (!map[i].old) { 15716 /* Reached an empty slot; haven't seen this id before */ 15717 map[i].old = old_id; 15718 map[i].cur = cur_id; 15719 return true; 15720 } 15721 if (map[i].old == old_id) 15722 return map[i].cur == cur_id; 15723 if (map[i].cur == cur_id) 15724 return false; 15725 } 15726 /* We ran out of idmap slots, which should be impossible */ 15727 WARN_ON_ONCE(1); 15728 return false; 15729 } 15730 15731 /* Similar to check_ids(), but allocate a unique temporary ID 15732 * for 'old_id' or 'cur_id' of zero. 15733 * This makes pairs like '0 vs unique ID', 'unique ID vs 0' valid. 15734 */ 15735 static bool check_scalar_ids(u32 old_id, u32 cur_id, struct bpf_idmap *idmap) 15736 { 15737 old_id = old_id ? old_id : ++idmap->tmp_id_gen; 15738 cur_id = cur_id ? cur_id : ++idmap->tmp_id_gen; 15739 15740 return check_ids(old_id, cur_id, idmap); 15741 } 15742 15743 static void clean_func_state(struct bpf_verifier_env *env, 15744 struct bpf_func_state *st) 15745 { 15746 enum bpf_reg_liveness live; 15747 int i, j; 15748 15749 for (i = 0; i < BPF_REG_FP; i++) { 15750 live = st->regs[i].live; 15751 /* liveness must not touch this register anymore */ 15752 st->regs[i].live |= REG_LIVE_DONE; 15753 if (!(live & REG_LIVE_READ)) 15754 /* since the register is unused, clear its state 15755 * to make further comparison simpler 15756 */ 15757 __mark_reg_not_init(env, &st->regs[i]); 15758 } 15759 15760 for (i = 0; i < st->allocated_stack / BPF_REG_SIZE; i++) { 15761 live = st->stack[i].spilled_ptr.live; 15762 /* liveness must not touch this stack slot anymore */ 15763 st->stack[i].spilled_ptr.live |= REG_LIVE_DONE; 15764 if (!(live & REG_LIVE_READ)) { 15765 __mark_reg_not_init(env, &st->stack[i].spilled_ptr); 15766 for (j = 0; j < BPF_REG_SIZE; j++) 15767 st->stack[i].slot_type[j] = STACK_INVALID; 15768 } 15769 } 15770 } 15771 15772 static void clean_verifier_state(struct bpf_verifier_env *env, 15773 struct bpf_verifier_state *st) 15774 { 15775 int i; 15776 15777 if (st->frame[0]->regs[0].live & REG_LIVE_DONE) 15778 /* all regs in this state in all frames were already marked */ 15779 return; 15780 15781 for (i = 0; i <= st->curframe; i++) 15782 clean_func_state(env, st->frame[i]); 15783 } 15784 15785 /* the parentage chains form a tree. 15786 * the verifier states are added to state lists at given insn and 15787 * pushed into state stack for future exploration. 15788 * when the verifier reaches bpf_exit insn some of the verifer states 15789 * stored in the state lists have their final liveness state already, 15790 * but a lot of states will get revised from liveness point of view when 15791 * the verifier explores other branches. 15792 * Example: 15793 * 1: r0 = 1 15794 * 2: if r1 == 100 goto pc+1 15795 * 3: r0 = 2 15796 * 4: exit 15797 * when the verifier reaches exit insn the register r0 in the state list of 15798 * insn 2 will be seen as !REG_LIVE_READ. Then the verifier pops the other_branch 15799 * of insn 2 and goes exploring further. At the insn 4 it will walk the 15800 * parentage chain from insn 4 into insn 2 and will mark r0 as REG_LIVE_READ. 15801 * 15802 * Since the verifier pushes the branch states as it sees them while exploring 15803 * the program the condition of walking the branch instruction for the second 15804 * time means that all states below this branch were already explored and 15805 * their final liveness marks are already propagated. 15806 * Hence when the verifier completes the search of state list in is_state_visited() 15807 * we can call this clean_live_states() function to mark all liveness states 15808 * as REG_LIVE_DONE to indicate that 'parent' pointers of 'struct bpf_reg_state' 15809 * will not be used. 15810 * This function also clears the registers and stack for states that !READ 15811 * to simplify state merging. 15812 * 15813 * Important note here that walking the same branch instruction in the callee 15814 * doesn't meant that the states are DONE. The verifier has to compare 15815 * the callsites 15816 */ 15817 static void clean_live_states(struct bpf_verifier_env *env, int insn, 15818 struct bpf_verifier_state *cur) 15819 { 15820 struct bpf_verifier_state_list *sl; 15821 int i; 15822 15823 sl = *explored_state(env, insn); 15824 while (sl) { 15825 if (sl->state.branches) 15826 goto next; 15827 if (sl->state.insn_idx != insn || 15828 sl->state.curframe != cur->curframe) 15829 goto next; 15830 for (i = 0; i <= cur->curframe; i++) 15831 if (sl->state.frame[i]->callsite != cur->frame[i]->callsite) 15832 goto next; 15833 clean_verifier_state(env, &sl->state); 15834 next: 15835 sl = sl->next; 15836 } 15837 } 15838 15839 static bool regs_exact(const struct bpf_reg_state *rold, 15840 const struct bpf_reg_state *rcur, 15841 struct bpf_idmap *idmap) 15842 { 15843 return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 && 15844 check_ids(rold->id, rcur->id, idmap) && 15845 check_ids(rold->ref_obj_id, rcur->ref_obj_id, idmap); 15846 } 15847 15848 /* Returns true if (rold safe implies rcur safe) */ 15849 static bool regsafe(struct bpf_verifier_env *env, struct bpf_reg_state *rold, 15850 struct bpf_reg_state *rcur, struct bpf_idmap *idmap) 15851 { 15852 if (!(rold->live & REG_LIVE_READ)) 15853 /* explored state didn't use this */ 15854 return true; 15855 if (rold->type == NOT_INIT) 15856 /* explored state can't have used this */ 15857 return true; 15858 if (rcur->type == NOT_INIT) 15859 return false; 15860 15861 /* Enforce that register types have to match exactly, including their 15862 * modifiers (like PTR_MAYBE_NULL, MEM_RDONLY, etc), as a general 15863 * rule. 15864 * 15865 * One can make a point that using a pointer register as unbounded 15866 * SCALAR would be technically acceptable, but this could lead to 15867 * pointer leaks because scalars are allowed to leak while pointers 15868 * are not. We could make this safe in special cases if root is 15869 * calling us, but it's probably not worth the hassle. 15870 * 15871 * Also, register types that are *not* MAYBE_NULL could technically be 15872 * safe to use as their MAYBE_NULL variants (e.g., PTR_TO_MAP_VALUE 15873 * is safe to be used as PTR_TO_MAP_VALUE_OR_NULL, provided both point 15874 * to the same map). 15875 * However, if the old MAYBE_NULL register then got NULL checked, 15876 * doing so could have affected others with the same id, and we can't 15877 * check for that because we lost the id when we converted to 15878 * a non-MAYBE_NULL variant. 15879 * So, as a general rule we don't allow mixing MAYBE_NULL and 15880 * non-MAYBE_NULL registers as well. 15881 */ 15882 if (rold->type != rcur->type) 15883 return false; 15884 15885 switch (base_type(rold->type)) { 15886 case SCALAR_VALUE: 15887 if (env->explore_alu_limits) { 15888 /* explore_alu_limits disables tnum_in() and range_within() 15889 * logic and requires everything to be strict 15890 */ 15891 return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 && 15892 check_scalar_ids(rold->id, rcur->id, idmap); 15893 } 15894 if (!rold->precise) 15895 return true; 15896 /* Why check_ids() for scalar registers? 15897 * 15898 * Consider the following BPF code: 15899 * 1: r6 = ... unbound scalar, ID=a ... 15900 * 2: r7 = ... unbound scalar, ID=b ... 15901 * 3: if (r6 > r7) goto +1 15902 * 4: r6 = r7 15903 * 5: if (r6 > X) goto ... 15904 * 6: ... memory operation using r7 ... 15905 * 15906 * First verification path is [1-6]: 15907 * - at (4) same bpf_reg_state::id (b) would be assigned to r6 and r7; 15908 * - at (5) r6 would be marked <= X, find_equal_scalars() would also mark 15909 * r7 <= X, because r6 and r7 share same id. 15910 * Next verification path is [1-4, 6]. 15911 * 15912 * Instruction (6) would be reached in two states: 15913 * I. r6{.id=b}, r7{.id=b} via path 1-6; 15914 * II. r6{.id=a}, r7{.id=b} via path 1-4, 6. 15915 * 15916 * Use check_ids() to distinguish these states. 15917 * --- 15918 * Also verify that new value satisfies old value range knowledge. 15919 */ 15920 return range_within(rold, rcur) && 15921 tnum_in(rold->var_off, rcur->var_off) && 15922 check_scalar_ids(rold->id, rcur->id, idmap); 15923 case PTR_TO_MAP_KEY: 15924 case PTR_TO_MAP_VALUE: 15925 case PTR_TO_MEM: 15926 case PTR_TO_BUF: 15927 case PTR_TO_TP_BUFFER: 15928 /* If the new min/max/var_off satisfy the old ones and 15929 * everything else matches, we are OK. 15930 */ 15931 return memcmp(rold, rcur, offsetof(struct bpf_reg_state, var_off)) == 0 && 15932 range_within(rold, rcur) && 15933 tnum_in(rold->var_off, rcur->var_off) && 15934 check_ids(rold->id, rcur->id, idmap) && 15935 check_ids(rold->ref_obj_id, rcur->ref_obj_id, idmap); 15936 case PTR_TO_PACKET_META: 15937 case PTR_TO_PACKET: 15938 /* We must have at least as much range as the old ptr 15939 * did, so that any accesses which were safe before are 15940 * still safe. This is true even if old range < old off, 15941 * since someone could have accessed through (ptr - k), or 15942 * even done ptr -= k in a register, to get a safe access. 15943 */ 15944 if (rold->range > rcur->range) 15945 return false; 15946 /* If the offsets don't match, we can't trust our alignment; 15947 * nor can we be sure that we won't fall out of range. 15948 */ 15949 if (rold->off != rcur->off) 15950 return false; 15951 /* id relations must be preserved */ 15952 if (!check_ids(rold->id, rcur->id, idmap)) 15953 return false; 15954 /* new val must satisfy old val knowledge */ 15955 return range_within(rold, rcur) && 15956 tnum_in(rold->var_off, rcur->var_off); 15957 case PTR_TO_STACK: 15958 /* two stack pointers are equal only if they're pointing to 15959 * the same stack frame, since fp-8 in foo != fp-8 in bar 15960 */ 15961 return regs_exact(rold, rcur, idmap) && rold->frameno == rcur->frameno; 15962 default: 15963 return regs_exact(rold, rcur, idmap); 15964 } 15965 } 15966 15967 static bool stacksafe(struct bpf_verifier_env *env, struct bpf_func_state *old, 15968 struct bpf_func_state *cur, struct bpf_idmap *idmap) 15969 { 15970 int i, spi; 15971 15972 /* walk slots of the explored stack and ignore any additional 15973 * slots in the current stack, since explored(safe) state 15974 * didn't use them 15975 */ 15976 for (i = 0; i < old->allocated_stack; i++) { 15977 struct bpf_reg_state *old_reg, *cur_reg; 15978 15979 spi = i / BPF_REG_SIZE; 15980 15981 if (!(old->stack[spi].spilled_ptr.live & REG_LIVE_READ)) { 15982 i += BPF_REG_SIZE - 1; 15983 /* explored state didn't use this */ 15984 continue; 15985 } 15986 15987 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_INVALID) 15988 continue; 15989 15990 if (env->allow_uninit_stack && 15991 old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC) 15992 continue; 15993 15994 /* explored stack has more populated slots than current stack 15995 * and these slots were used 15996 */ 15997 if (i >= cur->allocated_stack) 15998 return false; 15999 16000 /* if old state was safe with misc data in the stack 16001 * it will be safe with zero-initialized stack. 16002 * The opposite is not true 16003 */ 16004 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC && 16005 cur->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_ZERO) 16006 continue; 16007 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] != 16008 cur->stack[spi].slot_type[i % BPF_REG_SIZE]) 16009 /* Ex: old explored (safe) state has STACK_SPILL in 16010 * this stack slot, but current has STACK_MISC -> 16011 * this verifier states are not equivalent, 16012 * return false to continue verification of this path 16013 */ 16014 return false; 16015 if (i % BPF_REG_SIZE != BPF_REG_SIZE - 1) 16016 continue; 16017 /* Both old and cur are having same slot_type */ 16018 switch (old->stack[spi].slot_type[BPF_REG_SIZE - 1]) { 16019 case STACK_SPILL: 16020 /* when explored and current stack slot are both storing 16021 * spilled registers, check that stored pointers types 16022 * are the same as well. 16023 * Ex: explored safe path could have stored 16024 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -8} 16025 * but current path has stored: 16026 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -16} 16027 * such verifier states are not equivalent. 16028 * return false to continue verification of this path 16029 */ 16030 if (!regsafe(env, &old->stack[spi].spilled_ptr, 16031 &cur->stack[spi].spilled_ptr, idmap)) 16032 return false; 16033 break; 16034 case STACK_DYNPTR: 16035 old_reg = &old->stack[spi].spilled_ptr; 16036 cur_reg = &cur->stack[spi].spilled_ptr; 16037 if (old_reg->dynptr.type != cur_reg->dynptr.type || 16038 old_reg->dynptr.first_slot != cur_reg->dynptr.first_slot || 16039 !check_ids(old_reg->ref_obj_id, cur_reg->ref_obj_id, idmap)) 16040 return false; 16041 break; 16042 case STACK_ITER: 16043 old_reg = &old->stack[spi].spilled_ptr; 16044 cur_reg = &cur->stack[spi].spilled_ptr; 16045 /* iter.depth is not compared between states as it 16046 * doesn't matter for correctness and would otherwise 16047 * prevent convergence; we maintain it only to prevent 16048 * infinite loop check triggering, see 16049 * iter_active_depths_differ() 16050 */ 16051 if (old_reg->iter.btf != cur_reg->iter.btf || 16052 old_reg->iter.btf_id != cur_reg->iter.btf_id || 16053 old_reg->iter.state != cur_reg->iter.state || 16054 /* ignore {old_reg,cur_reg}->iter.depth, see above */ 16055 !check_ids(old_reg->ref_obj_id, cur_reg->ref_obj_id, idmap)) 16056 return false; 16057 break; 16058 case STACK_MISC: 16059 case STACK_ZERO: 16060 case STACK_INVALID: 16061 continue; 16062 /* Ensure that new unhandled slot types return false by default */ 16063 default: 16064 return false; 16065 } 16066 } 16067 return true; 16068 } 16069 16070 static bool refsafe(struct bpf_func_state *old, struct bpf_func_state *cur, 16071 struct bpf_idmap *idmap) 16072 { 16073 int i; 16074 16075 if (old->acquired_refs != cur->acquired_refs) 16076 return false; 16077 16078 for (i = 0; i < old->acquired_refs; i++) { 16079 if (!check_ids(old->refs[i].id, cur->refs[i].id, idmap)) 16080 return false; 16081 } 16082 16083 return true; 16084 } 16085 16086 /* compare two verifier states 16087 * 16088 * all states stored in state_list are known to be valid, since 16089 * verifier reached 'bpf_exit' instruction through them 16090 * 16091 * this function is called when verifier exploring different branches of 16092 * execution popped from the state stack. If it sees an old state that has 16093 * more strict register state and more strict stack state then this execution 16094 * branch doesn't need to be explored further, since verifier already 16095 * concluded that more strict state leads to valid finish. 16096 * 16097 * Therefore two states are equivalent if register state is more conservative 16098 * and explored stack state is more conservative than the current one. 16099 * Example: 16100 * explored current 16101 * (slot1=INV slot2=MISC) == (slot1=MISC slot2=MISC) 16102 * (slot1=MISC slot2=MISC) != (slot1=INV slot2=MISC) 16103 * 16104 * In other words if current stack state (one being explored) has more 16105 * valid slots than old one that already passed validation, it means 16106 * the verifier can stop exploring and conclude that current state is valid too 16107 * 16108 * Similarly with registers. If explored state has register type as invalid 16109 * whereas register type in current state is meaningful, it means that 16110 * the current state will reach 'bpf_exit' instruction safely 16111 */ 16112 static bool func_states_equal(struct bpf_verifier_env *env, struct bpf_func_state *old, 16113 struct bpf_func_state *cur) 16114 { 16115 int i; 16116 16117 for (i = 0; i < MAX_BPF_REG; i++) 16118 if (!regsafe(env, &old->regs[i], &cur->regs[i], 16119 &env->idmap_scratch)) 16120 return false; 16121 16122 if (!stacksafe(env, old, cur, &env->idmap_scratch)) 16123 return false; 16124 16125 if (!refsafe(old, cur, &env->idmap_scratch)) 16126 return false; 16127 16128 return true; 16129 } 16130 16131 static bool states_equal(struct bpf_verifier_env *env, 16132 struct bpf_verifier_state *old, 16133 struct bpf_verifier_state *cur) 16134 { 16135 int i; 16136 16137 if (old->curframe != cur->curframe) 16138 return false; 16139 16140 env->idmap_scratch.tmp_id_gen = env->id_gen; 16141 memset(&env->idmap_scratch.map, 0, sizeof(env->idmap_scratch.map)); 16142 16143 /* Verification state from speculative execution simulation 16144 * must never prune a non-speculative execution one. 16145 */ 16146 if (old->speculative && !cur->speculative) 16147 return false; 16148 16149 if (old->active_lock.ptr != cur->active_lock.ptr) 16150 return false; 16151 16152 /* Old and cur active_lock's have to be either both present 16153 * or both absent. 16154 */ 16155 if (!!old->active_lock.id != !!cur->active_lock.id) 16156 return false; 16157 16158 if (old->active_lock.id && 16159 !check_ids(old->active_lock.id, cur->active_lock.id, &env->idmap_scratch)) 16160 return false; 16161 16162 if (old->active_rcu_lock != cur->active_rcu_lock) 16163 return false; 16164 16165 /* for states to be equal callsites have to be the same 16166 * and all frame states need to be equivalent 16167 */ 16168 for (i = 0; i <= old->curframe; i++) { 16169 if (old->frame[i]->callsite != cur->frame[i]->callsite) 16170 return false; 16171 if (!func_states_equal(env, old->frame[i], cur->frame[i])) 16172 return false; 16173 } 16174 return true; 16175 } 16176 16177 /* Return 0 if no propagation happened. Return negative error code if error 16178 * happened. Otherwise, return the propagated bit. 16179 */ 16180 static int propagate_liveness_reg(struct bpf_verifier_env *env, 16181 struct bpf_reg_state *reg, 16182 struct bpf_reg_state *parent_reg) 16183 { 16184 u8 parent_flag = parent_reg->live & REG_LIVE_READ; 16185 u8 flag = reg->live & REG_LIVE_READ; 16186 int err; 16187 16188 /* When comes here, read flags of PARENT_REG or REG could be any of 16189 * REG_LIVE_READ64, REG_LIVE_READ32, REG_LIVE_NONE. There is no need 16190 * of propagation if PARENT_REG has strongest REG_LIVE_READ64. 16191 */ 16192 if (parent_flag == REG_LIVE_READ64 || 16193 /* Or if there is no read flag from REG. */ 16194 !flag || 16195 /* Or if the read flag from REG is the same as PARENT_REG. */ 16196 parent_flag == flag) 16197 return 0; 16198 16199 err = mark_reg_read(env, reg, parent_reg, flag); 16200 if (err) 16201 return err; 16202 16203 return flag; 16204 } 16205 16206 /* A write screens off any subsequent reads; but write marks come from the 16207 * straight-line code between a state and its parent. When we arrive at an 16208 * equivalent state (jump target or such) we didn't arrive by the straight-line 16209 * code, so read marks in the state must propagate to the parent regardless 16210 * of the state's write marks. That's what 'parent == state->parent' comparison 16211 * in mark_reg_read() is for. 16212 */ 16213 static int propagate_liveness(struct bpf_verifier_env *env, 16214 const struct bpf_verifier_state *vstate, 16215 struct bpf_verifier_state *vparent) 16216 { 16217 struct bpf_reg_state *state_reg, *parent_reg; 16218 struct bpf_func_state *state, *parent; 16219 int i, frame, err = 0; 16220 16221 if (vparent->curframe != vstate->curframe) { 16222 WARN(1, "propagate_live: parent frame %d current frame %d\n", 16223 vparent->curframe, vstate->curframe); 16224 return -EFAULT; 16225 } 16226 /* Propagate read liveness of registers... */ 16227 BUILD_BUG_ON(BPF_REG_FP + 1 != MAX_BPF_REG); 16228 for (frame = 0; frame <= vstate->curframe; frame++) { 16229 parent = vparent->frame[frame]; 16230 state = vstate->frame[frame]; 16231 parent_reg = parent->regs; 16232 state_reg = state->regs; 16233 /* We don't need to worry about FP liveness, it's read-only */ 16234 for (i = frame < vstate->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++) { 16235 err = propagate_liveness_reg(env, &state_reg[i], 16236 &parent_reg[i]); 16237 if (err < 0) 16238 return err; 16239 if (err == REG_LIVE_READ64) 16240 mark_insn_zext(env, &parent_reg[i]); 16241 } 16242 16243 /* Propagate stack slots. */ 16244 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE && 16245 i < parent->allocated_stack / BPF_REG_SIZE; i++) { 16246 parent_reg = &parent->stack[i].spilled_ptr; 16247 state_reg = &state->stack[i].spilled_ptr; 16248 err = propagate_liveness_reg(env, state_reg, 16249 parent_reg); 16250 if (err < 0) 16251 return err; 16252 } 16253 } 16254 return 0; 16255 } 16256 16257 /* find precise scalars in the previous equivalent state and 16258 * propagate them into the current state 16259 */ 16260 static int propagate_precision(struct bpf_verifier_env *env, 16261 const struct bpf_verifier_state *old) 16262 { 16263 struct bpf_reg_state *state_reg; 16264 struct bpf_func_state *state; 16265 int i, err = 0, fr; 16266 bool first; 16267 16268 for (fr = old->curframe; fr >= 0; fr--) { 16269 state = old->frame[fr]; 16270 state_reg = state->regs; 16271 first = true; 16272 for (i = 0; i < BPF_REG_FP; i++, state_reg++) { 16273 if (state_reg->type != SCALAR_VALUE || 16274 !state_reg->precise || 16275 !(state_reg->live & REG_LIVE_READ)) 16276 continue; 16277 if (env->log.level & BPF_LOG_LEVEL2) { 16278 if (first) 16279 verbose(env, "frame %d: propagating r%d", fr, i); 16280 else 16281 verbose(env, ",r%d", i); 16282 } 16283 bt_set_frame_reg(&env->bt, fr, i); 16284 first = false; 16285 } 16286 16287 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) { 16288 if (!is_spilled_reg(&state->stack[i])) 16289 continue; 16290 state_reg = &state->stack[i].spilled_ptr; 16291 if (state_reg->type != SCALAR_VALUE || 16292 !state_reg->precise || 16293 !(state_reg->live & REG_LIVE_READ)) 16294 continue; 16295 if (env->log.level & BPF_LOG_LEVEL2) { 16296 if (first) 16297 verbose(env, "frame %d: propagating fp%d", 16298 fr, (-i - 1) * BPF_REG_SIZE); 16299 else 16300 verbose(env, ",fp%d", (-i - 1) * BPF_REG_SIZE); 16301 } 16302 bt_set_frame_slot(&env->bt, fr, i); 16303 first = false; 16304 } 16305 if (!first) 16306 verbose(env, "\n"); 16307 } 16308 16309 err = mark_chain_precision_batch(env); 16310 if (err < 0) 16311 return err; 16312 16313 return 0; 16314 } 16315 16316 static bool states_maybe_looping(struct bpf_verifier_state *old, 16317 struct bpf_verifier_state *cur) 16318 { 16319 struct bpf_func_state *fold, *fcur; 16320 int i, fr = cur->curframe; 16321 16322 if (old->curframe != fr) 16323 return false; 16324 16325 fold = old->frame[fr]; 16326 fcur = cur->frame[fr]; 16327 for (i = 0; i < MAX_BPF_REG; i++) 16328 if (memcmp(&fold->regs[i], &fcur->regs[i], 16329 offsetof(struct bpf_reg_state, parent))) 16330 return false; 16331 return true; 16332 } 16333 16334 static bool is_iter_next_insn(struct bpf_verifier_env *env, int insn_idx) 16335 { 16336 return env->insn_aux_data[insn_idx].is_iter_next; 16337 } 16338 16339 /* is_state_visited() handles iter_next() (see process_iter_next_call() for 16340 * terminology) calls specially: as opposed to bounded BPF loops, it *expects* 16341 * states to match, which otherwise would look like an infinite loop. So while 16342 * iter_next() calls are taken care of, we still need to be careful and 16343 * prevent erroneous and too eager declaration of "ininite loop", when 16344 * iterators are involved. 16345 * 16346 * Here's a situation in pseudo-BPF assembly form: 16347 * 16348 * 0: again: ; set up iter_next() call args 16349 * 1: r1 = &it ; <CHECKPOINT HERE> 16350 * 2: call bpf_iter_num_next ; this is iter_next() call 16351 * 3: if r0 == 0 goto done 16352 * 4: ... something useful here ... 16353 * 5: goto again ; another iteration 16354 * 6: done: 16355 * 7: r1 = &it 16356 * 8: call bpf_iter_num_destroy ; clean up iter state 16357 * 9: exit 16358 * 16359 * This is a typical loop. Let's assume that we have a prune point at 1:, 16360 * before we get to `call bpf_iter_num_next` (e.g., because of that `goto 16361 * again`, assuming other heuristics don't get in a way). 16362 * 16363 * When we first time come to 1:, let's say we have some state X. We proceed 16364 * to 2:, fork states, enqueue ACTIVE, validate NULL case successfully, exit. 16365 * Now we come back to validate that forked ACTIVE state. We proceed through 16366 * 3-5, come to goto, jump to 1:. Let's assume our state didn't change, so we 16367 * are converging. But the problem is that we don't know that yet, as this 16368 * convergence has to happen at iter_next() call site only. So if nothing is 16369 * done, at 1: verifier will use bounded loop logic and declare infinite 16370 * looping (and would be *technically* correct, if not for iterator's 16371 * "eventual sticky NULL" contract, see process_iter_next_call()). But we 16372 * don't want that. So what we do in process_iter_next_call() when we go on 16373 * another ACTIVE iteration, we bump slot->iter.depth, to mark that it's 16374 * a different iteration. So when we suspect an infinite loop, we additionally 16375 * check if any of the *ACTIVE* iterator states depths differ. If yes, we 16376 * pretend we are not looping and wait for next iter_next() call. 16377 * 16378 * This only applies to ACTIVE state. In DRAINED state we don't expect to 16379 * loop, because that would actually mean infinite loop, as DRAINED state is 16380 * "sticky", and so we'll keep returning into the same instruction with the 16381 * same state (at least in one of possible code paths). 16382 * 16383 * This approach allows to keep infinite loop heuristic even in the face of 16384 * active iterator. E.g., C snippet below is and will be detected as 16385 * inifintely looping: 16386 * 16387 * struct bpf_iter_num it; 16388 * int *p, x; 16389 * 16390 * bpf_iter_num_new(&it, 0, 10); 16391 * while ((p = bpf_iter_num_next(&t))) { 16392 * x = p; 16393 * while (x--) {} // <<-- infinite loop here 16394 * } 16395 * 16396 */ 16397 static bool iter_active_depths_differ(struct bpf_verifier_state *old, struct bpf_verifier_state *cur) 16398 { 16399 struct bpf_reg_state *slot, *cur_slot; 16400 struct bpf_func_state *state; 16401 int i, fr; 16402 16403 for (fr = old->curframe; fr >= 0; fr--) { 16404 state = old->frame[fr]; 16405 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) { 16406 if (state->stack[i].slot_type[0] != STACK_ITER) 16407 continue; 16408 16409 slot = &state->stack[i].spilled_ptr; 16410 if (slot->iter.state != BPF_ITER_STATE_ACTIVE) 16411 continue; 16412 16413 cur_slot = &cur->frame[fr]->stack[i].spilled_ptr; 16414 if (cur_slot->iter.depth != slot->iter.depth) 16415 return true; 16416 } 16417 } 16418 return false; 16419 } 16420 16421 static int is_state_visited(struct bpf_verifier_env *env, int insn_idx) 16422 { 16423 struct bpf_verifier_state_list *new_sl; 16424 struct bpf_verifier_state_list *sl, **pprev; 16425 struct bpf_verifier_state *cur = env->cur_state, *new; 16426 int i, j, err, states_cnt = 0; 16427 bool force_new_state = env->test_state_freq || is_force_checkpoint(env, insn_idx); 16428 bool add_new_state = force_new_state; 16429 16430 /* bpf progs typically have pruning point every 4 instructions 16431 * http://vger.kernel.org/bpfconf2019.html#session-1 16432 * Do not add new state for future pruning if the verifier hasn't seen 16433 * at least 2 jumps and at least 8 instructions. 16434 * This heuristics helps decrease 'total_states' and 'peak_states' metric. 16435 * In tests that amounts to up to 50% reduction into total verifier 16436 * memory consumption and 20% verifier time speedup. 16437 */ 16438 if (env->jmps_processed - env->prev_jmps_processed >= 2 && 16439 env->insn_processed - env->prev_insn_processed >= 8) 16440 add_new_state = true; 16441 16442 pprev = explored_state(env, insn_idx); 16443 sl = *pprev; 16444 16445 clean_live_states(env, insn_idx, cur); 16446 16447 while (sl) { 16448 states_cnt++; 16449 if (sl->state.insn_idx != insn_idx) 16450 goto next; 16451 16452 if (sl->state.branches) { 16453 struct bpf_func_state *frame = sl->state.frame[sl->state.curframe]; 16454 16455 if (frame->in_async_callback_fn && 16456 frame->async_entry_cnt != cur->frame[cur->curframe]->async_entry_cnt) { 16457 /* Different async_entry_cnt means that the verifier is 16458 * processing another entry into async callback. 16459 * Seeing the same state is not an indication of infinite 16460 * loop or infinite recursion. 16461 * But finding the same state doesn't mean that it's safe 16462 * to stop processing the current state. The previous state 16463 * hasn't yet reached bpf_exit, since state.branches > 0. 16464 * Checking in_async_callback_fn alone is not enough either. 16465 * Since the verifier still needs to catch infinite loops 16466 * inside async callbacks. 16467 */ 16468 goto skip_inf_loop_check; 16469 } 16470 /* BPF open-coded iterators loop detection is special. 16471 * states_maybe_looping() logic is too simplistic in detecting 16472 * states that *might* be equivalent, because it doesn't know 16473 * about ID remapping, so don't even perform it. 16474 * See process_iter_next_call() and iter_active_depths_differ() 16475 * for overview of the logic. When current and one of parent 16476 * states are detected as equivalent, it's a good thing: we prove 16477 * convergence and can stop simulating further iterations. 16478 * It's safe to assume that iterator loop will finish, taking into 16479 * account iter_next() contract of eventually returning 16480 * sticky NULL result. 16481 */ 16482 if (is_iter_next_insn(env, insn_idx)) { 16483 if (states_equal(env, &sl->state, cur)) { 16484 struct bpf_func_state *cur_frame; 16485 struct bpf_reg_state *iter_state, *iter_reg; 16486 int spi; 16487 16488 cur_frame = cur->frame[cur->curframe]; 16489 /* btf_check_iter_kfuncs() enforces that 16490 * iter state pointer is always the first arg 16491 */ 16492 iter_reg = &cur_frame->regs[BPF_REG_1]; 16493 /* current state is valid due to states_equal(), 16494 * so we can assume valid iter and reg state, 16495 * no need for extra (re-)validations 16496 */ 16497 spi = __get_spi(iter_reg->off + iter_reg->var_off.value); 16498 iter_state = &func(env, iter_reg)->stack[spi].spilled_ptr; 16499 if (iter_state->iter.state == BPF_ITER_STATE_ACTIVE) 16500 goto hit; 16501 } 16502 goto skip_inf_loop_check; 16503 } 16504 /* attempt to detect infinite loop to avoid unnecessary doomed work */ 16505 if (states_maybe_looping(&sl->state, cur) && 16506 states_equal(env, &sl->state, cur) && 16507 !iter_active_depths_differ(&sl->state, cur)) { 16508 verbose_linfo(env, insn_idx, "; "); 16509 verbose(env, "infinite loop detected at insn %d\n", insn_idx); 16510 return -EINVAL; 16511 } 16512 /* if the verifier is processing a loop, avoid adding new state 16513 * too often, since different loop iterations have distinct 16514 * states and may not help future pruning. 16515 * This threshold shouldn't be too low to make sure that 16516 * a loop with large bound will be rejected quickly. 16517 * The most abusive loop will be: 16518 * r1 += 1 16519 * if r1 < 1000000 goto pc-2 16520 * 1M insn_procssed limit / 100 == 10k peak states. 16521 * This threshold shouldn't be too high either, since states 16522 * at the end of the loop are likely to be useful in pruning. 16523 */ 16524 skip_inf_loop_check: 16525 if (!force_new_state && 16526 env->jmps_processed - env->prev_jmps_processed < 20 && 16527 env->insn_processed - env->prev_insn_processed < 100) 16528 add_new_state = false; 16529 goto miss; 16530 } 16531 if (states_equal(env, &sl->state, cur)) { 16532 hit: 16533 sl->hit_cnt++; 16534 /* reached equivalent register/stack state, 16535 * prune the search. 16536 * Registers read by the continuation are read by us. 16537 * If we have any write marks in env->cur_state, they 16538 * will prevent corresponding reads in the continuation 16539 * from reaching our parent (an explored_state). Our 16540 * own state will get the read marks recorded, but 16541 * they'll be immediately forgotten as we're pruning 16542 * this state and will pop a new one. 16543 */ 16544 err = propagate_liveness(env, &sl->state, cur); 16545 16546 /* if previous state reached the exit with precision and 16547 * current state is equivalent to it (except precsion marks) 16548 * the precision needs to be propagated back in 16549 * the current state. 16550 */ 16551 err = err ? : push_jmp_history(env, cur); 16552 err = err ? : propagate_precision(env, &sl->state); 16553 if (err) 16554 return err; 16555 return 1; 16556 } 16557 miss: 16558 /* when new state is not going to be added do not increase miss count. 16559 * Otherwise several loop iterations will remove the state 16560 * recorded earlier. The goal of these heuristics is to have 16561 * states from some iterations of the loop (some in the beginning 16562 * and some at the end) to help pruning. 16563 */ 16564 if (add_new_state) 16565 sl->miss_cnt++; 16566 /* heuristic to determine whether this state is beneficial 16567 * to keep checking from state equivalence point of view. 16568 * Higher numbers increase max_states_per_insn and verification time, 16569 * but do not meaningfully decrease insn_processed. 16570 */ 16571 if (sl->miss_cnt > sl->hit_cnt * 3 + 3) { 16572 /* the state is unlikely to be useful. Remove it to 16573 * speed up verification 16574 */ 16575 *pprev = sl->next; 16576 if (sl->state.frame[0]->regs[0].live & REG_LIVE_DONE) { 16577 u32 br = sl->state.branches; 16578 16579 WARN_ONCE(br, 16580 "BUG live_done but branches_to_explore %d\n", 16581 br); 16582 free_verifier_state(&sl->state, false); 16583 kfree(sl); 16584 env->peak_states--; 16585 } else { 16586 /* cannot free this state, since parentage chain may 16587 * walk it later. Add it for free_list instead to 16588 * be freed at the end of verification 16589 */ 16590 sl->next = env->free_list; 16591 env->free_list = sl; 16592 } 16593 sl = *pprev; 16594 continue; 16595 } 16596 next: 16597 pprev = &sl->next; 16598 sl = *pprev; 16599 } 16600 16601 if (env->max_states_per_insn < states_cnt) 16602 env->max_states_per_insn = states_cnt; 16603 16604 if (!env->bpf_capable && states_cnt > BPF_COMPLEXITY_LIMIT_STATES) 16605 return 0; 16606 16607 if (!add_new_state) 16608 return 0; 16609 16610 /* There were no equivalent states, remember the current one. 16611 * Technically the current state is not proven to be safe yet, 16612 * but it will either reach outer most bpf_exit (which means it's safe) 16613 * or it will be rejected. When there are no loops the verifier won't be 16614 * seeing this tuple (frame[0].callsite, frame[1].callsite, .. insn_idx) 16615 * again on the way to bpf_exit. 16616 * When looping the sl->state.branches will be > 0 and this state 16617 * will not be considered for equivalence until branches == 0. 16618 */ 16619 new_sl = kzalloc(sizeof(struct bpf_verifier_state_list), GFP_KERNEL); 16620 if (!new_sl) 16621 return -ENOMEM; 16622 env->total_states++; 16623 env->peak_states++; 16624 env->prev_jmps_processed = env->jmps_processed; 16625 env->prev_insn_processed = env->insn_processed; 16626 16627 /* forget precise markings we inherited, see __mark_chain_precision */ 16628 if (env->bpf_capable) 16629 mark_all_scalars_imprecise(env, cur); 16630 16631 /* add new state to the head of linked list */ 16632 new = &new_sl->state; 16633 err = copy_verifier_state(new, cur); 16634 if (err) { 16635 free_verifier_state(new, false); 16636 kfree(new_sl); 16637 return err; 16638 } 16639 new->insn_idx = insn_idx; 16640 WARN_ONCE(new->branches != 1, 16641 "BUG is_state_visited:branches_to_explore=%d insn %d\n", new->branches, insn_idx); 16642 16643 cur->parent = new; 16644 cur->first_insn_idx = insn_idx; 16645 clear_jmp_history(cur); 16646 new_sl->next = *explored_state(env, insn_idx); 16647 *explored_state(env, insn_idx) = new_sl; 16648 /* connect new state to parentage chain. Current frame needs all 16649 * registers connected. Only r6 - r9 of the callers are alive (pushed 16650 * to the stack implicitly by JITs) so in callers' frames connect just 16651 * r6 - r9 as an optimization. Callers will have r1 - r5 connected to 16652 * the state of the call instruction (with WRITTEN set), and r0 comes 16653 * from callee with its full parentage chain, anyway. 16654 */ 16655 /* clear write marks in current state: the writes we did are not writes 16656 * our child did, so they don't screen off its reads from us. 16657 * (There are no read marks in current state, because reads always mark 16658 * their parent and current state never has children yet. Only 16659 * explored_states can get read marks.) 16660 */ 16661 for (j = 0; j <= cur->curframe; j++) { 16662 for (i = j < cur->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++) 16663 cur->frame[j]->regs[i].parent = &new->frame[j]->regs[i]; 16664 for (i = 0; i < BPF_REG_FP; i++) 16665 cur->frame[j]->regs[i].live = REG_LIVE_NONE; 16666 } 16667 16668 /* all stack frames are accessible from callee, clear them all */ 16669 for (j = 0; j <= cur->curframe; j++) { 16670 struct bpf_func_state *frame = cur->frame[j]; 16671 struct bpf_func_state *newframe = new->frame[j]; 16672 16673 for (i = 0; i < frame->allocated_stack / BPF_REG_SIZE; i++) { 16674 frame->stack[i].spilled_ptr.live = REG_LIVE_NONE; 16675 frame->stack[i].spilled_ptr.parent = 16676 &newframe->stack[i].spilled_ptr; 16677 } 16678 } 16679 return 0; 16680 } 16681 16682 /* Return true if it's OK to have the same insn return a different type. */ 16683 static bool reg_type_mismatch_ok(enum bpf_reg_type type) 16684 { 16685 switch (base_type(type)) { 16686 case PTR_TO_CTX: 16687 case PTR_TO_SOCKET: 16688 case PTR_TO_SOCK_COMMON: 16689 case PTR_TO_TCP_SOCK: 16690 case PTR_TO_XDP_SOCK: 16691 case PTR_TO_BTF_ID: 16692 return false; 16693 default: 16694 return true; 16695 } 16696 } 16697 16698 /* If an instruction was previously used with particular pointer types, then we 16699 * need to be careful to avoid cases such as the below, where it may be ok 16700 * for one branch accessing the pointer, but not ok for the other branch: 16701 * 16702 * R1 = sock_ptr 16703 * goto X; 16704 * ... 16705 * R1 = some_other_valid_ptr; 16706 * goto X; 16707 * ... 16708 * R2 = *(u32 *)(R1 + 0); 16709 */ 16710 static bool reg_type_mismatch(enum bpf_reg_type src, enum bpf_reg_type prev) 16711 { 16712 return src != prev && (!reg_type_mismatch_ok(src) || 16713 !reg_type_mismatch_ok(prev)); 16714 } 16715 16716 static int save_aux_ptr_type(struct bpf_verifier_env *env, enum bpf_reg_type type, 16717 bool allow_trust_missmatch) 16718 { 16719 enum bpf_reg_type *prev_type = &env->insn_aux_data[env->insn_idx].ptr_type; 16720 16721 if (*prev_type == NOT_INIT) { 16722 /* Saw a valid insn 16723 * dst_reg = *(u32 *)(src_reg + off) 16724 * save type to validate intersecting paths 16725 */ 16726 *prev_type = type; 16727 } else if (reg_type_mismatch(type, *prev_type)) { 16728 /* Abuser program is trying to use the same insn 16729 * dst_reg = *(u32*) (src_reg + off) 16730 * with different pointer types: 16731 * src_reg == ctx in one branch and 16732 * src_reg == stack|map in some other branch. 16733 * Reject it. 16734 */ 16735 if (allow_trust_missmatch && 16736 base_type(type) == PTR_TO_BTF_ID && 16737 base_type(*prev_type) == PTR_TO_BTF_ID) { 16738 /* 16739 * Have to support a use case when one path through 16740 * the program yields TRUSTED pointer while another 16741 * is UNTRUSTED. Fallback to UNTRUSTED to generate 16742 * BPF_PROBE_MEM/BPF_PROBE_MEMSX. 16743 */ 16744 *prev_type = PTR_TO_BTF_ID | PTR_UNTRUSTED; 16745 } else { 16746 verbose(env, "same insn cannot be used with different pointers\n"); 16747 return -EINVAL; 16748 } 16749 } 16750 16751 return 0; 16752 } 16753 16754 static int do_check(struct bpf_verifier_env *env) 16755 { 16756 bool pop_log = !(env->log.level & BPF_LOG_LEVEL2); 16757 struct bpf_verifier_state *state = env->cur_state; 16758 struct bpf_insn *insns = env->prog->insnsi; 16759 struct bpf_reg_state *regs; 16760 int insn_cnt = env->prog->len; 16761 bool do_print_state = false; 16762 int prev_insn_idx = -1; 16763 16764 for (;;) { 16765 bool exception_exit = false; 16766 struct bpf_insn *insn; 16767 u8 class; 16768 int err; 16769 16770 env->prev_insn_idx = prev_insn_idx; 16771 if (env->insn_idx >= insn_cnt) { 16772 verbose(env, "invalid insn idx %d insn_cnt %d\n", 16773 env->insn_idx, insn_cnt); 16774 return -EFAULT; 16775 } 16776 16777 insn = &insns[env->insn_idx]; 16778 class = BPF_CLASS(insn->code); 16779 16780 if (++env->insn_processed > BPF_COMPLEXITY_LIMIT_INSNS) { 16781 verbose(env, 16782 "BPF program is too large. Processed %d insn\n", 16783 env->insn_processed); 16784 return -E2BIG; 16785 } 16786 16787 state->last_insn_idx = env->prev_insn_idx; 16788 16789 if (is_prune_point(env, env->insn_idx)) { 16790 err = is_state_visited(env, env->insn_idx); 16791 if (err < 0) 16792 return err; 16793 if (err == 1) { 16794 /* found equivalent state, can prune the search */ 16795 if (env->log.level & BPF_LOG_LEVEL) { 16796 if (do_print_state) 16797 verbose(env, "\nfrom %d to %d%s: safe\n", 16798 env->prev_insn_idx, env->insn_idx, 16799 env->cur_state->speculative ? 16800 " (speculative execution)" : ""); 16801 else 16802 verbose(env, "%d: safe\n", env->insn_idx); 16803 } 16804 goto process_bpf_exit; 16805 } 16806 } 16807 16808 if (is_jmp_point(env, env->insn_idx)) { 16809 err = push_jmp_history(env, state); 16810 if (err) 16811 return err; 16812 } 16813 16814 if (signal_pending(current)) 16815 return -EAGAIN; 16816 16817 if (need_resched()) 16818 cond_resched(); 16819 16820 if (env->log.level & BPF_LOG_LEVEL2 && do_print_state) { 16821 verbose(env, "\nfrom %d to %d%s:", 16822 env->prev_insn_idx, env->insn_idx, 16823 env->cur_state->speculative ? 16824 " (speculative execution)" : ""); 16825 print_verifier_state(env, state->frame[state->curframe], true); 16826 do_print_state = false; 16827 } 16828 16829 if (env->log.level & BPF_LOG_LEVEL) { 16830 const struct bpf_insn_cbs cbs = { 16831 .cb_call = disasm_kfunc_name, 16832 .cb_print = verbose, 16833 .private_data = env, 16834 }; 16835 16836 if (verifier_state_scratched(env)) 16837 print_insn_state(env, state->frame[state->curframe]); 16838 16839 verbose_linfo(env, env->insn_idx, "; "); 16840 env->prev_log_pos = env->log.end_pos; 16841 verbose(env, "%d: ", env->insn_idx); 16842 print_bpf_insn(&cbs, insn, env->allow_ptr_leaks); 16843 env->prev_insn_print_pos = env->log.end_pos - env->prev_log_pos; 16844 env->prev_log_pos = env->log.end_pos; 16845 } 16846 16847 if (bpf_prog_is_offloaded(env->prog->aux)) { 16848 err = bpf_prog_offload_verify_insn(env, env->insn_idx, 16849 env->prev_insn_idx); 16850 if (err) 16851 return err; 16852 } 16853 16854 regs = cur_regs(env); 16855 sanitize_mark_insn_seen(env); 16856 prev_insn_idx = env->insn_idx; 16857 16858 if (class == BPF_ALU || class == BPF_ALU64) { 16859 err = check_alu_op(env, insn); 16860 if (err) 16861 return err; 16862 16863 } else if (class == BPF_LDX) { 16864 enum bpf_reg_type src_reg_type; 16865 16866 /* check for reserved fields is already done */ 16867 16868 /* check src operand */ 16869 err = check_reg_arg(env, insn->src_reg, SRC_OP); 16870 if (err) 16871 return err; 16872 16873 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK); 16874 if (err) 16875 return err; 16876 16877 src_reg_type = regs[insn->src_reg].type; 16878 16879 /* check that memory (src_reg + off) is readable, 16880 * the state of dst_reg will be updated by this func 16881 */ 16882 err = check_mem_access(env, env->insn_idx, insn->src_reg, 16883 insn->off, BPF_SIZE(insn->code), 16884 BPF_READ, insn->dst_reg, false, 16885 BPF_MODE(insn->code) == BPF_MEMSX); 16886 if (err) 16887 return err; 16888 16889 err = save_aux_ptr_type(env, src_reg_type, true); 16890 if (err) 16891 return err; 16892 } else if (class == BPF_STX) { 16893 enum bpf_reg_type dst_reg_type; 16894 16895 if (BPF_MODE(insn->code) == BPF_ATOMIC) { 16896 err = check_atomic(env, env->insn_idx, insn); 16897 if (err) 16898 return err; 16899 env->insn_idx++; 16900 continue; 16901 } 16902 16903 if (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0) { 16904 verbose(env, "BPF_STX uses reserved fields\n"); 16905 return -EINVAL; 16906 } 16907 16908 /* check src1 operand */ 16909 err = check_reg_arg(env, insn->src_reg, SRC_OP); 16910 if (err) 16911 return err; 16912 /* check src2 operand */ 16913 err = check_reg_arg(env, insn->dst_reg, SRC_OP); 16914 if (err) 16915 return err; 16916 16917 dst_reg_type = regs[insn->dst_reg].type; 16918 16919 /* check that memory (dst_reg + off) is writeable */ 16920 err = check_mem_access(env, env->insn_idx, insn->dst_reg, 16921 insn->off, BPF_SIZE(insn->code), 16922 BPF_WRITE, insn->src_reg, false, false); 16923 if (err) 16924 return err; 16925 16926 err = save_aux_ptr_type(env, dst_reg_type, false); 16927 if (err) 16928 return err; 16929 } else if (class == BPF_ST) { 16930 enum bpf_reg_type dst_reg_type; 16931 16932 if (BPF_MODE(insn->code) != BPF_MEM || 16933 insn->src_reg != BPF_REG_0) { 16934 verbose(env, "BPF_ST uses reserved fields\n"); 16935 return -EINVAL; 16936 } 16937 /* check src operand */ 16938 err = check_reg_arg(env, insn->dst_reg, SRC_OP); 16939 if (err) 16940 return err; 16941 16942 dst_reg_type = regs[insn->dst_reg].type; 16943 16944 /* check that memory (dst_reg + off) is writeable */ 16945 err = check_mem_access(env, env->insn_idx, insn->dst_reg, 16946 insn->off, BPF_SIZE(insn->code), 16947 BPF_WRITE, -1, false, false); 16948 if (err) 16949 return err; 16950 16951 err = save_aux_ptr_type(env, dst_reg_type, false); 16952 if (err) 16953 return err; 16954 } else if (class == BPF_JMP || class == BPF_JMP32) { 16955 u8 opcode = BPF_OP(insn->code); 16956 16957 env->jmps_processed++; 16958 if (opcode == BPF_CALL) { 16959 if (BPF_SRC(insn->code) != BPF_K || 16960 (insn->src_reg != BPF_PSEUDO_KFUNC_CALL 16961 && insn->off != 0) || 16962 (insn->src_reg != BPF_REG_0 && 16963 insn->src_reg != BPF_PSEUDO_CALL && 16964 insn->src_reg != BPF_PSEUDO_KFUNC_CALL) || 16965 insn->dst_reg != BPF_REG_0 || 16966 class == BPF_JMP32) { 16967 verbose(env, "BPF_CALL uses reserved fields\n"); 16968 return -EINVAL; 16969 } 16970 16971 if (env->cur_state->active_lock.ptr) { 16972 if ((insn->src_reg == BPF_REG_0 && insn->imm != BPF_FUNC_spin_unlock) || 16973 (insn->src_reg == BPF_PSEUDO_CALL) || 16974 (insn->src_reg == BPF_PSEUDO_KFUNC_CALL && 16975 (insn->off != 0 || !is_bpf_graph_api_kfunc(insn->imm)))) { 16976 verbose(env, "function calls are not allowed while holding a lock\n"); 16977 return -EINVAL; 16978 } 16979 } 16980 if (insn->src_reg == BPF_PSEUDO_CALL) { 16981 err = check_func_call(env, insn, &env->insn_idx); 16982 } else if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) { 16983 err = check_kfunc_call(env, insn, &env->insn_idx); 16984 if (!err && is_bpf_throw_kfunc(insn)) { 16985 exception_exit = true; 16986 goto process_bpf_exit_full; 16987 } 16988 } else { 16989 err = check_helper_call(env, insn, &env->insn_idx); 16990 } 16991 if (err) 16992 return err; 16993 16994 mark_reg_scratched(env, BPF_REG_0); 16995 } else if (opcode == BPF_JA) { 16996 if (BPF_SRC(insn->code) != BPF_K || 16997 insn->src_reg != BPF_REG_0 || 16998 insn->dst_reg != BPF_REG_0 || 16999 (class == BPF_JMP && insn->imm != 0) || 17000 (class == BPF_JMP32 && insn->off != 0)) { 17001 verbose(env, "BPF_JA uses reserved fields\n"); 17002 return -EINVAL; 17003 } 17004 17005 if (class == BPF_JMP) 17006 env->insn_idx += insn->off + 1; 17007 else 17008 env->insn_idx += insn->imm + 1; 17009 continue; 17010 17011 } else if (opcode == BPF_EXIT) { 17012 if (BPF_SRC(insn->code) != BPF_K || 17013 insn->imm != 0 || 17014 insn->src_reg != BPF_REG_0 || 17015 insn->dst_reg != BPF_REG_0 || 17016 class == BPF_JMP32) { 17017 verbose(env, "BPF_EXIT uses reserved fields\n"); 17018 return -EINVAL; 17019 } 17020 process_bpf_exit_full: 17021 if (env->cur_state->active_lock.ptr && 17022 !in_rbtree_lock_required_cb(env)) { 17023 verbose(env, "bpf_spin_unlock is missing\n"); 17024 return -EINVAL; 17025 } 17026 17027 if (env->cur_state->active_rcu_lock && 17028 !in_rbtree_lock_required_cb(env)) { 17029 verbose(env, "bpf_rcu_read_unlock is missing\n"); 17030 return -EINVAL; 17031 } 17032 17033 /* We must do check_reference_leak here before 17034 * prepare_func_exit to handle the case when 17035 * state->curframe > 0, it may be a callback 17036 * function, for which reference_state must 17037 * match caller reference state when it exits. 17038 */ 17039 err = check_reference_leak(env, exception_exit); 17040 if (err) 17041 return err; 17042 17043 /* The side effect of the prepare_func_exit 17044 * which is being skipped is that it frees 17045 * bpf_func_state. Typically, process_bpf_exit 17046 * will only be hit with outermost exit. 17047 * copy_verifier_state in pop_stack will handle 17048 * freeing of any extra bpf_func_state left over 17049 * from not processing all nested function 17050 * exits. We also skip return code checks as 17051 * they are not needed for exceptional exits. 17052 */ 17053 if (exception_exit) 17054 goto process_bpf_exit; 17055 17056 if (state->curframe) { 17057 /* exit from nested function */ 17058 err = prepare_func_exit(env, &env->insn_idx); 17059 if (err) 17060 return err; 17061 do_print_state = true; 17062 continue; 17063 } 17064 17065 err = check_return_code(env, BPF_REG_0); 17066 if (err) 17067 return err; 17068 process_bpf_exit: 17069 mark_verifier_state_scratched(env); 17070 update_branch_counts(env, env->cur_state); 17071 err = pop_stack(env, &prev_insn_idx, 17072 &env->insn_idx, pop_log); 17073 if (err < 0) { 17074 if (err != -ENOENT) 17075 return err; 17076 break; 17077 } else { 17078 do_print_state = true; 17079 continue; 17080 } 17081 } else { 17082 err = check_cond_jmp_op(env, insn, &env->insn_idx); 17083 if (err) 17084 return err; 17085 } 17086 } else if (class == BPF_LD) { 17087 u8 mode = BPF_MODE(insn->code); 17088 17089 if (mode == BPF_ABS || mode == BPF_IND) { 17090 err = check_ld_abs(env, insn); 17091 if (err) 17092 return err; 17093 17094 } else if (mode == BPF_IMM) { 17095 err = check_ld_imm(env, insn); 17096 if (err) 17097 return err; 17098 17099 env->insn_idx++; 17100 sanitize_mark_insn_seen(env); 17101 } else { 17102 verbose(env, "invalid BPF_LD mode\n"); 17103 return -EINVAL; 17104 } 17105 } else { 17106 verbose(env, "unknown insn class %d\n", class); 17107 return -EINVAL; 17108 } 17109 17110 env->insn_idx++; 17111 } 17112 17113 return 0; 17114 } 17115 17116 static int find_btf_percpu_datasec(struct btf *btf) 17117 { 17118 const struct btf_type *t; 17119 const char *tname; 17120 int i, n; 17121 17122 /* 17123 * Both vmlinux and module each have their own ".data..percpu" 17124 * DATASECs in BTF. So for module's case, we need to skip vmlinux BTF 17125 * types to look at only module's own BTF types. 17126 */ 17127 n = btf_nr_types(btf); 17128 if (btf_is_module(btf)) 17129 i = btf_nr_types(btf_vmlinux); 17130 else 17131 i = 1; 17132 17133 for(; i < n; i++) { 17134 t = btf_type_by_id(btf, i); 17135 if (BTF_INFO_KIND(t->info) != BTF_KIND_DATASEC) 17136 continue; 17137 17138 tname = btf_name_by_offset(btf, t->name_off); 17139 if (!strcmp(tname, ".data..percpu")) 17140 return i; 17141 } 17142 17143 return -ENOENT; 17144 } 17145 17146 /* replace pseudo btf_id with kernel symbol address */ 17147 static int check_pseudo_btf_id(struct bpf_verifier_env *env, 17148 struct bpf_insn *insn, 17149 struct bpf_insn_aux_data *aux) 17150 { 17151 const struct btf_var_secinfo *vsi; 17152 const struct btf_type *datasec; 17153 struct btf_mod_pair *btf_mod; 17154 const struct btf_type *t; 17155 const char *sym_name; 17156 bool percpu = false; 17157 u32 type, id = insn->imm; 17158 struct btf *btf; 17159 s32 datasec_id; 17160 u64 addr; 17161 int i, btf_fd, err; 17162 17163 btf_fd = insn[1].imm; 17164 if (btf_fd) { 17165 btf = btf_get_by_fd(btf_fd); 17166 if (IS_ERR(btf)) { 17167 verbose(env, "invalid module BTF object FD specified.\n"); 17168 return -EINVAL; 17169 } 17170 } else { 17171 if (!btf_vmlinux) { 17172 verbose(env, "kernel is missing BTF, make sure CONFIG_DEBUG_INFO_BTF=y is specified in Kconfig.\n"); 17173 return -EINVAL; 17174 } 17175 btf = btf_vmlinux; 17176 btf_get(btf); 17177 } 17178 17179 t = btf_type_by_id(btf, id); 17180 if (!t) { 17181 verbose(env, "ldimm64 insn specifies invalid btf_id %d.\n", id); 17182 err = -ENOENT; 17183 goto err_put; 17184 } 17185 17186 if (!btf_type_is_var(t) && !btf_type_is_func(t)) { 17187 verbose(env, "pseudo btf_id %d in ldimm64 isn't KIND_VAR or KIND_FUNC\n", id); 17188 err = -EINVAL; 17189 goto err_put; 17190 } 17191 17192 sym_name = btf_name_by_offset(btf, t->name_off); 17193 addr = kallsyms_lookup_name(sym_name); 17194 if (!addr) { 17195 verbose(env, "ldimm64 failed to find the address for kernel symbol '%s'.\n", 17196 sym_name); 17197 err = -ENOENT; 17198 goto err_put; 17199 } 17200 insn[0].imm = (u32)addr; 17201 insn[1].imm = addr >> 32; 17202 17203 if (btf_type_is_func(t)) { 17204 aux->btf_var.reg_type = PTR_TO_MEM | MEM_RDONLY; 17205 aux->btf_var.mem_size = 0; 17206 goto check_btf; 17207 } 17208 17209 datasec_id = find_btf_percpu_datasec(btf); 17210 if (datasec_id > 0) { 17211 datasec = btf_type_by_id(btf, datasec_id); 17212 for_each_vsi(i, datasec, vsi) { 17213 if (vsi->type == id) { 17214 percpu = true; 17215 break; 17216 } 17217 } 17218 } 17219 17220 type = t->type; 17221 t = btf_type_skip_modifiers(btf, type, NULL); 17222 if (percpu) { 17223 aux->btf_var.reg_type = PTR_TO_BTF_ID | MEM_PERCPU; 17224 aux->btf_var.btf = btf; 17225 aux->btf_var.btf_id = type; 17226 } else if (!btf_type_is_struct(t)) { 17227 const struct btf_type *ret; 17228 const char *tname; 17229 u32 tsize; 17230 17231 /* resolve the type size of ksym. */ 17232 ret = btf_resolve_size(btf, t, &tsize); 17233 if (IS_ERR(ret)) { 17234 tname = btf_name_by_offset(btf, t->name_off); 17235 verbose(env, "ldimm64 unable to resolve the size of type '%s': %ld\n", 17236 tname, PTR_ERR(ret)); 17237 err = -EINVAL; 17238 goto err_put; 17239 } 17240 aux->btf_var.reg_type = PTR_TO_MEM | MEM_RDONLY; 17241 aux->btf_var.mem_size = tsize; 17242 } else { 17243 aux->btf_var.reg_type = PTR_TO_BTF_ID; 17244 aux->btf_var.btf = btf; 17245 aux->btf_var.btf_id = type; 17246 } 17247 check_btf: 17248 /* check whether we recorded this BTF (and maybe module) already */ 17249 for (i = 0; i < env->used_btf_cnt; i++) { 17250 if (env->used_btfs[i].btf == btf) { 17251 btf_put(btf); 17252 return 0; 17253 } 17254 } 17255 17256 if (env->used_btf_cnt >= MAX_USED_BTFS) { 17257 err = -E2BIG; 17258 goto err_put; 17259 } 17260 17261 btf_mod = &env->used_btfs[env->used_btf_cnt]; 17262 btf_mod->btf = btf; 17263 btf_mod->module = NULL; 17264 17265 /* if we reference variables from kernel module, bump its refcount */ 17266 if (btf_is_module(btf)) { 17267 btf_mod->module = btf_try_get_module(btf); 17268 if (!btf_mod->module) { 17269 err = -ENXIO; 17270 goto err_put; 17271 } 17272 } 17273 17274 env->used_btf_cnt++; 17275 17276 return 0; 17277 err_put: 17278 btf_put(btf); 17279 return err; 17280 } 17281 17282 static bool is_tracing_prog_type(enum bpf_prog_type type) 17283 { 17284 switch (type) { 17285 case BPF_PROG_TYPE_KPROBE: 17286 case BPF_PROG_TYPE_TRACEPOINT: 17287 case BPF_PROG_TYPE_PERF_EVENT: 17288 case BPF_PROG_TYPE_RAW_TRACEPOINT: 17289 case BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE: 17290 return true; 17291 default: 17292 return false; 17293 } 17294 } 17295 17296 static int check_map_prog_compatibility(struct bpf_verifier_env *env, 17297 struct bpf_map *map, 17298 struct bpf_prog *prog) 17299 17300 { 17301 enum bpf_prog_type prog_type = resolve_prog_type(prog); 17302 17303 if (btf_record_has_field(map->record, BPF_LIST_HEAD) || 17304 btf_record_has_field(map->record, BPF_RB_ROOT)) { 17305 if (is_tracing_prog_type(prog_type)) { 17306 verbose(env, "tracing progs cannot use bpf_{list_head,rb_root} yet\n"); 17307 return -EINVAL; 17308 } 17309 } 17310 17311 if (btf_record_has_field(map->record, BPF_SPIN_LOCK)) { 17312 if (prog_type == BPF_PROG_TYPE_SOCKET_FILTER) { 17313 verbose(env, "socket filter progs cannot use bpf_spin_lock yet\n"); 17314 return -EINVAL; 17315 } 17316 17317 if (is_tracing_prog_type(prog_type)) { 17318 verbose(env, "tracing progs cannot use bpf_spin_lock yet\n"); 17319 return -EINVAL; 17320 } 17321 } 17322 17323 if (btf_record_has_field(map->record, BPF_TIMER)) { 17324 if (is_tracing_prog_type(prog_type)) { 17325 verbose(env, "tracing progs cannot use bpf_timer yet\n"); 17326 return -EINVAL; 17327 } 17328 } 17329 17330 if ((bpf_prog_is_offloaded(prog->aux) || bpf_map_is_offloaded(map)) && 17331 !bpf_offload_prog_map_match(prog, map)) { 17332 verbose(env, "offload device mismatch between prog and map\n"); 17333 return -EINVAL; 17334 } 17335 17336 if (map->map_type == BPF_MAP_TYPE_STRUCT_OPS) { 17337 verbose(env, "bpf_struct_ops map cannot be used in prog\n"); 17338 return -EINVAL; 17339 } 17340 17341 if (prog->aux->sleepable) 17342 switch (map->map_type) { 17343 case BPF_MAP_TYPE_HASH: 17344 case BPF_MAP_TYPE_LRU_HASH: 17345 case BPF_MAP_TYPE_ARRAY: 17346 case BPF_MAP_TYPE_PERCPU_HASH: 17347 case BPF_MAP_TYPE_PERCPU_ARRAY: 17348 case BPF_MAP_TYPE_LRU_PERCPU_HASH: 17349 case BPF_MAP_TYPE_ARRAY_OF_MAPS: 17350 case BPF_MAP_TYPE_HASH_OF_MAPS: 17351 case BPF_MAP_TYPE_RINGBUF: 17352 case BPF_MAP_TYPE_USER_RINGBUF: 17353 case BPF_MAP_TYPE_INODE_STORAGE: 17354 case BPF_MAP_TYPE_SK_STORAGE: 17355 case BPF_MAP_TYPE_TASK_STORAGE: 17356 case BPF_MAP_TYPE_CGRP_STORAGE: 17357 break; 17358 default: 17359 verbose(env, 17360 "Sleepable programs can only use array, hash, ringbuf and local storage maps\n"); 17361 return -EINVAL; 17362 } 17363 17364 return 0; 17365 } 17366 17367 static bool bpf_map_is_cgroup_storage(struct bpf_map *map) 17368 { 17369 return (map->map_type == BPF_MAP_TYPE_CGROUP_STORAGE || 17370 map->map_type == BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE); 17371 } 17372 17373 /* find and rewrite pseudo imm in ld_imm64 instructions: 17374 * 17375 * 1. if it accesses map FD, replace it with actual map pointer. 17376 * 2. if it accesses btf_id of a VAR, replace it with pointer to the var. 17377 * 17378 * NOTE: btf_vmlinux is required for converting pseudo btf_id. 17379 */ 17380 static int resolve_pseudo_ldimm64(struct bpf_verifier_env *env) 17381 { 17382 struct bpf_insn *insn = env->prog->insnsi; 17383 int insn_cnt = env->prog->len; 17384 int i, j, err; 17385 17386 err = bpf_prog_calc_tag(env->prog); 17387 if (err) 17388 return err; 17389 17390 for (i = 0; i < insn_cnt; i++, insn++) { 17391 if (BPF_CLASS(insn->code) == BPF_LDX && 17392 ((BPF_MODE(insn->code) != BPF_MEM && BPF_MODE(insn->code) != BPF_MEMSX) || 17393 insn->imm != 0)) { 17394 verbose(env, "BPF_LDX uses reserved fields\n"); 17395 return -EINVAL; 17396 } 17397 17398 if (insn[0].code == (BPF_LD | BPF_IMM | BPF_DW)) { 17399 struct bpf_insn_aux_data *aux; 17400 struct bpf_map *map; 17401 struct fd f; 17402 u64 addr; 17403 u32 fd; 17404 17405 if (i == insn_cnt - 1 || insn[1].code != 0 || 17406 insn[1].dst_reg != 0 || insn[1].src_reg != 0 || 17407 insn[1].off != 0) { 17408 verbose(env, "invalid bpf_ld_imm64 insn\n"); 17409 return -EINVAL; 17410 } 17411 17412 if (insn[0].src_reg == 0) 17413 /* valid generic load 64-bit imm */ 17414 goto next_insn; 17415 17416 if (insn[0].src_reg == BPF_PSEUDO_BTF_ID) { 17417 aux = &env->insn_aux_data[i]; 17418 err = check_pseudo_btf_id(env, insn, aux); 17419 if (err) 17420 return err; 17421 goto next_insn; 17422 } 17423 17424 if (insn[0].src_reg == BPF_PSEUDO_FUNC) { 17425 aux = &env->insn_aux_data[i]; 17426 aux->ptr_type = PTR_TO_FUNC; 17427 goto next_insn; 17428 } 17429 17430 /* In final convert_pseudo_ld_imm64() step, this is 17431 * converted into regular 64-bit imm load insn. 17432 */ 17433 switch (insn[0].src_reg) { 17434 case BPF_PSEUDO_MAP_VALUE: 17435 case BPF_PSEUDO_MAP_IDX_VALUE: 17436 break; 17437 case BPF_PSEUDO_MAP_FD: 17438 case BPF_PSEUDO_MAP_IDX: 17439 if (insn[1].imm == 0) 17440 break; 17441 fallthrough; 17442 default: 17443 verbose(env, "unrecognized bpf_ld_imm64 insn\n"); 17444 return -EINVAL; 17445 } 17446 17447 switch (insn[0].src_reg) { 17448 case BPF_PSEUDO_MAP_IDX_VALUE: 17449 case BPF_PSEUDO_MAP_IDX: 17450 if (bpfptr_is_null(env->fd_array)) { 17451 verbose(env, "fd_idx without fd_array is invalid\n"); 17452 return -EPROTO; 17453 } 17454 if (copy_from_bpfptr_offset(&fd, env->fd_array, 17455 insn[0].imm * sizeof(fd), 17456 sizeof(fd))) 17457 return -EFAULT; 17458 break; 17459 default: 17460 fd = insn[0].imm; 17461 break; 17462 } 17463 17464 f = fdget(fd); 17465 map = __bpf_map_get(f); 17466 if (IS_ERR(map)) { 17467 verbose(env, "fd %d is not pointing to valid bpf_map\n", 17468 insn[0].imm); 17469 return PTR_ERR(map); 17470 } 17471 17472 err = check_map_prog_compatibility(env, map, env->prog); 17473 if (err) { 17474 fdput(f); 17475 return err; 17476 } 17477 17478 aux = &env->insn_aux_data[i]; 17479 if (insn[0].src_reg == BPF_PSEUDO_MAP_FD || 17480 insn[0].src_reg == BPF_PSEUDO_MAP_IDX) { 17481 addr = (unsigned long)map; 17482 } else { 17483 u32 off = insn[1].imm; 17484 17485 if (off >= BPF_MAX_VAR_OFF) { 17486 verbose(env, "direct value offset of %u is not allowed\n", off); 17487 fdput(f); 17488 return -EINVAL; 17489 } 17490 17491 if (!map->ops->map_direct_value_addr) { 17492 verbose(env, "no direct value access support for this map type\n"); 17493 fdput(f); 17494 return -EINVAL; 17495 } 17496 17497 err = map->ops->map_direct_value_addr(map, &addr, off); 17498 if (err) { 17499 verbose(env, "invalid access to map value pointer, value_size=%u off=%u\n", 17500 map->value_size, off); 17501 fdput(f); 17502 return err; 17503 } 17504 17505 aux->map_off = off; 17506 addr += off; 17507 } 17508 17509 insn[0].imm = (u32)addr; 17510 insn[1].imm = addr >> 32; 17511 17512 /* check whether we recorded this map already */ 17513 for (j = 0; j < env->used_map_cnt; j++) { 17514 if (env->used_maps[j] == map) { 17515 aux->map_index = j; 17516 fdput(f); 17517 goto next_insn; 17518 } 17519 } 17520 17521 if (env->used_map_cnt >= MAX_USED_MAPS) { 17522 fdput(f); 17523 return -E2BIG; 17524 } 17525 17526 /* hold the map. If the program is rejected by verifier, 17527 * the map will be released by release_maps() or it 17528 * will be used by the valid program until it's unloaded 17529 * and all maps are released in free_used_maps() 17530 */ 17531 bpf_map_inc(map); 17532 17533 aux->map_index = env->used_map_cnt; 17534 env->used_maps[env->used_map_cnt++] = map; 17535 17536 if (bpf_map_is_cgroup_storage(map) && 17537 bpf_cgroup_storage_assign(env->prog->aux, map)) { 17538 verbose(env, "only one cgroup storage of each type is allowed\n"); 17539 fdput(f); 17540 return -EBUSY; 17541 } 17542 17543 fdput(f); 17544 next_insn: 17545 insn++; 17546 i++; 17547 continue; 17548 } 17549 17550 /* Basic sanity check before we invest more work here. */ 17551 if (!bpf_opcode_in_insntable(insn->code)) { 17552 verbose(env, "unknown opcode %02x\n", insn->code); 17553 return -EINVAL; 17554 } 17555 } 17556 17557 /* now all pseudo BPF_LD_IMM64 instructions load valid 17558 * 'struct bpf_map *' into a register instead of user map_fd. 17559 * These pointers will be used later by verifier to validate map access. 17560 */ 17561 return 0; 17562 } 17563 17564 /* drop refcnt of maps used by the rejected program */ 17565 static void release_maps(struct bpf_verifier_env *env) 17566 { 17567 __bpf_free_used_maps(env->prog->aux, env->used_maps, 17568 env->used_map_cnt); 17569 } 17570 17571 /* drop refcnt of maps used by the rejected program */ 17572 static void release_btfs(struct bpf_verifier_env *env) 17573 { 17574 __bpf_free_used_btfs(env->prog->aux, env->used_btfs, 17575 env->used_btf_cnt); 17576 } 17577 17578 /* convert pseudo BPF_LD_IMM64 into generic BPF_LD_IMM64 */ 17579 static void convert_pseudo_ld_imm64(struct bpf_verifier_env *env) 17580 { 17581 struct bpf_insn *insn = env->prog->insnsi; 17582 int insn_cnt = env->prog->len; 17583 int i; 17584 17585 for (i = 0; i < insn_cnt; i++, insn++) { 17586 if (insn->code != (BPF_LD | BPF_IMM | BPF_DW)) 17587 continue; 17588 if (insn->src_reg == BPF_PSEUDO_FUNC) 17589 continue; 17590 insn->src_reg = 0; 17591 } 17592 } 17593 17594 /* single env->prog->insni[off] instruction was replaced with the range 17595 * insni[off, off + cnt). Adjust corresponding insn_aux_data by copying 17596 * [0, off) and [off, end) to new locations, so the patched range stays zero 17597 */ 17598 static void adjust_insn_aux_data(struct bpf_verifier_env *env, 17599 struct bpf_insn_aux_data *new_data, 17600 struct bpf_prog *new_prog, u32 off, u32 cnt) 17601 { 17602 struct bpf_insn_aux_data *old_data = env->insn_aux_data; 17603 struct bpf_insn *insn = new_prog->insnsi; 17604 u32 old_seen = old_data[off].seen; 17605 u32 prog_len; 17606 int i; 17607 17608 /* aux info at OFF always needs adjustment, no matter fast path 17609 * (cnt == 1) is taken or not. There is no guarantee INSN at OFF is the 17610 * original insn at old prog. 17611 */ 17612 old_data[off].zext_dst = insn_has_def32(env, insn + off + cnt - 1); 17613 17614 if (cnt == 1) 17615 return; 17616 prog_len = new_prog->len; 17617 17618 memcpy(new_data, old_data, sizeof(struct bpf_insn_aux_data) * off); 17619 memcpy(new_data + off + cnt - 1, old_data + off, 17620 sizeof(struct bpf_insn_aux_data) * (prog_len - off - cnt + 1)); 17621 for (i = off; i < off + cnt - 1; i++) { 17622 /* Expand insni[off]'s seen count to the patched range. */ 17623 new_data[i].seen = old_seen; 17624 new_data[i].zext_dst = insn_has_def32(env, insn + i); 17625 } 17626 env->insn_aux_data = new_data; 17627 vfree(old_data); 17628 } 17629 17630 static void adjust_subprog_starts(struct bpf_verifier_env *env, u32 off, u32 len) 17631 { 17632 int i; 17633 17634 if (len == 1) 17635 return; 17636 /* NOTE: fake 'exit' subprog should be updated as well. */ 17637 for (i = 0; i <= env->subprog_cnt; i++) { 17638 if (env->subprog_info[i].start <= off) 17639 continue; 17640 env->subprog_info[i].start += len - 1; 17641 } 17642 } 17643 17644 static void adjust_poke_descs(struct bpf_prog *prog, u32 off, u32 len) 17645 { 17646 struct bpf_jit_poke_descriptor *tab = prog->aux->poke_tab; 17647 int i, sz = prog->aux->size_poke_tab; 17648 struct bpf_jit_poke_descriptor *desc; 17649 17650 for (i = 0; i < sz; i++) { 17651 desc = &tab[i]; 17652 if (desc->insn_idx <= off) 17653 continue; 17654 desc->insn_idx += len - 1; 17655 } 17656 } 17657 17658 static struct bpf_prog *bpf_patch_insn_data(struct bpf_verifier_env *env, u32 off, 17659 const struct bpf_insn *patch, u32 len) 17660 { 17661 struct bpf_prog *new_prog; 17662 struct bpf_insn_aux_data *new_data = NULL; 17663 17664 if (len > 1) { 17665 new_data = vzalloc(array_size(env->prog->len + len - 1, 17666 sizeof(struct bpf_insn_aux_data))); 17667 if (!new_data) 17668 return NULL; 17669 } 17670 17671 new_prog = bpf_patch_insn_single(env->prog, off, patch, len); 17672 if (IS_ERR(new_prog)) { 17673 if (PTR_ERR(new_prog) == -ERANGE) 17674 verbose(env, 17675 "insn %d cannot be patched due to 16-bit range\n", 17676 env->insn_aux_data[off].orig_idx); 17677 vfree(new_data); 17678 return NULL; 17679 } 17680 adjust_insn_aux_data(env, new_data, new_prog, off, len); 17681 adjust_subprog_starts(env, off, len); 17682 adjust_poke_descs(new_prog, off, len); 17683 return new_prog; 17684 } 17685 17686 static int adjust_subprog_starts_after_remove(struct bpf_verifier_env *env, 17687 u32 off, u32 cnt) 17688 { 17689 int i, j; 17690 17691 /* find first prog starting at or after off (first to remove) */ 17692 for (i = 0; i < env->subprog_cnt; i++) 17693 if (env->subprog_info[i].start >= off) 17694 break; 17695 /* find first prog starting at or after off + cnt (first to stay) */ 17696 for (j = i; j < env->subprog_cnt; j++) 17697 if (env->subprog_info[j].start >= off + cnt) 17698 break; 17699 /* if j doesn't start exactly at off + cnt, we are just removing 17700 * the front of previous prog 17701 */ 17702 if (env->subprog_info[j].start != off + cnt) 17703 j--; 17704 17705 if (j > i) { 17706 struct bpf_prog_aux *aux = env->prog->aux; 17707 int move; 17708 17709 /* move fake 'exit' subprog as well */ 17710 move = env->subprog_cnt + 1 - j; 17711 17712 memmove(env->subprog_info + i, 17713 env->subprog_info + j, 17714 sizeof(*env->subprog_info) * move); 17715 env->subprog_cnt -= j - i; 17716 17717 /* remove func_info */ 17718 if (aux->func_info) { 17719 move = aux->func_info_cnt - j; 17720 17721 memmove(aux->func_info + i, 17722 aux->func_info + j, 17723 sizeof(*aux->func_info) * move); 17724 aux->func_info_cnt -= j - i; 17725 /* func_info->insn_off is set after all code rewrites, 17726 * in adjust_btf_func() - no need to adjust 17727 */ 17728 } 17729 } else { 17730 /* convert i from "first prog to remove" to "first to adjust" */ 17731 if (env->subprog_info[i].start == off) 17732 i++; 17733 } 17734 17735 /* update fake 'exit' subprog as well */ 17736 for (; i <= env->subprog_cnt; i++) 17737 env->subprog_info[i].start -= cnt; 17738 17739 return 0; 17740 } 17741 17742 static int bpf_adj_linfo_after_remove(struct bpf_verifier_env *env, u32 off, 17743 u32 cnt) 17744 { 17745 struct bpf_prog *prog = env->prog; 17746 u32 i, l_off, l_cnt, nr_linfo; 17747 struct bpf_line_info *linfo; 17748 17749 nr_linfo = prog->aux->nr_linfo; 17750 if (!nr_linfo) 17751 return 0; 17752 17753 linfo = prog->aux->linfo; 17754 17755 /* find first line info to remove, count lines to be removed */ 17756 for (i = 0; i < nr_linfo; i++) 17757 if (linfo[i].insn_off >= off) 17758 break; 17759 17760 l_off = i; 17761 l_cnt = 0; 17762 for (; i < nr_linfo; i++) 17763 if (linfo[i].insn_off < off + cnt) 17764 l_cnt++; 17765 else 17766 break; 17767 17768 /* First live insn doesn't match first live linfo, it needs to "inherit" 17769 * last removed linfo. prog is already modified, so prog->len == off 17770 * means no live instructions after (tail of the program was removed). 17771 */ 17772 if (prog->len != off && l_cnt && 17773 (i == nr_linfo || linfo[i].insn_off != off + cnt)) { 17774 l_cnt--; 17775 linfo[--i].insn_off = off + cnt; 17776 } 17777 17778 /* remove the line info which refer to the removed instructions */ 17779 if (l_cnt) { 17780 memmove(linfo + l_off, linfo + i, 17781 sizeof(*linfo) * (nr_linfo - i)); 17782 17783 prog->aux->nr_linfo -= l_cnt; 17784 nr_linfo = prog->aux->nr_linfo; 17785 } 17786 17787 /* pull all linfo[i].insn_off >= off + cnt in by cnt */ 17788 for (i = l_off; i < nr_linfo; i++) 17789 linfo[i].insn_off -= cnt; 17790 17791 /* fix up all subprogs (incl. 'exit') which start >= off */ 17792 for (i = 0; i <= env->subprog_cnt; i++) 17793 if (env->subprog_info[i].linfo_idx > l_off) { 17794 /* program may have started in the removed region but 17795 * may not be fully removed 17796 */ 17797 if (env->subprog_info[i].linfo_idx >= l_off + l_cnt) 17798 env->subprog_info[i].linfo_idx -= l_cnt; 17799 else 17800 env->subprog_info[i].linfo_idx = l_off; 17801 } 17802 17803 return 0; 17804 } 17805 17806 static int verifier_remove_insns(struct bpf_verifier_env *env, u32 off, u32 cnt) 17807 { 17808 struct bpf_insn_aux_data *aux_data = env->insn_aux_data; 17809 unsigned int orig_prog_len = env->prog->len; 17810 int err; 17811 17812 if (bpf_prog_is_offloaded(env->prog->aux)) 17813 bpf_prog_offload_remove_insns(env, off, cnt); 17814 17815 err = bpf_remove_insns(env->prog, off, cnt); 17816 if (err) 17817 return err; 17818 17819 err = adjust_subprog_starts_after_remove(env, off, cnt); 17820 if (err) 17821 return err; 17822 17823 err = bpf_adj_linfo_after_remove(env, off, cnt); 17824 if (err) 17825 return err; 17826 17827 memmove(aux_data + off, aux_data + off + cnt, 17828 sizeof(*aux_data) * (orig_prog_len - off - cnt)); 17829 17830 return 0; 17831 } 17832 17833 /* The verifier does more data flow analysis than llvm and will not 17834 * explore branches that are dead at run time. Malicious programs can 17835 * have dead code too. Therefore replace all dead at-run-time code 17836 * with 'ja -1'. 17837 * 17838 * Just nops are not optimal, e.g. if they would sit at the end of the 17839 * program and through another bug we would manage to jump there, then 17840 * we'd execute beyond program memory otherwise. Returning exception 17841 * code also wouldn't work since we can have subprogs where the dead 17842 * code could be located. 17843 */ 17844 static void sanitize_dead_code(struct bpf_verifier_env *env) 17845 { 17846 struct bpf_insn_aux_data *aux_data = env->insn_aux_data; 17847 struct bpf_insn trap = BPF_JMP_IMM(BPF_JA, 0, 0, -1); 17848 struct bpf_insn *insn = env->prog->insnsi; 17849 const int insn_cnt = env->prog->len; 17850 int i; 17851 17852 for (i = 0; i < insn_cnt; i++) { 17853 if (aux_data[i].seen) 17854 continue; 17855 memcpy(insn + i, &trap, sizeof(trap)); 17856 aux_data[i].zext_dst = false; 17857 } 17858 } 17859 17860 static bool insn_is_cond_jump(u8 code) 17861 { 17862 u8 op; 17863 17864 op = BPF_OP(code); 17865 if (BPF_CLASS(code) == BPF_JMP32) 17866 return op != BPF_JA; 17867 17868 if (BPF_CLASS(code) != BPF_JMP) 17869 return false; 17870 17871 return op != BPF_JA && op != BPF_EXIT && op != BPF_CALL; 17872 } 17873 17874 static void opt_hard_wire_dead_code_branches(struct bpf_verifier_env *env) 17875 { 17876 struct bpf_insn_aux_data *aux_data = env->insn_aux_data; 17877 struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0); 17878 struct bpf_insn *insn = env->prog->insnsi; 17879 const int insn_cnt = env->prog->len; 17880 int i; 17881 17882 for (i = 0; i < insn_cnt; i++, insn++) { 17883 if (!insn_is_cond_jump(insn->code)) 17884 continue; 17885 17886 if (!aux_data[i + 1].seen) 17887 ja.off = insn->off; 17888 else if (!aux_data[i + 1 + insn->off].seen) 17889 ja.off = 0; 17890 else 17891 continue; 17892 17893 if (bpf_prog_is_offloaded(env->prog->aux)) 17894 bpf_prog_offload_replace_insn(env, i, &ja); 17895 17896 memcpy(insn, &ja, sizeof(ja)); 17897 } 17898 } 17899 17900 static int opt_remove_dead_code(struct bpf_verifier_env *env) 17901 { 17902 struct bpf_insn_aux_data *aux_data = env->insn_aux_data; 17903 int insn_cnt = env->prog->len; 17904 int i, err; 17905 17906 for (i = 0; i < insn_cnt; i++) { 17907 int j; 17908 17909 j = 0; 17910 while (i + j < insn_cnt && !aux_data[i + j].seen) 17911 j++; 17912 if (!j) 17913 continue; 17914 17915 err = verifier_remove_insns(env, i, j); 17916 if (err) 17917 return err; 17918 insn_cnt = env->prog->len; 17919 } 17920 17921 return 0; 17922 } 17923 17924 static int opt_remove_nops(struct bpf_verifier_env *env) 17925 { 17926 const struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0); 17927 struct bpf_insn *insn = env->prog->insnsi; 17928 int insn_cnt = env->prog->len; 17929 int i, err; 17930 17931 for (i = 0; i < insn_cnt; i++) { 17932 if (memcmp(&insn[i], &ja, sizeof(ja))) 17933 continue; 17934 17935 err = verifier_remove_insns(env, i, 1); 17936 if (err) 17937 return err; 17938 insn_cnt--; 17939 i--; 17940 } 17941 17942 return 0; 17943 } 17944 17945 static int opt_subreg_zext_lo32_rnd_hi32(struct bpf_verifier_env *env, 17946 const union bpf_attr *attr) 17947 { 17948 struct bpf_insn *patch, zext_patch[2], rnd_hi32_patch[4]; 17949 struct bpf_insn_aux_data *aux = env->insn_aux_data; 17950 int i, patch_len, delta = 0, len = env->prog->len; 17951 struct bpf_insn *insns = env->prog->insnsi; 17952 struct bpf_prog *new_prog; 17953 bool rnd_hi32; 17954 17955 rnd_hi32 = attr->prog_flags & BPF_F_TEST_RND_HI32; 17956 zext_patch[1] = BPF_ZEXT_REG(0); 17957 rnd_hi32_patch[1] = BPF_ALU64_IMM(BPF_MOV, BPF_REG_AX, 0); 17958 rnd_hi32_patch[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_AX, 32); 17959 rnd_hi32_patch[3] = BPF_ALU64_REG(BPF_OR, 0, BPF_REG_AX); 17960 for (i = 0; i < len; i++) { 17961 int adj_idx = i + delta; 17962 struct bpf_insn insn; 17963 int load_reg; 17964 17965 insn = insns[adj_idx]; 17966 load_reg = insn_def_regno(&insn); 17967 if (!aux[adj_idx].zext_dst) { 17968 u8 code, class; 17969 u32 imm_rnd; 17970 17971 if (!rnd_hi32) 17972 continue; 17973 17974 code = insn.code; 17975 class = BPF_CLASS(code); 17976 if (load_reg == -1) 17977 continue; 17978 17979 /* NOTE: arg "reg" (the fourth one) is only used for 17980 * BPF_STX + SRC_OP, so it is safe to pass NULL 17981 * here. 17982 */ 17983 if (is_reg64(env, &insn, load_reg, NULL, DST_OP)) { 17984 if (class == BPF_LD && 17985 BPF_MODE(code) == BPF_IMM) 17986 i++; 17987 continue; 17988 } 17989 17990 /* ctx load could be transformed into wider load. */ 17991 if (class == BPF_LDX && 17992 aux[adj_idx].ptr_type == PTR_TO_CTX) 17993 continue; 17994 17995 imm_rnd = get_random_u32(); 17996 rnd_hi32_patch[0] = insn; 17997 rnd_hi32_patch[1].imm = imm_rnd; 17998 rnd_hi32_patch[3].dst_reg = load_reg; 17999 patch = rnd_hi32_patch; 18000 patch_len = 4; 18001 goto apply_patch_buffer; 18002 } 18003 18004 /* Add in an zero-extend instruction if a) the JIT has requested 18005 * it or b) it's a CMPXCHG. 18006 * 18007 * The latter is because: BPF_CMPXCHG always loads a value into 18008 * R0, therefore always zero-extends. However some archs' 18009 * equivalent instruction only does this load when the 18010 * comparison is successful. This detail of CMPXCHG is 18011 * orthogonal to the general zero-extension behaviour of the 18012 * CPU, so it's treated independently of bpf_jit_needs_zext. 18013 */ 18014 if (!bpf_jit_needs_zext() && !is_cmpxchg_insn(&insn)) 18015 continue; 18016 18017 /* Zero-extension is done by the caller. */ 18018 if (bpf_pseudo_kfunc_call(&insn)) 18019 continue; 18020 18021 if (WARN_ON(load_reg == -1)) { 18022 verbose(env, "verifier bug. zext_dst is set, but no reg is defined\n"); 18023 return -EFAULT; 18024 } 18025 18026 zext_patch[0] = insn; 18027 zext_patch[1].dst_reg = load_reg; 18028 zext_patch[1].src_reg = load_reg; 18029 patch = zext_patch; 18030 patch_len = 2; 18031 apply_patch_buffer: 18032 new_prog = bpf_patch_insn_data(env, adj_idx, patch, patch_len); 18033 if (!new_prog) 18034 return -ENOMEM; 18035 env->prog = new_prog; 18036 insns = new_prog->insnsi; 18037 aux = env->insn_aux_data; 18038 delta += patch_len - 1; 18039 } 18040 18041 return 0; 18042 } 18043 18044 /* convert load instructions that access fields of a context type into a 18045 * sequence of instructions that access fields of the underlying structure: 18046 * struct __sk_buff -> struct sk_buff 18047 * struct bpf_sock_ops -> struct sock 18048 */ 18049 static int convert_ctx_accesses(struct bpf_verifier_env *env) 18050 { 18051 const struct bpf_verifier_ops *ops = env->ops; 18052 int i, cnt, size, ctx_field_size, delta = 0; 18053 const int insn_cnt = env->prog->len; 18054 struct bpf_insn insn_buf[16], *insn; 18055 u32 target_size, size_default, off; 18056 struct bpf_prog *new_prog; 18057 enum bpf_access_type type; 18058 bool is_narrower_load; 18059 18060 if (ops->gen_prologue || env->seen_direct_write) { 18061 if (!ops->gen_prologue) { 18062 verbose(env, "bpf verifier is misconfigured\n"); 18063 return -EINVAL; 18064 } 18065 cnt = ops->gen_prologue(insn_buf, env->seen_direct_write, 18066 env->prog); 18067 if (cnt >= ARRAY_SIZE(insn_buf)) { 18068 verbose(env, "bpf verifier is misconfigured\n"); 18069 return -EINVAL; 18070 } else if (cnt) { 18071 new_prog = bpf_patch_insn_data(env, 0, insn_buf, cnt); 18072 if (!new_prog) 18073 return -ENOMEM; 18074 18075 env->prog = new_prog; 18076 delta += cnt - 1; 18077 } 18078 } 18079 18080 if (bpf_prog_is_offloaded(env->prog->aux)) 18081 return 0; 18082 18083 insn = env->prog->insnsi + delta; 18084 18085 for (i = 0; i < insn_cnt; i++, insn++) { 18086 bpf_convert_ctx_access_t convert_ctx_access; 18087 u8 mode; 18088 18089 if (insn->code == (BPF_LDX | BPF_MEM | BPF_B) || 18090 insn->code == (BPF_LDX | BPF_MEM | BPF_H) || 18091 insn->code == (BPF_LDX | BPF_MEM | BPF_W) || 18092 insn->code == (BPF_LDX | BPF_MEM | BPF_DW) || 18093 insn->code == (BPF_LDX | BPF_MEMSX | BPF_B) || 18094 insn->code == (BPF_LDX | BPF_MEMSX | BPF_H) || 18095 insn->code == (BPF_LDX | BPF_MEMSX | BPF_W)) { 18096 type = BPF_READ; 18097 } else if (insn->code == (BPF_STX | BPF_MEM | BPF_B) || 18098 insn->code == (BPF_STX | BPF_MEM | BPF_H) || 18099 insn->code == (BPF_STX | BPF_MEM | BPF_W) || 18100 insn->code == (BPF_STX | BPF_MEM | BPF_DW) || 18101 insn->code == (BPF_ST | BPF_MEM | BPF_B) || 18102 insn->code == (BPF_ST | BPF_MEM | BPF_H) || 18103 insn->code == (BPF_ST | BPF_MEM | BPF_W) || 18104 insn->code == (BPF_ST | BPF_MEM | BPF_DW)) { 18105 type = BPF_WRITE; 18106 } else { 18107 continue; 18108 } 18109 18110 if (type == BPF_WRITE && 18111 env->insn_aux_data[i + delta].sanitize_stack_spill) { 18112 struct bpf_insn patch[] = { 18113 *insn, 18114 BPF_ST_NOSPEC(), 18115 }; 18116 18117 cnt = ARRAY_SIZE(patch); 18118 new_prog = bpf_patch_insn_data(env, i + delta, patch, cnt); 18119 if (!new_prog) 18120 return -ENOMEM; 18121 18122 delta += cnt - 1; 18123 env->prog = new_prog; 18124 insn = new_prog->insnsi + i + delta; 18125 continue; 18126 } 18127 18128 switch ((int)env->insn_aux_data[i + delta].ptr_type) { 18129 case PTR_TO_CTX: 18130 if (!ops->convert_ctx_access) 18131 continue; 18132 convert_ctx_access = ops->convert_ctx_access; 18133 break; 18134 case PTR_TO_SOCKET: 18135 case PTR_TO_SOCK_COMMON: 18136 convert_ctx_access = bpf_sock_convert_ctx_access; 18137 break; 18138 case PTR_TO_TCP_SOCK: 18139 convert_ctx_access = bpf_tcp_sock_convert_ctx_access; 18140 break; 18141 case PTR_TO_XDP_SOCK: 18142 convert_ctx_access = bpf_xdp_sock_convert_ctx_access; 18143 break; 18144 case PTR_TO_BTF_ID: 18145 case PTR_TO_BTF_ID | PTR_UNTRUSTED: 18146 /* PTR_TO_BTF_ID | MEM_ALLOC always has a valid lifetime, unlike 18147 * PTR_TO_BTF_ID, and an active ref_obj_id, but the same cannot 18148 * be said once it is marked PTR_UNTRUSTED, hence we must handle 18149 * any faults for loads into such types. BPF_WRITE is disallowed 18150 * for this case. 18151 */ 18152 case PTR_TO_BTF_ID | MEM_ALLOC | PTR_UNTRUSTED: 18153 if (type == BPF_READ) { 18154 if (BPF_MODE(insn->code) == BPF_MEM) 18155 insn->code = BPF_LDX | BPF_PROBE_MEM | 18156 BPF_SIZE((insn)->code); 18157 else 18158 insn->code = BPF_LDX | BPF_PROBE_MEMSX | 18159 BPF_SIZE((insn)->code); 18160 env->prog->aux->num_exentries++; 18161 } 18162 continue; 18163 default: 18164 continue; 18165 } 18166 18167 ctx_field_size = env->insn_aux_data[i + delta].ctx_field_size; 18168 size = BPF_LDST_BYTES(insn); 18169 mode = BPF_MODE(insn->code); 18170 18171 /* If the read access is a narrower load of the field, 18172 * convert to a 4/8-byte load, to minimum program type specific 18173 * convert_ctx_access changes. If conversion is successful, 18174 * we will apply proper mask to the result. 18175 */ 18176 is_narrower_load = size < ctx_field_size; 18177 size_default = bpf_ctx_off_adjust_machine(ctx_field_size); 18178 off = insn->off; 18179 if (is_narrower_load) { 18180 u8 size_code; 18181 18182 if (type == BPF_WRITE) { 18183 verbose(env, "bpf verifier narrow ctx access misconfigured\n"); 18184 return -EINVAL; 18185 } 18186 18187 size_code = BPF_H; 18188 if (ctx_field_size == 4) 18189 size_code = BPF_W; 18190 else if (ctx_field_size == 8) 18191 size_code = BPF_DW; 18192 18193 insn->off = off & ~(size_default - 1); 18194 insn->code = BPF_LDX | BPF_MEM | size_code; 18195 } 18196 18197 target_size = 0; 18198 cnt = convert_ctx_access(type, insn, insn_buf, env->prog, 18199 &target_size); 18200 if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf) || 18201 (ctx_field_size && !target_size)) { 18202 verbose(env, "bpf verifier is misconfigured\n"); 18203 return -EINVAL; 18204 } 18205 18206 if (is_narrower_load && size < target_size) { 18207 u8 shift = bpf_ctx_narrow_access_offset( 18208 off, size, size_default) * 8; 18209 if (shift && cnt + 1 >= ARRAY_SIZE(insn_buf)) { 18210 verbose(env, "bpf verifier narrow ctx load misconfigured\n"); 18211 return -EINVAL; 18212 } 18213 if (ctx_field_size <= 4) { 18214 if (shift) 18215 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_RSH, 18216 insn->dst_reg, 18217 shift); 18218 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg, 18219 (1 << size * 8) - 1); 18220 } else { 18221 if (shift) 18222 insn_buf[cnt++] = BPF_ALU64_IMM(BPF_RSH, 18223 insn->dst_reg, 18224 shift); 18225 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg, 18226 (1ULL << size * 8) - 1); 18227 } 18228 } 18229 if (mode == BPF_MEMSX) 18230 insn_buf[cnt++] = BPF_RAW_INSN(BPF_ALU64 | BPF_MOV | BPF_X, 18231 insn->dst_reg, insn->dst_reg, 18232 size * 8, 0); 18233 18234 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 18235 if (!new_prog) 18236 return -ENOMEM; 18237 18238 delta += cnt - 1; 18239 18240 /* keep walking new program and skip insns we just inserted */ 18241 env->prog = new_prog; 18242 insn = new_prog->insnsi + i + delta; 18243 } 18244 18245 return 0; 18246 } 18247 18248 static int jit_subprogs(struct bpf_verifier_env *env) 18249 { 18250 struct bpf_prog *prog = env->prog, **func, *tmp; 18251 int i, j, subprog_start, subprog_end = 0, len, subprog; 18252 struct bpf_map *map_ptr; 18253 struct bpf_insn *insn; 18254 void *old_bpf_func; 18255 int err, num_exentries; 18256 18257 if (env->subprog_cnt <= 1) 18258 return 0; 18259 18260 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) { 18261 if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn)) 18262 continue; 18263 18264 /* Upon error here we cannot fall back to interpreter but 18265 * need a hard reject of the program. Thus -EFAULT is 18266 * propagated in any case. 18267 */ 18268 subprog = find_subprog(env, i + insn->imm + 1); 18269 if (subprog < 0) { 18270 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n", 18271 i + insn->imm + 1); 18272 return -EFAULT; 18273 } 18274 /* temporarily remember subprog id inside insn instead of 18275 * aux_data, since next loop will split up all insns into funcs 18276 */ 18277 insn->off = subprog; 18278 /* remember original imm in case JIT fails and fallback 18279 * to interpreter will be needed 18280 */ 18281 env->insn_aux_data[i].call_imm = insn->imm; 18282 /* point imm to __bpf_call_base+1 from JITs point of view */ 18283 insn->imm = 1; 18284 if (bpf_pseudo_func(insn)) 18285 /* jit (e.g. x86_64) may emit fewer instructions 18286 * if it learns a u32 imm is the same as a u64 imm. 18287 * Force a non zero here. 18288 */ 18289 insn[1].imm = 1; 18290 } 18291 18292 err = bpf_prog_alloc_jited_linfo(prog); 18293 if (err) 18294 goto out_undo_insn; 18295 18296 err = -ENOMEM; 18297 func = kcalloc(env->subprog_cnt, sizeof(prog), GFP_KERNEL); 18298 if (!func) 18299 goto out_undo_insn; 18300 18301 for (i = 0; i < env->subprog_cnt; i++) { 18302 subprog_start = subprog_end; 18303 subprog_end = env->subprog_info[i + 1].start; 18304 18305 len = subprog_end - subprog_start; 18306 /* bpf_prog_run() doesn't call subprogs directly, 18307 * hence main prog stats include the runtime of subprogs. 18308 * subprogs don't have IDs and not reachable via prog_get_next_id 18309 * func[i]->stats will never be accessed and stays NULL 18310 */ 18311 func[i] = bpf_prog_alloc_no_stats(bpf_prog_size(len), GFP_USER); 18312 if (!func[i]) 18313 goto out_free; 18314 memcpy(func[i]->insnsi, &prog->insnsi[subprog_start], 18315 len * sizeof(struct bpf_insn)); 18316 func[i]->type = prog->type; 18317 func[i]->len = len; 18318 if (bpf_prog_calc_tag(func[i])) 18319 goto out_free; 18320 func[i]->is_func = 1; 18321 func[i]->aux->func_idx = i; 18322 /* Below members will be freed only at prog->aux */ 18323 func[i]->aux->btf = prog->aux->btf; 18324 func[i]->aux->func_info = prog->aux->func_info; 18325 func[i]->aux->func_info_cnt = prog->aux->func_info_cnt; 18326 func[i]->aux->poke_tab = prog->aux->poke_tab; 18327 func[i]->aux->size_poke_tab = prog->aux->size_poke_tab; 18328 18329 for (j = 0; j < prog->aux->size_poke_tab; j++) { 18330 struct bpf_jit_poke_descriptor *poke; 18331 18332 poke = &prog->aux->poke_tab[j]; 18333 if (poke->insn_idx < subprog_end && 18334 poke->insn_idx >= subprog_start) 18335 poke->aux = func[i]->aux; 18336 } 18337 18338 func[i]->aux->name[0] = 'F'; 18339 func[i]->aux->stack_depth = env->subprog_info[i].stack_depth; 18340 func[i]->jit_requested = 1; 18341 func[i]->blinding_requested = prog->blinding_requested; 18342 func[i]->aux->kfunc_tab = prog->aux->kfunc_tab; 18343 func[i]->aux->kfunc_btf_tab = prog->aux->kfunc_btf_tab; 18344 func[i]->aux->linfo = prog->aux->linfo; 18345 func[i]->aux->nr_linfo = prog->aux->nr_linfo; 18346 func[i]->aux->jited_linfo = prog->aux->jited_linfo; 18347 func[i]->aux->linfo_idx = env->subprog_info[i].linfo_idx; 18348 num_exentries = 0; 18349 insn = func[i]->insnsi; 18350 for (j = 0; j < func[i]->len; j++, insn++) { 18351 if (BPF_CLASS(insn->code) == BPF_LDX && 18352 (BPF_MODE(insn->code) == BPF_PROBE_MEM || 18353 BPF_MODE(insn->code) == BPF_PROBE_MEMSX)) 18354 num_exentries++; 18355 } 18356 func[i]->aux->num_exentries = num_exentries; 18357 func[i]->aux->tail_call_reachable = env->subprog_info[i].tail_call_reachable; 18358 func[i]->aux->exception_cb = env->subprog_info[i].is_exception_cb; 18359 if (!i) 18360 func[i]->aux->exception_boundary = env->seen_exception; 18361 func[i] = bpf_int_jit_compile(func[i]); 18362 if (!func[i]->jited) { 18363 err = -ENOTSUPP; 18364 goto out_free; 18365 } 18366 cond_resched(); 18367 } 18368 18369 /* at this point all bpf functions were successfully JITed 18370 * now populate all bpf_calls with correct addresses and 18371 * run last pass of JIT 18372 */ 18373 for (i = 0; i < env->subprog_cnt; i++) { 18374 insn = func[i]->insnsi; 18375 for (j = 0; j < func[i]->len; j++, insn++) { 18376 if (bpf_pseudo_func(insn)) { 18377 subprog = insn->off; 18378 insn[0].imm = (u32)(long)func[subprog]->bpf_func; 18379 insn[1].imm = ((u64)(long)func[subprog]->bpf_func) >> 32; 18380 continue; 18381 } 18382 if (!bpf_pseudo_call(insn)) 18383 continue; 18384 subprog = insn->off; 18385 insn->imm = BPF_CALL_IMM(func[subprog]->bpf_func); 18386 } 18387 18388 /* we use the aux data to keep a list of the start addresses 18389 * of the JITed images for each function in the program 18390 * 18391 * for some architectures, such as powerpc64, the imm field 18392 * might not be large enough to hold the offset of the start 18393 * address of the callee's JITed image from __bpf_call_base 18394 * 18395 * in such cases, we can lookup the start address of a callee 18396 * by using its subprog id, available from the off field of 18397 * the call instruction, as an index for this list 18398 */ 18399 func[i]->aux->func = func; 18400 func[i]->aux->func_cnt = env->subprog_cnt - env->hidden_subprog_cnt; 18401 func[i]->aux->real_func_cnt = env->subprog_cnt; 18402 } 18403 for (i = 0; i < env->subprog_cnt; i++) { 18404 old_bpf_func = func[i]->bpf_func; 18405 tmp = bpf_int_jit_compile(func[i]); 18406 if (tmp != func[i] || func[i]->bpf_func != old_bpf_func) { 18407 verbose(env, "JIT doesn't support bpf-to-bpf calls\n"); 18408 err = -ENOTSUPP; 18409 goto out_free; 18410 } 18411 cond_resched(); 18412 } 18413 18414 /* finally lock prog and jit images for all functions and 18415 * populate kallsysm. Begin at the first subprogram, since 18416 * bpf_prog_load will add the kallsyms for the main program. 18417 */ 18418 for (i = 1; i < env->subprog_cnt; i++) { 18419 bpf_prog_lock_ro(func[i]); 18420 bpf_prog_kallsyms_add(func[i]); 18421 } 18422 18423 /* Last step: make now unused interpreter insns from main 18424 * prog consistent for later dump requests, so they can 18425 * later look the same as if they were interpreted only. 18426 */ 18427 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) { 18428 if (bpf_pseudo_func(insn)) { 18429 insn[0].imm = env->insn_aux_data[i].call_imm; 18430 insn[1].imm = insn->off; 18431 insn->off = 0; 18432 continue; 18433 } 18434 if (!bpf_pseudo_call(insn)) 18435 continue; 18436 insn->off = env->insn_aux_data[i].call_imm; 18437 subprog = find_subprog(env, i + insn->off + 1); 18438 insn->imm = subprog; 18439 } 18440 18441 prog->jited = 1; 18442 prog->bpf_func = func[0]->bpf_func; 18443 prog->jited_len = func[0]->jited_len; 18444 prog->aux->extable = func[0]->aux->extable; 18445 prog->aux->num_exentries = func[0]->aux->num_exentries; 18446 prog->aux->func = func; 18447 prog->aux->func_cnt = env->subprog_cnt - env->hidden_subprog_cnt; 18448 prog->aux->real_func_cnt = env->subprog_cnt; 18449 prog->aux->bpf_exception_cb = (void *)func[env->exception_callback_subprog]->bpf_func; 18450 prog->aux->exception_boundary = func[0]->aux->exception_boundary; 18451 bpf_prog_jit_attempt_done(prog); 18452 return 0; 18453 out_free: 18454 /* We failed JIT'ing, so at this point we need to unregister poke 18455 * descriptors from subprogs, so that kernel is not attempting to 18456 * patch it anymore as we're freeing the subprog JIT memory. 18457 */ 18458 for (i = 0; i < prog->aux->size_poke_tab; i++) { 18459 map_ptr = prog->aux->poke_tab[i].tail_call.map; 18460 map_ptr->ops->map_poke_untrack(map_ptr, prog->aux); 18461 } 18462 /* At this point we're guaranteed that poke descriptors are not 18463 * live anymore. We can just unlink its descriptor table as it's 18464 * released with the main prog. 18465 */ 18466 for (i = 0; i < env->subprog_cnt; i++) { 18467 if (!func[i]) 18468 continue; 18469 func[i]->aux->poke_tab = NULL; 18470 bpf_jit_free(func[i]); 18471 } 18472 kfree(func); 18473 out_undo_insn: 18474 /* cleanup main prog to be interpreted */ 18475 prog->jit_requested = 0; 18476 prog->blinding_requested = 0; 18477 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) { 18478 if (!bpf_pseudo_call(insn)) 18479 continue; 18480 insn->off = 0; 18481 insn->imm = env->insn_aux_data[i].call_imm; 18482 } 18483 bpf_prog_jit_attempt_done(prog); 18484 return err; 18485 } 18486 18487 static int fixup_call_args(struct bpf_verifier_env *env) 18488 { 18489 #ifndef CONFIG_BPF_JIT_ALWAYS_ON 18490 struct bpf_prog *prog = env->prog; 18491 struct bpf_insn *insn = prog->insnsi; 18492 bool has_kfunc_call = bpf_prog_has_kfunc_call(prog); 18493 int i, depth; 18494 #endif 18495 int err = 0; 18496 18497 if (env->prog->jit_requested && 18498 !bpf_prog_is_offloaded(env->prog->aux)) { 18499 err = jit_subprogs(env); 18500 if (err == 0) 18501 return 0; 18502 if (err == -EFAULT) 18503 return err; 18504 } 18505 #ifndef CONFIG_BPF_JIT_ALWAYS_ON 18506 if (has_kfunc_call) { 18507 verbose(env, "calling kernel functions are not allowed in non-JITed programs\n"); 18508 return -EINVAL; 18509 } 18510 if (env->subprog_cnt > 1 && env->prog->aux->tail_call_reachable) { 18511 /* When JIT fails the progs with bpf2bpf calls and tail_calls 18512 * have to be rejected, since interpreter doesn't support them yet. 18513 */ 18514 verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n"); 18515 return -EINVAL; 18516 } 18517 for (i = 0; i < prog->len; i++, insn++) { 18518 if (bpf_pseudo_func(insn)) { 18519 /* When JIT fails the progs with callback calls 18520 * have to be rejected, since interpreter doesn't support them yet. 18521 */ 18522 verbose(env, "callbacks are not allowed in non-JITed programs\n"); 18523 return -EINVAL; 18524 } 18525 18526 if (!bpf_pseudo_call(insn)) 18527 continue; 18528 depth = get_callee_stack_depth(env, insn, i); 18529 if (depth < 0) 18530 return depth; 18531 bpf_patch_call_args(insn, depth); 18532 } 18533 err = 0; 18534 #endif 18535 return err; 18536 } 18537 18538 /* replace a generic kfunc with a specialized version if necessary */ 18539 static void specialize_kfunc(struct bpf_verifier_env *env, 18540 u32 func_id, u16 offset, unsigned long *addr) 18541 { 18542 struct bpf_prog *prog = env->prog; 18543 bool seen_direct_write; 18544 void *xdp_kfunc; 18545 bool is_rdonly; 18546 18547 if (bpf_dev_bound_kfunc_id(func_id)) { 18548 xdp_kfunc = bpf_dev_bound_resolve_kfunc(prog, func_id); 18549 if (xdp_kfunc) { 18550 *addr = (unsigned long)xdp_kfunc; 18551 return; 18552 } 18553 /* fallback to default kfunc when not supported by netdev */ 18554 } 18555 18556 if (offset) 18557 return; 18558 18559 if (func_id == special_kfunc_list[KF_bpf_dynptr_from_skb]) { 18560 seen_direct_write = env->seen_direct_write; 18561 is_rdonly = !may_access_direct_pkt_data(env, NULL, BPF_WRITE); 18562 18563 if (is_rdonly) 18564 *addr = (unsigned long)bpf_dynptr_from_skb_rdonly; 18565 18566 /* restore env->seen_direct_write to its original value, since 18567 * may_access_direct_pkt_data mutates it 18568 */ 18569 env->seen_direct_write = seen_direct_write; 18570 } 18571 } 18572 18573 static void __fixup_collection_insert_kfunc(struct bpf_insn_aux_data *insn_aux, 18574 u16 struct_meta_reg, 18575 u16 node_offset_reg, 18576 struct bpf_insn *insn, 18577 struct bpf_insn *insn_buf, 18578 int *cnt) 18579 { 18580 struct btf_struct_meta *kptr_struct_meta = insn_aux->kptr_struct_meta; 18581 struct bpf_insn addr[2] = { BPF_LD_IMM64(struct_meta_reg, (long)kptr_struct_meta) }; 18582 18583 insn_buf[0] = addr[0]; 18584 insn_buf[1] = addr[1]; 18585 insn_buf[2] = BPF_MOV64_IMM(node_offset_reg, insn_aux->insert_off); 18586 insn_buf[3] = *insn; 18587 *cnt = 4; 18588 } 18589 18590 static int fixup_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn, 18591 struct bpf_insn *insn_buf, int insn_idx, int *cnt) 18592 { 18593 const struct bpf_kfunc_desc *desc; 18594 18595 if (!insn->imm) { 18596 verbose(env, "invalid kernel function call not eliminated in verifier pass\n"); 18597 return -EINVAL; 18598 } 18599 18600 *cnt = 0; 18601 18602 /* insn->imm has the btf func_id. Replace it with an offset relative to 18603 * __bpf_call_base, unless the JIT needs to call functions that are 18604 * further than 32 bits away (bpf_jit_supports_far_kfunc_call()). 18605 */ 18606 desc = find_kfunc_desc(env->prog, insn->imm, insn->off); 18607 if (!desc) { 18608 verbose(env, "verifier internal error: kernel function descriptor not found for func_id %u\n", 18609 insn->imm); 18610 return -EFAULT; 18611 } 18612 18613 if (!bpf_jit_supports_far_kfunc_call()) 18614 insn->imm = BPF_CALL_IMM(desc->addr); 18615 if (insn->off) 18616 return 0; 18617 if (desc->func_id == special_kfunc_list[KF_bpf_obj_new_impl] || 18618 desc->func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl]) { 18619 struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta; 18620 struct bpf_insn addr[2] = { BPF_LD_IMM64(BPF_REG_2, (long)kptr_struct_meta) }; 18621 u64 obj_new_size = env->insn_aux_data[insn_idx].obj_new_size; 18622 18623 if (desc->func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl] && kptr_struct_meta) { 18624 verbose(env, "verifier internal error: NULL kptr_struct_meta expected at insn_idx %d\n", 18625 insn_idx); 18626 return -EFAULT; 18627 } 18628 18629 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_1, obj_new_size); 18630 insn_buf[1] = addr[0]; 18631 insn_buf[2] = addr[1]; 18632 insn_buf[3] = *insn; 18633 *cnt = 4; 18634 } else if (desc->func_id == special_kfunc_list[KF_bpf_obj_drop_impl] || 18635 desc->func_id == special_kfunc_list[KF_bpf_percpu_obj_drop_impl] || 18636 desc->func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl]) { 18637 struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta; 18638 struct bpf_insn addr[2] = { BPF_LD_IMM64(BPF_REG_2, (long)kptr_struct_meta) }; 18639 18640 if (desc->func_id == special_kfunc_list[KF_bpf_percpu_obj_drop_impl] && kptr_struct_meta) { 18641 verbose(env, "verifier internal error: NULL kptr_struct_meta expected at insn_idx %d\n", 18642 insn_idx); 18643 return -EFAULT; 18644 } 18645 18646 if (desc->func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl] && 18647 !kptr_struct_meta) { 18648 verbose(env, "verifier internal error: kptr_struct_meta expected at insn_idx %d\n", 18649 insn_idx); 18650 return -EFAULT; 18651 } 18652 18653 insn_buf[0] = addr[0]; 18654 insn_buf[1] = addr[1]; 18655 insn_buf[2] = *insn; 18656 *cnt = 3; 18657 } else if (desc->func_id == special_kfunc_list[KF_bpf_list_push_back_impl] || 18658 desc->func_id == special_kfunc_list[KF_bpf_list_push_front_impl] || 18659 desc->func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) { 18660 struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta; 18661 int struct_meta_reg = BPF_REG_3; 18662 int node_offset_reg = BPF_REG_4; 18663 18664 /* rbtree_add has extra 'less' arg, so args-to-fixup are in diff regs */ 18665 if (desc->func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) { 18666 struct_meta_reg = BPF_REG_4; 18667 node_offset_reg = BPF_REG_5; 18668 } 18669 18670 if (!kptr_struct_meta) { 18671 verbose(env, "verifier internal error: kptr_struct_meta expected at insn_idx %d\n", 18672 insn_idx); 18673 return -EFAULT; 18674 } 18675 18676 __fixup_collection_insert_kfunc(&env->insn_aux_data[insn_idx], struct_meta_reg, 18677 node_offset_reg, insn, insn_buf, cnt); 18678 } else if (desc->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx] || 18679 desc->func_id == special_kfunc_list[KF_bpf_rdonly_cast]) { 18680 insn_buf[0] = BPF_MOV64_REG(BPF_REG_0, BPF_REG_1); 18681 *cnt = 1; 18682 } 18683 return 0; 18684 } 18685 18686 /* The function requires that first instruction in 'patch' is insnsi[prog->len - 1] */ 18687 static int add_hidden_subprog(struct bpf_verifier_env *env, struct bpf_insn *patch, int len) 18688 { 18689 struct bpf_subprog_info *info = env->subprog_info; 18690 int cnt = env->subprog_cnt; 18691 struct bpf_prog *prog; 18692 18693 /* We only reserve one slot for hidden subprogs in subprog_info. */ 18694 if (env->hidden_subprog_cnt) { 18695 verbose(env, "verifier internal error: only one hidden subprog supported\n"); 18696 return -EFAULT; 18697 } 18698 /* We're not patching any existing instruction, just appending the new 18699 * ones for the hidden subprog. Hence all of the adjustment operations 18700 * in bpf_patch_insn_data are no-ops. 18701 */ 18702 prog = bpf_patch_insn_data(env, env->prog->len - 1, patch, len); 18703 if (!prog) 18704 return -ENOMEM; 18705 env->prog = prog; 18706 info[cnt + 1].start = info[cnt].start; 18707 info[cnt].start = prog->len - len + 1; 18708 env->subprog_cnt++; 18709 env->hidden_subprog_cnt++; 18710 return 0; 18711 } 18712 18713 /* Do various post-verification rewrites in a single program pass. 18714 * These rewrites simplify JIT and interpreter implementations. 18715 */ 18716 static int do_misc_fixups(struct bpf_verifier_env *env) 18717 { 18718 struct bpf_prog *prog = env->prog; 18719 enum bpf_attach_type eatype = prog->expected_attach_type; 18720 enum bpf_prog_type prog_type = resolve_prog_type(prog); 18721 struct bpf_insn *insn = prog->insnsi; 18722 const struct bpf_func_proto *fn; 18723 const int insn_cnt = prog->len; 18724 const struct bpf_map_ops *ops; 18725 struct bpf_insn_aux_data *aux; 18726 struct bpf_insn insn_buf[16]; 18727 struct bpf_prog *new_prog; 18728 struct bpf_map *map_ptr; 18729 int i, ret, cnt, delta = 0; 18730 18731 if (env->seen_exception && !env->exception_callback_subprog) { 18732 struct bpf_insn patch[] = { 18733 env->prog->insnsi[insn_cnt - 1], 18734 BPF_MOV64_REG(BPF_REG_0, BPF_REG_1), 18735 BPF_EXIT_INSN(), 18736 }; 18737 18738 ret = add_hidden_subprog(env, patch, ARRAY_SIZE(patch)); 18739 if (ret < 0) 18740 return ret; 18741 prog = env->prog; 18742 insn = prog->insnsi; 18743 18744 env->exception_callback_subprog = env->subprog_cnt - 1; 18745 /* Don't update insn_cnt, as add_hidden_subprog always appends insns */ 18746 env->subprog_info[env->exception_callback_subprog].is_cb = true; 18747 env->subprog_info[env->exception_callback_subprog].is_async_cb = true; 18748 env->subprog_info[env->exception_callback_subprog].is_exception_cb = true; 18749 } 18750 18751 for (i = 0; i < insn_cnt; i++, insn++) { 18752 /* Make divide-by-zero exceptions impossible. */ 18753 if (insn->code == (BPF_ALU64 | BPF_MOD | BPF_X) || 18754 insn->code == (BPF_ALU64 | BPF_DIV | BPF_X) || 18755 insn->code == (BPF_ALU | BPF_MOD | BPF_X) || 18756 insn->code == (BPF_ALU | BPF_DIV | BPF_X)) { 18757 bool is64 = BPF_CLASS(insn->code) == BPF_ALU64; 18758 bool isdiv = BPF_OP(insn->code) == BPF_DIV; 18759 struct bpf_insn *patchlet; 18760 struct bpf_insn chk_and_div[] = { 18761 /* [R,W]x div 0 -> 0 */ 18762 BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) | 18763 BPF_JNE | BPF_K, insn->src_reg, 18764 0, 2, 0), 18765 BPF_ALU32_REG(BPF_XOR, insn->dst_reg, insn->dst_reg), 18766 BPF_JMP_IMM(BPF_JA, 0, 0, 1), 18767 *insn, 18768 }; 18769 struct bpf_insn chk_and_mod[] = { 18770 /* [R,W]x mod 0 -> [R,W]x */ 18771 BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) | 18772 BPF_JEQ | BPF_K, insn->src_reg, 18773 0, 1 + (is64 ? 0 : 1), 0), 18774 *insn, 18775 BPF_JMP_IMM(BPF_JA, 0, 0, 1), 18776 BPF_MOV32_REG(insn->dst_reg, insn->dst_reg), 18777 }; 18778 18779 patchlet = isdiv ? chk_and_div : chk_and_mod; 18780 cnt = isdiv ? ARRAY_SIZE(chk_and_div) : 18781 ARRAY_SIZE(chk_and_mod) - (is64 ? 2 : 0); 18782 18783 new_prog = bpf_patch_insn_data(env, i + delta, patchlet, cnt); 18784 if (!new_prog) 18785 return -ENOMEM; 18786 18787 delta += cnt - 1; 18788 env->prog = prog = new_prog; 18789 insn = new_prog->insnsi + i + delta; 18790 continue; 18791 } 18792 18793 /* Implement LD_ABS and LD_IND with a rewrite, if supported by the program type. */ 18794 if (BPF_CLASS(insn->code) == BPF_LD && 18795 (BPF_MODE(insn->code) == BPF_ABS || 18796 BPF_MODE(insn->code) == BPF_IND)) { 18797 cnt = env->ops->gen_ld_abs(insn, insn_buf); 18798 if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf)) { 18799 verbose(env, "bpf verifier is misconfigured\n"); 18800 return -EINVAL; 18801 } 18802 18803 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 18804 if (!new_prog) 18805 return -ENOMEM; 18806 18807 delta += cnt - 1; 18808 env->prog = prog = new_prog; 18809 insn = new_prog->insnsi + i + delta; 18810 continue; 18811 } 18812 18813 /* Rewrite pointer arithmetic to mitigate speculation attacks. */ 18814 if (insn->code == (BPF_ALU64 | BPF_ADD | BPF_X) || 18815 insn->code == (BPF_ALU64 | BPF_SUB | BPF_X)) { 18816 const u8 code_add = BPF_ALU64 | BPF_ADD | BPF_X; 18817 const u8 code_sub = BPF_ALU64 | BPF_SUB | BPF_X; 18818 struct bpf_insn *patch = &insn_buf[0]; 18819 bool issrc, isneg, isimm; 18820 u32 off_reg; 18821 18822 aux = &env->insn_aux_data[i + delta]; 18823 if (!aux->alu_state || 18824 aux->alu_state == BPF_ALU_NON_POINTER) 18825 continue; 18826 18827 isneg = aux->alu_state & BPF_ALU_NEG_VALUE; 18828 issrc = (aux->alu_state & BPF_ALU_SANITIZE) == 18829 BPF_ALU_SANITIZE_SRC; 18830 isimm = aux->alu_state & BPF_ALU_IMMEDIATE; 18831 18832 off_reg = issrc ? insn->src_reg : insn->dst_reg; 18833 if (isimm) { 18834 *patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit); 18835 } else { 18836 if (isneg) 18837 *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1); 18838 *patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit); 18839 *patch++ = BPF_ALU64_REG(BPF_SUB, BPF_REG_AX, off_reg); 18840 *patch++ = BPF_ALU64_REG(BPF_OR, BPF_REG_AX, off_reg); 18841 *patch++ = BPF_ALU64_IMM(BPF_NEG, BPF_REG_AX, 0); 18842 *patch++ = BPF_ALU64_IMM(BPF_ARSH, BPF_REG_AX, 63); 18843 *patch++ = BPF_ALU64_REG(BPF_AND, BPF_REG_AX, off_reg); 18844 } 18845 if (!issrc) 18846 *patch++ = BPF_MOV64_REG(insn->dst_reg, insn->src_reg); 18847 insn->src_reg = BPF_REG_AX; 18848 if (isneg) 18849 insn->code = insn->code == code_add ? 18850 code_sub : code_add; 18851 *patch++ = *insn; 18852 if (issrc && isneg && !isimm) 18853 *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1); 18854 cnt = patch - insn_buf; 18855 18856 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 18857 if (!new_prog) 18858 return -ENOMEM; 18859 18860 delta += cnt - 1; 18861 env->prog = prog = new_prog; 18862 insn = new_prog->insnsi + i + delta; 18863 continue; 18864 } 18865 18866 if (insn->code != (BPF_JMP | BPF_CALL)) 18867 continue; 18868 if (insn->src_reg == BPF_PSEUDO_CALL) 18869 continue; 18870 if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) { 18871 ret = fixup_kfunc_call(env, insn, insn_buf, i + delta, &cnt); 18872 if (ret) 18873 return ret; 18874 if (cnt == 0) 18875 continue; 18876 18877 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 18878 if (!new_prog) 18879 return -ENOMEM; 18880 18881 delta += cnt - 1; 18882 env->prog = prog = new_prog; 18883 insn = new_prog->insnsi + i + delta; 18884 continue; 18885 } 18886 18887 if (insn->imm == BPF_FUNC_get_route_realm) 18888 prog->dst_needed = 1; 18889 if (insn->imm == BPF_FUNC_get_prandom_u32) 18890 bpf_user_rnd_init_once(); 18891 if (insn->imm == BPF_FUNC_override_return) 18892 prog->kprobe_override = 1; 18893 if (insn->imm == BPF_FUNC_tail_call) { 18894 /* If we tail call into other programs, we 18895 * cannot make any assumptions since they can 18896 * be replaced dynamically during runtime in 18897 * the program array. 18898 */ 18899 prog->cb_access = 1; 18900 if (!allow_tail_call_in_subprogs(env)) 18901 prog->aux->stack_depth = MAX_BPF_STACK; 18902 prog->aux->max_pkt_offset = MAX_PACKET_OFF; 18903 18904 /* mark bpf_tail_call as different opcode to avoid 18905 * conditional branch in the interpreter for every normal 18906 * call and to prevent accidental JITing by JIT compiler 18907 * that doesn't support bpf_tail_call yet 18908 */ 18909 insn->imm = 0; 18910 insn->code = BPF_JMP | BPF_TAIL_CALL; 18911 18912 aux = &env->insn_aux_data[i + delta]; 18913 if (env->bpf_capable && !prog->blinding_requested && 18914 prog->jit_requested && 18915 !bpf_map_key_poisoned(aux) && 18916 !bpf_map_ptr_poisoned(aux) && 18917 !bpf_map_ptr_unpriv(aux)) { 18918 struct bpf_jit_poke_descriptor desc = { 18919 .reason = BPF_POKE_REASON_TAIL_CALL, 18920 .tail_call.map = BPF_MAP_PTR(aux->map_ptr_state), 18921 .tail_call.key = bpf_map_key_immediate(aux), 18922 .insn_idx = i + delta, 18923 }; 18924 18925 ret = bpf_jit_add_poke_descriptor(prog, &desc); 18926 if (ret < 0) { 18927 verbose(env, "adding tail call poke descriptor failed\n"); 18928 return ret; 18929 } 18930 18931 insn->imm = ret + 1; 18932 continue; 18933 } 18934 18935 if (!bpf_map_ptr_unpriv(aux)) 18936 continue; 18937 18938 /* instead of changing every JIT dealing with tail_call 18939 * emit two extra insns: 18940 * if (index >= max_entries) goto out; 18941 * index &= array->index_mask; 18942 * to avoid out-of-bounds cpu speculation 18943 */ 18944 if (bpf_map_ptr_poisoned(aux)) { 18945 verbose(env, "tail_call abusing map_ptr\n"); 18946 return -EINVAL; 18947 } 18948 18949 map_ptr = BPF_MAP_PTR(aux->map_ptr_state); 18950 insn_buf[0] = BPF_JMP_IMM(BPF_JGE, BPF_REG_3, 18951 map_ptr->max_entries, 2); 18952 insn_buf[1] = BPF_ALU32_IMM(BPF_AND, BPF_REG_3, 18953 container_of(map_ptr, 18954 struct bpf_array, 18955 map)->index_mask); 18956 insn_buf[2] = *insn; 18957 cnt = 3; 18958 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 18959 if (!new_prog) 18960 return -ENOMEM; 18961 18962 delta += cnt - 1; 18963 env->prog = prog = new_prog; 18964 insn = new_prog->insnsi + i + delta; 18965 continue; 18966 } 18967 18968 if (insn->imm == BPF_FUNC_timer_set_callback) { 18969 /* The verifier will process callback_fn as many times as necessary 18970 * with different maps and the register states prepared by 18971 * set_timer_callback_state will be accurate. 18972 * 18973 * The following use case is valid: 18974 * map1 is shared by prog1, prog2, prog3. 18975 * prog1 calls bpf_timer_init for some map1 elements 18976 * prog2 calls bpf_timer_set_callback for some map1 elements. 18977 * Those that were not bpf_timer_init-ed will return -EINVAL. 18978 * prog3 calls bpf_timer_start for some map1 elements. 18979 * Those that were not both bpf_timer_init-ed and 18980 * bpf_timer_set_callback-ed will return -EINVAL. 18981 */ 18982 struct bpf_insn ld_addrs[2] = { 18983 BPF_LD_IMM64(BPF_REG_3, (long)prog->aux), 18984 }; 18985 18986 insn_buf[0] = ld_addrs[0]; 18987 insn_buf[1] = ld_addrs[1]; 18988 insn_buf[2] = *insn; 18989 cnt = 3; 18990 18991 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 18992 if (!new_prog) 18993 return -ENOMEM; 18994 18995 delta += cnt - 1; 18996 env->prog = prog = new_prog; 18997 insn = new_prog->insnsi + i + delta; 18998 goto patch_call_imm; 18999 } 19000 19001 if (is_storage_get_function(insn->imm)) { 19002 if (!env->prog->aux->sleepable || 19003 env->insn_aux_data[i + delta].storage_get_func_atomic) 19004 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_5, (__force __s32)GFP_ATOMIC); 19005 else 19006 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_5, (__force __s32)GFP_KERNEL); 19007 insn_buf[1] = *insn; 19008 cnt = 2; 19009 19010 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 19011 if (!new_prog) 19012 return -ENOMEM; 19013 19014 delta += cnt - 1; 19015 env->prog = prog = new_prog; 19016 insn = new_prog->insnsi + i + delta; 19017 goto patch_call_imm; 19018 } 19019 19020 /* bpf_per_cpu_ptr() and bpf_this_cpu_ptr() */ 19021 if (env->insn_aux_data[i + delta].call_with_percpu_alloc_ptr) { 19022 /* patch with 'r1 = *(u64 *)(r1 + 0)' since for percpu data, 19023 * bpf_mem_alloc() returns a ptr to the percpu data ptr. 19024 */ 19025 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_1, BPF_REG_1, 0); 19026 insn_buf[1] = *insn; 19027 cnt = 2; 19028 19029 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 19030 if (!new_prog) 19031 return -ENOMEM; 19032 19033 delta += cnt - 1; 19034 env->prog = prog = new_prog; 19035 insn = new_prog->insnsi + i + delta; 19036 goto patch_call_imm; 19037 } 19038 19039 /* BPF_EMIT_CALL() assumptions in some of the map_gen_lookup 19040 * and other inlining handlers are currently limited to 64 bit 19041 * only. 19042 */ 19043 if (prog->jit_requested && BITS_PER_LONG == 64 && 19044 (insn->imm == BPF_FUNC_map_lookup_elem || 19045 insn->imm == BPF_FUNC_map_update_elem || 19046 insn->imm == BPF_FUNC_map_delete_elem || 19047 insn->imm == BPF_FUNC_map_push_elem || 19048 insn->imm == BPF_FUNC_map_pop_elem || 19049 insn->imm == BPF_FUNC_map_peek_elem || 19050 insn->imm == BPF_FUNC_redirect_map || 19051 insn->imm == BPF_FUNC_for_each_map_elem || 19052 insn->imm == BPF_FUNC_map_lookup_percpu_elem)) { 19053 aux = &env->insn_aux_data[i + delta]; 19054 if (bpf_map_ptr_poisoned(aux)) 19055 goto patch_call_imm; 19056 19057 map_ptr = BPF_MAP_PTR(aux->map_ptr_state); 19058 ops = map_ptr->ops; 19059 if (insn->imm == BPF_FUNC_map_lookup_elem && 19060 ops->map_gen_lookup) { 19061 cnt = ops->map_gen_lookup(map_ptr, insn_buf); 19062 if (cnt == -EOPNOTSUPP) 19063 goto patch_map_ops_generic; 19064 if (cnt <= 0 || cnt >= ARRAY_SIZE(insn_buf)) { 19065 verbose(env, "bpf verifier is misconfigured\n"); 19066 return -EINVAL; 19067 } 19068 19069 new_prog = bpf_patch_insn_data(env, i + delta, 19070 insn_buf, cnt); 19071 if (!new_prog) 19072 return -ENOMEM; 19073 19074 delta += cnt - 1; 19075 env->prog = prog = new_prog; 19076 insn = new_prog->insnsi + i + delta; 19077 continue; 19078 } 19079 19080 BUILD_BUG_ON(!__same_type(ops->map_lookup_elem, 19081 (void *(*)(struct bpf_map *map, void *key))NULL)); 19082 BUILD_BUG_ON(!__same_type(ops->map_delete_elem, 19083 (long (*)(struct bpf_map *map, void *key))NULL)); 19084 BUILD_BUG_ON(!__same_type(ops->map_update_elem, 19085 (long (*)(struct bpf_map *map, void *key, void *value, 19086 u64 flags))NULL)); 19087 BUILD_BUG_ON(!__same_type(ops->map_push_elem, 19088 (long (*)(struct bpf_map *map, void *value, 19089 u64 flags))NULL)); 19090 BUILD_BUG_ON(!__same_type(ops->map_pop_elem, 19091 (long (*)(struct bpf_map *map, void *value))NULL)); 19092 BUILD_BUG_ON(!__same_type(ops->map_peek_elem, 19093 (long (*)(struct bpf_map *map, void *value))NULL)); 19094 BUILD_BUG_ON(!__same_type(ops->map_redirect, 19095 (long (*)(struct bpf_map *map, u64 index, u64 flags))NULL)); 19096 BUILD_BUG_ON(!__same_type(ops->map_for_each_callback, 19097 (long (*)(struct bpf_map *map, 19098 bpf_callback_t callback_fn, 19099 void *callback_ctx, 19100 u64 flags))NULL)); 19101 BUILD_BUG_ON(!__same_type(ops->map_lookup_percpu_elem, 19102 (void *(*)(struct bpf_map *map, void *key, u32 cpu))NULL)); 19103 19104 patch_map_ops_generic: 19105 switch (insn->imm) { 19106 case BPF_FUNC_map_lookup_elem: 19107 insn->imm = BPF_CALL_IMM(ops->map_lookup_elem); 19108 continue; 19109 case BPF_FUNC_map_update_elem: 19110 insn->imm = BPF_CALL_IMM(ops->map_update_elem); 19111 continue; 19112 case BPF_FUNC_map_delete_elem: 19113 insn->imm = BPF_CALL_IMM(ops->map_delete_elem); 19114 continue; 19115 case BPF_FUNC_map_push_elem: 19116 insn->imm = BPF_CALL_IMM(ops->map_push_elem); 19117 continue; 19118 case BPF_FUNC_map_pop_elem: 19119 insn->imm = BPF_CALL_IMM(ops->map_pop_elem); 19120 continue; 19121 case BPF_FUNC_map_peek_elem: 19122 insn->imm = BPF_CALL_IMM(ops->map_peek_elem); 19123 continue; 19124 case BPF_FUNC_redirect_map: 19125 insn->imm = BPF_CALL_IMM(ops->map_redirect); 19126 continue; 19127 case BPF_FUNC_for_each_map_elem: 19128 insn->imm = BPF_CALL_IMM(ops->map_for_each_callback); 19129 continue; 19130 case BPF_FUNC_map_lookup_percpu_elem: 19131 insn->imm = BPF_CALL_IMM(ops->map_lookup_percpu_elem); 19132 continue; 19133 } 19134 19135 goto patch_call_imm; 19136 } 19137 19138 /* Implement bpf_jiffies64 inline. */ 19139 if (prog->jit_requested && BITS_PER_LONG == 64 && 19140 insn->imm == BPF_FUNC_jiffies64) { 19141 struct bpf_insn ld_jiffies_addr[2] = { 19142 BPF_LD_IMM64(BPF_REG_0, 19143 (unsigned long)&jiffies), 19144 }; 19145 19146 insn_buf[0] = ld_jiffies_addr[0]; 19147 insn_buf[1] = ld_jiffies_addr[1]; 19148 insn_buf[2] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, 19149 BPF_REG_0, 0); 19150 cnt = 3; 19151 19152 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 19153 cnt); 19154 if (!new_prog) 19155 return -ENOMEM; 19156 19157 delta += cnt - 1; 19158 env->prog = prog = new_prog; 19159 insn = new_prog->insnsi + i + delta; 19160 continue; 19161 } 19162 19163 /* Implement bpf_get_func_arg inline. */ 19164 if (prog_type == BPF_PROG_TYPE_TRACING && 19165 insn->imm == BPF_FUNC_get_func_arg) { 19166 /* Load nr_args from ctx - 8 */ 19167 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8); 19168 insn_buf[1] = BPF_JMP32_REG(BPF_JGE, BPF_REG_2, BPF_REG_0, 6); 19169 insn_buf[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_2, 3); 19170 insn_buf[3] = BPF_ALU64_REG(BPF_ADD, BPF_REG_2, BPF_REG_1); 19171 insn_buf[4] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_2, 0); 19172 insn_buf[5] = BPF_STX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0); 19173 insn_buf[6] = BPF_MOV64_IMM(BPF_REG_0, 0); 19174 insn_buf[7] = BPF_JMP_A(1); 19175 insn_buf[8] = BPF_MOV64_IMM(BPF_REG_0, -EINVAL); 19176 cnt = 9; 19177 19178 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 19179 if (!new_prog) 19180 return -ENOMEM; 19181 19182 delta += cnt - 1; 19183 env->prog = prog = new_prog; 19184 insn = new_prog->insnsi + i + delta; 19185 continue; 19186 } 19187 19188 /* Implement bpf_get_func_ret inline. */ 19189 if (prog_type == BPF_PROG_TYPE_TRACING && 19190 insn->imm == BPF_FUNC_get_func_ret) { 19191 if (eatype == BPF_TRACE_FEXIT || 19192 eatype == BPF_MODIFY_RETURN) { 19193 /* Load nr_args from ctx - 8 */ 19194 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8); 19195 insn_buf[1] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_0, 3); 19196 insn_buf[2] = BPF_ALU64_REG(BPF_ADD, BPF_REG_0, BPF_REG_1); 19197 insn_buf[3] = BPF_LDX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0); 19198 insn_buf[4] = BPF_STX_MEM(BPF_DW, BPF_REG_2, BPF_REG_3, 0); 19199 insn_buf[5] = BPF_MOV64_IMM(BPF_REG_0, 0); 19200 cnt = 6; 19201 } else { 19202 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_0, -EOPNOTSUPP); 19203 cnt = 1; 19204 } 19205 19206 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 19207 if (!new_prog) 19208 return -ENOMEM; 19209 19210 delta += cnt - 1; 19211 env->prog = prog = new_prog; 19212 insn = new_prog->insnsi + i + delta; 19213 continue; 19214 } 19215 19216 /* Implement get_func_arg_cnt inline. */ 19217 if (prog_type == BPF_PROG_TYPE_TRACING && 19218 insn->imm == BPF_FUNC_get_func_arg_cnt) { 19219 /* Load nr_args from ctx - 8 */ 19220 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8); 19221 19222 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1); 19223 if (!new_prog) 19224 return -ENOMEM; 19225 19226 env->prog = prog = new_prog; 19227 insn = new_prog->insnsi + i + delta; 19228 continue; 19229 } 19230 19231 /* Implement bpf_get_func_ip inline. */ 19232 if (prog_type == BPF_PROG_TYPE_TRACING && 19233 insn->imm == BPF_FUNC_get_func_ip) { 19234 /* Load IP address from ctx - 16 */ 19235 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -16); 19236 19237 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1); 19238 if (!new_prog) 19239 return -ENOMEM; 19240 19241 env->prog = prog = new_prog; 19242 insn = new_prog->insnsi + i + delta; 19243 continue; 19244 } 19245 19246 patch_call_imm: 19247 fn = env->ops->get_func_proto(insn->imm, env->prog); 19248 /* all functions that have prototype and verifier allowed 19249 * programs to call them, must be real in-kernel functions 19250 */ 19251 if (!fn->func) { 19252 verbose(env, 19253 "kernel subsystem misconfigured func %s#%d\n", 19254 func_id_name(insn->imm), insn->imm); 19255 return -EFAULT; 19256 } 19257 insn->imm = fn->func - __bpf_call_base; 19258 } 19259 19260 /* Since poke tab is now finalized, publish aux to tracker. */ 19261 for (i = 0; i < prog->aux->size_poke_tab; i++) { 19262 map_ptr = prog->aux->poke_tab[i].tail_call.map; 19263 if (!map_ptr->ops->map_poke_track || 19264 !map_ptr->ops->map_poke_untrack || 19265 !map_ptr->ops->map_poke_run) { 19266 verbose(env, "bpf verifier is misconfigured\n"); 19267 return -EINVAL; 19268 } 19269 19270 ret = map_ptr->ops->map_poke_track(map_ptr, prog->aux); 19271 if (ret < 0) { 19272 verbose(env, "tracking tail call prog failed\n"); 19273 return ret; 19274 } 19275 } 19276 19277 sort_kfunc_descs_by_imm_off(env->prog); 19278 19279 return 0; 19280 } 19281 19282 static struct bpf_prog *inline_bpf_loop(struct bpf_verifier_env *env, 19283 int position, 19284 s32 stack_base, 19285 u32 callback_subprogno, 19286 u32 *cnt) 19287 { 19288 s32 r6_offset = stack_base + 0 * BPF_REG_SIZE; 19289 s32 r7_offset = stack_base + 1 * BPF_REG_SIZE; 19290 s32 r8_offset = stack_base + 2 * BPF_REG_SIZE; 19291 int reg_loop_max = BPF_REG_6; 19292 int reg_loop_cnt = BPF_REG_7; 19293 int reg_loop_ctx = BPF_REG_8; 19294 19295 struct bpf_prog *new_prog; 19296 u32 callback_start; 19297 u32 call_insn_offset; 19298 s32 callback_offset; 19299 19300 /* This represents an inlined version of bpf_iter.c:bpf_loop, 19301 * be careful to modify this code in sync. 19302 */ 19303 struct bpf_insn insn_buf[] = { 19304 /* Return error and jump to the end of the patch if 19305 * expected number of iterations is too big. 19306 */ 19307 BPF_JMP_IMM(BPF_JLE, BPF_REG_1, BPF_MAX_LOOPS, 2), 19308 BPF_MOV32_IMM(BPF_REG_0, -E2BIG), 19309 BPF_JMP_IMM(BPF_JA, 0, 0, 16), 19310 /* spill R6, R7, R8 to use these as loop vars */ 19311 BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_6, r6_offset), 19312 BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_7, r7_offset), 19313 BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_8, r8_offset), 19314 /* initialize loop vars */ 19315 BPF_MOV64_REG(reg_loop_max, BPF_REG_1), 19316 BPF_MOV32_IMM(reg_loop_cnt, 0), 19317 BPF_MOV64_REG(reg_loop_ctx, BPF_REG_3), 19318 /* loop header, 19319 * if reg_loop_cnt >= reg_loop_max skip the loop body 19320 */ 19321 BPF_JMP_REG(BPF_JGE, reg_loop_cnt, reg_loop_max, 5), 19322 /* callback call, 19323 * correct callback offset would be set after patching 19324 */ 19325 BPF_MOV64_REG(BPF_REG_1, reg_loop_cnt), 19326 BPF_MOV64_REG(BPF_REG_2, reg_loop_ctx), 19327 BPF_CALL_REL(0), 19328 /* increment loop counter */ 19329 BPF_ALU64_IMM(BPF_ADD, reg_loop_cnt, 1), 19330 /* jump to loop header if callback returned 0 */ 19331 BPF_JMP_IMM(BPF_JEQ, BPF_REG_0, 0, -6), 19332 /* return value of bpf_loop, 19333 * set R0 to the number of iterations 19334 */ 19335 BPF_MOV64_REG(BPF_REG_0, reg_loop_cnt), 19336 /* restore original values of R6, R7, R8 */ 19337 BPF_LDX_MEM(BPF_DW, BPF_REG_6, BPF_REG_10, r6_offset), 19338 BPF_LDX_MEM(BPF_DW, BPF_REG_7, BPF_REG_10, r7_offset), 19339 BPF_LDX_MEM(BPF_DW, BPF_REG_8, BPF_REG_10, r8_offset), 19340 }; 19341 19342 *cnt = ARRAY_SIZE(insn_buf); 19343 new_prog = bpf_patch_insn_data(env, position, insn_buf, *cnt); 19344 if (!new_prog) 19345 return new_prog; 19346 19347 /* callback start is known only after patching */ 19348 callback_start = env->subprog_info[callback_subprogno].start; 19349 /* Note: insn_buf[12] is an offset of BPF_CALL_REL instruction */ 19350 call_insn_offset = position + 12; 19351 callback_offset = callback_start - call_insn_offset - 1; 19352 new_prog->insnsi[call_insn_offset].imm = callback_offset; 19353 19354 return new_prog; 19355 } 19356 19357 static bool is_bpf_loop_call(struct bpf_insn *insn) 19358 { 19359 return insn->code == (BPF_JMP | BPF_CALL) && 19360 insn->src_reg == 0 && 19361 insn->imm == BPF_FUNC_loop; 19362 } 19363 19364 /* For all sub-programs in the program (including main) check 19365 * insn_aux_data to see if there are bpf_loop calls that require 19366 * inlining. If such calls are found the calls are replaced with a 19367 * sequence of instructions produced by `inline_bpf_loop` function and 19368 * subprog stack_depth is increased by the size of 3 registers. 19369 * This stack space is used to spill values of the R6, R7, R8. These 19370 * registers are used to store the loop bound, counter and context 19371 * variables. 19372 */ 19373 static int optimize_bpf_loop(struct bpf_verifier_env *env) 19374 { 19375 struct bpf_subprog_info *subprogs = env->subprog_info; 19376 int i, cur_subprog = 0, cnt, delta = 0; 19377 struct bpf_insn *insn = env->prog->insnsi; 19378 int insn_cnt = env->prog->len; 19379 u16 stack_depth = subprogs[cur_subprog].stack_depth; 19380 u16 stack_depth_roundup = round_up(stack_depth, 8) - stack_depth; 19381 u16 stack_depth_extra = 0; 19382 19383 for (i = 0; i < insn_cnt; i++, insn++) { 19384 struct bpf_loop_inline_state *inline_state = 19385 &env->insn_aux_data[i + delta].loop_inline_state; 19386 19387 if (is_bpf_loop_call(insn) && inline_state->fit_for_inline) { 19388 struct bpf_prog *new_prog; 19389 19390 stack_depth_extra = BPF_REG_SIZE * 3 + stack_depth_roundup; 19391 new_prog = inline_bpf_loop(env, 19392 i + delta, 19393 -(stack_depth + stack_depth_extra), 19394 inline_state->callback_subprogno, 19395 &cnt); 19396 if (!new_prog) 19397 return -ENOMEM; 19398 19399 delta += cnt - 1; 19400 env->prog = new_prog; 19401 insn = new_prog->insnsi + i + delta; 19402 } 19403 19404 if (subprogs[cur_subprog + 1].start == i + delta + 1) { 19405 subprogs[cur_subprog].stack_depth += stack_depth_extra; 19406 cur_subprog++; 19407 stack_depth = subprogs[cur_subprog].stack_depth; 19408 stack_depth_roundup = round_up(stack_depth, 8) - stack_depth; 19409 stack_depth_extra = 0; 19410 } 19411 } 19412 19413 env->prog->aux->stack_depth = env->subprog_info[0].stack_depth; 19414 19415 return 0; 19416 } 19417 19418 static void free_states(struct bpf_verifier_env *env) 19419 { 19420 struct bpf_verifier_state_list *sl, *sln; 19421 int i; 19422 19423 sl = env->free_list; 19424 while (sl) { 19425 sln = sl->next; 19426 free_verifier_state(&sl->state, false); 19427 kfree(sl); 19428 sl = sln; 19429 } 19430 env->free_list = NULL; 19431 19432 if (!env->explored_states) 19433 return; 19434 19435 for (i = 0; i < state_htab_size(env); i++) { 19436 sl = env->explored_states[i]; 19437 19438 while (sl) { 19439 sln = sl->next; 19440 free_verifier_state(&sl->state, false); 19441 kfree(sl); 19442 sl = sln; 19443 } 19444 env->explored_states[i] = NULL; 19445 } 19446 } 19447 19448 static int do_check_common(struct bpf_verifier_env *env, int subprog, bool is_ex_cb) 19449 { 19450 bool pop_log = !(env->log.level & BPF_LOG_LEVEL2); 19451 struct bpf_verifier_state *state; 19452 struct bpf_reg_state *regs; 19453 int ret, i; 19454 19455 env->prev_linfo = NULL; 19456 env->pass_cnt++; 19457 19458 state = kzalloc(sizeof(struct bpf_verifier_state), GFP_KERNEL); 19459 if (!state) 19460 return -ENOMEM; 19461 state->curframe = 0; 19462 state->speculative = false; 19463 state->branches = 1; 19464 state->frame[0] = kzalloc(sizeof(struct bpf_func_state), GFP_KERNEL); 19465 if (!state->frame[0]) { 19466 kfree(state); 19467 return -ENOMEM; 19468 } 19469 env->cur_state = state; 19470 init_func_state(env, state->frame[0], 19471 BPF_MAIN_FUNC /* callsite */, 19472 0 /* frameno */, 19473 subprog); 19474 state->first_insn_idx = env->subprog_info[subprog].start; 19475 state->last_insn_idx = -1; 19476 19477 regs = state->frame[state->curframe]->regs; 19478 if (subprog || env->prog->type == BPF_PROG_TYPE_EXT) { 19479 ret = btf_prepare_func_args(env, subprog, regs, is_ex_cb); 19480 if (ret) 19481 goto out; 19482 for (i = BPF_REG_1; i <= BPF_REG_5; i++) { 19483 if (regs[i].type == PTR_TO_CTX) 19484 mark_reg_known_zero(env, regs, i); 19485 else if (regs[i].type == SCALAR_VALUE) 19486 mark_reg_unknown(env, regs, i); 19487 else if (base_type(regs[i].type) == PTR_TO_MEM) { 19488 const u32 mem_size = regs[i].mem_size; 19489 19490 mark_reg_known_zero(env, regs, i); 19491 regs[i].mem_size = mem_size; 19492 regs[i].id = ++env->id_gen; 19493 } 19494 } 19495 if (is_ex_cb) { 19496 state->frame[0]->in_exception_callback_fn = true; 19497 env->subprog_info[subprog].is_cb = true; 19498 env->subprog_info[subprog].is_async_cb = true; 19499 env->subprog_info[subprog].is_exception_cb = true; 19500 } 19501 } else { 19502 /* 1st arg to a function */ 19503 regs[BPF_REG_1].type = PTR_TO_CTX; 19504 mark_reg_known_zero(env, regs, BPF_REG_1); 19505 ret = btf_check_subprog_arg_match(env, subprog, regs); 19506 if (ret == -EFAULT) 19507 /* unlikely verifier bug. abort. 19508 * ret == 0 and ret < 0 are sadly acceptable for 19509 * main() function due to backward compatibility. 19510 * Like socket filter program may be written as: 19511 * int bpf_prog(struct pt_regs *ctx) 19512 * and never dereference that ctx in the program. 19513 * 'struct pt_regs' is a type mismatch for socket 19514 * filter that should be using 'struct __sk_buff'. 19515 */ 19516 goto out; 19517 } 19518 19519 ret = do_check(env); 19520 out: 19521 /* check for NULL is necessary, since cur_state can be freed inside 19522 * do_check() under memory pressure. 19523 */ 19524 if (env->cur_state) { 19525 free_verifier_state(env->cur_state, true); 19526 env->cur_state = NULL; 19527 } 19528 while (!pop_stack(env, NULL, NULL, false)); 19529 if (!ret && pop_log) 19530 bpf_vlog_reset(&env->log, 0); 19531 free_states(env); 19532 return ret; 19533 } 19534 19535 /* Verify all global functions in a BPF program one by one based on their BTF. 19536 * All global functions must pass verification. Otherwise the whole program is rejected. 19537 * Consider: 19538 * int bar(int); 19539 * int foo(int f) 19540 * { 19541 * return bar(f); 19542 * } 19543 * int bar(int b) 19544 * { 19545 * ... 19546 * } 19547 * foo() will be verified first for R1=any_scalar_value. During verification it 19548 * will be assumed that bar() already verified successfully and call to bar() 19549 * from foo() will be checked for type match only. Later bar() will be verified 19550 * independently to check that it's safe for R1=any_scalar_value. 19551 */ 19552 static int do_check_subprogs(struct bpf_verifier_env *env) 19553 { 19554 struct bpf_prog_aux *aux = env->prog->aux; 19555 int i, ret; 19556 19557 if (!aux->func_info) 19558 return 0; 19559 19560 for (i = 1; i < env->subprog_cnt; i++) { 19561 if (aux->func_info_aux[i].linkage != BTF_FUNC_GLOBAL) 19562 continue; 19563 env->insn_idx = env->subprog_info[i].start; 19564 WARN_ON_ONCE(env->insn_idx == 0); 19565 ret = do_check_common(env, i, env->exception_callback_subprog == i); 19566 if (ret) { 19567 return ret; 19568 } else if (env->log.level & BPF_LOG_LEVEL) { 19569 verbose(env, 19570 "Func#%d is safe for any args that match its prototype\n", 19571 i); 19572 } 19573 } 19574 return 0; 19575 } 19576 19577 static int do_check_main(struct bpf_verifier_env *env) 19578 { 19579 int ret; 19580 19581 env->insn_idx = 0; 19582 ret = do_check_common(env, 0, false); 19583 if (!ret) 19584 env->prog->aux->stack_depth = env->subprog_info[0].stack_depth; 19585 return ret; 19586 } 19587 19588 19589 static void print_verification_stats(struct bpf_verifier_env *env) 19590 { 19591 int i; 19592 19593 if (env->log.level & BPF_LOG_STATS) { 19594 verbose(env, "verification time %lld usec\n", 19595 div_u64(env->verification_time, 1000)); 19596 verbose(env, "stack depth "); 19597 for (i = 0; i < env->subprog_cnt; i++) { 19598 u32 depth = env->subprog_info[i].stack_depth; 19599 19600 verbose(env, "%d", depth); 19601 if (i + 1 < env->subprog_cnt) 19602 verbose(env, "+"); 19603 } 19604 verbose(env, "\n"); 19605 } 19606 verbose(env, "processed %d insns (limit %d) max_states_per_insn %d " 19607 "total_states %d peak_states %d mark_read %d\n", 19608 env->insn_processed, BPF_COMPLEXITY_LIMIT_INSNS, 19609 env->max_states_per_insn, env->total_states, 19610 env->peak_states, env->longest_mark_read_walk); 19611 } 19612 19613 static int check_struct_ops_btf_id(struct bpf_verifier_env *env) 19614 { 19615 const struct btf_type *t, *func_proto; 19616 const struct bpf_struct_ops *st_ops; 19617 const struct btf_member *member; 19618 struct bpf_prog *prog = env->prog; 19619 u32 btf_id, member_idx; 19620 const char *mname; 19621 19622 if (!prog->gpl_compatible) { 19623 verbose(env, "struct ops programs must have a GPL compatible license\n"); 19624 return -EINVAL; 19625 } 19626 19627 btf_id = prog->aux->attach_btf_id; 19628 st_ops = bpf_struct_ops_find(btf_id); 19629 if (!st_ops) { 19630 verbose(env, "attach_btf_id %u is not a supported struct\n", 19631 btf_id); 19632 return -ENOTSUPP; 19633 } 19634 19635 t = st_ops->type; 19636 member_idx = prog->expected_attach_type; 19637 if (member_idx >= btf_type_vlen(t)) { 19638 verbose(env, "attach to invalid member idx %u of struct %s\n", 19639 member_idx, st_ops->name); 19640 return -EINVAL; 19641 } 19642 19643 member = &btf_type_member(t)[member_idx]; 19644 mname = btf_name_by_offset(btf_vmlinux, member->name_off); 19645 func_proto = btf_type_resolve_func_ptr(btf_vmlinux, member->type, 19646 NULL); 19647 if (!func_proto) { 19648 verbose(env, "attach to invalid member %s(@idx %u) of struct %s\n", 19649 mname, member_idx, st_ops->name); 19650 return -EINVAL; 19651 } 19652 19653 if (st_ops->check_member) { 19654 int err = st_ops->check_member(t, member, prog); 19655 19656 if (err) { 19657 verbose(env, "attach to unsupported member %s of struct %s\n", 19658 mname, st_ops->name); 19659 return err; 19660 } 19661 } 19662 19663 prog->aux->attach_func_proto = func_proto; 19664 prog->aux->attach_func_name = mname; 19665 env->ops = st_ops->verifier_ops; 19666 19667 return 0; 19668 } 19669 #define SECURITY_PREFIX "security_" 19670 19671 static int check_attach_modify_return(unsigned long addr, const char *func_name) 19672 { 19673 if (within_error_injection_list(addr) || 19674 !strncmp(SECURITY_PREFIX, func_name, sizeof(SECURITY_PREFIX) - 1)) 19675 return 0; 19676 19677 return -EINVAL; 19678 } 19679 19680 /* list of non-sleepable functions that are otherwise on 19681 * ALLOW_ERROR_INJECTION list 19682 */ 19683 BTF_SET_START(btf_non_sleepable_error_inject) 19684 /* Three functions below can be called from sleepable and non-sleepable context. 19685 * Assume non-sleepable from bpf safety point of view. 19686 */ 19687 BTF_ID(func, __filemap_add_folio) 19688 BTF_ID(func, should_fail_alloc_page) 19689 BTF_ID(func, should_failslab) 19690 BTF_SET_END(btf_non_sleepable_error_inject) 19691 19692 static int check_non_sleepable_error_inject(u32 btf_id) 19693 { 19694 return btf_id_set_contains(&btf_non_sleepable_error_inject, btf_id); 19695 } 19696 19697 int bpf_check_attach_target(struct bpf_verifier_log *log, 19698 const struct bpf_prog *prog, 19699 const struct bpf_prog *tgt_prog, 19700 u32 btf_id, 19701 struct bpf_attach_target_info *tgt_info) 19702 { 19703 bool prog_extension = prog->type == BPF_PROG_TYPE_EXT; 19704 const char prefix[] = "btf_trace_"; 19705 int ret = 0, subprog = -1, i; 19706 const struct btf_type *t; 19707 bool conservative = true; 19708 const char *tname; 19709 struct btf *btf; 19710 long addr = 0; 19711 struct module *mod = NULL; 19712 19713 if (!btf_id) { 19714 bpf_log(log, "Tracing programs must provide btf_id\n"); 19715 return -EINVAL; 19716 } 19717 btf = tgt_prog ? tgt_prog->aux->btf : prog->aux->attach_btf; 19718 if (!btf) { 19719 bpf_log(log, 19720 "FENTRY/FEXIT program can only be attached to another program annotated with BTF\n"); 19721 return -EINVAL; 19722 } 19723 t = btf_type_by_id(btf, btf_id); 19724 if (!t) { 19725 bpf_log(log, "attach_btf_id %u is invalid\n", btf_id); 19726 return -EINVAL; 19727 } 19728 tname = btf_name_by_offset(btf, t->name_off); 19729 if (!tname) { 19730 bpf_log(log, "attach_btf_id %u doesn't have a name\n", btf_id); 19731 return -EINVAL; 19732 } 19733 if (tgt_prog) { 19734 struct bpf_prog_aux *aux = tgt_prog->aux; 19735 19736 if (bpf_prog_is_dev_bound(prog->aux) && 19737 !bpf_prog_dev_bound_match(prog, tgt_prog)) { 19738 bpf_log(log, "Target program bound device mismatch"); 19739 return -EINVAL; 19740 } 19741 19742 for (i = 0; i < aux->func_info_cnt; i++) 19743 if (aux->func_info[i].type_id == btf_id) { 19744 subprog = i; 19745 break; 19746 } 19747 if (subprog == -1) { 19748 bpf_log(log, "Subprog %s doesn't exist\n", tname); 19749 return -EINVAL; 19750 } 19751 if (aux->func && aux->func[subprog]->aux->exception_cb) { 19752 bpf_log(log, 19753 "%s programs cannot attach to exception callback\n", 19754 prog_extension ? "Extension" : "FENTRY/FEXIT"); 19755 return -EINVAL; 19756 } 19757 conservative = aux->func_info_aux[subprog].unreliable; 19758 if (prog_extension) { 19759 if (conservative) { 19760 bpf_log(log, 19761 "Cannot replace static functions\n"); 19762 return -EINVAL; 19763 } 19764 if (!prog->jit_requested) { 19765 bpf_log(log, 19766 "Extension programs should be JITed\n"); 19767 return -EINVAL; 19768 } 19769 } 19770 if (!tgt_prog->jited) { 19771 bpf_log(log, "Can attach to only JITed progs\n"); 19772 return -EINVAL; 19773 } 19774 if (tgt_prog->type == prog->type) { 19775 /* Cannot fentry/fexit another fentry/fexit program. 19776 * Cannot attach program extension to another extension. 19777 * It's ok to attach fentry/fexit to extension program. 19778 */ 19779 bpf_log(log, "Cannot recursively attach\n"); 19780 return -EINVAL; 19781 } 19782 if (tgt_prog->type == BPF_PROG_TYPE_TRACING && 19783 prog_extension && 19784 (tgt_prog->expected_attach_type == BPF_TRACE_FENTRY || 19785 tgt_prog->expected_attach_type == BPF_TRACE_FEXIT)) { 19786 /* Program extensions can extend all program types 19787 * except fentry/fexit. The reason is the following. 19788 * The fentry/fexit programs are used for performance 19789 * analysis, stats and can be attached to any program 19790 * type except themselves. When extension program is 19791 * replacing XDP function it is necessary to allow 19792 * performance analysis of all functions. Both original 19793 * XDP program and its program extension. Hence 19794 * attaching fentry/fexit to BPF_PROG_TYPE_EXT is 19795 * allowed. If extending of fentry/fexit was allowed it 19796 * would be possible to create long call chain 19797 * fentry->extension->fentry->extension beyond 19798 * reasonable stack size. Hence extending fentry is not 19799 * allowed. 19800 */ 19801 bpf_log(log, "Cannot extend fentry/fexit\n"); 19802 return -EINVAL; 19803 } 19804 } else { 19805 if (prog_extension) { 19806 bpf_log(log, "Cannot replace kernel functions\n"); 19807 return -EINVAL; 19808 } 19809 } 19810 19811 switch (prog->expected_attach_type) { 19812 case BPF_TRACE_RAW_TP: 19813 if (tgt_prog) { 19814 bpf_log(log, 19815 "Only FENTRY/FEXIT progs are attachable to another BPF prog\n"); 19816 return -EINVAL; 19817 } 19818 if (!btf_type_is_typedef(t)) { 19819 bpf_log(log, "attach_btf_id %u is not a typedef\n", 19820 btf_id); 19821 return -EINVAL; 19822 } 19823 if (strncmp(prefix, tname, sizeof(prefix) - 1)) { 19824 bpf_log(log, "attach_btf_id %u points to wrong type name %s\n", 19825 btf_id, tname); 19826 return -EINVAL; 19827 } 19828 tname += sizeof(prefix) - 1; 19829 t = btf_type_by_id(btf, t->type); 19830 if (!btf_type_is_ptr(t)) 19831 /* should never happen in valid vmlinux build */ 19832 return -EINVAL; 19833 t = btf_type_by_id(btf, t->type); 19834 if (!btf_type_is_func_proto(t)) 19835 /* should never happen in valid vmlinux build */ 19836 return -EINVAL; 19837 19838 break; 19839 case BPF_TRACE_ITER: 19840 if (!btf_type_is_func(t)) { 19841 bpf_log(log, "attach_btf_id %u is not a function\n", 19842 btf_id); 19843 return -EINVAL; 19844 } 19845 t = btf_type_by_id(btf, t->type); 19846 if (!btf_type_is_func_proto(t)) 19847 return -EINVAL; 19848 ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel); 19849 if (ret) 19850 return ret; 19851 break; 19852 default: 19853 if (!prog_extension) 19854 return -EINVAL; 19855 fallthrough; 19856 case BPF_MODIFY_RETURN: 19857 case BPF_LSM_MAC: 19858 case BPF_LSM_CGROUP: 19859 case BPF_TRACE_FENTRY: 19860 case BPF_TRACE_FEXIT: 19861 if (!btf_type_is_func(t)) { 19862 bpf_log(log, "attach_btf_id %u is not a function\n", 19863 btf_id); 19864 return -EINVAL; 19865 } 19866 if (prog_extension && 19867 btf_check_type_match(log, prog, btf, t)) 19868 return -EINVAL; 19869 t = btf_type_by_id(btf, t->type); 19870 if (!btf_type_is_func_proto(t)) 19871 return -EINVAL; 19872 19873 if ((prog->aux->saved_dst_prog_type || prog->aux->saved_dst_attach_type) && 19874 (!tgt_prog || prog->aux->saved_dst_prog_type != tgt_prog->type || 19875 prog->aux->saved_dst_attach_type != tgt_prog->expected_attach_type)) 19876 return -EINVAL; 19877 19878 if (tgt_prog && conservative) 19879 t = NULL; 19880 19881 ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel); 19882 if (ret < 0) 19883 return ret; 19884 19885 if (tgt_prog) { 19886 if (subprog == 0) 19887 addr = (long) tgt_prog->bpf_func; 19888 else 19889 addr = (long) tgt_prog->aux->func[subprog]->bpf_func; 19890 } else { 19891 if (btf_is_module(btf)) { 19892 mod = btf_try_get_module(btf); 19893 if (mod) 19894 addr = find_kallsyms_symbol_value(mod, tname); 19895 else 19896 addr = 0; 19897 } else { 19898 addr = kallsyms_lookup_name(tname); 19899 } 19900 if (!addr) { 19901 module_put(mod); 19902 bpf_log(log, 19903 "The address of function %s cannot be found\n", 19904 tname); 19905 return -ENOENT; 19906 } 19907 } 19908 19909 if (prog->aux->sleepable) { 19910 ret = -EINVAL; 19911 switch (prog->type) { 19912 case BPF_PROG_TYPE_TRACING: 19913 19914 /* fentry/fexit/fmod_ret progs can be sleepable if they are 19915 * attached to ALLOW_ERROR_INJECTION and are not in denylist. 19916 */ 19917 if (!check_non_sleepable_error_inject(btf_id) && 19918 within_error_injection_list(addr)) 19919 ret = 0; 19920 /* fentry/fexit/fmod_ret progs can also be sleepable if they are 19921 * in the fmodret id set with the KF_SLEEPABLE flag. 19922 */ 19923 else { 19924 u32 *flags = btf_kfunc_is_modify_return(btf, btf_id, 19925 prog); 19926 19927 if (flags && (*flags & KF_SLEEPABLE)) 19928 ret = 0; 19929 } 19930 break; 19931 case BPF_PROG_TYPE_LSM: 19932 /* LSM progs check that they are attached to bpf_lsm_*() funcs. 19933 * Only some of them are sleepable. 19934 */ 19935 if (bpf_lsm_is_sleepable_hook(btf_id)) 19936 ret = 0; 19937 break; 19938 default: 19939 break; 19940 } 19941 if (ret) { 19942 module_put(mod); 19943 bpf_log(log, "%s is not sleepable\n", tname); 19944 return ret; 19945 } 19946 } else if (prog->expected_attach_type == BPF_MODIFY_RETURN) { 19947 if (tgt_prog) { 19948 module_put(mod); 19949 bpf_log(log, "can't modify return codes of BPF programs\n"); 19950 return -EINVAL; 19951 } 19952 ret = -EINVAL; 19953 if (btf_kfunc_is_modify_return(btf, btf_id, prog) || 19954 !check_attach_modify_return(addr, tname)) 19955 ret = 0; 19956 if (ret) { 19957 module_put(mod); 19958 bpf_log(log, "%s() is not modifiable\n", tname); 19959 return ret; 19960 } 19961 } 19962 19963 break; 19964 } 19965 tgt_info->tgt_addr = addr; 19966 tgt_info->tgt_name = tname; 19967 tgt_info->tgt_type = t; 19968 tgt_info->tgt_mod = mod; 19969 return 0; 19970 } 19971 19972 BTF_SET_START(btf_id_deny) 19973 BTF_ID_UNUSED 19974 #ifdef CONFIG_SMP 19975 BTF_ID(func, migrate_disable) 19976 BTF_ID(func, migrate_enable) 19977 #endif 19978 #if !defined CONFIG_PREEMPT_RCU && !defined CONFIG_TINY_RCU 19979 BTF_ID(func, rcu_read_unlock_strict) 19980 #endif 19981 #if defined(CONFIG_DEBUG_PREEMPT) || defined(CONFIG_TRACE_PREEMPT_TOGGLE) 19982 BTF_ID(func, preempt_count_add) 19983 BTF_ID(func, preempt_count_sub) 19984 #endif 19985 #ifdef CONFIG_PREEMPT_RCU 19986 BTF_ID(func, __rcu_read_lock) 19987 BTF_ID(func, __rcu_read_unlock) 19988 #endif 19989 BTF_SET_END(btf_id_deny) 19990 19991 static bool can_be_sleepable(struct bpf_prog *prog) 19992 { 19993 if (prog->type == BPF_PROG_TYPE_TRACING) { 19994 switch (prog->expected_attach_type) { 19995 case BPF_TRACE_FENTRY: 19996 case BPF_TRACE_FEXIT: 19997 case BPF_MODIFY_RETURN: 19998 case BPF_TRACE_ITER: 19999 return true; 20000 default: 20001 return false; 20002 } 20003 } 20004 return prog->type == BPF_PROG_TYPE_LSM || 20005 prog->type == BPF_PROG_TYPE_KPROBE /* only for uprobes */ || 20006 prog->type == BPF_PROG_TYPE_STRUCT_OPS; 20007 } 20008 20009 static int check_attach_btf_id(struct bpf_verifier_env *env) 20010 { 20011 struct bpf_prog *prog = env->prog; 20012 struct bpf_prog *tgt_prog = prog->aux->dst_prog; 20013 struct bpf_attach_target_info tgt_info = {}; 20014 u32 btf_id = prog->aux->attach_btf_id; 20015 struct bpf_trampoline *tr; 20016 int ret; 20017 u64 key; 20018 20019 if (prog->type == BPF_PROG_TYPE_SYSCALL) { 20020 if (prog->aux->sleepable) 20021 /* attach_btf_id checked to be zero already */ 20022 return 0; 20023 verbose(env, "Syscall programs can only be sleepable\n"); 20024 return -EINVAL; 20025 } 20026 20027 if (prog->aux->sleepable && !can_be_sleepable(prog)) { 20028 verbose(env, "Only fentry/fexit/fmod_ret, lsm, iter, uprobe, and struct_ops programs can be sleepable\n"); 20029 return -EINVAL; 20030 } 20031 20032 if (prog->type == BPF_PROG_TYPE_STRUCT_OPS) 20033 return check_struct_ops_btf_id(env); 20034 20035 if (prog->type != BPF_PROG_TYPE_TRACING && 20036 prog->type != BPF_PROG_TYPE_LSM && 20037 prog->type != BPF_PROG_TYPE_EXT) 20038 return 0; 20039 20040 ret = bpf_check_attach_target(&env->log, prog, tgt_prog, btf_id, &tgt_info); 20041 if (ret) 20042 return ret; 20043 20044 if (tgt_prog && prog->type == BPF_PROG_TYPE_EXT) { 20045 /* to make freplace equivalent to their targets, they need to 20046 * inherit env->ops and expected_attach_type for the rest of the 20047 * verification 20048 */ 20049 env->ops = bpf_verifier_ops[tgt_prog->type]; 20050 prog->expected_attach_type = tgt_prog->expected_attach_type; 20051 } 20052 20053 /* store info about the attachment target that will be used later */ 20054 prog->aux->attach_func_proto = tgt_info.tgt_type; 20055 prog->aux->attach_func_name = tgt_info.tgt_name; 20056 prog->aux->mod = tgt_info.tgt_mod; 20057 20058 if (tgt_prog) { 20059 prog->aux->saved_dst_prog_type = tgt_prog->type; 20060 prog->aux->saved_dst_attach_type = tgt_prog->expected_attach_type; 20061 } 20062 20063 if (prog->expected_attach_type == BPF_TRACE_RAW_TP) { 20064 prog->aux->attach_btf_trace = true; 20065 return 0; 20066 } else if (prog->expected_attach_type == BPF_TRACE_ITER) { 20067 if (!bpf_iter_prog_supported(prog)) 20068 return -EINVAL; 20069 return 0; 20070 } 20071 20072 if (prog->type == BPF_PROG_TYPE_LSM) { 20073 ret = bpf_lsm_verify_prog(&env->log, prog); 20074 if (ret < 0) 20075 return ret; 20076 } else if (prog->type == BPF_PROG_TYPE_TRACING && 20077 btf_id_set_contains(&btf_id_deny, btf_id)) { 20078 return -EINVAL; 20079 } 20080 20081 key = bpf_trampoline_compute_key(tgt_prog, prog->aux->attach_btf, btf_id); 20082 tr = bpf_trampoline_get(key, &tgt_info); 20083 if (!tr) 20084 return -ENOMEM; 20085 20086 if (tgt_prog && tgt_prog->aux->tail_call_reachable) 20087 tr->flags = BPF_TRAMP_F_TAIL_CALL_CTX; 20088 20089 prog->aux->dst_trampoline = tr; 20090 return 0; 20091 } 20092 20093 struct btf *bpf_get_btf_vmlinux(void) 20094 { 20095 if (!btf_vmlinux && IS_ENABLED(CONFIG_DEBUG_INFO_BTF)) { 20096 mutex_lock(&bpf_verifier_lock); 20097 if (!btf_vmlinux) 20098 btf_vmlinux = btf_parse_vmlinux(); 20099 mutex_unlock(&bpf_verifier_lock); 20100 } 20101 return btf_vmlinux; 20102 } 20103 20104 int bpf_check(struct bpf_prog **prog, union bpf_attr *attr, bpfptr_t uattr, __u32 uattr_size) 20105 { 20106 u64 start_time = ktime_get_ns(); 20107 struct bpf_verifier_env *env; 20108 int i, len, ret = -EINVAL, err; 20109 u32 log_true_size; 20110 bool is_priv; 20111 20112 /* no program is valid */ 20113 if (ARRAY_SIZE(bpf_verifier_ops) == 0) 20114 return -EINVAL; 20115 20116 /* 'struct bpf_verifier_env' can be global, but since it's not small, 20117 * allocate/free it every time bpf_check() is called 20118 */ 20119 env = kzalloc(sizeof(struct bpf_verifier_env), GFP_KERNEL); 20120 if (!env) 20121 return -ENOMEM; 20122 20123 env->bt.env = env; 20124 20125 len = (*prog)->len; 20126 env->insn_aux_data = 20127 vzalloc(array_size(sizeof(struct bpf_insn_aux_data), len)); 20128 ret = -ENOMEM; 20129 if (!env->insn_aux_data) 20130 goto err_free_env; 20131 for (i = 0; i < len; i++) 20132 env->insn_aux_data[i].orig_idx = i; 20133 env->prog = *prog; 20134 env->ops = bpf_verifier_ops[env->prog->type]; 20135 env->fd_array = make_bpfptr(attr->fd_array, uattr.is_kernel); 20136 is_priv = bpf_capable(); 20137 20138 bpf_get_btf_vmlinux(); 20139 20140 /* grab the mutex to protect few globals used by verifier */ 20141 if (!is_priv) 20142 mutex_lock(&bpf_verifier_lock); 20143 20144 /* user could have requested verbose verifier output 20145 * and supplied buffer to store the verification trace 20146 */ 20147 ret = bpf_vlog_init(&env->log, attr->log_level, 20148 (char __user *) (unsigned long) attr->log_buf, 20149 attr->log_size); 20150 if (ret) 20151 goto err_unlock; 20152 20153 mark_verifier_state_clean(env); 20154 20155 if (IS_ERR(btf_vmlinux)) { 20156 /* Either gcc or pahole or kernel are broken. */ 20157 verbose(env, "in-kernel BTF is malformed\n"); 20158 ret = PTR_ERR(btf_vmlinux); 20159 goto skip_full_check; 20160 } 20161 20162 env->strict_alignment = !!(attr->prog_flags & BPF_F_STRICT_ALIGNMENT); 20163 if (!IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS)) 20164 env->strict_alignment = true; 20165 if (attr->prog_flags & BPF_F_ANY_ALIGNMENT) 20166 env->strict_alignment = false; 20167 20168 env->allow_ptr_leaks = bpf_allow_ptr_leaks(); 20169 env->allow_uninit_stack = bpf_allow_uninit_stack(); 20170 env->bypass_spec_v1 = bpf_bypass_spec_v1(); 20171 env->bypass_spec_v4 = bpf_bypass_spec_v4(); 20172 env->bpf_capable = bpf_capable(); 20173 20174 if (is_priv) 20175 env->test_state_freq = attr->prog_flags & BPF_F_TEST_STATE_FREQ; 20176 20177 env->explored_states = kvcalloc(state_htab_size(env), 20178 sizeof(struct bpf_verifier_state_list *), 20179 GFP_USER); 20180 ret = -ENOMEM; 20181 if (!env->explored_states) 20182 goto skip_full_check; 20183 20184 ret = check_btf_info_early(env, attr, uattr); 20185 if (ret < 0) 20186 goto skip_full_check; 20187 20188 ret = add_subprog_and_kfunc(env); 20189 if (ret < 0) 20190 goto skip_full_check; 20191 20192 ret = check_subprogs(env); 20193 if (ret < 0) 20194 goto skip_full_check; 20195 20196 ret = check_btf_info(env, attr, uattr); 20197 if (ret < 0) 20198 goto skip_full_check; 20199 20200 ret = check_attach_btf_id(env); 20201 if (ret) 20202 goto skip_full_check; 20203 20204 ret = resolve_pseudo_ldimm64(env); 20205 if (ret < 0) 20206 goto skip_full_check; 20207 20208 if (bpf_prog_is_offloaded(env->prog->aux)) { 20209 ret = bpf_prog_offload_verifier_prep(env->prog); 20210 if (ret) 20211 goto skip_full_check; 20212 } 20213 20214 ret = check_cfg(env); 20215 if (ret < 0) 20216 goto skip_full_check; 20217 20218 ret = do_check_subprogs(env); 20219 ret = ret ?: do_check_main(env); 20220 20221 if (ret == 0 && bpf_prog_is_offloaded(env->prog->aux)) 20222 ret = bpf_prog_offload_finalize(env); 20223 20224 skip_full_check: 20225 kvfree(env->explored_states); 20226 20227 if (ret == 0) 20228 ret = check_max_stack_depth(env); 20229 20230 /* instruction rewrites happen after this point */ 20231 if (ret == 0) 20232 ret = optimize_bpf_loop(env); 20233 20234 if (is_priv) { 20235 if (ret == 0) 20236 opt_hard_wire_dead_code_branches(env); 20237 if (ret == 0) 20238 ret = opt_remove_dead_code(env); 20239 if (ret == 0) 20240 ret = opt_remove_nops(env); 20241 } else { 20242 if (ret == 0) 20243 sanitize_dead_code(env); 20244 } 20245 20246 if (ret == 0) 20247 /* program is valid, convert *(u32*)(ctx + off) accesses */ 20248 ret = convert_ctx_accesses(env); 20249 20250 if (ret == 0) 20251 ret = do_misc_fixups(env); 20252 20253 /* do 32-bit optimization after insn patching has done so those patched 20254 * insns could be handled correctly. 20255 */ 20256 if (ret == 0 && !bpf_prog_is_offloaded(env->prog->aux)) { 20257 ret = opt_subreg_zext_lo32_rnd_hi32(env, attr); 20258 env->prog->aux->verifier_zext = bpf_jit_needs_zext() ? !ret 20259 : false; 20260 } 20261 20262 if (ret == 0) 20263 ret = fixup_call_args(env); 20264 20265 env->verification_time = ktime_get_ns() - start_time; 20266 print_verification_stats(env); 20267 env->prog->aux->verified_insns = env->insn_processed; 20268 20269 /* preserve original error even if log finalization is successful */ 20270 err = bpf_vlog_finalize(&env->log, &log_true_size); 20271 if (err) 20272 ret = err; 20273 20274 if (uattr_size >= offsetofend(union bpf_attr, log_true_size) && 20275 copy_to_bpfptr_offset(uattr, offsetof(union bpf_attr, log_true_size), 20276 &log_true_size, sizeof(log_true_size))) { 20277 ret = -EFAULT; 20278 goto err_release_maps; 20279 } 20280 20281 if (ret) 20282 goto err_release_maps; 20283 20284 if (env->used_map_cnt) { 20285 /* if program passed verifier, update used_maps in bpf_prog_info */ 20286 env->prog->aux->used_maps = kmalloc_array(env->used_map_cnt, 20287 sizeof(env->used_maps[0]), 20288 GFP_KERNEL); 20289 20290 if (!env->prog->aux->used_maps) { 20291 ret = -ENOMEM; 20292 goto err_release_maps; 20293 } 20294 20295 memcpy(env->prog->aux->used_maps, env->used_maps, 20296 sizeof(env->used_maps[0]) * env->used_map_cnt); 20297 env->prog->aux->used_map_cnt = env->used_map_cnt; 20298 } 20299 if (env->used_btf_cnt) { 20300 /* if program passed verifier, update used_btfs in bpf_prog_aux */ 20301 env->prog->aux->used_btfs = kmalloc_array(env->used_btf_cnt, 20302 sizeof(env->used_btfs[0]), 20303 GFP_KERNEL); 20304 if (!env->prog->aux->used_btfs) { 20305 ret = -ENOMEM; 20306 goto err_release_maps; 20307 } 20308 20309 memcpy(env->prog->aux->used_btfs, env->used_btfs, 20310 sizeof(env->used_btfs[0]) * env->used_btf_cnt); 20311 env->prog->aux->used_btf_cnt = env->used_btf_cnt; 20312 } 20313 if (env->used_map_cnt || env->used_btf_cnt) { 20314 /* program is valid. Convert pseudo bpf_ld_imm64 into generic 20315 * bpf_ld_imm64 instructions 20316 */ 20317 convert_pseudo_ld_imm64(env); 20318 } 20319 20320 adjust_btf_func(env); 20321 20322 err_release_maps: 20323 if (!env->prog->aux->used_maps) 20324 /* if we didn't copy map pointers into bpf_prog_info, release 20325 * them now. Otherwise free_used_maps() will release them. 20326 */ 20327 release_maps(env); 20328 if (!env->prog->aux->used_btfs) 20329 release_btfs(env); 20330 20331 /* extension progs temporarily inherit the attach_type of their targets 20332 for verification purposes, so set it back to zero before returning 20333 */ 20334 if (env->prog->type == BPF_PROG_TYPE_EXT) 20335 env->prog->expected_attach_type = 0; 20336 20337 *prog = env->prog; 20338 err_unlock: 20339 if (!is_priv) 20340 mutex_unlock(&bpf_verifier_lock); 20341 vfree(env->insn_aux_data); 20342 err_free_env: 20343 kfree(env); 20344 return ret; 20345 } 20346