1 // SPDX-License-Identifier: GPL-2.0-only 2 /* Copyright (c) 2011-2014 PLUMgrid, http://plumgrid.com 3 * Copyright (c) 2016 Facebook 4 * Copyright (c) 2018 Covalent IO, Inc. http://covalent.io 5 */ 6 #include <uapi/linux/btf.h> 7 #include <linux/bpf-cgroup.h> 8 #include <linux/kernel.h> 9 #include <linux/types.h> 10 #include <linux/slab.h> 11 #include <linux/bpf.h> 12 #include <linux/btf.h> 13 #include <linux/bpf_verifier.h> 14 #include <linux/filter.h> 15 #include <net/netlink.h> 16 #include <linux/file.h> 17 #include <linux/vmalloc.h> 18 #include <linux/stringify.h> 19 #include <linux/bsearch.h> 20 #include <linux/sort.h> 21 #include <linux/perf_event.h> 22 #include <linux/ctype.h> 23 #include <linux/error-injection.h> 24 #include <linux/bpf_lsm.h> 25 #include <linux/btf_ids.h> 26 #include <linux/poison.h> 27 #include <linux/module.h> 28 #include <linux/cpumask.h> 29 #include <net/xdp.h> 30 31 #include "disasm.h" 32 33 static const struct bpf_verifier_ops * const bpf_verifier_ops[] = { 34 #define BPF_PROG_TYPE(_id, _name, prog_ctx_type, kern_ctx_type) \ 35 [_id] = & _name ## _verifier_ops, 36 #define BPF_MAP_TYPE(_id, _ops) 37 #define BPF_LINK_TYPE(_id, _name) 38 #include <linux/bpf_types.h> 39 #undef BPF_PROG_TYPE 40 #undef BPF_MAP_TYPE 41 #undef BPF_LINK_TYPE 42 }; 43 44 /* bpf_check() is a static code analyzer that walks eBPF program 45 * instruction by instruction and updates register/stack state. 46 * All paths of conditional branches are analyzed until 'bpf_exit' insn. 47 * 48 * The first pass is depth-first-search to check that the program is a DAG. 49 * It rejects the following programs: 50 * - larger than BPF_MAXINSNS insns 51 * - if loop is present (detected via back-edge) 52 * - unreachable insns exist (shouldn't be a forest. program = one function) 53 * - out of bounds or malformed jumps 54 * The second pass is all possible path descent from the 1st insn. 55 * Since it's analyzing all paths through the program, the length of the 56 * analysis is limited to 64k insn, which may be hit even if total number of 57 * insn is less then 4K, but there are too many branches that change stack/regs. 58 * Number of 'branches to be analyzed' is limited to 1k 59 * 60 * On entry to each instruction, each register has a type, and the instruction 61 * changes the types of the registers depending on instruction semantics. 62 * If instruction is BPF_MOV64_REG(BPF_REG_1, BPF_REG_5), then type of R5 is 63 * copied to R1. 64 * 65 * All registers are 64-bit. 66 * R0 - return register 67 * R1-R5 argument passing registers 68 * R6-R9 callee saved registers 69 * R10 - frame pointer read-only 70 * 71 * At the start of BPF program the register R1 contains a pointer to bpf_context 72 * and has type PTR_TO_CTX. 73 * 74 * Verifier tracks arithmetic operations on pointers in case: 75 * BPF_MOV64_REG(BPF_REG_1, BPF_REG_10), 76 * BPF_ALU64_IMM(BPF_ADD, BPF_REG_1, -20), 77 * 1st insn copies R10 (which has FRAME_PTR) type into R1 78 * and 2nd arithmetic instruction is pattern matched to recognize 79 * that it wants to construct a pointer to some element within stack. 80 * So after 2nd insn, the register R1 has type PTR_TO_STACK 81 * (and -20 constant is saved for further stack bounds checking). 82 * Meaning that this reg is a pointer to stack plus known immediate constant. 83 * 84 * Most of the time the registers have SCALAR_VALUE type, which 85 * means the register has some value, but it's not a valid pointer. 86 * (like pointer plus pointer becomes SCALAR_VALUE type) 87 * 88 * When verifier sees load or store instructions the type of base register 89 * can be: PTR_TO_MAP_VALUE, PTR_TO_CTX, PTR_TO_STACK, PTR_TO_SOCKET. These are 90 * four pointer types recognized by check_mem_access() function. 91 * 92 * PTR_TO_MAP_VALUE means that this register is pointing to 'map element value' 93 * and the range of [ptr, ptr + map's value_size) is accessible. 94 * 95 * registers used to pass values to function calls are checked against 96 * function argument constraints. 97 * 98 * ARG_PTR_TO_MAP_KEY is one of such argument constraints. 99 * It means that the register type passed to this function must be 100 * PTR_TO_STACK and it will be used inside the function as 101 * 'pointer to map element key' 102 * 103 * For example the argument constraints for bpf_map_lookup_elem(): 104 * .ret_type = RET_PTR_TO_MAP_VALUE_OR_NULL, 105 * .arg1_type = ARG_CONST_MAP_PTR, 106 * .arg2_type = ARG_PTR_TO_MAP_KEY, 107 * 108 * ret_type says that this function returns 'pointer to map elem value or null' 109 * function expects 1st argument to be a const pointer to 'struct bpf_map' and 110 * 2nd argument should be a pointer to stack, which will be used inside 111 * the helper function as a pointer to map element key. 112 * 113 * On the kernel side the helper function looks like: 114 * u64 bpf_map_lookup_elem(u64 r1, u64 r2, u64 r3, u64 r4, u64 r5) 115 * { 116 * struct bpf_map *map = (struct bpf_map *) (unsigned long) r1; 117 * void *key = (void *) (unsigned long) r2; 118 * void *value; 119 * 120 * here kernel can access 'key' and 'map' pointers safely, knowing that 121 * [key, key + map->key_size) bytes are valid and were initialized on 122 * the stack of eBPF program. 123 * } 124 * 125 * Corresponding eBPF program may look like: 126 * BPF_MOV64_REG(BPF_REG_2, BPF_REG_10), // after this insn R2 type is FRAME_PTR 127 * BPF_ALU64_IMM(BPF_ADD, BPF_REG_2, -4), // after this insn R2 type is PTR_TO_STACK 128 * BPF_LD_MAP_FD(BPF_REG_1, map_fd), // after this insn R1 type is CONST_PTR_TO_MAP 129 * BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0, BPF_FUNC_map_lookup_elem), 130 * here verifier looks at prototype of map_lookup_elem() and sees: 131 * .arg1_type == ARG_CONST_MAP_PTR and R1->type == CONST_PTR_TO_MAP, which is ok, 132 * Now verifier knows that this map has key of R1->map_ptr->key_size bytes 133 * 134 * Then .arg2_type == ARG_PTR_TO_MAP_KEY and R2->type == PTR_TO_STACK, ok so far, 135 * Now verifier checks that [R2, R2 + map's key_size) are within stack limits 136 * and were initialized prior to this call. 137 * If it's ok, then verifier allows this BPF_CALL insn and looks at 138 * .ret_type which is RET_PTR_TO_MAP_VALUE_OR_NULL, so it sets 139 * R0->type = PTR_TO_MAP_VALUE_OR_NULL which means bpf_map_lookup_elem() function 140 * returns either pointer to map value or NULL. 141 * 142 * When type PTR_TO_MAP_VALUE_OR_NULL passes through 'if (reg != 0) goto +off' 143 * insn, the register holding that pointer in the true branch changes state to 144 * PTR_TO_MAP_VALUE and the same register changes state to CONST_IMM in the false 145 * branch. See check_cond_jmp_op(). 146 * 147 * After the call R0 is set to return type of the function and registers R1-R5 148 * are set to NOT_INIT to indicate that they are no longer readable. 149 * 150 * The following reference types represent a potential reference to a kernel 151 * resource which, after first being allocated, must be checked and freed by 152 * the BPF program: 153 * - PTR_TO_SOCKET_OR_NULL, PTR_TO_SOCKET 154 * 155 * When the verifier sees a helper call return a reference type, it allocates a 156 * pointer id for the reference and stores it in the current function state. 157 * Similar to the way that PTR_TO_MAP_VALUE_OR_NULL is converted into 158 * PTR_TO_MAP_VALUE, PTR_TO_SOCKET_OR_NULL becomes PTR_TO_SOCKET when the type 159 * passes through a NULL-check conditional. For the branch wherein the state is 160 * changed to CONST_IMM, the verifier releases the reference. 161 * 162 * For each helper function that allocates a reference, such as 163 * bpf_sk_lookup_tcp(), there is a corresponding release function, such as 164 * bpf_sk_release(). When a reference type passes into the release function, 165 * the verifier also releases the reference. If any unchecked or unreleased 166 * reference remains at the end of the program, the verifier rejects it. 167 */ 168 169 /* verifier_state + insn_idx are pushed to stack when branch is encountered */ 170 struct bpf_verifier_stack_elem { 171 /* verifer state is 'st' 172 * before processing instruction 'insn_idx' 173 * and after processing instruction 'prev_insn_idx' 174 */ 175 struct bpf_verifier_state st; 176 int insn_idx; 177 int prev_insn_idx; 178 struct bpf_verifier_stack_elem *next; 179 /* length of verifier log at the time this state was pushed on stack */ 180 u32 log_pos; 181 }; 182 183 #define BPF_COMPLEXITY_LIMIT_JMP_SEQ 8192 184 #define BPF_COMPLEXITY_LIMIT_STATES 64 185 186 #define BPF_MAP_KEY_POISON (1ULL << 63) 187 #define BPF_MAP_KEY_SEEN (1ULL << 62) 188 189 #define BPF_MAP_PTR_UNPRIV 1UL 190 #define BPF_MAP_PTR_POISON ((void *)((0xeB9FUL << 1) + \ 191 POISON_POINTER_DELTA)) 192 #define BPF_MAP_PTR(X) ((struct bpf_map *)((X) & ~BPF_MAP_PTR_UNPRIV)) 193 194 static int acquire_reference_state(struct bpf_verifier_env *env, int insn_idx); 195 static int release_reference(struct bpf_verifier_env *env, int ref_obj_id); 196 static void invalidate_non_owning_refs(struct bpf_verifier_env *env); 197 static bool in_rbtree_lock_required_cb(struct bpf_verifier_env *env); 198 static int ref_set_non_owning(struct bpf_verifier_env *env, 199 struct bpf_reg_state *reg); 200 static void specialize_kfunc(struct bpf_verifier_env *env, 201 u32 func_id, u16 offset, unsigned long *addr); 202 static bool is_trusted_reg(const struct bpf_reg_state *reg); 203 204 static bool bpf_map_ptr_poisoned(const struct bpf_insn_aux_data *aux) 205 { 206 return BPF_MAP_PTR(aux->map_ptr_state) == BPF_MAP_PTR_POISON; 207 } 208 209 static bool bpf_map_ptr_unpriv(const struct bpf_insn_aux_data *aux) 210 { 211 return aux->map_ptr_state & BPF_MAP_PTR_UNPRIV; 212 } 213 214 static void bpf_map_ptr_store(struct bpf_insn_aux_data *aux, 215 const struct bpf_map *map, bool unpriv) 216 { 217 BUILD_BUG_ON((unsigned long)BPF_MAP_PTR_POISON & BPF_MAP_PTR_UNPRIV); 218 unpriv |= bpf_map_ptr_unpriv(aux); 219 aux->map_ptr_state = (unsigned long)map | 220 (unpriv ? BPF_MAP_PTR_UNPRIV : 0UL); 221 } 222 223 static bool bpf_map_key_poisoned(const struct bpf_insn_aux_data *aux) 224 { 225 return aux->map_key_state & BPF_MAP_KEY_POISON; 226 } 227 228 static bool bpf_map_key_unseen(const struct bpf_insn_aux_data *aux) 229 { 230 return !(aux->map_key_state & BPF_MAP_KEY_SEEN); 231 } 232 233 static u64 bpf_map_key_immediate(const struct bpf_insn_aux_data *aux) 234 { 235 return aux->map_key_state & ~(BPF_MAP_KEY_SEEN | BPF_MAP_KEY_POISON); 236 } 237 238 static void bpf_map_key_store(struct bpf_insn_aux_data *aux, u64 state) 239 { 240 bool poisoned = bpf_map_key_poisoned(aux); 241 242 aux->map_key_state = state | BPF_MAP_KEY_SEEN | 243 (poisoned ? BPF_MAP_KEY_POISON : 0ULL); 244 } 245 246 static bool bpf_helper_call(const struct bpf_insn *insn) 247 { 248 return insn->code == (BPF_JMP | BPF_CALL) && 249 insn->src_reg == 0; 250 } 251 252 static bool bpf_pseudo_call(const struct bpf_insn *insn) 253 { 254 return insn->code == (BPF_JMP | BPF_CALL) && 255 insn->src_reg == BPF_PSEUDO_CALL; 256 } 257 258 static bool bpf_pseudo_kfunc_call(const struct bpf_insn *insn) 259 { 260 return insn->code == (BPF_JMP | BPF_CALL) && 261 insn->src_reg == BPF_PSEUDO_KFUNC_CALL; 262 } 263 264 struct bpf_call_arg_meta { 265 struct bpf_map *map_ptr; 266 bool raw_mode; 267 bool pkt_access; 268 u8 release_regno; 269 int regno; 270 int access_size; 271 int mem_size; 272 u64 msize_max_value; 273 int ref_obj_id; 274 int dynptr_id; 275 int map_uid; 276 int func_id; 277 struct btf *btf; 278 u32 btf_id; 279 struct btf *ret_btf; 280 u32 ret_btf_id; 281 u32 subprogno; 282 struct btf_field *kptr_field; 283 }; 284 285 struct bpf_kfunc_call_arg_meta { 286 /* In parameters */ 287 struct btf *btf; 288 u32 func_id; 289 u32 kfunc_flags; 290 const struct btf_type *func_proto; 291 const char *func_name; 292 /* Out parameters */ 293 u32 ref_obj_id; 294 u8 release_regno; 295 bool r0_rdonly; 296 u32 ret_btf_id; 297 u64 r0_size; 298 u32 subprogno; 299 struct { 300 u64 value; 301 bool found; 302 } arg_constant; 303 304 /* arg_{btf,btf_id,owning_ref} are used by kfunc-specific handling, 305 * generally to pass info about user-defined local kptr types to later 306 * verification logic 307 * bpf_obj_drop 308 * Record the local kptr type to be drop'd 309 * bpf_refcount_acquire (via KF_ARG_PTR_TO_REFCOUNTED_KPTR arg type) 310 * Record the local kptr type to be refcount_incr'd and use 311 * arg_owning_ref to determine whether refcount_acquire should be 312 * fallible 313 */ 314 struct btf *arg_btf; 315 u32 arg_btf_id; 316 bool arg_owning_ref; 317 318 struct { 319 struct btf_field *field; 320 } arg_list_head; 321 struct { 322 struct btf_field *field; 323 } arg_rbtree_root; 324 struct { 325 enum bpf_dynptr_type type; 326 u32 id; 327 u32 ref_obj_id; 328 } initialized_dynptr; 329 struct { 330 u8 spi; 331 u8 frameno; 332 } iter; 333 u64 mem_size; 334 }; 335 336 struct btf *btf_vmlinux; 337 338 static DEFINE_MUTEX(bpf_verifier_lock); 339 340 static const struct bpf_line_info * 341 find_linfo(const struct bpf_verifier_env *env, u32 insn_off) 342 { 343 const struct bpf_line_info *linfo; 344 const struct bpf_prog *prog; 345 u32 i, nr_linfo; 346 347 prog = env->prog; 348 nr_linfo = prog->aux->nr_linfo; 349 350 if (!nr_linfo || insn_off >= prog->len) 351 return NULL; 352 353 linfo = prog->aux->linfo; 354 for (i = 1; i < nr_linfo; i++) 355 if (insn_off < linfo[i].insn_off) 356 break; 357 358 return &linfo[i - 1]; 359 } 360 361 __printf(2, 3) static void verbose(void *private_data, const char *fmt, ...) 362 { 363 struct bpf_verifier_env *env = private_data; 364 va_list args; 365 366 if (!bpf_verifier_log_needed(&env->log)) 367 return; 368 369 va_start(args, fmt); 370 bpf_verifier_vlog(&env->log, fmt, args); 371 va_end(args); 372 } 373 374 static const char *ltrim(const char *s) 375 { 376 while (isspace(*s)) 377 s++; 378 379 return s; 380 } 381 382 __printf(3, 4) static void verbose_linfo(struct bpf_verifier_env *env, 383 u32 insn_off, 384 const char *prefix_fmt, ...) 385 { 386 const struct bpf_line_info *linfo; 387 388 if (!bpf_verifier_log_needed(&env->log)) 389 return; 390 391 linfo = find_linfo(env, insn_off); 392 if (!linfo || linfo == env->prev_linfo) 393 return; 394 395 if (prefix_fmt) { 396 va_list args; 397 398 va_start(args, prefix_fmt); 399 bpf_verifier_vlog(&env->log, prefix_fmt, args); 400 va_end(args); 401 } 402 403 verbose(env, "%s\n", 404 ltrim(btf_name_by_offset(env->prog->aux->btf, 405 linfo->line_off))); 406 407 env->prev_linfo = linfo; 408 } 409 410 static void verbose_invalid_scalar(struct bpf_verifier_env *env, 411 struct bpf_reg_state *reg, 412 struct tnum *range, const char *ctx, 413 const char *reg_name) 414 { 415 char tn_buf[48]; 416 417 verbose(env, "At %s the register %s ", ctx, reg_name); 418 if (!tnum_is_unknown(reg->var_off)) { 419 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 420 verbose(env, "has value %s", tn_buf); 421 } else { 422 verbose(env, "has unknown scalar value"); 423 } 424 tnum_strn(tn_buf, sizeof(tn_buf), *range); 425 verbose(env, " should have been in %s\n", tn_buf); 426 } 427 428 static bool type_is_pkt_pointer(enum bpf_reg_type type) 429 { 430 type = base_type(type); 431 return type == PTR_TO_PACKET || 432 type == PTR_TO_PACKET_META; 433 } 434 435 static bool type_is_sk_pointer(enum bpf_reg_type type) 436 { 437 return type == PTR_TO_SOCKET || 438 type == PTR_TO_SOCK_COMMON || 439 type == PTR_TO_TCP_SOCK || 440 type == PTR_TO_XDP_SOCK; 441 } 442 443 static bool type_may_be_null(u32 type) 444 { 445 return type & PTR_MAYBE_NULL; 446 } 447 448 static bool reg_not_null(const struct bpf_reg_state *reg) 449 { 450 enum bpf_reg_type type; 451 452 type = reg->type; 453 if (type_may_be_null(type)) 454 return false; 455 456 type = base_type(type); 457 return type == PTR_TO_SOCKET || 458 type == PTR_TO_TCP_SOCK || 459 type == PTR_TO_MAP_VALUE || 460 type == PTR_TO_MAP_KEY || 461 type == PTR_TO_SOCK_COMMON || 462 (type == PTR_TO_BTF_ID && is_trusted_reg(reg)) || 463 type == PTR_TO_MEM; 464 } 465 466 static bool type_is_ptr_alloc_obj(u32 type) 467 { 468 return base_type(type) == PTR_TO_BTF_ID && type_flag(type) & MEM_ALLOC; 469 } 470 471 static bool type_is_non_owning_ref(u32 type) 472 { 473 return type_is_ptr_alloc_obj(type) && type_flag(type) & NON_OWN_REF; 474 } 475 476 static struct btf_record *reg_btf_record(const struct bpf_reg_state *reg) 477 { 478 struct btf_record *rec = NULL; 479 struct btf_struct_meta *meta; 480 481 if (reg->type == PTR_TO_MAP_VALUE) { 482 rec = reg->map_ptr->record; 483 } else if (type_is_ptr_alloc_obj(reg->type)) { 484 meta = btf_find_struct_meta(reg->btf, reg->btf_id); 485 if (meta) 486 rec = meta->record; 487 } 488 return rec; 489 } 490 491 static bool subprog_is_global(const struct bpf_verifier_env *env, int subprog) 492 { 493 struct bpf_func_info_aux *aux = env->prog->aux->func_info_aux; 494 495 return aux && aux[subprog].linkage == BTF_FUNC_GLOBAL; 496 } 497 498 static bool reg_may_point_to_spin_lock(const struct bpf_reg_state *reg) 499 { 500 return btf_record_has_field(reg_btf_record(reg), BPF_SPIN_LOCK); 501 } 502 503 static bool type_is_rdonly_mem(u32 type) 504 { 505 return type & MEM_RDONLY; 506 } 507 508 static bool is_acquire_function(enum bpf_func_id func_id, 509 const struct bpf_map *map) 510 { 511 enum bpf_map_type map_type = map ? map->map_type : BPF_MAP_TYPE_UNSPEC; 512 513 if (func_id == BPF_FUNC_sk_lookup_tcp || 514 func_id == BPF_FUNC_sk_lookup_udp || 515 func_id == BPF_FUNC_skc_lookup_tcp || 516 func_id == BPF_FUNC_ringbuf_reserve || 517 func_id == BPF_FUNC_kptr_xchg) 518 return true; 519 520 if (func_id == BPF_FUNC_map_lookup_elem && 521 (map_type == BPF_MAP_TYPE_SOCKMAP || 522 map_type == BPF_MAP_TYPE_SOCKHASH)) 523 return true; 524 525 return false; 526 } 527 528 static bool is_ptr_cast_function(enum bpf_func_id func_id) 529 { 530 return func_id == BPF_FUNC_tcp_sock || 531 func_id == BPF_FUNC_sk_fullsock || 532 func_id == BPF_FUNC_skc_to_tcp_sock || 533 func_id == BPF_FUNC_skc_to_tcp6_sock || 534 func_id == BPF_FUNC_skc_to_udp6_sock || 535 func_id == BPF_FUNC_skc_to_mptcp_sock || 536 func_id == BPF_FUNC_skc_to_tcp_timewait_sock || 537 func_id == BPF_FUNC_skc_to_tcp_request_sock; 538 } 539 540 static bool is_dynptr_ref_function(enum bpf_func_id func_id) 541 { 542 return func_id == BPF_FUNC_dynptr_data; 543 } 544 545 static bool is_sync_callback_calling_kfunc(u32 btf_id); 546 547 static bool is_sync_callback_calling_function(enum bpf_func_id func_id) 548 { 549 return func_id == BPF_FUNC_for_each_map_elem || 550 func_id == BPF_FUNC_find_vma || 551 func_id == BPF_FUNC_loop || 552 func_id == BPF_FUNC_user_ringbuf_drain; 553 } 554 555 static bool is_async_callback_calling_function(enum bpf_func_id func_id) 556 { 557 return func_id == BPF_FUNC_timer_set_callback; 558 } 559 560 static bool is_callback_calling_function(enum bpf_func_id func_id) 561 { 562 return is_sync_callback_calling_function(func_id) || 563 is_async_callback_calling_function(func_id); 564 } 565 566 static bool is_sync_callback_calling_insn(struct bpf_insn *insn) 567 { 568 return (bpf_helper_call(insn) && is_sync_callback_calling_function(insn->imm)) || 569 (bpf_pseudo_kfunc_call(insn) && is_sync_callback_calling_kfunc(insn->imm)); 570 } 571 572 static bool is_storage_get_function(enum bpf_func_id func_id) 573 { 574 return func_id == BPF_FUNC_sk_storage_get || 575 func_id == BPF_FUNC_inode_storage_get || 576 func_id == BPF_FUNC_task_storage_get || 577 func_id == BPF_FUNC_cgrp_storage_get; 578 } 579 580 static bool helper_multiple_ref_obj_use(enum bpf_func_id func_id, 581 const struct bpf_map *map) 582 { 583 int ref_obj_uses = 0; 584 585 if (is_ptr_cast_function(func_id)) 586 ref_obj_uses++; 587 if (is_acquire_function(func_id, map)) 588 ref_obj_uses++; 589 if (is_dynptr_ref_function(func_id)) 590 ref_obj_uses++; 591 592 return ref_obj_uses > 1; 593 } 594 595 static bool is_cmpxchg_insn(const struct bpf_insn *insn) 596 { 597 return BPF_CLASS(insn->code) == BPF_STX && 598 BPF_MODE(insn->code) == BPF_ATOMIC && 599 insn->imm == BPF_CMPXCHG; 600 } 601 602 /* string representation of 'enum bpf_reg_type' 603 * 604 * Note that reg_type_str() can not appear more than once in a single verbose() 605 * statement. 606 */ 607 static const char *reg_type_str(struct bpf_verifier_env *env, 608 enum bpf_reg_type type) 609 { 610 char postfix[16] = {0}, prefix[64] = {0}; 611 static const char * const str[] = { 612 [NOT_INIT] = "?", 613 [SCALAR_VALUE] = "scalar", 614 [PTR_TO_CTX] = "ctx", 615 [CONST_PTR_TO_MAP] = "map_ptr", 616 [PTR_TO_MAP_VALUE] = "map_value", 617 [PTR_TO_STACK] = "fp", 618 [PTR_TO_PACKET] = "pkt", 619 [PTR_TO_PACKET_META] = "pkt_meta", 620 [PTR_TO_PACKET_END] = "pkt_end", 621 [PTR_TO_FLOW_KEYS] = "flow_keys", 622 [PTR_TO_SOCKET] = "sock", 623 [PTR_TO_SOCK_COMMON] = "sock_common", 624 [PTR_TO_TCP_SOCK] = "tcp_sock", 625 [PTR_TO_TP_BUFFER] = "tp_buffer", 626 [PTR_TO_XDP_SOCK] = "xdp_sock", 627 [PTR_TO_BTF_ID] = "ptr_", 628 [PTR_TO_MEM] = "mem", 629 [PTR_TO_BUF] = "buf", 630 [PTR_TO_FUNC] = "func", 631 [PTR_TO_MAP_KEY] = "map_key", 632 [CONST_PTR_TO_DYNPTR] = "dynptr_ptr", 633 }; 634 635 if (type & PTR_MAYBE_NULL) { 636 if (base_type(type) == PTR_TO_BTF_ID) 637 strncpy(postfix, "or_null_", 16); 638 else 639 strncpy(postfix, "_or_null", 16); 640 } 641 642 snprintf(prefix, sizeof(prefix), "%s%s%s%s%s%s%s", 643 type & MEM_RDONLY ? "rdonly_" : "", 644 type & MEM_RINGBUF ? "ringbuf_" : "", 645 type & MEM_USER ? "user_" : "", 646 type & MEM_PERCPU ? "percpu_" : "", 647 type & MEM_RCU ? "rcu_" : "", 648 type & PTR_UNTRUSTED ? "untrusted_" : "", 649 type & PTR_TRUSTED ? "trusted_" : "" 650 ); 651 652 snprintf(env->tmp_str_buf, TMP_STR_BUF_LEN, "%s%s%s", 653 prefix, str[base_type(type)], postfix); 654 return env->tmp_str_buf; 655 } 656 657 static char slot_type_char[] = { 658 [STACK_INVALID] = '?', 659 [STACK_SPILL] = 'r', 660 [STACK_MISC] = 'm', 661 [STACK_ZERO] = '0', 662 [STACK_DYNPTR] = 'd', 663 [STACK_ITER] = 'i', 664 }; 665 666 static void print_liveness(struct bpf_verifier_env *env, 667 enum bpf_reg_liveness live) 668 { 669 if (live & (REG_LIVE_READ | REG_LIVE_WRITTEN | REG_LIVE_DONE)) 670 verbose(env, "_"); 671 if (live & REG_LIVE_READ) 672 verbose(env, "r"); 673 if (live & REG_LIVE_WRITTEN) 674 verbose(env, "w"); 675 if (live & REG_LIVE_DONE) 676 verbose(env, "D"); 677 } 678 679 static int __get_spi(s32 off) 680 { 681 return (-off - 1) / BPF_REG_SIZE; 682 } 683 684 static struct bpf_func_state *func(struct bpf_verifier_env *env, 685 const struct bpf_reg_state *reg) 686 { 687 struct bpf_verifier_state *cur = env->cur_state; 688 689 return cur->frame[reg->frameno]; 690 } 691 692 static bool is_spi_bounds_valid(struct bpf_func_state *state, int spi, int nr_slots) 693 { 694 int allocated_slots = state->allocated_stack / BPF_REG_SIZE; 695 696 /* We need to check that slots between [spi - nr_slots + 1, spi] are 697 * within [0, allocated_stack). 698 * 699 * Please note that the spi grows downwards. For example, a dynptr 700 * takes the size of two stack slots; the first slot will be at 701 * spi and the second slot will be at spi - 1. 702 */ 703 return spi - nr_slots + 1 >= 0 && spi < allocated_slots; 704 } 705 706 static int stack_slot_obj_get_spi(struct bpf_verifier_env *env, struct bpf_reg_state *reg, 707 const char *obj_kind, int nr_slots) 708 { 709 int off, spi; 710 711 if (!tnum_is_const(reg->var_off)) { 712 verbose(env, "%s has to be at a constant offset\n", obj_kind); 713 return -EINVAL; 714 } 715 716 off = reg->off + reg->var_off.value; 717 if (off % BPF_REG_SIZE) { 718 verbose(env, "cannot pass in %s at an offset=%d\n", obj_kind, off); 719 return -EINVAL; 720 } 721 722 spi = __get_spi(off); 723 if (spi + 1 < nr_slots) { 724 verbose(env, "cannot pass in %s at an offset=%d\n", obj_kind, off); 725 return -EINVAL; 726 } 727 728 if (!is_spi_bounds_valid(func(env, reg), spi, nr_slots)) 729 return -ERANGE; 730 return spi; 731 } 732 733 static int dynptr_get_spi(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 734 { 735 return stack_slot_obj_get_spi(env, reg, "dynptr", BPF_DYNPTR_NR_SLOTS); 736 } 737 738 static int iter_get_spi(struct bpf_verifier_env *env, struct bpf_reg_state *reg, int nr_slots) 739 { 740 return stack_slot_obj_get_spi(env, reg, "iter", nr_slots); 741 } 742 743 static const char *btf_type_name(const struct btf *btf, u32 id) 744 { 745 return btf_name_by_offset(btf, btf_type_by_id(btf, id)->name_off); 746 } 747 748 static const char *dynptr_type_str(enum bpf_dynptr_type type) 749 { 750 switch (type) { 751 case BPF_DYNPTR_TYPE_LOCAL: 752 return "local"; 753 case BPF_DYNPTR_TYPE_RINGBUF: 754 return "ringbuf"; 755 case BPF_DYNPTR_TYPE_SKB: 756 return "skb"; 757 case BPF_DYNPTR_TYPE_XDP: 758 return "xdp"; 759 case BPF_DYNPTR_TYPE_INVALID: 760 return "<invalid>"; 761 default: 762 WARN_ONCE(1, "unknown dynptr type %d\n", type); 763 return "<unknown>"; 764 } 765 } 766 767 static const char *iter_type_str(const struct btf *btf, u32 btf_id) 768 { 769 if (!btf || btf_id == 0) 770 return "<invalid>"; 771 772 /* we already validated that type is valid and has conforming name */ 773 return btf_type_name(btf, btf_id) + sizeof(ITER_PREFIX) - 1; 774 } 775 776 static const char *iter_state_str(enum bpf_iter_state state) 777 { 778 switch (state) { 779 case BPF_ITER_STATE_ACTIVE: 780 return "active"; 781 case BPF_ITER_STATE_DRAINED: 782 return "drained"; 783 case BPF_ITER_STATE_INVALID: 784 return "<invalid>"; 785 default: 786 WARN_ONCE(1, "unknown iter state %d\n", state); 787 return "<unknown>"; 788 } 789 } 790 791 static void mark_reg_scratched(struct bpf_verifier_env *env, u32 regno) 792 { 793 env->scratched_regs |= 1U << regno; 794 } 795 796 static void mark_stack_slot_scratched(struct bpf_verifier_env *env, u32 spi) 797 { 798 env->scratched_stack_slots |= 1ULL << spi; 799 } 800 801 static bool reg_scratched(const struct bpf_verifier_env *env, u32 regno) 802 { 803 return (env->scratched_regs >> regno) & 1; 804 } 805 806 static bool stack_slot_scratched(const struct bpf_verifier_env *env, u64 regno) 807 { 808 return (env->scratched_stack_slots >> regno) & 1; 809 } 810 811 static bool verifier_state_scratched(const struct bpf_verifier_env *env) 812 { 813 return env->scratched_regs || env->scratched_stack_slots; 814 } 815 816 static void mark_verifier_state_clean(struct bpf_verifier_env *env) 817 { 818 env->scratched_regs = 0U; 819 env->scratched_stack_slots = 0ULL; 820 } 821 822 /* Used for printing the entire verifier state. */ 823 static void mark_verifier_state_scratched(struct bpf_verifier_env *env) 824 { 825 env->scratched_regs = ~0U; 826 env->scratched_stack_slots = ~0ULL; 827 } 828 829 static enum bpf_dynptr_type arg_to_dynptr_type(enum bpf_arg_type arg_type) 830 { 831 switch (arg_type & DYNPTR_TYPE_FLAG_MASK) { 832 case DYNPTR_TYPE_LOCAL: 833 return BPF_DYNPTR_TYPE_LOCAL; 834 case DYNPTR_TYPE_RINGBUF: 835 return BPF_DYNPTR_TYPE_RINGBUF; 836 case DYNPTR_TYPE_SKB: 837 return BPF_DYNPTR_TYPE_SKB; 838 case DYNPTR_TYPE_XDP: 839 return BPF_DYNPTR_TYPE_XDP; 840 default: 841 return BPF_DYNPTR_TYPE_INVALID; 842 } 843 } 844 845 static enum bpf_type_flag get_dynptr_type_flag(enum bpf_dynptr_type type) 846 { 847 switch (type) { 848 case BPF_DYNPTR_TYPE_LOCAL: 849 return DYNPTR_TYPE_LOCAL; 850 case BPF_DYNPTR_TYPE_RINGBUF: 851 return DYNPTR_TYPE_RINGBUF; 852 case BPF_DYNPTR_TYPE_SKB: 853 return DYNPTR_TYPE_SKB; 854 case BPF_DYNPTR_TYPE_XDP: 855 return DYNPTR_TYPE_XDP; 856 default: 857 return 0; 858 } 859 } 860 861 static bool dynptr_type_refcounted(enum bpf_dynptr_type type) 862 { 863 return type == BPF_DYNPTR_TYPE_RINGBUF; 864 } 865 866 static void __mark_dynptr_reg(struct bpf_reg_state *reg, 867 enum bpf_dynptr_type type, 868 bool first_slot, int dynptr_id); 869 870 static void __mark_reg_not_init(const struct bpf_verifier_env *env, 871 struct bpf_reg_state *reg); 872 873 static void mark_dynptr_stack_regs(struct bpf_verifier_env *env, 874 struct bpf_reg_state *sreg1, 875 struct bpf_reg_state *sreg2, 876 enum bpf_dynptr_type type) 877 { 878 int id = ++env->id_gen; 879 880 __mark_dynptr_reg(sreg1, type, true, id); 881 __mark_dynptr_reg(sreg2, type, false, id); 882 } 883 884 static void mark_dynptr_cb_reg(struct bpf_verifier_env *env, 885 struct bpf_reg_state *reg, 886 enum bpf_dynptr_type type) 887 { 888 __mark_dynptr_reg(reg, type, true, ++env->id_gen); 889 } 890 891 static int destroy_if_dynptr_stack_slot(struct bpf_verifier_env *env, 892 struct bpf_func_state *state, int spi); 893 894 static int mark_stack_slots_dynptr(struct bpf_verifier_env *env, struct bpf_reg_state *reg, 895 enum bpf_arg_type arg_type, int insn_idx, int clone_ref_obj_id) 896 { 897 struct bpf_func_state *state = func(env, reg); 898 enum bpf_dynptr_type type; 899 int spi, i, err; 900 901 spi = dynptr_get_spi(env, reg); 902 if (spi < 0) 903 return spi; 904 905 /* We cannot assume both spi and spi - 1 belong to the same dynptr, 906 * hence we need to call destroy_if_dynptr_stack_slot twice for both, 907 * to ensure that for the following example: 908 * [d1][d1][d2][d2] 909 * spi 3 2 1 0 910 * So marking spi = 2 should lead to destruction of both d1 and d2. In 911 * case they do belong to same dynptr, second call won't see slot_type 912 * as STACK_DYNPTR and will simply skip destruction. 913 */ 914 err = destroy_if_dynptr_stack_slot(env, state, spi); 915 if (err) 916 return err; 917 err = destroy_if_dynptr_stack_slot(env, state, spi - 1); 918 if (err) 919 return err; 920 921 for (i = 0; i < BPF_REG_SIZE; i++) { 922 state->stack[spi].slot_type[i] = STACK_DYNPTR; 923 state->stack[spi - 1].slot_type[i] = STACK_DYNPTR; 924 } 925 926 type = arg_to_dynptr_type(arg_type); 927 if (type == BPF_DYNPTR_TYPE_INVALID) 928 return -EINVAL; 929 930 mark_dynptr_stack_regs(env, &state->stack[spi].spilled_ptr, 931 &state->stack[spi - 1].spilled_ptr, type); 932 933 if (dynptr_type_refcounted(type)) { 934 /* The id is used to track proper releasing */ 935 int id; 936 937 if (clone_ref_obj_id) 938 id = clone_ref_obj_id; 939 else 940 id = acquire_reference_state(env, insn_idx); 941 942 if (id < 0) 943 return id; 944 945 state->stack[spi].spilled_ptr.ref_obj_id = id; 946 state->stack[spi - 1].spilled_ptr.ref_obj_id = id; 947 } 948 949 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN; 950 state->stack[spi - 1].spilled_ptr.live |= REG_LIVE_WRITTEN; 951 952 return 0; 953 } 954 955 static void invalidate_dynptr(struct bpf_verifier_env *env, struct bpf_func_state *state, int spi) 956 { 957 int i; 958 959 for (i = 0; i < BPF_REG_SIZE; i++) { 960 state->stack[spi].slot_type[i] = STACK_INVALID; 961 state->stack[spi - 1].slot_type[i] = STACK_INVALID; 962 } 963 964 __mark_reg_not_init(env, &state->stack[spi].spilled_ptr); 965 __mark_reg_not_init(env, &state->stack[spi - 1].spilled_ptr); 966 967 /* Why do we need to set REG_LIVE_WRITTEN for STACK_INVALID slot? 968 * 969 * While we don't allow reading STACK_INVALID, it is still possible to 970 * do <8 byte writes marking some but not all slots as STACK_MISC. Then, 971 * helpers or insns can do partial read of that part without failing, 972 * but check_stack_range_initialized, check_stack_read_var_off, and 973 * check_stack_read_fixed_off will do mark_reg_read for all 8-bytes of 974 * the slot conservatively. Hence we need to prevent those liveness 975 * marking walks. 976 * 977 * This was not a problem before because STACK_INVALID is only set by 978 * default (where the default reg state has its reg->parent as NULL), or 979 * in clean_live_states after REG_LIVE_DONE (at which point 980 * mark_reg_read won't walk reg->parent chain), but not randomly during 981 * verifier state exploration (like we did above). Hence, for our case 982 * parentage chain will still be live (i.e. reg->parent may be 983 * non-NULL), while earlier reg->parent was NULL, so we need 984 * REG_LIVE_WRITTEN to screen off read marker propagation when it is 985 * done later on reads or by mark_dynptr_read as well to unnecessary 986 * mark registers in verifier state. 987 */ 988 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN; 989 state->stack[spi - 1].spilled_ptr.live |= REG_LIVE_WRITTEN; 990 } 991 992 static int unmark_stack_slots_dynptr(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 993 { 994 struct bpf_func_state *state = func(env, reg); 995 int spi, ref_obj_id, i; 996 997 spi = dynptr_get_spi(env, reg); 998 if (spi < 0) 999 return spi; 1000 1001 if (!dynptr_type_refcounted(state->stack[spi].spilled_ptr.dynptr.type)) { 1002 invalidate_dynptr(env, state, spi); 1003 return 0; 1004 } 1005 1006 ref_obj_id = state->stack[spi].spilled_ptr.ref_obj_id; 1007 1008 /* If the dynptr has a ref_obj_id, then we need to invalidate 1009 * two things: 1010 * 1011 * 1) Any dynptrs with a matching ref_obj_id (clones) 1012 * 2) Any slices derived from this dynptr. 1013 */ 1014 1015 /* Invalidate any slices associated with this dynptr */ 1016 WARN_ON_ONCE(release_reference(env, ref_obj_id)); 1017 1018 /* Invalidate any dynptr clones */ 1019 for (i = 1; i < state->allocated_stack / BPF_REG_SIZE; i++) { 1020 if (state->stack[i].spilled_ptr.ref_obj_id != ref_obj_id) 1021 continue; 1022 1023 /* it should always be the case that if the ref obj id 1024 * matches then the stack slot also belongs to a 1025 * dynptr 1026 */ 1027 if (state->stack[i].slot_type[0] != STACK_DYNPTR) { 1028 verbose(env, "verifier internal error: misconfigured ref_obj_id\n"); 1029 return -EFAULT; 1030 } 1031 if (state->stack[i].spilled_ptr.dynptr.first_slot) 1032 invalidate_dynptr(env, state, i); 1033 } 1034 1035 return 0; 1036 } 1037 1038 static void __mark_reg_unknown(const struct bpf_verifier_env *env, 1039 struct bpf_reg_state *reg); 1040 1041 static void mark_reg_invalid(const struct bpf_verifier_env *env, struct bpf_reg_state *reg) 1042 { 1043 if (!env->allow_ptr_leaks) 1044 __mark_reg_not_init(env, reg); 1045 else 1046 __mark_reg_unknown(env, reg); 1047 } 1048 1049 static int destroy_if_dynptr_stack_slot(struct bpf_verifier_env *env, 1050 struct bpf_func_state *state, int spi) 1051 { 1052 struct bpf_func_state *fstate; 1053 struct bpf_reg_state *dreg; 1054 int i, dynptr_id; 1055 1056 /* We always ensure that STACK_DYNPTR is never set partially, 1057 * hence just checking for slot_type[0] is enough. This is 1058 * different for STACK_SPILL, where it may be only set for 1059 * 1 byte, so code has to use is_spilled_reg. 1060 */ 1061 if (state->stack[spi].slot_type[0] != STACK_DYNPTR) 1062 return 0; 1063 1064 /* Reposition spi to first slot */ 1065 if (!state->stack[spi].spilled_ptr.dynptr.first_slot) 1066 spi = spi + 1; 1067 1068 if (dynptr_type_refcounted(state->stack[spi].spilled_ptr.dynptr.type)) { 1069 verbose(env, "cannot overwrite referenced dynptr\n"); 1070 return -EINVAL; 1071 } 1072 1073 mark_stack_slot_scratched(env, spi); 1074 mark_stack_slot_scratched(env, spi - 1); 1075 1076 /* Writing partially to one dynptr stack slot destroys both. */ 1077 for (i = 0; i < BPF_REG_SIZE; i++) { 1078 state->stack[spi].slot_type[i] = STACK_INVALID; 1079 state->stack[spi - 1].slot_type[i] = STACK_INVALID; 1080 } 1081 1082 dynptr_id = state->stack[spi].spilled_ptr.id; 1083 /* Invalidate any slices associated with this dynptr */ 1084 bpf_for_each_reg_in_vstate(env->cur_state, fstate, dreg, ({ 1085 /* Dynptr slices are only PTR_TO_MEM_OR_NULL and PTR_TO_MEM */ 1086 if (dreg->type != (PTR_TO_MEM | PTR_MAYBE_NULL) && dreg->type != PTR_TO_MEM) 1087 continue; 1088 if (dreg->dynptr_id == dynptr_id) 1089 mark_reg_invalid(env, dreg); 1090 })); 1091 1092 /* Do not release reference state, we are destroying dynptr on stack, 1093 * not using some helper to release it. Just reset register. 1094 */ 1095 __mark_reg_not_init(env, &state->stack[spi].spilled_ptr); 1096 __mark_reg_not_init(env, &state->stack[spi - 1].spilled_ptr); 1097 1098 /* Same reason as unmark_stack_slots_dynptr above */ 1099 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN; 1100 state->stack[spi - 1].spilled_ptr.live |= REG_LIVE_WRITTEN; 1101 1102 return 0; 1103 } 1104 1105 static bool is_dynptr_reg_valid_uninit(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 1106 { 1107 int spi; 1108 1109 if (reg->type == CONST_PTR_TO_DYNPTR) 1110 return false; 1111 1112 spi = dynptr_get_spi(env, reg); 1113 1114 /* -ERANGE (i.e. spi not falling into allocated stack slots) isn't an 1115 * error because this just means the stack state hasn't been updated yet. 1116 * We will do check_mem_access to check and update stack bounds later. 1117 */ 1118 if (spi < 0 && spi != -ERANGE) 1119 return false; 1120 1121 /* We don't need to check if the stack slots are marked by previous 1122 * dynptr initializations because we allow overwriting existing unreferenced 1123 * STACK_DYNPTR slots, see mark_stack_slots_dynptr which calls 1124 * destroy_if_dynptr_stack_slot to ensure dynptr objects at the slots we are 1125 * touching are completely destructed before we reinitialize them for a new 1126 * one. For referenced ones, destroy_if_dynptr_stack_slot returns an error early 1127 * instead of delaying it until the end where the user will get "Unreleased 1128 * reference" error. 1129 */ 1130 return true; 1131 } 1132 1133 static bool is_dynptr_reg_valid_init(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 1134 { 1135 struct bpf_func_state *state = func(env, reg); 1136 int i, spi; 1137 1138 /* This already represents first slot of initialized bpf_dynptr. 1139 * 1140 * CONST_PTR_TO_DYNPTR already has fixed and var_off as 0 due to 1141 * check_func_arg_reg_off's logic, so we don't need to check its 1142 * offset and alignment. 1143 */ 1144 if (reg->type == CONST_PTR_TO_DYNPTR) 1145 return true; 1146 1147 spi = dynptr_get_spi(env, reg); 1148 if (spi < 0) 1149 return false; 1150 if (!state->stack[spi].spilled_ptr.dynptr.first_slot) 1151 return false; 1152 1153 for (i = 0; i < BPF_REG_SIZE; i++) { 1154 if (state->stack[spi].slot_type[i] != STACK_DYNPTR || 1155 state->stack[spi - 1].slot_type[i] != STACK_DYNPTR) 1156 return false; 1157 } 1158 1159 return true; 1160 } 1161 1162 static bool is_dynptr_type_expected(struct bpf_verifier_env *env, struct bpf_reg_state *reg, 1163 enum bpf_arg_type arg_type) 1164 { 1165 struct bpf_func_state *state = func(env, reg); 1166 enum bpf_dynptr_type dynptr_type; 1167 int spi; 1168 1169 /* ARG_PTR_TO_DYNPTR takes any type of dynptr */ 1170 if (arg_type == ARG_PTR_TO_DYNPTR) 1171 return true; 1172 1173 dynptr_type = arg_to_dynptr_type(arg_type); 1174 if (reg->type == CONST_PTR_TO_DYNPTR) { 1175 return reg->dynptr.type == dynptr_type; 1176 } else { 1177 spi = dynptr_get_spi(env, reg); 1178 if (spi < 0) 1179 return false; 1180 return state->stack[spi].spilled_ptr.dynptr.type == dynptr_type; 1181 } 1182 } 1183 1184 static void __mark_reg_known_zero(struct bpf_reg_state *reg); 1185 1186 static int mark_stack_slots_iter(struct bpf_verifier_env *env, 1187 struct bpf_reg_state *reg, int insn_idx, 1188 struct btf *btf, u32 btf_id, int nr_slots) 1189 { 1190 struct bpf_func_state *state = func(env, reg); 1191 int spi, i, j, id; 1192 1193 spi = iter_get_spi(env, reg, nr_slots); 1194 if (spi < 0) 1195 return spi; 1196 1197 id = acquire_reference_state(env, insn_idx); 1198 if (id < 0) 1199 return id; 1200 1201 for (i = 0; i < nr_slots; i++) { 1202 struct bpf_stack_state *slot = &state->stack[spi - i]; 1203 struct bpf_reg_state *st = &slot->spilled_ptr; 1204 1205 __mark_reg_known_zero(st); 1206 st->type = PTR_TO_STACK; /* we don't have dedicated reg type */ 1207 st->live |= REG_LIVE_WRITTEN; 1208 st->ref_obj_id = i == 0 ? id : 0; 1209 st->iter.btf = btf; 1210 st->iter.btf_id = btf_id; 1211 st->iter.state = BPF_ITER_STATE_ACTIVE; 1212 st->iter.depth = 0; 1213 1214 for (j = 0; j < BPF_REG_SIZE; j++) 1215 slot->slot_type[j] = STACK_ITER; 1216 1217 mark_stack_slot_scratched(env, spi - i); 1218 } 1219 1220 return 0; 1221 } 1222 1223 static int unmark_stack_slots_iter(struct bpf_verifier_env *env, 1224 struct bpf_reg_state *reg, int nr_slots) 1225 { 1226 struct bpf_func_state *state = func(env, reg); 1227 int spi, i, j; 1228 1229 spi = iter_get_spi(env, reg, nr_slots); 1230 if (spi < 0) 1231 return spi; 1232 1233 for (i = 0; i < nr_slots; i++) { 1234 struct bpf_stack_state *slot = &state->stack[spi - i]; 1235 struct bpf_reg_state *st = &slot->spilled_ptr; 1236 1237 if (i == 0) 1238 WARN_ON_ONCE(release_reference(env, st->ref_obj_id)); 1239 1240 __mark_reg_not_init(env, st); 1241 1242 /* see unmark_stack_slots_dynptr() for why we need to set REG_LIVE_WRITTEN */ 1243 st->live |= REG_LIVE_WRITTEN; 1244 1245 for (j = 0; j < BPF_REG_SIZE; j++) 1246 slot->slot_type[j] = STACK_INVALID; 1247 1248 mark_stack_slot_scratched(env, spi - i); 1249 } 1250 1251 return 0; 1252 } 1253 1254 static bool is_iter_reg_valid_uninit(struct bpf_verifier_env *env, 1255 struct bpf_reg_state *reg, int nr_slots) 1256 { 1257 struct bpf_func_state *state = func(env, reg); 1258 int spi, i, j; 1259 1260 /* For -ERANGE (i.e. spi not falling into allocated stack slots), we 1261 * will do check_mem_access to check and update stack bounds later, so 1262 * return true for that case. 1263 */ 1264 spi = iter_get_spi(env, reg, nr_slots); 1265 if (spi == -ERANGE) 1266 return true; 1267 if (spi < 0) 1268 return false; 1269 1270 for (i = 0; i < nr_slots; i++) { 1271 struct bpf_stack_state *slot = &state->stack[spi - i]; 1272 1273 for (j = 0; j < BPF_REG_SIZE; j++) 1274 if (slot->slot_type[j] == STACK_ITER) 1275 return false; 1276 } 1277 1278 return true; 1279 } 1280 1281 static bool is_iter_reg_valid_init(struct bpf_verifier_env *env, struct bpf_reg_state *reg, 1282 struct btf *btf, u32 btf_id, int nr_slots) 1283 { 1284 struct bpf_func_state *state = func(env, reg); 1285 int spi, i, j; 1286 1287 spi = iter_get_spi(env, reg, nr_slots); 1288 if (spi < 0) 1289 return false; 1290 1291 for (i = 0; i < nr_slots; i++) { 1292 struct bpf_stack_state *slot = &state->stack[spi - i]; 1293 struct bpf_reg_state *st = &slot->spilled_ptr; 1294 1295 /* only main (first) slot has ref_obj_id set */ 1296 if (i == 0 && !st->ref_obj_id) 1297 return false; 1298 if (i != 0 && st->ref_obj_id) 1299 return false; 1300 if (st->iter.btf != btf || st->iter.btf_id != btf_id) 1301 return false; 1302 1303 for (j = 0; j < BPF_REG_SIZE; j++) 1304 if (slot->slot_type[j] != STACK_ITER) 1305 return false; 1306 } 1307 1308 return true; 1309 } 1310 1311 /* Check if given stack slot is "special": 1312 * - spilled register state (STACK_SPILL); 1313 * - dynptr state (STACK_DYNPTR); 1314 * - iter state (STACK_ITER). 1315 */ 1316 static bool is_stack_slot_special(const struct bpf_stack_state *stack) 1317 { 1318 enum bpf_stack_slot_type type = stack->slot_type[BPF_REG_SIZE - 1]; 1319 1320 switch (type) { 1321 case STACK_SPILL: 1322 case STACK_DYNPTR: 1323 case STACK_ITER: 1324 return true; 1325 case STACK_INVALID: 1326 case STACK_MISC: 1327 case STACK_ZERO: 1328 return false; 1329 default: 1330 WARN_ONCE(1, "unknown stack slot type %d\n", type); 1331 return true; 1332 } 1333 } 1334 1335 /* The reg state of a pointer or a bounded scalar was saved when 1336 * it was spilled to the stack. 1337 */ 1338 static bool is_spilled_reg(const struct bpf_stack_state *stack) 1339 { 1340 return stack->slot_type[BPF_REG_SIZE - 1] == STACK_SPILL; 1341 } 1342 1343 static bool is_spilled_scalar_reg(const struct bpf_stack_state *stack) 1344 { 1345 return stack->slot_type[BPF_REG_SIZE - 1] == STACK_SPILL && 1346 stack->spilled_ptr.type == SCALAR_VALUE; 1347 } 1348 1349 static void scrub_spilled_slot(u8 *stype) 1350 { 1351 if (*stype != STACK_INVALID) 1352 *stype = STACK_MISC; 1353 } 1354 1355 static void print_verifier_state(struct bpf_verifier_env *env, 1356 const struct bpf_func_state *state, 1357 bool print_all) 1358 { 1359 const struct bpf_reg_state *reg; 1360 enum bpf_reg_type t; 1361 int i; 1362 1363 if (state->frameno) 1364 verbose(env, " frame%d:", state->frameno); 1365 for (i = 0; i < MAX_BPF_REG; i++) { 1366 reg = &state->regs[i]; 1367 t = reg->type; 1368 if (t == NOT_INIT) 1369 continue; 1370 if (!print_all && !reg_scratched(env, i)) 1371 continue; 1372 verbose(env, " R%d", i); 1373 print_liveness(env, reg->live); 1374 verbose(env, "="); 1375 if (t == SCALAR_VALUE && reg->precise) 1376 verbose(env, "P"); 1377 if ((t == SCALAR_VALUE || t == PTR_TO_STACK) && 1378 tnum_is_const(reg->var_off)) { 1379 /* reg->off should be 0 for SCALAR_VALUE */ 1380 verbose(env, "%s", t == SCALAR_VALUE ? "" : reg_type_str(env, t)); 1381 verbose(env, "%lld", reg->var_off.value + reg->off); 1382 } else { 1383 const char *sep = ""; 1384 1385 verbose(env, "%s", reg_type_str(env, t)); 1386 if (base_type(t) == PTR_TO_BTF_ID) 1387 verbose(env, "%s", btf_type_name(reg->btf, reg->btf_id)); 1388 verbose(env, "("); 1389 /* 1390 * _a stands for append, was shortened to avoid multiline statements below. 1391 * This macro is used to output a comma separated list of attributes. 1392 */ 1393 #define verbose_a(fmt, ...) ({ verbose(env, "%s" fmt, sep, __VA_ARGS__); sep = ","; }) 1394 1395 if (reg->id) 1396 verbose_a("id=%d", reg->id); 1397 if (reg->ref_obj_id) 1398 verbose_a("ref_obj_id=%d", reg->ref_obj_id); 1399 if (type_is_non_owning_ref(reg->type)) 1400 verbose_a("%s", "non_own_ref"); 1401 if (t != SCALAR_VALUE) 1402 verbose_a("off=%d", reg->off); 1403 if (type_is_pkt_pointer(t)) 1404 verbose_a("r=%d", reg->range); 1405 else if (base_type(t) == CONST_PTR_TO_MAP || 1406 base_type(t) == PTR_TO_MAP_KEY || 1407 base_type(t) == PTR_TO_MAP_VALUE) 1408 verbose_a("ks=%d,vs=%d", 1409 reg->map_ptr->key_size, 1410 reg->map_ptr->value_size); 1411 if (tnum_is_const(reg->var_off)) { 1412 /* Typically an immediate SCALAR_VALUE, but 1413 * could be a pointer whose offset is too big 1414 * for reg->off 1415 */ 1416 verbose_a("imm=%llx", reg->var_off.value); 1417 } else { 1418 if (reg->smin_value != reg->umin_value && 1419 reg->smin_value != S64_MIN) 1420 verbose_a("smin=%lld", (long long)reg->smin_value); 1421 if (reg->smax_value != reg->umax_value && 1422 reg->smax_value != S64_MAX) 1423 verbose_a("smax=%lld", (long long)reg->smax_value); 1424 if (reg->umin_value != 0) 1425 verbose_a("umin=%llu", (unsigned long long)reg->umin_value); 1426 if (reg->umax_value != U64_MAX) 1427 verbose_a("umax=%llu", (unsigned long long)reg->umax_value); 1428 if (!tnum_is_unknown(reg->var_off)) { 1429 char tn_buf[48]; 1430 1431 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 1432 verbose_a("var_off=%s", tn_buf); 1433 } 1434 if (reg->s32_min_value != reg->smin_value && 1435 reg->s32_min_value != S32_MIN) 1436 verbose_a("s32_min=%d", (int)(reg->s32_min_value)); 1437 if (reg->s32_max_value != reg->smax_value && 1438 reg->s32_max_value != S32_MAX) 1439 verbose_a("s32_max=%d", (int)(reg->s32_max_value)); 1440 if (reg->u32_min_value != reg->umin_value && 1441 reg->u32_min_value != U32_MIN) 1442 verbose_a("u32_min=%d", (int)(reg->u32_min_value)); 1443 if (reg->u32_max_value != reg->umax_value && 1444 reg->u32_max_value != U32_MAX) 1445 verbose_a("u32_max=%d", (int)(reg->u32_max_value)); 1446 } 1447 #undef verbose_a 1448 1449 verbose(env, ")"); 1450 } 1451 } 1452 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) { 1453 char types_buf[BPF_REG_SIZE + 1]; 1454 bool valid = false; 1455 int j; 1456 1457 for (j = 0; j < BPF_REG_SIZE; j++) { 1458 if (state->stack[i].slot_type[j] != STACK_INVALID) 1459 valid = true; 1460 types_buf[j] = slot_type_char[state->stack[i].slot_type[j]]; 1461 } 1462 types_buf[BPF_REG_SIZE] = 0; 1463 if (!valid) 1464 continue; 1465 if (!print_all && !stack_slot_scratched(env, i)) 1466 continue; 1467 switch (state->stack[i].slot_type[BPF_REG_SIZE - 1]) { 1468 case STACK_SPILL: 1469 reg = &state->stack[i].spilled_ptr; 1470 t = reg->type; 1471 1472 verbose(env, " fp%d", (-i - 1) * BPF_REG_SIZE); 1473 print_liveness(env, reg->live); 1474 verbose(env, "=%s", t == SCALAR_VALUE ? "" : reg_type_str(env, t)); 1475 if (t == SCALAR_VALUE && reg->precise) 1476 verbose(env, "P"); 1477 if (t == SCALAR_VALUE && tnum_is_const(reg->var_off)) 1478 verbose(env, "%lld", reg->var_off.value + reg->off); 1479 break; 1480 case STACK_DYNPTR: 1481 i += BPF_DYNPTR_NR_SLOTS - 1; 1482 reg = &state->stack[i].spilled_ptr; 1483 1484 verbose(env, " fp%d", (-i - 1) * BPF_REG_SIZE); 1485 print_liveness(env, reg->live); 1486 verbose(env, "=dynptr_%s", dynptr_type_str(reg->dynptr.type)); 1487 if (reg->ref_obj_id) 1488 verbose(env, "(ref_id=%d)", reg->ref_obj_id); 1489 break; 1490 case STACK_ITER: 1491 /* only main slot has ref_obj_id set; skip others */ 1492 reg = &state->stack[i].spilled_ptr; 1493 if (!reg->ref_obj_id) 1494 continue; 1495 1496 verbose(env, " fp%d", (-i - 1) * BPF_REG_SIZE); 1497 print_liveness(env, reg->live); 1498 verbose(env, "=iter_%s(ref_id=%d,state=%s,depth=%u)", 1499 iter_type_str(reg->iter.btf, reg->iter.btf_id), 1500 reg->ref_obj_id, iter_state_str(reg->iter.state), 1501 reg->iter.depth); 1502 break; 1503 case STACK_MISC: 1504 case STACK_ZERO: 1505 default: 1506 reg = &state->stack[i].spilled_ptr; 1507 1508 for (j = 0; j < BPF_REG_SIZE; j++) 1509 types_buf[j] = slot_type_char[state->stack[i].slot_type[j]]; 1510 types_buf[BPF_REG_SIZE] = 0; 1511 1512 verbose(env, " fp%d", (-i - 1) * BPF_REG_SIZE); 1513 print_liveness(env, reg->live); 1514 verbose(env, "=%s", types_buf); 1515 break; 1516 } 1517 } 1518 if (state->acquired_refs && state->refs[0].id) { 1519 verbose(env, " refs=%d", state->refs[0].id); 1520 for (i = 1; i < state->acquired_refs; i++) 1521 if (state->refs[i].id) 1522 verbose(env, ",%d", state->refs[i].id); 1523 } 1524 if (state->in_callback_fn) 1525 verbose(env, " cb"); 1526 if (state->in_async_callback_fn) 1527 verbose(env, " async_cb"); 1528 verbose(env, "\n"); 1529 if (!print_all) 1530 mark_verifier_state_clean(env); 1531 } 1532 1533 static inline u32 vlog_alignment(u32 pos) 1534 { 1535 return round_up(max(pos + BPF_LOG_MIN_ALIGNMENT / 2, BPF_LOG_ALIGNMENT), 1536 BPF_LOG_MIN_ALIGNMENT) - pos - 1; 1537 } 1538 1539 static void print_insn_state(struct bpf_verifier_env *env, 1540 const struct bpf_func_state *state) 1541 { 1542 if (env->prev_log_pos && env->prev_log_pos == env->log.end_pos) { 1543 /* remove new line character */ 1544 bpf_vlog_reset(&env->log, env->prev_log_pos - 1); 1545 verbose(env, "%*c;", vlog_alignment(env->prev_insn_print_pos), ' '); 1546 } else { 1547 verbose(env, "%d:", env->insn_idx); 1548 } 1549 print_verifier_state(env, state, false); 1550 } 1551 1552 /* copy array src of length n * size bytes to dst. dst is reallocated if it's too 1553 * small to hold src. This is different from krealloc since we don't want to preserve 1554 * the contents of dst. 1555 * 1556 * Leaves dst untouched if src is NULL or length is zero. Returns NULL if memory could 1557 * not be allocated. 1558 */ 1559 static void *copy_array(void *dst, const void *src, size_t n, size_t size, gfp_t flags) 1560 { 1561 size_t alloc_bytes; 1562 void *orig = dst; 1563 size_t bytes; 1564 1565 if (ZERO_OR_NULL_PTR(src)) 1566 goto out; 1567 1568 if (unlikely(check_mul_overflow(n, size, &bytes))) 1569 return NULL; 1570 1571 alloc_bytes = max(ksize(orig), kmalloc_size_roundup(bytes)); 1572 dst = krealloc(orig, alloc_bytes, flags); 1573 if (!dst) { 1574 kfree(orig); 1575 return NULL; 1576 } 1577 1578 memcpy(dst, src, bytes); 1579 out: 1580 return dst ? dst : ZERO_SIZE_PTR; 1581 } 1582 1583 /* resize an array from old_n items to new_n items. the array is reallocated if it's too 1584 * small to hold new_n items. new items are zeroed out if the array grows. 1585 * 1586 * Contrary to krealloc_array, does not free arr if new_n is zero. 1587 */ 1588 static void *realloc_array(void *arr, size_t old_n, size_t new_n, size_t size) 1589 { 1590 size_t alloc_size; 1591 void *new_arr; 1592 1593 if (!new_n || old_n == new_n) 1594 goto out; 1595 1596 alloc_size = kmalloc_size_roundup(size_mul(new_n, size)); 1597 new_arr = krealloc(arr, alloc_size, GFP_KERNEL); 1598 if (!new_arr) { 1599 kfree(arr); 1600 return NULL; 1601 } 1602 arr = new_arr; 1603 1604 if (new_n > old_n) 1605 memset(arr + old_n * size, 0, (new_n - old_n) * size); 1606 1607 out: 1608 return arr ? arr : ZERO_SIZE_PTR; 1609 } 1610 1611 static int copy_reference_state(struct bpf_func_state *dst, const struct bpf_func_state *src) 1612 { 1613 dst->refs = copy_array(dst->refs, src->refs, src->acquired_refs, 1614 sizeof(struct bpf_reference_state), GFP_KERNEL); 1615 if (!dst->refs) 1616 return -ENOMEM; 1617 1618 dst->acquired_refs = src->acquired_refs; 1619 return 0; 1620 } 1621 1622 static int copy_stack_state(struct bpf_func_state *dst, const struct bpf_func_state *src) 1623 { 1624 size_t n = src->allocated_stack / BPF_REG_SIZE; 1625 1626 dst->stack = copy_array(dst->stack, src->stack, n, sizeof(struct bpf_stack_state), 1627 GFP_KERNEL); 1628 if (!dst->stack) 1629 return -ENOMEM; 1630 1631 dst->allocated_stack = src->allocated_stack; 1632 return 0; 1633 } 1634 1635 static int resize_reference_state(struct bpf_func_state *state, size_t n) 1636 { 1637 state->refs = realloc_array(state->refs, state->acquired_refs, n, 1638 sizeof(struct bpf_reference_state)); 1639 if (!state->refs) 1640 return -ENOMEM; 1641 1642 state->acquired_refs = n; 1643 return 0; 1644 } 1645 1646 /* Possibly update state->allocated_stack to be at least size bytes. Also 1647 * possibly update the function's high-water mark in its bpf_subprog_info. 1648 */ 1649 static int grow_stack_state(struct bpf_verifier_env *env, struct bpf_func_state *state, int size) 1650 { 1651 size_t old_n = state->allocated_stack / BPF_REG_SIZE, n = size / BPF_REG_SIZE; 1652 1653 if (old_n >= n) 1654 return 0; 1655 1656 state->stack = realloc_array(state->stack, old_n, n, sizeof(struct bpf_stack_state)); 1657 if (!state->stack) 1658 return -ENOMEM; 1659 1660 state->allocated_stack = size; 1661 1662 /* update known max for given subprogram */ 1663 if (env->subprog_info[state->subprogno].stack_depth < size) 1664 env->subprog_info[state->subprogno].stack_depth = size; 1665 1666 return 0; 1667 } 1668 1669 /* Acquire a pointer id from the env and update the state->refs to include 1670 * this new pointer reference. 1671 * On success, returns a valid pointer id to associate with the register 1672 * On failure, returns a negative errno. 1673 */ 1674 static int acquire_reference_state(struct bpf_verifier_env *env, int insn_idx) 1675 { 1676 struct bpf_func_state *state = cur_func(env); 1677 int new_ofs = state->acquired_refs; 1678 int id, err; 1679 1680 err = resize_reference_state(state, state->acquired_refs + 1); 1681 if (err) 1682 return err; 1683 id = ++env->id_gen; 1684 state->refs[new_ofs].id = id; 1685 state->refs[new_ofs].insn_idx = insn_idx; 1686 state->refs[new_ofs].callback_ref = state->in_callback_fn ? state->frameno : 0; 1687 1688 return id; 1689 } 1690 1691 /* release function corresponding to acquire_reference_state(). Idempotent. */ 1692 static int release_reference_state(struct bpf_func_state *state, int ptr_id) 1693 { 1694 int i, last_idx; 1695 1696 last_idx = state->acquired_refs - 1; 1697 for (i = 0; i < state->acquired_refs; i++) { 1698 if (state->refs[i].id == ptr_id) { 1699 /* Cannot release caller references in callbacks */ 1700 if (state->in_callback_fn && state->refs[i].callback_ref != state->frameno) 1701 return -EINVAL; 1702 if (last_idx && i != last_idx) 1703 memcpy(&state->refs[i], &state->refs[last_idx], 1704 sizeof(*state->refs)); 1705 memset(&state->refs[last_idx], 0, sizeof(*state->refs)); 1706 state->acquired_refs--; 1707 return 0; 1708 } 1709 } 1710 return -EINVAL; 1711 } 1712 1713 static void free_func_state(struct bpf_func_state *state) 1714 { 1715 if (!state) 1716 return; 1717 kfree(state->refs); 1718 kfree(state->stack); 1719 kfree(state); 1720 } 1721 1722 static void clear_jmp_history(struct bpf_verifier_state *state) 1723 { 1724 kfree(state->jmp_history); 1725 state->jmp_history = NULL; 1726 state->jmp_history_cnt = 0; 1727 } 1728 1729 static void free_verifier_state(struct bpf_verifier_state *state, 1730 bool free_self) 1731 { 1732 int i; 1733 1734 for (i = 0; i <= state->curframe; i++) { 1735 free_func_state(state->frame[i]); 1736 state->frame[i] = NULL; 1737 } 1738 clear_jmp_history(state); 1739 if (free_self) 1740 kfree(state); 1741 } 1742 1743 /* copy verifier state from src to dst growing dst stack space 1744 * when necessary to accommodate larger src stack 1745 */ 1746 static int copy_func_state(struct bpf_func_state *dst, 1747 const struct bpf_func_state *src) 1748 { 1749 int err; 1750 1751 memcpy(dst, src, offsetof(struct bpf_func_state, acquired_refs)); 1752 err = copy_reference_state(dst, src); 1753 if (err) 1754 return err; 1755 return copy_stack_state(dst, src); 1756 } 1757 1758 static int copy_verifier_state(struct bpf_verifier_state *dst_state, 1759 const struct bpf_verifier_state *src) 1760 { 1761 struct bpf_func_state *dst; 1762 int i, err; 1763 1764 dst_state->jmp_history = copy_array(dst_state->jmp_history, src->jmp_history, 1765 src->jmp_history_cnt, sizeof(*dst_state->jmp_history), 1766 GFP_USER); 1767 if (!dst_state->jmp_history) 1768 return -ENOMEM; 1769 dst_state->jmp_history_cnt = src->jmp_history_cnt; 1770 1771 /* if dst has more stack frames then src frame, free them */ 1772 for (i = src->curframe + 1; i <= dst_state->curframe; i++) { 1773 free_func_state(dst_state->frame[i]); 1774 dst_state->frame[i] = NULL; 1775 } 1776 dst_state->speculative = src->speculative; 1777 dst_state->active_rcu_lock = src->active_rcu_lock; 1778 dst_state->curframe = src->curframe; 1779 dst_state->active_lock.ptr = src->active_lock.ptr; 1780 dst_state->active_lock.id = src->active_lock.id; 1781 dst_state->branches = src->branches; 1782 dst_state->parent = src->parent; 1783 dst_state->first_insn_idx = src->first_insn_idx; 1784 dst_state->last_insn_idx = src->last_insn_idx; 1785 dst_state->dfs_depth = src->dfs_depth; 1786 dst_state->callback_unroll_depth = src->callback_unroll_depth; 1787 dst_state->used_as_loop_entry = src->used_as_loop_entry; 1788 for (i = 0; i <= src->curframe; i++) { 1789 dst = dst_state->frame[i]; 1790 if (!dst) { 1791 dst = kzalloc(sizeof(*dst), GFP_KERNEL); 1792 if (!dst) 1793 return -ENOMEM; 1794 dst_state->frame[i] = dst; 1795 } 1796 err = copy_func_state(dst, src->frame[i]); 1797 if (err) 1798 return err; 1799 } 1800 return 0; 1801 } 1802 1803 static u32 state_htab_size(struct bpf_verifier_env *env) 1804 { 1805 return env->prog->len; 1806 } 1807 1808 static struct bpf_verifier_state_list **explored_state(struct bpf_verifier_env *env, int idx) 1809 { 1810 struct bpf_verifier_state *cur = env->cur_state; 1811 struct bpf_func_state *state = cur->frame[cur->curframe]; 1812 1813 return &env->explored_states[(idx ^ state->callsite) % state_htab_size(env)]; 1814 } 1815 1816 static bool same_callsites(struct bpf_verifier_state *a, struct bpf_verifier_state *b) 1817 { 1818 int fr; 1819 1820 if (a->curframe != b->curframe) 1821 return false; 1822 1823 for (fr = a->curframe; fr >= 0; fr--) 1824 if (a->frame[fr]->callsite != b->frame[fr]->callsite) 1825 return false; 1826 1827 return true; 1828 } 1829 1830 /* Open coded iterators allow back-edges in the state graph in order to 1831 * check unbounded loops that iterators. 1832 * 1833 * In is_state_visited() it is necessary to know if explored states are 1834 * part of some loops in order to decide whether non-exact states 1835 * comparison could be used: 1836 * - non-exact states comparison establishes sub-state relation and uses 1837 * read and precision marks to do so, these marks are propagated from 1838 * children states and thus are not guaranteed to be final in a loop; 1839 * - exact states comparison just checks if current and explored states 1840 * are identical (and thus form a back-edge). 1841 * 1842 * Paper "A New Algorithm for Identifying Loops in Decompilation" 1843 * by Tao Wei, Jian Mao, Wei Zou and Yu Chen [1] presents a convenient 1844 * algorithm for loop structure detection and gives an overview of 1845 * relevant terminology. It also has helpful illustrations. 1846 * 1847 * [1] https://api.semanticscholar.org/CorpusID:15784067 1848 * 1849 * We use a similar algorithm but because loop nested structure is 1850 * irrelevant for verifier ours is significantly simpler and resembles 1851 * strongly connected components algorithm from Sedgewick's textbook. 1852 * 1853 * Define topmost loop entry as a first node of the loop traversed in a 1854 * depth first search starting from initial state. The goal of the loop 1855 * tracking algorithm is to associate topmost loop entries with states 1856 * derived from these entries. 1857 * 1858 * For each step in the DFS states traversal algorithm needs to identify 1859 * the following situations: 1860 * 1861 * initial initial initial 1862 * | | | 1863 * V V V 1864 * ... ... .---------> hdr 1865 * | | | | 1866 * V V | V 1867 * cur .-> succ | .------... 1868 * | | | | | | 1869 * V | V | V V 1870 * succ '-- cur | ... ... 1871 * | | | 1872 * | V V 1873 * | succ <- cur 1874 * | | 1875 * | V 1876 * | ... 1877 * | | 1878 * '----' 1879 * 1880 * (A) successor state of cur (B) successor state of cur or it's entry 1881 * not yet traversed are in current DFS path, thus cur and succ 1882 * are members of the same outermost loop 1883 * 1884 * initial initial 1885 * | | 1886 * V V 1887 * ... ... 1888 * | | 1889 * V V 1890 * .------... .------... 1891 * | | | | 1892 * V V V V 1893 * .-> hdr ... ... ... 1894 * | | | | | 1895 * | V V V V 1896 * | succ <- cur succ <- cur 1897 * | | | 1898 * | V V 1899 * | ... ... 1900 * | | | 1901 * '----' exit 1902 * 1903 * (C) successor state of cur is a part of some loop but this loop 1904 * does not include cur or successor state is not in a loop at all. 1905 * 1906 * Algorithm could be described as the following python code: 1907 * 1908 * traversed = set() # Set of traversed nodes 1909 * entries = {} # Mapping from node to loop entry 1910 * depths = {} # Depth level assigned to graph node 1911 * path = set() # Current DFS path 1912 * 1913 * # Find outermost loop entry known for n 1914 * def get_loop_entry(n): 1915 * h = entries.get(n, None) 1916 * while h in entries and entries[h] != h: 1917 * h = entries[h] 1918 * return h 1919 * 1920 * # Update n's loop entry if h's outermost entry comes 1921 * # before n's outermost entry in current DFS path. 1922 * def update_loop_entry(n, h): 1923 * n1 = get_loop_entry(n) or n 1924 * h1 = get_loop_entry(h) or h 1925 * if h1 in path and depths[h1] <= depths[n1]: 1926 * entries[n] = h1 1927 * 1928 * def dfs(n, depth): 1929 * traversed.add(n) 1930 * path.add(n) 1931 * depths[n] = depth 1932 * for succ in G.successors(n): 1933 * if succ not in traversed: 1934 * # Case A: explore succ and update cur's loop entry 1935 * # only if succ's entry is in current DFS path. 1936 * dfs(succ, depth + 1) 1937 * h = get_loop_entry(succ) 1938 * update_loop_entry(n, h) 1939 * else: 1940 * # Case B or C depending on `h1 in path` check in update_loop_entry(). 1941 * update_loop_entry(n, succ) 1942 * path.remove(n) 1943 * 1944 * To adapt this algorithm for use with verifier: 1945 * - use st->branch == 0 as a signal that DFS of succ had been finished 1946 * and cur's loop entry has to be updated (case A), handle this in 1947 * update_branch_counts(); 1948 * - use st->branch > 0 as a signal that st is in the current DFS path; 1949 * - handle cases B and C in is_state_visited(); 1950 * - update topmost loop entry for intermediate states in get_loop_entry(). 1951 */ 1952 static struct bpf_verifier_state *get_loop_entry(struct bpf_verifier_state *st) 1953 { 1954 struct bpf_verifier_state *topmost = st->loop_entry, *old; 1955 1956 while (topmost && topmost->loop_entry && topmost != topmost->loop_entry) 1957 topmost = topmost->loop_entry; 1958 /* Update loop entries for intermediate states to avoid this 1959 * traversal in future get_loop_entry() calls. 1960 */ 1961 while (st && st->loop_entry != topmost) { 1962 old = st->loop_entry; 1963 st->loop_entry = topmost; 1964 st = old; 1965 } 1966 return topmost; 1967 } 1968 1969 static void update_loop_entry(struct bpf_verifier_state *cur, struct bpf_verifier_state *hdr) 1970 { 1971 struct bpf_verifier_state *cur1, *hdr1; 1972 1973 cur1 = get_loop_entry(cur) ?: cur; 1974 hdr1 = get_loop_entry(hdr) ?: hdr; 1975 /* The head1->branches check decides between cases B and C in 1976 * comment for get_loop_entry(). If hdr1->branches == 0 then 1977 * head's topmost loop entry is not in current DFS path, 1978 * hence 'cur' and 'hdr' are not in the same loop and there is 1979 * no need to update cur->loop_entry. 1980 */ 1981 if (hdr1->branches && hdr1->dfs_depth <= cur1->dfs_depth) { 1982 cur->loop_entry = hdr; 1983 hdr->used_as_loop_entry = true; 1984 } 1985 } 1986 1987 static void update_branch_counts(struct bpf_verifier_env *env, struct bpf_verifier_state *st) 1988 { 1989 while (st) { 1990 u32 br = --st->branches; 1991 1992 /* br == 0 signals that DFS exploration for 'st' is finished, 1993 * thus it is necessary to update parent's loop entry if it 1994 * turned out that st is a part of some loop. 1995 * This is a part of 'case A' in get_loop_entry() comment. 1996 */ 1997 if (br == 0 && st->parent && st->loop_entry) 1998 update_loop_entry(st->parent, st->loop_entry); 1999 2000 /* WARN_ON(br > 1) technically makes sense here, 2001 * but see comment in push_stack(), hence: 2002 */ 2003 WARN_ONCE((int)br < 0, 2004 "BUG update_branch_counts:branches_to_explore=%d\n", 2005 br); 2006 if (br) 2007 break; 2008 st = st->parent; 2009 } 2010 } 2011 2012 static int pop_stack(struct bpf_verifier_env *env, int *prev_insn_idx, 2013 int *insn_idx, bool pop_log) 2014 { 2015 struct bpf_verifier_state *cur = env->cur_state; 2016 struct bpf_verifier_stack_elem *elem, *head = env->head; 2017 int err; 2018 2019 if (env->head == NULL) 2020 return -ENOENT; 2021 2022 if (cur) { 2023 err = copy_verifier_state(cur, &head->st); 2024 if (err) 2025 return err; 2026 } 2027 if (pop_log) 2028 bpf_vlog_reset(&env->log, head->log_pos); 2029 if (insn_idx) 2030 *insn_idx = head->insn_idx; 2031 if (prev_insn_idx) 2032 *prev_insn_idx = head->prev_insn_idx; 2033 elem = head->next; 2034 free_verifier_state(&head->st, false); 2035 kfree(head); 2036 env->head = elem; 2037 env->stack_size--; 2038 return 0; 2039 } 2040 2041 static struct bpf_verifier_state *push_stack(struct bpf_verifier_env *env, 2042 int insn_idx, int prev_insn_idx, 2043 bool speculative) 2044 { 2045 struct bpf_verifier_state *cur = env->cur_state; 2046 struct bpf_verifier_stack_elem *elem; 2047 int err; 2048 2049 elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL); 2050 if (!elem) 2051 goto err; 2052 2053 elem->insn_idx = insn_idx; 2054 elem->prev_insn_idx = prev_insn_idx; 2055 elem->next = env->head; 2056 elem->log_pos = env->log.end_pos; 2057 env->head = elem; 2058 env->stack_size++; 2059 err = copy_verifier_state(&elem->st, cur); 2060 if (err) 2061 goto err; 2062 elem->st.speculative |= speculative; 2063 if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) { 2064 verbose(env, "The sequence of %d jumps is too complex.\n", 2065 env->stack_size); 2066 goto err; 2067 } 2068 if (elem->st.parent) { 2069 ++elem->st.parent->branches; 2070 /* WARN_ON(branches > 2) technically makes sense here, 2071 * but 2072 * 1. speculative states will bump 'branches' for non-branch 2073 * instructions 2074 * 2. is_state_visited() heuristics may decide not to create 2075 * a new state for a sequence of branches and all such current 2076 * and cloned states will be pointing to a single parent state 2077 * which might have large 'branches' count. 2078 */ 2079 } 2080 return &elem->st; 2081 err: 2082 free_verifier_state(env->cur_state, true); 2083 env->cur_state = NULL; 2084 /* pop all elements and return */ 2085 while (!pop_stack(env, NULL, NULL, false)); 2086 return NULL; 2087 } 2088 2089 #define CALLER_SAVED_REGS 6 2090 static const int caller_saved[CALLER_SAVED_REGS] = { 2091 BPF_REG_0, BPF_REG_1, BPF_REG_2, BPF_REG_3, BPF_REG_4, BPF_REG_5 2092 }; 2093 2094 /* This helper doesn't clear reg->id */ 2095 static void ___mark_reg_known(struct bpf_reg_state *reg, u64 imm) 2096 { 2097 reg->var_off = tnum_const(imm); 2098 reg->smin_value = (s64)imm; 2099 reg->smax_value = (s64)imm; 2100 reg->umin_value = imm; 2101 reg->umax_value = imm; 2102 2103 reg->s32_min_value = (s32)imm; 2104 reg->s32_max_value = (s32)imm; 2105 reg->u32_min_value = (u32)imm; 2106 reg->u32_max_value = (u32)imm; 2107 } 2108 2109 /* Mark the unknown part of a register (variable offset or scalar value) as 2110 * known to have the value @imm. 2111 */ 2112 static void __mark_reg_known(struct bpf_reg_state *reg, u64 imm) 2113 { 2114 /* Clear off and union(map_ptr, range) */ 2115 memset(((u8 *)reg) + sizeof(reg->type), 0, 2116 offsetof(struct bpf_reg_state, var_off) - sizeof(reg->type)); 2117 reg->id = 0; 2118 reg->ref_obj_id = 0; 2119 ___mark_reg_known(reg, imm); 2120 } 2121 2122 static void __mark_reg32_known(struct bpf_reg_state *reg, u64 imm) 2123 { 2124 reg->var_off = tnum_const_subreg(reg->var_off, imm); 2125 reg->s32_min_value = (s32)imm; 2126 reg->s32_max_value = (s32)imm; 2127 reg->u32_min_value = (u32)imm; 2128 reg->u32_max_value = (u32)imm; 2129 } 2130 2131 /* Mark the 'variable offset' part of a register as zero. This should be 2132 * used only on registers holding a pointer type. 2133 */ 2134 static void __mark_reg_known_zero(struct bpf_reg_state *reg) 2135 { 2136 __mark_reg_known(reg, 0); 2137 } 2138 2139 static void __mark_reg_const_zero(struct bpf_reg_state *reg) 2140 { 2141 __mark_reg_known(reg, 0); 2142 reg->type = SCALAR_VALUE; 2143 } 2144 2145 static void mark_reg_known_zero(struct bpf_verifier_env *env, 2146 struct bpf_reg_state *regs, u32 regno) 2147 { 2148 if (WARN_ON(regno >= MAX_BPF_REG)) { 2149 verbose(env, "mark_reg_known_zero(regs, %u)\n", regno); 2150 /* Something bad happened, let's kill all regs */ 2151 for (regno = 0; regno < MAX_BPF_REG; regno++) 2152 __mark_reg_not_init(env, regs + regno); 2153 return; 2154 } 2155 __mark_reg_known_zero(regs + regno); 2156 } 2157 2158 static void __mark_dynptr_reg(struct bpf_reg_state *reg, enum bpf_dynptr_type type, 2159 bool first_slot, int dynptr_id) 2160 { 2161 /* reg->type has no meaning for STACK_DYNPTR, but when we set reg for 2162 * callback arguments, it does need to be CONST_PTR_TO_DYNPTR, so simply 2163 * set it unconditionally as it is ignored for STACK_DYNPTR anyway. 2164 */ 2165 __mark_reg_known_zero(reg); 2166 reg->type = CONST_PTR_TO_DYNPTR; 2167 /* Give each dynptr a unique id to uniquely associate slices to it. */ 2168 reg->id = dynptr_id; 2169 reg->dynptr.type = type; 2170 reg->dynptr.first_slot = first_slot; 2171 } 2172 2173 static void mark_ptr_not_null_reg(struct bpf_reg_state *reg) 2174 { 2175 if (base_type(reg->type) == PTR_TO_MAP_VALUE) { 2176 const struct bpf_map *map = reg->map_ptr; 2177 2178 if (map->inner_map_meta) { 2179 reg->type = CONST_PTR_TO_MAP; 2180 reg->map_ptr = map->inner_map_meta; 2181 /* transfer reg's id which is unique for every map_lookup_elem 2182 * as UID of the inner map. 2183 */ 2184 if (btf_record_has_field(map->inner_map_meta->record, BPF_TIMER)) 2185 reg->map_uid = reg->id; 2186 } else if (map->map_type == BPF_MAP_TYPE_XSKMAP) { 2187 reg->type = PTR_TO_XDP_SOCK; 2188 } else if (map->map_type == BPF_MAP_TYPE_SOCKMAP || 2189 map->map_type == BPF_MAP_TYPE_SOCKHASH) { 2190 reg->type = PTR_TO_SOCKET; 2191 } else { 2192 reg->type = PTR_TO_MAP_VALUE; 2193 } 2194 return; 2195 } 2196 2197 reg->type &= ~PTR_MAYBE_NULL; 2198 } 2199 2200 static void mark_reg_graph_node(struct bpf_reg_state *regs, u32 regno, 2201 struct btf_field_graph_root *ds_head) 2202 { 2203 __mark_reg_known_zero(®s[regno]); 2204 regs[regno].type = PTR_TO_BTF_ID | MEM_ALLOC; 2205 regs[regno].btf = ds_head->btf; 2206 regs[regno].btf_id = ds_head->value_btf_id; 2207 regs[regno].off = ds_head->node_offset; 2208 } 2209 2210 static bool reg_is_pkt_pointer(const struct bpf_reg_state *reg) 2211 { 2212 return type_is_pkt_pointer(reg->type); 2213 } 2214 2215 static bool reg_is_pkt_pointer_any(const struct bpf_reg_state *reg) 2216 { 2217 return reg_is_pkt_pointer(reg) || 2218 reg->type == PTR_TO_PACKET_END; 2219 } 2220 2221 static bool reg_is_dynptr_slice_pkt(const struct bpf_reg_state *reg) 2222 { 2223 return base_type(reg->type) == PTR_TO_MEM && 2224 (reg->type & DYNPTR_TYPE_SKB || reg->type & DYNPTR_TYPE_XDP); 2225 } 2226 2227 /* Unmodified PTR_TO_PACKET[_META,_END] register from ctx access. */ 2228 static bool reg_is_init_pkt_pointer(const struct bpf_reg_state *reg, 2229 enum bpf_reg_type which) 2230 { 2231 /* The register can already have a range from prior markings. 2232 * This is fine as long as it hasn't been advanced from its 2233 * origin. 2234 */ 2235 return reg->type == which && 2236 reg->id == 0 && 2237 reg->off == 0 && 2238 tnum_equals_const(reg->var_off, 0); 2239 } 2240 2241 /* Reset the min/max bounds of a register */ 2242 static void __mark_reg_unbounded(struct bpf_reg_state *reg) 2243 { 2244 reg->smin_value = S64_MIN; 2245 reg->smax_value = S64_MAX; 2246 reg->umin_value = 0; 2247 reg->umax_value = U64_MAX; 2248 2249 reg->s32_min_value = S32_MIN; 2250 reg->s32_max_value = S32_MAX; 2251 reg->u32_min_value = 0; 2252 reg->u32_max_value = U32_MAX; 2253 } 2254 2255 static void __mark_reg64_unbounded(struct bpf_reg_state *reg) 2256 { 2257 reg->smin_value = S64_MIN; 2258 reg->smax_value = S64_MAX; 2259 reg->umin_value = 0; 2260 reg->umax_value = U64_MAX; 2261 } 2262 2263 static void __mark_reg32_unbounded(struct bpf_reg_state *reg) 2264 { 2265 reg->s32_min_value = S32_MIN; 2266 reg->s32_max_value = S32_MAX; 2267 reg->u32_min_value = 0; 2268 reg->u32_max_value = U32_MAX; 2269 } 2270 2271 static void __update_reg32_bounds(struct bpf_reg_state *reg) 2272 { 2273 struct tnum var32_off = tnum_subreg(reg->var_off); 2274 2275 /* min signed is max(sign bit) | min(other bits) */ 2276 reg->s32_min_value = max_t(s32, reg->s32_min_value, 2277 var32_off.value | (var32_off.mask & S32_MIN)); 2278 /* max signed is min(sign bit) | max(other bits) */ 2279 reg->s32_max_value = min_t(s32, reg->s32_max_value, 2280 var32_off.value | (var32_off.mask & S32_MAX)); 2281 reg->u32_min_value = max_t(u32, reg->u32_min_value, (u32)var32_off.value); 2282 reg->u32_max_value = min(reg->u32_max_value, 2283 (u32)(var32_off.value | var32_off.mask)); 2284 } 2285 2286 static void __update_reg64_bounds(struct bpf_reg_state *reg) 2287 { 2288 /* min signed is max(sign bit) | min(other bits) */ 2289 reg->smin_value = max_t(s64, reg->smin_value, 2290 reg->var_off.value | (reg->var_off.mask & S64_MIN)); 2291 /* max signed is min(sign bit) | max(other bits) */ 2292 reg->smax_value = min_t(s64, reg->smax_value, 2293 reg->var_off.value | (reg->var_off.mask & S64_MAX)); 2294 reg->umin_value = max(reg->umin_value, reg->var_off.value); 2295 reg->umax_value = min(reg->umax_value, 2296 reg->var_off.value | reg->var_off.mask); 2297 } 2298 2299 static void __update_reg_bounds(struct bpf_reg_state *reg) 2300 { 2301 __update_reg32_bounds(reg); 2302 __update_reg64_bounds(reg); 2303 } 2304 2305 /* Uses signed min/max values to inform unsigned, and vice-versa */ 2306 static void __reg32_deduce_bounds(struct bpf_reg_state *reg) 2307 { 2308 /* Learn sign from signed bounds. 2309 * If we cannot cross the sign boundary, then signed and unsigned bounds 2310 * are the same, so combine. This works even in the negative case, e.g. 2311 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff. 2312 */ 2313 if (reg->s32_min_value >= 0 || reg->s32_max_value < 0) { 2314 reg->s32_min_value = reg->u32_min_value = 2315 max_t(u32, reg->s32_min_value, reg->u32_min_value); 2316 reg->s32_max_value = reg->u32_max_value = 2317 min_t(u32, reg->s32_max_value, reg->u32_max_value); 2318 return; 2319 } 2320 /* Learn sign from unsigned bounds. Signed bounds cross the sign 2321 * boundary, so we must be careful. 2322 */ 2323 if ((s32)reg->u32_max_value >= 0) { 2324 /* Positive. We can't learn anything from the smin, but smax 2325 * is positive, hence safe. 2326 */ 2327 reg->s32_min_value = reg->u32_min_value; 2328 reg->s32_max_value = reg->u32_max_value = 2329 min_t(u32, reg->s32_max_value, reg->u32_max_value); 2330 } else if ((s32)reg->u32_min_value < 0) { 2331 /* Negative. We can't learn anything from the smax, but smin 2332 * is negative, hence safe. 2333 */ 2334 reg->s32_min_value = reg->u32_min_value = 2335 max_t(u32, reg->s32_min_value, reg->u32_min_value); 2336 reg->s32_max_value = reg->u32_max_value; 2337 } 2338 } 2339 2340 static void __reg64_deduce_bounds(struct bpf_reg_state *reg) 2341 { 2342 /* Learn sign from signed bounds. 2343 * If we cannot cross the sign boundary, then signed and unsigned bounds 2344 * are the same, so combine. This works even in the negative case, e.g. 2345 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff. 2346 */ 2347 if (reg->smin_value >= 0 || reg->smax_value < 0) { 2348 reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value, 2349 reg->umin_value); 2350 reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value, 2351 reg->umax_value); 2352 return; 2353 } 2354 /* Learn sign from unsigned bounds. Signed bounds cross the sign 2355 * boundary, so we must be careful. 2356 */ 2357 if ((s64)reg->umax_value >= 0) { 2358 /* Positive. We can't learn anything from the smin, but smax 2359 * is positive, hence safe. 2360 */ 2361 reg->smin_value = reg->umin_value; 2362 reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value, 2363 reg->umax_value); 2364 } else if ((s64)reg->umin_value < 0) { 2365 /* Negative. We can't learn anything from the smax, but smin 2366 * is negative, hence safe. 2367 */ 2368 reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value, 2369 reg->umin_value); 2370 reg->smax_value = reg->umax_value; 2371 } 2372 } 2373 2374 static void __reg_deduce_bounds(struct bpf_reg_state *reg) 2375 { 2376 __reg32_deduce_bounds(reg); 2377 __reg64_deduce_bounds(reg); 2378 } 2379 2380 /* Attempts to improve var_off based on unsigned min/max information */ 2381 static void __reg_bound_offset(struct bpf_reg_state *reg) 2382 { 2383 struct tnum var64_off = tnum_intersect(reg->var_off, 2384 tnum_range(reg->umin_value, 2385 reg->umax_value)); 2386 struct tnum var32_off = tnum_intersect(tnum_subreg(var64_off), 2387 tnum_range(reg->u32_min_value, 2388 reg->u32_max_value)); 2389 2390 reg->var_off = tnum_or(tnum_clear_subreg(var64_off), var32_off); 2391 } 2392 2393 static void reg_bounds_sync(struct bpf_reg_state *reg) 2394 { 2395 /* We might have learned new bounds from the var_off. */ 2396 __update_reg_bounds(reg); 2397 /* We might have learned something about the sign bit. */ 2398 __reg_deduce_bounds(reg); 2399 /* We might have learned some bits from the bounds. */ 2400 __reg_bound_offset(reg); 2401 /* Intersecting with the old var_off might have improved our bounds 2402 * slightly, e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc), 2403 * then new var_off is (0; 0x7f...fc) which improves our umax. 2404 */ 2405 __update_reg_bounds(reg); 2406 } 2407 2408 static bool __reg32_bound_s64(s32 a) 2409 { 2410 return a >= 0 && a <= S32_MAX; 2411 } 2412 2413 static void __reg_assign_32_into_64(struct bpf_reg_state *reg) 2414 { 2415 reg->umin_value = reg->u32_min_value; 2416 reg->umax_value = reg->u32_max_value; 2417 2418 /* Attempt to pull 32-bit signed bounds into 64-bit bounds but must 2419 * be positive otherwise set to worse case bounds and refine later 2420 * from tnum. 2421 */ 2422 if (__reg32_bound_s64(reg->s32_min_value) && 2423 __reg32_bound_s64(reg->s32_max_value)) { 2424 reg->smin_value = reg->s32_min_value; 2425 reg->smax_value = reg->s32_max_value; 2426 } else { 2427 reg->smin_value = 0; 2428 reg->smax_value = U32_MAX; 2429 } 2430 } 2431 2432 static void __reg_combine_32_into_64(struct bpf_reg_state *reg) 2433 { 2434 /* special case when 64-bit register has upper 32-bit register 2435 * zeroed. Typically happens after zext or <<32, >>32 sequence 2436 * allowing us to use 32-bit bounds directly, 2437 */ 2438 if (tnum_equals_const(tnum_clear_subreg(reg->var_off), 0)) { 2439 __reg_assign_32_into_64(reg); 2440 } else { 2441 /* Otherwise the best we can do is push lower 32bit known and 2442 * unknown bits into register (var_off set from jmp logic) 2443 * then learn as much as possible from the 64-bit tnum 2444 * known and unknown bits. The previous smin/smax bounds are 2445 * invalid here because of jmp32 compare so mark them unknown 2446 * so they do not impact tnum bounds calculation. 2447 */ 2448 __mark_reg64_unbounded(reg); 2449 } 2450 reg_bounds_sync(reg); 2451 } 2452 2453 static bool __reg64_bound_s32(s64 a) 2454 { 2455 return a >= S32_MIN && a <= S32_MAX; 2456 } 2457 2458 static bool __reg64_bound_u32(u64 a) 2459 { 2460 return a >= U32_MIN && a <= U32_MAX; 2461 } 2462 2463 static void __reg_combine_64_into_32(struct bpf_reg_state *reg) 2464 { 2465 __mark_reg32_unbounded(reg); 2466 if (__reg64_bound_s32(reg->smin_value) && __reg64_bound_s32(reg->smax_value)) { 2467 reg->s32_min_value = (s32)reg->smin_value; 2468 reg->s32_max_value = (s32)reg->smax_value; 2469 } 2470 if (__reg64_bound_u32(reg->umin_value) && __reg64_bound_u32(reg->umax_value)) { 2471 reg->u32_min_value = (u32)reg->umin_value; 2472 reg->u32_max_value = (u32)reg->umax_value; 2473 } 2474 reg_bounds_sync(reg); 2475 } 2476 2477 /* Mark a register as having a completely unknown (scalar) value. */ 2478 static void __mark_reg_unknown(const struct bpf_verifier_env *env, 2479 struct bpf_reg_state *reg) 2480 { 2481 /* 2482 * Clear type, off, and union(map_ptr, range) and 2483 * padding between 'type' and union 2484 */ 2485 memset(reg, 0, offsetof(struct bpf_reg_state, var_off)); 2486 reg->type = SCALAR_VALUE; 2487 reg->id = 0; 2488 reg->ref_obj_id = 0; 2489 reg->var_off = tnum_unknown; 2490 reg->frameno = 0; 2491 reg->precise = !env->bpf_capable; 2492 __mark_reg_unbounded(reg); 2493 } 2494 2495 static void mark_reg_unknown(struct bpf_verifier_env *env, 2496 struct bpf_reg_state *regs, u32 regno) 2497 { 2498 if (WARN_ON(regno >= MAX_BPF_REG)) { 2499 verbose(env, "mark_reg_unknown(regs, %u)\n", regno); 2500 /* Something bad happened, let's kill all regs except FP */ 2501 for (regno = 0; regno < BPF_REG_FP; regno++) 2502 __mark_reg_not_init(env, regs + regno); 2503 return; 2504 } 2505 __mark_reg_unknown(env, regs + regno); 2506 } 2507 2508 static void __mark_reg_not_init(const struct bpf_verifier_env *env, 2509 struct bpf_reg_state *reg) 2510 { 2511 __mark_reg_unknown(env, reg); 2512 reg->type = NOT_INIT; 2513 } 2514 2515 static void mark_reg_not_init(struct bpf_verifier_env *env, 2516 struct bpf_reg_state *regs, u32 regno) 2517 { 2518 if (WARN_ON(regno >= MAX_BPF_REG)) { 2519 verbose(env, "mark_reg_not_init(regs, %u)\n", regno); 2520 /* Something bad happened, let's kill all regs except FP */ 2521 for (regno = 0; regno < BPF_REG_FP; regno++) 2522 __mark_reg_not_init(env, regs + regno); 2523 return; 2524 } 2525 __mark_reg_not_init(env, regs + regno); 2526 } 2527 2528 static void mark_btf_ld_reg(struct bpf_verifier_env *env, 2529 struct bpf_reg_state *regs, u32 regno, 2530 enum bpf_reg_type reg_type, 2531 struct btf *btf, u32 btf_id, 2532 enum bpf_type_flag flag) 2533 { 2534 if (reg_type == SCALAR_VALUE) { 2535 mark_reg_unknown(env, regs, regno); 2536 return; 2537 } 2538 mark_reg_known_zero(env, regs, regno); 2539 regs[regno].type = PTR_TO_BTF_ID | flag; 2540 regs[regno].btf = btf; 2541 regs[regno].btf_id = btf_id; 2542 if (type_may_be_null(flag)) 2543 regs[regno].id = ++env->id_gen; 2544 } 2545 2546 #define DEF_NOT_SUBREG (0) 2547 static void init_reg_state(struct bpf_verifier_env *env, 2548 struct bpf_func_state *state) 2549 { 2550 struct bpf_reg_state *regs = state->regs; 2551 int i; 2552 2553 for (i = 0; i < MAX_BPF_REG; i++) { 2554 mark_reg_not_init(env, regs, i); 2555 regs[i].live = REG_LIVE_NONE; 2556 regs[i].parent = NULL; 2557 regs[i].subreg_def = DEF_NOT_SUBREG; 2558 } 2559 2560 /* frame pointer */ 2561 regs[BPF_REG_FP].type = PTR_TO_STACK; 2562 mark_reg_known_zero(env, regs, BPF_REG_FP); 2563 regs[BPF_REG_FP].frameno = state->frameno; 2564 } 2565 2566 #define BPF_MAIN_FUNC (-1) 2567 static void init_func_state(struct bpf_verifier_env *env, 2568 struct bpf_func_state *state, 2569 int callsite, int frameno, int subprogno) 2570 { 2571 state->callsite = callsite; 2572 state->frameno = frameno; 2573 state->subprogno = subprogno; 2574 state->callback_ret_range = tnum_range(0, 0); 2575 init_reg_state(env, state); 2576 mark_verifier_state_scratched(env); 2577 } 2578 2579 /* Similar to push_stack(), but for async callbacks */ 2580 static struct bpf_verifier_state *push_async_cb(struct bpf_verifier_env *env, 2581 int insn_idx, int prev_insn_idx, 2582 int subprog) 2583 { 2584 struct bpf_verifier_stack_elem *elem; 2585 struct bpf_func_state *frame; 2586 2587 elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL); 2588 if (!elem) 2589 goto err; 2590 2591 elem->insn_idx = insn_idx; 2592 elem->prev_insn_idx = prev_insn_idx; 2593 elem->next = env->head; 2594 elem->log_pos = env->log.end_pos; 2595 env->head = elem; 2596 env->stack_size++; 2597 if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) { 2598 verbose(env, 2599 "The sequence of %d jumps is too complex for async cb.\n", 2600 env->stack_size); 2601 goto err; 2602 } 2603 /* Unlike push_stack() do not copy_verifier_state(). 2604 * The caller state doesn't matter. 2605 * This is async callback. It starts in a fresh stack. 2606 * Initialize it similar to do_check_common(). 2607 */ 2608 elem->st.branches = 1; 2609 frame = kzalloc(sizeof(*frame), GFP_KERNEL); 2610 if (!frame) 2611 goto err; 2612 init_func_state(env, frame, 2613 BPF_MAIN_FUNC /* callsite */, 2614 0 /* frameno within this callchain */, 2615 subprog /* subprog number within this prog */); 2616 elem->st.frame[0] = frame; 2617 return &elem->st; 2618 err: 2619 free_verifier_state(env->cur_state, true); 2620 env->cur_state = NULL; 2621 /* pop all elements and return */ 2622 while (!pop_stack(env, NULL, NULL, false)); 2623 return NULL; 2624 } 2625 2626 2627 enum reg_arg_type { 2628 SRC_OP, /* register is used as source operand */ 2629 DST_OP, /* register is used as destination operand */ 2630 DST_OP_NO_MARK /* same as above, check only, don't mark */ 2631 }; 2632 2633 static int cmp_subprogs(const void *a, const void *b) 2634 { 2635 return ((struct bpf_subprog_info *)a)->start - 2636 ((struct bpf_subprog_info *)b)->start; 2637 } 2638 2639 static int find_subprog(struct bpf_verifier_env *env, int off) 2640 { 2641 struct bpf_subprog_info *p; 2642 2643 p = bsearch(&off, env->subprog_info, env->subprog_cnt, 2644 sizeof(env->subprog_info[0]), cmp_subprogs); 2645 if (!p) 2646 return -ENOENT; 2647 return p - env->subprog_info; 2648 2649 } 2650 2651 static int add_subprog(struct bpf_verifier_env *env, int off) 2652 { 2653 int insn_cnt = env->prog->len; 2654 int ret; 2655 2656 if (off >= insn_cnt || off < 0) { 2657 verbose(env, "call to invalid destination\n"); 2658 return -EINVAL; 2659 } 2660 ret = find_subprog(env, off); 2661 if (ret >= 0) 2662 return ret; 2663 if (env->subprog_cnt >= BPF_MAX_SUBPROGS) { 2664 verbose(env, "too many subprograms\n"); 2665 return -E2BIG; 2666 } 2667 /* determine subprog starts. The end is one before the next starts */ 2668 env->subprog_info[env->subprog_cnt++].start = off; 2669 sort(env->subprog_info, env->subprog_cnt, 2670 sizeof(env->subprog_info[0]), cmp_subprogs, NULL); 2671 return env->subprog_cnt - 1; 2672 } 2673 2674 #define MAX_KFUNC_DESCS 256 2675 #define MAX_KFUNC_BTFS 256 2676 2677 struct bpf_kfunc_desc { 2678 struct btf_func_model func_model; 2679 u32 func_id; 2680 s32 imm; 2681 u16 offset; 2682 unsigned long addr; 2683 }; 2684 2685 struct bpf_kfunc_btf { 2686 struct btf *btf; 2687 struct module *module; 2688 u16 offset; 2689 }; 2690 2691 struct bpf_kfunc_desc_tab { 2692 /* Sorted by func_id (BTF ID) and offset (fd_array offset) during 2693 * verification. JITs do lookups by bpf_insn, where func_id may not be 2694 * available, therefore at the end of verification do_misc_fixups() 2695 * sorts this by imm and offset. 2696 */ 2697 struct bpf_kfunc_desc descs[MAX_KFUNC_DESCS]; 2698 u32 nr_descs; 2699 }; 2700 2701 struct bpf_kfunc_btf_tab { 2702 struct bpf_kfunc_btf descs[MAX_KFUNC_BTFS]; 2703 u32 nr_descs; 2704 }; 2705 2706 static int kfunc_desc_cmp_by_id_off(const void *a, const void *b) 2707 { 2708 const struct bpf_kfunc_desc *d0 = a; 2709 const struct bpf_kfunc_desc *d1 = b; 2710 2711 /* func_id is not greater than BTF_MAX_TYPE */ 2712 return d0->func_id - d1->func_id ?: d0->offset - d1->offset; 2713 } 2714 2715 static int kfunc_btf_cmp_by_off(const void *a, const void *b) 2716 { 2717 const struct bpf_kfunc_btf *d0 = a; 2718 const struct bpf_kfunc_btf *d1 = b; 2719 2720 return d0->offset - d1->offset; 2721 } 2722 2723 static const struct bpf_kfunc_desc * 2724 find_kfunc_desc(const struct bpf_prog *prog, u32 func_id, u16 offset) 2725 { 2726 struct bpf_kfunc_desc desc = { 2727 .func_id = func_id, 2728 .offset = offset, 2729 }; 2730 struct bpf_kfunc_desc_tab *tab; 2731 2732 tab = prog->aux->kfunc_tab; 2733 return bsearch(&desc, tab->descs, tab->nr_descs, 2734 sizeof(tab->descs[0]), kfunc_desc_cmp_by_id_off); 2735 } 2736 2737 int bpf_get_kfunc_addr(const struct bpf_prog *prog, u32 func_id, 2738 u16 btf_fd_idx, u8 **func_addr) 2739 { 2740 const struct bpf_kfunc_desc *desc; 2741 2742 desc = find_kfunc_desc(prog, func_id, btf_fd_idx); 2743 if (!desc) 2744 return -EFAULT; 2745 2746 *func_addr = (u8 *)desc->addr; 2747 return 0; 2748 } 2749 2750 static struct btf *__find_kfunc_desc_btf(struct bpf_verifier_env *env, 2751 s16 offset) 2752 { 2753 struct bpf_kfunc_btf kf_btf = { .offset = offset }; 2754 struct bpf_kfunc_btf_tab *tab; 2755 struct bpf_kfunc_btf *b; 2756 struct module *mod; 2757 struct btf *btf; 2758 int btf_fd; 2759 2760 tab = env->prog->aux->kfunc_btf_tab; 2761 b = bsearch(&kf_btf, tab->descs, tab->nr_descs, 2762 sizeof(tab->descs[0]), kfunc_btf_cmp_by_off); 2763 if (!b) { 2764 if (tab->nr_descs == MAX_KFUNC_BTFS) { 2765 verbose(env, "too many different module BTFs\n"); 2766 return ERR_PTR(-E2BIG); 2767 } 2768 2769 if (bpfptr_is_null(env->fd_array)) { 2770 verbose(env, "kfunc offset > 0 without fd_array is invalid\n"); 2771 return ERR_PTR(-EPROTO); 2772 } 2773 2774 if (copy_from_bpfptr_offset(&btf_fd, env->fd_array, 2775 offset * sizeof(btf_fd), 2776 sizeof(btf_fd))) 2777 return ERR_PTR(-EFAULT); 2778 2779 btf = btf_get_by_fd(btf_fd); 2780 if (IS_ERR(btf)) { 2781 verbose(env, "invalid module BTF fd specified\n"); 2782 return btf; 2783 } 2784 2785 if (!btf_is_module(btf)) { 2786 verbose(env, "BTF fd for kfunc is not a module BTF\n"); 2787 btf_put(btf); 2788 return ERR_PTR(-EINVAL); 2789 } 2790 2791 mod = btf_try_get_module(btf); 2792 if (!mod) { 2793 btf_put(btf); 2794 return ERR_PTR(-ENXIO); 2795 } 2796 2797 b = &tab->descs[tab->nr_descs++]; 2798 b->btf = btf; 2799 b->module = mod; 2800 b->offset = offset; 2801 2802 /* sort() reorders entries by value, so b may no longer point 2803 * to the right entry after this 2804 */ 2805 sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]), 2806 kfunc_btf_cmp_by_off, NULL); 2807 } else { 2808 btf = b->btf; 2809 } 2810 2811 return btf; 2812 } 2813 2814 void bpf_free_kfunc_btf_tab(struct bpf_kfunc_btf_tab *tab) 2815 { 2816 if (!tab) 2817 return; 2818 2819 while (tab->nr_descs--) { 2820 module_put(tab->descs[tab->nr_descs].module); 2821 btf_put(tab->descs[tab->nr_descs].btf); 2822 } 2823 kfree(tab); 2824 } 2825 2826 static struct btf *find_kfunc_desc_btf(struct bpf_verifier_env *env, s16 offset) 2827 { 2828 if (offset) { 2829 if (offset < 0) { 2830 /* In the future, this can be allowed to increase limit 2831 * of fd index into fd_array, interpreted as u16. 2832 */ 2833 verbose(env, "negative offset disallowed for kernel module function call\n"); 2834 return ERR_PTR(-EINVAL); 2835 } 2836 2837 return __find_kfunc_desc_btf(env, offset); 2838 } 2839 return btf_vmlinux ?: ERR_PTR(-ENOENT); 2840 } 2841 2842 static int add_kfunc_call(struct bpf_verifier_env *env, u32 func_id, s16 offset) 2843 { 2844 const struct btf_type *func, *func_proto; 2845 struct bpf_kfunc_btf_tab *btf_tab; 2846 struct bpf_kfunc_desc_tab *tab; 2847 struct bpf_prog_aux *prog_aux; 2848 struct bpf_kfunc_desc *desc; 2849 const char *func_name; 2850 struct btf *desc_btf; 2851 unsigned long call_imm; 2852 unsigned long addr; 2853 int err; 2854 2855 prog_aux = env->prog->aux; 2856 tab = prog_aux->kfunc_tab; 2857 btf_tab = prog_aux->kfunc_btf_tab; 2858 if (!tab) { 2859 if (!btf_vmlinux) { 2860 verbose(env, "calling kernel function is not supported without CONFIG_DEBUG_INFO_BTF\n"); 2861 return -ENOTSUPP; 2862 } 2863 2864 if (!env->prog->jit_requested) { 2865 verbose(env, "JIT is required for calling kernel function\n"); 2866 return -ENOTSUPP; 2867 } 2868 2869 if (!bpf_jit_supports_kfunc_call()) { 2870 verbose(env, "JIT does not support calling kernel function\n"); 2871 return -ENOTSUPP; 2872 } 2873 2874 if (!env->prog->gpl_compatible) { 2875 verbose(env, "cannot call kernel function from non-GPL compatible program\n"); 2876 return -EINVAL; 2877 } 2878 2879 tab = kzalloc(sizeof(*tab), GFP_KERNEL); 2880 if (!tab) 2881 return -ENOMEM; 2882 prog_aux->kfunc_tab = tab; 2883 } 2884 2885 /* func_id == 0 is always invalid, but instead of returning an error, be 2886 * conservative and wait until the code elimination pass before returning 2887 * error, so that invalid calls that get pruned out can be in BPF programs 2888 * loaded from userspace. It is also required that offset be untouched 2889 * for such calls. 2890 */ 2891 if (!func_id && !offset) 2892 return 0; 2893 2894 if (!btf_tab && offset) { 2895 btf_tab = kzalloc(sizeof(*btf_tab), GFP_KERNEL); 2896 if (!btf_tab) 2897 return -ENOMEM; 2898 prog_aux->kfunc_btf_tab = btf_tab; 2899 } 2900 2901 desc_btf = find_kfunc_desc_btf(env, offset); 2902 if (IS_ERR(desc_btf)) { 2903 verbose(env, "failed to find BTF for kernel function\n"); 2904 return PTR_ERR(desc_btf); 2905 } 2906 2907 if (find_kfunc_desc(env->prog, func_id, offset)) 2908 return 0; 2909 2910 if (tab->nr_descs == MAX_KFUNC_DESCS) { 2911 verbose(env, "too many different kernel function calls\n"); 2912 return -E2BIG; 2913 } 2914 2915 func = btf_type_by_id(desc_btf, func_id); 2916 if (!func || !btf_type_is_func(func)) { 2917 verbose(env, "kernel btf_id %u is not a function\n", 2918 func_id); 2919 return -EINVAL; 2920 } 2921 func_proto = btf_type_by_id(desc_btf, func->type); 2922 if (!func_proto || !btf_type_is_func_proto(func_proto)) { 2923 verbose(env, "kernel function btf_id %u does not have a valid func_proto\n", 2924 func_id); 2925 return -EINVAL; 2926 } 2927 2928 func_name = btf_name_by_offset(desc_btf, func->name_off); 2929 addr = kallsyms_lookup_name(func_name); 2930 if (!addr) { 2931 verbose(env, "cannot find address for kernel function %s\n", 2932 func_name); 2933 return -EINVAL; 2934 } 2935 specialize_kfunc(env, func_id, offset, &addr); 2936 2937 if (bpf_jit_supports_far_kfunc_call()) { 2938 call_imm = func_id; 2939 } else { 2940 call_imm = BPF_CALL_IMM(addr); 2941 /* Check whether the relative offset overflows desc->imm */ 2942 if ((unsigned long)(s32)call_imm != call_imm) { 2943 verbose(env, "address of kernel function %s is out of range\n", 2944 func_name); 2945 return -EINVAL; 2946 } 2947 } 2948 2949 if (bpf_dev_bound_kfunc_id(func_id)) { 2950 err = bpf_dev_bound_kfunc_check(&env->log, prog_aux); 2951 if (err) 2952 return err; 2953 } 2954 2955 desc = &tab->descs[tab->nr_descs++]; 2956 desc->func_id = func_id; 2957 desc->imm = call_imm; 2958 desc->offset = offset; 2959 desc->addr = addr; 2960 err = btf_distill_func_proto(&env->log, desc_btf, 2961 func_proto, func_name, 2962 &desc->func_model); 2963 if (!err) 2964 sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]), 2965 kfunc_desc_cmp_by_id_off, NULL); 2966 return err; 2967 } 2968 2969 static int kfunc_desc_cmp_by_imm_off(const void *a, const void *b) 2970 { 2971 const struct bpf_kfunc_desc *d0 = a; 2972 const struct bpf_kfunc_desc *d1 = b; 2973 2974 if (d0->imm != d1->imm) 2975 return d0->imm < d1->imm ? -1 : 1; 2976 if (d0->offset != d1->offset) 2977 return d0->offset < d1->offset ? -1 : 1; 2978 return 0; 2979 } 2980 2981 static void sort_kfunc_descs_by_imm_off(struct bpf_prog *prog) 2982 { 2983 struct bpf_kfunc_desc_tab *tab; 2984 2985 tab = prog->aux->kfunc_tab; 2986 if (!tab) 2987 return; 2988 2989 sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]), 2990 kfunc_desc_cmp_by_imm_off, NULL); 2991 } 2992 2993 bool bpf_prog_has_kfunc_call(const struct bpf_prog *prog) 2994 { 2995 return !!prog->aux->kfunc_tab; 2996 } 2997 2998 const struct btf_func_model * 2999 bpf_jit_find_kfunc_model(const struct bpf_prog *prog, 3000 const struct bpf_insn *insn) 3001 { 3002 const struct bpf_kfunc_desc desc = { 3003 .imm = insn->imm, 3004 .offset = insn->off, 3005 }; 3006 const struct bpf_kfunc_desc *res; 3007 struct bpf_kfunc_desc_tab *tab; 3008 3009 tab = prog->aux->kfunc_tab; 3010 res = bsearch(&desc, tab->descs, tab->nr_descs, 3011 sizeof(tab->descs[0]), kfunc_desc_cmp_by_imm_off); 3012 3013 return res ? &res->func_model : NULL; 3014 } 3015 3016 static int add_subprog_and_kfunc(struct bpf_verifier_env *env) 3017 { 3018 struct bpf_subprog_info *subprog = env->subprog_info; 3019 struct bpf_insn *insn = env->prog->insnsi; 3020 int i, ret, insn_cnt = env->prog->len; 3021 3022 /* Add entry function. */ 3023 ret = add_subprog(env, 0); 3024 if (ret) 3025 return ret; 3026 3027 for (i = 0; i < insn_cnt; i++, insn++) { 3028 if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn) && 3029 !bpf_pseudo_kfunc_call(insn)) 3030 continue; 3031 3032 if (!env->bpf_capable) { 3033 verbose(env, "loading/calling other bpf or kernel functions are allowed for CAP_BPF and CAP_SYS_ADMIN\n"); 3034 return -EPERM; 3035 } 3036 3037 if (bpf_pseudo_func(insn) || bpf_pseudo_call(insn)) 3038 ret = add_subprog(env, i + insn->imm + 1); 3039 else 3040 ret = add_kfunc_call(env, insn->imm, insn->off); 3041 3042 if (ret < 0) 3043 return ret; 3044 } 3045 3046 /* Add a fake 'exit' subprog which could simplify subprog iteration 3047 * logic. 'subprog_cnt' should not be increased. 3048 */ 3049 subprog[env->subprog_cnt].start = insn_cnt; 3050 3051 if (env->log.level & BPF_LOG_LEVEL2) 3052 for (i = 0; i < env->subprog_cnt; i++) 3053 verbose(env, "func#%d @%d\n", i, subprog[i].start); 3054 3055 return 0; 3056 } 3057 3058 static int check_subprogs(struct bpf_verifier_env *env) 3059 { 3060 int i, subprog_start, subprog_end, off, cur_subprog = 0; 3061 struct bpf_subprog_info *subprog = env->subprog_info; 3062 struct bpf_insn *insn = env->prog->insnsi; 3063 int insn_cnt = env->prog->len; 3064 3065 /* now check that all jumps are within the same subprog */ 3066 subprog_start = subprog[cur_subprog].start; 3067 subprog_end = subprog[cur_subprog + 1].start; 3068 for (i = 0; i < insn_cnt; i++) { 3069 u8 code = insn[i].code; 3070 3071 if (code == (BPF_JMP | BPF_CALL) && 3072 insn[i].src_reg == 0 && 3073 insn[i].imm == BPF_FUNC_tail_call) { 3074 subprog[cur_subprog].has_tail_call = true; 3075 subprog[cur_subprog].tail_call_reachable = true; 3076 } 3077 if (BPF_CLASS(code) == BPF_LD && 3078 (BPF_MODE(code) == BPF_ABS || BPF_MODE(code) == BPF_IND)) 3079 subprog[cur_subprog].has_ld_abs = true; 3080 if (BPF_CLASS(code) != BPF_JMP && BPF_CLASS(code) != BPF_JMP32) 3081 goto next; 3082 if (BPF_OP(code) == BPF_EXIT || BPF_OP(code) == BPF_CALL) 3083 goto next; 3084 if (code == (BPF_JMP32 | BPF_JA)) 3085 off = i + insn[i].imm + 1; 3086 else 3087 off = i + insn[i].off + 1; 3088 if (off < subprog_start || off >= subprog_end) { 3089 verbose(env, "jump out of range from insn %d to %d\n", i, off); 3090 return -EINVAL; 3091 } 3092 next: 3093 if (i == subprog_end - 1) { 3094 /* to avoid fall-through from one subprog into another 3095 * the last insn of the subprog should be either exit 3096 * or unconditional jump back 3097 */ 3098 if (code != (BPF_JMP | BPF_EXIT) && 3099 code != (BPF_JMP32 | BPF_JA) && 3100 code != (BPF_JMP | BPF_JA)) { 3101 verbose(env, "last insn is not an exit or jmp\n"); 3102 return -EINVAL; 3103 } 3104 subprog_start = subprog_end; 3105 cur_subprog++; 3106 if (cur_subprog < env->subprog_cnt) 3107 subprog_end = subprog[cur_subprog + 1].start; 3108 } 3109 } 3110 return 0; 3111 } 3112 3113 /* Parentage chain of this register (or stack slot) should take care of all 3114 * issues like callee-saved registers, stack slot allocation time, etc. 3115 */ 3116 static int mark_reg_read(struct bpf_verifier_env *env, 3117 const struct bpf_reg_state *state, 3118 struct bpf_reg_state *parent, u8 flag) 3119 { 3120 bool writes = parent == state->parent; /* Observe write marks */ 3121 int cnt = 0; 3122 3123 while (parent) { 3124 /* if read wasn't screened by an earlier write ... */ 3125 if (writes && state->live & REG_LIVE_WRITTEN) 3126 break; 3127 if (parent->live & REG_LIVE_DONE) { 3128 verbose(env, "verifier BUG type %s var_off %lld off %d\n", 3129 reg_type_str(env, parent->type), 3130 parent->var_off.value, parent->off); 3131 return -EFAULT; 3132 } 3133 /* The first condition is more likely to be true than the 3134 * second, checked it first. 3135 */ 3136 if ((parent->live & REG_LIVE_READ) == flag || 3137 parent->live & REG_LIVE_READ64) 3138 /* The parentage chain never changes and 3139 * this parent was already marked as LIVE_READ. 3140 * There is no need to keep walking the chain again and 3141 * keep re-marking all parents as LIVE_READ. 3142 * This case happens when the same register is read 3143 * multiple times without writes into it in-between. 3144 * Also, if parent has the stronger REG_LIVE_READ64 set, 3145 * then no need to set the weak REG_LIVE_READ32. 3146 */ 3147 break; 3148 /* ... then we depend on parent's value */ 3149 parent->live |= flag; 3150 /* REG_LIVE_READ64 overrides REG_LIVE_READ32. */ 3151 if (flag == REG_LIVE_READ64) 3152 parent->live &= ~REG_LIVE_READ32; 3153 state = parent; 3154 parent = state->parent; 3155 writes = true; 3156 cnt++; 3157 } 3158 3159 if (env->longest_mark_read_walk < cnt) 3160 env->longest_mark_read_walk = cnt; 3161 return 0; 3162 } 3163 3164 static int mark_dynptr_read(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 3165 { 3166 struct bpf_func_state *state = func(env, reg); 3167 int spi, ret; 3168 3169 /* For CONST_PTR_TO_DYNPTR, it must have already been done by 3170 * check_reg_arg in check_helper_call and mark_btf_func_reg_size in 3171 * check_kfunc_call. 3172 */ 3173 if (reg->type == CONST_PTR_TO_DYNPTR) 3174 return 0; 3175 spi = dynptr_get_spi(env, reg); 3176 if (spi < 0) 3177 return spi; 3178 /* Caller ensures dynptr is valid and initialized, which means spi is in 3179 * bounds and spi is the first dynptr slot. Simply mark stack slot as 3180 * read. 3181 */ 3182 ret = mark_reg_read(env, &state->stack[spi].spilled_ptr, 3183 state->stack[spi].spilled_ptr.parent, REG_LIVE_READ64); 3184 if (ret) 3185 return ret; 3186 return mark_reg_read(env, &state->stack[spi - 1].spilled_ptr, 3187 state->stack[spi - 1].spilled_ptr.parent, REG_LIVE_READ64); 3188 } 3189 3190 static int mark_iter_read(struct bpf_verifier_env *env, struct bpf_reg_state *reg, 3191 int spi, int nr_slots) 3192 { 3193 struct bpf_func_state *state = func(env, reg); 3194 int err, i; 3195 3196 for (i = 0; i < nr_slots; i++) { 3197 struct bpf_reg_state *st = &state->stack[spi - i].spilled_ptr; 3198 3199 err = mark_reg_read(env, st, st->parent, REG_LIVE_READ64); 3200 if (err) 3201 return err; 3202 3203 mark_stack_slot_scratched(env, spi - i); 3204 } 3205 3206 return 0; 3207 } 3208 3209 /* This function is supposed to be used by the following 32-bit optimization 3210 * code only. It returns TRUE if the source or destination register operates 3211 * on 64-bit, otherwise return FALSE. 3212 */ 3213 static bool is_reg64(struct bpf_verifier_env *env, struct bpf_insn *insn, 3214 u32 regno, struct bpf_reg_state *reg, enum reg_arg_type t) 3215 { 3216 u8 code, class, op; 3217 3218 code = insn->code; 3219 class = BPF_CLASS(code); 3220 op = BPF_OP(code); 3221 if (class == BPF_JMP) { 3222 /* BPF_EXIT for "main" will reach here. Return TRUE 3223 * conservatively. 3224 */ 3225 if (op == BPF_EXIT) 3226 return true; 3227 if (op == BPF_CALL) { 3228 /* BPF to BPF call will reach here because of marking 3229 * caller saved clobber with DST_OP_NO_MARK for which we 3230 * don't care the register def because they are anyway 3231 * marked as NOT_INIT already. 3232 */ 3233 if (insn->src_reg == BPF_PSEUDO_CALL) 3234 return false; 3235 /* Helper call will reach here because of arg type 3236 * check, conservatively return TRUE. 3237 */ 3238 if (t == SRC_OP) 3239 return true; 3240 3241 return false; 3242 } 3243 } 3244 3245 if (class == BPF_ALU64 && op == BPF_END && (insn->imm == 16 || insn->imm == 32)) 3246 return false; 3247 3248 if (class == BPF_ALU64 || class == BPF_JMP || 3249 (class == BPF_ALU && op == BPF_END && insn->imm == 64)) 3250 return true; 3251 3252 if (class == BPF_ALU || class == BPF_JMP32) 3253 return false; 3254 3255 if (class == BPF_LDX) { 3256 if (t != SRC_OP) 3257 return BPF_SIZE(code) == BPF_DW; 3258 /* LDX source must be ptr. */ 3259 return true; 3260 } 3261 3262 if (class == BPF_STX) { 3263 /* BPF_STX (including atomic variants) has multiple source 3264 * operands, one of which is a ptr. Check whether the caller is 3265 * asking about it. 3266 */ 3267 if (t == SRC_OP && reg->type != SCALAR_VALUE) 3268 return true; 3269 return BPF_SIZE(code) == BPF_DW; 3270 } 3271 3272 if (class == BPF_LD) { 3273 u8 mode = BPF_MODE(code); 3274 3275 /* LD_IMM64 */ 3276 if (mode == BPF_IMM) 3277 return true; 3278 3279 /* Both LD_IND and LD_ABS return 32-bit data. */ 3280 if (t != SRC_OP) 3281 return false; 3282 3283 /* Implicit ctx ptr. */ 3284 if (regno == BPF_REG_6) 3285 return true; 3286 3287 /* Explicit source could be any width. */ 3288 return true; 3289 } 3290 3291 if (class == BPF_ST) 3292 /* The only source register for BPF_ST is a ptr. */ 3293 return true; 3294 3295 /* Conservatively return true at default. */ 3296 return true; 3297 } 3298 3299 /* Return the regno defined by the insn, or -1. */ 3300 static int insn_def_regno(const struct bpf_insn *insn) 3301 { 3302 switch (BPF_CLASS(insn->code)) { 3303 case BPF_JMP: 3304 case BPF_JMP32: 3305 case BPF_ST: 3306 return -1; 3307 case BPF_STX: 3308 if (BPF_MODE(insn->code) == BPF_ATOMIC && 3309 (insn->imm & BPF_FETCH)) { 3310 if (insn->imm == BPF_CMPXCHG) 3311 return BPF_REG_0; 3312 else 3313 return insn->src_reg; 3314 } else { 3315 return -1; 3316 } 3317 default: 3318 return insn->dst_reg; 3319 } 3320 } 3321 3322 /* Return TRUE if INSN has defined any 32-bit value explicitly. */ 3323 static bool insn_has_def32(struct bpf_verifier_env *env, struct bpf_insn *insn) 3324 { 3325 int dst_reg = insn_def_regno(insn); 3326 3327 if (dst_reg == -1) 3328 return false; 3329 3330 return !is_reg64(env, insn, dst_reg, NULL, DST_OP); 3331 } 3332 3333 static void mark_insn_zext(struct bpf_verifier_env *env, 3334 struct bpf_reg_state *reg) 3335 { 3336 s32 def_idx = reg->subreg_def; 3337 3338 if (def_idx == DEF_NOT_SUBREG) 3339 return; 3340 3341 env->insn_aux_data[def_idx - 1].zext_dst = true; 3342 /* The dst will be zero extended, so won't be sub-register anymore. */ 3343 reg->subreg_def = DEF_NOT_SUBREG; 3344 } 3345 3346 static int __check_reg_arg(struct bpf_verifier_env *env, struct bpf_reg_state *regs, u32 regno, 3347 enum reg_arg_type t) 3348 { 3349 struct bpf_insn *insn = env->prog->insnsi + env->insn_idx; 3350 struct bpf_reg_state *reg; 3351 bool rw64; 3352 3353 if (regno >= MAX_BPF_REG) { 3354 verbose(env, "R%d is invalid\n", regno); 3355 return -EINVAL; 3356 } 3357 3358 mark_reg_scratched(env, regno); 3359 3360 reg = ®s[regno]; 3361 rw64 = is_reg64(env, insn, regno, reg, t); 3362 if (t == SRC_OP) { 3363 /* check whether register used as source operand can be read */ 3364 if (reg->type == NOT_INIT) { 3365 verbose(env, "R%d !read_ok\n", regno); 3366 return -EACCES; 3367 } 3368 /* We don't need to worry about FP liveness because it's read-only */ 3369 if (regno == BPF_REG_FP) 3370 return 0; 3371 3372 if (rw64) 3373 mark_insn_zext(env, reg); 3374 3375 return mark_reg_read(env, reg, reg->parent, 3376 rw64 ? REG_LIVE_READ64 : REG_LIVE_READ32); 3377 } else { 3378 /* check whether register used as dest operand can be written to */ 3379 if (regno == BPF_REG_FP) { 3380 verbose(env, "frame pointer is read only\n"); 3381 return -EACCES; 3382 } 3383 reg->live |= REG_LIVE_WRITTEN; 3384 reg->subreg_def = rw64 ? DEF_NOT_SUBREG : env->insn_idx + 1; 3385 if (t == DST_OP) 3386 mark_reg_unknown(env, regs, regno); 3387 } 3388 return 0; 3389 } 3390 3391 static int check_reg_arg(struct bpf_verifier_env *env, u32 regno, 3392 enum reg_arg_type t) 3393 { 3394 struct bpf_verifier_state *vstate = env->cur_state; 3395 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 3396 3397 return __check_reg_arg(env, state->regs, regno, t); 3398 } 3399 3400 static int insn_stack_access_flags(int frameno, int spi) 3401 { 3402 return INSN_F_STACK_ACCESS | (spi << INSN_F_SPI_SHIFT) | frameno; 3403 } 3404 3405 static int insn_stack_access_spi(int insn_flags) 3406 { 3407 return (insn_flags >> INSN_F_SPI_SHIFT) & INSN_F_SPI_MASK; 3408 } 3409 3410 static int insn_stack_access_frameno(int insn_flags) 3411 { 3412 return insn_flags & INSN_F_FRAMENO_MASK; 3413 } 3414 3415 static void mark_jmp_point(struct bpf_verifier_env *env, int idx) 3416 { 3417 env->insn_aux_data[idx].jmp_point = true; 3418 } 3419 3420 static bool is_jmp_point(struct bpf_verifier_env *env, int insn_idx) 3421 { 3422 return env->insn_aux_data[insn_idx].jmp_point; 3423 } 3424 3425 /* for any branch, call, exit record the history of jmps in the given state */ 3426 static int push_jmp_history(struct bpf_verifier_env *env, struct bpf_verifier_state *cur, 3427 int insn_flags) 3428 { 3429 u32 cnt = cur->jmp_history_cnt; 3430 struct bpf_jmp_history_entry *p; 3431 size_t alloc_size; 3432 3433 /* combine instruction flags if we already recorded this instruction */ 3434 if (env->cur_hist_ent) { 3435 /* atomic instructions push insn_flags twice, for READ and 3436 * WRITE sides, but they should agree on stack slot 3437 */ 3438 WARN_ONCE((env->cur_hist_ent->flags & insn_flags) && 3439 (env->cur_hist_ent->flags & insn_flags) != insn_flags, 3440 "verifier insn history bug: insn_idx %d cur flags %x new flags %x\n", 3441 env->insn_idx, env->cur_hist_ent->flags, insn_flags); 3442 env->cur_hist_ent->flags |= insn_flags; 3443 return 0; 3444 } 3445 3446 cnt++; 3447 alloc_size = kmalloc_size_roundup(size_mul(cnt, sizeof(*p))); 3448 p = krealloc(cur->jmp_history, alloc_size, GFP_USER); 3449 if (!p) 3450 return -ENOMEM; 3451 cur->jmp_history = p; 3452 3453 p = &cur->jmp_history[cnt - 1]; 3454 p->idx = env->insn_idx; 3455 p->prev_idx = env->prev_insn_idx; 3456 p->flags = insn_flags; 3457 cur->jmp_history_cnt = cnt; 3458 env->cur_hist_ent = p; 3459 3460 return 0; 3461 } 3462 3463 static struct bpf_jmp_history_entry *get_jmp_hist_entry(struct bpf_verifier_state *st, 3464 u32 hist_end, int insn_idx) 3465 { 3466 if (hist_end > 0 && st->jmp_history[hist_end - 1].idx == insn_idx) 3467 return &st->jmp_history[hist_end - 1]; 3468 return NULL; 3469 } 3470 3471 /* Backtrack one insn at a time. If idx is not at the top of recorded 3472 * history then previous instruction came from straight line execution. 3473 * Return -ENOENT if we exhausted all instructions within given state. 3474 * 3475 * It's legal to have a bit of a looping with the same starting and ending 3476 * insn index within the same state, e.g.: 3->4->5->3, so just because current 3477 * instruction index is the same as state's first_idx doesn't mean we are 3478 * done. If there is still some jump history left, we should keep going. We 3479 * need to take into account that we might have a jump history between given 3480 * state's parent and itself, due to checkpointing. In this case, we'll have 3481 * history entry recording a jump from last instruction of parent state and 3482 * first instruction of given state. 3483 */ 3484 static int get_prev_insn_idx(struct bpf_verifier_state *st, int i, 3485 u32 *history) 3486 { 3487 u32 cnt = *history; 3488 3489 if (i == st->first_insn_idx) { 3490 if (cnt == 0) 3491 return -ENOENT; 3492 if (cnt == 1 && st->jmp_history[0].idx == i) 3493 return -ENOENT; 3494 } 3495 3496 if (cnt && st->jmp_history[cnt - 1].idx == i) { 3497 i = st->jmp_history[cnt - 1].prev_idx; 3498 (*history)--; 3499 } else { 3500 i--; 3501 } 3502 return i; 3503 } 3504 3505 static const char *disasm_kfunc_name(void *data, const struct bpf_insn *insn) 3506 { 3507 const struct btf_type *func; 3508 struct btf *desc_btf; 3509 3510 if (insn->src_reg != BPF_PSEUDO_KFUNC_CALL) 3511 return NULL; 3512 3513 desc_btf = find_kfunc_desc_btf(data, insn->off); 3514 if (IS_ERR(desc_btf)) 3515 return "<error>"; 3516 3517 func = btf_type_by_id(desc_btf, insn->imm); 3518 return btf_name_by_offset(desc_btf, func->name_off); 3519 } 3520 3521 static inline void bt_init(struct backtrack_state *bt, u32 frame) 3522 { 3523 bt->frame = frame; 3524 } 3525 3526 static inline void bt_reset(struct backtrack_state *bt) 3527 { 3528 struct bpf_verifier_env *env = bt->env; 3529 3530 memset(bt, 0, sizeof(*bt)); 3531 bt->env = env; 3532 } 3533 3534 static inline u32 bt_empty(struct backtrack_state *bt) 3535 { 3536 u64 mask = 0; 3537 int i; 3538 3539 for (i = 0; i <= bt->frame; i++) 3540 mask |= bt->reg_masks[i] | bt->stack_masks[i]; 3541 3542 return mask == 0; 3543 } 3544 3545 static inline int bt_subprog_enter(struct backtrack_state *bt) 3546 { 3547 if (bt->frame == MAX_CALL_FRAMES - 1) { 3548 verbose(bt->env, "BUG subprog enter from frame %d\n", bt->frame); 3549 WARN_ONCE(1, "verifier backtracking bug"); 3550 return -EFAULT; 3551 } 3552 bt->frame++; 3553 return 0; 3554 } 3555 3556 static inline int bt_subprog_exit(struct backtrack_state *bt) 3557 { 3558 if (bt->frame == 0) { 3559 verbose(bt->env, "BUG subprog exit from frame 0\n"); 3560 WARN_ONCE(1, "verifier backtracking bug"); 3561 return -EFAULT; 3562 } 3563 bt->frame--; 3564 return 0; 3565 } 3566 3567 static inline void bt_set_frame_reg(struct backtrack_state *bt, u32 frame, u32 reg) 3568 { 3569 bt->reg_masks[frame] |= 1 << reg; 3570 } 3571 3572 static inline void bt_clear_frame_reg(struct backtrack_state *bt, u32 frame, u32 reg) 3573 { 3574 bt->reg_masks[frame] &= ~(1 << reg); 3575 } 3576 3577 static inline void bt_set_reg(struct backtrack_state *bt, u32 reg) 3578 { 3579 bt_set_frame_reg(bt, bt->frame, reg); 3580 } 3581 3582 static inline void bt_clear_reg(struct backtrack_state *bt, u32 reg) 3583 { 3584 bt_clear_frame_reg(bt, bt->frame, reg); 3585 } 3586 3587 static inline void bt_set_frame_slot(struct backtrack_state *bt, u32 frame, u32 slot) 3588 { 3589 bt->stack_masks[frame] |= 1ull << slot; 3590 } 3591 3592 static inline void bt_clear_frame_slot(struct backtrack_state *bt, u32 frame, u32 slot) 3593 { 3594 bt->stack_masks[frame] &= ~(1ull << slot); 3595 } 3596 3597 static inline void bt_set_slot(struct backtrack_state *bt, u32 slot) 3598 { 3599 bt_set_frame_slot(bt, bt->frame, slot); 3600 } 3601 3602 static inline void bt_clear_slot(struct backtrack_state *bt, u32 slot) 3603 { 3604 bt_clear_frame_slot(bt, bt->frame, slot); 3605 } 3606 3607 static inline u32 bt_frame_reg_mask(struct backtrack_state *bt, u32 frame) 3608 { 3609 return bt->reg_masks[frame]; 3610 } 3611 3612 static inline u32 bt_reg_mask(struct backtrack_state *bt) 3613 { 3614 return bt->reg_masks[bt->frame]; 3615 } 3616 3617 static inline u64 bt_frame_stack_mask(struct backtrack_state *bt, u32 frame) 3618 { 3619 return bt->stack_masks[frame]; 3620 } 3621 3622 static inline u64 bt_stack_mask(struct backtrack_state *bt) 3623 { 3624 return bt->stack_masks[bt->frame]; 3625 } 3626 3627 static inline bool bt_is_reg_set(struct backtrack_state *bt, u32 reg) 3628 { 3629 return bt->reg_masks[bt->frame] & (1 << reg); 3630 } 3631 3632 static inline bool bt_is_frame_slot_set(struct backtrack_state *bt, u32 frame, u32 slot) 3633 { 3634 return bt->stack_masks[frame] & (1ull << slot); 3635 } 3636 3637 static inline bool bt_is_slot_set(struct backtrack_state *bt, u32 slot) 3638 { 3639 return bt_is_frame_slot_set(bt, bt->frame, slot); 3640 } 3641 3642 /* format registers bitmask, e.g., "r0,r2,r4" for 0x15 mask */ 3643 static void fmt_reg_mask(char *buf, ssize_t buf_sz, u32 reg_mask) 3644 { 3645 DECLARE_BITMAP(mask, 64); 3646 bool first = true; 3647 int i, n; 3648 3649 buf[0] = '\0'; 3650 3651 bitmap_from_u64(mask, reg_mask); 3652 for_each_set_bit(i, mask, 32) { 3653 n = snprintf(buf, buf_sz, "%sr%d", first ? "" : ",", i); 3654 first = false; 3655 buf += n; 3656 buf_sz -= n; 3657 if (buf_sz < 0) 3658 break; 3659 } 3660 } 3661 /* format stack slots bitmask, e.g., "-8,-24,-40" for 0x15 mask */ 3662 static void fmt_stack_mask(char *buf, ssize_t buf_sz, u64 stack_mask) 3663 { 3664 DECLARE_BITMAP(mask, 64); 3665 bool first = true; 3666 int i, n; 3667 3668 buf[0] = '\0'; 3669 3670 bitmap_from_u64(mask, stack_mask); 3671 for_each_set_bit(i, mask, 64) { 3672 n = snprintf(buf, buf_sz, "%s%d", first ? "" : ",", -(i + 1) * 8); 3673 first = false; 3674 buf += n; 3675 buf_sz -= n; 3676 if (buf_sz < 0) 3677 break; 3678 } 3679 } 3680 3681 static bool calls_callback(struct bpf_verifier_env *env, int insn_idx); 3682 3683 /* For given verifier state backtrack_insn() is called from the last insn to 3684 * the first insn. Its purpose is to compute a bitmask of registers and 3685 * stack slots that needs precision in the parent verifier state. 3686 * 3687 * @idx is an index of the instruction we are currently processing; 3688 * @subseq_idx is an index of the subsequent instruction that: 3689 * - *would be* executed next, if jump history is viewed in forward order; 3690 * - *was* processed previously during backtracking. 3691 */ 3692 static int backtrack_insn(struct bpf_verifier_env *env, int idx, int subseq_idx, 3693 struct bpf_jmp_history_entry *hist, struct backtrack_state *bt) 3694 { 3695 const struct bpf_insn_cbs cbs = { 3696 .cb_call = disasm_kfunc_name, 3697 .cb_print = verbose, 3698 .private_data = env, 3699 }; 3700 struct bpf_insn *insn = env->prog->insnsi + idx; 3701 u8 class = BPF_CLASS(insn->code); 3702 u8 opcode = BPF_OP(insn->code); 3703 u8 mode = BPF_MODE(insn->code); 3704 u32 dreg = insn->dst_reg; 3705 u32 sreg = insn->src_reg; 3706 u32 spi, i, fr; 3707 3708 if (insn->code == 0) 3709 return 0; 3710 if (env->log.level & BPF_LOG_LEVEL2) { 3711 fmt_reg_mask(env->tmp_str_buf, TMP_STR_BUF_LEN, bt_reg_mask(bt)); 3712 verbose(env, "mark_precise: frame%d: regs=%s ", 3713 bt->frame, env->tmp_str_buf); 3714 fmt_stack_mask(env->tmp_str_buf, TMP_STR_BUF_LEN, bt_stack_mask(bt)); 3715 verbose(env, "stack=%s before ", env->tmp_str_buf); 3716 verbose(env, "%d: ", idx); 3717 print_bpf_insn(&cbs, insn, env->allow_ptr_leaks); 3718 } 3719 3720 if (class == BPF_ALU || class == BPF_ALU64) { 3721 if (!bt_is_reg_set(bt, dreg)) 3722 return 0; 3723 if (opcode == BPF_END || opcode == BPF_NEG) { 3724 /* sreg is reserved and unused 3725 * dreg still need precision before this insn 3726 */ 3727 return 0; 3728 } else if (opcode == BPF_MOV) { 3729 if (BPF_SRC(insn->code) == BPF_X) { 3730 /* dreg = sreg or dreg = (s8, s16, s32)sreg 3731 * dreg needs precision after this insn 3732 * sreg needs precision before this insn 3733 */ 3734 bt_clear_reg(bt, dreg); 3735 if (sreg != BPF_REG_FP) 3736 bt_set_reg(bt, sreg); 3737 } else { 3738 /* dreg = K 3739 * dreg needs precision after this insn. 3740 * Corresponding register is already marked 3741 * as precise=true in this verifier state. 3742 * No further markings in parent are necessary 3743 */ 3744 bt_clear_reg(bt, dreg); 3745 } 3746 } else { 3747 if (BPF_SRC(insn->code) == BPF_X) { 3748 /* dreg += sreg 3749 * both dreg and sreg need precision 3750 * before this insn 3751 */ 3752 if (sreg != BPF_REG_FP) 3753 bt_set_reg(bt, sreg); 3754 } /* else dreg += K 3755 * dreg still needs precision before this insn 3756 */ 3757 } 3758 } else if (class == BPF_LDX) { 3759 if (!bt_is_reg_set(bt, dreg)) 3760 return 0; 3761 bt_clear_reg(bt, dreg); 3762 3763 /* scalars can only be spilled into stack w/o losing precision. 3764 * Load from any other memory can be zero extended. 3765 * The desire to keep that precision is already indicated 3766 * by 'precise' mark in corresponding register of this state. 3767 * No further tracking necessary. 3768 */ 3769 if (!hist || !(hist->flags & INSN_F_STACK_ACCESS)) 3770 return 0; 3771 /* dreg = *(u64 *)[fp - off] was a fill from the stack. 3772 * that [fp - off] slot contains scalar that needs to be 3773 * tracked with precision 3774 */ 3775 spi = insn_stack_access_spi(hist->flags); 3776 fr = insn_stack_access_frameno(hist->flags); 3777 bt_set_frame_slot(bt, fr, spi); 3778 } else if (class == BPF_STX || class == BPF_ST) { 3779 if (bt_is_reg_set(bt, dreg)) 3780 /* stx & st shouldn't be using _scalar_ dst_reg 3781 * to access memory. It means backtracking 3782 * encountered a case of pointer subtraction. 3783 */ 3784 return -ENOTSUPP; 3785 /* scalars can only be spilled into stack */ 3786 if (!hist || !(hist->flags & INSN_F_STACK_ACCESS)) 3787 return 0; 3788 spi = insn_stack_access_spi(hist->flags); 3789 fr = insn_stack_access_frameno(hist->flags); 3790 if (!bt_is_frame_slot_set(bt, fr, spi)) 3791 return 0; 3792 bt_clear_frame_slot(bt, fr, spi); 3793 if (class == BPF_STX) 3794 bt_set_reg(bt, sreg); 3795 } else if (class == BPF_JMP || class == BPF_JMP32) { 3796 if (bpf_pseudo_call(insn)) { 3797 int subprog_insn_idx, subprog; 3798 3799 subprog_insn_idx = idx + insn->imm + 1; 3800 subprog = find_subprog(env, subprog_insn_idx); 3801 if (subprog < 0) 3802 return -EFAULT; 3803 3804 if (subprog_is_global(env, subprog)) { 3805 /* check that jump history doesn't have any 3806 * extra instructions from subprog; the next 3807 * instruction after call to global subprog 3808 * should be literally next instruction in 3809 * caller program 3810 */ 3811 WARN_ONCE(idx + 1 != subseq_idx, "verifier backtracking bug"); 3812 /* r1-r5 are invalidated after subprog call, 3813 * so for global func call it shouldn't be set 3814 * anymore 3815 */ 3816 if (bt_reg_mask(bt) & BPF_REGMASK_ARGS) { 3817 verbose(env, "BUG regs %x\n", bt_reg_mask(bt)); 3818 WARN_ONCE(1, "verifier backtracking bug"); 3819 return -EFAULT; 3820 } 3821 /* global subprog always sets R0 */ 3822 bt_clear_reg(bt, BPF_REG_0); 3823 return 0; 3824 } else { 3825 /* static subprog call instruction, which 3826 * means that we are exiting current subprog, 3827 * so only r1-r5 could be still requested as 3828 * precise, r0 and r6-r10 or any stack slot in 3829 * the current frame should be zero by now 3830 */ 3831 if (bt_reg_mask(bt) & ~BPF_REGMASK_ARGS) { 3832 verbose(env, "BUG regs %x\n", bt_reg_mask(bt)); 3833 WARN_ONCE(1, "verifier backtracking bug"); 3834 return -EFAULT; 3835 } 3836 /* we are now tracking register spills correctly, 3837 * so any instance of leftover slots is a bug 3838 */ 3839 if (bt_stack_mask(bt) != 0) { 3840 verbose(env, "BUG stack slots %llx\n", bt_stack_mask(bt)); 3841 WARN_ONCE(1, "verifier backtracking bug (subprog leftover stack slots)"); 3842 return -EFAULT; 3843 } 3844 /* propagate r1-r5 to the caller */ 3845 for (i = BPF_REG_1; i <= BPF_REG_5; i++) { 3846 if (bt_is_reg_set(bt, i)) { 3847 bt_clear_reg(bt, i); 3848 bt_set_frame_reg(bt, bt->frame - 1, i); 3849 } 3850 } 3851 if (bt_subprog_exit(bt)) 3852 return -EFAULT; 3853 return 0; 3854 } 3855 } else if (is_sync_callback_calling_insn(insn) && idx != subseq_idx - 1) { 3856 /* exit from callback subprog to callback-calling helper or 3857 * kfunc call. Use idx/subseq_idx check to discern it from 3858 * straight line code backtracking. 3859 * Unlike the subprog call handling above, we shouldn't 3860 * propagate precision of r1-r5 (if any requested), as they are 3861 * not actually arguments passed directly to callback subprogs 3862 */ 3863 if (bt_reg_mask(bt) & ~BPF_REGMASK_ARGS) { 3864 verbose(env, "BUG regs %x\n", bt_reg_mask(bt)); 3865 WARN_ONCE(1, "verifier backtracking bug"); 3866 return -EFAULT; 3867 } 3868 if (bt_stack_mask(bt) != 0) { 3869 verbose(env, "BUG stack slots %llx\n", bt_stack_mask(bt)); 3870 WARN_ONCE(1, "verifier backtracking bug (callback leftover stack slots)"); 3871 return -EFAULT; 3872 } 3873 /* clear r1-r5 in callback subprog's mask */ 3874 for (i = BPF_REG_1; i <= BPF_REG_5; i++) 3875 bt_clear_reg(bt, i); 3876 if (bt_subprog_exit(bt)) 3877 return -EFAULT; 3878 return 0; 3879 } else if (opcode == BPF_CALL) { 3880 /* kfunc with imm==0 is invalid and fixup_kfunc_call will 3881 * catch this error later. Make backtracking conservative 3882 * with ENOTSUPP. 3883 */ 3884 if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL && insn->imm == 0) 3885 return -ENOTSUPP; 3886 /* regular helper call sets R0 */ 3887 bt_clear_reg(bt, BPF_REG_0); 3888 if (bt_reg_mask(bt) & BPF_REGMASK_ARGS) { 3889 /* if backtracing was looking for registers R1-R5 3890 * they should have been found already. 3891 */ 3892 verbose(env, "BUG regs %x\n", bt_reg_mask(bt)); 3893 WARN_ONCE(1, "verifier backtracking bug"); 3894 return -EFAULT; 3895 } 3896 } else if (opcode == BPF_EXIT) { 3897 bool r0_precise; 3898 3899 /* Backtracking to a nested function call, 'idx' is a part of 3900 * the inner frame 'subseq_idx' is a part of the outer frame. 3901 * In case of a regular function call, instructions giving 3902 * precision to registers R1-R5 should have been found already. 3903 * In case of a callback, it is ok to have R1-R5 marked for 3904 * backtracking, as these registers are set by the function 3905 * invoking callback. 3906 */ 3907 if (subseq_idx >= 0 && calls_callback(env, subseq_idx)) 3908 for (i = BPF_REG_1; i <= BPF_REG_5; i++) 3909 bt_clear_reg(bt, i); 3910 if (bt_reg_mask(bt) & BPF_REGMASK_ARGS) { 3911 verbose(env, "BUG regs %x\n", bt_reg_mask(bt)); 3912 WARN_ONCE(1, "verifier backtracking bug"); 3913 return -EFAULT; 3914 } 3915 3916 /* BPF_EXIT in subprog or callback always returns 3917 * right after the call instruction, so by checking 3918 * whether the instruction at subseq_idx-1 is subprog 3919 * call or not we can distinguish actual exit from 3920 * *subprog* from exit from *callback*. In the former 3921 * case, we need to propagate r0 precision, if 3922 * necessary. In the former we never do that. 3923 */ 3924 r0_precise = subseq_idx - 1 >= 0 && 3925 bpf_pseudo_call(&env->prog->insnsi[subseq_idx - 1]) && 3926 bt_is_reg_set(bt, BPF_REG_0); 3927 3928 bt_clear_reg(bt, BPF_REG_0); 3929 if (bt_subprog_enter(bt)) 3930 return -EFAULT; 3931 3932 if (r0_precise) 3933 bt_set_reg(bt, BPF_REG_0); 3934 /* r6-r9 and stack slots will stay set in caller frame 3935 * bitmasks until we return back from callee(s) 3936 */ 3937 return 0; 3938 } else if (BPF_SRC(insn->code) == BPF_X) { 3939 if (!bt_is_reg_set(bt, dreg) && !bt_is_reg_set(bt, sreg)) 3940 return 0; 3941 /* dreg <cond> sreg 3942 * Both dreg and sreg need precision before 3943 * this insn. If only sreg was marked precise 3944 * before it would be equally necessary to 3945 * propagate it to dreg. 3946 */ 3947 bt_set_reg(bt, dreg); 3948 bt_set_reg(bt, sreg); 3949 /* else dreg <cond> K 3950 * Only dreg still needs precision before 3951 * this insn, so for the K-based conditional 3952 * there is nothing new to be marked. 3953 */ 3954 } 3955 } else if (class == BPF_LD) { 3956 if (!bt_is_reg_set(bt, dreg)) 3957 return 0; 3958 bt_clear_reg(bt, dreg); 3959 /* It's ld_imm64 or ld_abs or ld_ind. 3960 * For ld_imm64 no further tracking of precision 3961 * into parent is necessary 3962 */ 3963 if (mode == BPF_IND || mode == BPF_ABS) 3964 /* to be analyzed */ 3965 return -ENOTSUPP; 3966 } 3967 return 0; 3968 } 3969 3970 /* the scalar precision tracking algorithm: 3971 * . at the start all registers have precise=false. 3972 * . scalar ranges are tracked as normal through alu and jmp insns. 3973 * . once precise value of the scalar register is used in: 3974 * . ptr + scalar alu 3975 * . if (scalar cond K|scalar) 3976 * . helper_call(.., scalar, ...) where ARG_CONST is expected 3977 * backtrack through the verifier states and mark all registers and 3978 * stack slots with spilled constants that these scalar regisers 3979 * should be precise. 3980 * . during state pruning two registers (or spilled stack slots) 3981 * are equivalent if both are not precise. 3982 * 3983 * Note the verifier cannot simply walk register parentage chain, 3984 * since many different registers and stack slots could have been 3985 * used to compute single precise scalar. 3986 * 3987 * The approach of starting with precise=true for all registers and then 3988 * backtrack to mark a register as not precise when the verifier detects 3989 * that program doesn't care about specific value (e.g., when helper 3990 * takes register as ARG_ANYTHING parameter) is not safe. 3991 * 3992 * It's ok to walk single parentage chain of the verifier states. 3993 * It's possible that this backtracking will go all the way till 1st insn. 3994 * All other branches will be explored for needing precision later. 3995 * 3996 * The backtracking needs to deal with cases like: 3997 * 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) 3998 * r9 -= r8 3999 * r5 = r9 4000 * if r5 > 0x79f goto pc+7 4001 * R5_w=inv(id=0,umax_value=1951,var_off=(0x0; 0x7ff)) 4002 * r5 += 1 4003 * ... 4004 * call bpf_perf_event_output#25 4005 * where .arg5_type = ARG_CONST_SIZE_OR_ZERO 4006 * 4007 * and this case: 4008 * r6 = 1 4009 * call foo // uses callee's r6 inside to compute r0 4010 * r0 += r6 4011 * if r0 == 0 goto 4012 * 4013 * to track above reg_mask/stack_mask needs to be independent for each frame. 4014 * 4015 * Also if parent's curframe > frame where backtracking started, 4016 * the verifier need to mark registers in both frames, otherwise callees 4017 * may incorrectly prune callers. This is similar to 4018 * commit 7640ead93924 ("bpf: verifier: make sure callees don't prune with caller differences") 4019 * 4020 * For now backtracking falls back into conservative marking. 4021 */ 4022 static void mark_all_scalars_precise(struct bpf_verifier_env *env, 4023 struct bpf_verifier_state *st) 4024 { 4025 struct bpf_func_state *func; 4026 struct bpf_reg_state *reg; 4027 int i, j; 4028 4029 if (env->log.level & BPF_LOG_LEVEL2) { 4030 verbose(env, "mark_precise: frame%d: falling back to forcing all scalars precise\n", 4031 st->curframe); 4032 } 4033 4034 /* big hammer: mark all scalars precise in this path. 4035 * pop_stack may still get !precise scalars. 4036 * We also skip current state and go straight to first parent state, 4037 * because precision markings in current non-checkpointed state are 4038 * not needed. See why in the comment in __mark_chain_precision below. 4039 */ 4040 for (st = st->parent; st; st = st->parent) { 4041 for (i = 0; i <= st->curframe; i++) { 4042 func = st->frame[i]; 4043 for (j = 0; j < BPF_REG_FP; j++) { 4044 reg = &func->regs[j]; 4045 if (reg->type != SCALAR_VALUE || reg->precise) 4046 continue; 4047 reg->precise = true; 4048 if (env->log.level & BPF_LOG_LEVEL2) { 4049 verbose(env, "force_precise: frame%d: forcing r%d to be precise\n", 4050 i, j); 4051 } 4052 } 4053 for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) { 4054 if (!is_spilled_reg(&func->stack[j])) 4055 continue; 4056 reg = &func->stack[j].spilled_ptr; 4057 if (reg->type != SCALAR_VALUE || reg->precise) 4058 continue; 4059 reg->precise = true; 4060 if (env->log.level & BPF_LOG_LEVEL2) { 4061 verbose(env, "force_precise: frame%d: forcing fp%d to be precise\n", 4062 i, -(j + 1) * 8); 4063 } 4064 } 4065 } 4066 } 4067 } 4068 4069 static void mark_all_scalars_imprecise(struct bpf_verifier_env *env, struct bpf_verifier_state *st) 4070 { 4071 struct bpf_func_state *func; 4072 struct bpf_reg_state *reg; 4073 int i, j; 4074 4075 for (i = 0; i <= st->curframe; i++) { 4076 func = st->frame[i]; 4077 for (j = 0; j < BPF_REG_FP; j++) { 4078 reg = &func->regs[j]; 4079 if (reg->type != SCALAR_VALUE) 4080 continue; 4081 reg->precise = false; 4082 } 4083 for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) { 4084 if (!is_spilled_reg(&func->stack[j])) 4085 continue; 4086 reg = &func->stack[j].spilled_ptr; 4087 if (reg->type != SCALAR_VALUE) 4088 continue; 4089 reg->precise = false; 4090 } 4091 } 4092 } 4093 4094 static bool idset_contains(struct bpf_idset *s, u32 id) 4095 { 4096 u32 i; 4097 4098 for (i = 0; i < s->count; ++i) 4099 if (s->ids[i] == id) 4100 return true; 4101 4102 return false; 4103 } 4104 4105 static int idset_push(struct bpf_idset *s, u32 id) 4106 { 4107 if (WARN_ON_ONCE(s->count >= ARRAY_SIZE(s->ids))) 4108 return -EFAULT; 4109 s->ids[s->count++] = id; 4110 return 0; 4111 } 4112 4113 static void idset_reset(struct bpf_idset *s) 4114 { 4115 s->count = 0; 4116 } 4117 4118 /* Collect a set of IDs for all registers currently marked as precise in env->bt. 4119 * Mark all registers with these IDs as precise. 4120 */ 4121 static int mark_precise_scalar_ids(struct bpf_verifier_env *env, struct bpf_verifier_state *st) 4122 { 4123 struct bpf_idset *precise_ids = &env->idset_scratch; 4124 struct backtrack_state *bt = &env->bt; 4125 struct bpf_func_state *func; 4126 struct bpf_reg_state *reg; 4127 DECLARE_BITMAP(mask, 64); 4128 int i, fr; 4129 4130 idset_reset(precise_ids); 4131 4132 for (fr = bt->frame; fr >= 0; fr--) { 4133 func = st->frame[fr]; 4134 4135 bitmap_from_u64(mask, bt_frame_reg_mask(bt, fr)); 4136 for_each_set_bit(i, mask, 32) { 4137 reg = &func->regs[i]; 4138 if (!reg->id || reg->type != SCALAR_VALUE) 4139 continue; 4140 if (idset_push(precise_ids, reg->id)) 4141 return -EFAULT; 4142 } 4143 4144 bitmap_from_u64(mask, bt_frame_stack_mask(bt, fr)); 4145 for_each_set_bit(i, mask, 64) { 4146 if (i >= func->allocated_stack / BPF_REG_SIZE) 4147 break; 4148 if (!is_spilled_scalar_reg(&func->stack[i])) 4149 continue; 4150 reg = &func->stack[i].spilled_ptr; 4151 if (!reg->id) 4152 continue; 4153 if (idset_push(precise_ids, reg->id)) 4154 return -EFAULT; 4155 } 4156 } 4157 4158 for (fr = 0; fr <= st->curframe; ++fr) { 4159 func = st->frame[fr]; 4160 4161 for (i = BPF_REG_0; i < BPF_REG_10; ++i) { 4162 reg = &func->regs[i]; 4163 if (!reg->id) 4164 continue; 4165 if (!idset_contains(precise_ids, reg->id)) 4166 continue; 4167 bt_set_frame_reg(bt, fr, i); 4168 } 4169 for (i = 0; i < func->allocated_stack / BPF_REG_SIZE; ++i) { 4170 if (!is_spilled_scalar_reg(&func->stack[i])) 4171 continue; 4172 reg = &func->stack[i].spilled_ptr; 4173 if (!reg->id) 4174 continue; 4175 if (!idset_contains(precise_ids, reg->id)) 4176 continue; 4177 bt_set_frame_slot(bt, fr, i); 4178 } 4179 } 4180 4181 return 0; 4182 } 4183 4184 /* 4185 * __mark_chain_precision() backtracks BPF program instruction sequence and 4186 * chain of verifier states making sure that register *regno* (if regno >= 0) 4187 * and/or stack slot *spi* (if spi >= 0) are marked as precisely tracked 4188 * SCALARS, as well as any other registers and slots that contribute to 4189 * a tracked state of given registers/stack slots, depending on specific BPF 4190 * assembly instructions (see backtrack_insns() for exact instruction handling 4191 * logic). This backtracking relies on recorded jmp_history and is able to 4192 * traverse entire chain of parent states. This process ends only when all the 4193 * necessary registers/slots and their transitive dependencies are marked as 4194 * precise. 4195 * 4196 * One important and subtle aspect is that precise marks *do not matter* in 4197 * the currently verified state (current state). It is important to understand 4198 * why this is the case. 4199 * 4200 * First, note that current state is the state that is not yet "checkpointed", 4201 * i.e., it is not yet put into env->explored_states, and it has no children 4202 * states as well. It's ephemeral, and can end up either a) being discarded if 4203 * compatible explored state is found at some point or BPF_EXIT instruction is 4204 * reached or b) checkpointed and put into env->explored_states, branching out 4205 * into one or more children states. 4206 * 4207 * In the former case, precise markings in current state are completely 4208 * ignored by state comparison code (see regsafe() for details). Only 4209 * checkpointed ("old") state precise markings are important, and if old 4210 * state's register/slot is precise, regsafe() assumes current state's 4211 * register/slot as precise and checks value ranges exactly and precisely. If 4212 * states turn out to be compatible, current state's necessary precise 4213 * markings and any required parent states' precise markings are enforced 4214 * after the fact with propagate_precision() logic, after the fact. But it's 4215 * important to realize that in this case, even after marking current state 4216 * registers/slots as precise, we immediately discard current state. So what 4217 * actually matters is any of the precise markings propagated into current 4218 * state's parent states, which are always checkpointed (due to b) case above). 4219 * As such, for scenario a) it doesn't matter if current state has precise 4220 * markings set or not. 4221 * 4222 * Now, for the scenario b), checkpointing and forking into child(ren) 4223 * state(s). Note that before current state gets to checkpointing step, any 4224 * processed instruction always assumes precise SCALAR register/slot 4225 * knowledge: if precise value or range is useful to prune jump branch, BPF 4226 * verifier takes this opportunity enthusiastically. Similarly, when 4227 * register's value is used to calculate offset or memory address, exact 4228 * knowledge of SCALAR range is assumed, checked, and enforced. So, similar to 4229 * what we mentioned above about state comparison ignoring precise markings 4230 * during state comparison, BPF verifier ignores and also assumes precise 4231 * markings *at will* during instruction verification process. But as verifier 4232 * assumes precision, it also propagates any precision dependencies across 4233 * parent states, which are not yet finalized, so can be further restricted 4234 * based on new knowledge gained from restrictions enforced by their children 4235 * states. This is so that once those parent states are finalized, i.e., when 4236 * they have no more active children state, state comparison logic in 4237 * is_state_visited() would enforce strict and precise SCALAR ranges, if 4238 * required for correctness. 4239 * 4240 * To build a bit more intuition, note also that once a state is checkpointed, 4241 * the path we took to get to that state is not important. This is crucial 4242 * property for state pruning. When state is checkpointed and finalized at 4243 * some instruction index, it can be correctly and safely used to "short 4244 * circuit" any *compatible* state that reaches exactly the same instruction 4245 * index. I.e., if we jumped to that instruction from a completely different 4246 * code path than original finalized state was derived from, it doesn't 4247 * matter, current state can be discarded because from that instruction 4248 * forward having a compatible state will ensure we will safely reach the 4249 * exit. States describe preconditions for further exploration, but completely 4250 * forget the history of how we got here. 4251 * 4252 * This also means that even if we needed precise SCALAR range to get to 4253 * finalized state, but from that point forward *that same* SCALAR register is 4254 * never used in a precise context (i.e., it's precise value is not needed for 4255 * correctness), it's correct and safe to mark such register as "imprecise" 4256 * (i.e., precise marking set to false). This is what we rely on when we do 4257 * not set precise marking in current state. If no child state requires 4258 * precision for any given SCALAR register, it's safe to dictate that it can 4259 * be imprecise. If any child state does require this register to be precise, 4260 * we'll mark it precise later retroactively during precise markings 4261 * propagation from child state to parent states. 4262 * 4263 * Skipping precise marking setting in current state is a mild version of 4264 * relying on the above observation. But we can utilize this property even 4265 * more aggressively by proactively forgetting any precise marking in the 4266 * current state (which we inherited from the parent state), right before we 4267 * checkpoint it and branch off into new child state. This is done by 4268 * mark_all_scalars_imprecise() to hopefully get more permissive and generic 4269 * finalized states which help in short circuiting more future states. 4270 */ 4271 static int __mark_chain_precision(struct bpf_verifier_env *env, int regno) 4272 { 4273 struct backtrack_state *bt = &env->bt; 4274 struct bpf_verifier_state *st = env->cur_state; 4275 int first_idx = st->first_insn_idx; 4276 int last_idx = env->insn_idx; 4277 int subseq_idx = -1; 4278 struct bpf_func_state *func; 4279 struct bpf_reg_state *reg; 4280 bool skip_first = true; 4281 int i, fr, err; 4282 4283 if (!env->bpf_capable) 4284 return 0; 4285 4286 /* set frame number from which we are starting to backtrack */ 4287 bt_init(bt, env->cur_state->curframe); 4288 4289 /* Do sanity checks against current state of register and/or stack 4290 * slot, but don't set precise flag in current state, as precision 4291 * tracking in the current state is unnecessary. 4292 */ 4293 func = st->frame[bt->frame]; 4294 if (regno >= 0) { 4295 reg = &func->regs[regno]; 4296 if (reg->type != SCALAR_VALUE) { 4297 WARN_ONCE(1, "backtracing misuse"); 4298 return -EFAULT; 4299 } 4300 bt_set_reg(bt, regno); 4301 } 4302 4303 if (bt_empty(bt)) 4304 return 0; 4305 4306 for (;;) { 4307 DECLARE_BITMAP(mask, 64); 4308 u32 history = st->jmp_history_cnt; 4309 struct bpf_jmp_history_entry *hist; 4310 4311 if (env->log.level & BPF_LOG_LEVEL2) { 4312 verbose(env, "mark_precise: frame%d: last_idx %d first_idx %d subseq_idx %d \n", 4313 bt->frame, last_idx, first_idx, subseq_idx); 4314 } 4315 4316 /* If some register with scalar ID is marked as precise, 4317 * make sure that all registers sharing this ID are also precise. 4318 * This is needed to estimate effect of find_equal_scalars(). 4319 * Do this at the last instruction of each state, 4320 * bpf_reg_state::id fields are valid for these instructions. 4321 * 4322 * Allows to track precision in situation like below: 4323 * 4324 * r2 = unknown value 4325 * ... 4326 * --- state #0 --- 4327 * ... 4328 * r1 = r2 // r1 and r2 now share the same ID 4329 * ... 4330 * --- state #1 {r1.id = A, r2.id = A} --- 4331 * ... 4332 * if (r2 > 10) goto exit; // find_equal_scalars() assigns range to r1 4333 * ... 4334 * --- state #2 {r1.id = A, r2.id = A} --- 4335 * r3 = r10 4336 * r3 += r1 // need to mark both r1 and r2 4337 */ 4338 if (mark_precise_scalar_ids(env, st)) 4339 return -EFAULT; 4340 4341 if (last_idx < 0) { 4342 /* we are at the entry into subprog, which 4343 * is expected for global funcs, but only if 4344 * requested precise registers are R1-R5 4345 * (which are global func's input arguments) 4346 */ 4347 if (st->curframe == 0 && 4348 st->frame[0]->subprogno > 0 && 4349 st->frame[0]->callsite == BPF_MAIN_FUNC && 4350 bt_stack_mask(bt) == 0 && 4351 (bt_reg_mask(bt) & ~BPF_REGMASK_ARGS) == 0) { 4352 bitmap_from_u64(mask, bt_reg_mask(bt)); 4353 for_each_set_bit(i, mask, 32) { 4354 reg = &st->frame[0]->regs[i]; 4355 bt_clear_reg(bt, i); 4356 if (reg->type == SCALAR_VALUE) 4357 reg->precise = true; 4358 } 4359 return 0; 4360 } 4361 4362 verbose(env, "BUG backtracking func entry subprog %d reg_mask %x stack_mask %llx\n", 4363 st->frame[0]->subprogno, bt_reg_mask(bt), bt_stack_mask(bt)); 4364 WARN_ONCE(1, "verifier backtracking bug"); 4365 return -EFAULT; 4366 } 4367 4368 for (i = last_idx;;) { 4369 if (skip_first) { 4370 err = 0; 4371 skip_first = false; 4372 } else { 4373 hist = get_jmp_hist_entry(st, history, i); 4374 err = backtrack_insn(env, i, subseq_idx, hist, bt); 4375 } 4376 if (err == -ENOTSUPP) { 4377 mark_all_scalars_precise(env, env->cur_state); 4378 bt_reset(bt); 4379 return 0; 4380 } else if (err) { 4381 return err; 4382 } 4383 if (bt_empty(bt)) 4384 /* Found assignment(s) into tracked register in this state. 4385 * Since this state is already marked, just return. 4386 * Nothing to be tracked further in the parent state. 4387 */ 4388 return 0; 4389 subseq_idx = i; 4390 i = get_prev_insn_idx(st, i, &history); 4391 if (i == -ENOENT) 4392 break; 4393 if (i >= env->prog->len) { 4394 /* This can happen if backtracking reached insn 0 4395 * and there are still reg_mask or stack_mask 4396 * to backtrack. 4397 * It means the backtracking missed the spot where 4398 * particular register was initialized with a constant. 4399 */ 4400 verbose(env, "BUG backtracking idx %d\n", i); 4401 WARN_ONCE(1, "verifier backtracking bug"); 4402 return -EFAULT; 4403 } 4404 } 4405 st = st->parent; 4406 if (!st) 4407 break; 4408 4409 for (fr = bt->frame; fr >= 0; fr--) { 4410 func = st->frame[fr]; 4411 bitmap_from_u64(mask, bt_frame_reg_mask(bt, fr)); 4412 for_each_set_bit(i, mask, 32) { 4413 reg = &func->regs[i]; 4414 if (reg->type != SCALAR_VALUE) { 4415 bt_clear_frame_reg(bt, fr, i); 4416 continue; 4417 } 4418 if (reg->precise) 4419 bt_clear_frame_reg(bt, fr, i); 4420 else 4421 reg->precise = true; 4422 } 4423 4424 bitmap_from_u64(mask, bt_frame_stack_mask(bt, fr)); 4425 for_each_set_bit(i, mask, 64) { 4426 if (i >= func->allocated_stack / BPF_REG_SIZE) { 4427 verbose(env, "BUG backtracking (stack slot %d, total slots %d)\n", 4428 i, func->allocated_stack / BPF_REG_SIZE); 4429 WARN_ONCE(1, "verifier backtracking bug (stack slot out of bounds)"); 4430 return -EFAULT; 4431 } 4432 4433 if (!is_spilled_scalar_reg(&func->stack[i])) { 4434 bt_clear_frame_slot(bt, fr, i); 4435 continue; 4436 } 4437 reg = &func->stack[i].spilled_ptr; 4438 if (reg->precise) 4439 bt_clear_frame_slot(bt, fr, i); 4440 else 4441 reg->precise = true; 4442 } 4443 if (env->log.level & BPF_LOG_LEVEL2) { 4444 fmt_reg_mask(env->tmp_str_buf, TMP_STR_BUF_LEN, 4445 bt_frame_reg_mask(bt, fr)); 4446 verbose(env, "mark_precise: frame%d: parent state regs=%s ", 4447 fr, env->tmp_str_buf); 4448 fmt_stack_mask(env->tmp_str_buf, TMP_STR_BUF_LEN, 4449 bt_frame_stack_mask(bt, fr)); 4450 verbose(env, "stack=%s: ", env->tmp_str_buf); 4451 print_verifier_state(env, func, true); 4452 } 4453 } 4454 4455 if (bt_empty(bt)) 4456 return 0; 4457 4458 subseq_idx = first_idx; 4459 last_idx = st->last_insn_idx; 4460 first_idx = st->first_insn_idx; 4461 } 4462 4463 /* if we still have requested precise regs or slots, we missed 4464 * something (e.g., stack access through non-r10 register), so 4465 * fallback to marking all precise 4466 */ 4467 if (!bt_empty(bt)) { 4468 mark_all_scalars_precise(env, env->cur_state); 4469 bt_reset(bt); 4470 } 4471 4472 return 0; 4473 } 4474 4475 int mark_chain_precision(struct bpf_verifier_env *env, int regno) 4476 { 4477 return __mark_chain_precision(env, regno); 4478 } 4479 4480 /* mark_chain_precision_batch() assumes that env->bt is set in the caller to 4481 * desired reg and stack masks across all relevant frames 4482 */ 4483 static int mark_chain_precision_batch(struct bpf_verifier_env *env) 4484 { 4485 return __mark_chain_precision(env, -1); 4486 } 4487 4488 static bool is_spillable_regtype(enum bpf_reg_type type) 4489 { 4490 switch (base_type(type)) { 4491 case PTR_TO_MAP_VALUE: 4492 case PTR_TO_STACK: 4493 case PTR_TO_CTX: 4494 case PTR_TO_PACKET: 4495 case PTR_TO_PACKET_META: 4496 case PTR_TO_PACKET_END: 4497 case PTR_TO_FLOW_KEYS: 4498 case CONST_PTR_TO_MAP: 4499 case PTR_TO_SOCKET: 4500 case PTR_TO_SOCK_COMMON: 4501 case PTR_TO_TCP_SOCK: 4502 case PTR_TO_XDP_SOCK: 4503 case PTR_TO_BTF_ID: 4504 case PTR_TO_BUF: 4505 case PTR_TO_MEM: 4506 case PTR_TO_FUNC: 4507 case PTR_TO_MAP_KEY: 4508 return true; 4509 default: 4510 return false; 4511 } 4512 } 4513 4514 /* Does this register contain a constant zero? */ 4515 static bool register_is_null(struct bpf_reg_state *reg) 4516 { 4517 return reg->type == SCALAR_VALUE && tnum_equals_const(reg->var_off, 0); 4518 } 4519 4520 static bool register_is_const(struct bpf_reg_state *reg) 4521 { 4522 return reg->type == SCALAR_VALUE && tnum_is_const(reg->var_off); 4523 } 4524 4525 static bool __is_scalar_unbounded(struct bpf_reg_state *reg) 4526 { 4527 return tnum_is_unknown(reg->var_off) && 4528 reg->smin_value == S64_MIN && reg->smax_value == S64_MAX && 4529 reg->umin_value == 0 && reg->umax_value == U64_MAX && 4530 reg->s32_min_value == S32_MIN && reg->s32_max_value == S32_MAX && 4531 reg->u32_min_value == 0 && reg->u32_max_value == U32_MAX; 4532 } 4533 4534 static bool register_is_bounded(struct bpf_reg_state *reg) 4535 { 4536 return reg->type == SCALAR_VALUE && !__is_scalar_unbounded(reg); 4537 } 4538 4539 static bool __is_pointer_value(bool allow_ptr_leaks, 4540 const struct bpf_reg_state *reg) 4541 { 4542 if (allow_ptr_leaks) 4543 return false; 4544 4545 return reg->type != SCALAR_VALUE; 4546 } 4547 4548 /* Copy src state preserving dst->parent and dst->live fields */ 4549 static void copy_register_state(struct bpf_reg_state *dst, const struct bpf_reg_state *src) 4550 { 4551 struct bpf_reg_state *parent = dst->parent; 4552 enum bpf_reg_liveness live = dst->live; 4553 4554 *dst = *src; 4555 dst->parent = parent; 4556 dst->live = live; 4557 } 4558 4559 static void save_register_state(struct bpf_func_state *state, 4560 int spi, struct bpf_reg_state *reg, 4561 int size) 4562 { 4563 int i; 4564 4565 copy_register_state(&state->stack[spi].spilled_ptr, reg); 4566 if (size == BPF_REG_SIZE) 4567 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN; 4568 4569 for (i = BPF_REG_SIZE; i > BPF_REG_SIZE - size; i--) 4570 state->stack[spi].slot_type[i - 1] = STACK_SPILL; 4571 4572 /* size < 8 bytes spill */ 4573 for (; i; i--) 4574 scrub_spilled_slot(&state->stack[spi].slot_type[i - 1]); 4575 } 4576 4577 static bool is_bpf_st_mem(struct bpf_insn *insn) 4578 { 4579 return BPF_CLASS(insn->code) == BPF_ST && BPF_MODE(insn->code) == BPF_MEM; 4580 } 4581 4582 /* check_stack_{read,write}_fixed_off functions track spill/fill of registers, 4583 * stack boundary and alignment are checked in check_mem_access() 4584 */ 4585 static int check_stack_write_fixed_off(struct bpf_verifier_env *env, 4586 /* stack frame we're writing to */ 4587 struct bpf_func_state *state, 4588 int off, int size, int value_regno, 4589 int insn_idx) 4590 { 4591 struct bpf_func_state *cur; /* state of the current function */ 4592 int i, slot = -off - 1, spi = slot / BPF_REG_SIZE, err; 4593 struct bpf_insn *insn = &env->prog->insnsi[insn_idx]; 4594 struct bpf_reg_state *reg = NULL; 4595 int insn_flags = insn_stack_access_flags(state->frameno, spi); 4596 4597 /* caller checked that off % size == 0 and -MAX_BPF_STACK <= off < 0, 4598 * so it's aligned access and [off, off + size) are within stack limits 4599 */ 4600 if (!env->allow_ptr_leaks && 4601 is_spilled_reg(&state->stack[spi]) && 4602 size != BPF_REG_SIZE) { 4603 verbose(env, "attempt to corrupt spilled pointer on stack\n"); 4604 return -EACCES; 4605 } 4606 4607 cur = env->cur_state->frame[env->cur_state->curframe]; 4608 if (value_regno >= 0) 4609 reg = &cur->regs[value_regno]; 4610 if (!env->bypass_spec_v4) { 4611 bool sanitize = reg && is_spillable_regtype(reg->type); 4612 4613 for (i = 0; i < size; i++) { 4614 u8 type = state->stack[spi].slot_type[i]; 4615 4616 if (type != STACK_MISC && type != STACK_ZERO) { 4617 sanitize = true; 4618 break; 4619 } 4620 } 4621 4622 if (sanitize) 4623 env->insn_aux_data[insn_idx].sanitize_stack_spill = true; 4624 } 4625 4626 err = destroy_if_dynptr_stack_slot(env, state, spi); 4627 if (err) 4628 return err; 4629 4630 mark_stack_slot_scratched(env, spi); 4631 if (reg && !(off % BPF_REG_SIZE) && register_is_bounded(reg) && 4632 !register_is_null(reg) && env->bpf_capable) { 4633 save_register_state(state, spi, reg, size); 4634 /* Break the relation on a narrowing spill. */ 4635 if (fls64(reg->umax_value) > BITS_PER_BYTE * size) 4636 state->stack[spi].spilled_ptr.id = 0; 4637 } else if (!reg && !(off % BPF_REG_SIZE) && is_bpf_st_mem(insn) && 4638 insn->imm != 0 && env->bpf_capable) { 4639 struct bpf_reg_state fake_reg = {}; 4640 4641 __mark_reg_known(&fake_reg, insn->imm); 4642 fake_reg.type = SCALAR_VALUE; 4643 save_register_state(state, spi, &fake_reg, size); 4644 insn_flags = 0; /* not a register spill */ 4645 } else if (reg && is_spillable_regtype(reg->type)) { 4646 /* register containing pointer is being spilled into stack */ 4647 if (size != BPF_REG_SIZE) { 4648 verbose_linfo(env, insn_idx, "; "); 4649 verbose(env, "invalid size of register spill\n"); 4650 return -EACCES; 4651 } 4652 if (state != cur && reg->type == PTR_TO_STACK) { 4653 verbose(env, "cannot spill pointers to stack into stack frame of the caller\n"); 4654 return -EINVAL; 4655 } 4656 save_register_state(state, spi, reg, size); 4657 } else { 4658 u8 type = STACK_MISC; 4659 4660 /* regular write of data into stack destroys any spilled ptr */ 4661 state->stack[spi].spilled_ptr.type = NOT_INIT; 4662 /* Mark slots as STACK_MISC if they belonged to spilled ptr/dynptr/iter. */ 4663 if (is_stack_slot_special(&state->stack[spi])) 4664 for (i = 0; i < BPF_REG_SIZE; i++) 4665 scrub_spilled_slot(&state->stack[spi].slot_type[i]); 4666 4667 /* only mark the slot as written if all 8 bytes were written 4668 * otherwise read propagation may incorrectly stop too soon 4669 * when stack slots are partially written. 4670 * This heuristic means that read propagation will be 4671 * conservative, since it will add reg_live_read marks 4672 * to stack slots all the way to first state when programs 4673 * writes+reads less than 8 bytes 4674 */ 4675 if (size == BPF_REG_SIZE) 4676 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN; 4677 4678 /* when we zero initialize stack slots mark them as such */ 4679 if ((reg && register_is_null(reg)) || 4680 (!reg && is_bpf_st_mem(insn) && insn->imm == 0)) { 4681 /* backtracking doesn't work for STACK_ZERO yet. */ 4682 err = mark_chain_precision(env, value_regno); 4683 if (err) 4684 return err; 4685 type = STACK_ZERO; 4686 } 4687 4688 /* Mark slots affected by this stack write. */ 4689 for (i = 0; i < size; i++) 4690 state->stack[spi].slot_type[(slot - i) % BPF_REG_SIZE] = type; 4691 insn_flags = 0; /* not a register spill */ 4692 } 4693 4694 if (insn_flags) 4695 return push_jmp_history(env, env->cur_state, insn_flags); 4696 return 0; 4697 } 4698 4699 /* Write the stack: 'stack[ptr_regno + off] = value_regno'. 'ptr_regno' is 4700 * known to contain a variable offset. 4701 * This function checks whether the write is permitted and conservatively 4702 * tracks the effects of the write, considering that each stack slot in the 4703 * dynamic range is potentially written to. 4704 * 4705 * 'off' includes 'regno->off'. 4706 * 'value_regno' can be -1, meaning that an unknown value is being written to 4707 * the stack. 4708 * 4709 * Spilled pointers in range are not marked as written because we don't know 4710 * what's going to be actually written. This means that read propagation for 4711 * future reads cannot be terminated by this write. 4712 * 4713 * For privileged programs, uninitialized stack slots are considered 4714 * initialized by this write (even though we don't know exactly what offsets 4715 * are going to be written to). The idea is that we don't want the verifier to 4716 * reject future reads that access slots written to through variable offsets. 4717 */ 4718 static int check_stack_write_var_off(struct bpf_verifier_env *env, 4719 /* func where register points to */ 4720 struct bpf_func_state *state, 4721 int ptr_regno, int off, int size, 4722 int value_regno, int insn_idx) 4723 { 4724 struct bpf_func_state *cur; /* state of the current function */ 4725 int min_off, max_off; 4726 int i, err; 4727 struct bpf_reg_state *ptr_reg = NULL, *value_reg = NULL; 4728 struct bpf_insn *insn = &env->prog->insnsi[insn_idx]; 4729 bool writing_zero = false; 4730 /* set if the fact that we're writing a zero is used to let any 4731 * stack slots remain STACK_ZERO 4732 */ 4733 bool zero_used = false; 4734 4735 cur = env->cur_state->frame[env->cur_state->curframe]; 4736 ptr_reg = &cur->regs[ptr_regno]; 4737 min_off = ptr_reg->smin_value + off; 4738 max_off = ptr_reg->smax_value + off + size; 4739 if (value_regno >= 0) 4740 value_reg = &cur->regs[value_regno]; 4741 if ((value_reg && register_is_null(value_reg)) || 4742 (!value_reg && is_bpf_st_mem(insn) && insn->imm == 0)) 4743 writing_zero = true; 4744 4745 for (i = min_off; i < max_off; i++) { 4746 int spi; 4747 4748 spi = __get_spi(i); 4749 err = destroy_if_dynptr_stack_slot(env, state, spi); 4750 if (err) 4751 return err; 4752 } 4753 4754 /* Variable offset writes destroy any spilled pointers in range. */ 4755 for (i = min_off; i < max_off; i++) { 4756 u8 new_type, *stype; 4757 int slot, spi; 4758 4759 slot = -i - 1; 4760 spi = slot / BPF_REG_SIZE; 4761 stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE]; 4762 mark_stack_slot_scratched(env, spi); 4763 4764 if (!env->allow_ptr_leaks && *stype != STACK_MISC && *stype != STACK_ZERO) { 4765 /* Reject the write if range we may write to has not 4766 * been initialized beforehand. If we didn't reject 4767 * here, the ptr status would be erased below (even 4768 * though not all slots are actually overwritten), 4769 * possibly opening the door to leaks. 4770 * 4771 * We do however catch STACK_INVALID case below, and 4772 * only allow reading possibly uninitialized memory 4773 * later for CAP_PERFMON, as the write may not happen to 4774 * that slot. 4775 */ 4776 verbose(env, "spilled ptr in range of var-offset stack write; insn %d, ptr off: %d", 4777 insn_idx, i); 4778 return -EINVAL; 4779 } 4780 4781 /* Erase all spilled pointers. */ 4782 state->stack[spi].spilled_ptr.type = NOT_INIT; 4783 4784 /* Update the slot type. */ 4785 new_type = STACK_MISC; 4786 if (writing_zero && *stype == STACK_ZERO) { 4787 new_type = STACK_ZERO; 4788 zero_used = true; 4789 } 4790 /* If the slot is STACK_INVALID, we check whether it's OK to 4791 * pretend that it will be initialized by this write. The slot 4792 * might not actually be written to, and so if we mark it as 4793 * initialized future reads might leak uninitialized memory. 4794 * For privileged programs, we will accept such reads to slots 4795 * that may or may not be written because, if we're reject 4796 * them, the error would be too confusing. 4797 */ 4798 if (*stype == STACK_INVALID && !env->allow_uninit_stack) { 4799 verbose(env, "uninit stack in range of var-offset write prohibited for !root; insn %d, off: %d", 4800 insn_idx, i); 4801 return -EINVAL; 4802 } 4803 *stype = new_type; 4804 } 4805 if (zero_used) { 4806 /* backtracking doesn't work for STACK_ZERO yet. */ 4807 err = mark_chain_precision(env, value_regno); 4808 if (err) 4809 return err; 4810 } 4811 return 0; 4812 } 4813 4814 /* When register 'dst_regno' is assigned some values from stack[min_off, 4815 * max_off), we set the register's type according to the types of the 4816 * respective stack slots. If all the stack values are known to be zeros, then 4817 * so is the destination reg. Otherwise, the register is considered to be 4818 * SCALAR. This function does not deal with register filling; the caller must 4819 * ensure that all spilled registers in the stack range have been marked as 4820 * read. 4821 */ 4822 static void mark_reg_stack_read(struct bpf_verifier_env *env, 4823 /* func where src register points to */ 4824 struct bpf_func_state *ptr_state, 4825 int min_off, int max_off, int dst_regno) 4826 { 4827 struct bpf_verifier_state *vstate = env->cur_state; 4828 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 4829 int i, slot, spi; 4830 u8 *stype; 4831 int zeros = 0; 4832 4833 for (i = min_off; i < max_off; i++) { 4834 slot = -i - 1; 4835 spi = slot / BPF_REG_SIZE; 4836 mark_stack_slot_scratched(env, spi); 4837 stype = ptr_state->stack[spi].slot_type; 4838 if (stype[slot % BPF_REG_SIZE] != STACK_ZERO) 4839 break; 4840 zeros++; 4841 } 4842 if (zeros == max_off - min_off) { 4843 /* any access_size read into register is zero extended, 4844 * so the whole register == const_zero 4845 */ 4846 __mark_reg_const_zero(&state->regs[dst_regno]); 4847 /* backtracking doesn't support STACK_ZERO yet, 4848 * so mark it precise here, so that later 4849 * backtracking can stop here. 4850 * Backtracking may not need this if this register 4851 * doesn't participate in pointer adjustment. 4852 * Forward propagation of precise flag is not 4853 * necessary either. This mark is only to stop 4854 * backtracking. Any register that contributed 4855 * to const 0 was marked precise before spill. 4856 */ 4857 state->regs[dst_regno].precise = true; 4858 } else { 4859 /* have read misc data from the stack */ 4860 mark_reg_unknown(env, state->regs, dst_regno); 4861 } 4862 state->regs[dst_regno].live |= REG_LIVE_WRITTEN; 4863 } 4864 4865 /* Read the stack at 'off' and put the results into the register indicated by 4866 * 'dst_regno'. It handles reg filling if the addressed stack slot is a 4867 * spilled reg. 4868 * 4869 * 'dst_regno' can be -1, meaning that the read value is not going to a 4870 * register. 4871 * 4872 * The access is assumed to be within the current stack bounds. 4873 */ 4874 static int check_stack_read_fixed_off(struct bpf_verifier_env *env, 4875 /* func where src register points to */ 4876 struct bpf_func_state *reg_state, 4877 int off, int size, int dst_regno) 4878 { 4879 struct bpf_verifier_state *vstate = env->cur_state; 4880 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 4881 int i, slot = -off - 1, spi = slot / BPF_REG_SIZE; 4882 struct bpf_reg_state *reg; 4883 u8 *stype, type; 4884 int insn_flags = insn_stack_access_flags(reg_state->frameno, spi); 4885 4886 stype = reg_state->stack[spi].slot_type; 4887 reg = ®_state->stack[spi].spilled_ptr; 4888 4889 mark_stack_slot_scratched(env, spi); 4890 4891 if (is_spilled_reg(®_state->stack[spi])) { 4892 u8 spill_size = 1; 4893 4894 for (i = BPF_REG_SIZE - 1; i > 0 && stype[i - 1] == STACK_SPILL; i--) 4895 spill_size++; 4896 4897 if (size != BPF_REG_SIZE || spill_size != BPF_REG_SIZE) { 4898 if (reg->type != SCALAR_VALUE) { 4899 verbose_linfo(env, env->insn_idx, "; "); 4900 verbose(env, "invalid size of register fill\n"); 4901 return -EACCES; 4902 } 4903 4904 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64); 4905 if (dst_regno < 0) 4906 return 0; 4907 4908 if (!(off % BPF_REG_SIZE) && size == spill_size) { 4909 /* The earlier check_reg_arg() has decided the 4910 * subreg_def for this insn. Save it first. 4911 */ 4912 s32 subreg_def = state->regs[dst_regno].subreg_def; 4913 4914 copy_register_state(&state->regs[dst_regno], reg); 4915 state->regs[dst_regno].subreg_def = subreg_def; 4916 } else { 4917 for (i = 0; i < size; i++) { 4918 type = stype[(slot - i) % BPF_REG_SIZE]; 4919 if (type == STACK_SPILL) 4920 continue; 4921 if (type == STACK_MISC) 4922 continue; 4923 if (type == STACK_INVALID && env->allow_uninit_stack) 4924 continue; 4925 verbose(env, "invalid read from stack off %d+%d size %d\n", 4926 off, i, size); 4927 return -EACCES; 4928 } 4929 mark_reg_unknown(env, state->regs, dst_regno); 4930 insn_flags = 0; /* not restoring original register state */ 4931 } 4932 state->regs[dst_regno].live |= REG_LIVE_WRITTEN; 4933 } else if (dst_regno >= 0) { 4934 /* restore register state from stack */ 4935 copy_register_state(&state->regs[dst_regno], reg); 4936 /* mark reg as written since spilled pointer state likely 4937 * has its liveness marks cleared by is_state_visited() 4938 * which resets stack/reg liveness for state transitions 4939 */ 4940 state->regs[dst_regno].live |= REG_LIVE_WRITTEN; 4941 } else if (__is_pointer_value(env->allow_ptr_leaks, reg)) { 4942 /* If dst_regno==-1, the caller is asking us whether 4943 * it is acceptable to use this value as a SCALAR_VALUE 4944 * (e.g. for XADD). 4945 * We must not allow unprivileged callers to do that 4946 * with spilled pointers. 4947 */ 4948 verbose(env, "leaking pointer from stack off %d\n", 4949 off); 4950 return -EACCES; 4951 } 4952 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64); 4953 } else { 4954 for (i = 0; i < size; i++) { 4955 type = stype[(slot - i) % BPF_REG_SIZE]; 4956 if (type == STACK_MISC) 4957 continue; 4958 if (type == STACK_ZERO) 4959 continue; 4960 if (type == STACK_INVALID && env->allow_uninit_stack) 4961 continue; 4962 verbose(env, "invalid read from stack off %d+%d size %d\n", 4963 off, i, size); 4964 return -EACCES; 4965 } 4966 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64); 4967 if (dst_regno >= 0) 4968 mark_reg_stack_read(env, reg_state, off, off + size, dst_regno); 4969 insn_flags = 0; /* we are not restoring spilled register */ 4970 } 4971 if (insn_flags) 4972 return push_jmp_history(env, env->cur_state, insn_flags); 4973 return 0; 4974 } 4975 4976 enum bpf_access_src { 4977 ACCESS_DIRECT = 1, /* the access is performed by an instruction */ 4978 ACCESS_HELPER = 2, /* the access is performed by a helper */ 4979 }; 4980 4981 static int check_stack_range_initialized(struct bpf_verifier_env *env, 4982 int regno, int off, int access_size, 4983 bool zero_size_allowed, 4984 enum bpf_access_src type, 4985 struct bpf_call_arg_meta *meta); 4986 4987 static struct bpf_reg_state *reg_state(struct bpf_verifier_env *env, int regno) 4988 { 4989 return cur_regs(env) + regno; 4990 } 4991 4992 /* Read the stack at 'ptr_regno + off' and put the result into the register 4993 * 'dst_regno'. 4994 * 'off' includes the pointer register's fixed offset(i.e. 'ptr_regno.off'), 4995 * but not its variable offset. 4996 * 'size' is assumed to be <= reg size and the access is assumed to be aligned. 4997 * 4998 * As opposed to check_stack_read_fixed_off, this function doesn't deal with 4999 * filling registers (i.e. reads of spilled register cannot be detected when 5000 * the offset is not fixed). We conservatively mark 'dst_regno' as containing 5001 * SCALAR_VALUE. That's why we assert that the 'ptr_regno' has a variable 5002 * offset; for a fixed offset check_stack_read_fixed_off should be used 5003 * instead. 5004 */ 5005 static int check_stack_read_var_off(struct bpf_verifier_env *env, 5006 int ptr_regno, int off, int size, int dst_regno) 5007 { 5008 /* The state of the source register. */ 5009 struct bpf_reg_state *reg = reg_state(env, ptr_regno); 5010 struct bpf_func_state *ptr_state = func(env, reg); 5011 int err; 5012 int min_off, max_off; 5013 5014 /* Note that we pass a NULL meta, so raw access will not be permitted. 5015 */ 5016 err = check_stack_range_initialized(env, ptr_regno, off, size, 5017 false, ACCESS_DIRECT, NULL); 5018 if (err) 5019 return err; 5020 5021 min_off = reg->smin_value + off; 5022 max_off = reg->smax_value + off; 5023 mark_reg_stack_read(env, ptr_state, min_off, max_off + size, dst_regno); 5024 return 0; 5025 } 5026 5027 /* check_stack_read dispatches to check_stack_read_fixed_off or 5028 * check_stack_read_var_off. 5029 * 5030 * The caller must ensure that the offset falls within the allocated stack 5031 * bounds. 5032 * 5033 * 'dst_regno' is a register which will receive the value from the stack. It 5034 * can be -1, meaning that the read value is not going to a register. 5035 */ 5036 static int check_stack_read(struct bpf_verifier_env *env, 5037 int ptr_regno, int off, int size, 5038 int dst_regno) 5039 { 5040 struct bpf_reg_state *reg = reg_state(env, ptr_regno); 5041 struct bpf_func_state *state = func(env, reg); 5042 int err; 5043 /* Some accesses are only permitted with a static offset. */ 5044 bool var_off = !tnum_is_const(reg->var_off); 5045 5046 /* The offset is required to be static when reads don't go to a 5047 * register, in order to not leak pointers (see 5048 * check_stack_read_fixed_off). 5049 */ 5050 if (dst_regno < 0 && var_off) { 5051 char tn_buf[48]; 5052 5053 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 5054 verbose(env, "variable offset stack pointer cannot be passed into helper function; var_off=%s off=%d size=%d\n", 5055 tn_buf, off, size); 5056 return -EACCES; 5057 } 5058 /* Variable offset is prohibited for unprivileged mode for simplicity 5059 * since it requires corresponding support in Spectre masking for stack 5060 * ALU. See also retrieve_ptr_limit(). The check in 5061 * check_stack_access_for_ptr_arithmetic() called by 5062 * adjust_ptr_min_max_vals() prevents users from creating stack pointers 5063 * with variable offsets, therefore no check is required here. Further, 5064 * just checking it here would be insufficient as speculative stack 5065 * writes could still lead to unsafe speculative behaviour. 5066 */ 5067 if (!var_off) { 5068 off += reg->var_off.value; 5069 err = check_stack_read_fixed_off(env, state, off, size, 5070 dst_regno); 5071 } else { 5072 /* Variable offset stack reads need more conservative handling 5073 * than fixed offset ones. Note that dst_regno >= 0 on this 5074 * branch. 5075 */ 5076 err = check_stack_read_var_off(env, ptr_regno, off, size, 5077 dst_regno); 5078 } 5079 return err; 5080 } 5081 5082 5083 /* check_stack_write dispatches to check_stack_write_fixed_off or 5084 * check_stack_write_var_off. 5085 * 5086 * 'ptr_regno' is the register used as a pointer into the stack. 5087 * 'off' includes 'ptr_regno->off', but not its variable offset (if any). 5088 * 'value_regno' is the register whose value we're writing to the stack. It can 5089 * be -1, meaning that we're not writing from a register. 5090 * 5091 * The caller must ensure that the offset falls within the maximum stack size. 5092 */ 5093 static int check_stack_write(struct bpf_verifier_env *env, 5094 int ptr_regno, int off, int size, 5095 int value_regno, int insn_idx) 5096 { 5097 struct bpf_reg_state *reg = reg_state(env, ptr_regno); 5098 struct bpf_func_state *state = func(env, reg); 5099 int err; 5100 5101 if (tnum_is_const(reg->var_off)) { 5102 off += reg->var_off.value; 5103 err = check_stack_write_fixed_off(env, state, off, size, 5104 value_regno, insn_idx); 5105 } else { 5106 /* Variable offset stack reads need more conservative handling 5107 * than fixed offset ones. 5108 */ 5109 err = check_stack_write_var_off(env, state, 5110 ptr_regno, off, size, 5111 value_regno, insn_idx); 5112 } 5113 return err; 5114 } 5115 5116 static int check_map_access_type(struct bpf_verifier_env *env, u32 regno, 5117 int off, int size, enum bpf_access_type type) 5118 { 5119 struct bpf_reg_state *regs = cur_regs(env); 5120 struct bpf_map *map = regs[regno].map_ptr; 5121 u32 cap = bpf_map_flags_to_cap(map); 5122 5123 if (type == BPF_WRITE && !(cap & BPF_MAP_CAN_WRITE)) { 5124 verbose(env, "write into map forbidden, value_size=%d off=%d size=%d\n", 5125 map->value_size, off, size); 5126 return -EACCES; 5127 } 5128 5129 if (type == BPF_READ && !(cap & BPF_MAP_CAN_READ)) { 5130 verbose(env, "read from map forbidden, value_size=%d off=%d size=%d\n", 5131 map->value_size, off, size); 5132 return -EACCES; 5133 } 5134 5135 return 0; 5136 } 5137 5138 /* check read/write into memory region (e.g., map value, ringbuf sample, etc) */ 5139 static int __check_mem_access(struct bpf_verifier_env *env, int regno, 5140 int off, int size, u32 mem_size, 5141 bool zero_size_allowed) 5142 { 5143 bool size_ok = size > 0 || (size == 0 && zero_size_allowed); 5144 struct bpf_reg_state *reg; 5145 5146 if (off >= 0 && size_ok && (u64)off + size <= mem_size) 5147 return 0; 5148 5149 reg = &cur_regs(env)[regno]; 5150 switch (reg->type) { 5151 case PTR_TO_MAP_KEY: 5152 verbose(env, "invalid access to map key, key_size=%d off=%d size=%d\n", 5153 mem_size, off, size); 5154 break; 5155 case PTR_TO_MAP_VALUE: 5156 verbose(env, "invalid access to map value, value_size=%d off=%d size=%d\n", 5157 mem_size, off, size); 5158 break; 5159 case PTR_TO_PACKET: 5160 case PTR_TO_PACKET_META: 5161 case PTR_TO_PACKET_END: 5162 verbose(env, "invalid access to packet, off=%d size=%d, R%d(id=%d,off=%d,r=%d)\n", 5163 off, size, regno, reg->id, off, mem_size); 5164 break; 5165 case PTR_TO_MEM: 5166 default: 5167 verbose(env, "invalid access to memory, mem_size=%u off=%d size=%d\n", 5168 mem_size, off, size); 5169 } 5170 5171 return -EACCES; 5172 } 5173 5174 /* check read/write into a memory region with possible variable offset */ 5175 static int check_mem_region_access(struct bpf_verifier_env *env, u32 regno, 5176 int off, int size, u32 mem_size, 5177 bool zero_size_allowed) 5178 { 5179 struct bpf_verifier_state *vstate = env->cur_state; 5180 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 5181 struct bpf_reg_state *reg = &state->regs[regno]; 5182 int err; 5183 5184 /* We may have adjusted the register pointing to memory region, so we 5185 * need to try adding each of min_value and max_value to off 5186 * to make sure our theoretical access will be safe. 5187 * 5188 * The minimum value is only important with signed 5189 * comparisons where we can't assume the floor of a 5190 * value is 0. If we are using signed variables for our 5191 * index'es we need to make sure that whatever we use 5192 * will have a set floor within our range. 5193 */ 5194 if (reg->smin_value < 0 && 5195 (reg->smin_value == S64_MIN || 5196 (off + reg->smin_value != (s64)(s32)(off + reg->smin_value)) || 5197 reg->smin_value + off < 0)) { 5198 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n", 5199 regno); 5200 return -EACCES; 5201 } 5202 err = __check_mem_access(env, regno, reg->smin_value + off, size, 5203 mem_size, zero_size_allowed); 5204 if (err) { 5205 verbose(env, "R%d min value is outside of the allowed memory range\n", 5206 regno); 5207 return err; 5208 } 5209 5210 /* If we haven't set a max value then we need to bail since we can't be 5211 * sure we won't do bad things. 5212 * If reg->umax_value + off could overflow, treat that as unbounded too. 5213 */ 5214 if (reg->umax_value >= BPF_MAX_VAR_OFF) { 5215 verbose(env, "R%d unbounded memory access, make sure to bounds check any such access\n", 5216 regno); 5217 return -EACCES; 5218 } 5219 err = __check_mem_access(env, regno, reg->umax_value + off, size, 5220 mem_size, zero_size_allowed); 5221 if (err) { 5222 verbose(env, "R%d max value is outside of the allowed memory range\n", 5223 regno); 5224 return err; 5225 } 5226 5227 return 0; 5228 } 5229 5230 static int __check_ptr_off_reg(struct bpf_verifier_env *env, 5231 const struct bpf_reg_state *reg, int regno, 5232 bool fixed_off_ok) 5233 { 5234 /* Access to this pointer-typed register or passing it to a helper 5235 * is only allowed in its original, unmodified form. 5236 */ 5237 5238 if (reg->off < 0) { 5239 verbose(env, "negative offset %s ptr R%d off=%d disallowed\n", 5240 reg_type_str(env, reg->type), regno, reg->off); 5241 return -EACCES; 5242 } 5243 5244 if (!fixed_off_ok && reg->off) { 5245 verbose(env, "dereference of modified %s ptr R%d off=%d disallowed\n", 5246 reg_type_str(env, reg->type), regno, reg->off); 5247 return -EACCES; 5248 } 5249 5250 if (!tnum_is_const(reg->var_off) || reg->var_off.value) { 5251 char tn_buf[48]; 5252 5253 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 5254 verbose(env, "variable %s access var_off=%s disallowed\n", 5255 reg_type_str(env, reg->type), tn_buf); 5256 return -EACCES; 5257 } 5258 5259 return 0; 5260 } 5261 5262 int check_ptr_off_reg(struct bpf_verifier_env *env, 5263 const struct bpf_reg_state *reg, int regno) 5264 { 5265 return __check_ptr_off_reg(env, reg, regno, false); 5266 } 5267 5268 static int map_kptr_match_type(struct bpf_verifier_env *env, 5269 struct btf_field *kptr_field, 5270 struct bpf_reg_state *reg, u32 regno) 5271 { 5272 const char *targ_name = btf_type_name(kptr_field->kptr.btf, kptr_field->kptr.btf_id); 5273 int perm_flags; 5274 const char *reg_name = ""; 5275 5276 if (btf_is_kernel(reg->btf)) { 5277 perm_flags = PTR_MAYBE_NULL | PTR_TRUSTED | MEM_RCU; 5278 5279 /* Only unreferenced case accepts untrusted pointers */ 5280 if (kptr_field->type == BPF_KPTR_UNREF) 5281 perm_flags |= PTR_UNTRUSTED; 5282 } else { 5283 perm_flags = PTR_MAYBE_NULL | MEM_ALLOC; 5284 } 5285 5286 if (base_type(reg->type) != PTR_TO_BTF_ID || (type_flag(reg->type) & ~perm_flags)) 5287 goto bad_type; 5288 5289 /* We need to verify reg->type and reg->btf, before accessing reg->btf */ 5290 reg_name = btf_type_name(reg->btf, reg->btf_id); 5291 5292 /* For ref_ptr case, release function check should ensure we get one 5293 * referenced PTR_TO_BTF_ID, and that its fixed offset is 0. For the 5294 * normal store of unreferenced kptr, we must ensure var_off is zero. 5295 * Since ref_ptr cannot be accessed directly by BPF insns, checks for 5296 * reg->off and reg->ref_obj_id are not needed here. 5297 */ 5298 if (__check_ptr_off_reg(env, reg, regno, true)) 5299 return -EACCES; 5300 5301 /* A full type match is needed, as BTF can be vmlinux, module or prog BTF, and 5302 * we also need to take into account the reg->off. 5303 * 5304 * We want to support cases like: 5305 * 5306 * struct foo { 5307 * struct bar br; 5308 * struct baz bz; 5309 * }; 5310 * 5311 * struct foo *v; 5312 * v = func(); // PTR_TO_BTF_ID 5313 * val->foo = v; // reg->off is zero, btf and btf_id match type 5314 * val->bar = &v->br; // reg->off is still zero, but we need to retry with 5315 * // first member type of struct after comparison fails 5316 * val->baz = &v->bz; // reg->off is non-zero, so struct needs to be walked 5317 * // to match type 5318 * 5319 * In the kptr_ref case, check_func_arg_reg_off already ensures reg->off 5320 * is zero. We must also ensure that btf_struct_ids_match does not walk 5321 * the struct to match type against first member of struct, i.e. reject 5322 * second case from above. Hence, when type is BPF_KPTR_REF, we set 5323 * strict mode to true for type match. 5324 */ 5325 if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off, 5326 kptr_field->kptr.btf, kptr_field->kptr.btf_id, 5327 kptr_field->type == BPF_KPTR_REF)) 5328 goto bad_type; 5329 return 0; 5330 bad_type: 5331 verbose(env, "invalid kptr access, R%d type=%s%s ", regno, 5332 reg_type_str(env, reg->type), reg_name); 5333 verbose(env, "expected=%s%s", reg_type_str(env, PTR_TO_BTF_ID), targ_name); 5334 if (kptr_field->type == BPF_KPTR_UNREF) 5335 verbose(env, " or %s%s\n", reg_type_str(env, PTR_TO_BTF_ID | PTR_UNTRUSTED), 5336 targ_name); 5337 else 5338 verbose(env, "\n"); 5339 return -EINVAL; 5340 } 5341 5342 /* The non-sleepable programs and sleepable programs with explicit bpf_rcu_read_lock() 5343 * can dereference RCU protected pointers and result is PTR_TRUSTED. 5344 */ 5345 static bool in_rcu_cs(struct bpf_verifier_env *env) 5346 { 5347 return env->cur_state->active_rcu_lock || 5348 env->cur_state->active_lock.ptr || 5349 !env->prog->aux->sleepable; 5350 } 5351 5352 /* Once GCC supports btf_type_tag the following mechanism will be replaced with tag check */ 5353 BTF_SET_START(rcu_protected_types) 5354 BTF_ID(struct, prog_test_ref_kfunc) 5355 BTF_ID(struct, cgroup) 5356 BTF_ID(struct, bpf_cpumask) 5357 BTF_ID(struct, task_struct) 5358 BTF_SET_END(rcu_protected_types) 5359 5360 static bool rcu_protected_object(const struct btf *btf, u32 btf_id) 5361 { 5362 if (!btf_is_kernel(btf)) 5363 return false; 5364 return btf_id_set_contains(&rcu_protected_types, btf_id); 5365 } 5366 5367 static bool rcu_safe_kptr(const struct btf_field *field) 5368 { 5369 const struct btf_field_kptr *kptr = &field->kptr; 5370 5371 return field->type == BPF_KPTR_REF && rcu_protected_object(kptr->btf, kptr->btf_id); 5372 } 5373 5374 static int check_map_kptr_access(struct bpf_verifier_env *env, u32 regno, 5375 int value_regno, int insn_idx, 5376 struct btf_field *kptr_field) 5377 { 5378 struct bpf_insn *insn = &env->prog->insnsi[insn_idx]; 5379 int class = BPF_CLASS(insn->code); 5380 struct bpf_reg_state *val_reg; 5381 5382 /* Things we already checked for in check_map_access and caller: 5383 * - Reject cases where variable offset may touch kptr 5384 * - size of access (must be BPF_DW) 5385 * - tnum_is_const(reg->var_off) 5386 * - kptr_field->offset == off + reg->var_off.value 5387 */ 5388 /* Only BPF_[LDX,STX,ST] | BPF_MEM | BPF_DW is supported */ 5389 if (BPF_MODE(insn->code) != BPF_MEM) { 5390 verbose(env, "kptr in map can only be accessed using BPF_MEM instruction mode\n"); 5391 return -EACCES; 5392 } 5393 5394 /* We only allow loading referenced kptr, since it will be marked as 5395 * untrusted, similar to unreferenced kptr. 5396 */ 5397 if (class != BPF_LDX && kptr_field->type == BPF_KPTR_REF) { 5398 verbose(env, "store to referenced kptr disallowed\n"); 5399 return -EACCES; 5400 } 5401 5402 if (class == BPF_LDX) { 5403 val_reg = reg_state(env, value_regno); 5404 /* We can simply mark the value_regno receiving the pointer 5405 * value from map as PTR_TO_BTF_ID, with the correct type. 5406 */ 5407 mark_btf_ld_reg(env, cur_regs(env), value_regno, PTR_TO_BTF_ID, kptr_field->kptr.btf, 5408 kptr_field->kptr.btf_id, 5409 rcu_safe_kptr(kptr_field) && in_rcu_cs(env) ? 5410 PTR_MAYBE_NULL | MEM_RCU : 5411 PTR_MAYBE_NULL | PTR_UNTRUSTED); 5412 } else if (class == BPF_STX) { 5413 val_reg = reg_state(env, value_regno); 5414 if (!register_is_null(val_reg) && 5415 map_kptr_match_type(env, kptr_field, val_reg, value_regno)) 5416 return -EACCES; 5417 } else if (class == BPF_ST) { 5418 if (insn->imm) { 5419 verbose(env, "BPF_ST imm must be 0 when storing to kptr at off=%u\n", 5420 kptr_field->offset); 5421 return -EACCES; 5422 } 5423 } else { 5424 verbose(env, "kptr in map can only be accessed using BPF_LDX/BPF_STX/BPF_ST\n"); 5425 return -EACCES; 5426 } 5427 return 0; 5428 } 5429 5430 /* check read/write into a map element with possible variable offset */ 5431 static int check_map_access(struct bpf_verifier_env *env, u32 regno, 5432 int off, int size, bool zero_size_allowed, 5433 enum bpf_access_src src) 5434 { 5435 struct bpf_verifier_state *vstate = env->cur_state; 5436 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 5437 struct bpf_reg_state *reg = &state->regs[regno]; 5438 struct bpf_map *map = reg->map_ptr; 5439 struct btf_record *rec; 5440 int err, i; 5441 5442 err = check_mem_region_access(env, regno, off, size, map->value_size, 5443 zero_size_allowed); 5444 if (err) 5445 return err; 5446 5447 if (IS_ERR_OR_NULL(map->record)) 5448 return 0; 5449 rec = map->record; 5450 for (i = 0; i < rec->cnt; i++) { 5451 struct btf_field *field = &rec->fields[i]; 5452 u32 p = field->offset; 5453 5454 /* If any part of a field can be touched by load/store, reject 5455 * this program. To check that [x1, x2) overlaps with [y1, y2), 5456 * it is sufficient to check x1 < y2 && y1 < x2. 5457 */ 5458 if (reg->smin_value + off < p + btf_field_type_size(field->type) && 5459 p < reg->umax_value + off + size) { 5460 switch (field->type) { 5461 case BPF_KPTR_UNREF: 5462 case BPF_KPTR_REF: 5463 if (src != ACCESS_DIRECT) { 5464 verbose(env, "kptr cannot be accessed indirectly by helper\n"); 5465 return -EACCES; 5466 } 5467 if (!tnum_is_const(reg->var_off)) { 5468 verbose(env, "kptr access cannot have variable offset\n"); 5469 return -EACCES; 5470 } 5471 if (p != off + reg->var_off.value) { 5472 verbose(env, "kptr access misaligned expected=%u off=%llu\n", 5473 p, off + reg->var_off.value); 5474 return -EACCES; 5475 } 5476 if (size != bpf_size_to_bytes(BPF_DW)) { 5477 verbose(env, "kptr access size must be BPF_DW\n"); 5478 return -EACCES; 5479 } 5480 break; 5481 default: 5482 verbose(env, "%s cannot be accessed directly by load/store\n", 5483 btf_field_type_name(field->type)); 5484 return -EACCES; 5485 } 5486 } 5487 } 5488 return 0; 5489 } 5490 5491 #define MAX_PACKET_OFF 0xffff 5492 5493 static bool may_access_direct_pkt_data(struct bpf_verifier_env *env, 5494 const struct bpf_call_arg_meta *meta, 5495 enum bpf_access_type t) 5496 { 5497 enum bpf_prog_type prog_type = resolve_prog_type(env->prog); 5498 5499 switch (prog_type) { 5500 /* Program types only with direct read access go here! */ 5501 case BPF_PROG_TYPE_LWT_IN: 5502 case BPF_PROG_TYPE_LWT_OUT: 5503 case BPF_PROG_TYPE_LWT_SEG6LOCAL: 5504 case BPF_PROG_TYPE_SK_REUSEPORT: 5505 case BPF_PROG_TYPE_FLOW_DISSECTOR: 5506 case BPF_PROG_TYPE_CGROUP_SKB: 5507 if (t == BPF_WRITE) 5508 return false; 5509 fallthrough; 5510 5511 /* Program types with direct read + write access go here! */ 5512 case BPF_PROG_TYPE_SCHED_CLS: 5513 case BPF_PROG_TYPE_SCHED_ACT: 5514 case BPF_PROG_TYPE_XDP: 5515 case BPF_PROG_TYPE_LWT_XMIT: 5516 case BPF_PROG_TYPE_SK_SKB: 5517 case BPF_PROG_TYPE_SK_MSG: 5518 if (meta) 5519 return meta->pkt_access; 5520 5521 env->seen_direct_write = true; 5522 return true; 5523 5524 case BPF_PROG_TYPE_CGROUP_SOCKOPT: 5525 if (t == BPF_WRITE) 5526 env->seen_direct_write = true; 5527 5528 return true; 5529 5530 default: 5531 return false; 5532 } 5533 } 5534 5535 static int check_packet_access(struct bpf_verifier_env *env, u32 regno, int off, 5536 int size, bool zero_size_allowed) 5537 { 5538 struct bpf_reg_state *regs = cur_regs(env); 5539 struct bpf_reg_state *reg = ®s[regno]; 5540 int err; 5541 5542 /* We may have added a variable offset to the packet pointer; but any 5543 * reg->range we have comes after that. We are only checking the fixed 5544 * offset. 5545 */ 5546 5547 /* We don't allow negative numbers, because we aren't tracking enough 5548 * detail to prove they're safe. 5549 */ 5550 if (reg->smin_value < 0) { 5551 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n", 5552 regno); 5553 return -EACCES; 5554 } 5555 5556 err = reg->range < 0 ? -EINVAL : 5557 __check_mem_access(env, regno, off, size, reg->range, 5558 zero_size_allowed); 5559 if (err) { 5560 verbose(env, "R%d offset is outside of the packet\n", regno); 5561 return err; 5562 } 5563 5564 /* __check_mem_access has made sure "off + size - 1" is within u16. 5565 * reg->umax_value can't be bigger than MAX_PACKET_OFF which is 0xffff, 5566 * otherwise find_good_pkt_pointers would have refused to set range info 5567 * that __check_mem_access would have rejected this pkt access. 5568 * Therefore, "off + reg->umax_value + size - 1" won't overflow u32. 5569 */ 5570 env->prog->aux->max_pkt_offset = 5571 max_t(u32, env->prog->aux->max_pkt_offset, 5572 off + reg->umax_value + size - 1); 5573 5574 return err; 5575 } 5576 5577 /* check access to 'struct bpf_context' fields. Supports fixed offsets only */ 5578 static int check_ctx_access(struct bpf_verifier_env *env, int insn_idx, int off, int size, 5579 enum bpf_access_type t, enum bpf_reg_type *reg_type, 5580 struct btf **btf, u32 *btf_id) 5581 { 5582 struct bpf_insn_access_aux info = { 5583 .reg_type = *reg_type, 5584 .log = &env->log, 5585 }; 5586 5587 if (env->ops->is_valid_access && 5588 env->ops->is_valid_access(off, size, t, env->prog, &info)) { 5589 /* A non zero info.ctx_field_size indicates that this field is a 5590 * candidate for later verifier transformation to load the whole 5591 * field and then apply a mask when accessed with a narrower 5592 * access than actual ctx access size. A zero info.ctx_field_size 5593 * will only allow for whole field access and rejects any other 5594 * type of narrower access. 5595 */ 5596 *reg_type = info.reg_type; 5597 5598 if (base_type(*reg_type) == PTR_TO_BTF_ID) { 5599 *btf = info.btf; 5600 *btf_id = info.btf_id; 5601 } else { 5602 env->insn_aux_data[insn_idx].ctx_field_size = info.ctx_field_size; 5603 } 5604 /* remember the offset of last byte accessed in ctx */ 5605 if (env->prog->aux->max_ctx_offset < off + size) 5606 env->prog->aux->max_ctx_offset = off + size; 5607 return 0; 5608 } 5609 5610 verbose(env, "invalid bpf_context access off=%d size=%d\n", off, size); 5611 return -EACCES; 5612 } 5613 5614 static int check_flow_keys_access(struct bpf_verifier_env *env, int off, 5615 int size) 5616 { 5617 if (size < 0 || off < 0 || 5618 (u64)off + size > sizeof(struct bpf_flow_keys)) { 5619 verbose(env, "invalid access to flow keys off=%d size=%d\n", 5620 off, size); 5621 return -EACCES; 5622 } 5623 return 0; 5624 } 5625 5626 static int check_sock_access(struct bpf_verifier_env *env, int insn_idx, 5627 u32 regno, int off, int size, 5628 enum bpf_access_type t) 5629 { 5630 struct bpf_reg_state *regs = cur_regs(env); 5631 struct bpf_reg_state *reg = ®s[regno]; 5632 struct bpf_insn_access_aux info = {}; 5633 bool valid; 5634 5635 if (reg->smin_value < 0) { 5636 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n", 5637 regno); 5638 return -EACCES; 5639 } 5640 5641 switch (reg->type) { 5642 case PTR_TO_SOCK_COMMON: 5643 valid = bpf_sock_common_is_valid_access(off, size, t, &info); 5644 break; 5645 case PTR_TO_SOCKET: 5646 valid = bpf_sock_is_valid_access(off, size, t, &info); 5647 break; 5648 case PTR_TO_TCP_SOCK: 5649 valid = bpf_tcp_sock_is_valid_access(off, size, t, &info); 5650 break; 5651 case PTR_TO_XDP_SOCK: 5652 valid = bpf_xdp_sock_is_valid_access(off, size, t, &info); 5653 break; 5654 default: 5655 valid = false; 5656 } 5657 5658 5659 if (valid) { 5660 env->insn_aux_data[insn_idx].ctx_field_size = 5661 info.ctx_field_size; 5662 return 0; 5663 } 5664 5665 verbose(env, "R%d invalid %s access off=%d size=%d\n", 5666 regno, reg_type_str(env, reg->type), off, size); 5667 5668 return -EACCES; 5669 } 5670 5671 static bool is_pointer_value(struct bpf_verifier_env *env, int regno) 5672 { 5673 return __is_pointer_value(env->allow_ptr_leaks, reg_state(env, regno)); 5674 } 5675 5676 static bool is_ctx_reg(struct bpf_verifier_env *env, int regno) 5677 { 5678 const struct bpf_reg_state *reg = reg_state(env, regno); 5679 5680 return reg->type == PTR_TO_CTX; 5681 } 5682 5683 static bool is_sk_reg(struct bpf_verifier_env *env, int regno) 5684 { 5685 const struct bpf_reg_state *reg = reg_state(env, regno); 5686 5687 return type_is_sk_pointer(reg->type); 5688 } 5689 5690 static bool is_pkt_reg(struct bpf_verifier_env *env, int regno) 5691 { 5692 const struct bpf_reg_state *reg = reg_state(env, regno); 5693 5694 return type_is_pkt_pointer(reg->type); 5695 } 5696 5697 static bool is_flow_key_reg(struct bpf_verifier_env *env, int regno) 5698 { 5699 const struct bpf_reg_state *reg = reg_state(env, regno); 5700 5701 /* Separate to is_ctx_reg() since we still want to allow BPF_ST here. */ 5702 return reg->type == PTR_TO_FLOW_KEYS; 5703 } 5704 5705 static u32 *reg2btf_ids[__BPF_REG_TYPE_MAX] = { 5706 #ifdef CONFIG_NET 5707 [PTR_TO_SOCKET] = &btf_sock_ids[BTF_SOCK_TYPE_SOCK], 5708 [PTR_TO_SOCK_COMMON] = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON], 5709 [PTR_TO_TCP_SOCK] = &btf_sock_ids[BTF_SOCK_TYPE_TCP], 5710 #endif 5711 [CONST_PTR_TO_MAP] = btf_bpf_map_id, 5712 }; 5713 5714 static bool is_trusted_reg(const struct bpf_reg_state *reg) 5715 { 5716 /* A referenced register is always trusted. */ 5717 if (reg->ref_obj_id) 5718 return true; 5719 5720 /* Types listed in the reg2btf_ids are always trusted */ 5721 if (reg2btf_ids[base_type(reg->type)] && 5722 !bpf_type_has_unsafe_modifiers(reg->type)) 5723 return true; 5724 5725 /* If a register is not referenced, it is trusted if it has the 5726 * MEM_ALLOC or PTR_TRUSTED type modifiers, and no others. Some of the 5727 * other type modifiers may be safe, but we elect to take an opt-in 5728 * approach here as some (e.g. PTR_UNTRUSTED and PTR_MAYBE_NULL) are 5729 * not. 5730 * 5731 * Eventually, we should make PTR_TRUSTED the single source of truth 5732 * for whether a register is trusted. 5733 */ 5734 return type_flag(reg->type) & BPF_REG_TRUSTED_MODIFIERS && 5735 !bpf_type_has_unsafe_modifiers(reg->type); 5736 } 5737 5738 static bool is_rcu_reg(const struct bpf_reg_state *reg) 5739 { 5740 return reg->type & MEM_RCU; 5741 } 5742 5743 static void clear_trusted_flags(enum bpf_type_flag *flag) 5744 { 5745 *flag &= ~(BPF_REG_TRUSTED_MODIFIERS | MEM_RCU); 5746 } 5747 5748 static int check_pkt_ptr_alignment(struct bpf_verifier_env *env, 5749 const struct bpf_reg_state *reg, 5750 int off, int size, bool strict) 5751 { 5752 struct tnum reg_off; 5753 int ip_align; 5754 5755 /* Byte size accesses are always allowed. */ 5756 if (!strict || size == 1) 5757 return 0; 5758 5759 /* For platforms that do not have a Kconfig enabling 5760 * CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS the value of 5761 * NET_IP_ALIGN is universally set to '2'. And on platforms 5762 * that do set CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS, we get 5763 * to this code only in strict mode where we want to emulate 5764 * the NET_IP_ALIGN==2 checking. Therefore use an 5765 * unconditional IP align value of '2'. 5766 */ 5767 ip_align = 2; 5768 5769 reg_off = tnum_add(reg->var_off, tnum_const(ip_align + reg->off + off)); 5770 if (!tnum_is_aligned(reg_off, size)) { 5771 char tn_buf[48]; 5772 5773 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 5774 verbose(env, 5775 "misaligned packet access off %d+%s+%d+%d size %d\n", 5776 ip_align, tn_buf, reg->off, off, size); 5777 return -EACCES; 5778 } 5779 5780 return 0; 5781 } 5782 5783 static int check_generic_ptr_alignment(struct bpf_verifier_env *env, 5784 const struct bpf_reg_state *reg, 5785 const char *pointer_desc, 5786 int off, int size, bool strict) 5787 { 5788 struct tnum reg_off; 5789 5790 /* Byte size accesses are always allowed. */ 5791 if (!strict || size == 1) 5792 return 0; 5793 5794 reg_off = tnum_add(reg->var_off, tnum_const(reg->off + off)); 5795 if (!tnum_is_aligned(reg_off, size)) { 5796 char tn_buf[48]; 5797 5798 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 5799 verbose(env, "misaligned %saccess off %s+%d+%d size %d\n", 5800 pointer_desc, tn_buf, reg->off, off, size); 5801 return -EACCES; 5802 } 5803 5804 return 0; 5805 } 5806 5807 static int check_ptr_alignment(struct bpf_verifier_env *env, 5808 const struct bpf_reg_state *reg, int off, 5809 int size, bool strict_alignment_once) 5810 { 5811 bool strict = env->strict_alignment || strict_alignment_once; 5812 const char *pointer_desc = ""; 5813 5814 switch (reg->type) { 5815 case PTR_TO_PACKET: 5816 case PTR_TO_PACKET_META: 5817 /* Special case, because of NET_IP_ALIGN. Given metadata sits 5818 * right in front, treat it the very same way. 5819 */ 5820 return check_pkt_ptr_alignment(env, reg, off, size, strict); 5821 case PTR_TO_FLOW_KEYS: 5822 pointer_desc = "flow keys "; 5823 break; 5824 case PTR_TO_MAP_KEY: 5825 pointer_desc = "key "; 5826 break; 5827 case PTR_TO_MAP_VALUE: 5828 pointer_desc = "value "; 5829 break; 5830 case PTR_TO_CTX: 5831 pointer_desc = "context "; 5832 break; 5833 case PTR_TO_STACK: 5834 pointer_desc = "stack "; 5835 /* The stack spill tracking logic in check_stack_write_fixed_off() 5836 * and check_stack_read_fixed_off() relies on stack accesses being 5837 * aligned. 5838 */ 5839 strict = true; 5840 break; 5841 case PTR_TO_SOCKET: 5842 pointer_desc = "sock "; 5843 break; 5844 case PTR_TO_SOCK_COMMON: 5845 pointer_desc = "sock_common "; 5846 break; 5847 case PTR_TO_TCP_SOCK: 5848 pointer_desc = "tcp_sock "; 5849 break; 5850 case PTR_TO_XDP_SOCK: 5851 pointer_desc = "xdp_sock "; 5852 break; 5853 default: 5854 break; 5855 } 5856 return check_generic_ptr_alignment(env, reg, pointer_desc, off, size, 5857 strict); 5858 } 5859 5860 /* starting from main bpf function walk all instructions of the function 5861 * and recursively walk all callees that given function can call. 5862 * Ignore jump and exit insns. 5863 * Since recursion is prevented by check_cfg() this algorithm 5864 * only needs a local stack of MAX_CALL_FRAMES to remember callsites 5865 */ 5866 static int check_max_stack_depth_subprog(struct bpf_verifier_env *env, int idx) 5867 { 5868 struct bpf_subprog_info *subprog = env->subprog_info; 5869 struct bpf_insn *insn = env->prog->insnsi; 5870 int depth = 0, frame = 0, i, subprog_end; 5871 bool tail_call_reachable = false; 5872 int ret_insn[MAX_CALL_FRAMES]; 5873 int ret_prog[MAX_CALL_FRAMES]; 5874 int j; 5875 5876 i = subprog[idx].start; 5877 process_func: 5878 /* protect against potential stack overflow that might happen when 5879 * bpf2bpf calls get combined with tailcalls. Limit the caller's stack 5880 * depth for such case down to 256 so that the worst case scenario 5881 * would result in 8k stack size (32 which is tailcall limit * 256 = 5882 * 8k). 5883 * 5884 * To get the idea what might happen, see an example: 5885 * func1 -> sub rsp, 128 5886 * subfunc1 -> sub rsp, 256 5887 * tailcall1 -> add rsp, 256 5888 * func2 -> sub rsp, 192 (total stack size = 128 + 192 = 320) 5889 * subfunc2 -> sub rsp, 64 5890 * subfunc22 -> sub rsp, 128 5891 * tailcall2 -> add rsp, 128 5892 * func3 -> sub rsp, 32 (total stack size 128 + 192 + 64 + 32 = 416) 5893 * 5894 * tailcall will unwind the current stack frame but it will not get rid 5895 * of caller's stack as shown on the example above. 5896 */ 5897 if (idx && subprog[idx].has_tail_call && depth >= 256) { 5898 verbose(env, 5899 "tail_calls are not allowed when call stack of previous frames is %d bytes. Too large\n", 5900 depth); 5901 return -EACCES; 5902 } 5903 /* round up to 32-bytes, since this is granularity 5904 * of interpreter stack size 5905 */ 5906 depth += round_up(max_t(u32, subprog[idx].stack_depth, 1), 32); 5907 if (depth > MAX_BPF_STACK) { 5908 verbose(env, "combined stack size of %d calls is %d. Too large\n", 5909 frame + 1, depth); 5910 return -EACCES; 5911 } 5912 continue_func: 5913 subprog_end = subprog[idx + 1].start; 5914 for (; i < subprog_end; i++) { 5915 int next_insn, sidx; 5916 5917 if (!bpf_pseudo_call(insn + i) && !bpf_pseudo_func(insn + i)) 5918 continue; 5919 /* remember insn and function to return to */ 5920 ret_insn[frame] = i + 1; 5921 ret_prog[frame] = idx; 5922 5923 /* find the callee */ 5924 next_insn = i + insn[i].imm + 1; 5925 sidx = find_subprog(env, next_insn); 5926 if (sidx < 0) { 5927 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n", 5928 next_insn); 5929 return -EFAULT; 5930 } 5931 if (subprog[sidx].is_async_cb) { 5932 if (subprog[sidx].has_tail_call) { 5933 verbose(env, "verifier bug. subprog has tail_call and async cb\n"); 5934 return -EFAULT; 5935 } 5936 /* async callbacks don't increase bpf prog stack size unless called directly */ 5937 if (!bpf_pseudo_call(insn + i)) 5938 continue; 5939 } 5940 i = next_insn; 5941 idx = sidx; 5942 5943 if (subprog[idx].has_tail_call) 5944 tail_call_reachable = true; 5945 5946 frame++; 5947 if (frame >= MAX_CALL_FRAMES) { 5948 verbose(env, "the call stack of %d frames is too deep !\n", 5949 frame); 5950 return -E2BIG; 5951 } 5952 goto process_func; 5953 } 5954 /* if tail call got detected across bpf2bpf calls then mark each of the 5955 * currently present subprog frames as tail call reachable subprogs; 5956 * this info will be utilized by JIT so that we will be preserving the 5957 * tail call counter throughout bpf2bpf calls combined with tailcalls 5958 */ 5959 if (tail_call_reachable) 5960 for (j = 0; j < frame; j++) 5961 subprog[ret_prog[j]].tail_call_reachable = true; 5962 if (subprog[0].tail_call_reachable) 5963 env->prog->aux->tail_call_reachable = true; 5964 5965 /* end of for() loop means the last insn of the 'subprog' 5966 * was reached. Doesn't matter whether it was JA or EXIT 5967 */ 5968 if (frame == 0) 5969 return 0; 5970 depth -= round_up(max_t(u32, subprog[idx].stack_depth, 1), 32); 5971 frame--; 5972 i = ret_insn[frame]; 5973 idx = ret_prog[frame]; 5974 goto continue_func; 5975 } 5976 5977 static int check_max_stack_depth(struct bpf_verifier_env *env) 5978 { 5979 struct bpf_subprog_info *si = env->subprog_info; 5980 int ret; 5981 5982 for (int i = 0; i < env->subprog_cnt; i++) { 5983 if (!i || si[i].is_async_cb) { 5984 ret = check_max_stack_depth_subprog(env, i); 5985 if (ret < 0) 5986 return ret; 5987 } 5988 continue; 5989 } 5990 return 0; 5991 } 5992 5993 #ifndef CONFIG_BPF_JIT_ALWAYS_ON 5994 static int get_callee_stack_depth(struct bpf_verifier_env *env, 5995 const struct bpf_insn *insn, int idx) 5996 { 5997 int start = idx + insn->imm + 1, subprog; 5998 5999 subprog = find_subprog(env, start); 6000 if (subprog < 0) { 6001 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n", 6002 start); 6003 return -EFAULT; 6004 } 6005 return env->subprog_info[subprog].stack_depth; 6006 } 6007 #endif 6008 6009 static int __check_buffer_access(struct bpf_verifier_env *env, 6010 const char *buf_info, 6011 const struct bpf_reg_state *reg, 6012 int regno, int off, int size) 6013 { 6014 if (off < 0) { 6015 verbose(env, 6016 "R%d invalid %s buffer access: off=%d, size=%d\n", 6017 regno, buf_info, off, size); 6018 return -EACCES; 6019 } 6020 if (!tnum_is_const(reg->var_off) || reg->var_off.value) { 6021 char tn_buf[48]; 6022 6023 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 6024 verbose(env, 6025 "R%d invalid variable buffer offset: off=%d, var_off=%s\n", 6026 regno, off, tn_buf); 6027 return -EACCES; 6028 } 6029 6030 return 0; 6031 } 6032 6033 static int check_tp_buffer_access(struct bpf_verifier_env *env, 6034 const struct bpf_reg_state *reg, 6035 int regno, int off, int size) 6036 { 6037 int err; 6038 6039 err = __check_buffer_access(env, "tracepoint", reg, regno, off, size); 6040 if (err) 6041 return err; 6042 6043 if (off + size > env->prog->aux->max_tp_access) 6044 env->prog->aux->max_tp_access = off + size; 6045 6046 return 0; 6047 } 6048 6049 static int check_buffer_access(struct bpf_verifier_env *env, 6050 const struct bpf_reg_state *reg, 6051 int regno, int off, int size, 6052 bool zero_size_allowed, 6053 u32 *max_access) 6054 { 6055 const char *buf_info = type_is_rdonly_mem(reg->type) ? "rdonly" : "rdwr"; 6056 int err; 6057 6058 err = __check_buffer_access(env, buf_info, reg, regno, off, size); 6059 if (err) 6060 return err; 6061 6062 if (off + size > *max_access) 6063 *max_access = off + size; 6064 6065 return 0; 6066 } 6067 6068 /* BPF architecture zero extends alu32 ops into 64-bit registesr */ 6069 static void zext_32_to_64(struct bpf_reg_state *reg) 6070 { 6071 reg->var_off = tnum_subreg(reg->var_off); 6072 __reg_assign_32_into_64(reg); 6073 } 6074 6075 /* truncate register to smaller size (in bytes) 6076 * must be called with size < BPF_REG_SIZE 6077 */ 6078 static void coerce_reg_to_size(struct bpf_reg_state *reg, int size) 6079 { 6080 u64 mask; 6081 6082 /* clear high bits in bit representation */ 6083 reg->var_off = tnum_cast(reg->var_off, size); 6084 6085 /* fix arithmetic bounds */ 6086 mask = ((u64)1 << (size * 8)) - 1; 6087 if ((reg->umin_value & ~mask) == (reg->umax_value & ~mask)) { 6088 reg->umin_value &= mask; 6089 reg->umax_value &= mask; 6090 } else { 6091 reg->umin_value = 0; 6092 reg->umax_value = mask; 6093 } 6094 reg->smin_value = reg->umin_value; 6095 reg->smax_value = reg->umax_value; 6096 6097 /* If size is smaller than 32bit register the 32bit register 6098 * values are also truncated so we push 64-bit bounds into 6099 * 32-bit bounds. Above were truncated < 32-bits already. 6100 */ 6101 if (size >= 4) 6102 return; 6103 __reg_combine_64_into_32(reg); 6104 } 6105 6106 static void set_sext64_default_val(struct bpf_reg_state *reg, int size) 6107 { 6108 if (size == 1) { 6109 reg->smin_value = reg->s32_min_value = S8_MIN; 6110 reg->smax_value = reg->s32_max_value = S8_MAX; 6111 } else if (size == 2) { 6112 reg->smin_value = reg->s32_min_value = S16_MIN; 6113 reg->smax_value = reg->s32_max_value = S16_MAX; 6114 } else { 6115 /* size == 4 */ 6116 reg->smin_value = reg->s32_min_value = S32_MIN; 6117 reg->smax_value = reg->s32_max_value = S32_MAX; 6118 } 6119 reg->umin_value = reg->u32_min_value = 0; 6120 reg->umax_value = U64_MAX; 6121 reg->u32_max_value = U32_MAX; 6122 reg->var_off = tnum_unknown; 6123 } 6124 6125 static void coerce_reg_to_size_sx(struct bpf_reg_state *reg, int size) 6126 { 6127 s64 init_s64_max, init_s64_min, s64_max, s64_min, u64_cval; 6128 u64 top_smax_value, top_smin_value; 6129 u64 num_bits = size * 8; 6130 6131 if (tnum_is_const(reg->var_off)) { 6132 u64_cval = reg->var_off.value; 6133 if (size == 1) 6134 reg->var_off = tnum_const((s8)u64_cval); 6135 else if (size == 2) 6136 reg->var_off = tnum_const((s16)u64_cval); 6137 else 6138 /* size == 4 */ 6139 reg->var_off = tnum_const((s32)u64_cval); 6140 6141 u64_cval = reg->var_off.value; 6142 reg->smax_value = reg->smin_value = u64_cval; 6143 reg->umax_value = reg->umin_value = u64_cval; 6144 reg->s32_max_value = reg->s32_min_value = u64_cval; 6145 reg->u32_max_value = reg->u32_min_value = u64_cval; 6146 return; 6147 } 6148 6149 top_smax_value = ((u64)reg->smax_value >> num_bits) << num_bits; 6150 top_smin_value = ((u64)reg->smin_value >> num_bits) << num_bits; 6151 6152 if (top_smax_value != top_smin_value) 6153 goto out; 6154 6155 /* find the s64_min and s64_min after sign extension */ 6156 if (size == 1) { 6157 init_s64_max = (s8)reg->smax_value; 6158 init_s64_min = (s8)reg->smin_value; 6159 } else if (size == 2) { 6160 init_s64_max = (s16)reg->smax_value; 6161 init_s64_min = (s16)reg->smin_value; 6162 } else { 6163 init_s64_max = (s32)reg->smax_value; 6164 init_s64_min = (s32)reg->smin_value; 6165 } 6166 6167 s64_max = max(init_s64_max, init_s64_min); 6168 s64_min = min(init_s64_max, init_s64_min); 6169 6170 /* both of s64_max/s64_min positive or negative */ 6171 if ((s64_max >= 0) == (s64_min >= 0)) { 6172 reg->s32_min_value = reg->smin_value = s64_min; 6173 reg->s32_max_value = reg->smax_value = s64_max; 6174 reg->u32_min_value = reg->umin_value = s64_min; 6175 reg->u32_max_value = reg->umax_value = s64_max; 6176 reg->var_off = tnum_range(s64_min, s64_max); 6177 return; 6178 } 6179 6180 out: 6181 set_sext64_default_val(reg, size); 6182 } 6183 6184 static void set_sext32_default_val(struct bpf_reg_state *reg, int size) 6185 { 6186 if (size == 1) { 6187 reg->s32_min_value = S8_MIN; 6188 reg->s32_max_value = S8_MAX; 6189 } else { 6190 /* size == 2 */ 6191 reg->s32_min_value = S16_MIN; 6192 reg->s32_max_value = S16_MAX; 6193 } 6194 reg->u32_min_value = 0; 6195 reg->u32_max_value = U32_MAX; 6196 reg->var_off = tnum_subreg(tnum_unknown); 6197 } 6198 6199 static void coerce_subreg_to_size_sx(struct bpf_reg_state *reg, int size) 6200 { 6201 s32 init_s32_max, init_s32_min, s32_max, s32_min, u32_val; 6202 u32 top_smax_value, top_smin_value; 6203 u32 num_bits = size * 8; 6204 6205 if (tnum_is_const(reg->var_off)) { 6206 u32_val = reg->var_off.value; 6207 if (size == 1) 6208 reg->var_off = tnum_const((s8)u32_val); 6209 else 6210 reg->var_off = tnum_const((s16)u32_val); 6211 6212 u32_val = reg->var_off.value; 6213 reg->s32_min_value = reg->s32_max_value = u32_val; 6214 reg->u32_min_value = reg->u32_max_value = u32_val; 6215 return; 6216 } 6217 6218 top_smax_value = ((u32)reg->s32_max_value >> num_bits) << num_bits; 6219 top_smin_value = ((u32)reg->s32_min_value >> num_bits) << num_bits; 6220 6221 if (top_smax_value != top_smin_value) 6222 goto out; 6223 6224 /* find the s32_min and s32_min after sign extension */ 6225 if (size == 1) { 6226 init_s32_max = (s8)reg->s32_max_value; 6227 init_s32_min = (s8)reg->s32_min_value; 6228 } else { 6229 /* size == 2 */ 6230 init_s32_max = (s16)reg->s32_max_value; 6231 init_s32_min = (s16)reg->s32_min_value; 6232 } 6233 s32_max = max(init_s32_max, init_s32_min); 6234 s32_min = min(init_s32_max, init_s32_min); 6235 6236 if ((s32_min >= 0) == (s32_max >= 0)) { 6237 reg->s32_min_value = s32_min; 6238 reg->s32_max_value = s32_max; 6239 reg->u32_min_value = (u32)s32_min; 6240 reg->u32_max_value = (u32)s32_max; 6241 reg->var_off = tnum_subreg(tnum_range(s32_min, s32_max)); 6242 return; 6243 } 6244 6245 out: 6246 set_sext32_default_val(reg, size); 6247 } 6248 6249 static bool bpf_map_is_rdonly(const struct bpf_map *map) 6250 { 6251 /* A map is considered read-only if the following condition are true: 6252 * 6253 * 1) BPF program side cannot change any of the map content. The 6254 * BPF_F_RDONLY_PROG flag is throughout the lifetime of a map 6255 * and was set at map creation time. 6256 * 2) The map value(s) have been initialized from user space by a 6257 * loader and then "frozen", such that no new map update/delete 6258 * operations from syscall side are possible for the rest of 6259 * the map's lifetime from that point onwards. 6260 * 3) Any parallel/pending map update/delete operations from syscall 6261 * side have been completed. Only after that point, it's safe to 6262 * assume that map value(s) are immutable. 6263 */ 6264 return (map->map_flags & BPF_F_RDONLY_PROG) && 6265 READ_ONCE(map->frozen) && 6266 !bpf_map_write_active(map); 6267 } 6268 6269 static int bpf_map_direct_read(struct bpf_map *map, int off, int size, u64 *val, 6270 bool is_ldsx) 6271 { 6272 void *ptr; 6273 u64 addr; 6274 int err; 6275 6276 err = map->ops->map_direct_value_addr(map, &addr, off); 6277 if (err) 6278 return err; 6279 ptr = (void *)(long)addr + off; 6280 6281 switch (size) { 6282 case sizeof(u8): 6283 *val = is_ldsx ? (s64)*(s8 *)ptr : (u64)*(u8 *)ptr; 6284 break; 6285 case sizeof(u16): 6286 *val = is_ldsx ? (s64)*(s16 *)ptr : (u64)*(u16 *)ptr; 6287 break; 6288 case sizeof(u32): 6289 *val = is_ldsx ? (s64)*(s32 *)ptr : (u64)*(u32 *)ptr; 6290 break; 6291 case sizeof(u64): 6292 *val = *(u64 *)ptr; 6293 break; 6294 default: 6295 return -EINVAL; 6296 } 6297 return 0; 6298 } 6299 6300 #define BTF_TYPE_SAFE_RCU(__type) __PASTE(__type, __safe_rcu) 6301 #define BTF_TYPE_SAFE_RCU_OR_NULL(__type) __PASTE(__type, __safe_rcu_or_null) 6302 #define BTF_TYPE_SAFE_TRUSTED(__type) __PASTE(__type, __safe_trusted) 6303 #define BTF_TYPE_SAFE_TRUSTED_OR_NULL(__type) __PASTE(__type, __safe_trusted_or_null) 6304 6305 /* 6306 * Allow list few fields as RCU trusted or full trusted. 6307 * This logic doesn't allow mix tagging and will be removed once GCC supports 6308 * btf_type_tag. 6309 */ 6310 6311 /* RCU trusted: these fields are trusted in RCU CS and never NULL */ 6312 BTF_TYPE_SAFE_RCU(struct task_struct) { 6313 const cpumask_t *cpus_ptr; 6314 struct css_set __rcu *cgroups; 6315 struct task_struct __rcu *real_parent; 6316 struct task_struct *group_leader; 6317 }; 6318 6319 BTF_TYPE_SAFE_RCU(struct cgroup) { 6320 /* cgrp->kn is always accessible as documented in kernel/cgroup/cgroup.c */ 6321 struct kernfs_node *kn; 6322 }; 6323 6324 BTF_TYPE_SAFE_RCU(struct css_set) { 6325 struct cgroup *dfl_cgrp; 6326 }; 6327 6328 /* RCU trusted: these fields are trusted in RCU CS and can be NULL */ 6329 BTF_TYPE_SAFE_RCU_OR_NULL(struct mm_struct) { 6330 struct file __rcu *exe_file; 6331 }; 6332 6333 /* skb->sk, req->sk are not RCU protected, but we mark them as such 6334 * because bpf prog accessible sockets are SOCK_RCU_FREE. 6335 */ 6336 BTF_TYPE_SAFE_RCU_OR_NULL(struct sk_buff) { 6337 struct sock *sk; 6338 }; 6339 6340 BTF_TYPE_SAFE_RCU_OR_NULL(struct request_sock) { 6341 struct sock *sk; 6342 }; 6343 6344 /* full trusted: these fields are trusted even outside of RCU CS and never NULL */ 6345 BTF_TYPE_SAFE_TRUSTED(struct bpf_iter_meta) { 6346 struct seq_file *seq; 6347 }; 6348 6349 BTF_TYPE_SAFE_TRUSTED(struct bpf_iter__task) { 6350 struct bpf_iter_meta *meta; 6351 struct task_struct *task; 6352 }; 6353 6354 BTF_TYPE_SAFE_TRUSTED(struct linux_binprm) { 6355 struct file *file; 6356 }; 6357 6358 BTF_TYPE_SAFE_TRUSTED(struct file) { 6359 struct inode *f_inode; 6360 }; 6361 6362 BTF_TYPE_SAFE_TRUSTED(struct dentry) { 6363 /* no negative dentry-s in places where bpf can see it */ 6364 struct inode *d_inode; 6365 }; 6366 6367 BTF_TYPE_SAFE_TRUSTED_OR_NULL(struct socket) { 6368 struct sock *sk; 6369 }; 6370 6371 static bool type_is_rcu(struct bpf_verifier_env *env, 6372 struct bpf_reg_state *reg, 6373 const char *field_name, u32 btf_id) 6374 { 6375 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct task_struct)); 6376 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct cgroup)); 6377 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct css_set)); 6378 6379 return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_rcu"); 6380 } 6381 6382 static bool type_is_rcu_or_null(struct bpf_verifier_env *env, 6383 struct bpf_reg_state *reg, 6384 const char *field_name, u32 btf_id) 6385 { 6386 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct mm_struct)); 6387 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct sk_buff)); 6388 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct request_sock)); 6389 6390 return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_rcu_or_null"); 6391 } 6392 6393 static bool type_is_trusted(struct bpf_verifier_env *env, 6394 struct bpf_reg_state *reg, 6395 const char *field_name, u32 btf_id) 6396 { 6397 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct bpf_iter_meta)); 6398 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct bpf_iter__task)); 6399 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct linux_binprm)); 6400 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct file)); 6401 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct dentry)); 6402 6403 return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_trusted"); 6404 } 6405 6406 static bool type_is_trusted_or_null(struct bpf_verifier_env *env, 6407 struct bpf_reg_state *reg, 6408 const char *field_name, u32 btf_id) 6409 { 6410 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED_OR_NULL(struct socket)); 6411 6412 return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, 6413 "__safe_trusted_or_null"); 6414 } 6415 6416 static int check_ptr_to_btf_access(struct bpf_verifier_env *env, 6417 struct bpf_reg_state *regs, 6418 int regno, int off, int size, 6419 enum bpf_access_type atype, 6420 int value_regno) 6421 { 6422 struct bpf_reg_state *reg = regs + regno; 6423 const struct btf_type *t = btf_type_by_id(reg->btf, reg->btf_id); 6424 const char *tname = btf_name_by_offset(reg->btf, t->name_off); 6425 const char *field_name = NULL; 6426 enum bpf_type_flag flag = 0; 6427 u32 btf_id = 0; 6428 int ret; 6429 6430 if (!env->allow_ptr_leaks) { 6431 verbose(env, 6432 "'struct %s' access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n", 6433 tname); 6434 return -EPERM; 6435 } 6436 if (!env->prog->gpl_compatible && btf_is_kernel(reg->btf)) { 6437 verbose(env, 6438 "Cannot access kernel 'struct %s' from non-GPL compatible program\n", 6439 tname); 6440 return -EINVAL; 6441 } 6442 if (off < 0) { 6443 verbose(env, 6444 "R%d is ptr_%s invalid negative access: off=%d\n", 6445 regno, tname, off); 6446 return -EACCES; 6447 } 6448 if (!tnum_is_const(reg->var_off) || reg->var_off.value) { 6449 char tn_buf[48]; 6450 6451 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 6452 verbose(env, 6453 "R%d is ptr_%s invalid variable offset: off=%d, var_off=%s\n", 6454 regno, tname, off, tn_buf); 6455 return -EACCES; 6456 } 6457 6458 if (reg->type & MEM_USER) { 6459 verbose(env, 6460 "R%d is ptr_%s access user memory: off=%d\n", 6461 regno, tname, off); 6462 return -EACCES; 6463 } 6464 6465 if (reg->type & MEM_PERCPU) { 6466 verbose(env, 6467 "R%d is ptr_%s access percpu memory: off=%d\n", 6468 regno, tname, off); 6469 return -EACCES; 6470 } 6471 6472 if (env->ops->btf_struct_access && !type_is_alloc(reg->type) && atype == BPF_WRITE) { 6473 if (!btf_is_kernel(reg->btf)) { 6474 verbose(env, "verifier internal error: reg->btf must be kernel btf\n"); 6475 return -EFAULT; 6476 } 6477 ret = env->ops->btf_struct_access(&env->log, reg, off, size); 6478 } else { 6479 /* Writes are permitted with default btf_struct_access for 6480 * program allocated objects (which always have ref_obj_id > 0), 6481 * but not for untrusted PTR_TO_BTF_ID | MEM_ALLOC. 6482 */ 6483 if (atype != BPF_READ && !type_is_ptr_alloc_obj(reg->type)) { 6484 verbose(env, "only read is supported\n"); 6485 return -EACCES; 6486 } 6487 6488 if (type_is_alloc(reg->type) && !type_is_non_owning_ref(reg->type) && 6489 !reg->ref_obj_id) { 6490 verbose(env, "verifier internal error: ref_obj_id for allocated object must be non-zero\n"); 6491 return -EFAULT; 6492 } 6493 6494 ret = btf_struct_access(&env->log, reg, off, size, atype, &btf_id, &flag, &field_name); 6495 } 6496 6497 if (ret < 0) 6498 return ret; 6499 6500 if (ret != PTR_TO_BTF_ID) { 6501 /* just mark; */ 6502 6503 } else if (type_flag(reg->type) & PTR_UNTRUSTED) { 6504 /* If this is an untrusted pointer, all pointers formed by walking it 6505 * also inherit the untrusted flag. 6506 */ 6507 flag = PTR_UNTRUSTED; 6508 6509 } else if (is_trusted_reg(reg) || is_rcu_reg(reg)) { 6510 /* By default any pointer obtained from walking a trusted pointer is no 6511 * longer trusted, unless the field being accessed has explicitly been 6512 * marked as inheriting its parent's state of trust (either full or RCU). 6513 * For example: 6514 * 'cgroups' pointer is untrusted if task->cgroups dereference 6515 * happened in a sleepable program outside of bpf_rcu_read_lock() 6516 * section. In a non-sleepable program it's trusted while in RCU CS (aka MEM_RCU). 6517 * Note bpf_rcu_read_unlock() converts MEM_RCU pointers to PTR_UNTRUSTED. 6518 * 6519 * A regular RCU-protected pointer with __rcu tag can also be deemed 6520 * trusted if we are in an RCU CS. Such pointer can be NULL. 6521 */ 6522 if (type_is_trusted(env, reg, field_name, btf_id)) { 6523 flag |= PTR_TRUSTED; 6524 } else if (type_is_trusted_or_null(env, reg, field_name, btf_id)) { 6525 flag |= PTR_TRUSTED | PTR_MAYBE_NULL; 6526 } else if (in_rcu_cs(env) && !type_may_be_null(reg->type)) { 6527 if (type_is_rcu(env, reg, field_name, btf_id)) { 6528 /* ignore __rcu tag and mark it MEM_RCU */ 6529 flag |= MEM_RCU; 6530 } else if (flag & MEM_RCU || 6531 type_is_rcu_or_null(env, reg, field_name, btf_id)) { 6532 /* __rcu tagged pointers can be NULL */ 6533 flag |= MEM_RCU | PTR_MAYBE_NULL; 6534 6535 /* We always trust them */ 6536 if (type_is_rcu_or_null(env, reg, field_name, btf_id) && 6537 flag & PTR_UNTRUSTED) 6538 flag &= ~PTR_UNTRUSTED; 6539 } else if (flag & (MEM_PERCPU | MEM_USER)) { 6540 /* keep as-is */ 6541 } else { 6542 /* walking unknown pointers yields old deprecated PTR_TO_BTF_ID */ 6543 clear_trusted_flags(&flag); 6544 } 6545 } else { 6546 /* 6547 * If not in RCU CS or MEM_RCU pointer can be NULL then 6548 * aggressively mark as untrusted otherwise such 6549 * pointers will be plain PTR_TO_BTF_ID without flags 6550 * and will be allowed to be passed into helpers for 6551 * compat reasons. 6552 */ 6553 flag = PTR_UNTRUSTED; 6554 } 6555 } else { 6556 /* Old compat. Deprecated */ 6557 clear_trusted_flags(&flag); 6558 } 6559 6560 if (atype == BPF_READ && value_regno >= 0) 6561 mark_btf_ld_reg(env, regs, value_regno, ret, reg->btf, btf_id, flag); 6562 6563 return 0; 6564 } 6565 6566 static int check_ptr_to_map_access(struct bpf_verifier_env *env, 6567 struct bpf_reg_state *regs, 6568 int regno, int off, int size, 6569 enum bpf_access_type atype, 6570 int value_regno) 6571 { 6572 struct bpf_reg_state *reg = regs + regno; 6573 struct bpf_map *map = reg->map_ptr; 6574 struct bpf_reg_state map_reg; 6575 enum bpf_type_flag flag = 0; 6576 const struct btf_type *t; 6577 const char *tname; 6578 u32 btf_id; 6579 int ret; 6580 6581 if (!btf_vmlinux) { 6582 verbose(env, "map_ptr access not supported without CONFIG_DEBUG_INFO_BTF\n"); 6583 return -ENOTSUPP; 6584 } 6585 6586 if (!map->ops->map_btf_id || !*map->ops->map_btf_id) { 6587 verbose(env, "map_ptr access not supported for map type %d\n", 6588 map->map_type); 6589 return -ENOTSUPP; 6590 } 6591 6592 t = btf_type_by_id(btf_vmlinux, *map->ops->map_btf_id); 6593 tname = btf_name_by_offset(btf_vmlinux, t->name_off); 6594 6595 if (!env->allow_ptr_leaks) { 6596 verbose(env, 6597 "'struct %s' access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n", 6598 tname); 6599 return -EPERM; 6600 } 6601 6602 if (off < 0) { 6603 verbose(env, "R%d is %s invalid negative access: off=%d\n", 6604 regno, tname, off); 6605 return -EACCES; 6606 } 6607 6608 if (atype != BPF_READ) { 6609 verbose(env, "only read from %s is supported\n", tname); 6610 return -EACCES; 6611 } 6612 6613 /* Simulate access to a PTR_TO_BTF_ID */ 6614 memset(&map_reg, 0, sizeof(map_reg)); 6615 mark_btf_ld_reg(env, &map_reg, 0, PTR_TO_BTF_ID, btf_vmlinux, *map->ops->map_btf_id, 0); 6616 ret = btf_struct_access(&env->log, &map_reg, off, size, atype, &btf_id, &flag, NULL); 6617 if (ret < 0) 6618 return ret; 6619 6620 if (value_regno >= 0) 6621 mark_btf_ld_reg(env, regs, value_regno, ret, btf_vmlinux, btf_id, flag); 6622 6623 return 0; 6624 } 6625 6626 /* Check that the stack access at the given offset is within bounds. The 6627 * maximum valid offset is -1. 6628 * 6629 * The minimum valid offset is -MAX_BPF_STACK for writes, and 6630 * -state->allocated_stack for reads. 6631 */ 6632 static int check_stack_slot_within_bounds(struct bpf_verifier_env *env, 6633 s64 off, 6634 struct bpf_func_state *state, 6635 enum bpf_access_type t) 6636 { 6637 int min_valid_off; 6638 6639 if (t == BPF_WRITE || env->allow_uninit_stack) 6640 min_valid_off = -MAX_BPF_STACK; 6641 else 6642 min_valid_off = -state->allocated_stack; 6643 6644 if (off < min_valid_off || off > -1) 6645 return -EACCES; 6646 return 0; 6647 } 6648 6649 /* Check that the stack access at 'regno + off' falls within the maximum stack 6650 * bounds. 6651 * 6652 * 'off' includes `regno->offset`, but not its dynamic part (if any). 6653 */ 6654 static int check_stack_access_within_bounds( 6655 struct bpf_verifier_env *env, 6656 int regno, int off, int access_size, 6657 enum bpf_access_src src, enum bpf_access_type type) 6658 { 6659 struct bpf_reg_state *regs = cur_regs(env); 6660 struct bpf_reg_state *reg = regs + regno; 6661 struct bpf_func_state *state = func(env, reg); 6662 s64 min_off, max_off; 6663 int err; 6664 char *err_extra; 6665 6666 if (src == ACCESS_HELPER) 6667 /* We don't know if helpers are reading or writing (or both). */ 6668 err_extra = " indirect access to"; 6669 else if (type == BPF_READ) 6670 err_extra = " read from"; 6671 else 6672 err_extra = " write to"; 6673 6674 if (tnum_is_const(reg->var_off)) { 6675 min_off = (s64)reg->var_off.value + off; 6676 max_off = min_off + access_size; 6677 } else { 6678 if (reg->smax_value >= BPF_MAX_VAR_OFF || 6679 reg->smin_value <= -BPF_MAX_VAR_OFF) { 6680 verbose(env, "invalid unbounded variable-offset%s stack R%d\n", 6681 err_extra, regno); 6682 return -EACCES; 6683 } 6684 min_off = reg->smin_value + off; 6685 max_off = reg->smax_value + off + access_size; 6686 } 6687 6688 err = check_stack_slot_within_bounds(env, min_off, state, type); 6689 if (!err && max_off > 0) 6690 err = -EINVAL; /* out of stack access into non-negative offsets */ 6691 if (!err && access_size < 0) 6692 /* access_size should not be negative (or overflow an int); others checks 6693 * along the way should have prevented such an access. 6694 */ 6695 err = -EFAULT; /* invalid negative access size; integer overflow? */ 6696 6697 if (err) { 6698 if (tnum_is_const(reg->var_off)) { 6699 verbose(env, "invalid%s stack R%d off=%d size=%d\n", 6700 err_extra, regno, off, access_size); 6701 } else { 6702 char tn_buf[48]; 6703 6704 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 6705 verbose(env, "invalid variable-offset%s stack R%d var_off=%s size=%d\n", 6706 err_extra, regno, tn_buf, access_size); 6707 } 6708 return err; 6709 } 6710 6711 return grow_stack_state(env, state, round_up(-min_off, BPF_REG_SIZE)); 6712 } 6713 6714 /* check whether memory at (regno + off) is accessible for t = (read | write) 6715 * if t==write, value_regno is a register which value is stored into memory 6716 * if t==read, value_regno is a register which will receive the value from memory 6717 * if t==write && value_regno==-1, some unknown value is stored into memory 6718 * if t==read && value_regno==-1, don't care what we read from memory 6719 */ 6720 static int check_mem_access(struct bpf_verifier_env *env, int insn_idx, u32 regno, 6721 int off, int bpf_size, enum bpf_access_type t, 6722 int value_regno, bool strict_alignment_once, bool is_ldsx) 6723 { 6724 struct bpf_reg_state *regs = cur_regs(env); 6725 struct bpf_reg_state *reg = regs + regno; 6726 int size, err = 0; 6727 6728 size = bpf_size_to_bytes(bpf_size); 6729 if (size < 0) 6730 return size; 6731 6732 /* alignment checks will add in reg->off themselves */ 6733 err = check_ptr_alignment(env, reg, off, size, strict_alignment_once); 6734 if (err) 6735 return err; 6736 6737 /* for access checks, reg->off is just part of off */ 6738 off += reg->off; 6739 6740 if (reg->type == PTR_TO_MAP_KEY) { 6741 if (t == BPF_WRITE) { 6742 verbose(env, "write to change key R%d not allowed\n", regno); 6743 return -EACCES; 6744 } 6745 6746 err = check_mem_region_access(env, regno, off, size, 6747 reg->map_ptr->key_size, false); 6748 if (err) 6749 return err; 6750 if (value_regno >= 0) 6751 mark_reg_unknown(env, regs, value_regno); 6752 } else if (reg->type == PTR_TO_MAP_VALUE) { 6753 struct btf_field *kptr_field = NULL; 6754 6755 if (t == BPF_WRITE && value_regno >= 0 && 6756 is_pointer_value(env, value_regno)) { 6757 verbose(env, "R%d leaks addr into map\n", value_regno); 6758 return -EACCES; 6759 } 6760 err = check_map_access_type(env, regno, off, size, t); 6761 if (err) 6762 return err; 6763 err = check_map_access(env, regno, off, size, false, ACCESS_DIRECT); 6764 if (err) 6765 return err; 6766 if (tnum_is_const(reg->var_off)) 6767 kptr_field = btf_record_find(reg->map_ptr->record, 6768 off + reg->var_off.value, BPF_KPTR); 6769 if (kptr_field) { 6770 err = check_map_kptr_access(env, regno, value_regno, insn_idx, kptr_field); 6771 } else if (t == BPF_READ && value_regno >= 0) { 6772 struct bpf_map *map = reg->map_ptr; 6773 6774 /* if map is read-only, track its contents as scalars */ 6775 if (tnum_is_const(reg->var_off) && 6776 bpf_map_is_rdonly(map) && 6777 map->ops->map_direct_value_addr) { 6778 int map_off = off + reg->var_off.value; 6779 u64 val = 0; 6780 6781 err = bpf_map_direct_read(map, map_off, size, 6782 &val, is_ldsx); 6783 if (err) 6784 return err; 6785 6786 regs[value_regno].type = SCALAR_VALUE; 6787 __mark_reg_known(®s[value_regno], val); 6788 } else { 6789 mark_reg_unknown(env, regs, value_regno); 6790 } 6791 } 6792 } else if (base_type(reg->type) == PTR_TO_MEM) { 6793 bool rdonly_mem = type_is_rdonly_mem(reg->type); 6794 6795 if (type_may_be_null(reg->type)) { 6796 verbose(env, "R%d invalid mem access '%s'\n", regno, 6797 reg_type_str(env, reg->type)); 6798 return -EACCES; 6799 } 6800 6801 if (t == BPF_WRITE && rdonly_mem) { 6802 verbose(env, "R%d cannot write into %s\n", 6803 regno, reg_type_str(env, reg->type)); 6804 return -EACCES; 6805 } 6806 6807 if (t == BPF_WRITE && value_regno >= 0 && 6808 is_pointer_value(env, value_regno)) { 6809 verbose(env, "R%d leaks addr into mem\n", value_regno); 6810 return -EACCES; 6811 } 6812 6813 err = check_mem_region_access(env, regno, off, size, 6814 reg->mem_size, false); 6815 if (!err && value_regno >= 0 && (t == BPF_READ || rdonly_mem)) 6816 mark_reg_unknown(env, regs, value_regno); 6817 } else if (reg->type == PTR_TO_CTX) { 6818 enum bpf_reg_type reg_type = SCALAR_VALUE; 6819 struct btf *btf = NULL; 6820 u32 btf_id = 0; 6821 6822 if (t == BPF_WRITE && value_regno >= 0 && 6823 is_pointer_value(env, value_regno)) { 6824 verbose(env, "R%d leaks addr into ctx\n", value_regno); 6825 return -EACCES; 6826 } 6827 6828 err = check_ptr_off_reg(env, reg, regno); 6829 if (err < 0) 6830 return err; 6831 6832 err = check_ctx_access(env, insn_idx, off, size, t, ®_type, &btf, 6833 &btf_id); 6834 if (err) 6835 verbose_linfo(env, insn_idx, "; "); 6836 if (!err && t == BPF_READ && value_regno >= 0) { 6837 /* ctx access returns either a scalar, or a 6838 * PTR_TO_PACKET[_META,_END]. In the latter 6839 * case, we know the offset is zero. 6840 */ 6841 if (reg_type == SCALAR_VALUE) { 6842 mark_reg_unknown(env, regs, value_regno); 6843 } else { 6844 mark_reg_known_zero(env, regs, 6845 value_regno); 6846 if (type_may_be_null(reg_type)) 6847 regs[value_regno].id = ++env->id_gen; 6848 /* A load of ctx field could have different 6849 * actual load size with the one encoded in the 6850 * insn. When the dst is PTR, it is for sure not 6851 * a sub-register. 6852 */ 6853 regs[value_regno].subreg_def = DEF_NOT_SUBREG; 6854 if (base_type(reg_type) == PTR_TO_BTF_ID) { 6855 regs[value_regno].btf = btf; 6856 regs[value_regno].btf_id = btf_id; 6857 } 6858 } 6859 regs[value_regno].type = reg_type; 6860 } 6861 6862 } else if (reg->type == PTR_TO_STACK) { 6863 /* Basic bounds checks. */ 6864 err = check_stack_access_within_bounds(env, regno, off, size, ACCESS_DIRECT, t); 6865 if (err) 6866 return err; 6867 6868 if (t == BPF_READ) 6869 err = check_stack_read(env, regno, off, size, 6870 value_regno); 6871 else 6872 err = check_stack_write(env, regno, off, size, 6873 value_regno, insn_idx); 6874 } else if (reg_is_pkt_pointer(reg)) { 6875 if (t == BPF_WRITE && !may_access_direct_pkt_data(env, NULL, t)) { 6876 verbose(env, "cannot write into packet\n"); 6877 return -EACCES; 6878 } 6879 if (t == BPF_WRITE && value_regno >= 0 && 6880 is_pointer_value(env, value_regno)) { 6881 verbose(env, "R%d leaks addr into packet\n", 6882 value_regno); 6883 return -EACCES; 6884 } 6885 err = check_packet_access(env, regno, off, size, false); 6886 if (!err && t == BPF_READ && value_regno >= 0) 6887 mark_reg_unknown(env, regs, value_regno); 6888 } else if (reg->type == PTR_TO_FLOW_KEYS) { 6889 if (t == BPF_WRITE && value_regno >= 0 && 6890 is_pointer_value(env, value_regno)) { 6891 verbose(env, "R%d leaks addr into flow keys\n", 6892 value_regno); 6893 return -EACCES; 6894 } 6895 6896 err = check_flow_keys_access(env, off, size); 6897 if (!err && t == BPF_READ && value_regno >= 0) 6898 mark_reg_unknown(env, regs, value_regno); 6899 } else if (type_is_sk_pointer(reg->type)) { 6900 if (t == BPF_WRITE) { 6901 verbose(env, "R%d cannot write into %s\n", 6902 regno, reg_type_str(env, reg->type)); 6903 return -EACCES; 6904 } 6905 err = check_sock_access(env, insn_idx, regno, off, size, t); 6906 if (!err && value_regno >= 0) 6907 mark_reg_unknown(env, regs, value_regno); 6908 } else if (reg->type == PTR_TO_TP_BUFFER) { 6909 err = check_tp_buffer_access(env, reg, regno, off, size); 6910 if (!err && t == BPF_READ && value_regno >= 0) 6911 mark_reg_unknown(env, regs, value_regno); 6912 } else if (base_type(reg->type) == PTR_TO_BTF_ID && 6913 !type_may_be_null(reg->type)) { 6914 err = check_ptr_to_btf_access(env, regs, regno, off, size, t, 6915 value_regno); 6916 } else if (reg->type == CONST_PTR_TO_MAP) { 6917 err = check_ptr_to_map_access(env, regs, regno, off, size, t, 6918 value_regno); 6919 } else if (base_type(reg->type) == PTR_TO_BUF) { 6920 bool rdonly_mem = type_is_rdonly_mem(reg->type); 6921 u32 *max_access; 6922 6923 if (rdonly_mem) { 6924 if (t == BPF_WRITE) { 6925 verbose(env, "R%d cannot write into %s\n", 6926 regno, reg_type_str(env, reg->type)); 6927 return -EACCES; 6928 } 6929 max_access = &env->prog->aux->max_rdonly_access; 6930 } else { 6931 max_access = &env->prog->aux->max_rdwr_access; 6932 } 6933 6934 err = check_buffer_access(env, reg, regno, off, size, false, 6935 max_access); 6936 6937 if (!err && value_regno >= 0 && (rdonly_mem || t == BPF_READ)) 6938 mark_reg_unknown(env, regs, value_regno); 6939 } else { 6940 verbose(env, "R%d invalid mem access '%s'\n", regno, 6941 reg_type_str(env, reg->type)); 6942 return -EACCES; 6943 } 6944 6945 if (!err && size < BPF_REG_SIZE && value_regno >= 0 && t == BPF_READ && 6946 regs[value_regno].type == SCALAR_VALUE) { 6947 if (!is_ldsx) 6948 /* b/h/w load zero-extends, mark upper bits as known 0 */ 6949 coerce_reg_to_size(®s[value_regno], size); 6950 else 6951 coerce_reg_to_size_sx(®s[value_regno], size); 6952 } 6953 return err; 6954 } 6955 6956 static int check_atomic(struct bpf_verifier_env *env, int insn_idx, struct bpf_insn *insn) 6957 { 6958 int load_reg; 6959 int err; 6960 6961 switch (insn->imm) { 6962 case BPF_ADD: 6963 case BPF_ADD | BPF_FETCH: 6964 case BPF_AND: 6965 case BPF_AND | BPF_FETCH: 6966 case BPF_OR: 6967 case BPF_OR | BPF_FETCH: 6968 case BPF_XOR: 6969 case BPF_XOR | BPF_FETCH: 6970 case BPF_XCHG: 6971 case BPF_CMPXCHG: 6972 break; 6973 default: 6974 verbose(env, "BPF_ATOMIC uses invalid atomic opcode %02x\n", insn->imm); 6975 return -EINVAL; 6976 } 6977 6978 if (BPF_SIZE(insn->code) != BPF_W && BPF_SIZE(insn->code) != BPF_DW) { 6979 verbose(env, "invalid atomic operand size\n"); 6980 return -EINVAL; 6981 } 6982 6983 /* check src1 operand */ 6984 err = check_reg_arg(env, insn->src_reg, SRC_OP); 6985 if (err) 6986 return err; 6987 6988 /* check src2 operand */ 6989 err = check_reg_arg(env, insn->dst_reg, SRC_OP); 6990 if (err) 6991 return err; 6992 6993 if (insn->imm == BPF_CMPXCHG) { 6994 /* Check comparison of R0 with memory location */ 6995 const u32 aux_reg = BPF_REG_0; 6996 6997 err = check_reg_arg(env, aux_reg, SRC_OP); 6998 if (err) 6999 return err; 7000 7001 if (is_pointer_value(env, aux_reg)) { 7002 verbose(env, "R%d leaks addr into mem\n", aux_reg); 7003 return -EACCES; 7004 } 7005 } 7006 7007 if (is_pointer_value(env, insn->src_reg)) { 7008 verbose(env, "R%d leaks addr into mem\n", insn->src_reg); 7009 return -EACCES; 7010 } 7011 7012 if (is_ctx_reg(env, insn->dst_reg) || 7013 is_pkt_reg(env, insn->dst_reg) || 7014 is_flow_key_reg(env, insn->dst_reg) || 7015 is_sk_reg(env, insn->dst_reg)) { 7016 verbose(env, "BPF_ATOMIC stores into R%d %s is not allowed\n", 7017 insn->dst_reg, 7018 reg_type_str(env, reg_state(env, insn->dst_reg)->type)); 7019 return -EACCES; 7020 } 7021 7022 if (insn->imm & BPF_FETCH) { 7023 if (insn->imm == BPF_CMPXCHG) 7024 load_reg = BPF_REG_0; 7025 else 7026 load_reg = insn->src_reg; 7027 7028 /* check and record load of old value */ 7029 err = check_reg_arg(env, load_reg, DST_OP); 7030 if (err) 7031 return err; 7032 } else { 7033 /* This instruction accesses a memory location but doesn't 7034 * actually load it into a register. 7035 */ 7036 load_reg = -1; 7037 } 7038 7039 /* Check whether we can read the memory, with second call for fetch 7040 * case to simulate the register fill. 7041 */ 7042 err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off, 7043 BPF_SIZE(insn->code), BPF_READ, -1, true, false); 7044 if (!err && load_reg >= 0) 7045 err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off, 7046 BPF_SIZE(insn->code), BPF_READ, load_reg, 7047 true, false); 7048 if (err) 7049 return err; 7050 7051 /* Check whether we can write into the same memory. */ 7052 err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off, 7053 BPF_SIZE(insn->code), BPF_WRITE, -1, true, false); 7054 if (err) 7055 return err; 7056 return 0; 7057 } 7058 7059 /* When register 'regno' is used to read the stack (either directly or through 7060 * a helper function) make sure that it's within stack boundary and, depending 7061 * on the access type and privileges, that all elements of the stack are 7062 * initialized. 7063 * 7064 * 'off' includes 'regno->off', but not its dynamic part (if any). 7065 * 7066 * All registers that have been spilled on the stack in the slots within the 7067 * read offsets are marked as read. 7068 */ 7069 static int check_stack_range_initialized( 7070 struct bpf_verifier_env *env, int regno, int off, 7071 int access_size, bool zero_size_allowed, 7072 enum bpf_access_src type, struct bpf_call_arg_meta *meta) 7073 { 7074 struct bpf_reg_state *reg = reg_state(env, regno); 7075 struct bpf_func_state *state = func(env, reg); 7076 int err, min_off, max_off, i, j, slot, spi; 7077 char *err_extra = type == ACCESS_HELPER ? " indirect" : ""; 7078 enum bpf_access_type bounds_check_type; 7079 /* Some accesses can write anything into the stack, others are 7080 * read-only. 7081 */ 7082 bool clobber = false; 7083 7084 if (access_size == 0 && !zero_size_allowed) { 7085 verbose(env, "invalid zero-sized read\n"); 7086 return -EACCES; 7087 } 7088 7089 if (type == ACCESS_HELPER) { 7090 /* The bounds checks for writes are more permissive than for 7091 * reads. However, if raw_mode is not set, we'll do extra 7092 * checks below. 7093 */ 7094 bounds_check_type = BPF_WRITE; 7095 clobber = true; 7096 } else { 7097 bounds_check_type = BPF_READ; 7098 } 7099 err = check_stack_access_within_bounds(env, regno, off, access_size, 7100 type, bounds_check_type); 7101 if (err) 7102 return err; 7103 7104 7105 if (tnum_is_const(reg->var_off)) { 7106 min_off = max_off = reg->var_off.value + off; 7107 } else { 7108 /* Variable offset is prohibited for unprivileged mode for 7109 * simplicity since it requires corresponding support in 7110 * Spectre masking for stack ALU. 7111 * See also retrieve_ptr_limit(). 7112 */ 7113 if (!env->bypass_spec_v1) { 7114 char tn_buf[48]; 7115 7116 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 7117 verbose(env, "R%d%s variable offset stack access prohibited for !root, var_off=%s\n", 7118 regno, err_extra, tn_buf); 7119 return -EACCES; 7120 } 7121 /* Only initialized buffer on stack is allowed to be accessed 7122 * with variable offset. With uninitialized buffer it's hard to 7123 * guarantee that whole memory is marked as initialized on 7124 * helper return since specific bounds are unknown what may 7125 * cause uninitialized stack leaking. 7126 */ 7127 if (meta && meta->raw_mode) 7128 meta = NULL; 7129 7130 min_off = reg->smin_value + off; 7131 max_off = reg->smax_value + off; 7132 } 7133 7134 if (meta && meta->raw_mode) { 7135 /* Ensure we won't be overwriting dynptrs when simulating byte 7136 * by byte access in check_helper_call using meta.access_size. 7137 * This would be a problem if we have a helper in the future 7138 * which takes: 7139 * 7140 * helper(uninit_mem, len, dynptr) 7141 * 7142 * Now, uninint_mem may overlap with dynptr pointer. Hence, it 7143 * may end up writing to dynptr itself when touching memory from 7144 * arg 1. This can be relaxed on a case by case basis for known 7145 * safe cases, but reject due to the possibilitiy of aliasing by 7146 * default. 7147 */ 7148 for (i = min_off; i < max_off + access_size; i++) { 7149 int stack_off = -i - 1; 7150 7151 spi = __get_spi(i); 7152 /* raw_mode may write past allocated_stack */ 7153 if (state->allocated_stack <= stack_off) 7154 continue; 7155 if (state->stack[spi].slot_type[stack_off % BPF_REG_SIZE] == STACK_DYNPTR) { 7156 verbose(env, "potential write to dynptr at off=%d disallowed\n", i); 7157 return -EACCES; 7158 } 7159 } 7160 meta->access_size = access_size; 7161 meta->regno = regno; 7162 return 0; 7163 } 7164 7165 for (i = min_off; i < max_off + access_size; i++) { 7166 u8 *stype; 7167 7168 slot = -i - 1; 7169 spi = slot / BPF_REG_SIZE; 7170 if (state->allocated_stack <= slot) { 7171 verbose(env, "verifier bug: allocated_stack too small"); 7172 return -EFAULT; 7173 } 7174 7175 stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE]; 7176 if (*stype == STACK_MISC) 7177 goto mark; 7178 if ((*stype == STACK_ZERO) || 7179 (*stype == STACK_INVALID && env->allow_uninit_stack)) { 7180 if (clobber) { 7181 /* helper can write anything into the stack */ 7182 *stype = STACK_MISC; 7183 } 7184 goto mark; 7185 } 7186 7187 if (is_spilled_reg(&state->stack[spi]) && 7188 (state->stack[spi].spilled_ptr.type == SCALAR_VALUE || 7189 env->allow_ptr_leaks)) { 7190 if (clobber) { 7191 __mark_reg_unknown(env, &state->stack[spi].spilled_ptr); 7192 for (j = 0; j < BPF_REG_SIZE; j++) 7193 scrub_spilled_slot(&state->stack[spi].slot_type[j]); 7194 } 7195 goto mark; 7196 } 7197 7198 if (tnum_is_const(reg->var_off)) { 7199 verbose(env, "invalid%s read from stack R%d off %d+%d size %d\n", 7200 err_extra, regno, min_off, i - min_off, access_size); 7201 } else { 7202 char tn_buf[48]; 7203 7204 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 7205 verbose(env, "invalid%s read from stack R%d var_off %s+%d size %d\n", 7206 err_extra, regno, tn_buf, i - min_off, access_size); 7207 } 7208 return -EACCES; 7209 mark: 7210 /* reading any byte out of 8-byte 'spill_slot' will cause 7211 * the whole slot to be marked as 'read' 7212 */ 7213 mark_reg_read(env, &state->stack[spi].spilled_ptr, 7214 state->stack[spi].spilled_ptr.parent, 7215 REG_LIVE_READ64); 7216 /* We do not set REG_LIVE_WRITTEN for stack slot, as we can not 7217 * be sure that whether stack slot is written to or not. Hence, 7218 * we must still conservatively propagate reads upwards even if 7219 * helper may write to the entire memory range. 7220 */ 7221 } 7222 return 0; 7223 } 7224 7225 static int check_helper_mem_access(struct bpf_verifier_env *env, int regno, 7226 int access_size, enum bpf_access_type access_type, 7227 bool zero_size_allowed, 7228 struct bpf_call_arg_meta *meta) 7229 { 7230 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno]; 7231 u32 *max_access; 7232 7233 switch (base_type(reg->type)) { 7234 case PTR_TO_PACKET: 7235 case PTR_TO_PACKET_META: 7236 return check_packet_access(env, regno, reg->off, access_size, 7237 zero_size_allowed); 7238 case PTR_TO_MAP_KEY: 7239 if (access_type == BPF_WRITE) { 7240 verbose(env, "R%d cannot write into %s\n", regno, 7241 reg_type_str(env, reg->type)); 7242 return -EACCES; 7243 } 7244 return check_mem_region_access(env, regno, reg->off, access_size, 7245 reg->map_ptr->key_size, false); 7246 case PTR_TO_MAP_VALUE: 7247 if (check_map_access_type(env, regno, reg->off, access_size, access_type)) 7248 return -EACCES; 7249 return check_map_access(env, regno, reg->off, access_size, 7250 zero_size_allowed, ACCESS_HELPER); 7251 case PTR_TO_MEM: 7252 if (type_is_rdonly_mem(reg->type)) { 7253 if (access_type == BPF_WRITE) { 7254 verbose(env, "R%d cannot write into %s\n", regno, 7255 reg_type_str(env, reg->type)); 7256 return -EACCES; 7257 } 7258 } 7259 return check_mem_region_access(env, regno, reg->off, 7260 access_size, reg->mem_size, 7261 zero_size_allowed); 7262 case PTR_TO_BUF: 7263 if (type_is_rdonly_mem(reg->type)) { 7264 if (access_type == BPF_WRITE) { 7265 verbose(env, "R%d cannot write into %s\n", regno, 7266 reg_type_str(env, reg->type)); 7267 return -EACCES; 7268 } 7269 7270 max_access = &env->prog->aux->max_rdonly_access; 7271 } else { 7272 max_access = &env->prog->aux->max_rdwr_access; 7273 } 7274 return check_buffer_access(env, reg, regno, reg->off, 7275 access_size, zero_size_allowed, 7276 max_access); 7277 case PTR_TO_STACK: 7278 return check_stack_range_initialized( 7279 env, 7280 regno, reg->off, access_size, 7281 zero_size_allowed, ACCESS_HELPER, meta); 7282 case PTR_TO_BTF_ID: 7283 return check_ptr_to_btf_access(env, regs, regno, reg->off, 7284 access_size, BPF_READ, -1); 7285 case PTR_TO_CTX: 7286 /* in case the function doesn't know how to access the context, 7287 * (because we are in a program of type SYSCALL for example), we 7288 * can not statically check its size. 7289 * Dynamically check it now. 7290 */ 7291 if (!env->ops->convert_ctx_access) { 7292 int offset = access_size - 1; 7293 7294 /* Allow zero-byte read from PTR_TO_CTX */ 7295 if (access_size == 0) 7296 return zero_size_allowed ? 0 : -EACCES; 7297 7298 return check_mem_access(env, env->insn_idx, regno, offset, BPF_B, 7299 access_type, -1, false, false); 7300 } 7301 7302 fallthrough; 7303 default: /* scalar_value or invalid ptr */ 7304 /* Allow zero-byte read from NULL, regardless of pointer type */ 7305 if (zero_size_allowed && access_size == 0 && 7306 register_is_null(reg)) 7307 return 0; 7308 7309 verbose(env, "R%d type=%s ", regno, 7310 reg_type_str(env, reg->type)); 7311 verbose(env, "expected=%s\n", reg_type_str(env, PTR_TO_STACK)); 7312 return -EACCES; 7313 } 7314 } 7315 7316 static int check_mem_size_reg(struct bpf_verifier_env *env, 7317 struct bpf_reg_state *reg, u32 regno, 7318 enum bpf_access_type access_type, 7319 bool zero_size_allowed, 7320 struct bpf_call_arg_meta *meta) 7321 { 7322 int err; 7323 7324 /* This is used to refine r0 return value bounds for helpers 7325 * that enforce this value as an upper bound on return values. 7326 * See do_refine_retval_range() for helpers that can refine 7327 * the return value. C type of helper is u32 so we pull register 7328 * bound from umax_value however, if negative verifier errors 7329 * out. Only upper bounds can be learned because retval is an 7330 * int type and negative retvals are allowed. 7331 */ 7332 meta->msize_max_value = reg->umax_value; 7333 7334 /* The register is SCALAR_VALUE; the access check happens using 7335 * its boundaries. For unprivileged variable accesses, disable 7336 * raw mode so that the program is required to initialize all 7337 * the memory that the helper could just partially fill up. 7338 */ 7339 if (!tnum_is_const(reg->var_off)) 7340 meta = NULL; 7341 7342 if (reg->smin_value < 0) { 7343 verbose(env, "R%d min value is negative, either use unsigned or 'var &= const'\n", 7344 regno); 7345 return -EACCES; 7346 } 7347 7348 if (reg->umin_value == 0 && !zero_size_allowed) { 7349 verbose(env, "R%d invalid zero-sized read: u64=[%lld,%lld]\n", 7350 regno, reg->umin_value, reg->umax_value); 7351 return -EACCES; 7352 } 7353 7354 if (reg->umax_value >= BPF_MAX_VAR_SIZ) { 7355 verbose(env, "R%d unbounded memory access, use 'var &= const' or 'if (var < const)'\n", 7356 regno); 7357 return -EACCES; 7358 } 7359 err = check_helper_mem_access(env, regno - 1, reg->umax_value, 7360 access_type, zero_size_allowed, meta); 7361 if (!err) 7362 err = mark_chain_precision(env, regno); 7363 return err; 7364 } 7365 7366 int check_mem_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg, 7367 u32 regno, u32 mem_size) 7368 { 7369 bool may_be_null = type_may_be_null(reg->type); 7370 struct bpf_reg_state saved_reg; 7371 int err; 7372 7373 if (register_is_null(reg)) 7374 return 0; 7375 7376 /* Assuming that the register contains a value check if the memory 7377 * access is safe. Temporarily save and restore the register's state as 7378 * the conversion shouldn't be visible to a caller. 7379 */ 7380 if (may_be_null) { 7381 saved_reg = *reg; 7382 mark_ptr_not_null_reg(reg); 7383 } 7384 7385 err = check_helper_mem_access(env, regno, mem_size, BPF_READ, true, NULL); 7386 err = err ?: check_helper_mem_access(env, regno, mem_size, BPF_WRITE, true, NULL); 7387 7388 if (may_be_null) 7389 *reg = saved_reg; 7390 7391 return err; 7392 } 7393 7394 static int check_kfunc_mem_size_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg, 7395 u32 regno) 7396 { 7397 struct bpf_reg_state *mem_reg = &cur_regs(env)[regno - 1]; 7398 bool may_be_null = type_may_be_null(mem_reg->type); 7399 struct bpf_reg_state saved_reg; 7400 struct bpf_call_arg_meta meta; 7401 int err; 7402 7403 WARN_ON_ONCE(regno < BPF_REG_2 || regno > BPF_REG_5); 7404 7405 memset(&meta, 0, sizeof(meta)); 7406 7407 if (may_be_null) { 7408 saved_reg = *mem_reg; 7409 mark_ptr_not_null_reg(mem_reg); 7410 } 7411 7412 err = check_mem_size_reg(env, reg, regno, BPF_READ, true, &meta); 7413 err = err ?: check_mem_size_reg(env, reg, regno, BPF_WRITE, true, &meta); 7414 7415 if (may_be_null) 7416 *mem_reg = saved_reg; 7417 7418 return err; 7419 } 7420 7421 /* Implementation details: 7422 * bpf_map_lookup returns PTR_TO_MAP_VALUE_OR_NULL. 7423 * bpf_obj_new returns PTR_TO_BTF_ID | MEM_ALLOC | PTR_MAYBE_NULL. 7424 * Two bpf_map_lookups (even with the same key) will have different reg->id. 7425 * Two separate bpf_obj_new will also have different reg->id. 7426 * For traditional PTR_TO_MAP_VALUE or PTR_TO_BTF_ID | MEM_ALLOC, the verifier 7427 * clears reg->id after value_or_null->value transition, since the verifier only 7428 * cares about the range of access to valid map value pointer and doesn't care 7429 * about actual address of the map element. 7430 * For maps with 'struct bpf_spin_lock' inside map value the verifier keeps 7431 * reg->id > 0 after value_or_null->value transition. By doing so 7432 * two bpf_map_lookups will be considered two different pointers that 7433 * point to different bpf_spin_locks. Likewise for pointers to allocated objects 7434 * returned from bpf_obj_new. 7435 * The verifier allows taking only one bpf_spin_lock at a time to avoid 7436 * dead-locks. 7437 * Since only one bpf_spin_lock is allowed the checks are simpler than 7438 * reg_is_refcounted() logic. The verifier needs to remember only 7439 * one spin_lock instead of array of acquired_refs. 7440 * cur_state->active_lock remembers which map value element or allocated 7441 * object got locked and clears it after bpf_spin_unlock. 7442 */ 7443 static int process_spin_lock(struct bpf_verifier_env *env, int regno, 7444 bool is_lock) 7445 { 7446 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno]; 7447 struct bpf_verifier_state *cur = env->cur_state; 7448 bool is_const = tnum_is_const(reg->var_off); 7449 u64 val = reg->var_off.value; 7450 struct bpf_map *map = NULL; 7451 struct btf *btf = NULL; 7452 struct btf_record *rec; 7453 7454 if (!is_const) { 7455 verbose(env, 7456 "R%d doesn't have constant offset. bpf_spin_lock has to be at the constant offset\n", 7457 regno); 7458 return -EINVAL; 7459 } 7460 if (reg->type == PTR_TO_MAP_VALUE) { 7461 map = reg->map_ptr; 7462 if (!map->btf) { 7463 verbose(env, 7464 "map '%s' has to have BTF in order to use bpf_spin_lock\n", 7465 map->name); 7466 return -EINVAL; 7467 } 7468 } else { 7469 btf = reg->btf; 7470 } 7471 7472 rec = reg_btf_record(reg); 7473 if (!btf_record_has_field(rec, BPF_SPIN_LOCK)) { 7474 verbose(env, "%s '%s' has no valid bpf_spin_lock\n", map ? "map" : "local", 7475 map ? map->name : "kptr"); 7476 return -EINVAL; 7477 } 7478 if (rec->spin_lock_off != val + reg->off) { 7479 verbose(env, "off %lld doesn't point to 'struct bpf_spin_lock' that is at %d\n", 7480 val + reg->off, rec->spin_lock_off); 7481 return -EINVAL; 7482 } 7483 if (is_lock) { 7484 if (cur->active_lock.ptr) { 7485 verbose(env, 7486 "Locking two bpf_spin_locks are not allowed\n"); 7487 return -EINVAL; 7488 } 7489 if (map) 7490 cur->active_lock.ptr = map; 7491 else 7492 cur->active_lock.ptr = btf; 7493 cur->active_lock.id = reg->id; 7494 } else { 7495 void *ptr; 7496 7497 if (map) 7498 ptr = map; 7499 else 7500 ptr = btf; 7501 7502 if (!cur->active_lock.ptr) { 7503 verbose(env, "bpf_spin_unlock without taking a lock\n"); 7504 return -EINVAL; 7505 } 7506 if (cur->active_lock.ptr != ptr || 7507 cur->active_lock.id != reg->id) { 7508 verbose(env, "bpf_spin_unlock of different lock\n"); 7509 return -EINVAL; 7510 } 7511 7512 invalidate_non_owning_refs(env); 7513 7514 cur->active_lock.ptr = NULL; 7515 cur->active_lock.id = 0; 7516 } 7517 return 0; 7518 } 7519 7520 static int process_timer_func(struct bpf_verifier_env *env, int regno, 7521 struct bpf_call_arg_meta *meta) 7522 { 7523 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno]; 7524 bool is_const = tnum_is_const(reg->var_off); 7525 struct bpf_map *map = reg->map_ptr; 7526 u64 val = reg->var_off.value; 7527 7528 if (!is_const) { 7529 verbose(env, 7530 "R%d doesn't have constant offset. bpf_timer has to be at the constant offset\n", 7531 regno); 7532 return -EINVAL; 7533 } 7534 if (!map->btf) { 7535 verbose(env, "map '%s' has to have BTF in order to use bpf_timer\n", 7536 map->name); 7537 return -EINVAL; 7538 } 7539 if (!btf_record_has_field(map->record, BPF_TIMER)) { 7540 verbose(env, "map '%s' has no valid bpf_timer\n", map->name); 7541 return -EINVAL; 7542 } 7543 if (map->record->timer_off != val + reg->off) { 7544 verbose(env, "off %lld doesn't point to 'struct bpf_timer' that is at %d\n", 7545 val + reg->off, map->record->timer_off); 7546 return -EINVAL; 7547 } 7548 if (meta->map_ptr) { 7549 verbose(env, "verifier bug. Two map pointers in a timer helper\n"); 7550 return -EFAULT; 7551 } 7552 meta->map_uid = reg->map_uid; 7553 meta->map_ptr = map; 7554 return 0; 7555 } 7556 7557 static int process_kptr_func(struct bpf_verifier_env *env, int regno, 7558 struct bpf_call_arg_meta *meta) 7559 { 7560 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno]; 7561 struct bpf_map *map_ptr = reg->map_ptr; 7562 struct btf_field *kptr_field; 7563 u32 kptr_off; 7564 7565 if (!tnum_is_const(reg->var_off)) { 7566 verbose(env, 7567 "R%d doesn't have constant offset. kptr has to be at the constant offset\n", 7568 regno); 7569 return -EINVAL; 7570 } 7571 if (!map_ptr->btf) { 7572 verbose(env, "map '%s' has to have BTF in order to use bpf_kptr_xchg\n", 7573 map_ptr->name); 7574 return -EINVAL; 7575 } 7576 if (!btf_record_has_field(map_ptr->record, BPF_KPTR)) { 7577 verbose(env, "map '%s' has no valid kptr\n", map_ptr->name); 7578 return -EINVAL; 7579 } 7580 7581 meta->map_ptr = map_ptr; 7582 kptr_off = reg->off + reg->var_off.value; 7583 kptr_field = btf_record_find(map_ptr->record, kptr_off, BPF_KPTR); 7584 if (!kptr_field) { 7585 verbose(env, "off=%d doesn't point to kptr\n", kptr_off); 7586 return -EACCES; 7587 } 7588 if (kptr_field->type != BPF_KPTR_REF) { 7589 verbose(env, "off=%d kptr isn't referenced kptr\n", kptr_off); 7590 return -EACCES; 7591 } 7592 meta->kptr_field = kptr_field; 7593 return 0; 7594 } 7595 7596 /* There are two register types representing a bpf_dynptr, one is PTR_TO_STACK 7597 * which points to a stack slot, and the other is CONST_PTR_TO_DYNPTR. 7598 * 7599 * In both cases we deal with the first 8 bytes, but need to mark the next 8 7600 * bytes as STACK_DYNPTR in case of PTR_TO_STACK. In case of 7601 * CONST_PTR_TO_DYNPTR, we are guaranteed to get the beginning of the object. 7602 * 7603 * Mutability of bpf_dynptr is at two levels, one is at the level of struct 7604 * bpf_dynptr itself, i.e. whether the helper is receiving a pointer to struct 7605 * bpf_dynptr or pointer to const struct bpf_dynptr. In the former case, it can 7606 * mutate the view of the dynptr and also possibly destroy it. In the latter 7607 * case, it cannot mutate the bpf_dynptr itself but it can still mutate the 7608 * memory that dynptr points to. 7609 * 7610 * The verifier will keep track both levels of mutation (bpf_dynptr's in 7611 * reg->type and the memory's in reg->dynptr.type), but there is no support for 7612 * readonly dynptr view yet, hence only the first case is tracked and checked. 7613 * 7614 * This is consistent with how C applies the const modifier to a struct object, 7615 * where the pointer itself inside bpf_dynptr becomes const but not what it 7616 * points to. 7617 * 7618 * Helpers which do not mutate the bpf_dynptr set MEM_RDONLY in their argument 7619 * type, and declare it as 'const struct bpf_dynptr *' in their prototype. 7620 */ 7621 static int process_dynptr_func(struct bpf_verifier_env *env, int regno, int insn_idx, 7622 enum bpf_arg_type arg_type, int clone_ref_obj_id) 7623 { 7624 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno]; 7625 int err; 7626 7627 /* MEM_UNINIT and MEM_RDONLY are exclusive, when applied to an 7628 * ARG_PTR_TO_DYNPTR (or ARG_PTR_TO_DYNPTR | DYNPTR_TYPE_*): 7629 */ 7630 if ((arg_type & (MEM_UNINIT | MEM_RDONLY)) == (MEM_UNINIT | MEM_RDONLY)) { 7631 verbose(env, "verifier internal error: misconfigured dynptr helper type flags\n"); 7632 return -EFAULT; 7633 } 7634 7635 /* MEM_UNINIT - Points to memory that is an appropriate candidate for 7636 * constructing a mutable bpf_dynptr object. 7637 * 7638 * Currently, this is only possible with PTR_TO_STACK 7639 * pointing to a region of at least 16 bytes which doesn't 7640 * contain an existing bpf_dynptr. 7641 * 7642 * MEM_RDONLY - Points to a initialized bpf_dynptr that will not be 7643 * mutated or destroyed. However, the memory it points to 7644 * may be mutated. 7645 * 7646 * None - Points to a initialized dynptr that can be mutated and 7647 * destroyed, including mutation of the memory it points 7648 * to. 7649 */ 7650 if (arg_type & MEM_UNINIT) { 7651 int i; 7652 7653 if (!is_dynptr_reg_valid_uninit(env, reg)) { 7654 verbose(env, "Dynptr has to be an uninitialized dynptr\n"); 7655 return -EINVAL; 7656 } 7657 7658 /* we write BPF_DW bits (8 bytes) at a time */ 7659 for (i = 0; i < BPF_DYNPTR_SIZE; i += 8) { 7660 err = check_mem_access(env, insn_idx, regno, 7661 i, BPF_DW, BPF_WRITE, -1, false, false); 7662 if (err) 7663 return err; 7664 } 7665 7666 err = mark_stack_slots_dynptr(env, reg, arg_type, insn_idx, clone_ref_obj_id); 7667 } else /* MEM_RDONLY and None case from above */ { 7668 /* For the reg->type == PTR_TO_STACK case, bpf_dynptr is never const */ 7669 if (reg->type == CONST_PTR_TO_DYNPTR && !(arg_type & MEM_RDONLY)) { 7670 verbose(env, "cannot pass pointer to const bpf_dynptr, the helper mutates it\n"); 7671 return -EINVAL; 7672 } 7673 7674 if (!is_dynptr_reg_valid_init(env, reg)) { 7675 verbose(env, 7676 "Expected an initialized dynptr as arg #%d\n", 7677 regno); 7678 return -EINVAL; 7679 } 7680 7681 /* Fold modifiers (in this case, MEM_RDONLY) when checking expected type */ 7682 if (!is_dynptr_type_expected(env, reg, arg_type & ~MEM_RDONLY)) { 7683 verbose(env, 7684 "Expected a dynptr of type %s as arg #%d\n", 7685 dynptr_type_str(arg_to_dynptr_type(arg_type)), regno); 7686 return -EINVAL; 7687 } 7688 7689 err = mark_dynptr_read(env, reg); 7690 } 7691 return err; 7692 } 7693 7694 static u32 iter_ref_obj_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg, int spi) 7695 { 7696 struct bpf_func_state *state = func(env, reg); 7697 7698 return state->stack[spi].spilled_ptr.ref_obj_id; 7699 } 7700 7701 static bool is_iter_kfunc(struct bpf_kfunc_call_arg_meta *meta) 7702 { 7703 return meta->kfunc_flags & (KF_ITER_NEW | KF_ITER_NEXT | KF_ITER_DESTROY); 7704 } 7705 7706 static bool is_iter_new_kfunc(struct bpf_kfunc_call_arg_meta *meta) 7707 { 7708 return meta->kfunc_flags & KF_ITER_NEW; 7709 } 7710 7711 static bool is_iter_next_kfunc(struct bpf_kfunc_call_arg_meta *meta) 7712 { 7713 return meta->kfunc_flags & KF_ITER_NEXT; 7714 } 7715 7716 static bool is_iter_destroy_kfunc(struct bpf_kfunc_call_arg_meta *meta) 7717 { 7718 return meta->kfunc_flags & KF_ITER_DESTROY; 7719 } 7720 7721 static bool is_kfunc_arg_iter(struct bpf_kfunc_call_arg_meta *meta, int arg) 7722 { 7723 /* btf_check_iter_kfuncs() guarantees that first argument of any iter 7724 * kfunc is iter state pointer 7725 */ 7726 return arg == 0 && is_iter_kfunc(meta); 7727 } 7728 7729 static int process_iter_arg(struct bpf_verifier_env *env, int regno, int insn_idx, 7730 struct bpf_kfunc_call_arg_meta *meta) 7731 { 7732 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno]; 7733 const struct btf_type *t; 7734 const struct btf_param *arg; 7735 int spi, err, i, nr_slots; 7736 u32 btf_id; 7737 7738 /* btf_check_iter_kfuncs() ensures we don't need to validate anything here */ 7739 arg = &btf_params(meta->func_proto)[0]; 7740 t = btf_type_skip_modifiers(meta->btf, arg->type, NULL); /* PTR */ 7741 t = btf_type_skip_modifiers(meta->btf, t->type, &btf_id); /* STRUCT */ 7742 nr_slots = t->size / BPF_REG_SIZE; 7743 7744 if (is_iter_new_kfunc(meta)) { 7745 /* bpf_iter_<type>_new() expects pointer to uninit iter state */ 7746 if (!is_iter_reg_valid_uninit(env, reg, nr_slots)) { 7747 verbose(env, "expected uninitialized iter_%s as arg #%d\n", 7748 iter_type_str(meta->btf, btf_id), regno); 7749 return -EINVAL; 7750 } 7751 7752 for (i = 0; i < nr_slots * 8; i += BPF_REG_SIZE) { 7753 err = check_mem_access(env, insn_idx, regno, 7754 i, BPF_DW, BPF_WRITE, -1, false, false); 7755 if (err) 7756 return err; 7757 } 7758 7759 err = mark_stack_slots_iter(env, reg, insn_idx, meta->btf, btf_id, nr_slots); 7760 if (err) 7761 return err; 7762 } else { 7763 /* iter_next() or iter_destroy() expect initialized iter state*/ 7764 if (!is_iter_reg_valid_init(env, reg, meta->btf, btf_id, nr_slots)) { 7765 verbose(env, "expected an initialized iter_%s as arg #%d\n", 7766 iter_type_str(meta->btf, btf_id), regno); 7767 return -EINVAL; 7768 } 7769 7770 spi = iter_get_spi(env, reg, nr_slots); 7771 if (spi < 0) 7772 return spi; 7773 7774 err = mark_iter_read(env, reg, spi, nr_slots); 7775 if (err) 7776 return err; 7777 7778 /* remember meta->iter info for process_iter_next_call() */ 7779 meta->iter.spi = spi; 7780 meta->iter.frameno = reg->frameno; 7781 meta->ref_obj_id = iter_ref_obj_id(env, reg, spi); 7782 7783 if (is_iter_destroy_kfunc(meta)) { 7784 err = unmark_stack_slots_iter(env, reg, nr_slots); 7785 if (err) 7786 return err; 7787 } 7788 } 7789 7790 return 0; 7791 } 7792 7793 /* Look for a previous loop entry at insn_idx: nearest parent state 7794 * stopped at insn_idx with callsites matching those in cur->frame. 7795 */ 7796 static struct bpf_verifier_state *find_prev_entry(struct bpf_verifier_env *env, 7797 struct bpf_verifier_state *cur, 7798 int insn_idx) 7799 { 7800 struct bpf_verifier_state_list *sl; 7801 struct bpf_verifier_state *st; 7802 7803 /* Explored states are pushed in stack order, most recent states come first */ 7804 sl = *explored_state(env, insn_idx); 7805 for (; sl; sl = sl->next) { 7806 /* If st->branches != 0 state is a part of current DFS verification path, 7807 * hence cur & st for a loop. 7808 */ 7809 st = &sl->state; 7810 if (st->insn_idx == insn_idx && st->branches && same_callsites(st, cur) && 7811 st->dfs_depth < cur->dfs_depth) 7812 return st; 7813 } 7814 7815 return NULL; 7816 } 7817 7818 static void reset_idmap_scratch(struct bpf_verifier_env *env); 7819 static bool regs_exact(const struct bpf_reg_state *rold, 7820 const struct bpf_reg_state *rcur, 7821 struct bpf_idmap *idmap); 7822 7823 static void maybe_widen_reg(struct bpf_verifier_env *env, 7824 struct bpf_reg_state *rold, struct bpf_reg_state *rcur, 7825 struct bpf_idmap *idmap) 7826 { 7827 if (rold->type != SCALAR_VALUE) 7828 return; 7829 if (rold->type != rcur->type) 7830 return; 7831 if (rold->precise || rcur->precise || regs_exact(rold, rcur, idmap)) 7832 return; 7833 __mark_reg_unknown(env, rcur); 7834 } 7835 7836 static int widen_imprecise_scalars(struct bpf_verifier_env *env, 7837 struct bpf_verifier_state *old, 7838 struct bpf_verifier_state *cur) 7839 { 7840 struct bpf_func_state *fold, *fcur; 7841 int i, fr; 7842 7843 reset_idmap_scratch(env); 7844 for (fr = old->curframe; fr >= 0; fr--) { 7845 fold = old->frame[fr]; 7846 fcur = cur->frame[fr]; 7847 7848 for (i = 0; i < MAX_BPF_REG; i++) 7849 maybe_widen_reg(env, 7850 &fold->regs[i], 7851 &fcur->regs[i], 7852 &env->idmap_scratch); 7853 7854 for (i = 0; i < fold->allocated_stack / BPF_REG_SIZE; i++) { 7855 if (!is_spilled_reg(&fold->stack[i]) || 7856 !is_spilled_reg(&fcur->stack[i])) 7857 continue; 7858 7859 maybe_widen_reg(env, 7860 &fold->stack[i].spilled_ptr, 7861 &fcur->stack[i].spilled_ptr, 7862 &env->idmap_scratch); 7863 } 7864 } 7865 return 0; 7866 } 7867 7868 static struct bpf_reg_state *get_iter_from_state(struct bpf_verifier_state *cur_st, 7869 struct bpf_kfunc_call_arg_meta *meta) 7870 { 7871 int iter_frameno = meta->iter.frameno; 7872 int iter_spi = meta->iter.spi; 7873 7874 return &cur_st->frame[iter_frameno]->stack[iter_spi].spilled_ptr; 7875 } 7876 7877 /* process_iter_next_call() is called when verifier gets to iterator's next 7878 * "method" (e.g., bpf_iter_num_next() for numbers iterator) call. We'll refer 7879 * to it as just "iter_next()" in comments below. 7880 * 7881 * BPF verifier relies on a crucial contract for any iter_next() 7882 * implementation: it should *eventually* return NULL, and once that happens 7883 * it should keep returning NULL. That is, once iterator exhausts elements to 7884 * iterate, it should never reset or spuriously return new elements. 7885 * 7886 * With the assumption of such contract, process_iter_next_call() simulates 7887 * a fork in the verifier state to validate loop logic correctness and safety 7888 * without having to simulate infinite amount of iterations. 7889 * 7890 * In current state, we first assume that iter_next() returned NULL and 7891 * iterator state is set to DRAINED (BPF_ITER_STATE_DRAINED). In such 7892 * conditions we should not form an infinite loop and should eventually reach 7893 * exit. 7894 * 7895 * Besides that, we also fork current state and enqueue it for later 7896 * verification. In a forked state we keep iterator state as ACTIVE 7897 * (BPF_ITER_STATE_ACTIVE) and assume non-NULL return from iter_next(). We 7898 * also bump iteration depth to prevent erroneous infinite loop detection 7899 * later on (see iter_active_depths_differ() comment for details). In this 7900 * state we assume that we'll eventually loop back to another iter_next() 7901 * calls (it could be in exactly same location or in some other instruction, 7902 * it doesn't matter, we don't make any unnecessary assumptions about this, 7903 * everything revolves around iterator state in a stack slot, not which 7904 * instruction is calling iter_next()). When that happens, we either will come 7905 * to iter_next() with equivalent state and can conclude that next iteration 7906 * will proceed in exactly the same way as we just verified, so it's safe to 7907 * assume that loop converges. If not, we'll go on another iteration 7908 * simulation with a different input state, until all possible starting states 7909 * are validated or we reach maximum number of instructions limit. 7910 * 7911 * This way, we will either exhaustively discover all possible input states 7912 * that iterator loop can start with and eventually will converge, or we'll 7913 * effectively regress into bounded loop simulation logic and either reach 7914 * maximum number of instructions if loop is not provably convergent, or there 7915 * is some statically known limit on number of iterations (e.g., if there is 7916 * an explicit `if n > 100 then break;` statement somewhere in the loop). 7917 * 7918 * Iteration convergence logic in is_state_visited() relies on exact 7919 * states comparison, which ignores read and precision marks. 7920 * This is necessary because read and precision marks are not finalized 7921 * while in the loop. Exact comparison might preclude convergence for 7922 * simple programs like below: 7923 * 7924 * i = 0; 7925 * while(iter_next(&it)) 7926 * i++; 7927 * 7928 * At each iteration step i++ would produce a new distinct state and 7929 * eventually instruction processing limit would be reached. 7930 * 7931 * To avoid such behavior speculatively forget (widen) range for 7932 * imprecise scalar registers, if those registers were not precise at the 7933 * end of the previous iteration and do not match exactly. 7934 * 7935 * This is a conservative heuristic that allows to verify wide range of programs, 7936 * however it precludes verification of programs that conjure an 7937 * imprecise value on the first loop iteration and use it as precise on a second. 7938 * For example, the following safe program would fail to verify: 7939 * 7940 * struct bpf_num_iter it; 7941 * int arr[10]; 7942 * int i = 0, a = 0; 7943 * bpf_iter_num_new(&it, 0, 10); 7944 * while (bpf_iter_num_next(&it)) { 7945 * if (a == 0) { 7946 * a = 1; 7947 * i = 7; // Because i changed verifier would forget 7948 * // it's range on second loop entry. 7949 * } else { 7950 * arr[i] = 42; // This would fail to verify. 7951 * } 7952 * } 7953 * bpf_iter_num_destroy(&it); 7954 */ 7955 static int process_iter_next_call(struct bpf_verifier_env *env, int insn_idx, 7956 struct bpf_kfunc_call_arg_meta *meta) 7957 { 7958 struct bpf_verifier_state *cur_st = env->cur_state, *queued_st, *prev_st; 7959 struct bpf_func_state *cur_fr = cur_st->frame[cur_st->curframe], *queued_fr; 7960 struct bpf_reg_state *cur_iter, *queued_iter; 7961 7962 BTF_TYPE_EMIT(struct bpf_iter); 7963 7964 cur_iter = get_iter_from_state(cur_st, meta); 7965 7966 if (cur_iter->iter.state != BPF_ITER_STATE_ACTIVE && 7967 cur_iter->iter.state != BPF_ITER_STATE_DRAINED) { 7968 verbose(env, "verifier internal error: unexpected iterator state %d (%s)\n", 7969 cur_iter->iter.state, iter_state_str(cur_iter->iter.state)); 7970 return -EFAULT; 7971 } 7972 7973 if (cur_iter->iter.state == BPF_ITER_STATE_ACTIVE) { 7974 /* Because iter_next() call is a checkpoint is_state_visitied() 7975 * should guarantee parent state with same call sites and insn_idx. 7976 */ 7977 if (!cur_st->parent || cur_st->parent->insn_idx != insn_idx || 7978 !same_callsites(cur_st->parent, cur_st)) { 7979 verbose(env, "bug: bad parent state for iter next call"); 7980 return -EFAULT; 7981 } 7982 /* Note cur_st->parent in the call below, it is necessary to skip 7983 * checkpoint created for cur_st by is_state_visited() 7984 * right at this instruction. 7985 */ 7986 prev_st = find_prev_entry(env, cur_st->parent, insn_idx); 7987 /* branch out active iter state */ 7988 queued_st = push_stack(env, insn_idx + 1, insn_idx, false); 7989 if (!queued_st) 7990 return -ENOMEM; 7991 7992 queued_iter = get_iter_from_state(queued_st, meta); 7993 queued_iter->iter.state = BPF_ITER_STATE_ACTIVE; 7994 queued_iter->iter.depth++; 7995 if (prev_st) 7996 widen_imprecise_scalars(env, prev_st, queued_st); 7997 7998 queued_fr = queued_st->frame[queued_st->curframe]; 7999 mark_ptr_not_null_reg(&queued_fr->regs[BPF_REG_0]); 8000 } 8001 8002 /* switch to DRAINED state, but keep the depth unchanged */ 8003 /* mark current iter state as drained and assume returned NULL */ 8004 cur_iter->iter.state = BPF_ITER_STATE_DRAINED; 8005 __mark_reg_const_zero(&cur_fr->regs[BPF_REG_0]); 8006 8007 return 0; 8008 } 8009 8010 static bool arg_type_is_mem_size(enum bpf_arg_type type) 8011 { 8012 return type == ARG_CONST_SIZE || 8013 type == ARG_CONST_SIZE_OR_ZERO; 8014 } 8015 8016 static bool arg_type_is_raw_mem(enum bpf_arg_type type) 8017 { 8018 return base_type(type) == ARG_PTR_TO_MEM && 8019 type & MEM_UNINIT; 8020 } 8021 8022 static bool arg_type_is_release(enum bpf_arg_type type) 8023 { 8024 return type & OBJ_RELEASE; 8025 } 8026 8027 static bool arg_type_is_dynptr(enum bpf_arg_type type) 8028 { 8029 return base_type(type) == ARG_PTR_TO_DYNPTR; 8030 } 8031 8032 static int resolve_map_arg_type(struct bpf_verifier_env *env, 8033 const struct bpf_call_arg_meta *meta, 8034 enum bpf_arg_type *arg_type) 8035 { 8036 if (!meta->map_ptr) { 8037 /* kernel subsystem misconfigured verifier */ 8038 verbose(env, "invalid map_ptr to access map->type\n"); 8039 return -EACCES; 8040 } 8041 8042 switch (meta->map_ptr->map_type) { 8043 case BPF_MAP_TYPE_SOCKMAP: 8044 case BPF_MAP_TYPE_SOCKHASH: 8045 if (*arg_type == ARG_PTR_TO_MAP_VALUE) { 8046 *arg_type = ARG_PTR_TO_BTF_ID_SOCK_COMMON; 8047 } else { 8048 verbose(env, "invalid arg_type for sockmap/sockhash\n"); 8049 return -EINVAL; 8050 } 8051 break; 8052 case BPF_MAP_TYPE_BLOOM_FILTER: 8053 if (meta->func_id == BPF_FUNC_map_peek_elem) 8054 *arg_type = ARG_PTR_TO_MAP_VALUE; 8055 break; 8056 default: 8057 break; 8058 } 8059 return 0; 8060 } 8061 8062 struct bpf_reg_types { 8063 const enum bpf_reg_type types[10]; 8064 u32 *btf_id; 8065 }; 8066 8067 static const struct bpf_reg_types sock_types = { 8068 .types = { 8069 PTR_TO_SOCK_COMMON, 8070 PTR_TO_SOCKET, 8071 PTR_TO_TCP_SOCK, 8072 PTR_TO_XDP_SOCK, 8073 }, 8074 }; 8075 8076 #ifdef CONFIG_NET 8077 static const struct bpf_reg_types btf_id_sock_common_types = { 8078 .types = { 8079 PTR_TO_SOCK_COMMON, 8080 PTR_TO_SOCKET, 8081 PTR_TO_TCP_SOCK, 8082 PTR_TO_XDP_SOCK, 8083 PTR_TO_BTF_ID, 8084 PTR_TO_BTF_ID | PTR_TRUSTED, 8085 }, 8086 .btf_id = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON], 8087 }; 8088 #endif 8089 8090 static const struct bpf_reg_types mem_types = { 8091 .types = { 8092 PTR_TO_STACK, 8093 PTR_TO_PACKET, 8094 PTR_TO_PACKET_META, 8095 PTR_TO_MAP_KEY, 8096 PTR_TO_MAP_VALUE, 8097 PTR_TO_MEM, 8098 PTR_TO_MEM | MEM_RINGBUF, 8099 PTR_TO_BUF, 8100 PTR_TO_BTF_ID | PTR_TRUSTED, 8101 }, 8102 }; 8103 8104 static const struct bpf_reg_types spin_lock_types = { 8105 .types = { 8106 PTR_TO_MAP_VALUE, 8107 PTR_TO_BTF_ID | MEM_ALLOC, 8108 } 8109 }; 8110 8111 static const struct bpf_reg_types fullsock_types = { .types = { PTR_TO_SOCKET } }; 8112 static const struct bpf_reg_types scalar_types = { .types = { SCALAR_VALUE } }; 8113 static const struct bpf_reg_types context_types = { .types = { PTR_TO_CTX } }; 8114 static const struct bpf_reg_types ringbuf_mem_types = { .types = { PTR_TO_MEM | MEM_RINGBUF } }; 8115 static const struct bpf_reg_types const_map_ptr_types = { .types = { CONST_PTR_TO_MAP } }; 8116 static const struct bpf_reg_types btf_ptr_types = { 8117 .types = { 8118 PTR_TO_BTF_ID, 8119 PTR_TO_BTF_ID | PTR_TRUSTED, 8120 PTR_TO_BTF_ID | MEM_RCU, 8121 }, 8122 }; 8123 static const struct bpf_reg_types percpu_btf_ptr_types = { 8124 .types = { 8125 PTR_TO_BTF_ID | MEM_PERCPU, 8126 PTR_TO_BTF_ID | MEM_PERCPU | PTR_TRUSTED, 8127 } 8128 }; 8129 static const struct bpf_reg_types func_ptr_types = { .types = { PTR_TO_FUNC } }; 8130 static const struct bpf_reg_types stack_ptr_types = { .types = { PTR_TO_STACK } }; 8131 static const struct bpf_reg_types const_str_ptr_types = { .types = { PTR_TO_MAP_VALUE } }; 8132 static const struct bpf_reg_types timer_types = { .types = { PTR_TO_MAP_VALUE } }; 8133 static const struct bpf_reg_types kptr_types = { .types = { PTR_TO_MAP_VALUE } }; 8134 static const struct bpf_reg_types dynptr_types = { 8135 .types = { 8136 PTR_TO_STACK, 8137 CONST_PTR_TO_DYNPTR, 8138 } 8139 }; 8140 8141 static const struct bpf_reg_types *compatible_reg_types[__BPF_ARG_TYPE_MAX] = { 8142 [ARG_PTR_TO_MAP_KEY] = &mem_types, 8143 [ARG_PTR_TO_MAP_VALUE] = &mem_types, 8144 [ARG_CONST_SIZE] = &scalar_types, 8145 [ARG_CONST_SIZE_OR_ZERO] = &scalar_types, 8146 [ARG_CONST_ALLOC_SIZE_OR_ZERO] = &scalar_types, 8147 [ARG_CONST_MAP_PTR] = &const_map_ptr_types, 8148 [ARG_PTR_TO_CTX] = &context_types, 8149 [ARG_PTR_TO_SOCK_COMMON] = &sock_types, 8150 #ifdef CONFIG_NET 8151 [ARG_PTR_TO_BTF_ID_SOCK_COMMON] = &btf_id_sock_common_types, 8152 #endif 8153 [ARG_PTR_TO_SOCKET] = &fullsock_types, 8154 [ARG_PTR_TO_BTF_ID] = &btf_ptr_types, 8155 [ARG_PTR_TO_SPIN_LOCK] = &spin_lock_types, 8156 [ARG_PTR_TO_MEM] = &mem_types, 8157 [ARG_PTR_TO_RINGBUF_MEM] = &ringbuf_mem_types, 8158 [ARG_PTR_TO_PERCPU_BTF_ID] = &percpu_btf_ptr_types, 8159 [ARG_PTR_TO_FUNC] = &func_ptr_types, 8160 [ARG_PTR_TO_STACK] = &stack_ptr_types, 8161 [ARG_PTR_TO_CONST_STR] = &const_str_ptr_types, 8162 [ARG_PTR_TO_TIMER] = &timer_types, 8163 [ARG_PTR_TO_KPTR] = &kptr_types, 8164 [ARG_PTR_TO_DYNPTR] = &dynptr_types, 8165 }; 8166 8167 static int check_reg_type(struct bpf_verifier_env *env, u32 regno, 8168 enum bpf_arg_type arg_type, 8169 const u32 *arg_btf_id, 8170 struct bpf_call_arg_meta *meta) 8171 { 8172 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno]; 8173 enum bpf_reg_type expected, type = reg->type; 8174 const struct bpf_reg_types *compatible; 8175 int i, j; 8176 8177 compatible = compatible_reg_types[base_type(arg_type)]; 8178 if (!compatible) { 8179 verbose(env, "verifier internal error: unsupported arg type %d\n", arg_type); 8180 return -EFAULT; 8181 } 8182 8183 /* ARG_PTR_TO_MEM + RDONLY is compatible with PTR_TO_MEM and PTR_TO_MEM + RDONLY, 8184 * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM and NOT with PTR_TO_MEM + RDONLY 8185 * 8186 * Same for MAYBE_NULL: 8187 * 8188 * ARG_PTR_TO_MEM + MAYBE_NULL is compatible with PTR_TO_MEM and PTR_TO_MEM + MAYBE_NULL, 8189 * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM but NOT with PTR_TO_MEM + MAYBE_NULL 8190 * 8191 * ARG_PTR_TO_MEM is compatible with PTR_TO_MEM that is tagged with a dynptr type. 8192 * 8193 * Therefore we fold these flags depending on the arg_type before comparison. 8194 */ 8195 if (arg_type & MEM_RDONLY) 8196 type &= ~MEM_RDONLY; 8197 if (arg_type & PTR_MAYBE_NULL) 8198 type &= ~PTR_MAYBE_NULL; 8199 if (base_type(arg_type) == ARG_PTR_TO_MEM) 8200 type &= ~DYNPTR_TYPE_FLAG_MASK; 8201 8202 if (meta->func_id == BPF_FUNC_kptr_xchg && type_is_alloc(type)) 8203 type &= ~MEM_ALLOC; 8204 8205 for (i = 0; i < ARRAY_SIZE(compatible->types); i++) { 8206 expected = compatible->types[i]; 8207 if (expected == NOT_INIT) 8208 break; 8209 8210 if (type == expected) 8211 goto found; 8212 } 8213 8214 verbose(env, "R%d type=%s expected=", regno, reg_type_str(env, reg->type)); 8215 for (j = 0; j + 1 < i; j++) 8216 verbose(env, "%s, ", reg_type_str(env, compatible->types[j])); 8217 verbose(env, "%s\n", reg_type_str(env, compatible->types[j])); 8218 return -EACCES; 8219 8220 found: 8221 if (base_type(reg->type) != PTR_TO_BTF_ID) 8222 return 0; 8223 8224 if (compatible == &mem_types) { 8225 if (!(arg_type & MEM_RDONLY)) { 8226 verbose(env, 8227 "%s() may write into memory pointed by R%d type=%s\n", 8228 func_id_name(meta->func_id), 8229 regno, reg_type_str(env, reg->type)); 8230 return -EACCES; 8231 } 8232 return 0; 8233 } 8234 8235 switch ((int)reg->type) { 8236 case PTR_TO_BTF_ID: 8237 case PTR_TO_BTF_ID | PTR_TRUSTED: 8238 case PTR_TO_BTF_ID | MEM_RCU: 8239 case PTR_TO_BTF_ID | PTR_MAYBE_NULL: 8240 case PTR_TO_BTF_ID | PTR_MAYBE_NULL | MEM_RCU: 8241 { 8242 /* For bpf_sk_release, it needs to match against first member 8243 * 'struct sock_common', hence make an exception for it. This 8244 * allows bpf_sk_release to work for multiple socket types. 8245 */ 8246 bool strict_type_match = arg_type_is_release(arg_type) && 8247 meta->func_id != BPF_FUNC_sk_release; 8248 8249 if (type_may_be_null(reg->type) && 8250 (!type_may_be_null(arg_type) || arg_type_is_release(arg_type))) { 8251 verbose(env, "Possibly NULL pointer passed to helper arg%d\n", regno); 8252 return -EACCES; 8253 } 8254 8255 if (!arg_btf_id) { 8256 if (!compatible->btf_id) { 8257 verbose(env, "verifier internal error: missing arg compatible BTF ID\n"); 8258 return -EFAULT; 8259 } 8260 arg_btf_id = compatible->btf_id; 8261 } 8262 8263 if (meta->func_id == BPF_FUNC_kptr_xchg) { 8264 if (map_kptr_match_type(env, meta->kptr_field, reg, regno)) 8265 return -EACCES; 8266 } else { 8267 if (arg_btf_id == BPF_PTR_POISON) { 8268 verbose(env, "verifier internal error:"); 8269 verbose(env, "R%d has non-overwritten BPF_PTR_POISON type\n", 8270 regno); 8271 return -EACCES; 8272 } 8273 8274 if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off, 8275 btf_vmlinux, *arg_btf_id, 8276 strict_type_match)) { 8277 verbose(env, "R%d is of type %s but %s is expected\n", 8278 regno, btf_type_name(reg->btf, reg->btf_id), 8279 btf_type_name(btf_vmlinux, *arg_btf_id)); 8280 return -EACCES; 8281 } 8282 } 8283 break; 8284 } 8285 case PTR_TO_BTF_ID | MEM_ALLOC: 8286 if (meta->func_id != BPF_FUNC_spin_lock && meta->func_id != BPF_FUNC_spin_unlock && 8287 meta->func_id != BPF_FUNC_kptr_xchg) { 8288 verbose(env, "verifier internal error: unimplemented handling of MEM_ALLOC\n"); 8289 return -EFAULT; 8290 } 8291 if (meta->func_id == BPF_FUNC_kptr_xchg) { 8292 if (map_kptr_match_type(env, meta->kptr_field, reg, regno)) 8293 return -EACCES; 8294 } 8295 break; 8296 case PTR_TO_BTF_ID | MEM_PERCPU: 8297 case PTR_TO_BTF_ID | MEM_PERCPU | PTR_TRUSTED: 8298 /* Handled by helper specific checks */ 8299 break; 8300 default: 8301 verbose(env, "verifier internal error: invalid PTR_TO_BTF_ID register for type match\n"); 8302 return -EFAULT; 8303 } 8304 return 0; 8305 } 8306 8307 static struct btf_field * 8308 reg_find_field_offset(const struct bpf_reg_state *reg, s32 off, u32 fields) 8309 { 8310 struct btf_field *field; 8311 struct btf_record *rec; 8312 8313 rec = reg_btf_record(reg); 8314 if (!rec) 8315 return NULL; 8316 8317 field = btf_record_find(rec, off, fields); 8318 if (!field) 8319 return NULL; 8320 8321 return field; 8322 } 8323 8324 int check_func_arg_reg_off(struct bpf_verifier_env *env, 8325 const struct bpf_reg_state *reg, int regno, 8326 enum bpf_arg_type arg_type) 8327 { 8328 u32 type = reg->type; 8329 8330 /* When referenced register is passed to release function, its fixed 8331 * offset must be 0. 8332 * 8333 * We will check arg_type_is_release reg has ref_obj_id when storing 8334 * meta->release_regno. 8335 */ 8336 if (arg_type_is_release(arg_type)) { 8337 /* ARG_PTR_TO_DYNPTR with OBJ_RELEASE is a bit special, as it 8338 * may not directly point to the object being released, but to 8339 * dynptr pointing to such object, which might be at some offset 8340 * on the stack. In that case, we simply to fallback to the 8341 * default handling. 8342 */ 8343 if (arg_type_is_dynptr(arg_type) && type == PTR_TO_STACK) 8344 return 0; 8345 8346 /* Doing check_ptr_off_reg check for the offset will catch this 8347 * because fixed_off_ok is false, but checking here allows us 8348 * to give the user a better error message. 8349 */ 8350 if (reg->off) { 8351 verbose(env, "R%d must have zero offset when passed to release func or trusted arg to kfunc\n", 8352 regno); 8353 return -EINVAL; 8354 } 8355 return __check_ptr_off_reg(env, reg, regno, false); 8356 } 8357 8358 switch (type) { 8359 /* Pointer types where both fixed and variable offset is explicitly allowed: */ 8360 case PTR_TO_STACK: 8361 case PTR_TO_PACKET: 8362 case PTR_TO_PACKET_META: 8363 case PTR_TO_MAP_KEY: 8364 case PTR_TO_MAP_VALUE: 8365 case PTR_TO_MEM: 8366 case PTR_TO_MEM | MEM_RDONLY: 8367 case PTR_TO_MEM | MEM_RINGBUF: 8368 case PTR_TO_BUF: 8369 case PTR_TO_BUF | MEM_RDONLY: 8370 case SCALAR_VALUE: 8371 return 0; 8372 /* All the rest must be rejected, except PTR_TO_BTF_ID which allows 8373 * fixed offset. 8374 */ 8375 case PTR_TO_BTF_ID: 8376 case PTR_TO_BTF_ID | MEM_ALLOC: 8377 case PTR_TO_BTF_ID | PTR_TRUSTED: 8378 case PTR_TO_BTF_ID | MEM_RCU: 8379 case PTR_TO_BTF_ID | MEM_ALLOC | NON_OWN_REF: 8380 case PTR_TO_BTF_ID | MEM_ALLOC | NON_OWN_REF | MEM_RCU: 8381 /* When referenced PTR_TO_BTF_ID is passed to release function, 8382 * its fixed offset must be 0. In the other cases, fixed offset 8383 * can be non-zero. This was already checked above. So pass 8384 * fixed_off_ok as true to allow fixed offset for all other 8385 * cases. var_off always must be 0 for PTR_TO_BTF_ID, hence we 8386 * still need to do checks instead of returning. 8387 */ 8388 return __check_ptr_off_reg(env, reg, regno, true); 8389 default: 8390 return __check_ptr_off_reg(env, reg, regno, false); 8391 } 8392 } 8393 8394 static struct bpf_reg_state *get_dynptr_arg_reg(struct bpf_verifier_env *env, 8395 const struct bpf_func_proto *fn, 8396 struct bpf_reg_state *regs) 8397 { 8398 struct bpf_reg_state *state = NULL; 8399 int i; 8400 8401 for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++) 8402 if (arg_type_is_dynptr(fn->arg_type[i])) { 8403 if (state) { 8404 verbose(env, "verifier internal error: multiple dynptr args\n"); 8405 return NULL; 8406 } 8407 state = ®s[BPF_REG_1 + i]; 8408 } 8409 8410 if (!state) 8411 verbose(env, "verifier internal error: no dynptr arg found\n"); 8412 8413 return state; 8414 } 8415 8416 static int dynptr_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 8417 { 8418 struct bpf_func_state *state = func(env, reg); 8419 int spi; 8420 8421 if (reg->type == CONST_PTR_TO_DYNPTR) 8422 return reg->id; 8423 spi = dynptr_get_spi(env, reg); 8424 if (spi < 0) 8425 return spi; 8426 return state->stack[spi].spilled_ptr.id; 8427 } 8428 8429 static int dynptr_ref_obj_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 8430 { 8431 struct bpf_func_state *state = func(env, reg); 8432 int spi; 8433 8434 if (reg->type == CONST_PTR_TO_DYNPTR) 8435 return reg->ref_obj_id; 8436 spi = dynptr_get_spi(env, reg); 8437 if (spi < 0) 8438 return spi; 8439 return state->stack[spi].spilled_ptr.ref_obj_id; 8440 } 8441 8442 static enum bpf_dynptr_type dynptr_get_type(struct bpf_verifier_env *env, 8443 struct bpf_reg_state *reg) 8444 { 8445 struct bpf_func_state *state = func(env, reg); 8446 int spi; 8447 8448 if (reg->type == CONST_PTR_TO_DYNPTR) 8449 return reg->dynptr.type; 8450 8451 spi = __get_spi(reg->off); 8452 if (spi < 0) { 8453 verbose(env, "verifier internal error: invalid spi when querying dynptr type\n"); 8454 return BPF_DYNPTR_TYPE_INVALID; 8455 } 8456 8457 return state->stack[spi].spilled_ptr.dynptr.type; 8458 } 8459 8460 static int check_func_arg(struct bpf_verifier_env *env, u32 arg, 8461 struct bpf_call_arg_meta *meta, 8462 const struct bpf_func_proto *fn, 8463 int insn_idx) 8464 { 8465 u32 regno = BPF_REG_1 + arg; 8466 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno]; 8467 enum bpf_arg_type arg_type = fn->arg_type[arg]; 8468 enum bpf_reg_type type = reg->type; 8469 u32 *arg_btf_id = NULL; 8470 int err = 0; 8471 8472 if (arg_type == ARG_DONTCARE) 8473 return 0; 8474 8475 err = check_reg_arg(env, regno, SRC_OP); 8476 if (err) 8477 return err; 8478 8479 if (arg_type == ARG_ANYTHING) { 8480 if (is_pointer_value(env, regno)) { 8481 verbose(env, "R%d leaks addr into helper function\n", 8482 regno); 8483 return -EACCES; 8484 } 8485 return 0; 8486 } 8487 8488 if (type_is_pkt_pointer(type) && 8489 !may_access_direct_pkt_data(env, meta, BPF_READ)) { 8490 verbose(env, "helper access to the packet is not allowed\n"); 8491 return -EACCES; 8492 } 8493 8494 if (base_type(arg_type) == ARG_PTR_TO_MAP_VALUE) { 8495 err = resolve_map_arg_type(env, meta, &arg_type); 8496 if (err) 8497 return err; 8498 } 8499 8500 if (register_is_null(reg) && type_may_be_null(arg_type)) 8501 /* A NULL register has a SCALAR_VALUE type, so skip 8502 * type checking. 8503 */ 8504 goto skip_type_check; 8505 8506 /* arg_btf_id and arg_size are in a union. */ 8507 if (base_type(arg_type) == ARG_PTR_TO_BTF_ID || 8508 base_type(arg_type) == ARG_PTR_TO_SPIN_LOCK) 8509 arg_btf_id = fn->arg_btf_id[arg]; 8510 8511 err = check_reg_type(env, regno, arg_type, arg_btf_id, meta); 8512 if (err) 8513 return err; 8514 8515 err = check_func_arg_reg_off(env, reg, regno, arg_type); 8516 if (err) 8517 return err; 8518 8519 skip_type_check: 8520 if (arg_type_is_release(arg_type)) { 8521 if (arg_type_is_dynptr(arg_type)) { 8522 struct bpf_func_state *state = func(env, reg); 8523 int spi; 8524 8525 /* Only dynptr created on stack can be released, thus 8526 * the get_spi and stack state checks for spilled_ptr 8527 * should only be done before process_dynptr_func for 8528 * PTR_TO_STACK. 8529 */ 8530 if (reg->type == PTR_TO_STACK) { 8531 spi = dynptr_get_spi(env, reg); 8532 if (spi < 0 || !state->stack[spi].spilled_ptr.ref_obj_id) { 8533 verbose(env, "arg %d is an unacquired reference\n", regno); 8534 return -EINVAL; 8535 } 8536 } else { 8537 verbose(env, "cannot release unowned const bpf_dynptr\n"); 8538 return -EINVAL; 8539 } 8540 } else if (!reg->ref_obj_id && !register_is_null(reg)) { 8541 verbose(env, "R%d must be referenced when passed to release function\n", 8542 regno); 8543 return -EINVAL; 8544 } 8545 if (meta->release_regno) { 8546 verbose(env, "verifier internal error: more than one release argument\n"); 8547 return -EFAULT; 8548 } 8549 meta->release_regno = regno; 8550 } 8551 8552 if (reg->ref_obj_id) { 8553 if (meta->ref_obj_id) { 8554 verbose(env, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n", 8555 regno, reg->ref_obj_id, 8556 meta->ref_obj_id); 8557 return -EFAULT; 8558 } 8559 meta->ref_obj_id = reg->ref_obj_id; 8560 } 8561 8562 switch (base_type(arg_type)) { 8563 case ARG_CONST_MAP_PTR: 8564 /* bpf_map_xxx(map_ptr) call: remember that map_ptr */ 8565 if (meta->map_ptr) { 8566 /* Use map_uid (which is unique id of inner map) to reject: 8567 * inner_map1 = bpf_map_lookup_elem(outer_map, key1) 8568 * inner_map2 = bpf_map_lookup_elem(outer_map, key2) 8569 * if (inner_map1 && inner_map2) { 8570 * timer = bpf_map_lookup_elem(inner_map1); 8571 * if (timer) 8572 * // mismatch would have been allowed 8573 * bpf_timer_init(timer, inner_map2); 8574 * } 8575 * 8576 * Comparing map_ptr is enough to distinguish normal and outer maps. 8577 */ 8578 if (meta->map_ptr != reg->map_ptr || 8579 meta->map_uid != reg->map_uid) { 8580 verbose(env, 8581 "timer pointer in R1 map_uid=%d doesn't match map pointer in R2 map_uid=%d\n", 8582 meta->map_uid, reg->map_uid); 8583 return -EINVAL; 8584 } 8585 } 8586 meta->map_ptr = reg->map_ptr; 8587 meta->map_uid = reg->map_uid; 8588 break; 8589 case ARG_PTR_TO_MAP_KEY: 8590 /* bpf_map_xxx(..., map_ptr, ..., key) call: 8591 * check that [key, key + map->key_size) are within 8592 * stack limits and initialized 8593 */ 8594 if (!meta->map_ptr) { 8595 /* in function declaration map_ptr must come before 8596 * map_key, so that it's verified and known before 8597 * we have to check map_key here. Otherwise it means 8598 * that kernel subsystem misconfigured verifier 8599 */ 8600 verbose(env, "invalid map_ptr to access map->key\n"); 8601 return -EACCES; 8602 } 8603 err = check_helper_mem_access(env, regno, meta->map_ptr->key_size, 8604 BPF_READ, false, NULL); 8605 break; 8606 case ARG_PTR_TO_MAP_VALUE: 8607 if (type_may_be_null(arg_type) && register_is_null(reg)) 8608 return 0; 8609 8610 /* bpf_map_xxx(..., map_ptr, ..., value) call: 8611 * check [value, value + map->value_size) validity 8612 */ 8613 if (!meta->map_ptr) { 8614 /* kernel subsystem misconfigured verifier */ 8615 verbose(env, "invalid map_ptr to access map->value\n"); 8616 return -EACCES; 8617 } 8618 meta->raw_mode = arg_type & MEM_UNINIT; 8619 err = check_helper_mem_access(env, regno, meta->map_ptr->value_size, 8620 arg_type & MEM_WRITE ? BPF_WRITE : BPF_READ, 8621 false, meta); 8622 break; 8623 case ARG_PTR_TO_PERCPU_BTF_ID: 8624 if (!reg->btf_id) { 8625 verbose(env, "Helper has invalid btf_id in R%d\n", regno); 8626 return -EACCES; 8627 } 8628 meta->ret_btf = reg->btf; 8629 meta->ret_btf_id = reg->btf_id; 8630 break; 8631 case ARG_PTR_TO_SPIN_LOCK: 8632 if (in_rbtree_lock_required_cb(env)) { 8633 verbose(env, "can't spin_{lock,unlock} in rbtree cb\n"); 8634 return -EACCES; 8635 } 8636 if (meta->func_id == BPF_FUNC_spin_lock) { 8637 err = process_spin_lock(env, regno, true); 8638 if (err) 8639 return err; 8640 } else if (meta->func_id == BPF_FUNC_spin_unlock) { 8641 err = process_spin_lock(env, regno, false); 8642 if (err) 8643 return err; 8644 } else { 8645 verbose(env, "verifier internal error\n"); 8646 return -EFAULT; 8647 } 8648 break; 8649 case ARG_PTR_TO_TIMER: 8650 err = process_timer_func(env, regno, meta); 8651 if (err) 8652 return err; 8653 break; 8654 case ARG_PTR_TO_FUNC: 8655 meta->subprogno = reg->subprogno; 8656 break; 8657 case ARG_PTR_TO_MEM: 8658 /* The access to this pointer is only checked when we hit the 8659 * next is_mem_size argument below. 8660 */ 8661 meta->raw_mode = arg_type & MEM_UNINIT; 8662 if (arg_type & MEM_FIXED_SIZE) { 8663 err = check_helper_mem_access(env, regno, fn->arg_size[arg], 8664 arg_type & MEM_WRITE ? BPF_WRITE : BPF_READ, 8665 false, meta); 8666 if (err) 8667 return err; 8668 if (arg_type & MEM_ALIGNED) 8669 err = check_ptr_alignment(env, reg, 0, fn->arg_size[arg], true); 8670 } 8671 break; 8672 case ARG_CONST_SIZE: 8673 err = check_mem_size_reg(env, reg, regno, 8674 fn->arg_type[arg - 1] & MEM_WRITE ? 8675 BPF_WRITE : BPF_READ, 8676 false, meta); 8677 break; 8678 case ARG_CONST_SIZE_OR_ZERO: 8679 err = check_mem_size_reg(env, reg, regno, 8680 fn->arg_type[arg - 1] & MEM_WRITE ? 8681 BPF_WRITE : BPF_READ, 8682 true, meta); 8683 break; 8684 case ARG_PTR_TO_DYNPTR: 8685 err = process_dynptr_func(env, regno, insn_idx, arg_type, 0); 8686 if (err) 8687 return err; 8688 break; 8689 case ARG_CONST_ALLOC_SIZE_OR_ZERO: 8690 if (!tnum_is_const(reg->var_off)) { 8691 verbose(env, "R%d is not a known constant'\n", 8692 regno); 8693 return -EACCES; 8694 } 8695 meta->mem_size = reg->var_off.value; 8696 err = mark_chain_precision(env, regno); 8697 if (err) 8698 return err; 8699 break; 8700 case ARG_PTR_TO_CONST_STR: 8701 { 8702 struct bpf_map *map = reg->map_ptr; 8703 int map_off; 8704 u64 map_addr; 8705 char *str_ptr; 8706 8707 if (!bpf_map_is_rdonly(map)) { 8708 verbose(env, "R%d does not point to a readonly map'\n", regno); 8709 return -EACCES; 8710 } 8711 8712 if (!tnum_is_const(reg->var_off)) { 8713 verbose(env, "R%d is not a constant address'\n", regno); 8714 return -EACCES; 8715 } 8716 8717 if (!map->ops->map_direct_value_addr) { 8718 verbose(env, "no direct value access support for this map type\n"); 8719 return -EACCES; 8720 } 8721 8722 err = check_map_access(env, regno, reg->off, 8723 map->value_size - reg->off, false, 8724 ACCESS_HELPER); 8725 if (err) 8726 return err; 8727 8728 map_off = reg->off + reg->var_off.value; 8729 err = map->ops->map_direct_value_addr(map, &map_addr, map_off); 8730 if (err) { 8731 verbose(env, "direct value access on string failed\n"); 8732 return err; 8733 } 8734 8735 str_ptr = (char *)(long)(map_addr); 8736 if (!strnchr(str_ptr + map_off, map->value_size - map_off, 0)) { 8737 verbose(env, "string is not zero-terminated\n"); 8738 return -EINVAL; 8739 } 8740 break; 8741 } 8742 case ARG_PTR_TO_KPTR: 8743 err = process_kptr_func(env, regno, meta); 8744 if (err) 8745 return err; 8746 break; 8747 } 8748 8749 return err; 8750 } 8751 8752 static bool may_update_sockmap(struct bpf_verifier_env *env, int func_id) 8753 { 8754 enum bpf_attach_type eatype = env->prog->expected_attach_type; 8755 enum bpf_prog_type type = resolve_prog_type(env->prog); 8756 8757 if (func_id != BPF_FUNC_map_update_elem && 8758 func_id != BPF_FUNC_map_delete_elem) 8759 return false; 8760 8761 /* It's not possible to get access to a locked struct sock in these 8762 * contexts, so updating is safe. 8763 */ 8764 switch (type) { 8765 case BPF_PROG_TYPE_TRACING: 8766 if (eatype == BPF_TRACE_ITER) 8767 return true; 8768 break; 8769 case BPF_PROG_TYPE_SOCK_OPS: 8770 /* map_update allowed only via dedicated helpers with event type checks */ 8771 if (func_id == BPF_FUNC_map_delete_elem) 8772 return true; 8773 break; 8774 case BPF_PROG_TYPE_SOCKET_FILTER: 8775 case BPF_PROG_TYPE_SCHED_CLS: 8776 case BPF_PROG_TYPE_SCHED_ACT: 8777 case BPF_PROG_TYPE_XDP: 8778 case BPF_PROG_TYPE_SK_REUSEPORT: 8779 case BPF_PROG_TYPE_FLOW_DISSECTOR: 8780 case BPF_PROG_TYPE_SK_LOOKUP: 8781 return true; 8782 default: 8783 break; 8784 } 8785 8786 verbose(env, "cannot update sockmap in this context\n"); 8787 return false; 8788 } 8789 8790 static bool allow_tail_call_in_subprogs(struct bpf_verifier_env *env) 8791 { 8792 return env->prog->jit_requested && 8793 bpf_jit_supports_subprog_tailcalls(); 8794 } 8795 8796 static int check_map_func_compatibility(struct bpf_verifier_env *env, 8797 struct bpf_map *map, int func_id) 8798 { 8799 if (!map) 8800 return 0; 8801 8802 /* We need a two way check, first is from map perspective ... */ 8803 switch (map->map_type) { 8804 case BPF_MAP_TYPE_PROG_ARRAY: 8805 if (func_id != BPF_FUNC_tail_call) 8806 goto error; 8807 break; 8808 case BPF_MAP_TYPE_PERF_EVENT_ARRAY: 8809 if (func_id != BPF_FUNC_perf_event_read && 8810 func_id != BPF_FUNC_perf_event_output && 8811 func_id != BPF_FUNC_skb_output && 8812 func_id != BPF_FUNC_perf_event_read_value && 8813 func_id != BPF_FUNC_xdp_output) 8814 goto error; 8815 break; 8816 case BPF_MAP_TYPE_RINGBUF: 8817 if (func_id != BPF_FUNC_ringbuf_output && 8818 func_id != BPF_FUNC_ringbuf_reserve && 8819 func_id != BPF_FUNC_ringbuf_query && 8820 func_id != BPF_FUNC_ringbuf_reserve_dynptr && 8821 func_id != BPF_FUNC_ringbuf_submit_dynptr && 8822 func_id != BPF_FUNC_ringbuf_discard_dynptr) 8823 goto error; 8824 break; 8825 case BPF_MAP_TYPE_USER_RINGBUF: 8826 if (func_id != BPF_FUNC_user_ringbuf_drain) 8827 goto error; 8828 break; 8829 case BPF_MAP_TYPE_STACK_TRACE: 8830 if (func_id != BPF_FUNC_get_stackid) 8831 goto error; 8832 break; 8833 case BPF_MAP_TYPE_CGROUP_ARRAY: 8834 if (func_id != BPF_FUNC_skb_under_cgroup && 8835 func_id != BPF_FUNC_current_task_under_cgroup) 8836 goto error; 8837 break; 8838 case BPF_MAP_TYPE_CGROUP_STORAGE: 8839 case BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE: 8840 if (func_id != BPF_FUNC_get_local_storage) 8841 goto error; 8842 break; 8843 case BPF_MAP_TYPE_DEVMAP: 8844 case BPF_MAP_TYPE_DEVMAP_HASH: 8845 if (func_id != BPF_FUNC_redirect_map && 8846 func_id != BPF_FUNC_map_lookup_elem) 8847 goto error; 8848 break; 8849 /* Restrict bpf side of cpumap and xskmap, open when use-cases 8850 * appear. 8851 */ 8852 case BPF_MAP_TYPE_CPUMAP: 8853 if (func_id != BPF_FUNC_redirect_map) 8854 goto error; 8855 break; 8856 case BPF_MAP_TYPE_XSKMAP: 8857 if (func_id != BPF_FUNC_redirect_map && 8858 func_id != BPF_FUNC_map_lookup_elem) 8859 goto error; 8860 break; 8861 case BPF_MAP_TYPE_ARRAY_OF_MAPS: 8862 case BPF_MAP_TYPE_HASH_OF_MAPS: 8863 if (func_id != BPF_FUNC_map_lookup_elem) 8864 goto error; 8865 break; 8866 case BPF_MAP_TYPE_SOCKMAP: 8867 if (func_id != BPF_FUNC_sk_redirect_map && 8868 func_id != BPF_FUNC_sock_map_update && 8869 func_id != BPF_FUNC_msg_redirect_map && 8870 func_id != BPF_FUNC_sk_select_reuseport && 8871 func_id != BPF_FUNC_map_lookup_elem && 8872 !may_update_sockmap(env, func_id)) 8873 goto error; 8874 break; 8875 case BPF_MAP_TYPE_SOCKHASH: 8876 if (func_id != BPF_FUNC_sk_redirect_hash && 8877 func_id != BPF_FUNC_sock_hash_update && 8878 func_id != BPF_FUNC_msg_redirect_hash && 8879 func_id != BPF_FUNC_sk_select_reuseport && 8880 func_id != BPF_FUNC_map_lookup_elem && 8881 !may_update_sockmap(env, func_id)) 8882 goto error; 8883 break; 8884 case BPF_MAP_TYPE_REUSEPORT_SOCKARRAY: 8885 if (func_id != BPF_FUNC_sk_select_reuseport) 8886 goto error; 8887 break; 8888 case BPF_MAP_TYPE_QUEUE: 8889 case BPF_MAP_TYPE_STACK: 8890 if (func_id != BPF_FUNC_map_peek_elem && 8891 func_id != BPF_FUNC_map_pop_elem && 8892 func_id != BPF_FUNC_map_push_elem) 8893 goto error; 8894 break; 8895 case BPF_MAP_TYPE_SK_STORAGE: 8896 if (func_id != BPF_FUNC_sk_storage_get && 8897 func_id != BPF_FUNC_sk_storage_delete && 8898 func_id != BPF_FUNC_kptr_xchg) 8899 goto error; 8900 break; 8901 case BPF_MAP_TYPE_INODE_STORAGE: 8902 if (func_id != BPF_FUNC_inode_storage_get && 8903 func_id != BPF_FUNC_inode_storage_delete && 8904 func_id != BPF_FUNC_kptr_xchg) 8905 goto error; 8906 break; 8907 case BPF_MAP_TYPE_TASK_STORAGE: 8908 if (func_id != BPF_FUNC_task_storage_get && 8909 func_id != BPF_FUNC_task_storage_delete && 8910 func_id != BPF_FUNC_kptr_xchg) 8911 goto error; 8912 break; 8913 case BPF_MAP_TYPE_CGRP_STORAGE: 8914 if (func_id != BPF_FUNC_cgrp_storage_get && 8915 func_id != BPF_FUNC_cgrp_storage_delete && 8916 func_id != BPF_FUNC_kptr_xchg) 8917 goto error; 8918 break; 8919 case BPF_MAP_TYPE_BLOOM_FILTER: 8920 if (func_id != BPF_FUNC_map_peek_elem && 8921 func_id != BPF_FUNC_map_push_elem) 8922 goto error; 8923 break; 8924 default: 8925 break; 8926 } 8927 8928 /* ... and second from the function itself. */ 8929 switch (func_id) { 8930 case BPF_FUNC_tail_call: 8931 if (map->map_type != BPF_MAP_TYPE_PROG_ARRAY) 8932 goto error; 8933 if (env->subprog_cnt > 1 && !allow_tail_call_in_subprogs(env)) { 8934 verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n"); 8935 return -EINVAL; 8936 } 8937 break; 8938 case BPF_FUNC_perf_event_read: 8939 case BPF_FUNC_perf_event_output: 8940 case BPF_FUNC_perf_event_read_value: 8941 case BPF_FUNC_skb_output: 8942 case BPF_FUNC_xdp_output: 8943 if (map->map_type != BPF_MAP_TYPE_PERF_EVENT_ARRAY) 8944 goto error; 8945 break; 8946 case BPF_FUNC_ringbuf_output: 8947 case BPF_FUNC_ringbuf_reserve: 8948 case BPF_FUNC_ringbuf_query: 8949 case BPF_FUNC_ringbuf_reserve_dynptr: 8950 case BPF_FUNC_ringbuf_submit_dynptr: 8951 case BPF_FUNC_ringbuf_discard_dynptr: 8952 if (map->map_type != BPF_MAP_TYPE_RINGBUF) 8953 goto error; 8954 break; 8955 case BPF_FUNC_user_ringbuf_drain: 8956 if (map->map_type != BPF_MAP_TYPE_USER_RINGBUF) 8957 goto error; 8958 break; 8959 case BPF_FUNC_get_stackid: 8960 if (map->map_type != BPF_MAP_TYPE_STACK_TRACE) 8961 goto error; 8962 break; 8963 case BPF_FUNC_current_task_under_cgroup: 8964 case BPF_FUNC_skb_under_cgroup: 8965 if (map->map_type != BPF_MAP_TYPE_CGROUP_ARRAY) 8966 goto error; 8967 break; 8968 case BPF_FUNC_redirect_map: 8969 if (map->map_type != BPF_MAP_TYPE_DEVMAP && 8970 map->map_type != BPF_MAP_TYPE_DEVMAP_HASH && 8971 map->map_type != BPF_MAP_TYPE_CPUMAP && 8972 map->map_type != BPF_MAP_TYPE_XSKMAP) 8973 goto error; 8974 break; 8975 case BPF_FUNC_sk_redirect_map: 8976 case BPF_FUNC_msg_redirect_map: 8977 case BPF_FUNC_sock_map_update: 8978 if (map->map_type != BPF_MAP_TYPE_SOCKMAP) 8979 goto error; 8980 break; 8981 case BPF_FUNC_sk_redirect_hash: 8982 case BPF_FUNC_msg_redirect_hash: 8983 case BPF_FUNC_sock_hash_update: 8984 if (map->map_type != BPF_MAP_TYPE_SOCKHASH) 8985 goto error; 8986 break; 8987 case BPF_FUNC_get_local_storage: 8988 if (map->map_type != BPF_MAP_TYPE_CGROUP_STORAGE && 8989 map->map_type != BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE) 8990 goto error; 8991 break; 8992 case BPF_FUNC_sk_select_reuseport: 8993 if (map->map_type != BPF_MAP_TYPE_REUSEPORT_SOCKARRAY && 8994 map->map_type != BPF_MAP_TYPE_SOCKMAP && 8995 map->map_type != BPF_MAP_TYPE_SOCKHASH) 8996 goto error; 8997 break; 8998 case BPF_FUNC_map_pop_elem: 8999 if (map->map_type != BPF_MAP_TYPE_QUEUE && 9000 map->map_type != BPF_MAP_TYPE_STACK) 9001 goto error; 9002 break; 9003 case BPF_FUNC_map_peek_elem: 9004 case BPF_FUNC_map_push_elem: 9005 if (map->map_type != BPF_MAP_TYPE_QUEUE && 9006 map->map_type != BPF_MAP_TYPE_STACK && 9007 map->map_type != BPF_MAP_TYPE_BLOOM_FILTER) 9008 goto error; 9009 break; 9010 case BPF_FUNC_map_lookup_percpu_elem: 9011 if (map->map_type != BPF_MAP_TYPE_PERCPU_ARRAY && 9012 map->map_type != BPF_MAP_TYPE_PERCPU_HASH && 9013 map->map_type != BPF_MAP_TYPE_LRU_PERCPU_HASH) 9014 goto error; 9015 break; 9016 case BPF_FUNC_sk_storage_get: 9017 case BPF_FUNC_sk_storage_delete: 9018 if (map->map_type != BPF_MAP_TYPE_SK_STORAGE) 9019 goto error; 9020 break; 9021 case BPF_FUNC_inode_storage_get: 9022 case BPF_FUNC_inode_storage_delete: 9023 if (map->map_type != BPF_MAP_TYPE_INODE_STORAGE) 9024 goto error; 9025 break; 9026 case BPF_FUNC_task_storage_get: 9027 case BPF_FUNC_task_storage_delete: 9028 if (map->map_type != BPF_MAP_TYPE_TASK_STORAGE) 9029 goto error; 9030 break; 9031 case BPF_FUNC_cgrp_storage_get: 9032 case BPF_FUNC_cgrp_storage_delete: 9033 if (map->map_type != BPF_MAP_TYPE_CGRP_STORAGE) 9034 goto error; 9035 break; 9036 default: 9037 break; 9038 } 9039 9040 return 0; 9041 error: 9042 verbose(env, "cannot pass map_type %d into func %s#%d\n", 9043 map->map_type, func_id_name(func_id), func_id); 9044 return -EINVAL; 9045 } 9046 9047 static bool check_raw_mode_ok(const struct bpf_func_proto *fn) 9048 { 9049 int count = 0; 9050 9051 if (arg_type_is_raw_mem(fn->arg1_type)) 9052 count++; 9053 if (arg_type_is_raw_mem(fn->arg2_type)) 9054 count++; 9055 if (arg_type_is_raw_mem(fn->arg3_type)) 9056 count++; 9057 if (arg_type_is_raw_mem(fn->arg4_type)) 9058 count++; 9059 if (arg_type_is_raw_mem(fn->arg5_type)) 9060 count++; 9061 9062 /* We only support one arg being in raw mode at the moment, 9063 * which is sufficient for the helper functions we have 9064 * right now. 9065 */ 9066 return count <= 1; 9067 } 9068 9069 static bool check_args_pair_invalid(const struct bpf_func_proto *fn, int arg) 9070 { 9071 bool is_fixed = fn->arg_type[arg] & MEM_FIXED_SIZE; 9072 bool has_size = fn->arg_size[arg] != 0; 9073 bool is_next_size = false; 9074 9075 if (arg + 1 < ARRAY_SIZE(fn->arg_type)) 9076 is_next_size = arg_type_is_mem_size(fn->arg_type[arg + 1]); 9077 9078 if (base_type(fn->arg_type[arg]) != ARG_PTR_TO_MEM) 9079 return is_next_size; 9080 9081 return has_size == is_next_size || is_next_size == is_fixed; 9082 } 9083 9084 static bool check_arg_pair_ok(const struct bpf_func_proto *fn) 9085 { 9086 /* bpf_xxx(..., buf, len) call will access 'len' 9087 * bytes from memory 'buf'. Both arg types need 9088 * to be paired, so make sure there's no buggy 9089 * helper function specification. 9090 */ 9091 if (arg_type_is_mem_size(fn->arg1_type) || 9092 check_args_pair_invalid(fn, 0) || 9093 check_args_pair_invalid(fn, 1) || 9094 check_args_pair_invalid(fn, 2) || 9095 check_args_pair_invalid(fn, 3) || 9096 check_args_pair_invalid(fn, 4)) 9097 return false; 9098 9099 return true; 9100 } 9101 9102 static bool check_btf_id_ok(const struct bpf_func_proto *fn) 9103 { 9104 int i; 9105 9106 for (i = 0; i < ARRAY_SIZE(fn->arg_type); i++) { 9107 if (base_type(fn->arg_type[i]) == ARG_PTR_TO_BTF_ID) 9108 return !!fn->arg_btf_id[i]; 9109 if (base_type(fn->arg_type[i]) == ARG_PTR_TO_SPIN_LOCK) 9110 return fn->arg_btf_id[i] == BPF_PTR_POISON; 9111 if (base_type(fn->arg_type[i]) != ARG_PTR_TO_BTF_ID && fn->arg_btf_id[i] && 9112 /* arg_btf_id and arg_size are in a union. */ 9113 (base_type(fn->arg_type[i]) != ARG_PTR_TO_MEM || 9114 !(fn->arg_type[i] & MEM_FIXED_SIZE))) 9115 return false; 9116 } 9117 9118 return true; 9119 } 9120 9121 static int check_func_proto(const struct bpf_func_proto *fn, int func_id) 9122 { 9123 return check_raw_mode_ok(fn) && 9124 check_arg_pair_ok(fn) && 9125 check_btf_id_ok(fn) ? 0 : -EINVAL; 9126 } 9127 9128 /* Packet data might have moved, any old PTR_TO_PACKET[_META,_END] 9129 * are now invalid, so turn them into unknown SCALAR_VALUE. 9130 * 9131 * This also applies to dynptr slices belonging to skb and xdp dynptrs, 9132 * since these slices point to packet data. 9133 */ 9134 static void clear_all_pkt_pointers(struct bpf_verifier_env *env) 9135 { 9136 struct bpf_func_state *state; 9137 struct bpf_reg_state *reg; 9138 9139 bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({ 9140 if (reg_is_pkt_pointer_any(reg) || reg_is_dynptr_slice_pkt(reg)) 9141 mark_reg_invalid(env, reg); 9142 })); 9143 } 9144 9145 enum { 9146 AT_PKT_END = -1, 9147 BEYOND_PKT_END = -2, 9148 }; 9149 9150 static void mark_pkt_end(struct bpf_verifier_state *vstate, int regn, bool range_open) 9151 { 9152 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 9153 struct bpf_reg_state *reg = &state->regs[regn]; 9154 9155 if (reg->type != PTR_TO_PACKET) 9156 /* PTR_TO_PACKET_META is not supported yet */ 9157 return; 9158 9159 /* The 'reg' is pkt > pkt_end or pkt >= pkt_end. 9160 * How far beyond pkt_end it goes is unknown. 9161 * if (!range_open) it's the case of pkt >= pkt_end 9162 * if (range_open) it's the case of pkt > pkt_end 9163 * hence this pointer is at least 1 byte bigger than pkt_end 9164 */ 9165 if (range_open) 9166 reg->range = BEYOND_PKT_END; 9167 else 9168 reg->range = AT_PKT_END; 9169 } 9170 9171 /* The pointer with the specified id has released its reference to kernel 9172 * resources. Identify all copies of the same pointer and clear the reference. 9173 */ 9174 static int release_reference(struct bpf_verifier_env *env, 9175 int ref_obj_id) 9176 { 9177 struct bpf_func_state *state; 9178 struct bpf_reg_state *reg; 9179 int err; 9180 9181 err = release_reference_state(cur_func(env), ref_obj_id); 9182 if (err) 9183 return err; 9184 9185 bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({ 9186 if (reg->ref_obj_id == ref_obj_id) 9187 mark_reg_invalid(env, reg); 9188 })); 9189 9190 return 0; 9191 } 9192 9193 static void invalidate_non_owning_refs(struct bpf_verifier_env *env) 9194 { 9195 struct bpf_func_state *unused; 9196 struct bpf_reg_state *reg; 9197 9198 bpf_for_each_reg_in_vstate(env->cur_state, unused, reg, ({ 9199 if (type_is_non_owning_ref(reg->type)) 9200 mark_reg_invalid(env, reg); 9201 })); 9202 } 9203 9204 static void clear_caller_saved_regs(struct bpf_verifier_env *env, 9205 struct bpf_reg_state *regs) 9206 { 9207 int i; 9208 9209 /* after the call registers r0 - r5 were scratched */ 9210 for (i = 0; i < CALLER_SAVED_REGS; i++) { 9211 mark_reg_not_init(env, regs, caller_saved[i]); 9212 __check_reg_arg(env, regs, caller_saved[i], DST_OP_NO_MARK); 9213 } 9214 } 9215 9216 typedef int (*set_callee_state_fn)(struct bpf_verifier_env *env, 9217 struct bpf_func_state *caller, 9218 struct bpf_func_state *callee, 9219 int insn_idx); 9220 9221 static int set_callee_state(struct bpf_verifier_env *env, 9222 struct bpf_func_state *caller, 9223 struct bpf_func_state *callee, int insn_idx); 9224 9225 static int setup_func_entry(struct bpf_verifier_env *env, int subprog, int callsite, 9226 set_callee_state_fn set_callee_state_cb, 9227 struct bpf_verifier_state *state) 9228 { 9229 struct bpf_func_state *caller, *callee; 9230 int err; 9231 9232 if (state->curframe + 1 >= MAX_CALL_FRAMES) { 9233 verbose(env, "the call stack of %d frames is too deep\n", 9234 state->curframe + 2); 9235 return -E2BIG; 9236 } 9237 9238 if (state->frame[state->curframe + 1]) { 9239 verbose(env, "verifier bug. Frame %d already allocated\n", 9240 state->curframe + 1); 9241 return -EFAULT; 9242 } 9243 9244 caller = state->frame[state->curframe]; 9245 callee = kzalloc(sizeof(*callee), GFP_KERNEL); 9246 if (!callee) 9247 return -ENOMEM; 9248 state->frame[state->curframe + 1] = callee; 9249 9250 /* callee cannot access r0, r6 - r9 for reading and has to write 9251 * into its own stack before reading from it. 9252 * callee can read/write into caller's stack 9253 */ 9254 init_func_state(env, callee, 9255 /* remember the callsite, it will be used by bpf_exit */ 9256 callsite, 9257 state->curframe + 1 /* frameno within this callchain */, 9258 subprog /* subprog number within this prog */); 9259 /* Transfer references to the callee */ 9260 err = copy_reference_state(callee, caller); 9261 err = err ?: set_callee_state_cb(env, caller, callee, callsite); 9262 if (err) 9263 goto err_out; 9264 9265 /* only increment it after check_reg_arg() finished */ 9266 state->curframe++; 9267 9268 return 0; 9269 9270 err_out: 9271 free_func_state(callee); 9272 state->frame[state->curframe + 1] = NULL; 9273 return err; 9274 } 9275 9276 static int push_callback_call(struct bpf_verifier_env *env, struct bpf_insn *insn, 9277 int insn_idx, int subprog, 9278 set_callee_state_fn set_callee_state_cb) 9279 { 9280 struct bpf_verifier_state *state = env->cur_state, *callback_state; 9281 struct bpf_func_state *caller, *callee; 9282 int err; 9283 9284 caller = state->frame[state->curframe]; 9285 err = btf_check_subprog_call(env, subprog, caller->regs); 9286 if (err == -EFAULT) 9287 return err; 9288 9289 /* set_callee_state is used for direct subprog calls, but we are 9290 * interested in validating only BPF helpers that can call subprogs as 9291 * callbacks 9292 */ 9293 if (bpf_pseudo_kfunc_call(insn) && 9294 !is_sync_callback_calling_kfunc(insn->imm)) { 9295 verbose(env, "verifier bug: kfunc %s#%d not marked as callback-calling\n", 9296 func_id_name(insn->imm), insn->imm); 9297 return -EFAULT; 9298 } else if (!bpf_pseudo_kfunc_call(insn) && 9299 !is_callback_calling_function(insn->imm)) { /* helper */ 9300 verbose(env, "verifier bug: helper %s#%d not marked as callback-calling\n", 9301 func_id_name(insn->imm), insn->imm); 9302 return -EFAULT; 9303 } 9304 9305 if (insn->code == (BPF_JMP | BPF_CALL) && 9306 insn->src_reg == 0 && 9307 insn->imm == BPF_FUNC_timer_set_callback) { 9308 struct bpf_verifier_state *async_cb; 9309 9310 /* there is no real recursion here. timer callbacks are async */ 9311 env->subprog_info[subprog].is_async_cb = true; 9312 async_cb = push_async_cb(env, env->subprog_info[subprog].start, 9313 insn_idx, subprog); 9314 if (!async_cb) 9315 return -EFAULT; 9316 callee = async_cb->frame[0]; 9317 callee->async_entry_cnt = caller->async_entry_cnt + 1; 9318 9319 /* Convert bpf_timer_set_callback() args into timer callback args */ 9320 err = set_callee_state_cb(env, caller, callee, insn_idx); 9321 if (err) 9322 return err; 9323 9324 return 0; 9325 } 9326 9327 /* for callback functions enqueue entry to callback and 9328 * proceed with next instruction within current frame. 9329 */ 9330 callback_state = push_stack(env, env->subprog_info[subprog].start, insn_idx, false); 9331 if (!callback_state) 9332 return -ENOMEM; 9333 9334 err = setup_func_entry(env, subprog, insn_idx, set_callee_state_cb, 9335 callback_state); 9336 if (err) 9337 return err; 9338 9339 callback_state->callback_unroll_depth++; 9340 callback_state->frame[callback_state->curframe - 1]->callback_depth++; 9341 caller->callback_depth = 0; 9342 return 0; 9343 } 9344 9345 static int check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn, 9346 int *insn_idx) 9347 { 9348 struct bpf_verifier_state *state = env->cur_state; 9349 struct bpf_func_state *caller; 9350 int err, subprog, target_insn; 9351 9352 target_insn = *insn_idx + insn->imm + 1; 9353 subprog = find_subprog(env, target_insn); 9354 if (subprog < 0) { 9355 verbose(env, "verifier bug. No program starts at insn %d\n", target_insn); 9356 return -EFAULT; 9357 } 9358 9359 caller = state->frame[state->curframe]; 9360 err = btf_check_subprog_call(env, subprog, caller->regs); 9361 if (err == -EFAULT) 9362 return err; 9363 if (subprog_is_global(env, subprog)) { 9364 if (err) { 9365 verbose(env, "Caller passes invalid args into func#%d\n", subprog); 9366 return err; 9367 } 9368 9369 if (env->log.level & BPF_LOG_LEVEL) 9370 verbose(env, "Func#%d is global and valid. Skipping.\n", subprog); 9371 clear_caller_saved_regs(env, caller->regs); 9372 9373 /* All global functions return a 64-bit SCALAR_VALUE */ 9374 mark_reg_unknown(env, caller->regs, BPF_REG_0); 9375 caller->regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG; 9376 9377 /* continue with next insn after call */ 9378 return 0; 9379 } 9380 9381 /* for regular function entry setup new frame and continue 9382 * from that frame. 9383 */ 9384 err = setup_func_entry(env, subprog, *insn_idx, set_callee_state, state); 9385 if (err) 9386 return err; 9387 9388 clear_caller_saved_regs(env, caller->regs); 9389 9390 /* and go analyze first insn of the callee */ 9391 *insn_idx = env->subprog_info[subprog].start - 1; 9392 9393 if (env->log.level & BPF_LOG_LEVEL) { 9394 verbose(env, "caller:\n"); 9395 print_verifier_state(env, caller, true); 9396 verbose(env, "callee:\n"); 9397 print_verifier_state(env, state->frame[state->curframe], true); 9398 } 9399 9400 return 0; 9401 } 9402 9403 int map_set_for_each_callback_args(struct bpf_verifier_env *env, 9404 struct bpf_func_state *caller, 9405 struct bpf_func_state *callee) 9406 { 9407 /* bpf_for_each_map_elem(struct bpf_map *map, void *callback_fn, 9408 * void *callback_ctx, u64 flags); 9409 * callback_fn(struct bpf_map *map, void *key, void *value, 9410 * void *callback_ctx); 9411 */ 9412 callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1]; 9413 9414 callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY; 9415 __mark_reg_known_zero(&callee->regs[BPF_REG_2]); 9416 callee->regs[BPF_REG_2].map_ptr = caller->regs[BPF_REG_1].map_ptr; 9417 9418 callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE; 9419 __mark_reg_known_zero(&callee->regs[BPF_REG_3]); 9420 callee->regs[BPF_REG_3].map_ptr = caller->regs[BPF_REG_1].map_ptr; 9421 9422 /* pointer to stack or null */ 9423 callee->regs[BPF_REG_4] = caller->regs[BPF_REG_3]; 9424 9425 /* unused */ 9426 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]); 9427 return 0; 9428 } 9429 9430 static int set_callee_state(struct bpf_verifier_env *env, 9431 struct bpf_func_state *caller, 9432 struct bpf_func_state *callee, int insn_idx) 9433 { 9434 int i; 9435 9436 /* copy r1 - r5 args that callee can access. The copy includes parent 9437 * pointers, which connects us up to the liveness chain 9438 */ 9439 for (i = BPF_REG_1; i <= BPF_REG_5; i++) 9440 callee->regs[i] = caller->regs[i]; 9441 return 0; 9442 } 9443 9444 static int set_map_elem_callback_state(struct bpf_verifier_env *env, 9445 struct bpf_func_state *caller, 9446 struct bpf_func_state *callee, 9447 int insn_idx) 9448 { 9449 struct bpf_insn_aux_data *insn_aux = &env->insn_aux_data[insn_idx]; 9450 struct bpf_map *map; 9451 int err; 9452 9453 if (bpf_map_ptr_poisoned(insn_aux)) { 9454 verbose(env, "tail_call abusing map_ptr\n"); 9455 return -EINVAL; 9456 } 9457 9458 map = BPF_MAP_PTR(insn_aux->map_ptr_state); 9459 if (!map->ops->map_set_for_each_callback_args || 9460 !map->ops->map_for_each_callback) { 9461 verbose(env, "callback function not allowed for map\n"); 9462 return -ENOTSUPP; 9463 } 9464 9465 err = map->ops->map_set_for_each_callback_args(env, caller, callee); 9466 if (err) 9467 return err; 9468 9469 callee->in_callback_fn = true; 9470 callee->callback_ret_range = tnum_range(0, 1); 9471 return 0; 9472 } 9473 9474 static int set_loop_callback_state(struct bpf_verifier_env *env, 9475 struct bpf_func_state *caller, 9476 struct bpf_func_state *callee, 9477 int insn_idx) 9478 { 9479 /* bpf_loop(u32 nr_loops, void *callback_fn, void *callback_ctx, 9480 * u64 flags); 9481 * callback_fn(u32 index, void *callback_ctx); 9482 */ 9483 callee->regs[BPF_REG_1].type = SCALAR_VALUE; 9484 callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3]; 9485 9486 /* unused */ 9487 __mark_reg_not_init(env, &callee->regs[BPF_REG_3]); 9488 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]); 9489 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]); 9490 9491 callee->in_callback_fn = true; 9492 callee->callback_ret_range = tnum_range(0, 1); 9493 return 0; 9494 } 9495 9496 static int set_timer_callback_state(struct bpf_verifier_env *env, 9497 struct bpf_func_state *caller, 9498 struct bpf_func_state *callee, 9499 int insn_idx) 9500 { 9501 struct bpf_map *map_ptr = caller->regs[BPF_REG_1].map_ptr; 9502 9503 /* bpf_timer_set_callback(struct bpf_timer *timer, void *callback_fn); 9504 * callback_fn(struct bpf_map *map, void *key, void *value); 9505 */ 9506 callee->regs[BPF_REG_1].type = CONST_PTR_TO_MAP; 9507 __mark_reg_known_zero(&callee->regs[BPF_REG_1]); 9508 callee->regs[BPF_REG_1].map_ptr = map_ptr; 9509 9510 callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY; 9511 __mark_reg_known_zero(&callee->regs[BPF_REG_2]); 9512 callee->regs[BPF_REG_2].map_ptr = map_ptr; 9513 9514 callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE; 9515 __mark_reg_known_zero(&callee->regs[BPF_REG_3]); 9516 callee->regs[BPF_REG_3].map_ptr = map_ptr; 9517 9518 /* unused */ 9519 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]); 9520 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]); 9521 callee->in_async_callback_fn = true; 9522 callee->callback_ret_range = tnum_range(0, 1); 9523 return 0; 9524 } 9525 9526 static int set_find_vma_callback_state(struct bpf_verifier_env *env, 9527 struct bpf_func_state *caller, 9528 struct bpf_func_state *callee, 9529 int insn_idx) 9530 { 9531 /* bpf_find_vma(struct task_struct *task, u64 addr, 9532 * void *callback_fn, void *callback_ctx, u64 flags) 9533 * (callback_fn)(struct task_struct *task, 9534 * struct vm_area_struct *vma, void *callback_ctx); 9535 */ 9536 callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1]; 9537 9538 callee->regs[BPF_REG_2].type = PTR_TO_BTF_ID; 9539 __mark_reg_known_zero(&callee->regs[BPF_REG_2]); 9540 callee->regs[BPF_REG_2].btf = btf_vmlinux; 9541 callee->regs[BPF_REG_2].btf_id = btf_tracing_ids[BTF_TRACING_TYPE_VMA], 9542 9543 /* pointer to stack or null */ 9544 callee->regs[BPF_REG_3] = caller->regs[BPF_REG_4]; 9545 9546 /* unused */ 9547 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]); 9548 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]); 9549 callee->in_callback_fn = true; 9550 callee->callback_ret_range = tnum_range(0, 1); 9551 return 0; 9552 } 9553 9554 static int set_user_ringbuf_callback_state(struct bpf_verifier_env *env, 9555 struct bpf_func_state *caller, 9556 struct bpf_func_state *callee, 9557 int insn_idx) 9558 { 9559 /* bpf_user_ringbuf_drain(struct bpf_map *map, void *callback_fn, void 9560 * callback_ctx, u64 flags); 9561 * callback_fn(const struct bpf_dynptr_t* dynptr, void *callback_ctx); 9562 */ 9563 __mark_reg_not_init(env, &callee->regs[BPF_REG_0]); 9564 mark_dynptr_cb_reg(env, &callee->regs[BPF_REG_1], BPF_DYNPTR_TYPE_LOCAL); 9565 callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3]; 9566 9567 /* unused */ 9568 __mark_reg_not_init(env, &callee->regs[BPF_REG_3]); 9569 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]); 9570 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]); 9571 9572 callee->in_callback_fn = true; 9573 callee->callback_ret_range = tnum_range(0, 1); 9574 return 0; 9575 } 9576 9577 static int set_rbtree_add_callback_state(struct bpf_verifier_env *env, 9578 struct bpf_func_state *caller, 9579 struct bpf_func_state *callee, 9580 int insn_idx) 9581 { 9582 /* void bpf_rbtree_add_impl(struct bpf_rb_root *root, struct bpf_rb_node *node, 9583 * bool (less)(struct bpf_rb_node *a, const struct bpf_rb_node *b)); 9584 * 9585 * 'struct bpf_rb_node *node' arg to bpf_rbtree_add_impl is the same PTR_TO_BTF_ID w/ offset 9586 * that 'less' callback args will be receiving. However, 'node' arg was release_reference'd 9587 * by this point, so look at 'root' 9588 */ 9589 struct btf_field *field; 9590 9591 field = reg_find_field_offset(&caller->regs[BPF_REG_1], caller->regs[BPF_REG_1].off, 9592 BPF_RB_ROOT); 9593 if (!field || !field->graph_root.value_btf_id) 9594 return -EFAULT; 9595 9596 mark_reg_graph_node(callee->regs, BPF_REG_1, &field->graph_root); 9597 ref_set_non_owning(env, &callee->regs[BPF_REG_1]); 9598 mark_reg_graph_node(callee->regs, BPF_REG_2, &field->graph_root); 9599 ref_set_non_owning(env, &callee->regs[BPF_REG_2]); 9600 9601 __mark_reg_not_init(env, &callee->regs[BPF_REG_3]); 9602 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]); 9603 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]); 9604 callee->in_callback_fn = true; 9605 callee->callback_ret_range = tnum_range(0, 1); 9606 return 0; 9607 } 9608 9609 static bool is_rbtree_lock_required_kfunc(u32 btf_id); 9610 9611 /* Are we currently verifying the callback for a rbtree helper that must 9612 * be called with lock held? If so, no need to complain about unreleased 9613 * lock 9614 */ 9615 static bool in_rbtree_lock_required_cb(struct bpf_verifier_env *env) 9616 { 9617 struct bpf_verifier_state *state = env->cur_state; 9618 struct bpf_insn *insn = env->prog->insnsi; 9619 struct bpf_func_state *callee; 9620 int kfunc_btf_id; 9621 9622 if (!state->curframe) 9623 return false; 9624 9625 callee = state->frame[state->curframe]; 9626 9627 if (!callee->in_callback_fn) 9628 return false; 9629 9630 kfunc_btf_id = insn[callee->callsite].imm; 9631 return is_rbtree_lock_required_kfunc(kfunc_btf_id); 9632 } 9633 9634 static int prepare_func_exit(struct bpf_verifier_env *env, int *insn_idx) 9635 { 9636 struct bpf_verifier_state *state = env->cur_state, *prev_st; 9637 struct bpf_func_state *caller, *callee; 9638 struct bpf_reg_state *r0; 9639 bool in_callback_fn; 9640 int err; 9641 9642 callee = state->frame[state->curframe]; 9643 r0 = &callee->regs[BPF_REG_0]; 9644 if (r0->type == PTR_TO_STACK) { 9645 /* technically it's ok to return caller's stack pointer 9646 * (or caller's caller's pointer) back to the caller, 9647 * since these pointers are valid. Only current stack 9648 * pointer will be invalid as soon as function exits, 9649 * but let's be conservative 9650 */ 9651 verbose(env, "cannot return stack pointer to the caller\n"); 9652 return -EINVAL; 9653 } 9654 9655 caller = state->frame[state->curframe - 1]; 9656 if (callee->in_callback_fn) { 9657 /* enforce R0 return value range [0, 1]. */ 9658 struct tnum range = callee->callback_ret_range; 9659 9660 if (r0->type != SCALAR_VALUE) { 9661 verbose(env, "R0 not a scalar value\n"); 9662 return -EACCES; 9663 } 9664 9665 /* we are going to rely on register's precise value */ 9666 err = mark_reg_read(env, r0, r0->parent, REG_LIVE_READ64); 9667 err = err ?: mark_chain_precision(env, BPF_REG_0); 9668 if (err) 9669 return err; 9670 9671 if (!tnum_in(range, r0->var_off)) { 9672 verbose_invalid_scalar(env, r0, &range, "callback return", "R0"); 9673 return -EINVAL; 9674 } 9675 if (!calls_callback(env, callee->callsite)) { 9676 verbose(env, "BUG: in callback at %d, callsite %d !calls_callback\n", 9677 *insn_idx, callee->callsite); 9678 return -EFAULT; 9679 } 9680 } else { 9681 /* return to the caller whatever r0 had in the callee */ 9682 caller->regs[BPF_REG_0] = *r0; 9683 } 9684 9685 /* callback_fn frame should have released its own additions to parent's 9686 * reference state at this point, or check_reference_leak would 9687 * complain, hence it must be the same as the caller. There is no need 9688 * to copy it back. 9689 */ 9690 if (!callee->in_callback_fn) { 9691 /* Transfer references to the caller */ 9692 err = copy_reference_state(caller, callee); 9693 if (err) 9694 return err; 9695 } 9696 9697 /* for callbacks like bpf_loop or bpf_for_each_map_elem go back to callsite, 9698 * there function call logic would reschedule callback visit. If iteration 9699 * converges is_state_visited() would prune that visit eventually. 9700 */ 9701 in_callback_fn = callee->in_callback_fn; 9702 if (in_callback_fn) 9703 *insn_idx = callee->callsite; 9704 else 9705 *insn_idx = callee->callsite + 1; 9706 9707 if (env->log.level & BPF_LOG_LEVEL) { 9708 verbose(env, "returning from callee:\n"); 9709 print_verifier_state(env, callee, true); 9710 verbose(env, "to caller at %d:\n", *insn_idx); 9711 print_verifier_state(env, caller, true); 9712 } 9713 /* clear everything in the callee */ 9714 free_func_state(callee); 9715 state->frame[state->curframe--] = NULL; 9716 9717 /* for callbacks widen imprecise scalars to make programs like below verify: 9718 * 9719 * struct ctx { int i; } 9720 * void cb(int idx, struct ctx *ctx) { ctx->i++; ... } 9721 * ... 9722 * struct ctx = { .i = 0; } 9723 * bpf_loop(100, cb, &ctx, 0); 9724 * 9725 * This is similar to what is done in process_iter_next_call() for open 9726 * coded iterators. 9727 */ 9728 prev_st = in_callback_fn ? find_prev_entry(env, state, *insn_idx) : NULL; 9729 if (prev_st) { 9730 err = widen_imprecise_scalars(env, prev_st, state); 9731 if (err) 9732 return err; 9733 } 9734 return 0; 9735 } 9736 9737 static void do_refine_retval_range(struct bpf_reg_state *regs, int ret_type, 9738 int func_id, 9739 struct bpf_call_arg_meta *meta) 9740 { 9741 struct bpf_reg_state *ret_reg = ®s[BPF_REG_0]; 9742 9743 if (ret_type != RET_INTEGER) 9744 return; 9745 9746 switch (func_id) { 9747 case BPF_FUNC_get_stack: 9748 case BPF_FUNC_get_task_stack: 9749 case BPF_FUNC_probe_read_str: 9750 case BPF_FUNC_probe_read_kernel_str: 9751 case BPF_FUNC_probe_read_user_str: 9752 ret_reg->smax_value = meta->msize_max_value; 9753 ret_reg->s32_max_value = meta->msize_max_value; 9754 ret_reg->smin_value = -MAX_ERRNO; 9755 ret_reg->s32_min_value = -MAX_ERRNO; 9756 reg_bounds_sync(ret_reg); 9757 break; 9758 case BPF_FUNC_get_smp_processor_id: 9759 ret_reg->umax_value = nr_cpu_ids - 1; 9760 ret_reg->u32_max_value = nr_cpu_ids - 1; 9761 ret_reg->smax_value = nr_cpu_ids - 1; 9762 ret_reg->s32_max_value = nr_cpu_ids - 1; 9763 ret_reg->umin_value = 0; 9764 ret_reg->u32_min_value = 0; 9765 ret_reg->smin_value = 0; 9766 ret_reg->s32_min_value = 0; 9767 reg_bounds_sync(ret_reg); 9768 break; 9769 } 9770 } 9771 9772 static int 9773 record_func_map(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta, 9774 int func_id, int insn_idx) 9775 { 9776 struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx]; 9777 struct bpf_map *map = meta->map_ptr; 9778 9779 if (func_id != BPF_FUNC_tail_call && 9780 func_id != BPF_FUNC_map_lookup_elem && 9781 func_id != BPF_FUNC_map_update_elem && 9782 func_id != BPF_FUNC_map_delete_elem && 9783 func_id != BPF_FUNC_map_push_elem && 9784 func_id != BPF_FUNC_map_pop_elem && 9785 func_id != BPF_FUNC_map_peek_elem && 9786 func_id != BPF_FUNC_for_each_map_elem && 9787 func_id != BPF_FUNC_redirect_map && 9788 func_id != BPF_FUNC_map_lookup_percpu_elem) 9789 return 0; 9790 9791 if (map == NULL) { 9792 verbose(env, "kernel subsystem misconfigured verifier\n"); 9793 return -EINVAL; 9794 } 9795 9796 /* In case of read-only, some additional restrictions 9797 * need to be applied in order to prevent altering the 9798 * state of the map from program side. 9799 */ 9800 if ((map->map_flags & BPF_F_RDONLY_PROG) && 9801 (func_id == BPF_FUNC_map_delete_elem || 9802 func_id == BPF_FUNC_map_update_elem || 9803 func_id == BPF_FUNC_map_push_elem || 9804 func_id == BPF_FUNC_map_pop_elem)) { 9805 verbose(env, "write into map forbidden\n"); 9806 return -EACCES; 9807 } 9808 9809 if (!BPF_MAP_PTR(aux->map_ptr_state)) 9810 bpf_map_ptr_store(aux, meta->map_ptr, 9811 !meta->map_ptr->bypass_spec_v1); 9812 else if (BPF_MAP_PTR(aux->map_ptr_state) != meta->map_ptr) 9813 bpf_map_ptr_store(aux, BPF_MAP_PTR_POISON, 9814 !meta->map_ptr->bypass_spec_v1); 9815 return 0; 9816 } 9817 9818 static int 9819 record_func_key(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta, 9820 int func_id, int insn_idx) 9821 { 9822 struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx]; 9823 struct bpf_reg_state *regs = cur_regs(env), *reg; 9824 struct bpf_map *map = meta->map_ptr; 9825 u64 val, max; 9826 int err; 9827 9828 if (func_id != BPF_FUNC_tail_call) 9829 return 0; 9830 if (!map || map->map_type != BPF_MAP_TYPE_PROG_ARRAY) { 9831 verbose(env, "kernel subsystem misconfigured verifier\n"); 9832 return -EINVAL; 9833 } 9834 9835 reg = ®s[BPF_REG_3]; 9836 val = reg->var_off.value; 9837 max = map->max_entries; 9838 9839 if (!(register_is_const(reg) && val < max)) { 9840 bpf_map_key_store(aux, BPF_MAP_KEY_POISON); 9841 return 0; 9842 } 9843 9844 err = mark_chain_precision(env, BPF_REG_3); 9845 if (err) 9846 return err; 9847 if (bpf_map_key_unseen(aux)) 9848 bpf_map_key_store(aux, val); 9849 else if (!bpf_map_key_poisoned(aux) && 9850 bpf_map_key_immediate(aux) != val) 9851 bpf_map_key_store(aux, BPF_MAP_KEY_POISON); 9852 return 0; 9853 } 9854 9855 static int check_reference_leak(struct bpf_verifier_env *env) 9856 { 9857 struct bpf_func_state *state = cur_func(env); 9858 bool refs_lingering = false; 9859 int i; 9860 9861 if (state->frameno && !state->in_callback_fn) 9862 return 0; 9863 9864 for (i = 0; i < state->acquired_refs; i++) { 9865 if (state->in_callback_fn && state->refs[i].callback_ref != state->frameno) 9866 continue; 9867 verbose(env, "Unreleased reference id=%d alloc_insn=%d\n", 9868 state->refs[i].id, state->refs[i].insn_idx); 9869 refs_lingering = true; 9870 } 9871 return refs_lingering ? -EINVAL : 0; 9872 } 9873 9874 static int check_bpf_snprintf_call(struct bpf_verifier_env *env, 9875 struct bpf_reg_state *regs) 9876 { 9877 struct bpf_reg_state *fmt_reg = ®s[BPF_REG_3]; 9878 struct bpf_reg_state *data_len_reg = ®s[BPF_REG_5]; 9879 struct bpf_map *fmt_map = fmt_reg->map_ptr; 9880 struct bpf_bprintf_data data = {}; 9881 int err, fmt_map_off, num_args; 9882 u64 fmt_addr; 9883 char *fmt; 9884 9885 /* data must be an array of u64 */ 9886 if (data_len_reg->var_off.value % 8) 9887 return -EINVAL; 9888 num_args = data_len_reg->var_off.value / 8; 9889 9890 /* fmt being ARG_PTR_TO_CONST_STR guarantees that var_off is const 9891 * and map_direct_value_addr is set. 9892 */ 9893 fmt_map_off = fmt_reg->off + fmt_reg->var_off.value; 9894 err = fmt_map->ops->map_direct_value_addr(fmt_map, &fmt_addr, 9895 fmt_map_off); 9896 if (err) { 9897 verbose(env, "verifier bug\n"); 9898 return -EFAULT; 9899 } 9900 fmt = (char *)(long)fmt_addr + fmt_map_off; 9901 9902 /* We are also guaranteed that fmt+fmt_map_off is NULL terminated, we 9903 * can focus on validating the format specifiers. 9904 */ 9905 err = bpf_bprintf_prepare(fmt, UINT_MAX, NULL, num_args, &data); 9906 if (err < 0) 9907 verbose(env, "Invalid format string\n"); 9908 9909 return err; 9910 } 9911 9912 static int check_get_func_ip(struct bpf_verifier_env *env) 9913 { 9914 enum bpf_prog_type type = resolve_prog_type(env->prog); 9915 int func_id = BPF_FUNC_get_func_ip; 9916 9917 if (type == BPF_PROG_TYPE_TRACING) { 9918 if (!bpf_prog_has_trampoline(env->prog)) { 9919 verbose(env, "func %s#%d supported only for fentry/fexit/fmod_ret programs\n", 9920 func_id_name(func_id), func_id); 9921 return -ENOTSUPP; 9922 } 9923 return 0; 9924 } else if (type == BPF_PROG_TYPE_KPROBE) { 9925 return 0; 9926 } 9927 9928 verbose(env, "func %s#%d not supported for program type %d\n", 9929 func_id_name(func_id), func_id, type); 9930 return -ENOTSUPP; 9931 } 9932 9933 static struct bpf_insn_aux_data *cur_aux(struct bpf_verifier_env *env) 9934 { 9935 return &env->insn_aux_data[env->insn_idx]; 9936 } 9937 9938 static bool loop_flag_is_zero(struct bpf_verifier_env *env) 9939 { 9940 struct bpf_reg_state *regs = cur_regs(env); 9941 struct bpf_reg_state *reg = ®s[BPF_REG_4]; 9942 bool reg_is_null = register_is_null(reg); 9943 9944 if (reg_is_null) 9945 mark_chain_precision(env, BPF_REG_4); 9946 9947 return reg_is_null; 9948 } 9949 9950 static void update_loop_inline_state(struct bpf_verifier_env *env, u32 subprogno) 9951 { 9952 struct bpf_loop_inline_state *state = &cur_aux(env)->loop_inline_state; 9953 9954 if (!state->initialized) { 9955 state->initialized = 1; 9956 state->fit_for_inline = loop_flag_is_zero(env); 9957 state->callback_subprogno = subprogno; 9958 return; 9959 } 9960 9961 if (!state->fit_for_inline) 9962 return; 9963 9964 state->fit_for_inline = (loop_flag_is_zero(env) && 9965 state->callback_subprogno == subprogno); 9966 } 9967 9968 static int check_helper_call(struct bpf_verifier_env *env, struct bpf_insn *insn, 9969 int *insn_idx_p) 9970 { 9971 enum bpf_prog_type prog_type = resolve_prog_type(env->prog); 9972 const struct bpf_func_proto *fn = NULL; 9973 enum bpf_return_type ret_type; 9974 enum bpf_type_flag ret_flag; 9975 struct bpf_reg_state *regs; 9976 struct bpf_call_arg_meta meta; 9977 int insn_idx = *insn_idx_p; 9978 bool changes_data; 9979 int i, err, func_id; 9980 9981 /* find function prototype */ 9982 func_id = insn->imm; 9983 if (func_id < 0 || func_id >= __BPF_FUNC_MAX_ID) { 9984 verbose(env, "invalid func %s#%d\n", func_id_name(func_id), 9985 func_id); 9986 return -EINVAL; 9987 } 9988 9989 if (env->ops->get_func_proto) 9990 fn = env->ops->get_func_proto(func_id, env->prog); 9991 if (!fn) { 9992 verbose(env, "unknown func %s#%d\n", func_id_name(func_id), 9993 func_id); 9994 return -EINVAL; 9995 } 9996 9997 /* eBPF programs must be GPL compatible to use GPL-ed functions */ 9998 if (!env->prog->gpl_compatible && fn->gpl_only) { 9999 verbose(env, "cannot call GPL-restricted function from non-GPL compatible program\n"); 10000 return -EINVAL; 10001 } 10002 10003 if (fn->allowed && !fn->allowed(env->prog)) { 10004 verbose(env, "helper call is not allowed in probe\n"); 10005 return -EINVAL; 10006 } 10007 10008 if (!env->prog->aux->sleepable && fn->might_sleep) { 10009 verbose(env, "helper call might sleep in a non-sleepable prog\n"); 10010 return -EINVAL; 10011 } 10012 10013 /* With LD_ABS/IND some JITs save/restore skb from r1. */ 10014 changes_data = bpf_helper_changes_pkt_data(fn->func); 10015 if (changes_data && fn->arg1_type != ARG_PTR_TO_CTX) { 10016 verbose(env, "kernel subsystem misconfigured func %s#%d: r1 != ctx\n", 10017 func_id_name(func_id), func_id); 10018 return -EINVAL; 10019 } 10020 10021 memset(&meta, 0, sizeof(meta)); 10022 meta.pkt_access = fn->pkt_access; 10023 10024 err = check_func_proto(fn, func_id); 10025 if (err) { 10026 verbose(env, "kernel subsystem misconfigured func %s#%d\n", 10027 func_id_name(func_id), func_id); 10028 return err; 10029 } 10030 10031 if (env->cur_state->active_rcu_lock) { 10032 if (fn->might_sleep) { 10033 verbose(env, "sleepable helper %s#%d in rcu_read_lock region\n", 10034 func_id_name(func_id), func_id); 10035 return -EINVAL; 10036 } 10037 10038 if (env->prog->aux->sleepable && is_storage_get_function(func_id)) 10039 env->insn_aux_data[insn_idx].storage_get_func_atomic = true; 10040 } 10041 10042 meta.func_id = func_id; 10043 /* check args */ 10044 for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++) { 10045 err = check_func_arg(env, i, &meta, fn, insn_idx); 10046 if (err) 10047 return err; 10048 } 10049 10050 err = record_func_map(env, &meta, func_id, insn_idx); 10051 if (err) 10052 return err; 10053 10054 err = record_func_key(env, &meta, func_id, insn_idx); 10055 if (err) 10056 return err; 10057 10058 /* Mark slots with STACK_MISC in case of raw mode, stack offset 10059 * is inferred from register state. 10060 */ 10061 for (i = 0; i < meta.access_size; i++) { 10062 err = check_mem_access(env, insn_idx, meta.regno, i, BPF_B, 10063 BPF_WRITE, -1, false, false); 10064 if (err) 10065 return err; 10066 } 10067 10068 regs = cur_regs(env); 10069 10070 if (meta.release_regno) { 10071 err = -EINVAL; 10072 /* This can only be set for PTR_TO_STACK, as CONST_PTR_TO_DYNPTR cannot 10073 * be released by any dynptr helper. Hence, unmark_stack_slots_dynptr 10074 * is safe to do directly. 10075 */ 10076 if (arg_type_is_dynptr(fn->arg_type[meta.release_regno - BPF_REG_1])) { 10077 if (regs[meta.release_regno].type == CONST_PTR_TO_DYNPTR) { 10078 verbose(env, "verifier internal error: CONST_PTR_TO_DYNPTR cannot be released\n"); 10079 return -EFAULT; 10080 } 10081 err = unmark_stack_slots_dynptr(env, ®s[meta.release_regno]); 10082 } else if (meta.ref_obj_id) { 10083 err = release_reference(env, meta.ref_obj_id); 10084 } else if (register_is_null(®s[meta.release_regno])) { 10085 /* meta.ref_obj_id can only be 0 if register that is meant to be 10086 * released is NULL, which must be > R0. 10087 */ 10088 err = 0; 10089 } 10090 if (err) { 10091 verbose(env, "func %s#%d reference has not been acquired before\n", 10092 func_id_name(func_id), func_id); 10093 return err; 10094 } 10095 } 10096 10097 switch (func_id) { 10098 case BPF_FUNC_tail_call: 10099 err = check_reference_leak(env); 10100 if (err) { 10101 verbose(env, "tail_call would lead to reference leak\n"); 10102 return err; 10103 } 10104 break; 10105 case BPF_FUNC_get_local_storage: 10106 /* check that flags argument in get_local_storage(map, flags) is 0, 10107 * this is required because get_local_storage() can't return an error. 10108 */ 10109 if (!register_is_null(®s[BPF_REG_2])) { 10110 verbose(env, "get_local_storage() doesn't support non-zero flags\n"); 10111 return -EINVAL; 10112 } 10113 break; 10114 case BPF_FUNC_for_each_map_elem: 10115 err = push_callback_call(env, insn, insn_idx, meta.subprogno, 10116 set_map_elem_callback_state); 10117 break; 10118 case BPF_FUNC_timer_set_callback: 10119 err = push_callback_call(env, insn, insn_idx, meta.subprogno, 10120 set_timer_callback_state); 10121 break; 10122 case BPF_FUNC_find_vma: 10123 err = push_callback_call(env, insn, insn_idx, meta.subprogno, 10124 set_find_vma_callback_state); 10125 break; 10126 case BPF_FUNC_snprintf: 10127 err = check_bpf_snprintf_call(env, regs); 10128 break; 10129 case BPF_FUNC_loop: 10130 update_loop_inline_state(env, meta.subprogno); 10131 /* Verifier relies on R1 value to determine if bpf_loop() iteration 10132 * is finished, thus mark it precise. 10133 */ 10134 err = mark_chain_precision(env, BPF_REG_1); 10135 if (err) 10136 return err; 10137 if (cur_func(env)->callback_depth < regs[BPF_REG_1].umax_value) { 10138 err = push_callback_call(env, insn, insn_idx, meta.subprogno, 10139 set_loop_callback_state); 10140 } else { 10141 cur_func(env)->callback_depth = 0; 10142 if (env->log.level & BPF_LOG_LEVEL2) 10143 verbose(env, "frame%d bpf_loop iteration limit reached\n", 10144 env->cur_state->curframe); 10145 } 10146 break; 10147 case BPF_FUNC_dynptr_from_mem: 10148 if (regs[BPF_REG_1].type != PTR_TO_MAP_VALUE) { 10149 verbose(env, "Unsupported reg type %s for bpf_dynptr_from_mem data\n", 10150 reg_type_str(env, regs[BPF_REG_1].type)); 10151 return -EACCES; 10152 } 10153 break; 10154 case BPF_FUNC_set_retval: 10155 if (prog_type == BPF_PROG_TYPE_LSM && 10156 env->prog->expected_attach_type == BPF_LSM_CGROUP) { 10157 if (!env->prog->aux->attach_func_proto->type) { 10158 /* Make sure programs that attach to void 10159 * hooks don't try to modify return value. 10160 */ 10161 verbose(env, "BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n"); 10162 return -EINVAL; 10163 } 10164 } 10165 break; 10166 case BPF_FUNC_dynptr_data: 10167 { 10168 struct bpf_reg_state *reg; 10169 int id, ref_obj_id; 10170 10171 reg = get_dynptr_arg_reg(env, fn, regs); 10172 if (!reg) 10173 return -EFAULT; 10174 10175 10176 if (meta.dynptr_id) { 10177 verbose(env, "verifier internal error: meta.dynptr_id already set\n"); 10178 return -EFAULT; 10179 } 10180 if (meta.ref_obj_id) { 10181 verbose(env, "verifier internal error: meta.ref_obj_id already set\n"); 10182 return -EFAULT; 10183 } 10184 10185 id = dynptr_id(env, reg); 10186 if (id < 0) { 10187 verbose(env, "verifier internal error: failed to obtain dynptr id\n"); 10188 return id; 10189 } 10190 10191 ref_obj_id = dynptr_ref_obj_id(env, reg); 10192 if (ref_obj_id < 0) { 10193 verbose(env, "verifier internal error: failed to obtain dynptr ref_obj_id\n"); 10194 return ref_obj_id; 10195 } 10196 10197 meta.dynptr_id = id; 10198 meta.ref_obj_id = ref_obj_id; 10199 10200 break; 10201 } 10202 case BPF_FUNC_dynptr_write: 10203 { 10204 enum bpf_dynptr_type dynptr_type; 10205 struct bpf_reg_state *reg; 10206 10207 reg = get_dynptr_arg_reg(env, fn, regs); 10208 if (!reg) 10209 return -EFAULT; 10210 10211 dynptr_type = dynptr_get_type(env, reg); 10212 if (dynptr_type == BPF_DYNPTR_TYPE_INVALID) 10213 return -EFAULT; 10214 10215 if (dynptr_type == BPF_DYNPTR_TYPE_SKB) 10216 /* this will trigger clear_all_pkt_pointers(), which will 10217 * invalidate all dynptr slices associated with the skb 10218 */ 10219 changes_data = true; 10220 10221 break; 10222 } 10223 case BPF_FUNC_user_ringbuf_drain: 10224 err = push_callback_call(env, insn, insn_idx, meta.subprogno, 10225 set_user_ringbuf_callback_state); 10226 break; 10227 } 10228 10229 if (err) 10230 return err; 10231 10232 /* reset caller saved regs */ 10233 for (i = 0; i < CALLER_SAVED_REGS; i++) { 10234 mark_reg_not_init(env, regs, caller_saved[i]); 10235 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK); 10236 } 10237 10238 /* helper call returns 64-bit value. */ 10239 regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG; 10240 10241 /* update return register (already marked as written above) */ 10242 ret_type = fn->ret_type; 10243 ret_flag = type_flag(ret_type); 10244 10245 switch (base_type(ret_type)) { 10246 case RET_INTEGER: 10247 /* sets type to SCALAR_VALUE */ 10248 mark_reg_unknown(env, regs, BPF_REG_0); 10249 break; 10250 case RET_VOID: 10251 regs[BPF_REG_0].type = NOT_INIT; 10252 break; 10253 case RET_PTR_TO_MAP_VALUE: 10254 /* There is no offset yet applied, variable or fixed */ 10255 mark_reg_known_zero(env, regs, BPF_REG_0); 10256 /* remember map_ptr, so that check_map_access() 10257 * can check 'value_size' boundary of memory access 10258 * to map element returned from bpf_map_lookup_elem() 10259 */ 10260 if (meta.map_ptr == NULL) { 10261 verbose(env, 10262 "kernel subsystem misconfigured verifier\n"); 10263 return -EINVAL; 10264 } 10265 regs[BPF_REG_0].map_ptr = meta.map_ptr; 10266 regs[BPF_REG_0].map_uid = meta.map_uid; 10267 regs[BPF_REG_0].type = PTR_TO_MAP_VALUE | ret_flag; 10268 if (!type_may_be_null(ret_type) && 10269 btf_record_has_field(meta.map_ptr->record, BPF_SPIN_LOCK)) { 10270 regs[BPF_REG_0].id = ++env->id_gen; 10271 } 10272 break; 10273 case RET_PTR_TO_SOCKET: 10274 mark_reg_known_zero(env, regs, BPF_REG_0); 10275 regs[BPF_REG_0].type = PTR_TO_SOCKET | ret_flag; 10276 break; 10277 case RET_PTR_TO_SOCK_COMMON: 10278 mark_reg_known_zero(env, regs, BPF_REG_0); 10279 regs[BPF_REG_0].type = PTR_TO_SOCK_COMMON | ret_flag; 10280 break; 10281 case RET_PTR_TO_TCP_SOCK: 10282 mark_reg_known_zero(env, regs, BPF_REG_0); 10283 regs[BPF_REG_0].type = PTR_TO_TCP_SOCK | ret_flag; 10284 break; 10285 case RET_PTR_TO_MEM: 10286 mark_reg_known_zero(env, regs, BPF_REG_0); 10287 regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag; 10288 regs[BPF_REG_0].mem_size = meta.mem_size; 10289 break; 10290 case RET_PTR_TO_MEM_OR_BTF_ID: 10291 { 10292 const struct btf_type *t; 10293 10294 mark_reg_known_zero(env, regs, BPF_REG_0); 10295 t = btf_type_skip_modifiers(meta.ret_btf, meta.ret_btf_id, NULL); 10296 if (!btf_type_is_struct(t)) { 10297 u32 tsize; 10298 const struct btf_type *ret; 10299 const char *tname; 10300 10301 /* resolve the type size of ksym. */ 10302 ret = btf_resolve_size(meta.ret_btf, t, &tsize); 10303 if (IS_ERR(ret)) { 10304 tname = btf_name_by_offset(meta.ret_btf, t->name_off); 10305 verbose(env, "unable to resolve the size of type '%s': %ld\n", 10306 tname, PTR_ERR(ret)); 10307 return -EINVAL; 10308 } 10309 regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag; 10310 regs[BPF_REG_0].mem_size = tsize; 10311 } else { 10312 /* MEM_RDONLY may be carried from ret_flag, but it 10313 * doesn't apply on PTR_TO_BTF_ID. Fold it, otherwise 10314 * it will confuse the check of PTR_TO_BTF_ID in 10315 * check_mem_access(). 10316 */ 10317 ret_flag &= ~MEM_RDONLY; 10318 10319 regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag; 10320 regs[BPF_REG_0].btf = meta.ret_btf; 10321 regs[BPF_REG_0].btf_id = meta.ret_btf_id; 10322 } 10323 break; 10324 } 10325 case RET_PTR_TO_BTF_ID: 10326 { 10327 struct btf *ret_btf; 10328 int ret_btf_id; 10329 10330 mark_reg_known_zero(env, regs, BPF_REG_0); 10331 regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag; 10332 if (func_id == BPF_FUNC_kptr_xchg) { 10333 ret_btf = meta.kptr_field->kptr.btf; 10334 ret_btf_id = meta.kptr_field->kptr.btf_id; 10335 if (!btf_is_kernel(ret_btf)) 10336 regs[BPF_REG_0].type |= MEM_ALLOC; 10337 } else { 10338 if (fn->ret_btf_id == BPF_PTR_POISON) { 10339 verbose(env, "verifier internal error:"); 10340 verbose(env, "func %s has non-overwritten BPF_PTR_POISON return type\n", 10341 func_id_name(func_id)); 10342 return -EINVAL; 10343 } 10344 ret_btf = btf_vmlinux; 10345 ret_btf_id = *fn->ret_btf_id; 10346 } 10347 if (ret_btf_id == 0) { 10348 verbose(env, "invalid return type %u of func %s#%d\n", 10349 base_type(ret_type), func_id_name(func_id), 10350 func_id); 10351 return -EINVAL; 10352 } 10353 regs[BPF_REG_0].btf = ret_btf; 10354 regs[BPF_REG_0].btf_id = ret_btf_id; 10355 break; 10356 } 10357 default: 10358 verbose(env, "unknown return type %u of func %s#%d\n", 10359 base_type(ret_type), func_id_name(func_id), func_id); 10360 return -EINVAL; 10361 } 10362 10363 if (type_may_be_null(regs[BPF_REG_0].type)) 10364 regs[BPF_REG_0].id = ++env->id_gen; 10365 10366 if (helper_multiple_ref_obj_use(func_id, meta.map_ptr)) { 10367 verbose(env, "verifier internal error: func %s#%d sets ref_obj_id more than once\n", 10368 func_id_name(func_id), func_id); 10369 return -EFAULT; 10370 } 10371 10372 if (is_dynptr_ref_function(func_id)) 10373 regs[BPF_REG_0].dynptr_id = meta.dynptr_id; 10374 10375 if (is_ptr_cast_function(func_id) || is_dynptr_ref_function(func_id)) { 10376 /* For release_reference() */ 10377 regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id; 10378 } else if (is_acquire_function(func_id, meta.map_ptr)) { 10379 int id = acquire_reference_state(env, insn_idx); 10380 10381 if (id < 0) 10382 return id; 10383 /* For mark_ptr_or_null_reg() */ 10384 regs[BPF_REG_0].id = id; 10385 /* For release_reference() */ 10386 regs[BPF_REG_0].ref_obj_id = id; 10387 } 10388 10389 do_refine_retval_range(regs, fn->ret_type, func_id, &meta); 10390 10391 err = check_map_func_compatibility(env, meta.map_ptr, func_id); 10392 if (err) 10393 return err; 10394 10395 if ((func_id == BPF_FUNC_get_stack || 10396 func_id == BPF_FUNC_get_task_stack) && 10397 !env->prog->has_callchain_buf) { 10398 const char *err_str; 10399 10400 #ifdef CONFIG_PERF_EVENTS 10401 err = get_callchain_buffers(sysctl_perf_event_max_stack); 10402 err_str = "cannot get callchain buffer for func %s#%d\n"; 10403 #else 10404 err = -ENOTSUPP; 10405 err_str = "func %s#%d not supported without CONFIG_PERF_EVENTS\n"; 10406 #endif 10407 if (err) { 10408 verbose(env, err_str, func_id_name(func_id), func_id); 10409 return err; 10410 } 10411 10412 env->prog->has_callchain_buf = true; 10413 } 10414 10415 if (func_id == BPF_FUNC_get_stackid || func_id == BPF_FUNC_get_stack) 10416 env->prog->call_get_stack = true; 10417 10418 if (func_id == BPF_FUNC_get_func_ip) { 10419 if (check_get_func_ip(env)) 10420 return -ENOTSUPP; 10421 env->prog->call_get_func_ip = true; 10422 } 10423 10424 if (changes_data) 10425 clear_all_pkt_pointers(env); 10426 return 0; 10427 } 10428 10429 /* mark_btf_func_reg_size() is used when the reg size is determined by 10430 * the BTF func_proto's return value size and argument. 10431 */ 10432 static void mark_btf_func_reg_size(struct bpf_verifier_env *env, u32 regno, 10433 size_t reg_size) 10434 { 10435 struct bpf_reg_state *reg = &cur_regs(env)[regno]; 10436 10437 if (regno == BPF_REG_0) { 10438 /* Function return value */ 10439 reg->live |= REG_LIVE_WRITTEN; 10440 reg->subreg_def = reg_size == sizeof(u64) ? 10441 DEF_NOT_SUBREG : env->insn_idx + 1; 10442 } else { 10443 /* Function argument */ 10444 if (reg_size == sizeof(u64)) { 10445 mark_insn_zext(env, reg); 10446 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64); 10447 } else { 10448 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ32); 10449 } 10450 } 10451 } 10452 10453 static bool is_kfunc_acquire(struct bpf_kfunc_call_arg_meta *meta) 10454 { 10455 return meta->kfunc_flags & KF_ACQUIRE; 10456 } 10457 10458 static bool is_kfunc_release(struct bpf_kfunc_call_arg_meta *meta) 10459 { 10460 return meta->kfunc_flags & KF_RELEASE; 10461 } 10462 10463 static bool is_kfunc_trusted_args(struct bpf_kfunc_call_arg_meta *meta) 10464 { 10465 return (meta->kfunc_flags & KF_TRUSTED_ARGS) || is_kfunc_release(meta); 10466 } 10467 10468 static bool is_kfunc_sleepable(struct bpf_kfunc_call_arg_meta *meta) 10469 { 10470 return meta->kfunc_flags & KF_SLEEPABLE; 10471 } 10472 10473 static bool is_kfunc_destructive(struct bpf_kfunc_call_arg_meta *meta) 10474 { 10475 return meta->kfunc_flags & KF_DESTRUCTIVE; 10476 } 10477 10478 static bool is_kfunc_rcu(struct bpf_kfunc_call_arg_meta *meta) 10479 { 10480 return meta->kfunc_flags & KF_RCU; 10481 } 10482 10483 static bool __kfunc_param_match_suffix(const struct btf *btf, 10484 const struct btf_param *arg, 10485 const char *suffix) 10486 { 10487 int suffix_len = strlen(suffix), len; 10488 const char *param_name; 10489 10490 /* In the future, this can be ported to use BTF tagging */ 10491 param_name = btf_name_by_offset(btf, arg->name_off); 10492 if (str_is_empty(param_name)) 10493 return false; 10494 len = strlen(param_name); 10495 if (len < suffix_len) 10496 return false; 10497 param_name += len - suffix_len; 10498 return !strncmp(param_name, suffix, suffix_len); 10499 } 10500 10501 static bool is_kfunc_arg_mem_size(const struct btf *btf, 10502 const struct btf_param *arg, 10503 const struct bpf_reg_state *reg) 10504 { 10505 const struct btf_type *t; 10506 10507 t = btf_type_skip_modifiers(btf, arg->type, NULL); 10508 if (!btf_type_is_scalar(t) || reg->type != SCALAR_VALUE) 10509 return false; 10510 10511 return __kfunc_param_match_suffix(btf, arg, "__sz"); 10512 } 10513 10514 static bool is_kfunc_arg_const_mem_size(const struct btf *btf, 10515 const struct btf_param *arg, 10516 const struct bpf_reg_state *reg) 10517 { 10518 const struct btf_type *t; 10519 10520 t = btf_type_skip_modifiers(btf, arg->type, NULL); 10521 if (!btf_type_is_scalar(t) || reg->type != SCALAR_VALUE) 10522 return false; 10523 10524 return __kfunc_param_match_suffix(btf, arg, "__szk"); 10525 } 10526 10527 static bool is_kfunc_arg_optional(const struct btf *btf, const struct btf_param *arg) 10528 { 10529 return __kfunc_param_match_suffix(btf, arg, "__opt"); 10530 } 10531 10532 static bool is_kfunc_arg_constant(const struct btf *btf, const struct btf_param *arg) 10533 { 10534 return __kfunc_param_match_suffix(btf, arg, "__k"); 10535 } 10536 10537 static bool is_kfunc_arg_ignore(const struct btf *btf, const struct btf_param *arg) 10538 { 10539 return __kfunc_param_match_suffix(btf, arg, "__ign"); 10540 } 10541 10542 static bool is_kfunc_arg_alloc_obj(const struct btf *btf, const struct btf_param *arg) 10543 { 10544 return __kfunc_param_match_suffix(btf, arg, "__alloc"); 10545 } 10546 10547 static bool is_kfunc_arg_uninit(const struct btf *btf, const struct btf_param *arg) 10548 { 10549 return __kfunc_param_match_suffix(btf, arg, "__uninit"); 10550 } 10551 10552 static bool is_kfunc_arg_refcounted_kptr(const struct btf *btf, const struct btf_param *arg) 10553 { 10554 return __kfunc_param_match_suffix(btf, arg, "__refcounted_kptr"); 10555 } 10556 10557 static bool is_kfunc_arg_scalar_with_name(const struct btf *btf, 10558 const struct btf_param *arg, 10559 const char *name) 10560 { 10561 int len, target_len = strlen(name); 10562 const char *param_name; 10563 10564 param_name = btf_name_by_offset(btf, arg->name_off); 10565 if (str_is_empty(param_name)) 10566 return false; 10567 len = strlen(param_name); 10568 if (len != target_len) 10569 return false; 10570 if (strcmp(param_name, name)) 10571 return false; 10572 10573 return true; 10574 } 10575 10576 enum { 10577 KF_ARG_DYNPTR_ID, 10578 KF_ARG_LIST_HEAD_ID, 10579 KF_ARG_LIST_NODE_ID, 10580 KF_ARG_RB_ROOT_ID, 10581 KF_ARG_RB_NODE_ID, 10582 }; 10583 10584 BTF_ID_LIST(kf_arg_btf_ids) 10585 BTF_ID(struct, bpf_dynptr_kern) 10586 BTF_ID(struct, bpf_list_head) 10587 BTF_ID(struct, bpf_list_node) 10588 BTF_ID(struct, bpf_rb_root) 10589 BTF_ID(struct, bpf_rb_node) 10590 10591 static bool __is_kfunc_ptr_arg_type(const struct btf *btf, 10592 const struct btf_param *arg, int type) 10593 { 10594 const struct btf_type *t; 10595 u32 res_id; 10596 10597 t = btf_type_skip_modifiers(btf, arg->type, NULL); 10598 if (!t) 10599 return false; 10600 if (!btf_type_is_ptr(t)) 10601 return false; 10602 t = btf_type_skip_modifiers(btf, t->type, &res_id); 10603 if (!t) 10604 return false; 10605 return btf_types_are_same(btf, res_id, btf_vmlinux, kf_arg_btf_ids[type]); 10606 } 10607 10608 static bool is_kfunc_arg_dynptr(const struct btf *btf, const struct btf_param *arg) 10609 { 10610 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_DYNPTR_ID); 10611 } 10612 10613 static bool is_kfunc_arg_list_head(const struct btf *btf, const struct btf_param *arg) 10614 { 10615 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_LIST_HEAD_ID); 10616 } 10617 10618 static bool is_kfunc_arg_list_node(const struct btf *btf, const struct btf_param *arg) 10619 { 10620 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_LIST_NODE_ID); 10621 } 10622 10623 static bool is_kfunc_arg_rbtree_root(const struct btf *btf, const struct btf_param *arg) 10624 { 10625 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_RB_ROOT_ID); 10626 } 10627 10628 static bool is_kfunc_arg_rbtree_node(const struct btf *btf, const struct btf_param *arg) 10629 { 10630 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_RB_NODE_ID); 10631 } 10632 10633 static bool is_kfunc_arg_callback(struct bpf_verifier_env *env, const struct btf *btf, 10634 const struct btf_param *arg) 10635 { 10636 const struct btf_type *t; 10637 10638 t = btf_type_resolve_func_ptr(btf, arg->type, NULL); 10639 if (!t) 10640 return false; 10641 10642 return true; 10643 } 10644 10645 /* Returns true if struct is composed of scalars, 4 levels of nesting allowed */ 10646 static bool __btf_type_is_scalar_struct(struct bpf_verifier_env *env, 10647 const struct btf *btf, 10648 const struct btf_type *t, int rec) 10649 { 10650 const struct btf_type *member_type; 10651 const struct btf_member *member; 10652 u32 i; 10653 10654 if (!btf_type_is_struct(t)) 10655 return false; 10656 10657 for_each_member(i, t, member) { 10658 const struct btf_array *array; 10659 10660 member_type = btf_type_skip_modifiers(btf, member->type, NULL); 10661 if (btf_type_is_struct(member_type)) { 10662 if (rec >= 3) { 10663 verbose(env, "max struct nesting depth exceeded\n"); 10664 return false; 10665 } 10666 if (!__btf_type_is_scalar_struct(env, btf, member_type, rec + 1)) 10667 return false; 10668 continue; 10669 } 10670 if (btf_type_is_array(member_type)) { 10671 array = btf_array(member_type); 10672 if (!array->nelems) 10673 return false; 10674 member_type = btf_type_skip_modifiers(btf, array->type, NULL); 10675 if (!btf_type_is_scalar(member_type)) 10676 return false; 10677 continue; 10678 } 10679 if (!btf_type_is_scalar(member_type)) 10680 return false; 10681 } 10682 return true; 10683 } 10684 10685 enum kfunc_ptr_arg_type { 10686 KF_ARG_PTR_TO_CTX, 10687 KF_ARG_PTR_TO_ALLOC_BTF_ID, /* Allocated object */ 10688 KF_ARG_PTR_TO_REFCOUNTED_KPTR, /* Refcounted local kptr */ 10689 KF_ARG_PTR_TO_DYNPTR, 10690 KF_ARG_PTR_TO_ITER, 10691 KF_ARG_PTR_TO_LIST_HEAD, 10692 KF_ARG_PTR_TO_LIST_NODE, 10693 KF_ARG_PTR_TO_BTF_ID, /* Also covers reg2btf_ids conversions */ 10694 KF_ARG_PTR_TO_MEM, 10695 KF_ARG_PTR_TO_MEM_SIZE, /* Size derived from next argument, skip it */ 10696 KF_ARG_PTR_TO_CALLBACK, 10697 KF_ARG_PTR_TO_RB_ROOT, 10698 KF_ARG_PTR_TO_RB_NODE, 10699 }; 10700 10701 enum special_kfunc_type { 10702 KF_bpf_obj_new_impl, 10703 KF_bpf_obj_drop_impl, 10704 KF_bpf_refcount_acquire_impl, 10705 KF_bpf_list_push_front_impl, 10706 KF_bpf_list_push_back_impl, 10707 KF_bpf_list_pop_front, 10708 KF_bpf_list_pop_back, 10709 KF_bpf_cast_to_kern_ctx, 10710 KF_bpf_rdonly_cast, 10711 KF_bpf_rcu_read_lock, 10712 KF_bpf_rcu_read_unlock, 10713 KF_bpf_rbtree_remove, 10714 KF_bpf_rbtree_add_impl, 10715 KF_bpf_rbtree_first, 10716 KF_bpf_dynptr_from_skb, 10717 KF_bpf_dynptr_from_xdp, 10718 KF_bpf_dynptr_slice, 10719 KF_bpf_dynptr_slice_rdwr, 10720 KF_bpf_dynptr_clone, 10721 }; 10722 10723 BTF_SET_START(special_kfunc_set) 10724 BTF_ID(func, bpf_obj_new_impl) 10725 BTF_ID(func, bpf_obj_drop_impl) 10726 BTF_ID(func, bpf_refcount_acquire_impl) 10727 BTF_ID(func, bpf_list_push_front_impl) 10728 BTF_ID(func, bpf_list_push_back_impl) 10729 BTF_ID(func, bpf_list_pop_front) 10730 BTF_ID(func, bpf_list_pop_back) 10731 BTF_ID(func, bpf_cast_to_kern_ctx) 10732 BTF_ID(func, bpf_rdonly_cast) 10733 BTF_ID(func, bpf_rbtree_remove) 10734 BTF_ID(func, bpf_rbtree_add_impl) 10735 BTF_ID(func, bpf_rbtree_first) 10736 BTF_ID(func, bpf_dynptr_from_skb) 10737 BTF_ID(func, bpf_dynptr_from_xdp) 10738 BTF_ID(func, bpf_dynptr_slice) 10739 BTF_ID(func, bpf_dynptr_slice_rdwr) 10740 BTF_ID(func, bpf_dynptr_clone) 10741 BTF_SET_END(special_kfunc_set) 10742 10743 BTF_ID_LIST(special_kfunc_list) 10744 BTF_ID(func, bpf_obj_new_impl) 10745 BTF_ID(func, bpf_obj_drop_impl) 10746 BTF_ID(func, bpf_refcount_acquire_impl) 10747 BTF_ID(func, bpf_list_push_front_impl) 10748 BTF_ID(func, bpf_list_push_back_impl) 10749 BTF_ID(func, bpf_list_pop_front) 10750 BTF_ID(func, bpf_list_pop_back) 10751 BTF_ID(func, bpf_cast_to_kern_ctx) 10752 BTF_ID(func, bpf_rdonly_cast) 10753 BTF_ID(func, bpf_rcu_read_lock) 10754 BTF_ID(func, bpf_rcu_read_unlock) 10755 BTF_ID(func, bpf_rbtree_remove) 10756 BTF_ID(func, bpf_rbtree_add_impl) 10757 BTF_ID(func, bpf_rbtree_first) 10758 BTF_ID(func, bpf_dynptr_from_skb) 10759 BTF_ID(func, bpf_dynptr_from_xdp) 10760 BTF_ID(func, bpf_dynptr_slice) 10761 BTF_ID(func, bpf_dynptr_slice_rdwr) 10762 BTF_ID(func, bpf_dynptr_clone) 10763 10764 static bool is_kfunc_ret_null(struct bpf_kfunc_call_arg_meta *meta) 10765 { 10766 if (meta->func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl] && 10767 meta->arg_owning_ref) { 10768 return false; 10769 } 10770 10771 return meta->kfunc_flags & KF_RET_NULL; 10772 } 10773 10774 static bool is_kfunc_bpf_rcu_read_lock(struct bpf_kfunc_call_arg_meta *meta) 10775 { 10776 return meta->func_id == special_kfunc_list[KF_bpf_rcu_read_lock]; 10777 } 10778 10779 static bool is_kfunc_bpf_rcu_read_unlock(struct bpf_kfunc_call_arg_meta *meta) 10780 { 10781 return meta->func_id == special_kfunc_list[KF_bpf_rcu_read_unlock]; 10782 } 10783 10784 static enum kfunc_ptr_arg_type 10785 get_kfunc_ptr_arg_type(struct bpf_verifier_env *env, 10786 struct bpf_kfunc_call_arg_meta *meta, 10787 const struct btf_type *t, const struct btf_type *ref_t, 10788 const char *ref_tname, const struct btf_param *args, 10789 int argno, int nargs) 10790 { 10791 u32 regno = argno + 1; 10792 struct bpf_reg_state *regs = cur_regs(env); 10793 struct bpf_reg_state *reg = ®s[regno]; 10794 bool arg_mem_size = false; 10795 10796 if (meta->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx]) 10797 return KF_ARG_PTR_TO_CTX; 10798 10799 /* In this function, we verify the kfunc's BTF as per the argument type, 10800 * leaving the rest of the verification with respect to the register 10801 * type to our caller. When a set of conditions hold in the BTF type of 10802 * arguments, we resolve it to a known kfunc_ptr_arg_type. 10803 */ 10804 if (btf_get_prog_ctx_type(&env->log, meta->btf, t, resolve_prog_type(env->prog), argno)) 10805 return KF_ARG_PTR_TO_CTX; 10806 10807 if (is_kfunc_arg_alloc_obj(meta->btf, &args[argno])) 10808 return KF_ARG_PTR_TO_ALLOC_BTF_ID; 10809 10810 if (is_kfunc_arg_refcounted_kptr(meta->btf, &args[argno])) 10811 return KF_ARG_PTR_TO_REFCOUNTED_KPTR; 10812 10813 if (is_kfunc_arg_dynptr(meta->btf, &args[argno])) 10814 return KF_ARG_PTR_TO_DYNPTR; 10815 10816 if (is_kfunc_arg_iter(meta, argno)) 10817 return KF_ARG_PTR_TO_ITER; 10818 10819 if (is_kfunc_arg_list_head(meta->btf, &args[argno])) 10820 return KF_ARG_PTR_TO_LIST_HEAD; 10821 10822 if (is_kfunc_arg_list_node(meta->btf, &args[argno])) 10823 return KF_ARG_PTR_TO_LIST_NODE; 10824 10825 if (is_kfunc_arg_rbtree_root(meta->btf, &args[argno])) 10826 return KF_ARG_PTR_TO_RB_ROOT; 10827 10828 if (is_kfunc_arg_rbtree_node(meta->btf, &args[argno])) 10829 return KF_ARG_PTR_TO_RB_NODE; 10830 10831 if ((base_type(reg->type) == PTR_TO_BTF_ID || reg2btf_ids[base_type(reg->type)])) { 10832 if (!btf_type_is_struct(ref_t)) { 10833 verbose(env, "kernel function %s args#%d pointer type %s %s is not supported\n", 10834 meta->func_name, argno, btf_type_str(ref_t), ref_tname); 10835 return -EINVAL; 10836 } 10837 return KF_ARG_PTR_TO_BTF_ID; 10838 } 10839 10840 if (is_kfunc_arg_callback(env, meta->btf, &args[argno])) 10841 return KF_ARG_PTR_TO_CALLBACK; 10842 10843 10844 if (argno + 1 < nargs && 10845 (is_kfunc_arg_mem_size(meta->btf, &args[argno + 1], ®s[regno + 1]) || 10846 is_kfunc_arg_const_mem_size(meta->btf, &args[argno + 1], ®s[regno + 1]))) 10847 arg_mem_size = true; 10848 10849 /* This is the catch all argument type of register types supported by 10850 * check_helper_mem_access. However, we only allow when argument type is 10851 * pointer to scalar, or struct composed (recursively) of scalars. When 10852 * arg_mem_size is true, the pointer can be void *. 10853 */ 10854 if (!btf_type_is_scalar(ref_t) && !__btf_type_is_scalar_struct(env, meta->btf, ref_t, 0) && 10855 (arg_mem_size ? !btf_type_is_void(ref_t) : 1)) { 10856 verbose(env, "arg#%d pointer type %s %s must point to %sscalar, or struct with scalar\n", 10857 argno, btf_type_str(ref_t), ref_tname, arg_mem_size ? "void, " : ""); 10858 return -EINVAL; 10859 } 10860 return arg_mem_size ? KF_ARG_PTR_TO_MEM_SIZE : KF_ARG_PTR_TO_MEM; 10861 } 10862 10863 static int process_kf_arg_ptr_to_btf_id(struct bpf_verifier_env *env, 10864 struct bpf_reg_state *reg, 10865 const struct btf_type *ref_t, 10866 const char *ref_tname, u32 ref_id, 10867 struct bpf_kfunc_call_arg_meta *meta, 10868 int argno) 10869 { 10870 const struct btf_type *reg_ref_t; 10871 bool strict_type_match = false; 10872 const struct btf *reg_btf; 10873 const char *reg_ref_tname; 10874 u32 reg_ref_id; 10875 10876 if (base_type(reg->type) == PTR_TO_BTF_ID) { 10877 reg_btf = reg->btf; 10878 reg_ref_id = reg->btf_id; 10879 } else { 10880 reg_btf = btf_vmlinux; 10881 reg_ref_id = *reg2btf_ids[base_type(reg->type)]; 10882 } 10883 10884 /* Enforce strict type matching for calls to kfuncs that are acquiring 10885 * or releasing a reference, or are no-cast aliases. We do _not_ 10886 * enforce strict matching for plain KF_TRUSTED_ARGS kfuncs by default, 10887 * as we want to enable BPF programs to pass types that are bitwise 10888 * equivalent without forcing them to explicitly cast with something 10889 * like bpf_cast_to_kern_ctx(). 10890 * 10891 * For example, say we had a type like the following: 10892 * 10893 * struct bpf_cpumask { 10894 * cpumask_t cpumask; 10895 * refcount_t usage; 10896 * }; 10897 * 10898 * Note that as specified in <linux/cpumask.h>, cpumask_t is typedef'ed 10899 * to a struct cpumask, so it would be safe to pass a struct 10900 * bpf_cpumask * to a kfunc expecting a struct cpumask *. 10901 * 10902 * The philosophy here is similar to how we allow scalars of different 10903 * types to be passed to kfuncs as long as the size is the same. The 10904 * only difference here is that we're simply allowing 10905 * btf_struct_ids_match() to walk the struct at the 0th offset, and 10906 * resolve types. 10907 */ 10908 if (is_kfunc_acquire(meta) || 10909 (is_kfunc_release(meta) && reg->ref_obj_id) || 10910 btf_type_ids_nocast_alias(&env->log, reg_btf, reg_ref_id, meta->btf, ref_id)) 10911 strict_type_match = true; 10912 10913 WARN_ON_ONCE(is_kfunc_trusted_args(meta) && reg->off); 10914 10915 reg_ref_t = btf_type_skip_modifiers(reg_btf, reg_ref_id, ®_ref_id); 10916 reg_ref_tname = btf_name_by_offset(reg_btf, reg_ref_t->name_off); 10917 if (!btf_struct_ids_match(&env->log, reg_btf, reg_ref_id, reg->off, meta->btf, ref_id, strict_type_match)) { 10918 verbose(env, "kernel function %s args#%d expected pointer to %s %s but R%d has a pointer to %s %s\n", 10919 meta->func_name, argno, btf_type_str(ref_t), ref_tname, argno + 1, 10920 btf_type_str(reg_ref_t), reg_ref_tname); 10921 return -EINVAL; 10922 } 10923 return 0; 10924 } 10925 10926 static int ref_set_non_owning(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 10927 { 10928 struct bpf_verifier_state *state = env->cur_state; 10929 struct btf_record *rec = reg_btf_record(reg); 10930 10931 if (!state->active_lock.ptr) { 10932 verbose(env, "verifier internal error: ref_set_non_owning w/o active lock\n"); 10933 return -EFAULT; 10934 } 10935 10936 if (type_flag(reg->type) & NON_OWN_REF) { 10937 verbose(env, "verifier internal error: NON_OWN_REF already set\n"); 10938 return -EFAULT; 10939 } 10940 10941 reg->type |= NON_OWN_REF; 10942 if (rec->refcount_off >= 0) 10943 reg->type |= MEM_RCU; 10944 10945 return 0; 10946 } 10947 10948 static int ref_convert_owning_non_owning(struct bpf_verifier_env *env, u32 ref_obj_id) 10949 { 10950 struct bpf_func_state *state, *unused; 10951 struct bpf_reg_state *reg; 10952 int i; 10953 10954 state = cur_func(env); 10955 10956 if (!ref_obj_id) { 10957 verbose(env, "verifier internal error: ref_obj_id is zero for " 10958 "owning -> non-owning conversion\n"); 10959 return -EFAULT; 10960 } 10961 10962 for (i = 0; i < state->acquired_refs; i++) { 10963 if (state->refs[i].id != ref_obj_id) 10964 continue; 10965 10966 /* Clear ref_obj_id here so release_reference doesn't clobber 10967 * the whole reg 10968 */ 10969 bpf_for_each_reg_in_vstate(env->cur_state, unused, reg, ({ 10970 if (reg->ref_obj_id == ref_obj_id) { 10971 reg->ref_obj_id = 0; 10972 ref_set_non_owning(env, reg); 10973 } 10974 })); 10975 return 0; 10976 } 10977 10978 verbose(env, "verifier internal error: ref state missing for ref_obj_id\n"); 10979 return -EFAULT; 10980 } 10981 10982 /* Implementation details: 10983 * 10984 * Each register points to some region of memory, which we define as an 10985 * allocation. Each allocation may embed a bpf_spin_lock which protects any 10986 * special BPF objects (bpf_list_head, bpf_rb_root, etc.) part of the same 10987 * allocation. The lock and the data it protects are colocated in the same 10988 * memory region. 10989 * 10990 * Hence, everytime a register holds a pointer value pointing to such 10991 * allocation, the verifier preserves a unique reg->id for it. 10992 * 10993 * The verifier remembers the lock 'ptr' and the lock 'id' whenever 10994 * bpf_spin_lock is called. 10995 * 10996 * To enable this, lock state in the verifier captures two values: 10997 * active_lock.ptr = Register's type specific pointer 10998 * active_lock.id = A unique ID for each register pointer value 10999 * 11000 * Currently, PTR_TO_MAP_VALUE and PTR_TO_BTF_ID | MEM_ALLOC are the two 11001 * supported register types. 11002 * 11003 * The active_lock.ptr in case of map values is the reg->map_ptr, and in case of 11004 * allocated objects is the reg->btf pointer. 11005 * 11006 * The active_lock.id is non-unique for maps supporting direct_value_addr, as we 11007 * can establish the provenance of the map value statically for each distinct 11008 * lookup into such maps. They always contain a single map value hence unique 11009 * IDs for each pseudo load pessimizes the algorithm and rejects valid programs. 11010 * 11011 * So, in case of global variables, they use array maps with max_entries = 1, 11012 * hence their active_lock.ptr becomes map_ptr and id = 0 (since they all point 11013 * into the same map value as max_entries is 1, as described above). 11014 * 11015 * In case of inner map lookups, the inner map pointer has same map_ptr as the 11016 * outer map pointer (in verifier context), but each lookup into an inner map 11017 * assigns a fresh reg->id to the lookup, so while lookups into distinct inner 11018 * maps from the same outer map share the same map_ptr as active_lock.ptr, they 11019 * will get different reg->id assigned to each lookup, hence different 11020 * active_lock.id. 11021 * 11022 * In case of allocated objects, active_lock.ptr is the reg->btf, and the 11023 * reg->id is a unique ID preserved after the NULL pointer check on the pointer 11024 * returned from bpf_obj_new. Each allocation receives a new reg->id. 11025 */ 11026 static int check_reg_allocation_locked(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 11027 { 11028 void *ptr; 11029 u32 id; 11030 11031 switch ((int)reg->type) { 11032 case PTR_TO_MAP_VALUE: 11033 ptr = reg->map_ptr; 11034 break; 11035 case PTR_TO_BTF_ID | MEM_ALLOC: 11036 ptr = reg->btf; 11037 break; 11038 default: 11039 verbose(env, "verifier internal error: unknown reg type for lock check\n"); 11040 return -EFAULT; 11041 } 11042 id = reg->id; 11043 11044 if (!env->cur_state->active_lock.ptr) 11045 return -EINVAL; 11046 if (env->cur_state->active_lock.ptr != ptr || 11047 env->cur_state->active_lock.id != id) { 11048 verbose(env, "held lock and object are not in the same allocation\n"); 11049 return -EINVAL; 11050 } 11051 return 0; 11052 } 11053 11054 static bool is_bpf_list_api_kfunc(u32 btf_id) 11055 { 11056 return btf_id == special_kfunc_list[KF_bpf_list_push_front_impl] || 11057 btf_id == special_kfunc_list[KF_bpf_list_push_back_impl] || 11058 btf_id == special_kfunc_list[KF_bpf_list_pop_front] || 11059 btf_id == special_kfunc_list[KF_bpf_list_pop_back]; 11060 } 11061 11062 static bool is_bpf_rbtree_api_kfunc(u32 btf_id) 11063 { 11064 return btf_id == special_kfunc_list[KF_bpf_rbtree_add_impl] || 11065 btf_id == special_kfunc_list[KF_bpf_rbtree_remove] || 11066 btf_id == special_kfunc_list[KF_bpf_rbtree_first]; 11067 } 11068 11069 static bool is_bpf_graph_api_kfunc(u32 btf_id) 11070 { 11071 return is_bpf_list_api_kfunc(btf_id) || is_bpf_rbtree_api_kfunc(btf_id) || 11072 btf_id == special_kfunc_list[KF_bpf_refcount_acquire_impl]; 11073 } 11074 11075 static bool is_sync_callback_calling_kfunc(u32 btf_id) 11076 { 11077 return btf_id == special_kfunc_list[KF_bpf_rbtree_add_impl]; 11078 } 11079 11080 static bool is_rbtree_lock_required_kfunc(u32 btf_id) 11081 { 11082 return is_bpf_rbtree_api_kfunc(btf_id); 11083 } 11084 11085 static bool check_kfunc_is_graph_root_api(struct bpf_verifier_env *env, 11086 enum btf_field_type head_field_type, 11087 u32 kfunc_btf_id) 11088 { 11089 bool ret; 11090 11091 switch (head_field_type) { 11092 case BPF_LIST_HEAD: 11093 ret = is_bpf_list_api_kfunc(kfunc_btf_id); 11094 break; 11095 case BPF_RB_ROOT: 11096 ret = is_bpf_rbtree_api_kfunc(kfunc_btf_id); 11097 break; 11098 default: 11099 verbose(env, "verifier internal error: unexpected graph root argument type %s\n", 11100 btf_field_type_name(head_field_type)); 11101 return false; 11102 } 11103 11104 if (!ret) 11105 verbose(env, "verifier internal error: %s head arg for unknown kfunc\n", 11106 btf_field_type_name(head_field_type)); 11107 return ret; 11108 } 11109 11110 static bool check_kfunc_is_graph_node_api(struct bpf_verifier_env *env, 11111 enum btf_field_type node_field_type, 11112 u32 kfunc_btf_id) 11113 { 11114 bool ret; 11115 11116 switch (node_field_type) { 11117 case BPF_LIST_NODE: 11118 ret = (kfunc_btf_id == special_kfunc_list[KF_bpf_list_push_front_impl] || 11119 kfunc_btf_id == special_kfunc_list[KF_bpf_list_push_back_impl]); 11120 break; 11121 case BPF_RB_NODE: 11122 ret = (kfunc_btf_id == special_kfunc_list[KF_bpf_rbtree_remove] || 11123 kfunc_btf_id == special_kfunc_list[KF_bpf_rbtree_add_impl]); 11124 break; 11125 default: 11126 verbose(env, "verifier internal error: unexpected graph node argument type %s\n", 11127 btf_field_type_name(node_field_type)); 11128 return false; 11129 } 11130 11131 if (!ret) 11132 verbose(env, "verifier internal error: %s node arg for unknown kfunc\n", 11133 btf_field_type_name(node_field_type)); 11134 return ret; 11135 } 11136 11137 static int 11138 __process_kf_arg_ptr_to_graph_root(struct bpf_verifier_env *env, 11139 struct bpf_reg_state *reg, u32 regno, 11140 struct bpf_kfunc_call_arg_meta *meta, 11141 enum btf_field_type head_field_type, 11142 struct btf_field **head_field) 11143 { 11144 const char *head_type_name; 11145 struct btf_field *field; 11146 struct btf_record *rec; 11147 u32 head_off; 11148 11149 if (meta->btf != btf_vmlinux) { 11150 verbose(env, "verifier internal error: unexpected btf mismatch in kfunc call\n"); 11151 return -EFAULT; 11152 } 11153 11154 if (!check_kfunc_is_graph_root_api(env, head_field_type, meta->func_id)) 11155 return -EFAULT; 11156 11157 head_type_name = btf_field_type_name(head_field_type); 11158 if (!tnum_is_const(reg->var_off)) { 11159 verbose(env, 11160 "R%d doesn't have constant offset. %s has to be at the constant offset\n", 11161 regno, head_type_name); 11162 return -EINVAL; 11163 } 11164 11165 rec = reg_btf_record(reg); 11166 head_off = reg->off + reg->var_off.value; 11167 field = btf_record_find(rec, head_off, head_field_type); 11168 if (!field) { 11169 verbose(env, "%s not found at offset=%u\n", head_type_name, head_off); 11170 return -EINVAL; 11171 } 11172 11173 /* All functions require bpf_list_head to be protected using a bpf_spin_lock */ 11174 if (check_reg_allocation_locked(env, reg)) { 11175 verbose(env, "bpf_spin_lock at off=%d must be held for %s\n", 11176 rec->spin_lock_off, head_type_name); 11177 return -EINVAL; 11178 } 11179 11180 if (*head_field) { 11181 verbose(env, "verifier internal error: repeating %s arg\n", head_type_name); 11182 return -EFAULT; 11183 } 11184 *head_field = field; 11185 return 0; 11186 } 11187 11188 static int process_kf_arg_ptr_to_list_head(struct bpf_verifier_env *env, 11189 struct bpf_reg_state *reg, u32 regno, 11190 struct bpf_kfunc_call_arg_meta *meta) 11191 { 11192 return __process_kf_arg_ptr_to_graph_root(env, reg, regno, meta, BPF_LIST_HEAD, 11193 &meta->arg_list_head.field); 11194 } 11195 11196 static int process_kf_arg_ptr_to_rbtree_root(struct bpf_verifier_env *env, 11197 struct bpf_reg_state *reg, u32 regno, 11198 struct bpf_kfunc_call_arg_meta *meta) 11199 { 11200 return __process_kf_arg_ptr_to_graph_root(env, reg, regno, meta, BPF_RB_ROOT, 11201 &meta->arg_rbtree_root.field); 11202 } 11203 11204 static int 11205 __process_kf_arg_ptr_to_graph_node(struct bpf_verifier_env *env, 11206 struct bpf_reg_state *reg, u32 regno, 11207 struct bpf_kfunc_call_arg_meta *meta, 11208 enum btf_field_type head_field_type, 11209 enum btf_field_type node_field_type, 11210 struct btf_field **node_field) 11211 { 11212 const char *node_type_name; 11213 const struct btf_type *et, *t; 11214 struct btf_field *field; 11215 u32 node_off; 11216 11217 if (meta->btf != btf_vmlinux) { 11218 verbose(env, "verifier internal error: unexpected btf mismatch in kfunc call\n"); 11219 return -EFAULT; 11220 } 11221 11222 if (!check_kfunc_is_graph_node_api(env, node_field_type, meta->func_id)) 11223 return -EFAULT; 11224 11225 node_type_name = btf_field_type_name(node_field_type); 11226 if (!tnum_is_const(reg->var_off)) { 11227 verbose(env, 11228 "R%d doesn't have constant offset. %s has to be at the constant offset\n", 11229 regno, node_type_name); 11230 return -EINVAL; 11231 } 11232 11233 node_off = reg->off + reg->var_off.value; 11234 field = reg_find_field_offset(reg, node_off, node_field_type); 11235 if (!field || field->offset != node_off) { 11236 verbose(env, "%s not found at offset=%u\n", node_type_name, node_off); 11237 return -EINVAL; 11238 } 11239 11240 field = *node_field; 11241 11242 et = btf_type_by_id(field->graph_root.btf, field->graph_root.value_btf_id); 11243 t = btf_type_by_id(reg->btf, reg->btf_id); 11244 if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, 0, field->graph_root.btf, 11245 field->graph_root.value_btf_id, true)) { 11246 verbose(env, "operation on %s expects arg#1 %s at offset=%d " 11247 "in struct %s, but arg is at offset=%d in struct %s\n", 11248 btf_field_type_name(head_field_type), 11249 btf_field_type_name(node_field_type), 11250 field->graph_root.node_offset, 11251 btf_name_by_offset(field->graph_root.btf, et->name_off), 11252 node_off, btf_name_by_offset(reg->btf, t->name_off)); 11253 return -EINVAL; 11254 } 11255 meta->arg_btf = reg->btf; 11256 meta->arg_btf_id = reg->btf_id; 11257 11258 if (node_off != field->graph_root.node_offset) { 11259 verbose(env, "arg#1 offset=%d, but expected %s at offset=%d in struct %s\n", 11260 node_off, btf_field_type_name(node_field_type), 11261 field->graph_root.node_offset, 11262 btf_name_by_offset(field->graph_root.btf, et->name_off)); 11263 return -EINVAL; 11264 } 11265 11266 return 0; 11267 } 11268 11269 static int process_kf_arg_ptr_to_list_node(struct bpf_verifier_env *env, 11270 struct bpf_reg_state *reg, u32 regno, 11271 struct bpf_kfunc_call_arg_meta *meta) 11272 { 11273 return __process_kf_arg_ptr_to_graph_node(env, reg, regno, meta, 11274 BPF_LIST_HEAD, BPF_LIST_NODE, 11275 &meta->arg_list_head.field); 11276 } 11277 11278 static int process_kf_arg_ptr_to_rbtree_node(struct bpf_verifier_env *env, 11279 struct bpf_reg_state *reg, u32 regno, 11280 struct bpf_kfunc_call_arg_meta *meta) 11281 { 11282 return __process_kf_arg_ptr_to_graph_node(env, reg, regno, meta, 11283 BPF_RB_ROOT, BPF_RB_NODE, 11284 &meta->arg_rbtree_root.field); 11285 } 11286 11287 static int check_kfunc_args(struct bpf_verifier_env *env, struct bpf_kfunc_call_arg_meta *meta, 11288 int insn_idx) 11289 { 11290 const char *func_name = meta->func_name, *ref_tname; 11291 const struct btf *btf = meta->btf; 11292 const struct btf_param *args; 11293 struct btf_record *rec; 11294 u32 i, nargs; 11295 int ret; 11296 11297 args = (const struct btf_param *)(meta->func_proto + 1); 11298 nargs = btf_type_vlen(meta->func_proto); 11299 if (nargs > MAX_BPF_FUNC_REG_ARGS) { 11300 verbose(env, "Function %s has %d > %d args\n", func_name, nargs, 11301 MAX_BPF_FUNC_REG_ARGS); 11302 return -EINVAL; 11303 } 11304 11305 /* Check that BTF function arguments match actual types that the 11306 * verifier sees. 11307 */ 11308 for (i = 0; i < nargs; i++) { 11309 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[i + 1]; 11310 const struct btf_type *t, *ref_t, *resolve_ret; 11311 enum bpf_arg_type arg_type = ARG_DONTCARE; 11312 u32 regno = i + 1, ref_id, type_size; 11313 bool is_ret_buf_sz = false; 11314 int kf_arg_type; 11315 11316 t = btf_type_skip_modifiers(btf, args[i].type, NULL); 11317 11318 if (is_kfunc_arg_ignore(btf, &args[i])) 11319 continue; 11320 11321 if (btf_type_is_scalar(t)) { 11322 if (reg->type != SCALAR_VALUE) { 11323 verbose(env, "R%d is not a scalar\n", regno); 11324 return -EINVAL; 11325 } 11326 11327 if (is_kfunc_arg_constant(meta->btf, &args[i])) { 11328 if (meta->arg_constant.found) { 11329 verbose(env, "verifier internal error: only one constant argument permitted\n"); 11330 return -EFAULT; 11331 } 11332 if (!tnum_is_const(reg->var_off)) { 11333 verbose(env, "R%d must be a known constant\n", regno); 11334 return -EINVAL; 11335 } 11336 ret = mark_chain_precision(env, regno); 11337 if (ret < 0) 11338 return ret; 11339 meta->arg_constant.found = true; 11340 meta->arg_constant.value = reg->var_off.value; 11341 } else if (is_kfunc_arg_scalar_with_name(btf, &args[i], "rdonly_buf_size")) { 11342 meta->r0_rdonly = true; 11343 is_ret_buf_sz = true; 11344 } else if (is_kfunc_arg_scalar_with_name(btf, &args[i], "rdwr_buf_size")) { 11345 is_ret_buf_sz = true; 11346 } 11347 11348 if (is_ret_buf_sz) { 11349 if (meta->r0_size) { 11350 verbose(env, "2 or more rdonly/rdwr_buf_size parameters for kfunc"); 11351 return -EINVAL; 11352 } 11353 11354 if (!tnum_is_const(reg->var_off)) { 11355 verbose(env, "R%d is not a const\n", regno); 11356 return -EINVAL; 11357 } 11358 11359 meta->r0_size = reg->var_off.value; 11360 ret = mark_chain_precision(env, regno); 11361 if (ret) 11362 return ret; 11363 } 11364 continue; 11365 } 11366 11367 if (!btf_type_is_ptr(t)) { 11368 verbose(env, "Unrecognized arg#%d type %s\n", i, btf_type_str(t)); 11369 return -EINVAL; 11370 } 11371 11372 if ((is_kfunc_trusted_args(meta) || is_kfunc_rcu(meta)) && 11373 (register_is_null(reg) || type_may_be_null(reg->type))) { 11374 verbose(env, "Possibly NULL pointer passed to trusted arg%d\n", i); 11375 return -EACCES; 11376 } 11377 11378 if (reg->ref_obj_id) { 11379 if (is_kfunc_release(meta) && meta->ref_obj_id) { 11380 verbose(env, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n", 11381 regno, reg->ref_obj_id, 11382 meta->ref_obj_id); 11383 return -EFAULT; 11384 } 11385 meta->ref_obj_id = reg->ref_obj_id; 11386 if (is_kfunc_release(meta)) 11387 meta->release_regno = regno; 11388 } 11389 11390 ref_t = btf_type_skip_modifiers(btf, t->type, &ref_id); 11391 ref_tname = btf_name_by_offset(btf, ref_t->name_off); 11392 11393 kf_arg_type = get_kfunc_ptr_arg_type(env, meta, t, ref_t, ref_tname, args, i, nargs); 11394 if (kf_arg_type < 0) 11395 return kf_arg_type; 11396 11397 switch (kf_arg_type) { 11398 case KF_ARG_PTR_TO_ALLOC_BTF_ID: 11399 case KF_ARG_PTR_TO_BTF_ID: 11400 if (!is_kfunc_trusted_args(meta) && !is_kfunc_rcu(meta)) 11401 break; 11402 11403 if (!is_trusted_reg(reg)) { 11404 if (!is_kfunc_rcu(meta)) { 11405 verbose(env, "R%d must be referenced or trusted\n", regno); 11406 return -EINVAL; 11407 } 11408 if (!is_rcu_reg(reg)) { 11409 verbose(env, "R%d must be a rcu pointer\n", regno); 11410 return -EINVAL; 11411 } 11412 } 11413 11414 fallthrough; 11415 case KF_ARG_PTR_TO_CTX: 11416 /* Trusted arguments have the same offset checks as release arguments */ 11417 arg_type |= OBJ_RELEASE; 11418 break; 11419 case KF_ARG_PTR_TO_DYNPTR: 11420 case KF_ARG_PTR_TO_ITER: 11421 case KF_ARG_PTR_TO_LIST_HEAD: 11422 case KF_ARG_PTR_TO_LIST_NODE: 11423 case KF_ARG_PTR_TO_RB_ROOT: 11424 case KF_ARG_PTR_TO_RB_NODE: 11425 case KF_ARG_PTR_TO_MEM: 11426 case KF_ARG_PTR_TO_MEM_SIZE: 11427 case KF_ARG_PTR_TO_CALLBACK: 11428 case KF_ARG_PTR_TO_REFCOUNTED_KPTR: 11429 /* Trusted by default */ 11430 break; 11431 default: 11432 WARN_ON_ONCE(1); 11433 return -EFAULT; 11434 } 11435 11436 if (is_kfunc_release(meta) && reg->ref_obj_id) 11437 arg_type |= OBJ_RELEASE; 11438 ret = check_func_arg_reg_off(env, reg, regno, arg_type); 11439 if (ret < 0) 11440 return ret; 11441 11442 switch (kf_arg_type) { 11443 case KF_ARG_PTR_TO_CTX: 11444 if (reg->type != PTR_TO_CTX) { 11445 verbose(env, "arg#%d expected pointer to ctx, but got %s\n", i, btf_type_str(t)); 11446 return -EINVAL; 11447 } 11448 11449 if (meta->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx]) { 11450 ret = get_kern_ctx_btf_id(&env->log, resolve_prog_type(env->prog)); 11451 if (ret < 0) 11452 return -EINVAL; 11453 meta->ret_btf_id = ret; 11454 } 11455 break; 11456 case KF_ARG_PTR_TO_ALLOC_BTF_ID: 11457 if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) { 11458 verbose(env, "arg#%d expected pointer to allocated object\n", i); 11459 return -EINVAL; 11460 } 11461 if (!reg->ref_obj_id) { 11462 verbose(env, "allocated object must be referenced\n"); 11463 return -EINVAL; 11464 } 11465 if (meta->btf == btf_vmlinux && 11466 meta->func_id == special_kfunc_list[KF_bpf_obj_drop_impl]) { 11467 meta->arg_btf = reg->btf; 11468 meta->arg_btf_id = reg->btf_id; 11469 } 11470 break; 11471 case KF_ARG_PTR_TO_DYNPTR: 11472 { 11473 enum bpf_arg_type dynptr_arg_type = ARG_PTR_TO_DYNPTR; 11474 int clone_ref_obj_id = 0; 11475 11476 if (reg->type != PTR_TO_STACK && 11477 reg->type != CONST_PTR_TO_DYNPTR) { 11478 verbose(env, "arg#%d expected pointer to stack or dynptr_ptr\n", i); 11479 return -EINVAL; 11480 } 11481 11482 if (reg->type == CONST_PTR_TO_DYNPTR) 11483 dynptr_arg_type |= MEM_RDONLY; 11484 11485 if (is_kfunc_arg_uninit(btf, &args[i])) 11486 dynptr_arg_type |= MEM_UNINIT; 11487 11488 if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_from_skb]) { 11489 dynptr_arg_type |= DYNPTR_TYPE_SKB; 11490 } else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_from_xdp]) { 11491 dynptr_arg_type |= DYNPTR_TYPE_XDP; 11492 } else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_clone] && 11493 (dynptr_arg_type & MEM_UNINIT)) { 11494 enum bpf_dynptr_type parent_type = meta->initialized_dynptr.type; 11495 11496 if (parent_type == BPF_DYNPTR_TYPE_INVALID) { 11497 verbose(env, "verifier internal error: no dynptr type for parent of clone\n"); 11498 return -EFAULT; 11499 } 11500 11501 dynptr_arg_type |= (unsigned int)get_dynptr_type_flag(parent_type); 11502 clone_ref_obj_id = meta->initialized_dynptr.ref_obj_id; 11503 if (dynptr_type_refcounted(parent_type) && !clone_ref_obj_id) { 11504 verbose(env, "verifier internal error: missing ref obj id for parent of clone\n"); 11505 return -EFAULT; 11506 } 11507 } 11508 11509 ret = process_dynptr_func(env, regno, insn_idx, dynptr_arg_type, clone_ref_obj_id); 11510 if (ret < 0) 11511 return ret; 11512 11513 if (!(dynptr_arg_type & MEM_UNINIT)) { 11514 int id = dynptr_id(env, reg); 11515 11516 if (id < 0) { 11517 verbose(env, "verifier internal error: failed to obtain dynptr id\n"); 11518 return id; 11519 } 11520 meta->initialized_dynptr.id = id; 11521 meta->initialized_dynptr.type = dynptr_get_type(env, reg); 11522 meta->initialized_dynptr.ref_obj_id = dynptr_ref_obj_id(env, reg); 11523 } 11524 11525 break; 11526 } 11527 case KF_ARG_PTR_TO_ITER: 11528 ret = process_iter_arg(env, regno, insn_idx, meta); 11529 if (ret < 0) 11530 return ret; 11531 break; 11532 case KF_ARG_PTR_TO_LIST_HEAD: 11533 if (reg->type != PTR_TO_MAP_VALUE && 11534 reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) { 11535 verbose(env, "arg#%d expected pointer to map value or allocated object\n", i); 11536 return -EINVAL; 11537 } 11538 if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC) && !reg->ref_obj_id) { 11539 verbose(env, "allocated object must be referenced\n"); 11540 return -EINVAL; 11541 } 11542 ret = process_kf_arg_ptr_to_list_head(env, reg, regno, meta); 11543 if (ret < 0) 11544 return ret; 11545 break; 11546 case KF_ARG_PTR_TO_RB_ROOT: 11547 if (reg->type != PTR_TO_MAP_VALUE && 11548 reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) { 11549 verbose(env, "arg#%d expected pointer to map value or allocated object\n", i); 11550 return -EINVAL; 11551 } 11552 if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC) && !reg->ref_obj_id) { 11553 verbose(env, "allocated object must be referenced\n"); 11554 return -EINVAL; 11555 } 11556 ret = process_kf_arg_ptr_to_rbtree_root(env, reg, regno, meta); 11557 if (ret < 0) 11558 return ret; 11559 break; 11560 case KF_ARG_PTR_TO_LIST_NODE: 11561 if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) { 11562 verbose(env, "arg#%d expected pointer to allocated object\n", i); 11563 return -EINVAL; 11564 } 11565 if (!reg->ref_obj_id) { 11566 verbose(env, "allocated object must be referenced\n"); 11567 return -EINVAL; 11568 } 11569 ret = process_kf_arg_ptr_to_list_node(env, reg, regno, meta); 11570 if (ret < 0) 11571 return ret; 11572 break; 11573 case KF_ARG_PTR_TO_RB_NODE: 11574 if (meta->func_id == special_kfunc_list[KF_bpf_rbtree_remove]) { 11575 if (!type_is_non_owning_ref(reg->type) || reg->ref_obj_id) { 11576 verbose(env, "rbtree_remove node input must be non-owning ref\n"); 11577 return -EINVAL; 11578 } 11579 if (in_rbtree_lock_required_cb(env)) { 11580 verbose(env, "rbtree_remove not allowed in rbtree cb\n"); 11581 return -EINVAL; 11582 } 11583 } else { 11584 if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) { 11585 verbose(env, "arg#%d expected pointer to allocated object\n", i); 11586 return -EINVAL; 11587 } 11588 if (!reg->ref_obj_id) { 11589 verbose(env, "allocated object must be referenced\n"); 11590 return -EINVAL; 11591 } 11592 } 11593 11594 ret = process_kf_arg_ptr_to_rbtree_node(env, reg, regno, meta); 11595 if (ret < 0) 11596 return ret; 11597 break; 11598 case KF_ARG_PTR_TO_BTF_ID: 11599 /* Only base_type is checked, further checks are done here */ 11600 if ((base_type(reg->type) != PTR_TO_BTF_ID || 11601 (bpf_type_has_unsafe_modifiers(reg->type) && !is_rcu_reg(reg))) && 11602 !reg2btf_ids[base_type(reg->type)]) { 11603 verbose(env, "arg#%d is %s ", i, reg_type_str(env, reg->type)); 11604 verbose(env, "expected %s or socket\n", 11605 reg_type_str(env, base_type(reg->type) | 11606 (type_flag(reg->type) & BPF_REG_TRUSTED_MODIFIERS))); 11607 return -EINVAL; 11608 } 11609 ret = process_kf_arg_ptr_to_btf_id(env, reg, ref_t, ref_tname, ref_id, meta, i); 11610 if (ret < 0) 11611 return ret; 11612 break; 11613 case KF_ARG_PTR_TO_MEM: 11614 resolve_ret = btf_resolve_size(btf, ref_t, &type_size); 11615 if (IS_ERR(resolve_ret)) { 11616 verbose(env, "arg#%d reference type('%s %s') size cannot be determined: %ld\n", 11617 i, btf_type_str(ref_t), ref_tname, PTR_ERR(resolve_ret)); 11618 return -EINVAL; 11619 } 11620 ret = check_mem_reg(env, reg, regno, type_size); 11621 if (ret < 0) 11622 return ret; 11623 break; 11624 case KF_ARG_PTR_TO_MEM_SIZE: 11625 { 11626 struct bpf_reg_state *buff_reg = ®s[regno]; 11627 const struct btf_param *buff_arg = &args[i]; 11628 struct bpf_reg_state *size_reg = ®s[regno + 1]; 11629 const struct btf_param *size_arg = &args[i + 1]; 11630 11631 if (!register_is_null(buff_reg) || !is_kfunc_arg_optional(meta->btf, buff_arg)) { 11632 ret = check_kfunc_mem_size_reg(env, size_reg, regno + 1); 11633 if (ret < 0) { 11634 verbose(env, "arg#%d arg#%d memory, len pair leads to invalid memory access\n", i, i + 1); 11635 return ret; 11636 } 11637 } 11638 11639 if (is_kfunc_arg_const_mem_size(meta->btf, size_arg, size_reg)) { 11640 if (meta->arg_constant.found) { 11641 verbose(env, "verifier internal error: only one constant argument permitted\n"); 11642 return -EFAULT; 11643 } 11644 if (!tnum_is_const(size_reg->var_off)) { 11645 verbose(env, "R%d must be a known constant\n", regno + 1); 11646 return -EINVAL; 11647 } 11648 meta->arg_constant.found = true; 11649 meta->arg_constant.value = size_reg->var_off.value; 11650 } 11651 11652 /* Skip next '__sz' or '__szk' argument */ 11653 i++; 11654 break; 11655 } 11656 case KF_ARG_PTR_TO_CALLBACK: 11657 if (reg->type != PTR_TO_FUNC) { 11658 verbose(env, "arg%d expected pointer to func\n", i); 11659 return -EINVAL; 11660 } 11661 meta->subprogno = reg->subprogno; 11662 break; 11663 case KF_ARG_PTR_TO_REFCOUNTED_KPTR: 11664 if (!type_is_ptr_alloc_obj(reg->type)) { 11665 verbose(env, "arg#%d is neither owning or non-owning ref\n", i); 11666 return -EINVAL; 11667 } 11668 if (!type_is_non_owning_ref(reg->type)) 11669 meta->arg_owning_ref = true; 11670 11671 rec = reg_btf_record(reg); 11672 if (!rec) { 11673 verbose(env, "verifier internal error: Couldn't find btf_record\n"); 11674 return -EFAULT; 11675 } 11676 11677 if (rec->refcount_off < 0) { 11678 verbose(env, "arg#%d doesn't point to a type with bpf_refcount field\n", i); 11679 return -EINVAL; 11680 } 11681 11682 meta->arg_btf = reg->btf; 11683 meta->arg_btf_id = reg->btf_id; 11684 break; 11685 } 11686 } 11687 11688 if (is_kfunc_release(meta) && !meta->release_regno) { 11689 verbose(env, "release kernel function %s expects refcounted PTR_TO_BTF_ID\n", 11690 func_name); 11691 return -EINVAL; 11692 } 11693 11694 return 0; 11695 } 11696 11697 static int fetch_kfunc_meta(struct bpf_verifier_env *env, 11698 struct bpf_insn *insn, 11699 struct bpf_kfunc_call_arg_meta *meta, 11700 const char **kfunc_name) 11701 { 11702 const struct btf_type *func, *func_proto; 11703 u32 func_id, *kfunc_flags; 11704 const char *func_name; 11705 struct btf *desc_btf; 11706 11707 if (kfunc_name) 11708 *kfunc_name = NULL; 11709 11710 if (!insn->imm) 11711 return -EINVAL; 11712 11713 desc_btf = find_kfunc_desc_btf(env, insn->off); 11714 if (IS_ERR(desc_btf)) 11715 return PTR_ERR(desc_btf); 11716 11717 func_id = insn->imm; 11718 func = btf_type_by_id(desc_btf, func_id); 11719 func_name = btf_name_by_offset(desc_btf, func->name_off); 11720 if (kfunc_name) 11721 *kfunc_name = func_name; 11722 func_proto = btf_type_by_id(desc_btf, func->type); 11723 11724 kfunc_flags = btf_kfunc_id_set_contains(desc_btf, func_id, env->prog); 11725 if (!kfunc_flags) { 11726 return -EACCES; 11727 } 11728 11729 memset(meta, 0, sizeof(*meta)); 11730 meta->btf = desc_btf; 11731 meta->func_id = func_id; 11732 meta->kfunc_flags = *kfunc_flags; 11733 meta->func_proto = func_proto; 11734 meta->func_name = func_name; 11735 11736 return 0; 11737 } 11738 11739 static int check_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn, 11740 int *insn_idx_p) 11741 { 11742 const struct btf_type *t, *ptr_type; 11743 u32 i, nargs, ptr_type_id, release_ref_obj_id; 11744 struct bpf_reg_state *regs = cur_regs(env); 11745 const char *func_name, *ptr_type_name; 11746 bool sleepable, rcu_lock, rcu_unlock; 11747 struct bpf_kfunc_call_arg_meta meta; 11748 struct bpf_insn_aux_data *insn_aux; 11749 int err, insn_idx = *insn_idx_p; 11750 const struct btf_param *args; 11751 const struct btf_type *ret_t; 11752 struct btf *desc_btf; 11753 11754 /* skip for now, but return error when we find this in fixup_kfunc_call */ 11755 if (!insn->imm) 11756 return 0; 11757 11758 err = fetch_kfunc_meta(env, insn, &meta, &func_name); 11759 if (err == -EACCES && func_name) 11760 verbose(env, "calling kernel function %s is not allowed\n", func_name); 11761 if (err) 11762 return err; 11763 desc_btf = meta.btf; 11764 insn_aux = &env->insn_aux_data[insn_idx]; 11765 11766 insn_aux->is_iter_next = is_iter_next_kfunc(&meta); 11767 11768 if (is_kfunc_destructive(&meta) && !capable(CAP_SYS_BOOT)) { 11769 verbose(env, "destructive kfunc calls require CAP_SYS_BOOT capability\n"); 11770 return -EACCES; 11771 } 11772 11773 sleepable = is_kfunc_sleepable(&meta); 11774 if (sleepable && !env->prog->aux->sleepable) { 11775 verbose(env, "program must be sleepable to call sleepable kfunc %s\n", func_name); 11776 return -EACCES; 11777 } 11778 11779 /* Check the arguments */ 11780 err = check_kfunc_args(env, &meta, insn_idx); 11781 if (err < 0) 11782 return err; 11783 11784 if (meta.func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) { 11785 err = push_callback_call(env, insn, insn_idx, meta.subprogno, 11786 set_rbtree_add_callback_state); 11787 if (err) { 11788 verbose(env, "kfunc %s#%d failed callback verification\n", 11789 func_name, meta.func_id); 11790 return err; 11791 } 11792 } 11793 11794 rcu_lock = is_kfunc_bpf_rcu_read_lock(&meta); 11795 rcu_unlock = is_kfunc_bpf_rcu_read_unlock(&meta); 11796 11797 if (env->cur_state->active_rcu_lock) { 11798 struct bpf_func_state *state; 11799 struct bpf_reg_state *reg; 11800 11801 if (in_rbtree_lock_required_cb(env) && (rcu_lock || rcu_unlock)) { 11802 verbose(env, "Calling bpf_rcu_read_{lock,unlock} in unnecessary rbtree callback\n"); 11803 return -EACCES; 11804 } 11805 11806 if (rcu_lock) { 11807 verbose(env, "nested rcu read lock (kernel function %s)\n", func_name); 11808 return -EINVAL; 11809 } else if (rcu_unlock) { 11810 bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({ 11811 if (reg->type & MEM_RCU) { 11812 reg->type &= ~(MEM_RCU | PTR_MAYBE_NULL); 11813 reg->type |= PTR_UNTRUSTED; 11814 } 11815 })); 11816 env->cur_state->active_rcu_lock = false; 11817 } else if (sleepable) { 11818 verbose(env, "kernel func %s is sleepable within rcu_read_lock region\n", func_name); 11819 return -EACCES; 11820 } 11821 } else if (rcu_lock) { 11822 env->cur_state->active_rcu_lock = true; 11823 } else if (rcu_unlock) { 11824 verbose(env, "unmatched rcu read unlock (kernel function %s)\n", func_name); 11825 return -EINVAL; 11826 } 11827 11828 /* In case of release function, we get register number of refcounted 11829 * PTR_TO_BTF_ID in bpf_kfunc_arg_meta, do the release now. 11830 */ 11831 if (meta.release_regno) { 11832 err = release_reference(env, regs[meta.release_regno].ref_obj_id); 11833 if (err) { 11834 verbose(env, "kfunc %s#%d reference has not been acquired before\n", 11835 func_name, meta.func_id); 11836 return err; 11837 } 11838 } 11839 11840 if (meta.func_id == special_kfunc_list[KF_bpf_list_push_front_impl] || 11841 meta.func_id == special_kfunc_list[KF_bpf_list_push_back_impl] || 11842 meta.func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) { 11843 release_ref_obj_id = regs[BPF_REG_2].ref_obj_id; 11844 insn_aux->insert_off = regs[BPF_REG_2].off; 11845 insn_aux->kptr_struct_meta = btf_find_struct_meta(meta.arg_btf, meta.arg_btf_id); 11846 err = ref_convert_owning_non_owning(env, release_ref_obj_id); 11847 if (err) { 11848 verbose(env, "kfunc %s#%d conversion of owning ref to non-owning failed\n", 11849 func_name, meta.func_id); 11850 return err; 11851 } 11852 11853 err = release_reference(env, release_ref_obj_id); 11854 if (err) { 11855 verbose(env, "kfunc %s#%d reference has not been acquired before\n", 11856 func_name, meta.func_id); 11857 return err; 11858 } 11859 } 11860 11861 for (i = 0; i < CALLER_SAVED_REGS; i++) 11862 mark_reg_not_init(env, regs, caller_saved[i]); 11863 11864 /* Check return type */ 11865 t = btf_type_skip_modifiers(desc_btf, meta.func_proto->type, NULL); 11866 11867 if (is_kfunc_acquire(&meta) && !btf_type_is_struct_ptr(meta.btf, t)) { 11868 /* Only exception is bpf_obj_new_impl */ 11869 if (meta.btf != btf_vmlinux || 11870 (meta.func_id != special_kfunc_list[KF_bpf_obj_new_impl] && 11871 meta.func_id != special_kfunc_list[KF_bpf_refcount_acquire_impl])) { 11872 verbose(env, "acquire kernel function does not return PTR_TO_BTF_ID\n"); 11873 return -EINVAL; 11874 } 11875 } 11876 11877 if (btf_type_is_scalar(t)) { 11878 mark_reg_unknown(env, regs, BPF_REG_0); 11879 mark_btf_func_reg_size(env, BPF_REG_0, t->size); 11880 } else if (btf_type_is_ptr(t)) { 11881 ptr_type = btf_type_skip_modifiers(desc_btf, t->type, &ptr_type_id); 11882 11883 if (meta.btf == btf_vmlinux && btf_id_set_contains(&special_kfunc_set, meta.func_id)) { 11884 if (meta.func_id == special_kfunc_list[KF_bpf_obj_new_impl]) { 11885 struct btf *ret_btf; 11886 u32 ret_btf_id; 11887 11888 if (unlikely(!bpf_global_ma_set)) 11889 return -ENOMEM; 11890 11891 if (((u64)(u32)meta.arg_constant.value) != meta.arg_constant.value) { 11892 verbose(env, "local type ID argument must be in range [0, U32_MAX]\n"); 11893 return -EINVAL; 11894 } 11895 11896 ret_btf = env->prog->aux->btf; 11897 ret_btf_id = meta.arg_constant.value; 11898 11899 /* This may be NULL due to user not supplying a BTF */ 11900 if (!ret_btf) { 11901 verbose(env, "bpf_obj_new requires prog BTF\n"); 11902 return -EINVAL; 11903 } 11904 11905 ret_t = btf_type_by_id(ret_btf, ret_btf_id); 11906 if (!ret_t || !__btf_type_is_struct(ret_t)) { 11907 verbose(env, "bpf_obj_new type ID argument must be of a struct\n"); 11908 return -EINVAL; 11909 } 11910 11911 mark_reg_known_zero(env, regs, BPF_REG_0); 11912 regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC; 11913 regs[BPF_REG_0].btf = ret_btf; 11914 regs[BPF_REG_0].btf_id = ret_btf_id; 11915 11916 insn_aux->obj_new_size = ret_t->size; 11917 insn_aux->kptr_struct_meta = 11918 btf_find_struct_meta(ret_btf, ret_btf_id); 11919 } else if (meta.func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl]) { 11920 mark_reg_known_zero(env, regs, BPF_REG_0); 11921 regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC; 11922 regs[BPF_REG_0].btf = meta.arg_btf; 11923 regs[BPF_REG_0].btf_id = meta.arg_btf_id; 11924 11925 insn_aux->kptr_struct_meta = 11926 btf_find_struct_meta(meta.arg_btf, 11927 meta.arg_btf_id); 11928 } else if (meta.func_id == special_kfunc_list[KF_bpf_list_pop_front] || 11929 meta.func_id == special_kfunc_list[KF_bpf_list_pop_back]) { 11930 struct btf_field *field = meta.arg_list_head.field; 11931 11932 mark_reg_graph_node(regs, BPF_REG_0, &field->graph_root); 11933 } else if (meta.func_id == special_kfunc_list[KF_bpf_rbtree_remove] || 11934 meta.func_id == special_kfunc_list[KF_bpf_rbtree_first]) { 11935 struct btf_field *field = meta.arg_rbtree_root.field; 11936 11937 mark_reg_graph_node(regs, BPF_REG_0, &field->graph_root); 11938 } else if (meta.func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx]) { 11939 mark_reg_known_zero(env, regs, BPF_REG_0); 11940 regs[BPF_REG_0].type = PTR_TO_BTF_ID | PTR_TRUSTED; 11941 regs[BPF_REG_0].btf = desc_btf; 11942 regs[BPF_REG_0].btf_id = meta.ret_btf_id; 11943 } else if (meta.func_id == special_kfunc_list[KF_bpf_rdonly_cast]) { 11944 ret_t = btf_type_by_id(desc_btf, meta.arg_constant.value); 11945 if (!ret_t || !btf_type_is_struct(ret_t)) { 11946 verbose(env, 11947 "kfunc bpf_rdonly_cast type ID argument must be of a struct\n"); 11948 return -EINVAL; 11949 } 11950 11951 mark_reg_known_zero(env, regs, BPF_REG_0); 11952 regs[BPF_REG_0].type = PTR_TO_BTF_ID | PTR_UNTRUSTED; 11953 regs[BPF_REG_0].btf = desc_btf; 11954 regs[BPF_REG_0].btf_id = meta.arg_constant.value; 11955 } else if (meta.func_id == special_kfunc_list[KF_bpf_dynptr_slice] || 11956 meta.func_id == special_kfunc_list[KF_bpf_dynptr_slice_rdwr]) { 11957 enum bpf_type_flag type_flag = get_dynptr_type_flag(meta.initialized_dynptr.type); 11958 11959 mark_reg_known_zero(env, regs, BPF_REG_0); 11960 11961 if (!meta.arg_constant.found) { 11962 verbose(env, "verifier internal error: bpf_dynptr_slice(_rdwr) no constant size\n"); 11963 return -EFAULT; 11964 } 11965 11966 regs[BPF_REG_0].mem_size = meta.arg_constant.value; 11967 11968 /* PTR_MAYBE_NULL will be added when is_kfunc_ret_null is checked */ 11969 regs[BPF_REG_0].type = PTR_TO_MEM | type_flag; 11970 11971 if (meta.func_id == special_kfunc_list[KF_bpf_dynptr_slice]) { 11972 regs[BPF_REG_0].type |= MEM_RDONLY; 11973 } else { 11974 /* this will set env->seen_direct_write to true */ 11975 if (!may_access_direct_pkt_data(env, NULL, BPF_WRITE)) { 11976 verbose(env, "the prog does not allow writes to packet data\n"); 11977 return -EINVAL; 11978 } 11979 } 11980 11981 if (!meta.initialized_dynptr.id) { 11982 verbose(env, "verifier internal error: no dynptr id\n"); 11983 return -EFAULT; 11984 } 11985 regs[BPF_REG_0].dynptr_id = meta.initialized_dynptr.id; 11986 11987 /* we don't need to set BPF_REG_0's ref obj id 11988 * because packet slices are not refcounted (see 11989 * dynptr_type_refcounted) 11990 */ 11991 } else { 11992 verbose(env, "kernel function %s unhandled dynamic return type\n", 11993 meta.func_name); 11994 return -EFAULT; 11995 } 11996 } else if (!__btf_type_is_struct(ptr_type)) { 11997 if (!meta.r0_size) { 11998 __u32 sz; 11999 12000 if (!IS_ERR(btf_resolve_size(desc_btf, ptr_type, &sz))) { 12001 meta.r0_size = sz; 12002 meta.r0_rdonly = true; 12003 } 12004 } 12005 if (!meta.r0_size) { 12006 ptr_type_name = btf_name_by_offset(desc_btf, 12007 ptr_type->name_off); 12008 verbose(env, 12009 "kernel function %s returns pointer type %s %s is not supported\n", 12010 func_name, 12011 btf_type_str(ptr_type), 12012 ptr_type_name); 12013 return -EINVAL; 12014 } 12015 12016 mark_reg_known_zero(env, regs, BPF_REG_0); 12017 regs[BPF_REG_0].type = PTR_TO_MEM; 12018 regs[BPF_REG_0].mem_size = meta.r0_size; 12019 12020 if (meta.r0_rdonly) 12021 regs[BPF_REG_0].type |= MEM_RDONLY; 12022 12023 /* Ensures we don't access the memory after a release_reference() */ 12024 if (meta.ref_obj_id) 12025 regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id; 12026 } else { 12027 mark_reg_known_zero(env, regs, BPF_REG_0); 12028 regs[BPF_REG_0].btf = desc_btf; 12029 regs[BPF_REG_0].type = PTR_TO_BTF_ID; 12030 regs[BPF_REG_0].btf_id = ptr_type_id; 12031 12032 if (is_iter_next_kfunc(&meta)) { 12033 struct bpf_reg_state *cur_iter; 12034 12035 cur_iter = get_iter_from_state(env->cur_state, &meta); 12036 12037 if (cur_iter->type & MEM_RCU) /* KF_RCU_PROTECTED */ 12038 regs[BPF_REG_0].type |= MEM_RCU; 12039 else 12040 regs[BPF_REG_0].type |= PTR_TRUSTED; 12041 } 12042 } 12043 12044 if (is_kfunc_ret_null(&meta)) { 12045 regs[BPF_REG_0].type |= PTR_MAYBE_NULL; 12046 /* For mark_ptr_or_null_reg, see 93c230e3f5bd6 */ 12047 regs[BPF_REG_0].id = ++env->id_gen; 12048 } 12049 mark_btf_func_reg_size(env, BPF_REG_0, sizeof(void *)); 12050 if (is_kfunc_acquire(&meta)) { 12051 int id = acquire_reference_state(env, insn_idx); 12052 12053 if (id < 0) 12054 return id; 12055 if (is_kfunc_ret_null(&meta)) 12056 regs[BPF_REG_0].id = id; 12057 regs[BPF_REG_0].ref_obj_id = id; 12058 } else if (meta.func_id == special_kfunc_list[KF_bpf_rbtree_first]) { 12059 ref_set_non_owning(env, ®s[BPF_REG_0]); 12060 } 12061 12062 if (reg_may_point_to_spin_lock(®s[BPF_REG_0]) && !regs[BPF_REG_0].id) 12063 regs[BPF_REG_0].id = ++env->id_gen; 12064 } else if (btf_type_is_void(t)) { 12065 if (meta.btf == btf_vmlinux && btf_id_set_contains(&special_kfunc_set, meta.func_id)) { 12066 if (meta.func_id == special_kfunc_list[KF_bpf_obj_drop_impl]) { 12067 insn_aux->kptr_struct_meta = 12068 btf_find_struct_meta(meta.arg_btf, 12069 meta.arg_btf_id); 12070 } 12071 } 12072 } 12073 12074 nargs = btf_type_vlen(meta.func_proto); 12075 args = (const struct btf_param *)(meta.func_proto + 1); 12076 for (i = 0; i < nargs; i++) { 12077 u32 regno = i + 1; 12078 12079 t = btf_type_skip_modifiers(desc_btf, args[i].type, NULL); 12080 if (btf_type_is_ptr(t)) 12081 mark_btf_func_reg_size(env, regno, sizeof(void *)); 12082 else 12083 /* scalar. ensured by btf_check_kfunc_arg_match() */ 12084 mark_btf_func_reg_size(env, regno, t->size); 12085 } 12086 12087 if (is_iter_next_kfunc(&meta)) { 12088 err = process_iter_next_call(env, insn_idx, &meta); 12089 if (err) 12090 return err; 12091 } 12092 12093 return 0; 12094 } 12095 12096 static bool signed_add_overflows(s64 a, s64 b) 12097 { 12098 /* Do the add in u64, where overflow is well-defined */ 12099 s64 res = (s64)((u64)a + (u64)b); 12100 12101 if (b < 0) 12102 return res > a; 12103 return res < a; 12104 } 12105 12106 static bool signed_add32_overflows(s32 a, s32 b) 12107 { 12108 /* Do the add in u32, where overflow is well-defined */ 12109 s32 res = (s32)((u32)a + (u32)b); 12110 12111 if (b < 0) 12112 return res > a; 12113 return res < a; 12114 } 12115 12116 static bool signed_sub_overflows(s64 a, s64 b) 12117 { 12118 /* Do the sub in u64, where overflow is well-defined */ 12119 s64 res = (s64)((u64)a - (u64)b); 12120 12121 if (b < 0) 12122 return res < a; 12123 return res > a; 12124 } 12125 12126 static bool signed_sub32_overflows(s32 a, s32 b) 12127 { 12128 /* Do the sub in u32, where overflow is well-defined */ 12129 s32 res = (s32)((u32)a - (u32)b); 12130 12131 if (b < 0) 12132 return res < a; 12133 return res > a; 12134 } 12135 12136 static bool check_reg_sane_offset(struct bpf_verifier_env *env, 12137 const struct bpf_reg_state *reg, 12138 enum bpf_reg_type type) 12139 { 12140 bool known = tnum_is_const(reg->var_off); 12141 s64 val = reg->var_off.value; 12142 s64 smin = reg->smin_value; 12143 12144 if (known && (val >= BPF_MAX_VAR_OFF || val <= -BPF_MAX_VAR_OFF)) { 12145 verbose(env, "math between %s pointer and %lld is not allowed\n", 12146 reg_type_str(env, type), val); 12147 return false; 12148 } 12149 12150 if (reg->off >= BPF_MAX_VAR_OFF || reg->off <= -BPF_MAX_VAR_OFF) { 12151 verbose(env, "%s pointer offset %d is not allowed\n", 12152 reg_type_str(env, type), reg->off); 12153 return false; 12154 } 12155 12156 if (smin == S64_MIN) { 12157 verbose(env, "math between %s pointer and register with unbounded min value is not allowed\n", 12158 reg_type_str(env, type)); 12159 return false; 12160 } 12161 12162 if (smin >= BPF_MAX_VAR_OFF || smin <= -BPF_MAX_VAR_OFF) { 12163 verbose(env, "value %lld makes %s pointer be out of bounds\n", 12164 smin, reg_type_str(env, type)); 12165 return false; 12166 } 12167 12168 return true; 12169 } 12170 12171 enum { 12172 REASON_BOUNDS = -1, 12173 REASON_TYPE = -2, 12174 REASON_PATHS = -3, 12175 REASON_LIMIT = -4, 12176 REASON_STACK = -5, 12177 }; 12178 12179 static int retrieve_ptr_limit(const struct bpf_reg_state *ptr_reg, 12180 u32 *alu_limit, bool mask_to_left) 12181 { 12182 u32 max = 0, ptr_limit = 0; 12183 12184 switch (ptr_reg->type) { 12185 case PTR_TO_STACK: 12186 /* Offset 0 is out-of-bounds, but acceptable start for the 12187 * left direction, see BPF_REG_FP. Also, unknown scalar 12188 * offset where we would need to deal with min/max bounds is 12189 * currently prohibited for unprivileged. 12190 */ 12191 max = MAX_BPF_STACK + mask_to_left; 12192 ptr_limit = -(ptr_reg->var_off.value + ptr_reg->off); 12193 break; 12194 case PTR_TO_MAP_VALUE: 12195 max = ptr_reg->map_ptr->value_size; 12196 ptr_limit = (mask_to_left ? 12197 ptr_reg->smin_value : 12198 ptr_reg->umax_value) + ptr_reg->off; 12199 break; 12200 default: 12201 return REASON_TYPE; 12202 } 12203 12204 if (ptr_limit >= max) 12205 return REASON_LIMIT; 12206 *alu_limit = ptr_limit; 12207 return 0; 12208 } 12209 12210 static bool can_skip_alu_sanitation(const struct bpf_verifier_env *env, 12211 const struct bpf_insn *insn) 12212 { 12213 return env->bypass_spec_v1 || BPF_SRC(insn->code) == BPF_K; 12214 } 12215 12216 static int update_alu_sanitation_state(struct bpf_insn_aux_data *aux, 12217 u32 alu_state, u32 alu_limit) 12218 { 12219 /* If we arrived here from different branches with different 12220 * state or limits to sanitize, then this won't work. 12221 */ 12222 if (aux->alu_state && 12223 (aux->alu_state != alu_state || 12224 aux->alu_limit != alu_limit)) 12225 return REASON_PATHS; 12226 12227 /* Corresponding fixup done in do_misc_fixups(). */ 12228 aux->alu_state = alu_state; 12229 aux->alu_limit = alu_limit; 12230 return 0; 12231 } 12232 12233 static int sanitize_val_alu(struct bpf_verifier_env *env, 12234 struct bpf_insn *insn) 12235 { 12236 struct bpf_insn_aux_data *aux = cur_aux(env); 12237 12238 if (can_skip_alu_sanitation(env, insn)) 12239 return 0; 12240 12241 return update_alu_sanitation_state(aux, BPF_ALU_NON_POINTER, 0); 12242 } 12243 12244 static bool sanitize_needed(u8 opcode) 12245 { 12246 return opcode == BPF_ADD || opcode == BPF_SUB; 12247 } 12248 12249 struct bpf_sanitize_info { 12250 struct bpf_insn_aux_data aux; 12251 bool mask_to_left; 12252 }; 12253 12254 static struct bpf_verifier_state * 12255 sanitize_speculative_path(struct bpf_verifier_env *env, 12256 const struct bpf_insn *insn, 12257 u32 next_idx, u32 curr_idx) 12258 { 12259 struct bpf_verifier_state *branch; 12260 struct bpf_reg_state *regs; 12261 12262 branch = push_stack(env, next_idx, curr_idx, true); 12263 if (branch && insn) { 12264 regs = branch->frame[branch->curframe]->regs; 12265 if (BPF_SRC(insn->code) == BPF_K) { 12266 mark_reg_unknown(env, regs, insn->dst_reg); 12267 } else if (BPF_SRC(insn->code) == BPF_X) { 12268 mark_reg_unknown(env, regs, insn->dst_reg); 12269 mark_reg_unknown(env, regs, insn->src_reg); 12270 } 12271 } 12272 return branch; 12273 } 12274 12275 static int sanitize_ptr_alu(struct bpf_verifier_env *env, 12276 struct bpf_insn *insn, 12277 const struct bpf_reg_state *ptr_reg, 12278 const struct bpf_reg_state *off_reg, 12279 struct bpf_reg_state *dst_reg, 12280 struct bpf_sanitize_info *info, 12281 const bool commit_window) 12282 { 12283 struct bpf_insn_aux_data *aux = commit_window ? cur_aux(env) : &info->aux; 12284 struct bpf_verifier_state *vstate = env->cur_state; 12285 bool off_is_imm = tnum_is_const(off_reg->var_off); 12286 bool off_is_neg = off_reg->smin_value < 0; 12287 bool ptr_is_dst_reg = ptr_reg == dst_reg; 12288 u8 opcode = BPF_OP(insn->code); 12289 u32 alu_state, alu_limit; 12290 struct bpf_reg_state tmp; 12291 bool ret; 12292 int err; 12293 12294 if (can_skip_alu_sanitation(env, insn)) 12295 return 0; 12296 12297 /* We already marked aux for masking from non-speculative 12298 * paths, thus we got here in the first place. We only care 12299 * to explore bad access from here. 12300 */ 12301 if (vstate->speculative) 12302 goto do_sim; 12303 12304 if (!commit_window) { 12305 if (!tnum_is_const(off_reg->var_off) && 12306 (off_reg->smin_value < 0) != (off_reg->smax_value < 0)) 12307 return REASON_BOUNDS; 12308 12309 info->mask_to_left = (opcode == BPF_ADD && off_is_neg) || 12310 (opcode == BPF_SUB && !off_is_neg); 12311 } 12312 12313 err = retrieve_ptr_limit(ptr_reg, &alu_limit, info->mask_to_left); 12314 if (err < 0) 12315 return err; 12316 12317 if (commit_window) { 12318 /* In commit phase we narrow the masking window based on 12319 * the observed pointer move after the simulated operation. 12320 */ 12321 alu_state = info->aux.alu_state; 12322 alu_limit = abs(info->aux.alu_limit - alu_limit); 12323 } else { 12324 alu_state = off_is_neg ? BPF_ALU_NEG_VALUE : 0; 12325 alu_state |= off_is_imm ? BPF_ALU_IMMEDIATE : 0; 12326 alu_state |= ptr_is_dst_reg ? 12327 BPF_ALU_SANITIZE_SRC : BPF_ALU_SANITIZE_DST; 12328 12329 /* Limit pruning on unknown scalars to enable deep search for 12330 * potential masking differences from other program paths. 12331 */ 12332 if (!off_is_imm) 12333 env->explore_alu_limits = true; 12334 } 12335 12336 err = update_alu_sanitation_state(aux, alu_state, alu_limit); 12337 if (err < 0) 12338 return err; 12339 do_sim: 12340 /* If we're in commit phase, we're done here given we already 12341 * pushed the truncated dst_reg into the speculative verification 12342 * stack. 12343 * 12344 * Also, when register is a known constant, we rewrite register-based 12345 * operation to immediate-based, and thus do not need masking (and as 12346 * a consequence, do not need to simulate the zero-truncation either). 12347 */ 12348 if (commit_window || off_is_imm) 12349 return 0; 12350 12351 /* Simulate and find potential out-of-bounds access under 12352 * speculative execution from truncation as a result of 12353 * masking when off was not within expected range. If off 12354 * sits in dst, then we temporarily need to move ptr there 12355 * to simulate dst (== 0) +/-= ptr. Needed, for example, 12356 * for cases where we use K-based arithmetic in one direction 12357 * and truncated reg-based in the other in order to explore 12358 * bad access. 12359 */ 12360 if (!ptr_is_dst_reg) { 12361 tmp = *dst_reg; 12362 copy_register_state(dst_reg, ptr_reg); 12363 } 12364 ret = sanitize_speculative_path(env, NULL, env->insn_idx + 1, 12365 env->insn_idx); 12366 if (!ptr_is_dst_reg && ret) 12367 *dst_reg = tmp; 12368 return !ret ? REASON_STACK : 0; 12369 } 12370 12371 static void sanitize_mark_insn_seen(struct bpf_verifier_env *env) 12372 { 12373 struct bpf_verifier_state *vstate = env->cur_state; 12374 12375 /* If we simulate paths under speculation, we don't update the 12376 * insn as 'seen' such that when we verify unreachable paths in 12377 * the non-speculative domain, sanitize_dead_code() can still 12378 * rewrite/sanitize them. 12379 */ 12380 if (!vstate->speculative) 12381 env->insn_aux_data[env->insn_idx].seen = env->pass_cnt; 12382 } 12383 12384 static int sanitize_err(struct bpf_verifier_env *env, 12385 const struct bpf_insn *insn, int reason, 12386 const struct bpf_reg_state *off_reg, 12387 const struct bpf_reg_state *dst_reg) 12388 { 12389 static const char *err = "pointer arithmetic with it prohibited for !root"; 12390 const char *op = BPF_OP(insn->code) == BPF_ADD ? "add" : "sub"; 12391 u32 dst = insn->dst_reg, src = insn->src_reg; 12392 12393 switch (reason) { 12394 case REASON_BOUNDS: 12395 verbose(env, "R%d has unknown scalar with mixed signed bounds, %s\n", 12396 off_reg == dst_reg ? dst : src, err); 12397 break; 12398 case REASON_TYPE: 12399 verbose(env, "R%d has pointer with unsupported alu operation, %s\n", 12400 off_reg == dst_reg ? src : dst, err); 12401 break; 12402 case REASON_PATHS: 12403 verbose(env, "R%d tried to %s from different maps, paths or scalars, %s\n", 12404 dst, op, err); 12405 break; 12406 case REASON_LIMIT: 12407 verbose(env, "R%d tried to %s beyond pointer bounds, %s\n", 12408 dst, op, err); 12409 break; 12410 case REASON_STACK: 12411 verbose(env, "R%d could not be pushed for speculative verification, %s\n", 12412 dst, err); 12413 break; 12414 default: 12415 verbose(env, "verifier internal error: unknown reason (%d)\n", 12416 reason); 12417 break; 12418 } 12419 12420 return -EACCES; 12421 } 12422 12423 /* check that stack access falls within stack limits and that 'reg' doesn't 12424 * have a variable offset. 12425 * 12426 * Variable offset is prohibited for unprivileged mode for simplicity since it 12427 * requires corresponding support in Spectre masking for stack ALU. See also 12428 * retrieve_ptr_limit(). 12429 * 12430 * 12431 * 'off' includes 'reg->off'. 12432 */ 12433 static int check_stack_access_for_ptr_arithmetic( 12434 struct bpf_verifier_env *env, 12435 int regno, 12436 const struct bpf_reg_state *reg, 12437 int off) 12438 { 12439 if (!tnum_is_const(reg->var_off)) { 12440 char tn_buf[48]; 12441 12442 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 12443 verbose(env, "R%d variable stack access prohibited for !root, var_off=%s off=%d\n", 12444 regno, tn_buf, off); 12445 return -EACCES; 12446 } 12447 12448 if (off >= 0 || off < -MAX_BPF_STACK) { 12449 verbose(env, "R%d stack pointer arithmetic goes out of range, " 12450 "prohibited for !root; off=%d\n", regno, off); 12451 return -EACCES; 12452 } 12453 12454 return 0; 12455 } 12456 12457 static int sanitize_check_bounds(struct bpf_verifier_env *env, 12458 const struct bpf_insn *insn, 12459 const struct bpf_reg_state *dst_reg) 12460 { 12461 u32 dst = insn->dst_reg; 12462 12463 /* For unprivileged we require that resulting offset must be in bounds 12464 * in order to be able to sanitize access later on. 12465 */ 12466 if (env->bypass_spec_v1) 12467 return 0; 12468 12469 switch (dst_reg->type) { 12470 case PTR_TO_STACK: 12471 if (check_stack_access_for_ptr_arithmetic(env, dst, dst_reg, 12472 dst_reg->off + dst_reg->var_off.value)) 12473 return -EACCES; 12474 break; 12475 case PTR_TO_MAP_VALUE: 12476 if (check_map_access(env, dst, dst_reg->off, 1, false, ACCESS_HELPER)) { 12477 verbose(env, "R%d pointer arithmetic of map value goes out of range, " 12478 "prohibited for !root\n", dst); 12479 return -EACCES; 12480 } 12481 break; 12482 default: 12483 break; 12484 } 12485 12486 return 0; 12487 } 12488 12489 /* Handles arithmetic on a pointer and a scalar: computes new min/max and var_off. 12490 * Caller should also handle BPF_MOV case separately. 12491 * If we return -EACCES, caller may want to try again treating pointer as a 12492 * scalar. So we only emit a diagnostic if !env->allow_ptr_leaks. 12493 */ 12494 static int adjust_ptr_min_max_vals(struct bpf_verifier_env *env, 12495 struct bpf_insn *insn, 12496 const struct bpf_reg_state *ptr_reg, 12497 const struct bpf_reg_state *off_reg) 12498 { 12499 struct bpf_verifier_state *vstate = env->cur_state; 12500 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 12501 struct bpf_reg_state *regs = state->regs, *dst_reg; 12502 bool known = tnum_is_const(off_reg->var_off); 12503 s64 smin_val = off_reg->smin_value, smax_val = off_reg->smax_value, 12504 smin_ptr = ptr_reg->smin_value, smax_ptr = ptr_reg->smax_value; 12505 u64 umin_val = off_reg->umin_value, umax_val = off_reg->umax_value, 12506 umin_ptr = ptr_reg->umin_value, umax_ptr = ptr_reg->umax_value; 12507 struct bpf_sanitize_info info = {}; 12508 u8 opcode = BPF_OP(insn->code); 12509 u32 dst = insn->dst_reg; 12510 int ret; 12511 12512 dst_reg = ®s[dst]; 12513 12514 if ((known && (smin_val != smax_val || umin_val != umax_val)) || 12515 smin_val > smax_val || umin_val > umax_val) { 12516 /* Taint dst register if offset had invalid bounds derived from 12517 * e.g. dead branches. 12518 */ 12519 __mark_reg_unknown(env, dst_reg); 12520 return 0; 12521 } 12522 12523 if (BPF_CLASS(insn->code) != BPF_ALU64) { 12524 /* 32-bit ALU ops on pointers produce (meaningless) scalars */ 12525 if (opcode == BPF_SUB && env->allow_ptr_leaks) { 12526 __mark_reg_unknown(env, dst_reg); 12527 return 0; 12528 } 12529 12530 verbose(env, 12531 "R%d 32-bit pointer arithmetic prohibited\n", 12532 dst); 12533 return -EACCES; 12534 } 12535 12536 if (ptr_reg->type & PTR_MAYBE_NULL) { 12537 verbose(env, "R%d pointer arithmetic on %s prohibited, null-check it first\n", 12538 dst, reg_type_str(env, ptr_reg->type)); 12539 return -EACCES; 12540 } 12541 12542 switch (base_type(ptr_reg->type)) { 12543 case PTR_TO_FLOW_KEYS: 12544 if (known) 12545 break; 12546 fallthrough; 12547 case CONST_PTR_TO_MAP: 12548 /* smin_val represents the known value */ 12549 if (known && smin_val == 0 && opcode == BPF_ADD) 12550 break; 12551 fallthrough; 12552 case PTR_TO_PACKET_END: 12553 case PTR_TO_SOCKET: 12554 case PTR_TO_SOCK_COMMON: 12555 case PTR_TO_TCP_SOCK: 12556 case PTR_TO_XDP_SOCK: 12557 verbose(env, "R%d pointer arithmetic on %s prohibited\n", 12558 dst, reg_type_str(env, ptr_reg->type)); 12559 return -EACCES; 12560 default: 12561 break; 12562 } 12563 12564 /* In case of 'scalar += pointer', dst_reg inherits pointer type and id. 12565 * The id may be overwritten later if we create a new variable offset. 12566 */ 12567 dst_reg->type = ptr_reg->type; 12568 dst_reg->id = ptr_reg->id; 12569 12570 if (!check_reg_sane_offset(env, off_reg, ptr_reg->type) || 12571 !check_reg_sane_offset(env, ptr_reg, ptr_reg->type)) 12572 return -EINVAL; 12573 12574 /* pointer types do not carry 32-bit bounds at the moment. */ 12575 __mark_reg32_unbounded(dst_reg); 12576 12577 if (sanitize_needed(opcode)) { 12578 ret = sanitize_ptr_alu(env, insn, ptr_reg, off_reg, dst_reg, 12579 &info, false); 12580 if (ret < 0) 12581 return sanitize_err(env, insn, ret, off_reg, dst_reg); 12582 } 12583 12584 switch (opcode) { 12585 case BPF_ADD: 12586 /* We can take a fixed offset as long as it doesn't overflow 12587 * the s32 'off' field 12588 */ 12589 if (known && (ptr_reg->off + smin_val == 12590 (s64)(s32)(ptr_reg->off + smin_val))) { 12591 /* pointer += K. Accumulate it into fixed offset */ 12592 dst_reg->smin_value = smin_ptr; 12593 dst_reg->smax_value = smax_ptr; 12594 dst_reg->umin_value = umin_ptr; 12595 dst_reg->umax_value = umax_ptr; 12596 dst_reg->var_off = ptr_reg->var_off; 12597 dst_reg->off = ptr_reg->off + smin_val; 12598 dst_reg->raw = ptr_reg->raw; 12599 break; 12600 } 12601 /* A new variable offset is created. Note that off_reg->off 12602 * == 0, since it's a scalar. 12603 * dst_reg gets the pointer type and since some positive 12604 * integer value was added to the pointer, give it a new 'id' 12605 * if it's a PTR_TO_PACKET. 12606 * this creates a new 'base' pointer, off_reg (variable) gets 12607 * added into the variable offset, and we copy the fixed offset 12608 * from ptr_reg. 12609 */ 12610 if (signed_add_overflows(smin_ptr, smin_val) || 12611 signed_add_overflows(smax_ptr, smax_val)) { 12612 dst_reg->smin_value = S64_MIN; 12613 dst_reg->smax_value = S64_MAX; 12614 } else { 12615 dst_reg->smin_value = smin_ptr + smin_val; 12616 dst_reg->smax_value = smax_ptr + smax_val; 12617 } 12618 if (umin_ptr + umin_val < umin_ptr || 12619 umax_ptr + umax_val < umax_ptr) { 12620 dst_reg->umin_value = 0; 12621 dst_reg->umax_value = U64_MAX; 12622 } else { 12623 dst_reg->umin_value = umin_ptr + umin_val; 12624 dst_reg->umax_value = umax_ptr + umax_val; 12625 } 12626 dst_reg->var_off = tnum_add(ptr_reg->var_off, off_reg->var_off); 12627 dst_reg->off = ptr_reg->off; 12628 dst_reg->raw = ptr_reg->raw; 12629 if (reg_is_pkt_pointer(ptr_reg)) { 12630 dst_reg->id = ++env->id_gen; 12631 /* something was added to pkt_ptr, set range to zero */ 12632 memset(&dst_reg->raw, 0, sizeof(dst_reg->raw)); 12633 } 12634 break; 12635 case BPF_SUB: 12636 if (dst_reg == off_reg) { 12637 /* scalar -= pointer. Creates an unknown scalar */ 12638 verbose(env, "R%d tried to subtract pointer from scalar\n", 12639 dst); 12640 return -EACCES; 12641 } 12642 /* We don't allow subtraction from FP, because (according to 12643 * test_verifier.c test "invalid fp arithmetic", JITs might not 12644 * be able to deal with it. 12645 */ 12646 if (ptr_reg->type == PTR_TO_STACK) { 12647 verbose(env, "R%d subtraction from stack pointer prohibited\n", 12648 dst); 12649 return -EACCES; 12650 } 12651 if (known && (ptr_reg->off - smin_val == 12652 (s64)(s32)(ptr_reg->off - smin_val))) { 12653 /* pointer -= K. Subtract it from fixed offset */ 12654 dst_reg->smin_value = smin_ptr; 12655 dst_reg->smax_value = smax_ptr; 12656 dst_reg->umin_value = umin_ptr; 12657 dst_reg->umax_value = umax_ptr; 12658 dst_reg->var_off = ptr_reg->var_off; 12659 dst_reg->id = ptr_reg->id; 12660 dst_reg->off = ptr_reg->off - smin_val; 12661 dst_reg->raw = ptr_reg->raw; 12662 break; 12663 } 12664 /* A new variable offset is created. If the subtrahend is known 12665 * nonnegative, then any reg->range we had before is still good. 12666 */ 12667 if (signed_sub_overflows(smin_ptr, smax_val) || 12668 signed_sub_overflows(smax_ptr, smin_val)) { 12669 /* Overflow possible, we know nothing */ 12670 dst_reg->smin_value = S64_MIN; 12671 dst_reg->smax_value = S64_MAX; 12672 } else { 12673 dst_reg->smin_value = smin_ptr - smax_val; 12674 dst_reg->smax_value = smax_ptr - smin_val; 12675 } 12676 if (umin_ptr < umax_val) { 12677 /* Overflow possible, we know nothing */ 12678 dst_reg->umin_value = 0; 12679 dst_reg->umax_value = U64_MAX; 12680 } else { 12681 /* Cannot overflow (as long as bounds are consistent) */ 12682 dst_reg->umin_value = umin_ptr - umax_val; 12683 dst_reg->umax_value = umax_ptr - umin_val; 12684 } 12685 dst_reg->var_off = tnum_sub(ptr_reg->var_off, off_reg->var_off); 12686 dst_reg->off = ptr_reg->off; 12687 dst_reg->raw = ptr_reg->raw; 12688 if (reg_is_pkt_pointer(ptr_reg)) { 12689 dst_reg->id = ++env->id_gen; 12690 /* something was added to pkt_ptr, set range to zero */ 12691 if (smin_val < 0) 12692 memset(&dst_reg->raw, 0, sizeof(dst_reg->raw)); 12693 } 12694 break; 12695 case BPF_AND: 12696 case BPF_OR: 12697 case BPF_XOR: 12698 /* bitwise ops on pointers are troublesome, prohibit. */ 12699 verbose(env, "R%d bitwise operator %s on pointer prohibited\n", 12700 dst, bpf_alu_string[opcode >> 4]); 12701 return -EACCES; 12702 default: 12703 /* other operators (e.g. MUL,LSH) produce non-pointer results */ 12704 verbose(env, "R%d pointer arithmetic with %s operator prohibited\n", 12705 dst, bpf_alu_string[opcode >> 4]); 12706 return -EACCES; 12707 } 12708 12709 if (!check_reg_sane_offset(env, dst_reg, ptr_reg->type)) 12710 return -EINVAL; 12711 reg_bounds_sync(dst_reg); 12712 if (sanitize_check_bounds(env, insn, dst_reg) < 0) 12713 return -EACCES; 12714 if (sanitize_needed(opcode)) { 12715 ret = sanitize_ptr_alu(env, insn, dst_reg, off_reg, dst_reg, 12716 &info, true); 12717 if (ret < 0) 12718 return sanitize_err(env, insn, ret, off_reg, dst_reg); 12719 } 12720 12721 return 0; 12722 } 12723 12724 static void scalar32_min_max_add(struct bpf_reg_state *dst_reg, 12725 struct bpf_reg_state *src_reg) 12726 { 12727 s32 smin_val = src_reg->s32_min_value; 12728 s32 smax_val = src_reg->s32_max_value; 12729 u32 umin_val = src_reg->u32_min_value; 12730 u32 umax_val = src_reg->u32_max_value; 12731 12732 if (signed_add32_overflows(dst_reg->s32_min_value, smin_val) || 12733 signed_add32_overflows(dst_reg->s32_max_value, smax_val)) { 12734 dst_reg->s32_min_value = S32_MIN; 12735 dst_reg->s32_max_value = S32_MAX; 12736 } else { 12737 dst_reg->s32_min_value += smin_val; 12738 dst_reg->s32_max_value += smax_val; 12739 } 12740 if (dst_reg->u32_min_value + umin_val < umin_val || 12741 dst_reg->u32_max_value + umax_val < umax_val) { 12742 dst_reg->u32_min_value = 0; 12743 dst_reg->u32_max_value = U32_MAX; 12744 } else { 12745 dst_reg->u32_min_value += umin_val; 12746 dst_reg->u32_max_value += umax_val; 12747 } 12748 } 12749 12750 static void scalar_min_max_add(struct bpf_reg_state *dst_reg, 12751 struct bpf_reg_state *src_reg) 12752 { 12753 s64 smin_val = src_reg->smin_value; 12754 s64 smax_val = src_reg->smax_value; 12755 u64 umin_val = src_reg->umin_value; 12756 u64 umax_val = src_reg->umax_value; 12757 12758 if (signed_add_overflows(dst_reg->smin_value, smin_val) || 12759 signed_add_overflows(dst_reg->smax_value, smax_val)) { 12760 dst_reg->smin_value = S64_MIN; 12761 dst_reg->smax_value = S64_MAX; 12762 } else { 12763 dst_reg->smin_value += smin_val; 12764 dst_reg->smax_value += smax_val; 12765 } 12766 if (dst_reg->umin_value + umin_val < umin_val || 12767 dst_reg->umax_value + umax_val < umax_val) { 12768 dst_reg->umin_value = 0; 12769 dst_reg->umax_value = U64_MAX; 12770 } else { 12771 dst_reg->umin_value += umin_val; 12772 dst_reg->umax_value += umax_val; 12773 } 12774 } 12775 12776 static void scalar32_min_max_sub(struct bpf_reg_state *dst_reg, 12777 struct bpf_reg_state *src_reg) 12778 { 12779 s32 smin_val = src_reg->s32_min_value; 12780 s32 smax_val = src_reg->s32_max_value; 12781 u32 umin_val = src_reg->u32_min_value; 12782 u32 umax_val = src_reg->u32_max_value; 12783 12784 if (signed_sub32_overflows(dst_reg->s32_min_value, smax_val) || 12785 signed_sub32_overflows(dst_reg->s32_max_value, smin_val)) { 12786 /* Overflow possible, we know nothing */ 12787 dst_reg->s32_min_value = S32_MIN; 12788 dst_reg->s32_max_value = S32_MAX; 12789 } else { 12790 dst_reg->s32_min_value -= smax_val; 12791 dst_reg->s32_max_value -= smin_val; 12792 } 12793 if (dst_reg->u32_min_value < umax_val) { 12794 /* Overflow possible, we know nothing */ 12795 dst_reg->u32_min_value = 0; 12796 dst_reg->u32_max_value = U32_MAX; 12797 } else { 12798 /* Cannot overflow (as long as bounds are consistent) */ 12799 dst_reg->u32_min_value -= umax_val; 12800 dst_reg->u32_max_value -= umin_val; 12801 } 12802 } 12803 12804 static void scalar_min_max_sub(struct bpf_reg_state *dst_reg, 12805 struct bpf_reg_state *src_reg) 12806 { 12807 s64 smin_val = src_reg->smin_value; 12808 s64 smax_val = src_reg->smax_value; 12809 u64 umin_val = src_reg->umin_value; 12810 u64 umax_val = src_reg->umax_value; 12811 12812 if (signed_sub_overflows(dst_reg->smin_value, smax_val) || 12813 signed_sub_overflows(dst_reg->smax_value, smin_val)) { 12814 /* Overflow possible, we know nothing */ 12815 dst_reg->smin_value = S64_MIN; 12816 dst_reg->smax_value = S64_MAX; 12817 } else { 12818 dst_reg->smin_value -= smax_val; 12819 dst_reg->smax_value -= smin_val; 12820 } 12821 if (dst_reg->umin_value < umax_val) { 12822 /* Overflow possible, we know nothing */ 12823 dst_reg->umin_value = 0; 12824 dst_reg->umax_value = U64_MAX; 12825 } else { 12826 /* Cannot overflow (as long as bounds are consistent) */ 12827 dst_reg->umin_value -= umax_val; 12828 dst_reg->umax_value -= umin_val; 12829 } 12830 } 12831 12832 static void scalar32_min_max_mul(struct bpf_reg_state *dst_reg, 12833 struct bpf_reg_state *src_reg) 12834 { 12835 s32 smin_val = src_reg->s32_min_value; 12836 u32 umin_val = src_reg->u32_min_value; 12837 u32 umax_val = src_reg->u32_max_value; 12838 12839 if (smin_val < 0 || dst_reg->s32_min_value < 0) { 12840 /* Ain't nobody got time to multiply that sign */ 12841 __mark_reg32_unbounded(dst_reg); 12842 return; 12843 } 12844 /* Both values are positive, so we can work with unsigned and 12845 * copy the result to signed (unless it exceeds S32_MAX). 12846 */ 12847 if (umax_val > U16_MAX || dst_reg->u32_max_value > U16_MAX) { 12848 /* Potential overflow, we know nothing */ 12849 __mark_reg32_unbounded(dst_reg); 12850 return; 12851 } 12852 dst_reg->u32_min_value *= umin_val; 12853 dst_reg->u32_max_value *= umax_val; 12854 if (dst_reg->u32_max_value > S32_MAX) { 12855 /* Overflow possible, we know nothing */ 12856 dst_reg->s32_min_value = S32_MIN; 12857 dst_reg->s32_max_value = S32_MAX; 12858 } else { 12859 dst_reg->s32_min_value = dst_reg->u32_min_value; 12860 dst_reg->s32_max_value = dst_reg->u32_max_value; 12861 } 12862 } 12863 12864 static void scalar_min_max_mul(struct bpf_reg_state *dst_reg, 12865 struct bpf_reg_state *src_reg) 12866 { 12867 s64 smin_val = src_reg->smin_value; 12868 u64 umin_val = src_reg->umin_value; 12869 u64 umax_val = src_reg->umax_value; 12870 12871 if (smin_val < 0 || dst_reg->smin_value < 0) { 12872 /* Ain't nobody got time to multiply that sign */ 12873 __mark_reg64_unbounded(dst_reg); 12874 return; 12875 } 12876 /* Both values are positive, so we can work with unsigned and 12877 * copy the result to signed (unless it exceeds S64_MAX). 12878 */ 12879 if (umax_val > U32_MAX || dst_reg->umax_value > U32_MAX) { 12880 /* Potential overflow, we know nothing */ 12881 __mark_reg64_unbounded(dst_reg); 12882 return; 12883 } 12884 dst_reg->umin_value *= umin_val; 12885 dst_reg->umax_value *= umax_val; 12886 if (dst_reg->umax_value > S64_MAX) { 12887 /* Overflow possible, we know nothing */ 12888 dst_reg->smin_value = S64_MIN; 12889 dst_reg->smax_value = S64_MAX; 12890 } else { 12891 dst_reg->smin_value = dst_reg->umin_value; 12892 dst_reg->smax_value = dst_reg->umax_value; 12893 } 12894 } 12895 12896 static void scalar32_min_max_and(struct bpf_reg_state *dst_reg, 12897 struct bpf_reg_state *src_reg) 12898 { 12899 bool src_known = tnum_subreg_is_const(src_reg->var_off); 12900 bool dst_known = tnum_subreg_is_const(dst_reg->var_off); 12901 struct tnum var32_off = tnum_subreg(dst_reg->var_off); 12902 s32 smin_val = src_reg->s32_min_value; 12903 u32 umax_val = src_reg->u32_max_value; 12904 12905 if (src_known && dst_known) { 12906 __mark_reg32_known(dst_reg, var32_off.value); 12907 return; 12908 } 12909 12910 /* We get our minimum from the var_off, since that's inherently 12911 * bitwise. Our maximum is the minimum of the operands' maxima. 12912 */ 12913 dst_reg->u32_min_value = var32_off.value; 12914 dst_reg->u32_max_value = min(dst_reg->u32_max_value, umax_val); 12915 if (dst_reg->s32_min_value < 0 || smin_val < 0) { 12916 /* Lose signed bounds when ANDing negative numbers, 12917 * ain't nobody got time for that. 12918 */ 12919 dst_reg->s32_min_value = S32_MIN; 12920 dst_reg->s32_max_value = S32_MAX; 12921 } else { 12922 /* ANDing two positives gives a positive, so safe to 12923 * cast result into s64. 12924 */ 12925 dst_reg->s32_min_value = dst_reg->u32_min_value; 12926 dst_reg->s32_max_value = dst_reg->u32_max_value; 12927 } 12928 } 12929 12930 static void scalar_min_max_and(struct bpf_reg_state *dst_reg, 12931 struct bpf_reg_state *src_reg) 12932 { 12933 bool src_known = tnum_is_const(src_reg->var_off); 12934 bool dst_known = tnum_is_const(dst_reg->var_off); 12935 s64 smin_val = src_reg->smin_value; 12936 u64 umax_val = src_reg->umax_value; 12937 12938 if (src_known && dst_known) { 12939 __mark_reg_known(dst_reg, dst_reg->var_off.value); 12940 return; 12941 } 12942 12943 /* We get our minimum from the var_off, since that's inherently 12944 * bitwise. Our maximum is the minimum of the operands' maxima. 12945 */ 12946 dst_reg->umin_value = dst_reg->var_off.value; 12947 dst_reg->umax_value = min(dst_reg->umax_value, umax_val); 12948 if (dst_reg->smin_value < 0 || smin_val < 0) { 12949 /* Lose signed bounds when ANDing negative numbers, 12950 * ain't nobody got time for that. 12951 */ 12952 dst_reg->smin_value = S64_MIN; 12953 dst_reg->smax_value = S64_MAX; 12954 } else { 12955 /* ANDing two positives gives a positive, so safe to 12956 * cast result into s64. 12957 */ 12958 dst_reg->smin_value = dst_reg->umin_value; 12959 dst_reg->smax_value = dst_reg->umax_value; 12960 } 12961 /* We may learn something more from the var_off */ 12962 __update_reg_bounds(dst_reg); 12963 } 12964 12965 static void scalar32_min_max_or(struct bpf_reg_state *dst_reg, 12966 struct bpf_reg_state *src_reg) 12967 { 12968 bool src_known = tnum_subreg_is_const(src_reg->var_off); 12969 bool dst_known = tnum_subreg_is_const(dst_reg->var_off); 12970 struct tnum var32_off = tnum_subreg(dst_reg->var_off); 12971 s32 smin_val = src_reg->s32_min_value; 12972 u32 umin_val = src_reg->u32_min_value; 12973 12974 if (src_known && dst_known) { 12975 __mark_reg32_known(dst_reg, var32_off.value); 12976 return; 12977 } 12978 12979 /* We get our maximum from the var_off, and our minimum is the 12980 * maximum of the operands' minima 12981 */ 12982 dst_reg->u32_min_value = max(dst_reg->u32_min_value, umin_val); 12983 dst_reg->u32_max_value = var32_off.value | var32_off.mask; 12984 if (dst_reg->s32_min_value < 0 || smin_val < 0) { 12985 /* Lose signed bounds when ORing negative numbers, 12986 * ain't nobody got time for that. 12987 */ 12988 dst_reg->s32_min_value = S32_MIN; 12989 dst_reg->s32_max_value = S32_MAX; 12990 } else { 12991 /* ORing two positives gives a positive, so safe to 12992 * cast result into s64. 12993 */ 12994 dst_reg->s32_min_value = dst_reg->u32_min_value; 12995 dst_reg->s32_max_value = dst_reg->u32_max_value; 12996 } 12997 } 12998 12999 static void scalar_min_max_or(struct bpf_reg_state *dst_reg, 13000 struct bpf_reg_state *src_reg) 13001 { 13002 bool src_known = tnum_is_const(src_reg->var_off); 13003 bool dst_known = tnum_is_const(dst_reg->var_off); 13004 s64 smin_val = src_reg->smin_value; 13005 u64 umin_val = src_reg->umin_value; 13006 13007 if (src_known && dst_known) { 13008 __mark_reg_known(dst_reg, dst_reg->var_off.value); 13009 return; 13010 } 13011 13012 /* We get our maximum from the var_off, and our minimum is the 13013 * maximum of the operands' minima 13014 */ 13015 dst_reg->umin_value = max(dst_reg->umin_value, umin_val); 13016 dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask; 13017 if (dst_reg->smin_value < 0 || smin_val < 0) { 13018 /* Lose signed bounds when ORing negative numbers, 13019 * ain't nobody got time for that. 13020 */ 13021 dst_reg->smin_value = S64_MIN; 13022 dst_reg->smax_value = S64_MAX; 13023 } else { 13024 /* ORing two positives gives a positive, so safe to 13025 * cast result into s64. 13026 */ 13027 dst_reg->smin_value = dst_reg->umin_value; 13028 dst_reg->smax_value = dst_reg->umax_value; 13029 } 13030 /* We may learn something more from the var_off */ 13031 __update_reg_bounds(dst_reg); 13032 } 13033 13034 static void scalar32_min_max_xor(struct bpf_reg_state *dst_reg, 13035 struct bpf_reg_state *src_reg) 13036 { 13037 bool src_known = tnum_subreg_is_const(src_reg->var_off); 13038 bool dst_known = tnum_subreg_is_const(dst_reg->var_off); 13039 struct tnum var32_off = tnum_subreg(dst_reg->var_off); 13040 s32 smin_val = src_reg->s32_min_value; 13041 13042 if (src_known && dst_known) { 13043 __mark_reg32_known(dst_reg, var32_off.value); 13044 return; 13045 } 13046 13047 /* We get both minimum and maximum from the var32_off. */ 13048 dst_reg->u32_min_value = var32_off.value; 13049 dst_reg->u32_max_value = var32_off.value | var32_off.mask; 13050 13051 if (dst_reg->s32_min_value >= 0 && smin_val >= 0) { 13052 /* XORing two positive sign numbers gives a positive, 13053 * so safe to cast u32 result into s32. 13054 */ 13055 dst_reg->s32_min_value = dst_reg->u32_min_value; 13056 dst_reg->s32_max_value = dst_reg->u32_max_value; 13057 } else { 13058 dst_reg->s32_min_value = S32_MIN; 13059 dst_reg->s32_max_value = S32_MAX; 13060 } 13061 } 13062 13063 static void scalar_min_max_xor(struct bpf_reg_state *dst_reg, 13064 struct bpf_reg_state *src_reg) 13065 { 13066 bool src_known = tnum_is_const(src_reg->var_off); 13067 bool dst_known = tnum_is_const(dst_reg->var_off); 13068 s64 smin_val = src_reg->smin_value; 13069 13070 if (src_known && dst_known) { 13071 /* dst_reg->var_off.value has been updated earlier */ 13072 __mark_reg_known(dst_reg, dst_reg->var_off.value); 13073 return; 13074 } 13075 13076 /* We get both minimum and maximum from the var_off. */ 13077 dst_reg->umin_value = dst_reg->var_off.value; 13078 dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask; 13079 13080 if (dst_reg->smin_value >= 0 && smin_val >= 0) { 13081 /* XORing two positive sign numbers gives a positive, 13082 * so safe to cast u64 result into s64. 13083 */ 13084 dst_reg->smin_value = dst_reg->umin_value; 13085 dst_reg->smax_value = dst_reg->umax_value; 13086 } else { 13087 dst_reg->smin_value = S64_MIN; 13088 dst_reg->smax_value = S64_MAX; 13089 } 13090 13091 __update_reg_bounds(dst_reg); 13092 } 13093 13094 static void __scalar32_min_max_lsh(struct bpf_reg_state *dst_reg, 13095 u64 umin_val, u64 umax_val) 13096 { 13097 /* We lose all sign bit information (except what we can pick 13098 * up from var_off) 13099 */ 13100 dst_reg->s32_min_value = S32_MIN; 13101 dst_reg->s32_max_value = S32_MAX; 13102 /* If we might shift our top bit out, then we know nothing */ 13103 if (umax_val > 31 || dst_reg->u32_max_value > 1ULL << (31 - umax_val)) { 13104 dst_reg->u32_min_value = 0; 13105 dst_reg->u32_max_value = U32_MAX; 13106 } else { 13107 dst_reg->u32_min_value <<= umin_val; 13108 dst_reg->u32_max_value <<= umax_val; 13109 } 13110 } 13111 13112 static void scalar32_min_max_lsh(struct bpf_reg_state *dst_reg, 13113 struct bpf_reg_state *src_reg) 13114 { 13115 u32 umax_val = src_reg->u32_max_value; 13116 u32 umin_val = src_reg->u32_min_value; 13117 /* u32 alu operation will zext upper bits */ 13118 struct tnum subreg = tnum_subreg(dst_reg->var_off); 13119 13120 __scalar32_min_max_lsh(dst_reg, umin_val, umax_val); 13121 dst_reg->var_off = tnum_subreg(tnum_lshift(subreg, umin_val)); 13122 /* Not required but being careful mark reg64 bounds as unknown so 13123 * that we are forced to pick them up from tnum and zext later and 13124 * if some path skips this step we are still safe. 13125 */ 13126 __mark_reg64_unbounded(dst_reg); 13127 __update_reg32_bounds(dst_reg); 13128 } 13129 13130 static void __scalar64_min_max_lsh(struct bpf_reg_state *dst_reg, 13131 u64 umin_val, u64 umax_val) 13132 { 13133 /* Special case <<32 because it is a common compiler pattern to sign 13134 * extend subreg by doing <<32 s>>32. In this case if 32bit bounds are 13135 * positive we know this shift will also be positive so we can track 13136 * bounds correctly. Otherwise we lose all sign bit information except 13137 * what we can pick up from var_off. Perhaps we can generalize this 13138 * later to shifts of any length. 13139 */ 13140 if (umin_val == 32 && umax_val == 32 && dst_reg->s32_max_value >= 0) 13141 dst_reg->smax_value = (s64)dst_reg->s32_max_value << 32; 13142 else 13143 dst_reg->smax_value = S64_MAX; 13144 13145 if (umin_val == 32 && umax_val == 32 && dst_reg->s32_min_value >= 0) 13146 dst_reg->smin_value = (s64)dst_reg->s32_min_value << 32; 13147 else 13148 dst_reg->smin_value = S64_MIN; 13149 13150 /* If we might shift our top bit out, then we know nothing */ 13151 if (dst_reg->umax_value > 1ULL << (63 - umax_val)) { 13152 dst_reg->umin_value = 0; 13153 dst_reg->umax_value = U64_MAX; 13154 } else { 13155 dst_reg->umin_value <<= umin_val; 13156 dst_reg->umax_value <<= umax_val; 13157 } 13158 } 13159 13160 static void scalar_min_max_lsh(struct bpf_reg_state *dst_reg, 13161 struct bpf_reg_state *src_reg) 13162 { 13163 u64 umax_val = src_reg->umax_value; 13164 u64 umin_val = src_reg->umin_value; 13165 13166 /* scalar64 calc uses 32bit unshifted bounds so must be called first */ 13167 __scalar64_min_max_lsh(dst_reg, umin_val, umax_val); 13168 __scalar32_min_max_lsh(dst_reg, umin_val, umax_val); 13169 13170 dst_reg->var_off = tnum_lshift(dst_reg->var_off, umin_val); 13171 /* We may learn something more from the var_off */ 13172 __update_reg_bounds(dst_reg); 13173 } 13174 13175 static void scalar32_min_max_rsh(struct bpf_reg_state *dst_reg, 13176 struct bpf_reg_state *src_reg) 13177 { 13178 struct tnum subreg = tnum_subreg(dst_reg->var_off); 13179 u32 umax_val = src_reg->u32_max_value; 13180 u32 umin_val = src_reg->u32_min_value; 13181 13182 /* BPF_RSH is an unsigned shift. If the value in dst_reg might 13183 * be negative, then either: 13184 * 1) src_reg might be zero, so the sign bit of the result is 13185 * unknown, so we lose our signed bounds 13186 * 2) it's known negative, thus the unsigned bounds capture the 13187 * signed bounds 13188 * 3) the signed bounds cross zero, so they tell us nothing 13189 * about the result 13190 * If the value in dst_reg is known nonnegative, then again the 13191 * unsigned bounds capture the signed bounds. 13192 * Thus, in all cases it suffices to blow away our signed bounds 13193 * and rely on inferring new ones from the unsigned bounds and 13194 * var_off of the result. 13195 */ 13196 dst_reg->s32_min_value = S32_MIN; 13197 dst_reg->s32_max_value = S32_MAX; 13198 13199 dst_reg->var_off = tnum_rshift(subreg, umin_val); 13200 dst_reg->u32_min_value >>= umax_val; 13201 dst_reg->u32_max_value >>= umin_val; 13202 13203 __mark_reg64_unbounded(dst_reg); 13204 __update_reg32_bounds(dst_reg); 13205 } 13206 13207 static void scalar_min_max_rsh(struct bpf_reg_state *dst_reg, 13208 struct bpf_reg_state *src_reg) 13209 { 13210 u64 umax_val = src_reg->umax_value; 13211 u64 umin_val = src_reg->umin_value; 13212 13213 /* BPF_RSH is an unsigned shift. If the value in dst_reg might 13214 * be negative, then either: 13215 * 1) src_reg might be zero, so the sign bit of the result is 13216 * unknown, so we lose our signed bounds 13217 * 2) it's known negative, thus the unsigned bounds capture the 13218 * signed bounds 13219 * 3) the signed bounds cross zero, so they tell us nothing 13220 * about the result 13221 * If the value in dst_reg is known nonnegative, then again the 13222 * unsigned bounds capture the signed bounds. 13223 * Thus, in all cases it suffices to blow away our signed bounds 13224 * and rely on inferring new ones from the unsigned bounds and 13225 * var_off of the result. 13226 */ 13227 dst_reg->smin_value = S64_MIN; 13228 dst_reg->smax_value = S64_MAX; 13229 dst_reg->var_off = tnum_rshift(dst_reg->var_off, umin_val); 13230 dst_reg->umin_value >>= umax_val; 13231 dst_reg->umax_value >>= umin_val; 13232 13233 /* Its not easy to operate on alu32 bounds here because it depends 13234 * on bits being shifted in. Take easy way out and mark unbounded 13235 * so we can recalculate later from tnum. 13236 */ 13237 __mark_reg32_unbounded(dst_reg); 13238 __update_reg_bounds(dst_reg); 13239 } 13240 13241 static void scalar32_min_max_arsh(struct bpf_reg_state *dst_reg, 13242 struct bpf_reg_state *src_reg) 13243 { 13244 u64 umin_val = src_reg->u32_min_value; 13245 13246 /* Upon reaching here, src_known is true and 13247 * umax_val is equal to umin_val. 13248 */ 13249 dst_reg->s32_min_value = (u32)(((s32)dst_reg->s32_min_value) >> umin_val); 13250 dst_reg->s32_max_value = (u32)(((s32)dst_reg->s32_max_value) >> umin_val); 13251 13252 dst_reg->var_off = tnum_arshift(tnum_subreg(dst_reg->var_off), umin_val, 32); 13253 13254 /* blow away the dst_reg umin_value/umax_value and rely on 13255 * dst_reg var_off to refine the result. 13256 */ 13257 dst_reg->u32_min_value = 0; 13258 dst_reg->u32_max_value = U32_MAX; 13259 13260 __mark_reg64_unbounded(dst_reg); 13261 __update_reg32_bounds(dst_reg); 13262 } 13263 13264 static void scalar_min_max_arsh(struct bpf_reg_state *dst_reg, 13265 struct bpf_reg_state *src_reg) 13266 { 13267 u64 umin_val = src_reg->umin_value; 13268 13269 /* Upon reaching here, src_known is true and umax_val is equal 13270 * to umin_val. 13271 */ 13272 dst_reg->smin_value >>= umin_val; 13273 dst_reg->smax_value >>= umin_val; 13274 13275 dst_reg->var_off = tnum_arshift(dst_reg->var_off, umin_val, 64); 13276 13277 /* blow away the dst_reg umin_value/umax_value and rely on 13278 * dst_reg var_off to refine the result. 13279 */ 13280 dst_reg->umin_value = 0; 13281 dst_reg->umax_value = U64_MAX; 13282 13283 /* Its not easy to operate on alu32 bounds here because it depends 13284 * on bits being shifted in from upper 32-bits. Take easy way out 13285 * and mark unbounded so we can recalculate later from tnum. 13286 */ 13287 __mark_reg32_unbounded(dst_reg); 13288 __update_reg_bounds(dst_reg); 13289 } 13290 13291 /* WARNING: This function does calculations on 64-bit values, but the actual 13292 * execution may occur on 32-bit values. Therefore, things like bitshifts 13293 * need extra checks in the 32-bit case. 13294 */ 13295 static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env, 13296 struct bpf_insn *insn, 13297 struct bpf_reg_state *dst_reg, 13298 struct bpf_reg_state src_reg) 13299 { 13300 struct bpf_reg_state *regs = cur_regs(env); 13301 u8 opcode = BPF_OP(insn->code); 13302 bool src_known; 13303 s64 smin_val, smax_val; 13304 u64 umin_val, umax_val; 13305 s32 s32_min_val, s32_max_val; 13306 u32 u32_min_val, u32_max_val; 13307 u64 insn_bitness = (BPF_CLASS(insn->code) == BPF_ALU64) ? 64 : 32; 13308 bool alu32 = (BPF_CLASS(insn->code) != BPF_ALU64); 13309 int ret; 13310 13311 smin_val = src_reg.smin_value; 13312 smax_val = src_reg.smax_value; 13313 umin_val = src_reg.umin_value; 13314 umax_val = src_reg.umax_value; 13315 13316 s32_min_val = src_reg.s32_min_value; 13317 s32_max_val = src_reg.s32_max_value; 13318 u32_min_val = src_reg.u32_min_value; 13319 u32_max_val = src_reg.u32_max_value; 13320 13321 if (alu32) { 13322 src_known = tnum_subreg_is_const(src_reg.var_off); 13323 if ((src_known && 13324 (s32_min_val != s32_max_val || u32_min_val != u32_max_val)) || 13325 s32_min_val > s32_max_val || u32_min_val > u32_max_val) { 13326 /* Taint dst register if offset had invalid bounds 13327 * derived from e.g. dead branches. 13328 */ 13329 __mark_reg_unknown(env, dst_reg); 13330 return 0; 13331 } 13332 } else { 13333 src_known = tnum_is_const(src_reg.var_off); 13334 if ((src_known && 13335 (smin_val != smax_val || umin_val != umax_val)) || 13336 smin_val > smax_val || umin_val > umax_val) { 13337 /* Taint dst register if offset had invalid bounds 13338 * derived from e.g. dead branches. 13339 */ 13340 __mark_reg_unknown(env, dst_reg); 13341 return 0; 13342 } 13343 } 13344 13345 if (!src_known && 13346 opcode != BPF_ADD && opcode != BPF_SUB && opcode != BPF_AND) { 13347 __mark_reg_unknown(env, dst_reg); 13348 return 0; 13349 } 13350 13351 if (sanitize_needed(opcode)) { 13352 ret = sanitize_val_alu(env, insn); 13353 if (ret < 0) 13354 return sanitize_err(env, insn, ret, NULL, NULL); 13355 } 13356 13357 /* Calculate sign/unsigned bounds and tnum for alu32 and alu64 bit ops. 13358 * There are two classes of instructions: The first class we track both 13359 * alu32 and alu64 sign/unsigned bounds independently this provides the 13360 * greatest amount of precision when alu operations are mixed with jmp32 13361 * operations. These operations are BPF_ADD, BPF_SUB, BPF_MUL, BPF_ADD, 13362 * and BPF_OR. This is possible because these ops have fairly easy to 13363 * understand and calculate behavior in both 32-bit and 64-bit alu ops. 13364 * See alu32 verifier tests for examples. The second class of 13365 * operations, BPF_LSH, BPF_RSH, and BPF_ARSH, however are not so easy 13366 * with regards to tracking sign/unsigned bounds because the bits may 13367 * cross subreg boundaries in the alu64 case. When this happens we mark 13368 * the reg unbounded in the subreg bound space and use the resulting 13369 * tnum to calculate an approximation of the sign/unsigned bounds. 13370 */ 13371 switch (opcode) { 13372 case BPF_ADD: 13373 scalar32_min_max_add(dst_reg, &src_reg); 13374 scalar_min_max_add(dst_reg, &src_reg); 13375 dst_reg->var_off = tnum_add(dst_reg->var_off, src_reg.var_off); 13376 break; 13377 case BPF_SUB: 13378 scalar32_min_max_sub(dst_reg, &src_reg); 13379 scalar_min_max_sub(dst_reg, &src_reg); 13380 dst_reg->var_off = tnum_sub(dst_reg->var_off, src_reg.var_off); 13381 break; 13382 case BPF_MUL: 13383 dst_reg->var_off = tnum_mul(dst_reg->var_off, src_reg.var_off); 13384 scalar32_min_max_mul(dst_reg, &src_reg); 13385 scalar_min_max_mul(dst_reg, &src_reg); 13386 break; 13387 case BPF_AND: 13388 dst_reg->var_off = tnum_and(dst_reg->var_off, src_reg.var_off); 13389 scalar32_min_max_and(dst_reg, &src_reg); 13390 scalar_min_max_and(dst_reg, &src_reg); 13391 break; 13392 case BPF_OR: 13393 dst_reg->var_off = tnum_or(dst_reg->var_off, src_reg.var_off); 13394 scalar32_min_max_or(dst_reg, &src_reg); 13395 scalar_min_max_or(dst_reg, &src_reg); 13396 break; 13397 case BPF_XOR: 13398 dst_reg->var_off = tnum_xor(dst_reg->var_off, src_reg.var_off); 13399 scalar32_min_max_xor(dst_reg, &src_reg); 13400 scalar_min_max_xor(dst_reg, &src_reg); 13401 break; 13402 case BPF_LSH: 13403 if (umax_val >= insn_bitness) { 13404 /* Shifts greater than 31 or 63 are undefined. 13405 * This includes shifts by a negative number. 13406 */ 13407 mark_reg_unknown(env, regs, insn->dst_reg); 13408 break; 13409 } 13410 if (alu32) 13411 scalar32_min_max_lsh(dst_reg, &src_reg); 13412 else 13413 scalar_min_max_lsh(dst_reg, &src_reg); 13414 break; 13415 case BPF_RSH: 13416 if (umax_val >= insn_bitness) { 13417 /* Shifts greater than 31 or 63 are undefined. 13418 * This includes shifts by a negative number. 13419 */ 13420 mark_reg_unknown(env, regs, insn->dst_reg); 13421 break; 13422 } 13423 if (alu32) 13424 scalar32_min_max_rsh(dst_reg, &src_reg); 13425 else 13426 scalar_min_max_rsh(dst_reg, &src_reg); 13427 break; 13428 case BPF_ARSH: 13429 if (umax_val >= insn_bitness) { 13430 /* Shifts greater than 31 or 63 are undefined. 13431 * This includes shifts by a negative number. 13432 */ 13433 mark_reg_unknown(env, regs, insn->dst_reg); 13434 break; 13435 } 13436 if (alu32) 13437 scalar32_min_max_arsh(dst_reg, &src_reg); 13438 else 13439 scalar_min_max_arsh(dst_reg, &src_reg); 13440 break; 13441 default: 13442 mark_reg_unknown(env, regs, insn->dst_reg); 13443 break; 13444 } 13445 13446 /* ALU32 ops are zero extended into 64bit register */ 13447 if (alu32) 13448 zext_32_to_64(dst_reg); 13449 reg_bounds_sync(dst_reg); 13450 return 0; 13451 } 13452 13453 /* Handles ALU ops other than BPF_END, BPF_NEG and BPF_MOV: computes new min/max 13454 * and var_off. 13455 */ 13456 static int adjust_reg_min_max_vals(struct bpf_verifier_env *env, 13457 struct bpf_insn *insn) 13458 { 13459 struct bpf_verifier_state *vstate = env->cur_state; 13460 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 13461 struct bpf_reg_state *regs = state->regs, *dst_reg, *src_reg; 13462 struct bpf_reg_state *ptr_reg = NULL, off_reg = {0}; 13463 u8 opcode = BPF_OP(insn->code); 13464 int err; 13465 13466 dst_reg = ®s[insn->dst_reg]; 13467 src_reg = NULL; 13468 if (dst_reg->type != SCALAR_VALUE) 13469 ptr_reg = dst_reg; 13470 else 13471 /* Make sure ID is cleared otherwise dst_reg min/max could be 13472 * incorrectly propagated into other registers by find_equal_scalars() 13473 */ 13474 dst_reg->id = 0; 13475 if (BPF_SRC(insn->code) == BPF_X) { 13476 src_reg = ®s[insn->src_reg]; 13477 if (src_reg->type != SCALAR_VALUE) { 13478 if (dst_reg->type != SCALAR_VALUE) { 13479 /* Combining two pointers by any ALU op yields 13480 * an arbitrary scalar. Disallow all math except 13481 * pointer subtraction 13482 */ 13483 if (opcode == BPF_SUB && env->allow_ptr_leaks) { 13484 mark_reg_unknown(env, regs, insn->dst_reg); 13485 return 0; 13486 } 13487 verbose(env, "R%d pointer %s pointer prohibited\n", 13488 insn->dst_reg, 13489 bpf_alu_string[opcode >> 4]); 13490 return -EACCES; 13491 } else { 13492 /* scalar += pointer 13493 * This is legal, but we have to reverse our 13494 * src/dest handling in computing the range 13495 */ 13496 err = mark_chain_precision(env, insn->dst_reg); 13497 if (err) 13498 return err; 13499 return adjust_ptr_min_max_vals(env, insn, 13500 src_reg, dst_reg); 13501 } 13502 } else if (ptr_reg) { 13503 /* pointer += scalar */ 13504 err = mark_chain_precision(env, insn->src_reg); 13505 if (err) 13506 return err; 13507 return adjust_ptr_min_max_vals(env, insn, 13508 dst_reg, src_reg); 13509 } else if (dst_reg->precise) { 13510 /* if dst_reg is precise, src_reg should be precise as well */ 13511 err = mark_chain_precision(env, insn->src_reg); 13512 if (err) 13513 return err; 13514 } 13515 } else { 13516 /* Pretend the src is a reg with a known value, since we only 13517 * need to be able to read from this state. 13518 */ 13519 off_reg.type = SCALAR_VALUE; 13520 __mark_reg_known(&off_reg, insn->imm); 13521 src_reg = &off_reg; 13522 if (ptr_reg) /* pointer += K */ 13523 return adjust_ptr_min_max_vals(env, insn, 13524 ptr_reg, src_reg); 13525 } 13526 13527 /* Got here implies adding two SCALAR_VALUEs */ 13528 if (WARN_ON_ONCE(ptr_reg)) { 13529 print_verifier_state(env, state, true); 13530 verbose(env, "verifier internal error: unexpected ptr_reg\n"); 13531 return -EINVAL; 13532 } 13533 if (WARN_ON(!src_reg)) { 13534 print_verifier_state(env, state, true); 13535 verbose(env, "verifier internal error: no src_reg\n"); 13536 return -EINVAL; 13537 } 13538 return adjust_scalar_min_max_vals(env, insn, dst_reg, *src_reg); 13539 } 13540 13541 /* check validity of 32-bit and 64-bit arithmetic operations */ 13542 static int check_alu_op(struct bpf_verifier_env *env, struct bpf_insn *insn) 13543 { 13544 struct bpf_reg_state *regs = cur_regs(env); 13545 u8 opcode = BPF_OP(insn->code); 13546 int err; 13547 13548 if (opcode == BPF_END || opcode == BPF_NEG) { 13549 if (opcode == BPF_NEG) { 13550 if (BPF_SRC(insn->code) != BPF_K || 13551 insn->src_reg != BPF_REG_0 || 13552 insn->off != 0 || insn->imm != 0) { 13553 verbose(env, "BPF_NEG uses reserved fields\n"); 13554 return -EINVAL; 13555 } 13556 } else { 13557 if (insn->src_reg != BPF_REG_0 || insn->off != 0 || 13558 (insn->imm != 16 && insn->imm != 32 && insn->imm != 64) || 13559 (BPF_CLASS(insn->code) == BPF_ALU64 && 13560 BPF_SRC(insn->code) != BPF_TO_LE)) { 13561 verbose(env, "BPF_END uses reserved fields\n"); 13562 return -EINVAL; 13563 } 13564 } 13565 13566 /* check src operand */ 13567 err = check_reg_arg(env, insn->dst_reg, SRC_OP); 13568 if (err) 13569 return err; 13570 13571 if (is_pointer_value(env, insn->dst_reg)) { 13572 verbose(env, "R%d pointer arithmetic prohibited\n", 13573 insn->dst_reg); 13574 return -EACCES; 13575 } 13576 13577 /* check dest operand */ 13578 err = check_reg_arg(env, insn->dst_reg, DST_OP); 13579 if (err) 13580 return err; 13581 13582 } else if (opcode == BPF_MOV) { 13583 13584 if (BPF_SRC(insn->code) == BPF_X) { 13585 if (insn->imm != 0) { 13586 verbose(env, "BPF_MOV uses reserved fields\n"); 13587 return -EINVAL; 13588 } 13589 13590 if (BPF_CLASS(insn->code) == BPF_ALU) { 13591 if (insn->off != 0 && insn->off != 8 && insn->off != 16) { 13592 verbose(env, "BPF_MOV uses reserved fields\n"); 13593 return -EINVAL; 13594 } 13595 } else { 13596 if (insn->off != 0 && insn->off != 8 && insn->off != 16 && 13597 insn->off != 32) { 13598 verbose(env, "BPF_MOV uses reserved fields\n"); 13599 return -EINVAL; 13600 } 13601 } 13602 13603 /* check src operand */ 13604 err = check_reg_arg(env, insn->src_reg, SRC_OP); 13605 if (err) 13606 return err; 13607 } else { 13608 if (insn->src_reg != BPF_REG_0 || insn->off != 0) { 13609 verbose(env, "BPF_MOV uses reserved fields\n"); 13610 return -EINVAL; 13611 } 13612 } 13613 13614 /* check dest operand, mark as required later */ 13615 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK); 13616 if (err) 13617 return err; 13618 13619 if (BPF_SRC(insn->code) == BPF_X) { 13620 struct bpf_reg_state *src_reg = regs + insn->src_reg; 13621 struct bpf_reg_state *dst_reg = regs + insn->dst_reg; 13622 bool need_id = src_reg->type == SCALAR_VALUE && !src_reg->id && 13623 !tnum_is_const(src_reg->var_off); 13624 13625 if (BPF_CLASS(insn->code) == BPF_ALU64) { 13626 if (insn->off == 0) { 13627 /* case: R1 = R2 13628 * copy register state to dest reg 13629 */ 13630 if (need_id) 13631 /* Assign src and dst registers the same ID 13632 * that will be used by find_equal_scalars() 13633 * to propagate min/max range. 13634 */ 13635 src_reg->id = ++env->id_gen; 13636 copy_register_state(dst_reg, src_reg); 13637 dst_reg->live |= REG_LIVE_WRITTEN; 13638 dst_reg->subreg_def = DEF_NOT_SUBREG; 13639 } else { 13640 /* case: R1 = (s8, s16 s32)R2 */ 13641 if (is_pointer_value(env, insn->src_reg)) { 13642 verbose(env, 13643 "R%d sign-extension part of pointer\n", 13644 insn->src_reg); 13645 return -EACCES; 13646 } else if (src_reg->type == SCALAR_VALUE) { 13647 bool no_sext; 13648 13649 no_sext = src_reg->umax_value < (1ULL << (insn->off - 1)); 13650 if (no_sext && need_id) 13651 src_reg->id = ++env->id_gen; 13652 copy_register_state(dst_reg, src_reg); 13653 if (!no_sext) 13654 dst_reg->id = 0; 13655 coerce_reg_to_size_sx(dst_reg, insn->off >> 3); 13656 dst_reg->live |= REG_LIVE_WRITTEN; 13657 dst_reg->subreg_def = DEF_NOT_SUBREG; 13658 } else { 13659 mark_reg_unknown(env, regs, insn->dst_reg); 13660 } 13661 } 13662 } else { 13663 /* R1 = (u32) R2 */ 13664 if (is_pointer_value(env, insn->src_reg)) { 13665 verbose(env, 13666 "R%d partial copy of pointer\n", 13667 insn->src_reg); 13668 return -EACCES; 13669 } else if (src_reg->type == SCALAR_VALUE) { 13670 if (insn->off == 0) { 13671 bool is_src_reg_u32 = src_reg->umax_value <= U32_MAX; 13672 13673 if (is_src_reg_u32 && need_id) 13674 src_reg->id = ++env->id_gen; 13675 copy_register_state(dst_reg, src_reg); 13676 /* Make sure ID is cleared if src_reg is not in u32 13677 * range otherwise dst_reg min/max could be incorrectly 13678 * propagated into src_reg by find_equal_scalars() 13679 */ 13680 if (!is_src_reg_u32) 13681 dst_reg->id = 0; 13682 dst_reg->live |= REG_LIVE_WRITTEN; 13683 dst_reg->subreg_def = env->insn_idx + 1; 13684 } else { 13685 /* case: W1 = (s8, s16)W2 */ 13686 bool no_sext = src_reg->umax_value < (1ULL << (insn->off - 1)); 13687 13688 if (no_sext && need_id) 13689 src_reg->id = ++env->id_gen; 13690 copy_register_state(dst_reg, src_reg); 13691 if (!no_sext) 13692 dst_reg->id = 0; 13693 dst_reg->live |= REG_LIVE_WRITTEN; 13694 dst_reg->subreg_def = env->insn_idx + 1; 13695 coerce_subreg_to_size_sx(dst_reg, insn->off >> 3); 13696 } 13697 } else { 13698 mark_reg_unknown(env, regs, 13699 insn->dst_reg); 13700 } 13701 zext_32_to_64(dst_reg); 13702 reg_bounds_sync(dst_reg); 13703 } 13704 } else { 13705 /* case: R = imm 13706 * remember the value we stored into this reg 13707 */ 13708 /* clear any state __mark_reg_known doesn't set */ 13709 mark_reg_unknown(env, regs, insn->dst_reg); 13710 regs[insn->dst_reg].type = SCALAR_VALUE; 13711 if (BPF_CLASS(insn->code) == BPF_ALU64) { 13712 __mark_reg_known(regs + insn->dst_reg, 13713 insn->imm); 13714 } else { 13715 __mark_reg_known(regs + insn->dst_reg, 13716 (u32)insn->imm); 13717 } 13718 } 13719 13720 } else if (opcode > BPF_END) { 13721 verbose(env, "invalid BPF_ALU opcode %x\n", opcode); 13722 return -EINVAL; 13723 13724 } else { /* all other ALU ops: and, sub, xor, add, ... */ 13725 13726 if (BPF_SRC(insn->code) == BPF_X) { 13727 if (insn->imm != 0 || insn->off > 1 || 13728 (insn->off == 1 && opcode != BPF_MOD && opcode != BPF_DIV)) { 13729 verbose(env, "BPF_ALU uses reserved fields\n"); 13730 return -EINVAL; 13731 } 13732 /* check src1 operand */ 13733 err = check_reg_arg(env, insn->src_reg, SRC_OP); 13734 if (err) 13735 return err; 13736 } else { 13737 if (insn->src_reg != BPF_REG_0 || insn->off > 1 || 13738 (insn->off == 1 && opcode != BPF_MOD && opcode != BPF_DIV)) { 13739 verbose(env, "BPF_ALU uses reserved fields\n"); 13740 return -EINVAL; 13741 } 13742 } 13743 13744 /* check src2 operand */ 13745 err = check_reg_arg(env, insn->dst_reg, SRC_OP); 13746 if (err) 13747 return err; 13748 13749 if ((opcode == BPF_MOD || opcode == BPF_DIV) && 13750 BPF_SRC(insn->code) == BPF_K && insn->imm == 0) { 13751 verbose(env, "div by zero\n"); 13752 return -EINVAL; 13753 } 13754 13755 if ((opcode == BPF_LSH || opcode == BPF_RSH || 13756 opcode == BPF_ARSH) && BPF_SRC(insn->code) == BPF_K) { 13757 int size = BPF_CLASS(insn->code) == BPF_ALU64 ? 64 : 32; 13758 13759 if (insn->imm < 0 || insn->imm >= size) { 13760 verbose(env, "invalid shift %d\n", insn->imm); 13761 return -EINVAL; 13762 } 13763 } 13764 13765 /* check dest operand */ 13766 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK); 13767 if (err) 13768 return err; 13769 13770 return adjust_reg_min_max_vals(env, insn); 13771 } 13772 13773 return 0; 13774 } 13775 13776 static void find_good_pkt_pointers(struct bpf_verifier_state *vstate, 13777 struct bpf_reg_state *dst_reg, 13778 enum bpf_reg_type type, 13779 bool range_right_open) 13780 { 13781 struct bpf_func_state *state; 13782 struct bpf_reg_state *reg; 13783 int new_range; 13784 13785 if (dst_reg->off < 0 || 13786 (dst_reg->off == 0 && range_right_open)) 13787 /* This doesn't give us any range */ 13788 return; 13789 13790 if (dst_reg->umax_value > MAX_PACKET_OFF || 13791 dst_reg->umax_value + dst_reg->off > MAX_PACKET_OFF) 13792 /* Risk of overflow. For instance, ptr + (1<<63) may be less 13793 * than pkt_end, but that's because it's also less than pkt. 13794 */ 13795 return; 13796 13797 new_range = dst_reg->off; 13798 if (range_right_open) 13799 new_range++; 13800 13801 /* Examples for register markings: 13802 * 13803 * pkt_data in dst register: 13804 * 13805 * r2 = r3; 13806 * r2 += 8; 13807 * if (r2 > pkt_end) goto <handle exception> 13808 * <access okay> 13809 * 13810 * r2 = r3; 13811 * r2 += 8; 13812 * if (r2 < pkt_end) goto <access okay> 13813 * <handle exception> 13814 * 13815 * Where: 13816 * r2 == dst_reg, pkt_end == src_reg 13817 * r2=pkt(id=n,off=8,r=0) 13818 * r3=pkt(id=n,off=0,r=0) 13819 * 13820 * pkt_data in src register: 13821 * 13822 * r2 = r3; 13823 * r2 += 8; 13824 * if (pkt_end >= r2) goto <access okay> 13825 * <handle exception> 13826 * 13827 * r2 = r3; 13828 * r2 += 8; 13829 * if (pkt_end <= r2) goto <handle exception> 13830 * <access okay> 13831 * 13832 * Where: 13833 * pkt_end == dst_reg, r2 == src_reg 13834 * r2=pkt(id=n,off=8,r=0) 13835 * r3=pkt(id=n,off=0,r=0) 13836 * 13837 * Find register r3 and mark its range as r3=pkt(id=n,off=0,r=8) 13838 * or r3=pkt(id=n,off=0,r=8-1), so that range of bytes [r3, r3 + 8) 13839 * and [r3, r3 + 8-1) respectively is safe to access depending on 13840 * the check. 13841 */ 13842 13843 /* If our ids match, then we must have the same max_value. And we 13844 * don't care about the other reg's fixed offset, since if it's too big 13845 * the range won't allow anything. 13846 * dst_reg->off is known < MAX_PACKET_OFF, therefore it fits in a u16. 13847 */ 13848 bpf_for_each_reg_in_vstate(vstate, state, reg, ({ 13849 if (reg->type == type && reg->id == dst_reg->id) 13850 /* keep the maximum range already checked */ 13851 reg->range = max(reg->range, new_range); 13852 })); 13853 } 13854 13855 static int is_branch32_taken(struct bpf_reg_state *reg, u32 val, u8 opcode) 13856 { 13857 struct tnum subreg = tnum_subreg(reg->var_off); 13858 s32 sval = (s32)val; 13859 13860 switch (opcode) { 13861 case BPF_JEQ: 13862 if (tnum_is_const(subreg)) 13863 return !!tnum_equals_const(subreg, val); 13864 else if (val < reg->u32_min_value || val > reg->u32_max_value) 13865 return 0; 13866 break; 13867 case BPF_JNE: 13868 if (tnum_is_const(subreg)) 13869 return !tnum_equals_const(subreg, val); 13870 else if (val < reg->u32_min_value || val > reg->u32_max_value) 13871 return 1; 13872 break; 13873 case BPF_JSET: 13874 if ((~subreg.mask & subreg.value) & val) 13875 return 1; 13876 if (!((subreg.mask | subreg.value) & val)) 13877 return 0; 13878 break; 13879 case BPF_JGT: 13880 if (reg->u32_min_value > val) 13881 return 1; 13882 else if (reg->u32_max_value <= val) 13883 return 0; 13884 break; 13885 case BPF_JSGT: 13886 if (reg->s32_min_value > sval) 13887 return 1; 13888 else if (reg->s32_max_value <= sval) 13889 return 0; 13890 break; 13891 case BPF_JLT: 13892 if (reg->u32_max_value < val) 13893 return 1; 13894 else if (reg->u32_min_value >= val) 13895 return 0; 13896 break; 13897 case BPF_JSLT: 13898 if (reg->s32_max_value < sval) 13899 return 1; 13900 else if (reg->s32_min_value >= sval) 13901 return 0; 13902 break; 13903 case BPF_JGE: 13904 if (reg->u32_min_value >= val) 13905 return 1; 13906 else if (reg->u32_max_value < val) 13907 return 0; 13908 break; 13909 case BPF_JSGE: 13910 if (reg->s32_min_value >= sval) 13911 return 1; 13912 else if (reg->s32_max_value < sval) 13913 return 0; 13914 break; 13915 case BPF_JLE: 13916 if (reg->u32_max_value <= val) 13917 return 1; 13918 else if (reg->u32_min_value > val) 13919 return 0; 13920 break; 13921 case BPF_JSLE: 13922 if (reg->s32_max_value <= sval) 13923 return 1; 13924 else if (reg->s32_min_value > sval) 13925 return 0; 13926 break; 13927 } 13928 13929 return -1; 13930 } 13931 13932 13933 static int is_branch64_taken(struct bpf_reg_state *reg, u64 val, u8 opcode) 13934 { 13935 s64 sval = (s64)val; 13936 13937 switch (opcode) { 13938 case BPF_JEQ: 13939 if (tnum_is_const(reg->var_off)) 13940 return !!tnum_equals_const(reg->var_off, val); 13941 else if (val < reg->umin_value || val > reg->umax_value) 13942 return 0; 13943 break; 13944 case BPF_JNE: 13945 if (tnum_is_const(reg->var_off)) 13946 return !tnum_equals_const(reg->var_off, val); 13947 else if (val < reg->umin_value || val > reg->umax_value) 13948 return 1; 13949 break; 13950 case BPF_JSET: 13951 if ((~reg->var_off.mask & reg->var_off.value) & val) 13952 return 1; 13953 if (!((reg->var_off.mask | reg->var_off.value) & val)) 13954 return 0; 13955 break; 13956 case BPF_JGT: 13957 if (reg->umin_value > val) 13958 return 1; 13959 else if (reg->umax_value <= val) 13960 return 0; 13961 break; 13962 case BPF_JSGT: 13963 if (reg->smin_value > sval) 13964 return 1; 13965 else if (reg->smax_value <= sval) 13966 return 0; 13967 break; 13968 case BPF_JLT: 13969 if (reg->umax_value < val) 13970 return 1; 13971 else if (reg->umin_value >= val) 13972 return 0; 13973 break; 13974 case BPF_JSLT: 13975 if (reg->smax_value < sval) 13976 return 1; 13977 else if (reg->smin_value >= sval) 13978 return 0; 13979 break; 13980 case BPF_JGE: 13981 if (reg->umin_value >= val) 13982 return 1; 13983 else if (reg->umax_value < val) 13984 return 0; 13985 break; 13986 case BPF_JSGE: 13987 if (reg->smin_value >= sval) 13988 return 1; 13989 else if (reg->smax_value < sval) 13990 return 0; 13991 break; 13992 case BPF_JLE: 13993 if (reg->umax_value <= val) 13994 return 1; 13995 else if (reg->umin_value > val) 13996 return 0; 13997 break; 13998 case BPF_JSLE: 13999 if (reg->smax_value <= sval) 14000 return 1; 14001 else if (reg->smin_value > sval) 14002 return 0; 14003 break; 14004 } 14005 14006 return -1; 14007 } 14008 14009 /* compute branch direction of the expression "if (reg opcode val) goto target;" 14010 * and return: 14011 * 1 - branch will be taken and "goto target" will be executed 14012 * 0 - branch will not be taken and fall-through to next insn 14013 * -1 - unknown. Example: "if (reg < 5)" is unknown when register value 14014 * range [0,10] 14015 */ 14016 static int is_branch_taken(struct bpf_reg_state *reg, u64 val, u8 opcode, 14017 bool is_jmp32) 14018 { 14019 if (__is_pointer_value(false, reg)) { 14020 if (!reg_not_null(reg)) 14021 return -1; 14022 14023 /* If pointer is valid tests against zero will fail so we can 14024 * use this to direct branch taken. 14025 */ 14026 if (val != 0) 14027 return -1; 14028 14029 switch (opcode) { 14030 case BPF_JEQ: 14031 return 0; 14032 case BPF_JNE: 14033 return 1; 14034 default: 14035 return -1; 14036 } 14037 } 14038 14039 if (is_jmp32) 14040 return is_branch32_taken(reg, val, opcode); 14041 return is_branch64_taken(reg, val, opcode); 14042 } 14043 14044 static int flip_opcode(u32 opcode) 14045 { 14046 /* How can we transform "a <op> b" into "b <op> a"? */ 14047 static const u8 opcode_flip[16] = { 14048 /* these stay the same */ 14049 [BPF_JEQ >> 4] = BPF_JEQ, 14050 [BPF_JNE >> 4] = BPF_JNE, 14051 [BPF_JSET >> 4] = BPF_JSET, 14052 /* these swap "lesser" and "greater" (L and G in the opcodes) */ 14053 [BPF_JGE >> 4] = BPF_JLE, 14054 [BPF_JGT >> 4] = BPF_JLT, 14055 [BPF_JLE >> 4] = BPF_JGE, 14056 [BPF_JLT >> 4] = BPF_JGT, 14057 [BPF_JSGE >> 4] = BPF_JSLE, 14058 [BPF_JSGT >> 4] = BPF_JSLT, 14059 [BPF_JSLE >> 4] = BPF_JSGE, 14060 [BPF_JSLT >> 4] = BPF_JSGT 14061 }; 14062 return opcode_flip[opcode >> 4]; 14063 } 14064 14065 static int is_pkt_ptr_branch_taken(struct bpf_reg_state *dst_reg, 14066 struct bpf_reg_state *src_reg, 14067 u8 opcode) 14068 { 14069 struct bpf_reg_state *pkt; 14070 14071 if (src_reg->type == PTR_TO_PACKET_END) { 14072 pkt = dst_reg; 14073 } else if (dst_reg->type == PTR_TO_PACKET_END) { 14074 pkt = src_reg; 14075 opcode = flip_opcode(opcode); 14076 } else { 14077 return -1; 14078 } 14079 14080 if (pkt->range >= 0) 14081 return -1; 14082 14083 switch (opcode) { 14084 case BPF_JLE: 14085 /* pkt <= pkt_end */ 14086 fallthrough; 14087 case BPF_JGT: 14088 /* pkt > pkt_end */ 14089 if (pkt->range == BEYOND_PKT_END) 14090 /* pkt has at last one extra byte beyond pkt_end */ 14091 return opcode == BPF_JGT; 14092 break; 14093 case BPF_JLT: 14094 /* pkt < pkt_end */ 14095 fallthrough; 14096 case BPF_JGE: 14097 /* pkt >= pkt_end */ 14098 if (pkt->range == BEYOND_PKT_END || pkt->range == AT_PKT_END) 14099 return opcode == BPF_JGE; 14100 break; 14101 } 14102 return -1; 14103 } 14104 14105 /* Adjusts the register min/max values in the case that the dst_reg is the 14106 * variable register that we are working on, and src_reg is a constant or we're 14107 * simply doing a BPF_K check. 14108 * In JEQ/JNE cases we also adjust the var_off values. 14109 */ 14110 static void reg_set_min_max(struct bpf_reg_state *true_reg, 14111 struct bpf_reg_state *false_reg, 14112 u64 val, u32 val32, 14113 u8 opcode, bool is_jmp32) 14114 { 14115 struct tnum false_32off = tnum_subreg(false_reg->var_off); 14116 struct tnum false_64off = false_reg->var_off; 14117 struct tnum true_32off = tnum_subreg(true_reg->var_off); 14118 struct tnum true_64off = true_reg->var_off; 14119 s64 sval = (s64)val; 14120 s32 sval32 = (s32)val32; 14121 14122 /* If the dst_reg is a pointer, we can't learn anything about its 14123 * variable offset from the compare (unless src_reg were a pointer into 14124 * the same object, but we don't bother with that. 14125 * Since false_reg and true_reg have the same type by construction, we 14126 * only need to check one of them for pointerness. 14127 */ 14128 if (__is_pointer_value(false, false_reg)) 14129 return; 14130 14131 switch (opcode) { 14132 /* JEQ/JNE comparison doesn't change the register equivalence. 14133 * 14134 * r1 = r2; 14135 * if (r1 == 42) goto label; 14136 * ... 14137 * label: // here both r1 and r2 are known to be 42. 14138 * 14139 * Hence when marking register as known preserve it's ID. 14140 */ 14141 case BPF_JEQ: 14142 if (is_jmp32) { 14143 __mark_reg32_known(true_reg, val32); 14144 true_32off = tnum_subreg(true_reg->var_off); 14145 } else { 14146 ___mark_reg_known(true_reg, val); 14147 true_64off = true_reg->var_off; 14148 } 14149 break; 14150 case BPF_JNE: 14151 if (is_jmp32) { 14152 __mark_reg32_known(false_reg, val32); 14153 false_32off = tnum_subreg(false_reg->var_off); 14154 } else { 14155 ___mark_reg_known(false_reg, val); 14156 false_64off = false_reg->var_off; 14157 } 14158 break; 14159 case BPF_JSET: 14160 if (is_jmp32) { 14161 false_32off = tnum_and(false_32off, tnum_const(~val32)); 14162 if (is_power_of_2(val32)) 14163 true_32off = tnum_or(true_32off, 14164 tnum_const(val32)); 14165 } else { 14166 false_64off = tnum_and(false_64off, tnum_const(~val)); 14167 if (is_power_of_2(val)) 14168 true_64off = tnum_or(true_64off, 14169 tnum_const(val)); 14170 } 14171 break; 14172 case BPF_JGE: 14173 case BPF_JGT: 14174 { 14175 if (is_jmp32) { 14176 u32 false_umax = opcode == BPF_JGT ? val32 : val32 - 1; 14177 u32 true_umin = opcode == BPF_JGT ? val32 + 1 : val32; 14178 14179 false_reg->u32_max_value = min(false_reg->u32_max_value, 14180 false_umax); 14181 true_reg->u32_min_value = max(true_reg->u32_min_value, 14182 true_umin); 14183 } else { 14184 u64 false_umax = opcode == BPF_JGT ? val : val - 1; 14185 u64 true_umin = opcode == BPF_JGT ? val + 1 : val; 14186 14187 false_reg->umax_value = min(false_reg->umax_value, false_umax); 14188 true_reg->umin_value = max(true_reg->umin_value, true_umin); 14189 } 14190 break; 14191 } 14192 case BPF_JSGE: 14193 case BPF_JSGT: 14194 { 14195 if (is_jmp32) { 14196 s32 false_smax = opcode == BPF_JSGT ? sval32 : sval32 - 1; 14197 s32 true_smin = opcode == BPF_JSGT ? sval32 + 1 : sval32; 14198 14199 false_reg->s32_max_value = min(false_reg->s32_max_value, false_smax); 14200 true_reg->s32_min_value = max(true_reg->s32_min_value, true_smin); 14201 } else { 14202 s64 false_smax = opcode == BPF_JSGT ? sval : sval - 1; 14203 s64 true_smin = opcode == BPF_JSGT ? sval + 1 : sval; 14204 14205 false_reg->smax_value = min(false_reg->smax_value, false_smax); 14206 true_reg->smin_value = max(true_reg->smin_value, true_smin); 14207 } 14208 break; 14209 } 14210 case BPF_JLE: 14211 case BPF_JLT: 14212 { 14213 if (is_jmp32) { 14214 u32 false_umin = opcode == BPF_JLT ? val32 : val32 + 1; 14215 u32 true_umax = opcode == BPF_JLT ? val32 - 1 : val32; 14216 14217 false_reg->u32_min_value = max(false_reg->u32_min_value, 14218 false_umin); 14219 true_reg->u32_max_value = min(true_reg->u32_max_value, 14220 true_umax); 14221 } else { 14222 u64 false_umin = opcode == BPF_JLT ? val : val + 1; 14223 u64 true_umax = opcode == BPF_JLT ? val - 1 : val; 14224 14225 false_reg->umin_value = max(false_reg->umin_value, false_umin); 14226 true_reg->umax_value = min(true_reg->umax_value, true_umax); 14227 } 14228 break; 14229 } 14230 case BPF_JSLE: 14231 case BPF_JSLT: 14232 { 14233 if (is_jmp32) { 14234 s32 false_smin = opcode == BPF_JSLT ? sval32 : sval32 + 1; 14235 s32 true_smax = opcode == BPF_JSLT ? sval32 - 1 : sval32; 14236 14237 false_reg->s32_min_value = max(false_reg->s32_min_value, false_smin); 14238 true_reg->s32_max_value = min(true_reg->s32_max_value, true_smax); 14239 } else { 14240 s64 false_smin = opcode == BPF_JSLT ? sval : sval + 1; 14241 s64 true_smax = opcode == BPF_JSLT ? sval - 1 : sval; 14242 14243 false_reg->smin_value = max(false_reg->smin_value, false_smin); 14244 true_reg->smax_value = min(true_reg->smax_value, true_smax); 14245 } 14246 break; 14247 } 14248 default: 14249 return; 14250 } 14251 14252 if (is_jmp32) { 14253 false_reg->var_off = tnum_or(tnum_clear_subreg(false_64off), 14254 tnum_subreg(false_32off)); 14255 true_reg->var_off = tnum_or(tnum_clear_subreg(true_64off), 14256 tnum_subreg(true_32off)); 14257 __reg_combine_32_into_64(false_reg); 14258 __reg_combine_32_into_64(true_reg); 14259 } else { 14260 false_reg->var_off = false_64off; 14261 true_reg->var_off = true_64off; 14262 __reg_combine_64_into_32(false_reg); 14263 __reg_combine_64_into_32(true_reg); 14264 } 14265 } 14266 14267 /* Same as above, but for the case that dst_reg holds a constant and src_reg is 14268 * the variable reg. 14269 */ 14270 static void reg_set_min_max_inv(struct bpf_reg_state *true_reg, 14271 struct bpf_reg_state *false_reg, 14272 u64 val, u32 val32, 14273 u8 opcode, bool is_jmp32) 14274 { 14275 opcode = flip_opcode(opcode); 14276 /* This uses zero as "not present in table"; luckily the zero opcode, 14277 * BPF_JA, can't get here. 14278 */ 14279 if (opcode) 14280 reg_set_min_max(true_reg, false_reg, val, val32, opcode, is_jmp32); 14281 } 14282 14283 /* Regs are known to be equal, so intersect their min/max/var_off */ 14284 static void __reg_combine_min_max(struct bpf_reg_state *src_reg, 14285 struct bpf_reg_state *dst_reg) 14286 { 14287 src_reg->umin_value = dst_reg->umin_value = max(src_reg->umin_value, 14288 dst_reg->umin_value); 14289 src_reg->umax_value = dst_reg->umax_value = min(src_reg->umax_value, 14290 dst_reg->umax_value); 14291 src_reg->smin_value = dst_reg->smin_value = max(src_reg->smin_value, 14292 dst_reg->smin_value); 14293 src_reg->smax_value = dst_reg->smax_value = min(src_reg->smax_value, 14294 dst_reg->smax_value); 14295 src_reg->var_off = dst_reg->var_off = tnum_intersect(src_reg->var_off, 14296 dst_reg->var_off); 14297 reg_bounds_sync(src_reg); 14298 reg_bounds_sync(dst_reg); 14299 } 14300 14301 static void reg_combine_min_max(struct bpf_reg_state *true_src, 14302 struct bpf_reg_state *true_dst, 14303 struct bpf_reg_state *false_src, 14304 struct bpf_reg_state *false_dst, 14305 u8 opcode) 14306 { 14307 switch (opcode) { 14308 case BPF_JEQ: 14309 __reg_combine_min_max(true_src, true_dst); 14310 break; 14311 case BPF_JNE: 14312 __reg_combine_min_max(false_src, false_dst); 14313 break; 14314 } 14315 } 14316 14317 static void mark_ptr_or_null_reg(struct bpf_func_state *state, 14318 struct bpf_reg_state *reg, u32 id, 14319 bool is_null) 14320 { 14321 if (type_may_be_null(reg->type) && reg->id == id && 14322 (is_rcu_reg(reg) || !WARN_ON_ONCE(!reg->id))) { 14323 /* Old offset (both fixed and variable parts) should have been 14324 * known-zero, because we don't allow pointer arithmetic on 14325 * pointers that might be NULL. If we see this happening, don't 14326 * convert the register. 14327 * 14328 * But in some cases, some helpers that return local kptrs 14329 * advance offset for the returned pointer. In those cases, it 14330 * is fine to expect to see reg->off. 14331 */ 14332 if (WARN_ON_ONCE(reg->smin_value || reg->smax_value || !tnum_equals_const(reg->var_off, 0))) 14333 return; 14334 if (!(type_is_ptr_alloc_obj(reg->type) || type_is_non_owning_ref(reg->type)) && 14335 WARN_ON_ONCE(reg->off)) 14336 return; 14337 14338 if (is_null) { 14339 reg->type = SCALAR_VALUE; 14340 /* We don't need id and ref_obj_id from this point 14341 * onwards anymore, thus we should better reset it, 14342 * so that state pruning has chances to take effect. 14343 */ 14344 reg->id = 0; 14345 reg->ref_obj_id = 0; 14346 14347 return; 14348 } 14349 14350 mark_ptr_not_null_reg(reg); 14351 14352 if (!reg_may_point_to_spin_lock(reg)) { 14353 /* For not-NULL ptr, reg->ref_obj_id will be reset 14354 * in release_reference(). 14355 * 14356 * reg->id is still used by spin_lock ptr. Other 14357 * than spin_lock ptr type, reg->id can be reset. 14358 */ 14359 reg->id = 0; 14360 } 14361 } 14362 } 14363 14364 /* The logic is similar to find_good_pkt_pointers(), both could eventually 14365 * be folded together at some point. 14366 */ 14367 static void mark_ptr_or_null_regs(struct bpf_verifier_state *vstate, u32 regno, 14368 bool is_null) 14369 { 14370 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 14371 struct bpf_reg_state *regs = state->regs, *reg; 14372 u32 ref_obj_id = regs[regno].ref_obj_id; 14373 u32 id = regs[regno].id; 14374 14375 if (ref_obj_id && ref_obj_id == id && is_null) 14376 /* regs[regno] is in the " == NULL" branch. 14377 * No one could have freed the reference state before 14378 * doing the NULL check. 14379 */ 14380 WARN_ON_ONCE(release_reference_state(state, id)); 14381 14382 bpf_for_each_reg_in_vstate(vstate, state, reg, ({ 14383 mark_ptr_or_null_reg(state, reg, id, is_null); 14384 })); 14385 } 14386 14387 static bool try_match_pkt_pointers(const struct bpf_insn *insn, 14388 struct bpf_reg_state *dst_reg, 14389 struct bpf_reg_state *src_reg, 14390 struct bpf_verifier_state *this_branch, 14391 struct bpf_verifier_state *other_branch) 14392 { 14393 if (BPF_SRC(insn->code) != BPF_X) 14394 return false; 14395 14396 /* Pointers are always 64-bit. */ 14397 if (BPF_CLASS(insn->code) == BPF_JMP32) 14398 return false; 14399 14400 switch (BPF_OP(insn->code)) { 14401 case BPF_JGT: 14402 if ((dst_reg->type == PTR_TO_PACKET && 14403 src_reg->type == PTR_TO_PACKET_END) || 14404 (dst_reg->type == PTR_TO_PACKET_META && 14405 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) { 14406 /* pkt_data' > pkt_end, pkt_meta' > pkt_data */ 14407 find_good_pkt_pointers(this_branch, dst_reg, 14408 dst_reg->type, false); 14409 mark_pkt_end(other_branch, insn->dst_reg, true); 14410 } else if ((dst_reg->type == PTR_TO_PACKET_END && 14411 src_reg->type == PTR_TO_PACKET) || 14412 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) && 14413 src_reg->type == PTR_TO_PACKET_META)) { 14414 /* pkt_end > pkt_data', pkt_data > pkt_meta' */ 14415 find_good_pkt_pointers(other_branch, src_reg, 14416 src_reg->type, true); 14417 mark_pkt_end(this_branch, insn->src_reg, false); 14418 } else { 14419 return false; 14420 } 14421 break; 14422 case BPF_JLT: 14423 if ((dst_reg->type == PTR_TO_PACKET && 14424 src_reg->type == PTR_TO_PACKET_END) || 14425 (dst_reg->type == PTR_TO_PACKET_META && 14426 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) { 14427 /* pkt_data' < pkt_end, pkt_meta' < pkt_data */ 14428 find_good_pkt_pointers(other_branch, dst_reg, 14429 dst_reg->type, true); 14430 mark_pkt_end(this_branch, insn->dst_reg, false); 14431 } else if ((dst_reg->type == PTR_TO_PACKET_END && 14432 src_reg->type == PTR_TO_PACKET) || 14433 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) && 14434 src_reg->type == PTR_TO_PACKET_META)) { 14435 /* pkt_end < pkt_data', pkt_data > pkt_meta' */ 14436 find_good_pkt_pointers(this_branch, src_reg, 14437 src_reg->type, false); 14438 mark_pkt_end(other_branch, insn->src_reg, true); 14439 } else { 14440 return false; 14441 } 14442 break; 14443 case BPF_JGE: 14444 if ((dst_reg->type == PTR_TO_PACKET && 14445 src_reg->type == PTR_TO_PACKET_END) || 14446 (dst_reg->type == PTR_TO_PACKET_META && 14447 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) { 14448 /* pkt_data' >= pkt_end, pkt_meta' >= pkt_data */ 14449 find_good_pkt_pointers(this_branch, dst_reg, 14450 dst_reg->type, true); 14451 mark_pkt_end(other_branch, insn->dst_reg, false); 14452 } else if ((dst_reg->type == PTR_TO_PACKET_END && 14453 src_reg->type == PTR_TO_PACKET) || 14454 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) && 14455 src_reg->type == PTR_TO_PACKET_META)) { 14456 /* pkt_end >= pkt_data', pkt_data >= pkt_meta' */ 14457 find_good_pkt_pointers(other_branch, src_reg, 14458 src_reg->type, false); 14459 mark_pkt_end(this_branch, insn->src_reg, true); 14460 } else { 14461 return false; 14462 } 14463 break; 14464 case BPF_JLE: 14465 if ((dst_reg->type == PTR_TO_PACKET && 14466 src_reg->type == PTR_TO_PACKET_END) || 14467 (dst_reg->type == PTR_TO_PACKET_META && 14468 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) { 14469 /* pkt_data' <= pkt_end, pkt_meta' <= pkt_data */ 14470 find_good_pkt_pointers(other_branch, dst_reg, 14471 dst_reg->type, false); 14472 mark_pkt_end(this_branch, insn->dst_reg, true); 14473 } else if ((dst_reg->type == PTR_TO_PACKET_END && 14474 src_reg->type == PTR_TO_PACKET) || 14475 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) && 14476 src_reg->type == PTR_TO_PACKET_META)) { 14477 /* pkt_end <= pkt_data', pkt_data <= pkt_meta' */ 14478 find_good_pkt_pointers(this_branch, src_reg, 14479 src_reg->type, true); 14480 mark_pkt_end(other_branch, insn->src_reg, false); 14481 } else { 14482 return false; 14483 } 14484 break; 14485 default: 14486 return false; 14487 } 14488 14489 return true; 14490 } 14491 14492 static void find_equal_scalars(struct bpf_verifier_state *vstate, 14493 struct bpf_reg_state *known_reg) 14494 { 14495 struct bpf_func_state *state; 14496 struct bpf_reg_state *reg; 14497 14498 bpf_for_each_reg_in_vstate(vstate, state, reg, ({ 14499 if (reg->type == SCALAR_VALUE && reg->id == known_reg->id) 14500 copy_register_state(reg, known_reg); 14501 })); 14502 } 14503 14504 static int check_cond_jmp_op(struct bpf_verifier_env *env, 14505 struct bpf_insn *insn, int *insn_idx) 14506 { 14507 struct bpf_verifier_state *this_branch = env->cur_state; 14508 struct bpf_verifier_state *other_branch; 14509 struct bpf_reg_state *regs = this_branch->frame[this_branch->curframe]->regs; 14510 struct bpf_reg_state *dst_reg, *other_branch_regs, *src_reg = NULL; 14511 struct bpf_reg_state *eq_branch_regs; 14512 u8 opcode = BPF_OP(insn->code); 14513 bool is_jmp32; 14514 int pred = -1; 14515 int err; 14516 14517 /* Only conditional jumps are expected to reach here. */ 14518 if (opcode == BPF_JA || opcode > BPF_JSLE) { 14519 verbose(env, "invalid BPF_JMP/JMP32 opcode %x\n", opcode); 14520 return -EINVAL; 14521 } 14522 14523 /* check src2 operand */ 14524 err = check_reg_arg(env, insn->dst_reg, SRC_OP); 14525 if (err) 14526 return err; 14527 14528 dst_reg = ®s[insn->dst_reg]; 14529 if (BPF_SRC(insn->code) == BPF_X) { 14530 if (insn->imm != 0) { 14531 verbose(env, "BPF_JMP/JMP32 uses reserved fields\n"); 14532 return -EINVAL; 14533 } 14534 14535 /* check src1 operand */ 14536 err = check_reg_arg(env, insn->src_reg, SRC_OP); 14537 if (err) 14538 return err; 14539 14540 src_reg = ®s[insn->src_reg]; 14541 if (!(reg_is_pkt_pointer_any(dst_reg) && reg_is_pkt_pointer_any(src_reg)) && 14542 is_pointer_value(env, insn->src_reg)) { 14543 verbose(env, "R%d pointer comparison prohibited\n", 14544 insn->src_reg); 14545 return -EACCES; 14546 } 14547 } else { 14548 if (insn->src_reg != BPF_REG_0) { 14549 verbose(env, "BPF_JMP/JMP32 uses reserved fields\n"); 14550 return -EINVAL; 14551 } 14552 } 14553 14554 is_jmp32 = BPF_CLASS(insn->code) == BPF_JMP32; 14555 14556 if (BPF_SRC(insn->code) == BPF_K) { 14557 pred = is_branch_taken(dst_reg, insn->imm, opcode, is_jmp32); 14558 } else if (src_reg->type == SCALAR_VALUE && 14559 is_jmp32 && tnum_is_const(tnum_subreg(src_reg->var_off))) { 14560 pred = is_branch_taken(dst_reg, 14561 tnum_subreg(src_reg->var_off).value, 14562 opcode, 14563 is_jmp32); 14564 } else if (src_reg->type == SCALAR_VALUE && 14565 !is_jmp32 && tnum_is_const(src_reg->var_off)) { 14566 pred = is_branch_taken(dst_reg, 14567 src_reg->var_off.value, 14568 opcode, 14569 is_jmp32); 14570 } else if (dst_reg->type == SCALAR_VALUE && 14571 is_jmp32 && tnum_is_const(tnum_subreg(dst_reg->var_off))) { 14572 pred = is_branch_taken(src_reg, 14573 tnum_subreg(dst_reg->var_off).value, 14574 flip_opcode(opcode), 14575 is_jmp32); 14576 } else if (dst_reg->type == SCALAR_VALUE && 14577 !is_jmp32 && tnum_is_const(dst_reg->var_off)) { 14578 pred = is_branch_taken(src_reg, 14579 dst_reg->var_off.value, 14580 flip_opcode(opcode), 14581 is_jmp32); 14582 } else if (reg_is_pkt_pointer_any(dst_reg) && 14583 reg_is_pkt_pointer_any(src_reg) && 14584 !is_jmp32) { 14585 pred = is_pkt_ptr_branch_taken(dst_reg, src_reg, opcode); 14586 } 14587 14588 if (pred >= 0) { 14589 /* If we get here with a dst_reg pointer type it is because 14590 * above is_branch_taken() special cased the 0 comparison. 14591 */ 14592 if (!__is_pointer_value(false, dst_reg)) 14593 err = mark_chain_precision(env, insn->dst_reg); 14594 if (BPF_SRC(insn->code) == BPF_X && !err && 14595 !__is_pointer_value(false, src_reg)) 14596 err = mark_chain_precision(env, insn->src_reg); 14597 if (err) 14598 return err; 14599 } 14600 14601 if (pred == 1) { 14602 /* Only follow the goto, ignore fall-through. If needed, push 14603 * the fall-through branch for simulation under speculative 14604 * execution. 14605 */ 14606 if (!env->bypass_spec_v1 && 14607 !sanitize_speculative_path(env, insn, *insn_idx + 1, 14608 *insn_idx)) 14609 return -EFAULT; 14610 if (env->log.level & BPF_LOG_LEVEL) 14611 print_insn_state(env, this_branch->frame[this_branch->curframe]); 14612 *insn_idx += insn->off; 14613 return 0; 14614 } else if (pred == 0) { 14615 /* Only follow the fall-through branch, since that's where the 14616 * program will go. If needed, push the goto branch for 14617 * simulation under speculative execution. 14618 */ 14619 if (!env->bypass_spec_v1 && 14620 !sanitize_speculative_path(env, insn, 14621 *insn_idx + insn->off + 1, 14622 *insn_idx)) 14623 return -EFAULT; 14624 if (env->log.level & BPF_LOG_LEVEL) 14625 print_insn_state(env, this_branch->frame[this_branch->curframe]); 14626 return 0; 14627 } 14628 14629 other_branch = push_stack(env, *insn_idx + insn->off + 1, *insn_idx, 14630 false); 14631 if (!other_branch) 14632 return -EFAULT; 14633 other_branch_regs = other_branch->frame[other_branch->curframe]->regs; 14634 14635 /* detect if we are comparing against a constant value so we can adjust 14636 * our min/max values for our dst register. 14637 * this is only legit if both are scalars (or pointers to the same 14638 * object, I suppose, see the PTR_MAYBE_NULL related if block below), 14639 * because otherwise the different base pointers mean the offsets aren't 14640 * comparable. 14641 */ 14642 if (BPF_SRC(insn->code) == BPF_X) { 14643 struct bpf_reg_state *src_reg = ®s[insn->src_reg]; 14644 14645 if (dst_reg->type == SCALAR_VALUE && 14646 src_reg->type == SCALAR_VALUE) { 14647 if (tnum_is_const(src_reg->var_off) || 14648 (is_jmp32 && 14649 tnum_is_const(tnum_subreg(src_reg->var_off)))) 14650 reg_set_min_max(&other_branch_regs[insn->dst_reg], 14651 dst_reg, 14652 src_reg->var_off.value, 14653 tnum_subreg(src_reg->var_off).value, 14654 opcode, is_jmp32); 14655 else if (tnum_is_const(dst_reg->var_off) || 14656 (is_jmp32 && 14657 tnum_is_const(tnum_subreg(dst_reg->var_off)))) 14658 reg_set_min_max_inv(&other_branch_regs[insn->src_reg], 14659 src_reg, 14660 dst_reg->var_off.value, 14661 tnum_subreg(dst_reg->var_off).value, 14662 opcode, is_jmp32); 14663 else if (!is_jmp32 && 14664 (opcode == BPF_JEQ || opcode == BPF_JNE)) 14665 /* Comparing for equality, we can combine knowledge */ 14666 reg_combine_min_max(&other_branch_regs[insn->src_reg], 14667 &other_branch_regs[insn->dst_reg], 14668 src_reg, dst_reg, opcode); 14669 if (src_reg->id && 14670 !WARN_ON_ONCE(src_reg->id != other_branch_regs[insn->src_reg].id)) { 14671 find_equal_scalars(this_branch, src_reg); 14672 find_equal_scalars(other_branch, &other_branch_regs[insn->src_reg]); 14673 } 14674 14675 } 14676 } else if (dst_reg->type == SCALAR_VALUE) { 14677 reg_set_min_max(&other_branch_regs[insn->dst_reg], 14678 dst_reg, insn->imm, (u32)insn->imm, 14679 opcode, is_jmp32); 14680 } 14681 14682 if (dst_reg->type == SCALAR_VALUE && dst_reg->id && 14683 !WARN_ON_ONCE(dst_reg->id != other_branch_regs[insn->dst_reg].id)) { 14684 find_equal_scalars(this_branch, dst_reg); 14685 find_equal_scalars(other_branch, &other_branch_regs[insn->dst_reg]); 14686 } 14687 14688 /* if one pointer register is compared to another pointer 14689 * register check if PTR_MAYBE_NULL could be lifted. 14690 * E.g. register A - maybe null 14691 * register B - not null 14692 * for JNE A, B, ... - A is not null in the false branch; 14693 * for JEQ A, B, ... - A is not null in the true branch. 14694 * 14695 * Since PTR_TO_BTF_ID points to a kernel struct that does 14696 * not need to be null checked by the BPF program, i.e., 14697 * could be null even without PTR_MAYBE_NULL marking, so 14698 * only propagate nullness when neither reg is that type. 14699 */ 14700 if (!is_jmp32 && BPF_SRC(insn->code) == BPF_X && 14701 __is_pointer_value(false, src_reg) && __is_pointer_value(false, dst_reg) && 14702 type_may_be_null(src_reg->type) != type_may_be_null(dst_reg->type) && 14703 base_type(src_reg->type) != PTR_TO_BTF_ID && 14704 base_type(dst_reg->type) != PTR_TO_BTF_ID) { 14705 eq_branch_regs = NULL; 14706 switch (opcode) { 14707 case BPF_JEQ: 14708 eq_branch_regs = other_branch_regs; 14709 break; 14710 case BPF_JNE: 14711 eq_branch_regs = regs; 14712 break; 14713 default: 14714 /* do nothing */ 14715 break; 14716 } 14717 if (eq_branch_regs) { 14718 if (type_may_be_null(src_reg->type)) 14719 mark_ptr_not_null_reg(&eq_branch_regs[insn->src_reg]); 14720 else 14721 mark_ptr_not_null_reg(&eq_branch_regs[insn->dst_reg]); 14722 } 14723 } 14724 14725 /* detect if R == 0 where R is returned from bpf_map_lookup_elem(). 14726 * NOTE: these optimizations below are related with pointer comparison 14727 * which will never be JMP32. 14728 */ 14729 if (!is_jmp32 && BPF_SRC(insn->code) == BPF_K && 14730 insn->imm == 0 && (opcode == BPF_JEQ || opcode == BPF_JNE) && 14731 type_may_be_null(dst_reg->type)) { 14732 /* Mark all identical registers in each branch as either 14733 * safe or unknown depending R == 0 or R != 0 conditional. 14734 */ 14735 mark_ptr_or_null_regs(this_branch, insn->dst_reg, 14736 opcode == BPF_JNE); 14737 mark_ptr_or_null_regs(other_branch, insn->dst_reg, 14738 opcode == BPF_JEQ); 14739 } else if (!try_match_pkt_pointers(insn, dst_reg, ®s[insn->src_reg], 14740 this_branch, other_branch) && 14741 is_pointer_value(env, insn->dst_reg)) { 14742 verbose(env, "R%d pointer comparison prohibited\n", 14743 insn->dst_reg); 14744 return -EACCES; 14745 } 14746 if (env->log.level & BPF_LOG_LEVEL) 14747 print_insn_state(env, this_branch->frame[this_branch->curframe]); 14748 return 0; 14749 } 14750 14751 /* verify BPF_LD_IMM64 instruction */ 14752 static int check_ld_imm(struct bpf_verifier_env *env, struct bpf_insn *insn) 14753 { 14754 struct bpf_insn_aux_data *aux = cur_aux(env); 14755 struct bpf_reg_state *regs = cur_regs(env); 14756 struct bpf_reg_state *dst_reg; 14757 struct bpf_map *map; 14758 int err; 14759 14760 if (BPF_SIZE(insn->code) != BPF_DW) { 14761 verbose(env, "invalid BPF_LD_IMM insn\n"); 14762 return -EINVAL; 14763 } 14764 if (insn->off != 0) { 14765 verbose(env, "BPF_LD_IMM64 uses reserved fields\n"); 14766 return -EINVAL; 14767 } 14768 14769 err = check_reg_arg(env, insn->dst_reg, DST_OP); 14770 if (err) 14771 return err; 14772 14773 dst_reg = ®s[insn->dst_reg]; 14774 if (insn->src_reg == 0) { 14775 u64 imm = ((u64)(insn + 1)->imm << 32) | (u32)insn->imm; 14776 14777 dst_reg->type = SCALAR_VALUE; 14778 __mark_reg_known(®s[insn->dst_reg], imm); 14779 return 0; 14780 } 14781 14782 /* All special src_reg cases are listed below. From this point onwards 14783 * we either succeed and assign a corresponding dst_reg->type after 14784 * zeroing the offset, or fail and reject the program. 14785 */ 14786 mark_reg_known_zero(env, regs, insn->dst_reg); 14787 14788 if (insn->src_reg == BPF_PSEUDO_BTF_ID) { 14789 dst_reg->type = aux->btf_var.reg_type; 14790 switch (base_type(dst_reg->type)) { 14791 case PTR_TO_MEM: 14792 dst_reg->mem_size = aux->btf_var.mem_size; 14793 break; 14794 case PTR_TO_BTF_ID: 14795 dst_reg->btf = aux->btf_var.btf; 14796 dst_reg->btf_id = aux->btf_var.btf_id; 14797 break; 14798 default: 14799 verbose(env, "bpf verifier is misconfigured\n"); 14800 return -EFAULT; 14801 } 14802 return 0; 14803 } 14804 14805 if (insn->src_reg == BPF_PSEUDO_FUNC) { 14806 struct bpf_prog_aux *aux = env->prog->aux; 14807 u32 subprogno = find_subprog(env, 14808 env->insn_idx + insn->imm + 1); 14809 14810 if (!aux->func_info) { 14811 verbose(env, "missing btf func_info\n"); 14812 return -EINVAL; 14813 } 14814 if (aux->func_info_aux[subprogno].linkage != BTF_FUNC_STATIC) { 14815 verbose(env, "callback function not static\n"); 14816 return -EINVAL; 14817 } 14818 14819 dst_reg->type = PTR_TO_FUNC; 14820 dst_reg->subprogno = subprogno; 14821 return 0; 14822 } 14823 14824 map = env->used_maps[aux->map_index]; 14825 dst_reg->map_ptr = map; 14826 14827 if (insn->src_reg == BPF_PSEUDO_MAP_VALUE || 14828 insn->src_reg == BPF_PSEUDO_MAP_IDX_VALUE) { 14829 dst_reg->type = PTR_TO_MAP_VALUE; 14830 dst_reg->off = aux->map_off; 14831 WARN_ON_ONCE(map->max_entries != 1); 14832 /* We want reg->id to be same (0) as map_value is not distinct */ 14833 } else if (insn->src_reg == BPF_PSEUDO_MAP_FD || 14834 insn->src_reg == BPF_PSEUDO_MAP_IDX) { 14835 dst_reg->type = CONST_PTR_TO_MAP; 14836 } else { 14837 verbose(env, "bpf verifier is misconfigured\n"); 14838 return -EINVAL; 14839 } 14840 14841 return 0; 14842 } 14843 14844 static bool may_access_skb(enum bpf_prog_type type) 14845 { 14846 switch (type) { 14847 case BPF_PROG_TYPE_SOCKET_FILTER: 14848 case BPF_PROG_TYPE_SCHED_CLS: 14849 case BPF_PROG_TYPE_SCHED_ACT: 14850 return true; 14851 default: 14852 return false; 14853 } 14854 } 14855 14856 /* verify safety of LD_ABS|LD_IND instructions: 14857 * - they can only appear in the programs where ctx == skb 14858 * - since they are wrappers of function calls, they scratch R1-R5 registers, 14859 * preserve R6-R9, and store return value into R0 14860 * 14861 * Implicit input: 14862 * ctx == skb == R6 == CTX 14863 * 14864 * Explicit input: 14865 * SRC == any register 14866 * IMM == 32-bit immediate 14867 * 14868 * Output: 14869 * R0 - 8/16/32-bit skb data converted to cpu endianness 14870 */ 14871 static int check_ld_abs(struct bpf_verifier_env *env, struct bpf_insn *insn) 14872 { 14873 struct bpf_reg_state *regs = cur_regs(env); 14874 static const int ctx_reg = BPF_REG_6; 14875 u8 mode = BPF_MODE(insn->code); 14876 int i, err; 14877 14878 if (!may_access_skb(resolve_prog_type(env->prog))) { 14879 verbose(env, "BPF_LD_[ABS|IND] instructions not allowed for this program type\n"); 14880 return -EINVAL; 14881 } 14882 14883 if (!env->ops->gen_ld_abs) { 14884 verbose(env, "bpf verifier is misconfigured\n"); 14885 return -EINVAL; 14886 } 14887 14888 if (insn->dst_reg != BPF_REG_0 || insn->off != 0 || 14889 BPF_SIZE(insn->code) == BPF_DW || 14890 (mode == BPF_ABS && insn->src_reg != BPF_REG_0)) { 14891 verbose(env, "BPF_LD_[ABS|IND] uses reserved fields\n"); 14892 return -EINVAL; 14893 } 14894 14895 /* check whether implicit source operand (register R6) is readable */ 14896 err = check_reg_arg(env, ctx_reg, SRC_OP); 14897 if (err) 14898 return err; 14899 14900 /* Disallow usage of BPF_LD_[ABS|IND] with reference tracking, as 14901 * gen_ld_abs() may terminate the program at runtime, leading to 14902 * reference leak. 14903 */ 14904 err = check_reference_leak(env); 14905 if (err) { 14906 verbose(env, "BPF_LD_[ABS|IND] cannot be mixed with socket references\n"); 14907 return err; 14908 } 14909 14910 if (env->cur_state->active_lock.ptr) { 14911 verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_spin_lock-ed region\n"); 14912 return -EINVAL; 14913 } 14914 14915 if (env->cur_state->active_rcu_lock) { 14916 verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_rcu_read_lock-ed region\n"); 14917 return -EINVAL; 14918 } 14919 14920 if (regs[ctx_reg].type != PTR_TO_CTX) { 14921 verbose(env, 14922 "at the time of BPF_LD_ABS|IND R6 != pointer to skb\n"); 14923 return -EINVAL; 14924 } 14925 14926 if (mode == BPF_IND) { 14927 /* check explicit source operand */ 14928 err = check_reg_arg(env, insn->src_reg, SRC_OP); 14929 if (err) 14930 return err; 14931 } 14932 14933 err = check_ptr_off_reg(env, ®s[ctx_reg], ctx_reg); 14934 if (err < 0) 14935 return err; 14936 14937 /* reset caller saved regs to unreadable */ 14938 for (i = 0; i < CALLER_SAVED_REGS; i++) { 14939 mark_reg_not_init(env, regs, caller_saved[i]); 14940 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK); 14941 } 14942 14943 /* mark destination R0 register as readable, since it contains 14944 * the value fetched from the packet. 14945 * Already marked as written above. 14946 */ 14947 mark_reg_unknown(env, regs, BPF_REG_0); 14948 /* ld_abs load up to 32-bit skb data. */ 14949 regs[BPF_REG_0].subreg_def = env->insn_idx + 1; 14950 return 0; 14951 } 14952 14953 static int check_return_code(struct bpf_verifier_env *env) 14954 { 14955 struct tnum enforce_attach_type_range = tnum_unknown; 14956 const struct bpf_prog *prog = env->prog; 14957 struct bpf_reg_state *reg; 14958 struct tnum range = tnum_range(0, 1), const_0 = tnum_const(0); 14959 enum bpf_prog_type prog_type = resolve_prog_type(env->prog); 14960 int err; 14961 struct bpf_func_state *frame = env->cur_state->frame[0]; 14962 const bool is_subprog = frame->subprogno; 14963 14964 /* LSM and struct_ops func-ptr's return type could be "void" */ 14965 if (!is_subprog) { 14966 switch (prog_type) { 14967 case BPF_PROG_TYPE_LSM: 14968 if (prog->expected_attach_type == BPF_LSM_CGROUP) 14969 /* See below, can be 0 or 0-1 depending on hook. */ 14970 break; 14971 fallthrough; 14972 case BPF_PROG_TYPE_STRUCT_OPS: 14973 if (!prog->aux->attach_func_proto->type) 14974 return 0; 14975 break; 14976 default: 14977 break; 14978 } 14979 } 14980 14981 /* eBPF calling convention is such that R0 is used 14982 * to return the value from eBPF program. 14983 * Make sure that it's readable at this time 14984 * of bpf_exit, which means that program wrote 14985 * something into it earlier 14986 */ 14987 err = check_reg_arg(env, BPF_REG_0, SRC_OP); 14988 if (err) 14989 return err; 14990 14991 if (is_pointer_value(env, BPF_REG_0)) { 14992 verbose(env, "R0 leaks addr as return value\n"); 14993 return -EACCES; 14994 } 14995 14996 reg = cur_regs(env) + BPF_REG_0; 14997 14998 if (frame->in_async_callback_fn) { 14999 /* enforce return zero from async callbacks like timer */ 15000 if (reg->type != SCALAR_VALUE) { 15001 verbose(env, "In async callback the register R0 is not a known value (%s)\n", 15002 reg_type_str(env, reg->type)); 15003 return -EINVAL; 15004 } 15005 15006 if (!tnum_in(const_0, reg->var_off)) { 15007 verbose_invalid_scalar(env, reg, &const_0, "async callback", "R0"); 15008 return -EINVAL; 15009 } 15010 return 0; 15011 } 15012 15013 if (is_subprog) { 15014 if (reg->type != SCALAR_VALUE) { 15015 verbose(env, "At subprogram exit the register R0 is not a scalar value (%s)\n", 15016 reg_type_str(env, reg->type)); 15017 return -EINVAL; 15018 } 15019 return 0; 15020 } 15021 15022 switch (prog_type) { 15023 case BPF_PROG_TYPE_CGROUP_SOCK_ADDR: 15024 if (env->prog->expected_attach_type == BPF_CGROUP_UDP4_RECVMSG || 15025 env->prog->expected_attach_type == BPF_CGROUP_UDP6_RECVMSG || 15026 env->prog->expected_attach_type == BPF_CGROUP_INET4_GETPEERNAME || 15027 env->prog->expected_attach_type == BPF_CGROUP_INET6_GETPEERNAME || 15028 env->prog->expected_attach_type == BPF_CGROUP_INET4_GETSOCKNAME || 15029 env->prog->expected_attach_type == BPF_CGROUP_INET6_GETSOCKNAME) 15030 range = tnum_range(1, 1); 15031 if (env->prog->expected_attach_type == BPF_CGROUP_INET4_BIND || 15032 env->prog->expected_attach_type == BPF_CGROUP_INET6_BIND) 15033 range = tnum_range(0, 3); 15034 break; 15035 case BPF_PROG_TYPE_CGROUP_SKB: 15036 if (env->prog->expected_attach_type == BPF_CGROUP_INET_EGRESS) { 15037 range = tnum_range(0, 3); 15038 enforce_attach_type_range = tnum_range(2, 3); 15039 } 15040 break; 15041 case BPF_PROG_TYPE_CGROUP_SOCK: 15042 case BPF_PROG_TYPE_SOCK_OPS: 15043 case BPF_PROG_TYPE_CGROUP_DEVICE: 15044 case BPF_PROG_TYPE_CGROUP_SYSCTL: 15045 case BPF_PROG_TYPE_CGROUP_SOCKOPT: 15046 break; 15047 case BPF_PROG_TYPE_RAW_TRACEPOINT: 15048 if (!env->prog->aux->attach_btf_id) 15049 return 0; 15050 range = tnum_const(0); 15051 break; 15052 case BPF_PROG_TYPE_TRACING: 15053 switch (env->prog->expected_attach_type) { 15054 case BPF_TRACE_FENTRY: 15055 case BPF_TRACE_FEXIT: 15056 range = tnum_const(0); 15057 break; 15058 case BPF_TRACE_RAW_TP: 15059 case BPF_MODIFY_RETURN: 15060 return 0; 15061 case BPF_TRACE_ITER: 15062 break; 15063 default: 15064 return -ENOTSUPP; 15065 } 15066 break; 15067 case BPF_PROG_TYPE_SK_LOOKUP: 15068 range = tnum_range(SK_DROP, SK_PASS); 15069 break; 15070 15071 case BPF_PROG_TYPE_LSM: 15072 if (env->prog->expected_attach_type != BPF_LSM_CGROUP) { 15073 /* Regular BPF_PROG_TYPE_LSM programs can return 15074 * any value. 15075 */ 15076 return 0; 15077 } 15078 if (!env->prog->aux->attach_func_proto->type) { 15079 /* Make sure programs that attach to void 15080 * hooks don't try to modify return value. 15081 */ 15082 range = tnum_range(1, 1); 15083 } 15084 break; 15085 15086 case BPF_PROG_TYPE_NETFILTER: 15087 range = tnum_range(NF_DROP, NF_ACCEPT); 15088 break; 15089 case BPF_PROG_TYPE_EXT: 15090 /* freplace program can return anything as its return value 15091 * depends on the to-be-replaced kernel func or bpf program. 15092 */ 15093 default: 15094 return 0; 15095 } 15096 15097 if (reg->type != SCALAR_VALUE) { 15098 verbose(env, "At program exit the register R0 is not a known value (%s)\n", 15099 reg_type_str(env, reg->type)); 15100 return -EINVAL; 15101 } 15102 15103 if (!tnum_in(range, reg->var_off)) { 15104 verbose_invalid_scalar(env, reg, &range, "program exit", "R0"); 15105 if (prog->expected_attach_type == BPF_LSM_CGROUP && 15106 prog_type == BPF_PROG_TYPE_LSM && 15107 !prog->aux->attach_func_proto->type) 15108 verbose(env, "Note, BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n"); 15109 return -EINVAL; 15110 } 15111 15112 if (!tnum_is_unknown(enforce_attach_type_range) && 15113 tnum_in(enforce_attach_type_range, reg->var_off)) 15114 env->prog->enforce_expected_attach_type = 1; 15115 return 0; 15116 } 15117 15118 /* non-recursive DFS pseudo code 15119 * 1 procedure DFS-iterative(G,v): 15120 * 2 label v as discovered 15121 * 3 let S be a stack 15122 * 4 S.push(v) 15123 * 5 while S is not empty 15124 * 6 t <- S.peek() 15125 * 7 if t is what we're looking for: 15126 * 8 return t 15127 * 9 for all edges e in G.adjacentEdges(t) do 15128 * 10 if edge e is already labelled 15129 * 11 continue with the next edge 15130 * 12 w <- G.adjacentVertex(t,e) 15131 * 13 if vertex w is not discovered and not explored 15132 * 14 label e as tree-edge 15133 * 15 label w as discovered 15134 * 16 S.push(w) 15135 * 17 continue at 5 15136 * 18 else if vertex w is discovered 15137 * 19 label e as back-edge 15138 * 20 else 15139 * 21 // vertex w is explored 15140 * 22 label e as forward- or cross-edge 15141 * 23 label t as explored 15142 * 24 S.pop() 15143 * 15144 * convention: 15145 * 0x10 - discovered 15146 * 0x11 - discovered and fall-through edge labelled 15147 * 0x12 - discovered and fall-through and branch edges labelled 15148 * 0x20 - explored 15149 */ 15150 15151 enum { 15152 DISCOVERED = 0x10, 15153 EXPLORED = 0x20, 15154 FALLTHROUGH = 1, 15155 BRANCH = 2, 15156 }; 15157 15158 static void mark_prune_point(struct bpf_verifier_env *env, int idx) 15159 { 15160 env->insn_aux_data[idx].prune_point = true; 15161 } 15162 15163 static bool is_prune_point(struct bpf_verifier_env *env, int insn_idx) 15164 { 15165 return env->insn_aux_data[insn_idx].prune_point; 15166 } 15167 15168 static void mark_force_checkpoint(struct bpf_verifier_env *env, int idx) 15169 { 15170 env->insn_aux_data[idx].force_checkpoint = true; 15171 } 15172 15173 static bool is_force_checkpoint(struct bpf_verifier_env *env, int insn_idx) 15174 { 15175 return env->insn_aux_data[insn_idx].force_checkpoint; 15176 } 15177 15178 static void mark_calls_callback(struct bpf_verifier_env *env, int idx) 15179 { 15180 env->insn_aux_data[idx].calls_callback = true; 15181 } 15182 15183 static bool calls_callback(struct bpf_verifier_env *env, int insn_idx) 15184 { 15185 return env->insn_aux_data[insn_idx].calls_callback; 15186 } 15187 15188 enum { 15189 DONE_EXPLORING = 0, 15190 KEEP_EXPLORING = 1, 15191 }; 15192 15193 /* t, w, e - match pseudo-code above: 15194 * t - index of current instruction 15195 * w - next instruction 15196 * e - edge 15197 */ 15198 static int push_insn(int t, int w, int e, struct bpf_verifier_env *env) 15199 { 15200 int *insn_stack = env->cfg.insn_stack; 15201 int *insn_state = env->cfg.insn_state; 15202 15203 if (e == FALLTHROUGH && insn_state[t] >= (DISCOVERED | FALLTHROUGH)) 15204 return DONE_EXPLORING; 15205 15206 if (e == BRANCH && insn_state[t] >= (DISCOVERED | BRANCH)) 15207 return DONE_EXPLORING; 15208 15209 if (w < 0 || w >= env->prog->len) { 15210 verbose_linfo(env, t, "%d: ", t); 15211 verbose(env, "jump out of range from insn %d to %d\n", t, w); 15212 return -EINVAL; 15213 } 15214 15215 if (e == BRANCH) { 15216 /* mark branch target for state pruning */ 15217 mark_prune_point(env, w); 15218 mark_jmp_point(env, w); 15219 } 15220 15221 if (insn_state[w] == 0) { 15222 /* tree-edge */ 15223 insn_state[t] = DISCOVERED | e; 15224 insn_state[w] = DISCOVERED; 15225 if (env->cfg.cur_stack >= env->prog->len) 15226 return -E2BIG; 15227 insn_stack[env->cfg.cur_stack++] = w; 15228 return KEEP_EXPLORING; 15229 } else if ((insn_state[w] & 0xF0) == DISCOVERED) { 15230 if (env->bpf_capable) 15231 return DONE_EXPLORING; 15232 verbose_linfo(env, t, "%d: ", t); 15233 verbose_linfo(env, w, "%d: ", w); 15234 verbose(env, "back-edge from insn %d to %d\n", t, w); 15235 return -EINVAL; 15236 } else if (insn_state[w] == EXPLORED) { 15237 /* forward- or cross-edge */ 15238 insn_state[t] = DISCOVERED | e; 15239 } else { 15240 verbose(env, "insn state internal bug\n"); 15241 return -EFAULT; 15242 } 15243 return DONE_EXPLORING; 15244 } 15245 15246 static int visit_func_call_insn(int t, struct bpf_insn *insns, 15247 struct bpf_verifier_env *env, 15248 bool visit_callee) 15249 { 15250 int ret, insn_sz; 15251 15252 insn_sz = bpf_is_ldimm64(&insns[t]) ? 2 : 1; 15253 ret = push_insn(t, t + insn_sz, FALLTHROUGH, env); 15254 if (ret) 15255 return ret; 15256 15257 mark_prune_point(env, t + insn_sz); 15258 /* when we exit from subprog, we need to record non-linear history */ 15259 mark_jmp_point(env, t + insn_sz); 15260 15261 if (visit_callee) { 15262 mark_prune_point(env, t); 15263 ret = push_insn(t, t + insns[t].imm + 1, BRANCH, env); 15264 } 15265 return ret; 15266 } 15267 15268 /* Visits the instruction at index t and returns one of the following: 15269 * < 0 - an error occurred 15270 * DONE_EXPLORING - the instruction was fully explored 15271 * KEEP_EXPLORING - there is still work to be done before it is fully explored 15272 */ 15273 static int visit_insn(int t, struct bpf_verifier_env *env) 15274 { 15275 struct bpf_insn *insns = env->prog->insnsi, *insn = &insns[t]; 15276 int ret, off, insn_sz; 15277 15278 if (bpf_pseudo_func(insn)) 15279 return visit_func_call_insn(t, insns, env, true); 15280 15281 /* All non-branch instructions have a single fall-through edge. */ 15282 if (BPF_CLASS(insn->code) != BPF_JMP && 15283 BPF_CLASS(insn->code) != BPF_JMP32) { 15284 insn_sz = bpf_is_ldimm64(insn) ? 2 : 1; 15285 return push_insn(t, t + insn_sz, FALLTHROUGH, env); 15286 } 15287 15288 switch (BPF_OP(insn->code)) { 15289 case BPF_EXIT: 15290 return DONE_EXPLORING; 15291 15292 case BPF_CALL: 15293 if (insn->src_reg == 0 && insn->imm == BPF_FUNC_timer_set_callback) 15294 /* Mark this call insn as a prune point to trigger 15295 * is_state_visited() check before call itself is 15296 * processed by __check_func_call(). Otherwise new 15297 * async state will be pushed for further exploration. 15298 */ 15299 mark_prune_point(env, t); 15300 /* For functions that invoke callbacks it is not known how many times 15301 * callback would be called. Verifier models callback calling functions 15302 * by repeatedly visiting callback bodies and returning to origin call 15303 * instruction. 15304 * In order to stop such iteration verifier needs to identify when a 15305 * state identical some state from a previous iteration is reached. 15306 * Check below forces creation of checkpoint before callback calling 15307 * instruction to allow search for such identical states. 15308 */ 15309 if (is_sync_callback_calling_insn(insn)) { 15310 mark_calls_callback(env, t); 15311 mark_force_checkpoint(env, t); 15312 mark_prune_point(env, t); 15313 mark_jmp_point(env, t); 15314 } 15315 if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) { 15316 struct bpf_kfunc_call_arg_meta meta; 15317 15318 ret = fetch_kfunc_meta(env, insn, &meta, NULL); 15319 if (ret == 0 && is_iter_next_kfunc(&meta)) { 15320 mark_prune_point(env, t); 15321 /* Checking and saving state checkpoints at iter_next() call 15322 * is crucial for fast convergence of open-coded iterator loop 15323 * logic, so we need to force it. If we don't do that, 15324 * is_state_visited() might skip saving a checkpoint, causing 15325 * unnecessarily long sequence of not checkpointed 15326 * instructions and jumps, leading to exhaustion of jump 15327 * history buffer, and potentially other undesired outcomes. 15328 * It is expected that with correct open-coded iterators 15329 * convergence will happen quickly, so we don't run a risk of 15330 * exhausting memory. 15331 */ 15332 mark_force_checkpoint(env, t); 15333 } 15334 } 15335 return visit_func_call_insn(t, insns, env, insn->src_reg == BPF_PSEUDO_CALL); 15336 15337 case BPF_JA: 15338 if (BPF_SRC(insn->code) != BPF_K) 15339 return -EINVAL; 15340 15341 if (BPF_CLASS(insn->code) == BPF_JMP) 15342 off = insn->off; 15343 else 15344 off = insn->imm; 15345 15346 /* unconditional jump with single edge */ 15347 ret = push_insn(t, t + off + 1, FALLTHROUGH, env); 15348 if (ret) 15349 return ret; 15350 15351 mark_prune_point(env, t + off + 1); 15352 mark_jmp_point(env, t + off + 1); 15353 15354 return ret; 15355 15356 default: 15357 /* conditional jump with two edges */ 15358 mark_prune_point(env, t); 15359 15360 ret = push_insn(t, t + 1, FALLTHROUGH, env); 15361 if (ret) 15362 return ret; 15363 15364 return push_insn(t, t + insn->off + 1, BRANCH, env); 15365 } 15366 } 15367 15368 /* non-recursive depth-first-search to detect loops in BPF program 15369 * loop == back-edge in directed graph 15370 */ 15371 static int check_cfg(struct bpf_verifier_env *env) 15372 { 15373 int insn_cnt = env->prog->len; 15374 int *insn_stack, *insn_state; 15375 int ret = 0; 15376 int i; 15377 15378 insn_state = env->cfg.insn_state = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL); 15379 if (!insn_state) 15380 return -ENOMEM; 15381 15382 insn_stack = env->cfg.insn_stack = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL); 15383 if (!insn_stack) { 15384 kvfree(insn_state); 15385 return -ENOMEM; 15386 } 15387 15388 insn_state[0] = DISCOVERED; /* mark 1st insn as discovered */ 15389 insn_stack[0] = 0; /* 0 is the first instruction */ 15390 env->cfg.cur_stack = 1; 15391 15392 while (env->cfg.cur_stack > 0) { 15393 int t = insn_stack[env->cfg.cur_stack - 1]; 15394 15395 ret = visit_insn(t, env); 15396 switch (ret) { 15397 case DONE_EXPLORING: 15398 insn_state[t] = EXPLORED; 15399 env->cfg.cur_stack--; 15400 break; 15401 case KEEP_EXPLORING: 15402 break; 15403 default: 15404 if (ret > 0) { 15405 verbose(env, "visit_insn internal bug\n"); 15406 ret = -EFAULT; 15407 } 15408 goto err_free; 15409 } 15410 } 15411 15412 if (env->cfg.cur_stack < 0) { 15413 verbose(env, "pop stack internal bug\n"); 15414 ret = -EFAULT; 15415 goto err_free; 15416 } 15417 15418 for (i = 0; i < insn_cnt; i++) { 15419 struct bpf_insn *insn = &env->prog->insnsi[i]; 15420 15421 if (insn_state[i] != EXPLORED) { 15422 verbose(env, "unreachable insn %d\n", i); 15423 ret = -EINVAL; 15424 goto err_free; 15425 } 15426 if (bpf_is_ldimm64(insn)) { 15427 if (insn_state[i + 1] != 0) { 15428 verbose(env, "jump into the middle of ldimm64 insn %d\n", i); 15429 ret = -EINVAL; 15430 goto err_free; 15431 } 15432 i++; /* skip second half of ldimm64 */ 15433 } 15434 } 15435 ret = 0; /* cfg looks good */ 15436 15437 err_free: 15438 kvfree(insn_state); 15439 kvfree(insn_stack); 15440 env->cfg.insn_state = env->cfg.insn_stack = NULL; 15441 return ret; 15442 } 15443 15444 static int check_abnormal_return(struct bpf_verifier_env *env) 15445 { 15446 int i; 15447 15448 for (i = 1; i < env->subprog_cnt; i++) { 15449 if (env->subprog_info[i].has_ld_abs) { 15450 verbose(env, "LD_ABS is not allowed in subprogs without BTF\n"); 15451 return -EINVAL; 15452 } 15453 if (env->subprog_info[i].has_tail_call) { 15454 verbose(env, "tail_call is not allowed in subprogs without BTF\n"); 15455 return -EINVAL; 15456 } 15457 } 15458 return 0; 15459 } 15460 15461 /* The minimum supported BTF func info size */ 15462 #define MIN_BPF_FUNCINFO_SIZE 8 15463 #define MAX_FUNCINFO_REC_SIZE 252 15464 15465 static int check_btf_func(struct bpf_verifier_env *env, 15466 const union bpf_attr *attr, 15467 bpfptr_t uattr) 15468 { 15469 const struct btf_type *type, *func_proto, *ret_type; 15470 u32 i, nfuncs, urec_size, min_size; 15471 u32 krec_size = sizeof(struct bpf_func_info); 15472 struct bpf_func_info *krecord; 15473 struct bpf_func_info_aux *info_aux = NULL; 15474 struct bpf_prog *prog; 15475 const struct btf *btf; 15476 bpfptr_t urecord; 15477 u32 prev_offset = 0; 15478 bool scalar_return; 15479 int ret = -ENOMEM; 15480 15481 nfuncs = attr->func_info_cnt; 15482 if (!nfuncs) { 15483 if (check_abnormal_return(env)) 15484 return -EINVAL; 15485 return 0; 15486 } 15487 15488 if (nfuncs != env->subprog_cnt) { 15489 verbose(env, "number of funcs in func_info doesn't match number of subprogs\n"); 15490 return -EINVAL; 15491 } 15492 15493 urec_size = attr->func_info_rec_size; 15494 if (urec_size < MIN_BPF_FUNCINFO_SIZE || 15495 urec_size > MAX_FUNCINFO_REC_SIZE || 15496 urec_size % sizeof(u32)) { 15497 verbose(env, "invalid func info rec size %u\n", urec_size); 15498 return -EINVAL; 15499 } 15500 15501 prog = env->prog; 15502 btf = prog->aux->btf; 15503 15504 urecord = make_bpfptr(attr->func_info, uattr.is_kernel); 15505 min_size = min_t(u32, krec_size, urec_size); 15506 15507 krecord = kvcalloc(nfuncs, krec_size, GFP_KERNEL | __GFP_NOWARN); 15508 if (!krecord) 15509 return -ENOMEM; 15510 info_aux = kcalloc(nfuncs, sizeof(*info_aux), GFP_KERNEL | __GFP_NOWARN); 15511 if (!info_aux) 15512 goto err_free; 15513 15514 for (i = 0; i < nfuncs; i++) { 15515 ret = bpf_check_uarg_tail_zero(urecord, krec_size, urec_size); 15516 if (ret) { 15517 if (ret == -E2BIG) { 15518 verbose(env, "nonzero tailing record in func info"); 15519 /* set the size kernel expects so loader can zero 15520 * out the rest of the record. 15521 */ 15522 if (copy_to_bpfptr_offset(uattr, 15523 offsetof(union bpf_attr, func_info_rec_size), 15524 &min_size, sizeof(min_size))) 15525 ret = -EFAULT; 15526 } 15527 goto err_free; 15528 } 15529 15530 if (copy_from_bpfptr(&krecord[i], urecord, min_size)) { 15531 ret = -EFAULT; 15532 goto err_free; 15533 } 15534 15535 /* check insn_off */ 15536 ret = -EINVAL; 15537 if (i == 0) { 15538 if (krecord[i].insn_off) { 15539 verbose(env, 15540 "nonzero insn_off %u for the first func info record", 15541 krecord[i].insn_off); 15542 goto err_free; 15543 } 15544 } else if (krecord[i].insn_off <= prev_offset) { 15545 verbose(env, 15546 "same or smaller insn offset (%u) than previous func info record (%u)", 15547 krecord[i].insn_off, prev_offset); 15548 goto err_free; 15549 } 15550 15551 if (env->subprog_info[i].start != krecord[i].insn_off) { 15552 verbose(env, "func_info BTF section doesn't match subprog layout in BPF program\n"); 15553 goto err_free; 15554 } 15555 15556 /* check type_id */ 15557 type = btf_type_by_id(btf, krecord[i].type_id); 15558 if (!type || !btf_type_is_func(type)) { 15559 verbose(env, "invalid type id %d in func info", 15560 krecord[i].type_id); 15561 goto err_free; 15562 } 15563 info_aux[i].linkage = BTF_INFO_VLEN(type->info); 15564 15565 func_proto = btf_type_by_id(btf, type->type); 15566 if (unlikely(!func_proto || !btf_type_is_func_proto(func_proto))) 15567 /* btf_func_check() already verified it during BTF load */ 15568 goto err_free; 15569 ret_type = btf_type_skip_modifiers(btf, func_proto->type, NULL); 15570 scalar_return = 15571 btf_type_is_small_int(ret_type) || btf_is_any_enum(ret_type); 15572 if (i && !scalar_return && env->subprog_info[i].has_ld_abs) { 15573 verbose(env, "LD_ABS is only allowed in functions that return 'int'.\n"); 15574 goto err_free; 15575 } 15576 if (i && !scalar_return && env->subprog_info[i].has_tail_call) { 15577 verbose(env, "tail_call is only allowed in functions that return 'int'.\n"); 15578 goto err_free; 15579 } 15580 15581 prev_offset = krecord[i].insn_off; 15582 bpfptr_add(&urecord, urec_size); 15583 } 15584 15585 prog->aux->func_info = krecord; 15586 prog->aux->func_info_cnt = nfuncs; 15587 prog->aux->func_info_aux = info_aux; 15588 return 0; 15589 15590 err_free: 15591 kvfree(krecord); 15592 kfree(info_aux); 15593 return ret; 15594 } 15595 15596 static void adjust_btf_func(struct bpf_verifier_env *env) 15597 { 15598 struct bpf_prog_aux *aux = env->prog->aux; 15599 int i; 15600 15601 if (!aux->func_info) 15602 return; 15603 15604 for (i = 0; i < env->subprog_cnt; i++) 15605 aux->func_info[i].insn_off = env->subprog_info[i].start; 15606 } 15607 15608 #define MIN_BPF_LINEINFO_SIZE offsetofend(struct bpf_line_info, line_col) 15609 #define MAX_LINEINFO_REC_SIZE MAX_FUNCINFO_REC_SIZE 15610 15611 static int check_btf_line(struct bpf_verifier_env *env, 15612 const union bpf_attr *attr, 15613 bpfptr_t uattr) 15614 { 15615 u32 i, s, nr_linfo, ncopy, expected_size, rec_size, prev_offset = 0; 15616 struct bpf_subprog_info *sub; 15617 struct bpf_line_info *linfo; 15618 struct bpf_prog *prog; 15619 const struct btf *btf; 15620 bpfptr_t ulinfo; 15621 int err; 15622 15623 nr_linfo = attr->line_info_cnt; 15624 if (!nr_linfo) 15625 return 0; 15626 if (nr_linfo > INT_MAX / sizeof(struct bpf_line_info)) 15627 return -EINVAL; 15628 15629 rec_size = attr->line_info_rec_size; 15630 if (rec_size < MIN_BPF_LINEINFO_SIZE || 15631 rec_size > MAX_LINEINFO_REC_SIZE || 15632 rec_size & (sizeof(u32) - 1)) 15633 return -EINVAL; 15634 15635 /* Need to zero it in case the userspace may 15636 * pass in a smaller bpf_line_info object. 15637 */ 15638 linfo = kvcalloc(nr_linfo, sizeof(struct bpf_line_info), 15639 GFP_KERNEL | __GFP_NOWARN); 15640 if (!linfo) 15641 return -ENOMEM; 15642 15643 prog = env->prog; 15644 btf = prog->aux->btf; 15645 15646 s = 0; 15647 sub = env->subprog_info; 15648 ulinfo = make_bpfptr(attr->line_info, uattr.is_kernel); 15649 expected_size = sizeof(struct bpf_line_info); 15650 ncopy = min_t(u32, expected_size, rec_size); 15651 for (i = 0; i < nr_linfo; i++) { 15652 err = bpf_check_uarg_tail_zero(ulinfo, expected_size, rec_size); 15653 if (err) { 15654 if (err == -E2BIG) { 15655 verbose(env, "nonzero tailing record in line_info"); 15656 if (copy_to_bpfptr_offset(uattr, 15657 offsetof(union bpf_attr, line_info_rec_size), 15658 &expected_size, sizeof(expected_size))) 15659 err = -EFAULT; 15660 } 15661 goto err_free; 15662 } 15663 15664 if (copy_from_bpfptr(&linfo[i], ulinfo, ncopy)) { 15665 err = -EFAULT; 15666 goto err_free; 15667 } 15668 15669 /* 15670 * Check insn_off to ensure 15671 * 1) strictly increasing AND 15672 * 2) bounded by prog->len 15673 * 15674 * The linfo[0].insn_off == 0 check logically falls into 15675 * the later "missing bpf_line_info for func..." case 15676 * because the first linfo[0].insn_off must be the 15677 * first sub also and the first sub must have 15678 * subprog_info[0].start == 0. 15679 */ 15680 if ((i && linfo[i].insn_off <= prev_offset) || 15681 linfo[i].insn_off >= prog->len) { 15682 verbose(env, "Invalid line_info[%u].insn_off:%u (prev_offset:%u prog->len:%u)\n", 15683 i, linfo[i].insn_off, prev_offset, 15684 prog->len); 15685 err = -EINVAL; 15686 goto err_free; 15687 } 15688 15689 if (!prog->insnsi[linfo[i].insn_off].code) { 15690 verbose(env, 15691 "Invalid insn code at line_info[%u].insn_off\n", 15692 i); 15693 err = -EINVAL; 15694 goto err_free; 15695 } 15696 15697 if (!btf_name_by_offset(btf, linfo[i].line_off) || 15698 !btf_name_by_offset(btf, linfo[i].file_name_off)) { 15699 verbose(env, "Invalid line_info[%u].line_off or .file_name_off\n", i); 15700 err = -EINVAL; 15701 goto err_free; 15702 } 15703 15704 if (s != env->subprog_cnt) { 15705 if (linfo[i].insn_off == sub[s].start) { 15706 sub[s].linfo_idx = i; 15707 s++; 15708 } else if (sub[s].start < linfo[i].insn_off) { 15709 verbose(env, "missing bpf_line_info for func#%u\n", s); 15710 err = -EINVAL; 15711 goto err_free; 15712 } 15713 } 15714 15715 prev_offset = linfo[i].insn_off; 15716 bpfptr_add(&ulinfo, rec_size); 15717 } 15718 15719 if (s != env->subprog_cnt) { 15720 verbose(env, "missing bpf_line_info for %u funcs starting from func#%u\n", 15721 env->subprog_cnt - s, s); 15722 err = -EINVAL; 15723 goto err_free; 15724 } 15725 15726 prog->aux->linfo = linfo; 15727 prog->aux->nr_linfo = nr_linfo; 15728 15729 return 0; 15730 15731 err_free: 15732 kvfree(linfo); 15733 return err; 15734 } 15735 15736 #define MIN_CORE_RELO_SIZE sizeof(struct bpf_core_relo) 15737 #define MAX_CORE_RELO_SIZE MAX_FUNCINFO_REC_SIZE 15738 15739 static int check_core_relo(struct bpf_verifier_env *env, 15740 const union bpf_attr *attr, 15741 bpfptr_t uattr) 15742 { 15743 u32 i, nr_core_relo, ncopy, expected_size, rec_size; 15744 struct bpf_core_relo core_relo = {}; 15745 struct bpf_prog *prog = env->prog; 15746 const struct btf *btf = prog->aux->btf; 15747 struct bpf_core_ctx ctx = { 15748 .log = &env->log, 15749 .btf = btf, 15750 }; 15751 bpfptr_t u_core_relo; 15752 int err; 15753 15754 nr_core_relo = attr->core_relo_cnt; 15755 if (!nr_core_relo) 15756 return 0; 15757 if (nr_core_relo > INT_MAX / sizeof(struct bpf_core_relo)) 15758 return -EINVAL; 15759 15760 rec_size = attr->core_relo_rec_size; 15761 if (rec_size < MIN_CORE_RELO_SIZE || 15762 rec_size > MAX_CORE_RELO_SIZE || 15763 rec_size % sizeof(u32)) 15764 return -EINVAL; 15765 15766 u_core_relo = make_bpfptr(attr->core_relos, uattr.is_kernel); 15767 expected_size = sizeof(struct bpf_core_relo); 15768 ncopy = min_t(u32, expected_size, rec_size); 15769 15770 /* Unlike func_info and line_info, copy and apply each CO-RE 15771 * relocation record one at a time. 15772 */ 15773 for (i = 0; i < nr_core_relo; i++) { 15774 /* future proofing when sizeof(bpf_core_relo) changes */ 15775 err = bpf_check_uarg_tail_zero(u_core_relo, expected_size, rec_size); 15776 if (err) { 15777 if (err == -E2BIG) { 15778 verbose(env, "nonzero tailing record in core_relo"); 15779 if (copy_to_bpfptr_offset(uattr, 15780 offsetof(union bpf_attr, core_relo_rec_size), 15781 &expected_size, sizeof(expected_size))) 15782 err = -EFAULT; 15783 } 15784 break; 15785 } 15786 15787 if (copy_from_bpfptr(&core_relo, u_core_relo, ncopy)) { 15788 err = -EFAULT; 15789 break; 15790 } 15791 15792 if (core_relo.insn_off % 8 || core_relo.insn_off / 8 >= prog->len) { 15793 verbose(env, "Invalid core_relo[%u].insn_off:%u prog->len:%u\n", 15794 i, core_relo.insn_off, prog->len); 15795 err = -EINVAL; 15796 break; 15797 } 15798 15799 err = bpf_core_apply(&ctx, &core_relo, i, 15800 &prog->insnsi[core_relo.insn_off / 8]); 15801 if (err) 15802 break; 15803 bpfptr_add(&u_core_relo, rec_size); 15804 } 15805 return err; 15806 } 15807 15808 static int check_btf_info(struct bpf_verifier_env *env, 15809 const union bpf_attr *attr, 15810 bpfptr_t uattr) 15811 { 15812 struct btf *btf; 15813 int err; 15814 15815 if (!attr->func_info_cnt && !attr->line_info_cnt) { 15816 if (check_abnormal_return(env)) 15817 return -EINVAL; 15818 return 0; 15819 } 15820 15821 btf = btf_get_by_fd(attr->prog_btf_fd); 15822 if (IS_ERR(btf)) 15823 return PTR_ERR(btf); 15824 if (btf_is_kernel(btf)) { 15825 btf_put(btf); 15826 return -EACCES; 15827 } 15828 env->prog->aux->btf = btf; 15829 15830 err = check_btf_func(env, attr, uattr); 15831 if (err) 15832 return err; 15833 15834 err = check_btf_line(env, attr, uattr); 15835 if (err) 15836 return err; 15837 15838 err = check_core_relo(env, attr, uattr); 15839 if (err) 15840 return err; 15841 15842 return 0; 15843 } 15844 15845 /* check %cur's range satisfies %old's */ 15846 static bool range_within(struct bpf_reg_state *old, 15847 struct bpf_reg_state *cur) 15848 { 15849 return old->umin_value <= cur->umin_value && 15850 old->umax_value >= cur->umax_value && 15851 old->smin_value <= cur->smin_value && 15852 old->smax_value >= cur->smax_value && 15853 old->u32_min_value <= cur->u32_min_value && 15854 old->u32_max_value >= cur->u32_max_value && 15855 old->s32_min_value <= cur->s32_min_value && 15856 old->s32_max_value >= cur->s32_max_value; 15857 } 15858 15859 /* If in the old state two registers had the same id, then they need to have 15860 * the same id in the new state as well. But that id could be different from 15861 * the old state, so we need to track the mapping from old to new ids. 15862 * Once we have seen that, say, a reg with old id 5 had new id 9, any subsequent 15863 * regs with old id 5 must also have new id 9 for the new state to be safe. But 15864 * regs with a different old id could still have new id 9, we don't care about 15865 * that. 15866 * So we look through our idmap to see if this old id has been seen before. If 15867 * so, we require the new id to match; otherwise, we add the id pair to the map. 15868 */ 15869 static bool check_ids(u32 old_id, u32 cur_id, struct bpf_idmap *idmap) 15870 { 15871 struct bpf_id_pair *map = idmap->map; 15872 unsigned int i; 15873 15874 /* either both IDs should be set or both should be zero */ 15875 if (!!old_id != !!cur_id) 15876 return false; 15877 15878 if (old_id == 0) /* cur_id == 0 as well */ 15879 return true; 15880 15881 for (i = 0; i < BPF_ID_MAP_SIZE; i++) { 15882 if (!map[i].old) { 15883 /* Reached an empty slot; haven't seen this id before */ 15884 map[i].old = old_id; 15885 map[i].cur = cur_id; 15886 return true; 15887 } 15888 if (map[i].old == old_id) 15889 return map[i].cur == cur_id; 15890 if (map[i].cur == cur_id) 15891 return false; 15892 } 15893 /* We ran out of idmap slots, which should be impossible */ 15894 WARN_ON_ONCE(1); 15895 return false; 15896 } 15897 15898 /* Similar to check_ids(), but allocate a unique temporary ID 15899 * for 'old_id' or 'cur_id' of zero. 15900 * This makes pairs like '0 vs unique ID', 'unique ID vs 0' valid. 15901 */ 15902 static bool check_scalar_ids(u32 old_id, u32 cur_id, struct bpf_idmap *idmap) 15903 { 15904 old_id = old_id ? old_id : ++idmap->tmp_id_gen; 15905 cur_id = cur_id ? cur_id : ++idmap->tmp_id_gen; 15906 15907 return check_ids(old_id, cur_id, idmap); 15908 } 15909 15910 static void clean_func_state(struct bpf_verifier_env *env, 15911 struct bpf_func_state *st) 15912 { 15913 enum bpf_reg_liveness live; 15914 int i, j; 15915 15916 for (i = 0; i < BPF_REG_FP; i++) { 15917 live = st->regs[i].live; 15918 /* liveness must not touch this register anymore */ 15919 st->regs[i].live |= REG_LIVE_DONE; 15920 if (!(live & REG_LIVE_READ)) 15921 /* since the register is unused, clear its state 15922 * to make further comparison simpler 15923 */ 15924 __mark_reg_not_init(env, &st->regs[i]); 15925 } 15926 15927 for (i = 0; i < st->allocated_stack / BPF_REG_SIZE; i++) { 15928 live = st->stack[i].spilled_ptr.live; 15929 /* liveness must not touch this stack slot anymore */ 15930 st->stack[i].spilled_ptr.live |= REG_LIVE_DONE; 15931 if (!(live & REG_LIVE_READ)) { 15932 __mark_reg_not_init(env, &st->stack[i].spilled_ptr); 15933 for (j = 0; j < BPF_REG_SIZE; j++) 15934 st->stack[i].slot_type[j] = STACK_INVALID; 15935 } 15936 } 15937 } 15938 15939 static void clean_verifier_state(struct bpf_verifier_env *env, 15940 struct bpf_verifier_state *st) 15941 { 15942 int i; 15943 15944 if (st->frame[0]->regs[0].live & REG_LIVE_DONE) 15945 /* all regs in this state in all frames were already marked */ 15946 return; 15947 15948 for (i = 0; i <= st->curframe; i++) 15949 clean_func_state(env, st->frame[i]); 15950 } 15951 15952 /* the parentage chains form a tree. 15953 * the verifier states are added to state lists at given insn and 15954 * pushed into state stack for future exploration. 15955 * when the verifier reaches bpf_exit insn some of the verifer states 15956 * stored in the state lists have their final liveness state already, 15957 * but a lot of states will get revised from liveness point of view when 15958 * the verifier explores other branches. 15959 * Example: 15960 * 1: r0 = 1 15961 * 2: if r1 == 100 goto pc+1 15962 * 3: r0 = 2 15963 * 4: exit 15964 * when the verifier reaches exit insn the register r0 in the state list of 15965 * insn 2 will be seen as !REG_LIVE_READ. Then the verifier pops the other_branch 15966 * of insn 2 and goes exploring further. At the insn 4 it will walk the 15967 * parentage chain from insn 4 into insn 2 and will mark r0 as REG_LIVE_READ. 15968 * 15969 * Since the verifier pushes the branch states as it sees them while exploring 15970 * the program the condition of walking the branch instruction for the second 15971 * time means that all states below this branch were already explored and 15972 * their final liveness marks are already propagated. 15973 * Hence when the verifier completes the search of state list in is_state_visited() 15974 * we can call this clean_live_states() function to mark all liveness states 15975 * as REG_LIVE_DONE to indicate that 'parent' pointers of 'struct bpf_reg_state' 15976 * will not be used. 15977 * This function also clears the registers and stack for states that !READ 15978 * to simplify state merging. 15979 * 15980 * Important note here that walking the same branch instruction in the callee 15981 * doesn't meant that the states are DONE. The verifier has to compare 15982 * the callsites 15983 */ 15984 static void clean_live_states(struct bpf_verifier_env *env, int insn, 15985 struct bpf_verifier_state *cur) 15986 { 15987 struct bpf_verifier_state_list *sl; 15988 15989 sl = *explored_state(env, insn); 15990 while (sl) { 15991 if (sl->state.branches) 15992 goto next; 15993 if (sl->state.insn_idx != insn || 15994 !same_callsites(&sl->state, cur)) 15995 goto next; 15996 clean_verifier_state(env, &sl->state); 15997 next: 15998 sl = sl->next; 15999 } 16000 } 16001 16002 static bool regs_exact(const struct bpf_reg_state *rold, 16003 const struct bpf_reg_state *rcur, 16004 struct bpf_idmap *idmap) 16005 { 16006 return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 && 16007 check_ids(rold->id, rcur->id, idmap) && 16008 check_ids(rold->ref_obj_id, rcur->ref_obj_id, idmap); 16009 } 16010 16011 /* Returns true if (rold safe implies rcur safe) */ 16012 static bool regsafe(struct bpf_verifier_env *env, struct bpf_reg_state *rold, 16013 struct bpf_reg_state *rcur, struct bpf_idmap *idmap, bool exact) 16014 { 16015 if (exact) 16016 return regs_exact(rold, rcur, idmap); 16017 16018 if (!(rold->live & REG_LIVE_READ)) 16019 /* explored state didn't use this */ 16020 return true; 16021 if (rold->type == NOT_INIT) 16022 /* explored state can't have used this */ 16023 return true; 16024 if (rcur->type == NOT_INIT) 16025 return false; 16026 16027 /* Enforce that register types have to match exactly, including their 16028 * modifiers (like PTR_MAYBE_NULL, MEM_RDONLY, etc), as a general 16029 * rule. 16030 * 16031 * One can make a point that using a pointer register as unbounded 16032 * SCALAR would be technically acceptable, but this could lead to 16033 * pointer leaks because scalars are allowed to leak while pointers 16034 * are not. We could make this safe in special cases if root is 16035 * calling us, but it's probably not worth the hassle. 16036 * 16037 * Also, register types that are *not* MAYBE_NULL could technically be 16038 * safe to use as their MAYBE_NULL variants (e.g., PTR_TO_MAP_VALUE 16039 * is safe to be used as PTR_TO_MAP_VALUE_OR_NULL, provided both point 16040 * to the same map). 16041 * However, if the old MAYBE_NULL register then got NULL checked, 16042 * doing so could have affected others with the same id, and we can't 16043 * check for that because we lost the id when we converted to 16044 * a non-MAYBE_NULL variant. 16045 * So, as a general rule we don't allow mixing MAYBE_NULL and 16046 * non-MAYBE_NULL registers as well. 16047 */ 16048 if (rold->type != rcur->type) 16049 return false; 16050 16051 switch (base_type(rold->type)) { 16052 case SCALAR_VALUE: 16053 if (env->explore_alu_limits) { 16054 /* explore_alu_limits disables tnum_in() and range_within() 16055 * logic and requires everything to be strict 16056 */ 16057 return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 && 16058 check_scalar_ids(rold->id, rcur->id, idmap); 16059 } 16060 if (!rold->precise) 16061 return true; 16062 /* Why check_ids() for scalar registers? 16063 * 16064 * Consider the following BPF code: 16065 * 1: r6 = ... unbound scalar, ID=a ... 16066 * 2: r7 = ... unbound scalar, ID=b ... 16067 * 3: if (r6 > r7) goto +1 16068 * 4: r6 = r7 16069 * 5: if (r6 > X) goto ... 16070 * 6: ... memory operation using r7 ... 16071 * 16072 * First verification path is [1-6]: 16073 * - at (4) same bpf_reg_state::id (b) would be assigned to r6 and r7; 16074 * - at (5) r6 would be marked <= X, find_equal_scalars() would also mark 16075 * r7 <= X, because r6 and r7 share same id. 16076 * Next verification path is [1-4, 6]. 16077 * 16078 * Instruction (6) would be reached in two states: 16079 * I. r6{.id=b}, r7{.id=b} via path 1-6; 16080 * II. r6{.id=a}, r7{.id=b} via path 1-4, 6. 16081 * 16082 * Use check_ids() to distinguish these states. 16083 * --- 16084 * Also verify that new value satisfies old value range knowledge. 16085 */ 16086 return range_within(rold, rcur) && 16087 tnum_in(rold->var_off, rcur->var_off) && 16088 check_scalar_ids(rold->id, rcur->id, idmap); 16089 case PTR_TO_MAP_KEY: 16090 case PTR_TO_MAP_VALUE: 16091 case PTR_TO_MEM: 16092 case PTR_TO_BUF: 16093 case PTR_TO_TP_BUFFER: 16094 /* If the new min/max/var_off satisfy the old ones and 16095 * everything else matches, we are OK. 16096 */ 16097 return memcmp(rold, rcur, offsetof(struct bpf_reg_state, var_off)) == 0 && 16098 range_within(rold, rcur) && 16099 tnum_in(rold->var_off, rcur->var_off) && 16100 check_ids(rold->id, rcur->id, idmap) && 16101 check_ids(rold->ref_obj_id, rcur->ref_obj_id, idmap); 16102 case PTR_TO_PACKET_META: 16103 case PTR_TO_PACKET: 16104 /* We must have at least as much range as the old ptr 16105 * did, so that any accesses which were safe before are 16106 * still safe. This is true even if old range < old off, 16107 * since someone could have accessed through (ptr - k), or 16108 * even done ptr -= k in a register, to get a safe access. 16109 */ 16110 if (rold->range > rcur->range) 16111 return false; 16112 /* If the offsets don't match, we can't trust our alignment; 16113 * nor can we be sure that we won't fall out of range. 16114 */ 16115 if (rold->off != rcur->off) 16116 return false; 16117 /* id relations must be preserved */ 16118 if (!check_ids(rold->id, rcur->id, idmap)) 16119 return false; 16120 /* new val must satisfy old val knowledge */ 16121 return range_within(rold, rcur) && 16122 tnum_in(rold->var_off, rcur->var_off); 16123 case PTR_TO_STACK: 16124 /* two stack pointers are equal only if they're pointing to 16125 * the same stack frame, since fp-8 in foo != fp-8 in bar 16126 */ 16127 return regs_exact(rold, rcur, idmap) && rold->frameno == rcur->frameno; 16128 default: 16129 return regs_exact(rold, rcur, idmap); 16130 } 16131 } 16132 16133 static bool stacksafe(struct bpf_verifier_env *env, struct bpf_func_state *old, 16134 struct bpf_func_state *cur, struct bpf_idmap *idmap, bool exact) 16135 { 16136 int i, spi; 16137 16138 /* walk slots of the explored stack and ignore any additional 16139 * slots in the current stack, since explored(safe) state 16140 * didn't use them 16141 */ 16142 for (i = 0; i < old->allocated_stack; i++) { 16143 struct bpf_reg_state *old_reg, *cur_reg; 16144 16145 spi = i / BPF_REG_SIZE; 16146 16147 if (exact && 16148 (i >= cur->allocated_stack || 16149 old->stack[spi].slot_type[i % BPF_REG_SIZE] != 16150 cur->stack[spi].slot_type[i % BPF_REG_SIZE])) 16151 return false; 16152 16153 if (!(old->stack[spi].spilled_ptr.live & REG_LIVE_READ) && !exact) { 16154 i += BPF_REG_SIZE - 1; 16155 /* explored state didn't use this */ 16156 continue; 16157 } 16158 16159 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_INVALID) 16160 continue; 16161 16162 if (env->allow_uninit_stack && 16163 old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC) 16164 continue; 16165 16166 /* explored stack has more populated slots than current stack 16167 * and these slots were used 16168 */ 16169 if (i >= cur->allocated_stack) 16170 return false; 16171 16172 /* if old state was safe with misc data in the stack 16173 * it will be safe with zero-initialized stack. 16174 * The opposite is not true 16175 */ 16176 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC && 16177 cur->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_ZERO) 16178 continue; 16179 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] != 16180 cur->stack[spi].slot_type[i % BPF_REG_SIZE]) 16181 /* Ex: old explored (safe) state has STACK_SPILL in 16182 * this stack slot, but current has STACK_MISC -> 16183 * this verifier states are not equivalent, 16184 * return false to continue verification of this path 16185 */ 16186 return false; 16187 if (i % BPF_REG_SIZE != BPF_REG_SIZE - 1) 16188 continue; 16189 /* Both old and cur are having same slot_type */ 16190 switch (old->stack[spi].slot_type[BPF_REG_SIZE - 1]) { 16191 case STACK_SPILL: 16192 /* when explored and current stack slot are both storing 16193 * spilled registers, check that stored pointers types 16194 * are the same as well. 16195 * Ex: explored safe path could have stored 16196 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -8} 16197 * but current path has stored: 16198 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -16} 16199 * such verifier states are not equivalent. 16200 * return false to continue verification of this path 16201 */ 16202 if (!regsafe(env, &old->stack[spi].spilled_ptr, 16203 &cur->stack[spi].spilled_ptr, idmap, exact)) 16204 return false; 16205 break; 16206 case STACK_DYNPTR: 16207 old_reg = &old->stack[spi].spilled_ptr; 16208 cur_reg = &cur->stack[spi].spilled_ptr; 16209 if (old_reg->dynptr.type != cur_reg->dynptr.type || 16210 old_reg->dynptr.first_slot != cur_reg->dynptr.first_slot || 16211 !check_ids(old_reg->ref_obj_id, cur_reg->ref_obj_id, idmap)) 16212 return false; 16213 break; 16214 case STACK_ITER: 16215 old_reg = &old->stack[spi].spilled_ptr; 16216 cur_reg = &cur->stack[spi].spilled_ptr; 16217 /* iter.depth is not compared between states as it 16218 * doesn't matter for correctness and would otherwise 16219 * prevent convergence; we maintain it only to prevent 16220 * infinite loop check triggering, see 16221 * iter_active_depths_differ() 16222 */ 16223 if (old_reg->iter.btf != cur_reg->iter.btf || 16224 old_reg->iter.btf_id != cur_reg->iter.btf_id || 16225 old_reg->iter.state != cur_reg->iter.state || 16226 /* ignore {old_reg,cur_reg}->iter.depth, see above */ 16227 !check_ids(old_reg->ref_obj_id, cur_reg->ref_obj_id, idmap)) 16228 return false; 16229 break; 16230 case STACK_MISC: 16231 case STACK_ZERO: 16232 case STACK_INVALID: 16233 continue; 16234 /* Ensure that new unhandled slot types return false by default */ 16235 default: 16236 return false; 16237 } 16238 } 16239 return true; 16240 } 16241 16242 static bool refsafe(struct bpf_func_state *old, struct bpf_func_state *cur, 16243 struct bpf_idmap *idmap) 16244 { 16245 int i; 16246 16247 if (old->acquired_refs != cur->acquired_refs) 16248 return false; 16249 16250 for (i = 0; i < old->acquired_refs; i++) { 16251 if (!check_ids(old->refs[i].id, cur->refs[i].id, idmap)) 16252 return false; 16253 } 16254 16255 return true; 16256 } 16257 16258 /* compare two verifier states 16259 * 16260 * all states stored in state_list are known to be valid, since 16261 * verifier reached 'bpf_exit' instruction through them 16262 * 16263 * this function is called when verifier exploring different branches of 16264 * execution popped from the state stack. If it sees an old state that has 16265 * more strict register state and more strict stack state then this execution 16266 * branch doesn't need to be explored further, since verifier already 16267 * concluded that more strict state leads to valid finish. 16268 * 16269 * Therefore two states are equivalent if register state is more conservative 16270 * and explored stack state is more conservative than the current one. 16271 * Example: 16272 * explored current 16273 * (slot1=INV slot2=MISC) == (slot1=MISC slot2=MISC) 16274 * (slot1=MISC slot2=MISC) != (slot1=INV slot2=MISC) 16275 * 16276 * In other words if current stack state (one being explored) has more 16277 * valid slots than old one that already passed validation, it means 16278 * the verifier can stop exploring and conclude that current state is valid too 16279 * 16280 * Similarly with registers. If explored state has register type as invalid 16281 * whereas register type in current state is meaningful, it means that 16282 * the current state will reach 'bpf_exit' instruction safely 16283 */ 16284 static bool func_states_equal(struct bpf_verifier_env *env, struct bpf_func_state *old, 16285 struct bpf_func_state *cur, bool exact) 16286 { 16287 int i; 16288 16289 if (old->callback_depth > cur->callback_depth) 16290 return false; 16291 16292 for (i = 0; i < MAX_BPF_REG; i++) 16293 if (!regsafe(env, &old->regs[i], &cur->regs[i], 16294 &env->idmap_scratch, exact)) 16295 return false; 16296 16297 if (!stacksafe(env, old, cur, &env->idmap_scratch, exact)) 16298 return false; 16299 16300 if (!refsafe(old, cur, &env->idmap_scratch)) 16301 return false; 16302 16303 return true; 16304 } 16305 16306 static void reset_idmap_scratch(struct bpf_verifier_env *env) 16307 { 16308 env->idmap_scratch.tmp_id_gen = env->id_gen; 16309 memset(&env->idmap_scratch.map, 0, sizeof(env->idmap_scratch.map)); 16310 } 16311 16312 static bool states_equal(struct bpf_verifier_env *env, 16313 struct bpf_verifier_state *old, 16314 struct bpf_verifier_state *cur, 16315 bool exact) 16316 { 16317 int i; 16318 16319 if (old->curframe != cur->curframe) 16320 return false; 16321 16322 reset_idmap_scratch(env); 16323 16324 /* Verification state from speculative execution simulation 16325 * must never prune a non-speculative execution one. 16326 */ 16327 if (old->speculative && !cur->speculative) 16328 return false; 16329 16330 if (old->active_lock.ptr != cur->active_lock.ptr) 16331 return false; 16332 16333 /* Old and cur active_lock's have to be either both present 16334 * or both absent. 16335 */ 16336 if (!!old->active_lock.id != !!cur->active_lock.id) 16337 return false; 16338 16339 if (old->active_lock.id && 16340 !check_ids(old->active_lock.id, cur->active_lock.id, &env->idmap_scratch)) 16341 return false; 16342 16343 if (old->active_rcu_lock != cur->active_rcu_lock) 16344 return false; 16345 16346 /* for states to be equal callsites have to be the same 16347 * and all frame states need to be equivalent 16348 */ 16349 for (i = 0; i <= old->curframe; i++) { 16350 if (old->frame[i]->callsite != cur->frame[i]->callsite) 16351 return false; 16352 if (!func_states_equal(env, old->frame[i], cur->frame[i], exact)) 16353 return false; 16354 } 16355 return true; 16356 } 16357 16358 /* Return 0 if no propagation happened. Return negative error code if error 16359 * happened. Otherwise, return the propagated bit. 16360 */ 16361 static int propagate_liveness_reg(struct bpf_verifier_env *env, 16362 struct bpf_reg_state *reg, 16363 struct bpf_reg_state *parent_reg) 16364 { 16365 u8 parent_flag = parent_reg->live & REG_LIVE_READ; 16366 u8 flag = reg->live & REG_LIVE_READ; 16367 int err; 16368 16369 /* When comes here, read flags of PARENT_REG or REG could be any of 16370 * REG_LIVE_READ64, REG_LIVE_READ32, REG_LIVE_NONE. There is no need 16371 * of propagation if PARENT_REG has strongest REG_LIVE_READ64. 16372 */ 16373 if (parent_flag == REG_LIVE_READ64 || 16374 /* Or if there is no read flag from REG. */ 16375 !flag || 16376 /* Or if the read flag from REG is the same as PARENT_REG. */ 16377 parent_flag == flag) 16378 return 0; 16379 16380 err = mark_reg_read(env, reg, parent_reg, flag); 16381 if (err) 16382 return err; 16383 16384 return flag; 16385 } 16386 16387 /* A write screens off any subsequent reads; but write marks come from the 16388 * straight-line code between a state and its parent. When we arrive at an 16389 * equivalent state (jump target or such) we didn't arrive by the straight-line 16390 * code, so read marks in the state must propagate to the parent regardless 16391 * of the state's write marks. That's what 'parent == state->parent' comparison 16392 * in mark_reg_read() is for. 16393 */ 16394 static int propagate_liveness(struct bpf_verifier_env *env, 16395 const struct bpf_verifier_state *vstate, 16396 struct bpf_verifier_state *vparent) 16397 { 16398 struct bpf_reg_state *state_reg, *parent_reg; 16399 struct bpf_func_state *state, *parent; 16400 int i, frame, err = 0; 16401 16402 if (vparent->curframe != vstate->curframe) { 16403 WARN(1, "propagate_live: parent frame %d current frame %d\n", 16404 vparent->curframe, vstate->curframe); 16405 return -EFAULT; 16406 } 16407 /* Propagate read liveness of registers... */ 16408 BUILD_BUG_ON(BPF_REG_FP + 1 != MAX_BPF_REG); 16409 for (frame = 0; frame <= vstate->curframe; frame++) { 16410 parent = vparent->frame[frame]; 16411 state = vstate->frame[frame]; 16412 parent_reg = parent->regs; 16413 state_reg = state->regs; 16414 /* We don't need to worry about FP liveness, it's read-only */ 16415 for (i = frame < vstate->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++) { 16416 err = propagate_liveness_reg(env, &state_reg[i], 16417 &parent_reg[i]); 16418 if (err < 0) 16419 return err; 16420 if (err == REG_LIVE_READ64) 16421 mark_insn_zext(env, &parent_reg[i]); 16422 } 16423 16424 /* Propagate stack slots. */ 16425 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE && 16426 i < parent->allocated_stack / BPF_REG_SIZE; i++) { 16427 parent_reg = &parent->stack[i].spilled_ptr; 16428 state_reg = &state->stack[i].spilled_ptr; 16429 err = propagate_liveness_reg(env, state_reg, 16430 parent_reg); 16431 if (err < 0) 16432 return err; 16433 } 16434 } 16435 return 0; 16436 } 16437 16438 /* find precise scalars in the previous equivalent state and 16439 * propagate them into the current state 16440 */ 16441 static int propagate_precision(struct bpf_verifier_env *env, 16442 const struct bpf_verifier_state *old) 16443 { 16444 struct bpf_reg_state *state_reg; 16445 struct bpf_func_state *state; 16446 int i, err = 0, fr; 16447 bool first; 16448 16449 for (fr = old->curframe; fr >= 0; fr--) { 16450 state = old->frame[fr]; 16451 state_reg = state->regs; 16452 first = true; 16453 for (i = 0; i < BPF_REG_FP; i++, state_reg++) { 16454 if (state_reg->type != SCALAR_VALUE || 16455 !state_reg->precise || 16456 !(state_reg->live & REG_LIVE_READ)) 16457 continue; 16458 if (env->log.level & BPF_LOG_LEVEL2) { 16459 if (first) 16460 verbose(env, "frame %d: propagating r%d", fr, i); 16461 else 16462 verbose(env, ",r%d", i); 16463 } 16464 bt_set_frame_reg(&env->bt, fr, i); 16465 first = false; 16466 } 16467 16468 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) { 16469 if (!is_spilled_reg(&state->stack[i])) 16470 continue; 16471 state_reg = &state->stack[i].spilled_ptr; 16472 if (state_reg->type != SCALAR_VALUE || 16473 !state_reg->precise || 16474 !(state_reg->live & REG_LIVE_READ)) 16475 continue; 16476 if (env->log.level & BPF_LOG_LEVEL2) { 16477 if (first) 16478 verbose(env, "frame %d: propagating fp%d", 16479 fr, (-i - 1) * BPF_REG_SIZE); 16480 else 16481 verbose(env, ",fp%d", (-i - 1) * BPF_REG_SIZE); 16482 } 16483 bt_set_frame_slot(&env->bt, fr, i); 16484 first = false; 16485 } 16486 if (!first) 16487 verbose(env, "\n"); 16488 } 16489 16490 err = mark_chain_precision_batch(env); 16491 if (err < 0) 16492 return err; 16493 16494 return 0; 16495 } 16496 16497 static bool states_maybe_looping(struct bpf_verifier_state *old, 16498 struct bpf_verifier_state *cur) 16499 { 16500 struct bpf_func_state *fold, *fcur; 16501 int i, fr = cur->curframe; 16502 16503 if (old->curframe != fr) 16504 return false; 16505 16506 fold = old->frame[fr]; 16507 fcur = cur->frame[fr]; 16508 for (i = 0; i < MAX_BPF_REG; i++) 16509 if (memcmp(&fold->regs[i], &fcur->regs[i], 16510 offsetof(struct bpf_reg_state, parent))) 16511 return false; 16512 return true; 16513 } 16514 16515 static bool is_iter_next_insn(struct bpf_verifier_env *env, int insn_idx) 16516 { 16517 return env->insn_aux_data[insn_idx].is_iter_next; 16518 } 16519 16520 /* is_state_visited() handles iter_next() (see process_iter_next_call() for 16521 * terminology) calls specially: as opposed to bounded BPF loops, it *expects* 16522 * states to match, which otherwise would look like an infinite loop. So while 16523 * iter_next() calls are taken care of, we still need to be careful and 16524 * prevent erroneous and too eager declaration of "ininite loop", when 16525 * iterators are involved. 16526 * 16527 * Here's a situation in pseudo-BPF assembly form: 16528 * 16529 * 0: again: ; set up iter_next() call args 16530 * 1: r1 = &it ; <CHECKPOINT HERE> 16531 * 2: call bpf_iter_num_next ; this is iter_next() call 16532 * 3: if r0 == 0 goto done 16533 * 4: ... something useful here ... 16534 * 5: goto again ; another iteration 16535 * 6: done: 16536 * 7: r1 = &it 16537 * 8: call bpf_iter_num_destroy ; clean up iter state 16538 * 9: exit 16539 * 16540 * This is a typical loop. Let's assume that we have a prune point at 1:, 16541 * before we get to `call bpf_iter_num_next` (e.g., because of that `goto 16542 * again`, assuming other heuristics don't get in a way). 16543 * 16544 * When we first time come to 1:, let's say we have some state X. We proceed 16545 * to 2:, fork states, enqueue ACTIVE, validate NULL case successfully, exit. 16546 * Now we come back to validate that forked ACTIVE state. We proceed through 16547 * 3-5, come to goto, jump to 1:. Let's assume our state didn't change, so we 16548 * are converging. But the problem is that we don't know that yet, as this 16549 * convergence has to happen at iter_next() call site only. So if nothing is 16550 * done, at 1: verifier will use bounded loop logic and declare infinite 16551 * looping (and would be *technically* correct, if not for iterator's 16552 * "eventual sticky NULL" contract, see process_iter_next_call()). But we 16553 * don't want that. So what we do in process_iter_next_call() when we go on 16554 * another ACTIVE iteration, we bump slot->iter.depth, to mark that it's 16555 * a different iteration. So when we suspect an infinite loop, we additionally 16556 * check if any of the *ACTIVE* iterator states depths differ. If yes, we 16557 * pretend we are not looping and wait for next iter_next() call. 16558 * 16559 * This only applies to ACTIVE state. In DRAINED state we don't expect to 16560 * loop, because that would actually mean infinite loop, as DRAINED state is 16561 * "sticky", and so we'll keep returning into the same instruction with the 16562 * same state (at least in one of possible code paths). 16563 * 16564 * This approach allows to keep infinite loop heuristic even in the face of 16565 * active iterator. E.g., C snippet below is and will be detected as 16566 * inifintely looping: 16567 * 16568 * struct bpf_iter_num it; 16569 * int *p, x; 16570 * 16571 * bpf_iter_num_new(&it, 0, 10); 16572 * while ((p = bpf_iter_num_next(&t))) { 16573 * x = p; 16574 * while (x--) {} // <<-- infinite loop here 16575 * } 16576 * 16577 */ 16578 static bool iter_active_depths_differ(struct bpf_verifier_state *old, struct bpf_verifier_state *cur) 16579 { 16580 struct bpf_reg_state *slot, *cur_slot; 16581 struct bpf_func_state *state; 16582 int i, fr; 16583 16584 for (fr = old->curframe; fr >= 0; fr--) { 16585 state = old->frame[fr]; 16586 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) { 16587 if (state->stack[i].slot_type[0] != STACK_ITER) 16588 continue; 16589 16590 slot = &state->stack[i].spilled_ptr; 16591 if (slot->iter.state != BPF_ITER_STATE_ACTIVE) 16592 continue; 16593 16594 cur_slot = &cur->frame[fr]->stack[i].spilled_ptr; 16595 if (cur_slot->iter.depth != slot->iter.depth) 16596 return true; 16597 } 16598 } 16599 return false; 16600 } 16601 16602 static int is_state_visited(struct bpf_verifier_env *env, int insn_idx) 16603 { 16604 struct bpf_verifier_state_list *new_sl; 16605 struct bpf_verifier_state_list *sl, **pprev; 16606 struct bpf_verifier_state *cur = env->cur_state, *new, *loop_entry; 16607 int i, j, n, err, states_cnt = 0; 16608 bool force_new_state, add_new_state, force_exact; 16609 16610 force_new_state = env->test_state_freq || is_force_checkpoint(env, insn_idx) || 16611 /* Avoid accumulating infinitely long jmp history */ 16612 cur->jmp_history_cnt > 40; 16613 16614 /* bpf progs typically have pruning point every 4 instructions 16615 * http://vger.kernel.org/bpfconf2019.html#session-1 16616 * Do not add new state for future pruning if the verifier hasn't seen 16617 * at least 2 jumps and at least 8 instructions. 16618 * This heuristics helps decrease 'total_states' and 'peak_states' metric. 16619 * In tests that amounts to up to 50% reduction into total verifier 16620 * memory consumption and 20% verifier time speedup. 16621 */ 16622 add_new_state = force_new_state; 16623 if (env->jmps_processed - env->prev_jmps_processed >= 2 && 16624 env->insn_processed - env->prev_insn_processed >= 8) 16625 add_new_state = true; 16626 16627 pprev = explored_state(env, insn_idx); 16628 sl = *pprev; 16629 16630 clean_live_states(env, insn_idx, cur); 16631 16632 while (sl) { 16633 states_cnt++; 16634 if (sl->state.insn_idx != insn_idx) 16635 goto next; 16636 16637 if (sl->state.branches) { 16638 struct bpf_func_state *frame = sl->state.frame[sl->state.curframe]; 16639 16640 if (frame->in_async_callback_fn && 16641 frame->async_entry_cnt != cur->frame[cur->curframe]->async_entry_cnt) { 16642 /* Different async_entry_cnt means that the verifier is 16643 * processing another entry into async callback. 16644 * Seeing the same state is not an indication of infinite 16645 * loop or infinite recursion. 16646 * But finding the same state doesn't mean that it's safe 16647 * to stop processing the current state. The previous state 16648 * hasn't yet reached bpf_exit, since state.branches > 0. 16649 * Checking in_async_callback_fn alone is not enough either. 16650 * Since the verifier still needs to catch infinite loops 16651 * inside async callbacks. 16652 */ 16653 goto skip_inf_loop_check; 16654 } 16655 /* BPF open-coded iterators loop detection is special. 16656 * states_maybe_looping() logic is too simplistic in detecting 16657 * states that *might* be equivalent, because it doesn't know 16658 * about ID remapping, so don't even perform it. 16659 * See process_iter_next_call() and iter_active_depths_differ() 16660 * for overview of the logic. When current and one of parent 16661 * states are detected as equivalent, it's a good thing: we prove 16662 * convergence and can stop simulating further iterations. 16663 * It's safe to assume that iterator loop will finish, taking into 16664 * account iter_next() contract of eventually returning 16665 * sticky NULL result. 16666 * 16667 * Note, that states have to be compared exactly in this case because 16668 * read and precision marks might not be finalized inside the loop. 16669 * E.g. as in the program below: 16670 * 16671 * 1. r7 = -16 16672 * 2. r6 = bpf_get_prandom_u32() 16673 * 3. while (bpf_iter_num_next(&fp[-8])) { 16674 * 4. if (r6 != 42) { 16675 * 5. r7 = -32 16676 * 6. r6 = bpf_get_prandom_u32() 16677 * 7. continue 16678 * 8. } 16679 * 9. r0 = r10 16680 * 10. r0 += r7 16681 * 11. r8 = *(u64 *)(r0 + 0) 16682 * 12. r6 = bpf_get_prandom_u32() 16683 * 13. } 16684 * 16685 * Here verifier would first visit path 1-3, create a checkpoint at 3 16686 * with r7=-16, continue to 4-7,3. Existing checkpoint at 3 does 16687 * not have read or precision mark for r7 yet, thus inexact states 16688 * comparison would discard current state with r7=-32 16689 * => unsafe memory access at 11 would not be caught. 16690 */ 16691 if (is_iter_next_insn(env, insn_idx)) { 16692 if (states_equal(env, &sl->state, cur, true)) { 16693 struct bpf_func_state *cur_frame; 16694 struct bpf_reg_state *iter_state, *iter_reg; 16695 int spi; 16696 16697 cur_frame = cur->frame[cur->curframe]; 16698 /* btf_check_iter_kfuncs() enforces that 16699 * iter state pointer is always the first arg 16700 */ 16701 iter_reg = &cur_frame->regs[BPF_REG_1]; 16702 /* current state is valid due to states_equal(), 16703 * so we can assume valid iter and reg state, 16704 * no need for extra (re-)validations 16705 */ 16706 spi = __get_spi(iter_reg->off + iter_reg->var_off.value); 16707 iter_state = &func(env, iter_reg)->stack[spi].spilled_ptr; 16708 if (iter_state->iter.state == BPF_ITER_STATE_ACTIVE) { 16709 update_loop_entry(cur, &sl->state); 16710 goto hit; 16711 } 16712 } 16713 goto skip_inf_loop_check; 16714 } 16715 if (calls_callback(env, insn_idx)) { 16716 if (states_equal(env, &sl->state, cur, true)) 16717 goto hit; 16718 goto skip_inf_loop_check; 16719 } 16720 /* attempt to detect infinite loop to avoid unnecessary doomed work */ 16721 if (states_maybe_looping(&sl->state, cur) && 16722 states_equal(env, &sl->state, cur, false) && 16723 !iter_active_depths_differ(&sl->state, cur) && 16724 sl->state.callback_unroll_depth == cur->callback_unroll_depth) { 16725 verbose_linfo(env, insn_idx, "; "); 16726 verbose(env, "infinite loop detected at insn %d\n", insn_idx); 16727 verbose(env, "cur state:"); 16728 print_verifier_state(env, cur->frame[cur->curframe], true); 16729 verbose(env, "old state:"); 16730 print_verifier_state(env, sl->state.frame[cur->curframe], true); 16731 return -EINVAL; 16732 } 16733 /* if the verifier is processing a loop, avoid adding new state 16734 * too often, since different loop iterations have distinct 16735 * states and may not help future pruning. 16736 * This threshold shouldn't be too low to make sure that 16737 * a loop with large bound will be rejected quickly. 16738 * The most abusive loop will be: 16739 * r1 += 1 16740 * if r1 < 1000000 goto pc-2 16741 * 1M insn_procssed limit / 100 == 10k peak states. 16742 * This threshold shouldn't be too high either, since states 16743 * at the end of the loop are likely to be useful in pruning. 16744 */ 16745 skip_inf_loop_check: 16746 if (!force_new_state && 16747 env->jmps_processed - env->prev_jmps_processed < 20 && 16748 env->insn_processed - env->prev_insn_processed < 100) 16749 add_new_state = false; 16750 goto miss; 16751 } 16752 /* If sl->state is a part of a loop and this loop's entry is a part of 16753 * current verification path then states have to be compared exactly. 16754 * 'force_exact' is needed to catch the following case: 16755 * 16756 * initial Here state 'succ' was processed first, 16757 * | it was eventually tracked to produce a 16758 * V state identical to 'hdr'. 16759 * .---------> hdr All branches from 'succ' had been explored 16760 * | | and thus 'succ' has its .branches == 0. 16761 * | V 16762 * | .------... Suppose states 'cur' and 'succ' correspond 16763 * | | | to the same instruction + callsites. 16764 * | V V In such case it is necessary to check 16765 * | ... ... if 'succ' and 'cur' are states_equal(). 16766 * | | | If 'succ' and 'cur' are a part of the 16767 * | V V same loop exact flag has to be set. 16768 * | succ <- cur To check if that is the case, verify 16769 * | | if loop entry of 'succ' is in current 16770 * | V DFS path. 16771 * | ... 16772 * | | 16773 * '----' 16774 * 16775 * Additional details are in the comment before get_loop_entry(). 16776 */ 16777 loop_entry = get_loop_entry(&sl->state); 16778 force_exact = loop_entry && loop_entry->branches > 0; 16779 if (states_equal(env, &sl->state, cur, force_exact)) { 16780 if (force_exact) 16781 update_loop_entry(cur, loop_entry); 16782 hit: 16783 sl->hit_cnt++; 16784 /* reached equivalent register/stack state, 16785 * prune the search. 16786 * Registers read by the continuation are read by us. 16787 * If we have any write marks in env->cur_state, they 16788 * will prevent corresponding reads in the continuation 16789 * from reaching our parent (an explored_state). Our 16790 * own state will get the read marks recorded, but 16791 * they'll be immediately forgotten as we're pruning 16792 * this state and will pop a new one. 16793 */ 16794 err = propagate_liveness(env, &sl->state, cur); 16795 16796 /* if previous state reached the exit with precision and 16797 * current state is equivalent to it (except precsion marks) 16798 * the precision needs to be propagated back in 16799 * the current state. 16800 */ 16801 if (is_jmp_point(env, env->insn_idx)) 16802 err = err ? : push_jmp_history(env, cur, 0); 16803 err = err ? : propagate_precision(env, &sl->state); 16804 if (err) 16805 return err; 16806 return 1; 16807 } 16808 miss: 16809 /* when new state is not going to be added do not increase miss count. 16810 * Otherwise several loop iterations will remove the state 16811 * recorded earlier. The goal of these heuristics is to have 16812 * states from some iterations of the loop (some in the beginning 16813 * and some at the end) to help pruning. 16814 */ 16815 if (add_new_state) 16816 sl->miss_cnt++; 16817 /* heuristic to determine whether this state is beneficial 16818 * to keep checking from state equivalence point of view. 16819 * Higher numbers increase max_states_per_insn and verification time, 16820 * but do not meaningfully decrease insn_processed. 16821 * 'n' controls how many times state could miss before eviction. 16822 * Use bigger 'n' for checkpoints because evicting checkpoint states 16823 * too early would hinder iterator convergence. 16824 */ 16825 n = is_force_checkpoint(env, insn_idx) && sl->state.branches > 0 ? 64 : 3; 16826 if (sl->miss_cnt > sl->hit_cnt * n + n) { 16827 /* the state is unlikely to be useful. Remove it to 16828 * speed up verification 16829 */ 16830 *pprev = sl->next; 16831 if (sl->state.frame[0]->regs[0].live & REG_LIVE_DONE && 16832 !sl->state.used_as_loop_entry) { 16833 u32 br = sl->state.branches; 16834 16835 WARN_ONCE(br, 16836 "BUG live_done but branches_to_explore %d\n", 16837 br); 16838 free_verifier_state(&sl->state, false); 16839 kfree(sl); 16840 env->peak_states--; 16841 } else { 16842 /* cannot free this state, since parentage chain may 16843 * walk it later. Add it for free_list instead to 16844 * be freed at the end of verification 16845 */ 16846 sl->next = env->free_list; 16847 env->free_list = sl; 16848 } 16849 sl = *pprev; 16850 continue; 16851 } 16852 next: 16853 pprev = &sl->next; 16854 sl = *pprev; 16855 } 16856 16857 if (env->max_states_per_insn < states_cnt) 16858 env->max_states_per_insn = states_cnt; 16859 16860 if (!env->bpf_capable && states_cnt > BPF_COMPLEXITY_LIMIT_STATES) 16861 return 0; 16862 16863 if (!add_new_state) 16864 return 0; 16865 16866 /* There were no equivalent states, remember the current one. 16867 * Technically the current state is not proven to be safe yet, 16868 * but it will either reach outer most bpf_exit (which means it's safe) 16869 * or it will be rejected. When there are no loops the verifier won't be 16870 * seeing this tuple (frame[0].callsite, frame[1].callsite, .. insn_idx) 16871 * again on the way to bpf_exit. 16872 * When looping the sl->state.branches will be > 0 and this state 16873 * will not be considered for equivalence until branches == 0. 16874 */ 16875 new_sl = kzalloc(sizeof(struct bpf_verifier_state_list), GFP_KERNEL); 16876 if (!new_sl) 16877 return -ENOMEM; 16878 env->total_states++; 16879 env->peak_states++; 16880 env->prev_jmps_processed = env->jmps_processed; 16881 env->prev_insn_processed = env->insn_processed; 16882 16883 /* forget precise markings we inherited, see __mark_chain_precision */ 16884 if (env->bpf_capable) 16885 mark_all_scalars_imprecise(env, cur); 16886 16887 /* add new state to the head of linked list */ 16888 new = &new_sl->state; 16889 err = copy_verifier_state(new, cur); 16890 if (err) { 16891 free_verifier_state(new, false); 16892 kfree(new_sl); 16893 return err; 16894 } 16895 new->insn_idx = insn_idx; 16896 WARN_ONCE(new->branches != 1, 16897 "BUG is_state_visited:branches_to_explore=%d insn %d\n", new->branches, insn_idx); 16898 16899 cur->parent = new; 16900 cur->first_insn_idx = insn_idx; 16901 cur->dfs_depth = new->dfs_depth + 1; 16902 clear_jmp_history(cur); 16903 new_sl->next = *explored_state(env, insn_idx); 16904 *explored_state(env, insn_idx) = new_sl; 16905 /* connect new state to parentage chain. Current frame needs all 16906 * registers connected. Only r6 - r9 of the callers are alive (pushed 16907 * to the stack implicitly by JITs) so in callers' frames connect just 16908 * r6 - r9 as an optimization. Callers will have r1 - r5 connected to 16909 * the state of the call instruction (with WRITTEN set), and r0 comes 16910 * from callee with its full parentage chain, anyway. 16911 */ 16912 /* clear write marks in current state: the writes we did are not writes 16913 * our child did, so they don't screen off its reads from us. 16914 * (There are no read marks in current state, because reads always mark 16915 * their parent and current state never has children yet. Only 16916 * explored_states can get read marks.) 16917 */ 16918 for (j = 0; j <= cur->curframe; j++) { 16919 for (i = j < cur->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++) 16920 cur->frame[j]->regs[i].parent = &new->frame[j]->regs[i]; 16921 for (i = 0; i < BPF_REG_FP; i++) 16922 cur->frame[j]->regs[i].live = REG_LIVE_NONE; 16923 } 16924 16925 /* all stack frames are accessible from callee, clear them all */ 16926 for (j = 0; j <= cur->curframe; j++) { 16927 struct bpf_func_state *frame = cur->frame[j]; 16928 struct bpf_func_state *newframe = new->frame[j]; 16929 16930 for (i = 0; i < frame->allocated_stack / BPF_REG_SIZE; i++) { 16931 frame->stack[i].spilled_ptr.live = REG_LIVE_NONE; 16932 frame->stack[i].spilled_ptr.parent = 16933 &newframe->stack[i].spilled_ptr; 16934 } 16935 } 16936 return 0; 16937 } 16938 16939 /* Return true if it's OK to have the same insn return a different type. */ 16940 static bool reg_type_mismatch_ok(enum bpf_reg_type type) 16941 { 16942 switch (base_type(type)) { 16943 case PTR_TO_CTX: 16944 case PTR_TO_SOCKET: 16945 case PTR_TO_SOCK_COMMON: 16946 case PTR_TO_TCP_SOCK: 16947 case PTR_TO_XDP_SOCK: 16948 case PTR_TO_BTF_ID: 16949 return false; 16950 default: 16951 return true; 16952 } 16953 } 16954 16955 /* If an instruction was previously used with particular pointer types, then we 16956 * need to be careful to avoid cases such as the below, where it may be ok 16957 * for one branch accessing the pointer, but not ok for the other branch: 16958 * 16959 * R1 = sock_ptr 16960 * goto X; 16961 * ... 16962 * R1 = some_other_valid_ptr; 16963 * goto X; 16964 * ... 16965 * R2 = *(u32 *)(R1 + 0); 16966 */ 16967 static bool reg_type_mismatch(enum bpf_reg_type src, enum bpf_reg_type prev) 16968 { 16969 return src != prev && (!reg_type_mismatch_ok(src) || 16970 !reg_type_mismatch_ok(prev)); 16971 } 16972 16973 static int save_aux_ptr_type(struct bpf_verifier_env *env, enum bpf_reg_type type, 16974 bool allow_trust_missmatch) 16975 { 16976 enum bpf_reg_type *prev_type = &env->insn_aux_data[env->insn_idx].ptr_type; 16977 16978 if (*prev_type == NOT_INIT) { 16979 /* Saw a valid insn 16980 * dst_reg = *(u32 *)(src_reg + off) 16981 * save type to validate intersecting paths 16982 */ 16983 *prev_type = type; 16984 } else if (reg_type_mismatch(type, *prev_type)) { 16985 /* Abuser program is trying to use the same insn 16986 * dst_reg = *(u32*) (src_reg + off) 16987 * with different pointer types: 16988 * src_reg == ctx in one branch and 16989 * src_reg == stack|map in some other branch. 16990 * Reject it. 16991 */ 16992 if (allow_trust_missmatch && 16993 base_type(type) == PTR_TO_BTF_ID && 16994 base_type(*prev_type) == PTR_TO_BTF_ID) { 16995 /* 16996 * Have to support a use case when one path through 16997 * the program yields TRUSTED pointer while another 16998 * is UNTRUSTED. Fallback to UNTRUSTED to generate 16999 * BPF_PROBE_MEM/BPF_PROBE_MEMSX. 17000 */ 17001 *prev_type = PTR_TO_BTF_ID | PTR_UNTRUSTED; 17002 } else { 17003 verbose(env, "same insn cannot be used with different pointers\n"); 17004 return -EINVAL; 17005 } 17006 } 17007 17008 return 0; 17009 } 17010 17011 static int do_check(struct bpf_verifier_env *env) 17012 { 17013 bool pop_log = !(env->log.level & BPF_LOG_LEVEL2); 17014 struct bpf_verifier_state *state = env->cur_state; 17015 struct bpf_insn *insns = env->prog->insnsi; 17016 struct bpf_reg_state *regs; 17017 int insn_cnt = env->prog->len; 17018 bool do_print_state = false; 17019 int prev_insn_idx = -1; 17020 17021 for (;;) { 17022 struct bpf_insn *insn; 17023 u8 class; 17024 int err; 17025 17026 /* reset current history entry on each new instruction */ 17027 env->cur_hist_ent = NULL; 17028 17029 env->prev_insn_idx = prev_insn_idx; 17030 if (env->insn_idx >= insn_cnt) { 17031 verbose(env, "invalid insn idx %d insn_cnt %d\n", 17032 env->insn_idx, insn_cnt); 17033 return -EFAULT; 17034 } 17035 17036 insn = &insns[env->insn_idx]; 17037 class = BPF_CLASS(insn->code); 17038 17039 if (++env->insn_processed > BPF_COMPLEXITY_LIMIT_INSNS) { 17040 verbose(env, 17041 "BPF program is too large. Processed %d insn\n", 17042 env->insn_processed); 17043 return -E2BIG; 17044 } 17045 17046 state->last_insn_idx = env->prev_insn_idx; 17047 17048 if (is_prune_point(env, env->insn_idx)) { 17049 err = is_state_visited(env, env->insn_idx); 17050 if (err < 0) 17051 return err; 17052 if (err == 1) { 17053 /* found equivalent state, can prune the search */ 17054 if (env->log.level & BPF_LOG_LEVEL) { 17055 if (do_print_state) 17056 verbose(env, "\nfrom %d to %d%s: safe\n", 17057 env->prev_insn_idx, env->insn_idx, 17058 env->cur_state->speculative ? 17059 " (speculative execution)" : ""); 17060 else 17061 verbose(env, "%d: safe\n", env->insn_idx); 17062 } 17063 goto process_bpf_exit; 17064 } 17065 } 17066 17067 if (is_jmp_point(env, env->insn_idx)) { 17068 err = push_jmp_history(env, state, 0); 17069 if (err) 17070 return err; 17071 } 17072 17073 if (signal_pending(current)) 17074 return -EAGAIN; 17075 17076 if (need_resched()) 17077 cond_resched(); 17078 17079 if (env->log.level & BPF_LOG_LEVEL2 && do_print_state) { 17080 verbose(env, "\nfrom %d to %d%s:", 17081 env->prev_insn_idx, env->insn_idx, 17082 env->cur_state->speculative ? 17083 " (speculative execution)" : ""); 17084 print_verifier_state(env, state->frame[state->curframe], true); 17085 do_print_state = false; 17086 } 17087 17088 if (env->log.level & BPF_LOG_LEVEL) { 17089 const struct bpf_insn_cbs cbs = { 17090 .cb_call = disasm_kfunc_name, 17091 .cb_print = verbose, 17092 .private_data = env, 17093 }; 17094 17095 if (verifier_state_scratched(env)) 17096 print_insn_state(env, state->frame[state->curframe]); 17097 17098 verbose_linfo(env, env->insn_idx, "; "); 17099 env->prev_log_pos = env->log.end_pos; 17100 verbose(env, "%d: ", env->insn_idx); 17101 print_bpf_insn(&cbs, insn, env->allow_ptr_leaks); 17102 env->prev_insn_print_pos = env->log.end_pos - env->prev_log_pos; 17103 env->prev_log_pos = env->log.end_pos; 17104 } 17105 17106 if (bpf_prog_is_offloaded(env->prog->aux)) { 17107 err = bpf_prog_offload_verify_insn(env, env->insn_idx, 17108 env->prev_insn_idx); 17109 if (err) 17110 return err; 17111 } 17112 17113 regs = cur_regs(env); 17114 sanitize_mark_insn_seen(env); 17115 prev_insn_idx = env->insn_idx; 17116 17117 if (class == BPF_ALU || class == BPF_ALU64) { 17118 err = check_alu_op(env, insn); 17119 if (err) 17120 return err; 17121 17122 } else if (class == BPF_LDX) { 17123 enum bpf_reg_type src_reg_type; 17124 17125 /* check for reserved fields is already done */ 17126 17127 /* check src operand */ 17128 err = check_reg_arg(env, insn->src_reg, SRC_OP); 17129 if (err) 17130 return err; 17131 17132 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK); 17133 if (err) 17134 return err; 17135 17136 src_reg_type = regs[insn->src_reg].type; 17137 17138 /* check that memory (src_reg + off) is readable, 17139 * the state of dst_reg will be updated by this func 17140 */ 17141 err = check_mem_access(env, env->insn_idx, insn->src_reg, 17142 insn->off, BPF_SIZE(insn->code), 17143 BPF_READ, insn->dst_reg, false, 17144 BPF_MODE(insn->code) == BPF_MEMSX); 17145 if (err) 17146 return err; 17147 17148 err = save_aux_ptr_type(env, src_reg_type, true); 17149 if (err) 17150 return err; 17151 } else if (class == BPF_STX) { 17152 enum bpf_reg_type dst_reg_type; 17153 17154 if (BPF_MODE(insn->code) == BPF_ATOMIC) { 17155 err = check_atomic(env, env->insn_idx, insn); 17156 if (err) 17157 return err; 17158 env->insn_idx++; 17159 continue; 17160 } 17161 17162 if (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0) { 17163 verbose(env, "BPF_STX uses reserved fields\n"); 17164 return -EINVAL; 17165 } 17166 17167 /* check src1 operand */ 17168 err = check_reg_arg(env, insn->src_reg, SRC_OP); 17169 if (err) 17170 return err; 17171 /* check src2 operand */ 17172 err = check_reg_arg(env, insn->dst_reg, SRC_OP); 17173 if (err) 17174 return err; 17175 17176 dst_reg_type = regs[insn->dst_reg].type; 17177 17178 /* check that memory (dst_reg + off) is writeable */ 17179 err = check_mem_access(env, env->insn_idx, insn->dst_reg, 17180 insn->off, BPF_SIZE(insn->code), 17181 BPF_WRITE, insn->src_reg, false, false); 17182 if (err) 17183 return err; 17184 17185 err = save_aux_ptr_type(env, dst_reg_type, false); 17186 if (err) 17187 return err; 17188 } else if (class == BPF_ST) { 17189 enum bpf_reg_type dst_reg_type; 17190 17191 if (BPF_MODE(insn->code) != BPF_MEM || 17192 insn->src_reg != BPF_REG_0) { 17193 verbose(env, "BPF_ST uses reserved fields\n"); 17194 return -EINVAL; 17195 } 17196 /* check src operand */ 17197 err = check_reg_arg(env, insn->dst_reg, SRC_OP); 17198 if (err) 17199 return err; 17200 17201 dst_reg_type = regs[insn->dst_reg].type; 17202 17203 /* check that memory (dst_reg + off) is writeable */ 17204 err = check_mem_access(env, env->insn_idx, insn->dst_reg, 17205 insn->off, BPF_SIZE(insn->code), 17206 BPF_WRITE, -1, false, false); 17207 if (err) 17208 return err; 17209 17210 err = save_aux_ptr_type(env, dst_reg_type, false); 17211 if (err) 17212 return err; 17213 } else if (class == BPF_JMP || class == BPF_JMP32) { 17214 u8 opcode = BPF_OP(insn->code); 17215 17216 env->jmps_processed++; 17217 if (opcode == BPF_CALL) { 17218 if (BPF_SRC(insn->code) != BPF_K || 17219 (insn->src_reg != BPF_PSEUDO_KFUNC_CALL 17220 && insn->off != 0) || 17221 (insn->src_reg != BPF_REG_0 && 17222 insn->src_reg != BPF_PSEUDO_CALL && 17223 insn->src_reg != BPF_PSEUDO_KFUNC_CALL) || 17224 insn->dst_reg != BPF_REG_0 || 17225 class == BPF_JMP32) { 17226 verbose(env, "BPF_CALL uses reserved fields\n"); 17227 return -EINVAL; 17228 } 17229 17230 if (env->cur_state->active_lock.ptr) { 17231 if ((insn->src_reg == BPF_REG_0 && insn->imm != BPF_FUNC_spin_unlock) || 17232 (insn->src_reg == BPF_PSEUDO_CALL) || 17233 (insn->src_reg == BPF_PSEUDO_KFUNC_CALL && 17234 (insn->off != 0 || !is_bpf_graph_api_kfunc(insn->imm)))) { 17235 verbose(env, "function calls are not allowed while holding a lock\n"); 17236 return -EINVAL; 17237 } 17238 } 17239 if (insn->src_reg == BPF_PSEUDO_CALL) 17240 err = check_func_call(env, insn, &env->insn_idx); 17241 else if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) 17242 err = check_kfunc_call(env, insn, &env->insn_idx); 17243 else 17244 err = check_helper_call(env, insn, &env->insn_idx); 17245 if (err) 17246 return err; 17247 17248 mark_reg_scratched(env, BPF_REG_0); 17249 } else if (opcode == BPF_JA) { 17250 if (BPF_SRC(insn->code) != BPF_K || 17251 insn->src_reg != BPF_REG_0 || 17252 insn->dst_reg != BPF_REG_0 || 17253 (class == BPF_JMP && insn->imm != 0) || 17254 (class == BPF_JMP32 && insn->off != 0)) { 17255 verbose(env, "BPF_JA uses reserved fields\n"); 17256 return -EINVAL; 17257 } 17258 17259 if (class == BPF_JMP) 17260 env->insn_idx += insn->off + 1; 17261 else 17262 env->insn_idx += insn->imm + 1; 17263 continue; 17264 17265 } else if (opcode == BPF_EXIT) { 17266 if (BPF_SRC(insn->code) != BPF_K || 17267 insn->imm != 0 || 17268 insn->src_reg != BPF_REG_0 || 17269 insn->dst_reg != BPF_REG_0 || 17270 class == BPF_JMP32) { 17271 verbose(env, "BPF_EXIT uses reserved fields\n"); 17272 return -EINVAL; 17273 } 17274 17275 if (env->cur_state->active_lock.ptr && 17276 !in_rbtree_lock_required_cb(env)) { 17277 verbose(env, "bpf_spin_unlock is missing\n"); 17278 return -EINVAL; 17279 } 17280 17281 if (env->cur_state->active_rcu_lock && 17282 !in_rbtree_lock_required_cb(env)) { 17283 verbose(env, "bpf_rcu_read_unlock is missing\n"); 17284 return -EINVAL; 17285 } 17286 17287 /* We must do check_reference_leak here before 17288 * prepare_func_exit to handle the case when 17289 * state->curframe > 0, it may be a callback 17290 * function, for which reference_state must 17291 * match caller reference state when it exits. 17292 */ 17293 err = check_reference_leak(env); 17294 if (err) 17295 return err; 17296 17297 if (state->curframe) { 17298 /* exit from nested function */ 17299 err = prepare_func_exit(env, &env->insn_idx); 17300 if (err) 17301 return err; 17302 do_print_state = true; 17303 continue; 17304 } 17305 17306 err = check_return_code(env); 17307 if (err) 17308 return err; 17309 process_bpf_exit: 17310 mark_verifier_state_scratched(env); 17311 update_branch_counts(env, env->cur_state); 17312 err = pop_stack(env, &prev_insn_idx, 17313 &env->insn_idx, pop_log); 17314 if (err < 0) { 17315 if (err != -ENOENT) 17316 return err; 17317 break; 17318 } else { 17319 do_print_state = true; 17320 continue; 17321 } 17322 } else { 17323 err = check_cond_jmp_op(env, insn, &env->insn_idx); 17324 if (err) 17325 return err; 17326 } 17327 } else if (class == BPF_LD) { 17328 u8 mode = BPF_MODE(insn->code); 17329 17330 if (mode == BPF_ABS || mode == BPF_IND) { 17331 err = check_ld_abs(env, insn); 17332 if (err) 17333 return err; 17334 17335 } else if (mode == BPF_IMM) { 17336 err = check_ld_imm(env, insn); 17337 if (err) 17338 return err; 17339 17340 env->insn_idx++; 17341 sanitize_mark_insn_seen(env); 17342 } else { 17343 verbose(env, "invalid BPF_LD mode\n"); 17344 return -EINVAL; 17345 } 17346 } else { 17347 verbose(env, "unknown insn class %d\n", class); 17348 return -EINVAL; 17349 } 17350 17351 env->insn_idx++; 17352 } 17353 17354 return 0; 17355 } 17356 17357 static int find_btf_percpu_datasec(struct btf *btf) 17358 { 17359 const struct btf_type *t; 17360 const char *tname; 17361 int i, n; 17362 17363 /* 17364 * Both vmlinux and module each have their own ".data..percpu" 17365 * DATASECs in BTF. So for module's case, we need to skip vmlinux BTF 17366 * types to look at only module's own BTF types. 17367 */ 17368 n = btf_nr_types(btf); 17369 if (btf_is_module(btf)) 17370 i = btf_nr_types(btf_vmlinux); 17371 else 17372 i = 1; 17373 17374 for(; i < n; i++) { 17375 t = btf_type_by_id(btf, i); 17376 if (BTF_INFO_KIND(t->info) != BTF_KIND_DATASEC) 17377 continue; 17378 17379 tname = btf_name_by_offset(btf, t->name_off); 17380 if (!strcmp(tname, ".data..percpu")) 17381 return i; 17382 } 17383 17384 return -ENOENT; 17385 } 17386 17387 /* replace pseudo btf_id with kernel symbol address */ 17388 static int check_pseudo_btf_id(struct bpf_verifier_env *env, 17389 struct bpf_insn *insn, 17390 struct bpf_insn_aux_data *aux) 17391 { 17392 const struct btf_var_secinfo *vsi; 17393 const struct btf_type *datasec; 17394 struct btf_mod_pair *btf_mod; 17395 const struct btf_type *t; 17396 const char *sym_name; 17397 bool percpu = false; 17398 u32 type, id = insn->imm; 17399 struct btf *btf; 17400 s32 datasec_id; 17401 u64 addr; 17402 int i, btf_fd, err; 17403 17404 btf_fd = insn[1].imm; 17405 if (btf_fd) { 17406 btf = btf_get_by_fd(btf_fd); 17407 if (IS_ERR(btf)) { 17408 verbose(env, "invalid module BTF object FD specified.\n"); 17409 return -EINVAL; 17410 } 17411 } else { 17412 if (!btf_vmlinux) { 17413 verbose(env, "kernel is missing BTF, make sure CONFIG_DEBUG_INFO_BTF=y is specified in Kconfig.\n"); 17414 return -EINVAL; 17415 } 17416 btf = btf_vmlinux; 17417 btf_get(btf); 17418 } 17419 17420 t = btf_type_by_id(btf, id); 17421 if (!t) { 17422 verbose(env, "ldimm64 insn specifies invalid btf_id %d.\n", id); 17423 err = -ENOENT; 17424 goto err_put; 17425 } 17426 17427 if (!btf_type_is_var(t) && !btf_type_is_func(t)) { 17428 verbose(env, "pseudo btf_id %d in ldimm64 isn't KIND_VAR or KIND_FUNC\n", id); 17429 err = -EINVAL; 17430 goto err_put; 17431 } 17432 17433 sym_name = btf_name_by_offset(btf, t->name_off); 17434 addr = kallsyms_lookup_name(sym_name); 17435 if (!addr) { 17436 verbose(env, "ldimm64 failed to find the address for kernel symbol '%s'.\n", 17437 sym_name); 17438 err = -ENOENT; 17439 goto err_put; 17440 } 17441 insn[0].imm = (u32)addr; 17442 insn[1].imm = addr >> 32; 17443 17444 if (btf_type_is_func(t)) { 17445 aux->btf_var.reg_type = PTR_TO_MEM | MEM_RDONLY; 17446 aux->btf_var.mem_size = 0; 17447 goto check_btf; 17448 } 17449 17450 datasec_id = find_btf_percpu_datasec(btf); 17451 if (datasec_id > 0) { 17452 datasec = btf_type_by_id(btf, datasec_id); 17453 for_each_vsi(i, datasec, vsi) { 17454 if (vsi->type == id) { 17455 percpu = true; 17456 break; 17457 } 17458 } 17459 } 17460 17461 type = t->type; 17462 t = btf_type_skip_modifiers(btf, type, NULL); 17463 if (percpu) { 17464 aux->btf_var.reg_type = PTR_TO_BTF_ID | MEM_PERCPU; 17465 aux->btf_var.btf = btf; 17466 aux->btf_var.btf_id = type; 17467 } else if (!btf_type_is_struct(t)) { 17468 const struct btf_type *ret; 17469 const char *tname; 17470 u32 tsize; 17471 17472 /* resolve the type size of ksym. */ 17473 ret = btf_resolve_size(btf, t, &tsize); 17474 if (IS_ERR(ret)) { 17475 tname = btf_name_by_offset(btf, t->name_off); 17476 verbose(env, "ldimm64 unable to resolve the size of type '%s': %ld\n", 17477 tname, PTR_ERR(ret)); 17478 err = -EINVAL; 17479 goto err_put; 17480 } 17481 aux->btf_var.reg_type = PTR_TO_MEM | MEM_RDONLY; 17482 aux->btf_var.mem_size = tsize; 17483 } else { 17484 aux->btf_var.reg_type = PTR_TO_BTF_ID; 17485 aux->btf_var.btf = btf; 17486 aux->btf_var.btf_id = type; 17487 } 17488 check_btf: 17489 /* check whether we recorded this BTF (and maybe module) already */ 17490 for (i = 0; i < env->used_btf_cnt; i++) { 17491 if (env->used_btfs[i].btf == btf) { 17492 btf_put(btf); 17493 return 0; 17494 } 17495 } 17496 17497 if (env->used_btf_cnt >= MAX_USED_BTFS) { 17498 err = -E2BIG; 17499 goto err_put; 17500 } 17501 17502 btf_mod = &env->used_btfs[env->used_btf_cnt]; 17503 btf_mod->btf = btf; 17504 btf_mod->module = NULL; 17505 17506 /* if we reference variables from kernel module, bump its refcount */ 17507 if (btf_is_module(btf)) { 17508 btf_mod->module = btf_try_get_module(btf); 17509 if (!btf_mod->module) { 17510 err = -ENXIO; 17511 goto err_put; 17512 } 17513 } 17514 17515 env->used_btf_cnt++; 17516 17517 return 0; 17518 err_put: 17519 btf_put(btf); 17520 return err; 17521 } 17522 17523 static bool is_tracing_prog_type(enum bpf_prog_type type) 17524 { 17525 switch (type) { 17526 case BPF_PROG_TYPE_KPROBE: 17527 case BPF_PROG_TYPE_TRACEPOINT: 17528 case BPF_PROG_TYPE_PERF_EVENT: 17529 case BPF_PROG_TYPE_RAW_TRACEPOINT: 17530 case BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE: 17531 return true; 17532 default: 17533 return false; 17534 } 17535 } 17536 17537 static int check_map_prog_compatibility(struct bpf_verifier_env *env, 17538 struct bpf_map *map, 17539 struct bpf_prog *prog) 17540 17541 { 17542 enum bpf_prog_type prog_type = resolve_prog_type(prog); 17543 17544 if (btf_record_has_field(map->record, BPF_LIST_HEAD) || 17545 btf_record_has_field(map->record, BPF_RB_ROOT)) { 17546 if (is_tracing_prog_type(prog_type)) { 17547 verbose(env, "tracing progs cannot use bpf_{list_head,rb_root} yet\n"); 17548 return -EINVAL; 17549 } 17550 } 17551 17552 if (btf_record_has_field(map->record, BPF_SPIN_LOCK)) { 17553 if (prog_type == BPF_PROG_TYPE_SOCKET_FILTER) { 17554 verbose(env, "socket filter progs cannot use bpf_spin_lock yet\n"); 17555 return -EINVAL; 17556 } 17557 17558 if (is_tracing_prog_type(prog_type)) { 17559 verbose(env, "tracing progs cannot use bpf_spin_lock yet\n"); 17560 return -EINVAL; 17561 } 17562 } 17563 17564 if (btf_record_has_field(map->record, BPF_TIMER)) { 17565 if (is_tracing_prog_type(prog_type)) { 17566 verbose(env, "tracing progs cannot use bpf_timer yet\n"); 17567 return -EINVAL; 17568 } 17569 } 17570 17571 if ((bpf_prog_is_offloaded(prog->aux) || bpf_map_is_offloaded(map)) && 17572 !bpf_offload_prog_map_match(prog, map)) { 17573 verbose(env, "offload device mismatch between prog and map\n"); 17574 return -EINVAL; 17575 } 17576 17577 if (map->map_type == BPF_MAP_TYPE_STRUCT_OPS) { 17578 verbose(env, "bpf_struct_ops map cannot be used in prog\n"); 17579 return -EINVAL; 17580 } 17581 17582 if (prog->aux->sleepable) 17583 switch (map->map_type) { 17584 case BPF_MAP_TYPE_HASH: 17585 case BPF_MAP_TYPE_LRU_HASH: 17586 case BPF_MAP_TYPE_ARRAY: 17587 case BPF_MAP_TYPE_PERCPU_HASH: 17588 case BPF_MAP_TYPE_PERCPU_ARRAY: 17589 case BPF_MAP_TYPE_LRU_PERCPU_HASH: 17590 case BPF_MAP_TYPE_ARRAY_OF_MAPS: 17591 case BPF_MAP_TYPE_HASH_OF_MAPS: 17592 case BPF_MAP_TYPE_RINGBUF: 17593 case BPF_MAP_TYPE_USER_RINGBUF: 17594 case BPF_MAP_TYPE_INODE_STORAGE: 17595 case BPF_MAP_TYPE_SK_STORAGE: 17596 case BPF_MAP_TYPE_TASK_STORAGE: 17597 case BPF_MAP_TYPE_CGRP_STORAGE: 17598 break; 17599 default: 17600 verbose(env, 17601 "Sleepable programs can only use array, hash, ringbuf and local storage maps\n"); 17602 return -EINVAL; 17603 } 17604 17605 return 0; 17606 } 17607 17608 static bool bpf_map_is_cgroup_storage(struct bpf_map *map) 17609 { 17610 return (map->map_type == BPF_MAP_TYPE_CGROUP_STORAGE || 17611 map->map_type == BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE); 17612 } 17613 17614 /* find and rewrite pseudo imm in ld_imm64 instructions: 17615 * 17616 * 1. if it accesses map FD, replace it with actual map pointer. 17617 * 2. if it accesses btf_id of a VAR, replace it with pointer to the var. 17618 * 17619 * NOTE: btf_vmlinux is required for converting pseudo btf_id. 17620 */ 17621 static int resolve_pseudo_ldimm64(struct bpf_verifier_env *env) 17622 { 17623 struct bpf_insn *insn = env->prog->insnsi; 17624 int insn_cnt = env->prog->len; 17625 int i, j, err; 17626 17627 err = bpf_prog_calc_tag(env->prog); 17628 if (err) 17629 return err; 17630 17631 for (i = 0; i < insn_cnt; i++, insn++) { 17632 if (BPF_CLASS(insn->code) == BPF_LDX && 17633 ((BPF_MODE(insn->code) != BPF_MEM && BPF_MODE(insn->code) != BPF_MEMSX) || 17634 insn->imm != 0)) { 17635 verbose(env, "BPF_LDX uses reserved fields\n"); 17636 return -EINVAL; 17637 } 17638 17639 if (insn[0].code == (BPF_LD | BPF_IMM | BPF_DW)) { 17640 struct bpf_insn_aux_data *aux; 17641 struct bpf_map *map; 17642 struct fd f; 17643 u64 addr; 17644 u32 fd; 17645 17646 if (i == insn_cnt - 1 || insn[1].code != 0 || 17647 insn[1].dst_reg != 0 || insn[1].src_reg != 0 || 17648 insn[1].off != 0) { 17649 verbose(env, "invalid bpf_ld_imm64 insn\n"); 17650 return -EINVAL; 17651 } 17652 17653 if (insn[0].src_reg == 0) 17654 /* valid generic load 64-bit imm */ 17655 goto next_insn; 17656 17657 if (insn[0].src_reg == BPF_PSEUDO_BTF_ID) { 17658 aux = &env->insn_aux_data[i]; 17659 err = check_pseudo_btf_id(env, insn, aux); 17660 if (err) 17661 return err; 17662 goto next_insn; 17663 } 17664 17665 if (insn[0].src_reg == BPF_PSEUDO_FUNC) { 17666 aux = &env->insn_aux_data[i]; 17667 aux->ptr_type = PTR_TO_FUNC; 17668 goto next_insn; 17669 } 17670 17671 /* In final convert_pseudo_ld_imm64() step, this is 17672 * converted into regular 64-bit imm load insn. 17673 */ 17674 switch (insn[0].src_reg) { 17675 case BPF_PSEUDO_MAP_VALUE: 17676 case BPF_PSEUDO_MAP_IDX_VALUE: 17677 break; 17678 case BPF_PSEUDO_MAP_FD: 17679 case BPF_PSEUDO_MAP_IDX: 17680 if (insn[1].imm == 0) 17681 break; 17682 fallthrough; 17683 default: 17684 verbose(env, "unrecognized bpf_ld_imm64 insn\n"); 17685 return -EINVAL; 17686 } 17687 17688 switch (insn[0].src_reg) { 17689 case BPF_PSEUDO_MAP_IDX_VALUE: 17690 case BPF_PSEUDO_MAP_IDX: 17691 if (bpfptr_is_null(env->fd_array)) { 17692 verbose(env, "fd_idx without fd_array is invalid\n"); 17693 return -EPROTO; 17694 } 17695 if (copy_from_bpfptr_offset(&fd, env->fd_array, 17696 insn[0].imm * sizeof(fd), 17697 sizeof(fd))) 17698 return -EFAULT; 17699 break; 17700 default: 17701 fd = insn[0].imm; 17702 break; 17703 } 17704 17705 f = fdget(fd); 17706 map = __bpf_map_get(f); 17707 if (IS_ERR(map)) { 17708 verbose(env, "fd %d is not pointing to valid bpf_map\n", fd); 17709 return PTR_ERR(map); 17710 } 17711 17712 err = check_map_prog_compatibility(env, map, env->prog); 17713 if (err) { 17714 fdput(f); 17715 return err; 17716 } 17717 17718 aux = &env->insn_aux_data[i]; 17719 if (insn[0].src_reg == BPF_PSEUDO_MAP_FD || 17720 insn[0].src_reg == BPF_PSEUDO_MAP_IDX) { 17721 addr = (unsigned long)map; 17722 } else { 17723 u32 off = insn[1].imm; 17724 17725 if (off >= BPF_MAX_VAR_OFF) { 17726 verbose(env, "direct value offset of %u is not allowed\n", off); 17727 fdput(f); 17728 return -EINVAL; 17729 } 17730 17731 if (!map->ops->map_direct_value_addr) { 17732 verbose(env, "no direct value access support for this map type\n"); 17733 fdput(f); 17734 return -EINVAL; 17735 } 17736 17737 err = map->ops->map_direct_value_addr(map, &addr, off); 17738 if (err) { 17739 verbose(env, "invalid access to map value pointer, value_size=%u off=%u\n", 17740 map->value_size, off); 17741 fdput(f); 17742 return err; 17743 } 17744 17745 aux->map_off = off; 17746 addr += off; 17747 } 17748 17749 insn[0].imm = (u32)addr; 17750 insn[1].imm = addr >> 32; 17751 17752 /* check whether we recorded this map already */ 17753 for (j = 0; j < env->used_map_cnt; j++) { 17754 if (env->used_maps[j] == map) { 17755 aux->map_index = j; 17756 fdput(f); 17757 goto next_insn; 17758 } 17759 } 17760 17761 if (env->used_map_cnt >= MAX_USED_MAPS) { 17762 fdput(f); 17763 return -E2BIG; 17764 } 17765 17766 if (env->prog->aux->sleepable) 17767 atomic64_inc(&map->sleepable_refcnt); 17768 /* hold the map. If the program is rejected by verifier, 17769 * the map will be released by release_maps() or it 17770 * will be used by the valid program until it's unloaded 17771 * and all maps are released in bpf_free_used_maps() 17772 */ 17773 bpf_map_inc(map); 17774 17775 aux->map_index = env->used_map_cnt; 17776 env->used_maps[env->used_map_cnt++] = map; 17777 17778 if (bpf_map_is_cgroup_storage(map) && 17779 bpf_cgroup_storage_assign(env->prog->aux, map)) { 17780 verbose(env, "only one cgroup storage of each type is allowed\n"); 17781 fdput(f); 17782 return -EBUSY; 17783 } 17784 17785 fdput(f); 17786 next_insn: 17787 insn++; 17788 i++; 17789 continue; 17790 } 17791 17792 /* Basic sanity check before we invest more work here. */ 17793 if (!bpf_opcode_in_insntable(insn->code)) { 17794 verbose(env, "unknown opcode %02x\n", insn->code); 17795 return -EINVAL; 17796 } 17797 } 17798 17799 /* now all pseudo BPF_LD_IMM64 instructions load valid 17800 * 'struct bpf_map *' into a register instead of user map_fd. 17801 * These pointers will be used later by verifier to validate map access. 17802 */ 17803 return 0; 17804 } 17805 17806 /* drop refcnt of maps used by the rejected program */ 17807 static void release_maps(struct bpf_verifier_env *env) 17808 { 17809 __bpf_free_used_maps(env->prog->aux, env->used_maps, 17810 env->used_map_cnt); 17811 } 17812 17813 /* drop refcnt of maps used by the rejected program */ 17814 static void release_btfs(struct bpf_verifier_env *env) 17815 { 17816 __bpf_free_used_btfs(env->prog->aux, env->used_btfs, 17817 env->used_btf_cnt); 17818 } 17819 17820 /* convert pseudo BPF_LD_IMM64 into generic BPF_LD_IMM64 */ 17821 static void convert_pseudo_ld_imm64(struct bpf_verifier_env *env) 17822 { 17823 struct bpf_insn *insn = env->prog->insnsi; 17824 int insn_cnt = env->prog->len; 17825 int i; 17826 17827 for (i = 0; i < insn_cnt; i++, insn++) { 17828 if (insn->code != (BPF_LD | BPF_IMM | BPF_DW)) 17829 continue; 17830 if (insn->src_reg == BPF_PSEUDO_FUNC) 17831 continue; 17832 insn->src_reg = 0; 17833 } 17834 } 17835 17836 /* single env->prog->insni[off] instruction was replaced with the range 17837 * insni[off, off + cnt). Adjust corresponding insn_aux_data by copying 17838 * [0, off) and [off, end) to new locations, so the patched range stays zero 17839 */ 17840 static void adjust_insn_aux_data(struct bpf_verifier_env *env, 17841 struct bpf_insn_aux_data *new_data, 17842 struct bpf_prog *new_prog, u32 off, u32 cnt) 17843 { 17844 struct bpf_insn_aux_data *old_data = env->insn_aux_data; 17845 struct bpf_insn *insn = new_prog->insnsi; 17846 u32 old_seen = old_data[off].seen; 17847 u32 prog_len; 17848 int i; 17849 17850 /* aux info at OFF always needs adjustment, no matter fast path 17851 * (cnt == 1) is taken or not. There is no guarantee INSN at OFF is the 17852 * original insn at old prog. 17853 */ 17854 old_data[off].zext_dst = insn_has_def32(env, insn + off + cnt - 1); 17855 17856 if (cnt == 1) 17857 return; 17858 prog_len = new_prog->len; 17859 17860 memcpy(new_data, old_data, sizeof(struct bpf_insn_aux_data) * off); 17861 memcpy(new_data + off + cnt - 1, old_data + off, 17862 sizeof(struct bpf_insn_aux_data) * (prog_len - off - cnt + 1)); 17863 for (i = off; i < off + cnt - 1; i++) { 17864 /* Expand insni[off]'s seen count to the patched range. */ 17865 new_data[i].seen = old_seen; 17866 new_data[i].zext_dst = insn_has_def32(env, insn + i); 17867 } 17868 env->insn_aux_data = new_data; 17869 vfree(old_data); 17870 } 17871 17872 static void adjust_subprog_starts(struct bpf_verifier_env *env, u32 off, u32 len) 17873 { 17874 int i; 17875 17876 if (len == 1) 17877 return; 17878 /* NOTE: fake 'exit' subprog should be updated as well. */ 17879 for (i = 0; i <= env->subprog_cnt; i++) { 17880 if (env->subprog_info[i].start <= off) 17881 continue; 17882 env->subprog_info[i].start += len - 1; 17883 } 17884 } 17885 17886 static void adjust_poke_descs(struct bpf_prog *prog, u32 off, u32 len) 17887 { 17888 struct bpf_jit_poke_descriptor *tab = prog->aux->poke_tab; 17889 int i, sz = prog->aux->size_poke_tab; 17890 struct bpf_jit_poke_descriptor *desc; 17891 17892 for (i = 0; i < sz; i++) { 17893 desc = &tab[i]; 17894 if (desc->insn_idx <= off) 17895 continue; 17896 desc->insn_idx += len - 1; 17897 } 17898 } 17899 17900 static struct bpf_prog *bpf_patch_insn_data(struct bpf_verifier_env *env, u32 off, 17901 const struct bpf_insn *patch, u32 len) 17902 { 17903 struct bpf_prog *new_prog; 17904 struct bpf_insn_aux_data *new_data = NULL; 17905 17906 if (len > 1) { 17907 new_data = vzalloc(array_size(env->prog->len + len - 1, 17908 sizeof(struct bpf_insn_aux_data))); 17909 if (!new_data) 17910 return NULL; 17911 } 17912 17913 new_prog = bpf_patch_insn_single(env->prog, off, patch, len); 17914 if (IS_ERR(new_prog)) { 17915 if (PTR_ERR(new_prog) == -ERANGE) 17916 verbose(env, 17917 "insn %d cannot be patched due to 16-bit range\n", 17918 env->insn_aux_data[off].orig_idx); 17919 vfree(new_data); 17920 return NULL; 17921 } 17922 adjust_insn_aux_data(env, new_data, new_prog, off, len); 17923 adjust_subprog_starts(env, off, len); 17924 adjust_poke_descs(new_prog, off, len); 17925 return new_prog; 17926 } 17927 17928 static int adjust_subprog_starts_after_remove(struct bpf_verifier_env *env, 17929 u32 off, u32 cnt) 17930 { 17931 int i, j; 17932 17933 /* find first prog starting at or after off (first to remove) */ 17934 for (i = 0; i < env->subprog_cnt; i++) 17935 if (env->subprog_info[i].start >= off) 17936 break; 17937 /* find first prog starting at or after off + cnt (first to stay) */ 17938 for (j = i; j < env->subprog_cnt; j++) 17939 if (env->subprog_info[j].start >= off + cnt) 17940 break; 17941 /* if j doesn't start exactly at off + cnt, we are just removing 17942 * the front of previous prog 17943 */ 17944 if (env->subprog_info[j].start != off + cnt) 17945 j--; 17946 17947 if (j > i) { 17948 struct bpf_prog_aux *aux = env->prog->aux; 17949 int move; 17950 17951 /* move fake 'exit' subprog as well */ 17952 move = env->subprog_cnt + 1 - j; 17953 17954 memmove(env->subprog_info + i, 17955 env->subprog_info + j, 17956 sizeof(*env->subprog_info) * move); 17957 env->subprog_cnt -= j - i; 17958 17959 /* remove func_info */ 17960 if (aux->func_info) { 17961 move = aux->func_info_cnt - j; 17962 17963 memmove(aux->func_info + i, 17964 aux->func_info + j, 17965 sizeof(*aux->func_info) * move); 17966 aux->func_info_cnt -= j - i; 17967 /* func_info->insn_off is set after all code rewrites, 17968 * in adjust_btf_func() - no need to adjust 17969 */ 17970 } 17971 } else { 17972 /* convert i from "first prog to remove" to "first to adjust" */ 17973 if (env->subprog_info[i].start == off) 17974 i++; 17975 } 17976 17977 /* update fake 'exit' subprog as well */ 17978 for (; i <= env->subprog_cnt; i++) 17979 env->subprog_info[i].start -= cnt; 17980 17981 return 0; 17982 } 17983 17984 static int bpf_adj_linfo_after_remove(struct bpf_verifier_env *env, u32 off, 17985 u32 cnt) 17986 { 17987 struct bpf_prog *prog = env->prog; 17988 u32 i, l_off, l_cnt, nr_linfo; 17989 struct bpf_line_info *linfo; 17990 17991 nr_linfo = prog->aux->nr_linfo; 17992 if (!nr_linfo) 17993 return 0; 17994 17995 linfo = prog->aux->linfo; 17996 17997 /* find first line info to remove, count lines to be removed */ 17998 for (i = 0; i < nr_linfo; i++) 17999 if (linfo[i].insn_off >= off) 18000 break; 18001 18002 l_off = i; 18003 l_cnt = 0; 18004 for (; i < nr_linfo; i++) 18005 if (linfo[i].insn_off < off + cnt) 18006 l_cnt++; 18007 else 18008 break; 18009 18010 /* First live insn doesn't match first live linfo, it needs to "inherit" 18011 * last removed linfo. prog is already modified, so prog->len == off 18012 * means no live instructions after (tail of the program was removed). 18013 */ 18014 if (prog->len != off && l_cnt && 18015 (i == nr_linfo || linfo[i].insn_off != off + cnt)) { 18016 l_cnt--; 18017 linfo[--i].insn_off = off + cnt; 18018 } 18019 18020 /* remove the line info which refer to the removed instructions */ 18021 if (l_cnt) { 18022 memmove(linfo + l_off, linfo + i, 18023 sizeof(*linfo) * (nr_linfo - i)); 18024 18025 prog->aux->nr_linfo -= l_cnt; 18026 nr_linfo = prog->aux->nr_linfo; 18027 } 18028 18029 /* pull all linfo[i].insn_off >= off + cnt in by cnt */ 18030 for (i = l_off; i < nr_linfo; i++) 18031 linfo[i].insn_off -= cnt; 18032 18033 /* fix up all subprogs (incl. 'exit') which start >= off */ 18034 for (i = 0; i <= env->subprog_cnt; i++) 18035 if (env->subprog_info[i].linfo_idx > l_off) { 18036 /* program may have started in the removed region but 18037 * may not be fully removed 18038 */ 18039 if (env->subprog_info[i].linfo_idx >= l_off + l_cnt) 18040 env->subprog_info[i].linfo_idx -= l_cnt; 18041 else 18042 env->subprog_info[i].linfo_idx = l_off; 18043 } 18044 18045 return 0; 18046 } 18047 18048 static int verifier_remove_insns(struct bpf_verifier_env *env, u32 off, u32 cnt) 18049 { 18050 struct bpf_insn_aux_data *aux_data = env->insn_aux_data; 18051 unsigned int orig_prog_len = env->prog->len; 18052 int err; 18053 18054 if (bpf_prog_is_offloaded(env->prog->aux)) 18055 bpf_prog_offload_remove_insns(env, off, cnt); 18056 18057 err = bpf_remove_insns(env->prog, off, cnt); 18058 if (err) 18059 return err; 18060 18061 err = adjust_subprog_starts_after_remove(env, off, cnt); 18062 if (err) 18063 return err; 18064 18065 err = bpf_adj_linfo_after_remove(env, off, cnt); 18066 if (err) 18067 return err; 18068 18069 memmove(aux_data + off, aux_data + off + cnt, 18070 sizeof(*aux_data) * (orig_prog_len - off - cnt)); 18071 18072 return 0; 18073 } 18074 18075 /* The verifier does more data flow analysis than llvm and will not 18076 * explore branches that are dead at run time. Malicious programs can 18077 * have dead code too. Therefore replace all dead at-run-time code 18078 * with 'ja -1'. 18079 * 18080 * Just nops are not optimal, e.g. if they would sit at the end of the 18081 * program and through another bug we would manage to jump there, then 18082 * we'd execute beyond program memory otherwise. Returning exception 18083 * code also wouldn't work since we can have subprogs where the dead 18084 * code could be located. 18085 */ 18086 static void sanitize_dead_code(struct bpf_verifier_env *env) 18087 { 18088 struct bpf_insn_aux_data *aux_data = env->insn_aux_data; 18089 struct bpf_insn trap = BPF_JMP_IMM(BPF_JA, 0, 0, -1); 18090 struct bpf_insn *insn = env->prog->insnsi; 18091 const int insn_cnt = env->prog->len; 18092 int i; 18093 18094 for (i = 0; i < insn_cnt; i++) { 18095 if (aux_data[i].seen) 18096 continue; 18097 memcpy(insn + i, &trap, sizeof(trap)); 18098 aux_data[i].zext_dst = false; 18099 } 18100 } 18101 18102 static bool insn_is_cond_jump(u8 code) 18103 { 18104 u8 op; 18105 18106 op = BPF_OP(code); 18107 if (BPF_CLASS(code) == BPF_JMP32) 18108 return op != BPF_JA; 18109 18110 if (BPF_CLASS(code) != BPF_JMP) 18111 return false; 18112 18113 return op != BPF_JA && op != BPF_EXIT && op != BPF_CALL; 18114 } 18115 18116 static void opt_hard_wire_dead_code_branches(struct bpf_verifier_env *env) 18117 { 18118 struct bpf_insn_aux_data *aux_data = env->insn_aux_data; 18119 struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0); 18120 struct bpf_insn *insn = env->prog->insnsi; 18121 const int insn_cnt = env->prog->len; 18122 int i; 18123 18124 for (i = 0; i < insn_cnt; i++, insn++) { 18125 if (!insn_is_cond_jump(insn->code)) 18126 continue; 18127 18128 if (!aux_data[i + 1].seen) 18129 ja.off = insn->off; 18130 else if (!aux_data[i + 1 + insn->off].seen) 18131 ja.off = 0; 18132 else 18133 continue; 18134 18135 if (bpf_prog_is_offloaded(env->prog->aux)) 18136 bpf_prog_offload_replace_insn(env, i, &ja); 18137 18138 memcpy(insn, &ja, sizeof(ja)); 18139 } 18140 } 18141 18142 static int opt_remove_dead_code(struct bpf_verifier_env *env) 18143 { 18144 struct bpf_insn_aux_data *aux_data = env->insn_aux_data; 18145 int insn_cnt = env->prog->len; 18146 int i, err; 18147 18148 for (i = 0; i < insn_cnt; i++) { 18149 int j; 18150 18151 j = 0; 18152 while (i + j < insn_cnt && !aux_data[i + j].seen) 18153 j++; 18154 if (!j) 18155 continue; 18156 18157 err = verifier_remove_insns(env, i, j); 18158 if (err) 18159 return err; 18160 insn_cnt = env->prog->len; 18161 } 18162 18163 return 0; 18164 } 18165 18166 static int opt_remove_nops(struct bpf_verifier_env *env) 18167 { 18168 const struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0); 18169 struct bpf_insn *insn = env->prog->insnsi; 18170 int insn_cnt = env->prog->len; 18171 int i, err; 18172 18173 for (i = 0; i < insn_cnt; i++) { 18174 if (memcmp(&insn[i], &ja, sizeof(ja))) 18175 continue; 18176 18177 err = verifier_remove_insns(env, i, 1); 18178 if (err) 18179 return err; 18180 insn_cnt--; 18181 i--; 18182 } 18183 18184 return 0; 18185 } 18186 18187 static int opt_subreg_zext_lo32_rnd_hi32(struct bpf_verifier_env *env, 18188 const union bpf_attr *attr) 18189 { 18190 struct bpf_insn *patch, zext_patch[2], rnd_hi32_patch[4]; 18191 struct bpf_insn_aux_data *aux = env->insn_aux_data; 18192 int i, patch_len, delta = 0, len = env->prog->len; 18193 struct bpf_insn *insns = env->prog->insnsi; 18194 struct bpf_prog *new_prog; 18195 bool rnd_hi32; 18196 18197 rnd_hi32 = attr->prog_flags & BPF_F_TEST_RND_HI32; 18198 zext_patch[1] = BPF_ZEXT_REG(0); 18199 rnd_hi32_patch[1] = BPF_ALU64_IMM(BPF_MOV, BPF_REG_AX, 0); 18200 rnd_hi32_patch[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_AX, 32); 18201 rnd_hi32_patch[3] = BPF_ALU64_REG(BPF_OR, 0, BPF_REG_AX); 18202 for (i = 0; i < len; i++) { 18203 int adj_idx = i + delta; 18204 struct bpf_insn insn; 18205 int load_reg; 18206 18207 insn = insns[adj_idx]; 18208 load_reg = insn_def_regno(&insn); 18209 if (!aux[adj_idx].zext_dst) { 18210 u8 code, class; 18211 u32 imm_rnd; 18212 18213 if (!rnd_hi32) 18214 continue; 18215 18216 code = insn.code; 18217 class = BPF_CLASS(code); 18218 if (load_reg == -1) 18219 continue; 18220 18221 /* NOTE: arg "reg" (the fourth one) is only used for 18222 * BPF_STX + SRC_OP, so it is safe to pass NULL 18223 * here. 18224 */ 18225 if (is_reg64(env, &insn, load_reg, NULL, DST_OP)) { 18226 if (class == BPF_LD && 18227 BPF_MODE(code) == BPF_IMM) 18228 i++; 18229 continue; 18230 } 18231 18232 /* ctx load could be transformed into wider load. */ 18233 if (class == BPF_LDX && 18234 aux[adj_idx].ptr_type == PTR_TO_CTX) 18235 continue; 18236 18237 imm_rnd = get_random_u32(); 18238 rnd_hi32_patch[0] = insn; 18239 rnd_hi32_patch[1].imm = imm_rnd; 18240 rnd_hi32_patch[3].dst_reg = load_reg; 18241 patch = rnd_hi32_patch; 18242 patch_len = 4; 18243 goto apply_patch_buffer; 18244 } 18245 18246 /* Add in an zero-extend instruction if a) the JIT has requested 18247 * it or b) it's a CMPXCHG. 18248 * 18249 * The latter is because: BPF_CMPXCHG always loads a value into 18250 * R0, therefore always zero-extends. However some archs' 18251 * equivalent instruction only does this load when the 18252 * comparison is successful. This detail of CMPXCHG is 18253 * orthogonal to the general zero-extension behaviour of the 18254 * CPU, so it's treated independently of bpf_jit_needs_zext. 18255 */ 18256 if (!bpf_jit_needs_zext() && !is_cmpxchg_insn(&insn)) 18257 continue; 18258 18259 /* Zero-extension is done by the caller. */ 18260 if (bpf_pseudo_kfunc_call(&insn)) 18261 continue; 18262 18263 if (WARN_ON(load_reg == -1)) { 18264 verbose(env, "verifier bug. zext_dst is set, but no reg is defined\n"); 18265 return -EFAULT; 18266 } 18267 18268 zext_patch[0] = insn; 18269 zext_patch[1].dst_reg = load_reg; 18270 zext_patch[1].src_reg = load_reg; 18271 patch = zext_patch; 18272 patch_len = 2; 18273 apply_patch_buffer: 18274 new_prog = bpf_patch_insn_data(env, adj_idx, patch, patch_len); 18275 if (!new_prog) 18276 return -ENOMEM; 18277 env->prog = new_prog; 18278 insns = new_prog->insnsi; 18279 aux = env->insn_aux_data; 18280 delta += patch_len - 1; 18281 } 18282 18283 return 0; 18284 } 18285 18286 /* convert load instructions that access fields of a context type into a 18287 * sequence of instructions that access fields of the underlying structure: 18288 * struct __sk_buff -> struct sk_buff 18289 * struct bpf_sock_ops -> struct sock 18290 */ 18291 static int convert_ctx_accesses(struct bpf_verifier_env *env) 18292 { 18293 const struct bpf_verifier_ops *ops = env->ops; 18294 int i, cnt, size, ctx_field_size, delta = 0; 18295 const int insn_cnt = env->prog->len; 18296 struct bpf_insn insn_buf[16], *insn; 18297 u32 target_size, size_default, off; 18298 struct bpf_prog *new_prog; 18299 enum bpf_access_type type; 18300 bool is_narrower_load; 18301 18302 if (ops->gen_prologue || env->seen_direct_write) { 18303 if (!ops->gen_prologue) { 18304 verbose(env, "bpf verifier is misconfigured\n"); 18305 return -EINVAL; 18306 } 18307 cnt = ops->gen_prologue(insn_buf, env->seen_direct_write, 18308 env->prog); 18309 if (cnt >= ARRAY_SIZE(insn_buf)) { 18310 verbose(env, "bpf verifier is misconfigured\n"); 18311 return -EINVAL; 18312 } else if (cnt) { 18313 new_prog = bpf_patch_insn_data(env, 0, insn_buf, cnt); 18314 if (!new_prog) 18315 return -ENOMEM; 18316 18317 env->prog = new_prog; 18318 delta += cnt - 1; 18319 } 18320 } 18321 18322 if (bpf_prog_is_offloaded(env->prog->aux)) 18323 return 0; 18324 18325 insn = env->prog->insnsi + delta; 18326 18327 for (i = 0; i < insn_cnt; i++, insn++) { 18328 bpf_convert_ctx_access_t convert_ctx_access; 18329 u8 mode; 18330 18331 if (insn->code == (BPF_LDX | BPF_MEM | BPF_B) || 18332 insn->code == (BPF_LDX | BPF_MEM | BPF_H) || 18333 insn->code == (BPF_LDX | BPF_MEM | BPF_W) || 18334 insn->code == (BPF_LDX | BPF_MEM | BPF_DW) || 18335 insn->code == (BPF_LDX | BPF_MEMSX | BPF_B) || 18336 insn->code == (BPF_LDX | BPF_MEMSX | BPF_H) || 18337 insn->code == (BPF_LDX | BPF_MEMSX | BPF_W)) { 18338 type = BPF_READ; 18339 } else if (insn->code == (BPF_STX | BPF_MEM | BPF_B) || 18340 insn->code == (BPF_STX | BPF_MEM | BPF_H) || 18341 insn->code == (BPF_STX | BPF_MEM | BPF_W) || 18342 insn->code == (BPF_STX | BPF_MEM | BPF_DW) || 18343 insn->code == (BPF_ST | BPF_MEM | BPF_B) || 18344 insn->code == (BPF_ST | BPF_MEM | BPF_H) || 18345 insn->code == (BPF_ST | BPF_MEM | BPF_W) || 18346 insn->code == (BPF_ST | BPF_MEM | BPF_DW)) { 18347 type = BPF_WRITE; 18348 } else { 18349 continue; 18350 } 18351 18352 if (type == BPF_WRITE && 18353 env->insn_aux_data[i + delta].sanitize_stack_spill) { 18354 struct bpf_insn patch[] = { 18355 *insn, 18356 BPF_ST_NOSPEC(), 18357 }; 18358 18359 cnt = ARRAY_SIZE(patch); 18360 new_prog = bpf_patch_insn_data(env, i + delta, patch, cnt); 18361 if (!new_prog) 18362 return -ENOMEM; 18363 18364 delta += cnt - 1; 18365 env->prog = new_prog; 18366 insn = new_prog->insnsi + i + delta; 18367 continue; 18368 } 18369 18370 switch ((int)env->insn_aux_data[i + delta].ptr_type) { 18371 case PTR_TO_CTX: 18372 if (!ops->convert_ctx_access) 18373 continue; 18374 convert_ctx_access = ops->convert_ctx_access; 18375 break; 18376 case PTR_TO_SOCKET: 18377 case PTR_TO_SOCK_COMMON: 18378 convert_ctx_access = bpf_sock_convert_ctx_access; 18379 break; 18380 case PTR_TO_TCP_SOCK: 18381 convert_ctx_access = bpf_tcp_sock_convert_ctx_access; 18382 break; 18383 case PTR_TO_XDP_SOCK: 18384 convert_ctx_access = bpf_xdp_sock_convert_ctx_access; 18385 break; 18386 case PTR_TO_BTF_ID: 18387 case PTR_TO_BTF_ID | PTR_UNTRUSTED: 18388 /* PTR_TO_BTF_ID | MEM_ALLOC always has a valid lifetime, unlike 18389 * PTR_TO_BTF_ID, and an active ref_obj_id, but the same cannot 18390 * be said once it is marked PTR_UNTRUSTED, hence we must handle 18391 * any faults for loads into such types. BPF_WRITE is disallowed 18392 * for this case. 18393 */ 18394 case PTR_TO_BTF_ID | MEM_ALLOC | PTR_UNTRUSTED: 18395 if (type == BPF_READ) { 18396 if (BPF_MODE(insn->code) == BPF_MEM) 18397 insn->code = BPF_LDX | BPF_PROBE_MEM | 18398 BPF_SIZE((insn)->code); 18399 else 18400 insn->code = BPF_LDX | BPF_PROBE_MEMSX | 18401 BPF_SIZE((insn)->code); 18402 env->prog->aux->num_exentries++; 18403 } 18404 continue; 18405 default: 18406 continue; 18407 } 18408 18409 ctx_field_size = env->insn_aux_data[i + delta].ctx_field_size; 18410 size = BPF_LDST_BYTES(insn); 18411 mode = BPF_MODE(insn->code); 18412 18413 /* If the read access is a narrower load of the field, 18414 * convert to a 4/8-byte load, to minimum program type specific 18415 * convert_ctx_access changes. If conversion is successful, 18416 * we will apply proper mask to the result. 18417 */ 18418 is_narrower_load = size < ctx_field_size; 18419 size_default = bpf_ctx_off_adjust_machine(ctx_field_size); 18420 off = insn->off; 18421 if (is_narrower_load) { 18422 u8 size_code; 18423 18424 if (type == BPF_WRITE) { 18425 verbose(env, "bpf verifier narrow ctx access misconfigured\n"); 18426 return -EINVAL; 18427 } 18428 18429 size_code = BPF_H; 18430 if (ctx_field_size == 4) 18431 size_code = BPF_W; 18432 else if (ctx_field_size == 8) 18433 size_code = BPF_DW; 18434 18435 insn->off = off & ~(size_default - 1); 18436 insn->code = BPF_LDX | BPF_MEM | size_code; 18437 } 18438 18439 target_size = 0; 18440 cnt = convert_ctx_access(type, insn, insn_buf, env->prog, 18441 &target_size); 18442 if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf) || 18443 (ctx_field_size && !target_size)) { 18444 verbose(env, "bpf verifier is misconfigured\n"); 18445 return -EINVAL; 18446 } 18447 18448 if (is_narrower_load && size < target_size) { 18449 u8 shift = bpf_ctx_narrow_access_offset( 18450 off, size, size_default) * 8; 18451 if (shift && cnt + 1 >= ARRAY_SIZE(insn_buf)) { 18452 verbose(env, "bpf verifier narrow ctx load misconfigured\n"); 18453 return -EINVAL; 18454 } 18455 if (ctx_field_size <= 4) { 18456 if (shift) 18457 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_RSH, 18458 insn->dst_reg, 18459 shift); 18460 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg, 18461 (1 << size * 8) - 1); 18462 } else { 18463 if (shift) 18464 insn_buf[cnt++] = BPF_ALU64_IMM(BPF_RSH, 18465 insn->dst_reg, 18466 shift); 18467 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg, 18468 (1ULL << size * 8) - 1); 18469 } 18470 } 18471 if (mode == BPF_MEMSX) 18472 insn_buf[cnt++] = BPF_RAW_INSN(BPF_ALU64 | BPF_MOV | BPF_X, 18473 insn->dst_reg, insn->dst_reg, 18474 size * 8, 0); 18475 18476 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 18477 if (!new_prog) 18478 return -ENOMEM; 18479 18480 delta += cnt - 1; 18481 18482 /* keep walking new program and skip insns we just inserted */ 18483 env->prog = new_prog; 18484 insn = new_prog->insnsi + i + delta; 18485 } 18486 18487 return 0; 18488 } 18489 18490 static int jit_subprogs(struct bpf_verifier_env *env) 18491 { 18492 struct bpf_prog *prog = env->prog, **func, *tmp; 18493 int i, j, subprog_start, subprog_end = 0, len, subprog; 18494 struct bpf_map *map_ptr; 18495 struct bpf_insn *insn; 18496 void *old_bpf_func; 18497 int err, num_exentries; 18498 18499 if (env->subprog_cnt <= 1) 18500 return 0; 18501 18502 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) { 18503 if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn)) 18504 continue; 18505 18506 /* Upon error here we cannot fall back to interpreter but 18507 * need a hard reject of the program. Thus -EFAULT is 18508 * propagated in any case. 18509 */ 18510 subprog = find_subprog(env, i + insn->imm + 1); 18511 if (subprog < 0) { 18512 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n", 18513 i + insn->imm + 1); 18514 return -EFAULT; 18515 } 18516 /* temporarily remember subprog id inside insn instead of 18517 * aux_data, since next loop will split up all insns into funcs 18518 */ 18519 insn->off = subprog; 18520 /* remember original imm in case JIT fails and fallback 18521 * to interpreter will be needed 18522 */ 18523 env->insn_aux_data[i].call_imm = insn->imm; 18524 /* point imm to __bpf_call_base+1 from JITs point of view */ 18525 insn->imm = 1; 18526 if (bpf_pseudo_func(insn)) 18527 /* jit (e.g. x86_64) may emit fewer instructions 18528 * if it learns a u32 imm is the same as a u64 imm. 18529 * Force a non zero here. 18530 */ 18531 insn[1].imm = 1; 18532 } 18533 18534 err = bpf_prog_alloc_jited_linfo(prog); 18535 if (err) 18536 goto out_undo_insn; 18537 18538 err = -ENOMEM; 18539 func = kcalloc(env->subprog_cnt, sizeof(prog), GFP_KERNEL); 18540 if (!func) 18541 goto out_undo_insn; 18542 18543 for (i = 0; i < env->subprog_cnt; i++) { 18544 subprog_start = subprog_end; 18545 subprog_end = env->subprog_info[i + 1].start; 18546 18547 len = subprog_end - subprog_start; 18548 /* bpf_prog_run() doesn't call subprogs directly, 18549 * hence main prog stats include the runtime of subprogs. 18550 * subprogs don't have IDs and not reachable via prog_get_next_id 18551 * func[i]->stats will never be accessed and stays NULL 18552 */ 18553 func[i] = bpf_prog_alloc_no_stats(bpf_prog_size(len), GFP_USER); 18554 if (!func[i]) 18555 goto out_free; 18556 memcpy(func[i]->insnsi, &prog->insnsi[subprog_start], 18557 len * sizeof(struct bpf_insn)); 18558 func[i]->type = prog->type; 18559 func[i]->len = len; 18560 if (bpf_prog_calc_tag(func[i])) 18561 goto out_free; 18562 func[i]->is_func = 1; 18563 func[i]->aux->func_idx = i; 18564 /* Below members will be freed only at prog->aux */ 18565 func[i]->aux->btf = prog->aux->btf; 18566 func[i]->aux->func_info = prog->aux->func_info; 18567 func[i]->aux->func_info_cnt = prog->aux->func_info_cnt; 18568 func[i]->aux->poke_tab = prog->aux->poke_tab; 18569 func[i]->aux->size_poke_tab = prog->aux->size_poke_tab; 18570 18571 for (j = 0; j < prog->aux->size_poke_tab; j++) { 18572 struct bpf_jit_poke_descriptor *poke; 18573 18574 poke = &prog->aux->poke_tab[j]; 18575 if (poke->insn_idx < subprog_end && 18576 poke->insn_idx >= subprog_start) 18577 poke->aux = func[i]->aux; 18578 } 18579 18580 func[i]->aux->name[0] = 'F'; 18581 func[i]->aux->stack_depth = env->subprog_info[i].stack_depth; 18582 func[i]->jit_requested = 1; 18583 func[i]->blinding_requested = prog->blinding_requested; 18584 func[i]->aux->kfunc_tab = prog->aux->kfunc_tab; 18585 func[i]->aux->kfunc_btf_tab = prog->aux->kfunc_btf_tab; 18586 func[i]->aux->linfo = prog->aux->linfo; 18587 func[i]->aux->nr_linfo = prog->aux->nr_linfo; 18588 func[i]->aux->jited_linfo = prog->aux->jited_linfo; 18589 func[i]->aux->linfo_idx = env->subprog_info[i].linfo_idx; 18590 num_exentries = 0; 18591 insn = func[i]->insnsi; 18592 for (j = 0; j < func[i]->len; j++, insn++) { 18593 if (BPF_CLASS(insn->code) == BPF_LDX && 18594 (BPF_MODE(insn->code) == BPF_PROBE_MEM || 18595 BPF_MODE(insn->code) == BPF_PROBE_MEMSX)) 18596 num_exentries++; 18597 } 18598 func[i]->aux->num_exentries = num_exentries; 18599 func[i]->aux->tail_call_reachable = env->subprog_info[i].tail_call_reachable; 18600 func[i] = bpf_int_jit_compile(func[i]); 18601 if (!func[i]->jited) { 18602 err = -ENOTSUPP; 18603 goto out_free; 18604 } 18605 cond_resched(); 18606 } 18607 18608 /* at this point all bpf functions were successfully JITed 18609 * now populate all bpf_calls with correct addresses and 18610 * run last pass of JIT 18611 */ 18612 for (i = 0; i < env->subprog_cnt; i++) { 18613 insn = func[i]->insnsi; 18614 for (j = 0; j < func[i]->len; j++, insn++) { 18615 if (bpf_pseudo_func(insn)) { 18616 subprog = insn->off; 18617 insn[0].imm = (u32)(long)func[subprog]->bpf_func; 18618 insn[1].imm = ((u64)(long)func[subprog]->bpf_func) >> 32; 18619 continue; 18620 } 18621 if (!bpf_pseudo_call(insn)) 18622 continue; 18623 subprog = insn->off; 18624 insn->imm = BPF_CALL_IMM(func[subprog]->bpf_func); 18625 } 18626 18627 /* we use the aux data to keep a list of the start addresses 18628 * of the JITed images for each function in the program 18629 * 18630 * for some architectures, such as powerpc64, the imm field 18631 * might not be large enough to hold the offset of the start 18632 * address of the callee's JITed image from __bpf_call_base 18633 * 18634 * in such cases, we can lookup the start address of a callee 18635 * by using its subprog id, available from the off field of 18636 * the call instruction, as an index for this list 18637 */ 18638 func[i]->aux->func = func; 18639 func[i]->aux->func_cnt = env->subprog_cnt; 18640 } 18641 for (i = 0; i < env->subprog_cnt; i++) { 18642 old_bpf_func = func[i]->bpf_func; 18643 tmp = bpf_int_jit_compile(func[i]); 18644 if (tmp != func[i] || func[i]->bpf_func != old_bpf_func) { 18645 verbose(env, "JIT doesn't support bpf-to-bpf calls\n"); 18646 err = -ENOTSUPP; 18647 goto out_free; 18648 } 18649 cond_resched(); 18650 } 18651 18652 /* finally lock prog and jit images for all functions and 18653 * populate kallsysm. Begin at the first subprogram, since 18654 * bpf_prog_load will add the kallsyms for the main program. 18655 */ 18656 for (i = 1; i < env->subprog_cnt; i++) { 18657 bpf_prog_lock_ro(func[i]); 18658 bpf_prog_kallsyms_add(func[i]); 18659 } 18660 18661 /* Last step: make now unused interpreter insns from main 18662 * prog consistent for later dump requests, so they can 18663 * later look the same as if they were interpreted only. 18664 */ 18665 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) { 18666 if (bpf_pseudo_func(insn)) { 18667 insn[0].imm = env->insn_aux_data[i].call_imm; 18668 insn[1].imm = insn->off; 18669 insn->off = 0; 18670 continue; 18671 } 18672 if (!bpf_pseudo_call(insn)) 18673 continue; 18674 insn->off = env->insn_aux_data[i].call_imm; 18675 subprog = find_subprog(env, i + insn->off + 1); 18676 insn->imm = subprog; 18677 } 18678 18679 prog->jited = 1; 18680 prog->bpf_func = func[0]->bpf_func; 18681 prog->jited_len = func[0]->jited_len; 18682 prog->aux->extable = func[0]->aux->extable; 18683 prog->aux->num_exentries = func[0]->aux->num_exentries; 18684 prog->aux->func = func; 18685 prog->aux->func_cnt = env->subprog_cnt; 18686 bpf_prog_jit_attempt_done(prog); 18687 return 0; 18688 out_free: 18689 /* We failed JIT'ing, so at this point we need to unregister poke 18690 * descriptors from subprogs, so that kernel is not attempting to 18691 * patch it anymore as we're freeing the subprog JIT memory. 18692 */ 18693 for (i = 0; i < prog->aux->size_poke_tab; i++) { 18694 map_ptr = prog->aux->poke_tab[i].tail_call.map; 18695 map_ptr->ops->map_poke_untrack(map_ptr, prog->aux); 18696 } 18697 /* At this point we're guaranteed that poke descriptors are not 18698 * live anymore. We can just unlink its descriptor table as it's 18699 * released with the main prog. 18700 */ 18701 for (i = 0; i < env->subprog_cnt; i++) { 18702 if (!func[i]) 18703 continue; 18704 func[i]->aux->poke_tab = NULL; 18705 bpf_jit_free(func[i]); 18706 } 18707 kfree(func); 18708 out_undo_insn: 18709 /* cleanup main prog to be interpreted */ 18710 prog->jit_requested = 0; 18711 prog->blinding_requested = 0; 18712 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) { 18713 if (!bpf_pseudo_call(insn)) 18714 continue; 18715 insn->off = 0; 18716 insn->imm = env->insn_aux_data[i].call_imm; 18717 } 18718 bpf_prog_jit_attempt_done(prog); 18719 return err; 18720 } 18721 18722 static int fixup_call_args(struct bpf_verifier_env *env) 18723 { 18724 #ifndef CONFIG_BPF_JIT_ALWAYS_ON 18725 struct bpf_prog *prog = env->prog; 18726 struct bpf_insn *insn = prog->insnsi; 18727 bool has_kfunc_call = bpf_prog_has_kfunc_call(prog); 18728 int i, depth; 18729 #endif 18730 int err = 0; 18731 18732 if (env->prog->jit_requested && 18733 !bpf_prog_is_offloaded(env->prog->aux)) { 18734 err = jit_subprogs(env); 18735 if (err == 0) 18736 return 0; 18737 if (err == -EFAULT) 18738 return err; 18739 } 18740 #ifndef CONFIG_BPF_JIT_ALWAYS_ON 18741 if (has_kfunc_call) { 18742 verbose(env, "calling kernel functions are not allowed in non-JITed programs\n"); 18743 return -EINVAL; 18744 } 18745 if (env->subprog_cnt > 1 && env->prog->aux->tail_call_reachable) { 18746 /* When JIT fails the progs with bpf2bpf calls and tail_calls 18747 * have to be rejected, since interpreter doesn't support them yet. 18748 */ 18749 verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n"); 18750 return -EINVAL; 18751 } 18752 for (i = 0; i < prog->len; i++, insn++) { 18753 if (bpf_pseudo_func(insn)) { 18754 /* When JIT fails the progs with callback calls 18755 * have to be rejected, since interpreter doesn't support them yet. 18756 */ 18757 verbose(env, "callbacks are not allowed in non-JITed programs\n"); 18758 return -EINVAL; 18759 } 18760 18761 if (!bpf_pseudo_call(insn)) 18762 continue; 18763 depth = get_callee_stack_depth(env, insn, i); 18764 if (depth < 0) 18765 return depth; 18766 bpf_patch_call_args(insn, depth); 18767 } 18768 err = 0; 18769 #endif 18770 return err; 18771 } 18772 18773 /* replace a generic kfunc with a specialized version if necessary */ 18774 static void specialize_kfunc(struct bpf_verifier_env *env, 18775 u32 func_id, u16 offset, unsigned long *addr) 18776 { 18777 struct bpf_prog *prog = env->prog; 18778 bool seen_direct_write; 18779 void *xdp_kfunc; 18780 bool is_rdonly; 18781 18782 if (bpf_dev_bound_kfunc_id(func_id)) { 18783 xdp_kfunc = bpf_dev_bound_resolve_kfunc(prog, func_id); 18784 if (xdp_kfunc) { 18785 *addr = (unsigned long)xdp_kfunc; 18786 return; 18787 } 18788 /* fallback to default kfunc when not supported by netdev */ 18789 } 18790 18791 if (offset) 18792 return; 18793 18794 if (func_id == special_kfunc_list[KF_bpf_dynptr_from_skb]) { 18795 seen_direct_write = env->seen_direct_write; 18796 is_rdonly = !may_access_direct_pkt_data(env, NULL, BPF_WRITE); 18797 18798 if (is_rdonly) 18799 *addr = (unsigned long)bpf_dynptr_from_skb_rdonly; 18800 18801 /* restore env->seen_direct_write to its original value, since 18802 * may_access_direct_pkt_data mutates it 18803 */ 18804 env->seen_direct_write = seen_direct_write; 18805 } 18806 } 18807 18808 static void __fixup_collection_insert_kfunc(struct bpf_insn_aux_data *insn_aux, 18809 u16 struct_meta_reg, 18810 u16 node_offset_reg, 18811 struct bpf_insn *insn, 18812 struct bpf_insn *insn_buf, 18813 int *cnt) 18814 { 18815 struct btf_struct_meta *kptr_struct_meta = insn_aux->kptr_struct_meta; 18816 struct bpf_insn addr[2] = { BPF_LD_IMM64(struct_meta_reg, (long)kptr_struct_meta) }; 18817 18818 insn_buf[0] = addr[0]; 18819 insn_buf[1] = addr[1]; 18820 insn_buf[2] = BPF_MOV64_IMM(node_offset_reg, insn_aux->insert_off); 18821 insn_buf[3] = *insn; 18822 *cnt = 4; 18823 } 18824 18825 static int fixup_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn, 18826 struct bpf_insn *insn_buf, int insn_idx, int *cnt) 18827 { 18828 const struct bpf_kfunc_desc *desc; 18829 18830 if (!insn->imm) { 18831 verbose(env, "invalid kernel function call not eliminated in verifier pass\n"); 18832 return -EINVAL; 18833 } 18834 18835 *cnt = 0; 18836 18837 /* insn->imm has the btf func_id. Replace it with an offset relative to 18838 * __bpf_call_base, unless the JIT needs to call functions that are 18839 * further than 32 bits away (bpf_jit_supports_far_kfunc_call()). 18840 */ 18841 desc = find_kfunc_desc(env->prog, insn->imm, insn->off); 18842 if (!desc) { 18843 verbose(env, "verifier internal error: kernel function descriptor not found for func_id %u\n", 18844 insn->imm); 18845 return -EFAULT; 18846 } 18847 18848 if (!bpf_jit_supports_far_kfunc_call()) 18849 insn->imm = BPF_CALL_IMM(desc->addr); 18850 if (insn->off) 18851 return 0; 18852 if (desc->func_id == special_kfunc_list[KF_bpf_obj_new_impl]) { 18853 struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta; 18854 struct bpf_insn addr[2] = { BPF_LD_IMM64(BPF_REG_2, (long)kptr_struct_meta) }; 18855 u64 obj_new_size = env->insn_aux_data[insn_idx].obj_new_size; 18856 18857 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_1, obj_new_size); 18858 insn_buf[1] = addr[0]; 18859 insn_buf[2] = addr[1]; 18860 insn_buf[3] = *insn; 18861 *cnt = 4; 18862 } else if (desc->func_id == special_kfunc_list[KF_bpf_obj_drop_impl] || 18863 desc->func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl]) { 18864 struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta; 18865 struct bpf_insn addr[2] = { BPF_LD_IMM64(BPF_REG_2, (long)kptr_struct_meta) }; 18866 18867 if (desc->func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl] && 18868 !kptr_struct_meta) { 18869 verbose(env, "verifier internal error: kptr_struct_meta expected at insn_idx %d\n", 18870 insn_idx); 18871 return -EFAULT; 18872 } 18873 18874 insn_buf[0] = addr[0]; 18875 insn_buf[1] = addr[1]; 18876 insn_buf[2] = *insn; 18877 *cnt = 3; 18878 } else if (desc->func_id == special_kfunc_list[KF_bpf_list_push_back_impl] || 18879 desc->func_id == special_kfunc_list[KF_bpf_list_push_front_impl] || 18880 desc->func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) { 18881 struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta; 18882 int struct_meta_reg = BPF_REG_3; 18883 int node_offset_reg = BPF_REG_4; 18884 18885 /* rbtree_add has extra 'less' arg, so args-to-fixup are in diff regs */ 18886 if (desc->func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) { 18887 struct_meta_reg = BPF_REG_4; 18888 node_offset_reg = BPF_REG_5; 18889 } 18890 18891 if (!kptr_struct_meta) { 18892 verbose(env, "verifier internal error: kptr_struct_meta expected at insn_idx %d\n", 18893 insn_idx); 18894 return -EFAULT; 18895 } 18896 18897 __fixup_collection_insert_kfunc(&env->insn_aux_data[insn_idx], struct_meta_reg, 18898 node_offset_reg, insn, insn_buf, cnt); 18899 } else if (desc->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx] || 18900 desc->func_id == special_kfunc_list[KF_bpf_rdonly_cast]) { 18901 insn_buf[0] = BPF_MOV64_REG(BPF_REG_0, BPF_REG_1); 18902 *cnt = 1; 18903 } 18904 return 0; 18905 } 18906 18907 /* Do various post-verification rewrites in a single program pass. 18908 * These rewrites simplify JIT and interpreter implementations. 18909 */ 18910 static int do_misc_fixups(struct bpf_verifier_env *env) 18911 { 18912 struct bpf_prog *prog = env->prog; 18913 enum bpf_attach_type eatype = prog->expected_attach_type; 18914 enum bpf_prog_type prog_type = resolve_prog_type(prog); 18915 struct bpf_insn *insn = prog->insnsi; 18916 const struct bpf_func_proto *fn; 18917 const int insn_cnt = prog->len; 18918 const struct bpf_map_ops *ops; 18919 struct bpf_insn_aux_data *aux; 18920 struct bpf_insn insn_buf[16]; 18921 struct bpf_prog *new_prog; 18922 struct bpf_map *map_ptr; 18923 int i, ret, cnt, delta = 0; 18924 18925 for (i = 0; i < insn_cnt; i++, insn++) { 18926 /* Make divide-by-zero exceptions impossible. */ 18927 if (insn->code == (BPF_ALU64 | BPF_MOD | BPF_X) || 18928 insn->code == (BPF_ALU64 | BPF_DIV | BPF_X) || 18929 insn->code == (BPF_ALU | BPF_MOD | BPF_X) || 18930 insn->code == (BPF_ALU | BPF_DIV | BPF_X)) { 18931 bool is64 = BPF_CLASS(insn->code) == BPF_ALU64; 18932 bool isdiv = BPF_OP(insn->code) == BPF_DIV; 18933 struct bpf_insn *patchlet; 18934 struct bpf_insn chk_and_div[] = { 18935 /* [R,W]x div 0 -> 0 */ 18936 BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) | 18937 BPF_JNE | BPF_K, insn->src_reg, 18938 0, 2, 0), 18939 BPF_ALU32_REG(BPF_XOR, insn->dst_reg, insn->dst_reg), 18940 BPF_JMP_IMM(BPF_JA, 0, 0, 1), 18941 *insn, 18942 }; 18943 struct bpf_insn chk_and_mod[] = { 18944 /* [R,W]x mod 0 -> [R,W]x */ 18945 BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) | 18946 BPF_JEQ | BPF_K, insn->src_reg, 18947 0, 1 + (is64 ? 0 : 1), 0), 18948 *insn, 18949 BPF_JMP_IMM(BPF_JA, 0, 0, 1), 18950 BPF_MOV32_REG(insn->dst_reg, insn->dst_reg), 18951 }; 18952 18953 patchlet = isdiv ? chk_and_div : chk_and_mod; 18954 cnt = isdiv ? ARRAY_SIZE(chk_and_div) : 18955 ARRAY_SIZE(chk_and_mod) - (is64 ? 2 : 0); 18956 18957 new_prog = bpf_patch_insn_data(env, i + delta, patchlet, cnt); 18958 if (!new_prog) 18959 return -ENOMEM; 18960 18961 delta += cnt - 1; 18962 env->prog = prog = new_prog; 18963 insn = new_prog->insnsi + i + delta; 18964 continue; 18965 } 18966 18967 /* Implement LD_ABS and LD_IND with a rewrite, if supported by the program type. */ 18968 if (BPF_CLASS(insn->code) == BPF_LD && 18969 (BPF_MODE(insn->code) == BPF_ABS || 18970 BPF_MODE(insn->code) == BPF_IND)) { 18971 cnt = env->ops->gen_ld_abs(insn, insn_buf); 18972 if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf)) { 18973 verbose(env, "bpf verifier is misconfigured\n"); 18974 return -EINVAL; 18975 } 18976 18977 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 18978 if (!new_prog) 18979 return -ENOMEM; 18980 18981 delta += cnt - 1; 18982 env->prog = prog = new_prog; 18983 insn = new_prog->insnsi + i + delta; 18984 continue; 18985 } 18986 18987 /* Rewrite pointer arithmetic to mitigate speculation attacks. */ 18988 if (insn->code == (BPF_ALU64 | BPF_ADD | BPF_X) || 18989 insn->code == (BPF_ALU64 | BPF_SUB | BPF_X)) { 18990 const u8 code_add = BPF_ALU64 | BPF_ADD | BPF_X; 18991 const u8 code_sub = BPF_ALU64 | BPF_SUB | BPF_X; 18992 struct bpf_insn *patch = &insn_buf[0]; 18993 bool issrc, isneg, isimm; 18994 u32 off_reg; 18995 18996 aux = &env->insn_aux_data[i + delta]; 18997 if (!aux->alu_state || 18998 aux->alu_state == BPF_ALU_NON_POINTER) 18999 continue; 19000 19001 isneg = aux->alu_state & BPF_ALU_NEG_VALUE; 19002 issrc = (aux->alu_state & BPF_ALU_SANITIZE) == 19003 BPF_ALU_SANITIZE_SRC; 19004 isimm = aux->alu_state & BPF_ALU_IMMEDIATE; 19005 19006 off_reg = issrc ? insn->src_reg : insn->dst_reg; 19007 if (isimm) { 19008 *patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit); 19009 } else { 19010 if (isneg) 19011 *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1); 19012 *patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit); 19013 *patch++ = BPF_ALU64_REG(BPF_SUB, BPF_REG_AX, off_reg); 19014 *patch++ = BPF_ALU64_REG(BPF_OR, BPF_REG_AX, off_reg); 19015 *patch++ = BPF_ALU64_IMM(BPF_NEG, BPF_REG_AX, 0); 19016 *patch++ = BPF_ALU64_IMM(BPF_ARSH, BPF_REG_AX, 63); 19017 *patch++ = BPF_ALU64_REG(BPF_AND, BPF_REG_AX, off_reg); 19018 } 19019 if (!issrc) 19020 *patch++ = BPF_MOV64_REG(insn->dst_reg, insn->src_reg); 19021 insn->src_reg = BPF_REG_AX; 19022 if (isneg) 19023 insn->code = insn->code == code_add ? 19024 code_sub : code_add; 19025 *patch++ = *insn; 19026 if (issrc && isneg && !isimm) 19027 *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1); 19028 cnt = patch - insn_buf; 19029 19030 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 19031 if (!new_prog) 19032 return -ENOMEM; 19033 19034 delta += cnt - 1; 19035 env->prog = prog = new_prog; 19036 insn = new_prog->insnsi + i + delta; 19037 continue; 19038 } 19039 19040 if (insn->code != (BPF_JMP | BPF_CALL)) 19041 continue; 19042 if (insn->src_reg == BPF_PSEUDO_CALL) 19043 continue; 19044 if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) { 19045 ret = fixup_kfunc_call(env, insn, insn_buf, i + delta, &cnt); 19046 if (ret) 19047 return ret; 19048 if (cnt == 0) 19049 continue; 19050 19051 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 19052 if (!new_prog) 19053 return -ENOMEM; 19054 19055 delta += cnt - 1; 19056 env->prog = prog = new_prog; 19057 insn = new_prog->insnsi + i + delta; 19058 continue; 19059 } 19060 19061 if (insn->imm == BPF_FUNC_get_route_realm) 19062 prog->dst_needed = 1; 19063 if (insn->imm == BPF_FUNC_get_prandom_u32) 19064 bpf_user_rnd_init_once(); 19065 if (insn->imm == BPF_FUNC_override_return) 19066 prog->kprobe_override = 1; 19067 if (insn->imm == BPF_FUNC_tail_call) { 19068 /* If we tail call into other programs, we 19069 * cannot make any assumptions since they can 19070 * be replaced dynamically during runtime in 19071 * the program array. 19072 */ 19073 prog->cb_access = 1; 19074 if (!allow_tail_call_in_subprogs(env)) 19075 prog->aux->stack_depth = MAX_BPF_STACK; 19076 prog->aux->max_pkt_offset = MAX_PACKET_OFF; 19077 19078 /* mark bpf_tail_call as different opcode to avoid 19079 * conditional branch in the interpreter for every normal 19080 * call and to prevent accidental JITing by JIT compiler 19081 * that doesn't support bpf_tail_call yet 19082 */ 19083 insn->imm = 0; 19084 insn->code = BPF_JMP | BPF_TAIL_CALL; 19085 19086 aux = &env->insn_aux_data[i + delta]; 19087 if (env->bpf_capable && !prog->blinding_requested && 19088 prog->jit_requested && 19089 !bpf_map_key_poisoned(aux) && 19090 !bpf_map_ptr_poisoned(aux) && 19091 !bpf_map_ptr_unpriv(aux)) { 19092 struct bpf_jit_poke_descriptor desc = { 19093 .reason = BPF_POKE_REASON_TAIL_CALL, 19094 .tail_call.map = BPF_MAP_PTR(aux->map_ptr_state), 19095 .tail_call.key = bpf_map_key_immediate(aux), 19096 .insn_idx = i + delta, 19097 }; 19098 19099 ret = bpf_jit_add_poke_descriptor(prog, &desc); 19100 if (ret < 0) { 19101 verbose(env, "adding tail call poke descriptor failed\n"); 19102 return ret; 19103 } 19104 19105 insn->imm = ret + 1; 19106 continue; 19107 } 19108 19109 if (!bpf_map_ptr_unpriv(aux)) 19110 continue; 19111 19112 /* instead of changing every JIT dealing with tail_call 19113 * emit two extra insns: 19114 * if (index >= max_entries) goto out; 19115 * index &= array->index_mask; 19116 * to avoid out-of-bounds cpu speculation 19117 */ 19118 if (bpf_map_ptr_poisoned(aux)) { 19119 verbose(env, "tail_call abusing map_ptr\n"); 19120 return -EINVAL; 19121 } 19122 19123 map_ptr = BPF_MAP_PTR(aux->map_ptr_state); 19124 insn_buf[0] = BPF_JMP_IMM(BPF_JGE, BPF_REG_3, 19125 map_ptr->max_entries, 2); 19126 insn_buf[1] = BPF_ALU32_IMM(BPF_AND, BPF_REG_3, 19127 container_of(map_ptr, 19128 struct bpf_array, 19129 map)->index_mask); 19130 insn_buf[2] = *insn; 19131 cnt = 3; 19132 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 19133 if (!new_prog) 19134 return -ENOMEM; 19135 19136 delta += cnt - 1; 19137 env->prog = prog = new_prog; 19138 insn = new_prog->insnsi + i + delta; 19139 continue; 19140 } 19141 19142 if (insn->imm == BPF_FUNC_timer_set_callback) { 19143 /* The verifier will process callback_fn as many times as necessary 19144 * with different maps and the register states prepared by 19145 * set_timer_callback_state will be accurate. 19146 * 19147 * The following use case is valid: 19148 * map1 is shared by prog1, prog2, prog3. 19149 * prog1 calls bpf_timer_init for some map1 elements 19150 * prog2 calls bpf_timer_set_callback for some map1 elements. 19151 * Those that were not bpf_timer_init-ed will return -EINVAL. 19152 * prog3 calls bpf_timer_start for some map1 elements. 19153 * Those that were not both bpf_timer_init-ed and 19154 * bpf_timer_set_callback-ed will return -EINVAL. 19155 */ 19156 struct bpf_insn ld_addrs[2] = { 19157 BPF_LD_IMM64(BPF_REG_3, (long)prog->aux), 19158 }; 19159 19160 insn_buf[0] = ld_addrs[0]; 19161 insn_buf[1] = ld_addrs[1]; 19162 insn_buf[2] = *insn; 19163 cnt = 3; 19164 19165 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 19166 if (!new_prog) 19167 return -ENOMEM; 19168 19169 delta += cnt - 1; 19170 env->prog = prog = new_prog; 19171 insn = new_prog->insnsi + i + delta; 19172 goto patch_call_imm; 19173 } 19174 19175 if (is_storage_get_function(insn->imm)) { 19176 if (!env->prog->aux->sleepable || 19177 env->insn_aux_data[i + delta].storage_get_func_atomic) 19178 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_5, (__force __s32)GFP_ATOMIC); 19179 else 19180 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_5, (__force __s32)GFP_KERNEL); 19181 insn_buf[1] = *insn; 19182 cnt = 2; 19183 19184 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 19185 if (!new_prog) 19186 return -ENOMEM; 19187 19188 delta += cnt - 1; 19189 env->prog = prog = new_prog; 19190 insn = new_prog->insnsi + i + delta; 19191 goto patch_call_imm; 19192 } 19193 19194 /* BPF_EMIT_CALL() assumptions in some of the map_gen_lookup 19195 * and other inlining handlers are currently limited to 64 bit 19196 * only. 19197 */ 19198 if (prog->jit_requested && BITS_PER_LONG == 64 && 19199 (insn->imm == BPF_FUNC_map_lookup_elem || 19200 insn->imm == BPF_FUNC_map_update_elem || 19201 insn->imm == BPF_FUNC_map_delete_elem || 19202 insn->imm == BPF_FUNC_map_push_elem || 19203 insn->imm == BPF_FUNC_map_pop_elem || 19204 insn->imm == BPF_FUNC_map_peek_elem || 19205 insn->imm == BPF_FUNC_redirect_map || 19206 insn->imm == BPF_FUNC_for_each_map_elem || 19207 insn->imm == BPF_FUNC_map_lookup_percpu_elem)) { 19208 aux = &env->insn_aux_data[i + delta]; 19209 if (bpf_map_ptr_poisoned(aux)) 19210 goto patch_call_imm; 19211 19212 map_ptr = BPF_MAP_PTR(aux->map_ptr_state); 19213 ops = map_ptr->ops; 19214 if (insn->imm == BPF_FUNC_map_lookup_elem && 19215 ops->map_gen_lookup) { 19216 cnt = ops->map_gen_lookup(map_ptr, insn_buf); 19217 if (cnt == -EOPNOTSUPP) 19218 goto patch_map_ops_generic; 19219 if (cnt <= 0 || cnt >= ARRAY_SIZE(insn_buf)) { 19220 verbose(env, "bpf verifier is misconfigured\n"); 19221 return -EINVAL; 19222 } 19223 19224 new_prog = bpf_patch_insn_data(env, i + delta, 19225 insn_buf, cnt); 19226 if (!new_prog) 19227 return -ENOMEM; 19228 19229 delta += cnt - 1; 19230 env->prog = prog = new_prog; 19231 insn = new_prog->insnsi + i + delta; 19232 continue; 19233 } 19234 19235 BUILD_BUG_ON(!__same_type(ops->map_lookup_elem, 19236 (void *(*)(struct bpf_map *map, void *key))NULL)); 19237 BUILD_BUG_ON(!__same_type(ops->map_delete_elem, 19238 (long (*)(struct bpf_map *map, void *key))NULL)); 19239 BUILD_BUG_ON(!__same_type(ops->map_update_elem, 19240 (long (*)(struct bpf_map *map, void *key, void *value, 19241 u64 flags))NULL)); 19242 BUILD_BUG_ON(!__same_type(ops->map_push_elem, 19243 (long (*)(struct bpf_map *map, void *value, 19244 u64 flags))NULL)); 19245 BUILD_BUG_ON(!__same_type(ops->map_pop_elem, 19246 (long (*)(struct bpf_map *map, void *value))NULL)); 19247 BUILD_BUG_ON(!__same_type(ops->map_peek_elem, 19248 (long (*)(struct bpf_map *map, void *value))NULL)); 19249 BUILD_BUG_ON(!__same_type(ops->map_redirect, 19250 (long (*)(struct bpf_map *map, u64 index, u64 flags))NULL)); 19251 BUILD_BUG_ON(!__same_type(ops->map_for_each_callback, 19252 (long (*)(struct bpf_map *map, 19253 bpf_callback_t callback_fn, 19254 void *callback_ctx, 19255 u64 flags))NULL)); 19256 BUILD_BUG_ON(!__same_type(ops->map_lookup_percpu_elem, 19257 (void *(*)(struct bpf_map *map, void *key, u32 cpu))NULL)); 19258 19259 patch_map_ops_generic: 19260 switch (insn->imm) { 19261 case BPF_FUNC_map_lookup_elem: 19262 insn->imm = BPF_CALL_IMM(ops->map_lookup_elem); 19263 continue; 19264 case BPF_FUNC_map_update_elem: 19265 insn->imm = BPF_CALL_IMM(ops->map_update_elem); 19266 continue; 19267 case BPF_FUNC_map_delete_elem: 19268 insn->imm = BPF_CALL_IMM(ops->map_delete_elem); 19269 continue; 19270 case BPF_FUNC_map_push_elem: 19271 insn->imm = BPF_CALL_IMM(ops->map_push_elem); 19272 continue; 19273 case BPF_FUNC_map_pop_elem: 19274 insn->imm = BPF_CALL_IMM(ops->map_pop_elem); 19275 continue; 19276 case BPF_FUNC_map_peek_elem: 19277 insn->imm = BPF_CALL_IMM(ops->map_peek_elem); 19278 continue; 19279 case BPF_FUNC_redirect_map: 19280 insn->imm = BPF_CALL_IMM(ops->map_redirect); 19281 continue; 19282 case BPF_FUNC_for_each_map_elem: 19283 insn->imm = BPF_CALL_IMM(ops->map_for_each_callback); 19284 continue; 19285 case BPF_FUNC_map_lookup_percpu_elem: 19286 insn->imm = BPF_CALL_IMM(ops->map_lookup_percpu_elem); 19287 continue; 19288 } 19289 19290 goto patch_call_imm; 19291 } 19292 19293 /* Implement bpf_jiffies64 inline. */ 19294 if (prog->jit_requested && BITS_PER_LONG == 64 && 19295 insn->imm == BPF_FUNC_jiffies64) { 19296 struct bpf_insn ld_jiffies_addr[2] = { 19297 BPF_LD_IMM64(BPF_REG_0, 19298 (unsigned long)&jiffies), 19299 }; 19300 19301 insn_buf[0] = ld_jiffies_addr[0]; 19302 insn_buf[1] = ld_jiffies_addr[1]; 19303 insn_buf[2] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, 19304 BPF_REG_0, 0); 19305 cnt = 3; 19306 19307 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 19308 cnt); 19309 if (!new_prog) 19310 return -ENOMEM; 19311 19312 delta += cnt - 1; 19313 env->prog = prog = new_prog; 19314 insn = new_prog->insnsi + i + delta; 19315 continue; 19316 } 19317 19318 /* Implement bpf_get_func_arg inline. */ 19319 if (prog_type == BPF_PROG_TYPE_TRACING && 19320 insn->imm == BPF_FUNC_get_func_arg) { 19321 /* Load nr_args from ctx - 8 */ 19322 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8); 19323 insn_buf[1] = BPF_JMP32_REG(BPF_JGE, BPF_REG_2, BPF_REG_0, 6); 19324 insn_buf[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_2, 3); 19325 insn_buf[3] = BPF_ALU64_REG(BPF_ADD, BPF_REG_2, BPF_REG_1); 19326 insn_buf[4] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_2, 0); 19327 insn_buf[5] = BPF_STX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0); 19328 insn_buf[6] = BPF_MOV64_IMM(BPF_REG_0, 0); 19329 insn_buf[7] = BPF_JMP_A(1); 19330 insn_buf[8] = BPF_MOV64_IMM(BPF_REG_0, -EINVAL); 19331 cnt = 9; 19332 19333 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 19334 if (!new_prog) 19335 return -ENOMEM; 19336 19337 delta += cnt - 1; 19338 env->prog = prog = new_prog; 19339 insn = new_prog->insnsi + i + delta; 19340 continue; 19341 } 19342 19343 /* Implement bpf_get_func_ret inline. */ 19344 if (prog_type == BPF_PROG_TYPE_TRACING && 19345 insn->imm == BPF_FUNC_get_func_ret) { 19346 if (eatype == BPF_TRACE_FEXIT || 19347 eatype == BPF_MODIFY_RETURN) { 19348 /* Load nr_args from ctx - 8 */ 19349 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8); 19350 insn_buf[1] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_0, 3); 19351 insn_buf[2] = BPF_ALU64_REG(BPF_ADD, BPF_REG_0, BPF_REG_1); 19352 insn_buf[3] = BPF_LDX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0); 19353 insn_buf[4] = BPF_STX_MEM(BPF_DW, BPF_REG_2, BPF_REG_3, 0); 19354 insn_buf[5] = BPF_MOV64_IMM(BPF_REG_0, 0); 19355 cnt = 6; 19356 } else { 19357 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_0, -EOPNOTSUPP); 19358 cnt = 1; 19359 } 19360 19361 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 19362 if (!new_prog) 19363 return -ENOMEM; 19364 19365 delta += cnt - 1; 19366 env->prog = prog = new_prog; 19367 insn = new_prog->insnsi + i + delta; 19368 continue; 19369 } 19370 19371 /* Implement get_func_arg_cnt inline. */ 19372 if (prog_type == BPF_PROG_TYPE_TRACING && 19373 insn->imm == BPF_FUNC_get_func_arg_cnt) { 19374 /* Load nr_args from ctx - 8 */ 19375 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8); 19376 19377 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1); 19378 if (!new_prog) 19379 return -ENOMEM; 19380 19381 env->prog = prog = new_prog; 19382 insn = new_prog->insnsi + i + delta; 19383 continue; 19384 } 19385 19386 /* Implement bpf_get_func_ip inline. */ 19387 if (prog_type == BPF_PROG_TYPE_TRACING && 19388 insn->imm == BPF_FUNC_get_func_ip) { 19389 /* Load IP address from ctx - 16 */ 19390 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -16); 19391 19392 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1); 19393 if (!new_prog) 19394 return -ENOMEM; 19395 19396 env->prog = prog = new_prog; 19397 insn = new_prog->insnsi + i + delta; 19398 continue; 19399 } 19400 19401 patch_call_imm: 19402 fn = env->ops->get_func_proto(insn->imm, env->prog); 19403 /* all functions that have prototype and verifier allowed 19404 * programs to call them, must be real in-kernel functions 19405 */ 19406 if (!fn->func) { 19407 verbose(env, 19408 "kernel subsystem misconfigured func %s#%d\n", 19409 func_id_name(insn->imm), insn->imm); 19410 return -EFAULT; 19411 } 19412 insn->imm = fn->func - __bpf_call_base; 19413 } 19414 19415 /* Since poke tab is now finalized, publish aux to tracker. */ 19416 for (i = 0; i < prog->aux->size_poke_tab; i++) { 19417 map_ptr = prog->aux->poke_tab[i].tail_call.map; 19418 if (!map_ptr->ops->map_poke_track || 19419 !map_ptr->ops->map_poke_untrack || 19420 !map_ptr->ops->map_poke_run) { 19421 verbose(env, "bpf verifier is misconfigured\n"); 19422 return -EINVAL; 19423 } 19424 19425 ret = map_ptr->ops->map_poke_track(map_ptr, prog->aux); 19426 if (ret < 0) { 19427 verbose(env, "tracking tail call prog failed\n"); 19428 return ret; 19429 } 19430 } 19431 19432 sort_kfunc_descs_by_imm_off(env->prog); 19433 19434 return 0; 19435 } 19436 19437 static struct bpf_prog *inline_bpf_loop(struct bpf_verifier_env *env, 19438 int position, 19439 s32 stack_base, 19440 u32 callback_subprogno, 19441 u32 *cnt) 19442 { 19443 s32 r6_offset = stack_base + 0 * BPF_REG_SIZE; 19444 s32 r7_offset = stack_base + 1 * BPF_REG_SIZE; 19445 s32 r8_offset = stack_base + 2 * BPF_REG_SIZE; 19446 int reg_loop_max = BPF_REG_6; 19447 int reg_loop_cnt = BPF_REG_7; 19448 int reg_loop_ctx = BPF_REG_8; 19449 19450 struct bpf_prog *new_prog; 19451 u32 callback_start; 19452 u32 call_insn_offset; 19453 s32 callback_offset; 19454 19455 /* This represents an inlined version of bpf_iter.c:bpf_loop, 19456 * be careful to modify this code in sync. 19457 */ 19458 struct bpf_insn insn_buf[] = { 19459 /* Return error and jump to the end of the patch if 19460 * expected number of iterations is too big. 19461 */ 19462 BPF_JMP_IMM(BPF_JLE, BPF_REG_1, BPF_MAX_LOOPS, 2), 19463 BPF_MOV32_IMM(BPF_REG_0, -E2BIG), 19464 BPF_JMP_IMM(BPF_JA, 0, 0, 16), 19465 /* spill R6, R7, R8 to use these as loop vars */ 19466 BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_6, r6_offset), 19467 BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_7, r7_offset), 19468 BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_8, r8_offset), 19469 /* initialize loop vars */ 19470 BPF_MOV64_REG(reg_loop_max, BPF_REG_1), 19471 BPF_MOV32_IMM(reg_loop_cnt, 0), 19472 BPF_MOV64_REG(reg_loop_ctx, BPF_REG_3), 19473 /* loop header, 19474 * if reg_loop_cnt >= reg_loop_max skip the loop body 19475 */ 19476 BPF_JMP_REG(BPF_JGE, reg_loop_cnt, reg_loop_max, 5), 19477 /* callback call, 19478 * correct callback offset would be set after patching 19479 */ 19480 BPF_MOV64_REG(BPF_REG_1, reg_loop_cnt), 19481 BPF_MOV64_REG(BPF_REG_2, reg_loop_ctx), 19482 BPF_CALL_REL(0), 19483 /* increment loop counter */ 19484 BPF_ALU64_IMM(BPF_ADD, reg_loop_cnt, 1), 19485 /* jump to loop header if callback returned 0 */ 19486 BPF_JMP_IMM(BPF_JEQ, BPF_REG_0, 0, -6), 19487 /* return value of bpf_loop, 19488 * set R0 to the number of iterations 19489 */ 19490 BPF_MOV64_REG(BPF_REG_0, reg_loop_cnt), 19491 /* restore original values of R6, R7, R8 */ 19492 BPF_LDX_MEM(BPF_DW, BPF_REG_6, BPF_REG_10, r6_offset), 19493 BPF_LDX_MEM(BPF_DW, BPF_REG_7, BPF_REG_10, r7_offset), 19494 BPF_LDX_MEM(BPF_DW, BPF_REG_8, BPF_REG_10, r8_offset), 19495 }; 19496 19497 *cnt = ARRAY_SIZE(insn_buf); 19498 new_prog = bpf_patch_insn_data(env, position, insn_buf, *cnt); 19499 if (!new_prog) 19500 return new_prog; 19501 19502 /* callback start is known only after patching */ 19503 callback_start = env->subprog_info[callback_subprogno].start; 19504 /* Note: insn_buf[12] is an offset of BPF_CALL_REL instruction */ 19505 call_insn_offset = position + 12; 19506 callback_offset = callback_start - call_insn_offset - 1; 19507 new_prog->insnsi[call_insn_offset].imm = callback_offset; 19508 19509 return new_prog; 19510 } 19511 19512 static bool is_bpf_loop_call(struct bpf_insn *insn) 19513 { 19514 return insn->code == (BPF_JMP | BPF_CALL) && 19515 insn->src_reg == 0 && 19516 insn->imm == BPF_FUNC_loop; 19517 } 19518 19519 /* For all sub-programs in the program (including main) check 19520 * insn_aux_data to see if there are bpf_loop calls that require 19521 * inlining. If such calls are found the calls are replaced with a 19522 * sequence of instructions produced by `inline_bpf_loop` function and 19523 * subprog stack_depth is increased by the size of 3 registers. 19524 * This stack space is used to spill values of the R6, R7, R8. These 19525 * registers are used to store the loop bound, counter and context 19526 * variables. 19527 */ 19528 static int optimize_bpf_loop(struct bpf_verifier_env *env) 19529 { 19530 struct bpf_subprog_info *subprogs = env->subprog_info; 19531 int i, cur_subprog = 0, cnt, delta = 0; 19532 struct bpf_insn *insn = env->prog->insnsi; 19533 int insn_cnt = env->prog->len; 19534 u16 stack_depth = subprogs[cur_subprog].stack_depth; 19535 u16 stack_depth_roundup = round_up(stack_depth, 8) - stack_depth; 19536 u16 stack_depth_extra = 0; 19537 19538 for (i = 0; i < insn_cnt; i++, insn++) { 19539 struct bpf_loop_inline_state *inline_state = 19540 &env->insn_aux_data[i + delta].loop_inline_state; 19541 19542 if (is_bpf_loop_call(insn) && inline_state->fit_for_inline) { 19543 struct bpf_prog *new_prog; 19544 19545 stack_depth_extra = BPF_REG_SIZE * 3 + stack_depth_roundup; 19546 new_prog = inline_bpf_loop(env, 19547 i + delta, 19548 -(stack_depth + stack_depth_extra), 19549 inline_state->callback_subprogno, 19550 &cnt); 19551 if (!new_prog) 19552 return -ENOMEM; 19553 19554 delta += cnt - 1; 19555 env->prog = new_prog; 19556 insn = new_prog->insnsi + i + delta; 19557 } 19558 19559 if (subprogs[cur_subprog + 1].start == i + delta + 1) { 19560 subprogs[cur_subprog].stack_depth += stack_depth_extra; 19561 cur_subprog++; 19562 stack_depth = subprogs[cur_subprog].stack_depth; 19563 stack_depth_roundup = round_up(stack_depth, 8) - stack_depth; 19564 stack_depth_extra = 0; 19565 } 19566 } 19567 19568 env->prog->aux->stack_depth = env->subprog_info[0].stack_depth; 19569 19570 return 0; 19571 } 19572 19573 static void free_states(struct bpf_verifier_env *env) 19574 { 19575 struct bpf_verifier_state_list *sl, *sln; 19576 int i; 19577 19578 sl = env->free_list; 19579 while (sl) { 19580 sln = sl->next; 19581 free_verifier_state(&sl->state, false); 19582 kfree(sl); 19583 sl = sln; 19584 } 19585 env->free_list = NULL; 19586 19587 if (!env->explored_states) 19588 return; 19589 19590 for (i = 0; i < state_htab_size(env); i++) { 19591 sl = env->explored_states[i]; 19592 19593 while (sl) { 19594 sln = sl->next; 19595 free_verifier_state(&sl->state, false); 19596 kfree(sl); 19597 sl = sln; 19598 } 19599 env->explored_states[i] = NULL; 19600 } 19601 } 19602 19603 static int do_check_common(struct bpf_verifier_env *env, int subprog) 19604 { 19605 bool pop_log = !(env->log.level & BPF_LOG_LEVEL2); 19606 struct bpf_verifier_state *state; 19607 struct bpf_reg_state *regs; 19608 int ret, i; 19609 19610 env->prev_linfo = NULL; 19611 env->pass_cnt++; 19612 19613 state = kzalloc(sizeof(struct bpf_verifier_state), GFP_KERNEL); 19614 if (!state) 19615 return -ENOMEM; 19616 state->curframe = 0; 19617 state->speculative = false; 19618 state->branches = 1; 19619 state->frame[0] = kzalloc(sizeof(struct bpf_func_state), GFP_KERNEL); 19620 if (!state->frame[0]) { 19621 kfree(state); 19622 return -ENOMEM; 19623 } 19624 env->cur_state = state; 19625 init_func_state(env, state->frame[0], 19626 BPF_MAIN_FUNC /* callsite */, 19627 0 /* frameno */, 19628 subprog); 19629 state->first_insn_idx = env->subprog_info[subprog].start; 19630 state->last_insn_idx = -1; 19631 19632 regs = state->frame[state->curframe]->regs; 19633 if (subprog || env->prog->type == BPF_PROG_TYPE_EXT) { 19634 ret = btf_prepare_func_args(env, subprog, regs); 19635 if (ret) 19636 goto out; 19637 for (i = BPF_REG_1; i <= BPF_REG_5; i++) { 19638 if (regs[i].type == PTR_TO_CTX) 19639 mark_reg_known_zero(env, regs, i); 19640 else if (regs[i].type == SCALAR_VALUE) 19641 mark_reg_unknown(env, regs, i); 19642 else if (base_type(regs[i].type) == PTR_TO_MEM) { 19643 const u32 mem_size = regs[i].mem_size; 19644 19645 mark_reg_known_zero(env, regs, i); 19646 regs[i].mem_size = mem_size; 19647 regs[i].id = ++env->id_gen; 19648 } 19649 } 19650 } else { 19651 /* 1st arg to a function */ 19652 regs[BPF_REG_1].type = PTR_TO_CTX; 19653 mark_reg_known_zero(env, regs, BPF_REG_1); 19654 ret = btf_check_subprog_arg_match(env, subprog, regs); 19655 if (ret == -EFAULT) 19656 /* unlikely verifier bug. abort. 19657 * ret == 0 and ret < 0 are sadly acceptable for 19658 * main() function due to backward compatibility. 19659 * Like socket filter program may be written as: 19660 * int bpf_prog(struct pt_regs *ctx) 19661 * and never dereference that ctx in the program. 19662 * 'struct pt_regs' is a type mismatch for socket 19663 * filter that should be using 'struct __sk_buff'. 19664 */ 19665 goto out; 19666 } 19667 19668 ret = do_check(env); 19669 out: 19670 /* check for NULL is necessary, since cur_state can be freed inside 19671 * do_check() under memory pressure. 19672 */ 19673 if (env->cur_state) { 19674 free_verifier_state(env->cur_state, true); 19675 env->cur_state = NULL; 19676 } 19677 while (!pop_stack(env, NULL, NULL, false)); 19678 if (!ret && pop_log) 19679 bpf_vlog_reset(&env->log, 0); 19680 free_states(env); 19681 return ret; 19682 } 19683 19684 /* Verify all global functions in a BPF program one by one based on their BTF. 19685 * All global functions must pass verification. Otherwise the whole program is rejected. 19686 * Consider: 19687 * int bar(int); 19688 * int foo(int f) 19689 * { 19690 * return bar(f); 19691 * } 19692 * int bar(int b) 19693 * { 19694 * ... 19695 * } 19696 * foo() will be verified first for R1=any_scalar_value. During verification it 19697 * will be assumed that bar() already verified successfully and call to bar() 19698 * from foo() will be checked for type match only. Later bar() will be verified 19699 * independently to check that it's safe for R1=any_scalar_value. 19700 */ 19701 static int do_check_subprogs(struct bpf_verifier_env *env) 19702 { 19703 struct bpf_prog_aux *aux = env->prog->aux; 19704 int i, ret; 19705 19706 if (!aux->func_info) 19707 return 0; 19708 19709 for (i = 1; i < env->subprog_cnt; i++) { 19710 if (aux->func_info_aux[i].linkage != BTF_FUNC_GLOBAL) 19711 continue; 19712 env->insn_idx = env->subprog_info[i].start; 19713 WARN_ON_ONCE(env->insn_idx == 0); 19714 ret = do_check_common(env, i); 19715 if (ret) { 19716 return ret; 19717 } else if (env->log.level & BPF_LOG_LEVEL) { 19718 verbose(env, 19719 "Func#%d is safe for any args that match its prototype\n", 19720 i); 19721 } 19722 } 19723 return 0; 19724 } 19725 19726 static int do_check_main(struct bpf_verifier_env *env) 19727 { 19728 int ret; 19729 19730 env->insn_idx = 0; 19731 ret = do_check_common(env, 0); 19732 if (!ret) 19733 env->prog->aux->stack_depth = env->subprog_info[0].stack_depth; 19734 return ret; 19735 } 19736 19737 19738 static void print_verification_stats(struct bpf_verifier_env *env) 19739 { 19740 int i; 19741 19742 if (env->log.level & BPF_LOG_STATS) { 19743 verbose(env, "verification time %lld usec\n", 19744 div_u64(env->verification_time, 1000)); 19745 verbose(env, "stack depth "); 19746 for (i = 0; i < env->subprog_cnt; i++) { 19747 u32 depth = env->subprog_info[i].stack_depth; 19748 19749 verbose(env, "%d", depth); 19750 if (i + 1 < env->subprog_cnt) 19751 verbose(env, "+"); 19752 } 19753 verbose(env, "\n"); 19754 } 19755 verbose(env, "processed %d insns (limit %d) max_states_per_insn %d " 19756 "total_states %d peak_states %d mark_read %d\n", 19757 env->insn_processed, BPF_COMPLEXITY_LIMIT_INSNS, 19758 env->max_states_per_insn, env->total_states, 19759 env->peak_states, env->longest_mark_read_walk); 19760 } 19761 19762 static int check_struct_ops_btf_id(struct bpf_verifier_env *env) 19763 { 19764 const struct btf_type *t, *func_proto; 19765 const struct bpf_struct_ops *st_ops; 19766 const struct btf_member *member; 19767 struct bpf_prog *prog = env->prog; 19768 u32 btf_id, member_idx; 19769 const char *mname; 19770 19771 if (!prog->gpl_compatible) { 19772 verbose(env, "struct ops programs must have a GPL compatible license\n"); 19773 return -EINVAL; 19774 } 19775 19776 btf_id = prog->aux->attach_btf_id; 19777 st_ops = bpf_struct_ops_find(btf_id); 19778 if (!st_ops) { 19779 verbose(env, "attach_btf_id %u is not a supported struct\n", 19780 btf_id); 19781 return -ENOTSUPP; 19782 } 19783 19784 t = st_ops->type; 19785 member_idx = prog->expected_attach_type; 19786 if (member_idx >= btf_type_vlen(t)) { 19787 verbose(env, "attach to invalid member idx %u of struct %s\n", 19788 member_idx, st_ops->name); 19789 return -EINVAL; 19790 } 19791 19792 member = &btf_type_member(t)[member_idx]; 19793 mname = btf_name_by_offset(btf_vmlinux, member->name_off); 19794 func_proto = btf_type_resolve_func_ptr(btf_vmlinux, member->type, 19795 NULL); 19796 if (!func_proto) { 19797 verbose(env, "attach to invalid member %s(@idx %u) of struct %s\n", 19798 mname, member_idx, st_ops->name); 19799 return -EINVAL; 19800 } 19801 19802 if (st_ops->check_member) { 19803 int err = st_ops->check_member(t, member, prog); 19804 19805 if (err) { 19806 verbose(env, "attach to unsupported member %s of struct %s\n", 19807 mname, st_ops->name); 19808 return err; 19809 } 19810 } 19811 19812 prog->aux->attach_func_proto = func_proto; 19813 prog->aux->attach_func_name = mname; 19814 env->ops = st_ops->verifier_ops; 19815 19816 return 0; 19817 } 19818 #define SECURITY_PREFIX "security_" 19819 19820 static int check_attach_modify_return(unsigned long addr, const char *func_name) 19821 { 19822 if (within_error_injection_list(addr) || 19823 !strncmp(SECURITY_PREFIX, func_name, sizeof(SECURITY_PREFIX) - 1)) 19824 return 0; 19825 19826 return -EINVAL; 19827 } 19828 19829 /* list of non-sleepable functions that are otherwise on 19830 * ALLOW_ERROR_INJECTION list 19831 */ 19832 BTF_SET_START(btf_non_sleepable_error_inject) 19833 /* Three functions below can be called from sleepable and non-sleepable context. 19834 * Assume non-sleepable from bpf safety point of view. 19835 */ 19836 BTF_ID(func, __filemap_add_folio) 19837 BTF_ID(func, should_fail_alloc_page) 19838 BTF_ID(func, should_failslab) 19839 BTF_SET_END(btf_non_sleepable_error_inject) 19840 19841 static int check_non_sleepable_error_inject(u32 btf_id) 19842 { 19843 return btf_id_set_contains(&btf_non_sleepable_error_inject, btf_id); 19844 } 19845 19846 int bpf_check_attach_target(struct bpf_verifier_log *log, 19847 const struct bpf_prog *prog, 19848 const struct bpf_prog *tgt_prog, 19849 u32 btf_id, 19850 struct bpf_attach_target_info *tgt_info) 19851 { 19852 bool prog_extension = prog->type == BPF_PROG_TYPE_EXT; 19853 const char prefix[] = "btf_trace_"; 19854 int ret = 0, subprog = -1, i; 19855 const struct btf_type *t; 19856 bool conservative = true; 19857 const char *tname; 19858 struct btf *btf; 19859 long addr = 0; 19860 struct module *mod = NULL; 19861 19862 if (!btf_id) { 19863 bpf_log(log, "Tracing programs must provide btf_id\n"); 19864 return -EINVAL; 19865 } 19866 btf = tgt_prog ? tgt_prog->aux->btf : prog->aux->attach_btf; 19867 if (!btf) { 19868 bpf_log(log, 19869 "FENTRY/FEXIT program can only be attached to another program annotated with BTF\n"); 19870 return -EINVAL; 19871 } 19872 t = btf_type_by_id(btf, btf_id); 19873 if (!t) { 19874 bpf_log(log, "attach_btf_id %u is invalid\n", btf_id); 19875 return -EINVAL; 19876 } 19877 tname = btf_name_by_offset(btf, t->name_off); 19878 if (!tname) { 19879 bpf_log(log, "attach_btf_id %u doesn't have a name\n", btf_id); 19880 return -EINVAL; 19881 } 19882 if (tgt_prog) { 19883 struct bpf_prog_aux *aux = tgt_prog->aux; 19884 19885 if (bpf_prog_is_dev_bound(prog->aux) && 19886 !bpf_prog_dev_bound_match(prog, tgt_prog)) { 19887 bpf_log(log, "Target program bound device mismatch"); 19888 return -EINVAL; 19889 } 19890 19891 for (i = 0; i < aux->func_info_cnt; i++) 19892 if (aux->func_info[i].type_id == btf_id) { 19893 subprog = i; 19894 break; 19895 } 19896 if (subprog == -1) { 19897 bpf_log(log, "Subprog %s doesn't exist\n", tname); 19898 return -EINVAL; 19899 } 19900 conservative = aux->func_info_aux[subprog].unreliable; 19901 if (prog_extension) { 19902 if (conservative) { 19903 bpf_log(log, 19904 "Cannot replace static functions\n"); 19905 return -EINVAL; 19906 } 19907 if (!prog->jit_requested) { 19908 bpf_log(log, 19909 "Extension programs should be JITed\n"); 19910 return -EINVAL; 19911 } 19912 } 19913 if (!tgt_prog->jited) { 19914 bpf_log(log, "Can attach to only JITed progs\n"); 19915 return -EINVAL; 19916 } 19917 if (tgt_prog->type == prog->type) { 19918 /* Cannot fentry/fexit another fentry/fexit program. 19919 * Cannot attach program extension to another extension. 19920 * It's ok to attach fentry/fexit to extension program. 19921 */ 19922 bpf_log(log, "Cannot recursively attach\n"); 19923 return -EINVAL; 19924 } 19925 if (tgt_prog->type == BPF_PROG_TYPE_TRACING && 19926 prog_extension && 19927 (tgt_prog->expected_attach_type == BPF_TRACE_FENTRY || 19928 tgt_prog->expected_attach_type == BPF_TRACE_FEXIT)) { 19929 /* Program extensions can extend all program types 19930 * except fentry/fexit. The reason is the following. 19931 * The fentry/fexit programs are used for performance 19932 * analysis, stats and can be attached to any program 19933 * type except themselves. When extension program is 19934 * replacing XDP function it is necessary to allow 19935 * performance analysis of all functions. Both original 19936 * XDP program and its program extension. Hence 19937 * attaching fentry/fexit to BPF_PROG_TYPE_EXT is 19938 * allowed. If extending of fentry/fexit was allowed it 19939 * would be possible to create long call chain 19940 * fentry->extension->fentry->extension beyond 19941 * reasonable stack size. Hence extending fentry is not 19942 * allowed. 19943 */ 19944 bpf_log(log, "Cannot extend fentry/fexit\n"); 19945 return -EINVAL; 19946 } 19947 } else { 19948 if (prog_extension) { 19949 bpf_log(log, "Cannot replace kernel functions\n"); 19950 return -EINVAL; 19951 } 19952 } 19953 19954 switch (prog->expected_attach_type) { 19955 case BPF_TRACE_RAW_TP: 19956 if (tgt_prog) { 19957 bpf_log(log, 19958 "Only FENTRY/FEXIT progs are attachable to another BPF prog\n"); 19959 return -EINVAL; 19960 } 19961 if (!btf_type_is_typedef(t)) { 19962 bpf_log(log, "attach_btf_id %u is not a typedef\n", 19963 btf_id); 19964 return -EINVAL; 19965 } 19966 if (strncmp(prefix, tname, sizeof(prefix) - 1)) { 19967 bpf_log(log, "attach_btf_id %u points to wrong type name %s\n", 19968 btf_id, tname); 19969 return -EINVAL; 19970 } 19971 tname += sizeof(prefix) - 1; 19972 t = btf_type_by_id(btf, t->type); 19973 if (!btf_type_is_ptr(t)) 19974 /* should never happen in valid vmlinux build */ 19975 return -EINVAL; 19976 t = btf_type_by_id(btf, t->type); 19977 if (!btf_type_is_func_proto(t)) 19978 /* should never happen in valid vmlinux build */ 19979 return -EINVAL; 19980 19981 break; 19982 case BPF_TRACE_ITER: 19983 if (!btf_type_is_func(t)) { 19984 bpf_log(log, "attach_btf_id %u is not a function\n", 19985 btf_id); 19986 return -EINVAL; 19987 } 19988 t = btf_type_by_id(btf, t->type); 19989 if (!btf_type_is_func_proto(t)) 19990 return -EINVAL; 19991 ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel); 19992 if (ret) 19993 return ret; 19994 break; 19995 default: 19996 if (!prog_extension) 19997 return -EINVAL; 19998 fallthrough; 19999 case BPF_MODIFY_RETURN: 20000 case BPF_LSM_MAC: 20001 case BPF_LSM_CGROUP: 20002 case BPF_TRACE_FENTRY: 20003 case BPF_TRACE_FEXIT: 20004 if (!btf_type_is_func(t)) { 20005 bpf_log(log, "attach_btf_id %u is not a function\n", 20006 btf_id); 20007 return -EINVAL; 20008 } 20009 if (prog_extension && 20010 btf_check_type_match(log, prog, btf, t)) 20011 return -EINVAL; 20012 t = btf_type_by_id(btf, t->type); 20013 if (!btf_type_is_func_proto(t)) 20014 return -EINVAL; 20015 20016 if ((prog->aux->saved_dst_prog_type || prog->aux->saved_dst_attach_type) && 20017 (!tgt_prog || prog->aux->saved_dst_prog_type != tgt_prog->type || 20018 prog->aux->saved_dst_attach_type != tgt_prog->expected_attach_type)) 20019 return -EINVAL; 20020 20021 if (tgt_prog && conservative) 20022 t = NULL; 20023 20024 ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel); 20025 if (ret < 0) 20026 return ret; 20027 20028 if (tgt_prog) { 20029 if (subprog == 0) 20030 addr = (long) tgt_prog->bpf_func; 20031 else 20032 addr = (long) tgt_prog->aux->func[subprog]->bpf_func; 20033 } else { 20034 if (btf_is_module(btf)) { 20035 mod = btf_try_get_module(btf); 20036 if (mod) 20037 addr = find_kallsyms_symbol_value(mod, tname); 20038 else 20039 addr = 0; 20040 } else { 20041 addr = kallsyms_lookup_name(tname); 20042 } 20043 if (!addr) { 20044 module_put(mod); 20045 bpf_log(log, 20046 "The address of function %s cannot be found\n", 20047 tname); 20048 return -ENOENT; 20049 } 20050 } 20051 20052 if (prog->aux->sleepable) { 20053 ret = -EINVAL; 20054 switch (prog->type) { 20055 case BPF_PROG_TYPE_TRACING: 20056 20057 /* fentry/fexit/fmod_ret progs can be sleepable if they are 20058 * attached to ALLOW_ERROR_INJECTION and are not in denylist. 20059 */ 20060 if (!check_non_sleepable_error_inject(btf_id) && 20061 within_error_injection_list(addr)) 20062 ret = 0; 20063 /* fentry/fexit/fmod_ret progs can also be sleepable if they are 20064 * in the fmodret id set with the KF_SLEEPABLE flag. 20065 */ 20066 else { 20067 u32 *flags = btf_kfunc_is_modify_return(btf, btf_id, 20068 prog); 20069 20070 if (flags && (*flags & KF_SLEEPABLE)) 20071 ret = 0; 20072 } 20073 break; 20074 case BPF_PROG_TYPE_LSM: 20075 /* LSM progs check that they are attached to bpf_lsm_*() funcs. 20076 * Only some of them are sleepable. 20077 */ 20078 if (bpf_lsm_is_sleepable_hook(btf_id)) 20079 ret = 0; 20080 break; 20081 default: 20082 break; 20083 } 20084 if (ret) { 20085 module_put(mod); 20086 bpf_log(log, "%s is not sleepable\n", tname); 20087 return ret; 20088 } 20089 } else if (prog->expected_attach_type == BPF_MODIFY_RETURN) { 20090 if (tgt_prog) { 20091 module_put(mod); 20092 bpf_log(log, "can't modify return codes of BPF programs\n"); 20093 return -EINVAL; 20094 } 20095 ret = -EINVAL; 20096 if (btf_kfunc_is_modify_return(btf, btf_id, prog) || 20097 !check_attach_modify_return(addr, tname)) 20098 ret = 0; 20099 if (ret) { 20100 module_put(mod); 20101 bpf_log(log, "%s() is not modifiable\n", tname); 20102 return ret; 20103 } 20104 } 20105 20106 break; 20107 } 20108 tgt_info->tgt_addr = addr; 20109 tgt_info->tgt_name = tname; 20110 tgt_info->tgt_type = t; 20111 tgt_info->tgt_mod = mod; 20112 return 0; 20113 } 20114 20115 BTF_SET_START(btf_id_deny) 20116 BTF_ID_UNUSED 20117 #ifdef CONFIG_SMP 20118 BTF_ID(func, migrate_disable) 20119 BTF_ID(func, migrate_enable) 20120 #endif 20121 #if !defined CONFIG_PREEMPT_RCU && !defined CONFIG_TINY_RCU 20122 BTF_ID(func, rcu_read_unlock_strict) 20123 #endif 20124 #if defined(CONFIG_DEBUG_PREEMPT) || defined(CONFIG_TRACE_PREEMPT_TOGGLE) 20125 BTF_ID(func, preempt_count_add) 20126 BTF_ID(func, preempt_count_sub) 20127 #endif 20128 #ifdef CONFIG_PREEMPT_RCU 20129 BTF_ID(func, __rcu_read_lock) 20130 BTF_ID(func, __rcu_read_unlock) 20131 #endif 20132 BTF_SET_END(btf_id_deny) 20133 20134 static bool can_be_sleepable(struct bpf_prog *prog) 20135 { 20136 if (prog->type == BPF_PROG_TYPE_TRACING) { 20137 switch (prog->expected_attach_type) { 20138 case BPF_TRACE_FENTRY: 20139 case BPF_TRACE_FEXIT: 20140 case BPF_MODIFY_RETURN: 20141 case BPF_TRACE_ITER: 20142 return true; 20143 default: 20144 return false; 20145 } 20146 } 20147 return prog->type == BPF_PROG_TYPE_LSM || 20148 prog->type == BPF_PROG_TYPE_KPROBE /* only for uprobes */ || 20149 prog->type == BPF_PROG_TYPE_STRUCT_OPS; 20150 } 20151 20152 static int check_attach_btf_id(struct bpf_verifier_env *env) 20153 { 20154 struct bpf_prog *prog = env->prog; 20155 struct bpf_prog *tgt_prog = prog->aux->dst_prog; 20156 struct bpf_attach_target_info tgt_info = {}; 20157 u32 btf_id = prog->aux->attach_btf_id; 20158 struct bpf_trampoline *tr; 20159 int ret; 20160 u64 key; 20161 20162 if (prog->type == BPF_PROG_TYPE_SYSCALL) { 20163 if (prog->aux->sleepable) 20164 /* attach_btf_id checked to be zero already */ 20165 return 0; 20166 verbose(env, "Syscall programs can only be sleepable\n"); 20167 return -EINVAL; 20168 } 20169 20170 if (prog->aux->sleepable && !can_be_sleepable(prog)) { 20171 verbose(env, "Only fentry/fexit/fmod_ret, lsm, iter, uprobe, and struct_ops programs can be sleepable\n"); 20172 return -EINVAL; 20173 } 20174 20175 if (prog->type == BPF_PROG_TYPE_STRUCT_OPS) 20176 return check_struct_ops_btf_id(env); 20177 20178 if (prog->type != BPF_PROG_TYPE_TRACING && 20179 prog->type != BPF_PROG_TYPE_LSM && 20180 prog->type != BPF_PROG_TYPE_EXT) 20181 return 0; 20182 20183 ret = bpf_check_attach_target(&env->log, prog, tgt_prog, btf_id, &tgt_info); 20184 if (ret) 20185 return ret; 20186 20187 if (tgt_prog && prog->type == BPF_PROG_TYPE_EXT) { 20188 /* to make freplace equivalent to their targets, they need to 20189 * inherit env->ops and expected_attach_type for the rest of the 20190 * verification 20191 */ 20192 env->ops = bpf_verifier_ops[tgt_prog->type]; 20193 prog->expected_attach_type = tgt_prog->expected_attach_type; 20194 } 20195 20196 /* store info about the attachment target that will be used later */ 20197 prog->aux->attach_func_proto = tgt_info.tgt_type; 20198 prog->aux->attach_func_name = tgt_info.tgt_name; 20199 prog->aux->mod = tgt_info.tgt_mod; 20200 20201 if (tgt_prog) { 20202 prog->aux->saved_dst_prog_type = tgt_prog->type; 20203 prog->aux->saved_dst_attach_type = tgt_prog->expected_attach_type; 20204 } 20205 20206 if (prog->expected_attach_type == BPF_TRACE_RAW_TP) { 20207 prog->aux->attach_btf_trace = true; 20208 return 0; 20209 } else if (prog->expected_attach_type == BPF_TRACE_ITER) { 20210 if (!bpf_iter_prog_supported(prog)) 20211 return -EINVAL; 20212 return 0; 20213 } 20214 20215 if (prog->type == BPF_PROG_TYPE_LSM) { 20216 ret = bpf_lsm_verify_prog(&env->log, prog); 20217 if (ret < 0) 20218 return ret; 20219 } else if (prog->type == BPF_PROG_TYPE_TRACING && 20220 btf_id_set_contains(&btf_id_deny, btf_id)) { 20221 return -EINVAL; 20222 } 20223 20224 key = bpf_trampoline_compute_key(tgt_prog, prog->aux->attach_btf, btf_id); 20225 tr = bpf_trampoline_get(key, &tgt_info); 20226 if (!tr) 20227 return -ENOMEM; 20228 20229 if (tgt_prog && tgt_prog->aux->tail_call_reachable) 20230 tr->flags = BPF_TRAMP_F_TAIL_CALL_CTX; 20231 20232 prog->aux->dst_trampoline = tr; 20233 return 0; 20234 } 20235 20236 struct btf *bpf_get_btf_vmlinux(void) 20237 { 20238 if (!btf_vmlinux && IS_ENABLED(CONFIG_DEBUG_INFO_BTF)) { 20239 mutex_lock(&bpf_verifier_lock); 20240 if (!btf_vmlinux) 20241 btf_vmlinux = btf_parse_vmlinux(); 20242 mutex_unlock(&bpf_verifier_lock); 20243 } 20244 return btf_vmlinux; 20245 } 20246 20247 int bpf_check(struct bpf_prog **prog, union bpf_attr *attr, bpfptr_t uattr, __u32 uattr_size) 20248 { 20249 u64 start_time = ktime_get_ns(); 20250 struct bpf_verifier_env *env; 20251 int i, len, ret = -EINVAL, err; 20252 u32 log_true_size; 20253 bool is_priv; 20254 20255 /* no program is valid */ 20256 if (ARRAY_SIZE(bpf_verifier_ops) == 0) 20257 return -EINVAL; 20258 20259 /* 'struct bpf_verifier_env' can be global, but since it's not small, 20260 * allocate/free it every time bpf_check() is called 20261 */ 20262 env = kvzalloc(sizeof(struct bpf_verifier_env), GFP_KERNEL); 20263 if (!env) 20264 return -ENOMEM; 20265 20266 env->bt.env = env; 20267 20268 len = (*prog)->len; 20269 env->insn_aux_data = 20270 vzalloc(array_size(sizeof(struct bpf_insn_aux_data), len)); 20271 ret = -ENOMEM; 20272 if (!env->insn_aux_data) 20273 goto err_free_env; 20274 for (i = 0; i < len; i++) 20275 env->insn_aux_data[i].orig_idx = i; 20276 env->prog = *prog; 20277 env->ops = bpf_verifier_ops[env->prog->type]; 20278 env->fd_array = make_bpfptr(attr->fd_array, uattr.is_kernel); 20279 is_priv = bpf_capable(); 20280 20281 bpf_get_btf_vmlinux(); 20282 20283 /* grab the mutex to protect few globals used by verifier */ 20284 if (!is_priv) 20285 mutex_lock(&bpf_verifier_lock); 20286 20287 /* user could have requested verbose verifier output 20288 * and supplied buffer to store the verification trace 20289 */ 20290 ret = bpf_vlog_init(&env->log, attr->log_level, 20291 (char __user *) (unsigned long) attr->log_buf, 20292 attr->log_size); 20293 if (ret) 20294 goto err_unlock; 20295 20296 mark_verifier_state_clean(env); 20297 20298 if (IS_ERR(btf_vmlinux)) { 20299 /* Either gcc or pahole or kernel are broken. */ 20300 verbose(env, "in-kernel BTF is malformed\n"); 20301 ret = PTR_ERR(btf_vmlinux); 20302 goto skip_full_check; 20303 } 20304 20305 env->strict_alignment = !!(attr->prog_flags & BPF_F_STRICT_ALIGNMENT); 20306 if (!IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS)) 20307 env->strict_alignment = true; 20308 if (attr->prog_flags & BPF_F_ANY_ALIGNMENT) 20309 env->strict_alignment = false; 20310 20311 env->allow_ptr_leaks = bpf_allow_ptr_leaks(); 20312 env->allow_uninit_stack = bpf_allow_uninit_stack(); 20313 env->bypass_spec_v1 = bpf_bypass_spec_v1(); 20314 env->bypass_spec_v4 = bpf_bypass_spec_v4(); 20315 env->bpf_capable = bpf_capable(); 20316 20317 if (is_priv) 20318 env->test_state_freq = attr->prog_flags & BPF_F_TEST_STATE_FREQ; 20319 20320 env->explored_states = kvcalloc(state_htab_size(env), 20321 sizeof(struct bpf_verifier_state_list *), 20322 GFP_USER); 20323 ret = -ENOMEM; 20324 if (!env->explored_states) 20325 goto skip_full_check; 20326 20327 ret = add_subprog_and_kfunc(env); 20328 if (ret < 0) 20329 goto skip_full_check; 20330 20331 ret = check_subprogs(env); 20332 if (ret < 0) 20333 goto skip_full_check; 20334 20335 ret = check_btf_info(env, attr, uattr); 20336 if (ret < 0) 20337 goto skip_full_check; 20338 20339 ret = check_attach_btf_id(env); 20340 if (ret) 20341 goto skip_full_check; 20342 20343 ret = resolve_pseudo_ldimm64(env); 20344 if (ret < 0) 20345 goto skip_full_check; 20346 20347 if (bpf_prog_is_offloaded(env->prog->aux)) { 20348 ret = bpf_prog_offload_verifier_prep(env->prog); 20349 if (ret) 20350 goto skip_full_check; 20351 } 20352 20353 ret = check_cfg(env); 20354 if (ret < 0) 20355 goto skip_full_check; 20356 20357 ret = do_check_subprogs(env); 20358 ret = ret ?: do_check_main(env); 20359 20360 if (ret == 0 && bpf_prog_is_offloaded(env->prog->aux)) 20361 ret = bpf_prog_offload_finalize(env); 20362 20363 skip_full_check: 20364 kvfree(env->explored_states); 20365 20366 if (ret == 0) 20367 ret = check_max_stack_depth(env); 20368 20369 /* instruction rewrites happen after this point */ 20370 if (ret == 0) 20371 ret = optimize_bpf_loop(env); 20372 20373 if (is_priv) { 20374 if (ret == 0) 20375 opt_hard_wire_dead_code_branches(env); 20376 if (ret == 0) 20377 ret = opt_remove_dead_code(env); 20378 if (ret == 0) 20379 ret = opt_remove_nops(env); 20380 } else { 20381 if (ret == 0) 20382 sanitize_dead_code(env); 20383 } 20384 20385 if (ret == 0) 20386 /* program is valid, convert *(u32*)(ctx + off) accesses */ 20387 ret = convert_ctx_accesses(env); 20388 20389 if (ret == 0) 20390 ret = do_misc_fixups(env); 20391 20392 /* do 32-bit optimization after insn patching has done so those patched 20393 * insns could be handled correctly. 20394 */ 20395 if (ret == 0 && !bpf_prog_is_offloaded(env->prog->aux)) { 20396 ret = opt_subreg_zext_lo32_rnd_hi32(env, attr); 20397 env->prog->aux->verifier_zext = bpf_jit_needs_zext() ? !ret 20398 : false; 20399 } 20400 20401 if (ret == 0) 20402 ret = fixup_call_args(env); 20403 20404 env->verification_time = ktime_get_ns() - start_time; 20405 print_verification_stats(env); 20406 env->prog->aux->verified_insns = env->insn_processed; 20407 20408 /* preserve original error even if log finalization is successful */ 20409 err = bpf_vlog_finalize(&env->log, &log_true_size); 20410 if (err) 20411 ret = err; 20412 20413 if (uattr_size >= offsetofend(union bpf_attr, log_true_size) && 20414 copy_to_bpfptr_offset(uattr, offsetof(union bpf_attr, log_true_size), 20415 &log_true_size, sizeof(log_true_size))) { 20416 ret = -EFAULT; 20417 goto err_release_maps; 20418 } 20419 20420 if (ret) 20421 goto err_release_maps; 20422 20423 if (env->used_map_cnt) { 20424 /* if program passed verifier, update used_maps in bpf_prog_info */ 20425 env->prog->aux->used_maps = kmalloc_array(env->used_map_cnt, 20426 sizeof(env->used_maps[0]), 20427 GFP_KERNEL); 20428 20429 if (!env->prog->aux->used_maps) { 20430 ret = -ENOMEM; 20431 goto err_release_maps; 20432 } 20433 20434 memcpy(env->prog->aux->used_maps, env->used_maps, 20435 sizeof(env->used_maps[0]) * env->used_map_cnt); 20436 env->prog->aux->used_map_cnt = env->used_map_cnt; 20437 } 20438 if (env->used_btf_cnt) { 20439 /* if program passed verifier, update used_btfs in bpf_prog_aux */ 20440 env->prog->aux->used_btfs = kmalloc_array(env->used_btf_cnt, 20441 sizeof(env->used_btfs[0]), 20442 GFP_KERNEL); 20443 if (!env->prog->aux->used_btfs) { 20444 ret = -ENOMEM; 20445 goto err_release_maps; 20446 } 20447 20448 memcpy(env->prog->aux->used_btfs, env->used_btfs, 20449 sizeof(env->used_btfs[0]) * env->used_btf_cnt); 20450 env->prog->aux->used_btf_cnt = env->used_btf_cnt; 20451 } 20452 if (env->used_map_cnt || env->used_btf_cnt) { 20453 /* program is valid. Convert pseudo bpf_ld_imm64 into generic 20454 * bpf_ld_imm64 instructions 20455 */ 20456 convert_pseudo_ld_imm64(env); 20457 } 20458 20459 adjust_btf_func(env); 20460 20461 err_release_maps: 20462 if (!env->prog->aux->used_maps) 20463 /* if we didn't copy map pointers into bpf_prog_info, release 20464 * them now. Otherwise free_used_maps() will release them. 20465 */ 20466 release_maps(env); 20467 if (!env->prog->aux->used_btfs) 20468 release_btfs(env); 20469 20470 /* extension progs temporarily inherit the attach_type of their targets 20471 for verification purposes, so set it back to zero before returning 20472 */ 20473 if (env->prog->type == BPF_PROG_TYPE_EXT) 20474 env->prog->expected_attach_type = 0; 20475 20476 *prog = env->prog; 20477 err_unlock: 20478 if (!is_priv) 20479 mutex_unlock(&bpf_verifier_lock); 20480 vfree(env->insn_aux_data); 20481 err_free_env: 20482 kvfree(env); 20483 return ret; 20484 } 20485