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 29 #include "disasm.h" 30 31 static const struct bpf_verifier_ops * const bpf_verifier_ops[] = { 32 #define BPF_PROG_TYPE(_id, _name, prog_ctx_type, kern_ctx_type) \ 33 [_id] = & _name ## _verifier_ops, 34 #define BPF_MAP_TYPE(_id, _ops) 35 #define BPF_LINK_TYPE(_id, _name) 36 #include <linux/bpf_types.h> 37 #undef BPF_PROG_TYPE 38 #undef BPF_MAP_TYPE 39 #undef BPF_LINK_TYPE 40 }; 41 42 /* bpf_check() is a static code analyzer that walks eBPF program 43 * instruction by instruction and updates register/stack state. 44 * All paths of conditional branches are analyzed until 'bpf_exit' insn. 45 * 46 * The first pass is depth-first-search to check that the program is a DAG. 47 * It rejects the following programs: 48 * - larger than BPF_MAXINSNS insns 49 * - if loop is present (detected via back-edge) 50 * - unreachable insns exist (shouldn't be a forest. program = one function) 51 * - out of bounds or malformed jumps 52 * The second pass is all possible path descent from the 1st insn. 53 * Since it's analyzing all paths through the program, the length of the 54 * analysis is limited to 64k insn, which may be hit even if total number of 55 * insn is less then 4K, but there are too many branches that change stack/regs. 56 * Number of 'branches to be analyzed' is limited to 1k 57 * 58 * On entry to each instruction, each register has a type, and the instruction 59 * changes the types of the registers depending on instruction semantics. 60 * If instruction is BPF_MOV64_REG(BPF_REG_1, BPF_REG_5), then type of R5 is 61 * copied to R1. 62 * 63 * All registers are 64-bit. 64 * R0 - return register 65 * R1-R5 argument passing registers 66 * R6-R9 callee saved registers 67 * R10 - frame pointer read-only 68 * 69 * At the start of BPF program the register R1 contains a pointer to bpf_context 70 * and has type PTR_TO_CTX. 71 * 72 * Verifier tracks arithmetic operations on pointers in case: 73 * BPF_MOV64_REG(BPF_REG_1, BPF_REG_10), 74 * BPF_ALU64_IMM(BPF_ADD, BPF_REG_1, -20), 75 * 1st insn copies R10 (which has FRAME_PTR) type into R1 76 * and 2nd arithmetic instruction is pattern matched to recognize 77 * that it wants to construct a pointer to some element within stack. 78 * So after 2nd insn, the register R1 has type PTR_TO_STACK 79 * (and -20 constant is saved for further stack bounds checking). 80 * Meaning that this reg is a pointer to stack plus known immediate constant. 81 * 82 * Most of the time the registers have SCALAR_VALUE type, which 83 * means the register has some value, but it's not a valid pointer. 84 * (like pointer plus pointer becomes SCALAR_VALUE type) 85 * 86 * When verifier sees load or store instructions the type of base register 87 * can be: PTR_TO_MAP_VALUE, PTR_TO_CTX, PTR_TO_STACK, PTR_TO_SOCKET. These are 88 * four pointer types recognized by check_mem_access() function. 89 * 90 * PTR_TO_MAP_VALUE means that this register is pointing to 'map element value' 91 * and the range of [ptr, ptr + map's value_size) is accessible. 92 * 93 * registers used to pass values to function calls are checked against 94 * function argument constraints. 95 * 96 * ARG_PTR_TO_MAP_KEY is one of such argument constraints. 97 * It means that the register type passed to this function must be 98 * PTR_TO_STACK and it will be used inside the function as 99 * 'pointer to map element key' 100 * 101 * For example the argument constraints for bpf_map_lookup_elem(): 102 * .ret_type = RET_PTR_TO_MAP_VALUE_OR_NULL, 103 * .arg1_type = ARG_CONST_MAP_PTR, 104 * .arg2_type = ARG_PTR_TO_MAP_KEY, 105 * 106 * ret_type says that this function returns 'pointer to map elem value or null' 107 * function expects 1st argument to be a const pointer to 'struct bpf_map' and 108 * 2nd argument should be a pointer to stack, which will be used inside 109 * the helper function as a pointer to map element key. 110 * 111 * On the kernel side the helper function looks like: 112 * u64 bpf_map_lookup_elem(u64 r1, u64 r2, u64 r3, u64 r4, u64 r5) 113 * { 114 * struct bpf_map *map = (struct bpf_map *) (unsigned long) r1; 115 * void *key = (void *) (unsigned long) r2; 116 * void *value; 117 * 118 * here kernel can access 'key' and 'map' pointers safely, knowing that 119 * [key, key + map->key_size) bytes are valid and were initialized on 120 * the stack of eBPF program. 121 * } 122 * 123 * Corresponding eBPF program may look like: 124 * BPF_MOV64_REG(BPF_REG_2, BPF_REG_10), // after this insn R2 type is FRAME_PTR 125 * BPF_ALU64_IMM(BPF_ADD, BPF_REG_2, -4), // after this insn R2 type is PTR_TO_STACK 126 * BPF_LD_MAP_FD(BPF_REG_1, map_fd), // after this insn R1 type is CONST_PTR_TO_MAP 127 * BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0, BPF_FUNC_map_lookup_elem), 128 * here verifier looks at prototype of map_lookup_elem() and sees: 129 * .arg1_type == ARG_CONST_MAP_PTR and R1->type == CONST_PTR_TO_MAP, which is ok, 130 * Now verifier knows that this map has key of R1->map_ptr->key_size bytes 131 * 132 * Then .arg2_type == ARG_PTR_TO_MAP_KEY and R2->type == PTR_TO_STACK, ok so far, 133 * Now verifier checks that [R2, R2 + map's key_size) are within stack limits 134 * and were initialized prior to this call. 135 * If it's ok, then verifier allows this BPF_CALL insn and looks at 136 * .ret_type which is RET_PTR_TO_MAP_VALUE_OR_NULL, so it sets 137 * R0->type = PTR_TO_MAP_VALUE_OR_NULL which means bpf_map_lookup_elem() function 138 * returns either pointer to map value or NULL. 139 * 140 * When type PTR_TO_MAP_VALUE_OR_NULL passes through 'if (reg != 0) goto +off' 141 * insn, the register holding that pointer in the true branch changes state to 142 * PTR_TO_MAP_VALUE and the same register changes state to CONST_IMM in the false 143 * branch. See check_cond_jmp_op(). 144 * 145 * After the call R0 is set to return type of the function and registers R1-R5 146 * are set to NOT_INIT to indicate that they are no longer readable. 147 * 148 * The following reference types represent a potential reference to a kernel 149 * resource which, after first being allocated, must be checked and freed by 150 * the BPF program: 151 * - PTR_TO_SOCKET_OR_NULL, PTR_TO_SOCKET 152 * 153 * When the verifier sees a helper call return a reference type, it allocates a 154 * pointer id for the reference and stores it in the current function state. 155 * Similar to the way that PTR_TO_MAP_VALUE_OR_NULL is converted into 156 * PTR_TO_MAP_VALUE, PTR_TO_SOCKET_OR_NULL becomes PTR_TO_SOCKET when the type 157 * passes through a NULL-check conditional. For the branch wherein the state is 158 * changed to CONST_IMM, the verifier releases the reference. 159 * 160 * For each helper function that allocates a reference, such as 161 * bpf_sk_lookup_tcp(), there is a corresponding release function, such as 162 * bpf_sk_release(). When a reference type passes into the release function, 163 * the verifier also releases the reference. If any unchecked or unreleased 164 * reference remains at the end of the program, the verifier rejects it. 165 */ 166 167 /* verifier_state + insn_idx are pushed to stack when branch is encountered */ 168 struct bpf_verifier_stack_elem { 169 /* verifer state is 'st' 170 * before processing instruction 'insn_idx' 171 * and after processing instruction 'prev_insn_idx' 172 */ 173 struct bpf_verifier_state st; 174 int insn_idx; 175 int prev_insn_idx; 176 struct bpf_verifier_stack_elem *next; 177 /* length of verifier log at the time this state was pushed on stack */ 178 u32 log_pos; 179 }; 180 181 #define BPF_COMPLEXITY_LIMIT_JMP_SEQ 8192 182 #define BPF_COMPLEXITY_LIMIT_STATES 64 183 184 #define BPF_MAP_KEY_POISON (1ULL << 63) 185 #define BPF_MAP_KEY_SEEN (1ULL << 62) 186 187 #define BPF_MAP_PTR_UNPRIV 1UL 188 #define BPF_MAP_PTR_POISON ((void *)((0xeB9FUL << 1) + \ 189 POISON_POINTER_DELTA)) 190 #define BPF_MAP_PTR(X) ((struct bpf_map *)((X) & ~BPF_MAP_PTR_UNPRIV)) 191 192 static int acquire_reference_state(struct bpf_verifier_env *env, int insn_idx); 193 static int release_reference(struct bpf_verifier_env *env, int ref_obj_id); 194 static void invalidate_non_owning_refs(struct bpf_verifier_env *env); 195 static bool in_rbtree_lock_required_cb(struct bpf_verifier_env *env); 196 static int ref_set_non_owning(struct bpf_verifier_env *env, 197 struct bpf_reg_state *reg); 198 static void specialize_kfunc(struct bpf_verifier_env *env, 199 u32 func_id, u16 offset, unsigned long *addr); 200 201 static bool bpf_map_ptr_poisoned(const struct bpf_insn_aux_data *aux) 202 { 203 return BPF_MAP_PTR(aux->map_ptr_state) == BPF_MAP_PTR_POISON; 204 } 205 206 static bool bpf_map_ptr_unpriv(const struct bpf_insn_aux_data *aux) 207 { 208 return aux->map_ptr_state & BPF_MAP_PTR_UNPRIV; 209 } 210 211 static void bpf_map_ptr_store(struct bpf_insn_aux_data *aux, 212 const struct bpf_map *map, bool unpriv) 213 { 214 BUILD_BUG_ON((unsigned long)BPF_MAP_PTR_POISON & BPF_MAP_PTR_UNPRIV); 215 unpriv |= bpf_map_ptr_unpriv(aux); 216 aux->map_ptr_state = (unsigned long)map | 217 (unpriv ? BPF_MAP_PTR_UNPRIV : 0UL); 218 } 219 220 static bool bpf_map_key_poisoned(const struct bpf_insn_aux_data *aux) 221 { 222 return aux->map_key_state & BPF_MAP_KEY_POISON; 223 } 224 225 static bool bpf_map_key_unseen(const struct bpf_insn_aux_data *aux) 226 { 227 return !(aux->map_key_state & BPF_MAP_KEY_SEEN); 228 } 229 230 static u64 bpf_map_key_immediate(const struct bpf_insn_aux_data *aux) 231 { 232 return aux->map_key_state & ~(BPF_MAP_KEY_SEEN | BPF_MAP_KEY_POISON); 233 } 234 235 static void bpf_map_key_store(struct bpf_insn_aux_data *aux, u64 state) 236 { 237 bool poisoned = bpf_map_key_poisoned(aux); 238 239 aux->map_key_state = state | BPF_MAP_KEY_SEEN | 240 (poisoned ? BPF_MAP_KEY_POISON : 0ULL); 241 } 242 243 static bool bpf_helper_call(const struct bpf_insn *insn) 244 { 245 return insn->code == (BPF_JMP | BPF_CALL) && 246 insn->src_reg == 0; 247 } 248 249 static bool bpf_pseudo_call(const struct bpf_insn *insn) 250 { 251 return insn->code == (BPF_JMP | BPF_CALL) && 252 insn->src_reg == BPF_PSEUDO_CALL; 253 } 254 255 static bool bpf_pseudo_kfunc_call(const struct bpf_insn *insn) 256 { 257 return insn->code == (BPF_JMP | BPF_CALL) && 258 insn->src_reg == BPF_PSEUDO_KFUNC_CALL; 259 } 260 261 struct bpf_call_arg_meta { 262 struct bpf_map *map_ptr; 263 bool raw_mode; 264 bool pkt_access; 265 u8 release_regno; 266 int regno; 267 int access_size; 268 int mem_size; 269 u64 msize_max_value; 270 int ref_obj_id; 271 int dynptr_id; 272 int map_uid; 273 int func_id; 274 struct btf *btf; 275 u32 btf_id; 276 struct btf *ret_btf; 277 u32 ret_btf_id; 278 u32 subprogno; 279 struct btf_field *kptr_field; 280 }; 281 282 struct btf_and_id { 283 struct btf *btf; 284 u32 btf_id; 285 }; 286 287 struct bpf_kfunc_call_arg_meta { 288 /* In parameters */ 289 struct btf *btf; 290 u32 func_id; 291 u32 kfunc_flags; 292 const struct btf_type *func_proto; 293 const char *func_name; 294 /* Out parameters */ 295 u32 ref_obj_id; 296 u8 release_regno; 297 bool r0_rdonly; 298 u32 ret_btf_id; 299 u64 r0_size; 300 u32 subprogno; 301 struct { 302 u64 value; 303 bool found; 304 } arg_constant; 305 union { 306 struct btf_and_id arg_obj_drop; 307 struct btf_and_id arg_refcount_acquire; 308 }; 309 struct { 310 struct btf_field *field; 311 } arg_list_head; 312 struct { 313 struct btf_field *field; 314 } arg_rbtree_root; 315 struct { 316 enum bpf_dynptr_type type; 317 u32 id; 318 u32 ref_obj_id; 319 } initialized_dynptr; 320 struct { 321 u8 spi; 322 u8 frameno; 323 } iter; 324 u64 mem_size; 325 }; 326 327 struct btf *btf_vmlinux; 328 329 static DEFINE_MUTEX(bpf_verifier_lock); 330 331 static const struct bpf_line_info * 332 find_linfo(const struct bpf_verifier_env *env, u32 insn_off) 333 { 334 const struct bpf_line_info *linfo; 335 const struct bpf_prog *prog; 336 u32 i, nr_linfo; 337 338 prog = env->prog; 339 nr_linfo = prog->aux->nr_linfo; 340 341 if (!nr_linfo || insn_off >= prog->len) 342 return NULL; 343 344 linfo = prog->aux->linfo; 345 for (i = 1; i < nr_linfo; i++) 346 if (insn_off < linfo[i].insn_off) 347 break; 348 349 return &linfo[i - 1]; 350 } 351 352 __printf(2, 3) static void verbose(void *private_data, const char *fmt, ...) 353 { 354 struct bpf_verifier_env *env = private_data; 355 va_list args; 356 357 if (!bpf_verifier_log_needed(&env->log)) 358 return; 359 360 va_start(args, fmt); 361 bpf_verifier_vlog(&env->log, fmt, args); 362 va_end(args); 363 } 364 365 static const char *ltrim(const char *s) 366 { 367 while (isspace(*s)) 368 s++; 369 370 return s; 371 } 372 373 __printf(3, 4) static void verbose_linfo(struct bpf_verifier_env *env, 374 u32 insn_off, 375 const char *prefix_fmt, ...) 376 { 377 const struct bpf_line_info *linfo; 378 379 if (!bpf_verifier_log_needed(&env->log)) 380 return; 381 382 linfo = find_linfo(env, insn_off); 383 if (!linfo || linfo == env->prev_linfo) 384 return; 385 386 if (prefix_fmt) { 387 va_list args; 388 389 va_start(args, prefix_fmt); 390 bpf_verifier_vlog(&env->log, prefix_fmt, args); 391 va_end(args); 392 } 393 394 verbose(env, "%s\n", 395 ltrim(btf_name_by_offset(env->prog->aux->btf, 396 linfo->line_off))); 397 398 env->prev_linfo = linfo; 399 } 400 401 static void verbose_invalid_scalar(struct bpf_verifier_env *env, 402 struct bpf_reg_state *reg, 403 struct tnum *range, const char *ctx, 404 const char *reg_name) 405 { 406 char tn_buf[48]; 407 408 verbose(env, "At %s the register %s ", ctx, reg_name); 409 if (!tnum_is_unknown(reg->var_off)) { 410 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 411 verbose(env, "has value %s", tn_buf); 412 } else { 413 verbose(env, "has unknown scalar value"); 414 } 415 tnum_strn(tn_buf, sizeof(tn_buf), *range); 416 verbose(env, " should have been in %s\n", tn_buf); 417 } 418 419 static bool type_is_pkt_pointer(enum bpf_reg_type type) 420 { 421 type = base_type(type); 422 return type == PTR_TO_PACKET || 423 type == PTR_TO_PACKET_META; 424 } 425 426 static bool type_is_sk_pointer(enum bpf_reg_type type) 427 { 428 return type == PTR_TO_SOCKET || 429 type == PTR_TO_SOCK_COMMON || 430 type == PTR_TO_TCP_SOCK || 431 type == PTR_TO_XDP_SOCK; 432 } 433 434 static bool type_may_be_null(u32 type) 435 { 436 return type & PTR_MAYBE_NULL; 437 } 438 439 static bool reg_type_not_null(enum bpf_reg_type type) 440 { 441 if (type_may_be_null(type)) 442 return false; 443 444 type = base_type(type); 445 return type == PTR_TO_SOCKET || 446 type == PTR_TO_TCP_SOCK || 447 type == PTR_TO_MAP_VALUE || 448 type == PTR_TO_MAP_KEY || 449 type == PTR_TO_SOCK_COMMON || 450 type == PTR_TO_MEM; 451 } 452 453 static bool type_is_ptr_alloc_obj(u32 type) 454 { 455 return base_type(type) == PTR_TO_BTF_ID && type_flag(type) & MEM_ALLOC; 456 } 457 458 static bool type_is_non_owning_ref(u32 type) 459 { 460 return type_is_ptr_alloc_obj(type) && type_flag(type) & NON_OWN_REF; 461 } 462 463 static struct btf_record *reg_btf_record(const struct bpf_reg_state *reg) 464 { 465 struct btf_record *rec = NULL; 466 struct btf_struct_meta *meta; 467 468 if (reg->type == PTR_TO_MAP_VALUE) { 469 rec = reg->map_ptr->record; 470 } else if (type_is_ptr_alloc_obj(reg->type)) { 471 meta = btf_find_struct_meta(reg->btf, reg->btf_id); 472 if (meta) 473 rec = meta->record; 474 } 475 return rec; 476 } 477 478 static bool subprog_is_global(const struct bpf_verifier_env *env, int subprog) 479 { 480 struct bpf_func_info_aux *aux = env->prog->aux->func_info_aux; 481 482 return aux && aux[subprog].linkage == BTF_FUNC_GLOBAL; 483 } 484 485 static bool reg_may_point_to_spin_lock(const struct bpf_reg_state *reg) 486 { 487 return btf_record_has_field(reg_btf_record(reg), BPF_SPIN_LOCK); 488 } 489 490 static bool type_is_rdonly_mem(u32 type) 491 { 492 return type & MEM_RDONLY; 493 } 494 495 static bool is_acquire_function(enum bpf_func_id func_id, 496 const struct bpf_map *map) 497 { 498 enum bpf_map_type map_type = map ? map->map_type : BPF_MAP_TYPE_UNSPEC; 499 500 if (func_id == BPF_FUNC_sk_lookup_tcp || 501 func_id == BPF_FUNC_sk_lookup_udp || 502 func_id == BPF_FUNC_skc_lookup_tcp || 503 func_id == BPF_FUNC_ringbuf_reserve || 504 func_id == BPF_FUNC_kptr_xchg) 505 return true; 506 507 if (func_id == BPF_FUNC_map_lookup_elem && 508 (map_type == BPF_MAP_TYPE_SOCKMAP || 509 map_type == BPF_MAP_TYPE_SOCKHASH)) 510 return true; 511 512 return false; 513 } 514 515 static bool is_ptr_cast_function(enum bpf_func_id func_id) 516 { 517 return func_id == BPF_FUNC_tcp_sock || 518 func_id == BPF_FUNC_sk_fullsock || 519 func_id == BPF_FUNC_skc_to_tcp_sock || 520 func_id == BPF_FUNC_skc_to_tcp6_sock || 521 func_id == BPF_FUNC_skc_to_udp6_sock || 522 func_id == BPF_FUNC_skc_to_mptcp_sock || 523 func_id == BPF_FUNC_skc_to_tcp_timewait_sock || 524 func_id == BPF_FUNC_skc_to_tcp_request_sock; 525 } 526 527 static bool is_dynptr_ref_function(enum bpf_func_id func_id) 528 { 529 return func_id == BPF_FUNC_dynptr_data; 530 } 531 532 static bool is_callback_calling_kfunc(u32 btf_id); 533 534 static bool is_callback_calling_function(enum bpf_func_id func_id) 535 { 536 return func_id == BPF_FUNC_for_each_map_elem || 537 func_id == BPF_FUNC_timer_set_callback || 538 func_id == BPF_FUNC_find_vma || 539 func_id == BPF_FUNC_loop || 540 func_id == BPF_FUNC_user_ringbuf_drain; 541 } 542 543 static bool is_async_callback_calling_function(enum bpf_func_id func_id) 544 { 545 return func_id == BPF_FUNC_timer_set_callback; 546 } 547 548 static bool is_storage_get_function(enum bpf_func_id func_id) 549 { 550 return func_id == BPF_FUNC_sk_storage_get || 551 func_id == BPF_FUNC_inode_storage_get || 552 func_id == BPF_FUNC_task_storage_get || 553 func_id == BPF_FUNC_cgrp_storage_get; 554 } 555 556 static bool helper_multiple_ref_obj_use(enum bpf_func_id func_id, 557 const struct bpf_map *map) 558 { 559 int ref_obj_uses = 0; 560 561 if (is_ptr_cast_function(func_id)) 562 ref_obj_uses++; 563 if (is_acquire_function(func_id, map)) 564 ref_obj_uses++; 565 if (is_dynptr_ref_function(func_id)) 566 ref_obj_uses++; 567 568 return ref_obj_uses > 1; 569 } 570 571 static bool is_cmpxchg_insn(const struct bpf_insn *insn) 572 { 573 return BPF_CLASS(insn->code) == BPF_STX && 574 BPF_MODE(insn->code) == BPF_ATOMIC && 575 insn->imm == BPF_CMPXCHG; 576 } 577 578 /* string representation of 'enum bpf_reg_type' 579 * 580 * Note that reg_type_str() can not appear more than once in a single verbose() 581 * statement. 582 */ 583 static const char *reg_type_str(struct bpf_verifier_env *env, 584 enum bpf_reg_type type) 585 { 586 char postfix[16] = {0}, prefix[64] = {0}; 587 static const char * const str[] = { 588 [NOT_INIT] = "?", 589 [SCALAR_VALUE] = "scalar", 590 [PTR_TO_CTX] = "ctx", 591 [CONST_PTR_TO_MAP] = "map_ptr", 592 [PTR_TO_MAP_VALUE] = "map_value", 593 [PTR_TO_STACK] = "fp", 594 [PTR_TO_PACKET] = "pkt", 595 [PTR_TO_PACKET_META] = "pkt_meta", 596 [PTR_TO_PACKET_END] = "pkt_end", 597 [PTR_TO_FLOW_KEYS] = "flow_keys", 598 [PTR_TO_SOCKET] = "sock", 599 [PTR_TO_SOCK_COMMON] = "sock_common", 600 [PTR_TO_TCP_SOCK] = "tcp_sock", 601 [PTR_TO_TP_BUFFER] = "tp_buffer", 602 [PTR_TO_XDP_SOCK] = "xdp_sock", 603 [PTR_TO_BTF_ID] = "ptr_", 604 [PTR_TO_MEM] = "mem", 605 [PTR_TO_BUF] = "buf", 606 [PTR_TO_FUNC] = "func", 607 [PTR_TO_MAP_KEY] = "map_key", 608 [CONST_PTR_TO_DYNPTR] = "dynptr_ptr", 609 }; 610 611 if (type & PTR_MAYBE_NULL) { 612 if (base_type(type) == PTR_TO_BTF_ID) 613 strncpy(postfix, "or_null_", 16); 614 else 615 strncpy(postfix, "_or_null", 16); 616 } 617 618 snprintf(prefix, sizeof(prefix), "%s%s%s%s%s%s%s", 619 type & MEM_RDONLY ? "rdonly_" : "", 620 type & MEM_RINGBUF ? "ringbuf_" : "", 621 type & MEM_USER ? "user_" : "", 622 type & MEM_PERCPU ? "percpu_" : "", 623 type & MEM_RCU ? "rcu_" : "", 624 type & PTR_UNTRUSTED ? "untrusted_" : "", 625 type & PTR_TRUSTED ? "trusted_" : "" 626 ); 627 628 snprintf(env->tmp_str_buf, TMP_STR_BUF_LEN, "%s%s%s", 629 prefix, str[base_type(type)], postfix); 630 return env->tmp_str_buf; 631 } 632 633 static char slot_type_char[] = { 634 [STACK_INVALID] = '?', 635 [STACK_SPILL] = 'r', 636 [STACK_MISC] = 'm', 637 [STACK_ZERO] = '0', 638 [STACK_DYNPTR] = 'd', 639 [STACK_ITER] = 'i', 640 }; 641 642 static void print_liveness(struct bpf_verifier_env *env, 643 enum bpf_reg_liveness live) 644 { 645 if (live & (REG_LIVE_READ | REG_LIVE_WRITTEN | REG_LIVE_DONE)) 646 verbose(env, "_"); 647 if (live & REG_LIVE_READ) 648 verbose(env, "r"); 649 if (live & REG_LIVE_WRITTEN) 650 verbose(env, "w"); 651 if (live & REG_LIVE_DONE) 652 verbose(env, "D"); 653 } 654 655 static int __get_spi(s32 off) 656 { 657 return (-off - 1) / BPF_REG_SIZE; 658 } 659 660 static struct bpf_func_state *func(struct bpf_verifier_env *env, 661 const struct bpf_reg_state *reg) 662 { 663 struct bpf_verifier_state *cur = env->cur_state; 664 665 return cur->frame[reg->frameno]; 666 } 667 668 static bool is_spi_bounds_valid(struct bpf_func_state *state, int spi, int nr_slots) 669 { 670 int allocated_slots = state->allocated_stack / BPF_REG_SIZE; 671 672 /* We need to check that slots between [spi - nr_slots + 1, spi] are 673 * within [0, allocated_stack). 674 * 675 * Please note that the spi grows downwards. For example, a dynptr 676 * takes the size of two stack slots; the first slot will be at 677 * spi and the second slot will be at spi - 1. 678 */ 679 return spi - nr_slots + 1 >= 0 && spi < allocated_slots; 680 } 681 682 static int stack_slot_obj_get_spi(struct bpf_verifier_env *env, struct bpf_reg_state *reg, 683 const char *obj_kind, int nr_slots) 684 { 685 int off, spi; 686 687 if (!tnum_is_const(reg->var_off)) { 688 verbose(env, "%s has to be at a constant offset\n", obj_kind); 689 return -EINVAL; 690 } 691 692 off = reg->off + reg->var_off.value; 693 if (off % BPF_REG_SIZE) { 694 verbose(env, "cannot pass in %s at an offset=%d\n", obj_kind, off); 695 return -EINVAL; 696 } 697 698 spi = __get_spi(off); 699 if (spi + 1 < nr_slots) { 700 verbose(env, "cannot pass in %s at an offset=%d\n", obj_kind, off); 701 return -EINVAL; 702 } 703 704 if (!is_spi_bounds_valid(func(env, reg), spi, nr_slots)) 705 return -ERANGE; 706 return spi; 707 } 708 709 static int dynptr_get_spi(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 710 { 711 return stack_slot_obj_get_spi(env, reg, "dynptr", BPF_DYNPTR_NR_SLOTS); 712 } 713 714 static int iter_get_spi(struct bpf_verifier_env *env, struct bpf_reg_state *reg, int nr_slots) 715 { 716 return stack_slot_obj_get_spi(env, reg, "iter", nr_slots); 717 } 718 719 static const char *btf_type_name(const struct btf *btf, u32 id) 720 { 721 return btf_name_by_offset(btf, btf_type_by_id(btf, id)->name_off); 722 } 723 724 static const char *dynptr_type_str(enum bpf_dynptr_type type) 725 { 726 switch (type) { 727 case BPF_DYNPTR_TYPE_LOCAL: 728 return "local"; 729 case BPF_DYNPTR_TYPE_RINGBUF: 730 return "ringbuf"; 731 case BPF_DYNPTR_TYPE_SKB: 732 return "skb"; 733 case BPF_DYNPTR_TYPE_XDP: 734 return "xdp"; 735 case BPF_DYNPTR_TYPE_INVALID: 736 return "<invalid>"; 737 default: 738 WARN_ONCE(1, "unknown dynptr type %d\n", type); 739 return "<unknown>"; 740 } 741 } 742 743 static const char *iter_type_str(const struct btf *btf, u32 btf_id) 744 { 745 if (!btf || btf_id == 0) 746 return "<invalid>"; 747 748 /* we already validated that type is valid and has conforming name */ 749 return btf_type_name(btf, btf_id) + sizeof(ITER_PREFIX) - 1; 750 } 751 752 static const char *iter_state_str(enum bpf_iter_state state) 753 { 754 switch (state) { 755 case BPF_ITER_STATE_ACTIVE: 756 return "active"; 757 case BPF_ITER_STATE_DRAINED: 758 return "drained"; 759 case BPF_ITER_STATE_INVALID: 760 return "<invalid>"; 761 default: 762 WARN_ONCE(1, "unknown iter state %d\n", state); 763 return "<unknown>"; 764 } 765 } 766 767 static void mark_reg_scratched(struct bpf_verifier_env *env, u32 regno) 768 { 769 env->scratched_regs |= 1U << regno; 770 } 771 772 static void mark_stack_slot_scratched(struct bpf_verifier_env *env, u32 spi) 773 { 774 env->scratched_stack_slots |= 1ULL << spi; 775 } 776 777 static bool reg_scratched(const struct bpf_verifier_env *env, u32 regno) 778 { 779 return (env->scratched_regs >> regno) & 1; 780 } 781 782 static bool stack_slot_scratched(const struct bpf_verifier_env *env, u64 regno) 783 { 784 return (env->scratched_stack_slots >> regno) & 1; 785 } 786 787 static bool verifier_state_scratched(const struct bpf_verifier_env *env) 788 { 789 return env->scratched_regs || env->scratched_stack_slots; 790 } 791 792 static void mark_verifier_state_clean(struct bpf_verifier_env *env) 793 { 794 env->scratched_regs = 0U; 795 env->scratched_stack_slots = 0ULL; 796 } 797 798 /* Used for printing the entire verifier state. */ 799 static void mark_verifier_state_scratched(struct bpf_verifier_env *env) 800 { 801 env->scratched_regs = ~0U; 802 env->scratched_stack_slots = ~0ULL; 803 } 804 805 static enum bpf_dynptr_type arg_to_dynptr_type(enum bpf_arg_type arg_type) 806 { 807 switch (arg_type & DYNPTR_TYPE_FLAG_MASK) { 808 case DYNPTR_TYPE_LOCAL: 809 return BPF_DYNPTR_TYPE_LOCAL; 810 case DYNPTR_TYPE_RINGBUF: 811 return BPF_DYNPTR_TYPE_RINGBUF; 812 case DYNPTR_TYPE_SKB: 813 return BPF_DYNPTR_TYPE_SKB; 814 case DYNPTR_TYPE_XDP: 815 return BPF_DYNPTR_TYPE_XDP; 816 default: 817 return BPF_DYNPTR_TYPE_INVALID; 818 } 819 } 820 821 static enum bpf_type_flag get_dynptr_type_flag(enum bpf_dynptr_type type) 822 { 823 switch (type) { 824 case BPF_DYNPTR_TYPE_LOCAL: 825 return DYNPTR_TYPE_LOCAL; 826 case BPF_DYNPTR_TYPE_RINGBUF: 827 return DYNPTR_TYPE_RINGBUF; 828 case BPF_DYNPTR_TYPE_SKB: 829 return DYNPTR_TYPE_SKB; 830 case BPF_DYNPTR_TYPE_XDP: 831 return DYNPTR_TYPE_XDP; 832 default: 833 return 0; 834 } 835 } 836 837 static bool dynptr_type_refcounted(enum bpf_dynptr_type type) 838 { 839 return type == BPF_DYNPTR_TYPE_RINGBUF; 840 } 841 842 static void __mark_dynptr_reg(struct bpf_reg_state *reg, 843 enum bpf_dynptr_type type, 844 bool first_slot, int dynptr_id); 845 846 static void __mark_reg_not_init(const struct bpf_verifier_env *env, 847 struct bpf_reg_state *reg); 848 849 static void mark_dynptr_stack_regs(struct bpf_verifier_env *env, 850 struct bpf_reg_state *sreg1, 851 struct bpf_reg_state *sreg2, 852 enum bpf_dynptr_type type) 853 { 854 int id = ++env->id_gen; 855 856 __mark_dynptr_reg(sreg1, type, true, id); 857 __mark_dynptr_reg(sreg2, type, false, id); 858 } 859 860 static void mark_dynptr_cb_reg(struct bpf_verifier_env *env, 861 struct bpf_reg_state *reg, 862 enum bpf_dynptr_type type) 863 { 864 __mark_dynptr_reg(reg, type, true, ++env->id_gen); 865 } 866 867 static int destroy_if_dynptr_stack_slot(struct bpf_verifier_env *env, 868 struct bpf_func_state *state, int spi); 869 870 static int mark_stack_slots_dynptr(struct bpf_verifier_env *env, struct bpf_reg_state *reg, 871 enum bpf_arg_type arg_type, int insn_idx, int clone_ref_obj_id) 872 { 873 struct bpf_func_state *state = func(env, reg); 874 enum bpf_dynptr_type type; 875 int spi, i, err; 876 877 spi = dynptr_get_spi(env, reg); 878 if (spi < 0) 879 return spi; 880 881 /* We cannot assume both spi and spi - 1 belong to the same dynptr, 882 * hence we need to call destroy_if_dynptr_stack_slot twice for both, 883 * to ensure that for the following example: 884 * [d1][d1][d2][d2] 885 * spi 3 2 1 0 886 * So marking spi = 2 should lead to destruction of both d1 and d2. In 887 * case they do belong to same dynptr, second call won't see slot_type 888 * as STACK_DYNPTR and will simply skip destruction. 889 */ 890 err = destroy_if_dynptr_stack_slot(env, state, spi); 891 if (err) 892 return err; 893 err = destroy_if_dynptr_stack_slot(env, state, spi - 1); 894 if (err) 895 return err; 896 897 for (i = 0; i < BPF_REG_SIZE; i++) { 898 state->stack[spi].slot_type[i] = STACK_DYNPTR; 899 state->stack[spi - 1].slot_type[i] = STACK_DYNPTR; 900 } 901 902 type = arg_to_dynptr_type(arg_type); 903 if (type == BPF_DYNPTR_TYPE_INVALID) 904 return -EINVAL; 905 906 mark_dynptr_stack_regs(env, &state->stack[spi].spilled_ptr, 907 &state->stack[spi - 1].spilled_ptr, type); 908 909 if (dynptr_type_refcounted(type)) { 910 /* The id is used to track proper releasing */ 911 int id; 912 913 if (clone_ref_obj_id) 914 id = clone_ref_obj_id; 915 else 916 id = acquire_reference_state(env, insn_idx); 917 918 if (id < 0) 919 return id; 920 921 state->stack[spi].spilled_ptr.ref_obj_id = id; 922 state->stack[spi - 1].spilled_ptr.ref_obj_id = id; 923 } 924 925 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN; 926 state->stack[spi - 1].spilled_ptr.live |= REG_LIVE_WRITTEN; 927 928 return 0; 929 } 930 931 static void invalidate_dynptr(struct bpf_verifier_env *env, struct bpf_func_state *state, int spi) 932 { 933 int i; 934 935 for (i = 0; i < BPF_REG_SIZE; i++) { 936 state->stack[spi].slot_type[i] = STACK_INVALID; 937 state->stack[spi - 1].slot_type[i] = STACK_INVALID; 938 } 939 940 __mark_reg_not_init(env, &state->stack[spi].spilled_ptr); 941 __mark_reg_not_init(env, &state->stack[spi - 1].spilled_ptr); 942 943 /* Why do we need to set REG_LIVE_WRITTEN for STACK_INVALID slot? 944 * 945 * While we don't allow reading STACK_INVALID, it is still possible to 946 * do <8 byte writes marking some but not all slots as STACK_MISC. Then, 947 * helpers or insns can do partial read of that part without failing, 948 * but check_stack_range_initialized, check_stack_read_var_off, and 949 * check_stack_read_fixed_off will do mark_reg_read for all 8-bytes of 950 * the slot conservatively. Hence we need to prevent those liveness 951 * marking walks. 952 * 953 * This was not a problem before because STACK_INVALID is only set by 954 * default (where the default reg state has its reg->parent as NULL), or 955 * in clean_live_states after REG_LIVE_DONE (at which point 956 * mark_reg_read won't walk reg->parent chain), but not randomly during 957 * verifier state exploration (like we did above). Hence, for our case 958 * parentage chain will still be live (i.e. reg->parent may be 959 * non-NULL), while earlier reg->parent was NULL, so we need 960 * REG_LIVE_WRITTEN to screen off read marker propagation when it is 961 * done later on reads or by mark_dynptr_read as well to unnecessary 962 * mark registers in verifier state. 963 */ 964 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN; 965 state->stack[spi - 1].spilled_ptr.live |= REG_LIVE_WRITTEN; 966 } 967 968 static int unmark_stack_slots_dynptr(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 969 { 970 struct bpf_func_state *state = func(env, reg); 971 int spi, ref_obj_id, i; 972 973 spi = dynptr_get_spi(env, reg); 974 if (spi < 0) 975 return spi; 976 977 if (!dynptr_type_refcounted(state->stack[spi].spilled_ptr.dynptr.type)) { 978 invalidate_dynptr(env, state, spi); 979 return 0; 980 } 981 982 ref_obj_id = state->stack[spi].spilled_ptr.ref_obj_id; 983 984 /* If the dynptr has a ref_obj_id, then we need to invalidate 985 * two things: 986 * 987 * 1) Any dynptrs with a matching ref_obj_id (clones) 988 * 2) Any slices derived from this dynptr. 989 */ 990 991 /* Invalidate any slices associated with this dynptr */ 992 WARN_ON_ONCE(release_reference(env, ref_obj_id)); 993 994 /* Invalidate any dynptr clones */ 995 for (i = 1; i < state->allocated_stack / BPF_REG_SIZE; i++) { 996 if (state->stack[i].spilled_ptr.ref_obj_id != ref_obj_id) 997 continue; 998 999 /* it should always be the case that if the ref obj id 1000 * matches then the stack slot also belongs to a 1001 * dynptr 1002 */ 1003 if (state->stack[i].slot_type[0] != STACK_DYNPTR) { 1004 verbose(env, "verifier internal error: misconfigured ref_obj_id\n"); 1005 return -EFAULT; 1006 } 1007 if (state->stack[i].spilled_ptr.dynptr.first_slot) 1008 invalidate_dynptr(env, state, i); 1009 } 1010 1011 return 0; 1012 } 1013 1014 static void __mark_reg_unknown(const struct bpf_verifier_env *env, 1015 struct bpf_reg_state *reg); 1016 1017 static void mark_reg_invalid(const struct bpf_verifier_env *env, struct bpf_reg_state *reg) 1018 { 1019 if (!env->allow_ptr_leaks) 1020 __mark_reg_not_init(env, reg); 1021 else 1022 __mark_reg_unknown(env, reg); 1023 } 1024 1025 static int destroy_if_dynptr_stack_slot(struct bpf_verifier_env *env, 1026 struct bpf_func_state *state, int spi) 1027 { 1028 struct bpf_func_state *fstate; 1029 struct bpf_reg_state *dreg; 1030 int i, dynptr_id; 1031 1032 /* We always ensure that STACK_DYNPTR is never set partially, 1033 * hence just checking for slot_type[0] is enough. This is 1034 * different for STACK_SPILL, where it may be only set for 1035 * 1 byte, so code has to use is_spilled_reg. 1036 */ 1037 if (state->stack[spi].slot_type[0] != STACK_DYNPTR) 1038 return 0; 1039 1040 /* Reposition spi to first slot */ 1041 if (!state->stack[spi].spilled_ptr.dynptr.first_slot) 1042 spi = spi + 1; 1043 1044 if (dynptr_type_refcounted(state->stack[spi].spilled_ptr.dynptr.type)) { 1045 verbose(env, "cannot overwrite referenced dynptr\n"); 1046 return -EINVAL; 1047 } 1048 1049 mark_stack_slot_scratched(env, spi); 1050 mark_stack_slot_scratched(env, spi - 1); 1051 1052 /* Writing partially to one dynptr stack slot destroys both. */ 1053 for (i = 0; i < BPF_REG_SIZE; i++) { 1054 state->stack[spi].slot_type[i] = STACK_INVALID; 1055 state->stack[spi - 1].slot_type[i] = STACK_INVALID; 1056 } 1057 1058 dynptr_id = state->stack[spi].spilled_ptr.id; 1059 /* Invalidate any slices associated with this dynptr */ 1060 bpf_for_each_reg_in_vstate(env->cur_state, fstate, dreg, ({ 1061 /* Dynptr slices are only PTR_TO_MEM_OR_NULL and PTR_TO_MEM */ 1062 if (dreg->type != (PTR_TO_MEM | PTR_MAYBE_NULL) && dreg->type != PTR_TO_MEM) 1063 continue; 1064 if (dreg->dynptr_id == dynptr_id) 1065 mark_reg_invalid(env, dreg); 1066 })); 1067 1068 /* Do not release reference state, we are destroying dynptr on stack, 1069 * not using some helper to release it. Just reset register. 1070 */ 1071 __mark_reg_not_init(env, &state->stack[spi].spilled_ptr); 1072 __mark_reg_not_init(env, &state->stack[spi - 1].spilled_ptr); 1073 1074 /* Same reason as unmark_stack_slots_dynptr above */ 1075 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN; 1076 state->stack[spi - 1].spilled_ptr.live |= REG_LIVE_WRITTEN; 1077 1078 return 0; 1079 } 1080 1081 static bool is_dynptr_reg_valid_uninit(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 1082 { 1083 int spi; 1084 1085 if (reg->type == CONST_PTR_TO_DYNPTR) 1086 return false; 1087 1088 spi = dynptr_get_spi(env, reg); 1089 1090 /* -ERANGE (i.e. spi not falling into allocated stack slots) isn't an 1091 * error because this just means the stack state hasn't been updated yet. 1092 * We will do check_mem_access to check and update stack bounds later. 1093 */ 1094 if (spi < 0 && spi != -ERANGE) 1095 return false; 1096 1097 /* We don't need to check if the stack slots are marked by previous 1098 * dynptr initializations because we allow overwriting existing unreferenced 1099 * STACK_DYNPTR slots, see mark_stack_slots_dynptr which calls 1100 * destroy_if_dynptr_stack_slot to ensure dynptr objects at the slots we are 1101 * touching are completely destructed before we reinitialize them for a new 1102 * one. For referenced ones, destroy_if_dynptr_stack_slot returns an error early 1103 * instead of delaying it until the end where the user will get "Unreleased 1104 * reference" error. 1105 */ 1106 return true; 1107 } 1108 1109 static bool is_dynptr_reg_valid_init(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 1110 { 1111 struct bpf_func_state *state = func(env, reg); 1112 int i, spi; 1113 1114 /* This already represents first slot of initialized bpf_dynptr. 1115 * 1116 * CONST_PTR_TO_DYNPTR already has fixed and var_off as 0 due to 1117 * check_func_arg_reg_off's logic, so we don't need to check its 1118 * offset and alignment. 1119 */ 1120 if (reg->type == CONST_PTR_TO_DYNPTR) 1121 return true; 1122 1123 spi = dynptr_get_spi(env, reg); 1124 if (spi < 0) 1125 return false; 1126 if (!state->stack[spi].spilled_ptr.dynptr.first_slot) 1127 return false; 1128 1129 for (i = 0; i < BPF_REG_SIZE; i++) { 1130 if (state->stack[spi].slot_type[i] != STACK_DYNPTR || 1131 state->stack[spi - 1].slot_type[i] != STACK_DYNPTR) 1132 return false; 1133 } 1134 1135 return true; 1136 } 1137 1138 static bool is_dynptr_type_expected(struct bpf_verifier_env *env, struct bpf_reg_state *reg, 1139 enum bpf_arg_type arg_type) 1140 { 1141 struct bpf_func_state *state = func(env, reg); 1142 enum bpf_dynptr_type dynptr_type; 1143 int spi; 1144 1145 /* ARG_PTR_TO_DYNPTR takes any type of dynptr */ 1146 if (arg_type == ARG_PTR_TO_DYNPTR) 1147 return true; 1148 1149 dynptr_type = arg_to_dynptr_type(arg_type); 1150 if (reg->type == CONST_PTR_TO_DYNPTR) { 1151 return reg->dynptr.type == dynptr_type; 1152 } else { 1153 spi = dynptr_get_spi(env, reg); 1154 if (spi < 0) 1155 return false; 1156 return state->stack[spi].spilled_ptr.dynptr.type == dynptr_type; 1157 } 1158 } 1159 1160 static void __mark_reg_known_zero(struct bpf_reg_state *reg); 1161 1162 static int mark_stack_slots_iter(struct bpf_verifier_env *env, 1163 struct bpf_reg_state *reg, int insn_idx, 1164 struct btf *btf, u32 btf_id, int nr_slots) 1165 { 1166 struct bpf_func_state *state = func(env, reg); 1167 int spi, i, j, id; 1168 1169 spi = iter_get_spi(env, reg, nr_slots); 1170 if (spi < 0) 1171 return spi; 1172 1173 id = acquire_reference_state(env, insn_idx); 1174 if (id < 0) 1175 return id; 1176 1177 for (i = 0; i < nr_slots; i++) { 1178 struct bpf_stack_state *slot = &state->stack[spi - i]; 1179 struct bpf_reg_state *st = &slot->spilled_ptr; 1180 1181 __mark_reg_known_zero(st); 1182 st->type = PTR_TO_STACK; /* we don't have dedicated reg type */ 1183 st->live |= REG_LIVE_WRITTEN; 1184 st->ref_obj_id = i == 0 ? id : 0; 1185 st->iter.btf = btf; 1186 st->iter.btf_id = btf_id; 1187 st->iter.state = BPF_ITER_STATE_ACTIVE; 1188 st->iter.depth = 0; 1189 1190 for (j = 0; j < BPF_REG_SIZE; j++) 1191 slot->slot_type[j] = STACK_ITER; 1192 1193 mark_stack_slot_scratched(env, spi - i); 1194 } 1195 1196 return 0; 1197 } 1198 1199 static int unmark_stack_slots_iter(struct bpf_verifier_env *env, 1200 struct bpf_reg_state *reg, int nr_slots) 1201 { 1202 struct bpf_func_state *state = func(env, reg); 1203 int spi, i, j; 1204 1205 spi = iter_get_spi(env, reg, nr_slots); 1206 if (spi < 0) 1207 return spi; 1208 1209 for (i = 0; i < nr_slots; i++) { 1210 struct bpf_stack_state *slot = &state->stack[spi - i]; 1211 struct bpf_reg_state *st = &slot->spilled_ptr; 1212 1213 if (i == 0) 1214 WARN_ON_ONCE(release_reference(env, st->ref_obj_id)); 1215 1216 __mark_reg_not_init(env, st); 1217 1218 /* see unmark_stack_slots_dynptr() for why we need to set REG_LIVE_WRITTEN */ 1219 st->live |= REG_LIVE_WRITTEN; 1220 1221 for (j = 0; j < BPF_REG_SIZE; j++) 1222 slot->slot_type[j] = STACK_INVALID; 1223 1224 mark_stack_slot_scratched(env, spi - i); 1225 } 1226 1227 return 0; 1228 } 1229 1230 static bool is_iter_reg_valid_uninit(struct bpf_verifier_env *env, 1231 struct bpf_reg_state *reg, int nr_slots) 1232 { 1233 struct bpf_func_state *state = func(env, reg); 1234 int spi, i, j; 1235 1236 /* For -ERANGE (i.e. spi not falling into allocated stack slots), we 1237 * will do check_mem_access to check and update stack bounds later, so 1238 * return true for that case. 1239 */ 1240 spi = iter_get_spi(env, reg, nr_slots); 1241 if (spi == -ERANGE) 1242 return true; 1243 if (spi < 0) 1244 return false; 1245 1246 for (i = 0; i < nr_slots; i++) { 1247 struct bpf_stack_state *slot = &state->stack[spi - i]; 1248 1249 for (j = 0; j < BPF_REG_SIZE; j++) 1250 if (slot->slot_type[j] == STACK_ITER) 1251 return false; 1252 } 1253 1254 return true; 1255 } 1256 1257 static bool is_iter_reg_valid_init(struct bpf_verifier_env *env, struct bpf_reg_state *reg, 1258 struct btf *btf, u32 btf_id, int nr_slots) 1259 { 1260 struct bpf_func_state *state = func(env, reg); 1261 int spi, i, j; 1262 1263 spi = iter_get_spi(env, reg, nr_slots); 1264 if (spi < 0) 1265 return false; 1266 1267 for (i = 0; i < nr_slots; i++) { 1268 struct bpf_stack_state *slot = &state->stack[spi - i]; 1269 struct bpf_reg_state *st = &slot->spilled_ptr; 1270 1271 /* only main (first) slot has ref_obj_id set */ 1272 if (i == 0 && !st->ref_obj_id) 1273 return false; 1274 if (i != 0 && st->ref_obj_id) 1275 return false; 1276 if (st->iter.btf != btf || st->iter.btf_id != btf_id) 1277 return false; 1278 1279 for (j = 0; j < BPF_REG_SIZE; j++) 1280 if (slot->slot_type[j] != STACK_ITER) 1281 return false; 1282 } 1283 1284 return true; 1285 } 1286 1287 /* Check if given stack slot is "special": 1288 * - spilled register state (STACK_SPILL); 1289 * - dynptr state (STACK_DYNPTR); 1290 * - iter state (STACK_ITER). 1291 */ 1292 static bool is_stack_slot_special(const struct bpf_stack_state *stack) 1293 { 1294 enum bpf_stack_slot_type type = stack->slot_type[BPF_REG_SIZE - 1]; 1295 1296 switch (type) { 1297 case STACK_SPILL: 1298 case STACK_DYNPTR: 1299 case STACK_ITER: 1300 return true; 1301 case STACK_INVALID: 1302 case STACK_MISC: 1303 case STACK_ZERO: 1304 return false; 1305 default: 1306 WARN_ONCE(1, "unknown stack slot type %d\n", type); 1307 return true; 1308 } 1309 } 1310 1311 /* The reg state of a pointer or a bounded scalar was saved when 1312 * it was spilled to the stack. 1313 */ 1314 static bool is_spilled_reg(const struct bpf_stack_state *stack) 1315 { 1316 return stack->slot_type[BPF_REG_SIZE - 1] == STACK_SPILL; 1317 } 1318 1319 static bool is_spilled_scalar_reg(const struct bpf_stack_state *stack) 1320 { 1321 return stack->slot_type[BPF_REG_SIZE - 1] == STACK_SPILL && 1322 stack->spilled_ptr.type == SCALAR_VALUE; 1323 } 1324 1325 static void scrub_spilled_slot(u8 *stype) 1326 { 1327 if (*stype != STACK_INVALID) 1328 *stype = STACK_MISC; 1329 } 1330 1331 static void print_verifier_state(struct bpf_verifier_env *env, 1332 const struct bpf_func_state *state, 1333 bool print_all) 1334 { 1335 const struct bpf_reg_state *reg; 1336 enum bpf_reg_type t; 1337 int i; 1338 1339 if (state->frameno) 1340 verbose(env, " frame%d:", state->frameno); 1341 for (i = 0; i < MAX_BPF_REG; i++) { 1342 reg = &state->regs[i]; 1343 t = reg->type; 1344 if (t == NOT_INIT) 1345 continue; 1346 if (!print_all && !reg_scratched(env, i)) 1347 continue; 1348 verbose(env, " R%d", i); 1349 print_liveness(env, reg->live); 1350 verbose(env, "="); 1351 if (t == SCALAR_VALUE && reg->precise) 1352 verbose(env, "P"); 1353 if ((t == SCALAR_VALUE || t == PTR_TO_STACK) && 1354 tnum_is_const(reg->var_off)) { 1355 /* reg->off should be 0 for SCALAR_VALUE */ 1356 verbose(env, "%s", t == SCALAR_VALUE ? "" : reg_type_str(env, t)); 1357 verbose(env, "%lld", reg->var_off.value + reg->off); 1358 } else { 1359 const char *sep = ""; 1360 1361 verbose(env, "%s", reg_type_str(env, t)); 1362 if (base_type(t) == PTR_TO_BTF_ID) 1363 verbose(env, "%s", btf_type_name(reg->btf, reg->btf_id)); 1364 verbose(env, "("); 1365 /* 1366 * _a stands for append, was shortened to avoid multiline statements below. 1367 * This macro is used to output a comma separated list of attributes. 1368 */ 1369 #define verbose_a(fmt, ...) ({ verbose(env, "%s" fmt, sep, __VA_ARGS__); sep = ","; }) 1370 1371 if (reg->id) 1372 verbose_a("id=%d", reg->id); 1373 if (reg->ref_obj_id) 1374 verbose_a("ref_obj_id=%d", reg->ref_obj_id); 1375 if (type_is_non_owning_ref(reg->type)) 1376 verbose_a("%s", "non_own_ref"); 1377 if (t != SCALAR_VALUE) 1378 verbose_a("off=%d", reg->off); 1379 if (type_is_pkt_pointer(t)) 1380 verbose_a("r=%d", reg->range); 1381 else if (base_type(t) == CONST_PTR_TO_MAP || 1382 base_type(t) == PTR_TO_MAP_KEY || 1383 base_type(t) == PTR_TO_MAP_VALUE) 1384 verbose_a("ks=%d,vs=%d", 1385 reg->map_ptr->key_size, 1386 reg->map_ptr->value_size); 1387 if (tnum_is_const(reg->var_off)) { 1388 /* Typically an immediate SCALAR_VALUE, but 1389 * could be a pointer whose offset is too big 1390 * for reg->off 1391 */ 1392 verbose_a("imm=%llx", reg->var_off.value); 1393 } else { 1394 if (reg->smin_value != reg->umin_value && 1395 reg->smin_value != S64_MIN) 1396 verbose_a("smin=%lld", (long long)reg->smin_value); 1397 if (reg->smax_value != reg->umax_value && 1398 reg->smax_value != S64_MAX) 1399 verbose_a("smax=%lld", (long long)reg->smax_value); 1400 if (reg->umin_value != 0) 1401 verbose_a("umin=%llu", (unsigned long long)reg->umin_value); 1402 if (reg->umax_value != U64_MAX) 1403 verbose_a("umax=%llu", (unsigned long long)reg->umax_value); 1404 if (!tnum_is_unknown(reg->var_off)) { 1405 char tn_buf[48]; 1406 1407 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 1408 verbose_a("var_off=%s", tn_buf); 1409 } 1410 if (reg->s32_min_value != reg->smin_value && 1411 reg->s32_min_value != S32_MIN) 1412 verbose_a("s32_min=%d", (int)(reg->s32_min_value)); 1413 if (reg->s32_max_value != reg->smax_value && 1414 reg->s32_max_value != S32_MAX) 1415 verbose_a("s32_max=%d", (int)(reg->s32_max_value)); 1416 if (reg->u32_min_value != reg->umin_value && 1417 reg->u32_min_value != U32_MIN) 1418 verbose_a("u32_min=%d", (int)(reg->u32_min_value)); 1419 if (reg->u32_max_value != reg->umax_value && 1420 reg->u32_max_value != U32_MAX) 1421 verbose_a("u32_max=%d", (int)(reg->u32_max_value)); 1422 } 1423 #undef verbose_a 1424 1425 verbose(env, ")"); 1426 } 1427 } 1428 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) { 1429 char types_buf[BPF_REG_SIZE + 1]; 1430 bool valid = false; 1431 int j; 1432 1433 for (j = 0; j < BPF_REG_SIZE; j++) { 1434 if (state->stack[i].slot_type[j] != STACK_INVALID) 1435 valid = true; 1436 types_buf[j] = slot_type_char[state->stack[i].slot_type[j]]; 1437 } 1438 types_buf[BPF_REG_SIZE] = 0; 1439 if (!valid) 1440 continue; 1441 if (!print_all && !stack_slot_scratched(env, i)) 1442 continue; 1443 switch (state->stack[i].slot_type[BPF_REG_SIZE - 1]) { 1444 case STACK_SPILL: 1445 reg = &state->stack[i].spilled_ptr; 1446 t = reg->type; 1447 1448 verbose(env, " fp%d", (-i - 1) * BPF_REG_SIZE); 1449 print_liveness(env, reg->live); 1450 verbose(env, "=%s", t == SCALAR_VALUE ? "" : reg_type_str(env, t)); 1451 if (t == SCALAR_VALUE && reg->precise) 1452 verbose(env, "P"); 1453 if (t == SCALAR_VALUE && tnum_is_const(reg->var_off)) 1454 verbose(env, "%lld", reg->var_off.value + reg->off); 1455 break; 1456 case STACK_DYNPTR: 1457 i += BPF_DYNPTR_NR_SLOTS - 1; 1458 reg = &state->stack[i].spilled_ptr; 1459 1460 verbose(env, " fp%d", (-i - 1) * BPF_REG_SIZE); 1461 print_liveness(env, reg->live); 1462 verbose(env, "=dynptr_%s", dynptr_type_str(reg->dynptr.type)); 1463 if (reg->ref_obj_id) 1464 verbose(env, "(ref_id=%d)", reg->ref_obj_id); 1465 break; 1466 case STACK_ITER: 1467 /* only main slot has ref_obj_id set; skip others */ 1468 reg = &state->stack[i].spilled_ptr; 1469 if (!reg->ref_obj_id) 1470 continue; 1471 1472 verbose(env, " fp%d", (-i - 1) * BPF_REG_SIZE); 1473 print_liveness(env, reg->live); 1474 verbose(env, "=iter_%s(ref_id=%d,state=%s,depth=%u)", 1475 iter_type_str(reg->iter.btf, reg->iter.btf_id), 1476 reg->ref_obj_id, iter_state_str(reg->iter.state), 1477 reg->iter.depth); 1478 break; 1479 case STACK_MISC: 1480 case STACK_ZERO: 1481 default: 1482 reg = &state->stack[i].spilled_ptr; 1483 1484 for (j = 0; j < BPF_REG_SIZE; j++) 1485 types_buf[j] = slot_type_char[state->stack[i].slot_type[j]]; 1486 types_buf[BPF_REG_SIZE] = 0; 1487 1488 verbose(env, " fp%d", (-i - 1) * BPF_REG_SIZE); 1489 print_liveness(env, reg->live); 1490 verbose(env, "=%s", types_buf); 1491 break; 1492 } 1493 } 1494 if (state->acquired_refs && state->refs[0].id) { 1495 verbose(env, " refs=%d", state->refs[0].id); 1496 for (i = 1; i < state->acquired_refs; i++) 1497 if (state->refs[i].id) 1498 verbose(env, ",%d", state->refs[i].id); 1499 } 1500 if (state->in_callback_fn) 1501 verbose(env, " cb"); 1502 if (state->in_async_callback_fn) 1503 verbose(env, " async_cb"); 1504 verbose(env, "\n"); 1505 mark_verifier_state_clean(env); 1506 } 1507 1508 static inline u32 vlog_alignment(u32 pos) 1509 { 1510 return round_up(max(pos + BPF_LOG_MIN_ALIGNMENT / 2, BPF_LOG_ALIGNMENT), 1511 BPF_LOG_MIN_ALIGNMENT) - pos - 1; 1512 } 1513 1514 static void print_insn_state(struct bpf_verifier_env *env, 1515 const struct bpf_func_state *state) 1516 { 1517 if (env->prev_log_pos && env->prev_log_pos == env->log.end_pos) { 1518 /* remove new line character */ 1519 bpf_vlog_reset(&env->log, env->prev_log_pos - 1); 1520 verbose(env, "%*c;", vlog_alignment(env->prev_insn_print_pos), ' '); 1521 } else { 1522 verbose(env, "%d:", env->insn_idx); 1523 } 1524 print_verifier_state(env, state, false); 1525 } 1526 1527 /* copy array src of length n * size bytes to dst. dst is reallocated if it's too 1528 * small to hold src. This is different from krealloc since we don't want to preserve 1529 * the contents of dst. 1530 * 1531 * Leaves dst untouched if src is NULL or length is zero. Returns NULL if memory could 1532 * not be allocated. 1533 */ 1534 static void *copy_array(void *dst, const void *src, size_t n, size_t size, gfp_t flags) 1535 { 1536 size_t alloc_bytes; 1537 void *orig = dst; 1538 size_t bytes; 1539 1540 if (ZERO_OR_NULL_PTR(src)) 1541 goto out; 1542 1543 if (unlikely(check_mul_overflow(n, size, &bytes))) 1544 return NULL; 1545 1546 alloc_bytes = max(ksize(orig), kmalloc_size_roundup(bytes)); 1547 dst = krealloc(orig, alloc_bytes, flags); 1548 if (!dst) { 1549 kfree(orig); 1550 return NULL; 1551 } 1552 1553 memcpy(dst, src, bytes); 1554 out: 1555 return dst ? dst : ZERO_SIZE_PTR; 1556 } 1557 1558 /* resize an array from old_n items to new_n items. the array is reallocated if it's too 1559 * small to hold new_n items. new items are zeroed out if the array grows. 1560 * 1561 * Contrary to krealloc_array, does not free arr if new_n is zero. 1562 */ 1563 static void *realloc_array(void *arr, size_t old_n, size_t new_n, size_t size) 1564 { 1565 size_t alloc_size; 1566 void *new_arr; 1567 1568 if (!new_n || old_n == new_n) 1569 goto out; 1570 1571 alloc_size = kmalloc_size_roundup(size_mul(new_n, size)); 1572 new_arr = krealloc(arr, alloc_size, GFP_KERNEL); 1573 if (!new_arr) { 1574 kfree(arr); 1575 return NULL; 1576 } 1577 arr = new_arr; 1578 1579 if (new_n > old_n) 1580 memset(arr + old_n * size, 0, (new_n - old_n) * size); 1581 1582 out: 1583 return arr ? arr : ZERO_SIZE_PTR; 1584 } 1585 1586 static int copy_reference_state(struct bpf_func_state *dst, const struct bpf_func_state *src) 1587 { 1588 dst->refs = copy_array(dst->refs, src->refs, src->acquired_refs, 1589 sizeof(struct bpf_reference_state), GFP_KERNEL); 1590 if (!dst->refs) 1591 return -ENOMEM; 1592 1593 dst->acquired_refs = src->acquired_refs; 1594 return 0; 1595 } 1596 1597 static int copy_stack_state(struct bpf_func_state *dst, const struct bpf_func_state *src) 1598 { 1599 size_t n = src->allocated_stack / BPF_REG_SIZE; 1600 1601 dst->stack = copy_array(dst->stack, src->stack, n, sizeof(struct bpf_stack_state), 1602 GFP_KERNEL); 1603 if (!dst->stack) 1604 return -ENOMEM; 1605 1606 dst->allocated_stack = src->allocated_stack; 1607 return 0; 1608 } 1609 1610 static int resize_reference_state(struct bpf_func_state *state, size_t n) 1611 { 1612 state->refs = realloc_array(state->refs, state->acquired_refs, n, 1613 sizeof(struct bpf_reference_state)); 1614 if (!state->refs) 1615 return -ENOMEM; 1616 1617 state->acquired_refs = n; 1618 return 0; 1619 } 1620 1621 static int grow_stack_state(struct bpf_func_state *state, int size) 1622 { 1623 size_t old_n = state->allocated_stack / BPF_REG_SIZE, n = size / BPF_REG_SIZE; 1624 1625 if (old_n >= n) 1626 return 0; 1627 1628 state->stack = realloc_array(state->stack, old_n, n, sizeof(struct bpf_stack_state)); 1629 if (!state->stack) 1630 return -ENOMEM; 1631 1632 state->allocated_stack = size; 1633 return 0; 1634 } 1635 1636 /* Acquire a pointer id from the env and update the state->refs to include 1637 * this new pointer reference. 1638 * On success, returns a valid pointer id to associate with the register 1639 * On failure, returns a negative errno. 1640 */ 1641 static int acquire_reference_state(struct bpf_verifier_env *env, int insn_idx) 1642 { 1643 struct bpf_func_state *state = cur_func(env); 1644 int new_ofs = state->acquired_refs; 1645 int id, err; 1646 1647 err = resize_reference_state(state, state->acquired_refs + 1); 1648 if (err) 1649 return err; 1650 id = ++env->id_gen; 1651 state->refs[new_ofs].id = id; 1652 state->refs[new_ofs].insn_idx = insn_idx; 1653 state->refs[new_ofs].callback_ref = state->in_callback_fn ? state->frameno : 0; 1654 1655 return id; 1656 } 1657 1658 /* release function corresponding to acquire_reference_state(). Idempotent. */ 1659 static int release_reference_state(struct bpf_func_state *state, int ptr_id) 1660 { 1661 int i, last_idx; 1662 1663 last_idx = state->acquired_refs - 1; 1664 for (i = 0; i < state->acquired_refs; i++) { 1665 if (state->refs[i].id == ptr_id) { 1666 /* Cannot release caller references in callbacks */ 1667 if (state->in_callback_fn && state->refs[i].callback_ref != state->frameno) 1668 return -EINVAL; 1669 if (last_idx && i != last_idx) 1670 memcpy(&state->refs[i], &state->refs[last_idx], 1671 sizeof(*state->refs)); 1672 memset(&state->refs[last_idx], 0, sizeof(*state->refs)); 1673 state->acquired_refs--; 1674 return 0; 1675 } 1676 } 1677 return -EINVAL; 1678 } 1679 1680 static void free_func_state(struct bpf_func_state *state) 1681 { 1682 if (!state) 1683 return; 1684 kfree(state->refs); 1685 kfree(state->stack); 1686 kfree(state); 1687 } 1688 1689 static void clear_jmp_history(struct bpf_verifier_state *state) 1690 { 1691 kfree(state->jmp_history); 1692 state->jmp_history = NULL; 1693 state->jmp_history_cnt = 0; 1694 } 1695 1696 static void free_verifier_state(struct bpf_verifier_state *state, 1697 bool free_self) 1698 { 1699 int i; 1700 1701 for (i = 0; i <= state->curframe; i++) { 1702 free_func_state(state->frame[i]); 1703 state->frame[i] = NULL; 1704 } 1705 clear_jmp_history(state); 1706 if (free_self) 1707 kfree(state); 1708 } 1709 1710 /* copy verifier state from src to dst growing dst stack space 1711 * when necessary to accommodate larger src stack 1712 */ 1713 static int copy_func_state(struct bpf_func_state *dst, 1714 const struct bpf_func_state *src) 1715 { 1716 int err; 1717 1718 memcpy(dst, src, offsetof(struct bpf_func_state, acquired_refs)); 1719 err = copy_reference_state(dst, src); 1720 if (err) 1721 return err; 1722 return copy_stack_state(dst, src); 1723 } 1724 1725 static int copy_verifier_state(struct bpf_verifier_state *dst_state, 1726 const struct bpf_verifier_state *src) 1727 { 1728 struct bpf_func_state *dst; 1729 int i, err; 1730 1731 dst_state->jmp_history = copy_array(dst_state->jmp_history, src->jmp_history, 1732 src->jmp_history_cnt, sizeof(struct bpf_idx_pair), 1733 GFP_USER); 1734 if (!dst_state->jmp_history) 1735 return -ENOMEM; 1736 dst_state->jmp_history_cnt = src->jmp_history_cnt; 1737 1738 /* if dst has more stack frames then src frame, free them */ 1739 for (i = src->curframe + 1; i <= dst_state->curframe; i++) { 1740 free_func_state(dst_state->frame[i]); 1741 dst_state->frame[i] = NULL; 1742 } 1743 dst_state->speculative = src->speculative; 1744 dst_state->active_rcu_lock = src->active_rcu_lock; 1745 dst_state->curframe = src->curframe; 1746 dst_state->active_lock.ptr = src->active_lock.ptr; 1747 dst_state->active_lock.id = src->active_lock.id; 1748 dst_state->branches = src->branches; 1749 dst_state->parent = src->parent; 1750 dst_state->first_insn_idx = src->first_insn_idx; 1751 dst_state->last_insn_idx = src->last_insn_idx; 1752 for (i = 0; i <= src->curframe; i++) { 1753 dst = dst_state->frame[i]; 1754 if (!dst) { 1755 dst = kzalloc(sizeof(*dst), GFP_KERNEL); 1756 if (!dst) 1757 return -ENOMEM; 1758 dst_state->frame[i] = dst; 1759 } 1760 err = copy_func_state(dst, src->frame[i]); 1761 if (err) 1762 return err; 1763 } 1764 return 0; 1765 } 1766 1767 static void update_branch_counts(struct bpf_verifier_env *env, struct bpf_verifier_state *st) 1768 { 1769 while (st) { 1770 u32 br = --st->branches; 1771 1772 /* WARN_ON(br > 1) technically makes sense here, 1773 * but see comment in push_stack(), hence: 1774 */ 1775 WARN_ONCE((int)br < 0, 1776 "BUG update_branch_counts:branches_to_explore=%d\n", 1777 br); 1778 if (br) 1779 break; 1780 st = st->parent; 1781 } 1782 } 1783 1784 static int pop_stack(struct bpf_verifier_env *env, int *prev_insn_idx, 1785 int *insn_idx, bool pop_log) 1786 { 1787 struct bpf_verifier_state *cur = env->cur_state; 1788 struct bpf_verifier_stack_elem *elem, *head = env->head; 1789 int err; 1790 1791 if (env->head == NULL) 1792 return -ENOENT; 1793 1794 if (cur) { 1795 err = copy_verifier_state(cur, &head->st); 1796 if (err) 1797 return err; 1798 } 1799 if (pop_log) 1800 bpf_vlog_reset(&env->log, head->log_pos); 1801 if (insn_idx) 1802 *insn_idx = head->insn_idx; 1803 if (prev_insn_idx) 1804 *prev_insn_idx = head->prev_insn_idx; 1805 elem = head->next; 1806 free_verifier_state(&head->st, false); 1807 kfree(head); 1808 env->head = elem; 1809 env->stack_size--; 1810 return 0; 1811 } 1812 1813 static struct bpf_verifier_state *push_stack(struct bpf_verifier_env *env, 1814 int insn_idx, int prev_insn_idx, 1815 bool speculative) 1816 { 1817 struct bpf_verifier_state *cur = env->cur_state; 1818 struct bpf_verifier_stack_elem *elem; 1819 int err; 1820 1821 elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL); 1822 if (!elem) 1823 goto err; 1824 1825 elem->insn_idx = insn_idx; 1826 elem->prev_insn_idx = prev_insn_idx; 1827 elem->next = env->head; 1828 elem->log_pos = env->log.end_pos; 1829 env->head = elem; 1830 env->stack_size++; 1831 err = copy_verifier_state(&elem->st, cur); 1832 if (err) 1833 goto err; 1834 elem->st.speculative |= speculative; 1835 if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) { 1836 verbose(env, "The sequence of %d jumps is too complex.\n", 1837 env->stack_size); 1838 goto err; 1839 } 1840 if (elem->st.parent) { 1841 ++elem->st.parent->branches; 1842 /* WARN_ON(branches > 2) technically makes sense here, 1843 * but 1844 * 1. speculative states will bump 'branches' for non-branch 1845 * instructions 1846 * 2. is_state_visited() heuristics may decide not to create 1847 * a new state for a sequence of branches and all such current 1848 * and cloned states will be pointing to a single parent state 1849 * which might have large 'branches' count. 1850 */ 1851 } 1852 return &elem->st; 1853 err: 1854 free_verifier_state(env->cur_state, true); 1855 env->cur_state = NULL; 1856 /* pop all elements and return */ 1857 while (!pop_stack(env, NULL, NULL, false)); 1858 return NULL; 1859 } 1860 1861 #define CALLER_SAVED_REGS 6 1862 static const int caller_saved[CALLER_SAVED_REGS] = { 1863 BPF_REG_0, BPF_REG_1, BPF_REG_2, BPF_REG_3, BPF_REG_4, BPF_REG_5 1864 }; 1865 1866 /* This helper doesn't clear reg->id */ 1867 static void ___mark_reg_known(struct bpf_reg_state *reg, u64 imm) 1868 { 1869 reg->var_off = tnum_const(imm); 1870 reg->smin_value = (s64)imm; 1871 reg->smax_value = (s64)imm; 1872 reg->umin_value = imm; 1873 reg->umax_value = imm; 1874 1875 reg->s32_min_value = (s32)imm; 1876 reg->s32_max_value = (s32)imm; 1877 reg->u32_min_value = (u32)imm; 1878 reg->u32_max_value = (u32)imm; 1879 } 1880 1881 /* Mark the unknown part of a register (variable offset or scalar value) as 1882 * known to have the value @imm. 1883 */ 1884 static void __mark_reg_known(struct bpf_reg_state *reg, u64 imm) 1885 { 1886 /* Clear off and union(map_ptr, range) */ 1887 memset(((u8 *)reg) + sizeof(reg->type), 0, 1888 offsetof(struct bpf_reg_state, var_off) - sizeof(reg->type)); 1889 reg->id = 0; 1890 reg->ref_obj_id = 0; 1891 ___mark_reg_known(reg, imm); 1892 } 1893 1894 static void __mark_reg32_known(struct bpf_reg_state *reg, u64 imm) 1895 { 1896 reg->var_off = tnum_const_subreg(reg->var_off, imm); 1897 reg->s32_min_value = (s32)imm; 1898 reg->s32_max_value = (s32)imm; 1899 reg->u32_min_value = (u32)imm; 1900 reg->u32_max_value = (u32)imm; 1901 } 1902 1903 /* Mark the 'variable offset' part of a register as zero. This should be 1904 * used only on registers holding a pointer type. 1905 */ 1906 static void __mark_reg_known_zero(struct bpf_reg_state *reg) 1907 { 1908 __mark_reg_known(reg, 0); 1909 } 1910 1911 static void __mark_reg_const_zero(struct bpf_reg_state *reg) 1912 { 1913 __mark_reg_known(reg, 0); 1914 reg->type = SCALAR_VALUE; 1915 } 1916 1917 static void mark_reg_known_zero(struct bpf_verifier_env *env, 1918 struct bpf_reg_state *regs, u32 regno) 1919 { 1920 if (WARN_ON(regno >= MAX_BPF_REG)) { 1921 verbose(env, "mark_reg_known_zero(regs, %u)\n", regno); 1922 /* Something bad happened, let's kill all regs */ 1923 for (regno = 0; regno < MAX_BPF_REG; regno++) 1924 __mark_reg_not_init(env, regs + regno); 1925 return; 1926 } 1927 __mark_reg_known_zero(regs + regno); 1928 } 1929 1930 static void __mark_dynptr_reg(struct bpf_reg_state *reg, enum bpf_dynptr_type type, 1931 bool first_slot, int dynptr_id) 1932 { 1933 /* reg->type has no meaning for STACK_DYNPTR, but when we set reg for 1934 * callback arguments, it does need to be CONST_PTR_TO_DYNPTR, so simply 1935 * set it unconditionally as it is ignored for STACK_DYNPTR anyway. 1936 */ 1937 __mark_reg_known_zero(reg); 1938 reg->type = CONST_PTR_TO_DYNPTR; 1939 /* Give each dynptr a unique id to uniquely associate slices to it. */ 1940 reg->id = dynptr_id; 1941 reg->dynptr.type = type; 1942 reg->dynptr.first_slot = first_slot; 1943 } 1944 1945 static void mark_ptr_not_null_reg(struct bpf_reg_state *reg) 1946 { 1947 if (base_type(reg->type) == PTR_TO_MAP_VALUE) { 1948 const struct bpf_map *map = reg->map_ptr; 1949 1950 if (map->inner_map_meta) { 1951 reg->type = CONST_PTR_TO_MAP; 1952 reg->map_ptr = map->inner_map_meta; 1953 /* transfer reg's id which is unique for every map_lookup_elem 1954 * as UID of the inner map. 1955 */ 1956 if (btf_record_has_field(map->inner_map_meta->record, BPF_TIMER)) 1957 reg->map_uid = reg->id; 1958 } else if (map->map_type == BPF_MAP_TYPE_XSKMAP) { 1959 reg->type = PTR_TO_XDP_SOCK; 1960 } else if (map->map_type == BPF_MAP_TYPE_SOCKMAP || 1961 map->map_type == BPF_MAP_TYPE_SOCKHASH) { 1962 reg->type = PTR_TO_SOCKET; 1963 } else { 1964 reg->type = PTR_TO_MAP_VALUE; 1965 } 1966 return; 1967 } 1968 1969 reg->type &= ~PTR_MAYBE_NULL; 1970 } 1971 1972 static void mark_reg_graph_node(struct bpf_reg_state *regs, u32 regno, 1973 struct btf_field_graph_root *ds_head) 1974 { 1975 __mark_reg_known_zero(®s[regno]); 1976 regs[regno].type = PTR_TO_BTF_ID | MEM_ALLOC; 1977 regs[regno].btf = ds_head->btf; 1978 regs[regno].btf_id = ds_head->value_btf_id; 1979 regs[regno].off = ds_head->node_offset; 1980 } 1981 1982 static bool reg_is_pkt_pointer(const struct bpf_reg_state *reg) 1983 { 1984 return type_is_pkt_pointer(reg->type); 1985 } 1986 1987 static bool reg_is_pkt_pointer_any(const struct bpf_reg_state *reg) 1988 { 1989 return reg_is_pkt_pointer(reg) || 1990 reg->type == PTR_TO_PACKET_END; 1991 } 1992 1993 static bool reg_is_dynptr_slice_pkt(const struct bpf_reg_state *reg) 1994 { 1995 return base_type(reg->type) == PTR_TO_MEM && 1996 (reg->type & DYNPTR_TYPE_SKB || reg->type & DYNPTR_TYPE_XDP); 1997 } 1998 1999 /* Unmodified PTR_TO_PACKET[_META,_END] register from ctx access. */ 2000 static bool reg_is_init_pkt_pointer(const struct bpf_reg_state *reg, 2001 enum bpf_reg_type which) 2002 { 2003 /* The register can already have a range from prior markings. 2004 * This is fine as long as it hasn't been advanced from its 2005 * origin. 2006 */ 2007 return reg->type == which && 2008 reg->id == 0 && 2009 reg->off == 0 && 2010 tnum_equals_const(reg->var_off, 0); 2011 } 2012 2013 /* Reset the min/max bounds of a register */ 2014 static void __mark_reg_unbounded(struct bpf_reg_state *reg) 2015 { 2016 reg->smin_value = S64_MIN; 2017 reg->smax_value = S64_MAX; 2018 reg->umin_value = 0; 2019 reg->umax_value = U64_MAX; 2020 2021 reg->s32_min_value = S32_MIN; 2022 reg->s32_max_value = S32_MAX; 2023 reg->u32_min_value = 0; 2024 reg->u32_max_value = U32_MAX; 2025 } 2026 2027 static void __mark_reg64_unbounded(struct bpf_reg_state *reg) 2028 { 2029 reg->smin_value = S64_MIN; 2030 reg->smax_value = S64_MAX; 2031 reg->umin_value = 0; 2032 reg->umax_value = U64_MAX; 2033 } 2034 2035 static void __mark_reg32_unbounded(struct bpf_reg_state *reg) 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 __update_reg32_bounds(struct bpf_reg_state *reg) 2044 { 2045 struct tnum var32_off = tnum_subreg(reg->var_off); 2046 2047 /* min signed is max(sign bit) | min(other bits) */ 2048 reg->s32_min_value = max_t(s32, reg->s32_min_value, 2049 var32_off.value | (var32_off.mask & S32_MIN)); 2050 /* max signed is min(sign bit) | max(other bits) */ 2051 reg->s32_max_value = min_t(s32, reg->s32_max_value, 2052 var32_off.value | (var32_off.mask & S32_MAX)); 2053 reg->u32_min_value = max_t(u32, reg->u32_min_value, (u32)var32_off.value); 2054 reg->u32_max_value = min(reg->u32_max_value, 2055 (u32)(var32_off.value | var32_off.mask)); 2056 } 2057 2058 static void __update_reg64_bounds(struct bpf_reg_state *reg) 2059 { 2060 /* min signed is max(sign bit) | min(other bits) */ 2061 reg->smin_value = max_t(s64, reg->smin_value, 2062 reg->var_off.value | (reg->var_off.mask & S64_MIN)); 2063 /* max signed is min(sign bit) | max(other bits) */ 2064 reg->smax_value = min_t(s64, reg->smax_value, 2065 reg->var_off.value | (reg->var_off.mask & S64_MAX)); 2066 reg->umin_value = max(reg->umin_value, reg->var_off.value); 2067 reg->umax_value = min(reg->umax_value, 2068 reg->var_off.value | reg->var_off.mask); 2069 } 2070 2071 static void __update_reg_bounds(struct bpf_reg_state *reg) 2072 { 2073 __update_reg32_bounds(reg); 2074 __update_reg64_bounds(reg); 2075 } 2076 2077 /* Uses signed min/max values to inform unsigned, and vice-versa */ 2078 static void __reg32_deduce_bounds(struct bpf_reg_state *reg) 2079 { 2080 /* Learn sign from signed bounds. 2081 * If we cannot cross the sign boundary, then signed and unsigned bounds 2082 * are the same, so combine. This works even in the negative case, e.g. 2083 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff. 2084 */ 2085 if (reg->s32_min_value >= 0 || reg->s32_max_value < 0) { 2086 reg->s32_min_value = reg->u32_min_value = 2087 max_t(u32, reg->s32_min_value, reg->u32_min_value); 2088 reg->s32_max_value = reg->u32_max_value = 2089 min_t(u32, reg->s32_max_value, reg->u32_max_value); 2090 return; 2091 } 2092 /* Learn sign from unsigned bounds. Signed bounds cross the sign 2093 * boundary, so we must be careful. 2094 */ 2095 if ((s32)reg->u32_max_value >= 0) { 2096 /* Positive. We can't learn anything from the smin, but smax 2097 * is positive, hence safe. 2098 */ 2099 reg->s32_min_value = reg->u32_min_value; 2100 reg->s32_max_value = reg->u32_max_value = 2101 min_t(u32, reg->s32_max_value, reg->u32_max_value); 2102 } else if ((s32)reg->u32_min_value < 0) { 2103 /* Negative. We can't learn anything from the smax, but smin 2104 * is negative, hence safe. 2105 */ 2106 reg->s32_min_value = reg->u32_min_value = 2107 max_t(u32, reg->s32_min_value, reg->u32_min_value); 2108 reg->s32_max_value = reg->u32_max_value; 2109 } 2110 } 2111 2112 static void __reg64_deduce_bounds(struct bpf_reg_state *reg) 2113 { 2114 /* Learn sign from signed bounds. 2115 * If we cannot cross the sign boundary, then signed and unsigned bounds 2116 * are the same, so combine. This works even in the negative case, e.g. 2117 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff. 2118 */ 2119 if (reg->smin_value >= 0 || reg->smax_value < 0) { 2120 reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value, 2121 reg->umin_value); 2122 reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value, 2123 reg->umax_value); 2124 return; 2125 } 2126 /* Learn sign from unsigned bounds. Signed bounds cross the sign 2127 * boundary, so we must be careful. 2128 */ 2129 if ((s64)reg->umax_value >= 0) { 2130 /* Positive. We can't learn anything from the smin, but smax 2131 * is positive, hence safe. 2132 */ 2133 reg->smin_value = reg->umin_value; 2134 reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value, 2135 reg->umax_value); 2136 } else if ((s64)reg->umin_value < 0) { 2137 /* Negative. We can't learn anything from the smax, but smin 2138 * is negative, hence safe. 2139 */ 2140 reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value, 2141 reg->umin_value); 2142 reg->smax_value = reg->umax_value; 2143 } 2144 } 2145 2146 static void __reg_deduce_bounds(struct bpf_reg_state *reg) 2147 { 2148 __reg32_deduce_bounds(reg); 2149 __reg64_deduce_bounds(reg); 2150 } 2151 2152 /* Attempts to improve var_off based on unsigned min/max information */ 2153 static void __reg_bound_offset(struct bpf_reg_state *reg) 2154 { 2155 struct tnum var64_off = tnum_intersect(reg->var_off, 2156 tnum_range(reg->umin_value, 2157 reg->umax_value)); 2158 struct tnum var32_off = tnum_intersect(tnum_subreg(var64_off), 2159 tnum_range(reg->u32_min_value, 2160 reg->u32_max_value)); 2161 2162 reg->var_off = tnum_or(tnum_clear_subreg(var64_off), var32_off); 2163 } 2164 2165 static void reg_bounds_sync(struct bpf_reg_state *reg) 2166 { 2167 /* We might have learned new bounds from the var_off. */ 2168 __update_reg_bounds(reg); 2169 /* We might have learned something about the sign bit. */ 2170 __reg_deduce_bounds(reg); 2171 /* We might have learned some bits from the bounds. */ 2172 __reg_bound_offset(reg); 2173 /* Intersecting with the old var_off might have improved our bounds 2174 * slightly, e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc), 2175 * then new var_off is (0; 0x7f...fc) which improves our umax. 2176 */ 2177 __update_reg_bounds(reg); 2178 } 2179 2180 static bool __reg32_bound_s64(s32 a) 2181 { 2182 return a >= 0 && a <= S32_MAX; 2183 } 2184 2185 static void __reg_assign_32_into_64(struct bpf_reg_state *reg) 2186 { 2187 reg->umin_value = reg->u32_min_value; 2188 reg->umax_value = reg->u32_max_value; 2189 2190 /* Attempt to pull 32-bit signed bounds into 64-bit bounds but must 2191 * be positive otherwise set to worse case bounds and refine later 2192 * from tnum. 2193 */ 2194 if (__reg32_bound_s64(reg->s32_min_value) && 2195 __reg32_bound_s64(reg->s32_max_value)) { 2196 reg->smin_value = reg->s32_min_value; 2197 reg->smax_value = reg->s32_max_value; 2198 } else { 2199 reg->smin_value = 0; 2200 reg->smax_value = U32_MAX; 2201 } 2202 } 2203 2204 static void __reg_combine_32_into_64(struct bpf_reg_state *reg) 2205 { 2206 /* special case when 64-bit register has upper 32-bit register 2207 * zeroed. Typically happens after zext or <<32, >>32 sequence 2208 * allowing us to use 32-bit bounds directly, 2209 */ 2210 if (tnum_equals_const(tnum_clear_subreg(reg->var_off), 0)) { 2211 __reg_assign_32_into_64(reg); 2212 } else { 2213 /* Otherwise the best we can do is push lower 32bit known and 2214 * unknown bits into register (var_off set from jmp logic) 2215 * then learn as much as possible from the 64-bit tnum 2216 * known and unknown bits. The previous smin/smax bounds are 2217 * invalid here because of jmp32 compare so mark them unknown 2218 * so they do not impact tnum bounds calculation. 2219 */ 2220 __mark_reg64_unbounded(reg); 2221 } 2222 reg_bounds_sync(reg); 2223 } 2224 2225 static bool __reg64_bound_s32(s64 a) 2226 { 2227 return a >= S32_MIN && a <= S32_MAX; 2228 } 2229 2230 static bool __reg64_bound_u32(u64 a) 2231 { 2232 return a >= U32_MIN && a <= U32_MAX; 2233 } 2234 2235 static void __reg_combine_64_into_32(struct bpf_reg_state *reg) 2236 { 2237 __mark_reg32_unbounded(reg); 2238 if (__reg64_bound_s32(reg->smin_value) && __reg64_bound_s32(reg->smax_value)) { 2239 reg->s32_min_value = (s32)reg->smin_value; 2240 reg->s32_max_value = (s32)reg->smax_value; 2241 } 2242 if (__reg64_bound_u32(reg->umin_value) && __reg64_bound_u32(reg->umax_value)) { 2243 reg->u32_min_value = (u32)reg->umin_value; 2244 reg->u32_max_value = (u32)reg->umax_value; 2245 } 2246 reg_bounds_sync(reg); 2247 } 2248 2249 /* Mark a register as having a completely unknown (scalar) value. */ 2250 static void __mark_reg_unknown(const struct bpf_verifier_env *env, 2251 struct bpf_reg_state *reg) 2252 { 2253 /* 2254 * Clear type, off, and union(map_ptr, range) and 2255 * padding between 'type' and union 2256 */ 2257 memset(reg, 0, offsetof(struct bpf_reg_state, var_off)); 2258 reg->type = SCALAR_VALUE; 2259 reg->id = 0; 2260 reg->ref_obj_id = 0; 2261 reg->var_off = tnum_unknown; 2262 reg->frameno = 0; 2263 reg->precise = !env->bpf_capable; 2264 __mark_reg_unbounded(reg); 2265 } 2266 2267 static void mark_reg_unknown(struct bpf_verifier_env *env, 2268 struct bpf_reg_state *regs, u32 regno) 2269 { 2270 if (WARN_ON(regno >= MAX_BPF_REG)) { 2271 verbose(env, "mark_reg_unknown(regs, %u)\n", regno); 2272 /* Something bad happened, let's kill all regs except FP */ 2273 for (regno = 0; regno < BPF_REG_FP; regno++) 2274 __mark_reg_not_init(env, regs + regno); 2275 return; 2276 } 2277 __mark_reg_unknown(env, regs + regno); 2278 } 2279 2280 static void __mark_reg_not_init(const struct bpf_verifier_env *env, 2281 struct bpf_reg_state *reg) 2282 { 2283 __mark_reg_unknown(env, reg); 2284 reg->type = NOT_INIT; 2285 } 2286 2287 static void mark_reg_not_init(struct bpf_verifier_env *env, 2288 struct bpf_reg_state *regs, u32 regno) 2289 { 2290 if (WARN_ON(regno >= MAX_BPF_REG)) { 2291 verbose(env, "mark_reg_not_init(regs, %u)\n", regno); 2292 /* Something bad happened, let's kill all regs except FP */ 2293 for (regno = 0; regno < BPF_REG_FP; regno++) 2294 __mark_reg_not_init(env, regs + regno); 2295 return; 2296 } 2297 __mark_reg_not_init(env, regs + regno); 2298 } 2299 2300 static void mark_btf_ld_reg(struct bpf_verifier_env *env, 2301 struct bpf_reg_state *regs, u32 regno, 2302 enum bpf_reg_type reg_type, 2303 struct btf *btf, u32 btf_id, 2304 enum bpf_type_flag flag) 2305 { 2306 if (reg_type == SCALAR_VALUE) { 2307 mark_reg_unknown(env, regs, regno); 2308 return; 2309 } 2310 mark_reg_known_zero(env, regs, regno); 2311 regs[regno].type = PTR_TO_BTF_ID | flag; 2312 regs[regno].btf = btf; 2313 regs[regno].btf_id = btf_id; 2314 } 2315 2316 #define DEF_NOT_SUBREG (0) 2317 static void init_reg_state(struct bpf_verifier_env *env, 2318 struct bpf_func_state *state) 2319 { 2320 struct bpf_reg_state *regs = state->regs; 2321 int i; 2322 2323 for (i = 0; i < MAX_BPF_REG; i++) { 2324 mark_reg_not_init(env, regs, i); 2325 regs[i].live = REG_LIVE_NONE; 2326 regs[i].parent = NULL; 2327 regs[i].subreg_def = DEF_NOT_SUBREG; 2328 } 2329 2330 /* frame pointer */ 2331 regs[BPF_REG_FP].type = PTR_TO_STACK; 2332 mark_reg_known_zero(env, regs, BPF_REG_FP); 2333 regs[BPF_REG_FP].frameno = state->frameno; 2334 } 2335 2336 #define BPF_MAIN_FUNC (-1) 2337 static void init_func_state(struct bpf_verifier_env *env, 2338 struct bpf_func_state *state, 2339 int callsite, int frameno, int subprogno) 2340 { 2341 state->callsite = callsite; 2342 state->frameno = frameno; 2343 state->subprogno = subprogno; 2344 state->callback_ret_range = tnum_range(0, 0); 2345 init_reg_state(env, state); 2346 mark_verifier_state_scratched(env); 2347 } 2348 2349 /* Similar to push_stack(), but for async callbacks */ 2350 static struct bpf_verifier_state *push_async_cb(struct bpf_verifier_env *env, 2351 int insn_idx, int prev_insn_idx, 2352 int subprog) 2353 { 2354 struct bpf_verifier_stack_elem *elem; 2355 struct bpf_func_state *frame; 2356 2357 elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL); 2358 if (!elem) 2359 goto err; 2360 2361 elem->insn_idx = insn_idx; 2362 elem->prev_insn_idx = prev_insn_idx; 2363 elem->next = env->head; 2364 elem->log_pos = env->log.end_pos; 2365 env->head = elem; 2366 env->stack_size++; 2367 if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) { 2368 verbose(env, 2369 "The sequence of %d jumps is too complex for async cb.\n", 2370 env->stack_size); 2371 goto err; 2372 } 2373 /* Unlike push_stack() do not copy_verifier_state(). 2374 * The caller state doesn't matter. 2375 * This is async callback. It starts in a fresh stack. 2376 * Initialize it similar to do_check_common(). 2377 */ 2378 elem->st.branches = 1; 2379 frame = kzalloc(sizeof(*frame), GFP_KERNEL); 2380 if (!frame) 2381 goto err; 2382 init_func_state(env, frame, 2383 BPF_MAIN_FUNC /* callsite */, 2384 0 /* frameno within this callchain */, 2385 subprog /* subprog number within this prog */); 2386 elem->st.frame[0] = frame; 2387 return &elem->st; 2388 err: 2389 free_verifier_state(env->cur_state, true); 2390 env->cur_state = NULL; 2391 /* pop all elements and return */ 2392 while (!pop_stack(env, NULL, NULL, false)); 2393 return NULL; 2394 } 2395 2396 2397 enum reg_arg_type { 2398 SRC_OP, /* register is used as source operand */ 2399 DST_OP, /* register is used as destination operand */ 2400 DST_OP_NO_MARK /* same as above, check only, don't mark */ 2401 }; 2402 2403 static int cmp_subprogs(const void *a, const void *b) 2404 { 2405 return ((struct bpf_subprog_info *)a)->start - 2406 ((struct bpf_subprog_info *)b)->start; 2407 } 2408 2409 static int find_subprog(struct bpf_verifier_env *env, int off) 2410 { 2411 struct bpf_subprog_info *p; 2412 2413 p = bsearch(&off, env->subprog_info, env->subprog_cnt, 2414 sizeof(env->subprog_info[0]), cmp_subprogs); 2415 if (!p) 2416 return -ENOENT; 2417 return p - env->subprog_info; 2418 2419 } 2420 2421 static int add_subprog(struct bpf_verifier_env *env, int off) 2422 { 2423 int insn_cnt = env->prog->len; 2424 int ret; 2425 2426 if (off >= insn_cnt || off < 0) { 2427 verbose(env, "call to invalid destination\n"); 2428 return -EINVAL; 2429 } 2430 ret = find_subprog(env, off); 2431 if (ret >= 0) 2432 return ret; 2433 if (env->subprog_cnt >= BPF_MAX_SUBPROGS) { 2434 verbose(env, "too many subprograms\n"); 2435 return -E2BIG; 2436 } 2437 /* determine subprog starts. The end is one before the next starts */ 2438 env->subprog_info[env->subprog_cnt++].start = off; 2439 sort(env->subprog_info, env->subprog_cnt, 2440 sizeof(env->subprog_info[0]), cmp_subprogs, NULL); 2441 return env->subprog_cnt - 1; 2442 } 2443 2444 #define MAX_KFUNC_DESCS 256 2445 #define MAX_KFUNC_BTFS 256 2446 2447 struct bpf_kfunc_desc { 2448 struct btf_func_model func_model; 2449 u32 func_id; 2450 s32 imm; 2451 u16 offset; 2452 unsigned long addr; 2453 }; 2454 2455 struct bpf_kfunc_btf { 2456 struct btf *btf; 2457 struct module *module; 2458 u16 offset; 2459 }; 2460 2461 struct bpf_kfunc_desc_tab { 2462 /* Sorted by func_id (BTF ID) and offset (fd_array offset) during 2463 * verification. JITs do lookups by bpf_insn, where func_id may not be 2464 * available, therefore at the end of verification do_misc_fixups() 2465 * sorts this by imm and offset. 2466 */ 2467 struct bpf_kfunc_desc descs[MAX_KFUNC_DESCS]; 2468 u32 nr_descs; 2469 }; 2470 2471 struct bpf_kfunc_btf_tab { 2472 struct bpf_kfunc_btf descs[MAX_KFUNC_BTFS]; 2473 u32 nr_descs; 2474 }; 2475 2476 static int kfunc_desc_cmp_by_id_off(const void *a, const void *b) 2477 { 2478 const struct bpf_kfunc_desc *d0 = a; 2479 const struct bpf_kfunc_desc *d1 = b; 2480 2481 /* func_id is not greater than BTF_MAX_TYPE */ 2482 return d0->func_id - d1->func_id ?: d0->offset - d1->offset; 2483 } 2484 2485 static int kfunc_btf_cmp_by_off(const void *a, const void *b) 2486 { 2487 const struct bpf_kfunc_btf *d0 = a; 2488 const struct bpf_kfunc_btf *d1 = b; 2489 2490 return d0->offset - d1->offset; 2491 } 2492 2493 static const struct bpf_kfunc_desc * 2494 find_kfunc_desc(const struct bpf_prog *prog, u32 func_id, u16 offset) 2495 { 2496 struct bpf_kfunc_desc desc = { 2497 .func_id = func_id, 2498 .offset = offset, 2499 }; 2500 struct bpf_kfunc_desc_tab *tab; 2501 2502 tab = prog->aux->kfunc_tab; 2503 return bsearch(&desc, tab->descs, tab->nr_descs, 2504 sizeof(tab->descs[0]), kfunc_desc_cmp_by_id_off); 2505 } 2506 2507 int bpf_get_kfunc_addr(const struct bpf_prog *prog, u32 func_id, 2508 u16 btf_fd_idx, u8 **func_addr) 2509 { 2510 const struct bpf_kfunc_desc *desc; 2511 2512 desc = find_kfunc_desc(prog, func_id, btf_fd_idx); 2513 if (!desc) 2514 return -EFAULT; 2515 2516 *func_addr = (u8 *)desc->addr; 2517 return 0; 2518 } 2519 2520 static struct btf *__find_kfunc_desc_btf(struct bpf_verifier_env *env, 2521 s16 offset) 2522 { 2523 struct bpf_kfunc_btf kf_btf = { .offset = offset }; 2524 struct bpf_kfunc_btf_tab *tab; 2525 struct bpf_kfunc_btf *b; 2526 struct module *mod; 2527 struct btf *btf; 2528 int btf_fd; 2529 2530 tab = env->prog->aux->kfunc_btf_tab; 2531 b = bsearch(&kf_btf, tab->descs, tab->nr_descs, 2532 sizeof(tab->descs[0]), kfunc_btf_cmp_by_off); 2533 if (!b) { 2534 if (tab->nr_descs == MAX_KFUNC_BTFS) { 2535 verbose(env, "too many different module BTFs\n"); 2536 return ERR_PTR(-E2BIG); 2537 } 2538 2539 if (bpfptr_is_null(env->fd_array)) { 2540 verbose(env, "kfunc offset > 0 without fd_array is invalid\n"); 2541 return ERR_PTR(-EPROTO); 2542 } 2543 2544 if (copy_from_bpfptr_offset(&btf_fd, env->fd_array, 2545 offset * sizeof(btf_fd), 2546 sizeof(btf_fd))) 2547 return ERR_PTR(-EFAULT); 2548 2549 btf = btf_get_by_fd(btf_fd); 2550 if (IS_ERR(btf)) { 2551 verbose(env, "invalid module BTF fd specified\n"); 2552 return btf; 2553 } 2554 2555 if (!btf_is_module(btf)) { 2556 verbose(env, "BTF fd for kfunc is not a module BTF\n"); 2557 btf_put(btf); 2558 return ERR_PTR(-EINVAL); 2559 } 2560 2561 mod = btf_try_get_module(btf); 2562 if (!mod) { 2563 btf_put(btf); 2564 return ERR_PTR(-ENXIO); 2565 } 2566 2567 b = &tab->descs[tab->nr_descs++]; 2568 b->btf = btf; 2569 b->module = mod; 2570 b->offset = offset; 2571 2572 sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]), 2573 kfunc_btf_cmp_by_off, NULL); 2574 } 2575 return b->btf; 2576 } 2577 2578 void bpf_free_kfunc_btf_tab(struct bpf_kfunc_btf_tab *tab) 2579 { 2580 if (!tab) 2581 return; 2582 2583 while (tab->nr_descs--) { 2584 module_put(tab->descs[tab->nr_descs].module); 2585 btf_put(tab->descs[tab->nr_descs].btf); 2586 } 2587 kfree(tab); 2588 } 2589 2590 static struct btf *find_kfunc_desc_btf(struct bpf_verifier_env *env, s16 offset) 2591 { 2592 if (offset) { 2593 if (offset < 0) { 2594 /* In the future, this can be allowed to increase limit 2595 * of fd index into fd_array, interpreted as u16. 2596 */ 2597 verbose(env, "negative offset disallowed for kernel module function call\n"); 2598 return ERR_PTR(-EINVAL); 2599 } 2600 2601 return __find_kfunc_desc_btf(env, offset); 2602 } 2603 return btf_vmlinux ?: ERR_PTR(-ENOENT); 2604 } 2605 2606 static int add_kfunc_call(struct bpf_verifier_env *env, u32 func_id, s16 offset) 2607 { 2608 const struct btf_type *func, *func_proto; 2609 struct bpf_kfunc_btf_tab *btf_tab; 2610 struct bpf_kfunc_desc_tab *tab; 2611 struct bpf_prog_aux *prog_aux; 2612 struct bpf_kfunc_desc *desc; 2613 const char *func_name; 2614 struct btf *desc_btf; 2615 unsigned long call_imm; 2616 unsigned long addr; 2617 int err; 2618 2619 prog_aux = env->prog->aux; 2620 tab = prog_aux->kfunc_tab; 2621 btf_tab = prog_aux->kfunc_btf_tab; 2622 if (!tab) { 2623 if (!btf_vmlinux) { 2624 verbose(env, "calling kernel function is not supported without CONFIG_DEBUG_INFO_BTF\n"); 2625 return -ENOTSUPP; 2626 } 2627 2628 if (!env->prog->jit_requested) { 2629 verbose(env, "JIT is required for calling kernel function\n"); 2630 return -ENOTSUPP; 2631 } 2632 2633 if (!bpf_jit_supports_kfunc_call()) { 2634 verbose(env, "JIT does not support calling kernel function\n"); 2635 return -ENOTSUPP; 2636 } 2637 2638 if (!env->prog->gpl_compatible) { 2639 verbose(env, "cannot call kernel function from non-GPL compatible program\n"); 2640 return -EINVAL; 2641 } 2642 2643 tab = kzalloc(sizeof(*tab), GFP_KERNEL); 2644 if (!tab) 2645 return -ENOMEM; 2646 prog_aux->kfunc_tab = tab; 2647 } 2648 2649 /* func_id == 0 is always invalid, but instead of returning an error, be 2650 * conservative and wait until the code elimination pass before returning 2651 * error, so that invalid calls that get pruned out can be in BPF programs 2652 * loaded from userspace. It is also required that offset be untouched 2653 * for such calls. 2654 */ 2655 if (!func_id && !offset) 2656 return 0; 2657 2658 if (!btf_tab && offset) { 2659 btf_tab = kzalloc(sizeof(*btf_tab), GFP_KERNEL); 2660 if (!btf_tab) 2661 return -ENOMEM; 2662 prog_aux->kfunc_btf_tab = btf_tab; 2663 } 2664 2665 desc_btf = find_kfunc_desc_btf(env, offset); 2666 if (IS_ERR(desc_btf)) { 2667 verbose(env, "failed to find BTF for kernel function\n"); 2668 return PTR_ERR(desc_btf); 2669 } 2670 2671 if (find_kfunc_desc(env->prog, func_id, offset)) 2672 return 0; 2673 2674 if (tab->nr_descs == MAX_KFUNC_DESCS) { 2675 verbose(env, "too many different kernel function calls\n"); 2676 return -E2BIG; 2677 } 2678 2679 func = btf_type_by_id(desc_btf, func_id); 2680 if (!func || !btf_type_is_func(func)) { 2681 verbose(env, "kernel btf_id %u is not a function\n", 2682 func_id); 2683 return -EINVAL; 2684 } 2685 func_proto = btf_type_by_id(desc_btf, func->type); 2686 if (!func_proto || !btf_type_is_func_proto(func_proto)) { 2687 verbose(env, "kernel function btf_id %u does not have a valid func_proto\n", 2688 func_id); 2689 return -EINVAL; 2690 } 2691 2692 func_name = btf_name_by_offset(desc_btf, func->name_off); 2693 addr = kallsyms_lookup_name(func_name); 2694 if (!addr) { 2695 verbose(env, "cannot find address for kernel function %s\n", 2696 func_name); 2697 return -EINVAL; 2698 } 2699 specialize_kfunc(env, func_id, offset, &addr); 2700 2701 if (bpf_jit_supports_far_kfunc_call()) { 2702 call_imm = func_id; 2703 } else { 2704 call_imm = BPF_CALL_IMM(addr); 2705 /* Check whether the relative offset overflows desc->imm */ 2706 if ((unsigned long)(s32)call_imm != call_imm) { 2707 verbose(env, "address of kernel function %s is out of range\n", 2708 func_name); 2709 return -EINVAL; 2710 } 2711 } 2712 2713 if (bpf_dev_bound_kfunc_id(func_id)) { 2714 err = bpf_dev_bound_kfunc_check(&env->log, prog_aux); 2715 if (err) 2716 return err; 2717 } 2718 2719 desc = &tab->descs[tab->nr_descs++]; 2720 desc->func_id = func_id; 2721 desc->imm = call_imm; 2722 desc->offset = offset; 2723 desc->addr = addr; 2724 err = btf_distill_func_proto(&env->log, desc_btf, 2725 func_proto, func_name, 2726 &desc->func_model); 2727 if (!err) 2728 sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]), 2729 kfunc_desc_cmp_by_id_off, NULL); 2730 return err; 2731 } 2732 2733 static int kfunc_desc_cmp_by_imm_off(const void *a, const void *b) 2734 { 2735 const struct bpf_kfunc_desc *d0 = a; 2736 const struct bpf_kfunc_desc *d1 = b; 2737 2738 if (d0->imm != d1->imm) 2739 return d0->imm < d1->imm ? -1 : 1; 2740 if (d0->offset != d1->offset) 2741 return d0->offset < d1->offset ? -1 : 1; 2742 return 0; 2743 } 2744 2745 static void sort_kfunc_descs_by_imm_off(struct bpf_prog *prog) 2746 { 2747 struct bpf_kfunc_desc_tab *tab; 2748 2749 tab = prog->aux->kfunc_tab; 2750 if (!tab) 2751 return; 2752 2753 sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]), 2754 kfunc_desc_cmp_by_imm_off, NULL); 2755 } 2756 2757 bool bpf_prog_has_kfunc_call(const struct bpf_prog *prog) 2758 { 2759 return !!prog->aux->kfunc_tab; 2760 } 2761 2762 const struct btf_func_model * 2763 bpf_jit_find_kfunc_model(const struct bpf_prog *prog, 2764 const struct bpf_insn *insn) 2765 { 2766 const struct bpf_kfunc_desc desc = { 2767 .imm = insn->imm, 2768 .offset = insn->off, 2769 }; 2770 const struct bpf_kfunc_desc *res; 2771 struct bpf_kfunc_desc_tab *tab; 2772 2773 tab = prog->aux->kfunc_tab; 2774 res = bsearch(&desc, tab->descs, tab->nr_descs, 2775 sizeof(tab->descs[0]), kfunc_desc_cmp_by_imm_off); 2776 2777 return res ? &res->func_model : NULL; 2778 } 2779 2780 static int add_subprog_and_kfunc(struct bpf_verifier_env *env) 2781 { 2782 struct bpf_subprog_info *subprog = env->subprog_info; 2783 struct bpf_insn *insn = env->prog->insnsi; 2784 int i, ret, insn_cnt = env->prog->len; 2785 2786 /* Add entry function. */ 2787 ret = add_subprog(env, 0); 2788 if (ret) 2789 return ret; 2790 2791 for (i = 0; i < insn_cnt; i++, insn++) { 2792 if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn) && 2793 !bpf_pseudo_kfunc_call(insn)) 2794 continue; 2795 2796 if (!env->bpf_capable) { 2797 verbose(env, "loading/calling other bpf or kernel functions are allowed for CAP_BPF and CAP_SYS_ADMIN\n"); 2798 return -EPERM; 2799 } 2800 2801 if (bpf_pseudo_func(insn) || bpf_pseudo_call(insn)) 2802 ret = add_subprog(env, i + insn->imm + 1); 2803 else 2804 ret = add_kfunc_call(env, insn->imm, insn->off); 2805 2806 if (ret < 0) 2807 return ret; 2808 } 2809 2810 /* Add a fake 'exit' subprog which could simplify subprog iteration 2811 * logic. 'subprog_cnt' should not be increased. 2812 */ 2813 subprog[env->subprog_cnt].start = insn_cnt; 2814 2815 if (env->log.level & BPF_LOG_LEVEL2) 2816 for (i = 0; i < env->subprog_cnt; i++) 2817 verbose(env, "func#%d @%d\n", i, subprog[i].start); 2818 2819 return 0; 2820 } 2821 2822 static int check_subprogs(struct bpf_verifier_env *env) 2823 { 2824 int i, subprog_start, subprog_end, off, cur_subprog = 0; 2825 struct bpf_subprog_info *subprog = env->subprog_info; 2826 struct bpf_insn *insn = env->prog->insnsi; 2827 int insn_cnt = env->prog->len; 2828 2829 /* now check that all jumps are within the same subprog */ 2830 subprog_start = subprog[cur_subprog].start; 2831 subprog_end = subprog[cur_subprog + 1].start; 2832 for (i = 0; i < insn_cnt; i++) { 2833 u8 code = insn[i].code; 2834 2835 if (code == (BPF_JMP | BPF_CALL) && 2836 insn[i].src_reg == 0 && 2837 insn[i].imm == BPF_FUNC_tail_call) 2838 subprog[cur_subprog].has_tail_call = true; 2839 if (BPF_CLASS(code) == BPF_LD && 2840 (BPF_MODE(code) == BPF_ABS || BPF_MODE(code) == BPF_IND)) 2841 subprog[cur_subprog].has_ld_abs = true; 2842 if (BPF_CLASS(code) != BPF_JMP && BPF_CLASS(code) != BPF_JMP32) 2843 goto next; 2844 if (BPF_OP(code) == BPF_EXIT || BPF_OP(code) == BPF_CALL) 2845 goto next; 2846 off = i + insn[i].off + 1; 2847 if (off < subprog_start || off >= subprog_end) { 2848 verbose(env, "jump out of range from insn %d to %d\n", i, off); 2849 return -EINVAL; 2850 } 2851 next: 2852 if (i == subprog_end - 1) { 2853 /* to avoid fall-through from one subprog into another 2854 * the last insn of the subprog should be either exit 2855 * or unconditional jump back 2856 */ 2857 if (code != (BPF_JMP | BPF_EXIT) && 2858 code != (BPF_JMP | BPF_JA)) { 2859 verbose(env, "last insn is not an exit or jmp\n"); 2860 return -EINVAL; 2861 } 2862 subprog_start = subprog_end; 2863 cur_subprog++; 2864 if (cur_subprog < env->subprog_cnt) 2865 subprog_end = subprog[cur_subprog + 1].start; 2866 } 2867 } 2868 return 0; 2869 } 2870 2871 /* Parentage chain of this register (or stack slot) should take care of all 2872 * issues like callee-saved registers, stack slot allocation time, etc. 2873 */ 2874 static int mark_reg_read(struct bpf_verifier_env *env, 2875 const struct bpf_reg_state *state, 2876 struct bpf_reg_state *parent, u8 flag) 2877 { 2878 bool writes = parent == state->parent; /* Observe write marks */ 2879 int cnt = 0; 2880 2881 while (parent) { 2882 /* if read wasn't screened by an earlier write ... */ 2883 if (writes && state->live & REG_LIVE_WRITTEN) 2884 break; 2885 if (parent->live & REG_LIVE_DONE) { 2886 verbose(env, "verifier BUG type %s var_off %lld off %d\n", 2887 reg_type_str(env, parent->type), 2888 parent->var_off.value, parent->off); 2889 return -EFAULT; 2890 } 2891 /* The first condition is more likely to be true than the 2892 * second, checked it first. 2893 */ 2894 if ((parent->live & REG_LIVE_READ) == flag || 2895 parent->live & REG_LIVE_READ64) 2896 /* The parentage chain never changes and 2897 * this parent was already marked as LIVE_READ. 2898 * There is no need to keep walking the chain again and 2899 * keep re-marking all parents as LIVE_READ. 2900 * This case happens when the same register is read 2901 * multiple times without writes into it in-between. 2902 * Also, if parent has the stronger REG_LIVE_READ64 set, 2903 * then no need to set the weak REG_LIVE_READ32. 2904 */ 2905 break; 2906 /* ... then we depend on parent's value */ 2907 parent->live |= flag; 2908 /* REG_LIVE_READ64 overrides REG_LIVE_READ32. */ 2909 if (flag == REG_LIVE_READ64) 2910 parent->live &= ~REG_LIVE_READ32; 2911 state = parent; 2912 parent = state->parent; 2913 writes = true; 2914 cnt++; 2915 } 2916 2917 if (env->longest_mark_read_walk < cnt) 2918 env->longest_mark_read_walk = cnt; 2919 return 0; 2920 } 2921 2922 static int mark_dynptr_read(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 2923 { 2924 struct bpf_func_state *state = func(env, reg); 2925 int spi, ret; 2926 2927 /* For CONST_PTR_TO_DYNPTR, it must have already been done by 2928 * check_reg_arg in check_helper_call and mark_btf_func_reg_size in 2929 * check_kfunc_call. 2930 */ 2931 if (reg->type == CONST_PTR_TO_DYNPTR) 2932 return 0; 2933 spi = dynptr_get_spi(env, reg); 2934 if (spi < 0) 2935 return spi; 2936 /* Caller ensures dynptr is valid and initialized, which means spi is in 2937 * bounds and spi is the first dynptr slot. Simply mark stack slot as 2938 * read. 2939 */ 2940 ret = mark_reg_read(env, &state->stack[spi].spilled_ptr, 2941 state->stack[spi].spilled_ptr.parent, REG_LIVE_READ64); 2942 if (ret) 2943 return ret; 2944 return mark_reg_read(env, &state->stack[spi - 1].spilled_ptr, 2945 state->stack[spi - 1].spilled_ptr.parent, REG_LIVE_READ64); 2946 } 2947 2948 static int mark_iter_read(struct bpf_verifier_env *env, struct bpf_reg_state *reg, 2949 int spi, int nr_slots) 2950 { 2951 struct bpf_func_state *state = func(env, reg); 2952 int err, i; 2953 2954 for (i = 0; i < nr_slots; i++) { 2955 struct bpf_reg_state *st = &state->stack[spi - i].spilled_ptr; 2956 2957 err = mark_reg_read(env, st, st->parent, REG_LIVE_READ64); 2958 if (err) 2959 return err; 2960 2961 mark_stack_slot_scratched(env, spi - i); 2962 } 2963 2964 return 0; 2965 } 2966 2967 /* This function is supposed to be used by the following 32-bit optimization 2968 * code only. It returns TRUE if the source or destination register operates 2969 * on 64-bit, otherwise return FALSE. 2970 */ 2971 static bool is_reg64(struct bpf_verifier_env *env, struct bpf_insn *insn, 2972 u32 regno, struct bpf_reg_state *reg, enum reg_arg_type t) 2973 { 2974 u8 code, class, op; 2975 2976 code = insn->code; 2977 class = BPF_CLASS(code); 2978 op = BPF_OP(code); 2979 if (class == BPF_JMP) { 2980 /* BPF_EXIT for "main" will reach here. Return TRUE 2981 * conservatively. 2982 */ 2983 if (op == BPF_EXIT) 2984 return true; 2985 if (op == BPF_CALL) { 2986 /* BPF to BPF call will reach here because of marking 2987 * caller saved clobber with DST_OP_NO_MARK for which we 2988 * don't care the register def because they are anyway 2989 * marked as NOT_INIT already. 2990 */ 2991 if (insn->src_reg == BPF_PSEUDO_CALL) 2992 return false; 2993 /* Helper call will reach here because of arg type 2994 * check, conservatively return TRUE. 2995 */ 2996 if (t == SRC_OP) 2997 return true; 2998 2999 return false; 3000 } 3001 } 3002 3003 if (class == BPF_ALU64 || class == BPF_JMP || 3004 /* BPF_END always use BPF_ALU class. */ 3005 (class == BPF_ALU && op == BPF_END && insn->imm == 64)) 3006 return true; 3007 3008 if (class == BPF_ALU || class == BPF_JMP32) 3009 return false; 3010 3011 if (class == BPF_LDX) { 3012 if (t != SRC_OP) 3013 return BPF_SIZE(code) == BPF_DW; 3014 /* LDX source must be ptr. */ 3015 return true; 3016 } 3017 3018 if (class == BPF_STX) { 3019 /* BPF_STX (including atomic variants) has multiple source 3020 * operands, one of which is a ptr. Check whether the caller is 3021 * asking about it. 3022 */ 3023 if (t == SRC_OP && reg->type != SCALAR_VALUE) 3024 return true; 3025 return BPF_SIZE(code) == BPF_DW; 3026 } 3027 3028 if (class == BPF_LD) { 3029 u8 mode = BPF_MODE(code); 3030 3031 /* LD_IMM64 */ 3032 if (mode == BPF_IMM) 3033 return true; 3034 3035 /* Both LD_IND and LD_ABS return 32-bit data. */ 3036 if (t != SRC_OP) 3037 return false; 3038 3039 /* Implicit ctx ptr. */ 3040 if (regno == BPF_REG_6) 3041 return true; 3042 3043 /* Explicit source could be any width. */ 3044 return true; 3045 } 3046 3047 if (class == BPF_ST) 3048 /* The only source register for BPF_ST is a ptr. */ 3049 return true; 3050 3051 /* Conservatively return true at default. */ 3052 return true; 3053 } 3054 3055 /* Return the regno defined by the insn, or -1. */ 3056 static int insn_def_regno(const struct bpf_insn *insn) 3057 { 3058 switch (BPF_CLASS(insn->code)) { 3059 case BPF_JMP: 3060 case BPF_JMP32: 3061 case BPF_ST: 3062 return -1; 3063 case BPF_STX: 3064 if (BPF_MODE(insn->code) == BPF_ATOMIC && 3065 (insn->imm & BPF_FETCH)) { 3066 if (insn->imm == BPF_CMPXCHG) 3067 return BPF_REG_0; 3068 else 3069 return insn->src_reg; 3070 } else { 3071 return -1; 3072 } 3073 default: 3074 return insn->dst_reg; 3075 } 3076 } 3077 3078 /* Return TRUE if INSN has defined any 32-bit value explicitly. */ 3079 static bool insn_has_def32(struct bpf_verifier_env *env, struct bpf_insn *insn) 3080 { 3081 int dst_reg = insn_def_regno(insn); 3082 3083 if (dst_reg == -1) 3084 return false; 3085 3086 return !is_reg64(env, insn, dst_reg, NULL, DST_OP); 3087 } 3088 3089 static void mark_insn_zext(struct bpf_verifier_env *env, 3090 struct bpf_reg_state *reg) 3091 { 3092 s32 def_idx = reg->subreg_def; 3093 3094 if (def_idx == DEF_NOT_SUBREG) 3095 return; 3096 3097 env->insn_aux_data[def_idx - 1].zext_dst = true; 3098 /* The dst will be zero extended, so won't be sub-register anymore. */ 3099 reg->subreg_def = DEF_NOT_SUBREG; 3100 } 3101 3102 static int check_reg_arg(struct bpf_verifier_env *env, u32 regno, 3103 enum reg_arg_type t) 3104 { 3105 struct bpf_verifier_state *vstate = env->cur_state; 3106 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 3107 struct bpf_insn *insn = env->prog->insnsi + env->insn_idx; 3108 struct bpf_reg_state *reg, *regs = state->regs; 3109 bool rw64; 3110 3111 if (regno >= MAX_BPF_REG) { 3112 verbose(env, "R%d is invalid\n", regno); 3113 return -EINVAL; 3114 } 3115 3116 mark_reg_scratched(env, regno); 3117 3118 reg = ®s[regno]; 3119 rw64 = is_reg64(env, insn, regno, reg, t); 3120 if (t == SRC_OP) { 3121 /* check whether register used as source operand can be read */ 3122 if (reg->type == NOT_INIT) { 3123 verbose(env, "R%d !read_ok\n", regno); 3124 return -EACCES; 3125 } 3126 /* We don't need to worry about FP liveness because it's read-only */ 3127 if (regno == BPF_REG_FP) 3128 return 0; 3129 3130 if (rw64) 3131 mark_insn_zext(env, reg); 3132 3133 return mark_reg_read(env, reg, reg->parent, 3134 rw64 ? REG_LIVE_READ64 : REG_LIVE_READ32); 3135 } else { 3136 /* check whether register used as dest operand can be written to */ 3137 if (regno == BPF_REG_FP) { 3138 verbose(env, "frame pointer is read only\n"); 3139 return -EACCES; 3140 } 3141 reg->live |= REG_LIVE_WRITTEN; 3142 reg->subreg_def = rw64 ? DEF_NOT_SUBREG : env->insn_idx + 1; 3143 if (t == DST_OP) 3144 mark_reg_unknown(env, regs, regno); 3145 } 3146 return 0; 3147 } 3148 3149 static void mark_jmp_point(struct bpf_verifier_env *env, int idx) 3150 { 3151 env->insn_aux_data[idx].jmp_point = true; 3152 } 3153 3154 static bool is_jmp_point(struct bpf_verifier_env *env, int insn_idx) 3155 { 3156 return env->insn_aux_data[insn_idx].jmp_point; 3157 } 3158 3159 /* for any branch, call, exit record the history of jmps in the given state */ 3160 static int push_jmp_history(struct bpf_verifier_env *env, 3161 struct bpf_verifier_state *cur) 3162 { 3163 u32 cnt = cur->jmp_history_cnt; 3164 struct bpf_idx_pair *p; 3165 size_t alloc_size; 3166 3167 if (!is_jmp_point(env, env->insn_idx)) 3168 return 0; 3169 3170 cnt++; 3171 alloc_size = kmalloc_size_roundup(size_mul(cnt, sizeof(*p))); 3172 p = krealloc(cur->jmp_history, alloc_size, GFP_USER); 3173 if (!p) 3174 return -ENOMEM; 3175 p[cnt - 1].idx = env->insn_idx; 3176 p[cnt - 1].prev_idx = env->prev_insn_idx; 3177 cur->jmp_history = p; 3178 cur->jmp_history_cnt = cnt; 3179 return 0; 3180 } 3181 3182 /* Backtrack one insn at a time. If idx is not at the top of recorded 3183 * history then previous instruction came from straight line execution. 3184 */ 3185 static int get_prev_insn_idx(struct bpf_verifier_state *st, int i, 3186 u32 *history) 3187 { 3188 u32 cnt = *history; 3189 3190 if (cnt && st->jmp_history[cnt - 1].idx == i) { 3191 i = st->jmp_history[cnt - 1].prev_idx; 3192 (*history)--; 3193 } else { 3194 i--; 3195 } 3196 return i; 3197 } 3198 3199 static const char *disasm_kfunc_name(void *data, const struct bpf_insn *insn) 3200 { 3201 const struct btf_type *func; 3202 struct btf *desc_btf; 3203 3204 if (insn->src_reg != BPF_PSEUDO_KFUNC_CALL) 3205 return NULL; 3206 3207 desc_btf = find_kfunc_desc_btf(data, insn->off); 3208 if (IS_ERR(desc_btf)) 3209 return "<error>"; 3210 3211 func = btf_type_by_id(desc_btf, insn->imm); 3212 return btf_name_by_offset(desc_btf, func->name_off); 3213 } 3214 3215 static inline void bt_init(struct backtrack_state *bt, u32 frame) 3216 { 3217 bt->frame = frame; 3218 } 3219 3220 static inline void bt_reset(struct backtrack_state *bt) 3221 { 3222 struct bpf_verifier_env *env = bt->env; 3223 3224 memset(bt, 0, sizeof(*bt)); 3225 bt->env = env; 3226 } 3227 3228 static inline u32 bt_empty(struct backtrack_state *bt) 3229 { 3230 u64 mask = 0; 3231 int i; 3232 3233 for (i = 0; i <= bt->frame; i++) 3234 mask |= bt->reg_masks[i] | bt->stack_masks[i]; 3235 3236 return mask == 0; 3237 } 3238 3239 static inline int bt_subprog_enter(struct backtrack_state *bt) 3240 { 3241 if (bt->frame == MAX_CALL_FRAMES - 1) { 3242 verbose(bt->env, "BUG subprog enter from frame %d\n", bt->frame); 3243 WARN_ONCE(1, "verifier backtracking bug"); 3244 return -EFAULT; 3245 } 3246 bt->frame++; 3247 return 0; 3248 } 3249 3250 static inline int bt_subprog_exit(struct backtrack_state *bt) 3251 { 3252 if (bt->frame == 0) { 3253 verbose(bt->env, "BUG subprog exit from frame 0\n"); 3254 WARN_ONCE(1, "verifier backtracking bug"); 3255 return -EFAULT; 3256 } 3257 bt->frame--; 3258 return 0; 3259 } 3260 3261 static inline void bt_set_frame_reg(struct backtrack_state *bt, u32 frame, u32 reg) 3262 { 3263 bt->reg_masks[frame] |= 1 << reg; 3264 } 3265 3266 static inline void bt_clear_frame_reg(struct backtrack_state *bt, u32 frame, u32 reg) 3267 { 3268 bt->reg_masks[frame] &= ~(1 << reg); 3269 } 3270 3271 static inline void bt_set_reg(struct backtrack_state *bt, u32 reg) 3272 { 3273 bt_set_frame_reg(bt, bt->frame, reg); 3274 } 3275 3276 static inline void bt_clear_reg(struct backtrack_state *bt, u32 reg) 3277 { 3278 bt_clear_frame_reg(bt, bt->frame, reg); 3279 } 3280 3281 static inline void bt_set_frame_slot(struct backtrack_state *bt, u32 frame, u32 slot) 3282 { 3283 bt->stack_masks[frame] |= 1ull << slot; 3284 } 3285 3286 static inline void bt_clear_frame_slot(struct backtrack_state *bt, u32 frame, u32 slot) 3287 { 3288 bt->stack_masks[frame] &= ~(1ull << slot); 3289 } 3290 3291 static inline void bt_set_slot(struct backtrack_state *bt, u32 slot) 3292 { 3293 bt_set_frame_slot(bt, bt->frame, slot); 3294 } 3295 3296 static inline void bt_clear_slot(struct backtrack_state *bt, u32 slot) 3297 { 3298 bt_clear_frame_slot(bt, bt->frame, slot); 3299 } 3300 3301 static inline u32 bt_frame_reg_mask(struct backtrack_state *bt, u32 frame) 3302 { 3303 return bt->reg_masks[frame]; 3304 } 3305 3306 static inline u32 bt_reg_mask(struct backtrack_state *bt) 3307 { 3308 return bt->reg_masks[bt->frame]; 3309 } 3310 3311 static inline u64 bt_frame_stack_mask(struct backtrack_state *bt, u32 frame) 3312 { 3313 return bt->stack_masks[frame]; 3314 } 3315 3316 static inline u64 bt_stack_mask(struct backtrack_state *bt) 3317 { 3318 return bt->stack_masks[bt->frame]; 3319 } 3320 3321 static inline bool bt_is_reg_set(struct backtrack_state *bt, u32 reg) 3322 { 3323 return bt->reg_masks[bt->frame] & (1 << reg); 3324 } 3325 3326 static inline bool bt_is_slot_set(struct backtrack_state *bt, u32 slot) 3327 { 3328 return bt->stack_masks[bt->frame] & (1ull << slot); 3329 } 3330 3331 /* format registers bitmask, e.g., "r0,r2,r4" for 0x15 mask */ 3332 static void fmt_reg_mask(char *buf, ssize_t buf_sz, u32 reg_mask) 3333 { 3334 DECLARE_BITMAP(mask, 64); 3335 bool first = true; 3336 int i, n; 3337 3338 buf[0] = '\0'; 3339 3340 bitmap_from_u64(mask, reg_mask); 3341 for_each_set_bit(i, mask, 32) { 3342 n = snprintf(buf, buf_sz, "%sr%d", first ? "" : ",", i); 3343 first = false; 3344 buf += n; 3345 buf_sz -= n; 3346 if (buf_sz < 0) 3347 break; 3348 } 3349 } 3350 /* format stack slots bitmask, e.g., "-8,-24,-40" for 0x15 mask */ 3351 static void fmt_stack_mask(char *buf, ssize_t buf_sz, u64 stack_mask) 3352 { 3353 DECLARE_BITMAP(mask, 64); 3354 bool first = true; 3355 int i, n; 3356 3357 buf[0] = '\0'; 3358 3359 bitmap_from_u64(mask, stack_mask); 3360 for_each_set_bit(i, mask, 64) { 3361 n = snprintf(buf, buf_sz, "%s%d", first ? "" : ",", -(i + 1) * 8); 3362 first = false; 3363 buf += n; 3364 buf_sz -= n; 3365 if (buf_sz < 0) 3366 break; 3367 } 3368 } 3369 3370 /* For given verifier state backtrack_insn() is called from the last insn to 3371 * the first insn. Its purpose is to compute a bitmask of registers and 3372 * stack slots that needs precision in the parent verifier state. 3373 * 3374 * @idx is an index of the instruction we are currently processing; 3375 * @subseq_idx is an index of the subsequent instruction that: 3376 * - *would be* executed next, if jump history is viewed in forward order; 3377 * - *was* processed previously during backtracking. 3378 */ 3379 static int backtrack_insn(struct bpf_verifier_env *env, int idx, int subseq_idx, 3380 struct backtrack_state *bt) 3381 { 3382 const struct bpf_insn_cbs cbs = { 3383 .cb_call = disasm_kfunc_name, 3384 .cb_print = verbose, 3385 .private_data = env, 3386 }; 3387 struct bpf_insn *insn = env->prog->insnsi + idx; 3388 u8 class = BPF_CLASS(insn->code); 3389 u8 opcode = BPF_OP(insn->code); 3390 u8 mode = BPF_MODE(insn->code); 3391 u32 dreg = insn->dst_reg; 3392 u32 sreg = insn->src_reg; 3393 u32 spi, i; 3394 3395 if (insn->code == 0) 3396 return 0; 3397 if (env->log.level & BPF_LOG_LEVEL2) { 3398 fmt_reg_mask(env->tmp_str_buf, TMP_STR_BUF_LEN, bt_reg_mask(bt)); 3399 verbose(env, "mark_precise: frame%d: regs=%s ", 3400 bt->frame, env->tmp_str_buf); 3401 fmt_stack_mask(env->tmp_str_buf, TMP_STR_BUF_LEN, bt_stack_mask(bt)); 3402 verbose(env, "stack=%s before ", env->tmp_str_buf); 3403 verbose(env, "%d: ", idx); 3404 print_bpf_insn(&cbs, insn, env->allow_ptr_leaks); 3405 } 3406 3407 if (class == BPF_ALU || class == BPF_ALU64) { 3408 if (!bt_is_reg_set(bt, dreg)) 3409 return 0; 3410 if (opcode == BPF_MOV) { 3411 if (BPF_SRC(insn->code) == BPF_X) { 3412 /* dreg = sreg 3413 * dreg needs precision after this insn 3414 * sreg needs precision before this insn 3415 */ 3416 bt_clear_reg(bt, dreg); 3417 bt_set_reg(bt, sreg); 3418 } else { 3419 /* dreg = K 3420 * dreg needs precision after this insn. 3421 * Corresponding register is already marked 3422 * as precise=true in this verifier state. 3423 * No further markings in parent are necessary 3424 */ 3425 bt_clear_reg(bt, dreg); 3426 } 3427 } else { 3428 if (BPF_SRC(insn->code) == BPF_X) { 3429 /* dreg += sreg 3430 * both dreg and sreg need precision 3431 * before this insn 3432 */ 3433 bt_set_reg(bt, sreg); 3434 } /* else dreg += K 3435 * dreg still needs precision before this insn 3436 */ 3437 } 3438 } else if (class == BPF_LDX) { 3439 if (!bt_is_reg_set(bt, dreg)) 3440 return 0; 3441 bt_clear_reg(bt, dreg); 3442 3443 /* scalars can only be spilled into stack w/o losing precision. 3444 * Load from any other memory can be zero extended. 3445 * The desire to keep that precision is already indicated 3446 * by 'precise' mark in corresponding register of this state. 3447 * No further tracking necessary. 3448 */ 3449 if (insn->src_reg != BPF_REG_FP) 3450 return 0; 3451 3452 /* dreg = *(u64 *)[fp - off] was a fill from the stack. 3453 * that [fp - off] slot contains scalar that needs to be 3454 * tracked with precision 3455 */ 3456 spi = (-insn->off - 1) / BPF_REG_SIZE; 3457 if (spi >= 64) { 3458 verbose(env, "BUG spi %d\n", spi); 3459 WARN_ONCE(1, "verifier backtracking bug"); 3460 return -EFAULT; 3461 } 3462 bt_set_slot(bt, spi); 3463 } else if (class == BPF_STX || class == BPF_ST) { 3464 if (bt_is_reg_set(bt, dreg)) 3465 /* stx & st shouldn't be using _scalar_ dst_reg 3466 * to access memory. It means backtracking 3467 * encountered a case of pointer subtraction. 3468 */ 3469 return -ENOTSUPP; 3470 /* scalars can only be spilled into stack */ 3471 if (insn->dst_reg != BPF_REG_FP) 3472 return 0; 3473 spi = (-insn->off - 1) / BPF_REG_SIZE; 3474 if (spi >= 64) { 3475 verbose(env, "BUG spi %d\n", spi); 3476 WARN_ONCE(1, "verifier backtracking bug"); 3477 return -EFAULT; 3478 } 3479 if (!bt_is_slot_set(bt, spi)) 3480 return 0; 3481 bt_clear_slot(bt, spi); 3482 if (class == BPF_STX) 3483 bt_set_reg(bt, sreg); 3484 } else if (class == BPF_JMP || class == BPF_JMP32) { 3485 if (bpf_pseudo_call(insn)) { 3486 int subprog_insn_idx, subprog; 3487 3488 subprog_insn_idx = idx + insn->imm + 1; 3489 subprog = find_subprog(env, subprog_insn_idx); 3490 if (subprog < 0) 3491 return -EFAULT; 3492 3493 if (subprog_is_global(env, subprog)) { 3494 /* check that jump history doesn't have any 3495 * extra instructions from subprog; the next 3496 * instruction after call to global subprog 3497 * should be literally next instruction in 3498 * caller program 3499 */ 3500 WARN_ONCE(idx + 1 != subseq_idx, "verifier backtracking bug"); 3501 /* r1-r5 are invalidated after subprog call, 3502 * so for global func call it shouldn't be set 3503 * anymore 3504 */ 3505 if (bt_reg_mask(bt) & BPF_REGMASK_ARGS) { 3506 verbose(env, "BUG regs %x\n", bt_reg_mask(bt)); 3507 WARN_ONCE(1, "verifier backtracking bug"); 3508 return -EFAULT; 3509 } 3510 /* global subprog always sets R0 */ 3511 bt_clear_reg(bt, BPF_REG_0); 3512 return 0; 3513 } else { 3514 /* static subprog call instruction, which 3515 * means that we are exiting current subprog, 3516 * so only r1-r5 could be still requested as 3517 * precise, r0 and r6-r10 or any stack slot in 3518 * the current frame should be zero by now 3519 */ 3520 if (bt_reg_mask(bt) & ~BPF_REGMASK_ARGS) { 3521 verbose(env, "BUG regs %x\n", bt_reg_mask(bt)); 3522 WARN_ONCE(1, "verifier backtracking bug"); 3523 return -EFAULT; 3524 } 3525 /* we don't track register spills perfectly, 3526 * so fallback to force-precise instead of failing */ 3527 if (bt_stack_mask(bt) != 0) 3528 return -ENOTSUPP; 3529 /* propagate r1-r5 to the caller */ 3530 for (i = BPF_REG_1; i <= BPF_REG_5; i++) { 3531 if (bt_is_reg_set(bt, i)) { 3532 bt_clear_reg(bt, i); 3533 bt_set_frame_reg(bt, bt->frame - 1, i); 3534 } 3535 } 3536 if (bt_subprog_exit(bt)) 3537 return -EFAULT; 3538 return 0; 3539 } 3540 } else if ((bpf_helper_call(insn) && 3541 is_callback_calling_function(insn->imm) && 3542 !is_async_callback_calling_function(insn->imm)) || 3543 (bpf_pseudo_kfunc_call(insn) && is_callback_calling_kfunc(insn->imm))) { 3544 /* callback-calling helper or kfunc call, which means 3545 * we are exiting from subprog, but unlike the subprog 3546 * call handling above, we shouldn't propagate 3547 * precision of r1-r5 (if any requested), as they are 3548 * not actually arguments passed directly to callback 3549 * subprogs 3550 */ 3551 if (bt_reg_mask(bt) & ~BPF_REGMASK_ARGS) { 3552 verbose(env, "BUG regs %x\n", bt_reg_mask(bt)); 3553 WARN_ONCE(1, "verifier backtracking bug"); 3554 return -EFAULT; 3555 } 3556 if (bt_stack_mask(bt) != 0) 3557 return -ENOTSUPP; 3558 /* clear r1-r5 in callback subprog's mask */ 3559 for (i = BPF_REG_1; i <= BPF_REG_5; i++) 3560 bt_clear_reg(bt, i); 3561 if (bt_subprog_exit(bt)) 3562 return -EFAULT; 3563 return 0; 3564 } else if (opcode == BPF_CALL) { 3565 /* kfunc with imm==0 is invalid and fixup_kfunc_call will 3566 * catch this error later. Make backtracking conservative 3567 * with ENOTSUPP. 3568 */ 3569 if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL && insn->imm == 0) 3570 return -ENOTSUPP; 3571 /* regular helper call sets R0 */ 3572 bt_clear_reg(bt, BPF_REG_0); 3573 if (bt_reg_mask(bt) & BPF_REGMASK_ARGS) { 3574 /* if backtracing was looking for registers R1-R5 3575 * they should have been found already. 3576 */ 3577 verbose(env, "BUG regs %x\n", bt_reg_mask(bt)); 3578 WARN_ONCE(1, "verifier backtracking bug"); 3579 return -EFAULT; 3580 } 3581 } else if (opcode == BPF_EXIT) { 3582 bool r0_precise; 3583 3584 if (bt_reg_mask(bt) & BPF_REGMASK_ARGS) { 3585 /* if backtracing was looking for registers R1-R5 3586 * they should have been found already. 3587 */ 3588 verbose(env, "BUG regs %x\n", bt_reg_mask(bt)); 3589 WARN_ONCE(1, "verifier backtracking bug"); 3590 return -EFAULT; 3591 } 3592 3593 /* BPF_EXIT in subprog or callback always returns 3594 * right after the call instruction, so by checking 3595 * whether the instruction at subseq_idx-1 is subprog 3596 * call or not we can distinguish actual exit from 3597 * *subprog* from exit from *callback*. In the former 3598 * case, we need to propagate r0 precision, if 3599 * necessary. In the former we never do that. 3600 */ 3601 r0_precise = subseq_idx - 1 >= 0 && 3602 bpf_pseudo_call(&env->prog->insnsi[subseq_idx - 1]) && 3603 bt_is_reg_set(bt, BPF_REG_0); 3604 3605 bt_clear_reg(bt, BPF_REG_0); 3606 if (bt_subprog_enter(bt)) 3607 return -EFAULT; 3608 3609 if (r0_precise) 3610 bt_set_reg(bt, BPF_REG_0); 3611 /* r6-r9 and stack slots will stay set in caller frame 3612 * bitmasks until we return back from callee(s) 3613 */ 3614 return 0; 3615 } else if (BPF_SRC(insn->code) == BPF_X) { 3616 if (!bt_is_reg_set(bt, dreg) && !bt_is_reg_set(bt, sreg)) 3617 return 0; 3618 /* dreg <cond> sreg 3619 * Both dreg and sreg need precision before 3620 * this insn. If only sreg was marked precise 3621 * before it would be equally necessary to 3622 * propagate it to dreg. 3623 */ 3624 bt_set_reg(bt, dreg); 3625 bt_set_reg(bt, sreg); 3626 /* else dreg <cond> K 3627 * Only dreg still needs precision before 3628 * this insn, so for the K-based conditional 3629 * there is nothing new to be marked. 3630 */ 3631 } 3632 } else if (class == BPF_LD) { 3633 if (!bt_is_reg_set(bt, dreg)) 3634 return 0; 3635 bt_clear_reg(bt, dreg); 3636 /* It's ld_imm64 or ld_abs or ld_ind. 3637 * For ld_imm64 no further tracking of precision 3638 * into parent is necessary 3639 */ 3640 if (mode == BPF_IND || mode == BPF_ABS) 3641 /* to be analyzed */ 3642 return -ENOTSUPP; 3643 } 3644 return 0; 3645 } 3646 3647 /* the scalar precision tracking algorithm: 3648 * . at the start all registers have precise=false. 3649 * . scalar ranges are tracked as normal through alu and jmp insns. 3650 * . once precise value of the scalar register is used in: 3651 * . ptr + scalar alu 3652 * . if (scalar cond K|scalar) 3653 * . helper_call(.., scalar, ...) where ARG_CONST is expected 3654 * backtrack through the verifier states and mark all registers and 3655 * stack slots with spilled constants that these scalar regisers 3656 * should be precise. 3657 * . during state pruning two registers (or spilled stack slots) 3658 * are equivalent if both are not precise. 3659 * 3660 * Note the verifier cannot simply walk register parentage chain, 3661 * since many different registers and stack slots could have been 3662 * used to compute single precise scalar. 3663 * 3664 * The approach of starting with precise=true for all registers and then 3665 * backtrack to mark a register as not precise when the verifier detects 3666 * that program doesn't care about specific value (e.g., when helper 3667 * takes register as ARG_ANYTHING parameter) is not safe. 3668 * 3669 * It's ok to walk single parentage chain of the verifier states. 3670 * It's possible that this backtracking will go all the way till 1st insn. 3671 * All other branches will be explored for needing precision later. 3672 * 3673 * The backtracking needs to deal with cases like: 3674 * 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) 3675 * r9 -= r8 3676 * r5 = r9 3677 * if r5 > 0x79f goto pc+7 3678 * R5_w=inv(id=0,umax_value=1951,var_off=(0x0; 0x7ff)) 3679 * r5 += 1 3680 * ... 3681 * call bpf_perf_event_output#25 3682 * where .arg5_type = ARG_CONST_SIZE_OR_ZERO 3683 * 3684 * and this case: 3685 * r6 = 1 3686 * call foo // uses callee's r6 inside to compute r0 3687 * r0 += r6 3688 * if r0 == 0 goto 3689 * 3690 * to track above reg_mask/stack_mask needs to be independent for each frame. 3691 * 3692 * Also if parent's curframe > frame where backtracking started, 3693 * the verifier need to mark registers in both frames, otherwise callees 3694 * may incorrectly prune callers. This is similar to 3695 * commit 7640ead93924 ("bpf: verifier: make sure callees don't prune with caller differences") 3696 * 3697 * For now backtracking falls back into conservative marking. 3698 */ 3699 static void mark_all_scalars_precise(struct bpf_verifier_env *env, 3700 struct bpf_verifier_state *st) 3701 { 3702 struct bpf_func_state *func; 3703 struct bpf_reg_state *reg; 3704 int i, j; 3705 3706 if (env->log.level & BPF_LOG_LEVEL2) { 3707 verbose(env, "mark_precise: frame%d: falling back to forcing all scalars precise\n", 3708 st->curframe); 3709 } 3710 3711 /* big hammer: mark all scalars precise in this path. 3712 * pop_stack may still get !precise scalars. 3713 * We also skip current state and go straight to first parent state, 3714 * because precision markings in current non-checkpointed state are 3715 * not needed. See why in the comment in __mark_chain_precision below. 3716 */ 3717 for (st = st->parent; st; st = st->parent) { 3718 for (i = 0; i <= st->curframe; i++) { 3719 func = st->frame[i]; 3720 for (j = 0; j < BPF_REG_FP; j++) { 3721 reg = &func->regs[j]; 3722 if (reg->type != SCALAR_VALUE || reg->precise) 3723 continue; 3724 reg->precise = true; 3725 if (env->log.level & BPF_LOG_LEVEL2) { 3726 verbose(env, "force_precise: frame%d: forcing r%d to be precise\n", 3727 i, j); 3728 } 3729 } 3730 for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) { 3731 if (!is_spilled_reg(&func->stack[j])) 3732 continue; 3733 reg = &func->stack[j].spilled_ptr; 3734 if (reg->type != SCALAR_VALUE || reg->precise) 3735 continue; 3736 reg->precise = true; 3737 if (env->log.level & BPF_LOG_LEVEL2) { 3738 verbose(env, "force_precise: frame%d: forcing fp%d to be precise\n", 3739 i, -(j + 1) * 8); 3740 } 3741 } 3742 } 3743 } 3744 } 3745 3746 static void mark_all_scalars_imprecise(struct bpf_verifier_env *env, struct bpf_verifier_state *st) 3747 { 3748 struct bpf_func_state *func; 3749 struct bpf_reg_state *reg; 3750 int i, j; 3751 3752 for (i = 0; i <= st->curframe; i++) { 3753 func = st->frame[i]; 3754 for (j = 0; j < BPF_REG_FP; j++) { 3755 reg = &func->regs[j]; 3756 if (reg->type != SCALAR_VALUE) 3757 continue; 3758 reg->precise = false; 3759 } 3760 for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) { 3761 if (!is_spilled_reg(&func->stack[j])) 3762 continue; 3763 reg = &func->stack[j].spilled_ptr; 3764 if (reg->type != SCALAR_VALUE) 3765 continue; 3766 reg->precise = false; 3767 } 3768 } 3769 } 3770 3771 /* 3772 * __mark_chain_precision() backtracks BPF program instruction sequence and 3773 * chain of verifier states making sure that register *regno* (if regno >= 0) 3774 * and/or stack slot *spi* (if spi >= 0) are marked as precisely tracked 3775 * SCALARS, as well as any other registers and slots that contribute to 3776 * a tracked state of given registers/stack slots, depending on specific BPF 3777 * assembly instructions (see backtrack_insns() for exact instruction handling 3778 * logic). This backtracking relies on recorded jmp_history and is able to 3779 * traverse entire chain of parent states. This process ends only when all the 3780 * necessary registers/slots and their transitive dependencies are marked as 3781 * precise. 3782 * 3783 * One important and subtle aspect is that precise marks *do not matter* in 3784 * the currently verified state (current state). It is important to understand 3785 * why this is the case. 3786 * 3787 * First, note that current state is the state that is not yet "checkpointed", 3788 * i.e., it is not yet put into env->explored_states, and it has no children 3789 * states as well. It's ephemeral, and can end up either a) being discarded if 3790 * compatible explored state is found at some point or BPF_EXIT instruction is 3791 * reached or b) checkpointed and put into env->explored_states, branching out 3792 * into one or more children states. 3793 * 3794 * In the former case, precise markings in current state are completely 3795 * ignored by state comparison code (see regsafe() for details). Only 3796 * checkpointed ("old") state precise markings are important, and if old 3797 * state's register/slot is precise, regsafe() assumes current state's 3798 * register/slot as precise and checks value ranges exactly and precisely. If 3799 * states turn out to be compatible, current state's necessary precise 3800 * markings and any required parent states' precise markings are enforced 3801 * after the fact with propagate_precision() logic, after the fact. But it's 3802 * important to realize that in this case, even after marking current state 3803 * registers/slots as precise, we immediately discard current state. So what 3804 * actually matters is any of the precise markings propagated into current 3805 * state's parent states, which are always checkpointed (due to b) case above). 3806 * As such, for scenario a) it doesn't matter if current state has precise 3807 * markings set or not. 3808 * 3809 * Now, for the scenario b), checkpointing and forking into child(ren) 3810 * state(s). Note that before current state gets to checkpointing step, any 3811 * processed instruction always assumes precise SCALAR register/slot 3812 * knowledge: if precise value or range is useful to prune jump branch, BPF 3813 * verifier takes this opportunity enthusiastically. Similarly, when 3814 * register's value is used to calculate offset or memory address, exact 3815 * knowledge of SCALAR range is assumed, checked, and enforced. So, similar to 3816 * what we mentioned above about state comparison ignoring precise markings 3817 * during state comparison, BPF verifier ignores and also assumes precise 3818 * markings *at will* during instruction verification process. But as verifier 3819 * assumes precision, it also propagates any precision dependencies across 3820 * parent states, which are not yet finalized, so can be further restricted 3821 * based on new knowledge gained from restrictions enforced by their children 3822 * states. This is so that once those parent states are finalized, i.e., when 3823 * they have no more active children state, state comparison logic in 3824 * is_state_visited() would enforce strict and precise SCALAR ranges, if 3825 * required for correctness. 3826 * 3827 * To build a bit more intuition, note also that once a state is checkpointed, 3828 * the path we took to get to that state is not important. This is crucial 3829 * property for state pruning. When state is checkpointed and finalized at 3830 * some instruction index, it can be correctly and safely used to "short 3831 * circuit" any *compatible* state that reaches exactly the same instruction 3832 * index. I.e., if we jumped to that instruction from a completely different 3833 * code path than original finalized state was derived from, it doesn't 3834 * matter, current state can be discarded because from that instruction 3835 * forward having a compatible state will ensure we will safely reach the 3836 * exit. States describe preconditions for further exploration, but completely 3837 * forget the history of how we got here. 3838 * 3839 * This also means that even if we needed precise SCALAR range to get to 3840 * finalized state, but from that point forward *that same* SCALAR register is 3841 * never used in a precise context (i.e., it's precise value is not needed for 3842 * correctness), it's correct and safe to mark such register as "imprecise" 3843 * (i.e., precise marking set to false). This is what we rely on when we do 3844 * not set precise marking in current state. If no child state requires 3845 * precision for any given SCALAR register, it's safe to dictate that it can 3846 * be imprecise. If any child state does require this register to be precise, 3847 * we'll mark it precise later retroactively during precise markings 3848 * propagation from child state to parent states. 3849 * 3850 * Skipping precise marking setting in current state is a mild version of 3851 * relying on the above observation. But we can utilize this property even 3852 * more aggressively by proactively forgetting any precise marking in the 3853 * current state (which we inherited from the parent state), right before we 3854 * checkpoint it and branch off into new child state. This is done by 3855 * mark_all_scalars_imprecise() to hopefully get more permissive and generic 3856 * finalized states which help in short circuiting more future states. 3857 */ 3858 static int __mark_chain_precision(struct bpf_verifier_env *env, int regno) 3859 { 3860 struct backtrack_state *bt = &env->bt; 3861 struct bpf_verifier_state *st = env->cur_state; 3862 int first_idx = st->first_insn_idx; 3863 int last_idx = env->insn_idx; 3864 struct bpf_func_state *func; 3865 struct bpf_reg_state *reg; 3866 bool skip_first = true; 3867 int i, prev_i, fr, err; 3868 3869 if (!env->bpf_capable) 3870 return 0; 3871 3872 /* set frame number from which we are starting to backtrack */ 3873 bt_init(bt, env->cur_state->curframe); 3874 3875 /* Do sanity checks against current state of register and/or stack 3876 * slot, but don't set precise flag in current state, as precision 3877 * tracking in the current state is unnecessary. 3878 */ 3879 func = st->frame[bt->frame]; 3880 if (regno >= 0) { 3881 reg = &func->regs[regno]; 3882 if (reg->type != SCALAR_VALUE) { 3883 WARN_ONCE(1, "backtracing misuse"); 3884 return -EFAULT; 3885 } 3886 bt_set_reg(bt, regno); 3887 } 3888 3889 if (bt_empty(bt)) 3890 return 0; 3891 3892 for (;;) { 3893 DECLARE_BITMAP(mask, 64); 3894 u32 history = st->jmp_history_cnt; 3895 3896 if (env->log.level & BPF_LOG_LEVEL2) { 3897 verbose(env, "mark_precise: frame%d: last_idx %d first_idx %d\n", 3898 bt->frame, last_idx, first_idx); 3899 } 3900 3901 if (last_idx < 0) { 3902 /* we are at the entry into subprog, which 3903 * is expected for global funcs, but only if 3904 * requested precise registers are R1-R5 3905 * (which are global func's input arguments) 3906 */ 3907 if (st->curframe == 0 && 3908 st->frame[0]->subprogno > 0 && 3909 st->frame[0]->callsite == BPF_MAIN_FUNC && 3910 bt_stack_mask(bt) == 0 && 3911 (bt_reg_mask(bt) & ~BPF_REGMASK_ARGS) == 0) { 3912 bitmap_from_u64(mask, bt_reg_mask(bt)); 3913 for_each_set_bit(i, mask, 32) { 3914 reg = &st->frame[0]->regs[i]; 3915 if (reg->type != SCALAR_VALUE) { 3916 bt_clear_reg(bt, i); 3917 continue; 3918 } 3919 reg->precise = true; 3920 } 3921 return 0; 3922 } 3923 3924 verbose(env, "BUG backtracking func entry subprog %d reg_mask %x stack_mask %llx\n", 3925 st->frame[0]->subprogno, bt_reg_mask(bt), bt_stack_mask(bt)); 3926 WARN_ONCE(1, "verifier backtracking bug"); 3927 return -EFAULT; 3928 } 3929 3930 for (i = last_idx, prev_i = -1;;) { 3931 if (skip_first) { 3932 err = 0; 3933 skip_first = false; 3934 } else { 3935 err = backtrack_insn(env, i, prev_i, bt); 3936 } 3937 if (err == -ENOTSUPP) { 3938 mark_all_scalars_precise(env, env->cur_state); 3939 bt_reset(bt); 3940 return 0; 3941 } else if (err) { 3942 return err; 3943 } 3944 if (bt_empty(bt)) 3945 /* Found assignment(s) into tracked register in this state. 3946 * Since this state is already marked, just return. 3947 * Nothing to be tracked further in the parent state. 3948 */ 3949 return 0; 3950 if (i == first_idx) 3951 break; 3952 prev_i = i; 3953 i = get_prev_insn_idx(st, i, &history); 3954 if (i >= env->prog->len) { 3955 /* This can happen if backtracking reached insn 0 3956 * and there are still reg_mask or stack_mask 3957 * to backtrack. 3958 * It means the backtracking missed the spot where 3959 * particular register was initialized with a constant. 3960 */ 3961 verbose(env, "BUG backtracking idx %d\n", i); 3962 WARN_ONCE(1, "verifier backtracking bug"); 3963 return -EFAULT; 3964 } 3965 } 3966 st = st->parent; 3967 if (!st) 3968 break; 3969 3970 for (fr = bt->frame; fr >= 0; fr--) { 3971 func = st->frame[fr]; 3972 bitmap_from_u64(mask, bt_frame_reg_mask(bt, fr)); 3973 for_each_set_bit(i, mask, 32) { 3974 reg = &func->regs[i]; 3975 if (reg->type != SCALAR_VALUE) { 3976 bt_clear_frame_reg(bt, fr, i); 3977 continue; 3978 } 3979 if (reg->precise) 3980 bt_clear_frame_reg(bt, fr, i); 3981 else 3982 reg->precise = true; 3983 } 3984 3985 bitmap_from_u64(mask, bt_frame_stack_mask(bt, fr)); 3986 for_each_set_bit(i, mask, 64) { 3987 if (i >= func->allocated_stack / BPF_REG_SIZE) { 3988 /* the sequence of instructions: 3989 * 2: (bf) r3 = r10 3990 * 3: (7b) *(u64 *)(r3 -8) = r0 3991 * 4: (79) r4 = *(u64 *)(r10 -8) 3992 * doesn't contain jmps. It's backtracked 3993 * as a single block. 3994 * During backtracking insn 3 is not recognized as 3995 * stack access, so at the end of backtracking 3996 * stack slot fp-8 is still marked in stack_mask. 3997 * However the parent state may not have accessed 3998 * fp-8 and it's "unallocated" stack space. 3999 * In such case fallback to conservative. 4000 */ 4001 mark_all_scalars_precise(env, env->cur_state); 4002 bt_reset(bt); 4003 return 0; 4004 } 4005 4006 if (!is_spilled_scalar_reg(&func->stack[i])) { 4007 bt_clear_frame_slot(bt, fr, i); 4008 continue; 4009 } 4010 reg = &func->stack[i].spilled_ptr; 4011 if (reg->precise) 4012 bt_clear_frame_slot(bt, fr, i); 4013 else 4014 reg->precise = true; 4015 } 4016 if (env->log.level & BPF_LOG_LEVEL2) { 4017 fmt_reg_mask(env->tmp_str_buf, TMP_STR_BUF_LEN, 4018 bt_frame_reg_mask(bt, fr)); 4019 verbose(env, "mark_precise: frame%d: parent state regs=%s ", 4020 fr, env->tmp_str_buf); 4021 fmt_stack_mask(env->tmp_str_buf, TMP_STR_BUF_LEN, 4022 bt_frame_stack_mask(bt, fr)); 4023 verbose(env, "stack=%s: ", env->tmp_str_buf); 4024 print_verifier_state(env, func, true); 4025 } 4026 } 4027 4028 if (bt_empty(bt)) 4029 return 0; 4030 4031 last_idx = st->last_insn_idx; 4032 first_idx = st->first_insn_idx; 4033 } 4034 4035 /* if we still have requested precise regs or slots, we missed 4036 * something (e.g., stack access through non-r10 register), so 4037 * fallback to marking all precise 4038 */ 4039 if (!bt_empty(bt)) { 4040 mark_all_scalars_precise(env, env->cur_state); 4041 bt_reset(bt); 4042 } 4043 4044 return 0; 4045 } 4046 4047 int mark_chain_precision(struct bpf_verifier_env *env, int regno) 4048 { 4049 return __mark_chain_precision(env, regno); 4050 } 4051 4052 /* mark_chain_precision_batch() assumes that env->bt is set in the caller to 4053 * desired reg and stack masks across all relevant frames 4054 */ 4055 static int mark_chain_precision_batch(struct bpf_verifier_env *env) 4056 { 4057 return __mark_chain_precision(env, -1); 4058 } 4059 4060 static bool is_spillable_regtype(enum bpf_reg_type type) 4061 { 4062 switch (base_type(type)) { 4063 case PTR_TO_MAP_VALUE: 4064 case PTR_TO_STACK: 4065 case PTR_TO_CTX: 4066 case PTR_TO_PACKET: 4067 case PTR_TO_PACKET_META: 4068 case PTR_TO_PACKET_END: 4069 case PTR_TO_FLOW_KEYS: 4070 case CONST_PTR_TO_MAP: 4071 case PTR_TO_SOCKET: 4072 case PTR_TO_SOCK_COMMON: 4073 case PTR_TO_TCP_SOCK: 4074 case PTR_TO_XDP_SOCK: 4075 case PTR_TO_BTF_ID: 4076 case PTR_TO_BUF: 4077 case PTR_TO_MEM: 4078 case PTR_TO_FUNC: 4079 case PTR_TO_MAP_KEY: 4080 return true; 4081 default: 4082 return false; 4083 } 4084 } 4085 4086 /* Does this register contain a constant zero? */ 4087 static bool register_is_null(struct bpf_reg_state *reg) 4088 { 4089 return reg->type == SCALAR_VALUE && tnum_equals_const(reg->var_off, 0); 4090 } 4091 4092 static bool register_is_const(struct bpf_reg_state *reg) 4093 { 4094 return reg->type == SCALAR_VALUE && tnum_is_const(reg->var_off); 4095 } 4096 4097 static bool __is_scalar_unbounded(struct bpf_reg_state *reg) 4098 { 4099 return tnum_is_unknown(reg->var_off) && 4100 reg->smin_value == S64_MIN && reg->smax_value == S64_MAX && 4101 reg->umin_value == 0 && reg->umax_value == U64_MAX && 4102 reg->s32_min_value == S32_MIN && reg->s32_max_value == S32_MAX && 4103 reg->u32_min_value == 0 && reg->u32_max_value == U32_MAX; 4104 } 4105 4106 static bool register_is_bounded(struct bpf_reg_state *reg) 4107 { 4108 return reg->type == SCALAR_VALUE && !__is_scalar_unbounded(reg); 4109 } 4110 4111 static bool __is_pointer_value(bool allow_ptr_leaks, 4112 const struct bpf_reg_state *reg) 4113 { 4114 if (allow_ptr_leaks) 4115 return false; 4116 4117 return reg->type != SCALAR_VALUE; 4118 } 4119 4120 /* Copy src state preserving dst->parent and dst->live fields */ 4121 static void copy_register_state(struct bpf_reg_state *dst, const struct bpf_reg_state *src) 4122 { 4123 struct bpf_reg_state *parent = dst->parent; 4124 enum bpf_reg_liveness live = dst->live; 4125 4126 *dst = *src; 4127 dst->parent = parent; 4128 dst->live = live; 4129 } 4130 4131 static void save_register_state(struct bpf_func_state *state, 4132 int spi, struct bpf_reg_state *reg, 4133 int size) 4134 { 4135 int i; 4136 4137 copy_register_state(&state->stack[spi].spilled_ptr, reg); 4138 if (size == BPF_REG_SIZE) 4139 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN; 4140 4141 for (i = BPF_REG_SIZE; i > BPF_REG_SIZE - size; i--) 4142 state->stack[spi].slot_type[i - 1] = STACK_SPILL; 4143 4144 /* size < 8 bytes spill */ 4145 for (; i; i--) 4146 scrub_spilled_slot(&state->stack[spi].slot_type[i - 1]); 4147 } 4148 4149 static bool is_bpf_st_mem(struct bpf_insn *insn) 4150 { 4151 return BPF_CLASS(insn->code) == BPF_ST && BPF_MODE(insn->code) == BPF_MEM; 4152 } 4153 4154 /* check_stack_{read,write}_fixed_off functions track spill/fill of registers, 4155 * stack boundary and alignment are checked in check_mem_access() 4156 */ 4157 static int check_stack_write_fixed_off(struct bpf_verifier_env *env, 4158 /* stack frame we're writing to */ 4159 struct bpf_func_state *state, 4160 int off, int size, int value_regno, 4161 int insn_idx) 4162 { 4163 struct bpf_func_state *cur; /* state of the current function */ 4164 int i, slot = -off - 1, spi = slot / BPF_REG_SIZE, err; 4165 struct bpf_insn *insn = &env->prog->insnsi[insn_idx]; 4166 struct bpf_reg_state *reg = NULL; 4167 u32 dst_reg = insn->dst_reg; 4168 4169 err = grow_stack_state(state, round_up(slot + 1, BPF_REG_SIZE)); 4170 if (err) 4171 return err; 4172 /* caller checked that off % size == 0 and -MAX_BPF_STACK <= off < 0, 4173 * so it's aligned access and [off, off + size) are within stack limits 4174 */ 4175 if (!env->allow_ptr_leaks && 4176 state->stack[spi].slot_type[0] == STACK_SPILL && 4177 size != BPF_REG_SIZE) { 4178 verbose(env, "attempt to corrupt spilled pointer on stack\n"); 4179 return -EACCES; 4180 } 4181 4182 cur = env->cur_state->frame[env->cur_state->curframe]; 4183 if (value_regno >= 0) 4184 reg = &cur->regs[value_regno]; 4185 if (!env->bypass_spec_v4) { 4186 bool sanitize = reg && is_spillable_regtype(reg->type); 4187 4188 for (i = 0; i < size; i++) { 4189 u8 type = state->stack[spi].slot_type[i]; 4190 4191 if (type != STACK_MISC && type != STACK_ZERO) { 4192 sanitize = true; 4193 break; 4194 } 4195 } 4196 4197 if (sanitize) 4198 env->insn_aux_data[insn_idx].sanitize_stack_spill = true; 4199 } 4200 4201 err = destroy_if_dynptr_stack_slot(env, state, spi); 4202 if (err) 4203 return err; 4204 4205 mark_stack_slot_scratched(env, spi); 4206 if (reg && !(off % BPF_REG_SIZE) && register_is_bounded(reg) && 4207 !register_is_null(reg) && env->bpf_capable) { 4208 if (dst_reg != BPF_REG_FP) { 4209 /* The backtracking logic can only recognize explicit 4210 * stack slot address like [fp - 8]. Other spill of 4211 * scalar via different register has to be conservative. 4212 * Backtrack from here and mark all registers as precise 4213 * that contributed into 'reg' being a constant. 4214 */ 4215 err = mark_chain_precision(env, value_regno); 4216 if (err) 4217 return err; 4218 } 4219 save_register_state(state, spi, reg, size); 4220 } else if (!reg && !(off % BPF_REG_SIZE) && is_bpf_st_mem(insn) && 4221 insn->imm != 0 && env->bpf_capable) { 4222 struct bpf_reg_state fake_reg = {}; 4223 4224 __mark_reg_known(&fake_reg, (u32)insn->imm); 4225 fake_reg.type = SCALAR_VALUE; 4226 save_register_state(state, spi, &fake_reg, size); 4227 } else if (reg && is_spillable_regtype(reg->type)) { 4228 /* register containing pointer is being spilled into stack */ 4229 if (size != BPF_REG_SIZE) { 4230 verbose_linfo(env, insn_idx, "; "); 4231 verbose(env, "invalid size of register spill\n"); 4232 return -EACCES; 4233 } 4234 if (state != cur && reg->type == PTR_TO_STACK) { 4235 verbose(env, "cannot spill pointers to stack into stack frame of the caller\n"); 4236 return -EINVAL; 4237 } 4238 save_register_state(state, spi, reg, size); 4239 } else { 4240 u8 type = STACK_MISC; 4241 4242 /* regular write of data into stack destroys any spilled ptr */ 4243 state->stack[spi].spilled_ptr.type = NOT_INIT; 4244 /* Mark slots as STACK_MISC if they belonged to spilled ptr/dynptr/iter. */ 4245 if (is_stack_slot_special(&state->stack[spi])) 4246 for (i = 0; i < BPF_REG_SIZE; i++) 4247 scrub_spilled_slot(&state->stack[spi].slot_type[i]); 4248 4249 /* only mark the slot as written if all 8 bytes were written 4250 * otherwise read propagation may incorrectly stop too soon 4251 * when stack slots are partially written. 4252 * This heuristic means that read propagation will be 4253 * conservative, since it will add reg_live_read marks 4254 * to stack slots all the way to first state when programs 4255 * writes+reads less than 8 bytes 4256 */ 4257 if (size == BPF_REG_SIZE) 4258 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN; 4259 4260 /* when we zero initialize stack slots mark them as such */ 4261 if ((reg && register_is_null(reg)) || 4262 (!reg && is_bpf_st_mem(insn) && insn->imm == 0)) { 4263 /* backtracking doesn't work for STACK_ZERO yet. */ 4264 err = mark_chain_precision(env, value_regno); 4265 if (err) 4266 return err; 4267 type = STACK_ZERO; 4268 } 4269 4270 /* Mark slots affected by this stack write. */ 4271 for (i = 0; i < size; i++) 4272 state->stack[spi].slot_type[(slot - i) % BPF_REG_SIZE] = 4273 type; 4274 } 4275 return 0; 4276 } 4277 4278 /* Write the stack: 'stack[ptr_regno + off] = value_regno'. 'ptr_regno' is 4279 * known to contain a variable offset. 4280 * This function checks whether the write is permitted and conservatively 4281 * tracks the effects of the write, considering that each stack slot in the 4282 * dynamic range is potentially written to. 4283 * 4284 * 'off' includes 'regno->off'. 4285 * 'value_regno' can be -1, meaning that an unknown value is being written to 4286 * the stack. 4287 * 4288 * Spilled pointers in range are not marked as written because we don't know 4289 * what's going to be actually written. This means that read propagation for 4290 * future reads cannot be terminated by this write. 4291 * 4292 * For privileged programs, uninitialized stack slots are considered 4293 * initialized by this write (even though we don't know exactly what offsets 4294 * are going to be written to). The idea is that we don't want the verifier to 4295 * reject future reads that access slots written to through variable offsets. 4296 */ 4297 static int check_stack_write_var_off(struct bpf_verifier_env *env, 4298 /* func where register points to */ 4299 struct bpf_func_state *state, 4300 int ptr_regno, int off, int size, 4301 int value_regno, int insn_idx) 4302 { 4303 struct bpf_func_state *cur; /* state of the current function */ 4304 int min_off, max_off; 4305 int i, err; 4306 struct bpf_reg_state *ptr_reg = NULL, *value_reg = NULL; 4307 struct bpf_insn *insn = &env->prog->insnsi[insn_idx]; 4308 bool writing_zero = false; 4309 /* set if the fact that we're writing a zero is used to let any 4310 * stack slots remain STACK_ZERO 4311 */ 4312 bool zero_used = false; 4313 4314 cur = env->cur_state->frame[env->cur_state->curframe]; 4315 ptr_reg = &cur->regs[ptr_regno]; 4316 min_off = ptr_reg->smin_value + off; 4317 max_off = ptr_reg->smax_value + off + size; 4318 if (value_regno >= 0) 4319 value_reg = &cur->regs[value_regno]; 4320 if ((value_reg && register_is_null(value_reg)) || 4321 (!value_reg && is_bpf_st_mem(insn) && insn->imm == 0)) 4322 writing_zero = true; 4323 4324 err = grow_stack_state(state, round_up(-min_off, BPF_REG_SIZE)); 4325 if (err) 4326 return err; 4327 4328 for (i = min_off; i < max_off; i++) { 4329 int spi; 4330 4331 spi = __get_spi(i); 4332 err = destroy_if_dynptr_stack_slot(env, state, spi); 4333 if (err) 4334 return err; 4335 } 4336 4337 /* Variable offset writes destroy any spilled pointers in range. */ 4338 for (i = min_off; i < max_off; i++) { 4339 u8 new_type, *stype; 4340 int slot, spi; 4341 4342 slot = -i - 1; 4343 spi = slot / BPF_REG_SIZE; 4344 stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE]; 4345 mark_stack_slot_scratched(env, spi); 4346 4347 if (!env->allow_ptr_leaks && *stype != STACK_MISC && *stype != STACK_ZERO) { 4348 /* Reject the write if range we may write to has not 4349 * been initialized beforehand. If we didn't reject 4350 * here, the ptr status would be erased below (even 4351 * though not all slots are actually overwritten), 4352 * possibly opening the door to leaks. 4353 * 4354 * We do however catch STACK_INVALID case below, and 4355 * only allow reading possibly uninitialized memory 4356 * later for CAP_PERFMON, as the write may not happen to 4357 * that slot. 4358 */ 4359 verbose(env, "spilled ptr in range of var-offset stack write; insn %d, ptr off: %d", 4360 insn_idx, i); 4361 return -EINVAL; 4362 } 4363 4364 /* Erase all spilled pointers. */ 4365 state->stack[spi].spilled_ptr.type = NOT_INIT; 4366 4367 /* Update the slot type. */ 4368 new_type = STACK_MISC; 4369 if (writing_zero && *stype == STACK_ZERO) { 4370 new_type = STACK_ZERO; 4371 zero_used = true; 4372 } 4373 /* If the slot is STACK_INVALID, we check whether it's OK to 4374 * pretend that it will be initialized by this write. The slot 4375 * might not actually be written to, and so if we mark it as 4376 * initialized future reads might leak uninitialized memory. 4377 * For privileged programs, we will accept such reads to slots 4378 * that may or may not be written because, if we're reject 4379 * them, the error would be too confusing. 4380 */ 4381 if (*stype == STACK_INVALID && !env->allow_uninit_stack) { 4382 verbose(env, "uninit stack in range of var-offset write prohibited for !root; insn %d, off: %d", 4383 insn_idx, i); 4384 return -EINVAL; 4385 } 4386 *stype = new_type; 4387 } 4388 if (zero_used) { 4389 /* backtracking doesn't work for STACK_ZERO yet. */ 4390 err = mark_chain_precision(env, value_regno); 4391 if (err) 4392 return err; 4393 } 4394 return 0; 4395 } 4396 4397 /* When register 'dst_regno' is assigned some values from stack[min_off, 4398 * max_off), we set the register's type according to the types of the 4399 * respective stack slots. If all the stack values are known to be zeros, then 4400 * so is the destination reg. Otherwise, the register is considered to be 4401 * SCALAR. This function does not deal with register filling; the caller must 4402 * ensure that all spilled registers in the stack range have been marked as 4403 * read. 4404 */ 4405 static void mark_reg_stack_read(struct bpf_verifier_env *env, 4406 /* func where src register points to */ 4407 struct bpf_func_state *ptr_state, 4408 int min_off, int max_off, int dst_regno) 4409 { 4410 struct bpf_verifier_state *vstate = env->cur_state; 4411 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 4412 int i, slot, spi; 4413 u8 *stype; 4414 int zeros = 0; 4415 4416 for (i = min_off; i < max_off; i++) { 4417 slot = -i - 1; 4418 spi = slot / BPF_REG_SIZE; 4419 mark_stack_slot_scratched(env, spi); 4420 stype = ptr_state->stack[spi].slot_type; 4421 if (stype[slot % BPF_REG_SIZE] != STACK_ZERO) 4422 break; 4423 zeros++; 4424 } 4425 if (zeros == max_off - min_off) { 4426 /* any access_size read into register is zero extended, 4427 * so the whole register == const_zero 4428 */ 4429 __mark_reg_const_zero(&state->regs[dst_regno]); 4430 /* backtracking doesn't support STACK_ZERO yet, 4431 * so mark it precise here, so that later 4432 * backtracking can stop here. 4433 * Backtracking may not need this if this register 4434 * doesn't participate in pointer adjustment. 4435 * Forward propagation of precise flag is not 4436 * necessary either. This mark is only to stop 4437 * backtracking. Any register that contributed 4438 * to const 0 was marked precise before spill. 4439 */ 4440 state->regs[dst_regno].precise = true; 4441 } else { 4442 /* have read misc data from the stack */ 4443 mark_reg_unknown(env, state->regs, dst_regno); 4444 } 4445 state->regs[dst_regno].live |= REG_LIVE_WRITTEN; 4446 } 4447 4448 /* Read the stack at 'off' and put the results into the register indicated by 4449 * 'dst_regno'. It handles reg filling if the addressed stack slot is a 4450 * spilled reg. 4451 * 4452 * 'dst_regno' can be -1, meaning that the read value is not going to a 4453 * register. 4454 * 4455 * The access is assumed to be within the current stack bounds. 4456 */ 4457 static int check_stack_read_fixed_off(struct bpf_verifier_env *env, 4458 /* func where src register points to */ 4459 struct bpf_func_state *reg_state, 4460 int off, int size, int dst_regno) 4461 { 4462 struct bpf_verifier_state *vstate = env->cur_state; 4463 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 4464 int i, slot = -off - 1, spi = slot / BPF_REG_SIZE; 4465 struct bpf_reg_state *reg; 4466 u8 *stype, type; 4467 4468 stype = reg_state->stack[spi].slot_type; 4469 reg = ®_state->stack[spi].spilled_ptr; 4470 4471 mark_stack_slot_scratched(env, spi); 4472 4473 if (is_spilled_reg(®_state->stack[spi])) { 4474 u8 spill_size = 1; 4475 4476 for (i = BPF_REG_SIZE - 1; i > 0 && stype[i - 1] == STACK_SPILL; i--) 4477 spill_size++; 4478 4479 if (size != BPF_REG_SIZE || spill_size != BPF_REG_SIZE) { 4480 if (reg->type != SCALAR_VALUE) { 4481 verbose_linfo(env, env->insn_idx, "; "); 4482 verbose(env, "invalid size of register fill\n"); 4483 return -EACCES; 4484 } 4485 4486 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64); 4487 if (dst_regno < 0) 4488 return 0; 4489 4490 if (!(off % BPF_REG_SIZE) && size == spill_size) { 4491 /* The earlier check_reg_arg() has decided the 4492 * subreg_def for this insn. Save it first. 4493 */ 4494 s32 subreg_def = state->regs[dst_regno].subreg_def; 4495 4496 copy_register_state(&state->regs[dst_regno], reg); 4497 state->regs[dst_regno].subreg_def = subreg_def; 4498 } else { 4499 for (i = 0; i < size; i++) { 4500 type = stype[(slot - i) % BPF_REG_SIZE]; 4501 if (type == STACK_SPILL) 4502 continue; 4503 if (type == STACK_MISC) 4504 continue; 4505 if (type == STACK_INVALID && env->allow_uninit_stack) 4506 continue; 4507 verbose(env, "invalid read from stack off %d+%d size %d\n", 4508 off, i, size); 4509 return -EACCES; 4510 } 4511 mark_reg_unknown(env, state->regs, dst_regno); 4512 } 4513 state->regs[dst_regno].live |= REG_LIVE_WRITTEN; 4514 return 0; 4515 } 4516 4517 if (dst_regno >= 0) { 4518 /* restore register state from stack */ 4519 copy_register_state(&state->regs[dst_regno], reg); 4520 /* mark reg as written since spilled pointer state likely 4521 * has its liveness marks cleared by is_state_visited() 4522 * which resets stack/reg liveness for state transitions 4523 */ 4524 state->regs[dst_regno].live |= REG_LIVE_WRITTEN; 4525 } else if (__is_pointer_value(env->allow_ptr_leaks, reg)) { 4526 /* If dst_regno==-1, the caller is asking us whether 4527 * it is acceptable to use this value as a SCALAR_VALUE 4528 * (e.g. for XADD). 4529 * We must not allow unprivileged callers to do that 4530 * with spilled pointers. 4531 */ 4532 verbose(env, "leaking pointer from stack off %d\n", 4533 off); 4534 return -EACCES; 4535 } 4536 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64); 4537 } else { 4538 for (i = 0; i < size; i++) { 4539 type = stype[(slot - i) % BPF_REG_SIZE]; 4540 if (type == STACK_MISC) 4541 continue; 4542 if (type == STACK_ZERO) 4543 continue; 4544 if (type == STACK_INVALID && env->allow_uninit_stack) 4545 continue; 4546 verbose(env, "invalid read from stack off %d+%d size %d\n", 4547 off, i, size); 4548 return -EACCES; 4549 } 4550 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64); 4551 if (dst_regno >= 0) 4552 mark_reg_stack_read(env, reg_state, off, off + size, dst_regno); 4553 } 4554 return 0; 4555 } 4556 4557 enum bpf_access_src { 4558 ACCESS_DIRECT = 1, /* the access is performed by an instruction */ 4559 ACCESS_HELPER = 2, /* the access is performed by a helper */ 4560 }; 4561 4562 static int check_stack_range_initialized(struct bpf_verifier_env *env, 4563 int regno, int off, int access_size, 4564 bool zero_size_allowed, 4565 enum bpf_access_src type, 4566 struct bpf_call_arg_meta *meta); 4567 4568 static struct bpf_reg_state *reg_state(struct bpf_verifier_env *env, int regno) 4569 { 4570 return cur_regs(env) + regno; 4571 } 4572 4573 /* Read the stack at 'ptr_regno + off' and put the result into the register 4574 * 'dst_regno'. 4575 * 'off' includes the pointer register's fixed offset(i.e. 'ptr_regno.off'), 4576 * but not its variable offset. 4577 * 'size' is assumed to be <= reg size and the access is assumed to be aligned. 4578 * 4579 * As opposed to check_stack_read_fixed_off, this function doesn't deal with 4580 * filling registers (i.e. reads of spilled register cannot be detected when 4581 * the offset is not fixed). We conservatively mark 'dst_regno' as containing 4582 * SCALAR_VALUE. That's why we assert that the 'ptr_regno' has a variable 4583 * offset; for a fixed offset check_stack_read_fixed_off should be used 4584 * instead. 4585 */ 4586 static int check_stack_read_var_off(struct bpf_verifier_env *env, 4587 int ptr_regno, int off, int size, int dst_regno) 4588 { 4589 /* The state of the source register. */ 4590 struct bpf_reg_state *reg = reg_state(env, ptr_regno); 4591 struct bpf_func_state *ptr_state = func(env, reg); 4592 int err; 4593 int min_off, max_off; 4594 4595 /* Note that we pass a NULL meta, so raw access will not be permitted. 4596 */ 4597 err = check_stack_range_initialized(env, ptr_regno, off, size, 4598 false, ACCESS_DIRECT, NULL); 4599 if (err) 4600 return err; 4601 4602 min_off = reg->smin_value + off; 4603 max_off = reg->smax_value + off; 4604 mark_reg_stack_read(env, ptr_state, min_off, max_off + size, dst_regno); 4605 return 0; 4606 } 4607 4608 /* check_stack_read dispatches to check_stack_read_fixed_off or 4609 * check_stack_read_var_off. 4610 * 4611 * The caller must ensure that the offset falls within the allocated stack 4612 * bounds. 4613 * 4614 * 'dst_regno' is a register which will receive the value from the stack. It 4615 * can be -1, meaning that the read value is not going to a register. 4616 */ 4617 static int check_stack_read(struct bpf_verifier_env *env, 4618 int ptr_regno, int off, int size, 4619 int dst_regno) 4620 { 4621 struct bpf_reg_state *reg = reg_state(env, ptr_regno); 4622 struct bpf_func_state *state = func(env, reg); 4623 int err; 4624 /* Some accesses are only permitted with a static offset. */ 4625 bool var_off = !tnum_is_const(reg->var_off); 4626 4627 /* The offset is required to be static when reads don't go to a 4628 * register, in order to not leak pointers (see 4629 * check_stack_read_fixed_off). 4630 */ 4631 if (dst_regno < 0 && var_off) { 4632 char tn_buf[48]; 4633 4634 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 4635 verbose(env, "variable offset stack pointer cannot be passed into helper function; var_off=%s off=%d size=%d\n", 4636 tn_buf, off, size); 4637 return -EACCES; 4638 } 4639 /* Variable offset is prohibited for unprivileged mode for simplicity 4640 * since it requires corresponding support in Spectre masking for stack 4641 * ALU. See also retrieve_ptr_limit(). The check in 4642 * check_stack_access_for_ptr_arithmetic() called by 4643 * adjust_ptr_min_max_vals() prevents users from creating stack pointers 4644 * with variable offsets, therefore no check is required here. Further, 4645 * just checking it here would be insufficient as speculative stack 4646 * writes could still lead to unsafe speculative behaviour. 4647 */ 4648 if (!var_off) { 4649 off += reg->var_off.value; 4650 err = check_stack_read_fixed_off(env, state, off, size, 4651 dst_regno); 4652 } else { 4653 /* Variable offset stack reads need more conservative handling 4654 * than fixed offset ones. Note that dst_regno >= 0 on this 4655 * branch. 4656 */ 4657 err = check_stack_read_var_off(env, ptr_regno, off, size, 4658 dst_regno); 4659 } 4660 return err; 4661 } 4662 4663 4664 /* check_stack_write dispatches to check_stack_write_fixed_off or 4665 * check_stack_write_var_off. 4666 * 4667 * 'ptr_regno' is the register used as a pointer into the stack. 4668 * 'off' includes 'ptr_regno->off', but not its variable offset (if any). 4669 * 'value_regno' is the register whose value we're writing to the stack. It can 4670 * be -1, meaning that we're not writing from a register. 4671 * 4672 * The caller must ensure that the offset falls within the maximum stack size. 4673 */ 4674 static int check_stack_write(struct bpf_verifier_env *env, 4675 int ptr_regno, int off, int size, 4676 int value_regno, int insn_idx) 4677 { 4678 struct bpf_reg_state *reg = reg_state(env, ptr_regno); 4679 struct bpf_func_state *state = func(env, reg); 4680 int err; 4681 4682 if (tnum_is_const(reg->var_off)) { 4683 off += reg->var_off.value; 4684 err = check_stack_write_fixed_off(env, state, off, size, 4685 value_regno, insn_idx); 4686 } else { 4687 /* Variable offset stack reads need more conservative handling 4688 * than fixed offset ones. 4689 */ 4690 err = check_stack_write_var_off(env, state, 4691 ptr_regno, off, size, 4692 value_regno, insn_idx); 4693 } 4694 return err; 4695 } 4696 4697 static int check_map_access_type(struct bpf_verifier_env *env, u32 regno, 4698 int off, int size, enum bpf_access_type type) 4699 { 4700 struct bpf_reg_state *regs = cur_regs(env); 4701 struct bpf_map *map = regs[regno].map_ptr; 4702 u32 cap = bpf_map_flags_to_cap(map); 4703 4704 if (type == BPF_WRITE && !(cap & BPF_MAP_CAN_WRITE)) { 4705 verbose(env, "write into map forbidden, value_size=%d off=%d size=%d\n", 4706 map->value_size, off, size); 4707 return -EACCES; 4708 } 4709 4710 if (type == BPF_READ && !(cap & BPF_MAP_CAN_READ)) { 4711 verbose(env, "read from map forbidden, value_size=%d off=%d size=%d\n", 4712 map->value_size, off, size); 4713 return -EACCES; 4714 } 4715 4716 return 0; 4717 } 4718 4719 /* check read/write into memory region (e.g., map value, ringbuf sample, etc) */ 4720 static int __check_mem_access(struct bpf_verifier_env *env, int regno, 4721 int off, int size, u32 mem_size, 4722 bool zero_size_allowed) 4723 { 4724 bool size_ok = size > 0 || (size == 0 && zero_size_allowed); 4725 struct bpf_reg_state *reg; 4726 4727 if (off >= 0 && size_ok && (u64)off + size <= mem_size) 4728 return 0; 4729 4730 reg = &cur_regs(env)[regno]; 4731 switch (reg->type) { 4732 case PTR_TO_MAP_KEY: 4733 verbose(env, "invalid access to map key, key_size=%d off=%d size=%d\n", 4734 mem_size, off, size); 4735 break; 4736 case PTR_TO_MAP_VALUE: 4737 verbose(env, "invalid access to map value, value_size=%d off=%d size=%d\n", 4738 mem_size, off, size); 4739 break; 4740 case PTR_TO_PACKET: 4741 case PTR_TO_PACKET_META: 4742 case PTR_TO_PACKET_END: 4743 verbose(env, "invalid access to packet, off=%d size=%d, R%d(id=%d,off=%d,r=%d)\n", 4744 off, size, regno, reg->id, off, mem_size); 4745 break; 4746 case PTR_TO_MEM: 4747 default: 4748 verbose(env, "invalid access to memory, mem_size=%u off=%d size=%d\n", 4749 mem_size, off, size); 4750 } 4751 4752 return -EACCES; 4753 } 4754 4755 /* check read/write into a memory region with possible variable offset */ 4756 static int check_mem_region_access(struct bpf_verifier_env *env, u32 regno, 4757 int off, int size, u32 mem_size, 4758 bool zero_size_allowed) 4759 { 4760 struct bpf_verifier_state *vstate = env->cur_state; 4761 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 4762 struct bpf_reg_state *reg = &state->regs[regno]; 4763 int err; 4764 4765 /* We may have adjusted the register pointing to memory region, so we 4766 * need to try adding each of min_value and max_value to off 4767 * to make sure our theoretical access will be safe. 4768 * 4769 * The minimum value is only important with signed 4770 * comparisons where we can't assume the floor of a 4771 * value is 0. If we are using signed variables for our 4772 * index'es we need to make sure that whatever we use 4773 * will have a set floor within our range. 4774 */ 4775 if (reg->smin_value < 0 && 4776 (reg->smin_value == S64_MIN || 4777 (off + reg->smin_value != (s64)(s32)(off + reg->smin_value)) || 4778 reg->smin_value + off < 0)) { 4779 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n", 4780 regno); 4781 return -EACCES; 4782 } 4783 err = __check_mem_access(env, regno, reg->smin_value + off, size, 4784 mem_size, zero_size_allowed); 4785 if (err) { 4786 verbose(env, "R%d min value is outside of the allowed memory range\n", 4787 regno); 4788 return err; 4789 } 4790 4791 /* If we haven't set a max value then we need to bail since we can't be 4792 * sure we won't do bad things. 4793 * If reg->umax_value + off could overflow, treat that as unbounded too. 4794 */ 4795 if (reg->umax_value >= BPF_MAX_VAR_OFF) { 4796 verbose(env, "R%d unbounded memory access, make sure to bounds check any such access\n", 4797 regno); 4798 return -EACCES; 4799 } 4800 err = __check_mem_access(env, regno, reg->umax_value + off, size, 4801 mem_size, zero_size_allowed); 4802 if (err) { 4803 verbose(env, "R%d max value is outside of the allowed memory range\n", 4804 regno); 4805 return err; 4806 } 4807 4808 return 0; 4809 } 4810 4811 static int __check_ptr_off_reg(struct bpf_verifier_env *env, 4812 const struct bpf_reg_state *reg, int regno, 4813 bool fixed_off_ok) 4814 { 4815 /* Access to this pointer-typed register or passing it to a helper 4816 * is only allowed in its original, unmodified form. 4817 */ 4818 4819 if (reg->off < 0) { 4820 verbose(env, "negative offset %s ptr R%d off=%d disallowed\n", 4821 reg_type_str(env, reg->type), regno, reg->off); 4822 return -EACCES; 4823 } 4824 4825 if (!fixed_off_ok && reg->off) { 4826 verbose(env, "dereference of modified %s ptr R%d off=%d disallowed\n", 4827 reg_type_str(env, reg->type), regno, reg->off); 4828 return -EACCES; 4829 } 4830 4831 if (!tnum_is_const(reg->var_off) || reg->var_off.value) { 4832 char tn_buf[48]; 4833 4834 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 4835 verbose(env, "variable %s access var_off=%s disallowed\n", 4836 reg_type_str(env, reg->type), tn_buf); 4837 return -EACCES; 4838 } 4839 4840 return 0; 4841 } 4842 4843 int check_ptr_off_reg(struct bpf_verifier_env *env, 4844 const struct bpf_reg_state *reg, int regno) 4845 { 4846 return __check_ptr_off_reg(env, reg, regno, false); 4847 } 4848 4849 static int map_kptr_match_type(struct bpf_verifier_env *env, 4850 struct btf_field *kptr_field, 4851 struct bpf_reg_state *reg, u32 regno) 4852 { 4853 const char *targ_name = btf_type_name(kptr_field->kptr.btf, kptr_field->kptr.btf_id); 4854 int perm_flags = PTR_MAYBE_NULL | PTR_TRUSTED | MEM_RCU; 4855 const char *reg_name = ""; 4856 4857 /* Only unreferenced case accepts untrusted pointers */ 4858 if (kptr_field->type == BPF_KPTR_UNREF) 4859 perm_flags |= PTR_UNTRUSTED; 4860 4861 if (base_type(reg->type) != PTR_TO_BTF_ID || (type_flag(reg->type) & ~perm_flags)) 4862 goto bad_type; 4863 4864 if (!btf_is_kernel(reg->btf)) { 4865 verbose(env, "R%d must point to kernel BTF\n", regno); 4866 return -EINVAL; 4867 } 4868 /* We need to verify reg->type and reg->btf, before accessing reg->btf */ 4869 reg_name = btf_type_name(reg->btf, reg->btf_id); 4870 4871 /* For ref_ptr case, release function check should ensure we get one 4872 * referenced PTR_TO_BTF_ID, and that its fixed offset is 0. For the 4873 * normal store of unreferenced kptr, we must ensure var_off is zero. 4874 * Since ref_ptr cannot be accessed directly by BPF insns, checks for 4875 * reg->off and reg->ref_obj_id are not needed here. 4876 */ 4877 if (__check_ptr_off_reg(env, reg, regno, true)) 4878 return -EACCES; 4879 4880 /* A full type match is needed, as BTF can be vmlinux or module BTF, and 4881 * we also need to take into account the reg->off. 4882 * 4883 * We want to support cases like: 4884 * 4885 * struct foo { 4886 * struct bar br; 4887 * struct baz bz; 4888 * }; 4889 * 4890 * struct foo *v; 4891 * v = func(); // PTR_TO_BTF_ID 4892 * val->foo = v; // reg->off is zero, btf and btf_id match type 4893 * val->bar = &v->br; // reg->off is still zero, but we need to retry with 4894 * // first member type of struct after comparison fails 4895 * val->baz = &v->bz; // reg->off is non-zero, so struct needs to be walked 4896 * // to match type 4897 * 4898 * In the kptr_ref case, check_func_arg_reg_off already ensures reg->off 4899 * is zero. We must also ensure that btf_struct_ids_match does not walk 4900 * the struct to match type against first member of struct, i.e. reject 4901 * second case from above. Hence, when type is BPF_KPTR_REF, we set 4902 * strict mode to true for type match. 4903 */ 4904 if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off, 4905 kptr_field->kptr.btf, kptr_field->kptr.btf_id, 4906 kptr_field->type == BPF_KPTR_REF)) 4907 goto bad_type; 4908 return 0; 4909 bad_type: 4910 verbose(env, "invalid kptr access, R%d type=%s%s ", regno, 4911 reg_type_str(env, reg->type), reg_name); 4912 verbose(env, "expected=%s%s", reg_type_str(env, PTR_TO_BTF_ID), targ_name); 4913 if (kptr_field->type == BPF_KPTR_UNREF) 4914 verbose(env, " or %s%s\n", reg_type_str(env, PTR_TO_BTF_ID | PTR_UNTRUSTED), 4915 targ_name); 4916 else 4917 verbose(env, "\n"); 4918 return -EINVAL; 4919 } 4920 4921 /* The non-sleepable programs and sleepable programs with explicit bpf_rcu_read_lock() 4922 * can dereference RCU protected pointers and result is PTR_TRUSTED. 4923 */ 4924 static bool in_rcu_cs(struct bpf_verifier_env *env) 4925 { 4926 return env->cur_state->active_rcu_lock || !env->prog->aux->sleepable; 4927 } 4928 4929 /* Once GCC supports btf_type_tag the following mechanism will be replaced with tag check */ 4930 BTF_SET_START(rcu_protected_types) 4931 BTF_ID(struct, prog_test_ref_kfunc) 4932 BTF_ID(struct, cgroup) 4933 BTF_ID(struct, bpf_cpumask) 4934 BTF_ID(struct, task_struct) 4935 BTF_SET_END(rcu_protected_types) 4936 4937 static bool rcu_protected_object(const struct btf *btf, u32 btf_id) 4938 { 4939 if (!btf_is_kernel(btf)) 4940 return false; 4941 return btf_id_set_contains(&rcu_protected_types, btf_id); 4942 } 4943 4944 static bool rcu_safe_kptr(const struct btf_field *field) 4945 { 4946 const struct btf_field_kptr *kptr = &field->kptr; 4947 4948 return field->type == BPF_KPTR_REF && rcu_protected_object(kptr->btf, kptr->btf_id); 4949 } 4950 4951 static int check_map_kptr_access(struct bpf_verifier_env *env, u32 regno, 4952 int value_regno, int insn_idx, 4953 struct btf_field *kptr_field) 4954 { 4955 struct bpf_insn *insn = &env->prog->insnsi[insn_idx]; 4956 int class = BPF_CLASS(insn->code); 4957 struct bpf_reg_state *val_reg; 4958 4959 /* Things we already checked for in check_map_access and caller: 4960 * - Reject cases where variable offset may touch kptr 4961 * - size of access (must be BPF_DW) 4962 * - tnum_is_const(reg->var_off) 4963 * - kptr_field->offset == off + reg->var_off.value 4964 */ 4965 /* Only BPF_[LDX,STX,ST] | BPF_MEM | BPF_DW is supported */ 4966 if (BPF_MODE(insn->code) != BPF_MEM) { 4967 verbose(env, "kptr in map can only be accessed using BPF_MEM instruction mode\n"); 4968 return -EACCES; 4969 } 4970 4971 /* We only allow loading referenced kptr, since it will be marked as 4972 * untrusted, similar to unreferenced kptr. 4973 */ 4974 if (class != BPF_LDX && kptr_field->type == BPF_KPTR_REF) { 4975 verbose(env, "store to referenced kptr disallowed\n"); 4976 return -EACCES; 4977 } 4978 4979 if (class == BPF_LDX) { 4980 val_reg = reg_state(env, value_regno); 4981 /* We can simply mark the value_regno receiving the pointer 4982 * value from map as PTR_TO_BTF_ID, with the correct type. 4983 */ 4984 mark_btf_ld_reg(env, cur_regs(env), value_regno, PTR_TO_BTF_ID, kptr_field->kptr.btf, 4985 kptr_field->kptr.btf_id, 4986 rcu_safe_kptr(kptr_field) && in_rcu_cs(env) ? 4987 PTR_MAYBE_NULL | MEM_RCU : 4988 PTR_MAYBE_NULL | PTR_UNTRUSTED); 4989 /* For mark_ptr_or_null_reg */ 4990 val_reg->id = ++env->id_gen; 4991 } else if (class == BPF_STX) { 4992 val_reg = reg_state(env, value_regno); 4993 if (!register_is_null(val_reg) && 4994 map_kptr_match_type(env, kptr_field, val_reg, value_regno)) 4995 return -EACCES; 4996 } else if (class == BPF_ST) { 4997 if (insn->imm) { 4998 verbose(env, "BPF_ST imm must be 0 when storing to kptr at off=%u\n", 4999 kptr_field->offset); 5000 return -EACCES; 5001 } 5002 } else { 5003 verbose(env, "kptr in map can only be accessed using BPF_LDX/BPF_STX/BPF_ST\n"); 5004 return -EACCES; 5005 } 5006 return 0; 5007 } 5008 5009 /* check read/write into a map element with possible variable offset */ 5010 static int check_map_access(struct bpf_verifier_env *env, u32 regno, 5011 int off, int size, bool zero_size_allowed, 5012 enum bpf_access_src src) 5013 { 5014 struct bpf_verifier_state *vstate = env->cur_state; 5015 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 5016 struct bpf_reg_state *reg = &state->regs[regno]; 5017 struct bpf_map *map = reg->map_ptr; 5018 struct btf_record *rec; 5019 int err, i; 5020 5021 err = check_mem_region_access(env, regno, off, size, map->value_size, 5022 zero_size_allowed); 5023 if (err) 5024 return err; 5025 5026 if (IS_ERR_OR_NULL(map->record)) 5027 return 0; 5028 rec = map->record; 5029 for (i = 0; i < rec->cnt; i++) { 5030 struct btf_field *field = &rec->fields[i]; 5031 u32 p = field->offset; 5032 5033 /* If any part of a field can be touched by load/store, reject 5034 * this program. To check that [x1, x2) overlaps with [y1, y2), 5035 * it is sufficient to check x1 < y2 && y1 < x2. 5036 */ 5037 if (reg->smin_value + off < p + btf_field_type_size(field->type) && 5038 p < reg->umax_value + off + size) { 5039 switch (field->type) { 5040 case BPF_KPTR_UNREF: 5041 case BPF_KPTR_REF: 5042 if (src != ACCESS_DIRECT) { 5043 verbose(env, "kptr cannot be accessed indirectly by helper\n"); 5044 return -EACCES; 5045 } 5046 if (!tnum_is_const(reg->var_off)) { 5047 verbose(env, "kptr access cannot have variable offset\n"); 5048 return -EACCES; 5049 } 5050 if (p != off + reg->var_off.value) { 5051 verbose(env, "kptr access misaligned expected=%u off=%llu\n", 5052 p, off + reg->var_off.value); 5053 return -EACCES; 5054 } 5055 if (size != bpf_size_to_bytes(BPF_DW)) { 5056 verbose(env, "kptr access size must be BPF_DW\n"); 5057 return -EACCES; 5058 } 5059 break; 5060 default: 5061 verbose(env, "%s cannot be accessed directly by load/store\n", 5062 btf_field_type_name(field->type)); 5063 return -EACCES; 5064 } 5065 } 5066 } 5067 return 0; 5068 } 5069 5070 #define MAX_PACKET_OFF 0xffff 5071 5072 static bool may_access_direct_pkt_data(struct bpf_verifier_env *env, 5073 const struct bpf_call_arg_meta *meta, 5074 enum bpf_access_type t) 5075 { 5076 enum bpf_prog_type prog_type = resolve_prog_type(env->prog); 5077 5078 switch (prog_type) { 5079 /* Program types only with direct read access go here! */ 5080 case BPF_PROG_TYPE_LWT_IN: 5081 case BPF_PROG_TYPE_LWT_OUT: 5082 case BPF_PROG_TYPE_LWT_SEG6LOCAL: 5083 case BPF_PROG_TYPE_SK_REUSEPORT: 5084 case BPF_PROG_TYPE_FLOW_DISSECTOR: 5085 case BPF_PROG_TYPE_CGROUP_SKB: 5086 if (t == BPF_WRITE) 5087 return false; 5088 fallthrough; 5089 5090 /* Program types with direct read + write access go here! */ 5091 case BPF_PROG_TYPE_SCHED_CLS: 5092 case BPF_PROG_TYPE_SCHED_ACT: 5093 case BPF_PROG_TYPE_XDP: 5094 case BPF_PROG_TYPE_LWT_XMIT: 5095 case BPF_PROG_TYPE_SK_SKB: 5096 case BPF_PROG_TYPE_SK_MSG: 5097 if (meta) 5098 return meta->pkt_access; 5099 5100 env->seen_direct_write = true; 5101 return true; 5102 5103 case BPF_PROG_TYPE_CGROUP_SOCKOPT: 5104 if (t == BPF_WRITE) 5105 env->seen_direct_write = true; 5106 5107 return true; 5108 5109 default: 5110 return false; 5111 } 5112 } 5113 5114 static int check_packet_access(struct bpf_verifier_env *env, u32 regno, int off, 5115 int size, bool zero_size_allowed) 5116 { 5117 struct bpf_reg_state *regs = cur_regs(env); 5118 struct bpf_reg_state *reg = ®s[regno]; 5119 int err; 5120 5121 /* We may have added a variable offset to the packet pointer; but any 5122 * reg->range we have comes after that. We are only checking the fixed 5123 * offset. 5124 */ 5125 5126 /* We don't allow negative numbers, because we aren't tracking enough 5127 * detail to prove they're safe. 5128 */ 5129 if (reg->smin_value < 0) { 5130 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n", 5131 regno); 5132 return -EACCES; 5133 } 5134 5135 err = reg->range < 0 ? -EINVAL : 5136 __check_mem_access(env, regno, off, size, reg->range, 5137 zero_size_allowed); 5138 if (err) { 5139 verbose(env, "R%d offset is outside of the packet\n", regno); 5140 return err; 5141 } 5142 5143 /* __check_mem_access has made sure "off + size - 1" is within u16. 5144 * reg->umax_value can't be bigger than MAX_PACKET_OFF which is 0xffff, 5145 * otherwise find_good_pkt_pointers would have refused to set range info 5146 * that __check_mem_access would have rejected this pkt access. 5147 * Therefore, "off + reg->umax_value + size - 1" won't overflow u32. 5148 */ 5149 env->prog->aux->max_pkt_offset = 5150 max_t(u32, env->prog->aux->max_pkt_offset, 5151 off + reg->umax_value + size - 1); 5152 5153 return err; 5154 } 5155 5156 /* check access to 'struct bpf_context' fields. Supports fixed offsets only */ 5157 static int check_ctx_access(struct bpf_verifier_env *env, int insn_idx, int off, int size, 5158 enum bpf_access_type t, enum bpf_reg_type *reg_type, 5159 struct btf **btf, u32 *btf_id) 5160 { 5161 struct bpf_insn_access_aux info = { 5162 .reg_type = *reg_type, 5163 .log = &env->log, 5164 }; 5165 5166 if (env->ops->is_valid_access && 5167 env->ops->is_valid_access(off, size, t, env->prog, &info)) { 5168 /* A non zero info.ctx_field_size indicates that this field is a 5169 * candidate for later verifier transformation to load the whole 5170 * field and then apply a mask when accessed with a narrower 5171 * access than actual ctx access size. A zero info.ctx_field_size 5172 * will only allow for whole field access and rejects any other 5173 * type of narrower access. 5174 */ 5175 *reg_type = info.reg_type; 5176 5177 if (base_type(*reg_type) == PTR_TO_BTF_ID) { 5178 *btf = info.btf; 5179 *btf_id = info.btf_id; 5180 } else { 5181 env->insn_aux_data[insn_idx].ctx_field_size = info.ctx_field_size; 5182 } 5183 /* remember the offset of last byte accessed in ctx */ 5184 if (env->prog->aux->max_ctx_offset < off + size) 5185 env->prog->aux->max_ctx_offset = off + size; 5186 return 0; 5187 } 5188 5189 verbose(env, "invalid bpf_context access off=%d size=%d\n", off, size); 5190 return -EACCES; 5191 } 5192 5193 static int check_flow_keys_access(struct bpf_verifier_env *env, int off, 5194 int size) 5195 { 5196 if (size < 0 || off < 0 || 5197 (u64)off + size > sizeof(struct bpf_flow_keys)) { 5198 verbose(env, "invalid access to flow keys off=%d size=%d\n", 5199 off, size); 5200 return -EACCES; 5201 } 5202 return 0; 5203 } 5204 5205 static int check_sock_access(struct bpf_verifier_env *env, int insn_idx, 5206 u32 regno, int off, int size, 5207 enum bpf_access_type t) 5208 { 5209 struct bpf_reg_state *regs = cur_regs(env); 5210 struct bpf_reg_state *reg = ®s[regno]; 5211 struct bpf_insn_access_aux info = {}; 5212 bool valid; 5213 5214 if (reg->smin_value < 0) { 5215 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n", 5216 regno); 5217 return -EACCES; 5218 } 5219 5220 switch (reg->type) { 5221 case PTR_TO_SOCK_COMMON: 5222 valid = bpf_sock_common_is_valid_access(off, size, t, &info); 5223 break; 5224 case PTR_TO_SOCKET: 5225 valid = bpf_sock_is_valid_access(off, size, t, &info); 5226 break; 5227 case PTR_TO_TCP_SOCK: 5228 valid = bpf_tcp_sock_is_valid_access(off, size, t, &info); 5229 break; 5230 case PTR_TO_XDP_SOCK: 5231 valid = bpf_xdp_sock_is_valid_access(off, size, t, &info); 5232 break; 5233 default: 5234 valid = false; 5235 } 5236 5237 5238 if (valid) { 5239 env->insn_aux_data[insn_idx].ctx_field_size = 5240 info.ctx_field_size; 5241 return 0; 5242 } 5243 5244 verbose(env, "R%d invalid %s access off=%d size=%d\n", 5245 regno, reg_type_str(env, reg->type), off, size); 5246 5247 return -EACCES; 5248 } 5249 5250 static bool is_pointer_value(struct bpf_verifier_env *env, int regno) 5251 { 5252 return __is_pointer_value(env->allow_ptr_leaks, reg_state(env, regno)); 5253 } 5254 5255 static bool is_ctx_reg(struct bpf_verifier_env *env, int regno) 5256 { 5257 const struct bpf_reg_state *reg = reg_state(env, regno); 5258 5259 return reg->type == PTR_TO_CTX; 5260 } 5261 5262 static bool is_sk_reg(struct bpf_verifier_env *env, int regno) 5263 { 5264 const struct bpf_reg_state *reg = reg_state(env, regno); 5265 5266 return type_is_sk_pointer(reg->type); 5267 } 5268 5269 static bool is_pkt_reg(struct bpf_verifier_env *env, int regno) 5270 { 5271 const struct bpf_reg_state *reg = reg_state(env, regno); 5272 5273 return type_is_pkt_pointer(reg->type); 5274 } 5275 5276 static bool is_flow_key_reg(struct bpf_verifier_env *env, int regno) 5277 { 5278 const struct bpf_reg_state *reg = reg_state(env, regno); 5279 5280 /* Separate to is_ctx_reg() since we still want to allow BPF_ST here. */ 5281 return reg->type == PTR_TO_FLOW_KEYS; 5282 } 5283 5284 static bool is_trusted_reg(const struct bpf_reg_state *reg) 5285 { 5286 /* A referenced register is always trusted. */ 5287 if (reg->ref_obj_id) 5288 return true; 5289 5290 /* If a register is not referenced, it is trusted if it has the 5291 * MEM_ALLOC or PTR_TRUSTED type modifiers, and no others. Some of the 5292 * other type modifiers may be safe, but we elect to take an opt-in 5293 * approach here as some (e.g. PTR_UNTRUSTED and PTR_MAYBE_NULL) are 5294 * not. 5295 * 5296 * Eventually, we should make PTR_TRUSTED the single source of truth 5297 * for whether a register is trusted. 5298 */ 5299 return type_flag(reg->type) & BPF_REG_TRUSTED_MODIFIERS && 5300 !bpf_type_has_unsafe_modifiers(reg->type); 5301 } 5302 5303 static bool is_rcu_reg(const struct bpf_reg_state *reg) 5304 { 5305 return reg->type & MEM_RCU; 5306 } 5307 5308 static void clear_trusted_flags(enum bpf_type_flag *flag) 5309 { 5310 *flag &= ~(BPF_REG_TRUSTED_MODIFIERS | MEM_RCU); 5311 } 5312 5313 static int check_pkt_ptr_alignment(struct bpf_verifier_env *env, 5314 const struct bpf_reg_state *reg, 5315 int off, int size, bool strict) 5316 { 5317 struct tnum reg_off; 5318 int ip_align; 5319 5320 /* Byte size accesses are always allowed. */ 5321 if (!strict || size == 1) 5322 return 0; 5323 5324 /* For platforms that do not have a Kconfig enabling 5325 * CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS the value of 5326 * NET_IP_ALIGN is universally set to '2'. And on platforms 5327 * that do set CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS, we get 5328 * to this code only in strict mode where we want to emulate 5329 * the NET_IP_ALIGN==2 checking. Therefore use an 5330 * unconditional IP align value of '2'. 5331 */ 5332 ip_align = 2; 5333 5334 reg_off = tnum_add(reg->var_off, tnum_const(ip_align + reg->off + off)); 5335 if (!tnum_is_aligned(reg_off, size)) { 5336 char tn_buf[48]; 5337 5338 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 5339 verbose(env, 5340 "misaligned packet access off %d+%s+%d+%d size %d\n", 5341 ip_align, tn_buf, reg->off, off, size); 5342 return -EACCES; 5343 } 5344 5345 return 0; 5346 } 5347 5348 static int check_generic_ptr_alignment(struct bpf_verifier_env *env, 5349 const struct bpf_reg_state *reg, 5350 const char *pointer_desc, 5351 int off, int size, bool strict) 5352 { 5353 struct tnum reg_off; 5354 5355 /* Byte size accesses are always allowed. */ 5356 if (!strict || size == 1) 5357 return 0; 5358 5359 reg_off = tnum_add(reg->var_off, tnum_const(reg->off + off)); 5360 if (!tnum_is_aligned(reg_off, size)) { 5361 char tn_buf[48]; 5362 5363 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 5364 verbose(env, "misaligned %saccess off %s+%d+%d size %d\n", 5365 pointer_desc, tn_buf, reg->off, off, size); 5366 return -EACCES; 5367 } 5368 5369 return 0; 5370 } 5371 5372 static int check_ptr_alignment(struct bpf_verifier_env *env, 5373 const struct bpf_reg_state *reg, int off, 5374 int size, bool strict_alignment_once) 5375 { 5376 bool strict = env->strict_alignment || strict_alignment_once; 5377 const char *pointer_desc = ""; 5378 5379 switch (reg->type) { 5380 case PTR_TO_PACKET: 5381 case PTR_TO_PACKET_META: 5382 /* Special case, because of NET_IP_ALIGN. Given metadata sits 5383 * right in front, treat it the very same way. 5384 */ 5385 return check_pkt_ptr_alignment(env, reg, off, size, strict); 5386 case PTR_TO_FLOW_KEYS: 5387 pointer_desc = "flow keys "; 5388 break; 5389 case PTR_TO_MAP_KEY: 5390 pointer_desc = "key "; 5391 break; 5392 case PTR_TO_MAP_VALUE: 5393 pointer_desc = "value "; 5394 break; 5395 case PTR_TO_CTX: 5396 pointer_desc = "context "; 5397 break; 5398 case PTR_TO_STACK: 5399 pointer_desc = "stack "; 5400 /* The stack spill tracking logic in check_stack_write_fixed_off() 5401 * and check_stack_read_fixed_off() relies on stack accesses being 5402 * aligned. 5403 */ 5404 strict = true; 5405 break; 5406 case PTR_TO_SOCKET: 5407 pointer_desc = "sock "; 5408 break; 5409 case PTR_TO_SOCK_COMMON: 5410 pointer_desc = "sock_common "; 5411 break; 5412 case PTR_TO_TCP_SOCK: 5413 pointer_desc = "tcp_sock "; 5414 break; 5415 case PTR_TO_XDP_SOCK: 5416 pointer_desc = "xdp_sock "; 5417 break; 5418 default: 5419 break; 5420 } 5421 return check_generic_ptr_alignment(env, reg, pointer_desc, off, size, 5422 strict); 5423 } 5424 5425 static int update_stack_depth(struct bpf_verifier_env *env, 5426 const struct bpf_func_state *func, 5427 int off) 5428 { 5429 u16 stack = env->subprog_info[func->subprogno].stack_depth; 5430 5431 if (stack >= -off) 5432 return 0; 5433 5434 /* update known max for given subprogram */ 5435 env->subprog_info[func->subprogno].stack_depth = -off; 5436 return 0; 5437 } 5438 5439 /* starting from main bpf function walk all instructions of the function 5440 * and recursively walk all callees that given function can call. 5441 * Ignore jump and exit insns. 5442 * Since recursion is prevented by check_cfg() this algorithm 5443 * only needs a local stack of MAX_CALL_FRAMES to remember callsites 5444 */ 5445 static int check_max_stack_depth(struct bpf_verifier_env *env) 5446 { 5447 int depth = 0, frame = 0, idx = 0, i = 0, subprog_end; 5448 struct bpf_subprog_info *subprog = env->subprog_info; 5449 struct bpf_insn *insn = env->prog->insnsi; 5450 bool tail_call_reachable = false; 5451 int ret_insn[MAX_CALL_FRAMES]; 5452 int ret_prog[MAX_CALL_FRAMES]; 5453 int j; 5454 5455 process_func: 5456 /* protect against potential stack overflow that might happen when 5457 * bpf2bpf calls get combined with tailcalls. Limit the caller's stack 5458 * depth for such case down to 256 so that the worst case scenario 5459 * would result in 8k stack size (32 which is tailcall limit * 256 = 5460 * 8k). 5461 * 5462 * To get the idea what might happen, see an example: 5463 * func1 -> sub rsp, 128 5464 * subfunc1 -> sub rsp, 256 5465 * tailcall1 -> add rsp, 256 5466 * func2 -> sub rsp, 192 (total stack size = 128 + 192 = 320) 5467 * subfunc2 -> sub rsp, 64 5468 * subfunc22 -> sub rsp, 128 5469 * tailcall2 -> add rsp, 128 5470 * func3 -> sub rsp, 32 (total stack size 128 + 192 + 64 + 32 = 416) 5471 * 5472 * tailcall will unwind the current stack frame but it will not get rid 5473 * of caller's stack as shown on the example above. 5474 */ 5475 if (idx && subprog[idx].has_tail_call && depth >= 256) { 5476 verbose(env, 5477 "tail_calls are not allowed when call stack of previous frames is %d bytes. Too large\n", 5478 depth); 5479 return -EACCES; 5480 } 5481 /* round up to 32-bytes, since this is granularity 5482 * of interpreter stack size 5483 */ 5484 depth += round_up(max_t(u32, subprog[idx].stack_depth, 1), 32); 5485 if (depth > MAX_BPF_STACK) { 5486 verbose(env, "combined stack size of %d calls is %d. Too large\n", 5487 frame + 1, depth); 5488 return -EACCES; 5489 } 5490 continue_func: 5491 subprog_end = subprog[idx + 1].start; 5492 for (; i < subprog_end; i++) { 5493 int next_insn; 5494 5495 if (!bpf_pseudo_call(insn + i) && !bpf_pseudo_func(insn + i)) 5496 continue; 5497 /* remember insn and function to return to */ 5498 ret_insn[frame] = i + 1; 5499 ret_prog[frame] = idx; 5500 5501 /* find the callee */ 5502 next_insn = i + insn[i].imm + 1; 5503 idx = find_subprog(env, next_insn); 5504 if (idx < 0) { 5505 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n", 5506 next_insn); 5507 return -EFAULT; 5508 } 5509 if (subprog[idx].is_async_cb) { 5510 if (subprog[idx].has_tail_call) { 5511 verbose(env, "verifier bug. subprog has tail_call and async cb\n"); 5512 return -EFAULT; 5513 } 5514 /* async callbacks don't increase bpf prog stack size */ 5515 continue; 5516 } 5517 i = next_insn; 5518 5519 if (subprog[idx].has_tail_call) 5520 tail_call_reachable = true; 5521 5522 frame++; 5523 if (frame >= MAX_CALL_FRAMES) { 5524 verbose(env, "the call stack of %d frames is too deep !\n", 5525 frame); 5526 return -E2BIG; 5527 } 5528 goto process_func; 5529 } 5530 /* if tail call got detected across bpf2bpf calls then mark each of the 5531 * currently present subprog frames as tail call reachable subprogs; 5532 * this info will be utilized by JIT so that we will be preserving the 5533 * tail call counter throughout bpf2bpf calls combined with tailcalls 5534 */ 5535 if (tail_call_reachable) 5536 for (j = 0; j < frame; j++) 5537 subprog[ret_prog[j]].tail_call_reachable = true; 5538 if (subprog[0].tail_call_reachable) 5539 env->prog->aux->tail_call_reachable = true; 5540 5541 /* end of for() loop means the last insn of the 'subprog' 5542 * was reached. Doesn't matter whether it was JA or EXIT 5543 */ 5544 if (frame == 0) 5545 return 0; 5546 depth -= round_up(max_t(u32, subprog[idx].stack_depth, 1), 32); 5547 frame--; 5548 i = ret_insn[frame]; 5549 idx = ret_prog[frame]; 5550 goto continue_func; 5551 } 5552 5553 #ifndef CONFIG_BPF_JIT_ALWAYS_ON 5554 static int get_callee_stack_depth(struct bpf_verifier_env *env, 5555 const struct bpf_insn *insn, int idx) 5556 { 5557 int start = idx + insn->imm + 1, subprog; 5558 5559 subprog = find_subprog(env, start); 5560 if (subprog < 0) { 5561 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n", 5562 start); 5563 return -EFAULT; 5564 } 5565 return env->subprog_info[subprog].stack_depth; 5566 } 5567 #endif 5568 5569 static int __check_buffer_access(struct bpf_verifier_env *env, 5570 const char *buf_info, 5571 const struct bpf_reg_state *reg, 5572 int regno, int off, int size) 5573 { 5574 if (off < 0) { 5575 verbose(env, 5576 "R%d invalid %s buffer access: off=%d, size=%d\n", 5577 regno, buf_info, off, size); 5578 return -EACCES; 5579 } 5580 if (!tnum_is_const(reg->var_off) || reg->var_off.value) { 5581 char tn_buf[48]; 5582 5583 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 5584 verbose(env, 5585 "R%d invalid variable buffer offset: off=%d, var_off=%s\n", 5586 regno, off, tn_buf); 5587 return -EACCES; 5588 } 5589 5590 return 0; 5591 } 5592 5593 static int check_tp_buffer_access(struct bpf_verifier_env *env, 5594 const struct bpf_reg_state *reg, 5595 int regno, int off, int size) 5596 { 5597 int err; 5598 5599 err = __check_buffer_access(env, "tracepoint", reg, regno, off, size); 5600 if (err) 5601 return err; 5602 5603 if (off + size > env->prog->aux->max_tp_access) 5604 env->prog->aux->max_tp_access = off + size; 5605 5606 return 0; 5607 } 5608 5609 static int check_buffer_access(struct bpf_verifier_env *env, 5610 const struct bpf_reg_state *reg, 5611 int regno, int off, int size, 5612 bool zero_size_allowed, 5613 u32 *max_access) 5614 { 5615 const char *buf_info = type_is_rdonly_mem(reg->type) ? "rdonly" : "rdwr"; 5616 int err; 5617 5618 err = __check_buffer_access(env, buf_info, reg, regno, off, size); 5619 if (err) 5620 return err; 5621 5622 if (off + size > *max_access) 5623 *max_access = off + size; 5624 5625 return 0; 5626 } 5627 5628 /* BPF architecture zero extends alu32 ops into 64-bit registesr */ 5629 static void zext_32_to_64(struct bpf_reg_state *reg) 5630 { 5631 reg->var_off = tnum_subreg(reg->var_off); 5632 __reg_assign_32_into_64(reg); 5633 } 5634 5635 /* truncate register to smaller size (in bytes) 5636 * must be called with size < BPF_REG_SIZE 5637 */ 5638 static void coerce_reg_to_size(struct bpf_reg_state *reg, int size) 5639 { 5640 u64 mask; 5641 5642 /* clear high bits in bit representation */ 5643 reg->var_off = tnum_cast(reg->var_off, size); 5644 5645 /* fix arithmetic bounds */ 5646 mask = ((u64)1 << (size * 8)) - 1; 5647 if ((reg->umin_value & ~mask) == (reg->umax_value & ~mask)) { 5648 reg->umin_value &= mask; 5649 reg->umax_value &= mask; 5650 } else { 5651 reg->umin_value = 0; 5652 reg->umax_value = mask; 5653 } 5654 reg->smin_value = reg->umin_value; 5655 reg->smax_value = reg->umax_value; 5656 5657 /* If size is smaller than 32bit register the 32bit register 5658 * values are also truncated so we push 64-bit bounds into 5659 * 32-bit bounds. Above were truncated < 32-bits already. 5660 */ 5661 if (size >= 4) 5662 return; 5663 __reg_combine_64_into_32(reg); 5664 } 5665 5666 static bool bpf_map_is_rdonly(const struct bpf_map *map) 5667 { 5668 /* A map is considered read-only if the following condition are true: 5669 * 5670 * 1) BPF program side cannot change any of the map content. The 5671 * BPF_F_RDONLY_PROG flag is throughout the lifetime of a map 5672 * and was set at map creation time. 5673 * 2) The map value(s) have been initialized from user space by a 5674 * loader and then "frozen", such that no new map update/delete 5675 * operations from syscall side are possible for the rest of 5676 * the map's lifetime from that point onwards. 5677 * 3) Any parallel/pending map update/delete operations from syscall 5678 * side have been completed. Only after that point, it's safe to 5679 * assume that map value(s) are immutable. 5680 */ 5681 return (map->map_flags & BPF_F_RDONLY_PROG) && 5682 READ_ONCE(map->frozen) && 5683 !bpf_map_write_active(map); 5684 } 5685 5686 static int bpf_map_direct_read(struct bpf_map *map, int off, int size, u64 *val) 5687 { 5688 void *ptr; 5689 u64 addr; 5690 int err; 5691 5692 err = map->ops->map_direct_value_addr(map, &addr, off); 5693 if (err) 5694 return err; 5695 ptr = (void *)(long)addr + off; 5696 5697 switch (size) { 5698 case sizeof(u8): 5699 *val = (u64)*(u8 *)ptr; 5700 break; 5701 case sizeof(u16): 5702 *val = (u64)*(u16 *)ptr; 5703 break; 5704 case sizeof(u32): 5705 *val = (u64)*(u32 *)ptr; 5706 break; 5707 case sizeof(u64): 5708 *val = *(u64 *)ptr; 5709 break; 5710 default: 5711 return -EINVAL; 5712 } 5713 return 0; 5714 } 5715 5716 #define BTF_TYPE_SAFE_RCU(__type) __PASTE(__type, __safe_rcu) 5717 #define BTF_TYPE_SAFE_RCU_OR_NULL(__type) __PASTE(__type, __safe_rcu_or_null) 5718 #define BTF_TYPE_SAFE_TRUSTED(__type) __PASTE(__type, __safe_trusted) 5719 5720 /* 5721 * Allow list few fields as RCU trusted or full trusted. 5722 * This logic doesn't allow mix tagging and will be removed once GCC supports 5723 * btf_type_tag. 5724 */ 5725 5726 /* RCU trusted: these fields are trusted in RCU CS and never NULL */ 5727 BTF_TYPE_SAFE_RCU(struct task_struct) { 5728 const cpumask_t *cpus_ptr; 5729 struct css_set __rcu *cgroups; 5730 struct task_struct __rcu *real_parent; 5731 struct task_struct *group_leader; 5732 }; 5733 5734 BTF_TYPE_SAFE_RCU(struct cgroup) { 5735 /* cgrp->kn is always accessible as documented in kernel/cgroup/cgroup.c */ 5736 struct kernfs_node *kn; 5737 }; 5738 5739 BTF_TYPE_SAFE_RCU(struct css_set) { 5740 struct cgroup *dfl_cgrp; 5741 }; 5742 5743 /* RCU trusted: these fields are trusted in RCU CS and can be NULL */ 5744 BTF_TYPE_SAFE_RCU_OR_NULL(struct mm_struct) { 5745 struct file __rcu *exe_file; 5746 }; 5747 5748 /* skb->sk, req->sk are not RCU protected, but we mark them as such 5749 * because bpf prog accessible sockets are SOCK_RCU_FREE. 5750 */ 5751 BTF_TYPE_SAFE_RCU_OR_NULL(struct sk_buff) { 5752 struct sock *sk; 5753 }; 5754 5755 BTF_TYPE_SAFE_RCU_OR_NULL(struct request_sock) { 5756 struct sock *sk; 5757 }; 5758 5759 /* full trusted: these fields are trusted even outside of RCU CS and never NULL */ 5760 BTF_TYPE_SAFE_TRUSTED(struct bpf_iter_meta) { 5761 struct seq_file *seq; 5762 }; 5763 5764 BTF_TYPE_SAFE_TRUSTED(struct bpf_iter__task) { 5765 struct bpf_iter_meta *meta; 5766 struct task_struct *task; 5767 }; 5768 5769 BTF_TYPE_SAFE_TRUSTED(struct linux_binprm) { 5770 struct file *file; 5771 }; 5772 5773 BTF_TYPE_SAFE_TRUSTED(struct file) { 5774 struct inode *f_inode; 5775 }; 5776 5777 BTF_TYPE_SAFE_TRUSTED(struct dentry) { 5778 /* no negative dentry-s in places where bpf can see it */ 5779 struct inode *d_inode; 5780 }; 5781 5782 BTF_TYPE_SAFE_TRUSTED(struct socket) { 5783 struct sock *sk; 5784 }; 5785 5786 static bool type_is_rcu(struct bpf_verifier_env *env, 5787 struct bpf_reg_state *reg, 5788 const char *field_name, u32 btf_id) 5789 { 5790 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct task_struct)); 5791 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct cgroup)); 5792 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct css_set)); 5793 5794 return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_rcu"); 5795 } 5796 5797 static bool type_is_rcu_or_null(struct bpf_verifier_env *env, 5798 struct bpf_reg_state *reg, 5799 const char *field_name, u32 btf_id) 5800 { 5801 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct mm_struct)); 5802 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct sk_buff)); 5803 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct request_sock)); 5804 5805 return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_rcu_or_null"); 5806 } 5807 5808 static bool type_is_trusted(struct bpf_verifier_env *env, 5809 struct bpf_reg_state *reg, 5810 const char *field_name, u32 btf_id) 5811 { 5812 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct bpf_iter_meta)); 5813 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct bpf_iter__task)); 5814 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct linux_binprm)); 5815 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct file)); 5816 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct dentry)); 5817 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct socket)); 5818 5819 return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_trusted"); 5820 } 5821 5822 static int check_ptr_to_btf_access(struct bpf_verifier_env *env, 5823 struct bpf_reg_state *regs, 5824 int regno, int off, int size, 5825 enum bpf_access_type atype, 5826 int value_regno) 5827 { 5828 struct bpf_reg_state *reg = regs + regno; 5829 const struct btf_type *t = btf_type_by_id(reg->btf, reg->btf_id); 5830 const char *tname = btf_name_by_offset(reg->btf, t->name_off); 5831 const char *field_name = NULL; 5832 enum bpf_type_flag flag = 0; 5833 u32 btf_id = 0; 5834 int ret; 5835 5836 if (!env->allow_ptr_leaks) { 5837 verbose(env, 5838 "'struct %s' access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n", 5839 tname); 5840 return -EPERM; 5841 } 5842 if (!env->prog->gpl_compatible && btf_is_kernel(reg->btf)) { 5843 verbose(env, 5844 "Cannot access kernel 'struct %s' from non-GPL compatible program\n", 5845 tname); 5846 return -EINVAL; 5847 } 5848 if (off < 0) { 5849 verbose(env, 5850 "R%d is ptr_%s invalid negative access: off=%d\n", 5851 regno, tname, off); 5852 return -EACCES; 5853 } 5854 if (!tnum_is_const(reg->var_off) || reg->var_off.value) { 5855 char tn_buf[48]; 5856 5857 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 5858 verbose(env, 5859 "R%d is ptr_%s invalid variable offset: off=%d, var_off=%s\n", 5860 regno, tname, off, tn_buf); 5861 return -EACCES; 5862 } 5863 5864 if (reg->type & MEM_USER) { 5865 verbose(env, 5866 "R%d is ptr_%s access user memory: off=%d\n", 5867 regno, tname, off); 5868 return -EACCES; 5869 } 5870 5871 if (reg->type & MEM_PERCPU) { 5872 verbose(env, 5873 "R%d is ptr_%s access percpu memory: off=%d\n", 5874 regno, tname, off); 5875 return -EACCES; 5876 } 5877 5878 if (env->ops->btf_struct_access && !type_is_alloc(reg->type) && atype == BPF_WRITE) { 5879 if (!btf_is_kernel(reg->btf)) { 5880 verbose(env, "verifier internal error: reg->btf must be kernel btf\n"); 5881 return -EFAULT; 5882 } 5883 ret = env->ops->btf_struct_access(&env->log, reg, off, size); 5884 } else { 5885 /* Writes are permitted with default btf_struct_access for 5886 * program allocated objects (which always have ref_obj_id > 0), 5887 * but not for untrusted PTR_TO_BTF_ID | MEM_ALLOC. 5888 */ 5889 if (atype != BPF_READ && reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) { 5890 verbose(env, "only read is supported\n"); 5891 return -EACCES; 5892 } 5893 5894 if (type_is_alloc(reg->type) && !type_is_non_owning_ref(reg->type) && 5895 !reg->ref_obj_id) { 5896 verbose(env, "verifier internal error: ref_obj_id for allocated object must be non-zero\n"); 5897 return -EFAULT; 5898 } 5899 5900 ret = btf_struct_access(&env->log, reg, off, size, atype, &btf_id, &flag, &field_name); 5901 } 5902 5903 if (ret < 0) 5904 return ret; 5905 5906 if (ret != PTR_TO_BTF_ID) { 5907 /* just mark; */ 5908 5909 } else if (type_flag(reg->type) & PTR_UNTRUSTED) { 5910 /* If this is an untrusted pointer, all pointers formed by walking it 5911 * also inherit the untrusted flag. 5912 */ 5913 flag = PTR_UNTRUSTED; 5914 5915 } else if (is_trusted_reg(reg) || is_rcu_reg(reg)) { 5916 /* By default any pointer obtained from walking a trusted pointer is no 5917 * longer trusted, unless the field being accessed has explicitly been 5918 * marked as inheriting its parent's state of trust (either full or RCU). 5919 * For example: 5920 * 'cgroups' pointer is untrusted if task->cgroups dereference 5921 * happened in a sleepable program outside of bpf_rcu_read_lock() 5922 * section. In a non-sleepable program it's trusted while in RCU CS (aka MEM_RCU). 5923 * Note bpf_rcu_read_unlock() converts MEM_RCU pointers to PTR_UNTRUSTED. 5924 * 5925 * A regular RCU-protected pointer with __rcu tag can also be deemed 5926 * trusted if we are in an RCU CS. Such pointer can be NULL. 5927 */ 5928 if (type_is_trusted(env, reg, field_name, btf_id)) { 5929 flag |= PTR_TRUSTED; 5930 } else if (in_rcu_cs(env) && !type_may_be_null(reg->type)) { 5931 if (type_is_rcu(env, reg, field_name, btf_id)) { 5932 /* ignore __rcu tag and mark it MEM_RCU */ 5933 flag |= MEM_RCU; 5934 } else if (flag & MEM_RCU || 5935 type_is_rcu_or_null(env, reg, field_name, btf_id)) { 5936 /* __rcu tagged pointers can be NULL */ 5937 flag |= MEM_RCU | PTR_MAYBE_NULL; 5938 } else if (flag & (MEM_PERCPU | MEM_USER)) { 5939 /* keep as-is */ 5940 } else { 5941 /* walking unknown pointers yields old deprecated PTR_TO_BTF_ID */ 5942 clear_trusted_flags(&flag); 5943 } 5944 } else { 5945 /* 5946 * If not in RCU CS or MEM_RCU pointer can be NULL then 5947 * aggressively mark as untrusted otherwise such 5948 * pointers will be plain PTR_TO_BTF_ID without flags 5949 * and will be allowed to be passed into helpers for 5950 * compat reasons. 5951 */ 5952 flag = PTR_UNTRUSTED; 5953 } 5954 } else { 5955 /* Old compat. Deprecated */ 5956 clear_trusted_flags(&flag); 5957 } 5958 5959 if (atype == BPF_READ && value_regno >= 0) 5960 mark_btf_ld_reg(env, regs, value_regno, ret, reg->btf, btf_id, flag); 5961 5962 return 0; 5963 } 5964 5965 static int check_ptr_to_map_access(struct bpf_verifier_env *env, 5966 struct bpf_reg_state *regs, 5967 int regno, int off, int size, 5968 enum bpf_access_type atype, 5969 int value_regno) 5970 { 5971 struct bpf_reg_state *reg = regs + regno; 5972 struct bpf_map *map = reg->map_ptr; 5973 struct bpf_reg_state map_reg; 5974 enum bpf_type_flag flag = 0; 5975 const struct btf_type *t; 5976 const char *tname; 5977 u32 btf_id; 5978 int ret; 5979 5980 if (!btf_vmlinux) { 5981 verbose(env, "map_ptr access not supported without CONFIG_DEBUG_INFO_BTF\n"); 5982 return -ENOTSUPP; 5983 } 5984 5985 if (!map->ops->map_btf_id || !*map->ops->map_btf_id) { 5986 verbose(env, "map_ptr access not supported for map type %d\n", 5987 map->map_type); 5988 return -ENOTSUPP; 5989 } 5990 5991 t = btf_type_by_id(btf_vmlinux, *map->ops->map_btf_id); 5992 tname = btf_name_by_offset(btf_vmlinux, t->name_off); 5993 5994 if (!env->allow_ptr_leaks) { 5995 verbose(env, 5996 "'struct %s' access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n", 5997 tname); 5998 return -EPERM; 5999 } 6000 6001 if (off < 0) { 6002 verbose(env, "R%d is %s invalid negative access: off=%d\n", 6003 regno, tname, off); 6004 return -EACCES; 6005 } 6006 6007 if (atype != BPF_READ) { 6008 verbose(env, "only read from %s is supported\n", tname); 6009 return -EACCES; 6010 } 6011 6012 /* Simulate access to a PTR_TO_BTF_ID */ 6013 memset(&map_reg, 0, sizeof(map_reg)); 6014 mark_btf_ld_reg(env, &map_reg, 0, PTR_TO_BTF_ID, btf_vmlinux, *map->ops->map_btf_id, 0); 6015 ret = btf_struct_access(&env->log, &map_reg, off, size, atype, &btf_id, &flag, NULL); 6016 if (ret < 0) 6017 return ret; 6018 6019 if (value_regno >= 0) 6020 mark_btf_ld_reg(env, regs, value_regno, ret, btf_vmlinux, btf_id, flag); 6021 6022 return 0; 6023 } 6024 6025 /* Check that the stack access at the given offset is within bounds. The 6026 * maximum valid offset is -1. 6027 * 6028 * The minimum valid offset is -MAX_BPF_STACK for writes, and 6029 * -state->allocated_stack for reads. 6030 */ 6031 static int check_stack_slot_within_bounds(int off, 6032 struct bpf_func_state *state, 6033 enum bpf_access_type t) 6034 { 6035 int min_valid_off; 6036 6037 if (t == BPF_WRITE) 6038 min_valid_off = -MAX_BPF_STACK; 6039 else 6040 min_valid_off = -state->allocated_stack; 6041 6042 if (off < min_valid_off || off > -1) 6043 return -EACCES; 6044 return 0; 6045 } 6046 6047 /* Check that the stack access at 'regno + off' falls within the maximum stack 6048 * bounds. 6049 * 6050 * 'off' includes `regno->offset`, but not its dynamic part (if any). 6051 */ 6052 static int check_stack_access_within_bounds( 6053 struct bpf_verifier_env *env, 6054 int regno, int off, int access_size, 6055 enum bpf_access_src src, enum bpf_access_type type) 6056 { 6057 struct bpf_reg_state *regs = cur_regs(env); 6058 struct bpf_reg_state *reg = regs + regno; 6059 struct bpf_func_state *state = func(env, reg); 6060 int min_off, max_off; 6061 int err; 6062 char *err_extra; 6063 6064 if (src == ACCESS_HELPER) 6065 /* We don't know if helpers are reading or writing (or both). */ 6066 err_extra = " indirect access to"; 6067 else if (type == BPF_READ) 6068 err_extra = " read from"; 6069 else 6070 err_extra = " write to"; 6071 6072 if (tnum_is_const(reg->var_off)) { 6073 min_off = reg->var_off.value + off; 6074 if (access_size > 0) 6075 max_off = min_off + access_size - 1; 6076 else 6077 max_off = min_off; 6078 } else { 6079 if (reg->smax_value >= BPF_MAX_VAR_OFF || 6080 reg->smin_value <= -BPF_MAX_VAR_OFF) { 6081 verbose(env, "invalid unbounded variable-offset%s stack R%d\n", 6082 err_extra, regno); 6083 return -EACCES; 6084 } 6085 min_off = reg->smin_value + off; 6086 if (access_size > 0) 6087 max_off = reg->smax_value + off + access_size - 1; 6088 else 6089 max_off = min_off; 6090 } 6091 6092 err = check_stack_slot_within_bounds(min_off, state, type); 6093 if (!err) 6094 err = check_stack_slot_within_bounds(max_off, state, type); 6095 6096 if (err) { 6097 if (tnum_is_const(reg->var_off)) { 6098 verbose(env, "invalid%s stack R%d off=%d size=%d\n", 6099 err_extra, regno, off, access_size); 6100 } else { 6101 char tn_buf[48]; 6102 6103 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 6104 verbose(env, "invalid variable-offset%s stack R%d var_off=%s size=%d\n", 6105 err_extra, regno, tn_buf, access_size); 6106 } 6107 } 6108 return err; 6109 } 6110 6111 /* check whether memory at (regno + off) is accessible for t = (read | write) 6112 * if t==write, value_regno is a register which value is stored into memory 6113 * if t==read, value_regno is a register which will receive the value from memory 6114 * if t==write && value_regno==-1, some unknown value is stored into memory 6115 * if t==read && value_regno==-1, don't care what we read from memory 6116 */ 6117 static int check_mem_access(struct bpf_verifier_env *env, int insn_idx, u32 regno, 6118 int off, int bpf_size, enum bpf_access_type t, 6119 int value_regno, bool strict_alignment_once) 6120 { 6121 struct bpf_reg_state *regs = cur_regs(env); 6122 struct bpf_reg_state *reg = regs + regno; 6123 struct bpf_func_state *state; 6124 int size, err = 0; 6125 6126 size = bpf_size_to_bytes(bpf_size); 6127 if (size < 0) 6128 return size; 6129 6130 /* alignment checks will add in reg->off themselves */ 6131 err = check_ptr_alignment(env, reg, off, size, strict_alignment_once); 6132 if (err) 6133 return err; 6134 6135 /* for access checks, reg->off is just part of off */ 6136 off += reg->off; 6137 6138 if (reg->type == PTR_TO_MAP_KEY) { 6139 if (t == BPF_WRITE) { 6140 verbose(env, "write to change key R%d not allowed\n", regno); 6141 return -EACCES; 6142 } 6143 6144 err = check_mem_region_access(env, regno, off, size, 6145 reg->map_ptr->key_size, false); 6146 if (err) 6147 return err; 6148 if (value_regno >= 0) 6149 mark_reg_unknown(env, regs, value_regno); 6150 } else if (reg->type == PTR_TO_MAP_VALUE) { 6151 struct btf_field *kptr_field = NULL; 6152 6153 if (t == BPF_WRITE && value_regno >= 0 && 6154 is_pointer_value(env, value_regno)) { 6155 verbose(env, "R%d leaks addr into map\n", value_regno); 6156 return -EACCES; 6157 } 6158 err = check_map_access_type(env, regno, off, size, t); 6159 if (err) 6160 return err; 6161 err = check_map_access(env, regno, off, size, false, ACCESS_DIRECT); 6162 if (err) 6163 return err; 6164 if (tnum_is_const(reg->var_off)) 6165 kptr_field = btf_record_find(reg->map_ptr->record, 6166 off + reg->var_off.value, BPF_KPTR); 6167 if (kptr_field) { 6168 err = check_map_kptr_access(env, regno, value_regno, insn_idx, kptr_field); 6169 } else if (t == BPF_READ && value_regno >= 0) { 6170 struct bpf_map *map = reg->map_ptr; 6171 6172 /* if map is read-only, track its contents as scalars */ 6173 if (tnum_is_const(reg->var_off) && 6174 bpf_map_is_rdonly(map) && 6175 map->ops->map_direct_value_addr) { 6176 int map_off = off + reg->var_off.value; 6177 u64 val = 0; 6178 6179 err = bpf_map_direct_read(map, map_off, size, 6180 &val); 6181 if (err) 6182 return err; 6183 6184 regs[value_regno].type = SCALAR_VALUE; 6185 __mark_reg_known(®s[value_regno], val); 6186 } else { 6187 mark_reg_unknown(env, regs, value_regno); 6188 } 6189 } 6190 } else if (base_type(reg->type) == PTR_TO_MEM) { 6191 bool rdonly_mem = type_is_rdonly_mem(reg->type); 6192 6193 if (type_may_be_null(reg->type)) { 6194 verbose(env, "R%d invalid mem access '%s'\n", regno, 6195 reg_type_str(env, reg->type)); 6196 return -EACCES; 6197 } 6198 6199 if (t == BPF_WRITE && rdonly_mem) { 6200 verbose(env, "R%d cannot write into %s\n", 6201 regno, reg_type_str(env, reg->type)); 6202 return -EACCES; 6203 } 6204 6205 if (t == BPF_WRITE && value_regno >= 0 && 6206 is_pointer_value(env, value_regno)) { 6207 verbose(env, "R%d leaks addr into mem\n", value_regno); 6208 return -EACCES; 6209 } 6210 6211 err = check_mem_region_access(env, regno, off, size, 6212 reg->mem_size, false); 6213 if (!err && value_regno >= 0 && (t == BPF_READ || rdonly_mem)) 6214 mark_reg_unknown(env, regs, value_regno); 6215 } else if (reg->type == PTR_TO_CTX) { 6216 enum bpf_reg_type reg_type = SCALAR_VALUE; 6217 struct btf *btf = NULL; 6218 u32 btf_id = 0; 6219 6220 if (t == BPF_WRITE && value_regno >= 0 && 6221 is_pointer_value(env, value_regno)) { 6222 verbose(env, "R%d leaks addr into ctx\n", value_regno); 6223 return -EACCES; 6224 } 6225 6226 err = check_ptr_off_reg(env, reg, regno); 6227 if (err < 0) 6228 return err; 6229 6230 err = check_ctx_access(env, insn_idx, off, size, t, ®_type, &btf, 6231 &btf_id); 6232 if (err) 6233 verbose_linfo(env, insn_idx, "; "); 6234 if (!err && t == BPF_READ && value_regno >= 0) { 6235 /* ctx access returns either a scalar, or a 6236 * PTR_TO_PACKET[_META,_END]. In the latter 6237 * case, we know the offset is zero. 6238 */ 6239 if (reg_type == SCALAR_VALUE) { 6240 mark_reg_unknown(env, regs, value_regno); 6241 } else { 6242 mark_reg_known_zero(env, regs, 6243 value_regno); 6244 if (type_may_be_null(reg_type)) 6245 regs[value_regno].id = ++env->id_gen; 6246 /* A load of ctx field could have different 6247 * actual load size with the one encoded in the 6248 * insn. When the dst is PTR, it is for sure not 6249 * a sub-register. 6250 */ 6251 regs[value_regno].subreg_def = DEF_NOT_SUBREG; 6252 if (base_type(reg_type) == PTR_TO_BTF_ID) { 6253 regs[value_regno].btf = btf; 6254 regs[value_regno].btf_id = btf_id; 6255 } 6256 } 6257 regs[value_regno].type = reg_type; 6258 } 6259 6260 } else if (reg->type == PTR_TO_STACK) { 6261 /* Basic bounds checks. */ 6262 err = check_stack_access_within_bounds(env, regno, off, size, ACCESS_DIRECT, t); 6263 if (err) 6264 return err; 6265 6266 state = func(env, reg); 6267 err = update_stack_depth(env, state, off); 6268 if (err) 6269 return err; 6270 6271 if (t == BPF_READ) 6272 err = check_stack_read(env, regno, off, size, 6273 value_regno); 6274 else 6275 err = check_stack_write(env, regno, off, size, 6276 value_regno, insn_idx); 6277 } else if (reg_is_pkt_pointer(reg)) { 6278 if (t == BPF_WRITE && !may_access_direct_pkt_data(env, NULL, t)) { 6279 verbose(env, "cannot write into packet\n"); 6280 return -EACCES; 6281 } 6282 if (t == BPF_WRITE && value_regno >= 0 && 6283 is_pointer_value(env, value_regno)) { 6284 verbose(env, "R%d leaks addr into packet\n", 6285 value_regno); 6286 return -EACCES; 6287 } 6288 err = check_packet_access(env, regno, off, size, false); 6289 if (!err && t == BPF_READ && value_regno >= 0) 6290 mark_reg_unknown(env, regs, value_regno); 6291 } else if (reg->type == PTR_TO_FLOW_KEYS) { 6292 if (t == BPF_WRITE && value_regno >= 0 && 6293 is_pointer_value(env, value_regno)) { 6294 verbose(env, "R%d leaks addr into flow keys\n", 6295 value_regno); 6296 return -EACCES; 6297 } 6298 6299 err = check_flow_keys_access(env, off, size); 6300 if (!err && t == BPF_READ && value_regno >= 0) 6301 mark_reg_unknown(env, regs, value_regno); 6302 } else if (type_is_sk_pointer(reg->type)) { 6303 if (t == BPF_WRITE) { 6304 verbose(env, "R%d cannot write into %s\n", 6305 regno, reg_type_str(env, reg->type)); 6306 return -EACCES; 6307 } 6308 err = check_sock_access(env, insn_idx, regno, off, size, t); 6309 if (!err && value_regno >= 0) 6310 mark_reg_unknown(env, regs, value_regno); 6311 } else if (reg->type == PTR_TO_TP_BUFFER) { 6312 err = check_tp_buffer_access(env, reg, regno, off, size); 6313 if (!err && t == BPF_READ && value_regno >= 0) 6314 mark_reg_unknown(env, regs, value_regno); 6315 } else if (base_type(reg->type) == PTR_TO_BTF_ID && 6316 !type_may_be_null(reg->type)) { 6317 err = check_ptr_to_btf_access(env, regs, regno, off, size, t, 6318 value_regno); 6319 } else if (reg->type == CONST_PTR_TO_MAP) { 6320 err = check_ptr_to_map_access(env, regs, regno, off, size, t, 6321 value_regno); 6322 } else if (base_type(reg->type) == PTR_TO_BUF) { 6323 bool rdonly_mem = type_is_rdonly_mem(reg->type); 6324 u32 *max_access; 6325 6326 if (rdonly_mem) { 6327 if (t == BPF_WRITE) { 6328 verbose(env, "R%d cannot write into %s\n", 6329 regno, reg_type_str(env, reg->type)); 6330 return -EACCES; 6331 } 6332 max_access = &env->prog->aux->max_rdonly_access; 6333 } else { 6334 max_access = &env->prog->aux->max_rdwr_access; 6335 } 6336 6337 err = check_buffer_access(env, reg, regno, off, size, false, 6338 max_access); 6339 6340 if (!err && value_regno >= 0 && (rdonly_mem || t == BPF_READ)) 6341 mark_reg_unknown(env, regs, value_regno); 6342 } else { 6343 verbose(env, "R%d invalid mem access '%s'\n", regno, 6344 reg_type_str(env, reg->type)); 6345 return -EACCES; 6346 } 6347 6348 if (!err && size < BPF_REG_SIZE && value_regno >= 0 && t == BPF_READ && 6349 regs[value_regno].type == SCALAR_VALUE) { 6350 /* b/h/w load zero-extends, mark upper bits as known 0 */ 6351 coerce_reg_to_size(®s[value_regno], size); 6352 } 6353 return err; 6354 } 6355 6356 static int check_atomic(struct bpf_verifier_env *env, int insn_idx, struct bpf_insn *insn) 6357 { 6358 int load_reg; 6359 int err; 6360 6361 switch (insn->imm) { 6362 case BPF_ADD: 6363 case BPF_ADD | BPF_FETCH: 6364 case BPF_AND: 6365 case BPF_AND | BPF_FETCH: 6366 case BPF_OR: 6367 case BPF_OR | BPF_FETCH: 6368 case BPF_XOR: 6369 case BPF_XOR | BPF_FETCH: 6370 case BPF_XCHG: 6371 case BPF_CMPXCHG: 6372 break; 6373 default: 6374 verbose(env, "BPF_ATOMIC uses invalid atomic opcode %02x\n", insn->imm); 6375 return -EINVAL; 6376 } 6377 6378 if (BPF_SIZE(insn->code) != BPF_W && BPF_SIZE(insn->code) != BPF_DW) { 6379 verbose(env, "invalid atomic operand size\n"); 6380 return -EINVAL; 6381 } 6382 6383 /* check src1 operand */ 6384 err = check_reg_arg(env, insn->src_reg, SRC_OP); 6385 if (err) 6386 return err; 6387 6388 /* check src2 operand */ 6389 err = check_reg_arg(env, insn->dst_reg, SRC_OP); 6390 if (err) 6391 return err; 6392 6393 if (insn->imm == BPF_CMPXCHG) { 6394 /* Check comparison of R0 with memory location */ 6395 const u32 aux_reg = BPF_REG_0; 6396 6397 err = check_reg_arg(env, aux_reg, SRC_OP); 6398 if (err) 6399 return err; 6400 6401 if (is_pointer_value(env, aux_reg)) { 6402 verbose(env, "R%d leaks addr into mem\n", aux_reg); 6403 return -EACCES; 6404 } 6405 } 6406 6407 if (is_pointer_value(env, insn->src_reg)) { 6408 verbose(env, "R%d leaks addr into mem\n", insn->src_reg); 6409 return -EACCES; 6410 } 6411 6412 if (is_ctx_reg(env, insn->dst_reg) || 6413 is_pkt_reg(env, insn->dst_reg) || 6414 is_flow_key_reg(env, insn->dst_reg) || 6415 is_sk_reg(env, insn->dst_reg)) { 6416 verbose(env, "BPF_ATOMIC stores into R%d %s is not allowed\n", 6417 insn->dst_reg, 6418 reg_type_str(env, reg_state(env, insn->dst_reg)->type)); 6419 return -EACCES; 6420 } 6421 6422 if (insn->imm & BPF_FETCH) { 6423 if (insn->imm == BPF_CMPXCHG) 6424 load_reg = BPF_REG_0; 6425 else 6426 load_reg = insn->src_reg; 6427 6428 /* check and record load of old value */ 6429 err = check_reg_arg(env, load_reg, DST_OP); 6430 if (err) 6431 return err; 6432 } else { 6433 /* This instruction accesses a memory location but doesn't 6434 * actually load it into a register. 6435 */ 6436 load_reg = -1; 6437 } 6438 6439 /* Check whether we can read the memory, with second call for fetch 6440 * case to simulate the register fill. 6441 */ 6442 err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off, 6443 BPF_SIZE(insn->code), BPF_READ, -1, true); 6444 if (!err && load_reg >= 0) 6445 err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off, 6446 BPF_SIZE(insn->code), BPF_READ, load_reg, 6447 true); 6448 if (err) 6449 return err; 6450 6451 /* Check whether we can write into the same memory. */ 6452 err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off, 6453 BPF_SIZE(insn->code), BPF_WRITE, -1, true); 6454 if (err) 6455 return err; 6456 6457 return 0; 6458 } 6459 6460 /* When register 'regno' is used to read the stack (either directly or through 6461 * a helper function) make sure that it's within stack boundary and, depending 6462 * on the access type, that all elements of the stack are initialized. 6463 * 6464 * 'off' includes 'regno->off', but not its dynamic part (if any). 6465 * 6466 * All registers that have been spilled on the stack in the slots within the 6467 * read offsets are marked as read. 6468 */ 6469 static int check_stack_range_initialized( 6470 struct bpf_verifier_env *env, int regno, int off, 6471 int access_size, bool zero_size_allowed, 6472 enum bpf_access_src type, struct bpf_call_arg_meta *meta) 6473 { 6474 struct bpf_reg_state *reg = reg_state(env, regno); 6475 struct bpf_func_state *state = func(env, reg); 6476 int err, min_off, max_off, i, j, slot, spi; 6477 char *err_extra = type == ACCESS_HELPER ? " indirect" : ""; 6478 enum bpf_access_type bounds_check_type; 6479 /* Some accesses can write anything into the stack, others are 6480 * read-only. 6481 */ 6482 bool clobber = false; 6483 6484 if (access_size == 0 && !zero_size_allowed) { 6485 verbose(env, "invalid zero-sized read\n"); 6486 return -EACCES; 6487 } 6488 6489 if (type == ACCESS_HELPER) { 6490 /* The bounds checks for writes are more permissive than for 6491 * reads. However, if raw_mode is not set, we'll do extra 6492 * checks below. 6493 */ 6494 bounds_check_type = BPF_WRITE; 6495 clobber = true; 6496 } else { 6497 bounds_check_type = BPF_READ; 6498 } 6499 err = check_stack_access_within_bounds(env, regno, off, access_size, 6500 type, bounds_check_type); 6501 if (err) 6502 return err; 6503 6504 6505 if (tnum_is_const(reg->var_off)) { 6506 min_off = max_off = reg->var_off.value + off; 6507 } else { 6508 /* Variable offset is prohibited for unprivileged mode for 6509 * simplicity since it requires corresponding support in 6510 * Spectre masking for stack ALU. 6511 * See also retrieve_ptr_limit(). 6512 */ 6513 if (!env->bypass_spec_v1) { 6514 char tn_buf[48]; 6515 6516 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 6517 verbose(env, "R%d%s variable offset stack access prohibited for !root, var_off=%s\n", 6518 regno, err_extra, tn_buf); 6519 return -EACCES; 6520 } 6521 /* Only initialized buffer on stack is allowed to be accessed 6522 * with variable offset. With uninitialized buffer it's hard to 6523 * guarantee that whole memory is marked as initialized on 6524 * helper return since specific bounds are unknown what may 6525 * cause uninitialized stack leaking. 6526 */ 6527 if (meta && meta->raw_mode) 6528 meta = NULL; 6529 6530 min_off = reg->smin_value + off; 6531 max_off = reg->smax_value + off; 6532 } 6533 6534 if (meta && meta->raw_mode) { 6535 /* Ensure we won't be overwriting dynptrs when simulating byte 6536 * by byte access in check_helper_call using meta.access_size. 6537 * This would be a problem if we have a helper in the future 6538 * which takes: 6539 * 6540 * helper(uninit_mem, len, dynptr) 6541 * 6542 * Now, uninint_mem may overlap with dynptr pointer. Hence, it 6543 * may end up writing to dynptr itself when touching memory from 6544 * arg 1. This can be relaxed on a case by case basis for known 6545 * safe cases, but reject due to the possibilitiy of aliasing by 6546 * default. 6547 */ 6548 for (i = min_off; i < max_off + access_size; i++) { 6549 int stack_off = -i - 1; 6550 6551 spi = __get_spi(i); 6552 /* raw_mode may write past allocated_stack */ 6553 if (state->allocated_stack <= stack_off) 6554 continue; 6555 if (state->stack[spi].slot_type[stack_off % BPF_REG_SIZE] == STACK_DYNPTR) { 6556 verbose(env, "potential write to dynptr at off=%d disallowed\n", i); 6557 return -EACCES; 6558 } 6559 } 6560 meta->access_size = access_size; 6561 meta->regno = regno; 6562 return 0; 6563 } 6564 6565 for (i = min_off; i < max_off + access_size; i++) { 6566 u8 *stype; 6567 6568 slot = -i - 1; 6569 spi = slot / BPF_REG_SIZE; 6570 if (state->allocated_stack <= slot) 6571 goto err; 6572 stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE]; 6573 if (*stype == STACK_MISC) 6574 goto mark; 6575 if ((*stype == STACK_ZERO) || 6576 (*stype == STACK_INVALID && env->allow_uninit_stack)) { 6577 if (clobber) { 6578 /* helper can write anything into the stack */ 6579 *stype = STACK_MISC; 6580 } 6581 goto mark; 6582 } 6583 6584 if (is_spilled_reg(&state->stack[spi]) && 6585 (state->stack[spi].spilled_ptr.type == SCALAR_VALUE || 6586 env->allow_ptr_leaks)) { 6587 if (clobber) { 6588 __mark_reg_unknown(env, &state->stack[spi].spilled_ptr); 6589 for (j = 0; j < BPF_REG_SIZE; j++) 6590 scrub_spilled_slot(&state->stack[spi].slot_type[j]); 6591 } 6592 goto mark; 6593 } 6594 6595 err: 6596 if (tnum_is_const(reg->var_off)) { 6597 verbose(env, "invalid%s read from stack R%d off %d+%d size %d\n", 6598 err_extra, regno, min_off, i - min_off, access_size); 6599 } else { 6600 char tn_buf[48]; 6601 6602 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 6603 verbose(env, "invalid%s read from stack R%d var_off %s+%d size %d\n", 6604 err_extra, regno, tn_buf, i - min_off, access_size); 6605 } 6606 return -EACCES; 6607 mark: 6608 /* reading any byte out of 8-byte 'spill_slot' will cause 6609 * the whole slot to be marked as 'read' 6610 */ 6611 mark_reg_read(env, &state->stack[spi].spilled_ptr, 6612 state->stack[spi].spilled_ptr.parent, 6613 REG_LIVE_READ64); 6614 /* We do not set REG_LIVE_WRITTEN for stack slot, as we can not 6615 * be sure that whether stack slot is written to or not. Hence, 6616 * we must still conservatively propagate reads upwards even if 6617 * helper may write to the entire memory range. 6618 */ 6619 } 6620 return update_stack_depth(env, state, min_off); 6621 } 6622 6623 static int check_helper_mem_access(struct bpf_verifier_env *env, int regno, 6624 int access_size, bool zero_size_allowed, 6625 struct bpf_call_arg_meta *meta) 6626 { 6627 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno]; 6628 u32 *max_access; 6629 6630 switch (base_type(reg->type)) { 6631 case PTR_TO_PACKET: 6632 case PTR_TO_PACKET_META: 6633 return check_packet_access(env, regno, reg->off, access_size, 6634 zero_size_allowed); 6635 case PTR_TO_MAP_KEY: 6636 if (meta && meta->raw_mode) { 6637 verbose(env, "R%d cannot write into %s\n", regno, 6638 reg_type_str(env, reg->type)); 6639 return -EACCES; 6640 } 6641 return check_mem_region_access(env, regno, reg->off, access_size, 6642 reg->map_ptr->key_size, false); 6643 case PTR_TO_MAP_VALUE: 6644 if (check_map_access_type(env, regno, reg->off, access_size, 6645 meta && meta->raw_mode ? BPF_WRITE : 6646 BPF_READ)) 6647 return -EACCES; 6648 return check_map_access(env, regno, reg->off, access_size, 6649 zero_size_allowed, ACCESS_HELPER); 6650 case PTR_TO_MEM: 6651 if (type_is_rdonly_mem(reg->type)) { 6652 if (meta && meta->raw_mode) { 6653 verbose(env, "R%d cannot write into %s\n", regno, 6654 reg_type_str(env, reg->type)); 6655 return -EACCES; 6656 } 6657 } 6658 return check_mem_region_access(env, regno, reg->off, 6659 access_size, reg->mem_size, 6660 zero_size_allowed); 6661 case PTR_TO_BUF: 6662 if (type_is_rdonly_mem(reg->type)) { 6663 if (meta && meta->raw_mode) { 6664 verbose(env, "R%d cannot write into %s\n", regno, 6665 reg_type_str(env, reg->type)); 6666 return -EACCES; 6667 } 6668 6669 max_access = &env->prog->aux->max_rdonly_access; 6670 } else { 6671 max_access = &env->prog->aux->max_rdwr_access; 6672 } 6673 return check_buffer_access(env, reg, regno, reg->off, 6674 access_size, zero_size_allowed, 6675 max_access); 6676 case PTR_TO_STACK: 6677 return check_stack_range_initialized( 6678 env, 6679 regno, reg->off, access_size, 6680 zero_size_allowed, ACCESS_HELPER, meta); 6681 case PTR_TO_BTF_ID: 6682 return check_ptr_to_btf_access(env, regs, regno, reg->off, 6683 access_size, BPF_READ, -1); 6684 case PTR_TO_CTX: 6685 /* in case the function doesn't know how to access the context, 6686 * (because we are in a program of type SYSCALL for example), we 6687 * can not statically check its size. 6688 * Dynamically check it now. 6689 */ 6690 if (!env->ops->convert_ctx_access) { 6691 enum bpf_access_type atype = meta && meta->raw_mode ? BPF_WRITE : BPF_READ; 6692 int offset = access_size - 1; 6693 6694 /* Allow zero-byte read from PTR_TO_CTX */ 6695 if (access_size == 0) 6696 return zero_size_allowed ? 0 : -EACCES; 6697 6698 return check_mem_access(env, env->insn_idx, regno, offset, BPF_B, 6699 atype, -1, false); 6700 } 6701 6702 fallthrough; 6703 default: /* scalar_value or invalid ptr */ 6704 /* Allow zero-byte read from NULL, regardless of pointer type */ 6705 if (zero_size_allowed && access_size == 0 && 6706 register_is_null(reg)) 6707 return 0; 6708 6709 verbose(env, "R%d type=%s ", regno, 6710 reg_type_str(env, reg->type)); 6711 verbose(env, "expected=%s\n", reg_type_str(env, PTR_TO_STACK)); 6712 return -EACCES; 6713 } 6714 } 6715 6716 static int check_mem_size_reg(struct bpf_verifier_env *env, 6717 struct bpf_reg_state *reg, u32 regno, 6718 bool zero_size_allowed, 6719 struct bpf_call_arg_meta *meta) 6720 { 6721 int err; 6722 6723 /* This is used to refine r0 return value bounds for helpers 6724 * that enforce this value as an upper bound on return values. 6725 * See do_refine_retval_range() for helpers that can refine 6726 * the return value. C type of helper is u32 so we pull register 6727 * bound from umax_value however, if negative verifier errors 6728 * out. Only upper bounds can be learned because retval is an 6729 * int type and negative retvals are allowed. 6730 */ 6731 meta->msize_max_value = reg->umax_value; 6732 6733 /* The register is SCALAR_VALUE; the access check 6734 * happens using its boundaries. 6735 */ 6736 if (!tnum_is_const(reg->var_off)) 6737 /* For unprivileged variable accesses, disable raw 6738 * mode so that the program is required to 6739 * initialize all the memory that the helper could 6740 * just partially fill up. 6741 */ 6742 meta = NULL; 6743 6744 if (reg->smin_value < 0) { 6745 verbose(env, "R%d min value is negative, either use unsigned or 'var &= const'\n", 6746 regno); 6747 return -EACCES; 6748 } 6749 6750 if (reg->umin_value == 0) { 6751 err = check_helper_mem_access(env, regno - 1, 0, 6752 zero_size_allowed, 6753 meta); 6754 if (err) 6755 return err; 6756 } 6757 6758 if (reg->umax_value >= BPF_MAX_VAR_SIZ) { 6759 verbose(env, "R%d unbounded memory access, use 'var &= const' or 'if (var < const)'\n", 6760 regno); 6761 return -EACCES; 6762 } 6763 err = check_helper_mem_access(env, regno - 1, 6764 reg->umax_value, 6765 zero_size_allowed, meta); 6766 if (!err) 6767 err = mark_chain_precision(env, regno); 6768 return err; 6769 } 6770 6771 int check_mem_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg, 6772 u32 regno, u32 mem_size) 6773 { 6774 bool may_be_null = type_may_be_null(reg->type); 6775 struct bpf_reg_state saved_reg; 6776 struct bpf_call_arg_meta meta; 6777 int err; 6778 6779 if (register_is_null(reg)) 6780 return 0; 6781 6782 memset(&meta, 0, sizeof(meta)); 6783 /* Assuming that the register contains a value check if the memory 6784 * access is safe. Temporarily save and restore the register's state as 6785 * the conversion shouldn't be visible to a caller. 6786 */ 6787 if (may_be_null) { 6788 saved_reg = *reg; 6789 mark_ptr_not_null_reg(reg); 6790 } 6791 6792 err = check_helper_mem_access(env, regno, mem_size, true, &meta); 6793 /* Check access for BPF_WRITE */ 6794 meta.raw_mode = true; 6795 err = err ?: check_helper_mem_access(env, regno, mem_size, true, &meta); 6796 6797 if (may_be_null) 6798 *reg = saved_reg; 6799 6800 return err; 6801 } 6802 6803 static int check_kfunc_mem_size_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg, 6804 u32 regno) 6805 { 6806 struct bpf_reg_state *mem_reg = &cur_regs(env)[regno - 1]; 6807 bool may_be_null = type_may_be_null(mem_reg->type); 6808 struct bpf_reg_state saved_reg; 6809 struct bpf_call_arg_meta meta; 6810 int err; 6811 6812 WARN_ON_ONCE(regno < BPF_REG_2 || regno > BPF_REG_5); 6813 6814 memset(&meta, 0, sizeof(meta)); 6815 6816 if (may_be_null) { 6817 saved_reg = *mem_reg; 6818 mark_ptr_not_null_reg(mem_reg); 6819 } 6820 6821 err = check_mem_size_reg(env, reg, regno, true, &meta); 6822 /* Check access for BPF_WRITE */ 6823 meta.raw_mode = true; 6824 err = err ?: check_mem_size_reg(env, reg, regno, true, &meta); 6825 6826 if (may_be_null) 6827 *mem_reg = saved_reg; 6828 return err; 6829 } 6830 6831 /* Implementation details: 6832 * bpf_map_lookup returns PTR_TO_MAP_VALUE_OR_NULL. 6833 * bpf_obj_new returns PTR_TO_BTF_ID | MEM_ALLOC | PTR_MAYBE_NULL. 6834 * Two bpf_map_lookups (even with the same key) will have different reg->id. 6835 * Two separate bpf_obj_new will also have different reg->id. 6836 * For traditional PTR_TO_MAP_VALUE or PTR_TO_BTF_ID | MEM_ALLOC, the verifier 6837 * clears reg->id after value_or_null->value transition, since the verifier only 6838 * cares about the range of access to valid map value pointer and doesn't care 6839 * about actual address of the map element. 6840 * For maps with 'struct bpf_spin_lock' inside map value the verifier keeps 6841 * reg->id > 0 after value_or_null->value transition. By doing so 6842 * two bpf_map_lookups will be considered two different pointers that 6843 * point to different bpf_spin_locks. Likewise for pointers to allocated objects 6844 * returned from bpf_obj_new. 6845 * The verifier allows taking only one bpf_spin_lock at a time to avoid 6846 * dead-locks. 6847 * Since only one bpf_spin_lock is allowed the checks are simpler than 6848 * reg_is_refcounted() logic. The verifier needs to remember only 6849 * one spin_lock instead of array of acquired_refs. 6850 * cur_state->active_lock remembers which map value element or allocated 6851 * object got locked and clears it after bpf_spin_unlock. 6852 */ 6853 static int process_spin_lock(struct bpf_verifier_env *env, int regno, 6854 bool is_lock) 6855 { 6856 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno]; 6857 struct bpf_verifier_state *cur = env->cur_state; 6858 bool is_const = tnum_is_const(reg->var_off); 6859 u64 val = reg->var_off.value; 6860 struct bpf_map *map = NULL; 6861 struct btf *btf = NULL; 6862 struct btf_record *rec; 6863 6864 if (!is_const) { 6865 verbose(env, 6866 "R%d doesn't have constant offset. bpf_spin_lock has to be at the constant offset\n", 6867 regno); 6868 return -EINVAL; 6869 } 6870 if (reg->type == PTR_TO_MAP_VALUE) { 6871 map = reg->map_ptr; 6872 if (!map->btf) { 6873 verbose(env, 6874 "map '%s' has to have BTF in order to use bpf_spin_lock\n", 6875 map->name); 6876 return -EINVAL; 6877 } 6878 } else { 6879 btf = reg->btf; 6880 } 6881 6882 rec = reg_btf_record(reg); 6883 if (!btf_record_has_field(rec, BPF_SPIN_LOCK)) { 6884 verbose(env, "%s '%s' has no valid bpf_spin_lock\n", map ? "map" : "local", 6885 map ? map->name : "kptr"); 6886 return -EINVAL; 6887 } 6888 if (rec->spin_lock_off != val + reg->off) { 6889 verbose(env, "off %lld doesn't point to 'struct bpf_spin_lock' that is at %d\n", 6890 val + reg->off, rec->spin_lock_off); 6891 return -EINVAL; 6892 } 6893 if (is_lock) { 6894 if (cur->active_lock.ptr) { 6895 verbose(env, 6896 "Locking two bpf_spin_locks are not allowed\n"); 6897 return -EINVAL; 6898 } 6899 if (map) 6900 cur->active_lock.ptr = map; 6901 else 6902 cur->active_lock.ptr = btf; 6903 cur->active_lock.id = reg->id; 6904 } else { 6905 void *ptr; 6906 6907 if (map) 6908 ptr = map; 6909 else 6910 ptr = btf; 6911 6912 if (!cur->active_lock.ptr) { 6913 verbose(env, "bpf_spin_unlock without taking a lock\n"); 6914 return -EINVAL; 6915 } 6916 if (cur->active_lock.ptr != ptr || 6917 cur->active_lock.id != reg->id) { 6918 verbose(env, "bpf_spin_unlock of different lock\n"); 6919 return -EINVAL; 6920 } 6921 6922 invalidate_non_owning_refs(env); 6923 6924 cur->active_lock.ptr = NULL; 6925 cur->active_lock.id = 0; 6926 } 6927 return 0; 6928 } 6929 6930 static int process_timer_func(struct bpf_verifier_env *env, int regno, 6931 struct bpf_call_arg_meta *meta) 6932 { 6933 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno]; 6934 bool is_const = tnum_is_const(reg->var_off); 6935 struct bpf_map *map = reg->map_ptr; 6936 u64 val = reg->var_off.value; 6937 6938 if (!is_const) { 6939 verbose(env, 6940 "R%d doesn't have constant offset. bpf_timer has to be at the constant offset\n", 6941 regno); 6942 return -EINVAL; 6943 } 6944 if (!map->btf) { 6945 verbose(env, "map '%s' has to have BTF in order to use bpf_timer\n", 6946 map->name); 6947 return -EINVAL; 6948 } 6949 if (!btf_record_has_field(map->record, BPF_TIMER)) { 6950 verbose(env, "map '%s' has no valid bpf_timer\n", map->name); 6951 return -EINVAL; 6952 } 6953 if (map->record->timer_off != val + reg->off) { 6954 verbose(env, "off %lld doesn't point to 'struct bpf_timer' that is at %d\n", 6955 val + reg->off, map->record->timer_off); 6956 return -EINVAL; 6957 } 6958 if (meta->map_ptr) { 6959 verbose(env, "verifier bug. Two map pointers in a timer helper\n"); 6960 return -EFAULT; 6961 } 6962 meta->map_uid = reg->map_uid; 6963 meta->map_ptr = map; 6964 return 0; 6965 } 6966 6967 static int process_kptr_func(struct bpf_verifier_env *env, int regno, 6968 struct bpf_call_arg_meta *meta) 6969 { 6970 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno]; 6971 struct bpf_map *map_ptr = reg->map_ptr; 6972 struct btf_field *kptr_field; 6973 u32 kptr_off; 6974 6975 if (!tnum_is_const(reg->var_off)) { 6976 verbose(env, 6977 "R%d doesn't have constant offset. kptr has to be at the constant offset\n", 6978 regno); 6979 return -EINVAL; 6980 } 6981 if (!map_ptr->btf) { 6982 verbose(env, "map '%s' has to have BTF in order to use bpf_kptr_xchg\n", 6983 map_ptr->name); 6984 return -EINVAL; 6985 } 6986 if (!btf_record_has_field(map_ptr->record, BPF_KPTR)) { 6987 verbose(env, "map '%s' has no valid kptr\n", map_ptr->name); 6988 return -EINVAL; 6989 } 6990 6991 meta->map_ptr = map_ptr; 6992 kptr_off = reg->off + reg->var_off.value; 6993 kptr_field = btf_record_find(map_ptr->record, kptr_off, BPF_KPTR); 6994 if (!kptr_field) { 6995 verbose(env, "off=%d doesn't point to kptr\n", kptr_off); 6996 return -EACCES; 6997 } 6998 if (kptr_field->type != BPF_KPTR_REF) { 6999 verbose(env, "off=%d kptr isn't referenced kptr\n", kptr_off); 7000 return -EACCES; 7001 } 7002 meta->kptr_field = kptr_field; 7003 return 0; 7004 } 7005 7006 /* There are two register types representing a bpf_dynptr, one is PTR_TO_STACK 7007 * which points to a stack slot, and the other is CONST_PTR_TO_DYNPTR. 7008 * 7009 * In both cases we deal with the first 8 bytes, but need to mark the next 8 7010 * bytes as STACK_DYNPTR in case of PTR_TO_STACK. In case of 7011 * CONST_PTR_TO_DYNPTR, we are guaranteed to get the beginning of the object. 7012 * 7013 * Mutability of bpf_dynptr is at two levels, one is at the level of struct 7014 * bpf_dynptr itself, i.e. whether the helper is receiving a pointer to struct 7015 * bpf_dynptr or pointer to const struct bpf_dynptr. In the former case, it can 7016 * mutate the view of the dynptr and also possibly destroy it. In the latter 7017 * case, it cannot mutate the bpf_dynptr itself but it can still mutate the 7018 * memory that dynptr points to. 7019 * 7020 * The verifier will keep track both levels of mutation (bpf_dynptr's in 7021 * reg->type and the memory's in reg->dynptr.type), but there is no support for 7022 * readonly dynptr view yet, hence only the first case is tracked and checked. 7023 * 7024 * This is consistent with how C applies the const modifier to a struct object, 7025 * where the pointer itself inside bpf_dynptr becomes const but not what it 7026 * points to. 7027 * 7028 * Helpers which do not mutate the bpf_dynptr set MEM_RDONLY in their argument 7029 * type, and declare it as 'const struct bpf_dynptr *' in their prototype. 7030 */ 7031 static int process_dynptr_func(struct bpf_verifier_env *env, int regno, int insn_idx, 7032 enum bpf_arg_type arg_type, int clone_ref_obj_id) 7033 { 7034 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno]; 7035 int err; 7036 7037 /* MEM_UNINIT and MEM_RDONLY are exclusive, when applied to an 7038 * ARG_PTR_TO_DYNPTR (or ARG_PTR_TO_DYNPTR | DYNPTR_TYPE_*): 7039 */ 7040 if ((arg_type & (MEM_UNINIT | MEM_RDONLY)) == (MEM_UNINIT | MEM_RDONLY)) { 7041 verbose(env, "verifier internal error: misconfigured dynptr helper type flags\n"); 7042 return -EFAULT; 7043 } 7044 7045 /* MEM_UNINIT - Points to memory that is an appropriate candidate for 7046 * constructing a mutable bpf_dynptr object. 7047 * 7048 * Currently, this is only possible with PTR_TO_STACK 7049 * pointing to a region of at least 16 bytes which doesn't 7050 * contain an existing bpf_dynptr. 7051 * 7052 * MEM_RDONLY - Points to a initialized bpf_dynptr that will not be 7053 * mutated or destroyed. However, the memory it points to 7054 * may be mutated. 7055 * 7056 * None - Points to a initialized dynptr that can be mutated and 7057 * destroyed, including mutation of the memory it points 7058 * to. 7059 */ 7060 if (arg_type & MEM_UNINIT) { 7061 int i; 7062 7063 if (!is_dynptr_reg_valid_uninit(env, reg)) { 7064 verbose(env, "Dynptr has to be an uninitialized dynptr\n"); 7065 return -EINVAL; 7066 } 7067 7068 /* we write BPF_DW bits (8 bytes) at a time */ 7069 for (i = 0; i < BPF_DYNPTR_SIZE; i += 8) { 7070 err = check_mem_access(env, insn_idx, regno, 7071 i, BPF_DW, BPF_WRITE, -1, false); 7072 if (err) 7073 return err; 7074 } 7075 7076 err = mark_stack_slots_dynptr(env, reg, arg_type, insn_idx, clone_ref_obj_id); 7077 } else /* MEM_RDONLY and None case from above */ { 7078 /* For the reg->type == PTR_TO_STACK case, bpf_dynptr is never const */ 7079 if (reg->type == CONST_PTR_TO_DYNPTR && !(arg_type & MEM_RDONLY)) { 7080 verbose(env, "cannot pass pointer to const bpf_dynptr, the helper mutates it\n"); 7081 return -EINVAL; 7082 } 7083 7084 if (!is_dynptr_reg_valid_init(env, reg)) { 7085 verbose(env, 7086 "Expected an initialized dynptr as arg #%d\n", 7087 regno); 7088 return -EINVAL; 7089 } 7090 7091 /* Fold modifiers (in this case, MEM_RDONLY) when checking expected type */ 7092 if (!is_dynptr_type_expected(env, reg, arg_type & ~MEM_RDONLY)) { 7093 verbose(env, 7094 "Expected a dynptr of type %s as arg #%d\n", 7095 dynptr_type_str(arg_to_dynptr_type(arg_type)), regno); 7096 return -EINVAL; 7097 } 7098 7099 err = mark_dynptr_read(env, reg); 7100 } 7101 return err; 7102 } 7103 7104 static u32 iter_ref_obj_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg, int spi) 7105 { 7106 struct bpf_func_state *state = func(env, reg); 7107 7108 return state->stack[spi].spilled_ptr.ref_obj_id; 7109 } 7110 7111 static bool is_iter_kfunc(struct bpf_kfunc_call_arg_meta *meta) 7112 { 7113 return meta->kfunc_flags & (KF_ITER_NEW | KF_ITER_NEXT | KF_ITER_DESTROY); 7114 } 7115 7116 static bool is_iter_new_kfunc(struct bpf_kfunc_call_arg_meta *meta) 7117 { 7118 return meta->kfunc_flags & KF_ITER_NEW; 7119 } 7120 7121 static bool is_iter_next_kfunc(struct bpf_kfunc_call_arg_meta *meta) 7122 { 7123 return meta->kfunc_flags & KF_ITER_NEXT; 7124 } 7125 7126 static bool is_iter_destroy_kfunc(struct bpf_kfunc_call_arg_meta *meta) 7127 { 7128 return meta->kfunc_flags & KF_ITER_DESTROY; 7129 } 7130 7131 static bool is_kfunc_arg_iter(struct bpf_kfunc_call_arg_meta *meta, int arg) 7132 { 7133 /* btf_check_iter_kfuncs() guarantees that first argument of any iter 7134 * kfunc is iter state pointer 7135 */ 7136 return arg == 0 && is_iter_kfunc(meta); 7137 } 7138 7139 static int process_iter_arg(struct bpf_verifier_env *env, int regno, int insn_idx, 7140 struct bpf_kfunc_call_arg_meta *meta) 7141 { 7142 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno]; 7143 const struct btf_type *t; 7144 const struct btf_param *arg; 7145 int spi, err, i, nr_slots; 7146 u32 btf_id; 7147 7148 /* btf_check_iter_kfuncs() ensures we don't need to validate anything here */ 7149 arg = &btf_params(meta->func_proto)[0]; 7150 t = btf_type_skip_modifiers(meta->btf, arg->type, NULL); /* PTR */ 7151 t = btf_type_skip_modifiers(meta->btf, t->type, &btf_id); /* STRUCT */ 7152 nr_slots = t->size / BPF_REG_SIZE; 7153 7154 if (is_iter_new_kfunc(meta)) { 7155 /* bpf_iter_<type>_new() expects pointer to uninit iter state */ 7156 if (!is_iter_reg_valid_uninit(env, reg, nr_slots)) { 7157 verbose(env, "expected uninitialized iter_%s as arg #%d\n", 7158 iter_type_str(meta->btf, btf_id), regno); 7159 return -EINVAL; 7160 } 7161 7162 for (i = 0; i < nr_slots * 8; i += BPF_REG_SIZE) { 7163 err = check_mem_access(env, insn_idx, regno, 7164 i, BPF_DW, BPF_WRITE, -1, false); 7165 if (err) 7166 return err; 7167 } 7168 7169 err = mark_stack_slots_iter(env, reg, insn_idx, meta->btf, btf_id, nr_slots); 7170 if (err) 7171 return err; 7172 } else { 7173 /* iter_next() or iter_destroy() expect initialized iter state*/ 7174 if (!is_iter_reg_valid_init(env, reg, meta->btf, btf_id, nr_slots)) { 7175 verbose(env, "expected an initialized iter_%s as arg #%d\n", 7176 iter_type_str(meta->btf, btf_id), regno); 7177 return -EINVAL; 7178 } 7179 7180 spi = iter_get_spi(env, reg, nr_slots); 7181 if (spi < 0) 7182 return spi; 7183 7184 err = mark_iter_read(env, reg, spi, nr_slots); 7185 if (err) 7186 return err; 7187 7188 /* remember meta->iter info for process_iter_next_call() */ 7189 meta->iter.spi = spi; 7190 meta->iter.frameno = reg->frameno; 7191 meta->ref_obj_id = iter_ref_obj_id(env, reg, spi); 7192 7193 if (is_iter_destroy_kfunc(meta)) { 7194 err = unmark_stack_slots_iter(env, reg, nr_slots); 7195 if (err) 7196 return err; 7197 } 7198 } 7199 7200 return 0; 7201 } 7202 7203 /* process_iter_next_call() is called when verifier gets to iterator's next 7204 * "method" (e.g., bpf_iter_num_next() for numbers iterator) call. We'll refer 7205 * to it as just "iter_next()" in comments below. 7206 * 7207 * BPF verifier relies on a crucial contract for any iter_next() 7208 * implementation: it should *eventually* return NULL, and once that happens 7209 * it should keep returning NULL. That is, once iterator exhausts elements to 7210 * iterate, it should never reset or spuriously return new elements. 7211 * 7212 * With the assumption of such contract, process_iter_next_call() simulates 7213 * a fork in the verifier state to validate loop logic correctness and safety 7214 * without having to simulate infinite amount of iterations. 7215 * 7216 * In current state, we first assume that iter_next() returned NULL and 7217 * iterator state is set to DRAINED (BPF_ITER_STATE_DRAINED). In such 7218 * conditions we should not form an infinite loop and should eventually reach 7219 * exit. 7220 * 7221 * Besides that, we also fork current state and enqueue it for later 7222 * verification. In a forked state we keep iterator state as ACTIVE 7223 * (BPF_ITER_STATE_ACTIVE) and assume non-NULL return from iter_next(). We 7224 * also bump iteration depth to prevent erroneous infinite loop detection 7225 * later on (see iter_active_depths_differ() comment for details). In this 7226 * state we assume that we'll eventually loop back to another iter_next() 7227 * calls (it could be in exactly same location or in some other instruction, 7228 * it doesn't matter, we don't make any unnecessary assumptions about this, 7229 * everything revolves around iterator state in a stack slot, not which 7230 * instruction is calling iter_next()). When that happens, we either will come 7231 * to iter_next() with equivalent state and can conclude that next iteration 7232 * will proceed in exactly the same way as we just verified, so it's safe to 7233 * assume that loop converges. If not, we'll go on another iteration 7234 * simulation with a different input state, until all possible starting states 7235 * are validated or we reach maximum number of instructions limit. 7236 * 7237 * This way, we will either exhaustively discover all possible input states 7238 * that iterator loop can start with and eventually will converge, or we'll 7239 * effectively regress into bounded loop simulation logic and either reach 7240 * maximum number of instructions if loop is not provably convergent, or there 7241 * is some statically known limit on number of iterations (e.g., if there is 7242 * an explicit `if n > 100 then break;` statement somewhere in the loop). 7243 * 7244 * One very subtle but very important aspect is that we *always* simulate NULL 7245 * condition first (as the current state) before we simulate non-NULL case. 7246 * This has to do with intricacies of scalar precision tracking. By simulating 7247 * "exit condition" of iter_next() returning NULL first, we make sure all the 7248 * relevant precision marks *that will be set **after** we exit iterator loop* 7249 * are propagated backwards to common parent state of NULL and non-NULL 7250 * branches. Thanks to that, state equivalence checks done later in forked 7251 * state, when reaching iter_next() for ACTIVE iterator, can assume that 7252 * precision marks are finalized and won't change. Because simulating another 7253 * ACTIVE iterator iteration won't change them (because given same input 7254 * states we'll end up with exactly same output states which we are currently 7255 * comparing; and verification after the loop already propagated back what 7256 * needs to be **additionally** tracked as precise). It's subtle, grok 7257 * precision tracking for more intuitive understanding. 7258 */ 7259 static int process_iter_next_call(struct bpf_verifier_env *env, int insn_idx, 7260 struct bpf_kfunc_call_arg_meta *meta) 7261 { 7262 struct bpf_verifier_state *cur_st = env->cur_state, *queued_st; 7263 struct bpf_func_state *cur_fr = cur_st->frame[cur_st->curframe], *queued_fr; 7264 struct bpf_reg_state *cur_iter, *queued_iter; 7265 int iter_frameno = meta->iter.frameno; 7266 int iter_spi = meta->iter.spi; 7267 7268 BTF_TYPE_EMIT(struct bpf_iter); 7269 7270 cur_iter = &env->cur_state->frame[iter_frameno]->stack[iter_spi].spilled_ptr; 7271 7272 if (cur_iter->iter.state != BPF_ITER_STATE_ACTIVE && 7273 cur_iter->iter.state != BPF_ITER_STATE_DRAINED) { 7274 verbose(env, "verifier internal error: unexpected iterator state %d (%s)\n", 7275 cur_iter->iter.state, iter_state_str(cur_iter->iter.state)); 7276 return -EFAULT; 7277 } 7278 7279 if (cur_iter->iter.state == BPF_ITER_STATE_ACTIVE) { 7280 /* branch out active iter state */ 7281 queued_st = push_stack(env, insn_idx + 1, insn_idx, false); 7282 if (!queued_st) 7283 return -ENOMEM; 7284 7285 queued_iter = &queued_st->frame[iter_frameno]->stack[iter_spi].spilled_ptr; 7286 queued_iter->iter.state = BPF_ITER_STATE_ACTIVE; 7287 queued_iter->iter.depth++; 7288 7289 queued_fr = queued_st->frame[queued_st->curframe]; 7290 mark_ptr_not_null_reg(&queued_fr->regs[BPF_REG_0]); 7291 } 7292 7293 /* switch to DRAINED state, but keep the depth unchanged */ 7294 /* mark current iter state as drained and assume returned NULL */ 7295 cur_iter->iter.state = BPF_ITER_STATE_DRAINED; 7296 __mark_reg_const_zero(&cur_fr->regs[BPF_REG_0]); 7297 7298 return 0; 7299 } 7300 7301 static bool arg_type_is_mem_size(enum bpf_arg_type type) 7302 { 7303 return type == ARG_CONST_SIZE || 7304 type == ARG_CONST_SIZE_OR_ZERO; 7305 } 7306 7307 static bool arg_type_is_release(enum bpf_arg_type type) 7308 { 7309 return type & OBJ_RELEASE; 7310 } 7311 7312 static bool arg_type_is_dynptr(enum bpf_arg_type type) 7313 { 7314 return base_type(type) == ARG_PTR_TO_DYNPTR; 7315 } 7316 7317 static int int_ptr_type_to_size(enum bpf_arg_type type) 7318 { 7319 if (type == ARG_PTR_TO_INT) 7320 return sizeof(u32); 7321 else if (type == ARG_PTR_TO_LONG) 7322 return sizeof(u64); 7323 7324 return -EINVAL; 7325 } 7326 7327 static int resolve_map_arg_type(struct bpf_verifier_env *env, 7328 const struct bpf_call_arg_meta *meta, 7329 enum bpf_arg_type *arg_type) 7330 { 7331 if (!meta->map_ptr) { 7332 /* kernel subsystem misconfigured verifier */ 7333 verbose(env, "invalid map_ptr to access map->type\n"); 7334 return -EACCES; 7335 } 7336 7337 switch (meta->map_ptr->map_type) { 7338 case BPF_MAP_TYPE_SOCKMAP: 7339 case BPF_MAP_TYPE_SOCKHASH: 7340 if (*arg_type == ARG_PTR_TO_MAP_VALUE) { 7341 *arg_type = ARG_PTR_TO_BTF_ID_SOCK_COMMON; 7342 } else { 7343 verbose(env, "invalid arg_type for sockmap/sockhash\n"); 7344 return -EINVAL; 7345 } 7346 break; 7347 case BPF_MAP_TYPE_BLOOM_FILTER: 7348 if (meta->func_id == BPF_FUNC_map_peek_elem) 7349 *arg_type = ARG_PTR_TO_MAP_VALUE; 7350 break; 7351 default: 7352 break; 7353 } 7354 return 0; 7355 } 7356 7357 struct bpf_reg_types { 7358 const enum bpf_reg_type types[10]; 7359 u32 *btf_id; 7360 }; 7361 7362 static const struct bpf_reg_types sock_types = { 7363 .types = { 7364 PTR_TO_SOCK_COMMON, 7365 PTR_TO_SOCKET, 7366 PTR_TO_TCP_SOCK, 7367 PTR_TO_XDP_SOCK, 7368 }, 7369 }; 7370 7371 #ifdef CONFIG_NET 7372 static const struct bpf_reg_types btf_id_sock_common_types = { 7373 .types = { 7374 PTR_TO_SOCK_COMMON, 7375 PTR_TO_SOCKET, 7376 PTR_TO_TCP_SOCK, 7377 PTR_TO_XDP_SOCK, 7378 PTR_TO_BTF_ID, 7379 PTR_TO_BTF_ID | PTR_TRUSTED, 7380 }, 7381 .btf_id = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON], 7382 }; 7383 #endif 7384 7385 static const struct bpf_reg_types mem_types = { 7386 .types = { 7387 PTR_TO_STACK, 7388 PTR_TO_PACKET, 7389 PTR_TO_PACKET_META, 7390 PTR_TO_MAP_KEY, 7391 PTR_TO_MAP_VALUE, 7392 PTR_TO_MEM, 7393 PTR_TO_MEM | MEM_RINGBUF, 7394 PTR_TO_BUF, 7395 PTR_TO_BTF_ID | PTR_TRUSTED, 7396 }, 7397 }; 7398 7399 static const struct bpf_reg_types int_ptr_types = { 7400 .types = { 7401 PTR_TO_STACK, 7402 PTR_TO_PACKET, 7403 PTR_TO_PACKET_META, 7404 PTR_TO_MAP_KEY, 7405 PTR_TO_MAP_VALUE, 7406 }, 7407 }; 7408 7409 static const struct bpf_reg_types spin_lock_types = { 7410 .types = { 7411 PTR_TO_MAP_VALUE, 7412 PTR_TO_BTF_ID | MEM_ALLOC, 7413 } 7414 }; 7415 7416 static const struct bpf_reg_types fullsock_types = { .types = { PTR_TO_SOCKET } }; 7417 static const struct bpf_reg_types scalar_types = { .types = { SCALAR_VALUE } }; 7418 static const struct bpf_reg_types context_types = { .types = { PTR_TO_CTX } }; 7419 static const struct bpf_reg_types ringbuf_mem_types = { .types = { PTR_TO_MEM | MEM_RINGBUF } }; 7420 static const struct bpf_reg_types const_map_ptr_types = { .types = { CONST_PTR_TO_MAP } }; 7421 static const struct bpf_reg_types btf_ptr_types = { 7422 .types = { 7423 PTR_TO_BTF_ID, 7424 PTR_TO_BTF_ID | PTR_TRUSTED, 7425 PTR_TO_BTF_ID | MEM_RCU, 7426 }, 7427 }; 7428 static const struct bpf_reg_types percpu_btf_ptr_types = { 7429 .types = { 7430 PTR_TO_BTF_ID | MEM_PERCPU, 7431 PTR_TO_BTF_ID | MEM_PERCPU | PTR_TRUSTED, 7432 } 7433 }; 7434 static const struct bpf_reg_types func_ptr_types = { .types = { PTR_TO_FUNC } }; 7435 static const struct bpf_reg_types stack_ptr_types = { .types = { PTR_TO_STACK } }; 7436 static const struct bpf_reg_types const_str_ptr_types = { .types = { PTR_TO_MAP_VALUE } }; 7437 static const struct bpf_reg_types timer_types = { .types = { PTR_TO_MAP_VALUE } }; 7438 static const struct bpf_reg_types kptr_types = { .types = { PTR_TO_MAP_VALUE } }; 7439 static const struct bpf_reg_types dynptr_types = { 7440 .types = { 7441 PTR_TO_STACK, 7442 CONST_PTR_TO_DYNPTR, 7443 } 7444 }; 7445 7446 static const struct bpf_reg_types *compatible_reg_types[__BPF_ARG_TYPE_MAX] = { 7447 [ARG_PTR_TO_MAP_KEY] = &mem_types, 7448 [ARG_PTR_TO_MAP_VALUE] = &mem_types, 7449 [ARG_CONST_SIZE] = &scalar_types, 7450 [ARG_CONST_SIZE_OR_ZERO] = &scalar_types, 7451 [ARG_CONST_ALLOC_SIZE_OR_ZERO] = &scalar_types, 7452 [ARG_CONST_MAP_PTR] = &const_map_ptr_types, 7453 [ARG_PTR_TO_CTX] = &context_types, 7454 [ARG_PTR_TO_SOCK_COMMON] = &sock_types, 7455 #ifdef CONFIG_NET 7456 [ARG_PTR_TO_BTF_ID_SOCK_COMMON] = &btf_id_sock_common_types, 7457 #endif 7458 [ARG_PTR_TO_SOCKET] = &fullsock_types, 7459 [ARG_PTR_TO_BTF_ID] = &btf_ptr_types, 7460 [ARG_PTR_TO_SPIN_LOCK] = &spin_lock_types, 7461 [ARG_PTR_TO_MEM] = &mem_types, 7462 [ARG_PTR_TO_RINGBUF_MEM] = &ringbuf_mem_types, 7463 [ARG_PTR_TO_INT] = &int_ptr_types, 7464 [ARG_PTR_TO_LONG] = &int_ptr_types, 7465 [ARG_PTR_TO_PERCPU_BTF_ID] = &percpu_btf_ptr_types, 7466 [ARG_PTR_TO_FUNC] = &func_ptr_types, 7467 [ARG_PTR_TO_STACK] = &stack_ptr_types, 7468 [ARG_PTR_TO_CONST_STR] = &const_str_ptr_types, 7469 [ARG_PTR_TO_TIMER] = &timer_types, 7470 [ARG_PTR_TO_KPTR] = &kptr_types, 7471 [ARG_PTR_TO_DYNPTR] = &dynptr_types, 7472 }; 7473 7474 static int check_reg_type(struct bpf_verifier_env *env, u32 regno, 7475 enum bpf_arg_type arg_type, 7476 const u32 *arg_btf_id, 7477 struct bpf_call_arg_meta *meta) 7478 { 7479 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno]; 7480 enum bpf_reg_type expected, type = reg->type; 7481 const struct bpf_reg_types *compatible; 7482 int i, j; 7483 7484 compatible = compatible_reg_types[base_type(arg_type)]; 7485 if (!compatible) { 7486 verbose(env, "verifier internal error: unsupported arg type %d\n", arg_type); 7487 return -EFAULT; 7488 } 7489 7490 /* ARG_PTR_TO_MEM + RDONLY is compatible with PTR_TO_MEM and PTR_TO_MEM + RDONLY, 7491 * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM and NOT with PTR_TO_MEM + RDONLY 7492 * 7493 * Same for MAYBE_NULL: 7494 * 7495 * ARG_PTR_TO_MEM + MAYBE_NULL is compatible with PTR_TO_MEM and PTR_TO_MEM + MAYBE_NULL, 7496 * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM but NOT with PTR_TO_MEM + MAYBE_NULL 7497 * 7498 * Therefore we fold these flags depending on the arg_type before comparison. 7499 */ 7500 if (arg_type & MEM_RDONLY) 7501 type &= ~MEM_RDONLY; 7502 if (arg_type & PTR_MAYBE_NULL) 7503 type &= ~PTR_MAYBE_NULL; 7504 7505 if (meta->func_id == BPF_FUNC_kptr_xchg && type & MEM_ALLOC) 7506 type &= ~MEM_ALLOC; 7507 7508 for (i = 0; i < ARRAY_SIZE(compatible->types); i++) { 7509 expected = compatible->types[i]; 7510 if (expected == NOT_INIT) 7511 break; 7512 7513 if (type == expected) 7514 goto found; 7515 } 7516 7517 verbose(env, "R%d type=%s expected=", regno, reg_type_str(env, reg->type)); 7518 for (j = 0; j + 1 < i; j++) 7519 verbose(env, "%s, ", reg_type_str(env, compatible->types[j])); 7520 verbose(env, "%s\n", reg_type_str(env, compatible->types[j])); 7521 return -EACCES; 7522 7523 found: 7524 if (base_type(reg->type) != PTR_TO_BTF_ID) 7525 return 0; 7526 7527 if (compatible == &mem_types) { 7528 if (!(arg_type & MEM_RDONLY)) { 7529 verbose(env, 7530 "%s() may write into memory pointed by R%d type=%s\n", 7531 func_id_name(meta->func_id), 7532 regno, reg_type_str(env, reg->type)); 7533 return -EACCES; 7534 } 7535 return 0; 7536 } 7537 7538 switch ((int)reg->type) { 7539 case PTR_TO_BTF_ID: 7540 case PTR_TO_BTF_ID | PTR_TRUSTED: 7541 case PTR_TO_BTF_ID | MEM_RCU: 7542 case PTR_TO_BTF_ID | PTR_MAYBE_NULL: 7543 case PTR_TO_BTF_ID | PTR_MAYBE_NULL | MEM_RCU: 7544 { 7545 /* For bpf_sk_release, it needs to match against first member 7546 * 'struct sock_common', hence make an exception for it. This 7547 * allows bpf_sk_release to work for multiple socket types. 7548 */ 7549 bool strict_type_match = arg_type_is_release(arg_type) && 7550 meta->func_id != BPF_FUNC_sk_release; 7551 7552 if (type_may_be_null(reg->type) && 7553 (!type_may_be_null(arg_type) || arg_type_is_release(arg_type))) { 7554 verbose(env, "Possibly NULL pointer passed to helper arg%d\n", regno); 7555 return -EACCES; 7556 } 7557 7558 if (!arg_btf_id) { 7559 if (!compatible->btf_id) { 7560 verbose(env, "verifier internal error: missing arg compatible BTF ID\n"); 7561 return -EFAULT; 7562 } 7563 arg_btf_id = compatible->btf_id; 7564 } 7565 7566 if (meta->func_id == BPF_FUNC_kptr_xchg) { 7567 if (map_kptr_match_type(env, meta->kptr_field, reg, regno)) 7568 return -EACCES; 7569 } else { 7570 if (arg_btf_id == BPF_PTR_POISON) { 7571 verbose(env, "verifier internal error:"); 7572 verbose(env, "R%d has non-overwritten BPF_PTR_POISON type\n", 7573 regno); 7574 return -EACCES; 7575 } 7576 7577 if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off, 7578 btf_vmlinux, *arg_btf_id, 7579 strict_type_match)) { 7580 verbose(env, "R%d is of type %s but %s is expected\n", 7581 regno, btf_type_name(reg->btf, reg->btf_id), 7582 btf_type_name(btf_vmlinux, *arg_btf_id)); 7583 return -EACCES; 7584 } 7585 } 7586 break; 7587 } 7588 case PTR_TO_BTF_ID | MEM_ALLOC: 7589 if (meta->func_id != BPF_FUNC_spin_lock && meta->func_id != BPF_FUNC_spin_unlock && 7590 meta->func_id != BPF_FUNC_kptr_xchg) { 7591 verbose(env, "verifier internal error: unimplemented handling of MEM_ALLOC\n"); 7592 return -EFAULT; 7593 } 7594 /* Handled by helper specific checks */ 7595 break; 7596 case PTR_TO_BTF_ID | MEM_PERCPU: 7597 case PTR_TO_BTF_ID | MEM_PERCPU | PTR_TRUSTED: 7598 /* Handled by helper specific checks */ 7599 break; 7600 default: 7601 verbose(env, "verifier internal error: invalid PTR_TO_BTF_ID register for type match\n"); 7602 return -EFAULT; 7603 } 7604 return 0; 7605 } 7606 7607 static struct btf_field * 7608 reg_find_field_offset(const struct bpf_reg_state *reg, s32 off, u32 fields) 7609 { 7610 struct btf_field *field; 7611 struct btf_record *rec; 7612 7613 rec = reg_btf_record(reg); 7614 if (!rec) 7615 return NULL; 7616 7617 field = btf_record_find(rec, off, fields); 7618 if (!field) 7619 return NULL; 7620 7621 return field; 7622 } 7623 7624 int check_func_arg_reg_off(struct bpf_verifier_env *env, 7625 const struct bpf_reg_state *reg, int regno, 7626 enum bpf_arg_type arg_type) 7627 { 7628 u32 type = reg->type; 7629 7630 /* When referenced register is passed to release function, its fixed 7631 * offset must be 0. 7632 * 7633 * We will check arg_type_is_release reg has ref_obj_id when storing 7634 * meta->release_regno. 7635 */ 7636 if (arg_type_is_release(arg_type)) { 7637 /* ARG_PTR_TO_DYNPTR with OBJ_RELEASE is a bit special, as it 7638 * may not directly point to the object being released, but to 7639 * dynptr pointing to such object, which might be at some offset 7640 * on the stack. In that case, we simply to fallback to the 7641 * default handling. 7642 */ 7643 if (arg_type_is_dynptr(arg_type) && type == PTR_TO_STACK) 7644 return 0; 7645 7646 if ((type_is_ptr_alloc_obj(type) || type_is_non_owning_ref(type)) && reg->off) { 7647 if (reg_find_field_offset(reg, reg->off, BPF_GRAPH_NODE_OR_ROOT)) 7648 return __check_ptr_off_reg(env, reg, regno, true); 7649 7650 verbose(env, "R%d must have zero offset when passed to release func\n", 7651 regno); 7652 verbose(env, "No graph node or root found at R%d type:%s off:%d\n", regno, 7653 btf_type_name(reg->btf, reg->btf_id), reg->off); 7654 return -EINVAL; 7655 } 7656 7657 /* Doing check_ptr_off_reg check for the offset will catch this 7658 * because fixed_off_ok is false, but checking here allows us 7659 * to give the user a better error message. 7660 */ 7661 if (reg->off) { 7662 verbose(env, "R%d must have zero offset when passed to release func or trusted arg to kfunc\n", 7663 regno); 7664 return -EINVAL; 7665 } 7666 return __check_ptr_off_reg(env, reg, regno, false); 7667 } 7668 7669 switch (type) { 7670 /* Pointer types where both fixed and variable offset is explicitly allowed: */ 7671 case PTR_TO_STACK: 7672 case PTR_TO_PACKET: 7673 case PTR_TO_PACKET_META: 7674 case PTR_TO_MAP_KEY: 7675 case PTR_TO_MAP_VALUE: 7676 case PTR_TO_MEM: 7677 case PTR_TO_MEM | MEM_RDONLY: 7678 case PTR_TO_MEM | MEM_RINGBUF: 7679 case PTR_TO_BUF: 7680 case PTR_TO_BUF | MEM_RDONLY: 7681 case SCALAR_VALUE: 7682 return 0; 7683 /* All the rest must be rejected, except PTR_TO_BTF_ID which allows 7684 * fixed offset. 7685 */ 7686 case PTR_TO_BTF_ID: 7687 case PTR_TO_BTF_ID | MEM_ALLOC: 7688 case PTR_TO_BTF_ID | PTR_TRUSTED: 7689 case PTR_TO_BTF_ID | MEM_RCU: 7690 case PTR_TO_BTF_ID | MEM_ALLOC | NON_OWN_REF: 7691 /* When referenced PTR_TO_BTF_ID is passed to release function, 7692 * its fixed offset must be 0. In the other cases, fixed offset 7693 * can be non-zero. This was already checked above. So pass 7694 * fixed_off_ok as true to allow fixed offset for all other 7695 * cases. var_off always must be 0 for PTR_TO_BTF_ID, hence we 7696 * still need to do checks instead of returning. 7697 */ 7698 return __check_ptr_off_reg(env, reg, regno, true); 7699 default: 7700 return __check_ptr_off_reg(env, reg, regno, false); 7701 } 7702 } 7703 7704 static struct bpf_reg_state *get_dynptr_arg_reg(struct bpf_verifier_env *env, 7705 const struct bpf_func_proto *fn, 7706 struct bpf_reg_state *regs) 7707 { 7708 struct bpf_reg_state *state = NULL; 7709 int i; 7710 7711 for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++) 7712 if (arg_type_is_dynptr(fn->arg_type[i])) { 7713 if (state) { 7714 verbose(env, "verifier internal error: multiple dynptr args\n"); 7715 return NULL; 7716 } 7717 state = ®s[BPF_REG_1 + i]; 7718 } 7719 7720 if (!state) 7721 verbose(env, "verifier internal error: no dynptr arg found\n"); 7722 7723 return state; 7724 } 7725 7726 static int dynptr_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 7727 { 7728 struct bpf_func_state *state = func(env, reg); 7729 int spi; 7730 7731 if (reg->type == CONST_PTR_TO_DYNPTR) 7732 return reg->id; 7733 spi = dynptr_get_spi(env, reg); 7734 if (spi < 0) 7735 return spi; 7736 return state->stack[spi].spilled_ptr.id; 7737 } 7738 7739 static int dynptr_ref_obj_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 7740 { 7741 struct bpf_func_state *state = func(env, reg); 7742 int spi; 7743 7744 if (reg->type == CONST_PTR_TO_DYNPTR) 7745 return reg->ref_obj_id; 7746 spi = dynptr_get_spi(env, reg); 7747 if (spi < 0) 7748 return spi; 7749 return state->stack[spi].spilled_ptr.ref_obj_id; 7750 } 7751 7752 static enum bpf_dynptr_type dynptr_get_type(struct bpf_verifier_env *env, 7753 struct bpf_reg_state *reg) 7754 { 7755 struct bpf_func_state *state = func(env, reg); 7756 int spi; 7757 7758 if (reg->type == CONST_PTR_TO_DYNPTR) 7759 return reg->dynptr.type; 7760 7761 spi = __get_spi(reg->off); 7762 if (spi < 0) { 7763 verbose(env, "verifier internal error: invalid spi when querying dynptr type\n"); 7764 return BPF_DYNPTR_TYPE_INVALID; 7765 } 7766 7767 return state->stack[spi].spilled_ptr.dynptr.type; 7768 } 7769 7770 static int check_func_arg(struct bpf_verifier_env *env, u32 arg, 7771 struct bpf_call_arg_meta *meta, 7772 const struct bpf_func_proto *fn, 7773 int insn_idx) 7774 { 7775 u32 regno = BPF_REG_1 + arg; 7776 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno]; 7777 enum bpf_arg_type arg_type = fn->arg_type[arg]; 7778 enum bpf_reg_type type = reg->type; 7779 u32 *arg_btf_id = NULL; 7780 int err = 0; 7781 7782 if (arg_type == ARG_DONTCARE) 7783 return 0; 7784 7785 err = check_reg_arg(env, regno, SRC_OP); 7786 if (err) 7787 return err; 7788 7789 if (arg_type == ARG_ANYTHING) { 7790 if (is_pointer_value(env, regno)) { 7791 verbose(env, "R%d leaks addr into helper function\n", 7792 regno); 7793 return -EACCES; 7794 } 7795 return 0; 7796 } 7797 7798 if (type_is_pkt_pointer(type) && 7799 !may_access_direct_pkt_data(env, meta, BPF_READ)) { 7800 verbose(env, "helper access to the packet is not allowed\n"); 7801 return -EACCES; 7802 } 7803 7804 if (base_type(arg_type) == ARG_PTR_TO_MAP_VALUE) { 7805 err = resolve_map_arg_type(env, meta, &arg_type); 7806 if (err) 7807 return err; 7808 } 7809 7810 if (register_is_null(reg) && type_may_be_null(arg_type)) 7811 /* A NULL register has a SCALAR_VALUE type, so skip 7812 * type checking. 7813 */ 7814 goto skip_type_check; 7815 7816 /* arg_btf_id and arg_size are in a union. */ 7817 if (base_type(arg_type) == ARG_PTR_TO_BTF_ID || 7818 base_type(arg_type) == ARG_PTR_TO_SPIN_LOCK) 7819 arg_btf_id = fn->arg_btf_id[arg]; 7820 7821 err = check_reg_type(env, regno, arg_type, arg_btf_id, meta); 7822 if (err) 7823 return err; 7824 7825 err = check_func_arg_reg_off(env, reg, regno, arg_type); 7826 if (err) 7827 return err; 7828 7829 skip_type_check: 7830 if (arg_type_is_release(arg_type)) { 7831 if (arg_type_is_dynptr(arg_type)) { 7832 struct bpf_func_state *state = func(env, reg); 7833 int spi; 7834 7835 /* Only dynptr created on stack can be released, thus 7836 * the get_spi and stack state checks for spilled_ptr 7837 * should only be done before process_dynptr_func for 7838 * PTR_TO_STACK. 7839 */ 7840 if (reg->type == PTR_TO_STACK) { 7841 spi = dynptr_get_spi(env, reg); 7842 if (spi < 0 || !state->stack[spi].spilled_ptr.ref_obj_id) { 7843 verbose(env, "arg %d is an unacquired reference\n", regno); 7844 return -EINVAL; 7845 } 7846 } else { 7847 verbose(env, "cannot release unowned const bpf_dynptr\n"); 7848 return -EINVAL; 7849 } 7850 } else if (!reg->ref_obj_id && !register_is_null(reg)) { 7851 verbose(env, "R%d must be referenced when passed to release function\n", 7852 regno); 7853 return -EINVAL; 7854 } 7855 if (meta->release_regno) { 7856 verbose(env, "verifier internal error: more than one release argument\n"); 7857 return -EFAULT; 7858 } 7859 meta->release_regno = regno; 7860 } 7861 7862 if (reg->ref_obj_id) { 7863 if (meta->ref_obj_id) { 7864 verbose(env, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n", 7865 regno, reg->ref_obj_id, 7866 meta->ref_obj_id); 7867 return -EFAULT; 7868 } 7869 meta->ref_obj_id = reg->ref_obj_id; 7870 } 7871 7872 switch (base_type(arg_type)) { 7873 case ARG_CONST_MAP_PTR: 7874 /* bpf_map_xxx(map_ptr) call: remember that map_ptr */ 7875 if (meta->map_ptr) { 7876 /* Use map_uid (which is unique id of inner map) to reject: 7877 * inner_map1 = bpf_map_lookup_elem(outer_map, key1) 7878 * inner_map2 = bpf_map_lookup_elem(outer_map, key2) 7879 * if (inner_map1 && inner_map2) { 7880 * timer = bpf_map_lookup_elem(inner_map1); 7881 * if (timer) 7882 * // mismatch would have been allowed 7883 * bpf_timer_init(timer, inner_map2); 7884 * } 7885 * 7886 * Comparing map_ptr is enough to distinguish normal and outer maps. 7887 */ 7888 if (meta->map_ptr != reg->map_ptr || 7889 meta->map_uid != reg->map_uid) { 7890 verbose(env, 7891 "timer pointer in R1 map_uid=%d doesn't match map pointer in R2 map_uid=%d\n", 7892 meta->map_uid, reg->map_uid); 7893 return -EINVAL; 7894 } 7895 } 7896 meta->map_ptr = reg->map_ptr; 7897 meta->map_uid = reg->map_uid; 7898 break; 7899 case ARG_PTR_TO_MAP_KEY: 7900 /* bpf_map_xxx(..., map_ptr, ..., key) call: 7901 * check that [key, key + map->key_size) are within 7902 * stack limits and initialized 7903 */ 7904 if (!meta->map_ptr) { 7905 /* in function declaration map_ptr must come before 7906 * map_key, so that it's verified and known before 7907 * we have to check map_key here. Otherwise it means 7908 * that kernel subsystem misconfigured verifier 7909 */ 7910 verbose(env, "invalid map_ptr to access map->key\n"); 7911 return -EACCES; 7912 } 7913 err = check_helper_mem_access(env, regno, 7914 meta->map_ptr->key_size, false, 7915 NULL); 7916 break; 7917 case ARG_PTR_TO_MAP_VALUE: 7918 if (type_may_be_null(arg_type) && register_is_null(reg)) 7919 return 0; 7920 7921 /* bpf_map_xxx(..., map_ptr, ..., value) call: 7922 * check [value, value + map->value_size) validity 7923 */ 7924 if (!meta->map_ptr) { 7925 /* kernel subsystem misconfigured verifier */ 7926 verbose(env, "invalid map_ptr to access map->value\n"); 7927 return -EACCES; 7928 } 7929 meta->raw_mode = arg_type & MEM_UNINIT; 7930 err = check_helper_mem_access(env, regno, 7931 meta->map_ptr->value_size, false, 7932 meta); 7933 break; 7934 case ARG_PTR_TO_PERCPU_BTF_ID: 7935 if (!reg->btf_id) { 7936 verbose(env, "Helper has invalid btf_id in R%d\n", regno); 7937 return -EACCES; 7938 } 7939 meta->ret_btf = reg->btf; 7940 meta->ret_btf_id = reg->btf_id; 7941 break; 7942 case ARG_PTR_TO_SPIN_LOCK: 7943 if (in_rbtree_lock_required_cb(env)) { 7944 verbose(env, "can't spin_{lock,unlock} in rbtree cb\n"); 7945 return -EACCES; 7946 } 7947 if (meta->func_id == BPF_FUNC_spin_lock) { 7948 err = process_spin_lock(env, regno, true); 7949 if (err) 7950 return err; 7951 } else if (meta->func_id == BPF_FUNC_spin_unlock) { 7952 err = process_spin_lock(env, regno, false); 7953 if (err) 7954 return err; 7955 } else { 7956 verbose(env, "verifier internal error\n"); 7957 return -EFAULT; 7958 } 7959 break; 7960 case ARG_PTR_TO_TIMER: 7961 err = process_timer_func(env, regno, meta); 7962 if (err) 7963 return err; 7964 break; 7965 case ARG_PTR_TO_FUNC: 7966 meta->subprogno = reg->subprogno; 7967 break; 7968 case ARG_PTR_TO_MEM: 7969 /* The access to this pointer is only checked when we hit the 7970 * next is_mem_size argument below. 7971 */ 7972 meta->raw_mode = arg_type & MEM_UNINIT; 7973 if (arg_type & MEM_FIXED_SIZE) { 7974 err = check_helper_mem_access(env, regno, 7975 fn->arg_size[arg], false, 7976 meta); 7977 } 7978 break; 7979 case ARG_CONST_SIZE: 7980 err = check_mem_size_reg(env, reg, regno, false, meta); 7981 break; 7982 case ARG_CONST_SIZE_OR_ZERO: 7983 err = check_mem_size_reg(env, reg, regno, true, meta); 7984 break; 7985 case ARG_PTR_TO_DYNPTR: 7986 err = process_dynptr_func(env, regno, insn_idx, arg_type, 0); 7987 if (err) 7988 return err; 7989 break; 7990 case ARG_CONST_ALLOC_SIZE_OR_ZERO: 7991 if (!tnum_is_const(reg->var_off)) { 7992 verbose(env, "R%d is not a known constant'\n", 7993 regno); 7994 return -EACCES; 7995 } 7996 meta->mem_size = reg->var_off.value; 7997 err = mark_chain_precision(env, regno); 7998 if (err) 7999 return err; 8000 break; 8001 case ARG_PTR_TO_INT: 8002 case ARG_PTR_TO_LONG: 8003 { 8004 int size = int_ptr_type_to_size(arg_type); 8005 8006 err = check_helper_mem_access(env, regno, size, false, meta); 8007 if (err) 8008 return err; 8009 err = check_ptr_alignment(env, reg, 0, size, true); 8010 break; 8011 } 8012 case ARG_PTR_TO_CONST_STR: 8013 { 8014 struct bpf_map *map = reg->map_ptr; 8015 int map_off; 8016 u64 map_addr; 8017 char *str_ptr; 8018 8019 if (!bpf_map_is_rdonly(map)) { 8020 verbose(env, "R%d does not point to a readonly map'\n", regno); 8021 return -EACCES; 8022 } 8023 8024 if (!tnum_is_const(reg->var_off)) { 8025 verbose(env, "R%d is not a constant address'\n", regno); 8026 return -EACCES; 8027 } 8028 8029 if (!map->ops->map_direct_value_addr) { 8030 verbose(env, "no direct value access support for this map type\n"); 8031 return -EACCES; 8032 } 8033 8034 err = check_map_access(env, regno, reg->off, 8035 map->value_size - reg->off, false, 8036 ACCESS_HELPER); 8037 if (err) 8038 return err; 8039 8040 map_off = reg->off + reg->var_off.value; 8041 err = map->ops->map_direct_value_addr(map, &map_addr, map_off); 8042 if (err) { 8043 verbose(env, "direct value access on string failed\n"); 8044 return err; 8045 } 8046 8047 str_ptr = (char *)(long)(map_addr); 8048 if (!strnchr(str_ptr + map_off, map->value_size - map_off, 0)) { 8049 verbose(env, "string is not zero-terminated\n"); 8050 return -EINVAL; 8051 } 8052 break; 8053 } 8054 case ARG_PTR_TO_KPTR: 8055 err = process_kptr_func(env, regno, meta); 8056 if (err) 8057 return err; 8058 break; 8059 } 8060 8061 return err; 8062 } 8063 8064 static bool may_update_sockmap(struct bpf_verifier_env *env, int func_id) 8065 { 8066 enum bpf_attach_type eatype = env->prog->expected_attach_type; 8067 enum bpf_prog_type type = resolve_prog_type(env->prog); 8068 8069 if (func_id != BPF_FUNC_map_update_elem) 8070 return false; 8071 8072 /* It's not possible to get access to a locked struct sock in these 8073 * contexts, so updating is safe. 8074 */ 8075 switch (type) { 8076 case BPF_PROG_TYPE_TRACING: 8077 if (eatype == BPF_TRACE_ITER) 8078 return true; 8079 break; 8080 case BPF_PROG_TYPE_SOCKET_FILTER: 8081 case BPF_PROG_TYPE_SCHED_CLS: 8082 case BPF_PROG_TYPE_SCHED_ACT: 8083 case BPF_PROG_TYPE_XDP: 8084 case BPF_PROG_TYPE_SK_REUSEPORT: 8085 case BPF_PROG_TYPE_FLOW_DISSECTOR: 8086 case BPF_PROG_TYPE_SK_LOOKUP: 8087 return true; 8088 default: 8089 break; 8090 } 8091 8092 verbose(env, "cannot update sockmap in this context\n"); 8093 return false; 8094 } 8095 8096 static bool allow_tail_call_in_subprogs(struct bpf_verifier_env *env) 8097 { 8098 return env->prog->jit_requested && 8099 bpf_jit_supports_subprog_tailcalls(); 8100 } 8101 8102 static int check_map_func_compatibility(struct bpf_verifier_env *env, 8103 struct bpf_map *map, int func_id) 8104 { 8105 if (!map) 8106 return 0; 8107 8108 /* We need a two way check, first is from map perspective ... */ 8109 switch (map->map_type) { 8110 case BPF_MAP_TYPE_PROG_ARRAY: 8111 if (func_id != BPF_FUNC_tail_call) 8112 goto error; 8113 break; 8114 case BPF_MAP_TYPE_PERF_EVENT_ARRAY: 8115 if (func_id != BPF_FUNC_perf_event_read && 8116 func_id != BPF_FUNC_perf_event_output && 8117 func_id != BPF_FUNC_skb_output && 8118 func_id != BPF_FUNC_perf_event_read_value && 8119 func_id != BPF_FUNC_xdp_output) 8120 goto error; 8121 break; 8122 case BPF_MAP_TYPE_RINGBUF: 8123 if (func_id != BPF_FUNC_ringbuf_output && 8124 func_id != BPF_FUNC_ringbuf_reserve && 8125 func_id != BPF_FUNC_ringbuf_query && 8126 func_id != BPF_FUNC_ringbuf_reserve_dynptr && 8127 func_id != BPF_FUNC_ringbuf_submit_dynptr && 8128 func_id != BPF_FUNC_ringbuf_discard_dynptr) 8129 goto error; 8130 break; 8131 case BPF_MAP_TYPE_USER_RINGBUF: 8132 if (func_id != BPF_FUNC_user_ringbuf_drain) 8133 goto error; 8134 break; 8135 case BPF_MAP_TYPE_STACK_TRACE: 8136 if (func_id != BPF_FUNC_get_stackid) 8137 goto error; 8138 break; 8139 case BPF_MAP_TYPE_CGROUP_ARRAY: 8140 if (func_id != BPF_FUNC_skb_under_cgroup && 8141 func_id != BPF_FUNC_current_task_under_cgroup) 8142 goto error; 8143 break; 8144 case BPF_MAP_TYPE_CGROUP_STORAGE: 8145 case BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE: 8146 if (func_id != BPF_FUNC_get_local_storage) 8147 goto error; 8148 break; 8149 case BPF_MAP_TYPE_DEVMAP: 8150 case BPF_MAP_TYPE_DEVMAP_HASH: 8151 if (func_id != BPF_FUNC_redirect_map && 8152 func_id != BPF_FUNC_map_lookup_elem) 8153 goto error; 8154 break; 8155 /* Restrict bpf side of cpumap and xskmap, open when use-cases 8156 * appear. 8157 */ 8158 case BPF_MAP_TYPE_CPUMAP: 8159 if (func_id != BPF_FUNC_redirect_map) 8160 goto error; 8161 break; 8162 case BPF_MAP_TYPE_XSKMAP: 8163 if (func_id != BPF_FUNC_redirect_map && 8164 func_id != BPF_FUNC_map_lookup_elem) 8165 goto error; 8166 break; 8167 case BPF_MAP_TYPE_ARRAY_OF_MAPS: 8168 case BPF_MAP_TYPE_HASH_OF_MAPS: 8169 if (func_id != BPF_FUNC_map_lookup_elem) 8170 goto error; 8171 break; 8172 case BPF_MAP_TYPE_SOCKMAP: 8173 if (func_id != BPF_FUNC_sk_redirect_map && 8174 func_id != BPF_FUNC_sock_map_update && 8175 func_id != BPF_FUNC_map_delete_elem && 8176 func_id != BPF_FUNC_msg_redirect_map && 8177 func_id != BPF_FUNC_sk_select_reuseport && 8178 func_id != BPF_FUNC_map_lookup_elem && 8179 !may_update_sockmap(env, func_id)) 8180 goto error; 8181 break; 8182 case BPF_MAP_TYPE_SOCKHASH: 8183 if (func_id != BPF_FUNC_sk_redirect_hash && 8184 func_id != BPF_FUNC_sock_hash_update && 8185 func_id != BPF_FUNC_map_delete_elem && 8186 func_id != BPF_FUNC_msg_redirect_hash && 8187 func_id != BPF_FUNC_sk_select_reuseport && 8188 func_id != BPF_FUNC_map_lookup_elem && 8189 !may_update_sockmap(env, func_id)) 8190 goto error; 8191 break; 8192 case BPF_MAP_TYPE_REUSEPORT_SOCKARRAY: 8193 if (func_id != BPF_FUNC_sk_select_reuseport) 8194 goto error; 8195 break; 8196 case BPF_MAP_TYPE_QUEUE: 8197 case BPF_MAP_TYPE_STACK: 8198 if (func_id != BPF_FUNC_map_peek_elem && 8199 func_id != BPF_FUNC_map_pop_elem && 8200 func_id != BPF_FUNC_map_push_elem) 8201 goto error; 8202 break; 8203 case BPF_MAP_TYPE_SK_STORAGE: 8204 if (func_id != BPF_FUNC_sk_storage_get && 8205 func_id != BPF_FUNC_sk_storage_delete && 8206 func_id != BPF_FUNC_kptr_xchg) 8207 goto error; 8208 break; 8209 case BPF_MAP_TYPE_INODE_STORAGE: 8210 if (func_id != BPF_FUNC_inode_storage_get && 8211 func_id != BPF_FUNC_inode_storage_delete && 8212 func_id != BPF_FUNC_kptr_xchg) 8213 goto error; 8214 break; 8215 case BPF_MAP_TYPE_TASK_STORAGE: 8216 if (func_id != BPF_FUNC_task_storage_get && 8217 func_id != BPF_FUNC_task_storage_delete && 8218 func_id != BPF_FUNC_kptr_xchg) 8219 goto error; 8220 break; 8221 case BPF_MAP_TYPE_CGRP_STORAGE: 8222 if (func_id != BPF_FUNC_cgrp_storage_get && 8223 func_id != BPF_FUNC_cgrp_storage_delete && 8224 func_id != BPF_FUNC_kptr_xchg) 8225 goto error; 8226 break; 8227 case BPF_MAP_TYPE_BLOOM_FILTER: 8228 if (func_id != BPF_FUNC_map_peek_elem && 8229 func_id != BPF_FUNC_map_push_elem) 8230 goto error; 8231 break; 8232 default: 8233 break; 8234 } 8235 8236 /* ... and second from the function itself. */ 8237 switch (func_id) { 8238 case BPF_FUNC_tail_call: 8239 if (map->map_type != BPF_MAP_TYPE_PROG_ARRAY) 8240 goto error; 8241 if (env->subprog_cnt > 1 && !allow_tail_call_in_subprogs(env)) { 8242 verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n"); 8243 return -EINVAL; 8244 } 8245 break; 8246 case BPF_FUNC_perf_event_read: 8247 case BPF_FUNC_perf_event_output: 8248 case BPF_FUNC_perf_event_read_value: 8249 case BPF_FUNC_skb_output: 8250 case BPF_FUNC_xdp_output: 8251 if (map->map_type != BPF_MAP_TYPE_PERF_EVENT_ARRAY) 8252 goto error; 8253 break; 8254 case BPF_FUNC_ringbuf_output: 8255 case BPF_FUNC_ringbuf_reserve: 8256 case BPF_FUNC_ringbuf_query: 8257 case BPF_FUNC_ringbuf_reserve_dynptr: 8258 case BPF_FUNC_ringbuf_submit_dynptr: 8259 case BPF_FUNC_ringbuf_discard_dynptr: 8260 if (map->map_type != BPF_MAP_TYPE_RINGBUF) 8261 goto error; 8262 break; 8263 case BPF_FUNC_user_ringbuf_drain: 8264 if (map->map_type != BPF_MAP_TYPE_USER_RINGBUF) 8265 goto error; 8266 break; 8267 case BPF_FUNC_get_stackid: 8268 if (map->map_type != BPF_MAP_TYPE_STACK_TRACE) 8269 goto error; 8270 break; 8271 case BPF_FUNC_current_task_under_cgroup: 8272 case BPF_FUNC_skb_under_cgroup: 8273 if (map->map_type != BPF_MAP_TYPE_CGROUP_ARRAY) 8274 goto error; 8275 break; 8276 case BPF_FUNC_redirect_map: 8277 if (map->map_type != BPF_MAP_TYPE_DEVMAP && 8278 map->map_type != BPF_MAP_TYPE_DEVMAP_HASH && 8279 map->map_type != BPF_MAP_TYPE_CPUMAP && 8280 map->map_type != BPF_MAP_TYPE_XSKMAP) 8281 goto error; 8282 break; 8283 case BPF_FUNC_sk_redirect_map: 8284 case BPF_FUNC_msg_redirect_map: 8285 case BPF_FUNC_sock_map_update: 8286 if (map->map_type != BPF_MAP_TYPE_SOCKMAP) 8287 goto error; 8288 break; 8289 case BPF_FUNC_sk_redirect_hash: 8290 case BPF_FUNC_msg_redirect_hash: 8291 case BPF_FUNC_sock_hash_update: 8292 if (map->map_type != BPF_MAP_TYPE_SOCKHASH) 8293 goto error; 8294 break; 8295 case BPF_FUNC_get_local_storage: 8296 if (map->map_type != BPF_MAP_TYPE_CGROUP_STORAGE && 8297 map->map_type != BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE) 8298 goto error; 8299 break; 8300 case BPF_FUNC_sk_select_reuseport: 8301 if (map->map_type != BPF_MAP_TYPE_REUSEPORT_SOCKARRAY && 8302 map->map_type != BPF_MAP_TYPE_SOCKMAP && 8303 map->map_type != BPF_MAP_TYPE_SOCKHASH) 8304 goto error; 8305 break; 8306 case BPF_FUNC_map_pop_elem: 8307 if (map->map_type != BPF_MAP_TYPE_QUEUE && 8308 map->map_type != BPF_MAP_TYPE_STACK) 8309 goto error; 8310 break; 8311 case BPF_FUNC_map_peek_elem: 8312 case BPF_FUNC_map_push_elem: 8313 if (map->map_type != BPF_MAP_TYPE_QUEUE && 8314 map->map_type != BPF_MAP_TYPE_STACK && 8315 map->map_type != BPF_MAP_TYPE_BLOOM_FILTER) 8316 goto error; 8317 break; 8318 case BPF_FUNC_map_lookup_percpu_elem: 8319 if (map->map_type != BPF_MAP_TYPE_PERCPU_ARRAY && 8320 map->map_type != BPF_MAP_TYPE_PERCPU_HASH && 8321 map->map_type != BPF_MAP_TYPE_LRU_PERCPU_HASH) 8322 goto error; 8323 break; 8324 case BPF_FUNC_sk_storage_get: 8325 case BPF_FUNC_sk_storage_delete: 8326 if (map->map_type != BPF_MAP_TYPE_SK_STORAGE) 8327 goto error; 8328 break; 8329 case BPF_FUNC_inode_storage_get: 8330 case BPF_FUNC_inode_storage_delete: 8331 if (map->map_type != BPF_MAP_TYPE_INODE_STORAGE) 8332 goto error; 8333 break; 8334 case BPF_FUNC_task_storage_get: 8335 case BPF_FUNC_task_storage_delete: 8336 if (map->map_type != BPF_MAP_TYPE_TASK_STORAGE) 8337 goto error; 8338 break; 8339 case BPF_FUNC_cgrp_storage_get: 8340 case BPF_FUNC_cgrp_storage_delete: 8341 if (map->map_type != BPF_MAP_TYPE_CGRP_STORAGE) 8342 goto error; 8343 break; 8344 default: 8345 break; 8346 } 8347 8348 return 0; 8349 error: 8350 verbose(env, "cannot pass map_type %d into func %s#%d\n", 8351 map->map_type, func_id_name(func_id), func_id); 8352 return -EINVAL; 8353 } 8354 8355 static bool check_raw_mode_ok(const struct bpf_func_proto *fn) 8356 { 8357 int count = 0; 8358 8359 if (fn->arg1_type == ARG_PTR_TO_UNINIT_MEM) 8360 count++; 8361 if (fn->arg2_type == ARG_PTR_TO_UNINIT_MEM) 8362 count++; 8363 if (fn->arg3_type == ARG_PTR_TO_UNINIT_MEM) 8364 count++; 8365 if (fn->arg4_type == ARG_PTR_TO_UNINIT_MEM) 8366 count++; 8367 if (fn->arg5_type == ARG_PTR_TO_UNINIT_MEM) 8368 count++; 8369 8370 /* We only support one arg being in raw mode at the moment, 8371 * which is sufficient for the helper functions we have 8372 * right now. 8373 */ 8374 return count <= 1; 8375 } 8376 8377 static bool check_args_pair_invalid(const struct bpf_func_proto *fn, int arg) 8378 { 8379 bool is_fixed = fn->arg_type[arg] & MEM_FIXED_SIZE; 8380 bool has_size = fn->arg_size[arg] != 0; 8381 bool is_next_size = false; 8382 8383 if (arg + 1 < ARRAY_SIZE(fn->arg_type)) 8384 is_next_size = arg_type_is_mem_size(fn->arg_type[arg + 1]); 8385 8386 if (base_type(fn->arg_type[arg]) != ARG_PTR_TO_MEM) 8387 return is_next_size; 8388 8389 return has_size == is_next_size || is_next_size == is_fixed; 8390 } 8391 8392 static bool check_arg_pair_ok(const struct bpf_func_proto *fn) 8393 { 8394 /* bpf_xxx(..., buf, len) call will access 'len' 8395 * bytes from memory 'buf'. Both arg types need 8396 * to be paired, so make sure there's no buggy 8397 * helper function specification. 8398 */ 8399 if (arg_type_is_mem_size(fn->arg1_type) || 8400 check_args_pair_invalid(fn, 0) || 8401 check_args_pair_invalid(fn, 1) || 8402 check_args_pair_invalid(fn, 2) || 8403 check_args_pair_invalid(fn, 3) || 8404 check_args_pair_invalid(fn, 4)) 8405 return false; 8406 8407 return true; 8408 } 8409 8410 static bool check_btf_id_ok(const struct bpf_func_proto *fn) 8411 { 8412 int i; 8413 8414 for (i = 0; i < ARRAY_SIZE(fn->arg_type); i++) { 8415 if (base_type(fn->arg_type[i]) == ARG_PTR_TO_BTF_ID) 8416 return !!fn->arg_btf_id[i]; 8417 if (base_type(fn->arg_type[i]) == ARG_PTR_TO_SPIN_LOCK) 8418 return fn->arg_btf_id[i] == BPF_PTR_POISON; 8419 if (base_type(fn->arg_type[i]) != ARG_PTR_TO_BTF_ID && fn->arg_btf_id[i] && 8420 /* arg_btf_id and arg_size are in a union. */ 8421 (base_type(fn->arg_type[i]) != ARG_PTR_TO_MEM || 8422 !(fn->arg_type[i] & MEM_FIXED_SIZE))) 8423 return false; 8424 } 8425 8426 return true; 8427 } 8428 8429 static int check_func_proto(const struct bpf_func_proto *fn, int func_id) 8430 { 8431 return check_raw_mode_ok(fn) && 8432 check_arg_pair_ok(fn) && 8433 check_btf_id_ok(fn) ? 0 : -EINVAL; 8434 } 8435 8436 /* Packet data might have moved, any old PTR_TO_PACKET[_META,_END] 8437 * are now invalid, so turn them into unknown SCALAR_VALUE. 8438 * 8439 * This also applies to dynptr slices belonging to skb and xdp dynptrs, 8440 * since these slices point to packet data. 8441 */ 8442 static void clear_all_pkt_pointers(struct bpf_verifier_env *env) 8443 { 8444 struct bpf_func_state *state; 8445 struct bpf_reg_state *reg; 8446 8447 bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({ 8448 if (reg_is_pkt_pointer_any(reg) || reg_is_dynptr_slice_pkt(reg)) 8449 mark_reg_invalid(env, reg); 8450 })); 8451 } 8452 8453 enum { 8454 AT_PKT_END = -1, 8455 BEYOND_PKT_END = -2, 8456 }; 8457 8458 static void mark_pkt_end(struct bpf_verifier_state *vstate, int regn, bool range_open) 8459 { 8460 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 8461 struct bpf_reg_state *reg = &state->regs[regn]; 8462 8463 if (reg->type != PTR_TO_PACKET) 8464 /* PTR_TO_PACKET_META is not supported yet */ 8465 return; 8466 8467 /* The 'reg' is pkt > pkt_end or pkt >= pkt_end. 8468 * How far beyond pkt_end it goes is unknown. 8469 * if (!range_open) it's the case of pkt >= pkt_end 8470 * if (range_open) it's the case of pkt > pkt_end 8471 * hence this pointer is at least 1 byte bigger than pkt_end 8472 */ 8473 if (range_open) 8474 reg->range = BEYOND_PKT_END; 8475 else 8476 reg->range = AT_PKT_END; 8477 } 8478 8479 /* The pointer with the specified id has released its reference to kernel 8480 * resources. Identify all copies of the same pointer and clear the reference. 8481 */ 8482 static int release_reference(struct bpf_verifier_env *env, 8483 int ref_obj_id) 8484 { 8485 struct bpf_func_state *state; 8486 struct bpf_reg_state *reg; 8487 int err; 8488 8489 err = release_reference_state(cur_func(env), ref_obj_id); 8490 if (err) 8491 return err; 8492 8493 bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({ 8494 if (reg->ref_obj_id == ref_obj_id) 8495 mark_reg_invalid(env, reg); 8496 })); 8497 8498 return 0; 8499 } 8500 8501 static void invalidate_non_owning_refs(struct bpf_verifier_env *env) 8502 { 8503 struct bpf_func_state *unused; 8504 struct bpf_reg_state *reg; 8505 8506 bpf_for_each_reg_in_vstate(env->cur_state, unused, reg, ({ 8507 if (type_is_non_owning_ref(reg->type)) 8508 mark_reg_invalid(env, reg); 8509 })); 8510 } 8511 8512 static void clear_caller_saved_regs(struct bpf_verifier_env *env, 8513 struct bpf_reg_state *regs) 8514 { 8515 int i; 8516 8517 /* after the call registers r0 - r5 were scratched */ 8518 for (i = 0; i < CALLER_SAVED_REGS; i++) { 8519 mark_reg_not_init(env, regs, caller_saved[i]); 8520 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK); 8521 } 8522 } 8523 8524 typedef int (*set_callee_state_fn)(struct bpf_verifier_env *env, 8525 struct bpf_func_state *caller, 8526 struct bpf_func_state *callee, 8527 int insn_idx); 8528 8529 static int set_callee_state(struct bpf_verifier_env *env, 8530 struct bpf_func_state *caller, 8531 struct bpf_func_state *callee, int insn_idx); 8532 8533 static int __check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn, 8534 int *insn_idx, int subprog, 8535 set_callee_state_fn set_callee_state_cb) 8536 { 8537 struct bpf_verifier_state *state = env->cur_state; 8538 struct bpf_func_state *caller, *callee; 8539 int err; 8540 8541 if (state->curframe + 1 >= MAX_CALL_FRAMES) { 8542 verbose(env, "the call stack of %d frames is too deep\n", 8543 state->curframe + 2); 8544 return -E2BIG; 8545 } 8546 8547 caller = state->frame[state->curframe]; 8548 if (state->frame[state->curframe + 1]) { 8549 verbose(env, "verifier bug. Frame %d already allocated\n", 8550 state->curframe + 1); 8551 return -EFAULT; 8552 } 8553 8554 err = btf_check_subprog_call(env, subprog, caller->regs); 8555 if (err == -EFAULT) 8556 return err; 8557 if (subprog_is_global(env, subprog)) { 8558 if (err) { 8559 verbose(env, "Caller passes invalid args into func#%d\n", 8560 subprog); 8561 return err; 8562 } else { 8563 if (env->log.level & BPF_LOG_LEVEL) 8564 verbose(env, 8565 "Func#%d is global and valid. Skipping.\n", 8566 subprog); 8567 clear_caller_saved_regs(env, caller->regs); 8568 8569 /* All global functions return a 64-bit SCALAR_VALUE */ 8570 mark_reg_unknown(env, caller->regs, BPF_REG_0); 8571 caller->regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG; 8572 8573 /* continue with next insn after call */ 8574 return 0; 8575 } 8576 } 8577 8578 /* set_callee_state is used for direct subprog calls, but we are 8579 * interested in validating only BPF helpers that can call subprogs as 8580 * callbacks 8581 */ 8582 if (set_callee_state_cb != set_callee_state) { 8583 if (bpf_pseudo_kfunc_call(insn) && 8584 !is_callback_calling_kfunc(insn->imm)) { 8585 verbose(env, "verifier bug: kfunc %s#%d not marked as callback-calling\n", 8586 func_id_name(insn->imm), insn->imm); 8587 return -EFAULT; 8588 } else if (!bpf_pseudo_kfunc_call(insn) && 8589 !is_callback_calling_function(insn->imm)) { /* helper */ 8590 verbose(env, "verifier bug: helper %s#%d not marked as callback-calling\n", 8591 func_id_name(insn->imm), insn->imm); 8592 return -EFAULT; 8593 } 8594 } 8595 8596 if (insn->code == (BPF_JMP | BPF_CALL) && 8597 insn->src_reg == 0 && 8598 insn->imm == BPF_FUNC_timer_set_callback) { 8599 struct bpf_verifier_state *async_cb; 8600 8601 /* there is no real recursion here. timer callbacks are async */ 8602 env->subprog_info[subprog].is_async_cb = true; 8603 async_cb = push_async_cb(env, env->subprog_info[subprog].start, 8604 *insn_idx, subprog); 8605 if (!async_cb) 8606 return -EFAULT; 8607 callee = async_cb->frame[0]; 8608 callee->async_entry_cnt = caller->async_entry_cnt + 1; 8609 8610 /* Convert bpf_timer_set_callback() args into timer callback args */ 8611 err = set_callee_state_cb(env, caller, callee, *insn_idx); 8612 if (err) 8613 return err; 8614 8615 clear_caller_saved_regs(env, caller->regs); 8616 mark_reg_unknown(env, caller->regs, BPF_REG_0); 8617 caller->regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG; 8618 /* continue with next insn after call */ 8619 return 0; 8620 } 8621 8622 callee = kzalloc(sizeof(*callee), GFP_KERNEL); 8623 if (!callee) 8624 return -ENOMEM; 8625 state->frame[state->curframe + 1] = callee; 8626 8627 /* callee cannot access r0, r6 - r9 for reading and has to write 8628 * into its own stack before reading from it. 8629 * callee can read/write into caller's stack 8630 */ 8631 init_func_state(env, callee, 8632 /* remember the callsite, it will be used by bpf_exit */ 8633 *insn_idx /* callsite */, 8634 state->curframe + 1 /* frameno within this callchain */, 8635 subprog /* subprog number within this prog */); 8636 8637 /* Transfer references to the callee */ 8638 err = copy_reference_state(callee, caller); 8639 if (err) 8640 goto err_out; 8641 8642 err = set_callee_state_cb(env, caller, callee, *insn_idx); 8643 if (err) 8644 goto err_out; 8645 8646 clear_caller_saved_regs(env, caller->regs); 8647 8648 /* only increment it after check_reg_arg() finished */ 8649 state->curframe++; 8650 8651 /* and go analyze first insn of the callee */ 8652 *insn_idx = env->subprog_info[subprog].start - 1; 8653 8654 if (env->log.level & BPF_LOG_LEVEL) { 8655 verbose(env, "caller:\n"); 8656 print_verifier_state(env, caller, true); 8657 verbose(env, "callee:\n"); 8658 print_verifier_state(env, callee, true); 8659 } 8660 return 0; 8661 8662 err_out: 8663 free_func_state(callee); 8664 state->frame[state->curframe + 1] = NULL; 8665 return err; 8666 } 8667 8668 int map_set_for_each_callback_args(struct bpf_verifier_env *env, 8669 struct bpf_func_state *caller, 8670 struct bpf_func_state *callee) 8671 { 8672 /* bpf_for_each_map_elem(struct bpf_map *map, void *callback_fn, 8673 * void *callback_ctx, u64 flags); 8674 * callback_fn(struct bpf_map *map, void *key, void *value, 8675 * void *callback_ctx); 8676 */ 8677 callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1]; 8678 8679 callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY; 8680 __mark_reg_known_zero(&callee->regs[BPF_REG_2]); 8681 callee->regs[BPF_REG_2].map_ptr = caller->regs[BPF_REG_1].map_ptr; 8682 8683 callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE; 8684 __mark_reg_known_zero(&callee->regs[BPF_REG_3]); 8685 callee->regs[BPF_REG_3].map_ptr = caller->regs[BPF_REG_1].map_ptr; 8686 8687 /* pointer to stack or null */ 8688 callee->regs[BPF_REG_4] = caller->regs[BPF_REG_3]; 8689 8690 /* unused */ 8691 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]); 8692 return 0; 8693 } 8694 8695 static int set_callee_state(struct bpf_verifier_env *env, 8696 struct bpf_func_state *caller, 8697 struct bpf_func_state *callee, int insn_idx) 8698 { 8699 int i; 8700 8701 /* copy r1 - r5 args that callee can access. The copy includes parent 8702 * pointers, which connects us up to the liveness chain 8703 */ 8704 for (i = BPF_REG_1; i <= BPF_REG_5; i++) 8705 callee->regs[i] = caller->regs[i]; 8706 return 0; 8707 } 8708 8709 static int check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn, 8710 int *insn_idx) 8711 { 8712 int subprog, target_insn; 8713 8714 target_insn = *insn_idx + insn->imm + 1; 8715 subprog = find_subprog(env, target_insn); 8716 if (subprog < 0) { 8717 verbose(env, "verifier bug. No program starts at insn %d\n", 8718 target_insn); 8719 return -EFAULT; 8720 } 8721 8722 return __check_func_call(env, insn, insn_idx, subprog, set_callee_state); 8723 } 8724 8725 static int set_map_elem_callback_state(struct bpf_verifier_env *env, 8726 struct bpf_func_state *caller, 8727 struct bpf_func_state *callee, 8728 int insn_idx) 8729 { 8730 struct bpf_insn_aux_data *insn_aux = &env->insn_aux_data[insn_idx]; 8731 struct bpf_map *map; 8732 int err; 8733 8734 if (bpf_map_ptr_poisoned(insn_aux)) { 8735 verbose(env, "tail_call abusing map_ptr\n"); 8736 return -EINVAL; 8737 } 8738 8739 map = BPF_MAP_PTR(insn_aux->map_ptr_state); 8740 if (!map->ops->map_set_for_each_callback_args || 8741 !map->ops->map_for_each_callback) { 8742 verbose(env, "callback function not allowed for map\n"); 8743 return -ENOTSUPP; 8744 } 8745 8746 err = map->ops->map_set_for_each_callback_args(env, caller, callee); 8747 if (err) 8748 return err; 8749 8750 callee->in_callback_fn = true; 8751 callee->callback_ret_range = tnum_range(0, 1); 8752 return 0; 8753 } 8754 8755 static int set_loop_callback_state(struct bpf_verifier_env *env, 8756 struct bpf_func_state *caller, 8757 struct bpf_func_state *callee, 8758 int insn_idx) 8759 { 8760 /* bpf_loop(u32 nr_loops, void *callback_fn, void *callback_ctx, 8761 * u64 flags); 8762 * callback_fn(u32 index, void *callback_ctx); 8763 */ 8764 callee->regs[BPF_REG_1].type = SCALAR_VALUE; 8765 callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3]; 8766 8767 /* unused */ 8768 __mark_reg_not_init(env, &callee->regs[BPF_REG_3]); 8769 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]); 8770 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]); 8771 8772 callee->in_callback_fn = true; 8773 callee->callback_ret_range = tnum_range(0, 1); 8774 return 0; 8775 } 8776 8777 static int set_timer_callback_state(struct bpf_verifier_env *env, 8778 struct bpf_func_state *caller, 8779 struct bpf_func_state *callee, 8780 int insn_idx) 8781 { 8782 struct bpf_map *map_ptr = caller->regs[BPF_REG_1].map_ptr; 8783 8784 /* bpf_timer_set_callback(struct bpf_timer *timer, void *callback_fn); 8785 * callback_fn(struct bpf_map *map, void *key, void *value); 8786 */ 8787 callee->regs[BPF_REG_1].type = CONST_PTR_TO_MAP; 8788 __mark_reg_known_zero(&callee->regs[BPF_REG_1]); 8789 callee->regs[BPF_REG_1].map_ptr = map_ptr; 8790 8791 callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY; 8792 __mark_reg_known_zero(&callee->regs[BPF_REG_2]); 8793 callee->regs[BPF_REG_2].map_ptr = map_ptr; 8794 8795 callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE; 8796 __mark_reg_known_zero(&callee->regs[BPF_REG_3]); 8797 callee->regs[BPF_REG_3].map_ptr = map_ptr; 8798 8799 /* unused */ 8800 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]); 8801 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]); 8802 callee->in_async_callback_fn = true; 8803 callee->callback_ret_range = tnum_range(0, 1); 8804 return 0; 8805 } 8806 8807 static int set_find_vma_callback_state(struct bpf_verifier_env *env, 8808 struct bpf_func_state *caller, 8809 struct bpf_func_state *callee, 8810 int insn_idx) 8811 { 8812 /* bpf_find_vma(struct task_struct *task, u64 addr, 8813 * void *callback_fn, void *callback_ctx, u64 flags) 8814 * (callback_fn)(struct task_struct *task, 8815 * struct vm_area_struct *vma, void *callback_ctx); 8816 */ 8817 callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1]; 8818 8819 callee->regs[BPF_REG_2].type = PTR_TO_BTF_ID; 8820 __mark_reg_known_zero(&callee->regs[BPF_REG_2]); 8821 callee->regs[BPF_REG_2].btf = btf_vmlinux; 8822 callee->regs[BPF_REG_2].btf_id = btf_tracing_ids[BTF_TRACING_TYPE_VMA], 8823 8824 /* pointer to stack or null */ 8825 callee->regs[BPF_REG_3] = caller->regs[BPF_REG_4]; 8826 8827 /* unused */ 8828 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]); 8829 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]); 8830 callee->in_callback_fn = true; 8831 callee->callback_ret_range = tnum_range(0, 1); 8832 return 0; 8833 } 8834 8835 static int set_user_ringbuf_callback_state(struct bpf_verifier_env *env, 8836 struct bpf_func_state *caller, 8837 struct bpf_func_state *callee, 8838 int insn_idx) 8839 { 8840 /* bpf_user_ringbuf_drain(struct bpf_map *map, void *callback_fn, void 8841 * callback_ctx, u64 flags); 8842 * callback_fn(const struct bpf_dynptr_t* dynptr, void *callback_ctx); 8843 */ 8844 __mark_reg_not_init(env, &callee->regs[BPF_REG_0]); 8845 mark_dynptr_cb_reg(env, &callee->regs[BPF_REG_1], BPF_DYNPTR_TYPE_LOCAL); 8846 callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3]; 8847 8848 /* unused */ 8849 __mark_reg_not_init(env, &callee->regs[BPF_REG_3]); 8850 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]); 8851 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]); 8852 8853 callee->in_callback_fn = true; 8854 callee->callback_ret_range = tnum_range(0, 1); 8855 return 0; 8856 } 8857 8858 static int set_rbtree_add_callback_state(struct bpf_verifier_env *env, 8859 struct bpf_func_state *caller, 8860 struct bpf_func_state *callee, 8861 int insn_idx) 8862 { 8863 /* void bpf_rbtree_add_impl(struct bpf_rb_root *root, struct bpf_rb_node *node, 8864 * bool (less)(struct bpf_rb_node *a, const struct bpf_rb_node *b)); 8865 * 8866 * 'struct bpf_rb_node *node' arg to bpf_rbtree_add_impl is the same PTR_TO_BTF_ID w/ offset 8867 * that 'less' callback args will be receiving. However, 'node' arg was release_reference'd 8868 * by this point, so look at 'root' 8869 */ 8870 struct btf_field *field; 8871 8872 field = reg_find_field_offset(&caller->regs[BPF_REG_1], caller->regs[BPF_REG_1].off, 8873 BPF_RB_ROOT); 8874 if (!field || !field->graph_root.value_btf_id) 8875 return -EFAULT; 8876 8877 mark_reg_graph_node(callee->regs, BPF_REG_1, &field->graph_root); 8878 ref_set_non_owning(env, &callee->regs[BPF_REG_1]); 8879 mark_reg_graph_node(callee->regs, BPF_REG_2, &field->graph_root); 8880 ref_set_non_owning(env, &callee->regs[BPF_REG_2]); 8881 8882 __mark_reg_not_init(env, &callee->regs[BPF_REG_3]); 8883 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]); 8884 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]); 8885 callee->in_callback_fn = true; 8886 callee->callback_ret_range = tnum_range(0, 1); 8887 return 0; 8888 } 8889 8890 static bool is_rbtree_lock_required_kfunc(u32 btf_id); 8891 8892 /* Are we currently verifying the callback for a rbtree helper that must 8893 * be called with lock held? If so, no need to complain about unreleased 8894 * lock 8895 */ 8896 static bool in_rbtree_lock_required_cb(struct bpf_verifier_env *env) 8897 { 8898 struct bpf_verifier_state *state = env->cur_state; 8899 struct bpf_insn *insn = env->prog->insnsi; 8900 struct bpf_func_state *callee; 8901 int kfunc_btf_id; 8902 8903 if (!state->curframe) 8904 return false; 8905 8906 callee = state->frame[state->curframe]; 8907 8908 if (!callee->in_callback_fn) 8909 return false; 8910 8911 kfunc_btf_id = insn[callee->callsite].imm; 8912 return is_rbtree_lock_required_kfunc(kfunc_btf_id); 8913 } 8914 8915 static int prepare_func_exit(struct bpf_verifier_env *env, int *insn_idx) 8916 { 8917 struct bpf_verifier_state *state = env->cur_state; 8918 struct bpf_func_state *caller, *callee; 8919 struct bpf_reg_state *r0; 8920 int err; 8921 8922 callee = state->frame[state->curframe]; 8923 r0 = &callee->regs[BPF_REG_0]; 8924 if (r0->type == PTR_TO_STACK) { 8925 /* technically it's ok to return caller's stack pointer 8926 * (or caller's caller's pointer) back to the caller, 8927 * since these pointers are valid. Only current stack 8928 * pointer will be invalid as soon as function exits, 8929 * but let's be conservative 8930 */ 8931 verbose(env, "cannot return stack pointer to the caller\n"); 8932 return -EINVAL; 8933 } 8934 8935 caller = state->frame[state->curframe - 1]; 8936 if (callee->in_callback_fn) { 8937 /* enforce R0 return value range [0, 1]. */ 8938 struct tnum range = callee->callback_ret_range; 8939 8940 if (r0->type != SCALAR_VALUE) { 8941 verbose(env, "R0 not a scalar value\n"); 8942 return -EACCES; 8943 } 8944 if (!tnum_in(range, r0->var_off)) { 8945 verbose_invalid_scalar(env, r0, &range, "callback return", "R0"); 8946 return -EINVAL; 8947 } 8948 } else { 8949 /* return to the caller whatever r0 had in the callee */ 8950 caller->regs[BPF_REG_0] = *r0; 8951 } 8952 8953 /* callback_fn frame should have released its own additions to parent's 8954 * reference state at this point, or check_reference_leak would 8955 * complain, hence it must be the same as the caller. There is no need 8956 * to copy it back. 8957 */ 8958 if (!callee->in_callback_fn) { 8959 /* Transfer references to the caller */ 8960 err = copy_reference_state(caller, callee); 8961 if (err) 8962 return err; 8963 } 8964 8965 *insn_idx = callee->callsite + 1; 8966 if (env->log.level & BPF_LOG_LEVEL) { 8967 verbose(env, "returning from callee:\n"); 8968 print_verifier_state(env, callee, true); 8969 verbose(env, "to caller at %d:\n", *insn_idx); 8970 print_verifier_state(env, caller, true); 8971 } 8972 /* clear everything in the callee */ 8973 free_func_state(callee); 8974 state->frame[state->curframe--] = NULL; 8975 return 0; 8976 } 8977 8978 static void do_refine_retval_range(struct bpf_reg_state *regs, int ret_type, 8979 int func_id, 8980 struct bpf_call_arg_meta *meta) 8981 { 8982 struct bpf_reg_state *ret_reg = ®s[BPF_REG_0]; 8983 8984 if (ret_type != RET_INTEGER || 8985 (func_id != BPF_FUNC_get_stack && 8986 func_id != BPF_FUNC_get_task_stack && 8987 func_id != BPF_FUNC_probe_read_str && 8988 func_id != BPF_FUNC_probe_read_kernel_str && 8989 func_id != BPF_FUNC_probe_read_user_str)) 8990 return; 8991 8992 ret_reg->smax_value = meta->msize_max_value; 8993 ret_reg->s32_max_value = meta->msize_max_value; 8994 ret_reg->smin_value = -MAX_ERRNO; 8995 ret_reg->s32_min_value = -MAX_ERRNO; 8996 reg_bounds_sync(ret_reg); 8997 } 8998 8999 static int 9000 record_func_map(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta, 9001 int func_id, int insn_idx) 9002 { 9003 struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx]; 9004 struct bpf_map *map = meta->map_ptr; 9005 9006 if (func_id != BPF_FUNC_tail_call && 9007 func_id != BPF_FUNC_map_lookup_elem && 9008 func_id != BPF_FUNC_map_update_elem && 9009 func_id != BPF_FUNC_map_delete_elem && 9010 func_id != BPF_FUNC_map_push_elem && 9011 func_id != BPF_FUNC_map_pop_elem && 9012 func_id != BPF_FUNC_map_peek_elem && 9013 func_id != BPF_FUNC_for_each_map_elem && 9014 func_id != BPF_FUNC_redirect_map && 9015 func_id != BPF_FUNC_map_lookup_percpu_elem) 9016 return 0; 9017 9018 if (map == NULL) { 9019 verbose(env, "kernel subsystem misconfigured verifier\n"); 9020 return -EINVAL; 9021 } 9022 9023 /* In case of read-only, some additional restrictions 9024 * need to be applied in order to prevent altering the 9025 * state of the map from program side. 9026 */ 9027 if ((map->map_flags & BPF_F_RDONLY_PROG) && 9028 (func_id == BPF_FUNC_map_delete_elem || 9029 func_id == BPF_FUNC_map_update_elem || 9030 func_id == BPF_FUNC_map_push_elem || 9031 func_id == BPF_FUNC_map_pop_elem)) { 9032 verbose(env, "write into map forbidden\n"); 9033 return -EACCES; 9034 } 9035 9036 if (!BPF_MAP_PTR(aux->map_ptr_state)) 9037 bpf_map_ptr_store(aux, meta->map_ptr, 9038 !meta->map_ptr->bypass_spec_v1); 9039 else if (BPF_MAP_PTR(aux->map_ptr_state) != meta->map_ptr) 9040 bpf_map_ptr_store(aux, BPF_MAP_PTR_POISON, 9041 !meta->map_ptr->bypass_spec_v1); 9042 return 0; 9043 } 9044 9045 static int 9046 record_func_key(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta, 9047 int func_id, int insn_idx) 9048 { 9049 struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx]; 9050 struct bpf_reg_state *regs = cur_regs(env), *reg; 9051 struct bpf_map *map = meta->map_ptr; 9052 u64 val, max; 9053 int err; 9054 9055 if (func_id != BPF_FUNC_tail_call) 9056 return 0; 9057 if (!map || map->map_type != BPF_MAP_TYPE_PROG_ARRAY) { 9058 verbose(env, "kernel subsystem misconfigured verifier\n"); 9059 return -EINVAL; 9060 } 9061 9062 reg = ®s[BPF_REG_3]; 9063 val = reg->var_off.value; 9064 max = map->max_entries; 9065 9066 if (!(register_is_const(reg) && val < max)) { 9067 bpf_map_key_store(aux, BPF_MAP_KEY_POISON); 9068 return 0; 9069 } 9070 9071 err = mark_chain_precision(env, BPF_REG_3); 9072 if (err) 9073 return err; 9074 if (bpf_map_key_unseen(aux)) 9075 bpf_map_key_store(aux, val); 9076 else if (!bpf_map_key_poisoned(aux) && 9077 bpf_map_key_immediate(aux) != val) 9078 bpf_map_key_store(aux, BPF_MAP_KEY_POISON); 9079 return 0; 9080 } 9081 9082 static int check_reference_leak(struct bpf_verifier_env *env) 9083 { 9084 struct bpf_func_state *state = cur_func(env); 9085 bool refs_lingering = false; 9086 int i; 9087 9088 if (state->frameno && !state->in_callback_fn) 9089 return 0; 9090 9091 for (i = 0; i < state->acquired_refs; i++) { 9092 if (state->in_callback_fn && state->refs[i].callback_ref != state->frameno) 9093 continue; 9094 verbose(env, "Unreleased reference id=%d alloc_insn=%d\n", 9095 state->refs[i].id, state->refs[i].insn_idx); 9096 refs_lingering = true; 9097 } 9098 return refs_lingering ? -EINVAL : 0; 9099 } 9100 9101 static int check_bpf_snprintf_call(struct bpf_verifier_env *env, 9102 struct bpf_reg_state *regs) 9103 { 9104 struct bpf_reg_state *fmt_reg = ®s[BPF_REG_3]; 9105 struct bpf_reg_state *data_len_reg = ®s[BPF_REG_5]; 9106 struct bpf_map *fmt_map = fmt_reg->map_ptr; 9107 struct bpf_bprintf_data data = {}; 9108 int err, fmt_map_off, num_args; 9109 u64 fmt_addr; 9110 char *fmt; 9111 9112 /* data must be an array of u64 */ 9113 if (data_len_reg->var_off.value % 8) 9114 return -EINVAL; 9115 num_args = data_len_reg->var_off.value / 8; 9116 9117 /* fmt being ARG_PTR_TO_CONST_STR guarantees that var_off is const 9118 * and map_direct_value_addr is set. 9119 */ 9120 fmt_map_off = fmt_reg->off + fmt_reg->var_off.value; 9121 err = fmt_map->ops->map_direct_value_addr(fmt_map, &fmt_addr, 9122 fmt_map_off); 9123 if (err) { 9124 verbose(env, "verifier bug\n"); 9125 return -EFAULT; 9126 } 9127 fmt = (char *)(long)fmt_addr + fmt_map_off; 9128 9129 /* We are also guaranteed that fmt+fmt_map_off is NULL terminated, we 9130 * can focus on validating the format specifiers. 9131 */ 9132 err = bpf_bprintf_prepare(fmt, UINT_MAX, NULL, num_args, &data); 9133 if (err < 0) 9134 verbose(env, "Invalid format string\n"); 9135 9136 return err; 9137 } 9138 9139 static int check_get_func_ip(struct bpf_verifier_env *env) 9140 { 9141 enum bpf_prog_type type = resolve_prog_type(env->prog); 9142 int func_id = BPF_FUNC_get_func_ip; 9143 9144 if (type == BPF_PROG_TYPE_TRACING) { 9145 if (!bpf_prog_has_trampoline(env->prog)) { 9146 verbose(env, "func %s#%d supported only for fentry/fexit/fmod_ret programs\n", 9147 func_id_name(func_id), func_id); 9148 return -ENOTSUPP; 9149 } 9150 return 0; 9151 } else if (type == BPF_PROG_TYPE_KPROBE) { 9152 return 0; 9153 } 9154 9155 verbose(env, "func %s#%d not supported for program type %d\n", 9156 func_id_name(func_id), func_id, type); 9157 return -ENOTSUPP; 9158 } 9159 9160 static struct bpf_insn_aux_data *cur_aux(struct bpf_verifier_env *env) 9161 { 9162 return &env->insn_aux_data[env->insn_idx]; 9163 } 9164 9165 static bool loop_flag_is_zero(struct bpf_verifier_env *env) 9166 { 9167 struct bpf_reg_state *regs = cur_regs(env); 9168 struct bpf_reg_state *reg = ®s[BPF_REG_4]; 9169 bool reg_is_null = register_is_null(reg); 9170 9171 if (reg_is_null) 9172 mark_chain_precision(env, BPF_REG_4); 9173 9174 return reg_is_null; 9175 } 9176 9177 static void update_loop_inline_state(struct bpf_verifier_env *env, u32 subprogno) 9178 { 9179 struct bpf_loop_inline_state *state = &cur_aux(env)->loop_inline_state; 9180 9181 if (!state->initialized) { 9182 state->initialized = 1; 9183 state->fit_for_inline = loop_flag_is_zero(env); 9184 state->callback_subprogno = subprogno; 9185 return; 9186 } 9187 9188 if (!state->fit_for_inline) 9189 return; 9190 9191 state->fit_for_inline = (loop_flag_is_zero(env) && 9192 state->callback_subprogno == subprogno); 9193 } 9194 9195 static int check_helper_call(struct bpf_verifier_env *env, struct bpf_insn *insn, 9196 int *insn_idx_p) 9197 { 9198 enum bpf_prog_type prog_type = resolve_prog_type(env->prog); 9199 const struct bpf_func_proto *fn = NULL; 9200 enum bpf_return_type ret_type; 9201 enum bpf_type_flag ret_flag; 9202 struct bpf_reg_state *regs; 9203 struct bpf_call_arg_meta meta; 9204 int insn_idx = *insn_idx_p; 9205 bool changes_data; 9206 int i, err, func_id; 9207 9208 /* find function prototype */ 9209 func_id = insn->imm; 9210 if (func_id < 0 || func_id >= __BPF_FUNC_MAX_ID) { 9211 verbose(env, "invalid func %s#%d\n", func_id_name(func_id), 9212 func_id); 9213 return -EINVAL; 9214 } 9215 9216 if (env->ops->get_func_proto) 9217 fn = env->ops->get_func_proto(func_id, env->prog); 9218 if (!fn) { 9219 verbose(env, "unknown func %s#%d\n", func_id_name(func_id), 9220 func_id); 9221 return -EINVAL; 9222 } 9223 9224 /* eBPF programs must be GPL compatible to use GPL-ed functions */ 9225 if (!env->prog->gpl_compatible && fn->gpl_only) { 9226 verbose(env, "cannot call GPL-restricted function from non-GPL compatible program\n"); 9227 return -EINVAL; 9228 } 9229 9230 if (fn->allowed && !fn->allowed(env->prog)) { 9231 verbose(env, "helper call is not allowed in probe\n"); 9232 return -EINVAL; 9233 } 9234 9235 if (!env->prog->aux->sleepable && fn->might_sleep) { 9236 verbose(env, "helper call might sleep in a non-sleepable prog\n"); 9237 return -EINVAL; 9238 } 9239 9240 /* With LD_ABS/IND some JITs save/restore skb from r1. */ 9241 changes_data = bpf_helper_changes_pkt_data(fn->func); 9242 if (changes_data && fn->arg1_type != ARG_PTR_TO_CTX) { 9243 verbose(env, "kernel subsystem misconfigured func %s#%d: r1 != ctx\n", 9244 func_id_name(func_id), func_id); 9245 return -EINVAL; 9246 } 9247 9248 memset(&meta, 0, sizeof(meta)); 9249 meta.pkt_access = fn->pkt_access; 9250 9251 err = check_func_proto(fn, func_id); 9252 if (err) { 9253 verbose(env, "kernel subsystem misconfigured func %s#%d\n", 9254 func_id_name(func_id), func_id); 9255 return err; 9256 } 9257 9258 if (env->cur_state->active_rcu_lock) { 9259 if (fn->might_sleep) { 9260 verbose(env, "sleepable helper %s#%d in rcu_read_lock region\n", 9261 func_id_name(func_id), func_id); 9262 return -EINVAL; 9263 } 9264 9265 if (env->prog->aux->sleepable && is_storage_get_function(func_id)) 9266 env->insn_aux_data[insn_idx].storage_get_func_atomic = true; 9267 } 9268 9269 meta.func_id = func_id; 9270 /* check args */ 9271 for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++) { 9272 err = check_func_arg(env, i, &meta, fn, insn_idx); 9273 if (err) 9274 return err; 9275 } 9276 9277 err = record_func_map(env, &meta, func_id, insn_idx); 9278 if (err) 9279 return err; 9280 9281 err = record_func_key(env, &meta, func_id, insn_idx); 9282 if (err) 9283 return err; 9284 9285 /* Mark slots with STACK_MISC in case of raw mode, stack offset 9286 * is inferred from register state. 9287 */ 9288 for (i = 0; i < meta.access_size; i++) { 9289 err = check_mem_access(env, insn_idx, meta.regno, i, BPF_B, 9290 BPF_WRITE, -1, false); 9291 if (err) 9292 return err; 9293 } 9294 9295 regs = cur_regs(env); 9296 9297 if (meta.release_regno) { 9298 err = -EINVAL; 9299 /* This can only be set for PTR_TO_STACK, as CONST_PTR_TO_DYNPTR cannot 9300 * be released by any dynptr helper. Hence, unmark_stack_slots_dynptr 9301 * is safe to do directly. 9302 */ 9303 if (arg_type_is_dynptr(fn->arg_type[meta.release_regno - BPF_REG_1])) { 9304 if (regs[meta.release_regno].type == CONST_PTR_TO_DYNPTR) { 9305 verbose(env, "verifier internal error: CONST_PTR_TO_DYNPTR cannot be released\n"); 9306 return -EFAULT; 9307 } 9308 err = unmark_stack_slots_dynptr(env, ®s[meta.release_regno]); 9309 } else if (meta.ref_obj_id) { 9310 err = release_reference(env, meta.ref_obj_id); 9311 } else if (register_is_null(®s[meta.release_regno])) { 9312 /* meta.ref_obj_id can only be 0 if register that is meant to be 9313 * released is NULL, which must be > R0. 9314 */ 9315 err = 0; 9316 } 9317 if (err) { 9318 verbose(env, "func %s#%d reference has not been acquired before\n", 9319 func_id_name(func_id), func_id); 9320 return err; 9321 } 9322 } 9323 9324 switch (func_id) { 9325 case BPF_FUNC_tail_call: 9326 err = check_reference_leak(env); 9327 if (err) { 9328 verbose(env, "tail_call would lead to reference leak\n"); 9329 return err; 9330 } 9331 break; 9332 case BPF_FUNC_get_local_storage: 9333 /* check that flags argument in get_local_storage(map, flags) is 0, 9334 * this is required because get_local_storage() can't return an error. 9335 */ 9336 if (!register_is_null(®s[BPF_REG_2])) { 9337 verbose(env, "get_local_storage() doesn't support non-zero flags\n"); 9338 return -EINVAL; 9339 } 9340 break; 9341 case BPF_FUNC_for_each_map_elem: 9342 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno, 9343 set_map_elem_callback_state); 9344 break; 9345 case BPF_FUNC_timer_set_callback: 9346 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno, 9347 set_timer_callback_state); 9348 break; 9349 case BPF_FUNC_find_vma: 9350 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno, 9351 set_find_vma_callback_state); 9352 break; 9353 case BPF_FUNC_snprintf: 9354 err = check_bpf_snprintf_call(env, regs); 9355 break; 9356 case BPF_FUNC_loop: 9357 update_loop_inline_state(env, meta.subprogno); 9358 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno, 9359 set_loop_callback_state); 9360 break; 9361 case BPF_FUNC_dynptr_from_mem: 9362 if (regs[BPF_REG_1].type != PTR_TO_MAP_VALUE) { 9363 verbose(env, "Unsupported reg type %s for bpf_dynptr_from_mem data\n", 9364 reg_type_str(env, regs[BPF_REG_1].type)); 9365 return -EACCES; 9366 } 9367 break; 9368 case BPF_FUNC_set_retval: 9369 if (prog_type == BPF_PROG_TYPE_LSM && 9370 env->prog->expected_attach_type == BPF_LSM_CGROUP) { 9371 if (!env->prog->aux->attach_func_proto->type) { 9372 /* Make sure programs that attach to void 9373 * hooks don't try to modify return value. 9374 */ 9375 verbose(env, "BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n"); 9376 return -EINVAL; 9377 } 9378 } 9379 break; 9380 case BPF_FUNC_dynptr_data: 9381 { 9382 struct bpf_reg_state *reg; 9383 int id, ref_obj_id; 9384 9385 reg = get_dynptr_arg_reg(env, fn, regs); 9386 if (!reg) 9387 return -EFAULT; 9388 9389 9390 if (meta.dynptr_id) { 9391 verbose(env, "verifier internal error: meta.dynptr_id already set\n"); 9392 return -EFAULT; 9393 } 9394 if (meta.ref_obj_id) { 9395 verbose(env, "verifier internal error: meta.ref_obj_id already set\n"); 9396 return -EFAULT; 9397 } 9398 9399 id = dynptr_id(env, reg); 9400 if (id < 0) { 9401 verbose(env, "verifier internal error: failed to obtain dynptr id\n"); 9402 return id; 9403 } 9404 9405 ref_obj_id = dynptr_ref_obj_id(env, reg); 9406 if (ref_obj_id < 0) { 9407 verbose(env, "verifier internal error: failed to obtain dynptr ref_obj_id\n"); 9408 return ref_obj_id; 9409 } 9410 9411 meta.dynptr_id = id; 9412 meta.ref_obj_id = ref_obj_id; 9413 9414 break; 9415 } 9416 case BPF_FUNC_dynptr_write: 9417 { 9418 enum bpf_dynptr_type dynptr_type; 9419 struct bpf_reg_state *reg; 9420 9421 reg = get_dynptr_arg_reg(env, fn, regs); 9422 if (!reg) 9423 return -EFAULT; 9424 9425 dynptr_type = dynptr_get_type(env, reg); 9426 if (dynptr_type == BPF_DYNPTR_TYPE_INVALID) 9427 return -EFAULT; 9428 9429 if (dynptr_type == BPF_DYNPTR_TYPE_SKB) 9430 /* this will trigger clear_all_pkt_pointers(), which will 9431 * invalidate all dynptr slices associated with the skb 9432 */ 9433 changes_data = true; 9434 9435 break; 9436 } 9437 case BPF_FUNC_user_ringbuf_drain: 9438 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno, 9439 set_user_ringbuf_callback_state); 9440 break; 9441 } 9442 9443 if (err) 9444 return err; 9445 9446 /* reset caller saved regs */ 9447 for (i = 0; i < CALLER_SAVED_REGS; i++) { 9448 mark_reg_not_init(env, regs, caller_saved[i]); 9449 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK); 9450 } 9451 9452 /* helper call returns 64-bit value. */ 9453 regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG; 9454 9455 /* update return register (already marked as written above) */ 9456 ret_type = fn->ret_type; 9457 ret_flag = type_flag(ret_type); 9458 9459 switch (base_type(ret_type)) { 9460 case RET_INTEGER: 9461 /* sets type to SCALAR_VALUE */ 9462 mark_reg_unknown(env, regs, BPF_REG_0); 9463 break; 9464 case RET_VOID: 9465 regs[BPF_REG_0].type = NOT_INIT; 9466 break; 9467 case RET_PTR_TO_MAP_VALUE: 9468 /* There is no offset yet applied, variable or fixed */ 9469 mark_reg_known_zero(env, regs, BPF_REG_0); 9470 /* remember map_ptr, so that check_map_access() 9471 * can check 'value_size' boundary of memory access 9472 * to map element returned from bpf_map_lookup_elem() 9473 */ 9474 if (meta.map_ptr == NULL) { 9475 verbose(env, 9476 "kernel subsystem misconfigured verifier\n"); 9477 return -EINVAL; 9478 } 9479 regs[BPF_REG_0].map_ptr = meta.map_ptr; 9480 regs[BPF_REG_0].map_uid = meta.map_uid; 9481 regs[BPF_REG_0].type = PTR_TO_MAP_VALUE | ret_flag; 9482 if (!type_may_be_null(ret_type) && 9483 btf_record_has_field(meta.map_ptr->record, BPF_SPIN_LOCK)) { 9484 regs[BPF_REG_0].id = ++env->id_gen; 9485 } 9486 break; 9487 case RET_PTR_TO_SOCKET: 9488 mark_reg_known_zero(env, regs, BPF_REG_0); 9489 regs[BPF_REG_0].type = PTR_TO_SOCKET | ret_flag; 9490 break; 9491 case RET_PTR_TO_SOCK_COMMON: 9492 mark_reg_known_zero(env, regs, BPF_REG_0); 9493 regs[BPF_REG_0].type = PTR_TO_SOCK_COMMON | ret_flag; 9494 break; 9495 case RET_PTR_TO_TCP_SOCK: 9496 mark_reg_known_zero(env, regs, BPF_REG_0); 9497 regs[BPF_REG_0].type = PTR_TO_TCP_SOCK | ret_flag; 9498 break; 9499 case RET_PTR_TO_MEM: 9500 mark_reg_known_zero(env, regs, BPF_REG_0); 9501 regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag; 9502 regs[BPF_REG_0].mem_size = meta.mem_size; 9503 break; 9504 case RET_PTR_TO_MEM_OR_BTF_ID: 9505 { 9506 const struct btf_type *t; 9507 9508 mark_reg_known_zero(env, regs, BPF_REG_0); 9509 t = btf_type_skip_modifiers(meta.ret_btf, meta.ret_btf_id, NULL); 9510 if (!btf_type_is_struct(t)) { 9511 u32 tsize; 9512 const struct btf_type *ret; 9513 const char *tname; 9514 9515 /* resolve the type size of ksym. */ 9516 ret = btf_resolve_size(meta.ret_btf, t, &tsize); 9517 if (IS_ERR(ret)) { 9518 tname = btf_name_by_offset(meta.ret_btf, t->name_off); 9519 verbose(env, "unable to resolve the size of type '%s': %ld\n", 9520 tname, PTR_ERR(ret)); 9521 return -EINVAL; 9522 } 9523 regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag; 9524 regs[BPF_REG_0].mem_size = tsize; 9525 } else { 9526 /* MEM_RDONLY may be carried from ret_flag, but it 9527 * doesn't apply on PTR_TO_BTF_ID. Fold it, otherwise 9528 * it will confuse the check of PTR_TO_BTF_ID in 9529 * check_mem_access(). 9530 */ 9531 ret_flag &= ~MEM_RDONLY; 9532 9533 regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag; 9534 regs[BPF_REG_0].btf = meta.ret_btf; 9535 regs[BPF_REG_0].btf_id = meta.ret_btf_id; 9536 } 9537 break; 9538 } 9539 case RET_PTR_TO_BTF_ID: 9540 { 9541 struct btf *ret_btf; 9542 int ret_btf_id; 9543 9544 mark_reg_known_zero(env, regs, BPF_REG_0); 9545 regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag; 9546 if (func_id == BPF_FUNC_kptr_xchg) { 9547 ret_btf = meta.kptr_field->kptr.btf; 9548 ret_btf_id = meta.kptr_field->kptr.btf_id; 9549 if (!btf_is_kernel(ret_btf)) 9550 regs[BPF_REG_0].type |= MEM_ALLOC; 9551 } else { 9552 if (fn->ret_btf_id == BPF_PTR_POISON) { 9553 verbose(env, "verifier internal error:"); 9554 verbose(env, "func %s has non-overwritten BPF_PTR_POISON return type\n", 9555 func_id_name(func_id)); 9556 return -EINVAL; 9557 } 9558 ret_btf = btf_vmlinux; 9559 ret_btf_id = *fn->ret_btf_id; 9560 } 9561 if (ret_btf_id == 0) { 9562 verbose(env, "invalid return type %u of func %s#%d\n", 9563 base_type(ret_type), func_id_name(func_id), 9564 func_id); 9565 return -EINVAL; 9566 } 9567 regs[BPF_REG_0].btf = ret_btf; 9568 regs[BPF_REG_0].btf_id = ret_btf_id; 9569 break; 9570 } 9571 default: 9572 verbose(env, "unknown return type %u of func %s#%d\n", 9573 base_type(ret_type), func_id_name(func_id), func_id); 9574 return -EINVAL; 9575 } 9576 9577 if (type_may_be_null(regs[BPF_REG_0].type)) 9578 regs[BPF_REG_0].id = ++env->id_gen; 9579 9580 if (helper_multiple_ref_obj_use(func_id, meta.map_ptr)) { 9581 verbose(env, "verifier internal error: func %s#%d sets ref_obj_id more than once\n", 9582 func_id_name(func_id), func_id); 9583 return -EFAULT; 9584 } 9585 9586 if (is_dynptr_ref_function(func_id)) 9587 regs[BPF_REG_0].dynptr_id = meta.dynptr_id; 9588 9589 if (is_ptr_cast_function(func_id) || is_dynptr_ref_function(func_id)) { 9590 /* For release_reference() */ 9591 regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id; 9592 } else if (is_acquire_function(func_id, meta.map_ptr)) { 9593 int id = acquire_reference_state(env, insn_idx); 9594 9595 if (id < 0) 9596 return id; 9597 /* For mark_ptr_or_null_reg() */ 9598 regs[BPF_REG_0].id = id; 9599 /* For release_reference() */ 9600 regs[BPF_REG_0].ref_obj_id = id; 9601 } 9602 9603 do_refine_retval_range(regs, fn->ret_type, func_id, &meta); 9604 9605 err = check_map_func_compatibility(env, meta.map_ptr, func_id); 9606 if (err) 9607 return err; 9608 9609 if ((func_id == BPF_FUNC_get_stack || 9610 func_id == BPF_FUNC_get_task_stack) && 9611 !env->prog->has_callchain_buf) { 9612 const char *err_str; 9613 9614 #ifdef CONFIG_PERF_EVENTS 9615 err = get_callchain_buffers(sysctl_perf_event_max_stack); 9616 err_str = "cannot get callchain buffer for func %s#%d\n"; 9617 #else 9618 err = -ENOTSUPP; 9619 err_str = "func %s#%d not supported without CONFIG_PERF_EVENTS\n"; 9620 #endif 9621 if (err) { 9622 verbose(env, err_str, func_id_name(func_id), func_id); 9623 return err; 9624 } 9625 9626 env->prog->has_callchain_buf = true; 9627 } 9628 9629 if (func_id == BPF_FUNC_get_stackid || func_id == BPF_FUNC_get_stack) 9630 env->prog->call_get_stack = true; 9631 9632 if (func_id == BPF_FUNC_get_func_ip) { 9633 if (check_get_func_ip(env)) 9634 return -ENOTSUPP; 9635 env->prog->call_get_func_ip = true; 9636 } 9637 9638 if (changes_data) 9639 clear_all_pkt_pointers(env); 9640 return 0; 9641 } 9642 9643 /* mark_btf_func_reg_size() is used when the reg size is determined by 9644 * the BTF func_proto's return value size and argument. 9645 */ 9646 static void mark_btf_func_reg_size(struct bpf_verifier_env *env, u32 regno, 9647 size_t reg_size) 9648 { 9649 struct bpf_reg_state *reg = &cur_regs(env)[regno]; 9650 9651 if (regno == BPF_REG_0) { 9652 /* Function return value */ 9653 reg->live |= REG_LIVE_WRITTEN; 9654 reg->subreg_def = reg_size == sizeof(u64) ? 9655 DEF_NOT_SUBREG : env->insn_idx + 1; 9656 } else { 9657 /* Function argument */ 9658 if (reg_size == sizeof(u64)) { 9659 mark_insn_zext(env, reg); 9660 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64); 9661 } else { 9662 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ32); 9663 } 9664 } 9665 } 9666 9667 static bool is_kfunc_acquire(struct bpf_kfunc_call_arg_meta *meta) 9668 { 9669 return meta->kfunc_flags & KF_ACQUIRE; 9670 } 9671 9672 static bool is_kfunc_ret_null(struct bpf_kfunc_call_arg_meta *meta) 9673 { 9674 return meta->kfunc_flags & KF_RET_NULL; 9675 } 9676 9677 static bool is_kfunc_release(struct bpf_kfunc_call_arg_meta *meta) 9678 { 9679 return meta->kfunc_flags & KF_RELEASE; 9680 } 9681 9682 static bool is_kfunc_trusted_args(struct bpf_kfunc_call_arg_meta *meta) 9683 { 9684 return (meta->kfunc_flags & KF_TRUSTED_ARGS) || is_kfunc_release(meta); 9685 } 9686 9687 static bool is_kfunc_sleepable(struct bpf_kfunc_call_arg_meta *meta) 9688 { 9689 return meta->kfunc_flags & KF_SLEEPABLE; 9690 } 9691 9692 static bool is_kfunc_destructive(struct bpf_kfunc_call_arg_meta *meta) 9693 { 9694 return meta->kfunc_flags & KF_DESTRUCTIVE; 9695 } 9696 9697 static bool is_kfunc_rcu(struct bpf_kfunc_call_arg_meta *meta) 9698 { 9699 return meta->kfunc_flags & KF_RCU; 9700 } 9701 9702 static bool __kfunc_param_match_suffix(const struct btf *btf, 9703 const struct btf_param *arg, 9704 const char *suffix) 9705 { 9706 int suffix_len = strlen(suffix), len; 9707 const char *param_name; 9708 9709 /* In the future, this can be ported to use BTF tagging */ 9710 param_name = btf_name_by_offset(btf, arg->name_off); 9711 if (str_is_empty(param_name)) 9712 return false; 9713 len = strlen(param_name); 9714 if (len < suffix_len) 9715 return false; 9716 param_name += len - suffix_len; 9717 return !strncmp(param_name, suffix, suffix_len); 9718 } 9719 9720 static bool is_kfunc_arg_mem_size(const struct btf *btf, 9721 const struct btf_param *arg, 9722 const struct bpf_reg_state *reg) 9723 { 9724 const struct btf_type *t; 9725 9726 t = btf_type_skip_modifiers(btf, arg->type, NULL); 9727 if (!btf_type_is_scalar(t) || reg->type != SCALAR_VALUE) 9728 return false; 9729 9730 return __kfunc_param_match_suffix(btf, arg, "__sz"); 9731 } 9732 9733 static bool is_kfunc_arg_const_mem_size(const struct btf *btf, 9734 const struct btf_param *arg, 9735 const struct bpf_reg_state *reg) 9736 { 9737 const struct btf_type *t; 9738 9739 t = btf_type_skip_modifiers(btf, arg->type, NULL); 9740 if (!btf_type_is_scalar(t) || reg->type != SCALAR_VALUE) 9741 return false; 9742 9743 return __kfunc_param_match_suffix(btf, arg, "__szk"); 9744 } 9745 9746 static bool is_kfunc_arg_constant(const struct btf *btf, const struct btf_param *arg) 9747 { 9748 return __kfunc_param_match_suffix(btf, arg, "__k"); 9749 } 9750 9751 static bool is_kfunc_arg_ignore(const struct btf *btf, const struct btf_param *arg) 9752 { 9753 return __kfunc_param_match_suffix(btf, arg, "__ign"); 9754 } 9755 9756 static bool is_kfunc_arg_alloc_obj(const struct btf *btf, const struct btf_param *arg) 9757 { 9758 return __kfunc_param_match_suffix(btf, arg, "__alloc"); 9759 } 9760 9761 static bool is_kfunc_arg_uninit(const struct btf *btf, const struct btf_param *arg) 9762 { 9763 return __kfunc_param_match_suffix(btf, arg, "__uninit"); 9764 } 9765 9766 static bool is_kfunc_arg_refcounted_kptr(const struct btf *btf, const struct btf_param *arg) 9767 { 9768 return __kfunc_param_match_suffix(btf, arg, "__refcounted_kptr"); 9769 } 9770 9771 static bool is_kfunc_arg_scalar_with_name(const struct btf *btf, 9772 const struct btf_param *arg, 9773 const char *name) 9774 { 9775 int len, target_len = strlen(name); 9776 const char *param_name; 9777 9778 param_name = btf_name_by_offset(btf, arg->name_off); 9779 if (str_is_empty(param_name)) 9780 return false; 9781 len = strlen(param_name); 9782 if (len != target_len) 9783 return false; 9784 if (strcmp(param_name, name)) 9785 return false; 9786 9787 return true; 9788 } 9789 9790 enum { 9791 KF_ARG_DYNPTR_ID, 9792 KF_ARG_LIST_HEAD_ID, 9793 KF_ARG_LIST_NODE_ID, 9794 KF_ARG_RB_ROOT_ID, 9795 KF_ARG_RB_NODE_ID, 9796 }; 9797 9798 BTF_ID_LIST(kf_arg_btf_ids) 9799 BTF_ID(struct, bpf_dynptr_kern) 9800 BTF_ID(struct, bpf_list_head) 9801 BTF_ID(struct, bpf_list_node) 9802 BTF_ID(struct, bpf_rb_root) 9803 BTF_ID(struct, bpf_rb_node) 9804 9805 static bool __is_kfunc_ptr_arg_type(const struct btf *btf, 9806 const struct btf_param *arg, int type) 9807 { 9808 const struct btf_type *t; 9809 u32 res_id; 9810 9811 t = btf_type_skip_modifiers(btf, arg->type, NULL); 9812 if (!t) 9813 return false; 9814 if (!btf_type_is_ptr(t)) 9815 return false; 9816 t = btf_type_skip_modifiers(btf, t->type, &res_id); 9817 if (!t) 9818 return false; 9819 return btf_types_are_same(btf, res_id, btf_vmlinux, kf_arg_btf_ids[type]); 9820 } 9821 9822 static bool is_kfunc_arg_dynptr(const struct btf *btf, const struct btf_param *arg) 9823 { 9824 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_DYNPTR_ID); 9825 } 9826 9827 static bool is_kfunc_arg_list_head(const struct btf *btf, const struct btf_param *arg) 9828 { 9829 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_LIST_HEAD_ID); 9830 } 9831 9832 static bool is_kfunc_arg_list_node(const struct btf *btf, const struct btf_param *arg) 9833 { 9834 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_LIST_NODE_ID); 9835 } 9836 9837 static bool is_kfunc_arg_rbtree_root(const struct btf *btf, const struct btf_param *arg) 9838 { 9839 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_RB_ROOT_ID); 9840 } 9841 9842 static bool is_kfunc_arg_rbtree_node(const struct btf *btf, const struct btf_param *arg) 9843 { 9844 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_RB_NODE_ID); 9845 } 9846 9847 static bool is_kfunc_arg_callback(struct bpf_verifier_env *env, const struct btf *btf, 9848 const struct btf_param *arg) 9849 { 9850 const struct btf_type *t; 9851 9852 t = btf_type_resolve_func_ptr(btf, arg->type, NULL); 9853 if (!t) 9854 return false; 9855 9856 return true; 9857 } 9858 9859 /* Returns true if struct is composed of scalars, 4 levels of nesting allowed */ 9860 static bool __btf_type_is_scalar_struct(struct bpf_verifier_env *env, 9861 const struct btf *btf, 9862 const struct btf_type *t, int rec) 9863 { 9864 const struct btf_type *member_type; 9865 const struct btf_member *member; 9866 u32 i; 9867 9868 if (!btf_type_is_struct(t)) 9869 return false; 9870 9871 for_each_member(i, t, member) { 9872 const struct btf_array *array; 9873 9874 member_type = btf_type_skip_modifiers(btf, member->type, NULL); 9875 if (btf_type_is_struct(member_type)) { 9876 if (rec >= 3) { 9877 verbose(env, "max struct nesting depth exceeded\n"); 9878 return false; 9879 } 9880 if (!__btf_type_is_scalar_struct(env, btf, member_type, rec + 1)) 9881 return false; 9882 continue; 9883 } 9884 if (btf_type_is_array(member_type)) { 9885 array = btf_array(member_type); 9886 if (!array->nelems) 9887 return false; 9888 member_type = btf_type_skip_modifiers(btf, array->type, NULL); 9889 if (!btf_type_is_scalar(member_type)) 9890 return false; 9891 continue; 9892 } 9893 if (!btf_type_is_scalar(member_type)) 9894 return false; 9895 } 9896 return true; 9897 } 9898 9899 9900 static u32 *reg2btf_ids[__BPF_REG_TYPE_MAX] = { 9901 #ifdef CONFIG_NET 9902 [PTR_TO_SOCKET] = &btf_sock_ids[BTF_SOCK_TYPE_SOCK], 9903 [PTR_TO_SOCK_COMMON] = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON], 9904 [PTR_TO_TCP_SOCK] = &btf_sock_ids[BTF_SOCK_TYPE_TCP], 9905 #endif 9906 }; 9907 9908 enum kfunc_ptr_arg_type { 9909 KF_ARG_PTR_TO_CTX, 9910 KF_ARG_PTR_TO_ALLOC_BTF_ID, /* Allocated object */ 9911 KF_ARG_PTR_TO_REFCOUNTED_KPTR, /* Refcounted local kptr */ 9912 KF_ARG_PTR_TO_DYNPTR, 9913 KF_ARG_PTR_TO_ITER, 9914 KF_ARG_PTR_TO_LIST_HEAD, 9915 KF_ARG_PTR_TO_LIST_NODE, 9916 KF_ARG_PTR_TO_BTF_ID, /* Also covers reg2btf_ids conversions */ 9917 KF_ARG_PTR_TO_MEM, 9918 KF_ARG_PTR_TO_MEM_SIZE, /* Size derived from next argument, skip it */ 9919 KF_ARG_PTR_TO_CALLBACK, 9920 KF_ARG_PTR_TO_RB_ROOT, 9921 KF_ARG_PTR_TO_RB_NODE, 9922 }; 9923 9924 enum special_kfunc_type { 9925 KF_bpf_obj_new_impl, 9926 KF_bpf_obj_drop_impl, 9927 KF_bpf_refcount_acquire_impl, 9928 KF_bpf_list_push_front_impl, 9929 KF_bpf_list_push_back_impl, 9930 KF_bpf_list_pop_front, 9931 KF_bpf_list_pop_back, 9932 KF_bpf_cast_to_kern_ctx, 9933 KF_bpf_rdonly_cast, 9934 KF_bpf_rcu_read_lock, 9935 KF_bpf_rcu_read_unlock, 9936 KF_bpf_rbtree_remove, 9937 KF_bpf_rbtree_add_impl, 9938 KF_bpf_rbtree_first, 9939 KF_bpf_dynptr_from_skb, 9940 KF_bpf_dynptr_from_xdp, 9941 KF_bpf_dynptr_slice, 9942 KF_bpf_dynptr_slice_rdwr, 9943 KF_bpf_dynptr_clone, 9944 }; 9945 9946 BTF_SET_START(special_kfunc_set) 9947 BTF_ID(func, bpf_obj_new_impl) 9948 BTF_ID(func, bpf_obj_drop_impl) 9949 BTF_ID(func, bpf_refcount_acquire_impl) 9950 BTF_ID(func, bpf_list_push_front_impl) 9951 BTF_ID(func, bpf_list_push_back_impl) 9952 BTF_ID(func, bpf_list_pop_front) 9953 BTF_ID(func, bpf_list_pop_back) 9954 BTF_ID(func, bpf_cast_to_kern_ctx) 9955 BTF_ID(func, bpf_rdonly_cast) 9956 BTF_ID(func, bpf_rbtree_remove) 9957 BTF_ID(func, bpf_rbtree_add_impl) 9958 BTF_ID(func, bpf_rbtree_first) 9959 BTF_ID(func, bpf_dynptr_from_skb) 9960 BTF_ID(func, bpf_dynptr_from_xdp) 9961 BTF_ID(func, bpf_dynptr_slice) 9962 BTF_ID(func, bpf_dynptr_slice_rdwr) 9963 BTF_ID(func, bpf_dynptr_clone) 9964 BTF_SET_END(special_kfunc_set) 9965 9966 BTF_ID_LIST(special_kfunc_list) 9967 BTF_ID(func, bpf_obj_new_impl) 9968 BTF_ID(func, bpf_obj_drop_impl) 9969 BTF_ID(func, bpf_refcount_acquire_impl) 9970 BTF_ID(func, bpf_list_push_front_impl) 9971 BTF_ID(func, bpf_list_push_back_impl) 9972 BTF_ID(func, bpf_list_pop_front) 9973 BTF_ID(func, bpf_list_pop_back) 9974 BTF_ID(func, bpf_cast_to_kern_ctx) 9975 BTF_ID(func, bpf_rdonly_cast) 9976 BTF_ID(func, bpf_rcu_read_lock) 9977 BTF_ID(func, bpf_rcu_read_unlock) 9978 BTF_ID(func, bpf_rbtree_remove) 9979 BTF_ID(func, bpf_rbtree_add_impl) 9980 BTF_ID(func, bpf_rbtree_first) 9981 BTF_ID(func, bpf_dynptr_from_skb) 9982 BTF_ID(func, bpf_dynptr_from_xdp) 9983 BTF_ID(func, bpf_dynptr_slice) 9984 BTF_ID(func, bpf_dynptr_slice_rdwr) 9985 BTF_ID(func, bpf_dynptr_clone) 9986 9987 static bool is_kfunc_bpf_rcu_read_lock(struct bpf_kfunc_call_arg_meta *meta) 9988 { 9989 return meta->func_id == special_kfunc_list[KF_bpf_rcu_read_lock]; 9990 } 9991 9992 static bool is_kfunc_bpf_rcu_read_unlock(struct bpf_kfunc_call_arg_meta *meta) 9993 { 9994 return meta->func_id == special_kfunc_list[KF_bpf_rcu_read_unlock]; 9995 } 9996 9997 static enum kfunc_ptr_arg_type 9998 get_kfunc_ptr_arg_type(struct bpf_verifier_env *env, 9999 struct bpf_kfunc_call_arg_meta *meta, 10000 const struct btf_type *t, const struct btf_type *ref_t, 10001 const char *ref_tname, const struct btf_param *args, 10002 int argno, int nargs) 10003 { 10004 u32 regno = argno + 1; 10005 struct bpf_reg_state *regs = cur_regs(env); 10006 struct bpf_reg_state *reg = ®s[regno]; 10007 bool arg_mem_size = false; 10008 10009 if (meta->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx]) 10010 return KF_ARG_PTR_TO_CTX; 10011 10012 /* In this function, we verify the kfunc's BTF as per the argument type, 10013 * leaving the rest of the verification with respect to the register 10014 * type to our caller. When a set of conditions hold in the BTF type of 10015 * arguments, we resolve it to a known kfunc_ptr_arg_type. 10016 */ 10017 if (btf_get_prog_ctx_type(&env->log, meta->btf, t, resolve_prog_type(env->prog), argno)) 10018 return KF_ARG_PTR_TO_CTX; 10019 10020 if (is_kfunc_arg_alloc_obj(meta->btf, &args[argno])) 10021 return KF_ARG_PTR_TO_ALLOC_BTF_ID; 10022 10023 if (is_kfunc_arg_refcounted_kptr(meta->btf, &args[argno])) 10024 return KF_ARG_PTR_TO_REFCOUNTED_KPTR; 10025 10026 if (is_kfunc_arg_dynptr(meta->btf, &args[argno])) 10027 return KF_ARG_PTR_TO_DYNPTR; 10028 10029 if (is_kfunc_arg_iter(meta, argno)) 10030 return KF_ARG_PTR_TO_ITER; 10031 10032 if (is_kfunc_arg_list_head(meta->btf, &args[argno])) 10033 return KF_ARG_PTR_TO_LIST_HEAD; 10034 10035 if (is_kfunc_arg_list_node(meta->btf, &args[argno])) 10036 return KF_ARG_PTR_TO_LIST_NODE; 10037 10038 if (is_kfunc_arg_rbtree_root(meta->btf, &args[argno])) 10039 return KF_ARG_PTR_TO_RB_ROOT; 10040 10041 if (is_kfunc_arg_rbtree_node(meta->btf, &args[argno])) 10042 return KF_ARG_PTR_TO_RB_NODE; 10043 10044 if ((base_type(reg->type) == PTR_TO_BTF_ID || reg2btf_ids[base_type(reg->type)])) { 10045 if (!btf_type_is_struct(ref_t)) { 10046 verbose(env, "kernel function %s args#%d pointer type %s %s is not supported\n", 10047 meta->func_name, argno, btf_type_str(ref_t), ref_tname); 10048 return -EINVAL; 10049 } 10050 return KF_ARG_PTR_TO_BTF_ID; 10051 } 10052 10053 if (is_kfunc_arg_callback(env, meta->btf, &args[argno])) 10054 return KF_ARG_PTR_TO_CALLBACK; 10055 10056 10057 if (argno + 1 < nargs && 10058 (is_kfunc_arg_mem_size(meta->btf, &args[argno + 1], ®s[regno + 1]) || 10059 is_kfunc_arg_const_mem_size(meta->btf, &args[argno + 1], ®s[regno + 1]))) 10060 arg_mem_size = true; 10061 10062 /* This is the catch all argument type of register types supported by 10063 * check_helper_mem_access. However, we only allow when argument type is 10064 * pointer to scalar, or struct composed (recursively) of scalars. When 10065 * arg_mem_size is true, the pointer can be void *. 10066 */ 10067 if (!btf_type_is_scalar(ref_t) && !__btf_type_is_scalar_struct(env, meta->btf, ref_t, 0) && 10068 (arg_mem_size ? !btf_type_is_void(ref_t) : 1)) { 10069 verbose(env, "arg#%d pointer type %s %s must point to %sscalar, or struct with scalar\n", 10070 argno, btf_type_str(ref_t), ref_tname, arg_mem_size ? "void, " : ""); 10071 return -EINVAL; 10072 } 10073 return arg_mem_size ? KF_ARG_PTR_TO_MEM_SIZE : KF_ARG_PTR_TO_MEM; 10074 } 10075 10076 static int process_kf_arg_ptr_to_btf_id(struct bpf_verifier_env *env, 10077 struct bpf_reg_state *reg, 10078 const struct btf_type *ref_t, 10079 const char *ref_tname, u32 ref_id, 10080 struct bpf_kfunc_call_arg_meta *meta, 10081 int argno) 10082 { 10083 const struct btf_type *reg_ref_t; 10084 bool strict_type_match = false; 10085 const struct btf *reg_btf; 10086 const char *reg_ref_tname; 10087 u32 reg_ref_id; 10088 10089 if (base_type(reg->type) == PTR_TO_BTF_ID) { 10090 reg_btf = reg->btf; 10091 reg_ref_id = reg->btf_id; 10092 } else { 10093 reg_btf = btf_vmlinux; 10094 reg_ref_id = *reg2btf_ids[base_type(reg->type)]; 10095 } 10096 10097 /* Enforce strict type matching for calls to kfuncs that are acquiring 10098 * or releasing a reference, or are no-cast aliases. We do _not_ 10099 * enforce strict matching for plain KF_TRUSTED_ARGS kfuncs by default, 10100 * as we want to enable BPF programs to pass types that are bitwise 10101 * equivalent without forcing them to explicitly cast with something 10102 * like bpf_cast_to_kern_ctx(). 10103 * 10104 * For example, say we had a type like the following: 10105 * 10106 * struct bpf_cpumask { 10107 * cpumask_t cpumask; 10108 * refcount_t usage; 10109 * }; 10110 * 10111 * Note that as specified in <linux/cpumask.h>, cpumask_t is typedef'ed 10112 * to a struct cpumask, so it would be safe to pass a struct 10113 * bpf_cpumask * to a kfunc expecting a struct cpumask *. 10114 * 10115 * The philosophy here is similar to how we allow scalars of different 10116 * types to be passed to kfuncs as long as the size is the same. The 10117 * only difference here is that we're simply allowing 10118 * btf_struct_ids_match() to walk the struct at the 0th offset, and 10119 * resolve types. 10120 */ 10121 if (is_kfunc_acquire(meta) || 10122 (is_kfunc_release(meta) && reg->ref_obj_id) || 10123 btf_type_ids_nocast_alias(&env->log, reg_btf, reg_ref_id, meta->btf, ref_id)) 10124 strict_type_match = true; 10125 10126 WARN_ON_ONCE(is_kfunc_trusted_args(meta) && reg->off); 10127 10128 reg_ref_t = btf_type_skip_modifiers(reg_btf, reg_ref_id, ®_ref_id); 10129 reg_ref_tname = btf_name_by_offset(reg_btf, reg_ref_t->name_off); 10130 if (!btf_struct_ids_match(&env->log, reg_btf, reg_ref_id, reg->off, meta->btf, ref_id, strict_type_match)) { 10131 verbose(env, "kernel function %s args#%d expected pointer to %s %s but R%d has a pointer to %s %s\n", 10132 meta->func_name, argno, btf_type_str(ref_t), ref_tname, argno + 1, 10133 btf_type_str(reg_ref_t), reg_ref_tname); 10134 return -EINVAL; 10135 } 10136 return 0; 10137 } 10138 10139 static int ref_set_non_owning(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 10140 { 10141 struct bpf_verifier_state *state = env->cur_state; 10142 10143 if (!state->active_lock.ptr) { 10144 verbose(env, "verifier internal error: ref_set_non_owning w/o active lock\n"); 10145 return -EFAULT; 10146 } 10147 10148 if (type_flag(reg->type) & NON_OWN_REF) { 10149 verbose(env, "verifier internal error: NON_OWN_REF already set\n"); 10150 return -EFAULT; 10151 } 10152 10153 reg->type |= NON_OWN_REF; 10154 return 0; 10155 } 10156 10157 static int ref_convert_owning_non_owning(struct bpf_verifier_env *env, u32 ref_obj_id) 10158 { 10159 struct bpf_func_state *state, *unused; 10160 struct bpf_reg_state *reg; 10161 int i; 10162 10163 state = cur_func(env); 10164 10165 if (!ref_obj_id) { 10166 verbose(env, "verifier internal error: ref_obj_id is zero for " 10167 "owning -> non-owning conversion\n"); 10168 return -EFAULT; 10169 } 10170 10171 for (i = 0; i < state->acquired_refs; i++) { 10172 if (state->refs[i].id != ref_obj_id) 10173 continue; 10174 10175 /* Clear ref_obj_id here so release_reference doesn't clobber 10176 * the whole reg 10177 */ 10178 bpf_for_each_reg_in_vstate(env->cur_state, unused, reg, ({ 10179 if (reg->ref_obj_id == ref_obj_id) { 10180 reg->ref_obj_id = 0; 10181 ref_set_non_owning(env, reg); 10182 } 10183 })); 10184 return 0; 10185 } 10186 10187 verbose(env, "verifier internal error: ref state missing for ref_obj_id\n"); 10188 return -EFAULT; 10189 } 10190 10191 /* Implementation details: 10192 * 10193 * Each register points to some region of memory, which we define as an 10194 * allocation. Each allocation may embed a bpf_spin_lock which protects any 10195 * special BPF objects (bpf_list_head, bpf_rb_root, etc.) part of the same 10196 * allocation. The lock and the data it protects are colocated in the same 10197 * memory region. 10198 * 10199 * Hence, everytime a register holds a pointer value pointing to such 10200 * allocation, the verifier preserves a unique reg->id for it. 10201 * 10202 * The verifier remembers the lock 'ptr' and the lock 'id' whenever 10203 * bpf_spin_lock is called. 10204 * 10205 * To enable this, lock state in the verifier captures two values: 10206 * active_lock.ptr = Register's type specific pointer 10207 * active_lock.id = A unique ID for each register pointer value 10208 * 10209 * Currently, PTR_TO_MAP_VALUE and PTR_TO_BTF_ID | MEM_ALLOC are the two 10210 * supported register types. 10211 * 10212 * The active_lock.ptr in case of map values is the reg->map_ptr, and in case of 10213 * allocated objects is the reg->btf pointer. 10214 * 10215 * The active_lock.id is non-unique for maps supporting direct_value_addr, as we 10216 * can establish the provenance of the map value statically for each distinct 10217 * lookup into such maps. They always contain a single map value hence unique 10218 * IDs for each pseudo load pessimizes the algorithm and rejects valid programs. 10219 * 10220 * So, in case of global variables, they use array maps with max_entries = 1, 10221 * hence their active_lock.ptr becomes map_ptr and id = 0 (since they all point 10222 * into the same map value as max_entries is 1, as described above). 10223 * 10224 * In case of inner map lookups, the inner map pointer has same map_ptr as the 10225 * outer map pointer (in verifier context), but each lookup into an inner map 10226 * assigns a fresh reg->id to the lookup, so while lookups into distinct inner 10227 * maps from the same outer map share the same map_ptr as active_lock.ptr, they 10228 * will get different reg->id assigned to each lookup, hence different 10229 * active_lock.id. 10230 * 10231 * In case of allocated objects, active_lock.ptr is the reg->btf, and the 10232 * reg->id is a unique ID preserved after the NULL pointer check on the pointer 10233 * returned from bpf_obj_new. Each allocation receives a new reg->id. 10234 */ 10235 static int check_reg_allocation_locked(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 10236 { 10237 void *ptr; 10238 u32 id; 10239 10240 switch ((int)reg->type) { 10241 case PTR_TO_MAP_VALUE: 10242 ptr = reg->map_ptr; 10243 break; 10244 case PTR_TO_BTF_ID | MEM_ALLOC: 10245 ptr = reg->btf; 10246 break; 10247 default: 10248 verbose(env, "verifier internal error: unknown reg type for lock check\n"); 10249 return -EFAULT; 10250 } 10251 id = reg->id; 10252 10253 if (!env->cur_state->active_lock.ptr) 10254 return -EINVAL; 10255 if (env->cur_state->active_lock.ptr != ptr || 10256 env->cur_state->active_lock.id != id) { 10257 verbose(env, "held lock and object are not in the same allocation\n"); 10258 return -EINVAL; 10259 } 10260 return 0; 10261 } 10262 10263 static bool is_bpf_list_api_kfunc(u32 btf_id) 10264 { 10265 return btf_id == special_kfunc_list[KF_bpf_list_push_front_impl] || 10266 btf_id == special_kfunc_list[KF_bpf_list_push_back_impl] || 10267 btf_id == special_kfunc_list[KF_bpf_list_pop_front] || 10268 btf_id == special_kfunc_list[KF_bpf_list_pop_back]; 10269 } 10270 10271 static bool is_bpf_rbtree_api_kfunc(u32 btf_id) 10272 { 10273 return btf_id == special_kfunc_list[KF_bpf_rbtree_add_impl] || 10274 btf_id == special_kfunc_list[KF_bpf_rbtree_remove] || 10275 btf_id == special_kfunc_list[KF_bpf_rbtree_first]; 10276 } 10277 10278 static bool is_bpf_graph_api_kfunc(u32 btf_id) 10279 { 10280 return is_bpf_list_api_kfunc(btf_id) || is_bpf_rbtree_api_kfunc(btf_id) || 10281 btf_id == special_kfunc_list[KF_bpf_refcount_acquire_impl]; 10282 } 10283 10284 static bool is_callback_calling_kfunc(u32 btf_id) 10285 { 10286 return btf_id == special_kfunc_list[KF_bpf_rbtree_add_impl]; 10287 } 10288 10289 static bool is_rbtree_lock_required_kfunc(u32 btf_id) 10290 { 10291 return is_bpf_rbtree_api_kfunc(btf_id); 10292 } 10293 10294 static bool check_kfunc_is_graph_root_api(struct bpf_verifier_env *env, 10295 enum btf_field_type head_field_type, 10296 u32 kfunc_btf_id) 10297 { 10298 bool ret; 10299 10300 switch (head_field_type) { 10301 case BPF_LIST_HEAD: 10302 ret = is_bpf_list_api_kfunc(kfunc_btf_id); 10303 break; 10304 case BPF_RB_ROOT: 10305 ret = is_bpf_rbtree_api_kfunc(kfunc_btf_id); 10306 break; 10307 default: 10308 verbose(env, "verifier internal error: unexpected graph root argument type %s\n", 10309 btf_field_type_name(head_field_type)); 10310 return false; 10311 } 10312 10313 if (!ret) 10314 verbose(env, "verifier internal error: %s head arg for unknown kfunc\n", 10315 btf_field_type_name(head_field_type)); 10316 return ret; 10317 } 10318 10319 static bool check_kfunc_is_graph_node_api(struct bpf_verifier_env *env, 10320 enum btf_field_type node_field_type, 10321 u32 kfunc_btf_id) 10322 { 10323 bool ret; 10324 10325 switch (node_field_type) { 10326 case BPF_LIST_NODE: 10327 ret = (kfunc_btf_id == special_kfunc_list[KF_bpf_list_push_front_impl] || 10328 kfunc_btf_id == special_kfunc_list[KF_bpf_list_push_back_impl]); 10329 break; 10330 case BPF_RB_NODE: 10331 ret = (kfunc_btf_id == special_kfunc_list[KF_bpf_rbtree_remove] || 10332 kfunc_btf_id == special_kfunc_list[KF_bpf_rbtree_add_impl]); 10333 break; 10334 default: 10335 verbose(env, "verifier internal error: unexpected graph node argument type %s\n", 10336 btf_field_type_name(node_field_type)); 10337 return false; 10338 } 10339 10340 if (!ret) 10341 verbose(env, "verifier internal error: %s node arg for unknown kfunc\n", 10342 btf_field_type_name(node_field_type)); 10343 return ret; 10344 } 10345 10346 static int 10347 __process_kf_arg_ptr_to_graph_root(struct bpf_verifier_env *env, 10348 struct bpf_reg_state *reg, u32 regno, 10349 struct bpf_kfunc_call_arg_meta *meta, 10350 enum btf_field_type head_field_type, 10351 struct btf_field **head_field) 10352 { 10353 const char *head_type_name; 10354 struct btf_field *field; 10355 struct btf_record *rec; 10356 u32 head_off; 10357 10358 if (meta->btf != btf_vmlinux) { 10359 verbose(env, "verifier internal error: unexpected btf mismatch in kfunc call\n"); 10360 return -EFAULT; 10361 } 10362 10363 if (!check_kfunc_is_graph_root_api(env, head_field_type, meta->func_id)) 10364 return -EFAULT; 10365 10366 head_type_name = btf_field_type_name(head_field_type); 10367 if (!tnum_is_const(reg->var_off)) { 10368 verbose(env, 10369 "R%d doesn't have constant offset. %s has to be at the constant offset\n", 10370 regno, head_type_name); 10371 return -EINVAL; 10372 } 10373 10374 rec = reg_btf_record(reg); 10375 head_off = reg->off + reg->var_off.value; 10376 field = btf_record_find(rec, head_off, head_field_type); 10377 if (!field) { 10378 verbose(env, "%s not found at offset=%u\n", head_type_name, head_off); 10379 return -EINVAL; 10380 } 10381 10382 /* All functions require bpf_list_head to be protected using a bpf_spin_lock */ 10383 if (check_reg_allocation_locked(env, reg)) { 10384 verbose(env, "bpf_spin_lock at off=%d must be held for %s\n", 10385 rec->spin_lock_off, head_type_name); 10386 return -EINVAL; 10387 } 10388 10389 if (*head_field) { 10390 verbose(env, "verifier internal error: repeating %s arg\n", head_type_name); 10391 return -EFAULT; 10392 } 10393 *head_field = field; 10394 return 0; 10395 } 10396 10397 static int process_kf_arg_ptr_to_list_head(struct bpf_verifier_env *env, 10398 struct bpf_reg_state *reg, u32 regno, 10399 struct bpf_kfunc_call_arg_meta *meta) 10400 { 10401 return __process_kf_arg_ptr_to_graph_root(env, reg, regno, meta, BPF_LIST_HEAD, 10402 &meta->arg_list_head.field); 10403 } 10404 10405 static int process_kf_arg_ptr_to_rbtree_root(struct bpf_verifier_env *env, 10406 struct bpf_reg_state *reg, u32 regno, 10407 struct bpf_kfunc_call_arg_meta *meta) 10408 { 10409 return __process_kf_arg_ptr_to_graph_root(env, reg, regno, meta, BPF_RB_ROOT, 10410 &meta->arg_rbtree_root.field); 10411 } 10412 10413 static int 10414 __process_kf_arg_ptr_to_graph_node(struct bpf_verifier_env *env, 10415 struct bpf_reg_state *reg, u32 regno, 10416 struct bpf_kfunc_call_arg_meta *meta, 10417 enum btf_field_type head_field_type, 10418 enum btf_field_type node_field_type, 10419 struct btf_field **node_field) 10420 { 10421 const char *node_type_name; 10422 const struct btf_type *et, *t; 10423 struct btf_field *field; 10424 u32 node_off; 10425 10426 if (meta->btf != btf_vmlinux) { 10427 verbose(env, "verifier internal error: unexpected btf mismatch in kfunc call\n"); 10428 return -EFAULT; 10429 } 10430 10431 if (!check_kfunc_is_graph_node_api(env, node_field_type, meta->func_id)) 10432 return -EFAULT; 10433 10434 node_type_name = btf_field_type_name(node_field_type); 10435 if (!tnum_is_const(reg->var_off)) { 10436 verbose(env, 10437 "R%d doesn't have constant offset. %s has to be at the constant offset\n", 10438 regno, node_type_name); 10439 return -EINVAL; 10440 } 10441 10442 node_off = reg->off + reg->var_off.value; 10443 field = reg_find_field_offset(reg, node_off, node_field_type); 10444 if (!field || field->offset != node_off) { 10445 verbose(env, "%s not found at offset=%u\n", node_type_name, node_off); 10446 return -EINVAL; 10447 } 10448 10449 field = *node_field; 10450 10451 et = btf_type_by_id(field->graph_root.btf, field->graph_root.value_btf_id); 10452 t = btf_type_by_id(reg->btf, reg->btf_id); 10453 if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, 0, field->graph_root.btf, 10454 field->graph_root.value_btf_id, true)) { 10455 verbose(env, "operation on %s expects arg#1 %s at offset=%d " 10456 "in struct %s, but arg is at offset=%d in struct %s\n", 10457 btf_field_type_name(head_field_type), 10458 btf_field_type_name(node_field_type), 10459 field->graph_root.node_offset, 10460 btf_name_by_offset(field->graph_root.btf, et->name_off), 10461 node_off, btf_name_by_offset(reg->btf, t->name_off)); 10462 return -EINVAL; 10463 } 10464 10465 if (node_off != field->graph_root.node_offset) { 10466 verbose(env, "arg#1 offset=%d, but expected %s at offset=%d in struct %s\n", 10467 node_off, btf_field_type_name(node_field_type), 10468 field->graph_root.node_offset, 10469 btf_name_by_offset(field->graph_root.btf, et->name_off)); 10470 return -EINVAL; 10471 } 10472 10473 return 0; 10474 } 10475 10476 static int process_kf_arg_ptr_to_list_node(struct bpf_verifier_env *env, 10477 struct bpf_reg_state *reg, u32 regno, 10478 struct bpf_kfunc_call_arg_meta *meta) 10479 { 10480 return __process_kf_arg_ptr_to_graph_node(env, reg, regno, meta, 10481 BPF_LIST_HEAD, BPF_LIST_NODE, 10482 &meta->arg_list_head.field); 10483 } 10484 10485 static int process_kf_arg_ptr_to_rbtree_node(struct bpf_verifier_env *env, 10486 struct bpf_reg_state *reg, u32 regno, 10487 struct bpf_kfunc_call_arg_meta *meta) 10488 { 10489 return __process_kf_arg_ptr_to_graph_node(env, reg, regno, meta, 10490 BPF_RB_ROOT, BPF_RB_NODE, 10491 &meta->arg_rbtree_root.field); 10492 } 10493 10494 static int check_kfunc_args(struct bpf_verifier_env *env, struct bpf_kfunc_call_arg_meta *meta, 10495 int insn_idx) 10496 { 10497 const char *func_name = meta->func_name, *ref_tname; 10498 const struct btf *btf = meta->btf; 10499 const struct btf_param *args; 10500 struct btf_record *rec; 10501 u32 i, nargs; 10502 int ret; 10503 10504 args = (const struct btf_param *)(meta->func_proto + 1); 10505 nargs = btf_type_vlen(meta->func_proto); 10506 if (nargs > MAX_BPF_FUNC_REG_ARGS) { 10507 verbose(env, "Function %s has %d > %d args\n", func_name, nargs, 10508 MAX_BPF_FUNC_REG_ARGS); 10509 return -EINVAL; 10510 } 10511 10512 /* Check that BTF function arguments match actual types that the 10513 * verifier sees. 10514 */ 10515 for (i = 0; i < nargs; i++) { 10516 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[i + 1]; 10517 const struct btf_type *t, *ref_t, *resolve_ret; 10518 enum bpf_arg_type arg_type = ARG_DONTCARE; 10519 u32 regno = i + 1, ref_id, type_size; 10520 bool is_ret_buf_sz = false; 10521 int kf_arg_type; 10522 10523 t = btf_type_skip_modifiers(btf, args[i].type, NULL); 10524 10525 if (is_kfunc_arg_ignore(btf, &args[i])) 10526 continue; 10527 10528 if (btf_type_is_scalar(t)) { 10529 if (reg->type != SCALAR_VALUE) { 10530 verbose(env, "R%d is not a scalar\n", regno); 10531 return -EINVAL; 10532 } 10533 10534 if (is_kfunc_arg_constant(meta->btf, &args[i])) { 10535 if (meta->arg_constant.found) { 10536 verbose(env, "verifier internal error: only one constant argument permitted\n"); 10537 return -EFAULT; 10538 } 10539 if (!tnum_is_const(reg->var_off)) { 10540 verbose(env, "R%d must be a known constant\n", regno); 10541 return -EINVAL; 10542 } 10543 ret = mark_chain_precision(env, regno); 10544 if (ret < 0) 10545 return ret; 10546 meta->arg_constant.found = true; 10547 meta->arg_constant.value = reg->var_off.value; 10548 } else if (is_kfunc_arg_scalar_with_name(btf, &args[i], "rdonly_buf_size")) { 10549 meta->r0_rdonly = true; 10550 is_ret_buf_sz = true; 10551 } else if (is_kfunc_arg_scalar_with_name(btf, &args[i], "rdwr_buf_size")) { 10552 is_ret_buf_sz = true; 10553 } 10554 10555 if (is_ret_buf_sz) { 10556 if (meta->r0_size) { 10557 verbose(env, "2 or more rdonly/rdwr_buf_size parameters for kfunc"); 10558 return -EINVAL; 10559 } 10560 10561 if (!tnum_is_const(reg->var_off)) { 10562 verbose(env, "R%d is not a const\n", regno); 10563 return -EINVAL; 10564 } 10565 10566 meta->r0_size = reg->var_off.value; 10567 ret = mark_chain_precision(env, regno); 10568 if (ret) 10569 return ret; 10570 } 10571 continue; 10572 } 10573 10574 if (!btf_type_is_ptr(t)) { 10575 verbose(env, "Unrecognized arg#%d type %s\n", i, btf_type_str(t)); 10576 return -EINVAL; 10577 } 10578 10579 if ((is_kfunc_trusted_args(meta) || is_kfunc_rcu(meta)) && 10580 (register_is_null(reg) || type_may_be_null(reg->type))) { 10581 verbose(env, "Possibly NULL pointer passed to trusted arg%d\n", i); 10582 return -EACCES; 10583 } 10584 10585 if (reg->ref_obj_id) { 10586 if (is_kfunc_release(meta) && meta->ref_obj_id) { 10587 verbose(env, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n", 10588 regno, reg->ref_obj_id, 10589 meta->ref_obj_id); 10590 return -EFAULT; 10591 } 10592 meta->ref_obj_id = reg->ref_obj_id; 10593 if (is_kfunc_release(meta)) 10594 meta->release_regno = regno; 10595 } 10596 10597 ref_t = btf_type_skip_modifiers(btf, t->type, &ref_id); 10598 ref_tname = btf_name_by_offset(btf, ref_t->name_off); 10599 10600 kf_arg_type = get_kfunc_ptr_arg_type(env, meta, t, ref_t, ref_tname, args, i, nargs); 10601 if (kf_arg_type < 0) 10602 return kf_arg_type; 10603 10604 switch (kf_arg_type) { 10605 case KF_ARG_PTR_TO_ALLOC_BTF_ID: 10606 case KF_ARG_PTR_TO_BTF_ID: 10607 if (!is_kfunc_trusted_args(meta) && !is_kfunc_rcu(meta)) 10608 break; 10609 10610 if (!is_trusted_reg(reg)) { 10611 if (!is_kfunc_rcu(meta)) { 10612 verbose(env, "R%d must be referenced or trusted\n", regno); 10613 return -EINVAL; 10614 } 10615 if (!is_rcu_reg(reg)) { 10616 verbose(env, "R%d must be a rcu pointer\n", regno); 10617 return -EINVAL; 10618 } 10619 } 10620 10621 fallthrough; 10622 case KF_ARG_PTR_TO_CTX: 10623 /* Trusted arguments have the same offset checks as release arguments */ 10624 arg_type |= OBJ_RELEASE; 10625 break; 10626 case KF_ARG_PTR_TO_DYNPTR: 10627 case KF_ARG_PTR_TO_ITER: 10628 case KF_ARG_PTR_TO_LIST_HEAD: 10629 case KF_ARG_PTR_TO_LIST_NODE: 10630 case KF_ARG_PTR_TO_RB_ROOT: 10631 case KF_ARG_PTR_TO_RB_NODE: 10632 case KF_ARG_PTR_TO_MEM: 10633 case KF_ARG_PTR_TO_MEM_SIZE: 10634 case KF_ARG_PTR_TO_CALLBACK: 10635 case KF_ARG_PTR_TO_REFCOUNTED_KPTR: 10636 /* Trusted by default */ 10637 break; 10638 default: 10639 WARN_ON_ONCE(1); 10640 return -EFAULT; 10641 } 10642 10643 if (is_kfunc_release(meta) && reg->ref_obj_id) 10644 arg_type |= OBJ_RELEASE; 10645 ret = check_func_arg_reg_off(env, reg, regno, arg_type); 10646 if (ret < 0) 10647 return ret; 10648 10649 switch (kf_arg_type) { 10650 case KF_ARG_PTR_TO_CTX: 10651 if (reg->type != PTR_TO_CTX) { 10652 verbose(env, "arg#%d expected pointer to ctx, but got %s\n", i, btf_type_str(t)); 10653 return -EINVAL; 10654 } 10655 10656 if (meta->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx]) { 10657 ret = get_kern_ctx_btf_id(&env->log, resolve_prog_type(env->prog)); 10658 if (ret < 0) 10659 return -EINVAL; 10660 meta->ret_btf_id = ret; 10661 } 10662 break; 10663 case KF_ARG_PTR_TO_ALLOC_BTF_ID: 10664 if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) { 10665 verbose(env, "arg#%d expected pointer to allocated object\n", i); 10666 return -EINVAL; 10667 } 10668 if (!reg->ref_obj_id) { 10669 verbose(env, "allocated object must be referenced\n"); 10670 return -EINVAL; 10671 } 10672 if (meta->btf == btf_vmlinux && 10673 meta->func_id == special_kfunc_list[KF_bpf_obj_drop_impl]) { 10674 meta->arg_obj_drop.btf = reg->btf; 10675 meta->arg_obj_drop.btf_id = reg->btf_id; 10676 } 10677 break; 10678 case KF_ARG_PTR_TO_DYNPTR: 10679 { 10680 enum bpf_arg_type dynptr_arg_type = ARG_PTR_TO_DYNPTR; 10681 int clone_ref_obj_id = 0; 10682 10683 if (reg->type != PTR_TO_STACK && 10684 reg->type != CONST_PTR_TO_DYNPTR) { 10685 verbose(env, "arg#%d expected pointer to stack or dynptr_ptr\n", i); 10686 return -EINVAL; 10687 } 10688 10689 if (reg->type == CONST_PTR_TO_DYNPTR) 10690 dynptr_arg_type |= MEM_RDONLY; 10691 10692 if (is_kfunc_arg_uninit(btf, &args[i])) 10693 dynptr_arg_type |= MEM_UNINIT; 10694 10695 if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_from_skb]) { 10696 dynptr_arg_type |= DYNPTR_TYPE_SKB; 10697 } else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_from_xdp]) { 10698 dynptr_arg_type |= DYNPTR_TYPE_XDP; 10699 } else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_clone] && 10700 (dynptr_arg_type & MEM_UNINIT)) { 10701 enum bpf_dynptr_type parent_type = meta->initialized_dynptr.type; 10702 10703 if (parent_type == BPF_DYNPTR_TYPE_INVALID) { 10704 verbose(env, "verifier internal error: no dynptr type for parent of clone\n"); 10705 return -EFAULT; 10706 } 10707 10708 dynptr_arg_type |= (unsigned int)get_dynptr_type_flag(parent_type); 10709 clone_ref_obj_id = meta->initialized_dynptr.ref_obj_id; 10710 if (dynptr_type_refcounted(parent_type) && !clone_ref_obj_id) { 10711 verbose(env, "verifier internal error: missing ref obj id for parent of clone\n"); 10712 return -EFAULT; 10713 } 10714 } 10715 10716 ret = process_dynptr_func(env, regno, insn_idx, dynptr_arg_type, clone_ref_obj_id); 10717 if (ret < 0) 10718 return ret; 10719 10720 if (!(dynptr_arg_type & MEM_UNINIT)) { 10721 int id = dynptr_id(env, reg); 10722 10723 if (id < 0) { 10724 verbose(env, "verifier internal error: failed to obtain dynptr id\n"); 10725 return id; 10726 } 10727 meta->initialized_dynptr.id = id; 10728 meta->initialized_dynptr.type = dynptr_get_type(env, reg); 10729 meta->initialized_dynptr.ref_obj_id = dynptr_ref_obj_id(env, reg); 10730 } 10731 10732 break; 10733 } 10734 case KF_ARG_PTR_TO_ITER: 10735 ret = process_iter_arg(env, regno, insn_idx, meta); 10736 if (ret < 0) 10737 return ret; 10738 break; 10739 case KF_ARG_PTR_TO_LIST_HEAD: 10740 if (reg->type != PTR_TO_MAP_VALUE && 10741 reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) { 10742 verbose(env, "arg#%d expected pointer to map value or allocated object\n", i); 10743 return -EINVAL; 10744 } 10745 if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC) && !reg->ref_obj_id) { 10746 verbose(env, "allocated object must be referenced\n"); 10747 return -EINVAL; 10748 } 10749 ret = process_kf_arg_ptr_to_list_head(env, reg, regno, meta); 10750 if (ret < 0) 10751 return ret; 10752 break; 10753 case KF_ARG_PTR_TO_RB_ROOT: 10754 if (reg->type != PTR_TO_MAP_VALUE && 10755 reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) { 10756 verbose(env, "arg#%d expected pointer to map value or allocated object\n", i); 10757 return -EINVAL; 10758 } 10759 if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC) && !reg->ref_obj_id) { 10760 verbose(env, "allocated object must be referenced\n"); 10761 return -EINVAL; 10762 } 10763 ret = process_kf_arg_ptr_to_rbtree_root(env, reg, regno, meta); 10764 if (ret < 0) 10765 return ret; 10766 break; 10767 case KF_ARG_PTR_TO_LIST_NODE: 10768 if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) { 10769 verbose(env, "arg#%d expected pointer to allocated object\n", i); 10770 return -EINVAL; 10771 } 10772 if (!reg->ref_obj_id) { 10773 verbose(env, "allocated object must be referenced\n"); 10774 return -EINVAL; 10775 } 10776 ret = process_kf_arg_ptr_to_list_node(env, reg, regno, meta); 10777 if (ret < 0) 10778 return ret; 10779 break; 10780 case KF_ARG_PTR_TO_RB_NODE: 10781 if (meta->func_id == special_kfunc_list[KF_bpf_rbtree_remove]) { 10782 if (!type_is_non_owning_ref(reg->type) || reg->ref_obj_id) { 10783 verbose(env, "rbtree_remove node input must be non-owning ref\n"); 10784 return -EINVAL; 10785 } 10786 if (in_rbtree_lock_required_cb(env)) { 10787 verbose(env, "rbtree_remove not allowed in rbtree cb\n"); 10788 return -EINVAL; 10789 } 10790 } else { 10791 if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) { 10792 verbose(env, "arg#%d expected pointer to allocated object\n", i); 10793 return -EINVAL; 10794 } 10795 if (!reg->ref_obj_id) { 10796 verbose(env, "allocated object must be referenced\n"); 10797 return -EINVAL; 10798 } 10799 } 10800 10801 ret = process_kf_arg_ptr_to_rbtree_node(env, reg, regno, meta); 10802 if (ret < 0) 10803 return ret; 10804 break; 10805 case KF_ARG_PTR_TO_BTF_ID: 10806 /* Only base_type is checked, further checks are done here */ 10807 if ((base_type(reg->type) != PTR_TO_BTF_ID || 10808 (bpf_type_has_unsafe_modifiers(reg->type) && !is_rcu_reg(reg))) && 10809 !reg2btf_ids[base_type(reg->type)]) { 10810 verbose(env, "arg#%d is %s ", i, reg_type_str(env, reg->type)); 10811 verbose(env, "expected %s or socket\n", 10812 reg_type_str(env, base_type(reg->type) | 10813 (type_flag(reg->type) & BPF_REG_TRUSTED_MODIFIERS))); 10814 return -EINVAL; 10815 } 10816 ret = process_kf_arg_ptr_to_btf_id(env, reg, ref_t, ref_tname, ref_id, meta, i); 10817 if (ret < 0) 10818 return ret; 10819 break; 10820 case KF_ARG_PTR_TO_MEM: 10821 resolve_ret = btf_resolve_size(btf, ref_t, &type_size); 10822 if (IS_ERR(resolve_ret)) { 10823 verbose(env, "arg#%d reference type('%s %s') size cannot be determined: %ld\n", 10824 i, btf_type_str(ref_t), ref_tname, PTR_ERR(resolve_ret)); 10825 return -EINVAL; 10826 } 10827 ret = check_mem_reg(env, reg, regno, type_size); 10828 if (ret < 0) 10829 return ret; 10830 break; 10831 case KF_ARG_PTR_TO_MEM_SIZE: 10832 { 10833 struct bpf_reg_state *size_reg = ®s[regno + 1]; 10834 const struct btf_param *size_arg = &args[i + 1]; 10835 10836 ret = check_kfunc_mem_size_reg(env, size_reg, regno + 1); 10837 if (ret < 0) { 10838 verbose(env, "arg#%d arg#%d memory, len pair leads to invalid memory access\n", i, i + 1); 10839 return ret; 10840 } 10841 10842 if (is_kfunc_arg_const_mem_size(meta->btf, size_arg, size_reg)) { 10843 if (meta->arg_constant.found) { 10844 verbose(env, "verifier internal error: only one constant argument permitted\n"); 10845 return -EFAULT; 10846 } 10847 if (!tnum_is_const(size_reg->var_off)) { 10848 verbose(env, "R%d must be a known constant\n", regno + 1); 10849 return -EINVAL; 10850 } 10851 meta->arg_constant.found = true; 10852 meta->arg_constant.value = size_reg->var_off.value; 10853 } 10854 10855 /* Skip next '__sz' or '__szk' argument */ 10856 i++; 10857 break; 10858 } 10859 case KF_ARG_PTR_TO_CALLBACK: 10860 meta->subprogno = reg->subprogno; 10861 break; 10862 case KF_ARG_PTR_TO_REFCOUNTED_KPTR: 10863 if (!type_is_ptr_alloc_obj(reg->type) && !type_is_non_owning_ref(reg->type)) { 10864 verbose(env, "arg#%d is neither owning or non-owning ref\n", i); 10865 return -EINVAL; 10866 } 10867 10868 rec = reg_btf_record(reg); 10869 if (!rec) { 10870 verbose(env, "verifier internal error: Couldn't find btf_record\n"); 10871 return -EFAULT; 10872 } 10873 10874 if (rec->refcount_off < 0) { 10875 verbose(env, "arg#%d doesn't point to a type with bpf_refcount field\n", i); 10876 return -EINVAL; 10877 } 10878 if (rec->refcount_off >= 0) { 10879 verbose(env, "bpf_refcount_acquire calls are disabled for now\n"); 10880 return -EINVAL; 10881 } 10882 meta->arg_refcount_acquire.btf = reg->btf; 10883 meta->arg_refcount_acquire.btf_id = reg->btf_id; 10884 break; 10885 } 10886 } 10887 10888 if (is_kfunc_release(meta) && !meta->release_regno) { 10889 verbose(env, "release kernel function %s expects refcounted PTR_TO_BTF_ID\n", 10890 func_name); 10891 return -EINVAL; 10892 } 10893 10894 return 0; 10895 } 10896 10897 static int fetch_kfunc_meta(struct bpf_verifier_env *env, 10898 struct bpf_insn *insn, 10899 struct bpf_kfunc_call_arg_meta *meta, 10900 const char **kfunc_name) 10901 { 10902 const struct btf_type *func, *func_proto; 10903 u32 func_id, *kfunc_flags; 10904 const char *func_name; 10905 struct btf *desc_btf; 10906 10907 if (kfunc_name) 10908 *kfunc_name = NULL; 10909 10910 if (!insn->imm) 10911 return -EINVAL; 10912 10913 desc_btf = find_kfunc_desc_btf(env, insn->off); 10914 if (IS_ERR(desc_btf)) 10915 return PTR_ERR(desc_btf); 10916 10917 func_id = insn->imm; 10918 func = btf_type_by_id(desc_btf, func_id); 10919 func_name = btf_name_by_offset(desc_btf, func->name_off); 10920 if (kfunc_name) 10921 *kfunc_name = func_name; 10922 func_proto = btf_type_by_id(desc_btf, func->type); 10923 10924 kfunc_flags = btf_kfunc_id_set_contains(desc_btf, resolve_prog_type(env->prog), func_id); 10925 if (!kfunc_flags) { 10926 return -EACCES; 10927 } 10928 10929 memset(meta, 0, sizeof(*meta)); 10930 meta->btf = desc_btf; 10931 meta->func_id = func_id; 10932 meta->kfunc_flags = *kfunc_flags; 10933 meta->func_proto = func_proto; 10934 meta->func_name = func_name; 10935 10936 return 0; 10937 } 10938 10939 static int check_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn, 10940 int *insn_idx_p) 10941 { 10942 const struct btf_type *t, *ptr_type; 10943 u32 i, nargs, ptr_type_id, release_ref_obj_id; 10944 struct bpf_reg_state *regs = cur_regs(env); 10945 const char *func_name, *ptr_type_name; 10946 bool sleepable, rcu_lock, rcu_unlock; 10947 struct bpf_kfunc_call_arg_meta meta; 10948 struct bpf_insn_aux_data *insn_aux; 10949 int err, insn_idx = *insn_idx_p; 10950 const struct btf_param *args; 10951 const struct btf_type *ret_t; 10952 struct btf *desc_btf; 10953 10954 /* skip for now, but return error when we find this in fixup_kfunc_call */ 10955 if (!insn->imm) 10956 return 0; 10957 10958 err = fetch_kfunc_meta(env, insn, &meta, &func_name); 10959 if (err == -EACCES && func_name) 10960 verbose(env, "calling kernel function %s is not allowed\n", func_name); 10961 if (err) 10962 return err; 10963 desc_btf = meta.btf; 10964 insn_aux = &env->insn_aux_data[insn_idx]; 10965 10966 insn_aux->is_iter_next = is_iter_next_kfunc(&meta); 10967 10968 if (is_kfunc_destructive(&meta) && !capable(CAP_SYS_BOOT)) { 10969 verbose(env, "destructive kfunc calls require CAP_SYS_BOOT capability\n"); 10970 return -EACCES; 10971 } 10972 10973 sleepable = is_kfunc_sleepable(&meta); 10974 if (sleepable && !env->prog->aux->sleepable) { 10975 verbose(env, "program must be sleepable to call sleepable kfunc %s\n", func_name); 10976 return -EACCES; 10977 } 10978 10979 rcu_lock = is_kfunc_bpf_rcu_read_lock(&meta); 10980 rcu_unlock = is_kfunc_bpf_rcu_read_unlock(&meta); 10981 10982 if (env->cur_state->active_rcu_lock) { 10983 struct bpf_func_state *state; 10984 struct bpf_reg_state *reg; 10985 10986 if (rcu_lock) { 10987 verbose(env, "nested rcu read lock (kernel function %s)\n", func_name); 10988 return -EINVAL; 10989 } else if (rcu_unlock) { 10990 bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({ 10991 if (reg->type & MEM_RCU) { 10992 reg->type &= ~(MEM_RCU | PTR_MAYBE_NULL); 10993 reg->type |= PTR_UNTRUSTED; 10994 } 10995 })); 10996 env->cur_state->active_rcu_lock = false; 10997 } else if (sleepable) { 10998 verbose(env, "kernel func %s is sleepable within rcu_read_lock region\n", func_name); 10999 return -EACCES; 11000 } 11001 } else if (rcu_lock) { 11002 env->cur_state->active_rcu_lock = true; 11003 } else if (rcu_unlock) { 11004 verbose(env, "unmatched rcu read unlock (kernel function %s)\n", func_name); 11005 return -EINVAL; 11006 } 11007 11008 /* Check the arguments */ 11009 err = check_kfunc_args(env, &meta, insn_idx); 11010 if (err < 0) 11011 return err; 11012 /* In case of release function, we get register number of refcounted 11013 * PTR_TO_BTF_ID in bpf_kfunc_arg_meta, do the release now. 11014 */ 11015 if (meta.release_regno) { 11016 err = release_reference(env, regs[meta.release_regno].ref_obj_id); 11017 if (err) { 11018 verbose(env, "kfunc %s#%d reference has not been acquired before\n", 11019 func_name, meta.func_id); 11020 return err; 11021 } 11022 } 11023 11024 if (meta.func_id == special_kfunc_list[KF_bpf_list_push_front_impl] || 11025 meta.func_id == special_kfunc_list[KF_bpf_list_push_back_impl] || 11026 meta.func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) { 11027 release_ref_obj_id = regs[BPF_REG_2].ref_obj_id; 11028 insn_aux->insert_off = regs[BPF_REG_2].off; 11029 err = ref_convert_owning_non_owning(env, release_ref_obj_id); 11030 if (err) { 11031 verbose(env, "kfunc %s#%d conversion of owning ref to non-owning failed\n", 11032 func_name, meta.func_id); 11033 return err; 11034 } 11035 11036 err = release_reference(env, release_ref_obj_id); 11037 if (err) { 11038 verbose(env, "kfunc %s#%d reference has not been acquired before\n", 11039 func_name, meta.func_id); 11040 return err; 11041 } 11042 } 11043 11044 if (meta.func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) { 11045 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno, 11046 set_rbtree_add_callback_state); 11047 if (err) { 11048 verbose(env, "kfunc %s#%d failed callback verification\n", 11049 func_name, meta.func_id); 11050 return err; 11051 } 11052 } 11053 11054 for (i = 0; i < CALLER_SAVED_REGS; i++) 11055 mark_reg_not_init(env, regs, caller_saved[i]); 11056 11057 /* Check return type */ 11058 t = btf_type_skip_modifiers(desc_btf, meta.func_proto->type, NULL); 11059 11060 if (is_kfunc_acquire(&meta) && !btf_type_is_struct_ptr(meta.btf, t)) { 11061 /* Only exception is bpf_obj_new_impl */ 11062 if (meta.btf != btf_vmlinux || 11063 (meta.func_id != special_kfunc_list[KF_bpf_obj_new_impl] && 11064 meta.func_id != special_kfunc_list[KF_bpf_refcount_acquire_impl])) { 11065 verbose(env, "acquire kernel function does not return PTR_TO_BTF_ID\n"); 11066 return -EINVAL; 11067 } 11068 } 11069 11070 if (btf_type_is_scalar(t)) { 11071 mark_reg_unknown(env, regs, BPF_REG_0); 11072 mark_btf_func_reg_size(env, BPF_REG_0, t->size); 11073 } else if (btf_type_is_ptr(t)) { 11074 ptr_type = btf_type_skip_modifiers(desc_btf, t->type, &ptr_type_id); 11075 11076 if (meta.btf == btf_vmlinux && btf_id_set_contains(&special_kfunc_set, meta.func_id)) { 11077 if (meta.func_id == special_kfunc_list[KF_bpf_obj_new_impl]) { 11078 struct btf *ret_btf; 11079 u32 ret_btf_id; 11080 11081 if (unlikely(!bpf_global_ma_set)) 11082 return -ENOMEM; 11083 11084 if (((u64)(u32)meta.arg_constant.value) != meta.arg_constant.value) { 11085 verbose(env, "local type ID argument must be in range [0, U32_MAX]\n"); 11086 return -EINVAL; 11087 } 11088 11089 ret_btf = env->prog->aux->btf; 11090 ret_btf_id = meta.arg_constant.value; 11091 11092 /* This may be NULL due to user not supplying a BTF */ 11093 if (!ret_btf) { 11094 verbose(env, "bpf_obj_new requires prog BTF\n"); 11095 return -EINVAL; 11096 } 11097 11098 ret_t = btf_type_by_id(ret_btf, ret_btf_id); 11099 if (!ret_t || !__btf_type_is_struct(ret_t)) { 11100 verbose(env, "bpf_obj_new type ID argument must be of a struct\n"); 11101 return -EINVAL; 11102 } 11103 11104 mark_reg_known_zero(env, regs, BPF_REG_0); 11105 regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC; 11106 regs[BPF_REG_0].btf = ret_btf; 11107 regs[BPF_REG_0].btf_id = ret_btf_id; 11108 11109 insn_aux->obj_new_size = ret_t->size; 11110 insn_aux->kptr_struct_meta = 11111 btf_find_struct_meta(ret_btf, ret_btf_id); 11112 } else if (meta.func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl]) { 11113 mark_reg_known_zero(env, regs, BPF_REG_0); 11114 regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC; 11115 regs[BPF_REG_0].btf = meta.arg_refcount_acquire.btf; 11116 regs[BPF_REG_0].btf_id = meta.arg_refcount_acquire.btf_id; 11117 11118 insn_aux->kptr_struct_meta = 11119 btf_find_struct_meta(meta.arg_refcount_acquire.btf, 11120 meta.arg_refcount_acquire.btf_id); 11121 } else if (meta.func_id == special_kfunc_list[KF_bpf_list_pop_front] || 11122 meta.func_id == special_kfunc_list[KF_bpf_list_pop_back]) { 11123 struct btf_field *field = meta.arg_list_head.field; 11124 11125 mark_reg_graph_node(regs, BPF_REG_0, &field->graph_root); 11126 } else if (meta.func_id == special_kfunc_list[KF_bpf_rbtree_remove] || 11127 meta.func_id == special_kfunc_list[KF_bpf_rbtree_first]) { 11128 struct btf_field *field = meta.arg_rbtree_root.field; 11129 11130 mark_reg_graph_node(regs, BPF_REG_0, &field->graph_root); 11131 } else if (meta.func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx]) { 11132 mark_reg_known_zero(env, regs, BPF_REG_0); 11133 regs[BPF_REG_0].type = PTR_TO_BTF_ID | PTR_TRUSTED; 11134 regs[BPF_REG_0].btf = desc_btf; 11135 regs[BPF_REG_0].btf_id = meta.ret_btf_id; 11136 } else if (meta.func_id == special_kfunc_list[KF_bpf_rdonly_cast]) { 11137 ret_t = btf_type_by_id(desc_btf, meta.arg_constant.value); 11138 if (!ret_t || !btf_type_is_struct(ret_t)) { 11139 verbose(env, 11140 "kfunc bpf_rdonly_cast type ID argument must be of a struct\n"); 11141 return -EINVAL; 11142 } 11143 11144 mark_reg_known_zero(env, regs, BPF_REG_0); 11145 regs[BPF_REG_0].type = PTR_TO_BTF_ID | PTR_UNTRUSTED; 11146 regs[BPF_REG_0].btf = desc_btf; 11147 regs[BPF_REG_0].btf_id = meta.arg_constant.value; 11148 } else if (meta.func_id == special_kfunc_list[KF_bpf_dynptr_slice] || 11149 meta.func_id == special_kfunc_list[KF_bpf_dynptr_slice_rdwr]) { 11150 enum bpf_type_flag type_flag = get_dynptr_type_flag(meta.initialized_dynptr.type); 11151 11152 mark_reg_known_zero(env, regs, BPF_REG_0); 11153 11154 if (!meta.arg_constant.found) { 11155 verbose(env, "verifier internal error: bpf_dynptr_slice(_rdwr) no constant size\n"); 11156 return -EFAULT; 11157 } 11158 11159 regs[BPF_REG_0].mem_size = meta.arg_constant.value; 11160 11161 /* PTR_MAYBE_NULL will be added when is_kfunc_ret_null is checked */ 11162 regs[BPF_REG_0].type = PTR_TO_MEM | type_flag; 11163 11164 if (meta.func_id == special_kfunc_list[KF_bpf_dynptr_slice]) { 11165 regs[BPF_REG_0].type |= MEM_RDONLY; 11166 } else { 11167 /* this will set env->seen_direct_write to true */ 11168 if (!may_access_direct_pkt_data(env, NULL, BPF_WRITE)) { 11169 verbose(env, "the prog does not allow writes to packet data\n"); 11170 return -EINVAL; 11171 } 11172 } 11173 11174 if (!meta.initialized_dynptr.id) { 11175 verbose(env, "verifier internal error: no dynptr id\n"); 11176 return -EFAULT; 11177 } 11178 regs[BPF_REG_0].dynptr_id = meta.initialized_dynptr.id; 11179 11180 /* we don't need to set BPF_REG_0's ref obj id 11181 * because packet slices are not refcounted (see 11182 * dynptr_type_refcounted) 11183 */ 11184 } else { 11185 verbose(env, "kernel function %s unhandled dynamic return type\n", 11186 meta.func_name); 11187 return -EFAULT; 11188 } 11189 } else if (!__btf_type_is_struct(ptr_type)) { 11190 if (!meta.r0_size) { 11191 __u32 sz; 11192 11193 if (!IS_ERR(btf_resolve_size(desc_btf, ptr_type, &sz))) { 11194 meta.r0_size = sz; 11195 meta.r0_rdonly = true; 11196 } 11197 } 11198 if (!meta.r0_size) { 11199 ptr_type_name = btf_name_by_offset(desc_btf, 11200 ptr_type->name_off); 11201 verbose(env, 11202 "kernel function %s returns pointer type %s %s is not supported\n", 11203 func_name, 11204 btf_type_str(ptr_type), 11205 ptr_type_name); 11206 return -EINVAL; 11207 } 11208 11209 mark_reg_known_zero(env, regs, BPF_REG_0); 11210 regs[BPF_REG_0].type = PTR_TO_MEM; 11211 regs[BPF_REG_0].mem_size = meta.r0_size; 11212 11213 if (meta.r0_rdonly) 11214 regs[BPF_REG_0].type |= MEM_RDONLY; 11215 11216 /* Ensures we don't access the memory after a release_reference() */ 11217 if (meta.ref_obj_id) 11218 regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id; 11219 } else { 11220 mark_reg_known_zero(env, regs, BPF_REG_0); 11221 regs[BPF_REG_0].btf = desc_btf; 11222 regs[BPF_REG_0].type = PTR_TO_BTF_ID; 11223 regs[BPF_REG_0].btf_id = ptr_type_id; 11224 } 11225 11226 if (is_kfunc_ret_null(&meta)) { 11227 regs[BPF_REG_0].type |= PTR_MAYBE_NULL; 11228 /* For mark_ptr_or_null_reg, see 93c230e3f5bd6 */ 11229 regs[BPF_REG_0].id = ++env->id_gen; 11230 } 11231 mark_btf_func_reg_size(env, BPF_REG_0, sizeof(void *)); 11232 if (is_kfunc_acquire(&meta)) { 11233 int id = acquire_reference_state(env, insn_idx); 11234 11235 if (id < 0) 11236 return id; 11237 if (is_kfunc_ret_null(&meta)) 11238 regs[BPF_REG_0].id = id; 11239 regs[BPF_REG_0].ref_obj_id = id; 11240 } else if (meta.func_id == special_kfunc_list[KF_bpf_rbtree_first]) { 11241 ref_set_non_owning(env, ®s[BPF_REG_0]); 11242 } 11243 11244 if (reg_may_point_to_spin_lock(®s[BPF_REG_0]) && !regs[BPF_REG_0].id) 11245 regs[BPF_REG_0].id = ++env->id_gen; 11246 } else if (btf_type_is_void(t)) { 11247 if (meta.btf == btf_vmlinux && btf_id_set_contains(&special_kfunc_set, meta.func_id)) { 11248 if (meta.func_id == special_kfunc_list[KF_bpf_obj_drop_impl]) { 11249 insn_aux->kptr_struct_meta = 11250 btf_find_struct_meta(meta.arg_obj_drop.btf, 11251 meta.arg_obj_drop.btf_id); 11252 } 11253 } 11254 } 11255 11256 nargs = btf_type_vlen(meta.func_proto); 11257 args = (const struct btf_param *)(meta.func_proto + 1); 11258 for (i = 0; i < nargs; i++) { 11259 u32 regno = i + 1; 11260 11261 t = btf_type_skip_modifiers(desc_btf, args[i].type, NULL); 11262 if (btf_type_is_ptr(t)) 11263 mark_btf_func_reg_size(env, regno, sizeof(void *)); 11264 else 11265 /* scalar. ensured by btf_check_kfunc_arg_match() */ 11266 mark_btf_func_reg_size(env, regno, t->size); 11267 } 11268 11269 if (is_iter_next_kfunc(&meta)) { 11270 err = process_iter_next_call(env, insn_idx, &meta); 11271 if (err) 11272 return err; 11273 } 11274 11275 return 0; 11276 } 11277 11278 static bool signed_add_overflows(s64 a, s64 b) 11279 { 11280 /* Do the add in u64, where overflow is well-defined */ 11281 s64 res = (s64)((u64)a + (u64)b); 11282 11283 if (b < 0) 11284 return res > a; 11285 return res < a; 11286 } 11287 11288 static bool signed_add32_overflows(s32 a, s32 b) 11289 { 11290 /* Do the add in u32, where overflow is well-defined */ 11291 s32 res = (s32)((u32)a + (u32)b); 11292 11293 if (b < 0) 11294 return res > a; 11295 return res < a; 11296 } 11297 11298 static bool signed_sub_overflows(s64 a, s64 b) 11299 { 11300 /* Do the sub in u64, where overflow is well-defined */ 11301 s64 res = (s64)((u64)a - (u64)b); 11302 11303 if (b < 0) 11304 return res < a; 11305 return res > a; 11306 } 11307 11308 static bool signed_sub32_overflows(s32 a, s32 b) 11309 { 11310 /* Do the sub in u32, where overflow is well-defined */ 11311 s32 res = (s32)((u32)a - (u32)b); 11312 11313 if (b < 0) 11314 return res < a; 11315 return res > a; 11316 } 11317 11318 static bool check_reg_sane_offset(struct bpf_verifier_env *env, 11319 const struct bpf_reg_state *reg, 11320 enum bpf_reg_type type) 11321 { 11322 bool known = tnum_is_const(reg->var_off); 11323 s64 val = reg->var_off.value; 11324 s64 smin = reg->smin_value; 11325 11326 if (known && (val >= BPF_MAX_VAR_OFF || val <= -BPF_MAX_VAR_OFF)) { 11327 verbose(env, "math between %s pointer and %lld is not allowed\n", 11328 reg_type_str(env, type), val); 11329 return false; 11330 } 11331 11332 if (reg->off >= BPF_MAX_VAR_OFF || reg->off <= -BPF_MAX_VAR_OFF) { 11333 verbose(env, "%s pointer offset %d is not allowed\n", 11334 reg_type_str(env, type), reg->off); 11335 return false; 11336 } 11337 11338 if (smin == S64_MIN) { 11339 verbose(env, "math between %s pointer and register with unbounded min value is not allowed\n", 11340 reg_type_str(env, type)); 11341 return false; 11342 } 11343 11344 if (smin >= BPF_MAX_VAR_OFF || smin <= -BPF_MAX_VAR_OFF) { 11345 verbose(env, "value %lld makes %s pointer be out of bounds\n", 11346 smin, reg_type_str(env, type)); 11347 return false; 11348 } 11349 11350 return true; 11351 } 11352 11353 enum { 11354 REASON_BOUNDS = -1, 11355 REASON_TYPE = -2, 11356 REASON_PATHS = -3, 11357 REASON_LIMIT = -4, 11358 REASON_STACK = -5, 11359 }; 11360 11361 static int retrieve_ptr_limit(const struct bpf_reg_state *ptr_reg, 11362 u32 *alu_limit, bool mask_to_left) 11363 { 11364 u32 max = 0, ptr_limit = 0; 11365 11366 switch (ptr_reg->type) { 11367 case PTR_TO_STACK: 11368 /* Offset 0 is out-of-bounds, but acceptable start for the 11369 * left direction, see BPF_REG_FP. Also, unknown scalar 11370 * offset where we would need to deal with min/max bounds is 11371 * currently prohibited for unprivileged. 11372 */ 11373 max = MAX_BPF_STACK + mask_to_left; 11374 ptr_limit = -(ptr_reg->var_off.value + ptr_reg->off); 11375 break; 11376 case PTR_TO_MAP_VALUE: 11377 max = ptr_reg->map_ptr->value_size; 11378 ptr_limit = (mask_to_left ? 11379 ptr_reg->smin_value : 11380 ptr_reg->umax_value) + ptr_reg->off; 11381 break; 11382 default: 11383 return REASON_TYPE; 11384 } 11385 11386 if (ptr_limit >= max) 11387 return REASON_LIMIT; 11388 *alu_limit = ptr_limit; 11389 return 0; 11390 } 11391 11392 static bool can_skip_alu_sanitation(const struct bpf_verifier_env *env, 11393 const struct bpf_insn *insn) 11394 { 11395 return env->bypass_spec_v1 || BPF_SRC(insn->code) == BPF_K; 11396 } 11397 11398 static int update_alu_sanitation_state(struct bpf_insn_aux_data *aux, 11399 u32 alu_state, u32 alu_limit) 11400 { 11401 /* If we arrived here from different branches with different 11402 * state or limits to sanitize, then this won't work. 11403 */ 11404 if (aux->alu_state && 11405 (aux->alu_state != alu_state || 11406 aux->alu_limit != alu_limit)) 11407 return REASON_PATHS; 11408 11409 /* Corresponding fixup done in do_misc_fixups(). */ 11410 aux->alu_state = alu_state; 11411 aux->alu_limit = alu_limit; 11412 return 0; 11413 } 11414 11415 static int sanitize_val_alu(struct bpf_verifier_env *env, 11416 struct bpf_insn *insn) 11417 { 11418 struct bpf_insn_aux_data *aux = cur_aux(env); 11419 11420 if (can_skip_alu_sanitation(env, insn)) 11421 return 0; 11422 11423 return update_alu_sanitation_state(aux, BPF_ALU_NON_POINTER, 0); 11424 } 11425 11426 static bool sanitize_needed(u8 opcode) 11427 { 11428 return opcode == BPF_ADD || opcode == BPF_SUB; 11429 } 11430 11431 struct bpf_sanitize_info { 11432 struct bpf_insn_aux_data aux; 11433 bool mask_to_left; 11434 }; 11435 11436 static struct bpf_verifier_state * 11437 sanitize_speculative_path(struct bpf_verifier_env *env, 11438 const struct bpf_insn *insn, 11439 u32 next_idx, u32 curr_idx) 11440 { 11441 struct bpf_verifier_state *branch; 11442 struct bpf_reg_state *regs; 11443 11444 branch = push_stack(env, next_idx, curr_idx, true); 11445 if (branch && insn) { 11446 regs = branch->frame[branch->curframe]->regs; 11447 if (BPF_SRC(insn->code) == BPF_K) { 11448 mark_reg_unknown(env, regs, insn->dst_reg); 11449 } else if (BPF_SRC(insn->code) == BPF_X) { 11450 mark_reg_unknown(env, regs, insn->dst_reg); 11451 mark_reg_unknown(env, regs, insn->src_reg); 11452 } 11453 } 11454 return branch; 11455 } 11456 11457 static int sanitize_ptr_alu(struct bpf_verifier_env *env, 11458 struct bpf_insn *insn, 11459 const struct bpf_reg_state *ptr_reg, 11460 const struct bpf_reg_state *off_reg, 11461 struct bpf_reg_state *dst_reg, 11462 struct bpf_sanitize_info *info, 11463 const bool commit_window) 11464 { 11465 struct bpf_insn_aux_data *aux = commit_window ? cur_aux(env) : &info->aux; 11466 struct bpf_verifier_state *vstate = env->cur_state; 11467 bool off_is_imm = tnum_is_const(off_reg->var_off); 11468 bool off_is_neg = off_reg->smin_value < 0; 11469 bool ptr_is_dst_reg = ptr_reg == dst_reg; 11470 u8 opcode = BPF_OP(insn->code); 11471 u32 alu_state, alu_limit; 11472 struct bpf_reg_state tmp; 11473 bool ret; 11474 int err; 11475 11476 if (can_skip_alu_sanitation(env, insn)) 11477 return 0; 11478 11479 /* We already marked aux for masking from non-speculative 11480 * paths, thus we got here in the first place. We only care 11481 * to explore bad access from here. 11482 */ 11483 if (vstate->speculative) 11484 goto do_sim; 11485 11486 if (!commit_window) { 11487 if (!tnum_is_const(off_reg->var_off) && 11488 (off_reg->smin_value < 0) != (off_reg->smax_value < 0)) 11489 return REASON_BOUNDS; 11490 11491 info->mask_to_left = (opcode == BPF_ADD && off_is_neg) || 11492 (opcode == BPF_SUB && !off_is_neg); 11493 } 11494 11495 err = retrieve_ptr_limit(ptr_reg, &alu_limit, info->mask_to_left); 11496 if (err < 0) 11497 return err; 11498 11499 if (commit_window) { 11500 /* In commit phase we narrow the masking window based on 11501 * the observed pointer move after the simulated operation. 11502 */ 11503 alu_state = info->aux.alu_state; 11504 alu_limit = abs(info->aux.alu_limit - alu_limit); 11505 } else { 11506 alu_state = off_is_neg ? BPF_ALU_NEG_VALUE : 0; 11507 alu_state |= off_is_imm ? BPF_ALU_IMMEDIATE : 0; 11508 alu_state |= ptr_is_dst_reg ? 11509 BPF_ALU_SANITIZE_SRC : BPF_ALU_SANITIZE_DST; 11510 11511 /* Limit pruning on unknown scalars to enable deep search for 11512 * potential masking differences from other program paths. 11513 */ 11514 if (!off_is_imm) 11515 env->explore_alu_limits = true; 11516 } 11517 11518 err = update_alu_sanitation_state(aux, alu_state, alu_limit); 11519 if (err < 0) 11520 return err; 11521 do_sim: 11522 /* If we're in commit phase, we're done here given we already 11523 * pushed the truncated dst_reg into the speculative verification 11524 * stack. 11525 * 11526 * Also, when register is a known constant, we rewrite register-based 11527 * operation to immediate-based, and thus do not need masking (and as 11528 * a consequence, do not need to simulate the zero-truncation either). 11529 */ 11530 if (commit_window || off_is_imm) 11531 return 0; 11532 11533 /* Simulate and find potential out-of-bounds access under 11534 * speculative execution from truncation as a result of 11535 * masking when off was not within expected range. If off 11536 * sits in dst, then we temporarily need to move ptr there 11537 * to simulate dst (== 0) +/-= ptr. Needed, for example, 11538 * for cases where we use K-based arithmetic in one direction 11539 * and truncated reg-based in the other in order to explore 11540 * bad access. 11541 */ 11542 if (!ptr_is_dst_reg) { 11543 tmp = *dst_reg; 11544 copy_register_state(dst_reg, ptr_reg); 11545 } 11546 ret = sanitize_speculative_path(env, NULL, env->insn_idx + 1, 11547 env->insn_idx); 11548 if (!ptr_is_dst_reg && ret) 11549 *dst_reg = tmp; 11550 return !ret ? REASON_STACK : 0; 11551 } 11552 11553 static void sanitize_mark_insn_seen(struct bpf_verifier_env *env) 11554 { 11555 struct bpf_verifier_state *vstate = env->cur_state; 11556 11557 /* If we simulate paths under speculation, we don't update the 11558 * insn as 'seen' such that when we verify unreachable paths in 11559 * the non-speculative domain, sanitize_dead_code() can still 11560 * rewrite/sanitize them. 11561 */ 11562 if (!vstate->speculative) 11563 env->insn_aux_data[env->insn_idx].seen = env->pass_cnt; 11564 } 11565 11566 static int sanitize_err(struct bpf_verifier_env *env, 11567 const struct bpf_insn *insn, int reason, 11568 const struct bpf_reg_state *off_reg, 11569 const struct bpf_reg_state *dst_reg) 11570 { 11571 static const char *err = "pointer arithmetic with it prohibited for !root"; 11572 const char *op = BPF_OP(insn->code) == BPF_ADD ? "add" : "sub"; 11573 u32 dst = insn->dst_reg, src = insn->src_reg; 11574 11575 switch (reason) { 11576 case REASON_BOUNDS: 11577 verbose(env, "R%d has unknown scalar with mixed signed bounds, %s\n", 11578 off_reg == dst_reg ? dst : src, err); 11579 break; 11580 case REASON_TYPE: 11581 verbose(env, "R%d has pointer with unsupported alu operation, %s\n", 11582 off_reg == dst_reg ? src : dst, err); 11583 break; 11584 case REASON_PATHS: 11585 verbose(env, "R%d tried to %s from different maps, paths or scalars, %s\n", 11586 dst, op, err); 11587 break; 11588 case REASON_LIMIT: 11589 verbose(env, "R%d tried to %s beyond pointer bounds, %s\n", 11590 dst, op, err); 11591 break; 11592 case REASON_STACK: 11593 verbose(env, "R%d could not be pushed for speculative verification, %s\n", 11594 dst, err); 11595 break; 11596 default: 11597 verbose(env, "verifier internal error: unknown reason (%d)\n", 11598 reason); 11599 break; 11600 } 11601 11602 return -EACCES; 11603 } 11604 11605 /* check that stack access falls within stack limits and that 'reg' doesn't 11606 * have a variable offset. 11607 * 11608 * Variable offset is prohibited for unprivileged mode for simplicity since it 11609 * requires corresponding support in Spectre masking for stack ALU. See also 11610 * retrieve_ptr_limit(). 11611 * 11612 * 11613 * 'off' includes 'reg->off'. 11614 */ 11615 static int check_stack_access_for_ptr_arithmetic( 11616 struct bpf_verifier_env *env, 11617 int regno, 11618 const struct bpf_reg_state *reg, 11619 int off) 11620 { 11621 if (!tnum_is_const(reg->var_off)) { 11622 char tn_buf[48]; 11623 11624 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 11625 verbose(env, "R%d variable stack access prohibited for !root, var_off=%s off=%d\n", 11626 regno, tn_buf, off); 11627 return -EACCES; 11628 } 11629 11630 if (off >= 0 || off < -MAX_BPF_STACK) { 11631 verbose(env, "R%d stack pointer arithmetic goes out of range, " 11632 "prohibited for !root; off=%d\n", regno, off); 11633 return -EACCES; 11634 } 11635 11636 return 0; 11637 } 11638 11639 static int sanitize_check_bounds(struct bpf_verifier_env *env, 11640 const struct bpf_insn *insn, 11641 const struct bpf_reg_state *dst_reg) 11642 { 11643 u32 dst = insn->dst_reg; 11644 11645 /* For unprivileged we require that resulting offset must be in bounds 11646 * in order to be able to sanitize access later on. 11647 */ 11648 if (env->bypass_spec_v1) 11649 return 0; 11650 11651 switch (dst_reg->type) { 11652 case PTR_TO_STACK: 11653 if (check_stack_access_for_ptr_arithmetic(env, dst, dst_reg, 11654 dst_reg->off + dst_reg->var_off.value)) 11655 return -EACCES; 11656 break; 11657 case PTR_TO_MAP_VALUE: 11658 if (check_map_access(env, dst, dst_reg->off, 1, false, ACCESS_HELPER)) { 11659 verbose(env, "R%d pointer arithmetic of map value goes out of range, " 11660 "prohibited for !root\n", dst); 11661 return -EACCES; 11662 } 11663 break; 11664 default: 11665 break; 11666 } 11667 11668 return 0; 11669 } 11670 11671 /* Handles arithmetic on a pointer and a scalar: computes new min/max and var_off. 11672 * Caller should also handle BPF_MOV case separately. 11673 * If we return -EACCES, caller may want to try again treating pointer as a 11674 * scalar. So we only emit a diagnostic if !env->allow_ptr_leaks. 11675 */ 11676 static int adjust_ptr_min_max_vals(struct bpf_verifier_env *env, 11677 struct bpf_insn *insn, 11678 const struct bpf_reg_state *ptr_reg, 11679 const struct bpf_reg_state *off_reg) 11680 { 11681 struct bpf_verifier_state *vstate = env->cur_state; 11682 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 11683 struct bpf_reg_state *regs = state->regs, *dst_reg; 11684 bool known = tnum_is_const(off_reg->var_off); 11685 s64 smin_val = off_reg->smin_value, smax_val = off_reg->smax_value, 11686 smin_ptr = ptr_reg->smin_value, smax_ptr = ptr_reg->smax_value; 11687 u64 umin_val = off_reg->umin_value, umax_val = off_reg->umax_value, 11688 umin_ptr = ptr_reg->umin_value, umax_ptr = ptr_reg->umax_value; 11689 struct bpf_sanitize_info info = {}; 11690 u8 opcode = BPF_OP(insn->code); 11691 u32 dst = insn->dst_reg; 11692 int ret; 11693 11694 dst_reg = ®s[dst]; 11695 11696 if ((known && (smin_val != smax_val || umin_val != umax_val)) || 11697 smin_val > smax_val || umin_val > umax_val) { 11698 /* Taint dst register if offset had invalid bounds derived from 11699 * e.g. dead branches. 11700 */ 11701 __mark_reg_unknown(env, dst_reg); 11702 return 0; 11703 } 11704 11705 if (BPF_CLASS(insn->code) != BPF_ALU64) { 11706 /* 32-bit ALU ops on pointers produce (meaningless) scalars */ 11707 if (opcode == BPF_SUB && env->allow_ptr_leaks) { 11708 __mark_reg_unknown(env, dst_reg); 11709 return 0; 11710 } 11711 11712 verbose(env, 11713 "R%d 32-bit pointer arithmetic prohibited\n", 11714 dst); 11715 return -EACCES; 11716 } 11717 11718 if (ptr_reg->type & PTR_MAYBE_NULL) { 11719 verbose(env, "R%d pointer arithmetic on %s prohibited, null-check it first\n", 11720 dst, reg_type_str(env, ptr_reg->type)); 11721 return -EACCES; 11722 } 11723 11724 switch (base_type(ptr_reg->type)) { 11725 case CONST_PTR_TO_MAP: 11726 /* smin_val represents the known value */ 11727 if (known && smin_val == 0 && opcode == BPF_ADD) 11728 break; 11729 fallthrough; 11730 case PTR_TO_PACKET_END: 11731 case PTR_TO_SOCKET: 11732 case PTR_TO_SOCK_COMMON: 11733 case PTR_TO_TCP_SOCK: 11734 case PTR_TO_XDP_SOCK: 11735 verbose(env, "R%d pointer arithmetic on %s prohibited\n", 11736 dst, reg_type_str(env, ptr_reg->type)); 11737 return -EACCES; 11738 default: 11739 break; 11740 } 11741 11742 /* In case of 'scalar += pointer', dst_reg inherits pointer type and id. 11743 * The id may be overwritten later if we create a new variable offset. 11744 */ 11745 dst_reg->type = ptr_reg->type; 11746 dst_reg->id = ptr_reg->id; 11747 11748 if (!check_reg_sane_offset(env, off_reg, ptr_reg->type) || 11749 !check_reg_sane_offset(env, ptr_reg, ptr_reg->type)) 11750 return -EINVAL; 11751 11752 /* pointer types do not carry 32-bit bounds at the moment. */ 11753 __mark_reg32_unbounded(dst_reg); 11754 11755 if (sanitize_needed(opcode)) { 11756 ret = sanitize_ptr_alu(env, insn, ptr_reg, off_reg, dst_reg, 11757 &info, false); 11758 if (ret < 0) 11759 return sanitize_err(env, insn, ret, off_reg, dst_reg); 11760 } 11761 11762 switch (opcode) { 11763 case BPF_ADD: 11764 /* We can take a fixed offset as long as it doesn't overflow 11765 * the s32 'off' field 11766 */ 11767 if (known && (ptr_reg->off + smin_val == 11768 (s64)(s32)(ptr_reg->off + smin_val))) { 11769 /* pointer += K. Accumulate it into fixed offset */ 11770 dst_reg->smin_value = smin_ptr; 11771 dst_reg->smax_value = smax_ptr; 11772 dst_reg->umin_value = umin_ptr; 11773 dst_reg->umax_value = umax_ptr; 11774 dst_reg->var_off = ptr_reg->var_off; 11775 dst_reg->off = ptr_reg->off + smin_val; 11776 dst_reg->raw = ptr_reg->raw; 11777 break; 11778 } 11779 /* A new variable offset is created. Note that off_reg->off 11780 * == 0, since it's a scalar. 11781 * dst_reg gets the pointer type and since some positive 11782 * integer value was added to the pointer, give it a new 'id' 11783 * if it's a PTR_TO_PACKET. 11784 * this creates a new 'base' pointer, off_reg (variable) gets 11785 * added into the variable offset, and we copy the fixed offset 11786 * from ptr_reg. 11787 */ 11788 if (signed_add_overflows(smin_ptr, smin_val) || 11789 signed_add_overflows(smax_ptr, smax_val)) { 11790 dst_reg->smin_value = S64_MIN; 11791 dst_reg->smax_value = S64_MAX; 11792 } else { 11793 dst_reg->smin_value = smin_ptr + smin_val; 11794 dst_reg->smax_value = smax_ptr + smax_val; 11795 } 11796 if (umin_ptr + umin_val < umin_ptr || 11797 umax_ptr + umax_val < umax_ptr) { 11798 dst_reg->umin_value = 0; 11799 dst_reg->umax_value = U64_MAX; 11800 } else { 11801 dst_reg->umin_value = umin_ptr + umin_val; 11802 dst_reg->umax_value = umax_ptr + umax_val; 11803 } 11804 dst_reg->var_off = tnum_add(ptr_reg->var_off, off_reg->var_off); 11805 dst_reg->off = ptr_reg->off; 11806 dst_reg->raw = ptr_reg->raw; 11807 if (reg_is_pkt_pointer(ptr_reg)) { 11808 dst_reg->id = ++env->id_gen; 11809 /* something was added to pkt_ptr, set range to zero */ 11810 memset(&dst_reg->raw, 0, sizeof(dst_reg->raw)); 11811 } 11812 break; 11813 case BPF_SUB: 11814 if (dst_reg == off_reg) { 11815 /* scalar -= pointer. Creates an unknown scalar */ 11816 verbose(env, "R%d tried to subtract pointer from scalar\n", 11817 dst); 11818 return -EACCES; 11819 } 11820 /* We don't allow subtraction from FP, because (according to 11821 * test_verifier.c test "invalid fp arithmetic", JITs might not 11822 * be able to deal with it. 11823 */ 11824 if (ptr_reg->type == PTR_TO_STACK) { 11825 verbose(env, "R%d subtraction from stack pointer prohibited\n", 11826 dst); 11827 return -EACCES; 11828 } 11829 if (known && (ptr_reg->off - smin_val == 11830 (s64)(s32)(ptr_reg->off - smin_val))) { 11831 /* pointer -= K. Subtract it from fixed offset */ 11832 dst_reg->smin_value = smin_ptr; 11833 dst_reg->smax_value = smax_ptr; 11834 dst_reg->umin_value = umin_ptr; 11835 dst_reg->umax_value = umax_ptr; 11836 dst_reg->var_off = ptr_reg->var_off; 11837 dst_reg->id = ptr_reg->id; 11838 dst_reg->off = ptr_reg->off - smin_val; 11839 dst_reg->raw = ptr_reg->raw; 11840 break; 11841 } 11842 /* A new variable offset is created. If the subtrahend is known 11843 * nonnegative, then any reg->range we had before is still good. 11844 */ 11845 if (signed_sub_overflows(smin_ptr, smax_val) || 11846 signed_sub_overflows(smax_ptr, smin_val)) { 11847 /* Overflow possible, we know nothing */ 11848 dst_reg->smin_value = S64_MIN; 11849 dst_reg->smax_value = S64_MAX; 11850 } else { 11851 dst_reg->smin_value = smin_ptr - smax_val; 11852 dst_reg->smax_value = smax_ptr - smin_val; 11853 } 11854 if (umin_ptr < umax_val) { 11855 /* Overflow possible, we know nothing */ 11856 dst_reg->umin_value = 0; 11857 dst_reg->umax_value = U64_MAX; 11858 } else { 11859 /* Cannot overflow (as long as bounds are consistent) */ 11860 dst_reg->umin_value = umin_ptr - umax_val; 11861 dst_reg->umax_value = umax_ptr - umin_val; 11862 } 11863 dst_reg->var_off = tnum_sub(ptr_reg->var_off, off_reg->var_off); 11864 dst_reg->off = ptr_reg->off; 11865 dst_reg->raw = ptr_reg->raw; 11866 if (reg_is_pkt_pointer(ptr_reg)) { 11867 dst_reg->id = ++env->id_gen; 11868 /* something was added to pkt_ptr, set range to zero */ 11869 if (smin_val < 0) 11870 memset(&dst_reg->raw, 0, sizeof(dst_reg->raw)); 11871 } 11872 break; 11873 case BPF_AND: 11874 case BPF_OR: 11875 case BPF_XOR: 11876 /* bitwise ops on pointers are troublesome, prohibit. */ 11877 verbose(env, "R%d bitwise operator %s on pointer prohibited\n", 11878 dst, bpf_alu_string[opcode >> 4]); 11879 return -EACCES; 11880 default: 11881 /* other operators (e.g. MUL,LSH) produce non-pointer results */ 11882 verbose(env, "R%d pointer arithmetic with %s operator prohibited\n", 11883 dst, bpf_alu_string[opcode >> 4]); 11884 return -EACCES; 11885 } 11886 11887 if (!check_reg_sane_offset(env, dst_reg, ptr_reg->type)) 11888 return -EINVAL; 11889 reg_bounds_sync(dst_reg); 11890 if (sanitize_check_bounds(env, insn, dst_reg) < 0) 11891 return -EACCES; 11892 if (sanitize_needed(opcode)) { 11893 ret = sanitize_ptr_alu(env, insn, dst_reg, off_reg, dst_reg, 11894 &info, true); 11895 if (ret < 0) 11896 return sanitize_err(env, insn, ret, off_reg, dst_reg); 11897 } 11898 11899 return 0; 11900 } 11901 11902 static void scalar32_min_max_add(struct bpf_reg_state *dst_reg, 11903 struct bpf_reg_state *src_reg) 11904 { 11905 s32 smin_val = src_reg->s32_min_value; 11906 s32 smax_val = src_reg->s32_max_value; 11907 u32 umin_val = src_reg->u32_min_value; 11908 u32 umax_val = src_reg->u32_max_value; 11909 11910 if (signed_add32_overflows(dst_reg->s32_min_value, smin_val) || 11911 signed_add32_overflows(dst_reg->s32_max_value, smax_val)) { 11912 dst_reg->s32_min_value = S32_MIN; 11913 dst_reg->s32_max_value = S32_MAX; 11914 } else { 11915 dst_reg->s32_min_value += smin_val; 11916 dst_reg->s32_max_value += smax_val; 11917 } 11918 if (dst_reg->u32_min_value + umin_val < umin_val || 11919 dst_reg->u32_max_value + umax_val < umax_val) { 11920 dst_reg->u32_min_value = 0; 11921 dst_reg->u32_max_value = U32_MAX; 11922 } else { 11923 dst_reg->u32_min_value += umin_val; 11924 dst_reg->u32_max_value += umax_val; 11925 } 11926 } 11927 11928 static void scalar_min_max_add(struct bpf_reg_state *dst_reg, 11929 struct bpf_reg_state *src_reg) 11930 { 11931 s64 smin_val = src_reg->smin_value; 11932 s64 smax_val = src_reg->smax_value; 11933 u64 umin_val = src_reg->umin_value; 11934 u64 umax_val = src_reg->umax_value; 11935 11936 if (signed_add_overflows(dst_reg->smin_value, smin_val) || 11937 signed_add_overflows(dst_reg->smax_value, smax_val)) { 11938 dst_reg->smin_value = S64_MIN; 11939 dst_reg->smax_value = S64_MAX; 11940 } else { 11941 dst_reg->smin_value += smin_val; 11942 dst_reg->smax_value += smax_val; 11943 } 11944 if (dst_reg->umin_value + umin_val < umin_val || 11945 dst_reg->umax_value + umax_val < umax_val) { 11946 dst_reg->umin_value = 0; 11947 dst_reg->umax_value = U64_MAX; 11948 } else { 11949 dst_reg->umin_value += umin_val; 11950 dst_reg->umax_value += umax_val; 11951 } 11952 } 11953 11954 static void scalar32_min_max_sub(struct bpf_reg_state *dst_reg, 11955 struct bpf_reg_state *src_reg) 11956 { 11957 s32 smin_val = src_reg->s32_min_value; 11958 s32 smax_val = src_reg->s32_max_value; 11959 u32 umin_val = src_reg->u32_min_value; 11960 u32 umax_val = src_reg->u32_max_value; 11961 11962 if (signed_sub32_overflows(dst_reg->s32_min_value, smax_val) || 11963 signed_sub32_overflows(dst_reg->s32_max_value, smin_val)) { 11964 /* Overflow possible, we know nothing */ 11965 dst_reg->s32_min_value = S32_MIN; 11966 dst_reg->s32_max_value = S32_MAX; 11967 } else { 11968 dst_reg->s32_min_value -= smax_val; 11969 dst_reg->s32_max_value -= smin_val; 11970 } 11971 if (dst_reg->u32_min_value < umax_val) { 11972 /* Overflow possible, we know nothing */ 11973 dst_reg->u32_min_value = 0; 11974 dst_reg->u32_max_value = U32_MAX; 11975 } else { 11976 /* Cannot overflow (as long as bounds are consistent) */ 11977 dst_reg->u32_min_value -= umax_val; 11978 dst_reg->u32_max_value -= umin_val; 11979 } 11980 } 11981 11982 static void scalar_min_max_sub(struct bpf_reg_state *dst_reg, 11983 struct bpf_reg_state *src_reg) 11984 { 11985 s64 smin_val = src_reg->smin_value; 11986 s64 smax_val = src_reg->smax_value; 11987 u64 umin_val = src_reg->umin_value; 11988 u64 umax_val = src_reg->umax_value; 11989 11990 if (signed_sub_overflows(dst_reg->smin_value, smax_val) || 11991 signed_sub_overflows(dst_reg->smax_value, smin_val)) { 11992 /* Overflow possible, we know nothing */ 11993 dst_reg->smin_value = S64_MIN; 11994 dst_reg->smax_value = S64_MAX; 11995 } else { 11996 dst_reg->smin_value -= smax_val; 11997 dst_reg->smax_value -= smin_val; 11998 } 11999 if (dst_reg->umin_value < umax_val) { 12000 /* Overflow possible, we know nothing */ 12001 dst_reg->umin_value = 0; 12002 dst_reg->umax_value = U64_MAX; 12003 } else { 12004 /* Cannot overflow (as long as bounds are consistent) */ 12005 dst_reg->umin_value -= umax_val; 12006 dst_reg->umax_value -= umin_val; 12007 } 12008 } 12009 12010 static void scalar32_min_max_mul(struct bpf_reg_state *dst_reg, 12011 struct bpf_reg_state *src_reg) 12012 { 12013 s32 smin_val = src_reg->s32_min_value; 12014 u32 umin_val = src_reg->u32_min_value; 12015 u32 umax_val = src_reg->u32_max_value; 12016 12017 if (smin_val < 0 || dst_reg->s32_min_value < 0) { 12018 /* Ain't nobody got time to multiply that sign */ 12019 __mark_reg32_unbounded(dst_reg); 12020 return; 12021 } 12022 /* Both values are positive, so we can work with unsigned and 12023 * copy the result to signed (unless it exceeds S32_MAX). 12024 */ 12025 if (umax_val > U16_MAX || dst_reg->u32_max_value > U16_MAX) { 12026 /* Potential overflow, we know nothing */ 12027 __mark_reg32_unbounded(dst_reg); 12028 return; 12029 } 12030 dst_reg->u32_min_value *= umin_val; 12031 dst_reg->u32_max_value *= umax_val; 12032 if (dst_reg->u32_max_value > S32_MAX) { 12033 /* Overflow possible, we know nothing */ 12034 dst_reg->s32_min_value = S32_MIN; 12035 dst_reg->s32_max_value = S32_MAX; 12036 } else { 12037 dst_reg->s32_min_value = dst_reg->u32_min_value; 12038 dst_reg->s32_max_value = dst_reg->u32_max_value; 12039 } 12040 } 12041 12042 static void scalar_min_max_mul(struct bpf_reg_state *dst_reg, 12043 struct bpf_reg_state *src_reg) 12044 { 12045 s64 smin_val = src_reg->smin_value; 12046 u64 umin_val = src_reg->umin_value; 12047 u64 umax_val = src_reg->umax_value; 12048 12049 if (smin_val < 0 || dst_reg->smin_value < 0) { 12050 /* Ain't nobody got time to multiply that sign */ 12051 __mark_reg64_unbounded(dst_reg); 12052 return; 12053 } 12054 /* Both values are positive, so we can work with unsigned and 12055 * copy the result to signed (unless it exceeds S64_MAX). 12056 */ 12057 if (umax_val > U32_MAX || dst_reg->umax_value > U32_MAX) { 12058 /* Potential overflow, we know nothing */ 12059 __mark_reg64_unbounded(dst_reg); 12060 return; 12061 } 12062 dst_reg->umin_value *= umin_val; 12063 dst_reg->umax_value *= umax_val; 12064 if (dst_reg->umax_value > S64_MAX) { 12065 /* Overflow possible, we know nothing */ 12066 dst_reg->smin_value = S64_MIN; 12067 dst_reg->smax_value = S64_MAX; 12068 } else { 12069 dst_reg->smin_value = dst_reg->umin_value; 12070 dst_reg->smax_value = dst_reg->umax_value; 12071 } 12072 } 12073 12074 static void scalar32_min_max_and(struct bpf_reg_state *dst_reg, 12075 struct bpf_reg_state *src_reg) 12076 { 12077 bool src_known = tnum_subreg_is_const(src_reg->var_off); 12078 bool dst_known = tnum_subreg_is_const(dst_reg->var_off); 12079 struct tnum var32_off = tnum_subreg(dst_reg->var_off); 12080 s32 smin_val = src_reg->s32_min_value; 12081 u32 umax_val = src_reg->u32_max_value; 12082 12083 if (src_known && dst_known) { 12084 __mark_reg32_known(dst_reg, var32_off.value); 12085 return; 12086 } 12087 12088 /* We get our minimum from the var_off, since that's inherently 12089 * bitwise. Our maximum is the minimum of the operands' maxima. 12090 */ 12091 dst_reg->u32_min_value = var32_off.value; 12092 dst_reg->u32_max_value = min(dst_reg->u32_max_value, umax_val); 12093 if (dst_reg->s32_min_value < 0 || smin_val < 0) { 12094 /* Lose signed bounds when ANDing negative numbers, 12095 * ain't nobody got time for that. 12096 */ 12097 dst_reg->s32_min_value = S32_MIN; 12098 dst_reg->s32_max_value = S32_MAX; 12099 } else { 12100 /* ANDing two positives gives a positive, so safe to 12101 * cast result into s64. 12102 */ 12103 dst_reg->s32_min_value = dst_reg->u32_min_value; 12104 dst_reg->s32_max_value = dst_reg->u32_max_value; 12105 } 12106 } 12107 12108 static void scalar_min_max_and(struct bpf_reg_state *dst_reg, 12109 struct bpf_reg_state *src_reg) 12110 { 12111 bool src_known = tnum_is_const(src_reg->var_off); 12112 bool dst_known = tnum_is_const(dst_reg->var_off); 12113 s64 smin_val = src_reg->smin_value; 12114 u64 umax_val = src_reg->umax_value; 12115 12116 if (src_known && dst_known) { 12117 __mark_reg_known(dst_reg, dst_reg->var_off.value); 12118 return; 12119 } 12120 12121 /* We get our minimum from the var_off, since that's inherently 12122 * bitwise. Our maximum is the minimum of the operands' maxima. 12123 */ 12124 dst_reg->umin_value = dst_reg->var_off.value; 12125 dst_reg->umax_value = min(dst_reg->umax_value, umax_val); 12126 if (dst_reg->smin_value < 0 || smin_val < 0) { 12127 /* Lose signed bounds when ANDing negative numbers, 12128 * ain't nobody got time for that. 12129 */ 12130 dst_reg->smin_value = S64_MIN; 12131 dst_reg->smax_value = S64_MAX; 12132 } else { 12133 /* ANDing two positives gives a positive, so safe to 12134 * cast result into s64. 12135 */ 12136 dst_reg->smin_value = dst_reg->umin_value; 12137 dst_reg->smax_value = dst_reg->umax_value; 12138 } 12139 /* We may learn something more from the var_off */ 12140 __update_reg_bounds(dst_reg); 12141 } 12142 12143 static void scalar32_min_max_or(struct bpf_reg_state *dst_reg, 12144 struct bpf_reg_state *src_reg) 12145 { 12146 bool src_known = tnum_subreg_is_const(src_reg->var_off); 12147 bool dst_known = tnum_subreg_is_const(dst_reg->var_off); 12148 struct tnum var32_off = tnum_subreg(dst_reg->var_off); 12149 s32 smin_val = src_reg->s32_min_value; 12150 u32 umin_val = src_reg->u32_min_value; 12151 12152 if (src_known && dst_known) { 12153 __mark_reg32_known(dst_reg, var32_off.value); 12154 return; 12155 } 12156 12157 /* We get our maximum from the var_off, and our minimum is the 12158 * maximum of the operands' minima 12159 */ 12160 dst_reg->u32_min_value = max(dst_reg->u32_min_value, umin_val); 12161 dst_reg->u32_max_value = var32_off.value | var32_off.mask; 12162 if (dst_reg->s32_min_value < 0 || smin_val < 0) { 12163 /* Lose signed bounds when ORing negative numbers, 12164 * ain't nobody got time for that. 12165 */ 12166 dst_reg->s32_min_value = S32_MIN; 12167 dst_reg->s32_max_value = S32_MAX; 12168 } else { 12169 /* ORing two positives gives a positive, so safe to 12170 * cast result into s64. 12171 */ 12172 dst_reg->s32_min_value = dst_reg->u32_min_value; 12173 dst_reg->s32_max_value = dst_reg->u32_max_value; 12174 } 12175 } 12176 12177 static void scalar_min_max_or(struct bpf_reg_state *dst_reg, 12178 struct bpf_reg_state *src_reg) 12179 { 12180 bool src_known = tnum_is_const(src_reg->var_off); 12181 bool dst_known = tnum_is_const(dst_reg->var_off); 12182 s64 smin_val = src_reg->smin_value; 12183 u64 umin_val = src_reg->umin_value; 12184 12185 if (src_known && dst_known) { 12186 __mark_reg_known(dst_reg, dst_reg->var_off.value); 12187 return; 12188 } 12189 12190 /* We get our maximum from the var_off, and our minimum is the 12191 * maximum of the operands' minima 12192 */ 12193 dst_reg->umin_value = max(dst_reg->umin_value, umin_val); 12194 dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask; 12195 if (dst_reg->smin_value < 0 || smin_val < 0) { 12196 /* Lose signed bounds when ORing negative numbers, 12197 * ain't nobody got time for that. 12198 */ 12199 dst_reg->smin_value = S64_MIN; 12200 dst_reg->smax_value = S64_MAX; 12201 } else { 12202 /* ORing two positives gives a positive, so safe to 12203 * cast result into s64. 12204 */ 12205 dst_reg->smin_value = dst_reg->umin_value; 12206 dst_reg->smax_value = dst_reg->umax_value; 12207 } 12208 /* We may learn something more from the var_off */ 12209 __update_reg_bounds(dst_reg); 12210 } 12211 12212 static void scalar32_min_max_xor(struct bpf_reg_state *dst_reg, 12213 struct bpf_reg_state *src_reg) 12214 { 12215 bool src_known = tnum_subreg_is_const(src_reg->var_off); 12216 bool dst_known = tnum_subreg_is_const(dst_reg->var_off); 12217 struct tnum var32_off = tnum_subreg(dst_reg->var_off); 12218 s32 smin_val = src_reg->s32_min_value; 12219 12220 if (src_known && dst_known) { 12221 __mark_reg32_known(dst_reg, var32_off.value); 12222 return; 12223 } 12224 12225 /* We get both minimum and maximum from the var32_off. */ 12226 dst_reg->u32_min_value = var32_off.value; 12227 dst_reg->u32_max_value = var32_off.value | var32_off.mask; 12228 12229 if (dst_reg->s32_min_value >= 0 && smin_val >= 0) { 12230 /* XORing two positive sign numbers gives a positive, 12231 * so safe to cast u32 result into s32. 12232 */ 12233 dst_reg->s32_min_value = dst_reg->u32_min_value; 12234 dst_reg->s32_max_value = dst_reg->u32_max_value; 12235 } else { 12236 dst_reg->s32_min_value = S32_MIN; 12237 dst_reg->s32_max_value = S32_MAX; 12238 } 12239 } 12240 12241 static void scalar_min_max_xor(struct bpf_reg_state *dst_reg, 12242 struct bpf_reg_state *src_reg) 12243 { 12244 bool src_known = tnum_is_const(src_reg->var_off); 12245 bool dst_known = tnum_is_const(dst_reg->var_off); 12246 s64 smin_val = src_reg->smin_value; 12247 12248 if (src_known && dst_known) { 12249 /* dst_reg->var_off.value has been updated earlier */ 12250 __mark_reg_known(dst_reg, dst_reg->var_off.value); 12251 return; 12252 } 12253 12254 /* We get both minimum and maximum from the var_off. */ 12255 dst_reg->umin_value = dst_reg->var_off.value; 12256 dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask; 12257 12258 if (dst_reg->smin_value >= 0 && smin_val >= 0) { 12259 /* XORing two positive sign numbers gives a positive, 12260 * so safe to cast u64 result into s64. 12261 */ 12262 dst_reg->smin_value = dst_reg->umin_value; 12263 dst_reg->smax_value = dst_reg->umax_value; 12264 } else { 12265 dst_reg->smin_value = S64_MIN; 12266 dst_reg->smax_value = S64_MAX; 12267 } 12268 12269 __update_reg_bounds(dst_reg); 12270 } 12271 12272 static void __scalar32_min_max_lsh(struct bpf_reg_state *dst_reg, 12273 u64 umin_val, u64 umax_val) 12274 { 12275 /* We lose all sign bit information (except what we can pick 12276 * up from var_off) 12277 */ 12278 dst_reg->s32_min_value = S32_MIN; 12279 dst_reg->s32_max_value = S32_MAX; 12280 /* If we might shift our top bit out, then we know nothing */ 12281 if (umax_val > 31 || dst_reg->u32_max_value > 1ULL << (31 - umax_val)) { 12282 dst_reg->u32_min_value = 0; 12283 dst_reg->u32_max_value = U32_MAX; 12284 } else { 12285 dst_reg->u32_min_value <<= umin_val; 12286 dst_reg->u32_max_value <<= umax_val; 12287 } 12288 } 12289 12290 static void scalar32_min_max_lsh(struct bpf_reg_state *dst_reg, 12291 struct bpf_reg_state *src_reg) 12292 { 12293 u32 umax_val = src_reg->u32_max_value; 12294 u32 umin_val = src_reg->u32_min_value; 12295 /* u32 alu operation will zext upper bits */ 12296 struct tnum subreg = tnum_subreg(dst_reg->var_off); 12297 12298 __scalar32_min_max_lsh(dst_reg, umin_val, umax_val); 12299 dst_reg->var_off = tnum_subreg(tnum_lshift(subreg, umin_val)); 12300 /* Not required but being careful mark reg64 bounds as unknown so 12301 * that we are forced to pick them up from tnum and zext later and 12302 * if some path skips this step we are still safe. 12303 */ 12304 __mark_reg64_unbounded(dst_reg); 12305 __update_reg32_bounds(dst_reg); 12306 } 12307 12308 static void __scalar64_min_max_lsh(struct bpf_reg_state *dst_reg, 12309 u64 umin_val, u64 umax_val) 12310 { 12311 /* Special case <<32 because it is a common compiler pattern to sign 12312 * extend subreg by doing <<32 s>>32. In this case if 32bit bounds are 12313 * positive we know this shift will also be positive so we can track 12314 * bounds correctly. Otherwise we lose all sign bit information except 12315 * what we can pick up from var_off. Perhaps we can generalize this 12316 * later to shifts of any length. 12317 */ 12318 if (umin_val == 32 && umax_val == 32 && dst_reg->s32_max_value >= 0) 12319 dst_reg->smax_value = (s64)dst_reg->s32_max_value << 32; 12320 else 12321 dst_reg->smax_value = S64_MAX; 12322 12323 if (umin_val == 32 && umax_val == 32 && dst_reg->s32_min_value >= 0) 12324 dst_reg->smin_value = (s64)dst_reg->s32_min_value << 32; 12325 else 12326 dst_reg->smin_value = S64_MIN; 12327 12328 /* If we might shift our top bit out, then we know nothing */ 12329 if (dst_reg->umax_value > 1ULL << (63 - umax_val)) { 12330 dst_reg->umin_value = 0; 12331 dst_reg->umax_value = U64_MAX; 12332 } else { 12333 dst_reg->umin_value <<= umin_val; 12334 dst_reg->umax_value <<= umax_val; 12335 } 12336 } 12337 12338 static void scalar_min_max_lsh(struct bpf_reg_state *dst_reg, 12339 struct bpf_reg_state *src_reg) 12340 { 12341 u64 umax_val = src_reg->umax_value; 12342 u64 umin_val = src_reg->umin_value; 12343 12344 /* scalar64 calc uses 32bit unshifted bounds so must be called first */ 12345 __scalar64_min_max_lsh(dst_reg, umin_val, umax_val); 12346 __scalar32_min_max_lsh(dst_reg, umin_val, umax_val); 12347 12348 dst_reg->var_off = tnum_lshift(dst_reg->var_off, umin_val); 12349 /* We may learn something more from the var_off */ 12350 __update_reg_bounds(dst_reg); 12351 } 12352 12353 static void scalar32_min_max_rsh(struct bpf_reg_state *dst_reg, 12354 struct bpf_reg_state *src_reg) 12355 { 12356 struct tnum subreg = tnum_subreg(dst_reg->var_off); 12357 u32 umax_val = src_reg->u32_max_value; 12358 u32 umin_val = src_reg->u32_min_value; 12359 12360 /* BPF_RSH is an unsigned shift. If the value in dst_reg might 12361 * be negative, then either: 12362 * 1) src_reg might be zero, so the sign bit of the result is 12363 * unknown, so we lose our signed bounds 12364 * 2) it's known negative, thus the unsigned bounds capture the 12365 * signed bounds 12366 * 3) the signed bounds cross zero, so they tell us nothing 12367 * about the result 12368 * If the value in dst_reg is known nonnegative, then again the 12369 * unsigned bounds capture the signed bounds. 12370 * Thus, in all cases it suffices to blow away our signed bounds 12371 * and rely on inferring new ones from the unsigned bounds and 12372 * var_off of the result. 12373 */ 12374 dst_reg->s32_min_value = S32_MIN; 12375 dst_reg->s32_max_value = S32_MAX; 12376 12377 dst_reg->var_off = tnum_rshift(subreg, umin_val); 12378 dst_reg->u32_min_value >>= umax_val; 12379 dst_reg->u32_max_value >>= umin_val; 12380 12381 __mark_reg64_unbounded(dst_reg); 12382 __update_reg32_bounds(dst_reg); 12383 } 12384 12385 static void scalar_min_max_rsh(struct bpf_reg_state *dst_reg, 12386 struct bpf_reg_state *src_reg) 12387 { 12388 u64 umax_val = src_reg->umax_value; 12389 u64 umin_val = src_reg->umin_value; 12390 12391 /* BPF_RSH is an unsigned shift. If the value in dst_reg might 12392 * be negative, then either: 12393 * 1) src_reg might be zero, so the sign bit of the result is 12394 * unknown, so we lose our signed bounds 12395 * 2) it's known negative, thus the unsigned bounds capture the 12396 * signed bounds 12397 * 3) the signed bounds cross zero, so they tell us nothing 12398 * about the result 12399 * If the value in dst_reg is known nonnegative, then again the 12400 * unsigned bounds capture the signed bounds. 12401 * Thus, in all cases it suffices to blow away our signed bounds 12402 * and rely on inferring new ones from the unsigned bounds and 12403 * var_off of the result. 12404 */ 12405 dst_reg->smin_value = S64_MIN; 12406 dst_reg->smax_value = S64_MAX; 12407 dst_reg->var_off = tnum_rshift(dst_reg->var_off, umin_val); 12408 dst_reg->umin_value >>= umax_val; 12409 dst_reg->umax_value >>= umin_val; 12410 12411 /* Its not easy to operate on alu32 bounds here because it depends 12412 * on bits being shifted in. Take easy way out and mark unbounded 12413 * so we can recalculate later from tnum. 12414 */ 12415 __mark_reg32_unbounded(dst_reg); 12416 __update_reg_bounds(dst_reg); 12417 } 12418 12419 static void scalar32_min_max_arsh(struct bpf_reg_state *dst_reg, 12420 struct bpf_reg_state *src_reg) 12421 { 12422 u64 umin_val = src_reg->u32_min_value; 12423 12424 /* Upon reaching here, src_known is true and 12425 * umax_val is equal to umin_val. 12426 */ 12427 dst_reg->s32_min_value = (u32)(((s32)dst_reg->s32_min_value) >> umin_val); 12428 dst_reg->s32_max_value = (u32)(((s32)dst_reg->s32_max_value) >> umin_val); 12429 12430 dst_reg->var_off = tnum_arshift(tnum_subreg(dst_reg->var_off), umin_val, 32); 12431 12432 /* blow away the dst_reg umin_value/umax_value and rely on 12433 * dst_reg var_off to refine the result. 12434 */ 12435 dst_reg->u32_min_value = 0; 12436 dst_reg->u32_max_value = U32_MAX; 12437 12438 __mark_reg64_unbounded(dst_reg); 12439 __update_reg32_bounds(dst_reg); 12440 } 12441 12442 static void scalar_min_max_arsh(struct bpf_reg_state *dst_reg, 12443 struct bpf_reg_state *src_reg) 12444 { 12445 u64 umin_val = src_reg->umin_value; 12446 12447 /* Upon reaching here, src_known is true and umax_val is equal 12448 * to umin_val. 12449 */ 12450 dst_reg->smin_value >>= umin_val; 12451 dst_reg->smax_value >>= umin_val; 12452 12453 dst_reg->var_off = tnum_arshift(dst_reg->var_off, umin_val, 64); 12454 12455 /* blow away the dst_reg umin_value/umax_value and rely on 12456 * dst_reg var_off to refine the result. 12457 */ 12458 dst_reg->umin_value = 0; 12459 dst_reg->umax_value = U64_MAX; 12460 12461 /* Its not easy to operate on alu32 bounds here because it depends 12462 * on bits being shifted in from upper 32-bits. Take easy way out 12463 * and mark unbounded so we can recalculate later from tnum. 12464 */ 12465 __mark_reg32_unbounded(dst_reg); 12466 __update_reg_bounds(dst_reg); 12467 } 12468 12469 /* WARNING: This function does calculations on 64-bit values, but the actual 12470 * execution may occur on 32-bit values. Therefore, things like bitshifts 12471 * need extra checks in the 32-bit case. 12472 */ 12473 static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env, 12474 struct bpf_insn *insn, 12475 struct bpf_reg_state *dst_reg, 12476 struct bpf_reg_state src_reg) 12477 { 12478 struct bpf_reg_state *regs = cur_regs(env); 12479 u8 opcode = BPF_OP(insn->code); 12480 bool src_known; 12481 s64 smin_val, smax_val; 12482 u64 umin_val, umax_val; 12483 s32 s32_min_val, s32_max_val; 12484 u32 u32_min_val, u32_max_val; 12485 u64 insn_bitness = (BPF_CLASS(insn->code) == BPF_ALU64) ? 64 : 32; 12486 bool alu32 = (BPF_CLASS(insn->code) != BPF_ALU64); 12487 int ret; 12488 12489 smin_val = src_reg.smin_value; 12490 smax_val = src_reg.smax_value; 12491 umin_val = src_reg.umin_value; 12492 umax_val = src_reg.umax_value; 12493 12494 s32_min_val = src_reg.s32_min_value; 12495 s32_max_val = src_reg.s32_max_value; 12496 u32_min_val = src_reg.u32_min_value; 12497 u32_max_val = src_reg.u32_max_value; 12498 12499 if (alu32) { 12500 src_known = tnum_subreg_is_const(src_reg.var_off); 12501 if ((src_known && 12502 (s32_min_val != s32_max_val || u32_min_val != u32_max_val)) || 12503 s32_min_val > s32_max_val || u32_min_val > u32_max_val) { 12504 /* Taint dst register if offset had invalid bounds 12505 * derived from e.g. dead branches. 12506 */ 12507 __mark_reg_unknown(env, dst_reg); 12508 return 0; 12509 } 12510 } else { 12511 src_known = tnum_is_const(src_reg.var_off); 12512 if ((src_known && 12513 (smin_val != smax_val || umin_val != umax_val)) || 12514 smin_val > smax_val || umin_val > umax_val) { 12515 /* Taint dst register if offset had invalid bounds 12516 * derived from e.g. dead branches. 12517 */ 12518 __mark_reg_unknown(env, dst_reg); 12519 return 0; 12520 } 12521 } 12522 12523 if (!src_known && 12524 opcode != BPF_ADD && opcode != BPF_SUB && opcode != BPF_AND) { 12525 __mark_reg_unknown(env, dst_reg); 12526 return 0; 12527 } 12528 12529 if (sanitize_needed(opcode)) { 12530 ret = sanitize_val_alu(env, insn); 12531 if (ret < 0) 12532 return sanitize_err(env, insn, ret, NULL, NULL); 12533 } 12534 12535 /* Calculate sign/unsigned bounds and tnum for alu32 and alu64 bit ops. 12536 * There are two classes of instructions: The first class we track both 12537 * alu32 and alu64 sign/unsigned bounds independently this provides the 12538 * greatest amount of precision when alu operations are mixed with jmp32 12539 * operations. These operations are BPF_ADD, BPF_SUB, BPF_MUL, BPF_ADD, 12540 * and BPF_OR. This is possible because these ops have fairly easy to 12541 * understand and calculate behavior in both 32-bit and 64-bit alu ops. 12542 * See alu32 verifier tests for examples. The second class of 12543 * operations, BPF_LSH, BPF_RSH, and BPF_ARSH, however are not so easy 12544 * with regards to tracking sign/unsigned bounds because the bits may 12545 * cross subreg boundaries in the alu64 case. When this happens we mark 12546 * the reg unbounded in the subreg bound space and use the resulting 12547 * tnum to calculate an approximation of the sign/unsigned bounds. 12548 */ 12549 switch (opcode) { 12550 case BPF_ADD: 12551 scalar32_min_max_add(dst_reg, &src_reg); 12552 scalar_min_max_add(dst_reg, &src_reg); 12553 dst_reg->var_off = tnum_add(dst_reg->var_off, src_reg.var_off); 12554 break; 12555 case BPF_SUB: 12556 scalar32_min_max_sub(dst_reg, &src_reg); 12557 scalar_min_max_sub(dst_reg, &src_reg); 12558 dst_reg->var_off = tnum_sub(dst_reg->var_off, src_reg.var_off); 12559 break; 12560 case BPF_MUL: 12561 dst_reg->var_off = tnum_mul(dst_reg->var_off, src_reg.var_off); 12562 scalar32_min_max_mul(dst_reg, &src_reg); 12563 scalar_min_max_mul(dst_reg, &src_reg); 12564 break; 12565 case BPF_AND: 12566 dst_reg->var_off = tnum_and(dst_reg->var_off, src_reg.var_off); 12567 scalar32_min_max_and(dst_reg, &src_reg); 12568 scalar_min_max_and(dst_reg, &src_reg); 12569 break; 12570 case BPF_OR: 12571 dst_reg->var_off = tnum_or(dst_reg->var_off, src_reg.var_off); 12572 scalar32_min_max_or(dst_reg, &src_reg); 12573 scalar_min_max_or(dst_reg, &src_reg); 12574 break; 12575 case BPF_XOR: 12576 dst_reg->var_off = tnum_xor(dst_reg->var_off, src_reg.var_off); 12577 scalar32_min_max_xor(dst_reg, &src_reg); 12578 scalar_min_max_xor(dst_reg, &src_reg); 12579 break; 12580 case BPF_LSH: 12581 if (umax_val >= insn_bitness) { 12582 /* Shifts greater than 31 or 63 are undefined. 12583 * This includes shifts by a negative number. 12584 */ 12585 mark_reg_unknown(env, regs, insn->dst_reg); 12586 break; 12587 } 12588 if (alu32) 12589 scalar32_min_max_lsh(dst_reg, &src_reg); 12590 else 12591 scalar_min_max_lsh(dst_reg, &src_reg); 12592 break; 12593 case BPF_RSH: 12594 if (umax_val >= insn_bitness) { 12595 /* Shifts greater than 31 or 63 are undefined. 12596 * This includes shifts by a negative number. 12597 */ 12598 mark_reg_unknown(env, regs, insn->dst_reg); 12599 break; 12600 } 12601 if (alu32) 12602 scalar32_min_max_rsh(dst_reg, &src_reg); 12603 else 12604 scalar_min_max_rsh(dst_reg, &src_reg); 12605 break; 12606 case BPF_ARSH: 12607 if (umax_val >= insn_bitness) { 12608 /* Shifts greater than 31 or 63 are undefined. 12609 * This includes shifts by a negative number. 12610 */ 12611 mark_reg_unknown(env, regs, insn->dst_reg); 12612 break; 12613 } 12614 if (alu32) 12615 scalar32_min_max_arsh(dst_reg, &src_reg); 12616 else 12617 scalar_min_max_arsh(dst_reg, &src_reg); 12618 break; 12619 default: 12620 mark_reg_unknown(env, regs, insn->dst_reg); 12621 break; 12622 } 12623 12624 /* ALU32 ops are zero extended into 64bit register */ 12625 if (alu32) 12626 zext_32_to_64(dst_reg); 12627 reg_bounds_sync(dst_reg); 12628 return 0; 12629 } 12630 12631 /* Handles ALU ops other than BPF_END, BPF_NEG and BPF_MOV: computes new min/max 12632 * and var_off. 12633 */ 12634 static int adjust_reg_min_max_vals(struct bpf_verifier_env *env, 12635 struct bpf_insn *insn) 12636 { 12637 struct bpf_verifier_state *vstate = env->cur_state; 12638 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 12639 struct bpf_reg_state *regs = state->regs, *dst_reg, *src_reg; 12640 struct bpf_reg_state *ptr_reg = NULL, off_reg = {0}; 12641 u8 opcode = BPF_OP(insn->code); 12642 int err; 12643 12644 dst_reg = ®s[insn->dst_reg]; 12645 src_reg = NULL; 12646 if (dst_reg->type != SCALAR_VALUE) 12647 ptr_reg = dst_reg; 12648 else 12649 /* Make sure ID is cleared otherwise dst_reg min/max could be 12650 * incorrectly propagated into other registers by find_equal_scalars() 12651 */ 12652 dst_reg->id = 0; 12653 if (BPF_SRC(insn->code) == BPF_X) { 12654 src_reg = ®s[insn->src_reg]; 12655 if (src_reg->type != SCALAR_VALUE) { 12656 if (dst_reg->type != SCALAR_VALUE) { 12657 /* Combining two pointers by any ALU op yields 12658 * an arbitrary scalar. Disallow all math except 12659 * pointer subtraction 12660 */ 12661 if (opcode == BPF_SUB && env->allow_ptr_leaks) { 12662 mark_reg_unknown(env, regs, insn->dst_reg); 12663 return 0; 12664 } 12665 verbose(env, "R%d pointer %s pointer prohibited\n", 12666 insn->dst_reg, 12667 bpf_alu_string[opcode >> 4]); 12668 return -EACCES; 12669 } else { 12670 /* scalar += pointer 12671 * This is legal, but we have to reverse our 12672 * src/dest handling in computing the range 12673 */ 12674 err = mark_chain_precision(env, insn->dst_reg); 12675 if (err) 12676 return err; 12677 return adjust_ptr_min_max_vals(env, insn, 12678 src_reg, dst_reg); 12679 } 12680 } else if (ptr_reg) { 12681 /* pointer += scalar */ 12682 err = mark_chain_precision(env, insn->src_reg); 12683 if (err) 12684 return err; 12685 return adjust_ptr_min_max_vals(env, insn, 12686 dst_reg, src_reg); 12687 } else if (dst_reg->precise) { 12688 /* if dst_reg is precise, src_reg should be precise as well */ 12689 err = mark_chain_precision(env, insn->src_reg); 12690 if (err) 12691 return err; 12692 } 12693 } else { 12694 /* Pretend the src is a reg with a known value, since we only 12695 * need to be able to read from this state. 12696 */ 12697 off_reg.type = SCALAR_VALUE; 12698 __mark_reg_known(&off_reg, insn->imm); 12699 src_reg = &off_reg; 12700 if (ptr_reg) /* pointer += K */ 12701 return adjust_ptr_min_max_vals(env, insn, 12702 ptr_reg, src_reg); 12703 } 12704 12705 /* Got here implies adding two SCALAR_VALUEs */ 12706 if (WARN_ON_ONCE(ptr_reg)) { 12707 print_verifier_state(env, state, true); 12708 verbose(env, "verifier internal error: unexpected ptr_reg\n"); 12709 return -EINVAL; 12710 } 12711 if (WARN_ON(!src_reg)) { 12712 print_verifier_state(env, state, true); 12713 verbose(env, "verifier internal error: no src_reg\n"); 12714 return -EINVAL; 12715 } 12716 return adjust_scalar_min_max_vals(env, insn, dst_reg, *src_reg); 12717 } 12718 12719 /* check validity of 32-bit and 64-bit arithmetic operations */ 12720 static int check_alu_op(struct bpf_verifier_env *env, struct bpf_insn *insn) 12721 { 12722 struct bpf_reg_state *regs = cur_regs(env); 12723 u8 opcode = BPF_OP(insn->code); 12724 int err; 12725 12726 if (opcode == BPF_END || opcode == BPF_NEG) { 12727 if (opcode == BPF_NEG) { 12728 if (BPF_SRC(insn->code) != BPF_K || 12729 insn->src_reg != BPF_REG_0 || 12730 insn->off != 0 || insn->imm != 0) { 12731 verbose(env, "BPF_NEG uses reserved fields\n"); 12732 return -EINVAL; 12733 } 12734 } else { 12735 if (insn->src_reg != BPF_REG_0 || insn->off != 0 || 12736 (insn->imm != 16 && insn->imm != 32 && insn->imm != 64) || 12737 BPF_CLASS(insn->code) == BPF_ALU64) { 12738 verbose(env, "BPF_END uses reserved fields\n"); 12739 return -EINVAL; 12740 } 12741 } 12742 12743 /* check src operand */ 12744 err = check_reg_arg(env, insn->dst_reg, SRC_OP); 12745 if (err) 12746 return err; 12747 12748 if (is_pointer_value(env, insn->dst_reg)) { 12749 verbose(env, "R%d pointer arithmetic prohibited\n", 12750 insn->dst_reg); 12751 return -EACCES; 12752 } 12753 12754 /* check dest operand */ 12755 err = check_reg_arg(env, insn->dst_reg, DST_OP); 12756 if (err) 12757 return err; 12758 12759 } else if (opcode == BPF_MOV) { 12760 12761 if (BPF_SRC(insn->code) == BPF_X) { 12762 if (insn->imm != 0 || insn->off != 0) { 12763 verbose(env, "BPF_MOV uses reserved fields\n"); 12764 return -EINVAL; 12765 } 12766 12767 /* check src operand */ 12768 err = check_reg_arg(env, insn->src_reg, SRC_OP); 12769 if (err) 12770 return err; 12771 } else { 12772 if (insn->src_reg != BPF_REG_0 || insn->off != 0) { 12773 verbose(env, "BPF_MOV uses reserved fields\n"); 12774 return -EINVAL; 12775 } 12776 } 12777 12778 /* check dest operand, mark as required later */ 12779 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK); 12780 if (err) 12781 return err; 12782 12783 if (BPF_SRC(insn->code) == BPF_X) { 12784 struct bpf_reg_state *src_reg = regs + insn->src_reg; 12785 struct bpf_reg_state *dst_reg = regs + insn->dst_reg; 12786 12787 if (BPF_CLASS(insn->code) == BPF_ALU64) { 12788 /* case: R1 = R2 12789 * copy register state to dest reg 12790 */ 12791 if (src_reg->type == SCALAR_VALUE && !src_reg->id) 12792 /* Assign src and dst registers the same ID 12793 * that will be used by find_equal_scalars() 12794 * to propagate min/max range. 12795 */ 12796 src_reg->id = ++env->id_gen; 12797 copy_register_state(dst_reg, src_reg); 12798 dst_reg->live |= REG_LIVE_WRITTEN; 12799 dst_reg->subreg_def = DEF_NOT_SUBREG; 12800 } else { 12801 /* R1 = (u32) R2 */ 12802 if (is_pointer_value(env, insn->src_reg)) { 12803 verbose(env, 12804 "R%d partial copy of pointer\n", 12805 insn->src_reg); 12806 return -EACCES; 12807 } else if (src_reg->type == SCALAR_VALUE) { 12808 bool is_src_reg_u32 = src_reg->umax_value <= U32_MAX; 12809 12810 if (is_src_reg_u32 && !src_reg->id) 12811 src_reg->id = ++env->id_gen; 12812 copy_register_state(dst_reg, src_reg); 12813 /* Make sure ID is cleared if src_reg is not in u32 range otherwise 12814 * dst_reg min/max could be incorrectly 12815 * propagated into src_reg by find_equal_scalars() 12816 */ 12817 if (!is_src_reg_u32) 12818 dst_reg->id = 0; 12819 dst_reg->live |= REG_LIVE_WRITTEN; 12820 dst_reg->subreg_def = env->insn_idx + 1; 12821 } else { 12822 mark_reg_unknown(env, regs, 12823 insn->dst_reg); 12824 } 12825 zext_32_to_64(dst_reg); 12826 reg_bounds_sync(dst_reg); 12827 } 12828 } else { 12829 /* case: R = imm 12830 * remember the value we stored into this reg 12831 */ 12832 /* clear any state __mark_reg_known doesn't set */ 12833 mark_reg_unknown(env, regs, insn->dst_reg); 12834 regs[insn->dst_reg].type = SCALAR_VALUE; 12835 if (BPF_CLASS(insn->code) == BPF_ALU64) { 12836 __mark_reg_known(regs + insn->dst_reg, 12837 insn->imm); 12838 } else { 12839 __mark_reg_known(regs + insn->dst_reg, 12840 (u32)insn->imm); 12841 } 12842 } 12843 12844 } else if (opcode > BPF_END) { 12845 verbose(env, "invalid BPF_ALU opcode %x\n", opcode); 12846 return -EINVAL; 12847 12848 } else { /* all other ALU ops: and, sub, xor, add, ... */ 12849 12850 if (BPF_SRC(insn->code) == BPF_X) { 12851 if (insn->imm != 0 || insn->off != 0) { 12852 verbose(env, "BPF_ALU uses reserved fields\n"); 12853 return -EINVAL; 12854 } 12855 /* check src1 operand */ 12856 err = check_reg_arg(env, insn->src_reg, SRC_OP); 12857 if (err) 12858 return err; 12859 } else { 12860 if (insn->src_reg != BPF_REG_0 || insn->off != 0) { 12861 verbose(env, "BPF_ALU uses reserved fields\n"); 12862 return -EINVAL; 12863 } 12864 } 12865 12866 /* check src2 operand */ 12867 err = check_reg_arg(env, insn->dst_reg, SRC_OP); 12868 if (err) 12869 return err; 12870 12871 if ((opcode == BPF_MOD || opcode == BPF_DIV) && 12872 BPF_SRC(insn->code) == BPF_K && insn->imm == 0) { 12873 verbose(env, "div by zero\n"); 12874 return -EINVAL; 12875 } 12876 12877 if ((opcode == BPF_LSH || opcode == BPF_RSH || 12878 opcode == BPF_ARSH) && BPF_SRC(insn->code) == BPF_K) { 12879 int size = BPF_CLASS(insn->code) == BPF_ALU64 ? 64 : 32; 12880 12881 if (insn->imm < 0 || insn->imm >= size) { 12882 verbose(env, "invalid shift %d\n", insn->imm); 12883 return -EINVAL; 12884 } 12885 } 12886 12887 /* check dest operand */ 12888 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK); 12889 if (err) 12890 return err; 12891 12892 return adjust_reg_min_max_vals(env, insn); 12893 } 12894 12895 return 0; 12896 } 12897 12898 static void find_good_pkt_pointers(struct bpf_verifier_state *vstate, 12899 struct bpf_reg_state *dst_reg, 12900 enum bpf_reg_type type, 12901 bool range_right_open) 12902 { 12903 struct bpf_func_state *state; 12904 struct bpf_reg_state *reg; 12905 int new_range; 12906 12907 if (dst_reg->off < 0 || 12908 (dst_reg->off == 0 && range_right_open)) 12909 /* This doesn't give us any range */ 12910 return; 12911 12912 if (dst_reg->umax_value > MAX_PACKET_OFF || 12913 dst_reg->umax_value + dst_reg->off > MAX_PACKET_OFF) 12914 /* Risk of overflow. For instance, ptr + (1<<63) may be less 12915 * than pkt_end, but that's because it's also less than pkt. 12916 */ 12917 return; 12918 12919 new_range = dst_reg->off; 12920 if (range_right_open) 12921 new_range++; 12922 12923 /* Examples for register markings: 12924 * 12925 * pkt_data in dst register: 12926 * 12927 * r2 = r3; 12928 * r2 += 8; 12929 * if (r2 > pkt_end) goto <handle exception> 12930 * <access okay> 12931 * 12932 * r2 = r3; 12933 * r2 += 8; 12934 * if (r2 < pkt_end) goto <access okay> 12935 * <handle exception> 12936 * 12937 * Where: 12938 * r2 == dst_reg, pkt_end == src_reg 12939 * r2=pkt(id=n,off=8,r=0) 12940 * r3=pkt(id=n,off=0,r=0) 12941 * 12942 * pkt_data in src register: 12943 * 12944 * r2 = r3; 12945 * r2 += 8; 12946 * if (pkt_end >= r2) goto <access okay> 12947 * <handle exception> 12948 * 12949 * r2 = r3; 12950 * r2 += 8; 12951 * if (pkt_end <= r2) goto <handle exception> 12952 * <access okay> 12953 * 12954 * Where: 12955 * pkt_end == dst_reg, r2 == src_reg 12956 * r2=pkt(id=n,off=8,r=0) 12957 * r3=pkt(id=n,off=0,r=0) 12958 * 12959 * Find register r3 and mark its range as r3=pkt(id=n,off=0,r=8) 12960 * or r3=pkt(id=n,off=0,r=8-1), so that range of bytes [r3, r3 + 8) 12961 * and [r3, r3 + 8-1) respectively is safe to access depending on 12962 * the check. 12963 */ 12964 12965 /* If our ids match, then we must have the same max_value. And we 12966 * don't care about the other reg's fixed offset, since if it's too big 12967 * the range won't allow anything. 12968 * dst_reg->off is known < MAX_PACKET_OFF, therefore it fits in a u16. 12969 */ 12970 bpf_for_each_reg_in_vstate(vstate, state, reg, ({ 12971 if (reg->type == type && reg->id == dst_reg->id) 12972 /* keep the maximum range already checked */ 12973 reg->range = max(reg->range, new_range); 12974 })); 12975 } 12976 12977 static int is_branch32_taken(struct bpf_reg_state *reg, u32 val, u8 opcode) 12978 { 12979 struct tnum subreg = tnum_subreg(reg->var_off); 12980 s32 sval = (s32)val; 12981 12982 switch (opcode) { 12983 case BPF_JEQ: 12984 if (tnum_is_const(subreg)) 12985 return !!tnum_equals_const(subreg, val); 12986 else if (val < reg->u32_min_value || val > reg->u32_max_value) 12987 return 0; 12988 break; 12989 case BPF_JNE: 12990 if (tnum_is_const(subreg)) 12991 return !tnum_equals_const(subreg, val); 12992 else if (val < reg->u32_min_value || val > reg->u32_max_value) 12993 return 1; 12994 break; 12995 case BPF_JSET: 12996 if ((~subreg.mask & subreg.value) & val) 12997 return 1; 12998 if (!((subreg.mask | subreg.value) & val)) 12999 return 0; 13000 break; 13001 case BPF_JGT: 13002 if (reg->u32_min_value > val) 13003 return 1; 13004 else if (reg->u32_max_value <= val) 13005 return 0; 13006 break; 13007 case BPF_JSGT: 13008 if (reg->s32_min_value > sval) 13009 return 1; 13010 else if (reg->s32_max_value <= sval) 13011 return 0; 13012 break; 13013 case BPF_JLT: 13014 if (reg->u32_max_value < val) 13015 return 1; 13016 else if (reg->u32_min_value >= val) 13017 return 0; 13018 break; 13019 case BPF_JSLT: 13020 if (reg->s32_max_value < sval) 13021 return 1; 13022 else if (reg->s32_min_value >= sval) 13023 return 0; 13024 break; 13025 case BPF_JGE: 13026 if (reg->u32_min_value >= val) 13027 return 1; 13028 else if (reg->u32_max_value < val) 13029 return 0; 13030 break; 13031 case BPF_JSGE: 13032 if (reg->s32_min_value >= sval) 13033 return 1; 13034 else if (reg->s32_max_value < sval) 13035 return 0; 13036 break; 13037 case BPF_JLE: 13038 if (reg->u32_max_value <= val) 13039 return 1; 13040 else if (reg->u32_min_value > val) 13041 return 0; 13042 break; 13043 case BPF_JSLE: 13044 if (reg->s32_max_value <= sval) 13045 return 1; 13046 else if (reg->s32_min_value > sval) 13047 return 0; 13048 break; 13049 } 13050 13051 return -1; 13052 } 13053 13054 13055 static int is_branch64_taken(struct bpf_reg_state *reg, u64 val, u8 opcode) 13056 { 13057 s64 sval = (s64)val; 13058 13059 switch (opcode) { 13060 case BPF_JEQ: 13061 if (tnum_is_const(reg->var_off)) 13062 return !!tnum_equals_const(reg->var_off, val); 13063 else if (val < reg->umin_value || val > reg->umax_value) 13064 return 0; 13065 break; 13066 case BPF_JNE: 13067 if (tnum_is_const(reg->var_off)) 13068 return !tnum_equals_const(reg->var_off, val); 13069 else if (val < reg->umin_value || val > reg->umax_value) 13070 return 1; 13071 break; 13072 case BPF_JSET: 13073 if ((~reg->var_off.mask & reg->var_off.value) & val) 13074 return 1; 13075 if (!((reg->var_off.mask | reg->var_off.value) & val)) 13076 return 0; 13077 break; 13078 case BPF_JGT: 13079 if (reg->umin_value > val) 13080 return 1; 13081 else if (reg->umax_value <= val) 13082 return 0; 13083 break; 13084 case BPF_JSGT: 13085 if (reg->smin_value > sval) 13086 return 1; 13087 else if (reg->smax_value <= sval) 13088 return 0; 13089 break; 13090 case BPF_JLT: 13091 if (reg->umax_value < val) 13092 return 1; 13093 else if (reg->umin_value >= val) 13094 return 0; 13095 break; 13096 case BPF_JSLT: 13097 if (reg->smax_value < sval) 13098 return 1; 13099 else if (reg->smin_value >= sval) 13100 return 0; 13101 break; 13102 case BPF_JGE: 13103 if (reg->umin_value >= val) 13104 return 1; 13105 else if (reg->umax_value < val) 13106 return 0; 13107 break; 13108 case BPF_JSGE: 13109 if (reg->smin_value >= sval) 13110 return 1; 13111 else if (reg->smax_value < sval) 13112 return 0; 13113 break; 13114 case BPF_JLE: 13115 if (reg->umax_value <= val) 13116 return 1; 13117 else if (reg->umin_value > val) 13118 return 0; 13119 break; 13120 case BPF_JSLE: 13121 if (reg->smax_value <= sval) 13122 return 1; 13123 else if (reg->smin_value > sval) 13124 return 0; 13125 break; 13126 } 13127 13128 return -1; 13129 } 13130 13131 /* compute branch direction of the expression "if (reg opcode val) goto target;" 13132 * and return: 13133 * 1 - branch will be taken and "goto target" will be executed 13134 * 0 - branch will not be taken and fall-through to next insn 13135 * -1 - unknown. Example: "if (reg < 5)" is unknown when register value 13136 * range [0,10] 13137 */ 13138 static int is_branch_taken(struct bpf_reg_state *reg, u64 val, u8 opcode, 13139 bool is_jmp32) 13140 { 13141 if (__is_pointer_value(false, reg)) { 13142 if (!reg_type_not_null(reg->type)) 13143 return -1; 13144 13145 /* If pointer is valid tests against zero will fail so we can 13146 * use this to direct branch taken. 13147 */ 13148 if (val != 0) 13149 return -1; 13150 13151 switch (opcode) { 13152 case BPF_JEQ: 13153 return 0; 13154 case BPF_JNE: 13155 return 1; 13156 default: 13157 return -1; 13158 } 13159 } 13160 13161 if (is_jmp32) 13162 return is_branch32_taken(reg, val, opcode); 13163 return is_branch64_taken(reg, val, opcode); 13164 } 13165 13166 static int flip_opcode(u32 opcode) 13167 { 13168 /* How can we transform "a <op> b" into "b <op> a"? */ 13169 static const u8 opcode_flip[16] = { 13170 /* these stay the same */ 13171 [BPF_JEQ >> 4] = BPF_JEQ, 13172 [BPF_JNE >> 4] = BPF_JNE, 13173 [BPF_JSET >> 4] = BPF_JSET, 13174 /* these swap "lesser" and "greater" (L and G in the opcodes) */ 13175 [BPF_JGE >> 4] = BPF_JLE, 13176 [BPF_JGT >> 4] = BPF_JLT, 13177 [BPF_JLE >> 4] = BPF_JGE, 13178 [BPF_JLT >> 4] = BPF_JGT, 13179 [BPF_JSGE >> 4] = BPF_JSLE, 13180 [BPF_JSGT >> 4] = BPF_JSLT, 13181 [BPF_JSLE >> 4] = BPF_JSGE, 13182 [BPF_JSLT >> 4] = BPF_JSGT 13183 }; 13184 return opcode_flip[opcode >> 4]; 13185 } 13186 13187 static int is_pkt_ptr_branch_taken(struct bpf_reg_state *dst_reg, 13188 struct bpf_reg_state *src_reg, 13189 u8 opcode) 13190 { 13191 struct bpf_reg_state *pkt; 13192 13193 if (src_reg->type == PTR_TO_PACKET_END) { 13194 pkt = dst_reg; 13195 } else if (dst_reg->type == PTR_TO_PACKET_END) { 13196 pkt = src_reg; 13197 opcode = flip_opcode(opcode); 13198 } else { 13199 return -1; 13200 } 13201 13202 if (pkt->range >= 0) 13203 return -1; 13204 13205 switch (opcode) { 13206 case BPF_JLE: 13207 /* pkt <= pkt_end */ 13208 fallthrough; 13209 case BPF_JGT: 13210 /* pkt > pkt_end */ 13211 if (pkt->range == BEYOND_PKT_END) 13212 /* pkt has at last one extra byte beyond pkt_end */ 13213 return opcode == BPF_JGT; 13214 break; 13215 case BPF_JLT: 13216 /* pkt < pkt_end */ 13217 fallthrough; 13218 case BPF_JGE: 13219 /* pkt >= pkt_end */ 13220 if (pkt->range == BEYOND_PKT_END || pkt->range == AT_PKT_END) 13221 return opcode == BPF_JGE; 13222 break; 13223 } 13224 return -1; 13225 } 13226 13227 /* Adjusts the register min/max values in the case that the dst_reg is the 13228 * variable register that we are working on, and src_reg is a constant or we're 13229 * simply doing a BPF_K check. 13230 * In JEQ/JNE cases we also adjust the var_off values. 13231 */ 13232 static void reg_set_min_max(struct bpf_reg_state *true_reg, 13233 struct bpf_reg_state *false_reg, 13234 u64 val, u32 val32, 13235 u8 opcode, bool is_jmp32) 13236 { 13237 struct tnum false_32off = tnum_subreg(false_reg->var_off); 13238 struct tnum false_64off = false_reg->var_off; 13239 struct tnum true_32off = tnum_subreg(true_reg->var_off); 13240 struct tnum true_64off = true_reg->var_off; 13241 s64 sval = (s64)val; 13242 s32 sval32 = (s32)val32; 13243 13244 /* If the dst_reg is a pointer, we can't learn anything about its 13245 * variable offset from the compare (unless src_reg were a pointer into 13246 * the same object, but we don't bother with that. 13247 * Since false_reg and true_reg have the same type by construction, we 13248 * only need to check one of them for pointerness. 13249 */ 13250 if (__is_pointer_value(false, false_reg)) 13251 return; 13252 13253 switch (opcode) { 13254 /* JEQ/JNE comparison doesn't change the register equivalence. 13255 * 13256 * r1 = r2; 13257 * if (r1 == 42) goto label; 13258 * ... 13259 * label: // here both r1 and r2 are known to be 42. 13260 * 13261 * Hence when marking register as known preserve it's ID. 13262 */ 13263 case BPF_JEQ: 13264 if (is_jmp32) { 13265 __mark_reg32_known(true_reg, val32); 13266 true_32off = tnum_subreg(true_reg->var_off); 13267 } else { 13268 ___mark_reg_known(true_reg, val); 13269 true_64off = true_reg->var_off; 13270 } 13271 break; 13272 case BPF_JNE: 13273 if (is_jmp32) { 13274 __mark_reg32_known(false_reg, val32); 13275 false_32off = tnum_subreg(false_reg->var_off); 13276 } else { 13277 ___mark_reg_known(false_reg, val); 13278 false_64off = false_reg->var_off; 13279 } 13280 break; 13281 case BPF_JSET: 13282 if (is_jmp32) { 13283 false_32off = tnum_and(false_32off, tnum_const(~val32)); 13284 if (is_power_of_2(val32)) 13285 true_32off = tnum_or(true_32off, 13286 tnum_const(val32)); 13287 } else { 13288 false_64off = tnum_and(false_64off, tnum_const(~val)); 13289 if (is_power_of_2(val)) 13290 true_64off = tnum_or(true_64off, 13291 tnum_const(val)); 13292 } 13293 break; 13294 case BPF_JGE: 13295 case BPF_JGT: 13296 { 13297 if (is_jmp32) { 13298 u32 false_umax = opcode == BPF_JGT ? val32 : val32 - 1; 13299 u32 true_umin = opcode == BPF_JGT ? val32 + 1 : val32; 13300 13301 false_reg->u32_max_value = min(false_reg->u32_max_value, 13302 false_umax); 13303 true_reg->u32_min_value = max(true_reg->u32_min_value, 13304 true_umin); 13305 } else { 13306 u64 false_umax = opcode == BPF_JGT ? val : val - 1; 13307 u64 true_umin = opcode == BPF_JGT ? val + 1 : val; 13308 13309 false_reg->umax_value = min(false_reg->umax_value, false_umax); 13310 true_reg->umin_value = max(true_reg->umin_value, true_umin); 13311 } 13312 break; 13313 } 13314 case BPF_JSGE: 13315 case BPF_JSGT: 13316 { 13317 if (is_jmp32) { 13318 s32 false_smax = opcode == BPF_JSGT ? sval32 : sval32 - 1; 13319 s32 true_smin = opcode == BPF_JSGT ? sval32 + 1 : sval32; 13320 13321 false_reg->s32_max_value = min(false_reg->s32_max_value, false_smax); 13322 true_reg->s32_min_value = max(true_reg->s32_min_value, true_smin); 13323 } else { 13324 s64 false_smax = opcode == BPF_JSGT ? sval : sval - 1; 13325 s64 true_smin = opcode == BPF_JSGT ? sval + 1 : sval; 13326 13327 false_reg->smax_value = min(false_reg->smax_value, false_smax); 13328 true_reg->smin_value = max(true_reg->smin_value, true_smin); 13329 } 13330 break; 13331 } 13332 case BPF_JLE: 13333 case BPF_JLT: 13334 { 13335 if (is_jmp32) { 13336 u32 false_umin = opcode == BPF_JLT ? val32 : val32 + 1; 13337 u32 true_umax = opcode == BPF_JLT ? val32 - 1 : val32; 13338 13339 false_reg->u32_min_value = max(false_reg->u32_min_value, 13340 false_umin); 13341 true_reg->u32_max_value = min(true_reg->u32_max_value, 13342 true_umax); 13343 } else { 13344 u64 false_umin = opcode == BPF_JLT ? val : val + 1; 13345 u64 true_umax = opcode == BPF_JLT ? val - 1 : val; 13346 13347 false_reg->umin_value = max(false_reg->umin_value, false_umin); 13348 true_reg->umax_value = min(true_reg->umax_value, true_umax); 13349 } 13350 break; 13351 } 13352 case BPF_JSLE: 13353 case BPF_JSLT: 13354 { 13355 if (is_jmp32) { 13356 s32 false_smin = opcode == BPF_JSLT ? sval32 : sval32 + 1; 13357 s32 true_smax = opcode == BPF_JSLT ? sval32 - 1 : sval32; 13358 13359 false_reg->s32_min_value = max(false_reg->s32_min_value, false_smin); 13360 true_reg->s32_max_value = min(true_reg->s32_max_value, true_smax); 13361 } else { 13362 s64 false_smin = opcode == BPF_JSLT ? sval : sval + 1; 13363 s64 true_smax = opcode == BPF_JSLT ? sval - 1 : sval; 13364 13365 false_reg->smin_value = max(false_reg->smin_value, false_smin); 13366 true_reg->smax_value = min(true_reg->smax_value, true_smax); 13367 } 13368 break; 13369 } 13370 default: 13371 return; 13372 } 13373 13374 if (is_jmp32) { 13375 false_reg->var_off = tnum_or(tnum_clear_subreg(false_64off), 13376 tnum_subreg(false_32off)); 13377 true_reg->var_off = tnum_or(tnum_clear_subreg(true_64off), 13378 tnum_subreg(true_32off)); 13379 __reg_combine_32_into_64(false_reg); 13380 __reg_combine_32_into_64(true_reg); 13381 } else { 13382 false_reg->var_off = false_64off; 13383 true_reg->var_off = true_64off; 13384 __reg_combine_64_into_32(false_reg); 13385 __reg_combine_64_into_32(true_reg); 13386 } 13387 } 13388 13389 /* Same as above, but for the case that dst_reg holds a constant and src_reg is 13390 * the variable reg. 13391 */ 13392 static void reg_set_min_max_inv(struct bpf_reg_state *true_reg, 13393 struct bpf_reg_state *false_reg, 13394 u64 val, u32 val32, 13395 u8 opcode, bool is_jmp32) 13396 { 13397 opcode = flip_opcode(opcode); 13398 /* This uses zero as "not present in table"; luckily the zero opcode, 13399 * BPF_JA, can't get here. 13400 */ 13401 if (opcode) 13402 reg_set_min_max(true_reg, false_reg, val, val32, opcode, is_jmp32); 13403 } 13404 13405 /* Regs are known to be equal, so intersect their min/max/var_off */ 13406 static void __reg_combine_min_max(struct bpf_reg_state *src_reg, 13407 struct bpf_reg_state *dst_reg) 13408 { 13409 src_reg->umin_value = dst_reg->umin_value = max(src_reg->umin_value, 13410 dst_reg->umin_value); 13411 src_reg->umax_value = dst_reg->umax_value = min(src_reg->umax_value, 13412 dst_reg->umax_value); 13413 src_reg->smin_value = dst_reg->smin_value = max(src_reg->smin_value, 13414 dst_reg->smin_value); 13415 src_reg->smax_value = dst_reg->smax_value = min(src_reg->smax_value, 13416 dst_reg->smax_value); 13417 src_reg->var_off = dst_reg->var_off = tnum_intersect(src_reg->var_off, 13418 dst_reg->var_off); 13419 reg_bounds_sync(src_reg); 13420 reg_bounds_sync(dst_reg); 13421 } 13422 13423 static void reg_combine_min_max(struct bpf_reg_state *true_src, 13424 struct bpf_reg_state *true_dst, 13425 struct bpf_reg_state *false_src, 13426 struct bpf_reg_state *false_dst, 13427 u8 opcode) 13428 { 13429 switch (opcode) { 13430 case BPF_JEQ: 13431 __reg_combine_min_max(true_src, true_dst); 13432 break; 13433 case BPF_JNE: 13434 __reg_combine_min_max(false_src, false_dst); 13435 break; 13436 } 13437 } 13438 13439 static void mark_ptr_or_null_reg(struct bpf_func_state *state, 13440 struct bpf_reg_state *reg, u32 id, 13441 bool is_null) 13442 { 13443 if (type_may_be_null(reg->type) && reg->id == id && 13444 (is_rcu_reg(reg) || !WARN_ON_ONCE(!reg->id))) { 13445 /* Old offset (both fixed and variable parts) should have been 13446 * known-zero, because we don't allow pointer arithmetic on 13447 * pointers that might be NULL. If we see this happening, don't 13448 * convert the register. 13449 * 13450 * But in some cases, some helpers that return local kptrs 13451 * advance offset for the returned pointer. In those cases, it 13452 * is fine to expect to see reg->off. 13453 */ 13454 if (WARN_ON_ONCE(reg->smin_value || reg->smax_value || !tnum_equals_const(reg->var_off, 0))) 13455 return; 13456 if (!(type_is_ptr_alloc_obj(reg->type) || type_is_non_owning_ref(reg->type)) && 13457 WARN_ON_ONCE(reg->off)) 13458 return; 13459 13460 if (is_null) { 13461 reg->type = SCALAR_VALUE; 13462 /* We don't need id and ref_obj_id from this point 13463 * onwards anymore, thus we should better reset it, 13464 * so that state pruning has chances to take effect. 13465 */ 13466 reg->id = 0; 13467 reg->ref_obj_id = 0; 13468 13469 return; 13470 } 13471 13472 mark_ptr_not_null_reg(reg); 13473 13474 if (!reg_may_point_to_spin_lock(reg)) { 13475 /* For not-NULL ptr, reg->ref_obj_id will be reset 13476 * in release_reference(). 13477 * 13478 * reg->id is still used by spin_lock ptr. Other 13479 * than spin_lock ptr type, reg->id can be reset. 13480 */ 13481 reg->id = 0; 13482 } 13483 } 13484 } 13485 13486 /* The logic is similar to find_good_pkt_pointers(), both could eventually 13487 * be folded together at some point. 13488 */ 13489 static void mark_ptr_or_null_regs(struct bpf_verifier_state *vstate, u32 regno, 13490 bool is_null) 13491 { 13492 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 13493 struct bpf_reg_state *regs = state->regs, *reg; 13494 u32 ref_obj_id = regs[regno].ref_obj_id; 13495 u32 id = regs[regno].id; 13496 13497 if (ref_obj_id && ref_obj_id == id && is_null) 13498 /* regs[regno] is in the " == NULL" branch. 13499 * No one could have freed the reference state before 13500 * doing the NULL check. 13501 */ 13502 WARN_ON_ONCE(release_reference_state(state, id)); 13503 13504 bpf_for_each_reg_in_vstate(vstate, state, reg, ({ 13505 mark_ptr_or_null_reg(state, reg, id, is_null); 13506 })); 13507 } 13508 13509 static bool try_match_pkt_pointers(const struct bpf_insn *insn, 13510 struct bpf_reg_state *dst_reg, 13511 struct bpf_reg_state *src_reg, 13512 struct bpf_verifier_state *this_branch, 13513 struct bpf_verifier_state *other_branch) 13514 { 13515 if (BPF_SRC(insn->code) != BPF_X) 13516 return false; 13517 13518 /* Pointers are always 64-bit. */ 13519 if (BPF_CLASS(insn->code) == BPF_JMP32) 13520 return false; 13521 13522 switch (BPF_OP(insn->code)) { 13523 case BPF_JGT: 13524 if ((dst_reg->type == PTR_TO_PACKET && 13525 src_reg->type == PTR_TO_PACKET_END) || 13526 (dst_reg->type == PTR_TO_PACKET_META && 13527 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) { 13528 /* pkt_data' > pkt_end, pkt_meta' > pkt_data */ 13529 find_good_pkt_pointers(this_branch, dst_reg, 13530 dst_reg->type, false); 13531 mark_pkt_end(other_branch, insn->dst_reg, true); 13532 } else if ((dst_reg->type == PTR_TO_PACKET_END && 13533 src_reg->type == PTR_TO_PACKET) || 13534 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) && 13535 src_reg->type == PTR_TO_PACKET_META)) { 13536 /* pkt_end > pkt_data', pkt_data > pkt_meta' */ 13537 find_good_pkt_pointers(other_branch, src_reg, 13538 src_reg->type, true); 13539 mark_pkt_end(this_branch, insn->src_reg, false); 13540 } else { 13541 return false; 13542 } 13543 break; 13544 case BPF_JLT: 13545 if ((dst_reg->type == PTR_TO_PACKET && 13546 src_reg->type == PTR_TO_PACKET_END) || 13547 (dst_reg->type == PTR_TO_PACKET_META && 13548 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) { 13549 /* pkt_data' < pkt_end, pkt_meta' < pkt_data */ 13550 find_good_pkt_pointers(other_branch, dst_reg, 13551 dst_reg->type, true); 13552 mark_pkt_end(this_branch, insn->dst_reg, false); 13553 } else if ((dst_reg->type == PTR_TO_PACKET_END && 13554 src_reg->type == PTR_TO_PACKET) || 13555 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) && 13556 src_reg->type == PTR_TO_PACKET_META)) { 13557 /* pkt_end < pkt_data', pkt_data > pkt_meta' */ 13558 find_good_pkt_pointers(this_branch, src_reg, 13559 src_reg->type, false); 13560 mark_pkt_end(other_branch, insn->src_reg, true); 13561 } else { 13562 return false; 13563 } 13564 break; 13565 case BPF_JGE: 13566 if ((dst_reg->type == PTR_TO_PACKET && 13567 src_reg->type == PTR_TO_PACKET_END) || 13568 (dst_reg->type == PTR_TO_PACKET_META && 13569 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) { 13570 /* pkt_data' >= pkt_end, pkt_meta' >= pkt_data */ 13571 find_good_pkt_pointers(this_branch, dst_reg, 13572 dst_reg->type, true); 13573 mark_pkt_end(other_branch, insn->dst_reg, false); 13574 } else if ((dst_reg->type == PTR_TO_PACKET_END && 13575 src_reg->type == PTR_TO_PACKET) || 13576 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) && 13577 src_reg->type == PTR_TO_PACKET_META)) { 13578 /* pkt_end >= pkt_data', pkt_data >= pkt_meta' */ 13579 find_good_pkt_pointers(other_branch, src_reg, 13580 src_reg->type, false); 13581 mark_pkt_end(this_branch, insn->src_reg, true); 13582 } else { 13583 return false; 13584 } 13585 break; 13586 case BPF_JLE: 13587 if ((dst_reg->type == PTR_TO_PACKET && 13588 src_reg->type == PTR_TO_PACKET_END) || 13589 (dst_reg->type == PTR_TO_PACKET_META && 13590 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) { 13591 /* pkt_data' <= pkt_end, pkt_meta' <= pkt_data */ 13592 find_good_pkt_pointers(other_branch, dst_reg, 13593 dst_reg->type, false); 13594 mark_pkt_end(this_branch, insn->dst_reg, true); 13595 } else if ((dst_reg->type == PTR_TO_PACKET_END && 13596 src_reg->type == PTR_TO_PACKET) || 13597 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) && 13598 src_reg->type == PTR_TO_PACKET_META)) { 13599 /* pkt_end <= pkt_data', pkt_data <= pkt_meta' */ 13600 find_good_pkt_pointers(this_branch, src_reg, 13601 src_reg->type, true); 13602 mark_pkt_end(other_branch, insn->src_reg, false); 13603 } else { 13604 return false; 13605 } 13606 break; 13607 default: 13608 return false; 13609 } 13610 13611 return true; 13612 } 13613 13614 static void find_equal_scalars(struct bpf_verifier_state *vstate, 13615 struct bpf_reg_state *known_reg) 13616 { 13617 struct bpf_func_state *state; 13618 struct bpf_reg_state *reg; 13619 13620 bpf_for_each_reg_in_vstate(vstate, state, reg, ({ 13621 if (reg->type == SCALAR_VALUE && reg->id == known_reg->id) 13622 copy_register_state(reg, known_reg); 13623 })); 13624 } 13625 13626 static int check_cond_jmp_op(struct bpf_verifier_env *env, 13627 struct bpf_insn *insn, int *insn_idx) 13628 { 13629 struct bpf_verifier_state *this_branch = env->cur_state; 13630 struct bpf_verifier_state *other_branch; 13631 struct bpf_reg_state *regs = this_branch->frame[this_branch->curframe]->regs; 13632 struct bpf_reg_state *dst_reg, *other_branch_regs, *src_reg = NULL; 13633 struct bpf_reg_state *eq_branch_regs; 13634 u8 opcode = BPF_OP(insn->code); 13635 bool is_jmp32; 13636 int pred = -1; 13637 int err; 13638 13639 /* Only conditional jumps are expected to reach here. */ 13640 if (opcode == BPF_JA || opcode > BPF_JSLE) { 13641 verbose(env, "invalid BPF_JMP/JMP32 opcode %x\n", opcode); 13642 return -EINVAL; 13643 } 13644 13645 if (BPF_SRC(insn->code) == BPF_X) { 13646 if (insn->imm != 0) { 13647 verbose(env, "BPF_JMP/JMP32 uses reserved fields\n"); 13648 return -EINVAL; 13649 } 13650 13651 /* check src1 operand */ 13652 err = check_reg_arg(env, insn->src_reg, SRC_OP); 13653 if (err) 13654 return err; 13655 13656 if (is_pointer_value(env, insn->src_reg)) { 13657 verbose(env, "R%d pointer comparison prohibited\n", 13658 insn->src_reg); 13659 return -EACCES; 13660 } 13661 src_reg = ®s[insn->src_reg]; 13662 } else { 13663 if (insn->src_reg != BPF_REG_0) { 13664 verbose(env, "BPF_JMP/JMP32 uses reserved fields\n"); 13665 return -EINVAL; 13666 } 13667 } 13668 13669 /* check src2 operand */ 13670 err = check_reg_arg(env, insn->dst_reg, SRC_OP); 13671 if (err) 13672 return err; 13673 13674 dst_reg = ®s[insn->dst_reg]; 13675 is_jmp32 = BPF_CLASS(insn->code) == BPF_JMP32; 13676 13677 if (BPF_SRC(insn->code) == BPF_K) { 13678 pred = is_branch_taken(dst_reg, insn->imm, opcode, is_jmp32); 13679 } else if (src_reg->type == SCALAR_VALUE && 13680 is_jmp32 && tnum_is_const(tnum_subreg(src_reg->var_off))) { 13681 pred = is_branch_taken(dst_reg, 13682 tnum_subreg(src_reg->var_off).value, 13683 opcode, 13684 is_jmp32); 13685 } else if (src_reg->type == SCALAR_VALUE && 13686 !is_jmp32 && tnum_is_const(src_reg->var_off)) { 13687 pred = is_branch_taken(dst_reg, 13688 src_reg->var_off.value, 13689 opcode, 13690 is_jmp32); 13691 } else if (dst_reg->type == SCALAR_VALUE && 13692 is_jmp32 && tnum_is_const(tnum_subreg(dst_reg->var_off))) { 13693 pred = is_branch_taken(src_reg, 13694 tnum_subreg(dst_reg->var_off).value, 13695 flip_opcode(opcode), 13696 is_jmp32); 13697 } else if (dst_reg->type == SCALAR_VALUE && 13698 !is_jmp32 && tnum_is_const(dst_reg->var_off)) { 13699 pred = is_branch_taken(src_reg, 13700 dst_reg->var_off.value, 13701 flip_opcode(opcode), 13702 is_jmp32); 13703 } else if (reg_is_pkt_pointer_any(dst_reg) && 13704 reg_is_pkt_pointer_any(src_reg) && 13705 !is_jmp32) { 13706 pred = is_pkt_ptr_branch_taken(dst_reg, src_reg, opcode); 13707 } 13708 13709 if (pred >= 0) { 13710 /* If we get here with a dst_reg pointer type it is because 13711 * above is_branch_taken() special cased the 0 comparison. 13712 */ 13713 if (!__is_pointer_value(false, dst_reg)) 13714 err = mark_chain_precision(env, insn->dst_reg); 13715 if (BPF_SRC(insn->code) == BPF_X && !err && 13716 !__is_pointer_value(false, src_reg)) 13717 err = mark_chain_precision(env, insn->src_reg); 13718 if (err) 13719 return err; 13720 } 13721 13722 if (pred == 1) { 13723 /* Only follow the goto, ignore fall-through. If needed, push 13724 * the fall-through branch for simulation under speculative 13725 * execution. 13726 */ 13727 if (!env->bypass_spec_v1 && 13728 !sanitize_speculative_path(env, insn, *insn_idx + 1, 13729 *insn_idx)) 13730 return -EFAULT; 13731 *insn_idx += insn->off; 13732 return 0; 13733 } else if (pred == 0) { 13734 /* Only follow the fall-through branch, since that's where the 13735 * program will go. If needed, push the goto branch for 13736 * simulation under speculative execution. 13737 */ 13738 if (!env->bypass_spec_v1 && 13739 !sanitize_speculative_path(env, insn, 13740 *insn_idx + insn->off + 1, 13741 *insn_idx)) 13742 return -EFAULT; 13743 return 0; 13744 } 13745 13746 other_branch = push_stack(env, *insn_idx + insn->off + 1, *insn_idx, 13747 false); 13748 if (!other_branch) 13749 return -EFAULT; 13750 other_branch_regs = other_branch->frame[other_branch->curframe]->regs; 13751 13752 /* detect if we are comparing against a constant value so we can adjust 13753 * our min/max values for our dst register. 13754 * this is only legit if both are scalars (or pointers to the same 13755 * object, I suppose, see the PTR_MAYBE_NULL related if block below), 13756 * because otherwise the different base pointers mean the offsets aren't 13757 * comparable. 13758 */ 13759 if (BPF_SRC(insn->code) == BPF_X) { 13760 struct bpf_reg_state *src_reg = ®s[insn->src_reg]; 13761 13762 if (dst_reg->type == SCALAR_VALUE && 13763 src_reg->type == SCALAR_VALUE) { 13764 if (tnum_is_const(src_reg->var_off) || 13765 (is_jmp32 && 13766 tnum_is_const(tnum_subreg(src_reg->var_off)))) 13767 reg_set_min_max(&other_branch_regs[insn->dst_reg], 13768 dst_reg, 13769 src_reg->var_off.value, 13770 tnum_subreg(src_reg->var_off).value, 13771 opcode, is_jmp32); 13772 else if (tnum_is_const(dst_reg->var_off) || 13773 (is_jmp32 && 13774 tnum_is_const(tnum_subreg(dst_reg->var_off)))) 13775 reg_set_min_max_inv(&other_branch_regs[insn->src_reg], 13776 src_reg, 13777 dst_reg->var_off.value, 13778 tnum_subreg(dst_reg->var_off).value, 13779 opcode, is_jmp32); 13780 else if (!is_jmp32 && 13781 (opcode == BPF_JEQ || opcode == BPF_JNE)) 13782 /* Comparing for equality, we can combine knowledge */ 13783 reg_combine_min_max(&other_branch_regs[insn->src_reg], 13784 &other_branch_regs[insn->dst_reg], 13785 src_reg, dst_reg, opcode); 13786 if (src_reg->id && 13787 !WARN_ON_ONCE(src_reg->id != other_branch_regs[insn->src_reg].id)) { 13788 find_equal_scalars(this_branch, src_reg); 13789 find_equal_scalars(other_branch, &other_branch_regs[insn->src_reg]); 13790 } 13791 13792 } 13793 } else if (dst_reg->type == SCALAR_VALUE) { 13794 reg_set_min_max(&other_branch_regs[insn->dst_reg], 13795 dst_reg, insn->imm, (u32)insn->imm, 13796 opcode, is_jmp32); 13797 } 13798 13799 if (dst_reg->type == SCALAR_VALUE && dst_reg->id && 13800 !WARN_ON_ONCE(dst_reg->id != other_branch_regs[insn->dst_reg].id)) { 13801 find_equal_scalars(this_branch, dst_reg); 13802 find_equal_scalars(other_branch, &other_branch_regs[insn->dst_reg]); 13803 } 13804 13805 /* if one pointer register is compared to another pointer 13806 * register check if PTR_MAYBE_NULL could be lifted. 13807 * E.g. register A - maybe null 13808 * register B - not null 13809 * for JNE A, B, ... - A is not null in the false branch; 13810 * for JEQ A, B, ... - A is not null in the true branch. 13811 * 13812 * Since PTR_TO_BTF_ID points to a kernel struct that does 13813 * not need to be null checked by the BPF program, i.e., 13814 * could be null even without PTR_MAYBE_NULL marking, so 13815 * only propagate nullness when neither reg is that type. 13816 */ 13817 if (!is_jmp32 && BPF_SRC(insn->code) == BPF_X && 13818 __is_pointer_value(false, src_reg) && __is_pointer_value(false, dst_reg) && 13819 type_may_be_null(src_reg->type) != type_may_be_null(dst_reg->type) && 13820 base_type(src_reg->type) != PTR_TO_BTF_ID && 13821 base_type(dst_reg->type) != PTR_TO_BTF_ID) { 13822 eq_branch_regs = NULL; 13823 switch (opcode) { 13824 case BPF_JEQ: 13825 eq_branch_regs = other_branch_regs; 13826 break; 13827 case BPF_JNE: 13828 eq_branch_regs = regs; 13829 break; 13830 default: 13831 /* do nothing */ 13832 break; 13833 } 13834 if (eq_branch_regs) { 13835 if (type_may_be_null(src_reg->type)) 13836 mark_ptr_not_null_reg(&eq_branch_regs[insn->src_reg]); 13837 else 13838 mark_ptr_not_null_reg(&eq_branch_regs[insn->dst_reg]); 13839 } 13840 } 13841 13842 /* detect if R == 0 where R is returned from bpf_map_lookup_elem(). 13843 * NOTE: these optimizations below are related with pointer comparison 13844 * which will never be JMP32. 13845 */ 13846 if (!is_jmp32 && BPF_SRC(insn->code) == BPF_K && 13847 insn->imm == 0 && (opcode == BPF_JEQ || opcode == BPF_JNE) && 13848 type_may_be_null(dst_reg->type)) { 13849 /* Mark all identical registers in each branch as either 13850 * safe or unknown depending R == 0 or R != 0 conditional. 13851 */ 13852 mark_ptr_or_null_regs(this_branch, insn->dst_reg, 13853 opcode == BPF_JNE); 13854 mark_ptr_or_null_regs(other_branch, insn->dst_reg, 13855 opcode == BPF_JEQ); 13856 } else if (!try_match_pkt_pointers(insn, dst_reg, ®s[insn->src_reg], 13857 this_branch, other_branch) && 13858 is_pointer_value(env, insn->dst_reg)) { 13859 verbose(env, "R%d pointer comparison prohibited\n", 13860 insn->dst_reg); 13861 return -EACCES; 13862 } 13863 if (env->log.level & BPF_LOG_LEVEL) 13864 print_insn_state(env, this_branch->frame[this_branch->curframe]); 13865 return 0; 13866 } 13867 13868 /* verify BPF_LD_IMM64 instruction */ 13869 static int check_ld_imm(struct bpf_verifier_env *env, struct bpf_insn *insn) 13870 { 13871 struct bpf_insn_aux_data *aux = cur_aux(env); 13872 struct bpf_reg_state *regs = cur_regs(env); 13873 struct bpf_reg_state *dst_reg; 13874 struct bpf_map *map; 13875 int err; 13876 13877 if (BPF_SIZE(insn->code) != BPF_DW) { 13878 verbose(env, "invalid BPF_LD_IMM insn\n"); 13879 return -EINVAL; 13880 } 13881 if (insn->off != 0) { 13882 verbose(env, "BPF_LD_IMM64 uses reserved fields\n"); 13883 return -EINVAL; 13884 } 13885 13886 err = check_reg_arg(env, insn->dst_reg, DST_OP); 13887 if (err) 13888 return err; 13889 13890 dst_reg = ®s[insn->dst_reg]; 13891 if (insn->src_reg == 0) { 13892 u64 imm = ((u64)(insn + 1)->imm << 32) | (u32)insn->imm; 13893 13894 dst_reg->type = SCALAR_VALUE; 13895 __mark_reg_known(®s[insn->dst_reg], imm); 13896 return 0; 13897 } 13898 13899 /* All special src_reg cases are listed below. From this point onwards 13900 * we either succeed and assign a corresponding dst_reg->type after 13901 * zeroing the offset, or fail and reject the program. 13902 */ 13903 mark_reg_known_zero(env, regs, insn->dst_reg); 13904 13905 if (insn->src_reg == BPF_PSEUDO_BTF_ID) { 13906 dst_reg->type = aux->btf_var.reg_type; 13907 switch (base_type(dst_reg->type)) { 13908 case PTR_TO_MEM: 13909 dst_reg->mem_size = aux->btf_var.mem_size; 13910 break; 13911 case PTR_TO_BTF_ID: 13912 dst_reg->btf = aux->btf_var.btf; 13913 dst_reg->btf_id = aux->btf_var.btf_id; 13914 break; 13915 default: 13916 verbose(env, "bpf verifier is misconfigured\n"); 13917 return -EFAULT; 13918 } 13919 return 0; 13920 } 13921 13922 if (insn->src_reg == BPF_PSEUDO_FUNC) { 13923 struct bpf_prog_aux *aux = env->prog->aux; 13924 u32 subprogno = find_subprog(env, 13925 env->insn_idx + insn->imm + 1); 13926 13927 if (!aux->func_info) { 13928 verbose(env, "missing btf func_info\n"); 13929 return -EINVAL; 13930 } 13931 if (aux->func_info_aux[subprogno].linkage != BTF_FUNC_STATIC) { 13932 verbose(env, "callback function not static\n"); 13933 return -EINVAL; 13934 } 13935 13936 dst_reg->type = PTR_TO_FUNC; 13937 dst_reg->subprogno = subprogno; 13938 return 0; 13939 } 13940 13941 map = env->used_maps[aux->map_index]; 13942 dst_reg->map_ptr = map; 13943 13944 if (insn->src_reg == BPF_PSEUDO_MAP_VALUE || 13945 insn->src_reg == BPF_PSEUDO_MAP_IDX_VALUE) { 13946 dst_reg->type = PTR_TO_MAP_VALUE; 13947 dst_reg->off = aux->map_off; 13948 WARN_ON_ONCE(map->max_entries != 1); 13949 /* We want reg->id to be same (0) as map_value is not distinct */ 13950 } else if (insn->src_reg == BPF_PSEUDO_MAP_FD || 13951 insn->src_reg == BPF_PSEUDO_MAP_IDX) { 13952 dst_reg->type = CONST_PTR_TO_MAP; 13953 } else { 13954 verbose(env, "bpf verifier is misconfigured\n"); 13955 return -EINVAL; 13956 } 13957 13958 return 0; 13959 } 13960 13961 static bool may_access_skb(enum bpf_prog_type type) 13962 { 13963 switch (type) { 13964 case BPF_PROG_TYPE_SOCKET_FILTER: 13965 case BPF_PROG_TYPE_SCHED_CLS: 13966 case BPF_PROG_TYPE_SCHED_ACT: 13967 return true; 13968 default: 13969 return false; 13970 } 13971 } 13972 13973 /* verify safety of LD_ABS|LD_IND instructions: 13974 * - they can only appear in the programs where ctx == skb 13975 * - since they are wrappers of function calls, they scratch R1-R5 registers, 13976 * preserve R6-R9, and store return value into R0 13977 * 13978 * Implicit input: 13979 * ctx == skb == R6 == CTX 13980 * 13981 * Explicit input: 13982 * SRC == any register 13983 * IMM == 32-bit immediate 13984 * 13985 * Output: 13986 * R0 - 8/16/32-bit skb data converted to cpu endianness 13987 */ 13988 static int check_ld_abs(struct bpf_verifier_env *env, struct bpf_insn *insn) 13989 { 13990 struct bpf_reg_state *regs = cur_regs(env); 13991 static const int ctx_reg = BPF_REG_6; 13992 u8 mode = BPF_MODE(insn->code); 13993 int i, err; 13994 13995 if (!may_access_skb(resolve_prog_type(env->prog))) { 13996 verbose(env, "BPF_LD_[ABS|IND] instructions not allowed for this program type\n"); 13997 return -EINVAL; 13998 } 13999 14000 if (!env->ops->gen_ld_abs) { 14001 verbose(env, "bpf verifier is misconfigured\n"); 14002 return -EINVAL; 14003 } 14004 14005 if (insn->dst_reg != BPF_REG_0 || insn->off != 0 || 14006 BPF_SIZE(insn->code) == BPF_DW || 14007 (mode == BPF_ABS && insn->src_reg != BPF_REG_0)) { 14008 verbose(env, "BPF_LD_[ABS|IND] uses reserved fields\n"); 14009 return -EINVAL; 14010 } 14011 14012 /* check whether implicit source operand (register R6) is readable */ 14013 err = check_reg_arg(env, ctx_reg, SRC_OP); 14014 if (err) 14015 return err; 14016 14017 /* Disallow usage of BPF_LD_[ABS|IND] with reference tracking, as 14018 * gen_ld_abs() may terminate the program at runtime, leading to 14019 * reference leak. 14020 */ 14021 err = check_reference_leak(env); 14022 if (err) { 14023 verbose(env, "BPF_LD_[ABS|IND] cannot be mixed with socket references\n"); 14024 return err; 14025 } 14026 14027 if (env->cur_state->active_lock.ptr) { 14028 verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_spin_lock-ed region\n"); 14029 return -EINVAL; 14030 } 14031 14032 if (env->cur_state->active_rcu_lock) { 14033 verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_rcu_read_lock-ed region\n"); 14034 return -EINVAL; 14035 } 14036 14037 if (regs[ctx_reg].type != PTR_TO_CTX) { 14038 verbose(env, 14039 "at the time of BPF_LD_ABS|IND R6 != pointer to skb\n"); 14040 return -EINVAL; 14041 } 14042 14043 if (mode == BPF_IND) { 14044 /* check explicit source operand */ 14045 err = check_reg_arg(env, insn->src_reg, SRC_OP); 14046 if (err) 14047 return err; 14048 } 14049 14050 err = check_ptr_off_reg(env, ®s[ctx_reg], ctx_reg); 14051 if (err < 0) 14052 return err; 14053 14054 /* reset caller saved regs to unreadable */ 14055 for (i = 0; i < CALLER_SAVED_REGS; i++) { 14056 mark_reg_not_init(env, regs, caller_saved[i]); 14057 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK); 14058 } 14059 14060 /* mark destination R0 register as readable, since it contains 14061 * the value fetched from the packet. 14062 * Already marked as written above. 14063 */ 14064 mark_reg_unknown(env, regs, BPF_REG_0); 14065 /* ld_abs load up to 32-bit skb data. */ 14066 regs[BPF_REG_0].subreg_def = env->insn_idx + 1; 14067 return 0; 14068 } 14069 14070 static int check_return_code(struct bpf_verifier_env *env) 14071 { 14072 struct tnum enforce_attach_type_range = tnum_unknown; 14073 const struct bpf_prog *prog = env->prog; 14074 struct bpf_reg_state *reg; 14075 struct tnum range = tnum_range(0, 1); 14076 enum bpf_prog_type prog_type = resolve_prog_type(env->prog); 14077 int err; 14078 struct bpf_func_state *frame = env->cur_state->frame[0]; 14079 const bool is_subprog = frame->subprogno; 14080 14081 /* LSM and struct_ops func-ptr's return type could be "void" */ 14082 if (!is_subprog) { 14083 switch (prog_type) { 14084 case BPF_PROG_TYPE_LSM: 14085 if (prog->expected_attach_type == BPF_LSM_CGROUP) 14086 /* See below, can be 0 or 0-1 depending on hook. */ 14087 break; 14088 fallthrough; 14089 case BPF_PROG_TYPE_STRUCT_OPS: 14090 if (!prog->aux->attach_func_proto->type) 14091 return 0; 14092 break; 14093 default: 14094 break; 14095 } 14096 } 14097 14098 /* eBPF calling convention is such that R0 is used 14099 * to return the value from eBPF program. 14100 * Make sure that it's readable at this time 14101 * of bpf_exit, which means that program wrote 14102 * something into it earlier 14103 */ 14104 err = check_reg_arg(env, BPF_REG_0, SRC_OP); 14105 if (err) 14106 return err; 14107 14108 if (is_pointer_value(env, BPF_REG_0)) { 14109 verbose(env, "R0 leaks addr as return value\n"); 14110 return -EACCES; 14111 } 14112 14113 reg = cur_regs(env) + BPF_REG_0; 14114 14115 if (frame->in_async_callback_fn) { 14116 /* enforce return zero from async callbacks like timer */ 14117 if (reg->type != SCALAR_VALUE) { 14118 verbose(env, "In async callback the register R0 is not a known value (%s)\n", 14119 reg_type_str(env, reg->type)); 14120 return -EINVAL; 14121 } 14122 14123 if (!tnum_in(tnum_const(0), reg->var_off)) { 14124 verbose_invalid_scalar(env, reg, &range, "async callback", "R0"); 14125 return -EINVAL; 14126 } 14127 return 0; 14128 } 14129 14130 if (is_subprog) { 14131 if (reg->type != SCALAR_VALUE) { 14132 verbose(env, "At subprogram exit the register R0 is not a scalar value (%s)\n", 14133 reg_type_str(env, reg->type)); 14134 return -EINVAL; 14135 } 14136 return 0; 14137 } 14138 14139 switch (prog_type) { 14140 case BPF_PROG_TYPE_CGROUP_SOCK_ADDR: 14141 if (env->prog->expected_attach_type == BPF_CGROUP_UDP4_RECVMSG || 14142 env->prog->expected_attach_type == BPF_CGROUP_UDP6_RECVMSG || 14143 env->prog->expected_attach_type == BPF_CGROUP_INET4_GETPEERNAME || 14144 env->prog->expected_attach_type == BPF_CGROUP_INET6_GETPEERNAME || 14145 env->prog->expected_attach_type == BPF_CGROUP_INET4_GETSOCKNAME || 14146 env->prog->expected_attach_type == BPF_CGROUP_INET6_GETSOCKNAME) 14147 range = tnum_range(1, 1); 14148 if (env->prog->expected_attach_type == BPF_CGROUP_INET4_BIND || 14149 env->prog->expected_attach_type == BPF_CGROUP_INET6_BIND) 14150 range = tnum_range(0, 3); 14151 break; 14152 case BPF_PROG_TYPE_CGROUP_SKB: 14153 if (env->prog->expected_attach_type == BPF_CGROUP_INET_EGRESS) { 14154 range = tnum_range(0, 3); 14155 enforce_attach_type_range = tnum_range(2, 3); 14156 } 14157 break; 14158 case BPF_PROG_TYPE_CGROUP_SOCK: 14159 case BPF_PROG_TYPE_SOCK_OPS: 14160 case BPF_PROG_TYPE_CGROUP_DEVICE: 14161 case BPF_PROG_TYPE_CGROUP_SYSCTL: 14162 case BPF_PROG_TYPE_CGROUP_SOCKOPT: 14163 break; 14164 case BPF_PROG_TYPE_RAW_TRACEPOINT: 14165 if (!env->prog->aux->attach_btf_id) 14166 return 0; 14167 range = tnum_const(0); 14168 break; 14169 case BPF_PROG_TYPE_TRACING: 14170 switch (env->prog->expected_attach_type) { 14171 case BPF_TRACE_FENTRY: 14172 case BPF_TRACE_FEXIT: 14173 range = tnum_const(0); 14174 break; 14175 case BPF_TRACE_RAW_TP: 14176 case BPF_MODIFY_RETURN: 14177 return 0; 14178 case BPF_TRACE_ITER: 14179 break; 14180 default: 14181 return -ENOTSUPP; 14182 } 14183 break; 14184 case BPF_PROG_TYPE_SK_LOOKUP: 14185 range = tnum_range(SK_DROP, SK_PASS); 14186 break; 14187 14188 case BPF_PROG_TYPE_LSM: 14189 if (env->prog->expected_attach_type != BPF_LSM_CGROUP) { 14190 /* Regular BPF_PROG_TYPE_LSM programs can return 14191 * any value. 14192 */ 14193 return 0; 14194 } 14195 if (!env->prog->aux->attach_func_proto->type) { 14196 /* Make sure programs that attach to void 14197 * hooks don't try to modify return value. 14198 */ 14199 range = tnum_range(1, 1); 14200 } 14201 break; 14202 14203 case BPF_PROG_TYPE_NETFILTER: 14204 range = tnum_range(NF_DROP, NF_ACCEPT); 14205 break; 14206 case BPF_PROG_TYPE_EXT: 14207 /* freplace program can return anything as its return value 14208 * depends on the to-be-replaced kernel func or bpf program. 14209 */ 14210 default: 14211 return 0; 14212 } 14213 14214 if (reg->type != SCALAR_VALUE) { 14215 verbose(env, "At program exit the register R0 is not a known value (%s)\n", 14216 reg_type_str(env, reg->type)); 14217 return -EINVAL; 14218 } 14219 14220 if (!tnum_in(range, reg->var_off)) { 14221 verbose_invalid_scalar(env, reg, &range, "program exit", "R0"); 14222 if (prog->expected_attach_type == BPF_LSM_CGROUP && 14223 prog_type == BPF_PROG_TYPE_LSM && 14224 !prog->aux->attach_func_proto->type) 14225 verbose(env, "Note, BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n"); 14226 return -EINVAL; 14227 } 14228 14229 if (!tnum_is_unknown(enforce_attach_type_range) && 14230 tnum_in(enforce_attach_type_range, reg->var_off)) 14231 env->prog->enforce_expected_attach_type = 1; 14232 return 0; 14233 } 14234 14235 /* non-recursive DFS pseudo code 14236 * 1 procedure DFS-iterative(G,v): 14237 * 2 label v as discovered 14238 * 3 let S be a stack 14239 * 4 S.push(v) 14240 * 5 while S is not empty 14241 * 6 t <- S.peek() 14242 * 7 if t is what we're looking for: 14243 * 8 return t 14244 * 9 for all edges e in G.adjacentEdges(t) do 14245 * 10 if edge e is already labelled 14246 * 11 continue with the next edge 14247 * 12 w <- G.adjacentVertex(t,e) 14248 * 13 if vertex w is not discovered and not explored 14249 * 14 label e as tree-edge 14250 * 15 label w as discovered 14251 * 16 S.push(w) 14252 * 17 continue at 5 14253 * 18 else if vertex w is discovered 14254 * 19 label e as back-edge 14255 * 20 else 14256 * 21 // vertex w is explored 14257 * 22 label e as forward- or cross-edge 14258 * 23 label t as explored 14259 * 24 S.pop() 14260 * 14261 * convention: 14262 * 0x10 - discovered 14263 * 0x11 - discovered and fall-through edge labelled 14264 * 0x12 - discovered and fall-through and branch edges labelled 14265 * 0x20 - explored 14266 */ 14267 14268 enum { 14269 DISCOVERED = 0x10, 14270 EXPLORED = 0x20, 14271 FALLTHROUGH = 1, 14272 BRANCH = 2, 14273 }; 14274 14275 static u32 state_htab_size(struct bpf_verifier_env *env) 14276 { 14277 return env->prog->len; 14278 } 14279 14280 static struct bpf_verifier_state_list **explored_state( 14281 struct bpf_verifier_env *env, 14282 int idx) 14283 { 14284 struct bpf_verifier_state *cur = env->cur_state; 14285 struct bpf_func_state *state = cur->frame[cur->curframe]; 14286 14287 return &env->explored_states[(idx ^ state->callsite) % state_htab_size(env)]; 14288 } 14289 14290 static void mark_prune_point(struct bpf_verifier_env *env, int idx) 14291 { 14292 env->insn_aux_data[idx].prune_point = true; 14293 } 14294 14295 static bool is_prune_point(struct bpf_verifier_env *env, int insn_idx) 14296 { 14297 return env->insn_aux_data[insn_idx].prune_point; 14298 } 14299 14300 static void mark_force_checkpoint(struct bpf_verifier_env *env, int idx) 14301 { 14302 env->insn_aux_data[idx].force_checkpoint = true; 14303 } 14304 14305 static bool is_force_checkpoint(struct bpf_verifier_env *env, int insn_idx) 14306 { 14307 return env->insn_aux_data[insn_idx].force_checkpoint; 14308 } 14309 14310 14311 enum { 14312 DONE_EXPLORING = 0, 14313 KEEP_EXPLORING = 1, 14314 }; 14315 14316 /* t, w, e - match pseudo-code above: 14317 * t - index of current instruction 14318 * w - next instruction 14319 * e - edge 14320 */ 14321 static int push_insn(int t, int w, int e, struct bpf_verifier_env *env, 14322 bool loop_ok) 14323 { 14324 int *insn_stack = env->cfg.insn_stack; 14325 int *insn_state = env->cfg.insn_state; 14326 14327 if (e == FALLTHROUGH && insn_state[t] >= (DISCOVERED | FALLTHROUGH)) 14328 return DONE_EXPLORING; 14329 14330 if (e == BRANCH && insn_state[t] >= (DISCOVERED | BRANCH)) 14331 return DONE_EXPLORING; 14332 14333 if (w < 0 || w >= env->prog->len) { 14334 verbose_linfo(env, t, "%d: ", t); 14335 verbose(env, "jump out of range from insn %d to %d\n", t, w); 14336 return -EINVAL; 14337 } 14338 14339 if (e == BRANCH) { 14340 /* mark branch target for state pruning */ 14341 mark_prune_point(env, w); 14342 mark_jmp_point(env, w); 14343 } 14344 14345 if (insn_state[w] == 0) { 14346 /* tree-edge */ 14347 insn_state[t] = DISCOVERED | e; 14348 insn_state[w] = DISCOVERED; 14349 if (env->cfg.cur_stack >= env->prog->len) 14350 return -E2BIG; 14351 insn_stack[env->cfg.cur_stack++] = w; 14352 return KEEP_EXPLORING; 14353 } else if ((insn_state[w] & 0xF0) == DISCOVERED) { 14354 if (loop_ok && env->bpf_capable) 14355 return DONE_EXPLORING; 14356 verbose_linfo(env, t, "%d: ", t); 14357 verbose_linfo(env, w, "%d: ", w); 14358 verbose(env, "back-edge from insn %d to %d\n", t, w); 14359 return -EINVAL; 14360 } else if (insn_state[w] == EXPLORED) { 14361 /* forward- or cross-edge */ 14362 insn_state[t] = DISCOVERED | e; 14363 } else { 14364 verbose(env, "insn state internal bug\n"); 14365 return -EFAULT; 14366 } 14367 return DONE_EXPLORING; 14368 } 14369 14370 static int visit_func_call_insn(int t, struct bpf_insn *insns, 14371 struct bpf_verifier_env *env, 14372 bool visit_callee) 14373 { 14374 int ret; 14375 14376 ret = push_insn(t, t + 1, FALLTHROUGH, env, false); 14377 if (ret) 14378 return ret; 14379 14380 mark_prune_point(env, t + 1); 14381 /* when we exit from subprog, we need to record non-linear history */ 14382 mark_jmp_point(env, t + 1); 14383 14384 if (visit_callee) { 14385 mark_prune_point(env, t); 14386 ret = push_insn(t, t + insns[t].imm + 1, BRANCH, env, 14387 /* It's ok to allow recursion from CFG point of 14388 * view. __check_func_call() will do the actual 14389 * check. 14390 */ 14391 bpf_pseudo_func(insns + t)); 14392 } 14393 return ret; 14394 } 14395 14396 /* Visits the instruction at index t and returns one of the following: 14397 * < 0 - an error occurred 14398 * DONE_EXPLORING - the instruction was fully explored 14399 * KEEP_EXPLORING - there is still work to be done before it is fully explored 14400 */ 14401 static int visit_insn(int t, struct bpf_verifier_env *env) 14402 { 14403 struct bpf_insn *insns = env->prog->insnsi, *insn = &insns[t]; 14404 int ret; 14405 14406 if (bpf_pseudo_func(insn)) 14407 return visit_func_call_insn(t, insns, env, true); 14408 14409 /* All non-branch instructions have a single fall-through edge. */ 14410 if (BPF_CLASS(insn->code) != BPF_JMP && 14411 BPF_CLASS(insn->code) != BPF_JMP32) 14412 return push_insn(t, t + 1, FALLTHROUGH, env, false); 14413 14414 switch (BPF_OP(insn->code)) { 14415 case BPF_EXIT: 14416 return DONE_EXPLORING; 14417 14418 case BPF_CALL: 14419 if (insn->src_reg == 0 && insn->imm == BPF_FUNC_timer_set_callback) 14420 /* Mark this call insn as a prune point to trigger 14421 * is_state_visited() check before call itself is 14422 * processed by __check_func_call(). Otherwise new 14423 * async state will be pushed for further exploration. 14424 */ 14425 mark_prune_point(env, t); 14426 if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) { 14427 struct bpf_kfunc_call_arg_meta meta; 14428 14429 ret = fetch_kfunc_meta(env, insn, &meta, NULL); 14430 if (ret == 0 && is_iter_next_kfunc(&meta)) { 14431 mark_prune_point(env, t); 14432 /* Checking and saving state checkpoints at iter_next() call 14433 * is crucial for fast convergence of open-coded iterator loop 14434 * logic, so we need to force it. If we don't do that, 14435 * is_state_visited() might skip saving a checkpoint, causing 14436 * unnecessarily long sequence of not checkpointed 14437 * instructions and jumps, leading to exhaustion of jump 14438 * history buffer, and potentially other undesired outcomes. 14439 * It is expected that with correct open-coded iterators 14440 * convergence will happen quickly, so we don't run a risk of 14441 * exhausting memory. 14442 */ 14443 mark_force_checkpoint(env, t); 14444 } 14445 } 14446 return visit_func_call_insn(t, insns, env, insn->src_reg == BPF_PSEUDO_CALL); 14447 14448 case BPF_JA: 14449 if (BPF_SRC(insn->code) != BPF_K) 14450 return -EINVAL; 14451 14452 /* unconditional jump with single edge */ 14453 ret = push_insn(t, t + insn->off + 1, FALLTHROUGH, env, 14454 true); 14455 if (ret) 14456 return ret; 14457 14458 mark_prune_point(env, t + insn->off + 1); 14459 mark_jmp_point(env, t + insn->off + 1); 14460 14461 return ret; 14462 14463 default: 14464 /* conditional jump with two edges */ 14465 mark_prune_point(env, t); 14466 14467 ret = push_insn(t, t + 1, FALLTHROUGH, env, true); 14468 if (ret) 14469 return ret; 14470 14471 return push_insn(t, t + insn->off + 1, BRANCH, env, true); 14472 } 14473 } 14474 14475 /* non-recursive depth-first-search to detect loops in BPF program 14476 * loop == back-edge in directed graph 14477 */ 14478 static int check_cfg(struct bpf_verifier_env *env) 14479 { 14480 int insn_cnt = env->prog->len; 14481 int *insn_stack, *insn_state; 14482 int ret = 0; 14483 int i; 14484 14485 insn_state = env->cfg.insn_state = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL); 14486 if (!insn_state) 14487 return -ENOMEM; 14488 14489 insn_stack = env->cfg.insn_stack = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL); 14490 if (!insn_stack) { 14491 kvfree(insn_state); 14492 return -ENOMEM; 14493 } 14494 14495 insn_state[0] = DISCOVERED; /* mark 1st insn as discovered */ 14496 insn_stack[0] = 0; /* 0 is the first instruction */ 14497 env->cfg.cur_stack = 1; 14498 14499 while (env->cfg.cur_stack > 0) { 14500 int t = insn_stack[env->cfg.cur_stack - 1]; 14501 14502 ret = visit_insn(t, env); 14503 switch (ret) { 14504 case DONE_EXPLORING: 14505 insn_state[t] = EXPLORED; 14506 env->cfg.cur_stack--; 14507 break; 14508 case KEEP_EXPLORING: 14509 break; 14510 default: 14511 if (ret > 0) { 14512 verbose(env, "visit_insn internal bug\n"); 14513 ret = -EFAULT; 14514 } 14515 goto err_free; 14516 } 14517 } 14518 14519 if (env->cfg.cur_stack < 0) { 14520 verbose(env, "pop stack internal bug\n"); 14521 ret = -EFAULT; 14522 goto err_free; 14523 } 14524 14525 for (i = 0; i < insn_cnt; i++) { 14526 if (insn_state[i] != EXPLORED) { 14527 verbose(env, "unreachable insn %d\n", i); 14528 ret = -EINVAL; 14529 goto err_free; 14530 } 14531 } 14532 ret = 0; /* cfg looks good */ 14533 14534 err_free: 14535 kvfree(insn_state); 14536 kvfree(insn_stack); 14537 env->cfg.insn_state = env->cfg.insn_stack = NULL; 14538 return ret; 14539 } 14540 14541 static int check_abnormal_return(struct bpf_verifier_env *env) 14542 { 14543 int i; 14544 14545 for (i = 1; i < env->subprog_cnt; i++) { 14546 if (env->subprog_info[i].has_ld_abs) { 14547 verbose(env, "LD_ABS is not allowed in subprogs without BTF\n"); 14548 return -EINVAL; 14549 } 14550 if (env->subprog_info[i].has_tail_call) { 14551 verbose(env, "tail_call is not allowed in subprogs without BTF\n"); 14552 return -EINVAL; 14553 } 14554 } 14555 return 0; 14556 } 14557 14558 /* The minimum supported BTF func info size */ 14559 #define MIN_BPF_FUNCINFO_SIZE 8 14560 #define MAX_FUNCINFO_REC_SIZE 252 14561 14562 static int check_btf_func(struct bpf_verifier_env *env, 14563 const union bpf_attr *attr, 14564 bpfptr_t uattr) 14565 { 14566 const struct btf_type *type, *func_proto, *ret_type; 14567 u32 i, nfuncs, urec_size, min_size; 14568 u32 krec_size = sizeof(struct bpf_func_info); 14569 struct bpf_func_info *krecord; 14570 struct bpf_func_info_aux *info_aux = NULL; 14571 struct bpf_prog *prog; 14572 const struct btf *btf; 14573 bpfptr_t urecord; 14574 u32 prev_offset = 0; 14575 bool scalar_return; 14576 int ret = -ENOMEM; 14577 14578 nfuncs = attr->func_info_cnt; 14579 if (!nfuncs) { 14580 if (check_abnormal_return(env)) 14581 return -EINVAL; 14582 return 0; 14583 } 14584 14585 if (nfuncs != env->subprog_cnt) { 14586 verbose(env, "number of funcs in func_info doesn't match number of subprogs\n"); 14587 return -EINVAL; 14588 } 14589 14590 urec_size = attr->func_info_rec_size; 14591 if (urec_size < MIN_BPF_FUNCINFO_SIZE || 14592 urec_size > MAX_FUNCINFO_REC_SIZE || 14593 urec_size % sizeof(u32)) { 14594 verbose(env, "invalid func info rec size %u\n", urec_size); 14595 return -EINVAL; 14596 } 14597 14598 prog = env->prog; 14599 btf = prog->aux->btf; 14600 14601 urecord = make_bpfptr(attr->func_info, uattr.is_kernel); 14602 min_size = min_t(u32, krec_size, urec_size); 14603 14604 krecord = kvcalloc(nfuncs, krec_size, GFP_KERNEL | __GFP_NOWARN); 14605 if (!krecord) 14606 return -ENOMEM; 14607 info_aux = kcalloc(nfuncs, sizeof(*info_aux), GFP_KERNEL | __GFP_NOWARN); 14608 if (!info_aux) 14609 goto err_free; 14610 14611 for (i = 0; i < nfuncs; i++) { 14612 ret = bpf_check_uarg_tail_zero(urecord, krec_size, urec_size); 14613 if (ret) { 14614 if (ret == -E2BIG) { 14615 verbose(env, "nonzero tailing record in func info"); 14616 /* set the size kernel expects so loader can zero 14617 * out the rest of the record. 14618 */ 14619 if (copy_to_bpfptr_offset(uattr, 14620 offsetof(union bpf_attr, func_info_rec_size), 14621 &min_size, sizeof(min_size))) 14622 ret = -EFAULT; 14623 } 14624 goto err_free; 14625 } 14626 14627 if (copy_from_bpfptr(&krecord[i], urecord, min_size)) { 14628 ret = -EFAULT; 14629 goto err_free; 14630 } 14631 14632 /* check insn_off */ 14633 ret = -EINVAL; 14634 if (i == 0) { 14635 if (krecord[i].insn_off) { 14636 verbose(env, 14637 "nonzero insn_off %u for the first func info record", 14638 krecord[i].insn_off); 14639 goto err_free; 14640 } 14641 } else if (krecord[i].insn_off <= prev_offset) { 14642 verbose(env, 14643 "same or smaller insn offset (%u) than previous func info record (%u)", 14644 krecord[i].insn_off, prev_offset); 14645 goto err_free; 14646 } 14647 14648 if (env->subprog_info[i].start != krecord[i].insn_off) { 14649 verbose(env, "func_info BTF section doesn't match subprog layout in BPF program\n"); 14650 goto err_free; 14651 } 14652 14653 /* check type_id */ 14654 type = btf_type_by_id(btf, krecord[i].type_id); 14655 if (!type || !btf_type_is_func(type)) { 14656 verbose(env, "invalid type id %d in func info", 14657 krecord[i].type_id); 14658 goto err_free; 14659 } 14660 info_aux[i].linkage = BTF_INFO_VLEN(type->info); 14661 14662 func_proto = btf_type_by_id(btf, type->type); 14663 if (unlikely(!func_proto || !btf_type_is_func_proto(func_proto))) 14664 /* btf_func_check() already verified it during BTF load */ 14665 goto err_free; 14666 ret_type = btf_type_skip_modifiers(btf, func_proto->type, NULL); 14667 scalar_return = 14668 btf_type_is_small_int(ret_type) || btf_is_any_enum(ret_type); 14669 if (i && !scalar_return && env->subprog_info[i].has_ld_abs) { 14670 verbose(env, "LD_ABS is only allowed in functions that return 'int'.\n"); 14671 goto err_free; 14672 } 14673 if (i && !scalar_return && env->subprog_info[i].has_tail_call) { 14674 verbose(env, "tail_call is only allowed in functions that return 'int'.\n"); 14675 goto err_free; 14676 } 14677 14678 prev_offset = krecord[i].insn_off; 14679 bpfptr_add(&urecord, urec_size); 14680 } 14681 14682 prog->aux->func_info = krecord; 14683 prog->aux->func_info_cnt = nfuncs; 14684 prog->aux->func_info_aux = info_aux; 14685 return 0; 14686 14687 err_free: 14688 kvfree(krecord); 14689 kfree(info_aux); 14690 return ret; 14691 } 14692 14693 static void adjust_btf_func(struct bpf_verifier_env *env) 14694 { 14695 struct bpf_prog_aux *aux = env->prog->aux; 14696 int i; 14697 14698 if (!aux->func_info) 14699 return; 14700 14701 for (i = 0; i < env->subprog_cnt; i++) 14702 aux->func_info[i].insn_off = env->subprog_info[i].start; 14703 } 14704 14705 #define MIN_BPF_LINEINFO_SIZE offsetofend(struct bpf_line_info, line_col) 14706 #define MAX_LINEINFO_REC_SIZE MAX_FUNCINFO_REC_SIZE 14707 14708 static int check_btf_line(struct bpf_verifier_env *env, 14709 const union bpf_attr *attr, 14710 bpfptr_t uattr) 14711 { 14712 u32 i, s, nr_linfo, ncopy, expected_size, rec_size, prev_offset = 0; 14713 struct bpf_subprog_info *sub; 14714 struct bpf_line_info *linfo; 14715 struct bpf_prog *prog; 14716 const struct btf *btf; 14717 bpfptr_t ulinfo; 14718 int err; 14719 14720 nr_linfo = attr->line_info_cnt; 14721 if (!nr_linfo) 14722 return 0; 14723 if (nr_linfo > INT_MAX / sizeof(struct bpf_line_info)) 14724 return -EINVAL; 14725 14726 rec_size = attr->line_info_rec_size; 14727 if (rec_size < MIN_BPF_LINEINFO_SIZE || 14728 rec_size > MAX_LINEINFO_REC_SIZE || 14729 rec_size & (sizeof(u32) - 1)) 14730 return -EINVAL; 14731 14732 /* Need to zero it in case the userspace may 14733 * pass in a smaller bpf_line_info object. 14734 */ 14735 linfo = kvcalloc(nr_linfo, sizeof(struct bpf_line_info), 14736 GFP_KERNEL | __GFP_NOWARN); 14737 if (!linfo) 14738 return -ENOMEM; 14739 14740 prog = env->prog; 14741 btf = prog->aux->btf; 14742 14743 s = 0; 14744 sub = env->subprog_info; 14745 ulinfo = make_bpfptr(attr->line_info, uattr.is_kernel); 14746 expected_size = sizeof(struct bpf_line_info); 14747 ncopy = min_t(u32, expected_size, rec_size); 14748 for (i = 0; i < nr_linfo; i++) { 14749 err = bpf_check_uarg_tail_zero(ulinfo, expected_size, rec_size); 14750 if (err) { 14751 if (err == -E2BIG) { 14752 verbose(env, "nonzero tailing record in line_info"); 14753 if (copy_to_bpfptr_offset(uattr, 14754 offsetof(union bpf_attr, line_info_rec_size), 14755 &expected_size, sizeof(expected_size))) 14756 err = -EFAULT; 14757 } 14758 goto err_free; 14759 } 14760 14761 if (copy_from_bpfptr(&linfo[i], ulinfo, ncopy)) { 14762 err = -EFAULT; 14763 goto err_free; 14764 } 14765 14766 /* 14767 * Check insn_off to ensure 14768 * 1) strictly increasing AND 14769 * 2) bounded by prog->len 14770 * 14771 * The linfo[0].insn_off == 0 check logically falls into 14772 * the later "missing bpf_line_info for func..." case 14773 * because the first linfo[0].insn_off must be the 14774 * first sub also and the first sub must have 14775 * subprog_info[0].start == 0. 14776 */ 14777 if ((i && linfo[i].insn_off <= prev_offset) || 14778 linfo[i].insn_off >= prog->len) { 14779 verbose(env, "Invalid line_info[%u].insn_off:%u (prev_offset:%u prog->len:%u)\n", 14780 i, linfo[i].insn_off, prev_offset, 14781 prog->len); 14782 err = -EINVAL; 14783 goto err_free; 14784 } 14785 14786 if (!prog->insnsi[linfo[i].insn_off].code) { 14787 verbose(env, 14788 "Invalid insn code at line_info[%u].insn_off\n", 14789 i); 14790 err = -EINVAL; 14791 goto err_free; 14792 } 14793 14794 if (!btf_name_by_offset(btf, linfo[i].line_off) || 14795 !btf_name_by_offset(btf, linfo[i].file_name_off)) { 14796 verbose(env, "Invalid line_info[%u].line_off or .file_name_off\n", i); 14797 err = -EINVAL; 14798 goto err_free; 14799 } 14800 14801 if (s != env->subprog_cnt) { 14802 if (linfo[i].insn_off == sub[s].start) { 14803 sub[s].linfo_idx = i; 14804 s++; 14805 } else if (sub[s].start < linfo[i].insn_off) { 14806 verbose(env, "missing bpf_line_info for func#%u\n", s); 14807 err = -EINVAL; 14808 goto err_free; 14809 } 14810 } 14811 14812 prev_offset = linfo[i].insn_off; 14813 bpfptr_add(&ulinfo, rec_size); 14814 } 14815 14816 if (s != env->subprog_cnt) { 14817 verbose(env, "missing bpf_line_info for %u funcs starting from func#%u\n", 14818 env->subprog_cnt - s, s); 14819 err = -EINVAL; 14820 goto err_free; 14821 } 14822 14823 prog->aux->linfo = linfo; 14824 prog->aux->nr_linfo = nr_linfo; 14825 14826 return 0; 14827 14828 err_free: 14829 kvfree(linfo); 14830 return err; 14831 } 14832 14833 #define MIN_CORE_RELO_SIZE sizeof(struct bpf_core_relo) 14834 #define MAX_CORE_RELO_SIZE MAX_FUNCINFO_REC_SIZE 14835 14836 static int check_core_relo(struct bpf_verifier_env *env, 14837 const union bpf_attr *attr, 14838 bpfptr_t uattr) 14839 { 14840 u32 i, nr_core_relo, ncopy, expected_size, rec_size; 14841 struct bpf_core_relo core_relo = {}; 14842 struct bpf_prog *prog = env->prog; 14843 const struct btf *btf = prog->aux->btf; 14844 struct bpf_core_ctx ctx = { 14845 .log = &env->log, 14846 .btf = btf, 14847 }; 14848 bpfptr_t u_core_relo; 14849 int err; 14850 14851 nr_core_relo = attr->core_relo_cnt; 14852 if (!nr_core_relo) 14853 return 0; 14854 if (nr_core_relo > INT_MAX / sizeof(struct bpf_core_relo)) 14855 return -EINVAL; 14856 14857 rec_size = attr->core_relo_rec_size; 14858 if (rec_size < MIN_CORE_RELO_SIZE || 14859 rec_size > MAX_CORE_RELO_SIZE || 14860 rec_size % sizeof(u32)) 14861 return -EINVAL; 14862 14863 u_core_relo = make_bpfptr(attr->core_relos, uattr.is_kernel); 14864 expected_size = sizeof(struct bpf_core_relo); 14865 ncopy = min_t(u32, expected_size, rec_size); 14866 14867 /* Unlike func_info and line_info, copy and apply each CO-RE 14868 * relocation record one at a time. 14869 */ 14870 for (i = 0; i < nr_core_relo; i++) { 14871 /* future proofing when sizeof(bpf_core_relo) changes */ 14872 err = bpf_check_uarg_tail_zero(u_core_relo, expected_size, rec_size); 14873 if (err) { 14874 if (err == -E2BIG) { 14875 verbose(env, "nonzero tailing record in core_relo"); 14876 if (copy_to_bpfptr_offset(uattr, 14877 offsetof(union bpf_attr, core_relo_rec_size), 14878 &expected_size, sizeof(expected_size))) 14879 err = -EFAULT; 14880 } 14881 break; 14882 } 14883 14884 if (copy_from_bpfptr(&core_relo, u_core_relo, ncopy)) { 14885 err = -EFAULT; 14886 break; 14887 } 14888 14889 if (core_relo.insn_off % 8 || core_relo.insn_off / 8 >= prog->len) { 14890 verbose(env, "Invalid core_relo[%u].insn_off:%u prog->len:%u\n", 14891 i, core_relo.insn_off, prog->len); 14892 err = -EINVAL; 14893 break; 14894 } 14895 14896 err = bpf_core_apply(&ctx, &core_relo, i, 14897 &prog->insnsi[core_relo.insn_off / 8]); 14898 if (err) 14899 break; 14900 bpfptr_add(&u_core_relo, rec_size); 14901 } 14902 return err; 14903 } 14904 14905 static int check_btf_info(struct bpf_verifier_env *env, 14906 const union bpf_attr *attr, 14907 bpfptr_t uattr) 14908 { 14909 struct btf *btf; 14910 int err; 14911 14912 if (!attr->func_info_cnt && !attr->line_info_cnt) { 14913 if (check_abnormal_return(env)) 14914 return -EINVAL; 14915 return 0; 14916 } 14917 14918 btf = btf_get_by_fd(attr->prog_btf_fd); 14919 if (IS_ERR(btf)) 14920 return PTR_ERR(btf); 14921 if (btf_is_kernel(btf)) { 14922 btf_put(btf); 14923 return -EACCES; 14924 } 14925 env->prog->aux->btf = btf; 14926 14927 err = check_btf_func(env, attr, uattr); 14928 if (err) 14929 return err; 14930 14931 err = check_btf_line(env, attr, uattr); 14932 if (err) 14933 return err; 14934 14935 err = check_core_relo(env, attr, uattr); 14936 if (err) 14937 return err; 14938 14939 return 0; 14940 } 14941 14942 /* check %cur's range satisfies %old's */ 14943 static bool range_within(struct bpf_reg_state *old, 14944 struct bpf_reg_state *cur) 14945 { 14946 return old->umin_value <= cur->umin_value && 14947 old->umax_value >= cur->umax_value && 14948 old->smin_value <= cur->smin_value && 14949 old->smax_value >= cur->smax_value && 14950 old->u32_min_value <= cur->u32_min_value && 14951 old->u32_max_value >= cur->u32_max_value && 14952 old->s32_min_value <= cur->s32_min_value && 14953 old->s32_max_value >= cur->s32_max_value; 14954 } 14955 14956 /* If in the old state two registers had the same id, then they need to have 14957 * the same id in the new state as well. But that id could be different from 14958 * the old state, so we need to track the mapping from old to new ids. 14959 * Once we have seen that, say, a reg with old id 5 had new id 9, any subsequent 14960 * regs with old id 5 must also have new id 9 for the new state to be safe. But 14961 * regs with a different old id could still have new id 9, we don't care about 14962 * that. 14963 * So we look through our idmap to see if this old id has been seen before. If 14964 * so, we require the new id to match; otherwise, we add the id pair to the map. 14965 */ 14966 static bool check_ids(u32 old_id, u32 cur_id, struct bpf_id_pair *idmap) 14967 { 14968 unsigned int i; 14969 14970 /* either both IDs should be set or both should be zero */ 14971 if (!!old_id != !!cur_id) 14972 return false; 14973 14974 if (old_id == 0) /* cur_id == 0 as well */ 14975 return true; 14976 14977 for (i = 0; i < BPF_ID_MAP_SIZE; i++) { 14978 if (!idmap[i].old) { 14979 /* Reached an empty slot; haven't seen this id before */ 14980 idmap[i].old = old_id; 14981 idmap[i].cur = cur_id; 14982 return true; 14983 } 14984 if (idmap[i].old == old_id) 14985 return idmap[i].cur == cur_id; 14986 } 14987 /* We ran out of idmap slots, which should be impossible */ 14988 WARN_ON_ONCE(1); 14989 return false; 14990 } 14991 14992 static void clean_func_state(struct bpf_verifier_env *env, 14993 struct bpf_func_state *st) 14994 { 14995 enum bpf_reg_liveness live; 14996 int i, j; 14997 14998 for (i = 0; i < BPF_REG_FP; i++) { 14999 live = st->regs[i].live; 15000 /* liveness must not touch this register anymore */ 15001 st->regs[i].live |= REG_LIVE_DONE; 15002 if (!(live & REG_LIVE_READ)) 15003 /* since the register is unused, clear its state 15004 * to make further comparison simpler 15005 */ 15006 __mark_reg_not_init(env, &st->regs[i]); 15007 } 15008 15009 for (i = 0; i < st->allocated_stack / BPF_REG_SIZE; i++) { 15010 live = st->stack[i].spilled_ptr.live; 15011 /* liveness must not touch this stack slot anymore */ 15012 st->stack[i].spilled_ptr.live |= REG_LIVE_DONE; 15013 if (!(live & REG_LIVE_READ)) { 15014 __mark_reg_not_init(env, &st->stack[i].spilled_ptr); 15015 for (j = 0; j < BPF_REG_SIZE; j++) 15016 st->stack[i].slot_type[j] = STACK_INVALID; 15017 } 15018 } 15019 } 15020 15021 static void clean_verifier_state(struct bpf_verifier_env *env, 15022 struct bpf_verifier_state *st) 15023 { 15024 int i; 15025 15026 if (st->frame[0]->regs[0].live & REG_LIVE_DONE) 15027 /* all regs in this state in all frames were already marked */ 15028 return; 15029 15030 for (i = 0; i <= st->curframe; i++) 15031 clean_func_state(env, st->frame[i]); 15032 } 15033 15034 /* the parentage chains form a tree. 15035 * the verifier states are added to state lists at given insn and 15036 * pushed into state stack for future exploration. 15037 * when the verifier reaches bpf_exit insn some of the verifer states 15038 * stored in the state lists have their final liveness state already, 15039 * but a lot of states will get revised from liveness point of view when 15040 * the verifier explores other branches. 15041 * Example: 15042 * 1: r0 = 1 15043 * 2: if r1 == 100 goto pc+1 15044 * 3: r0 = 2 15045 * 4: exit 15046 * when the verifier reaches exit insn the register r0 in the state list of 15047 * insn 2 will be seen as !REG_LIVE_READ. Then the verifier pops the other_branch 15048 * of insn 2 and goes exploring further. At the insn 4 it will walk the 15049 * parentage chain from insn 4 into insn 2 and will mark r0 as REG_LIVE_READ. 15050 * 15051 * Since the verifier pushes the branch states as it sees them while exploring 15052 * the program the condition of walking the branch instruction for the second 15053 * time means that all states below this branch were already explored and 15054 * their final liveness marks are already propagated. 15055 * Hence when the verifier completes the search of state list in is_state_visited() 15056 * we can call this clean_live_states() function to mark all liveness states 15057 * as REG_LIVE_DONE to indicate that 'parent' pointers of 'struct bpf_reg_state' 15058 * will not be used. 15059 * This function also clears the registers and stack for states that !READ 15060 * to simplify state merging. 15061 * 15062 * Important note here that walking the same branch instruction in the callee 15063 * doesn't meant that the states are DONE. The verifier has to compare 15064 * the callsites 15065 */ 15066 static void clean_live_states(struct bpf_verifier_env *env, int insn, 15067 struct bpf_verifier_state *cur) 15068 { 15069 struct bpf_verifier_state_list *sl; 15070 int i; 15071 15072 sl = *explored_state(env, insn); 15073 while (sl) { 15074 if (sl->state.branches) 15075 goto next; 15076 if (sl->state.insn_idx != insn || 15077 sl->state.curframe != cur->curframe) 15078 goto next; 15079 for (i = 0; i <= cur->curframe; i++) 15080 if (sl->state.frame[i]->callsite != cur->frame[i]->callsite) 15081 goto next; 15082 clean_verifier_state(env, &sl->state); 15083 next: 15084 sl = sl->next; 15085 } 15086 } 15087 15088 static bool regs_exact(const struct bpf_reg_state *rold, 15089 const struct bpf_reg_state *rcur, 15090 struct bpf_id_pair *idmap) 15091 { 15092 return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 && 15093 check_ids(rold->id, rcur->id, idmap) && 15094 check_ids(rold->ref_obj_id, rcur->ref_obj_id, idmap); 15095 } 15096 15097 /* Returns true if (rold safe implies rcur safe) */ 15098 static bool regsafe(struct bpf_verifier_env *env, struct bpf_reg_state *rold, 15099 struct bpf_reg_state *rcur, struct bpf_id_pair *idmap) 15100 { 15101 if (!(rold->live & REG_LIVE_READ)) 15102 /* explored state didn't use this */ 15103 return true; 15104 if (rold->type == NOT_INIT) 15105 /* explored state can't have used this */ 15106 return true; 15107 if (rcur->type == NOT_INIT) 15108 return false; 15109 15110 /* Enforce that register types have to match exactly, including their 15111 * modifiers (like PTR_MAYBE_NULL, MEM_RDONLY, etc), as a general 15112 * rule. 15113 * 15114 * One can make a point that using a pointer register as unbounded 15115 * SCALAR would be technically acceptable, but this could lead to 15116 * pointer leaks because scalars are allowed to leak while pointers 15117 * are not. We could make this safe in special cases if root is 15118 * calling us, but it's probably not worth the hassle. 15119 * 15120 * Also, register types that are *not* MAYBE_NULL could technically be 15121 * safe to use as their MAYBE_NULL variants (e.g., PTR_TO_MAP_VALUE 15122 * is safe to be used as PTR_TO_MAP_VALUE_OR_NULL, provided both point 15123 * to the same map). 15124 * However, if the old MAYBE_NULL register then got NULL checked, 15125 * doing so could have affected others with the same id, and we can't 15126 * check for that because we lost the id when we converted to 15127 * a non-MAYBE_NULL variant. 15128 * So, as a general rule we don't allow mixing MAYBE_NULL and 15129 * non-MAYBE_NULL registers as well. 15130 */ 15131 if (rold->type != rcur->type) 15132 return false; 15133 15134 switch (base_type(rold->type)) { 15135 case SCALAR_VALUE: 15136 if (regs_exact(rold, rcur, idmap)) 15137 return true; 15138 if (env->explore_alu_limits) 15139 return false; 15140 if (!rold->precise) 15141 return true; 15142 /* new val must satisfy old val knowledge */ 15143 return range_within(rold, rcur) && 15144 tnum_in(rold->var_off, rcur->var_off); 15145 case PTR_TO_MAP_KEY: 15146 case PTR_TO_MAP_VALUE: 15147 case PTR_TO_MEM: 15148 case PTR_TO_BUF: 15149 case PTR_TO_TP_BUFFER: 15150 /* If the new min/max/var_off satisfy the old ones and 15151 * everything else matches, we are OK. 15152 */ 15153 return memcmp(rold, rcur, offsetof(struct bpf_reg_state, var_off)) == 0 && 15154 range_within(rold, rcur) && 15155 tnum_in(rold->var_off, rcur->var_off) && 15156 check_ids(rold->id, rcur->id, idmap) && 15157 check_ids(rold->ref_obj_id, rcur->ref_obj_id, idmap); 15158 case PTR_TO_PACKET_META: 15159 case PTR_TO_PACKET: 15160 /* We must have at least as much range as the old ptr 15161 * did, so that any accesses which were safe before are 15162 * still safe. This is true even if old range < old off, 15163 * since someone could have accessed through (ptr - k), or 15164 * even done ptr -= k in a register, to get a safe access. 15165 */ 15166 if (rold->range > rcur->range) 15167 return false; 15168 /* If the offsets don't match, we can't trust our alignment; 15169 * nor can we be sure that we won't fall out of range. 15170 */ 15171 if (rold->off != rcur->off) 15172 return false; 15173 /* id relations must be preserved */ 15174 if (!check_ids(rold->id, rcur->id, idmap)) 15175 return false; 15176 /* new val must satisfy old val knowledge */ 15177 return range_within(rold, rcur) && 15178 tnum_in(rold->var_off, rcur->var_off); 15179 case PTR_TO_STACK: 15180 /* two stack pointers are equal only if they're pointing to 15181 * the same stack frame, since fp-8 in foo != fp-8 in bar 15182 */ 15183 return regs_exact(rold, rcur, idmap) && rold->frameno == rcur->frameno; 15184 default: 15185 return regs_exact(rold, rcur, idmap); 15186 } 15187 } 15188 15189 static bool stacksafe(struct bpf_verifier_env *env, struct bpf_func_state *old, 15190 struct bpf_func_state *cur, struct bpf_id_pair *idmap) 15191 { 15192 int i, spi; 15193 15194 /* walk slots of the explored stack and ignore any additional 15195 * slots in the current stack, since explored(safe) state 15196 * didn't use them 15197 */ 15198 for (i = 0; i < old->allocated_stack; i++) { 15199 struct bpf_reg_state *old_reg, *cur_reg; 15200 15201 spi = i / BPF_REG_SIZE; 15202 15203 if (!(old->stack[spi].spilled_ptr.live & REG_LIVE_READ)) { 15204 i += BPF_REG_SIZE - 1; 15205 /* explored state didn't use this */ 15206 continue; 15207 } 15208 15209 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_INVALID) 15210 continue; 15211 15212 if (env->allow_uninit_stack && 15213 old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC) 15214 continue; 15215 15216 /* explored stack has more populated slots than current stack 15217 * and these slots were used 15218 */ 15219 if (i >= cur->allocated_stack) 15220 return false; 15221 15222 /* if old state was safe with misc data in the stack 15223 * it will be safe with zero-initialized stack. 15224 * The opposite is not true 15225 */ 15226 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC && 15227 cur->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_ZERO) 15228 continue; 15229 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] != 15230 cur->stack[spi].slot_type[i % BPF_REG_SIZE]) 15231 /* Ex: old explored (safe) state has STACK_SPILL in 15232 * this stack slot, but current has STACK_MISC -> 15233 * this verifier states are not equivalent, 15234 * return false to continue verification of this path 15235 */ 15236 return false; 15237 if (i % BPF_REG_SIZE != BPF_REG_SIZE - 1) 15238 continue; 15239 /* Both old and cur are having same slot_type */ 15240 switch (old->stack[spi].slot_type[BPF_REG_SIZE - 1]) { 15241 case STACK_SPILL: 15242 /* when explored and current stack slot are both storing 15243 * spilled registers, check that stored pointers types 15244 * are the same as well. 15245 * Ex: explored safe path could have stored 15246 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -8} 15247 * but current path has stored: 15248 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -16} 15249 * such verifier states are not equivalent. 15250 * return false to continue verification of this path 15251 */ 15252 if (!regsafe(env, &old->stack[spi].spilled_ptr, 15253 &cur->stack[spi].spilled_ptr, idmap)) 15254 return false; 15255 break; 15256 case STACK_DYNPTR: 15257 old_reg = &old->stack[spi].spilled_ptr; 15258 cur_reg = &cur->stack[spi].spilled_ptr; 15259 if (old_reg->dynptr.type != cur_reg->dynptr.type || 15260 old_reg->dynptr.first_slot != cur_reg->dynptr.first_slot || 15261 !check_ids(old_reg->ref_obj_id, cur_reg->ref_obj_id, idmap)) 15262 return false; 15263 break; 15264 case STACK_ITER: 15265 old_reg = &old->stack[spi].spilled_ptr; 15266 cur_reg = &cur->stack[spi].spilled_ptr; 15267 /* iter.depth is not compared between states as it 15268 * doesn't matter for correctness and would otherwise 15269 * prevent convergence; we maintain it only to prevent 15270 * infinite loop check triggering, see 15271 * iter_active_depths_differ() 15272 */ 15273 if (old_reg->iter.btf != cur_reg->iter.btf || 15274 old_reg->iter.btf_id != cur_reg->iter.btf_id || 15275 old_reg->iter.state != cur_reg->iter.state || 15276 /* ignore {old_reg,cur_reg}->iter.depth, see above */ 15277 !check_ids(old_reg->ref_obj_id, cur_reg->ref_obj_id, idmap)) 15278 return false; 15279 break; 15280 case STACK_MISC: 15281 case STACK_ZERO: 15282 case STACK_INVALID: 15283 continue; 15284 /* Ensure that new unhandled slot types return false by default */ 15285 default: 15286 return false; 15287 } 15288 } 15289 return true; 15290 } 15291 15292 static bool refsafe(struct bpf_func_state *old, struct bpf_func_state *cur, 15293 struct bpf_id_pair *idmap) 15294 { 15295 int i; 15296 15297 if (old->acquired_refs != cur->acquired_refs) 15298 return false; 15299 15300 for (i = 0; i < old->acquired_refs; i++) { 15301 if (!check_ids(old->refs[i].id, cur->refs[i].id, idmap)) 15302 return false; 15303 } 15304 15305 return true; 15306 } 15307 15308 /* compare two verifier states 15309 * 15310 * all states stored in state_list are known to be valid, since 15311 * verifier reached 'bpf_exit' instruction through them 15312 * 15313 * this function is called when verifier exploring different branches of 15314 * execution popped from the state stack. If it sees an old state that has 15315 * more strict register state and more strict stack state then this execution 15316 * branch doesn't need to be explored further, since verifier already 15317 * concluded that more strict state leads to valid finish. 15318 * 15319 * Therefore two states are equivalent if register state is more conservative 15320 * and explored stack state is more conservative than the current one. 15321 * Example: 15322 * explored current 15323 * (slot1=INV slot2=MISC) == (slot1=MISC slot2=MISC) 15324 * (slot1=MISC slot2=MISC) != (slot1=INV slot2=MISC) 15325 * 15326 * In other words if current stack state (one being explored) has more 15327 * valid slots than old one that already passed validation, it means 15328 * the verifier can stop exploring and conclude that current state is valid too 15329 * 15330 * Similarly with registers. If explored state has register type as invalid 15331 * whereas register type in current state is meaningful, it means that 15332 * the current state will reach 'bpf_exit' instruction safely 15333 */ 15334 static bool func_states_equal(struct bpf_verifier_env *env, struct bpf_func_state *old, 15335 struct bpf_func_state *cur) 15336 { 15337 int i; 15338 15339 for (i = 0; i < MAX_BPF_REG; i++) 15340 if (!regsafe(env, &old->regs[i], &cur->regs[i], 15341 env->idmap_scratch)) 15342 return false; 15343 15344 if (!stacksafe(env, old, cur, env->idmap_scratch)) 15345 return false; 15346 15347 if (!refsafe(old, cur, env->idmap_scratch)) 15348 return false; 15349 15350 return true; 15351 } 15352 15353 static bool states_equal(struct bpf_verifier_env *env, 15354 struct bpf_verifier_state *old, 15355 struct bpf_verifier_state *cur) 15356 { 15357 int i; 15358 15359 if (old->curframe != cur->curframe) 15360 return false; 15361 15362 memset(env->idmap_scratch, 0, sizeof(env->idmap_scratch)); 15363 15364 /* Verification state from speculative execution simulation 15365 * must never prune a non-speculative execution one. 15366 */ 15367 if (old->speculative && !cur->speculative) 15368 return false; 15369 15370 if (old->active_lock.ptr != cur->active_lock.ptr) 15371 return false; 15372 15373 /* Old and cur active_lock's have to be either both present 15374 * or both absent. 15375 */ 15376 if (!!old->active_lock.id != !!cur->active_lock.id) 15377 return false; 15378 15379 if (old->active_lock.id && 15380 !check_ids(old->active_lock.id, cur->active_lock.id, env->idmap_scratch)) 15381 return false; 15382 15383 if (old->active_rcu_lock != cur->active_rcu_lock) 15384 return false; 15385 15386 /* for states to be equal callsites have to be the same 15387 * and all frame states need to be equivalent 15388 */ 15389 for (i = 0; i <= old->curframe; i++) { 15390 if (old->frame[i]->callsite != cur->frame[i]->callsite) 15391 return false; 15392 if (!func_states_equal(env, old->frame[i], cur->frame[i])) 15393 return false; 15394 } 15395 return true; 15396 } 15397 15398 /* Return 0 if no propagation happened. Return negative error code if error 15399 * happened. Otherwise, return the propagated bit. 15400 */ 15401 static int propagate_liveness_reg(struct bpf_verifier_env *env, 15402 struct bpf_reg_state *reg, 15403 struct bpf_reg_state *parent_reg) 15404 { 15405 u8 parent_flag = parent_reg->live & REG_LIVE_READ; 15406 u8 flag = reg->live & REG_LIVE_READ; 15407 int err; 15408 15409 /* When comes here, read flags of PARENT_REG or REG could be any of 15410 * REG_LIVE_READ64, REG_LIVE_READ32, REG_LIVE_NONE. There is no need 15411 * of propagation if PARENT_REG has strongest REG_LIVE_READ64. 15412 */ 15413 if (parent_flag == REG_LIVE_READ64 || 15414 /* Or if there is no read flag from REG. */ 15415 !flag || 15416 /* Or if the read flag from REG is the same as PARENT_REG. */ 15417 parent_flag == flag) 15418 return 0; 15419 15420 err = mark_reg_read(env, reg, parent_reg, flag); 15421 if (err) 15422 return err; 15423 15424 return flag; 15425 } 15426 15427 /* A write screens off any subsequent reads; but write marks come from the 15428 * straight-line code between a state and its parent. When we arrive at an 15429 * equivalent state (jump target or such) we didn't arrive by the straight-line 15430 * code, so read marks in the state must propagate to the parent regardless 15431 * of the state's write marks. That's what 'parent == state->parent' comparison 15432 * in mark_reg_read() is for. 15433 */ 15434 static int propagate_liveness(struct bpf_verifier_env *env, 15435 const struct bpf_verifier_state *vstate, 15436 struct bpf_verifier_state *vparent) 15437 { 15438 struct bpf_reg_state *state_reg, *parent_reg; 15439 struct bpf_func_state *state, *parent; 15440 int i, frame, err = 0; 15441 15442 if (vparent->curframe != vstate->curframe) { 15443 WARN(1, "propagate_live: parent frame %d current frame %d\n", 15444 vparent->curframe, vstate->curframe); 15445 return -EFAULT; 15446 } 15447 /* Propagate read liveness of registers... */ 15448 BUILD_BUG_ON(BPF_REG_FP + 1 != MAX_BPF_REG); 15449 for (frame = 0; frame <= vstate->curframe; frame++) { 15450 parent = vparent->frame[frame]; 15451 state = vstate->frame[frame]; 15452 parent_reg = parent->regs; 15453 state_reg = state->regs; 15454 /* We don't need to worry about FP liveness, it's read-only */ 15455 for (i = frame < vstate->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++) { 15456 err = propagate_liveness_reg(env, &state_reg[i], 15457 &parent_reg[i]); 15458 if (err < 0) 15459 return err; 15460 if (err == REG_LIVE_READ64) 15461 mark_insn_zext(env, &parent_reg[i]); 15462 } 15463 15464 /* Propagate stack slots. */ 15465 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE && 15466 i < parent->allocated_stack / BPF_REG_SIZE; i++) { 15467 parent_reg = &parent->stack[i].spilled_ptr; 15468 state_reg = &state->stack[i].spilled_ptr; 15469 err = propagate_liveness_reg(env, state_reg, 15470 parent_reg); 15471 if (err < 0) 15472 return err; 15473 } 15474 } 15475 return 0; 15476 } 15477 15478 /* find precise scalars in the previous equivalent state and 15479 * propagate them into the current state 15480 */ 15481 static int propagate_precision(struct bpf_verifier_env *env, 15482 const struct bpf_verifier_state *old) 15483 { 15484 struct bpf_reg_state *state_reg; 15485 struct bpf_func_state *state; 15486 int i, err = 0, fr; 15487 bool first; 15488 15489 for (fr = old->curframe; fr >= 0; fr--) { 15490 state = old->frame[fr]; 15491 state_reg = state->regs; 15492 first = true; 15493 for (i = 0; i < BPF_REG_FP; i++, state_reg++) { 15494 if (state_reg->type != SCALAR_VALUE || 15495 !state_reg->precise || 15496 !(state_reg->live & REG_LIVE_READ)) 15497 continue; 15498 if (env->log.level & BPF_LOG_LEVEL2) { 15499 if (first) 15500 verbose(env, "frame %d: propagating r%d", fr, i); 15501 else 15502 verbose(env, ",r%d", i); 15503 } 15504 bt_set_frame_reg(&env->bt, fr, i); 15505 first = false; 15506 } 15507 15508 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) { 15509 if (!is_spilled_reg(&state->stack[i])) 15510 continue; 15511 state_reg = &state->stack[i].spilled_ptr; 15512 if (state_reg->type != SCALAR_VALUE || 15513 !state_reg->precise || 15514 !(state_reg->live & REG_LIVE_READ)) 15515 continue; 15516 if (env->log.level & BPF_LOG_LEVEL2) { 15517 if (first) 15518 verbose(env, "frame %d: propagating fp%d", 15519 fr, (-i - 1) * BPF_REG_SIZE); 15520 else 15521 verbose(env, ",fp%d", (-i - 1) * BPF_REG_SIZE); 15522 } 15523 bt_set_frame_slot(&env->bt, fr, i); 15524 first = false; 15525 } 15526 if (!first) 15527 verbose(env, "\n"); 15528 } 15529 15530 err = mark_chain_precision_batch(env); 15531 if (err < 0) 15532 return err; 15533 15534 return 0; 15535 } 15536 15537 static bool states_maybe_looping(struct bpf_verifier_state *old, 15538 struct bpf_verifier_state *cur) 15539 { 15540 struct bpf_func_state *fold, *fcur; 15541 int i, fr = cur->curframe; 15542 15543 if (old->curframe != fr) 15544 return false; 15545 15546 fold = old->frame[fr]; 15547 fcur = cur->frame[fr]; 15548 for (i = 0; i < MAX_BPF_REG; i++) 15549 if (memcmp(&fold->regs[i], &fcur->regs[i], 15550 offsetof(struct bpf_reg_state, parent))) 15551 return false; 15552 return true; 15553 } 15554 15555 static bool is_iter_next_insn(struct bpf_verifier_env *env, int insn_idx) 15556 { 15557 return env->insn_aux_data[insn_idx].is_iter_next; 15558 } 15559 15560 /* is_state_visited() handles iter_next() (see process_iter_next_call() for 15561 * terminology) calls specially: as opposed to bounded BPF loops, it *expects* 15562 * states to match, which otherwise would look like an infinite loop. So while 15563 * iter_next() calls are taken care of, we still need to be careful and 15564 * prevent erroneous and too eager declaration of "ininite loop", when 15565 * iterators are involved. 15566 * 15567 * Here's a situation in pseudo-BPF assembly form: 15568 * 15569 * 0: again: ; set up iter_next() call args 15570 * 1: r1 = &it ; <CHECKPOINT HERE> 15571 * 2: call bpf_iter_num_next ; this is iter_next() call 15572 * 3: if r0 == 0 goto done 15573 * 4: ... something useful here ... 15574 * 5: goto again ; another iteration 15575 * 6: done: 15576 * 7: r1 = &it 15577 * 8: call bpf_iter_num_destroy ; clean up iter state 15578 * 9: exit 15579 * 15580 * This is a typical loop. Let's assume that we have a prune point at 1:, 15581 * before we get to `call bpf_iter_num_next` (e.g., because of that `goto 15582 * again`, assuming other heuristics don't get in a way). 15583 * 15584 * When we first time come to 1:, let's say we have some state X. We proceed 15585 * to 2:, fork states, enqueue ACTIVE, validate NULL case successfully, exit. 15586 * Now we come back to validate that forked ACTIVE state. We proceed through 15587 * 3-5, come to goto, jump to 1:. Let's assume our state didn't change, so we 15588 * are converging. But the problem is that we don't know that yet, as this 15589 * convergence has to happen at iter_next() call site only. So if nothing is 15590 * done, at 1: verifier will use bounded loop logic and declare infinite 15591 * looping (and would be *technically* correct, if not for iterator's 15592 * "eventual sticky NULL" contract, see process_iter_next_call()). But we 15593 * don't want that. So what we do in process_iter_next_call() when we go on 15594 * another ACTIVE iteration, we bump slot->iter.depth, to mark that it's 15595 * a different iteration. So when we suspect an infinite loop, we additionally 15596 * check if any of the *ACTIVE* iterator states depths differ. If yes, we 15597 * pretend we are not looping and wait for next iter_next() call. 15598 * 15599 * This only applies to ACTIVE state. In DRAINED state we don't expect to 15600 * loop, because that would actually mean infinite loop, as DRAINED state is 15601 * "sticky", and so we'll keep returning into the same instruction with the 15602 * same state (at least in one of possible code paths). 15603 * 15604 * This approach allows to keep infinite loop heuristic even in the face of 15605 * active iterator. E.g., C snippet below is and will be detected as 15606 * inifintely looping: 15607 * 15608 * struct bpf_iter_num it; 15609 * int *p, x; 15610 * 15611 * bpf_iter_num_new(&it, 0, 10); 15612 * while ((p = bpf_iter_num_next(&t))) { 15613 * x = p; 15614 * while (x--) {} // <<-- infinite loop here 15615 * } 15616 * 15617 */ 15618 static bool iter_active_depths_differ(struct bpf_verifier_state *old, struct bpf_verifier_state *cur) 15619 { 15620 struct bpf_reg_state *slot, *cur_slot; 15621 struct bpf_func_state *state; 15622 int i, fr; 15623 15624 for (fr = old->curframe; fr >= 0; fr--) { 15625 state = old->frame[fr]; 15626 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) { 15627 if (state->stack[i].slot_type[0] != STACK_ITER) 15628 continue; 15629 15630 slot = &state->stack[i].spilled_ptr; 15631 if (slot->iter.state != BPF_ITER_STATE_ACTIVE) 15632 continue; 15633 15634 cur_slot = &cur->frame[fr]->stack[i].spilled_ptr; 15635 if (cur_slot->iter.depth != slot->iter.depth) 15636 return true; 15637 } 15638 } 15639 return false; 15640 } 15641 15642 static int is_state_visited(struct bpf_verifier_env *env, int insn_idx) 15643 { 15644 struct bpf_verifier_state_list *new_sl; 15645 struct bpf_verifier_state_list *sl, **pprev; 15646 struct bpf_verifier_state *cur = env->cur_state, *new; 15647 int i, j, err, states_cnt = 0; 15648 bool force_new_state = env->test_state_freq || is_force_checkpoint(env, insn_idx); 15649 bool add_new_state = force_new_state; 15650 15651 /* bpf progs typically have pruning point every 4 instructions 15652 * http://vger.kernel.org/bpfconf2019.html#session-1 15653 * Do not add new state for future pruning if the verifier hasn't seen 15654 * at least 2 jumps and at least 8 instructions. 15655 * This heuristics helps decrease 'total_states' and 'peak_states' metric. 15656 * In tests that amounts to up to 50% reduction into total verifier 15657 * memory consumption and 20% verifier time speedup. 15658 */ 15659 if (env->jmps_processed - env->prev_jmps_processed >= 2 && 15660 env->insn_processed - env->prev_insn_processed >= 8) 15661 add_new_state = true; 15662 15663 pprev = explored_state(env, insn_idx); 15664 sl = *pprev; 15665 15666 clean_live_states(env, insn_idx, cur); 15667 15668 while (sl) { 15669 states_cnt++; 15670 if (sl->state.insn_idx != insn_idx) 15671 goto next; 15672 15673 if (sl->state.branches) { 15674 struct bpf_func_state *frame = sl->state.frame[sl->state.curframe]; 15675 15676 if (frame->in_async_callback_fn && 15677 frame->async_entry_cnt != cur->frame[cur->curframe]->async_entry_cnt) { 15678 /* Different async_entry_cnt means that the verifier is 15679 * processing another entry into async callback. 15680 * Seeing the same state is not an indication of infinite 15681 * loop or infinite recursion. 15682 * But finding the same state doesn't mean that it's safe 15683 * to stop processing the current state. The previous state 15684 * hasn't yet reached bpf_exit, since state.branches > 0. 15685 * Checking in_async_callback_fn alone is not enough either. 15686 * Since the verifier still needs to catch infinite loops 15687 * inside async callbacks. 15688 */ 15689 goto skip_inf_loop_check; 15690 } 15691 /* BPF open-coded iterators loop detection is special. 15692 * states_maybe_looping() logic is too simplistic in detecting 15693 * states that *might* be equivalent, because it doesn't know 15694 * about ID remapping, so don't even perform it. 15695 * See process_iter_next_call() and iter_active_depths_differ() 15696 * for overview of the logic. When current and one of parent 15697 * states are detected as equivalent, it's a good thing: we prove 15698 * convergence and can stop simulating further iterations. 15699 * It's safe to assume that iterator loop will finish, taking into 15700 * account iter_next() contract of eventually returning 15701 * sticky NULL result. 15702 */ 15703 if (is_iter_next_insn(env, insn_idx)) { 15704 if (states_equal(env, &sl->state, cur)) { 15705 struct bpf_func_state *cur_frame; 15706 struct bpf_reg_state *iter_state, *iter_reg; 15707 int spi; 15708 15709 cur_frame = cur->frame[cur->curframe]; 15710 /* btf_check_iter_kfuncs() enforces that 15711 * iter state pointer is always the first arg 15712 */ 15713 iter_reg = &cur_frame->regs[BPF_REG_1]; 15714 /* current state is valid due to states_equal(), 15715 * so we can assume valid iter and reg state, 15716 * no need for extra (re-)validations 15717 */ 15718 spi = __get_spi(iter_reg->off + iter_reg->var_off.value); 15719 iter_state = &func(env, iter_reg)->stack[spi].spilled_ptr; 15720 if (iter_state->iter.state == BPF_ITER_STATE_ACTIVE) 15721 goto hit; 15722 } 15723 goto skip_inf_loop_check; 15724 } 15725 /* attempt to detect infinite loop to avoid unnecessary doomed work */ 15726 if (states_maybe_looping(&sl->state, cur) && 15727 states_equal(env, &sl->state, cur) && 15728 !iter_active_depths_differ(&sl->state, cur)) { 15729 verbose_linfo(env, insn_idx, "; "); 15730 verbose(env, "infinite loop detected at insn %d\n", insn_idx); 15731 return -EINVAL; 15732 } 15733 /* if the verifier is processing a loop, avoid adding new state 15734 * too often, since different loop iterations have distinct 15735 * states and may not help future pruning. 15736 * This threshold shouldn't be too low to make sure that 15737 * a loop with large bound will be rejected quickly. 15738 * The most abusive loop will be: 15739 * r1 += 1 15740 * if r1 < 1000000 goto pc-2 15741 * 1M insn_procssed limit / 100 == 10k peak states. 15742 * This threshold shouldn't be too high either, since states 15743 * at the end of the loop are likely to be useful in pruning. 15744 */ 15745 skip_inf_loop_check: 15746 if (!force_new_state && 15747 env->jmps_processed - env->prev_jmps_processed < 20 && 15748 env->insn_processed - env->prev_insn_processed < 100) 15749 add_new_state = false; 15750 goto miss; 15751 } 15752 if (states_equal(env, &sl->state, cur)) { 15753 hit: 15754 sl->hit_cnt++; 15755 /* reached equivalent register/stack state, 15756 * prune the search. 15757 * Registers read by the continuation are read by us. 15758 * If we have any write marks in env->cur_state, they 15759 * will prevent corresponding reads in the continuation 15760 * from reaching our parent (an explored_state). Our 15761 * own state will get the read marks recorded, but 15762 * they'll be immediately forgotten as we're pruning 15763 * this state and will pop a new one. 15764 */ 15765 err = propagate_liveness(env, &sl->state, cur); 15766 15767 /* if previous state reached the exit with precision and 15768 * current state is equivalent to it (except precsion marks) 15769 * the precision needs to be propagated back in 15770 * the current state. 15771 */ 15772 err = err ? : push_jmp_history(env, cur); 15773 err = err ? : propagate_precision(env, &sl->state); 15774 if (err) 15775 return err; 15776 return 1; 15777 } 15778 miss: 15779 /* when new state is not going to be added do not increase miss count. 15780 * Otherwise several loop iterations will remove the state 15781 * recorded earlier. The goal of these heuristics is to have 15782 * states from some iterations of the loop (some in the beginning 15783 * and some at the end) to help pruning. 15784 */ 15785 if (add_new_state) 15786 sl->miss_cnt++; 15787 /* heuristic to determine whether this state is beneficial 15788 * to keep checking from state equivalence point of view. 15789 * Higher numbers increase max_states_per_insn and verification time, 15790 * but do not meaningfully decrease insn_processed. 15791 */ 15792 if (sl->miss_cnt > sl->hit_cnt * 3 + 3) { 15793 /* the state is unlikely to be useful. Remove it to 15794 * speed up verification 15795 */ 15796 *pprev = sl->next; 15797 if (sl->state.frame[0]->regs[0].live & REG_LIVE_DONE) { 15798 u32 br = sl->state.branches; 15799 15800 WARN_ONCE(br, 15801 "BUG live_done but branches_to_explore %d\n", 15802 br); 15803 free_verifier_state(&sl->state, false); 15804 kfree(sl); 15805 env->peak_states--; 15806 } else { 15807 /* cannot free this state, since parentage chain may 15808 * walk it later. Add it for free_list instead to 15809 * be freed at the end of verification 15810 */ 15811 sl->next = env->free_list; 15812 env->free_list = sl; 15813 } 15814 sl = *pprev; 15815 continue; 15816 } 15817 next: 15818 pprev = &sl->next; 15819 sl = *pprev; 15820 } 15821 15822 if (env->max_states_per_insn < states_cnt) 15823 env->max_states_per_insn = states_cnt; 15824 15825 if (!env->bpf_capable && states_cnt > BPF_COMPLEXITY_LIMIT_STATES) 15826 return 0; 15827 15828 if (!add_new_state) 15829 return 0; 15830 15831 /* There were no equivalent states, remember the current one. 15832 * Technically the current state is not proven to be safe yet, 15833 * but it will either reach outer most bpf_exit (which means it's safe) 15834 * or it will be rejected. When there are no loops the verifier won't be 15835 * seeing this tuple (frame[0].callsite, frame[1].callsite, .. insn_idx) 15836 * again on the way to bpf_exit. 15837 * When looping the sl->state.branches will be > 0 and this state 15838 * will not be considered for equivalence until branches == 0. 15839 */ 15840 new_sl = kzalloc(sizeof(struct bpf_verifier_state_list), GFP_KERNEL); 15841 if (!new_sl) 15842 return -ENOMEM; 15843 env->total_states++; 15844 env->peak_states++; 15845 env->prev_jmps_processed = env->jmps_processed; 15846 env->prev_insn_processed = env->insn_processed; 15847 15848 /* forget precise markings we inherited, see __mark_chain_precision */ 15849 if (env->bpf_capable) 15850 mark_all_scalars_imprecise(env, cur); 15851 15852 /* add new state to the head of linked list */ 15853 new = &new_sl->state; 15854 err = copy_verifier_state(new, cur); 15855 if (err) { 15856 free_verifier_state(new, false); 15857 kfree(new_sl); 15858 return err; 15859 } 15860 new->insn_idx = insn_idx; 15861 WARN_ONCE(new->branches != 1, 15862 "BUG is_state_visited:branches_to_explore=%d insn %d\n", new->branches, insn_idx); 15863 15864 cur->parent = new; 15865 cur->first_insn_idx = insn_idx; 15866 clear_jmp_history(cur); 15867 new_sl->next = *explored_state(env, insn_idx); 15868 *explored_state(env, insn_idx) = new_sl; 15869 /* connect new state to parentage chain. Current frame needs all 15870 * registers connected. Only r6 - r9 of the callers are alive (pushed 15871 * to the stack implicitly by JITs) so in callers' frames connect just 15872 * r6 - r9 as an optimization. Callers will have r1 - r5 connected to 15873 * the state of the call instruction (with WRITTEN set), and r0 comes 15874 * from callee with its full parentage chain, anyway. 15875 */ 15876 /* clear write marks in current state: the writes we did are not writes 15877 * our child did, so they don't screen off its reads from us. 15878 * (There are no read marks in current state, because reads always mark 15879 * their parent and current state never has children yet. Only 15880 * explored_states can get read marks.) 15881 */ 15882 for (j = 0; j <= cur->curframe; j++) { 15883 for (i = j < cur->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++) 15884 cur->frame[j]->regs[i].parent = &new->frame[j]->regs[i]; 15885 for (i = 0; i < BPF_REG_FP; i++) 15886 cur->frame[j]->regs[i].live = REG_LIVE_NONE; 15887 } 15888 15889 /* all stack frames are accessible from callee, clear them all */ 15890 for (j = 0; j <= cur->curframe; j++) { 15891 struct bpf_func_state *frame = cur->frame[j]; 15892 struct bpf_func_state *newframe = new->frame[j]; 15893 15894 for (i = 0; i < frame->allocated_stack / BPF_REG_SIZE; i++) { 15895 frame->stack[i].spilled_ptr.live = REG_LIVE_NONE; 15896 frame->stack[i].spilled_ptr.parent = 15897 &newframe->stack[i].spilled_ptr; 15898 } 15899 } 15900 return 0; 15901 } 15902 15903 /* Return true if it's OK to have the same insn return a different type. */ 15904 static bool reg_type_mismatch_ok(enum bpf_reg_type type) 15905 { 15906 switch (base_type(type)) { 15907 case PTR_TO_CTX: 15908 case PTR_TO_SOCKET: 15909 case PTR_TO_SOCK_COMMON: 15910 case PTR_TO_TCP_SOCK: 15911 case PTR_TO_XDP_SOCK: 15912 case PTR_TO_BTF_ID: 15913 return false; 15914 default: 15915 return true; 15916 } 15917 } 15918 15919 /* If an instruction was previously used with particular pointer types, then we 15920 * need to be careful to avoid cases such as the below, where it may be ok 15921 * for one branch accessing the pointer, but not ok for the other branch: 15922 * 15923 * R1 = sock_ptr 15924 * goto X; 15925 * ... 15926 * R1 = some_other_valid_ptr; 15927 * goto X; 15928 * ... 15929 * R2 = *(u32 *)(R1 + 0); 15930 */ 15931 static bool reg_type_mismatch(enum bpf_reg_type src, enum bpf_reg_type prev) 15932 { 15933 return src != prev && (!reg_type_mismatch_ok(src) || 15934 !reg_type_mismatch_ok(prev)); 15935 } 15936 15937 static int save_aux_ptr_type(struct bpf_verifier_env *env, enum bpf_reg_type type, 15938 bool allow_trust_missmatch) 15939 { 15940 enum bpf_reg_type *prev_type = &env->insn_aux_data[env->insn_idx].ptr_type; 15941 15942 if (*prev_type == NOT_INIT) { 15943 /* Saw a valid insn 15944 * dst_reg = *(u32 *)(src_reg + off) 15945 * save type to validate intersecting paths 15946 */ 15947 *prev_type = type; 15948 } else if (reg_type_mismatch(type, *prev_type)) { 15949 /* Abuser program is trying to use the same insn 15950 * dst_reg = *(u32*) (src_reg + off) 15951 * with different pointer types: 15952 * src_reg == ctx in one branch and 15953 * src_reg == stack|map in some other branch. 15954 * Reject it. 15955 */ 15956 if (allow_trust_missmatch && 15957 base_type(type) == PTR_TO_BTF_ID && 15958 base_type(*prev_type) == PTR_TO_BTF_ID) { 15959 /* 15960 * Have to support a use case when one path through 15961 * the program yields TRUSTED pointer while another 15962 * is UNTRUSTED. Fallback to UNTRUSTED to generate 15963 * BPF_PROBE_MEM. 15964 */ 15965 *prev_type = PTR_TO_BTF_ID | PTR_UNTRUSTED; 15966 } else { 15967 verbose(env, "same insn cannot be used with different pointers\n"); 15968 return -EINVAL; 15969 } 15970 } 15971 15972 return 0; 15973 } 15974 15975 static int do_check(struct bpf_verifier_env *env) 15976 { 15977 bool pop_log = !(env->log.level & BPF_LOG_LEVEL2); 15978 struct bpf_verifier_state *state = env->cur_state; 15979 struct bpf_insn *insns = env->prog->insnsi; 15980 struct bpf_reg_state *regs; 15981 int insn_cnt = env->prog->len; 15982 bool do_print_state = false; 15983 int prev_insn_idx = -1; 15984 15985 for (;;) { 15986 struct bpf_insn *insn; 15987 u8 class; 15988 int err; 15989 15990 env->prev_insn_idx = prev_insn_idx; 15991 if (env->insn_idx >= insn_cnt) { 15992 verbose(env, "invalid insn idx %d insn_cnt %d\n", 15993 env->insn_idx, insn_cnt); 15994 return -EFAULT; 15995 } 15996 15997 insn = &insns[env->insn_idx]; 15998 class = BPF_CLASS(insn->code); 15999 16000 if (++env->insn_processed > BPF_COMPLEXITY_LIMIT_INSNS) { 16001 verbose(env, 16002 "BPF program is too large. Processed %d insn\n", 16003 env->insn_processed); 16004 return -E2BIG; 16005 } 16006 16007 state->last_insn_idx = env->prev_insn_idx; 16008 16009 if (is_prune_point(env, env->insn_idx)) { 16010 err = is_state_visited(env, env->insn_idx); 16011 if (err < 0) 16012 return err; 16013 if (err == 1) { 16014 /* found equivalent state, can prune the search */ 16015 if (env->log.level & BPF_LOG_LEVEL) { 16016 if (do_print_state) 16017 verbose(env, "\nfrom %d to %d%s: safe\n", 16018 env->prev_insn_idx, env->insn_idx, 16019 env->cur_state->speculative ? 16020 " (speculative execution)" : ""); 16021 else 16022 verbose(env, "%d: safe\n", env->insn_idx); 16023 } 16024 goto process_bpf_exit; 16025 } 16026 } 16027 16028 if (is_jmp_point(env, env->insn_idx)) { 16029 err = push_jmp_history(env, state); 16030 if (err) 16031 return err; 16032 } 16033 16034 if (signal_pending(current)) 16035 return -EAGAIN; 16036 16037 if (need_resched()) 16038 cond_resched(); 16039 16040 if (env->log.level & BPF_LOG_LEVEL2 && do_print_state) { 16041 verbose(env, "\nfrom %d to %d%s:", 16042 env->prev_insn_idx, env->insn_idx, 16043 env->cur_state->speculative ? 16044 " (speculative execution)" : ""); 16045 print_verifier_state(env, state->frame[state->curframe], true); 16046 do_print_state = false; 16047 } 16048 16049 if (env->log.level & BPF_LOG_LEVEL) { 16050 const struct bpf_insn_cbs cbs = { 16051 .cb_call = disasm_kfunc_name, 16052 .cb_print = verbose, 16053 .private_data = env, 16054 }; 16055 16056 if (verifier_state_scratched(env)) 16057 print_insn_state(env, state->frame[state->curframe]); 16058 16059 verbose_linfo(env, env->insn_idx, "; "); 16060 env->prev_log_pos = env->log.end_pos; 16061 verbose(env, "%d: ", env->insn_idx); 16062 print_bpf_insn(&cbs, insn, env->allow_ptr_leaks); 16063 env->prev_insn_print_pos = env->log.end_pos - env->prev_log_pos; 16064 env->prev_log_pos = env->log.end_pos; 16065 } 16066 16067 if (bpf_prog_is_offloaded(env->prog->aux)) { 16068 err = bpf_prog_offload_verify_insn(env, env->insn_idx, 16069 env->prev_insn_idx); 16070 if (err) 16071 return err; 16072 } 16073 16074 regs = cur_regs(env); 16075 sanitize_mark_insn_seen(env); 16076 prev_insn_idx = env->insn_idx; 16077 16078 if (class == BPF_ALU || class == BPF_ALU64) { 16079 err = check_alu_op(env, insn); 16080 if (err) 16081 return err; 16082 16083 } else if (class == BPF_LDX) { 16084 enum bpf_reg_type src_reg_type; 16085 16086 /* check for reserved fields is already done */ 16087 16088 /* check src operand */ 16089 err = check_reg_arg(env, insn->src_reg, SRC_OP); 16090 if (err) 16091 return err; 16092 16093 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK); 16094 if (err) 16095 return err; 16096 16097 src_reg_type = regs[insn->src_reg].type; 16098 16099 /* check that memory (src_reg + off) is readable, 16100 * the state of dst_reg will be updated by this func 16101 */ 16102 err = check_mem_access(env, env->insn_idx, insn->src_reg, 16103 insn->off, BPF_SIZE(insn->code), 16104 BPF_READ, insn->dst_reg, false); 16105 if (err) 16106 return err; 16107 16108 err = save_aux_ptr_type(env, src_reg_type, true); 16109 if (err) 16110 return err; 16111 } else if (class == BPF_STX) { 16112 enum bpf_reg_type dst_reg_type; 16113 16114 if (BPF_MODE(insn->code) == BPF_ATOMIC) { 16115 err = check_atomic(env, env->insn_idx, insn); 16116 if (err) 16117 return err; 16118 env->insn_idx++; 16119 continue; 16120 } 16121 16122 if (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0) { 16123 verbose(env, "BPF_STX uses reserved fields\n"); 16124 return -EINVAL; 16125 } 16126 16127 /* check src1 operand */ 16128 err = check_reg_arg(env, insn->src_reg, SRC_OP); 16129 if (err) 16130 return err; 16131 /* check src2 operand */ 16132 err = check_reg_arg(env, insn->dst_reg, SRC_OP); 16133 if (err) 16134 return err; 16135 16136 dst_reg_type = regs[insn->dst_reg].type; 16137 16138 /* check that memory (dst_reg + off) is writeable */ 16139 err = check_mem_access(env, env->insn_idx, insn->dst_reg, 16140 insn->off, BPF_SIZE(insn->code), 16141 BPF_WRITE, insn->src_reg, false); 16142 if (err) 16143 return err; 16144 16145 err = save_aux_ptr_type(env, dst_reg_type, false); 16146 if (err) 16147 return err; 16148 } else if (class == BPF_ST) { 16149 enum bpf_reg_type dst_reg_type; 16150 16151 if (BPF_MODE(insn->code) != BPF_MEM || 16152 insn->src_reg != BPF_REG_0) { 16153 verbose(env, "BPF_ST uses reserved fields\n"); 16154 return -EINVAL; 16155 } 16156 /* check src operand */ 16157 err = check_reg_arg(env, insn->dst_reg, SRC_OP); 16158 if (err) 16159 return err; 16160 16161 dst_reg_type = regs[insn->dst_reg].type; 16162 16163 /* check that memory (dst_reg + off) is writeable */ 16164 err = check_mem_access(env, env->insn_idx, insn->dst_reg, 16165 insn->off, BPF_SIZE(insn->code), 16166 BPF_WRITE, -1, false); 16167 if (err) 16168 return err; 16169 16170 err = save_aux_ptr_type(env, dst_reg_type, false); 16171 if (err) 16172 return err; 16173 } else if (class == BPF_JMP || class == BPF_JMP32) { 16174 u8 opcode = BPF_OP(insn->code); 16175 16176 env->jmps_processed++; 16177 if (opcode == BPF_CALL) { 16178 if (BPF_SRC(insn->code) != BPF_K || 16179 (insn->src_reg != BPF_PSEUDO_KFUNC_CALL 16180 && insn->off != 0) || 16181 (insn->src_reg != BPF_REG_0 && 16182 insn->src_reg != BPF_PSEUDO_CALL && 16183 insn->src_reg != BPF_PSEUDO_KFUNC_CALL) || 16184 insn->dst_reg != BPF_REG_0 || 16185 class == BPF_JMP32) { 16186 verbose(env, "BPF_CALL uses reserved fields\n"); 16187 return -EINVAL; 16188 } 16189 16190 if (env->cur_state->active_lock.ptr) { 16191 if ((insn->src_reg == BPF_REG_0 && insn->imm != BPF_FUNC_spin_unlock) || 16192 (insn->src_reg == BPF_PSEUDO_CALL) || 16193 (insn->src_reg == BPF_PSEUDO_KFUNC_CALL && 16194 (insn->off != 0 || !is_bpf_graph_api_kfunc(insn->imm)))) { 16195 verbose(env, "function calls are not allowed while holding a lock\n"); 16196 return -EINVAL; 16197 } 16198 } 16199 if (insn->src_reg == BPF_PSEUDO_CALL) 16200 err = check_func_call(env, insn, &env->insn_idx); 16201 else if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) 16202 err = check_kfunc_call(env, insn, &env->insn_idx); 16203 else 16204 err = check_helper_call(env, insn, &env->insn_idx); 16205 if (err) 16206 return err; 16207 16208 mark_reg_scratched(env, BPF_REG_0); 16209 } else if (opcode == BPF_JA) { 16210 if (BPF_SRC(insn->code) != BPF_K || 16211 insn->imm != 0 || 16212 insn->src_reg != BPF_REG_0 || 16213 insn->dst_reg != BPF_REG_0 || 16214 class == BPF_JMP32) { 16215 verbose(env, "BPF_JA uses reserved fields\n"); 16216 return -EINVAL; 16217 } 16218 16219 env->insn_idx += insn->off + 1; 16220 continue; 16221 16222 } else if (opcode == BPF_EXIT) { 16223 if (BPF_SRC(insn->code) != BPF_K || 16224 insn->imm != 0 || 16225 insn->src_reg != BPF_REG_0 || 16226 insn->dst_reg != BPF_REG_0 || 16227 class == BPF_JMP32) { 16228 verbose(env, "BPF_EXIT uses reserved fields\n"); 16229 return -EINVAL; 16230 } 16231 16232 if (env->cur_state->active_lock.ptr && 16233 !in_rbtree_lock_required_cb(env)) { 16234 verbose(env, "bpf_spin_unlock is missing\n"); 16235 return -EINVAL; 16236 } 16237 16238 if (env->cur_state->active_rcu_lock) { 16239 verbose(env, "bpf_rcu_read_unlock is missing\n"); 16240 return -EINVAL; 16241 } 16242 16243 /* We must do check_reference_leak here before 16244 * prepare_func_exit to handle the case when 16245 * state->curframe > 0, it may be a callback 16246 * function, for which reference_state must 16247 * match caller reference state when it exits. 16248 */ 16249 err = check_reference_leak(env); 16250 if (err) 16251 return err; 16252 16253 if (state->curframe) { 16254 /* exit from nested function */ 16255 err = prepare_func_exit(env, &env->insn_idx); 16256 if (err) 16257 return err; 16258 do_print_state = true; 16259 continue; 16260 } 16261 16262 err = check_return_code(env); 16263 if (err) 16264 return err; 16265 process_bpf_exit: 16266 mark_verifier_state_scratched(env); 16267 update_branch_counts(env, env->cur_state); 16268 err = pop_stack(env, &prev_insn_idx, 16269 &env->insn_idx, pop_log); 16270 if (err < 0) { 16271 if (err != -ENOENT) 16272 return err; 16273 break; 16274 } else { 16275 do_print_state = true; 16276 continue; 16277 } 16278 } else { 16279 err = check_cond_jmp_op(env, insn, &env->insn_idx); 16280 if (err) 16281 return err; 16282 } 16283 } else if (class == BPF_LD) { 16284 u8 mode = BPF_MODE(insn->code); 16285 16286 if (mode == BPF_ABS || mode == BPF_IND) { 16287 err = check_ld_abs(env, insn); 16288 if (err) 16289 return err; 16290 16291 } else if (mode == BPF_IMM) { 16292 err = check_ld_imm(env, insn); 16293 if (err) 16294 return err; 16295 16296 env->insn_idx++; 16297 sanitize_mark_insn_seen(env); 16298 } else { 16299 verbose(env, "invalid BPF_LD mode\n"); 16300 return -EINVAL; 16301 } 16302 } else { 16303 verbose(env, "unknown insn class %d\n", class); 16304 return -EINVAL; 16305 } 16306 16307 env->insn_idx++; 16308 } 16309 16310 return 0; 16311 } 16312 16313 static int find_btf_percpu_datasec(struct btf *btf) 16314 { 16315 const struct btf_type *t; 16316 const char *tname; 16317 int i, n; 16318 16319 /* 16320 * Both vmlinux and module each have their own ".data..percpu" 16321 * DATASECs in BTF. So for module's case, we need to skip vmlinux BTF 16322 * types to look at only module's own BTF types. 16323 */ 16324 n = btf_nr_types(btf); 16325 if (btf_is_module(btf)) 16326 i = btf_nr_types(btf_vmlinux); 16327 else 16328 i = 1; 16329 16330 for(; i < n; i++) { 16331 t = btf_type_by_id(btf, i); 16332 if (BTF_INFO_KIND(t->info) != BTF_KIND_DATASEC) 16333 continue; 16334 16335 tname = btf_name_by_offset(btf, t->name_off); 16336 if (!strcmp(tname, ".data..percpu")) 16337 return i; 16338 } 16339 16340 return -ENOENT; 16341 } 16342 16343 /* replace pseudo btf_id with kernel symbol address */ 16344 static int check_pseudo_btf_id(struct bpf_verifier_env *env, 16345 struct bpf_insn *insn, 16346 struct bpf_insn_aux_data *aux) 16347 { 16348 const struct btf_var_secinfo *vsi; 16349 const struct btf_type *datasec; 16350 struct btf_mod_pair *btf_mod; 16351 const struct btf_type *t; 16352 const char *sym_name; 16353 bool percpu = false; 16354 u32 type, id = insn->imm; 16355 struct btf *btf; 16356 s32 datasec_id; 16357 u64 addr; 16358 int i, btf_fd, err; 16359 16360 btf_fd = insn[1].imm; 16361 if (btf_fd) { 16362 btf = btf_get_by_fd(btf_fd); 16363 if (IS_ERR(btf)) { 16364 verbose(env, "invalid module BTF object FD specified.\n"); 16365 return -EINVAL; 16366 } 16367 } else { 16368 if (!btf_vmlinux) { 16369 verbose(env, "kernel is missing BTF, make sure CONFIG_DEBUG_INFO_BTF=y is specified in Kconfig.\n"); 16370 return -EINVAL; 16371 } 16372 btf = btf_vmlinux; 16373 btf_get(btf); 16374 } 16375 16376 t = btf_type_by_id(btf, id); 16377 if (!t) { 16378 verbose(env, "ldimm64 insn specifies invalid btf_id %d.\n", id); 16379 err = -ENOENT; 16380 goto err_put; 16381 } 16382 16383 if (!btf_type_is_var(t) && !btf_type_is_func(t)) { 16384 verbose(env, "pseudo btf_id %d in ldimm64 isn't KIND_VAR or KIND_FUNC\n", id); 16385 err = -EINVAL; 16386 goto err_put; 16387 } 16388 16389 sym_name = btf_name_by_offset(btf, t->name_off); 16390 addr = kallsyms_lookup_name(sym_name); 16391 if (!addr) { 16392 verbose(env, "ldimm64 failed to find the address for kernel symbol '%s'.\n", 16393 sym_name); 16394 err = -ENOENT; 16395 goto err_put; 16396 } 16397 insn[0].imm = (u32)addr; 16398 insn[1].imm = addr >> 32; 16399 16400 if (btf_type_is_func(t)) { 16401 aux->btf_var.reg_type = PTR_TO_MEM | MEM_RDONLY; 16402 aux->btf_var.mem_size = 0; 16403 goto check_btf; 16404 } 16405 16406 datasec_id = find_btf_percpu_datasec(btf); 16407 if (datasec_id > 0) { 16408 datasec = btf_type_by_id(btf, datasec_id); 16409 for_each_vsi(i, datasec, vsi) { 16410 if (vsi->type == id) { 16411 percpu = true; 16412 break; 16413 } 16414 } 16415 } 16416 16417 type = t->type; 16418 t = btf_type_skip_modifiers(btf, type, NULL); 16419 if (percpu) { 16420 aux->btf_var.reg_type = PTR_TO_BTF_ID | MEM_PERCPU; 16421 aux->btf_var.btf = btf; 16422 aux->btf_var.btf_id = type; 16423 } else if (!btf_type_is_struct(t)) { 16424 const struct btf_type *ret; 16425 const char *tname; 16426 u32 tsize; 16427 16428 /* resolve the type size of ksym. */ 16429 ret = btf_resolve_size(btf, t, &tsize); 16430 if (IS_ERR(ret)) { 16431 tname = btf_name_by_offset(btf, t->name_off); 16432 verbose(env, "ldimm64 unable to resolve the size of type '%s': %ld\n", 16433 tname, PTR_ERR(ret)); 16434 err = -EINVAL; 16435 goto err_put; 16436 } 16437 aux->btf_var.reg_type = PTR_TO_MEM | MEM_RDONLY; 16438 aux->btf_var.mem_size = tsize; 16439 } else { 16440 aux->btf_var.reg_type = PTR_TO_BTF_ID; 16441 aux->btf_var.btf = btf; 16442 aux->btf_var.btf_id = type; 16443 } 16444 check_btf: 16445 /* check whether we recorded this BTF (and maybe module) already */ 16446 for (i = 0; i < env->used_btf_cnt; i++) { 16447 if (env->used_btfs[i].btf == btf) { 16448 btf_put(btf); 16449 return 0; 16450 } 16451 } 16452 16453 if (env->used_btf_cnt >= MAX_USED_BTFS) { 16454 err = -E2BIG; 16455 goto err_put; 16456 } 16457 16458 btf_mod = &env->used_btfs[env->used_btf_cnt]; 16459 btf_mod->btf = btf; 16460 btf_mod->module = NULL; 16461 16462 /* if we reference variables from kernel module, bump its refcount */ 16463 if (btf_is_module(btf)) { 16464 btf_mod->module = btf_try_get_module(btf); 16465 if (!btf_mod->module) { 16466 err = -ENXIO; 16467 goto err_put; 16468 } 16469 } 16470 16471 env->used_btf_cnt++; 16472 16473 return 0; 16474 err_put: 16475 btf_put(btf); 16476 return err; 16477 } 16478 16479 static bool is_tracing_prog_type(enum bpf_prog_type type) 16480 { 16481 switch (type) { 16482 case BPF_PROG_TYPE_KPROBE: 16483 case BPF_PROG_TYPE_TRACEPOINT: 16484 case BPF_PROG_TYPE_PERF_EVENT: 16485 case BPF_PROG_TYPE_RAW_TRACEPOINT: 16486 case BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE: 16487 return true; 16488 default: 16489 return false; 16490 } 16491 } 16492 16493 static int check_map_prog_compatibility(struct bpf_verifier_env *env, 16494 struct bpf_map *map, 16495 struct bpf_prog *prog) 16496 16497 { 16498 enum bpf_prog_type prog_type = resolve_prog_type(prog); 16499 16500 if (btf_record_has_field(map->record, BPF_LIST_HEAD) || 16501 btf_record_has_field(map->record, BPF_RB_ROOT)) { 16502 if (is_tracing_prog_type(prog_type)) { 16503 verbose(env, "tracing progs cannot use bpf_{list_head,rb_root} yet\n"); 16504 return -EINVAL; 16505 } 16506 } 16507 16508 if (btf_record_has_field(map->record, BPF_SPIN_LOCK)) { 16509 if (prog_type == BPF_PROG_TYPE_SOCKET_FILTER) { 16510 verbose(env, "socket filter progs cannot use bpf_spin_lock yet\n"); 16511 return -EINVAL; 16512 } 16513 16514 if (is_tracing_prog_type(prog_type)) { 16515 verbose(env, "tracing progs cannot use bpf_spin_lock yet\n"); 16516 return -EINVAL; 16517 } 16518 16519 if (prog->aux->sleepable) { 16520 verbose(env, "sleepable progs cannot use bpf_spin_lock yet\n"); 16521 return -EINVAL; 16522 } 16523 } 16524 16525 if (btf_record_has_field(map->record, BPF_TIMER)) { 16526 if (is_tracing_prog_type(prog_type)) { 16527 verbose(env, "tracing progs cannot use bpf_timer yet\n"); 16528 return -EINVAL; 16529 } 16530 } 16531 16532 if ((bpf_prog_is_offloaded(prog->aux) || bpf_map_is_offloaded(map)) && 16533 !bpf_offload_prog_map_match(prog, map)) { 16534 verbose(env, "offload device mismatch between prog and map\n"); 16535 return -EINVAL; 16536 } 16537 16538 if (map->map_type == BPF_MAP_TYPE_STRUCT_OPS) { 16539 verbose(env, "bpf_struct_ops map cannot be used in prog\n"); 16540 return -EINVAL; 16541 } 16542 16543 if (prog->aux->sleepable) 16544 switch (map->map_type) { 16545 case BPF_MAP_TYPE_HASH: 16546 case BPF_MAP_TYPE_LRU_HASH: 16547 case BPF_MAP_TYPE_ARRAY: 16548 case BPF_MAP_TYPE_PERCPU_HASH: 16549 case BPF_MAP_TYPE_PERCPU_ARRAY: 16550 case BPF_MAP_TYPE_LRU_PERCPU_HASH: 16551 case BPF_MAP_TYPE_ARRAY_OF_MAPS: 16552 case BPF_MAP_TYPE_HASH_OF_MAPS: 16553 case BPF_MAP_TYPE_RINGBUF: 16554 case BPF_MAP_TYPE_USER_RINGBUF: 16555 case BPF_MAP_TYPE_INODE_STORAGE: 16556 case BPF_MAP_TYPE_SK_STORAGE: 16557 case BPF_MAP_TYPE_TASK_STORAGE: 16558 case BPF_MAP_TYPE_CGRP_STORAGE: 16559 break; 16560 default: 16561 verbose(env, 16562 "Sleepable programs can only use array, hash, ringbuf and local storage maps\n"); 16563 return -EINVAL; 16564 } 16565 16566 return 0; 16567 } 16568 16569 static bool bpf_map_is_cgroup_storage(struct bpf_map *map) 16570 { 16571 return (map->map_type == BPF_MAP_TYPE_CGROUP_STORAGE || 16572 map->map_type == BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE); 16573 } 16574 16575 /* find and rewrite pseudo imm in ld_imm64 instructions: 16576 * 16577 * 1. if it accesses map FD, replace it with actual map pointer. 16578 * 2. if it accesses btf_id of a VAR, replace it with pointer to the var. 16579 * 16580 * NOTE: btf_vmlinux is required for converting pseudo btf_id. 16581 */ 16582 static int resolve_pseudo_ldimm64(struct bpf_verifier_env *env) 16583 { 16584 struct bpf_insn *insn = env->prog->insnsi; 16585 int insn_cnt = env->prog->len; 16586 int i, j, err; 16587 16588 err = bpf_prog_calc_tag(env->prog); 16589 if (err) 16590 return err; 16591 16592 for (i = 0; i < insn_cnt; i++, insn++) { 16593 if (BPF_CLASS(insn->code) == BPF_LDX && 16594 (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0)) { 16595 verbose(env, "BPF_LDX uses reserved fields\n"); 16596 return -EINVAL; 16597 } 16598 16599 if (insn[0].code == (BPF_LD | BPF_IMM | BPF_DW)) { 16600 struct bpf_insn_aux_data *aux; 16601 struct bpf_map *map; 16602 struct fd f; 16603 u64 addr; 16604 u32 fd; 16605 16606 if (i == insn_cnt - 1 || insn[1].code != 0 || 16607 insn[1].dst_reg != 0 || insn[1].src_reg != 0 || 16608 insn[1].off != 0) { 16609 verbose(env, "invalid bpf_ld_imm64 insn\n"); 16610 return -EINVAL; 16611 } 16612 16613 if (insn[0].src_reg == 0) 16614 /* valid generic load 64-bit imm */ 16615 goto next_insn; 16616 16617 if (insn[0].src_reg == BPF_PSEUDO_BTF_ID) { 16618 aux = &env->insn_aux_data[i]; 16619 err = check_pseudo_btf_id(env, insn, aux); 16620 if (err) 16621 return err; 16622 goto next_insn; 16623 } 16624 16625 if (insn[0].src_reg == BPF_PSEUDO_FUNC) { 16626 aux = &env->insn_aux_data[i]; 16627 aux->ptr_type = PTR_TO_FUNC; 16628 goto next_insn; 16629 } 16630 16631 /* In final convert_pseudo_ld_imm64() step, this is 16632 * converted into regular 64-bit imm load insn. 16633 */ 16634 switch (insn[0].src_reg) { 16635 case BPF_PSEUDO_MAP_VALUE: 16636 case BPF_PSEUDO_MAP_IDX_VALUE: 16637 break; 16638 case BPF_PSEUDO_MAP_FD: 16639 case BPF_PSEUDO_MAP_IDX: 16640 if (insn[1].imm == 0) 16641 break; 16642 fallthrough; 16643 default: 16644 verbose(env, "unrecognized bpf_ld_imm64 insn\n"); 16645 return -EINVAL; 16646 } 16647 16648 switch (insn[0].src_reg) { 16649 case BPF_PSEUDO_MAP_IDX_VALUE: 16650 case BPF_PSEUDO_MAP_IDX: 16651 if (bpfptr_is_null(env->fd_array)) { 16652 verbose(env, "fd_idx without fd_array is invalid\n"); 16653 return -EPROTO; 16654 } 16655 if (copy_from_bpfptr_offset(&fd, env->fd_array, 16656 insn[0].imm * sizeof(fd), 16657 sizeof(fd))) 16658 return -EFAULT; 16659 break; 16660 default: 16661 fd = insn[0].imm; 16662 break; 16663 } 16664 16665 f = fdget(fd); 16666 map = __bpf_map_get(f); 16667 if (IS_ERR(map)) { 16668 verbose(env, "fd %d is not pointing to valid bpf_map\n", 16669 insn[0].imm); 16670 return PTR_ERR(map); 16671 } 16672 16673 err = check_map_prog_compatibility(env, map, env->prog); 16674 if (err) { 16675 fdput(f); 16676 return err; 16677 } 16678 16679 aux = &env->insn_aux_data[i]; 16680 if (insn[0].src_reg == BPF_PSEUDO_MAP_FD || 16681 insn[0].src_reg == BPF_PSEUDO_MAP_IDX) { 16682 addr = (unsigned long)map; 16683 } else { 16684 u32 off = insn[1].imm; 16685 16686 if (off >= BPF_MAX_VAR_OFF) { 16687 verbose(env, "direct value offset of %u is not allowed\n", off); 16688 fdput(f); 16689 return -EINVAL; 16690 } 16691 16692 if (!map->ops->map_direct_value_addr) { 16693 verbose(env, "no direct value access support for this map type\n"); 16694 fdput(f); 16695 return -EINVAL; 16696 } 16697 16698 err = map->ops->map_direct_value_addr(map, &addr, off); 16699 if (err) { 16700 verbose(env, "invalid access to map value pointer, value_size=%u off=%u\n", 16701 map->value_size, off); 16702 fdput(f); 16703 return err; 16704 } 16705 16706 aux->map_off = off; 16707 addr += off; 16708 } 16709 16710 insn[0].imm = (u32)addr; 16711 insn[1].imm = addr >> 32; 16712 16713 /* check whether we recorded this map already */ 16714 for (j = 0; j < env->used_map_cnt; j++) { 16715 if (env->used_maps[j] == map) { 16716 aux->map_index = j; 16717 fdput(f); 16718 goto next_insn; 16719 } 16720 } 16721 16722 if (env->used_map_cnt >= MAX_USED_MAPS) { 16723 fdput(f); 16724 return -E2BIG; 16725 } 16726 16727 /* hold the map. If the program is rejected by verifier, 16728 * the map will be released by release_maps() or it 16729 * will be used by the valid program until it's unloaded 16730 * and all maps are released in free_used_maps() 16731 */ 16732 bpf_map_inc(map); 16733 16734 aux->map_index = env->used_map_cnt; 16735 env->used_maps[env->used_map_cnt++] = map; 16736 16737 if (bpf_map_is_cgroup_storage(map) && 16738 bpf_cgroup_storage_assign(env->prog->aux, map)) { 16739 verbose(env, "only one cgroup storage of each type is allowed\n"); 16740 fdput(f); 16741 return -EBUSY; 16742 } 16743 16744 fdput(f); 16745 next_insn: 16746 insn++; 16747 i++; 16748 continue; 16749 } 16750 16751 /* Basic sanity check before we invest more work here. */ 16752 if (!bpf_opcode_in_insntable(insn->code)) { 16753 verbose(env, "unknown opcode %02x\n", insn->code); 16754 return -EINVAL; 16755 } 16756 } 16757 16758 /* now all pseudo BPF_LD_IMM64 instructions load valid 16759 * 'struct bpf_map *' into a register instead of user map_fd. 16760 * These pointers will be used later by verifier to validate map access. 16761 */ 16762 return 0; 16763 } 16764 16765 /* drop refcnt of maps used by the rejected program */ 16766 static void release_maps(struct bpf_verifier_env *env) 16767 { 16768 __bpf_free_used_maps(env->prog->aux, env->used_maps, 16769 env->used_map_cnt); 16770 } 16771 16772 /* drop refcnt of maps used by the rejected program */ 16773 static void release_btfs(struct bpf_verifier_env *env) 16774 { 16775 __bpf_free_used_btfs(env->prog->aux, env->used_btfs, 16776 env->used_btf_cnt); 16777 } 16778 16779 /* convert pseudo BPF_LD_IMM64 into generic BPF_LD_IMM64 */ 16780 static void convert_pseudo_ld_imm64(struct bpf_verifier_env *env) 16781 { 16782 struct bpf_insn *insn = env->prog->insnsi; 16783 int insn_cnt = env->prog->len; 16784 int i; 16785 16786 for (i = 0; i < insn_cnt; i++, insn++) { 16787 if (insn->code != (BPF_LD | BPF_IMM | BPF_DW)) 16788 continue; 16789 if (insn->src_reg == BPF_PSEUDO_FUNC) 16790 continue; 16791 insn->src_reg = 0; 16792 } 16793 } 16794 16795 /* single env->prog->insni[off] instruction was replaced with the range 16796 * insni[off, off + cnt). Adjust corresponding insn_aux_data by copying 16797 * [0, off) and [off, end) to new locations, so the patched range stays zero 16798 */ 16799 static void adjust_insn_aux_data(struct bpf_verifier_env *env, 16800 struct bpf_insn_aux_data *new_data, 16801 struct bpf_prog *new_prog, u32 off, u32 cnt) 16802 { 16803 struct bpf_insn_aux_data *old_data = env->insn_aux_data; 16804 struct bpf_insn *insn = new_prog->insnsi; 16805 u32 old_seen = old_data[off].seen; 16806 u32 prog_len; 16807 int i; 16808 16809 /* aux info at OFF always needs adjustment, no matter fast path 16810 * (cnt == 1) is taken or not. There is no guarantee INSN at OFF is the 16811 * original insn at old prog. 16812 */ 16813 old_data[off].zext_dst = insn_has_def32(env, insn + off + cnt - 1); 16814 16815 if (cnt == 1) 16816 return; 16817 prog_len = new_prog->len; 16818 16819 memcpy(new_data, old_data, sizeof(struct bpf_insn_aux_data) * off); 16820 memcpy(new_data + off + cnt - 1, old_data + off, 16821 sizeof(struct bpf_insn_aux_data) * (prog_len - off - cnt + 1)); 16822 for (i = off; i < off + cnt - 1; i++) { 16823 /* Expand insni[off]'s seen count to the patched range. */ 16824 new_data[i].seen = old_seen; 16825 new_data[i].zext_dst = insn_has_def32(env, insn + i); 16826 } 16827 env->insn_aux_data = new_data; 16828 vfree(old_data); 16829 } 16830 16831 static void adjust_subprog_starts(struct bpf_verifier_env *env, u32 off, u32 len) 16832 { 16833 int i; 16834 16835 if (len == 1) 16836 return; 16837 /* NOTE: fake 'exit' subprog should be updated as well. */ 16838 for (i = 0; i <= env->subprog_cnt; i++) { 16839 if (env->subprog_info[i].start <= off) 16840 continue; 16841 env->subprog_info[i].start += len - 1; 16842 } 16843 } 16844 16845 static void adjust_poke_descs(struct bpf_prog *prog, u32 off, u32 len) 16846 { 16847 struct bpf_jit_poke_descriptor *tab = prog->aux->poke_tab; 16848 int i, sz = prog->aux->size_poke_tab; 16849 struct bpf_jit_poke_descriptor *desc; 16850 16851 for (i = 0; i < sz; i++) { 16852 desc = &tab[i]; 16853 if (desc->insn_idx <= off) 16854 continue; 16855 desc->insn_idx += len - 1; 16856 } 16857 } 16858 16859 static struct bpf_prog *bpf_patch_insn_data(struct bpf_verifier_env *env, u32 off, 16860 const struct bpf_insn *patch, u32 len) 16861 { 16862 struct bpf_prog *new_prog; 16863 struct bpf_insn_aux_data *new_data = NULL; 16864 16865 if (len > 1) { 16866 new_data = vzalloc(array_size(env->prog->len + len - 1, 16867 sizeof(struct bpf_insn_aux_data))); 16868 if (!new_data) 16869 return NULL; 16870 } 16871 16872 new_prog = bpf_patch_insn_single(env->prog, off, patch, len); 16873 if (IS_ERR(new_prog)) { 16874 if (PTR_ERR(new_prog) == -ERANGE) 16875 verbose(env, 16876 "insn %d cannot be patched due to 16-bit range\n", 16877 env->insn_aux_data[off].orig_idx); 16878 vfree(new_data); 16879 return NULL; 16880 } 16881 adjust_insn_aux_data(env, new_data, new_prog, off, len); 16882 adjust_subprog_starts(env, off, len); 16883 adjust_poke_descs(new_prog, off, len); 16884 return new_prog; 16885 } 16886 16887 static int adjust_subprog_starts_after_remove(struct bpf_verifier_env *env, 16888 u32 off, u32 cnt) 16889 { 16890 int i, j; 16891 16892 /* find first prog starting at or after off (first to remove) */ 16893 for (i = 0; i < env->subprog_cnt; i++) 16894 if (env->subprog_info[i].start >= off) 16895 break; 16896 /* find first prog starting at or after off + cnt (first to stay) */ 16897 for (j = i; j < env->subprog_cnt; j++) 16898 if (env->subprog_info[j].start >= off + cnt) 16899 break; 16900 /* if j doesn't start exactly at off + cnt, we are just removing 16901 * the front of previous prog 16902 */ 16903 if (env->subprog_info[j].start != off + cnt) 16904 j--; 16905 16906 if (j > i) { 16907 struct bpf_prog_aux *aux = env->prog->aux; 16908 int move; 16909 16910 /* move fake 'exit' subprog as well */ 16911 move = env->subprog_cnt + 1 - j; 16912 16913 memmove(env->subprog_info + i, 16914 env->subprog_info + j, 16915 sizeof(*env->subprog_info) * move); 16916 env->subprog_cnt -= j - i; 16917 16918 /* remove func_info */ 16919 if (aux->func_info) { 16920 move = aux->func_info_cnt - j; 16921 16922 memmove(aux->func_info + i, 16923 aux->func_info + j, 16924 sizeof(*aux->func_info) * move); 16925 aux->func_info_cnt -= j - i; 16926 /* func_info->insn_off is set after all code rewrites, 16927 * in adjust_btf_func() - no need to adjust 16928 */ 16929 } 16930 } else { 16931 /* convert i from "first prog to remove" to "first to adjust" */ 16932 if (env->subprog_info[i].start == off) 16933 i++; 16934 } 16935 16936 /* update fake 'exit' subprog as well */ 16937 for (; i <= env->subprog_cnt; i++) 16938 env->subprog_info[i].start -= cnt; 16939 16940 return 0; 16941 } 16942 16943 static int bpf_adj_linfo_after_remove(struct bpf_verifier_env *env, u32 off, 16944 u32 cnt) 16945 { 16946 struct bpf_prog *prog = env->prog; 16947 u32 i, l_off, l_cnt, nr_linfo; 16948 struct bpf_line_info *linfo; 16949 16950 nr_linfo = prog->aux->nr_linfo; 16951 if (!nr_linfo) 16952 return 0; 16953 16954 linfo = prog->aux->linfo; 16955 16956 /* find first line info to remove, count lines to be removed */ 16957 for (i = 0; i < nr_linfo; i++) 16958 if (linfo[i].insn_off >= off) 16959 break; 16960 16961 l_off = i; 16962 l_cnt = 0; 16963 for (; i < nr_linfo; i++) 16964 if (linfo[i].insn_off < off + cnt) 16965 l_cnt++; 16966 else 16967 break; 16968 16969 /* First live insn doesn't match first live linfo, it needs to "inherit" 16970 * last removed linfo. prog is already modified, so prog->len == off 16971 * means no live instructions after (tail of the program was removed). 16972 */ 16973 if (prog->len != off && l_cnt && 16974 (i == nr_linfo || linfo[i].insn_off != off + cnt)) { 16975 l_cnt--; 16976 linfo[--i].insn_off = off + cnt; 16977 } 16978 16979 /* remove the line info which refer to the removed instructions */ 16980 if (l_cnt) { 16981 memmove(linfo + l_off, linfo + i, 16982 sizeof(*linfo) * (nr_linfo - i)); 16983 16984 prog->aux->nr_linfo -= l_cnt; 16985 nr_linfo = prog->aux->nr_linfo; 16986 } 16987 16988 /* pull all linfo[i].insn_off >= off + cnt in by cnt */ 16989 for (i = l_off; i < nr_linfo; i++) 16990 linfo[i].insn_off -= cnt; 16991 16992 /* fix up all subprogs (incl. 'exit') which start >= off */ 16993 for (i = 0; i <= env->subprog_cnt; i++) 16994 if (env->subprog_info[i].linfo_idx > l_off) { 16995 /* program may have started in the removed region but 16996 * may not be fully removed 16997 */ 16998 if (env->subprog_info[i].linfo_idx >= l_off + l_cnt) 16999 env->subprog_info[i].linfo_idx -= l_cnt; 17000 else 17001 env->subprog_info[i].linfo_idx = l_off; 17002 } 17003 17004 return 0; 17005 } 17006 17007 static int verifier_remove_insns(struct bpf_verifier_env *env, u32 off, u32 cnt) 17008 { 17009 struct bpf_insn_aux_data *aux_data = env->insn_aux_data; 17010 unsigned int orig_prog_len = env->prog->len; 17011 int err; 17012 17013 if (bpf_prog_is_offloaded(env->prog->aux)) 17014 bpf_prog_offload_remove_insns(env, off, cnt); 17015 17016 err = bpf_remove_insns(env->prog, off, cnt); 17017 if (err) 17018 return err; 17019 17020 err = adjust_subprog_starts_after_remove(env, off, cnt); 17021 if (err) 17022 return err; 17023 17024 err = bpf_adj_linfo_after_remove(env, off, cnt); 17025 if (err) 17026 return err; 17027 17028 memmove(aux_data + off, aux_data + off + cnt, 17029 sizeof(*aux_data) * (orig_prog_len - off - cnt)); 17030 17031 return 0; 17032 } 17033 17034 /* The verifier does more data flow analysis than llvm and will not 17035 * explore branches that are dead at run time. Malicious programs can 17036 * have dead code too. Therefore replace all dead at-run-time code 17037 * with 'ja -1'. 17038 * 17039 * Just nops are not optimal, e.g. if they would sit at the end of the 17040 * program and through another bug we would manage to jump there, then 17041 * we'd execute beyond program memory otherwise. Returning exception 17042 * code also wouldn't work since we can have subprogs where the dead 17043 * code could be located. 17044 */ 17045 static void sanitize_dead_code(struct bpf_verifier_env *env) 17046 { 17047 struct bpf_insn_aux_data *aux_data = env->insn_aux_data; 17048 struct bpf_insn trap = BPF_JMP_IMM(BPF_JA, 0, 0, -1); 17049 struct bpf_insn *insn = env->prog->insnsi; 17050 const int insn_cnt = env->prog->len; 17051 int i; 17052 17053 for (i = 0; i < insn_cnt; i++) { 17054 if (aux_data[i].seen) 17055 continue; 17056 memcpy(insn + i, &trap, sizeof(trap)); 17057 aux_data[i].zext_dst = false; 17058 } 17059 } 17060 17061 static bool insn_is_cond_jump(u8 code) 17062 { 17063 u8 op; 17064 17065 if (BPF_CLASS(code) == BPF_JMP32) 17066 return true; 17067 17068 if (BPF_CLASS(code) != BPF_JMP) 17069 return false; 17070 17071 op = BPF_OP(code); 17072 return op != BPF_JA && op != BPF_EXIT && op != BPF_CALL; 17073 } 17074 17075 static void opt_hard_wire_dead_code_branches(struct bpf_verifier_env *env) 17076 { 17077 struct bpf_insn_aux_data *aux_data = env->insn_aux_data; 17078 struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0); 17079 struct bpf_insn *insn = env->prog->insnsi; 17080 const int insn_cnt = env->prog->len; 17081 int i; 17082 17083 for (i = 0; i < insn_cnt; i++, insn++) { 17084 if (!insn_is_cond_jump(insn->code)) 17085 continue; 17086 17087 if (!aux_data[i + 1].seen) 17088 ja.off = insn->off; 17089 else if (!aux_data[i + 1 + insn->off].seen) 17090 ja.off = 0; 17091 else 17092 continue; 17093 17094 if (bpf_prog_is_offloaded(env->prog->aux)) 17095 bpf_prog_offload_replace_insn(env, i, &ja); 17096 17097 memcpy(insn, &ja, sizeof(ja)); 17098 } 17099 } 17100 17101 static int opt_remove_dead_code(struct bpf_verifier_env *env) 17102 { 17103 struct bpf_insn_aux_data *aux_data = env->insn_aux_data; 17104 int insn_cnt = env->prog->len; 17105 int i, err; 17106 17107 for (i = 0; i < insn_cnt; i++) { 17108 int j; 17109 17110 j = 0; 17111 while (i + j < insn_cnt && !aux_data[i + j].seen) 17112 j++; 17113 if (!j) 17114 continue; 17115 17116 err = verifier_remove_insns(env, i, j); 17117 if (err) 17118 return err; 17119 insn_cnt = env->prog->len; 17120 } 17121 17122 return 0; 17123 } 17124 17125 static int opt_remove_nops(struct bpf_verifier_env *env) 17126 { 17127 const struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0); 17128 struct bpf_insn *insn = env->prog->insnsi; 17129 int insn_cnt = env->prog->len; 17130 int i, err; 17131 17132 for (i = 0; i < insn_cnt; i++) { 17133 if (memcmp(&insn[i], &ja, sizeof(ja))) 17134 continue; 17135 17136 err = verifier_remove_insns(env, i, 1); 17137 if (err) 17138 return err; 17139 insn_cnt--; 17140 i--; 17141 } 17142 17143 return 0; 17144 } 17145 17146 static int opt_subreg_zext_lo32_rnd_hi32(struct bpf_verifier_env *env, 17147 const union bpf_attr *attr) 17148 { 17149 struct bpf_insn *patch, zext_patch[2], rnd_hi32_patch[4]; 17150 struct bpf_insn_aux_data *aux = env->insn_aux_data; 17151 int i, patch_len, delta = 0, len = env->prog->len; 17152 struct bpf_insn *insns = env->prog->insnsi; 17153 struct bpf_prog *new_prog; 17154 bool rnd_hi32; 17155 17156 rnd_hi32 = attr->prog_flags & BPF_F_TEST_RND_HI32; 17157 zext_patch[1] = BPF_ZEXT_REG(0); 17158 rnd_hi32_patch[1] = BPF_ALU64_IMM(BPF_MOV, BPF_REG_AX, 0); 17159 rnd_hi32_patch[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_AX, 32); 17160 rnd_hi32_patch[3] = BPF_ALU64_REG(BPF_OR, 0, BPF_REG_AX); 17161 for (i = 0; i < len; i++) { 17162 int adj_idx = i + delta; 17163 struct bpf_insn insn; 17164 int load_reg; 17165 17166 insn = insns[adj_idx]; 17167 load_reg = insn_def_regno(&insn); 17168 if (!aux[adj_idx].zext_dst) { 17169 u8 code, class; 17170 u32 imm_rnd; 17171 17172 if (!rnd_hi32) 17173 continue; 17174 17175 code = insn.code; 17176 class = BPF_CLASS(code); 17177 if (load_reg == -1) 17178 continue; 17179 17180 /* NOTE: arg "reg" (the fourth one) is only used for 17181 * BPF_STX + SRC_OP, so it is safe to pass NULL 17182 * here. 17183 */ 17184 if (is_reg64(env, &insn, load_reg, NULL, DST_OP)) { 17185 if (class == BPF_LD && 17186 BPF_MODE(code) == BPF_IMM) 17187 i++; 17188 continue; 17189 } 17190 17191 /* ctx load could be transformed into wider load. */ 17192 if (class == BPF_LDX && 17193 aux[adj_idx].ptr_type == PTR_TO_CTX) 17194 continue; 17195 17196 imm_rnd = get_random_u32(); 17197 rnd_hi32_patch[0] = insn; 17198 rnd_hi32_patch[1].imm = imm_rnd; 17199 rnd_hi32_patch[3].dst_reg = load_reg; 17200 patch = rnd_hi32_patch; 17201 patch_len = 4; 17202 goto apply_patch_buffer; 17203 } 17204 17205 /* Add in an zero-extend instruction if a) the JIT has requested 17206 * it or b) it's a CMPXCHG. 17207 * 17208 * The latter is because: BPF_CMPXCHG always loads a value into 17209 * R0, therefore always zero-extends. However some archs' 17210 * equivalent instruction only does this load when the 17211 * comparison is successful. This detail of CMPXCHG is 17212 * orthogonal to the general zero-extension behaviour of the 17213 * CPU, so it's treated independently of bpf_jit_needs_zext. 17214 */ 17215 if (!bpf_jit_needs_zext() && !is_cmpxchg_insn(&insn)) 17216 continue; 17217 17218 /* Zero-extension is done by the caller. */ 17219 if (bpf_pseudo_kfunc_call(&insn)) 17220 continue; 17221 17222 if (WARN_ON(load_reg == -1)) { 17223 verbose(env, "verifier bug. zext_dst is set, but no reg is defined\n"); 17224 return -EFAULT; 17225 } 17226 17227 zext_patch[0] = insn; 17228 zext_patch[1].dst_reg = load_reg; 17229 zext_patch[1].src_reg = load_reg; 17230 patch = zext_patch; 17231 patch_len = 2; 17232 apply_patch_buffer: 17233 new_prog = bpf_patch_insn_data(env, adj_idx, patch, patch_len); 17234 if (!new_prog) 17235 return -ENOMEM; 17236 env->prog = new_prog; 17237 insns = new_prog->insnsi; 17238 aux = env->insn_aux_data; 17239 delta += patch_len - 1; 17240 } 17241 17242 return 0; 17243 } 17244 17245 /* convert load instructions that access fields of a context type into a 17246 * sequence of instructions that access fields of the underlying structure: 17247 * struct __sk_buff -> struct sk_buff 17248 * struct bpf_sock_ops -> struct sock 17249 */ 17250 static int convert_ctx_accesses(struct bpf_verifier_env *env) 17251 { 17252 const struct bpf_verifier_ops *ops = env->ops; 17253 int i, cnt, size, ctx_field_size, delta = 0; 17254 const int insn_cnt = env->prog->len; 17255 struct bpf_insn insn_buf[16], *insn; 17256 u32 target_size, size_default, off; 17257 struct bpf_prog *new_prog; 17258 enum bpf_access_type type; 17259 bool is_narrower_load; 17260 17261 if (ops->gen_prologue || env->seen_direct_write) { 17262 if (!ops->gen_prologue) { 17263 verbose(env, "bpf verifier is misconfigured\n"); 17264 return -EINVAL; 17265 } 17266 cnt = ops->gen_prologue(insn_buf, env->seen_direct_write, 17267 env->prog); 17268 if (cnt >= ARRAY_SIZE(insn_buf)) { 17269 verbose(env, "bpf verifier is misconfigured\n"); 17270 return -EINVAL; 17271 } else if (cnt) { 17272 new_prog = bpf_patch_insn_data(env, 0, insn_buf, cnt); 17273 if (!new_prog) 17274 return -ENOMEM; 17275 17276 env->prog = new_prog; 17277 delta += cnt - 1; 17278 } 17279 } 17280 17281 if (bpf_prog_is_offloaded(env->prog->aux)) 17282 return 0; 17283 17284 insn = env->prog->insnsi + delta; 17285 17286 for (i = 0; i < insn_cnt; i++, insn++) { 17287 bpf_convert_ctx_access_t convert_ctx_access; 17288 17289 if (insn->code == (BPF_LDX | BPF_MEM | BPF_B) || 17290 insn->code == (BPF_LDX | BPF_MEM | BPF_H) || 17291 insn->code == (BPF_LDX | BPF_MEM | BPF_W) || 17292 insn->code == (BPF_LDX | BPF_MEM | BPF_DW)) { 17293 type = BPF_READ; 17294 } else if (insn->code == (BPF_STX | BPF_MEM | BPF_B) || 17295 insn->code == (BPF_STX | BPF_MEM | BPF_H) || 17296 insn->code == (BPF_STX | BPF_MEM | BPF_W) || 17297 insn->code == (BPF_STX | BPF_MEM | BPF_DW) || 17298 insn->code == (BPF_ST | BPF_MEM | BPF_B) || 17299 insn->code == (BPF_ST | BPF_MEM | BPF_H) || 17300 insn->code == (BPF_ST | BPF_MEM | BPF_W) || 17301 insn->code == (BPF_ST | BPF_MEM | BPF_DW)) { 17302 type = BPF_WRITE; 17303 } else { 17304 continue; 17305 } 17306 17307 if (type == BPF_WRITE && 17308 env->insn_aux_data[i + delta].sanitize_stack_spill) { 17309 struct bpf_insn patch[] = { 17310 *insn, 17311 BPF_ST_NOSPEC(), 17312 }; 17313 17314 cnt = ARRAY_SIZE(patch); 17315 new_prog = bpf_patch_insn_data(env, i + delta, patch, cnt); 17316 if (!new_prog) 17317 return -ENOMEM; 17318 17319 delta += cnt - 1; 17320 env->prog = new_prog; 17321 insn = new_prog->insnsi + i + delta; 17322 continue; 17323 } 17324 17325 switch ((int)env->insn_aux_data[i + delta].ptr_type) { 17326 case PTR_TO_CTX: 17327 if (!ops->convert_ctx_access) 17328 continue; 17329 convert_ctx_access = ops->convert_ctx_access; 17330 break; 17331 case PTR_TO_SOCKET: 17332 case PTR_TO_SOCK_COMMON: 17333 convert_ctx_access = bpf_sock_convert_ctx_access; 17334 break; 17335 case PTR_TO_TCP_SOCK: 17336 convert_ctx_access = bpf_tcp_sock_convert_ctx_access; 17337 break; 17338 case PTR_TO_XDP_SOCK: 17339 convert_ctx_access = bpf_xdp_sock_convert_ctx_access; 17340 break; 17341 case PTR_TO_BTF_ID: 17342 case PTR_TO_BTF_ID | PTR_UNTRUSTED: 17343 /* PTR_TO_BTF_ID | MEM_ALLOC always has a valid lifetime, unlike 17344 * PTR_TO_BTF_ID, and an active ref_obj_id, but the same cannot 17345 * be said once it is marked PTR_UNTRUSTED, hence we must handle 17346 * any faults for loads into such types. BPF_WRITE is disallowed 17347 * for this case. 17348 */ 17349 case PTR_TO_BTF_ID | MEM_ALLOC | PTR_UNTRUSTED: 17350 if (type == BPF_READ) { 17351 insn->code = BPF_LDX | BPF_PROBE_MEM | 17352 BPF_SIZE((insn)->code); 17353 env->prog->aux->num_exentries++; 17354 } 17355 continue; 17356 default: 17357 continue; 17358 } 17359 17360 ctx_field_size = env->insn_aux_data[i + delta].ctx_field_size; 17361 size = BPF_LDST_BYTES(insn); 17362 17363 /* If the read access is a narrower load of the field, 17364 * convert to a 4/8-byte load, to minimum program type specific 17365 * convert_ctx_access changes. If conversion is successful, 17366 * we will apply proper mask to the result. 17367 */ 17368 is_narrower_load = size < ctx_field_size; 17369 size_default = bpf_ctx_off_adjust_machine(ctx_field_size); 17370 off = insn->off; 17371 if (is_narrower_load) { 17372 u8 size_code; 17373 17374 if (type == BPF_WRITE) { 17375 verbose(env, "bpf verifier narrow ctx access misconfigured\n"); 17376 return -EINVAL; 17377 } 17378 17379 size_code = BPF_H; 17380 if (ctx_field_size == 4) 17381 size_code = BPF_W; 17382 else if (ctx_field_size == 8) 17383 size_code = BPF_DW; 17384 17385 insn->off = off & ~(size_default - 1); 17386 insn->code = BPF_LDX | BPF_MEM | size_code; 17387 } 17388 17389 target_size = 0; 17390 cnt = convert_ctx_access(type, insn, insn_buf, env->prog, 17391 &target_size); 17392 if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf) || 17393 (ctx_field_size && !target_size)) { 17394 verbose(env, "bpf verifier is misconfigured\n"); 17395 return -EINVAL; 17396 } 17397 17398 if (is_narrower_load && size < target_size) { 17399 u8 shift = bpf_ctx_narrow_access_offset( 17400 off, size, size_default) * 8; 17401 if (shift && cnt + 1 >= ARRAY_SIZE(insn_buf)) { 17402 verbose(env, "bpf verifier narrow ctx load misconfigured\n"); 17403 return -EINVAL; 17404 } 17405 if (ctx_field_size <= 4) { 17406 if (shift) 17407 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_RSH, 17408 insn->dst_reg, 17409 shift); 17410 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg, 17411 (1 << size * 8) - 1); 17412 } else { 17413 if (shift) 17414 insn_buf[cnt++] = BPF_ALU64_IMM(BPF_RSH, 17415 insn->dst_reg, 17416 shift); 17417 insn_buf[cnt++] = BPF_ALU64_IMM(BPF_AND, insn->dst_reg, 17418 (1ULL << size * 8) - 1); 17419 } 17420 } 17421 17422 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 17423 if (!new_prog) 17424 return -ENOMEM; 17425 17426 delta += cnt - 1; 17427 17428 /* keep walking new program and skip insns we just inserted */ 17429 env->prog = new_prog; 17430 insn = new_prog->insnsi + i + delta; 17431 } 17432 17433 return 0; 17434 } 17435 17436 static int jit_subprogs(struct bpf_verifier_env *env) 17437 { 17438 struct bpf_prog *prog = env->prog, **func, *tmp; 17439 int i, j, subprog_start, subprog_end = 0, len, subprog; 17440 struct bpf_map *map_ptr; 17441 struct bpf_insn *insn; 17442 void *old_bpf_func; 17443 int err, num_exentries; 17444 17445 if (env->subprog_cnt <= 1) 17446 return 0; 17447 17448 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) { 17449 if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn)) 17450 continue; 17451 17452 /* Upon error here we cannot fall back to interpreter but 17453 * need a hard reject of the program. Thus -EFAULT is 17454 * propagated in any case. 17455 */ 17456 subprog = find_subprog(env, i + insn->imm + 1); 17457 if (subprog < 0) { 17458 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n", 17459 i + insn->imm + 1); 17460 return -EFAULT; 17461 } 17462 /* temporarily remember subprog id inside insn instead of 17463 * aux_data, since next loop will split up all insns into funcs 17464 */ 17465 insn->off = subprog; 17466 /* remember original imm in case JIT fails and fallback 17467 * to interpreter will be needed 17468 */ 17469 env->insn_aux_data[i].call_imm = insn->imm; 17470 /* point imm to __bpf_call_base+1 from JITs point of view */ 17471 insn->imm = 1; 17472 if (bpf_pseudo_func(insn)) 17473 /* jit (e.g. x86_64) may emit fewer instructions 17474 * if it learns a u32 imm is the same as a u64 imm. 17475 * Force a non zero here. 17476 */ 17477 insn[1].imm = 1; 17478 } 17479 17480 err = bpf_prog_alloc_jited_linfo(prog); 17481 if (err) 17482 goto out_undo_insn; 17483 17484 err = -ENOMEM; 17485 func = kcalloc(env->subprog_cnt, sizeof(prog), GFP_KERNEL); 17486 if (!func) 17487 goto out_undo_insn; 17488 17489 for (i = 0; i < env->subprog_cnt; i++) { 17490 subprog_start = subprog_end; 17491 subprog_end = env->subprog_info[i + 1].start; 17492 17493 len = subprog_end - subprog_start; 17494 /* bpf_prog_run() doesn't call subprogs directly, 17495 * hence main prog stats include the runtime of subprogs. 17496 * subprogs don't have IDs and not reachable via prog_get_next_id 17497 * func[i]->stats will never be accessed and stays NULL 17498 */ 17499 func[i] = bpf_prog_alloc_no_stats(bpf_prog_size(len), GFP_USER); 17500 if (!func[i]) 17501 goto out_free; 17502 memcpy(func[i]->insnsi, &prog->insnsi[subprog_start], 17503 len * sizeof(struct bpf_insn)); 17504 func[i]->type = prog->type; 17505 func[i]->len = len; 17506 if (bpf_prog_calc_tag(func[i])) 17507 goto out_free; 17508 func[i]->is_func = 1; 17509 func[i]->aux->func_idx = i; 17510 /* Below members will be freed only at prog->aux */ 17511 func[i]->aux->btf = prog->aux->btf; 17512 func[i]->aux->func_info = prog->aux->func_info; 17513 func[i]->aux->func_info_cnt = prog->aux->func_info_cnt; 17514 func[i]->aux->poke_tab = prog->aux->poke_tab; 17515 func[i]->aux->size_poke_tab = prog->aux->size_poke_tab; 17516 17517 for (j = 0; j < prog->aux->size_poke_tab; j++) { 17518 struct bpf_jit_poke_descriptor *poke; 17519 17520 poke = &prog->aux->poke_tab[j]; 17521 if (poke->insn_idx < subprog_end && 17522 poke->insn_idx >= subprog_start) 17523 poke->aux = func[i]->aux; 17524 } 17525 17526 func[i]->aux->name[0] = 'F'; 17527 func[i]->aux->stack_depth = env->subprog_info[i].stack_depth; 17528 func[i]->jit_requested = 1; 17529 func[i]->blinding_requested = prog->blinding_requested; 17530 func[i]->aux->kfunc_tab = prog->aux->kfunc_tab; 17531 func[i]->aux->kfunc_btf_tab = prog->aux->kfunc_btf_tab; 17532 func[i]->aux->linfo = prog->aux->linfo; 17533 func[i]->aux->nr_linfo = prog->aux->nr_linfo; 17534 func[i]->aux->jited_linfo = prog->aux->jited_linfo; 17535 func[i]->aux->linfo_idx = env->subprog_info[i].linfo_idx; 17536 num_exentries = 0; 17537 insn = func[i]->insnsi; 17538 for (j = 0; j < func[i]->len; j++, insn++) { 17539 if (BPF_CLASS(insn->code) == BPF_LDX && 17540 BPF_MODE(insn->code) == BPF_PROBE_MEM) 17541 num_exentries++; 17542 } 17543 func[i]->aux->num_exentries = num_exentries; 17544 func[i]->aux->tail_call_reachable = env->subprog_info[i].tail_call_reachable; 17545 func[i] = bpf_int_jit_compile(func[i]); 17546 if (!func[i]->jited) { 17547 err = -ENOTSUPP; 17548 goto out_free; 17549 } 17550 cond_resched(); 17551 } 17552 17553 /* at this point all bpf functions were successfully JITed 17554 * now populate all bpf_calls with correct addresses and 17555 * run last pass of JIT 17556 */ 17557 for (i = 0; i < env->subprog_cnt; i++) { 17558 insn = func[i]->insnsi; 17559 for (j = 0; j < func[i]->len; j++, insn++) { 17560 if (bpf_pseudo_func(insn)) { 17561 subprog = insn->off; 17562 insn[0].imm = (u32)(long)func[subprog]->bpf_func; 17563 insn[1].imm = ((u64)(long)func[subprog]->bpf_func) >> 32; 17564 continue; 17565 } 17566 if (!bpf_pseudo_call(insn)) 17567 continue; 17568 subprog = insn->off; 17569 insn->imm = BPF_CALL_IMM(func[subprog]->bpf_func); 17570 } 17571 17572 /* we use the aux data to keep a list of the start addresses 17573 * of the JITed images for each function in the program 17574 * 17575 * for some architectures, such as powerpc64, the imm field 17576 * might not be large enough to hold the offset of the start 17577 * address of the callee's JITed image from __bpf_call_base 17578 * 17579 * in such cases, we can lookup the start address of a callee 17580 * by using its subprog id, available from the off field of 17581 * the call instruction, as an index for this list 17582 */ 17583 func[i]->aux->func = func; 17584 func[i]->aux->func_cnt = env->subprog_cnt; 17585 } 17586 for (i = 0; i < env->subprog_cnt; i++) { 17587 old_bpf_func = func[i]->bpf_func; 17588 tmp = bpf_int_jit_compile(func[i]); 17589 if (tmp != func[i] || func[i]->bpf_func != old_bpf_func) { 17590 verbose(env, "JIT doesn't support bpf-to-bpf calls\n"); 17591 err = -ENOTSUPP; 17592 goto out_free; 17593 } 17594 cond_resched(); 17595 } 17596 17597 /* finally lock prog and jit images for all functions and 17598 * populate kallsysm 17599 */ 17600 for (i = 0; i < env->subprog_cnt; i++) { 17601 bpf_prog_lock_ro(func[i]); 17602 bpf_prog_kallsyms_add(func[i]); 17603 } 17604 17605 /* Last step: make now unused interpreter insns from main 17606 * prog consistent for later dump requests, so they can 17607 * later look the same as if they were interpreted only. 17608 */ 17609 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) { 17610 if (bpf_pseudo_func(insn)) { 17611 insn[0].imm = env->insn_aux_data[i].call_imm; 17612 insn[1].imm = insn->off; 17613 insn->off = 0; 17614 continue; 17615 } 17616 if (!bpf_pseudo_call(insn)) 17617 continue; 17618 insn->off = env->insn_aux_data[i].call_imm; 17619 subprog = find_subprog(env, i + insn->off + 1); 17620 insn->imm = subprog; 17621 } 17622 17623 prog->jited = 1; 17624 prog->bpf_func = func[0]->bpf_func; 17625 prog->jited_len = func[0]->jited_len; 17626 prog->aux->func = func; 17627 prog->aux->func_cnt = env->subprog_cnt; 17628 bpf_prog_jit_attempt_done(prog); 17629 return 0; 17630 out_free: 17631 /* We failed JIT'ing, so at this point we need to unregister poke 17632 * descriptors from subprogs, so that kernel is not attempting to 17633 * patch it anymore as we're freeing the subprog JIT memory. 17634 */ 17635 for (i = 0; i < prog->aux->size_poke_tab; i++) { 17636 map_ptr = prog->aux->poke_tab[i].tail_call.map; 17637 map_ptr->ops->map_poke_untrack(map_ptr, prog->aux); 17638 } 17639 /* At this point we're guaranteed that poke descriptors are not 17640 * live anymore. We can just unlink its descriptor table as it's 17641 * released with the main prog. 17642 */ 17643 for (i = 0; i < env->subprog_cnt; i++) { 17644 if (!func[i]) 17645 continue; 17646 func[i]->aux->poke_tab = NULL; 17647 bpf_jit_free(func[i]); 17648 } 17649 kfree(func); 17650 out_undo_insn: 17651 /* cleanup main prog to be interpreted */ 17652 prog->jit_requested = 0; 17653 prog->blinding_requested = 0; 17654 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) { 17655 if (!bpf_pseudo_call(insn)) 17656 continue; 17657 insn->off = 0; 17658 insn->imm = env->insn_aux_data[i].call_imm; 17659 } 17660 bpf_prog_jit_attempt_done(prog); 17661 return err; 17662 } 17663 17664 static int fixup_call_args(struct bpf_verifier_env *env) 17665 { 17666 #ifndef CONFIG_BPF_JIT_ALWAYS_ON 17667 struct bpf_prog *prog = env->prog; 17668 struct bpf_insn *insn = prog->insnsi; 17669 bool has_kfunc_call = bpf_prog_has_kfunc_call(prog); 17670 int i, depth; 17671 #endif 17672 int err = 0; 17673 17674 if (env->prog->jit_requested && 17675 !bpf_prog_is_offloaded(env->prog->aux)) { 17676 err = jit_subprogs(env); 17677 if (err == 0) 17678 return 0; 17679 if (err == -EFAULT) 17680 return err; 17681 } 17682 #ifndef CONFIG_BPF_JIT_ALWAYS_ON 17683 if (has_kfunc_call) { 17684 verbose(env, "calling kernel functions are not allowed in non-JITed programs\n"); 17685 return -EINVAL; 17686 } 17687 if (env->subprog_cnt > 1 && env->prog->aux->tail_call_reachable) { 17688 /* When JIT fails the progs with bpf2bpf calls and tail_calls 17689 * have to be rejected, since interpreter doesn't support them yet. 17690 */ 17691 verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n"); 17692 return -EINVAL; 17693 } 17694 for (i = 0; i < prog->len; i++, insn++) { 17695 if (bpf_pseudo_func(insn)) { 17696 /* When JIT fails the progs with callback calls 17697 * have to be rejected, since interpreter doesn't support them yet. 17698 */ 17699 verbose(env, "callbacks are not allowed in non-JITed programs\n"); 17700 return -EINVAL; 17701 } 17702 17703 if (!bpf_pseudo_call(insn)) 17704 continue; 17705 depth = get_callee_stack_depth(env, insn, i); 17706 if (depth < 0) 17707 return depth; 17708 bpf_patch_call_args(insn, depth); 17709 } 17710 err = 0; 17711 #endif 17712 return err; 17713 } 17714 17715 /* replace a generic kfunc with a specialized version if necessary */ 17716 static void specialize_kfunc(struct bpf_verifier_env *env, 17717 u32 func_id, u16 offset, unsigned long *addr) 17718 { 17719 struct bpf_prog *prog = env->prog; 17720 bool seen_direct_write; 17721 void *xdp_kfunc; 17722 bool is_rdonly; 17723 17724 if (bpf_dev_bound_kfunc_id(func_id)) { 17725 xdp_kfunc = bpf_dev_bound_resolve_kfunc(prog, func_id); 17726 if (xdp_kfunc) { 17727 *addr = (unsigned long)xdp_kfunc; 17728 return; 17729 } 17730 /* fallback to default kfunc when not supported by netdev */ 17731 } 17732 17733 if (offset) 17734 return; 17735 17736 if (func_id == special_kfunc_list[KF_bpf_dynptr_from_skb]) { 17737 seen_direct_write = env->seen_direct_write; 17738 is_rdonly = !may_access_direct_pkt_data(env, NULL, BPF_WRITE); 17739 17740 if (is_rdonly) 17741 *addr = (unsigned long)bpf_dynptr_from_skb_rdonly; 17742 17743 /* restore env->seen_direct_write to its original value, since 17744 * may_access_direct_pkt_data mutates it 17745 */ 17746 env->seen_direct_write = seen_direct_write; 17747 } 17748 } 17749 17750 static void __fixup_collection_insert_kfunc(struct bpf_insn_aux_data *insn_aux, 17751 u16 struct_meta_reg, 17752 u16 node_offset_reg, 17753 struct bpf_insn *insn, 17754 struct bpf_insn *insn_buf, 17755 int *cnt) 17756 { 17757 struct btf_struct_meta *kptr_struct_meta = insn_aux->kptr_struct_meta; 17758 struct bpf_insn addr[2] = { BPF_LD_IMM64(struct_meta_reg, (long)kptr_struct_meta) }; 17759 17760 insn_buf[0] = addr[0]; 17761 insn_buf[1] = addr[1]; 17762 insn_buf[2] = BPF_MOV64_IMM(node_offset_reg, insn_aux->insert_off); 17763 insn_buf[3] = *insn; 17764 *cnt = 4; 17765 } 17766 17767 static int fixup_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn, 17768 struct bpf_insn *insn_buf, int insn_idx, int *cnt) 17769 { 17770 const struct bpf_kfunc_desc *desc; 17771 17772 if (!insn->imm) { 17773 verbose(env, "invalid kernel function call not eliminated in verifier pass\n"); 17774 return -EINVAL; 17775 } 17776 17777 *cnt = 0; 17778 17779 /* insn->imm has the btf func_id. Replace it with an offset relative to 17780 * __bpf_call_base, unless the JIT needs to call functions that are 17781 * further than 32 bits away (bpf_jit_supports_far_kfunc_call()). 17782 */ 17783 desc = find_kfunc_desc(env->prog, insn->imm, insn->off); 17784 if (!desc) { 17785 verbose(env, "verifier internal error: kernel function descriptor not found for func_id %u\n", 17786 insn->imm); 17787 return -EFAULT; 17788 } 17789 17790 if (!bpf_jit_supports_far_kfunc_call()) 17791 insn->imm = BPF_CALL_IMM(desc->addr); 17792 if (insn->off) 17793 return 0; 17794 if (desc->func_id == special_kfunc_list[KF_bpf_obj_new_impl]) { 17795 struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta; 17796 struct bpf_insn addr[2] = { BPF_LD_IMM64(BPF_REG_2, (long)kptr_struct_meta) }; 17797 u64 obj_new_size = env->insn_aux_data[insn_idx].obj_new_size; 17798 17799 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_1, obj_new_size); 17800 insn_buf[1] = addr[0]; 17801 insn_buf[2] = addr[1]; 17802 insn_buf[3] = *insn; 17803 *cnt = 4; 17804 } else if (desc->func_id == special_kfunc_list[KF_bpf_obj_drop_impl] || 17805 desc->func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl]) { 17806 struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta; 17807 struct bpf_insn addr[2] = { BPF_LD_IMM64(BPF_REG_2, (long)kptr_struct_meta) }; 17808 17809 insn_buf[0] = addr[0]; 17810 insn_buf[1] = addr[1]; 17811 insn_buf[2] = *insn; 17812 *cnt = 3; 17813 } else if (desc->func_id == special_kfunc_list[KF_bpf_list_push_back_impl] || 17814 desc->func_id == special_kfunc_list[KF_bpf_list_push_front_impl] || 17815 desc->func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) { 17816 int struct_meta_reg = BPF_REG_3; 17817 int node_offset_reg = BPF_REG_4; 17818 17819 /* rbtree_add has extra 'less' arg, so args-to-fixup are in diff regs */ 17820 if (desc->func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) { 17821 struct_meta_reg = BPF_REG_4; 17822 node_offset_reg = BPF_REG_5; 17823 } 17824 17825 __fixup_collection_insert_kfunc(&env->insn_aux_data[insn_idx], struct_meta_reg, 17826 node_offset_reg, insn, insn_buf, cnt); 17827 } else if (desc->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx] || 17828 desc->func_id == special_kfunc_list[KF_bpf_rdonly_cast]) { 17829 insn_buf[0] = BPF_MOV64_REG(BPF_REG_0, BPF_REG_1); 17830 *cnt = 1; 17831 } 17832 return 0; 17833 } 17834 17835 /* Do various post-verification rewrites in a single program pass. 17836 * These rewrites simplify JIT and interpreter implementations. 17837 */ 17838 static int do_misc_fixups(struct bpf_verifier_env *env) 17839 { 17840 struct bpf_prog *prog = env->prog; 17841 enum bpf_attach_type eatype = prog->expected_attach_type; 17842 enum bpf_prog_type prog_type = resolve_prog_type(prog); 17843 struct bpf_insn *insn = prog->insnsi; 17844 const struct bpf_func_proto *fn; 17845 const int insn_cnt = prog->len; 17846 const struct bpf_map_ops *ops; 17847 struct bpf_insn_aux_data *aux; 17848 struct bpf_insn insn_buf[16]; 17849 struct bpf_prog *new_prog; 17850 struct bpf_map *map_ptr; 17851 int i, ret, cnt, delta = 0; 17852 17853 for (i = 0; i < insn_cnt; i++, insn++) { 17854 /* Make divide-by-zero exceptions impossible. */ 17855 if (insn->code == (BPF_ALU64 | BPF_MOD | BPF_X) || 17856 insn->code == (BPF_ALU64 | BPF_DIV | BPF_X) || 17857 insn->code == (BPF_ALU | BPF_MOD | BPF_X) || 17858 insn->code == (BPF_ALU | BPF_DIV | BPF_X)) { 17859 bool is64 = BPF_CLASS(insn->code) == BPF_ALU64; 17860 bool isdiv = BPF_OP(insn->code) == BPF_DIV; 17861 struct bpf_insn *patchlet; 17862 struct bpf_insn chk_and_div[] = { 17863 /* [R,W]x div 0 -> 0 */ 17864 BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) | 17865 BPF_JNE | BPF_K, insn->src_reg, 17866 0, 2, 0), 17867 BPF_ALU32_REG(BPF_XOR, insn->dst_reg, insn->dst_reg), 17868 BPF_JMP_IMM(BPF_JA, 0, 0, 1), 17869 *insn, 17870 }; 17871 struct bpf_insn chk_and_mod[] = { 17872 /* [R,W]x mod 0 -> [R,W]x */ 17873 BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) | 17874 BPF_JEQ | BPF_K, insn->src_reg, 17875 0, 1 + (is64 ? 0 : 1), 0), 17876 *insn, 17877 BPF_JMP_IMM(BPF_JA, 0, 0, 1), 17878 BPF_MOV32_REG(insn->dst_reg, insn->dst_reg), 17879 }; 17880 17881 patchlet = isdiv ? chk_and_div : chk_and_mod; 17882 cnt = isdiv ? ARRAY_SIZE(chk_and_div) : 17883 ARRAY_SIZE(chk_and_mod) - (is64 ? 2 : 0); 17884 17885 new_prog = bpf_patch_insn_data(env, i + delta, patchlet, cnt); 17886 if (!new_prog) 17887 return -ENOMEM; 17888 17889 delta += cnt - 1; 17890 env->prog = prog = new_prog; 17891 insn = new_prog->insnsi + i + delta; 17892 continue; 17893 } 17894 17895 /* Implement LD_ABS and LD_IND with a rewrite, if supported by the program type. */ 17896 if (BPF_CLASS(insn->code) == BPF_LD && 17897 (BPF_MODE(insn->code) == BPF_ABS || 17898 BPF_MODE(insn->code) == BPF_IND)) { 17899 cnt = env->ops->gen_ld_abs(insn, insn_buf); 17900 if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf)) { 17901 verbose(env, "bpf verifier is misconfigured\n"); 17902 return -EINVAL; 17903 } 17904 17905 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 17906 if (!new_prog) 17907 return -ENOMEM; 17908 17909 delta += cnt - 1; 17910 env->prog = prog = new_prog; 17911 insn = new_prog->insnsi + i + delta; 17912 continue; 17913 } 17914 17915 /* Rewrite pointer arithmetic to mitigate speculation attacks. */ 17916 if (insn->code == (BPF_ALU64 | BPF_ADD | BPF_X) || 17917 insn->code == (BPF_ALU64 | BPF_SUB | BPF_X)) { 17918 const u8 code_add = BPF_ALU64 | BPF_ADD | BPF_X; 17919 const u8 code_sub = BPF_ALU64 | BPF_SUB | BPF_X; 17920 struct bpf_insn *patch = &insn_buf[0]; 17921 bool issrc, isneg, isimm; 17922 u32 off_reg; 17923 17924 aux = &env->insn_aux_data[i + delta]; 17925 if (!aux->alu_state || 17926 aux->alu_state == BPF_ALU_NON_POINTER) 17927 continue; 17928 17929 isneg = aux->alu_state & BPF_ALU_NEG_VALUE; 17930 issrc = (aux->alu_state & BPF_ALU_SANITIZE) == 17931 BPF_ALU_SANITIZE_SRC; 17932 isimm = aux->alu_state & BPF_ALU_IMMEDIATE; 17933 17934 off_reg = issrc ? insn->src_reg : insn->dst_reg; 17935 if (isimm) { 17936 *patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit); 17937 } else { 17938 if (isneg) 17939 *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1); 17940 *patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit); 17941 *patch++ = BPF_ALU64_REG(BPF_SUB, BPF_REG_AX, off_reg); 17942 *patch++ = BPF_ALU64_REG(BPF_OR, BPF_REG_AX, off_reg); 17943 *patch++ = BPF_ALU64_IMM(BPF_NEG, BPF_REG_AX, 0); 17944 *patch++ = BPF_ALU64_IMM(BPF_ARSH, BPF_REG_AX, 63); 17945 *patch++ = BPF_ALU64_REG(BPF_AND, BPF_REG_AX, off_reg); 17946 } 17947 if (!issrc) 17948 *patch++ = BPF_MOV64_REG(insn->dst_reg, insn->src_reg); 17949 insn->src_reg = BPF_REG_AX; 17950 if (isneg) 17951 insn->code = insn->code == code_add ? 17952 code_sub : code_add; 17953 *patch++ = *insn; 17954 if (issrc && isneg && !isimm) 17955 *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1); 17956 cnt = patch - insn_buf; 17957 17958 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 17959 if (!new_prog) 17960 return -ENOMEM; 17961 17962 delta += cnt - 1; 17963 env->prog = prog = new_prog; 17964 insn = new_prog->insnsi + i + delta; 17965 continue; 17966 } 17967 17968 if (insn->code != (BPF_JMP | BPF_CALL)) 17969 continue; 17970 if (insn->src_reg == BPF_PSEUDO_CALL) 17971 continue; 17972 if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) { 17973 ret = fixup_kfunc_call(env, insn, insn_buf, i + delta, &cnt); 17974 if (ret) 17975 return ret; 17976 if (cnt == 0) 17977 continue; 17978 17979 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 17980 if (!new_prog) 17981 return -ENOMEM; 17982 17983 delta += cnt - 1; 17984 env->prog = prog = new_prog; 17985 insn = new_prog->insnsi + i + delta; 17986 continue; 17987 } 17988 17989 if (insn->imm == BPF_FUNC_get_route_realm) 17990 prog->dst_needed = 1; 17991 if (insn->imm == BPF_FUNC_get_prandom_u32) 17992 bpf_user_rnd_init_once(); 17993 if (insn->imm == BPF_FUNC_override_return) 17994 prog->kprobe_override = 1; 17995 if (insn->imm == BPF_FUNC_tail_call) { 17996 /* If we tail call into other programs, we 17997 * cannot make any assumptions since they can 17998 * be replaced dynamically during runtime in 17999 * the program array. 18000 */ 18001 prog->cb_access = 1; 18002 if (!allow_tail_call_in_subprogs(env)) 18003 prog->aux->stack_depth = MAX_BPF_STACK; 18004 prog->aux->max_pkt_offset = MAX_PACKET_OFF; 18005 18006 /* mark bpf_tail_call as different opcode to avoid 18007 * conditional branch in the interpreter for every normal 18008 * call and to prevent accidental JITing by JIT compiler 18009 * that doesn't support bpf_tail_call yet 18010 */ 18011 insn->imm = 0; 18012 insn->code = BPF_JMP | BPF_TAIL_CALL; 18013 18014 aux = &env->insn_aux_data[i + delta]; 18015 if (env->bpf_capable && !prog->blinding_requested && 18016 prog->jit_requested && 18017 !bpf_map_key_poisoned(aux) && 18018 !bpf_map_ptr_poisoned(aux) && 18019 !bpf_map_ptr_unpriv(aux)) { 18020 struct bpf_jit_poke_descriptor desc = { 18021 .reason = BPF_POKE_REASON_TAIL_CALL, 18022 .tail_call.map = BPF_MAP_PTR(aux->map_ptr_state), 18023 .tail_call.key = bpf_map_key_immediate(aux), 18024 .insn_idx = i + delta, 18025 }; 18026 18027 ret = bpf_jit_add_poke_descriptor(prog, &desc); 18028 if (ret < 0) { 18029 verbose(env, "adding tail call poke descriptor failed\n"); 18030 return ret; 18031 } 18032 18033 insn->imm = ret + 1; 18034 continue; 18035 } 18036 18037 if (!bpf_map_ptr_unpriv(aux)) 18038 continue; 18039 18040 /* instead of changing every JIT dealing with tail_call 18041 * emit two extra insns: 18042 * if (index >= max_entries) goto out; 18043 * index &= array->index_mask; 18044 * to avoid out-of-bounds cpu speculation 18045 */ 18046 if (bpf_map_ptr_poisoned(aux)) { 18047 verbose(env, "tail_call abusing map_ptr\n"); 18048 return -EINVAL; 18049 } 18050 18051 map_ptr = BPF_MAP_PTR(aux->map_ptr_state); 18052 insn_buf[0] = BPF_JMP_IMM(BPF_JGE, BPF_REG_3, 18053 map_ptr->max_entries, 2); 18054 insn_buf[1] = BPF_ALU32_IMM(BPF_AND, BPF_REG_3, 18055 container_of(map_ptr, 18056 struct bpf_array, 18057 map)->index_mask); 18058 insn_buf[2] = *insn; 18059 cnt = 3; 18060 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 18061 if (!new_prog) 18062 return -ENOMEM; 18063 18064 delta += cnt - 1; 18065 env->prog = prog = new_prog; 18066 insn = new_prog->insnsi + i + delta; 18067 continue; 18068 } 18069 18070 if (insn->imm == BPF_FUNC_timer_set_callback) { 18071 /* The verifier will process callback_fn as many times as necessary 18072 * with different maps and the register states prepared by 18073 * set_timer_callback_state will be accurate. 18074 * 18075 * The following use case is valid: 18076 * map1 is shared by prog1, prog2, prog3. 18077 * prog1 calls bpf_timer_init for some map1 elements 18078 * prog2 calls bpf_timer_set_callback for some map1 elements. 18079 * Those that were not bpf_timer_init-ed will return -EINVAL. 18080 * prog3 calls bpf_timer_start for some map1 elements. 18081 * Those that were not both bpf_timer_init-ed and 18082 * bpf_timer_set_callback-ed will return -EINVAL. 18083 */ 18084 struct bpf_insn ld_addrs[2] = { 18085 BPF_LD_IMM64(BPF_REG_3, (long)prog->aux), 18086 }; 18087 18088 insn_buf[0] = ld_addrs[0]; 18089 insn_buf[1] = ld_addrs[1]; 18090 insn_buf[2] = *insn; 18091 cnt = 3; 18092 18093 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 18094 if (!new_prog) 18095 return -ENOMEM; 18096 18097 delta += cnt - 1; 18098 env->prog = prog = new_prog; 18099 insn = new_prog->insnsi + i + delta; 18100 goto patch_call_imm; 18101 } 18102 18103 if (is_storage_get_function(insn->imm)) { 18104 if (!env->prog->aux->sleepable || 18105 env->insn_aux_data[i + delta].storage_get_func_atomic) 18106 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_5, (__force __s32)GFP_ATOMIC); 18107 else 18108 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_5, (__force __s32)GFP_KERNEL); 18109 insn_buf[1] = *insn; 18110 cnt = 2; 18111 18112 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 18113 if (!new_prog) 18114 return -ENOMEM; 18115 18116 delta += cnt - 1; 18117 env->prog = prog = new_prog; 18118 insn = new_prog->insnsi + i + delta; 18119 goto patch_call_imm; 18120 } 18121 18122 /* BPF_EMIT_CALL() assumptions in some of the map_gen_lookup 18123 * and other inlining handlers are currently limited to 64 bit 18124 * only. 18125 */ 18126 if (prog->jit_requested && BITS_PER_LONG == 64 && 18127 (insn->imm == BPF_FUNC_map_lookup_elem || 18128 insn->imm == BPF_FUNC_map_update_elem || 18129 insn->imm == BPF_FUNC_map_delete_elem || 18130 insn->imm == BPF_FUNC_map_push_elem || 18131 insn->imm == BPF_FUNC_map_pop_elem || 18132 insn->imm == BPF_FUNC_map_peek_elem || 18133 insn->imm == BPF_FUNC_redirect_map || 18134 insn->imm == BPF_FUNC_for_each_map_elem || 18135 insn->imm == BPF_FUNC_map_lookup_percpu_elem)) { 18136 aux = &env->insn_aux_data[i + delta]; 18137 if (bpf_map_ptr_poisoned(aux)) 18138 goto patch_call_imm; 18139 18140 map_ptr = BPF_MAP_PTR(aux->map_ptr_state); 18141 ops = map_ptr->ops; 18142 if (insn->imm == BPF_FUNC_map_lookup_elem && 18143 ops->map_gen_lookup) { 18144 cnt = ops->map_gen_lookup(map_ptr, insn_buf); 18145 if (cnt == -EOPNOTSUPP) 18146 goto patch_map_ops_generic; 18147 if (cnt <= 0 || cnt >= ARRAY_SIZE(insn_buf)) { 18148 verbose(env, "bpf verifier is misconfigured\n"); 18149 return -EINVAL; 18150 } 18151 18152 new_prog = bpf_patch_insn_data(env, i + delta, 18153 insn_buf, cnt); 18154 if (!new_prog) 18155 return -ENOMEM; 18156 18157 delta += cnt - 1; 18158 env->prog = prog = new_prog; 18159 insn = new_prog->insnsi + i + delta; 18160 continue; 18161 } 18162 18163 BUILD_BUG_ON(!__same_type(ops->map_lookup_elem, 18164 (void *(*)(struct bpf_map *map, void *key))NULL)); 18165 BUILD_BUG_ON(!__same_type(ops->map_delete_elem, 18166 (long (*)(struct bpf_map *map, void *key))NULL)); 18167 BUILD_BUG_ON(!__same_type(ops->map_update_elem, 18168 (long (*)(struct bpf_map *map, void *key, void *value, 18169 u64 flags))NULL)); 18170 BUILD_BUG_ON(!__same_type(ops->map_push_elem, 18171 (long (*)(struct bpf_map *map, void *value, 18172 u64 flags))NULL)); 18173 BUILD_BUG_ON(!__same_type(ops->map_pop_elem, 18174 (long (*)(struct bpf_map *map, void *value))NULL)); 18175 BUILD_BUG_ON(!__same_type(ops->map_peek_elem, 18176 (long (*)(struct bpf_map *map, void *value))NULL)); 18177 BUILD_BUG_ON(!__same_type(ops->map_redirect, 18178 (long (*)(struct bpf_map *map, u64 index, u64 flags))NULL)); 18179 BUILD_BUG_ON(!__same_type(ops->map_for_each_callback, 18180 (long (*)(struct bpf_map *map, 18181 bpf_callback_t callback_fn, 18182 void *callback_ctx, 18183 u64 flags))NULL)); 18184 BUILD_BUG_ON(!__same_type(ops->map_lookup_percpu_elem, 18185 (void *(*)(struct bpf_map *map, void *key, u32 cpu))NULL)); 18186 18187 patch_map_ops_generic: 18188 switch (insn->imm) { 18189 case BPF_FUNC_map_lookup_elem: 18190 insn->imm = BPF_CALL_IMM(ops->map_lookup_elem); 18191 continue; 18192 case BPF_FUNC_map_update_elem: 18193 insn->imm = BPF_CALL_IMM(ops->map_update_elem); 18194 continue; 18195 case BPF_FUNC_map_delete_elem: 18196 insn->imm = BPF_CALL_IMM(ops->map_delete_elem); 18197 continue; 18198 case BPF_FUNC_map_push_elem: 18199 insn->imm = BPF_CALL_IMM(ops->map_push_elem); 18200 continue; 18201 case BPF_FUNC_map_pop_elem: 18202 insn->imm = BPF_CALL_IMM(ops->map_pop_elem); 18203 continue; 18204 case BPF_FUNC_map_peek_elem: 18205 insn->imm = BPF_CALL_IMM(ops->map_peek_elem); 18206 continue; 18207 case BPF_FUNC_redirect_map: 18208 insn->imm = BPF_CALL_IMM(ops->map_redirect); 18209 continue; 18210 case BPF_FUNC_for_each_map_elem: 18211 insn->imm = BPF_CALL_IMM(ops->map_for_each_callback); 18212 continue; 18213 case BPF_FUNC_map_lookup_percpu_elem: 18214 insn->imm = BPF_CALL_IMM(ops->map_lookup_percpu_elem); 18215 continue; 18216 } 18217 18218 goto patch_call_imm; 18219 } 18220 18221 /* Implement bpf_jiffies64 inline. */ 18222 if (prog->jit_requested && BITS_PER_LONG == 64 && 18223 insn->imm == BPF_FUNC_jiffies64) { 18224 struct bpf_insn ld_jiffies_addr[2] = { 18225 BPF_LD_IMM64(BPF_REG_0, 18226 (unsigned long)&jiffies), 18227 }; 18228 18229 insn_buf[0] = ld_jiffies_addr[0]; 18230 insn_buf[1] = ld_jiffies_addr[1]; 18231 insn_buf[2] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, 18232 BPF_REG_0, 0); 18233 cnt = 3; 18234 18235 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 18236 cnt); 18237 if (!new_prog) 18238 return -ENOMEM; 18239 18240 delta += cnt - 1; 18241 env->prog = prog = new_prog; 18242 insn = new_prog->insnsi + i + delta; 18243 continue; 18244 } 18245 18246 /* Implement bpf_get_func_arg inline. */ 18247 if (prog_type == BPF_PROG_TYPE_TRACING && 18248 insn->imm == BPF_FUNC_get_func_arg) { 18249 /* Load nr_args from ctx - 8 */ 18250 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8); 18251 insn_buf[1] = BPF_JMP32_REG(BPF_JGE, BPF_REG_2, BPF_REG_0, 6); 18252 insn_buf[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_2, 3); 18253 insn_buf[3] = BPF_ALU64_REG(BPF_ADD, BPF_REG_2, BPF_REG_1); 18254 insn_buf[4] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_2, 0); 18255 insn_buf[5] = BPF_STX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0); 18256 insn_buf[6] = BPF_MOV64_IMM(BPF_REG_0, 0); 18257 insn_buf[7] = BPF_JMP_A(1); 18258 insn_buf[8] = BPF_MOV64_IMM(BPF_REG_0, -EINVAL); 18259 cnt = 9; 18260 18261 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 18262 if (!new_prog) 18263 return -ENOMEM; 18264 18265 delta += cnt - 1; 18266 env->prog = prog = new_prog; 18267 insn = new_prog->insnsi + i + delta; 18268 continue; 18269 } 18270 18271 /* Implement bpf_get_func_ret inline. */ 18272 if (prog_type == BPF_PROG_TYPE_TRACING && 18273 insn->imm == BPF_FUNC_get_func_ret) { 18274 if (eatype == BPF_TRACE_FEXIT || 18275 eatype == BPF_MODIFY_RETURN) { 18276 /* Load nr_args from ctx - 8 */ 18277 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8); 18278 insn_buf[1] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_0, 3); 18279 insn_buf[2] = BPF_ALU64_REG(BPF_ADD, BPF_REG_0, BPF_REG_1); 18280 insn_buf[3] = BPF_LDX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0); 18281 insn_buf[4] = BPF_STX_MEM(BPF_DW, BPF_REG_2, BPF_REG_3, 0); 18282 insn_buf[5] = BPF_MOV64_IMM(BPF_REG_0, 0); 18283 cnt = 6; 18284 } else { 18285 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_0, -EOPNOTSUPP); 18286 cnt = 1; 18287 } 18288 18289 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 18290 if (!new_prog) 18291 return -ENOMEM; 18292 18293 delta += cnt - 1; 18294 env->prog = prog = new_prog; 18295 insn = new_prog->insnsi + i + delta; 18296 continue; 18297 } 18298 18299 /* Implement get_func_arg_cnt inline. */ 18300 if (prog_type == BPF_PROG_TYPE_TRACING && 18301 insn->imm == BPF_FUNC_get_func_arg_cnt) { 18302 /* Load nr_args from ctx - 8 */ 18303 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8); 18304 18305 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1); 18306 if (!new_prog) 18307 return -ENOMEM; 18308 18309 env->prog = prog = new_prog; 18310 insn = new_prog->insnsi + i + delta; 18311 continue; 18312 } 18313 18314 /* Implement bpf_get_func_ip inline. */ 18315 if (prog_type == BPF_PROG_TYPE_TRACING && 18316 insn->imm == BPF_FUNC_get_func_ip) { 18317 /* Load IP address from ctx - 16 */ 18318 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -16); 18319 18320 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1); 18321 if (!new_prog) 18322 return -ENOMEM; 18323 18324 env->prog = prog = new_prog; 18325 insn = new_prog->insnsi + i + delta; 18326 continue; 18327 } 18328 18329 patch_call_imm: 18330 fn = env->ops->get_func_proto(insn->imm, env->prog); 18331 /* all functions that have prototype and verifier allowed 18332 * programs to call them, must be real in-kernel functions 18333 */ 18334 if (!fn->func) { 18335 verbose(env, 18336 "kernel subsystem misconfigured func %s#%d\n", 18337 func_id_name(insn->imm), insn->imm); 18338 return -EFAULT; 18339 } 18340 insn->imm = fn->func - __bpf_call_base; 18341 } 18342 18343 /* Since poke tab is now finalized, publish aux to tracker. */ 18344 for (i = 0; i < prog->aux->size_poke_tab; i++) { 18345 map_ptr = prog->aux->poke_tab[i].tail_call.map; 18346 if (!map_ptr->ops->map_poke_track || 18347 !map_ptr->ops->map_poke_untrack || 18348 !map_ptr->ops->map_poke_run) { 18349 verbose(env, "bpf verifier is misconfigured\n"); 18350 return -EINVAL; 18351 } 18352 18353 ret = map_ptr->ops->map_poke_track(map_ptr, prog->aux); 18354 if (ret < 0) { 18355 verbose(env, "tracking tail call prog failed\n"); 18356 return ret; 18357 } 18358 } 18359 18360 sort_kfunc_descs_by_imm_off(env->prog); 18361 18362 return 0; 18363 } 18364 18365 static struct bpf_prog *inline_bpf_loop(struct bpf_verifier_env *env, 18366 int position, 18367 s32 stack_base, 18368 u32 callback_subprogno, 18369 u32 *cnt) 18370 { 18371 s32 r6_offset = stack_base + 0 * BPF_REG_SIZE; 18372 s32 r7_offset = stack_base + 1 * BPF_REG_SIZE; 18373 s32 r8_offset = stack_base + 2 * BPF_REG_SIZE; 18374 int reg_loop_max = BPF_REG_6; 18375 int reg_loop_cnt = BPF_REG_7; 18376 int reg_loop_ctx = BPF_REG_8; 18377 18378 struct bpf_prog *new_prog; 18379 u32 callback_start; 18380 u32 call_insn_offset; 18381 s32 callback_offset; 18382 18383 /* This represents an inlined version of bpf_iter.c:bpf_loop, 18384 * be careful to modify this code in sync. 18385 */ 18386 struct bpf_insn insn_buf[] = { 18387 /* Return error and jump to the end of the patch if 18388 * expected number of iterations is too big. 18389 */ 18390 BPF_JMP_IMM(BPF_JLE, BPF_REG_1, BPF_MAX_LOOPS, 2), 18391 BPF_MOV32_IMM(BPF_REG_0, -E2BIG), 18392 BPF_JMP_IMM(BPF_JA, 0, 0, 16), 18393 /* spill R6, R7, R8 to use these as loop vars */ 18394 BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_6, r6_offset), 18395 BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_7, r7_offset), 18396 BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_8, r8_offset), 18397 /* initialize loop vars */ 18398 BPF_MOV64_REG(reg_loop_max, BPF_REG_1), 18399 BPF_MOV32_IMM(reg_loop_cnt, 0), 18400 BPF_MOV64_REG(reg_loop_ctx, BPF_REG_3), 18401 /* loop header, 18402 * if reg_loop_cnt >= reg_loop_max skip the loop body 18403 */ 18404 BPF_JMP_REG(BPF_JGE, reg_loop_cnt, reg_loop_max, 5), 18405 /* callback call, 18406 * correct callback offset would be set after patching 18407 */ 18408 BPF_MOV64_REG(BPF_REG_1, reg_loop_cnt), 18409 BPF_MOV64_REG(BPF_REG_2, reg_loop_ctx), 18410 BPF_CALL_REL(0), 18411 /* increment loop counter */ 18412 BPF_ALU64_IMM(BPF_ADD, reg_loop_cnt, 1), 18413 /* jump to loop header if callback returned 0 */ 18414 BPF_JMP_IMM(BPF_JEQ, BPF_REG_0, 0, -6), 18415 /* return value of bpf_loop, 18416 * set R0 to the number of iterations 18417 */ 18418 BPF_MOV64_REG(BPF_REG_0, reg_loop_cnt), 18419 /* restore original values of R6, R7, R8 */ 18420 BPF_LDX_MEM(BPF_DW, BPF_REG_6, BPF_REG_10, r6_offset), 18421 BPF_LDX_MEM(BPF_DW, BPF_REG_7, BPF_REG_10, r7_offset), 18422 BPF_LDX_MEM(BPF_DW, BPF_REG_8, BPF_REG_10, r8_offset), 18423 }; 18424 18425 *cnt = ARRAY_SIZE(insn_buf); 18426 new_prog = bpf_patch_insn_data(env, position, insn_buf, *cnt); 18427 if (!new_prog) 18428 return new_prog; 18429 18430 /* callback start is known only after patching */ 18431 callback_start = env->subprog_info[callback_subprogno].start; 18432 /* Note: insn_buf[12] is an offset of BPF_CALL_REL instruction */ 18433 call_insn_offset = position + 12; 18434 callback_offset = callback_start - call_insn_offset - 1; 18435 new_prog->insnsi[call_insn_offset].imm = callback_offset; 18436 18437 return new_prog; 18438 } 18439 18440 static bool is_bpf_loop_call(struct bpf_insn *insn) 18441 { 18442 return insn->code == (BPF_JMP | BPF_CALL) && 18443 insn->src_reg == 0 && 18444 insn->imm == BPF_FUNC_loop; 18445 } 18446 18447 /* For all sub-programs in the program (including main) check 18448 * insn_aux_data to see if there are bpf_loop calls that require 18449 * inlining. If such calls are found the calls are replaced with a 18450 * sequence of instructions produced by `inline_bpf_loop` function and 18451 * subprog stack_depth is increased by the size of 3 registers. 18452 * This stack space is used to spill values of the R6, R7, R8. These 18453 * registers are used to store the loop bound, counter and context 18454 * variables. 18455 */ 18456 static int optimize_bpf_loop(struct bpf_verifier_env *env) 18457 { 18458 struct bpf_subprog_info *subprogs = env->subprog_info; 18459 int i, cur_subprog = 0, cnt, delta = 0; 18460 struct bpf_insn *insn = env->prog->insnsi; 18461 int insn_cnt = env->prog->len; 18462 u16 stack_depth = subprogs[cur_subprog].stack_depth; 18463 u16 stack_depth_roundup = round_up(stack_depth, 8) - stack_depth; 18464 u16 stack_depth_extra = 0; 18465 18466 for (i = 0; i < insn_cnt; i++, insn++) { 18467 struct bpf_loop_inline_state *inline_state = 18468 &env->insn_aux_data[i + delta].loop_inline_state; 18469 18470 if (is_bpf_loop_call(insn) && inline_state->fit_for_inline) { 18471 struct bpf_prog *new_prog; 18472 18473 stack_depth_extra = BPF_REG_SIZE * 3 + stack_depth_roundup; 18474 new_prog = inline_bpf_loop(env, 18475 i + delta, 18476 -(stack_depth + stack_depth_extra), 18477 inline_state->callback_subprogno, 18478 &cnt); 18479 if (!new_prog) 18480 return -ENOMEM; 18481 18482 delta += cnt - 1; 18483 env->prog = new_prog; 18484 insn = new_prog->insnsi + i + delta; 18485 } 18486 18487 if (subprogs[cur_subprog + 1].start == i + delta + 1) { 18488 subprogs[cur_subprog].stack_depth += stack_depth_extra; 18489 cur_subprog++; 18490 stack_depth = subprogs[cur_subprog].stack_depth; 18491 stack_depth_roundup = round_up(stack_depth, 8) - stack_depth; 18492 stack_depth_extra = 0; 18493 } 18494 } 18495 18496 env->prog->aux->stack_depth = env->subprog_info[0].stack_depth; 18497 18498 return 0; 18499 } 18500 18501 static void free_states(struct bpf_verifier_env *env) 18502 { 18503 struct bpf_verifier_state_list *sl, *sln; 18504 int i; 18505 18506 sl = env->free_list; 18507 while (sl) { 18508 sln = sl->next; 18509 free_verifier_state(&sl->state, false); 18510 kfree(sl); 18511 sl = sln; 18512 } 18513 env->free_list = NULL; 18514 18515 if (!env->explored_states) 18516 return; 18517 18518 for (i = 0; i < state_htab_size(env); i++) { 18519 sl = env->explored_states[i]; 18520 18521 while (sl) { 18522 sln = sl->next; 18523 free_verifier_state(&sl->state, false); 18524 kfree(sl); 18525 sl = sln; 18526 } 18527 env->explored_states[i] = NULL; 18528 } 18529 } 18530 18531 static int do_check_common(struct bpf_verifier_env *env, int subprog) 18532 { 18533 bool pop_log = !(env->log.level & BPF_LOG_LEVEL2); 18534 struct bpf_verifier_state *state; 18535 struct bpf_reg_state *regs; 18536 int ret, i; 18537 18538 env->prev_linfo = NULL; 18539 env->pass_cnt++; 18540 18541 state = kzalloc(sizeof(struct bpf_verifier_state), GFP_KERNEL); 18542 if (!state) 18543 return -ENOMEM; 18544 state->curframe = 0; 18545 state->speculative = false; 18546 state->branches = 1; 18547 state->frame[0] = kzalloc(sizeof(struct bpf_func_state), GFP_KERNEL); 18548 if (!state->frame[0]) { 18549 kfree(state); 18550 return -ENOMEM; 18551 } 18552 env->cur_state = state; 18553 init_func_state(env, state->frame[0], 18554 BPF_MAIN_FUNC /* callsite */, 18555 0 /* frameno */, 18556 subprog); 18557 state->first_insn_idx = env->subprog_info[subprog].start; 18558 state->last_insn_idx = -1; 18559 18560 regs = state->frame[state->curframe]->regs; 18561 if (subprog || env->prog->type == BPF_PROG_TYPE_EXT) { 18562 ret = btf_prepare_func_args(env, subprog, regs); 18563 if (ret) 18564 goto out; 18565 for (i = BPF_REG_1; i <= BPF_REG_5; i++) { 18566 if (regs[i].type == PTR_TO_CTX) 18567 mark_reg_known_zero(env, regs, i); 18568 else if (regs[i].type == SCALAR_VALUE) 18569 mark_reg_unknown(env, regs, i); 18570 else if (base_type(regs[i].type) == PTR_TO_MEM) { 18571 const u32 mem_size = regs[i].mem_size; 18572 18573 mark_reg_known_zero(env, regs, i); 18574 regs[i].mem_size = mem_size; 18575 regs[i].id = ++env->id_gen; 18576 } 18577 } 18578 } else { 18579 /* 1st arg to a function */ 18580 regs[BPF_REG_1].type = PTR_TO_CTX; 18581 mark_reg_known_zero(env, regs, BPF_REG_1); 18582 ret = btf_check_subprog_arg_match(env, subprog, regs); 18583 if (ret == -EFAULT) 18584 /* unlikely verifier bug. abort. 18585 * ret == 0 and ret < 0 are sadly acceptable for 18586 * main() function due to backward compatibility. 18587 * Like socket filter program may be written as: 18588 * int bpf_prog(struct pt_regs *ctx) 18589 * and never dereference that ctx in the program. 18590 * 'struct pt_regs' is a type mismatch for socket 18591 * filter that should be using 'struct __sk_buff'. 18592 */ 18593 goto out; 18594 } 18595 18596 ret = do_check(env); 18597 out: 18598 /* check for NULL is necessary, since cur_state can be freed inside 18599 * do_check() under memory pressure. 18600 */ 18601 if (env->cur_state) { 18602 free_verifier_state(env->cur_state, true); 18603 env->cur_state = NULL; 18604 } 18605 while (!pop_stack(env, NULL, NULL, false)); 18606 if (!ret && pop_log) 18607 bpf_vlog_reset(&env->log, 0); 18608 free_states(env); 18609 return ret; 18610 } 18611 18612 /* Verify all global functions in a BPF program one by one based on their BTF. 18613 * All global functions must pass verification. Otherwise the whole program is rejected. 18614 * Consider: 18615 * int bar(int); 18616 * int foo(int f) 18617 * { 18618 * return bar(f); 18619 * } 18620 * int bar(int b) 18621 * { 18622 * ... 18623 * } 18624 * foo() will be verified first for R1=any_scalar_value. During verification it 18625 * will be assumed that bar() already verified successfully and call to bar() 18626 * from foo() will be checked for type match only. Later bar() will be verified 18627 * independently to check that it's safe for R1=any_scalar_value. 18628 */ 18629 static int do_check_subprogs(struct bpf_verifier_env *env) 18630 { 18631 struct bpf_prog_aux *aux = env->prog->aux; 18632 int i, ret; 18633 18634 if (!aux->func_info) 18635 return 0; 18636 18637 for (i = 1; i < env->subprog_cnt; i++) { 18638 if (aux->func_info_aux[i].linkage != BTF_FUNC_GLOBAL) 18639 continue; 18640 env->insn_idx = env->subprog_info[i].start; 18641 WARN_ON_ONCE(env->insn_idx == 0); 18642 ret = do_check_common(env, i); 18643 if (ret) { 18644 return ret; 18645 } else if (env->log.level & BPF_LOG_LEVEL) { 18646 verbose(env, 18647 "Func#%d is safe for any args that match its prototype\n", 18648 i); 18649 } 18650 } 18651 return 0; 18652 } 18653 18654 static int do_check_main(struct bpf_verifier_env *env) 18655 { 18656 int ret; 18657 18658 env->insn_idx = 0; 18659 ret = do_check_common(env, 0); 18660 if (!ret) 18661 env->prog->aux->stack_depth = env->subprog_info[0].stack_depth; 18662 return ret; 18663 } 18664 18665 18666 static void print_verification_stats(struct bpf_verifier_env *env) 18667 { 18668 int i; 18669 18670 if (env->log.level & BPF_LOG_STATS) { 18671 verbose(env, "verification time %lld usec\n", 18672 div_u64(env->verification_time, 1000)); 18673 verbose(env, "stack depth "); 18674 for (i = 0; i < env->subprog_cnt; i++) { 18675 u32 depth = env->subprog_info[i].stack_depth; 18676 18677 verbose(env, "%d", depth); 18678 if (i + 1 < env->subprog_cnt) 18679 verbose(env, "+"); 18680 } 18681 verbose(env, "\n"); 18682 } 18683 verbose(env, "processed %d insns (limit %d) max_states_per_insn %d " 18684 "total_states %d peak_states %d mark_read %d\n", 18685 env->insn_processed, BPF_COMPLEXITY_LIMIT_INSNS, 18686 env->max_states_per_insn, env->total_states, 18687 env->peak_states, env->longest_mark_read_walk); 18688 } 18689 18690 static int check_struct_ops_btf_id(struct bpf_verifier_env *env) 18691 { 18692 const struct btf_type *t, *func_proto; 18693 const struct bpf_struct_ops *st_ops; 18694 const struct btf_member *member; 18695 struct bpf_prog *prog = env->prog; 18696 u32 btf_id, member_idx; 18697 const char *mname; 18698 18699 if (!prog->gpl_compatible) { 18700 verbose(env, "struct ops programs must have a GPL compatible license\n"); 18701 return -EINVAL; 18702 } 18703 18704 btf_id = prog->aux->attach_btf_id; 18705 st_ops = bpf_struct_ops_find(btf_id); 18706 if (!st_ops) { 18707 verbose(env, "attach_btf_id %u is not a supported struct\n", 18708 btf_id); 18709 return -ENOTSUPP; 18710 } 18711 18712 t = st_ops->type; 18713 member_idx = prog->expected_attach_type; 18714 if (member_idx >= btf_type_vlen(t)) { 18715 verbose(env, "attach to invalid member idx %u of struct %s\n", 18716 member_idx, st_ops->name); 18717 return -EINVAL; 18718 } 18719 18720 member = &btf_type_member(t)[member_idx]; 18721 mname = btf_name_by_offset(btf_vmlinux, member->name_off); 18722 func_proto = btf_type_resolve_func_ptr(btf_vmlinux, member->type, 18723 NULL); 18724 if (!func_proto) { 18725 verbose(env, "attach to invalid member %s(@idx %u) of struct %s\n", 18726 mname, member_idx, st_ops->name); 18727 return -EINVAL; 18728 } 18729 18730 if (st_ops->check_member) { 18731 int err = st_ops->check_member(t, member, prog); 18732 18733 if (err) { 18734 verbose(env, "attach to unsupported member %s of struct %s\n", 18735 mname, st_ops->name); 18736 return err; 18737 } 18738 } 18739 18740 prog->aux->attach_func_proto = func_proto; 18741 prog->aux->attach_func_name = mname; 18742 env->ops = st_ops->verifier_ops; 18743 18744 return 0; 18745 } 18746 #define SECURITY_PREFIX "security_" 18747 18748 static int check_attach_modify_return(unsigned long addr, const char *func_name) 18749 { 18750 if (within_error_injection_list(addr) || 18751 !strncmp(SECURITY_PREFIX, func_name, sizeof(SECURITY_PREFIX) - 1)) 18752 return 0; 18753 18754 return -EINVAL; 18755 } 18756 18757 /* list of non-sleepable functions that are otherwise on 18758 * ALLOW_ERROR_INJECTION list 18759 */ 18760 BTF_SET_START(btf_non_sleepable_error_inject) 18761 /* Three functions below can be called from sleepable and non-sleepable context. 18762 * Assume non-sleepable from bpf safety point of view. 18763 */ 18764 BTF_ID(func, __filemap_add_folio) 18765 BTF_ID(func, should_fail_alloc_page) 18766 BTF_ID(func, should_failslab) 18767 BTF_SET_END(btf_non_sleepable_error_inject) 18768 18769 static int check_non_sleepable_error_inject(u32 btf_id) 18770 { 18771 return btf_id_set_contains(&btf_non_sleepable_error_inject, btf_id); 18772 } 18773 18774 int bpf_check_attach_target(struct bpf_verifier_log *log, 18775 const struct bpf_prog *prog, 18776 const struct bpf_prog *tgt_prog, 18777 u32 btf_id, 18778 struct bpf_attach_target_info *tgt_info) 18779 { 18780 bool prog_extension = prog->type == BPF_PROG_TYPE_EXT; 18781 const char prefix[] = "btf_trace_"; 18782 int ret = 0, subprog = -1, i; 18783 const struct btf_type *t; 18784 bool conservative = true; 18785 const char *tname; 18786 struct btf *btf; 18787 long addr = 0; 18788 struct module *mod = NULL; 18789 18790 if (!btf_id) { 18791 bpf_log(log, "Tracing programs must provide btf_id\n"); 18792 return -EINVAL; 18793 } 18794 btf = tgt_prog ? tgt_prog->aux->btf : prog->aux->attach_btf; 18795 if (!btf) { 18796 bpf_log(log, 18797 "FENTRY/FEXIT program can only be attached to another program annotated with BTF\n"); 18798 return -EINVAL; 18799 } 18800 t = btf_type_by_id(btf, btf_id); 18801 if (!t) { 18802 bpf_log(log, "attach_btf_id %u is invalid\n", btf_id); 18803 return -EINVAL; 18804 } 18805 tname = btf_name_by_offset(btf, t->name_off); 18806 if (!tname) { 18807 bpf_log(log, "attach_btf_id %u doesn't have a name\n", btf_id); 18808 return -EINVAL; 18809 } 18810 if (tgt_prog) { 18811 struct bpf_prog_aux *aux = tgt_prog->aux; 18812 18813 if (bpf_prog_is_dev_bound(prog->aux) && 18814 !bpf_prog_dev_bound_match(prog, tgt_prog)) { 18815 bpf_log(log, "Target program bound device mismatch"); 18816 return -EINVAL; 18817 } 18818 18819 for (i = 0; i < aux->func_info_cnt; i++) 18820 if (aux->func_info[i].type_id == btf_id) { 18821 subprog = i; 18822 break; 18823 } 18824 if (subprog == -1) { 18825 bpf_log(log, "Subprog %s doesn't exist\n", tname); 18826 return -EINVAL; 18827 } 18828 conservative = aux->func_info_aux[subprog].unreliable; 18829 if (prog_extension) { 18830 if (conservative) { 18831 bpf_log(log, 18832 "Cannot replace static functions\n"); 18833 return -EINVAL; 18834 } 18835 if (!prog->jit_requested) { 18836 bpf_log(log, 18837 "Extension programs should be JITed\n"); 18838 return -EINVAL; 18839 } 18840 } 18841 if (!tgt_prog->jited) { 18842 bpf_log(log, "Can attach to only JITed progs\n"); 18843 return -EINVAL; 18844 } 18845 if (tgt_prog->type == prog->type) { 18846 /* Cannot fentry/fexit another fentry/fexit program. 18847 * Cannot attach program extension to another extension. 18848 * It's ok to attach fentry/fexit to extension program. 18849 */ 18850 bpf_log(log, "Cannot recursively attach\n"); 18851 return -EINVAL; 18852 } 18853 if (tgt_prog->type == BPF_PROG_TYPE_TRACING && 18854 prog_extension && 18855 (tgt_prog->expected_attach_type == BPF_TRACE_FENTRY || 18856 tgt_prog->expected_attach_type == BPF_TRACE_FEXIT)) { 18857 /* Program extensions can extend all program types 18858 * except fentry/fexit. The reason is the following. 18859 * The fentry/fexit programs are used for performance 18860 * analysis, stats and can be attached to any program 18861 * type except themselves. When extension program is 18862 * replacing XDP function it is necessary to allow 18863 * performance analysis of all functions. Both original 18864 * XDP program and its program extension. Hence 18865 * attaching fentry/fexit to BPF_PROG_TYPE_EXT is 18866 * allowed. If extending of fentry/fexit was allowed it 18867 * would be possible to create long call chain 18868 * fentry->extension->fentry->extension beyond 18869 * reasonable stack size. Hence extending fentry is not 18870 * allowed. 18871 */ 18872 bpf_log(log, "Cannot extend fentry/fexit\n"); 18873 return -EINVAL; 18874 } 18875 } else { 18876 if (prog_extension) { 18877 bpf_log(log, "Cannot replace kernel functions\n"); 18878 return -EINVAL; 18879 } 18880 } 18881 18882 switch (prog->expected_attach_type) { 18883 case BPF_TRACE_RAW_TP: 18884 if (tgt_prog) { 18885 bpf_log(log, 18886 "Only FENTRY/FEXIT progs are attachable to another BPF prog\n"); 18887 return -EINVAL; 18888 } 18889 if (!btf_type_is_typedef(t)) { 18890 bpf_log(log, "attach_btf_id %u is not a typedef\n", 18891 btf_id); 18892 return -EINVAL; 18893 } 18894 if (strncmp(prefix, tname, sizeof(prefix) - 1)) { 18895 bpf_log(log, "attach_btf_id %u points to wrong type name %s\n", 18896 btf_id, tname); 18897 return -EINVAL; 18898 } 18899 tname += sizeof(prefix) - 1; 18900 t = btf_type_by_id(btf, t->type); 18901 if (!btf_type_is_ptr(t)) 18902 /* should never happen in valid vmlinux build */ 18903 return -EINVAL; 18904 t = btf_type_by_id(btf, t->type); 18905 if (!btf_type_is_func_proto(t)) 18906 /* should never happen in valid vmlinux build */ 18907 return -EINVAL; 18908 18909 break; 18910 case BPF_TRACE_ITER: 18911 if (!btf_type_is_func(t)) { 18912 bpf_log(log, "attach_btf_id %u is not a function\n", 18913 btf_id); 18914 return -EINVAL; 18915 } 18916 t = btf_type_by_id(btf, t->type); 18917 if (!btf_type_is_func_proto(t)) 18918 return -EINVAL; 18919 ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel); 18920 if (ret) 18921 return ret; 18922 break; 18923 default: 18924 if (!prog_extension) 18925 return -EINVAL; 18926 fallthrough; 18927 case BPF_MODIFY_RETURN: 18928 case BPF_LSM_MAC: 18929 case BPF_LSM_CGROUP: 18930 case BPF_TRACE_FENTRY: 18931 case BPF_TRACE_FEXIT: 18932 if (!btf_type_is_func(t)) { 18933 bpf_log(log, "attach_btf_id %u is not a function\n", 18934 btf_id); 18935 return -EINVAL; 18936 } 18937 if (prog_extension && 18938 btf_check_type_match(log, prog, btf, t)) 18939 return -EINVAL; 18940 t = btf_type_by_id(btf, t->type); 18941 if (!btf_type_is_func_proto(t)) 18942 return -EINVAL; 18943 18944 if ((prog->aux->saved_dst_prog_type || prog->aux->saved_dst_attach_type) && 18945 (!tgt_prog || prog->aux->saved_dst_prog_type != tgt_prog->type || 18946 prog->aux->saved_dst_attach_type != tgt_prog->expected_attach_type)) 18947 return -EINVAL; 18948 18949 if (tgt_prog && conservative) 18950 t = NULL; 18951 18952 ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel); 18953 if (ret < 0) 18954 return ret; 18955 18956 if (tgt_prog) { 18957 if (subprog == 0) 18958 addr = (long) tgt_prog->bpf_func; 18959 else 18960 addr = (long) tgt_prog->aux->func[subprog]->bpf_func; 18961 } else { 18962 if (btf_is_module(btf)) { 18963 mod = btf_try_get_module(btf); 18964 if (mod) 18965 addr = find_kallsyms_symbol_value(mod, tname); 18966 else 18967 addr = 0; 18968 } else { 18969 addr = kallsyms_lookup_name(tname); 18970 } 18971 if (!addr) { 18972 module_put(mod); 18973 bpf_log(log, 18974 "The address of function %s cannot be found\n", 18975 tname); 18976 return -ENOENT; 18977 } 18978 } 18979 18980 if (prog->aux->sleepable) { 18981 ret = -EINVAL; 18982 switch (prog->type) { 18983 case BPF_PROG_TYPE_TRACING: 18984 18985 /* fentry/fexit/fmod_ret progs can be sleepable if they are 18986 * attached to ALLOW_ERROR_INJECTION and are not in denylist. 18987 */ 18988 if (!check_non_sleepable_error_inject(btf_id) && 18989 within_error_injection_list(addr)) 18990 ret = 0; 18991 /* fentry/fexit/fmod_ret progs can also be sleepable if they are 18992 * in the fmodret id set with the KF_SLEEPABLE flag. 18993 */ 18994 else { 18995 u32 *flags = btf_kfunc_is_modify_return(btf, btf_id); 18996 18997 if (flags && (*flags & KF_SLEEPABLE)) 18998 ret = 0; 18999 } 19000 break; 19001 case BPF_PROG_TYPE_LSM: 19002 /* LSM progs check that they are attached to bpf_lsm_*() funcs. 19003 * Only some of them are sleepable. 19004 */ 19005 if (bpf_lsm_is_sleepable_hook(btf_id)) 19006 ret = 0; 19007 break; 19008 default: 19009 break; 19010 } 19011 if (ret) { 19012 module_put(mod); 19013 bpf_log(log, "%s is not sleepable\n", tname); 19014 return ret; 19015 } 19016 } else if (prog->expected_attach_type == BPF_MODIFY_RETURN) { 19017 if (tgt_prog) { 19018 module_put(mod); 19019 bpf_log(log, "can't modify return codes of BPF programs\n"); 19020 return -EINVAL; 19021 } 19022 ret = -EINVAL; 19023 if (btf_kfunc_is_modify_return(btf, btf_id) || 19024 !check_attach_modify_return(addr, tname)) 19025 ret = 0; 19026 if (ret) { 19027 module_put(mod); 19028 bpf_log(log, "%s() is not modifiable\n", tname); 19029 return ret; 19030 } 19031 } 19032 19033 break; 19034 } 19035 tgt_info->tgt_addr = addr; 19036 tgt_info->tgt_name = tname; 19037 tgt_info->tgt_type = t; 19038 tgt_info->tgt_mod = mod; 19039 return 0; 19040 } 19041 19042 BTF_SET_START(btf_id_deny) 19043 BTF_ID_UNUSED 19044 #ifdef CONFIG_SMP 19045 BTF_ID(func, migrate_disable) 19046 BTF_ID(func, migrate_enable) 19047 #endif 19048 #if !defined CONFIG_PREEMPT_RCU && !defined CONFIG_TINY_RCU 19049 BTF_ID(func, rcu_read_unlock_strict) 19050 #endif 19051 #if defined(CONFIG_DEBUG_PREEMPT) || defined(CONFIG_TRACE_PREEMPT_TOGGLE) 19052 BTF_ID(func, preempt_count_add) 19053 BTF_ID(func, preempt_count_sub) 19054 #endif 19055 #ifdef CONFIG_PREEMPT_RCU 19056 BTF_ID(func, __rcu_read_lock) 19057 BTF_ID(func, __rcu_read_unlock) 19058 #endif 19059 BTF_SET_END(btf_id_deny) 19060 19061 static bool can_be_sleepable(struct bpf_prog *prog) 19062 { 19063 if (prog->type == BPF_PROG_TYPE_TRACING) { 19064 switch (prog->expected_attach_type) { 19065 case BPF_TRACE_FENTRY: 19066 case BPF_TRACE_FEXIT: 19067 case BPF_MODIFY_RETURN: 19068 case BPF_TRACE_ITER: 19069 return true; 19070 default: 19071 return false; 19072 } 19073 } 19074 return prog->type == BPF_PROG_TYPE_LSM || 19075 prog->type == BPF_PROG_TYPE_KPROBE /* only for uprobes */ || 19076 prog->type == BPF_PROG_TYPE_STRUCT_OPS; 19077 } 19078 19079 static int check_attach_btf_id(struct bpf_verifier_env *env) 19080 { 19081 struct bpf_prog *prog = env->prog; 19082 struct bpf_prog *tgt_prog = prog->aux->dst_prog; 19083 struct bpf_attach_target_info tgt_info = {}; 19084 u32 btf_id = prog->aux->attach_btf_id; 19085 struct bpf_trampoline *tr; 19086 int ret; 19087 u64 key; 19088 19089 if (prog->type == BPF_PROG_TYPE_SYSCALL) { 19090 if (prog->aux->sleepable) 19091 /* attach_btf_id checked to be zero already */ 19092 return 0; 19093 verbose(env, "Syscall programs can only be sleepable\n"); 19094 return -EINVAL; 19095 } 19096 19097 if (prog->aux->sleepable && !can_be_sleepable(prog)) { 19098 verbose(env, "Only fentry/fexit/fmod_ret, lsm, iter, uprobe, and struct_ops programs can be sleepable\n"); 19099 return -EINVAL; 19100 } 19101 19102 if (prog->type == BPF_PROG_TYPE_STRUCT_OPS) 19103 return check_struct_ops_btf_id(env); 19104 19105 if (prog->type != BPF_PROG_TYPE_TRACING && 19106 prog->type != BPF_PROG_TYPE_LSM && 19107 prog->type != BPF_PROG_TYPE_EXT) 19108 return 0; 19109 19110 ret = bpf_check_attach_target(&env->log, prog, tgt_prog, btf_id, &tgt_info); 19111 if (ret) 19112 return ret; 19113 19114 if (tgt_prog && prog->type == BPF_PROG_TYPE_EXT) { 19115 /* to make freplace equivalent to their targets, they need to 19116 * inherit env->ops and expected_attach_type for the rest of the 19117 * verification 19118 */ 19119 env->ops = bpf_verifier_ops[tgt_prog->type]; 19120 prog->expected_attach_type = tgt_prog->expected_attach_type; 19121 } 19122 19123 /* store info about the attachment target that will be used later */ 19124 prog->aux->attach_func_proto = tgt_info.tgt_type; 19125 prog->aux->attach_func_name = tgt_info.tgt_name; 19126 prog->aux->mod = tgt_info.tgt_mod; 19127 19128 if (tgt_prog) { 19129 prog->aux->saved_dst_prog_type = tgt_prog->type; 19130 prog->aux->saved_dst_attach_type = tgt_prog->expected_attach_type; 19131 } 19132 19133 if (prog->expected_attach_type == BPF_TRACE_RAW_TP) { 19134 prog->aux->attach_btf_trace = true; 19135 return 0; 19136 } else if (prog->expected_attach_type == BPF_TRACE_ITER) { 19137 if (!bpf_iter_prog_supported(prog)) 19138 return -EINVAL; 19139 return 0; 19140 } 19141 19142 if (prog->type == BPF_PROG_TYPE_LSM) { 19143 ret = bpf_lsm_verify_prog(&env->log, prog); 19144 if (ret < 0) 19145 return ret; 19146 } else if (prog->type == BPF_PROG_TYPE_TRACING && 19147 btf_id_set_contains(&btf_id_deny, btf_id)) { 19148 return -EINVAL; 19149 } 19150 19151 key = bpf_trampoline_compute_key(tgt_prog, prog->aux->attach_btf, btf_id); 19152 tr = bpf_trampoline_get(key, &tgt_info); 19153 if (!tr) 19154 return -ENOMEM; 19155 19156 prog->aux->dst_trampoline = tr; 19157 return 0; 19158 } 19159 19160 struct btf *bpf_get_btf_vmlinux(void) 19161 { 19162 if (!btf_vmlinux && IS_ENABLED(CONFIG_DEBUG_INFO_BTF)) { 19163 mutex_lock(&bpf_verifier_lock); 19164 if (!btf_vmlinux) 19165 btf_vmlinux = btf_parse_vmlinux(); 19166 mutex_unlock(&bpf_verifier_lock); 19167 } 19168 return btf_vmlinux; 19169 } 19170 19171 int bpf_check(struct bpf_prog **prog, union bpf_attr *attr, bpfptr_t uattr, __u32 uattr_size) 19172 { 19173 u64 start_time = ktime_get_ns(); 19174 struct bpf_verifier_env *env; 19175 int i, len, ret = -EINVAL, err; 19176 u32 log_true_size; 19177 bool is_priv; 19178 19179 /* no program is valid */ 19180 if (ARRAY_SIZE(bpf_verifier_ops) == 0) 19181 return -EINVAL; 19182 19183 /* 'struct bpf_verifier_env' can be global, but since it's not small, 19184 * allocate/free it every time bpf_check() is called 19185 */ 19186 env = kzalloc(sizeof(struct bpf_verifier_env), GFP_KERNEL); 19187 if (!env) 19188 return -ENOMEM; 19189 19190 env->bt.env = env; 19191 19192 len = (*prog)->len; 19193 env->insn_aux_data = 19194 vzalloc(array_size(sizeof(struct bpf_insn_aux_data), len)); 19195 ret = -ENOMEM; 19196 if (!env->insn_aux_data) 19197 goto err_free_env; 19198 for (i = 0; i < len; i++) 19199 env->insn_aux_data[i].orig_idx = i; 19200 env->prog = *prog; 19201 env->ops = bpf_verifier_ops[env->prog->type]; 19202 env->fd_array = make_bpfptr(attr->fd_array, uattr.is_kernel); 19203 is_priv = bpf_capable(); 19204 19205 bpf_get_btf_vmlinux(); 19206 19207 /* grab the mutex to protect few globals used by verifier */ 19208 if (!is_priv) 19209 mutex_lock(&bpf_verifier_lock); 19210 19211 /* user could have requested verbose verifier output 19212 * and supplied buffer to store the verification trace 19213 */ 19214 ret = bpf_vlog_init(&env->log, attr->log_level, 19215 (char __user *) (unsigned long) attr->log_buf, 19216 attr->log_size); 19217 if (ret) 19218 goto err_unlock; 19219 19220 mark_verifier_state_clean(env); 19221 19222 if (IS_ERR(btf_vmlinux)) { 19223 /* Either gcc or pahole or kernel are broken. */ 19224 verbose(env, "in-kernel BTF is malformed\n"); 19225 ret = PTR_ERR(btf_vmlinux); 19226 goto skip_full_check; 19227 } 19228 19229 env->strict_alignment = !!(attr->prog_flags & BPF_F_STRICT_ALIGNMENT); 19230 if (!IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS)) 19231 env->strict_alignment = true; 19232 if (attr->prog_flags & BPF_F_ANY_ALIGNMENT) 19233 env->strict_alignment = false; 19234 19235 env->allow_ptr_leaks = bpf_allow_ptr_leaks(); 19236 env->allow_uninit_stack = bpf_allow_uninit_stack(); 19237 env->bypass_spec_v1 = bpf_bypass_spec_v1(); 19238 env->bypass_spec_v4 = bpf_bypass_spec_v4(); 19239 env->bpf_capable = bpf_capable(); 19240 19241 if (is_priv) 19242 env->test_state_freq = attr->prog_flags & BPF_F_TEST_STATE_FREQ; 19243 19244 env->explored_states = kvcalloc(state_htab_size(env), 19245 sizeof(struct bpf_verifier_state_list *), 19246 GFP_USER); 19247 ret = -ENOMEM; 19248 if (!env->explored_states) 19249 goto skip_full_check; 19250 19251 ret = add_subprog_and_kfunc(env); 19252 if (ret < 0) 19253 goto skip_full_check; 19254 19255 ret = check_subprogs(env); 19256 if (ret < 0) 19257 goto skip_full_check; 19258 19259 ret = check_btf_info(env, attr, uattr); 19260 if (ret < 0) 19261 goto skip_full_check; 19262 19263 ret = check_attach_btf_id(env); 19264 if (ret) 19265 goto skip_full_check; 19266 19267 ret = resolve_pseudo_ldimm64(env); 19268 if (ret < 0) 19269 goto skip_full_check; 19270 19271 if (bpf_prog_is_offloaded(env->prog->aux)) { 19272 ret = bpf_prog_offload_verifier_prep(env->prog); 19273 if (ret) 19274 goto skip_full_check; 19275 } 19276 19277 ret = check_cfg(env); 19278 if (ret < 0) 19279 goto skip_full_check; 19280 19281 ret = do_check_subprogs(env); 19282 ret = ret ?: do_check_main(env); 19283 19284 if (ret == 0 && bpf_prog_is_offloaded(env->prog->aux)) 19285 ret = bpf_prog_offload_finalize(env); 19286 19287 skip_full_check: 19288 kvfree(env->explored_states); 19289 19290 if (ret == 0) 19291 ret = check_max_stack_depth(env); 19292 19293 /* instruction rewrites happen after this point */ 19294 if (ret == 0) 19295 ret = optimize_bpf_loop(env); 19296 19297 if (is_priv) { 19298 if (ret == 0) 19299 opt_hard_wire_dead_code_branches(env); 19300 if (ret == 0) 19301 ret = opt_remove_dead_code(env); 19302 if (ret == 0) 19303 ret = opt_remove_nops(env); 19304 } else { 19305 if (ret == 0) 19306 sanitize_dead_code(env); 19307 } 19308 19309 if (ret == 0) 19310 /* program is valid, convert *(u32*)(ctx + off) accesses */ 19311 ret = convert_ctx_accesses(env); 19312 19313 if (ret == 0) 19314 ret = do_misc_fixups(env); 19315 19316 /* do 32-bit optimization after insn patching has done so those patched 19317 * insns could be handled correctly. 19318 */ 19319 if (ret == 0 && !bpf_prog_is_offloaded(env->prog->aux)) { 19320 ret = opt_subreg_zext_lo32_rnd_hi32(env, attr); 19321 env->prog->aux->verifier_zext = bpf_jit_needs_zext() ? !ret 19322 : false; 19323 } 19324 19325 if (ret == 0) 19326 ret = fixup_call_args(env); 19327 19328 env->verification_time = ktime_get_ns() - start_time; 19329 print_verification_stats(env); 19330 env->prog->aux->verified_insns = env->insn_processed; 19331 19332 /* preserve original error even if log finalization is successful */ 19333 err = bpf_vlog_finalize(&env->log, &log_true_size); 19334 if (err) 19335 ret = err; 19336 19337 if (uattr_size >= offsetofend(union bpf_attr, log_true_size) && 19338 copy_to_bpfptr_offset(uattr, offsetof(union bpf_attr, log_true_size), 19339 &log_true_size, sizeof(log_true_size))) { 19340 ret = -EFAULT; 19341 goto err_release_maps; 19342 } 19343 19344 if (ret) 19345 goto err_release_maps; 19346 19347 if (env->used_map_cnt) { 19348 /* if program passed verifier, update used_maps in bpf_prog_info */ 19349 env->prog->aux->used_maps = kmalloc_array(env->used_map_cnt, 19350 sizeof(env->used_maps[0]), 19351 GFP_KERNEL); 19352 19353 if (!env->prog->aux->used_maps) { 19354 ret = -ENOMEM; 19355 goto err_release_maps; 19356 } 19357 19358 memcpy(env->prog->aux->used_maps, env->used_maps, 19359 sizeof(env->used_maps[0]) * env->used_map_cnt); 19360 env->prog->aux->used_map_cnt = env->used_map_cnt; 19361 } 19362 if (env->used_btf_cnt) { 19363 /* if program passed verifier, update used_btfs in bpf_prog_aux */ 19364 env->prog->aux->used_btfs = kmalloc_array(env->used_btf_cnt, 19365 sizeof(env->used_btfs[0]), 19366 GFP_KERNEL); 19367 if (!env->prog->aux->used_btfs) { 19368 ret = -ENOMEM; 19369 goto err_release_maps; 19370 } 19371 19372 memcpy(env->prog->aux->used_btfs, env->used_btfs, 19373 sizeof(env->used_btfs[0]) * env->used_btf_cnt); 19374 env->prog->aux->used_btf_cnt = env->used_btf_cnt; 19375 } 19376 if (env->used_map_cnt || env->used_btf_cnt) { 19377 /* program is valid. Convert pseudo bpf_ld_imm64 into generic 19378 * bpf_ld_imm64 instructions 19379 */ 19380 convert_pseudo_ld_imm64(env); 19381 } 19382 19383 adjust_btf_func(env); 19384 19385 err_release_maps: 19386 if (!env->prog->aux->used_maps) 19387 /* if we didn't copy map pointers into bpf_prog_info, release 19388 * them now. Otherwise free_used_maps() will release them. 19389 */ 19390 release_maps(env); 19391 if (!env->prog->aux->used_btfs) 19392 release_btfs(env); 19393 19394 /* extension progs temporarily inherit the attach_type of their targets 19395 for verification purposes, so set it back to zero before returning 19396 */ 19397 if (env->prog->type == BPF_PROG_TYPE_EXT) 19398 env->prog->expected_attach_type = 0; 19399 19400 *prog = env->prog; 19401 err_unlock: 19402 if (!is_priv) 19403 mutex_unlock(&bpf_verifier_lock); 19404 vfree(env->insn_aux_data); 19405 err_free_env: 19406 kfree(env); 19407 return ret; 19408 } 19409