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 <linux/bpf_mem_alloc.h> 30 #include <net/xdp.h> 31 32 #include "disasm.h" 33 34 static const struct bpf_verifier_ops * const bpf_verifier_ops[] = { 35 #define BPF_PROG_TYPE(_id, _name, prog_ctx_type, kern_ctx_type) \ 36 [_id] = & _name ## _verifier_ops, 37 #define BPF_MAP_TYPE(_id, _ops) 38 #define BPF_LINK_TYPE(_id, _name) 39 #include <linux/bpf_types.h> 40 #undef BPF_PROG_TYPE 41 #undef BPF_MAP_TYPE 42 #undef BPF_LINK_TYPE 43 }; 44 45 struct bpf_mem_alloc bpf_global_percpu_ma; 46 static bool bpf_global_percpu_ma_set; 47 48 /* bpf_check() is a static code analyzer that walks eBPF program 49 * instruction by instruction and updates register/stack state. 50 * All paths of conditional branches are analyzed until 'bpf_exit' insn. 51 * 52 * The first pass is depth-first-search to check that the program is a DAG. 53 * It rejects the following programs: 54 * - larger than BPF_MAXINSNS insns 55 * - if loop is present (detected via back-edge) 56 * - unreachable insns exist (shouldn't be a forest. program = one function) 57 * - out of bounds or malformed jumps 58 * The second pass is all possible path descent from the 1st insn. 59 * Since it's analyzing all paths through the program, the length of the 60 * analysis is limited to 64k insn, which may be hit even if total number of 61 * insn is less then 4K, but there are too many branches that change stack/regs. 62 * Number of 'branches to be analyzed' is limited to 1k 63 * 64 * On entry to each instruction, each register has a type, and the instruction 65 * changes the types of the registers depending on instruction semantics. 66 * If instruction is BPF_MOV64_REG(BPF_REG_1, BPF_REG_5), then type of R5 is 67 * copied to R1. 68 * 69 * All registers are 64-bit. 70 * R0 - return register 71 * R1-R5 argument passing registers 72 * R6-R9 callee saved registers 73 * R10 - frame pointer read-only 74 * 75 * At the start of BPF program the register R1 contains a pointer to bpf_context 76 * and has type PTR_TO_CTX. 77 * 78 * Verifier tracks arithmetic operations on pointers in case: 79 * BPF_MOV64_REG(BPF_REG_1, BPF_REG_10), 80 * BPF_ALU64_IMM(BPF_ADD, BPF_REG_1, -20), 81 * 1st insn copies R10 (which has FRAME_PTR) type into R1 82 * and 2nd arithmetic instruction is pattern matched to recognize 83 * that it wants to construct a pointer to some element within stack. 84 * So after 2nd insn, the register R1 has type PTR_TO_STACK 85 * (and -20 constant is saved for further stack bounds checking). 86 * Meaning that this reg is a pointer to stack plus known immediate constant. 87 * 88 * Most of the time the registers have SCALAR_VALUE type, which 89 * means the register has some value, but it's not a valid pointer. 90 * (like pointer plus pointer becomes SCALAR_VALUE type) 91 * 92 * When verifier sees load or store instructions the type of base register 93 * can be: PTR_TO_MAP_VALUE, PTR_TO_CTX, PTR_TO_STACK, PTR_TO_SOCKET. These are 94 * four pointer types recognized by check_mem_access() function. 95 * 96 * PTR_TO_MAP_VALUE means that this register is pointing to 'map element value' 97 * and the range of [ptr, ptr + map's value_size) is accessible. 98 * 99 * registers used to pass values to function calls are checked against 100 * function argument constraints. 101 * 102 * ARG_PTR_TO_MAP_KEY is one of such argument constraints. 103 * It means that the register type passed to this function must be 104 * PTR_TO_STACK and it will be used inside the function as 105 * 'pointer to map element key' 106 * 107 * For example the argument constraints for bpf_map_lookup_elem(): 108 * .ret_type = RET_PTR_TO_MAP_VALUE_OR_NULL, 109 * .arg1_type = ARG_CONST_MAP_PTR, 110 * .arg2_type = ARG_PTR_TO_MAP_KEY, 111 * 112 * ret_type says that this function returns 'pointer to map elem value or null' 113 * function expects 1st argument to be a const pointer to 'struct bpf_map' and 114 * 2nd argument should be a pointer to stack, which will be used inside 115 * the helper function as a pointer to map element key. 116 * 117 * On the kernel side the helper function looks like: 118 * u64 bpf_map_lookup_elem(u64 r1, u64 r2, u64 r3, u64 r4, u64 r5) 119 * { 120 * struct bpf_map *map = (struct bpf_map *) (unsigned long) r1; 121 * void *key = (void *) (unsigned long) r2; 122 * void *value; 123 * 124 * here kernel can access 'key' and 'map' pointers safely, knowing that 125 * [key, key + map->key_size) bytes are valid and were initialized on 126 * the stack of eBPF program. 127 * } 128 * 129 * Corresponding eBPF program may look like: 130 * BPF_MOV64_REG(BPF_REG_2, BPF_REG_10), // after this insn R2 type is FRAME_PTR 131 * BPF_ALU64_IMM(BPF_ADD, BPF_REG_2, -4), // after this insn R2 type is PTR_TO_STACK 132 * BPF_LD_MAP_FD(BPF_REG_1, map_fd), // after this insn R1 type is CONST_PTR_TO_MAP 133 * BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0, BPF_FUNC_map_lookup_elem), 134 * here verifier looks at prototype of map_lookup_elem() and sees: 135 * .arg1_type == ARG_CONST_MAP_PTR and R1->type == CONST_PTR_TO_MAP, which is ok, 136 * Now verifier knows that this map has key of R1->map_ptr->key_size bytes 137 * 138 * Then .arg2_type == ARG_PTR_TO_MAP_KEY and R2->type == PTR_TO_STACK, ok so far, 139 * Now verifier checks that [R2, R2 + map's key_size) are within stack limits 140 * and were initialized prior to this call. 141 * If it's ok, then verifier allows this BPF_CALL insn and looks at 142 * .ret_type which is RET_PTR_TO_MAP_VALUE_OR_NULL, so it sets 143 * R0->type = PTR_TO_MAP_VALUE_OR_NULL which means bpf_map_lookup_elem() function 144 * returns either pointer to map value or NULL. 145 * 146 * When type PTR_TO_MAP_VALUE_OR_NULL passes through 'if (reg != 0) goto +off' 147 * insn, the register holding that pointer in the true branch changes state to 148 * PTR_TO_MAP_VALUE and the same register changes state to CONST_IMM in the false 149 * branch. See check_cond_jmp_op(). 150 * 151 * After the call R0 is set to return type of the function and registers R1-R5 152 * are set to NOT_INIT to indicate that they are no longer readable. 153 * 154 * The following reference types represent a potential reference to a kernel 155 * resource which, after first being allocated, must be checked and freed by 156 * the BPF program: 157 * - PTR_TO_SOCKET_OR_NULL, PTR_TO_SOCKET 158 * 159 * When the verifier sees a helper call return a reference type, it allocates a 160 * pointer id for the reference and stores it in the current function state. 161 * Similar to the way that PTR_TO_MAP_VALUE_OR_NULL is converted into 162 * PTR_TO_MAP_VALUE, PTR_TO_SOCKET_OR_NULL becomes PTR_TO_SOCKET when the type 163 * passes through a NULL-check conditional. For the branch wherein the state is 164 * changed to CONST_IMM, the verifier releases the reference. 165 * 166 * For each helper function that allocates a reference, such as 167 * bpf_sk_lookup_tcp(), there is a corresponding release function, such as 168 * bpf_sk_release(). When a reference type passes into the release function, 169 * the verifier also releases the reference. If any unchecked or unreleased 170 * reference remains at the end of the program, the verifier rejects it. 171 */ 172 173 /* verifier_state + insn_idx are pushed to stack when branch is encountered */ 174 struct bpf_verifier_stack_elem { 175 /* verifer state is 'st' 176 * before processing instruction 'insn_idx' 177 * and after processing instruction 'prev_insn_idx' 178 */ 179 struct bpf_verifier_state st; 180 int insn_idx; 181 int prev_insn_idx; 182 struct bpf_verifier_stack_elem *next; 183 /* length of verifier log at the time this state was pushed on stack */ 184 u32 log_pos; 185 }; 186 187 #define BPF_COMPLEXITY_LIMIT_JMP_SEQ 8192 188 #define BPF_COMPLEXITY_LIMIT_STATES 64 189 190 #define BPF_MAP_KEY_POISON (1ULL << 63) 191 #define BPF_MAP_KEY_SEEN (1ULL << 62) 192 193 #define BPF_MAP_PTR_UNPRIV 1UL 194 #define BPF_MAP_PTR_POISON ((void *)((0xeB9FUL << 1) + \ 195 POISON_POINTER_DELTA)) 196 #define BPF_MAP_PTR(X) ((struct bpf_map *)((X) & ~BPF_MAP_PTR_UNPRIV)) 197 198 static int acquire_reference_state(struct bpf_verifier_env *env, int insn_idx); 199 static int release_reference(struct bpf_verifier_env *env, int ref_obj_id); 200 static void invalidate_non_owning_refs(struct bpf_verifier_env *env); 201 static bool in_rbtree_lock_required_cb(struct bpf_verifier_env *env); 202 static int ref_set_non_owning(struct bpf_verifier_env *env, 203 struct bpf_reg_state *reg); 204 static void specialize_kfunc(struct bpf_verifier_env *env, 205 u32 func_id, u16 offset, unsigned long *addr); 206 static bool is_trusted_reg(const struct bpf_reg_state *reg); 207 208 static bool bpf_map_ptr_poisoned(const struct bpf_insn_aux_data *aux) 209 { 210 return BPF_MAP_PTR(aux->map_ptr_state) == BPF_MAP_PTR_POISON; 211 } 212 213 static bool bpf_map_ptr_unpriv(const struct bpf_insn_aux_data *aux) 214 { 215 return aux->map_ptr_state & BPF_MAP_PTR_UNPRIV; 216 } 217 218 static void bpf_map_ptr_store(struct bpf_insn_aux_data *aux, 219 const struct bpf_map *map, bool unpriv) 220 { 221 BUILD_BUG_ON((unsigned long)BPF_MAP_PTR_POISON & BPF_MAP_PTR_UNPRIV); 222 unpriv |= bpf_map_ptr_unpriv(aux); 223 aux->map_ptr_state = (unsigned long)map | 224 (unpriv ? BPF_MAP_PTR_UNPRIV : 0UL); 225 } 226 227 static bool bpf_map_key_poisoned(const struct bpf_insn_aux_data *aux) 228 { 229 return aux->map_key_state & BPF_MAP_KEY_POISON; 230 } 231 232 static bool bpf_map_key_unseen(const struct bpf_insn_aux_data *aux) 233 { 234 return !(aux->map_key_state & BPF_MAP_KEY_SEEN); 235 } 236 237 static u64 bpf_map_key_immediate(const struct bpf_insn_aux_data *aux) 238 { 239 return aux->map_key_state & ~(BPF_MAP_KEY_SEEN | BPF_MAP_KEY_POISON); 240 } 241 242 static void bpf_map_key_store(struct bpf_insn_aux_data *aux, u64 state) 243 { 244 bool poisoned = bpf_map_key_poisoned(aux); 245 246 aux->map_key_state = state | BPF_MAP_KEY_SEEN | 247 (poisoned ? BPF_MAP_KEY_POISON : 0ULL); 248 } 249 250 static bool bpf_helper_call(const struct bpf_insn *insn) 251 { 252 return insn->code == (BPF_JMP | BPF_CALL) && 253 insn->src_reg == 0; 254 } 255 256 static bool bpf_pseudo_call(const struct bpf_insn *insn) 257 { 258 return insn->code == (BPF_JMP | BPF_CALL) && 259 insn->src_reg == BPF_PSEUDO_CALL; 260 } 261 262 static bool bpf_pseudo_kfunc_call(const struct bpf_insn *insn) 263 { 264 return insn->code == (BPF_JMP | BPF_CALL) && 265 insn->src_reg == BPF_PSEUDO_KFUNC_CALL; 266 } 267 268 struct bpf_call_arg_meta { 269 struct bpf_map *map_ptr; 270 bool raw_mode; 271 bool pkt_access; 272 u8 release_regno; 273 int regno; 274 int access_size; 275 int mem_size; 276 u64 msize_max_value; 277 int ref_obj_id; 278 int dynptr_id; 279 int map_uid; 280 int func_id; 281 struct btf *btf; 282 u32 btf_id; 283 struct btf *ret_btf; 284 u32 ret_btf_id; 285 u32 subprogno; 286 struct btf_field *kptr_field; 287 }; 288 289 struct bpf_kfunc_call_arg_meta { 290 /* In parameters */ 291 struct btf *btf; 292 u32 func_id; 293 u32 kfunc_flags; 294 const struct btf_type *func_proto; 295 const char *func_name; 296 /* Out parameters */ 297 u32 ref_obj_id; 298 u8 release_regno; 299 bool r0_rdonly; 300 u32 ret_btf_id; 301 u64 r0_size; 302 u32 subprogno; 303 struct { 304 u64 value; 305 bool found; 306 } arg_constant; 307 308 /* arg_{btf,btf_id,owning_ref} are used by kfunc-specific handling, 309 * generally to pass info about user-defined local kptr types to later 310 * verification logic 311 * bpf_obj_drop/bpf_percpu_obj_drop 312 * Record the local kptr type to be drop'd 313 * bpf_refcount_acquire (via KF_ARG_PTR_TO_REFCOUNTED_KPTR arg type) 314 * Record the local kptr type to be refcount_incr'd and use 315 * arg_owning_ref to determine whether refcount_acquire should be 316 * fallible 317 */ 318 struct btf *arg_btf; 319 u32 arg_btf_id; 320 bool arg_owning_ref; 321 322 struct { 323 struct btf_field *field; 324 } arg_list_head; 325 struct { 326 struct btf_field *field; 327 } arg_rbtree_root; 328 struct { 329 enum bpf_dynptr_type type; 330 u32 id; 331 u32 ref_obj_id; 332 } initialized_dynptr; 333 struct { 334 u8 spi; 335 u8 frameno; 336 } iter; 337 u64 mem_size; 338 }; 339 340 struct btf *btf_vmlinux; 341 342 static DEFINE_MUTEX(bpf_verifier_lock); 343 static DEFINE_MUTEX(bpf_percpu_ma_lock); 344 345 static const struct bpf_line_info * 346 find_linfo(const struct bpf_verifier_env *env, u32 insn_off) 347 { 348 const struct bpf_line_info *linfo; 349 const struct bpf_prog *prog; 350 u32 i, nr_linfo; 351 352 prog = env->prog; 353 nr_linfo = prog->aux->nr_linfo; 354 355 if (!nr_linfo || insn_off >= prog->len) 356 return NULL; 357 358 linfo = prog->aux->linfo; 359 for (i = 1; i < nr_linfo; i++) 360 if (insn_off < linfo[i].insn_off) 361 break; 362 363 return &linfo[i - 1]; 364 } 365 366 __printf(2, 3) static void verbose(void *private_data, const char *fmt, ...) 367 { 368 struct bpf_verifier_env *env = private_data; 369 va_list args; 370 371 if (!bpf_verifier_log_needed(&env->log)) 372 return; 373 374 va_start(args, fmt); 375 bpf_verifier_vlog(&env->log, fmt, args); 376 va_end(args); 377 } 378 379 static const char *ltrim(const char *s) 380 { 381 while (isspace(*s)) 382 s++; 383 384 return s; 385 } 386 387 __printf(3, 4) static void verbose_linfo(struct bpf_verifier_env *env, 388 u32 insn_off, 389 const char *prefix_fmt, ...) 390 { 391 const struct bpf_line_info *linfo; 392 393 if (!bpf_verifier_log_needed(&env->log)) 394 return; 395 396 linfo = find_linfo(env, insn_off); 397 if (!linfo || linfo == env->prev_linfo) 398 return; 399 400 if (prefix_fmt) { 401 va_list args; 402 403 va_start(args, prefix_fmt); 404 bpf_verifier_vlog(&env->log, prefix_fmt, args); 405 va_end(args); 406 } 407 408 verbose(env, "%s\n", 409 ltrim(btf_name_by_offset(env->prog->aux->btf, 410 linfo->line_off))); 411 412 env->prev_linfo = linfo; 413 } 414 415 static void verbose_invalid_scalar(struct bpf_verifier_env *env, 416 struct bpf_reg_state *reg, 417 struct tnum *range, const char *ctx, 418 const char *reg_name) 419 { 420 char tn_buf[48]; 421 422 verbose(env, "At %s the register %s ", ctx, reg_name); 423 if (!tnum_is_unknown(reg->var_off)) { 424 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 425 verbose(env, "has value %s", tn_buf); 426 } else { 427 verbose(env, "has unknown scalar value"); 428 } 429 tnum_strn(tn_buf, sizeof(tn_buf), *range); 430 verbose(env, " should have been in %s\n", tn_buf); 431 } 432 433 static bool type_is_pkt_pointer(enum bpf_reg_type type) 434 { 435 type = base_type(type); 436 return type == PTR_TO_PACKET || 437 type == PTR_TO_PACKET_META; 438 } 439 440 static bool type_is_sk_pointer(enum bpf_reg_type type) 441 { 442 return type == PTR_TO_SOCKET || 443 type == PTR_TO_SOCK_COMMON || 444 type == PTR_TO_TCP_SOCK || 445 type == PTR_TO_XDP_SOCK; 446 } 447 448 static bool type_may_be_null(u32 type) 449 { 450 return type & PTR_MAYBE_NULL; 451 } 452 453 static bool reg_not_null(const struct bpf_reg_state *reg) 454 { 455 enum bpf_reg_type type; 456 457 type = reg->type; 458 if (type_may_be_null(type)) 459 return false; 460 461 type = base_type(type); 462 return type == PTR_TO_SOCKET || 463 type == PTR_TO_TCP_SOCK || 464 type == PTR_TO_MAP_VALUE || 465 type == PTR_TO_MAP_KEY || 466 type == PTR_TO_SOCK_COMMON || 467 (type == PTR_TO_BTF_ID && is_trusted_reg(reg)) || 468 type == PTR_TO_MEM; 469 } 470 471 static bool type_is_ptr_alloc_obj(u32 type) 472 { 473 return base_type(type) == PTR_TO_BTF_ID && type_flag(type) & MEM_ALLOC; 474 } 475 476 static bool type_is_non_owning_ref(u32 type) 477 { 478 return type_is_ptr_alloc_obj(type) && type_flag(type) & NON_OWN_REF; 479 } 480 481 static struct btf_record *reg_btf_record(const struct bpf_reg_state *reg) 482 { 483 struct btf_record *rec = NULL; 484 struct btf_struct_meta *meta; 485 486 if (reg->type == PTR_TO_MAP_VALUE) { 487 rec = reg->map_ptr->record; 488 } else if (type_is_ptr_alloc_obj(reg->type)) { 489 meta = btf_find_struct_meta(reg->btf, reg->btf_id); 490 if (meta) 491 rec = meta->record; 492 } 493 return rec; 494 } 495 496 static bool subprog_is_global(const struct bpf_verifier_env *env, int subprog) 497 { 498 struct bpf_func_info_aux *aux = env->prog->aux->func_info_aux; 499 500 return aux && aux[subprog].linkage == BTF_FUNC_GLOBAL; 501 } 502 503 static bool reg_may_point_to_spin_lock(const struct bpf_reg_state *reg) 504 { 505 return btf_record_has_field(reg_btf_record(reg), BPF_SPIN_LOCK); 506 } 507 508 static bool type_is_rdonly_mem(u32 type) 509 { 510 return type & MEM_RDONLY; 511 } 512 513 static bool is_acquire_function(enum bpf_func_id func_id, 514 const struct bpf_map *map) 515 { 516 enum bpf_map_type map_type = map ? map->map_type : BPF_MAP_TYPE_UNSPEC; 517 518 if (func_id == BPF_FUNC_sk_lookup_tcp || 519 func_id == BPF_FUNC_sk_lookup_udp || 520 func_id == BPF_FUNC_skc_lookup_tcp || 521 func_id == BPF_FUNC_ringbuf_reserve || 522 func_id == BPF_FUNC_kptr_xchg) 523 return true; 524 525 if (func_id == BPF_FUNC_map_lookup_elem && 526 (map_type == BPF_MAP_TYPE_SOCKMAP || 527 map_type == BPF_MAP_TYPE_SOCKHASH)) 528 return true; 529 530 return false; 531 } 532 533 static bool is_ptr_cast_function(enum bpf_func_id func_id) 534 { 535 return func_id == BPF_FUNC_tcp_sock || 536 func_id == BPF_FUNC_sk_fullsock || 537 func_id == BPF_FUNC_skc_to_tcp_sock || 538 func_id == BPF_FUNC_skc_to_tcp6_sock || 539 func_id == BPF_FUNC_skc_to_udp6_sock || 540 func_id == BPF_FUNC_skc_to_mptcp_sock || 541 func_id == BPF_FUNC_skc_to_tcp_timewait_sock || 542 func_id == BPF_FUNC_skc_to_tcp_request_sock; 543 } 544 545 static bool is_dynptr_ref_function(enum bpf_func_id func_id) 546 { 547 return func_id == BPF_FUNC_dynptr_data; 548 } 549 550 static bool is_callback_calling_kfunc(u32 btf_id); 551 static bool is_bpf_throw_kfunc(struct bpf_insn *insn); 552 553 static bool is_callback_calling_function(enum bpf_func_id func_id) 554 { 555 return func_id == BPF_FUNC_for_each_map_elem || 556 func_id == BPF_FUNC_timer_set_callback || 557 func_id == BPF_FUNC_find_vma || 558 func_id == BPF_FUNC_loop || 559 func_id == BPF_FUNC_user_ringbuf_drain; 560 } 561 562 static bool is_async_callback_calling_function(enum bpf_func_id func_id) 563 { 564 return func_id == BPF_FUNC_timer_set_callback; 565 } 566 567 static bool is_storage_get_function(enum bpf_func_id func_id) 568 { 569 return func_id == BPF_FUNC_sk_storage_get || 570 func_id == BPF_FUNC_inode_storage_get || 571 func_id == BPF_FUNC_task_storage_get || 572 func_id == BPF_FUNC_cgrp_storage_get; 573 } 574 575 static bool helper_multiple_ref_obj_use(enum bpf_func_id func_id, 576 const struct bpf_map *map) 577 { 578 int ref_obj_uses = 0; 579 580 if (is_ptr_cast_function(func_id)) 581 ref_obj_uses++; 582 if (is_acquire_function(func_id, map)) 583 ref_obj_uses++; 584 if (is_dynptr_ref_function(func_id)) 585 ref_obj_uses++; 586 587 return ref_obj_uses > 1; 588 } 589 590 static bool is_cmpxchg_insn(const struct bpf_insn *insn) 591 { 592 return BPF_CLASS(insn->code) == BPF_STX && 593 BPF_MODE(insn->code) == BPF_ATOMIC && 594 insn->imm == BPF_CMPXCHG; 595 } 596 597 /* string representation of 'enum bpf_reg_type' 598 * 599 * Note that reg_type_str() can not appear more than once in a single verbose() 600 * statement. 601 */ 602 static const char *reg_type_str(struct bpf_verifier_env *env, 603 enum bpf_reg_type type) 604 { 605 char postfix[16] = {0}, prefix[64] = {0}; 606 static const char * const str[] = { 607 [NOT_INIT] = "?", 608 [SCALAR_VALUE] = "scalar", 609 [PTR_TO_CTX] = "ctx", 610 [CONST_PTR_TO_MAP] = "map_ptr", 611 [PTR_TO_MAP_VALUE] = "map_value", 612 [PTR_TO_STACK] = "fp", 613 [PTR_TO_PACKET] = "pkt", 614 [PTR_TO_PACKET_META] = "pkt_meta", 615 [PTR_TO_PACKET_END] = "pkt_end", 616 [PTR_TO_FLOW_KEYS] = "flow_keys", 617 [PTR_TO_SOCKET] = "sock", 618 [PTR_TO_SOCK_COMMON] = "sock_common", 619 [PTR_TO_TCP_SOCK] = "tcp_sock", 620 [PTR_TO_TP_BUFFER] = "tp_buffer", 621 [PTR_TO_XDP_SOCK] = "xdp_sock", 622 [PTR_TO_BTF_ID] = "ptr_", 623 [PTR_TO_MEM] = "mem", 624 [PTR_TO_BUF] = "buf", 625 [PTR_TO_FUNC] = "func", 626 [PTR_TO_MAP_KEY] = "map_key", 627 [CONST_PTR_TO_DYNPTR] = "dynptr_ptr", 628 }; 629 630 if (type & PTR_MAYBE_NULL) { 631 if (base_type(type) == PTR_TO_BTF_ID) 632 strncpy(postfix, "or_null_", 16); 633 else 634 strncpy(postfix, "_or_null", 16); 635 } 636 637 snprintf(prefix, sizeof(prefix), "%s%s%s%s%s%s%s", 638 type & MEM_RDONLY ? "rdonly_" : "", 639 type & MEM_RINGBUF ? "ringbuf_" : "", 640 type & MEM_USER ? "user_" : "", 641 type & MEM_PERCPU ? "percpu_" : "", 642 type & MEM_RCU ? "rcu_" : "", 643 type & PTR_UNTRUSTED ? "untrusted_" : "", 644 type & PTR_TRUSTED ? "trusted_" : "" 645 ); 646 647 snprintf(env->tmp_str_buf, TMP_STR_BUF_LEN, "%s%s%s", 648 prefix, str[base_type(type)], postfix); 649 return env->tmp_str_buf; 650 } 651 652 static char slot_type_char[] = { 653 [STACK_INVALID] = '?', 654 [STACK_SPILL] = 'r', 655 [STACK_MISC] = 'm', 656 [STACK_ZERO] = '0', 657 [STACK_DYNPTR] = 'd', 658 [STACK_ITER] = 'i', 659 }; 660 661 static void print_liveness(struct bpf_verifier_env *env, 662 enum bpf_reg_liveness live) 663 { 664 if (live & (REG_LIVE_READ | REG_LIVE_WRITTEN | REG_LIVE_DONE)) 665 verbose(env, "_"); 666 if (live & REG_LIVE_READ) 667 verbose(env, "r"); 668 if (live & REG_LIVE_WRITTEN) 669 verbose(env, "w"); 670 if (live & REG_LIVE_DONE) 671 verbose(env, "D"); 672 } 673 674 static int __get_spi(s32 off) 675 { 676 return (-off - 1) / BPF_REG_SIZE; 677 } 678 679 static struct bpf_func_state *func(struct bpf_verifier_env *env, 680 const struct bpf_reg_state *reg) 681 { 682 struct bpf_verifier_state *cur = env->cur_state; 683 684 return cur->frame[reg->frameno]; 685 } 686 687 static bool is_spi_bounds_valid(struct bpf_func_state *state, int spi, int nr_slots) 688 { 689 int allocated_slots = state->allocated_stack / BPF_REG_SIZE; 690 691 /* We need to check that slots between [spi - nr_slots + 1, spi] are 692 * within [0, allocated_stack). 693 * 694 * Please note that the spi grows downwards. For example, a dynptr 695 * takes the size of two stack slots; the first slot will be at 696 * spi and the second slot will be at spi - 1. 697 */ 698 return spi - nr_slots + 1 >= 0 && spi < allocated_slots; 699 } 700 701 static int stack_slot_obj_get_spi(struct bpf_verifier_env *env, struct bpf_reg_state *reg, 702 const char *obj_kind, int nr_slots) 703 { 704 int off, spi; 705 706 if (!tnum_is_const(reg->var_off)) { 707 verbose(env, "%s has to be at a constant offset\n", obj_kind); 708 return -EINVAL; 709 } 710 711 off = reg->off + reg->var_off.value; 712 if (off % BPF_REG_SIZE) { 713 verbose(env, "cannot pass in %s at an offset=%d\n", obj_kind, off); 714 return -EINVAL; 715 } 716 717 spi = __get_spi(off); 718 if (spi + 1 < nr_slots) { 719 verbose(env, "cannot pass in %s at an offset=%d\n", obj_kind, off); 720 return -EINVAL; 721 } 722 723 if (!is_spi_bounds_valid(func(env, reg), spi, nr_slots)) 724 return -ERANGE; 725 return spi; 726 } 727 728 static int dynptr_get_spi(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 729 { 730 return stack_slot_obj_get_spi(env, reg, "dynptr", BPF_DYNPTR_NR_SLOTS); 731 } 732 733 static int iter_get_spi(struct bpf_verifier_env *env, struct bpf_reg_state *reg, int nr_slots) 734 { 735 return stack_slot_obj_get_spi(env, reg, "iter", nr_slots); 736 } 737 738 static const char *btf_type_name(const struct btf *btf, u32 id) 739 { 740 return btf_name_by_offset(btf, btf_type_by_id(btf, id)->name_off); 741 } 742 743 static const char *dynptr_type_str(enum bpf_dynptr_type type) 744 { 745 switch (type) { 746 case BPF_DYNPTR_TYPE_LOCAL: 747 return "local"; 748 case BPF_DYNPTR_TYPE_RINGBUF: 749 return "ringbuf"; 750 case BPF_DYNPTR_TYPE_SKB: 751 return "skb"; 752 case BPF_DYNPTR_TYPE_XDP: 753 return "xdp"; 754 case BPF_DYNPTR_TYPE_INVALID: 755 return "<invalid>"; 756 default: 757 WARN_ONCE(1, "unknown dynptr type %d\n", type); 758 return "<unknown>"; 759 } 760 } 761 762 static const char *iter_type_str(const struct btf *btf, u32 btf_id) 763 { 764 if (!btf || btf_id == 0) 765 return "<invalid>"; 766 767 /* we already validated that type is valid and has conforming name */ 768 return btf_type_name(btf, btf_id) + sizeof(ITER_PREFIX) - 1; 769 } 770 771 static const char *iter_state_str(enum bpf_iter_state state) 772 { 773 switch (state) { 774 case BPF_ITER_STATE_ACTIVE: 775 return "active"; 776 case BPF_ITER_STATE_DRAINED: 777 return "drained"; 778 case BPF_ITER_STATE_INVALID: 779 return "<invalid>"; 780 default: 781 WARN_ONCE(1, "unknown iter state %d\n", state); 782 return "<unknown>"; 783 } 784 } 785 786 static void mark_reg_scratched(struct bpf_verifier_env *env, u32 regno) 787 { 788 env->scratched_regs |= 1U << regno; 789 } 790 791 static void mark_stack_slot_scratched(struct bpf_verifier_env *env, u32 spi) 792 { 793 env->scratched_stack_slots |= 1ULL << spi; 794 } 795 796 static bool reg_scratched(const struct bpf_verifier_env *env, u32 regno) 797 { 798 return (env->scratched_regs >> regno) & 1; 799 } 800 801 static bool stack_slot_scratched(const struct bpf_verifier_env *env, u64 regno) 802 { 803 return (env->scratched_stack_slots >> regno) & 1; 804 } 805 806 static bool verifier_state_scratched(const struct bpf_verifier_env *env) 807 { 808 return env->scratched_regs || env->scratched_stack_slots; 809 } 810 811 static void mark_verifier_state_clean(struct bpf_verifier_env *env) 812 { 813 env->scratched_regs = 0U; 814 env->scratched_stack_slots = 0ULL; 815 } 816 817 /* Used for printing the entire verifier state. */ 818 static void mark_verifier_state_scratched(struct bpf_verifier_env *env) 819 { 820 env->scratched_regs = ~0U; 821 env->scratched_stack_slots = ~0ULL; 822 } 823 824 static enum bpf_dynptr_type arg_to_dynptr_type(enum bpf_arg_type arg_type) 825 { 826 switch (arg_type & DYNPTR_TYPE_FLAG_MASK) { 827 case DYNPTR_TYPE_LOCAL: 828 return BPF_DYNPTR_TYPE_LOCAL; 829 case DYNPTR_TYPE_RINGBUF: 830 return BPF_DYNPTR_TYPE_RINGBUF; 831 case DYNPTR_TYPE_SKB: 832 return BPF_DYNPTR_TYPE_SKB; 833 case DYNPTR_TYPE_XDP: 834 return BPF_DYNPTR_TYPE_XDP; 835 default: 836 return BPF_DYNPTR_TYPE_INVALID; 837 } 838 } 839 840 static enum bpf_type_flag get_dynptr_type_flag(enum bpf_dynptr_type type) 841 { 842 switch (type) { 843 case BPF_DYNPTR_TYPE_LOCAL: 844 return DYNPTR_TYPE_LOCAL; 845 case BPF_DYNPTR_TYPE_RINGBUF: 846 return DYNPTR_TYPE_RINGBUF; 847 case BPF_DYNPTR_TYPE_SKB: 848 return DYNPTR_TYPE_SKB; 849 case BPF_DYNPTR_TYPE_XDP: 850 return DYNPTR_TYPE_XDP; 851 default: 852 return 0; 853 } 854 } 855 856 static bool dynptr_type_refcounted(enum bpf_dynptr_type type) 857 { 858 return type == BPF_DYNPTR_TYPE_RINGBUF; 859 } 860 861 static void __mark_dynptr_reg(struct bpf_reg_state *reg, 862 enum bpf_dynptr_type type, 863 bool first_slot, int dynptr_id); 864 865 static void __mark_reg_not_init(const struct bpf_verifier_env *env, 866 struct bpf_reg_state *reg); 867 868 static void mark_dynptr_stack_regs(struct bpf_verifier_env *env, 869 struct bpf_reg_state *sreg1, 870 struct bpf_reg_state *sreg2, 871 enum bpf_dynptr_type type) 872 { 873 int id = ++env->id_gen; 874 875 __mark_dynptr_reg(sreg1, type, true, id); 876 __mark_dynptr_reg(sreg2, type, false, id); 877 } 878 879 static void mark_dynptr_cb_reg(struct bpf_verifier_env *env, 880 struct bpf_reg_state *reg, 881 enum bpf_dynptr_type type) 882 { 883 __mark_dynptr_reg(reg, type, true, ++env->id_gen); 884 } 885 886 static int destroy_if_dynptr_stack_slot(struct bpf_verifier_env *env, 887 struct bpf_func_state *state, int spi); 888 889 static int mark_stack_slots_dynptr(struct bpf_verifier_env *env, struct bpf_reg_state *reg, 890 enum bpf_arg_type arg_type, int insn_idx, int clone_ref_obj_id) 891 { 892 struct bpf_func_state *state = func(env, reg); 893 enum bpf_dynptr_type type; 894 int spi, i, err; 895 896 spi = dynptr_get_spi(env, reg); 897 if (spi < 0) 898 return spi; 899 900 /* We cannot assume both spi and spi - 1 belong to the same dynptr, 901 * hence we need to call destroy_if_dynptr_stack_slot twice for both, 902 * to ensure that for the following example: 903 * [d1][d1][d2][d2] 904 * spi 3 2 1 0 905 * So marking spi = 2 should lead to destruction of both d1 and d2. In 906 * case they do belong to same dynptr, second call won't see slot_type 907 * as STACK_DYNPTR and will simply skip destruction. 908 */ 909 err = destroy_if_dynptr_stack_slot(env, state, spi); 910 if (err) 911 return err; 912 err = destroy_if_dynptr_stack_slot(env, state, spi - 1); 913 if (err) 914 return err; 915 916 for (i = 0; i < BPF_REG_SIZE; i++) { 917 state->stack[spi].slot_type[i] = STACK_DYNPTR; 918 state->stack[spi - 1].slot_type[i] = STACK_DYNPTR; 919 } 920 921 type = arg_to_dynptr_type(arg_type); 922 if (type == BPF_DYNPTR_TYPE_INVALID) 923 return -EINVAL; 924 925 mark_dynptr_stack_regs(env, &state->stack[spi].spilled_ptr, 926 &state->stack[spi - 1].spilled_ptr, type); 927 928 if (dynptr_type_refcounted(type)) { 929 /* The id is used to track proper releasing */ 930 int id; 931 932 if (clone_ref_obj_id) 933 id = clone_ref_obj_id; 934 else 935 id = acquire_reference_state(env, insn_idx); 936 937 if (id < 0) 938 return id; 939 940 state->stack[spi].spilled_ptr.ref_obj_id = id; 941 state->stack[spi - 1].spilled_ptr.ref_obj_id = id; 942 } 943 944 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN; 945 state->stack[spi - 1].spilled_ptr.live |= REG_LIVE_WRITTEN; 946 947 return 0; 948 } 949 950 static void invalidate_dynptr(struct bpf_verifier_env *env, struct bpf_func_state *state, int spi) 951 { 952 int i; 953 954 for (i = 0; i < BPF_REG_SIZE; i++) { 955 state->stack[spi].slot_type[i] = STACK_INVALID; 956 state->stack[spi - 1].slot_type[i] = STACK_INVALID; 957 } 958 959 __mark_reg_not_init(env, &state->stack[spi].spilled_ptr); 960 __mark_reg_not_init(env, &state->stack[spi - 1].spilled_ptr); 961 962 /* Why do we need to set REG_LIVE_WRITTEN for STACK_INVALID slot? 963 * 964 * While we don't allow reading STACK_INVALID, it is still possible to 965 * do <8 byte writes marking some but not all slots as STACK_MISC. Then, 966 * helpers or insns can do partial read of that part without failing, 967 * but check_stack_range_initialized, check_stack_read_var_off, and 968 * check_stack_read_fixed_off will do mark_reg_read for all 8-bytes of 969 * the slot conservatively. Hence we need to prevent those liveness 970 * marking walks. 971 * 972 * This was not a problem before because STACK_INVALID is only set by 973 * default (where the default reg state has its reg->parent as NULL), or 974 * in clean_live_states after REG_LIVE_DONE (at which point 975 * mark_reg_read won't walk reg->parent chain), but not randomly during 976 * verifier state exploration (like we did above). Hence, for our case 977 * parentage chain will still be live (i.e. reg->parent may be 978 * non-NULL), while earlier reg->parent was NULL, so we need 979 * REG_LIVE_WRITTEN to screen off read marker propagation when it is 980 * done later on reads or by mark_dynptr_read as well to unnecessary 981 * mark registers in verifier state. 982 */ 983 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN; 984 state->stack[spi - 1].spilled_ptr.live |= REG_LIVE_WRITTEN; 985 } 986 987 static int unmark_stack_slots_dynptr(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 988 { 989 struct bpf_func_state *state = func(env, reg); 990 int spi, ref_obj_id, i; 991 992 spi = dynptr_get_spi(env, reg); 993 if (spi < 0) 994 return spi; 995 996 if (!dynptr_type_refcounted(state->stack[spi].spilled_ptr.dynptr.type)) { 997 invalidate_dynptr(env, state, spi); 998 return 0; 999 } 1000 1001 ref_obj_id = state->stack[spi].spilled_ptr.ref_obj_id; 1002 1003 /* If the dynptr has a ref_obj_id, then we need to invalidate 1004 * two things: 1005 * 1006 * 1) Any dynptrs with a matching ref_obj_id (clones) 1007 * 2) Any slices derived from this dynptr. 1008 */ 1009 1010 /* Invalidate any slices associated with this dynptr */ 1011 WARN_ON_ONCE(release_reference(env, ref_obj_id)); 1012 1013 /* Invalidate any dynptr clones */ 1014 for (i = 1; i < state->allocated_stack / BPF_REG_SIZE; i++) { 1015 if (state->stack[i].spilled_ptr.ref_obj_id != ref_obj_id) 1016 continue; 1017 1018 /* it should always be the case that if the ref obj id 1019 * matches then the stack slot also belongs to a 1020 * dynptr 1021 */ 1022 if (state->stack[i].slot_type[0] != STACK_DYNPTR) { 1023 verbose(env, "verifier internal error: misconfigured ref_obj_id\n"); 1024 return -EFAULT; 1025 } 1026 if (state->stack[i].spilled_ptr.dynptr.first_slot) 1027 invalidate_dynptr(env, state, i); 1028 } 1029 1030 return 0; 1031 } 1032 1033 static void __mark_reg_unknown(const struct bpf_verifier_env *env, 1034 struct bpf_reg_state *reg); 1035 1036 static void mark_reg_invalid(const struct bpf_verifier_env *env, struct bpf_reg_state *reg) 1037 { 1038 if (!env->allow_ptr_leaks) 1039 __mark_reg_not_init(env, reg); 1040 else 1041 __mark_reg_unknown(env, reg); 1042 } 1043 1044 static int destroy_if_dynptr_stack_slot(struct bpf_verifier_env *env, 1045 struct bpf_func_state *state, int spi) 1046 { 1047 struct bpf_func_state *fstate; 1048 struct bpf_reg_state *dreg; 1049 int i, dynptr_id; 1050 1051 /* We always ensure that STACK_DYNPTR is never set partially, 1052 * hence just checking for slot_type[0] is enough. This is 1053 * different for STACK_SPILL, where it may be only set for 1054 * 1 byte, so code has to use is_spilled_reg. 1055 */ 1056 if (state->stack[spi].slot_type[0] != STACK_DYNPTR) 1057 return 0; 1058 1059 /* Reposition spi to first slot */ 1060 if (!state->stack[spi].spilled_ptr.dynptr.first_slot) 1061 spi = spi + 1; 1062 1063 if (dynptr_type_refcounted(state->stack[spi].spilled_ptr.dynptr.type)) { 1064 verbose(env, "cannot overwrite referenced dynptr\n"); 1065 return -EINVAL; 1066 } 1067 1068 mark_stack_slot_scratched(env, spi); 1069 mark_stack_slot_scratched(env, spi - 1); 1070 1071 /* Writing partially to one dynptr stack slot destroys both. */ 1072 for (i = 0; i < BPF_REG_SIZE; i++) { 1073 state->stack[spi].slot_type[i] = STACK_INVALID; 1074 state->stack[spi - 1].slot_type[i] = STACK_INVALID; 1075 } 1076 1077 dynptr_id = state->stack[spi].spilled_ptr.id; 1078 /* Invalidate any slices associated with this dynptr */ 1079 bpf_for_each_reg_in_vstate(env->cur_state, fstate, dreg, ({ 1080 /* Dynptr slices are only PTR_TO_MEM_OR_NULL and PTR_TO_MEM */ 1081 if (dreg->type != (PTR_TO_MEM | PTR_MAYBE_NULL) && dreg->type != PTR_TO_MEM) 1082 continue; 1083 if (dreg->dynptr_id == dynptr_id) 1084 mark_reg_invalid(env, dreg); 1085 })); 1086 1087 /* Do not release reference state, we are destroying dynptr on stack, 1088 * not using some helper to release it. Just reset register. 1089 */ 1090 __mark_reg_not_init(env, &state->stack[spi].spilled_ptr); 1091 __mark_reg_not_init(env, &state->stack[spi - 1].spilled_ptr); 1092 1093 /* Same reason as unmark_stack_slots_dynptr above */ 1094 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN; 1095 state->stack[spi - 1].spilled_ptr.live |= REG_LIVE_WRITTEN; 1096 1097 return 0; 1098 } 1099 1100 static bool is_dynptr_reg_valid_uninit(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 1101 { 1102 int spi; 1103 1104 if (reg->type == CONST_PTR_TO_DYNPTR) 1105 return false; 1106 1107 spi = dynptr_get_spi(env, reg); 1108 1109 /* -ERANGE (i.e. spi not falling into allocated stack slots) isn't an 1110 * error because this just means the stack state hasn't been updated yet. 1111 * We will do check_mem_access to check and update stack bounds later. 1112 */ 1113 if (spi < 0 && spi != -ERANGE) 1114 return false; 1115 1116 /* We don't need to check if the stack slots are marked by previous 1117 * dynptr initializations because we allow overwriting existing unreferenced 1118 * STACK_DYNPTR slots, see mark_stack_slots_dynptr which calls 1119 * destroy_if_dynptr_stack_slot to ensure dynptr objects at the slots we are 1120 * touching are completely destructed before we reinitialize them for a new 1121 * one. For referenced ones, destroy_if_dynptr_stack_slot returns an error early 1122 * instead of delaying it until the end where the user will get "Unreleased 1123 * reference" error. 1124 */ 1125 return true; 1126 } 1127 1128 static bool is_dynptr_reg_valid_init(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 1129 { 1130 struct bpf_func_state *state = func(env, reg); 1131 int i, spi; 1132 1133 /* This already represents first slot of initialized bpf_dynptr. 1134 * 1135 * CONST_PTR_TO_DYNPTR already has fixed and var_off as 0 due to 1136 * check_func_arg_reg_off's logic, so we don't need to check its 1137 * offset and alignment. 1138 */ 1139 if (reg->type == CONST_PTR_TO_DYNPTR) 1140 return true; 1141 1142 spi = dynptr_get_spi(env, reg); 1143 if (spi < 0) 1144 return false; 1145 if (!state->stack[spi].spilled_ptr.dynptr.first_slot) 1146 return false; 1147 1148 for (i = 0; i < BPF_REG_SIZE; i++) { 1149 if (state->stack[spi].slot_type[i] != STACK_DYNPTR || 1150 state->stack[spi - 1].slot_type[i] != STACK_DYNPTR) 1151 return false; 1152 } 1153 1154 return true; 1155 } 1156 1157 static bool is_dynptr_type_expected(struct bpf_verifier_env *env, struct bpf_reg_state *reg, 1158 enum bpf_arg_type arg_type) 1159 { 1160 struct bpf_func_state *state = func(env, reg); 1161 enum bpf_dynptr_type dynptr_type; 1162 int spi; 1163 1164 /* ARG_PTR_TO_DYNPTR takes any type of dynptr */ 1165 if (arg_type == ARG_PTR_TO_DYNPTR) 1166 return true; 1167 1168 dynptr_type = arg_to_dynptr_type(arg_type); 1169 if (reg->type == CONST_PTR_TO_DYNPTR) { 1170 return reg->dynptr.type == dynptr_type; 1171 } else { 1172 spi = dynptr_get_spi(env, reg); 1173 if (spi < 0) 1174 return false; 1175 return state->stack[spi].spilled_ptr.dynptr.type == dynptr_type; 1176 } 1177 } 1178 1179 static void __mark_reg_known_zero(struct bpf_reg_state *reg); 1180 1181 static bool in_rcu_cs(struct bpf_verifier_env *env); 1182 1183 static bool is_kfunc_rcu_protected(struct bpf_kfunc_call_arg_meta *meta); 1184 1185 static int mark_stack_slots_iter(struct bpf_verifier_env *env, 1186 struct bpf_kfunc_call_arg_meta *meta, 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 if (is_kfunc_rcu_protected(meta)) { 1208 if (in_rcu_cs(env)) 1209 st->type |= MEM_RCU; 1210 else 1211 st->type |= PTR_UNTRUSTED; 1212 } 1213 st->live |= REG_LIVE_WRITTEN; 1214 st->ref_obj_id = i == 0 ? id : 0; 1215 st->iter.btf = btf; 1216 st->iter.btf_id = btf_id; 1217 st->iter.state = BPF_ITER_STATE_ACTIVE; 1218 st->iter.depth = 0; 1219 1220 for (j = 0; j < BPF_REG_SIZE; j++) 1221 slot->slot_type[j] = STACK_ITER; 1222 1223 mark_stack_slot_scratched(env, spi - i); 1224 } 1225 1226 return 0; 1227 } 1228 1229 static int unmark_stack_slots_iter(struct bpf_verifier_env *env, 1230 struct bpf_reg_state *reg, int nr_slots) 1231 { 1232 struct bpf_func_state *state = func(env, reg); 1233 int spi, i, j; 1234 1235 spi = iter_get_spi(env, reg, nr_slots); 1236 if (spi < 0) 1237 return spi; 1238 1239 for (i = 0; i < nr_slots; i++) { 1240 struct bpf_stack_state *slot = &state->stack[spi - i]; 1241 struct bpf_reg_state *st = &slot->spilled_ptr; 1242 1243 if (i == 0) 1244 WARN_ON_ONCE(release_reference(env, st->ref_obj_id)); 1245 1246 __mark_reg_not_init(env, st); 1247 1248 /* see unmark_stack_slots_dynptr() for why we need to set REG_LIVE_WRITTEN */ 1249 st->live |= REG_LIVE_WRITTEN; 1250 1251 for (j = 0; j < BPF_REG_SIZE; j++) 1252 slot->slot_type[j] = STACK_INVALID; 1253 1254 mark_stack_slot_scratched(env, spi - i); 1255 } 1256 1257 return 0; 1258 } 1259 1260 static bool is_iter_reg_valid_uninit(struct bpf_verifier_env *env, 1261 struct bpf_reg_state *reg, int nr_slots) 1262 { 1263 struct bpf_func_state *state = func(env, reg); 1264 int spi, i, j; 1265 1266 /* For -ERANGE (i.e. spi not falling into allocated stack slots), we 1267 * will do check_mem_access to check and update stack bounds later, so 1268 * return true for that case. 1269 */ 1270 spi = iter_get_spi(env, reg, nr_slots); 1271 if (spi == -ERANGE) 1272 return true; 1273 if (spi < 0) 1274 return false; 1275 1276 for (i = 0; i < nr_slots; i++) { 1277 struct bpf_stack_state *slot = &state->stack[spi - i]; 1278 1279 for (j = 0; j < BPF_REG_SIZE; j++) 1280 if (slot->slot_type[j] == STACK_ITER) 1281 return false; 1282 } 1283 1284 return true; 1285 } 1286 1287 static int is_iter_reg_valid_init(struct bpf_verifier_env *env, struct bpf_reg_state *reg, 1288 struct btf *btf, u32 btf_id, int nr_slots) 1289 { 1290 struct bpf_func_state *state = func(env, reg); 1291 int spi, i, j; 1292 1293 spi = iter_get_spi(env, reg, nr_slots); 1294 if (spi < 0) 1295 return -EINVAL; 1296 1297 for (i = 0; i < nr_slots; i++) { 1298 struct bpf_stack_state *slot = &state->stack[spi - i]; 1299 struct bpf_reg_state *st = &slot->spilled_ptr; 1300 1301 if (st->type & PTR_UNTRUSTED) 1302 return -EPROTO; 1303 /* only main (first) slot has ref_obj_id set */ 1304 if (i == 0 && !st->ref_obj_id) 1305 return -EINVAL; 1306 if (i != 0 && st->ref_obj_id) 1307 return -EINVAL; 1308 if (st->iter.btf != btf || st->iter.btf_id != btf_id) 1309 return -EINVAL; 1310 1311 for (j = 0; j < BPF_REG_SIZE; j++) 1312 if (slot->slot_type[j] != STACK_ITER) 1313 return -EINVAL; 1314 } 1315 1316 return 0; 1317 } 1318 1319 /* Check if given stack slot is "special": 1320 * - spilled register state (STACK_SPILL); 1321 * - dynptr state (STACK_DYNPTR); 1322 * - iter state (STACK_ITER). 1323 */ 1324 static bool is_stack_slot_special(const struct bpf_stack_state *stack) 1325 { 1326 enum bpf_stack_slot_type type = stack->slot_type[BPF_REG_SIZE - 1]; 1327 1328 switch (type) { 1329 case STACK_SPILL: 1330 case STACK_DYNPTR: 1331 case STACK_ITER: 1332 return true; 1333 case STACK_INVALID: 1334 case STACK_MISC: 1335 case STACK_ZERO: 1336 return false; 1337 default: 1338 WARN_ONCE(1, "unknown stack slot type %d\n", type); 1339 return true; 1340 } 1341 } 1342 1343 /* The reg state of a pointer or a bounded scalar was saved when 1344 * it was spilled to the stack. 1345 */ 1346 static bool is_spilled_reg(const struct bpf_stack_state *stack) 1347 { 1348 return stack->slot_type[BPF_REG_SIZE - 1] == STACK_SPILL; 1349 } 1350 1351 static bool is_spilled_scalar_reg(const struct bpf_stack_state *stack) 1352 { 1353 return stack->slot_type[BPF_REG_SIZE - 1] == STACK_SPILL && 1354 stack->spilled_ptr.type == SCALAR_VALUE; 1355 } 1356 1357 static void scrub_spilled_slot(u8 *stype) 1358 { 1359 if (*stype != STACK_INVALID) 1360 *stype = STACK_MISC; 1361 } 1362 1363 static void print_scalar_ranges(struct bpf_verifier_env *env, 1364 const struct bpf_reg_state *reg, 1365 const char **sep) 1366 { 1367 struct { 1368 const char *name; 1369 u64 val; 1370 bool omit; 1371 } minmaxs[] = { 1372 {"smin", reg->smin_value, reg->smin_value == S64_MIN}, 1373 {"smax", reg->smax_value, reg->smax_value == S64_MAX}, 1374 {"umin", reg->umin_value, reg->umin_value == 0}, 1375 {"umax", reg->umax_value, reg->umax_value == U64_MAX}, 1376 {"smin32", (s64)reg->s32_min_value, reg->s32_min_value == S32_MIN}, 1377 {"smax32", (s64)reg->s32_max_value, reg->s32_max_value == S32_MAX}, 1378 {"umin32", reg->u32_min_value, reg->u32_min_value == 0}, 1379 {"umax32", reg->u32_max_value, reg->u32_max_value == U32_MAX}, 1380 }, *m1, *m2, *mend = &minmaxs[ARRAY_SIZE(minmaxs)]; 1381 bool neg1, neg2; 1382 1383 for (m1 = &minmaxs[0]; m1 < mend; m1++) { 1384 if (m1->omit) 1385 continue; 1386 1387 neg1 = m1->name[0] == 's' && (s64)m1->val < 0; 1388 1389 verbose(env, "%s%s=", *sep, m1->name); 1390 *sep = ","; 1391 1392 for (m2 = m1 + 2; m2 < mend; m2 += 2) { 1393 if (m2->omit || m2->val != m1->val) 1394 continue; 1395 /* don't mix negatives with positives */ 1396 neg2 = m2->name[0] == 's' && (s64)m2->val < 0; 1397 if (neg2 != neg1) 1398 continue; 1399 m2->omit = true; 1400 verbose(env, "%s=", m2->name); 1401 } 1402 1403 verbose(env, m1->name[0] == 's' ? "%lld" : "%llu", m1->val); 1404 } 1405 } 1406 1407 static void print_verifier_state(struct bpf_verifier_env *env, 1408 const struct bpf_func_state *state, 1409 bool print_all) 1410 { 1411 const struct bpf_reg_state *reg; 1412 enum bpf_reg_type t; 1413 int i; 1414 1415 if (state->frameno) 1416 verbose(env, " frame%d:", state->frameno); 1417 for (i = 0; i < MAX_BPF_REG; i++) { 1418 reg = &state->regs[i]; 1419 t = reg->type; 1420 if (t == NOT_INIT) 1421 continue; 1422 if (!print_all && !reg_scratched(env, i)) 1423 continue; 1424 verbose(env, " R%d", i); 1425 print_liveness(env, reg->live); 1426 verbose(env, "="); 1427 if (t == SCALAR_VALUE && reg->precise) 1428 verbose(env, "P"); 1429 if ((t == SCALAR_VALUE || t == PTR_TO_STACK) && 1430 tnum_is_const(reg->var_off)) { 1431 /* reg->off should be 0 for SCALAR_VALUE */ 1432 verbose(env, "%s", t == SCALAR_VALUE ? "" : reg_type_str(env, t)); 1433 verbose(env, "%lld", reg->var_off.value + reg->off); 1434 } else { 1435 const char *sep = ""; 1436 1437 verbose(env, "%s", reg_type_str(env, t)); 1438 if (base_type(t) == PTR_TO_BTF_ID) 1439 verbose(env, "%s", btf_type_name(reg->btf, reg->btf_id)); 1440 verbose(env, "("); 1441 /* 1442 * _a stands for append, was shortened to avoid multiline statements below. 1443 * This macro is used to output a comma separated list of attributes. 1444 */ 1445 #define verbose_a(fmt, ...) ({ verbose(env, "%s" fmt, sep, __VA_ARGS__); sep = ","; }) 1446 1447 if (reg->id) 1448 verbose_a("id=%d", reg->id); 1449 if (reg->ref_obj_id) 1450 verbose_a("ref_obj_id=%d", reg->ref_obj_id); 1451 if (type_is_non_owning_ref(reg->type)) 1452 verbose_a("%s", "non_own_ref"); 1453 if (t != SCALAR_VALUE) 1454 verbose_a("off=%d", reg->off); 1455 if (type_is_pkt_pointer(t)) 1456 verbose_a("r=%d", reg->range); 1457 else if (base_type(t) == CONST_PTR_TO_MAP || 1458 base_type(t) == PTR_TO_MAP_KEY || 1459 base_type(t) == PTR_TO_MAP_VALUE) 1460 verbose_a("ks=%d,vs=%d", 1461 reg->map_ptr->key_size, 1462 reg->map_ptr->value_size); 1463 if (tnum_is_const(reg->var_off)) { 1464 /* Typically an immediate SCALAR_VALUE, but 1465 * could be a pointer whose offset is too big 1466 * for reg->off 1467 */ 1468 verbose_a("imm=%llx", reg->var_off.value); 1469 } else { 1470 print_scalar_ranges(env, reg, &sep); 1471 if (!tnum_is_unknown(reg->var_off)) { 1472 char tn_buf[48]; 1473 1474 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 1475 verbose_a("var_off=%s", tn_buf); 1476 } 1477 } 1478 #undef verbose_a 1479 1480 verbose(env, ")"); 1481 } 1482 } 1483 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) { 1484 char types_buf[BPF_REG_SIZE + 1]; 1485 bool valid = false; 1486 int j; 1487 1488 for (j = 0; j < BPF_REG_SIZE; j++) { 1489 if (state->stack[i].slot_type[j] != STACK_INVALID) 1490 valid = true; 1491 types_buf[j] = slot_type_char[state->stack[i].slot_type[j]]; 1492 } 1493 types_buf[BPF_REG_SIZE] = 0; 1494 if (!valid) 1495 continue; 1496 if (!print_all && !stack_slot_scratched(env, i)) 1497 continue; 1498 switch (state->stack[i].slot_type[BPF_REG_SIZE - 1]) { 1499 case STACK_SPILL: 1500 reg = &state->stack[i].spilled_ptr; 1501 t = reg->type; 1502 1503 verbose(env, " fp%d", (-i - 1) * BPF_REG_SIZE); 1504 print_liveness(env, reg->live); 1505 verbose(env, "=%s", t == SCALAR_VALUE ? "" : reg_type_str(env, t)); 1506 if (t == SCALAR_VALUE && reg->precise) 1507 verbose(env, "P"); 1508 if (t == SCALAR_VALUE && tnum_is_const(reg->var_off)) 1509 verbose(env, "%lld", reg->var_off.value + reg->off); 1510 break; 1511 case STACK_DYNPTR: 1512 i += BPF_DYNPTR_NR_SLOTS - 1; 1513 reg = &state->stack[i].spilled_ptr; 1514 1515 verbose(env, " fp%d", (-i - 1) * BPF_REG_SIZE); 1516 print_liveness(env, reg->live); 1517 verbose(env, "=dynptr_%s", dynptr_type_str(reg->dynptr.type)); 1518 if (reg->ref_obj_id) 1519 verbose(env, "(ref_id=%d)", reg->ref_obj_id); 1520 break; 1521 case STACK_ITER: 1522 /* only main slot has ref_obj_id set; skip others */ 1523 reg = &state->stack[i].spilled_ptr; 1524 if (!reg->ref_obj_id) 1525 continue; 1526 1527 verbose(env, " fp%d", (-i - 1) * BPF_REG_SIZE); 1528 print_liveness(env, reg->live); 1529 verbose(env, "=iter_%s(ref_id=%d,state=%s,depth=%u)", 1530 iter_type_str(reg->iter.btf, reg->iter.btf_id), 1531 reg->ref_obj_id, iter_state_str(reg->iter.state), 1532 reg->iter.depth); 1533 break; 1534 case STACK_MISC: 1535 case STACK_ZERO: 1536 default: 1537 reg = &state->stack[i].spilled_ptr; 1538 1539 for (j = 0; j < BPF_REG_SIZE; j++) 1540 types_buf[j] = slot_type_char[state->stack[i].slot_type[j]]; 1541 types_buf[BPF_REG_SIZE] = 0; 1542 1543 verbose(env, " fp%d", (-i - 1) * BPF_REG_SIZE); 1544 print_liveness(env, reg->live); 1545 verbose(env, "=%s", types_buf); 1546 break; 1547 } 1548 } 1549 if (state->acquired_refs && state->refs[0].id) { 1550 verbose(env, " refs=%d", state->refs[0].id); 1551 for (i = 1; i < state->acquired_refs; i++) 1552 if (state->refs[i].id) 1553 verbose(env, ",%d", state->refs[i].id); 1554 } 1555 if (state->in_callback_fn) 1556 verbose(env, " cb"); 1557 if (state->in_async_callback_fn) 1558 verbose(env, " async_cb"); 1559 verbose(env, "\n"); 1560 if (!print_all) 1561 mark_verifier_state_clean(env); 1562 } 1563 1564 static inline u32 vlog_alignment(u32 pos) 1565 { 1566 return round_up(max(pos + BPF_LOG_MIN_ALIGNMENT / 2, BPF_LOG_ALIGNMENT), 1567 BPF_LOG_MIN_ALIGNMENT) - pos - 1; 1568 } 1569 1570 static void print_insn_state(struct bpf_verifier_env *env, 1571 const struct bpf_func_state *state) 1572 { 1573 if (env->prev_log_pos && env->prev_log_pos == env->log.end_pos) { 1574 /* remove new line character */ 1575 bpf_vlog_reset(&env->log, env->prev_log_pos - 1); 1576 verbose(env, "%*c;", vlog_alignment(env->prev_insn_print_pos), ' '); 1577 } else { 1578 verbose(env, "%d:", env->insn_idx); 1579 } 1580 print_verifier_state(env, state, false); 1581 } 1582 1583 /* copy array src of length n * size bytes to dst. dst is reallocated if it's too 1584 * small to hold src. This is different from krealloc since we don't want to preserve 1585 * the contents of dst. 1586 * 1587 * Leaves dst untouched if src is NULL or length is zero. Returns NULL if memory could 1588 * not be allocated. 1589 */ 1590 static void *copy_array(void *dst, const void *src, size_t n, size_t size, gfp_t flags) 1591 { 1592 size_t alloc_bytes; 1593 void *orig = dst; 1594 size_t bytes; 1595 1596 if (ZERO_OR_NULL_PTR(src)) 1597 goto out; 1598 1599 if (unlikely(check_mul_overflow(n, size, &bytes))) 1600 return NULL; 1601 1602 alloc_bytes = max(ksize(orig), kmalloc_size_roundup(bytes)); 1603 dst = krealloc(orig, alloc_bytes, flags); 1604 if (!dst) { 1605 kfree(orig); 1606 return NULL; 1607 } 1608 1609 memcpy(dst, src, bytes); 1610 out: 1611 return dst ? dst : ZERO_SIZE_PTR; 1612 } 1613 1614 /* resize an array from old_n items to new_n items. the array is reallocated if it's too 1615 * small to hold new_n items. new items are zeroed out if the array grows. 1616 * 1617 * Contrary to krealloc_array, does not free arr if new_n is zero. 1618 */ 1619 static void *realloc_array(void *arr, size_t old_n, size_t new_n, size_t size) 1620 { 1621 size_t alloc_size; 1622 void *new_arr; 1623 1624 if (!new_n || old_n == new_n) 1625 goto out; 1626 1627 alloc_size = kmalloc_size_roundup(size_mul(new_n, size)); 1628 new_arr = krealloc(arr, alloc_size, GFP_KERNEL); 1629 if (!new_arr) { 1630 kfree(arr); 1631 return NULL; 1632 } 1633 arr = new_arr; 1634 1635 if (new_n > old_n) 1636 memset(arr + old_n * size, 0, (new_n - old_n) * size); 1637 1638 out: 1639 return arr ? arr : ZERO_SIZE_PTR; 1640 } 1641 1642 static int copy_reference_state(struct bpf_func_state *dst, const struct bpf_func_state *src) 1643 { 1644 dst->refs = copy_array(dst->refs, src->refs, src->acquired_refs, 1645 sizeof(struct bpf_reference_state), GFP_KERNEL); 1646 if (!dst->refs) 1647 return -ENOMEM; 1648 1649 dst->acquired_refs = src->acquired_refs; 1650 return 0; 1651 } 1652 1653 static int copy_stack_state(struct bpf_func_state *dst, const struct bpf_func_state *src) 1654 { 1655 size_t n = src->allocated_stack / BPF_REG_SIZE; 1656 1657 dst->stack = copy_array(dst->stack, src->stack, n, sizeof(struct bpf_stack_state), 1658 GFP_KERNEL); 1659 if (!dst->stack) 1660 return -ENOMEM; 1661 1662 dst->allocated_stack = src->allocated_stack; 1663 return 0; 1664 } 1665 1666 static int resize_reference_state(struct bpf_func_state *state, size_t n) 1667 { 1668 state->refs = realloc_array(state->refs, state->acquired_refs, n, 1669 sizeof(struct bpf_reference_state)); 1670 if (!state->refs) 1671 return -ENOMEM; 1672 1673 state->acquired_refs = n; 1674 return 0; 1675 } 1676 1677 static int grow_stack_state(struct bpf_func_state *state, int size) 1678 { 1679 size_t old_n = state->allocated_stack / BPF_REG_SIZE, n = size / BPF_REG_SIZE; 1680 1681 if (old_n >= n) 1682 return 0; 1683 1684 state->stack = realloc_array(state->stack, old_n, n, sizeof(struct bpf_stack_state)); 1685 if (!state->stack) 1686 return -ENOMEM; 1687 1688 state->allocated_stack = size; 1689 return 0; 1690 } 1691 1692 /* Acquire a pointer id from the env and update the state->refs to include 1693 * this new pointer reference. 1694 * On success, returns a valid pointer id to associate with the register 1695 * On failure, returns a negative errno. 1696 */ 1697 static int acquire_reference_state(struct bpf_verifier_env *env, int insn_idx) 1698 { 1699 struct bpf_func_state *state = cur_func(env); 1700 int new_ofs = state->acquired_refs; 1701 int id, err; 1702 1703 err = resize_reference_state(state, state->acquired_refs + 1); 1704 if (err) 1705 return err; 1706 id = ++env->id_gen; 1707 state->refs[new_ofs].id = id; 1708 state->refs[new_ofs].insn_idx = insn_idx; 1709 state->refs[new_ofs].callback_ref = state->in_callback_fn ? state->frameno : 0; 1710 1711 return id; 1712 } 1713 1714 /* release function corresponding to acquire_reference_state(). Idempotent. */ 1715 static int release_reference_state(struct bpf_func_state *state, int ptr_id) 1716 { 1717 int i, last_idx; 1718 1719 last_idx = state->acquired_refs - 1; 1720 for (i = 0; i < state->acquired_refs; i++) { 1721 if (state->refs[i].id == ptr_id) { 1722 /* Cannot release caller references in callbacks */ 1723 if (state->in_callback_fn && state->refs[i].callback_ref != state->frameno) 1724 return -EINVAL; 1725 if (last_idx && i != last_idx) 1726 memcpy(&state->refs[i], &state->refs[last_idx], 1727 sizeof(*state->refs)); 1728 memset(&state->refs[last_idx], 0, sizeof(*state->refs)); 1729 state->acquired_refs--; 1730 return 0; 1731 } 1732 } 1733 return -EINVAL; 1734 } 1735 1736 static void free_func_state(struct bpf_func_state *state) 1737 { 1738 if (!state) 1739 return; 1740 kfree(state->refs); 1741 kfree(state->stack); 1742 kfree(state); 1743 } 1744 1745 static void clear_jmp_history(struct bpf_verifier_state *state) 1746 { 1747 kfree(state->jmp_history); 1748 state->jmp_history = NULL; 1749 state->jmp_history_cnt = 0; 1750 } 1751 1752 static void free_verifier_state(struct bpf_verifier_state *state, 1753 bool free_self) 1754 { 1755 int i; 1756 1757 for (i = 0; i <= state->curframe; i++) { 1758 free_func_state(state->frame[i]); 1759 state->frame[i] = NULL; 1760 } 1761 clear_jmp_history(state); 1762 if (free_self) 1763 kfree(state); 1764 } 1765 1766 /* copy verifier state from src to dst growing dst stack space 1767 * when necessary to accommodate larger src stack 1768 */ 1769 static int copy_func_state(struct bpf_func_state *dst, 1770 const struct bpf_func_state *src) 1771 { 1772 int err; 1773 1774 memcpy(dst, src, offsetof(struct bpf_func_state, acquired_refs)); 1775 err = copy_reference_state(dst, src); 1776 if (err) 1777 return err; 1778 return copy_stack_state(dst, src); 1779 } 1780 1781 static int copy_verifier_state(struct bpf_verifier_state *dst_state, 1782 const struct bpf_verifier_state *src) 1783 { 1784 struct bpf_func_state *dst; 1785 int i, err; 1786 1787 dst_state->jmp_history = copy_array(dst_state->jmp_history, src->jmp_history, 1788 src->jmp_history_cnt, sizeof(struct bpf_idx_pair), 1789 GFP_USER); 1790 if (!dst_state->jmp_history) 1791 return -ENOMEM; 1792 dst_state->jmp_history_cnt = src->jmp_history_cnt; 1793 1794 /* if dst has more stack frames then src frame, free them, this is also 1795 * necessary in case of exceptional exits using bpf_throw. 1796 */ 1797 for (i = src->curframe + 1; i <= dst_state->curframe; i++) { 1798 free_func_state(dst_state->frame[i]); 1799 dst_state->frame[i] = NULL; 1800 } 1801 dst_state->speculative = src->speculative; 1802 dst_state->active_rcu_lock = src->active_rcu_lock; 1803 dst_state->curframe = src->curframe; 1804 dst_state->active_lock.ptr = src->active_lock.ptr; 1805 dst_state->active_lock.id = src->active_lock.id; 1806 dst_state->branches = src->branches; 1807 dst_state->parent = src->parent; 1808 dst_state->first_insn_idx = src->first_insn_idx; 1809 dst_state->last_insn_idx = src->last_insn_idx; 1810 dst_state->dfs_depth = src->dfs_depth; 1811 dst_state->used_as_loop_entry = src->used_as_loop_entry; 1812 for (i = 0; i <= src->curframe; i++) { 1813 dst = dst_state->frame[i]; 1814 if (!dst) { 1815 dst = kzalloc(sizeof(*dst), GFP_KERNEL); 1816 if (!dst) 1817 return -ENOMEM; 1818 dst_state->frame[i] = dst; 1819 } 1820 err = copy_func_state(dst, src->frame[i]); 1821 if (err) 1822 return err; 1823 } 1824 return 0; 1825 } 1826 1827 static u32 state_htab_size(struct bpf_verifier_env *env) 1828 { 1829 return env->prog->len; 1830 } 1831 1832 static struct bpf_verifier_state_list **explored_state(struct bpf_verifier_env *env, int idx) 1833 { 1834 struct bpf_verifier_state *cur = env->cur_state; 1835 struct bpf_func_state *state = cur->frame[cur->curframe]; 1836 1837 return &env->explored_states[(idx ^ state->callsite) % state_htab_size(env)]; 1838 } 1839 1840 static bool same_callsites(struct bpf_verifier_state *a, struct bpf_verifier_state *b) 1841 { 1842 int fr; 1843 1844 if (a->curframe != b->curframe) 1845 return false; 1846 1847 for (fr = a->curframe; fr >= 0; fr--) 1848 if (a->frame[fr]->callsite != b->frame[fr]->callsite) 1849 return false; 1850 1851 return true; 1852 } 1853 1854 /* Open coded iterators allow back-edges in the state graph in order to 1855 * check unbounded loops that iterators. 1856 * 1857 * In is_state_visited() it is necessary to know if explored states are 1858 * part of some loops in order to decide whether non-exact states 1859 * comparison could be used: 1860 * - non-exact states comparison establishes sub-state relation and uses 1861 * read and precision marks to do so, these marks are propagated from 1862 * children states and thus are not guaranteed to be final in a loop; 1863 * - exact states comparison just checks if current and explored states 1864 * are identical (and thus form a back-edge). 1865 * 1866 * Paper "A New Algorithm for Identifying Loops in Decompilation" 1867 * by Tao Wei, Jian Mao, Wei Zou and Yu Chen [1] presents a convenient 1868 * algorithm for loop structure detection and gives an overview of 1869 * relevant terminology. It also has helpful illustrations. 1870 * 1871 * [1] https://api.semanticscholar.org/CorpusID:15784067 1872 * 1873 * We use a similar algorithm but because loop nested structure is 1874 * irrelevant for verifier ours is significantly simpler and resembles 1875 * strongly connected components algorithm from Sedgewick's textbook. 1876 * 1877 * Define topmost loop entry as a first node of the loop traversed in a 1878 * depth first search starting from initial state. The goal of the loop 1879 * tracking algorithm is to associate topmost loop entries with states 1880 * derived from these entries. 1881 * 1882 * For each step in the DFS states traversal algorithm needs to identify 1883 * the following situations: 1884 * 1885 * initial initial initial 1886 * | | | 1887 * V V V 1888 * ... ... .---------> hdr 1889 * | | | | 1890 * V V | V 1891 * cur .-> succ | .------... 1892 * | | | | | | 1893 * V | V | V V 1894 * succ '-- cur | ... ... 1895 * | | | 1896 * | V V 1897 * | succ <- cur 1898 * | | 1899 * | V 1900 * | ... 1901 * | | 1902 * '----' 1903 * 1904 * (A) successor state of cur (B) successor state of cur or it's entry 1905 * not yet traversed are in current DFS path, thus cur and succ 1906 * are members of the same outermost loop 1907 * 1908 * initial initial 1909 * | | 1910 * V V 1911 * ... ... 1912 * | | 1913 * V V 1914 * .------... .------... 1915 * | | | | 1916 * V V V V 1917 * .-> hdr ... ... ... 1918 * | | | | | 1919 * | V V V V 1920 * | succ <- cur succ <- cur 1921 * | | | 1922 * | V V 1923 * | ... ... 1924 * | | | 1925 * '----' exit 1926 * 1927 * (C) successor state of cur is a part of some loop but this loop 1928 * does not include cur or successor state is not in a loop at all. 1929 * 1930 * Algorithm could be described as the following python code: 1931 * 1932 * traversed = set() # Set of traversed nodes 1933 * entries = {} # Mapping from node to loop entry 1934 * depths = {} # Depth level assigned to graph node 1935 * path = set() # Current DFS path 1936 * 1937 * # Find outermost loop entry known for n 1938 * def get_loop_entry(n): 1939 * h = entries.get(n, None) 1940 * while h in entries and entries[h] != h: 1941 * h = entries[h] 1942 * return h 1943 * 1944 * # Update n's loop entry if h's outermost entry comes 1945 * # before n's outermost entry in current DFS path. 1946 * def update_loop_entry(n, h): 1947 * n1 = get_loop_entry(n) or n 1948 * h1 = get_loop_entry(h) or h 1949 * if h1 in path and depths[h1] <= depths[n1]: 1950 * entries[n] = h1 1951 * 1952 * def dfs(n, depth): 1953 * traversed.add(n) 1954 * path.add(n) 1955 * depths[n] = depth 1956 * for succ in G.successors(n): 1957 * if succ not in traversed: 1958 * # Case A: explore succ and update cur's loop entry 1959 * # only if succ's entry is in current DFS path. 1960 * dfs(succ, depth + 1) 1961 * h = get_loop_entry(succ) 1962 * update_loop_entry(n, h) 1963 * else: 1964 * # Case B or C depending on `h1 in path` check in update_loop_entry(). 1965 * update_loop_entry(n, succ) 1966 * path.remove(n) 1967 * 1968 * To adapt this algorithm for use with verifier: 1969 * - use st->branch == 0 as a signal that DFS of succ had been finished 1970 * and cur's loop entry has to be updated (case A), handle this in 1971 * update_branch_counts(); 1972 * - use st->branch > 0 as a signal that st is in the current DFS path; 1973 * - handle cases B and C in is_state_visited(); 1974 * - update topmost loop entry for intermediate states in get_loop_entry(). 1975 */ 1976 static struct bpf_verifier_state *get_loop_entry(struct bpf_verifier_state *st) 1977 { 1978 struct bpf_verifier_state *topmost = st->loop_entry, *old; 1979 1980 while (topmost && topmost->loop_entry && topmost != topmost->loop_entry) 1981 topmost = topmost->loop_entry; 1982 /* Update loop entries for intermediate states to avoid this 1983 * traversal in future get_loop_entry() calls. 1984 */ 1985 while (st && st->loop_entry != topmost) { 1986 old = st->loop_entry; 1987 st->loop_entry = topmost; 1988 st = old; 1989 } 1990 return topmost; 1991 } 1992 1993 static void update_loop_entry(struct bpf_verifier_state *cur, struct bpf_verifier_state *hdr) 1994 { 1995 struct bpf_verifier_state *cur1, *hdr1; 1996 1997 cur1 = get_loop_entry(cur) ?: cur; 1998 hdr1 = get_loop_entry(hdr) ?: hdr; 1999 /* The head1->branches check decides between cases B and C in 2000 * comment for get_loop_entry(). If hdr1->branches == 0 then 2001 * head's topmost loop entry is not in current DFS path, 2002 * hence 'cur' and 'hdr' are not in the same loop and there is 2003 * no need to update cur->loop_entry. 2004 */ 2005 if (hdr1->branches && hdr1->dfs_depth <= cur1->dfs_depth) { 2006 cur->loop_entry = hdr; 2007 hdr->used_as_loop_entry = true; 2008 } 2009 } 2010 2011 static void update_branch_counts(struct bpf_verifier_env *env, struct bpf_verifier_state *st) 2012 { 2013 while (st) { 2014 u32 br = --st->branches; 2015 2016 /* br == 0 signals that DFS exploration for 'st' is finished, 2017 * thus it is necessary to update parent's loop entry if it 2018 * turned out that st is a part of some loop. 2019 * This is a part of 'case A' in get_loop_entry() comment. 2020 */ 2021 if (br == 0 && st->parent && st->loop_entry) 2022 update_loop_entry(st->parent, st->loop_entry); 2023 2024 /* WARN_ON(br > 1) technically makes sense here, 2025 * but see comment in push_stack(), hence: 2026 */ 2027 WARN_ONCE((int)br < 0, 2028 "BUG update_branch_counts:branches_to_explore=%d\n", 2029 br); 2030 if (br) 2031 break; 2032 st = st->parent; 2033 } 2034 } 2035 2036 static int pop_stack(struct bpf_verifier_env *env, int *prev_insn_idx, 2037 int *insn_idx, bool pop_log) 2038 { 2039 struct bpf_verifier_state *cur = env->cur_state; 2040 struct bpf_verifier_stack_elem *elem, *head = env->head; 2041 int err; 2042 2043 if (env->head == NULL) 2044 return -ENOENT; 2045 2046 if (cur) { 2047 err = copy_verifier_state(cur, &head->st); 2048 if (err) 2049 return err; 2050 } 2051 if (pop_log) 2052 bpf_vlog_reset(&env->log, head->log_pos); 2053 if (insn_idx) 2054 *insn_idx = head->insn_idx; 2055 if (prev_insn_idx) 2056 *prev_insn_idx = head->prev_insn_idx; 2057 elem = head->next; 2058 free_verifier_state(&head->st, false); 2059 kfree(head); 2060 env->head = elem; 2061 env->stack_size--; 2062 return 0; 2063 } 2064 2065 static struct bpf_verifier_state *push_stack(struct bpf_verifier_env *env, 2066 int insn_idx, int prev_insn_idx, 2067 bool speculative) 2068 { 2069 struct bpf_verifier_state *cur = env->cur_state; 2070 struct bpf_verifier_stack_elem *elem; 2071 int err; 2072 2073 elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL); 2074 if (!elem) 2075 goto err; 2076 2077 elem->insn_idx = insn_idx; 2078 elem->prev_insn_idx = prev_insn_idx; 2079 elem->next = env->head; 2080 elem->log_pos = env->log.end_pos; 2081 env->head = elem; 2082 env->stack_size++; 2083 err = copy_verifier_state(&elem->st, cur); 2084 if (err) 2085 goto err; 2086 elem->st.speculative |= speculative; 2087 if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) { 2088 verbose(env, "The sequence of %d jumps is too complex.\n", 2089 env->stack_size); 2090 goto err; 2091 } 2092 if (elem->st.parent) { 2093 ++elem->st.parent->branches; 2094 /* WARN_ON(branches > 2) technically makes sense here, 2095 * but 2096 * 1. speculative states will bump 'branches' for non-branch 2097 * instructions 2098 * 2. is_state_visited() heuristics may decide not to create 2099 * a new state for a sequence of branches and all such current 2100 * and cloned states will be pointing to a single parent state 2101 * which might have large 'branches' count. 2102 */ 2103 } 2104 return &elem->st; 2105 err: 2106 free_verifier_state(env->cur_state, true); 2107 env->cur_state = NULL; 2108 /* pop all elements and return */ 2109 while (!pop_stack(env, NULL, NULL, false)); 2110 return NULL; 2111 } 2112 2113 #define CALLER_SAVED_REGS 6 2114 static const int caller_saved[CALLER_SAVED_REGS] = { 2115 BPF_REG_0, BPF_REG_1, BPF_REG_2, BPF_REG_3, BPF_REG_4, BPF_REG_5 2116 }; 2117 2118 /* This helper doesn't clear reg->id */ 2119 static void ___mark_reg_known(struct bpf_reg_state *reg, u64 imm) 2120 { 2121 reg->var_off = tnum_const(imm); 2122 reg->smin_value = (s64)imm; 2123 reg->smax_value = (s64)imm; 2124 reg->umin_value = imm; 2125 reg->umax_value = imm; 2126 2127 reg->s32_min_value = (s32)imm; 2128 reg->s32_max_value = (s32)imm; 2129 reg->u32_min_value = (u32)imm; 2130 reg->u32_max_value = (u32)imm; 2131 } 2132 2133 /* Mark the unknown part of a register (variable offset or scalar value) as 2134 * known to have the value @imm. 2135 */ 2136 static void __mark_reg_known(struct bpf_reg_state *reg, u64 imm) 2137 { 2138 /* Clear off and union(map_ptr, range) */ 2139 memset(((u8 *)reg) + sizeof(reg->type), 0, 2140 offsetof(struct bpf_reg_state, var_off) - sizeof(reg->type)); 2141 reg->id = 0; 2142 reg->ref_obj_id = 0; 2143 ___mark_reg_known(reg, imm); 2144 } 2145 2146 static void __mark_reg32_known(struct bpf_reg_state *reg, u64 imm) 2147 { 2148 reg->var_off = tnum_const_subreg(reg->var_off, imm); 2149 reg->s32_min_value = (s32)imm; 2150 reg->s32_max_value = (s32)imm; 2151 reg->u32_min_value = (u32)imm; 2152 reg->u32_max_value = (u32)imm; 2153 } 2154 2155 /* Mark the 'variable offset' part of a register as zero. This should be 2156 * used only on registers holding a pointer type. 2157 */ 2158 static void __mark_reg_known_zero(struct bpf_reg_state *reg) 2159 { 2160 __mark_reg_known(reg, 0); 2161 } 2162 2163 static void __mark_reg_const_zero(struct bpf_reg_state *reg) 2164 { 2165 __mark_reg_known(reg, 0); 2166 reg->type = SCALAR_VALUE; 2167 } 2168 2169 static void mark_reg_known_zero(struct bpf_verifier_env *env, 2170 struct bpf_reg_state *regs, u32 regno) 2171 { 2172 if (WARN_ON(regno >= MAX_BPF_REG)) { 2173 verbose(env, "mark_reg_known_zero(regs, %u)\n", regno); 2174 /* Something bad happened, let's kill all regs */ 2175 for (regno = 0; regno < MAX_BPF_REG; regno++) 2176 __mark_reg_not_init(env, regs + regno); 2177 return; 2178 } 2179 __mark_reg_known_zero(regs + regno); 2180 } 2181 2182 static void __mark_dynptr_reg(struct bpf_reg_state *reg, enum bpf_dynptr_type type, 2183 bool first_slot, int dynptr_id) 2184 { 2185 /* reg->type has no meaning for STACK_DYNPTR, but when we set reg for 2186 * callback arguments, it does need to be CONST_PTR_TO_DYNPTR, so simply 2187 * set it unconditionally as it is ignored for STACK_DYNPTR anyway. 2188 */ 2189 __mark_reg_known_zero(reg); 2190 reg->type = CONST_PTR_TO_DYNPTR; 2191 /* Give each dynptr a unique id to uniquely associate slices to it. */ 2192 reg->id = dynptr_id; 2193 reg->dynptr.type = type; 2194 reg->dynptr.first_slot = first_slot; 2195 } 2196 2197 static void mark_ptr_not_null_reg(struct bpf_reg_state *reg) 2198 { 2199 if (base_type(reg->type) == PTR_TO_MAP_VALUE) { 2200 const struct bpf_map *map = reg->map_ptr; 2201 2202 if (map->inner_map_meta) { 2203 reg->type = CONST_PTR_TO_MAP; 2204 reg->map_ptr = map->inner_map_meta; 2205 /* transfer reg's id which is unique for every map_lookup_elem 2206 * as UID of the inner map. 2207 */ 2208 if (btf_record_has_field(map->inner_map_meta->record, BPF_TIMER)) 2209 reg->map_uid = reg->id; 2210 } else if (map->map_type == BPF_MAP_TYPE_XSKMAP) { 2211 reg->type = PTR_TO_XDP_SOCK; 2212 } else if (map->map_type == BPF_MAP_TYPE_SOCKMAP || 2213 map->map_type == BPF_MAP_TYPE_SOCKHASH) { 2214 reg->type = PTR_TO_SOCKET; 2215 } else { 2216 reg->type = PTR_TO_MAP_VALUE; 2217 } 2218 return; 2219 } 2220 2221 reg->type &= ~PTR_MAYBE_NULL; 2222 } 2223 2224 static void mark_reg_graph_node(struct bpf_reg_state *regs, u32 regno, 2225 struct btf_field_graph_root *ds_head) 2226 { 2227 __mark_reg_known_zero(®s[regno]); 2228 regs[regno].type = PTR_TO_BTF_ID | MEM_ALLOC; 2229 regs[regno].btf = ds_head->btf; 2230 regs[regno].btf_id = ds_head->value_btf_id; 2231 regs[regno].off = ds_head->node_offset; 2232 } 2233 2234 static bool reg_is_pkt_pointer(const struct bpf_reg_state *reg) 2235 { 2236 return type_is_pkt_pointer(reg->type); 2237 } 2238 2239 static bool reg_is_pkt_pointer_any(const struct bpf_reg_state *reg) 2240 { 2241 return reg_is_pkt_pointer(reg) || 2242 reg->type == PTR_TO_PACKET_END; 2243 } 2244 2245 static bool reg_is_dynptr_slice_pkt(const struct bpf_reg_state *reg) 2246 { 2247 return base_type(reg->type) == PTR_TO_MEM && 2248 (reg->type & DYNPTR_TYPE_SKB || reg->type & DYNPTR_TYPE_XDP); 2249 } 2250 2251 /* Unmodified PTR_TO_PACKET[_META,_END] register from ctx access. */ 2252 static bool reg_is_init_pkt_pointer(const struct bpf_reg_state *reg, 2253 enum bpf_reg_type which) 2254 { 2255 /* The register can already have a range from prior markings. 2256 * This is fine as long as it hasn't been advanced from its 2257 * origin. 2258 */ 2259 return reg->type == which && 2260 reg->id == 0 && 2261 reg->off == 0 && 2262 tnum_equals_const(reg->var_off, 0); 2263 } 2264 2265 /* Reset the min/max bounds of a register */ 2266 static void __mark_reg_unbounded(struct bpf_reg_state *reg) 2267 { 2268 reg->smin_value = S64_MIN; 2269 reg->smax_value = S64_MAX; 2270 reg->umin_value = 0; 2271 reg->umax_value = U64_MAX; 2272 2273 reg->s32_min_value = S32_MIN; 2274 reg->s32_max_value = S32_MAX; 2275 reg->u32_min_value = 0; 2276 reg->u32_max_value = U32_MAX; 2277 } 2278 2279 static void __mark_reg64_unbounded(struct bpf_reg_state *reg) 2280 { 2281 reg->smin_value = S64_MIN; 2282 reg->smax_value = S64_MAX; 2283 reg->umin_value = 0; 2284 reg->umax_value = U64_MAX; 2285 } 2286 2287 static void __mark_reg32_unbounded(struct bpf_reg_state *reg) 2288 { 2289 reg->s32_min_value = S32_MIN; 2290 reg->s32_max_value = S32_MAX; 2291 reg->u32_min_value = 0; 2292 reg->u32_max_value = U32_MAX; 2293 } 2294 2295 static void __update_reg32_bounds(struct bpf_reg_state *reg) 2296 { 2297 struct tnum var32_off = tnum_subreg(reg->var_off); 2298 2299 /* min signed is max(sign bit) | min(other bits) */ 2300 reg->s32_min_value = max_t(s32, reg->s32_min_value, 2301 var32_off.value | (var32_off.mask & S32_MIN)); 2302 /* max signed is min(sign bit) | max(other bits) */ 2303 reg->s32_max_value = min_t(s32, reg->s32_max_value, 2304 var32_off.value | (var32_off.mask & S32_MAX)); 2305 reg->u32_min_value = max_t(u32, reg->u32_min_value, (u32)var32_off.value); 2306 reg->u32_max_value = min(reg->u32_max_value, 2307 (u32)(var32_off.value | var32_off.mask)); 2308 } 2309 2310 static void __update_reg64_bounds(struct bpf_reg_state *reg) 2311 { 2312 /* min signed is max(sign bit) | min(other bits) */ 2313 reg->smin_value = max_t(s64, reg->smin_value, 2314 reg->var_off.value | (reg->var_off.mask & S64_MIN)); 2315 /* max signed is min(sign bit) | max(other bits) */ 2316 reg->smax_value = min_t(s64, reg->smax_value, 2317 reg->var_off.value | (reg->var_off.mask & S64_MAX)); 2318 reg->umin_value = max(reg->umin_value, reg->var_off.value); 2319 reg->umax_value = min(reg->umax_value, 2320 reg->var_off.value | reg->var_off.mask); 2321 } 2322 2323 static void __update_reg_bounds(struct bpf_reg_state *reg) 2324 { 2325 __update_reg32_bounds(reg); 2326 __update_reg64_bounds(reg); 2327 } 2328 2329 /* Uses signed min/max values to inform unsigned, and vice-versa */ 2330 static void __reg32_deduce_bounds(struct bpf_reg_state *reg) 2331 { 2332 /* Learn sign from signed bounds. 2333 * If we cannot cross the sign boundary, then signed and unsigned bounds 2334 * are the same, so combine. This works even in the negative case, e.g. 2335 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff. 2336 */ 2337 if (reg->s32_min_value >= 0 || reg->s32_max_value < 0) { 2338 reg->s32_min_value = reg->u32_min_value = 2339 max_t(u32, reg->s32_min_value, reg->u32_min_value); 2340 reg->s32_max_value = reg->u32_max_value = 2341 min_t(u32, reg->s32_max_value, reg->u32_max_value); 2342 return; 2343 } 2344 /* Learn sign from unsigned bounds. Signed bounds cross the sign 2345 * boundary, so we must be careful. 2346 */ 2347 if ((s32)reg->u32_max_value >= 0) { 2348 /* Positive. We can't learn anything from the smin, but smax 2349 * is positive, hence safe. 2350 */ 2351 reg->s32_min_value = reg->u32_min_value; 2352 reg->s32_max_value = reg->u32_max_value = 2353 min_t(u32, reg->s32_max_value, reg->u32_max_value); 2354 } else if ((s32)reg->u32_min_value < 0) { 2355 /* Negative. We can't learn anything from the smax, but smin 2356 * is negative, hence safe. 2357 */ 2358 reg->s32_min_value = reg->u32_min_value = 2359 max_t(u32, reg->s32_min_value, reg->u32_min_value); 2360 reg->s32_max_value = reg->u32_max_value; 2361 } 2362 } 2363 2364 static void __reg64_deduce_bounds(struct bpf_reg_state *reg) 2365 { 2366 /* Learn sign from signed bounds. 2367 * If we cannot cross the sign boundary, then signed and unsigned bounds 2368 * are the same, so combine. This works even in the negative case, e.g. 2369 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff. 2370 */ 2371 if (reg->smin_value >= 0 || reg->smax_value < 0) { 2372 reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value, 2373 reg->umin_value); 2374 reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value, 2375 reg->umax_value); 2376 return; 2377 } 2378 /* Learn sign from unsigned bounds. Signed bounds cross the sign 2379 * boundary, so we must be careful. 2380 */ 2381 if ((s64)reg->umax_value >= 0) { 2382 /* Positive. We can't learn anything from the smin, but smax 2383 * is positive, hence safe. 2384 */ 2385 reg->smin_value = reg->umin_value; 2386 reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value, 2387 reg->umax_value); 2388 } else if ((s64)reg->umin_value < 0) { 2389 /* Negative. We can't learn anything from the smax, but smin 2390 * is negative, hence safe. 2391 */ 2392 reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value, 2393 reg->umin_value); 2394 reg->smax_value = reg->umax_value; 2395 } 2396 } 2397 2398 static void __reg_deduce_bounds(struct bpf_reg_state *reg) 2399 { 2400 __reg32_deduce_bounds(reg); 2401 __reg64_deduce_bounds(reg); 2402 } 2403 2404 /* Attempts to improve var_off based on unsigned min/max information */ 2405 static void __reg_bound_offset(struct bpf_reg_state *reg) 2406 { 2407 struct tnum var64_off = tnum_intersect(reg->var_off, 2408 tnum_range(reg->umin_value, 2409 reg->umax_value)); 2410 struct tnum var32_off = tnum_intersect(tnum_subreg(var64_off), 2411 tnum_range(reg->u32_min_value, 2412 reg->u32_max_value)); 2413 2414 reg->var_off = tnum_or(tnum_clear_subreg(var64_off), var32_off); 2415 } 2416 2417 static void reg_bounds_sync(struct bpf_reg_state *reg) 2418 { 2419 /* We might have learned new bounds from the var_off. */ 2420 __update_reg_bounds(reg); 2421 /* We might have learned something about the sign bit. */ 2422 __reg_deduce_bounds(reg); 2423 /* We might have learned some bits from the bounds. */ 2424 __reg_bound_offset(reg); 2425 /* Intersecting with the old var_off might have improved our bounds 2426 * slightly, e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc), 2427 * then new var_off is (0; 0x7f...fc) which improves our umax. 2428 */ 2429 __update_reg_bounds(reg); 2430 } 2431 2432 static bool __reg32_bound_s64(s32 a) 2433 { 2434 return a >= 0 && a <= S32_MAX; 2435 } 2436 2437 static void __reg_assign_32_into_64(struct bpf_reg_state *reg) 2438 { 2439 reg->umin_value = reg->u32_min_value; 2440 reg->umax_value = reg->u32_max_value; 2441 2442 /* Attempt to pull 32-bit signed bounds into 64-bit bounds but must 2443 * be positive otherwise set to worse case bounds and refine later 2444 * from tnum. 2445 */ 2446 if (__reg32_bound_s64(reg->s32_min_value) && 2447 __reg32_bound_s64(reg->s32_max_value)) { 2448 reg->smin_value = reg->s32_min_value; 2449 reg->smax_value = reg->s32_max_value; 2450 } else { 2451 reg->smin_value = 0; 2452 reg->smax_value = U32_MAX; 2453 } 2454 } 2455 2456 static void __reg_combine_32_into_64(struct bpf_reg_state *reg) 2457 { 2458 /* special case when 64-bit register has upper 32-bit register 2459 * zeroed. Typically happens after zext or <<32, >>32 sequence 2460 * allowing us to use 32-bit bounds directly, 2461 */ 2462 if (tnum_equals_const(tnum_clear_subreg(reg->var_off), 0)) { 2463 __reg_assign_32_into_64(reg); 2464 } else { 2465 /* Otherwise the best we can do is push lower 32bit known and 2466 * unknown bits into register (var_off set from jmp logic) 2467 * then learn as much as possible from the 64-bit tnum 2468 * known and unknown bits. The previous smin/smax bounds are 2469 * invalid here because of jmp32 compare so mark them unknown 2470 * so they do not impact tnum bounds calculation. 2471 */ 2472 __mark_reg64_unbounded(reg); 2473 } 2474 reg_bounds_sync(reg); 2475 } 2476 2477 static bool __reg64_bound_s32(s64 a) 2478 { 2479 return a >= S32_MIN && a <= S32_MAX; 2480 } 2481 2482 static bool __reg64_bound_u32(u64 a) 2483 { 2484 return a >= U32_MIN && a <= U32_MAX; 2485 } 2486 2487 static void __reg_combine_64_into_32(struct bpf_reg_state *reg) 2488 { 2489 __mark_reg32_unbounded(reg); 2490 if (__reg64_bound_s32(reg->smin_value) && __reg64_bound_s32(reg->smax_value)) { 2491 reg->s32_min_value = (s32)reg->smin_value; 2492 reg->s32_max_value = (s32)reg->smax_value; 2493 } 2494 if (__reg64_bound_u32(reg->umin_value) && __reg64_bound_u32(reg->umax_value)) { 2495 reg->u32_min_value = (u32)reg->umin_value; 2496 reg->u32_max_value = (u32)reg->umax_value; 2497 } 2498 reg_bounds_sync(reg); 2499 } 2500 2501 /* Mark a register as having a completely unknown (scalar) value. */ 2502 static void __mark_reg_unknown(const struct bpf_verifier_env *env, 2503 struct bpf_reg_state *reg) 2504 { 2505 /* 2506 * Clear type, off, and union(map_ptr, range) and 2507 * padding between 'type' and union 2508 */ 2509 memset(reg, 0, offsetof(struct bpf_reg_state, var_off)); 2510 reg->type = SCALAR_VALUE; 2511 reg->id = 0; 2512 reg->ref_obj_id = 0; 2513 reg->var_off = tnum_unknown; 2514 reg->frameno = 0; 2515 reg->precise = !env->bpf_capable; 2516 __mark_reg_unbounded(reg); 2517 } 2518 2519 static void mark_reg_unknown(struct bpf_verifier_env *env, 2520 struct bpf_reg_state *regs, u32 regno) 2521 { 2522 if (WARN_ON(regno >= MAX_BPF_REG)) { 2523 verbose(env, "mark_reg_unknown(regs, %u)\n", regno); 2524 /* Something bad happened, let's kill all regs except FP */ 2525 for (regno = 0; regno < BPF_REG_FP; regno++) 2526 __mark_reg_not_init(env, regs + regno); 2527 return; 2528 } 2529 __mark_reg_unknown(env, regs + regno); 2530 } 2531 2532 static void __mark_reg_not_init(const struct bpf_verifier_env *env, 2533 struct bpf_reg_state *reg) 2534 { 2535 __mark_reg_unknown(env, reg); 2536 reg->type = NOT_INIT; 2537 } 2538 2539 static void mark_reg_not_init(struct bpf_verifier_env *env, 2540 struct bpf_reg_state *regs, u32 regno) 2541 { 2542 if (WARN_ON(regno >= MAX_BPF_REG)) { 2543 verbose(env, "mark_reg_not_init(regs, %u)\n", regno); 2544 /* Something bad happened, let's kill all regs except FP */ 2545 for (regno = 0; regno < BPF_REG_FP; regno++) 2546 __mark_reg_not_init(env, regs + regno); 2547 return; 2548 } 2549 __mark_reg_not_init(env, regs + regno); 2550 } 2551 2552 static void mark_btf_ld_reg(struct bpf_verifier_env *env, 2553 struct bpf_reg_state *regs, u32 regno, 2554 enum bpf_reg_type reg_type, 2555 struct btf *btf, u32 btf_id, 2556 enum bpf_type_flag flag) 2557 { 2558 if (reg_type == SCALAR_VALUE) { 2559 mark_reg_unknown(env, regs, regno); 2560 return; 2561 } 2562 mark_reg_known_zero(env, regs, regno); 2563 regs[regno].type = PTR_TO_BTF_ID | flag; 2564 regs[regno].btf = btf; 2565 regs[regno].btf_id = btf_id; 2566 } 2567 2568 #define DEF_NOT_SUBREG (0) 2569 static void init_reg_state(struct bpf_verifier_env *env, 2570 struct bpf_func_state *state) 2571 { 2572 struct bpf_reg_state *regs = state->regs; 2573 int i; 2574 2575 for (i = 0; i < MAX_BPF_REG; i++) { 2576 mark_reg_not_init(env, regs, i); 2577 regs[i].live = REG_LIVE_NONE; 2578 regs[i].parent = NULL; 2579 regs[i].subreg_def = DEF_NOT_SUBREG; 2580 } 2581 2582 /* frame pointer */ 2583 regs[BPF_REG_FP].type = PTR_TO_STACK; 2584 mark_reg_known_zero(env, regs, BPF_REG_FP); 2585 regs[BPF_REG_FP].frameno = state->frameno; 2586 } 2587 2588 #define BPF_MAIN_FUNC (-1) 2589 static void init_func_state(struct bpf_verifier_env *env, 2590 struct bpf_func_state *state, 2591 int callsite, int frameno, int subprogno) 2592 { 2593 state->callsite = callsite; 2594 state->frameno = frameno; 2595 state->subprogno = subprogno; 2596 state->callback_ret_range = tnum_range(0, 0); 2597 init_reg_state(env, state); 2598 mark_verifier_state_scratched(env); 2599 } 2600 2601 /* Similar to push_stack(), but for async callbacks */ 2602 static struct bpf_verifier_state *push_async_cb(struct bpf_verifier_env *env, 2603 int insn_idx, int prev_insn_idx, 2604 int subprog) 2605 { 2606 struct bpf_verifier_stack_elem *elem; 2607 struct bpf_func_state *frame; 2608 2609 elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL); 2610 if (!elem) 2611 goto err; 2612 2613 elem->insn_idx = insn_idx; 2614 elem->prev_insn_idx = prev_insn_idx; 2615 elem->next = env->head; 2616 elem->log_pos = env->log.end_pos; 2617 env->head = elem; 2618 env->stack_size++; 2619 if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) { 2620 verbose(env, 2621 "The sequence of %d jumps is too complex for async cb.\n", 2622 env->stack_size); 2623 goto err; 2624 } 2625 /* Unlike push_stack() do not copy_verifier_state(). 2626 * The caller state doesn't matter. 2627 * This is async callback. It starts in a fresh stack. 2628 * Initialize it similar to do_check_common(). 2629 */ 2630 elem->st.branches = 1; 2631 frame = kzalloc(sizeof(*frame), GFP_KERNEL); 2632 if (!frame) 2633 goto err; 2634 init_func_state(env, frame, 2635 BPF_MAIN_FUNC /* callsite */, 2636 0 /* frameno within this callchain */, 2637 subprog /* subprog number within this prog */); 2638 elem->st.frame[0] = frame; 2639 return &elem->st; 2640 err: 2641 free_verifier_state(env->cur_state, true); 2642 env->cur_state = NULL; 2643 /* pop all elements and return */ 2644 while (!pop_stack(env, NULL, NULL, false)); 2645 return NULL; 2646 } 2647 2648 2649 enum reg_arg_type { 2650 SRC_OP, /* register is used as source operand */ 2651 DST_OP, /* register is used as destination operand */ 2652 DST_OP_NO_MARK /* same as above, check only, don't mark */ 2653 }; 2654 2655 static int cmp_subprogs(const void *a, const void *b) 2656 { 2657 return ((struct bpf_subprog_info *)a)->start - 2658 ((struct bpf_subprog_info *)b)->start; 2659 } 2660 2661 static int find_subprog(struct bpf_verifier_env *env, int off) 2662 { 2663 struct bpf_subprog_info *p; 2664 2665 p = bsearch(&off, env->subprog_info, env->subprog_cnt, 2666 sizeof(env->subprog_info[0]), cmp_subprogs); 2667 if (!p) 2668 return -ENOENT; 2669 return p - env->subprog_info; 2670 2671 } 2672 2673 static int add_subprog(struct bpf_verifier_env *env, int off) 2674 { 2675 int insn_cnt = env->prog->len; 2676 int ret; 2677 2678 if (off >= insn_cnt || off < 0) { 2679 verbose(env, "call to invalid destination\n"); 2680 return -EINVAL; 2681 } 2682 ret = find_subprog(env, off); 2683 if (ret >= 0) 2684 return ret; 2685 if (env->subprog_cnt >= BPF_MAX_SUBPROGS) { 2686 verbose(env, "too many subprograms\n"); 2687 return -E2BIG; 2688 } 2689 /* determine subprog starts. The end is one before the next starts */ 2690 env->subprog_info[env->subprog_cnt++].start = off; 2691 sort(env->subprog_info, env->subprog_cnt, 2692 sizeof(env->subprog_info[0]), cmp_subprogs, NULL); 2693 return env->subprog_cnt - 1; 2694 } 2695 2696 static int bpf_find_exception_callback_insn_off(struct bpf_verifier_env *env) 2697 { 2698 struct bpf_prog_aux *aux = env->prog->aux; 2699 struct btf *btf = aux->btf; 2700 const struct btf_type *t; 2701 u32 main_btf_id, id; 2702 const char *name; 2703 int ret, i; 2704 2705 /* Non-zero func_info_cnt implies valid btf */ 2706 if (!aux->func_info_cnt) 2707 return 0; 2708 main_btf_id = aux->func_info[0].type_id; 2709 2710 t = btf_type_by_id(btf, main_btf_id); 2711 if (!t) { 2712 verbose(env, "invalid btf id for main subprog in func_info\n"); 2713 return -EINVAL; 2714 } 2715 2716 name = btf_find_decl_tag_value(btf, t, -1, "exception_callback:"); 2717 if (IS_ERR(name)) { 2718 ret = PTR_ERR(name); 2719 /* If there is no tag present, there is no exception callback */ 2720 if (ret == -ENOENT) 2721 ret = 0; 2722 else if (ret == -EEXIST) 2723 verbose(env, "multiple exception callback tags for main subprog\n"); 2724 return ret; 2725 } 2726 2727 ret = btf_find_by_name_kind(btf, name, BTF_KIND_FUNC); 2728 if (ret < 0) { 2729 verbose(env, "exception callback '%s' could not be found in BTF\n", name); 2730 return ret; 2731 } 2732 id = ret; 2733 t = btf_type_by_id(btf, id); 2734 if (btf_func_linkage(t) != BTF_FUNC_GLOBAL) { 2735 verbose(env, "exception callback '%s' must have global linkage\n", name); 2736 return -EINVAL; 2737 } 2738 ret = 0; 2739 for (i = 0; i < aux->func_info_cnt; i++) { 2740 if (aux->func_info[i].type_id != id) 2741 continue; 2742 ret = aux->func_info[i].insn_off; 2743 /* Further func_info and subprog checks will also happen 2744 * later, so assume this is the right insn_off for now. 2745 */ 2746 if (!ret) { 2747 verbose(env, "invalid exception callback insn_off in func_info: 0\n"); 2748 ret = -EINVAL; 2749 } 2750 } 2751 if (!ret) { 2752 verbose(env, "exception callback type id not found in func_info\n"); 2753 ret = -EINVAL; 2754 } 2755 return ret; 2756 } 2757 2758 #define MAX_KFUNC_DESCS 256 2759 #define MAX_KFUNC_BTFS 256 2760 2761 struct bpf_kfunc_desc { 2762 struct btf_func_model func_model; 2763 u32 func_id; 2764 s32 imm; 2765 u16 offset; 2766 unsigned long addr; 2767 }; 2768 2769 struct bpf_kfunc_btf { 2770 struct btf *btf; 2771 struct module *module; 2772 u16 offset; 2773 }; 2774 2775 struct bpf_kfunc_desc_tab { 2776 /* Sorted by func_id (BTF ID) and offset (fd_array offset) during 2777 * verification. JITs do lookups by bpf_insn, where func_id may not be 2778 * available, therefore at the end of verification do_misc_fixups() 2779 * sorts this by imm and offset. 2780 */ 2781 struct bpf_kfunc_desc descs[MAX_KFUNC_DESCS]; 2782 u32 nr_descs; 2783 }; 2784 2785 struct bpf_kfunc_btf_tab { 2786 struct bpf_kfunc_btf descs[MAX_KFUNC_BTFS]; 2787 u32 nr_descs; 2788 }; 2789 2790 static int kfunc_desc_cmp_by_id_off(const void *a, const void *b) 2791 { 2792 const struct bpf_kfunc_desc *d0 = a; 2793 const struct bpf_kfunc_desc *d1 = b; 2794 2795 /* func_id is not greater than BTF_MAX_TYPE */ 2796 return d0->func_id - d1->func_id ?: d0->offset - d1->offset; 2797 } 2798 2799 static int kfunc_btf_cmp_by_off(const void *a, const void *b) 2800 { 2801 const struct bpf_kfunc_btf *d0 = a; 2802 const struct bpf_kfunc_btf *d1 = b; 2803 2804 return d0->offset - d1->offset; 2805 } 2806 2807 static const struct bpf_kfunc_desc * 2808 find_kfunc_desc(const struct bpf_prog *prog, u32 func_id, u16 offset) 2809 { 2810 struct bpf_kfunc_desc desc = { 2811 .func_id = func_id, 2812 .offset = offset, 2813 }; 2814 struct bpf_kfunc_desc_tab *tab; 2815 2816 tab = prog->aux->kfunc_tab; 2817 return bsearch(&desc, tab->descs, tab->nr_descs, 2818 sizeof(tab->descs[0]), kfunc_desc_cmp_by_id_off); 2819 } 2820 2821 int bpf_get_kfunc_addr(const struct bpf_prog *prog, u32 func_id, 2822 u16 btf_fd_idx, u8 **func_addr) 2823 { 2824 const struct bpf_kfunc_desc *desc; 2825 2826 desc = find_kfunc_desc(prog, func_id, btf_fd_idx); 2827 if (!desc) 2828 return -EFAULT; 2829 2830 *func_addr = (u8 *)desc->addr; 2831 return 0; 2832 } 2833 2834 static struct btf *__find_kfunc_desc_btf(struct bpf_verifier_env *env, 2835 s16 offset) 2836 { 2837 struct bpf_kfunc_btf kf_btf = { .offset = offset }; 2838 struct bpf_kfunc_btf_tab *tab; 2839 struct bpf_kfunc_btf *b; 2840 struct module *mod; 2841 struct btf *btf; 2842 int btf_fd; 2843 2844 tab = env->prog->aux->kfunc_btf_tab; 2845 b = bsearch(&kf_btf, tab->descs, tab->nr_descs, 2846 sizeof(tab->descs[0]), kfunc_btf_cmp_by_off); 2847 if (!b) { 2848 if (tab->nr_descs == MAX_KFUNC_BTFS) { 2849 verbose(env, "too many different module BTFs\n"); 2850 return ERR_PTR(-E2BIG); 2851 } 2852 2853 if (bpfptr_is_null(env->fd_array)) { 2854 verbose(env, "kfunc offset > 0 without fd_array is invalid\n"); 2855 return ERR_PTR(-EPROTO); 2856 } 2857 2858 if (copy_from_bpfptr_offset(&btf_fd, env->fd_array, 2859 offset * sizeof(btf_fd), 2860 sizeof(btf_fd))) 2861 return ERR_PTR(-EFAULT); 2862 2863 btf = btf_get_by_fd(btf_fd); 2864 if (IS_ERR(btf)) { 2865 verbose(env, "invalid module BTF fd specified\n"); 2866 return btf; 2867 } 2868 2869 if (!btf_is_module(btf)) { 2870 verbose(env, "BTF fd for kfunc is not a module BTF\n"); 2871 btf_put(btf); 2872 return ERR_PTR(-EINVAL); 2873 } 2874 2875 mod = btf_try_get_module(btf); 2876 if (!mod) { 2877 btf_put(btf); 2878 return ERR_PTR(-ENXIO); 2879 } 2880 2881 b = &tab->descs[tab->nr_descs++]; 2882 b->btf = btf; 2883 b->module = mod; 2884 b->offset = offset; 2885 2886 sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]), 2887 kfunc_btf_cmp_by_off, NULL); 2888 } 2889 return b->btf; 2890 } 2891 2892 void bpf_free_kfunc_btf_tab(struct bpf_kfunc_btf_tab *tab) 2893 { 2894 if (!tab) 2895 return; 2896 2897 while (tab->nr_descs--) { 2898 module_put(tab->descs[tab->nr_descs].module); 2899 btf_put(tab->descs[tab->nr_descs].btf); 2900 } 2901 kfree(tab); 2902 } 2903 2904 static struct btf *find_kfunc_desc_btf(struct bpf_verifier_env *env, s16 offset) 2905 { 2906 if (offset) { 2907 if (offset < 0) { 2908 /* In the future, this can be allowed to increase limit 2909 * of fd index into fd_array, interpreted as u16. 2910 */ 2911 verbose(env, "negative offset disallowed for kernel module function call\n"); 2912 return ERR_PTR(-EINVAL); 2913 } 2914 2915 return __find_kfunc_desc_btf(env, offset); 2916 } 2917 return btf_vmlinux ?: ERR_PTR(-ENOENT); 2918 } 2919 2920 static int add_kfunc_call(struct bpf_verifier_env *env, u32 func_id, s16 offset) 2921 { 2922 const struct btf_type *func, *func_proto; 2923 struct bpf_kfunc_btf_tab *btf_tab; 2924 struct bpf_kfunc_desc_tab *tab; 2925 struct bpf_prog_aux *prog_aux; 2926 struct bpf_kfunc_desc *desc; 2927 const char *func_name; 2928 struct btf *desc_btf; 2929 unsigned long call_imm; 2930 unsigned long addr; 2931 int err; 2932 2933 prog_aux = env->prog->aux; 2934 tab = prog_aux->kfunc_tab; 2935 btf_tab = prog_aux->kfunc_btf_tab; 2936 if (!tab) { 2937 if (!btf_vmlinux) { 2938 verbose(env, "calling kernel function is not supported without CONFIG_DEBUG_INFO_BTF\n"); 2939 return -ENOTSUPP; 2940 } 2941 2942 if (!env->prog->jit_requested) { 2943 verbose(env, "JIT is required for calling kernel function\n"); 2944 return -ENOTSUPP; 2945 } 2946 2947 if (!bpf_jit_supports_kfunc_call()) { 2948 verbose(env, "JIT does not support calling kernel function\n"); 2949 return -ENOTSUPP; 2950 } 2951 2952 if (!env->prog->gpl_compatible) { 2953 verbose(env, "cannot call kernel function from non-GPL compatible program\n"); 2954 return -EINVAL; 2955 } 2956 2957 tab = kzalloc(sizeof(*tab), GFP_KERNEL); 2958 if (!tab) 2959 return -ENOMEM; 2960 prog_aux->kfunc_tab = tab; 2961 } 2962 2963 /* func_id == 0 is always invalid, but instead of returning an error, be 2964 * conservative and wait until the code elimination pass before returning 2965 * error, so that invalid calls that get pruned out can be in BPF programs 2966 * loaded from userspace. It is also required that offset be untouched 2967 * for such calls. 2968 */ 2969 if (!func_id && !offset) 2970 return 0; 2971 2972 if (!btf_tab && offset) { 2973 btf_tab = kzalloc(sizeof(*btf_tab), GFP_KERNEL); 2974 if (!btf_tab) 2975 return -ENOMEM; 2976 prog_aux->kfunc_btf_tab = btf_tab; 2977 } 2978 2979 desc_btf = find_kfunc_desc_btf(env, offset); 2980 if (IS_ERR(desc_btf)) { 2981 verbose(env, "failed to find BTF for kernel function\n"); 2982 return PTR_ERR(desc_btf); 2983 } 2984 2985 if (find_kfunc_desc(env->prog, func_id, offset)) 2986 return 0; 2987 2988 if (tab->nr_descs == MAX_KFUNC_DESCS) { 2989 verbose(env, "too many different kernel function calls\n"); 2990 return -E2BIG; 2991 } 2992 2993 func = btf_type_by_id(desc_btf, func_id); 2994 if (!func || !btf_type_is_func(func)) { 2995 verbose(env, "kernel btf_id %u is not a function\n", 2996 func_id); 2997 return -EINVAL; 2998 } 2999 func_proto = btf_type_by_id(desc_btf, func->type); 3000 if (!func_proto || !btf_type_is_func_proto(func_proto)) { 3001 verbose(env, "kernel function btf_id %u does not have a valid func_proto\n", 3002 func_id); 3003 return -EINVAL; 3004 } 3005 3006 func_name = btf_name_by_offset(desc_btf, func->name_off); 3007 addr = kallsyms_lookup_name(func_name); 3008 if (!addr) { 3009 verbose(env, "cannot find address for kernel function %s\n", 3010 func_name); 3011 return -EINVAL; 3012 } 3013 specialize_kfunc(env, func_id, offset, &addr); 3014 3015 if (bpf_jit_supports_far_kfunc_call()) { 3016 call_imm = func_id; 3017 } else { 3018 call_imm = BPF_CALL_IMM(addr); 3019 /* Check whether the relative offset overflows desc->imm */ 3020 if ((unsigned long)(s32)call_imm != call_imm) { 3021 verbose(env, "address of kernel function %s is out of range\n", 3022 func_name); 3023 return -EINVAL; 3024 } 3025 } 3026 3027 if (bpf_dev_bound_kfunc_id(func_id)) { 3028 err = bpf_dev_bound_kfunc_check(&env->log, prog_aux); 3029 if (err) 3030 return err; 3031 } 3032 3033 desc = &tab->descs[tab->nr_descs++]; 3034 desc->func_id = func_id; 3035 desc->imm = call_imm; 3036 desc->offset = offset; 3037 desc->addr = addr; 3038 err = btf_distill_func_proto(&env->log, desc_btf, 3039 func_proto, func_name, 3040 &desc->func_model); 3041 if (!err) 3042 sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]), 3043 kfunc_desc_cmp_by_id_off, NULL); 3044 return err; 3045 } 3046 3047 static int kfunc_desc_cmp_by_imm_off(const void *a, const void *b) 3048 { 3049 const struct bpf_kfunc_desc *d0 = a; 3050 const struct bpf_kfunc_desc *d1 = b; 3051 3052 if (d0->imm != d1->imm) 3053 return d0->imm < d1->imm ? -1 : 1; 3054 if (d0->offset != d1->offset) 3055 return d0->offset < d1->offset ? -1 : 1; 3056 return 0; 3057 } 3058 3059 static void sort_kfunc_descs_by_imm_off(struct bpf_prog *prog) 3060 { 3061 struct bpf_kfunc_desc_tab *tab; 3062 3063 tab = prog->aux->kfunc_tab; 3064 if (!tab) 3065 return; 3066 3067 sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]), 3068 kfunc_desc_cmp_by_imm_off, NULL); 3069 } 3070 3071 bool bpf_prog_has_kfunc_call(const struct bpf_prog *prog) 3072 { 3073 return !!prog->aux->kfunc_tab; 3074 } 3075 3076 const struct btf_func_model * 3077 bpf_jit_find_kfunc_model(const struct bpf_prog *prog, 3078 const struct bpf_insn *insn) 3079 { 3080 const struct bpf_kfunc_desc desc = { 3081 .imm = insn->imm, 3082 .offset = insn->off, 3083 }; 3084 const struct bpf_kfunc_desc *res; 3085 struct bpf_kfunc_desc_tab *tab; 3086 3087 tab = prog->aux->kfunc_tab; 3088 res = bsearch(&desc, tab->descs, tab->nr_descs, 3089 sizeof(tab->descs[0]), kfunc_desc_cmp_by_imm_off); 3090 3091 return res ? &res->func_model : NULL; 3092 } 3093 3094 static int add_subprog_and_kfunc(struct bpf_verifier_env *env) 3095 { 3096 struct bpf_subprog_info *subprog = env->subprog_info; 3097 int i, ret, insn_cnt = env->prog->len, ex_cb_insn; 3098 struct bpf_insn *insn = env->prog->insnsi; 3099 3100 /* Add entry function. */ 3101 ret = add_subprog(env, 0); 3102 if (ret) 3103 return ret; 3104 3105 for (i = 0; i < insn_cnt; i++, insn++) { 3106 if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn) && 3107 !bpf_pseudo_kfunc_call(insn)) 3108 continue; 3109 3110 if (!env->bpf_capable) { 3111 verbose(env, "loading/calling other bpf or kernel functions are allowed for CAP_BPF and CAP_SYS_ADMIN\n"); 3112 return -EPERM; 3113 } 3114 3115 if (bpf_pseudo_func(insn) || bpf_pseudo_call(insn)) 3116 ret = add_subprog(env, i + insn->imm + 1); 3117 else 3118 ret = add_kfunc_call(env, insn->imm, insn->off); 3119 3120 if (ret < 0) 3121 return ret; 3122 } 3123 3124 ret = bpf_find_exception_callback_insn_off(env); 3125 if (ret < 0) 3126 return ret; 3127 ex_cb_insn = ret; 3128 3129 /* If ex_cb_insn > 0, this means that the main program has a subprog 3130 * marked using BTF decl tag to serve as the exception callback. 3131 */ 3132 if (ex_cb_insn) { 3133 ret = add_subprog(env, ex_cb_insn); 3134 if (ret < 0) 3135 return ret; 3136 for (i = 1; i < env->subprog_cnt; i++) { 3137 if (env->subprog_info[i].start != ex_cb_insn) 3138 continue; 3139 env->exception_callback_subprog = i; 3140 break; 3141 } 3142 } 3143 3144 /* Add a fake 'exit' subprog which could simplify subprog iteration 3145 * logic. 'subprog_cnt' should not be increased. 3146 */ 3147 subprog[env->subprog_cnt].start = insn_cnt; 3148 3149 if (env->log.level & BPF_LOG_LEVEL2) 3150 for (i = 0; i < env->subprog_cnt; i++) 3151 verbose(env, "func#%d @%d\n", i, subprog[i].start); 3152 3153 return 0; 3154 } 3155 3156 static int check_subprogs(struct bpf_verifier_env *env) 3157 { 3158 int i, subprog_start, subprog_end, off, cur_subprog = 0; 3159 struct bpf_subprog_info *subprog = env->subprog_info; 3160 struct bpf_insn *insn = env->prog->insnsi; 3161 int insn_cnt = env->prog->len; 3162 3163 /* now check that all jumps are within the same subprog */ 3164 subprog_start = subprog[cur_subprog].start; 3165 subprog_end = subprog[cur_subprog + 1].start; 3166 for (i = 0; i < insn_cnt; i++) { 3167 u8 code = insn[i].code; 3168 3169 if (code == (BPF_JMP | BPF_CALL) && 3170 insn[i].src_reg == 0 && 3171 insn[i].imm == BPF_FUNC_tail_call) 3172 subprog[cur_subprog].has_tail_call = true; 3173 if (BPF_CLASS(code) == BPF_LD && 3174 (BPF_MODE(code) == BPF_ABS || BPF_MODE(code) == BPF_IND)) 3175 subprog[cur_subprog].has_ld_abs = true; 3176 if (BPF_CLASS(code) != BPF_JMP && BPF_CLASS(code) != BPF_JMP32) 3177 goto next; 3178 if (BPF_OP(code) == BPF_EXIT || BPF_OP(code) == BPF_CALL) 3179 goto next; 3180 if (code == (BPF_JMP32 | BPF_JA)) 3181 off = i + insn[i].imm + 1; 3182 else 3183 off = i + insn[i].off + 1; 3184 if (off < subprog_start || off >= subprog_end) { 3185 verbose(env, "jump out of range from insn %d to %d\n", i, off); 3186 return -EINVAL; 3187 } 3188 next: 3189 if (i == subprog_end - 1) { 3190 /* to avoid fall-through from one subprog into another 3191 * the last insn of the subprog should be either exit 3192 * or unconditional jump back or bpf_throw call 3193 */ 3194 if (code != (BPF_JMP | BPF_EXIT) && 3195 code != (BPF_JMP32 | BPF_JA) && 3196 code != (BPF_JMP | BPF_JA)) { 3197 verbose(env, "last insn is not an exit or jmp\n"); 3198 return -EINVAL; 3199 } 3200 subprog_start = subprog_end; 3201 cur_subprog++; 3202 if (cur_subprog < env->subprog_cnt) 3203 subprog_end = subprog[cur_subprog + 1].start; 3204 } 3205 } 3206 return 0; 3207 } 3208 3209 /* Parentage chain of this register (or stack slot) should take care of all 3210 * issues like callee-saved registers, stack slot allocation time, etc. 3211 */ 3212 static int mark_reg_read(struct bpf_verifier_env *env, 3213 const struct bpf_reg_state *state, 3214 struct bpf_reg_state *parent, u8 flag) 3215 { 3216 bool writes = parent == state->parent; /* Observe write marks */ 3217 int cnt = 0; 3218 3219 while (parent) { 3220 /* if read wasn't screened by an earlier write ... */ 3221 if (writes && state->live & REG_LIVE_WRITTEN) 3222 break; 3223 if (parent->live & REG_LIVE_DONE) { 3224 verbose(env, "verifier BUG type %s var_off %lld off %d\n", 3225 reg_type_str(env, parent->type), 3226 parent->var_off.value, parent->off); 3227 return -EFAULT; 3228 } 3229 /* The first condition is more likely to be true than the 3230 * second, checked it first. 3231 */ 3232 if ((parent->live & REG_LIVE_READ) == flag || 3233 parent->live & REG_LIVE_READ64) 3234 /* The parentage chain never changes and 3235 * this parent was already marked as LIVE_READ. 3236 * There is no need to keep walking the chain again and 3237 * keep re-marking all parents as LIVE_READ. 3238 * This case happens when the same register is read 3239 * multiple times without writes into it in-between. 3240 * Also, if parent has the stronger REG_LIVE_READ64 set, 3241 * then no need to set the weak REG_LIVE_READ32. 3242 */ 3243 break; 3244 /* ... then we depend on parent's value */ 3245 parent->live |= flag; 3246 /* REG_LIVE_READ64 overrides REG_LIVE_READ32. */ 3247 if (flag == REG_LIVE_READ64) 3248 parent->live &= ~REG_LIVE_READ32; 3249 state = parent; 3250 parent = state->parent; 3251 writes = true; 3252 cnt++; 3253 } 3254 3255 if (env->longest_mark_read_walk < cnt) 3256 env->longest_mark_read_walk = cnt; 3257 return 0; 3258 } 3259 3260 static int mark_dynptr_read(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 3261 { 3262 struct bpf_func_state *state = func(env, reg); 3263 int spi, ret; 3264 3265 /* For CONST_PTR_TO_DYNPTR, it must have already been done by 3266 * check_reg_arg in check_helper_call and mark_btf_func_reg_size in 3267 * check_kfunc_call. 3268 */ 3269 if (reg->type == CONST_PTR_TO_DYNPTR) 3270 return 0; 3271 spi = dynptr_get_spi(env, reg); 3272 if (spi < 0) 3273 return spi; 3274 /* Caller ensures dynptr is valid and initialized, which means spi is in 3275 * bounds and spi is the first dynptr slot. Simply mark stack slot as 3276 * read. 3277 */ 3278 ret = mark_reg_read(env, &state->stack[spi].spilled_ptr, 3279 state->stack[spi].spilled_ptr.parent, REG_LIVE_READ64); 3280 if (ret) 3281 return ret; 3282 return mark_reg_read(env, &state->stack[spi - 1].spilled_ptr, 3283 state->stack[spi - 1].spilled_ptr.parent, REG_LIVE_READ64); 3284 } 3285 3286 static int mark_iter_read(struct bpf_verifier_env *env, struct bpf_reg_state *reg, 3287 int spi, int nr_slots) 3288 { 3289 struct bpf_func_state *state = func(env, reg); 3290 int err, i; 3291 3292 for (i = 0; i < nr_slots; i++) { 3293 struct bpf_reg_state *st = &state->stack[spi - i].spilled_ptr; 3294 3295 err = mark_reg_read(env, st, st->parent, REG_LIVE_READ64); 3296 if (err) 3297 return err; 3298 3299 mark_stack_slot_scratched(env, spi - i); 3300 } 3301 3302 return 0; 3303 } 3304 3305 /* This function is supposed to be used by the following 32-bit optimization 3306 * code only. It returns TRUE if the source or destination register operates 3307 * on 64-bit, otherwise return FALSE. 3308 */ 3309 static bool is_reg64(struct bpf_verifier_env *env, struct bpf_insn *insn, 3310 u32 regno, struct bpf_reg_state *reg, enum reg_arg_type t) 3311 { 3312 u8 code, class, op; 3313 3314 code = insn->code; 3315 class = BPF_CLASS(code); 3316 op = BPF_OP(code); 3317 if (class == BPF_JMP) { 3318 /* BPF_EXIT for "main" will reach here. Return TRUE 3319 * conservatively. 3320 */ 3321 if (op == BPF_EXIT) 3322 return true; 3323 if (op == BPF_CALL) { 3324 /* BPF to BPF call will reach here because of marking 3325 * caller saved clobber with DST_OP_NO_MARK for which we 3326 * don't care the register def because they are anyway 3327 * marked as NOT_INIT already. 3328 */ 3329 if (insn->src_reg == BPF_PSEUDO_CALL) 3330 return false; 3331 /* Helper call will reach here because of arg type 3332 * check, conservatively return TRUE. 3333 */ 3334 if (t == SRC_OP) 3335 return true; 3336 3337 return false; 3338 } 3339 } 3340 3341 if (class == BPF_ALU64 && op == BPF_END && (insn->imm == 16 || insn->imm == 32)) 3342 return false; 3343 3344 if (class == BPF_ALU64 || class == BPF_JMP || 3345 (class == BPF_ALU && op == BPF_END && insn->imm == 64)) 3346 return true; 3347 3348 if (class == BPF_ALU || class == BPF_JMP32) 3349 return false; 3350 3351 if (class == BPF_LDX) { 3352 if (t != SRC_OP) 3353 return BPF_SIZE(code) == BPF_DW || BPF_MODE(code) == BPF_MEMSX; 3354 /* LDX source must be ptr. */ 3355 return true; 3356 } 3357 3358 if (class == BPF_STX) { 3359 /* BPF_STX (including atomic variants) has multiple source 3360 * operands, one of which is a ptr. Check whether the caller is 3361 * asking about it. 3362 */ 3363 if (t == SRC_OP && reg->type != SCALAR_VALUE) 3364 return true; 3365 return BPF_SIZE(code) == BPF_DW; 3366 } 3367 3368 if (class == BPF_LD) { 3369 u8 mode = BPF_MODE(code); 3370 3371 /* LD_IMM64 */ 3372 if (mode == BPF_IMM) 3373 return true; 3374 3375 /* Both LD_IND and LD_ABS return 32-bit data. */ 3376 if (t != SRC_OP) 3377 return false; 3378 3379 /* Implicit ctx ptr. */ 3380 if (regno == BPF_REG_6) 3381 return true; 3382 3383 /* Explicit source could be any width. */ 3384 return true; 3385 } 3386 3387 if (class == BPF_ST) 3388 /* The only source register for BPF_ST is a ptr. */ 3389 return true; 3390 3391 /* Conservatively return true at default. */ 3392 return true; 3393 } 3394 3395 /* Return the regno defined by the insn, or -1. */ 3396 static int insn_def_regno(const struct bpf_insn *insn) 3397 { 3398 switch (BPF_CLASS(insn->code)) { 3399 case BPF_JMP: 3400 case BPF_JMP32: 3401 case BPF_ST: 3402 return -1; 3403 case BPF_STX: 3404 if (BPF_MODE(insn->code) == BPF_ATOMIC && 3405 (insn->imm & BPF_FETCH)) { 3406 if (insn->imm == BPF_CMPXCHG) 3407 return BPF_REG_0; 3408 else 3409 return insn->src_reg; 3410 } else { 3411 return -1; 3412 } 3413 default: 3414 return insn->dst_reg; 3415 } 3416 } 3417 3418 /* Return TRUE if INSN has defined any 32-bit value explicitly. */ 3419 static bool insn_has_def32(struct bpf_verifier_env *env, struct bpf_insn *insn) 3420 { 3421 int dst_reg = insn_def_regno(insn); 3422 3423 if (dst_reg == -1) 3424 return false; 3425 3426 return !is_reg64(env, insn, dst_reg, NULL, DST_OP); 3427 } 3428 3429 static void mark_insn_zext(struct bpf_verifier_env *env, 3430 struct bpf_reg_state *reg) 3431 { 3432 s32 def_idx = reg->subreg_def; 3433 3434 if (def_idx == DEF_NOT_SUBREG) 3435 return; 3436 3437 env->insn_aux_data[def_idx - 1].zext_dst = true; 3438 /* The dst will be zero extended, so won't be sub-register anymore. */ 3439 reg->subreg_def = DEF_NOT_SUBREG; 3440 } 3441 3442 static int check_reg_arg(struct bpf_verifier_env *env, u32 regno, 3443 enum reg_arg_type t) 3444 { 3445 struct bpf_verifier_state *vstate = env->cur_state; 3446 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 3447 struct bpf_insn *insn = env->prog->insnsi + env->insn_idx; 3448 struct bpf_reg_state *reg, *regs = state->regs; 3449 bool rw64; 3450 3451 if (regno >= MAX_BPF_REG) { 3452 verbose(env, "R%d is invalid\n", regno); 3453 return -EINVAL; 3454 } 3455 3456 mark_reg_scratched(env, regno); 3457 3458 reg = ®s[regno]; 3459 rw64 = is_reg64(env, insn, regno, reg, t); 3460 if (t == SRC_OP) { 3461 /* check whether register used as source operand can be read */ 3462 if (reg->type == NOT_INIT) { 3463 verbose(env, "R%d !read_ok\n", regno); 3464 return -EACCES; 3465 } 3466 /* We don't need to worry about FP liveness because it's read-only */ 3467 if (regno == BPF_REG_FP) 3468 return 0; 3469 3470 if (rw64) 3471 mark_insn_zext(env, reg); 3472 3473 return mark_reg_read(env, reg, reg->parent, 3474 rw64 ? REG_LIVE_READ64 : REG_LIVE_READ32); 3475 } else { 3476 /* check whether register used as dest operand can be written to */ 3477 if (regno == BPF_REG_FP) { 3478 verbose(env, "frame pointer is read only\n"); 3479 return -EACCES; 3480 } 3481 reg->live |= REG_LIVE_WRITTEN; 3482 reg->subreg_def = rw64 ? DEF_NOT_SUBREG : env->insn_idx + 1; 3483 if (t == DST_OP) 3484 mark_reg_unknown(env, regs, regno); 3485 } 3486 return 0; 3487 } 3488 3489 static void mark_jmp_point(struct bpf_verifier_env *env, int idx) 3490 { 3491 env->insn_aux_data[idx].jmp_point = true; 3492 } 3493 3494 static bool is_jmp_point(struct bpf_verifier_env *env, int insn_idx) 3495 { 3496 return env->insn_aux_data[insn_idx].jmp_point; 3497 } 3498 3499 /* for any branch, call, exit record the history of jmps in the given state */ 3500 static int push_jmp_history(struct bpf_verifier_env *env, 3501 struct bpf_verifier_state *cur) 3502 { 3503 u32 cnt = cur->jmp_history_cnt; 3504 struct bpf_idx_pair *p; 3505 size_t alloc_size; 3506 3507 if (!is_jmp_point(env, env->insn_idx)) 3508 return 0; 3509 3510 cnt++; 3511 alloc_size = kmalloc_size_roundup(size_mul(cnt, sizeof(*p))); 3512 p = krealloc(cur->jmp_history, alloc_size, GFP_USER); 3513 if (!p) 3514 return -ENOMEM; 3515 p[cnt - 1].idx = env->insn_idx; 3516 p[cnt - 1].prev_idx = env->prev_insn_idx; 3517 cur->jmp_history = p; 3518 cur->jmp_history_cnt = cnt; 3519 return 0; 3520 } 3521 3522 /* Backtrack one insn at a time. If idx is not at the top of recorded 3523 * history then previous instruction came from straight line execution. 3524 * Return -ENOENT if we exhausted all instructions within given state. 3525 * 3526 * It's legal to have a bit of a looping with the same starting and ending 3527 * insn index within the same state, e.g.: 3->4->5->3, so just because current 3528 * instruction index is the same as state's first_idx doesn't mean we are 3529 * done. If there is still some jump history left, we should keep going. We 3530 * need to take into account that we might have a jump history between given 3531 * state's parent and itself, due to checkpointing. In this case, we'll have 3532 * history entry recording a jump from last instruction of parent state and 3533 * first instruction of given state. 3534 */ 3535 static int get_prev_insn_idx(struct bpf_verifier_state *st, int i, 3536 u32 *history) 3537 { 3538 u32 cnt = *history; 3539 3540 if (i == st->first_insn_idx) { 3541 if (cnt == 0) 3542 return -ENOENT; 3543 if (cnt == 1 && st->jmp_history[0].idx == i) 3544 return -ENOENT; 3545 } 3546 3547 if (cnt && st->jmp_history[cnt - 1].idx == i) { 3548 i = st->jmp_history[cnt - 1].prev_idx; 3549 (*history)--; 3550 } else { 3551 i--; 3552 } 3553 return i; 3554 } 3555 3556 static const char *disasm_kfunc_name(void *data, const struct bpf_insn *insn) 3557 { 3558 const struct btf_type *func; 3559 struct btf *desc_btf; 3560 3561 if (insn->src_reg != BPF_PSEUDO_KFUNC_CALL) 3562 return NULL; 3563 3564 desc_btf = find_kfunc_desc_btf(data, insn->off); 3565 if (IS_ERR(desc_btf)) 3566 return "<error>"; 3567 3568 func = btf_type_by_id(desc_btf, insn->imm); 3569 return btf_name_by_offset(desc_btf, func->name_off); 3570 } 3571 3572 static inline void bt_init(struct backtrack_state *bt, u32 frame) 3573 { 3574 bt->frame = frame; 3575 } 3576 3577 static inline void bt_reset(struct backtrack_state *bt) 3578 { 3579 struct bpf_verifier_env *env = bt->env; 3580 3581 memset(bt, 0, sizeof(*bt)); 3582 bt->env = env; 3583 } 3584 3585 static inline u32 bt_empty(struct backtrack_state *bt) 3586 { 3587 u64 mask = 0; 3588 int i; 3589 3590 for (i = 0; i <= bt->frame; i++) 3591 mask |= bt->reg_masks[i] | bt->stack_masks[i]; 3592 3593 return mask == 0; 3594 } 3595 3596 static inline int bt_subprog_enter(struct backtrack_state *bt) 3597 { 3598 if (bt->frame == MAX_CALL_FRAMES - 1) { 3599 verbose(bt->env, "BUG subprog enter from frame %d\n", bt->frame); 3600 WARN_ONCE(1, "verifier backtracking bug"); 3601 return -EFAULT; 3602 } 3603 bt->frame++; 3604 return 0; 3605 } 3606 3607 static inline int bt_subprog_exit(struct backtrack_state *bt) 3608 { 3609 if (bt->frame == 0) { 3610 verbose(bt->env, "BUG subprog exit from frame 0\n"); 3611 WARN_ONCE(1, "verifier backtracking bug"); 3612 return -EFAULT; 3613 } 3614 bt->frame--; 3615 return 0; 3616 } 3617 3618 static inline void bt_set_frame_reg(struct backtrack_state *bt, u32 frame, u32 reg) 3619 { 3620 bt->reg_masks[frame] |= 1 << reg; 3621 } 3622 3623 static inline void bt_clear_frame_reg(struct backtrack_state *bt, u32 frame, u32 reg) 3624 { 3625 bt->reg_masks[frame] &= ~(1 << reg); 3626 } 3627 3628 static inline void bt_set_reg(struct backtrack_state *bt, u32 reg) 3629 { 3630 bt_set_frame_reg(bt, bt->frame, reg); 3631 } 3632 3633 static inline void bt_clear_reg(struct backtrack_state *bt, u32 reg) 3634 { 3635 bt_clear_frame_reg(bt, bt->frame, reg); 3636 } 3637 3638 static inline void bt_set_frame_slot(struct backtrack_state *bt, u32 frame, u32 slot) 3639 { 3640 bt->stack_masks[frame] |= 1ull << slot; 3641 } 3642 3643 static inline void bt_clear_frame_slot(struct backtrack_state *bt, u32 frame, u32 slot) 3644 { 3645 bt->stack_masks[frame] &= ~(1ull << slot); 3646 } 3647 3648 static inline void bt_set_slot(struct backtrack_state *bt, u32 slot) 3649 { 3650 bt_set_frame_slot(bt, bt->frame, slot); 3651 } 3652 3653 static inline void bt_clear_slot(struct backtrack_state *bt, u32 slot) 3654 { 3655 bt_clear_frame_slot(bt, bt->frame, slot); 3656 } 3657 3658 static inline u32 bt_frame_reg_mask(struct backtrack_state *bt, u32 frame) 3659 { 3660 return bt->reg_masks[frame]; 3661 } 3662 3663 static inline u32 bt_reg_mask(struct backtrack_state *bt) 3664 { 3665 return bt->reg_masks[bt->frame]; 3666 } 3667 3668 static inline u64 bt_frame_stack_mask(struct backtrack_state *bt, u32 frame) 3669 { 3670 return bt->stack_masks[frame]; 3671 } 3672 3673 static inline u64 bt_stack_mask(struct backtrack_state *bt) 3674 { 3675 return bt->stack_masks[bt->frame]; 3676 } 3677 3678 static inline bool bt_is_reg_set(struct backtrack_state *bt, u32 reg) 3679 { 3680 return bt->reg_masks[bt->frame] & (1 << reg); 3681 } 3682 3683 static inline bool bt_is_slot_set(struct backtrack_state *bt, u32 slot) 3684 { 3685 return bt->stack_masks[bt->frame] & (1ull << slot); 3686 } 3687 3688 /* format registers bitmask, e.g., "r0,r2,r4" for 0x15 mask */ 3689 static void fmt_reg_mask(char *buf, ssize_t buf_sz, u32 reg_mask) 3690 { 3691 DECLARE_BITMAP(mask, 64); 3692 bool first = true; 3693 int i, n; 3694 3695 buf[0] = '\0'; 3696 3697 bitmap_from_u64(mask, reg_mask); 3698 for_each_set_bit(i, mask, 32) { 3699 n = snprintf(buf, buf_sz, "%sr%d", first ? "" : ",", i); 3700 first = false; 3701 buf += n; 3702 buf_sz -= n; 3703 if (buf_sz < 0) 3704 break; 3705 } 3706 } 3707 /* format stack slots bitmask, e.g., "-8,-24,-40" for 0x15 mask */ 3708 static void fmt_stack_mask(char *buf, ssize_t buf_sz, u64 stack_mask) 3709 { 3710 DECLARE_BITMAP(mask, 64); 3711 bool first = true; 3712 int i, n; 3713 3714 buf[0] = '\0'; 3715 3716 bitmap_from_u64(mask, stack_mask); 3717 for_each_set_bit(i, mask, 64) { 3718 n = snprintf(buf, buf_sz, "%s%d", first ? "" : ",", -(i + 1) * 8); 3719 first = false; 3720 buf += n; 3721 buf_sz -= n; 3722 if (buf_sz < 0) 3723 break; 3724 } 3725 } 3726 3727 /* For given verifier state backtrack_insn() is called from the last insn to 3728 * the first insn. Its purpose is to compute a bitmask of registers and 3729 * stack slots that needs precision in the parent verifier state. 3730 * 3731 * @idx is an index of the instruction we are currently processing; 3732 * @subseq_idx is an index of the subsequent instruction that: 3733 * - *would be* executed next, if jump history is viewed in forward order; 3734 * - *was* processed previously during backtracking. 3735 */ 3736 static int backtrack_insn(struct bpf_verifier_env *env, int idx, int subseq_idx, 3737 struct backtrack_state *bt) 3738 { 3739 const struct bpf_insn_cbs cbs = { 3740 .cb_call = disasm_kfunc_name, 3741 .cb_print = verbose, 3742 .private_data = env, 3743 }; 3744 struct bpf_insn *insn = env->prog->insnsi + idx; 3745 u8 class = BPF_CLASS(insn->code); 3746 u8 opcode = BPF_OP(insn->code); 3747 u8 mode = BPF_MODE(insn->code); 3748 u32 dreg = insn->dst_reg; 3749 u32 sreg = insn->src_reg; 3750 u32 spi, i; 3751 3752 if (insn->code == 0) 3753 return 0; 3754 if (env->log.level & BPF_LOG_LEVEL2) { 3755 fmt_reg_mask(env->tmp_str_buf, TMP_STR_BUF_LEN, bt_reg_mask(bt)); 3756 verbose(env, "mark_precise: frame%d: regs=%s ", 3757 bt->frame, env->tmp_str_buf); 3758 fmt_stack_mask(env->tmp_str_buf, TMP_STR_BUF_LEN, bt_stack_mask(bt)); 3759 verbose(env, "stack=%s before ", env->tmp_str_buf); 3760 verbose(env, "%d: ", idx); 3761 print_bpf_insn(&cbs, insn, env->allow_ptr_leaks); 3762 } 3763 3764 if (class == BPF_ALU || class == BPF_ALU64) { 3765 if (!bt_is_reg_set(bt, dreg)) 3766 return 0; 3767 if (opcode == BPF_END || opcode == BPF_NEG) { 3768 /* sreg is reserved and unused 3769 * dreg still need precision before this insn 3770 */ 3771 return 0; 3772 } else if (opcode == BPF_MOV) { 3773 if (BPF_SRC(insn->code) == BPF_X) { 3774 /* dreg = sreg or dreg = (s8, s16, s32)sreg 3775 * dreg needs precision after this insn 3776 * sreg needs precision before this insn 3777 */ 3778 bt_clear_reg(bt, dreg); 3779 bt_set_reg(bt, sreg); 3780 } else { 3781 /* dreg = K 3782 * dreg needs precision after this insn. 3783 * Corresponding register is already marked 3784 * as precise=true in this verifier state. 3785 * No further markings in parent are necessary 3786 */ 3787 bt_clear_reg(bt, dreg); 3788 } 3789 } else { 3790 if (BPF_SRC(insn->code) == BPF_X) { 3791 /* dreg += sreg 3792 * both dreg and sreg need precision 3793 * before this insn 3794 */ 3795 bt_set_reg(bt, sreg); 3796 } /* else dreg += K 3797 * dreg still needs precision before this insn 3798 */ 3799 } 3800 } else if (class == BPF_LDX) { 3801 if (!bt_is_reg_set(bt, dreg)) 3802 return 0; 3803 bt_clear_reg(bt, dreg); 3804 3805 /* scalars can only be spilled into stack w/o losing precision. 3806 * Load from any other memory can be zero extended. 3807 * The desire to keep that precision is already indicated 3808 * by 'precise' mark in corresponding register of this state. 3809 * No further tracking necessary. 3810 */ 3811 if (insn->src_reg != BPF_REG_FP) 3812 return 0; 3813 3814 /* dreg = *(u64 *)[fp - off] was a fill from the stack. 3815 * that [fp - off] slot contains scalar that needs to be 3816 * tracked with precision 3817 */ 3818 spi = (-insn->off - 1) / BPF_REG_SIZE; 3819 if (spi >= 64) { 3820 verbose(env, "BUG spi %d\n", spi); 3821 WARN_ONCE(1, "verifier backtracking bug"); 3822 return -EFAULT; 3823 } 3824 bt_set_slot(bt, spi); 3825 } else if (class == BPF_STX || class == BPF_ST) { 3826 if (bt_is_reg_set(bt, dreg)) 3827 /* stx & st shouldn't be using _scalar_ dst_reg 3828 * to access memory. It means backtracking 3829 * encountered a case of pointer subtraction. 3830 */ 3831 return -ENOTSUPP; 3832 /* scalars can only be spilled into stack */ 3833 if (insn->dst_reg != BPF_REG_FP) 3834 return 0; 3835 spi = (-insn->off - 1) / BPF_REG_SIZE; 3836 if (spi >= 64) { 3837 verbose(env, "BUG spi %d\n", spi); 3838 WARN_ONCE(1, "verifier backtracking bug"); 3839 return -EFAULT; 3840 } 3841 if (!bt_is_slot_set(bt, spi)) 3842 return 0; 3843 bt_clear_slot(bt, spi); 3844 if (class == BPF_STX) 3845 bt_set_reg(bt, sreg); 3846 } else if (class == BPF_JMP || class == BPF_JMP32) { 3847 if (bpf_pseudo_call(insn)) { 3848 int subprog_insn_idx, subprog; 3849 3850 subprog_insn_idx = idx + insn->imm + 1; 3851 subprog = find_subprog(env, subprog_insn_idx); 3852 if (subprog < 0) 3853 return -EFAULT; 3854 3855 if (subprog_is_global(env, subprog)) { 3856 /* check that jump history doesn't have any 3857 * extra instructions from subprog; the next 3858 * instruction after call to global subprog 3859 * should be literally next instruction in 3860 * caller program 3861 */ 3862 WARN_ONCE(idx + 1 != subseq_idx, "verifier backtracking bug"); 3863 /* r1-r5 are invalidated after subprog call, 3864 * so for global func call it shouldn't be set 3865 * anymore 3866 */ 3867 if (bt_reg_mask(bt) & BPF_REGMASK_ARGS) { 3868 verbose(env, "BUG regs %x\n", bt_reg_mask(bt)); 3869 WARN_ONCE(1, "verifier backtracking bug"); 3870 return -EFAULT; 3871 } 3872 /* global subprog always sets R0 */ 3873 bt_clear_reg(bt, BPF_REG_0); 3874 return 0; 3875 } else { 3876 /* static subprog call instruction, which 3877 * means that we are exiting current subprog, 3878 * so only r1-r5 could be still requested as 3879 * precise, r0 and r6-r10 or any stack slot in 3880 * the current frame should be zero by now 3881 */ 3882 if (bt_reg_mask(bt) & ~BPF_REGMASK_ARGS) { 3883 verbose(env, "BUG regs %x\n", bt_reg_mask(bt)); 3884 WARN_ONCE(1, "verifier backtracking bug"); 3885 return -EFAULT; 3886 } 3887 /* we don't track register spills perfectly, 3888 * so fallback to force-precise instead of failing */ 3889 if (bt_stack_mask(bt) != 0) 3890 return -ENOTSUPP; 3891 /* propagate r1-r5 to the caller */ 3892 for (i = BPF_REG_1; i <= BPF_REG_5; i++) { 3893 if (bt_is_reg_set(bt, i)) { 3894 bt_clear_reg(bt, i); 3895 bt_set_frame_reg(bt, bt->frame - 1, i); 3896 } 3897 } 3898 if (bt_subprog_exit(bt)) 3899 return -EFAULT; 3900 return 0; 3901 } 3902 } else if ((bpf_helper_call(insn) && 3903 is_callback_calling_function(insn->imm) && 3904 !is_async_callback_calling_function(insn->imm)) || 3905 (bpf_pseudo_kfunc_call(insn) && is_callback_calling_kfunc(insn->imm))) { 3906 /* callback-calling helper or kfunc call, which means 3907 * we are exiting from subprog, but unlike the subprog 3908 * call handling above, we shouldn't propagate 3909 * precision of r1-r5 (if any requested), as they are 3910 * not actually arguments passed directly to callback 3911 * subprogs 3912 */ 3913 if (bt_reg_mask(bt) & ~BPF_REGMASK_ARGS) { 3914 verbose(env, "BUG regs %x\n", bt_reg_mask(bt)); 3915 WARN_ONCE(1, "verifier backtracking bug"); 3916 return -EFAULT; 3917 } 3918 if (bt_stack_mask(bt) != 0) 3919 return -ENOTSUPP; 3920 /* clear r1-r5 in callback subprog's mask */ 3921 for (i = BPF_REG_1; i <= BPF_REG_5; i++) 3922 bt_clear_reg(bt, i); 3923 if (bt_subprog_exit(bt)) 3924 return -EFAULT; 3925 return 0; 3926 } else if (opcode == BPF_CALL) { 3927 /* kfunc with imm==0 is invalid and fixup_kfunc_call will 3928 * catch this error later. Make backtracking conservative 3929 * with ENOTSUPP. 3930 */ 3931 if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL && insn->imm == 0) 3932 return -ENOTSUPP; 3933 /* regular helper call sets R0 */ 3934 bt_clear_reg(bt, BPF_REG_0); 3935 if (bt_reg_mask(bt) & BPF_REGMASK_ARGS) { 3936 /* if backtracing was looking for registers R1-R5 3937 * they should have been found already. 3938 */ 3939 verbose(env, "BUG regs %x\n", bt_reg_mask(bt)); 3940 WARN_ONCE(1, "verifier backtracking bug"); 3941 return -EFAULT; 3942 } 3943 } else if (opcode == BPF_EXIT) { 3944 bool r0_precise; 3945 3946 if (bt_reg_mask(bt) & BPF_REGMASK_ARGS) { 3947 /* if backtracing was looking for registers R1-R5 3948 * they should have been found already. 3949 */ 3950 verbose(env, "BUG regs %x\n", bt_reg_mask(bt)); 3951 WARN_ONCE(1, "verifier backtracking bug"); 3952 return -EFAULT; 3953 } 3954 3955 /* BPF_EXIT in subprog or callback always returns 3956 * right after the call instruction, so by checking 3957 * whether the instruction at subseq_idx-1 is subprog 3958 * call or not we can distinguish actual exit from 3959 * *subprog* from exit from *callback*. In the former 3960 * case, we need to propagate r0 precision, if 3961 * necessary. In the former we never do that. 3962 */ 3963 r0_precise = subseq_idx - 1 >= 0 && 3964 bpf_pseudo_call(&env->prog->insnsi[subseq_idx - 1]) && 3965 bt_is_reg_set(bt, BPF_REG_0); 3966 3967 bt_clear_reg(bt, BPF_REG_0); 3968 if (bt_subprog_enter(bt)) 3969 return -EFAULT; 3970 3971 if (r0_precise) 3972 bt_set_reg(bt, BPF_REG_0); 3973 /* r6-r9 and stack slots will stay set in caller frame 3974 * bitmasks until we return back from callee(s) 3975 */ 3976 return 0; 3977 } else if (BPF_SRC(insn->code) == BPF_X) { 3978 if (!bt_is_reg_set(bt, dreg) && !bt_is_reg_set(bt, sreg)) 3979 return 0; 3980 /* dreg <cond> sreg 3981 * Both dreg and sreg need precision before 3982 * this insn. If only sreg was marked precise 3983 * before it would be equally necessary to 3984 * propagate it to dreg. 3985 */ 3986 bt_set_reg(bt, dreg); 3987 bt_set_reg(bt, sreg); 3988 /* else dreg <cond> K 3989 * Only dreg still needs precision before 3990 * this insn, so for the K-based conditional 3991 * there is nothing new to be marked. 3992 */ 3993 } 3994 } else if (class == BPF_LD) { 3995 if (!bt_is_reg_set(bt, dreg)) 3996 return 0; 3997 bt_clear_reg(bt, dreg); 3998 /* It's ld_imm64 or ld_abs or ld_ind. 3999 * For ld_imm64 no further tracking of precision 4000 * into parent is necessary 4001 */ 4002 if (mode == BPF_IND || mode == BPF_ABS) 4003 /* to be analyzed */ 4004 return -ENOTSUPP; 4005 } 4006 return 0; 4007 } 4008 4009 /* the scalar precision tracking algorithm: 4010 * . at the start all registers have precise=false. 4011 * . scalar ranges are tracked as normal through alu and jmp insns. 4012 * . once precise value of the scalar register is used in: 4013 * . ptr + scalar alu 4014 * . if (scalar cond K|scalar) 4015 * . helper_call(.., scalar, ...) where ARG_CONST is expected 4016 * backtrack through the verifier states and mark all registers and 4017 * stack slots with spilled constants that these scalar regisers 4018 * should be precise. 4019 * . during state pruning two registers (or spilled stack slots) 4020 * are equivalent if both are not precise. 4021 * 4022 * Note the verifier cannot simply walk register parentage chain, 4023 * since many different registers and stack slots could have been 4024 * used to compute single precise scalar. 4025 * 4026 * The approach of starting with precise=true for all registers and then 4027 * backtrack to mark a register as not precise when the verifier detects 4028 * that program doesn't care about specific value (e.g., when helper 4029 * takes register as ARG_ANYTHING parameter) is not safe. 4030 * 4031 * It's ok to walk single parentage chain of the verifier states. 4032 * It's possible that this backtracking will go all the way till 1st insn. 4033 * All other branches will be explored for needing precision later. 4034 * 4035 * The backtracking needs to deal with cases like: 4036 * 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) 4037 * r9 -= r8 4038 * r5 = r9 4039 * if r5 > 0x79f goto pc+7 4040 * R5_w=inv(id=0,umax_value=1951,var_off=(0x0; 0x7ff)) 4041 * r5 += 1 4042 * ... 4043 * call bpf_perf_event_output#25 4044 * where .arg5_type = ARG_CONST_SIZE_OR_ZERO 4045 * 4046 * and this case: 4047 * r6 = 1 4048 * call foo // uses callee's r6 inside to compute r0 4049 * r0 += r6 4050 * if r0 == 0 goto 4051 * 4052 * to track above reg_mask/stack_mask needs to be independent for each frame. 4053 * 4054 * Also if parent's curframe > frame where backtracking started, 4055 * the verifier need to mark registers in both frames, otherwise callees 4056 * may incorrectly prune callers. This is similar to 4057 * commit 7640ead93924 ("bpf: verifier: make sure callees don't prune with caller differences") 4058 * 4059 * For now backtracking falls back into conservative marking. 4060 */ 4061 static void mark_all_scalars_precise(struct bpf_verifier_env *env, 4062 struct bpf_verifier_state *st) 4063 { 4064 struct bpf_func_state *func; 4065 struct bpf_reg_state *reg; 4066 int i, j; 4067 4068 if (env->log.level & BPF_LOG_LEVEL2) { 4069 verbose(env, "mark_precise: frame%d: falling back to forcing all scalars precise\n", 4070 st->curframe); 4071 } 4072 4073 /* big hammer: mark all scalars precise in this path. 4074 * pop_stack may still get !precise scalars. 4075 * We also skip current state and go straight to first parent state, 4076 * because precision markings in current non-checkpointed state are 4077 * not needed. See why in the comment in __mark_chain_precision below. 4078 */ 4079 for (st = st->parent; st; st = st->parent) { 4080 for (i = 0; i <= st->curframe; i++) { 4081 func = st->frame[i]; 4082 for (j = 0; j < BPF_REG_FP; j++) { 4083 reg = &func->regs[j]; 4084 if (reg->type != SCALAR_VALUE || reg->precise) 4085 continue; 4086 reg->precise = true; 4087 if (env->log.level & BPF_LOG_LEVEL2) { 4088 verbose(env, "force_precise: frame%d: forcing r%d to be precise\n", 4089 i, j); 4090 } 4091 } 4092 for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) { 4093 if (!is_spilled_reg(&func->stack[j])) 4094 continue; 4095 reg = &func->stack[j].spilled_ptr; 4096 if (reg->type != SCALAR_VALUE || reg->precise) 4097 continue; 4098 reg->precise = true; 4099 if (env->log.level & BPF_LOG_LEVEL2) { 4100 verbose(env, "force_precise: frame%d: forcing fp%d to be precise\n", 4101 i, -(j + 1) * 8); 4102 } 4103 } 4104 } 4105 } 4106 } 4107 4108 static void mark_all_scalars_imprecise(struct bpf_verifier_env *env, struct bpf_verifier_state *st) 4109 { 4110 struct bpf_func_state *func; 4111 struct bpf_reg_state *reg; 4112 int i, j; 4113 4114 for (i = 0; i <= st->curframe; i++) { 4115 func = st->frame[i]; 4116 for (j = 0; j < BPF_REG_FP; j++) { 4117 reg = &func->regs[j]; 4118 if (reg->type != SCALAR_VALUE) 4119 continue; 4120 reg->precise = false; 4121 } 4122 for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) { 4123 if (!is_spilled_reg(&func->stack[j])) 4124 continue; 4125 reg = &func->stack[j].spilled_ptr; 4126 if (reg->type != SCALAR_VALUE) 4127 continue; 4128 reg->precise = false; 4129 } 4130 } 4131 } 4132 4133 static bool idset_contains(struct bpf_idset *s, u32 id) 4134 { 4135 u32 i; 4136 4137 for (i = 0; i < s->count; ++i) 4138 if (s->ids[i] == id) 4139 return true; 4140 4141 return false; 4142 } 4143 4144 static int idset_push(struct bpf_idset *s, u32 id) 4145 { 4146 if (WARN_ON_ONCE(s->count >= ARRAY_SIZE(s->ids))) 4147 return -EFAULT; 4148 s->ids[s->count++] = id; 4149 return 0; 4150 } 4151 4152 static void idset_reset(struct bpf_idset *s) 4153 { 4154 s->count = 0; 4155 } 4156 4157 /* Collect a set of IDs for all registers currently marked as precise in env->bt. 4158 * Mark all registers with these IDs as precise. 4159 */ 4160 static int mark_precise_scalar_ids(struct bpf_verifier_env *env, struct bpf_verifier_state *st) 4161 { 4162 struct bpf_idset *precise_ids = &env->idset_scratch; 4163 struct backtrack_state *bt = &env->bt; 4164 struct bpf_func_state *func; 4165 struct bpf_reg_state *reg; 4166 DECLARE_BITMAP(mask, 64); 4167 int i, fr; 4168 4169 idset_reset(precise_ids); 4170 4171 for (fr = bt->frame; fr >= 0; fr--) { 4172 func = st->frame[fr]; 4173 4174 bitmap_from_u64(mask, bt_frame_reg_mask(bt, fr)); 4175 for_each_set_bit(i, mask, 32) { 4176 reg = &func->regs[i]; 4177 if (!reg->id || reg->type != SCALAR_VALUE) 4178 continue; 4179 if (idset_push(precise_ids, reg->id)) 4180 return -EFAULT; 4181 } 4182 4183 bitmap_from_u64(mask, bt_frame_stack_mask(bt, fr)); 4184 for_each_set_bit(i, mask, 64) { 4185 if (i >= func->allocated_stack / BPF_REG_SIZE) 4186 break; 4187 if (!is_spilled_scalar_reg(&func->stack[i])) 4188 continue; 4189 reg = &func->stack[i].spilled_ptr; 4190 if (!reg->id) 4191 continue; 4192 if (idset_push(precise_ids, reg->id)) 4193 return -EFAULT; 4194 } 4195 } 4196 4197 for (fr = 0; fr <= st->curframe; ++fr) { 4198 func = st->frame[fr]; 4199 4200 for (i = BPF_REG_0; i < BPF_REG_10; ++i) { 4201 reg = &func->regs[i]; 4202 if (!reg->id) 4203 continue; 4204 if (!idset_contains(precise_ids, reg->id)) 4205 continue; 4206 bt_set_frame_reg(bt, fr, i); 4207 } 4208 for (i = 0; i < func->allocated_stack / BPF_REG_SIZE; ++i) { 4209 if (!is_spilled_scalar_reg(&func->stack[i])) 4210 continue; 4211 reg = &func->stack[i].spilled_ptr; 4212 if (!reg->id) 4213 continue; 4214 if (!idset_contains(precise_ids, reg->id)) 4215 continue; 4216 bt_set_frame_slot(bt, fr, i); 4217 } 4218 } 4219 4220 return 0; 4221 } 4222 4223 /* 4224 * __mark_chain_precision() backtracks BPF program instruction sequence and 4225 * chain of verifier states making sure that register *regno* (if regno >= 0) 4226 * and/or stack slot *spi* (if spi >= 0) are marked as precisely tracked 4227 * SCALARS, as well as any other registers and slots that contribute to 4228 * a tracked state of given registers/stack slots, depending on specific BPF 4229 * assembly instructions (see backtrack_insns() for exact instruction handling 4230 * logic). This backtracking relies on recorded jmp_history and is able to 4231 * traverse entire chain of parent states. This process ends only when all the 4232 * necessary registers/slots and their transitive dependencies are marked as 4233 * precise. 4234 * 4235 * One important and subtle aspect is that precise marks *do not matter* in 4236 * the currently verified state (current state). It is important to understand 4237 * why this is the case. 4238 * 4239 * First, note that current state is the state that is not yet "checkpointed", 4240 * i.e., it is not yet put into env->explored_states, and it has no children 4241 * states as well. It's ephemeral, and can end up either a) being discarded if 4242 * compatible explored state is found at some point or BPF_EXIT instruction is 4243 * reached or b) checkpointed and put into env->explored_states, branching out 4244 * into one or more children states. 4245 * 4246 * In the former case, precise markings in current state are completely 4247 * ignored by state comparison code (see regsafe() for details). Only 4248 * checkpointed ("old") state precise markings are important, and if old 4249 * state's register/slot is precise, regsafe() assumes current state's 4250 * register/slot as precise and checks value ranges exactly and precisely. If 4251 * states turn out to be compatible, current state's necessary precise 4252 * markings and any required parent states' precise markings are enforced 4253 * after the fact with propagate_precision() logic, after the fact. But it's 4254 * important to realize that in this case, even after marking current state 4255 * registers/slots as precise, we immediately discard current state. So what 4256 * actually matters is any of the precise markings propagated into current 4257 * state's parent states, which are always checkpointed (due to b) case above). 4258 * As such, for scenario a) it doesn't matter if current state has precise 4259 * markings set or not. 4260 * 4261 * Now, for the scenario b), checkpointing and forking into child(ren) 4262 * state(s). Note that before current state gets to checkpointing step, any 4263 * processed instruction always assumes precise SCALAR register/slot 4264 * knowledge: if precise value or range is useful to prune jump branch, BPF 4265 * verifier takes this opportunity enthusiastically. Similarly, when 4266 * register's value is used to calculate offset or memory address, exact 4267 * knowledge of SCALAR range is assumed, checked, and enforced. So, similar to 4268 * what we mentioned above about state comparison ignoring precise markings 4269 * during state comparison, BPF verifier ignores and also assumes precise 4270 * markings *at will* during instruction verification process. But as verifier 4271 * assumes precision, it also propagates any precision dependencies across 4272 * parent states, which are not yet finalized, so can be further restricted 4273 * based on new knowledge gained from restrictions enforced by their children 4274 * states. This is so that once those parent states are finalized, i.e., when 4275 * they have no more active children state, state comparison logic in 4276 * is_state_visited() would enforce strict and precise SCALAR ranges, if 4277 * required for correctness. 4278 * 4279 * To build a bit more intuition, note also that once a state is checkpointed, 4280 * the path we took to get to that state is not important. This is crucial 4281 * property for state pruning. When state is checkpointed and finalized at 4282 * some instruction index, it can be correctly and safely used to "short 4283 * circuit" any *compatible* state that reaches exactly the same instruction 4284 * index. I.e., if we jumped to that instruction from a completely different 4285 * code path than original finalized state was derived from, it doesn't 4286 * matter, current state can be discarded because from that instruction 4287 * forward having a compatible state will ensure we will safely reach the 4288 * exit. States describe preconditions for further exploration, but completely 4289 * forget the history of how we got here. 4290 * 4291 * This also means that even if we needed precise SCALAR range to get to 4292 * finalized state, but from that point forward *that same* SCALAR register is 4293 * never used in a precise context (i.e., it's precise value is not needed for 4294 * correctness), it's correct and safe to mark such register as "imprecise" 4295 * (i.e., precise marking set to false). This is what we rely on when we do 4296 * not set precise marking in current state. If no child state requires 4297 * precision for any given SCALAR register, it's safe to dictate that it can 4298 * be imprecise. If any child state does require this register to be precise, 4299 * we'll mark it precise later retroactively during precise markings 4300 * propagation from child state to parent states. 4301 * 4302 * Skipping precise marking setting in current state is a mild version of 4303 * relying on the above observation. But we can utilize this property even 4304 * more aggressively by proactively forgetting any precise marking in the 4305 * current state (which we inherited from the parent state), right before we 4306 * checkpoint it and branch off into new child state. This is done by 4307 * mark_all_scalars_imprecise() to hopefully get more permissive and generic 4308 * finalized states which help in short circuiting more future states. 4309 */ 4310 static int __mark_chain_precision(struct bpf_verifier_env *env, int regno) 4311 { 4312 struct backtrack_state *bt = &env->bt; 4313 struct bpf_verifier_state *st = env->cur_state; 4314 int first_idx = st->first_insn_idx; 4315 int last_idx = env->insn_idx; 4316 int subseq_idx = -1; 4317 struct bpf_func_state *func; 4318 struct bpf_reg_state *reg; 4319 bool skip_first = true; 4320 int i, fr, err; 4321 4322 if (!env->bpf_capable) 4323 return 0; 4324 4325 /* set frame number from which we are starting to backtrack */ 4326 bt_init(bt, env->cur_state->curframe); 4327 4328 /* Do sanity checks against current state of register and/or stack 4329 * slot, but don't set precise flag in current state, as precision 4330 * tracking in the current state is unnecessary. 4331 */ 4332 func = st->frame[bt->frame]; 4333 if (regno >= 0) { 4334 reg = &func->regs[regno]; 4335 if (reg->type != SCALAR_VALUE) { 4336 WARN_ONCE(1, "backtracing misuse"); 4337 return -EFAULT; 4338 } 4339 bt_set_reg(bt, regno); 4340 } 4341 4342 if (bt_empty(bt)) 4343 return 0; 4344 4345 for (;;) { 4346 DECLARE_BITMAP(mask, 64); 4347 u32 history = st->jmp_history_cnt; 4348 4349 if (env->log.level & BPF_LOG_LEVEL2) { 4350 verbose(env, "mark_precise: frame%d: last_idx %d first_idx %d subseq_idx %d \n", 4351 bt->frame, last_idx, first_idx, subseq_idx); 4352 } 4353 4354 /* If some register with scalar ID is marked as precise, 4355 * make sure that all registers sharing this ID are also precise. 4356 * This is needed to estimate effect of find_equal_scalars(). 4357 * Do this at the last instruction of each state, 4358 * bpf_reg_state::id fields are valid for these instructions. 4359 * 4360 * Allows to track precision in situation like below: 4361 * 4362 * r2 = unknown value 4363 * ... 4364 * --- state #0 --- 4365 * ... 4366 * r1 = r2 // r1 and r2 now share the same ID 4367 * ... 4368 * --- state #1 {r1.id = A, r2.id = A} --- 4369 * ... 4370 * if (r2 > 10) goto exit; // find_equal_scalars() assigns range to r1 4371 * ... 4372 * --- state #2 {r1.id = A, r2.id = A} --- 4373 * r3 = r10 4374 * r3 += r1 // need to mark both r1 and r2 4375 */ 4376 if (mark_precise_scalar_ids(env, st)) 4377 return -EFAULT; 4378 4379 if (last_idx < 0) { 4380 /* we are at the entry into subprog, which 4381 * is expected for global funcs, but only if 4382 * requested precise registers are R1-R5 4383 * (which are global func's input arguments) 4384 */ 4385 if (st->curframe == 0 && 4386 st->frame[0]->subprogno > 0 && 4387 st->frame[0]->callsite == BPF_MAIN_FUNC && 4388 bt_stack_mask(bt) == 0 && 4389 (bt_reg_mask(bt) & ~BPF_REGMASK_ARGS) == 0) { 4390 bitmap_from_u64(mask, bt_reg_mask(bt)); 4391 for_each_set_bit(i, mask, 32) { 4392 reg = &st->frame[0]->regs[i]; 4393 bt_clear_reg(bt, i); 4394 if (reg->type == SCALAR_VALUE) 4395 reg->precise = true; 4396 } 4397 return 0; 4398 } 4399 4400 verbose(env, "BUG backtracking func entry subprog %d reg_mask %x stack_mask %llx\n", 4401 st->frame[0]->subprogno, bt_reg_mask(bt), bt_stack_mask(bt)); 4402 WARN_ONCE(1, "verifier backtracking bug"); 4403 return -EFAULT; 4404 } 4405 4406 for (i = last_idx;;) { 4407 if (skip_first) { 4408 err = 0; 4409 skip_first = false; 4410 } else { 4411 err = backtrack_insn(env, i, subseq_idx, bt); 4412 } 4413 if (err == -ENOTSUPP) { 4414 mark_all_scalars_precise(env, env->cur_state); 4415 bt_reset(bt); 4416 return 0; 4417 } else if (err) { 4418 return err; 4419 } 4420 if (bt_empty(bt)) 4421 /* Found assignment(s) into tracked register in this state. 4422 * Since this state is already marked, just return. 4423 * Nothing to be tracked further in the parent state. 4424 */ 4425 return 0; 4426 subseq_idx = i; 4427 i = get_prev_insn_idx(st, i, &history); 4428 if (i == -ENOENT) 4429 break; 4430 if (i >= env->prog->len) { 4431 /* This can happen if backtracking reached insn 0 4432 * and there are still reg_mask or stack_mask 4433 * to backtrack. 4434 * It means the backtracking missed the spot where 4435 * particular register was initialized with a constant. 4436 */ 4437 verbose(env, "BUG backtracking idx %d\n", i); 4438 WARN_ONCE(1, "verifier backtracking bug"); 4439 return -EFAULT; 4440 } 4441 } 4442 st = st->parent; 4443 if (!st) 4444 break; 4445 4446 for (fr = bt->frame; fr >= 0; fr--) { 4447 func = st->frame[fr]; 4448 bitmap_from_u64(mask, bt_frame_reg_mask(bt, fr)); 4449 for_each_set_bit(i, mask, 32) { 4450 reg = &func->regs[i]; 4451 if (reg->type != SCALAR_VALUE) { 4452 bt_clear_frame_reg(bt, fr, i); 4453 continue; 4454 } 4455 if (reg->precise) 4456 bt_clear_frame_reg(bt, fr, i); 4457 else 4458 reg->precise = true; 4459 } 4460 4461 bitmap_from_u64(mask, bt_frame_stack_mask(bt, fr)); 4462 for_each_set_bit(i, mask, 64) { 4463 if (i >= func->allocated_stack / BPF_REG_SIZE) { 4464 /* the sequence of instructions: 4465 * 2: (bf) r3 = r10 4466 * 3: (7b) *(u64 *)(r3 -8) = r0 4467 * 4: (79) r4 = *(u64 *)(r10 -8) 4468 * doesn't contain jmps. It's backtracked 4469 * as a single block. 4470 * During backtracking insn 3 is not recognized as 4471 * stack access, so at the end of backtracking 4472 * stack slot fp-8 is still marked in stack_mask. 4473 * However the parent state may not have accessed 4474 * fp-8 and it's "unallocated" stack space. 4475 * In such case fallback to conservative. 4476 */ 4477 mark_all_scalars_precise(env, env->cur_state); 4478 bt_reset(bt); 4479 return 0; 4480 } 4481 4482 if (!is_spilled_scalar_reg(&func->stack[i])) { 4483 bt_clear_frame_slot(bt, fr, i); 4484 continue; 4485 } 4486 reg = &func->stack[i].spilled_ptr; 4487 if (reg->precise) 4488 bt_clear_frame_slot(bt, fr, i); 4489 else 4490 reg->precise = true; 4491 } 4492 if (env->log.level & BPF_LOG_LEVEL2) { 4493 fmt_reg_mask(env->tmp_str_buf, TMP_STR_BUF_LEN, 4494 bt_frame_reg_mask(bt, fr)); 4495 verbose(env, "mark_precise: frame%d: parent state regs=%s ", 4496 fr, env->tmp_str_buf); 4497 fmt_stack_mask(env->tmp_str_buf, TMP_STR_BUF_LEN, 4498 bt_frame_stack_mask(bt, fr)); 4499 verbose(env, "stack=%s: ", env->tmp_str_buf); 4500 print_verifier_state(env, func, true); 4501 } 4502 } 4503 4504 if (bt_empty(bt)) 4505 return 0; 4506 4507 subseq_idx = first_idx; 4508 last_idx = st->last_insn_idx; 4509 first_idx = st->first_insn_idx; 4510 } 4511 4512 /* if we still have requested precise regs or slots, we missed 4513 * something (e.g., stack access through non-r10 register), so 4514 * fallback to marking all precise 4515 */ 4516 if (!bt_empty(bt)) { 4517 mark_all_scalars_precise(env, env->cur_state); 4518 bt_reset(bt); 4519 } 4520 4521 return 0; 4522 } 4523 4524 int mark_chain_precision(struct bpf_verifier_env *env, int regno) 4525 { 4526 return __mark_chain_precision(env, regno); 4527 } 4528 4529 /* mark_chain_precision_batch() assumes that env->bt is set in the caller to 4530 * desired reg and stack masks across all relevant frames 4531 */ 4532 static int mark_chain_precision_batch(struct bpf_verifier_env *env) 4533 { 4534 return __mark_chain_precision(env, -1); 4535 } 4536 4537 static bool is_spillable_regtype(enum bpf_reg_type type) 4538 { 4539 switch (base_type(type)) { 4540 case PTR_TO_MAP_VALUE: 4541 case PTR_TO_STACK: 4542 case PTR_TO_CTX: 4543 case PTR_TO_PACKET: 4544 case PTR_TO_PACKET_META: 4545 case PTR_TO_PACKET_END: 4546 case PTR_TO_FLOW_KEYS: 4547 case CONST_PTR_TO_MAP: 4548 case PTR_TO_SOCKET: 4549 case PTR_TO_SOCK_COMMON: 4550 case PTR_TO_TCP_SOCK: 4551 case PTR_TO_XDP_SOCK: 4552 case PTR_TO_BTF_ID: 4553 case PTR_TO_BUF: 4554 case PTR_TO_MEM: 4555 case PTR_TO_FUNC: 4556 case PTR_TO_MAP_KEY: 4557 return true; 4558 default: 4559 return false; 4560 } 4561 } 4562 4563 /* Does this register contain a constant zero? */ 4564 static bool register_is_null(struct bpf_reg_state *reg) 4565 { 4566 return reg->type == SCALAR_VALUE && tnum_equals_const(reg->var_off, 0); 4567 } 4568 4569 static bool register_is_const(struct bpf_reg_state *reg) 4570 { 4571 return reg->type == SCALAR_VALUE && tnum_is_const(reg->var_off); 4572 } 4573 4574 static bool __is_scalar_unbounded(struct bpf_reg_state *reg) 4575 { 4576 return tnum_is_unknown(reg->var_off) && 4577 reg->smin_value == S64_MIN && reg->smax_value == S64_MAX && 4578 reg->umin_value == 0 && reg->umax_value == U64_MAX && 4579 reg->s32_min_value == S32_MIN && reg->s32_max_value == S32_MAX && 4580 reg->u32_min_value == 0 && reg->u32_max_value == U32_MAX; 4581 } 4582 4583 static bool register_is_bounded(struct bpf_reg_state *reg) 4584 { 4585 return reg->type == SCALAR_VALUE && !__is_scalar_unbounded(reg); 4586 } 4587 4588 static bool __is_pointer_value(bool allow_ptr_leaks, 4589 const struct bpf_reg_state *reg) 4590 { 4591 if (allow_ptr_leaks) 4592 return false; 4593 4594 return reg->type != SCALAR_VALUE; 4595 } 4596 4597 /* Copy src state preserving dst->parent and dst->live fields */ 4598 static void copy_register_state(struct bpf_reg_state *dst, const struct bpf_reg_state *src) 4599 { 4600 struct bpf_reg_state *parent = dst->parent; 4601 enum bpf_reg_liveness live = dst->live; 4602 4603 *dst = *src; 4604 dst->parent = parent; 4605 dst->live = live; 4606 } 4607 4608 static void save_register_state(struct bpf_func_state *state, 4609 int spi, struct bpf_reg_state *reg, 4610 int size) 4611 { 4612 int i; 4613 4614 copy_register_state(&state->stack[spi].spilled_ptr, reg); 4615 if (size == BPF_REG_SIZE) 4616 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN; 4617 4618 for (i = BPF_REG_SIZE; i > BPF_REG_SIZE - size; i--) 4619 state->stack[spi].slot_type[i - 1] = STACK_SPILL; 4620 4621 /* size < 8 bytes spill */ 4622 for (; i; i--) 4623 scrub_spilled_slot(&state->stack[spi].slot_type[i - 1]); 4624 } 4625 4626 static bool is_bpf_st_mem(struct bpf_insn *insn) 4627 { 4628 return BPF_CLASS(insn->code) == BPF_ST && BPF_MODE(insn->code) == BPF_MEM; 4629 } 4630 4631 /* check_stack_{read,write}_fixed_off functions track spill/fill of registers, 4632 * stack boundary and alignment are checked in check_mem_access() 4633 */ 4634 static int check_stack_write_fixed_off(struct bpf_verifier_env *env, 4635 /* stack frame we're writing to */ 4636 struct bpf_func_state *state, 4637 int off, int size, int value_regno, 4638 int insn_idx) 4639 { 4640 struct bpf_func_state *cur; /* state of the current function */ 4641 int i, slot = -off - 1, spi = slot / BPF_REG_SIZE, err; 4642 struct bpf_insn *insn = &env->prog->insnsi[insn_idx]; 4643 struct bpf_reg_state *reg = NULL; 4644 u32 dst_reg = insn->dst_reg; 4645 4646 err = grow_stack_state(state, round_up(slot + 1, BPF_REG_SIZE)); 4647 if (err) 4648 return err; 4649 /* caller checked that off % size == 0 and -MAX_BPF_STACK <= off < 0, 4650 * so it's aligned access and [off, off + size) are within stack limits 4651 */ 4652 if (!env->allow_ptr_leaks && 4653 state->stack[spi].slot_type[0] == STACK_SPILL && 4654 size != BPF_REG_SIZE) { 4655 verbose(env, "attempt to corrupt spilled pointer on stack\n"); 4656 return -EACCES; 4657 } 4658 4659 cur = env->cur_state->frame[env->cur_state->curframe]; 4660 if (value_regno >= 0) 4661 reg = &cur->regs[value_regno]; 4662 if (!env->bypass_spec_v4) { 4663 bool sanitize = reg && is_spillable_regtype(reg->type); 4664 4665 for (i = 0; i < size; i++) { 4666 u8 type = state->stack[spi].slot_type[i]; 4667 4668 if (type != STACK_MISC && type != STACK_ZERO) { 4669 sanitize = true; 4670 break; 4671 } 4672 } 4673 4674 if (sanitize) 4675 env->insn_aux_data[insn_idx].sanitize_stack_spill = true; 4676 } 4677 4678 err = destroy_if_dynptr_stack_slot(env, state, spi); 4679 if (err) 4680 return err; 4681 4682 mark_stack_slot_scratched(env, spi); 4683 if (reg && !(off % BPF_REG_SIZE) && register_is_bounded(reg) && 4684 !register_is_null(reg) && env->bpf_capable) { 4685 if (dst_reg != BPF_REG_FP) { 4686 /* The backtracking logic can only recognize explicit 4687 * stack slot address like [fp - 8]. Other spill of 4688 * scalar via different register has to be conservative. 4689 * Backtrack from here and mark all registers as precise 4690 * that contributed into 'reg' being a constant. 4691 */ 4692 err = mark_chain_precision(env, value_regno); 4693 if (err) 4694 return err; 4695 } 4696 save_register_state(state, spi, reg, size); 4697 /* Break the relation on a narrowing spill. */ 4698 if (fls64(reg->umax_value) > BITS_PER_BYTE * size) 4699 state->stack[spi].spilled_ptr.id = 0; 4700 } else if (!reg && !(off % BPF_REG_SIZE) && is_bpf_st_mem(insn) && 4701 insn->imm != 0 && env->bpf_capable) { 4702 struct bpf_reg_state fake_reg = {}; 4703 4704 __mark_reg_known(&fake_reg, insn->imm); 4705 fake_reg.type = SCALAR_VALUE; 4706 save_register_state(state, spi, &fake_reg, size); 4707 } else if (reg && is_spillable_regtype(reg->type)) { 4708 /* register containing pointer is being spilled into stack */ 4709 if (size != BPF_REG_SIZE) { 4710 verbose_linfo(env, insn_idx, "; "); 4711 verbose(env, "invalid size of register spill\n"); 4712 return -EACCES; 4713 } 4714 if (state != cur && reg->type == PTR_TO_STACK) { 4715 verbose(env, "cannot spill pointers to stack into stack frame of the caller\n"); 4716 return -EINVAL; 4717 } 4718 save_register_state(state, spi, reg, size); 4719 } else { 4720 u8 type = STACK_MISC; 4721 4722 /* regular write of data into stack destroys any spilled ptr */ 4723 state->stack[spi].spilled_ptr.type = NOT_INIT; 4724 /* Mark slots as STACK_MISC if they belonged to spilled ptr/dynptr/iter. */ 4725 if (is_stack_slot_special(&state->stack[spi])) 4726 for (i = 0; i < BPF_REG_SIZE; i++) 4727 scrub_spilled_slot(&state->stack[spi].slot_type[i]); 4728 4729 /* only mark the slot as written if all 8 bytes were written 4730 * otherwise read propagation may incorrectly stop too soon 4731 * when stack slots are partially written. 4732 * This heuristic means that read propagation will be 4733 * conservative, since it will add reg_live_read marks 4734 * to stack slots all the way to first state when programs 4735 * writes+reads less than 8 bytes 4736 */ 4737 if (size == BPF_REG_SIZE) 4738 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN; 4739 4740 /* when we zero initialize stack slots mark them as such */ 4741 if ((reg && register_is_null(reg)) || 4742 (!reg && is_bpf_st_mem(insn) && insn->imm == 0)) { 4743 /* backtracking doesn't work for STACK_ZERO yet. */ 4744 err = mark_chain_precision(env, value_regno); 4745 if (err) 4746 return err; 4747 type = STACK_ZERO; 4748 } 4749 4750 /* Mark slots affected by this stack write. */ 4751 for (i = 0; i < size; i++) 4752 state->stack[spi].slot_type[(slot - i) % BPF_REG_SIZE] = 4753 type; 4754 } 4755 return 0; 4756 } 4757 4758 /* Write the stack: 'stack[ptr_regno + off] = value_regno'. 'ptr_regno' is 4759 * known to contain a variable offset. 4760 * This function checks whether the write is permitted and conservatively 4761 * tracks the effects of the write, considering that each stack slot in the 4762 * dynamic range is potentially written to. 4763 * 4764 * 'off' includes 'regno->off'. 4765 * 'value_regno' can be -1, meaning that an unknown value is being written to 4766 * the stack. 4767 * 4768 * Spilled pointers in range are not marked as written because we don't know 4769 * what's going to be actually written. This means that read propagation for 4770 * future reads cannot be terminated by this write. 4771 * 4772 * For privileged programs, uninitialized stack slots are considered 4773 * initialized by this write (even though we don't know exactly what offsets 4774 * are going to be written to). The idea is that we don't want the verifier to 4775 * reject future reads that access slots written to through variable offsets. 4776 */ 4777 static int check_stack_write_var_off(struct bpf_verifier_env *env, 4778 /* func where register points to */ 4779 struct bpf_func_state *state, 4780 int ptr_regno, int off, int size, 4781 int value_regno, int insn_idx) 4782 { 4783 struct bpf_func_state *cur; /* state of the current function */ 4784 int min_off, max_off; 4785 int i, err; 4786 struct bpf_reg_state *ptr_reg = NULL, *value_reg = NULL; 4787 struct bpf_insn *insn = &env->prog->insnsi[insn_idx]; 4788 bool writing_zero = false; 4789 /* set if the fact that we're writing a zero is used to let any 4790 * stack slots remain STACK_ZERO 4791 */ 4792 bool zero_used = false; 4793 4794 cur = env->cur_state->frame[env->cur_state->curframe]; 4795 ptr_reg = &cur->regs[ptr_regno]; 4796 min_off = ptr_reg->smin_value + off; 4797 max_off = ptr_reg->smax_value + off + size; 4798 if (value_regno >= 0) 4799 value_reg = &cur->regs[value_regno]; 4800 if ((value_reg && register_is_null(value_reg)) || 4801 (!value_reg && is_bpf_st_mem(insn) && insn->imm == 0)) 4802 writing_zero = true; 4803 4804 err = grow_stack_state(state, round_up(-min_off, BPF_REG_SIZE)); 4805 if (err) 4806 return err; 4807 4808 for (i = min_off; i < max_off; i++) { 4809 int spi; 4810 4811 spi = __get_spi(i); 4812 err = destroy_if_dynptr_stack_slot(env, state, spi); 4813 if (err) 4814 return err; 4815 } 4816 4817 /* Variable offset writes destroy any spilled pointers in range. */ 4818 for (i = min_off; i < max_off; i++) { 4819 u8 new_type, *stype; 4820 int slot, spi; 4821 4822 slot = -i - 1; 4823 spi = slot / BPF_REG_SIZE; 4824 stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE]; 4825 mark_stack_slot_scratched(env, spi); 4826 4827 if (!env->allow_ptr_leaks && *stype != STACK_MISC && *stype != STACK_ZERO) { 4828 /* Reject the write if range we may write to has not 4829 * been initialized beforehand. If we didn't reject 4830 * here, the ptr status would be erased below (even 4831 * though not all slots are actually overwritten), 4832 * possibly opening the door to leaks. 4833 * 4834 * We do however catch STACK_INVALID case below, and 4835 * only allow reading possibly uninitialized memory 4836 * later for CAP_PERFMON, as the write may not happen to 4837 * that slot. 4838 */ 4839 verbose(env, "spilled ptr in range of var-offset stack write; insn %d, ptr off: %d", 4840 insn_idx, i); 4841 return -EINVAL; 4842 } 4843 4844 /* Erase all spilled pointers. */ 4845 state->stack[spi].spilled_ptr.type = NOT_INIT; 4846 4847 /* Update the slot type. */ 4848 new_type = STACK_MISC; 4849 if (writing_zero && *stype == STACK_ZERO) { 4850 new_type = STACK_ZERO; 4851 zero_used = true; 4852 } 4853 /* If the slot is STACK_INVALID, we check whether it's OK to 4854 * pretend that it will be initialized by this write. The slot 4855 * might not actually be written to, and so if we mark it as 4856 * initialized future reads might leak uninitialized memory. 4857 * For privileged programs, we will accept such reads to slots 4858 * that may or may not be written because, if we're reject 4859 * them, the error would be too confusing. 4860 */ 4861 if (*stype == STACK_INVALID && !env->allow_uninit_stack) { 4862 verbose(env, "uninit stack in range of var-offset write prohibited for !root; insn %d, off: %d", 4863 insn_idx, i); 4864 return -EINVAL; 4865 } 4866 *stype = new_type; 4867 } 4868 if (zero_used) { 4869 /* backtracking doesn't work for STACK_ZERO yet. */ 4870 err = mark_chain_precision(env, value_regno); 4871 if (err) 4872 return err; 4873 } 4874 return 0; 4875 } 4876 4877 /* When register 'dst_regno' is assigned some values from stack[min_off, 4878 * max_off), we set the register's type according to the types of the 4879 * respective stack slots. If all the stack values are known to be zeros, then 4880 * so is the destination reg. Otherwise, the register is considered to be 4881 * SCALAR. This function does not deal with register filling; the caller must 4882 * ensure that all spilled registers in the stack range have been marked as 4883 * read. 4884 */ 4885 static void mark_reg_stack_read(struct bpf_verifier_env *env, 4886 /* func where src register points to */ 4887 struct bpf_func_state *ptr_state, 4888 int min_off, int max_off, int dst_regno) 4889 { 4890 struct bpf_verifier_state *vstate = env->cur_state; 4891 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 4892 int i, slot, spi; 4893 u8 *stype; 4894 int zeros = 0; 4895 4896 for (i = min_off; i < max_off; i++) { 4897 slot = -i - 1; 4898 spi = slot / BPF_REG_SIZE; 4899 mark_stack_slot_scratched(env, spi); 4900 stype = ptr_state->stack[spi].slot_type; 4901 if (stype[slot % BPF_REG_SIZE] != STACK_ZERO) 4902 break; 4903 zeros++; 4904 } 4905 if (zeros == max_off - min_off) { 4906 /* any access_size read into register is zero extended, 4907 * so the whole register == const_zero 4908 */ 4909 __mark_reg_const_zero(&state->regs[dst_regno]); 4910 /* backtracking doesn't support STACK_ZERO yet, 4911 * so mark it precise here, so that later 4912 * backtracking can stop here. 4913 * Backtracking may not need this if this register 4914 * doesn't participate in pointer adjustment. 4915 * Forward propagation of precise flag is not 4916 * necessary either. This mark is only to stop 4917 * backtracking. Any register that contributed 4918 * to const 0 was marked precise before spill. 4919 */ 4920 state->regs[dst_regno].precise = true; 4921 } else { 4922 /* have read misc data from the stack */ 4923 mark_reg_unknown(env, state->regs, dst_regno); 4924 } 4925 state->regs[dst_regno].live |= REG_LIVE_WRITTEN; 4926 } 4927 4928 /* Read the stack at 'off' and put the results into the register indicated by 4929 * 'dst_regno'. It handles reg filling if the addressed stack slot is a 4930 * spilled reg. 4931 * 4932 * 'dst_regno' can be -1, meaning that the read value is not going to a 4933 * register. 4934 * 4935 * The access is assumed to be within the current stack bounds. 4936 */ 4937 static int check_stack_read_fixed_off(struct bpf_verifier_env *env, 4938 /* func where src register points to */ 4939 struct bpf_func_state *reg_state, 4940 int off, int size, int dst_regno) 4941 { 4942 struct bpf_verifier_state *vstate = env->cur_state; 4943 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 4944 int i, slot = -off - 1, spi = slot / BPF_REG_SIZE; 4945 struct bpf_reg_state *reg; 4946 u8 *stype, type; 4947 4948 stype = reg_state->stack[spi].slot_type; 4949 reg = ®_state->stack[spi].spilled_ptr; 4950 4951 mark_stack_slot_scratched(env, spi); 4952 4953 if (is_spilled_reg(®_state->stack[spi])) { 4954 u8 spill_size = 1; 4955 4956 for (i = BPF_REG_SIZE - 1; i > 0 && stype[i - 1] == STACK_SPILL; i--) 4957 spill_size++; 4958 4959 if (size != BPF_REG_SIZE || spill_size != BPF_REG_SIZE) { 4960 if (reg->type != SCALAR_VALUE) { 4961 verbose_linfo(env, env->insn_idx, "; "); 4962 verbose(env, "invalid size of register fill\n"); 4963 return -EACCES; 4964 } 4965 4966 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64); 4967 if (dst_regno < 0) 4968 return 0; 4969 4970 if (!(off % BPF_REG_SIZE) && size == spill_size) { 4971 /* The earlier check_reg_arg() has decided the 4972 * subreg_def for this insn. Save it first. 4973 */ 4974 s32 subreg_def = state->regs[dst_regno].subreg_def; 4975 4976 copy_register_state(&state->regs[dst_regno], reg); 4977 state->regs[dst_regno].subreg_def = subreg_def; 4978 } else { 4979 for (i = 0; i < size; i++) { 4980 type = stype[(slot - i) % BPF_REG_SIZE]; 4981 if (type == STACK_SPILL) 4982 continue; 4983 if (type == STACK_MISC) 4984 continue; 4985 if (type == STACK_INVALID && env->allow_uninit_stack) 4986 continue; 4987 verbose(env, "invalid read from stack off %d+%d size %d\n", 4988 off, i, size); 4989 return -EACCES; 4990 } 4991 mark_reg_unknown(env, state->regs, dst_regno); 4992 } 4993 state->regs[dst_regno].live |= REG_LIVE_WRITTEN; 4994 return 0; 4995 } 4996 4997 if (dst_regno >= 0) { 4998 /* restore register state from stack */ 4999 copy_register_state(&state->regs[dst_regno], reg); 5000 /* mark reg as written since spilled pointer state likely 5001 * has its liveness marks cleared by is_state_visited() 5002 * which resets stack/reg liveness for state transitions 5003 */ 5004 state->regs[dst_regno].live |= REG_LIVE_WRITTEN; 5005 } else if (__is_pointer_value(env->allow_ptr_leaks, reg)) { 5006 /* If dst_regno==-1, the caller is asking us whether 5007 * it is acceptable to use this value as a SCALAR_VALUE 5008 * (e.g. for XADD). 5009 * We must not allow unprivileged callers to do that 5010 * with spilled pointers. 5011 */ 5012 verbose(env, "leaking pointer from stack off %d\n", 5013 off); 5014 return -EACCES; 5015 } 5016 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64); 5017 } else { 5018 for (i = 0; i < size; i++) { 5019 type = stype[(slot - i) % BPF_REG_SIZE]; 5020 if (type == STACK_MISC) 5021 continue; 5022 if (type == STACK_ZERO) 5023 continue; 5024 if (type == STACK_INVALID && env->allow_uninit_stack) 5025 continue; 5026 verbose(env, "invalid read from stack off %d+%d size %d\n", 5027 off, i, size); 5028 return -EACCES; 5029 } 5030 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64); 5031 if (dst_regno >= 0) 5032 mark_reg_stack_read(env, reg_state, off, off + size, dst_regno); 5033 } 5034 return 0; 5035 } 5036 5037 enum bpf_access_src { 5038 ACCESS_DIRECT = 1, /* the access is performed by an instruction */ 5039 ACCESS_HELPER = 2, /* the access is performed by a helper */ 5040 }; 5041 5042 static int check_stack_range_initialized(struct bpf_verifier_env *env, 5043 int regno, int off, int access_size, 5044 bool zero_size_allowed, 5045 enum bpf_access_src type, 5046 struct bpf_call_arg_meta *meta); 5047 5048 static struct bpf_reg_state *reg_state(struct bpf_verifier_env *env, int regno) 5049 { 5050 return cur_regs(env) + regno; 5051 } 5052 5053 /* Read the stack at 'ptr_regno + off' and put the result into the register 5054 * 'dst_regno'. 5055 * 'off' includes the pointer register's fixed offset(i.e. 'ptr_regno.off'), 5056 * but not its variable offset. 5057 * 'size' is assumed to be <= reg size and the access is assumed to be aligned. 5058 * 5059 * As opposed to check_stack_read_fixed_off, this function doesn't deal with 5060 * filling registers (i.e. reads of spilled register cannot be detected when 5061 * the offset is not fixed). We conservatively mark 'dst_regno' as containing 5062 * SCALAR_VALUE. That's why we assert that the 'ptr_regno' has a variable 5063 * offset; for a fixed offset check_stack_read_fixed_off should be used 5064 * instead. 5065 */ 5066 static int check_stack_read_var_off(struct bpf_verifier_env *env, 5067 int ptr_regno, int off, int size, int dst_regno) 5068 { 5069 /* The state of the source register. */ 5070 struct bpf_reg_state *reg = reg_state(env, ptr_regno); 5071 struct bpf_func_state *ptr_state = func(env, reg); 5072 int err; 5073 int min_off, max_off; 5074 5075 /* Note that we pass a NULL meta, so raw access will not be permitted. 5076 */ 5077 err = check_stack_range_initialized(env, ptr_regno, off, size, 5078 false, ACCESS_DIRECT, NULL); 5079 if (err) 5080 return err; 5081 5082 min_off = reg->smin_value + off; 5083 max_off = reg->smax_value + off; 5084 mark_reg_stack_read(env, ptr_state, min_off, max_off + size, dst_regno); 5085 return 0; 5086 } 5087 5088 /* check_stack_read dispatches to check_stack_read_fixed_off or 5089 * check_stack_read_var_off. 5090 * 5091 * The caller must ensure that the offset falls within the allocated stack 5092 * bounds. 5093 * 5094 * 'dst_regno' is a register which will receive the value from the stack. It 5095 * can be -1, meaning that the read value is not going to a register. 5096 */ 5097 static int check_stack_read(struct bpf_verifier_env *env, 5098 int ptr_regno, int off, int size, 5099 int dst_regno) 5100 { 5101 struct bpf_reg_state *reg = reg_state(env, ptr_regno); 5102 struct bpf_func_state *state = func(env, reg); 5103 int err; 5104 /* Some accesses are only permitted with a static offset. */ 5105 bool var_off = !tnum_is_const(reg->var_off); 5106 5107 /* The offset is required to be static when reads don't go to a 5108 * register, in order to not leak pointers (see 5109 * check_stack_read_fixed_off). 5110 */ 5111 if (dst_regno < 0 && var_off) { 5112 char tn_buf[48]; 5113 5114 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 5115 verbose(env, "variable offset stack pointer cannot be passed into helper function; var_off=%s off=%d size=%d\n", 5116 tn_buf, off, size); 5117 return -EACCES; 5118 } 5119 /* Variable offset is prohibited for unprivileged mode for simplicity 5120 * since it requires corresponding support in Spectre masking for stack 5121 * ALU. See also retrieve_ptr_limit(). The check in 5122 * check_stack_access_for_ptr_arithmetic() called by 5123 * adjust_ptr_min_max_vals() prevents users from creating stack pointers 5124 * with variable offsets, therefore no check is required here. Further, 5125 * just checking it here would be insufficient as speculative stack 5126 * writes could still lead to unsafe speculative behaviour. 5127 */ 5128 if (!var_off) { 5129 off += reg->var_off.value; 5130 err = check_stack_read_fixed_off(env, state, off, size, 5131 dst_regno); 5132 } else { 5133 /* Variable offset stack reads need more conservative handling 5134 * than fixed offset ones. Note that dst_regno >= 0 on this 5135 * branch. 5136 */ 5137 err = check_stack_read_var_off(env, ptr_regno, off, size, 5138 dst_regno); 5139 } 5140 return err; 5141 } 5142 5143 5144 /* check_stack_write dispatches to check_stack_write_fixed_off or 5145 * check_stack_write_var_off. 5146 * 5147 * 'ptr_regno' is the register used as a pointer into the stack. 5148 * 'off' includes 'ptr_regno->off', but not its variable offset (if any). 5149 * 'value_regno' is the register whose value we're writing to the stack. It can 5150 * be -1, meaning that we're not writing from a register. 5151 * 5152 * The caller must ensure that the offset falls within the maximum stack size. 5153 */ 5154 static int check_stack_write(struct bpf_verifier_env *env, 5155 int ptr_regno, int off, int size, 5156 int value_regno, int insn_idx) 5157 { 5158 struct bpf_reg_state *reg = reg_state(env, ptr_regno); 5159 struct bpf_func_state *state = func(env, reg); 5160 int err; 5161 5162 if (tnum_is_const(reg->var_off)) { 5163 off += reg->var_off.value; 5164 err = check_stack_write_fixed_off(env, state, off, size, 5165 value_regno, insn_idx); 5166 } else { 5167 /* Variable offset stack reads need more conservative handling 5168 * than fixed offset ones. 5169 */ 5170 err = check_stack_write_var_off(env, state, 5171 ptr_regno, off, size, 5172 value_regno, insn_idx); 5173 } 5174 return err; 5175 } 5176 5177 static int check_map_access_type(struct bpf_verifier_env *env, u32 regno, 5178 int off, int size, enum bpf_access_type type) 5179 { 5180 struct bpf_reg_state *regs = cur_regs(env); 5181 struct bpf_map *map = regs[regno].map_ptr; 5182 u32 cap = bpf_map_flags_to_cap(map); 5183 5184 if (type == BPF_WRITE && !(cap & BPF_MAP_CAN_WRITE)) { 5185 verbose(env, "write into map forbidden, value_size=%d off=%d size=%d\n", 5186 map->value_size, off, size); 5187 return -EACCES; 5188 } 5189 5190 if (type == BPF_READ && !(cap & BPF_MAP_CAN_READ)) { 5191 verbose(env, "read from map forbidden, value_size=%d off=%d size=%d\n", 5192 map->value_size, off, size); 5193 return -EACCES; 5194 } 5195 5196 return 0; 5197 } 5198 5199 /* check read/write into memory region (e.g., map value, ringbuf sample, etc) */ 5200 static int __check_mem_access(struct bpf_verifier_env *env, int regno, 5201 int off, int size, u32 mem_size, 5202 bool zero_size_allowed) 5203 { 5204 bool size_ok = size > 0 || (size == 0 && zero_size_allowed); 5205 struct bpf_reg_state *reg; 5206 5207 if (off >= 0 && size_ok && (u64)off + size <= mem_size) 5208 return 0; 5209 5210 reg = &cur_regs(env)[regno]; 5211 switch (reg->type) { 5212 case PTR_TO_MAP_KEY: 5213 verbose(env, "invalid access to map key, key_size=%d off=%d size=%d\n", 5214 mem_size, off, size); 5215 break; 5216 case PTR_TO_MAP_VALUE: 5217 verbose(env, "invalid access to map value, value_size=%d off=%d size=%d\n", 5218 mem_size, off, size); 5219 break; 5220 case PTR_TO_PACKET: 5221 case PTR_TO_PACKET_META: 5222 case PTR_TO_PACKET_END: 5223 verbose(env, "invalid access to packet, off=%d size=%d, R%d(id=%d,off=%d,r=%d)\n", 5224 off, size, regno, reg->id, off, mem_size); 5225 break; 5226 case PTR_TO_MEM: 5227 default: 5228 verbose(env, "invalid access to memory, mem_size=%u off=%d size=%d\n", 5229 mem_size, off, size); 5230 } 5231 5232 return -EACCES; 5233 } 5234 5235 /* check read/write into a memory region with possible variable offset */ 5236 static int check_mem_region_access(struct bpf_verifier_env *env, u32 regno, 5237 int off, int size, u32 mem_size, 5238 bool zero_size_allowed) 5239 { 5240 struct bpf_verifier_state *vstate = env->cur_state; 5241 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 5242 struct bpf_reg_state *reg = &state->regs[regno]; 5243 int err; 5244 5245 /* We may have adjusted the register pointing to memory region, so we 5246 * need to try adding each of min_value and max_value to off 5247 * to make sure our theoretical access will be safe. 5248 * 5249 * The minimum value is only important with signed 5250 * comparisons where we can't assume the floor of a 5251 * value is 0. If we are using signed variables for our 5252 * index'es we need to make sure that whatever we use 5253 * will have a set floor within our range. 5254 */ 5255 if (reg->smin_value < 0 && 5256 (reg->smin_value == S64_MIN || 5257 (off + reg->smin_value != (s64)(s32)(off + reg->smin_value)) || 5258 reg->smin_value + off < 0)) { 5259 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n", 5260 regno); 5261 return -EACCES; 5262 } 5263 err = __check_mem_access(env, regno, reg->smin_value + off, size, 5264 mem_size, zero_size_allowed); 5265 if (err) { 5266 verbose(env, "R%d min value is outside of the allowed memory range\n", 5267 regno); 5268 return err; 5269 } 5270 5271 /* If we haven't set a max value then we need to bail since we can't be 5272 * sure we won't do bad things. 5273 * If reg->umax_value + off could overflow, treat that as unbounded too. 5274 */ 5275 if (reg->umax_value >= BPF_MAX_VAR_OFF) { 5276 verbose(env, "R%d unbounded memory access, make sure to bounds check any such access\n", 5277 regno); 5278 return -EACCES; 5279 } 5280 err = __check_mem_access(env, regno, reg->umax_value + off, size, 5281 mem_size, zero_size_allowed); 5282 if (err) { 5283 verbose(env, "R%d max value is outside of the allowed memory range\n", 5284 regno); 5285 return err; 5286 } 5287 5288 return 0; 5289 } 5290 5291 static int __check_ptr_off_reg(struct bpf_verifier_env *env, 5292 const struct bpf_reg_state *reg, int regno, 5293 bool fixed_off_ok) 5294 { 5295 /* Access to this pointer-typed register or passing it to a helper 5296 * is only allowed in its original, unmodified form. 5297 */ 5298 5299 if (reg->off < 0) { 5300 verbose(env, "negative offset %s ptr R%d off=%d disallowed\n", 5301 reg_type_str(env, reg->type), regno, reg->off); 5302 return -EACCES; 5303 } 5304 5305 if (!fixed_off_ok && reg->off) { 5306 verbose(env, "dereference of modified %s ptr R%d off=%d disallowed\n", 5307 reg_type_str(env, reg->type), regno, reg->off); 5308 return -EACCES; 5309 } 5310 5311 if (!tnum_is_const(reg->var_off) || reg->var_off.value) { 5312 char tn_buf[48]; 5313 5314 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 5315 verbose(env, "variable %s access var_off=%s disallowed\n", 5316 reg_type_str(env, reg->type), tn_buf); 5317 return -EACCES; 5318 } 5319 5320 return 0; 5321 } 5322 5323 int check_ptr_off_reg(struct bpf_verifier_env *env, 5324 const struct bpf_reg_state *reg, int regno) 5325 { 5326 return __check_ptr_off_reg(env, reg, regno, false); 5327 } 5328 5329 static int map_kptr_match_type(struct bpf_verifier_env *env, 5330 struct btf_field *kptr_field, 5331 struct bpf_reg_state *reg, u32 regno) 5332 { 5333 const char *targ_name = btf_type_name(kptr_field->kptr.btf, kptr_field->kptr.btf_id); 5334 int perm_flags; 5335 const char *reg_name = ""; 5336 5337 if (btf_is_kernel(reg->btf)) { 5338 perm_flags = PTR_MAYBE_NULL | PTR_TRUSTED | MEM_RCU; 5339 5340 /* Only unreferenced case accepts untrusted pointers */ 5341 if (kptr_field->type == BPF_KPTR_UNREF) 5342 perm_flags |= PTR_UNTRUSTED; 5343 } else { 5344 perm_flags = PTR_MAYBE_NULL | MEM_ALLOC; 5345 if (kptr_field->type == BPF_KPTR_PERCPU) 5346 perm_flags |= MEM_PERCPU; 5347 } 5348 5349 if (base_type(reg->type) != PTR_TO_BTF_ID || (type_flag(reg->type) & ~perm_flags)) 5350 goto bad_type; 5351 5352 /* We need to verify reg->type and reg->btf, before accessing reg->btf */ 5353 reg_name = btf_type_name(reg->btf, reg->btf_id); 5354 5355 /* For ref_ptr case, release function check should ensure we get one 5356 * referenced PTR_TO_BTF_ID, and that its fixed offset is 0. For the 5357 * normal store of unreferenced kptr, we must ensure var_off is zero. 5358 * Since ref_ptr cannot be accessed directly by BPF insns, checks for 5359 * reg->off and reg->ref_obj_id are not needed here. 5360 */ 5361 if (__check_ptr_off_reg(env, reg, regno, true)) 5362 return -EACCES; 5363 5364 /* A full type match is needed, as BTF can be vmlinux, module or prog BTF, and 5365 * we also need to take into account the reg->off. 5366 * 5367 * We want to support cases like: 5368 * 5369 * struct foo { 5370 * struct bar br; 5371 * struct baz bz; 5372 * }; 5373 * 5374 * struct foo *v; 5375 * v = func(); // PTR_TO_BTF_ID 5376 * val->foo = v; // reg->off is zero, btf and btf_id match type 5377 * val->bar = &v->br; // reg->off is still zero, but we need to retry with 5378 * // first member type of struct after comparison fails 5379 * val->baz = &v->bz; // reg->off is non-zero, so struct needs to be walked 5380 * // to match type 5381 * 5382 * In the kptr_ref case, check_func_arg_reg_off already ensures reg->off 5383 * is zero. We must also ensure that btf_struct_ids_match does not walk 5384 * the struct to match type against first member of struct, i.e. reject 5385 * second case from above. Hence, when type is BPF_KPTR_REF, we set 5386 * strict mode to true for type match. 5387 */ 5388 if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off, 5389 kptr_field->kptr.btf, kptr_field->kptr.btf_id, 5390 kptr_field->type != BPF_KPTR_UNREF)) 5391 goto bad_type; 5392 return 0; 5393 bad_type: 5394 verbose(env, "invalid kptr access, R%d type=%s%s ", regno, 5395 reg_type_str(env, reg->type), reg_name); 5396 verbose(env, "expected=%s%s", reg_type_str(env, PTR_TO_BTF_ID), targ_name); 5397 if (kptr_field->type == BPF_KPTR_UNREF) 5398 verbose(env, " or %s%s\n", reg_type_str(env, PTR_TO_BTF_ID | PTR_UNTRUSTED), 5399 targ_name); 5400 else 5401 verbose(env, "\n"); 5402 return -EINVAL; 5403 } 5404 5405 /* The non-sleepable programs and sleepable programs with explicit bpf_rcu_read_lock() 5406 * can dereference RCU protected pointers and result is PTR_TRUSTED. 5407 */ 5408 static bool in_rcu_cs(struct bpf_verifier_env *env) 5409 { 5410 return env->cur_state->active_rcu_lock || 5411 env->cur_state->active_lock.ptr || 5412 !env->prog->aux->sleepable; 5413 } 5414 5415 /* Once GCC supports btf_type_tag the following mechanism will be replaced with tag check */ 5416 BTF_SET_START(rcu_protected_types) 5417 BTF_ID(struct, prog_test_ref_kfunc) 5418 #ifdef CONFIG_CGROUPS 5419 BTF_ID(struct, cgroup) 5420 #endif 5421 BTF_ID(struct, bpf_cpumask) 5422 BTF_ID(struct, task_struct) 5423 BTF_SET_END(rcu_protected_types) 5424 5425 static bool rcu_protected_object(const struct btf *btf, u32 btf_id) 5426 { 5427 if (!btf_is_kernel(btf)) 5428 return false; 5429 return btf_id_set_contains(&rcu_protected_types, btf_id); 5430 } 5431 5432 static bool rcu_safe_kptr(const struct btf_field *field) 5433 { 5434 const struct btf_field_kptr *kptr = &field->kptr; 5435 5436 return field->type == BPF_KPTR_PERCPU || 5437 (field->type == BPF_KPTR_REF && rcu_protected_object(kptr->btf, kptr->btf_id)); 5438 } 5439 5440 static u32 btf_ld_kptr_type(struct bpf_verifier_env *env, struct btf_field *kptr_field) 5441 { 5442 if (rcu_safe_kptr(kptr_field) && in_rcu_cs(env)) { 5443 if (kptr_field->type != BPF_KPTR_PERCPU) 5444 return PTR_MAYBE_NULL | MEM_RCU; 5445 return PTR_MAYBE_NULL | MEM_RCU | MEM_PERCPU; 5446 } 5447 return PTR_MAYBE_NULL | PTR_UNTRUSTED; 5448 } 5449 5450 static int check_map_kptr_access(struct bpf_verifier_env *env, u32 regno, 5451 int value_regno, int insn_idx, 5452 struct btf_field *kptr_field) 5453 { 5454 struct bpf_insn *insn = &env->prog->insnsi[insn_idx]; 5455 int class = BPF_CLASS(insn->code); 5456 struct bpf_reg_state *val_reg; 5457 5458 /* Things we already checked for in check_map_access and caller: 5459 * - Reject cases where variable offset may touch kptr 5460 * - size of access (must be BPF_DW) 5461 * - tnum_is_const(reg->var_off) 5462 * - kptr_field->offset == off + reg->var_off.value 5463 */ 5464 /* Only BPF_[LDX,STX,ST] | BPF_MEM | BPF_DW is supported */ 5465 if (BPF_MODE(insn->code) != BPF_MEM) { 5466 verbose(env, "kptr in map can only be accessed using BPF_MEM instruction mode\n"); 5467 return -EACCES; 5468 } 5469 5470 /* We only allow loading referenced kptr, since it will be marked as 5471 * untrusted, similar to unreferenced kptr. 5472 */ 5473 if (class != BPF_LDX && 5474 (kptr_field->type == BPF_KPTR_REF || kptr_field->type == BPF_KPTR_PERCPU)) { 5475 verbose(env, "store to referenced kptr disallowed\n"); 5476 return -EACCES; 5477 } 5478 5479 if (class == BPF_LDX) { 5480 val_reg = reg_state(env, value_regno); 5481 /* We can simply mark the value_regno receiving the pointer 5482 * value from map as PTR_TO_BTF_ID, with the correct type. 5483 */ 5484 mark_btf_ld_reg(env, cur_regs(env), value_regno, PTR_TO_BTF_ID, kptr_field->kptr.btf, 5485 kptr_field->kptr.btf_id, btf_ld_kptr_type(env, kptr_field)); 5486 /* For mark_ptr_or_null_reg */ 5487 val_reg->id = ++env->id_gen; 5488 } else if (class == BPF_STX) { 5489 val_reg = reg_state(env, value_regno); 5490 if (!register_is_null(val_reg) && 5491 map_kptr_match_type(env, kptr_field, val_reg, value_regno)) 5492 return -EACCES; 5493 } else if (class == BPF_ST) { 5494 if (insn->imm) { 5495 verbose(env, "BPF_ST imm must be 0 when storing to kptr at off=%u\n", 5496 kptr_field->offset); 5497 return -EACCES; 5498 } 5499 } else { 5500 verbose(env, "kptr in map can only be accessed using BPF_LDX/BPF_STX/BPF_ST\n"); 5501 return -EACCES; 5502 } 5503 return 0; 5504 } 5505 5506 /* check read/write into a map element with possible variable offset */ 5507 static int check_map_access(struct bpf_verifier_env *env, u32 regno, 5508 int off, int size, bool zero_size_allowed, 5509 enum bpf_access_src src) 5510 { 5511 struct bpf_verifier_state *vstate = env->cur_state; 5512 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 5513 struct bpf_reg_state *reg = &state->regs[regno]; 5514 struct bpf_map *map = reg->map_ptr; 5515 struct btf_record *rec; 5516 int err, i; 5517 5518 err = check_mem_region_access(env, regno, off, size, map->value_size, 5519 zero_size_allowed); 5520 if (err) 5521 return err; 5522 5523 if (IS_ERR_OR_NULL(map->record)) 5524 return 0; 5525 rec = map->record; 5526 for (i = 0; i < rec->cnt; i++) { 5527 struct btf_field *field = &rec->fields[i]; 5528 u32 p = field->offset; 5529 5530 /* If any part of a field can be touched by load/store, reject 5531 * this program. To check that [x1, x2) overlaps with [y1, y2), 5532 * it is sufficient to check x1 < y2 && y1 < x2. 5533 */ 5534 if (reg->smin_value + off < p + btf_field_type_size(field->type) && 5535 p < reg->umax_value + off + size) { 5536 switch (field->type) { 5537 case BPF_KPTR_UNREF: 5538 case BPF_KPTR_REF: 5539 case BPF_KPTR_PERCPU: 5540 if (src != ACCESS_DIRECT) { 5541 verbose(env, "kptr cannot be accessed indirectly by helper\n"); 5542 return -EACCES; 5543 } 5544 if (!tnum_is_const(reg->var_off)) { 5545 verbose(env, "kptr access cannot have variable offset\n"); 5546 return -EACCES; 5547 } 5548 if (p != off + reg->var_off.value) { 5549 verbose(env, "kptr access misaligned expected=%u off=%llu\n", 5550 p, off + reg->var_off.value); 5551 return -EACCES; 5552 } 5553 if (size != bpf_size_to_bytes(BPF_DW)) { 5554 verbose(env, "kptr access size must be BPF_DW\n"); 5555 return -EACCES; 5556 } 5557 break; 5558 default: 5559 verbose(env, "%s cannot be accessed directly by load/store\n", 5560 btf_field_type_name(field->type)); 5561 return -EACCES; 5562 } 5563 } 5564 } 5565 return 0; 5566 } 5567 5568 #define MAX_PACKET_OFF 0xffff 5569 5570 static bool may_access_direct_pkt_data(struct bpf_verifier_env *env, 5571 const struct bpf_call_arg_meta *meta, 5572 enum bpf_access_type t) 5573 { 5574 enum bpf_prog_type prog_type = resolve_prog_type(env->prog); 5575 5576 switch (prog_type) { 5577 /* Program types only with direct read access go here! */ 5578 case BPF_PROG_TYPE_LWT_IN: 5579 case BPF_PROG_TYPE_LWT_OUT: 5580 case BPF_PROG_TYPE_LWT_SEG6LOCAL: 5581 case BPF_PROG_TYPE_SK_REUSEPORT: 5582 case BPF_PROG_TYPE_FLOW_DISSECTOR: 5583 case BPF_PROG_TYPE_CGROUP_SKB: 5584 if (t == BPF_WRITE) 5585 return false; 5586 fallthrough; 5587 5588 /* Program types with direct read + write access go here! */ 5589 case BPF_PROG_TYPE_SCHED_CLS: 5590 case BPF_PROG_TYPE_SCHED_ACT: 5591 case BPF_PROG_TYPE_XDP: 5592 case BPF_PROG_TYPE_LWT_XMIT: 5593 case BPF_PROG_TYPE_SK_SKB: 5594 case BPF_PROG_TYPE_SK_MSG: 5595 if (meta) 5596 return meta->pkt_access; 5597 5598 env->seen_direct_write = true; 5599 return true; 5600 5601 case BPF_PROG_TYPE_CGROUP_SOCKOPT: 5602 if (t == BPF_WRITE) 5603 env->seen_direct_write = true; 5604 5605 return true; 5606 5607 default: 5608 return false; 5609 } 5610 } 5611 5612 static int check_packet_access(struct bpf_verifier_env *env, u32 regno, int off, 5613 int size, bool zero_size_allowed) 5614 { 5615 struct bpf_reg_state *regs = cur_regs(env); 5616 struct bpf_reg_state *reg = ®s[regno]; 5617 int err; 5618 5619 /* We may have added a variable offset to the packet pointer; but any 5620 * reg->range we have comes after that. We are only checking the fixed 5621 * offset. 5622 */ 5623 5624 /* We don't allow negative numbers, because we aren't tracking enough 5625 * detail to prove they're safe. 5626 */ 5627 if (reg->smin_value < 0) { 5628 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n", 5629 regno); 5630 return -EACCES; 5631 } 5632 5633 err = reg->range < 0 ? -EINVAL : 5634 __check_mem_access(env, regno, off, size, reg->range, 5635 zero_size_allowed); 5636 if (err) { 5637 verbose(env, "R%d offset is outside of the packet\n", regno); 5638 return err; 5639 } 5640 5641 /* __check_mem_access has made sure "off + size - 1" is within u16. 5642 * reg->umax_value can't be bigger than MAX_PACKET_OFF which is 0xffff, 5643 * otherwise find_good_pkt_pointers would have refused to set range info 5644 * that __check_mem_access would have rejected this pkt access. 5645 * Therefore, "off + reg->umax_value + size - 1" won't overflow u32. 5646 */ 5647 env->prog->aux->max_pkt_offset = 5648 max_t(u32, env->prog->aux->max_pkt_offset, 5649 off + reg->umax_value + size - 1); 5650 5651 return err; 5652 } 5653 5654 /* check access to 'struct bpf_context' fields. Supports fixed offsets only */ 5655 static int check_ctx_access(struct bpf_verifier_env *env, int insn_idx, int off, int size, 5656 enum bpf_access_type t, enum bpf_reg_type *reg_type, 5657 struct btf **btf, u32 *btf_id) 5658 { 5659 struct bpf_insn_access_aux info = { 5660 .reg_type = *reg_type, 5661 .log = &env->log, 5662 }; 5663 5664 if (env->ops->is_valid_access && 5665 env->ops->is_valid_access(off, size, t, env->prog, &info)) { 5666 /* A non zero info.ctx_field_size indicates that this field is a 5667 * candidate for later verifier transformation to load the whole 5668 * field and then apply a mask when accessed with a narrower 5669 * access than actual ctx access size. A zero info.ctx_field_size 5670 * will only allow for whole field access and rejects any other 5671 * type of narrower access. 5672 */ 5673 *reg_type = info.reg_type; 5674 5675 if (base_type(*reg_type) == PTR_TO_BTF_ID) { 5676 *btf = info.btf; 5677 *btf_id = info.btf_id; 5678 } else { 5679 env->insn_aux_data[insn_idx].ctx_field_size = info.ctx_field_size; 5680 } 5681 /* remember the offset of last byte accessed in ctx */ 5682 if (env->prog->aux->max_ctx_offset < off + size) 5683 env->prog->aux->max_ctx_offset = off + size; 5684 return 0; 5685 } 5686 5687 verbose(env, "invalid bpf_context access off=%d size=%d\n", off, size); 5688 return -EACCES; 5689 } 5690 5691 static int check_flow_keys_access(struct bpf_verifier_env *env, int off, 5692 int size) 5693 { 5694 if (size < 0 || off < 0 || 5695 (u64)off + size > sizeof(struct bpf_flow_keys)) { 5696 verbose(env, "invalid access to flow keys off=%d size=%d\n", 5697 off, size); 5698 return -EACCES; 5699 } 5700 return 0; 5701 } 5702 5703 static int check_sock_access(struct bpf_verifier_env *env, int insn_idx, 5704 u32 regno, int off, int size, 5705 enum bpf_access_type t) 5706 { 5707 struct bpf_reg_state *regs = cur_regs(env); 5708 struct bpf_reg_state *reg = ®s[regno]; 5709 struct bpf_insn_access_aux info = {}; 5710 bool valid; 5711 5712 if (reg->smin_value < 0) { 5713 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n", 5714 regno); 5715 return -EACCES; 5716 } 5717 5718 switch (reg->type) { 5719 case PTR_TO_SOCK_COMMON: 5720 valid = bpf_sock_common_is_valid_access(off, size, t, &info); 5721 break; 5722 case PTR_TO_SOCKET: 5723 valid = bpf_sock_is_valid_access(off, size, t, &info); 5724 break; 5725 case PTR_TO_TCP_SOCK: 5726 valid = bpf_tcp_sock_is_valid_access(off, size, t, &info); 5727 break; 5728 case PTR_TO_XDP_SOCK: 5729 valid = bpf_xdp_sock_is_valid_access(off, size, t, &info); 5730 break; 5731 default: 5732 valid = false; 5733 } 5734 5735 5736 if (valid) { 5737 env->insn_aux_data[insn_idx].ctx_field_size = 5738 info.ctx_field_size; 5739 return 0; 5740 } 5741 5742 verbose(env, "R%d invalid %s access off=%d size=%d\n", 5743 regno, reg_type_str(env, reg->type), off, size); 5744 5745 return -EACCES; 5746 } 5747 5748 static bool is_pointer_value(struct bpf_verifier_env *env, int regno) 5749 { 5750 return __is_pointer_value(env->allow_ptr_leaks, reg_state(env, regno)); 5751 } 5752 5753 static bool is_ctx_reg(struct bpf_verifier_env *env, int regno) 5754 { 5755 const struct bpf_reg_state *reg = reg_state(env, regno); 5756 5757 return reg->type == PTR_TO_CTX; 5758 } 5759 5760 static bool is_sk_reg(struct bpf_verifier_env *env, int regno) 5761 { 5762 const struct bpf_reg_state *reg = reg_state(env, regno); 5763 5764 return type_is_sk_pointer(reg->type); 5765 } 5766 5767 static bool is_pkt_reg(struct bpf_verifier_env *env, int regno) 5768 { 5769 const struct bpf_reg_state *reg = reg_state(env, regno); 5770 5771 return type_is_pkt_pointer(reg->type); 5772 } 5773 5774 static bool is_flow_key_reg(struct bpf_verifier_env *env, int regno) 5775 { 5776 const struct bpf_reg_state *reg = reg_state(env, regno); 5777 5778 /* Separate to is_ctx_reg() since we still want to allow BPF_ST here. */ 5779 return reg->type == PTR_TO_FLOW_KEYS; 5780 } 5781 5782 static u32 *reg2btf_ids[__BPF_REG_TYPE_MAX] = { 5783 #ifdef CONFIG_NET 5784 [PTR_TO_SOCKET] = &btf_sock_ids[BTF_SOCK_TYPE_SOCK], 5785 [PTR_TO_SOCK_COMMON] = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON], 5786 [PTR_TO_TCP_SOCK] = &btf_sock_ids[BTF_SOCK_TYPE_TCP], 5787 #endif 5788 [CONST_PTR_TO_MAP] = btf_bpf_map_id, 5789 }; 5790 5791 static bool is_trusted_reg(const struct bpf_reg_state *reg) 5792 { 5793 /* A referenced register is always trusted. */ 5794 if (reg->ref_obj_id) 5795 return true; 5796 5797 /* Types listed in the reg2btf_ids are always trusted */ 5798 if (reg2btf_ids[base_type(reg->type)]) 5799 return true; 5800 5801 /* If a register is not referenced, it is trusted if it has the 5802 * MEM_ALLOC or PTR_TRUSTED type modifiers, and no others. Some of the 5803 * other type modifiers may be safe, but we elect to take an opt-in 5804 * approach here as some (e.g. PTR_UNTRUSTED and PTR_MAYBE_NULL) are 5805 * not. 5806 * 5807 * Eventually, we should make PTR_TRUSTED the single source of truth 5808 * for whether a register is trusted. 5809 */ 5810 return type_flag(reg->type) & BPF_REG_TRUSTED_MODIFIERS && 5811 !bpf_type_has_unsafe_modifiers(reg->type); 5812 } 5813 5814 static bool is_rcu_reg(const struct bpf_reg_state *reg) 5815 { 5816 return reg->type & MEM_RCU; 5817 } 5818 5819 static void clear_trusted_flags(enum bpf_type_flag *flag) 5820 { 5821 *flag &= ~(BPF_REG_TRUSTED_MODIFIERS | MEM_RCU); 5822 } 5823 5824 static int check_pkt_ptr_alignment(struct bpf_verifier_env *env, 5825 const struct bpf_reg_state *reg, 5826 int off, int size, bool strict) 5827 { 5828 struct tnum reg_off; 5829 int ip_align; 5830 5831 /* Byte size accesses are always allowed. */ 5832 if (!strict || size == 1) 5833 return 0; 5834 5835 /* For platforms that do not have a Kconfig enabling 5836 * CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS the value of 5837 * NET_IP_ALIGN is universally set to '2'. And on platforms 5838 * that do set CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS, we get 5839 * to this code only in strict mode where we want to emulate 5840 * the NET_IP_ALIGN==2 checking. Therefore use an 5841 * unconditional IP align value of '2'. 5842 */ 5843 ip_align = 2; 5844 5845 reg_off = tnum_add(reg->var_off, tnum_const(ip_align + reg->off + off)); 5846 if (!tnum_is_aligned(reg_off, size)) { 5847 char tn_buf[48]; 5848 5849 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 5850 verbose(env, 5851 "misaligned packet access off %d+%s+%d+%d size %d\n", 5852 ip_align, tn_buf, reg->off, off, size); 5853 return -EACCES; 5854 } 5855 5856 return 0; 5857 } 5858 5859 static int check_generic_ptr_alignment(struct bpf_verifier_env *env, 5860 const struct bpf_reg_state *reg, 5861 const char *pointer_desc, 5862 int off, int size, bool strict) 5863 { 5864 struct tnum reg_off; 5865 5866 /* Byte size accesses are always allowed. */ 5867 if (!strict || size == 1) 5868 return 0; 5869 5870 reg_off = tnum_add(reg->var_off, tnum_const(reg->off + off)); 5871 if (!tnum_is_aligned(reg_off, size)) { 5872 char tn_buf[48]; 5873 5874 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 5875 verbose(env, "misaligned %saccess off %s+%d+%d size %d\n", 5876 pointer_desc, tn_buf, reg->off, off, size); 5877 return -EACCES; 5878 } 5879 5880 return 0; 5881 } 5882 5883 static int check_ptr_alignment(struct bpf_verifier_env *env, 5884 const struct bpf_reg_state *reg, int off, 5885 int size, bool strict_alignment_once) 5886 { 5887 bool strict = env->strict_alignment || strict_alignment_once; 5888 const char *pointer_desc = ""; 5889 5890 switch (reg->type) { 5891 case PTR_TO_PACKET: 5892 case PTR_TO_PACKET_META: 5893 /* Special case, because of NET_IP_ALIGN. Given metadata sits 5894 * right in front, treat it the very same way. 5895 */ 5896 return check_pkt_ptr_alignment(env, reg, off, size, strict); 5897 case PTR_TO_FLOW_KEYS: 5898 pointer_desc = "flow keys "; 5899 break; 5900 case PTR_TO_MAP_KEY: 5901 pointer_desc = "key "; 5902 break; 5903 case PTR_TO_MAP_VALUE: 5904 pointer_desc = "value "; 5905 break; 5906 case PTR_TO_CTX: 5907 pointer_desc = "context "; 5908 break; 5909 case PTR_TO_STACK: 5910 pointer_desc = "stack "; 5911 /* The stack spill tracking logic in check_stack_write_fixed_off() 5912 * and check_stack_read_fixed_off() relies on stack accesses being 5913 * aligned. 5914 */ 5915 strict = true; 5916 break; 5917 case PTR_TO_SOCKET: 5918 pointer_desc = "sock "; 5919 break; 5920 case PTR_TO_SOCK_COMMON: 5921 pointer_desc = "sock_common "; 5922 break; 5923 case PTR_TO_TCP_SOCK: 5924 pointer_desc = "tcp_sock "; 5925 break; 5926 case PTR_TO_XDP_SOCK: 5927 pointer_desc = "xdp_sock "; 5928 break; 5929 default: 5930 break; 5931 } 5932 return check_generic_ptr_alignment(env, reg, pointer_desc, off, size, 5933 strict); 5934 } 5935 5936 static int update_stack_depth(struct bpf_verifier_env *env, 5937 const struct bpf_func_state *func, 5938 int off) 5939 { 5940 u16 stack = env->subprog_info[func->subprogno].stack_depth; 5941 5942 if (stack >= -off) 5943 return 0; 5944 5945 /* update known max for given subprogram */ 5946 env->subprog_info[func->subprogno].stack_depth = -off; 5947 return 0; 5948 } 5949 5950 /* starting from main bpf function walk all instructions of the function 5951 * and recursively walk all callees that given function can call. 5952 * Ignore jump and exit insns. 5953 * Since recursion is prevented by check_cfg() this algorithm 5954 * only needs a local stack of MAX_CALL_FRAMES to remember callsites 5955 */ 5956 static int check_max_stack_depth_subprog(struct bpf_verifier_env *env, int idx) 5957 { 5958 struct bpf_subprog_info *subprog = env->subprog_info; 5959 struct bpf_insn *insn = env->prog->insnsi; 5960 int depth = 0, frame = 0, i, subprog_end; 5961 bool tail_call_reachable = false; 5962 int ret_insn[MAX_CALL_FRAMES]; 5963 int ret_prog[MAX_CALL_FRAMES]; 5964 int j; 5965 5966 i = subprog[idx].start; 5967 process_func: 5968 /* protect against potential stack overflow that might happen when 5969 * bpf2bpf calls get combined with tailcalls. Limit the caller's stack 5970 * depth for such case down to 256 so that the worst case scenario 5971 * would result in 8k stack size (32 which is tailcall limit * 256 = 5972 * 8k). 5973 * 5974 * To get the idea what might happen, see an example: 5975 * func1 -> sub rsp, 128 5976 * subfunc1 -> sub rsp, 256 5977 * tailcall1 -> add rsp, 256 5978 * func2 -> sub rsp, 192 (total stack size = 128 + 192 = 320) 5979 * subfunc2 -> sub rsp, 64 5980 * subfunc22 -> sub rsp, 128 5981 * tailcall2 -> add rsp, 128 5982 * func3 -> sub rsp, 32 (total stack size 128 + 192 + 64 + 32 = 416) 5983 * 5984 * tailcall will unwind the current stack frame but it will not get rid 5985 * of caller's stack as shown on the example above. 5986 */ 5987 if (idx && subprog[idx].has_tail_call && depth >= 256) { 5988 verbose(env, 5989 "tail_calls are not allowed when call stack of previous frames is %d bytes. Too large\n", 5990 depth); 5991 return -EACCES; 5992 } 5993 /* round up to 32-bytes, since this is granularity 5994 * of interpreter stack size 5995 */ 5996 depth += round_up(max_t(u32, subprog[idx].stack_depth, 1), 32); 5997 if (depth > MAX_BPF_STACK) { 5998 verbose(env, "combined stack size of %d calls is %d. Too large\n", 5999 frame + 1, depth); 6000 return -EACCES; 6001 } 6002 continue_func: 6003 subprog_end = subprog[idx + 1].start; 6004 for (; i < subprog_end; i++) { 6005 int next_insn, sidx; 6006 6007 if (bpf_pseudo_kfunc_call(insn + i) && !insn[i].off) { 6008 bool err = false; 6009 6010 if (!is_bpf_throw_kfunc(insn + i)) 6011 continue; 6012 if (subprog[idx].is_cb) 6013 err = true; 6014 for (int c = 0; c < frame && !err; c++) { 6015 if (subprog[ret_prog[c]].is_cb) { 6016 err = true; 6017 break; 6018 } 6019 } 6020 if (!err) 6021 continue; 6022 verbose(env, 6023 "bpf_throw kfunc (insn %d) cannot be called from callback subprog %d\n", 6024 i, idx); 6025 return -EINVAL; 6026 } 6027 6028 if (!bpf_pseudo_call(insn + i) && !bpf_pseudo_func(insn + i)) 6029 continue; 6030 /* remember insn and function to return to */ 6031 ret_insn[frame] = i + 1; 6032 ret_prog[frame] = idx; 6033 6034 /* find the callee */ 6035 next_insn = i + insn[i].imm + 1; 6036 sidx = find_subprog(env, next_insn); 6037 if (sidx < 0) { 6038 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n", 6039 next_insn); 6040 return -EFAULT; 6041 } 6042 if (subprog[sidx].is_async_cb) { 6043 if (subprog[sidx].has_tail_call) { 6044 verbose(env, "verifier bug. subprog has tail_call and async cb\n"); 6045 return -EFAULT; 6046 } 6047 /* async callbacks don't increase bpf prog stack size unless called directly */ 6048 if (!bpf_pseudo_call(insn + i)) 6049 continue; 6050 if (subprog[sidx].is_exception_cb) { 6051 verbose(env, "insn %d cannot call exception cb directly\n", i); 6052 return -EINVAL; 6053 } 6054 } 6055 i = next_insn; 6056 idx = sidx; 6057 6058 if (subprog[idx].has_tail_call) 6059 tail_call_reachable = true; 6060 6061 frame++; 6062 if (frame >= MAX_CALL_FRAMES) { 6063 verbose(env, "the call stack of %d frames is too deep !\n", 6064 frame); 6065 return -E2BIG; 6066 } 6067 goto process_func; 6068 } 6069 /* if tail call got detected across bpf2bpf calls then mark each of the 6070 * currently present subprog frames as tail call reachable subprogs; 6071 * this info will be utilized by JIT so that we will be preserving the 6072 * tail call counter throughout bpf2bpf calls combined with tailcalls 6073 */ 6074 if (tail_call_reachable) 6075 for (j = 0; j < frame; j++) { 6076 if (subprog[ret_prog[j]].is_exception_cb) { 6077 verbose(env, "cannot tail call within exception cb\n"); 6078 return -EINVAL; 6079 } 6080 subprog[ret_prog[j]].tail_call_reachable = true; 6081 } 6082 if (subprog[0].tail_call_reachable) 6083 env->prog->aux->tail_call_reachable = true; 6084 6085 /* end of for() loop means the last insn of the 'subprog' 6086 * was reached. Doesn't matter whether it was JA or EXIT 6087 */ 6088 if (frame == 0) 6089 return 0; 6090 depth -= round_up(max_t(u32, subprog[idx].stack_depth, 1), 32); 6091 frame--; 6092 i = ret_insn[frame]; 6093 idx = ret_prog[frame]; 6094 goto continue_func; 6095 } 6096 6097 static int check_max_stack_depth(struct bpf_verifier_env *env) 6098 { 6099 struct bpf_subprog_info *si = env->subprog_info; 6100 int ret; 6101 6102 for (int i = 0; i < env->subprog_cnt; i++) { 6103 if (!i || si[i].is_async_cb) { 6104 ret = check_max_stack_depth_subprog(env, i); 6105 if (ret < 0) 6106 return ret; 6107 } 6108 continue; 6109 } 6110 return 0; 6111 } 6112 6113 #ifndef CONFIG_BPF_JIT_ALWAYS_ON 6114 static int get_callee_stack_depth(struct bpf_verifier_env *env, 6115 const struct bpf_insn *insn, int idx) 6116 { 6117 int start = idx + insn->imm + 1, subprog; 6118 6119 subprog = find_subprog(env, start); 6120 if (subprog < 0) { 6121 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n", 6122 start); 6123 return -EFAULT; 6124 } 6125 return env->subprog_info[subprog].stack_depth; 6126 } 6127 #endif 6128 6129 static int __check_buffer_access(struct bpf_verifier_env *env, 6130 const char *buf_info, 6131 const struct bpf_reg_state *reg, 6132 int regno, int off, int size) 6133 { 6134 if (off < 0) { 6135 verbose(env, 6136 "R%d invalid %s buffer access: off=%d, size=%d\n", 6137 regno, buf_info, off, size); 6138 return -EACCES; 6139 } 6140 if (!tnum_is_const(reg->var_off) || reg->var_off.value) { 6141 char tn_buf[48]; 6142 6143 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 6144 verbose(env, 6145 "R%d invalid variable buffer offset: off=%d, var_off=%s\n", 6146 regno, off, tn_buf); 6147 return -EACCES; 6148 } 6149 6150 return 0; 6151 } 6152 6153 static int check_tp_buffer_access(struct bpf_verifier_env *env, 6154 const struct bpf_reg_state *reg, 6155 int regno, int off, int size) 6156 { 6157 int err; 6158 6159 err = __check_buffer_access(env, "tracepoint", reg, regno, off, size); 6160 if (err) 6161 return err; 6162 6163 if (off + size > env->prog->aux->max_tp_access) 6164 env->prog->aux->max_tp_access = off + size; 6165 6166 return 0; 6167 } 6168 6169 static int check_buffer_access(struct bpf_verifier_env *env, 6170 const struct bpf_reg_state *reg, 6171 int regno, int off, int size, 6172 bool zero_size_allowed, 6173 u32 *max_access) 6174 { 6175 const char *buf_info = type_is_rdonly_mem(reg->type) ? "rdonly" : "rdwr"; 6176 int err; 6177 6178 err = __check_buffer_access(env, buf_info, reg, regno, off, size); 6179 if (err) 6180 return err; 6181 6182 if (off + size > *max_access) 6183 *max_access = off + size; 6184 6185 return 0; 6186 } 6187 6188 /* BPF architecture zero extends alu32 ops into 64-bit registesr */ 6189 static void zext_32_to_64(struct bpf_reg_state *reg) 6190 { 6191 reg->var_off = tnum_subreg(reg->var_off); 6192 __reg_assign_32_into_64(reg); 6193 } 6194 6195 /* truncate register to smaller size (in bytes) 6196 * must be called with size < BPF_REG_SIZE 6197 */ 6198 static void coerce_reg_to_size(struct bpf_reg_state *reg, int size) 6199 { 6200 u64 mask; 6201 6202 /* clear high bits in bit representation */ 6203 reg->var_off = tnum_cast(reg->var_off, size); 6204 6205 /* fix arithmetic bounds */ 6206 mask = ((u64)1 << (size * 8)) - 1; 6207 if ((reg->umin_value & ~mask) == (reg->umax_value & ~mask)) { 6208 reg->umin_value &= mask; 6209 reg->umax_value &= mask; 6210 } else { 6211 reg->umin_value = 0; 6212 reg->umax_value = mask; 6213 } 6214 reg->smin_value = reg->umin_value; 6215 reg->smax_value = reg->umax_value; 6216 6217 /* If size is smaller than 32bit register the 32bit register 6218 * values are also truncated so we push 64-bit bounds into 6219 * 32-bit bounds. Above were truncated < 32-bits already. 6220 */ 6221 if (size >= 4) 6222 return; 6223 __reg_combine_64_into_32(reg); 6224 } 6225 6226 static void set_sext64_default_val(struct bpf_reg_state *reg, int size) 6227 { 6228 if (size == 1) { 6229 reg->smin_value = reg->s32_min_value = S8_MIN; 6230 reg->smax_value = reg->s32_max_value = S8_MAX; 6231 } else if (size == 2) { 6232 reg->smin_value = reg->s32_min_value = S16_MIN; 6233 reg->smax_value = reg->s32_max_value = S16_MAX; 6234 } else { 6235 /* size == 4 */ 6236 reg->smin_value = reg->s32_min_value = S32_MIN; 6237 reg->smax_value = reg->s32_max_value = S32_MAX; 6238 } 6239 reg->umin_value = reg->u32_min_value = 0; 6240 reg->umax_value = U64_MAX; 6241 reg->u32_max_value = U32_MAX; 6242 reg->var_off = tnum_unknown; 6243 } 6244 6245 static void coerce_reg_to_size_sx(struct bpf_reg_state *reg, int size) 6246 { 6247 s64 init_s64_max, init_s64_min, s64_max, s64_min, u64_cval; 6248 u64 top_smax_value, top_smin_value; 6249 u64 num_bits = size * 8; 6250 6251 if (tnum_is_const(reg->var_off)) { 6252 u64_cval = reg->var_off.value; 6253 if (size == 1) 6254 reg->var_off = tnum_const((s8)u64_cval); 6255 else if (size == 2) 6256 reg->var_off = tnum_const((s16)u64_cval); 6257 else 6258 /* size == 4 */ 6259 reg->var_off = tnum_const((s32)u64_cval); 6260 6261 u64_cval = reg->var_off.value; 6262 reg->smax_value = reg->smin_value = u64_cval; 6263 reg->umax_value = reg->umin_value = u64_cval; 6264 reg->s32_max_value = reg->s32_min_value = u64_cval; 6265 reg->u32_max_value = reg->u32_min_value = u64_cval; 6266 return; 6267 } 6268 6269 top_smax_value = ((u64)reg->smax_value >> num_bits) << num_bits; 6270 top_smin_value = ((u64)reg->smin_value >> num_bits) << num_bits; 6271 6272 if (top_smax_value != top_smin_value) 6273 goto out; 6274 6275 /* find the s64_min and s64_min after sign extension */ 6276 if (size == 1) { 6277 init_s64_max = (s8)reg->smax_value; 6278 init_s64_min = (s8)reg->smin_value; 6279 } else if (size == 2) { 6280 init_s64_max = (s16)reg->smax_value; 6281 init_s64_min = (s16)reg->smin_value; 6282 } else { 6283 init_s64_max = (s32)reg->smax_value; 6284 init_s64_min = (s32)reg->smin_value; 6285 } 6286 6287 s64_max = max(init_s64_max, init_s64_min); 6288 s64_min = min(init_s64_max, init_s64_min); 6289 6290 /* both of s64_max/s64_min positive or negative */ 6291 if ((s64_max >= 0) == (s64_min >= 0)) { 6292 reg->smin_value = reg->s32_min_value = s64_min; 6293 reg->smax_value = reg->s32_max_value = s64_max; 6294 reg->umin_value = reg->u32_min_value = s64_min; 6295 reg->umax_value = reg->u32_max_value = s64_max; 6296 reg->var_off = tnum_range(s64_min, s64_max); 6297 return; 6298 } 6299 6300 out: 6301 set_sext64_default_val(reg, size); 6302 } 6303 6304 static void set_sext32_default_val(struct bpf_reg_state *reg, int size) 6305 { 6306 if (size == 1) { 6307 reg->s32_min_value = S8_MIN; 6308 reg->s32_max_value = S8_MAX; 6309 } else { 6310 /* size == 2 */ 6311 reg->s32_min_value = S16_MIN; 6312 reg->s32_max_value = S16_MAX; 6313 } 6314 reg->u32_min_value = 0; 6315 reg->u32_max_value = U32_MAX; 6316 } 6317 6318 static void coerce_subreg_to_size_sx(struct bpf_reg_state *reg, int size) 6319 { 6320 s32 init_s32_max, init_s32_min, s32_max, s32_min, u32_val; 6321 u32 top_smax_value, top_smin_value; 6322 u32 num_bits = size * 8; 6323 6324 if (tnum_is_const(reg->var_off)) { 6325 u32_val = reg->var_off.value; 6326 if (size == 1) 6327 reg->var_off = tnum_const((s8)u32_val); 6328 else 6329 reg->var_off = tnum_const((s16)u32_val); 6330 6331 u32_val = reg->var_off.value; 6332 reg->s32_min_value = reg->s32_max_value = u32_val; 6333 reg->u32_min_value = reg->u32_max_value = u32_val; 6334 return; 6335 } 6336 6337 top_smax_value = ((u32)reg->s32_max_value >> num_bits) << num_bits; 6338 top_smin_value = ((u32)reg->s32_min_value >> num_bits) << num_bits; 6339 6340 if (top_smax_value != top_smin_value) 6341 goto out; 6342 6343 /* find the s32_min and s32_min after sign extension */ 6344 if (size == 1) { 6345 init_s32_max = (s8)reg->s32_max_value; 6346 init_s32_min = (s8)reg->s32_min_value; 6347 } else { 6348 /* size == 2 */ 6349 init_s32_max = (s16)reg->s32_max_value; 6350 init_s32_min = (s16)reg->s32_min_value; 6351 } 6352 s32_max = max(init_s32_max, init_s32_min); 6353 s32_min = min(init_s32_max, init_s32_min); 6354 6355 if ((s32_min >= 0) == (s32_max >= 0)) { 6356 reg->s32_min_value = s32_min; 6357 reg->s32_max_value = s32_max; 6358 reg->u32_min_value = (u32)s32_min; 6359 reg->u32_max_value = (u32)s32_max; 6360 return; 6361 } 6362 6363 out: 6364 set_sext32_default_val(reg, size); 6365 } 6366 6367 static bool bpf_map_is_rdonly(const struct bpf_map *map) 6368 { 6369 /* A map is considered read-only if the following condition are true: 6370 * 6371 * 1) BPF program side cannot change any of the map content. The 6372 * BPF_F_RDONLY_PROG flag is throughout the lifetime of a map 6373 * and was set at map creation time. 6374 * 2) The map value(s) have been initialized from user space by a 6375 * loader and then "frozen", such that no new map update/delete 6376 * operations from syscall side are possible for the rest of 6377 * the map's lifetime from that point onwards. 6378 * 3) Any parallel/pending map update/delete operations from syscall 6379 * side have been completed. Only after that point, it's safe to 6380 * assume that map value(s) are immutable. 6381 */ 6382 return (map->map_flags & BPF_F_RDONLY_PROG) && 6383 READ_ONCE(map->frozen) && 6384 !bpf_map_write_active(map); 6385 } 6386 6387 static int bpf_map_direct_read(struct bpf_map *map, int off, int size, u64 *val, 6388 bool is_ldsx) 6389 { 6390 void *ptr; 6391 u64 addr; 6392 int err; 6393 6394 err = map->ops->map_direct_value_addr(map, &addr, off); 6395 if (err) 6396 return err; 6397 ptr = (void *)(long)addr + off; 6398 6399 switch (size) { 6400 case sizeof(u8): 6401 *val = is_ldsx ? (s64)*(s8 *)ptr : (u64)*(u8 *)ptr; 6402 break; 6403 case sizeof(u16): 6404 *val = is_ldsx ? (s64)*(s16 *)ptr : (u64)*(u16 *)ptr; 6405 break; 6406 case sizeof(u32): 6407 *val = is_ldsx ? (s64)*(s32 *)ptr : (u64)*(u32 *)ptr; 6408 break; 6409 case sizeof(u64): 6410 *val = *(u64 *)ptr; 6411 break; 6412 default: 6413 return -EINVAL; 6414 } 6415 return 0; 6416 } 6417 6418 #define BTF_TYPE_SAFE_RCU(__type) __PASTE(__type, __safe_rcu) 6419 #define BTF_TYPE_SAFE_RCU_OR_NULL(__type) __PASTE(__type, __safe_rcu_or_null) 6420 #define BTF_TYPE_SAFE_TRUSTED(__type) __PASTE(__type, __safe_trusted) 6421 6422 /* 6423 * Allow list few fields as RCU trusted or full trusted. 6424 * This logic doesn't allow mix tagging and will be removed once GCC supports 6425 * btf_type_tag. 6426 */ 6427 6428 /* RCU trusted: these fields are trusted in RCU CS and never NULL */ 6429 BTF_TYPE_SAFE_RCU(struct task_struct) { 6430 const cpumask_t *cpus_ptr; 6431 struct css_set __rcu *cgroups; 6432 struct task_struct __rcu *real_parent; 6433 struct task_struct *group_leader; 6434 }; 6435 6436 BTF_TYPE_SAFE_RCU(struct cgroup) { 6437 /* cgrp->kn is always accessible as documented in kernel/cgroup/cgroup.c */ 6438 struct kernfs_node *kn; 6439 }; 6440 6441 BTF_TYPE_SAFE_RCU(struct css_set) { 6442 struct cgroup *dfl_cgrp; 6443 }; 6444 6445 /* RCU trusted: these fields are trusted in RCU CS and can be NULL */ 6446 BTF_TYPE_SAFE_RCU_OR_NULL(struct mm_struct) { 6447 struct file __rcu *exe_file; 6448 }; 6449 6450 /* skb->sk, req->sk are not RCU protected, but we mark them as such 6451 * because bpf prog accessible sockets are SOCK_RCU_FREE. 6452 */ 6453 BTF_TYPE_SAFE_RCU_OR_NULL(struct sk_buff) { 6454 struct sock *sk; 6455 }; 6456 6457 BTF_TYPE_SAFE_RCU_OR_NULL(struct request_sock) { 6458 struct sock *sk; 6459 }; 6460 6461 /* full trusted: these fields are trusted even outside of RCU CS and never NULL */ 6462 BTF_TYPE_SAFE_TRUSTED(struct bpf_iter_meta) { 6463 struct seq_file *seq; 6464 }; 6465 6466 BTF_TYPE_SAFE_TRUSTED(struct bpf_iter__task) { 6467 struct bpf_iter_meta *meta; 6468 struct task_struct *task; 6469 }; 6470 6471 BTF_TYPE_SAFE_TRUSTED(struct linux_binprm) { 6472 struct file *file; 6473 }; 6474 6475 BTF_TYPE_SAFE_TRUSTED(struct file) { 6476 struct inode *f_inode; 6477 }; 6478 6479 BTF_TYPE_SAFE_TRUSTED(struct dentry) { 6480 /* no negative dentry-s in places where bpf can see it */ 6481 struct inode *d_inode; 6482 }; 6483 6484 BTF_TYPE_SAFE_TRUSTED(struct socket) { 6485 struct sock *sk; 6486 }; 6487 6488 static bool type_is_rcu(struct bpf_verifier_env *env, 6489 struct bpf_reg_state *reg, 6490 const char *field_name, u32 btf_id) 6491 { 6492 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct task_struct)); 6493 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct cgroup)); 6494 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct css_set)); 6495 6496 return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_rcu"); 6497 } 6498 6499 static bool type_is_rcu_or_null(struct bpf_verifier_env *env, 6500 struct bpf_reg_state *reg, 6501 const char *field_name, u32 btf_id) 6502 { 6503 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct mm_struct)); 6504 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct sk_buff)); 6505 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct request_sock)); 6506 6507 return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_rcu_or_null"); 6508 } 6509 6510 static bool type_is_trusted(struct bpf_verifier_env *env, 6511 struct bpf_reg_state *reg, 6512 const char *field_name, u32 btf_id) 6513 { 6514 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct bpf_iter_meta)); 6515 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct bpf_iter__task)); 6516 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct linux_binprm)); 6517 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct file)); 6518 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct dentry)); 6519 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct socket)); 6520 6521 return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_trusted"); 6522 } 6523 6524 static int check_ptr_to_btf_access(struct bpf_verifier_env *env, 6525 struct bpf_reg_state *regs, 6526 int regno, int off, int size, 6527 enum bpf_access_type atype, 6528 int value_regno) 6529 { 6530 struct bpf_reg_state *reg = regs + regno; 6531 const struct btf_type *t = btf_type_by_id(reg->btf, reg->btf_id); 6532 const char *tname = btf_name_by_offset(reg->btf, t->name_off); 6533 const char *field_name = NULL; 6534 enum bpf_type_flag flag = 0; 6535 u32 btf_id = 0; 6536 int ret; 6537 6538 if (!env->allow_ptr_leaks) { 6539 verbose(env, 6540 "'struct %s' access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n", 6541 tname); 6542 return -EPERM; 6543 } 6544 if (!env->prog->gpl_compatible && btf_is_kernel(reg->btf)) { 6545 verbose(env, 6546 "Cannot access kernel 'struct %s' from non-GPL compatible program\n", 6547 tname); 6548 return -EINVAL; 6549 } 6550 if (off < 0) { 6551 verbose(env, 6552 "R%d is ptr_%s invalid negative access: off=%d\n", 6553 regno, tname, off); 6554 return -EACCES; 6555 } 6556 if (!tnum_is_const(reg->var_off) || reg->var_off.value) { 6557 char tn_buf[48]; 6558 6559 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 6560 verbose(env, 6561 "R%d is ptr_%s invalid variable offset: off=%d, var_off=%s\n", 6562 regno, tname, off, tn_buf); 6563 return -EACCES; 6564 } 6565 6566 if (reg->type & MEM_USER) { 6567 verbose(env, 6568 "R%d is ptr_%s access user memory: off=%d\n", 6569 regno, tname, off); 6570 return -EACCES; 6571 } 6572 6573 if (reg->type & MEM_PERCPU) { 6574 verbose(env, 6575 "R%d is ptr_%s access percpu memory: off=%d\n", 6576 regno, tname, off); 6577 return -EACCES; 6578 } 6579 6580 if (env->ops->btf_struct_access && !type_is_alloc(reg->type) && atype == BPF_WRITE) { 6581 if (!btf_is_kernel(reg->btf)) { 6582 verbose(env, "verifier internal error: reg->btf must be kernel btf\n"); 6583 return -EFAULT; 6584 } 6585 ret = env->ops->btf_struct_access(&env->log, reg, off, size); 6586 } else { 6587 /* Writes are permitted with default btf_struct_access for 6588 * program allocated objects (which always have ref_obj_id > 0), 6589 * but not for untrusted PTR_TO_BTF_ID | MEM_ALLOC. 6590 */ 6591 if (atype != BPF_READ && !type_is_ptr_alloc_obj(reg->type)) { 6592 verbose(env, "only read is supported\n"); 6593 return -EACCES; 6594 } 6595 6596 if (type_is_alloc(reg->type) && !type_is_non_owning_ref(reg->type) && 6597 !(reg->type & MEM_RCU) && !reg->ref_obj_id) { 6598 verbose(env, "verifier internal error: ref_obj_id for allocated object must be non-zero\n"); 6599 return -EFAULT; 6600 } 6601 6602 ret = btf_struct_access(&env->log, reg, off, size, atype, &btf_id, &flag, &field_name); 6603 } 6604 6605 if (ret < 0) 6606 return ret; 6607 6608 if (ret != PTR_TO_BTF_ID) { 6609 /* just mark; */ 6610 6611 } else if (type_flag(reg->type) & PTR_UNTRUSTED) { 6612 /* If this is an untrusted pointer, all pointers formed by walking it 6613 * also inherit the untrusted flag. 6614 */ 6615 flag = PTR_UNTRUSTED; 6616 6617 } else if (is_trusted_reg(reg) || is_rcu_reg(reg)) { 6618 /* By default any pointer obtained from walking a trusted pointer is no 6619 * longer trusted, unless the field being accessed has explicitly been 6620 * marked as inheriting its parent's state of trust (either full or RCU). 6621 * For example: 6622 * 'cgroups' pointer is untrusted if task->cgroups dereference 6623 * happened in a sleepable program outside of bpf_rcu_read_lock() 6624 * section. In a non-sleepable program it's trusted while in RCU CS (aka MEM_RCU). 6625 * Note bpf_rcu_read_unlock() converts MEM_RCU pointers to PTR_UNTRUSTED. 6626 * 6627 * A regular RCU-protected pointer with __rcu tag can also be deemed 6628 * trusted if we are in an RCU CS. Such pointer can be NULL. 6629 */ 6630 if (type_is_trusted(env, reg, field_name, btf_id)) { 6631 flag |= PTR_TRUSTED; 6632 } else if (in_rcu_cs(env) && !type_may_be_null(reg->type)) { 6633 if (type_is_rcu(env, reg, field_name, btf_id)) { 6634 /* ignore __rcu tag and mark it MEM_RCU */ 6635 flag |= MEM_RCU; 6636 } else if (flag & MEM_RCU || 6637 type_is_rcu_or_null(env, reg, field_name, btf_id)) { 6638 /* __rcu tagged pointers can be NULL */ 6639 flag |= MEM_RCU | PTR_MAYBE_NULL; 6640 6641 /* We always trust them */ 6642 if (type_is_rcu_or_null(env, reg, field_name, btf_id) && 6643 flag & PTR_UNTRUSTED) 6644 flag &= ~PTR_UNTRUSTED; 6645 } else if (flag & (MEM_PERCPU | MEM_USER)) { 6646 /* keep as-is */ 6647 } else { 6648 /* walking unknown pointers yields old deprecated PTR_TO_BTF_ID */ 6649 clear_trusted_flags(&flag); 6650 } 6651 } else { 6652 /* 6653 * If not in RCU CS or MEM_RCU pointer can be NULL then 6654 * aggressively mark as untrusted otherwise such 6655 * pointers will be plain PTR_TO_BTF_ID without flags 6656 * and will be allowed to be passed into helpers for 6657 * compat reasons. 6658 */ 6659 flag = PTR_UNTRUSTED; 6660 } 6661 } else { 6662 /* Old compat. Deprecated */ 6663 clear_trusted_flags(&flag); 6664 } 6665 6666 if (atype == BPF_READ && value_regno >= 0) 6667 mark_btf_ld_reg(env, regs, value_regno, ret, reg->btf, btf_id, flag); 6668 6669 return 0; 6670 } 6671 6672 static int check_ptr_to_map_access(struct bpf_verifier_env *env, 6673 struct bpf_reg_state *regs, 6674 int regno, int off, int size, 6675 enum bpf_access_type atype, 6676 int value_regno) 6677 { 6678 struct bpf_reg_state *reg = regs + regno; 6679 struct bpf_map *map = reg->map_ptr; 6680 struct bpf_reg_state map_reg; 6681 enum bpf_type_flag flag = 0; 6682 const struct btf_type *t; 6683 const char *tname; 6684 u32 btf_id; 6685 int ret; 6686 6687 if (!btf_vmlinux) { 6688 verbose(env, "map_ptr access not supported without CONFIG_DEBUG_INFO_BTF\n"); 6689 return -ENOTSUPP; 6690 } 6691 6692 if (!map->ops->map_btf_id || !*map->ops->map_btf_id) { 6693 verbose(env, "map_ptr access not supported for map type %d\n", 6694 map->map_type); 6695 return -ENOTSUPP; 6696 } 6697 6698 t = btf_type_by_id(btf_vmlinux, *map->ops->map_btf_id); 6699 tname = btf_name_by_offset(btf_vmlinux, t->name_off); 6700 6701 if (!env->allow_ptr_leaks) { 6702 verbose(env, 6703 "'struct %s' access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n", 6704 tname); 6705 return -EPERM; 6706 } 6707 6708 if (off < 0) { 6709 verbose(env, "R%d is %s invalid negative access: off=%d\n", 6710 regno, tname, off); 6711 return -EACCES; 6712 } 6713 6714 if (atype != BPF_READ) { 6715 verbose(env, "only read from %s is supported\n", tname); 6716 return -EACCES; 6717 } 6718 6719 /* Simulate access to a PTR_TO_BTF_ID */ 6720 memset(&map_reg, 0, sizeof(map_reg)); 6721 mark_btf_ld_reg(env, &map_reg, 0, PTR_TO_BTF_ID, btf_vmlinux, *map->ops->map_btf_id, 0); 6722 ret = btf_struct_access(&env->log, &map_reg, off, size, atype, &btf_id, &flag, NULL); 6723 if (ret < 0) 6724 return ret; 6725 6726 if (value_regno >= 0) 6727 mark_btf_ld_reg(env, regs, value_regno, ret, btf_vmlinux, btf_id, flag); 6728 6729 return 0; 6730 } 6731 6732 /* Check that the stack access at the given offset is within bounds. The 6733 * maximum valid offset is -1. 6734 * 6735 * The minimum valid offset is -MAX_BPF_STACK for writes, and 6736 * -state->allocated_stack for reads. 6737 */ 6738 static int check_stack_slot_within_bounds(int off, 6739 struct bpf_func_state *state, 6740 enum bpf_access_type t) 6741 { 6742 int min_valid_off; 6743 6744 if (t == BPF_WRITE) 6745 min_valid_off = -MAX_BPF_STACK; 6746 else 6747 min_valid_off = -state->allocated_stack; 6748 6749 if (off < min_valid_off || off > -1) 6750 return -EACCES; 6751 return 0; 6752 } 6753 6754 /* Check that the stack access at 'regno + off' falls within the maximum stack 6755 * bounds. 6756 * 6757 * 'off' includes `regno->offset`, but not its dynamic part (if any). 6758 */ 6759 static int check_stack_access_within_bounds( 6760 struct bpf_verifier_env *env, 6761 int regno, int off, int access_size, 6762 enum bpf_access_src src, enum bpf_access_type type) 6763 { 6764 struct bpf_reg_state *regs = cur_regs(env); 6765 struct bpf_reg_state *reg = regs + regno; 6766 struct bpf_func_state *state = func(env, reg); 6767 int min_off, max_off; 6768 int err; 6769 char *err_extra; 6770 6771 if (src == ACCESS_HELPER) 6772 /* We don't know if helpers are reading or writing (or both). */ 6773 err_extra = " indirect access to"; 6774 else if (type == BPF_READ) 6775 err_extra = " read from"; 6776 else 6777 err_extra = " write to"; 6778 6779 if (tnum_is_const(reg->var_off)) { 6780 min_off = reg->var_off.value + off; 6781 if (access_size > 0) 6782 max_off = min_off + access_size - 1; 6783 else 6784 max_off = min_off; 6785 } else { 6786 if (reg->smax_value >= BPF_MAX_VAR_OFF || 6787 reg->smin_value <= -BPF_MAX_VAR_OFF) { 6788 verbose(env, "invalid unbounded variable-offset%s stack R%d\n", 6789 err_extra, regno); 6790 return -EACCES; 6791 } 6792 min_off = reg->smin_value + off; 6793 if (access_size > 0) 6794 max_off = reg->smax_value + off + access_size - 1; 6795 else 6796 max_off = min_off; 6797 } 6798 6799 err = check_stack_slot_within_bounds(min_off, state, type); 6800 if (!err) 6801 err = check_stack_slot_within_bounds(max_off, state, type); 6802 6803 if (err) { 6804 if (tnum_is_const(reg->var_off)) { 6805 verbose(env, "invalid%s stack R%d off=%d size=%d\n", 6806 err_extra, regno, off, access_size); 6807 } else { 6808 char tn_buf[48]; 6809 6810 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 6811 verbose(env, "invalid variable-offset%s stack R%d var_off=%s size=%d\n", 6812 err_extra, regno, tn_buf, access_size); 6813 } 6814 } 6815 return err; 6816 } 6817 6818 /* check whether memory at (regno + off) is accessible for t = (read | write) 6819 * if t==write, value_regno is a register which value is stored into memory 6820 * if t==read, value_regno is a register which will receive the value from memory 6821 * if t==write && value_regno==-1, some unknown value is stored into memory 6822 * if t==read && value_regno==-1, don't care what we read from memory 6823 */ 6824 static int check_mem_access(struct bpf_verifier_env *env, int insn_idx, u32 regno, 6825 int off, int bpf_size, enum bpf_access_type t, 6826 int value_regno, bool strict_alignment_once, bool is_ldsx) 6827 { 6828 struct bpf_reg_state *regs = cur_regs(env); 6829 struct bpf_reg_state *reg = regs + regno; 6830 struct bpf_func_state *state; 6831 int size, err = 0; 6832 6833 size = bpf_size_to_bytes(bpf_size); 6834 if (size < 0) 6835 return size; 6836 6837 /* alignment checks will add in reg->off themselves */ 6838 err = check_ptr_alignment(env, reg, off, size, strict_alignment_once); 6839 if (err) 6840 return err; 6841 6842 /* for access checks, reg->off is just part of off */ 6843 off += reg->off; 6844 6845 if (reg->type == PTR_TO_MAP_KEY) { 6846 if (t == BPF_WRITE) { 6847 verbose(env, "write to change key R%d not allowed\n", regno); 6848 return -EACCES; 6849 } 6850 6851 err = check_mem_region_access(env, regno, off, size, 6852 reg->map_ptr->key_size, false); 6853 if (err) 6854 return err; 6855 if (value_regno >= 0) 6856 mark_reg_unknown(env, regs, value_regno); 6857 } else if (reg->type == PTR_TO_MAP_VALUE) { 6858 struct btf_field *kptr_field = NULL; 6859 6860 if (t == BPF_WRITE && value_regno >= 0 && 6861 is_pointer_value(env, value_regno)) { 6862 verbose(env, "R%d leaks addr into map\n", value_regno); 6863 return -EACCES; 6864 } 6865 err = check_map_access_type(env, regno, off, size, t); 6866 if (err) 6867 return err; 6868 err = check_map_access(env, regno, off, size, false, ACCESS_DIRECT); 6869 if (err) 6870 return err; 6871 if (tnum_is_const(reg->var_off)) 6872 kptr_field = btf_record_find(reg->map_ptr->record, 6873 off + reg->var_off.value, BPF_KPTR); 6874 if (kptr_field) { 6875 err = check_map_kptr_access(env, regno, value_regno, insn_idx, kptr_field); 6876 } else if (t == BPF_READ && value_regno >= 0) { 6877 struct bpf_map *map = reg->map_ptr; 6878 6879 /* if map is read-only, track its contents as scalars */ 6880 if (tnum_is_const(reg->var_off) && 6881 bpf_map_is_rdonly(map) && 6882 map->ops->map_direct_value_addr) { 6883 int map_off = off + reg->var_off.value; 6884 u64 val = 0; 6885 6886 err = bpf_map_direct_read(map, map_off, size, 6887 &val, is_ldsx); 6888 if (err) 6889 return err; 6890 6891 regs[value_regno].type = SCALAR_VALUE; 6892 __mark_reg_known(®s[value_regno], val); 6893 } else { 6894 mark_reg_unknown(env, regs, value_regno); 6895 } 6896 } 6897 } else if (base_type(reg->type) == PTR_TO_MEM) { 6898 bool rdonly_mem = type_is_rdonly_mem(reg->type); 6899 6900 if (type_may_be_null(reg->type)) { 6901 verbose(env, "R%d invalid mem access '%s'\n", regno, 6902 reg_type_str(env, reg->type)); 6903 return -EACCES; 6904 } 6905 6906 if (t == BPF_WRITE && rdonly_mem) { 6907 verbose(env, "R%d cannot write into %s\n", 6908 regno, reg_type_str(env, reg->type)); 6909 return -EACCES; 6910 } 6911 6912 if (t == BPF_WRITE && value_regno >= 0 && 6913 is_pointer_value(env, value_regno)) { 6914 verbose(env, "R%d leaks addr into mem\n", value_regno); 6915 return -EACCES; 6916 } 6917 6918 err = check_mem_region_access(env, regno, off, size, 6919 reg->mem_size, false); 6920 if (!err && value_regno >= 0 && (t == BPF_READ || rdonly_mem)) 6921 mark_reg_unknown(env, regs, value_regno); 6922 } else if (reg->type == PTR_TO_CTX) { 6923 enum bpf_reg_type reg_type = SCALAR_VALUE; 6924 struct btf *btf = NULL; 6925 u32 btf_id = 0; 6926 6927 if (t == BPF_WRITE && value_regno >= 0 && 6928 is_pointer_value(env, value_regno)) { 6929 verbose(env, "R%d leaks addr into ctx\n", value_regno); 6930 return -EACCES; 6931 } 6932 6933 err = check_ptr_off_reg(env, reg, regno); 6934 if (err < 0) 6935 return err; 6936 6937 err = check_ctx_access(env, insn_idx, off, size, t, ®_type, &btf, 6938 &btf_id); 6939 if (err) 6940 verbose_linfo(env, insn_idx, "; "); 6941 if (!err && t == BPF_READ && value_regno >= 0) { 6942 /* ctx access returns either a scalar, or a 6943 * PTR_TO_PACKET[_META,_END]. In the latter 6944 * case, we know the offset is zero. 6945 */ 6946 if (reg_type == SCALAR_VALUE) { 6947 mark_reg_unknown(env, regs, value_regno); 6948 } else { 6949 mark_reg_known_zero(env, regs, 6950 value_regno); 6951 if (type_may_be_null(reg_type)) 6952 regs[value_regno].id = ++env->id_gen; 6953 /* A load of ctx field could have different 6954 * actual load size with the one encoded in the 6955 * insn. When the dst is PTR, it is for sure not 6956 * a sub-register. 6957 */ 6958 regs[value_regno].subreg_def = DEF_NOT_SUBREG; 6959 if (base_type(reg_type) == PTR_TO_BTF_ID) { 6960 regs[value_regno].btf = btf; 6961 regs[value_regno].btf_id = btf_id; 6962 } 6963 } 6964 regs[value_regno].type = reg_type; 6965 } 6966 6967 } else if (reg->type == PTR_TO_STACK) { 6968 /* Basic bounds checks. */ 6969 err = check_stack_access_within_bounds(env, regno, off, size, ACCESS_DIRECT, t); 6970 if (err) 6971 return err; 6972 6973 state = func(env, reg); 6974 err = update_stack_depth(env, state, off); 6975 if (err) 6976 return err; 6977 6978 if (t == BPF_READ) 6979 err = check_stack_read(env, regno, off, size, 6980 value_regno); 6981 else 6982 err = check_stack_write(env, regno, off, size, 6983 value_regno, insn_idx); 6984 } else if (reg_is_pkt_pointer(reg)) { 6985 if (t == BPF_WRITE && !may_access_direct_pkt_data(env, NULL, t)) { 6986 verbose(env, "cannot write into packet\n"); 6987 return -EACCES; 6988 } 6989 if (t == BPF_WRITE && value_regno >= 0 && 6990 is_pointer_value(env, value_regno)) { 6991 verbose(env, "R%d leaks addr into packet\n", 6992 value_regno); 6993 return -EACCES; 6994 } 6995 err = check_packet_access(env, regno, off, size, false); 6996 if (!err && t == BPF_READ && value_regno >= 0) 6997 mark_reg_unknown(env, regs, value_regno); 6998 } else if (reg->type == PTR_TO_FLOW_KEYS) { 6999 if (t == BPF_WRITE && value_regno >= 0 && 7000 is_pointer_value(env, value_regno)) { 7001 verbose(env, "R%d leaks addr into flow keys\n", 7002 value_regno); 7003 return -EACCES; 7004 } 7005 7006 err = check_flow_keys_access(env, off, size); 7007 if (!err && t == BPF_READ && value_regno >= 0) 7008 mark_reg_unknown(env, regs, value_regno); 7009 } else if (type_is_sk_pointer(reg->type)) { 7010 if (t == BPF_WRITE) { 7011 verbose(env, "R%d cannot write into %s\n", 7012 regno, reg_type_str(env, reg->type)); 7013 return -EACCES; 7014 } 7015 err = check_sock_access(env, insn_idx, regno, off, size, t); 7016 if (!err && value_regno >= 0) 7017 mark_reg_unknown(env, regs, value_regno); 7018 } else if (reg->type == PTR_TO_TP_BUFFER) { 7019 err = check_tp_buffer_access(env, reg, regno, off, size); 7020 if (!err && t == BPF_READ && value_regno >= 0) 7021 mark_reg_unknown(env, regs, value_regno); 7022 } else if (base_type(reg->type) == PTR_TO_BTF_ID && 7023 !type_may_be_null(reg->type)) { 7024 err = check_ptr_to_btf_access(env, regs, regno, off, size, t, 7025 value_regno); 7026 } else if (reg->type == CONST_PTR_TO_MAP) { 7027 err = check_ptr_to_map_access(env, regs, regno, off, size, t, 7028 value_regno); 7029 } else if (base_type(reg->type) == PTR_TO_BUF) { 7030 bool rdonly_mem = type_is_rdonly_mem(reg->type); 7031 u32 *max_access; 7032 7033 if (rdonly_mem) { 7034 if (t == BPF_WRITE) { 7035 verbose(env, "R%d cannot write into %s\n", 7036 regno, reg_type_str(env, reg->type)); 7037 return -EACCES; 7038 } 7039 max_access = &env->prog->aux->max_rdonly_access; 7040 } else { 7041 max_access = &env->prog->aux->max_rdwr_access; 7042 } 7043 7044 err = check_buffer_access(env, reg, regno, off, size, false, 7045 max_access); 7046 7047 if (!err && value_regno >= 0 && (rdonly_mem || t == BPF_READ)) 7048 mark_reg_unknown(env, regs, value_regno); 7049 } else { 7050 verbose(env, "R%d invalid mem access '%s'\n", regno, 7051 reg_type_str(env, reg->type)); 7052 return -EACCES; 7053 } 7054 7055 if (!err && size < BPF_REG_SIZE && value_regno >= 0 && t == BPF_READ && 7056 regs[value_regno].type == SCALAR_VALUE) { 7057 if (!is_ldsx) 7058 /* b/h/w load zero-extends, mark upper bits as known 0 */ 7059 coerce_reg_to_size(®s[value_regno], size); 7060 else 7061 coerce_reg_to_size_sx(®s[value_regno], size); 7062 } 7063 return err; 7064 } 7065 7066 static int check_atomic(struct bpf_verifier_env *env, int insn_idx, struct bpf_insn *insn) 7067 { 7068 int load_reg; 7069 int err; 7070 7071 switch (insn->imm) { 7072 case BPF_ADD: 7073 case BPF_ADD | BPF_FETCH: 7074 case BPF_AND: 7075 case BPF_AND | BPF_FETCH: 7076 case BPF_OR: 7077 case BPF_OR | BPF_FETCH: 7078 case BPF_XOR: 7079 case BPF_XOR | BPF_FETCH: 7080 case BPF_XCHG: 7081 case BPF_CMPXCHG: 7082 break; 7083 default: 7084 verbose(env, "BPF_ATOMIC uses invalid atomic opcode %02x\n", insn->imm); 7085 return -EINVAL; 7086 } 7087 7088 if (BPF_SIZE(insn->code) != BPF_W && BPF_SIZE(insn->code) != BPF_DW) { 7089 verbose(env, "invalid atomic operand size\n"); 7090 return -EINVAL; 7091 } 7092 7093 /* check src1 operand */ 7094 err = check_reg_arg(env, insn->src_reg, SRC_OP); 7095 if (err) 7096 return err; 7097 7098 /* check src2 operand */ 7099 err = check_reg_arg(env, insn->dst_reg, SRC_OP); 7100 if (err) 7101 return err; 7102 7103 if (insn->imm == BPF_CMPXCHG) { 7104 /* Check comparison of R0 with memory location */ 7105 const u32 aux_reg = BPF_REG_0; 7106 7107 err = check_reg_arg(env, aux_reg, SRC_OP); 7108 if (err) 7109 return err; 7110 7111 if (is_pointer_value(env, aux_reg)) { 7112 verbose(env, "R%d leaks addr into mem\n", aux_reg); 7113 return -EACCES; 7114 } 7115 } 7116 7117 if (is_pointer_value(env, insn->src_reg)) { 7118 verbose(env, "R%d leaks addr into mem\n", insn->src_reg); 7119 return -EACCES; 7120 } 7121 7122 if (is_ctx_reg(env, insn->dst_reg) || 7123 is_pkt_reg(env, insn->dst_reg) || 7124 is_flow_key_reg(env, insn->dst_reg) || 7125 is_sk_reg(env, insn->dst_reg)) { 7126 verbose(env, "BPF_ATOMIC stores into R%d %s is not allowed\n", 7127 insn->dst_reg, 7128 reg_type_str(env, reg_state(env, insn->dst_reg)->type)); 7129 return -EACCES; 7130 } 7131 7132 if (insn->imm & BPF_FETCH) { 7133 if (insn->imm == BPF_CMPXCHG) 7134 load_reg = BPF_REG_0; 7135 else 7136 load_reg = insn->src_reg; 7137 7138 /* check and record load of old value */ 7139 err = check_reg_arg(env, load_reg, DST_OP); 7140 if (err) 7141 return err; 7142 } else { 7143 /* This instruction accesses a memory location but doesn't 7144 * actually load it into a register. 7145 */ 7146 load_reg = -1; 7147 } 7148 7149 /* Check whether we can read the memory, with second call for fetch 7150 * case to simulate the register fill. 7151 */ 7152 err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off, 7153 BPF_SIZE(insn->code), BPF_READ, -1, true, false); 7154 if (!err && load_reg >= 0) 7155 err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off, 7156 BPF_SIZE(insn->code), BPF_READ, load_reg, 7157 true, false); 7158 if (err) 7159 return err; 7160 7161 /* Check whether we can write into the same memory. */ 7162 err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off, 7163 BPF_SIZE(insn->code), BPF_WRITE, -1, true, false); 7164 if (err) 7165 return err; 7166 7167 return 0; 7168 } 7169 7170 /* When register 'regno' is used to read the stack (either directly or through 7171 * a helper function) make sure that it's within stack boundary and, depending 7172 * on the access type, that all elements of the stack are initialized. 7173 * 7174 * 'off' includes 'regno->off', but not its dynamic part (if any). 7175 * 7176 * All registers that have been spilled on the stack in the slots within the 7177 * read offsets are marked as read. 7178 */ 7179 static int check_stack_range_initialized( 7180 struct bpf_verifier_env *env, int regno, int off, 7181 int access_size, bool zero_size_allowed, 7182 enum bpf_access_src type, struct bpf_call_arg_meta *meta) 7183 { 7184 struct bpf_reg_state *reg = reg_state(env, regno); 7185 struct bpf_func_state *state = func(env, reg); 7186 int err, min_off, max_off, i, j, slot, spi; 7187 char *err_extra = type == ACCESS_HELPER ? " indirect" : ""; 7188 enum bpf_access_type bounds_check_type; 7189 /* Some accesses can write anything into the stack, others are 7190 * read-only. 7191 */ 7192 bool clobber = false; 7193 7194 if (access_size == 0 && !zero_size_allowed) { 7195 verbose(env, "invalid zero-sized read\n"); 7196 return -EACCES; 7197 } 7198 7199 if (type == ACCESS_HELPER) { 7200 /* The bounds checks for writes are more permissive than for 7201 * reads. However, if raw_mode is not set, we'll do extra 7202 * checks below. 7203 */ 7204 bounds_check_type = BPF_WRITE; 7205 clobber = true; 7206 } else { 7207 bounds_check_type = BPF_READ; 7208 } 7209 err = check_stack_access_within_bounds(env, regno, off, access_size, 7210 type, bounds_check_type); 7211 if (err) 7212 return err; 7213 7214 7215 if (tnum_is_const(reg->var_off)) { 7216 min_off = max_off = reg->var_off.value + off; 7217 } else { 7218 /* Variable offset is prohibited for unprivileged mode for 7219 * simplicity since it requires corresponding support in 7220 * Spectre masking for stack ALU. 7221 * See also retrieve_ptr_limit(). 7222 */ 7223 if (!env->bypass_spec_v1) { 7224 char tn_buf[48]; 7225 7226 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 7227 verbose(env, "R%d%s variable offset stack access prohibited for !root, var_off=%s\n", 7228 regno, err_extra, tn_buf); 7229 return -EACCES; 7230 } 7231 /* Only initialized buffer on stack is allowed to be accessed 7232 * with variable offset. With uninitialized buffer it's hard to 7233 * guarantee that whole memory is marked as initialized on 7234 * helper return since specific bounds are unknown what may 7235 * cause uninitialized stack leaking. 7236 */ 7237 if (meta && meta->raw_mode) 7238 meta = NULL; 7239 7240 min_off = reg->smin_value + off; 7241 max_off = reg->smax_value + off; 7242 } 7243 7244 if (meta && meta->raw_mode) { 7245 /* Ensure we won't be overwriting dynptrs when simulating byte 7246 * by byte access in check_helper_call using meta.access_size. 7247 * This would be a problem if we have a helper in the future 7248 * which takes: 7249 * 7250 * helper(uninit_mem, len, dynptr) 7251 * 7252 * Now, uninint_mem may overlap with dynptr pointer. Hence, it 7253 * may end up writing to dynptr itself when touching memory from 7254 * arg 1. This can be relaxed on a case by case basis for known 7255 * safe cases, but reject due to the possibilitiy of aliasing by 7256 * default. 7257 */ 7258 for (i = min_off; i < max_off + access_size; i++) { 7259 int stack_off = -i - 1; 7260 7261 spi = __get_spi(i); 7262 /* raw_mode may write past allocated_stack */ 7263 if (state->allocated_stack <= stack_off) 7264 continue; 7265 if (state->stack[spi].slot_type[stack_off % BPF_REG_SIZE] == STACK_DYNPTR) { 7266 verbose(env, "potential write to dynptr at off=%d disallowed\n", i); 7267 return -EACCES; 7268 } 7269 } 7270 meta->access_size = access_size; 7271 meta->regno = regno; 7272 return 0; 7273 } 7274 7275 for (i = min_off; i < max_off + access_size; i++) { 7276 u8 *stype; 7277 7278 slot = -i - 1; 7279 spi = slot / BPF_REG_SIZE; 7280 if (state->allocated_stack <= slot) 7281 goto err; 7282 stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE]; 7283 if (*stype == STACK_MISC) 7284 goto mark; 7285 if ((*stype == STACK_ZERO) || 7286 (*stype == STACK_INVALID && env->allow_uninit_stack)) { 7287 if (clobber) { 7288 /* helper can write anything into the stack */ 7289 *stype = STACK_MISC; 7290 } 7291 goto mark; 7292 } 7293 7294 if (is_spilled_reg(&state->stack[spi]) && 7295 (state->stack[spi].spilled_ptr.type == SCALAR_VALUE || 7296 env->allow_ptr_leaks)) { 7297 if (clobber) { 7298 __mark_reg_unknown(env, &state->stack[spi].spilled_ptr); 7299 for (j = 0; j < BPF_REG_SIZE; j++) 7300 scrub_spilled_slot(&state->stack[spi].slot_type[j]); 7301 } 7302 goto mark; 7303 } 7304 7305 err: 7306 if (tnum_is_const(reg->var_off)) { 7307 verbose(env, "invalid%s read from stack R%d off %d+%d size %d\n", 7308 err_extra, regno, min_off, i - min_off, access_size); 7309 } else { 7310 char tn_buf[48]; 7311 7312 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 7313 verbose(env, "invalid%s read from stack R%d var_off %s+%d size %d\n", 7314 err_extra, regno, tn_buf, i - min_off, access_size); 7315 } 7316 return -EACCES; 7317 mark: 7318 /* reading any byte out of 8-byte 'spill_slot' will cause 7319 * the whole slot to be marked as 'read' 7320 */ 7321 mark_reg_read(env, &state->stack[spi].spilled_ptr, 7322 state->stack[spi].spilled_ptr.parent, 7323 REG_LIVE_READ64); 7324 /* We do not set REG_LIVE_WRITTEN for stack slot, as we can not 7325 * be sure that whether stack slot is written to or not. Hence, 7326 * we must still conservatively propagate reads upwards even if 7327 * helper may write to the entire memory range. 7328 */ 7329 } 7330 return update_stack_depth(env, state, min_off); 7331 } 7332 7333 static int check_helper_mem_access(struct bpf_verifier_env *env, int regno, 7334 int access_size, bool zero_size_allowed, 7335 struct bpf_call_arg_meta *meta) 7336 { 7337 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno]; 7338 u32 *max_access; 7339 7340 switch (base_type(reg->type)) { 7341 case PTR_TO_PACKET: 7342 case PTR_TO_PACKET_META: 7343 return check_packet_access(env, regno, reg->off, access_size, 7344 zero_size_allowed); 7345 case PTR_TO_MAP_KEY: 7346 if (meta && meta->raw_mode) { 7347 verbose(env, "R%d cannot write into %s\n", regno, 7348 reg_type_str(env, reg->type)); 7349 return -EACCES; 7350 } 7351 return check_mem_region_access(env, regno, reg->off, access_size, 7352 reg->map_ptr->key_size, false); 7353 case PTR_TO_MAP_VALUE: 7354 if (check_map_access_type(env, regno, reg->off, access_size, 7355 meta && meta->raw_mode ? BPF_WRITE : 7356 BPF_READ)) 7357 return -EACCES; 7358 return check_map_access(env, regno, reg->off, access_size, 7359 zero_size_allowed, ACCESS_HELPER); 7360 case PTR_TO_MEM: 7361 if (type_is_rdonly_mem(reg->type)) { 7362 if (meta && meta->raw_mode) { 7363 verbose(env, "R%d cannot write into %s\n", regno, 7364 reg_type_str(env, reg->type)); 7365 return -EACCES; 7366 } 7367 } 7368 return check_mem_region_access(env, regno, reg->off, 7369 access_size, reg->mem_size, 7370 zero_size_allowed); 7371 case PTR_TO_BUF: 7372 if (type_is_rdonly_mem(reg->type)) { 7373 if (meta && meta->raw_mode) { 7374 verbose(env, "R%d cannot write into %s\n", regno, 7375 reg_type_str(env, reg->type)); 7376 return -EACCES; 7377 } 7378 7379 max_access = &env->prog->aux->max_rdonly_access; 7380 } else { 7381 max_access = &env->prog->aux->max_rdwr_access; 7382 } 7383 return check_buffer_access(env, reg, regno, reg->off, 7384 access_size, zero_size_allowed, 7385 max_access); 7386 case PTR_TO_STACK: 7387 return check_stack_range_initialized( 7388 env, 7389 regno, reg->off, access_size, 7390 zero_size_allowed, ACCESS_HELPER, meta); 7391 case PTR_TO_BTF_ID: 7392 return check_ptr_to_btf_access(env, regs, regno, reg->off, 7393 access_size, BPF_READ, -1); 7394 case PTR_TO_CTX: 7395 /* in case the function doesn't know how to access the context, 7396 * (because we are in a program of type SYSCALL for example), we 7397 * can not statically check its size. 7398 * Dynamically check it now. 7399 */ 7400 if (!env->ops->convert_ctx_access) { 7401 enum bpf_access_type atype = meta && meta->raw_mode ? BPF_WRITE : BPF_READ; 7402 int offset = access_size - 1; 7403 7404 /* Allow zero-byte read from PTR_TO_CTX */ 7405 if (access_size == 0) 7406 return zero_size_allowed ? 0 : -EACCES; 7407 7408 return check_mem_access(env, env->insn_idx, regno, offset, BPF_B, 7409 atype, -1, false, false); 7410 } 7411 7412 fallthrough; 7413 default: /* scalar_value or invalid ptr */ 7414 /* Allow zero-byte read from NULL, regardless of pointer type */ 7415 if (zero_size_allowed && access_size == 0 && 7416 register_is_null(reg)) 7417 return 0; 7418 7419 verbose(env, "R%d type=%s ", regno, 7420 reg_type_str(env, reg->type)); 7421 verbose(env, "expected=%s\n", reg_type_str(env, PTR_TO_STACK)); 7422 return -EACCES; 7423 } 7424 } 7425 7426 static int check_mem_size_reg(struct bpf_verifier_env *env, 7427 struct bpf_reg_state *reg, u32 regno, 7428 bool zero_size_allowed, 7429 struct bpf_call_arg_meta *meta) 7430 { 7431 int err; 7432 7433 /* This is used to refine r0 return value bounds for helpers 7434 * that enforce this value as an upper bound on return values. 7435 * See do_refine_retval_range() for helpers that can refine 7436 * the return value. C type of helper is u32 so we pull register 7437 * bound from umax_value however, if negative verifier errors 7438 * out. Only upper bounds can be learned because retval is an 7439 * int type and negative retvals are allowed. 7440 */ 7441 meta->msize_max_value = reg->umax_value; 7442 7443 /* The register is SCALAR_VALUE; the access check 7444 * happens using its boundaries. 7445 */ 7446 if (!tnum_is_const(reg->var_off)) 7447 /* For unprivileged variable accesses, disable raw 7448 * mode so that the program is required to 7449 * initialize all the memory that the helper could 7450 * just partially fill up. 7451 */ 7452 meta = NULL; 7453 7454 if (reg->smin_value < 0) { 7455 verbose(env, "R%d min value is negative, either use unsigned or 'var &= const'\n", 7456 regno); 7457 return -EACCES; 7458 } 7459 7460 if (reg->umin_value == 0) { 7461 err = check_helper_mem_access(env, regno - 1, 0, 7462 zero_size_allowed, 7463 meta); 7464 if (err) 7465 return err; 7466 } 7467 7468 if (reg->umax_value >= BPF_MAX_VAR_SIZ) { 7469 verbose(env, "R%d unbounded memory access, use 'var &= const' or 'if (var < const)'\n", 7470 regno); 7471 return -EACCES; 7472 } 7473 err = check_helper_mem_access(env, regno - 1, 7474 reg->umax_value, 7475 zero_size_allowed, meta); 7476 if (!err) 7477 err = mark_chain_precision(env, regno); 7478 return err; 7479 } 7480 7481 int check_mem_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg, 7482 u32 regno, u32 mem_size) 7483 { 7484 bool may_be_null = type_may_be_null(reg->type); 7485 struct bpf_reg_state saved_reg; 7486 struct bpf_call_arg_meta meta; 7487 int err; 7488 7489 if (register_is_null(reg)) 7490 return 0; 7491 7492 memset(&meta, 0, sizeof(meta)); 7493 /* Assuming that the register contains a value check if the memory 7494 * access is safe. Temporarily save and restore the register's state as 7495 * the conversion shouldn't be visible to a caller. 7496 */ 7497 if (may_be_null) { 7498 saved_reg = *reg; 7499 mark_ptr_not_null_reg(reg); 7500 } 7501 7502 err = check_helper_mem_access(env, regno, mem_size, true, &meta); 7503 /* Check access for BPF_WRITE */ 7504 meta.raw_mode = true; 7505 err = err ?: check_helper_mem_access(env, regno, mem_size, true, &meta); 7506 7507 if (may_be_null) 7508 *reg = saved_reg; 7509 7510 return err; 7511 } 7512 7513 static int check_kfunc_mem_size_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg, 7514 u32 regno) 7515 { 7516 struct bpf_reg_state *mem_reg = &cur_regs(env)[regno - 1]; 7517 bool may_be_null = type_may_be_null(mem_reg->type); 7518 struct bpf_reg_state saved_reg; 7519 struct bpf_call_arg_meta meta; 7520 int err; 7521 7522 WARN_ON_ONCE(regno < BPF_REG_2 || regno > BPF_REG_5); 7523 7524 memset(&meta, 0, sizeof(meta)); 7525 7526 if (may_be_null) { 7527 saved_reg = *mem_reg; 7528 mark_ptr_not_null_reg(mem_reg); 7529 } 7530 7531 err = check_mem_size_reg(env, reg, regno, true, &meta); 7532 /* Check access for BPF_WRITE */ 7533 meta.raw_mode = true; 7534 err = err ?: check_mem_size_reg(env, reg, regno, true, &meta); 7535 7536 if (may_be_null) 7537 *mem_reg = saved_reg; 7538 return err; 7539 } 7540 7541 /* Implementation details: 7542 * bpf_map_lookup returns PTR_TO_MAP_VALUE_OR_NULL. 7543 * bpf_obj_new returns PTR_TO_BTF_ID | MEM_ALLOC | PTR_MAYBE_NULL. 7544 * Two bpf_map_lookups (even with the same key) will have different reg->id. 7545 * Two separate bpf_obj_new will also have different reg->id. 7546 * For traditional PTR_TO_MAP_VALUE or PTR_TO_BTF_ID | MEM_ALLOC, the verifier 7547 * clears reg->id after value_or_null->value transition, since the verifier only 7548 * cares about the range of access to valid map value pointer and doesn't care 7549 * about actual address of the map element. 7550 * For maps with 'struct bpf_spin_lock' inside map value the verifier keeps 7551 * reg->id > 0 after value_or_null->value transition. By doing so 7552 * two bpf_map_lookups will be considered two different pointers that 7553 * point to different bpf_spin_locks. Likewise for pointers to allocated objects 7554 * returned from bpf_obj_new. 7555 * The verifier allows taking only one bpf_spin_lock at a time to avoid 7556 * dead-locks. 7557 * Since only one bpf_spin_lock is allowed the checks are simpler than 7558 * reg_is_refcounted() logic. The verifier needs to remember only 7559 * one spin_lock instead of array of acquired_refs. 7560 * cur_state->active_lock remembers which map value element or allocated 7561 * object got locked and clears it after bpf_spin_unlock. 7562 */ 7563 static int process_spin_lock(struct bpf_verifier_env *env, int regno, 7564 bool is_lock) 7565 { 7566 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno]; 7567 struct bpf_verifier_state *cur = env->cur_state; 7568 bool is_const = tnum_is_const(reg->var_off); 7569 u64 val = reg->var_off.value; 7570 struct bpf_map *map = NULL; 7571 struct btf *btf = NULL; 7572 struct btf_record *rec; 7573 7574 if (!is_const) { 7575 verbose(env, 7576 "R%d doesn't have constant offset. bpf_spin_lock has to be at the constant offset\n", 7577 regno); 7578 return -EINVAL; 7579 } 7580 if (reg->type == PTR_TO_MAP_VALUE) { 7581 map = reg->map_ptr; 7582 if (!map->btf) { 7583 verbose(env, 7584 "map '%s' has to have BTF in order to use bpf_spin_lock\n", 7585 map->name); 7586 return -EINVAL; 7587 } 7588 } else { 7589 btf = reg->btf; 7590 } 7591 7592 rec = reg_btf_record(reg); 7593 if (!btf_record_has_field(rec, BPF_SPIN_LOCK)) { 7594 verbose(env, "%s '%s' has no valid bpf_spin_lock\n", map ? "map" : "local", 7595 map ? map->name : "kptr"); 7596 return -EINVAL; 7597 } 7598 if (rec->spin_lock_off != val + reg->off) { 7599 verbose(env, "off %lld doesn't point to 'struct bpf_spin_lock' that is at %d\n", 7600 val + reg->off, rec->spin_lock_off); 7601 return -EINVAL; 7602 } 7603 if (is_lock) { 7604 if (cur->active_lock.ptr) { 7605 verbose(env, 7606 "Locking two bpf_spin_locks are not allowed\n"); 7607 return -EINVAL; 7608 } 7609 if (map) 7610 cur->active_lock.ptr = map; 7611 else 7612 cur->active_lock.ptr = btf; 7613 cur->active_lock.id = reg->id; 7614 } else { 7615 void *ptr; 7616 7617 if (map) 7618 ptr = map; 7619 else 7620 ptr = btf; 7621 7622 if (!cur->active_lock.ptr) { 7623 verbose(env, "bpf_spin_unlock without taking a lock\n"); 7624 return -EINVAL; 7625 } 7626 if (cur->active_lock.ptr != ptr || 7627 cur->active_lock.id != reg->id) { 7628 verbose(env, "bpf_spin_unlock of different lock\n"); 7629 return -EINVAL; 7630 } 7631 7632 invalidate_non_owning_refs(env); 7633 7634 cur->active_lock.ptr = NULL; 7635 cur->active_lock.id = 0; 7636 } 7637 return 0; 7638 } 7639 7640 static int process_timer_func(struct bpf_verifier_env *env, int regno, 7641 struct bpf_call_arg_meta *meta) 7642 { 7643 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno]; 7644 bool is_const = tnum_is_const(reg->var_off); 7645 struct bpf_map *map = reg->map_ptr; 7646 u64 val = reg->var_off.value; 7647 7648 if (!is_const) { 7649 verbose(env, 7650 "R%d doesn't have constant offset. bpf_timer has to be at the constant offset\n", 7651 regno); 7652 return -EINVAL; 7653 } 7654 if (!map->btf) { 7655 verbose(env, "map '%s' has to have BTF in order to use bpf_timer\n", 7656 map->name); 7657 return -EINVAL; 7658 } 7659 if (!btf_record_has_field(map->record, BPF_TIMER)) { 7660 verbose(env, "map '%s' has no valid bpf_timer\n", map->name); 7661 return -EINVAL; 7662 } 7663 if (map->record->timer_off != val + reg->off) { 7664 verbose(env, "off %lld doesn't point to 'struct bpf_timer' that is at %d\n", 7665 val + reg->off, map->record->timer_off); 7666 return -EINVAL; 7667 } 7668 if (meta->map_ptr) { 7669 verbose(env, "verifier bug. Two map pointers in a timer helper\n"); 7670 return -EFAULT; 7671 } 7672 meta->map_uid = reg->map_uid; 7673 meta->map_ptr = map; 7674 return 0; 7675 } 7676 7677 static int process_kptr_func(struct bpf_verifier_env *env, int regno, 7678 struct bpf_call_arg_meta *meta) 7679 { 7680 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno]; 7681 struct bpf_map *map_ptr = reg->map_ptr; 7682 struct btf_field *kptr_field; 7683 u32 kptr_off; 7684 7685 if (!tnum_is_const(reg->var_off)) { 7686 verbose(env, 7687 "R%d doesn't have constant offset. kptr has to be at the constant offset\n", 7688 regno); 7689 return -EINVAL; 7690 } 7691 if (!map_ptr->btf) { 7692 verbose(env, "map '%s' has to have BTF in order to use bpf_kptr_xchg\n", 7693 map_ptr->name); 7694 return -EINVAL; 7695 } 7696 if (!btf_record_has_field(map_ptr->record, BPF_KPTR)) { 7697 verbose(env, "map '%s' has no valid kptr\n", map_ptr->name); 7698 return -EINVAL; 7699 } 7700 7701 meta->map_ptr = map_ptr; 7702 kptr_off = reg->off + reg->var_off.value; 7703 kptr_field = btf_record_find(map_ptr->record, kptr_off, BPF_KPTR); 7704 if (!kptr_field) { 7705 verbose(env, "off=%d doesn't point to kptr\n", kptr_off); 7706 return -EACCES; 7707 } 7708 if (kptr_field->type != BPF_KPTR_REF && kptr_field->type != BPF_KPTR_PERCPU) { 7709 verbose(env, "off=%d kptr isn't referenced kptr\n", kptr_off); 7710 return -EACCES; 7711 } 7712 meta->kptr_field = kptr_field; 7713 return 0; 7714 } 7715 7716 /* There are two register types representing a bpf_dynptr, one is PTR_TO_STACK 7717 * which points to a stack slot, and the other is CONST_PTR_TO_DYNPTR. 7718 * 7719 * In both cases we deal with the first 8 bytes, but need to mark the next 8 7720 * bytes as STACK_DYNPTR in case of PTR_TO_STACK. In case of 7721 * CONST_PTR_TO_DYNPTR, we are guaranteed to get the beginning of the object. 7722 * 7723 * Mutability of bpf_dynptr is at two levels, one is at the level of struct 7724 * bpf_dynptr itself, i.e. whether the helper is receiving a pointer to struct 7725 * bpf_dynptr or pointer to const struct bpf_dynptr. In the former case, it can 7726 * mutate the view of the dynptr and also possibly destroy it. In the latter 7727 * case, it cannot mutate the bpf_dynptr itself but it can still mutate the 7728 * memory that dynptr points to. 7729 * 7730 * The verifier will keep track both levels of mutation (bpf_dynptr's in 7731 * reg->type and the memory's in reg->dynptr.type), but there is no support for 7732 * readonly dynptr view yet, hence only the first case is tracked and checked. 7733 * 7734 * This is consistent with how C applies the const modifier to a struct object, 7735 * where the pointer itself inside bpf_dynptr becomes const but not what it 7736 * points to. 7737 * 7738 * Helpers which do not mutate the bpf_dynptr set MEM_RDONLY in their argument 7739 * type, and declare it as 'const struct bpf_dynptr *' in their prototype. 7740 */ 7741 static int process_dynptr_func(struct bpf_verifier_env *env, int regno, int insn_idx, 7742 enum bpf_arg_type arg_type, int clone_ref_obj_id) 7743 { 7744 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno]; 7745 int err; 7746 7747 /* MEM_UNINIT and MEM_RDONLY are exclusive, when applied to an 7748 * ARG_PTR_TO_DYNPTR (or ARG_PTR_TO_DYNPTR | DYNPTR_TYPE_*): 7749 */ 7750 if ((arg_type & (MEM_UNINIT | MEM_RDONLY)) == (MEM_UNINIT | MEM_RDONLY)) { 7751 verbose(env, "verifier internal error: misconfigured dynptr helper type flags\n"); 7752 return -EFAULT; 7753 } 7754 7755 /* MEM_UNINIT - Points to memory that is an appropriate candidate for 7756 * constructing a mutable bpf_dynptr object. 7757 * 7758 * Currently, this is only possible with PTR_TO_STACK 7759 * pointing to a region of at least 16 bytes which doesn't 7760 * contain an existing bpf_dynptr. 7761 * 7762 * MEM_RDONLY - Points to a initialized bpf_dynptr that will not be 7763 * mutated or destroyed. However, the memory it points to 7764 * may be mutated. 7765 * 7766 * None - Points to a initialized dynptr that can be mutated and 7767 * destroyed, including mutation of the memory it points 7768 * to. 7769 */ 7770 if (arg_type & MEM_UNINIT) { 7771 int i; 7772 7773 if (!is_dynptr_reg_valid_uninit(env, reg)) { 7774 verbose(env, "Dynptr has to be an uninitialized dynptr\n"); 7775 return -EINVAL; 7776 } 7777 7778 /* we write BPF_DW bits (8 bytes) at a time */ 7779 for (i = 0; i < BPF_DYNPTR_SIZE; i += 8) { 7780 err = check_mem_access(env, insn_idx, regno, 7781 i, BPF_DW, BPF_WRITE, -1, false, false); 7782 if (err) 7783 return err; 7784 } 7785 7786 err = mark_stack_slots_dynptr(env, reg, arg_type, insn_idx, clone_ref_obj_id); 7787 } else /* MEM_RDONLY and None case from above */ { 7788 /* For the reg->type == PTR_TO_STACK case, bpf_dynptr is never const */ 7789 if (reg->type == CONST_PTR_TO_DYNPTR && !(arg_type & MEM_RDONLY)) { 7790 verbose(env, "cannot pass pointer to const bpf_dynptr, the helper mutates it\n"); 7791 return -EINVAL; 7792 } 7793 7794 if (!is_dynptr_reg_valid_init(env, reg)) { 7795 verbose(env, 7796 "Expected an initialized dynptr as arg #%d\n", 7797 regno); 7798 return -EINVAL; 7799 } 7800 7801 /* Fold modifiers (in this case, MEM_RDONLY) when checking expected type */ 7802 if (!is_dynptr_type_expected(env, reg, arg_type & ~MEM_RDONLY)) { 7803 verbose(env, 7804 "Expected a dynptr of type %s as arg #%d\n", 7805 dynptr_type_str(arg_to_dynptr_type(arg_type)), regno); 7806 return -EINVAL; 7807 } 7808 7809 err = mark_dynptr_read(env, reg); 7810 } 7811 return err; 7812 } 7813 7814 static u32 iter_ref_obj_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg, int spi) 7815 { 7816 struct bpf_func_state *state = func(env, reg); 7817 7818 return state->stack[spi].spilled_ptr.ref_obj_id; 7819 } 7820 7821 static bool is_iter_kfunc(struct bpf_kfunc_call_arg_meta *meta) 7822 { 7823 return meta->kfunc_flags & (KF_ITER_NEW | KF_ITER_NEXT | KF_ITER_DESTROY); 7824 } 7825 7826 static bool is_iter_new_kfunc(struct bpf_kfunc_call_arg_meta *meta) 7827 { 7828 return meta->kfunc_flags & KF_ITER_NEW; 7829 } 7830 7831 static bool is_iter_next_kfunc(struct bpf_kfunc_call_arg_meta *meta) 7832 { 7833 return meta->kfunc_flags & KF_ITER_NEXT; 7834 } 7835 7836 static bool is_iter_destroy_kfunc(struct bpf_kfunc_call_arg_meta *meta) 7837 { 7838 return meta->kfunc_flags & KF_ITER_DESTROY; 7839 } 7840 7841 static bool is_kfunc_arg_iter(struct bpf_kfunc_call_arg_meta *meta, int arg) 7842 { 7843 /* btf_check_iter_kfuncs() guarantees that first argument of any iter 7844 * kfunc is iter state pointer 7845 */ 7846 return arg == 0 && is_iter_kfunc(meta); 7847 } 7848 7849 static int process_iter_arg(struct bpf_verifier_env *env, int regno, int insn_idx, 7850 struct bpf_kfunc_call_arg_meta *meta) 7851 { 7852 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno]; 7853 const struct btf_type *t; 7854 const struct btf_param *arg; 7855 int spi, err, i, nr_slots; 7856 u32 btf_id; 7857 7858 /* btf_check_iter_kfuncs() ensures we don't need to validate anything here */ 7859 arg = &btf_params(meta->func_proto)[0]; 7860 t = btf_type_skip_modifiers(meta->btf, arg->type, NULL); /* PTR */ 7861 t = btf_type_skip_modifiers(meta->btf, t->type, &btf_id); /* STRUCT */ 7862 nr_slots = t->size / BPF_REG_SIZE; 7863 7864 if (is_iter_new_kfunc(meta)) { 7865 /* bpf_iter_<type>_new() expects pointer to uninit iter state */ 7866 if (!is_iter_reg_valid_uninit(env, reg, nr_slots)) { 7867 verbose(env, "expected uninitialized iter_%s as arg #%d\n", 7868 iter_type_str(meta->btf, btf_id), regno); 7869 return -EINVAL; 7870 } 7871 7872 for (i = 0; i < nr_slots * 8; i += BPF_REG_SIZE) { 7873 err = check_mem_access(env, insn_idx, regno, 7874 i, BPF_DW, BPF_WRITE, -1, false, false); 7875 if (err) 7876 return err; 7877 } 7878 7879 err = mark_stack_slots_iter(env, meta, reg, insn_idx, meta->btf, btf_id, nr_slots); 7880 if (err) 7881 return err; 7882 } else { 7883 /* iter_next() or iter_destroy() expect initialized iter state*/ 7884 err = is_iter_reg_valid_init(env, reg, meta->btf, btf_id, nr_slots); 7885 switch (err) { 7886 case 0: 7887 break; 7888 case -EINVAL: 7889 verbose(env, "expected an initialized iter_%s as arg #%d\n", 7890 iter_type_str(meta->btf, btf_id), regno); 7891 return err; 7892 case -EPROTO: 7893 verbose(env, "expected an RCU CS when using %s\n", meta->func_name); 7894 return err; 7895 default: 7896 return err; 7897 } 7898 7899 spi = iter_get_spi(env, reg, nr_slots); 7900 if (spi < 0) 7901 return spi; 7902 7903 err = mark_iter_read(env, reg, spi, nr_slots); 7904 if (err) 7905 return err; 7906 7907 /* remember meta->iter info for process_iter_next_call() */ 7908 meta->iter.spi = spi; 7909 meta->iter.frameno = reg->frameno; 7910 meta->ref_obj_id = iter_ref_obj_id(env, reg, spi); 7911 7912 if (is_iter_destroy_kfunc(meta)) { 7913 err = unmark_stack_slots_iter(env, reg, nr_slots); 7914 if (err) 7915 return err; 7916 } 7917 } 7918 7919 return 0; 7920 } 7921 7922 /* Look for a previous loop entry at insn_idx: nearest parent state 7923 * stopped at insn_idx with callsites matching those in cur->frame. 7924 */ 7925 static struct bpf_verifier_state *find_prev_entry(struct bpf_verifier_env *env, 7926 struct bpf_verifier_state *cur, 7927 int insn_idx) 7928 { 7929 struct bpf_verifier_state_list *sl; 7930 struct bpf_verifier_state *st; 7931 7932 /* Explored states are pushed in stack order, most recent states come first */ 7933 sl = *explored_state(env, insn_idx); 7934 for (; sl; sl = sl->next) { 7935 /* If st->branches != 0 state is a part of current DFS verification path, 7936 * hence cur & st for a loop. 7937 */ 7938 st = &sl->state; 7939 if (st->insn_idx == insn_idx && st->branches && same_callsites(st, cur) && 7940 st->dfs_depth < cur->dfs_depth) 7941 return st; 7942 } 7943 7944 return NULL; 7945 } 7946 7947 static void reset_idmap_scratch(struct bpf_verifier_env *env); 7948 static bool regs_exact(const struct bpf_reg_state *rold, 7949 const struct bpf_reg_state *rcur, 7950 struct bpf_idmap *idmap); 7951 7952 static void maybe_widen_reg(struct bpf_verifier_env *env, 7953 struct bpf_reg_state *rold, struct bpf_reg_state *rcur, 7954 struct bpf_idmap *idmap) 7955 { 7956 if (rold->type != SCALAR_VALUE) 7957 return; 7958 if (rold->type != rcur->type) 7959 return; 7960 if (rold->precise || rcur->precise || regs_exact(rold, rcur, idmap)) 7961 return; 7962 __mark_reg_unknown(env, rcur); 7963 } 7964 7965 static int widen_imprecise_scalars(struct bpf_verifier_env *env, 7966 struct bpf_verifier_state *old, 7967 struct bpf_verifier_state *cur) 7968 { 7969 struct bpf_func_state *fold, *fcur; 7970 int i, fr; 7971 7972 reset_idmap_scratch(env); 7973 for (fr = old->curframe; fr >= 0; fr--) { 7974 fold = old->frame[fr]; 7975 fcur = cur->frame[fr]; 7976 7977 for (i = 0; i < MAX_BPF_REG; i++) 7978 maybe_widen_reg(env, 7979 &fold->regs[i], 7980 &fcur->regs[i], 7981 &env->idmap_scratch); 7982 7983 for (i = 0; i < fold->allocated_stack / BPF_REG_SIZE; i++) { 7984 if (!is_spilled_reg(&fold->stack[i]) || 7985 !is_spilled_reg(&fcur->stack[i])) 7986 continue; 7987 7988 maybe_widen_reg(env, 7989 &fold->stack[i].spilled_ptr, 7990 &fcur->stack[i].spilled_ptr, 7991 &env->idmap_scratch); 7992 } 7993 } 7994 return 0; 7995 } 7996 7997 /* process_iter_next_call() is called when verifier gets to iterator's next 7998 * "method" (e.g., bpf_iter_num_next() for numbers iterator) call. We'll refer 7999 * to it as just "iter_next()" in comments below. 8000 * 8001 * BPF verifier relies on a crucial contract for any iter_next() 8002 * implementation: it should *eventually* return NULL, and once that happens 8003 * it should keep returning NULL. That is, once iterator exhausts elements to 8004 * iterate, it should never reset or spuriously return new elements. 8005 * 8006 * With the assumption of such contract, process_iter_next_call() simulates 8007 * a fork in the verifier state to validate loop logic correctness and safety 8008 * without having to simulate infinite amount of iterations. 8009 * 8010 * In current state, we first assume that iter_next() returned NULL and 8011 * iterator state is set to DRAINED (BPF_ITER_STATE_DRAINED). In such 8012 * conditions we should not form an infinite loop and should eventually reach 8013 * exit. 8014 * 8015 * Besides that, we also fork current state and enqueue it for later 8016 * verification. In a forked state we keep iterator state as ACTIVE 8017 * (BPF_ITER_STATE_ACTIVE) and assume non-NULL return from iter_next(). We 8018 * also bump iteration depth to prevent erroneous infinite loop detection 8019 * later on (see iter_active_depths_differ() comment for details). In this 8020 * state we assume that we'll eventually loop back to another iter_next() 8021 * calls (it could be in exactly same location or in some other instruction, 8022 * it doesn't matter, we don't make any unnecessary assumptions about this, 8023 * everything revolves around iterator state in a stack slot, not which 8024 * instruction is calling iter_next()). When that happens, we either will come 8025 * to iter_next() with equivalent state and can conclude that next iteration 8026 * will proceed in exactly the same way as we just verified, so it's safe to 8027 * assume that loop converges. If not, we'll go on another iteration 8028 * simulation with a different input state, until all possible starting states 8029 * are validated or we reach maximum number of instructions limit. 8030 * 8031 * This way, we will either exhaustively discover all possible input states 8032 * that iterator loop can start with and eventually will converge, or we'll 8033 * effectively regress into bounded loop simulation logic and either reach 8034 * maximum number of instructions if loop is not provably convergent, or there 8035 * is some statically known limit on number of iterations (e.g., if there is 8036 * an explicit `if n > 100 then break;` statement somewhere in the loop). 8037 * 8038 * Iteration convergence logic in is_state_visited() relies on exact 8039 * states comparison, which ignores read and precision marks. 8040 * This is necessary because read and precision marks are not finalized 8041 * while in the loop. Exact comparison might preclude convergence for 8042 * simple programs like below: 8043 * 8044 * i = 0; 8045 * while(iter_next(&it)) 8046 * i++; 8047 * 8048 * At each iteration step i++ would produce a new distinct state and 8049 * eventually instruction processing limit would be reached. 8050 * 8051 * To avoid such behavior speculatively forget (widen) range for 8052 * imprecise scalar registers, if those registers were not precise at the 8053 * end of the previous iteration and do not match exactly. 8054 * 8055 * This is a conservative heuristic that allows to verify wide range of programs, 8056 * however it precludes verification of programs that conjure an 8057 * imprecise value on the first loop iteration and use it as precise on a second. 8058 * For example, the following safe program would fail to verify: 8059 * 8060 * struct bpf_num_iter it; 8061 * int arr[10]; 8062 * int i = 0, a = 0; 8063 * bpf_iter_num_new(&it, 0, 10); 8064 * while (bpf_iter_num_next(&it)) { 8065 * if (a == 0) { 8066 * a = 1; 8067 * i = 7; // Because i changed verifier would forget 8068 * // it's range on second loop entry. 8069 * } else { 8070 * arr[i] = 42; // This would fail to verify. 8071 * } 8072 * } 8073 * bpf_iter_num_destroy(&it); 8074 */ 8075 static int process_iter_next_call(struct bpf_verifier_env *env, int insn_idx, 8076 struct bpf_kfunc_call_arg_meta *meta) 8077 { 8078 struct bpf_verifier_state *cur_st = env->cur_state, *queued_st, *prev_st; 8079 struct bpf_func_state *cur_fr = cur_st->frame[cur_st->curframe], *queued_fr; 8080 struct bpf_reg_state *cur_iter, *queued_iter; 8081 int iter_frameno = meta->iter.frameno; 8082 int iter_spi = meta->iter.spi; 8083 8084 BTF_TYPE_EMIT(struct bpf_iter); 8085 8086 cur_iter = &env->cur_state->frame[iter_frameno]->stack[iter_spi].spilled_ptr; 8087 8088 if (cur_iter->iter.state != BPF_ITER_STATE_ACTIVE && 8089 cur_iter->iter.state != BPF_ITER_STATE_DRAINED) { 8090 verbose(env, "verifier internal error: unexpected iterator state %d (%s)\n", 8091 cur_iter->iter.state, iter_state_str(cur_iter->iter.state)); 8092 return -EFAULT; 8093 } 8094 8095 if (cur_iter->iter.state == BPF_ITER_STATE_ACTIVE) { 8096 /* Because iter_next() call is a checkpoint is_state_visitied() 8097 * should guarantee parent state with same call sites and insn_idx. 8098 */ 8099 if (!cur_st->parent || cur_st->parent->insn_idx != insn_idx || 8100 !same_callsites(cur_st->parent, cur_st)) { 8101 verbose(env, "bug: bad parent state for iter next call"); 8102 return -EFAULT; 8103 } 8104 /* Note cur_st->parent in the call below, it is necessary to skip 8105 * checkpoint created for cur_st by is_state_visited() 8106 * right at this instruction. 8107 */ 8108 prev_st = find_prev_entry(env, cur_st->parent, insn_idx); 8109 /* branch out active iter state */ 8110 queued_st = push_stack(env, insn_idx + 1, insn_idx, false); 8111 if (!queued_st) 8112 return -ENOMEM; 8113 8114 queued_iter = &queued_st->frame[iter_frameno]->stack[iter_spi].spilled_ptr; 8115 queued_iter->iter.state = BPF_ITER_STATE_ACTIVE; 8116 queued_iter->iter.depth++; 8117 if (prev_st) 8118 widen_imprecise_scalars(env, prev_st, queued_st); 8119 8120 queued_fr = queued_st->frame[queued_st->curframe]; 8121 mark_ptr_not_null_reg(&queued_fr->regs[BPF_REG_0]); 8122 } 8123 8124 /* switch to DRAINED state, but keep the depth unchanged */ 8125 /* mark current iter state as drained and assume returned NULL */ 8126 cur_iter->iter.state = BPF_ITER_STATE_DRAINED; 8127 __mark_reg_const_zero(&cur_fr->regs[BPF_REG_0]); 8128 8129 return 0; 8130 } 8131 8132 static bool arg_type_is_mem_size(enum bpf_arg_type type) 8133 { 8134 return type == ARG_CONST_SIZE || 8135 type == ARG_CONST_SIZE_OR_ZERO; 8136 } 8137 8138 static bool arg_type_is_release(enum bpf_arg_type type) 8139 { 8140 return type & OBJ_RELEASE; 8141 } 8142 8143 static bool arg_type_is_dynptr(enum bpf_arg_type type) 8144 { 8145 return base_type(type) == ARG_PTR_TO_DYNPTR; 8146 } 8147 8148 static int int_ptr_type_to_size(enum bpf_arg_type type) 8149 { 8150 if (type == ARG_PTR_TO_INT) 8151 return sizeof(u32); 8152 else if (type == ARG_PTR_TO_LONG) 8153 return sizeof(u64); 8154 8155 return -EINVAL; 8156 } 8157 8158 static int resolve_map_arg_type(struct bpf_verifier_env *env, 8159 const struct bpf_call_arg_meta *meta, 8160 enum bpf_arg_type *arg_type) 8161 { 8162 if (!meta->map_ptr) { 8163 /* kernel subsystem misconfigured verifier */ 8164 verbose(env, "invalid map_ptr to access map->type\n"); 8165 return -EACCES; 8166 } 8167 8168 switch (meta->map_ptr->map_type) { 8169 case BPF_MAP_TYPE_SOCKMAP: 8170 case BPF_MAP_TYPE_SOCKHASH: 8171 if (*arg_type == ARG_PTR_TO_MAP_VALUE) { 8172 *arg_type = ARG_PTR_TO_BTF_ID_SOCK_COMMON; 8173 } else { 8174 verbose(env, "invalid arg_type for sockmap/sockhash\n"); 8175 return -EINVAL; 8176 } 8177 break; 8178 case BPF_MAP_TYPE_BLOOM_FILTER: 8179 if (meta->func_id == BPF_FUNC_map_peek_elem) 8180 *arg_type = ARG_PTR_TO_MAP_VALUE; 8181 break; 8182 default: 8183 break; 8184 } 8185 return 0; 8186 } 8187 8188 struct bpf_reg_types { 8189 const enum bpf_reg_type types[10]; 8190 u32 *btf_id; 8191 }; 8192 8193 static const struct bpf_reg_types sock_types = { 8194 .types = { 8195 PTR_TO_SOCK_COMMON, 8196 PTR_TO_SOCKET, 8197 PTR_TO_TCP_SOCK, 8198 PTR_TO_XDP_SOCK, 8199 }, 8200 }; 8201 8202 #ifdef CONFIG_NET 8203 static const struct bpf_reg_types btf_id_sock_common_types = { 8204 .types = { 8205 PTR_TO_SOCK_COMMON, 8206 PTR_TO_SOCKET, 8207 PTR_TO_TCP_SOCK, 8208 PTR_TO_XDP_SOCK, 8209 PTR_TO_BTF_ID, 8210 PTR_TO_BTF_ID | PTR_TRUSTED, 8211 }, 8212 .btf_id = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON], 8213 }; 8214 #endif 8215 8216 static const struct bpf_reg_types mem_types = { 8217 .types = { 8218 PTR_TO_STACK, 8219 PTR_TO_PACKET, 8220 PTR_TO_PACKET_META, 8221 PTR_TO_MAP_KEY, 8222 PTR_TO_MAP_VALUE, 8223 PTR_TO_MEM, 8224 PTR_TO_MEM | MEM_RINGBUF, 8225 PTR_TO_BUF, 8226 PTR_TO_BTF_ID | PTR_TRUSTED, 8227 }, 8228 }; 8229 8230 static const struct bpf_reg_types int_ptr_types = { 8231 .types = { 8232 PTR_TO_STACK, 8233 PTR_TO_PACKET, 8234 PTR_TO_PACKET_META, 8235 PTR_TO_MAP_KEY, 8236 PTR_TO_MAP_VALUE, 8237 }, 8238 }; 8239 8240 static const struct bpf_reg_types spin_lock_types = { 8241 .types = { 8242 PTR_TO_MAP_VALUE, 8243 PTR_TO_BTF_ID | MEM_ALLOC, 8244 } 8245 }; 8246 8247 static const struct bpf_reg_types fullsock_types = { .types = { PTR_TO_SOCKET } }; 8248 static const struct bpf_reg_types scalar_types = { .types = { SCALAR_VALUE } }; 8249 static const struct bpf_reg_types context_types = { .types = { PTR_TO_CTX } }; 8250 static const struct bpf_reg_types ringbuf_mem_types = { .types = { PTR_TO_MEM | MEM_RINGBUF } }; 8251 static const struct bpf_reg_types const_map_ptr_types = { .types = { CONST_PTR_TO_MAP } }; 8252 static const struct bpf_reg_types btf_ptr_types = { 8253 .types = { 8254 PTR_TO_BTF_ID, 8255 PTR_TO_BTF_ID | PTR_TRUSTED, 8256 PTR_TO_BTF_ID | MEM_RCU, 8257 }, 8258 }; 8259 static const struct bpf_reg_types percpu_btf_ptr_types = { 8260 .types = { 8261 PTR_TO_BTF_ID | MEM_PERCPU, 8262 PTR_TO_BTF_ID | MEM_PERCPU | MEM_RCU, 8263 PTR_TO_BTF_ID | MEM_PERCPU | PTR_TRUSTED, 8264 } 8265 }; 8266 static const struct bpf_reg_types func_ptr_types = { .types = { PTR_TO_FUNC } }; 8267 static const struct bpf_reg_types stack_ptr_types = { .types = { PTR_TO_STACK } }; 8268 static const struct bpf_reg_types const_str_ptr_types = { .types = { PTR_TO_MAP_VALUE } }; 8269 static const struct bpf_reg_types timer_types = { .types = { PTR_TO_MAP_VALUE } }; 8270 static const struct bpf_reg_types kptr_types = { .types = { PTR_TO_MAP_VALUE } }; 8271 static const struct bpf_reg_types dynptr_types = { 8272 .types = { 8273 PTR_TO_STACK, 8274 CONST_PTR_TO_DYNPTR, 8275 } 8276 }; 8277 8278 static const struct bpf_reg_types *compatible_reg_types[__BPF_ARG_TYPE_MAX] = { 8279 [ARG_PTR_TO_MAP_KEY] = &mem_types, 8280 [ARG_PTR_TO_MAP_VALUE] = &mem_types, 8281 [ARG_CONST_SIZE] = &scalar_types, 8282 [ARG_CONST_SIZE_OR_ZERO] = &scalar_types, 8283 [ARG_CONST_ALLOC_SIZE_OR_ZERO] = &scalar_types, 8284 [ARG_CONST_MAP_PTR] = &const_map_ptr_types, 8285 [ARG_PTR_TO_CTX] = &context_types, 8286 [ARG_PTR_TO_SOCK_COMMON] = &sock_types, 8287 #ifdef CONFIG_NET 8288 [ARG_PTR_TO_BTF_ID_SOCK_COMMON] = &btf_id_sock_common_types, 8289 #endif 8290 [ARG_PTR_TO_SOCKET] = &fullsock_types, 8291 [ARG_PTR_TO_BTF_ID] = &btf_ptr_types, 8292 [ARG_PTR_TO_SPIN_LOCK] = &spin_lock_types, 8293 [ARG_PTR_TO_MEM] = &mem_types, 8294 [ARG_PTR_TO_RINGBUF_MEM] = &ringbuf_mem_types, 8295 [ARG_PTR_TO_INT] = &int_ptr_types, 8296 [ARG_PTR_TO_LONG] = &int_ptr_types, 8297 [ARG_PTR_TO_PERCPU_BTF_ID] = &percpu_btf_ptr_types, 8298 [ARG_PTR_TO_FUNC] = &func_ptr_types, 8299 [ARG_PTR_TO_STACK] = &stack_ptr_types, 8300 [ARG_PTR_TO_CONST_STR] = &const_str_ptr_types, 8301 [ARG_PTR_TO_TIMER] = &timer_types, 8302 [ARG_PTR_TO_KPTR] = &kptr_types, 8303 [ARG_PTR_TO_DYNPTR] = &dynptr_types, 8304 }; 8305 8306 static int check_reg_type(struct bpf_verifier_env *env, u32 regno, 8307 enum bpf_arg_type arg_type, 8308 const u32 *arg_btf_id, 8309 struct bpf_call_arg_meta *meta) 8310 { 8311 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno]; 8312 enum bpf_reg_type expected, type = reg->type; 8313 const struct bpf_reg_types *compatible; 8314 int i, j; 8315 8316 compatible = compatible_reg_types[base_type(arg_type)]; 8317 if (!compatible) { 8318 verbose(env, "verifier internal error: unsupported arg type %d\n", arg_type); 8319 return -EFAULT; 8320 } 8321 8322 /* ARG_PTR_TO_MEM + RDONLY is compatible with PTR_TO_MEM and PTR_TO_MEM + RDONLY, 8323 * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM and NOT with PTR_TO_MEM + RDONLY 8324 * 8325 * Same for MAYBE_NULL: 8326 * 8327 * ARG_PTR_TO_MEM + MAYBE_NULL is compatible with PTR_TO_MEM and PTR_TO_MEM + MAYBE_NULL, 8328 * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM but NOT with PTR_TO_MEM + MAYBE_NULL 8329 * 8330 * ARG_PTR_TO_MEM is compatible with PTR_TO_MEM that is tagged with a dynptr type. 8331 * 8332 * Therefore we fold these flags depending on the arg_type before comparison. 8333 */ 8334 if (arg_type & MEM_RDONLY) 8335 type &= ~MEM_RDONLY; 8336 if (arg_type & PTR_MAYBE_NULL) 8337 type &= ~PTR_MAYBE_NULL; 8338 if (base_type(arg_type) == ARG_PTR_TO_MEM) 8339 type &= ~DYNPTR_TYPE_FLAG_MASK; 8340 8341 if (meta->func_id == BPF_FUNC_kptr_xchg && type_is_alloc(type)) { 8342 type &= ~MEM_ALLOC; 8343 type &= ~MEM_PERCPU; 8344 } 8345 8346 for (i = 0; i < ARRAY_SIZE(compatible->types); i++) { 8347 expected = compatible->types[i]; 8348 if (expected == NOT_INIT) 8349 break; 8350 8351 if (type == expected) 8352 goto found; 8353 } 8354 8355 verbose(env, "R%d type=%s expected=", regno, reg_type_str(env, reg->type)); 8356 for (j = 0; j + 1 < i; j++) 8357 verbose(env, "%s, ", reg_type_str(env, compatible->types[j])); 8358 verbose(env, "%s\n", reg_type_str(env, compatible->types[j])); 8359 return -EACCES; 8360 8361 found: 8362 if (base_type(reg->type) != PTR_TO_BTF_ID) 8363 return 0; 8364 8365 if (compatible == &mem_types) { 8366 if (!(arg_type & MEM_RDONLY)) { 8367 verbose(env, 8368 "%s() may write into memory pointed by R%d type=%s\n", 8369 func_id_name(meta->func_id), 8370 regno, reg_type_str(env, reg->type)); 8371 return -EACCES; 8372 } 8373 return 0; 8374 } 8375 8376 switch ((int)reg->type) { 8377 case PTR_TO_BTF_ID: 8378 case PTR_TO_BTF_ID | PTR_TRUSTED: 8379 case PTR_TO_BTF_ID | MEM_RCU: 8380 case PTR_TO_BTF_ID | PTR_MAYBE_NULL: 8381 case PTR_TO_BTF_ID | PTR_MAYBE_NULL | MEM_RCU: 8382 { 8383 /* For bpf_sk_release, it needs to match against first member 8384 * 'struct sock_common', hence make an exception for it. This 8385 * allows bpf_sk_release to work for multiple socket types. 8386 */ 8387 bool strict_type_match = arg_type_is_release(arg_type) && 8388 meta->func_id != BPF_FUNC_sk_release; 8389 8390 if (type_may_be_null(reg->type) && 8391 (!type_may_be_null(arg_type) || arg_type_is_release(arg_type))) { 8392 verbose(env, "Possibly NULL pointer passed to helper arg%d\n", regno); 8393 return -EACCES; 8394 } 8395 8396 if (!arg_btf_id) { 8397 if (!compatible->btf_id) { 8398 verbose(env, "verifier internal error: missing arg compatible BTF ID\n"); 8399 return -EFAULT; 8400 } 8401 arg_btf_id = compatible->btf_id; 8402 } 8403 8404 if (meta->func_id == BPF_FUNC_kptr_xchg) { 8405 if (map_kptr_match_type(env, meta->kptr_field, reg, regno)) 8406 return -EACCES; 8407 } else { 8408 if (arg_btf_id == BPF_PTR_POISON) { 8409 verbose(env, "verifier internal error:"); 8410 verbose(env, "R%d has non-overwritten BPF_PTR_POISON type\n", 8411 regno); 8412 return -EACCES; 8413 } 8414 8415 if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off, 8416 btf_vmlinux, *arg_btf_id, 8417 strict_type_match)) { 8418 verbose(env, "R%d is of type %s but %s is expected\n", 8419 regno, btf_type_name(reg->btf, reg->btf_id), 8420 btf_type_name(btf_vmlinux, *arg_btf_id)); 8421 return -EACCES; 8422 } 8423 } 8424 break; 8425 } 8426 case PTR_TO_BTF_ID | MEM_ALLOC: 8427 case PTR_TO_BTF_ID | MEM_PERCPU | MEM_ALLOC: 8428 if (meta->func_id != BPF_FUNC_spin_lock && meta->func_id != BPF_FUNC_spin_unlock && 8429 meta->func_id != BPF_FUNC_kptr_xchg) { 8430 verbose(env, "verifier internal error: unimplemented handling of MEM_ALLOC\n"); 8431 return -EFAULT; 8432 } 8433 if (meta->func_id == BPF_FUNC_kptr_xchg) { 8434 if (map_kptr_match_type(env, meta->kptr_field, reg, regno)) 8435 return -EACCES; 8436 } 8437 break; 8438 case PTR_TO_BTF_ID | MEM_PERCPU: 8439 case PTR_TO_BTF_ID | MEM_PERCPU | MEM_RCU: 8440 case PTR_TO_BTF_ID | MEM_PERCPU | PTR_TRUSTED: 8441 /* Handled by helper specific checks */ 8442 break; 8443 default: 8444 verbose(env, "verifier internal error: invalid PTR_TO_BTF_ID register for type match\n"); 8445 return -EFAULT; 8446 } 8447 return 0; 8448 } 8449 8450 static struct btf_field * 8451 reg_find_field_offset(const struct bpf_reg_state *reg, s32 off, u32 fields) 8452 { 8453 struct btf_field *field; 8454 struct btf_record *rec; 8455 8456 rec = reg_btf_record(reg); 8457 if (!rec) 8458 return NULL; 8459 8460 field = btf_record_find(rec, off, fields); 8461 if (!field) 8462 return NULL; 8463 8464 return field; 8465 } 8466 8467 int check_func_arg_reg_off(struct bpf_verifier_env *env, 8468 const struct bpf_reg_state *reg, int regno, 8469 enum bpf_arg_type arg_type) 8470 { 8471 u32 type = reg->type; 8472 8473 /* When referenced register is passed to release function, its fixed 8474 * offset must be 0. 8475 * 8476 * We will check arg_type_is_release reg has ref_obj_id when storing 8477 * meta->release_regno. 8478 */ 8479 if (arg_type_is_release(arg_type)) { 8480 /* ARG_PTR_TO_DYNPTR with OBJ_RELEASE is a bit special, as it 8481 * may not directly point to the object being released, but to 8482 * dynptr pointing to such object, which might be at some offset 8483 * on the stack. In that case, we simply to fallback to the 8484 * default handling. 8485 */ 8486 if (arg_type_is_dynptr(arg_type) && type == PTR_TO_STACK) 8487 return 0; 8488 8489 /* Doing check_ptr_off_reg check for the offset will catch this 8490 * because fixed_off_ok is false, but checking here allows us 8491 * to give the user a better error message. 8492 */ 8493 if (reg->off) { 8494 verbose(env, "R%d must have zero offset when passed to release func or trusted arg to kfunc\n", 8495 regno); 8496 return -EINVAL; 8497 } 8498 return __check_ptr_off_reg(env, reg, regno, false); 8499 } 8500 8501 switch (type) { 8502 /* Pointer types where both fixed and variable offset is explicitly allowed: */ 8503 case PTR_TO_STACK: 8504 case PTR_TO_PACKET: 8505 case PTR_TO_PACKET_META: 8506 case PTR_TO_MAP_KEY: 8507 case PTR_TO_MAP_VALUE: 8508 case PTR_TO_MEM: 8509 case PTR_TO_MEM | MEM_RDONLY: 8510 case PTR_TO_MEM | MEM_RINGBUF: 8511 case PTR_TO_BUF: 8512 case PTR_TO_BUF | MEM_RDONLY: 8513 case SCALAR_VALUE: 8514 return 0; 8515 /* All the rest must be rejected, except PTR_TO_BTF_ID which allows 8516 * fixed offset. 8517 */ 8518 case PTR_TO_BTF_ID: 8519 case PTR_TO_BTF_ID | MEM_ALLOC: 8520 case PTR_TO_BTF_ID | PTR_TRUSTED: 8521 case PTR_TO_BTF_ID | MEM_RCU: 8522 case PTR_TO_BTF_ID | MEM_ALLOC | NON_OWN_REF: 8523 case PTR_TO_BTF_ID | MEM_ALLOC | NON_OWN_REF | MEM_RCU: 8524 /* When referenced PTR_TO_BTF_ID is passed to release function, 8525 * its fixed offset must be 0. In the other cases, fixed offset 8526 * can be non-zero. This was already checked above. So pass 8527 * fixed_off_ok as true to allow fixed offset for all other 8528 * cases. var_off always must be 0 for PTR_TO_BTF_ID, hence we 8529 * still need to do checks instead of returning. 8530 */ 8531 return __check_ptr_off_reg(env, reg, regno, true); 8532 default: 8533 return __check_ptr_off_reg(env, reg, regno, false); 8534 } 8535 } 8536 8537 static struct bpf_reg_state *get_dynptr_arg_reg(struct bpf_verifier_env *env, 8538 const struct bpf_func_proto *fn, 8539 struct bpf_reg_state *regs) 8540 { 8541 struct bpf_reg_state *state = NULL; 8542 int i; 8543 8544 for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++) 8545 if (arg_type_is_dynptr(fn->arg_type[i])) { 8546 if (state) { 8547 verbose(env, "verifier internal error: multiple dynptr args\n"); 8548 return NULL; 8549 } 8550 state = ®s[BPF_REG_1 + i]; 8551 } 8552 8553 if (!state) 8554 verbose(env, "verifier internal error: no dynptr arg found\n"); 8555 8556 return state; 8557 } 8558 8559 static int dynptr_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 8560 { 8561 struct bpf_func_state *state = func(env, reg); 8562 int spi; 8563 8564 if (reg->type == CONST_PTR_TO_DYNPTR) 8565 return reg->id; 8566 spi = dynptr_get_spi(env, reg); 8567 if (spi < 0) 8568 return spi; 8569 return state->stack[spi].spilled_ptr.id; 8570 } 8571 8572 static int dynptr_ref_obj_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 8573 { 8574 struct bpf_func_state *state = func(env, reg); 8575 int spi; 8576 8577 if (reg->type == CONST_PTR_TO_DYNPTR) 8578 return reg->ref_obj_id; 8579 spi = dynptr_get_spi(env, reg); 8580 if (spi < 0) 8581 return spi; 8582 return state->stack[spi].spilled_ptr.ref_obj_id; 8583 } 8584 8585 static enum bpf_dynptr_type dynptr_get_type(struct bpf_verifier_env *env, 8586 struct bpf_reg_state *reg) 8587 { 8588 struct bpf_func_state *state = func(env, reg); 8589 int spi; 8590 8591 if (reg->type == CONST_PTR_TO_DYNPTR) 8592 return reg->dynptr.type; 8593 8594 spi = __get_spi(reg->off); 8595 if (spi < 0) { 8596 verbose(env, "verifier internal error: invalid spi when querying dynptr type\n"); 8597 return BPF_DYNPTR_TYPE_INVALID; 8598 } 8599 8600 return state->stack[spi].spilled_ptr.dynptr.type; 8601 } 8602 8603 static int check_func_arg(struct bpf_verifier_env *env, u32 arg, 8604 struct bpf_call_arg_meta *meta, 8605 const struct bpf_func_proto *fn, 8606 int insn_idx) 8607 { 8608 u32 regno = BPF_REG_1 + arg; 8609 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno]; 8610 enum bpf_arg_type arg_type = fn->arg_type[arg]; 8611 enum bpf_reg_type type = reg->type; 8612 u32 *arg_btf_id = NULL; 8613 int err = 0; 8614 8615 if (arg_type == ARG_DONTCARE) 8616 return 0; 8617 8618 err = check_reg_arg(env, regno, SRC_OP); 8619 if (err) 8620 return err; 8621 8622 if (arg_type == ARG_ANYTHING) { 8623 if (is_pointer_value(env, regno)) { 8624 verbose(env, "R%d leaks addr into helper function\n", 8625 regno); 8626 return -EACCES; 8627 } 8628 return 0; 8629 } 8630 8631 if (type_is_pkt_pointer(type) && 8632 !may_access_direct_pkt_data(env, meta, BPF_READ)) { 8633 verbose(env, "helper access to the packet is not allowed\n"); 8634 return -EACCES; 8635 } 8636 8637 if (base_type(arg_type) == ARG_PTR_TO_MAP_VALUE) { 8638 err = resolve_map_arg_type(env, meta, &arg_type); 8639 if (err) 8640 return err; 8641 } 8642 8643 if (register_is_null(reg) && type_may_be_null(arg_type)) 8644 /* A NULL register has a SCALAR_VALUE type, so skip 8645 * type checking. 8646 */ 8647 goto skip_type_check; 8648 8649 /* arg_btf_id and arg_size are in a union. */ 8650 if (base_type(arg_type) == ARG_PTR_TO_BTF_ID || 8651 base_type(arg_type) == ARG_PTR_TO_SPIN_LOCK) 8652 arg_btf_id = fn->arg_btf_id[arg]; 8653 8654 err = check_reg_type(env, regno, arg_type, arg_btf_id, meta); 8655 if (err) 8656 return err; 8657 8658 err = check_func_arg_reg_off(env, reg, regno, arg_type); 8659 if (err) 8660 return err; 8661 8662 skip_type_check: 8663 if (arg_type_is_release(arg_type)) { 8664 if (arg_type_is_dynptr(arg_type)) { 8665 struct bpf_func_state *state = func(env, reg); 8666 int spi; 8667 8668 /* Only dynptr created on stack can be released, thus 8669 * the get_spi and stack state checks for spilled_ptr 8670 * should only be done before process_dynptr_func for 8671 * PTR_TO_STACK. 8672 */ 8673 if (reg->type == PTR_TO_STACK) { 8674 spi = dynptr_get_spi(env, reg); 8675 if (spi < 0 || !state->stack[spi].spilled_ptr.ref_obj_id) { 8676 verbose(env, "arg %d is an unacquired reference\n", regno); 8677 return -EINVAL; 8678 } 8679 } else { 8680 verbose(env, "cannot release unowned const bpf_dynptr\n"); 8681 return -EINVAL; 8682 } 8683 } else if (!reg->ref_obj_id && !register_is_null(reg)) { 8684 verbose(env, "R%d must be referenced when passed to release function\n", 8685 regno); 8686 return -EINVAL; 8687 } 8688 if (meta->release_regno) { 8689 verbose(env, "verifier internal error: more than one release argument\n"); 8690 return -EFAULT; 8691 } 8692 meta->release_regno = regno; 8693 } 8694 8695 if (reg->ref_obj_id) { 8696 if (meta->ref_obj_id) { 8697 verbose(env, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n", 8698 regno, reg->ref_obj_id, 8699 meta->ref_obj_id); 8700 return -EFAULT; 8701 } 8702 meta->ref_obj_id = reg->ref_obj_id; 8703 } 8704 8705 switch (base_type(arg_type)) { 8706 case ARG_CONST_MAP_PTR: 8707 /* bpf_map_xxx(map_ptr) call: remember that map_ptr */ 8708 if (meta->map_ptr) { 8709 /* Use map_uid (which is unique id of inner map) to reject: 8710 * inner_map1 = bpf_map_lookup_elem(outer_map, key1) 8711 * inner_map2 = bpf_map_lookup_elem(outer_map, key2) 8712 * if (inner_map1 && inner_map2) { 8713 * timer = bpf_map_lookup_elem(inner_map1); 8714 * if (timer) 8715 * // mismatch would have been allowed 8716 * bpf_timer_init(timer, inner_map2); 8717 * } 8718 * 8719 * Comparing map_ptr is enough to distinguish normal and outer maps. 8720 */ 8721 if (meta->map_ptr != reg->map_ptr || 8722 meta->map_uid != reg->map_uid) { 8723 verbose(env, 8724 "timer pointer in R1 map_uid=%d doesn't match map pointer in R2 map_uid=%d\n", 8725 meta->map_uid, reg->map_uid); 8726 return -EINVAL; 8727 } 8728 } 8729 meta->map_ptr = reg->map_ptr; 8730 meta->map_uid = reg->map_uid; 8731 break; 8732 case ARG_PTR_TO_MAP_KEY: 8733 /* bpf_map_xxx(..., map_ptr, ..., key) call: 8734 * check that [key, key + map->key_size) are within 8735 * stack limits and initialized 8736 */ 8737 if (!meta->map_ptr) { 8738 /* in function declaration map_ptr must come before 8739 * map_key, so that it's verified and known before 8740 * we have to check map_key here. Otherwise it means 8741 * that kernel subsystem misconfigured verifier 8742 */ 8743 verbose(env, "invalid map_ptr to access map->key\n"); 8744 return -EACCES; 8745 } 8746 err = check_helper_mem_access(env, regno, 8747 meta->map_ptr->key_size, false, 8748 NULL); 8749 break; 8750 case ARG_PTR_TO_MAP_VALUE: 8751 if (type_may_be_null(arg_type) && register_is_null(reg)) 8752 return 0; 8753 8754 /* bpf_map_xxx(..., map_ptr, ..., value) call: 8755 * check [value, value + map->value_size) validity 8756 */ 8757 if (!meta->map_ptr) { 8758 /* kernel subsystem misconfigured verifier */ 8759 verbose(env, "invalid map_ptr to access map->value\n"); 8760 return -EACCES; 8761 } 8762 meta->raw_mode = arg_type & MEM_UNINIT; 8763 err = check_helper_mem_access(env, regno, 8764 meta->map_ptr->value_size, false, 8765 meta); 8766 break; 8767 case ARG_PTR_TO_PERCPU_BTF_ID: 8768 if (!reg->btf_id) { 8769 verbose(env, "Helper has invalid btf_id in R%d\n", regno); 8770 return -EACCES; 8771 } 8772 meta->ret_btf = reg->btf; 8773 meta->ret_btf_id = reg->btf_id; 8774 break; 8775 case ARG_PTR_TO_SPIN_LOCK: 8776 if (in_rbtree_lock_required_cb(env)) { 8777 verbose(env, "can't spin_{lock,unlock} in rbtree cb\n"); 8778 return -EACCES; 8779 } 8780 if (meta->func_id == BPF_FUNC_spin_lock) { 8781 err = process_spin_lock(env, regno, true); 8782 if (err) 8783 return err; 8784 } else if (meta->func_id == BPF_FUNC_spin_unlock) { 8785 err = process_spin_lock(env, regno, false); 8786 if (err) 8787 return err; 8788 } else { 8789 verbose(env, "verifier internal error\n"); 8790 return -EFAULT; 8791 } 8792 break; 8793 case ARG_PTR_TO_TIMER: 8794 err = process_timer_func(env, regno, meta); 8795 if (err) 8796 return err; 8797 break; 8798 case ARG_PTR_TO_FUNC: 8799 meta->subprogno = reg->subprogno; 8800 break; 8801 case ARG_PTR_TO_MEM: 8802 /* The access to this pointer is only checked when we hit the 8803 * next is_mem_size argument below. 8804 */ 8805 meta->raw_mode = arg_type & MEM_UNINIT; 8806 if (arg_type & MEM_FIXED_SIZE) { 8807 err = check_helper_mem_access(env, regno, 8808 fn->arg_size[arg], false, 8809 meta); 8810 } 8811 break; 8812 case ARG_CONST_SIZE: 8813 err = check_mem_size_reg(env, reg, regno, false, meta); 8814 break; 8815 case ARG_CONST_SIZE_OR_ZERO: 8816 err = check_mem_size_reg(env, reg, regno, true, meta); 8817 break; 8818 case ARG_PTR_TO_DYNPTR: 8819 err = process_dynptr_func(env, regno, insn_idx, arg_type, 0); 8820 if (err) 8821 return err; 8822 break; 8823 case ARG_CONST_ALLOC_SIZE_OR_ZERO: 8824 if (!tnum_is_const(reg->var_off)) { 8825 verbose(env, "R%d is not a known constant'\n", 8826 regno); 8827 return -EACCES; 8828 } 8829 meta->mem_size = reg->var_off.value; 8830 err = mark_chain_precision(env, regno); 8831 if (err) 8832 return err; 8833 break; 8834 case ARG_PTR_TO_INT: 8835 case ARG_PTR_TO_LONG: 8836 { 8837 int size = int_ptr_type_to_size(arg_type); 8838 8839 err = check_helper_mem_access(env, regno, size, false, meta); 8840 if (err) 8841 return err; 8842 err = check_ptr_alignment(env, reg, 0, size, true); 8843 break; 8844 } 8845 case ARG_PTR_TO_CONST_STR: 8846 { 8847 struct bpf_map *map = reg->map_ptr; 8848 int map_off; 8849 u64 map_addr; 8850 char *str_ptr; 8851 8852 if (!bpf_map_is_rdonly(map)) { 8853 verbose(env, "R%d does not point to a readonly map'\n", regno); 8854 return -EACCES; 8855 } 8856 8857 if (!tnum_is_const(reg->var_off)) { 8858 verbose(env, "R%d is not a constant address'\n", regno); 8859 return -EACCES; 8860 } 8861 8862 if (!map->ops->map_direct_value_addr) { 8863 verbose(env, "no direct value access support for this map type\n"); 8864 return -EACCES; 8865 } 8866 8867 err = check_map_access(env, regno, reg->off, 8868 map->value_size - reg->off, false, 8869 ACCESS_HELPER); 8870 if (err) 8871 return err; 8872 8873 map_off = reg->off + reg->var_off.value; 8874 err = map->ops->map_direct_value_addr(map, &map_addr, map_off); 8875 if (err) { 8876 verbose(env, "direct value access on string failed\n"); 8877 return err; 8878 } 8879 8880 str_ptr = (char *)(long)(map_addr); 8881 if (!strnchr(str_ptr + map_off, map->value_size - map_off, 0)) { 8882 verbose(env, "string is not zero-terminated\n"); 8883 return -EINVAL; 8884 } 8885 break; 8886 } 8887 case ARG_PTR_TO_KPTR: 8888 err = process_kptr_func(env, regno, meta); 8889 if (err) 8890 return err; 8891 break; 8892 } 8893 8894 return err; 8895 } 8896 8897 static bool may_update_sockmap(struct bpf_verifier_env *env, int func_id) 8898 { 8899 enum bpf_attach_type eatype = env->prog->expected_attach_type; 8900 enum bpf_prog_type type = resolve_prog_type(env->prog); 8901 8902 if (func_id != BPF_FUNC_map_update_elem) 8903 return false; 8904 8905 /* It's not possible to get access to a locked struct sock in these 8906 * contexts, so updating is safe. 8907 */ 8908 switch (type) { 8909 case BPF_PROG_TYPE_TRACING: 8910 if (eatype == BPF_TRACE_ITER) 8911 return true; 8912 break; 8913 case BPF_PROG_TYPE_SOCKET_FILTER: 8914 case BPF_PROG_TYPE_SCHED_CLS: 8915 case BPF_PROG_TYPE_SCHED_ACT: 8916 case BPF_PROG_TYPE_XDP: 8917 case BPF_PROG_TYPE_SK_REUSEPORT: 8918 case BPF_PROG_TYPE_FLOW_DISSECTOR: 8919 case BPF_PROG_TYPE_SK_LOOKUP: 8920 return true; 8921 default: 8922 break; 8923 } 8924 8925 verbose(env, "cannot update sockmap in this context\n"); 8926 return false; 8927 } 8928 8929 static bool allow_tail_call_in_subprogs(struct bpf_verifier_env *env) 8930 { 8931 return env->prog->jit_requested && 8932 bpf_jit_supports_subprog_tailcalls(); 8933 } 8934 8935 static int check_map_func_compatibility(struct bpf_verifier_env *env, 8936 struct bpf_map *map, int func_id) 8937 { 8938 if (!map) 8939 return 0; 8940 8941 /* We need a two way check, first is from map perspective ... */ 8942 switch (map->map_type) { 8943 case BPF_MAP_TYPE_PROG_ARRAY: 8944 if (func_id != BPF_FUNC_tail_call) 8945 goto error; 8946 break; 8947 case BPF_MAP_TYPE_PERF_EVENT_ARRAY: 8948 if (func_id != BPF_FUNC_perf_event_read && 8949 func_id != BPF_FUNC_perf_event_output && 8950 func_id != BPF_FUNC_skb_output && 8951 func_id != BPF_FUNC_perf_event_read_value && 8952 func_id != BPF_FUNC_xdp_output) 8953 goto error; 8954 break; 8955 case BPF_MAP_TYPE_RINGBUF: 8956 if (func_id != BPF_FUNC_ringbuf_output && 8957 func_id != BPF_FUNC_ringbuf_reserve && 8958 func_id != BPF_FUNC_ringbuf_query && 8959 func_id != BPF_FUNC_ringbuf_reserve_dynptr && 8960 func_id != BPF_FUNC_ringbuf_submit_dynptr && 8961 func_id != BPF_FUNC_ringbuf_discard_dynptr) 8962 goto error; 8963 break; 8964 case BPF_MAP_TYPE_USER_RINGBUF: 8965 if (func_id != BPF_FUNC_user_ringbuf_drain) 8966 goto error; 8967 break; 8968 case BPF_MAP_TYPE_STACK_TRACE: 8969 if (func_id != BPF_FUNC_get_stackid) 8970 goto error; 8971 break; 8972 case BPF_MAP_TYPE_CGROUP_ARRAY: 8973 if (func_id != BPF_FUNC_skb_under_cgroup && 8974 func_id != BPF_FUNC_current_task_under_cgroup) 8975 goto error; 8976 break; 8977 case BPF_MAP_TYPE_CGROUP_STORAGE: 8978 case BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE: 8979 if (func_id != BPF_FUNC_get_local_storage) 8980 goto error; 8981 break; 8982 case BPF_MAP_TYPE_DEVMAP: 8983 case BPF_MAP_TYPE_DEVMAP_HASH: 8984 if (func_id != BPF_FUNC_redirect_map && 8985 func_id != BPF_FUNC_map_lookup_elem) 8986 goto error; 8987 break; 8988 /* Restrict bpf side of cpumap and xskmap, open when use-cases 8989 * appear. 8990 */ 8991 case BPF_MAP_TYPE_CPUMAP: 8992 if (func_id != BPF_FUNC_redirect_map) 8993 goto error; 8994 break; 8995 case BPF_MAP_TYPE_XSKMAP: 8996 if (func_id != BPF_FUNC_redirect_map && 8997 func_id != BPF_FUNC_map_lookup_elem) 8998 goto error; 8999 break; 9000 case BPF_MAP_TYPE_ARRAY_OF_MAPS: 9001 case BPF_MAP_TYPE_HASH_OF_MAPS: 9002 if (func_id != BPF_FUNC_map_lookup_elem) 9003 goto error; 9004 break; 9005 case BPF_MAP_TYPE_SOCKMAP: 9006 if (func_id != BPF_FUNC_sk_redirect_map && 9007 func_id != BPF_FUNC_sock_map_update && 9008 func_id != BPF_FUNC_map_delete_elem && 9009 func_id != BPF_FUNC_msg_redirect_map && 9010 func_id != BPF_FUNC_sk_select_reuseport && 9011 func_id != BPF_FUNC_map_lookup_elem && 9012 !may_update_sockmap(env, func_id)) 9013 goto error; 9014 break; 9015 case BPF_MAP_TYPE_SOCKHASH: 9016 if (func_id != BPF_FUNC_sk_redirect_hash && 9017 func_id != BPF_FUNC_sock_hash_update && 9018 func_id != BPF_FUNC_map_delete_elem && 9019 func_id != BPF_FUNC_msg_redirect_hash && 9020 func_id != BPF_FUNC_sk_select_reuseport && 9021 func_id != BPF_FUNC_map_lookup_elem && 9022 !may_update_sockmap(env, func_id)) 9023 goto error; 9024 break; 9025 case BPF_MAP_TYPE_REUSEPORT_SOCKARRAY: 9026 if (func_id != BPF_FUNC_sk_select_reuseport) 9027 goto error; 9028 break; 9029 case BPF_MAP_TYPE_QUEUE: 9030 case BPF_MAP_TYPE_STACK: 9031 if (func_id != BPF_FUNC_map_peek_elem && 9032 func_id != BPF_FUNC_map_pop_elem && 9033 func_id != BPF_FUNC_map_push_elem) 9034 goto error; 9035 break; 9036 case BPF_MAP_TYPE_SK_STORAGE: 9037 if (func_id != BPF_FUNC_sk_storage_get && 9038 func_id != BPF_FUNC_sk_storage_delete && 9039 func_id != BPF_FUNC_kptr_xchg) 9040 goto error; 9041 break; 9042 case BPF_MAP_TYPE_INODE_STORAGE: 9043 if (func_id != BPF_FUNC_inode_storage_get && 9044 func_id != BPF_FUNC_inode_storage_delete && 9045 func_id != BPF_FUNC_kptr_xchg) 9046 goto error; 9047 break; 9048 case BPF_MAP_TYPE_TASK_STORAGE: 9049 if (func_id != BPF_FUNC_task_storage_get && 9050 func_id != BPF_FUNC_task_storage_delete && 9051 func_id != BPF_FUNC_kptr_xchg) 9052 goto error; 9053 break; 9054 case BPF_MAP_TYPE_CGRP_STORAGE: 9055 if (func_id != BPF_FUNC_cgrp_storage_get && 9056 func_id != BPF_FUNC_cgrp_storage_delete && 9057 func_id != BPF_FUNC_kptr_xchg) 9058 goto error; 9059 break; 9060 case BPF_MAP_TYPE_BLOOM_FILTER: 9061 if (func_id != BPF_FUNC_map_peek_elem && 9062 func_id != BPF_FUNC_map_push_elem) 9063 goto error; 9064 break; 9065 default: 9066 break; 9067 } 9068 9069 /* ... and second from the function itself. */ 9070 switch (func_id) { 9071 case BPF_FUNC_tail_call: 9072 if (map->map_type != BPF_MAP_TYPE_PROG_ARRAY) 9073 goto error; 9074 if (env->subprog_cnt > 1 && !allow_tail_call_in_subprogs(env)) { 9075 verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n"); 9076 return -EINVAL; 9077 } 9078 break; 9079 case BPF_FUNC_perf_event_read: 9080 case BPF_FUNC_perf_event_output: 9081 case BPF_FUNC_perf_event_read_value: 9082 case BPF_FUNC_skb_output: 9083 case BPF_FUNC_xdp_output: 9084 if (map->map_type != BPF_MAP_TYPE_PERF_EVENT_ARRAY) 9085 goto error; 9086 break; 9087 case BPF_FUNC_ringbuf_output: 9088 case BPF_FUNC_ringbuf_reserve: 9089 case BPF_FUNC_ringbuf_query: 9090 case BPF_FUNC_ringbuf_reserve_dynptr: 9091 case BPF_FUNC_ringbuf_submit_dynptr: 9092 case BPF_FUNC_ringbuf_discard_dynptr: 9093 if (map->map_type != BPF_MAP_TYPE_RINGBUF) 9094 goto error; 9095 break; 9096 case BPF_FUNC_user_ringbuf_drain: 9097 if (map->map_type != BPF_MAP_TYPE_USER_RINGBUF) 9098 goto error; 9099 break; 9100 case BPF_FUNC_get_stackid: 9101 if (map->map_type != BPF_MAP_TYPE_STACK_TRACE) 9102 goto error; 9103 break; 9104 case BPF_FUNC_current_task_under_cgroup: 9105 case BPF_FUNC_skb_under_cgroup: 9106 if (map->map_type != BPF_MAP_TYPE_CGROUP_ARRAY) 9107 goto error; 9108 break; 9109 case BPF_FUNC_redirect_map: 9110 if (map->map_type != BPF_MAP_TYPE_DEVMAP && 9111 map->map_type != BPF_MAP_TYPE_DEVMAP_HASH && 9112 map->map_type != BPF_MAP_TYPE_CPUMAP && 9113 map->map_type != BPF_MAP_TYPE_XSKMAP) 9114 goto error; 9115 break; 9116 case BPF_FUNC_sk_redirect_map: 9117 case BPF_FUNC_msg_redirect_map: 9118 case BPF_FUNC_sock_map_update: 9119 if (map->map_type != BPF_MAP_TYPE_SOCKMAP) 9120 goto error; 9121 break; 9122 case BPF_FUNC_sk_redirect_hash: 9123 case BPF_FUNC_msg_redirect_hash: 9124 case BPF_FUNC_sock_hash_update: 9125 if (map->map_type != BPF_MAP_TYPE_SOCKHASH) 9126 goto error; 9127 break; 9128 case BPF_FUNC_get_local_storage: 9129 if (map->map_type != BPF_MAP_TYPE_CGROUP_STORAGE && 9130 map->map_type != BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE) 9131 goto error; 9132 break; 9133 case BPF_FUNC_sk_select_reuseport: 9134 if (map->map_type != BPF_MAP_TYPE_REUSEPORT_SOCKARRAY && 9135 map->map_type != BPF_MAP_TYPE_SOCKMAP && 9136 map->map_type != BPF_MAP_TYPE_SOCKHASH) 9137 goto error; 9138 break; 9139 case BPF_FUNC_map_pop_elem: 9140 if (map->map_type != BPF_MAP_TYPE_QUEUE && 9141 map->map_type != BPF_MAP_TYPE_STACK) 9142 goto error; 9143 break; 9144 case BPF_FUNC_map_peek_elem: 9145 case BPF_FUNC_map_push_elem: 9146 if (map->map_type != BPF_MAP_TYPE_QUEUE && 9147 map->map_type != BPF_MAP_TYPE_STACK && 9148 map->map_type != BPF_MAP_TYPE_BLOOM_FILTER) 9149 goto error; 9150 break; 9151 case BPF_FUNC_map_lookup_percpu_elem: 9152 if (map->map_type != BPF_MAP_TYPE_PERCPU_ARRAY && 9153 map->map_type != BPF_MAP_TYPE_PERCPU_HASH && 9154 map->map_type != BPF_MAP_TYPE_LRU_PERCPU_HASH) 9155 goto error; 9156 break; 9157 case BPF_FUNC_sk_storage_get: 9158 case BPF_FUNC_sk_storage_delete: 9159 if (map->map_type != BPF_MAP_TYPE_SK_STORAGE) 9160 goto error; 9161 break; 9162 case BPF_FUNC_inode_storage_get: 9163 case BPF_FUNC_inode_storage_delete: 9164 if (map->map_type != BPF_MAP_TYPE_INODE_STORAGE) 9165 goto error; 9166 break; 9167 case BPF_FUNC_task_storage_get: 9168 case BPF_FUNC_task_storage_delete: 9169 if (map->map_type != BPF_MAP_TYPE_TASK_STORAGE) 9170 goto error; 9171 break; 9172 case BPF_FUNC_cgrp_storage_get: 9173 case BPF_FUNC_cgrp_storage_delete: 9174 if (map->map_type != BPF_MAP_TYPE_CGRP_STORAGE) 9175 goto error; 9176 break; 9177 default: 9178 break; 9179 } 9180 9181 return 0; 9182 error: 9183 verbose(env, "cannot pass map_type %d into func %s#%d\n", 9184 map->map_type, func_id_name(func_id), func_id); 9185 return -EINVAL; 9186 } 9187 9188 static bool check_raw_mode_ok(const struct bpf_func_proto *fn) 9189 { 9190 int count = 0; 9191 9192 if (fn->arg1_type == ARG_PTR_TO_UNINIT_MEM) 9193 count++; 9194 if (fn->arg2_type == ARG_PTR_TO_UNINIT_MEM) 9195 count++; 9196 if (fn->arg3_type == ARG_PTR_TO_UNINIT_MEM) 9197 count++; 9198 if (fn->arg4_type == ARG_PTR_TO_UNINIT_MEM) 9199 count++; 9200 if (fn->arg5_type == ARG_PTR_TO_UNINIT_MEM) 9201 count++; 9202 9203 /* We only support one arg being in raw mode at the moment, 9204 * which is sufficient for the helper functions we have 9205 * right now. 9206 */ 9207 return count <= 1; 9208 } 9209 9210 static bool check_args_pair_invalid(const struct bpf_func_proto *fn, int arg) 9211 { 9212 bool is_fixed = fn->arg_type[arg] & MEM_FIXED_SIZE; 9213 bool has_size = fn->arg_size[arg] != 0; 9214 bool is_next_size = false; 9215 9216 if (arg + 1 < ARRAY_SIZE(fn->arg_type)) 9217 is_next_size = arg_type_is_mem_size(fn->arg_type[arg + 1]); 9218 9219 if (base_type(fn->arg_type[arg]) != ARG_PTR_TO_MEM) 9220 return is_next_size; 9221 9222 return has_size == is_next_size || is_next_size == is_fixed; 9223 } 9224 9225 static bool check_arg_pair_ok(const struct bpf_func_proto *fn) 9226 { 9227 /* bpf_xxx(..., buf, len) call will access 'len' 9228 * bytes from memory 'buf'. Both arg types need 9229 * to be paired, so make sure there's no buggy 9230 * helper function specification. 9231 */ 9232 if (arg_type_is_mem_size(fn->arg1_type) || 9233 check_args_pair_invalid(fn, 0) || 9234 check_args_pair_invalid(fn, 1) || 9235 check_args_pair_invalid(fn, 2) || 9236 check_args_pair_invalid(fn, 3) || 9237 check_args_pair_invalid(fn, 4)) 9238 return false; 9239 9240 return true; 9241 } 9242 9243 static bool check_btf_id_ok(const struct bpf_func_proto *fn) 9244 { 9245 int i; 9246 9247 for (i = 0; i < ARRAY_SIZE(fn->arg_type); i++) { 9248 if (base_type(fn->arg_type[i]) == ARG_PTR_TO_BTF_ID) 9249 return !!fn->arg_btf_id[i]; 9250 if (base_type(fn->arg_type[i]) == ARG_PTR_TO_SPIN_LOCK) 9251 return fn->arg_btf_id[i] == BPF_PTR_POISON; 9252 if (base_type(fn->arg_type[i]) != ARG_PTR_TO_BTF_ID && fn->arg_btf_id[i] && 9253 /* arg_btf_id and arg_size are in a union. */ 9254 (base_type(fn->arg_type[i]) != ARG_PTR_TO_MEM || 9255 !(fn->arg_type[i] & MEM_FIXED_SIZE))) 9256 return false; 9257 } 9258 9259 return true; 9260 } 9261 9262 static int check_func_proto(const struct bpf_func_proto *fn, int func_id) 9263 { 9264 return check_raw_mode_ok(fn) && 9265 check_arg_pair_ok(fn) && 9266 check_btf_id_ok(fn) ? 0 : -EINVAL; 9267 } 9268 9269 /* Packet data might have moved, any old PTR_TO_PACKET[_META,_END] 9270 * are now invalid, so turn them into unknown SCALAR_VALUE. 9271 * 9272 * This also applies to dynptr slices belonging to skb and xdp dynptrs, 9273 * since these slices point to packet data. 9274 */ 9275 static void clear_all_pkt_pointers(struct bpf_verifier_env *env) 9276 { 9277 struct bpf_func_state *state; 9278 struct bpf_reg_state *reg; 9279 9280 bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({ 9281 if (reg_is_pkt_pointer_any(reg) || reg_is_dynptr_slice_pkt(reg)) 9282 mark_reg_invalid(env, reg); 9283 })); 9284 } 9285 9286 enum { 9287 AT_PKT_END = -1, 9288 BEYOND_PKT_END = -2, 9289 }; 9290 9291 static void mark_pkt_end(struct bpf_verifier_state *vstate, int regn, bool range_open) 9292 { 9293 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 9294 struct bpf_reg_state *reg = &state->regs[regn]; 9295 9296 if (reg->type != PTR_TO_PACKET) 9297 /* PTR_TO_PACKET_META is not supported yet */ 9298 return; 9299 9300 /* The 'reg' is pkt > pkt_end or pkt >= pkt_end. 9301 * How far beyond pkt_end it goes is unknown. 9302 * if (!range_open) it's the case of pkt >= pkt_end 9303 * if (range_open) it's the case of pkt > pkt_end 9304 * hence this pointer is at least 1 byte bigger than pkt_end 9305 */ 9306 if (range_open) 9307 reg->range = BEYOND_PKT_END; 9308 else 9309 reg->range = AT_PKT_END; 9310 } 9311 9312 /* The pointer with the specified id has released its reference to kernel 9313 * resources. Identify all copies of the same pointer and clear the reference. 9314 */ 9315 static int release_reference(struct bpf_verifier_env *env, 9316 int ref_obj_id) 9317 { 9318 struct bpf_func_state *state; 9319 struct bpf_reg_state *reg; 9320 int err; 9321 9322 err = release_reference_state(cur_func(env), ref_obj_id); 9323 if (err) 9324 return err; 9325 9326 bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({ 9327 if (reg->ref_obj_id == ref_obj_id) 9328 mark_reg_invalid(env, reg); 9329 })); 9330 9331 return 0; 9332 } 9333 9334 static void invalidate_non_owning_refs(struct bpf_verifier_env *env) 9335 { 9336 struct bpf_func_state *unused; 9337 struct bpf_reg_state *reg; 9338 9339 bpf_for_each_reg_in_vstate(env->cur_state, unused, reg, ({ 9340 if (type_is_non_owning_ref(reg->type)) 9341 mark_reg_invalid(env, reg); 9342 })); 9343 } 9344 9345 static void clear_caller_saved_regs(struct bpf_verifier_env *env, 9346 struct bpf_reg_state *regs) 9347 { 9348 int i; 9349 9350 /* after the call registers r0 - r5 were scratched */ 9351 for (i = 0; i < CALLER_SAVED_REGS; i++) { 9352 mark_reg_not_init(env, regs, caller_saved[i]); 9353 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK); 9354 } 9355 } 9356 9357 typedef int (*set_callee_state_fn)(struct bpf_verifier_env *env, 9358 struct bpf_func_state *caller, 9359 struct bpf_func_state *callee, 9360 int insn_idx); 9361 9362 static int set_callee_state(struct bpf_verifier_env *env, 9363 struct bpf_func_state *caller, 9364 struct bpf_func_state *callee, int insn_idx); 9365 9366 static int __check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn, 9367 int *insn_idx, int subprog, 9368 set_callee_state_fn set_callee_state_cb) 9369 { 9370 struct bpf_verifier_state *state = env->cur_state; 9371 struct bpf_func_state *caller, *callee; 9372 int err; 9373 9374 if (state->curframe + 1 >= MAX_CALL_FRAMES) { 9375 verbose(env, "the call stack of %d frames is too deep\n", 9376 state->curframe + 2); 9377 return -E2BIG; 9378 } 9379 9380 caller = state->frame[state->curframe]; 9381 if (state->frame[state->curframe + 1]) { 9382 verbose(env, "verifier bug. Frame %d already allocated\n", 9383 state->curframe + 1); 9384 return -EFAULT; 9385 } 9386 9387 err = btf_check_subprog_call(env, subprog, caller->regs); 9388 if (err == -EFAULT) 9389 return err; 9390 if (subprog_is_global(env, subprog)) { 9391 if (err) { 9392 verbose(env, "Caller passes invalid args into func#%d\n", 9393 subprog); 9394 return err; 9395 } else { 9396 if (env->log.level & BPF_LOG_LEVEL) 9397 verbose(env, 9398 "Func#%d is global and valid. Skipping.\n", 9399 subprog); 9400 clear_caller_saved_regs(env, caller->regs); 9401 9402 /* All global functions return a 64-bit SCALAR_VALUE */ 9403 mark_reg_unknown(env, caller->regs, BPF_REG_0); 9404 caller->regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG; 9405 9406 /* continue with next insn after call */ 9407 return 0; 9408 } 9409 } 9410 9411 /* set_callee_state is used for direct subprog calls, but we are 9412 * interested in validating only BPF helpers that can call subprogs as 9413 * callbacks 9414 */ 9415 if (set_callee_state_cb != set_callee_state) { 9416 env->subprog_info[subprog].is_cb = true; 9417 if (bpf_pseudo_kfunc_call(insn) && 9418 !is_callback_calling_kfunc(insn->imm)) { 9419 verbose(env, "verifier bug: kfunc %s#%d not marked as callback-calling\n", 9420 func_id_name(insn->imm), insn->imm); 9421 return -EFAULT; 9422 } else if (!bpf_pseudo_kfunc_call(insn) && 9423 !is_callback_calling_function(insn->imm)) { /* helper */ 9424 verbose(env, "verifier bug: helper %s#%d not marked as callback-calling\n", 9425 func_id_name(insn->imm), insn->imm); 9426 return -EFAULT; 9427 } 9428 } 9429 9430 if (insn->code == (BPF_JMP | BPF_CALL) && 9431 insn->src_reg == 0 && 9432 insn->imm == BPF_FUNC_timer_set_callback) { 9433 struct bpf_verifier_state *async_cb; 9434 9435 /* there is no real recursion here. timer callbacks are async */ 9436 env->subprog_info[subprog].is_async_cb = true; 9437 async_cb = push_async_cb(env, env->subprog_info[subprog].start, 9438 *insn_idx, subprog); 9439 if (!async_cb) 9440 return -EFAULT; 9441 callee = async_cb->frame[0]; 9442 callee->async_entry_cnt = caller->async_entry_cnt + 1; 9443 9444 /* Convert bpf_timer_set_callback() args into timer callback args */ 9445 err = set_callee_state_cb(env, caller, callee, *insn_idx); 9446 if (err) 9447 return err; 9448 9449 clear_caller_saved_regs(env, caller->regs); 9450 mark_reg_unknown(env, caller->regs, BPF_REG_0); 9451 caller->regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG; 9452 /* continue with next insn after call */ 9453 return 0; 9454 } 9455 9456 callee = kzalloc(sizeof(*callee), GFP_KERNEL); 9457 if (!callee) 9458 return -ENOMEM; 9459 state->frame[state->curframe + 1] = callee; 9460 9461 /* callee cannot access r0, r6 - r9 for reading and has to write 9462 * into its own stack before reading from it. 9463 * callee can read/write into caller's stack 9464 */ 9465 init_func_state(env, callee, 9466 /* remember the callsite, it will be used by bpf_exit */ 9467 *insn_idx /* callsite */, 9468 state->curframe + 1 /* frameno within this callchain */, 9469 subprog /* subprog number within this prog */); 9470 9471 /* Transfer references to the callee */ 9472 err = copy_reference_state(callee, caller); 9473 if (err) 9474 goto err_out; 9475 9476 err = set_callee_state_cb(env, caller, callee, *insn_idx); 9477 if (err) 9478 goto err_out; 9479 9480 clear_caller_saved_regs(env, caller->regs); 9481 9482 /* only increment it after check_reg_arg() finished */ 9483 state->curframe++; 9484 9485 /* and go analyze first insn of the callee */ 9486 *insn_idx = env->subprog_info[subprog].start - 1; 9487 9488 if (env->log.level & BPF_LOG_LEVEL) { 9489 verbose(env, "caller:\n"); 9490 print_verifier_state(env, caller, true); 9491 verbose(env, "callee:\n"); 9492 print_verifier_state(env, callee, true); 9493 } 9494 return 0; 9495 9496 err_out: 9497 free_func_state(callee); 9498 state->frame[state->curframe + 1] = NULL; 9499 return err; 9500 } 9501 9502 int map_set_for_each_callback_args(struct bpf_verifier_env *env, 9503 struct bpf_func_state *caller, 9504 struct bpf_func_state *callee) 9505 { 9506 /* bpf_for_each_map_elem(struct bpf_map *map, void *callback_fn, 9507 * void *callback_ctx, u64 flags); 9508 * callback_fn(struct bpf_map *map, void *key, void *value, 9509 * void *callback_ctx); 9510 */ 9511 callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1]; 9512 9513 callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY; 9514 __mark_reg_known_zero(&callee->regs[BPF_REG_2]); 9515 callee->regs[BPF_REG_2].map_ptr = caller->regs[BPF_REG_1].map_ptr; 9516 9517 callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE; 9518 __mark_reg_known_zero(&callee->regs[BPF_REG_3]); 9519 callee->regs[BPF_REG_3].map_ptr = caller->regs[BPF_REG_1].map_ptr; 9520 9521 /* pointer to stack or null */ 9522 callee->regs[BPF_REG_4] = caller->regs[BPF_REG_3]; 9523 9524 /* unused */ 9525 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]); 9526 return 0; 9527 } 9528 9529 static int set_callee_state(struct bpf_verifier_env *env, 9530 struct bpf_func_state *caller, 9531 struct bpf_func_state *callee, int insn_idx) 9532 { 9533 int i; 9534 9535 /* copy r1 - r5 args that callee can access. The copy includes parent 9536 * pointers, which connects us up to the liveness chain 9537 */ 9538 for (i = BPF_REG_1; i <= BPF_REG_5; i++) 9539 callee->regs[i] = caller->regs[i]; 9540 return 0; 9541 } 9542 9543 static int check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn, 9544 int *insn_idx) 9545 { 9546 int subprog, target_insn; 9547 9548 target_insn = *insn_idx + insn->imm + 1; 9549 subprog = find_subprog(env, target_insn); 9550 if (subprog < 0) { 9551 verbose(env, "verifier bug. No program starts at insn %d\n", 9552 target_insn); 9553 return -EFAULT; 9554 } 9555 9556 return __check_func_call(env, insn, insn_idx, subprog, set_callee_state); 9557 } 9558 9559 static int set_map_elem_callback_state(struct bpf_verifier_env *env, 9560 struct bpf_func_state *caller, 9561 struct bpf_func_state *callee, 9562 int insn_idx) 9563 { 9564 struct bpf_insn_aux_data *insn_aux = &env->insn_aux_data[insn_idx]; 9565 struct bpf_map *map; 9566 int err; 9567 9568 if (bpf_map_ptr_poisoned(insn_aux)) { 9569 verbose(env, "tail_call abusing map_ptr\n"); 9570 return -EINVAL; 9571 } 9572 9573 map = BPF_MAP_PTR(insn_aux->map_ptr_state); 9574 if (!map->ops->map_set_for_each_callback_args || 9575 !map->ops->map_for_each_callback) { 9576 verbose(env, "callback function not allowed for map\n"); 9577 return -ENOTSUPP; 9578 } 9579 9580 err = map->ops->map_set_for_each_callback_args(env, caller, callee); 9581 if (err) 9582 return err; 9583 9584 callee->in_callback_fn = true; 9585 callee->callback_ret_range = tnum_range(0, 1); 9586 return 0; 9587 } 9588 9589 static int set_loop_callback_state(struct bpf_verifier_env *env, 9590 struct bpf_func_state *caller, 9591 struct bpf_func_state *callee, 9592 int insn_idx) 9593 { 9594 /* bpf_loop(u32 nr_loops, void *callback_fn, void *callback_ctx, 9595 * u64 flags); 9596 * callback_fn(u32 index, void *callback_ctx); 9597 */ 9598 callee->regs[BPF_REG_1].type = SCALAR_VALUE; 9599 callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3]; 9600 9601 /* unused */ 9602 __mark_reg_not_init(env, &callee->regs[BPF_REG_3]); 9603 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]); 9604 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]); 9605 9606 callee->in_callback_fn = true; 9607 callee->callback_ret_range = tnum_range(0, 1); 9608 return 0; 9609 } 9610 9611 static int set_timer_callback_state(struct bpf_verifier_env *env, 9612 struct bpf_func_state *caller, 9613 struct bpf_func_state *callee, 9614 int insn_idx) 9615 { 9616 struct bpf_map *map_ptr = caller->regs[BPF_REG_1].map_ptr; 9617 9618 /* bpf_timer_set_callback(struct bpf_timer *timer, void *callback_fn); 9619 * callback_fn(struct bpf_map *map, void *key, void *value); 9620 */ 9621 callee->regs[BPF_REG_1].type = CONST_PTR_TO_MAP; 9622 __mark_reg_known_zero(&callee->regs[BPF_REG_1]); 9623 callee->regs[BPF_REG_1].map_ptr = map_ptr; 9624 9625 callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY; 9626 __mark_reg_known_zero(&callee->regs[BPF_REG_2]); 9627 callee->regs[BPF_REG_2].map_ptr = map_ptr; 9628 9629 callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE; 9630 __mark_reg_known_zero(&callee->regs[BPF_REG_3]); 9631 callee->regs[BPF_REG_3].map_ptr = map_ptr; 9632 9633 /* unused */ 9634 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]); 9635 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]); 9636 callee->in_async_callback_fn = true; 9637 callee->callback_ret_range = tnum_range(0, 1); 9638 return 0; 9639 } 9640 9641 static int set_find_vma_callback_state(struct bpf_verifier_env *env, 9642 struct bpf_func_state *caller, 9643 struct bpf_func_state *callee, 9644 int insn_idx) 9645 { 9646 /* bpf_find_vma(struct task_struct *task, u64 addr, 9647 * void *callback_fn, void *callback_ctx, u64 flags) 9648 * (callback_fn)(struct task_struct *task, 9649 * struct vm_area_struct *vma, void *callback_ctx); 9650 */ 9651 callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1]; 9652 9653 callee->regs[BPF_REG_2].type = PTR_TO_BTF_ID; 9654 __mark_reg_known_zero(&callee->regs[BPF_REG_2]); 9655 callee->regs[BPF_REG_2].btf = btf_vmlinux; 9656 callee->regs[BPF_REG_2].btf_id = btf_tracing_ids[BTF_TRACING_TYPE_VMA], 9657 9658 /* pointer to stack or null */ 9659 callee->regs[BPF_REG_3] = caller->regs[BPF_REG_4]; 9660 9661 /* unused */ 9662 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]); 9663 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]); 9664 callee->in_callback_fn = true; 9665 callee->callback_ret_range = tnum_range(0, 1); 9666 return 0; 9667 } 9668 9669 static int set_user_ringbuf_callback_state(struct bpf_verifier_env *env, 9670 struct bpf_func_state *caller, 9671 struct bpf_func_state *callee, 9672 int insn_idx) 9673 { 9674 /* bpf_user_ringbuf_drain(struct bpf_map *map, void *callback_fn, void 9675 * callback_ctx, u64 flags); 9676 * callback_fn(const struct bpf_dynptr_t* dynptr, void *callback_ctx); 9677 */ 9678 __mark_reg_not_init(env, &callee->regs[BPF_REG_0]); 9679 mark_dynptr_cb_reg(env, &callee->regs[BPF_REG_1], BPF_DYNPTR_TYPE_LOCAL); 9680 callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3]; 9681 9682 /* unused */ 9683 __mark_reg_not_init(env, &callee->regs[BPF_REG_3]); 9684 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]); 9685 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]); 9686 9687 callee->in_callback_fn = true; 9688 callee->callback_ret_range = tnum_range(0, 1); 9689 return 0; 9690 } 9691 9692 static int set_rbtree_add_callback_state(struct bpf_verifier_env *env, 9693 struct bpf_func_state *caller, 9694 struct bpf_func_state *callee, 9695 int insn_idx) 9696 { 9697 /* void bpf_rbtree_add_impl(struct bpf_rb_root *root, struct bpf_rb_node *node, 9698 * bool (less)(struct bpf_rb_node *a, const struct bpf_rb_node *b)); 9699 * 9700 * 'struct bpf_rb_node *node' arg to bpf_rbtree_add_impl is the same PTR_TO_BTF_ID w/ offset 9701 * that 'less' callback args will be receiving. However, 'node' arg was release_reference'd 9702 * by this point, so look at 'root' 9703 */ 9704 struct btf_field *field; 9705 9706 field = reg_find_field_offset(&caller->regs[BPF_REG_1], caller->regs[BPF_REG_1].off, 9707 BPF_RB_ROOT); 9708 if (!field || !field->graph_root.value_btf_id) 9709 return -EFAULT; 9710 9711 mark_reg_graph_node(callee->regs, BPF_REG_1, &field->graph_root); 9712 ref_set_non_owning(env, &callee->regs[BPF_REG_1]); 9713 mark_reg_graph_node(callee->regs, BPF_REG_2, &field->graph_root); 9714 ref_set_non_owning(env, &callee->regs[BPF_REG_2]); 9715 9716 __mark_reg_not_init(env, &callee->regs[BPF_REG_3]); 9717 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]); 9718 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]); 9719 callee->in_callback_fn = true; 9720 callee->callback_ret_range = tnum_range(0, 1); 9721 return 0; 9722 } 9723 9724 static bool is_rbtree_lock_required_kfunc(u32 btf_id); 9725 9726 /* Are we currently verifying the callback for a rbtree helper that must 9727 * be called with lock held? If so, no need to complain about unreleased 9728 * lock 9729 */ 9730 static bool in_rbtree_lock_required_cb(struct bpf_verifier_env *env) 9731 { 9732 struct bpf_verifier_state *state = env->cur_state; 9733 struct bpf_insn *insn = env->prog->insnsi; 9734 struct bpf_func_state *callee; 9735 int kfunc_btf_id; 9736 9737 if (!state->curframe) 9738 return false; 9739 9740 callee = state->frame[state->curframe]; 9741 9742 if (!callee->in_callback_fn) 9743 return false; 9744 9745 kfunc_btf_id = insn[callee->callsite].imm; 9746 return is_rbtree_lock_required_kfunc(kfunc_btf_id); 9747 } 9748 9749 static int prepare_func_exit(struct bpf_verifier_env *env, int *insn_idx) 9750 { 9751 struct bpf_verifier_state *state = env->cur_state; 9752 struct bpf_func_state *caller, *callee; 9753 struct bpf_reg_state *r0; 9754 int err; 9755 9756 callee = state->frame[state->curframe]; 9757 r0 = &callee->regs[BPF_REG_0]; 9758 if (r0->type == PTR_TO_STACK) { 9759 /* technically it's ok to return caller's stack pointer 9760 * (or caller's caller's pointer) back to the caller, 9761 * since these pointers are valid. Only current stack 9762 * pointer will be invalid as soon as function exits, 9763 * but let's be conservative 9764 */ 9765 verbose(env, "cannot return stack pointer to the caller\n"); 9766 return -EINVAL; 9767 } 9768 9769 caller = state->frame[state->curframe - 1]; 9770 if (callee->in_callback_fn) { 9771 /* enforce R0 return value range [0, 1]. */ 9772 struct tnum range = callee->callback_ret_range; 9773 9774 if (r0->type != SCALAR_VALUE) { 9775 verbose(env, "R0 not a scalar value\n"); 9776 return -EACCES; 9777 } 9778 if (!tnum_in(range, r0->var_off)) { 9779 verbose_invalid_scalar(env, r0, &range, "callback return", "R0"); 9780 return -EINVAL; 9781 } 9782 } else { 9783 /* return to the caller whatever r0 had in the callee */ 9784 caller->regs[BPF_REG_0] = *r0; 9785 } 9786 9787 /* callback_fn frame should have released its own additions to parent's 9788 * reference state at this point, or check_reference_leak would 9789 * complain, hence it must be the same as the caller. There is no need 9790 * to copy it back. 9791 */ 9792 if (!callee->in_callback_fn) { 9793 /* Transfer references to the caller */ 9794 err = copy_reference_state(caller, callee); 9795 if (err) 9796 return err; 9797 } 9798 9799 *insn_idx = callee->callsite + 1; 9800 if (env->log.level & BPF_LOG_LEVEL) { 9801 verbose(env, "returning from callee:\n"); 9802 print_verifier_state(env, callee, true); 9803 verbose(env, "to caller at %d:\n", *insn_idx); 9804 print_verifier_state(env, caller, true); 9805 } 9806 /* clear everything in the callee. In case of exceptional exits using 9807 * bpf_throw, this will be done by copy_verifier_state for extra frames. */ 9808 free_func_state(callee); 9809 state->frame[state->curframe--] = NULL; 9810 return 0; 9811 } 9812 9813 static void do_refine_retval_range(struct bpf_reg_state *regs, int ret_type, 9814 int func_id, 9815 struct bpf_call_arg_meta *meta) 9816 { 9817 struct bpf_reg_state *ret_reg = ®s[BPF_REG_0]; 9818 9819 if (ret_type != RET_INTEGER) 9820 return; 9821 9822 switch (func_id) { 9823 case BPF_FUNC_get_stack: 9824 case BPF_FUNC_get_task_stack: 9825 case BPF_FUNC_probe_read_str: 9826 case BPF_FUNC_probe_read_kernel_str: 9827 case BPF_FUNC_probe_read_user_str: 9828 ret_reg->smax_value = meta->msize_max_value; 9829 ret_reg->s32_max_value = meta->msize_max_value; 9830 ret_reg->smin_value = -MAX_ERRNO; 9831 ret_reg->s32_min_value = -MAX_ERRNO; 9832 reg_bounds_sync(ret_reg); 9833 break; 9834 case BPF_FUNC_get_smp_processor_id: 9835 ret_reg->umax_value = nr_cpu_ids - 1; 9836 ret_reg->u32_max_value = nr_cpu_ids - 1; 9837 ret_reg->smax_value = nr_cpu_ids - 1; 9838 ret_reg->s32_max_value = nr_cpu_ids - 1; 9839 ret_reg->umin_value = 0; 9840 ret_reg->u32_min_value = 0; 9841 ret_reg->smin_value = 0; 9842 ret_reg->s32_min_value = 0; 9843 reg_bounds_sync(ret_reg); 9844 break; 9845 } 9846 } 9847 9848 static int 9849 record_func_map(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta, 9850 int func_id, int insn_idx) 9851 { 9852 struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx]; 9853 struct bpf_map *map = meta->map_ptr; 9854 9855 if (func_id != BPF_FUNC_tail_call && 9856 func_id != BPF_FUNC_map_lookup_elem && 9857 func_id != BPF_FUNC_map_update_elem && 9858 func_id != BPF_FUNC_map_delete_elem && 9859 func_id != BPF_FUNC_map_push_elem && 9860 func_id != BPF_FUNC_map_pop_elem && 9861 func_id != BPF_FUNC_map_peek_elem && 9862 func_id != BPF_FUNC_for_each_map_elem && 9863 func_id != BPF_FUNC_redirect_map && 9864 func_id != BPF_FUNC_map_lookup_percpu_elem) 9865 return 0; 9866 9867 if (map == NULL) { 9868 verbose(env, "kernel subsystem misconfigured verifier\n"); 9869 return -EINVAL; 9870 } 9871 9872 /* In case of read-only, some additional restrictions 9873 * need to be applied in order to prevent altering the 9874 * state of the map from program side. 9875 */ 9876 if ((map->map_flags & BPF_F_RDONLY_PROG) && 9877 (func_id == BPF_FUNC_map_delete_elem || 9878 func_id == BPF_FUNC_map_update_elem || 9879 func_id == BPF_FUNC_map_push_elem || 9880 func_id == BPF_FUNC_map_pop_elem)) { 9881 verbose(env, "write into map forbidden\n"); 9882 return -EACCES; 9883 } 9884 9885 if (!BPF_MAP_PTR(aux->map_ptr_state)) 9886 bpf_map_ptr_store(aux, meta->map_ptr, 9887 !meta->map_ptr->bypass_spec_v1); 9888 else if (BPF_MAP_PTR(aux->map_ptr_state) != meta->map_ptr) 9889 bpf_map_ptr_store(aux, BPF_MAP_PTR_POISON, 9890 !meta->map_ptr->bypass_spec_v1); 9891 return 0; 9892 } 9893 9894 static int 9895 record_func_key(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta, 9896 int func_id, int insn_idx) 9897 { 9898 struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx]; 9899 struct bpf_reg_state *regs = cur_regs(env), *reg; 9900 struct bpf_map *map = meta->map_ptr; 9901 u64 val, max; 9902 int err; 9903 9904 if (func_id != BPF_FUNC_tail_call) 9905 return 0; 9906 if (!map || map->map_type != BPF_MAP_TYPE_PROG_ARRAY) { 9907 verbose(env, "kernel subsystem misconfigured verifier\n"); 9908 return -EINVAL; 9909 } 9910 9911 reg = ®s[BPF_REG_3]; 9912 val = reg->var_off.value; 9913 max = map->max_entries; 9914 9915 if (!(register_is_const(reg) && val < max)) { 9916 bpf_map_key_store(aux, BPF_MAP_KEY_POISON); 9917 return 0; 9918 } 9919 9920 err = mark_chain_precision(env, BPF_REG_3); 9921 if (err) 9922 return err; 9923 if (bpf_map_key_unseen(aux)) 9924 bpf_map_key_store(aux, val); 9925 else if (!bpf_map_key_poisoned(aux) && 9926 bpf_map_key_immediate(aux) != val) 9927 bpf_map_key_store(aux, BPF_MAP_KEY_POISON); 9928 return 0; 9929 } 9930 9931 static int check_reference_leak(struct bpf_verifier_env *env, bool exception_exit) 9932 { 9933 struct bpf_func_state *state = cur_func(env); 9934 bool refs_lingering = false; 9935 int i; 9936 9937 if (!exception_exit && state->frameno && !state->in_callback_fn) 9938 return 0; 9939 9940 for (i = 0; i < state->acquired_refs; i++) { 9941 if (!exception_exit && state->in_callback_fn && state->refs[i].callback_ref != state->frameno) 9942 continue; 9943 verbose(env, "Unreleased reference id=%d alloc_insn=%d\n", 9944 state->refs[i].id, state->refs[i].insn_idx); 9945 refs_lingering = true; 9946 } 9947 return refs_lingering ? -EINVAL : 0; 9948 } 9949 9950 static int check_bpf_snprintf_call(struct bpf_verifier_env *env, 9951 struct bpf_reg_state *regs) 9952 { 9953 struct bpf_reg_state *fmt_reg = ®s[BPF_REG_3]; 9954 struct bpf_reg_state *data_len_reg = ®s[BPF_REG_5]; 9955 struct bpf_map *fmt_map = fmt_reg->map_ptr; 9956 struct bpf_bprintf_data data = {}; 9957 int err, fmt_map_off, num_args; 9958 u64 fmt_addr; 9959 char *fmt; 9960 9961 /* data must be an array of u64 */ 9962 if (data_len_reg->var_off.value % 8) 9963 return -EINVAL; 9964 num_args = data_len_reg->var_off.value / 8; 9965 9966 /* fmt being ARG_PTR_TO_CONST_STR guarantees that var_off is const 9967 * and map_direct_value_addr is set. 9968 */ 9969 fmt_map_off = fmt_reg->off + fmt_reg->var_off.value; 9970 err = fmt_map->ops->map_direct_value_addr(fmt_map, &fmt_addr, 9971 fmt_map_off); 9972 if (err) { 9973 verbose(env, "verifier bug\n"); 9974 return -EFAULT; 9975 } 9976 fmt = (char *)(long)fmt_addr + fmt_map_off; 9977 9978 /* We are also guaranteed that fmt+fmt_map_off is NULL terminated, we 9979 * can focus on validating the format specifiers. 9980 */ 9981 err = bpf_bprintf_prepare(fmt, UINT_MAX, NULL, num_args, &data); 9982 if (err < 0) 9983 verbose(env, "Invalid format string\n"); 9984 9985 return err; 9986 } 9987 9988 static int check_get_func_ip(struct bpf_verifier_env *env) 9989 { 9990 enum bpf_prog_type type = resolve_prog_type(env->prog); 9991 int func_id = BPF_FUNC_get_func_ip; 9992 9993 if (type == BPF_PROG_TYPE_TRACING) { 9994 if (!bpf_prog_has_trampoline(env->prog)) { 9995 verbose(env, "func %s#%d supported only for fentry/fexit/fmod_ret programs\n", 9996 func_id_name(func_id), func_id); 9997 return -ENOTSUPP; 9998 } 9999 return 0; 10000 } else if (type == BPF_PROG_TYPE_KPROBE) { 10001 return 0; 10002 } 10003 10004 verbose(env, "func %s#%d not supported for program type %d\n", 10005 func_id_name(func_id), func_id, type); 10006 return -ENOTSUPP; 10007 } 10008 10009 static struct bpf_insn_aux_data *cur_aux(struct bpf_verifier_env *env) 10010 { 10011 return &env->insn_aux_data[env->insn_idx]; 10012 } 10013 10014 static bool loop_flag_is_zero(struct bpf_verifier_env *env) 10015 { 10016 struct bpf_reg_state *regs = cur_regs(env); 10017 struct bpf_reg_state *reg = ®s[BPF_REG_4]; 10018 bool reg_is_null = register_is_null(reg); 10019 10020 if (reg_is_null) 10021 mark_chain_precision(env, BPF_REG_4); 10022 10023 return reg_is_null; 10024 } 10025 10026 static void update_loop_inline_state(struct bpf_verifier_env *env, u32 subprogno) 10027 { 10028 struct bpf_loop_inline_state *state = &cur_aux(env)->loop_inline_state; 10029 10030 if (!state->initialized) { 10031 state->initialized = 1; 10032 state->fit_for_inline = loop_flag_is_zero(env); 10033 state->callback_subprogno = subprogno; 10034 return; 10035 } 10036 10037 if (!state->fit_for_inline) 10038 return; 10039 10040 state->fit_for_inline = (loop_flag_is_zero(env) && 10041 state->callback_subprogno == subprogno); 10042 } 10043 10044 static int check_helper_call(struct bpf_verifier_env *env, struct bpf_insn *insn, 10045 int *insn_idx_p) 10046 { 10047 enum bpf_prog_type prog_type = resolve_prog_type(env->prog); 10048 bool returns_cpu_specific_alloc_ptr = false; 10049 const struct bpf_func_proto *fn = NULL; 10050 enum bpf_return_type ret_type; 10051 enum bpf_type_flag ret_flag; 10052 struct bpf_reg_state *regs; 10053 struct bpf_call_arg_meta meta; 10054 int insn_idx = *insn_idx_p; 10055 bool changes_data; 10056 int i, err, func_id; 10057 10058 /* find function prototype */ 10059 func_id = insn->imm; 10060 if (func_id < 0 || func_id >= __BPF_FUNC_MAX_ID) { 10061 verbose(env, "invalid func %s#%d\n", func_id_name(func_id), 10062 func_id); 10063 return -EINVAL; 10064 } 10065 10066 if (env->ops->get_func_proto) 10067 fn = env->ops->get_func_proto(func_id, env->prog); 10068 if (!fn) { 10069 verbose(env, "unknown func %s#%d\n", func_id_name(func_id), 10070 func_id); 10071 return -EINVAL; 10072 } 10073 10074 /* eBPF programs must be GPL compatible to use GPL-ed functions */ 10075 if (!env->prog->gpl_compatible && fn->gpl_only) { 10076 verbose(env, "cannot call GPL-restricted function from non-GPL compatible program\n"); 10077 return -EINVAL; 10078 } 10079 10080 if (fn->allowed && !fn->allowed(env->prog)) { 10081 verbose(env, "helper call is not allowed in probe\n"); 10082 return -EINVAL; 10083 } 10084 10085 if (!env->prog->aux->sleepable && fn->might_sleep) { 10086 verbose(env, "helper call might sleep in a non-sleepable prog\n"); 10087 return -EINVAL; 10088 } 10089 10090 /* With LD_ABS/IND some JITs save/restore skb from r1. */ 10091 changes_data = bpf_helper_changes_pkt_data(fn->func); 10092 if (changes_data && fn->arg1_type != ARG_PTR_TO_CTX) { 10093 verbose(env, "kernel subsystem misconfigured func %s#%d: r1 != ctx\n", 10094 func_id_name(func_id), func_id); 10095 return -EINVAL; 10096 } 10097 10098 memset(&meta, 0, sizeof(meta)); 10099 meta.pkt_access = fn->pkt_access; 10100 10101 err = check_func_proto(fn, func_id); 10102 if (err) { 10103 verbose(env, "kernel subsystem misconfigured func %s#%d\n", 10104 func_id_name(func_id), func_id); 10105 return err; 10106 } 10107 10108 if (env->cur_state->active_rcu_lock) { 10109 if (fn->might_sleep) { 10110 verbose(env, "sleepable helper %s#%d in rcu_read_lock region\n", 10111 func_id_name(func_id), func_id); 10112 return -EINVAL; 10113 } 10114 10115 if (env->prog->aux->sleepable && is_storage_get_function(func_id)) 10116 env->insn_aux_data[insn_idx].storage_get_func_atomic = true; 10117 } 10118 10119 meta.func_id = func_id; 10120 /* check args */ 10121 for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++) { 10122 err = check_func_arg(env, i, &meta, fn, insn_idx); 10123 if (err) 10124 return err; 10125 } 10126 10127 err = record_func_map(env, &meta, func_id, insn_idx); 10128 if (err) 10129 return err; 10130 10131 err = record_func_key(env, &meta, func_id, insn_idx); 10132 if (err) 10133 return err; 10134 10135 /* Mark slots with STACK_MISC in case of raw mode, stack offset 10136 * is inferred from register state. 10137 */ 10138 for (i = 0; i < meta.access_size; i++) { 10139 err = check_mem_access(env, insn_idx, meta.regno, i, BPF_B, 10140 BPF_WRITE, -1, false, false); 10141 if (err) 10142 return err; 10143 } 10144 10145 regs = cur_regs(env); 10146 10147 if (meta.release_regno) { 10148 err = -EINVAL; 10149 /* This can only be set for PTR_TO_STACK, as CONST_PTR_TO_DYNPTR cannot 10150 * be released by any dynptr helper. Hence, unmark_stack_slots_dynptr 10151 * is safe to do directly. 10152 */ 10153 if (arg_type_is_dynptr(fn->arg_type[meta.release_regno - BPF_REG_1])) { 10154 if (regs[meta.release_regno].type == CONST_PTR_TO_DYNPTR) { 10155 verbose(env, "verifier internal error: CONST_PTR_TO_DYNPTR cannot be released\n"); 10156 return -EFAULT; 10157 } 10158 err = unmark_stack_slots_dynptr(env, ®s[meta.release_regno]); 10159 } else if (func_id == BPF_FUNC_kptr_xchg && meta.ref_obj_id) { 10160 u32 ref_obj_id = meta.ref_obj_id; 10161 bool in_rcu = in_rcu_cs(env); 10162 struct bpf_func_state *state; 10163 struct bpf_reg_state *reg; 10164 10165 err = release_reference_state(cur_func(env), ref_obj_id); 10166 if (!err) { 10167 bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({ 10168 if (reg->ref_obj_id == ref_obj_id) { 10169 if (in_rcu && (reg->type & MEM_ALLOC) && (reg->type & MEM_PERCPU)) { 10170 reg->ref_obj_id = 0; 10171 reg->type &= ~MEM_ALLOC; 10172 reg->type |= MEM_RCU; 10173 } else { 10174 mark_reg_invalid(env, reg); 10175 } 10176 } 10177 })); 10178 } 10179 } else if (meta.ref_obj_id) { 10180 err = release_reference(env, meta.ref_obj_id); 10181 } else if (register_is_null(®s[meta.release_regno])) { 10182 /* meta.ref_obj_id can only be 0 if register that is meant to be 10183 * released is NULL, which must be > R0. 10184 */ 10185 err = 0; 10186 } 10187 if (err) { 10188 verbose(env, "func %s#%d reference has not been acquired before\n", 10189 func_id_name(func_id), func_id); 10190 return err; 10191 } 10192 } 10193 10194 switch (func_id) { 10195 case BPF_FUNC_tail_call: 10196 err = check_reference_leak(env, false); 10197 if (err) { 10198 verbose(env, "tail_call would lead to reference leak\n"); 10199 return err; 10200 } 10201 break; 10202 case BPF_FUNC_get_local_storage: 10203 /* check that flags argument in get_local_storage(map, flags) is 0, 10204 * this is required because get_local_storage() can't return an error. 10205 */ 10206 if (!register_is_null(®s[BPF_REG_2])) { 10207 verbose(env, "get_local_storage() doesn't support non-zero flags\n"); 10208 return -EINVAL; 10209 } 10210 break; 10211 case BPF_FUNC_for_each_map_elem: 10212 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno, 10213 set_map_elem_callback_state); 10214 break; 10215 case BPF_FUNC_timer_set_callback: 10216 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno, 10217 set_timer_callback_state); 10218 break; 10219 case BPF_FUNC_find_vma: 10220 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno, 10221 set_find_vma_callback_state); 10222 break; 10223 case BPF_FUNC_snprintf: 10224 err = check_bpf_snprintf_call(env, regs); 10225 break; 10226 case BPF_FUNC_loop: 10227 update_loop_inline_state(env, meta.subprogno); 10228 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno, 10229 set_loop_callback_state); 10230 break; 10231 case BPF_FUNC_dynptr_from_mem: 10232 if (regs[BPF_REG_1].type != PTR_TO_MAP_VALUE) { 10233 verbose(env, "Unsupported reg type %s for bpf_dynptr_from_mem data\n", 10234 reg_type_str(env, regs[BPF_REG_1].type)); 10235 return -EACCES; 10236 } 10237 break; 10238 case BPF_FUNC_set_retval: 10239 if (prog_type == BPF_PROG_TYPE_LSM && 10240 env->prog->expected_attach_type == BPF_LSM_CGROUP) { 10241 if (!env->prog->aux->attach_func_proto->type) { 10242 /* Make sure programs that attach to void 10243 * hooks don't try to modify return value. 10244 */ 10245 verbose(env, "BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n"); 10246 return -EINVAL; 10247 } 10248 } 10249 break; 10250 case BPF_FUNC_dynptr_data: 10251 { 10252 struct bpf_reg_state *reg; 10253 int id, ref_obj_id; 10254 10255 reg = get_dynptr_arg_reg(env, fn, regs); 10256 if (!reg) 10257 return -EFAULT; 10258 10259 10260 if (meta.dynptr_id) { 10261 verbose(env, "verifier internal error: meta.dynptr_id already set\n"); 10262 return -EFAULT; 10263 } 10264 if (meta.ref_obj_id) { 10265 verbose(env, "verifier internal error: meta.ref_obj_id already set\n"); 10266 return -EFAULT; 10267 } 10268 10269 id = dynptr_id(env, reg); 10270 if (id < 0) { 10271 verbose(env, "verifier internal error: failed to obtain dynptr id\n"); 10272 return id; 10273 } 10274 10275 ref_obj_id = dynptr_ref_obj_id(env, reg); 10276 if (ref_obj_id < 0) { 10277 verbose(env, "verifier internal error: failed to obtain dynptr ref_obj_id\n"); 10278 return ref_obj_id; 10279 } 10280 10281 meta.dynptr_id = id; 10282 meta.ref_obj_id = ref_obj_id; 10283 10284 break; 10285 } 10286 case BPF_FUNC_dynptr_write: 10287 { 10288 enum bpf_dynptr_type dynptr_type; 10289 struct bpf_reg_state *reg; 10290 10291 reg = get_dynptr_arg_reg(env, fn, regs); 10292 if (!reg) 10293 return -EFAULT; 10294 10295 dynptr_type = dynptr_get_type(env, reg); 10296 if (dynptr_type == BPF_DYNPTR_TYPE_INVALID) 10297 return -EFAULT; 10298 10299 if (dynptr_type == BPF_DYNPTR_TYPE_SKB) 10300 /* this will trigger clear_all_pkt_pointers(), which will 10301 * invalidate all dynptr slices associated with the skb 10302 */ 10303 changes_data = true; 10304 10305 break; 10306 } 10307 case BPF_FUNC_per_cpu_ptr: 10308 case BPF_FUNC_this_cpu_ptr: 10309 { 10310 struct bpf_reg_state *reg = ®s[BPF_REG_1]; 10311 const struct btf_type *type; 10312 10313 if (reg->type & MEM_RCU) { 10314 type = btf_type_by_id(reg->btf, reg->btf_id); 10315 if (!type || !btf_type_is_struct(type)) { 10316 verbose(env, "Helper has invalid btf/btf_id in R1\n"); 10317 return -EFAULT; 10318 } 10319 returns_cpu_specific_alloc_ptr = true; 10320 env->insn_aux_data[insn_idx].call_with_percpu_alloc_ptr = true; 10321 } 10322 break; 10323 } 10324 case BPF_FUNC_user_ringbuf_drain: 10325 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno, 10326 set_user_ringbuf_callback_state); 10327 break; 10328 } 10329 10330 if (err) 10331 return err; 10332 10333 /* reset caller saved regs */ 10334 for (i = 0; i < CALLER_SAVED_REGS; i++) { 10335 mark_reg_not_init(env, regs, caller_saved[i]); 10336 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK); 10337 } 10338 10339 /* helper call returns 64-bit value. */ 10340 regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG; 10341 10342 /* update return register (already marked as written above) */ 10343 ret_type = fn->ret_type; 10344 ret_flag = type_flag(ret_type); 10345 10346 switch (base_type(ret_type)) { 10347 case RET_INTEGER: 10348 /* sets type to SCALAR_VALUE */ 10349 mark_reg_unknown(env, regs, BPF_REG_0); 10350 break; 10351 case RET_VOID: 10352 regs[BPF_REG_0].type = NOT_INIT; 10353 break; 10354 case RET_PTR_TO_MAP_VALUE: 10355 /* There is no offset yet applied, variable or fixed */ 10356 mark_reg_known_zero(env, regs, BPF_REG_0); 10357 /* remember map_ptr, so that check_map_access() 10358 * can check 'value_size' boundary of memory access 10359 * to map element returned from bpf_map_lookup_elem() 10360 */ 10361 if (meta.map_ptr == NULL) { 10362 verbose(env, 10363 "kernel subsystem misconfigured verifier\n"); 10364 return -EINVAL; 10365 } 10366 regs[BPF_REG_0].map_ptr = meta.map_ptr; 10367 regs[BPF_REG_0].map_uid = meta.map_uid; 10368 regs[BPF_REG_0].type = PTR_TO_MAP_VALUE | ret_flag; 10369 if (!type_may_be_null(ret_type) && 10370 btf_record_has_field(meta.map_ptr->record, BPF_SPIN_LOCK)) { 10371 regs[BPF_REG_0].id = ++env->id_gen; 10372 } 10373 break; 10374 case RET_PTR_TO_SOCKET: 10375 mark_reg_known_zero(env, regs, BPF_REG_0); 10376 regs[BPF_REG_0].type = PTR_TO_SOCKET | ret_flag; 10377 break; 10378 case RET_PTR_TO_SOCK_COMMON: 10379 mark_reg_known_zero(env, regs, BPF_REG_0); 10380 regs[BPF_REG_0].type = PTR_TO_SOCK_COMMON | ret_flag; 10381 break; 10382 case RET_PTR_TO_TCP_SOCK: 10383 mark_reg_known_zero(env, regs, BPF_REG_0); 10384 regs[BPF_REG_0].type = PTR_TO_TCP_SOCK | ret_flag; 10385 break; 10386 case RET_PTR_TO_MEM: 10387 mark_reg_known_zero(env, regs, BPF_REG_0); 10388 regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag; 10389 regs[BPF_REG_0].mem_size = meta.mem_size; 10390 break; 10391 case RET_PTR_TO_MEM_OR_BTF_ID: 10392 { 10393 const struct btf_type *t; 10394 10395 mark_reg_known_zero(env, regs, BPF_REG_0); 10396 t = btf_type_skip_modifiers(meta.ret_btf, meta.ret_btf_id, NULL); 10397 if (!btf_type_is_struct(t)) { 10398 u32 tsize; 10399 const struct btf_type *ret; 10400 const char *tname; 10401 10402 /* resolve the type size of ksym. */ 10403 ret = btf_resolve_size(meta.ret_btf, t, &tsize); 10404 if (IS_ERR(ret)) { 10405 tname = btf_name_by_offset(meta.ret_btf, t->name_off); 10406 verbose(env, "unable to resolve the size of type '%s': %ld\n", 10407 tname, PTR_ERR(ret)); 10408 return -EINVAL; 10409 } 10410 regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag; 10411 regs[BPF_REG_0].mem_size = tsize; 10412 } else { 10413 if (returns_cpu_specific_alloc_ptr) { 10414 regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC | MEM_RCU; 10415 } else { 10416 /* MEM_RDONLY may be carried from ret_flag, but it 10417 * doesn't apply on PTR_TO_BTF_ID. Fold it, otherwise 10418 * it will confuse the check of PTR_TO_BTF_ID in 10419 * check_mem_access(). 10420 */ 10421 ret_flag &= ~MEM_RDONLY; 10422 regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag; 10423 } 10424 10425 regs[BPF_REG_0].btf = meta.ret_btf; 10426 regs[BPF_REG_0].btf_id = meta.ret_btf_id; 10427 } 10428 break; 10429 } 10430 case RET_PTR_TO_BTF_ID: 10431 { 10432 struct btf *ret_btf; 10433 int ret_btf_id; 10434 10435 mark_reg_known_zero(env, regs, BPF_REG_0); 10436 regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag; 10437 if (func_id == BPF_FUNC_kptr_xchg) { 10438 ret_btf = meta.kptr_field->kptr.btf; 10439 ret_btf_id = meta.kptr_field->kptr.btf_id; 10440 if (!btf_is_kernel(ret_btf)) { 10441 regs[BPF_REG_0].type |= MEM_ALLOC; 10442 if (meta.kptr_field->type == BPF_KPTR_PERCPU) 10443 regs[BPF_REG_0].type |= MEM_PERCPU; 10444 } 10445 } else { 10446 if (fn->ret_btf_id == BPF_PTR_POISON) { 10447 verbose(env, "verifier internal error:"); 10448 verbose(env, "func %s has non-overwritten BPF_PTR_POISON return type\n", 10449 func_id_name(func_id)); 10450 return -EINVAL; 10451 } 10452 ret_btf = btf_vmlinux; 10453 ret_btf_id = *fn->ret_btf_id; 10454 } 10455 if (ret_btf_id == 0) { 10456 verbose(env, "invalid return type %u of func %s#%d\n", 10457 base_type(ret_type), func_id_name(func_id), 10458 func_id); 10459 return -EINVAL; 10460 } 10461 regs[BPF_REG_0].btf = ret_btf; 10462 regs[BPF_REG_0].btf_id = ret_btf_id; 10463 break; 10464 } 10465 default: 10466 verbose(env, "unknown return type %u of func %s#%d\n", 10467 base_type(ret_type), func_id_name(func_id), func_id); 10468 return -EINVAL; 10469 } 10470 10471 if (type_may_be_null(regs[BPF_REG_0].type)) 10472 regs[BPF_REG_0].id = ++env->id_gen; 10473 10474 if (helper_multiple_ref_obj_use(func_id, meta.map_ptr)) { 10475 verbose(env, "verifier internal error: func %s#%d sets ref_obj_id more than once\n", 10476 func_id_name(func_id), func_id); 10477 return -EFAULT; 10478 } 10479 10480 if (is_dynptr_ref_function(func_id)) 10481 regs[BPF_REG_0].dynptr_id = meta.dynptr_id; 10482 10483 if (is_ptr_cast_function(func_id) || is_dynptr_ref_function(func_id)) { 10484 /* For release_reference() */ 10485 regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id; 10486 } else if (is_acquire_function(func_id, meta.map_ptr)) { 10487 int id = acquire_reference_state(env, insn_idx); 10488 10489 if (id < 0) 10490 return id; 10491 /* For mark_ptr_or_null_reg() */ 10492 regs[BPF_REG_0].id = id; 10493 /* For release_reference() */ 10494 regs[BPF_REG_0].ref_obj_id = id; 10495 } 10496 10497 do_refine_retval_range(regs, fn->ret_type, func_id, &meta); 10498 10499 err = check_map_func_compatibility(env, meta.map_ptr, func_id); 10500 if (err) 10501 return err; 10502 10503 if ((func_id == BPF_FUNC_get_stack || 10504 func_id == BPF_FUNC_get_task_stack) && 10505 !env->prog->has_callchain_buf) { 10506 const char *err_str; 10507 10508 #ifdef CONFIG_PERF_EVENTS 10509 err = get_callchain_buffers(sysctl_perf_event_max_stack); 10510 err_str = "cannot get callchain buffer for func %s#%d\n"; 10511 #else 10512 err = -ENOTSUPP; 10513 err_str = "func %s#%d not supported without CONFIG_PERF_EVENTS\n"; 10514 #endif 10515 if (err) { 10516 verbose(env, err_str, func_id_name(func_id), func_id); 10517 return err; 10518 } 10519 10520 env->prog->has_callchain_buf = true; 10521 } 10522 10523 if (func_id == BPF_FUNC_get_stackid || func_id == BPF_FUNC_get_stack) 10524 env->prog->call_get_stack = true; 10525 10526 if (func_id == BPF_FUNC_get_func_ip) { 10527 if (check_get_func_ip(env)) 10528 return -ENOTSUPP; 10529 env->prog->call_get_func_ip = true; 10530 } 10531 10532 if (changes_data) 10533 clear_all_pkt_pointers(env); 10534 return 0; 10535 } 10536 10537 /* mark_btf_func_reg_size() is used when the reg size is determined by 10538 * the BTF func_proto's return value size and argument. 10539 */ 10540 static void mark_btf_func_reg_size(struct bpf_verifier_env *env, u32 regno, 10541 size_t reg_size) 10542 { 10543 struct bpf_reg_state *reg = &cur_regs(env)[regno]; 10544 10545 if (regno == BPF_REG_0) { 10546 /* Function return value */ 10547 reg->live |= REG_LIVE_WRITTEN; 10548 reg->subreg_def = reg_size == sizeof(u64) ? 10549 DEF_NOT_SUBREG : env->insn_idx + 1; 10550 } else { 10551 /* Function argument */ 10552 if (reg_size == sizeof(u64)) { 10553 mark_insn_zext(env, reg); 10554 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64); 10555 } else { 10556 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ32); 10557 } 10558 } 10559 } 10560 10561 static bool is_kfunc_acquire(struct bpf_kfunc_call_arg_meta *meta) 10562 { 10563 return meta->kfunc_flags & KF_ACQUIRE; 10564 } 10565 10566 static bool is_kfunc_release(struct bpf_kfunc_call_arg_meta *meta) 10567 { 10568 return meta->kfunc_flags & KF_RELEASE; 10569 } 10570 10571 static bool is_kfunc_trusted_args(struct bpf_kfunc_call_arg_meta *meta) 10572 { 10573 return (meta->kfunc_flags & KF_TRUSTED_ARGS) || is_kfunc_release(meta); 10574 } 10575 10576 static bool is_kfunc_sleepable(struct bpf_kfunc_call_arg_meta *meta) 10577 { 10578 return meta->kfunc_flags & KF_SLEEPABLE; 10579 } 10580 10581 static bool is_kfunc_destructive(struct bpf_kfunc_call_arg_meta *meta) 10582 { 10583 return meta->kfunc_flags & KF_DESTRUCTIVE; 10584 } 10585 10586 static bool is_kfunc_rcu(struct bpf_kfunc_call_arg_meta *meta) 10587 { 10588 return meta->kfunc_flags & KF_RCU; 10589 } 10590 10591 static bool is_kfunc_rcu_protected(struct bpf_kfunc_call_arg_meta *meta) 10592 { 10593 return meta->kfunc_flags & KF_RCU_PROTECTED; 10594 } 10595 10596 static bool __kfunc_param_match_suffix(const struct btf *btf, 10597 const struct btf_param *arg, 10598 const char *suffix) 10599 { 10600 int suffix_len = strlen(suffix), len; 10601 const char *param_name; 10602 10603 /* In the future, this can be ported to use BTF tagging */ 10604 param_name = btf_name_by_offset(btf, arg->name_off); 10605 if (str_is_empty(param_name)) 10606 return false; 10607 len = strlen(param_name); 10608 if (len < suffix_len) 10609 return false; 10610 param_name += len - suffix_len; 10611 return !strncmp(param_name, suffix, suffix_len); 10612 } 10613 10614 static bool is_kfunc_arg_mem_size(const struct btf *btf, 10615 const struct btf_param *arg, 10616 const struct bpf_reg_state *reg) 10617 { 10618 const struct btf_type *t; 10619 10620 t = btf_type_skip_modifiers(btf, arg->type, NULL); 10621 if (!btf_type_is_scalar(t) || reg->type != SCALAR_VALUE) 10622 return false; 10623 10624 return __kfunc_param_match_suffix(btf, arg, "__sz"); 10625 } 10626 10627 static bool is_kfunc_arg_const_mem_size(const struct btf *btf, 10628 const struct btf_param *arg, 10629 const struct bpf_reg_state *reg) 10630 { 10631 const struct btf_type *t; 10632 10633 t = btf_type_skip_modifiers(btf, arg->type, NULL); 10634 if (!btf_type_is_scalar(t) || reg->type != SCALAR_VALUE) 10635 return false; 10636 10637 return __kfunc_param_match_suffix(btf, arg, "__szk"); 10638 } 10639 10640 static bool is_kfunc_arg_optional(const struct btf *btf, const struct btf_param *arg) 10641 { 10642 return __kfunc_param_match_suffix(btf, arg, "__opt"); 10643 } 10644 10645 static bool is_kfunc_arg_constant(const struct btf *btf, const struct btf_param *arg) 10646 { 10647 return __kfunc_param_match_suffix(btf, arg, "__k"); 10648 } 10649 10650 static bool is_kfunc_arg_ignore(const struct btf *btf, const struct btf_param *arg) 10651 { 10652 return __kfunc_param_match_suffix(btf, arg, "__ign"); 10653 } 10654 10655 static bool is_kfunc_arg_alloc_obj(const struct btf *btf, const struct btf_param *arg) 10656 { 10657 return __kfunc_param_match_suffix(btf, arg, "__alloc"); 10658 } 10659 10660 static bool is_kfunc_arg_uninit(const struct btf *btf, const struct btf_param *arg) 10661 { 10662 return __kfunc_param_match_suffix(btf, arg, "__uninit"); 10663 } 10664 10665 static bool is_kfunc_arg_refcounted_kptr(const struct btf *btf, const struct btf_param *arg) 10666 { 10667 return __kfunc_param_match_suffix(btf, arg, "__refcounted_kptr"); 10668 } 10669 10670 static bool is_kfunc_arg_nullable(const struct btf *btf, const struct btf_param *arg) 10671 { 10672 return __kfunc_param_match_suffix(btf, arg, "__nullable"); 10673 } 10674 10675 static bool is_kfunc_arg_scalar_with_name(const struct btf *btf, 10676 const struct btf_param *arg, 10677 const char *name) 10678 { 10679 int len, target_len = strlen(name); 10680 const char *param_name; 10681 10682 param_name = btf_name_by_offset(btf, arg->name_off); 10683 if (str_is_empty(param_name)) 10684 return false; 10685 len = strlen(param_name); 10686 if (len != target_len) 10687 return false; 10688 if (strcmp(param_name, name)) 10689 return false; 10690 10691 return true; 10692 } 10693 10694 enum { 10695 KF_ARG_DYNPTR_ID, 10696 KF_ARG_LIST_HEAD_ID, 10697 KF_ARG_LIST_NODE_ID, 10698 KF_ARG_RB_ROOT_ID, 10699 KF_ARG_RB_NODE_ID, 10700 }; 10701 10702 BTF_ID_LIST(kf_arg_btf_ids) 10703 BTF_ID(struct, bpf_dynptr_kern) 10704 BTF_ID(struct, bpf_list_head) 10705 BTF_ID(struct, bpf_list_node) 10706 BTF_ID(struct, bpf_rb_root) 10707 BTF_ID(struct, bpf_rb_node) 10708 10709 static bool __is_kfunc_ptr_arg_type(const struct btf *btf, 10710 const struct btf_param *arg, int type) 10711 { 10712 const struct btf_type *t; 10713 u32 res_id; 10714 10715 t = btf_type_skip_modifiers(btf, arg->type, NULL); 10716 if (!t) 10717 return false; 10718 if (!btf_type_is_ptr(t)) 10719 return false; 10720 t = btf_type_skip_modifiers(btf, t->type, &res_id); 10721 if (!t) 10722 return false; 10723 return btf_types_are_same(btf, res_id, btf_vmlinux, kf_arg_btf_ids[type]); 10724 } 10725 10726 static bool is_kfunc_arg_dynptr(const struct btf *btf, const struct btf_param *arg) 10727 { 10728 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_DYNPTR_ID); 10729 } 10730 10731 static bool is_kfunc_arg_list_head(const struct btf *btf, const struct btf_param *arg) 10732 { 10733 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_LIST_HEAD_ID); 10734 } 10735 10736 static bool is_kfunc_arg_list_node(const struct btf *btf, const struct btf_param *arg) 10737 { 10738 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_LIST_NODE_ID); 10739 } 10740 10741 static bool is_kfunc_arg_rbtree_root(const struct btf *btf, const struct btf_param *arg) 10742 { 10743 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_RB_ROOT_ID); 10744 } 10745 10746 static bool is_kfunc_arg_rbtree_node(const struct btf *btf, const struct btf_param *arg) 10747 { 10748 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_RB_NODE_ID); 10749 } 10750 10751 static bool is_kfunc_arg_callback(struct bpf_verifier_env *env, const struct btf *btf, 10752 const struct btf_param *arg) 10753 { 10754 const struct btf_type *t; 10755 10756 t = btf_type_resolve_func_ptr(btf, arg->type, NULL); 10757 if (!t) 10758 return false; 10759 10760 return true; 10761 } 10762 10763 /* Returns true if struct is composed of scalars, 4 levels of nesting allowed */ 10764 static bool __btf_type_is_scalar_struct(struct bpf_verifier_env *env, 10765 const struct btf *btf, 10766 const struct btf_type *t, int rec) 10767 { 10768 const struct btf_type *member_type; 10769 const struct btf_member *member; 10770 u32 i; 10771 10772 if (!btf_type_is_struct(t)) 10773 return false; 10774 10775 for_each_member(i, t, member) { 10776 const struct btf_array *array; 10777 10778 member_type = btf_type_skip_modifiers(btf, member->type, NULL); 10779 if (btf_type_is_struct(member_type)) { 10780 if (rec >= 3) { 10781 verbose(env, "max struct nesting depth exceeded\n"); 10782 return false; 10783 } 10784 if (!__btf_type_is_scalar_struct(env, btf, member_type, rec + 1)) 10785 return false; 10786 continue; 10787 } 10788 if (btf_type_is_array(member_type)) { 10789 array = btf_array(member_type); 10790 if (!array->nelems) 10791 return false; 10792 member_type = btf_type_skip_modifiers(btf, array->type, NULL); 10793 if (!btf_type_is_scalar(member_type)) 10794 return false; 10795 continue; 10796 } 10797 if (!btf_type_is_scalar(member_type)) 10798 return false; 10799 } 10800 return true; 10801 } 10802 10803 enum kfunc_ptr_arg_type { 10804 KF_ARG_PTR_TO_CTX, 10805 KF_ARG_PTR_TO_ALLOC_BTF_ID, /* Allocated object */ 10806 KF_ARG_PTR_TO_REFCOUNTED_KPTR, /* Refcounted local kptr */ 10807 KF_ARG_PTR_TO_DYNPTR, 10808 KF_ARG_PTR_TO_ITER, 10809 KF_ARG_PTR_TO_LIST_HEAD, 10810 KF_ARG_PTR_TO_LIST_NODE, 10811 KF_ARG_PTR_TO_BTF_ID, /* Also covers reg2btf_ids conversions */ 10812 KF_ARG_PTR_TO_MEM, 10813 KF_ARG_PTR_TO_MEM_SIZE, /* Size derived from next argument, skip it */ 10814 KF_ARG_PTR_TO_CALLBACK, 10815 KF_ARG_PTR_TO_RB_ROOT, 10816 KF_ARG_PTR_TO_RB_NODE, 10817 KF_ARG_PTR_TO_NULL, 10818 }; 10819 10820 enum special_kfunc_type { 10821 KF_bpf_obj_new_impl, 10822 KF_bpf_obj_drop_impl, 10823 KF_bpf_refcount_acquire_impl, 10824 KF_bpf_list_push_front_impl, 10825 KF_bpf_list_push_back_impl, 10826 KF_bpf_list_pop_front, 10827 KF_bpf_list_pop_back, 10828 KF_bpf_cast_to_kern_ctx, 10829 KF_bpf_rdonly_cast, 10830 KF_bpf_rcu_read_lock, 10831 KF_bpf_rcu_read_unlock, 10832 KF_bpf_rbtree_remove, 10833 KF_bpf_rbtree_add_impl, 10834 KF_bpf_rbtree_first, 10835 KF_bpf_dynptr_from_skb, 10836 KF_bpf_dynptr_from_xdp, 10837 KF_bpf_dynptr_slice, 10838 KF_bpf_dynptr_slice_rdwr, 10839 KF_bpf_dynptr_clone, 10840 KF_bpf_percpu_obj_new_impl, 10841 KF_bpf_percpu_obj_drop_impl, 10842 KF_bpf_throw, 10843 KF_bpf_iter_css_task_new, 10844 }; 10845 10846 BTF_SET_START(special_kfunc_set) 10847 BTF_ID(func, bpf_obj_new_impl) 10848 BTF_ID(func, bpf_obj_drop_impl) 10849 BTF_ID(func, bpf_refcount_acquire_impl) 10850 BTF_ID(func, bpf_list_push_front_impl) 10851 BTF_ID(func, bpf_list_push_back_impl) 10852 BTF_ID(func, bpf_list_pop_front) 10853 BTF_ID(func, bpf_list_pop_back) 10854 BTF_ID(func, bpf_cast_to_kern_ctx) 10855 BTF_ID(func, bpf_rdonly_cast) 10856 BTF_ID(func, bpf_rbtree_remove) 10857 BTF_ID(func, bpf_rbtree_add_impl) 10858 BTF_ID(func, bpf_rbtree_first) 10859 BTF_ID(func, bpf_dynptr_from_skb) 10860 BTF_ID(func, bpf_dynptr_from_xdp) 10861 BTF_ID(func, bpf_dynptr_slice) 10862 BTF_ID(func, bpf_dynptr_slice_rdwr) 10863 BTF_ID(func, bpf_dynptr_clone) 10864 BTF_ID(func, bpf_percpu_obj_new_impl) 10865 BTF_ID(func, bpf_percpu_obj_drop_impl) 10866 BTF_ID(func, bpf_throw) 10867 #ifdef CONFIG_CGROUPS 10868 BTF_ID(func, bpf_iter_css_task_new) 10869 #endif 10870 BTF_SET_END(special_kfunc_set) 10871 10872 BTF_ID_LIST(special_kfunc_list) 10873 BTF_ID(func, bpf_obj_new_impl) 10874 BTF_ID(func, bpf_obj_drop_impl) 10875 BTF_ID(func, bpf_refcount_acquire_impl) 10876 BTF_ID(func, bpf_list_push_front_impl) 10877 BTF_ID(func, bpf_list_push_back_impl) 10878 BTF_ID(func, bpf_list_pop_front) 10879 BTF_ID(func, bpf_list_pop_back) 10880 BTF_ID(func, bpf_cast_to_kern_ctx) 10881 BTF_ID(func, bpf_rdonly_cast) 10882 BTF_ID(func, bpf_rcu_read_lock) 10883 BTF_ID(func, bpf_rcu_read_unlock) 10884 BTF_ID(func, bpf_rbtree_remove) 10885 BTF_ID(func, bpf_rbtree_add_impl) 10886 BTF_ID(func, bpf_rbtree_first) 10887 BTF_ID(func, bpf_dynptr_from_skb) 10888 BTF_ID(func, bpf_dynptr_from_xdp) 10889 BTF_ID(func, bpf_dynptr_slice) 10890 BTF_ID(func, bpf_dynptr_slice_rdwr) 10891 BTF_ID(func, bpf_dynptr_clone) 10892 BTF_ID(func, bpf_percpu_obj_new_impl) 10893 BTF_ID(func, bpf_percpu_obj_drop_impl) 10894 BTF_ID(func, bpf_throw) 10895 #ifdef CONFIG_CGROUPS 10896 BTF_ID(func, bpf_iter_css_task_new) 10897 #else 10898 BTF_ID_UNUSED 10899 #endif 10900 10901 static bool is_kfunc_ret_null(struct bpf_kfunc_call_arg_meta *meta) 10902 { 10903 if (meta->func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl] && 10904 meta->arg_owning_ref) { 10905 return false; 10906 } 10907 10908 return meta->kfunc_flags & KF_RET_NULL; 10909 } 10910 10911 static bool is_kfunc_bpf_rcu_read_lock(struct bpf_kfunc_call_arg_meta *meta) 10912 { 10913 return meta->func_id == special_kfunc_list[KF_bpf_rcu_read_lock]; 10914 } 10915 10916 static bool is_kfunc_bpf_rcu_read_unlock(struct bpf_kfunc_call_arg_meta *meta) 10917 { 10918 return meta->func_id == special_kfunc_list[KF_bpf_rcu_read_unlock]; 10919 } 10920 10921 static enum kfunc_ptr_arg_type 10922 get_kfunc_ptr_arg_type(struct bpf_verifier_env *env, 10923 struct bpf_kfunc_call_arg_meta *meta, 10924 const struct btf_type *t, const struct btf_type *ref_t, 10925 const char *ref_tname, const struct btf_param *args, 10926 int argno, int nargs) 10927 { 10928 u32 regno = argno + 1; 10929 struct bpf_reg_state *regs = cur_regs(env); 10930 struct bpf_reg_state *reg = ®s[regno]; 10931 bool arg_mem_size = false; 10932 10933 if (meta->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx]) 10934 return KF_ARG_PTR_TO_CTX; 10935 10936 /* In this function, we verify the kfunc's BTF as per the argument type, 10937 * leaving the rest of the verification with respect to the register 10938 * type to our caller. When a set of conditions hold in the BTF type of 10939 * arguments, we resolve it to a known kfunc_ptr_arg_type. 10940 */ 10941 if (btf_get_prog_ctx_type(&env->log, meta->btf, t, resolve_prog_type(env->prog), argno)) 10942 return KF_ARG_PTR_TO_CTX; 10943 10944 if (is_kfunc_arg_alloc_obj(meta->btf, &args[argno])) 10945 return KF_ARG_PTR_TO_ALLOC_BTF_ID; 10946 10947 if (is_kfunc_arg_refcounted_kptr(meta->btf, &args[argno])) 10948 return KF_ARG_PTR_TO_REFCOUNTED_KPTR; 10949 10950 if (is_kfunc_arg_dynptr(meta->btf, &args[argno])) 10951 return KF_ARG_PTR_TO_DYNPTR; 10952 10953 if (is_kfunc_arg_iter(meta, argno)) 10954 return KF_ARG_PTR_TO_ITER; 10955 10956 if (is_kfunc_arg_list_head(meta->btf, &args[argno])) 10957 return KF_ARG_PTR_TO_LIST_HEAD; 10958 10959 if (is_kfunc_arg_list_node(meta->btf, &args[argno])) 10960 return KF_ARG_PTR_TO_LIST_NODE; 10961 10962 if (is_kfunc_arg_rbtree_root(meta->btf, &args[argno])) 10963 return KF_ARG_PTR_TO_RB_ROOT; 10964 10965 if (is_kfunc_arg_rbtree_node(meta->btf, &args[argno])) 10966 return KF_ARG_PTR_TO_RB_NODE; 10967 10968 if ((base_type(reg->type) == PTR_TO_BTF_ID || reg2btf_ids[base_type(reg->type)])) { 10969 if (!btf_type_is_struct(ref_t)) { 10970 verbose(env, "kernel function %s args#%d pointer type %s %s is not supported\n", 10971 meta->func_name, argno, btf_type_str(ref_t), ref_tname); 10972 return -EINVAL; 10973 } 10974 return KF_ARG_PTR_TO_BTF_ID; 10975 } 10976 10977 if (is_kfunc_arg_callback(env, meta->btf, &args[argno])) 10978 return KF_ARG_PTR_TO_CALLBACK; 10979 10980 if (is_kfunc_arg_nullable(meta->btf, &args[argno]) && register_is_null(reg)) 10981 return KF_ARG_PTR_TO_NULL; 10982 10983 if (argno + 1 < nargs && 10984 (is_kfunc_arg_mem_size(meta->btf, &args[argno + 1], ®s[regno + 1]) || 10985 is_kfunc_arg_const_mem_size(meta->btf, &args[argno + 1], ®s[regno + 1]))) 10986 arg_mem_size = true; 10987 10988 /* This is the catch all argument type of register types supported by 10989 * check_helper_mem_access. However, we only allow when argument type is 10990 * pointer to scalar, or struct composed (recursively) of scalars. When 10991 * arg_mem_size is true, the pointer can be void *. 10992 */ 10993 if (!btf_type_is_scalar(ref_t) && !__btf_type_is_scalar_struct(env, meta->btf, ref_t, 0) && 10994 (arg_mem_size ? !btf_type_is_void(ref_t) : 1)) { 10995 verbose(env, "arg#%d pointer type %s %s must point to %sscalar, or struct with scalar\n", 10996 argno, btf_type_str(ref_t), ref_tname, arg_mem_size ? "void, " : ""); 10997 return -EINVAL; 10998 } 10999 return arg_mem_size ? KF_ARG_PTR_TO_MEM_SIZE : KF_ARG_PTR_TO_MEM; 11000 } 11001 11002 static int process_kf_arg_ptr_to_btf_id(struct bpf_verifier_env *env, 11003 struct bpf_reg_state *reg, 11004 const struct btf_type *ref_t, 11005 const char *ref_tname, u32 ref_id, 11006 struct bpf_kfunc_call_arg_meta *meta, 11007 int argno) 11008 { 11009 const struct btf_type *reg_ref_t; 11010 bool strict_type_match = false; 11011 const struct btf *reg_btf; 11012 const char *reg_ref_tname; 11013 u32 reg_ref_id; 11014 11015 if (base_type(reg->type) == PTR_TO_BTF_ID) { 11016 reg_btf = reg->btf; 11017 reg_ref_id = reg->btf_id; 11018 } else { 11019 reg_btf = btf_vmlinux; 11020 reg_ref_id = *reg2btf_ids[base_type(reg->type)]; 11021 } 11022 11023 /* Enforce strict type matching for calls to kfuncs that are acquiring 11024 * or releasing a reference, or are no-cast aliases. We do _not_ 11025 * enforce strict matching for plain KF_TRUSTED_ARGS kfuncs by default, 11026 * as we want to enable BPF programs to pass types that are bitwise 11027 * equivalent without forcing them to explicitly cast with something 11028 * like bpf_cast_to_kern_ctx(). 11029 * 11030 * For example, say we had a type like the following: 11031 * 11032 * struct bpf_cpumask { 11033 * cpumask_t cpumask; 11034 * refcount_t usage; 11035 * }; 11036 * 11037 * Note that as specified in <linux/cpumask.h>, cpumask_t is typedef'ed 11038 * to a struct cpumask, so it would be safe to pass a struct 11039 * bpf_cpumask * to a kfunc expecting a struct cpumask *. 11040 * 11041 * The philosophy here is similar to how we allow scalars of different 11042 * types to be passed to kfuncs as long as the size is the same. The 11043 * only difference here is that we're simply allowing 11044 * btf_struct_ids_match() to walk the struct at the 0th offset, and 11045 * resolve types. 11046 */ 11047 if (is_kfunc_acquire(meta) || 11048 (is_kfunc_release(meta) && reg->ref_obj_id) || 11049 btf_type_ids_nocast_alias(&env->log, reg_btf, reg_ref_id, meta->btf, ref_id)) 11050 strict_type_match = true; 11051 11052 WARN_ON_ONCE(is_kfunc_trusted_args(meta) && reg->off); 11053 11054 reg_ref_t = btf_type_skip_modifiers(reg_btf, reg_ref_id, ®_ref_id); 11055 reg_ref_tname = btf_name_by_offset(reg_btf, reg_ref_t->name_off); 11056 if (!btf_struct_ids_match(&env->log, reg_btf, reg_ref_id, reg->off, meta->btf, ref_id, strict_type_match)) { 11057 verbose(env, "kernel function %s args#%d expected pointer to %s %s but R%d has a pointer to %s %s\n", 11058 meta->func_name, argno, btf_type_str(ref_t), ref_tname, argno + 1, 11059 btf_type_str(reg_ref_t), reg_ref_tname); 11060 return -EINVAL; 11061 } 11062 return 0; 11063 } 11064 11065 static int ref_set_non_owning(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 11066 { 11067 struct bpf_verifier_state *state = env->cur_state; 11068 struct btf_record *rec = reg_btf_record(reg); 11069 11070 if (!state->active_lock.ptr) { 11071 verbose(env, "verifier internal error: ref_set_non_owning w/o active lock\n"); 11072 return -EFAULT; 11073 } 11074 11075 if (type_flag(reg->type) & NON_OWN_REF) { 11076 verbose(env, "verifier internal error: NON_OWN_REF already set\n"); 11077 return -EFAULT; 11078 } 11079 11080 reg->type |= NON_OWN_REF; 11081 if (rec->refcount_off >= 0) 11082 reg->type |= MEM_RCU; 11083 11084 return 0; 11085 } 11086 11087 static int ref_convert_owning_non_owning(struct bpf_verifier_env *env, u32 ref_obj_id) 11088 { 11089 struct bpf_func_state *state, *unused; 11090 struct bpf_reg_state *reg; 11091 int i; 11092 11093 state = cur_func(env); 11094 11095 if (!ref_obj_id) { 11096 verbose(env, "verifier internal error: ref_obj_id is zero for " 11097 "owning -> non-owning conversion\n"); 11098 return -EFAULT; 11099 } 11100 11101 for (i = 0; i < state->acquired_refs; i++) { 11102 if (state->refs[i].id != ref_obj_id) 11103 continue; 11104 11105 /* Clear ref_obj_id here so release_reference doesn't clobber 11106 * the whole reg 11107 */ 11108 bpf_for_each_reg_in_vstate(env->cur_state, unused, reg, ({ 11109 if (reg->ref_obj_id == ref_obj_id) { 11110 reg->ref_obj_id = 0; 11111 ref_set_non_owning(env, reg); 11112 } 11113 })); 11114 return 0; 11115 } 11116 11117 verbose(env, "verifier internal error: ref state missing for ref_obj_id\n"); 11118 return -EFAULT; 11119 } 11120 11121 /* Implementation details: 11122 * 11123 * Each register points to some region of memory, which we define as an 11124 * allocation. Each allocation may embed a bpf_spin_lock which protects any 11125 * special BPF objects (bpf_list_head, bpf_rb_root, etc.) part of the same 11126 * allocation. The lock and the data it protects are colocated in the same 11127 * memory region. 11128 * 11129 * Hence, everytime a register holds a pointer value pointing to such 11130 * allocation, the verifier preserves a unique reg->id for it. 11131 * 11132 * The verifier remembers the lock 'ptr' and the lock 'id' whenever 11133 * bpf_spin_lock is called. 11134 * 11135 * To enable this, lock state in the verifier captures two values: 11136 * active_lock.ptr = Register's type specific pointer 11137 * active_lock.id = A unique ID for each register pointer value 11138 * 11139 * Currently, PTR_TO_MAP_VALUE and PTR_TO_BTF_ID | MEM_ALLOC are the two 11140 * supported register types. 11141 * 11142 * The active_lock.ptr in case of map values is the reg->map_ptr, and in case of 11143 * allocated objects is the reg->btf pointer. 11144 * 11145 * The active_lock.id is non-unique for maps supporting direct_value_addr, as we 11146 * can establish the provenance of the map value statically for each distinct 11147 * lookup into such maps. They always contain a single map value hence unique 11148 * IDs for each pseudo load pessimizes the algorithm and rejects valid programs. 11149 * 11150 * So, in case of global variables, they use array maps with max_entries = 1, 11151 * hence their active_lock.ptr becomes map_ptr and id = 0 (since they all point 11152 * into the same map value as max_entries is 1, as described above). 11153 * 11154 * In case of inner map lookups, the inner map pointer has same map_ptr as the 11155 * outer map pointer (in verifier context), but each lookup into an inner map 11156 * assigns a fresh reg->id to the lookup, so while lookups into distinct inner 11157 * maps from the same outer map share the same map_ptr as active_lock.ptr, they 11158 * will get different reg->id assigned to each lookup, hence different 11159 * active_lock.id. 11160 * 11161 * In case of allocated objects, active_lock.ptr is the reg->btf, and the 11162 * reg->id is a unique ID preserved after the NULL pointer check on the pointer 11163 * returned from bpf_obj_new. Each allocation receives a new reg->id. 11164 */ 11165 static int check_reg_allocation_locked(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 11166 { 11167 void *ptr; 11168 u32 id; 11169 11170 switch ((int)reg->type) { 11171 case PTR_TO_MAP_VALUE: 11172 ptr = reg->map_ptr; 11173 break; 11174 case PTR_TO_BTF_ID | MEM_ALLOC: 11175 ptr = reg->btf; 11176 break; 11177 default: 11178 verbose(env, "verifier internal error: unknown reg type for lock check\n"); 11179 return -EFAULT; 11180 } 11181 id = reg->id; 11182 11183 if (!env->cur_state->active_lock.ptr) 11184 return -EINVAL; 11185 if (env->cur_state->active_lock.ptr != ptr || 11186 env->cur_state->active_lock.id != id) { 11187 verbose(env, "held lock and object are not in the same allocation\n"); 11188 return -EINVAL; 11189 } 11190 return 0; 11191 } 11192 11193 static bool is_bpf_list_api_kfunc(u32 btf_id) 11194 { 11195 return btf_id == special_kfunc_list[KF_bpf_list_push_front_impl] || 11196 btf_id == special_kfunc_list[KF_bpf_list_push_back_impl] || 11197 btf_id == special_kfunc_list[KF_bpf_list_pop_front] || 11198 btf_id == special_kfunc_list[KF_bpf_list_pop_back]; 11199 } 11200 11201 static bool is_bpf_rbtree_api_kfunc(u32 btf_id) 11202 { 11203 return btf_id == special_kfunc_list[KF_bpf_rbtree_add_impl] || 11204 btf_id == special_kfunc_list[KF_bpf_rbtree_remove] || 11205 btf_id == special_kfunc_list[KF_bpf_rbtree_first]; 11206 } 11207 11208 static bool is_bpf_graph_api_kfunc(u32 btf_id) 11209 { 11210 return is_bpf_list_api_kfunc(btf_id) || is_bpf_rbtree_api_kfunc(btf_id) || 11211 btf_id == special_kfunc_list[KF_bpf_refcount_acquire_impl]; 11212 } 11213 11214 static bool is_callback_calling_kfunc(u32 btf_id) 11215 { 11216 return btf_id == special_kfunc_list[KF_bpf_rbtree_add_impl]; 11217 } 11218 11219 static bool is_bpf_throw_kfunc(struct bpf_insn *insn) 11220 { 11221 return bpf_pseudo_kfunc_call(insn) && insn->off == 0 && 11222 insn->imm == special_kfunc_list[KF_bpf_throw]; 11223 } 11224 11225 static bool is_rbtree_lock_required_kfunc(u32 btf_id) 11226 { 11227 return is_bpf_rbtree_api_kfunc(btf_id); 11228 } 11229 11230 static bool check_kfunc_is_graph_root_api(struct bpf_verifier_env *env, 11231 enum btf_field_type head_field_type, 11232 u32 kfunc_btf_id) 11233 { 11234 bool ret; 11235 11236 switch (head_field_type) { 11237 case BPF_LIST_HEAD: 11238 ret = is_bpf_list_api_kfunc(kfunc_btf_id); 11239 break; 11240 case BPF_RB_ROOT: 11241 ret = is_bpf_rbtree_api_kfunc(kfunc_btf_id); 11242 break; 11243 default: 11244 verbose(env, "verifier internal error: unexpected graph root argument type %s\n", 11245 btf_field_type_name(head_field_type)); 11246 return false; 11247 } 11248 11249 if (!ret) 11250 verbose(env, "verifier internal error: %s head arg for unknown kfunc\n", 11251 btf_field_type_name(head_field_type)); 11252 return ret; 11253 } 11254 11255 static bool check_kfunc_is_graph_node_api(struct bpf_verifier_env *env, 11256 enum btf_field_type node_field_type, 11257 u32 kfunc_btf_id) 11258 { 11259 bool ret; 11260 11261 switch (node_field_type) { 11262 case BPF_LIST_NODE: 11263 ret = (kfunc_btf_id == special_kfunc_list[KF_bpf_list_push_front_impl] || 11264 kfunc_btf_id == special_kfunc_list[KF_bpf_list_push_back_impl]); 11265 break; 11266 case BPF_RB_NODE: 11267 ret = (kfunc_btf_id == special_kfunc_list[KF_bpf_rbtree_remove] || 11268 kfunc_btf_id == special_kfunc_list[KF_bpf_rbtree_add_impl]); 11269 break; 11270 default: 11271 verbose(env, "verifier internal error: unexpected graph node argument type %s\n", 11272 btf_field_type_name(node_field_type)); 11273 return false; 11274 } 11275 11276 if (!ret) 11277 verbose(env, "verifier internal error: %s node arg for unknown kfunc\n", 11278 btf_field_type_name(node_field_type)); 11279 return ret; 11280 } 11281 11282 static int 11283 __process_kf_arg_ptr_to_graph_root(struct bpf_verifier_env *env, 11284 struct bpf_reg_state *reg, u32 regno, 11285 struct bpf_kfunc_call_arg_meta *meta, 11286 enum btf_field_type head_field_type, 11287 struct btf_field **head_field) 11288 { 11289 const char *head_type_name; 11290 struct btf_field *field; 11291 struct btf_record *rec; 11292 u32 head_off; 11293 11294 if (meta->btf != btf_vmlinux) { 11295 verbose(env, "verifier internal error: unexpected btf mismatch in kfunc call\n"); 11296 return -EFAULT; 11297 } 11298 11299 if (!check_kfunc_is_graph_root_api(env, head_field_type, meta->func_id)) 11300 return -EFAULT; 11301 11302 head_type_name = btf_field_type_name(head_field_type); 11303 if (!tnum_is_const(reg->var_off)) { 11304 verbose(env, 11305 "R%d doesn't have constant offset. %s has to be at the constant offset\n", 11306 regno, head_type_name); 11307 return -EINVAL; 11308 } 11309 11310 rec = reg_btf_record(reg); 11311 head_off = reg->off + reg->var_off.value; 11312 field = btf_record_find(rec, head_off, head_field_type); 11313 if (!field) { 11314 verbose(env, "%s not found at offset=%u\n", head_type_name, head_off); 11315 return -EINVAL; 11316 } 11317 11318 /* All functions require bpf_list_head to be protected using a bpf_spin_lock */ 11319 if (check_reg_allocation_locked(env, reg)) { 11320 verbose(env, "bpf_spin_lock at off=%d must be held for %s\n", 11321 rec->spin_lock_off, head_type_name); 11322 return -EINVAL; 11323 } 11324 11325 if (*head_field) { 11326 verbose(env, "verifier internal error: repeating %s arg\n", head_type_name); 11327 return -EFAULT; 11328 } 11329 *head_field = field; 11330 return 0; 11331 } 11332 11333 static int process_kf_arg_ptr_to_list_head(struct bpf_verifier_env *env, 11334 struct bpf_reg_state *reg, u32 regno, 11335 struct bpf_kfunc_call_arg_meta *meta) 11336 { 11337 return __process_kf_arg_ptr_to_graph_root(env, reg, regno, meta, BPF_LIST_HEAD, 11338 &meta->arg_list_head.field); 11339 } 11340 11341 static int process_kf_arg_ptr_to_rbtree_root(struct bpf_verifier_env *env, 11342 struct bpf_reg_state *reg, u32 regno, 11343 struct bpf_kfunc_call_arg_meta *meta) 11344 { 11345 return __process_kf_arg_ptr_to_graph_root(env, reg, regno, meta, BPF_RB_ROOT, 11346 &meta->arg_rbtree_root.field); 11347 } 11348 11349 static int 11350 __process_kf_arg_ptr_to_graph_node(struct bpf_verifier_env *env, 11351 struct bpf_reg_state *reg, u32 regno, 11352 struct bpf_kfunc_call_arg_meta *meta, 11353 enum btf_field_type head_field_type, 11354 enum btf_field_type node_field_type, 11355 struct btf_field **node_field) 11356 { 11357 const char *node_type_name; 11358 const struct btf_type *et, *t; 11359 struct btf_field *field; 11360 u32 node_off; 11361 11362 if (meta->btf != btf_vmlinux) { 11363 verbose(env, "verifier internal error: unexpected btf mismatch in kfunc call\n"); 11364 return -EFAULT; 11365 } 11366 11367 if (!check_kfunc_is_graph_node_api(env, node_field_type, meta->func_id)) 11368 return -EFAULT; 11369 11370 node_type_name = btf_field_type_name(node_field_type); 11371 if (!tnum_is_const(reg->var_off)) { 11372 verbose(env, 11373 "R%d doesn't have constant offset. %s has to be at the constant offset\n", 11374 regno, node_type_name); 11375 return -EINVAL; 11376 } 11377 11378 node_off = reg->off + reg->var_off.value; 11379 field = reg_find_field_offset(reg, node_off, node_field_type); 11380 if (!field || field->offset != node_off) { 11381 verbose(env, "%s not found at offset=%u\n", node_type_name, node_off); 11382 return -EINVAL; 11383 } 11384 11385 field = *node_field; 11386 11387 et = btf_type_by_id(field->graph_root.btf, field->graph_root.value_btf_id); 11388 t = btf_type_by_id(reg->btf, reg->btf_id); 11389 if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, 0, field->graph_root.btf, 11390 field->graph_root.value_btf_id, true)) { 11391 verbose(env, "operation on %s expects arg#1 %s at offset=%d " 11392 "in struct %s, but arg is at offset=%d in struct %s\n", 11393 btf_field_type_name(head_field_type), 11394 btf_field_type_name(node_field_type), 11395 field->graph_root.node_offset, 11396 btf_name_by_offset(field->graph_root.btf, et->name_off), 11397 node_off, btf_name_by_offset(reg->btf, t->name_off)); 11398 return -EINVAL; 11399 } 11400 meta->arg_btf = reg->btf; 11401 meta->arg_btf_id = reg->btf_id; 11402 11403 if (node_off != field->graph_root.node_offset) { 11404 verbose(env, "arg#1 offset=%d, but expected %s at offset=%d in struct %s\n", 11405 node_off, btf_field_type_name(node_field_type), 11406 field->graph_root.node_offset, 11407 btf_name_by_offset(field->graph_root.btf, et->name_off)); 11408 return -EINVAL; 11409 } 11410 11411 return 0; 11412 } 11413 11414 static int process_kf_arg_ptr_to_list_node(struct bpf_verifier_env *env, 11415 struct bpf_reg_state *reg, u32 regno, 11416 struct bpf_kfunc_call_arg_meta *meta) 11417 { 11418 return __process_kf_arg_ptr_to_graph_node(env, reg, regno, meta, 11419 BPF_LIST_HEAD, BPF_LIST_NODE, 11420 &meta->arg_list_head.field); 11421 } 11422 11423 static int process_kf_arg_ptr_to_rbtree_node(struct bpf_verifier_env *env, 11424 struct bpf_reg_state *reg, u32 regno, 11425 struct bpf_kfunc_call_arg_meta *meta) 11426 { 11427 return __process_kf_arg_ptr_to_graph_node(env, reg, regno, meta, 11428 BPF_RB_ROOT, BPF_RB_NODE, 11429 &meta->arg_rbtree_root.field); 11430 } 11431 11432 /* 11433 * css_task iter allowlist is needed to avoid dead locking on css_set_lock. 11434 * LSM hooks and iters (both sleepable and non-sleepable) are safe. 11435 * Any sleepable progs are also safe since bpf_check_attach_target() enforce 11436 * them can only be attached to some specific hook points. 11437 */ 11438 static bool check_css_task_iter_allowlist(struct bpf_verifier_env *env) 11439 { 11440 enum bpf_prog_type prog_type = resolve_prog_type(env->prog); 11441 11442 switch (prog_type) { 11443 case BPF_PROG_TYPE_LSM: 11444 return true; 11445 case BPF_PROG_TYPE_TRACING: 11446 if (env->prog->expected_attach_type == BPF_TRACE_ITER) 11447 return true; 11448 fallthrough; 11449 default: 11450 return env->prog->aux->sleepable; 11451 } 11452 } 11453 11454 static int check_kfunc_args(struct bpf_verifier_env *env, struct bpf_kfunc_call_arg_meta *meta, 11455 int insn_idx) 11456 { 11457 const char *func_name = meta->func_name, *ref_tname; 11458 const struct btf *btf = meta->btf; 11459 const struct btf_param *args; 11460 struct btf_record *rec; 11461 u32 i, nargs; 11462 int ret; 11463 11464 args = (const struct btf_param *)(meta->func_proto + 1); 11465 nargs = btf_type_vlen(meta->func_proto); 11466 if (nargs > MAX_BPF_FUNC_REG_ARGS) { 11467 verbose(env, "Function %s has %d > %d args\n", func_name, nargs, 11468 MAX_BPF_FUNC_REG_ARGS); 11469 return -EINVAL; 11470 } 11471 11472 /* Check that BTF function arguments match actual types that the 11473 * verifier sees. 11474 */ 11475 for (i = 0; i < nargs; i++) { 11476 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[i + 1]; 11477 const struct btf_type *t, *ref_t, *resolve_ret; 11478 enum bpf_arg_type arg_type = ARG_DONTCARE; 11479 u32 regno = i + 1, ref_id, type_size; 11480 bool is_ret_buf_sz = false; 11481 int kf_arg_type; 11482 11483 t = btf_type_skip_modifiers(btf, args[i].type, NULL); 11484 11485 if (is_kfunc_arg_ignore(btf, &args[i])) 11486 continue; 11487 11488 if (btf_type_is_scalar(t)) { 11489 if (reg->type != SCALAR_VALUE) { 11490 verbose(env, "R%d is not a scalar\n", regno); 11491 return -EINVAL; 11492 } 11493 11494 if (is_kfunc_arg_constant(meta->btf, &args[i])) { 11495 if (meta->arg_constant.found) { 11496 verbose(env, "verifier internal error: only one constant argument permitted\n"); 11497 return -EFAULT; 11498 } 11499 if (!tnum_is_const(reg->var_off)) { 11500 verbose(env, "R%d must be a known constant\n", regno); 11501 return -EINVAL; 11502 } 11503 ret = mark_chain_precision(env, regno); 11504 if (ret < 0) 11505 return ret; 11506 meta->arg_constant.found = true; 11507 meta->arg_constant.value = reg->var_off.value; 11508 } else if (is_kfunc_arg_scalar_with_name(btf, &args[i], "rdonly_buf_size")) { 11509 meta->r0_rdonly = true; 11510 is_ret_buf_sz = true; 11511 } else if (is_kfunc_arg_scalar_with_name(btf, &args[i], "rdwr_buf_size")) { 11512 is_ret_buf_sz = true; 11513 } 11514 11515 if (is_ret_buf_sz) { 11516 if (meta->r0_size) { 11517 verbose(env, "2 or more rdonly/rdwr_buf_size parameters for kfunc"); 11518 return -EINVAL; 11519 } 11520 11521 if (!tnum_is_const(reg->var_off)) { 11522 verbose(env, "R%d is not a const\n", regno); 11523 return -EINVAL; 11524 } 11525 11526 meta->r0_size = reg->var_off.value; 11527 ret = mark_chain_precision(env, regno); 11528 if (ret) 11529 return ret; 11530 } 11531 continue; 11532 } 11533 11534 if (!btf_type_is_ptr(t)) { 11535 verbose(env, "Unrecognized arg#%d type %s\n", i, btf_type_str(t)); 11536 return -EINVAL; 11537 } 11538 11539 if ((is_kfunc_trusted_args(meta) || is_kfunc_rcu(meta)) && 11540 (register_is_null(reg) || type_may_be_null(reg->type)) && 11541 !is_kfunc_arg_nullable(meta->btf, &args[i])) { 11542 verbose(env, "Possibly NULL pointer passed to trusted arg%d\n", i); 11543 return -EACCES; 11544 } 11545 11546 if (reg->ref_obj_id) { 11547 if (is_kfunc_release(meta) && meta->ref_obj_id) { 11548 verbose(env, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n", 11549 regno, reg->ref_obj_id, 11550 meta->ref_obj_id); 11551 return -EFAULT; 11552 } 11553 meta->ref_obj_id = reg->ref_obj_id; 11554 if (is_kfunc_release(meta)) 11555 meta->release_regno = regno; 11556 } 11557 11558 ref_t = btf_type_skip_modifiers(btf, t->type, &ref_id); 11559 ref_tname = btf_name_by_offset(btf, ref_t->name_off); 11560 11561 kf_arg_type = get_kfunc_ptr_arg_type(env, meta, t, ref_t, ref_tname, args, i, nargs); 11562 if (kf_arg_type < 0) 11563 return kf_arg_type; 11564 11565 switch (kf_arg_type) { 11566 case KF_ARG_PTR_TO_NULL: 11567 continue; 11568 case KF_ARG_PTR_TO_ALLOC_BTF_ID: 11569 case KF_ARG_PTR_TO_BTF_ID: 11570 if (!is_kfunc_trusted_args(meta) && !is_kfunc_rcu(meta)) 11571 break; 11572 11573 if (!is_trusted_reg(reg)) { 11574 if (!is_kfunc_rcu(meta)) { 11575 verbose(env, "R%d must be referenced or trusted\n", regno); 11576 return -EINVAL; 11577 } 11578 if (!is_rcu_reg(reg)) { 11579 verbose(env, "R%d must be a rcu pointer\n", regno); 11580 return -EINVAL; 11581 } 11582 } 11583 11584 fallthrough; 11585 case KF_ARG_PTR_TO_CTX: 11586 /* Trusted arguments have the same offset checks as release arguments */ 11587 arg_type |= OBJ_RELEASE; 11588 break; 11589 case KF_ARG_PTR_TO_DYNPTR: 11590 case KF_ARG_PTR_TO_ITER: 11591 case KF_ARG_PTR_TO_LIST_HEAD: 11592 case KF_ARG_PTR_TO_LIST_NODE: 11593 case KF_ARG_PTR_TO_RB_ROOT: 11594 case KF_ARG_PTR_TO_RB_NODE: 11595 case KF_ARG_PTR_TO_MEM: 11596 case KF_ARG_PTR_TO_MEM_SIZE: 11597 case KF_ARG_PTR_TO_CALLBACK: 11598 case KF_ARG_PTR_TO_REFCOUNTED_KPTR: 11599 /* Trusted by default */ 11600 break; 11601 default: 11602 WARN_ON_ONCE(1); 11603 return -EFAULT; 11604 } 11605 11606 if (is_kfunc_release(meta) && reg->ref_obj_id) 11607 arg_type |= OBJ_RELEASE; 11608 ret = check_func_arg_reg_off(env, reg, regno, arg_type); 11609 if (ret < 0) 11610 return ret; 11611 11612 switch (kf_arg_type) { 11613 case KF_ARG_PTR_TO_CTX: 11614 if (reg->type != PTR_TO_CTX) { 11615 verbose(env, "arg#%d expected pointer to ctx, but got %s\n", i, btf_type_str(t)); 11616 return -EINVAL; 11617 } 11618 11619 if (meta->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx]) { 11620 ret = get_kern_ctx_btf_id(&env->log, resolve_prog_type(env->prog)); 11621 if (ret < 0) 11622 return -EINVAL; 11623 meta->ret_btf_id = ret; 11624 } 11625 break; 11626 case KF_ARG_PTR_TO_ALLOC_BTF_ID: 11627 if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC)) { 11628 if (meta->func_id != special_kfunc_list[KF_bpf_obj_drop_impl]) { 11629 verbose(env, "arg#%d expected for bpf_obj_drop_impl()\n", i); 11630 return -EINVAL; 11631 } 11632 } else if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC | MEM_PERCPU)) { 11633 if (meta->func_id != special_kfunc_list[KF_bpf_percpu_obj_drop_impl]) { 11634 verbose(env, "arg#%d expected for bpf_percpu_obj_drop_impl()\n", i); 11635 return -EINVAL; 11636 } 11637 } else { 11638 verbose(env, "arg#%d expected pointer to allocated object\n", i); 11639 return -EINVAL; 11640 } 11641 if (!reg->ref_obj_id) { 11642 verbose(env, "allocated object must be referenced\n"); 11643 return -EINVAL; 11644 } 11645 if (meta->btf == btf_vmlinux) { 11646 meta->arg_btf = reg->btf; 11647 meta->arg_btf_id = reg->btf_id; 11648 } 11649 break; 11650 case KF_ARG_PTR_TO_DYNPTR: 11651 { 11652 enum bpf_arg_type dynptr_arg_type = ARG_PTR_TO_DYNPTR; 11653 int clone_ref_obj_id = 0; 11654 11655 if (reg->type != PTR_TO_STACK && 11656 reg->type != CONST_PTR_TO_DYNPTR) { 11657 verbose(env, "arg#%d expected pointer to stack or dynptr_ptr\n", i); 11658 return -EINVAL; 11659 } 11660 11661 if (reg->type == CONST_PTR_TO_DYNPTR) 11662 dynptr_arg_type |= MEM_RDONLY; 11663 11664 if (is_kfunc_arg_uninit(btf, &args[i])) 11665 dynptr_arg_type |= MEM_UNINIT; 11666 11667 if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_from_skb]) { 11668 dynptr_arg_type |= DYNPTR_TYPE_SKB; 11669 } else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_from_xdp]) { 11670 dynptr_arg_type |= DYNPTR_TYPE_XDP; 11671 } else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_clone] && 11672 (dynptr_arg_type & MEM_UNINIT)) { 11673 enum bpf_dynptr_type parent_type = meta->initialized_dynptr.type; 11674 11675 if (parent_type == BPF_DYNPTR_TYPE_INVALID) { 11676 verbose(env, "verifier internal error: no dynptr type for parent of clone\n"); 11677 return -EFAULT; 11678 } 11679 11680 dynptr_arg_type |= (unsigned int)get_dynptr_type_flag(parent_type); 11681 clone_ref_obj_id = meta->initialized_dynptr.ref_obj_id; 11682 if (dynptr_type_refcounted(parent_type) && !clone_ref_obj_id) { 11683 verbose(env, "verifier internal error: missing ref obj id for parent of clone\n"); 11684 return -EFAULT; 11685 } 11686 } 11687 11688 ret = process_dynptr_func(env, regno, insn_idx, dynptr_arg_type, clone_ref_obj_id); 11689 if (ret < 0) 11690 return ret; 11691 11692 if (!(dynptr_arg_type & MEM_UNINIT)) { 11693 int id = dynptr_id(env, reg); 11694 11695 if (id < 0) { 11696 verbose(env, "verifier internal error: failed to obtain dynptr id\n"); 11697 return id; 11698 } 11699 meta->initialized_dynptr.id = id; 11700 meta->initialized_dynptr.type = dynptr_get_type(env, reg); 11701 meta->initialized_dynptr.ref_obj_id = dynptr_ref_obj_id(env, reg); 11702 } 11703 11704 break; 11705 } 11706 case KF_ARG_PTR_TO_ITER: 11707 if (meta->func_id == special_kfunc_list[KF_bpf_iter_css_task_new]) { 11708 if (!check_css_task_iter_allowlist(env)) { 11709 verbose(env, "css_task_iter is only allowed in bpf_lsm, bpf_iter and sleepable progs\n"); 11710 return -EINVAL; 11711 } 11712 } 11713 ret = process_iter_arg(env, regno, insn_idx, meta); 11714 if (ret < 0) 11715 return ret; 11716 break; 11717 case KF_ARG_PTR_TO_LIST_HEAD: 11718 if (reg->type != PTR_TO_MAP_VALUE && 11719 reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) { 11720 verbose(env, "arg#%d expected pointer to map value or allocated object\n", i); 11721 return -EINVAL; 11722 } 11723 if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC) && !reg->ref_obj_id) { 11724 verbose(env, "allocated object must be referenced\n"); 11725 return -EINVAL; 11726 } 11727 ret = process_kf_arg_ptr_to_list_head(env, reg, regno, meta); 11728 if (ret < 0) 11729 return ret; 11730 break; 11731 case KF_ARG_PTR_TO_RB_ROOT: 11732 if (reg->type != PTR_TO_MAP_VALUE && 11733 reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) { 11734 verbose(env, "arg#%d expected pointer to map value or allocated object\n", i); 11735 return -EINVAL; 11736 } 11737 if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC) && !reg->ref_obj_id) { 11738 verbose(env, "allocated object must be referenced\n"); 11739 return -EINVAL; 11740 } 11741 ret = process_kf_arg_ptr_to_rbtree_root(env, reg, regno, meta); 11742 if (ret < 0) 11743 return ret; 11744 break; 11745 case KF_ARG_PTR_TO_LIST_NODE: 11746 if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) { 11747 verbose(env, "arg#%d expected pointer to allocated object\n", i); 11748 return -EINVAL; 11749 } 11750 if (!reg->ref_obj_id) { 11751 verbose(env, "allocated object must be referenced\n"); 11752 return -EINVAL; 11753 } 11754 ret = process_kf_arg_ptr_to_list_node(env, reg, regno, meta); 11755 if (ret < 0) 11756 return ret; 11757 break; 11758 case KF_ARG_PTR_TO_RB_NODE: 11759 if (meta->func_id == special_kfunc_list[KF_bpf_rbtree_remove]) { 11760 if (!type_is_non_owning_ref(reg->type) || reg->ref_obj_id) { 11761 verbose(env, "rbtree_remove node input must be non-owning ref\n"); 11762 return -EINVAL; 11763 } 11764 if (in_rbtree_lock_required_cb(env)) { 11765 verbose(env, "rbtree_remove not allowed in rbtree cb\n"); 11766 return -EINVAL; 11767 } 11768 } else { 11769 if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) { 11770 verbose(env, "arg#%d expected pointer to allocated object\n", i); 11771 return -EINVAL; 11772 } 11773 if (!reg->ref_obj_id) { 11774 verbose(env, "allocated object must be referenced\n"); 11775 return -EINVAL; 11776 } 11777 } 11778 11779 ret = process_kf_arg_ptr_to_rbtree_node(env, reg, regno, meta); 11780 if (ret < 0) 11781 return ret; 11782 break; 11783 case KF_ARG_PTR_TO_BTF_ID: 11784 /* Only base_type is checked, further checks are done here */ 11785 if ((base_type(reg->type) != PTR_TO_BTF_ID || 11786 (bpf_type_has_unsafe_modifiers(reg->type) && !is_rcu_reg(reg))) && 11787 !reg2btf_ids[base_type(reg->type)]) { 11788 verbose(env, "arg#%d is %s ", i, reg_type_str(env, reg->type)); 11789 verbose(env, "expected %s or socket\n", 11790 reg_type_str(env, base_type(reg->type) | 11791 (type_flag(reg->type) & BPF_REG_TRUSTED_MODIFIERS))); 11792 return -EINVAL; 11793 } 11794 ret = process_kf_arg_ptr_to_btf_id(env, reg, ref_t, ref_tname, ref_id, meta, i); 11795 if (ret < 0) 11796 return ret; 11797 break; 11798 case KF_ARG_PTR_TO_MEM: 11799 resolve_ret = btf_resolve_size(btf, ref_t, &type_size); 11800 if (IS_ERR(resolve_ret)) { 11801 verbose(env, "arg#%d reference type('%s %s') size cannot be determined: %ld\n", 11802 i, btf_type_str(ref_t), ref_tname, PTR_ERR(resolve_ret)); 11803 return -EINVAL; 11804 } 11805 ret = check_mem_reg(env, reg, regno, type_size); 11806 if (ret < 0) 11807 return ret; 11808 break; 11809 case KF_ARG_PTR_TO_MEM_SIZE: 11810 { 11811 struct bpf_reg_state *buff_reg = ®s[regno]; 11812 const struct btf_param *buff_arg = &args[i]; 11813 struct bpf_reg_state *size_reg = ®s[regno + 1]; 11814 const struct btf_param *size_arg = &args[i + 1]; 11815 11816 if (!register_is_null(buff_reg) || !is_kfunc_arg_optional(meta->btf, buff_arg)) { 11817 ret = check_kfunc_mem_size_reg(env, size_reg, regno + 1); 11818 if (ret < 0) { 11819 verbose(env, "arg#%d arg#%d memory, len pair leads to invalid memory access\n", i, i + 1); 11820 return ret; 11821 } 11822 } 11823 11824 if (is_kfunc_arg_const_mem_size(meta->btf, size_arg, size_reg)) { 11825 if (meta->arg_constant.found) { 11826 verbose(env, "verifier internal error: only one constant argument permitted\n"); 11827 return -EFAULT; 11828 } 11829 if (!tnum_is_const(size_reg->var_off)) { 11830 verbose(env, "R%d must be a known constant\n", regno + 1); 11831 return -EINVAL; 11832 } 11833 meta->arg_constant.found = true; 11834 meta->arg_constant.value = size_reg->var_off.value; 11835 } 11836 11837 /* Skip next '__sz' or '__szk' argument */ 11838 i++; 11839 break; 11840 } 11841 case KF_ARG_PTR_TO_CALLBACK: 11842 if (reg->type != PTR_TO_FUNC) { 11843 verbose(env, "arg%d expected pointer to func\n", i); 11844 return -EINVAL; 11845 } 11846 meta->subprogno = reg->subprogno; 11847 break; 11848 case KF_ARG_PTR_TO_REFCOUNTED_KPTR: 11849 if (!type_is_ptr_alloc_obj(reg->type)) { 11850 verbose(env, "arg#%d is neither owning or non-owning ref\n", i); 11851 return -EINVAL; 11852 } 11853 if (!type_is_non_owning_ref(reg->type)) 11854 meta->arg_owning_ref = true; 11855 11856 rec = reg_btf_record(reg); 11857 if (!rec) { 11858 verbose(env, "verifier internal error: Couldn't find btf_record\n"); 11859 return -EFAULT; 11860 } 11861 11862 if (rec->refcount_off < 0) { 11863 verbose(env, "arg#%d doesn't point to a type with bpf_refcount field\n", i); 11864 return -EINVAL; 11865 } 11866 11867 meta->arg_btf = reg->btf; 11868 meta->arg_btf_id = reg->btf_id; 11869 break; 11870 } 11871 } 11872 11873 if (is_kfunc_release(meta) && !meta->release_regno) { 11874 verbose(env, "release kernel function %s expects refcounted PTR_TO_BTF_ID\n", 11875 func_name); 11876 return -EINVAL; 11877 } 11878 11879 return 0; 11880 } 11881 11882 static int fetch_kfunc_meta(struct bpf_verifier_env *env, 11883 struct bpf_insn *insn, 11884 struct bpf_kfunc_call_arg_meta *meta, 11885 const char **kfunc_name) 11886 { 11887 const struct btf_type *func, *func_proto; 11888 u32 func_id, *kfunc_flags; 11889 const char *func_name; 11890 struct btf *desc_btf; 11891 11892 if (kfunc_name) 11893 *kfunc_name = NULL; 11894 11895 if (!insn->imm) 11896 return -EINVAL; 11897 11898 desc_btf = find_kfunc_desc_btf(env, insn->off); 11899 if (IS_ERR(desc_btf)) 11900 return PTR_ERR(desc_btf); 11901 11902 func_id = insn->imm; 11903 func = btf_type_by_id(desc_btf, func_id); 11904 func_name = btf_name_by_offset(desc_btf, func->name_off); 11905 if (kfunc_name) 11906 *kfunc_name = func_name; 11907 func_proto = btf_type_by_id(desc_btf, func->type); 11908 11909 kfunc_flags = btf_kfunc_id_set_contains(desc_btf, func_id, env->prog); 11910 if (!kfunc_flags) { 11911 return -EACCES; 11912 } 11913 11914 memset(meta, 0, sizeof(*meta)); 11915 meta->btf = desc_btf; 11916 meta->func_id = func_id; 11917 meta->kfunc_flags = *kfunc_flags; 11918 meta->func_proto = func_proto; 11919 meta->func_name = func_name; 11920 11921 return 0; 11922 } 11923 11924 static int check_return_code(struct bpf_verifier_env *env, int regno); 11925 11926 static int check_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn, 11927 int *insn_idx_p) 11928 { 11929 const struct btf_type *t, *ptr_type; 11930 u32 i, nargs, ptr_type_id, release_ref_obj_id; 11931 struct bpf_reg_state *regs = cur_regs(env); 11932 const char *func_name, *ptr_type_name; 11933 bool sleepable, rcu_lock, rcu_unlock; 11934 struct bpf_kfunc_call_arg_meta meta; 11935 struct bpf_insn_aux_data *insn_aux; 11936 int err, insn_idx = *insn_idx_p; 11937 const struct btf_param *args; 11938 const struct btf_type *ret_t; 11939 struct btf *desc_btf; 11940 11941 /* skip for now, but return error when we find this in fixup_kfunc_call */ 11942 if (!insn->imm) 11943 return 0; 11944 11945 err = fetch_kfunc_meta(env, insn, &meta, &func_name); 11946 if (err == -EACCES && func_name) 11947 verbose(env, "calling kernel function %s is not allowed\n", func_name); 11948 if (err) 11949 return err; 11950 desc_btf = meta.btf; 11951 insn_aux = &env->insn_aux_data[insn_idx]; 11952 11953 insn_aux->is_iter_next = is_iter_next_kfunc(&meta); 11954 11955 if (is_kfunc_destructive(&meta) && !capable(CAP_SYS_BOOT)) { 11956 verbose(env, "destructive kfunc calls require CAP_SYS_BOOT capability\n"); 11957 return -EACCES; 11958 } 11959 11960 sleepable = is_kfunc_sleepable(&meta); 11961 if (sleepable && !env->prog->aux->sleepable) { 11962 verbose(env, "program must be sleepable to call sleepable kfunc %s\n", func_name); 11963 return -EACCES; 11964 } 11965 11966 rcu_lock = is_kfunc_bpf_rcu_read_lock(&meta); 11967 rcu_unlock = is_kfunc_bpf_rcu_read_unlock(&meta); 11968 11969 if (env->cur_state->active_rcu_lock) { 11970 struct bpf_func_state *state; 11971 struct bpf_reg_state *reg; 11972 u32 clear_mask = (1 << STACK_SPILL) | (1 << STACK_ITER); 11973 11974 if (in_rbtree_lock_required_cb(env) && (rcu_lock || rcu_unlock)) { 11975 verbose(env, "Calling bpf_rcu_read_{lock,unlock} in unnecessary rbtree callback\n"); 11976 return -EACCES; 11977 } 11978 11979 if (rcu_lock) { 11980 verbose(env, "nested rcu read lock (kernel function %s)\n", func_name); 11981 return -EINVAL; 11982 } else if (rcu_unlock) { 11983 bpf_for_each_reg_in_vstate_mask(env->cur_state, state, reg, clear_mask, ({ 11984 if (reg->type & MEM_RCU) { 11985 reg->type &= ~(MEM_RCU | PTR_MAYBE_NULL); 11986 reg->type |= PTR_UNTRUSTED; 11987 } 11988 })); 11989 env->cur_state->active_rcu_lock = false; 11990 } else if (sleepable) { 11991 verbose(env, "kernel func %s is sleepable within rcu_read_lock region\n", func_name); 11992 return -EACCES; 11993 } 11994 } else if (rcu_lock) { 11995 env->cur_state->active_rcu_lock = true; 11996 } else if (rcu_unlock) { 11997 verbose(env, "unmatched rcu read unlock (kernel function %s)\n", func_name); 11998 return -EINVAL; 11999 } 12000 12001 /* Check the arguments */ 12002 err = check_kfunc_args(env, &meta, insn_idx); 12003 if (err < 0) 12004 return err; 12005 /* In case of release function, we get register number of refcounted 12006 * PTR_TO_BTF_ID in bpf_kfunc_arg_meta, do the release now. 12007 */ 12008 if (meta.release_regno) { 12009 err = release_reference(env, regs[meta.release_regno].ref_obj_id); 12010 if (err) { 12011 verbose(env, "kfunc %s#%d reference has not been acquired before\n", 12012 func_name, meta.func_id); 12013 return err; 12014 } 12015 } 12016 12017 if (meta.func_id == special_kfunc_list[KF_bpf_list_push_front_impl] || 12018 meta.func_id == special_kfunc_list[KF_bpf_list_push_back_impl] || 12019 meta.func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) { 12020 release_ref_obj_id = regs[BPF_REG_2].ref_obj_id; 12021 insn_aux->insert_off = regs[BPF_REG_2].off; 12022 insn_aux->kptr_struct_meta = btf_find_struct_meta(meta.arg_btf, meta.arg_btf_id); 12023 err = ref_convert_owning_non_owning(env, release_ref_obj_id); 12024 if (err) { 12025 verbose(env, "kfunc %s#%d conversion of owning ref to non-owning failed\n", 12026 func_name, meta.func_id); 12027 return err; 12028 } 12029 12030 err = release_reference(env, release_ref_obj_id); 12031 if (err) { 12032 verbose(env, "kfunc %s#%d reference has not been acquired before\n", 12033 func_name, meta.func_id); 12034 return err; 12035 } 12036 } 12037 12038 if (meta.func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) { 12039 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno, 12040 set_rbtree_add_callback_state); 12041 if (err) { 12042 verbose(env, "kfunc %s#%d failed callback verification\n", 12043 func_name, meta.func_id); 12044 return err; 12045 } 12046 } 12047 12048 if (meta.func_id == special_kfunc_list[KF_bpf_throw]) { 12049 if (!bpf_jit_supports_exceptions()) { 12050 verbose(env, "JIT does not support calling kfunc %s#%d\n", 12051 func_name, meta.func_id); 12052 return -ENOTSUPP; 12053 } 12054 env->seen_exception = true; 12055 12056 /* In the case of the default callback, the cookie value passed 12057 * to bpf_throw becomes the return value of the program. 12058 */ 12059 if (!env->exception_callback_subprog) { 12060 err = check_return_code(env, BPF_REG_1); 12061 if (err < 0) 12062 return err; 12063 } 12064 } 12065 12066 for (i = 0; i < CALLER_SAVED_REGS; i++) 12067 mark_reg_not_init(env, regs, caller_saved[i]); 12068 12069 /* Check return type */ 12070 t = btf_type_skip_modifiers(desc_btf, meta.func_proto->type, NULL); 12071 12072 if (is_kfunc_acquire(&meta) && !btf_type_is_struct_ptr(meta.btf, t)) { 12073 /* Only exception is bpf_obj_new_impl */ 12074 if (meta.btf != btf_vmlinux || 12075 (meta.func_id != special_kfunc_list[KF_bpf_obj_new_impl] && 12076 meta.func_id != special_kfunc_list[KF_bpf_percpu_obj_new_impl] && 12077 meta.func_id != special_kfunc_list[KF_bpf_refcount_acquire_impl])) { 12078 verbose(env, "acquire kernel function does not return PTR_TO_BTF_ID\n"); 12079 return -EINVAL; 12080 } 12081 } 12082 12083 if (btf_type_is_scalar(t)) { 12084 mark_reg_unknown(env, regs, BPF_REG_0); 12085 mark_btf_func_reg_size(env, BPF_REG_0, t->size); 12086 } else if (btf_type_is_ptr(t)) { 12087 ptr_type = btf_type_skip_modifiers(desc_btf, t->type, &ptr_type_id); 12088 12089 if (meta.btf == btf_vmlinux && btf_id_set_contains(&special_kfunc_set, meta.func_id)) { 12090 if (meta.func_id == special_kfunc_list[KF_bpf_obj_new_impl] || 12091 meta.func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl]) { 12092 struct btf_struct_meta *struct_meta; 12093 struct btf *ret_btf; 12094 u32 ret_btf_id; 12095 12096 if (meta.func_id == special_kfunc_list[KF_bpf_obj_new_impl] && !bpf_global_ma_set) 12097 return -ENOMEM; 12098 12099 if (meta.func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl]) { 12100 if (!bpf_global_percpu_ma_set) { 12101 mutex_lock(&bpf_percpu_ma_lock); 12102 if (!bpf_global_percpu_ma_set) { 12103 err = bpf_mem_alloc_init(&bpf_global_percpu_ma, 0, true); 12104 if (!err) 12105 bpf_global_percpu_ma_set = true; 12106 } 12107 mutex_unlock(&bpf_percpu_ma_lock); 12108 if (err) 12109 return err; 12110 } 12111 } 12112 12113 if (((u64)(u32)meta.arg_constant.value) != meta.arg_constant.value) { 12114 verbose(env, "local type ID argument must be in range [0, U32_MAX]\n"); 12115 return -EINVAL; 12116 } 12117 12118 ret_btf = env->prog->aux->btf; 12119 ret_btf_id = meta.arg_constant.value; 12120 12121 /* This may be NULL due to user not supplying a BTF */ 12122 if (!ret_btf) { 12123 verbose(env, "bpf_obj_new/bpf_percpu_obj_new requires prog BTF\n"); 12124 return -EINVAL; 12125 } 12126 12127 ret_t = btf_type_by_id(ret_btf, ret_btf_id); 12128 if (!ret_t || !__btf_type_is_struct(ret_t)) { 12129 verbose(env, "bpf_obj_new/bpf_percpu_obj_new type ID argument must be of a struct\n"); 12130 return -EINVAL; 12131 } 12132 12133 struct_meta = btf_find_struct_meta(ret_btf, ret_btf_id); 12134 if (meta.func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl]) { 12135 if (!__btf_type_is_scalar_struct(env, ret_btf, ret_t, 0)) { 12136 verbose(env, "bpf_percpu_obj_new type ID argument must be of a struct of scalars\n"); 12137 return -EINVAL; 12138 } 12139 12140 if (struct_meta) { 12141 verbose(env, "bpf_percpu_obj_new type ID argument must not contain special fields\n"); 12142 return -EINVAL; 12143 } 12144 } 12145 12146 mark_reg_known_zero(env, regs, BPF_REG_0); 12147 regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC; 12148 regs[BPF_REG_0].btf = ret_btf; 12149 regs[BPF_REG_0].btf_id = ret_btf_id; 12150 if (meta.func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl]) 12151 regs[BPF_REG_0].type |= MEM_PERCPU; 12152 12153 insn_aux->obj_new_size = ret_t->size; 12154 insn_aux->kptr_struct_meta = struct_meta; 12155 } else if (meta.func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl]) { 12156 mark_reg_known_zero(env, regs, BPF_REG_0); 12157 regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC; 12158 regs[BPF_REG_0].btf = meta.arg_btf; 12159 regs[BPF_REG_0].btf_id = meta.arg_btf_id; 12160 12161 insn_aux->kptr_struct_meta = 12162 btf_find_struct_meta(meta.arg_btf, 12163 meta.arg_btf_id); 12164 } else if (meta.func_id == special_kfunc_list[KF_bpf_list_pop_front] || 12165 meta.func_id == special_kfunc_list[KF_bpf_list_pop_back]) { 12166 struct btf_field *field = meta.arg_list_head.field; 12167 12168 mark_reg_graph_node(regs, BPF_REG_0, &field->graph_root); 12169 } else if (meta.func_id == special_kfunc_list[KF_bpf_rbtree_remove] || 12170 meta.func_id == special_kfunc_list[KF_bpf_rbtree_first]) { 12171 struct btf_field *field = meta.arg_rbtree_root.field; 12172 12173 mark_reg_graph_node(regs, BPF_REG_0, &field->graph_root); 12174 } else if (meta.func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx]) { 12175 mark_reg_known_zero(env, regs, BPF_REG_0); 12176 regs[BPF_REG_0].type = PTR_TO_BTF_ID | PTR_TRUSTED; 12177 regs[BPF_REG_0].btf = desc_btf; 12178 regs[BPF_REG_0].btf_id = meta.ret_btf_id; 12179 } else if (meta.func_id == special_kfunc_list[KF_bpf_rdonly_cast]) { 12180 ret_t = btf_type_by_id(desc_btf, meta.arg_constant.value); 12181 if (!ret_t || !btf_type_is_struct(ret_t)) { 12182 verbose(env, 12183 "kfunc bpf_rdonly_cast type ID argument must be of a struct\n"); 12184 return -EINVAL; 12185 } 12186 12187 mark_reg_known_zero(env, regs, BPF_REG_0); 12188 regs[BPF_REG_0].type = PTR_TO_BTF_ID | PTR_UNTRUSTED; 12189 regs[BPF_REG_0].btf = desc_btf; 12190 regs[BPF_REG_0].btf_id = meta.arg_constant.value; 12191 } else if (meta.func_id == special_kfunc_list[KF_bpf_dynptr_slice] || 12192 meta.func_id == special_kfunc_list[KF_bpf_dynptr_slice_rdwr]) { 12193 enum bpf_type_flag type_flag = get_dynptr_type_flag(meta.initialized_dynptr.type); 12194 12195 mark_reg_known_zero(env, regs, BPF_REG_0); 12196 12197 if (!meta.arg_constant.found) { 12198 verbose(env, "verifier internal error: bpf_dynptr_slice(_rdwr) no constant size\n"); 12199 return -EFAULT; 12200 } 12201 12202 regs[BPF_REG_0].mem_size = meta.arg_constant.value; 12203 12204 /* PTR_MAYBE_NULL will be added when is_kfunc_ret_null is checked */ 12205 regs[BPF_REG_0].type = PTR_TO_MEM | type_flag; 12206 12207 if (meta.func_id == special_kfunc_list[KF_bpf_dynptr_slice]) { 12208 regs[BPF_REG_0].type |= MEM_RDONLY; 12209 } else { 12210 /* this will set env->seen_direct_write to true */ 12211 if (!may_access_direct_pkt_data(env, NULL, BPF_WRITE)) { 12212 verbose(env, "the prog does not allow writes to packet data\n"); 12213 return -EINVAL; 12214 } 12215 } 12216 12217 if (!meta.initialized_dynptr.id) { 12218 verbose(env, "verifier internal error: no dynptr id\n"); 12219 return -EFAULT; 12220 } 12221 regs[BPF_REG_0].dynptr_id = meta.initialized_dynptr.id; 12222 12223 /* we don't need to set BPF_REG_0's ref obj id 12224 * because packet slices are not refcounted (see 12225 * dynptr_type_refcounted) 12226 */ 12227 } else { 12228 verbose(env, "kernel function %s unhandled dynamic return type\n", 12229 meta.func_name); 12230 return -EFAULT; 12231 } 12232 } else if (!__btf_type_is_struct(ptr_type)) { 12233 if (!meta.r0_size) { 12234 __u32 sz; 12235 12236 if (!IS_ERR(btf_resolve_size(desc_btf, ptr_type, &sz))) { 12237 meta.r0_size = sz; 12238 meta.r0_rdonly = true; 12239 } 12240 } 12241 if (!meta.r0_size) { 12242 ptr_type_name = btf_name_by_offset(desc_btf, 12243 ptr_type->name_off); 12244 verbose(env, 12245 "kernel function %s returns pointer type %s %s is not supported\n", 12246 func_name, 12247 btf_type_str(ptr_type), 12248 ptr_type_name); 12249 return -EINVAL; 12250 } 12251 12252 mark_reg_known_zero(env, regs, BPF_REG_0); 12253 regs[BPF_REG_0].type = PTR_TO_MEM; 12254 regs[BPF_REG_0].mem_size = meta.r0_size; 12255 12256 if (meta.r0_rdonly) 12257 regs[BPF_REG_0].type |= MEM_RDONLY; 12258 12259 /* Ensures we don't access the memory after a release_reference() */ 12260 if (meta.ref_obj_id) 12261 regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id; 12262 } else { 12263 mark_reg_known_zero(env, regs, BPF_REG_0); 12264 regs[BPF_REG_0].btf = desc_btf; 12265 regs[BPF_REG_0].type = PTR_TO_BTF_ID; 12266 regs[BPF_REG_0].btf_id = ptr_type_id; 12267 } 12268 12269 if (is_kfunc_ret_null(&meta)) { 12270 regs[BPF_REG_0].type |= PTR_MAYBE_NULL; 12271 /* For mark_ptr_or_null_reg, see 93c230e3f5bd6 */ 12272 regs[BPF_REG_0].id = ++env->id_gen; 12273 } 12274 mark_btf_func_reg_size(env, BPF_REG_0, sizeof(void *)); 12275 if (is_kfunc_acquire(&meta)) { 12276 int id = acquire_reference_state(env, insn_idx); 12277 12278 if (id < 0) 12279 return id; 12280 if (is_kfunc_ret_null(&meta)) 12281 regs[BPF_REG_0].id = id; 12282 regs[BPF_REG_0].ref_obj_id = id; 12283 } else if (meta.func_id == special_kfunc_list[KF_bpf_rbtree_first]) { 12284 ref_set_non_owning(env, ®s[BPF_REG_0]); 12285 } 12286 12287 if (reg_may_point_to_spin_lock(®s[BPF_REG_0]) && !regs[BPF_REG_0].id) 12288 regs[BPF_REG_0].id = ++env->id_gen; 12289 } else if (btf_type_is_void(t)) { 12290 if (meta.btf == btf_vmlinux && btf_id_set_contains(&special_kfunc_set, meta.func_id)) { 12291 if (meta.func_id == special_kfunc_list[KF_bpf_obj_drop_impl] || 12292 meta.func_id == special_kfunc_list[KF_bpf_percpu_obj_drop_impl]) { 12293 insn_aux->kptr_struct_meta = 12294 btf_find_struct_meta(meta.arg_btf, 12295 meta.arg_btf_id); 12296 } 12297 } 12298 } 12299 12300 nargs = btf_type_vlen(meta.func_proto); 12301 args = (const struct btf_param *)(meta.func_proto + 1); 12302 for (i = 0; i < nargs; i++) { 12303 u32 regno = i + 1; 12304 12305 t = btf_type_skip_modifiers(desc_btf, args[i].type, NULL); 12306 if (btf_type_is_ptr(t)) 12307 mark_btf_func_reg_size(env, regno, sizeof(void *)); 12308 else 12309 /* scalar. ensured by btf_check_kfunc_arg_match() */ 12310 mark_btf_func_reg_size(env, regno, t->size); 12311 } 12312 12313 if (is_iter_next_kfunc(&meta)) { 12314 err = process_iter_next_call(env, insn_idx, &meta); 12315 if (err) 12316 return err; 12317 } 12318 12319 return 0; 12320 } 12321 12322 static bool signed_add_overflows(s64 a, s64 b) 12323 { 12324 /* Do the add in u64, where overflow is well-defined */ 12325 s64 res = (s64)((u64)a + (u64)b); 12326 12327 if (b < 0) 12328 return res > a; 12329 return res < a; 12330 } 12331 12332 static bool signed_add32_overflows(s32 a, s32 b) 12333 { 12334 /* Do the add in u32, where overflow is well-defined */ 12335 s32 res = (s32)((u32)a + (u32)b); 12336 12337 if (b < 0) 12338 return res > a; 12339 return res < a; 12340 } 12341 12342 static bool signed_sub_overflows(s64 a, s64 b) 12343 { 12344 /* Do the sub in u64, where overflow is well-defined */ 12345 s64 res = (s64)((u64)a - (u64)b); 12346 12347 if (b < 0) 12348 return res < a; 12349 return res > a; 12350 } 12351 12352 static bool signed_sub32_overflows(s32 a, s32 b) 12353 { 12354 /* Do the sub in u32, where overflow is well-defined */ 12355 s32 res = (s32)((u32)a - (u32)b); 12356 12357 if (b < 0) 12358 return res < a; 12359 return res > a; 12360 } 12361 12362 static bool check_reg_sane_offset(struct bpf_verifier_env *env, 12363 const struct bpf_reg_state *reg, 12364 enum bpf_reg_type type) 12365 { 12366 bool known = tnum_is_const(reg->var_off); 12367 s64 val = reg->var_off.value; 12368 s64 smin = reg->smin_value; 12369 12370 if (known && (val >= BPF_MAX_VAR_OFF || val <= -BPF_MAX_VAR_OFF)) { 12371 verbose(env, "math between %s pointer and %lld is not allowed\n", 12372 reg_type_str(env, type), val); 12373 return false; 12374 } 12375 12376 if (reg->off >= BPF_MAX_VAR_OFF || reg->off <= -BPF_MAX_VAR_OFF) { 12377 verbose(env, "%s pointer offset %d is not allowed\n", 12378 reg_type_str(env, type), reg->off); 12379 return false; 12380 } 12381 12382 if (smin == S64_MIN) { 12383 verbose(env, "math between %s pointer and register with unbounded min value is not allowed\n", 12384 reg_type_str(env, type)); 12385 return false; 12386 } 12387 12388 if (smin >= BPF_MAX_VAR_OFF || smin <= -BPF_MAX_VAR_OFF) { 12389 verbose(env, "value %lld makes %s pointer be out of bounds\n", 12390 smin, reg_type_str(env, type)); 12391 return false; 12392 } 12393 12394 return true; 12395 } 12396 12397 enum { 12398 REASON_BOUNDS = -1, 12399 REASON_TYPE = -2, 12400 REASON_PATHS = -3, 12401 REASON_LIMIT = -4, 12402 REASON_STACK = -5, 12403 }; 12404 12405 static int retrieve_ptr_limit(const struct bpf_reg_state *ptr_reg, 12406 u32 *alu_limit, bool mask_to_left) 12407 { 12408 u32 max = 0, ptr_limit = 0; 12409 12410 switch (ptr_reg->type) { 12411 case PTR_TO_STACK: 12412 /* Offset 0 is out-of-bounds, but acceptable start for the 12413 * left direction, see BPF_REG_FP. Also, unknown scalar 12414 * offset where we would need to deal with min/max bounds is 12415 * currently prohibited for unprivileged. 12416 */ 12417 max = MAX_BPF_STACK + mask_to_left; 12418 ptr_limit = -(ptr_reg->var_off.value + ptr_reg->off); 12419 break; 12420 case PTR_TO_MAP_VALUE: 12421 max = ptr_reg->map_ptr->value_size; 12422 ptr_limit = (mask_to_left ? 12423 ptr_reg->smin_value : 12424 ptr_reg->umax_value) + ptr_reg->off; 12425 break; 12426 default: 12427 return REASON_TYPE; 12428 } 12429 12430 if (ptr_limit >= max) 12431 return REASON_LIMIT; 12432 *alu_limit = ptr_limit; 12433 return 0; 12434 } 12435 12436 static bool can_skip_alu_sanitation(const struct bpf_verifier_env *env, 12437 const struct bpf_insn *insn) 12438 { 12439 return env->bypass_spec_v1 || BPF_SRC(insn->code) == BPF_K; 12440 } 12441 12442 static int update_alu_sanitation_state(struct bpf_insn_aux_data *aux, 12443 u32 alu_state, u32 alu_limit) 12444 { 12445 /* If we arrived here from different branches with different 12446 * state or limits to sanitize, then this won't work. 12447 */ 12448 if (aux->alu_state && 12449 (aux->alu_state != alu_state || 12450 aux->alu_limit != alu_limit)) 12451 return REASON_PATHS; 12452 12453 /* Corresponding fixup done in do_misc_fixups(). */ 12454 aux->alu_state = alu_state; 12455 aux->alu_limit = alu_limit; 12456 return 0; 12457 } 12458 12459 static int sanitize_val_alu(struct bpf_verifier_env *env, 12460 struct bpf_insn *insn) 12461 { 12462 struct bpf_insn_aux_data *aux = cur_aux(env); 12463 12464 if (can_skip_alu_sanitation(env, insn)) 12465 return 0; 12466 12467 return update_alu_sanitation_state(aux, BPF_ALU_NON_POINTER, 0); 12468 } 12469 12470 static bool sanitize_needed(u8 opcode) 12471 { 12472 return opcode == BPF_ADD || opcode == BPF_SUB; 12473 } 12474 12475 struct bpf_sanitize_info { 12476 struct bpf_insn_aux_data aux; 12477 bool mask_to_left; 12478 }; 12479 12480 static struct bpf_verifier_state * 12481 sanitize_speculative_path(struct bpf_verifier_env *env, 12482 const struct bpf_insn *insn, 12483 u32 next_idx, u32 curr_idx) 12484 { 12485 struct bpf_verifier_state *branch; 12486 struct bpf_reg_state *regs; 12487 12488 branch = push_stack(env, next_idx, curr_idx, true); 12489 if (branch && insn) { 12490 regs = branch->frame[branch->curframe]->regs; 12491 if (BPF_SRC(insn->code) == BPF_K) { 12492 mark_reg_unknown(env, regs, insn->dst_reg); 12493 } else if (BPF_SRC(insn->code) == BPF_X) { 12494 mark_reg_unknown(env, regs, insn->dst_reg); 12495 mark_reg_unknown(env, regs, insn->src_reg); 12496 } 12497 } 12498 return branch; 12499 } 12500 12501 static int sanitize_ptr_alu(struct bpf_verifier_env *env, 12502 struct bpf_insn *insn, 12503 const struct bpf_reg_state *ptr_reg, 12504 const struct bpf_reg_state *off_reg, 12505 struct bpf_reg_state *dst_reg, 12506 struct bpf_sanitize_info *info, 12507 const bool commit_window) 12508 { 12509 struct bpf_insn_aux_data *aux = commit_window ? cur_aux(env) : &info->aux; 12510 struct bpf_verifier_state *vstate = env->cur_state; 12511 bool off_is_imm = tnum_is_const(off_reg->var_off); 12512 bool off_is_neg = off_reg->smin_value < 0; 12513 bool ptr_is_dst_reg = ptr_reg == dst_reg; 12514 u8 opcode = BPF_OP(insn->code); 12515 u32 alu_state, alu_limit; 12516 struct bpf_reg_state tmp; 12517 bool ret; 12518 int err; 12519 12520 if (can_skip_alu_sanitation(env, insn)) 12521 return 0; 12522 12523 /* We already marked aux for masking from non-speculative 12524 * paths, thus we got here in the first place. We only care 12525 * to explore bad access from here. 12526 */ 12527 if (vstate->speculative) 12528 goto do_sim; 12529 12530 if (!commit_window) { 12531 if (!tnum_is_const(off_reg->var_off) && 12532 (off_reg->smin_value < 0) != (off_reg->smax_value < 0)) 12533 return REASON_BOUNDS; 12534 12535 info->mask_to_left = (opcode == BPF_ADD && off_is_neg) || 12536 (opcode == BPF_SUB && !off_is_neg); 12537 } 12538 12539 err = retrieve_ptr_limit(ptr_reg, &alu_limit, info->mask_to_left); 12540 if (err < 0) 12541 return err; 12542 12543 if (commit_window) { 12544 /* In commit phase we narrow the masking window based on 12545 * the observed pointer move after the simulated operation. 12546 */ 12547 alu_state = info->aux.alu_state; 12548 alu_limit = abs(info->aux.alu_limit - alu_limit); 12549 } else { 12550 alu_state = off_is_neg ? BPF_ALU_NEG_VALUE : 0; 12551 alu_state |= off_is_imm ? BPF_ALU_IMMEDIATE : 0; 12552 alu_state |= ptr_is_dst_reg ? 12553 BPF_ALU_SANITIZE_SRC : BPF_ALU_SANITIZE_DST; 12554 12555 /* Limit pruning on unknown scalars to enable deep search for 12556 * potential masking differences from other program paths. 12557 */ 12558 if (!off_is_imm) 12559 env->explore_alu_limits = true; 12560 } 12561 12562 err = update_alu_sanitation_state(aux, alu_state, alu_limit); 12563 if (err < 0) 12564 return err; 12565 do_sim: 12566 /* If we're in commit phase, we're done here given we already 12567 * pushed the truncated dst_reg into the speculative verification 12568 * stack. 12569 * 12570 * Also, when register is a known constant, we rewrite register-based 12571 * operation to immediate-based, and thus do not need masking (and as 12572 * a consequence, do not need to simulate the zero-truncation either). 12573 */ 12574 if (commit_window || off_is_imm) 12575 return 0; 12576 12577 /* Simulate and find potential out-of-bounds access under 12578 * speculative execution from truncation as a result of 12579 * masking when off was not within expected range. If off 12580 * sits in dst, then we temporarily need to move ptr there 12581 * to simulate dst (== 0) +/-= ptr. Needed, for example, 12582 * for cases where we use K-based arithmetic in one direction 12583 * and truncated reg-based in the other in order to explore 12584 * bad access. 12585 */ 12586 if (!ptr_is_dst_reg) { 12587 tmp = *dst_reg; 12588 copy_register_state(dst_reg, ptr_reg); 12589 } 12590 ret = sanitize_speculative_path(env, NULL, env->insn_idx + 1, 12591 env->insn_idx); 12592 if (!ptr_is_dst_reg && ret) 12593 *dst_reg = tmp; 12594 return !ret ? REASON_STACK : 0; 12595 } 12596 12597 static void sanitize_mark_insn_seen(struct bpf_verifier_env *env) 12598 { 12599 struct bpf_verifier_state *vstate = env->cur_state; 12600 12601 /* If we simulate paths under speculation, we don't update the 12602 * insn as 'seen' such that when we verify unreachable paths in 12603 * the non-speculative domain, sanitize_dead_code() can still 12604 * rewrite/sanitize them. 12605 */ 12606 if (!vstate->speculative) 12607 env->insn_aux_data[env->insn_idx].seen = env->pass_cnt; 12608 } 12609 12610 static int sanitize_err(struct bpf_verifier_env *env, 12611 const struct bpf_insn *insn, int reason, 12612 const struct bpf_reg_state *off_reg, 12613 const struct bpf_reg_state *dst_reg) 12614 { 12615 static const char *err = "pointer arithmetic with it prohibited for !root"; 12616 const char *op = BPF_OP(insn->code) == BPF_ADD ? "add" : "sub"; 12617 u32 dst = insn->dst_reg, src = insn->src_reg; 12618 12619 switch (reason) { 12620 case REASON_BOUNDS: 12621 verbose(env, "R%d has unknown scalar with mixed signed bounds, %s\n", 12622 off_reg == dst_reg ? dst : src, err); 12623 break; 12624 case REASON_TYPE: 12625 verbose(env, "R%d has pointer with unsupported alu operation, %s\n", 12626 off_reg == dst_reg ? src : dst, err); 12627 break; 12628 case REASON_PATHS: 12629 verbose(env, "R%d tried to %s from different maps, paths or scalars, %s\n", 12630 dst, op, err); 12631 break; 12632 case REASON_LIMIT: 12633 verbose(env, "R%d tried to %s beyond pointer bounds, %s\n", 12634 dst, op, err); 12635 break; 12636 case REASON_STACK: 12637 verbose(env, "R%d could not be pushed for speculative verification, %s\n", 12638 dst, err); 12639 break; 12640 default: 12641 verbose(env, "verifier internal error: unknown reason (%d)\n", 12642 reason); 12643 break; 12644 } 12645 12646 return -EACCES; 12647 } 12648 12649 /* check that stack access falls within stack limits and that 'reg' doesn't 12650 * have a variable offset. 12651 * 12652 * Variable offset is prohibited for unprivileged mode for simplicity since it 12653 * requires corresponding support in Spectre masking for stack ALU. See also 12654 * retrieve_ptr_limit(). 12655 * 12656 * 12657 * 'off' includes 'reg->off'. 12658 */ 12659 static int check_stack_access_for_ptr_arithmetic( 12660 struct bpf_verifier_env *env, 12661 int regno, 12662 const struct bpf_reg_state *reg, 12663 int off) 12664 { 12665 if (!tnum_is_const(reg->var_off)) { 12666 char tn_buf[48]; 12667 12668 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 12669 verbose(env, "R%d variable stack access prohibited for !root, var_off=%s off=%d\n", 12670 regno, tn_buf, off); 12671 return -EACCES; 12672 } 12673 12674 if (off >= 0 || off < -MAX_BPF_STACK) { 12675 verbose(env, "R%d stack pointer arithmetic goes out of range, " 12676 "prohibited for !root; off=%d\n", regno, off); 12677 return -EACCES; 12678 } 12679 12680 return 0; 12681 } 12682 12683 static int sanitize_check_bounds(struct bpf_verifier_env *env, 12684 const struct bpf_insn *insn, 12685 const struct bpf_reg_state *dst_reg) 12686 { 12687 u32 dst = insn->dst_reg; 12688 12689 /* For unprivileged we require that resulting offset must be in bounds 12690 * in order to be able to sanitize access later on. 12691 */ 12692 if (env->bypass_spec_v1) 12693 return 0; 12694 12695 switch (dst_reg->type) { 12696 case PTR_TO_STACK: 12697 if (check_stack_access_for_ptr_arithmetic(env, dst, dst_reg, 12698 dst_reg->off + dst_reg->var_off.value)) 12699 return -EACCES; 12700 break; 12701 case PTR_TO_MAP_VALUE: 12702 if (check_map_access(env, dst, dst_reg->off, 1, false, ACCESS_HELPER)) { 12703 verbose(env, "R%d pointer arithmetic of map value goes out of range, " 12704 "prohibited for !root\n", dst); 12705 return -EACCES; 12706 } 12707 break; 12708 default: 12709 break; 12710 } 12711 12712 return 0; 12713 } 12714 12715 /* Handles arithmetic on a pointer and a scalar: computes new min/max and var_off. 12716 * Caller should also handle BPF_MOV case separately. 12717 * If we return -EACCES, caller may want to try again treating pointer as a 12718 * scalar. So we only emit a diagnostic if !env->allow_ptr_leaks. 12719 */ 12720 static int adjust_ptr_min_max_vals(struct bpf_verifier_env *env, 12721 struct bpf_insn *insn, 12722 const struct bpf_reg_state *ptr_reg, 12723 const struct bpf_reg_state *off_reg) 12724 { 12725 struct bpf_verifier_state *vstate = env->cur_state; 12726 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 12727 struct bpf_reg_state *regs = state->regs, *dst_reg; 12728 bool known = tnum_is_const(off_reg->var_off); 12729 s64 smin_val = off_reg->smin_value, smax_val = off_reg->smax_value, 12730 smin_ptr = ptr_reg->smin_value, smax_ptr = ptr_reg->smax_value; 12731 u64 umin_val = off_reg->umin_value, umax_val = off_reg->umax_value, 12732 umin_ptr = ptr_reg->umin_value, umax_ptr = ptr_reg->umax_value; 12733 struct bpf_sanitize_info info = {}; 12734 u8 opcode = BPF_OP(insn->code); 12735 u32 dst = insn->dst_reg; 12736 int ret; 12737 12738 dst_reg = ®s[dst]; 12739 12740 if ((known && (smin_val != smax_val || umin_val != umax_val)) || 12741 smin_val > smax_val || umin_val > umax_val) { 12742 /* Taint dst register if offset had invalid bounds derived from 12743 * e.g. dead branches. 12744 */ 12745 __mark_reg_unknown(env, dst_reg); 12746 return 0; 12747 } 12748 12749 if (BPF_CLASS(insn->code) != BPF_ALU64) { 12750 /* 32-bit ALU ops on pointers produce (meaningless) scalars */ 12751 if (opcode == BPF_SUB && env->allow_ptr_leaks) { 12752 __mark_reg_unknown(env, dst_reg); 12753 return 0; 12754 } 12755 12756 verbose(env, 12757 "R%d 32-bit pointer arithmetic prohibited\n", 12758 dst); 12759 return -EACCES; 12760 } 12761 12762 if (ptr_reg->type & PTR_MAYBE_NULL) { 12763 verbose(env, "R%d pointer arithmetic on %s prohibited, null-check it first\n", 12764 dst, reg_type_str(env, ptr_reg->type)); 12765 return -EACCES; 12766 } 12767 12768 switch (base_type(ptr_reg->type)) { 12769 case CONST_PTR_TO_MAP: 12770 /* smin_val represents the known value */ 12771 if (known && smin_val == 0 && opcode == BPF_ADD) 12772 break; 12773 fallthrough; 12774 case PTR_TO_PACKET_END: 12775 case PTR_TO_SOCKET: 12776 case PTR_TO_SOCK_COMMON: 12777 case PTR_TO_TCP_SOCK: 12778 case PTR_TO_XDP_SOCK: 12779 verbose(env, "R%d pointer arithmetic on %s prohibited\n", 12780 dst, reg_type_str(env, ptr_reg->type)); 12781 return -EACCES; 12782 default: 12783 break; 12784 } 12785 12786 /* In case of 'scalar += pointer', dst_reg inherits pointer type and id. 12787 * The id may be overwritten later if we create a new variable offset. 12788 */ 12789 dst_reg->type = ptr_reg->type; 12790 dst_reg->id = ptr_reg->id; 12791 12792 if (!check_reg_sane_offset(env, off_reg, ptr_reg->type) || 12793 !check_reg_sane_offset(env, ptr_reg, ptr_reg->type)) 12794 return -EINVAL; 12795 12796 /* pointer types do not carry 32-bit bounds at the moment. */ 12797 __mark_reg32_unbounded(dst_reg); 12798 12799 if (sanitize_needed(opcode)) { 12800 ret = sanitize_ptr_alu(env, insn, ptr_reg, off_reg, dst_reg, 12801 &info, false); 12802 if (ret < 0) 12803 return sanitize_err(env, insn, ret, off_reg, dst_reg); 12804 } 12805 12806 switch (opcode) { 12807 case BPF_ADD: 12808 /* We can take a fixed offset as long as it doesn't overflow 12809 * the s32 'off' field 12810 */ 12811 if (known && (ptr_reg->off + smin_val == 12812 (s64)(s32)(ptr_reg->off + smin_val))) { 12813 /* pointer += K. Accumulate it into fixed offset */ 12814 dst_reg->smin_value = smin_ptr; 12815 dst_reg->smax_value = smax_ptr; 12816 dst_reg->umin_value = umin_ptr; 12817 dst_reg->umax_value = umax_ptr; 12818 dst_reg->var_off = ptr_reg->var_off; 12819 dst_reg->off = ptr_reg->off + smin_val; 12820 dst_reg->raw = ptr_reg->raw; 12821 break; 12822 } 12823 /* A new variable offset is created. Note that off_reg->off 12824 * == 0, since it's a scalar. 12825 * dst_reg gets the pointer type and since some positive 12826 * integer value was added to the pointer, give it a new 'id' 12827 * if it's a PTR_TO_PACKET. 12828 * this creates a new 'base' pointer, off_reg (variable) gets 12829 * added into the variable offset, and we copy the fixed offset 12830 * from ptr_reg. 12831 */ 12832 if (signed_add_overflows(smin_ptr, smin_val) || 12833 signed_add_overflows(smax_ptr, smax_val)) { 12834 dst_reg->smin_value = S64_MIN; 12835 dst_reg->smax_value = S64_MAX; 12836 } else { 12837 dst_reg->smin_value = smin_ptr + smin_val; 12838 dst_reg->smax_value = smax_ptr + smax_val; 12839 } 12840 if (umin_ptr + umin_val < umin_ptr || 12841 umax_ptr + umax_val < umax_ptr) { 12842 dst_reg->umin_value = 0; 12843 dst_reg->umax_value = U64_MAX; 12844 } else { 12845 dst_reg->umin_value = umin_ptr + umin_val; 12846 dst_reg->umax_value = umax_ptr + umax_val; 12847 } 12848 dst_reg->var_off = tnum_add(ptr_reg->var_off, off_reg->var_off); 12849 dst_reg->off = ptr_reg->off; 12850 dst_reg->raw = ptr_reg->raw; 12851 if (reg_is_pkt_pointer(ptr_reg)) { 12852 dst_reg->id = ++env->id_gen; 12853 /* something was added to pkt_ptr, set range to zero */ 12854 memset(&dst_reg->raw, 0, sizeof(dst_reg->raw)); 12855 } 12856 break; 12857 case BPF_SUB: 12858 if (dst_reg == off_reg) { 12859 /* scalar -= pointer. Creates an unknown scalar */ 12860 verbose(env, "R%d tried to subtract pointer from scalar\n", 12861 dst); 12862 return -EACCES; 12863 } 12864 /* We don't allow subtraction from FP, because (according to 12865 * test_verifier.c test "invalid fp arithmetic", JITs might not 12866 * be able to deal with it. 12867 */ 12868 if (ptr_reg->type == PTR_TO_STACK) { 12869 verbose(env, "R%d subtraction from stack pointer prohibited\n", 12870 dst); 12871 return -EACCES; 12872 } 12873 if (known && (ptr_reg->off - smin_val == 12874 (s64)(s32)(ptr_reg->off - smin_val))) { 12875 /* pointer -= K. Subtract it from fixed offset */ 12876 dst_reg->smin_value = smin_ptr; 12877 dst_reg->smax_value = smax_ptr; 12878 dst_reg->umin_value = umin_ptr; 12879 dst_reg->umax_value = umax_ptr; 12880 dst_reg->var_off = ptr_reg->var_off; 12881 dst_reg->id = ptr_reg->id; 12882 dst_reg->off = ptr_reg->off - smin_val; 12883 dst_reg->raw = ptr_reg->raw; 12884 break; 12885 } 12886 /* A new variable offset is created. If the subtrahend is known 12887 * nonnegative, then any reg->range we had before is still good. 12888 */ 12889 if (signed_sub_overflows(smin_ptr, smax_val) || 12890 signed_sub_overflows(smax_ptr, smin_val)) { 12891 /* Overflow possible, we know nothing */ 12892 dst_reg->smin_value = S64_MIN; 12893 dst_reg->smax_value = S64_MAX; 12894 } else { 12895 dst_reg->smin_value = smin_ptr - smax_val; 12896 dst_reg->smax_value = smax_ptr - smin_val; 12897 } 12898 if (umin_ptr < umax_val) { 12899 /* Overflow possible, we know nothing */ 12900 dst_reg->umin_value = 0; 12901 dst_reg->umax_value = U64_MAX; 12902 } else { 12903 /* Cannot overflow (as long as bounds are consistent) */ 12904 dst_reg->umin_value = umin_ptr - umax_val; 12905 dst_reg->umax_value = umax_ptr - umin_val; 12906 } 12907 dst_reg->var_off = tnum_sub(ptr_reg->var_off, off_reg->var_off); 12908 dst_reg->off = ptr_reg->off; 12909 dst_reg->raw = ptr_reg->raw; 12910 if (reg_is_pkt_pointer(ptr_reg)) { 12911 dst_reg->id = ++env->id_gen; 12912 /* something was added to pkt_ptr, set range to zero */ 12913 if (smin_val < 0) 12914 memset(&dst_reg->raw, 0, sizeof(dst_reg->raw)); 12915 } 12916 break; 12917 case BPF_AND: 12918 case BPF_OR: 12919 case BPF_XOR: 12920 /* bitwise ops on pointers are troublesome, prohibit. */ 12921 verbose(env, "R%d bitwise operator %s on pointer prohibited\n", 12922 dst, bpf_alu_string[opcode >> 4]); 12923 return -EACCES; 12924 default: 12925 /* other operators (e.g. MUL,LSH) produce non-pointer results */ 12926 verbose(env, "R%d pointer arithmetic with %s operator prohibited\n", 12927 dst, bpf_alu_string[opcode >> 4]); 12928 return -EACCES; 12929 } 12930 12931 if (!check_reg_sane_offset(env, dst_reg, ptr_reg->type)) 12932 return -EINVAL; 12933 reg_bounds_sync(dst_reg); 12934 if (sanitize_check_bounds(env, insn, dst_reg) < 0) 12935 return -EACCES; 12936 if (sanitize_needed(opcode)) { 12937 ret = sanitize_ptr_alu(env, insn, dst_reg, off_reg, dst_reg, 12938 &info, true); 12939 if (ret < 0) 12940 return sanitize_err(env, insn, ret, off_reg, dst_reg); 12941 } 12942 12943 return 0; 12944 } 12945 12946 static void scalar32_min_max_add(struct bpf_reg_state *dst_reg, 12947 struct bpf_reg_state *src_reg) 12948 { 12949 s32 smin_val = src_reg->s32_min_value; 12950 s32 smax_val = src_reg->s32_max_value; 12951 u32 umin_val = src_reg->u32_min_value; 12952 u32 umax_val = src_reg->u32_max_value; 12953 12954 if (signed_add32_overflows(dst_reg->s32_min_value, smin_val) || 12955 signed_add32_overflows(dst_reg->s32_max_value, smax_val)) { 12956 dst_reg->s32_min_value = S32_MIN; 12957 dst_reg->s32_max_value = S32_MAX; 12958 } else { 12959 dst_reg->s32_min_value += smin_val; 12960 dst_reg->s32_max_value += smax_val; 12961 } 12962 if (dst_reg->u32_min_value + umin_val < umin_val || 12963 dst_reg->u32_max_value + umax_val < umax_val) { 12964 dst_reg->u32_min_value = 0; 12965 dst_reg->u32_max_value = U32_MAX; 12966 } else { 12967 dst_reg->u32_min_value += umin_val; 12968 dst_reg->u32_max_value += umax_val; 12969 } 12970 } 12971 12972 static void scalar_min_max_add(struct bpf_reg_state *dst_reg, 12973 struct bpf_reg_state *src_reg) 12974 { 12975 s64 smin_val = src_reg->smin_value; 12976 s64 smax_val = src_reg->smax_value; 12977 u64 umin_val = src_reg->umin_value; 12978 u64 umax_val = src_reg->umax_value; 12979 12980 if (signed_add_overflows(dst_reg->smin_value, smin_val) || 12981 signed_add_overflows(dst_reg->smax_value, smax_val)) { 12982 dst_reg->smin_value = S64_MIN; 12983 dst_reg->smax_value = S64_MAX; 12984 } else { 12985 dst_reg->smin_value += smin_val; 12986 dst_reg->smax_value += smax_val; 12987 } 12988 if (dst_reg->umin_value + umin_val < umin_val || 12989 dst_reg->umax_value + umax_val < umax_val) { 12990 dst_reg->umin_value = 0; 12991 dst_reg->umax_value = U64_MAX; 12992 } else { 12993 dst_reg->umin_value += umin_val; 12994 dst_reg->umax_value += umax_val; 12995 } 12996 } 12997 12998 static void scalar32_min_max_sub(struct bpf_reg_state *dst_reg, 12999 struct bpf_reg_state *src_reg) 13000 { 13001 s32 smin_val = src_reg->s32_min_value; 13002 s32 smax_val = src_reg->s32_max_value; 13003 u32 umin_val = src_reg->u32_min_value; 13004 u32 umax_val = src_reg->u32_max_value; 13005 13006 if (signed_sub32_overflows(dst_reg->s32_min_value, smax_val) || 13007 signed_sub32_overflows(dst_reg->s32_max_value, smin_val)) { 13008 /* Overflow possible, we know nothing */ 13009 dst_reg->s32_min_value = S32_MIN; 13010 dst_reg->s32_max_value = S32_MAX; 13011 } else { 13012 dst_reg->s32_min_value -= smax_val; 13013 dst_reg->s32_max_value -= smin_val; 13014 } 13015 if (dst_reg->u32_min_value < umax_val) { 13016 /* Overflow possible, we know nothing */ 13017 dst_reg->u32_min_value = 0; 13018 dst_reg->u32_max_value = U32_MAX; 13019 } else { 13020 /* Cannot overflow (as long as bounds are consistent) */ 13021 dst_reg->u32_min_value -= umax_val; 13022 dst_reg->u32_max_value -= umin_val; 13023 } 13024 } 13025 13026 static void scalar_min_max_sub(struct bpf_reg_state *dst_reg, 13027 struct bpf_reg_state *src_reg) 13028 { 13029 s64 smin_val = src_reg->smin_value; 13030 s64 smax_val = src_reg->smax_value; 13031 u64 umin_val = src_reg->umin_value; 13032 u64 umax_val = src_reg->umax_value; 13033 13034 if (signed_sub_overflows(dst_reg->smin_value, smax_val) || 13035 signed_sub_overflows(dst_reg->smax_value, smin_val)) { 13036 /* Overflow possible, we know nothing */ 13037 dst_reg->smin_value = S64_MIN; 13038 dst_reg->smax_value = S64_MAX; 13039 } else { 13040 dst_reg->smin_value -= smax_val; 13041 dst_reg->smax_value -= smin_val; 13042 } 13043 if (dst_reg->umin_value < umax_val) { 13044 /* Overflow possible, we know nothing */ 13045 dst_reg->umin_value = 0; 13046 dst_reg->umax_value = U64_MAX; 13047 } else { 13048 /* Cannot overflow (as long as bounds are consistent) */ 13049 dst_reg->umin_value -= umax_val; 13050 dst_reg->umax_value -= umin_val; 13051 } 13052 } 13053 13054 static void scalar32_min_max_mul(struct bpf_reg_state *dst_reg, 13055 struct bpf_reg_state *src_reg) 13056 { 13057 s32 smin_val = src_reg->s32_min_value; 13058 u32 umin_val = src_reg->u32_min_value; 13059 u32 umax_val = src_reg->u32_max_value; 13060 13061 if (smin_val < 0 || dst_reg->s32_min_value < 0) { 13062 /* Ain't nobody got time to multiply that sign */ 13063 __mark_reg32_unbounded(dst_reg); 13064 return; 13065 } 13066 /* Both values are positive, so we can work with unsigned and 13067 * copy the result to signed (unless it exceeds S32_MAX). 13068 */ 13069 if (umax_val > U16_MAX || dst_reg->u32_max_value > U16_MAX) { 13070 /* Potential overflow, we know nothing */ 13071 __mark_reg32_unbounded(dst_reg); 13072 return; 13073 } 13074 dst_reg->u32_min_value *= umin_val; 13075 dst_reg->u32_max_value *= umax_val; 13076 if (dst_reg->u32_max_value > S32_MAX) { 13077 /* Overflow possible, we know nothing */ 13078 dst_reg->s32_min_value = S32_MIN; 13079 dst_reg->s32_max_value = S32_MAX; 13080 } else { 13081 dst_reg->s32_min_value = dst_reg->u32_min_value; 13082 dst_reg->s32_max_value = dst_reg->u32_max_value; 13083 } 13084 } 13085 13086 static void scalar_min_max_mul(struct bpf_reg_state *dst_reg, 13087 struct bpf_reg_state *src_reg) 13088 { 13089 s64 smin_val = src_reg->smin_value; 13090 u64 umin_val = src_reg->umin_value; 13091 u64 umax_val = src_reg->umax_value; 13092 13093 if (smin_val < 0 || dst_reg->smin_value < 0) { 13094 /* Ain't nobody got time to multiply that sign */ 13095 __mark_reg64_unbounded(dst_reg); 13096 return; 13097 } 13098 /* Both values are positive, so we can work with unsigned and 13099 * copy the result to signed (unless it exceeds S64_MAX). 13100 */ 13101 if (umax_val > U32_MAX || dst_reg->umax_value > U32_MAX) { 13102 /* Potential overflow, we know nothing */ 13103 __mark_reg64_unbounded(dst_reg); 13104 return; 13105 } 13106 dst_reg->umin_value *= umin_val; 13107 dst_reg->umax_value *= umax_val; 13108 if (dst_reg->umax_value > S64_MAX) { 13109 /* Overflow possible, we know nothing */ 13110 dst_reg->smin_value = S64_MIN; 13111 dst_reg->smax_value = S64_MAX; 13112 } else { 13113 dst_reg->smin_value = dst_reg->umin_value; 13114 dst_reg->smax_value = dst_reg->umax_value; 13115 } 13116 } 13117 13118 static void scalar32_min_max_and(struct bpf_reg_state *dst_reg, 13119 struct bpf_reg_state *src_reg) 13120 { 13121 bool src_known = tnum_subreg_is_const(src_reg->var_off); 13122 bool dst_known = tnum_subreg_is_const(dst_reg->var_off); 13123 struct tnum var32_off = tnum_subreg(dst_reg->var_off); 13124 s32 smin_val = src_reg->s32_min_value; 13125 u32 umax_val = src_reg->u32_max_value; 13126 13127 if (src_known && dst_known) { 13128 __mark_reg32_known(dst_reg, var32_off.value); 13129 return; 13130 } 13131 13132 /* We get our minimum from the var_off, since that's inherently 13133 * bitwise. Our maximum is the minimum of the operands' maxima. 13134 */ 13135 dst_reg->u32_min_value = var32_off.value; 13136 dst_reg->u32_max_value = min(dst_reg->u32_max_value, umax_val); 13137 if (dst_reg->s32_min_value < 0 || smin_val < 0) { 13138 /* Lose signed bounds when ANDing negative numbers, 13139 * ain't nobody got time for that. 13140 */ 13141 dst_reg->s32_min_value = S32_MIN; 13142 dst_reg->s32_max_value = S32_MAX; 13143 } else { 13144 /* ANDing two positives gives a positive, so safe to 13145 * cast result into s64. 13146 */ 13147 dst_reg->s32_min_value = dst_reg->u32_min_value; 13148 dst_reg->s32_max_value = dst_reg->u32_max_value; 13149 } 13150 } 13151 13152 static void scalar_min_max_and(struct bpf_reg_state *dst_reg, 13153 struct bpf_reg_state *src_reg) 13154 { 13155 bool src_known = tnum_is_const(src_reg->var_off); 13156 bool dst_known = tnum_is_const(dst_reg->var_off); 13157 s64 smin_val = src_reg->smin_value; 13158 u64 umax_val = src_reg->umax_value; 13159 13160 if (src_known && dst_known) { 13161 __mark_reg_known(dst_reg, dst_reg->var_off.value); 13162 return; 13163 } 13164 13165 /* We get our minimum from the var_off, since that's inherently 13166 * bitwise. Our maximum is the minimum of the operands' maxima. 13167 */ 13168 dst_reg->umin_value = dst_reg->var_off.value; 13169 dst_reg->umax_value = min(dst_reg->umax_value, umax_val); 13170 if (dst_reg->smin_value < 0 || smin_val < 0) { 13171 /* Lose signed bounds when ANDing negative numbers, 13172 * ain't nobody got time for that. 13173 */ 13174 dst_reg->smin_value = S64_MIN; 13175 dst_reg->smax_value = S64_MAX; 13176 } else { 13177 /* ANDing two positives gives a positive, so safe to 13178 * cast result into s64. 13179 */ 13180 dst_reg->smin_value = dst_reg->umin_value; 13181 dst_reg->smax_value = dst_reg->umax_value; 13182 } 13183 /* We may learn something more from the var_off */ 13184 __update_reg_bounds(dst_reg); 13185 } 13186 13187 static void scalar32_min_max_or(struct bpf_reg_state *dst_reg, 13188 struct bpf_reg_state *src_reg) 13189 { 13190 bool src_known = tnum_subreg_is_const(src_reg->var_off); 13191 bool dst_known = tnum_subreg_is_const(dst_reg->var_off); 13192 struct tnum var32_off = tnum_subreg(dst_reg->var_off); 13193 s32 smin_val = src_reg->s32_min_value; 13194 u32 umin_val = src_reg->u32_min_value; 13195 13196 if (src_known && dst_known) { 13197 __mark_reg32_known(dst_reg, var32_off.value); 13198 return; 13199 } 13200 13201 /* We get our maximum from the var_off, and our minimum is the 13202 * maximum of the operands' minima 13203 */ 13204 dst_reg->u32_min_value = max(dst_reg->u32_min_value, umin_val); 13205 dst_reg->u32_max_value = var32_off.value | var32_off.mask; 13206 if (dst_reg->s32_min_value < 0 || smin_val < 0) { 13207 /* Lose signed bounds when ORing negative numbers, 13208 * ain't nobody got time for that. 13209 */ 13210 dst_reg->s32_min_value = S32_MIN; 13211 dst_reg->s32_max_value = S32_MAX; 13212 } else { 13213 /* ORing two positives gives a positive, so safe to 13214 * cast result into s64. 13215 */ 13216 dst_reg->s32_min_value = dst_reg->u32_min_value; 13217 dst_reg->s32_max_value = dst_reg->u32_max_value; 13218 } 13219 } 13220 13221 static void scalar_min_max_or(struct bpf_reg_state *dst_reg, 13222 struct bpf_reg_state *src_reg) 13223 { 13224 bool src_known = tnum_is_const(src_reg->var_off); 13225 bool dst_known = tnum_is_const(dst_reg->var_off); 13226 s64 smin_val = src_reg->smin_value; 13227 u64 umin_val = src_reg->umin_value; 13228 13229 if (src_known && dst_known) { 13230 __mark_reg_known(dst_reg, dst_reg->var_off.value); 13231 return; 13232 } 13233 13234 /* We get our maximum from the var_off, and our minimum is the 13235 * maximum of the operands' minima 13236 */ 13237 dst_reg->umin_value = max(dst_reg->umin_value, umin_val); 13238 dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask; 13239 if (dst_reg->smin_value < 0 || smin_val < 0) { 13240 /* Lose signed bounds when ORing negative numbers, 13241 * ain't nobody got time for that. 13242 */ 13243 dst_reg->smin_value = S64_MIN; 13244 dst_reg->smax_value = S64_MAX; 13245 } else { 13246 /* ORing two positives gives a positive, so safe to 13247 * cast result into s64. 13248 */ 13249 dst_reg->smin_value = dst_reg->umin_value; 13250 dst_reg->smax_value = dst_reg->umax_value; 13251 } 13252 /* We may learn something more from the var_off */ 13253 __update_reg_bounds(dst_reg); 13254 } 13255 13256 static void scalar32_min_max_xor(struct bpf_reg_state *dst_reg, 13257 struct bpf_reg_state *src_reg) 13258 { 13259 bool src_known = tnum_subreg_is_const(src_reg->var_off); 13260 bool dst_known = tnum_subreg_is_const(dst_reg->var_off); 13261 struct tnum var32_off = tnum_subreg(dst_reg->var_off); 13262 s32 smin_val = src_reg->s32_min_value; 13263 13264 if (src_known && dst_known) { 13265 __mark_reg32_known(dst_reg, var32_off.value); 13266 return; 13267 } 13268 13269 /* We get both minimum and maximum from the var32_off. */ 13270 dst_reg->u32_min_value = var32_off.value; 13271 dst_reg->u32_max_value = var32_off.value | var32_off.mask; 13272 13273 if (dst_reg->s32_min_value >= 0 && smin_val >= 0) { 13274 /* XORing two positive sign numbers gives a positive, 13275 * so safe to cast u32 result into s32. 13276 */ 13277 dst_reg->s32_min_value = dst_reg->u32_min_value; 13278 dst_reg->s32_max_value = dst_reg->u32_max_value; 13279 } else { 13280 dst_reg->s32_min_value = S32_MIN; 13281 dst_reg->s32_max_value = S32_MAX; 13282 } 13283 } 13284 13285 static void scalar_min_max_xor(struct bpf_reg_state *dst_reg, 13286 struct bpf_reg_state *src_reg) 13287 { 13288 bool src_known = tnum_is_const(src_reg->var_off); 13289 bool dst_known = tnum_is_const(dst_reg->var_off); 13290 s64 smin_val = src_reg->smin_value; 13291 13292 if (src_known && dst_known) { 13293 /* dst_reg->var_off.value has been updated earlier */ 13294 __mark_reg_known(dst_reg, dst_reg->var_off.value); 13295 return; 13296 } 13297 13298 /* We get both minimum and maximum from the var_off. */ 13299 dst_reg->umin_value = dst_reg->var_off.value; 13300 dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask; 13301 13302 if (dst_reg->smin_value >= 0 && smin_val >= 0) { 13303 /* XORing two positive sign numbers gives a positive, 13304 * so safe to cast u64 result into s64. 13305 */ 13306 dst_reg->smin_value = dst_reg->umin_value; 13307 dst_reg->smax_value = dst_reg->umax_value; 13308 } else { 13309 dst_reg->smin_value = S64_MIN; 13310 dst_reg->smax_value = S64_MAX; 13311 } 13312 13313 __update_reg_bounds(dst_reg); 13314 } 13315 13316 static void __scalar32_min_max_lsh(struct bpf_reg_state *dst_reg, 13317 u64 umin_val, u64 umax_val) 13318 { 13319 /* We lose all sign bit information (except what we can pick 13320 * up from var_off) 13321 */ 13322 dst_reg->s32_min_value = S32_MIN; 13323 dst_reg->s32_max_value = S32_MAX; 13324 /* If we might shift our top bit out, then we know nothing */ 13325 if (umax_val > 31 || dst_reg->u32_max_value > 1ULL << (31 - umax_val)) { 13326 dst_reg->u32_min_value = 0; 13327 dst_reg->u32_max_value = U32_MAX; 13328 } else { 13329 dst_reg->u32_min_value <<= umin_val; 13330 dst_reg->u32_max_value <<= umax_val; 13331 } 13332 } 13333 13334 static void scalar32_min_max_lsh(struct bpf_reg_state *dst_reg, 13335 struct bpf_reg_state *src_reg) 13336 { 13337 u32 umax_val = src_reg->u32_max_value; 13338 u32 umin_val = src_reg->u32_min_value; 13339 /* u32 alu operation will zext upper bits */ 13340 struct tnum subreg = tnum_subreg(dst_reg->var_off); 13341 13342 __scalar32_min_max_lsh(dst_reg, umin_val, umax_val); 13343 dst_reg->var_off = tnum_subreg(tnum_lshift(subreg, umin_val)); 13344 /* Not required but being careful mark reg64 bounds as unknown so 13345 * that we are forced to pick them up from tnum and zext later and 13346 * if some path skips this step we are still safe. 13347 */ 13348 __mark_reg64_unbounded(dst_reg); 13349 __update_reg32_bounds(dst_reg); 13350 } 13351 13352 static void __scalar64_min_max_lsh(struct bpf_reg_state *dst_reg, 13353 u64 umin_val, u64 umax_val) 13354 { 13355 /* Special case <<32 because it is a common compiler pattern to sign 13356 * extend subreg by doing <<32 s>>32. In this case if 32bit bounds are 13357 * positive we know this shift will also be positive so we can track 13358 * bounds correctly. Otherwise we lose all sign bit information except 13359 * what we can pick up from var_off. Perhaps we can generalize this 13360 * later to shifts of any length. 13361 */ 13362 if (umin_val == 32 && umax_val == 32 && dst_reg->s32_max_value >= 0) 13363 dst_reg->smax_value = (s64)dst_reg->s32_max_value << 32; 13364 else 13365 dst_reg->smax_value = S64_MAX; 13366 13367 if (umin_val == 32 && umax_val == 32 && dst_reg->s32_min_value >= 0) 13368 dst_reg->smin_value = (s64)dst_reg->s32_min_value << 32; 13369 else 13370 dst_reg->smin_value = S64_MIN; 13371 13372 /* If we might shift our top bit out, then we know nothing */ 13373 if (dst_reg->umax_value > 1ULL << (63 - umax_val)) { 13374 dst_reg->umin_value = 0; 13375 dst_reg->umax_value = U64_MAX; 13376 } else { 13377 dst_reg->umin_value <<= umin_val; 13378 dst_reg->umax_value <<= umax_val; 13379 } 13380 } 13381 13382 static void scalar_min_max_lsh(struct bpf_reg_state *dst_reg, 13383 struct bpf_reg_state *src_reg) 13384 { 13385 u64 umax_val = src_reg->umax_value; 13386 u64 umin_val = src_reg->umin_value; 13387 13388 /* scalar64 calc uses 32bit unshifted bounds so must be called first */ 13389 __scalar64_min_max_lsh(dst_reg, umin_val, umax_val); 13390 __scalar32_min_max_lsh(dst_reg, umin_val, umax_val); 13391 13392 dst_reg->var_off = tnum_lshift(dst_reg->var_off, umin_val); 13393 /* We may learn something more from the var_off */ 13394 __update_reg_bounds(dst_reg); 13395 } 13396 13397 static void scalar32_min_max_rsh(struct bpf_reg_state *dst_reg, 13398 struct bpf_reg_state *src_reg) 13399 { 13400 struct tnum subreg = tnum_subreg(dst_reg->var_off); 13401 u32 umax_val = src_reg->u32_max_value; 13402 u32 umin_val = src_reg->u32_min_value; 13403 13404 /* BPF_RSH is an unsigned shift. If the value in dst_reg might 13405 * be negative, then either: 13406 * 1) src_reg might be zero, so the sign bit of the result is 13407 * unknown, so we lose our signed bounds 13408 * 2) it's known negative, thus the unsigned bounds capture the 13409 * signed bounds 13410 * 3) the signed bounds cross zero, so they tell us nothing 13411 * about the result 13412 * If the value in dst_reg is known nonnegative, then again the 13413 * unsigned bounds capture the signed bounds. 13414 * Thus, in all cases it suffices to blow away our signed bounds 13415 * and rely on inferring new ones from the unsigned bounds and 13416 * var_off of the result. 13417 */ 13418 dst_reg->s32_min_value = S32_MIN; 13419 dst_reg->s32_max_value = S32_MAX; 13420 13421 dst_reg->var_off = tnum_rshift(subreg, umin_val); 13422 dst_reg->u32_min_value >>= umax_val; 13423 dst_reg->u32_max_value >>= umin_val; 13424 13425 __mark_reg64_unbounded(dst_reg); 13426 __update_reg32_bounds(dst_reg); 13427 } 13428 13429 static void scalar_min_max_rsh(struct bpf_reg_state *dst_reg, 13430 struct bpf_reg_state *src_reg) 13431 { 13432 u64 umax_val = src_reg->umax_value; 13433 u64 umin_val = src_reg->umin_value; 13434 13435 /* BPF_RSH is an unsigned shift. If the value in dst_reg might 13436 * be negative, then either: 13437 * 1) src_reg might be zero, so the sign bit of the result is 13438 * unknown, so we lose our signed bounds 13439 * 2) it's known negative, thus the unsigned bounds capture the 13440 * signed bounds 13441 * 3) the signed bounds cross zero, so they tell us nothing 13442 * about the result 13443 * If the value in dst_reg is known nonnegative, then again the 13444 * unsigned bounds capture the signed bounds. 13445 * Thus, in all cases it suffices to blow away our signed bounds 13446 * and rely on inferring new ones from the unsigned bounds and 13447 * var_off of the result. 13448 */ 13449 dst_reg->smin_value = S64_MIN; 13450 dst_reg->smax_value = S64_MAX; 13451 dst_reg->var_off = tnum_rshift(dst_reg->var_off, umin_val); 13452 dst_reg->umin_value >>= umax_val; 13453 dst_reg->umax_value >>= umin_val; 13454 13455 /* Its not easy to operate on alu32 bounds here because it depends 13456 * on bits being shifted in. Take easy way out and mark unbounded 13457 * so we can recalculate later from tnum. 13458 */ 13459 __mark_reg32_unbounded(dst_reg); 13460 __update_reg_bounds(dst_reg); 13461 } 13462 13463 static void scalar32_min_max_arsh(struct bpf_reg_state *dst_reg, 13464 struct bpf_reg_state *src_reg) 13465 { 13466 u64 umin_val = src_reg->u32_min_value; 13467 13468 /* Upon reaching here, src_known is true and 13469 * umax_val is equal to umin_val. 13470 */ 13471 dst_reg->s32_min_value = (u32)(((s32)dst_reg->s32_min_value) >> umin_val); 13472 dst_reg->s32_max_value = (u32)(((s32)dst_reg->s32_max_value) >> umin_val); 13473 13474 dst_reg->var_off = tnum_arshift(tnum_subreg(dst_reg->var_off), umin_val, 32); 13475 13476 /* blow away the dst_reg umin_value/umax_value and rely on 13477 * dst_reg var_off to refine the result. 13478 */ 13479 dst_reg->u32_min_value = 0; 13480 dst_reg->u32_max_value = U32_MAX; 13481 13482 __mark_reg64_unbounded(dst_reg); 13483 __update_reg32_bounds(dst_reg); 13484 } 13485 13486 static void scalar_min_max_arsh(struct bpf_reg_state *dst_reg, 13487 struct bpf_reg_state *src_reg) 13488 { 13489 u64 umin_val = src_reg->umin_value; 13490 13491 /* Upon reaching here, src_known is true and umax_val is equal 13492 * to umin_val. 13493 */ 13494 dst_reg->smin_value >>= umin_val; 13495 dst_reg->smax_value >>= umin_val; 13496 13497 dst_reg->var_off = tnum_arshift(dst_reg->var_off, umin_val, 64); 13498 13499 /* blow away the dst_reg umin_value/umax_value and rely on 13500 * dst_reg var_off to refine the result. 13501 */ 13502 dst_reg->umin_value = 0; 13503 dst_reg->umax_value = U64_MAX; 13504 13505 /* Its not easy to operate on alu32 bounds here because it depends 13506 * on bits being shifted in from upper 32-bits. Take easy way out 13507 * and mark unbounded so we can recalculate later from tnum. 13508 */ 13509 __mark_reg32_unbounded(dst_reg); 13510 __update_reg_bounds(dst_reg); 13511 } 13512 13513 /* WARNING: This function does calculations on 64-bit values, but the actual 13514 * execution may occur on 32-bit values. Therefore, things like bitshifts 13515 * need extra checks in the 32-bit case. 13516 */ 13517 static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env, 13518 struct bpf_insn *insn, 13519 struct bpf_reg_state *dst_reg, 13520 struct bpf_reg_state src_reg) 13521 { 13522 struct bpf_reg_state *regs = cur_regs(env); 13523 u8 opcode = BPF_OP(insn->code); 13524 bool src_known; 13525 s64 smin_val, smax_val; 13526 u64 umin_val, umax_val; 13527 s32 s32_min_val, s32_max_val; 13528 u32 u32_min_val, u32_max_val; 13529 u64 insn_bitness = (BPF_CLASS(insn->code) == BPF_ALU64) ? 64 : 32; 13530 bool alu32 = (BPF_CLASS(insn->code) != BPF_ALU64); 13531 int ret; 13532 13533 smin_val = src_reg.smin_value; 13534 smax_val = src_reg.smax_value; 13535 umin_val = src_reg.umin_value; 13536 umax_val = src_reg.umax_value; 13537 13538 s32_min_val = src_reg.s32_min_value; 13539 s32_max_val = src_reg.s32_max_value; 13540 u32_min_val = src_reg.u32_min_value; 13541 u32_max_val = src_reg.u32_max_value; 13542 13543 if (alu32) { 13544 src_known = tnum_subreg_is_const(src_reg.var_off); 13545 if ((src_known && 13546 (s32_min_val != s32_max_val || u32_min_val != u32_max_val)) || 13547 s32_min_val > s32_max_val || u32_min_val > u32_max_val) { 13548 /* Taint dst register if offset had invalid bounds 13549 * derived from e.g. dead branches. 13550 */ 13551 __mark_reg_unknown(env, dst_reg); 13552 return 0; 13553 } 13554 } else { 13555 src_known = tnum_is_const(src_reg.var_off); 13556 if ((src_known && 13557 (smin_val != smax_val || umin_val != umax_val)) || 13558 smin_val > smax_val || umin_val > umax_val) { 13559 /* Taint dst register if offset had invalid bounds 13560 * derived from e.g. dead branches. 13561 */ 13562 __mark_reg_unknown(env, dst_reg); 13563 return 0; 13564 } 13565 } 13566 13567 if (!src_known && 13568 opcode != BPF_ADD && opcode != BPF_SUB && opcode != BPF_AND) { 13569 __mark_reg_unknown(env, dst_reg); 13570 return 0; 13571 } 13572 13573 if (sanitize_needed(opcode)) { 13574 ret = sanitize_val_alu(env, insn); 13575 if (ret < 0) 13576 return sanitize_err(env, insn, ret, NULL, NULL); 13577 } 13578 13579 /* Calculate sign/unsigned bounds and tnum for alu32 and alu64 bit ops. 13580 * There are two classes of instructions: The first class we track both 13581 * alu32 and alu64 sign/unsigned bounds independently this provides the 13582 * greatest amount of precision when alu operations are mixed with jmp32 13583 * operations. These operations are BPF_ADD, BPF_SUB, BPF_MUL, BPF_ADD, 13584 * and BPF_OR. This is possible because these ops have fairly easy to 13585 * understand and calculate behavior in both 32-bit and 64-bit alu ops. 13586 * See alu32 verifier tests for examples. The second class of 13587 * operations, BPF_LSH, BPF_RSH, and BPF_ARSH, however are not so easy 13588 * with regards to tracking sign/unsigned bounds because the bits may 13589 * cross subreg boundaries in the alu64 case. When this happens we mark 13590 * the reg unbounded in the subreg bound space and use the resulting 13591 * tnum to calculate an approximation of the sign/unsigned bounds. 13592 */ 13593 switch (opcode) { 13594 case BPF_ADD: 13595 scalar32_min_max_add(dst_reg, &src_reg); 13596 scalar_min_max_add(dst_reg, &src_reg); 13597 dst_reg->var_off = tnum_add(dst_reg->var_off, src_reg.var_off); 13598 break; 13599 case BPF_SUB: 13600 scalar32_min_max_sub(dst_reg, &src_reg); 13601 scalar_min_max_sub(dst_reg, &src_reg); 13602 dst_reg->var_off = tnum_sub(dst_reg->var_off, src_reg.var_off); 13603 break; 13604 case BPF_MUL: 13605 dst_reg->var_off = tnum_mul(dst_reg->var_off, src_reg.var_off); 13606 scalar32_min_max_mul(dst_reg, &src_reg); 13607 scalar_min_max_mul(dst_reg, &src_reg); 13608 break; 13609 case BPF_AND: 13610 dst_reg->var_off = tnum_and(dst_reg->var_off, src_reg.var_off); 13611 scalar32_min_max_and(dst_reg, &src_reg); 13612 scalar_min_max_and(dst_reg, &src_reg); 13613 break; 13614 case BPF_OR: 13615 dst_reg->var_off = tnum_or(dst_reg->var_off, src_reg.var_off); 13616 scalar32_min_max_or(dst_reg, &src_reg); 13617 scalar_min_max_or(dst_reg, &src_reg); 13618 break; 13619 case BPF_XOR: 13620 dst_reg->var_off = tnum_xor(dst_reg->var_off, src_reg.var_off); 13621 scalar32_min_max_xor(dst_reg, &src_reg); 13622 scalar_min_max_xor(dst_reg, &src_reg); 13623 break; 13624 case BPF_LSH: 13625 if (umax_val >= insn_bitness) { 13626 /* Shifts greater than 31 or 63 are undefined. 13627 * This includes shifts by a negative number. 13628 */ 13629 mark_reg_unknown(env, regs, insn->dst_reg); 13630 break; 13631 } 13632 if (alu32) 13633 scalar32_min_max_lsh(dst_reg, &src_reg); 13634 else 13635 scalar_min_max_lsh(dst_reg, &src_reg); 13636 break; 13637 case BPF_RSH: 13638 if (umax_val >= insn_bitness) { 13639 /* Shifts greater than 31 or 63 are undefined. 13640 * This includes shifts by a negative number. 13641 */ 13642 mark_reg_unknown(env, regs, insn->dst_reg); 13643 break; 13644 } 13645 if (alu32) 13646 scalar32_min_max_rsh(dst_reg, &src_reg); 13647 else 13648 scalar_min_max_rsh(dst_reg, &src_reg); 13649 break; 13650 case BPF_ARSH: 13651 if (umax_val >= insn_bitness) { 13652 /* Shifts greater than 31 or 63 are undefined. 13653 * This includes shifts by a negative number. 13654 */ 13655 mark_reg_unknown(env, regs, insn->dst_reg); 13656 break; 13657 } 13658 if (alu32) 13659 scalar32_min_max_arsh(dst_reg, &src_reg); 13660 else 13661 scalar_min_max_arsh(dst_reg, &src_reg); 13662 break; 13663 default: 13664 mark_reg_unknown(env, regs, insn->dst_reg); 13665 break; 13666 } 13667 13668 /* ALU32 ops are zero extended into 64bit register */ 13669 if (alu32) 13670 zext_32_to_64(dst_reg); 13671 reg_bounds_sync(dst_reg); 13672 return 0; 13673 } 13674 13675 /* Handles ALU ops other than BPF_END, BPF_NEG and BPF_MOV: computes new min/max 13676 * and var_off. 13677 */ 13678 static int adjust_reg_min_max_vals(struct bpf_verifier_env *env, 13679 struct bpf_insn *insn) 13680 { 13681 struct bpf_verifier_state *vstate = env->cur_state; 13682 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 13683 struct bpf_reg_state *regs = state->regs, *dst_reg, *src_reg; 13684 struct bpf_reg_state *ptr_reg = NULL, off_reg = {0}; 13685 u8 opcode = BPF_OP(insn->code); 13686 int err; 13687 13688 dst_reg = ®s[insn->dst_reg]; 13689 src_reg = NULL; 13690 if (dst_reg->type != SCALAR_VALUE) 13691 ptr_reg = dst_reg; 13692 else 13693 /* Make sure ID is cleared otherwise dst_reg min/max could be 13694 * incorrectly propagated into other registers by find_equal_scalars() 13695 */ 13696 dst_reg->id = 0; 13697 if (BPF_SRC(insn->code) == BPF_X) { 13698 src_reg = ®s[insn->src_reg]; 13699 if (src_reg->type != SCALAR_VALUE) { 13700 if (dst_reg->type != SCALAR_VALUE) { 13701 /* Combining two pointers by any ALU op yields 13702 * an arbitrary scalar. Disallow all math except 13703 * pointer subtraction 13704 */ 13705 if (opcode == BPF_SUB && env->allow_ptr_leaks) { 13706 mark_reg_unknown(env, regs, insn->dst_reg); 13707 return 0; 13708 } 13709 verbose(env, "R%d pointer %s pointer prohibited\n", 13710 insn->dst_reg, 13711 bpf_alu_string[opcode >> 4]); 13712 return -EACCES; 13713 } else { 13714 /* scalar += pointer 13715 * This is legal, but we have to reverse our 13716 * src/dest handling in computing the range 13717 */ 13718 err = mark_chain_precision(env, insn->dst_reg); 13719 if (err) 13720 return err; 13721 return adjust_ptr_min_max_vals(env, insn, 13722 src_reg, dst_reg); 13723 } 13724 } else if (ptr_reg) { 13725 /* pointer += scalar */ 13726 err = mark_chain_precision(env, insn->src_reg); 13727 if (err) 13728 return err; 13729 return adjust_ptr_min_max_vals(env, insn, 13730 dst_reg, src_reg); 13731 } else if (dst_reg->precise) { 13732 /* if dst_reg is precise, src_reg should be precise as well */ 13733 err = mark_chain_precision(env, insn->src_reg); 13734 if (err) 13735 return err; 13736 } 13737 } else { 13738 /* Pretend the src is a reg with a known value, since we only 13739 * need to be able to read from this state. 13740 */ 13741 off_reg.type = SCALAR_VALUE; 13742 __mark_reg_known(&off_reg, insn->imm); 13743 src_reg = &off_reg; 13744 if (ptr_reg) /* pointer += K */ 13745 return adjust_ptr_min_max_vals(env, insn, 13746 ptr_reg, src_reg); 13747 } 13748 13749 /* Got here implies adding two SCALAR_VALUEs */ 13750 if (WARN_ON_ONCE(ptr_reg)) { 13751 print_verifier_state(env, state, true); 13752 verbose(env, "verifier internal error: unexpected ptr_reg\n"); 13753 return -EINVAL; 13754 } 13755 if (WARN_ON(!src_reg)) { 13756 print_verifier_state(env, state, true); 13757 verbose(env, "verifier internal error: no src_reg\n"); 13758 return -EINVAL; 13759 } 13760 return adjust_scalar_min_max_vals(env, insn, dst_reg, *src_reg); 13761 } 13762 13763 /* check validity of 32-bit and 64-bit arithmetic operations */ 13764 static int check_alu_op(struct bpf_verifier_env *env, struct bpf_insn *insn) 13765 { 13766 struct bpf_reg_state *regs = cur_regs(env); 13767 u8 opcode = BPF_OP(insn->code); 13768 int err; 13769 13770 if (opcode == BPF_END || opcode == BPF_NEG) { 13771 if (opcode == BPF_NEG) { 13772 if (BPF_SRC(insn->code) != BPF_K || 13773 insn->src_reg != BPF_REG_0 || 13774 insn->off != 0 || insn->imm != 0) { 13775 verbose(env, "BPF_NEG uses reserved fields\n"); 13776 return -EINVAL; 13777 } 13778 } else { 13779 if (insn->src_reg != BPF_REG_0 || insn->off != 0 || 13780 (insn->imm != 16 && insn->imm != 32 && insn->imm != 64) || 13781 (BPF_CLASS(insn->code) == BPF_ALU64 && 13782 BPF_SRC(insn->code) != BPF_TO_LE)) { 13783 verbose(env, "BPF_END uses reserved fields\n"); 13784 return -EINVAL; 13785 } 13786 } 13787 13788 /* check src operand */ 13789 err = check_reg_arg(env, insn->dst_reg, SRC_OP); 13790 if (err) 13791 return err; 13792 13793 if (is_pointer_value(env, insn->dst_reg)) { 13794 verbose(env, "R%d pointer arithmetic prohibited\n", 13795 insn->dst_reg); 13796 return -EACCES; 13797 } 13798 13799 /* check dest operand */ 13800 err = check_reg_arg(env, insn->dst_reg, DST_OP); 13801 if (err) 13802 return err; 13803 13804 } else if (opcode == BPF_MOV) { 13805 13806 if (BPF_SRC(insn->code) == BPF_X) { 13807 if (insn->imm != 0) { 13808 verbose(env, "BPF_MOV uses reserved fields\n"); 13809 return -EINVAL; 13810 } 13811 13812 if (BPF_CLASS(insn->code) == BPF_ALU) { 13813 if (insn->off != 0 && insn->off != 8 && insn->off != 16) { 13814 verbose(env, "BPF_MOV uses reserved fields\n"); 13815 return -EINVAL; 13816 } 13817 } else { 13818 if (insn->off != 0 && insn->off != 8 && insn->off != 16 && 13819 insn->off != 32) { 13820 verbose(env, "BPF_MOV uses reserved fields\n"); 13821 return -EINVAL; 13822 } 13823 } 13824 13825 /* check src operand */ 13826 err = check_reg_arg(env, insn->src_reg, SRC_OP); 13827 if (err) 13828 return err; 13829 } else { 13830 if (insn->src_reg != BPF_REG_0 || insn->off != 0) { 13831 verbose(env, "BPF_MOV uses reserved fields\n"); 13832 return -EINVAL; 13833 } 13834 } 13835 13836 /* check dest operand, mark as required later */ 13837 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK); 13838 if (err) 13839 return err; 13840 13841 if (BPF_SRC(insn->code) == BPF_X) { 13842 struct bpf_reg_state *src_reg = regs + insn->src_reg; 13843 struct bpf_reg_state *dst_reg = regs + insn->dst_reg; 13844 bool need_id = src_reg->type == SCALAR_VALUE && !src_reg->id && 13845 !tnum_is_const(src_reg->var_off); 13846 13847 if (BPF_CLASS(insn->code) == BPF_ALU64) { 13848 if (insn->off == 0) { 13849 /* case: R1 = R2 13850 * copy register state to dest reg 13851 */ 13852 if (need_id) 13853 /* Assign src and dst registers the same ID 13854 * that will be used by find_equal_scalars() 13855 * to propagate min/max range. 13856 */ 13857 src_reg->id = ++env->id_gen; 13858 copy_register_state(dst_reg, src_reg); 13859 dst_reg->live |= REG_LIVE_WRITTEN; 13860 dst_reg->subreg_def = DEF_NOT_SUBREG; 13861 } else { 13862 /* case: R1 = (s8, s16 s32)R2 */ 13863 if (is_pointer_value(env, insn->src_reg)) { 13864 verbose(env, 13865 "R%d sign-extension part of pointer\n", 13866 insn->src_reg); 13867 return -EACCES; 13868 } else if (src_reg->type == SCALAR_VALUE) { 13869 bool no_sext; 13870 13871 no_sext = src_reg->umax_value < (1ULL << (insn->off - 1)); 13872 if (no_sext && need_id) 13873 src_reg->id = ++env->id_gen; 13874 copy_register_state(dst_reg, src_reg); 13875 if (!no_sext) 13876 dst_reg->id = 0; 13877 coerce_reg_to_size_sx(dst_reg, insn->off >> 3); 13878 dst_reg->live |= REG_LIVE_WRITTEN; 13879 dst_reg->subreg_def = DEF_NOT_SUBREG; 13880 } else { 13881 mark_reg_unknown(env, regs, insn->dst_reg); 13882 } 13883 } 13884 } else { 13885 /* R1 = (u32) R2 */ 13886 if (is_pointer_value(env, insn->src_reg)) { 13887 verbose(env, 13888 "R%d partial copy of pointer\n", 13889 insn->src_reg); 13890 return -EACCES; 13891 } else if (src_reg->type == SCALAR_VALUE) { 13892 if (insn->off == 0) { 13893 bool is_src_reg_u32 = src_reg->umax_value <= U32_MAX; 13894 13895 if (is_src_reg_u32 && need_id) 13896 src_reg->id = ++env->id_gen; 13897 copy_register_state(dst_reg, src_reg); 13898 /* Make sure ID is cleared if src_reg is not in u32 13899 * range otherwise dst_reg min/max could be incorrectly 13900 * propagated into src_reg by find_equal_scalars() 13901 */ 13902 if (!is_src_reg_u32) 13903 dst_reg->id = 0; 13904 dst_reg->live |= REG_LIVE_WRITTEN; 13905 dst_reg->subreg_def = env->insn_idx + 1; 13906 } else { 13907 /* case: W1 = (s8, s16)W2 */ 13908 bool no_sext = src_reg->umax_value < (1ULL << (insn->off - 1)); 13909 13910 if (no_sext && need_id) 13911 src_reg->id = ++env->id_gen; 13912 copy_register_state(dst_reg, src_reg); 13913 if (!no_sext) 13914 dst_reg->id = 0; 13915 dst_reg->live |= REG_LIVE_WRITTEN; 13916 dst_reg->subreg_def = env->insn_idx + 1; 13917 coerce_subreg_to_size_sx(dst_reg, insn->off >> 3); 13918 } 13919 } else { 13920 mark_reg_unknown(env, regs, 13921 insn->dst_reg); 13922 } 13923 zext_32_to_64(dst_reg); 13924 reg_bounds_sync(dst_reg); 13925 } 13926 } else { 13927 /* case: R = imm 13928 * remember the value we stored into this reg 13929 */ 13930 /* clear any state __mark_reg_known doesn't set */ 13931 mark_reg_unknown(env, regs, insn->dst_reg); 13932 regs[insn->dst_reg].type = SCALAR_VALUE; 13933 if (BPF_CLASS(insn->code) == BPF_ALU64) { 13934 __mark_reg_known(regs + insn->dst_reg, 13935 insn->imm); 13936 } else { 13937 __mark_reg_known(regs + insn->dst_reg, 13938 (u32)insn->imm); 13939 } 13940 } 13941 13942 } else if (opcode > BPF_END) { 13943 verbose(env, "invalid BPF_ALU opcode %x\n", opcode); 13944 return -EINVAL; 13945 13946 } else { /* all other ALU ops: and, sub, xor, add, ... */ 13947 13948 if (BPF_SRC(insn->code) == BPF_X) { 13949 if (insn->imm != 0 || insn->off > 1 || 13950 (insn->off == 1 && opcode != BPF_MOD && opcode != BPF_DIV)) { 13951 verbose(env, "BPF_ALU uses reserved fields\n"); 13952 return -EINVAL; 13953 } 13954 /* check src1 operand */ 13955 err = check_reg_arg(env, insn->src_reg, SRC_OP); 13956 if (err) 13957 return err; 13958 } else { 13959 if (insn->src_reg != BPF_REG_0 || insn->off > 1 || 13960 (insn->off == 1 && opcode != BPF_MOD && opcode != BPF_DIV)) { 13961 verbose(env, "BPF_ALU uses reserved fields\n"); 13962 return -EINVAL; 13963 } 13964 } 13965 13966 /* check src2 operand */ 13967 err = check_reg_arg(env, insn->dst_reg, SRC_OP); 13968 if (err) 13969 return err; 13970 13971 if ((opcode == BPF_MOD || opcode == BPF_DIV) && 13972 BPF_SRC(insn->code) == BPF_K && insn->imm == 0) { 13973 verbose(env, "div by zero\n"); 13974 return -EINVAL; 13975 } 13976 13977 if ((opcode == BPF_LSH || opcode == BPF_RSH || 13978 opcode == BPF_ARSH) && BPF_SRC(insn->code) == BPF_K) { 13979 int size = BPF_CLASS(insn->code) == BPF_ALU64 ? 64 : 32; 13980 13981 if (insn->imm < 0 || insn->imm >= size) { 13982 verbose(env, "invalid shift %d\n", insn->imm); 13983 return -EINVAL; 13984 } 13985 } 13986 13987 /* check dest operand */ 13988 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK); 13989 if (err) 13990 return err; 13991 13992 return adjust_reg_min_max_vals(env, insn); 13993 } 13994 13995 return 0; 13996 } 13997 13998 static void find_good_pkt_pointers(struct bpf_verifier_state *vstate, 13999 struct bpf_reg_state *dst_reg, 14000 enum bpf_reg_type type, 14001 bool range_right_open) 14002 { 14003 struct bpf_func_state *state; 14004 struct bpf_reg_state *reg; 14005 int new_range; 14006 14007 if (dst_reg->off < 0 || 14008 (dst_reg->off == 0 && range_right_open)) 14009 /* This doesn't give us any range */ 14010 return; 14011 14012 if (dst_reg->umax_value > MAX_PACKET_OFF || 14013 dst_reg->umax_value + dst_reg->off > MAX_PACKET_OFF) 14014 /* Risk of overflow. For instance, ptr + (1<<63) may be less 14015 * than pkt_end, but that's because it's also less than pkt. 14016 */ 14017 return; 14018 14019 new_range = dst_reg->off; 14020 if (range_right_open) 14021 new_range++; 14022 14023 /* Examples for register markings: 14024 * 14025 * pkt_data in dst register: 14026 * 14027 * r2 = r3; 14028 * r2 += 8; 14029 * if (r2 > pkt_end) goto <handle exception> 14030 * <access okay> 14031 * 14032 * r2 = r3; 14033 * r2 += 8; 14034 * if (r2 < pkt_end) goto <access okay> 14035 * <handle exception> 14036 * 14037 * Where: 14038 * r2 == dst_reg, pkt_end == src_reg 14039 * r2=pkt(id=n,off=8,r=0) 14040 * r3=pkt(id=n,off=0,r=0) 14041 * 14042 * pkt_data in src register: 14043 * 14044 * r2 = r3; 14045 * r2 += 8; 14046 * if (pkt_end >= r2) goto <access okay> 14047 * <handle exception> 14048 * 14049 * r2 = r3; 14050 * r2 += 8; 14051 * if (pkt_end <= r2) goto <handle exception> 14052 * <access okay> 14053 * 14054 * Where: 14055 * pkt_end == dst_reg, r2 == src_reg 14056 * r2=pkt(id=n,off=8,r=0) 14057 * r3=pkt(id=n,off=0,r=0) 14058 * 14059 * Find register r3 and mark its range as r3=pkt(id=n,off=0,r=8) 14060 * or r3=pkt(id=n,off=0,r=8-1), so that range of bytes [r3, r3 + 8) 14061 * and [r3, r3 + 8-1) respectively is safe to access depending on 14062 * the check. 14063 */ 14064 14065 /* If our ids match, then we must have the same max_value. And we 14066 * don't care about the other reg's fixed offset, since if it's too big 14067 * the range won't allow anything. 14068 * dst_reg->off is known < MAX_PACKET_OFF, therefore it fits in a u16. 14069 */ 14070 bpf_for_each_reg_in_vstate(vstate, state, reg, ({ 14071 if (reg->type == type && reg->id == dst_reg->id) 14072 /* keep the maximum range already checked */ 14073 reg->range = max(reg->range, new_range); 14074 })); 14075 } 14076 14077 static int is_branch32_taken(struct bpf_reg_state *reg, u32 val, u8 opcode) 14078 { 14079 struct tnum subreg = tnum_subreg(reg->var_off); 14080 s32 sval = (s32)val; 14081 14082 switch (opcode) { 14083 case BPF_JEQ: 14084 if (tnum_is_const(subreg)) 14085 return !!tnum_equals_const(subreg, val); 14086 else if (val < reg->u32_min_value || val > reg->u32_max_value) 14087 return 0; 14088 else if (sval < reg->s32_min_value || sval > reg->s32_max_value) 14089 return 0; 14090 break; 14091 case BPF_JNE: 14092 if (tnum_is_const(subreg)) 14093 return !tnum_equals_const(subreg, val); 14094 else if (val < reg->u32_min_value || val > reg->u32_max_value) 14095 return 1; 14096 else if (sval < reg->s32_min_value || sval > reg->s32_max_value) 14097 return 1; 14098 break; 14099 case BPF_JSET: 14100 if ((~subreg.mask & subreg.value) & val) 14101 return 1; 14102 if (!((subreg.mask | subreg.value) & val)) 14103 return 0; 14104 break; 14105 case BPF_JGT: 14106 if (reg->u32_min_value > val) 14107 return 1; 14108 else if (reg->u32_max_value <= val) 14109 return 0; 14110 break; 14111 case BPF_JSGT: 14112 if (reg->s32_min_value > sval) 14113 return 1; 14114 else if (reg->s32_max_value <= sval) 14115 return 0; 14116 break; 14117 case BPF_JLT: 14118 if (reg->u32_max_value < val) 14119 return 1; 14120 else if (reg->u32_min_value >= val) 14121 return 0; 14122 break; 14123 case BPF_JSLT: 14124 if (reg->s32_max_value < sval) 14125 return 1; 14126 else if (reg->s32_min_value >= sval) 14127 return 0; 14128 break; 14129 case BPF_JGE: 14130 if (reg->u32_min_value >= val) 14131 return 1; 14132 else if (reg->u32_max_value < val) 14133 return 0; 14134 break; 14135 case BPF_JSGE: 14136 if (reg->s32_min_value >= sval) 14137 return 1; 14138 else if (reg->s32_max_value < sval) 14139 return 0; 14140 break; 14141 case BPF_JLE: 14142 if (reg->u32_max_value <= val) 14143 return 1; 14144 else if (reg->u32_min_value > val) 14145 return 0; 14146 break; 14147 case BPF_JSLE: 14148 if (reg->s32_max_value <= sval) 14149 return 1; 14150 else if (reg->s32_min_value > sval) 14151 return 0; 14152 break; 14153 } 14154 14155 return -1; 14156 } 14157 14158 14159 static int is_branch64_taken(struct bpf_reg_state *reg, u64 val, u8 opcode) 14160 { 14161 s64 sval = (s64)val; 14162 14163 switch (opcode) { 14164 case BPF_JEQ: 14165 if (tnum_is_const(reg->var_off)) 14166 return !!tnum_equals_const(reg->var_off, val); 14167 else if (val < reg->umin_value || val > reg->umax_value) 14168 return 0; 14169 else if (sval < reg->smin_value || sval > reg->smax_value) 14170 return 0; 14171 break; 14172 case BPF_JNE: 14173 if (tnum_is_const(reg->var_off)) 14174 return !tnum_equals_const(reg->var_off, val); 14175 else if (val < reg->umin_value || val > reg->umax_value) 14176 return 1; 14177 else if (sval < reg->smin_value || sval > reg->smax_value) 14178 return 1; 14179 break; 14180 case BPF_JSET: 14181 if ((~reg->var_off.mask & reg->var_off.value) & val) 14182 return 1; 14183 if (!((reg->var_off.mask | reg->var_off.value) & val)) 14184 return 0; 14185 break; 14186 case BPF_JGT: 14187 if (reg->umin_value > val) 14188 return 1; 14189 else if (reg->umax_value <= val) 14190 return 0; 14191 break; 14192 case BPF_JSGT: 14193 if (reg->smin_value > sval) 14194 return 1; 14195 else if (reg->smax_value <= sval) 14196 return 0; 14197 break; 14198 case BPF_JLT: 14199 if (reg->umax_value < val) 14200 return 1; 14201 else if (reg->umin_value >= val) 14202 return 0; 14203 break; 14204 case BPF_JSLT: 14205 if (reg->smax_value < sval) 14206 return 1; 14207 else if (reg->smin_value >= sval) 14208 return 0; 14209 break; 14210 case BPF_JGE: 14211 if (reg->umin_value >= val) 14212 return 1; 14213 else if (reg->umax_value < val) 14214 return 0; 14215 break; 14216 case BPF_JSGE: 14217 if (reg->smin_value >= sval) 14218 return 1; 14219 else if (reg->smax_value < sval) 14220 return 0; 14221 break; 14222 case BPF_JLE: 14223 if (reg->umax_value <= val) 14224 return 1; 14225 else if (reg->umin_value > val) 14226 return 0; 14227 break; 14228 case BPF_JSLE: 14229 if (reg->smax_value <= sval) 14230 return 1; 14231 else if (reg->smin_value > sval) 14232 return 0; 14233 break; 14234 } 14235 14236 return -1; 14237 } 14238 14239 /* compute branch direction of the expression "if (reg opcode val) goto target;" 14240 * and return: 14241 * 1 - branch will be taken and "goto target" will be executed 14242 * 0 - branch will not be taken and fall-through to next insn 14243 * -1 - unknown. Example: "if (reg < 5)" is unknown when register value 14244 * range [0,10] 14245 */ 14246 static int is_branch_taken(struct bpf_reg_state *reg, u64 val, u8 opcode, 14247 bool is_jmp32) 14248 { 14249 if (__is_pointer_value(false, reg)) { 14250 if (!reg_not_null(reg)) 14251 return -1; 14252 14253 /* If pointer is valid tests against zero will fail so we can 14254 * use this to direct branch taken. 14255 */ 14256 if (val != 0) 14257 return -1; 14258 14259 switch (opcode) { 14260 case BPF_JEQ: 14261 return 0; 14262 case BPF_JNE: 14263 return 1; 14264 default: 14265 return -1; 14266 } 14267 } 14268 14269 if (is_jmp32) 14270 return is_branch32_taken(reg, val, opcode); 14271 return is_branch64_taken(reg, val, opcode); 14272 } 14273 14274 static int flip_opcode(u32 opcode) 14275 { 14276 /* How can we transform "a <op> b" into "b <op> a"? */ 14277 static const u8 opcode_flip[16] = { 14278 /* these stay the same */ 14279 [BPF_JEQ >> 4] = BPF_JEQ, 14280 [BPF_JNE >> 4] = BPF_JNE, 14281 [BPF_JSET >> 4] = BPF_JSET, 14282 /* these swap "lesser" and "greater" (L and G in the opcodes) */ 14283 [BPF_JGE >> 4] = BPF_JLE, 14284 [BPF_JGT >> 4] = BPF_JLT, 14285 [BPF_JLE >> 4] = BPF_JGE, 14286 [BPF_JLT >> 4] = BPF_JGT, 14287 [BPF_JSGE >> 4] = BPF_JSLE, 14288 [BPF_JSGT >> 4] = BPF_JSLT, 14289 [BPF_JSLE >> 4] = BPF_JSGE, 14290 [BPF_JSLT >> 4] = BPF_JSGT 14291 }; 14292 return opcode_flip[opcode >> 4]; 14293 } 14294 14295 static int is_pkt_ptr_branch_taken(struct bpf_reg_state *dst_reg, 14296 struct bpf_reg_state *src_reg, 14297 u8 opcode) 14298 { 14299 struct bpf_reg_state *pkt; 14300 14301 if (src_reg->type == PTR_TO_PACKET_END) { 14302 pkt = dst_reg; 14303 } else if (dst_reg->type == PTR_TO_PACKET_END) { 14304 pkt = src_reg; 14305 opcode = flip_opcode(opcode); 14306 } else { 14307 return -1; 14308 } 14309 14310 if (pkt->range >= 0) 14311 return -1; 14312 14313 switch (opcode) { 14314 case BPF_JLE: 14315 /* pkt <= pkt_end */ 14316 fallthrough; 14317 case BPF_JGT: 14318 /* pkt > pkt_end */ 14319 if (pkt->range == BEYOND_PKT_END) 14320 /* pkt has at last one extra byte beyond pkt_end */ 14321 return opcode == BPF_JGT; 14322 break; 14323 case BPF_JLT: 14324 /* pkt < pkt_end */ 14325 fallthrough; 14326 case BPF_JGE: 14327 /* pkt >= pkt_end */ 14328 if (pkt->range == BEYOND_PKT_END || pkt->range == AT_PKT_END) 14329 return opcode == BPF_JGE; 14330 break; 14331 } 14332 return -1; 14333 } 14334 14335 /* Adjusts the register min/max values in the case that the dst_reg is the 14336 * variable register that we are working on, and src_reg is a constant or we're 14337 * simply doing a BPF_K check. 14338 * In JEQ/JNE cases we also adjust the var_off values. 14339 */ 14340 static void reg_set_min_max(struct bpf_reg_state *true_reg, 14341 struct bpf_reg_state *false_reg, 14342 u64 val, u32 val32, 14343 u8 opcode, bool is_jmp32) 14344 { 14345 struct tnum false_32off = tnum_subreg(false_reg->var_off); 14346 struct tnum false_64off = false_reg->var_off; 14347 struct tnum true_32off = tnum_subreg(true_reg->var_off); 14348 struct tnum true_64off = true_reg->var_off; 14349 s64 sval = (s64)val; 14350 s32 sval32 = (s32)val32; 14351 14352 /* If the dst_reg is a pointer, we can't learn anything about its 14353 * variable offset from the compare (unless src_reg were a pointer into 14354 * the same object, but we don't bother with that. 14355 * Since false_reg and true_reg have the same type by construction, we 14356 * only need to check one of them for pointerness. 14357 */ 14358 if (__is_pointer_value(false, false_reg)) 14359 return; 14360 14361 switch (opcode) { 14362 /* JEQ/JNE comparison doesn't change the register equivalence. 14363 * 14364 * r1 = r2; 14365 * if (r1 == 42) goto label; 14366 * ... 14367 * label: // here both r1 and r2 are known to be 42. 14368 * 14369 * Hence when marking register as known preserve it's ID. 14370 */ 14371 case BPF_JEQ: 14372 if (is_jmp32) { 14373 __mark_reg32_known(true_reg, val32); 14374 true_32off = tnum_subreg(true_reg->var_off); 14375 } else { 14376 ___mark_reg_known(true_reg, val); 14377 true_64off = true_reg->var_off; 14378 } 14379 break; 14380 case BPF_JNE: 14381 if (is_jmp32) { 14382 __mark_reg32_known(false_reg, val32); 14383 false_32off = tnum_subreg(false_reg->var_off); 14384 } else { 14385 ___mark_reg_known(false_reg, val); 14386 false_64off = false_reg->var_off; 14387 } 14388 break; 14389 case BPF_JSET: 14390 if (is_jmp32) { 14391 false_32off = tnum_and(false_32off, tnum_const(~val32)); 14392 if (is_power_of_2(val32)) 14393 true_32off = tnum_or(true_32off, 14394 tnum_const(val32)); 14395 } else { 14396 false_64off = tnum_and(false_64off, tnum_const(~val)); 14397 if (is_power_of_2(val)) 14398 true_64off = tnum_or(true_64off, 14399 tnum_const(val)); 14400 } 14401 break; 14402 case BPF_JGE: 14403 case BPF_JGT: 14404 { 14405 if (is_jmp32) { 14406 u32 false_umax = opcode == BPF_JGT ? val32 : val32 - 1; 14407 u32 true_umin = opcode == BPF_JGT ? val32 + 1 : val32; 14408 14409 false_reg->u32_max_value = min(false_reg->u32_max_value, 14410 false_umax); 14411 true_reg->u32_min_value = max(true_reg->u32_min_value, 14412 true_umin); 14413 } else { 14414 u64 false_umax = opcode == BPF_JGT ? val : val - 1; 14415 u64 true_umin = opcode == BPF_JGT ? val + 1 : val; 14416 14417 false_reg->umax_value = min(false_reg->umax_value, false_umax); 14418 true_reg->umin_value = max(true_reg->umin_value, true_umin); 14419 } 14420 break; 14421 } 14422 case BPF_JSGE: 14423 case BPF_JSGT: 14424 { 14425 if (is_jmp32) { 14426 s32 false_smax = opcode == BPF_JSGT ? sval32 : sval32 - 1; 14427 s32 true_smin = opcode == BPF_JSGT ? sval32 + 1 : sval32; 14428 14429 false_reg->s32_max_value = min(false_reg->s32_max_value, false_smax); 14430 true_reg->s32_min_value = max(true_reg->s32_min_value, true_smin); 14431 } else { 14432 s64 false_smax = opcode == BPF_JSGT ? sval : sval - 1; 14433 s64 true_smin = opcode == BPF_JSGT ? sval + 1 : sval; 14434 14435 false_reg->smax_value = min(false_reg->smax_value, false_smax); 14436 true_reg->smin_value = max(true_reg->smin_value, true_smin); 14437 } 14438 break; 14439 } 14440 case BPF_JLE: 14441 case BPF_JLT: 14442 { 14443 if (is_jmp32) { 14444 u32 false_umin = opcode == BPF_JLT ? val32 : val32 + 1; 14445 u32 true_umax = opcode == BPF_JLT ? val32 - 1 : val32; 14446 14447 false_reg->u32_min_value = max(false_reg->u32_min_value, 14448 false_umin); 14449 true_reg->u32_max_value = min(true_reg->u32_max_value, 14450 true_umax); 14451 } else { 14452 u64 false_umin = opcode == BPF_JLT ? val : val + 1; 14453 u64 true_umax = opcode == BPF_JLT ? val - 1 : val; 14454 14455 false_reg->umin_value = max(false_reg->umin_value, false_umin); 14456 true_reg->umax_value = min(true_reg->umax_value, true_umax); 14457 } 14458 break; 14459 } 14460 case BPF_JSLE: 14461 case BPF_JSLT: 14462 { 14463 if (is_jmp32) { 14464 s32 false_smin = opcode == BPF_JSLT ? sval32 : sval32 + 1; 14465 s32 true_smax = opcode == BPF_JSLT ? sval32 - 1 : sval32; 14466 14467 false_reg->s32_min_value = max(false_reg->s32_min_value, false_smin); 14468 true_reg->s32_max_value = min(true_reg->s32_max_value, true_smax); 14469 } else { 14470 s64 false_smin = opcode == BPF_JSLT ? sval : sval + 1; 14471 s64 true_smax = opcode == BPF_JSLT ? sval - 1 : sval; 14472 14473 false_reg->smin_value = max(false_reg->smin_value, false_smin); 14474 true_reg->smax_value = min(true_reg->smax_value, true_smax); 14475 } 14476 break; 14477 } 14478 default: 14479 return; 14480 } 14481 14482 if (is_jmp32) { 14483 false_reg->var_off = tnum_or(tnum_clear_subreg(false_64off), 14484 tnum_subreg(false_32off)); 14485 true_reg->var_off = tnum_or(tnum_clear_subreg(true_64off), 14486 tnum_subreg(true_32off)); 14487 __reg_combine_32_into_64(false_reg); 14488 __reg_combine_32_into_64(true_reg); 14489 } else { 14490 false_reg->var_off = false_64off; 14491 true_reg->var_off = true_64off; 14492 __reg_combine_64_into_32(false_reg); 14493 __reg_combine_64_into_32(true_reg); 14494 } 14495 } 14496 14497 /* Same as above, but for the case that dst_reg holds a constant and src_reg is 14498 * the variable reg. 14499 */ 14500 static void reg_set_min_max_inv(struct bpf_reg_state *true_reg, 14501 struct bpf_reg_state *false_reg, 14502 u64 val, u32 val32, 14503 u8 opcode, bool is_jmp32) 14504 { 14505 opcode = flip_opcode(opcode); 14506 /* This uses zero as "not present in table"; luckily the zero opcode, 14507 * BPF_JA, can't get here. 14508 */ 14509 if (opcode) 14510 reg_set_min_max(true_reg, false_reg, val, val32, opcode, is_jmp32); 14511 } 14512 14513 /* Regs are known to be equal, so intersect their min/max/var_off */ 14514 static void __reg_combine_min_max(struct bpf_reg_state *src_reg, 14515 struct bpf_reg_state *dst_reg) 14516 { 14517 src_reg->umin_value = dst_reg->umin_value = max(src_reg->umin_value, 14518 dst_reg->umin_value); 14519 src_reg->umax_value = dst_reg->umax_value = min(src_reg->umax_value, 14520 dst_reg->umax_value); 14521 src_reg->smin_value = dst_reg->smin_value = max(src_reg->smin_value, 14522 dst_reg->smin_value); 14523 src_reg->smax_value = dst_reg->smax_value = min(src_reg->smax_value, 14524 dst_reg->smax_value); 14525 src_reg->var_off = dst_reg->var_off = tnum_intersect(src_reg->var_off, 14526 dst_reg->var_off); 14527 reg_bounds_sync(src_reg); 14528 reg_bounds_sync(dst_reg); 14529 } 14530 14531 static void reg_combine_min_max(struct bpf_reg_state *true_src, 14532 struct bpf_reg_state *true_dst, 14533 struct bpf_reg_state *false_src, 14534 struct bpf_reg_state *false_dst, 14535 u8 opcode) 14536 { 14537 switch (opcode) { 14538 case BPF_JEQ: 14539 __reg_combine_min_max(true_src, true_dst); 14540 break; 14541 case BPF_JNE: 14542 __reg_combine_min_max(false_src, false_dst); 14543 break; 14544 } 14545 } 14546 14547 static void mark_ptr_or_null_reg(struct bpf_func_state *state, 14548 struct bpf_reg_state *reg, u32 id, 14549 bool is_null) 14550 { 14551 if (type_may_be_null(reg->type) && reg->id == id && 14552 (is_rcu_reg(reg) || !WARN_ON_ONCE(!reg->id))) { 14553 /* Old offset (both fixed and variable parts) should have been 14554 * known-zero, because we don't allow pointer arithmetic on 14555 * pointers that might be NULL. If we see this happening, don't 14556 * convert the register. 14557 * 14558 * But in some cases, some helpers that return local kptrs 14559 * advance offset for the returned pointer. In those cases, it 14560 * is fine to expect to see reg->off. 14561 */ 14562 if (WARN_ON_ONCE(reg->smin_value || reg->smax_value || !tnum_equals_const(reg->var_off, 0))) 14563 return; 14564 if (!(type_is_ptr_alloc_obj(reg->type) || type_is_non_owning_ref(reg->type)) && 14565 WARN_ON_ONCE(reg->off)) 14566 return; 14567 14568 if (is_null) { 14569 reg->type = SCALAR_VALUE; 14570 /* We don't need id and ref_obj_id from this point 14571 * onwards anymore, thus we should better reset it, 14572 * so that state pruning has chances to take effect. 14573 */ 14574 reg->id = 0; 14575 reg->ref_obj_id = 0; 14576 14577 return; 14578 } 14579 14580 mark_ptr_not_null_reg(reg); 14581 14582 if (!reg_may_point_to_spin_lock(reg)) { 14583 /* For not-NULL ptr, reg->ref_obj_id will be reset 14584 * in release_reference(). 14585 * 14586 * reg->id is still used by spin_lock ptr. Other 14587 * than spin_lock ptr type, reg->id can be reset. 14588 */ 14589 reg->id = 0; 14590 } 14591 } 14592 } 14593 14594 /* The logic is similar to find_good_pkt_pointers(), both could eventually 14595 * be folded together at some point. 14596 */ 14597 static void mark_ptr_or_null_regs(struct bpf_verifier_state *vstate, u32 regno, 14598 bool is_null) 14599 { 14600 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 14601 struct bpf_reg_state *regs = state->regs, *reg; 14602 u32 ref_obj_id = regs[regno].ref_obj_id; 14603 u32 id = regs[regno].id; 14604 14605 if (ref_obj_id && ref_obj_id == id && is_null) 14606 /* regs[regno] is in the " == NULL" branch. 14607 * No one could have freed the reference state before 14608 * doing the NULL check. 14609 */ 14610 WARN_ON_ONCE(release_reference_state(state, id)); 14611 14612 bpf_for_each_reg_in_vstate(vstate, state, reg, ({ 14613 mark_ptr_or_null_reg(state, reg, id, is_null); 14614 })); 14615 } 14616 14617 static bool try_match_pkt_pointers(const struct bpf_insn *insn, 14618 struct bpf_reg_state *dst_reg, 14619 struct bpf_reg_state *src_reg, 14620 struct bpf_verifier_state *this_branch, 14621 struct bpf_verifier_state *other_branch) 14622 { 14623 if (BPF_SRC(insn->code) != BPF_X) 14624 return false; 14625 14626 /* Pointers are always 64-bit. */ 14627 if (BPF_CLASS(insn->code) == BPF_JMP32) 14628 return false; 14629 14630 switch (BPF_OP(insn->code)) { 14631 case BPF_JGT: 14632 if ((dst_reg->type == PTR_TO_PACKET && 14633 src_reg->type == PTR_TO_PACKET_END) || 14634 (dst_reg->type == PTR_TO_PACKET_META && 14635 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) { 14636 /* pkt_data' > pkt_end, pkt_meta' > pkt_data */ 14637 find_good_pkt_pointers(this_branch, dst_reg, 14638 dst_reg->type, false); 14639 mark_pkt_end(other_branch, insn->dst_reg, true); 14640 } else if ((dst_reg->type == PTR_TO_PACKET_END && 14641 src_reg->type == PTR_TO_PACKET) || 14642 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) && 14643 src_reg->type == PTR_TO_PACKET_META)) { 14644 /* pkt_end > pkt_data', pkt_data > pkt_meta' */ 14645 find_good_pkt_pointers(other_branch, src_reg, 14646 src_reg->type, true); 14647 mark_pkt_end(this_branch, insn->src_reg, false); 14648 } else { 14649 return false; 14650 } 14651 break; 14652 case BPF_JLT: 14653 if ((dst_reg->type == PTR_TO_PACKET && 14654 src_reg->type == PTR_TO_PACKET_END) || 14655 (dst_reg->type == PTR_TO_PACKET_META && 14656 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) { 14657 /* pkt_data' < pkt_end, pkt_meta' < pkt_data */ 14658 find_good_pkt_pointers(other_branch, dst_reg, 14659 dst_reg->type, true); 14660 mark_pkt_end(this_branch, insn->dst_reg, false); 14661 } else if ((dst_reg->type == PTR_TO_PACKET_END && 14662 src_reg->type == PTR_TO_PACKET) || 14663 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) && 14664 src_reg->type == PTR_TO_PACKET_META)) { 14665 /* pkt_end < pkt_data', pkt_data > pkt_meta' */ 14666 find_good_pkt_pointers(this_branch, src_reg, 14667 src_reg->type, false); 14668 mark_pkt_end(other_branch, insn->src_reg, true); 14669 } else { 14670 return false; 14671 } 14672 break; 14673 case BPF_JGE: 14674 if ((dst_reg->type == PTR_TO_PACKET && 14675 src_reg->type == PTR_TO_PACKET_END) || 14676 (dst_reg->type == PTR_TO_PACKET_META && 14677 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) { 14678 /* pkt_data' >= pkt_end, pkt_meta' >= pkt_data */ 14679 find_good_pkt_pointers(this_branch, dst_reg, 14680 dst_reg->type, true); 14681 mark_pkt_end(other_branch, insn->dst_reg, false); 14682 } else if ((dst_reg->type == PTR_TO_PACKET_END && 14683 src_reg->type == PTR_TO_PACKET) || 14684 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) && 14685 src_reg->type == PTR_TO_PACKET_META)) { 14686 /* pkt_end >= pkt_data', pkt_data >= pkt_meta' */ 14687 find_good_pkt_pointers(other_branch, src_reg, 14688 src_reg->type, false); 14689 mark_pkt_end(this_branch, insn->src_reg, true); 14690 } else { 14691 return false; 14692 } 14693 break; 14694 case BPF_JLE: 14695 if ((dst_reg->type == PTR_TO_PACKET && 14696 src_reg->type == PTR_TO_PACKET_END) || 14697 (dst_reg->type == PTR_TO_PACKET_META && 14698 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) { 14699 /* pkt_data' <= pkt_end, pkt_meta' <= pkt_data */ 14700 find_good_pkt_pointers(other_branch, dst_reg, 14701 dst_reg->type, false); 14702 mark_pkt_end(this_branch, insn->dst_reg, true); 14703 } else if ((dst_reg->type == PTR_TO_PACKET_END && 14704 src_reg->type == PTR_TO_PACKET) || 14705 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) && 14706 src_reg->type == PTR_TO_PACKET_META)) { 14707 /* pkt_end <= pkt_data', pkt_data <= pkt_meta' */ 14708 find_good_pkt_pointers(this_branch, src_reg, 14709 src_reg->type, true); 14710 mark_pkt_end(other_branch, insn->src_reg, false); 14711 } else { 14712 return false; 14713 } 14714 break; 14715 default: 14716 return false; 14717 } 14718 14719 return true; 14720 } 14721 14722 static void find_equal_scalars(struct bpf_verifier_state *vstate, 14723 struct bpf_reg_state *known_reg) 14724 { 14725 struct bpf_func_state *state; 14726 struct bpf_reg_state *reg; 14727 14728 bpf_for_each_reg_in_vstate(vstate, state, reg, ({ 14729 if (reg->type == SCALAR_VALUE && reg->id == known_reg->id) 14730 copy_register_state(reg, known_reg); 14731 })); 14732 } 14733 14734 static int check_cond_jmp_op(struct bpf_verifier_env *env, 14735 struct bpf_insn *insn, int *insn_idx) 14736 { 14737 struct bpf_verifier_state *this_branch = env->cur_state; 14738 struct bpf_verifier_state *other_branch; 14739 struct bpf_reg_state *regs = this_branch->frame[this_branch->curframe]->regs; 14740 struct bpf_reg_state *dst_reg, *other_branch_regs, *src_reg = NULL; 14741 struct bpf_reg_state *eq_branch_regs; 14742 u8 opcode = BPF_OP(insn->code); 14743 bool is_jmp32; 14744 int pred = -1; 14745 int err; 14746 14747 /* Only conditional jumps are expected to reach here. */ 14748 if (opcode == BPF_JA || opcode > BPF_JSLE) { 14749 verbose(env, "invalid BPF_JMP/JMP32 opcode %x\n", opcode); 14750 return -EINVAL; 14751 } 14752 14753 /* check src2 operand */ 14754 err = check_reg_arg(env, insn->dst_reg, SRC_OP); 14755 if (err) 14756 return err; 14757 14758 dst_reg = ®s[insn->dst_reg]; 14759 if (BPF_SRC(insn->code) == BPF_X) { 14760 if (insn->imm != 0) { 14761 verbose(env, "BPF_JMP/JMP32 uses reserved fields\n"); 14762 return -EINVAL; 14763 } 14764 14765 /* check src1 operand */ 14766 err = check_reg_arg(env, insn->src_reg, SRC_OP); 14767 if (err) 14768 return err; 14769 14770 src_reg = ®s[insn->src_reg]; 14771 if (!(reg_is_pkt_pointer_any(dst_reg) && reg_is_pkt_pointer_any(src_reg)) && 14772 is_pointer_value(env, insn->src_reg)) { 14773 verbose(env, "R%d pointer comparison prohibited\n", 14774 insn->src_reg); 14775 return -EACCES; 14776 } 14777 } else { 14778 if (insn->src_reg != BPF_REG_0) { 14779 verbose(env, "BPF_JMP/JMP32 uses reserved fields\n"); 14780 return -EINVAL; 14781 } 14782 } 14783 14784 is_jmp32 = BPF_CLASS(insn->code) == BPF_JMP32; 14785 14786 if (BPF_SRC(insn->code) == BPF_K) { 14787 pred = is_branch_taken(dst_reg, insn->imm, opcode, is_jmp32); 14788 } else if (src_reg->type == SCALAR_VALUE && 14789 is_jmp32 && tnum_is_const(tnum_subreg(src_reg->var_off))) { 14790 pred = is_branch_taken(dst_reg, 14791 tnum_subreg(src_reg->var_off).value, 14792 opcode, 14793 is_jmp32); 14794 } else if (src_reg->type == SCALAR_VALUE && 14795 !is_jmp32 && tnum_is_const(src_reg->var_off)) { 14796 pred = is_branch_taken(dst_reg, 14797 src_reg->var_off.value, 14798 opcode, 14799 is_jmp32); 14800 } else if (dst_reg->type == SCALAR_VALUE && 14801 is_jmp32 && tnum_is_const(tnum_subreg(dst_reg->var_off))) { 14802 pred = is_branch_taken(src_reg, 14803 tnum_subreg(dst_reg->var_off).value, 14804 flip_opcode(opcode), 14805 is_jmp32); 14806 } else if (dst_reg->type == SCALAR_VALUE && 14807 !is_jmp32 && tnum_is_const(dst_reg->var_off)) { 14808 pred = is_branch_taken(src_reg, 14809 dst_reg->var_off.value, 14810 flip_opcode(opcode), 14811 is_jmp32); 14812 } else if (reg_is_pkt_pointer_any(dst_reg) && 14813 reg_is_pkt_pointer_any(src_reg) && 14814 !is_jmp32) { 14815 pred = is_pkt_ptr_branch_taken(dst_reg, src_reg, opcode); 14816 } 14817 14818 if (pred >= 0) { 14819 /* If we get here with a dst_reg pointer type it is because 14820 * above is_branch_taken() special cased the 0 comparison. 14821 */ 14822 if (!__is_pointer_value(false, dst_reg)) 14823 err = mark_chain_precision(env, insn->dst_reg); 14824 if (BPF_SRC(insn->code) == BPF_X && !err && 14825 !__is_pointer_value(false, src_reg)) 14826 err = mark_chain_precision(env, insn->src_reg); 14827 if (err) 14828 return err; 14829 } 14830 14831 if (pred == 1) { 14832 /* Only follow the goto, ignore fall-through. If needed, push 14833 * the fall-through branch for simulation under speculative 14834 * execution. 14835 */ 14836 if (!env->bypass_spec_v1 && 14837 !sanitize_speculative_path(env, insn, *insn_idx + 1, 14838 *insn_idx)) 14839 return -EFAULT; 14840 if (env->log.level & BPF_LOG_LEVEL) 14841 print_insn_state(env, this_branch->frame[this_branch->curframe]); 14842 *insn_idx += insn->off; 14843 return 0; 14844 } else if (pred == 0) { 14845 /* Only follow the fall-through branch, since that's where the 14846 * program will go. If needed, push the goto branch for 14847 * simulation under speculative execution. 14848 */ 14849 if (!env->bypass_spec_v1 && 14850 !sanitize_speculative_path(env, insn, 14851 *insn_idx + insn->off + 1, 14852 *insn_idx)) 14853 return -EFAULT; 14854 if (env->log.level & BPF_LOG_LEVEL) 14855 print_insn_state(env, this_branch->frame[this_branch->curframe]); 14856 return 0; 14857 } 14858 14859 other_branch = push_stack(env, *insn_idx + insn->off + 1, *insn_idx, 14860 false); 14861 if (!other_branch) 14862 return -EFAULT; 14863 other_branch_regs = other_branch->frame[other_branch->curframe]->regs; 14864 14865 /* detect if we are comparing against a constant value so we can adjust 14866 * our min/max values for our dst register. 14867 * this is only legit if both are scalars (or pointers to the same 14868 * object, I suppose, see the PTR_MAYBE_NULL related if block below), 14869 * because otherwise the different base pointers mean the offsets aren't 14870 * comparable. 14871 */ 14872 if (BPF_SRC(insn->code) == BPF_X) { 14873 struct bpf_reg_state *src_reg = ®s[insn->src_reg]; 14874 14875 if (dst_reg->type == SCALAR_VALUE && 14876 src_reg->type == SCALAR_VALUE) { 14877 if (tnum_is_const(src_reg->var_off) || 14878 (is_jmp32 && 14879 tnum_is_const(tnum_subreg(src_reg->var_off)))) 14880 reg_set_min_max(&other_branch_regs[insn->dst_reg], 14881 dst_reg, 14882 src_reg->var_off.value, 14883 tnum_subreg(src_reg->var_off).value, 14884 opcode, is_jmp32); 14885 else if (tnum_is_const(dst_reg->var_off) || 14886 (is_jmp32 && 14887 tnum_is_const(tnum_subreg(dst_reg->var_off)))) 14888 reg_set_min_max_inv(&other_branch_regs[insn->src_reg], 14889 src_reg, 14890 dst_reg->var_off.value, 14891 tnum_subreg(dst_reg->var_off).value, 14892 opcode, is_jmp32); 14893 else if (!is_jmp32 && 14894 (opcode == BPF_JEQ || opcode == BPF_JNE)) 14895 /* Comparing for equality, we can combine knowledge */ 14896 reg_combine_min_max(&other_branch_regs[insn->src_reg], 14897 &other_branch_regs[insn->dst_reg], 14898 src_reg, dst_reg, opcode); 14899 if (src_reg->id && 14900 !WARN_ON_ONCE(src_reg->id != other_branch_regs[insn->src_reg].id)) { 14901 find_equal_scalars(this_branch, src_reg); 14902 find_equal_scalars(other_branch, &other_branch_regs[insn->src_reg]); 14903 } 14904 14905 } 14906 } else if (dst_reg->type == SCALAR_VALUE) { 14907 reg_set_min_max(&other_branch_regs[insn->dst_reg], 14908 dst_reg, insn->imm, (u32)insn->imm, 14909 opcode, is_jmp32); 14910 } 14911 14912 if (dst_reg->type == SCALAR_VALUE && dst_reg->id && 14913 !WARN_ON_ONCE(dst_reg->id != other_branch_regs[insn->dst_reg].id)) { 14914 find_equal_scalars(this_branch, dst_reg); 14915 find_equal_scalars(other_branch, &other_branch_regs[insn->dst_reg]); 14916 } 14917 14918 /* if one pointer register is compared to another pointer 14919 * register check if PTR_MAYBE_NULL could be lifted. 14920 * E.g. register A - maybe null 14921 * register B - not null 14922 * for JNE A, B, ... - A is not null in the false branch; 14923 * for JEQ A, B, ... - A is not null in the true branch. 14924 * 14925 * Since PTR_TO_BTF_ID points to a kernel struct that does 14926 * not need to be null checked by the BPF program, i.e., 14927 * could be null even without PTR_MAYBE_NULL marking, so 14928 * only propagate nullness when neither reg is that type. 14929 */ 14930 if (!is_jmp32 && BPF_SRC(insn->code) == BPF_X && 14931 __is_pointer_value(false, src_reg) && __is_pointer_value(false, dst_reg) && 14932 type_may_be_null(src_reg->type) != type_may_be_null(dst_reg->type) && 14933 base_type(src_reg->type) != PTR_TO_BTF_ID && 14934 base_type(dst_reg->type) != PTR_TO_BTF_ID) { 14935 eq_branch_regs = NULL; 14936 switch (opcode) { 14937 case BPF_JEQ: 14938 eq_branch_regs = other_branch_regs; 14939 break; 14940 case BPF_JNE: 14941 eq_branch_regs = regs; 14942 break; 14943 default: 14944 /* do nothing */ 14945 break; 14946 } 14947 if (eq_branch_regs) { 14948 if (type_may_be_null(src_reg->type)) 14949 mark_ptr_not_null_reg(&eq_branch_regs[insn->src_reg]); 14950 else 14951 mark_ptr_not_null_reg(&eq_branch_regs[insn->dst_reg]); 14952 } 14953 } 14954 14955 /* detect if R == 0 where R is returned from bpf_map_lookup_elem(). 14956 * NOTE: these optimizations below are related with pointer comparison 14957 * which will never be JMP32. 14958 */ 14959 if (!is_jmp32 && BPF_SRC(insn->code) == BPF_K && 14960 insn->imm == 0 && (opcode == BPF_JEQ || opcode == BPF_JNE) && 14961 type_may_be_null(dst_reg->type)) { 14962 /* Mark all identical registers in each branch as either 14963 * safe or unknown depending R == 0 or R != 0 conditional. 14964 */ 14965 mark_ptr_or_null_regs(this_branch, insn->dst_reg, 14966 opcode == BPF_JNE); 14967 mark_ptr_or_null_regs(other_branch, insn->dst_reg, 14968 opcode == BPF_JEQ); 14969 } else if (!try_match_pkt_pointers(insn, dst_reg, ®s[insn->src_reg], 14970 this_branch, other_branch) && 14971 is_pointer_value(env, insn->dst_reg)) { 14972 verbose(env, "R%d pointer comparison prohibited\n", 14973 insn->dst_reg); 14974 return -EACCES; 14975 } 14976 if (env->log.level & BPF_LOG_LEVEL) 14977 print_insn_state(env, this_branch->frame[this_branch->curframe]); 14978 return 0; 14979 } 14980 14981 /* verify BPF_LD_IMM64 instruction */ 14982 static int check_ld_imm(struct bpf_verifier_env *env, struct bpf_insn *insn) 14983 { 14984 struct bpf_insn_aux_data *aux = cur_aux(env); 14985 struct bpf_reg_state *regs = cur_regs(env); 14986 struct bpf_reg_state *dst_reg; 14987 struct bpf_map *map; 14988 int err; 14989 14990 if (BPF_SIZE(insn->code) != BPF_DW) { 14991 verbose(env, "invalid BPF_LD_IMM insn\n"); 14992 return -EINVAL; 14993 } 14994 if (insn->off != 0) { 14995 verbose(env, "BPF_LD_IMM64 uses reserved fields\n"); 14996 return -EINVAL; 14997 } 14998 14999 err = check_reg_arg(env, insn->dst_reg, DST_OP); 15000 if (err) 15001 return err; 15002 15003 dst_reg = ®s[insn->dst_reg]; 15004 if (insn->src_reg == 0) { 15005 u64 imm = ((u64)(insn + 1)->imm << 32) | (u32)insn->imm; 15006 15007 dst_reg->type = SCALAR_VALUE; 15008 __mark_reg_known(®s[insn->dst_reg], imm); 15009 return 0; 15010 } 15011 15012 /* All special src_reg cases are listed below. From this point onwards 15013 * we either succeed and assign a corresponding dst_reg->type after 15014 * zeroing the offset, or fail and reject the program. 15015 */ 15016 mark_reg_known_zero(env, regs, insn->dst_reg); 15017 15018 if (insn->src_reg == BPF_PSEUDO_BTF_ID) { 15019 dst_reg->type = aux->btf_var.reg_type; 15020 switch (base_type(dst_reg->type)) { 15021 case PTR_TO_MEM: 15022 dst_reg->mem_size = aux->btf_var.mem_size; 15023 break; 15024 case PTR_TO_BTF_ID: 15025 dst_reg->btf = aux->btf_var.btf; 15026 dst_reg->btf_id = aux->btf_var.btf_id; 15027 break; 15028 default: 15029 verbose(env, "bpf verifier is misconfigured\n"); 15030 return -EFAULT; 15031 } 15032 return 0; 15033 } 15034 15035 if (insn->src_reg == BPF_PSEUDO_FUNC) { 15036 struct bpf_prog_aux *aux = env->prog->aux; 15037 u32 subprogno = find_subprog(env, 15038 env->insn_idx + insn->imm + 1); 15039 15040 if (!aux->func_info) { 15041 verbose(env, "missing btf func_info\n"); 15042 return -EINVAL; 15043 } 15044 if (aux->func_info_aux[subprogno].linkage != BTF_FUNC_STATIC) { 15045 verbose(env, "callback function not static\n"); 15046 return -EINVAL; 15047 } 15048 15049 dst_reg->type = PTR_TO_FUNC; 15050 dst_reg->subprogno = subprogno; 15051 return 0; 15052 } 15053 15054 map = env->used_maps[aux->map_index]; 15055 dst_reg->map_ptr = map; 15056 15057 if (insn->src_reg == BPF_PSEUDO_MAP_VALUE || 15058 insn->src_reg == BPF_PSEUDO_MAP_IDX_VALUE) { 15059 dst_reg->type = PTR_TO_MAP_VALUE; 15060 dst_reg->off = aux->map_off; 15061 WARN_ON_ONCE(map->max_entries != 1); 15062 /* We want reg->id to be same (0) as map_value is not distinct */ 15063 } else if (insn->src_reg == BPF_PSEUDO_MAP_FD || 15064 insn->src_reg == BPF_PSEUDO_MAP_IDX) { 15065 dst_reg->type = CONST_PTR_TO_MAP; 15066 } else { 15067 verbose(env, "bpf verifier is misconfigured\n"); 15068 return -EINVAL; 15069 } 15070 15071 return 0; 15072 } 15073 15074 static bool may_access_skb(enum bpf_prog_type type) 15075 { 15076 switch (type) { 15077 case BPF_PROG_TYPE_SOCKET_FILTER: 15078 case BPF_PROG_TYPE_SCHED_CLS: 15079 case BPF_PROG_TYPE_SCHED_ACT: 15080 return true; 15081 default: 15082 return false; 15083 } 15084 } 15085 15086 /* verify safety of LD_ABS|LD_IND instructions: 15087 * - they can only appear in the programs where ctx == skb 15088 * - since they are wrappers of function calls, they scratch R1-R5 registers, 15089 * preserve R6-R9, and store return value into R0 15090 * 15091 * Implicit input: 15092 * ctx == skb == R6 == CTX 15093 * 15094 * Explicit input: 15095 * SRC == any register 15096 * IMM == 32-bit immediate 15097 * 15098 * Output: 15099 * R0 - 8/16/32-bit skb data converted to cpu endianness 15100 */ 15101 static int check_ld_abs(struct bpf_verifier_env *env, struct bpf_insn *insn) 15102 { 15103 struct bpf_reg_state *regs = cur_regs(env); 15104 static const int ctx_reg = BPF_REG_6; 15105 u8 mode = BPF_MODE(insn->code); 15106 int i, err; 15107 15108 if (!may_access_skb(resolve_prog_type(env->prog))) { 15109 verbose(env, "BPF_LD_[ABS|IND] instructions not allowed for this program type\n"); 15110 return -EINVAL; 15111 } 15112 15113 if (!env->ops->gen_ld_abs) { 15114 verbose(env, "bpf verifier is misconfigured\n"); 15115 return -EINVAL; 15116 } 15117 15118 if (insn->dst_reg != BPF_REG_0 || insn->off != 0 || 15119 BPF_SIZE(insn->code) == BPF_DW || 15120 (mode == BPF_ABS && insn->src_reg != BPF_REG_0)) { 15121 verbose(env, "BPF_LD_[ABS|IND] uses reserved fields\n"); 15122 return -EINVAL; 15123 } 15124 15125 /* check whether implicit source operand (register R6) is readable */ 15126 err = check_reg_arg(env, ctx_reg, SRC_OP); 15127 if (err) 15128 return err; 15129 15130 /* Disallow usage of BPF_LD_[ABS|IND] with reference tracking, as 15131 * gen_ld_abs() may terminate the program at runtime, leading to 15132 * reference leak. 15133 */ 15134 err = check_reference_leak(env, false); 15135 if (err) { 15136 verbose(env, "BPF_LD_[ABS|IND] cannot be mixed with socket references\n"); 15137 return err; 15138 } 15139 15140 if (env->cur_state->active_lock.ptr) { 15141 verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_spin_lock-ed region\n"); 15142 return -EINVAL; 15143 } 15144 15145 if (env->cur_state->active_rcu_lock) { 15146 verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_rcu_read_lock-ed region\n"); 15147 return -EINVAL; 15148 } 15149 15150 if (regs[ctx_reg].type != PTR_TO_CTX) { 15151 verbose(env, 15152 "at the time of BPF_LD_ABS|IND R6 != pointer to skb\n"); 15153 return -EINVAL; 15154 } 15155 15156 if (mode == BPF_IND) { 15157 /* check explicit source operand */ 15158 err = check_reg_arg(env, insn->src_reg, SRC_OP); 15159 if (err) 15160 return err; 15161 } 15162 15163 err = check_ptr_off_reg(env, ®s[ctx_reg], ctx_reg); 15164 if (err < 0) 15165 return err; 15166 15167 /* reset caller saved regs to unreadable */ 15168 for (i = 0; i < CALLER_SAVED_REGS; i++) { 15169 mark_reg_not_init(env, regs, caller_saved[i]); 15170 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK); 15171 } 15172 15173 /* mark destination R0 register as readable, since it contains 15174 * the value fetched from the packet. 15175 * Already marked as written above. 15176 */ 15177 mark_reg_unknown(env, regs, BPF_REG_0); 15178 /* ld_abs load up to 32-bit skb data. */ 15179 regs[BPF_REG_0].subreg_def = env->insn_idx + 1; 15180 return 0; 15181 } 15182 15183 static int check_return_code(struct bpf_verifier_env *env, int regno) 15184 { 15185 struct tnum enforce_attach_type_range = tnum_unknown; 15186 const struct bpf_prog *prog = env->prog; 15187 struct bpf_reg_state *reg; 15188 struct tnum range = tnum_range(0, 1), const_0 = tnum_const(0); 15189 enum bpf_prog_type prog_type = resolve_prog_type(env->prog); 15190 int err; 15191 struct bpf_func_state *frame = env->cur_state->frame[0]; 15192 const bool is_subprog = frame->subprogno; 15193 15194 /* LSM and struct_ops func-ptr's return type could be "void" */ 15195 if (!is_subprog || frame->in_exception_callback_fn) { 15196 switch (prog_type) { 15197 case BPF_PROG_TYPE_LSM: 15198 if (prog->expected_attach_type == BPF_LSM_CGROUP) 15199 /* See below, can be 0 or 0-1 depending on hook. */ 15200 break; 15201 fallthrough; 15202 case BPF_PROG_TYPE_STRUCT_OPS: 15203 if (!prog->aux->attach_func_proto->type) 15204 return 0; 15205 break; 15206 default: 15207 break; 15208 } 15209 } 15210 15211 /* eBPF calling convention is such that R0 is used 15212 * to return the value from eBPF program. 15213 * Make sure that it's readable at this time 15214 * of bpf_exit, which means that program wrote 15215 * something into it earlier 15216 */ 15217 err = check_reg_arg(env, regno, SRC_OP); 15218 if (err) 15219 return err; 15220 15221 if (is_pointer_value(env, regno)) { 15222 verbose(env, "R%d leaks addr as return value\n", regno); 15223 return -EACCES; 15224 } 15225 15226 reg = cur_regs(env) + regno; 15227 15228 if (frame->in_async_callback_fn) { 15229 /* enforce return zero from async callbacks like timer */ 15230 if (reg->type != SCALAR_VALUE) { 15231 verbose(env, "In async callback the register R%d is not a known value (%s)\n", 15232 regno, reg_type_str(env, reg->type)); 15233 return -EINVAL; 15234 } 15235 15236 if (!tnum_in(const_0, reg->var_off)) { 15237 verbose_invalid_scalar(env, reg, &const_0, "async callback", "R0"); 15238 return -EINVAL; 15239 } 15240 return 0; 15241 } 15242 15243 if (is_subprog && !frame->in_exception_callback_fn) { 15244 if (reg->type != SCALAR_VALUE) { 15245 verbose(env, "At subprogram exit the register R%d is not a scalar value (%s)\n", 15246 regno, reg_type_str(env, reg->type)); 15247 return -EINVAL; 15248 } 15249 return 0; 15250 } 15251 15252 switch (prog_type) { 15253 case BPF_PROG_TYPE_CGROUP_SOCK_ADDR: 15254 if (env->prog->expected_attach_type == BPF_CGROUP_UDP4_RECVMSG || 15255 env->prog->expected_attach_type == BPF_CGROUP_UDP6_RECVMSG || 15256 env->prog->expected_attach_type == BPF_CGROUP_UNIX_RECVMSG || 15257 env->prog->expected_attach_type == BPF_CGROUP_INET4_GETPEERNAME || 15258 env->prog->expected_attach_type == BPF_CGROUP_INET6_GETPEERNAME || 15259 env->prog->expected_attach_type == BPF_CGROUP_UNIX_GETPEERNAME || 15260 env->prog->expected_attach_type == BPF_CGROUP_INET4_GETSOCKNAME || 15261 env->prog->expected_attach_type == BPF_CGROUP_INET6_GETSOCKNAME || 15262 env->prog->expected_attach_type == BPF_CGROUP_UNIX_GETSOCKNAME) 15263 range = tnum_range(1, 1); 15264 if (env->prog->expected_attach_type == BPF_CGROUP_INET4_BIND || 15265 env->prog->expected_attach_type == BPF_CGROUP_INET6_BIND) 15266 range = tnum_range(0, 3); 15267 break; 15268 case BPF_PROG_TYPE_CGROUP_SKB: 15269 if (env->prog->expected_attach_type == BPF_CGROUP_INET_EGRESS) { 15270 range = tnum_range(0, 3); 15271 enforce_attach_type_range = tnum_range(2, 3); 15272 } 15273 break; 15274 case BPF_PROG_TYPE_CGROUP_SOCK: 15275 case BPF_PROG_TYPE_SOCK_OPS: 15276 case BPF_PROG_TYPE_CGROUP_DEVICE: 15277 case BPF_PROG_TYPE_CGROUP_SYSCTL: 15278 case BPF_PROG_TYPE_CGROUP_SOCKOPT: 15279 break; 15280 case BPF_PROG_TYPE_RAW_TRACEPOINT: 15281 if (!env->prog->aux->attach_btf_id) 15282 return 0; 15283 range = tnum_const(0); 15284 break; 15285 case BPF_PROG_TYPE_TRACING: 15286 switch (env->prog->expected_attach_type) { 15287 case BPF_TRACE_FENTRY: 15288 case BPF_TRACE_FEXIT: 15289 range = tnum_const(0); 15290 break; 15291 case BPF_TRACE_RAW_TP: 15292 case BPF_MODIFY_RETURN: 15293 return 0; 15294 case BPF_TRACE_ITER: 15295 break; 15296 default: 15297 return -ENOTSUPP; 15298 } 15299 break; 15300 case BPF_PROG_TYPE_SK_LOOKUP: 15301 range = tnum_range(SK_DROP, SK_PASS); 15302 break; 15303 15304 case BPF_PROG_TYPE_LSM: 15305 if (env->prog->expected_attach_type != BPF_LSM_CGROUP) { 15306 /* Regular BPF_PROG_TYPE_LSM programs can return 15307 * any value. 15308 */ 15309 return 0; 15310 } 15311 if (!env->prog->aux->attach_func_proto->type) { 15312 /* Make sure programs that attach to void 15313 * hooks don't try to modify return value. 15314 */ 15315 range = tnum_range(1, 1); 15316 } 15317 break; 15318 15319 case BPF_PROG_TYPE_NETFILTER: 15320 range = tnum_range(NF_DROP, NF_ACCEPT); 15321 break; 15322 case BPF_PROG_TYPE_EXT: 15323 /* freplace program can return anything as its return value 15324 * depends on the to-be-replaced kernel func or bpf program. 15325 */ 15326 default: 15327 return 0; 15328 } 15329 15330 if (reg->type != SCALAR_VALUE) { 15331 verbose(env, "At program exit the register R%d is not a known value (%s)\n", 15332 regno, reg_type_str(env, reg->type)); 15333 return -EINVAL; 15334 } 15335 15336 if (!tnum_in(range, reg->var_off)) { 15337 verbose_invalid_scalar(env, reg, &range, "program exit", "R0"); 15338 if (prog->expected_attach_type == BPF_LSM_CGROUP && 15339 prog_type == BPF_PROG_TYPE_LSM && 15340 !prog->aux->attach_func_proto->type) 15341 verbose(env, "Note, BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n"); 15342 return -EINVAL; 15343 } 15344 15345 if (!tnum_is_unknown(enforce_attach_type_range) && 15346 tnum_in(enforce_attach_type_range, reg->var_off)) 15347 env->prog->enforce_expected_attach_type = 1; 15348 return 0; 15349 } 15350 15351 /* non-recursive DFS pseudo code 15352 * 1 procedure DFS-iterative(G,v): 15353 * 2 label v as discovered 15354 * 3 let S be a stack 15355 * 4 S.push(v) 15356 * 5 while S is not empty 15357 * 6 t <- S.peek() 15358 * 7 if t is what we're looking for: 15359 * 8 return t 15360 * 9 for all edges e in G.adjacentEdges(t) do 15361 * 10 if edge e is already labelled 15362 * 11 continue with the next edge 15363 * 12 w <- G.adjacentVertex(t,e) 15364 * 13 if vertex w is not discovered and not explored 15365 * 14 label e as tree-edge 15366 * 15 label w as discovered 15367 * 16 S.push(w) 15368 * 17 continue at 5 15369 * 18 else if vertex w is discovered 15370 * 19 label e as back-edge 15371 * 20 else 15372 * 21 // vertex w is explored 15373 * 22 label e as forward- or cross-edge 15374 * 23 label t as explored 15375 * 24 S.pop() 15376 * 15377 * convention: 15378 * 0x10 - discovered 15379 * 0x11 - discovered and fall-through edge labelled 15380 * 0x12 - discovered and fall-through and branch edges labelled 15381 * 0x20 - explored 15382 */ 15383 15384 enum { 15385 DISCOVERED = 0x10, 15386 EXPLORED = 0x20, 15387 FALLTHROUGH = 1, 15388 BRANCH = 2, 15389 }; 15390 15391 static void mark_prune_point(struct bpf_verifier_env *env, int idx) 15392 { 15393 env->insn_aux_data[idx].prune_point = true; 15394 } 15395 15396 static bool is_prune_point(struct bpf_verifier_env *env, int insn_idx) 15397 { 15398 return env->insn_aux_data[insn_idx].prune_point; 15399 } 15400 15401 static void mark_force_checkpoint(struct bpf_verifier_env *env, int idx) 15402 { 15403 env->insn_aux_data[idx].force_checkpoint = true; 15404 } 15405 15406 static bool is_force_checkpoint(struct bpf_verifier_env *env, int insn_idx) 15407 { 15408 return env->insn_aux_data[insn_idx].force_checkpoint; 15409 } 15410 15411 15412 enum { 15413 DONE_EXPLORING = 0, 15414 KEEP_EXPLORING = 1, 15415 }; 15416 15417 /* t, w, e - match pseudo-code above: 15418 * t - index of current instruction 15419 * w - next instruction 15420 * e - edge 15421 */ 15422 static int push_insn(int t, int w, int e, struct bpf_verifier_env *env) 15423 { 15424 int *insn_stack = env->cfg.insn_stack; 15425 int *insn_state = env->cfg.insn_state; 15426 15427 if (e == FALLTHROUGH && insn_state[t] >= (DISCOVERED | FALLTHROUGH)) 15428 return DONE_EXPLORING; 15429 15430 if (e == BRANCH && insn_state[t] >= (DISCOVERED | BRANCH)) 15431 return DONE_EXPLORING; 15432 15433 if (w < 0 || w >= env->prog->len) { 15434 verbose_linfo(env, t, "%d: ", t); 15435 verbose(env, "jump out of range from insn %d to %d\n", t, w); 15436 return -EINVAL; 15437 } 15438 15439 if (e == BRANCH) { 15440 /* mark branch target for state pruning */ 15441 mark_prune_point(env, w); 15442 mark_jmp_point(env, w); 15443 } 15444 15445 if (insn_state[w] == 0) { 15446 /* tree-edge */ 15447 insn_state[t] = DISCOVERED | e; 15448 insn_state[w] = DISCOVERED; 15449 if (env->cfg.cur_stack >= env->prog->len) 15450 return -E2BIG; 15451 insn_stack[env->cfg.cur_stack++] = w; 15452 return KEEP_EXPLORING; 15453 } else if ((insn_state[w] & 0xF0) == DISCOVERED) { 15454 if (env->bpf_capable) 15455 return DONE_EXPLORING; 15456 verbose_linfo(env, t, "%d: ", t); 15457 verbose_linfo(env, w, "%d: ", w); 15458 verbose(env, "back-edge from insn %d to %d\n", t, w); 15459 return -EINVAL; 15460 } else if (insn_state[w] == EXPLORED) { 15461 /* forward- or cross-edge */ 15462 insn_state[t] = DISCOVERED | e; 15463 } else { 15464 verbose(env, "insn state internal bug\n"); 15465 return -EFAULT; 15466 } 15467 return DONE_EXPLORING; 15468 } 15469 15470 static int visit_func_call_insn(int t, struct bpf_insn *insns, 15471 struct bpf_verifier_env *env, 15472 bool visit_callee) 15473 { 15474 int ret, insn_sz; 15475 15476 insn_sz = bpf_is_ldimm64(&insns[t]) ? 2 : 1; 15477 ret = push_insn(t, t + insn_sz, FALLTHROUGH, env); 15478 if (ret) 15479 return ret; 15480 15481 mark_prune_point(env, t + insn_sz); 15482 /* when we exit from subprog, we need to record non-linear history */ 15483 mark_jmp_point(env, t + insn_sz); 15484 15485 if (visit_callee) { 15486 mark_prune_point(env, t); 15487 ret = push_insn(t, t + insns[t].imm + 1, BRANCH, env); 15488 } 15489 return ret; 15490 } 15491 15492 /* Visits the instruction at index t and returns one of the following: 15493 * < 0 - an error occurred 15494 * DONE_EXPLORING - the instruction was fully explored 15495 * KEEP_EXPLORING - there is still work to be done before it is fully explored 15496 */ 15497 static int visit_insn(int t, struct bpf_verifier_env *env) 15498 { 15499 struct bpf_insn *insns = env->prog->insnsi, *insn = &insns[t]; 15500 int ret, off, insn_sz; 15501 15502 if (bpf_pseudo_func(insn)) 15503 return visit_func_call_insn(t, insns, env, true); 15504 15505 /* All non-branch instructions have a single fall-through edge. */ 15506 if (BPF_CLASS(insn->code) != BPF_JMP && 15507 BPF_CLASS(insn->code) != BPF_JMP32) { 15508 insn_sz = bpf_is_ldimm64(insn) ? 2 : 1; 15509 return push_insn(t, t + insn_sz, FALLTHROUGH, env); 15510 } 15511 15512 switch (BPF_OP(insn->code)) { 15513 case BPF_EXIT: 15514 return DONE_EXPLORING; 15515 15516 case BPF_CALL: 15517 if (insn->src_reg == 0 && insn->imm == BPF_FUNC_timer_set_callback) 15518 /* Mark this call insn as a prune point to trigger 15519 * is_state_visited() check before call itself is 15520 * processed by __check_func_call(). Otherwise new 15521 * async state will be pushed for further exploration. 15522 */ 15523 mark_prune_point(env, t); 15524 if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) { 15525 struct bpf_kfunc_call_arg_meta meta; 15526 15527 ret = fetch_kfunc_meta(env, insn, &meta, NULL); 15528 if (ret == 0 && is_iter_next_kfunc(&meta)) { 15529 mark_prune_point(env, t); 15530 /* Checking and saving state checkpoints at iter_next() call 15531 * is crucial for fast convergence of open-coded iterator loop 15532 * logic, so we need to force it. If we don't do that, 15533 * is_state_visited() might skip saving a checkpoint, causing 15534 * unnecessarily long sequence of not checkpointed 15535 * instructions and jumps, leading to exhaustion of jump 15536 * history buffer, and potentially other undesired outcomes. 15537 * It is expected that with correct open-coded iterators 15538 * convergence will happen quickly, so we don't run a risk of 15539 * exhausting memory. 15540 */ 15541 mark_force_checkpoint(env, t); 15542 } 15543 } 15544 return visit_func_call_insn(t, insns, env, insn->src_reg == BPF_PSEUDO_CALL); 15545 15546 case BPF_JA: 15547 if (BPF_SRC(insn->code) != BPF_K) 15548 return -EINVAL; 15549 15550 if (BPF_CLASS(insn->code) == BPF_JMP) 15551 off = insn->off; 15552 else 15553 off = insn->imm; 15554 15555 /* unconditional jump with single edge */ 15556 ret = push_insn(t, t + off + 1, FALLTHROUGH, env); 15557 if (ret) 15558 return ret; 15559 15560 mark_prune_point(env, t + off + 1); 15561 mark_jmp_point(env, t + off + 1); 15562 15563 return ret; 15564 15565 default: 15566 /* conditional jump with two edges */ 15567 mark_prune_point(env, t); 15568 15569 ret = push_insn(t, t + 1, FALLTHROUGH, env); 15570 if (ret) 15571 return ret; 15572 15573 return push_insn(t, t + insn->off + 1, BRANCH, env); 15574 } 15575 } 15576 15577 /* non-recursive depth-first-search to detect loops in BPF program 15578 * loop == back-edge in directed graph 15579 */ 15580 static int check_cfg(struct bpf_verifier_env *env) 15581 { 15582 int insn_cnt = env->prog->len; 15583 int *insn_stack, *insn_state; 15584 int ex_insn_beg, i, ret = 0; 15585 bool ex_done = false; 15586 15587 insn_state = env->cfg.insn_state = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL); 15588 if (!insn_state) 15589 return -ENOMEM; 15590 15591 insn_stack = env->cfg.insn_stack = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL); 15592 if (!insn_stack) { 15593 kvfree(insn_state); 15594 return -ENOMEM; 15595 } 15596 15597 insn_state[0] = DISCOVERED; /* mark 1st insn as discovered */ 15598 insn_stack[0] = 0; /* 0 is the first instruction */ 15599 env->cfg.cur_stack = 1; 15600 15601 walk_cfg: 15602 while (env->cfg.cur_stack > 0) { 15603 int t = insn_stack[env->cfg.cur_stack - 1]; 15604 15605 ret = visit_insn(t, env); 15606 switch (ret) { 15607 case DONE_EXPLORING: 15608 insn_state[t] = EXPLORED; 15609 env->cfg.cur_stack--; 15610 break; 15611 case KEEP_EXPLORING: 15612 break; 15613 default: 15614 if (ret > 0) { 15615 verbose(env, "visit_insn internal bug\n"); 15616 ret = -EFAULT; 15617 } 15618 goto err_free; 15619 } 15620 } 15621 15622 if (env->cfg.cur_stack < 0) { 15623 verbose(env, "pop stack internal bug\n"); 15624 ret = -EFAULT; 15625 goto err_free; 15626 } 15627 15628 if (env->exception_callback_subprog && !ex_done) { 15629 ex_insn_beg = env->subprog_info[env->exception_callback_subprog].start; 15630 15631 insn_state[ex_insn_beg] = DISCOVERED; 15632 insn_stack[0] = ex_insn_beg; 15633 env->cfg.cur_stack = 1; 15634 ex_done = true; 15635 goto walk_cfg; 15636 } 15637 15638 for (i = 0; i < insn_cnt; i++) { 15639 struct bpf_insn *insn = &env->prog->insnsi[i]; 15640 15641 if (insn_state[i] != EXPLORED) { 15642 verbose(env, "unreachable insn %d\n", i); 15643 ret = -EINVAL; 15644 goto err_free; 15645 } 15646 if (bpf_is_ldimm64(insn)) { 15647 if (insn_state[i + 1] != 0) { 15648 verbose(env, "jump into the middle of ldimm64 insn %d\n", i); 15649 ret = -EINVAL; 15650 goto err_free; 15651 } 15652 i++; /* skip second half of ldimm64 */ 15653 } 15654 } 15655 ret = 0; /* cfg looks good */ 15656 15657 err_free: 15658 kvfree(insn_state); 15659 kvfree(insn_stack); 15660 env->cfg.insn_state = env->cfg.insn_stack = NULL; 15661 return ret; 15662 } 15663 15664 static int check_abnormal_return(struct bpf_verifier_env *env) 15665 { 15666 int i; 15667 15668 for (i = 1; i < env->subprog_cnt; i++) { 15669 if (env->subprog_info[i].has_ld_abs) { 15670 verbose(env, "LD_ABS is not allowed in subprogs without BTF\n"); 15671 return -EINVAL; 15672 } 15673 if (env->subprog_info[i].has_tail_call) { 15674 verbose(env, "tail_call is not allowed in subprogs without BTF\n"); 15675 return -EINVAL; 15676 } 15677 } 15678 return 0; 15679 } 15680 15681 /* The minimum supported BTF func info size */ 15682 #define MIN_BPF_FUNCINFO_SIZE 8 15683 #define MAX_FUNCINFO_REC_SIZE 252 15684 15685 static int check_btf_func_early(struct bpf_verifier_env *env, 15686 const union bpf_attr *attr, 15687 bpfptr_t uattr) 15688 { 15689 u32 krec_size = sizeof(struct bpf_func_info); 15690 const struct btf_type *type, *func_proto; 15691 u32 i, nfuncs, urec_size, min_size; 15692 struct bpf_func_info *krecord; 15693 struct bpf_prog *prog; 15694 const struct btf *btf; 15695 u32 prev_offset = 0; 15696 bpfptr_t urecord; 15697 int ret = -ENOMEM; 15698 15699 nfuncs = attr->func_info_cnt; 15700 if (!nfuncs) { 15701 if (check_abnormal_return(env)) 15702 return -EINVAL; 15703 return 0; 15704 } 15705 15706 urec_size = attr->func_info_rec_size; 15707 if (urec_size < MIN_BPF_FUNCINFO_SIZE || 15708 urec_size > MAX_FUNCINFO_REC_SIZE || 15709 urec_size % sizeof(u32)) { 15710 verbose(env, "invalid func info rec size %u\n", urec_size); 15711 return -EINVAL; 15712 } 15713 15714 prog = env->prog; 15715 btf = prog->aux->btf; 15716 15717 urecord = make_bpfptr(attr->func_info, uattr.is_kernel); 15718 min_size = min_t(u32, krec_size, urec_size); 15719 15720 krecord = kvcalloc(nfuncs, krec_size, GFP_KERNEL | __GFP_NOWARN); 15721 if (!krecord) 15722 return -ENOMEM; 15723 15724 for (i = 0; i < nfuncs; i++) { 15725 ret = bpf_check_uarg_tail_zero(urecord, krec_size, urec_size); 15726 if (ret) { 15727 if (ret == -E2BIG) { 15728 verbose(env, "nonzero tailing record in func info"); 15729 /* set the size kernel expects so loader can zero 15730 * out the rest of the record. 15731 */ 15732 if (copy_to_bpfptr_offset(uattr, 15733 offsetof(union bpf_attr, func_info_rec_size), 15734 &min_size, sizeof(min_size))) 15735 ret = -EFAULT; 15736 } 15737 goto err_free; 15738 } 15739 15740 if (copy_from_bpfptr(&krecord[i], urecord, min_size)) { 15741 ret = -EFAULT; 15742 goto err_free; 15743 } 15744 15745 /* check insn_off */ 15746 ret = -EINVAL; 15747 if (i == 0) { 15748 if (krecord[i].insn_off) { 15749 verbose(env, 15750 "nonzero insn_off %u for the first func info record", 15751 krecord[i].insn_off); 15752 goto err_free; 15753 } 15754 } else if (krecord[i].insn_off <= prev_offset) { 15755 verbose(env, 15756 "same or smaller insn offset (%u) than previous func info record (%u)", 15757 krecord[i].insn_off, prev_offset); 15758 goto err_free; 15759 } 15760 15761 /* check type_id */ 15762 type = btf_type_by_id(btf, krecord[i].type_id); 15763 if (!type || !btf_type_is_func(type)) { 15764 verbose(env, "invalid type id %d in func info", 15765 krecord[i].type_id); 15766 goto err_free; 15767 } 15768 15769 func_proto = btf_type_by_id(btf, type->type); 15770 if (unlikely(!func_proto || !btf_type_is_func_proto(func_proto))) 15771 /* btf_func_check() already verified it during BTF load */ 15772 goto err_free; 15773 15774 prev_offset = krecord[i].insn_off; 15775 bpfptr_add(&urecord, urec_size); 15776 } 15777 15778 prog->aux->func_info = krecord; 15779 prog->aux->func_info_cnt = nfuncs; 15780 return 0; 15781 15782 err_free: 15783 kvfree(krecord); 15784 return ret; 15785 } 15786 15787 static int check_btf_func(struct bpf_verifier_env *env, 15788 const union bpf_attr *attr, 15789 bpfptr_t uattr) 15790 { 15791 const struct btf_type *type, *func_proto, *ret_type; 15792 u32 i, nfuncs, urec_size; 15793 struct bpf_func_info *krecord; 15794 struct bpf_func_info_aux *info_aux = NULL; 15795 struct bpf_prog *prog; 15796 const struct btf *btf; 15797 bpfptr_t urecord; 15798 bool scalar_return; 15799 int ret = -ENOMEM; 15800 15801 nfuncs = attr->func_info_cnt; 15802 if (!nfuncs) { 15803 if (check_abnormal_return(env)) 15804 return -EINVAL; 15805 return 0; 15806 } 15807 if (nfuncs != env->subprog_cnt) { 15808 verbose(env, "number of funcs in func_info doesn't match number of subprogs\n"); 15809 return -EINVAL; 15810 } 15811 15812 urec_size = attr->func_info_rec_size; 15813 15814 prog = env->prog; 15815 btf = prog->aux->btf; 15816 15817 urecord = make_bpfptr(attr->func_info, uattr.is_kernel); 15818 15819 krecord = prog->aux->func_info; 15820 info_aux = kcalloc(nfuncs, sizeof(*info_aux), GFP_KERNEL | __GFP_NOWARN); 15821 if (!info_aux) 15822 return -ENOMEM; 15823 15824 for (i = 0; i < nfuncs; i++) { 15825 /* check insn_off */ 15826 ret = -EINVAL; 15827 15828 if (env->subprog_info[i].start != krecord[i].insn_off) { 15829 verbose(env, "func_info BTF section doesn't match subprog layout in BPF program\n"); 15830 goto err_free; 15831 } 15832 15833 /* Already checked type_id */ 15834 type = btf_type_by_id(btf, krecord[i].type_id); 15835 info_aux[i].linkage = BTF_INFO_VLEN(type->info); 15836 /* Already checked func_proto */ 15837 func_proto = btf_type_by_id(btf, type->type); 15838 15839 ret_type = btf_type_skip_modifiers(btf, func_proto->type, NULL); 15840 scalar_return = 15841 btf_type_is_small_int(ret_type) || btf_is_any_enum(ret_type); 15842 if (i && !scalar_return && env->subprog_info[i].has_ld_abs) { 15843 verbose(env, "LD_ABS is only allowed in functions that return 'int'.\n"); 15844 goto err_free; 15845 } 15846 if (i && !scalar_return && env->subprog_info[i].has_tail_call) { 15847 verbose(env, "tail_call is only allowed in functions that return 'int'.\n"); 15848 goto err_free; 15849 } 15850 15851 bpfptr_add(&urecord, urec_size); 15852 } 15853 15854 prog->aux->func_info_aux = info_aux; 15855 return 0; 15856 15857 err_free: 15858 kfree(info_aux); 15859 return ret; 15860 } 15861 15862 static void adjust_btf_func(struct bpf_verifier_env *env) 15863 { 15864 struct bpf_prog_aux *aux = env->prog->aux; 15865 int i; 15866 15867 if (!aux->func_info) 15868 return; 15869 15870 /* func_info is not available for hidden subprogs */ 15871 for (i = 0; i < env->subprog_cnt - env->hidden_subprog_cnt; i++) 15872 aux->func_info[i].insn_off = env->subprog_info[i].start; 15873 } 15874 15875 #define MIN_BPF_LINEINFO_SIZE offsetofend(struct bpf_line_info, line_col) 15876 #define MAX_LINEINFO_REC_SIZE MAX_FUNCINFO_REC_SIZE 15877 15878 static int check_btf_line(struct bpf_verifier_env *env, 15879 const union bpf_attr *attr, 15880 bpfptr_t uattr) 15881 { 15882 u32 i, s, nr_linfo, ncopy, expected_size, rec_size, prev_offset = 0; 15883 struct bpf_subprog_info *sub; 15884 struct bpf_line_info *linfo; 15885 struct bpf_prog *prog; 15886 const struct btf *btf; 15887 bpfptr_t ulinfo; 15888 int err; 15889 15890 nr_linfo = attr->line_info_cnt; 15891 if (!nr_linfo) 15892 return 0; 15893 if (nr_linfo > INT_MAX / sizeof(struct bpf_line_info)) 15894 return -EINVAL; 15895 15896 rec_size = attr->line_info_rec_size; 15897 if (rec_size < MIN_BPF_LINEINFO_SIZE || 15898 rec_size > MAX_LINEINFO_REC_SIZE || 15899 rec_size & (sizeof(u32) - 1)) 15900 return -EINVAL; 15901 15902 /* Need to zero it in case the userspace may 15903 * pass in a smaller bpf_line_info object. 15904 */ 15905 linfo = kvcalloc(nr_linfo, sizeof(struct bpf_line_info), 15906 GFP_KERNEL | __GFP_NOWARN); 15907 if (!linfo) 15908 return -ENOMEM; 15909 15910 prog = env->prog; 15911 btf = prog->aux->btf; 15912 15913 s = 0; 15914 sub = env->subprog_info; 15915 ulinfo = make_bpfptr(attr->line_info, uattr.is_kernel); 15916 expected_size = sizeof(struct bpf_line_info); 15917 ncopy = min_t(u32, expected_size, rec_size); 15918 for (i = 0; i < nr_linfo; i++) { 15919 err = bpf_check_uarg_tail_zero(ulinfo, expected_size, rec_size); 15920 if (err) { 15921 if (err == -E2BIG) { 15922 verbose(env, "nonzero tailing record in line_info"); 15923 if (copy_to_bpfptr_offset(uattr, 15924 offsetof(union bpf_attr, line_info_rec_size), 15925 &expected_size, sizeof(expected_size))) 15926 err = -EFAULT; 15927 } 15928 goto err_free; 15929 } 15930 15931 if (copy_from_bpfptr(&linfo[i], ulinfo, ncopy)) { 15932 err = -EFAULT; 15933 goto err_free; 15934 } 15935 15936 /* 15937 * Check insn_off to ensure 15938 * 1) strictly increasing AND 15939 * 2) bounded by prog->len 15940 * 15941 * The linfo[0].insn_off == 0 check logically falls into 15942 * the later "missing bpf_line_info for func..." case 15943 * because the first linfo[0].insn_off must be the 15944 * first sub also and the first sub must have 15945 * subprog_info[0].start == 0. 15946 */ 15947 if ((i && linfo[i].insn_off <= prev_offset) || 15948 linfo[i].insn_off >= prog->len) { 15949 verbose(env, "Invalid line_info[%u].insn_off:%u (prev_offset:%u prog->len:%u)\n", 15950 i, linfo[i].insn_off, prev_offset, 15951 prog->len); 15952 err = -EINVAL; 15953 goto err_free; 15954 } 15955 15956 if (!prog->insnsi[linfo[i].insn_off].code) { 15957 verbose(env, 15958 "Invalid insn code at line_info[%u].insn_off\n", 15959 i); 15960 err = -EINVAL; 15961 goto err_free; 15962 } 15963 15964 if (!btf_name_by_offset(btf, linfo[i].line_off) || 15965 !btf_name_by_offset(btf, linfo[i].file_name_off)) { 15966 verbose(env, "Invalid line_info[%u].line_off or .file_name_off\n", i); 15967 err = -EINVAL; 15968 goto err_free; 15969 } 15970 15971 if (s != env->subprog_cnt) { 15972 if (linfo[i].insn_off == sub[s].start) { 15973 sub[s].linfo_idx = i; 15974 s++; 15975 } else if (sub[s].start < linfo[i].insn_off) { 15976 verbose(env, "missing bpf_line_info for func#%u\n", s); 15977 err = -EINVAL; 15978 goto err_free; 15979 } 15980 } 15981 15982 prev_offset = linfo[i].insn_off; 15983 bpfptr_add(&ulinfo, rec_size); 15984 } 15985 15986 if (s != env->subprog_cnt) { 15987 verbose(env, "missing bpf_line_info for %u funcs starting from func#%u\n", 15988 env->subprog_cnt - s, s); 15989 err = -EINVAL; 15990 goto err_free; 15991 } 15992 15993 prog->aux->linfo = linfo; 15994 prog->aux->nr_linfo = nr_linfo; 15995 15996 return 0; 15997 15998 err_free: 15999 kvfree(linfo); 16000 return err; 16001 } 16002 16003 #define MIN_CORE_RELO_SIZE sizeof(struct bpf_core_relo) 16004 #define MAX_CORE_RELO_SIZE MAX_FUNCINFO_REC_SIZE 16005 16006 static int check_core_relo(struct bpf_verifier_env *env, 16007 const union bpf_attr *attr, 16008 bpfptr_t uattr) 16009 { 16010 u32 i, nr_core_relo, ncopy, expected_size, rec_size; 16011 struct bpf_core_relo core_relo = {}; 16012 struct bpf_prog *prog = env->prog; 16013 const struct btf *btf = prog->aux->btf; 16014 struct bpf_core_ctx ctx = { 16015 .log = &env->log, 16016 .btf = btf, 16017 }; 16018 bpfptr_t u_core_relo; 16019 int err; 16020 16021 nr_core_relo = attr->core_relo_cnt; 16022 if (!nr_core_relo) 16023 return 0; 16024 if (nr_core_relo > INT_MAX / sizeof(struct bpf_core_relo)) 16025 return -EINVAL; 16026 16027 rec_size = attr->core_relo_rec_size; 16028 if (rec_size < MIN_CORE_RELO_SIZE || 16029 rec_size > MAX_CORE_RELO_SIZE || 16030 rec_size % sizeof(u32)) 16031 return -EINVAL; 16032 16033 u_core_relo = make_bpfptr(attr->core_relos, uattr.is_kernel); 16034 expected_size = sizeof(struct bpf_core_relo); 16035 ncopy = min_t(u32, expected_size, rec_size); 16036 16037 /* Unlike func_info and line_info, copy and apply each CO-RE 16038 * relocation record one at a time. 16039 */ 16040 for (i = 0; i < nr_core_relo; i++) { 16041 /* future proofing when sizeof(bpf_core_relo) changes */ 16042 err = bpf_check_uarg_tail_zero(u_core_relo, expected_size, rec_size); 16043 if (err) { 16044 if (err == -E2BIG) { 16045 verbose(env, "nonzero tailing record in core_relo"); 16046 if (copy_to_bpfptr_offset(uattr, 16047 offsetof(union bpf_attr, core_relo_rec_size), 16048 &expected_size, sizeof(expected_size))) 16049 err = -EFAULT; 16050 } 16051 break; 16052 } 16053 16054 if (copy_from_bpfptr(&core_relo, u_core_relo, ncopy)) { 16055 err = -EFAULT; 16056 break; 16057 } 16058 16059 if (core_relo.insn_off % 8 || core_relo.insn_off / 8 >= prog->len) { 16060 verbose(env, "Invalid core_relo[%u].insn_off:%u prog->len:%u\n", 16061 i, core_relo.insn_off, prog->len); 16062 err = -EINVAL; 16063 break; 16064 } 16065 16066 err = bpf_core_apply(&ctx, &core_relo, i, 16067 &prog->insnsi[core_relo.insn_off / 8]); 16068 if (err) 16069 break; 16070 bpfptr_add(&u_core_relo, rec_size); 16071 } 16072 return err; 16073 } 16074 16075 static int check_btf_info_early(struct bpf_verifier_env *env, 16076 const union bpf_attr *attr, 16077 bpfptr_t uattr) 16078 { 16079 struct btf *btf; 16080 int err; 16081 16082 if (!attr->func_info_cnt && !attr->line_info_cnt) { 16083 if (check_abnormal_return(env)) 16084 return -EINVAL; 16085 return 0; 16086 } 16087 16088 btf = btf_get_by_fd(attr->prog_btf_fd); 16089 if (IS_ERR(btf)) 16090 return PTR_ERR(btf); 16091 if (btf_is_kernel(btf)) { 16092 btf_put(btf); 16093 return -EACCES; 16094 } 16095 env->prog->aux->btf = btf; 16096 16097 err = check_btf_func_early(env, attr, uattr); 16098 if (err) 16099 return err; 16100 return 0; 16101 } 16102 16103 static int check_btf_info(struct bpf_verifier_env *env, 16104 const union bpf_attr *attr, 16105 bpfptr_t uattr) 16106 { 16107 int err; 16108 16109 if (!attr->func_info_cnt && !attr->line_info_cnt) { 16110 if (check_abnormal_return(env)) 16111 return -EINVAL; 16112 return 0; 16113 } 16114 16115 err = check_btf_func(env, attr, uattr); 16116 if (err) 16117 return err; 16118 16119 err = check_btf_line(env, attr, uattr); 16120 if (err) 16121 return err; 16122 16123 err = check_core_relo(env, attr, uattr); 16124 if (err) 16125 return err; 16126 16127 return 0; 16128 } 16129 16130 /* check %cur's range satisfies %old's */ 16131 static bool range_within(struct bpf_reg_state *old, 16132 struct bpf_reg_state *cur) 16133 { 16134 return old->umin_value <= cur->umin_value && 16135 old->umax_value >= cur->umax_value && 16136 old->smin_value <= cur->smin_value && 16137 old->smax_value >= cur->smax_value && 16138 old->u32_min_value <= cur->u32_min_value && 16139 old->u32_max_value >= cur->u32_max_value && 16140 old->s32_min_value <= cur->s32_min_value && 16141 old->s32_max_value >= cur->s32_max_value; 16142 } 16143 16144 /* If in the old state two registers had the same id, then they need to have 16145 * the same id in the new state as well. But that id could be different from 16146 * the old state, so we need to track the mapping from old to new ids. 16147 * Once we have seen that, say, a reg with old id 5 had new id 9, any subsequent 16148 * regs with old id 5 must also have new id 9 for the new state to be safe. But 16149 * regs with a different old id could still have new id 9, we don't care about 16150 * that. 16151 * So we look through our idmap to see if this old id has been seen before. If 16152 * so, we require the new id to match; otherwise, we add the id pair to the map. 16153 */ 16154 static bool check_ids(u32 old_id, u32 cur_id, struct bpf_idmap *idmap) 16155 { 16156 struct bpf_id_pair *map = idmap->map; 16157 unsigned int i; 16158 16159 /* either both IDs should be set or both should be zero */ 16160 if (!!old_id != !!cur_id) 16161 return false; 16162 16163 if (old_id == 0) /* cur_id == 0 as well */ 16164 return true; 16165 16166 for (i = 0; i < BPF_ID_MAP_SIZE; i++) { 16167 if (!map[i].old) { 16168 /* Reached an empty slot; haven't seen this id before */ 16169 map[i].old = old_id; 16170 map[i].cur = cur_id; 16171 return true; 16172 } 16173 if (map[i].old == old_id) 16174 return map[i].cur == cur_id; 16175 if (map[i].cur == cur_id) 16176 return false; 16177 } 16178 /* We ran out of idmap slots, which should be impossible */ 16179 WARN_ON_ONCE(1); 16180 return false; 16181 } 16182 16183 /* Similar to check_ids(), but allocate a unique temporary ID 16184 * for 'old_id' or 'cur_id' of zero. 16185 * This makes pairs like '0 vs unique ID', 'unique ID vs 0' valid. 16186 */ 16187 static bool check_scalar_ids(u32 old_id, u32 cur_id, struct bpf_idmap *idmap) 16188 { 16189 old_id = old_id ? old_id : ++idmap->tmp_id_gen; 16190 cur_id = cur_id ? cur_id : ++idmap->tmp_id_gen; 16191 16192 return check_ids(old_id, cur_id, idmap); 16193 } 16194 16195 static void clean_func_state(struct bpf_verifier_env *env, 16196 struct bpf_func_state *st) 16197 { 16198 enum bpf_reg_liveness live; 16199 int i, j; 16200 16201 for (i = 0; i < BPF_REG_FP; i++) { 16202 live = st->regs[i].live; 16203 /* liveness must not touch this register anymore */ 16204 st->regs[i].live |= REG_LIVE_DONE; 16205 if (!(live & REG_LIVE_READ)) 16206 /* since the register is unused, clear its state 16207 * to make further comparison simpler 16208 */ 16209 __mark_reg_not_init(env, &st->regs[i]); 16210 } 16211 16212 for (i = 0; i < st->allocated_stack / BPF_REG_SIZE; i++) { 16213 live = st->stack[i].spilled_ptr.live; 16214 /* liveness must not touch this stack slot anymore */ 16215 st->stack[i].spilled_ptr.live |= REG_LIVE_DONE; 16216 if (!(live & REG_LIVE_READ)) { 16217 __mark_reg_not_init(env, &st->stack[i].spilled_ptr); 16218 for (j = 0; j < BPF_REG_SIZE; j++) 16219 st->stack[i].slot_type[j] = STACK_INVALID; 16220 } 16221 } 16222 } 16223 16224 static void clean_verifier_state(struct bpf_verifier_env *env, 16225 struct bpf_verifier_state *st) 16226 { 16227 int i; 16228 16229 if (st->frame[0]->regs[0].live & REG_LIVE_DONE) 16230 /* all regs in this state in all frames were already marked */ 16231 return; 16232 16233 for (i = 0; i <= st->curframe; i++) 16234 clean_func_state(env, st->frame[i]); 16235 } 16236 16237 /* the parentage chains form a tree. 16238 * the verifier states are added to state lists at given insn and 16239 * pushed into state stack for future exploration. 16240 * when the verifier reaches bpf_exit insn some of the verifer states 16241 * stored in the state lists have their final liveness state already, 16242 * but a lot of states will get revised from liveness point of view when 16243 * the verifier explores other branches. 16244 * Example: 16245 * 1: r0 = 1 16246 * 2: if r1 == 100 goto pc+1 16247 * 3: r0 = 2 16248 * 4: exit 16249 * when the verifier reaches exit insn the register r0 in the state list of 16250 * insn 2 will be seen as !REG_LIVE_READ. Then the verifier pops the other_branch 16251 * of insn 2 and goes exploring further. At the insn 4 it will walk the 16252 * parentage chain from insn 4 into insn 2 and will mark r0 as REG_LIVE_READ. 16253 * 16254 * Since the verifier pushes the branch states as it sees them while exploring 16255 * the program the condition of walking the branch instruction for the second 16256 * time means that all states below this branch were already explored and 16257 * their final liveness marks are already propagated. 16258 * Hence when the verifier completes the search of state list in is_state_visited() 16259 * we can call this clean_live_states() function to mark all liveness states 16260 * as REG_LIVE_DONE to indicate that 'parent' pointers of 'struct bpf_reg_state' 16261 * will not be used. 16262 * This function also clears the registers and stack for states that !READ 16263 * to simplify state merging. 16264 * 16265 * Important note here that walking the same branch instruction in the callee 16266 * doesn't meant that the states are DONE. The verifier has to compare 16267 * the callsites 16268 */ 16269 static void clean_live_states(struct bpf_verifier_env *env, int insn, 16270 struct bpf_verifier_state *cur) 16271 { 16272 struct bpf_verifier_state_list *sl; 16273 16274 sl = *explored_state(env, insn); 16275 while (sl) { 16276 if (sl->state.branches) 16277 goto next; 16278 if (sl->state.insn_idx != insn || 16279 !same_callsites(&sl->state, cur)) 16280 goto next; 16281 clean_verifier_state(env, &sl->state); 16282 next: 16283 sl = sl->next; 16284 } 16285 } 16286 16287 static bool regs_exact(const struct bpf_reg_state *rold, 16288 const struct bpf_reg_state *rcur, 16289 struct bpf_idmap *idmap) 16290 { 16291 return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 && 16292 check_ids(rold->id, rcur->id, idmap) && 16293 check_ids(rold->ref_obj_id, rcur->ref_obj_id, idmap); 16294 } 16295 16296 /* Returns true if (rold safe implies rcur safe) */ 16297 static bool regsafe(struct bpf_verifier_env *env, struct bpf_reg_state *rold, 16298 struct bpf_reg_state *rcur, struct bpf_idmap *idmap, bool exact) 16299 { 16300 if (exact) 16301 return regs_exact(rold, rcur, idmap); 16302 16303 if (!(rold->live & REG_LIVE_READ)) 16304 /* explored state didn't use this */ 16305 return true; 16306 if (rold->type == NOT_INIT) 16307 /* explored state can't have used this */ 16308 return true; 16309 if (rcur->type == NOT_INIT) 16310 return false; 16311 16312 /* Enforce that register types have to match exactly, including their 16313 * modifiers (like PTR_MAYBE_NULL, MEM_RDONLY, etc), as a general 16314 * rule. 16315 * 16316 * One can make a point that using a pointer register as unbounded 16317 * SCALAR would be technically acceptable, but this could lead to 16318 * pointer leaks because scalars are allowed to leak while pointers 16319 * are not. We could make this safe in special cases if root is 16320 * calling us, but it's probably not worth the hassle. 16321 * 16322 * Also, register types that are *not* MAYBE_NULL could technically be 16323 * safe to use as their MAYBE_NULL variants (e.g., PTR_TO_MAP_VALUE 16324 * is safe to be used as PTR_TO_MAP_VALUE_OR_NULL, provided both point 16325 * to the same map). 16326 * However, if the old MAYBE_NULL register then got NULL checked, 16327 * doing so could have affected others with the same id, and we can't 16328 * check for that because we lost the id when we converted to 16329 * a non-MAYBE_NULL variant. 16330 * So, as a general rule we don't allow mixing MAYBE_NULL and 16331 * non-MAYBE_NULL registers as well. 16332 */ 16333 if (rold->type != rcur->type) 16334 return false; 16335 16336 switch (base_type(rold->type)) { 16337 case SCALAR_VALUE: 16338 if (env->explore_alu_limits) { 16339 /* explore_alu_limits disables tnum_in() and range_within() 16340 * logic and requires everything to be strict 16341 */ 16342 return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 && 16343 check_scalar_ids(rold->id, rcur->id, idmap); 16344 } 16345 if (!rold->precise) 16346 return true; 16347 /* Why check_ids() for scalar registers? 16348 * 16349 * Consider the following BPF code: 16350 * 1: r6 = ... unbound scalar, ID=a ... 16351 * 2: r7 = ... unbound scalar, ID=b ... 16352 * 3: if (r6 > r7) goto +1 16353 * 4: r6 = r7 16354 * 5: if (r6 > X) goto ... 16355 * 6: ... memory operation using r7 ... 16356 * 16357 * First verification path is [1-6]: 16358 * - at (4) same bpf_reg_state::id (b) would be assigned to r6 and r7; 16359 * - at (5) r6 would be marked <= X, find_equal_scalars() would also mark 16360 * r7 <= X, because r6 and r7 share same id. 16361 * Next verification path is [1-4, 6]. 16362 * 16363 * Instruction (6) would be reached in two states: 16364 * I. r6{.id=b}, r7{.id=b} via path 1-6; 16365 * II. r6{.id=a}, r7{.id=b} via path 1-4, 6. 16366 * 16367 * Use check_ids() to distinguish these states. 16368 * --- 16369 * Also verify that new value satisfies old value range knowledge. 16370 */ 16371 return range_within(rold, rcur) && 16372 tnum_in(rold->var_off, rcur->var_off) && 16373 check_scalar_ids(rold->id, rcur->id, idmap); 16374 case PTR_TO_MAP_KEY: 16375 case PTR_TO_MAP_VALUE: 16376 case PTR_TO_MEM: 16377 case PTR_TO_BUF: 16378 case PTR_TO_TP_BUFFER: 16379 /* If the new min/max/var_off satisfy the old ones and 16380 * everything else matches, we are OK. 16381 */ 16382 return memcmp(rold, rcur, offsetof(struct bpf_reg_state, var_off)) == 0 && 16383 range_within(rold, rcur) && 16384 tnum_in(rold->var_off, rcur->var_off) && 16385 check_ids(rold->id, rcur->id, idmap) && 16386 check_ids(rold->ref_obj_id, rcur->ref_obj_id, idmap); 16387 case PTR_TO_PACKET_META: 16388 case PTR_TO_PACKET: 16389 /* We must have at least as much range as the old ptr 16390 * did, so that any accesses which were safe before are 16391 * still safe. This is true even if old range < old off, 16392 * since someone could have accessed through (ptr - k), or 16393 * even done ptr -= k in a register, to get a safe access. 16394 */ 16395 if (rold->range > rcur->range) 16396 return false; 16397 /* If the offsets don't match, we can't trust our alignment; 16398 * nor can we be sure that we won't fall out of range. 16399 */ 16400 if (rold->off != rcur->off) 16401 return false; 16402 /* id relations must be preserved */ 16403 if (!check_ids(rold->id, rcur->id, idmap)) 16404 return false; 16405 /* new val must satisfy old val knowledge */ 16406 return range_within(rold, rcur) && 16407 tnum_in(rold->var_off, rcur->var_off); 16408 case PTR_TO_STACK: 16409 /* two stack pointers are equal only if they're pointing to 16410 * the same stack frame, since fp-8 in foo != fp-8 in bar 16411 */ 16412 return regs_exact(rold, rcur, idmap) && rold->frameno == rcur->frameno; 16413 default: 16414 return regs_exact(rold, rcur, idmap); 16415 } 16416 } 16417 16418 static bool stacksafe(struct bpf_verifier_env *env, struct bpf_func_state *old, 16419 struct bpf_func_state *cur, struct bpf_idmap *idmap, bool exact) 16420 { 16421 int i, spi; 16422 16423 /* walk slots of the explored stack and ignore any additional 16424 * slots in the current stack, since explored(safe) state 16425 * didn't use them 16426 */ 16427 for (i = 0; i < old->allocated_stack; i++) { 16428 struct bpf_reg_state *old_reg, *cur_reg; 16429 16430 spi = i / BPF_REG_SIZE; 16431 16432 if (exact && 16433 old->stack[spi].slot_type[i % BPF_REG_SIZE] != 16434 cur->stack[spi].slot_type[i % BPF_REG_SIZE]) 16435 return false; 16436 16437 if (!(old->stack[spi].spilled_ptr.live & REG_LIVE_READ) && !exact) { 16438 i += BPF_REG_SIZE - 1; 16439 /* explored state didn't use this */ 16440 continue; 16441 } 16442 16443 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_INVALID) 16444 continue; 16445 16446 if (env->allow_uninit_stack && 16447 old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC) 16448 continue; 16449 16450 /* explored stack has more populated slots than current stack 16451 * and these slots were used 16452 */ 16453 if (i >= cur->allocated_stack) 16454 return false; 16455 16456 /* if old state was safe with misc data in the stack 16457 * it will be safe with zero-initialized stack. 16458 * The opposite is not true 16459 */ 16460 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC && 16461 cur->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_ZERO) 16462 continue; 16463 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] != 16464 cur->stack[spi].slot_type[i % BPF_REG_SIZE]) 16465 /* Ex: old explored (safe) state has STACK_SPILL in 16466 * this stack slot, but current has STACK_MISC -> 16467 * this verifier states are not equivalent, 16468 * return false to continue verification of this path 16469 */ 16470 return false; 16471 if (i % BPF_REG_SIZE != BPF_REG_SIZE - 1) 16472 continue; 16473 /* Both old and cur are having same slot_type */ 16474 switch (old->stack[spi].slot_type[BPF_REG_SIZE - 1]) { 16475 case STACK_SPILL: 16476 /* when explored and current stack slot are both storing 16477 * spilled registers, check that stored pointers types 16478 * are the same as well. 16479 * Ex: explored safe path could have stored 16480 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -8} 16481 * but current path has stored: 16482 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -16} 16483 * such verifier states are not equivalent. 16484 * return false to continue verification of this path 16485 */ 16486 if (!regsafe(env, &old->stack[spi].spilled_ptr, 16487 &cur->stack[spi].spilled_ptr, idmap, exact)) 16488 return false; 16489 break; 16490 case STACK_DYNPTR: 16491 old_reg = &old->stack[spi].spilled_ptr; 16492 cur_reg = &cur->stack[spi].spilled_ptr; 16493 if (old_reg->dynptr.type != cur_reg->dynptr.type || 16494 old_reg->dynptr.first_slot != cur_reg->dynptr.first_slot || 16495 !check_ids(old_reg->ref_obj_id, cur_reg->ref_obj_id, idmap)) 16496 return false; 16497 break; 16498 case STACK_ITER: 16499 old_reg = &old->stack[spi].spilled_ptr; 16500 cur_reg = &cur->stack[spi].spilled_ptr; 16501 /* iter.depth is not compared between states as it 16502 * doesn't matter for correctness and would otherwise 16503 * prevent convergence; we maintain it only to prevent 16504 * infinite loop check triggering, see 16505 * iter_active_depths_differ() 16506 */ 16507 if (old_reg->iter.btf != cur_reg->iter.btf || 16508 old_reg->iter.btf_id != cur_reg->iter.btf_id || 16509 old_reg->iter.state != cur_reg->iter.state || 16510 /* ignore {old_reg,cur_reg}->iter.depth, see above */ 16511 !check_ids(old_reg->ref_obj_id, cur_reg->ref_obj_id, idmap)) 16512 return false; 16513 break; 16514 case STACK_MISC: 16515 case STACK_ZERO: 16516 case STACK_INVALID: 16517 continue; 16518 /* Ensure that new unhandled slot types return false by default */ 16519 default: 16520 return false; 16521 } 16522 } 16523 return true; 16524 } 16525 16526 static bool refsafe(struct bpf_func_state *old, struct bpf_func_state *cur, 16527 struct bpf_idmap *idmap) 16528 { 16529 int i; 16530 16531 if (old->acquired_refs != cur->acquired_refs) 16532 return false; 16533 16534 for (i = 0; i < old->acquired_refs; i++) { 16535 if (!check_ids(old->refs[i].id, cur->refs[i].id, idmap)) 16536 return false; 16537 } 16538 16539 return true; 16540 } 16541 16542 /* compare two verifier states 16543 * 16544 * all states stored in state_list are known to be valid, since 16545 * verifier reached 'bpf_exit' instruction through them 16546 * 16547 * this function is called when verifier exploring different branches of 16548 * execution popped from the state stack. If it sees an old state that has 16549 * more strict register state and more strict stack state then this execution 16550 * branch doesn't need to be explored further, since verifier already 16551 * concluded that more strict state leads to valid finish. 16552 * 16553 * Therefore two states are equivalent if register state is more conservative 16554 * and explored stack state is more conservative than the current one. 16555 * Example: 16556 * explored current 16557 * (slot1=INV slot2=MISC) == (slot1=MISC slot2=MISC) 16558 * (slot1=MISC slot2=MISC) != (slot1=INV slot2=MISC) 16559 * 16560 * In other words if current stack state (one being explored) has more 16561 * valid slots than old one that already passed validation, it means 16562 * the verifier can stop exploring and conclude that current state is valid too 16563 * 16564 * Similarly with registers. If explored state has register type as invalid 16565 * whereas register type in current state is meaningful, it means that 16566 * the current state will reach 'bpf_exit' instruction safely 16567 */ 16568 static bool func_states_equal(struct bpf_verifier_env *env, struct bpf_func_state *old, 16569 struct bpf_func_state *cur, bool exact) 16570 { 16571 int i; 16572 16573 for (i = 0; i < MAX_BPF_REG; i++) 16574 if (!regsafe(env, &old->regs[i], &cur->regs[i], 16575 &env->idmap_scratch, exact)) 16576 return false; 16577 16578 if (!stacksafe(env, old, cur, &env->idmap_scratch, exact)) 16579 return false; 16580 16581 if (!refsafe(old, cur, &env->idmap_scratch)) 16582 return false; 16583 16584 return true; 16585 } 16586 16587 static void reset_idmap_scratch(struct bpf_verifier_env *env) 16588 { 16589 env->idmap_scratch.tmp_id_gen = env->id_gen; 16590 memset(&env->idmap_scratch.map, 0, sizeof(env->idmap_scratch.map)); 16591 } 16592 16593 static bool states_equal(struct bpf_verifier_env *env, 16594 struct bpf_verifier_state *old, 16595 struct bpf_verifier_state *cur, 16596 bool exact) 16597 { 16598 int i; 16599 16600 if (old->curframe != cur->curframe) 16601 return false; 16602 16603 reset_idmap_scratch(env); 16604 16605 /* Verification state from speculative execution simulation 16606 * must never prune a non-speculative execution one. 16607 */ 16608 if (old->speculative && !cur->speculative) 16609 return false; 16610 16611 if (old->active_lock.ptr != cur->active_lock.ptr) 16612 return false; 16613 16614 /* Old and cur active_lock's have to be either both present 16615 * or both absent. 16616 */ 16617 if (!!old->active_lock.id != !!cur->active_lock.id) 16618 return false; 16619 16620 if (old->active_lock.id && 16621 !check_ids(old->active_lock.id, cur->active_lock.id, &env->idmap_scratch)) 16622 return false; 16623 16624 if (old->active_rcu_lock != cur->active_rcu_lock) 16625 return false; 16626 16627 /* for states to be equal callsites have to be the same 16628 * and all frame states need to be equivalent 16629 */ 16630 for (i = 0; i <= old->curframe; i++) { 16631 if (old->frame[i]->callsite != cur->frame[i]->callsite) 16632 return false; 16633 if (!func_states_equal(env, old->frame[i], cur->frame[i], exact)) 16634 return false; 16635 } 16636 return true; 16637 } 16638 16639 /* Return 0 if no propagation happened. Return negative error code if error 16640 * happened. Otherwise, return the propagated bit. 16641 */ 16642 static int propagate_liveness_reg(struct bpf_verifier_env *env, 16643 struct bpf_reg_state *reg, 16644 struct bpf_reg_state *parent_reg) 16645 { 16646 u8 parent_flag = parent_reg->live & REG_LIVE_READ; 16647 u8 flag = reg->live & REG_LIVE_READ; 16648 int err; 16649 16650 /* When comes here, read flags of PARENT_REG or REG could be any of 16651 * REG_LIVE_READ64, REG_LIVE_READ32, REG_LIVE_NONE. There is no need 16652 * of propagation if PARENT_REG has strongest REG_LIVE_READ64. 16653 */ 16654 if (parent_flag == REG_LIVE_READ64 || 16655 /* Or if there is no read flag from REG. */ 16656 !flag || 16657 /* Or if the read flag from REG is the same as PARENT_REG. */ 16658 parent_flag == flag) 16659 return 0; 16660 16661 err = mark_reg_read(env, reg, parent_reg, flag); 16662 if (err) 16663 return err; 16664 16665 return flag; 16666 } 16667 16668 /* A write screens off any subsequent reads; but write marks come from the 16669 * straight-line code between a state and its parent. When we arrive at an 16670 * equivalent state (jump target or such) we didn't arrive by the straight-line 16671 * code, so read marks in the state must propagate to the parent regardless 16672 * of the state's write marks. That's what 'parent == state->parent' comparison 16673 * in mark_reg_read() is for. 16674 */ 16675 static int propagate_liveness(struct bpf_verifier_env *env, 16676 const struct bpf_verifier_state *vstate, 16677 struct bpf_verifier_state *vparent) 16678 { 16679 struct bpf_reg_state *state_reg, *parent_reg; 16680 struct bpf_func_state *state, *parent; 16681 int i, frame, err = 0; 16682 16683 if (vparent->curframe != vstate->curframe) { 16684 WARN(1, "propagate_live: parent frame %d current frame %d\n", 16685 vparent->curframe, vstate->curframe); 16686 return -EFAULT; 16687 } 16688 /* Propagate read liveness of registers... */ 16689 BUILD_BUG_ON(BPF_REG_FP + 1 != MAX_BPF_REG); 16690 for (frame = 0; frame <= vstate->curframe; frame++) { 16691 parent = vparent->frame[frame]; 16692 state = vstate->frame[frame]; 16693 parent_reg = parent->regs; 16694 state_reg = state->regs; 16695 /* We don't need to worry about FP liveness, it's read-only */ 16696 for (i = frame < vstate->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++) { 16697 err = propagate_liveness_reg(env, &state_reg[i], 16698 &parent_reg[i]); 16699 if (err < 0) 16700 return err; 16701 if (err == REG_LIVE_READ64) 16702 mark_insn_zext(env, &parent_reg[i]); 16703 } 16704 16705 /* Propagate stack slots. */ 16706 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE && 16707 i < parent->allocated_stack / BPF_REG_SIZE; i++) { 16708 parent_reg = &parent->stack[i].spilled_ptr; 16709 state_reg = &state->stack[i].spilled_ptr; 16710 err = propagate_liveness_reg(env, state_reg, 16711 parent_reg); 16712 if (err < 0) 16713 return err; 16714 } 16715 } 16716 return 0; 16717 } 16718 16719 /* find precise scalars in the previous equivalent state and 16720 * propagate them into the current state 16721 */ 16722 static int propagate_precision(struct bpf_verifier_env *env, 16723 const struct bpf_verifier_state *old) 16724 { 16725 struct bpf_reg_state *state_reg; 16726 struct bpf_func_state *state; 16727 int i, err = 0, fr; 16728 bool first; 16729 16730 for (fr = old->curframe; fr >= 0; fr--) { 16731 state = old->frame[fr]; 16732 state_reg = state->regs; 16733 first = true; 16734 for (i = 0; i < BPF_REG_FP; i++, state_reg++) { 16735 if (state_reg->type != SCALAR_VALUE || 16736 !state_reg->precise || 16737 !(state_reg->live & REG_LIVE_READ)) 16738 continue; 16739 if (env->log.level & BPF_LOG_LEVEL2) { 16740 if (first) 16741 verbose(env, "frame %d: propagating r%d", fr, i); 16742 else 16743 verbose(env, ",r%d", i); 16744 } 16745 bt_set_frame_reg(&env->bt, fr, i); 16746 first = false; 16747 } 16748 16749 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) { 16750 if (!is_spilled_reg(&state->stack[i])) 16751 continue; 16752 state_reg = &state->stack[i].spilled_ptr; 16753 if (state_reg->type != SCALAR_VALUE || 16754 !state_reg->precise || 16755 !(state_reg->live & REG_LIVE_READ)) 16756 continue; 16757 if (env->log.level & BPF_LOG_LEVEL2) { 16758 if (first) 16759 verbose(env, "frame %d: propagating fp%d", 16760 fr, (-i - 1) * BPF_REG_SIZE); 16761 else 16762 verbose(env, ",fp%d", (-i - 1) * BPF_REG_SIZE); 16763 } 16764 bt_set_frame_slot(&env->bt, fr, i); 16765 first = false; 16766 } 16767 if (!first) 16768 verbose(env, "\n"); 16769 } 16770 16771 err = mark_chain_precision_batch(env); 16772 if (err < 0) 16773 return err; 16774 16775 return 0; 16776 } 16777 16778 static bool states_maybe_looping(struct bpf_verifier_state *old, 16779 struct bpf_verifier_state *cur) 16780 { 16781 struct bpf_func_state *fold, *fcur; 16782 int i, fr = cur->curframe; 16783 16784 if (old->curframe != fr) 16785 return false; 16786 16787 fold = old->frame[fr]; 16788 fcur = cur->frame[fr]; 16789 for (i = 0; i < MAX_BPF_REG; i++) 16790 if (memcmp(&fold->regs[i], &fcur->regs[i], 16791 offsetof(struct bpf_reg_state, parent))) 16792 return false; 16793 return true; 16794 } 16795 16796 static bool is_iter_next_insn(struct bpf_verifier_env *env, int insn_idx) 16797 { 16798 return env->insn_aux_data[insn_idx].is_iter_next; 16799 } 16800 16801 /* is_state_visited() handles iter_next() (see process_iter_next_call() for 16802 * terminology) calls specially: as opposed to bounded BPF loops, it *expects* 16803 * states to match, which otherwise would look like an infinite loop. So while 16804 * iter_next() calls are taken care of, we still need to be careful and 16805 * prevent erroneous and too eager declaration of "ininite loop", when 16806 * iterators are involved. 16807 * 16808 * Here's a situation in pseudo-BPF assembly form: 16809 * 16810 * 0: again: ; set up iter_next() call args 16811 * 1: r1 = &it ; <CHECKPOINT HERE> 16812 * 2: call bpf_iter_num_next ; this is iter_next() call 16813 * 3: if r0 == 0 goto done 16814 * 4: ... something useful here ... 16815 * 5: goto again ; another iteration 16816 * 6: done: 16817 * 7: r1 = &it 16818 * 8: call bpf_iter_num_destroy ; clean up iter state 16819 * 9: exit 16820 * 16821 * This is a typical loop. Let's assume that we have a prune point at 1:, 16822 * before we get to `call bpf_iter_num_next` (e.g., because of that `goto 16823 * again`, assuming other heuristics don't get in a way). 16824 * 16825 * When we first time come to 1:, let's say we have some state X. We proceed 16826 * to 2:, fork states, enqueue ACTIVE, validate NULL case successfully, exit. 16827 * Now we come back to validate that forked ACTIVE state. We proceed through 16828 * 3-5, come to goto, jump to 1:. Let's assume our state didn't change, so we 16829 * are converging. But the problem is that we don't know that yet, as this 16830 * convergence has to happen at iter_next() call site only. So if nothing is 16831 * done, at 1: verifier will use bounded loop logic and declare infinite 16832 * looping (and would be *technically* correct, if not for iterator's 16833 * "eventual sticky NULL" contract, see process_iter_next_call()). But we 16834 * don't want that. So what we do in process_iter_next_call() when we go on 16835 * another ACTIVE iteration, we bump slot->iter.depth, to mark that it's 16836 * a different iteration. So when we suspect an infinite loop, we additionally 16837 * check if any of the *ACTIVE* iterator states depths differ. If yes, we 16838 * pretend we are not looping and wait for next iter_next() call. 16839 * 16840 * This only applies to ACTIVE state. In DRAINED state we don't expect to 16841 * loop, because that would actually mean infinite loop, as DRAINED state is 16842 * "sticky", and so we'll keep returning into the same instruction with the 16843 * same state (at least in one of possible code paths). 16844 * 16845 * This approach allows to keep infinite loop heuristic even in the face of 16846 * active iterator. E.g., C snippet below is and will be detected as 16847 * inifintely looping: 16848 * 16849 * struct bpf_iter_num it; 16850 * int *p, x; 16851 * 16852 * bpf_iter_num_new(&it, 0, 10); 16853 * while ((p = bpf_iter_num_next(&t))) { 16854 * x = p; 16855 * while (x--) {} // <<-- infinite loop here 16856 * } 16857 * 16858 */ 16859 static bool iter_active_depths_differ(struct bpf_verifier_state *old, struct bpf_verifier_state *cur) 16860 { 16861 struct bpf_reg_state *slot, *cur_slot; 16862 struct bpf_func_state *state; 16863 int i, fr; 16864 16865 for (fr = old->curframe; fr >= 0; fr--) { 16866 state = old->frame[fr]; 16867 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) { 16868 if (state->stack[i].slot_type[0] != STACK_ITER) 16869 continue; 16870 16871 slot = &state->stack[i].spilled_ptr; 16872 if (slot->iter.state != BPF_ITER_STATE_ACTIVE) 16873 continue; 16874 16875 cur_slot = &cur->frame[fr]->stack[i].spilled_ptr; 16876 if (cur_slot->iter.depth != slot->iter.depth) 16877 return true; 16878 } 16879 } 16880 return false; 16881 } 16882 16883 static int is_state_visited(struct bpf_verifier_env *env, int insn_idx) 16884 { 16885 struct bpf_verifier_state_list *new_sl; 16886 struct bpf_verifier_state_list *sl, **pprev; 16887 struct bpf_verifier_state *cur = env->cur_state, *new, *loop_entry; 16888 int i, j, n, err, states_cnt = 0; 16889 bool force_new_state = env->test_state_freq || is_force_checkpoint(env, insn_idx); 16890 bool add_new_state = force_new_state; 16891 bool force_exact; 16892 16893 /* bpf progs typically have pruning point every 4 instructions 16894 * http://vger.kernel.org/bpfconf2019.html#session-1 16895 * Do not add new state for future pruning if the verifier hasn't seen 16896 * at least 2 jumps and at least 8 instructions. 16897 * This heuristics helps decrease 'total_states' and 'peak_states' metric. 16898 * In tests that amounts to up to 50% reduction into total verifier 16899 * memory consumption and 20% verifier time speedup. 16900 */ 16901 if (env->jmps_processed - env->prev_jmps_processed >= 2 && 16902 env->insn_processed - env->prev_insn_processed >= 8) 16903 add_new_state = true; 16904 16905 pprev = explored_state(env, insn_idx); 16906 sl = *pprev; 16907 16908 clean_live_states(env, insn_idx, cur); 16909 16910 while (sl) { 16911 states_cnt++; 16912 if (sl->state.insn_idx != insn_idx) 16913 goto next; 16914 16915 if (sl->state.branches) { 16916 struct bpf_func_state *frame = sl->state.frame[sl->state.curframe]; 16917 16918 if (frame->in_async_callback_fn && 16919 frame->async_entry_cnt != cur->frame[cur->curframe]->async_entry_cnt) { 16920 /* Different async_entry_cnt means that the verifier is 16921 * processing another entry into async callback. 16922 * Seeing the same state is not an indication of infinite 16923 * loop or infinite recursion. 16924 * But finding the same state doesn't mean that it's safe 16925 * to stop processing the current state. The previous state 16926 * hasn't yet reached bpf_exit, since state.branches > 0. 16927 * Checking in_async_callback_fn alone is not enough either. 16928 * Since the verifier still needs to catch infinite loops 16929 * inside async callbacks. 16930 */ 16931 goto skip_inf_loop_check; 16932 } 16933 /* BPF open-coded iterators loop detection is special. 16934 * states_maybe_looping() logic is too simplistic in detecting 16935 * states that *might* be equivalent, because it doesn't know 16936 * about ID remapping, so don't even perform it. 16937 * See process_iter_next_call() and iter_active_depths_differ() 16938 * for overview of the logic. When current and one of parent 16939 * states are detected as equivalent, it's a good thing: we prove 16940 * convergence and can stop simulating further iterations. 16941 * It's safe to assume that iterator loop will finish, taking into 16942 * account iter_next() contract of eventually returning 16943 * sticky NULL result. 16944 * 16945 * Note, that states have to be compared exactly in this case because 16946 * read and precision marks might not be finalized inside the loop. 16947 * E.g. as in the program below: 16948 * 16949 * 1. r7 = -16 16950 * 2. r6 = bpf_get_prandom_u32() 16951 * 3. while (bpf_iter_num_next(&fp[-8])) { 16952 * 4. if (r6 != 42) { 16953 * 5. r7 = -32 16954 * 6. r6 = bpf_get_prandom_u32() 16955 * 7. continue 16956 * 8. } 16957 * 9. r0 = r10 16958 * 10. r0 += r7 16959 * 11. r8 = *(u64 *)(r0 + 0) 16960 * 12. r6 = bpf_get_prandom_u32() 16961 * 13. } 16962 * 16963 * Here verifier would first visit path 1-3, create a checkpoint at 3 16964 * with r7=-16, continue to 4-7,3. Existing checkpoint at 3 does 16965 * not have read or precision mark for r7 yet, thus inexact states 16966 * comparison would discard current state with r7=-32 16967 * => unsafe memory access at 11 would not be caught. 16968 */ 16969 if (is_iter_next_insn(env, insn_idx)) { 16970 if (states_equal(env, &sl->state, cur, true)) { 16971 struct bpf_func_state *cur_frame; 16972 struct bpf_reg_state *iter_state, *iter_reg; 16973 int spi; 16974 16975 cur_frame = cur->frame[cur->curframe]; 16976 /* btf_check_iter_kfuncs() enforces that 16977 * iter state pointer is always the first arg 16978 */ 16979 iter_reg = &cur_frame->regs[BPF_REG_1]; 16980 /* current state is valid due to states_equal(), 16981 * so we can assume valid iter and reg state, 16982 * no need for extra (re-)validations 16983 */ 16984 spi = __get_spi(iter_reg->off + iter_reg->var_off.value); 16985 iter_state = &func(env, iter_reg)->stack[spi].spilled_ptr; 16986 if (iter_state->iter.state == BPF_ITER_STATE_ACTIVE) { 16987 update_loop_entry(cur, &sl->state); 16988 goto hit; 16989 } 16990 } 16991 goto skip_inf_loop_check; 16992 } 16993 /* attempt to detect infinite loop to avoid unnecessary doomed work */ 16994 if (states_maybe_looping(&sl->state, cur) && 16995 states_equal(env, &sl->state, cur, false) && 16996 !iter_active_depths_differ(&sl->state, cur)) { 16997 verbose_linfo(env, insn_idx, "; "); 16998 verbose(env, "infinite loop detected at insn %d\n", insn_idx); 16999 verbose(env, "cur state:"); 17000 print_verifier_state(env, cur->frame[cur->curframe], true); 17001 verbose(env, "old state:"); 17002 print_verifier_state(env, sl->state.frame[cur->curframe], true); 17003 return -EINVAL; 17004 } 17005 /* if the verifier is processing a loop, avoid adding new state 17006 * too often, since different loop iterations have distinct 17007 * states and may not help future pruning. 17008 * This threshold shouldn't be too low to make sure that 17009 * a loop with large bound will be rejected quickly. 17010 * The most abusive loop will be: 17011 * r1 += 1 17012 * if r1 < 1000000 goto pc-2 17013 * 1M insn_procssed limit / 100 == 10k peak states. 17014 * This threshold shouldn't be too high either, since states 17015 * at the end of the loop are likely to be useful in pruning. 17016 */ 17017 skip_inf_loop_check: 17018 if (!force_new_state && 17019 env->jmps_processed - env->prev_jmps_processed < 20 && 17020 env->insn_processed - env->prev_insn_processed < 100) 17021 add_new_state = false; 17022 goto miss; 17023 } 17024 /* If sl->state is a part of a loop and this loop's entry is a part of 17025 * current verification path then states have to be compared exactly. 17026 * 'force_exact' is needed to catch the following case: 17027 * 17028 * initial Here state 'succ' was processed first, 17029 * | it was eventually tracked to produce a 17030 * V state identical to 'hdr'. 17031 * .---------> hdr All branches from 'succ' had been explored 17032 * | | and thus 'succ' has its .branches == 0. 17033 * | V 17034 * | .------... Suppose states 'cur' and 'succ' correspond 17035 * | | | to the same instruction + callsites. 17036 * | V V In such case it is necessary to check 17037 * | ... ... if 'succ' and 'cur' are states_equal(). 17038 * | | | If 'succ' and 'cur' are a part of the 17039 * | V V same loop exact flag has to be set. 17040 * | succ <- cur To check if that is the case, verify 17041 * | | if loop entry of 'succ' is in current 17042 * | V DFS path. 17043 * | ... 17044 * | | 17045 * '----' 17046 * 17047 * Additional details are in the comment before get_loop_entry(). 17048 */ 17049 loop_entry = get_loop_entry(&sl->state); 17050 force_exact = loop_entry && loop_entry->branches > 0; 17051 if (states_equal(env, &sl->state, cur, force_exact)) { 17052 if (force_exact) 17053 update_loop_entry(cur, loop_entry); 17054 hit: 17055 sl->hit_cnt++; 17056 /* reached equivalent register/stack state, 17057 * prune the search. 17058 * Registers read by the continuation are read by us. 17059 * If we have any write marks in env->cur_state, they 17060 * will prevent corresponding reads in the continuation 17061 * from reaching our parent (an explored_state). Our 17062 * own state will get the read marks recorded, but 17063 * they'll be immediately forgotten as we're pruning 17064 * this state and will pop a new one. 17065 */ 17066 err = propagate_liveness(env, &sl->state, cur); 17067 17068 /* if previous state reached the exit with precision and 17069 * current state is equivalent to it (except precsion marks) 17070 * the precision needs to be propagated back in 17071 * the current state. 17072 */ 17073 err = err ? : push_jmp_history(env, cur); 17074 err = err ? : propagate_precision(env, &sl->state); 17075 if (err) 17076 return err; 17077 return 1; 17078 } 17079 miss: 17080 /* when new state is not going to be added do not increase miss count. 17081 * Otherwise several loop iterations will remove the state 17082 * recorded earlier. The goal of these heuristics is to have 17083 * states from some iterations of the loop (some in the beginning 17084 * and some at the end) to help pruning. 17085 */ 17086 if (add_new_state) 17087 sl->miss_cnt++; 17088 /* heuristic to determine whether this state is beneficial 17089 * to keep checking from state equivalence point of view. 17090 * Higher numbers increase max_states_per_insn and verification time, 17091 * but do not meaningfully decrease insn_processed. 17092 * 'n' controls how many times state could miss before eviction. 17093 * Use bigger 'n' for checkpoints because evicting checkpoint states 17094 * too early would hinder iterator convergence. 17095 */ 17096 n = is_force_checkpoint(env, insn_idx) && sl->state.branches > 0 ? 64 : 3; 17097 if (sl->miss_cnt > sl->hit_cnt * n + n) { 17098 /* the state is unlikely to be useful. Remove it to 17099 * speed up verification 17100 */ 17101 *pprev = sl->next; 17102 if (sl->state.frame[0]->regs[0].live & REG_LIVE_DONE && 17103 !sl->state.used_as_loop_entry) { 17104 u32 br = sl->state.branches; 17105 17106 WARN_ONCE(br, 17107 "BUG live_done but branches_to_explore %d\n", 17108 br); 17109 free_verifier_state(&sl->state, false); 17110 kfree(sl); 17111 env->peak_states--; 17112 } else { 17113 /* cannot free this state, since parentage chain may 17114 * walk it later. Add it for free_list instead to 17115 * be freed at the end of verification 17116 */ 17117 sl->next = env->free_list; 17118 env->free_list = sl; 17119 } 17120 sl = *pprev; 17121 continue; 17122 } 17123 next: 17124 pprev = &sl->next; 17125 sl = *pprev; 17126 } 17127 17128 if (env->max_states_per_insn < states_cnt) 17129 env->max_states_per_insn = states_cnt; 17130 17131 if (!env->bpf_capable && states_cnt > BPF_COMPLEXITY_LIMIT_STATES) 17132 return 0; 17133 17134 if (!add_new_state) 17135 return 0; 17136 17137 /* There were no equivalent states, remember the current one. 17138 * Technically the current state is not proven to be safe yet, 17139 * but it will either reach outer most bpf_exit (which means it's safe) 17140 * or it will be rejected. When there are no loops the verifier won't be 17141 * seeing this tuple (frame[0].callsite, frame[1].callsite, .. insn_idx) 17142 * again on the way to bpf_exit. 17143 * When looping the sl->state.branches will be > 0 and this state 17144 * will not be considered for equivalence until branches == 0. 17145 */ 17146 new_sl = kzalloc(sizeof(struct bpf_verifier_state_list), GFP_KERNEL); 17147 if (!new_sl) 17148 return -ENOMEM; 17149 env->total_states++; 17150 env->peak_states++; 17151 env->prev_jmps_processed = env->jmps_processed; 17152 env->prev_insn_processed = env->insn_processed; 17153 17154 /* forget precise markings we inherited, see __mark_chain_precision */ 17155 if (env->bpf_capable) 17156 mark_all_scalars_imprecise(env, cur); 17157 17158 /* add new state to the head of linked list */ 17159 new = &new_sl->state; 17160 err = copy_verifier_state(new, cur); 17161 if (err) { 17162 free_verifier_state(new, false); 17163 kfree(new_sl); 17164 return err; 17165 } 17166 new->insn_idx = insn_idx; 17167 WARN_ONCE(new->branches != 1, 17168 "BUG is_state_visited:branches_to_explore=%d insn %d\n", new->branches, insn_idx); 17169 17170 cur->parent = new; 17171 cur->first_insn_idx = insn_idx; 17172 cur->dfs_depth = new->dfs_depth + 1; 17173 clear_jmp_history(cur); 17174 new_sl->next = *explored_state(env, insn_idx); 17175 *explored_state(env, insn_idx) = new_sl; 17176 /* connect new state to parentage chain. Current frame needs all 17177 * registers connected. Only r6 - r9 of the callers are alive (pushed 17178 * to the stack implicitly by JITs) so in callers' frames connect just 17179 * r6 - r9 as an optimization. Callers will have r1 - r5 connected to 17180 * the state of the call instruction (with WRITTEN set), and r0 comes 17181 * from callee with its full parentage chain, anyway. 17182 */ 17183 /* clear write marks in current state: the writes we did are not writes 17184 * our child did, so they don't screen off its reads from us. 17185 * (There are no read marks in current state, because reads always mark 17186 * their parent and current state never has children yet. Only 17187 * explored_states can get read marks.) 17188 */ 17189 for (j = 0; j <= cur->curframe; j++) { 17190 for (i = j < cur->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++) 17191 cur->frame[j]->regs[i].parent = &new->frame[j]->regs[i]; 17192 for (i = 0; i < BPF_REG_FP; i++) 17193 cur->frame[j]->regs[i].live = REG_LIVE_NONE; 17194 } 17195 17196 /* all stack frames are accessible from callee, clear them all */ 17197 for (j = 0; j <= cur->curframe; j++) { 17198 struct bpf_func_state *frame = cur->frame[j]; 17199 struct bpf_func_state *newframe = new->frame[j]; 17200 17201 for (i = 0; i < frame->allocated_stack / BPF_REG_SIZE; i++) { 17202 frame->stack[i].spilled_ptr.live = REG_LIVE_NONE; 17203 frame->stack[i].spilled_ptr.parent = 17204 &newframe->stack[i].spilled_ptr; 17205 } 17206 } 17207 return 0; 17208 } 17209 17210 /* Return true if it's OK to have the same insn return a different type. */ 17211 static bool reg_type_mismatch_ok(enum bpf_reg_type type) 17212 { 17213 switch (base_type(type)) { 17214 case PTR_TO_CTX: 17215 case PTR_TO_SOCKET: 17216 case PTR_TO_SOCK_COMMON: 17217 case PTR_TO_TCP_SOCK: 17218 case PTR_TO_XDP_SOCK: 17219 case PTR_TO_BTF_ID: 17220 return false; 17221 default: 17222 return true; 17223 } 17224 } 17225 17226 /* If an instruction was previously used with particular pointer types, then we 17227 * need to be careful to avoid cases such as the below, where it may be ok 17228 * for one branch accessing the pointer, but not ok for the other branch: 17229 * 17230 * R1 = sock_ptr 17231 * goto X; 17232 * ... 17233 * R1 = some_other_valid_ptr; 17234 * goto X; 17235 * ... 17236 * R2 = *(u32 *)(R1 + 0); 17237 */ 17238 static bool reg_type_mismatch(enum bpf_reg_type src, enum bpf_reg_type prev) 17239 { 17240 return src != prev && (!reg_type_mismatch_ok(src) || 17241 !reg_type_mismatch_ok(prev)); 17242 } 17243 17244 static int save_aux_ptr_type(struct bpf_verifier_env *env, enum bpf_reg_type type, 17245 bool allow_trust_missmatch) 17246 { 17247 enum bpf_reg_type *prev_type = &env->insn_aux_data[env->insn_idx].ptr_type; 17248 17249 if (*prev_type == NOT_INIT) { 17250 /* Saw a valid insn 17251 * dst_reg = *(u32 *)(src_reg + off) 17252 * save type to validate intersecting paths 17253 */ 17254 *prev_type = type; 17255 } else if (reg_type_mismatch(type, *prev_type)) { 17256 /* Abuser program is trying to use the same insn 17257 * dst_reg = *(u32*) (src_reg + off) 17258 * with different pointer types: 17259 * src_reg == ctx in one branch and 17260 * src_reg == stack|map in some other branch. 17261 * Reject it. 17262 */ 17263 if (allow_trust_missmatch && 17264 base_type(type) == PTR_TO_BTF_ID && 17265 base_type(*prev_type) == PTR_TO_BTF_ID) { 17266 /* 17267 * Have to support a use case when one path through 17268 * the program yields TRUSTED pointer while another 17269 * is UNTRUSTED. Fallback to UNTRUSTED to generate 17270 * BPF_PROBE_MEM/BPF_PROBE_MEMSX. 17271 */ 17272 *prev_type = PTR_TO_BTF_ID | PTR_UNTRUSTED; 17273 } else { 17274 verbose(env, "same insn cannot be used with different pointers\n"); 17275 return -EINVAL; 17276 } 17277 } 17278 17279 return 0; 17280 } 17281 17282 static int do_check(struct bpf_verifier_env *env) 17283 { 17284 bool pop_log = !(env->log.level & BPF_LOG_LEVEL2); 17285 struct bpf_verifier_state *state = env->cur_state; 17286 struct bpf_insn *insns = env->prog->insnsi; 17287 struct bpf_reg_state *regs; 17288 int insn_cnt = env->prog->len; 17289 bool do_print_state = false; 17290 int prev_insn_idx = -1; 17291 17292 for (;;) { 17293 bool exception_exit = false; 17294 struct bpf_insn *insn; 17295 u8 class; 17296 int err; 17297 17298 env->prev_insn_idx = prev_insn_idx; 17299 if (env->insn_idx >= insn_cnt) { 17300 verbose(env, "invalid insn idx %d insn_cnt %d\n", 17301 env->insn_idx, insn_cnt); 17302 return -EFAULT; 17303 } 17304 17305 insn = &insns[env->insn_idx]; 17306 class = BPF_CLASS(insn->code); 17307 17308 if (++env->insn_processed > BPF_COMPLEXITY_LIMIT_INSNS) { 17309 verbose(env, 17310 "BPF program is too large. Processed %d insn\n", 17311 env->insn_processed); 17312 return -E2BIG; 17313 } 17314 17315 state->last_insn_idx = env->prev_insn_idx; 17316 17317 if (is_prune_point(env, env->insn_idx)) { 17318 err = is_state_visited(env, env->insn_idx); 17319 if (err < 0) 17320 return err; 17321 if (err == 1) { 17322 /* found equivalent state, can prune the search */ 17323 if (env->log.level & BPF_LOG_LEVEL) { 17324 if (do_print_state) 17325 verbose(env, "\nfrom %d to %d%s: safe\n", 17326 env->prev_insn_idx, env->insn_idx, 17327 env->cur_state->speculative ? 17328 " (speculative execution)" : ""); 17329 else 17330 verbose(env, "%d: safe\n", env->insn_idx); 17331 } 17332 goto process_bpf_exit; 17333 } 17334 } 17335 17336 if (is_jmp_point(env, env->insn_idx)) { 17337 err = push_jmp_history(env, state); 17338 if (err) 17339 return err; 17340 } 17341 17342 if (signal_pending(current)) 17343 return -EAGAIN; 17344 17345 if (need_resched()) 17346 cond_resched(); 17347 17348 if (env->log.level & BPF_LOG_LEVEL2 && do_print_state) { 17349 verbose(env, "\nfrom %d to %d%s:", 17350 env->prev_insn_idx, env->insn_idx, 17351 env->cur_state->speculative ? 17352 " (speculative execution)" : ""); 17353 print_verifier_state(env, state->frame[state->curframe], true); 17354 do_print_state = false; 17355 } 17356 17357 if (env->log.level & BPF_LOG_LEVEL) { 17358 const struct bpf_insn_cbs cbs = { 17359 .cb_call = disasm_kfunc_name, 17360 .cb_print = verbose, 17361 .private_data = env, 17362 }; 17363 17364 if (verifier_state_scratched(env)) 17365 print_insn_state(env, state->frame[state->curframe]); 17366 17367 verbose_linfo(env, env->insn_idx, "; "); 17368 env->prev_log_pos = env->log.end_pos; 17369 verbose(env, "%d: ", env->insn_idx); 17370 print_bpf_insn(&cbs, insn, env->allow_ptr_leaks); 17371 env->prev_insn_print_pos = env->log.end_pos - env->prev_log_pos; 17372 env->prev_log_pos = env->log.end_pos; 17373 } 17374 17375 if (bpf_prog_is_offloaded(env->prog->aux)) { 17376 err = bpf_prog_offload_verify_insn(env, env->insn_idx, 17377 env->prev_insn_idx); 17378 if (err) 17379 return err; 17380 } 17381 17382 regs = cur_regs(env); 17383 sanitize_mark_insn_seen(env); 17384 prev_insn_idx = env->insn_idx; 17385 17386 if (class == BPF_ALU || class == BPF_ALU64) { 17387 err = check_alu_op(env, insn); 17388 if (err) 17389 return err; 17390 17391 } else if (class == BPF_LDX) { 17392 enum bpf_reg_type src_reg_type; 17393 17394 /* check for reserved fields is already done */ 17395 17396 /* check src operand */ 17397 err = check_reg_arg(env, insn->src_reg, SRC_OP); 17398 if (err) 17399 return err; 17400 17401 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK); 17402 if (err) 17403 return err; 17404 17405 src_reg_type = regs[insn->src_reg].type; 17406 17407 /* check that memory (src_reg + off) is readable, 17408 * the state of dst_reg will be updated by this func 17409 */ 17410 err = check_mem_access(env, env->insn_idx, insn->src_reg, 17411 insn->off, BPF_SIZE(insn->code), 17412 BPF_READ, insn->dst_reg, false, 17413 BPF_MODE(insn->code) == BPF_MEMSX); 17414 if (err) 17415 return err; 17416 17417 err = save_aux_ptr_type(env, src_reg_type, true); 17418 if (err) 17419 return err; 17420 } else if (class == BPF_STX) { 17421 enum bpf_reg_type dst_reg_type; 17422 17423 if (BPF_MODE(insn->code) == BPF_ATOMIC) { 17424 err = check_atomic(env, env->insn_idx, insn); 17425 if (err) 17426 return err; 17427 env->insn_idx++; 17428 continue; 17429 } 17430 17431 if (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0) { 17432 verbose(env, "BPF_STX uses reserved fields\n"); 17433 return -EINVAL; 17434 } 17435 17436 /* check src1 operand */ 17437 err = check_reg_arg(env, insn->src_reg, SRC_OP); 17438 if (err) 17439 return err; 17440 /* check src2 operand */ 17441 err = check_reg_arg(env, insn->dst_reg, SRC_OP); 17442 if (err) 17443 return err; 17444 17445 dst_reg_type = regs[insn->dst_reg].type; 17446 17447 /* check that memory (dst_reg + off) is writeable */ 17448 err = check_mem_access(env, env->insn_idx, insn->dst_reg, 17449 insn->off, BPF_SIZE(insn->code), 17450 BPF_WRITE, insn->src_reg, false, false); 17451 if (err) 17452 return err; 17453 17454 err = save_aux_ptr_type(env, dst_reg_type, false); 17455 if (err) 17456 return err; 17457 } else if (class == BPF_ST) { 17458 enum bpf_reg_type dst_reg_type; 17459 17460 if (BPF_MODE(insn->code) != BPF_MEM || 17461 insn->src_reg != BPF_REG_0) { 17462 verbose(env, "BPF_ST uses reserved fields\n"); 17463 return -EINVAL; 17464 } 17465 /* check src operand */ 17466 err = check_reg_arg(env, insn->dst_reg, SRC_OP); 17467 if (err) 17468 return err; 17469 17470 dst_reg_type = regs[insn->dst_reg].type; 17471 17472 /* check that memory (dst_reg + off) is writeable */ 17473 err = check_mem_access(env, env->insn_idx, insn->dst_reg, 17474 insn->off, BPF_SIZE(insn->code), 17475 BPF_WRITE, -1, false, false); 17476 if (err) 17477 return err; 17478 17479 err = save_aux_ptr_type(env, dst_reg_type, false); 17480 if (err) 17481 return err; 17482 } else if (class == BPF_JMP || class == BPF_JMP32) { 17483 u8 opcode = BPF_OP(insn->code); 17484 17485 env->jmps_processed++; 17486 if (opcode == BPF_CALL) { 17487 if (BPF_SRC(insn->code) != BPF_K || 17488 (insn->src_reg != BPF_PSEUDO_KFUNC_CALL 17489 && insn->off != 0) || 17490 (insn->src_reg != BPF_REG_0 && 17491 insn->src_reg != BPF_PSEUDO_CALL && 17492 insn->src_reg != BPF_PSEUDO_KFUNC_CALL) || 17493 insn->dst_reg != BPF_REG_0 || 17494 class == BPF_JMP32) { 17495 verbose(env, "BPF_CALL uses reserved fields\n"); 17496 return -EINVAL; 17497 } 17498 17499 if (env->cur_state->active_lock.ptr) { 17500 if ((insn->src_reg == BPF_REG_0 && insn->imm != BPF_FUNC_spin_unlock) || 17501 (insn->src_reg == BPF_PSEUDO_CALL) || 17502 (insn->src_reg == BPF_PSEUDO_KFUNC_CALL && 17503 (insn->off != 0 || !is_bpf_graph_api_kfunc(insn->imm)))) { 17504 verbose(env, "function calls are not allowed while holding a lock\n"); 17505 return -EINVAL; 17506 } 17507 } 17508 if (insn->src_reg == BPF_PSEUDO_CALL) { 17509 err = check_func_call(env, insn, &env->insn_idx); 17510 } else if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) { 17511 err = check_kfunc_call(env, insn, &env->insn_idx); 17512 if (!err && is_bpf_throw_kfunc(insn)) { 17513 exception_exit = true; 17514 goto process_bpf_exit_full; 17515 } 17516 } else { 17517 err = check_helper_call(env, insn, &env->insn_idx); 17518 } 17519 if (err) 17520 return err; 17521 17522 mark_reg_scratched(env, BPF_REG_0); 17523 } else if (opcode == BPF_JA) { 17524 if (BPF_SRC(insn->code) != BPF_K || 17525 insn->src_reg != BPF_REG_0 || 17526 insn->dst_reg != BPF_REG_0 || 17527 (class == BPF_JMP && insn->imm != 0) || 17528 (class == BPF_JMP32 && insn->off != 0)) { 17529 verbose(env, "BPF_JA uses reserved fields\n"); 17530 return -EINVAL; 17531 } 17532 17533 if (class == BPF_JMP) 17534 env->insn_idx += insn->off + 1; 17535 else 17536 env->insn_idx += insn->imm + 1; 17537 continue; 17538 17539 } else if (opcode == BPF_EXIT) { 17540 if (BPF_SRC(insn->code) != BPF_K || 17541 insn->imm != 0 || 17542 insn->src_reg != BPF_REG_0 || 17543 insn->dst_reg != BPF_REG_0 || 17544 class == BPF_JMP32) { 17545 verbose(env, "BPF_EXIT uses reserved fields\n"); 17546 return -EINVAL; 17547 } 17548 process_bpf_exit_full: 17549 if (env->cur_state->active_lock.ptr && 17550 !in_rbtree_lock_required_cb(env)) { 17551 verbose(env, "bpf_spin_unlock is missing\n"); 17552 return -EINVAL; 17553 } 17554 17555 if (env->cur_state->active_rcu_lock && 17556 !in_rbtree_lock_required_cb(env)) { 17557 verbose(env, "bpf_rcu_read_unlock is missing\n"); 17558 return -EINVAL; 17559 } 17560 17561 /* We must do check_reference_leak here before 17562 * prepare_func_exit to handle the case when 17563 * state->curframe > 0, it may be a callback 17564 * function, for which reference_state must 17565 * match caller reference state when it exits. 17566 */ 17567 err = check_reference_leak(env, exception_exit); 17568 if (err) 17569 return err; 17570 17571 /* The side effect of the prepare_func_exit 17572 * which is being skipped is that it frees 17573 * bpf_func_state. Typically, process_bpf_exit 17574 * will only be hit with outermost exit. 17575 * copy_verifier_state in pop_stack will handle 17576 * freeing of any extra bpf_func_state left over 17577 * from not processing all nested function 17578 * exits. We also skip return code checks as 17579 * they are not needed for exceptional exits. 17580 */ 17581 if (exception_exit) 17582 goto process_bpf_exit; 17583 17584 if (state->curframe) { 17585 /* exit from nested function */ 17586 err = prepare_func_exit(env, &env->insn_idx); 17587 if (err) 17588 return err; 17589 do_print_state = true; 17590 continue; 17591 } 17592 17593 err = check_return_code(env, BPF_REG_0); 17594 if (err) 17595 return err; 17596 process_bpf_exit: 17597 mark_verifier_state_scratched(env); 17598 update_branch_counts(env, env->cur_state); 17599 err = pop_stack(env, &prev_insn_idx, 17600 &env->insn_idx, pop_log); 17601 if (err < 0) { 17602 if (err != -ENOENT) 17603 return err; 17604 break; 17605 } else { 17606 do_print_state = true; 17607 continue; 17608 } 17609 } else { 17610 err = check_cond_jmp_op(env, insn, &env->insn_idx); 17611 if (err) 17612 return err; 17613 } 17614 } else if (class == BPF_LD) { 17615 u8 mode = BPF_MODE(insn->code); 17616 17617 if (mode == BPF_ABS || mode == BPF_IND) { 17618 err = check_ld_abs(env, insn); 17619 if (err) 17620 return err; 17621 17622 } else if (mode == BPF_IMM) { 17623 err = check_ld_imm(env, insn); 17624 if (err) 17625 return err; 17626 17627 env->insn_idx++; 17628 sanitize_mark_insn_seen(env); 17629 } else { 17630 verbose(env, "invalid BPF_LD mode\n"); 17631 return -EINVAL; 17632 } 17633 } else { 17634 verbose(env, "unknown insn class %d\n", class); 17635 return -EINVAL; 17636 } 17637 17638 env->insn_idx++; 17639 } 17640 17641 return 0; 17642 } 17643 17644 static int find_btf_percpu_datasec(struct btf *btf) 17645 { 17646 const struct btf_type *t; 17647 const char *tname; 17648 int i, n; 17649 17650 /* 17651 * Both vmlinux and module each have their own ".data..percpu" 17652 * DATASECs in BTF. So for module's case, we need to skip vmlinux BTF 17653 * types to look at only module's own BTF types. 17654 */ 17655 n = btf_nr_types(btf); 17656 if (btf_is_module(btf)) 17657 i = btf_nr_types(btf_vmlinux); 17658 else 17659 i = 1; 17660 17661 for(; i < n; i++) { 17662 t = btf_type_by_id(btf, i); 17663 if (BTF_INFO_KIND(t->info) != BTF_KIND_DATASEC) 17664 continue; 17665 17666 tname = btf_name_by_offset(btf, t->name_off); 17667 if (!strcmp(tname, ".data..percpu")) 17668 return i; 17669 } 17670 17671 return -ENOENT; 17672 } 17673 17674 /* replace pseudo btf_id with kernel symbol address */ 17675 static int check_pseudo_btf_id(struct bpf_verifier_env *env, 17676 struct bpf_insn *insn, 17677 struct bpf_insn_aux_data *aux) 17678 { 17679 const struct btf_var_secinfo *vsi; 17680 const struct btf_type *datasec; 17681 struct btf_mod_pair *btf_mod; 17682 const struct btf_type *t; 17683 const char *sym_name; 17684 bool percpu = false; 17685 u32 type, id = insn->imm; 17686 struct btf *btf; 17687 s32 datasec_id; 17688 u64 addr; 17689 int i, btf_fd, err; 17690 17691 btf_fd = insn[1].imm; 17692 if (btf_fd) { 17693 btf = btf_get_by_fd(btf_fd); 17694 if (IS_ERR(btf)) { 17695 verbose(env, "invalid module BTF object FD specified.\n"); 17696 return -EINVAL; 17697 } 17698 } else { 17699 if (!btf_vmlinux) { 17700 verbose(env, "kernel is missing BTF, make sure CONFIG_DEBUG_INFO_BTF=y is specified in Kconfig.\n"); 17701 return -EINVAL; 17702 } 17703 btf = btf_vmlinux; 17704 btf_get(btf); 17705 } 17706 17707 t = btf_type_by_id(btf, id); 17708 if (!t) { 17709 verbose(env, "ldimm64 insn specifies invalid btf_id %d.\n", id); 17710 err = -ENOENT; 17711 goto err_put; 17712 } 17713 17714 if (!btf_type_is_var(t) && !btf_type_is_func(t)) { 17715 verbose(env, "pseudo btf_id %d in ldimm64 isn't KIND_VAR or KIND_FUNC\n", id); 17716 err = -EINVAL; 17717 goto err_put; 17718 } 17719 17720 sym_name = btf_name_by_offset(btf, t->name_off); 17721 addr = kallsyms_lookup_name(sym_name); 17722 if (!addr) { 17723 verbose(env, "ldimm64 failed to find the address for kernel symbol '%s'.\n", 17724 sym_name); 17725 err = -ENOENT; 17726 goto err_put; 17727 } 17728 insn[0].imm = (u32)addr; 17729 insn[1].imm = addr >> 32; 17730 17731 if (btf_type_is_func(t)) { 17732 aux->btf_var.reg_type = PTR_TO_MEM | MEM_RDONLY; 17733 aux->btf_var.mem_size = 0; 17734 goto check_btf; 17735 } 17736 17737 datasec_id = find_btf_percpu_datasec(btf); 17738 if (datasec_id > 0) { 17739 datasec = btf_type_by_id(btf, datasec_id); 17740 for_each_vsi(i, datasec, vsi) { 17741 if (vsi->type == id) { 17742 percpu = true; 17743 break; 17744 } 17745 } 17746 } 17747 17748 type = t->type; 17749 t = btf_type_skip_modifiers(btf, type, NULL); 17750 if (percpu) { 17751 aux->btf_var.reg_type = PTR_TO_BTF_ID | MEM_PERCPU; 17752 aux->btf_var.btf = btf; 17753 aux->btf_var.btf_id = type; 17754 } else if (!btf_type_is_struct(t)) { 17755 const struct btf_type *ret; 17756 const char *tname; 17757 u32 tsize; 17758 17759 /* resolve the type size of ksym. */ 17760 ret = btf_resolve_size(btf, t, &tsize); 17761 if (IS_ERR(ret)) { 17762 tname = btf_name_by_offset(btf, t->name_off); 17763 verbose(env, "ldimm64 unable to resolve the size of type '%s': %ld\n", 17764 tname, PTR_ERR(ret)); 17765 err = -EINVAL; 17766 goto err_put; 17767 } 17768 aux->btf_var.reg_type = PTR_TO_MEM | MEM_RDONLY; 17769 aux->btf_var.mem_size = tsize; 17770 } else { 17771 aux->btf_var.reg_type = PTR_TO_BTF_ID; 17772 aux->btf_var.btf = btf; 17773 aux->btf_var.btf_id = type; 17774 } 17775 check_btf: 17776 /* check whether we recorded this BTF (and maybe module) already */ 17777 for (i = 0; i < env->used_btf_cnt; i++) { 17778 if (env->used_btfs[i].btf == btf) { 17779 btf_put(btf); 17780 return 0; 17781 } 17782 } 17783 17784 if (env->used_btf_cnt >= MAX_USED_BTFS) { 17785 err = -E2BIG; 17786 goto err_put; 17787 } 17788 17789 btf_mod = &env->used_btfs[env->used_btf_cnt]; 17790 btf_mod->btf = btf; 17791 btf_mod->module = NULL; 17792 17793 /* if we reference variables from kernel module, bump its refcount */ 17794 if (btf_is_module(btf)) { 17795 btf_mod->module = btf_try_get_module(btf); 17796 if (!btf_mod->module) { 17797 err = -ENXIO; 17798 goto err_put; 17799 } 17800 } 17801 17802 env->used_btf_cnt++; 17803 17804 return 0; 17805 err_put: 17806 btf_put(btf); 17807 return err; 17808 } 17809 17810 static bool is_tracing_prog_type(enum bpf_prog_type type) 17811 { 17812 switch (type) { 17813 case BPF_PROG_TYPE_KPROBE: 17814 case BPF_PROG_TYPE_TRACEPOINT: 17815 case BPF_PROG_TYPE_PERF_EVENT: 17816 case BPF_PROG_TYPE_RAW_TRACEPOINT: 17817 case BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE: 17818 return true; 17819 default: 17820 return false; 17821 } 17822 } 17823 17824 static int check_map_prog_compatibility(struct bpf_verifier_env *env, 17825 struct bpf_map *map, 17826 struct bpf_prog *prog) 17827 17828 { 17829 enum bpf_prog_type prog_type = resolve_prog_type(prog); 17830 17831 if (btf_record_has_field(map->record, BPF_LIST_HEAD) || 17832 btf_record_has_field(map->record, BPF_RB_ROOT)) { 17833 if (is_tracing_prog_type(prog_type)) { 17834 verbose(env, "tracing progs cannot use bpf_{list_head,rb_root} yet\n"); 17835 return -EINVAL; 17836 } 17837 } 17838 17839 if (btf_record_has_field(map->record, BPF_SPIN_LOCK)) { 17840 if (prog_type == BPF_PROG_TYPE_SOCKET_FILTER) { 17841 verbose(env, "socket filter progs cannot use bpf_spin_lock yet\n"); 17842 return -EINVAL; 17843 } 17844 17845 if (is_tracing_prog_type(prog_type)) { 17846 verbose(env, "tracing progs cannot use bpf_spin_lock yet\n"); 17847 return -EINVAL; 17848 } 17849 } 17850 17851 if (btf_record_has_field(map->record, BPF_TIMER)) { 17852 if (is_tracing_prog_type(prog_type)) { 17853 verbose(env, "tracing progs cannot use bpf_timer yet\n"); 17854 return -EINVAL; 17855 } 17856 } 17857 17858 if ((bpf_prog_is_offloaded(prog->aux) || bpf_map_is_offloaded(map)) && 17859 !bpf_offload_prog_map_match(prog, map)) { 17860 verbose(env, "offload device mismatch between prog and map\n"); 17861 return -EINVAL; 17862 } 17863 17864 if (map->map_type == BPF_MAP_TYPE_STRUCT_OPS) { 17865 verbose(env, "bpf_struct_ops map cannot be used in prog\n"); 17866 return -EINVAL; 17867 } 17868 17869 if (prog->aux->sleepable) 17870 switch (map->map_type) { 17871 case BPF_MAP_TYPE_HASH: 17872 case BPF_MAP_TYPE_LRU_HASH: 17873 case BPF_MAP_TYPE_ARRAY: 17874 case BPF_MAP_TYPE_PERCPU_HASH: 17875 case BPF_MAP_TYPE_PERCPU_ARRAY: 17876 case BPF_MAP_TYPE_LRU_PERCPU_HASH: 17877 case BPF_MAP_TYPE_ARRAY_OF_MAPS: 17878 case BPF_MAP_TYPE_HASH_OF_MAPS: 17879 case BPF_MAP_TYPE_RINGBUF: 17880 case BPF_MAP_TYPE_USER_RINGBUF: 17881 case BPF_MAP_TYPE_INODE_STORAGE: 17882 case BPF_MAP_TYPE_SK_STORAGE: 17883 case BPF_MAP_TYPE_TASK_STORAGE: 17884 case BPF_MAP_TYPE_CGRP_STORAGE: 17885 break; 17886 default: 17887 verbose(env, 17888 "Sleepable programs can only use array, hash, ringbuf and local storage maps\n"); 17889 return -EINVAL; 17890 } 17891 17892 return 0; 17893 } 17894 17895 static bool bpf_map_is_cgroup_storage(struct bpf_map *map) 17896 { 17897 return (map->map_type == BPF_MAP_TYPE_CGROUP_STORAGE || 17898 map->map_type == BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE); 17899 } 17900 17901 /* find and rewrite pseudo imm in ld_imm64 instructions: 17902 * 17903 * 1. if it accesses map FD, replace it with actual map pointer. 17904 * 2. if it accesses btf_id of a VAR, replace it with pointer to the var. 17905 * 17906 * NOTE: btf_vmlinux is required for converting pseudo btf_id. 17907 */ 17908 static int resolve_pseudo_ldimm64(struct bpf_verifier_env *env) 17909 { 17910 struct bpf_insn *insn = env->prog->insnsi; 17911 int insn_cnt = env->prog->len; 17912 int i, j, err; 17913 17914 err = bpf_prog_calc_tag(env->prog); 17915 if (err) 17916 return err; 17917 17918 for (i = 0; i < insn_cnt; i++, insn++) { 17919 if (BPF_CLASS(insn->code) == BPF_LDX && 17920 ((BPF_MODE(insn->code) != BPF_MEM && BPF_MODE(insn->code) != BPF_MEMSX) || 17921 insn->imm != 0)) { 17922 verbose(env, "BPF_LDX uses reserved fields\n"); 17923 return -EINVAL; 17924 } 17925 17926 if (insn[0].code == (BPF_LD | BPF_IMM | BPF_DW)) { 17927 struct bpf_insn_aux_data *aux; 17928 struct bpf_map *map; 17929 struct fd f; 17930 u64 addr; 17931 u32 fd; 17932 17933 if (i == insn_cnt - 1 || insn[1].code != 0 || 17934 insn[1].dst_reg != 0 || insn[1].src_reg != 0 || 17935 insn[1].off != 0) { 17936 verbose(env, "invalid bpf_ld_imm64 insn\n"); 17937 return -EINVAL; 17938 } 17939 17940 if (insn[0].src_reg == 0) 17941 /* valid generic load 64-bit imm */ 17942 goto next_insn; 17943 17944 if (insn[0].src_reg == BPF_PSEUDO_BTF_ID) { 17945 aux = &env->insn_aux_data[i]; 17946 err = check_pseudo_btf_id(env, insn, aux); 17947 if (err) 17948 return err; 17949 goto next_insn; 17950 } 17951 17952 if (insn[0].src_reg == BPF_PSEUDO_FUNC) { 17953 aux = &env->insn_aux_data[i]; 17954 aux->ptr_type = PTR_TO_FUNC; 17955 goto next_insn; 17956 } 17957 17958 /* In final convert_pseudo_ld_imm64() step, this is 17959 * converted into regular 64-bit imm load insn. 17960 */ 17961 switch (insn[0].src_reg) { 17962 case BPF_PSEUDO_MAP_VALUE: 17963 case BPF_PSEUDO_MAP_IDX_VALUE: 17964 break; 17965 case BPF_PSEUDO_MAP_FD: 17966 case BPF_PSEUDO_MAP_IDX: 17967 if (insn[1].imm == 0) 17968 break; 17969 fallthrough; 17970 default: 17971 verbose(env, "unrecognized bpf_ld_imm64 insn\n"); 17972 return -EINVAL; 17973 } 17974 17975 switch (insn[0].src_reg) { 17976 case BPF_PSEUDO_MAP_IDX_VALUE: 17977 case BPF_PSEUDO_MAP_IDX: 17978 if (bpfptr_is_null(env->fd_array)) { 17979 verbose(env, "fd_idx without fd_array is invalid\n"); 17980 return -EPROTO; 17981 } 17982 if (copy_from_bpfptr_offset(&fd, env->fd_array, 17983 insn[0].imm * sizeof(fd), 17984 sizeof(fd))) 17985 return -EFAULT; 17986 break; 17987 default: 17988 fd = insn[0].imm; 17989 break; 17990 } 17991 17992 f = fdget(fd); 17993 map = __bpf_map_get(f); 17994 if (IS_ERR(map)) { 17995 verbose(env, "fd %d is not pointing to valid bpf_map\n", 17996 insn[0].imm); 17997 return PTR_ERR(map); 17998 } 17999 18000 err = check_map_prog_compatibility(env, map, env->prog); 18001 if (err) { 18002 fdput(f); 18003 return err; 18004 } 18005 18006 aux = &env->insn_aux_data[i]; 18007 if (insn[0].src_reg == BPF_PSEUDO_MAP_FD || 18008 insn[0].src_reg == BPF_PSEUDO_MAP_IDX) { 18009 addr = (unsigned long)map; 18010 } else { 18011 u32 off = insn[1].imm; 18012 18013 if (off >= BPF_MAX_VAR_OFF) { 18014 verbose(env, "direct value offset of %u is not allowed\n", off); 18015 fdput(f); 18016 return -EINVAL; 18017 } 18018 18019 if (!map->ops->map_direct_value_addr) { 18020 verbose(env, "no direct value access support for this map type\n"); 18021 fdput(f); 18022 return -EINVAL; 18023 } 18024 18025 err = map->ops->map_direct_value_addr(map, &addr, off); 18026 if (err) { 18027 verbose(env, "invalid access to map value pointer, value_size=%u off=%u\n", 18028 map->value_size, off); 18029 fdput(f); 18030 return err; 18031 } 18032 18033 aux->map_off = off; 18034 addr += off; 18035 } 18036 18037 insn[0].imm = (u32)addr; 18038 insn[1].imm = addr >> 32; 18039 18040 /* check whether we recorded this map already */ 18041 for (j = 0; j < env->used_map_cnt; j++) { 18042 if (env->used_maps[j] == map) { 18043 aux->map_index = j; 18044 fdput(f); 18045 goto next_insn; 18046 } 18047 } 18048 18049 if (env->used_map_cnt >= MAX_USED_MAPS) { 18050 fdput(f); 18051 return -E2BIG; 18052 } 18053 18054 /* hold the map. If the program is rejected by verifier, 18055 * the map will be released by release_maps() or it 18056 * will be used by the valid program until it's unloaded 18057 * and all maps are released in free_used_maps() 18058 */ 18059 bpf_map_inc(map); 18060 18061 aux->map_index = env->used_map_cnt; 18062 env->used_maps[env->used_map_cnt++] = map; 18063 18064 if (bpf_map_is_cgroup_storage(map) && 18065 bpf_cgroup_storage_assign(env->prog->aux, map)) { 18066 verbose(env, "only one cgroup storage of each type is allowed\n"); 18067 fdput(f); 18068 return -EBUSY; 18069 } 18070 18071 fdput(f); 18072 next_insn: 18073 insn++; 18074 i++; 18075 continue; 18076 } 18077 18078 /* Basic sanity check before we invest more work here. */ 18079 if (!bpf_opcode_in_insntable(insn->code)) { 18080 verbose(env, "unknown opcode %02x\n", insn->code); 18081 return -EINVAL; 18082 } 18083 } 18084 18085 /* now all pseudo BPF_LD_IMM64 instructions load valid 18086 * 'struct bpf_map *' into a register instead of user map_fd. 18087 * These pointers will be used later by verifier to validate map access. 18088 */ 18089 return 0; 18090 } 18091 18092 /* drop refcnt of maps used by the rejected program */ 18093 static void release_maps(struct bpf_verifier_env *env) 18094 { 18095 __bpf_free_used_maps(env->prog->aux, env->used_maps, 18096 env->used_map_cnt); 18097 } 18098 18099 /* drop refcnt of maps used by the rejected program */ 18100 static void release_btfs(struct bpf_verifier_env *env) 18101 { 18102 __bpf_free_used_btfs(env->prog->aux, env->used_btfs, 18103 env->used_btf_cnt); 18104 } 18105 18106 /* convert pseudo BPF_LD_IMM64 into generic BPF_LD_IMM64 */ 18107 static void convert_pseudo_ld_imm64(struct bpf_verifier_env *env) 18108 { 18109 struct bpf_insn *insn = env->prog->insnsi; 18110 int insn_cnt = env->prog->len; 18111 int i; 18112 18113 for (i = 0; i < insn_cnt; i++, insn++) { 18114 if (insn->code != (BPF_LD | BPF_IMM | BPF_DW)) 18115 continue; 18116 if (insn->src_reg == BPF_PSEUDO_FUNC) 18117 continue; 18118 insn->src_reg = 0; 18119 } 18120 } 18121 18122 /* single env->prog->insni[off] instruction was replaced with the range 18123 * insni[off, off + cnt). Adjust corresponding insn_aux_data by copying 18124 * [0, off) and [off, end) to new locations, so the patched range stays zero 18125 */ 18126 static void adjust_insn_aux_data(struct bpf_verifier_env *env, 18127 struct bpf_insn_aux_data *new_data, 18128 struct bpf_prog *new_prog, u32 off, u32 cnt) 18129 { 18130 struct bpf_insn_aux_data *old_data = env->insn_aux_data; 18131 struct bpf_insn *insn = new_prog->insnsi; 18132 u32 old_seen = old_data[off].seen; 18133 u32 prog_len; 18134 int i; 18135 18136 /* aux info at OFF always needs adjustment, no matter fast path 18137 * (cnt == 1) is taken or not. There is no guarantee INSN at OFF is the 18138 * original insn at old prog. 18139 */ 18140 old_data[off].zext_dst = insn_has_def32(env, insn + off + cnt - 1); 18141 18142 if (cnt == 1) 18143 return; 18144 prog_len = new_prog->len; 18145 18146 memcpy(new_data, old_data, sizeof(struct bpf_insn_aux_data) * off); 18147 memcpy(new_data + off + cnt - 1, old_data + off, 18148 sizeof(struct bpf_insn_aux_data) * (prog_len - off - cnt + 1)); 18149 for (i = off; i < off + cnt - 1; i++) { 18150 /* Expand insni[off]'s seen count to the patched range. */ 18151 new_data[i].seen = old_seen; 18152 new_data[i].zext_dst = insn_has_def32(env, insn + i); 18153 } 18154 env->insn_aux_data = new_data; 18155 vfree(old_data); 18156 } 18157 18158 static void adjust_subprog_starts(struct bpf_verifier_env *env, u32 off, u32 len) 18159 { 18160 int i; 18161 18162 if (len == 1) 18163 return; 18164 /* NOTE: fake 'exit' subprog should be updated as well. */ 18165 for (i = 0; i <= env->subprog_cnt; i++) { 18166 if (env->subprog_info[i].start <= off) 18167 continue; 18168 env->subprog_info[i].start += len - 1; 18169 } 18170 } 18171 18172 static void adjust_poke_descs(struct bpf_prog *prog, u32 off, u32 len) 18173 { 18174 struct bpf_jit_poke_descriptor *tab = prog->aux->poke_tab; 18175 int i, sz = prog->aux->size_poke_tab; 18176 struct bpf_jit_poke_descriptor *desc; 18177 18178 for (i = 0; i < sz; i++) { 18179 desc = &tab[i]; 18180 if (desc->insn_idx <= off) 18181 continue; 18182 desc->insn_idx += len - 1; 18183 } 18184 } 18185 18186 static struct bpf_prog *bpf_patch_insn_data(struct bpf_verifier_env *env, u32 off, 18187 const struct bpf_insn *patch, u32 len) 18188 { 18189 struct bpf_prog *new_prog; 18190 struct bpf_insn_aux_data *new_data = NULL; 18191 18192 if (len > 1) { 18193 new_data = vzalloc(array_size(env->prog->len + len - 1, 18194 sizeof(struct bpf_insn_aux_data))); 18195 if (!new_data) 18196 return NULL; 18197 } 18198 18199 new_prog = bpf_patch_insn_single(env->prog, off, patch, len); 18200 if (IS_ERR(new_prog)) { 18201 if (PTR_ERR(new_prog) == -ERANGE) 18202 verbose(env, 18203 "insn %d cannot be patched due to 16-bit range\n", 18204 env->insn_aux_data[off].orig_idx); 18205 vfree(new_data); 18206 return NULL; 18207 } 18208 adjust_insn_aux_data(env, new_data, new_prog, off, len); 18209 adjust_subprog_starts(env, off, len); 18210 adjust_poke_descs(new_prog, off, len); 18211 return new_prog; 18212 } 18213 18214 static int adjust_subprog_starts_after_remove(struct bpf_verifier_env *env, 18215 u32 off, u32 cnt) 18216 { 18217 int i, j; 18218 18219 /* find first prog starting at or after off (first to remove) */ 18220 for (i = 0; i < env->subprog_cnt; i++) 18221 if (env->subprog_info[i].start >= off) 18222 break; 18223 /* find first prog starting at or after off + cnt (first to stay) */ 18224 for (j = i; j < env->subprog_cnt; j++) 18225 if (env->subprog_info[j].start >= off + cnt) 18226 break; 18227 /* if j doesn't start exactly at off + cnt, we are just removing 18228 * the front of previous prog 18229 */ 18230 if (env->subprog_info[j].start != off + cnt) 18231 j--; 18232 18233 if (j > i) { 18234 struct bpf_prog_aux *aux = env->prog->aux; 18235 int move; 18236 18237 /* move fake 'exit' subprog as well */ 18238 move = env->subprog_cnt + 1 - j; 18239 18240 memmove(env->subprog_info + i, 18241 env->subprog_info + j, 18242 sizeof(*env->subprog_info) * move); 18243 env->subprog_cnt -= j - i; 18244 18245 /* remove func_info */ 18246 if (aux->func_info) { 18247 move = aux->func_info_cnt - j; 18248 18249 memmove(aux->func_info + i, 18250 aux->func_info + j, 18251 sizeof(*aux->func_info) * move); 18252 aux->func_info_cnt -= j - i; 18253 /* func_info->insn_off is set after all code rewrites, 18254 * in adjust_btf_func() - no need to adjust 18255 */ 18256 } 18257 } else { 18258 /* convert i from "first prog to remove" to "first to adjust" */ 18259 if (env->subprog_info[i].start == off) 18260 i++; 18261 } 18262 18263 /* update fake 'exit' subprog as well */ 18264 for (; i <= env->subprog_cnt; i++) 18265 env->subprog_info[i].start -= cnt; 18266 18267 return 0; 18268 } 18269 18270 static int bpf_adj_linfo_after_remove(struct bpf_verifier_env *env, u32 off, 18271 u32 cnt) 18272 { 18273 struct bpf_prog *prog = env->prog; 18274 u32 i, l_off, l_cnt, nr_linfo; 18275 struct bpf_line_info *linfo; 18276 18277 nr_linfo = prog->aux->nr_linfo; 18278 if (!nr_linfo) 18279 return 0; 18280 18281 linfo = prog->aux->linfo; 18282 18283 /* find first line info to remove, count lines to be removed */ 18284 for (i = 0; i < nr_linfo; i++) 18285 if (linfo[i].insn_off >= off) 18286 break; 18287 18288 l_off = i; 18289 l_cnt = 0; 18290 for (; i < nr_linfo; i++) 18291 if (linfo[i].insn_off < off + cnt) 18292 l_cnt++; 18293 else 18294 break; 18295 18296 /* First live insn doesn't match first live linfo, it needs to "inherit" 18297 * last removed linfo. prog is already modified, so prog->len == off 18298 * means no live instructions after (tail of the program was removed). 18299 */ 18300 if (prog->len != off && l_cnt && 18301 (i == nr_linfo || linfo[i].insn_off != off + cnt)) { 18302 l_cnt--; 18303 linfo[--i].insn_off = off + cnt; 18304 } 18305 18306 /* remove the line info which refer to the removed instructions */ 18307 if (l_cnt) { 18308 memmove(linfo + l_off, linfo + i, 18309 sizeof(*linfo) * (nr_linfo - i)); 18310 18311 prog->aux->nr_linfo -= l_cnt; 18312 nr_linfo = prog->aux->nr_linfo; 18313 } 18314 18315 /* pull all linfo[i].insn_off >= off + cnt in by cnt */ 18316 for (i = l_off; i < nr_linfo; i++) 18317 linfo[i].insn_off -= cnt; 18318 18319 /* fix up all subprogs (incl. 'exit') which start >= off */ 18320 for (i = 0; i <= env->subprog_cnt; i++) 18321 if (env->subprog_info[i].linfo_idx > l_off) { 18322 /* program may have started in the removed region but 18323 * may not be fully removed 18324 */ 18325 if (env->subprog_info[i].linfo_idx >= l_off + l_cnt) 18326 env->subprog_info[i].linfo_idx -= l_cnt; 18327 else 18328 env->subprog_info[i].linfo_idx = l_off; 18329 } 18330 18331 return 0; 18332 } 18333 18334 static int verifier_remove_insns(struct bpf_verifier_env *env, u32 off, u32 cnt) 18335 { 18336 struct bpf_insn_aux_data *aux_data = env->insn_aux_data; 18337 unsigned int orig_prog_len = env->prog->len; 18338 int err; 18339 18340 if (bpf_prog_is_offloaded(env->prog->aux)) 18341 bpf_prog_offload_remove_insns(env, off, cnt); 18342 18343 err = bpf_remove_insns(env->prog, off, cnt); 18344 if (err) 18345 return err; 18346 18347 err = adjust_subprog_starts_after_remove(env, off, cnt); 18348 if (err) 18349 return err; 18350 18351 err = bpf_adj_linfo_after_remove(env, off, cnt); 18352 if (err) 18353 return err; 18354 18355 memmove(aux_data + off, aux_data + off + cnt, 18356 sizeof(*aux_data) * (orig_prog_len - off - cnt)); 18357 18358 return 0; 18359 } 18360 18361 /* The verifier does more data flow analysis than llvm and will not 18362 * explore branches that are dead at run time. Malicious programs can 18363 * have dead code too. Therefore replace all dead at-run-time code 18364 * with 'ja -1'. 18365 * 18366 * Just nops are not optimal, e.g. if they would sit at the end of the 18367 * program and through another bug we would manage to jump there, then 18368 * we'd execute beyond program memory otherwise. Returning exception 18369 * code also wouldn't work since we can have subprogs where the dead 18370 * code could be located. 18371 */ 18372 static void sanitize_dead_code(struct bpf_verifier_env *env) 18373 { 18374 struct bpf_insn_aux_data *aux_data = env->insn_aux_data; 18375 struct bpf_insn trap = BPF_JMP_IMM(BPF_JA, 0, 0, -1); 18376 struct bpf_insn *insn = env->prog->insnsi; 18377 const int insn_cnt = env->prog->len; 18378 int i; 18379 18380 for (i = 0; i < insn_cnt; i++) { 18381 if (aux_data[i].seen) 18382 continue; 18383 memcpy(insn + i, &trap, sizeof(trap)); 18384 aux_data[i].zext_dst = false; 18385 } 18386 } 18387 18388 static bool insn_is_cond_jump(u8 code) 18389 { 18390 u8 op; 18391 18392 op = BPF_OP(code); 18393 if (BPF_CLASS(code) == BPF_JMP32) 18394 return op != BPF_JA; 18395 18396 if (BPF_CLASS(code) != BPF_JMP) 18397 return false; 18398 18399 return op != BPF_JA && op != BPF_EXIT && op != BPF_CALL; 18400 } 18401 18402 static void opt_hard_wire_dead_code_branches(struct bpf_verifier_env *env) 18403 { 18404 struct bpf_insn_aux_data *aux_data = env->insn_aux_data; 18405 struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0); 18406 struct bpf_insn *insn = env->prog->insnsi; 18407 const int insn_cnt = env->prog->len; 18408 int i; 18409 18410 for (i = 0; i < insn_cnt; i++, insn++) { 18411 if (!insn_is_cond_jump(insn->code)) 18412 continue; 18413 18414 if (!aux_data[i + 1].seen) 18415 ja.off = insn->off; 18416 else if (!aux_data[i + 1 + insn->off].seen) 18417 ja.off = 0; 18418 else 18419 continue; 18420 18421 if (bpf_prog_is_offloaded(env->prog->aux)) 18422 bpf_prog_offload_replace_insn(env, i, &ja); 18423 18424 memcpy(insn, &ja, sizeof(ja)); 18425 } 18426 } 18427 18428 static int opt_remove_dead_code(struct bpf_verifier_env *env) 18429 { 18430 struct bpf_insn_aux_data *aux_data = env->insn_aux_data; 18431 int insn_cnt = env->prog->len; 18432 int i, err; 18433 18434 for (i = 0; i < insn_cnt; i++) { 18435 int j; 18436 18437 j = 0; 18438 while (i + j < insn_cnt && !aux_data[i + j].seen) 18439 j++; 18440 if (!j) 18441 continue; 18442 18443 err = verifier_remove_insns(env, i, j); 18444 if (err) 18445 return err; 18446 insn_cnt = env->prog->len; 18447 } 18448 18449 return 0; 18450 } 18451 18452 static int opt_remove_nops(struct bpf_verifier_env *env) 18453 { 18454 const struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0); 18455 struct bpf_insn *insn = env->prog->insnsi; 18456 int insn_cnt = env->prog->len; 18457 int i, err; 18458 18459 for (i = 0; i < insn_cnt; i++) { 18460 if (memcmp(&insn[i], &ja, sizeof(ja))) 18461 continue; 18462 18463 err = verifier_remove_insns(env, i, 1); 18464 if (err) 18465 return err; 18466 insn_cnt--; 18467 i--; 18468 } 18469 18470 return 0; 18471 } 18472 18473 static int opt_subreg_zext_lo32_rnd_hi32(struct bpf_verifier_env *env, 18474 const union bpf_attr *attr) 18475 { 18476 struct bpf_insn *patch, zext_patch[2], rnd_hi32_patch[4]; 18477 struct bpf_insn_aux_data *aux = env->insn_aux_data; 18478 int i, patch_len, delta = 0, len = env->prog->len; 18479 struct bpf_insn *insns = env->prog->insnsi; 18480 struct bpf_prog *new_prog; 18481 bool rnd_hi32; 18482 18483 rnd_hi32 = attr->prog_flags & BPF_F_TEST_RND_HI32; 18484 zext_patch[1] = BPF_ZEXT_REG(0); 18485 rnd_hi32_patch[1] = BPF_ALU64_IMM(BPF_MOV, BPF_REG_AX, 0); 18486 rnd_hi32_patch[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_AX, 32); 18487 rnd_hi32_patch[3] = BPF_ALU64_REG(BPF_OR, 0, BPF_REG_AX); 18488 for (i = 0; i < len; i++) { 18489 int adj_idx = i + delta; 18490 struct bpf_insn insn; 18491 int load_reg; 18492 18493 insn = insns[adj_idx]; 18494 load_reg = insn_def_regno(&insn); 18495 if (!aux[adj_idx].zext_dst) { 18496 u8 code, class; 18497 u32 imm_rnd; 18498 18499 if (!rnd_hi32) 18500 continue; 18501 18502 code = insn.code; 18503 class = BPF_CLASS(code); 18504 if (load_reg == -1) 18505 continue; 18506 18507 /* NOTE: arg "reg" (the fourth one) is only used for 18508 * BPF_STX + SRC_OP, so it is safe to pass NULL 18509 * here. 18510 */ 18511 if (is_reg64(env, &insn, load_reg, NULL, DST_OP)) { 18512 if (class == BPF_LD && 18513 BPF_MODE(code) == BPF_IMM) 18514 i++; 18515 continue; 18516 } 18517 18518 /* ctx load could be transformed into wider load. */ 18519 if (class == BPF_LDX && 18520 aux[adj_idx].ptr_type == PTR_TO_CTX) 18521 continue; 18522 18523 imm_rnd = get_random_u32(); 18524 rnd_hi32_patch[0] = insn; 18525 rnd_hi32_patch[1].imm = imm_rnd; 18526 rnd_hi32_patch[3].dst_reg = load_reg; 18527 patch = rnd_hi32_patch; 18528 patch_len = 4; 18529 goto apply_patch_buffer; 18530 } 18531 18532 /* Add in an zero-extend instruction if a) the JIT has requested 18533 * it or b) it's a CMPXCHG. 18534 * 18535 * The latter is because: BPF_CMPXCHG always loads a value into 18536 * R0, therefore always zero-extends. However some archs' 18537 * equivalent instruction only does this load when the 18538 * comparison is successful. This detail of CMPXCHG is 18539 * orthogonal to the general zero-extension behaviour of the 18540 * CPU, so it's treated independently of bpf_jit_needs_zext. 18541 */ 18542 if (!bpf_jit_needs_zext() && !is_cmpxchg_insn(&insn)) 18543 continue; 18544 18545 /* Zero-extension is done by the caller. */ 18546 if (bpf_pseudo_kfunc_call(&insn)) 18547 continue; 18548 18549 if (WARN_ON(load_reg == -1)) { 18550 verbose(env, "verifier bug. zext_dst is set, but no reg is defined\n"); 18551 return -EFAULT; 18552 } 18553 18554 zext_patch[0] = insn; 18555 zext_patch[1].dst_reg = load_reg; 18556 zext_patch[1].src_reg = load_reg; 18557 patch = zext_patch; 18558 patch_len = 2; 18559 apply_patch_buffer: 18560 new_prog = bpf_patch_insn_data(env, adj_idx, patch, patch_len); 18561 if (!new_prog) 18562 return -ENOMEM; 18563 env->prog = new_prog; 18564 insns = new_prog->insnsi; 18565 aux = env->insn_aux_data; 18566 delta += patch_len - 1; 18567 } 18568 18569 return 0; 18570 } 18571 18572 /* convert load instructions that access fields of a context type into a 18573 * sequence of instructions that access fields of the underlying structure: 18574 * struct __sk_buff -> struct sk_buff 18575 * struct bpf_sock_ops -> struct sock 18576 */ 18577 static int convert_ctx_accesses(struct bpf_verifier_env *env) 18578 { 18579 const struct bpf_verifier_ops *ops = env->ops; 18580 int i, cnt, size, ctx_field_size, delta = 0; 18581 const int insn_cnt = env->prog->len; 18582 struct bpf_insn insn_buf[16], *insn; 18583 u32 target_size, size_default, off; 18584 struct bpf_prog *new_prog; 18585 enum bpf_access_type type; 18586 bool is_narrower_load; 18587 18588 if (ops->gen_prologue || env->seen_direct_write) { 18589 if (!ops->gen_prologue) { 18590 verbose(env, "bpf verifier is misconfigured\n"); 18591 return -EINVAL; 18592 } 18593 cnt = ops->gen_prologue(insn_buf, env->seen_direct_write, 18594 env->prog); 18595 if (cnt >= ARRAY_SIZE(insn_buf)) { 18596 verbose(env, "bpf verifier is misconfigured\n"); 18597 return -EINVAL; 18598 } else if (cnt) { 18599 new_prog = bpf_patch_insn_data(env, 0, insn_buf, cnt); 18600 if (!new_prog) 18601 return -ENOMEM; 18602 18603 env->prog = new_prog; 18604 delta += cnt - 1; 18605 } 18606 } 18607 18608 if (bpf_prog_is_offloaded(env->prog->aux)) 18609 return 0; 18610 18611 insn = env->prog->insnsi + delta; 18612 18613 for (i = 0; i < insn_cnt; i++, insn++) { 18614 bpf_convert_ctx_access_t convert_ctx_access; 18615 u8 mode; 18616 18617 if (insn->code == (BPF_LDX | BPF_MEM | BPF_B) || 18618 insn->code == (BPF_LDX | BPF_MEM | BPF_H) || 18619 insn->code == (BPF_LDX | BPF_MEM | BPF_W) || 18620 insn->code == (BPF_LDX | BPF_MEM | BPF_DW) || 18621 insn->code == (BPF_LDX | BPF_MEMSX | BPF_B) || 18622 insn->code == (BPF_LDX | BPF_MEMSX | BPF_H) || 18623 insn->code == (BPF_LDX | BPF_MEMSX | BPF_W)) { 18624 type = BPF_READ; 18625 } else if (insn->code == (BPF_STX | BPF_MEM | BPF_B) || 18626 insn->code == (BPF_STX | BPF_MEM | BPF_H) || 18627 insn->code == (BPF_STX | BPF_MEM | BPF_W) || 18628 insn->code == (BPF_STX | BPF_MEM | BPF_DW) || 18629 insn->code == (BPF_ST | BPF_MEM | BPF_B) || 18630 insn->code == (BPF_ST | BPF_MEM | BPF_H) || 18631 insn->code == (BPF_ST | BPF_MEM | BPF_W) || 18632 insn->code == (BPF_ST | BPF_MEM | BPF_DW)) { 18633 type = BPF_WRITE; 18634 } else { 18635 continue; 18636 } 18637 18638 if (type == BPF_WRITE && 18639 env->insn_aux_data[i + delta].sanitize_stack_spill) { 18640 struct bpf_insn patch[] = { 18641 *insn, 18642 BPF_ST_NOSPEC(), 18643 }; 18644 18645 cnt = ARRAY_SIZE(patch); 18646 new_prog = bpf_patch_insn_data(env, i + delta, patch, cnt); 18647 if (!new_prog) 18648 return -ENOMEM; 18649 18650 delta += cnt - 1; 18651 env->prog = new_prog; 18652 insn = new_prog->insnsi + i + delta; 18653 continue; 18654 } 18655 18656 switch ((int)env->insn_aux_data[i + delta].ptr_type) { 18657 case PTR_TO_CTX: 18658 if (!ops->convert_ctx_access) 18659 continue; 18660 convert_ctx_access = ops->convert_ctx_access; 18661 break; 18662 case PTR_TO_SOCKET: 18663 case PTR_TO_SOCK_COMMON: 18664 convert_ctx_access = bpf_sock_convert_ctx_access; 18665 break; 18666 case PTR_TO_TCP_SOCK: 18667 convert_ctx_access = bpf_tcp_sock_convert_ctx_access; 18668 break; 18669 case PTR_TO_XDP_SOCK: 18670 convert_ctx_access = bpf_xdp_sock_convert_ctx_access; 18671 break; 18672 case PTR_TO_BTF_ID: 18673 case PTR_TO_BTF_ID | PTR_UNTRUSTED: 18674 /* PTR_TO_BTF_ID | MEM_ALLOC always has a valid lifetime, unlike 18675 * PTR_TO_BTF_ID, and an active ref_obj_id, but the same cannot 18676 * be said once it is marked PTR_UNTRUSTED, hence we must handle 18677 * any faults for loads into such types. BPF_WRITE is disallowed 18678 * for this case. 18679 */ 18680 case PTR_TO_BTF_ID | MEM_ALLOC | PTR_UNTRUSTED: 18681 if (type == BPF_READ) { 18682 if (BPF_MODE(insn->code) == BPF_MEM) 18683 insn->code = BPF_LDX | BPF_PROBE_MEM | 18684 BPF_SIZE((insn)->code); 18685 else 18686 insn->code = BPF_LDX | BPF_PROBE_MEMSX | 18687 BPF_SIZE((insn)->code); 18688 env->prog->aux->num_exentries++; 18689 } 18690 continue; 18691 default: 18692 continue; 18693 } 18694 18695 ctx_field_size = env->insn_aux_data[i + delta].ctx_field_size; 18696 size = BPF_LDST_BYTES(insn); 18697 mode = BPF_MODE(insn->code); 18698 18699 /* If the read access is a narrower load of the field, 18700 * convert to a 4/8-byte load, to minimum program type specific 18701 * convert_ctx_access changes. If conversion is successful, 18702 * we will apply proper mask to the result. 18703 */ 18704 is_narrower_load = size < ctx_field_size; 18705 size_default = bpf_ctx_off_adjust_machine(ctx_field_size); 18706 off = insn->off; 18707 if (is_narrower_load) { 18708 u8 size_code; 18709 18710 if (type == BPF_WRITE) { 18711 verbose(env, "bpf verifier narrow ctx access misconfigured\n"); 18712 return -EINVAL; 18713 } 18714 18715 size_code = BPF_H; 18716 if (ctx_field_size == 4) 18717 size_code = BPF_W; 18718 else if (ctx_field_size == 8) 18719 size_code = BPF_DW; 18720 18721 insn->off = off & ~(size_default - 1); 18722 insn->code = BPF_LDX | BPF_MEM | size_code; 18723 } 18724 18725 target_size = 0; 18726 cnt = convert_ctx_access(type, insn, insn_buf, env->prog, 18727 &target_size); 18728 if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf) || 18729 (ctx_field_size && !target_size)) { 18730 verbose(env, "bpf verifier is misconfigured\n"); 18731 return -EINVAL; 18732 } 18733 18734 if (is_narrower_load && size < target_size) { 18735 u8 shift = bpf_ctx_narrow_access_offset( 18736 off, size, size_default) * 8; 18737 if (shift && cnt + 1 >= ARRAY_SIZE(insn_buf)) { 18738 verbose(env, "bpf verifier narrow ctx load misconfigured\n"); 18739 return -EINVAL; 18740 } 18741 if (ctx_field_size <= 4) { 18742 if (shift) 18743 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_RSH, 18744 insn->dst_reg, 18745 shift); 18746 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg, 18747 (1 << size * 8) - 1); 18748 } else { 18749 if (shift) 18750 insn_buf[cnt++] = BPF_ALU64_IMM(BPF_RSH, 18751 insn->dst_reg, 18752 shift); 18753 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg, 18754 (1ULL << size * 8) - 1); 18755 } 18756 } 18757 if (mode == BPF_MEMSX) 18758 insn_buf[cnt++] = BPF_RAW_INSN(BPF_ALU64 | BPF_MOV | BPF_X, 18759 insn->dst_reg, insn->dst_reg, 18760 size * 8, 0); 18761 18762 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 18763 if (!new_prog) 18764 return -ENOMEM; 18765 18766 delta += cnt - 1; 18767 18768 /* keep walking new program and skip insns we just inserted */ 18769 env->prog = new_prog; 18770 insn = new_prog->insnsi + i + delta; 18771 } 18772 18773 return 0; 18774 } 18775 18776 static int jit_subprogs(struct bpf_verifier_env *env) 18777 { 18778 struct bpf_prog *prog = env->prog, **func, *tmp; 18779 int i, j, subprog_start, subprog_end = 0, len, subprog; 18780 struct bpf_map *map_ptr; 18781 struct bpf_insn *insn; 18782 void *old_bpf_func; 18783 int err, num_exentries; 18784 18785 if (env->subprog_cnt <= 1) 18786 return 0; 18787 18788 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) { 18789 if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn)) 18790 continue; 18791 18792 /* Upon error here we cannot fall back to interpreter but 18793 * need a hard reject of the program. Thus -EFAULT is 18794 * propagated in any case. 18795 */ 18796 subprog = find_subprog(env, i + insn->imm + 1); 18797 if (subprog < 0) { 18798 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n", 18799 i + insn->imm + 1); 18800 return -EFAULT; 18801 } 18802 /* temporarily remember subprog id inside insn instead of 18803 * aux_data, since next loop will split up all insns into funcs 18804 */ 18805 insn->off = subprog; 18806 /* remember original imm in case JIT fails and fallback 18807 * to interpreter will be needed 18808 */ 18809 env->insn_aux_data[i].call_imm = insn->imm; 18810 /* point imm to __bpf_call_base+1 from JITs point of view */ 18811 insn->imm = 1; 18812 if (bpf_pseudo_func(insn)) 18813 /* jit (e.g. x86_64) may emit fewer instructions 18814 * if it learns a u32 imm is the same as a u64 imm. 18815 * Force a non zero here. 18816 */ 18817 insn[1].imm = 1; 18818 } 18819 18820 err = bpf_prog_alloc_jited_linfo(prog); 18821 if (err) 18822 goto out_undo_insn; 18823 18824 err = -ENOMEM; 18825 func = kcalloc(env->subprog_cnt, sizeof(prog), GFP_KERNEL); 18826 if (!func) 18827 goto out_undo_insn; 18828 18829 for (i = 0; i < env->subprog_cnt; i++) { 18830 subprog_start = subprog_end; 18831 subprog_end = env->subprog_info[i + 1].start; 18832 18833 len = subprog_end - subprog_start; 18834 /* bpf_prog_run() doesn't call subprogs directly, 18835 * hence main prog stats include the runtime of subprogs. 18836 * subprogs don't have IDs and not reachable via prog_get_next_id 18837 * func[i]->stats will never be accessed and stays NULL 18838 */ 18839 func[i] = bpf_prog_alloc_no_stats(bpf_prog_size(len), GFP_USER); 18840 if (!func[i]) 18841 goto out_free; 18842 memcpy(func[i]->insnsi, &prog->insnsi[subprog_start], 18843 len * sizeof(struct bpf_insn)); 18844 func[i]->type = prog->type; 18845 func[i]->len = len; 18846 if (bpf_prog_calc_tag(func[i])) 18847 goto out_free; 18848 func[i]->is_func = 1; 18849 func[i]->aux->func_idx = i; 18850 /* Below members will be freed only at prog->aux */ 18851 func[i]->aux->btf = prog->aux->btf; 18852 func[i]->aux->func_info = prog->aux->func_info; 18853 func[i]->aux->func_info_cnt = prog->aux->func_info_cnt; 18854 func[i]->aux->poke_tab = prog->aux->poke_tab; 18855 func[i]->aux->size_poke_tab = prog->aux->size_poke_tab; 18856 18857 for (j = 0; j < prog->aux->size_poke_tab; j++) { 18858 struct bpf_jit_poke_descriptor *poke; 18859 18860 poke = &prog->aux->poke_tab[j]; 18861 if (poke->insn_idx < subprog_end && 18862 poke->insn_idx >= subprog_start) 18863 poke->aux = func[i]->aux; 18864 } 18865 18866 func[i]->aux->name[0] = 'F'; 18867 func[i]->aux->stack_depth = env->subprog_info[i].stack_depth; 18868 func[i]->jit_requested = 1; 18869 func[i]->blinding_requested = prog->blinding_requested; 18870 func[i]->aux->kfunc_tab = prog->aux->kfunc_tab; 18871 func[i]->aux->kfunc_btf_tab = prog->aux->kfunc_btf_tab; 18872 func[i]->aux->linfo = prog->aux->linfo; 18873 func[i]->aux->nr_linfo = prog->aux->nr_linfo; 18874 func[i]->aux->jited_linfo = prog->aux->jited_linfo; 18875 func[i]->aux->linfo_idx = env->subprog_info[i].linfo_idx; 18876 num_exentries = 0; 18877 insn = func[i]->insnsi; 18878 for (j = 0; j < func[i]->len; j++, insn++) { 18879 if (BPF_CLASS(insn->code) == BPF_LDX && 18880 (BPF_MODE(insn->code) == BPF_PROBE_MEM || 18881 BPF_MODE(insn->code) == BPF_PROBE_MEMSX)) 18882 num_exentries++; 18883 } 18884 func[i]->aux->num_exentries = num_exentries; 18885 func[i]->aux->tail_call_reachable = env->subprog_info[i].tail_call_reachable; 18886 func[i]->aux->exception_cb = env->subprog_info[i].is_exception_cb; 18887 if (!i) 18888 func[i]->aux->exception_boundary = env->seen_exception; 18889 func[i] = bpf_int_jit_compile(func[i]); 18890 if (!func[i]->jited) { 18891 err = -ENOTSUPP; 18892 goto out_free; 18893 } 18894 cond_resched(); 18895 } 18896 18897 /* at this point all bpf functions were successfully JITed 18898 * now populate all bpf_calls with correct addresses and 18899 * run last pass of JIT 18900 */ 18901 for (i = 0; i < env->subprog_cnt; i++) { 18902 insn = func[i]->insnsi; 18903 for (j = 0; j < func[i]->len; j++, insn++) { 18904 if (bpf_pseudo_func(insn)) { 18905 subprog = insn->off; 18906 insn[0].imm = (u32)(long)func[subprog]->bpf_func; 18907 insn[1].imm = ((u64)(long)func[subprog]->bpf_func) >> 32; 18908 continue; 18909 } 18910 if (!bpf_pseudo_call(insn)) 18911 continue; 18912 subprog = insn->off; 18913 insn->imm = BPF_CALL_IMM(func[subprog]->bpf_func); 18914 } 18915 18916 /* we use the aux data to keep a list of the start addresses 18917 * of the JITed images for each function in the program 18918 * 18919 * for some architectures, such as powerpc64, the imm field 18920 * might not be large enough to hold the offset of the start 18921 * address of the callee's JITed image from __bpf_call_base 18922 * 18923 * in such cases, we can lookup the start address of a callee 18924 * by using its subprog id, available from the off field of 18925 * the call instruction, as an index for this list 18926 */ 18927 func[i]->aux->func = func; 18928 func[i]->aux->func_cnt = env->subprog_cnt - env->hidden_subprog_cnt; 18929 func[i]->aux->real_func_cnt = env->subprog_cnt; 18930 } 18931 for (i = 0; i < env->subprog_cnt; i++) { 18932 old_bpf_func = func[i]->bpf_func; 18933 tmp = bpf_int_jit_compile(func[i]); 18934 if (tmp != func[i] || func[i]->bpf_func != old_bpf_func) { 18935 verbose(env, "JIT doesn't support bpf-to-bpf calls\n"); 18936 err = -ENOTSUPP; 18937 goto out_free; 18938 } 18939 cond_resched(); 18940 } 18941 18942 /* finally lock prog and jit images for all functions and 18943 * populate kallsysm. Begin at the first subprogram, since 18944 * bpf_prog_load will add the kallsyms for the main program. 18945 */ 18946 for (i = 1; i < env->subprog_cnt; i++) { 18947 bpf_prog_lock_ro(func[i]); 18948 bpf_prog_kallsyms_add(func[i]); 18949 } 18950 18951 /* Last step: make now unused interpreter insns from main 18952 * prog consistent for later dump requests, so they can 18953 * later look the same as if they were interpreted only. 18954 */ 18955 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) { 18956 if (bpf_pseudo_func(insn)) { 18957 insn[0].imm = env->insn_aux_data[i].call_imm; 18958 insn[1].imm = insn->off; 18959 insn->off = 0; 18960 continue; 18961 } 18962 if (!bpf_pseudo_call(insn)) 18963 continue; 18964 insn->off = env->insn_aux_data[i].call_imm; 18965 subprog = find_subprog(env, i + insn->off + 1); 18966 insn->imm = subprog; 18967 } 18968 18969 prog->jited = 1; 18970 prog->bpf_func = func[0]->bpf_func; 18971 prog->jited_len = func[0]->jited_len; 18972 prog->aux->extable = func[0]->aux->extable; 18973 prog->aux->num_exentries = func[0]->aux->num_exentries; 18974 prog->aux->func = func; 18975 prog->aux->func_cnt = env->subprog_cnt - env->hidden_subprog_cnt; 18976 prog->aux->real_func_cnt = env->subprog_cnt; 18977 prog->aux->bpf_exception_cb = (void *)func[env->exception_callback_subprog]->bpf_func; 18978 prog->aux->exception_boundary = func[0]->aux->exception_boundary; 18979 bpf_prog_jit_attempt_done(prog); 18980 return 0; 18981 out_free: 18982 /* We failed JIT'ing, so at this point we need to unregister poke 18983 * descriptors from subprogs, so that kernel is not attempting to 18984 * patch it anymore as we're freeing the subprog JIT memory. 18985 */ 18986 for (i = 0; i < prog->aux->size_poke_tab; i++) { 18987 map_ptr = prog->aux->poke_tab[i].tail_call.map; 18988 map_ptr->ops->map_poke_untrack(map_ptr, prog->aux); 18989 } 18990 /* At this point we're guaranteed that poke descriptors are not 18991 * live anymore. We can just unlink its descriptor table as it's 18992 * released with the main prog. 18993 */ 18994 for (i = 0; i < env->subprog_cnt; i++) { 18995 if (!func[i]) 18996 continue; 18997 func[i]->aux->poke_tab = NULL; 18998 bpf_jit_free(func[i]); 18999 } 19000 kfree(func); 19001 out_undo_insn: 19002 /* cleanup main prog to be interpreted */ 19003 prog->jit_requested = 0; 19004 prog->blinding_requested = 0; 19005 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) { 19006 if (!bpf_pseudo_call(insn)) 19007 continue; 19008 insn->off = 0; 19009 insn->imm = env->insn_aux_data[i].call_imm; 19010 } 19011 bpf_prog_jit_attempt_done(prog); 19012 return err; 19013 } 19014 19015 static int fixup_call_args(struct bpf_verifier_env *env) 19016 { 19017 #ifndef CONFIG_BPF_JIT_ALWAYS_ON 19018 struct bpf_prog *prog = env->prog; 19019 struct bpf_insn *insn = prog->insnsi; 19020 bool has_kfunc_call = bpf_prog_has_kfunc_call(prog); 19021 int i, depth; 19022 #endif 19023 int err = 0; 19024 19025 if (env->prog->jit_requested && 19026 !bpf_prog_is_offloaded(env->prog->aux)) { 19027 err = jit_subprogs(env); 19028 if (err == 0) 19029 return 0; 19030 if (err == -EFAULT) 19031 return err; 19032 } 19033 #ifndef CONFIG_BPF_JIT_ALWAYS_ON 19034 if (has_kfunc_call) { 19035 verbose(env, "calling kernel functions are not allowed in non-JITed programs\n"); 19036 return -EINVAL; 19037 } 19038 if (env->subprog_cnt > 1 && env->prog->aux->tail_call_reachable) { 19039 /* When JIT fails the progs with bpf2bpf calls and tail_calls 19040 * have to be rejected, since interpreter doesn't support them yet. 19041 */ 19042 verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n"); 19043 return -EINVAL; 19044 } 19045 for (i = 0; i < prog->len; i++, insn++) { 19046 if (bpf_pseudo_func(insn)) { 19047 /* When JIT fails the progs with callback calls 19048 * have to be rejected, since interpreter doesn't support them yet. 19049 */ 19050 verbose(env, "callbacks are not allowed in non-JITed programs\n"); 19051 return -EINVAL; 19052 } 19053 19054 if (!bpf_pseudo_call(insn)) 19055 continue; 19056 depth = get_callee_stack_depth(env, insn, i); 19057 if (depth < 0) 19058 return depth; 19059 bpf_patch_call_args(insn, depth); 19060 } 19061 err = 0; 19062 #endif 19063 return err; 19064 } 19065 19066 /* replace a generic kfunc with a specialized version if necessary */ 19067 static void specialize_kfunc(struct bpf_verifier_env *env, 19068 u32 func_id, u16 offset, unsigned long *addr) 19069 { 19070 struct bpf_prog *prog = env->prog; 19071 bool seen_direct_write; 19072 void *xdp_kfunc; 19073 bool is_rdonly; 19074 19075 if (bpf_dev_bound_kfunc_id(func_id)) { 19076 xdp_kfunc = bpf_dev_bound_resolve_kfunc(prog, func_id); 19077 if (xdp_kfunc) { 19078 *addr = (unsigned long)xdp_kfunc; 19079 return; 19080 } 19081 /* fallback to default kfunc when not supported by netdev */ 19082 } 19083 19084 if (offset) 19085 return; 19086 19087 if (func_id == special_kfunc_list[KF_bpf_dynptr_from_skb]) { 19088 seen_direct_write = env->seen_direct_write; 19089 is_rdonly = !may_access_direct_pkt_data(env, NULL, BPF_WRITE); 19090 19091 if (is_rdonly) 19092 *addr = (unsigned long)bpf_dynptr_from_skb_rdonly; 19093 19094 /* restore env->seen_direct_write to its original value, since 19095 * may_access_direct_pkt_data mutates it 19096 */ 19097 env->seen_direct_write = seen_direct_write; 19098 } 19099 } 19100 19101 static void __fixup_collection_insert_kfunc(struct bpf_insn_aux_data *insn_aux, 19102 u16 struct_meta_reg, 19103 u16 node_offset_reg, 19104 struct bpf_insn *insn, 19105 struct bpf_insn *insn_buf, 19106 int *cnt) 19107 { 19108 struct btf_struct_meta *kptr_struct_meta = insn_aux->kptr_struct_meta; 19109 struct bpf_insn addr[2] = { BPF_LD_IMM64(struct_meta_reg, (long)kptr_struct_meta) }; 19110 19111 insn_buf[0] = addr[0]; 19112 insn_buf[1] = addr[1]; 19113 insn_buf[2] = BPF_MOV64_IMM(node_offset_reg, insn_aux->insert_off); 19114 insn_buf[3] = *insn; 19115 *cnt = 4; 19116 } 19117 19118 static int fixup_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn, 19119 struct bpf_insn *insn_buf, int insn_idx, int *cnt) 19120 { 19121 const struct bpf_kfunc_desc *desc; 19122 19123 if (!insn->imm) { 19124 verbose(env, "invalid kernel function call not eliminated in verifier pass\n"); 19125 return -EINVAL; 19126 } 19127 19128 *cnt = 0; 19129 19130 /* insn->imm has the btf func_id. Replace it with an offset relative to 19131 * __bpf_call_base, unless the JIT needs to call functions that are 19132 * further than 32 bits away (bpf_jit_supports_far_kfunc_call()). 19133 */ 19134 desc = find_kfunc_desc(env->prog, insn->imm, insn->off); 19135 if (!desc) { 19136 verbose(env, "verifier internal error: kernel function descriptor not found for func_id %u\n", 19137 insn->imm); 19138 return -EFAULT; 19139 } 19140 19141 if (!bpf_jit_supports_far_kfunc_call()) 19142 insn->imm = BPF_CALL_IMM(desc->addr); 19143 if (insn->off) 19144 return 0; 19145 if (desc->func_id == special_kfunc_list[KF_bpf_obj_new_impl] || 19146 desc->func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl]) { 19147 struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta; 19148 struct bpf_insn addr[2] = { BPF_LD_IMM64(BPF_REG_2, (long)kptr_struct_meta) }; 19149 u64 obj_new_size = env->insn_aux_data[insn_idx].obj_new_size; 19150 19151 if (desc->func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl] && kptr_struct_meta) { 19152 verbose(env, "verifier internal error: NULL kptr_struct_meta expected at insn_idx %d\n", 19153 insn_idx); 19154 return -EFAULT; 19155 } 19156 19157 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_1, obj_new_size); 19158 insn_buf[1] = addr[0]; 19159 insn_buf[2] = addr[1]; 19160 insn_buf[3] = *insn; 19161 *cnt = 4; 19162 } else if (desc->func_id == special_kfunc_list[KF_bpf_obj_drop_impl] || 19163 desc->func_id == special_kfunc_list[KF_bpf_percpu_obj_drop_impl] || 19164 desc->func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl]) { 19165 struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta; 19166 struct bpf_insn addr[2] = { BPF_LD_IMM64(BPF_REG_2, (long)kptr_struct_meta) }; 19167 19168 if (desc->func_id == special_kfunc_list[KF_bpf_percpu_obj_drop_impl] && kptr_struct_meta) { 19169 verbose(env, "verifier internal error: NULL kptr_struct_meta expected at insn_idx %d\n", 19170 insn_idx); 19171 return -EFAULT; 19172 } 19173 19174 if (desc->func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl] && 19175 !kptr_struct_meta) { 19176 verbose(env, "verifier internal error: kptr_struct_meta expected at insn_idx %d\n", 19177 insn_idx); 19178 return -EFAULT; 19179 } 19180 19181 insn_buf[0] = addr[0]; 19182 insn_buf[1] = addr[1]; 19183 insn_buf[2] = *insn; 19184 *cnt = 3; 19185 } else if (desc->func_id == special_kfunc_list[KF_bpf_list_push_back_impl] || 19186 desc->func_id == special_kfunc_list[KF_bpf_list_push_front_impl] || 19187 desc->func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) { 19188 struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta; 19189 int struct_meta_reg = BPF_REG_3; 19190 int node_offset_reg = BPF_REG_4; 19191 19192 /* rbtree_add has extra 'less' arg, so args-to-fixup are in diff regs */ 19193 if (desc->func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) { 19194 struct_meta_reg = BPF_REG_4; 19195 node_offset_reg = BPF_REG_5; 19196 } 19197 19198 if (!kptr_struct_meta) { 19199 verbose(env, "verifier internal error: kptr_struct_meta expected at insn_idx %d\n", 19200 insn_idx); 19201 return -EFAULT; 19202 } 19203 19204 __fixup_collection_insert_kfunc(&env->insn_aux_data[insn_idx], struct_meta_reg, 19205 node_offset_reg, insn, insn_buf, cnt); 19206 } else if (desc->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx] || 19207 desc->func_id == special_kfunc_list[KF_bpf_rdonly_cast]) { 19208 insn_buf[0] = BPF_MOV64_REG(BPF_REG_0, BPF_REG_1); 19209 *cnt = 1; 19210 } 19211 return 0; 19212 } 19213 19214 /* The function requires that first instruction in 'patch' is insnsi[prog->len - 1] */ 19215 static int add_hidden_subprog(struct bpf_verifier_env *env, struct bpf_insn *patch, int len) 19216 { 19217 struct bpf_subprog_info *info = env->subprog_info; 19218 int cnt = env->subprog_cnt; 19219 struct bpf_prog *prog; 19220 19221 /* We only reserve one slot for hidden subprogs in subprog_info. */ 19222 if (env->hidden_subprog_cnt) { 19223 verbose(env, "verifier internal error: only one hidden subprog supported\n"); 19224 return -EFAULT; 19225 } 19226 /* We're not patching any existing instruction, just appending the new 19227 * ones for the hidden subprog. Hence all of the adjustment operations 19228 * in bpf_patch_insn_data are no-ops. 19229 */ 19230 prog = bpf_patch_insn_data(env, env->prog->len - 1, patch, len); 19231 if (!prog) 19232 return -ENOMEM; 19233 env->prog = prog; 19234 info[cnt + 1].start = info[cnt].start; 19235 info[cnt].start = prog->len - len + 1; 19236 env->subprog_cnt++; 19237 env->hidden_subprog_cnt++; 19238 return 0; 19239 } 19240 19241 /* Do various post-verification rewrites in a single program pass. 19242 * These rewrites simplify JIT and interpreter implementations. 19243 */ 19244 static int do_misc_fixups(struct bpf_verifier_env *env) 19245 { 19246 struct bpf_prog *prog = env->prog; 19247 enum bpf_attach_type eatype = prog->expected_attach_type; 19248 enum bpf_prog_type prog_type = resolve_prog_type(prog); 19249 struct bpf_insn *insn = prog->insnsi; 19250 const struct bpf_func_proto *fn; 19251 const int insn_cnt = prog->len; 19252 const struct bpf_map_ops *ops; 19253 struct bpf_insn_aux_data *aux; 19254 struct bpf_insn insn_buf[16]; 19255 struct bpf_prog *new_prog; 19256 struct bpf_map *map_ptr; 19257 int i, ret, cnt, delta = 0; 19258 19259 if (env->seen_exception && !env->exception_callback_subprog) { 19260 struct bpf_insn patch[] = { 19261 env->prog->insnsi[insn_cnt - 1], 19262 BPF_MOV64_REG(BPF_REG_0, BPF_REG_1), 19263 BPF_EXIT_INSN(), 19264 }; 19265 19266 ret = add_hidden_subprog(env, patch, ARRAY_SIZE(patch)); 19267 if (ret < 0) 19268 return ret; 19269 prog = env->prog; 19270 insn = prog->insnsi; 19271 19272 env->exception_callback_subprog = env->subprog_cnt - 1; 19273 /* Don't update insn_cnt, as add_hidden_subprog always appends insns */ 19274 env->subprog_info[env->exception_callback_subprog].is_cb = true; 19275 env->subprog_info[env->exception_callback_subprog].is_async_cb = true; 19276 env->subprog_info[env->exception_callback_subprog].is_exception_cb = true; 19277 } 19278 19279 for (i = 0; i < insn_cnt; i++, insn++) { 19280 /* Make divide-by-zero exceptions impossible. */ 19281 if (insn->code == (BPF_ALU64 | BPF_MOD | BPF_X) || 19282 insn->code == (BPF_ALU64 | BPF_DIV | BPF_X) || 19283 insn->code == (BPF_ALU | BPF_MOD | BPF_X) || 19284 insn->code == (BPF_ALU | BPF_DIV | BPF_X)) { 19285 bool is64 = BPF_CLASS(insn->code) == BPF_ALU64; 19286 bool isdiv = BPF_OP(insn->code) == BPF_DIV; 19287 struct bpf_insn *patchlet; 19288 struct bpf_insn chk_and_div[] = { 19289 /* [R,W]x div 0 -> 0 */ 19290 BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) | 19291 BPF_JNE | BPF_K, insn->src_reg, 19292 0, 2, 0), 19293 BPF_ALU32_REG(BPF_XOR, insn->dst_reg, insn->dst_reg), 19294 BPF_JMP_IMM(BPF_JA, 0, 0, 1), 19295 *insn, 19296 }; 19297 struct bpf_insn chk_and_mod[] = { 19298 /* [R,W]x mod 0 -> [R,W]x */ 19299 BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) | 19300 BPF_JEQ | BPF_K, insn->src_reg, 19301 0, 1 + (is64 ? 0 : 1), 0), 19302 *insn, 19303 BPF_JMP_IMM(BPF_JA, 0, 0, 1), 19304 BPF_MOV32_REG(insn->dst_reg, insn->dst_reg), 19305 }; 19306 19307 patchlet = isdiv ? chk_and_div : chk_and_mod; 19308 cnt = isdiv ? ARRAY_SIZE(chk_and_div) : 19309 ARRAY_SIZE(chk_and_mod) - (is64 ? 2 : 0); 19310 19311 new_prog = bpf_patch_insn_data(env, i + delta, patchlet, cnt); 19312 if (!new_prog) 19313 return -ENOMEM; 19314 19315 delta += cnt - 1; 19316 env->prog = prog = new_prog; 19317 insn = new_prog->insnsi + i + delta; 19318 continue; 19319 } 19320 19321 /* Implement LD_ABS and LD_IND with a rewrite, if supported by the program type. */ 19322 if (BPF_CLASS(insn->code) == BPF_LD && 19323 (BPF_MODE(insn->code) == BPF_ABS || 19324 BPF_MODE(insn->code) == BPF_IND)) { 19325 cnt = env->ops->gen_ld_abs(insn, insn_buf); 19326 if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf)) { 19327 verbose(env, "bpf verifier is misconfigured\n"); 19328 return -EINVAL; 19329 } 19330 19331 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 19332 if (!new_prog) 19333 return -ENOMEM; 19334 19335 delta += cnt - 1; 19336 env->prog = prog = new_prog; 19337 insn = new_prog->insnsi + i + delta; 19338 continue; 19339 } 19340 19341 /* Rewrite pointer arithmetic to mitigate speculation attacks. */ 19342 if (insn->code == (BPF_ALU64 | BPF_ADD | BPF_X) || 19343 insn->code == (BPF_ALU64 | BPF_SUB | BPF_X)) { 19344 const u8 code_add = BPF_ALU64 | BPF_ADD | BPF_X; 19345 const u8 code_sub = BPF_ALU64 | BPF_SUB | BPF_X; 19346 struct bpf_insn *patch = &insn_buf[0]; 19347 bool issrc, isneg, isimm; 19348 u32 off_reg; 19349 19350 aux = &env->insn_aux_data[i + delta]; 19351 if (!aux->alu_state || 19352 aux->alu_state == BPF_ALU_NON_POINTER) 19353 continue; 19354 19355 isneg = aux->alu_state & BPF_ALU_NEG_VALUE; 19356 issrc = (aux->alu_state & BPF_ALU_SANITIZE) == 19357 BPF_ALU_SANITIZE_SRC; 19358 isimm = aux->alu_state & BPF_ALU_IMMEDIATE; 19359 19360 off_reg = issrc ? insn->src_reg : insn->dst_reg; 19361 if (isimm) { 19362 *patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit); 19363 } else { 19364 if (isneg) 19365 *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1); 19366 *patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit); 19367 *patch++ = BPF_ALU64_REG(BPF_SUB, BPF_REG_AX, off_reg); 19368 *patch++ = BPF_ALU64_REG(BPF_OR, BPF_REG_AX, off_reg); 19369 *patch++ = BPF_ALU64_IMM(BPF_NEG, BPF_REG_AX, 0); 19370 *patch++ = BPF_ALU64_IMM(BPF_ARSH, BPF_REG_AX, 63); 19371 *patch++ = BPF_ALU64_REG(BPF_AND, BPF_REG_AX, off_reg); 19372 } 19373 if (!issrc) 19374 *patch++ = BPF_MOV64_REG(insn->dst_reg, insn->src_reg); 19375 insn->src_reg = BPF_REG_AX; 19376 if (isneg) 19377 insn->code = insn->code == code_add ? 19378 code_sub : code_add; 19379 *patch++ = *insn; 19380 if (issrc && isneg && !isimm) 19381 *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1); 19382 cnt = patch - insn_buf; 19383 19384 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 19385 if (!new_prog) 19386 return -ENOMEM; 19387 19388 delta += cnt - 1; 19389 env->prog = prog = new_prog; 19390 insn = new_prog->insnsi + i + delta; 19391 continue; 19392 } 19393 19394 if (insn->code != (BPF_JMP | BPF_CALL)) 19395 continue; 19396 if (insn->src_reg == BPF_PSEUDO_CALL) 19397 continue; 19398 if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) { 19399 ret = fixup_kfunc_call(env, insn, insn_buf, i + delta, &cnt); 19400 if (ret) 19401 return ret; 19402 if (cnt == 0) 19403 continue; 19404 19405 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 19406 if (!new_prog) 19407 return -ENOMEM; 19408 19409 delta += cnt - 1; 19410 env->prog = prog = new_prog; 19411 insn = new_prog->insnsi + i + delta; 19412 continue; 19413 } 19414 19415 if (insn->imm == BPF_FUNC_get_route_realm) 19416 prog->dst_needed = 1; 19417 if (insn->imm == BPF_FUNC_get_prandom_u32) 19418 bpf_user_rnd_init_once(); 19419 if (insn->imm == BPF_FUNC_override_return) 19420 prog->kprobe_override = 1; 19421 if (insn->imm == BPF_FUNC_tail_call) { 19422 /* If we tail call into other programs, we 19423 * cannot make any assumptions since they can 19424 * be replaced dynamically during runtime in 19425 * the program array. 19426 */ 19427 prog->cb_access = 1; 19428 if (!allow_tail_call_in_subprogs(env)) 19429 prog->aux->stack_depth = MAX_BPF_STACK; 19430 prog->aux->max_pkt_offset = MAX_PACKET_OFF; 19431 19432 /* mark bpf_tail_call as different opcode to avoid 19433 * conditional branch in the interpreter for every normal 19434 * call and to prevent accidental JITing by JIT compiler 19435 * that doesn't support bpf_tail_call yet 19436 */ 19437 insn->imm = 0; 19438 insn->code = BPF_JMP | BPF_TAIL_CALL; 19439 19440 aux = &env->insn_aux_data[i + delta]; 19441 if (env->bpf_capable && !prog->blinding_requested && 19442 prog->jit_requested && 19443 !bpf_map_key_poisoned(aux) && 19444 !bpf_map_ptr_poisoned(aux) && 19445 !bpf_map_ptr_unpriv(aux)) { 19446 struct bpf_jit_poke_descriptor desc = { 19447 .reason = BPF_POKE_REASON_TAIL_CALL, 19448 .tail_call.map = BPF_MAP_PTR(aux->map_ptr_state), 19449 .tail_call.key = bpf_map_key_immediate(aux), 19450 .insn_idx = i + delta, 19451 }; 19452 19453 ret = bpf_jit_add_poke_descriptor(prog, &desc); 19454 if (ret < 0) { 19455 verbose(env, "adding tail call poke descriptor failed\n"); 19456 return ret; 19457 } 19458 19459 insn->imm = ret + 1; 19460 continue; 19461 } 19462 19463 if (!bpf_map_ptr_unpriv(aux)) 19464 continue; 19465 19466 /* instead of changing every JIT dealing with tail_call 19467 * emit two extra insns: 19468 * if (index >= max_entries) goto out; 19469 * index &= array->index_mask; 19470 * to avoid out-of-bounds cpu speculation 19471 */ 19472 if (bpf_map_ptr_poisoned(aux)) { 19473 verbose(env, "tail_call abusing map_ptr\n"); 19474 return -EINVAL; 19475 } 19476 19477 map_ptr = BPF_MAP_PTR(aux->map_ptr_state); 19478 insn_buf[0] = BPF_JMP_IMM(BPF_JGE, BPF_REG_3, 19479 map_ptr->max_entries, 2); 19480 insn_buf[1] = BPF_ALU32_IMM(BPF_AND, BPF_REG_3, 19481 container_of(map_ptr, 19482 struct bpf_array, 19483 map)->index_mask); 19484 insn_buf[2] = *insn; 19485 cnt = 3; 19486 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 19487 if (!new_prog) 19488 return -ENOMEM; 19489 19490 delta += cnt - 1; 19491 env->prog = prog = new_prog; 19492 insn = new_prog->insnsi + i + delta; 19493 continue; 19494 } 19495 19496 if (insn->imm == BPF_FUNC_timer_set_callback) { 19497 /* The verifier will process callback_fn as many times as necessary 19498 * with different maps and the register states prepared by 19499 * set_timer_callback_state will be accurate. 19500 * 19501 * The following use case is valid: 19502 * map1 is shared by prog1, prog2, prog3. 19503 * prog1 calls bpf_timer_init for some map1 elements 19504 * prog2 calls bpf_timer_set_callback for some map1 elements. 19505 * Those that were not bpf_timer_init-ed will return -EINVAL. 19506 * prog3 calls bpf_timer_start for some map1 elements. 19507 * Those that were not both bpf_timer_init-ed and 19508 * bpf_timer_set_callback-ed will return -EINVAL. 19509 */ 19510 struct bpf_insn ld_addrs[2] = { 19511 BPF_LD_IMM64(BPF_REG_3, (long)prog->aux), 19512 }; 19513 19514 insn_buf[0] = ld_addrs[0]; 19515 insn_buf[1] = ld_addrs[1]; 19516 insn_buf[2] = *insn; 19517 cnt = 3; 19518 19519 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 19520 if (!new_prog) 19521 return -ENOMEM; 19522 19523 delta += cnt - 1; 19524 env->prog = prog = new_prog; 19525 insn = new_prog->insnsi + i + delta; 19526 goto patch_call_imm; 19527 } 19528 19529 if (is_storage_get_function(insn->imm)) { 19530 if (!env->prog->aux->sleepable || 19531 env->insn_aux_data[i + delta].storage_get_func_atomic) 19532 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_5, (__force __s32)GFP_ATOMIC); 19533 else 19534 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_5, (__force __s32)GFP_KERNEL); 19535 insn_buf[1] = *insn; 19536 cnt = 2; 19537 19538 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 19539 if (!new_prog) 19540 return -ENOMEM; 19541 19542 delta += cnt - 1; 19543 env->prog = prog = new_prog; 19544 insn = new_prog->insnsi + i + delta; 19545 goto patch_call_imm; 19546 } 19547 19548 /* bpf_per_cpu_ptr() and bpf_this_cpu_ptr() */ 19549 if (env->insn_aux_data[i + delta].call_with_percpu_alloc_ptr) { 19550 /* patch with 'r1 = *(u64 *)(r1 + 0)' since for percpu data, 19551 * bpf_mem_alloc() returns a ptr to the percpu data ptr. 19552 */ 19553 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_1, BPF_REG_1, 0); 19554 insn_buf[1] = *insn; 19555 cnt = 2; 19556 19557 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 19558 if (!new_prog) 19559 return -ENOMEM; 19560 19561 delta += cnt - 1; 19562 env->prog = prog = new_prog; 19563 insn = new_prog->insnsi + i + delta; 19564 goto patch_call_imm; 19565 } 19566 19567 /* BPF_EMIT_CALL() assumptions in some of the map_gen_lookup 19568 * and other inlining handlers are currently limited to 64 bit 19569 * only. 19570 */ 19571 if (prog->jit_requested && BITS_PER_LONG == 64 && 19572 (insn->imm == BPF_FUNC_map_lookup_elem || 19573 insn->imm == BPF_FUNC_map_update_elem || 19574 insn->imm == BPF_FUNC_map_delete_elem || 19575 insn->imm == BPF_FUNC_map_push_elem || 19576 insn->imm == BPF_FUNC_map_pop_elem || 19577 insn->imm == BPF_FUNC_map_peek_elem || 19578 insn->imm == BPF_FUNC_redirect_map || 19579 insn->imm == BPF_FUNC_for_each_map_elem || 19580 insn->imm == BPF_FUNC_map_lookup_percpu_elem)) { 19581 aux = &env->insn_aux_data[i + delta]; 19582 if (bpf_map_ptr_poisoned(aux)) 19583 goto patch_call_imm; 19584 19585 map_ptr = BPF_MAP_PTR(aux->map_ptr_state); 19586 ops = map_ptr->ops; 19587 if (insn->imm == BPF_FUNC_map_lookup_elem && 19588 ops->map_gen_lookup) { 19589 cnt = ops->map_gen_lookup(map_ptr, insn_buf); 19590 if (cnt == -EOPNOTSUPP) 19591 goto patch_map_ops_generic; 19592 if (cnt <= 0 || cnt >= ARRAY_SIZE(insn_buf)) { 19593 verbose(env, "bpf verifier is misconfigured\n"); 19594 return -EINVAL; 19595 } 19596 19597 new_prog = bpf_patch_insn_data(env, i + delta, 19598 insn_buf, cnt); 19599 if (!new_prog) 19600 return -ENOMEM; 19601 19602 delta += cnt - 1; 19603 env->prog = prog = new_prog; 19604 insn = new_prog->insnsi + i + delta; 19605 continue; 19606 } 19607 19608 BUILD_BUG_ON(!__same_type(ops->map_lookup_elem, 19609 (void *(*)(struct bpf_map *map, void *key))NULL)); 19610 BUILD_BUG_ON(!__same_type(ops->map_delete_elem, 19611 (long (*)(struct bpf_map *map, void *key))NULL)); 19612 BUILD_BUG_ON(!__same_type(ops->map_update_elem, 19613 (long (*)(struct bpf_map *map, void *key, void *value, 19614 u64 flags))NULL)); 19615 BUILD_BUG_ON(!__same_type(ops->map_push_elem, 19616 (long (*)(struct bpf_map *map, void *value, 19617 u64 flags))NULL)); 19618 BUILD_BUG_ON(!__same_type(ops->map_pop_elem, 19619 (long (*)(struct bpf_map *map, void *value))NULL)); 19620 BUILD_BUG_ON(!__same_type(ops->map_peek_elem, 19621 (long (*)(struct bpf_map *map, void *value))NULL)); 19622 BUILD_BUG_ON(!__same_type(ops->map_redirect, 19623 (long (*)(struct bpf_map *map, u64 index, u64 flags))NULL)); 19624 BUILD_BUG_ON(!__same_type(ops->map_for_each_callback, 19625 (long (*)(struct bpf_map *map, 19626 bpf_callback_t callback_fn, 19627 void *callback_ctx, 19628 u64 flags))NULL)); 19629 BUILD_BUG_ON(!__same_type(ops->map_lookup_percpu_elem, 19630 (void *(*)(struct bpf_map *map, void *key, u32 cpu))NULL)); 19631 19632 patch_map_ops_generic: 19633 switch (insn->imm) { 19634 case BPF_FUNC_map_lookup_elem: 19635 insn->imm = BPF_CALL_IMM(ops->map_lookup_elem); 19636 continue; 19637 case BPF_FUNC_map_update_elem: 19638 insn->imm = BPF_CALL_IMM(ops->map_update_elem); 19639 continue; 19640 case BPF_FUNC_map_delete_elem: 19641 insn->imm = BPF_CALL_IMM(ops->map_delete_elem); 19642 continue; 19643 case BPF_FUNC_map_push_elem: 19644 insn->imm = BPF_CALL_IMM(ops->map_push_elem); 19645 continue; 19646 case BPF_FUNC_map_pop_elem: 19647 insn->imm = BPF_CALL_IMM(ops->map_pop_elem); 19648 continue; 19649 case BPF_FUNC_map_peek_elem: 19650 insn->imm = BPF_CALL_IMM(ops->map_peek_elem); 19651 continue; 19652 case BPF_FUNC_redirect_map: 19653 insn->imm = BPF_CALL_IMM(ops->map_redirect); 19654 continue; 19655 case BPF_FUNC_for_each_map_elem: 19656 insn->imm = BPF_CALL_IMM(ops->map_for_each_callback); 19657 continue; 19658 case BPF_FUNC_map_lookup_percpu_elem: 19659 insn->imm = BPF_CALL_IMM(ops->map_lookup_percpu_elem); 19660 continue; 19661 } 19662 19663 goto patch_call_imm; 19664 } 19665 19666 /* Implement bpf_jiffies64 inline. */ 19667 if (prog->jit_requested && BITS_PER_LONG == 64 && 19668 insn->imm == BPF_FUNC_jiffies64) { 19669 struct bpf_insn ld_jiffies_addr[2] = { 19670 BPF_LD_IMM64(BPF_REG_0, 19671 (unsigned long)&jiffies), 19672 }; 19673 19674 insn_buf[0] = ld_jiffies_addr[0]; 19675 insn_buf[1] = ld_jiffies_addr[1]; 19676 insn_buf[2] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, 19677 BPF_REG_0, 0); 19678 cnt = 3; 19679 19680 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 19681 cnt); 19682 if (!new_prog) 19683 return -ENOMEM; 19684 19685 delta += cnt - 1; 19686 env->prog = prog = new_prog; 19687 insn = new_prog->insnsi + i + delta; 19688 continue; 19689 } 19690 19691 /* Implement bpf_get_func_arg inline. */ 19692 if (prog_type == BPF_PROG_TYPE_TRACING && 19693 insn->imm == BPF_FUNC_get_func_arg) { 19694 /* Load nr_args from ctx - 8 */ 19695 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8); 19696 insn_buf[1] = BPF_JMP32_REG(BPF_JGE, BPF_REG_2, BPF_REG_0, 6); 19697 insn_buf[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_2, 3); 19698 insn_buf[3] = BPF_ALU64_REG(BPF_ADD, BPF_REG_2, BPF_REG_1); 19699 insn_buf[4] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_2, 0); 19700 insn_buf[5] = BPF_STX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0); 19701 insn_buf[6] = BPF_MOV64_IMM(BPF_REG_0, 0); 19702 insn_buf[7] = BPF_JMP_A(1); 19703 insn_buf[8] = BPF_MOV64_IMM(BPF_REG_0, -EINVAL); 19704 cnt = 9; 19705 19706 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 19707 if (!new_prog) 19708 return -ENOMEM; 19709 19710 delta += cnt - 1; 19711 env->prog = prog = new_prog; 19712 insn = new_prog->insnsi + i + delta; 19713 continue; 19714 } 19715 19716 /* Implement bpf_get_func_ret inline. */ 19717 if (prog_type == BPF_PROG_TYPE_TRACING && 19718 insn->imm == BPF_FUNC_get_func_ret) { 19719 if (eatype == BPF_TRACE_FEXIT || 19720 eatype == BPF_MODIFY_RETURN) { 19721 /* Load nr_args from ctx - 8 */ 19722 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8); 19723 insn_buf[1] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_0, 3); 19724 insn_buf[2] = BPF_ALU64_REG(BPF_ADD, BPF_REG_0, BPF_REG_1); 19725 insn_buf[3] = BPF_LDX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0); 19726 insn_buf[4] = BPF_STX_MEM(BPF_DW, BPF_REG_2, BPF_REG_3, 0); 19727 insn_buf[5] = BPF_MOV64_IMM(BPF_REG_0, 0); 19728 cnt = 6; 19729 } else { 19730 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_0, -EOPNOTSUPP); 19731 cnt = 1; 19732 } 19733 19734 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 19735 if (!new_prog) 19736 return -ENOMEM; 19737 19738 delta += cnt - 1; 19739 env->prog = prog = new_prog; 19740 insn = new_prog->insnsi + i + delta; 19741 continue; 19742 } 19743 19744 /* Implement get_func_arg_cnt inline. */ 19745 if (prog_type == BPF_PROG_TYPE_TRACING && 19746 insn->imm == BPF_FUNC_get_func_arg_cnt) { 19747 /* Load nr_args from ctx - 8 */ 19748 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8); 19749 19750 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1); 19751 if (!new_prog) 19752 return -ENOMEM; 19753 19754 env->prog = prog = new_prog; 19755 insn = new_prog->insnsi + i + delta; 19756 continue; 19757 } 19758 19759 /* Implement bpf_get_func_ip inline. */ 19760 if (prog_type == BPF_PROG_TYPE_TRACING && 19761 insn->imm == BPF_FUNC_get_func_ip) { 19762 /* Load IP address from ctx - 16 */ 19763 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -16); 19764 19765 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1); 19766 if (!new_prog) 19767 return -ENOMEM; 19768 19769 env->prog = prog = new_prog; 19770 insn = new_prog->insnsi + i + delta; 19771 continue; 19772 } 19773 19774 patch_call_imm: 19775 fn = env->ops->get_func_proto(insn->imm, env->prog); 19776 /* all functions that have prototype and verifier allowed 19777 * programs to call them, must be real in-kernel functions 19778 */ 19779 if (!fn->func) { 19780 verbose(env, 19781 "kernel subsystem misconfigured func %s#%d\n", 19782 func_id_name(insn->imm), insn->imm); 19783 return -EFAULT; 19784 } 19785 insn->imm = fn->func - __bpf_call_base; 19786 } 19787 19788 /* Since poke tab is now finalized, publish aux to tracker. */ 19789 for (i = 0; i < prog->aux->size_poke_tab; i++) { 19790 map_ptr = prog->aux->poke_tab[i].tail_call.map; 19791 if (!map_ptr->ops->map_poke_track || 19792 !map_ptr->ops->map_poke_untrack || 19793 !map_ptr->ops->map_poke_run) { 19794 verbose(env, "bpf verifier is misconfigured\n"); 19795 return -EINVAL; 19796 } 19797 19798 ret = map_ptr->ops->map_poke_track(map_ptr, prog->aux); 19799 if (ret < 0) { 19800 verbose(env, "tracking tail call prog failed\n"); 19801 return ret; 19802 } 19803 } 19804 19805 sort_kfunc_descs_by_imm_off(env->prog); 19806 19807 return 0; 19808 } 19809 19810 static struct bpf_prog *inline_bpf_loop(struct bpf_verifier_env *env, 19811 int position, 19812 s32 stack_base, 19813 u32 callback_subprogno, 19814 u32 *cnt) 19815 { 19816 s32 r6_offset = stack_base + 0 * BPF_REG_SIZE; 19817 s32 r7_offset = stack_base + 1 * BPF_REG_SIZE; 19818 s32 r8_offset = stack_base + 2 * BPF_REG_SIZE; 19819 int reg_loop_max = BPF_REG_6; 19820 int reg_loop_cnt = BPF_REG_7; 19821 int reg_loop_ctx = BPF_REG_8; 19822 19823 struct bpf_prog *new_prog; 19824 u32 callback_start; 19825 u32 call_insn_offset; 19826 s32 callback_offset; 19827 19828 /* This represents an inlined version of bpf_iter.c:bpf_loop, 19829 * be careful to modify this code in sync. 19830 */ 19831 struct bpf_insn insn_buf[] = { 19832 /* Return error and jump to the end of the patch if 19833 * expected number of iterations is too big. 19834 */ 19835 BPF_JMP_IMM(BPF_JLE, BPF_REG_1, BPF_MAX_LOOPS, 2), 19836 BPF_MOV32_IMM(BPF_REG_0, -E2BIG), 19837 BPF_JMP_IMM(BPF_JA, 0, 0, 16), 19838 /* spill R6, R7, R8 to use these as loop vars */ 19839 BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_6, r6_offset), 19840 BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_7, r7_offset), 19841 BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_8, r8_offset), 19842 /* initialize loop vars */ 19843 BPF_MOV64_REG(reg_loop_max, BPF_REG_1), 19844 BPF_MOV32_IMM(reg_loop_cnt, 0), 19845 BPF_MOV64_REG(reg_loop_ctx, BPF_REG_3), 19846 /* loop header, 19847 * if reg_loop_cnt >= reg_loop_max skip the loop body 19848 */ 19849 BPF_JMP_REG(BPF_JGE, reg_loop_cnt, reg_loop_max, 5), 19850 /* callback call, 19851 * correct callback offset would be set after patching 19852 */ 19853 BPF_MOV64_REG(BPF_REG_1, reg_loop_cnt), 19854 BPF_MOV64_REG(BPF_REG_2, reg_loop_ctx), 19855 BPF_CALL_REL(0), 19856 /* increment loop counter */ 19857 BPF_ALU64_IMM(BPF_ADD, reg_loop_cnt, 1), 19858 /* jump to loop header if callback returned 0 */ 19859 BPF_JMP_IMM(BPF_JEQ, BPF_REG_0, 0, -6), 19860 /* return value of bpf_loop, 19861 * set R0 to the number of iterations 19862 */ 19863 BPF_MOV64_REG(BPF_REG_0, reg_loop_cnt), 19864 /* restore original values of R6, R7, R8 */ 19865 BPF_LDX_MEM(BPF_DW, BPF_REG_6, BPF_REG_10, r6_offset), 19866 BPF_LDX_MEM(BPF_DW, BPF_REG_7, BPF_REG_10, r7_offset), 19867 BPF_LDX_MEM(BPF_DW, BPF_REG_8, BPF_REG_10, r8_offset), 19868 }; 19869 19870 *cnt = ARRAY_SIZE(insn_buf); 19871 new_prog = bpf_patch_insn_data(env, position, insn_buf, *cnt); 19872 if (!new_prog) 19873 return new_prog; 19874 19875 /* callback start is known only after patching */ 19876 callback_start = env->subprog_info[callback_subprogno].start; 19877 /* Note: insn_buf[12] is an offset of BPF_CALL_REL instruction */ 19878 call_insn_offset = position + 12; 19879 callback_offset = callback_start - call_insn_offset - 1; 19880 new_prog->insnsi[call_insn_offset].imm = callback_offset; 19881 19882 return new_prog; 19883 } 19884 19885 static bool is_bpf_loop_call(struct bpf_insn *insn) 19886 { 19887 return insn->code == (BPF_JMP | BPF_CALL) && 19888 insn->src_reg == 0 && 19889 insn->imm == BPF_FUNC_loop; 19890 } 19891 19892 /* For all sub-programs in the program (including main) check 19893 * insn_aux_data to see if there are bpf_loop calls that require 19894 * inlining. If such calls are found the calls are replaced with a 19895 * sequence of instructions produced by `inline_bpf_loop` function and 19896 * subprog stack_depth is increased by the size of 3 registers. 19897 * This stack space is used to spill values of the R6, R7, R8. These 19898 * registers are used to store the loop bound, counter and context 19899 * variables. 19900 */ 19901 static int optimize_bpf_loop(struct bpf_verifier_env *env) 19902 { 19903 struct bpf_subprog_info *subprogs = env->subprog_info; 19904 int i, cur_subprog = 0, cnt, delta = 0; 19905 struct bpf_insn *insn = env->prog->insnsi; 19906 int insn_cnt = env->prog->len; 19907 u16 stack_depth = subprogs[cur_subprog].stack_depth; 19908 u16 stack_depth_roundup = round_up(stack_depth, 8) - stack_depth; 19909 u16 stack_depth_extra = 0; 19910 19911 for (i = 0; i < insn_cnt; i++, insn++) { 19912 struct bpf_loop_inline_state *inline_state = 19913 &env->insn_aux_data[i + delta].loop_inline_state; 19914 19915 if (is_bpf_loop_call(insn) && inline_state->fit_for_inline) { 19916 struct bpf_prog *new_prog; 19917 19918 stack_depth_extra = BPF_REG_SIZE * 3 + stack_depth_roundup; 19919 new_prog = inline_bpf_loop(env, 19920 i + delta, 19921 -(stack_depth + stack_depth_extra), 19922 inline_state->callback_subprogno, 19923 &cnt); 19924 if (!new_prog) 19925 return -ENOMEM; 19926 19927 delta += cnt - 1; 19928 env->prog = new_prog; 19929 insn = new_prog->insnsi + i + delta; 19930 } 19931 19932 if (subprogs[cur_subprog + 1].start == i + delta + 1) { 19933 subprogs[cur_subprog].stack_depth += stack_depth_extra; 19934 cur_subprog++; 19935 stack_depth = subprogs[cur_subprog].stack_depth; 19936 stack_depth_roundup = round_up(stack_depth, 8) - stack_depth; 19937 stack_depth_extra = 0; 19938 } 19939 } 19940 19941 env->prog->aux->stack_depth = env->subprog_info[0].stack_depth; 19942 19943 return 0; 19944 } 19945 19946 static void free_states(struct bpf_verifier_env *env) 19947 { 19948 struct bpf_verifier_state_list *sl, *sln; 19949 int i; 19950 19951 sl = env->free_list; 19952 while (sl) { 19953 sln = sl->next; 19954 free_verifier_state(&sl->state, false); 19955 kfree(sl); 19956 sl = sln; 19957 } 19958 env->free_list = NULL; 19959 19960 if (!env->explored_states) 19961 return; 19962 19963 for (i = 0; i < state_htab_size(env); i++) { 19964 sl = env->explored_states[i]; 19965 19966 while (sl) { 19967 sln = sl->next; 19968 free_verifier_state(&sl->state, false); 19969 kfree(sl); 19970 sl = sln; 19971 } 19972 env->explored_states[i] = NULL; 19973 } 19974 } 19975 19976 static int do_check_common(struct bpf_verifier_env *env, int subprog, bool is_ex_cb) 19977 { 19978 bool pop_log = !(env->log.level & BPF_LOG_LEVEL2); 19979 struct bpf_verifier_state *state; 19980 struct bpf_reg_state *regs; 19981 int ret, i; 19982 19983 env->prev_linfo = NULL; 19984 env->pass_cnt++; 19985 19986 state = kzalloc(sizeof(struct bpf_verifier_state), GFP_KERNEL); 19987 if (!state) 19988 return -ENOMEM; 19989 state->curframe = 0; 19990 state->speculative = false; 19991 state->branches = 1; 19992 state->frame[0] = kzalloc(sizeof(struct bpf_func_state), GFP_KERNEL); 19993 if (!state->frame[0]) { 19994 kfree(state); 19995 return -ENOMEM; 19996 } 19997 env->cur_state = state; 19998 init_func_state(env, state->frame[0], 19999 BPF_MAIN_FUNC /* callsite */, 20000 0 /* frameno */, 20001 subprog); 20002 state->first_insn_idx = env->subprog_info[subprog].start; 20003 state->last_insn_idx = -1; 20004 20005 regs = state->frame[state->curframe]->regs; 20006 if (subprog || env->prog->type == BPF_PROG_TYPE_EXT) { 20007 ret = btf_prepare_func_args(env, subprog, regs, is_ex_cb); 20008 if (ret) 20009 goto out; 20010 for (i = BPF_REG_1; i <= BPF_REG_5; i++) { 20011 if (regs[i].type == PTR_TO_CTX) 20012 mark_reg_known_zero(env, regs, i); 20013 else if (regs[i].type == SCALAR_VALUE) 20014 mark_reg_unknown(env, regs, i); 20015 else if (base_type(regs[i].type) == PTR_TO_MEM) { 20016 const u32 mem_size = regs[i].mem_size; 20017 20018 mark_reg_known_zero(env, regs, i); 20019 regs[i].mem_size = mem_size; 20020 regs[i].id = ++env->id_gen; 20021 } 20022 } 20023 if (is_ex_cb) { 20024 state->frame[0]->in_exception_callback_fn = true; 20025 env->subprog_info[subprog].is_cb = true; 20026 env->subprog_info[subprog].is_async_cb = true; 20027 env->subprog_info[subprog].is_exception_cb = true; 20028 } 20029 } else { 20030 /* 1st arg to a function */ 20031 regs[BPF_REG_1].type = PTR_TO_CTX; 20032 mark_reg_known_zero(env, regs, BPF_REG_1); 20033 ret = btf_check_subprog_arg_match(env, subprog, regs); 20034 if (ret == -EFAULT) 20035 /* unlikely verifier bug. abort. 20036 * ret == 0 and ret < 0 are sadly acceptable for 20037 * main() function due to backward compatibility. 20038 * Like socket filter program may be written as: 20039 * int bpf_prog(struct pt_regs *ctx) 20040 * and never dereference that ctx in the program. 20041 * 'struct pt_regs' is a type mismatch for socket 20042 * filter that should be using 'struct __sk_buff'. 20043 */ 20044 goto out; 20045 } 20046 20047 ret = do_check(env); 20048 out: 20049 /* check for NULL is necessary, since cur_state can be freed inside 20050 * do_check() under memory pressure. 20051 */ 20052 if (env->cur_state) { 20053 free_verifier_state(env->cur_state, true); 20054 env->cur_state = NULL; 20055 } 20056 while (!pop_stack(env, NULL, NULL, false)); 20057 if (!ret && pop_log) 20058 bpf_vlog_reset(&env->log, 0); 20059 free_states(env); 20060 return ret; 20061 } 20062 20063 /* Verify all global functions in a BPF program one by one based on their BTF. 20064 * All global functions must pass verification. Otherwise the whole program is rejected. 20065 * Consider: 20066 * int bar(int); 20067 * int foo(int f) 20068 * { 20069 * return bar(f); 20070 * } 20071 * int bar(int b) 20072 * { 20073 * ... 20074 * } 20075 * foo() will be verified first for R1=any_scalar_value. During verification it 20076 * will be assumed that bar() already verified successfully and call to bar() 20077 * from foo() will be checked for type match only. Later bar() will be verified 20078 * independently to check that it's safe for R1=any_scalar_value. 20079 */ 20080 static int do_check_subprogs(struct bpf_verifier_env *env) 20081 { 20082 struct bpf_prog_aux *aux = env->prog->aux; 20083 int i, ret; 20084 20085 if (!aux->func_info) 20086 return 0; 20087 20088 for (i = 1; i < env->subprog_cnt; i++) { 20089 if (aux->func_info_aux[i].linkage != BTF_FUNC_GLOBAL) 20090 continue; 20091 env->insn_idx = env->subprog_info[i].start; 20092 WARN_ON_ONCE(env->insn_idx == 0); 20093 ret = do_check_common(env, i, env->exception_callback_subprog == i); 20094 if (ret) { 20095 return ret; 20096 } else if (env->log.level & BPF_LOG_LEVEL) { 20097 verbose(env, 20098 "Func#%d is safe for any args that match its prototype\n", 20099 i); 20100 } 20101 } 20102 return 0; 20103 } 20104 20105 static int do_check_main(struct bpf_verifier_env *env) 20106 { 20107 int ret; 20108 20109 env->insn_idx = 0; 20110 ret = do_check_common(env, 0, false); 20111 if (!ret) 20112 env->prog->aux->stack_depth = env->subprog_info[0].stack_depth; 20113 return ret; 20114 } 20115 20116 20117 static void print_verification_stats(struct bpf_verifier_env *env) 20118 { 20119 int i; 20120 20121 if (env->log.level & BPF_LOG_STATS) { 20122 verbose(env, "verification time %lld usec\n", 20123 div_u64(env->verification_time, 1000)); 20124 verbose(env, "stack depth "); 20125 for (i = 0; i < env->subprog_cnt; i++) { 20126 u32 depth = env->subprog_info[i].stack_depth; 20127 20128 verbose(env, "%d", depth); 20129 if (i + 1 < env->subprog_cnt) 20130 verbose(env, "+"); 20131 } 20132 verbose(env, "\n"); 20133 } 20134 verbose(env, "processed %d insns (limit %d) max_states_per_insn %d " 20135 "total_states %d peak_states %d mark_read %d\n", 20136 env->insn_processed, BPF_COMPLEXITY_LIMIT_INSNS, 20137 env->max_states_per_insn, env->total_states, 20138 env->peak_states, env->longest_mark_read_walk); 20139 } 20140 20141 static int check_struct_ops_btf_id(struct bpf_verifier_env *env) 20142 { 20143 const struct btf_type *t, *func_proto; 20144 const struct bpf_struct_ops *st_ops; 20145 const struct btf_member *member; 20146 struct bpf_prog *prog = env->prog; 20147 u32 btf_id, member_idx; 20148 const char *mname; 20149 20150 if (!prog->gpl_compatible) { 20151 verbose(env, "struct ops programs must have a GPL compatible license\n"); 20152 return -EINVAL; 20153 } 20154 20155 btf_id = prog->aux->attach_btf_id; 20156 st_ops = bpf_struct_ops_find(btf_id); 20157 if (!st_ops) { 20158 verbose(env, "attach_btf_id %u is not a supported struct\n", 20159 btf_id); 20160 return -ENOTSUPP; 20161 } 20162 20163 t = st_ops->type; 20164 member_idx = prog->expected_attach_type; 20165 if (member_idx >= btf_type_vlen(t)) { 20166 verbose(env, "attach to invalid member idx %u of struct %s\n", 20167 member_idx, st_ops->name); 20168 return -EINVAL; 20169 } 20170 20171 member = &btf_type_member(t)[member_idx]; 20172 mname = btf_name_by_offset(btf_vmlinux, member->name_off); 20173 func_proto = btf_type_resolve_func_ptr(btf_vmlinux, member->type, 20174 NULL); 20175 if (!func_proto) { 20176 verbose(env, "attach to invalid member %s(@idx %u) of struct %s\n", 20177 mname, member_idx, st_ops->name); 20178 return -EINVAL; 20179 } 20180 20181 if (st_ops->check_member) { 20182 int err = st_ops->check_member(t, member, prog); 20183 20184 if (err) { 20185 verbose(env, "attach to unsupported member %s of struct %s\n", 20186 mname, st_ops->name); 20187 return err; 20188 } 20189 } 20190 20191 prog->aux->attach_func_proto = func_proto; 20192 prog->aux->attach_func_name = mname; 20193 env->ops = st_ops->verifier_ops; 20194 20195 return 0; 20196 } 20197 #define SECURITY_PREFIX "security_" 20198 20199 static int check_attach_modify_return(unsigned long addr, const char *func_name) 20200 { 20201 if (within_error_injection_list(addr) || 20202 !strncmp(SECURITY_PREFIX, func_name, sizeof(SECURITY_PREFIX) - 1)) 20203 return 0; 20204 20205 return -EINVAL; 20206 } 20207 20208 /* list of non-sleepable functions that are otherwise on 20209 * ALLOW_ERROR_INJECTION list 20210 */ 20211 BTF_SET_START(btf_non_sleepable_error_inject) 20212 /* Three functions below can be called from sleepable and non-sleepable context. 20213 * Assume non-sleepable from bpf safety point of view. 20214 */ 20215 BTF_ID(func, __filemap_add_folio) 20216 BTF_ID(func, should_fail_alloc_page) 20217 BTF_ID(func, should_failslab) 20218 BTF_SET_END(btf_non_sleepable_error_inject) 20219 20220 static int check_non_sleepable_error_inject(u32 btf_id) 20221 { 20222 return btf_id_set_contains(&btf_non_sleepable_error_inject, btf_id); 20223 } 20224 20225 int bpf_check_attach_target(struct bpf_verifier_log *log, 20226 const struct bpf_prog *prog, 20227 const struct bpf_prog *tgt_prog, 20228 u32 btf_id, 20229 struct bpf_attach_target_info *tgt_info) 20230 { 20231 bool prog_extension = prog->type == BPF_PROG_TYPE_EXT; 20232 const char prefix[] = "btf_trace_"; 20233 int ret = 0, subprog = -1, i; 20234 const struct btf_type *t; 20235 bool conservative = true; 20236 const char *tname; 20237 struct btf *btf; 20238 long addr = 0; 20239 struct module *mod = NULL; 20240 20241 if (!btf_id) { 20242 bpf_log(log, "Tracing programs must provide btf_id\n"); 20243 return -EINVAL; 20244 } 20245 btf = tgt_prog ? tgt_prog->aux->btf : prog->aux->attach_btf; 20246 if (!btf) { 20247 bpf_log(log, 20248 "FENTRY/FEXIT program can only be attached to another program annotated with BTF\n"); 20249 return -EINVAL; 20250 } 20251 t = btf_type_by_id(btf, btf_id); 20252 if (!t) { 20253 bpf_log(log, "attach_btf_id %u is invalid\n", btf_id); 20254 return -EINVAL; 20255 } 20256 tname = btf_name_by_offset(btf, t->name_off); 20257 if (!tname) { 20258 bpf_log(log, "attach_btf_id %u doesn't have a name\n", btf_id); 20259 return -EINVAL; 20260 } 20261 if (tgt_prog) { 20262 struct bpf_prog_aux *aux = tgt_prog->aux; 20263 20264 if (bpf_prog_is_dev_bound(prog->aux) && 20265 !bpf_prog_dev_bound_match(prog, tgt_prog)) { 20266 bpf_log(log, "Target program bound device mismatch"); 20267 return -EINVAL; 20268 } 20269 20270 for (i = 0; i < aux->func_info_cnt; i++) 20271 if (aux->func_info[i].type_id == btf_id) { 20272 subprog = i; 20273 break; 20274 } 20275 if (subprog == -1) { 20276 bpf_log(log, "Subprog %s doesn't exist\n", tname); 20277 return -EINVAL; 20278 } 20279 if (aux->func && aux->func[subprog]->aux->exception_cb) { 20280 bpf_log(log, 20281 "%s programs cannot attach to exception callback\n", 20282 prog_extension ? "Extension" : "FENTRY/FEXIT"); 20283 return -EINVAL; 20284 } 20285 conservative = aux->func_info_aux[subprog].unreliable; 20286 if (prog_extension) { 20287 if (conservative) { 20288 bpf_log(log, 20289 "Cannot replace static functions\n"); 20290 return -EINVAL; 20291 } 20292 if (!prog->jit_requested) { 20293 bpf_log(log, 20294 "Extension programs should be JITed\n"); 20295 return -EINVAL; 20296 } 20297 } 20298 if (!tgt_prog->jited) { 20299 bpf_log(log, "Can attach to only JITed progs\n"); 20300 return -EINVAL; 20301 } 20302 if (tgt_prog->type == prog->type) { 20303 /* Cannot fentry/fexit another fentry/fexit program. 20304 * Cannot attach program extension to another extension. 20305 * It's ok to attach fentry/fexit to extension program. 20306 */ 20307 bpf_log(log, "Cannot recursively attach\n"); 20308 return -EINVAL; 20309 } 20310 if (tgt_prog->type == BPF_PROG_TYPE_TRACING && 20311 prog_extension && 20312 (tgt_prog->expected_attach_type == BPF_TRACE_FENTRY || 20313 tgt_prog->expected_attach_type == BPF_TRACE_FEXIT)) { 20314 /* Program extensions can extend all program types 20315 * except fentry/fexit. The reason is the following. 20316 * The fentry/fexit programs are used for performance 20317 * analysis, stats and can be attached to any program 20318 * type except themselves. When extension program is 20319 * replacing XDP function it is necessary to allow 20320 * performance analysis of all functions. Both original 20321 * XDP program and its program extension. Hence 20322 * attaching fentry/fexit to BPF_PROG_TYPE_EXT is 20323 * allowed. If extending of fentry/fexit was allowed it 20324 * would be possible to create long call chain 20325 * fentry->extension->fentry->extension beyond 20326 * reasonable stack size. Hence extending fentry is not 20327 * allowed. 20328 */ 20329 bpf_log(log, "Cannot extend fentry/fexit\n"); 20330 return -EINVAL; 20331 } 20332 } else { 20333 if (prog_extension) { 20334 bpf_log(log, "Cannot replace kernel functions\n"); 20335 return -EINVAL; 20336 } 20337 } 20338 20339 switch (prog->expected_attach_type) { 20340 case BPF_TRACE_RAW_TP: 20341 if (tgt_prog) { 20342 bpf_log(log, 20343 "Only FENTRY/FEXIT progs are attachable to another BPF prog\n"); 20344 return -EINVAL; 20345 } 20346 if (!btf_type_is_typedef(t)) { 20347 bpf_log(log, "attach_btf_id %u is not a typedef\n", 20348 btf_id); 20349 return -EINVAL; 20350 } 20351 if (strncmp(prefix, tname, sizeof(prefix) - 1)) { 20352 bpf_log(log, "attach_btf_id %u points to wrong type name %s\n", 20353 btf_id, tname); 20354 return -EINVAL; 20355 } 20356 tname += sizeof(prefix) - 1; 20357 t = btf_type_by_id(btf, t->type); 20358 if (!btf_type_is_ptr(t)) 20359 /* should never happen in valid vmlinux build */ 20360 return -EINVAL; 20361 t = btf_type_by_id(btf, t->type); 20362 if (!btf_type_is_func_proto(t)) 20363 /* should never happen in valid vmlinux build */ 20364 return -EINVAL; 20365 20366 break; 20367 case BPF_TRACE_ITER: 20368 if (!btf_type_is_func(t)) { 20369 bpf_log(log, "attach_btf_id %u is not a function\n", 20370 btf_id); 20371 return -EINVAL; 20372 } 20373 t = btf_type_by_id(btf, t->type); 20374 if (!btf_type_is_func_proto(t)) 20375 return -EINVAL; 20376 ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel); 20377 if (ret) 20378 return ret; 20379 break; 20380 default: 20381 if (!prog_extension) 20382 return -EINVAL; 20383 fallthrough; 20384 case BPF_MODIFY_RETURN: 20385 case BPF_LSM_MAC: 20386 case BPF_LSM_CGROUP: 20387 case BPF_TRACE_FENTRY: 20388 case BPF_TRACE_FEXIT: 20389 if (!btf_type_is_func(t)) { 20390 bpf_log(log, "attach_btf_id %u is not a function\n", 20391 btf_id); 20392 return -EINVAL; 20393 } 20394 if (prog_extension && 20395 btf_check_type_match(log, prog, btf, t)) 20396 return -EINVAL; 20397 t = btf_type_by_id(btf, t->type); 20398 if (!btf_type_is_func_proto(t)) 20399 return -EINVAL; 20400 20401 if ((prog->aux->saved_dst_prog_type || prog->aux->saved_dst_attach_type) && 20402 (!tgt_prog || prog->aux->saved_dst_prog_type != tgt_prog->type || 20403 prog->aux->saved_dst_attach_type != tgt_prog->expected_attach_type)) 20404 return -EINVAL; 20405 20406 if (tgt_prog && conservative) 20407 t = NULL; 20408 20409 ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel); 20410 if (ret < 0) 20411 return ret; 20412 20413 if (tgt_prog) { 20414 if (subprog == 0) 20415 addr = (long) tgt_prog->bpf_func; 20416 else 20417 addr = (long) tgt_prog->aux->func[subprog]->bpf_func; 20418 } else { 20419 if (btf_is_module(btf)) { 20420 mod = btf_try_get_module(btf); 20421 if (mod) 20422 addr = find_kallsyms_symbol_value(mod, tname); 20423 else 20424 addr = 0; 20425 } else { 20426 addr = kallsyms_lookup_name(tname); 20427 } 20428 if (!addr) { 20429 module_put(mod); 20430 bpf_log(log, 20431 "The address of function %s cannot be found\n", 20432 tname); 20433 return -ENOENT; 20434 } 20435 } 20436 20437 if (prog->aux->sleepable) { 20438 ret = -EINVAL; 20439 switch (prog->type) { 20440 case BPF_PROG_TYPE_TRACING: 20441 20442 /* fentry/fexit/fmod_ret progs can be sleepable if they are 20443 * attached to ALLOW_ERROR_INJECTION and are not in denylist. 20444 */ 20445 if (!check_non_sleepable_error_inject(btf_id) && 20446 within_error_injection_list(addr)) 20447 ret = 0; 20448 /* fentry/fexit/fmod_ret progs can also be sleepable if they are 20449 * in the fmodret id set with the KF_SLEEPABLE flag. 20450 */ 20451 else { 20452 u32 *flags = btf_kfunc_is_modify_return(btf, btf_id, 20453 prog); 20454 20455 if (flags && (*flags & KF_SLEEPABLE)) 20456 ret = 0; 20457 } 20458 break; 20459 case BPF_PROG_TYPE_LSM: 20460 /* LSM progs check that they are attached to bpf_lsm_*() funcs. 20461 * Only some of them are sleepable. 20462 */ 20463 if (bpf_lsm_is_sleepable_hook(btf_id)) 20464 ret = 0; 20465 break; 20466 default: 20467 break; 20468 } 20469 if (ret) { 20470 module_put(mod); 20471 bpf_log(log, "%s is not sleepable\n", tname); 20472 return ret; 20473 } 20474 } else if (prog->expected_attach_type == BPF_MODIFY_RETURN) { 20475 if (tgt_prog) { 20476 module_put(mod); 20477 bpf_log(log, "can't modify return codes of BPF programs\n"); 20478 return -EINVAL; 20479 } 20480 ret = -EINVAL; 20481 if (btf_kfunc_is_modify_return(btf, btf_id, prog) || 20482 !check_attach_modify_return(addr, tname)) 20483 ret = 0; 20484 if (ret) { 20485 module_put(mod); 20486 bpf_log(log, "%s() is not modifiable\n", tname); 20487 return ret; 20488 } 20489 } 20490 20491 break; 20492 } 20493 tgt_info->tgt_addr = addr; 20494 tgt_info->tgt_name = tname; 20495 tgt_info->tgt_type = t; 20496 tgt_info->tgt_mod = mod; 20497 return 0; 20498 } 20499 20500 BTF_SET_START(btf_id_deny) 20501 BTF_ID_UNUSED 20502 #ifdef CONFIG_SMP 20503 BTF_ID(func, migrate_disable) 20504 BTF_ID(func, migrate_enable) 20505 #endif 20506 #if !defined CONFIG_PREEMPT_RCU && !defined CONFIG_TINY_RCU 20507 BTF_ID(func, rcu_read_unlock_strict) 20508 #endif 20509 #if defined(CONFIG_DEBUG_PREEMPT) || defined(CONFIG_TRACE_PREEMPT_TOGGLE) 20510 BTF_ID(func, preempt_count_add) 20511 BTF_ID(func, preempt_count_sub) 20512 #endif 20513 #ifdef CONFIG_PREEMPT_RCU 20514 BTF_ID(func, __rcu_read_lock) 20515 BTF_ID(func, __rcu_read_unlock) 20516 #endif 20517 BTF_SET_END(btf_id_deny) 20518 20519 static bool can_be_sleepable(struct bpf_prog *prog) 20520 { 20521 if (prog->type == BPF_PROG_TYPE_TRACING) { 20522 switch (prog->expected_attach_type) { 20523 case BPF_TRACE_FENTRY: 20524 case BPF_TRACE_FEXIT: 20525 case BPF_MODIFY_RETURN: 20526 case BPF_TRACE_ITER: 20527 return true; 20528 default: 20529 return false; 20530 } 20531 } 20532 return prog->type == BPF_PROG_TYPE_LSM || 20533 prog->type == BPF_PROG_TYPE_KPROBE /* only for uprobes */ || 20534 prog->type == BPF_PROG_TYPE_STRUCT_OPS; 20535 } 20536 20537 static int check_attach_btf_id(struct bpf_verifier_env *env) 20538 { 20539 struct bpf_prog *prog = env->prog; 20540 struct bpf_prog *tgt_prog = prog->aux->dst_prog; 20541 struct bpf_attach_target_info tgt_info = {}; 20542 u32 btf_id = prog->aux->attach_btf_id; 20543 struct bpf_trampoline *tr; 20544 int ret; 20545 u64 key; 20546 20547 if (prog->type == BPF_PROG_TYPE_SYSCALL) { 20548 if (prog->aux->sleepable) 20549 /* attach_btf_id checked to be zero already */ 20550 return 0; 20551 verbose(env, "Syscall programs can only be sleepable\n"); 20552 return -EINVAL; 20553 } 20554 20555 if (prog->aux->sleepable && !can_be_sleepable(prog)) { 20556 verbose(env, "Only fentry/fexit/fmod_ret, lsm, iter, uprobe, and struct_ops programs can be sleepable\n"); 20557 return -EINVAL; 20558 } 20559 20560 if (prog->type == BPF_PROG_TYPE_STRUCT_OPS) 20561 return check_struct_ops_btf_id(env); 20562 20563 if (prog->type != BPF_PROG_TYPE_TRACING && 20564 prog->type != BPF_PROG_TYPE_LSM && 20565 prog->type != BPF_PROG_TYPE_EXT) 20566 return 0; 20567 20568 ret = bpf_check_attach_target(&env->log, prog, tgt_prog, btf_id, &tgt_info); 20569 if (ret) 20570 return ret; 20571 20572 if (tgt_prog && prog->type == BPF_PROG_TYPE_EXT) { 20573 /* to make freplace equivalent to their targets, they need to 20574 * inherit env->ops and expected_attach_type for the rest of the 20575 * verification 20576 */ 20577 env->ops = bpf_verifier_ops[tgt_prog->type]; 20578 prog->expected_attach_type = tgt_prog->expected_attach_type; 20579 } 20580 20581 /* store info about the attachment target that will be used later */ 20582 prog->aux->attach_func_proto = tgt_info.tgt_type; 20583 prog->aux->attach_func_name = tgt_info.tgt_name; 20584 prog->aux->mod = tgt_info.tgt_mod; 20585 20586 if (tgt_prog) { 20587 prog->aux->saved_dst_prog_type = tgt_prog->type; 20588 prog->aux->saved_dst_attach_type = tgt_prog->expected_attach_type; 20589 } 20590 20591 if (prog->expected_attach_type == BPF_TRACE_RAW_TP) { 20592 prog->aux->attach_btf_trace = true; 20593 return 0; 20594 } else if (prog->expected_attach_type == BPF_TRACE_ITER) { 20595 if (!bpf_iter_prog_supported(prog)) 20596 return -EINVAL; 20597 return 0; 20598 } 20599 20600 if (prog->type == BPF_PROG_TYPE_LSM) { 20601 ret = bpf_lsm_verify_prog(&env->log, prog); 20602 if (ret < 0) 20603 return ret; 20604 } else if (prog->type == BPF_PROG_TYPE_TRACING && 20605 btf_id_set_contains(&btf_id_deny, btf_id)) { 20606 return -EINVAL; 20607 } 20608 20609 key = bpf_trampoline_compute_key(tgt_prog, prog->aux->attach_btf, btf_id); 20610 tr = bpf_trampoline_get(key, &tgt_info); 20611 if (!tr) 20612 return -ENOMEM; 20613 20614 if (tgt_prog && tgt_prog->aux->tail_call_reachable) 20615 tr->flags = BPF_TRAMP_F_TAIL_CALL_CTX; 20616 20617 prog->aux->dst_trampoline = tr; 20618 return 0; 20619 } 20620 20621 struct btf *bpf_get_btf_vmlinux(void) 20622 { 20623 if (!btf_vmlinux && IS_ENABLED(CONFIG_DEBUG_INFO_BTF)) { 20624 mutex_lock(&bpf_verifier_lock); 20625 if (!btf_vmlinux) 20626 btf_vmlinux = btf_parse_vmlinux(); 20627 mutex_unlock(&bpf_verifier_lock); 20628 } 20629 return btf_vmlinux; 20630 } 20631 20632 int bpf_check(struct bpf_prog **prog, union bpf_attr *attr, bpfptr_t uattr, __u32 uattr_size) 20633 { 20634 u64 start_time = ktime_get_ns(); 20635 struct bpf_verifier_env *env; 20636 int i, len, ret = -EINVAL, err; 20637 u32 log_true_size; 20638 bool is_priv; 20639 20640 /* no program is valid */ 20641 if (ARRAY_SIZE(bpf_verifier_ops) == 0) 20642 return -EINVAL; 20643 20644 /* 'struct bpf_verifier_env' can be global, but since it's not small, 20645 * allocate/free it every time bpf_check() is called 20646 */ 20647 env = kzalloc(sizeof(struct bpf_verifier_env), GFP_KERNEL); 20648 if (!env) 20649 return -ENOMEM; 20650 20651 env->bt.env = env; 20652 20653 len = (*prog)->len; 20654 env->insn_aux_data = 20655 vzalloc(array_size(sizeof(struct bpf_insn_aux_data), len)); 20656 ret = -ENOMEM; 20657 if (!env->insn_aux_data) 20658 goto err_free_env; 20659 for (i = 0; i < len; i++) 20660 env->insn_aux_data[i].orig_idx = i; 20661 env->prog = *prog; 20662 env->ops = bpf_verifier_ops[env->prog->type]; 20663 env->fd_array = make_bpfptr(attr->fd_array, uattr.is_kernel); 20664 is_priv = bpf_capable(); 20665 20666 bpf_get_btf_vmlinux(); 20667 20668 /* grab the mutex to protect few globals used by verifier */ 20669 if (!is_priv) 20670 mutex_lock(&bpf_verifier_lock); 20671 20672 /* user could have requested verbose verifier output 20673 * and supplied buffer to store the verification trace 20674 */ 20675 ret = bpf_vlog_init(&env->log, attr->log_level, 20676 (char __user *) (unsigned long) attr->log_buf, 20677 attr->log_size); 20678 if (ret) 20679 goto err_unlock; 20680 20681 mark_verifier_state_clean(env); 20682 20683 if (IS_ERR(btf_vmlinux)) { 20684 /* Either gcc or pahole or kernel are broken. */ 20685 verbose(env, "in-kernel BTF is malformed\n"); 20686 ret = PTR_ERR(btf_vmlinux); 20687 goto skip_full_check; 20688 } 20689 20690 env->strict_alignment = !!(attr->prog_flags & BPF_F_STRICT_ALIGNMENT); 20691 if (!IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS)) 20692 env->strict_alignment = true; 20693 if (attr->prog_flags & BPF_F_ANY_ALIGNMENT) 20694 env->strict_alignment = false; 20695 20696 env->allow_ptr_leaks = bpf_allow_ptr_leaks(); 20697 env->allow_uninit_stack = bpf_allow_uninit_stack(); 20698 env->bypass_spec_v1 = bpf_bypass_spec_v1(); 20699 env->bypass_spec_v4 = bpf_bypass_spec_v4(); 20700 env->bpf_capable = bpf_capable(); 20701 20702 if (is_priv) 20703 env->test_state_freq = attr->prog_flags & BPF_F_TEST_STATE_FREQ; 20704 20705 env->explored_states = kvcalloc(state_htab_size(env), 20706 sizeof(struct bpf_verifier_state_list *), 20707 GFP_USER); 20708 ret = -ENOMEM; 20709 if (!env->explored_states) 20710 goto skip_full_check; 20711 20712 ret = check_btf_info_early(env, attr, uattr); 20713 if (ret < 0) 20714 goto skip_full_check; 20715 20716 ret = add_subprog_and_kfunc(env); 20717 if (ret < 0) 20718 goto skip_full_check; 20719 20720 ret = check_subprogs(env); 20721 if (ret < 0) 20722 goto skip_full_check; 20723 20724 ret = check_btf_info(env, attr, uattr); 20725 if (ret < 0) 20726 goto skip_full_check; 20727 20728 ret = check_attach_btf_id(env); 20729 if (ret) 20730 goto skip_full_check; 20731 20732 ret = resolve_pseudo_ldimm64(env); 20733 if (ret < 0) 20734 goto skip_full_check; 20735 20736 if (bpf_prog_is_offloaded(env->prog->aux)) { 20737 ret = bpf_prog_offload_verifier_prep(env->prog); 20738 if (ret) 20739 goto skip_full_check; 20740 } 20741 20742 ret = check_cfg(env); 20743 if (ret < 0) 20744 goto skip_full_check; 20745 20746 ret = do_check_subprogs(env); 20747 ret = ret ?: do_check_main(env); 20748 20749 if (ret == 0 && bpf_prog_is_offloaded(env->prog->aux)) 20750 ret = bpf_prog_offload_finalize(env); 20751 20752 skip_full_check: 20753 kvfree(env->explored_states); 20754 20755 if (ret == 0) 20756 ret = check_max_stack_depth(env); 20757 20758 /* instruction rewrites happen after this point */ 20759 if (ret == 0) 20760 ret = optimize_bpf_loop(env); 20761 20762 if (is_priv) { 20763 if (ret == 0) 20764 opt_hard_wire_dead_code_branches(env); 20765 if (ret == 0) 20766 ret = opt_remove_dead_code(env); 20767 if (ret == 0) 20768 ret = opt_remove_nops(env); 20769 } else { 20770 if (ret == 0) 20771 sanitize_dead_code(env); 20772 } 20773 20774 if (ret == 0) 20775 /* program is valid, convert *(u32*)(ctx + off) accesses */ 20776 ret = convert_ctx_accesses(env); 20777 20778 if (ret == 0) 20779 ret = do_misc_fixups(env); 20780 20781 /* do 32-bit optimization after insn patching has done so those patched 20782 * insns could be handled correctly. 20783 */ 20784 if (ret == 0 && !bpf_prog_is_offloaded(env->prog->aux)) { 20785 ret = opt_subreg_zext_lo32_rnd_hi32(env, attr); 20786 env->prog->aux->verifier_zext = bpf_jit_needs_zext() ? !ret 20787 : false; 20788 } 20789 20790 if (ret == 0) 20791 ret = fixup_call_args(env); 20792 20793 env->verification_time = ktime_get_ns() - start_time; 20794 print_verification_stats(env); 20795 env->prog->aux->verified_insns = env->insn_processed; 20796 20797 /* preserve original error even if log finalization is successful */ 20798 err = bpf_vlog_finalize(&env->log, &log_true_size); 20799 if (err) 20800 ret = err; 20801 20802 if (uattr_size >= offsetofend(union bpf_attr, log_true_size) && 20803 copy_to_bpfptr_offset(uattr, offsetof(union bpf_attr, log_true_size), 20804 &log_true_size, sizeof(log_true_size))) { 20805 ret = -EFAULT; 20806 goto err_release_maps; 20807 } 20808 20809 if (ret) 20810 goto err_release_maps; 20811 20812 if (env->used_map_cnt) { 20813 /* if program passed verifier, update used_maps in bpf_prog_info */ 20814 env->prog->aux->used_maps = kmalloc_array(env->used_map_cnt, 20815 sizeof(env->used_maps[0]), 20816 GFP_KERNEL); 20817 20818 if (!env->prog->aux->used_maps) { 20819 ret = -ENOMEM; 20820 goto err_release_maps; 20821 } 20822 20823 memcpy(env->prog->aux->used_maps, env->used_maps, 20824 sizeof(env->used_maps[0]) * env->used_map_cnt); 20825 env->prog->aux->used_map_cnt = env->used_map_cnt; 20826 } 20827 if (env->used_btf_cnt) { 20828 /* if program passed verifier, update used_btfs in bpf_prog_aux */ 20829 env->prog->aux->used_btfs = kmalloc_array(env->used_btf_cnt, 20830 sizeof(env->used_btfs[0]), 20831 GFP_KERNEL); 20832 if (!env->prog->aux->used_btfs) { 20833 ret = -ENOMEM; 20834 goto err_release_maps; 20835 } 20836 20837 memcpy(env->prog->aux->used_btfs, env->used_btfs, 20838 sizeof(env->used_btfs[0]) * env->used_btf_cnt); 20839 env->prog->aux->used_btf_cnt = env->used_btf_cnt; 20840 } 20841 if (env->used_map_cnt || env->used_btf_cnt) { 20842 /* program is valid. Convert pseudo bpf_ld_imm64 into generic 20843 * bpf_ld_imm64 instructions 20844 */ 20845 convert_pseudo_ld_imm64(env); 20846 } 20847 20848 adjust_btf_func(env); 20849 20850 err_release_maps: 20851 if (!env->prog->aux->used_maps) 20852 /* if we didn't copy map pointers into bpf_prog_info, release 20853 * them now. Otherwise free_used_maps() will release them. 20854 */ 20855 release_maps(env); 20856 if (!env->prog->aux->used_btfs) 20857 release_btfs(env); 20858 20859 /* extension progs temporarily inherit the attach_type of their targets 20860 for verification purposes, so set it back to zero before returning 20861 */ 20862 if (env->prog->type == BPF_PROG_TYPE_EXT) 20863 env->prog->expected_attach_type = 0; 20864 20865 *prog = env->prog; 20866 err_unlock: 20867 if (!is_priv) 20868 mutex_unlock(&bpf_verifier_lock); 20869 vfree(env->insn_aux_data); 20870 err_free_env: 20871 kfree(env); 20872 return ret; 20873 } 20874