1 // SPDX-License-Identifier: GPL-2.0-only 2 /* Copyright (c) 2011-2014 PLUMgrid, http://plumgrid.com 3 * Copyright (c) 2016 Facebook 4 * Copyright (c) 2018 Covalent IO, Inc. http://covalent.io 5 */ 6 #include <uapi/linux/btf.h> 7 #include <linux/bpf-cgroup.h> 8 #include <linux/kernel.h> 9 #include <linux/types.h> 10 #include <linux/slab.h> 11 #include <linux/bpf.h> 12 #include <linux/btf.h> 13 #include <linux/bpf_verifier.h> 14 #include <linux/filter.h> 15 #include <net/netlink.h> 16 #include <linux/file.h> 17 #include <linux/vmalloc.h> 18 #include <linux/stringify.h> 19 #include <linux/bsearch.h> 20 #include <linux/sort.h> 21 #include <linux/perf_event.h> 22 #include <linux/ctype.h> 23 #include <linux/error-injection.h> 24 #include <linux/bpf_lsm.h> 25 #include <linux/btf_ids.h> 26 #include <linux/poison.h> 27 #include <linux/module.h> 28 #include <linux/cpumask.h> 29 #include <net/xdp.h> 30 31 #include "disasm.h" 32 33 static const struct bpf_verifier_ops * const bpf_verifier_ops[] = { 34 #define BPF_PROG_TYPE(_id, _name, prog_ctx_type, kern_ctx_type) \ 35 [_id] = & _name ## _verifier_ops, 36 #define BPF_MAP_TYPE(_id, _ops) 37 #define BPF_LINK_TYPE(_id, _name) 38 #include <linux/bpf_types.h> 39 #undef BPF_PROG_TYPE 40 #undef BPF_MAP_TYPE 41 #undef BPF_LINK_TYPE 42 }; 43 44 /* bpf_check() is a static code analyzer that walks eBPF program 45 * instruction by instruction and updates register/stack state. 46 * All paths of conditional branches are analyzed until 'bpf_exit' insn. 47 * 48 * The first pass is depth-first-search to check that the program is a DAG. 49 * It rejects the following programs: 50 * - larger than BPF_MAXINSNS insns 51 * - if loop is present (detected via back-edge) 52 * - unreachable insns exist (shouldn't be a forest. program = one function) 53 * - out of bounds or malformed jumps 54 * The second pass is all possible path descent from the 1st insn. 55 * Since it's analyzing all paths through the program, the length of the 56 * analysis is limited to 64k insn, which may be hit even if total number of 57 * insn is less then 4K, but there are too many branches that change stack/regs. 58 * Number of 'branches to be analyzed' is limited to 1k 59 * 60 * On entry to each instruction, each register has a type, and the instruction 61 * changes the types of the registers depending on instruction semantics. 62 * If instruction is BPF_MOV64_REG(BPF_REG_1, BPF_REG_5), then type of R5 is 63 * copied to R1. 64 * 65 * All registers are 64-bit. 66 * R0 - return register 67 * R1-R5 argument passing registers 68 * R6-R9 callee saved registers 69 * R10 - frame pointer read-only 70 * 71 * At the start of BPF program the register R1 contains a pointer to bpf_context 72 * and has type PTR_TO_CTX. 73 * 74 * Verifier tracks arithmetic operations on pointers in case: 75 * BPF_MOV64_REG(BPF_REG_1, BPF_REG_10), 76 * BPF_ALU64_IMM(BPF_ADD, BPF_REG_1, -20), 77 * 1st insn copies R10 (which has FRAME_PTR) type into R1 78 * and 2nd arithmetic instruction is pattern matched to recognize 79 * that it wants to construct a pointer to some element within stack. 80 * So after 2nd insn, the register R1 has type PTR_TO_STACK 81 * (and -20 constant is saved for further stack bounds checking). 82 * Meaning that this reg is a pointer to stack plus known immediate constant. 83 * 84 * Most of the time the registers have SCALAR_VALUE type, which 85 * means the register has some value, but it's not a valid pointer. 86 * (like pointer plus pointer becomes SCALAR_VALUE type) 87 * 88 * When verifier sees load or store instructions the type of base register 89 * can be: PTR_TO_MAP_VALUE, PTR_TO_CTX, PTR_TO_STACK, PTR_TO_SOCKET. These are 90 * four pointer types recognized by check_mem_access() function. 91 * 92 * PTR_TO_MAP_VALUE means that this register is pointing to 'map element value' 93 * and the range of [ptr, ptr + map's value_size) is accessible. 94 * 95 * registers used to pass values to function calls are checked against 96 * function argument constraints. 97 * 98 * ARG_PTR_TO_MAP_KEY is one of such argument constraints. 99 * It means that the register type passed to this function must be 100 * PTR_TO_STACK and it will be used inside the function as 101 * 'pointer to map element key' 102 * 103 * For example the argument constraints for bpf_map_lookup_elem(): 104 * .ret_type = RET_PTR_TO_MAP_VALUE_OR_NULL, 105 * .arg1_type = ARG_CONST_MAP_PTR, 106 * .arg2_type = ARG_PTR_TO_MAP_KEY, 107 * 108 * ret_type says that this function returns 'pointer to map elem value or null' 109 * function expects 1st argument to be a const pointer to 'struct bpf_map' and 110 * 2nd argument should be a pointer to stack, which will be used inside 111 * the helper function as a pointer to map element key. 112 * 113 * On the kernel side the helper function looks like: 114 * u64 bpf_map_lookup_elem(u64 r1, u64 r2, u64 r3, u64 r4, u64 r5) 115 * { 116 * struct bpf_map *map = (struct bpf_map *) (unsigned long) r1; 117 * void *key = (void *) (unsigned long) r2; 118 * void *value; 119 * 120 * here kernel can access 'key' and 'map' pointers safely, knowing that 121 * [key, key + map->key_size) bytes are valid and were initialized on 122 * the stack of eBPF program. 123 * } 124 * 125 * Corresponding eBPF program may look like: 126 * BPF_MOV64_REG(BPF_REG_2, BPF_REG_10), // after this insn R2 type is FRAME_PTR 127 * BPF_ALU64_IMM(BPF_ADD, BPF_REG_2, -4), // after this insn R2 type is PTR_TO_STACK 128 * BPF_LD_MAP_FD(BPF_REG_1, map_fd), // after this insn R1 type is CONST_PTR_TO_MAP 129 * BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0, BPF_FUNC_map_lookup_elem), 130 * here verifier looks at prototype of map_lookup_elem() and sees: 131 * .arg1_type == ARG_CONST_MAP_PTR and R1->type == CONST_PTR_TO_MAP, which is ok, 132 * Now verifier knows that this map has key of R1->map_ptr->key_size bytes 133 * 134 * Then .arg2_type == ARG_PTR_TO_MAP_KEY and R2->type == PTR_TO_STACK, ok so far, 135 * Now verifier checks that [R2, R2 + map's key_size) are within stack limits 136 * and were initialized prior to this call. 137 * If it's ok, then verifier allows this BPF_CALL insn and looks at 138 * .ret_type which is RET_PTR_TO_MAP_VALUE_OR_NULL, so it sets 139 * R0->type = PTR_TO_MAP_VALUE_OR_NULL which means bpf_map_lookup_elem() function 140 * returns either pointer to map value or NULL. 141 * 142 * When type PTR_TO_MAP_VALUE_OR_NULL passes through 'if (reg != 0) goto +off' 143 * insn, the register holding that pointer in the true branch changes state to 144 * PTR_TO_MAP_VALUE and the same register changes state to CONST_IMM in the false 145 * branch. See check_cond_jmp_op(). 146 * 147 * After the call R0 is set to return type of the function and registers R1-R5 148 * are set to NOT_INIT to indicate that they are no longer readable. 149 * 150 * The following reference types represent a potential reference to a kernel 151 * resource which, after first being allocated, must be checked and freed by 152 * the BPF program: 153 * - PTR_TO_SOCKET_OR_NULL, PTR_TO_SOCKET 154 * 155 * When the verifier sees a helper call return a reference type, it allocates a 156 * pointer id for the reference and stores it in the current function state. 157 * Similar to the way that PTR_TO_MAP_VALUE_OR_NULL is converted into 158 * PTR_TO_MAP_VALUE, PTR_TO_SOCKET_OR_NULL becomes PTR_TO_SOCKET when the type 159 * passes through a NULL-check conditional. For the branch wherein the state is 160 * changed to CONST_IMM, the verifier releases the reference. 161 * 162 * For each helper function that allocates a reference, such as 163 * bpf_sk_lookup_tcp(), there is a corresponding release function, such as 164 * bpf_sk_release(). When a reference type passes into the release function, 165 * the verifier also releases the reference. If any unchecked or unreleased 166 * reference remains at the end of the program, the verifier rejects it. 167 */ 168 169 /* verifier_state + insn_idx are pushed to stack when branch is encountered */ 170 struct bpf_verifier_stack_elem { 171 /* verifer state is 'st' 172 * before processing instruction 'insn_idx' 173 * and after processing instruction 'prev_insn_idx' 174 */ 175 struct bpf_verifier_state st; 176 int insn_idx; 177 int prev_insn_idx; 178 struct bpf_verifier_stack_elem *next; 179 /* length of verifier log at the time this state was pushed on stack */ 180 u32 log_pos; 181 }; 182 183 #define BPF_COMPLEXITY_LIMIT_JMP_SEQ 8192 184 #define BPF_COMPLEXITY_LIMIT_STATES 64 185 186 #define BPF_MAP_KEY_POISON (1ULL << 63) 187 #define BPF_MAP_KEY_SEEN (1ULL << 62) 188 189 #define BPF_MAP_PTR_UNPRIV 1UL 190 #define BPF_MAP_PTR_POISON ((void *)((0xeB9FUL << 1) + \ 191 POISON_POINTER_DELTA)) 192 #define BPF_MAP_PTR(X) ((struct bpf_map *)((X) & ~BPF_MAP_PTR_UNPRIV)) 193 194 static int acquire_reference_state(struct bpf_verifier_env *env, int insn_idx); 195 static int release_reference(struct bpf_verifier_env *env, int ref_obj_id); 196 static void invalidate_non_owning_refs(struct bpf_verifier_env *env); 197 static bool in_rbtree_lock_required_cb(struct bpf_verifier_env *env); 198 static int ref_set_non_owning(struct bpf_verifier_env *env, 199 struct bpf_reg_state *reg); 200 static void specialize_kfunc(struct bpf_verifier_env *env, 201 u32 func_id, u16 offset, unsigned long *addr); 202 static bool is_trusted_reg(const struct bpf_reg_state *reg); 203 204 static bool bpf_map_ptr_poisoned(const struct bpf_insn_aux_data *aux) 205 { 206 return BPF_MAP_PTR(aux->map_ptr_state) == BPF_MAP_PTR_POISON; 207 } 208 209 static bool bpf_map_ptr_unpriv(const struct bpf_insn_aux_data *aux) 210 { 211 return aux->map_ptr_state & BPF_MAP_PTR_UNPRIV; 212 } 213 214 static void bpf_map_ptr_store(struct bpf_insn_aux_data *aux, 215 const struct bpf_map *map, bool unpriv) 216 { 217 BUILD_BUG_ON((unsigned long)BPF_MAP_PTR_POISON & BPF_MAP_PTR_UNPRIV); 218 unpriv |= bpf_map_ptr_unpriv(aux); 219 aux->map_ptr_state = (unsigned long)map | 220 (unpriv ? BPF_MAP_PTR_UNPRIV : 0UL); 221 } 222 223 static bool bpf_map_key_poisoned(const struct bpf_insn_aux_data *aux) 224 { 225 return aux->map_key_state & BPF_MAP_KEY_POISON; 226 } 227 228 static bool bpf_map_key_unseen(const struct bpf_insn_aux_data *aux) 229 { 230 return !(aux->map_key_state & BPF_MAP_KEY_SEEN); 231 } 232 233 static u64 bpf_map_key_immediate(const struct bpf_insn_aux_data *aux) 234 { 235 return aux->map_key_state & ~(BPF_MAP_KEY_SEEN | BPF_MAP_KEY_POISON); 236 } 237 238 static void bpf_map_key_store(struct bpf_insn_aux_data *aux, u64 state) 239 { 240 bool poisoned = bpf_map_key_poisoned(aux); 241 242 aux->map_key_state = state | BPF_MAP_KEY_SEEN | 243 (poisoned ? BPF_MAP_KEY_POISON : 0ULL); 244 } 245 246 static bool bpf_helper_call(const struct bpf_insn *insn) 247 { 248 return insn->code == (BPF_JMP | BPF_CALL) && 249 insn->src_reg == 0; 250 } 251 252 static bool bpf_pseudo_call(const struct bpf_insn *insn) 253 { 254 return insn->code == (BPF_JMP | BPF_CALL) && 255 insn->src_reg == BPF_PSEUDO_CALL; 256 } 257 258 static bool bpf_pseudo_kfunc_call(const struct bpf_insn *insn) 259 { 260 return insn->code == (BPF_JMP | BPF_CALL) && 261 insn->src_reg == BPF_PSEUDO_KFUNC_CALL; 262 } 263 264 struct bpf_call_arg_meta { 265 struct bpf_map *map_ptr; 266 bool raw_mode; 267 bool pkt_access; 268 u8 release_regno; 269 int regno; 270 int access_size; 271 int mem_size; 272 u64 msize_max_value; 273 int ref_obj_id; 274 int dynptr_id; 275 int map_uid; 276 int func_id; 277 struct btf *btf; 278 u32 btf_id; 279 struct btf *ret_btf; 280 u32 ret_btf_id; 281 u32 subprogno; 282 struct btf_field *kptr_field; 283 }; 284 285 struct bpf_kfunc_call_arg_meta { 286 /* In parameters */ 287 struct btf *btf; 288 u32 func_id; 289 u32 kfunc_flags; 290 const struct btf_type *func_proto; 291 const char *func_name; 292 /* Out parameters */ 293 u32 ref_obj_id; 294 u8 release_regno; 295 bool r0_rdonly; 296 u32 ret_btf_id; 297 u64 r0_size; 298 u32 subprogno; 299 struct { 300 u64 value; 301 bool found; 302 } arg_constant; 303 304 /* arg_{btf,btf_id,owning_ref} are used by kfunc-specific handling, 305 * generally to pass info about user-defined local kptr types to later 306 * verification logic 307 * bpf_obj_drop 308 * Record the local kptr type to be drop'd 309 * bpf_refcount_acquire (via KF_ARG_PTR_TO_REFCOUNTED_KPTR arg type) 310 * Record the local kptr type to be refcount_incr'd and use 311 * arg_owning_ref to determine whether refcount_acquire should be 312 * fallible 313 */ 314 struct btf *arg_btf; 315 u32 arg_btf_id; 316 bool arg_owning_ref; 317 318 struct { 319 struct btf_field *field; 320 } arg_list_head; 321 struct { 322 struct btf_field *field; 323 } arg_rbtree_root; 324 struct { 325 enum bpf_dynptr_type type; 326 u32 id; 327 u32 ref_obj_id; 328 } initialized_dynptr; 329 struct { 330 u8 spi; 331 u8 frameno; 332 } iter; 333 u64 mem_size; 334 }; 335 336 struct btf *btf_vmlinux; 337 338 static DEFINE_MUTEX(bpf_verifier_lock); 339 340 static const struct bpf_line_info * 341 find_linfo(const struct bpf_verifier_env *env, u32 insn_off) 342 { 343 const struct bpf_line_info *linfo; 344 const struct bpf_prog *prog; 345 u32 i, nr_linfo; 346 347 prog = env->prog; 348 nr_linfo = prog->aux->nr_linfo; 349 350 if (!nr_linfo || insn_off >= prog->len) 351 return NULL; 352 353 linfo = prog->aux->linfo; 354 for (i = 1; i < nr_linfo; i++) 355 if (insn_off < linfo[i].insn_off) 356 break; 357 358 return &linfo[i - 1]; 359 } 360 361 __printf(2, 3) static void verbose(void *private_data, const char *fmt, ...) 362 { 363 struct bpf_verifier_env *env = private_data; 364 va_list args; 365 366 if (!bpf_verifier_log_needed(&env->log)) 367 return; 368 369 va_start(args, fmt); 370 bpf_verifier_vlog(&env->log, fmt, args); 371 va_end(args); 372 } 373 374 static const char *ltrim(const char *s) 375 { 376 while (isspace(*s)) 377 s++; 378 379 return s; 380 } 381 382 __printf(3, 4) static void verbose_linfo(struct bpf_verifier_env *env, 383 u32 insn_off, 384 const char *prefix_fmt, ...) 385 { 386 const struct bpf_line_info *linfo; 387 388 if (!bpf_verifier_log_needed(&env->log)) 389 return; 390 391 linfo = find_linfo(env, insn_off); 392 if (!linfo || linfo == env->prev_linfo) 393 return; 394 395 if (prefix_fmt) { 396 va_list args; 397 398 va_start(args, prefix_fmt); 399 bpf_verifier_vlog(&env->log, prefix_fmt, args); 400 va_end(args); 401 } 402 403 verbose(env, "%s\n", 404 ltrim(btf_name_by_offset(env->prog->aux->btf, 405 linfo->line_off))); 406 407 env->prev_linfo = linfo; 408 } 409 410 static void verbose_invalid_scalar(struct bpf_verifier_env *env, 411 struct bpf_reg_state *reg, 412 struct tnum *range, const char *ctx, 413 const char *reg_name) 414 { 415 char tn_buf[48]; 416 417 verbose(env, "At %s the register %s ", ctx, reg_name); 418 if (!tnum_is_unknown(reg->var_off)) { 419 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 420 verbose(env, "has value %s", tn_buf); 421 } else { 422 verbose(env, "has unknown scalar value"); 423 } 424 tnum_strn(tn_buf, sizeof(tn_buf), *range); 425 verbose(env, " should have been in %s\n", tn_buf); 426 } 427 428 static bool type_is_pkt_pointer(enum bpf_reg_type type) 429 { 430 type = base_type(type); 431 return type == PTR_TO_PACKET || 432 type == PTR_TO_PACKET_META; 433 } 434 435 static bool type_is_sk_pointer(enum bpf_reg_type type) 436 { 437 return type == PTR_TO_SOCKET || 438 type == PTR_TO_SOCK_COMMON || 439 type == PTR_TO_TCP_SOCK || 440 type == PTR_TO_XDP_SOCK; 441 } 442 443 static bool type_may_be_null(u32 type) 444 { 445 return type & PTR_MAYBE_NULL; 446 } 447 448 static bool reg_not_null(const struct bpf_reg_state *reg) 449 { 450 enum bpf_reg_type type; 451 452 type = reg->type; 453 if (type_may_be_null(type)) 454 return false; 455 456 type = base_type(type); 457 return type == PTR_TO_SOCKET || 458 type == PTR_TO_TCP_SOCK || 459 type == PTR_TO_MAP_VALUE || 460 type == PTR_TO_MAP_KEY || 461 type == PTR_TO_SOCK_COMMON || 462 (type == PTR_TO_BTF_ID && is_trusted_reg(reg)) || 463 type == PTR_TO_MEM; 464 } 465 466 static bool type_is_ptr_alloc_obj(u32 type) 467 { 468 return base_type(type) == PTR_TO_BTF_ID && type_flag(type) & MEM_ALLOC; 469 } 470 471 static bool type_is_non_owning_ref(u32 type) 472 { 473 return type_is_ptr_alloc_obj(type) && type_flag(type) & NON_OWN_REF; 474 } 475 476 static struct btf_record *reg_btf_record(const struct bpf_reg_state *reg) 477 { 478 struct btf_record *rec = NULL; 479 struct btf_struct_meta *meta; 480 481 if (reg->type == PTR_TO_MAP_VALUE) { 482 rec = reg->map_ptr->record; 483 } else if (type_is_ptr_alloc_obj(reg->type)) { 484 meta = btf_find_struct_meta(reg->btf, reg->btf_id); 485 if (meta) 486 rec = meta->record; 487 } 488 return rec; 489 } 490 491 static bool subprog_is_global(const struct bpf_verifier_env *env, int subprog) 492 { 493 struct bpf_func_info_aux *aux = env->prog->aux->func_info_aux; 494 495 return aux && aux[subprog].linkage == BTF_FUNC_GLOBAL; 496 } 497 498 static bool reg_may_point_to_spin_lock(const struct bpf_reg_state *reg) 499 { 500 return btf_record_has_field(reg_btf_record(reg), BPF_SPIN_LOCK); 501 } 502 503 static bool type_is_rdonly_mem(u32 type) 504 { 505 return type & MEM_RDONLY; 506 } 507 508 static bool is_acquire_function(enum bpf_func_id func_id, 509 const struct bpf_map *map) 510 { 511 enum bpf_map_type map_type = map ? map->map_type : BPF_MAP_TYPE_UNSPEC; 512 513 if (func_id == BPF_FUNC_sk_lookup_tcp || 514 func_id == BPF_FUNC_sk_lookup_udp || 515 func_id == BPF_FUNC_skc_lookup_tcp || 516 func_id == BPF_FUNC_ringbuf_reserve || 517 func_id == BPF_FUNC_kptr_xchg) 518 return true; 519 520 if (func_id == BPF_FUNC_map_lookup_elem && 521 (map_type == BPF_MAP_TYPE_SOCKMAP || 522 map_type == BPF_MAP_TYPE_SOCKHASH)) 523 return true; 524 525 return false; 526 } 527 528 static bool is_ptr_cast_function(enum bpf_func_id func_id) 529 { 530 return func_id == BPF_FUNC_tcp_sock || 531 func_id == BPF_FUNC_sk_fullsock || 532 func_id == BPF_FUNC_skc_to_tcp_sock || 533 func_id == BPF_FUNC_skc_to_tcp6_sock || 534 func_id == BPF_FUNC_skc_to_udp6_sock || 535 func_id == BPF_FUNC_skc_to_mptcp_sock || 536 func_id == BPF_FUNC_skc_to_tcp_timewait_sock || 537 func_id == BPF_FUNC_skc_to_tcp_request_sock; 538 } 539 540 static bool is_dynptr_ref_function(enum bpf_func_id func_id) 541 { 542 return func_id == BPF_FUNC_dynptr_data; 543 } 544 545 static bool is_sync_callback_calling_kfunc(u32 btf_id); 546 547 static bool is_sync_callback_calling_function(enum bpf_func_id func_id) 548 { 549 return func_id == BPF_FUNC_for_each_map_elem || 550 func_id == BPF_FUNC_find_vma || 551 func_id == BPF_FUNC_loop || 552 func_id == BPF_FUNC_user_ringbuf_drain; 553 } 554 555 static bool is_async_callback_calling_function(enum bpf_func_id func_id) 556 { 557 return func_id == BPF_FUNC_timer_set_callback; 558 } 559 560 static bool is_callback_calling_function(enum bpf_func_id func_id) 561 { 562 return is_sync_callback_calling_function(func_id) || 563 is_async_callback_calling_function(func_id); 564 } 565 566 static bool is_sync_callback_calling_insn(struct bpf_insn *insn) 567 { 568 return (bpf_helper_call(insn) && is_sync_callback_calling_function(insn->imm)) || 569 (bpf_pseudo_kfunc_call(insn) && is_sync_callback_calling_kfunc(insn->imm)); 570 } 571 572 static bool is_storage_get_function(enum bpf_func_id func_id) 573 { 574 return func_id == BPF_FUNC_sk_storage_get || 575 func_id == BPF_FUNC_inode_storage_get || 576 func_id == BPF_FUNC_task_storage_get || 577 func_id == BPF_FUNC_cgrp_storage_get; 578 } 579 580 static bool helper_multiple_ref_obj_use(enum bpf_func_id func_id, 581 const struct bpf_map *map) 582 { 583 int ref_obj_uses = 0; 584 585 if (is_ptr_cast_function(func_id)) 586 ref_obj_uses++; 587 if (is_acquire_function(func_id, map)) 588 ref_obj_uses++; 589 if (is_dynptr_ref_function(func_id)) 590 ref_obj_uses++; 591 592 return ref_obj_uses > 1; 593 } 594 595 static bool is_cmpxchg_insn(const struct bpf_insn *insn) 596 { 597 return BPF_CLASS(insn->code) == BPF_STX && 598 BPF_MODE(insn->code) == BPF_ATOMIC && 599 insn->imm == BPF_CMPXCHG; 600 } 601 602 /* string representation of 'enum bpf_reg_type' 603 * 604 * Note that reg_type_str() can not appear more than once in a single verbose() 605 * statement. 606 */ 607 static const char *reg_type_str(struct bpf_verifier_env *env, 608 enum bpf_reg_type type) 609 { 610 char postfix[16] = {0}, prefix[64] = {0}; 611 static const char * const str[] = { 612 [NOT_INIT] = "?", 613 [SCALAR_VALUE] = "scalar", 614 [PTR_TO_CTX] = "ctx", 615 [CONST_PTR_TO_MAP] = "map_ptr", 616 [PTR_TO_MAP_VALUE] = "map_value", 617 [PTR_TO_STACK] = "fp", 618 [PTR_TO_PACKET] = "pkt", 619 [PTR_TO_PACKET_META] = "pkt_meta", 620 [PTR_TO_PACKET_END] = "pkt_end", 621 [PTR_TO_FLOW_KEYS] = "flow_keys", 622 [PTR_TO_SOCKET] = "sock", 623 [PTR_TO_SOCK_COMMON] = "sock_common", 624 [PTR_TO_TCP_SOCK] = "tcp_sock", 625 [PTR_TO_TP_BUFFER] = "tp_buffer", 626 [PTR_TO_XDP_SOCK] = "xdp_sock", 627 [PTR_TO_BTF_ID] = "ptr_", 628 [PTR_TO_MEM] = "mem", 629 [PTR_TO_BUF] = "buf", 630 [PTR_TO_FUNC] = "func", 631 [PTR_TO_MAP_KEY] = "map_key", 632 [CONST_PTR_TO_DYNPTR] = "dynptr_ptr", 633 }; 634 635 if (type & PTR_MAYBE_NULL) { 636 if (base_type(type) == PTR_TO_BTF_ID) 637 strncpy(postfix, "or_null_", 16); 638 else 639 strncpy(postfix, "_or_null", 16); 640 } 641 642 snprintf(prefix, sizeof(prefix), "%s%s%s%s%s%s%s", 643 type & MEM_RDONLY ? "rdonly_" : "", 644 type & MEM_RINGBUF ? "ringbuf_" : "", 645 type & MEM_USER ? "user_" : "", 646 type & MEM_PERCPU ? "percpu_" : "", 647 type & MEM_RCU ? "rcu_" : "", 648 type & PTR_UNTRUSTED ? "untrusted_" : "", 649 type & PTR_TRUSTED ? "trusted_" : "" 650 ); 651 652 snprintf(env->tmp_str_buf, TMP_STR_BUF_LEN, "%s%s%s", 653 prefix, str[base_type(type)], postfix); 654 return env->tmp_str_buf; 655 } 656 657 static char slot_type_char[] = { 658 [STACK_INVALID] = '?', 659 [STACK_SPILL] = 'r', 660 [STACK_MISC] = 'm', 661 [STACK_ZERO] = '0', 662 [STACK_DYNPTR] = 'd', 663 [STACK_ITER] = 'i', 664 }; 665 666 static void print_liveness(struct bpf_verifier_env *env, 667 enum bpf_reg_liveness live) 668 { 669 if (live & (REG_LIVE_READ | REG_LIVE_WRITTEN | REG_LIVE_DONE)) 670 verbose(env, "_"); 671 if (live & REG_LIVE_READ) 672 verbose(env, "r"); 673 if (live & REG_LIVE_WRITTEN) 674 verbose(env, "w"); 675 if (live & REG_LIVE_DONE) 676 verbose(env, "D"); 677 } 678 679 static int __get_spi(s32 off) 680 { 681 return (-off - 1) / BPF_REG_SIZE; 682 } 683 684 static struct bpf_func_state *func(struct bpf_verifier_env *env, 685 const struct bpf_reg_state *reg) 686 { 687 struct bpf_verifier_state *cur = env->cur_state; 688 689 return cur->frame[reg->frameno]; 690 } 691 692 static bool is_spi_bounds_valid(struct bpf_func_state *state, int spi, int nr_slots) 693 { 694 int allocated_slots = state->allocated_stack / BPF_REG_SIZE; 695 696 /* We need to check that slots between [spi - nr_slots + 1, spi] are 697 * within [0, allocated_stack). 698 * 699 * Please note that the spi grows downwards. For example, a dynptr 700 * takes the size of two stack slots; the first slot will be at 701 * spi and the second slot will be at spi - 1. 702 */ 703 return spi - nr_slots + 1 >= 0 && spi < allocated_slots; 704 } 705 706 static int stack_slot_obj_get_spi(struct bpf_verifier_env *env, struct bpf_reg_state *reg, 707 const char *obj_kind, int nr_slots) 708 { 709 int off, spi; 710 711 if (!tnum_is_const(reg->var_off)) { 712 verbose(env, "%s has to be at a constant offset\n", obj_kind); 713 return -EINVAL; 714 } 715 716 off = reg->off + reg->var_off.value; 717 if (off % BPF_REG_SIZE) { 718 verbose(env, "cannot pass in %s at an offset=%d\n", obj_kind, off); 719 return -EINVAL; 720 } 721 722 spi = __get_spi(off); 723 if (spi + 1 < nr_slots) { 724 verbose(env, "cannot pass in %s at an offset=%d\n", obj_kind, off); 725 return -EINVAL; 726 } 727 728 if (!is_spi_bounds_valid(func(env, reg), spi, nr_slots)) 729 return -ERANGE; 730 return spi; 731 } 732 733 static int dynptr_get_spi(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 734 { 735 return stack_slot_obj_get_spi(env, reg, "dynptr", BPF_DYNPTR_NR_SLOTS); 736 } 737 738 static int iter_get_spi(struct bpf_verifier_env *env, struct bpf_reg_state *reg, int nr_slots) 739 { 740 return stack_slot_obj_get_spi(env, reg, "iter", nr_slots); 741 } 742 743 static const char *btf_type_name(const struct btf *btf, u32 id) 744 { 745 return btf_name_by_offset(btf, btf_type_by_id(btf, id)->name_off); 746 } 747 748 static const char *dynptr_type_str(enum bpf_dynptr_type type) 749 { 750 switch (type) { 751 case BPF_DYNPTR_TYPE_LOCAL: 752 return "local"; 753 case BPF_DYNPTR_TYPE_RINGBUF: 754 return "ringbuf"; 755 case BPF_DYNPTR_TYPE_SKB: 756 return "skb"; 757 case BPF_DYNPTR_TYPE_XDP: 758 return "xdp"; 759 case BPF_DYNPTR_TYPE_INVALID: 760 return "<invalid>"; 761 default: 762 WARN_ONCE(1, "unknown dynptr type %d\n", type); 763 return "<unknown>"; 764 } 765 } 766 767 static const char *iter_type_str(const struct btf *btf, u32 btf_id) 768 { 769 if (!btf || btf_id == 0) 770 return "<invalid>"; 771 772 /* we already validated that type is valid and has conforming name */ 773 return btf_type_name(btf, btf_id) + sizeof(ITER_PREFIX) - 1; 774 } 775 776 static const char *iter_state_str(enum bpf_iter_state state) 777 { 778 switch (state) { 779 case BPF_ITER_STATE_ACTIVE: 780 return "active"; 781 case BPF_ITER_STATE_DRAINED: 782 return "drained"; 783 case BPF_ITER_STATE_INVALID: 784 return "<invalid>"; 785 default: 786 WARN_ONCE(1, "unknown iter state %d\n", state); 787 return "<unknown>"; 788 } 789 } 790 791 static void mark_reg_scratched(struct bpf_verifier_env *env, u32 regno) 792 { 793 env->scratched_regs |= 1U << regno; 794 } 795 796 static void mark_stack_slot_scratched(struct bpf_verifier_env *env, u32 spi) 797 { 798 env->scratched_stack_slots |= 1ULL << spi; 799 } 800 801 static bool reg_scratched(const struct bpf_verifier_env *env, u32 regno) 802 { 803 return (env->scratched_regs >> regno) & 1; 804 } 805 806 static bool stack_slot_scratched(const struct bpf_verifier_env *env, u64 regno) 807 { 808 return (env->scratched_stack_slots >> regno) & 1; 809 } 810 811 static bool verifier_state_scratched(const struct bpf_verifier_env *env) 812 { 813 return env->scratched_regs || env->scratched_stack_slots; 814 } 815 816 static void mark_verifier_state_clean(struct bpf_verifier_env *env) 817 { 818 env->scratched_regs = 0U; 819 env->scratched_stack_slots = 0ULL; 820 } 821 822 /* Used for printing the entire verifier state. */ 823 static void mark_verifier_state_scratched(struct bpf_verifier_env *env) 824 { 825 env->scratched_regs = ~0U; 826 env->scratched_stack_slots = ~0ULL; 827 } 828 829 static enum bpf_dynptr_type arg_to_dynptr_type(enum bpf_arg_type arg_type) 830 { 831 switch (arg_type & DYNPTR_TYPE_FLAG_MASK) { 832 case DYNPTR_TYPE_LOCAL: 833 return BPF_DYNPTR_TYPE_LOCAL; 834 case DYNPTR_TYPE_RINGBUF: 835 return BPF_DYNPTR_TYPE_RINGBUF; 836 case DYNPTR_TYPE_SKB: 837 return BPF_DYNPTR_TYPE_SKB; 838 case DYNPTR_TYPE_XDP: 839 return BPF_DYNPTR_TYPE_XDP; 840 default: 841 return BPF_DYNPTR_TYPE_INVALID; 842 } 843 } 844 845 static enum bpf_type_flag get_dynptr_type_flag(enum bpf_dynptr_type type) 846 { 847 switch (type) { 848 case BPF_DYNPTR_TYPE_LOCAL: 849 return DYNPTR_TYPE_LOCAL; 850 case BPF_DYNPTR_TYPE_RINGBUF: 851 return DYNPTR_TYPE_RINGBUF; 852 case BPF_DYNPTR_TYPE_SKB: 853 return DYNPTR_TYPE_SKB; 854 case BPF_DYNPTR_TYPE_XDP: 855 return DYNPTR_TYPE_XDP; 856 default: 857 return 0; 858 } 859 } 860 861 static bool dynptr_type_refcounted(enum bpf_dynptr_type type) 862 { 863 return type == BPF_DYNPTR_TYPE_RINGBUF; 864 } 865 866 static void __mark_dynptr_reg(struct bpf_reg_state *reg, 867 enum bpf_dynptr_type type, 868 bool first_slot, int dynptr_id); 869 870 static void __mark_reg_not_init(const struct bpf_verifier_env *env, 871 struct bpf_reg_state *reg); 872 873 static void mark_dynptr_stack_regs(struct bpf_verifier_env *env, 874 struct bpf_reg_state *sreg1, 875 struct bpf_reg_state *sreg2, 876 enum bpf_dynptr_type type) 877 { 878 int id = ++env->id_gen; 879 880 __mark_dynptr_reg(sreg1, type, true, id); 881 __mark_dynptr_reg(sreg2, type, false, id); 882 } 883 884 static void mark_dynptr_cb_reg(struct bpf_verifier_env *env, 885 struct bpf_reg_state *reg, 886 enum bpf_dynptr_type type) 887 { 888 __mark_dynptr_reg(reg, type, true, ++env->id_gen); 889 } 890 891 static int destroy_if_dynptr_stack_slot(struct bpf_verifier_env *env, 892 struct bpf_func_state *state, int spi); 893 894 static int mark_stack_slots_dynptr(struct bpf_verifier_env *env, struct bpf_reg_state *reg, 895 enum bpf_arg_type arg_type, int insn_idx, int clone_ref_obj_id) 896 { 897 struct bpf_func_state *state = func(env, reg); 898 enum bpf_dynptr_type type; 899 int spi, i, err; 900 901 spi = dynptr_get_spi(env, reg); 902 if (spi < 0) 903 return spi; 904 905 /* We cannot assume both spi and spi - 1 belong to the same dynptr, 906 * hence we need to call destroy_if_dynptr_stack_slot twice for both, 907 * to ensure that for the following example: 908 * [d1][d1][d2][d2] 909 * spi 3 2 1 0 910 * So marking spi = 2 should lead to destruction of both d1 and d2. In 911 * case they do belong to same dynptr, second call won't see slot_type 912 * as STACK_DYNPTR and will simply skip destruction. 913 */ 914 err = destroy_if_dynptr_stack_slot(env, state, spi); 915 if (err) 916 return err; 917 err = destroy_if_dynptr_stack_slot(env, state, spi - 1); 918 if (err) 919 return err; 920 921 for (i = 0; i < BPF_REG_SIZE; i++) { 922 state->stack[spi].slot_type[i] = STACK_DYNPTR; 923 state->stack[spi - 1].slot_type[i] = STACK_DYNPTR; 924 } 925 926 type = arg_to_dynptr_type(arg_type); 927 if (type == BPF_DYNPTR_TYPE_INVALID) 928 return -EINVAL; 929 930 mark_dynptr_stack_regs(env, &state->stack[spi].spilled_ptr, 931 &state->stack[spi - 1].spilled_ptr, type); 932 933 if (dynptr_type_refcounted(type)) { 934 /* The id is used to track proper releasing */ 935 int id; 936 937 if (clone_ref_obj_id) 938 id = clone_ref_obj_id; 939 else 940 id = acquire_reference_state(env, insn_idx); 941 942 if (id < 0) 943 return id; 944 945 state->stack[spi].spilled_ptr.ref_obj_id = id; 946 state->stack[spi - 1].spilled_ptr.ref_obj_id = id; 947 } 948 949 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN; 950 state->stack[spi - 1].spilled_ptr.live |= REG_LIVE_WRITTEN; 951 952 return 0; 953 } 954 955 static void invalidate_dynptr(struct bpf_verifier_env *env, struct bpf_func_state *state, int spi) 956 { 957 int i; 958 959 for (i = 0; i < BPF_REG_SIZE; i++) { 960 state->stack[spi].slot_type[i] = STACK_INVALID; 961 state->stack[spi - 1].slot_type[i] = STACK_INVALID; 962 } 963 964 __mark_reg_not_init(env, &state->stack[spi].spilled_ptr); 965 __mark_reg_not_init(env, &state->stack[spi - 1].spilled_ptr); 966 967 /* Why do we need to set REG_LIVE_WRITTEN for STACK_INVALID slot? 968 * 969 * While we don't allow reading STACK_INVALID, it is still possible to 970 * do <8 byte writes marking some but not all slots as STACK_MISC. Then, 971 * helpers or insns can do partial read of that part without failing, 972 * but check_stack_range_initialized, check_stack_read_var_off, and 973 * check_stack_read_fixed_off will do mark_reg_read for all 8-bytes of 974 * the slot conservatively. Hence we need to prevent those liveness 975 * marking walks. 976 * 977 * This was not a problem before because STACK_INVALID is only set by 978 * default (where the default reg state has its reg->parent as NULL), or 979 * in clean_live_states after REG_LIVE_DONE (at which point 980 * mark_reg_read won't walk reg->parent chain), but not randomly during 981 * verifier state exploration (like we did above). Hence, for our case 982 * parentage chain will still be live (i.e. reg->parent may be 983 * non-NULL), while earlier reg->parent was NULL, so we need 984 * REG_LIVE_WRITTEN to screen off read marker propagation when it is 985 * done later on reads or by mark_dynptr_read as well to unnecessary 986 * mark registers in verifier state. 987 */ 988 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN; 989 state->stack[spi - 1].spilled_ptr.live |= REG_LIVE_WRITTEN; 990 } 991 992 static int unmark_stack_slots_dynptr(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 993 { 994 struct bpf_func_state *state = func(env, reg); 995 int spi, ref_obj_id, i; 996 997 spi = dynptr_get_spi(env, reg); 998 if (spi < 0) 999 return spi; 1000 1001 if (!dynptr_type_refcounted(state->stack[spi].spilled_ptr.dynptr.type)) { 1002 invalidate_dynptr(env, state, spi); 1003 return 0; 1004 } 1005 1006 ref_obj_id = state->stack[spi].spilled_ptr.ref_obj_id; 1007 1008 /* If the dynptr has a ref_obj_id, then we need to invalidate 1009 * two things: 1010 * 1011 * 1) Any dynptrs with a matching ref_obj_id (clones) 1012 * 2) Any slices derived from this dynptr. 1013 */ 1014 1015 /* Invalidate any slices associated with this dynptr */ 1016 WARN_ON_ONCE(release_reference(env, ref_obj_id)); 1017 1018 /* Invalidate any dynptr clones */ 1019 for (i = 1; i < state->allocated_stack / BPF_REG_SIZE; i++) { 1020 if (state->stack[i].spilled_ptr.ref_obj_id != ref_obj_id) 1021 continue; 1022 1023 /* it should always be the case that if the ref obj id 1024 * matches then the stack slot also belongs to a 1025 * dynptr 1026 */ 1027 if (state->stack[i].slot_type[0] != STACK_DYNPTR) { 1028 verbose(env, "verifier internal error: misconfigured ref_obj_id\n"); 1029 return -EFAULT; 1030 } 1031 if (state->stack[i].spilled_ptr.dynptr.first_slot) 1032 invalidate_dynptr(env, state, i); 1033 } 1034 1035 return 0; 1036 } 1037 1038 static void __mark_reg_unknown(const struct bpf_verifier_env *env, 1039 struct bpf_reg_state *reg); 1040 1041 static void mark_reg_invalid(const struct bpf_verifier_env *env, struct bpf_reg_state *reg) 1042 { 1043 if (!env->allow_ptr_leaks) 1044 __mark_reg_not_init(env, reg); 1045 else 1046 __mark_reg_unknown(env, reg); 1047 } 1048 1049 static int destroy_if_dynptr_stack_slot(struct bpf_verifier_env *env, 1050 struct bpf_func_state *state, int spi) 1051 { 1052 struct bpf_func_state *fstate; 1053 struct bpf_reg_state *dreg; 1054 int i, dynptr_id; 1055 1056 /* We always ensure that STACK_DYNPTR is never set partially, 1057 * hence just checking for slot_type[0] is enough. This is 1058 * different for STACK_SPILL, where it may be only set for 1059 * 1 byte, so code has to use is_spilled_reg. 1060 */ 1061 if (state->stack[spi].slot_type[0] != STACK_DYNPTR) 1062 return 0; 1063 1064 /* Reposition spi to first slot */ 1065 if (!state->stack[spi].spilled_ptr.dynptr.first_slot) 1066 spi = spi + 1; 1067 1068 if (dynptr_type_refcounted(state->stack[spi].spilled_ptr.dynptr.type)) { 1069 verbose(env, "cannot overwrite referenced dynptr\n"); 1070 return -EINVAL; 1071 } 1072 1073 mark_stack_slot_scratched(env, spi); 1074 mark_stack_slot_scratched(env, spi - 1); 1075 1076 /* Writing partially to one dynptr stack slot destroys both. */ 1077 for (i = 0; i < BPF_REG_SIZE; i++) { 1078 state->stack[spi].slot_type[i] = STACK_INVALID; 1079 state->stack[spi - 1].slot_type[i] = STACK_INVALID; 1080 } 1081 1082 dynptr_id = state->stack[spi].spilled_ptr.id; 1083 /* Invalidate any slices associated with this dynptr */ 1084 bpf_for_each_reg_in_vstate(env->cur_state, fstate, dreg, ({ 1085 /* Dynptr slices are only PTR_TO_MEM_OR_NULL and PTR_TO_MEM */ 1086 if (dreg->type != (PTR_TO_MEM | PTR_MAYBE_NULL) && dreg->type != PTR_TO_MEM) 1087 continue; 1088 if (dreg->dynptr_id == dynptr_id) 1089 mark_reg_invalid(env, dreg); 1090 })); 1091 1092 /* Do not release reference state, we are destroying dynptr on stack, 1093 * not using some helper to release it. Just reset register. 1094 */ 1095 __mark_reg_not_init(env, &state->stack[spi].spilled_ptr); 1096 __mark_reg_not_init(env, &state->stack[spi - 1].spilled_ptr); 1097 1098 /* Same reason as unmark_stack_slots_dynptr above */ 1099 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN; 1100 state->stack[spi - 1].spilled_ptr.live |= REG_LIVE_WRITTEN; 1101 1102 return 0; 1103 } 1104 1105 static bool is_dynptr_reg_valid_uninit(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 1106 { 1107 int spi; 1108 1109 if (reg->type == CONST_PTR_TO_DYNPTR) 1110 return false; 1111 1112 spi = dynptr_get_spi(env, reg); 1113 1114 /* -ERANGE (i.e. spi not falling into allocated stack slots) isn't an 1115 * error because this just means the stack state hasn't been updated yet. 1116 * We will do check_mem_access to check and update stack bounds later. 1117 */ 1118 if (spi < 0 && spi != -ERANGE) 1119 return false; 1120 1121 /* We don't need to check if the stack slots are marked by previous 1122 * dynptr initializations because we allow overwriting existing unreferenced 1123 * STACK_DYNPTR slots, see mark_stack_slots_dynptr which calls 1124 * destroy_if_dynptr_stack_slot to ensure dynptr objects at the slots we are 1125 * touching are completely destructed before we reinitialize them for a new 1126 * one. For referenced ones, destroy_if_dynptr_stack_slot returns an error early 1127 * instead of delaying it until the end where the user will get "Unreleased 1128 * reference" error. 1129 */ 1130 return true; 1131 } 1132 1133 static bool is_dynptr_reg_valid_init(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 1134 { 1135 struct bpf_func_state *state = func(env, reg); 1136 int i, spi; 1137 1138 /* This already represents first slot of initialized bpf_dynptr. 1139 * 1140 * CONST_PTR_TO_DYNPTR already has fixed and var_off as 0 due to 1141 * check_func_arg_reg_off's logic, so we don't need to check its 1142 * offset and alignment. 1143 */ 1144 if (reg->type == CONST_PTR_TO_DYNPTR) 1145 return true; 1146 1147 spi = dynptr_get_spi(env, reg); 1148 if (spi < 0) 1149 return false; 1150 if (!state->stack[spi].spilled_ptr.dynptr.first_slot) 1151 return false; 1152 1153 for (i = 0; i < BPF_REG_SIZE; i++) { 1154 if (state->stack[spi].slot_type[i] != STACK_DYNPTR || 1155 state->stack[spi - 1].slot_type[i] != STACK_DYNPTR) 1156 return false; 1157 } 1158 1159 return true; 1160 } 1161 1162 static bool is_dynptr_type_expected(struct bpf_verifier_env *env, struct bpf_reg_state *reg, 1163 enum bpf_arg_type arg_type) 1164 { 1165 struct bpf_func_state *state = func(env, reg); 1166 enum bpf_dynptr_type dynptr_type; 1167 int spi; 1168 1169 /* ARG_PTR_TO_DYNPTR takes any type of dynptr */ 1170 if (arg_type == ARG_PTR_TO_DYNPTR) 1171 return true; 1172 1173 dynptr_type = arg_to_dynptr_type(arg_type); 1174 if (reg->type == CONST_PTR_TO_DYNPTR) { 1175 return reg->dynptr.type == dynptr_type; 1176 } else { 1177 spi = dynptr_get_spi(env, reg); 1178 if (spi < 0) 1179 return false; 1180 return state->stack[spi].spilled_ptr.dynptr.type == dynptr_type; 1181 } 1182 } 1183 1184 static void __mark_reg_known_zero(struct bpf_reg_state *reg); 1185 1186 static int mark_stack_slots_iter(struct bpf_verifier_env *env, 1187 struct bpf_reg_state *reg, int insn_idx, 1188 struct btf *btf, u32 btf_id, int nr_slots) 1189 { 1190 struct bpf_func_state *state = func(env, reg); 1191 int spi, i, j, id; 1192 1193 spi = iter_get_spi(env, reg, nr_slots); 1194 if (spi < 0) 1195 return spi; 1196 1197 id = acquire_reference_state(env, insn_idx); 1198 if (id < 0) 1199 return id; 1200 1201 for (i = 0; i < nr_slots; i++) { 1202 struct bpf_stack_state *slot = &state->stack[spi - i]; 1203 struct bpf_reg_state *st = &slot->spilled_ptr; 1204 1205 __mark_reg_known_zero(st); 1206 st->type = PTR_TO_STACK; /* we don't have dedicated reg type */ 1207 st->live |= REG_LIVE_WRITTEN; 1208 st->ref_obj_id = i == 0 ? id : 0; 1209 st->iter.btf = btf; 1210 st->iter.btf_id = btf_id; 1211 st->iter.state = BPF_ITER_STATE_ACTIVE; 1212 st->iter.depth = 0; 1213 1214 for (j = 0; j < BPF_REG_SIZE; j++) 1215 slot->slot_type[j] = STACK_ITER; 1216 1217 mark_stack_slot_scratched(env, spi - i); 1218 } 1219 1220 return 0; 1221 } 1222 1223 static int unmark_stack_slots_iter(struct bpf_verifier_env *env, 1224 struct bpf_reg_state *reg, int nr_slots) 1225 { 1226 struct bpf_func_state *state = func(env, reg); 1227 int spi, i, j; 1228 1229 spi = iter_get_spi(env, reg, nr_slots); 1230 if (spi < 0) 1231 return spi; 1232 1233 for (i = 0; i < nr_slots; i++) { 1234 struct bpf_stack_state *slot = &state->stack[spi - i]; 1235 struct bpf_reg_state *st = &slot->spilled_ptr; 1236 1237 if (i == 0) 1238 WARN_ON_ONCE(release_reference(env, st->ref_obj_id)); 1239 1240 __mark_reg_not_init(env, st); 1241 1242 /* see unmark_stack_slots_dynptr() for why we need to set REG_LIVE_WRITTEN */ 1243 st->live |= REG_LIVE_WRITTEN; 1244 1245 for (j = 0; j < BPF_REG_SIZE; j++) 1246 slot->slot_type[j] = STACK_INVALID; 1247 1248 mark_stack_slot_scratched(env, spi - i); 1249 } 1250 1251 return 0; 1252 } 1253 1254 static bool is_iter_reg_valid_uninit(struct bpf_verifier_env *env, 1255 struct bpf_reg_state *reg, int nr_slots) 1256 { 1257 struct bpf_func_state *state = func(env, reg); 1258 int spi, i, j; 1259 1260 /* For -ERANGE (i.e. spi not falling into allocated stack slots), we 1261 * will do check_mem_access to check and update stack bounds later, so 1262 * return true for that case. 1263 */ 1264 spi = iter_get_spi(env, reg, nr_slots); 1265 if (spi == -ERANGE) 1266 return true; 1267 if (spi < 0) 1268 return false; 1269 1270 for (i = 0; i < nr_slots; i++) { 1271 struct bpf_stack_state *slot = &state->stack[spi - i]; 1272 1273 for (j = 0; j < BPF_REG_SIZE; j++) 1274 if (slot->slot_type[j] == STACK_ITER) 1275 return false; 1276 } 1277 1278 return true; 1279 } 1280 1281 static bool is_iter_reg_valid_init(struct bpf_verifier_env *env, struct bpf_reg_state *reg, 1282 struct btf *btf, u32 btf_id, int nr_slots) 1283 { 1284 struct bpf_func_state *state = func(env, reg); 1285 int spi, i, j; 1286 1287 spi = iter_get_spi(env, reg, nr_slots); 1288 if (spi < 0) 1289 return false; 1290 1291 for (i = 0; i < nr_slots; i++) { 1292 struct bpf_stack_state *slot = &state->stack[spi - i]; 1293 struct bpf_reg_state *st = &slot->spilled_ptr; 1294 1295 /* only main (first) slot has ref_obj_id set */ 1296 if (i == 0 && !st->ref_obj_id) 1297 return false; 1298 if (i != 0 && st->ref_obj_id) 1299 return false; 1300 if (st->iter.btf != btf || st->iter.btf_id != btf_id) 1301 return false; 1302 1303 for (j = 0; j < BPF_REG_SIZE; j++) 1304 if (slot->slot_type[j] != STACK_ITER) 1305 return false; 1306 } 1307 1308 return true; 1309 } 1310 1311 /* Check if given stack slot is "special": 1312 * - spilled register state (STACK_SPILL); 1313 * - dynptr state (STACK_DYNPTR); 1314 * - iter state (STACK_ITER). 1315 */ 1316 static bool is_stack_slot_special(const struct bpf_stack_state *stack) 1317 { 1318 enum bpf_stack_slot_type type = stack->slot_type[BPF_REG_SIZE - 1]; 1319 1320 switch (type) { 1321 case STACK_SPILL: 1322 case STACK_DYNPTR: 1323 case STACK_ITER: 1324 return true; 1325 case STACK_INVALID: 1326 case STACK_MISC: 1327 case STACK_ZERO: 1328 return false; 1329 default: 1330 WARN_ONCE(1, "unknown stack slot type %d\n", type); 1331 return true; 1332 } 1333 } 1334 1335 /* The reg state of a pointer or a bounded scalar was saved when 1336 * it was spilled to the stack. 1337 */ 1338 static bool is_spilled_reg(const struct bpf_stack_state *stack) 1339 { 1340 return stack->slot_type[BPF_REG_SIZE - 1] == STACK_SPILL; 1341 } 1342 1343 static bool is_spilled_scalar_reg(const struct bpf_stack_state *stack) 1344 { 1345 return stack->slot_type[BPF_REG_SIZE - 1] == STACK_SPILL && 1346 stack->spilled_ptr.type == SCALAR_VALUE; 1347 } 1348 1349 static void scrub_spilled_slot(u8 *stype) 1350 { 1351 if (*stype != STACK_INVALID) 1352 *stype = STACK_MISC; 1353 } 1354 1355 static void print_verifier_state(struct bpf_verifier_env *env, 1356 const struct bpf_func_state *state, 1357 bool print_all) 1358 { 1359 const struct bpf_reg_state *reg; 1360 enum bpf_reg_type t; 1361 int i; 1362 1363 if (state->frameno) 1364 verbose(env, " frame%d:", state->frameno); 1365 for (i = 0; i < MAX_BPF_REG; i++) { 1366 reg = &state->regs[i]; 1367 t = reg->type; 1368 if (t == NOT_INIT) 1369 continue; 1370 if (!print_all && !reg_scratched(env, i)) 1371 continue; 1372 verbose(env, " R%d", i); 1373 print_liveness(env, reg->live); 1374 verbose(env, "="); 1375 if (t == SCALAR_VALUE && reg->precise) 1376 verbose(env, "P"); 1377 if ((t == SCALAR_VALUE || t == PTR_TO_STACK) && 1378 tnum_is_const(reg->var_off)) { 1379 /* reg->off should be 0 for SCALAR_VALUE */ 1380 verbose(env, "%s", t == SCALAR_VALUE ? "" : reg_type_str(env, t)); 1381 verbose(env, "%lld", reg->var_off.value + reg->off); 1382 } else { 1383 const char *sep = ""; 1384 1385 verbose(env, "%s", reg_type_str(env, t)); 1386 if (base_type(t) == PTR_TO_BTF_ID) 1387 verbose(env, "%s", btf_type_name(reg->btf, reg->btf_id)); 1388 verbose(env, "("); 1389 /* 1390 * _a stands for append, was shortened to avoid multiline statements below. 1391 * This macro is used to output a comma separated list of attributes. 1392 */ 1393 #define verbose_a(fmt, ...) ({ verbose(env, "%s" fmt, sep, __VA_ARGS__); sep = ","; }) 1394 1395 if (reg->id) 1396 verbose_a("id=%d", reg->id); 1397 if (reg->ref_obj_id) 1398 verbose_a("ref_obj_id=%d", reg->ref_obj_id); 1399 if (type_is_non_owning_ref(reg->type)) 1400 verbose_a("%s", "non_own_ref"); 1401 if (t != SCALAR_VALUE) 1402 verbose_a("off=%d", reg->off); 1403 if (type_is_pkt_pointer(t)) 1404 verbose_a("r=%d", reg->range); 1405 else if (base_type(t) == CONST_PTR_TO_MAP || 1406 base_type(t) == PTR_TO_MAP_KEY || 1407 base_type(t) == PTR_TO_MAP_VALUE) 1408 verbose_a("ks=%d,vs=%d", 1409 reg->map_ptr->key_size, 1410 reg->map_ptr->value_size); 1411 if (tnum_is_const(reg->var_off)) { 1412 /* Typically an immediate SCALAR_VALUE, but 1413 * could be a pointer whose offset is too big 1414 * for reg->off 1415 */ 1416 verbose_a("imm=%llx", reg->var_off.value); 1417 } else { 1418 if (reg->smin_value != reg->umin_value && 1419 reg->smin_value != S64_MIN) 1420 verbose_a("smin=%lld", (long long)reg->smin_value); 1421 if (reg->smax_value != reg->umax_value && 1422 reg->smax_value != S64_MAX) 1423 verbose_a("smax=%lld", (long long)reg->smax_value); 1424 if (reg->umin_value != 0) 1425 verbose_a("umin=%llu", (unsigned long long)reg->umin_value); 1426 if (reg->umax_value != U64_MAX) 1427 verbose_a("umax=%llu", (unsigned long long)reg->umax_value); 1428 if (!tnum_is_unknown(reg->var_off)) { 1429 char tn_buf[48]; 1430 1431 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 1432 verbose_a("var_off=%s", tn_buf); 1433 } 1434 if (reg->s32_min_value != reg->smin_value && 1435 reg->s32_min_value != S32_MIN) 1436 verbose_a("s32_min=%d", (int)(reg->s32_min_value)); 1437 if (reg->s32_max_value != reg->smax_value && 1438 reg->s32_max_value != S32_MAX) 1439 verbose_a("s32_max=%d", (int)(reg->s32_max_value)); 1440 if (reg->u32_min_value != reg->umin_value && 1441 reg->u32_min_value != U32_MIN) 1442 verbose_a("u32_min=%d", (int)(reg->u32_min_value)); 1443 if (reg->u32_max_value != reg->umax_value && 1444 reg->u32_max_value != U32_MAX) 1445 verbose_a("u32_max=%d", (int)(reg->u32_max_value)); 1446 } 1447 #undef verbose_a 1448 1449 verbose(env, ")"); 1450 } 1451 } 1452 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) { 1453 char types_buf[BPF_REG_SIZE + 1]; 1454 bool valid = false; 1455 int j; 1456 1457 for (j = 0; j < BPF_REG_SIZE; j++) { 1458 if (state->stack[i].slot_type[j] != STACK_INVALID) 1459 valid = true; 1460 types_buf[j] = slot_type_char[state->stack[i].slot_type[j]]; 1461 } 1462 types_buf[BPF_REG_SIZE] = 0; 1463 if (!valid) 1464 continue; 1465 if (!print_all && !stack_slot_scratched(env, i)) 1466 continue; 1467 switch (state->stack[i].slot_type[BPF_REG_SIZE - 1]) { 1468 case STACK_SPILL: 1469 reg = &state->stack[i].spilled_ptr; 1470 t = reg->type; 1471 1472 verbose(env, " fp%d", (-i - 1) * BPF_REG_SIZE); 1473 print_liveness(env, reg->live); 1474 verbose(env, "=%s", t == SCALAR_VALUE ? "" : reg_type_str(env, t)); 1475 if (t == SCALAR_VALUE && reg->precise) 1476 verbose(env, "P"); 1477 if (t == SCALAR_VALUE && tnum_is_const(reg->var_off)) 1478 verbose(env, "%lld", reg->var_off.value + reg->off); 1479 break; 1480 case STACK_DYNPTR: 1481 i += BPF_DYNPTR_NR_SLOTS - 1; 1482 reg = &state->stack[i].spilled_ptr; 1483 1484 verbose(env, " fp%d", (-i - 1) * BPF_REG_SIZE); 1485 print_liveness(env, reg->live); 1486 verbose(env, "=dynptr_%s", dynptr_type_str(reg->dynptr.type)); 1487 if (reg->ref_obj_id) 1488 verbose(env, "(ref_id=%d)", reg->ref_obj_id); 1489 break; 1490 case STACK_ITER: 1491 /* only main slot has ref_obj_id set; skip others */ 1492 reg = &state->stack[i].spilled_ptr; 1493 if (!reg->ref_obj_id) 1494 continue; 1495 1496 verbose(env, " fp%d", (-i - 1) * BPF_REG_SIZE); 1497 print_liveness(env, reg->live); 1498 verbose(env, "=iter_%s(ref_id=%d,state=%s,depth=%u)", 1499 iter_type_str(reg->iter.btf, reg->iter.btf_id), 1500 reg->ref_obj_id, iter_state_str(reg->iter.state), 1501 reg->iter.depth); 1502 break; 1503 case STACK_MISC: 1504 case STACK_ZERO: 1505 default: 1506 reg = &state->stack[i].spilled_ptr; 1507 1508 for (j = 0; j < BPF_REG_SIZE; j++) 1509 types_buf[j] = slot_type_char[state->stack[i].slot_type[j]]; 1510 types_buf[BPF_REG_SIZE] = 0; 1511 1512 verbose(env, " fp%d", (-i - 1) * BPF_REG_SIZE); 1513 print_liveness(env, reg->live); 1514 verbose(env, "=%s", types_buf); 1515 break; 1516 } 1517 } 1518 if (state->acquired_refs && state->refs[0].id) { 1519 verbose(env, " refs=%d", state->refs[0].id); 1520 for (i = 1; i < state->acquired_refs; i++) 1521 if (state->refs[i].id) 1522 verbose(env, ",%d", state->refs[i].id); 1523 } 1524 if (state->in_callback_fn) 1525 verbose(env, " cb"); 1526 if (state->in_async_callback_fn) 1527 verbose(env, " async_cb"); 1528 verbose(env, "\n"); 1529 if (!print_all) 1530 mark_verifier_state_clean(env); 1531 } 1532 1533 static inline u32 vlog_alignment(u32 pos) 1534 { 1535 return round_up(max(pos + BPF_LOG_MIN_ALIGNMENT / 2, BPF_LOG_ALIGNMENT), 1536 BPF_LOG_MIN_ALIGNMENT) - pos - 1; 1537 } 1538 1539 static void print_insn_state(struct bpf_verifier_env *env, 1540 const struct bpf_func_state *state) 1541 { 1542 if (env->prev_log_pos && env->prev_log_pos == env->log.end_pos) { 1543 /* remove new line character */ 1544 bpf_vlog_reset(&env->log, env->prev_log_pos - 1); 1545 verbose(env, "%*c;", vlog_alignment(env->prev_insn_print_pos), ' '); 1546 } else { 1547 verbose(env, "%d:", env->insn_idx); 1548 } 1549 print_verifier_state(env, state, false); 1550 } 1551 1552 /* copy array src of length n * size bytes to dst. dst is reallocated if it's too 1553 * small to hold src. This is different from krealloc since we don't want to preserve 1554 * the contents of dst. 1555 * 1556 * Leaves dst untouched if src is NULL or length is zero. Returns NULL if memory could 1557 * not be allocated. 1558 */ 1559 static void *copy_array(void *dst, const void *src, size_t n, size_t size, gfp_t flags) 1560 { 1561 size_t alloc_bytes; 1562 void *orig = dst; 1563 size_t bytes; 1564 1565 if (ZERO_OR_NULL_PTR(src)) 1566 goto out; 1567 1568 if (unlikely(check_mul_overflow(n, size, &bytes))) 1569 return NULL; 1570 1571 alloc_bytes = max(ksize(orig), kmalloc_size_roundup(bytes)); 1572 dst = krealloc(orig, alloc_bytes, flags); 1573 if (!dst) { 1574 kfree(orig); 1575 return NULL; 1576 } 1577 1578 memcpy(dst, src, bytes); 1579 out: 1580 return dst ? dst : ZERO_SIZE_PTR; 1581 } 1582 1583 /* resize an array from old_n items to new_n items. the array is reallocated if it's too 1584 * small to hold new_n items. new items are zeroed out if the array grows. 1585 * 1586 * Contrary to krealloc_array, does not free arr if new_n is zero. 1587 */ 1588 static void *realloc_array(void *arr, size_t old_n, size_t new_n, size_t size) 1589 { 1590 size_t alloc_size; 1591 void *new_arr; 1592 1593 if (!new_n || old_n == new_n) 1594 goto out; 1595 1596 alloc_size = kmalloc_size_roundup(size_mul(new_n, size)); 1597 new_arr = krealloc(arr, alloc_size, GFP_KERNEL); 1598 if (!new_arr) { 1599 kfree(arr); 1600 return NULL; 1601 } 1602 arr = new_arr; 1603 1604 if (new_n > old_n) 1605 memset(arr + old_n * size, 0, (new_n - old_n) * size); 1606 1607 out: 1608 return arr ? arr : ZERO_SIZE_PTR; 1609 } 1610 1611 static int copy_reference_state(struct bpf_func_state *dst, const struct bpf_func_state *src) 1612 { 1613 dst->refs = copy_array(dst->refs, src->refs, src->acquired_refs, 1614 sizeof(struct bpf_reference_state), GFP_KERNEL); 1615 if (!dst->refs) 1616 return -ENOMEM; 1617 1618 dst->acquired_refs = src->acquired_refs; 1619 return 0; 1620 } 1621 1622 static int copy_stack_state(struct bpf_func_state *dst, const struct bpf_func_state *src) 1623 { 1624 size_t n = src->allocated_stack / BPF_REG_SIZE; 1625 1626 dst->stack = copy_array(dst->stack, src->stack, n, sizeof(struct bpf_stack_state), 1627 GFP_KERNEL); 1628 if (!dst->stack) 1629 return -ENOMEM; 1630 1631 dst->allocated_stack = src->allocated_stack; 1632 return 0; 1633 } 1634 1635 static int resize_reference_state(struct bpf_func_state *state, size_t n) 1636 { 1637 state->refs = realloc_array(state->refs, state->acquired_refs, n, 1638 sizeof(struct bpf_reference_state)); 1639 if (!state->refs) 1640 return -ENOMEM; 1641 1642 state->acquired_refs = n; 1643 return 0; 1644 } 1645 1646 /* Possibly update state->allocated_stack to be at least size bytes. Also 1647 * possibly update the function's high-water mark in its bpf_subprog_info. 1648 */ 1649 static int grow_stack_state(struct bpf_verifier_env *env, struct bpf_func_state *state, int size) 1650 { 1651 size_t old_n = state->allocated_stack / BPF_REG_SIZE, n = size / BPF_REG_SIZE; 1652 1653 if (old_n >= n) 1654 return 0; 1655 1656 state->stack = realloc_array(state->stack, old_n, n, sizeof(struct bpf_stack_state)); 1657 if (!state->stack) 1658 return -ENOMEM; 1659 1660 state->allocated_stack = size; 1661 1662 /* update known max for given subprogram */ 1663 if (env->subprog_info[state->subprogno].stack_depth < size) 1664 env->subprog_info[state->subprogno].stack_depth = size; 1665 1666 return 0; 1667 } 1668 1669 /* Acquire a pointer id from the env and update the state->refs to include 1670 * this new pointer reference. 1671 * On success, returns a valid pointer id to associate with the register 1672 * On failure, returns a negative errno. 1673 */ 1674 static int acquire_reference_state(struct bpf_verifier_env *env, int insn_idx) 1675 { 1676 struct bpf_func_state *state = cur_func(env); 1677 int new_ofs = state->acquired_refs; 1678 int id, err; 1679 1680 err = resize_reference_state(state, state->acquired_refs + 1); 1681 if (err) 1682 return err; 1683 id = ++env->id_gen; 1684 state->refs[new_ofs].id = id; 1685 state->refs[new_ofs].insn_idx = insn_idx; 1686 state->refs[new_ofs].callback_ref = state->in_callback_fn ? state->frameno : 0; 1687 1688 return id; 1689 } 1690 1691 /* release function corresponding to acquire_reference_state(). Idempotent. */ 1692 static int release_reference_state(struct bpf_func_state *state, int ptr_id) 1693 { 1694 int i, last_idx; 1695 1696 last_idx = state->acquired_refs - 1; 1697 for (i = 0; i < state->acquired_refs; i++) { 1698 if (state->refs[i].id == ptr_id) { 1699 /* Cannot release caller references in callbacks */ 1700 if (state->in_callback_fn && state->refs[i].callback_ref != state->frameno) 1701 return -EINVAL; 1702 if (last_idx && i != last_idx) 1703 memcpy(&state->refs[i], &state->refs[last_idx], 1704 sizeof(*state->refs)); 1705 memset(&state->refs[last_idx], 0, sizeof(*state->refs)); 1706 state->acquired_refs--; 1707 return 0; 1708 } 1709 } 1710 return -EINVAL; 1711 } 1712 1713 static void free_func_state(struct bpf_func_state *state) 1714 { 1715 if (!state) 1716 return; 1717 kfree(state->refs); 1718 kfree(state->stack); 1719 kfree(state); 1720 } 1721 1722 static void clear_jmp_history(struct bpf_verifier_state *state) 1723 { 1724 kfree(state->jmp_history); 1725 state->jmp_history = NULL; 1726 state->jmp_history_cnt = 0; 1727 } 1728 1729 static void free_verifier_state(struct bpf_verifier_state *state, 1730 bool free_self) 1731 { 1732 int i; 1733 1734 for (i = 0; i <= state->curframe; i++) { 1735 free_func_state(state->frame[i]); 1736 state->frame[i] = NULL; 1737 } 1738 clear_jmp_history(state); 1739 if (free_self) 1740 kfree(state); 1741 } 1742 1743 /* copy verifier state from src to dst growing dst stack space 1744 * when necessary to accommodate larger src stack 1745 */ 1746 static int copy_func_state(struct bpf_func_state *dst, 1747 const struct bpf_func_state *src) 1748 { 1749 int err; 1750 1751 memcpy(dst, src, offsetof(struct bpf_func_state, acquired_refs)); 1752 err = copy_reference_state(dst, src); 1753 if (err) 1754 return err; 1755 return copy_stack_state(dst, src); 1756 } 1757 1758 static int copy_verifier_state(struct bpf_verifier_state *dst_state, 1759 const struct bpf_verifier_state *src) 1760 { 1761 struct bpf_func_state *dst; 1762 int i, err; 1763 1764 dst_state->jmp_history = copy_array(dst_state->jmp_history, src->jmp_history, 1765 src->jmp_history_cnt, sizeof(*dst_state->jmp_history), 1766 GFP_USER); 1767 if (!dst_state->jmp_history) 1768 return -ENOMEM; 1769 dst_state->jmp_history_cnt = src->jmp_history_cnt; 1770 1771 /* if dst has more stack frames then src frame, free them */ 1772 for (i = src->curframe + 1; i <= dst_state->curframe; i++) { 1773 free_func_state(dst_state->frame[i]); 1774 dst_state->frame[i] = NULL; 1775 } 1776 dst_state->speculative = src->speculative; 1777 dst_state->active_rcu_lock = src->active_rcu_lock; 1778 dst_state->curframe = src->curframe; 1779 dst_state->active_lock.ptr = src->active_lock.ptr; 1780 dst_state->active_lock.id = src->active_lock.id; 1781 dst_state->branches = src->branches; 1782 dst_state->parent = src->parent; 1783 dst_state->first_insn_idx = src->first_insn_idx; 1784 dst_state->last_insn_idx = src->last_insn_idx; 1785 dst_state->dfs_depth = src->dfs_depth; 1786 dst_state->callback_unroll_depth = src->callback_unroll_depth; 1787 dst_state->used_as_loop_entry = src->used_as_loop_entry; 1788 for (i = 0; i <= src->curframe; i++) { 1789 dst = dst_state->frame[i]; 1790 if (!dst) { 1791 dst = kzalloc(sizeof(*dst), GFP_KERNEL); 1792 if (!dst) 1793 return -ENOMEM; 1794 dst_state->frame[i] = dst; 1795 } 1796 err = copy_func_state(dst, src->frame[i]); 1797 if (err) 1798 return err; 1799 } 1800 return 0; 1801 } 1802 1803 static u32 state_htab_size(struct bpf_verifier_env *env) 1804 { 1805 return env->prog->len; 1806 } 1807 1808 static struct bpf_verifier_state_list **explored_state(struct bpf_verifier_env *env, int idx) 1809 { 1810 struct bpf_verifier_state *cur = env->cur_state; 1811 struct bpf_func_state *state = cur->frame[cur->curframe]; 1812 1813 return &env->explored_states[(idx ^ state->callsite) % state_htab_size(env)]; 1814 } 1815 1816 static bool same_callsites(struct bpf_verifier_state *a, struct bpf_verifier_state *b) 1817 { 1818 int fr; 1819 1820 if (a->curframe != b->curframe) 1821 return false; 1822 1823 for (fr = a->curframe; fr >= 0; fr--) 1824 if (a->frame[fr]->callsite != b->frame[fr]->callsite) 1825 return false; 1826 1827 return true; 1828 } 1829 1830 /* Open coded iterators allow back-edges in the state graph in order to 1831 * check unbounded loops that iterators. 1832 * 1833 * In is_state_visited() it is necessary to know if explored states are 1834 * part of some loops in order to decide whether non-exact states 1835 * comparison could be used: 1836 * - non-exact states comparison establishes sub-state relation and uses 1837 * read and precision marks to do so, these marks are propagated from 1838 * children states and thus are not guaranteed to be final in a loop; 1839 * - exact states comparison just checks if current and explored states 1840 * are identical (and thus form a back-edge). 1841 * 1842 * Paper "A New Algorithm for Identifying Loops in Decompilation" 1843 * by Tao Wei, Jian Mao, Wei Zou and Yu Chen [1] presents a convenient 1844 * algorithm for loop structure detection and gives an overview of 1845 * relevant terminology. It also has helpful illustrations. 1846 * 1847 * [1] https://api.semanticscholar.org/CorpusID:15784067 1848 * 1849 * We use a similar algorithm but because loop nested structure is 1850 * irrelevant for verifier ours is significantly simpler and resembles 1851 * strongly connected components algorithm from Sedgewick's textbook. 1852 * 1853 * Define topmost loop entry as a first node of the loop traversed in a 1854 * depth first search starting from initial state. The goal of the loop 1855 * tracking algorithm is to associate topmost loop entries with states 1856 * derived from these entries. 1857 * 1858 * For each step in the DFS states traversal algorithm needs to identify 1859 * the following situations: 1860 * 1861 * initial initial initial 1862 * | | | 1863 * V V V 1864 * ... ... .---------> hdr 1865 * | | | | 1866 * V V | V 1867 * cur .-> succ | .------... 1868 * | | | | | | 1869 * V | V | V V 1870 * succ '-- cur | ... ... 1871 * | | | 1872 * | V V 1873 * | succ <- cur 1874 * | | 1875 * | V 1876 * | ... 1877 * | | 1878 * '----' 1879 * 1880 * (A) successor state of cur (B) successor state of cur or it's entry 1881 * not yet traversed are in current DFS path, thus cur and succ 1882 * are members of the same outermost loop 1883 * 1884 * initial initial 1885 * | | 1886 * V V 1887 * ... ... 1888 * | | 1889 * V V 1890 * .------... .------... 1891 * | | | | 1892 * V V V V 1893 * .-> hdr ... ... ... 1894 * | | | | | 1895 * | V V V V 1896 * | succ <- cur succ <- cur 1897 * | | | 1898 * | V V 1899 * | ... ... 1900 * | | | 1901 * '----' exit 1902 * 1903 * (C) successor state of cur is a part of some loop but this loop 1904 * does not include cur or successor state is not in a loop at all. 1905 * 1906 * Algorithm could be described as the following python code: 1907 * 1908 * traversed = set() # Set of traversed nodes 1909 * entries = {} # Mapping from node to loop entry 1910 * depths = {} # Depth level assigned to graph node 1911 * path = set() # Current DFS path 1912 * 1913 * # Find outermost loop entry known for n 1914 * def get_loop_entry(n): 1915 * h = entries.get(n, None) 1916 * while h in entries and entries[h] != h: 1917 * h = entries[h] 1918 * return h 1919 * 1920 * # Update n's loop entry if h's outermost entry comes 1921 * # before n's outermost entry in current DFS path. 1922 * def update_loop_entry(n, h): 1923 * n1 = get_loop_entry(n) or n 1924 * h1 = get_loop_entry(h) or h 1925 * if h1 in path and depths[h1] <= depths[n1]: 1926 * entries[n] = h1 1927 * 1928 * def dfs(n, depth): 1929 * traversed.add(n) 1930 * path.add(n) 1931 * depths[n] = depth 1932 * for succ in G.successors(n): 1933 * if succ not in traversed: 1934 * # Case A: explore succ and update cur's loop entry 1935 * # only if succ's entry is in current DFS path. 1936 * dfs(succ, depth + 1) 1937 * h = get_loop_entry(succ) 1938 * update_loop_entry(n, h) 1939 * else: 1940 * # Case B or C depending on `h1 in path` check in update_loop_entry(). 1941 * update_loop_entry(n, succ) 1942 * path.remove(n) 1943 * 1944 * To adapt this algorithm for use with verifier: 1945 * - use st->branch == 0 as a signal that DFS of succ had been finished 1946 * and cur's loop entry has to be updated (case A), handle this in 1947 * update_branch_counts(); 1948 * - use st->branch > 0 as a signal that st is in the current DFS path; 1949 * - handle cases B and C in is_state_visited(); 1950 * - update topmost loop entry for intermediate states in get_loop_entry(). 1951 */ 1952 static struct bpf_verifier_state *get_loop_entry(struct bpf_verifier_state *st) 1953 { 1954 struct bpf_verifier_state *topmost = st->loop_entry, *old; 1955 1956 while (topmost && topmost->loop_entry && topmost != topmost->loop_entry) 1957 topmost = topmost->loop_entry; 1958 /* Update loop entries for intermediate states to avoid this 1959 * traversal in future get_loop_entry() calls. 1960 */ 1961 while (st && st->loop_entry != topmost) { 1962 old = st->loop_entry; 1963 st->loop_entry = topmost; 1964 st = old; 1965 } 1966 return topmost; 1967 } 1968 1969 static void update_loop_entry(struct bpf_verifier_state *cur, struct bpf_verifier_state *hdr) 1970 { 1971 struct bpf_verifier_state *cur1, *hdr1; 1972 1973 cur1 = get_loop_entry(cur) ?: cur; 1974 hdr1 = get_loop_entry(hdr) ?: hdr; 1975 /* The head1->branches check decides between cases B and C in 1976 * comment for get_loop_entry(). If hdr1->branches == 0 then 1977 * head's topmost loop entry is not in current DFS path, 1978 * hence 'cur' and 'hdr' are not in the same loop and there is 1979 * no need to update cur->loop_entry. 1980 */ 1981 if (hdr1->branches && hdr1->dfs_depth <= cur1->dfs_depth) { 1982 cur->loop_entry = hdr; 1983 hdr->used_as_loop_entry = true; 1984 } 1985 } 1986 1987 static void update_branch_counts(struct bpf_verifier_env *env, struct bpf_verifier_state *st) 1988 { 1989 while (st) { 1990 u32 br = --st->branches; 1991 1992 /* br == 0 signals that DFS exploration for 'st' is finished, 1993 * thus it is necessary to update parent's loop entry if it 1994 * turned out that st is a part of some loop. 1995 * This is a part of 'case A' in get_loop_entry() comment. 1996 */ 1997 if (br == 0 && st->parent && st->loop_entry) 1998 update_loop_entry(st->parent, st->loop_entry); 1999 2000 /* WARN_ON(br > 1) technically makes sense here, 2001 * but see comment in push_stack(), hence: 2002 */ 2003 WARN_ONCE((int)br < 0, 2004 "BUG update_branch_counts:branches_to_explore=%d\n", 2005 br); 2006 if (br) 2007 break; 2008 st = st->parent; 2009 } 2010 } 2011 2012 static int pop_stack(struct bpf_verifier_env *env, int *prev_insn_idx, 2013 int *insn_idx, bool pop_log) 2014 { 2015 struct bpf_verifier_state *cur = env->cur_state; 2016 struct bpf_verifier_stack_elem *elem, *head = env->head; 2017 int err; 2018 2019 if (env->head == NULL) 2020 return -ENOENT; 2021 2022 if (cur) { 2023 err = copy_verifier_state(cur, &head->st); 2024 if (err) 2025 return err; 2026 } 2027 if (pop_log) 2028 bpf_vlog_reset(&env->log, head->log_pos); 2029 if (insn_idx) 2030 *insn_idx = head->insn_idx; 2031 if (prev_insn_idx) 2032 *prev_insn_idx = head->prev_insn_idx; 2033 elem = head->next; 2034 free_verifier_state(&head->st, false); 2035 kfree(head); 2036 env->head = elem; 2037 env->stack_size--; 2038 return 0; 2039 } 2040 2041 static struct bpf_verifier_state *push_stack(struct bpf_verifier_env *env, 2042 int insn_idx, int prev_insn_idx, 2043 bool speculative) 2044 { 2045 struct bpf_verifier_state *cur = env->cur_state; 2046 struct bpf_verifier_stack_elem *elem; 2047 int err; 2048 2049 elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL); 2050 if (!elem) 2051 goto err; 2052 2053 elem->insn_idx = insn_idx; 2054 elem->prev_insn_idx = prev_insn_idx; 2055 elem->next = env->head; 2056 elem->log_pos = env->log.end_pos; 2057 env->head = elem; 2058 env->stack_size++; 2059 err = copy_verifier_state(&elem->st, cur); 2060 if (err) 2061 goto err; 2062 elem->st.speculative |= speculative; 2063 if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) { 2064 verbose(env, "The sequence of %d jumps is too complex.\n", 2065 env->stack_size); 2066 goto err; 2067 } 2068 if (elem->st.parent) { 2069 ++elem->st.parent->branches; 2070 /* WARN_ON(branches > 2) technically makes sense here, 2071 * but 2072 * 1. speculative states will bump 'branches' for non-branch 2073 * instructions 2074 * 2. is_state_visited() heuristics may decide not to create 2075 * a new state for a sequence of branches and all such current 2076 * and cloned states will be pointing to a single parent state 2077 * which might have large 'branches' count. 2078 */ 2079 } 2080 return &elem->st; 2081 err: 2082 free_verifier_state(env->cur_state, true); 2083 env->cur_state = NULL; 2084 /* pop all elements and return */ 2085 while (!pop_stack(env, NULL, NULL, false)); 2086 return NULL; 2087 } 2088 2089 #define CALLER_SAVED_REGS 6 2090 static const int caller_saved[CALLER_SAVED_REGS] = { 2091 BPF_REG_0, BPF_REG_1, BPF_REG_2, BPF_REG_3, BPF_REG_4, BPF_REG_5 2092 }; 2093 2094 /* This helper doesn't clear reg->id */ 2095 static void ___mark_reg_known(struct bpf_reg_state *reg, u64 imm) 2096 { 2097 reg->var_off = tnum_const(imm); 2098 reg->smin_value = (s64)imm; 2099 reg->smax_value = (s64)imm; 2100 reg->umin_value = imm; 2101 reg->umax_value = imm; 2102 2103 reg->s32_min_value = (s32)imm; 2104 reg->s32_max_value = (s32)imm; 2105 reg->u32_min_value = (u32)imm; 2106 reg->u32_max_value = (u32)imm; 2107 } 2108 2109 /* Mark the unknown part of a register (variable offset or scalar value) as 2110 * known to have the value @imm. 2111 */ 2112 static void __mark_reg_known(struct bpf_reg_state *reg, u64 imm) 2113 { 2114 /* Clear off and union(map_ptr, range) */ 2115 memset(((u8 *)reg) + sizeof(reg->type), 0, 2116 offsetof(struct bpf_reg_state, var_off) - sizeof(reg->type)); 2117 reg->id = 0; 2118 reg->ref_obj_id = 0; 2119 ___mark_reg_known(reg, imm); 2120 } 2121 2122 static void __mark_reg32_known(struct bpf_reg_state *reg, u64 imm) 2123 { 2124 reg->var_off = tnum_const_subreg(reg->var_off, imm); 2125 reg->s32_min_value = (s32)imm; 2126 reg->s32_max_value = (s32)imm; 2127 reg->u32_min_value = (u32)imm; 2128 reg->u32_max_value = (u32)imm; 2129 } 2130 2131 /* Mark the 'variable offset' part of a register as zero. This should be 2132 * used only on registers holding a pointer type. 2133 */ 2134 static void __mark_reg_known_zero(struct bpf_reg_state *reg) 2135 { 2136 __mark_reg_known(reg, 0); 2137 } 2138 2139 static void __mark_reg_const_zero(struct bpf_reg_state *reg) 2140 { 2141 __mark_reg_known(reg, 0); 2142 reg->type = SCALAR_VALUE; 2143 } 2144 2145 static void mark_reg_known_zero(struct bpf_verifier_env *env, 2146 struct bpf_reg_state *regs, u32 regno) 2147 { 2148 if (WARN_ON(regno >= MAX_BPF_REG)) { 2149 verbose(env, "mark_reg_known_zero(regs, %u)\n", regno); 2150 /* Something bad happened, let's kill all regs */ 2151 for (regno = 0; regno < MAX_BPF_REG; regno++) 2152 __mark_reg_not_init(env, regs + regno); 2153 return; 2154 } 2155 __mark_reg_known_zero(regs + regno); 2156 } 2157 2158 static void __mark_dynptr_reg(struct bpf_reg_state *reg, enum bpf_dynptr_type type, 2159 bool first_slot, int dynptr_id) 2160 { 2161 /* reg->type has no meaning for STACK_DYNPTR, but when we set reg for 2162 * callback arguments, it does need to be CONST_PTR_TO_DYNPTR, so simply 2163 * set it unconditionally as it is ignored for STACK_DYNPTR anyway. 2164 */ 2165 __mark_reg_known_zero(reg); 2166 reg->type = CONST_PTR_TO_DYNPTR; 2167 /* Give each dynptr a unique id to uniquely associate slices to it. */ 2168 reg->id = dynptr_id; 2169 reg->dynptr.type = type; 2170 reg->dynptr.first_slot = first_slot; 2171 } 2172 2173 static void mark_ptr_not_null_reg(struct bpf_reg_state *reg) 2174 { 2175 if (base_type(reg->type) == PTR_TO_MAP_VALUE) { 2176 const struct bpf_map *map = reg->map_ptr; 2177 2178 if (map->inner_map_meta) { 2179 reg->type = CONST_PTR_TO_MAP; 2180 reg->map_ptr = map->inner_map_meta; 2181 /* transfer reg's id which is unique for every map_lookup_elem 2182 * as UID of the inner map. 2183 */ 2184 if (btf_record_has_field(map->inner_map_meta->record, BPF_TIMER)) 2185 reg->map_uid = reg->id; 2186 } else if (map->map_type == BPF_MAP_TYPE_XSKMAP) { 2187 reg->type = PTR_TO_XDP_SOCK; 2188 } else if (map->map_type == BPF_MAP_TYPE_SOCKMAP || 2189 map->map_type == BPF_MAP_TYPE_SOCKHASH) { 2190 reg->type = PTR_TO_SOCKET; 2191 } else { 2192 reg->type = PTR_TO_MAP_VALUE; 2193 } 2194 return; 2195 } 2196 2197 reg->type &= ~PTR_MAYBE_NULL; 2198 } 2199 2200 static void mark_reg_graph_node(struct bpf_reg_state *regs, u32 regno, 2201 struct btf_field_graph_root *ds_head) 2202 { 2203 __mark_reg_known_zero(®s[regno]); 2204 regs[regno].type = PTR_TO_BTF_ID | MEM_ALLOC; 2205 regs[regno].btf = ds_head->btf; 2206 regs[regno].btf_id = ds_head->value_btf_id; 2207 regs[regno].off = ds_head->node_offset; 2208 } 2209 2210 static bool reg_is_pkt_pointer(const struct bpf_reg_state *reg) 2211 { 2212 return type_is_pkt_pointer(reg->type); 2213 } 2214 2215 static bool reg_is_pkt_pointer_any(const struct bpf_reg_state *reg) 2216 { 2217 return reg_is_pkt_pointer(reg) || 2218 reg->type == PTR_TO_PACKET_END; 2219 } 2220 2221 static bool reg_is_dynptr_slice_pkt(const struct bpf_reg_state *reg) 2222 { 2223 return base_type(reg->type) == PTR_TO_MEM && 2224 (reg->type & DYNPTR_TYPE_SKB || reg->type & DYNPTR_TYPE_XDP); 2225 } 2226 2227 /* Unmodified PTR_TO_PACKET[_META,_END] register from ctx access. */ 2228 static bool reg_is_init_pkt_pointer(const struct bpf_reg_state *reg, 2229 enum bpf_reg_type which) 2230 { 2231 /* The register can already have a range from prior markings. 2232 * This is fine as long as it hasn't been advanced from its 2233 * origin. 2234 */ 2235 return reg->type == which && 2236 reg->id == 0 && 2237 reg->off == 0 && 2238 tnum_equals_const(reg->var_off, 0); 2239 } 2240 2241 /* Reset the min/max bounds of a register */ 2242 static void __mark_reg_unbounded(struct bpf_reg_state *reg) 2243 { 2244 reg->smin_value = S64_MIN; 2245 reg->smax_value = S64_MAX; 2246 reg->umin_value = 0; 2247 reg->umax_value = U64_MAX; 2248 2249 reg->s32_min_value = S32_MIN; 2250 reg->s32_max_value = S32_MAX; 2251 reg->u32_min_value = 0; 2252 reg->u32_max_value = U32_MAX; 2253 } 2254 2255 static void __mark_reg64_unbounded(struct bpf_reg_state *reg) 2256 { 2257 reg->smin_value = S64_MIN; 2258 reg->smax_value = S64_MAX; 2259 reg->umin_value = 0; 2260 reg->umax_value = U64_MAX; 2261 } 2262 2263 static void __mark_reg32_unbounded(struct bpf_reg_state *reg) 2264 { 2265 reg->s32_min_value = S32_MIN; 2266 reg->s32_max_value = S32_MAX; 2267 reg->u32_min_value = 0; 2268 reg->u32_max_value = U32_MAX; 2269 } 2270 2271 static void __update_reg32_bounds(struct bpf_reg_state *reg) 2272 { 2273 struct tnum var32_off = tnum_subreg(reg->var_off); 2274 2275 /* min signed is max(sign bit) | min(other bits) */ 2276 reg->s32_min_value = max_t(s32, reg->s32_min_value, 2277 var32_off.value | (var32_off.mask & S32_MIN)); 2278 /* max signed is min(sign bit) | max(other bits) */ 2279 reg->s32_max_value = min_t(s32, reg->s32_max_value, 2280 var32_off.value | (var32_off.mask & S32_MAX)); 2281 reg->u32_min_value = max_t(u32, reg->u32_min_value, (u32)var32_off.value); 2282 reg->u32_max_value = min(reg->u32_max_value, 2283 (u32)(var32_off.value | var32_off.mask)); 2284 } 2285 2286 static void __update_reg64_bounds(struct bpf_reg_state *reg) 2287 { 2288 /* min signed is max(sign bit) | min(other bits) */ 2289 reg->smin_value = max_t(s64, reg->smin_value, 2290 reg->var_off.value | (reg->var_off.mask & S64_MIN)); 2291 /* max signed is min(sign bit) | max(other bits) */ 2292 reg->smax_value = min_t(s64, reg->smax_value, 2293 reg->var_off.value | (reg->var_off.mask & S64_MAX)); 2294 reg->umin_value = max(reg->umin_value, reg->var_off.value); 2295 reg->umax_value = min(reg->umax_value, 2296 reg->var_off.value | reg->var_off.mask); 2297 } 2298 2299 static void __update_reg_bounds(struct bpf_reg_state *reg) 2300 { 2301 __update_reg32_bounds(reg); 2302 __update_reg64_bounds(reg); 2303 } 2304 2305 /* Uses signed min/max values to inform unsigned, and vice-versa */ 2306 static void __reg32_deduce_bounds(struct bpf_reg_state *reg) 2307 { 2308 /* Learn sign from signed bounds. 2309 * If we cannot cross the sign boundary, then signed and unsigned bounds 2310 * are the same, so combine. This works even in the negative case, e.g. 2311 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff. 2312 */ 2313 if (reg->s32_min_value >= 0 || reg->s32_max_value < 0) { 2314 reg->s32_min_value = reg->u32_min_value = 2315 max_t(u32, reg->s32_min_value, reg->u32_min_value); 2316 reg->s32_max_value = reg->u32_max_value = 2317 min_t(u32, reg->s32_max_value, reg->u32_max_value); 2318 return; 2319 } 2320 /* Learn sign from unsigned bounds. Signed bounds cross the sign 2321 * boundary, so we must be careful. 2322 */ 2323 if ((s32)reg->u32_max_value >= 0) { 2324 /* Positive. We can't learn anything from the smin, but smax 2325 * is positive, hence safe. 2326 */ 2327 reg->s32_min_value = reg->u32_min_value; 2328 reg->s32_max_value = reg->u32_max_value = 2329 min_t(u32, reg->s32_max_value, reg->u32_max_value); 2330 } else if ((s32)reg->u32_min_value < 0) { 2331 /* Negative. We can't learn anything from the smax, but smin 2332 * is negative, hence safe. 2333 */ 2334 reg->s32_min_value = reg->u32_min_value = 2335 max_t(u32, reg->s32_min_value, reg->u32_min_value); 2336 reg->s32_max_value = reg->u32_max_value; 2337 } 2338 } 2339 2340 static void __reg64_deduce_bounds(struct bpf_reg_state *reg) 2341 { 2342 /* Learn sign from signed bounds. 2343 * If we cannot cross the sign boundary, then signed and unsigned bounds 2344 * are the same, so combine. This works even in the negative case, e.g. 2345 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff. 2346 */ 2347 if (reg->smin_value >= 0 || reg->smax_value < 0) { 2348 reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value, 2349 reg->umin_value); 2350 reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value, 2351 reg->umax_value); 2352 return; 2353 } 2354 /* Learn sign from unsigned bounds. Signed bounds cross the sign 2355 * boundary, so we must be careful. 2356 */ 2357 if ((s64)reg->umax_value >= 0) { 2358 /* Positive. We can't learn anything from the smin, but smax 2359 * is positive, hence safe. 2360 */ 2361 reg->smin_value = reg->umin_value; 2362 reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value, 2363 reg->umax_value); 2364 } else if ((s64)reg->umin_value < 0) { 2365 /* Negative. We can't learn anything from the smax, but smin 2366 * is negative, hence safe. 2367 */ 2368 reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value, 2369 reg->umin_value); 2370 reg->smax_value = reg->umax_value; 2371 } 2372 } 2373 2374 static void __reg_deduce_bounds(struct bpf_reg_state *reg) 2375 { 2376 __reg32_deduce_bounds(reg); 2377 __reg64_deduce_bounds(reg); 2378 } 2379 2380 /* Attempts to improve var_off based on unsigned min/max information */ 2381 static void __reg_bound_offset(struct bpf_reg_state *reg) 2382 { 2383 struct tnum var64_off = tnum_intersect(reg->var_off, 2384 tnum_range(reg->umin_value, 2385 reg->umax_value)); 2386 struct tnum var32_off = tnum_intersect(tnum_subreg(var64_off), 2387 tnum_range(reg->u32_min_value, 2388 reg->u32_max_value)); 2389 2390 reg->var_off = tnum_or(tnum_clear_subreg(var64_off), var32_off); 2391 } 2392 2393 static void reg_bounds_sync(struct bpf_reg_state *reg) 2394 { 2395 /* We might have learned new bounds from the var_off. */ 2396 __update_reg_bounds(reg); 2397 /* We might have learned something about the sign bit. */ 2398 __reg_deduce_bounds(reg); 2399 /* We might have learned some bits from the bounds. */ 2400 __reg_bound_offset(reg); 2401 /* Intersecting with the old var_off might have improved our bounds 2402 * slightly, e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc), 2403 * then new var_off is (0; 0x7f...fc) which improves our umax. 2404 */ 2405 __update_reg_bounds(reg); 2406 } 2407 2408 static bool __reg32_bound_s64(s32 a) 2409 { 2410 return a >= 0 && a <= S32_MAX; 2411 } 2412 2413 static void __reg_assign_32_into_64(struct bpf_reg_state *reg) 2414 { 2415 reg->umin_value = reg->u32_min_value; 2416 reg->umax_value = reg->u32_max_value; 2417 2418 /* Attempt to pull 32-bit signed bounds into 64-bit bounds but must 2419 * be positive otherwise set to worse case bounds and refine later 2420 * from tnum. 2421 */ 2422 if (__reg32_bound_s64(reg->s32_min_value) && 2423 __reg32_bound_s64(reg->s32_max_value)) { 2424 reg->smin_value = reg->s32_min_value; 2425 reg->smax_value = reg->s32_max_value; 2426 } else { 2427 reg->smin_value = 0; 2428 reg->smax_value = U32_MAX; 2429 } 2430 } 2431 2432 static void __reg_combine_32_into_64(struct bpf_reg_state *reg) 2433 { 2434 /* special case when 64-bit register has upper 32-bit register 2435 * zeroed. Typically happens after zext or <<32, >>32 sequence 2436 * allowing us to use 32-bit bounds directly, 2437 */ 2438 if (tnum_equals_const(tnum_clear_subreg(reg->var_off), 0)) { 2439 __reg_assign_32_into_64(reg); 2440 } else { 2441 /* Otherwise the best we can do is push lower 32bit known and 2442 * unknown bits into register (var_off set from jmp logic) 2443 * then learn as much as possible from the 64-bit tnum 2444 * known and unknown bits. The previous smin/smax bounds are 2445 * invalid here because of jmp32 compare so mark them unknown 2446 * so they do not impact tnum bounds calculation. 2447 */ 2448 __mark_reg64_unbounded(reg); 2449 } 2450 reg_bounds_sync(reg); 2451 } 2452 2453 static bool __reg64_bound_s32(s64 a) 2454 { 2455 return a >= S32_MIN && a <= S32_MAX; 2456 } 2457 2458 static bool __reg64_bound_u32(u64 a) 2459 { 2460 return a >= U32_MIN && a <= U32_MAX; 2461 } 2462 2463 static void __reg_combine_64_into_32(struct bpf_reg_state *reg) 2464 { 2465 __mark_reg32_unbounded(reg); 2466 if (__reg64_bound_s32(reg->smin_value) && __reg64_bound_s32(reg->smax_value)) { 2467 reg->s32_min_value = (s32)reg->smin_value; 2468 reg->s32_max_value = (s32)reg->smax_value; 2469 } 2470 if (__reg64_bound_u32(reg->umin_value) && __reg64_bound_u32(reg->umax_value)) { 2471 reg->u32_min_value = (u32)reg->umin_value; 2472 reg->u32_max_value = (u32)reg->umax_value; 2473 } 2474 reg_bounds_sync(reg); 2475 } 2476 2477 /* Mark a register as having a completely unknown (scalar) value. */ 2478 static void __mark_reg_unknown(const struct bpf_verifier_env *env, 2479 struct bpf_reg_state *reg) 2480 { 2481 /* 2482 * Clear type, off, and union(map_ptr, range) and 2483 * padding between 'type' and union 2484 */ 2485 memset(reg, 0, offsetof(struct bpf_reg_state, var_off)); 2486 reg->type = SCALAR_VALUE; 2487 reg->id = 0; 2488 reg->ref_obj_id = 0; 2489 reg->var_off = tnum_unknown; 2490 reg->frameno = 0; 2491 reg->precise = !env->bpf_capable; 2492 __mark_reg_unbounded(reg); 2493 } 2494 2495 static void mark_reg_unknown(struct bpf_verifier_env *env, 2496 struct bpf_reg_state *regs, u32 regno) 2497 { 2498 if (WARN_ON(regno >= MAX_BPF_REG)) { 2499 verbose(env, "mark_reg_unknown(regs, %u)\n", regno); 2500 /* Something bad happened, let's kill all regs except FP */ 2501 for (regno = 0; regno < BPF_REG_FP; regno++) 2502 __mark_reg_not_init(env, regs + regno); 2503 return; 2504 } 2505 __mark_reg_unknown(env, regs + regno); 2506 } 2507 2508 static void __mark_reg_not_init(const struct bpf_verifier_env *env, 2509 struct bpf_reg_state *reg) 2510 { 2511 __mark_reg_unknown(env, reg); 2512 reg->type = NOT_INIT; 2513 } 2514 2515 static void mark_reg_not_init(struct bpf_verifier_env *env, 2516 struct bpf_reg_state *regs, u32 regno) 2517 { 2518 if (WARN_ON(regno >= MAX_BPF_REG)) { 2519 verbose(env, "mark_reg_not_init(regs, %u)\n", regno); 2520 /* Something bad happened, let's kill all regs except FP */ 2521 for (regno = 0; regno < BPF_REG_FP; regno++) 2522 __mark_reg_not_init(env, regs + regno); 2523 return; 2524 } 2525 __mark_reg_not_init(env, regs + regno); 2526 } 2527 2528 static void mark_btf_ld_reg(struct bpf_verifier_env *env, 2529 struct bpf_reg_state *regs, u32 regno, 2530 enum bpf_reg_type reg_type, 2531 struct btf *btf, u32 btf_id, 2532 enum bpf_type_flag flag) 2533 { 2534 if (reg_type == SCALAR_VALUE) { 2535 mark_reg_unknown(env, regs, regno); 2536 return; 2537 } 2538 mark_reg_known_zero(env, regs, regno); 2539 regs[regno].type = PTR_TO_BTF_ID | flag; 2540 regs[regno].btf = btf; 2541 regs[regno].btf_id = btf_id; 2542 if (type_may_be_null(flag)) 2543 regs[regno].id = ++env->id_gen; 2544 } 2545 2546 #define DEF_NOT_SUBREG (0) 2547 static void init_reg_state(struct bpf_verifier_env *env, 2548 struct bpf_func_state *state) 2549 { 2550 struct bpf_reg_state *regs = state->regs; 2551 int i; 2552 2553 for (i = 0; i < MAX_BPF_REG; i++) { 2554 mark_reg_not_init(env, regs, i); 2555 regs[i].live = REG_LIVE_NONE; 2556 regs[i].parent = NULL; 2557 regs[i].subreg_def = DEF_NOT_SUBREG; 2558 } 2559 2560 /* frame pointer */ 2561 regs[BPF_REG_FP].type = PTR_TO_STACK; 2562 mark_reg_known_zero(env, regs, BPF_REG_FP); 2563 regs[BPF_REG_FP].frameno = state->frameno; 2564 } 2565 2566 #define BPF_MAIN_FUNC (-1) 2567 static void init_func_state(struct bpf_verifier_env *env, 2568 struct bpf_func_state *state, 2569 int callsite, int frameno, int subprogno) 2570 { 2571 state->callsite = callsite; 2572 state->frameno = frameno; 2573 state->subprogno = subprogno; 2574 state->callback_ret_range = tnum_range(0, 0); 2575 init_reg_state(env, state); 2576 mark_verifier_state_scratched(env); 2577 } 2578 2579 /* Similar to push_stack(), but for async callbacks */ 2580 static struct bpf_verifier_state *push_async_cb(struct bpf_verifier_env *env, 2581 int insn_idx, int prev_insn_idx, 2582 int subprog) 2583 { 2584 struct bpf_verifier_stack_elem *elem; 2585 struct bpf_func_state *frame; 2586 2587 elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL); 2588 if (!elem) 2589 goto err; 2590 2591 elem->insn_idx = insn_idx; 2592 elem->prev_insn_idx = prev_insn_idx; 2593 elem->next = env->head; 2594 elem->log_pos = env->log.end_pos; 2595 env->head = elem; 2596 env->stack_size++; 2597 if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) { 2598 verbose(env, 2599 "The sequence of %d jumps is too complex for async cb.\n", 2600 env->stack_size); 2601 goto err; 2602 } 2603 /* Unlike push_stack() do not copy_verifier_state(). 2604 * The caller state doesn't matter. 2605 * This is async callback. It starts in a fresh stack. 2606 * Initialize it similar to do_check_common(). 2607 */ 2608 elem->st.branches = 1; 2609 frame = kzalloc(sizeof(*frame), GFP_KERNEL); 2610 if (!frame) 2611 goto err; 2612 init_func_state(env, frame, 2613 BPF_MAIN_FUNC /* callsite */, 2614 0 /* frameno within this callchain */, 2615 subprog /* subprog number within this prog */); 2616 elem->st.frame[0] = frame; 2617 return &elem->st; 2618 err: 2619 free_verifier_state(env->cur_state, true); 2620 env->cur_state = NULL; 2621 /* pop all elements and return */ 2622 while (!pop_stack(env, NULL, NULL, false)); 2623 return NULL; 2624 } 2625 2626 2627 enum reg_arg_type { 2628 SRC_OP, /* register is used as source operand */ 2629 DST_OP, /* register is used as destination operand */ 2630 DST_OP_NO_MARK /* same as above, check only, don't mark */ 2631 }; 2632 2633 static int cmp_subprogs(const void *a, const void *b) 2634 { 2635 return ((struct bpf_subprog_info *)a)->start - 2636 ((struct bpf_subprog_info *)b)->start; 2637 } 2638 2639 static int find_subprog(struct bpf_verifier_env *env, int off) 2640 { 2641 struct bpf_subprog_info *p; 2642 2643 p = bsearch(&off, env->subprog_info, env->subprog_cnt, 2644 sizeof(env->subprog_info[0]), cmp_subprogs); 2645 if (!p) 2646 return -ENOENT; 2647 return p - env->subprog_info; 2648 2649 } 2650 2651 static int add_subprog(struct bpf_verifier_env *env, int off) 2652 { 2653 int insn_cnt = env->prog->len; 2654 int ret; 2655 2656 if (off >= insn_cnt || off < 0) { 2657 verbose(env, "call to invalid destination\n"); 2658 return -EINVAL; 2659 } 2660 ret = find_subprog(env, off); 2661 if (ret >= 0) 2662 return ret; 2663 if (env->subprog_cnt >= BPF_MAX_SUBPROGS) { 2664 verbose(env, "too many subprograms\n"); 2665 return -E2BIG; 2666 } 2667 /* determine subprog starts. The end is one before the next starts */ 2668 env->subprog_info[env->subprog_cnt++].start = off; 2669 sort(env->subprog_info, env->subprog_cnt, 2670 sizeof(env->subprog_info[0]), cmp_subprogs, NULL); 2671 return env->subprog_cnt - 1; 2672 } 2673 2674 #define MAX_KFUNC_DESCS 256 2675 #define MAX_KFUNC_BTFS 256 2676 2677 struct bpf_kfunc_desc { 2678 struct btf_func_model func_model; 2679 u32 func_id; 2680 s32 imm; 2681 u16 offset; 2682 unsigned long addr; 2683 }; 2684 2685 struct bpf_kfunc_btf { 2686 struct btf *btf; 2687 struct module *module; 2688 u16 offset; 2689 }; 2690 2691 struct bpf_kfunc_desc_tab { 2692 /* Sorted by func_id (BTF ID) and offset (fd_array offset) during 2693 * verification. JITs do lookups by bpf_insn, where func_id may not be 2694 * available, therefore at the end of verification do_misc_fixups() 2695 * sorts this by imm and offset. 2696 */ 2697 struct bpf_kfunc_desc descs[MAX_KFUNC_DESCS]; 2698 u32 nr_descs; 2699 }; 2700 2701 struct bpf_kfunc_btf_tab { 2702 struct bpf_kfunc_btf descs[MAX_KFUNC_BTFS]; 2703 u32 nr_descs; 2704 }; 2705 2706 static int kfunc_desc_cmp_by_id_off(const void *a, const void *b) 2707 { 2708 const struct bpf_kfunc_desc *d0 = a; 2709 const struct bpf_kfunc_desc *d1 = b; 2710 2711 /* func_id is not greater than BTF_MAX_TYPE */ 2712 return d0->func_id - d1->func_id ?: d0->offset - d1->offset; 2713 } 2714 2715 static int kfunc_btf_cmp_by_off(const void *a, const void *b) 2716 { 2717 const struct bpf_kfunc_btf *d0 = a; 2718 const struct bpf_kfunc_btf *d1 = b; 2719 2720 return d0->offset - d1->offset; 2721 } 2722 2723 static const struct bpf_kfunc_desc * 2724 find_kfunc_desc(const struct bpf_prog *prog, u32 func_id, u16 offset) 2725 { 2726 struct bpf_kfunc_desc desc = { 2727 .func_id = func_id, 2728 .offset = offset, 2729 }; 2730 struct bpf_kfunc_desc_tab *tab; 2731 2732 tab = prog->aux->kfunc_tab; 2733 return bsearch(&desc, tab->descs, tab->nr_descs, 2734 sizeof(tab->descs[0]), kfunc_desc_cmp_by_id_off); 2735 } 2736 2737 int bpf_get_kfunc_addr(const struct bpf_prog *prog, u32 func_id, 2738 u16 btf_fd_idx, u8 **func_addr) 2739 { 2740 const struct bpf_kfunc_desc *desc; 2741 2742 desc = find_kfunc_desc(prog, func_id, btf_fd_idx); 2743 if (!desc) 2744 return -EFAULT; 2745 2746 *func_addr = (u8 *)desc->addr; 2747 return 0; 2748 } 2749 2750 static struct btf *__find_kfunc_desc_btf(struct bpf_verifier_env *env, 2751 s16 offset) 2752 { 2753 struct bpf_kfunc_btf kf_btf = { .offset = offset }; 2754 struct bpf_kfunc_btf_tab *tab; 2755 struct bpf_kfunc_btf *b; 2756 struct module *mod; 2757 struct btf *btf; 2758 int btf_fd; 2759 2760 tab = env->prog->aux->kfunc_btf_tab; 2761 b = bsearch(&kf_btf, tab->descs, tab->nr_descs, 2762 sizeof(tab->descs[0]), kfunc_btf_cmp_by_off); 2763 if (!b) { 2764 if (tab->nr_descs == MAX_KFUNC_BTFS) { 2765 verbose(env, "too many different module BTFs\n"); 2766 return ERR_PTR(-E2BIG); 2767 } 2768 2769 if (bpfptr_is_null(env->fd_array)) { 2770 verbose(env, "kfunc offset > 0 without fd_array is invalid\n"); 2771 return ERR_PTR(-EPROTO); 2772 } 2773 2774 if (copy_from_bpfptr_offset(&btf_fd, env->fd_array, 2775 offset * sizeof(btf_fd), 2776 sizeof(btf_fd))) 2777 return ERR_PTR(-EFAULT); 2778 2779 btf = btf_get_by_fd(btf_fd); 2780 if (IS_ERR(btf)) { 2781 verbose(env, "invalid module BTF fd specified\n"); 2782 return btf; 2783 } 2784 2785 if (!btf_is_module(btf)) { 2786 verbose(env, "BTF fd for kfunc is not a module BTF\n"); 2787 btf_put(btf); 2788 return ERR_PTR(-EINVAL); 2789 } 2790 2791 mod = btf_try_get_module(btf); 2792 if (!mod) { 2793 btf_put(btf); 2794 return ERR_PTR(-ENXIO); 2795 } 2796 2797 b = &tab->descs[tab->nr_descs++]; 2798 b->btf = btf; 2799 b->module = mod; 2800 b->offset = offset; 2801 2802 /* sort() reorders entries by value, so b may no longer point 2803 * to the right entry after this 2804 */ 2805 sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]), 2806 kfunc_btf_cmp_by_off, NULL); 2807 } else { 2808 btf = b->btf; 2809 } 2810 2811 return btf; 2812 } 2813 2814 void bpf_free_kfunc_btf_tab(struct bpf_kfunc_btf_tab *tab) 2815 { 2816 if (!tab) 2817 return; 2818 2819 while (tab->nr_descs--) { 2820 module_put(tab->descs[tab->nr_descs].module); 2821 btf_put(tab->descs[tab->nr_descs].btf); 2822 } 2823 kfree(tab); 2824 } 2825 2826 static struct btf *find_kfunc_desc_btf(struct bpf_verifier_env *env, s16 offset) 2827 { 2828 if (offset) { 2829 if (offset < 0) { 2830 /* In the future, this can be allowed to increase limit 2831 * of fd index into fd_array, interpreted as u16. 2832 */ 2833 verbose(env, "negative offset disallowed for kernel module function call\n"); 2834 return ERR_PTR(-EINVAL); 2835 } 2836 2837 return __find_kfunc_desc_btf(env, offset); 2838 } 2839 return btf_vmlinux ?: ERR_PTR(-ENOENT); 2840 } 2841 2842 static int add_kfunc_call(struct bpf_verifier_env *env, u32 func_id, s16 offset) 2843 { 2844 const struct btf_type *func, *func_proto; 2845 struct bpf_kfunc_btf_tab *btf_tab; 2846 struct bpf_kfunc_desc_tab *tab; 2847 struct bpf_prog_aux *prog_aux; 2848 struct bpf_kfunc_desc *desc; 2849 const char *func_name; 2850 struct btf *desc_btf; 2851 unsigned long call_imm; 2852 unsigned long addr; 2853 int err; 2854 2855 prog_aux = env->prog->aux; 2856 tab = prog_aux->kfunc_tab; 2857 btf_tab = prog_aux->kfunc_btf_tab; 2858 if (!tab) { 2859 if (!btf_vmlinux) { 2860 verbose(env, "calling kernel function is not supported without CONFIG_DEBUG_INFO_BTF\n"); 2861 return -ENOTSUPP; 2862 } 2863 2864 if (!env->prog->jit_requested) { 2865 verbose(env, "JIT is required for calling kernel function\n"); 2866 return -ENOTSUPP; 2867 } 2868 2869 if (!bpf_jit_supports_kfunc_call()) { 2870 verbose(env, "JIT does not support calling kernel function\n"); 2871 return -ENOTSUPP; 2872 } 2873 2874 if (!env->prog->gpl_compatible) { 2875 verbose(env, "cannot call kernel function from non-GPL compatible program\n"); 2876 return -EINVAL; 2877 } 2878 2879 tab = kzalloc(sizeof(*tab), GFP_KERNEL); 2880 if (!tab) 2881 return -ENOMEM; 2882 prog_aux->kfunc_tab = tab; 2883 } 2884 2885 /* func_id == 0 is always invalid, but instead of returning an error, be 2886 * conservative and wait until the code elimination pass before returning 2887 * error, so that invalid calls that get pruned out can be in BPF programs 2888 * loaded from userspace. It is also required that offset be untouched 2889 * for such calls. 2890 */ 2891 if (!func_id && !offset) 2892 return 0; 2893 2894 if (!btf_tab && offset) { 2895 btf_tab = kzalloc(sizeof(*btf_tab), GFP_KERNEL); 2896 if (!btf_tab) 2897 return -ENOMEM; 2898 prog_aux->kfunc_btf_tab = btf_tab; 2899 } 2900 2901 desc_btf = find_kfunc_desc_btf(env, offset); 2902 if (IS_ERR(desc_btf)) { 2903 verbose(env, "failed to find BTF for kernel function\n"); 2904 return PTR_ERR(desc_btf); 2905 } 2906 2907 if (find_kfunc_desc(env->prog, func_id, offset)) 2908 return 0; 2909 2910 if (tab->nr_descs == MAX_KFUNC_DESCS) { 2911 verbose(env, "too many different kernel function calls\n"); 2912 return -E2BIG; 2913 } 2914 2915 func = btf_type_by_id(desc_btf, func_id); 2916 if (!func || !btf_type_is_func(func)) { 2917 verbose(env, "kernel btf_id %u is not a function\n", 2918 func_id); 2919 return -EINVAL; 2920 } 2921 func_proto = btf_type_by_id(desc_btf, func->type); 2922 if (!func_proto || !btf_type_is_func_proto(func_proto)) { 2923 verbose(env, "kernel function btf_id %u does not have a valid func_proto\n", 2924 func_id); 2925 return -EINVAL; 2926 } 2927 2928 func_name = btf_name_by_offset(desc_btf, func->name_off); 2929 addr = kallsyms_lookup_name(func_name); 2930 if (!addr) { 2931 verbose(env, "cannot find address for kernel function %s\n", 2932 func_name); 2933 return -EINVAL; 2934 } 2935 specialize_kfunc(env, func_id, offset, &addr); 2936 2937 if (bpf_jit_supports_far_kfunc_call()) { 2938 call_imm = func_id; 2939 } else { 2940 call_imm = BPF_CALL_IMM(addr); 2941 /* Check whether the relative offset overflows desc->imm */ 2942 if ((unsigned long)(s32)call_imm != call_imm) { 2943 verbose(env, "address of kernel function %s is out of range\n", 2944 func_name); 2945 return -EINVAL; 2946 } 2947 } 2948 2949 if (bpf_dev_bound_kfunc_id(func_id)) { 2950 err = bpf_dev_bound_kfunc_check(&env->log, prog_aux); 2951 if (err) 2952 return err; 2953 } 2954 2955 desc = &tab->descs[tab->nr_descs++]; 2956 desc->func_id = func_id; 2957 desc->imm = call_imm; 2958 desc->offset = offset; 2959 desc->addr = addr; 2960 err = btf_distill_func_proto(&env->log, desc_btf, 2961 func_proto, func_name, 2962 &desc->func_model); 2963 if (!err) 2964 sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]), 2965 kfunc_desc_cmp_by_id_off, NULL); 2966 return err; 2967 } 2968 2969 static int kfunc_desc_cmp_by_imm_off(const void *a, const void *b) 2970 { 2971 const struct bpf_kfunc_desc *d0 = a; 2972 const struct bpf_kfunc_desc *d1 = b; 2973 2974 if (d0->imm != d1->imm) 2975 return d0->imm < d1->imm ? -1 : 1; 2976 if (d0->offset != d1->offset) 2977 return d0->offset < d1->offset ? -1 : 1; 2978 return 0; 2979 } 2980 2981 static void sort_kfunc_descs_by_imm_off(struct bpf_prog *prog) 2982 { 2983 struct bpf_kfunc_desc_tab *tab; 2984 2985 tab = prog->aux->kfunc_tab; 2986 if (!tab) 2987 return; 2988 2989 sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]), 2990 kfunc_desc_cmp_by_imm_off, NULL); 2991 } 2992 2993 bool bpf_prog_has_kfunc_call(const struct bpf_prog *prog) 2994 { 2995 return !!prog->aux->kfunc_tab; 2996 } 2997 2998 const struct btf_func_model * 2999 bpf_jit_find_kfunc_model(const struct bpf_prog *prog, 3000 const struct bpf_insn *insn) 3001 { 3002 const struct bpf_kfunc_desc desc = { 3003 .imm = insn->imm, 3004 .offset = insn->off, 3005 }; 3006 const struct bpf_kfunc_desc *res; 3007 struct bpf_kfunc_desc_tab *tab; 3008 3009 tab = prog->aux->kfunc_tab; 3010 res = bsearch(&desc, tab->descs, tab->nr_descs, 3011 sizeof(tab->descs[0]), kfunc_desc_cmp_by_imm_off); 3012 3013 return res ? &res->func_model : NULL; 3014 } 3015 3016 static int add_subprog_and_kfunc(struct bpf_verifier_env *env) 3017 { 3018 struct bpf_subprog_info *subprog = env->subprog_info; 3019 struct bpf_insn *insn = env->prog->insnsi; 3020 int i, ret, insn_cnt = env->prog->len; 3021 3022 /* Add entry function. */ 3023 ret = add_subprog(env, 0); 3024 if (ret) 3025 return ret; 3026 3027 for (i = 0; i < insn_cnt; i++, insn++) { 3028 if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn) && 3029 !bpf_pseudo_kfunc_call(insn)) 3030 continue; 3031 3032 if (!env->bpf_capable) { 3033 verbose(env, "loading/calling other bpf or kernel functions are allowed for CAP_BPF and CAP_SYS_ADMIN\n"); 3034 return -EPERM; 3035 } 3036 3037 if (bpf_pseudo_func(insn) || bpf_pseudo_call(insn)) 3038 ret = add_subprog(env, i + insn->imm + 1); 3039 else 3040 ret = add_kfunc_call(env, insn->imm, insn->off); 3041 3042 if (ret < 0) 3043 return ret; 3044 } 3045 3046 /* Add a fake 'exit' subprog which could simplify subprog iteration 3047 * logic. 'subprog_cnt' should not be increased. 3048 */ 3049 subprog[env->subprog_cnt].start = insn_cnt; 3050 3051 if (env->log.level & BPF_LOG_LEVEL2) 3052 for (i = 0; i < env->subprog_cnt; i++) 3053 verbose(env, "func#%d @%d\n", i, subprog[i].start); 3054 3055 return 0; 3056 } 3057 3058 static int check_subprogs(struct bpf_verifier_env *env) 3059 { 3060 int i, subprog_start, subprog_end, off, cur_subprog = 0; 3061 struct bpf_subprog_info *subprog = env->subprog_info; 3062 struct bpf_insn *insn = env->prog->insnsi; 3063 int insn_cnt = env->prog->len; 3064 3065 /* now check that all jumps are within the same subprog */ 3066 subprog_start = subprog[cur_subprog].start; 3067 subprog_end = subprog[cur_subprog + 1].start; 3068 for (i = 0; i < insn_cnt; i++) { 3069 u8 code = insn[i].code; 3070 3071 if (code == (BPF_JMP | BPF_CALL) && 3072 insn[i].src_reg == 0 && 3073 insn[i].imm == BPF_FUNC_tail_call) { 3074 subprog[cur_subprog].has_tail_call = true; 3075 subprog[cur_subprog].tail_call_reachable = true; 3076 } 3077 if (BPF_CLASS(code) == BPF_LD && 3078 (BPF_MODE(code) == BPF_ABS || BPF_MODE(code) == BPF_IND)) 3079 subprog[cur_subprog].has_ld_abs = true; 3080 if (BPF_CLASS(code) != BPF_JMP && BPF_CLASS(code) != BPF_JMP32) 3081 goto next; 3082 if (BPF_OP(code) == BPF_EXIT || BPF_OP(code) == BPF_CALL) 3083 goto next; 3084 if (code == (BPF_JMP32 | BPF_JA)) 3085 off = i + insn[i].imm + 1; 3086 else 3087 off = i + insn[i].off + 1; 3088 if (off < subprog_start || off >= subprog_end) { 3089 verbose(env, "jump out of range from insn %d to %d\n", i, off); 3090 return -EINVAL; 3091 } 3092 next: 3093 if (i == subprog_end - 1) { 3094 /* to avoid fall-through from one subprog into another 3095 * the last insn of the subprog should be either exit 3096 * or unconditional jump back 3097 */ 3098 if (code != (BPF_JMP | BPF_EXIT) && 3099 code != (BPF_JMP32 | BPF_JA) && 3100 code != (BPF_JMP | BPF_JA)) { 3101 verbose(env, "last insn is not an exit or jmp\n"); 3102 return -EINVAL; 3103 } 3104 subprog_start = subprog_end; 3105 cur_subprog++; 3106 if (cur_subprog < env->subprog_cnt) 3107 subprog_end = subprog[cur_subprog + 1].start; 3108 } 3109 } 3110 return 0; 3111 } 3112 3113 /* Parentage chain of this register (or stack slot) should take care of all 3114 * issues like callee-saved registers, stack slot allocation time, etc. 3115 */ 3116 static int mark_reg_read(struct bpf_verifier_env *env, 3117 const struct bpf_reg_state *state, 3118 struct bpf_reg_state *parent, u8 flag) 3119 { 3120 bool writes = parent == state->parent; /* Observe write marks */ 3121 int cnt = 0; 3122 3123 while (parent) { 3124 /* if read wasn't screened by an earlier write ... */ 3125 if (writes && state->live & REG_LIVE_WRITTEN) 3126 break; 3127 if (parent->live & REG_LIVE_DONE) { 3128 verbose(env, "verifier BUG type %s var_off %lld off %d\n", 3129 reg_type_str(env, parent->type), 3130 parent->var_off.value, parent->off); 3131 return -EFAULT; 3132 } 3133 /* The first condition is more likely to be true than the 3134 * second, checked it first. 3135 */ 3136 if ((parent->live & REG_LIVE_READ) == flag || 3137 parent->live & REG_LIVE_READ64) 3138 /* The parentage chain never changes and 3139 * this parent was already marked as LIVE_READ. 3140 * There is no need to keep walking the chain again and 3141 * keep re-marking all parents as LIVE_READ. 3142 * This case happens when the same register is read 3143 * multiple times without writes into it in-between. 3144 * Also, if parent has the stronger REG_LIVE_READ64 set, 3145 * then no need to set the weak REG_LIVE_READ32. 3146 */ 3147 break; 3148 /* ... then we depend on parent's value */ 3149 parent->live |= flag; 3150 /* REG_LIVE_READ64 overrides REG_LIVE_READ32. */ 3151 if (flag == REG_LIVE_READ64) 3152 parent->live &= ~REG_LIVE_READ32; 3153 state = parent; 3154 parent = state->parent; 3155 writes = true; 3156 cnt++; 3157 } 3158 3159 if (env->longest_mark_read_walk < cnt) 3160 env->longest_mark_read_walk = cnt; 3161 return 0; 3162 } 3163 3164 static int mark_dynptr_read(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 3165 { 3166 struct bpf_func_state *state = func(env, reg); 3167 int spi, ret; 3168 3169 /* For CONST_PTR_TO_DYNPTR, it must have already been done by 3170 * check_reg_arg in check_helper_call and mark_btf_func_reg_size in 3171 * check_kfunc_call. 3172 */ 3173 if (reg->type == CONST_PTR_TO_DYNPTR) 3174 return 0; 3175 spi = dynptr_get_spi(env, reg); 3176 if (spi < 0) 3177 return spi; 3178 /* Caller ensures dynptr is valid and initialized, which means spi is in 3179 * bounds and spi is the first dynptr slot. Simply mark stack slot as 3180 * read. 3181 */ 3182 ret = mark_reg_read(env, &state->stack[spi].spilled_ptr, 3183 state->stack[spi].spilled_ptr.parent, REG_LIVE_READ64); 3184 if (ret) 3185 return ret; 3186 return mark_reg_read(env, &state->stack[spi - 1].spilled_ptr, 3187 state->stack[spi - 1].spilled_ptr.parent, REG_LIVE_READ64); 3188 } 3189 3190 static int mark_iter_read(struct bpf_verifier_env *env, struct bpf_reg_state *reg, 3191 int spi, int nr_slots) 3192 { 3193 struct bpf_func_state *state = func(env, reg); 3194 int err, i; 3195 3196 for (i = 0; i < nr_slots; i++) { 3197 struct bpf_reg_state *st = &state->stack[spi - i].spilled_ptr; 3198 3199 err = mark_reg_read(env, st, st->parent, REG_LIVE_READ64); 3200 if (err) 3201 return err; 3202 3203 mark_stack_slot_scratched(env, spi - i); 3204 } 3205 3206 return 0; 3207 } 3208 3209 /* This function is supposed to be used by the following 32-bit optimization 3210 * code only. It returns TRUE if the source or destination register operates 3211 * on 64-bit, otherwise return FALSE. 3212 */ 3213 static bool is_reg64(struct bpf_verifier_env *env, struct bpf_insn *insn, 3214 u32 regno, struct bpf_reg_state *reg, enum reg_arg_type t) 3215 { 3216 u8 code, class, op; 3217 3218 code = insn->code; 3219 class = BPF_CLASS(code); 3220 op = BPF_OP(code); 3221 if (class == BPF_JMP) { 3222 /* BPF_EXIT for "main" will reach here. Return TRUE 3223 * conservatively. 3224 */ 3225 if (op == BPF_EXIT) 3226 return true; 3227 if (op == BPF_CALL) { 3228 /* BPF to BPF call will reach here because of marking 3229 * caller saved clobber with DST_OP_NO_MARK for which we 3230 * don't care the register def because they are anyway 3231 * marked as NOT_INIT already. 3232 */ 3233 if (insn->src_reg == BPF_PSEUDO_CALL) 3234 return false; 3235 /* Helper call will reach here because of arg type 3236 * check, conservatively return TRUE. 3237 */ 3238 if (t == SRC_OP) 3239 return true; 3240 3241 return false; 3242 } 3243 } 3244 3245 if (class == BPF_ALU64 && op == BPF_END && (insn->imm == 16 || insn->imm == 32)) 3246 return false; 3247 3248 if (class == BPF_ALU64 || class == BPF_JMP || 3249 (class == BPF_ALU && op == BPF_END && insn->imm == 64)) 3250 return true; 3251 3252 if (class == BPF_ALU || class == BPF_JMP32) 3253 return false; 3254 3255 if (class == BPF_LDX) { 3256 if (t != SRC_OP) 3257 return BPF_SIZE(code) == BPF_DW; 3258 /* LDX source must be ptr. */ 3259 return true; 3260 } 3261 3262 if (class == BPF_STX) { 3263 /* BPF_STX (including atomic variants) has multiple source 3264 * operands, one of which is a ptr. Check whether the caller is 3265 * asking about it. 3266 */ 3267 if (t == SRC_OP && reg->type != SCALAR_VALUE) 3268 return true; 3269 return BPF_SIZE(code) == BPF_DW; 3270 } 3271 3272 if (class == BPF_LD) { 3273 u8 mode = BPF_MODE(code); 3274 3275 /* LD_IMM64 */ 3276 if (mode == BPF_IMM) 3277 return true; 3278 3279 /* Both LD_IND and LD_ABS return 32-bit data. */ 3280 if (t != SRC_OP) 3281 return false; 3282 3283 /* Implicit ctx ptr. */ 3284 if (regno == BPF_REG_6) 3285 return true; 3286 3287 /* Explicit source could be any width. */ 3288 return true; 3289 } 3290 3291 if (class == BPF_ST) 3292 /* The only source register for BPF_ST is a ptr. */ 3293 return true; 3294 3295 /* Conservatively return true at default. */ 3296 return true; 3297 } 3298 3299 /* Return the regno defined by the insn, or -1. */ 3300 static int insn_def_regno(const struct bpf_insn *insn) 3301 { 3302 switch (BPF_CLASS(insn->code)) { 3303 case BPF_JMP: 3304 case BPF_JMP32: 3305 case BPF_ST: 3306 return -1; 3307 case BPF_STX: 3308 if (BPF_MODE(insn->code) == BPF_ATOMIC && 3309 (insn->imm & BPF_FETCH)) { 3310 if (insn->imm == BPF_CMPXCHG) 3311 return BPF_REG_0; 3312 else 3313 return insn->src_reg; 3314 } else { 3315 return -1; 3316 } 3317 default: 3318 return insn->dst_reg; 3319 } 3320 } 3321 3322 /* Return TRUE if INSN has defined any 32-bit value explicitly. */ 3323 static bool insn_has_def32(struct bpf_verifier_env *env, struct bpf_insn *insn) 3324 { 3325 int dst_reg = insn_def_regno(insn); 3326 3327 if (dst_reg == -1) 3328 return false; 3329 3330 return !is_reg64(env, insn, dst_reg, NULL, DST_OP); 3331 } 3332 3333 static void mark_insn_zext(struct bpf_verifier_env *env, 3334 struct bpf_reg_state *reg) 3335 { 3336 s32 def_idx = reg->subreg_def; 3337 3338 if (def_idx == DEF_NOT_SUBREG) 3339 return; 3340 3341 env->insn_aux_data[def_idx - 1].zext_dst = true; 3342 /* The dst will be zero extended, so won't be sub-register anymore. */ 3343 reg->subreg_def = DEF_NOT_SUBREG; 3344 } 3345 3346 static int __check_reg_arg(struct bpf_verifier_env *env, struct bpf_reg_state *regs, u32 regno, 3347 enum reg_arg_type t) 3348 { 3349 struct bpf_insn *insn = env->prog->insnsi + env->insn_idx; 3350 struct bpf_reg_state *reg; 3351 bool rw64; 3352 3353 if (regno >= MAX_BPF_REG) { 3354 verbose(env, "R%d is invalid\n", regno); 3355 return -EINVAL; 3356 } 3357 3358 mark_reg_scratched(env, regno); 3359 3360 reg = ®s[regno]; 3361 rw64 = is_reg64(env, insn, regno, reg, t); 3362 if (t == SRC_OP) { 3363 /* check whether register used as source operand can be read */ 3364 if (reg->type == NOT_INIT) { 3365 verbose(env, "R%d !read_ok\n", regno); 3366 return -EACCES; 3367 } 3368 /* We don't need to worry about FP liveness because it's read-only */ 3369 if (regno == BPF_REG_FP) 3370 return 0; 3371 3372 if (rw64) 3373 mark_insn_zext(env, reg); 3374 3375 return mark_reg_read(env, reg, reg->parent, 3376 rw64 ? REG_LIVE_READ64 : REG_LIVE_READ32); 3377 } else { 3378 /* check whether register used as dest operand can be written to */ 3379 if (regno == BPF_REG_FP) { 3380 verbose(env, "frame pointer is read only\n"); 3381 return -EACCES; 3382 } 3383 reg->live |= REG_LIVE_WRITTEN; 3384 reg->subreg_def = rw64 ? DEF_NOT_SUBREG : env->insn_idx + 1; 3385 if (t == DST_OP) 3386 mark_reg_unknown(env, regs, regno); 3387 } 3388 return 0; 3389 } 3390 3391 static int check_reg_arg(struct bpf_verifier_env *env, u32 regno, 3392 enum reg_arg_type t) 3393 { 3394 struct bpf_verifier_state *vstate = env->cur_state; 3395 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 3396 3397 return __check_reg_arg(env, state->regs, regno, t); 3398 } 3399 3400 static int insn_stack_access_flags(int frameno, int spi) 3401 { 3402 return INSN_F_STACK_ACCESS | (spi << INSN_F_SPI_SHIFT) | frameno; 3403 } 3404 3405 static int insn_stack_access_spi(int insn_flags) 3406 { 3407 return (insn_flags >> INSN_F_SPI_SHIFT) & INSN_F_SPI_MASK; 3408 } 3409 3410 static int insn_stack_access_frameno(int insn_flags) 3411 { 3412 return insn_flags & INSN_F_FRAMENO_MASK; 3413 } 3414 3415 static void mark_jmp_point(struct bpf_verifier_env *env, int idx) 3416 { 3417 env->insn_aux_data[idx].jmp_point = true; 3418 } 3419 3420 static bool is_jmp_point(struct bpf_verifier_env *env, int insn_idx) 3421 { 3422 return env->insn_aux_data[insn_idx].jmp_point; 3423 } 3424 3425 /* for any branch, call, exit record the history of jmps in the given state */ 3426 static int push_jmp_history(struct bpf_verifier_env *env, struct bpf_verifier_state *cur, 3427 int insn_flags) 3428 { 3429 u32 cnt = cur->jmp_history_cnt; 3430 struct bpf_jmp_history_entry *p; 3431 size_t alloc_size; 3432 3433 /* combine instruction flags if we already recorded this instruction */ 3434 if (env->cur_hist_ent) { 3435 /* atomic instructions push insn_flags twice, for READ and 3436 * WRITE sides, but they should agree on stack slot 3437 */ 3438 WARN_ONCE((env->cur_hist_ent->flags & insn_flags) && 3439 (env->cur_hist_ent->flags & insn_flags) != insn_flags, 3440 "verifier insn history bug: insn_idx %d cur flags %x new flags %x\n", 3441 env->insn_idx, env->cur_hist_ent->flags, insn_flags); 3442 env->cur_hist_ent->flags |= insn_flags; 3443 return 0; 3444 } 3445 3446 cnt++; 3447 alloc_size = kmalloc_size_roundup(size_mul(cnt, sizeof(*p))); 3448 p = krealloc(cur->jmp_history, alloc_size, GFP_USER); 3449 if (!p) 3450 return -ENOMEM; 3451 cur->jmp_history = p; 3452 3453 p = &cur->jmp_history[cnt - 1]; 3454 p->idx = env->insn_idx; 3455 p->prev_idx = env->prev_insn_idx; 3456 p->flags = insn_flags; 3457 cur->jmp_history_cnt = cnt; 3458 env->cur_hist_ent = p; 3459 3460 return 0; 3461 } 3462 3463 static struct bpf_jmp_history_entry *get_jmp_hist_entry(struct bpf_verifier_state *st, 3464 u32 hist_end, int insn_idx) 3465 { 3466 if (hist_end > 0 && st->jmp_history[hist_end - 1].idx == insn_idx) 3467 return &st->jmp_history[hist_end - 1]; 3468 return NULL; 3469 } 3470 3471 /* Backtrack one insn at a time. If idx is not at the top of recorded 3472 * history then previous instruction came from straight line execution. 3473 * Return -ENOENT if we exhausted all instructions within given state. 3474 * 3475 * It's legal to have a bit of a looping with the same starting and ending 3476 * insn index within the same state, e.g.: 3->4->5->3, so just because current 3477 * instruction index is the same as state's first_idx doesn't mean we are 3478 * done. If there is still some jump history left, we should keep going. We 3479 * need to take into account that we might have a jump history between given 3480 * state's parent and itself, due to checkpointing. In this case, we'll have 3481 * history entry recording a jump from last instruction of parent state and 3482 * first instruction of given state. 3483 */ 3484 static int get_prev_insn_idx(struct bpf_verifier_state *st, int i, 3485 u32 *history) 3486 { 3487 u32 cnt = *history; 3488 3489 if (i == st->first_insn_idx) { 3490 if (cnt == 0) 3491 return -ENOENT; 3492 if (cnt == 1 && st->jmp_history[0].idx == i) 3493 return -ENOENT; 3494 } 3495 3496 if (cnt && st->jmp_history[cnt - 1].idx == i) { 3497 i = st->jmp_history[cnt - 1].prev_idx; 3498 (*history)--; 3499 } else { 3500 i--; 3501 } 3502 return i; 3503 } 3504 3505 static const char *disasm_kfunc_name(void *data, const struct bpf_insn *insn) 3506 { 3507 const struct btf_type *func; 3508 struct btf *desc_btf; 3509 3510 if (insn->src_reg != BPF_PSEUDO_KFUNC_CALL) 3511 return NULL; 3512 3513 desc_btf = find_kfunc_desc_btf(data, insn->off); 3514 if (IS_ERR(desc_btf)) 3515 return "<error>"; 3516 3517 func = btf_type_by_id(desc_btf, insn->imm); 3518 return btf_name_by_offset(desc_btf, func->name_off); 3519 } 3520 3521 static inline void bt_init(struct backtrack_state *bt, u32 frame) 3522 { 3523 bt->frame = frame; 3524 } 3525 3526 static inline void bt_reset(struct backtrack_state *bt) 3527 { 3528 struct bpf_verifier_env *env = bt->env; 3529 3530 memset(bt, 0, sizeof(*bt)); 3531 bt->env = env; 3532 } 3533 3534 static inline u32 bt_empty(struct backtrack_state *bt) 3535 { 3536 u64 mask = 0; 3537 int i; 3538 3539 for (i = 0; i <= bt->frame; i++) 3540 mask |= bt->reg_masks[i] | bt->stack_masks[i]; 3541 3542 return mask == 0; 3543 } 3544 3545 static inline int bt_subprog_enter(struct backtrack_state *bt) 3546 { 3547 if (bt->frame == MAX_CALL_FRAMES - 1) { 3548 verbose(bt->env, "BUG subprog enter from frame %d\n", bt->frame); 3549 WARN_ONCE(1, "verifier backtracking bug"); 3550 return -EFAULT; 3551 } 3552 bt->frame++; 3553 return 0; 3554 } 3555 3556 static inline int bt_subprog_exit(struct backtrack_state *bt) 3557 { 3558 if (bt->frame == 0) { 3559 verbose(bt->env, "BUG subprog exit from frame 0\n"); 3560 WARN_ONCE(1, "verifier backtracking bug"); 3561 return -EFAULT; 3562 } 3563 bt->frame--; 3564 return 0; 3565 } 3566 3567 static inline void bt_set_frame_reg(struct backtrack_state *bt, u32 frame, u32 reg) 3568 { 3569 bt->reg_masks[frame] |= 1 << reg; 3570 } 3571 3572 static inline void bt_clear_frame_reg(struct backtrack_state *bt, u32 frame, u32 reg) 3573 { 3574 bt->reg_masks[frame] &= ~(1 << reg); 3575 } 3576 3577 static inline void bt_set_reg(struct backtrack_state *bt, u32 reg) 3578 { 3579 bt_set_frame_reg(bt, bt->frame, reg); 3580 } 3581 3582 static inline void bt_clear_reg(struct backtrack_state *bt, u32 reg) 3583 { 3584 bt_clear_frame_reg(bt, bt->frame, reg); 3585 } 3586 3587 static inline void bt_set_frame_slot(struct backtrack_state *bt, u32 frame, u32 slot) 3588 { 3589 bt->stack_masks[frame] |= 1ull << slot; 3590 } 3591 3592 static inline void bt_clear_frame_slot(struct backtrack_state *bt, u32 frame, u32 slot) 3593 { 3594 bt->stack_masks[frame] &= ~(1ull << slot); 3595 } 3596 3597 static inline void bt_set_slot(struct backtrack_state *bt, u32 slot) 3598 { 3599 bt_set_frame_slot(bt, bt->frame, slot); 3600 } 3601 3602 static inline void bt_clear_slot(struct backtrack_state *bt, u32 slot) 3603 { 3604 bt_clear_frame_slot(bt, bt->frame, slot); 3605 } 3606 3607 static inline u32 bt_frame_reg_mask(struct backtrack_state *bt, u32 frame) 3608 { 3609 return bt->reg_masks[frame]; 3610 } 3611 3612 static inline u32 bt_reg_mask(struct backtrack_state *bt) 3613 { 3614 return bt->reg_masks[bt->frame]; 3615 } 3616 3617 static inline u64 bt_frame_stack_mask(struct backtrack_state *bt, u32 frame) 3618 { 3619 return bt->stack_masks[frame]; 3620 } 3621 3622 static inline u64 bt_stack_mask(struct backtrack_state *bt) 3623 { 3624 return bt->stack_masks[bt->frame]; 3625 } 3626 3627 static inline bool bt_is_reg_set(struct backtrack_state *bt, u32 reg) 3628 { 3629 return bt->reg_masks[bt->frame] & (1 << reg); 3630 } 3631 3632 static inline bool bt_is_frame_slot_set(struct backtrack_state *bt, u32 frame, u32 slot) 3633 { 3634 return bt->stack_masks[frame] & (1ull << slot); 3635 } 3636 3637 static inline bool bt_is_slot_set(struct backtrack_state *bt, u32 slot) 3638 { 3639 return bt_is_frame_slot_set(bt, bt->frame, slot); 3640 } 3641 3642 /* format registers bitmask, e.g., "r0,r2,r4" for 0x15 mask */ 3643 static void fmt_reg_mask(char *buf, ssize_t buf_sz, u32 reg_mask) 3644 { 3645 DECLARE_BITMAP(mask, 64); 3646 bool first = true; 3647 int i, n; 3648 3649 buf[0] = '\0'; 3650 3651 bitmap_from_u64(mask, reg_mask); 3652 for_each_set_bit(i, mask, 32) { 3653 n = snprintf(buf, buf_sz, "%sr%d", first ? "" : ",", i); 3654 first = false; 3655 buf += n; 3656 buf_sz -= n; 3657 if (buf_sz < 0) 3658 break; 3659 } 3660 } 3661 /* format stack slots bitmask, e.g., "-8,-24,-40" for 0x15 mask */ 3662 static void fmt_stack_mask(char *buf, ssize_t buf_sz, u64 stack_mask) 3663 { 3664 DECLARE_BITMAP(mask, 64); 3665 bool first = true; 3666 int i, n; 3667 3668 buf[0] = '\0'; 3669 3670 bitmap_from_u64(mask, stack_mask); 3671 for_each_set_bit(i, mask, 64) { 3672 n = snprintf(buf, buf_sz, "%s%d", first ? "" : ",", -(i + 1) * 8); 3673 first = false; 3674 buf += n; 3675 buf_sz -= n; 3676 if (buf_sz < 0) 3677 break; 3678 } 3679 } 3680 3681 static bool calls_callback(struct bpf_verifier_env *env, int insn_idx); 3682 3683 /* For given verifier state backtrack_insn() is called from the last insn to 3684 * the first insn. Its purpose is to compute a bitmask of registers and 3685 * stack slots that needs precision in the parent verifier state. 3686 * 3687 * @idx is an index of the instruction we are currently processing; 3688 * @subseq_idx is an index of the subsequent instruction that: 3689 * - *would be* executed next, if jump history is viewed in forward order; 3690 * - *was* processed previously during backtracking. 3691 */ 3692 static int backtrack_insn(struct bpf_verifier_env *env, int idx, int subseq_idx, 3693 struct bpf_jmp_history_entry *hist, struct backtrack_state *bt) 3694 { 3695 const struct bpf_insn_cbs cbs = { 3696 .cb_call = disasm_kfunc_name, 3697 .cb_print = verbose, 3698 .private_data = env, 3699 }; 3700 struct bpf_insn *insn = env->prog->insnsi + idx; 3701 u8 class = BPF_CLASS(insn->code); 3702 u8 opcode = BPF_OP(insn->code); 3703 u8 mode = BPF_MODE(insn->code); 3704 u32 dreg = insn->dst_reg; 3705 u32 sreg = insn->src_reg; 3706 u32 spi, i, fr; 3707 3708 if (insn->code == 0) 3709 return 0; 3710 if (env->log.level & BPF_LOG_LEVEL2) { 3711 fmt_reg_mask(env->tmp_str_buf, TMP_STR_BUF_LEN, bt_reg_mask(bt)); 3712 verbose(env, "mark_precise: frame%d: regs=%s ", 3713 bt->frame, env->tmp_str_buf); 3714 fmt_stack_mask(env->tmp_str_buf, TMP_STR_BUF_LEN, bt_stack_mask(bt)); 3715 verbose(env, "stack=%s before ", env->tmp_str_buf); 3716 verbose(env, "%d: ", idx); 3717 print_bpf_insn(&cbs, insn, env->allow_ptr_leaks); 3718 } 3719 3720 if (class == BPF_ALU || class == BPF_ALU64) { 3721 if (!bt_is_reg_set(bt, dreg)) 3722 return 0; 3723 if (opcode == BPF_END || opcode == BPF_NEG) { 3724 /* sreg is reserved and unused 3725 * dreg still need precision before this insn 3726 */ 3727 return 0; 3728 } else if (opcode == BPF_MOV) { 3729 if (BPF_SRC(insn->code) == BPF_X) { 3730 /* dreg = sreg or dreg = (s8, s16, s32)sreg 3731 * dreg needs precision after this insn 3732 * sreg needs precision before this insn 3733 */ 3734 bt_clear_reg(bt, dreg); 3735 if (sreg != BPF_REG_FP) 3736 bt_set_reg(bt, sreg); 3737 } else { 3738 /* dreg = K 3739 * dreg needs precision after this insn. 3740 * Corresponding register is already marked 3741 * as precise=true in this verifier state. 3742 * No further markings in parent are necessary 3743 */ 3744 bt_clear_reg(bt, dreg); 3745 } 3746 } else { 3747 if (BPF_SRC(insn->code) == BPF_X) { 3748 /* dreg += sreg 3749 * both dreg and sreg need precision 3750 * before this insn 3751 */ 3752 if (sreg != BPF_REG_FP) 3753 bt_set_reg(bt, sreg); 3754 } /* else dreg += K 3755 * dreg still needs precision before this insn 3756 */ 3757 } 3758 } else if (class == BPF_LDX) { 3759 if (!bt_is_reg_set(bt, dreg)) 3760 return 0; 3761 bt_clear_reg(bt, dreg); 3762 3763 /* scalars can only be spilled into stack w/o losing precision. 3764 * Load from any other memory can be zero extended. 3765 * The desire to keep that precision is already indicated 3766 * by 'precise' mark in corresponding register of this state. 3767 * No further tracking necessary. 3768 */ 3769 if (!hist || !(hist->flags & INSN_F_STACK_ACCESS)) 3770 return 0; 3771 /* dreg = *(u64 *)[fp - off] was a fill from the stack. 3772 * that [fp - off] slot contains scalar that needs to be 3773 * tracked with precision 3774 */ 3775 spi = insn_stack_access_spi(hist->flags); 3776 fr = insn_stack_access_frameno(hist->flags); 3777 bt_set_frame_slot(bt, fr, spi); 3778 } else if (class == BPF_STX || class == BPF_ST) { 3779 if (bt_is_reg_set(bt, dreg)) 3780 /* stx & st shouldn't be using _scalar_ dst_reg 3781 * to access memory. It means backtracking 3782 * encountered a case of pointer subtraction. 3783 */ 3784 return -ENOTSUPP; 3785 /* scalars can only be spilled into stack */ 3786 if (!hist || !(hist->flags & INSN_F_STACK_ACCESS)) 3787 return 0; 3788 spi = insn_stack_access_spi(hist->flags); 3789 fr = insn_stack_access_frameno(hist->flags); 3790 if (!bt_is_frame_slot_set(bt, fr, spi)) 3791 return 0; 3792 bt_clear_frame_slot(bt, fr, spi); 3793 if (class == BPF_STX) 3794 bt_set_reg(bt, sreg); 3795 } else if (class == BPF_JMP || class == BPF_JMP32) { 3796 if (bpf_pseudo_call(insn)) { 3797 int subprog_insn_idx, subprog; 3798 3799 subprog_insn_idx = idx + insn->imm + 1; 3800 subprog = find_subprog(env, subprog_insn_idx); 3801 if (subprog < 0) 3802 return -EFAULT; 3803 3804 if (subprog_is_global(env, subprog)) { 3805 /* check that jump history doesn't have any 3806 * extra instructions from subprog; the next 3807 * instruction after call to global subprog 3808 * should be literally next instruction in 3809 * caller program 3810 */ 3811 WARN_ONCE(idx + 1 != subseq_idx, "verifier backtracking bug"); 3812 /* r1-r5 are invalidated after subprog call, 3813 * so for global func call it shouldn't be set 3814 * anymore 3815 */ 3816 if (bt_reg_mask(bt) & BPF_REGMASK_ARGS) { 3817 verbose(env, "BUG regs %x\n", bt_reg_mask(bt)); 3818 WARN_ONCE(1, "verifier backtracking bug"); 3819 return -EFAULT; 3820 } 3821 /* global subprog always sets R0 */ 3822 bt_clear_reg(bt, BPF_REG_0); 3823 return 0; 3824 } else { 3825 /* static subprog call instruction, which 3826 * means that we are exiting current subprog, 3827 * so only r1-r5 could be still requested as 3828 * precise, r0 and r6-r10 or any stack slot in 3829 * the current frame should be zero by now 3830 */ 3831 if (bt_reg_mask(bt) & ~BPF_REGMASK_ARGS) { 3832 verbose(env, "BUG regs %x\n", bt_reg_mask(bt)); 3833 WARN_ONCE(1, "verifier backtracking bug"); 3834 return -EFAULT; 3835 } 3836 /* we are now tracking register spills correctly, 3837 * so any instance of leftover slots is a bug 3838 */ 3839 if (bt_stack_mask(bt) != 0) { 3840 verbose(env, "BUG stack slots %llx\n", bt_stack_mask(bt)); 3841 WARN_ONCE(1, "verifier backtracking bug (subprog leftover stack slots)"); 3842 return -EFAULT; 3843 } 3844 /* propagate r1-r5 to the caller */ 3845 for (i = BPF_REG_1; i <= BPF_REG_5; i++) { 3846 if (bt_is_reg_set(bt, i)) { 3847 bt_clear_reg(bt, i); 3848 bt_set_frame_reg(bt, bt->frame - 1, i); 3849 } 3850 } 3851 if (bt_subprog_exit(bt)) 3852 return -EFAULT; 3853 return 0; 3854 } 3855 } else if (is_sync_callback_calling_insn(insn) && idx != subseq_idx - 1) { 3856 /* exit from callback subprog to callback-calling helper or 3857 * kfunc call. Use idx/subseq_idx check to discern it from 3858 * straight line code backtracking. 3859 * Unlike the subprog call handling above, we shouldn't 3860 * propagate precision of r1-r5 (if any requested), as they are 3861 * not actually arguments passed directly to callback subprogs 3862 */ 3863 if (bt_reg_mask(bt) & ~BPF_REGMASK_ARGS) { 3864 verbose(env, "BUG regs %x\n", bt_reg_mask(bt)); 3865 WARN_ONCE(1, "verifier backtracking bug"); 3866 return -EFAULT; 3867 } 3868 if (bt_stack_mask(bt) != 0) { 3869 verbose(env, "BUG stack slots %llx\n", bt_stack_mask(bt)); 3870 WARN_ONCE(1, "verifier backtracking bug (callback leftover stack slots)"); 3871 return -EFAULT; 3872 } 3873 /* clear r1-r5 in callback subprog's mask */ 3874 for (i = BPF_REG_1; i <= BPF_REG_5; i++) 3875 bt_clear_reg(bt, i); 3876 if (bt_subprog_exit(bt)) 3877 return -EFAULT; 3878 return 0; 3879 } else if (opcode == BPF_CALL) { 3880 /* kfunc with imm==0 is invalid and fixup_kfunc_call will 3881 * catch this error later. Make backtracking conservative 3882 * with ENOTSUPP. 3883 */ 3884 if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL && insn->imm == 0) 3885 return -ENOTSUPP; 3886 /* regular helper call sets R0 */ 3887 bt_clear_reg(bt, BPF_REG_0); 3888 if (bt_reg_mask(bt) & BPF_REGMASK_ARGS) { 3889 /* if backtracing was looking for registers R1-R5 3890 * they should have been found already. 3891 */ 3892 verbose(env, "BUG regs %x\n", bt_reg_mask(bt)); 3893 WARN_ONCE(1, "verifier backtracking bug"); 3894 return -EFAULT; 3895 } 3896 } else if (opcode == BPF_EXIT) { 3897 bool r0_precise; 3898 3899 /* Backtracking to a nested function call, 'idx' is a part of 3900 * the inner frame 'subseq_idx' is a part of the outer frame. 3901 * In case of a regular function call, instructions giving 3902 * precision to registers R1-R5 should have been found already. 3903 * In case of a callback, it is ok to have R1-R5 marked for 3904 * backtracking, as these registers are set by the function 3905 * invoking callback. 3906 */ 3907 if (subseq_idx >= 0 && calls_callback(env, subseq_idx)) 3908 for (i = BPF_REG_1; i <= BPF_REG_5; i++) 3909 bt_clear_reg(bt, i); 3910 if (bt_reg_mask(bt) & BPF_REGMASK_ARGS) { 3911 verbose(env, "BUG regs %x\n", bt_reg_mask(bt)); 3912 WARN_ONCE(1, "verifier backtracking bug"); 3913 return -EFAULT; 3914 } 3915 3916 /* BPF_EXIT in subprog or callback always returns 3917 * right after the call instruction, so by checking 3918 * whether the instruction at subseq_idx-1 is subprog 3919 * call or not we can distinguish actual exit from 3920 * *subprog* from exit from *callback*. In the former 3921 * case, we need to propagate r0 precision, if 3922 * necessary. In the former we never do that. 3923 */ 3924 r0_precise = subseq_idx - 1 >= 0 && 3925 bpf_pseudo_call(&env->prog->insnsi[subseq_idx - 1]) && 3926 bt_is_reg_set(bt, BPF_REG_0); 3927 3928 bt_clear_reg(bt, BPF_REG_0); 3929 if (bt_subprog_enter(bt)) 3930 return -EFAULT; 3931 3932 if (r0_precise) 3933 bt_set_reg(bt, BPF_REG_0); 3934 /* r6-r9 and stack slots will stay set in caller frame 3935 * bitmasks until we return back from callee(s) 3936 */ 3937 return 0; 3938 } else if (BPF_SRC(insn->code) == BPF_X) { 3939 if (!bt_is_reg_set(bt, dreg) && !bt_is_reg_set(bt, sreg)) 3940 return 0; 3941 /* dreg <cond> sreg 3942 * Both dreg and sreg need precision before 3943 * this insn. If only sreg was marked precise 3944 * before it would be equally necessary to 3945 * propagate it to dreg. 3946 */ 3947 bt_set_reg(bt, dreg); 3948 bt_set_reg(bt, sreg); 3949 /* else dreg <cond> K 3950 * Only dreg still needs precision before 3951 * this insn, so for the K-based conditional 3952 * there is nothing new to be marked. 3953 */ 3954 } 3955 } else if (class == BPF_LD) { 3956 if (!bt_is_reg_set(bt, dreg)) 3957 return 0; 3958 bt_clear_reg(bt, dreg); 3959 /* It's ld_imm64 or ld_abs or ld_ind. 3960 * For ld_imm64 no further tracking of precision 3961 * into parent is necessary 3962 */ 3963 if (mode == BPF_IND || mode == BPF_ABS) 3964 /* to be analyzed */ 3965 return -ENOTSUPP; 3966 } 3967 return 0; 3968 } 3969 3970 /* the scalar precision tracking algorithm: 3971 * . at the start all registers have precise=false. 3972 * . scalar ranges are tracked as normal through alu and jmp insns. 3973 * . once precise value of the scalar register is used in: 3974 * . ptr + scalar alu 3975 * . if (scalar cond K|scalar) 3976 * . helper_call(.., scalar, ...) where ARG_CONST is expected 3977 * backtrack through the verifier states and mark all registers and 3978 * stack slots with spilled constants that these scalar regisers 3979 * should be precise. 3980 * . during state pruning two registers (or spilled stack slots) 3981 * are equivalent if both are not precise. 3982 * 3983 * Note the verifier cannot simply walk register parentage chain, 3984 * since many different registers and stack slots could have been 3985 * used to compute single precise scalar. 3986 * 3987 * The approach of starting with precise=true for all registers and then 3988 * backtrack to mark a register as not precise when the verifier detects 3989 * that program doesn't care about specific value (e.g., when helper 3990 * takes register as ARG_ANYTHING parameter) is not safe. 3991 * 3992 * It's ok to walk single parentage chain of the verifier states. 3993 * It's possible that this backtracking will go all the way till 1st insn. 3994 * All other branches will be explored for needing precision later. 3995 * 3996 * The backtracking needs to deal with cases like: 3997 * R8=map_value(id=0,off=0,ks=4,vs=1952,imm=0) R9_w=map_value(id=0,off=40,ks=4,vs=1952,imm=0) 3998 * r9 -= r8 3999 * r5 = r9 4000 * if r5 > 0x79f goto pc+7 4001 * R5_w=inv(id=0,umax_value=1951,var_off=(0x0; 0x7ff)) 4002 * r5 += 1 4003 * ... 4004 * call bpf_perf_event_output#25 4005 * where .arg5_type = ARG_CONST_SIZE_OR_ZERO 4006 * 4007 * and this case: 4008 * r6 = 1 4009 * call foo // uses callee's r6 inside to compute r0 4010 * r0 += r6 4011 * if r0 == 0 goto 4012 * 4013 * to track above reg_mask/stack_mask needs to be independent for each frame. 4014 * 4015 * Also if parent's curframe > frame where backtracking started, 4016 * the verifier need to mark registers in both frames, otherwise callees 4017 * may incorrectly prune callers. This is similar to 4018 * commit 7640ead93924 ("bpf: verifier: make sure callees don't prune with caller differences") 4019 * 4020 * For now backtracking falls back into conservative marking. 4021 */ 4022 static void mark_all_scalars_precise(struct bpf_verifier_env *env, 4023 struct bpf_verifier_state *st) 4024 { 4025 struct bpf_func_state *func; 4026 struct bpf_reg_state *reg; 4027 int i, j; 4028 4029 if (env->log.level & BPF_LOG_LEVEL2) { 4030 verbose(env, "mark_precise: frame%d: falling back to forcing all scalars precise\n", 4031 st->curframe); 4032 } 4033 4034 /* big hammer: mark all scalars precise in this path. 4035 * pop_stack may still get !precise scalars. 4036 * We also skip current state and go straight to first parent state, 4037 * because precision markings in current non-checkpointed state are 4038 * not needed. See why in the comment in __mark_chain_precision below. 4039 */ 4040 for (st = st->parent; st; st = st->parent) { 4041 for (i = 0; i <= st->curframe; i++) { 4042 func = st->frame[i]; 4043 for (j = 0; j < BPF_REG_FP; j++) { 4044 reg = &func->regs[j]; 4045 if (reg->type != SCALAR_VALUE || reg->precise) 4046 continue; 4047 reg->precise = true; 4048 if (env->log.level & BPF_LOG_LEVEL2) { 4049 verbose(env, "force_precise: frame%d: forcing r%d to be precise\n", 4050 i, j); 4051 } 4052 } 4053 for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) { 4054 if (!is_spilled_reg(&func->stack[j])) 4055 continue; 4056 reg = &func->stack[j].spilled_ptr; 4057 if (reg->type != SCALAR_VALUE || reg->precise) 4058 continue; 4059 reg->precise = true; 4060 if (env->log.level & BPF_LOG_LEVEL2) { 4061 verbose(env, "force_precise: frame%d: forcing fp%d to be precise\n", 4062 i, -(j + 1) * 8); 4063 } 4064 } 4065 } 4066 } 4067 } 4068 4069 static void mark_all_scalars_imprecise(struct bpf_verifier_env *env, struct bpf_verifier_state *st) 4070 { 4071 struct bpf_func_state *func; 4072 struct bpf_reg_state *reg; 4073 int i, j; 4074 4075 for (i = 0; i <= st->curframe; i++) { 4076 func = st->frame[i]; 4077 for (j = 0; j < BPF_REG_FP; j++) { 4078 reg = &func->regs[j]; 4079 if (reg->type != SCALAR_VALUE) 4080 continue; 4081 reg->precise = false; 4082 } 4083 for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) { 4084 if (!is_spilled_reg(&func->stack[j])) 4085 continue; 4086 reg = &func->stack[j].spilled_ptr; 4087 if (reg->type != SCALAR_VALUE) 4088 continue; 4089 reg->precise = false; 4090 } 4091 } 4092 } 4093 4094 static bool idset_contains(struct bpf_idset *s, u32 id) 4095 { 4096 u32 i; 4097 4098 for (i = 0; i < s->count; ++i) 4099 if (s->ids[i] == id) 4100 return true; 4101 4102 return false; 4103 } 4104 4105 static int idset_push(struct bpf_idset *s, u32 id) 4106 { 4107 if (WARN_ON_ONCE(s->count >= ARRAY_SIZE(s->ids))) 4108 return -EFAULT; 4109 s->ids[s->count++] = id; 4110 return 0; 4111 } 4112 4113 static void idset_reset(struct bpf_idset *s) 4114 { 4115 s->count = 0; 4116 } 4117 4118 /* Collect a set of IDs for all registers currently marked as precise in env->bt. 4119 * Mark all registers with these IDs as precise. 4120 */ 4121 static int mark_precise_scalar_ids(struct bpf_verifier_env *env, struct bpf_verifier_state *st) 4122 { 4123 struct bpf_idset *precise_ids = &env->idset_scratch; 4124 struct backtrack_state *bt = &env->bt; 4125 struct bpf_func_state *func; 4126 struct bpf_reg_state *reg; 4127 DECLARE_BITMAP(mask, 64); 4128 int i, fr; 4129 4130 idset_reset(precise_ids); 4131 4132 for (fr = bt->frame; fr >= 0; fr--) { 4133 func = st->frame[fr]; 4134 4135 bitmap_from_u64(mask, bt_frame_reg_mask(bt, fr)); 4136 for_each_set_bit(i, mask, 32) { 4137 reg = &func->regs[i]; 4138 if (!reg->id || reg->type != SCALAR_VALUE) 4139 continue; 4140 if (idset_push(precise_ids, reg->id)) 4141 return -EFAULT; 4142 } 4143 4144 bitmap_from_u64(mask, bt_frame_stack_mask(bt, fr)); 4145 for_each_set_bit(i, mask, 64) { 4146 if (i >= func->allocated_stack / BPF_REG_SIZE) 4147 break; 4148 if (!is_spilled_scalar_reg(&func->stack[i])) 4149 continue; 4150 reg = &func->stack[i].spilled_ptr; 4151 if (!reg->id) 4152 continue; 4153 if (idset_push(precise_ids, reg->id)) 4154 return -EFAULT; 4155 } 4156 } 4157 4158 for (fr = 0; fr <= st->curframe; ++fr) { 4159 func = st->frame[fr]; 4160 4161 for (i = BPF_REG_0; i < BPF_REG_10; ++i) { 4162 reg = &func->regs[i]; 4163 if (!reg->id) 4164 continue; 4165 if (!idset_contains(precise_ids, reg->id)) 4166 continue; 4167 bt_set_frame_reg(bt, fr, i); 4168 } 4169 for (i = 0; i < func->allocated_stack / BPF_REG_SIZE; ++i) { 4170 if (!is_spilled_scalar_reg(&func->stack[i])) 4171 continue; 4172 reg = &func->stack[i].spilled_ptr; 4173 if (!reg->id) 4174 continue; 4175 if (!idset_contains(precise_ids, reg->id)) 4176 continue; 4177 bt_set_frame_slot(bt, fr, i); 4178 } 4179 } 4180 4181 return 0; 4182 } 4183 4184 /* 4185 * __mark_chain_precision() backtracks BPF program instruction sequence and 4186 * chain of verifier states making sure that register *regno* (if regno >= 0) 4187 * and/or stack slot *spi* (if spi >= 0) are marked as precisely tracked 4188 * SCALARS, as well as any other registers and slots that contribute to 4189 * a tracked state of given registers/stack slots, depending on specific BPF 4190 * assembly instructions (see backtrack_insns() for exact instruction handling 4191 * logic). This backtracking relies on recorded jmp_history and is able to 4192 * traverse entire chain of parent states. This process ends only when all the 4193 * necessary registers/slots and their transitive dependencies are marked as 4194 * precise. 4195 * 4196 * One important and subtle aspect is that precise marks *do not matter* in 4197 * the currently verified state (current state). It is important to understand 4198 * why this is the case. 4199 * 4200 * First, note that current state is the state that is not yet "checkpointed", 4201 * i.e., it is not yet put into env->explored_states, and it has no children 4202 * states as well. It's ephemeral, and can end up either a) being discarded if 4203 * compatible explored state is found at some point or BPF_EXIT instruction is 4204 * reached or b) checkpointed and put into env->explored_states, branching out 4205 * into one or more children states. 4206 * 4207 * In the former case, precise markings in current state are completely 4208 * ignored by state comparison code (see regsafe() for details). Only 4209 * checkpointed ("old") state precise markings are important, and if old 4210 * state's register/slot is precise, regsafe() assumes current state's 4211 * register/slot as precise and checks value ranges exactly and precisely. If 4212 * states turn out to be compatible, current state's necessary precise 4213 * markings and any required parent states' precise markings are enforced 4214 * after the fact with propagate_precision() logic, after the fact. But it's 4215 * important to realize that in this case, even after marking current state 4216 * registers/slots as precise, we immediately discard current state. So what 4217 * actually matters is any of the precise markings propagated into current 4218 * state's parent states, which are always checkpointed (due to b) case above). 4219 * As such, for scenario a) it doesn't matter if current state has precise 4220 * markings set or not. 4221 * 4222 * Now, for the scenario b), checkpointing and forking into child(ren) 4223 * state(s). Note that before current state gets to checkpointing step, any 4224 * processed instruction always assumes precise SCALAR register/slot 4225 * knowledge: if precise value or range is useful to prune jump branch, BPF 4226 * verifier takes this opportunity enthusiastically. Similarly, when 4227 * register's value is used to calculate offset or memory address, exact 4228 * knowledge of SCALAR range is assumed, checked, and enforced. So, similar to 4229 * what we mentioned above about state comparison ignoring precise markings 4230 * during state comparison, BPF verifier ignores and also assumes precise 4231 * markings *at will* during instruction verification process. But as verifier 4232 * assumes precision, it also propagates any precision dependencies across 4233 * parent states, which are not yet finalized, so can be further restricted 4234 * based on new knowledge gained from restrictions enforced by their children 4235 * states. This is so that once those parent states are finalized, i.e., when 4236 * they have no more active children state, state comparison logic in 4237 * is_state_visited() would enforce strict and precise SCALAR ranges, if 4238 * required for correctness. 4239 * 4240 * To build a bit more intuition, note also that once a state is checkpointed, 4241 * the path we took to get to that state is not important. This is crucial 4242 * property for state pruning. When state is checkpointed and finalized at 4243 * some instruction index, it can be correctly and safely used to "short 4244 * circuit" any *compatible* state that reaches exactly the same instruction 4245 * index. I.e., if we jumped to that instruction from a completely different 4246 * code path than original finalized state was derived from, it doesn't 4247 * matter, current state can be discarded because from that instruction 4248 * forward having a compatible state will ensure we will safely reach the 4249 * exit. States describe preconditions for further exploration, but completely 4250 * forget the history of how we got here. 4251 * 4252 * This also means that even if we needed precise SCALAR range to get to 4253 * finalized state, but from that point forward *that same* SCALAR register is 4254 * never used in a precise context (i.e., it's precise value is not needed for 4255 * correctness), it's correct and safe to mark such register as "imprecise" 4256 * (i.e., precise marking set to false). This is what we rely on when we do 4257 * not set precise marking in current state. If no child state requires 4258 * precision for any given SCALAR register, it's safe to dictate that it can 4259 * be imprecise. If any child state does require this register to be precise, 4260 * we'll mark it precise later retroactively during precise markings 4261 * propagation from child state to parent states. 4262 * 4263 * Skipping precise marking setting in current state is a mild version of 4264 * relying on the above observation. But we can utilize this property even 4265 * more aggressively by proactively forgetting any precise marking in the 4266 * current state (which we inherited from the parent state), right before we 4267 * checkpoint it and branch off into new child state. This is done by 4268 * mark_all_scalars_imprecise() to hopefully get more permissive and generic 4269 * finalized states which help in short circuiting more future states. 4270 */ 4271 static int __mark_chain_precision(struct bpf_verifier_env *env, int regno) 4272 { 4273 struct backtrack_state *bt = &env->bt; 4274 struct bpf_verifier_state *st = env->cur_state; 4275 int first_idx = st->first_insn_idx; 4276 int last_idx = env->insn_idx; 4277 int subseq_idx = -1; 4278 struct bpf_func_state *func; 4279 struct bpf_reg_state *reg; 4280 bool skip_first = true; 4281 int i, fr, err; 4282 4283 if (!env->bpf_capable) 4284 return 0; 4285 4286 /* set frame number from which we are starting to backtrack */ 4287 bt_init(bt, env->cur_state->curframe); 4288 4289 /* Do sanity checks against current state of register and/or stack 4290 * slot, but don't set precise flag in current state, as precision 4291 * tracking in the current state is unnecessary. 4292 */ 4293 func = st->frame[bt->frame]; 4294 if (regno >= 0) { 4295 reg = &func->regs[regno]; 4296 if (reg->type != SCALAR_VALUE) { 4297 WARN_ONCE(1, "backtracing misuse"); 4298 return -EFAULT; 4299 } 4300 bt_set_reg(bt, regno); 4301 } 4302 4303 if (bt_empty(bt)) 4304 return 0; 4305 4306 for (;;) { 4307 DECLARE_BITMAP(mask, 64); 4308 u32 history = st->jmp_history_cnt; 4309 struct bpf_jmp_history_entry *hist; 4310 4311 if (env->log.level & BPF_LOG_LEVEL2) { 4312 verbose(env, "mark_precise: frame%d: last_idx %d first_idx %d subseq_idx %d \n", 4313 bt->frame, last_idx, first_idx, subseq_idx); 4314 } 4315 4316 /* If some register with scalar ID is marked as precise, 4317 * make sure that all registers sharing this ID are also precise. 4318 * This is needed to estimate effect of find_equal_scalars(). 4319 * Do this at the last instruction of each state, 4320 * bpf_reg_state::id fields are valid for these instructions. 4321 * 4322 * Allows to track precision in situation like below: 4323 * 4324 * r2 = unknown value 4325 * ... 4326 * --- state #0 --- 4327 * ... 4328 * r1 = r2 // r1 and r2 now share the same ID 4329 * ... 4330 * --- state #1 {r1.id = A, r2.id = A} --- 4331 * ... 4332 * if (r2 > 10) goto exit; // find_equal_scalars() assigns range to r1 4333 * ... 4334 * --- state #2 {r1.id = A, r2.id = A} --- 4335 * r3 = r10 4336 * r3 += r1 // need to mark both r1 and r2 4337 */ 4338 if (mark_precise_scalar_ids(env, st)) 4339 return -EFAULT; 4340 4341 if (last_idx < 0) { 4342 /* we are at the entry into subprog, which 4343 * is expected for global funcs, but only if 4344 * requested precise registers are R1-R5 4345 * (which are global func's input arguments) 4346 */ 4347 if (st->curframe == 0 && 4348 st->frame[0]->subprogno > 0 && 4349 st->frame[0]->callsite == BPF_MAIN_FUNC && 4350 bt_stack_mask(bt) == 0 && 4351 (bt_reg_mask(bt) & ~BPF_REGMASK_ARGS) == 0) { 4352 bitmap_from_u64(mask, bt_reg_mask(bt)); 4353 for_each_set_bit(i, mask, 32) { 4354 reg = &st->frame[0]->regs[i]; 4355 bt_clear_reg(bt, i); 4356 if (reg->type == SCALAR_VALUE) 4357 reg->precise = true; 4358 } 4359 return 0; 4360 } 4361 4362 verbose(env, "BUG backtracking func entry subprog %d reg_mask %x stack_mask %llx\n", 4363 st->frame[0]->subprogno, bt_reg_mask(bt), bt_stack_mask(bt)); 4364 WARN_ONCE(1, "verifier backtracking bug"); 4365 return -EFAULT; 4366 } 4367 4368 for (i = last_idx;;) { 4369 if (skip_first) { 4370 err = 0; 4371 skip_first = false; 4372 } else { 4373 hist = get_jmp_hist_entry(st, history, i); 4374 err = backtrack_insn(env, i, subseq_idx, hist, bt); 4375 } 4376 if (err == -ENOTSUPP) { 4377 mark_all_scalars_precise(env, env->cur_state); 4378 bt_reset(bt); 4379 return 0; 4380 } else if (err) { 4381 return err; 4382 } 4383 if (bt_empty(bt)) 4384 /* Found assignment(s) into tracked register in this state. 4385 * Since this state is already marked, just return. 4386 * Nothing to be tracked further in the parent state. 4387 */ 4388 return 0; 4389 subseq_idx = i; 4390 i = get_prev_insn_idx(st, i, &history); 4391 if (i == -ENOENT) 4392 break; 4393 if (i >= env->prog->len) { 4394 /* This can happen if backtracking reached insn 0 4395 * and there are still reg_mask or stack_mask 4396 * to backtrack. 4397 * It means the backtracking missed the spot where 4398 * particular register was initialized with a constant. 4399 */ 4400 verbose(env, "BUG backtracking idx %d\n", i); 4401 WARN_ONCE(1, "verifier backtracking bug"); 4402 return -EFAULT; 4403 } 4404 } 4405 st = st->parent; 4406 if (!st) 4407 break; 4408 4409 for (fr = bt->frame; fr >= 0; fr--) { 4410 func = st->frame[fr]; 4411 bitmap_from_u64(mask, bt_frame_reg_mask(bt, fr)); 4412 for_each_set_bit(i, mask, 32) { 4413 reg = &func->regs[i]; 4414 if (reg->type != SCALAR_VALUE) { 4415 bt_clear_frame_reg(bt, fr, i); 4416 continue; 4417 } 4418 if (reg->precise) 4419 bt_clear_frame_reg(bt, fr, i); 4420 else 4421 reg->precise = true; 4422 } 4423 4424 bitmap_from_u64(mask, bt_frame_stack_mask(bt, fr)); 4425 for_each_set_bit(i, mask, 64) { 4426 if (i >= func->allocated_stack / BPF_REG_SIZE) { 4427 verbose(env, "BUG backtracking (stack slot %d, total slots %d)\n", 4428 i, func->allocated_stack / BPF_REG_SIZE); 4429 WARN_ONCE(1, "verifier backtracking bug (stack slot out of bounds)"); 4430 return -EFAULT; 4431 } 4432 4433 if (!is_spilled_scalar_reg(&func->stack[i])) { 4434 bt_clear_frame_slot(bt, fr, i); 4435 continue; 4436 } 4437 reg = &func->stack[i].spilled_ptr; 4438 if (reg->precise) 4439 bt_clear_frame_slot(bt, fr, i); 4440 else 4441 reg->precise = true; 4442 } 4443 if (env->log.level & BPF_LOG_LEVEL2) { 4444 fmt_reg_mask(env->tmp_str_buf, TMP_STR_BUF_LEN, 4445 bt_frame_reg_mask(bt, fr)); 4446 verbose(env, "mark_precise: frame%d: parent state regs=%s ", 4447 fr, env->tmp_str_buf); 4448 fmt_stack_mask(env->tmp_str_buf, TMP_STR_BUF_LEN, 4449 bt_frame_stack_mask(bt, fr)); 4450 verbose(env, "stack=%s: ", env->tmp_str_buf); 4451 print_verifier_state(env, func, true); 4452 } 4453 } 4454 4455 if (bt_empty(bt)) 4456 return 0; 4457 4458 subseq_idx = first_idx; 4459 last_idx = st->last_insn_idx; 4460 first_idx = st->first_insn_idx; 4461 } 4462 4463 /* if we still have requested precise regs or slots, we missed 4464 * something (e.g., stack access through non-r10 register), so 4465 * fallback to marking all precise 4466 */ 4467 if (!bt_empty(bt)) { 4468 mark_all_scalars_precise(env, env->cur_state); 4469 bt_reset(bt); 4470 } 4471 4472 return 0; 4473 } 4474 4475 int mark_chain_precision(struct bpf_verifier_env *env, int regno) 4476 { 4477 return __mark_chain_precision(env, regno); 4478 } 4479 4480 /* mark_chain_precision_batch() assumes that env->bt is set in the caller to 4481 * desired reg and stack masks across all relevant frames 4482 */ 4483 static int mark_chain_precision_batch(struct bpf_verifier_env *env) 4484 { 4485 return __mark_chain_precision(env, -1); 4486 } 4487 4488 static bool is_spillable_regtype(enum bpf_reg_type type) 4489 { 4490 switch (base_type(type)) { 4491 case PTR_TO_MAP_VALUE: 4492 case PTR_TO_STACK: 4493 case PTR_TO_CTX: 4494 case PTR_TO_PACKET: 4495 case PTR_TO_PACKET_META: 4496 case PTR_TO_PACKET_END: 4497 case PTR_TO_FLOW_KEYS: 4498 case CONST_PTR_TO_MAP: 4499 case PTR_TO_SOCKET: 4500 case PTR_TO_SOCK_COMMON: 4501 case PTR_TO_TCP_SOCK: 4502 case PTR_TO_XDP_SOCK: 4503 case PTR_TO_BTF_ID: 4504 case PTR_TO_BUF: 4505 case PTR_TO_MEM: 4506 case PTR_TO_FUNC: 4507 case PTR_TO_MAP_KEY: 4508 return true; 4509 default: 4510 return false; 4511 } 4512 } 4513 4514 /* Does this register contain a constant zero? */ 4515 static bool register_is_null(struct bpf_reg_state *reg) 4516 { 4517 return reg->type == SCALAR_VALUE && tnum_equals_const(reg->var_off, 0); 4518 } 4519 4520 static bool register_is_const(struct bpf_reg_state *reg) 4521 { 4522 return reg->type == SCALAR_VALUE && tnum_is_const(reg->var_off); 4523 } 4524 4525 static bool __is_scalar_unbounded(struct bpf_reg_state *reg) 4526 { 4527 return tnum_is_unknown(reg->var_off) && 4528 reg->smin_value == S64_MIN && reg->smax_value == S64_MAX && 4529 reg->umin_value == 0 && reg->umax_value == U64_MAX && 4530 reg->s32_min_value == S32_MIN && reg->s32_max_value == S32_MAX && 4531 reg->u32_min_value == 0 && reg->u32_max_value == U32_MAX; 4532 } 4533 4534 static bool register_is_bounded(struct bpf_reg_state *reg) 4535 { 4536 return reg->type == SCALAR_VALUE && !__is_scalar_unbounded(reg); 4537 } 4538 4539 static bool __is_pointer_value(bool allow_ptr_leaks, 4540 const struct bpf_reg_state *reg) 4541 { 4542 if (allow_ptr_leaks) 4543 return false; 4544 4545 return reg->type != SCALAR_VALUE; 4546 } 4547 4548 /* Copy src state preserving dst->parent and dst->live fields */ 4549 static void copy_register_state(struct bpf_reg_state *dst, const struct bpf_reg_state *src) 4550 { 4551 struct bpf_reg_state *parent = dst->parent; 4552 enum bpf_reg_liveness live = dst->live; 4553 4554 *dst = *src; 4555 dst->parent = parent; 4556 dst->live = live; 4557 } 4558 4559 static void save_register_state(struct bpf_func_state *state, 4560 int spi, struct bpf_reg_state *reg, 4561 int size) 4562 { 4563 int i; 4564 4565 copy_register_state(&state->stack[spi].spilled_ptr, reg); 4566 if (size == BPF_REG_SIZE) 4567 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN; 4568 4569 for (i = BPF_REG_SIZE; i > BPF_REG_SIZE - size; i--) 4570 state->stack[spi].slot_type[i - 1] = STACK_SPILL; 4571 4572 /* size < 8 bytes spill */ 4573 for (; i; i--) 4574 scrub_spilled_slot(&state->stack[spi].slot_type[i - 1]); 4575 } 4576 4577 static bool is_bpf_st_mem(struct bpf_insn *insn) 4578 { 4579 return BPF_CLASS(insn->code) == BPF_ST && BPF_MODE(insn->code) == BPF_MEM; 4580 } 4581 4582 /* check_stack_{read,write}_fixed_off functions track spill/fill of registers, 4583 * stack boundary and alignment are checked in check_mem_access() 4584 */ 4585 static int check_stack_write_fixed_off(struct bpf_verifier_env *env, 4586 /* stack frame we're writing to */ 4587 struct bpf_func_state *state, 4588 int off, int size, int value_regno, 4589 int insn_idx) 4590 { 4591 struct bpf_func_state *cur; /* state of the current function */ 4592 int i, slot = -off - 1, spi = slot / BPF_REG_SIZE, err; 4593 struct bpf_insn *insn = &env->prog->insnsi[insn_idx]; 4594 struct bpf_reg_state *reg = NULL; 4595 int insn_flags = insn_stack_access_flags(state->frameno, spi); 4596 4597 /* caller checked that off % size == 0 and -MAX_BPF_STACK <= off < 0, 4598 * so it's aligned access and [off, off + size) are within stack limits 4599 */ 4600 if (!env->allow_ptr_leaks && 4601 is_spilled_reg(&state->stack[spi]) && 4602 !is_spilled_scalar_reg(&state->stack[spi]) && 4603 size != BPF_REG_SIZE) { 4604 verbose(env, "attempt to corrupt spilled pointer on stack\n"); 4605 return -EACCES; 4606 } 4607 4608 cur = env->cur_state->frame[env->cur_state->curframe]; 4609 if (value_regno >= 0) 4610 reg = &cur->regs[value_regno]; 4611 if (!env->bypass_spec_v4) { 4612 bool sanitize = reg && is_spillable_regtype(reg->type); 4613 4614 for (i = 0; i < size; i++) { 4615 u8 type = state->stack[spi].slot_type[i]; 4616 4617 if (type != STACK_MISC && type != STACK_ZERO) { 4618 sanitize = true; 4619 break; 4620 } 4621 } 4622 4623 if (sanitize) 4624 env->insn_aux_data[insn_idx].sanitize_stack_spill = true; 4625 } 4626 4627 err = destroy_if_dynptr_stack_slot(env, state, spi); 4628 if (err) 4629 return err; 4630 4631 mark_stack_slot_scratched(env, spi); 4632 if (reg && !(off % BPF_REG_SIZE) && register_is_bounded(reg) && 4633 !register_is_null(reg) && env->bpf_capable) { 4634 save_register_state(state, spi, reg, size); 4635 /* Break the relation on a narrowing spill. */ 4636 if (fls64(reg->umax_value) > BITS_PER_BYTE * size) 4637 state->stack[spi].spilled_ptr.id = 0; 4638 } else if (!reg && !(off % BPF_REG_SIZE) && is_bpf_st_mem(insn) && 4639 insn->imm != 0 && env->bpf_capable) { 4640 struct bpf_reg_state fake_reg = {}; 4641 4642 __mark_reg_known(&fake_reg, insn->imm); 4643 fake_reg.type = SCALAR_VALUE; 4644 save_register_state(state, spi, &fake_reg, size); 4645 insn_flags = 0; /* not a register spill */ 4646 } else if (reg && is_spillable_regtype(reg->type)) { 4647 /* register containing pointer is being spilled into stack */ 4648 if (size != BPF_REG_SIZE) { 4649 verbose_linfo(env, insn_idx, "; "); 4650 verbose(env, "invalid size of register spill\n"); 4651 return -EACCES; 4652 } 4653 if (state != cur && reg->type == PTR_TO_STACK) { 4654 verbose(env, "cannot spill pointers to stack into stack frame of the caller\n"); 4655 return -EINVAL; 4656 } 4657 save_register_state(state, spi, reg, size); 4658 } else { 4659 u8 type = STACK_MISC; 4660 4661 /* regular write of data into stack destroys any spilled ptr */ 4662 state->stack[spi].spilled_ptr.type = NOT_INIT; 4663 /* Mark slots as STACK_MISC if they belonged to spilled ptr/dynptr/iter. */ 4664 if (is_stack_slot_special(&state->stack[spi])) 4665 for (i = 0; i < BPF_REG_SIZE; i++) 4666 scrub_spilled_slot(&state->stack[spi].slot_type[i]); 4667 4668 /* only mark the slot as written if all 8 bytes were written 4669 * otherwise read propagation may incorrectly stop too soon 4670 * when stack slots are partially written. 4671 * This heuristic means that read propagation will be 4672 * conservative, since it will add reg_live_read marks 4673 * to stack slots all the way to first state when programs 4674 * writes+reads less than 8 bytes 4675 */ 4676 if (size == BPF_REG_SIZE) 4677 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN; 4678 4679 /* when we zero initialize stack slots mark them as such */ 4680 if ((reg && register_is_null(reg)) || 4681 (!reg && is_bpf_st_mem(insn) && insn->imm == 0)) { 4682 /* backtracking doesn't work for STACK_ZERO yet. */ 4683 err = mark_chain_precision(env, value_regno); 4684 if (err) 4685 return err; 4686 type = STACK_ZERO; 4687 } 4688 4689 /* Mark slots affected by this stack write. */ 4690 for (i = 0; i < size; i++) 4691 state->stack[spi].slot_type[(slot - i) % BPF_REG_SIZE] = type; 4692 insn_flags = 0; /* not a register spill */ 4693 } 4694 4695 if (insn_flags) 4696 return push_jmp_history(env, env->cur_state, insn_flags); 4697 return 0; 4698 } 4699 4700 /* Write the stack: 'stack[ptr_regno + off] = value_regno'. 'ptr_regno' is 4701 * known to contain a variable offset. 4702 * This function checks whether the write is permitted and conservatively 4703 * tracks the effects of the write, considering that each stack slot in the 4704 * dynamic range is potentially written to. 4705 * 4706 * 'off' includes 'regno->off'. 4707 * 'value_regno' can be -1, meaning that an unknown value is being written to 4708 * the stack. 4709 * 4710 * Spilled pointers in range are not marked as written because we don't know 4711 * what's going to be actually written. This means that read propagation for 4712 * future reads cannot be terminated by this write. 4713 * 4714 * For privileged programs, uninitialized stack slots are considered 4715 * initialized by this write (even though we don't know exactly what offsets 4716 * are going to be written to). The idea is that we don't want the verifier to 4717 * reject future reads that access slots written to through variable offsets. 4718 */ 4719 static int check_stack_write_var_off(struct bpf_verifier_env *env, 4720 /* func where register points to */ 4721 struct bpf_func_state *state, 4722 int ptr_regno, int off, int size, 4723 int value_regno, int insn_idx) 4724 { 4725 struct bpf_func_state *cur; /* state of the current function */ 4726 int min_off, max_off; 4727 int i, err; 4728 struct bpf_reg_state *ptr_reg = NULL, *value_reg = NULL; 4729 struct bpf_insn *insn = &env->prog->insnsi[insn_idx]; 4730 bool writing_zero = false; 4731 /* set if the fact that we're writing a zero is used to let any 4732 * stack slots remain STACK_ZERO 4733 */ 4734 bool zero_used = false; 4735 4736 cur = env->cur_state->frame[env->cur_state->curframe]; 4737 ptr_reg = &cur->regs[ptr_regno]; 4738 min_off = ptr_reg->smin_value + off; 4739 max_off = ptr_reg->smax_value + off + size; 4740 if (value_regno >= 0) 4741 value_reg = &cur->regs[value_regno]; 4742 if ((value_reg && register_is_null(value_reg)) || 4743 (!value_reg && is_bpf_st_mem(insn) && insn->imm == 0)) 4744 writing_zero = true; 4745 4746 for (i = min_off; i < max_off; i++) { 4747 int spi; 4748 4749 spi = __get_spi(i); 4750 err = destroy_if_dynptr_stack_slot(env, state, spi); 4751 if (err) 4752 return err; 4753 } 4754 4755 /* Variable offset writes destroy any spilled pointers in range. */ 4756 for (i = min_off; i < max_off; i++) { 4757 u8 new_type, *stype; 4758 int slot, spi; 4759 4760 slot = -i - 1; 4761 spi = slot / BPF_REG_SIZE; 4762 stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE]; 4763 mark_stack_slot_scratched(env, spi); 4764 4765 if (!env->allow_ptr_leaks && *stype != STACK_MISC && *stype != STACK_ZERO) { 4766 /* Reject the write if range we may write to has not 4767 * been initialized beforehand. If we didn't reject 4768 * here, the ptr status would be erased below (even 4769 * though not all slots are actually overwritten), 4770 * possibly opening the door to leaks. 4771 * 4772 * We do however catch STACK_INVALID case below, and 4773 * only allow reading possibly uninitialized memory 4774 * later for CAP_PERFMON, as the write may not happen to 4775 * that slot. 4776 */ 4777 verbose(env, "spilled ptr in range of var-offset stack write; insn %d, ptr off: %d", 4778 insn_idx, i); 4779 return -EINVAL; 4780 } 4781 4782 /* Erase all spilled pointers. */ 4783 state->stack[spi].spilled_ptr.type = NOT_INIT; 4784 4785 /* Update the slot type. */ 4786 new_type = STACK_MISC; 4787 if (writing_zero && *stype == STACK_ZERO) { 4788 new_type = STACK_ZERO; 4789 zero_used = true; 4790 } 4791 /* If the slot is STACK_INVALID, we check whether it's OK to 4792 * pretend that it will be initialized by this write. The slot 4793 * might not actually be written to, and so if we mark it as 4794 * initialized future reads might leak uninitialized memory. 4795 * For privileged programs, we will accept such reads to slots 4796 * that may or may not be written because, if we're reject 4797 * them, the error would be too confusing. 4798 */ 4799 if (*stype == STACK_INVALID && !env->allow_uninit_stack) { 4800 verbose(env, "uninit stack in range of var-offset write prohibited for !root; insn %d, off: %d", 4801 insn_idx, i); 4802 return -EINVAL; 4803 } 4804 *stype = new_type; 4805 } 4806 if (zero_used) { 4807 /* backtracking doesn't work for STACK_ZERO yet. */ 4808 err = mark_chain_precision(env, value_regno); 4809 if (err) 4810 return err; 4811 } 4812 return 0; 4813 } 4814 4815 /* When register 'dst_regno' is assigned some values from stack[min_off, 4816 * max_off), we set the register's type according to the types of the 4817 * respective stack slots. If all the stack values are known to be zeros, then 4818 * so is the destination reg. Otherwise, the register is considered to be 4819 * SCALAR. This function does not deal with register filling; the caller must 4820 * ensure that all spilled registers in the stack range have been marked as 4821 * read. 4822 */ 4823 static void mark_reg_stack_read(struct bpf_verifier_env *env, 4824 /* func where src register points to */ 4825 struct bpf_func_state *ptr_state, 4826 int min_off, int max_off, int dst_regno) 4827 { 4828 struct bpf_verifier_state *vstate = env->cur_state; 4829 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 4830 int i, slot, spi; 4831 u8 *stype; 4832 int zeros = 0; 4833 4834 for (i = min_off; i < max_off; i++) { 4835 slot = -i - 1; 4836 spi = slot / BPF_REG_SIZE; 4837 mark_stack_slot_scratched(env, spi); 4838 stype = ptr_state->stack[spi].slot_type; 4839 if (stype[slot % BPF_REG_SIZE] != STACK_ZERO) 4840 break; 4841 zeros++; 4842 } 4843 if (zeros == max_off - min_off) { 4844 /* any access_size read into register is zero extended, 4845 * so the whole register == const_zero 4846 */ 4847 __mark_reg_const_zero(&state->regs[dst_regno]); 4848 /* backtracking doesn't support STACK_ZERO yet, 4849 * so mark it precise here, so that later 4850 * backtracking can stop here. 4851 * Backtracking may not need this if this register 4852 * doesn't participate in pointer adjustment. 4853 * Forward propagation of precise flag is not 4854 * necessary either. This mark is only to stop 4855 * backtracking. Any register that contributed 4856 * to const 0 was marked precise before spill. 4857 */ 4858 state->regs[dst_regno].precise = true; 4859 } else { 4860 /* have read misc data from the stack */ 4861 mark_reg_unknown(env, state->regs, dst_regno); 4862 } 4863 state->regs[dst_regno].live |= REG_LIVE_WRITTEN; 4864 } 4865 4866 /* Read the stack at 'off' and put the results into the register indicated by 4867 * 'dst_regno'. It handles reg filling if the addressed stack slot is a 4868 * spilled reg. 4869 * 4870 * 'dst_regno' can be -1, meaning that the read value is not going to a 4871 * register. 4872 * 4873 * The access is assumed to be within the current stack bounds. 4874 */ 4875 static int check_stack_read_fixed_off(struct bpf_verifier_env *env, 4876 /* func where src register points to */ 4877 struct bpf_func_state *reg_state, 4878 int off, int size, int dst_regno) 4879 { 4880 struct bpf_verifier_state *vstate = env->cur_state; 4881 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 4882 int i, slot = -off - 1, spi = slot / BPF_REG_SIZE; 4883 struct bpf_reg_state *reg; 4884 u8 *stype, type; 4885 int insn_flags = insn_stack_access_flags(reg_state->frameno, spi); 4886 4887 stype = reg_state->stack[spi].slot_type; 4888 reg = ®_state->stack[spi].spilled_ptr; 4889 4890 mark_stack_slot_scratched(env, spi); 4891 4892 if (is_spilled_reg(®_state->stack[spi])) { 4893 u8 spill_size = 1; 4894 4895 for (i = BPF_REG_SIZE - 1; i > 0 && stype[i - 1] == STACK_SPILL; i--) 4896 spill_size++; 4897 4898 if (size != BPF_REG_SIZE || spill_size != BPF_REG_SIZE) { 4899 if (reg->type != SCALAR_VALUE) { 4900 verbose_linfo(env, env->insn_idx, "; "); 4901 verbose(env, "invalid size of register fill\n"); 4902 return -EACCES; 4903 } 4904 4905 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64); 4906 if (dst_regno < 0) 4907 return 0; 4908 4909 if (!(off % BPF_REG_SIZE) && size == spill_size) { 4910 /* The earlier check_reg_arg() has decided the 4911 * subreg_def for this insn. Save it first. 4912 */ 4913 s32 subreg_def = state->regs[dst_regno].subreg_def; 4914 4915 copy_register_state(&state->regs[dst_regno], reg); 4916 state->regs[dst_regno].subreg_def = subreg_def; 4917 } else { 4918 for (i = 0; i < size; i++) { 4919 type = stype[(slot - i) % BPF_REG_SIZE]; 4920 if (type == STACK_SPILL) 4921 continue; 4922 if (type == STACK_MISC) 4923 continue; 4924 if (type == STACK_INVALID && env->allow_uninit_stack) 4925 continue; 4926 verbose(env, "invalid read from stack off %d+%d size %d\n", 4927 off, i, size); 4928 return -EACCES; 4929 } 4930 mark_reg_unknown(env, state->regs, dst_regno); 4931 insn_flags = 0; /* not restoring original register state */ 4932 } 4933 state->regs[dst_regno].live |= REG_LIVE_WRITTEN; 4934 } else if (dst_regno >= 0) { 4935 /* restore register state from stack */ 4936 copy_register_state(&state->regs[dst_regno], reg); 4937 /* mark reg as written since spilled pointer state likely 4938 * has its liveness marks cleared by is_state_visited() 4939 * which resets stack/reg liveness for state transitions 4940 */ 4941 state->regs[dst_regno].live |= REG_LIVE_WRITTEN; 4942 } else if (__is_pointer_value(env->allow_ptr_leaks, reg)) { 4943 /* If dst_regno==-1, the caller is asking us whether 4944 * it is acceptable to use this value as a SCALAR_VALUE 4945 * (e.g. for XADD). 4946 * We must not allow unprivileged callers to do that 4947 * with spilled pointers. 4948 */ 4949 verbose(env, "leaking pointer from stack off %d\n", 4950 off); 4951 return -EACCES; 4952 } 4953 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64); 4954 } else { 4955 for (i = 0; i < size; i++) { 4956 type = stype[(slot - i) % BPF_REG_SIZE]; 4957 if (type == STACK_MISC) 4958 continue; 4959 if (type == STACK_ZERO) 4960 continue; 4961 if (type == STACK_INVALID && env->allow_uninit_stack) 4962 continue; 4963 verbose(env, "invalid read from stack off %d+%d size %d\n", 4964 off, i, size); 4965 return -EACCES; 4966 } 4967 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64); 4968 if (dst_regno >= 0) 4969 mark_reg_stack_read(env, reg_state, off, off + size, dst_regno); 4970 insn_flags = 0; /* we are not restoring spilled register */ 4971 } 4972 if (insn_flags) 4973 return push_jmp_history(env, env->cur_state, insn_flags); 4974 return 0; 4975 } 4976 4977 enum bpf_access_src { 4978 ACCESS_DIRECT = 1, /* the access is performed by an instruction */ 4979 ACCESS_HELPER = 2, /* the access is performed by a helper */ 4980 }; 4981 4982 static int check_stack_range_initialized(struct bpf_verifier_env *env, 4983 int regno, int off, int access_size, 4984 bool zero_size_allowed, 4985 enum bpf_access_src type, 4986 struct bpf_call_arg_meta *meta); 4987 4988 static struct bpf_reg_state *reg_state(struct bpf_verifier_env *env, int regno) 4989 { 4990 return cur_regs(env) + regno; 4991 } 4992 4993 /* Read the stack at 'ptr_regno + off' and put the result into the register 4994 * 'dst_regno'. 4995 * 'off' includes the pointer register's fixed offset(i.e. 'ptr_regno.off'), 4996 * but not its variable offset. 4997 * 'size' is assumed to be <= reg size and the access is assumed to be aligned. 4998 * 4999 * As opposed to check_stack_read_fixed_off, this function doesn't deal with 5000 * filling registers (i.e. reads of spilled register cannot be detected when 5001 * the offset is not fixed). We conservatively mark 'dst_regno' as containing 5002 * SCALAR_VALUE. That's why we assert that the 'ptr_regno' has a variable 5003 * offset; for a fixed offset check_stack_read_fixed_off should be used 5004 * instead. 5005 */ 5006 static int check_stack_read_var_off(struct bpf_verifier_env *env, 5007 int ptr_regno, int off, int size, int dst_regno) 5008 { 5009 /* The state of the source register. */ 5010 struct bpf_reg_state *reg = reg_state(env, ptr_regno); 5011 struct bpf_func_state *ptr_state = func(env, reg); 5012 int err; 5013 int min_off, max_off; 5014 5015 /* Note that we pass a NULL meta, so raw access will not be permitted. 5016 */ 5017 err = check_stack_range_initialized(env, ptr_regno, off, size, 5018 false, ACCESS_DIRECT, NULL); 5019 if (err) 5020 return err; 5021 5022 min_off = reg->smin_value + off; 5023 max_off = reg->smax_value + off; 5024 mark_reg_stack_read(env, ptr_state, min_off, max_off + size, dst_regno); 5025 return 0; 5026 } 5027 5028 /* check_stack_read dispatches to check_stack_read_fixed_off or 5029 * check_stack_read_var_off. 5030 * 5031 * The caller must ensure that the offset falls within the allocated stack 5032 * bounds. 5033 * 5034 * 'dst_regno' is a register which will receive the value from the stack. It 5035 * can be -1, meaning that the read value is not going to a register. 5036 */ 5037 static int check_stack_read(struct bpf_verifier_env *env, 5038 int ptr_regno, int off, int size, 5039 int dst_regno) 5040 { 5041 struct bpf_reg_state *reg = reg_state(env, ptr_regno); 5042 struct bpf_func_state *state = func(env, reg); 5043 int err; 5044 /* Some accesses are only permitted with a static offset. */ 5045 bool var_off = !tnum_is_const(reg->var_off); 5046 5047 /* The offset is required to be static when reads don't go to a 5048 * register, in order to not leak pointers (see 5049 * check_stack_read_fixed_off). 5050 */ 5051 if (dst_regno < 0 && var_off) { 5052 char tn_buf[48]; 5053 5054 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 5055 verbose(env, "variable offset stack pointer cannot be passed into helper function; var_off=%s off=%d size=%d\n", 5056 tn_buf, off, size); 5057 return -EACCES; 5058 } 5059 /* Variable offset is prohibited for unprivileged mode for simplicity 5060 * since it requires corresponding support in Spectre masking for stack 5061 * ALU. See also retrieve_ptr_limit(). The check in 5062 * check_stack_access_for_ptr_arithmetic() called by 5063 * adjust_ptr_min_max_vals() prevents users from creating stack pointers 5064 * with variable offsets, therefore no check is required here. Further, 5065 * just checking it here would be insufficient as speculative stack 5066 * writes could still lead to unsafe speculative behaviour. 5067 */ 5068 if (!var_off) { 5069 off += reg->var_off.value; 5070 err = check_stack_read_fixed_off(env, state, off, size, 5071 dst_regno); 5072 } else { 5073 /* Variable offset stack reads need more conservative handling 5074 * than fixed offset ones. Note that dst_regno >= 0 on this 5075 * branch. 5076 */ 5077 err = check_stack_read_var_off(env, ptr_regno, off, size, 5078 dst_regno); 5079 } 5080 return err; 5081 } 5082 5083 5084 /* check_stack_write dispatches to check_stack_write_fixed_off or 5085 * check_stack_write_var_off. 5086 * 5087 * 'ptr_regno' is the register used as a pointer into the stack. 5088 * 'off' includes 'ptr_regno->off', but not its variable offset (if any). 5089 * 'value_regno' is the register whose value we're writing to the stack. It can 5090 * be -1, meaning that we're not writing from a register. 5091 * 5092 * The caller must ensure that the offset falls within the maximum stack size. 5093 */ 5094 static int check_stack_write(struct bpf_verifier_env *env, 5095 int ptr_regno, int off, int size, 5096 int value_regno, int insn_idx) 5097 { 5098 struct bpf_reg_state *reg = reg_state(env, ptr_regno); 5099 struct bpf_func_state *state = func(env, reg); 5100 int err; 5101 5102 if (tnum_is_const(reg->var_off)) { 5103 off += reg->var_off.value; 5104 err = check_stack_write_fixed_off(env, state, off, size, 5105 value_regno, insn_idx); 5106 } else { 5107 /* Variable offset stack reads need more conservative handling 5108 * than fixed offset ones. 5109 */ 5110 err = check_stack_write_var_off(env, state, 5111 ptr_regno, off, size, 5112 value_regno, insn_idx); 5113 } 5114 return err; 5115 } 5116 5117 static int check_map_access_type(struct bpf_verifier_env *env, u32 regno, 5118 int off, int size, enum bpf_access_type type) 5119 { 5120 struct bpf_reg_state *regs = cur_regs(env); 5121 struct bpf_map *map = regs[regno].map_ptr; 5122 u32 cap = bpf_map_flags_to_cap(map); 5123 5124 if (type == BPF_WRITE && !(cap & BPF_MAP_CAN_WRITE)) { 5125 verbose(env, "write into map forbidden, value_size=%d off=%d size=%d\n", 5126 map->value_size, off, size); 5127 return -EACCES; 5128 } 5129 5130 if (type == BPF_READ && !(cap & BPF_MAP_CAN_READ)) { 5131 verbose(env, "read from map forbidden, value_size=%d off=%d size=%d\n", 5132 map->value_size, off, size); 5133 return -EACCES; 5134 } 5135 5136 return 0; 5137 } 5138 5139 /* check read/write into memory region (e.g., map value, ringbuf sample, etc) */ 5140 static int __check_mem_access(struct bpf_verifier_env *env, int regno, 5141 int off, int size, u32 mem_size, 5142 bool zero_size_allowed) 5143 { 5144 bool size_ok = size > 0 || (size == 0 && zero_size_allowed); 5145 struct bpf_reg_state *reg; 5146 5147 if (off >= 0 && size_ok && (u64)off + size <= mem_size) 5148 return 0; 5149 5150 reg = &cur_regs(env)[regno]; 5151 switch (reg->type) { 5152 case PTR_TO_MAP_KEY: 5153 verbose(env, "invalid access to map key, key_size=%d off=%d size=%d\n", 5154 mem_size, off, size); 5155 break; 5156 case PTR_TO_MAP_VALUE: 5157 verbose(env, "invalid access to map value, value_size=%d off=%d size=%d\n", 5158 mem_size, off, size); 5159 break; 5160 case PTR_TO_PACKET: 5161 case PTR_TO_PACKET_META: 5162 case PTR_TO_PACKET_END: 5163 verbose(env, "invalid access to packet, off=%d size=%d, R%d(id=%d,off=%d,r=%d)\n", 5164 off, size, regno, reg->id, off, mem_size); 5165 break; 5166 case PTR_TO_MEM: 5167 default: 5168 verbose(env, "invalid access to memory, mem_size=%u off=%d size=%d\n", 5169 mem_size, off, size); 5170 } 5171 5172 return -EACCES; 5173 } 5174 5175 /* check read/write into a memory region with possible variable offset */ 5176 static int check_mem_region_access(struct bpf_verifier_env *env, u32 regno, 5177 int off, int size, u32 mem_size, 5178 bool zero_size_allowed) 5179 { 5180 struct bpf_verifier_state *vstate = env->cur_state; 5181 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 5182 struct bpf_reg_state *reg = &state->regs[regno]; 5183 int err; 5184 5185 /* We may have adjusted the register pointing to memory region, so we 5186 * need to try adding each of min_value and max_value to off 5187 * to make sure our theoretical access will be safe. 5188 * 5189 * The minimum value is only important with signed 5190 * comparisons where we can't assume the floor of a 5191 * value is 0. If we are using signed variables for our 5192 * index'es we need to make sure that whatever we use 5193 * will have a set floor within our range. 5194 */ 5195 if (reg->smin_value < 0 && 5196 (reg->smin_value == S64_MIN || 5197 (off + reg->smin_value != (s64)(s32)(off + reg->smin_value)) || 5198 reg->smin_value + off < 0)) { 5199 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n", 5200 regno); 5201 return -EACCES; 5202 } 5203 err = __check_mem_access(env, regno, reg->smin_value + off, size, 5204 mem_size, zero_size_allowed); 5205 if (err) { 5206 verbose(env, "R%d min value is outside of the allowed memory range\n", 5207 regno); 5208 return err; 5209 } 5210 5211 /* If we haven't set a max value then we need to bail since we can't be 5212 * sure we won't do bad things. 5213 * If reg->umax_value + off could overflow, treat that as unbounded too. 5214 */ 5215 if (reg->umax_value >= BPF_MAX_VAR_OFF) { 5216 verbose(env, "R%d unbounded memory access, make sure to bounds check any such access\n", 5217 regno); 5218 return -EACCES; 5219 } 5220 err = __check_mem_access(env, regno, reg->umax_value + off, size, 5221 mem_size, zero_size_allowed); 5222 if (err) { 5223 verbose(env, "R%d max value is outside of the allowed memory range\n", 5224 regno); 5225 return err; 5226 } 5227 5228 return 0; 5229 } 5230 5231 static int __check_ptr_off_reg(struct bpf_verifier_env *env, 5232 const struct bpf_reg_state *reg, int regno, 5233 bool fixed_off_ok) 5234 { 5235 /* Access to this pointer-typed register or passing it to a helper 5236 * is only allowed in its original, unmodified form. 5237 */ 5238 5239 if (reg->off < 0) { 5240 verbose(env, "negative offset %s ptr R%d off=%d disallowed\n", 5241 reg_type_str(env, reg->type), regno, reg->off); 5242 return -EACCES; 5243 } 5244 5245 if (!fixed_off_ok && reg->off) { 5246 verbose(env, "dereference of modified %s ptr R%d off=%d disallowed\n", 5247 reg_type_str(env, reg->type), regno, reg->off); 5248 return -EACCES; 5249 } 5250 5251 if (!tnum_is_const(reg->var_off) || reg->var_off.value) { 5252 char tn_buf[48]; 5253 5254 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 5255 verbose(env, "variable %s access var_off=%s disallowed\n", 5256 reg_type_str(env, reg->type), tn_buf); 5257 return -EACCES; 5258 } 5259 5260 return 0; 5261 } 5262 5263 int check_ptr_off_reg(struct bpf_verifier_env *env, 5264 const struct bpf_reg_state *reg, int regno) 5265 { 5266 return __check_ptr_off_reg(env, reg, regno, false); 5267 } 5268 5269 static int map_kptr_match_type(struct bpf_verifier_env *env, 5270 struct btf_field *kptr_field, 5271 struct bpf_reg_state *reg, u32 regno) 5272 { 5273 const char *targ_name = btf_type_name(kptr_field->kptr.btf, kptr_field->kptr.btf_id); 5274 int perm_flags; 5275 const char *reg_name = ""; 5276 5277 if (btf_is_kernel(reg->btf)) { 5278 perm_flags = PTR_MAYBE_NULL | PTR_TRUSTED | MEM_RCU; 5279 5280 /* Only unreferenced case accepts untrusted pointers */ 5281 if (kptr_field->type == BPF_KPTR_UNREF) 5282 perm_flags |= PTR_UNTRUSTED; 5283 } else { 5284 perm_flags = PTR_MAYBE_NULL | MEM_ALLOC; 5285 } 5286 5287 if (base_type(reg->type) != PTR_TO_BTF_ID || (type_flag(reg->type) & ~perm_flags)) 5288 goto bad_type; 5289 5290 /* We need to verify reg->type and reg->btf, before accessing reg->btf */ 5291 reg_name = btf_type_name(reg->btf, reg->btf_id); 5292 5293 /* For ref_ptr case, release function check should ensure we get one 5294 * referenced PTR_TO_BTF_ID, and that its fixed offset is 0. For the 5295 * normal store of unreferenced kptr, we must ensure var_off is zero. 5296 * Since ref_ptr cannot be accessed directly by BPF insns, checks for 5297 * reg->off and reg->ref_obj_id are not needed here. 5298 */ 5299 if (__check_ptr_off_reg(env, reg, regno, true)) 5300 return -EACCES; 5301 5302 /* A full type match is needed, as BTF can be vmlinux, module or prog BTF, and 5303 * we also need to take into account the reg->off. 5304 * 5305 * We want to support cases like: 5306 * 5307 * struct foo { 5308 * struct bar br; 5309 * struct baz bz; 5310 * }; 5311 * 5312 * struct foo *v; 5313 * v = func(); // PTR_TO_BTF_ID 5314 * val->foo = v; // reg->off is zero, btf and btf_id match type 5315 * val->bar = &v->br; // reg->off is still zero, but we need to retry with 5316 * // first member type of struct after comparison fails 5317 * val->baz = &v->bz; // reg->off is non-zero, so struct needs to be walked 5318 * // to match type 5319 * 5320 * In the kptr_ref case, check_func_arg_reg_off already ensures reg->off 5321 * is zero. We must also ensure that btf_struct_ids_match does not walk 5322 * the struct to match type against first member of struct, i.e. reject 5323 * second case from above. Hence, when type is BPF_KPTR_REF, we set 5324 * strict mode to true for type match. 5325 */ 5326 if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off, 5327 kptr_field->kptr.btf, kptr_field->kptr.btf_id, 5328 kptr_field->type == BPF_KPTR_REF)) 5329 goto bad_type; 5330 return 0; 5331 bad_type: 5332 verbose(env, "invalid kptr access, R%d type=%s%s ", regno, 5333 reg_type_str(env, reg->type), reg_name); 5334 verbose(env, "expected=%s%s", reg_type_str(env, PTR_TO_BTF_ID), targ_name); 5335 if (kptr_field->type == BPF_KPTR_UNREF) 5336 verbose(env, " or %s%s\n", reg_type_str(env, PTR_TO_BTF_ID | PTR_UNTRUSTED), 5337 targ_name); 5338 else 5339 verbose(env, "\n"); 5340 return -EINVAL; 5341 } 5342 5343 /* The non-sleepable programs and sleepable programs with explicit bpf_rcu_read_lock() 5344 * can dereference RCU protected pointers and result is PTR_TRUSTED. 5345 */ 5346 static bool in_rcu_cs(struct bpf_verifier_env *env) 5347 { 5348 return env->cur_state->active_rcu_lock || 5349 env->cur_state->active_lock.ptr || 5350 !env->prog->aux->sleepable; 5351 } 5352 5353 /* Once GCC supports btf_type_tag the following mechanism will be replaced with tag check */ 5354 BTF_SET_START(rcu_protected_types) 5355 BTF_ID(struct, prog_test_ref_kfunc) 5356 BTF_ID(struct, cgroup) 5357 BTF_ID(struct, bpf_cpumask) 5358 BTF_ID(struct, task_struct) 5359 BTF_SET_END(rcu_protected_types) 5360 5361 static bool rcu_protected_object(const struct btf *btf, u32 btf_id) 5362 { 5363 if (!btf_is_kernel(btf)) 5364 return false; 5365 return btf_id_set_contains(&rcu_protected_types, btf_id); 5366 } 5367 5368 static bool rcu_safe_kptr(const struct btf_field *field) 5369 { 5370 const struct btf_field_kptr *kptr = &field->kptr; 5371 5372 return field->type == BPF_KPTR_REF && rcu_protected_object(kptr->btf, kptr->btf_id); 5373 } 5374 5375 static int check_map_kptr_access(struct bpf_verifier_env *env, u32 regno, 5376 int value_regno, int insn_idx, 5377 struct btf_field *kptr_field) 5378 { 5379 struct bpf_insn *insn = &env->prog->insnsi[insn_idx]; 5380 int class = BPF_CLASS(insn->code); 5381 struct bpf_reg_state *val_reg; 5382 5383 /* Things we already checked for in check_map_access and caller: 5384 * - Reject cases where variable offset may touch kptr 5385 * - size of access (must be BPF_DW) 5386 * - tnum_is_const(reg->var_off) 5387 * - kptr_field->offset == off + reg->var_off.value 5388 */ 5389 /* Only BPF_[LDX,STX,ST] | BPF_MEM | BPF_DW is supported */ 5390 if (BPF_MODE(insn->code) != BPF_MEM) { 5391 verbose(env, "kptr in map can only be accessed using BPF_MEM instruction mode\n"); 5392 return -EACCES; 5393 } 5394 5395 /* We only allow loading referenced kptr, since it will be marked as 5396 * untrusted, similar to unreferenced kptr. 5397 */ 5398 if (class != BPF_LDX && kptr_field->type == BPF_KPTR_REF) { 5399 verbose(env, "store to referenced kptr disallowed\n"); 5400 return -EACCES; 5401 } 5402 5403 if (class == BPF_LDX) { 5404 val_reg = reg_state(env, value_regno); 5405 /* We can simply mark the value_regno receiving the pointer 5406 * value from map as PTR_TO_BTF_ID, with the correct type. 5407 */ 5408 mark_btf_ld_reg(env, cur_regs(env), value_regno, PTR_TO_BTF_ID, kptr_field->kptr.btf, 5409 kptr_field->kptr.btf_id, 5410 rcu_safe_kptr(kptr_field) && in_rcu_cs(env) ? 5411 PTR_MAYBE_NULL | MEM_RCU : 5412 PTR_MAYBE_NULL | PTR_UNTRUSTED); 5413 } else if (class == BPF_STX) { 5414 val_reg = reg_state(env, value_regno); 5415 if (!register_is_null(val_reg) && 5416 map_kptr_match_type(env, kptr_field, val_reg, value_regno)) 5417 return -EACCES; 5418 } else if (class == BPF_ST) { 5419 if (insn->imm) { 5420 verbose(env, "BPF_ST imm must be 0 when storing to kptr at off=%u\n", 5421 kptr_field->offset); 5422 return -EACCES; 5423 } 5424 } else { 5425 verbose(env, "kptr in map can only be accessed using BPF_LDX/BPF_STX/BPF_ST\n"); 5426 return -EACCES; 5427 } 5428 return 0; 5429 } 5430 5431 /* check read/write into a map element with possible variable offset */ 5432 static int check_map_access(struct bpf_verifier_env *env, u32 regno, 5433 int off, int size, bool zero_size_allowed, 5434 enum bpf_access_src src) 5435 { 5436 struct bpf_verifier_state *vstate = env->cur_state; 5437 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 5438 struct bpf_reg_state *reg = &state->regs[regno]; 5439 struct bpf_map *map = reg->map_ptr; 5440 struct btf_record *rec; 5441 int err, i; 5442 5443 err = check_mem_region_access(env, regno, off, size, map->value_size, 5444 zero_size_allowed); 5445 if (err) 5446 return err; 5447 5448 if (IS_ERR_OR_NULL(map->record)) 5449 return 0; 5450 rec = map->record; 5451 for (i = 0; i < rec->cnt; i++) { 5452 struct btf_field *field = &rec->fields[i]; 5453 u32 p = field->offset; 5454 5455 /* If any part of a field can be touched by load/store, reject 5456 * this program. To check that [x1, x2) overlaps with [y1, y2), 5457 * it is sufficient to check x1 < y2 && y1 < x2. 5458 */ 5459 if (reg->smin_value + off < p + btf_field_type_size(field->type) && 5460 p < reg->umax_value + off + size) { 5461 switch (field->type) { 5462 case BPF_KPTR_UNREF: 5463 case BPF_KPTR_REF: 5464 if (src != ACCESS_DIRECT) { 5465 verbose(env, "kptr cannot be accessed indirectly by helper\n"); 5466 return -EACCES; 5467 } 5468 if (!tnum_is_const(reg->var_off)) { 5469 verbose(env, "kptr access cannot have variable offset\n"); 5470 return -EACCES; 5471 } 5472 if (p != off + reg->var_off.value) { 5473 verbose(env, "kptr access misaligned expected=%u off=%llu\n", 5474 p, off + reg->var_off.value); 5475 return -EACCES; 5476 } 5477 if (size != bpf_size_to_bytes(BPF_DW)) { 5478 verbose(env, "kptr access size must be BPF_DW\n"); 5479 return -EACCES; 5480 } 5481 break; 5482 default: 5483 verbose(env, "%s cannot be accessed directly by load/store\n", 5484 btf_field_type_name(field->type)); 5485 return -EACCES; 5486 } 5487 } 5488 } 5489 return 0; 5490 } 5491 5492 #define MAX_PACKET_OFF 0xffff 5493 5494 static bool may_access_direct_pkt_data(struct bpf_verifier_env *env, 5495 const struct bpf_call_arg_meta *meta, 5496 enum bpf_access_type t) 5497 { 5498 enum bpf_prog_type prog_type = resolve_prog_type(env->prog); 5499 5500 switch (prog_type) { 5501 /* Program types only with direct read access go here! */ 5502 case BPF_PROG_TYPE_LWT_IN: 5503 case BPF_PROG_TYPE_LWT_OUT: 5504 case BPF_PROG_TYPE_LWT_SEG6LOCAL: 5505 case BPF_PROG_TYPE_SK_REUSEPORT: 5506 case BPF_PROG_TYPE_FLOW_DISSECTOR: 5507 case BPF_PROG_TYPE_CGROUP_SKB: 5508 if (t == BPF_WRITE) 5509 return false; 5510 fallthrough; 5511 5512 /* Program types with direct read + write access go here! */ 5513 case BPF_PROG_TYPE_SCHED_CLS: 5514 case BPF_PROG_TYPE_SCHED_ACT: 5515 case BPF_PROG_TYPE_XDP: 5516 case BPF_PROG_TYPE_LWT_XMIT: 5517 case BPF_PROG_TYPE_SK_SKB: 5518 case BPF_PROG_TYPE_SK_MSG: 5519 if (meta) 5520 return meta->pkt_access; 5521 5522 env->seen_direct_write = true; 5523 return true; 5524 5525 case BPF_PROG_TYPE_CGROUP_SOCKOPT: 5526 if (t == BPF_WRITE) 5527 env->seen_direct_write = true; 5528 5529 return true; 5530 5531 default: 5532 return false; 5533 } 5534 } 5535 5536 static int check_packet_access(struct bpf_verifier_env *env, u32 regno, int off, 5537 int size, bool zero_size_allowed) 5538 { 5539 struct bpf_reg_state *regs = cur_regs(env); 5540 struct bpf_reg_state *reg = ®s[regno]; 5541 int err; 5542 5543 /* We may have added a variable offset to the packet pointer; but any 5544 * reg->range we have comes after that. We are only checking the fixed 5545 * offset. 5546 */ 5547 5548 /* We don't allow negative numbers, because we aren't tracking enough 5549 * detail to prove they're safe. 5550 */ 5551 if (reg->smin_value < 0) { 5552 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n", 5553 regno); 5554 return -EACCES; 5555 } 5556 5557 err = reg->range < 0 ? -EINVAL : 5558 __check_mem_access(env, regno, off, size, reg->range, 5559 zero_size_allowed); 5560 if (err) { 5561 verbose(env, "R%d offset is outside of the packet\n", regno); 5562 return err; 5563 } 5564 5565 /* __check_mem_access has made sure "off + size - 1" is within u16. 5566 * reg->umax_value can't be bigger than MAX_PACKET_OFF which is 0xffff, 5567 * otherwise find_good_pkt_pointers would have refused to set range info 5568 * that __check_mem_access would have rejected this pkt access. 5569 * Therefore, "off + reg->umax_value + size - 1" won't overflow u32. 5570 */ 5571 env->prog->aux->max_pkt_offset = 5572 max_t(u32, env->prog->aux->max_pkt_offset, 5573 off + reg->umax_value + size - 1); 5574 5575 return err; 5576 } 5577 5578 /* check access to 'struct bpf_context' fields. Supports fixed offsets only */ 5579 static int check_ctx_access(struct bpf_verifier_env *env, int insn_idx, int off, int size, 5580 enum bpf_access_type t, enum bpf_reg_type *reg_type, 5581 struct btf **btf, u32 *btf_id) 5582 { 5583 struct bpf_insn_access_aux info = { 5584 .reg_type = *reg_type, 5585 .log = &env->log, 5586 }; 5587 5588 if (env->ops->is_valid_access && 5589 env->ops->is_valid_access(off, size, t, env->prog, &info)) { 5590 /* A non zero info.ctx_field_size indicates that this field is a 5591 * candidate for later verifier transformation to load the whole 5592 * field and then apply a mask when accessed with a narrower 5593 * access than actual ctx access size. A zero info.ctx_field_size 5594 * will only allow for whole field access and rejects any other 5595 * type of narrower access. 5596 */ 5597 *reg_type = info.reg_type; 5598 5599 if (base_type(*reg_type) == PTR_TO_BTF_ID) { 5600 *btf = info.btf; 5601 *btf_id = info.btf_id; 5602 } else { 5603 env->insn_aux_data[insn_idx].ctx_field_size = info.ctx_field_size; 5604 } 5605 /* remember the offset of last byte accessed in ctx */ 5606 if (env->prog->aux->max_ctx_offset < off + size) 5607 env->prog->aux->max_ctx_offset = off + size; 5608 return 0; 5609 } 5610 5611 verbose(env, "invalid bpf_context access off=%d size=%d\n", off, size); 5612 return -EACCES; 5613 } 5614 5615 static int check_flow_keys_access(struct bpf_verifier_env *env, int off, 5616 int size) 5617 { 5618 if (size < 0 || off < 0 || 5619 (u64)off + size > sizeof(struct bpf_flow_keys)) { 5620 verbose(env, "invalid access to flow keys off=%d size=%d\n", 5621 off, size); 5622 return -EACCES; 5623 } 5624 return 0; 5625 } 5626 5627 static int check_sock_access(struct bpf_verifier_env *env, int insn_idx, 5628 u32 regno, int off, int size, 5629 enum bpf_access_type t) 5630 { 5631 struct bpf_reg_state *regs = cur_regs(env); 5632 struct bpf_reg_state *reg = ®s[regno]; 5633 struct bpf_insn_access_aux info = {}; 5634 bool valid; 5635 5636 if (reg->smin_value < 0) { 5637 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n", 5638 regno); 5639 return -EACCES; 5640 } 5641 5642 switch (reg->type) { 5643 case PTR_TO_SOCK_COMMON: 5644 valid = bpf_sock_common_is_valid_access(off, size, t, &info); 5645 break; 5646 case PTR_TO_SOCKET: 5647 valid = bpf_sock_is_valid_access(off, size, t, &info); 5648 break; 5649 case PTR_TO_TCP_SOCK: 5650 valid = bpf_tcp_sock_is_valid_access(off, size, t, &info); 5651 break; 5652 case PTR_TO_XDP_SOCK: 5653 valid = bpf_xdp_sock_is_valid_access(off, size, t, &info); 5654 break; 5655 default: 5656 valid = false; 5657 } 5658 5659 5660 if (valid) { 5661 env->insn_aux_data[insn_idx].ctx_field_size = 5662 info.ctx_field_size; 5663 return 0; 5664 } 5665 5666 verbose(env, "R%d invalid %s access off=%d size=%d\n", 5667 regno, reg_type_str(env, reg->type), off, size); 5668 5669 return -EACCES; 5670 } 5671 5672 static bool is_pointer_value(struct bpf_verifier_env *env, int regno) 5673 { 5674 return __is_pointer_value(env->allow_ptr_leaks, reg_state(env, regno)); 5675 } 5676 5677 static bool is_ctx_reg(struct bpf_verifier_env *env, int regno) 5678 { 5679 const struct bpf_reg_state *reg = reg_state(env, regno); 5680 5681 return reg->type == PTR_TO_CTX; 5682 } 5683 5684 static bool is_sk_reg(struct bpf_verifier_env *env, int regno) 5685 { 5686 const struct bpf_reg_state *reg = reg_state(env, regno); 5687 5688 return type_is_sk_pointer(reg->type); 5689 } 5690 5691 static bool is_pkt_reg(struct bpf_verifier_env *env, int regno) 5692 { 5693 const struct bpf_reg_state *reg = reg_state(env, regno); 5694 5695 return type_is_pkt_pointer(reg->type); 5696 } 5697 5698 static bool is_flow_key_reg(struct bpf_verifier_env *env, int regno) 5699 { 5700 const struct bpf_reg_state *reg = reg_state(env, regno); 5701 5702 /* Separate to is_ctx_reg() since we still want to allow BPF_ST here. */ 5703 return reg->type == PTR_TO_FLOW_KEYS; 5704 } 5705 5706 static u32 *reg2btf_ids[__BPF_REG_TYPE_MAX] = { 5707 #ifdef CONFIG_NET 5708 [PTR_TO_SOCKET] = &btf_sock_ids[BTF_SOCK_TYPE_SOCK], 5709 [PTR_TO_SOCK_COMMON] = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON], 5710 [PTR_TO_TCP_SOCK] = &btf_sock_ids[BTF_SOCK_TYPE_TCP], 5711 #endif 5712 [CONST_PTR_TO_MAP] = btf_bpf_map_id, 5713 }; 5714 5715 static bool is_trusted_reg(const struct bpf_reg_state *reg) 5716 { 5717 /* A referenced register is always trusted. */ 5718 if (reg->ref_obj_id) 5719 return true; 5720 5721 /* Types listed in the reg2btf_ids are always trusted */ 5722 if (reg2btf_ids[base_type(reg->type)] && 5723 !bpf_type_has_unsafe_modifiers(reg->type)) 5724 return true; 5725 5726 /* If a register is not referenced, it is trusted if it has the 5727 * MEM_ALLOC or PTR_TRUSTED type modifiers, and no others. Some of the 5728 * other type modifiers may be safe, but we elect to take an opt-in 5729 * approach here as some (e.g. PTR_UNTRUSTED and PTR_MAYBE_NULL) are 5730 * not. 5731 * 5732 * Eventually, we should make PTR_TRUSTED the single source of truth 5733 * for whether a register is trusted. 5734 */ 5735 return type_flag(reg->type) & BPF_REG_TRUSTED_MODIFIERS && 5736 !bpf_type_has_unsafe_modifiers(reg->type); 5737 } 5738 5739 static bool is_rcu_reg(const struct bpf_reg_state *reg) 5740 { 5741 return reg->type & MEM_RCU; 5742 } 5743 5744 static void clear_trusted_flags(enum bpf_type_flag *flag) 5745 { 5746 *flag &= ~(BPF_REG_TRUSTED_MODIFIERS | MEM_RCU); 5747 } 5748 5749 static int check_pkt_ptr_alignment(struct bpf_verifier_env *env, 5750 const struct bpf_reg_state *reg, 5751 int off, int size, bool strict) 5752 { 5753 struct tnum reg_off; 5754 int ip_align; 5755 5756 /* Byte size accesses are always allowed. */ 5757 if (!strict || size == 1) 5758 return 0; 5759 5760 /* For platforms that do not have a Kconfig enabling 5761 * CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS the value of 5762 * NET_IP_ALIGN is universally set to '2'. And on platforms 5763 * that do set CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS, we get 5764 * to this code only in strict mode where we want to emulate 5765 * the NET_IP_ALIGN==2 checking. Therefore use an 5766 * unconditional IP align value of '2'. 5767 */ 5768 ip_align = 2; 5769 5770 reg_off = tnum_add(reg->var_off, tnum_const(ip_align + reg->off + off)); 5771 if (!tnum_is_aligned(reg_off, size)) { 5772 char tn_buf[48]; 5773 5774 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 5775 verbose(env, 5776 "misaligned packet access off %d+%s+%d+%d size %d\n", 5777 ip_align, tn_buf, reg->off, off, size); 5778 return -EACCES; 5779 } 5780 5781 return 0; 5782 } 5783 5784 static int check_generic_ptr_alignment(struct bpf_verifier_env *env, 5785 const struct bpf_reg_state *reg, 5786 const char *pointer_desc, 5787 int off, int size, bool strict) 5788 { 5789 struct tnum reg_off; 5790 5791 /* Byte size accesses are always allowed. */ 5792 if (!strict || size == 1) 5793 return 0; 5794 5795 reg_off = tnum_add(reg->var_off, tnum_const(reg->off + off)); 5796 if (!tnum_is_aligned(reg_off, size)) { 5797 char tn_buf[48]; 5798 5799 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 5800 verbose(env, "misaligned %saccess off %s+%d+%d size %d\n", 5801 pointer_desc, tn_buf, reg->off, off, size); 5802 return -EACCES; 5803 } 5804 5805 return 0; 5806 } 5807 5808 static int check_ptr_alignment(struct bpf_verifier_env *env, 5809 const struct bpf_reg_state *reg, int off, 5810 int size, bool strict_alignment_once) 5811 { 5812 bool strict = env->strict_alignment || strict_alignment_once; 5813 const char *pointer_desc = ""; 5814 5815 switch (reg->type) { 5816 case PTR_TO_PACKET: 5817 case PTR_TO_PACKET_META: 5818 /* Special case, because of NET_IP_ALIGN. Given metadata sits 5819 * right in front, treat it the very same way. 5820 */ 5821 return check_pkt_ptr_alignment(env, reg, off, size, strict); 5822 case PTR_TO_FLOW_KEYS: 5823 pointer_desc = "flow keys "; 5824 break; 5825 case PTR_TO_MAP_KEY: 5826 pointer_desc = "key "; 5827 break; 5828 case PTR_TO_MAP_VALUE: 5829 pointer_desc = "value "; 5830 break; 5831 case PTR_TO_CTX: 5832 pointer_desc = "context "; 5833 break; 5834 case PTR_TO_STACK: 5835 pointer_desc = "stack "; 5836 /* The stack spill tracking logic in check_stack_write_fixed_off() 5837 * and check_stack_read_fixed_off() relies on stack accesses being 5838 * aligned. 5839 */ 5840 strict = true; 5841 break; 5842 case PTR_TO_SOCKET: 5843 pointer_desc = "sock "; 5844 break; 5845 case PTR_TO_SOCK_COMMON: 5846 pointer_desc = "sock_common "; 5847 break; 5848 case PTR_TO_TCP_SOCK: 5849 pointer_desc = "tcp_sock "; 5850 break; 5851 case PTR_TO_XDP_SOCK: 5852 pointer_desc = "xdp_sock "; 5853 break; 5854 default: 5855 break; 5856 } 5857 return check_generic_ptr_alignment(env, reg, pointer_desc, off, size, 5858 strict); 5859 } 5860 5861 /* starting from main bpf function walk all instructions of the function 5862 * and recursively walk all callees that given function can call. 5863 * Ignore jump and exit insns. 5864 * Since recursion is prevented by check_cfg() this algorithm 5865 * only needs a local stack of MAX_CALL_FRAMES to remember callsites 5866 */ 5867 static int check_max_stack_depth_subprog(struct bpf_verifier_env *env, int idx) 5868 { 5869 struct bpf_subprog_info *subprog = env->subprog_info; 5870 struct bpf_insn *insn = env->prog->insnsi; 5871 int depth = 0, frame = 0, i, subprog_end; 5872 bool tail_call_reachable = false; 5873 int ret_insn[MAX_CALL_FRAMES]; 5874 int ret_prog[MAX_CALL_FRAMES]; 5875 int j; 5876 5877 i = subprog[idx].start; 5878 process_func: 5879 /* protect against potential stack overflow that might happen when 5880 * bpf2bpf calls get combined with tailcalls. Limit the caller's stack 5881 * depth for such case down to 256 so that the worst case scenario 5882 * would result in 8k stack size (32 which is tailcall limit * 256 = 5883 * 8k). 5884 * 5885 * To get the idea what might happen, see an example: 5886 * func1 -> sub rsp, 128 5887 * subfunc1 -> sub rsp, 256 5888 * tailcall1 -> add rsp, 256 5889 * func2 -> sub rsp, 192 (total stack size = 128 + 192 = 320) 5890 * subfunc2 -> sub rsp, 64 5891 * subfunc22 -> sub rsp, 128 5892 * tailcall2 -> add rsp, 128 5893 * func3 -> sub rsp, 32 (total stack size 128 + 192 + 64 + 32 = 416) 5894 * 5895 * tailcall will unwind the current stack frame but it will not get rid 5896 * of caller's stack as shown on the example above. 5897 */ 5898 if (idx && subprog[idx].has_tail_call && depth >= 256) { 5899 verbose(env, 5900 "tail_calls are not allowed when call stack of previous frames is %d bytes. Too large\n", 5901 depth); 5902 return -EACCES; 5903 } 5904 /* round up to 32-bytes, since this is granularity 5905 * of interpreter stack size 5906 */ 5907 depth += round_up(max_t(u32, subprog[idx].stack_depth, 1), 32); 5908 if (depth > MAX_BPF_STACK) { 5909 verbose(env, "combined stack size of %d calls is %d. Too large\n", 5910 frame + 1, depth); 5911 return -EACCES; 5912 } 5913 continue_func: 5914 subprog_end = subprog[idx + 1].start; 5915 for (; i < subprog_end; i++) { 5916 int next_insn, sidx; 5917 5918 if (!bpf_pseudo_call(insn + i) && !bpf_pseudo_func(insn + i)) 5919 continue; 5920 /* remember insn and function to return to */ 5921 ret_insn[frame] = i + 1; 5922 ret_prog[frame] = idx; 5923 5924 /* find the callee */ 5925 next_insn = i + insn[i].imm + 1; 5926 sidx = find_subprog(env, next_insn); 5927 if (sidx < 0) { 5928 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n", 5929 next_insn); 5930 return -EFAULT; 5931 } 5932 if (subprog[sidx].is_async_cb) { 5933 if (subprog[sidx].has_tail_call) { 5934 verbose(env, "verifier bug. subprog has tail_call and async cb\n"); 5935 return -EFAULT; 5936 } 5937 /* async callbacks don't increase bpf prog stack size unless called directly */ 5938 if (!bpf_pseudo_call(insn + i)) 5939 continue; 5940 } 5941 i = next_insn; 5942 idx = sidx; 5943 5944 if (subprog[idx].has_tail_call) 5945 tail_call_reachable = true; 5946 5947 frame++; 5948 if (frame >= MAX_CALL_FRAMES) { 5949 verbose(env, "the call stack of %d frames is too deep !\n", 5950 frame); 5951 return -E2BIG; 5952 } 5953 goto process_func; 5954 } 5955 /* if tail call got detected across bpf2bpf calls then mark each of the 5956 * currently present subprog frames as tail call reachable subprogs; 5957 * this info will be utilized by JIT so that we will be preserving the 5958 * tail call counter throughout bpf2bpf calls combined with tailcalls 5959 */ 5960 if (tail_call_reachable) 5961 for (j = 0; j < frame; j++) 5962 subprog[ret_prog[j]].tail_call_reachable = true; 5963 if (subprog[0].tail_call_reachable) 5964 env->prog->aux->tail_call_reachable = true; 5965 5966 /* end of for() loop means the last insn of the 'subprog' 5967 * was reached. Doesn't matter whether it was JA or EXIT 5968 */ 5969 if (frame == 0) 5970 return 0; 5971 depth -= round_up(max_t(u32, subprog[idx].stack_depth, 1), 32); 5972 frame--; 5973 i = ret_insn[frame]; 5974 idx = ret_prog[frame]; 5975 goto continue_func; 5976 } 5977 5978 static int check_max_stack_depth(struct bpf_verifier_env *env) 5979 { 5980 struct bpf_subprog_info *si = env->subprog_info; 5981 int ret; 5982 5983 for (int i = 0; i < env->subprog_cnt; i++) { 5984 if (!i || si[i].is_async_cb) { 5985 ret = check_max_stack_depth_subprog(env, i); 5986 if (ret < 0) 5987 return ret; 5988 } 5989 continue; 5990 } 5991 return 0; 5992 } 5993 5994 #ifndef CONFIG_BPF_JIT_ALWAYS_ON 5995 static int get_callee_stack_depth(struct bpf_verifier_env *env, 5996 const struct bpf_insn *insn, int idx) 5997 { 5998 int start = idx + insn->imm + 1, subprog; 5999 6000 subprog = find_subprog(env, start); 6001 if (subprog < 0) { 6002 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n", 6003 start); 6004 return -EFAULT; 6005 } 6006 return env->subprog_info[subprog].stack_depth; 6007 } 6008 #endif 6009 6010 static int __check_buffer_access(struct bpf_verifier_env *env, 6011 const char *buf_info, 6012 const struct bpf_reg_state *reg, 6013 int regno, int off, int size) 6014 { 6015 if (off < 0) { 6016 verbose(env, 6017 "R%d invalid %s buffer access: off=%d, size=%d\n", 6018 regno, buf_info, off, size); 6019 return -EACCES; 6020 } 6021 if (!tnum_is_const(reg->var_off) || reg->var_off.value) { 6022 char tn_buf[48]; 6023 6024 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 6025 verbose(env, 6026 "R%d invalid variable buffer offset: off=%d, var_off=%s\n", 6027 regno, off, tn_buf); 6028 return -EACCES; 6029 } 6030 6031 return 0; 6032 } 6033 6034 static int check_tp_buffer_access(struct bpf_verifier_env *env, 6035 const struct bpf_reg_state *reg, 6036 int regno, int off, int size) 6037 { 6038 int err; 6039 6040 err = __check_buffer_access(env, "tracepoint", reg, regno, off, size); 6041 if (err) 6042 return err; 6043 6044 if (off + size > env->prog->aux->max_tp_access) 6045 env->prog->aux->max_tp_access = off + size; 6046 6047 return 0; 6048 } 6049 6050 static int check_buffer_access(struct bpf_verifier_env *env, 6051 const struct bpf_reg_state *reg, 6052 int regno, int off, int size, 6053 bool zero_size_allowed, 6054 u32 *max_access) 6055 { 6056 const char *buf_info = type_is_rdonly_mem(reg->type) ? "rdonly" : "rdwr"; 6057 int err; 6058 6059 err = __check_buffer_access(env, buf_info, reg, regno, off, size); 6060 if (err) 6061 return err; 6062 6063 if (off + size > *max_access) 6064 *max_access = off + size; 6065 6066 return 0; 6067 } 6068 6069 /* BPF architecture zero extends alu32 ops into 64-bit registesr */ 6070 static void zext_32_to_64(struct bpf_reg_state *reg) 6071 { 6072 reg->var_off = tnum_subreg(reg->var_off); 6073 __reg_assign_32_into_64(reg); 6074 } 6075 6076 /* truncate register to smaller size (in bytes) 6077 * must be called with size < BPF_REG_SIZE 6078 */ 6079 static void coerce_reg_to_size(struct bpf_reg_state *reg, int size) 6080 { 6081 u64 mask; 6082 6083 /* clear high bits in bit representation */ 6084 reg->var_off = tnum_cast(reg->var_off, size); 6085 6086 /* fix arithmetic bounds */ 6087 mask = ((u64)1 << (size * 8)) - 1; 6088 if ((reg->umin_value & ~mask) == (reg->umax_value & ~mask)) { 6089 reg->umin_value &= mask; 6090 reg->umax_value &= mask; 6091 } else { 6092 reg->umin_value = 0; 6093 reg->umax_value = mask; 6094 } 6095 reg->smin_value = reg->umin_value; 6096 reg->smax_value = reg->umax_value; 6097 6098 /* If size is smaller than 32bit register the 32bit register 6099 * values are also truncated so we push 64-bit bounds into 6100 * 32-bit bounds. Above were truncated < 32-bits already. 6101 */ 6102 if (size >= 4) 6103 return; 6104 __reg_combine_64_into_32(reg); 6105 } 6106 6107 static void set_sext64_default_val(struct bpf_reg_state *reg, int size) 6108 { 6109 if (size == 1) { 6110 reg->smin_value = reg->s32_min_value = S8_MIN; 6111 reg->smax_value = reg->s32_max_value = S8_MAX; 6112 } else if (size == 2) { 6113 reg->smin_value = reg->s32_min_value = S16_MIN; 6114 reg->smax_value = reg->s32_max_value = S16_MAX; 6115 } else { 6116 /* size == 4 */ 6117 reg->smin_value = reg->s32_min_value = S32_MIN; 6118 reg->smax_value = reg->s32_max_value = S32_MAX; 6119 } 6120 reg->umin_value = reg->u32_min_value = 0; 6121 reg->umax_value = U64_MAX; 6122 reg->u32_max_value = U32_MAX; 6123 reg->var_off = tnum_unknown; 6124 } 6125 6126 static void coerce_reg_to_size_sx(struct bpf_reg_state *reg, int size) 6127 { 6128 s64 init_s64_max, init_s64_min, s64_max, s64_min, u64_cval; 6129 u64 top_smax_value, top_smin_value; 6130 u64 num_bits = size * 8; 6131 6132 if (tnum_is_const(reg->var_off)) { 6133 u64_cval = reg->var_off.value; 6134 if (size == 1) 6135 reg->var_off = tnum_const((s8)u64_cval); 6136 else if (size == 2) 6137 reg->var_off = tnum_const((s16)u64_cval); 6138 else 6139 /* size == 4 */ 6140 reg->var_off = tnum_const((s32)u64_cval); 6141 6142 u64_cval = reg->var_off.value; 6143 reg->smax_value = reg->smin_value = u64_cval; 6144 reg->umax_value = reg->umin_value = u64_cval; 6145 reg->s32_max_value = reg->s32_min_value = u64_cval; 6146 reg->u32_max_value = reg->u32_min_value = u64_cval; 6147 return; 6148 } 6149 6150 top_smax_value = ((u64)reg->smax_value >> num_bits) << num_bits; 6151 top_smin_value = ((u64)reg->smin_value >> num_bits) << num_bits; 6152 6153 if (top_smax_value != top_smin_value) 6154 goto out; 6155 6156 /* find the s64_min and s64_min after sign extension */ 6157 if (size == 1) { 6158 init_s64_max = (s8)reg->smax_value; 6159 init_s64_min = (s8)reg->smin_value; 6160 } else if (size == 2) { 6161 init_s64_max = (s16)reg->smax_value; 6162 init_s64_min = (s16)reg->smin_value; 6163 } else { 6164 init_s64_max = (s32)reg->smax_value; 6165 init_s64_min = (s32)reg->smin_value; 6166 } 6167 6168 s64_max = max(init_s64_max, init_s64_min); 6169 s64_min = min(init_s64_max, init_s64_min); 6170 6171 /* both of s64_max/s64_min positive or negative */ 6172 if ((s64_max >= 0) == (s64_min >= 0)) { 6173 reg->s32_min_value = reg->smin_value = s64_min; 6174 reg->s32_max_value = reg->smax_value = s64_max; 6175 reg->u32_min_value = reg->umin_value = s64_min; 6176 reg->u32_max_value = reg->umax_value = s64_max; 6177 reg->var_off = tnum_range(s64_min, s64_max); 6178 return; 6179 } 6180 6181 out: 6182 set_sext64_default_val(reg, size); 6183 } 6184 6185 static void set_sext32_default_val(struct bpf_reg_state *reg, int size) 6186 { 6187 if (size == 1) { 6188 reg->s32_min_value = S8_MIN; 6189 reg->s32_max_value = S8_MAX; 6190 } else { 6191 /* size == 2 */ 6192 reg->s32_min_value = S16_MIN; 6193 reg->s32_max_value = S16_MAX; 6194 } 6195 reg->u32_min_value = 0; 6196 reg->u32_max_value = U32_MAX; 6197 reg->var_off = tnum_subreg(tnum_unknown); 6198 } 6199 6200 static void coerce_subreg_to_size_sx(struct bpf_reg_state *reg, int size) 6201 { 6202 s32 init_s32_max, init_s32_min, s32_max, s32_min, u32_val; 6203 u32 top_smax_value, top_smin_value; 6204 u32 num_bits = size * 8; 6205 6206 if (tnum_is_const(reg->var_off)) { 6207 u32_val = reg->var_off.value; 6208 if (size == 1) 6209 reg->var_off = tnum_const((s8)u32_val); 6210 else 6211 reg->var_off = tnum_const((s16)u32_val); 6212 6213 u32_val = reg->var_off.value; 6214 reg->s32_min_value = reg->s32_max_value = u32_val; 6215 reg->u32_min_value = reg->u32_max_value = u32_val; 6216 return; 6217 } 6218 6219 top_smax_value = ((u32)reg->s32_max_value >> num_bits) << num_bits; 6220 top_smin_value = ((u32)reg->s32_min_value >> num_bits) << num_bits; 6221 6222 if (top_smax_value != top_smin_value) 6223 goto out; 6224 6225 /* find the s32_min and s32_min after sign extension */ 6226 if (size == 1) { 6227 init_s32_max = (s8)reg->s32_max_value; 6228 init_s32_min = (s8)reg->s32_min_value; 6229 } else { 6230 /* size == 2 */ 6231 init_s32_max = (s16)reg->s32_max_value; 6232 init_s32_min = (s16)reg->s32_min_value; 6233 } 6234 s32_max = max(init_s32_max, init_s32_min); 6235 s32_min = min(init_s32_max, init_s32_min); 6236 6237 if ((s32_min >= 0) == (s32_max >= 0)) { 6238 reg->s32_min_value = s32_min; 6239 reg->s32_max_value = s32_max; 6240 reg->u32_min_value = (u32)s32_min; 6241 reg->u32_max_value = (u32)s32_max; 6242 reg->var_off = tnum_subreg(tnum_range(s32_min, s32_max)); 6243 return; 6244 } 6245 6246 out: 6247 set_sext32_default_val(reg, size); 6248 } 6249 6250 static bool bpf_map_is_rdonly(const struct bpf_map *map) 6251 { 6252 /* A map is considered read-only if the following condition are true: 6253 * 6254 * 1) BPF program side cannot change any of the map content. The 6255 * BPF_F_RDONLY_PROG flag is throughout the lifetime of a map 6256 * and was set at map creation time. 6257 * 2) The map value(s) have been initialized from user space by a 6258 * loader and then "frozen", such that no new map update/delete 6259 * operations from syscall side are possible for the rest of 6260 * the map's lifetime from that point onwards. 6261 * 3) Any parallel/pending map update/delete operations from syscall 6262 * side have been completed. Only after that point, it's safe to 6263 * assume that map value(s) are immutable. 6264 */ 6265 return (map->map_flags & BPF_F_RDONLY_PROG) && 6266 READ_ONCE(map->frozen) && 6267 !bpf_map_write_active(map); 6268 } 6269 6270 static int bpf_map_direct_read(struct bpf_map *map, int off, int size, u64 *val, 6271 bool is_ldsx) 6272 { 6273 void *ptr; 6274 u64 addr; 6275 int err; 6276 6277 err = map->ops->map_direct_value_addr(map, &addr, off); 6278 if (err) 6279 return err; 6280 ptr = (void *)(long)addr + off; 6281 6282 switch (size) { 6283 case sizeof(u8): 6284 *val = is_ldsx ? (s64)*(s8 *)ptr : (u64)*(u8 *)ptr; 6285 break; 6286 case sizeof(u16): 6287 *val = is_ldsx ? (s64)*(s16 *)ptr : (u64)*(u16 *)ptr; 6288 break; 6289 case sizeof(u32): 6290 *val = is_ldsx ? (s64)*(s32 *)ptr : (u64)*(u32 *)ptr; 6291 break; 6292 case sizeof(u64): 6293 *val = *(u64 *)ptr; 6294 break; 6295 default: 6296 return -EINVAL; 6297 } 6298 return 0; 6299 } 6300 6301 #define BTF_TYPE_SAFE_RCU(__type) __PASTE(__type, __safe_rcu) 6302 #define BTF_TYPE_SAFE_RCU_OR_NULL(__type) __PASTE(__type, __safe_rcu_or_null) 6303 #define BTF_TYPE_SAFE_TRUSTED(__type) __PASTE(__type, __safe_trusted) 6304 #define BTF_TYPE_SAFE_TRUSTED_OR_NULL(__type) __PASTE(__type, __safe_trusted_or_null) 6305 6306 /* 6307 * Allow list few fields as RCU trusted or full trusted. 6308 * This logic doesn't allow mix tagging and will be removed once GCC supports 6309 * btf_type_tag. 6310 */ 6311 6312 /* RCU trusted: these fields are trusted in RCU CS and never NULL */ 6313 BTF_TYPE_SAFE_RCU(struct task_struct) { 6314 const cpumask_t *cpus_ptr; 6315 struct css_set __rcu *cgroups; 6316 struct task_struct __rcu *real_parent; 6317 struct task_struct *group_leader; 6318 }; 6319 6320 BTF_TYPE_SAFE_RCU(struct cgroup) { 6321 /* cgrp->kn is always accessible as documented in kernel/cgroup/cgroup.c */ 6322 struct kernfs_node *kn; 6323 }; 6324 6325 BTF_TYPE_SAFE_RCU(struct css_set) { 6326 struct cgroup *dfl_cgrp; 6327 }; 6328 6329 /* RCU trusted: these fields are trusted in RCU CS and can be NULL */ 6330 BTF_TYPE_SAFE_RCU_OR_NULL(struct mm_struct) { 6331 struct file __rcu *exe_file; 6332 }; 6333 6334 /* skb->sk, req->sk are not RCU protected, but we mark them as such 6335 * because bpf prog accessible sockets are SOCK_RCU_FREE. 6336 */ 6337 BTF_TYPE_SAFE_RCU_OR_NULL(struct sk_buff) { 6338 struct sock *sk; 6339 }; 6340 6341 BTF_TYPE_SAFE_RCU_OR_NULL(struct request_sock) { 6342 struct sock *sk; 6343 }; 6344 6345 /* full trusted: these fields are trusted even outside of RCU CS and never NULL */ 6346 BTF_TYPE_SAFE_TRUSTED(struct bpf_iter_meta) { 6347 struct seq_file *seq; 6348 }; 6349 6350 BTF_TYPE_SAFE_TRUSTED(struct bpf_iter__task) { 6351 struct bpf_iter_meta *meta; 6352 struct task_struct *task; 6353 }; 6354 6355 BTF_TYPE_SAFE_TRUSTED(struct linux_binprm) { 6356 struct file *file; 6357 }; 6358 6359 BTF_TYPE_SAFE_TRUSTED(struct file) { 6360 struct inode *f_inode; 6361 }; 6362 6363 BTF_TYPE_SAFE_TRUSTED(struct dentry) { 6364 /* no negative dentry-s in places where bpf can see it */ 6365 struct inode *d_inode; 6366 }; 6367 6368 BTF_TYPE_SAFE_TRUSTED_OR_NULL(struct socket) { 6369 struct sock *sk; 6370 }; 6371 6372 static bool type_is_rcu(struct bpf_verifier_env *env, 6373 struct bpf_reg_state *reg, 6374 const char *field_name, u32 btf_id) 6375 { 6376 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct task_struct)); 6377 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct cgroup)); 6378 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct css_set)); 6379 6380 return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_rcu"); 6381 } 6382 6383 static bool type_is_rcu_or_null(struct bpf_verifier_env *env, 6384 struct bpf_reg_state *reg, 6385 const char *field_name, u32 btf_id) 6386 { 6387 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct mm_struct)); 6388 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct sk_buff)); 6389 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct request_sock)); 6390 6391 return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_rcu_or_null"); 6392 } 6393 6394 static bool type_is_trusted(struct bpf_verifier_env *env, 6395 struct bpf_reg_state *reg, 6396 const char *field_name, u32 btf_id) 6397 { 6398 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct bpf_iter_meta)); 6399 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct bpf_iter__task)); 6400 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct linux_binprm)); 6401 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct file)); 6402 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct dentry)); 6403 6404 return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_trusted"); 6405 } 6406 6407 static bool type_is_trusted_or_null(struct bpf_verifier_env *env, 6408 struct bpf_reg_state *reg, 6409 const char *field_name, u32 btf_id) 6410 { 6411 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED_OR_NULL(struct socket)); 6412 6413 return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, 6414 "__safe_trusted_or_null"); 6415 } 6416 6417 static int check_ptr_to_btf_access(struct bpf_verifier_env *env, 6418 struct bpf_reg_state *regs, 6419 int regno, int off, int size, 6420 enum bpf_access_type atype, 6421 int value_regno) 6422 { 6423 struct bpf_reg_state *reg = regs + regno; 6424 const struct btf_type *t = btf_type_by_id(reg->btf, reg->btf_id); 6425 const char *tname = btf_name_by_offset(reg->btf, t->name_off); 6426 const char *field_name = NULL; 6427 enum bpf_type_flag flag = 0; 6428 u32 btf_id = 0; 6429 int ret; 6430 6431 if (!env->allow_ptr_leaks) { 6432 verbose(env, 6433 "'struct %s' access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n", 6434 tname); 6435 return -EPERM; 6436 } 6437 if (!env->prog->gpl_compatible && btf_is_kernel(reg->btf)) { 6438 verbose(env, 6439 "Cannot access kernel 'struct %s' from non-GPL compatible program\n", 6440 tname); 6441 return -EINVAL; 6442 } 6443 if (off < 0) { 6444 verbose(env, 6445 "R%d is ptr_%s invalid negative access: off=%d\n", 6446 regno, tname, off); 6447 return -EACCES; 6448 } 6449 if (!tnum_is_const(reg->var_off) || reg->var_off.value) { 6450 char tn_buf[48]; 6451 6452 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 6453 verbose(env, 6454 "R%d is ptr_%s invalid variable offset: off=%d, var_off=%s\n", 6455 regno, tname, off, tn_buf); 6456 return -EACCES; 6457 } 6458 6459 if (reg->type & MEM_USER) { 6460 verbose(env, 6461 "R%d is ptr_%s access user memory: off=%d\n", 6462 regno, tname, off); 6463 return -EACCES; 6464 } 6465 6466 if (reg->type & MEM_PERCPU) { 6467 verbose(env, 6468 "R%d is ptr_%s access percpu memory: off=%d\n", 6469 regno, tname, off); 6470 return -EACCES; 6471 } 6472 6473 if (env->ops->btf_struct_access && !type_is_alloc(reg->type) && atype == BPF_WRITE) { 6474 if (!btf_is_kernel(reg->btf)) { 6475 verbose(env, "verifier internal error: reg->btf must be kernel btf\n"); 6476 return -EFAULT; 6477 } 6478 ret = env->ops->btf_struct_access(&env->log, reg, off, size); 6479 } else { 6480 /* Writes are permitted with default btf_struct_access for 6481 * program allocated objects (which always have ref_obj_id > 0), 6482 * but not for untrusted PTR_TO_BTF_ID | MEM_ALLOC. 6483 */ 6484 if (atype != BPF_READ && !type_is_ptr_alloc_obj(reg->type)) { 6485 verbose(env, "only read is supported\n"); 6486 return -EACCES; 6487 } 6488 6489 if (type_is_alloc(reg->type) && !type_is_non_owning_ref(reg->type) && 6490 !reg->ref_obj_id) { 6491 verbose(env, "verifier internal error: ref_obj_id for allocated object must be non-zero\n"); 6492 return -EFAULT; 6493 } 6494 6495 ret = btf_struct_access(&env->log, reg, off, size, atype, &btf_id, &flag, &field_name); 6496 } 6497 6498 if (ret < 0) 6499 return ret; 6500 6501 if (ret != PTR_TO_BTF_ID) { 6502 /* just mark; */ 6503 6504 } else if (type_flag(reg->type) & PTR_UNTRUSTED) { 6505 /* If this is an untrusted pointer, all pointers formed by walking it 6506 * also inherit the untrusted flag. 6507 */ 6508 flag = PTR_UNTRUSTED; 6509 6510 } else if (is_trusted_reg(reg) || is_rcu_reg(reg)) { 6511 /* By default any pointer obtained from walking a trusted pointer is no 6512 * longer trusted, unless the field being accessed has explicitly been 6513 * marked as inheriting its parent's state of trust (either full or RCU). 6514 * For example: 6515 * 'cgroups' pointer is untrusted if task->cgroups dereference 6516 * happened in a sleepable program outside of bpf_rcu_read_lock() 6517 * section. In a non-sleepable program it's trusted while in RCU CS (aka MEM_RCU). 6518 * Note bpf_rcu_read_unlock() converts MEM_RCU pointers to PTR_UNTRUSTED. 6519 * 6520 * A regular RCU-protected pointer with __rcu tag can also be deemed 6521 * trusted if we are in an RCU CS. Such pointer can be NULL. 6522 */ 6523 if (type_is_trusted(env, reg, field_name, btf_id)) { 6524 flag |= PTR_TRUSTED; 6525 } else if (type_is_trusted_or_null(env, reg, field_name, btf_id)) { 6526 flag |= PTR_TRUSTED | PTR_MAYBE_NULL; 6527 } else if (in_rcu_cs(env) && !type_may_be_null(reg->type)) { 6528 if (type_is_rcu(env, reg, field_name, btf_id)) { 6529 /* ignore __rcu tag and mark it MEM_RCU */ 6530 flag |= MEM_RCU; 6531 } else if (flag & MEM_RCU || 6532 type_is_rcu_or_null(env, reg, field_name, btf_id)) { 6533 /* __rcu tagged pointers can be NULL */ 6534 flag |= MEM_RCU | PTR_MAYBE_NULL; 6535 6536 /* We always trust them */ 6537 if (type_is_rcu_or_null(env, reg, field_name, btf_id) && 6538 flag & PTR_UNTRUSTED) 6539 flag &= ~PTR_UNTRUSTED; 6540 } else if (flag & (MEM_PERCPU | MEM_USER)) { 6541 /* keep as-is */ 6542 } else { 6543 /* walking unknown pointers yields old deprecated PTR_TO_BTF_ID */ 6544 clear_trusted_flags(&flag); 6545 } 6546 } else { 6547 /* 6548 * If not in RCU CS or MEM_RCU pointer can be NULL then 6549 * aggressively mark as untrusted otherwise such 6550 * pointers will be plain PTR_TO_BTF_ID without flags 6551 * and will be allowed to be passed into helpers for 6552 * compat reasons. 6553 */ 6554 flag = PTR_UNTRUSTED; 6555 } 6556 } else { 6557 /* Old compat. Deprecated */ 6558 clear_trusted_flags(&flag); 6559 } 6560 6561 if (atype == BPF_READ && value_regno >= 0) 6562 mark_btf_ld_reg(env, regs, value_regno, ret, reg->btf, btf_id, flag); 6563 6564 return 0; 6565 } 6566 6567 static int check_ptr_to_map_access(struct bpf_verifier_env *env, 6568 struct bpf_reg_state *regs, 6569 int regno, int off, int size, 6570 enum bpf_access_type atype, 6571 int value_regno) 6572 { 6573 struct bpf_reg_state *reg = regs + regno; 6574 struct bpf_map *map = reg->map_ptr; 6575 struct bpf_reg_state map_reg; 6576 enum bpf_type_flag flag = 0; 6577 const struct btf_type *t; 6578 const char *tname; 6579 u32 btf_id; 6580 int ret; 6581 6582 if (!btf_vmlinux) { 6583 verbose(env, "map_ptr access not supported without CONFIG_DEBUG_INFO_BTF\n"); 6584 return -ENOTSUPP; 6585 } 6586 6587 if (!map->ops->map_btf_id || !*map->ops->map_btf_id) { 6588 verbose(env, "map_ptr access not supported for map type %d\n", 6589 map->map_type); 6590 return -ENOTSUPP; 6591 } 6592 6593 t = btf_type_by_id(btf_vmlinux, *map->ops->map_btf_id); 6594 tname = btf_name_by_offset(btf_vmlinux, t->name_off); 6595 6596 if (!env->allow_ptr_leaks) { 6597 verbose(env, 6598 "'struct %s' access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n", 6599 tname); 6600 return -EPERM; 6601 } 6602 6603 if (off < 0) { 6604 verbose(env, "R%d is %s invalid negative access: off=%d\n", 6605 regno, tname, off); 6606 return -EACCES; 6607 } 6608 6609 if (atype != BPF_READ) { 6610 verbose(env, "only read from %s is supported\n", tname); 6611 return -EACCES; 6612 } 6613 6614 /* Simulate access to a PTR_TO_BTF_ID */ 6615 memset(&map_reg, 0, sizeof(map_reg)); 6616 mark_btf_ld_reg(env, &map_reg, 0, PTR_TO_BTF_ID, btf_vmlinux, *map->ops->map_btf_id, 0); 6617 ret = btf_struct_access(&env->log, &map_reg, off, size, atype, &btf_id, &flag, NULL); 6618 if (ret < 0) 6619 return ret; 6620 6621 if (value_regno >= 0) 6622 mark_btf_ld_reg(env, regs, value_regno, ret, btf_vmlinux, btf_id, flag); 6623 6624 return 0; 6625 } 6626 6627 /* Check that the stack access at the given offset is within bounds. The 6628 * maximum valid offset is -1. 6629 * 6630 * The minimum valid offset is -MAX_BPF_STACK for writes, and 6631 * -state->allocated_stack for reads. 6632 */ 6633 static int check_stack_slot_within_bounds(struct bpf_verifier_env *env, 6634 s64 off, 6635 struct bpf_func_state *state, 6636 enum bpf_access_type t) 6637 { 6638 int min_valid_off; 6639 6640 if (t == BPF_WRITE || env->allow_uninit_stack) 6641 min_valid_off = -MAX_BPF_STACK; 6642 else 6643 min_valid_off = -state->allocated_stack; 6644 6645 if (off < min_valid_off || off > -1) 6646 return -EACCES; 6647 return 0; 6648 } 6649 6650 /* Check that the stack access at 'regno + off' falls within the maximum stack 6651 * bounds. 6652 * 6653 * 'off' includes `regno->offset`, but not its dynamic part (if any). 6654 */ 6655 static int check_stack_access_within_bounds( 6656 struct bpf_verifier_env *env, 6657 int regno, int off, int access_size, 6658 enum bpf_access_src src, enum bpf_access_type type) 6659 { 6660 struct bpf_reg_state *regs = cur_regs(env); 6661 struct bpf_reg_state *reg = regs + regno; 6662 struct bpf_func_state *state = func(env, reg); 6663 s64 min_off, max_off; 6664 int err; 6665 char *err_extra; 6666 6667 if (src == ACCESS_HELPER) 6668 /* We don't know if helpers are reading or writing (or both). */ 6669 err_extra = " indirect access to"; 6670 else if (type == BPF_READ) 6671 err_extra = " read from"; 6672 else 6673 err_extra = " write to"; 6674 6675 if (tnum_is_const(reg->var_off)) { 6676 min_off = (s64)reg->var_off.value + off; 6677 max_off = min_off + access_size; 6678 } else { 6679 if (reg->smax_value >= BPF_MAX_VAR_OFF || 6680 reg->smin_value <= -BPF_MAX_VAR_OFF) { 6681 verbose(env, "invalid unbounded variable-offset%s stack R%d\n", 6682 err_extra, regno); 6683 return -EACCES; 6684 } 6685 min_off = reg->smin_value + off; 6686 max_off = reg->smax_value + off + access_size; 6687 } 6688 6689 err = check_stack_slot_within_bounds(env, min_off, state, type); 6690 if (!err && max_off > 0) 6691 err = -EINVAL; /* out of stack access into non-negative offsets */ 6692 if (!err && access_size < 0) 6693 /* access_size should not be negative (or overflow an int); others checks 6694 * along the way should have prevented such an access. 6695 */ 6696 err = -EFAULT; /* invalid negative access size; integer overflow? */ 6697 6698 if (err) { 6699 if (tnum_is_const(reg->var_off)) { 6700 verbose(env, "invalid%s stack R%d off=%d size=%d\n", 6701 err_extra, regno, off, access_size); 6702 } else { 6703 char tn_buf[48]; 6704 6705 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 6706 verbose(env, "invalid variable-offset%s stack R%d var_off=%s size=%d\n", 6707 err_extra, regno, tn_buf, access_size); 6708 } 6709 return err; 6710 } 6711 6712 return grow_stack_state(env, state, round_up(-min_off, BPF_REG_SIZE)); 6713 } 6714 6715 /* check whether memory at (regno + off) is accessible for t = (read | write) 6716 * if t==write, value_regno is a register which value is stored into memory 6717 * if t==read, value_regno is a register which will receive the value from memory 6718 * if t==write && value_regno==-1, some unknown value is stored into memory 6719 * if t==read && value_regno==-1, don't care what we read from memory 6720 */ 6721 static int check_mem_access(struct bpf_verifier_env *env, int insn_idx, u32 regno, 6722 int off, int bpf_size, enum bpf_access_type t, 6723 int value_regno, bool strict_alignment_once, bool is_ldsx) 6724 { 6725 struct bpf_reg_state *regs = cur_regs(env); 6726 struct bpf_reg_state *reg = regs + regno; 6727 int size, err = 0; 6728 6729 size = bpf_size_to_bytes(bpf_size); 6730 if (size < 0) 6731 return size; 6732 6733 /* alignment checks will add in reg->off themselves */ 6734 err = check_ptr_alignment(env, reg, off, size, strict_alignment_once); 6735 if (err) 6736 return err; 6737 6738 /* for access checks, reg->off is just part of off */ 6739 off += reg->off; 6740 6741 if (reg->type == PTR_TO_MAP_KEY) { 6742 if (t == BPF_WRITE) { 6743 verbose(env, "write to change key R%d not allowed\n", regno); 6744 return -EACCES; 6745 } 6746 6747 err = check_mem_region_access(env, regno, off, size, 6748 reg->map_ptr->key_size, false); 6749 if (err) 6750 return err; 6751 if (value_regno >= 0) 6752 mark_reg_unknown(env, regs, value_regno); 6753 } else if (reg->type == PTR_TO_MAP_VALUE) { 6754 struct btf_field *kptr_field = NULL; 6755 6756 if (t == BPF_WRITE && value_regno >= 0 && 6757 is_pointer_value(env, value_regno)) { 6758 verbose(env, "R%d leaks addr into map\n", value_regno); 6759 return -EACCES; 6760 } 6761 err = check_map_access_type(env, regno, off, size, t); 6762 if (err) 6763 return err; 6764 err = check_map_access(env, regno, off, size, false, ACCESS_DIRECT); 6765 if (err) 6766 return err; 6767 if (tnum_is_const(reg->var_off)) 6768 kptr_field = btf_record_find(reg->map_ptr->record, 6769 off + reg->var_off.value, BPF_KPTR); 6770 if (kptr_field) { 6771 err = check_map_kptr_access(env, regno, value_regno, insn_idx, kptr_field); 6772 } else if (t == BPF_READ && value_regno >= 0) { 6773 struct bpf_map *map = reg->map_ptr; 6774 6775 /* if map is read-only, track its contents as scalars */ 6776 if (tnum_is_const(reg->var_off) && 6777 bpf_map_is_rdonly(map) && 6778 map->ops->map_direct_value_addr) { 6779 int map_off = off + reg->var_off.value; 6780 u64 val = 0; 6781 6782 err = bpf_map_direct_read(map, map_off, size, 6783 &val, is_ldsx); 6784 if (err) 6785 return err; 6786 6787 regs[value_regno].type = SCALAR_VALUE; 6788 __mark_reg_known(®s[value_regno], val); 6789 } else { 6790 mark_reg_unknown(env, regs, value_regno); 6791 } 6792 } 6793 } else if (base_type(reg->type) == PTR_TO_MEM) { 6794 bool rdonly_mem = type_is_rdonly_mem(reg->type); 6795 6796 if (type_may_be_null(reg->type)) { 6797 verbose(env, "R%d invalid mem access '%s'\n", regno, 6798 reg_type_str(env, reg->type)); 6799 return -EACCES; 6800 } 6801 6802 if (t == BPF_WRITE && rdonly_mem) { 6803 verbose(env, "R%d cannot write into %s\n", 6804 regno, reg_type_str(env, reg->type)); 6805 return -EACCES; 6806 } 6807 6808 if (t == BPF_WRITE && value_regno >= 0 && 6809 is_pointer_value(env, value_regno)) { 6810 verbose(env, "R%d leaks addr into mem\n", value_regno); 6811 return -EACCES; 6812 } 6813 6814 err = check_mem_region_access(env, regno, off, size, 6815 reg->mem_size, false); 6816 if (!err && value_regno >= 0 && (t == BPF_READ || rdonly_mem)) 6817 mark_reg_unknown(env, regs, value_regno); 6818 } else if (reg->type == PTR_TO_CTX) { 6819 enum bpf_reg_type reg_type = SCALAR_VALUE; 6820 struct btf *btf = NULL; 6821 u32 btf_id = 0; 6822 6823 if (t == BPF_WRITE && value_regno >= 0 && 6824 is_pointer_value(env, value_regno)) { 6825 verbose(env, "R%d leaks addr into ctx\n", value_regno); 6826 return -EACCES; 6827 } 6828 6829 err = check_ptr_off_reg(env, reg, regno); 6830 if (err < 0) 6831 return err; 6832 6833 err = check_ctx_access(env, insn_idx, off, size, t, ®_type, &btf, 6834 &btf_id); 6835 if (err) 6836 verbose_linfo(env, insn_idx, "; "); 6837 if (!err && t == BPF_READ && value_regno >= 0) { 6838 /* ctx access returns either a scalar, or a 6839 * PTR_TO_PACKET[_META,_END]. In the latter 6840 * case, we know the offset is zero. 6841 */ 6842 if (reg_type == SCALAR_VALUE) { 6843 mark_reg_unknown(env, regs, value_regno); 6844 } else { 6845 mark_reg_known_zero(env, regs, 6846 value_regno); 6847 if (type_may_be_null(reg_type)) 6848 regs[value_regno].id = ++env->id_gen; 6849 /* A load of ctx field could have different 6850 * actual load size with the one encoded in the 6851 * insn. When the dst is PTR, it is for sure not 6852 * a sub-register. 6853 */ 6854 regs[value_regno].subreg_def = DEF_NOT_SUBREG; 6855 if (base_type(reg_type) == PTR_TO_BTF_ID) { 6856 regs[value_regno].btf = btf; 6857 regs[value_regno].btf_id = btf_id; 6858 } 6859 } 6860 regs[value_regno].type = reg_type; 6861 } 6862 6863 } else if (reg->type == PTR_TO_STACK) { 6864 /* Basic bounds checks. */ 6865 err = check_stack_access_within_bounds(env, regno, off, size, ACCESS_DIRECT, t); 6866 if (err) 6867 return err; 6868 6869 if (t == BPF_READ) 6870 err = check_stack_read(env, regno, off, size, 6871 value_regno); 6872 else 6873 err = check_stack_write(env, regno, off, size, 6874 value_regno, insn_idx); 6875 } else if (reg_is_pkt_pointer(reg)) { 6876 if (t == BPF_WRITE && !may_access_direct_pkt_data(env, NULL, t)) { 6877 verbose(env, "cannot write into packet\n"); 6878 return -EACCES; 6879 } 6880 if (t == BPF_WRITE && value_regno >= 0 && 6881 is_pointer_value(env, value_regno)) { 6882 verbose(env, "R%d leaks addr into packet\n", 6883 value_regno); 6884 return -EACCES; 6885 } 6886 err = check_packet_access(env, regno, off, size, false); 6887 if (!err && t == BPF_READ && value_regno >= 0) 6888 mark_reg_unknown(env, regs, value_regno); 6889 } else if (reg->type == PTR_TO_FLOW_KEYS) { 6890 if (t == BPF_WRITE && value_regno >= 0 && 6891 is_pointer_value(env, value_regno)) { 6892 verbose(env, "R%d leaks addr into flow keys\n", 6893 value_regno); 6894 return -EACCES; 6895 } 6896 6897 err = check_flow_keys_access(env, off, size); 6898 if (!err && t == BPF_READ && value_regno >= 0) 6899 mark_reg_unknown(env, regs, value_regno); 6900 } else if (type_is_sk_pointer(reg->type)) { 6901 if (t == BPF_WRITE) { 6902 verbose(env, "R%d cannot write into %s\n", 6903 regno, reg_type_str(env, reg->type)); 6904 return -EACCES; 6905 } 6906 err = check_sock_access(env, insn_idx, regno, off, size, t); 6907 if (!err && value_regno >= 0) 6908 mark_reg_unknown(env, regs, value_regno); 6909 } else if (reg->type == PTR_TO_TP_BUFFER) { 6910 err = check_tp_buffer_access(env, reg, regno, off, size); 6911 if (!err && t == BPF_READ && value_regno >= 0) 6912 mark_reg_unknown(env, regs, value_regno); 6913 } else if (base_type(reg->type) == PTR_TO_BTF_ID && 6914 !type_may_be_null(reg->type)) { 6915 err = check_ptr_to_btf_access(env, regs, regno, off, size, t, 6916 value_regno); 6917 } else if (reg->type == CONST_PTR_TO_MAP) { 6918 err = check_ptr_to_map_access(env, regs, regno, off, size, t, 6919 value_regno); 6920 } else if (base_type(reg->type) == PTR_TO_BUF) { 6921 bool rdonly_mem = type_is_rdonly_mem(reg->type); 6922 u32 *max_access; 6923 6924 if (rdonly_mem) { 6925 if (t == BPF_WRITE) { 6926 verbose(env, "R%d cannot write into %s\n", 6927 regno, reg_type_str(env, reg->type)); 6928 return -EACCES; 6929 } 6930 max_access = &env->prog->aux->max_rdonly_access; 6931 } else { 6932 max_access = &env->prog->aux->max_rdwr_access; 6933 } 6934 6935 err = check_buffer_access(env, reg, regno, off, size, false, 6936 max_access); 6937 6938 if (!err && value_regno >= 0 && (rdonly_mem || t == BPF_READ)) 6939 mark_reg_unknown(env, regs, value_regno); 6940 } else { 6941 verbose(env, "R%d invalid mem access '%s'\n", regno, 6942 reg_type_str(env, reg->type)); 6943 return -EACCES; 6944 } 6945 6946 if (!err && size < BPF_REG_SIZE && value_regno >= 0 && t == BPF_READ && 6947 regs[value_regno].type == SCALAR_VALUE) { 6948 if (!is_ldsx) 6949 /* b/h/w load zero-extends, mark upper bits as known 0 */ 6950 coerce_reg_to_size(®s[value_regno], size); 6951 else 6952 coerce_reg_to_size_sx(®s[value_regno], size); 6953 } 6954 return err; 6955 } 6956 6957 static int check_atomic(struct bpf_verifier_env *env, int insn_idx, struct bpf_insn *insn) 6958 { 6959 int load_reg; 6960 int err; 6961 6962 switch (insn->imm) { 6963 case BPF_ADD: 6964 case BPF_ADD | BPF_FETCH: 6965 case BPF_AND: 6966 case BPF_AND | BPF_FETCH: 6967 case BPF_OR: 6968 case BPF_OR | BPF_FETCH: 6969 case BPF_XOR: 6970 case BPF_XOR | BPF_FETCH: 6971 case BPF_XCHG: 6972 case BPF_CMPXCHG: 6973 break; 6974 default: 6975 verbose(env, "BPF_ATOMIC uses invalid atomic opcode %02x\n", insn->imm); 6976 return -EINVAL; 6977 } 6978 6979 if (BPF_SIZE(insn->code) != BPF_W && BPF_SIZE(insn->code) != BPF_DW) { 6980 verbose(env, "invalid atomic operand size\n"); 6981 return -EINVAL; 6982 } 6983 6984 /* check src1 operand */ 6985 err = check_reg_arg(env, insn->src_reg, SRC_OP); 6986 if (err) 6987 return err; 6988 6989 /* check src2 operand */ 6990 err = check_reg_arg(env, insn->dst_reg, SRC_OP); 6991 if (err) 6992 return err; 6993 6994 if (insn->imm == BPF_CMPXCHG) { 6995 /* Check comparison of R0 with memory location */ 6996 const u32 aux_reg = BPF_REG_0; 6997 6998 err = check_reg_arg(env, aux_reg, SRC_OP); 6999 if (err) 7000 return err; 7001 7002 if (is_pointer_value(env, aux_reg)) { 7003 verbose(env, "R%d leaks addr into mem\n", aux_reg); 7004 return -EACCES; 7005 } 7006 } 7007 7008 if (is_pointer_value(env, insn->src_reg)) { 7009 verbose(env, "R%d leaks addr into mem\n", insn->src_reg); 7010 return -EACCES; 7011 } 7012 7013 if (is_ctx_reg(env, insn->dst_reg) || 7014 is_pkt_reg(env, insn->dst_reg) || 7015 is_flow_key_reg(env, insn->dst_reg) || 7016 is_sk_reg(env, insn->dst_reg)) { 7017 verbose(env, "BPF_ATOMIC stores into R%d %s is not allowed\n", 7018 insn->dst_reg, 7019 reg_type_str(env, reg_state(env, insn->dst_reg)->type)); 7020 return -EACCES; 7021 } 7022 7023 if (insn->imm & BPF_FETCH) { 7024 if (insn->imm == BPF_CMPXCHG) 7025 load_reg = BPF_REG_0; 7026 else 7027 load_reg = insn->src_reg; 7028 7029 /* check and record load of old value */ 7030 err = check_reg_arg(env, load_reg, DST_OP); 7031 if (err) 7032 return err; 7033 } else { 7034 /* This instruction accesses a memory location but doesn't 7035 * actually load it into a register. 7036 */ 7037 load_reg = -1; 7038 } 7039 7040 /* Check whether we can read the memory, with second call for fetch 7041 * case to simulate the register fill. 7042 */ 7043 err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off, 7044 BPF_SIZE(insn->code), BPF_READ, -1, true, false); 7045 if (!err && load_reg >= 0) 7046 err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off, 7047 BPF_SIZE(insn->code), BPF_READ, load_reg, 7048 true, false); 7049 if (err) 7050 return err; 7051 7052 /* Check whether we can write into the same memory. */ 7053 err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off, 7054 BPF_SIZE(insn->code), BPF_WRITE, -1, true, false); 7055 if (err) 7056 return err; 7057 return 0; 7058 } 7059 7060 /* When register 'regno' is used to read the stack (either directly or through 7061 * a helper function) make sure that it's within stack boundary and, depending 7062 * on the access type and privileges, that all elements of the stack are 7063 * initialized. 7064 * 7065 * 'off' includes 'regno->off', but not its dynamic part (if any). 7066 * 7067 * All registers that have been spilled on the stack in the slots within the 7068 * read offsets are marked as read. 7069 */ 7070 static int check_stack_range_initialized( 7071 struct bpf_verifier_env *env, int regno, int off, 7072 int access_size, bool zero_size_allowed, 7073 enum bpf_access_src type, struct bpf_call_arg_meta *meta) 7074 { 7075 struct bpf_reg_state *reg = reg_state(env, regno); 7076 struct bpf_func_state *state = func(env, reg); 7077 int err, min_off, max_off, i, j, slot, spi; 7078 char *err_extra = type == ACCESS_HELPER ? " indirect" : ""; 7079 enum bpf_access_type bounds_check_type; 7080 /* Some accesses can write anything into the stack, others are 7081 * read-only. 7082 */ 7083 bool clobber = false; 7084 7085 if (access_size == 0 && !zero_size_allowed) { 7086 verbose(env, "invalid zero-sized read\n"); 7087 return -EACCES; 7088 } 7089 7090 if (type == ACCESS_HELPER) { 7091 /* The bounds checks for writes are more permissive than for 7092 * reads. However, if raw_mode is not set, we'll do extra 7093 * checks below. 7094 */ 7095 bounds_check_type = BPF_WRITE; 7096 clobber = true; 7097 } else { 7098 bounds_check_type = BPF_READ; 7099 } 7100 err = check_stack_access_within_bounds(env, regno, off, access_size, 7101 type, bounds_check_type); 7102 if (err) 7103 return err; 7104 7105 7106 if (tnum_is_const(reg->var_off)) { 7107 min_off = max_off = reg->var_off.value + off; 7108 } else { 7109 /* Variable offset is prohibited for unprivileged mode for 7110 * simplicity since it requires corresponding support in 7111 * Spectre masking for stack ALU. 7112 * See also retrieve_ptr_limit(). 7113 */ 7114 if (!env->bypass_spec_v1) { 7115 char tn_buf[48]; 7116 7117 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 7118 verbose(env, "R%d%s variable offset stack access prohibited for !root, var_off=%s\n", 7119 regno, err_extra, tn_buf); 7120 return -EACCES; 7121 } 7122 /* Only initialized buffer on stack is allowed to be accessed 7123 * with variable offset. With uninitialized buffer it's hard to 7124 * guarantee that whole memory is marked as initialized on 7125 * helper return since specific bounds are unknown what may 7126 * cause uninitialized stack leaking. 7127 */ 7128 if (meta && meta->raw_mode) 7129 meta = NULL; 7130 7131 min_off = reg->smin_value + off; 7132 max_off = reg->smax_value + off; 7133 } 7134 7135 if (meta && meta->raw_mode) { 7136 /* Ensure we won't be overwriting dynptrs when simulating byte 7137 * by byte access in check_helper_call using meta.access_size. 7138 * This would be a problem if we have a helper in the future 7139 * which takes: 7140 * 7141 * helper(uninit_mem, len, dynptr) 7142 * 7143 * Now, uninint_mem may overlap with dynptr pointer. Hence, it 7144 * may end up writing to dynptr itself when touching memory from 7145 * arg 1. This can be relaxed on a case by case basis for known 7146 * safe cases, but reject due to the possibilitiy of aliasing by 7147 * default. 7148 */ 7149 for (i = min_off; i < max_off + access_size; i++) { 7150 int stack_off = -i - 1; 7151 7152 spi = __get_spi(i); 7153 /* raw_mode may write past allocated_stack */ 7154 if (state->allocated_stack <= stack_off) 7155 continue; 7156 if (state->stack[spi].slot_type[stack_off % BPF_REG_SIZE] == STACK_DYNPTR) { 7157 verbose(env, "potential write to dynptr at off=%d disallowed\n", i); 7158 return -EACCES; 7159 } 7160 } 7161 meta->access_size = access_size; 7162 meta->regno = regno; 7163 return 0; 7164 } 7165 7166 for (i = min_off; i < max_off + access_size; i++) { 7167 u8 *stype; 7168 7169 slot = -i - 1; 7170 spi = slot / BPF_REG_SIZE; 7171 if (state->allocated_stack <= slot) { 7172 verbose(env, "verifier bug: allocated_stack too small"); 7173 return -EFAULT; 7174 } 7175 7176 stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE]; 7177 if (*stype == STACK_MISC) 7178 goto mark; 7179 if ((*stype == STACK_ZERO) || 7180 (*stype == STACK_INVALID && env->allow_uninit_stack)) { 7181 if (clobber) { 7182 /* helper can write anything into the stack */ 7183 *stype = STACK_MISC; 7184 } 7185 goto mark; 7186 } 7187 7188 if (is_spilled_reg(&state->stack[spi]) && 7189 (state->stack[spi].spilled_ptr.type == SCALAR_VALUE || 7190 env->allow_ptr_leaks)) { 7191 if (clobber) { 7192 __mark_reg_unknown(env, &state->stack[spi].spilled_ptr); 7193 for (j = 0; j < BPF_REG_SIZE; j++) 7194 scrub_spilled_slot(&state->stack[spi].slot_type[j]); 7195 } 7196 goto mark; 7197 } 7198 7199 if (tnum_is_const(reg->var_off)) { 7200 verbose(env, "invalid%s read from stack R%d off %d+%d size %d\n", 7201 err_extra, regno, min_off, i - min_off, access_size); 7202 } else { 7203 char tn_buf[48]; 7204 7205 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 7206 verbose(env, "invalid%s read from stack R%d var_off %s+%d size %d\n", 7207 err_extra, regno, tn_buf, i - min_off, access_size); 7208 } 7209 return -EACCES; 7210 mark: 7211 /* reading any byte out of 8-byte 'spill_slot' will cause 7212 * the whole slot to be marked as 'read' 7213 */ 7214 mark_reg_read(env, &state->stack[spi].spilled_ptr, 7215 state->stack[spi].spilled_ptr.parent, 7216 REG_LIVE_READ64); 7217 /* We do not set REG_LIVE_WRITTEN for stack slot, as we can not 7218 * be sure that whether stack slot is written to or not. Hence, 7219 * we must still conservatively propagate reads upwards even if 7220 * helper may write to the entire memory range. 7221 */ 7222 } 7223 return 0; 7224 } 7225 7226 static int check_helper_mem_access(struct bpf_verifier_env *env, int regno, 7227 int access_size, enum bpf_access_type access_type, 7228 bool zero_size_allowed, 7229 struct bpf_call_arg_meta *meta) 7230 { 7231 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno]; 7232 u32 *max_access; 7233 7234 switch (base_type(reg->type)) { 7235 case PTR_TO_PACKET: 7236 case PTR_TO_PACKET_META: 7237 return check_packet_access(env, regno, reg->off, access_size, 7238 zero_size_allowed); 7239 case PTR_TO_MAP_KEY: 7240 if (access_type == BPF_WRITE) { 7241 verbose(env, "R%d cannot write into %s\n", regno, 7242 reg_type_str(env, reg->type)); 7243 return -EACCES; 7244 } 7245 return check_mem_region_access(env, regno, reg->off, access_size, 7246 reg->map_ptr->key_size, false); 7247 case PTR_TO_MAP_VALUE: 7248 if (check_map_access_type(env, regno, reg->off, access_size, access_type)) 7249 return -EACCES; 7250 return check_map_access(env, regno, reg->off, access_size, 7251 zero_size_allowed, ACCESS_HELPER); 7252 case PTR_TO_MEM: 7253 if (type_is_rdonly_mem(reg->type)) { 7254 if (access_type == BPF_WRITE) { 7255 verbose(env, "R%d cannot write into %s\n", regno, 7256 reg_type_str(env, reg->type)); 7257 return -EACCES; 7258 } 7259 } 7260 return check_mem_region_access(env, regno, reg->off, 7261 access_size, reg->mem_size, 7262 zero_size_allowed); 7263 case PTR_TO_BUF: 7264 if (type_is_rdonly_mem(reg->type)) { 7265 if (access_type == BPF_WRITE) { 7266 verbose(env, "R%d cannot write into %s\n", regno, 7267 reg_type_str(env, reg->type)); 7268 return -EACCES; 7269 } 7270 7271 max_access = &env->prog->aux->max_rdonly_access; 7272 } else { 7273 max_access = &env->prog->aux->max_rdwr_access; 7274 } 7275 return check_buffer_access(env, reg, regno, reg->off, 7276 access_size, zero_size_allowed, 7277 max_access); 7278 case PTR_TO_STACK: 7279 return check_stack_range_initialized( 7280 env, 7281 regno, reg->off, access_size, 7282 zero_size_allowed, ACCESS_HELPER, meta); 7283 case PTR_TO_BTF_ID: 7284 return check_ptr_to_btf_access(env, regs, regno, reg->off, 7285 access_size, BPF_READ, -1); 7286 case PTR_TO_CTX: 7287 /* in case the function doesn't know how to access the context, 7288 * (because we are in a program of type SYSCALL for example), we 7289 * can not statically check its size. 7290 * Dynamically check it now. 7291 */ 7292 if (!env->ops->convert_ctx_access) { 7293 int offset = access_size - 1; 7294 7295 /* Allow zero-byte read from PTR_TO_CTX */ 7296 if (access_size == 0) 7297 return zero_size_allowed ? 0 : -EACCES; 7298 7299 return check_mem_access(env, env->insn_idx, regno, offset, BPF_B, 7300 access_type, -1, false, false); 7301 } 7302 7303 fallthrough; 7304 default: /* scalar_value or invalid ptr */ 7305 /* Allow zero-byte read from NULL, regardless of pointer type */ 7306 if (zero_size_allowed && access_size == 0 && 7307 register_is_null(reg)) 7308 return 0; 7309 7310 verbose(env, "R%d type=%s ", regno, 7311 reg_type_str(env, reg->type)); 7312 verbose(env, "expected=%s\n", reg_type_str(env, PTR_TO_STACK)); 7313 return -EACCES; 7314 } 7315 } 7316 7317 static int check_mem_size_reg(struct bpf_verifier_env *env, 7318 struct bpf_reg_state *reg, u32 regno, 7319 enum bpf_access_type access_type, 7320 bool zero_size_allowed, 7321 struct bpf_call_arg_meta *meta) 7322 { 7323 int err; 7324 7325 /* This is used to refine r0 return value bounds for helpers 7326 * that enforce this value as an upper bound on return values. 7327 * See do_refine_retval_range() for helpers that can refine 7328 * the return value. C type of helper is u32 so we pull register 7329 * bound from umax_value however, if negative verifier errors 7330 * out. Only upper bounds can be learned because retval is an 7331 * int type and negative retvals are allowed. 7332 */ 7333 meta->msize_max_value = reg->umax_value; 7334 7335 /* The register is SCALAR_VALUE; the access check happens using 7336 * its boundaries. For unprivileged variable accesses, disable 7337 * raw mode so that the program is required to initialize all 7338 * the memory that the helper could just partially fill up. 7339 */ 7340 if (!tnum_is_const(reg->var_off)) 7341 meta = NULL; 7342 7343 if (reg->smin_value < 0) { 7344 verbose(env, "R%d min value is negative, either use unsigned or 'var &= const'\n", 7345 regno); 7346 return -EACCES; 7347 } 7348 7349 if (reg->umin_value == 0 && !zero_size_allowed) { 7350 verbose(env, "R%d invalid zero-sized read: u64=[%lld,%lld]\n", 7351 regno, reg->umin_value, reg->umax_value); 7352 return -EACCES; 7353 } 7354 7355 if (reg->umax_value >= BPF_MAX_VAR_SIZ) { 7356 verbose(env, "R%d unbounded memory access, use 'var &= const' or 'if (var < const)'\n", 7357 regno); 7358 return -EACCES; 7359 } 7360 err = check_helper_mem_access(env, regno - 1, reg->umax_value, 7361 access_type, zero_size_allowed, meta); 7362 if (!err) 7363 err = mark_chain_precision(env, regno); 7364 return err; 7365 } 7366 7367 int check_mem_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg, 7368 u32 regno, u32 mem_size) 7369 { 7370 bool may_be_null = type_may_be_null(reg->type); 7371 struct bpf_reg_state saved_reg; 7372 int err; 7373 7374 if (register_is_null(reg)) 7375 return 0; 7376 7377 /* Assuming that the register contains a value check if the memory 7378 * access is safe. Temporarily save and restore the register's state as 7379 * the conversion shouldn't be visible to a caller. 7380 */ 7381 if (may_be_null) { 7382 saved_reg = *reg; 7383 mark_ptr_not_null_reg(reg); 7384 } 7385 7386 err = check_helper_mem_access(env, regno, mem_size, BPF_READ, true, NULL); 7387 err = err ?: check_helper_mem_access(env, regno, mem_size, BPF_WRITE, true, NULL); 7388 7389 if (may_be_null) 7390 *reg = saved_reg; 7391 7392 return err; 7393 } 7394 7395 static int check_kfunc_mem_size_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg, 7396 u32 regno) 7397 { 7398 struct bpf_reg_state *mem_reg = &cur_regs(env)[regno - 1]; 7399 bool may_be_null = type_may_be_null(mem_reg->type); 7400 struct bpf_reg_state saved_reg; 7401 struct bpf_call_arg_meta meta; 7402 int err; 7403 7404 WARN_ON_ONCE(regno < BPF_REG_2 || regno > BPF_REG_5); 7405 7406 memset(&meta, 0, sizeof(meta)); 7407 7408 if (may_be_null) { 7409 saved_reg = *mem_reg; 7410 mark_ptr_not_null_reg(mem_reg); 7411 } 7412 7413 err = check_mem_size_reg(env, reg, regno, BPF_READ, true, &meta); 7414 err = err ?: check_mem_size_reg(env, reg, regno, BPF_WRITE, true, &meta); 7415 7416 if (may_be_null) 7417 *mem_reg = saved_reg; 7418 7419 return err; 7420 } 7421 7422 /* Implementation details: 7423 * bpf_map_lookup returns PTR_TO_MAP_VALUE_OR_NULL. 7424 * bpf_obj_new returns PTR_TO_BTF_ID | MEM_ALLOC | PTR_MAYBE_NULL. 7425 * Two bpf_map_lookups (even with the same key) will have different reg->id. 7426 * Two separate bpf_obj_new will also have different reg->id. 7427 * For traditional PTR_TO_MAP_VALUE or PTR_TO_BTF_ID | MEM_ALLOC, the verifier 7428 * clears reg->id after value_or_null->value transition, since the verifier only 7429 * cares about the range of access to valid map value pointer and doesn't care 7430 * about actual address of the map element. 7431 * For maps with 'struct bpf_spin_lock' inside map value the verifier keeps 7432 * reg->id > 0 after value_or_null->value transition. By doing so 7433 * two bpf_map_lookups will be considered two different pointers that 7434 * point to different bpf_spin_locks. Likewise for pointers to allocated objects 7435 * returned from bpf_obj_new. 7436 * The verifier allows taking only one bpf_spin_lock at a time to avoid 7437 * dead-locks. 7438 * Since only one bpf_spin_lock is allowed the checks are simpler than 7439 * reg_is_refcounted() logic. The verifier needs to remember only 7440 * one spin_lock instead of array of acquired_refs. 7441 * cur_state->active_lock remembers which map value element or allocated 7442 * object got locked and clears it after bpf_spin_unlock. 7443 */ 7444 static int process_spin_lock(struct bpf_verifier_env *env, int regno, 7445 bool is_lock) 7446 { 7447 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno]; 7448 struct bpf_verifier_state *cur = env->cur_state; 7449 bool is_const = tnum_is_const(reg->var_off); 7450 u64 val = reg->var_off.value; 7451 struct bpf_map *map = NULL; 7452 struct btf *btf = NULL; 7453 struct btf_record *rec; 7454 7455 if (!is_const) { 7456 verbose(env, 7457 "R%d doesn't have constant offset. bpf_spin_lock has to be at the constant offset\n", 7458 regno); 7459 return -EINVAL; 7460 } 7461 if (reg->type == PTR_TO_MAP_VALUE) { 7462 map = reg->map_ptr; 7463 if (!map->btf) { 7464 verbose(env, 7465 "map '%s' has to have BTF in order to use bpf_spin_lock\n", 7466 map->name); 7467 return -EINVAL; 7468 } 7469 } else { 7470 btf = reg->btf; 7471 } 7472 7473 rec = reg_btf_record(reg); 7474 if (!btf_record_has_field(rec, BPF_SPIN_LOCK)) { 7475 verbose(env, "%s '%s' has no valid bpf_spin_lock\n", map ? "map" : "local", 7476 map ? map->name : "kptr"); 7477 return -EINVAL; 7478 } 7479 if (rec->spin_lock_off != val + reg->off) { 7480 verbose(env, "off %lld doesn't point to 'struct bpf_spin_lock' that is at %d\n", 7481 val + reg->off, rec->spin_lock_off); 7482 return -EINVAL; 7483 } 7484 if (is_lock) { 7485 if (cur->active_lock.ptr) { 7486 verbose(env, 7487 "Locking two bpf_spin_locks are not allowed\n"); 7488 return -EINVAL; 7489 } 7490 if (map) 7491 cur->active_lock.ptr = map; 7492 else 7493 cur->active_lock.ptr = btf; 7494 cur->active_lock.id = reg->id; 7495 } else { 7496 void *ptr; 7497 7498 if (map) 7499 ptr = map; 7500 else 7501 ptr = btf; 7502 7503 if (!cur->active_lock.ptr) { 7504 verbose(env, "bpf_spin_unlock without taking a lock\n"); 7505 return -EINVAL; 7506 } 7507 if (cur->active_lock.ptr != ptr || 7508 cur->active_lock.id != reg->id) { 7509 verbose(env, "bpf_spin_unlock of different lock\n"); 7510 return -EINVAL; 7511 } 7512 7513 invalidate_non_owning_refs(env); 7514 7515 cur->active_lock.ptr = NULL; 7516 cur->active_lock.id = 0; 7517 } 7518 return 0; 7519 } 7520 7521 static int process_timer_func(struct bpf_verifier_env *env, int regno, 7522 struct bpf_call_arg_meta *meta) 7523 { 7524 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno]; 7525 bool is_const = tnum_is_const(reg->var_off); 7526 struct bpf_map *map = reg->map_ptr; 7527 u64 val = reg->var_off.value; 7528 7529 if (!is_const) { 7530 verbose(env, 7531 "R%d doesn't have constant offset. bpf_timer has to be at the constant offset\n", 7532 regno); 7533 return -EINVAL; 7534 } 7535 if (!map->btf) { 7536 verbose(env, "map '%s' has to have BTF in order to use bpf_timer\n", 7537 map->name); 7538 return -EINVAL; 7539 } 7540 if (!btf_record_has_field(map->record, BPF_TIMER)) { 7541 verbose(env, "map '%s' has no valid bpf_timer\n", map->name); 7542 return -EINVAL; 7543 } 7544 if (map->record->timer_off != val + reg->off) { 7545 verbose(env, "off %lld doesn't point to 'struct bpf_timer' that is at %d\n", 7546 val + reg->off, map->record->timer_off); 7547 return -EINVAL; 7548 } 7549 if (meta->map_ptr) { 7550 verbose(env, "verifier bug. Two map pointers in a timer helper\n"); 7551 return -EFAULT; 7552 } 7553 meta->map_uid = reg->map_uid; 7554 meta->map_ptr = map; 7555 return 0; 7556 } 7557 7558 static int process_kptr_func(struct bpf_verifier_env *env, int regno, 7559 struct bpf_call_arg_meta *meta) 7560 { 7561 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno]; 7562 struct bpf_map *map_ptr = reg->map_ptr; 7563 struct btf_field *kptr_field; 7564 u32 kptr_off; 7565 7566 if (!tnum_is_const(reg->var_off)) { 7567 verbose(env, 7568 "R%d doesn't have constant offset. kptr has to be at the constant offset\n", 7569 regno); 7570 return -EINVAL; 7571 } 7572 if (!map_ptr->btf) { 7573 verbose(env, "map '%s' has to have BTF in order to use bpf_kptr_xchg\n", 7574 map_ptr->name); 7575 return -EINVAL; 7576 } 7577 if (!btf_record_has_field(map_ptr->record, BPF_KPTR)) { 7578 verbose(env, "map '%s' has no valid kptr\n", map_ptr->name); 7579 return -EINVAL; 7580 } 7581 7582 meta->map_ptr = map_ptr; 7583 kptr_off = reg->off + reg->var_off.value; 7584 kptr_field = btf_record_find(map_ptr->record, kptr_off, BPF_KPTR); 7585 if (!kptr_field) { 7586 verbose(env, "off=%d doesn't point to kptr\n", kptr_off); 7587 return -EACCES; 7588 } 7589 if (kptr_field->type != BPF_KPTR_REF) { 7590 verbose(env, "off=%d kptr isn't referenced kptr\n", kptr_off); 7591 return -EACCES; 7592 } 7593 meta->kptr_field = kptr_field; 7594 return 0; 7595 } 7596 7597 /* There are two register types representing a bpf_dynptr, one is PTR_TO_STACK 7598 * which points to a stack slot, and the other is CONST_PTR_TO_DYNPTR. 7599 * 7600 * In both cases we deal with the first 8 bytes, but need to mark the next 8 7601 * bytes as STACK_DYNPTR in case of PTR_TO_STACK. In case of 7602 * CONST_PTR_TO_DYNPTR, we are guaranteed to get the beginning of the object. 7603 * 7604 * Mutability of bpf_dynptr is at two levels, one is at the level of struct 7605 * bpf_dynptr itself, i.e. whether the helper is receiving a pointer to struct 7606 * bpf_dynptr or pointer to const struct bpf_dynptr. In the former case, it can 7607 * mutate the view of the dynptr and also possibly destroy it. In the latter 7608 * case, it cannot mutate the bpf_dynptr itself but it can still mutate the 7609 * memory that dynptr points to. 7610 * 7611 * The verifier will keep track both levels of mutation (bpf_dynptr's in 7612 * reg->type and the memory's in reg->dynptr.type), but there is no support for 7613 * readonly dynptr view yet, hence only the first case is tracked and checked. 7614 * 7615 * This is consistent with how C applies the const modifier to a struct object, 7616 * where the pointer itself inside bpf_dynptr becomes const but not what it 7617 * points to. 7618 * 7619 * Helpers which do not mutate the bpf_dynptr set MEM_RDONLY in their argument 7620 * type, and declare it as 'const struct bpf_dynptr *' in their prototype. 7621 */ 7622 static int process_dynptr_func(struct bpf_verifier_env *env, int regno, int insn_idx, 7623 enum bpf_arg_type arg_type, int clone_ref_obj_id) 7624 { 7625 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno]; 7626 int err; 7627 7628 /* MEM_UNINIT and MEM_RDONLY are exclusive, when applied to an 7629 * ARG_PTR_TO_DYNPTR (or ARG_PTR_TO_DYNPTR | DYNPTR_TYPE_*): 7630 */ 7631 if ((arg_type & (MEM_UNINIT | MEM_RDONLY)) == (MEM_UNINIT | MEM_RDONLY)) { 7632 verbose(env, "verifier internal error: misconfigured dynptr helper type flags\n"); 7633 return -EFAULT; 7634 } 7635 7636 /* MEM_UNINIT - Points to memory that is an appropriate candidate for 7637 * constructing a mutable bpf_dynptr object. 7638 * 7639 * Currently, this is only possible with PTR_TO_STACK 7640 * pointing to a region of at least 16 bytes which doesn't 7641 * contain an existing bpf_dynptr. 7642 * 7643 * MEM_RDONLY - Points to a initialized bpf_dynptr that will not be 7644 * mutated or destroyed. However, the memory it points to 7645 * may be mutated. 7646 * 7647 * None - Points to a initialized dynptr that can be mutated and 7648 * destroyed, including mutation of the memory it points 7649 * to. 7650 */ 7651 if (arg_type & MEM_UNINIT) { 7652 int i; 7653 7654 if (!is_dynptr_reg_valid_uninit(env, reg)) { 7655 verbose(env, "Dynptr has to be an uninitialized dynptr\n"); 7656 return -EINVAL; 7657 } 7658 7659 /* we write BPF_DW bits (8 bytes) at a time */ 7660 for (i = 0; i < BPF_DYNPTR_SIZE; i += 8) { 7661 err = check_mem_access(env, insn_idx, regno, 7662 i, BPF_DW, BPF_WRITE, -1, false, false); 7663 if (err) 7664 return err; 7665 } 7666 7667 err = mark_stack_slots_dynptr(env, reg, arg_type, insn_idx, clone_ref_obj_id); 7668 } else /* MEM_RDONLY and None case from above */ { 7669 /* For the reg->type == PTR_TO_STACK case, bpf_dynptr is never const */ 7670 if (reg->type == CONST_PTR_TO_DYNPTR && !(arg_type & MEM_RDONLY)) { 7671 verbose(env, "cannot pass pointer to const bpf_dynptr, the helper mutates it\n"); 7672 return -EINVAL; 7673 } 7674 7675 if (!is_dynptr_reg_valid_init(env, reg)) { 7676 verbose(env, 7677 "Expected an initialized dynptr as arg #%d\n", 7678 regno); 7679 return -EINVAL; 7680 } 7681 7682 /* Fold modifiers (in this case, MEM_RDONLY) when checking expected type */ 7683 if (!is_dynptr_type_expected(env, reg, arg_type & ~MEM_RDONLY)) { 7684 verbose(env, 7685 "Expected a dynptr of type %s as arg #%d\n", 7686 dynptr_type_str(arg_to_dynptr_type(arg_type)), regno); 7687 return -EINVAL; 7688 } 7689 7690 err = mark_dynptr_read(env, reg); 7691 } 7692 return err; 7693 } 7694 7695 static u32 iter_ref_obj_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg, int spi) 7696 { 7697 struct bpf_func_state *state = func(env, reg); 7698 7699 return state->stack[spi].spilled_ptr.ref_obj_id; 7700 } 7701 7702 static bool is_iter_kfunc(struct bpf_kfunc_call_arg_meta *meta) 7703 { 7704 return meta->kfunc_flags & (KF_ITER_NEW | KF_ITER_NEXT | KF_ITER_DESTROY); 7705 } 7706 7707 static bool is_iter_new_kfunc(struct bpf_kfunc_call_arg_meta *meta) 7708 { 7709 return meta->kfunc_flags & KF_ITER_NEW; 7710 } 7711 7712 static bool is_iter_next_kfunc(struct bpf_kfunc_call_arg_meta *meta) 7713 { 7714 return meta->kfunc_flags & KF_ITER_NEXT; 7715 } 7716 7717 static bool is_iter_destroy_kfunc(struct bpf_kfunc_call_arg_meta *meta) 7718 { 7719 return meta->kfunc_flags & KF_ITER_DESTROY; 7720 } 7721 7722 static bool is_kfunc_arg_iter(struct bpf_kfunc_call_arg_meta *meta, int arg) 7723 { 7724 /* btf_check_iter_kfuncs() guarantees that first argument of any iter 7725 * kfunc is iter state pointer 7726 */ 7727 return arg == 0 && is_iter_kfunc(meta); 7728 } 7729 7730 static int process_iter_arg(struct bpf_verifier_env *env, int regno, int insn_idx, 7731 struct bpf_kfunc_call_arg_meta *meta) 7732 { 7733 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno]; 7734 const struct btf_type *t; 7735 const struct btf_param *arg; 7736 int spi, err, i, nr_slots; 7737 u32 btf_id; 7738 7739 /* btf_check_iter_kfuncs() ensures we don't need to validate anything here */ 7740 arg = &btf_params(meta->func_proto)[0]; 7741 t = btf_type_skip_modifiers(meta->btf, arg->type, NULL); /* PTR */ 7742 t = btf_type_skip_modifiers(meta->btf, t->type, &btf_id); /* STRUCT */ 7743 nr_slots = t->size / BPF_REG_SIZE; 7744 7745 if (is_iter_new_kfunc(meta)) { 7746 /* bpf_iter_<type>_new() expects pointer to uninit iter state */ 7747 if (!is_iter_reg_valid_uninit(env, reg, nr_slots)) { 7748 verbose(env, "expected uninitialized iter_%s as arg #%d\n", 7749 iter_type_str(meta->btf, btf_id), regno); 7750 return -EINVAL; 7751 } 7752 7753 for (i = 0; i < nr_slots * 8; i += BPF_REG_SIZE) { 7754 err = check_mem_access(env, insn_idx, regno, 7755 i, BPF_DW, BPF_WRITE, -1, false, false); 7756 if (err) 7757 return err; 7758 } 7759 7760 err = mark_stack_slots_iter(env, reg, insn_idx, meta->btf, btf_id, nr_slots); 7761 if (err) 7762 return err; 7763 } else { 7764 /* iter_next() or iter_destroy() expect initialized iter state*/ 7765 if (!is_iter_reg_valid_init(env, reg, meta->btf, btf_id, nr_slots)) { 7766 verbose(env, "expected an initialized iter_%s as arg #%d\n", 7767 iter_type_str(meta->btf, btf_id), regno); 7768 return -EINVAL; 7769 } 7770 7771 spi = iter_get_spi(env, reg, nr_slots); 7772 if (spi < 0) 7773 return spi; 7774 7775 err = mark_iter_read(env, reg, spi, nr_slots); 7776 if (err) 7777 return err; 7778 7779 /* remember meta->iter info for process_iter_next_call() */ 7780 meta->iter.spi = spi; 7781 meta->iter.frameno = reg->frameno; 7782 meta->ref_obj_id = iter_ref_obj_id(env, reg, spi); 7783 7784 if (is_iter_destroy_kfunc(meta)) { 7785 err = unmark_stack_slots_iter(env, reg, nr_slots); 7786 if (err) 7787 return err; 7788 } 7789 } 7790 7791 return 0; 7792 } 7793 7794 /* Look for a previous loop entry at insn_idx: nearest parent state 7795 * stopped at insn_idx with callsites matching those in cur->frame. 7796 */ 7797 static struct bpf_verifier_state *find_prev_entry(struct bpf_verifier_env *env, 7798 struct bpf_verifier_state *cur, 7799 int insn_idx) 7800 { 7801 struct bpf_verifier_state_list *sl; 7802 struct bpf_verifier_state *st; 7803 7804 /* Explored states are pushed in stack order, most recent states come first */ 7805 sl = *explored_state(env, insn_idx); 7806 for (; sl; sl = sl->next) { 7807 /* If st->branches != 0 state is a part of current DFS verification path, 7808 * hence cur & st for a loop. 7809 */ 7810 st = &sl->state; 7811 if (st->insn_idx == insn_idx && st->branches && same_callsites(st, cur) && 7812 st->dfs_depth < cur->dfs_depth) 7813 return st; 7814 } 7815 7816 return NULL; 7817 } 7818 7819 static void reset_idmap_scratch(struct bpf_verifier_env *env); 7820 static bool regs_exact(const struct bpf_reg_state *rold, 7821 const struct bpf_reg_state *rcur, 7822 struct bpf_idmap *idmap); 7823 7824 static void maybe_widen_reg(struct bpf_verifier_env *env, 7825 struct bpf_reg_state *rold, struct bpf_reg_state *rcur, 7826 struct bpf_idmap *idmap) 7827 { 7828 if (rold->type != SCALAR_VALUE) 7829 return; 7830 if (rold->type != rcur->type) 7831 return; 7832 if (rold->precise || rcur->precise || regs_exact(rold, rcur, idmap)) 7833 return; 7834 __mark_reg_unknown(env, rcur); 7835 } 7836 7837 static int widen_imprecise_scalars(struct bpf_verifier_env *env, 7838 struct bpf_verifier_state *old, 7839 struct bpf_verifier_state *cur) 7840 { 7841 struct bpf_func_state *fold, *fcur; 7842 int i, fr; 7843 7844 reset_idmap_scratch(env); 7845 for (fr = old->curframe; fr >= 0; fr--) { 7846 fold = old->frame[fr]; 7847 fcur = cur->frame[fr]; 7848 7849 for (i = 0; i < MAX_BPF_REG; i++) 7850 maybe_widen_reg(env, 7851 &fold->regs[i], 7852 &fcur->regs[i], 7853 &env->idmap_scratch); 7854 7855 for (i = 0; i < fold->allocated_stack / BPF_REG_SIZE; i++) { 7856 if (!is_spilled_reg(&fold->stack[i]) || 7857 !is_spilled_reg(&fcur->stack[i])) 7858 continue; 7859 7860 maybe_widen_reg(env, 7861 &fold->stack[i].spilled_ptr, 7862 &fcur->stack[i].spilled_ptr, 7863 &env->idmap_scratch); 7864 } 7865 } 7866 return 0; 7867 } 7868 7869 static struct bpf_reg_state *get_iter_from_state(struct bpf_verifier_state *cur_st, 7870 struct bpf_kfunc_call_arg_meta *meta) 7871 { 7872 int iter_frameno = meta->iter.frameno; 7873 int iter_spi = meta->iter.spi; 7874 7875 return &cur_st->frame[iter_frameno]->stack[iter_spi].spilled_ptr; 7876 } 7877 7878 /* process_iter_next_call() is called when verifier gets to iterator's next 7879 * "method" (e.g., bpf_iter_num_next() for numbers iterator) call. We'll refer 7880 * to it as just "iter_next()" in comments below. 7881 * 7882 * BPF verifier relies on a crucial contract for any iter_next() 7883 * implementation: it should *eventually* return NULL, and once that happens 7884 * it should keep returning NULL. That is, once iterator exhausts elements to 7885 * iterate, it should never reset or spuriously return new elements. 7886 * 7887 * With the assumption of such contract, process_iter_next_call() simulates 7888 * a fork in the verifier state to validate loop logic correctness and safety 7889 * without having to simulate infinite amount of iterations. 7890 * 7891 * In current state, we first assume that iter_next() returned NULL and 7892 * iterator state is set to DRAINED (BPF_ITER_STATE_DRAINED). In such 7893 * conditions we should not form an infinite loop and should eventually reach 7894 * exit. 7895 * 7896 * Besides that, we also fork current state and enqueue it for later 7897 * verification. In a forked state we keep iterator state as ACTIVE 7898 * (BPF_ITER_STATE_ACTIVE) and assume non-NULL return from iter_next(). We 7899 * also bump iteration depth to prevent erroneous infinite loop detection 7900 * later on (see iter_active_depths_differ() comment for details). In this 7901 * state we assume that we'll eventually loop back to another iter_next() 7902 * calls (it could be in exactly same location or in some other instruction, 7903 * it doesn't matter, we don't make any unnecessary assumptions about this, 7904 * everything revolves around iterator state in a stack slot, not which 7905 * instruction is calling iter_next()). When that happens, we either will come 7906 * to iter_next() with equivalent state and can conclude that next iteration 7907 * will proceed in exactly the same way as we just verified, so it's safe to 7908 * assume that loop converges. If not, we'll go on another iteration 7909 * simulation with a different input state, until all possible starting states 7910 * are validated or we reach maximum number of instructions limit. 7911 * 7912 * This way, we will either exhaustively discover all possible input states 7913 * that iterator loop can start with and eventually will converge, or we'll 7914 * effectively regress into bounded loop simulation logic and either reach 7915 * maximum number of instructions if loop is not provably convergent, or there 7916 * is some statically known limit on number of iterations (e.g., if there is 7917 * an explicit `if n > 100 then break;` statement somewhere in the loop). 7918 * 7919 * Iteration convergence logic in is_state_visited() relies on exact 7920 * states comparison, which ignores read and precision marks. 7921 * This is necessary because read and precision marks are not finalized 7922 * while in the loop. Exact comparison might preclude convergence for 7923 * simple programs like below: 7924 * 7925 * i = 0; 7926 * while(iter_next(&it)) 7927 * i++; 7928 * 7929 * At each iteration step i++ would produce a new distinct state and 7930 * eventually instruction processing limit would be reached. 7931 * 7932 * To avoid such behavior speculatively forget (widen) range for 7933 * imprecise scalar registers, if those registers were not precise at the 7934 * end of the previous iteration and do not match exactly. 7935 * 7936 * This is a conservative heuristic that allows to verify wide range of programs, 7937 * however it precludes verification of programs that conjure an 7938 * imprecise value on the first loop iteration and use it as precise on a second. 7939 * For example, the following safe program would fail to verify: 7940 * 7941 * struct bpf_num_iter it; 7942 * int arr[10]; 7943 * int i = 0, a = 0; 7944 * bpf_iter_num_new(&it, 0, 10); 7945 * while (bpf_iter_num_next(&it)) { 7946 * if (a == 0) { 7947 * a = 1; 7948 * i = 7; // Because i changed verifier would forget 7949 * // it's range on second loop entry. 7950 * } else { 7951 * arr[i] = 42; // This would fail to verify. 7952 * } 7953 * } 7954 * bpf_iter_num_destroy(&it); 7955 */ 7956 static int process_iter_next_call(struct bpf_verifier_env *env, int insn_idx, 7957 struct bpf_kfunc_call_arg_meta *meta) 7958 { 7959 struct bpf_verifier_state *cur_st = env->cur_state, *queued_st, *prev_st; 7960 struct bpf_func_state *cur_fr = cur_st->frame[cur_st->curframe], *queued_fr; 7961 struct bpf_reg_state *cur_iter, *queued_iter; 7962 7963 BTF_TYPE_EMIT(struct bpf_iter); 7964 7965 cur_iter = get_iter_from_state(cur_st, meta); 7966 7967 if (cur_iter->iter.state != BPF_ITER_STATE_ACTIVE && 7968 cur_iter->iter.state != BPF_ITER_STATE_DRAINED) { 7969 verbose(env, "verifier internal error: unexpected iterator state %d (%s)\n", 7970 cur_iter->iter.state, iter_state_str(cur_iter->iter.state)); 7971 return -EFAULT; 7972 } 7973 7974 if (cur_iter->iter.state == BPF_ITER_STATE_ACTIVE) { 7975 /* Because iter_next() call is a checkpoint is_state_visitied() 7976 * should guarantee parent state with same call sites and insn_idx. 7977 */ 7978 if (!cur_st->parent || cur_st->parent->insn_idx != insn_idx || 7979 !same_callsites(cur_st->parent, cur_st)) { 7980 verbose(env, "bug: bad parent state for iter next call"); 7981 return -EFAULT; 7982 } 7983 /* Note cur_st->parent in the call below, it is necessary to skip 7984 * checkpoint created for cur_st by is_state_visited() 7985 * right at this instruction. 7986 */ 7987 prev_st = find_prev_entry(env, cur_st->parent, insn_idx); 7988 /* branch out active iter state */ 7989 queued_st = push_stack(env, insn_idx + 1, insn_idx, false); 7990 if (!queued_st) 7991 return -ENOMEM; 7992 7993 queued_iter = get_iter_from_state(queued_st, meta); 7994 queued_iter->iter.state = BPF_ITER_STATE_ACTIVE; 7995 queued_iter->iter.depth++; 7996 if (prev_st) 7997 widen_imprecise_scalars(env, prev_st, queued_st); 7998 7999 queued_fr = queued_st->frame[queued_st->curframe]; 8000 mark_ptr_not_null_reg(&queued_fr->regs[BPF_REG_0]); 8001 } 8002 8003 /* switch to DRAINED state, but keep the depth unchanged */ 8004 /* mark current iter state as drained and assume returned NULL */ 8005 cur_iter->iter.state = BPF_ITER_STATE_DRAINED; 8006 __mark_reg_const_zero(&cur_fr->regs[BPF_REG_0]); 8007 8008 return 0; 8009 } 8010 8011 static bool arg_type_is_mem_size(enum bpf_arg_type type) 8012 { 8013 return type == ARG_CONST_SIZE || 8014 type == ARG_CONST_SIZE_OR_ZERO; 8015 } 8016 8017 static bool arg_type_is_raw_mem(enum bpf_arg_type type) 8018 { 8019 return base_type(type) == ARG_PTR_TO_MEM && 8020 type & MEM_UNINIT; 8021 } 8022 8023 static bool arg_type_is_release(enum bpf_arg_type type) 8024 { 8025 return type & OBJ_RELEASE; 8026 } 8027 8028 static bool arg_type_is_dynptr(enum bpf_arg_type type) 8029 { 8030 return base_type(type) == ARG_PTR_TO_DYNPTR; 8031 } 8032 8033 static int resolve_map_arg_type(struct bpf_verifier_env *env, 8034 const struct bpf_call_arg_meta *meta, 8035 enum bpf_arg_type *arg_type) 8036 { 8037 if (!meta->map_ptr) { 8038 /* kernel subsystem misconfigured verifier */ 8039 verbose(env, "invalid map_ptr to access map->type\n"); 8040 return -EACCES; 8041 } 8042 8043 switch (meta->map_ptr->map_type) { 8044 case BPF_MAP_TYPE_SOCKMAP: 8045 case BPF_MAP_TYPE_SOCKHASH: 8046 if (*arg_type == ARG_PTR_TO_MAP_VALUE) { 8047 *arg_type = ARG_PTR_TO_BTF_ID_SOCK_COMMON; 8048 } else { 8049 verbose(env, "invalid arg_type for sockmap/sockhash\n"); 8050 return -EINVAL; 8051 } 8052 break; 8053 case BPF_MAP_TYPE_BLOOM_FILTER: 8054 if (meta->func_id == BPF_FUNC_map_peek_elem) 8055 *arg_type = ARG_PTR_TO_MAP_VALUE; 8056 break; 8057 default: 8058 break; 8059 } 8060 return 0; 8061 } 8062 8063 struct bpf_reg_types { 8064 const enum bpf_reg_type types[10]; 8065 u32 *btf_id; 8066 }; 8067 8068 static const struct bpf_reg_types sock_types = { 8069 .types = { 8070 PTR_TO_SOCK_COMMON, 8071 PTR_TO_SOCKET, 8072 PTR_TO_TCP_SOCK, 8073 PTR_TO_XDP_SOCK, 8074 }, 8075 }; 8076 8077 #ifdef CONFIG_NET 8078 static const struct bpf_reg_types btf_id_sock_common_types = { 8079 .types = { 8080 PTR_TO_SOCK_COMMON, 8081 PTR_TO_SOCKET, 8082 PTR_TO_TCP_SOCK, 8083 PTR_TO_XDP_SOCK, 8084 PTR_TO_BTF_ID, 8085 PTR_TO_BTF_ID | PTR_TRUSTED, 8086 }, 8087 .btf_id = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON], 8088 }; 8089 #endif 8090 8091 static const struct bpf_reg_types mem_types = { 8092 .types = { 8093 PTR_TO_STACK, 8094 PTR_TO_PACKET, 8095 PTR_TO_PACKET_META, 8096 PTR_TO_MAP_KEY, 8097 PTR_TO_MAP_VALUE, 8098 PTR_TO_MEM, 8099 PTR_TO_MEM | MEM_RINGBUF, 8100 PTR_TO_BUF, 8101 PTR_TO_BTF_ID | PTR_TRUSTED, 8102 }, 8103 }; 8104 8105 static const struct bpf_reg_types spin_lock_types = { 8106 .types = { 8107 PTR_TO_MAP_VALUE, 8108 PTR_TO_BTF_ID | MEM_ALLOC, 8109 } 8110 }; 8111 8112 static const struct bpf_reg_types fullsock_types = { .types = { PTR_TO_SOCKET } }; 8113 static const struct bpf_reg_types scalar_types = { .types = { SCALAR_VALUE } }; 8114 static const struct bpf_reg_types context_types = { .types = { PTR_TO_CTX } }; 8115 static const struct bpf_reg_types ringbuf_mem_types = { .types = { PTR_TO_MEM | MEM_RINGBUF } }; 8116 static const struct bpf_reg_types const_map_ptr_types = { .types = { CONST_PTR_TO_MAP } }; 8117 static const struct bpf_reg_types btf_ptr_types = { 8118 .types = { 8119 PTR_TO_BTF_ID, 8120 PTR_TO_BTF_ID | PTR_TRUSTED, 8121 PTR_TO_BTF_ID | MEM_RCU, 8122 }, 8123 }; 8124 static const struct bpf_reg_types percpu_btf_ptr_types = { 8125 .types = { 8126 PTR_TO_BTF_ID | MEM_PERCPU, 8127 PTR_TO_BTF_ID | MEM_PERCPU | PTR_TRUSTED, 8128 } 8129 }; 8130 static const struct bpf_reg_types func_ptr_types = { .types = { PTR_TO_FUNC } }; 8131 static const struct bpf_reg_types stack_ptr_types = { .types = { PTR_TO_STACK } }; 8132 static const struct bpf_reg_types const_str_ptr_types = { .types = { PTR_TO_MAP_VALUE } }; 8133 static const struct bpf_reg_types timer_types = { .types = { PTR_TO_MAP_VALUE } }; 8134 static const struct bpf_reg_types kptr_types = { .types = { PTR_TO_MAP_VALUE } }; 8135 static const struct bpf_reg_types dynptr_types = { 8136 .types = { 8137 PTR_TO_STACK, 8138 CONST_PTR_TO_DYNPTR, 8139 } 8140 }; 8141 8142 static const struct bpf_reg_types *compatible_reg_types[__BPF_ARG_TYPE_MAX] = { 8143 [ARG_PTR_TO_MAP_KEY] = &mem_types, 8144 [ARG_PTR_TO_MAP_VALUE] = &mem_types, 8145 [ARG_CONST_SIZE] = &scalar_types, 8146 [ARG_CONST_SIZE_OR_ZERO] = &scalar_types, 8147 [ARG_CONST_ALLOC_SIZE_OR_ZERO] = &scalar_types, 8148 [ARG_CONST_MAP_PTR] = &const_map_ptr_types, 8149 [ARG_PTR_TO_CTX] = &context_types, 8150 [ARG_PTR_TO_SOCK_COMMON] = &sock_types, 8151 #ifdef CONFIG_NET 8152 [ARG_PTR_TO_BTF_ID_SOCK_COMMON] = &btf_id_sock_common_types, 8153 #endif 8154 [ARG_PTR_TO_SOCKET] = &fullsock_types, 8155 [ARG_PTR_TO_BTF_ID] = &btf_ptr_types, 8156 [ARG_PTR_TO_SPIN_LOCK] = &spin_lock_types, 8157 [ARG_PTR_TO_MEM] = &mem_types, 8158 [ARG_PTR_TO_RINGBUF_MEM] = &ringbuf_mem_types, 8159 [ARG_PTR_TO_PERCPU_BTF_ID] = &percpu_btf_ptr_types, 8160 [ARG_PTR_TO_FUNC] = &func_ptr_types, 8161 [ARG_PTR_TO_STACK] = &stack_ptr_types, 8162 [ARG_PTR_TO_CONST_STR] = &const_str_ptr_types, 8163 [ARG_PTR_TO_TIMER] = &timer_types, 8164 [ARG_PTR_TO_KPTR] = &kptr_types, 8165 [ARG_PTR_TO_DYNPTR] = &dynptr_types, 8166 }; 8167 8168 static int check_reg_type(struct bpf_verifier_env *env, u32 regno, 8169 enum bpf_arg_type arg_type, 8170 const u32 *arg_btf_id, 8171 struct bpf_call_arg_meta *meta) 8172 { 8173 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno]; 8174 enum bpf_reg_type expected, type = reg->type; 8175 const struct bpf_reg_types *compatible; 8176 int i, j; 8177 8178 compatible = compatible_reg_types[base_type(arg_type)]; 8179 if (!compatible) { 8180 verbose(env, "verifier internal error: unsupported arg type %d\n", arg_type); 8181 return -EFAULT; 8182 } 8183 8184 /* ARG_PTR_TO_MEM + RDONLY is compatible with PTR_TO_MEM and PTR_TO_MEM + RDONLY, 8185 * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM and NOT with PTR_TO_MEM + RDONLY 8186 * 8187 * Same for MAYBE_NULL: 8188 * 8189 * ARG_PTR_TO_MEM + MAYBE_NULL is compatible with PTR_TO_MEM and PTR_TO_MEM + MAYBE_NULL, 8190 * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM but NOT with PTR_TO_MEM + MAYBE_NULL 8191 * 8192 * ARG_PTR_TO_MEM is compatible with PTR_TO_MEM that is tagged with a dynptr type. 8193 * 8194 * Therefore we fold these flags depending on the arg_type before comparison. 8195 */ 8196 if (arg_type & MEM_RDONLY) 8197 type &= ~MEM_RDONLY; 8198 if (arg_type & PTR_MAYBE_NULL) 8199 type &= ~PTR_MAYBE_NULL; 8200 if (base_type(arg_type) == ARG_PTR_TO_MEM) 8201 type &= ~DYNPTR_TYPE_FLAG_MASK; 8202 8203 if (meta->func_id == BPF_FUNC_kptr_xchg && type_is_alloc(type)) 8204 type &= ~MEM_ALLOC; 8205 8206 for (i = 0; i < ARRAY_SIZE(compatible->types); i++) { 8207 expected = compatible->types[i]; 8208 if (expected == NOT_INIT) 8209 break; 8210 8211 if (type == expected) 8212 goto found; 8213 } 8214 8215 verbose(env, "R%d type=%s expected=", regno, reg_type_str(env, reg->type)); 8216 for (j = 0; j + 1 < i; j++) 8217 verbose(env, "%s, ", reg_type_str(env, compatible->types[j])); 8218 verbose(env, "%s\n", reg_type_str(env, compatible->types[j])); 8219 return -EACCES; 8220 8221 found: 8222 if (base_type(reg->type) != PTR_TO_BTF_ID) 8223 return 0; 8224 8225 if (compatible == &mem_types) { 8226 if (!(arg_type & MEM_RDONLY)) { 8227 verbose(env, 8228 "%s() may write into memory pointed by R%d type=%s\n", 8229 func_id_name(meta->func_id), 8230 regno, reg_type_str(env, reg->type)); 8231 return -EACCES; 8232 } 8233 return 0; 8234 } 8235 8236 switch ((int)reg->type) { 8237 case PTR_TO_BTF_ID: 8238 case PTR_TO_BTF_ID | PTR_TRUSTED: 8239 case PTR_TO_BTF_ID | MEM_RCU: 8240 case PTR_TO_BTF_ID | PTR_MAYBE_NULL: 8241 case PTR_TO_BTF_ID | PTR_MAYBE_NULL | MEM_RCU: 8242 { 8243 /* For bpf_sk_release, it needs to match against first member 8244 * 'struct sock_common', hence make an exception for it. This 8245 * allows bpf_sk_release to work for multiple socket types. 8246 */ 8247 bool strict_type_match = arg_type_is_release(arg_type) && 8248 meta->func_id != BPF_FUNC_sk_release; 8249 8250 if (type_may_be_null(reg->type) && 8251 (!type_may_be_null(arg_type) || arg_type_is_release(arg_type))) { 8252 verbose(env, "Possibly NULL pointer passed to helper arg%d\n", regno); 8253 return -EACCES; 8254 } 8255 8256 if (!arg_btf_id) { 8257 if (!compatible->btf_id) { 8258 verbose(env, "verifier internal error: missing arg compatible BTF ID\n"); 8259 return -EFAULT; 8260 } 8261 arg_btf_id = compatible->btf_id; 8262 } 8263 8264 if (meta->func_id == BPF_FUNC_kptr_xchg) { 8265 if (map_kptr_match_type(env, meta->kptr_field, reg, regno)) 8266 return -EACCES; 8267 } else { 8268 if (arg_btf_id == BPF_PTR_POISON) { 8269 verbose(env, "verifier internal error:"); 8270 verbose(env, "R%d has non-overwritten BPF_PTR_POISON type\n", 8271 regno); 8272 return -EACCES; 8273 } 8274 8275 if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off, 8276 btf_vmlinux, *arg_btf_id, 8277 strict_type_match)) { 8278 verbose(env, "R%d is of type %s but %s is expected\n", 8279 regno, btf_type_name(reg->btf, reg->btf_id), 8280 btf_type_name(btf_vmlinux, *arg_btf_id)); 8281 return -EACCES; 8282 } 8283 } 8284 break; 8285 } 8286 case PTR_TO_BTF_ID | MEM_ALLOC: 8287 if (meta->func_id != BPF_FUNC_spin_lock && meta->func_id != BPF_FUNC_spin_unlock && 8288 meta->func_id != BPF_FUNC_kptr_xchg) { 8289 verbose(env, "verifier internal error: unimplemented handling of MEM_ALLOC\n"); 8290 return -EFAULT; 8291 } 8292 if (meta->func_id == BPF_FUNC_kptr_xchg) { 8293 if (map_kptr_match_type(env, meta->kptr_field, reg, regno)) 8294 return -EACCES; 8295 } 8296 break; 8297 case PTR_TO_BTF_ID | MEM_PERCPU: 8298 case PTR_TO_BTF_ID | MEM_PERCPU | PTR_TRUSTED: 8299 /* Handled by helper specific checks */ 8300 break; 8301 default: 8302 verbose(env, "verifier internal error: invalid PTR_TO_BTF_ID register for type match\n"); 8303 return -EFAULT; 8304 } 8305 return 0; 8306 } 8307 8308 static struct btf_field * 8309 reg_find_field_offset(const struct bpf_reg_state *reg, s32 off, u32 fields) 8310 { 8311 struct btf_field *field; 8312 struct btf_record *rec; 8313 8314 rec = reg_btf_record(reg); 8315 if (!rec) 8316 return NULL; 8317 8318 field = btf_record_find(rec, off, fields); 8319 if (!field) 8320 return NULL; 8321 8322 return field; 8323 } 8324 8325 int check_func_arg_reg_off(struct bpf_verifier_env *env, 8326 const struct bpf_reg_state *reg, int regno, 8327 enum bpf_arg_type arg_type) 8328 { 8329 u32 type = reg->type; 8330 8331 /* When referenced register is passed to release function, its fixed 8332 * offset must be 0. 8333 * 8334 * We will check arg_type_is_release reg has ref_obj_id when storing 8335 * meta->release_regno. 8336 */ 8337 if (arg_type_is_release(arg_type)) { 8338 /* ARG_PTR_TO_DYNPTR with OBJ_RELEASE is a bit special, as it 8339 * may not directly point to the object being released, but to 8340 * dynptr pointing to such object, which might be at some offset 8341 * on the stack. In that case, we simply to fallback to the 8342 * default handling. 8343 */ 8344 if (arg_type_is_dynptr(arg_type) && type == PTR_TO_STACK) 8345 return 0; 8346 8347 /* Doing check_ptr_off_reg check for the offset will catch this 8348 * because fixed_off_ok is false, but checking here allows us 8349 * to give the user a better error message. 8350 */ 8351 if (reg->off) { 8352 verbose(env, "R%d must have zero offset when passed to release func or trusted arg to kfunc\n", 8353 regno); 8354 return -EINVAL; 8355 } 8356 return __check_ptr_off_reg(env, reg, regno, false); 8357 } 8358 8359 switch (type) { 8360 /* Pointer types where both fixed and variable offset is explicitly allowed: */ 8361 case PTR_TO_STACK: 8362 case PTR_TO_PACKET: 8363 case PTR_TO_PACKET_META: 8364 case PTR_TO_MAP_KEY: 8365 case PTR_TO_MAP_VALUE: 8366 case PTR_TO_MEM: 8367 case PTR_TO_MEM | MEM_RDONLY: 8368 case PTR_TO_MEM | MEM_RINGBUF: 8369 case PTR_TO_BUF: 8370 case PTR_TO_BUF | MEM_RDONLY: 8371 case SCALAR_VALUE: 8372 return 0; 8373 /* All the rest must be rejected, except PTR_TO_BTF_ID which allows 8374 * fixed offset. 8375 */ 8376 case PTR_TO_BTF_ID: 8377 case PTR_TO_BTF_ID | MEM_ALLOC: 8378 case PTR_TO_BTF_ID | PTR_TRUSTED: 8379 case PTR_TO_BTF_ID | MEM_RCU: 8380 case PTR_TO_BTF_ID | MEM_ALLOC | NON_OWN_REF: 8381 case PTR_TO_BTF_ID | MEM_ALLOC | NON_OWN_REF | MEM_RCU: 8382 /* When referenced PTR_TO_BTF_ID is passed to release function, 8383 * its fixed offset must be 0. In the other cases, fixed offset 8384 * can be non-zero. This was already checked above. So pass 8385 * fixed_off_ok as true to allow fixed offset for all other 8386 * cases. var_off always must be 0 for PTR_TO_BTF_ID, hence we 8387 * still need to do checks instead of returning. 8388 */ 8389 return __check_ptr_off_reg(env, reg, regno, true); 8390 default: 8391 return __check_ptr_off_reg(env, reg, regno, false); 8392 } 8393 } 8394 8395 static struct bpf_reg_state *get_dynptr_arg_reg(struct bpf_verifier_env *env, 8396 const struct bpf_func_proto *fn, 8397 struct bpf_reg_state *regs) 8398 { 8399 struct bpf_reg_state *state = NULL; 8400 int i; 8401 8402 for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++) 8403 if (arg_type_is_dynptr(fn->arg_type[i])) { 8404 if (state) { 8405 verbose(env, "verifier internal error: multiple dynptr args\n"); 8406 return NULL; 8407 } 8408 state = ®s[BPF_REG_1 + i]; 8409 } 8410 8411 if (!state) 8412 verbose(env, "verifier internal error: no dynptr arg found\n"); 8413 8414 return state; 8415 } 8416 8417 static int dynptr_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 8418 { 8419 struct bpf_func_state *state = func(env, reg); 8420 int spi; 8421 8422 if (reg->type == CONST_PTR_TO_DYNPTR) 8423 return reg->id; 8424 spi = dynptr_get_spi(env, reg); 8425 if (spi < 0) 8426 return spi; 8427 return state->stack[spi].spilled_ptr.id; 8428 } 8429 8430 static int dynptr_ref_obj_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 8431 { 8432 struct bpf_func_state *state = func(env, reg); 8433 int spi; 8434 8435 if (reg->type == CONST_PTR_TO_DYNPTR) 8436 return reg->ref_obj_id; 8437 spi = dynptr_get_spi(env, reg); 8438 if (spi < 0) 8439 return spi; 8440 return state->stack[spi].spilled_ptr.ref_obj_id; 8441 } 8442 8443 static enum bpf_dynptr_type dynptr_get_type(struct bpf_verifier_env *env, 8444 struct bpf_reg_state *reg) 8445 { 8446 struct bpf_func_state *state = func(env, reg); 8447 int spi; 8448 8449 if (reg->type == CONST_PTR_TO_DYNPTR) 8450 return reg->dynptr.type; 8451 8452 spi = __get_spi(reg->off); 8453 if (spi < 0) { 8454 verbose(env, "verifier internal error: invalid spi when querying dynptr type\n"); 8455 return BPF_DYNPTR_TYPE_INVALID; 8456 } 8457 8458 return state->stack[spi].spilled_ptr.dynptr.type; 8459 } 8460 8461 static int check_func_arg(struct bpf_verifier_env *env, u32 arg, 8462 struct bpf_call_arg_meta *meta, 8463 const struct bpf_func_proto *fn, 8464 int insn_idx) 8465 { 8466 u32 regno = BPF_REG_1 + arg; 8467 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno]; 8468 enum bpf_arg_type arg_type = fn->arg_type[arg]; 8469 enum bpf_reg_type type = reg->type; 8470 u32 *arg_btf_id = NULL; 8471 int err = 0; 8472 8473 if (arg_type == ARG_DONTCARE) 8474 return 0; 8475 8476 err = check_reg_arg(env, regno, SRC_OP); 8477 if (err) 8478 return err; 8479 8480 if (arg_type == ARG_ANYTHING) { 8481 if (is_pointer_value(env, regno)) { 8482 verbose(env, "R%d leaks addr into helper function\n", 8483 regno); 8484 return -EACCES; 8485 } 8486 return 0; 8487 } 8488 8489 if (type_is_pkt_pointer(type) && 8490 !may_access_direct_pkt_data(env, meta, BPF_READ)) { 8491 verbose(env, "helper access to the packet is not allowed\n"); 8492 return -EACCES; 8493 } 8494 8495 if (base_type(arg_type) == ARG_PTR_TO_MAP_VALUE) { 8496 err = resolve_map_arg_type(env, meta, &arg_type); 8497 if (err) 8498 return err; 8499 } 8500 8501 if (register_is_null(reg) && type_may_be_null(arg_type)) 8502 /* A NULL register has a SCALAR_VALUE type, so skip 8503 * type checking. 8504 */ 8505 goto skip_type_check; 8506 8507 /* arg_btf_id and arg_size are in a union. */ 8508 if (base_type(arg_type) == ARG_PTR_TO_BTF_ID || 8509 base_type(arg_type) == ARG_PTR_TO_SPIN_LOCK) 8510 arg_btf_id = fn->arg_btf_id[arg]; 8511 8512 err = check_reg_type(env, regno, arg_type, arg_btf_id, meta); 8513 if (err) 8514 return err; 8515 8516 err = check_func_arg_reg_off(env, reg, regno, arg_type); 8517 if (err) 8518 return err; 8519 8520 skip_type_check: 8521 if (arg_type_is_release(arg_type)) { 8522 if (arg_type_is_dynptr(arg_type)) { 8523 struct bpf_func_state *state = func(env, reg); 8524 int spi; 8525 8526 /* Only dynptr created on stack can be released, thus 8527 * the get_spi and stack state checks for spilled_ptr 8528 * should only be done before process_dynptr_func for 8529 * PTR_TO_STACK. 8530 */ 8531 if (reg->type == PTR_TO_STACK) { 8532 spi = dynptr_get_spi(env, reg); 8533 if (spi < 0 || !state->stack[spi].spilled_ptr.ref_obj_id) { 8534 verbose(env, "arg %d is an unacquired reference\n", regno); 8535 return -EINVAL; 8536 } 8537 } else { 8538 verbose(env, "cannot release unowned const bpf_dynptr\n"); 8539 return -EINVAL; 8540 } 8541 } else if (!reg->ref_obj_id && !register_is_null(reg)) { 8542 verbose(env, "R%d must be referenced when passed to release function\n", 8543 regno); 8544 return -EINVAL; 8545 } 8546 if (meta->release_regno) { 8547 verbose(env, "verifier internal error: more than one release argument\n"); 8548 return -EFAULT; 8549 } 8550 meta->release_regno = regno; 8551 } 8552 8553 if (reg->ref_obj_id) { 8554 if (meta->ref_obj_id) { 8555 verbose(env, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n", 8556 regno, reg->ref_obj_id, 8557 meta->ref_obj_id); 8558 return -EFAULT; 8559 } 8560 meta->ref_obj_id = reg->ref_obj_id; 8561 } 8562 8563 switch (base_type(arg_type)) { 8564 case ARG_CONST_MAP_PTR: 8565 /* bpf_map_xxx(map_ptr) call: remember that map_ptr */ 8566 if (meta->map_ptr) { 8567 /* Use map_uid (which is unique id of inner map) to reject: 8568 * inner_map1 = bpf_map_lookup_elem(outer_map, key1) 8569 * inner_map2 = bpf_map_lookup_elem(outer_map, key2) 8570 * if (inner_map1 && inner_map2) { 8571 * timer = bpf_map_lookup_elem(inner_map1); 8572 * if (timer) 8573 * // mismatch would have been allowed 8574 * bpf_timer_init(timer, inner_map2); 8575 * } 8576 * 8577 * Comparing map_ptr is enough to distinguish normal and outer maps. 8578 */ 8579 if (meta->map_ptr != reg->map_ptr || 8580 meta->map_uid != reg->map_uid) { 8581 verbose(env, 8582 "timer pointer in R1 map_uid=%d doesn't match map pointer in R2 map_uid=%d\n", 8583 meta->map_uid, reg->map_uid); 8584 return -EINVAL; 8585 } 8586 } 8587 meta->map_ptr = reg->map_ptr; 8588 meta->map_uid = reg->map_uid; 8589 break; 8590 case ARG_PTR_TO_MAP_KEY: 8591 /* bpf_map_xxx(..., map_ptr, ..., key) call: 8592 * check that [key, key + map->key_size) are within 8593 * stack limits and initialized 8594 */ 8595 if (!meta->map_ptr) { 8596 /* in function declaration map_ptr must come before 8597 * map_key, so that it's verified and known before 8598 * we have to check map_key here. Otherwise it means 8599 * that kernel subsystem misconfigured verifier 8600 */ 8601 verbose(env, "invalid map_ptr to access map->key\n"); 8602 return -EACCES; 8603 } 8604 err = check_helper_mem_access(env, regno, meta->map_ptr->key_size, 8605 BPF_READ, false, NULL); 8606 break; 8607 case ARG_PTR_TO_MAP_VALUE: 8608 if (type_may_be_null(arg_type) && register_is_null(reg)) 8609 return 0; 8610 8611 /* bpf_map_xxx(..., map_ptr, ..., value) call: 8612 * check [value, value + map->value_size) validity 8613 */ 8614 if (!meta->map_ptr) { 8615 /* kernel subsystem misconfigured verifier */ 8616 verbose(env, "invalid map_ptr to access map->value\n"); 8617 return -EACCES; 8618 } 8619 meta->raw_mode = arg_type & MEM_UNINIT; 8620 err = check_helper_mem_access(env, regno, meta->map_ptr->value_size, 8621 arg_type & MEM_WRITE ? BPF_WRITE : BPF_READ, 8622 false, meta); 8623 break; 8624 case ARG_PTR_TO_PERCPU_BTF_ID: 8625 if (!reg->btf_id) { 8626 verbose(env, "Helper has invalid btf_id in R%d\n", regno); 8627 return -EACCES; 8628 } 8629 meta->ret_btf = reg->btf; 8630 meta->ret_btf_id = reg->btf_id; 8631 break; 8632 case ARG_PTR_TO_SPIN_LOCK: 8633 if (in_rbtree_lock_required_cb(env)) { 8634 verbose(env, "can't spin_{lock,unlock} in rbtree cb\n"); 8635 return -EACCES; 8636 } 8637 if (meta->func_id == BPF_FUNC_spin_lock) { 8638 err = process_spin_lock(env, regno, true); 8639 if (err) 8640 return err; 8641 } else if (meta->func_id == BPF_FUNC_spin_unlock) { 8642 err = process_spin_lock(env, regno, false); 8643 if (err) 8644 return err; 8645 } else { 8646 verbose(env, "verifier internal error\n"); 8647 return -EFAULT; 8648 } 8649 break; 8650 case ARG_PTR_TO_TIMER: 8651 err = process_timer_func(env, regno, meta); 8652 if (err) 8653 return err; 8654 break; 8655 case ARG_PTR_TO_FUNC: 8656 meta->subprogno = reg->subprogno; 8657 break; 8658 case ARG_PTR_TO_MEM: 8659 /* The access to this pointer is only checked when we hit the 8660 * next is_mem_size argument below. 8661 */ 8662 meta->raw_mode = arg_type & MEM_UNINIT; 8663 if (arg_type & MEM_FIXED_SIZE) { 8664 err = check_helper_mem_access(env, regno, fn->arg_size[arg], 8665 arg_type & MEM_WRITE ? BPF_WRITE : BPF_READ, 8666 false, meta); 8667 if (err) 8668 return err; 8669 if (arg_type & MEM_ALIGNED) 8670 err = check_ptr_alignment(env, reg, 0, fn->arg_size[arg], true); 8671 } 8672 break; 8673 case ARG_CONST_SIZE: 8674 err = check_mem_size_reg(env, reg, regno, 8675 fn->arg_type[arg - 1] & MEM_WRITE ? 8676 BPF_WRITE : BPF_READ, 8677 false, meta); 8678 break; 8679 case ARG_CONST_SIZE_OR_ZERO: 8680 err = check_mem_size_reg(env, reg, regno, 8681 fn->arg_type[arg - 1] & MEM_WRITE ? 8682 BPF_WRITE : BPF_READ, 8683 true, meta); 8684 break; 8685 case ARG_PTR_TO_DYNPTR: 8686 err = process_dynptr_func(env, regno, insn_idx, arg_type, 0); 8687 if (err) 8688 return err; 8689 break; 8690 case ARG_CONST_ALLOC_SIZE_OR_ZERO: 8691 if (!tnum_is_const(reg->var_off)) { 8692 verbose(env, "R%d is not a known constant'\n", 8693 regno); 8694 return -EACCES; 8695 } 8696 meta->mem_size = reg->var_off.value; 8697 err = mark_chain_precision(env, regno); 8698 if (err) 8699 return err; 8700 break; 8701 case ARG_PTR_TO_CONST_STR: 8702 { 8703 struct bpf_map *map = reg->map_ptr; 8704 int map_off; 8705 u64 map_addr; 8706 char *str_ptr; 8707 8708 if (!bpf_map_is_rdonly(map)) { 8709 verbose(env, "R%d does not point to a readonly map'\n", regno); 8710 return -EACCES; 8711 } 8712 8713 if (!tnum_is_const(reg->var_off)) { 8714 verbose(env, "R%d is not a constant address'\n", regno); 8715 return -EACCES; 8716 } 8717 8718 if (!map->ops->map_direct_value_addr) { 8719 verbose(env, "no direct value access support for this map type\n"); 8720 return -EACCES; 8721 } 8722 8723 err = check_map_access(env, regno, reg->off, 8724 map->value_size - reg->off, false, 8725 ACCESS_HELPER); 8726 if (err) 8727 return err; 8728 8729 map_off = reg->off + reg->var_off.value; 8730 err = map->ops->map_direct_value_addr(map, &map_addr, map_off); 8731 if (err) { 8732 verbose(env, "direct value access on string failed\n"); 8733 return err; 8734 } 8735 8736 str_ptr = (char *)(long)(map_addr); 8737 if (!strnchr(str_ptr + map_off, map->value_size - map_off, 0)) { 8738 verbose(env, "string is not zero-terminated\n"); 8739 return -EINVAL; 8740 } 8741 break; 8742 } 8743 case ARG_PTR_TO_KPTR: 8744 err = process_kptr_func(env, regno, meta); 8745 if (err) 8746 return err; 8747 break; 8748 } 8749 8750 return err; 8751 } 8752 8753 static bool may_update_sockmap(struct bpf_verifier_env *env, int func_id) 8754 { 8755 enum bpf_attach_type eatype = env->prog->expected_attach_type; 8756 enum bpf_prog_type type = resolve_prog_type(env->prog); 8757 8758 if (func_id != BPF_FUNC_map_update_elem && 8759 func_id != BPF_FUNC_map_delete_elem) 8760 return false; 8761 8762 /* It's not possible to get access to a locked struct sock in these 8763 * contexts, so updating is safe. 8764 */ 8765 switch (type) { 8766 case BPF_PROG_TYPE_TRACING: 8767 if (eatype == BPF_TRACE_ITER) 8768 return true; 8769 break; 8770 case BPF_PROG_TYPE_SOCK_OPS: 8771 /* map_update allowed only via dedicated helpers with event type checks */ 8772 if (func_id == BPF_FUNC_map_delete_elem) 8773 return true; 8774 break; 8775 case BPF_PROG_TYPE_SOCKET_FILTER: 8776 case BPF_PROG_TYPE_SCHED_CLS: 8777 case BPF_PROG_TYPE_SCHED_ACT: 8778 case BPF_PROG_TYPE_XDP: 8779 case BPF_PROG_TYPE_SK_REUSEPORT: 8780 case BPF_PROG_TYPE_FLOW_DISSECTOR: 8781 case BPF_PROG_TYPE_SK_LOOKUP: 8782 return true; 8783 default: 8784 break; 8785 } 8786 8787 verbose(env, "cannot update sockmap in this context\n"); 8788 return false; 8789 } 8790 8791 static bool allow_tail_call_in_subprogs(struct bpf_verifier_env *env) 8792 { 8793 return env->prog->jit_requested && 8794 bpf_jit_supports_subprog_tailcalls(); 8795 } 8796 8797 static int check_map_func_compatibility(struct bpf_verifier_env *env, 8798 struct bpf_map *map, int func_id) 8799 { 8800 if (!map) 8801 return 0; 8802 8803 /* We need a two way check, first is from map perspective ... */ 8804 switch (map->map_type) { 8805 case BPF_MAP_TYPE_PROG_ARRAY: 8806 if (func_id != BPF_FUNC_tail_call) 8807 goto error; 8808 break; 8809 case BPF_MAP_TYPE_PERF_EVENT_ARRAY: 8810 if (func_id != BPF_FUNC_perf_event_read && 8811 func_id != BPF_FUNC_perf_event_output && 8812 func_id != BPF_FUNC_skb_output && 8813 func_id != BPF_FUNC_perf_event_read_value && 8814 func_id != BPF_FUNC_xdp_output) 8815 goto error; 8816 break; 8817 case BPF_MAP_TYPE_RINGBUF: 8818 if (func_id != BPF_FUNC_ringbuf_output && 8819 func_id != BPF_FUNC_ringbuf_reserve && 8820 func_id != BPF_FUNC_ringbuf_query && 8821 func_id != BPF_FUNC_ringbuf_reserve_dynptr && 8822 func_id != BPF_FUNC_ringbuf_submit_dynptr && 8823 func_id != BPF_FUNC_ringbuf_discard_dynptr) 8824 goto error; 8825 break; 8826 case BPF_MAP_TYPE_USER_RINGBUF: 8827 if (func_id != BPF_FUNC_user_ringbuf_drain) 8828 goto error; 8829 break; 8830 case BPF_MAP_TYPE_STACK_TRACE: 8831 if (func_id != BPF_FUNC_get_stackid) 8832 goto error; 8833 break; 8834 case BPF_MAP_TYPE_CGROUP_ARRAY: 8835 if (func_id != BPF_FUNC_skb_under_cgroup && 8836 func_id != BPF_FUNC_current_task_under_cgroup) 8837 goto error; 8838 break; 8839 case BPF_MAP_TYPE_CGROUP_STORAGE: 8840 case BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE: 8841 if (func_id != BPF_FUNC_get_local_storage) 8842 goto error; 8843 break; 8844 case BPF_MAP_TYPE_DEVMAP: 8845 case BPF_MAP_TYPE_DEVMAP_HASH: 8846 if (func_id != BPF_FUNC_redirect_map && 8847 func_id != BPF_FUNC_map_lookup_elem) 8848 goto error; 8849 break; 8850 /* Restrict bpf side of cpumap and xskmap, open when use-cases 8851 * appear. 8852 */ 8853 case BPF_MAP_TYPE_CPUMAP: 8854 if (func_id != BPF_FUNC_redirect_map) 8855 goto error; 8856 break; 8857 case BPF_MAP_TYPE_XSKMAP: 8858 if (func_id != BPF_FUNC_redirect_map && 8859 func_id != BPF_FUNC_map_lookup_elem) 8860 goto error; 8861 break; 8862 case BPF_MAP_TYPE_ARRAY_OF_MAPS: 8863 case BPF_MAP_TYPE_HASH_OF_MAPS: 8864 if (func_id != BPF_FUNC_map_lookup_elem) 8865 goto error; 8866 break; 8867 case BPF_MAP_TYPE_SOCKMAP: 8868 if (func_id != BPF_FUNC_sk_redirect_map && 8869 func_id != BPF_FUNC_sock_map_update && 8870 func_id != BPF_FUNC_msg_redirect_map && 8871 func_id != BPF_FUNC_sk_select_reuseport && 8872 func_id != BPF_FUNC_map_lookup_elem && 8873 !may_update_sockmap(env, func_id)) 8874 goto error; 8875 break; 8876 case BPF_MAP_TYPE_SOCKHASH: 8877 if (func_id != BPF_FUNC_sk_redirect_hash && 8878 func_id != BPF_FUNC_sock_hash_update && 8879 func_id != BPF_FUNC_msg_redirect_hash && 8880 func_id != BPF_FUNC_sk_select_reuseport && 8881 func_id != BPF_FUNC_map_lookup_elem && 8882 !may_update_sockmap(env, func_id)) 8883 goto error; 8884 break; 8885 case BPF_MAP_TYPE_REUSEPORT_SOCKARRAY: 8886 if (func_id != BPF_FUNC_sk_select_reuseport) 8887 goto error; 8888 break; 8889 case BPF_MAP_TYPE_QUEUE: 8890 case BPF_MAP_TYPE_STACK: 8891 if (func_id != BPF_FUNC_map_peek_elem && 8892 func_id != BPF_FUNC_map_pop_elem && 8893 func_id != BPF_FUNC_map_push_elem) 8894 goto error; 8895 break; 8896 case BPF_MAP_TYPE_SK_STORAGE: 8897 if (func_id != BPF_FUNC_sk_storage_get && 8898 func_id != BPF_FUNC_sk_storage_delete && 8899 func_id != BPF_FUNC_kptr_xchg) 8900 goto error; 8901 break; 8902 case BPF_MAP_TYPE_INODE_STORAGE: 8903 if (func_id != BPF_FUNC_inode_storage_get && 8904 func_id != BPF_FUNC_inode_storage_delete && 8905 func_id != BPF_FUNC_kptr_xchg) 8906 goto error; 8907 break; 8908 case BPF_MAP_TYPE_TASK_STORAGE: 8909 if (func_id != BPF_FUNC_task_storage_get && 8910 func_id != BPF_FUNC_task_storage_delete && 8911 func_id != BPF_FUNC_kptr_xchg) 8912 goto error; 8913 break; 8914 case BPF_MAP_TYPE_CGRP_STORAGE: 8915 if (func_id != BPF_FUNC_cgrp_storage_get && 8916 func_id != BPF_FUNC_cgrp_storage_delete && 8917 func_id != BPF_FUNC_kptr_xchg) 8918 goto error; 8919 break; 8920 case BPF_MAP_TYPE_BLOOM_FILTER: 8921 if (func_id != BPF_FUNC_map_peek_elem && 8922 func_id != BPF_FUNC_map_push_elem) 8923 goto error; 8924 break; 8925 default: 8926 break; 8927 } 8928 8929 /* ... and second from the function itself. */ 8930 switch (func_id) { 8931 case BPF_FUNC_tail_call: 8932 if (map->map_type != BPF_MAP_TYPE_PROG_ARRAY) 8933 goto error; 8934 if (env->subprog_cnt > 1 && !allow_tail_call_in_subprogs(env)) { 8935 verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n"); 8936 return -EINVAL; 8937 } 8938 break; 8939 case BPF_FUNC_perf_event_read: 8940 case BPF_FUNC_perf_event_output: 8941 case BPF_FUNC_perf_event_read_value: 8942 case BPF_FUNC_skb_output: 8943 case BPF_FUNC_xdp_output: 8944 if (map->map_type != BPF_MAP_TYPE_PERF_EVENT_ARRAY) 8945 goto error; 8946 break; 8947 case BPF_FUNC_ringbuf_output: 8948 case BPF_FUNC_ringbuf_reserve: 8949 case BPF_FUNC_ringbuf_query: 8950 case BPF_FUNC_ringbuf_reserve_dynptr: 8951 case BPF_FUNC_ringbuf_submit_dynptr: 8952 case BPF_FUNC_ringbuf_discard_dynptr: 8953 if (map->map_type != BPF_MAP_TYPE_RINGBUF) 8954 goto error; 8955 break; 8956 case BPF_FUNC_user_ringbuf_drain: 8957 if (map->map_type != BPF_MAP_TYPE_USER_RINGBUF) 8958 goto error; 8959 break; 8960 case BPF_FUNC_get_stackid: 8961 if (map->map_type != BPF_MAP_TYPE_STACK_TRACE) 8962 goto error; 8963 break; 8964 case BPF_FUNC_current_task_under_cgroup: 8965 case BPF_FUNC_skb_under_cgroup: 8966 if (map->map_type != BPF_MAP_TYPE_CGROUP_ARRAY) 8967 goto error; 8968 break; 8969 case BPF_FUNC_redirect_map: 8970 if (map->map_type != BPF_MAP_TYPE_DEVMAP && 8971 map->map_type != BPF_MAP_TYPE_DEVMAP_HASH && 8972 map->map_type != BPF_MAP_TYPE_CPUMAP && 8973 map->map_type != BPF_MAP_TYPE_XSKMAP) 8974 goto error; 8975 break; 8976 case BPF_FUNC_sk_redirect_map: 8977 case BPF_FUNC_msg_redirect_map: 8978 case BPF_FUNC_sock_map_update: 8979 if (map->map_type != BPF_MAP_TYPE_SOCKMAP) 8980 goto error; 8981 break; 8982 case BPF_FUNC_sk_redirect_hash: 8983 case BPF_FUNC_msg_redirect_hash: 8984 case BPF_FUNC_sock_hash_update: 8985 if (map->map_type != BPF_MAP_TYPE_SOCKHASH) 8986 goto error; 8987 break; 8988 case BPF_FUNC_get_local_storage: 8989 if (map->map_type != BPF_MAP_TYPE_CGROUP_STORAGE && 8990 map->map_type != BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE) 8991 goto error; 8992 break; 8993 case BPF_FUNC_sk_select_reuseport: 8994 if (map->map_type != BPF_MAP_TYPE_REUSEPORT_SOCKARRAY && 8995 map->map_type != BPF_MAP_TYPE_SOCKMAP && 8996 map->map_type != BPF_MAP_TYPE_SOCKHASH) 8997 goto error; 8998 break; 8999 case BPF_FUNC_map_pop_elem: 9000 if (map->map_type != BPF_MAP_TYPE_QUEUE && 9001 map->map_type != BPF_MAP_TYPE_STACK) 9002 goto error; 9003 break; 9004 case BPF_FUNC_map_peek_elem: 9005 case BPF_FUNC_map_push_elem: 9006 if (map->map_type != BPF_MAP_TYPE_QUEUE && 9007 map->map_type != BPF_MAP_TYPE_STACK && 9008 map->map_type != BPF_MAP_TYPE_BLOOM_FILTER) 9009 goto error; 9010 break; 9011 case BPF_FUNC_map_lookup_percpu_elem: 9012 if (map->map_type != BPF_MAP_TYPE_PERCPU_ARRAY && 9013 map->map_type != BPF_MAP_TYPE_PERCPU_HASH && 9014 map->map_type != BPF_MAP_TYPE_LRU_PERCPU_HASH) 9015 goto error; 9016 break; 9017 case BPF_FUNC_sk_storage_get: 9018 case BPF_FUNC_sk_storage_delete: 9019 if (map->map_type != BPF_MAP_TYPE_SK_STORAGE) 9020 goto error; 9021 break; 9022 case BPF_FUNC_inode_storage_get: 9023 case BPF_FUNC_inode_storage_delete: 9024 if (map->map_type != BPF_MAP_TYPE_INODE_STORAGE) 9025 goto error; 9026 break; 9027 case BPF_FUNC_task_storage_get: 9028 case BPF_FUNC_task_storage_delete: 9029 if (map->map_type != BPF_MAP_TYPE_TASK_STORAGE) 9030 goto error; 9031 break; 9032 case BPF_FUNC_cgrp_storage_get: 9033 case BPF_FUNC_cgrp_storage_delete: 9034 if (map->map_type != BPF_MAP_TYPE_CGRP_STORAGE) 9035 goto error; 9036 break; 9037 default: 9038 break; 9039 } 9040 9041 return 0; 9042 error: 9043 verbose(env, "cannot pass map_type %d into func %s#%d\n", 9044 map->map_type, func_id_name(func_id), func_id); 9045 return -EINVAL; 9046 } 9047 9048 static bool check_raw_mode_ok(const struct bpf_func_proto *fn) 9049 { 9050 int count = 0; 9051 9052 if (arg_type_is_raw_mem(fn->arg1_type)) 9053 count++; 9054 if (arg_type_is_raw_mem(fn->arg2_type)) 9055 count++; 9056 if (arg_type_is_raw_mem(fn->arg3_type)) 9057 count++; 9058 if (arg_type_is_raw_mem(fn->arg4_type)) 9059 count++; 9060 if (arg_type_is_raw_mem(fn->arg5_type)) 9061 count++; 9062 9063 /* We only support one arg being in raw mode at the moment, 9064 * which is sufficient for the helper functions we have 9065 * right now. 9066 */ 9067 return count <= 1; 9068 } 9069 9070 static bool check_args_pair_invalid(const struct bpf_func_proto *fn, int arg) 9071 { 9072 bool is_fixed = fn->arg_type[arg] & MEM_FIXED_SIZE; 9073 bool has_size = fn->arg_size[arg] != 0; 9074 bool is_next_size = false; 9075 9076 if (arg + 1 < ARRAY_SIZE(fn->arg_type)) 9077 is_next_size = arg_type_is_mem_size(fn->arg_type[arg + 1]); 9078 9079 if (base_type(fn->arg_type[arg]) != ARG_PTR_TO_MEM) 9080 return is_next_size; 9081 9082 return has_size == is_next_size || is_next_size == is_fixed; 9083 } 9084 9085 static bool check_arg_pair_ok(const struct bpf_func_proto *fn) 9086 { 9087 /* bpf_xxx(..., buf, len) call will access 'len' 9088 * bytes from memory 'buf'. Both arg types need 9089 * to be paired, so make sure there's no buggy 9090 * helper function specification. 9091 */ 9092 if (arg_type_is_mem_size(fn->arg1_type) || 9093 check_args_pair_invalid(fn, 0) || 9094 check_args_pair_invalid(fn, 1) || 9095 check_args_pair_invalid(fn, 2) || 9096 check_args_pair_invalid(fn, 3) || 9097 check_args_pair_invalid(fn, 4)) 9098 return false; 9099 9100 return true; 9101 } 9102 9103 static bool check_btf_id_ok(const struct bpf_func_proto *fn) 9104 { 9105 int i; 9106 9107 for (i = 0; i < ARRAY_SIZE(fn->arg_type); i++) { 9108 if (base_type(fn->arg_type[i]) == ARG_PTR_TO_BTF_ID) 9109 return !!fn->arg_btf_id[i]; 9110 if (base_type(fn->arg_type[i]) == ARG_PTR_TO_SPIN_LOCK) 9111 return fn->arg_btf_id[i] == BPF_PTR_POISON; 9112 if (base_type(fn->arg_type[i]) != ARG_PTR_TO_BTF_ID && fn->arg_btf_id[i] && 9113 /* arg_btf_id and arg_size are in a union. */ 9114 (base_type(fn->arg_type[i]) != ARG_PTR_TO_MEM || 9115 !(fn->arg_type[i] & MEM_FIXED_SIZE))) 9116 return false; 9117 } 9118 9119 return true; 9120 } 9121 9122 static int check_func_proto(const struct bpf_func_proto *fn, int func_id) 9123 { 9124 return check_raw_mode_ok(fn) && 9125 check_arg_pair_ok(fn) && 9126 check_btf_id_ok(fn) ? 0 : -EINVAL; 9127 } 9128 9129 /* Packet data might have moved, any old PTR_TO_PACKET[_META,_END] 9130 * are now invalid, so turn them into unknown SCALAR_VALUE. 9131 * 9132 * This also applies to dynptr slices belonging to skb and xdp dynptrs, 9133 * since these slices point to packet data. 9134 */ 9135 static void clear_all_pkt_pointers(struct bpf_verifier_env *env) 9136 { 9137 struct bpf_func_state *state; 9138 struct bpf_reg_state *reg; 9139 9140 bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({ 9141 if (reg_is_pkt_pointer_any(reg) || reg_is_dynptr_slice_pkt(reg)) 9142 mark_reg_invalid(env, reg); 9143 })); 9144 } 9145 9146 enum { 9147 AT_PKT_END = -1, 9148 BEYOND_PKT_END = -2, 9149 }; 9150 9151 static void mark_pkt_end(struct bpf_verifier_state *vstate, int regn, bool range_open) 9152 { 9153 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 9154 struct bpf_reg_state *reg = &state->regs[regn]; 9155 9156 if (reg->type != PTR_TO_PACKET) 9157 /* PTR_TO_PACKET_META is not supported yet */ 9158 return; 9159 9160 /* The 'reg' is pkt > pkt_end or pkt >= pkt_end. 9161 * How far beyond pkt_end it goes is unknown. 9162 * if (!range_open) it's the case of pkt >= pkt_end 9163 * if (range_open) it's the case of pkt > pkt_end 9164 * hence this pointer is at least 1 byte bigger than pkt_end 9165 */ 9166 if (range_open) 9167 reg->range = BEYOND_PKT_END; 9168 else 9169 reg->range = AT_PKT_END; 9170 } 9171 9172 /* The pointer with the specified id has released its reference to kernel 9173 * resources. Identify all copies of the same pointer and clear the reference. 9174 */ 9175 static int release_reference(struct bpf_verifier_env *env, 9176 int ref_obj_id) 9177 { 9178 struct bpf_func_state *state; 9179 struct bpf_reg_state *reg; 9180 int err; 9181 9182 err = release_reference_state(cur_func(env), ref_obj_id); 9183 if (err) 9184 return err; 9185 9186 bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({ 9187 if (reg->ref_obj_id == ref_obj_id) 9188 mark_reg_invalid(env, reg); 9189 })); 9190 9191 return 0; 9192 } 9193 9194 static void invalidate_non_owning_refs(struct bpf_verifier_env *env) 9195 { 9196 struct bpf_func_state *unused; 9197 struct bpf_reg_state *reg; 9198 9199 bpf_for_each_reg_in_vstate(env->cur_state, unused, reg, ({ 9200 if (type_is_non_owning_ref(reg->type)) 9201 mark_reg_invalid(env, reg); 9202 })); 9203 } 9204 9205 static void clear_caller_saved_regs(struct bpf_verifier_env *env, 9206 struct bpf_reg_state *regs) 9207 { 9208 int i; 9209 9210 /* after the call registers r0 - r5 were scratched */ 9211 for (i = 0; i < CALLER_SAVED_REGS; i++) { 9212 mark_reg_not_init(env, regs, caller_saved[i]); 9213 __check_reg_arg(env, regs, caller_saved[i], DST_OP_NO_MARK); 9214 } 9215 } 9216 9217 typedef int (*set_callee_state_fn)(struct bpf_verifier_env *env, 9218 struct bpf_func_state *caller, 9219 struct bpf_func_state *callee, 9220 int insn_idx); 9221 9222 static int set_callee_state(struct bpf_verifier_env *env, 9223 struct bpf_func_state *caller, 9224 struct bpf_func_state *callee, int insn_idx); 9225 9226 static int setup_func_entry(struct bpf_verifier_env *env, int subprog, int callsite, 9227 set_callee_state_fn set_callee_state_cb, 9228 struct bpf_verifier_state *state) 9229 { 9230 struct bpf_func_state *caller, *callee; 9231 int err; 9232 9233 if (state->curframe + 1 >= MAX_CALL_FRAMES) { 9234 verbose(env, "the call stack of %d frames is too deep\n", 9235 state->curframe + 2); 9236 return -E2BIG; 9237 } 9238 9239 if (state->frame[state->curframe + 1]) { 9240 verbose(env, "verifier bug. Frame %d already allocated\n", 9241 state->curframe + 1); 9242 return -EFAULT; 9243 } 9244 9245 caller = state->frame[state->curframe]; 9246 callee = kzalloc(sizeof(*callee), GFP_KERNEL); 9247 if (!callee) 9248 return -ENOMEM; 9249 state->frame[state->curframe + 1] = callee; 9250 9251 /* callee cannot access r0, r6 - r9 for reading and has to write 9252 * into its own stack before reading from it. 9253 * callee can read/write into caller's stack 9254 */ 9255 init_func_state(env, callee, 9256 /* remember the callsite, it will be used by bpf_exit */ 9257 callsite, 9258 state->curframe + 1 /* frameno within this callchain */, 9259 subprog /* subprog number within this prog */); 9260 /* Transfer references to the callee */ 9261 err = copy_reference_state(callee, caller); 9262 err = err ?: set_callee_state_cb(env, caller, callee, callsite); 9263 if (err) 9264 goto err_out; 9265 9266 /* only increment it after check_reg_arg() finished */ 9267 state->curframe++; 9268 9269 return 0; 9270 9271 err_out: 9272 free_func_state(callee); 9273 state->frame[state->curframe + 1] = NULL; 9274 return err; 9275 } 9276 9277 static int push_callback_call(struct bpf_verifier_env *env, struct bpf_insn *insn, 9278 int insn_idx, int subprog, 9279 set_callee_state_fn set_callee_state_cb) 9280 { 9281 struct bpf_verifier_state *state = env->cur_state, *callback_state; 9282 struct bpf_func_state *caller, *callee; 9283 int err; 9284 9285 caller = state->frame[state->curframe]; 9286 err = btf_check_subprog_call(env, subprog, caller->regs); 9287 if (err == -EFAULT) 9288 return err; 9289 9290 /* set_callee_state is used for direct subprog calls, but we are 9291 * interested in validating only BPF helpers that can call subprogs as 9292 * callbacks 9293 */ 9294 if (bpf_pseudo_kfunc_call(insn) && 9295 !is_sync_callback_calling_kfunc(insn->imm)) { 9296 verbose(env, "verifier bug: kfunc %s#%d not marked as callback-calling\n", 9297 func_id_name(insn->imm), insn->imm); 9298 return -EFAULT; 9299 } else if (!bpf_pseudo_kfunc_call(insn) && 9300 !is_callback_calling_function(insn->imm)) { /* helper */ 9301 verbose(env, "verifier bug: helper %s#%d not marked as callback-calling\n", 9302 func_id_name(insn->imm), insn->imm); 9303 return -EFAULT; 9304 } 9305 9306 if (insn->code == (BPF_JMP | BPF_CALL) && 9307 insn->src_reg == 0 && 9308 insn->imm == BPF_FUNC_timer_set_callback) { 9309 struct bpf_verifier_state *async_cb; 9310 9311 /* there is no real recursion here. timer callbacks are async */ 9312 env->subprog_info[subprog].is_async_cb = true; 9313 async_cb = push_async_cb(env, env->subprog_info[subprog].start, 9314 insn_idx, subprog); 9315 if (!async_cb) 9316 return -EFAULT; 9317 callee = async_cb->frame[0]; 9318 callee->async_entry_cnt = caller->async_entry_cnt + 1; 9319 9320 /* Convert bpf_timer_set_callback() args into timer callback args */ 9321 err = set_callee_state_cb(env, caller, callee, insn_idx); 9322 if (err) 9323 return err; 9324 9325 return 0; 9326 } 9327 9328 /* for callback functions enqueue entry to callback and 9329 * proceed with next instruction within current frame. 9330 */ 9331 callback_state = push_stack(env, env->subprog_info[subprog].start, insn_idx, false); 9332 if (!callback_state) 9333 return -ENOMEM; 9334 9335 err = setup_func_entry(env, subprog, insn_idx, set_callee_state_cb, 9336 callback_state); 9337 if (err) 9338 return err; 9339 9340 callback_state->callback_unroll_depth++; 9341 callback_state->frame[callback_state->curframe - 1]->callback_depth++; 9342 caller->callback_depth = 0; 9343 return 0; 9344 } 9345 9346 static int check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn, 9347 int *insn_idx) 9348 { 9349 struct bpf_verifier_state *state = env->cur_state; 9350 struct bpf_func_state *caller; 9351 int err, subprog, target_insn; 9352 9353 target_insn = *insn_idx + insn->imm + 1; 9354 subprog = find_subprog(env, target_insn); 9355 if (subprog < 0) { 9356 verbose(env, "verifier bug. No program starts at insn %d\n", target_insn); 9357 return -EFAULT; 9358 } 9359 9360 caller = state->frame[state->curframe]; 9361 err = btf_check_subprog_call(env, subprog, caller->regs); 9362 if (err == -EFAULT) 9363 return err; 9364 if (subprog_is_global(env, subprog)) { 9365 if (err) { 9366 verbose(env, "Caller passes invalid args into func#%d\n", subprog); 9367 return err; 9368 } 9369 9370 if (env->log.level & BPF_LOG_LEVEL) 9371 verbose(env, "Func#%d is global and valid. Skipping.\n", subprog); 9372 clear_caller_saved_regs(env, caller->regs); 9373 9374 /* All global functions return a 64-bit SCALAR_VALUE */ 9375 mark_reg_unknown(env, caller->regs, BPF_REG_0); 9376 caller->regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG; 9377 9378 /* continue with next insn after call */ 9379 return 0; 9380 } 9381 9382 /* for regular function entry setup new frame and continue 9383 * from that frame. 9384 */ 9385 err = setup_func_entry(env, subprog, *insn_idx, set_callee_state, state); 9386 if (err) 9387 return err; 9388 9389 clear_caller_saved_regs(env, caller->regs); 9390 9391 /* and go analyze first insn of the callee */ 9392 *insn_idx = env->subprog_info[subprog].start - 1; 9393 9394 if (env->log.level & BPF_LOG_LEVEL) { 9395 verbose(env, "caller:\n"); 9396 print_verifier_state(env, caller, true); 9397 verbose(env, "callee:\n"); 9398 print_verifier_state(env, state->frame[state->curframe], true); 9399 } 9400 9401 return 0; 9402 } 9403 9404 int map_set_for_each_callback_args(struct bpf_verifier_env *env, 9405 struct bpf_func_state *caller, 9406 struct bpf_func_state *callee) 9407 { 9408 /* bpf_for_each_map_elem(struct bpf_map *map, void *callback_fn, 9409 * void *callback_ctx, u64 flags); 9410 * callback_fn(struct bpf_map *map, void *key, void *value, 9411 * void *callback_ctx); 9412 */ 9413 callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1]; 9414 9415 callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY; 9416 __mark_reg_known_zero(&callee->regs[BPF_REG_2]); 9417 callee->regs[BPF_REG_2].map_ptr = caller->regs[BPF_REG_1].map_ptr; 9418 9419 callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE; 9420 __mark_reg_known_zero(&callee->regs[BPF_REG_3]); 9421 callee->regs[BPF_REG_3].map_ptr = caller->regs[BPF_REG_1].map_ptr; 9422 9423 /* pointer to stack or null */ 9424 callee->regs[BPF_REG_4] = caller->regs[BPF_REG_3]; 9425 9426 /* unused */ 9427 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]); 9428 return 0; 9429 } 9430 9431 static int set_callee_state(struct bpf_verifier_env *env, 9432 struct bpf_func_state *caller, 9433 struct bpf_func_state *callee, int insn_idx) 9434 { 9435 int i; 9436 9437 /* copy r1 - r5 args that callee can access. The copy includes parent 9438 * pointers, which connects us up to the liveness chain 9439 */ 9440 for (i = BPF_REG_1; i <= BPF_REG_5; i++) 9441 callee->regs[i] = caller->regs[i]; 9442 return 0; 9443 } 9444 9445 static int set_map_elem_callback_state(struct bpf_verifier_env *env, 9446 struct bpf_func_state *caller, 9447 struct bpf_func_state *callee, 9448 int insn_idx) 9449 { 9450 struct bpf_insn_aux_data *insn_aux = &env->insn_aux_data[insn_idx]; 9451 struct bpf_map *map; 9452 int err; 9453 9454 if (bpf_map_ptr_poisoned(insn_aux)) { 9455 verbose(env, "tail_call abusing map_ptr\n"); 9456 return -EINVAL; 9457 } 9458 9459 map = BPF_MAP_PTR(insn_aux->map_ptr_state); 9460 if (!map->ops->map_set_for_each_callback_args || 9461 !map->ops->map_for_each_callback) { 9462 verbose(env, "callback function not allowed for map\n"); 9463 return -ENOTSUPP; 9464 } 9465 9466 err = map->ops->map_set_for_each_callback_args(env, caller, callee); 9467 if (err) 9468 return err; 9469 9470 callee->in_callback_fn = true; 9471 callee->callback_ret_range = tnum_range(0, 1); 9472 return 0; 9473 } 9474 9475 static int set_loop_callback_state(struct bpf_verifier_env *env, 9476 struct bpf_func_state *caller, 9477 struct bpf_func_state *callee, 9478 int insn_idx) 9479 { 9480 /* bpf_loop(u32 nr_loops, void *callback_fn, void *callback_ctx, 9481 * u64 flags); 9482 * callback_fn(u32 index, void *callback_ctx); 9483 */ 9484 callee->regs[BPF_REG_1].type = SCALAR_VALUE; 9485 callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3]; 9486 9487 /* unused */ 9488 __mark_reg_not_init(env, &callee->regs[BPF_REG_3]); 9489 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]); 9490 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]); 9491 9492 callee->in_callback_fn = true; 9493 callee->callback_ret_range = tnum_range(0, 1); 9494 return 0; 9495 } 9496 9497 static int set_timer_callback_state(struct bpf_verifier_env *env, 9498 struct bpf_func_state *caller, 9499 struct bpf_func_state *callee, 9500 int insn_idx) 9501 { 9502 struct bpf_map *map_ptr = caller->regs[BPF_REG_1].map_ptr; 9503 9504 /* bpf_timer_set_callback(struct bpf_timer *timer, void *callback_fn); 9505 * callback_fn(struct bpf_map *map, void *key, void *value); 9506 */ 9507 callee->regs[BPF_REG_1].type = CONST_PTR_TO_MAP; 9508 __mark_reg_known_zero(&callee->regs[BPF_REG_1]); 9509 callee->regs[BPF_REG_1].map_ptr = map_ptr; 9510 9511 callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY; 9512 __mark_reg_known_zero(&callee->regs[BPF_REG_2]); 9513 callee->regs[BPF_REG_2].map_ptr = map_ptr; 9514 9515 callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE; 9516 __mark_reg_known_zero(&callee->regs[BPF_REG_3]); 9517 callee->regs[BPF_REG_3].map_ptr = map_ptr; 9518 9519 /* unused */ 9520 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]); 9521 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]); 9522 callee->in_async_callback_fn = true; 9523 callee->callback_ret_range = tnum_range(0, 1); 9524 return 0; 9525 } 9526 9527 static int set_find_vma_callback_state(struct bpf_verifier_env *env, 9528 struct bpf_func_state *caller, 9529 struct bpf_func_state *callee, 9530 int insn_idx) 9531 { 9532 /* bpf_find_vma(struct task_struct *task, u64 addr, 9533 * void *callback_fn, void *callback_ctx, u64 flags) 9534 * (callback_fn)(struct task_struct *task, 9535 * struct vm_area_struct *vma, void *callback_ctx); 9536 */ 9537 callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1]; 9538 9539 callee->regs[BPF_REG_2].type = PTR_TO_BTF_ID; 9540 __mark_reg_known_zero(&callee->regs[BPF_REG_2]); 9541 callee->regs[BPF_REG_2].btf = btf_vmlinux; 9542 callee->regs[BPF_REG_2].btf_id = btf_tracing_ids[BTF_TRACING_TYPE_VMA], 9543 9544 /* pointer to stack or null */ 9545 callee->regs[BPF_REG_3] = caller->regs[BPF_REG_4]; 9546 9547 /* unused */ 9548 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]); 9549 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]); 9550 callee->in_callback_fn = true; 9551 callee->callback_ret_range = tnum_range(0, 1); 9552 return 0; 9553 } 9554 9555 static int set_user_ringbuf_callback_state(struct bpf_verifier_env *env, 9556 struct bpf_func_state *caller, 9557 struct bpf_func_state *callee, 9558 int insn_idx) 9559 { 9560 /* bpf_user_ringbuf_drain(struct bpf_map *map, void *callback_fn, void 9561 * callback_ctx, u64 flags); 9562 * callback_fn(const struct bpf_dynptr_t* dynptr, void *callback_ctx); 9563 */ 9564 __mark_reg_not_init(env, &callee->regs[BPF_REG_0]); 9565 mark_dynptr_cb_reg(env, &callee->regs[BPF_REG_1], BPF_DYNPTR_TYPE_LOCAL); 9566 callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3]; 9567 9568 /* unused */ 9569 __mark_reg_not_init(env, &callee->regs[BPF_REG_3]); 9570 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]); 9571 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]); 9572 9573 callee->in_callback_fn = true; 9574 callee->callback_ret_range = tnum_range(0, 1); 9575 return 0; 9576 } 9577 9578 static int set_rbtree_add_callback_state(struct bpf_verifier_env *env, 9579 struct bpf_func_state *caller, 9580 struct bpf_func_state *callee, 9581 int insn_idx) 9582 { 9583 /* void bpf_rbtree_add_impl(struct bpf_rb_root *root, struct bpf_rb_node *node, 9584 * bool (less)(struct bpf_rb_node *a, const struct bpf_rb_node *b)); 9585 * 9586 * 'struct bpf_rb_node *node' arg to bpf_rbtree_add_impl is the same PTR_TO_BTF_ID w/ offset 9587 * that 'less' callback args will be receiving. However, 'node' arg was release_reference'd 9588 * by this point, so look at 'root' 9589 */ 9590 struct btf_field *field; 9591 9592 field = reg_find_field_offset(&caller->regs[BPF_REG_1], caller->regs[BPF_REG_1].off, 9593 BPF_RB_ROOT); 9594 if (!field || !field->graph_root.value_btf_id) 9595 return -EFAULT; 9596 9597 mark_reg_graph_node(callee->regs, BPF_REG_1, &field->graph_root); 9598 ref_set_non_owning(env, &callee->regs[BPF_REG_1]); 9599 mark_reg_graph_node(callee->regs, BPF_REG_2, &field->graph_root); 9600 ref_set_non_owning(env, &callee->regs[BPF_REG_2]); 9601 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 callee->in_callback_fn = true; 9606 callee->callback_ret_range = tnum_range(0, 1); 9607 return 0; 9608 } 9609 9610 static bool is_rbtree_lock_required_kfunc(u32 btf_id); 9611 9612 /* Are we currently verifying the callback for a rbtree helper that must 9613 * be called with lock held? If so, no need to complain about unreleased 9614 * lock 9615 */ 9616 static bool in_rbtree_lock_required_cb(struct bpf_verifier_env *env) 9617 { 9618 struct bpf_verifier_state *state = env->cur_state; 9619 struct bpf_insn *insn = env->prog->insnsi; 9620 struct bpf_func_state *callee; 9621 int kfunc_btf_id; 9622 9623 if (!state->curframe) 9624 return false; 9625 9626 callee = state->frame[state->curframe]; 9627 9628 if (!callee->in_callback_fn) 9629 return false; 9630 9631 kfunc_btf_id = insn[callee->callsite].imm; 9632 return is_rbtree_lock_required_kfunc(kfunc_btf_id); 9633 } 9634 9635 static int prepare_func_exit(struct bpf_verifier_env *env, int *insn_idx) 9636 { 9637 struct bpf_verifier_state *state = env->cur_state, *prev_st; 9638 struct bpf_func_state *caller, *callee; 9639 struct bpf_reg_state *r0; 9640 bool in_callback_fn; 9641 int err; 9642 9643 callee = state->frame[state->curframe]; 9644 r0 = &callee->regs[BPF_REG_0]; 9645 if (r0->type == PTR_TO_STACK) { 9646 /* technically it's ok to return caller's stack pointer 9647 * (or caller's caller's pointer) back to the caller, 9648 * since these pointers are valid. Only current stack 9649 * pointer will be invalid as soon as function exits, 9650 * but let's be conservative 9651 */ 9652 verbose(env, "cannot return stack pointer to the caller\n"); 9653 return -EINVAL; 9654 } 9655 9656 caller = state->frame[state->curframe - 1]; 9657 if (callee->in_callback_fn) { 9658 /* enforce R0 return value range [0, 1]. */ 9659 struct tnum range = callee->callback_ret_range; 9660 9661 if (r0->type != SCALAR_VALUE) { 9662 verbose(env, "R0 not a scalar value\n"); 9663 return -EACCES; 9664 } 9665 9666 /* we are going to rely on register's precise value */ 9667 err = mark_reg_read(env, r0, r0->parent, REG_LIVE_READ64); 9668 err = err ?: mark_chain_precision(env, BPF_REG_0); 9669 if (err) 9670 return err; 9671 9672 if (!tnum_in(range, r0->var_off)) { 9673 verbose_invalid_scalar(env, r0, &range, "callback return", "R0"); 9674 return -EINVAL; 9675 } 9676 if (!calls_callback(env, callee->callsite)) { 9677 verbose(env, "BUG: in callback at %d, callsite %d !calls_callback\n", 9678 *insn_idx, callee->callsite); 9679 return -EFAULT; 9680 } 9681 } else { 9682 /* return to the caller whatever r0 had in the callee */ 9683 caller->regs[BPF_REG_0] = *r0; 9684 } 9685 9686 /* callback_fn frame should have released its own additions to parent's 9687 * reference state at this point, or check_reference_leak would 9688 * complain, hence it must be the same as the caller. There is no need 9689 * to copy it back. 9690 */ 9691 if (!callee->in_callback_fn) { 9692 /* Transfer references to the caller */ 9693 err = copy_reference_state(caller, callee); 9694 if (err) 9695 return err; 9696 } 9697 9698 /* for callbacks like bpf_loop or bpf_for_each_map_elem go back to callsite, 9699 * there function call logic would reschedule callback visit. If iteration 9700 * converges is_state_visited() would prune that visit eventually. 9701 */ 9702 in_callback_fn = callee->in_callback_fn; 9703 if (in_callback_fn) 9704 *insn_idx = callee->callsite; 9705 else 9706 *insn_idx = callee->callsite + 1; 9707 9708 if (env->log.level & BPF_LOG_LEVEL) { 9709 verbose(env, "returning from callee:\n"); 9710 print_verifier_state(env, callee, true); 9711 verbose(env, "to caller at %d:\n", *insn_idx); 9712 print_verifier_state(env, caller, true); 9713 } 9714 /* clear everything in the callee */ 9715 free_func_state(callee); 9716 state->frame[state->curframe--] = NULL; 9717 9718 /* for callbacks widen imprecise scalars to make programs like below verify: 9719 * 9720 * struct ctx { int i; } 9721 * void cb(int idx, struct ctx *ctx) { ctx->i++; ... } 9722 * ... 9723 * struct ctx = { .i = 0; } 9724 * bpf_loop(100, cb, &ctx, 0); 9725 * 9726 * This is similar to what is done in process_iter_next_call() for open 9727 * coded iterators. 9728 */ 9729 prev_st = in_callback_fn ? find_prev_entry(env, state, *insn_idx) : NULL; 9730 if (prev_st) { 9731 err = widen_imprecise_scalars(env, prev_st, state); 9732 if (err) 9733 return err; 9734 } 9735 return 0; 9736 } 9737 9738 static void do_refine_retval_range(struct bpf_reg_state *regs, int ret_type, 9739 int func_id, 9740 struct bpf_call_arg_meta *meta) 9741 { 9742 struct bpf_reg_state *ret_reg = ®s[BPF_REG_0]; 9743 9744 if (ret_type != RET_INTEGER) 9745 return; 9746 9747 switch (func_id) { 9748 case BPF_FUNC_get_stack: 9749 case BPF_FUNC_get_task_stack: 9750 case BPF_FUNC_probe_read_str: 9751 case BPF_FUNC_probe_read_kernel_str: 9752 case BPF_FUNC_probe_read_user_str: 9753 ret_reg->smax_value = meta->msize_max_value; 9754 ret_reg->s32_max_value = meta->msize_max_value; 9755 ret_reg->smin_value = -MAX_ERRNO; 9756 ret_reg->s32_min_value = -MAX_ERRNO; 9757 reg_bounds_sync(ret_reg); 9758 break; 9759 case BPF_FUNC_get_smp_processor_id: 9760 ret_reg->umax_value = nr_cpu_ids - 1; 9761 ret_reg->u32_max_value = nr_cpu_ids - 1; 9762 ret_reg->smax_value = nr_cpu_ids - 1; 9763 ret_reg->s32_max_value = nr_cpu_ids - 1; 9764 ret_reg->umin_value = 0; 9765 ret_reg->u32_min_value = 0; 9766 ret_reg->smin_value = 0; 9767 ret_reg->s32_min_value = 0; 9768 reg_bounds_sync(ret_reg); 9769 break; 9770 } 9771 } 9772 9773 static int 9774 record_func_map(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta, 9775 int func_id, int insn_idx) 9776 { 9777 struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx]; 9778 struct bpf_map *map = meta->map_ptr; 9779 9780 if (func_id != BPF_FUNC_tail_call && 9781 func_id != BPF_FUNC_map_lookup_elem && 9782 func_id != BPF_FUNC_map_update_elem && 9783 func_id != BPF_FUNC_map_delete_elem && 9784 func_id != BPF_FUNC_map_push_elem && 9785 func_id != BPF_FUNC_map_pop_elem && 9786 func_id != BPF_FUNC_map_peek_elem && 9787 func_id != BPF_FUNC_for_each_map_elem && 9788 func_id != BPF_FUNC_redirect_map && 9789 func_id != BPF_FUNC_map_lookup_percpu_elem) 9790 return 0; 9791 9792 if (map == NULL) { 9793 verbose(env, "kernel subsystem misconfigured verifier\n"); 9794 return -EINVAL; 9795 } 9796 9797 /* In case of read-only, some additional restrictions 9798 * need to be applied in order to prevent altering the 9799 * state of the map from program side. 9800 */ 9801 if ((map->map_flags & BPF_F_RDONLY_PROG) && 9802 (func_id == BPF_FUNC_map_delete_elem || 9803 func_id == BPF_FUNC_map_update_elem || 9804 func_id == BPF_FUNC_map_push_elem || 9805 func_id == BPF_FUNC_map_pop_elem)) { 9806 verbose(env, "write into map forbidden\n"); 9807 return -EACCES; 9808 } 9809 9810 if (!BPF_MAP_PTR(aux->map_ptr_state)) 9811 bpf_map_ptr_store(aux, meta->map_ptr, 9812 !meta->map_ptr->bypass_spec_v1); 9813 else if (BPF_MAP_PTR(aux->map_ptr_state) != meta->map_ptr) 9814 bpf_map_ptr_store(aux, BPF_MAP_PTR_POISON, 9815 !meta->map_ptr->bypass_spec_v1); 9816 return 0; 9817 } 9818 9819 static int 9820 record_func_key(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta, 9821 int func_id, int insn_idx) 9822 { 9823 struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx]; 9824 struct bpf_reg_state *regs = cur_regs(env), *reg; 9825 struct bpf_map *map = meta->map_ptr; 9826 u64 val, max; 9827 int err; 9828 9829 if (func_id != BPF_FUNC_tail_call) 9830 return 0; 9831 if (!map || map->map_type != BPF_MAP_TYPE_PROG_ARRAY) { 9832 verbose(env, "kernel subsystem misconfigured verifier\n"); 9833 return -EINVAL; 9834 } 9835 9836 reg = ®s[BPF_REG_3]; 9837 val = reg->var_off.value; 9838 max = map->max_entries; 9839 9840 if (!(register_is_const(reg) && val < max)) { 9841 bpf_map_key_store(aux, BPF_MAP_KEY_POISON); 9842 return 0; 9843 } 9844 9845 err = mark_chain_precision(env, BPF_REG_3); 9846 if (err) 9847 return err; 9848 if (bpf_map_key_unseen(aux)) 9849 bpf_map_key_store(aux, val); 9850 else if (!bpf_map_key_poisoned(aux) && 9851 bpf_map_key_immediate(aux) != val) 9852 bpf_map_key_store(aux, BPF_MAP_KEY_POISON); 9853 return 0; 9854 } 9855 9856 static int check_reference_leak(struct bpf_verifier_env *env) 9857 { 9858 struct bpf_func_state *state = cur_func(env); 9859 bool refs_lingering = false; 9860 int i; 9861 9862 if (state->frameno && !state->in_callback_fn) 9863 return 0; 9864 9865 for (i = 0; i < state->acquired_refs; i++) { 9866 if (state->in_callback_fn && state->refs[i].callback_ref != state->frameno) 9867 continue; 9868 verbose(env, "Unreleased reference id=%d alloc_insn=%d\n", 9869 state->refs[i].id, state->refs[i].insn_idx); 9870 refs_lingering = true; 9871 } 9872 return refs_lingering ? -EINVAL : 0; 9873 } 9874 9875 static int check_bpf_snprintf_call(struct bpf_verifier_env *env, 9876 struct bpf_reg_state *regs) 9877 { 9878 struct bpf_reg_state *fmt_reg = ®s[BPF_REG_3]; 9879 struct bpf_reg_state *data_len_reg = ®s[BPF_REG_5]; 9880 struct bpf_map *fmt_map = fmt_reg->map_ptr; 9881 struct bpf_bprintf_data data = {}; 9882 int err, fmt_map_off, num_args; 9883 u64 fmt_addr; 9884 char *fmt; 9885 9886 /* data must be an array of u64 */ 9887 if (data_len_reg->var_off.value % 8) 9888 return -EINVAL; 9889 num_args = data_len_reg->var_off.value / 8; 9890 9891 /* fmt being ARG_PTR_TO_CONST_STR guarantees that var_off is const 9892 * and map_direct_value_addr is set. 9893 */ 9894 fmt_map_off = fmt_reg->off + fmt_reg->var_off.value; 9895 err = fmt_map->ops->map_direct_value_addr(fmt_map, &fmt_addr, 9896 fmt_map_off); 9897 if (err) { 9898 verbose(env, "verifier bug\n"); 9899 return -EFAULT; 9900 } 9901 fmt = (char *)(long)fmt_addr + fmt_map_off; 9902 9903 /* We are also guaranteed that fmt+fmt_map_off is NULL terminated, we 9904 * can focus on validating the format specifiers. 9905 */ 9906 err = bpf_bprintf_prepare(fmt, UINT_MAX, NULL, num_args, &data); 9907 if (err < 0) 9908 verbose(env, "Invalid format string\n"); 9909 9910 return err; 9911 } 9912 9913 static int check_get_func_ip(struct bpf_verifier_env *env) 9914 { 9915 enum bpf_prog_type type = resolve_prog_type(env->prog); 9916 int func_id = BPF_FUNC_get_func_ip; 9917 9918 if (type == BPF_PROG_TYPE_TRACING) { 9919 if (!bpf_prog_has_trampoline(env->prog)) { 9920 verbose(env, "func %s#%d supported only for fentry/fexit/fmod_ret programs\n", 9921 func_id_name(func_id), func_id); 9922 return -ENOTSUPP; 9923 } 9924 return 0; 9925 } else if (type == BPF_PROG_TYPE_KPROBE) { 9926 return 0; 9927 } 9928 9929 verbose(env, "func %s#%d not supported for program type %d\n", 9930 func_id_name(func_id), func_id, type); 9931 return -ENOTSUPP; 9932 } 9933 9934 static struct bpf_insn_aux_data *cur_aux(struct bpf_verifier_env *env) 9935 { 9936 return &env->insn_aux_data[env->insn_idx]; 9937 } 9938 9939 static bool loop_flag_is_zero(struct bpf_verifier_env *env) 9940 { 9941 struct bpf_reg_state *regs = cur_regs(env); 9942 struct bpf_reg_state *reg = ®s[BPF_REG_4]; 9943 bool reg_is_null = register_is_null(reg); 9944 9945 if (reg_is_null) 9946 mark_chain_precision(env, BPF_REG_4); 9947 9948 return reg_is_null; 9949 } 9950 9951 static void update_loop_inline_state(struct bpf_verifier_env *env, u32 subprogno) 9952 { 9953 struct bpf_loop_inline_state *state = &cur_aux(env)->loop_inline_state; 9954 9955 if (!state->initialized) { 9956 state->initialized = 1; 9957 state->fit_for_inline = loop_flag_is_zero(env); 9958 state->callback_subprogno = subprogno; 9959 return; 9960 } 9961 9962 if (!state->fit_for_inline) 9963 return; 9964 9965 state->fit_for_inline = (loop_flag_is_zero(env) && 9966 state->callback_subprogno == subprogno); 9967 } 9968 9969 static int check_helper_call(struct bpf_verifier_env *env, struct bpf_insn *insn, 9970 int *insn_idx_p) 9971 { 9972 enum bpf_prog_type prog_type = resolve_prog_type(env->prog); 9973 const struct bpf_func_proto *fn = NULL; 9974 enum bpf_return_type ret_type; 9975 enum bpf_type_flag ret_flag; 9976 struct bpf_reg_state *regs; 9977 struct bpf_call_arg_meta meta; 9978 int insn_idx = *insn_idx_p; 9979 bool changes_data; 9980 int i, err, func_id; 9981 9982 /* find function prototype */ 9983 func_id = insn->imm; 9984 if (func_id < 0 || func_id >= __BPF_FUNC_MAX_ID) { 9985 verbose(env, "invalid func %s#%d\n", func_id_name(func_id), 9986 func_id); 9987 return -EINVAL; 9988 } 9989 9990 if (env->ops->get_func_proto) 9991 fn = env->ops->get_func_proto(func_id, env->prog); 9992 if (!fn) { 9993 verbose(env, "unknown func %s#%d\n", func_id_name(func_id), 9994 func_id); 9995 return -EINVAL; 9996 } 9997 9998 /* eBPF programs must be GPL compatible to use GPL-ed functions */ 9999 if (!env->prog->gpl_compatible && fn->gpl_only) { 10000 verbose(env, "cannot call GPL-restricted function from non-GPL compatible program\n"); 10001 return -EINVAL; 10002 } 10003 10004 if (fn->allowed && !fn->allowed(env->prog)) { 10005 verbose(env, "helper call is not allowed in probe\n"); 10006 return -EINVAL; 10007 } 10008 10009 if (!env->prog->aux->sleepable && fn->might_sleep) { 10010 verbose(env, "helper call might sleep in a non-sleepable prog\n"); 10011 return -EINVAL; 10012 } 10013 10014 /* With LD_ABS/IND some JITs save/restore skb from r1. */ 10015 changes_data = bpf_helper_changes_pkt_data(fn->func); 10016 if (changes_data && fn->arg1_type != ARG_PTR_TO_CTX) { 10017 verbose(env, "kernel subsystem misconfigured func %s#%d: r1 != ctx\n", 10018 func_id_name(func_id), func_id); 10019 return -EINVAL; 10020 } 10021 10022 memset(&meta, 0, sizeof(meta)); 10023 meta.pkt_access = fn->pkt_access; 10024 10025 err = check_func_proto(fn, func_id); 10026 if (err) { 10027 verbose(env, "kernel subsystem misconfigured func %s#%d\n", 10028 func_id_name(func_id), func_id); 10029 return err; 10030 } 10031 10032 if (env->cur_state->active_rcu_lock) { 10033 if (fn->might_sleep) { 10034 verbose(env, "sleepable helper %s#%d in rcu_read_lock region\n", 10035 func_id_name(func_id), func_id); 10036 return -EINVAL; 10037 } 10038 10039 if (env->prog->aux->sleepable && is_storage_get_function(func_id)) 10040 env->insn_aux_data[insn_idx].storage_get_func_atomic = true; 10041 } 10042 10043 meta.func_id = func_id; 10044 /* check args */ 10045 for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++) { 10046 err = check_func_arg(env, i, &meta, fn, insn_idx); 10047 if (err) 10048 return err; 10049 } 10050 10051 err = record_func_map(env, &meta, func_id, insn_idx); 10052 if (err) 10053 return err; 10054 10055 err = record_func_key(env, &meta, func_id, insn_idx); 10056 if (err) 10057 return err; 10058 10059 /* Mark slots with STACK_MISC in case of raw mode, stack offset 10060 * is inferred from register state. 10061 */ 10062 for (i = 0; i < meta.access_size; i++) { 10063 err = check_mem_access(env, insn_idx, meta.regno, i, BPF_B, 10064 BPF_WRITE, -1, false, false); 10065 if (err) 10066 return err; 10067 } 10068 10069 regs = cur_regs(env); 10070 10071 if (meta.release_regno) { 10072 err = -EINVAL; 10073 /* This can only be set for PTR_TO_STACK, as CONST_PTR_TO_DYNPTR cannot 10074 * be released by any dynptr helper. Hence, unmark_stack_slots_dynptr 10075 * is safe to do directly. 10076 */ 10077 if (arg_type_is_dynptr(fn->arg_type[meta.release_regno - BPF_REG_1])) { 10078 if (regs[meta.release_regno].type == CONST_PTR_TO_DYNPTR) { 10079 verbose(env, "verifier internal error: CONST_PTR_TO_DYNPTR cannot be released\n"); 10080 return -EFAULT; 10081 } 10082 err = unmark_stack_slots_dynptr(env, ®s[meta.release_regno]); 10083 } else if (meta.ref_obj_id) { 10084 err = release_reference(env, meta.ref_obj_id); 10085 } else if (register_is_null(®s[meta.release_regno])) { 10086 /* meta.ref_obj_id can only be 0 if register that is meant to be 10087 * released is NULL, which must be > R0. 10088 */ 10089 err = 0; 10090 } 10091 if (err) { 10092 verbose(env, "func %s#%d reference has not been acquired before\n", 10093 func_id_name(func_id), func_id); 10094 return err; 10095 } 10096 } 10097 10098 switch (func_id) { 10099 case BPF_FUNC_tail_call: 10100 err = check_reference_leak(env); 10101 if (err) { 10102 verbose(env, "tail_call would lead to reference leak\n"); 10103 return err; 10104 } 10105 break; 10106 case BPF_FUNC_get_local_storage: 10107 /* check that flags argument in get_local_storage(map, flags) is 0, 10108 * this is required because get_local_storage() can't return an error. 10109 */ 10110 if (!register_is_null(®s[BPF_REG_2])) { 10111 verbose(env, "get_local_storage() doesn't support non-zero flags\n"); 10112 return -EINVAL; 10113 } 10114 break; 10115 case BPF_FUNC_for_each_map_elem: 10116 err = push_callback_call(env, insn, insn_idx, meta.subprogno, 10117 set_map_elem_callback_state); 10118 break; 10119 case BPF_FUNC_timer_set_callback: 10120 err = push_callback_call(env, insn, insn_idx, meta.subprogno, 10121 set_timer_callback_state); 10122 break; 10123 case BPF_FUNC_find_vma: 10124 err = push_callback_call(env, insn, insn_idx, meta.subprogno, 10125 set_find_vma_callback_state); 10126 break; 10127 case BPF_FUNC_snprintf: 10128 err = check_bpf_snprintf_call(env, regs); 10129 break; 10130 case BPF_FUNC_loop: 10131 update_loop_inline_state(env, meta.subprogno); 10132 /* Verifier relies on R1 value to determine if bpf_loop() iteration 10133 * is finished, thus mark it precise. 10134 */ 10135 err = mark_chain_precision(env, BPF_REG_1); 10136 if (err) 10137 return err; 10138 if (cur_func(env)->callback_depth < regs[BPF_REG_1].umax_value) { 10139 err = push_callback_call(env, insn, insn_idx, meta.subprogno, 10140 set_loop_callback_state); 10141 } else { 10142 cur_func(env)->callback_depth = 0; 10143 if (env->log.level & BPF_LOG_LEVEL2) 10144 verbose(env, "frame%d bpf_loop iteration limit reached\n", 10145 env->cur_state->curframe); 10146 } 10147 break; 10148 case BPF_FUNC_dynptr_from_mem: 10149 if (regs[BPF_REG_1].type != PTR_TO_MAP_VALUE) { 10150 verbose(env, "Unsupported reg type %s for bpf_dynptr_from_mem data\n", 10151 reg_type_str(env, regs[BPF_REG_1].type)); 10152 return -EACCES; 10153 } 10154 break; 10155 case BPF_FUNC_set_retval: 10156 if (prog_type == BPF_PROG_TYPE_LSM && 10157 env->prog->expected_attach_type == BPF_LSM_CGROUP) { 10158 if (!env->prog->aux->attach_func_proto->type) { 10159 /* Make sure programs that attach to void 10160 * hooks don't try to modify return value. 10161 */ 10162 verbose(env, "BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n"); 10163 return -EINVAL; 10164 } 10165 } 10166 break; 10167 case BPF_FUNC_dynptr_data: 10168 { 10169 struct bpf_reg_state *reg; 10170 int id, ref_obj_id; 10171 10172 reg = get_dynptr_arg_reg(env, fn, regs); 10173 if (!reg) 10174 return -EFAULT; 10175 10176 10177 if (meta.dynptr_id) { 10178 verbose(env, "verifier internal error: meta.dynptr_id already set\n"); 10179 return -EFAULT; 10180 } 10181 if (meta.ref_obj_id) { 10182 verbose(env, "verifier internal error: meta.ref_obj_id already set\n"); 10183 return -EFAULT; 10184 } 10185 10186 id = dynptr_id(env, reg); 10187 if (id < 0) { 10188 verbose(env, "verifier internal error: failed to obtain dynptr id\n"); 10189 return id; 10190 } 10191 10192 ref_obj_id = dynptr_ref_obj_id(env, reg); 10193 if (ref_obj_id < 0) { 10194 verbose(env, "verifier internal error: failed to obtain dynptr ref_obj_id\n"); 10195 return ref_obj_id; 10196 } 10197 10198 meta.dynptr_id = id; 10199 meta.ref_obj_id = ref_obj_id; 10200 10201 break; 10202 } 10203 case BPF_FUNC_dynptr_write: 10204 { 10205 enum bpf_dynptr_type dynptr_type; 10206 struct bpf_reg_state *reg; 10207 10208 reg = get_dynptr_arg_reg(env, fn, regs); 10209 if (!reg) 10210 return -EFAULT; 10211 10212 dynptr_type = dynptr_get_type(env, reg); 10213 if (dynptr_type == BPF_DYNPTR_TYPE_INVALID) 10214 return -EFAULT; 10215 10216 if (dynptr_type == BPF_DYNPTR_TYPE_SKB) 10217 /* this will trigger clear_all_pkt_pointers(), which will 10218 * invalidate all dynptr slices associated with the skb 10219 */ 10220 changes_data = true; 10221 10222 break; 10223 } 10224 case BPF_FUNC_user_ringbuf_drain: 10225 err = push_callback_call(env, insn, insn_idx, meta.subprogno, 10226 set_user_ringbuf_callback_state); 10227 break; 10228 } 10229 10230 if (err) 10231 return err; 10232 10233 /* reset caller saved regs */ 10234 for (i = 0; i < CALLER_SAVED_REGS; i++) { 10235 mark_reg_not_init(env, regs, caller_saved[i]); 10236 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK); 10237 } 10238 10239 /* helper call returns 64-bit value. */ 10240 regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG; 10241 10242 /* update return register (already marked as written above) */ 10243 ret_type = fn->ret_type; 10244 ret_flag = type_flag(ret_type); 10245 10246 switch (base_type(ret_type)) { 10247 case RET_INTEGER: 10248 /* sets type to SCALAR_VALUE */ 10249 mark_reg_unknown(env, regs, BPF_REG_0); 10250 break; 10251 case RET_VOID: 10252 regs[BPF_REG_0].type = NOT_INIT; 10253 break; 10254 case RET_PTR_TO_MAP_VALUE: 10255 /* There is no offset yet applied, variable or fixed */ 10256 mark_reg_known_zero(env, regs, BPF_REG_0); 10257 /* remember map_ptr, so that check_map_access() 10258 * can check 'value_size' boundary of memory access 10259 * to map element returned from bpf_map_lookup_elem() 10260 */ 10261 if (meta.map_ptr == NULL) { 10262 verbose(env, 10263 "kernel subsystem misconfigured verifier\n"); 10264 return -EINVAL; 10265 } 10266 regs[BPF_REG_0].map_ptr = meta.map_ptr; 10267 regs[BPF_REG_0].map_uid = meta.map_uid; 10268 regs[BPF_REG_0].type = PTR_TO_MAP_VALUE | ret_flag; 10269 if (!type_may_be_null(ret_type) && 10270 btf_record_has_field(meta.map_ptr->record, BPF_SPIN_LOCK)) { 10271 regs[BPF_REG_0].id = ++env->id_gen; 10272 } 10273 break; 10274 case RET_PTR_TO_SOCKET: 10275 mark_reg_known_zero(env, regs, BPF_REG_0); 10276 regs[BPF_REG_0].type = PTR_TO_SOCKET | ret_flag; 10277 break; 10278 case RET_PTR_TO_SOCK_COMMON: 10279 mark_reg_known_zero(env, regs, BPF_REG_0); 10280 regs[BPF_REG_0].type = PTR_TO_SOCK_COMMON | ret_flag; 10281 break; 10282 case RET_PTR_TO_TCP_SOCK: 10283 mark_reg_known_zero(env, regs, BPF_REG_0); 10284 regs[BPF_REG_0].type = PTR_TO_TCP_SOCK | ret_flag; 10285 break; 10286 case RET_PTR_TO_MEM: 10287 mark_reg_known_zero(env, regs, BPF_REG_0); 10288 regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag; 10289 regs[BPF_REG_0].mem_size = meta.mem_size; 10290 break; 10291 case RET_PTR_TO_MEM_OR_BTF_ID: 10292 { 10293 const struct btf_type *t; 10294 10295 mark_reg_known_zero(env, regs, BPF_REG_0); 10296 t = btf_type_skip_modifiers(meta.ret_btf, meta.ret_btf_id, NULL); 10297 if (!btf_type_is_struct(t)) { 10298 u32 tsize; 10299 const struct btf_type *ret; 10300 const char *tname; 10301 10302 /* resolve the type size of ksym. */ 10303 ret = btf_resolve_size(meta.ret_btf, t, &tsize); 10304 if (IS_ERR(ret)) { 10305 tname = btf_name_by_offset(meta.ret_btf, t->name_off); 10306 verbose(env, "unable to resolve the size of type '%s': %ld\n", 10307 tname, PTR_ERR(ret)); 10308 return -EINVAL; 10309 } 10310 regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag; 10311 regs[BPF_REG_0].mem_size = tsize; 10312 } else { 10313 /* MEM_RDONLY may be carried from ret_flag, but it 10314 * doesn't apply on PTR_TO_BTF_ID. Fold it, otherwise 10315 * it will confuse the check of PTR_TO_BTF_ID in 10316 * check_mem_access(). 10317 */ 10318 ret_flag &= ~MEM_RDONLY; 10319 10320 regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag; 10321 regs[BPF_REG_0].btf = meta.ret_btf; 10322 regs[BPF_REG_0].btf_id = meta.ret_btf_id; 10323 } 10324 break; 10325 } 10326 case RET_PTR_TO_BTF_ID: 10327 { 10328 struct btf *ret_btf; 10329 int ret_btf_id; 10330 10331 mark_reg_known_zero(env, regs, BPF_REG_0); 10332 regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag; 10333 if (func_id == BPF_FUNC_kptr_xchg) { 10334 ret_btf = meta.kptr_field->kptr.btf; 10335 ret_btf_id = meta.kptr_field->kptr.btf_id; 10336 if (!btf_is_kernel(ret_btf)) 10337 regs[BPF_REG_0].type |= MEM_ALLOC; 10338 } else { 10339 if (fn->ret_btf_id == BPF_PTR_POISON) { 10340 verbose(env, "verifier internal error:"); 10341 verbose(env, "func %s has non-overwritten BPF_PTR_POISON return type\n", 10342 func_id_name(func_id)); 10343 return -EINVAL; 10344 } 10345 ret_btf = btf_vmlinux; 10346 ret_btf_id = *fn->ret_btf_id; 10347 } 10348 if (ret_btf_id == 0) { 10349 verbose(env, "invalid return type %u of func %s#%d\n", 10350 base_type(ret_type), func_id_name(func_id), 10351 func_id); 10352 return -EINVAL; 10353 } 10354 regs[BPF_REG_0].btf = ret_btf; 10355 regs[BPF_REG_0].btf_id = ret_btf_id; 10356 break; 10357 } 10358 default: 10359 verbose(env, "unknown return type %u of func %s#%d\n", 10360 base_type(ret_type), func_id_name(func_id), func_id); 10361 return -EINVAL; 10362 } 10363 10364 if (type_may_be_null(regs[BPF_REG_0].type)) 10365 regs[BPF_REG_0].id = ++env->id_gen; 10366 10367 if (helper_multiple_ref_obj_use(func_id, meta.map_ptr)) { 10368 verbose(env, "verifier internal error: func %s#%d sets ref_obj_id more than once\n", 10369 func_id_name(func_id), func_id); 10370 return -EFAULT; 10371 } 10372 10373 if (is_dynptr_ref_function(func_id)) 10374 regs[BPF_REG_0].dynptr_id = meta.dynptr_id; 10375 10376 if (is_ptr_cast_function(func_id) || is_dynptr_ref_function(func_id)) { 10377 /* For release_reference() */ 10378 regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id; 10379 } else if (is_acquire_function(func_id, meta.map_ptr)) { 10380 int id = acquire_reference_state(env, insn_idx); 10381 10382 if (id < 0) 10383 return id; 10384 /* For mark_ptr_or_null_reg() */ 10385 regs[BPF_REG_0].id = id; 10386 /* For release_reference() */ 10387 regs[BPF_REG_0].ref_obj_id = id; 10388 } 10389 10390 do_refine_retval_range(regs, fn->ret_type, func_id, &meta); 10391 10392 err = check_map_func_compatibility(env, meta.map_ptr, func_id); 10393 if (err) 10394 return err; 10395 10396 if ((func_id == BPF_FUNC_get_stack || 10397 func_id == BPF_FUNC_get_task_stack) && 10398 !env->prog->has_callchain_buf) { 10399 const char *err_str; 10400 10401 #ifdef CONFIG_PERF_EVENTS 10402 err = get_callchain_buffers(sysctl_perf_event_max_stack); 10403 err_str = "cannot get callchain buffer for func %s#%d\n"; 10404 #else 10405 err = -ENOTSUPP; 10406 err_str = "func %s#%d not supported without CONFIG_PERF_EVENTS\n"; 10407 #endif 10408 if (err) { 10409 verbose(env, err_str, func_id_name(func_id), func_id); 10410 return err; 10411 } 10412 10413 env->prog->has_callchain_buf = true; 10414 } 10415 10416 if (func_id == BPF_FUNC_get_stackid || func_id == BPF_FUNC_get_stack) 10417 env->prog->call_get_stack = true; 10418 10419 if (func_id == BPF_FUNC_get_func_ip) { 10420 if (check_get_func_ip(env)) 10421 return -ENOTSUPP; 10422 env->prog->call_get_func_ip = true; 10423 } 10424 10425 if (changes_data) 10426 clear_all_pkt_pointers(env); 10427 return 0; 10428 } 10429 10430 /* mark_btf_func_reg_size() is used when the reg size is determined by 10431 * the BTF func_proto's return value size and argument. 10432 */ 10433 static void mark_btf_func_reg_size(struct bpf_verifier_env *env, u32 regno, 10434 size_t reg_size) 10435 { 10436 struct bpf_reg_state *reg = &cur_regs(env)[regno]; 10437 10438 if (regno == BPF_REG_0) { 10439 /* Function return value */ 10440 reg->live |= REG_LIVE_WRITTEN; 10441 reg->subreg_def = reg_size == sizeof(u64) ? 10442 DEF_NOT_SUBREG : env->insn_idx + 1; 10443 } else { 10444 /* Function argument */ 10445 if (reg_size == sizeof(u64)) { 10446 mark_insn_zext(env, reg); 10447 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64); 10448 } else { 10449 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ32); 10450 } 10451 } 10452 } 10453 10454 static bool is_kfunc_acquire(struct bpf_kfunc_call_arg_meta *meta) 10455 { 10456 return meta->kfunc_flags & KF_ACQUIRE; 10457 } 10458 10459 static bool is_kfunc_release(struct bpf_kfunc_call_arg_meta *meta) 10460 { 10461 return meta->kfunc_flags & KF_RELEASE; 10462 } 10463 10464 static bool is_kfunc_trusted_args(struct bpf_kfunc_call_arg_meta *meta) 10465 { 10466 return (meta->kfunc_flags & KF_TRUSTED_ARGS) || is_kfunc_release(meta); 10467 } 10468 10469 static bool is_kfunc_sleepable(struct bpf_kfunc_call_arg_meta *meta) 10470 { 10471 return meta->kfunc_flags & KF_SLEEPABLE; 10472 } 10473 10474 static bool is_kfunc_destructive(struct bpf_kfunc_call_arg_meta *meta) 10475 { 10476 return meta->kfunc_flags & KF_DESTRUCTIVE; 10477 } 10478 10479 static bool is_kfunc_rcu(struct bpf_kfunc_call_arg_meta *meta) 10480 { 10481 return meta->kfunc_flags & KF_RCU; 10482 } 10483 10484 static bool __kfunc_param_match_suffix(const struct btf *btf, 10485 const struct btf_param *arg, 10486 const char *suffix) 10487 { 10488 int suffix_len = strlen(suffix), len; 10489 const char *param_name; 10490 10491 /* In the future, this can be ported to use BTF tagging */ 10492 param_name = btf_name_by_offset(btf, arg->name_off); 10493 if (str_is_empty(param_name)) 10494 return false; 10495 len = strlen(param_name); 10496 if (len < suffix_len) 10497 return false; 10498 param_name += len - suffix_len; 10499 return !strncmp(param_name, suffix, suffix_len); 10500 } 10501 10502 static bool is_kfunc_arg_mem_size(const struct btf *btf, 10503 const struct btf_param *arg, 10504 const struct bpf_reg_state *reg) 10505 { 10506 const struct btf_type *t; 10507 10508 t = btf_type_skip_modifiers(btf, arg->type, NULL); 10509 if (!btf_type_is_scalar(t) || reg->type != SCALAR_VALUE) 10510 return false; 10511 10512 return __kfunc_param_match_suffix(btf, arg, "__sz"); 10513 } 10514 10515 static bool is_kfunc_arg_const_mem_size(const struct btf *btf, 10516 const struct btf_param *arg, 10517 const struct bpf_reg_state *reg) 10518 { 10519 const struct btf_type *t; 10520 10521 t = btf_type_skip_modifiers(btf, arg->type, NULL); 10522 if (!btf_type_is_scalar(t) || reg->type != SCALAR_VALUE) 10523 return false; 10524 10525 return __kfunc_param_match_suffix(btf, arg, "__szk"); 10526 } 10527 10528 static bool is_kfunc_arg_optional(const struct btf *btf, const struct btf_param *arg) 10529 { 10530 return __kfunc_param_match_suffix(btf, arg, "__opt"); 10531 } 10532 10533 static bool is_kfunc_arg_constant(const struct btf *btf, const struct btf_param *arg) 10534 { 10535 return __kfunc_param_match_suffix(btf, arg, "__k"); 10536 } 10537 10538 static bool is_kfunc_arg_ignore(const struct btf *btf, const struct btf_param *arg) 10539 { 10540 return __kfunc_param_match_suffix(btf, arg, "__ign"); 10541 } 10542 10543 static bool is_kfunc_arg_alloc_obj(const struct btf *btf, const struct btf_param *arg) 10544 { 10545 return __kfunc_param_match_suffix(btf, arg, "__alloc"); 10546 } 10547 10548 static bool is_kfunc_arg_uninit(const struct btf *btf, const struct btf_param *arg) 10549 { 10550 return __kfunc_param_match_suffix(btf, arg, "__uninit"); 10551 } 10552 10553 static bool is_kfunc_arg_refcounted_kptr(const struct btf *btf, const struct btf_param *arg) 10554 { 10555 return __kfunc_param_match_suffix(btf, arg, "__refcounted_kptr"); 10556 } 10557 10558 static bool is_kfunc_arg_scalar_with_name(const struct btf *btf, 10559 const struct btf_param *arg, 10560 const char *name) 10561 { 10562 int len, target_len = strlen(name); 10563 const char *param_name; 10564 10565 param_name = btf_name_by_offset(btf, arg->name_off); 10566 if (str_is_empty(param_name)) 10567 return false; 10568 len = strlen(param_name); 10569 if (len != target_len) 10570 return false; 10571 if (strcmp(param_name, name)) 10572 return false; 10573 10574 return true; 10575 } 10576 10577 enum { 10578 KF_ARG_DYNPTR_ID, 10579 KF_ARG_LIST_HEAD_ID, 10580 KF_ARG_LIST_NODE_ID, 10581 KF_ARG_RB_ROOT_ID, 10582 KF_ARG_RB_NODE_ID, 10583 }; 10584 10585 BTF_ID_LIST(kf_arg_btf_ids) 10586 BTF_ID(struct, bpf_dynptr_kern) 10587 BTF_ID(struct, bpf_list_head) 10588 BTF_ID(struct, bpf_list_node) 10589 BTF_ID(struct, bpf_rb_root) 10590 BTF_ID(struct, bpf_rb_node) 10591 10592 static bool __is_kfunc_ptr_arg_type(const struct btf *btf, 10593 const struct btf_param *arg, int type) 10594 { 10595 const struct btf_type *t; 10596 u32 res_id; 10597 10598 t = btf_type_skip_modifiers(btf, arg->type, NULL); 10599 if (!t) 10600 return false; 10601 if (!btf_type_is_ptr(t)) 10602 return false; 10603 t = btf_type_skip_modifiers(btf, t->type, &res_id); 10604 if (!t) 10605 return false; 10606 return btf_types_are_same(btf, res_id, btf_vmlinux, kf_arg_btf_ids[type]); 10607 } 10608 10609 static bool is_kfunc_arg_dynptr(const struct btf *btf, const struct btf_param *arg) 10610 { 10611 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_DYNPTR_ID); 10612 } 10613 10614 static bool is_kfunc_arg_list_head(const struct btf *btf, const struct btf_param *arg) 10615 { 10616 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_LIST_HEAD_ID); 10617 } 10618 10619 static bool is_kfunc_arg_list_node(const struct btf *btf, const struct btf_param *arg) 10620 { 10621 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_LIST_NODE_ID); 10622 } 10623 10624 static bool is_kfunc_arg_rbtree_root(const struct btf *btf, const struct btf_param *arg) 10625 { 10626 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_RB_ROOT_ID); 10627 } 10628 10629 static bool is_kfunc_arg_rbtree_node(const struct btf *btf, const struct btf_param *arg) 10630 { 10631 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_RB_NODE_ID); 10632 } 10633 10634 static bool is_kfunc_arg_callback(struct bpf_verifier_env *env, const struct btf *btf, 10635 const struct btf_param *arg) 10636 { 10637 const struct btf_type *t; 10638 10639 t = btf_type_resolve_func_ptr(btf, arg->type, NULL); 10640 if (!t) 10641 return false; 10642 10643 return true; 10644 } 10645 10646 /* Returns true if struct is composed of scalars, 4 levels of nesting allowed */ 10647 static bool __btf_type_is_scalar_struct(struct bpf_verifier_env *env, 10648 const struct btf *btf, 10649 const struct btf_type *t, int rec) 10650 { 10651 const struct btf_type *member_type; 10652 const struct btf_member *member; 10653 u32 i; 10654 10655 if (!btf_type_is_struct(t)) 10656 return false; 10657 10658 for_each_member(i, t, member) { 10659 const struct btf_array *array; 10660 10661 member_type = btf_type_skip_modifiers(btf, member->type, NULL); 10662 if (btf_type_is_struct(member_type)) { 10663 if (rec >= 3) { 10664 verbose(env, "max struct nesting depth exceeded\n"); 10665 return false; 10666 } 10667 if (!__btf_type_is_scalar_struct(env, btf, member_type, rec + 1)) 10668 return false; 10669 continue; 10670 } 10671 if (btf_type_is_array(member_type)) { 10672 array = btf_array(member_type); 10673 if (!array->nelems) 10674 return false; 10675 member_type = btf_type_skip_modifiers(btf, array->type, NULL); 10676 if (!btf_type_is_scalar(member_type)) 10677 return false; 10678 continue; 10679 } 10680 if (!btf_type_is_scalar(member_type)) 10681 return false; 10682 } 10683 return true; 10684 } 10685 10686 enum kfunc_ptr_arg_type { 10687 KF_ARG_PTR_TO_CTX, 10688 KF_ARG_PTR_TO_ALLOC_BTF_ID, /* Allocated object */ 10689 KF_ARG_PTR_TO_REFCOUNTED_KPTR, /* Refcounted local kptr */ 10690 KF_ARG_PTR_TO_DYNPTR, 10691 KF_ARG_PTR_TO_ITER, 10692 KF_ARG_PTR_TO_LIST_HEAD, 10693 KF_ARG_PTR_TO_LIST_NODE, 10694 KF_ARG_PTR_TO_BTF_ID, /* Also covers reg2btf_ids conversions */ 10695 KF_ARG_PTR_TO_MEM, 10696 KF_ARG_PTR_TO_MEM_SIZE, /* Size derived from next argument, skip it */ 10697 KF_ARG_PTR_TO_CALLBACK, 10698 KF_ARG_PTR_TO_RB_ROOT, 10699 KF_ARG_PTR_TO_RB_NODE, 10700 }; 10701 10702 enum special_kfunc_type { 10703 KF_bpf_obj_new_impl, 10704 KF_bpf_obj_drop_impl, 10705 KF_bpf_refcount_acquire_impl, 10706 KF_bpf_list_push_front_impl, 10707 KF_bpf_list_push_back_impl, 10708 KF_bpf_list_pop_front, 10709 KF_bpf_list_pop_back, 10710 KF_bpf_cast_to_kern_ctx, 10711 KF_bpf_rdonly_cast, 10712 KF_bpf_rcu_read_lock, 10713 KF_bpf_rcu_read_unlock, 10714 KF_bpf_rbtree_remove, 10715 KF_bpf_rbtree_add_impl, 10716 KF_bpf_rbtree_first, 10717 KF_bpf_dynptr_from_skb, 10718 KF_bpf_dynptr_from_xdp, 10719 KF_bpf_dynptr_slice, 10720 KF_bpf_dynptr_slice_rdwr, 10721 KF_bpf_dynptr_clone, 10722 }; 10723 10724 BTF_SET_START(special_kfunc_set) 10725 BTF_ID(func, bpf_obj_new_impl) 10726 BTF_ID(func, bpf_obj_drop_impl) 10727 BTF_ID(func, bpf_refcount_acquire_impl) 10728 BTF_ID(func, bpf_list_push_front_impl) 10729 BTF_ID(func, bpf_list_push_back_impl) 10730 BTF_ID(func, bpf_list_pop_front) 10731 BTF_ID(func, bpf_list_pop_back) 10732 BTF_ID(func, bpf_cast_to_kern_ctx) 10733 BTF_ID(func, bpf_rdonly_cast) 10734 BTF_ID(func, bpf_rbtree_remove) 10735 BTF_ID(func, bpf_rbtree_add_impl) 10736 BTF_ID(func, bpf_rbtree_first) 10737 BTF_ID(func, bpf_dynptr_from_skb) 10738 BTF_ID(func, bpf_dynptr_from_xdp) 10739 BTF_ID(func, bpf_dynptr_slice) 10740 BTF_ID(func, bpf_dynptr_slice_rdwr) 10741 BTF_ID(func, bpf_dynptr_clone) 10742 BTF_SET_END(special_kfunc_set) 10743 10744 BTF_ID_LIST(special_kfunc_list) 10745 BTF_ID(func, bpf_obj_new_impl) 10746 BTF_ID(func, bpf_obj_drop_impl) 10747 BTF_ID(func, bpf_refcount_acquire_impl) 10748 BTF_ID(func, bpf_list_push_front_impl) 10749 BTF_ID(func, bpf_list_push_back_impl) 10750 BTF_ID(func, bpf_list_pop_front) 10751 BTF_ID(func, bpf_list_pop_back) 10752 BTF_ID(func, bpf_cast_to_kern_ctx) 10753 BTF_ID(func, bpf_rdonly_cast) 10754 BTF_ID(func, bpf_rcu_read_lock) 10755 BTF_ID(func, bpf_rcu_read_unlock) 10756 BTF_ID(func, bpf_rbtree_remove) 10757 BTF_ID(func, bpf_rbtree_add_impl) 10758 BTF_ID(func, bpf_rbtree_first) 10759 BTF_ID(func, bpf_dynptr_from_skb) 10760 BTF_ID(func, bpf_dynptr_from_xdp) 10761 BTF_ID(func, bpf_dynptr_slice) 10762 BTF_ID(func, bpf_dynptr_slice_rdwr) 10763 BTF_ID(func, bpf_dynptr_clone) 10764 10765 static bool is_kfunc_ret_null(struct bpf_kfunc_call_arg_meta *meta) 10766 { 10767 if (meta->func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl] && 10768 meta->arg_owning_ref) { 10769 return false; 10770 } 10771 10772 return meta->kfunc_flags & KF_RET_NULL; 10773 } 10774 10775 static bool is_kfunc_bpf_rcu_read_lock(struct bpf_kfunc_call_arg_meta *meta) 10776 { 10777 return meta->func_id == special_kfunc_list[KF_bpf_rcu_read_lock]; 10778 } 10779 10780 static bool is_kfunc_bpf_rcu_read_unlock(struct bpf_kfunc_call_arg_meta *meta) 10781 { 10782 return meta->func_id == special_kfunc_list[KF_bpf_rcu_read_unlock]; 10783 } 10784 10785 static enum kfunc_ptr_arg_type 10786 get_kfunc_ptr_arg_type(struct bpf_verifier_env *env, 10787 struct bpf_kfunc_call_arg_meta *meta, 10788 const struct btf_type *t, const struct btf_type *ref_t, 10789 const char *ref_tname, const struct btf_param *args, 10790 int argno, int nargs) 10791 { 10792 u32 regno = argno + 1; 10793 struct bpf_reg_state *regs = cur_regs(env); 10794 struct bpf_reg_state *reg = ®s[regno]; 10795 bool arg_mem_size = false; 10796 10797 if (meta->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx]) 10798 return KF_ARG_PTR_TO_CTX; 10799 10800 /* In this function, we verify the kfunc's BTF as per the argument type, 10801 * leaving the rest of the verification with respect to the register 10802 * type to our caller. When a set of conditions hold in the BTF type of 10803 * arguments, we resolve it to a known kfunc_ptr_arg_type. 10804 */ 10805 if (btf_get_prog_ctx_type(&env->log, meta->btf, t, resolve_prog_type(env->prog), argno)) 10806 return KF_ARG_PTR_TO_CTX; 10807 10808 if (is_kfunc_arg_alloc_obj(meta->btf, &args[argno])) 10809 return KF_ARG_PTR_TO_ALLOC_BTF_ID; 10810 10811 if (is_kfunc_arg_refcounted_kptr(meta->btf, &args[argno])) 10812 return KF_ARG_PTR_TO_REFCOUNTED_KPTR; 10813 10814 if (is_kfunc_arg_dynptr(meta->btf, &args[argno])) 10815 return KF_ARG_PTR_TO_DYNPTR; 10816 10817 if (is_kfunc_arg_iter(meta, argno)) 10818 return KF_ARG_PTR_TO_ITER; 10819 10820 if (is_kfunc_arg_list_head(meta->btf, &args[argno])) 10821 return KF_ARG_PTR_TO_LIST_HEAD; 10822 10823 if (is_kfunc_arg_list_node(meta->btf, &args[argno])) 10824 return KF_ARG_PTR_TO_LIST_NODE; 10825 10826 if (is_kfunc_arg_rbtree_root(meta->btf, &args[argno])) 10827 return KF_ARG_PTR_TO_RB_ROOT; 10828 10829 if (is_kfunc_arg_rbtree_node(meta->btf, &args[argno])) 10830 return KF_ARG_PTR_TO_RB_NODE; 10831 10832 if ((base_type(reg->type) == PTR_TO_BTF_ID || reg2btf_ids[base_type(reg->type)])) { 10833 if (!btf_type_is_struct(ref_t)) { 10834 verbose(env, "kernel function %s args#%d pointer type %s %s is not supported\n", 10835 meta->func_name, argno, btf_type_str(ref_t), ref_tname); 10836 return -EINVAL; 10837 } 10838 return KF_ARG_PTR_TO_BTF_ID; 10839 } 10840 10841 if (is_kfunc_arg_callback(env, meta->btf, &args[argno])) 10842 return KF_ARG_PTR_TO_CALLBACK; 10843 10844 10845 if (argno + 1 < nargs && 10846 (is_kfunc_arg_mem_size(meta->btf, &args[argno + 1], ®s[regno + 1]) || 10847 is_kfunc_arg_const_mem_size(meta->btf, &args[argno + 1], ®s[regno + 1]))) 10848 arg_mem_size = true; 10849 10850 /* This is the catch all argument type of register types supported by 10851 * check_helper_mem_access. However, we only allow when argument type is 10852 * pointer to scalar, or struct composed (recursively) of scalars. When 10853 * arg_mem_size is true, the pointer can be void *. 10854 */ 10855 if (!btf_type_is_scalar(ref_t) && !__btf_type_is_scalar_struct(env, meta->btf, ref_t, 0) && 10856 (arg_mem_size ? !btf_type_is_void(ref_t) : 1)) { 10857 verbose(env, "arg#%d pointer type %s %s must point to %sscalar, or struct with scalar\n", 10858 argno, btf_type_str(ref_t), ref_tname, arg_mem_size ? "void, " : ""); 10859 return -EINVAL; 10860 } 10861 return arg_mem_size ? KF_ARG_PTR_TO_MEM_SIZE : KF_ARG_PTR_TO_MEM; 10862 } 10863 10864 static int process_kf_arg_ptr_to_btf_id(struct bpf_verifier_env *env, 10865 struct bpf_reg_state *reg, 10866 const struct btf_type *ref_t, 10867 const char *ref_tname, u32 ref_id, 10868 struct bpf_kfunc_call_arg_meta *meta, 10869 int argno) 10870 { 10871 const struct btf_type *reg_ref_t; 10872 bool strict_type_match = false; 10873 const struct btf *reg_btf; 10874 const char *reg_ref_tname; 10875 u32 reg_ref_id; 10876 10877 if (base_type(reg->type) == PTR_TO_BTF_ID) { 10878 reg_btf = reg->btf; 10879 reg_ref_id = reg->btf_id; 10880 } else { 10881 reg_btf = btf_vmlinux; 10882 reg_ref_id = *reg2btf_ids[base_type(reg->type)]; 10883 } 10884 10885 /* Enforce strict type matching for calls to kfuncs that are acquiring 10886 * or releasing a reference, or are no-cast aliases. We do _not_ 10887 * enforce strict matching for plain KF_TRUSTED_ARGS kfuncs by default, 10888 * as we want to enable BPF programs to pass types that are bitwise 10889 * equivalent without forcing them to explicitly cast with something 10890 * like bpf_cast_to_kern_ctx(). 10891 * 10892 * For example, say we had a type like the following: 10893 * 10894 * struct bpf_cpumask { 10895 * cpumask_t cpumask; 10896 * refcount_t usage; 10897 * }; 10898 * 10899 * Note that as specified in <linux/cpumask.h>, cpumask_t is typedef'ed 10900 * to a struct cpumask, so it would be safe to pass a struct 10901 * bpf_cpumask * to a kfunc expecting a struct cpumask *. 10902 * 10903 * The philosophy here is similar to how we allow scalars of different 10904 * types to be passed to kfuncs as long as the size is the same. The 10905 * only difference here is that we're simply allowing 10906 * btf_struct_ids_match() to walk the struct at the 0th offset, and 10907 * resolve types. 10908 */ 10909 if (is_kfunc_acquire(meta) || 10910 (is_kfunc_release(meta) && reg->ref_obj_id) || 10911 btf_type_ids_nocast_alias(&env->log, reg_btf, reg_ref_id, meta->btf, ref_id)) 10912 strict_type_match = true; 10913 10914 WARN_ON_ONCE(is_kfunc_trusted_args(meta) && reg->off); 10915 10916 reg_ref_t = btf_type_skip_modifiers(reg_btf, reg_ref_id, ®_ref_id); 10917 reg_ref_tname = btf_name_by_offset(reg_btf, reg_ref_t->name_off); 10918 if (!btf_struct_ids_match(&env->log, reg_btf, reg_ref_id, reg->off, meta->btf, ref_id, strict_type_match)) { 10919 verbose(env, "kernel function %s args#%d expected pointer to %s %s but R%d has a pointer to %s %s\n", 10920 meta->func_name, argno, btf_type_str(ref_t), ref_tname, argno + 1, 10921 btf_type_str(reg_ref_t), reg_ref_tname); 10922 return -EINVAL; 10923 } 10924 return 0; 10925 } 10926 10927 static int ref_set_non_owning(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 10928 { 10929 struct bpf_verifier_state *state = env->cur_state; 10930 struct btf_record *rec = reg_btf_record(reg); 10931 10932 if (!state->active_lock.ptr) { 10933 verbose(env, "verifier internal error: ref_set_non_owning w/o active lock\n"); 10934 return -EFAULT; 10935 } 10936 10937 if (type_flag(reg->type) & NON_OWN_REF) { 10938 verbose(env, "verifier internal error: NON_OWN_REF already set\n"); 10939 return -EFAULT; 10940 } 10941 10942 reg->type |= NON_OWN_REF; 10943 if (rec->refcount_off >= 0) 10944 reg->type |= MEM_RCU; 10945 10946 return 0; 10947 } 10948 10949 static int ref_convert_owning_non_owning(struct bpf_verifier_env *env, u32 ref_obj_id) 10950 { 10951 struct bpf_func_state *state, *unused; 10952 struct bpf_reg_state *reg; 10953 int i; 10954 10955 state = cur_func(env); 10956 10957 if (!ref_obj_id) { 10958 verbose(env, "verifier internal error: ref_obj_id is zero for " 10959 "owning -> non-owning conversion\n"); 10960 return -EFAULT; 10961 } 10962 10963 for (i = 0; i < state->acquired_refs; i++) { 10964 if (state->refs[i].id != ref_obj_id) 10965 continue; 10966 10967 /* Clear ref_obj_id here so release_reference doesn't clobber 10968 * the whole reg 10969 */ 10970 bpf_for_each_reg_in_vstate(env->cur_state, unused, reg, ({ 10971 if (reg->ref_obj_id == ref_obj_id) { 10972 reg->ref_obj_id = 0; 10973 ref_set_non_owning(env, reg); 10974 } 10975 })); 10976 return 0; 10977 } 10978 10979 verbose(env, "verifier internal error: ref state missing for ref_obj_id\n"); 10980 return -EFAULT; 10981 } 10982 10983 /* Implementation details: 10984 * 10985 * Each register points to some region of memory, which we define as an 10986 * allocation. Each allocation may embed a bpf_spin_lock which protects any 10987 * special BPF objects (bpf_list_head, bpf_rb_root, etc.) part of the same 10988 * allocation. The lock and the data it protects are colocated in the same 10989 * memory region. 10990 * 10991 * Hence, everytime a register holds a pointer value pointing to such 10992 * allocation, the verifier preserves a unique reg->id for it. 10993 * 10994 * The verifier remembers the lock 'ptr' and the lock 'id' whenever 10995 * bpf_spin_lock is called. 10996 * 10997 * To enable this, lock state in the verifier captures two values: 10998 * active_lock.ptr = Register's type specific pointer 10999 * active_lock.id = A unique ID for each register pointer value 11000 * 11001 * Currently, PTR_TO_MAP_VALUE and PTR_TO_BTF_ID | MEM_ALLOC are the two 11002 * supported register types. 11003 * 11004 * The active_lock.ptr in case of map values is the reg->map_ptr, and in case of 11005 * allocated objects is the reg->btf pointer. 11006 * 11007 * The active_lock.id is non-unique for maps supporting direct_value_addr, as we 11008 * can establish the provenance of the map value statically for each distinct 11009 * lookup into such maps. They always contain a single map value hence unique 11010 * IDs for each pseudo load pessimizes the algorithm and rejects valid programs. 11011 * 11012 * So, in case of global variables, they use array maps with max_entries = 1, 11013 * hence their active_lock.ptr becomes map_ptr and id = 0 (since they all point 11014 * into the same map value as max_entries is 1, as described above). 11015 * 11016 * In case of inner map lookups, the inner map pointer has same map_ptr as the 11017 * outer map pointer (in verifier context), but each lookup into an inner map 11018 * assigns a fresh reg->id to the lookup, so while lookups into distinct inner 11019 * maps from the same outer map share the same map_ptr as active_lock.ptr, they 11020 * will get different reg->id assigned to each lookup, hence different 11021 * active_lock.id. 11022 * 11023 * In case of allocated objects, active_lock.ptr is the reg->btf, and the 11024 * reg->id is a unique ID preserved after the NULL pointer check on the pointer 11025 * returned from bpf_obj_new. Each allocation receives a new reg->id. 11026 */ 11027 static int check_reg_allocation_locked(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 11028 { 11029 void *ptr; 11030 u32 id; 11031 11032 switch ((int)reg->type) { 11033 case PTR_TO_MAP_VALUE: 11034 ptr = reg->map_ptr; 11035 break; 11036 case PTR_TO_BTF_ID | MEM_ALLOC: 11037 ptr = reg->btf; 11038 break; 11039 default: 11040 verbose(env, "verifier internal error: unknown reg type for lock check\n"); 11041 return -EFAULT; 11042 } 11043 id = reg->id; 11044 11045 if (!env->cur_state->active_lock.ptr) 11046 return -EINVAL; 11047 if (env->cur_state->active_lock.ptr != ptr || 11048 env->cur_state->active_lock.id != id) { 11049 verbose(env, "held lock and object are not in the same allocation\n"); 11050 return -EINVAL; 11051 } 11052 return 0; 11053 } 11054 11055 static bool is_bpf_list_api_kfunc(u32 btf_id) 11056 { 11057 return btf_id == special_kfunc_list[KF_bpf_list_push_front_impl] || 11058 btf_id == special_kfunc_list[KF_bpf_list_push_back_impl] || 11059 btf_id == special_kfunc_list[KF_bpf_list_pop_front] || 11060 btf_id == special_kfunc_list[KF_bpf_list_pop_back]; 11061 } 11062 11063 static bool is_bpf_rbtree_api_kfunc(u32 btf_id) 11064 { 11065 return btf_id == special_kfunc_list[KF_bpf_rbtree_add_impl] || 11066 btf_id == special_kfunc_list[KF_bpf_rbtree_remove] || 11067 btf_id == special_kfunc_list[KF_bpf_rbtree_first]; 11068 } 11069 11070 static bool is_bpf_graph_api_kfunc(u32 btf_id) 11071 { 11072 return is_bpf_list_api_kfunc(btf_id) || is_bpf_rbtree_api_kfunc(btf_id) || 11073 btf_id == special_kfunc_list[KF_bpf_refcount_acquire_impl]; 11074 } 11075 11076 static bool is_sync_callback_calling_kfunc(u32 btf_id) 11077 { 11078 return btf_id == special_kfunc_list[KF_bpf_rbtree_add_impl]; 11079 } 11080 11081 static bool is_rbtree_lock_required_kfunc(u32 btf_id) 11082 { 11083 return is_bpf_rbtree_api_kfunc(btf_id); 11084 } 11085 11086 static bool check_kfunc_is_graph_root_api(struct bpf_verifier_env *env, 11087 enum btf_field_type head_field_type, 11088 u32 kfunc_btf_id) 11089 { 11090 bool ret; 11091 11092 switch (head_field_type) { 11093 case BPF_LIST_HEAD: 11094 ret = is_bpf_list_api_kfunc(kfunc_btf_id); 11095 break; 11096 case BPF_RB_ROOT: 11097 ret = is_bpf_rbtree_api_kfunc(kfunc_btf_id); 11098 break; 11099 default: 11100 verbose(env, "verifier internal error: unexpected graph root argument type %s\n", 11101 btf_field_type_name(head_field_type)); 11102 return false; 11103 } 11104 11105 if (!ret) 11106 verbose(env, "verifier internal error: %s head arg for unknown kfunc\n", 11107 btf_field_type_name(head_field_type)); 11108 return ret; 11109 } 11110 11111 static bool check_kfunc_is_graph_node_api(struct bpf_verifier_env *env, 11112 enum btf_field_type node_field_type, 11113 u32 kfunc_btf_id) 11114 { 11115 bool ret; 11116 11117 switch (node_field_type) { 11118 case BPF_LIST_NODE: 11119 ret = (kfunc_btf_id == special_kfunc_list[KF_bpf_list_push_front_impl] || 11120 kfunc_btf_id == special_kfunc_list[KF_bpf_list_push_back_impl]); 11121 break; 11122 case BPF_RB_NODE: 11123 ret = (kfunc_btf_id == special_kfunc_list[KF_bpf_rbtree_remove] || 11124 kfunc_btf_id == special_kfunc_list[KF_bpf_rbtree_add_impl]); 11125 break; 11126 default: 11127 verbose(env, "verifier internal error: unexpected graph node argument type %s\n", 11128 btf_field_type_name(node_field_type)); 11129 return false; 11130 } 11131 11132 if (!ret) 11133 verbose(env, "verifier internal error: %s node arg for unknown kfunc\n", 11134 btf_field_type_name(node_field_type)); 11135 return ret; 11136 } 11137 11138 static int 11139 __process_kf_arg_ptr_to_graph_root(struct bpf_verifier_env *env, 11140 struct bpf_reg_state *reg, u32 regno, 11141 struct bpf_kfunc_call_arg_meta *meta, 11142 enum btf_field_type head_field_type, 11143 struct btf_field **head_field) 11144 { 11145 const char *head_type_name; 11146 struct btf_field *field; 11147 struct btf_record *rec; 11148 u32 head_off; 11149 11150 if (meta->btf != btf_vmlinux) { 11151 verbose(env, "verifier internal error: unexpected btf mismatch in kfunc call\n"); 11152 return -EFAULT; 11153 } 11154 11155 if (!check_kfunc_is_graph_root_api(env, head_field_type, meta->func_id)) 11156 return -EFAULT; 11157 11158 head_type_name = btf_field_type_name(head_field_type); 11159 if (!tnum_is_const(reg->var_off)) { 11160 verbose(env, 11161 "R%d doesn't have constant offset. %s has to be at the constant offset\n", 11162 regno, head_type_name); 11163 return -EINVAL; 11164 } 11165 11166 rec = reg_btf_record(reg); 11167 head_off = reg->off + reg->var_off.value; 11168 field = btf_record_find(rec, head_off, head_field_type); 11169 if (!field) { 11170 verbose(env, "%s not found at offset=%u\n", head_type_name, head_off); 11171 return -EINVAL; 11172 } 11173 11174 /* All functions require bpf_list_head to be protected using a bpf_spin_lock */ 11175 if (check_reg_allocation_locked(env, reg)) { 11176 verbose(env, "bpf_spin_lock at off=%d must be held for %s\n", 11177 rec->spin_lock_off, head_type_name); 11178 return -EINVAL; 11179 } 11180 11181 if (*head_field) { 11182 verbose(env, "verifier internal error: repeating %s arg\n", head_type_name); 11183 return -EFAULT; 11184 } 11185 *head_field = field; 11186 return 0; 11187 } 11188 11189 static int process_kf_arg_ptr_to_list_head(struct bpf_verifier_env *env, 11190 struct bpf_reg_state *reg, u32 regno, 11191 struct bpf_kfunc_call_arg_meta *meta) 11192 { 11193 return __process_kf_arg_ptr_to_graph_root(env, reg, regno, meta, BPF_LIST_HEAD, 11194 &meta->arg_list_head.field); 11195 } 11196 11197 static int process_kf_arg_ptr_to_rbtree_root(struct bpf_verifier_env *env, 11198 struct bpf_reg_state *reg, u32 regno, 11199 struct bpf_kfunc_call_arg_meta *meta) 11200 { 11201 return __process_kf_arg_ptr_to_graph_root(env, reg, regno, meta, BPF_RB_ROOT, 11202 &meta->arg_rbtree_root.field); 11203 } 11204 11205 static int 11206 __process_kf_arg_ptr_to_graph_node(struct bpf_verifier_env *env, 11207 struct bpf_reg_state *reg, u32 regno, 11208 struct bpf_kfunc_call_arg_meta *meta, 11209 enum btf_field_type head_field_type, 11210 enum btf_field_type node_field_type, 11211 struct btf_field **node_field) 11212 { 11213 const char *node_type_name; 11214 const struct btf_type *et, *t; 11215 struct btf_field *field; 11216 u32 node_off; 11217 11218 if (meta->btf != btf_vmlinux) { 11219 verbose(env, "verifier internal error: unexpected btf mismatch in kfunc call\n"); 11220 return -EFAULT; 11221 } 11222 11223 if (!check_kfunc_is_graph_node_api(env, node_field_type, meta->func_id)) 11224 return -EFAULT; 11225 11226 node_type_name = btf_field_type_name(node_field_type); 11227 if (!tnum_is_const(reg->var_off)) { 11228 verbose(env, 11229 "R%d doesn't have constant offset. %s has to be at the constant offset\n", 11230 regno, node_type_name); 11231 return -EINVAL; 11232 } 11233 11234 node_off = reg->off + reg->var_off.value; 11235 field = reg_find_field_offset(reg, node_off, node_field_type); 11236 if (!field || field->offset != node_off) { 11237 verbose(env, "%s not found at offset=%u\n", node_type_name, node_off); 11238 return -EINVAL; 11239 } 11240 11241 field = *node_field; 11242 11243 et = btf_type_by_id(field->graph_root.btf, field->graph_root.value_btf_id); 11244 t = btf_type_by_id(reg->btf, reg->btf_id); 11245 if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, 0, field->graph_root.btf, 11246 field->graph_root.value_btf_id, true)) { 11247 verbose(env, "operation on %s expects arg#1 %s at offset=%d " 11248 "in struct %s, but arg is at offset=%d in struct %s\n", 11249 btf_field_type_name(head_field_type), 11250 btf_field_type_name(node_field_type), 11251 field->graph_root.node_offset, 11252 btf_name_by_offset(field->graph_root.btf, et->name_off), 11253 node_off, btf_name_by_offset(reg->btf, t->name_off)); 11254 return -EINVAL; 11255 } 11256 meta->arg_btf = reg->btf; 11257 meta->arg_btf_id = reg->btf_id; 11258 11259 if (node_off != field->graph_root.node_offset) { 11260 verbose(env, "arg#1 offset=%d, but expected %s at offset=%d in struct %s\n", 11261 node_off, btf_field_type_name(node_field_type), 11262 field->graph_root.node_offset, 11263 btf_name_by_offset(field->graph_root.btf, et->name_off)); 11264 return -EINVAL; 11265 } 11266 11267 return 0; 11268 } 11269 11270 static int process_kf_arg_ptr_to_list_node(struct bpf_verifier_env *env, 11271 struct bpf_reg_state *reg, u32 regno, 11272 struct bpf_kfunc_call_arg_meta *meta) 11273 { 11274 return __process_kf_arg_ptr_to_graph_node(env, reg, regno, meta, 11275 BPF_LIST_HEAD, BPF_LIST_NODE, 11276 &meta->arg_list_head.field); 11277 } 11278 11279 static int process_kf_arg_ptr_to_rbtree_node(struct bpf_verifier_env *env, 11280 struct bpf_reg_state *reg, u32 regno, 11281 struct bpf_kfunc_call_arg_meta *meta) 11282 { 11283 return __process_kf_arg_ptr_to_graph_node(env, reg, regno, meta, 11284 BPF_RB_ROOT, BPF_RB_NODE, 11285 &meta->arg_rbtree_root.field); 11286 } 11287 11288 static int check_kfunc_args(struct bpf_verifier_env *env, struct bpf_kfunc_call_arg_meta *meta, 11289 int insn_idx) 11290 { 11291 const char *func_name = meta->func_name, *ref_tname; 11292 const struct btf *btf = meta->btf; 11293 const struct btf_param *args; 11294 struct btf_record *rec; 11295 u32 i, nargs; 11296 int ret; 11297 11298 args = (const struct btf_param *)(meta->func_proto + 1); 11299 nargs = btf_type_vlen(meta->func_proto); 11300 if (nargs > MAX_BPF_FUNC_REG_ARGS) { 11301 verbose(env, "Function %s has %d > %d args\n", func_name, nargs, 11302 MAX_BPF_FUNC_REG_ARGS); 11303 return -EINVAL; 11304 } 11305 11306 /* Check that BTF function arguments match actual types that the 11307 * verifier sees. 11308 */ 11309 for (i = 0; i < nargs; i++) { 11310 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[i + 1]; 11311 const struct btf_type *t, *ref_t, *resolve_ret; 11312 enum bpf_arg_type arg_type = ARG_DONTCARE; 11313 u32 regno = i + 1, ref_id, type_size; 11314 bool is_ret_buf_sz = false; 11315 int kf_arg_type; 11316 11317 t = btf_type_skip_modifiers(btf, args[i].type, NULL); 11318 11319 if (is_kfunc_arg_ignore(btf, &args[i])) 11320 continue; 11321 11322 if (btf_type_is_scalar(t)) { 11323 if (reg->type != SCALAR_VALUE) { 11324 verbose(env, "R%d is not a scalar\n", regno); 11325 return -EINVAL; 11326 } 11327 11328 if (is_kfunc_arg_constant(meta->btf, &args[i])) { 11329 if (meta->arg_constant.found) { 11330 verbose(env, "verifier internal error: only one constant argument permitted\n"); 11331 return -EFAULT; 11332 } 11333 if (!tnum_is_const(reg->var_off)) { 11334 verbose(env, "R%d must be a known constant\n", regno); 11335 return -EINVAL; 11336 } 11337 ret = mark_chain_precision(env, regno); 11338 if (ret < 0) 11339 return ret; 11340 meta->arg_constant.found = true; 11341 meta->arg_constant.value = reg->var_off.value; 11342 } else if (is_kfunc_arg_scalar_with_name(btf, &args[i], "rdonly_buf_size")) { 11343 meta->r0_rdonly = true; 11344 is_ret_buf_sz = true; 11345 } else if (is_kfunc_arg_scalar_with_name(btf, &args[i], "rdwr_buf_size")) { 11346 is_ret_buf_sz = true; 11347 } 11348 11349 if (is_ret_buf_sz) { 11350 if (meta->r0_size) { 11351 verbose(env, "2 or more rdonly/rdwr_buf_size parameters for kfunc"); 11352 return -EINVAL; 11353 } 11354 11355 if (!tnum_is_const(reg->var_off)) { 11356 verbose(env, "R%d is not a const\n", regno); 11357 return -EINVAL; 11358 } 11359 11360 meta->r0_size = reg->var_off.value; 11361 ret = mark_chain_precision(env, regno); 11362 if (ret) 11363 return ret; 11364 } 11365 continue; 11366 } 11367 11368 if (!btf_type_is_ptr(t)) { 11369 verbose(env, "Unrecognized arg#%d type %s\n", i, btf_type_str(t)); 11370 return -EINVAL; 11371 } 11372 11373 if ((is_kfunc_trusted_args(meta) || is_kfunc_rcu(meta)) && 11374 (register_is_null(reg) || type_may_be_null(reg->type))) { 11375 verbose(env, "Possibly NULL pointer passed to trusted arg%d\n", i); 11376 return -EACCES; 11377 } 11378 11379 if (reg->ref_obj_id) { 11380 if (is_kfunc_release(meta) && meta->ref_obj_id) { 11381 verbose(env, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n", 11382 regno, reg->ref_obj_id, 11383 meta->ref_obj_id); 11384 return -EFAULT; 11385 } 11386 meta->ref_obj_id = reg->ref_obj_id; 11387 if (is_kfunc_release(meta)) 11388 meta->release_regno = regno; 11389 } 11390 11391 ref_t = btf_type_skip_modifiers(btf, t->type, &ref_id); 11392 ref_tname = btf_name_by_offset(btf, ref_t->name_off); 11393 11394 kf_arg_type = get_kfunc_ptr_arg_type(env, meta, t, ref_t, ref_tname, args, i, nargs); 11395 if (kf_arg_type < 0) 11396 return kf_arg_type; 11397 11398 switch (kf_arg_type) { 11399 case KF_ARG_PTR_TO_ALLOC_BTF_ID: 11400 case KF_ARG_PTR_TO_BTF_ID: 11401 if (!is_kfunc_trusted_args(meta) && !is_kfunc_rcu(meta)) 11402 break; 11403 11404 if (!is_trusted_reg(reg)) { 11405 if (!is_kfunc_rcu(meta)) { 11406 verbose(env, "R%d must be referenced or trusted\n", regno); 11407 return -EINVAL; 11408 } 11409 if (!is_rcu_reg(reg)) { 11410 verbose(env, "R%d must be a rcu pointer\n", regno); 11411 return -EINVAL; 11412 } 11413 } 11414 11415 fallthrough; 11416 case KF_ARG_PTR_TO_CTX: 11417 /* Trusted arguments have the same offset checks as release arguments */ 11418 arg_type |= OBJ_RELEASE; 11419 break; 11420 case KF_ARG_PTR_TO_DYNPTR: 11421 case KF_ARG_PTR_TO_ITER: 11422 case KF_ARG_PTR_TO_LIST_HEAD: 11423 case KF_ARG_PTR_TO_LIST_NODE: 11424 case KF_ARG_PTR_TO_RB_ROOT: 11425 case KF_ARG_PTR_TO_RB_NODE: 11426 case KF_ARG_PTR_TO_MEM: 11427 case KF_ARG_PTR_TO_MEM_SIZE: 11428 case KF_ARG_PTR_TO_CALLBACK: 11429 case KF_ARG_PTR_TO_REFCOUNTED_KPTR: 11430 /* Trusted by default */ 11431 break; 11432 default: 11433 WARN_ON_ONCE(1); 11434 return -EFAULT; 11435 } 11436 11437 if (is_kfunc_release(meta) && reg->ref_obj_id) 11438 arg_type |= OBJ_RELEASE; 11439 ret = check_func_arg_reg_off(env, reg, regno, arg_type); 11440 if (ret < 0) 11441 return ret; 11442 11443 switch (kf_arg_type) { 11444 case KF_ARG_PTR_TO_CTX: 11445 if (reg->type != PTR_TO_CTX) { 11446 verbose(env, "arg#%d expected pointer to ctx, but got %s\n", i, btf_type_str(t)); 11447 return -EINVAL; 11448 } 11449 11450 if (meta->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx]) { 11451 ret = get_kern_ctx_btf_id(&env->log, resolve_prog_type(env->prog)); 11452 if (ret < 0) 11453 return -EINVAL; 11454 meta->ret_btf_id = ret; 11455 } 11456 break; 11457 case KF_ARG_PTR_TO_ALLOC_BTF_ID: 11458 if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) { 11459 verbose(env, "arg#%d expected pointer to allocated object\n", i); 11460 return -EINVAL; 11461 } 11462 if (!reg->ref_obj_id) { 11463 verbose(env, "allocated object must be referenced\n"); 11464 return -EINVAL; 11465 } 11466 if (meta->btf == btf_vmlinux && 11467 meta->func_id == special_kfunc_list[KF_bpf_obj_drop_impl]) { 11468 meta->arg_btf = reg->btf; 11469 meta->arg_btf_id = reg->btf_id; 11470 } 11471 break; 11472 case KF_ARG_PTR_TO_DYNPTR: 11473 { 11474 enum bpf_arg_type dynptr_arg_type = ARG_PTR_TO_DYNPTR; 11475 int clone_ref_obj_id = 0; 11476 11477 if (reg->type != PTR_TO_STACK && 11478 reg->type != CONST_PTR_TO_DYNPTR) { 11479 verbose(env, "arg#%d expected pointer to stack or dynptr_ptr\n", i); 11480 return -EINVAL; 11481 } 11482 11483 if (reg->type == CONST_PTR_TO_DYNPTR) 11484 dynptr_arg_type |= MEM_RDONLY; 11485 11486 if (is_kfunc_arg_uninit(btf, &args[i])) 11487 dynptr_arg_type |= MEM_UNINIT; 11488 11489 if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_from_skb]) { 11490 dynptr_arg_type |= DYNPTR_TYPE_SKB; 11491 } else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_from_xdp]) { 11492 dynptr_arg_type |= DYNPTR_TYPE_XDP; 11493 } else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_clone] && 11494 (dynptr_arg_type & MEM_UNINIT)) { 11495 enum bpf_dynptr_type parent_type = meta->initialized_dynptr.type; 11496 11497 if (parent_type == BPF_DYNPTR_TYPE_INVALID) { 11498 verbose(env, "verifier internal error: no dynptr type for parent of clone\n"); 11499 return -EFAULT; 11500 } 11501 11502 dynptr_arg_type |= (unsigned int)get_dynptr_type_flag(parent_type); 11503 clone_ref_obj_id = meta->initialized_dynptr.ref_obj_id; 11504 if (dynptr_type_refcounted(parent_type) && !clone_ref_obj_id) { 11505 verbose(env, "verifier internal error: missing ref obj id for parent of clone\n"); 11506 return -EFAULT; 11507 } 11508 } 11509 11510 ret = process_dynptr_func(env, regno, insn_idx, dynptr_arg_type, clone_ref_obj_id); 11511 if (ret < 0) 11512 return ret; 11513 11514 if (!(dynptr_arg_type & MEM_UNINIT)) { 11515 int id = dynptr_id(env, reg); 11516 11517 if (id < 0) { 11518 verbose(env, "verifier internal error: failed to obtain dynptr id\n"); 11519 return id; 11520 } 11521 meta->initialized_dynptr.id = id; 11522 meta->initialized_dynptr.type = dynptr_get_type(env, reg); 11523 meta->initialized_dynptr.ref_obj_id = dynptr_ref_obj_id(env, reg); 11524 } 11525 11526 break; 11527 } 11528 case KF_ARG_PTR_TO_ITER: 11529 ret = process_iter_arg(env, regno, insn_idx, meta); 11530 if (ret < 0) 11531 return ret; 11532 break; 11533 case KF_ARG_PTR_TO_LIST_HEAD: 11534 if (reg->type != PTR_TO_MAP_VALUE && 11535 reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) { 11536 verbose(env, "arg#%d expected pointer to map value or allocated object\n", i); 11537 return -EINVAL; 11538 } 11539 if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC) && !reg->ref_obj_id) { 11540 verbose(env, "allocated object must be referenced\n"); 11541 return -EINVAL; 11542 } 11543 ret = process_kf_arg_ptr_to_list_head(env, reg, regno, meta); 11544 if (ret < 0) 11545 return ret; 11546 break; 11547 case KF_ARG_PTR_TO_RB_ROOT: 11548 if (reg->type != PTR_TO_MAP_VALUE && 11549 reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) { 11550 verbose(env, "arg#%d expected pointer to map value or allocated object\n", i); 11551 return -EINVAL; 11552 } 11553 if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC) && !reg->ref_obj_id) { 11554 verbose(env, "allocated object must be referenced\n"); 11555 return -EINVAL; 11556 } 11557 ret = process_kf_arg_ptr_to_rbtree_root(env, reg, regno, meta); 11558 if (ret < 0) 11559 return ret; 11560 break; 11561 case KF_ARG_PTR_TO_LIST_NODE: 11562 if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) { 11563 verbose(env, "arg#%d expected pointer to allocated object\n", i); 11564 return -EINVAL; 11565 } 11566 if (!reg->ref_obj_id) { 11567 verbose(env, "allocated object must be referenced\n"); 11568 return -EINVAL; 11569 } 11570 ret = process_kf_arg_ptr_to_list_node(env, reg, regno, meta); 11571 if (ret < 0) 11572 return ret; 11573 break; 11574 case KF_ARG_PTR_TO_RB_NODE: 11575 if (meta->func_id == special_kfunc_list[KF_bpf_rbtree_remove]) { 11576 if (!type_is_non_owning_ref(reg->type) || reg->ref_obj_id) { 11577 verbose(env, "rbtree_remove node input must be non-owning ref\n"); 11578 return -EINVAL; 11579 } 11580 if (in_rbtree_lock_required_cb(env)) { 11581 verbose(env, "rbtree_remove not allowed in rbtree cb\n"); 11582 return -EINVAL; 11583 } 11584 } else { 11585 if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) { 11586 verbose(env, "arg#%d expected pointer to allocated object\n", i); 11587 return -EINVAL; 11588 } 11589 if (!reg->ref_obj_id) { 11590 verbose(env, "allocated object must be referenced\n"); 11591 return -EINVAL; 11592 } 11593 } 11594 11595 ret = process_kf_arg_ptr_to_rbtree_node(env, reg, regno, meta); 11596 if (ret < 0) 11597 return ret; 11598 break; 11599 case KF_ARG_PTR_TO_BTF_ID: 11600 /* Only base_type is checked, further checks are done here */ 11601 if ((base_type(reg->type) != PTR_TO_BTF_ID || 11602 (bpf_type_has_unsafe_modifiers(reg->type) && !is_rcu_reg(reg))) && 11603 !reg2btf_ids[base_type(reg->type)]) { 11604 verbose(env, "arg#%d is %s ", i, reg_type_str(env, reg->type)); 11605 verbose(env, "expected %s or socket\n", 11606 reg_type_str(env, base_type(reg->type) | 11607 (type_flag(reg->type) & BPF_REG_TRUSTED_MODIFIERS))); 11608 return -EINVAL; 11609 } 11610 ret = process_kf_arg_ptr_to_btf_id(env, reg, ref_t, ref_tname, ref_id, meta, i); 11611 if (ret < 0) 11612 return ret; 11613 break; 11614 case KF_ARG_PTR_TO_MEM: 11615 resolve_ret = btf_resolve_size(btf, ref_t, &type_size); 11616 if (IS_ERR(resolve_ret)) { 11617 verbose(env, "arg#%d reference type('%s %s') size cannot be determined: %ld\n", 11618 i, btf_type_str(ref_t), ref_tname, PTR_ERR(resolve_ret)); 11619 return -EINVAL; 11620 } 11621 ret = check_mem_reg(env, reg, regno, type_size); 11622 if (ret < 0) 11623 return ret; 11624 break; 11625 case KF_ARG_PTR_TO_MEM_SIZE: 11626 { 11627 struct bpf_reg_state *buff_reg = ®s[regno]; 11628 const struct btf_param *buff_arg = &args[i]; 11629 struct bpf_reg_state *size_reg = ®s[regno + 1]; 11630 const struct btf_param *size_arg = &args[i + 1]; 11631 11632 if (!register_is_null(buff_reg) || !is_kfunc_arg_optional(meta->btf, buff_arg)) { 11633 ret = check_kfunc_mem_size_reg(env, size_reg, regno + 1); 11634 if (ret < 0) { 11635 verbose(env, "arg#%d arg#%d memory, len pair leads to invalid memory access\n", i, i + 1); 11636 return ret; 11637 } 11638 } 11639 11640 if (is_kfunc_arg_const_mem_size(meta->btf, size_arg, size_reg)) { 11641 if (meta->arg_constant.found) { 11642 verbose(env, "verifier internal error: only one constant argument permitted\n"); 11643 return -EFAULT; 11644 } 11645 if (!tnum_is_const(size_reg->var_off)) { 11646 verbose(env, "R%d must be a known constant\n", regno + 1); 11647 return -EINVAL; 11648 } 11649 meta->arg_constant.found = true; 11650 meta->arg_constant.value = size_reg->var_off.value; 11651 } 11652 11653 /* Skip next '__sz' or '__szk' argument */ 11654 i++; 11655 break; 11656 } 11657 case KF_ARG_PTR_TO_CALLBACK: 11658 if (reg->type != PTR_TO_FUNC) { 11659 verbose(env, "arg%d expected pointer to func\n", i); 11660 return -EINVAL; 11661 } 11662 meta->subprogno = reg->subprogno; 11663 break; 11664 case KF_ARG_PTR_TO_REFCOUNTED_KPTR: 11665 if (!type_is_ptr_alloc_obj(reg->type)) { 11666 verbose(env, "arg#%d is neither owning or non-owning ref\n", i); 11667 return -EINVAL; 11668 } 11669 if (!type_is_non_owning_ref(reg->type)) 11670 meta->arg_owning_ref = true; 11671 11672 rec = reg_btf_record(reg); 11673 if (!rec) { 11674 verbose(env, "verifier internal error: Couldn't find btf_record\n"); 11675 return -EFAULT; 11676 } 11677 11678 if (rec->refcount_off < 0) { 11679 verbose(env, "arg#%d doesn't point to a type with bpf_refcount field\n", i); 11680 return -EINVAL; 11681 } 11682 11683 meta->arg_btf = reg->btf; 11684 meta->arg_btf_id = reg->btf_id; 11685 break; 11686 } 11687 } 11688 11689 if (is_kfunc_release(meta) && !meta->release_regno) { 11690 verbose(env, "release kernel function %s expects refcounted PTR_TO_BTF_ID\n", 11691 func_name); 11692 return -EINVAL; 11693 } 11694 11695 return 0; 11696 } 11697 11698 static int fetch_kfunc_meta(struct bpf_verifier_env *env, 11699 struct bpf_insn *insn, 11700 struct bpf_kfunc_call_arg_meta *meta, 11701 const char **kfunc_name) 11702 { 11703 const struct btf_type *func, *func_proto; 11704 u32 func_id, *kfunc_flags; 11705 const char *func_name; 11706 struct btf *desc_btf; 11707 11708 if (kfunc_name) 11709 *kfunc_name = NULL; 11710 11711 if (!insn->imm) 11712 return -EINVAL; 11713 11714 desc_btf = find_kfunc_desc_btf(env, insn->off); 11715 if (IS_ERR(desc_btf)) 11716 return PTR_ERR(desc_btf); 11717 11718 func_id = insn->imm; 11719 func = btf_type_by_id(desc_btf, func_id); 11720 func_name = btf_name_by_offset(desc_btf, func->name_off); 11721 if (kfunc_name) 11722 *kfunc_name = func_name; 11723 func_proto = btf_type_by_id(desc_btf, func->type); 11724 11725 kfunc_flags = btf_kfunc_id_set_contains(desc_btf, func_id, env->prog); 11726 if (!kfunc_flags) { 11727 return -EACCES; 11728 } 11729 11730 memset(meta, 0, sizeof(*meta)); 11731 meta->btf = desc_btf; 11732 meta->func_id = func_id; 11733 meta->kfunc_flags = *kfunc_flags; 11734 meta->func_proto = func_proto; 11735 meta->func_name = func_name; 11736 11737 return 0; 11738 } 11739 11740 static int check_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn, 11741 int *insn_idx_p) 11742 { 11743 const struct btf_type *t, *ptr_type; 11744 u32 i, nargs, ptr_type_id, release_ref_obj_id; 11745 struct bpf_reg_state *regs = cur_regs(env); 11746 const char *func_name, *ptr_type_name; 11747 bool sleepable, rcu_lock, rcu_unlock; 11748 struct bpf_kfunc_call_arg_meta meta; 11749 struct bpf_insn_aux_data *insn_aux; 11750 int err, insn_idx = *insn_idx_p; 11751 const struct btf_param *args; 11752 const struct btf_type *ret_t; 11753 struct btf *desc_btf; 11754 11755 /* skip for now, but return error when we find this in fixup_kfunc_call */ 11756 if (!insn->imm) 11757 return 0; 11758 11759 err = fetch_kfunc_meta(env, insn, &meta, &func_name); 11760 if (err == -EACCES && func_name) 11761 verbose(env, "calling kernel function %s is not allowed\n", func_name); 11762 if (err) 11763 return err; 11764 desc_btf = meta.btf; 11765 insn_aux = &env->insn_aux_data[insn_idx]; 11766 11767 insn_aux->is_iter_next = is_iter_next_kfunc(&meta); 11768 11769 if (is_kfunc_destructive(&meta) && !capable(CAP_SYS_BOOT)) { 11770 verbose(env, "destructive kfunc calls require CAP_SYS_BOOT capability\n"); 11771 return -EACCES; 11772 } 11773 11774 sleepable = is_kfunc_sleepable(&meta); 11775 if (sleepable && !env->prog->aux->sleepable) { 11776 verbose(env, "program must be sleepable to call sleepable kfunc %s\n", func_name); 11777 return -EACCES; 11778 } 11779 11780 /* Check the arguments */ 11781 err = check_kfunc_args(env, &meta, insn_idx); 11782 if (err < 0) 11783 return err; 11784 11785 if (meta.func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) { 11786 err = push_callback_call(env, insn, insn_idx, meta.subprogno, 11787 set_rbtree_add_callback_state); 11788 if (err) { 11789 verbose(env, "kfunc %s#%d failed callback verification\n", 11790 func_name, meta.func_id); 11791 return err; 11792 } 11793 } 11794 11795 rcu_lock = is_kfunc_bpf_rcu_read_lock(&meta); 11796 rcu_unlock = is_kfunc_bpf_rcu_read_unlock(&meta); 11797 11798 if (env->cur_state->active_rcu_lock) { 11799 struct bpf_func_state *state; 11800 struct bpf_reg_state *reg; 11801 11802 if (in_rbtree_lock_required_cb(env) && (rcu_lock || rcu_unlock)) { 11803 verbose(env, "Calling bpf_rcu_read_{lock,unlock} in unnecessary rbtree callback\n"); 11804 return -EACCES; 11805 } 11806 11807 if (rcu_lock) { 11808 verbose(env, "nested rcu read lock (kernel function %s)\n", func_name); 11809 return -EINVAL; 11810 } else if (rcu_unlock) { 11811 bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({ 11812 if (reg->type & MEM_RCU) { 11813 reg->type &= ~(MEM_RCU | PTR_MAYBE_NULL); 11814 reg->type |= PTR_UNTRUSTED; 11815 } 11816 })); 11817 env->cur_state->active_rcu_lock = false; 11818 } else if (sleepable) { 11819 verbose(env, "kernel func %s is sleepable within rcu_read_lock region\n", func_name); 11820 return -EACCES; 11821 } 11822 } else if (rcu_lock) { 11823 env->cur_state->active_rcu_lock = true; 11824 } else if (rcu_unlock) { 11825 verbose(env, "unmatched rcu read unlock (kernel function %s)\n", func_name); 11826 return -EINVAL; 11827 } 11828 11829 /* In case of release function, we get register number of refcounted 11830 * PTR_TO_BTF_ID in bpf_kfunc_arg_meta, do the release now. 11831 */ 11832 if (meta.release_regno) { 11833 err = release_reference(env, regs[meta.release_regno].ref_obj_id); 11834 if (err) { 11835 verbose(env, "kfunc %s#%d reference has not been acquired before\n", 11836 func_name, meta.func_id); 11837 return err; 11838 } 11839 } 11840 11841 if (meta.func_id == special_kfunc_list[KF_bpf_list_push_front_impl] || 11842 meta.func_id == special_kfunc_list[KF_bpf_list_push_back_impl] || 11843 meta.func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) { 11844 release_ref_obj_id = regs[BPF_REG_2].ref_obj_id; 11845 insn_aux->insert_off = regs[BPF_REG_2].off; 11846 insn_aux->kptr_struct_meta = btf_find_struct_meta(meta.arg_btf, meta.arg_btf_id); 11847 err = ref_convert_owning_non_owning(env, release_ref_obj_id); 11848 if (err) { 11849 verbose(env, "kfunc %s#%d conversion of owning ref to non-owning failed\n", 11850 func_name, meta.func_id); 11851 return err; 11852 } 11853 11854 err = release_reference(env, release_ref_obj_id); 11855 if (err) { 11856 verbose(env, "kfunc %s#%d reference has not been acquired before\n", 11857 func_name, meta.func_id); 11858 return err; 11859 } 11860 } 11861 11862 for (i = 0; i < CALLER_SAVED_REGS; i++) 11863 mark_reg_not_init(env, regs, caller_saved[i]); 11864 11865 /* Check return type */ 11866 t = btf_type_skip_modifiers(desc_btf, meta.func_proto->type, NULL); 11867 11868 if (is_kfunc_acquire(&meta) && !btf_type_is_struct_ptr(meta.btf, t)) { 11869 /* Only exception is bpf_obj_new_impl */ 11870 if (meta.btf != btf_vmlinux || 11871 (meta.func_id != special_kfunc_list[KF_bpf_obj_new_impl] && 11872 meta.func_id != special_kfunc_list[KF_bpf_refcount_acquire_impl])) { 11873 verbose(env, "acquire kernel function does not return PTR_TO_BTF_ID\n"); 11874 return -EINVAL; 11875 } 11876 } 11877 11878 if (btf_type_is_scalar(t)) { 11879 mark_reg_unknown(env, regs, BPF_REG_0); 11880 mark_btf_func_reg_size(env, BPF_REG_0, t->size); 11881 } else if (btf_type_is_ptr(t)) { 11882 ptr_type = btf_type_skip_modifiers(desc_btf, t->type, &ptr_type_id); 11883 11884 if (meta.btf == btf_vmlinux && btf_id_set_contains(&special_kfunc_set, meta.func_id)) { 11885 if (meta.func_id == special_kfunc_list[KF_bpf_obj_new_impl]) { 11886 struct btf *ret_btf; 11887 u32 ret_btf_id; 11888 11889 if (unlikely(!bpf_global_ma_set)) 11890 return -ENOMEM; 11891 11892 if (((u64)(u32)meta.arg_constant.value) != meta.arg_constant.value) { 11893 verbose(env, "local type ID argument must be in range [0, U32_MAX]\n"); 11894 return -EINVAL; 11895 } 11896 11897 ret_btf = env->prog->aux->btf; 11898 ret_btf_id = meta.arg_constant.value; 11899 11900 /* This may be NULL due to user not supplying a BTF */ 11901 if (!ret_btf) { 11902 verbose(env, "bpf_obj_new requires prog BTF\n"); 11903 return -EINVAL; 11904 } 11905 11906 ret_t = btf_type_by_id(ret_btf, ret_btf_id); 11907 if (!ret_t || !__btf_type_is_struct(ret_t)) { 11908 verbose(env, "bpf_obj_new type ID argument must be of a struct\n"); 11909 return -EINVAL; 11910 } 11911 11912 mark_reg_known_zero(env, regs, BPF_REG_0); 11913 regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC; 11914 regs[BPF_REG_0].btf = ret_btf; 11915 regs[BPF_REG_0].btf_id = ret_btf_id; 11916 11917 insn_aux->obj_new_size = ret_t->size; 11918 insn_aux->kptr_struct_meta = 11919 btf_find_struct_meta(ret_btf, ret_btf_id); 11920 } else if (meta.func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl]) { 11921 mark_reg_known_zero(env, regs, BPF_REG_0); 11922 regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC; 11923 regs[BPF_REG_0].btf = meta.arg_btf; 11924 regs[BPF_REG_0].btf_id = meta.arg_btf_id; 11925 11926 insn_aux->kptr_struct_meta = 11927 btf_find_struct_meta(meta.arg_btf, 11928 meta.arg_btf_id); 11929 } else if (meta.func_id == special_kfunc_list[KF_bpf_list_pop_front] || 11930 meta.func_id == special_kfunc_list[KF_bpf_list_pop_back]) { 11931 struct btf_field *field = meta.arg_list_head.field; 11932 11933 mark_reg_graph_node(regs, BPF_REG_0, &field->graph_root); 11934 } else if (meta.func_id == special_kfunc_list[KF_bpf_rbtree_remove] || 11935 meta.func_id == special_kfunc_list[KF_bpf_rbtree_first]) { 11936 struct btf_field *field = meta.arg_rbtree_root.field; 11937 11938 mark_reg_graph_node(regs, BPF_REG_0, &field->graph_root); 11939 } else if (meta.func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx]) { 11940 mark_reg_known_zero(env, regs, BPF_REG_0); 11941 regs[BPF_REG_0].type = PTR_TO_BTF_ID | PTR_TRUSTED; 11942 regs[BPF_REG_0].btf = desc_btf; 11943 regs[BPF_REG_0].btf_id = meta.ret_btf_id; 11944 } else if (meta.func_id == special_kfunc_list[KF_bpf_rdonly_cast]) { 11945 ret_t = btf_type_by_id(desc_btf, meta.arg_constant.value); 11946 if (!ret_t || !btf_type_is_struct(ret_t)) { 11947 verbose(env, 11948 "kfunc bpf_rdonly_cast type ID argument must be of a struct\n"); 11949 return -EINVAL; 11950 } 11951 11952 mark_reg_known_zero(env, regs, BPF_REG_0); 11953 regs[BPF_REG_0].type = PTR_TO_BTF_ID | PTR_UNTRUSTED; 11954 regs[BPF_REG_0].btf = desc_btf; 11955 regs[BPF_REG_0].btf_id = meta.arg_constant.value; 11956 } else if (meta.func_id == special_kfunc_list[KF_bpf_dynptr_slice] || 11957 meta.func_id == special_kfunc_list[KF_bpf_dynptr_slice_rdwr]) { 11958 enum bpf_type_flag type_flag = get_dynptr_type_flag(meta.initialized_dynptr.type); 11959 11960 mark_reg_known_zero(env, regs, BPF_REG_0); 11961 11962 if (!meta.arg_constant.found) { 11963 verbose(env, "verifier internal error: bpf_dynptr_slice(_rdwr) no constant size\n"); 11964 return -EFAULT; 11965 } 11966 11967 regs[BPF_REG_0].mem_size = meta.arg_constant.value; 11968 11969 /* PTR_MAYBE_NULL will be added when is_kfunc_ret_null is checked */ 11970 regs[BPF_REG_0].type = PTR_TO_MEM | type_flag; 11971 11972 if (meta.func_id == special_kfunc_list[KF_bpf_dynptr_slice]) { 11973 regs[BPF_REG_0].type |= MEM_RDONLY; 11974 } else { 11975 /* this will set env->seen_direct_write to true */ 11976 if (!may_access_direct_pkt_data(env, NULL, BPF_WRITE)) { 11977 verbose(env, "the prog does not allow writes to packet data\n"); 11978 return -EINVAL; 11979 } 11980 } 11981 11982 if (!meta.initialized_dynptr.id) { 11983 verbose(env, "verifier internal error: no dynptr id\n"); 11984 return -EFAULT; 11985 } 11986 regs[BPF_REG_0].dynptr_id = meta.initialized_dynptr.id; 11987 11988 /* we don't need to set BPF_REG_0's ref obj id 11989 * because packet slices are not refcounted (see 11990 * dynptr_type_refcounted) 11991 */ 11992 } else { 11993 verbose(env, "kernel function %s unhandled dynamic return type\n", 11994 meta.func_name); 11995 return -EFAULT; 11996 } 11997 } else if (!__btf_type_is_struct(ptr_type)) { 11998 if (!meta.r0_size) { 11999 __u32 sz; 12000 12001 if (!IS_ERR(btf_resolve_size(desc_btf, ptr_type, &sz))) { 12002 meta.r0_size = sz; 12003 meta.r0_rdonly = true; 12004 } 12005 } 12006 if (!meta.r0_size) { 12007 ptr_type_name = btf_name_by_offset(desc_btf, 12008 ptr_type->name_off); 12009 verbose(env, 12010 "kernel function %s returns pointer type %s %s is not supported\n", 12011 func_name, 12012 btf_type_str(ptr_type), 12013 ptr_type_name); 12014 return -EINVAL; 12015 } 12016 12017 mark_reg_known_zero(env, regs, BPF_REG_0); 12018 regs[BPF_REG_0].type = PTR_TO_MEM; 12019 regs[BPF_REG_0].mem_size = meta.r0_size; 12020 12021 if (meta.r0_rdonly) 12022 regs[BPF_REG_0].type |= MEM_RDONLY; 12023 12024 /* Ensures we don't access the memory after a release_reference() */ 12025 if (meta.ref_obj_id) 12026 regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id; 12027 } else { 12028 mark_reg_known_zero(env, regs, BPF_REG_0); 12029 regs[BPF_REG_0].btf = desc_btf; 12030 regs[BPF_REG_0].type = PTR_TO_BTF_ID; 12031 regs[BPF_REG_0].btf_id = ptr_type_id; 12032 12033 if (is_iter_next_kfunc(&meta)) { 12034 struct bpf_reg_state *cur_iter; 12035 12036 cur_iter = get_iter_from_state(env->cur_state, &meta); 12037 12038 if (cur_iter->type & MEM_RCU) /* KF_RCU_PROTECTED */ 12039 regs[BPF_REG_0].type |= MEM_RCU; 12040 else 12041 regs[BPF_REG_0].type |= PTR_TRUSTED; 12042 } 12043 } 12044 12045 if (is_kfunc_ret_null(&meta)) { 12046 regs[BPF_REG_0].type |= PTR_MAYBE_NULL; 12047 /* For mark_ptr_or_null_reg, see 93c230e3f5bd6 */ 12048 regs[BPF_REG_0].id = ++env->id_gen; 12049 } 12050 mark_btf_func_reg_size(env, BPF_REG_0, sizeof(void *)); 12051 if (is_kfunc_acquire(&meta)) { 12052 int id = acquire_reference_state(env, insn_idx); 12053 12054 if (id < 0) 12055 return id; 12056 if (is_kfunc_ret_null(&meta)) 12057 regs[BPF_REG_0].id = id; 12058 regs[BPF_REG_0].ref_obj_id = id; 12059 } else if (meta.func_id == special_kfunc_list[KF_bpf_rbtree_first]) { 12060 ref_set_non_owning(env, ®s[BPF_REG_0]); 12061 } 12062 12063 if (reg_may_point_to_spin_lock(®s[BPF_REG_0]) && !regs[BPF_REG_0].id) 12064 regs[BPF_REG_0].id = ++env->id_gen; 12065 } else if (btf_type_is_void(t)) { 12066 if (meta.btf == btf_vmlinux && btf_id_set_contains(&special_kfunc_set, meta.func_id)) { 12067 if (meta.func_id == special_kfunc_list[KF_bpf_obj_drop_impl]) { 12068 insn_aux->kptr_struct_meta = 12069 btf_find_struct_meta(meta.arg_btf, 12070 meta.arg_btf_id); 12071 } 12072 } 12073 } 12074 12075 nargs = btf_type_vlen(meta.func_proto); 12076 args = (const struct btf_param *)(meta.func_proto + 1); 12077 for (i = 0; i < nargs; i++) { 12078 u32 regno = i + 1; 12079 12080 t = btf_type_skip_modifiers(desc_btf, args[i].type, NULL); 12081 if (btf_type_is_ptr(t)) 12082 mark_btf_func_reg_size(env, regno, sizeof(void *)); 12083 else 12084 /* scalar. ensured by btf_check_kfunc_arg_match() */ 12085 mark_btf_func_reg_size(env, regno, t->size); 12086 } 12087 12088 if (is_iter_next_kfunc(&meta)) { 12089 err = process_iter_next_call(env, insn_idx, &meta); 12090 if (err) 12091 return err; 12092 } 12093 12094 return 0; 12095 } 12096 12097 static bool signed_add_overflows(s64 a, s64 b) 12098 { 12099 /* Do the add in u64, where overflow is well-defined */ 12100 s64 res = (s64)((u64)a + (u64)b); 12101 12102 if (b < 0) 12103 return res > a; 12104 return res < a; 12105 } 12106 12107 static bool signed_add32_overflows(s32 a, s32 b) 12108 { 12109 /* Do the add in u32, where overflow is well-defined */ 12110 s32 res = (s32)((u32)a + (u32)b); 12111 12112 if (b < 0) 12113 return res > a; 12114 return res < a; 12115 } 12116 12117 static bool signed_sub_overflows(s64 a, s64 b) 12118 { 12119 /* Do the sub in u64, where overflow is well-defined */ 12120 s64 res = (s64)((u64)a - (u64)b); 12121 12122 if (b < 0) 12123 return res < a; 12124 return res > a; 12125 } 12126 12127 static bool signed_sub32_overflows(s32 a, s32 b) 12128 { 12129 /* Do the sub in u32, where overflow is well-defined */ 12130 s32 res = (s32)((u32)a - (u32)b); 12131 12132 if (b < 0) 12133 return res < a; 12134 return res > a; 12135 } 12136 12137 static bool check_reg_sane_offset(struct bpf_verifier_env *env, 12138 const struct bpf_reg_state *reg, 12139 enum bpf_reg_type type) 12140 { 12141 bool known = tnum_is_const(reg->var_off); 12142 s64 val = reg->var_off.value; 12143 s64 smin = reg->smin_value; 12144 12145 if (known && (val >= BPF_MAX_VAR_OFF || val <= -BPF_MAX_VAR_OFF)) { 12146 verbose(env, "math between %s pointer and %lld is not allowed\n", 12147 reg_type_str(env, type), val); 12148 return false; 12149 } 12150 12151 if (reg->off >= BPF_MAX_VAR_OFF || reg->off <= -BPF_MAX_VAR_OFF) { 12152 verbose(env, "%s pointer offset %d is not allowed\n", 12153 reg_type_str(env, type), reg->off); 12154 return false; 12155 } 12156 12157 if (smin == S64_MIN) { 12158 verbose(env, "math between %s pointer and register with unbounded min value is not allowed\n", 12159 reg_type_str(env, type)); 12160 return false; 12161 } 12162 12163 if (smin >= BPF_MAX_VAR_OFF || smin <= -BPF_MAX_VAR_OFF) { 12164 verbose(env, "value %lld makes %s pointer be out of bounds\n", 12165 smin, reg_type_str(env, type)); 12166 return false; 12167 } 12168 12169 return true; 12170 } 12171 12172 enum { 12173 REASON_BOUNDS = -1, 12174 REASON_TYPE = -2, 12175 REASON_PATHS = -3, 12176 REASON_LIMIT = -4, 12177 REASON_STACK = -5, 12178 }; 12179 12180 static int retrieve_ptr_limit(const struct bpf_reg_state *ptr_reg, 12181 u32 *alu_limit, bool mask_to_left) 12182 { 12183 u32 max = 0, ptr_limit = 0; 12184 12185 switch (ptr_reg->type) { 12186 case PTR_TO_STACK: 12187 /* Offset 0 is out-of-bounds, but acceptable start for the 12188 * left direction, see BPF_REG_FP. Also, unknown scalar 12189 * offset where we would need to deal with min/max bounds is 12190 * currently prohibited for unprivileged. 12191 */ 12192 max = MAX_BPF_STACK + mask_to_left; 12193 ptr_limit = -(ptr_reg->var_off.value + ptr_reg->off); 12194 break; 12195 case PTR_TO_MAP_VALUE: 12196 max = ptr_reg->map_ptr->value_size; 12197 ptr_limit = (mask_to_left ? 12198 ptr_reg->smin_value : 12199 ptr_reg->umax_value) + ptr_reg->off; 12200 break; 12201 default: 12202 return REASON_TYPE; 12203 } 12204 12205 if (ptr_limit >= max) 12206 return REASON_LIMIT; 12207 *alu_limit = ptr_limit; 12208 return 0; 12209 } 12210 12211 static bool can_skip_alu_sanitation(const struct bpf_verifier_env *env, 12212 const struct bpf_insn *insn) 12213 { 12214 return env->bypass_spec_v1 || BPF_SRC(insn->code) == BPF_K; 12215 } 12216 12217 static int update_alu_sanitation_state(struct bpf_insn_aux_data *aux, 12218 u32 alu_state, u32 alu_limit) 12219 { 12220 /* If we arrived here from different branches with different 12221 * state or limits to sanitize, then this won't work. 12222 */ 12223 if (aux->alu_state && 12224 (aux->alu_state != alu_state || 12225 aux->alu_limit != alu_limit)) 12226 return REASON_PATHS; 12227 12228 /* Corresponding fixup done in do_misc_fixups(). */ 12229 aux->alu_state = alu_state; 12230 aux->alu_limit = alu_limit; 12231 return 0; 12232 } 12233 12234 static int sanitize_val_alu(struct bpf_verifier_env *env, 12235 struct bpf_insn *insn) 12236 { 12237 struct bpf_insn_aux_data *aux = cur_aux(env); 12238 12239 if (can_skip_alu_sanitation(env, insn)) 12240 return 0; 12241 12242 return update_alu_sanitation_state(aux, BPF_ALU_NON_POINTER, 0); 12243 } 12244 12245 static bool sanitize_needed(u8 opcode) 12246 { 12247 return opcode == BPF_ADD || opcode == BPF_SUB; 12248 } 12249 12250 struct bpf_sanitize_info { 12251 struct bpf_insn_aux_data aux; 12252 bool mask_to_left; 12253 }; 12254 12255 static struct bpf_verifier_state * 12256 sanitize_speculative_path(struct bpf_verifier_env *env, 12257 const struct bpf_insn *insn, 12258 u32 next_idx, u32 curr_idx) 12259 { 12260 struct bpf_verifier_state *branch; 12261 struct bpf_reg_state *regs; 12262 12263 branch = push_stack(env, next_idx, curr_idx, true); 12264 if (branch && insn) { 12265 regs = branch->frame[branch->curframe]->regs; 12266 if (BPF_SRC(insn->code) == BPF_K) { 12267 mark_reg_unknown(env, regs, insn->dst_reg); 12268 } else if (BPF_SRC(insn->code) == BPF_X) { 12269 mark_reg_unknown(env, regs, insn->dst_reg); 12270 mark_reg_unknown(env, regs, insn->src_reg); 12271 } 12272 } 12273 return branch; 12274 } 12275 12276 static int sanitize_ptr_alu(struct bpf_verifier_env *env, 12277 struct bpf_insn *insn, 12278 const struct bpf_reg_state *ptr_reg, 12279 const struct bpf_reg_state *off_reg, 12280 struct bpf_reg_state *dst_reg, 12281 struct bpf_sanitize_info *info, 12282 const bool commit_window) 12283 { 12284 struct bpf_insn_aux_data *aux = commit_window ? cur_aux(env) : &info->aux; 12285 struct bpf_verifier_state *vstate = env->cur_state; 12286 bool off_is_imm = tnum_is_const(off_reg->var_off); 12287 bool off_is_neg = off_reg->smin_value < 0; 12288 bool ptr_is_dst_reg = ptr_reg == dst_reg; 12289 u8 opcode = BPF_OP(insn->code); 12290 u32 alu_state, alu_limit; 12291 struct bpf_reg_state tmp; 12292 bool ret; 12293 int err; 12294 12295 if (can_skip_alu_sanitation(env, insn)) 12296 return 0; 12297 12298 /* We already marked aux for masking from non-speculative 12299 * paths, thus we got here in the first place. We only care 12300 * to explore bad access from here. 12301 */ 12302 if (vstate->speculative) 12303 goto do_sim; 12304 12305 if (!commit_window) { 12306 if (!tnum_is_const(off_reg->var_off) && 12307 (off_reg->smin_value < 0) != (off_reg->smax_value < 0)) 12308 return REASON_BOUNDS; 12309 12310 info->mask_to_left = (opcode == BPF_ADD && off_is_neg) || 12311 (opcode == BPF_SUB && !off_is_neg); 12312 } 12313 12314 err = retrieve_ptr_limit(ptr_reg, &alu_limit, info->mask_to_left); 12315 if (err < 0) 12316 return err; 12317 12318 if (commit_window) { 12319 /* In commit phase we narrow the masking window based on 12320 * the observed pointer move after the simulated operation. 12321 */ 12322 alu_state = info->aux.alu_state; 12323 alu_limit = abs(info->aux.alu_limit - alu_limit); 12324 } else { 12325 alu_state = off_is_neg ? BPF_ALU_NEG_VALUE : 0; 12326 alu_state |= off_is_imm ? BPF_ALU_IMMEDIATE : 0; 12327 alu_state |= ptr_is_dst_reg ? 12328 BPF_ALU_SANITIZE_SRC : BPF_ALU_SANITIZE_DST; 12329 12330 /* Limit pruning on unknown scalars to enable deep search for 12331 * potential masking differences from other program paths. 12332 */ 12333 if (!off_is_imm) 12334 env->explore_alu_limits = true; 12335 } 12336 12337 err = update_alu_sanitation_state(aux, alu_state, alu_limit); 12338 if (err < 0) 12339 return err; 12340 do_sim: 12341 /* If we're in commit phase, we're done here given we already 12342 * pushed the truncated dst_reg into the speculative verification 12343 * stack. 12344 * 12345 * Also, when register is a known constant, we rewrite register-based 12346 * operation to immediate-based, and thus do not need masking (and as 12347 * a consequence, do not need to simulate the zero-truncation either). 12348 */ 12349 if (commit_window || off_is_imm) 12350 return 0; 12351 12352 /* Simulate and find potential out-of-bounds access under 12353 * speculative execution from truncation as a result of 12354 * masking when off was not within expected range. If off 12355 * sits in dst, then we temporarily need to move ptr there 12356 * to simulate dst (== 0) +/-= ptr. Needed, for example, 12357 * for cases where we use K-based arithmetic in one direction 12358 * and truncated reg-based in the other in order to explore 12359 * bad access. 12360 */ 12361 if (!ptr_is_dst_reg) { 12362 tmp = *dst_reg; 12363 copy_register_state(dst_reg, ptr_reg); 12364 } 12365 ret = sanitize_speculative_path(env, NULL, env->insn_idx + 1, 12366 env->insn_idx); 12367 if (!ptr_is_dst_reg && ret) 12368 *dst_reg = tmp; 12369 return !ret ? REASON_STACK : 0; 12370 } 12371 12372 static void sanitize_mark_insn_seen(struct bpf_verifier_env *env) 12373 { 12374 struct bpf_verifier_state *vstate = env->cur_state; 12375 12376 /* If we simulate paths under speculation, we don't update the 12377 * insn as 'seen' such that when we verify unreachable paths in 12378 * the non-speculative domain, sanitize_dead_code() can still 12379 * rewrite/sanitize them. 12380 */ 12381 if (!vstate->speculative) 12382 env->insn_aux_data[env->insn_idx].seen = env->pass_cnt; 12383 } 12384 12385 static int sanitize_err(struct bpf_verifier_env *env, 12386 const struct bpf_insn *insn, int reason, 12387 const struct bpf_reg_state *off_reg, 12388 const struct bpf_reg_state *dst_reg) 12389 { 12390 static const char *err = "pointer arithmetic with it prohibited for !root"; 12391 const char *op = BPF_OP(insn->code) == BPF_ADD ? "add" : "sub"; 12392 u32 dst = insn->dst_reg, src = insn->src_reg; 12393 12394 switch (reason) { 12395 case REASON_BOUNDS: 12396 verbose(env, "R%d has unknown scalar with mixed signed bounds, %s\n", 12397 off_reg == dst_reg ? dst : src, err); 12398 break; 12399 case REASON_TYPE: 12400 verbose(env, "R%d has pointer with unsupported alu operation, %s\n", 12401 off_reg == dst_reg ? src : dst, err); 12402 break; 12403 case REASON_PATHS: 12404 verbose(env, "R%d tried to %s from different maps, paths or scalars, %s\n", 12405 dst, op, err); 12406 break; 12407 case REASON_LIMIT: 12408 verbose(env, "R%d tried to %s beyond pointer bounds, %s\n", 12409 dst, op, err); 12410 break; 12411 case REASON_STACK: 12412 verbose(env, "R%d could not be pushed for speculative verification, %s\n", 12413 dst, err); 12414 break; 12415 default: 12416 verbose(env, "verifier internal error: unknown reason (%d)\n", 12417 reason); 12418 break; 12419 } 12420 12421 return -EACCES; 12422 } 12423 12424 /* check that stack access falls within stack limits and that 'reg' doesn't 12425 * have a variable offset. 12426 * 12427 * Variable offset is prohibited for unprivileged mode for simplicity since it 12428 * requires corresponding support in Spectre masking for stack ALU. See also 12429 * retrieve_ptr_limit(). 12430 * 12431 * 12432 * 'off' includes 'reg->off'. 12433 */ 12434 static int check_stack_access_for_ptr_arithmetic( 12435 struct bpf_verifier_env *env, 12436 int regno, 12437 const struct bpf_reg_state *reg, 12438 int off) 12439 { 12440 if (!tnum_is_const(reg->var_off)) { 12441 char tn_buf[48]; 12442 12443 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 12444 verbose(env, "R%d variable stack access prohibited for !root, var_off=%s off=%d\n", 12445 regno, tn_buf, off); 12446 return -EACCES; 12447 } 12448 12449 if (off >= 0 || off < -MAX_BPF_STACK) { 12450 verbose(env, "R%d stack pointer arithmetic goes out of range, " 12451 "prohibited for !root; off=%d\n", regno, off); 12452 return -EACCES; 12453 } 12454 12455 return 0; 12456 } 12457 12458 static int sanitize_check_bounds(struct bpf_verifier_env *env, 12459 const struct bpf_insn *insn, 12460 const struct bpf_reg_state *dst_reg) 12461 { 12462 u32 dst = insn->dst_reg; 12463 12464 /* For unprivileged we require that resulting offset must be in bounds 12465 * in order to be able to sanitize access later on. 12466 */ 12467 if (env->bypass_spec_v1) 12468 return 0; 12469 12470 switch (dst_reg->type) { 12471 case PTR_TO_STACK: 12472 if (check_stack_access_for_ptr_arithmetic(env, dst, dst_reg, 12473 dst_reg->off + dst_reg->var_off.value)) 12474 return -EACCES; 12475 break; 12476 case PTR_TO_MAP_VALUE: 12477 if (check_map_access(env, dst, dst_reg->off, 1, false, ACCESS_HELPER)) { 12478 verbose(env, "R%d pointer arithmetic of map value goes out of range, " 12479 "prohibited for !root\n", dst); 12480 return -EACCES; 12481 } 12482 break; 12483 default: 12484 break; 12485 } 12486 12487 return 0; 12488 } 12489 12490 /* Handles arithmetic on a pointer and a scalar: computes new min/max and var_off. 12491 * Caller should also handle BPF_MOV case separately. 12492 * If we return -EACCES, caller may want to try again treating pointer as a 12493 * scalar. So we only emit a diagnostic if !env->allow_ptr_leaks. 12494 */ 12495 static int adjust_ptr_min_max_vals(struct bpf_verifier_env *env, 12496 struct bpf_insn *insn, 12497 const struct bpf_reg_state *ptr_reg, 12498 const struct bpf_reg_state *off_reg) 12499 { 12500 struct bpf_verifier_state *vstate = env->cur_state; 12501 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 12502 struct bpf_reg_state *regs = state->regs, *dst_reg; 12503 bool known = tnum_is_const(off_reg->var_off); 12504 s64 smin_val = off_reg->smin_value, smax_val = off_reg->smax_value, 12505 smin_ptr = ptr_reg->smin_value, smax_ptr = ptr_reg->smax_value; 12506 u64 umin_val = off_reg->umin_value, umax_val = off_reg->umax_value, 12507 umin_ptr = ptr_reg->umin_value, umax_ptr = ptr_reg->umax_value; 12508 struct bpf_sanitize_info info = {}; 12509 u8 opcode = BPF_OP(insn->code); 12510 u32 dst = insn->dst_reg; 12511 int ret; 12512 12513 dst_reg = ®s[dst]; 12514 12515 if ((known && (smin_val != smax_val || umin_val != umax_val)) || 12516 smin_val > smax_val || umin_val > umax_val) { 12517 /* Taint dst register if offset had invalid bounds derived from 12518 * e.g. dead branches. 12519 */ 12520 __mark_reg_unknown(env, dst_reg); 12521 return 0; 12522 } 12523 12524 if (BPF_CLASS(insn->code) != BPF_ALU64) { 12525 /* 32-bit ALU ops on pointers produce (meaningless) scalars */ 12526 if (opcode == BPF_SUB && env->allow_ptr_leaks) { 12527 __mark_reg_unknown(env, dst_reg); 12528 return 0; 12529 } 12530 12531 verbose(env, 12532 "R%d 32-bit pointer arithmetic prohibited\n", 12533 dst); 12534 return -EACCES; 12535 } 12536 12537 if (ptr_reg->type & PTR_MAYBE_NULL) { 12538 verbose(env, "R%d pointer arithmetic on %s prohibited, null-check it first\n", 12539 dst, reg_type_str(env, ptr_reg->type)); 12540 return -EACCES; 12541 } 12542 12543 switch (base_type(ptr_reg->type)) { 12544 case PTR_TO_FLOW_KEYS: 12545 if (known) 12546 break; 12547 fallthrough; 12548 case CONST_PTR_TO_MAP: 12549 /* smin_val represents the known value */ 12550 if (known && smin_val == 0 && opcode == BPF_ADD) 12551 break; 12552 fallthrough; 12553 case PTR_TO_PACKET_END: 12554 case PTR_TO_SOCKET: 12555 case PTR_TO_SOCK_COMMON: 12556 case PTR_TO_TCP_SOCK: 12557 case PTR_TO_XDP_SOCK: 12558 verbose(env, "R%d pointer arithmetic on %s prohibited\n", 12559 dst, reg_type_str(env, ptr_reg->type)); 12560 return -EACCES; 12561 default: 12562 break; 12563 } 12564 12565 /* In case of 'scalar += pointer', dst_reg inherits pointer type and id. 12566 * The id may be overwritten later if we create a new variable offset. 12567 */ 12568 dst_reg->type = ptr_reg->type; 12569 dst_reg->id = ptr_reg->id; 12570 12571 if (!check_reg_sane_offset(env, off_reg, ptr_reg->type) || 12572 !check_reg_sane_offset(env, ptr_reg, ptr_reg->type)) 12573 return -EINVAL; 12574 12575 /* pointer types do not carry 32-bit bounds at the moment. */ 12576 __mark_reg32_unbounded(dst_reg); 12577 12578 if (sanitize_needed(opcode)) { 12579 ret = sanitize_ptr_alu(env, insn, ptr_reg, off_reg, dst_reg, 12580 &info, false); 12581 if (ret < 0) 12582 return sanitize_err(env, insn, ret, off_reg, dst_reg); 12583 } 12584 12585 switch (opcode) { 12586 case BPF_ADD: 12587 /* We can take a fixed offset as long as it doesn't overflow 12588 * the s32 'off' field 12589 */ 12590 if (known && (ptr_reg->off + smin_val == 12591 (s64)(s32)(ptr_reg->off + smin_val))) { 12592 /* pointer += K. Accumulate it into fixed offset */ 12593 dst_reg->smin_value = smin_ptr; 12594 dst_reg->smax_value = smax_ptr; 12595 dst_reg->umin_value = umin_ptr; 12596 dst_reg->umax_value = umax_ptr; 12597 dst_reg->var_off = ptr_reg->var_off; 12598 dst_reg->off = ptr_reg->off + smin_val; 12599 dst_reg->raw = ptr_reg->raw; 12600 break; 12601 } 12602 /* A new variable offset is created. Note that off_reg->off 12603 * == 0, since it's a scalar. 12604 * dst_reg gets the pointer type and since some positive 12605 * integer value was added to the pointer, give it a new 'id' 12606 * if it's a PTR_TO_PACKET. 12607 * this creates a new 'base' pointer, off_reg (variable) gets 12608 * added into the variable offset, and we copy the fixed offset 12609 * from ptr_reg. 12610 */ 12611 if (signed_add_overflows(smin_ptr, smin_val) || 12612 signed_add_overflows(smax_ptr, smax_val)) { 12613 dst_reg->smin_value = S64_MIN; 12614 dst_reg->smax_value = S64_MAX; 12615 } else { 12616 dst_reg->smin_value = smin_ptr + smin_val; 12617 dst_reg->smax_value = smax_ptr + smax_val; 12618 } 12619 if (umin_ptr + umin_val < umin_ptr || 12620 umax_ptr + umax_val < umax_ptr) { 12621 dst_reg->umin_value = 0; 12622 dst_reg->umax_value = U64_MAX; 12623 } else { 12624 dst_reg->umin_value = umin_ptr + umin_val; 12625 dst_reg->umax_value = umax_ptr + umax_val; 12626 } 12627 dst_reg->var_off = tnum_add(ptr_reg->var_off, off_reg->var_off); 12628 dst_reg->off = ptr_reg->off; 12629 dst_reg->raw = ptr_reg->raw; 12630 if (reg_is_pkt_pointer(ptr_reg)) { 12631 dst_reg->id = ++env->id_gen; 12632 /* something was added to pkt_ptr, set range to zero */ 12633 memset(&dst_reg->raw, 0, sizeof(dst_reg->raw)); 12634 } 12635 break; 12636 case BPF_SUB: 12637 if (dst_reg == off_reg) { 12638 /* scalar -= pointer. Creates an unknown scalar */ 12639 verbose(env, "R%d tried to subtract pointer from scalar\n", 12640 dst); 12641 return -EACCES; 12642 } 12643 /* We don't allow subtraction from FP, because (according to 12644 * test_verifier.c test "invalid fp arithmetic", JITs might not 12645 * be able to deal with it. 12646 */ 12647 if (ptr_reg->type == PTR_TO_STACK) { 12648 verbose(env, "R%d subtraction from stack pointer prohibited\n", 12649 dst); 12650 return -EACCES; 12651 } 12652 if (known && (ptr_reg->off - smin_val == 12653 (s64)(s32)(ptr_reg->off - smin_val))) { 12654 /* pointer -= K. Subtract it from fixed offset */ 12655 dst_reg->smin_value = smin_ptr; 12656 dst_reg->smax_value = smax_ptr; 12657 dst_reg->umin_value = umin_ptr; 12658 dst_reg->umax_value = umax_ptr; 12659 dst_reg->var_off = ptr_reg->var_off; 12660 dst_reg->id = ptr_reg->id; 12661 dst_reg->off = ptr_reg->off - smin_val; 12662 dst_reg->raw = ptr_reg->raw; 12663 break; 12664 } 12665 /* A new variable offset is created. If the subtrahend is known 12666 * nonnegative, then any reg->range we had before is still good. 12667 */ 12668 if (signed_sub_overflows(smin_ptr, smax_val) || 12669 signed_sub_overflows(smax_ptr, smin_val)) { 12670 /* Overflow possible, we know nothing */ 12671 dst_reg->smin_value = S64_MIN; 12672 dst_reg->smax_value = S64_MAX; 12673 } else { 12674 dst_reg->smin_value = smin_ptr - smax_val; 12675 dst_reg->smax_value = smax_ptr - smin_val; 12676 } 12677 if (umin_ptr < umax_val) { 12678 /* Overflow possible, we know nothing */ 12679 dst_reg->umin_value = 0; 12680 dst_reg->umax_value = U64_MAX; 12681 } else { 12682 /* Cannot overflow (as long as bounds are consistent) */ 12683 dst_reg->umin_value = umin_ptr - umax_val; 12684 dst_reg->umax_value = umax_ptr - umin_val; 12685 } 12686 dst_reg->var_off = tnum_sub(ptr_reg->var_off, off_reg->var_off); 12687 dst_reg->off = ptr_reg->off; 12688 dst_reg->raw = ptr_reg->raw; 12689 if (reg_is_pkt_pointer(ptr_reg)) { 12690 dst_reg->id = ++env->id_gen; 12691 /* something was added to pkt_ptr, set range to zero */ 12692 if (smin_val < 0) 12693 memset(&dst_reg->raw, 0, sizeof(dst_reg->raw)); 12694 } 12695 break; 12696 case BPF_AND: 12697 case BPF_OR: 12698 case BPF_XOR: 12699 /* bitwise ops on pointers are troublesome, prohibit. */ 12700 verbose(env, "R%d bitwise operator %s on pointer prohibited\n", 12701 dst, bpf_alu_string[opcode >> 4]); 12702 return -EACCES; 12703 default: 12704 /* other operators (e.g. MUL,LSH) produce non-pointer results */ 12705 verbose(env, "R%d pointer arithmetic with %s operator prohibited\n", 12706 dst, bpf_alu_string[opcode >> 4]); 12707 return -EACCES; 12708 } 12709 12710 if (!check_reg_sane_offset(env, dst_reg, ptr_reg->type)) 12711 return -EINVAL; 12712 reg_bounds_sync(dst_reg); 12713 if (sanitize_check_bounds(env, insn, dst_reg) < 0) 12714 return -EACCES; 12715 if (sanitize_needed(opcode)) { 12716 ret = sanitize_ptr_alu(env, insn, dst_reg, off_reg, dst_reg, 12717 &info, true); 12718 if (ret < 0) 12719 return sanitize_err(env, insn, ret, off_reg, dst_reg); 12720 } 12721 12722 return 0; 12723 } 12724 12725 static void scalar32_min_max_add(struct bpf_reg_state *dst_reg, 12726 struct bpf_reg_state *src_reg) 12727 { 12728 s32 smin_val = src_reg->s32_min_value; 12729 s32 smax_val = src_reg->s32_max_value; 12730 u32 umin_val = src_reg->u32_min_value; 12731 u32 umax_val = src_reg->u32_max_value; 12732 12733 if (signed_add32_overflows(dst_reg->s32_min_value, smin_val) || 12734 signed_add32_overflows(dst_reg->s32_max_value, smax_val)) { 12735 dst_reg->s32_min_value = S32_MIN; 12736 dst_reg->s32_max_value = S32_MAX; 12737 } else { 12738 dst_reg->s32_min_value += smin_val; 12739 dst_reg->s32_max_value += smax_val; 12740 } 12741 if (dst_reg->u32_min_value + umin_val < umin_val || 12742 dst_reg->u32_max_value + umax_val < umax_val) { 12743 dst_reg->u32_min_value = 0; 12744 dst_reg->u32_max_value = U32_MAX; 12745 } else { 12746 dst_reg->u32_min_value += umin_val; 12747 dst_reg->u32_max_value += umax_val; 12748 } 12749 } 12750 12751 static void scalar_min_max_add(struct bpf_reg_state *dst_reg, 12752 struct bpf_reg_state *src_reg) 12753 { 12754 s64 smin_val = src_reg->smin_value; 12755 s64 smax_val = src_reg->smax_value; 12756 u64 umin_val = src_reg->umin_value; 12757 u64 umax_val = src_reg->umax_value; 12758 12759 if (signed_add_overflows(dst_reg->smin_value, smin_val) || 12760 signed_add_overflows(dst_reg->smax_value, smax_val)) { 12761 dst_reg->smin_value = S64_MIN; 12762 dst_reg->smax_value = S64_MAX; 12763 } else { 12764 dst_reg->smin_value += smin_val; 12765 dst_reg->smax_value += smax_val; 12766 } 12767 if (dst_reg->umin_value + umin_val < umin_val || 12768 dst_reg->umax_value + umax_val < umax_val) { 12769 dst_reg->umin_value = 0; 12770 dst_reg->umax_value = U64_MAX; 12771 } else { 12772 dst_reg->umin_value += umin_val; 12773 dst_reg->umax_value += umax_val; 12774 } 12775 } 12776 12777 static void scalar32_min_max_sub(struct bpf_reg_state *dst_reg, 12778 struct bpf_reg_state *src_reg) 12779 { 12780 s32 smin_val = src_reg->s32_min_value; 12781 s32 smax_val = src_reg->s32_max_value; 12782 u32 umin_val = src_reg->u32_min_value; 12783 u32 umax_val = src_reg->u32_max_value; 12784 12785 if (signed_sub32_overflows(dst_reg->s32_min_value, smax_val) || 12786 signed_sub32_overflows(dst_reg->s32_max_value, smin_val)) { 12787 /* Overflow possible, we know nothing */ 12788 dst_reg->s32_min_value = S32_MIN; 12789 dst_reg->s32_max_value = S32_MAX; 12790 } else { 12791 dst_reg->s32_min_value -= smax_val; 12792 dst_reg->s32_max_value -= smin_val; 12793 } 12794 if (dst_reg->u32_min_value < umax_val) { 12795 /* Overflow possible, we know nothing */ 12796 dst_reg->u32_min_value = 0; 12797 dst_reg->u32_max_value = U32_MAX; 12798 } else { 12799 /* Cannot overflow (as long as bounds are consistent) */ 12800 dst_reg->u32_min_value -= umax_val; 12801 dst_reg->u32_max_value -= umin_val; 12802 } 12803 } 12804 12805 static void scalar_min_max_sub(struct bpf_reg_state *dst_reg, 12806 struct bpf_reg_state *src_reg) 12807 { 12808 s64 smin_val = src_reg->smin_value; 12809 s64 smax_val = src_reg->smax_value; 12810 u64 umin_val = src_reg->umin_value; 12811 u64 umax_val = src_reg->umax_value; 12812 12813 if (signed_sub_overflows(dst_reg->smin_value, smax_val) || 12814 signed_sub_overflows(dst_reg->smax_value, smin_val)) { 12815 /* Overflow possible, we know nothing */ 12816 dst_reg->smin_value = S64_MIN; 12817 dst_reg->smax_value = S64_MAX; 12818 } else { 12819 dst_reg->smin_value -= smax_val; 12820 dst_reg->smax_value -= smin_val; 12821 } 12822 if (dst_reg->umin_value < umax_val) { 12823 /* Overflow possible, we know nothing */ 12824 dst_reg->umin_value = 0; 12825 dst_reg->umax_value = U64_MAX; 12826 } else { 12827 /* Cannot overflow (as long as bounds are consistent) */ 12828 dst_reg->umin_value -= umax_val; 12829 dst_reg->umax_value -= umin_val; 12830 } 12831 } 12832 12833 static void scalar32_min_max_mul(struct bpf_reg_state *dst_reg, 12834 struct bpf_reg_state *src_reg) 12835 { 12836 s32 smin_val = src_reg->s32_min_value; 12837 u32 umin_val = src_reg->u32_min_value; 12838 u32 umax_val = src_reg->u32_max_value; 12839 12840 if (smin_val < 0 || dst_reg->s32_min_value < 0) { 12841 /* Ain't nobody got time to multiply that sign */ 12842 __mark_reg32_unbounded(dst_reg); 12843 return; 12844 } 12845 /* Both values are positive, so we can work with unsigned and 12846 * copy the result to signed (unless it exceeds S32_MAX). 12847 */ 12848 if (umax_val > U16_MAX || dst_reg->u32_max_value > U16_MAX) { 12849 /* Potential overflow, we know nothing */ 12850 __mark_reg32_unbounded(dst_reg); 12851 return; 12852 } 12853 dst_reg->u32_min_value *= umin_val; 12854 dst_reg->u32_max_value *= umax_val; 12855 if (dst_reg->u32_max_value > S32_MAX) { 12856 /* Overflow possible, we know nothing */ 12857 dst_reg->s32_min_value = S32_MIN; 12858 dst_reg->s32_max_value = S32_MAX; 12859 } else { 12860 dst_reg->s32_min_value = dst_reg->u32_min_value; 12861 dst_reg->s32_max_value = dst_reg->u32_max_value; 12862 } 12863 } 12864 12865 static void scalar_min_max_mul(struct bpf_reg_state *dst_reg, 12866 struct bpf_reg_state *src_reg) 12867 { 12868 s64 smin_val = src_reg->smin_value; 12869 u64 umin_val = src_reg->umin_value; 12870 u64 umax_val = src_reg->umax_value; 12871 12872 if (smin_val < 0 || dst_reg->smin_value < 0) { 12873 /* Ain't nobody got time to multiply that sign */ 12874 __mark_reg64_unbounded(dst_reg); 12875 return; 12876 } 12877 /* Both values are positive, so we can work with unsigned and 12878 * copy the result to signed (unless it exceeds S64_MAX). 12879 */ 12880 if (umax_val > U32_MAX || dst_reg->umax_value > U32_MAX) { 12881 /* Potential overflow, we know nothing */ 12882 __mark_reg64_unbounded(dst_reg); 12883 return; 12884 } 12885 dst_reg->umin_value *= umin_val; 12886 dst_reg->umax_value *= umax_val; 12887 if (dst_reg->umax_value > S64_MAX) { 12888 /* Overflow possible, we know nothing */ 12889 dst_reg->smin_value = S64_MIN; 12890 dst_reg->smax_value = S64_MAX; 12891 } else { 12892 dst_reg->smin_value = dst_reg->umin_value; 12893 dst_reg->smax_value = dst_reg->umax_value; 12894 } 12895 } 12896 12897 static void scalar32_min_max_and(struct bpf_reg_state *dst_reg, 12898 struct bpf_reg_state *src_reg) 12899 { 12900 bool src_known = tnum_subreg_is_const(src_reg->var_off); 12901 bool dst_known = tnum_subreg_is_const(dst_reg->var_off); 12902 struct tnum var32_off = tnum_subreg(dst_reg->var_off); 12903 s32 smin_val = src_reg->s32_min_value; 12904 u32 umax_val = src_reg->u32_max_value; 12905 12906 if (src_known && dst_known) { 12907 __mark_reg32_known(dst_reg, var32_off.value); 12908 return; 12909 } 12910 12911 /* We get our minimum from the var_off, since that's inherently 12912 * bitwise. Our maximum is the minimum of the operands' maxima. 12913 */ 12914 dst_reg->u32_min_value = var32_off.value; 12915 dst_reg->u32_max_value = min(dst_reg->u32_max_value, umax_val); 12916 if (dst_reg->s32_min_value < 0 || smin_val < 0) { 12917 /* Lose signed bounds when ANDing negative numbers, 12918 * ain't nobody got time for that. 12919 */ 12920 dst_reg->s32_min_value = S32_MIN; 12921 dst_reg->s32_max_value = S32_MAX; 12922 } else { 12923 /* ANDing two positives gives a positive, so safe to 12924 * cast result into s64. 12925 */ 12926 dst_reg->s32_min_value = dst_reg->u32_min_value; 12927 dst_reg->s32_max_value = dst_reg->u32_max_value; 12928 } 12929 } 12930 12931 static void scalar_min_max_and(struct bpf_reg_state *dst_reg, 12932 struct bpf_reg_state *src_reg) 12933 { 12934 bool src_known = tnum_is_const(src_reg->var_off); 12935 bool dst_known = tnum_is_const(dst_reg->var_off); 12936 s64 smin_val = src_reg->smin_value; 12937 u64 umax_val = src_reg->umax_value; 12938 12939 if (src_known && dst_known) { 12940 __mark_reg_known(dst_reg, dst_reg->var_off.value); 12941 return; 12942 } 12943 12944 /* We get our minimum from the var_off, since that's inherently 12945 * bitwise. Our maximum is the minimum of the operands' maxima. 12946 */ 12947 dst_reg->umin_value = dst_reg->var_off.value; 12948 dst_reg->umax_value = min(dst_reg->umax_value, umax_val); 12949 if (dst_reg->smin_value < 0 || smin_val < 0) { 12950 /* Lose signed bounds when ANDing negative numbers, 12951 * ain't nobody got time for that. 12952 */ 12953 dst_reg->smin_value = S64_MIN; 12954 dst_reg->smax_value = S64_MAX; 12955 } else { 12956 /* ANDing two positives gives a positive, so safe to 12957 * cast result into s64. 12958 */ 12959 dst_reg->smin_value = dst_reg->umin_value; 12960 dst_reg->smax_value = dst_reg->umax_value; 12961 } 12962 /* We may learn something more from the var_off */ 12963 __update_reg_bounds(dst_reg); 12964 } 12965 12966 static void scalar32_min_max_or(struct bpf_reg_state *dst_reg, 12967 struct bpf_reg_state *src_reg) 12968 { 12969 bool src_known = tnum_subreg_is_const(src_reg->var_off); 12970 bool dst_known = tnum_subreg_is_const(dst_reg->var_off); 12971 struct tnum var32_off = tnum_subreg(dst_reg->var_off); 12972 s32 smin_val = src_reg->s32_min_value; 12973 u32 umin_val = src_reg->u32_min_value; 12974 12975 if (src_known && dst_known) { 12976 __mark_reg32_known(dst_reg, var32_off.value); 12977 return; 12978 } 12979 12980 /* We get our maximum from the var_off, and our minimum is the 12981 * maximum of the operands' minima 12982 */ 12983 dst_reg->u32_min_value = max(dst_reg->u32_min_value, umin_val); 12984 dst_reg->u32_max_value = var32_off.value | var32_off.mask; 12985 if (dst_reg->s32_min_value < 0 || smin_val < 0) { 12986 /* Lose signed bounds when ORing negative numbers, 12987 * ain't nobody got time for that. 12988 */ 12989 dst_reg->s32_min_value = S32_MIN; 12990 dst_reg->s32_max_value = S32_MAX; 12991 } else { 12992 /* ORing two positives gives a positive, so safe to 12993 * cast result into s64. 12994 */ 12995 dst_reg->s32_min_value = dst_reg->u32_min_value; 12996 dst_reg->s32_max_value = dst_reg->u32_max_value; 12997 } 12998 } 12999 13000 static void scalar_min_max_or(struct bpf_reg_state *dst_reg, 13001 struct bpf_reg_state *src_reg) 13002 { 13003 bool src_known = tnum_is_const(src_reg->var_off); 13004 bool dst_known = tnum_is_const(dst_reg->var_off); 13005 s64 smin_val = src_reg->smin_value; 13006 u64 umin_val = src_reg->umin_value; 13007 13008 if (src_known && dst_known) { 13009 __mark_reg_known(dst_reg, dst_reg->var_off.value); 13010 return; 13011 } 13012 13013 /* We get our maximum from the var_off, and our minimum is the 13014 * maximum of the operands' minima 13015 */ 13016 dst_reg->umin_value = max(dst_reg->umin_value, umin_val); 13017 dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask; 13018 if (dst_reg->smin_value < 0 || smin_val < 0) { 13019 /* Lose signed bounds when ORing negative numbers, 13020 * ain't nobody got time for that. 13021 */ 13022 dst_reg->smin_value = S64_MIN; 13023 dst_reg->smax_value = S64_MAX; 13024 } else { 13025 /* ORing two positives gives a positive, so safe to 13026 * cast result into s64. 13027 */ 13028 dst_reg->smin_value = dst_reg->umin_value; 13029 dst_reg->smax_value = dst_reg->umax_value; 13030 } 13031 /* We may learn something more from the var_off */ 13032 __update_reg_bounds(dst_reg); 13033 } 13034 13035 static void scalar32_min_max_xor(struct bpf_reg_state *dst_reg, 13036 struct bpf_reg_state *src_reg) 13037 { 13038 bool src_known = tnum_subreg_is_const(src_reg->var_off); 13039 bool dst_known = tnum_subreg_is_const(dst_reg->var_off); 13040 struct tnum var32_off = tnum_subreg(dst_reg->var_off); 13041 s32 smin_val = src_reg->s32_min_value; 13042 13043 if (src_known && dst_known) { 13044 __mark_reg32_known(dst_reg, var32_off.value); 13045 return; 13046 } 13047 13048 /* We get both minimum and maximum from the var32_off. */ 13049 dst_reg->u32_min_value = var32_off.value; 13050 dst_reg->u32_max_value = var32_off.value | var32_off.mask; 13051 13052 if (dst_reg->s32_min_value >= 0 && smin_val >= 0) { 13053 /* XORing two positive sign numbers gives a positive, 13054 * so safe to cast u32 result into s32. 13055 */ 13056 dst_reg->s32_min_value = dst_reg->u32_min_value; 13057 dst_reg->s32_max_value = dst_reg->u32_max_value; 13058 } else { 13059 dst_reg->s32_min_value = S32_MIN; 13060 dst_reg->s32_max_value = S32_MAX; 13061 } 13062 } 13063 13064 static void scalar_min_max_xor(struct bpf_reg_state *dst_reg, 13065 struct bpf_reg_state *src_reg) 13066 { 13067 bool src_known = tnum_is_const(src_reg->var_off); 13068 bool dst_known = tnum_is_const(dst_reg->var_off); 13069 s64 smin_val = src_reg->smin_value; 13070 13071 if (src_known && dst_known) { 13072 /* dst_reg->var_off.value has been updated earlier */ 13073 __mark_reg_known(dst_reg, dst_reg->var_off.value); 13074 return; 13075 } 13076 13077 /* We get both minimum and maximum from the var_off. */ 13078 dst_reg->umin_value = dst_reg->var_off.value; 13079 dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask; 13080 13081 if (dst_reg->smin_value >= 0 && smin_val >= 0) { 13082 /* XORing two positive sign numbers gives a positive, 13083 * so safe to cast u64 result into s64. 13084 */ 13085 dst_reg->smin_value = dst_reg->umin_value; 13086 dst_reg->smax_value = dst_reg->umax_value; 13087 } else { 13088 dst_reg->smin_value = S64_MIN; 13089 dst_reg->smax_value = S64_MAX; 13090 } 13091 13092 __update_reg_bounds(dst_reg); 13093 } 13094 13095 static void __scalar32_min_max_lsh(struct bpf_reg_state *dst_reg, 13096 u64 umin_val, u64 umax_val) 13097 { 13098 /* We lose all sign bit information (except what we can pick 13099 * up from var_off) 13100 */ 13101 dst_reg->s32_min_value = S32_MIN; 13102 dst_reg->s32_max_value = S32_MAX; 13103 /* If we might shift our top bit out, then we know nothing */ 13104 if (umax_val > 31 || dst_reg->u32_max_value > 1ULL << (31 - umax_val)) { 13105 dst_reg->u32_min_value = 0; 13106 dst_reg->u32_max_value = U32_MAX; 13107 } else { 13108 dst_reg->u32_min_value <<= umin_val; 13109 dst_reg->u32_max_value <<= umax_val; 13110 } 13111 } 13112 13113 static void scalar32_min_max_lsh(struct bpf_reg_state *dst_reg, 13114 struct bpf_reg_state *src_reg) 13115 { 13116 u32 umax_val = src_reg->u32_max_value; 13117 u32 umin_val = src_reg->u32_min_value; 13118 /* u32 alu operation will zext upper bits */ 13119 struct tnum subreg = tnum_subreg(dst_reg->var_off); 13120 13121 __scalar32_min_max_lsh(dst_reg, umin_val, umax_val); 13122 dst_reg->var_off = tnum_subreg(tnum_lshift(subreg, umin_val)); 13123 /* Not required but being careful mark reg64 bounds as unknown so 13124 * that we are forced to pick them up from tnum and zext later and 13125 * if some path skips this step we are still safe. 13126 */ 13127 __mark_reg64_unbounded(dst_reg); 13128 __update_reg32_bounds(dst_reg); 13129 } 13130 13131 static void __scalar64_min_max_lsh(struct bpf_reg_state *dst_reg, 13132 u64 umin_val, u64 umax_val) 13133 { 13134 /* Special case <<32 because it is a common compiler pattern to sign 13135 * extend subreg by doing <<32 s>>32. In this case if 32bit bounds are 13136 * positive we know this shift will also be positive so we can track 13137 * bounds correctly. Otherwise we lose all sign bit information except 13138 * what we can pick up from var_off. Perhaps we can generalize this 13139 * later to shifts of any length. 13140 */ 13141 if (umin_val == 32 && umax_val == 32 && dst_reg->s32_max_value >= 0) 13142 dst_reg->smax_value = (s64)dst_reg->s32_max_value << 32; 13143 else 13144 dst_reg->smax_value = S64_MAX; 13145 13146 if (umin_val == 32 && umax_val == 32 && dst_reg->s32_min_value >= 0) 13147 dst_reg->smin_value = (s64)dst_reg->s32_min_value << 32; 13148 else 13149 dst_reg->smin_value = S64_MIN; 13150 13151 /* If we might shift our top bit out, then we know nothing */ 13152 if (dst_reg->umax_value > 1ULL << (63 - umax_val)) { 13153 dst_reg->umin_value = 0; 13154 dst_reg->umax_value = U64_MAX; 13155 } else { 13156 dst_reg->umin_value <<= umin_val; 13157 dst_reg->umax_value <<= umax_val; 13158 } 13159 } 13160 13161 static void scalar_min_max_lsh(struct bpf_reg_state *dst_reg, 13162 struct bpf_reg_state *src_reg) 13163 { 13164 u64 umax_val = src_reg->umax_value; 13165 u64 umin_val = src_reg->umin_value; 13166 13167 /* scalar64 calc uses 32bit unshifted bounds so must be called first */ 13168 __scalar64_min_max_lsh(dst_reg, umin_val, umax_val); 13169 __scalar32_min_max_lsh(dst_reg, umin_val, umax_val); 13170 13171 dst_reg->var_off = tnum_lshift(dst_reg->var_off, umin_val); 13172 /* We may learn something more from the var_off */ 13173 __update_reg_bounds(dst_reg); 13174 } 13175 13176 static void scalar32_min_max_rsh(struct bpf_reg_state *dst_reg, 13177 struct bpf_reg_state *src_reg) 13178 { 13179 struct tnum subreg = tnum_subreg(dst_reg->var_off); 13180 u32 umax_val = src_reg->u32_max_value; 13181 u32 umin_val = src_reg->u32_min_value; 13182 13183 /* BPF_RSH is an unsigned shift. If the value in dst_reg might 13184 * be negative, then either: 13185 * 1) src_reg might be zero, so the sign bit of the result is 13186 * unknown, so we lose our signed bounds 13187 * 2) it's known negative, thus the unsigned bounds capture the 13188 * signed bounds 13189 * 3) the signed bounds cross zero, so they tell us nothing 13190 * about the result 13191 * If the value in dst_reg is known nonnegative, then again the 13192 * unsigned bounds capture the signed bounds. 13193 * Thus, in all cases it suffices to blow away our signed bounds 13194 * and rely on inferring new ones from the unsigned bounds and 13195 * var_off of the result. 13196 */ 13197 dst_reg->s32_min_value = S32_MIN; 13198 dst_reg->s32_max_value = S32_MAX; 13199 13200 dst_reg->var_off = tnum_rshift(subreg, umin_val); 13201 dst_reg->u32_min_value >>= umax_val; 13202 dst_reg->u32_max_value >>= umin_val; 13203 13204 __mark_reg64_unbounded(dst_reg); 13205 __update_reg32_bounds(dst_reg); 13206 } 13207 13208 static void scalar_min_max_rsh(struct bpf_reg_state *dst_reg, 13209 struct bpf_reg_state *src_reg) 13210 { 13211 u64 umax_val = src_reg->umax_value; 13212 u64 umin_val = src_reg->umin_value; 13213 13214 /* BPF_RSH is an unsigned shift. If the value in dst_reg might 13215 * be negative, then either: 13216 * 1) src_reg might be zero, so the sign bit of the result is 13217 * unknown, so we lose our signed bounds 13218 * 2) it's known negative, thus the unsigned bounds capture the 13219 * signed bounds 13220 * 3) the signed bounds cross zero, so they tell us nothing 13221 * about the result 13222 * If the value in dst_reg is known nonnegative, then again the 13223 * unsigned bounds capture the signed bounds. 13224 * Thus, in all cases it suffices to blow away our signed bounds 13225 * and rely on inferring new ones from the unsigned bounds and 13226 * var_off of the result. 13227 */ 13228 dst_reg->smin_value = S64_MIN; 13229 dst_reg->smax_value = S64_MAX; 13230 dst_reg->var_off = tnum_rshift(dst_reg->var_off, umin_val); 13231 dst_reg->umin_value >>= umax_val; 13232 dst_reg->umax_value >>= umin_val; 13233 13234 /* Its not easy to operate on alu32 bounds here because it depends 13235 * on bits being shifted in. Take easy way out and mark unbounded 13236 * so we can recalculate later from tnum. 13237 */ 13238 __mark_reg32_unbounded(dst_reg); 13239 __update_reg_bounds(dst_reg); 13240 } 13241 13242 static void scalar32_min_max_arsh(struct bpf_reg_state *dst_reg, 13243 struct bpf_reg_state *src_reg) 13244 { 13245 u64 umin_val = src_reg->u32_min_value; 13246 13247 /* Upon reaching here, src_known is true and 13248 * umax_val is equal to umin_val. 13249 */ 13250 dst_reg->s32_min_value = (u32)(((s32)dst_reg->s32_min_value) >> umin_val); 13251 dst_reg->s32_max_value = (u32)(((s32)dst_reg->s32_max_value) >> umin_val); 13252 13253 dst_reg->var_off = tnum_arshift(tnum_subreg(dst_reg->var_off), umin_val, 32); 13254 13255 /* blow away the dst_reg umin_value/umax_value and rely on 13256 * dst_reg var_off to refine the result. 13257 */ 13258 dst_reg->u32_min_value = 0; 13259 dst_reg->u32_max_value = U32_MAX; 13260 13261 __mark_reg64_unbounded(dst_reg); 13262 __update_reg32_bounds(dst_reg); 13263 } 13264 13265 static void scalar_min_max_arsh(struct bpf_reg_state *dst_reg, 13266 struct bpf_reg_state *src_reg) 13267 { 13268 u64 umin_val = src_reg->umin_value; 13269 13270 /* Upon reaching here, src_known is true and umax_val is equal 13271 * to umin_val. 13272 */ 13273 dst_reg->smin_value >>= umin_val; 13274 dst_reg->smax_value >>= umin_val; 13275 13276 dst_reg->var_off = tnum_arshift(dst_reg->var_off, umin_val, 64); 13277 13278 /* blow away the dst_reg umin_value/umax_value and rely on 13279 * dst_reg var_off to refine the result. 13280 */ 13281 dst_reg->umin_value = 0; 13282 dst_reg->umax_value = U64_MAX; 13283 13284 /* Its not easy to operate on alu32 bounds here because it depends 13285 * on bits being shifted in from upper 32-bits. Take easy way out 13286 * and mark unbounded so we can recalculate later from tnum. 13287 */ 13288 __mark_reg32_unbounded(dst_reg); 13289 __update_reg_bounds(dst_reg); 13290 } 13291 13292 /* WARNING: This function does calculations on 64-bit values, but the actual 13293 * execution may occur on 32-bit values. Therefore, things like bitshifts 13294 * need extra checks in the 32-bit case. 13295 */ 13296 static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env, 13297 struct bpf_insn *insn, 13298 struct bpf_reg_state *dst_reg, 13299 struct bpf_reg_state src_reg) 13300 { 13301 struct bpf_reg_state *regs = cur_regs(env); 13302 u8 opcode = BPF_OP(insn->code); 13303 bool src_known; 13304 s64 smin_val, smax_val; 13305 u64 umin_val, umax_val; 13306 s32 s32_min_val, s32_max_val; 13307 u32 u32_min_val, u32_max_val; 13308 u64 insn_bitness = (BPF_CLASS(insn->code) == BPF_ALU64) ? 64 : 32; 13309 bool alu32 = (BPF_CLASS(insn->code) != BPF_ALU64); 13310 int ret; 13311 13312 smin_val = src_reg.smin_value; 13313 smax_val = src_reg.smax_value; 13314 umin_val = src_reg.umin_value; 13315 umax_val = src_reg.umax_value; 13316 13317 s32_min_val = src_reg.s32_min_value; 13318 s32_max_val = src_reg.s32_max_value; 13319 u32_min_val = src_reg.u32_min_value; 13320 u32_max_val = src_reg.u32_max_value; 13321 13322 if (alu32) { 13323 src_known = tnum_subreg_is_const(src_reg.var_off); 13324 if ((src_known && 13325 (s32_min_val != s32_max_val || u32_min_val != u32_max_val)) || 13326 s32_min_val > s32_max_val || u32_min_val > u32_max_val) { 13327 /* Taint dst register if offset had invalid bounds 13328 * derived from e.g. dead branches. 13329 */ 13330 __mark_reg_unknown(env, dst_reg); 13331 return 0; 13332 } 13333 } else { 13334 src_known = tnum_is_const(src_reg.var_off); 13335 if ((src_known && 13336 (smin_val != smax_val || umin_val != umax_val)) || 13337 smin_val > smax_val || umin_val > umax_val) { 13338 /* Taint dst register if offset had invalid bounds 13339 * derived from e.g. dead branches. 13340 */ 13341 __mark_reg_unknown(env, dst_reg); 13342 return 0; 13343 } 13344 } 13345 13346 if (!src_known && 13347 opcode != BPF_ADD && opcode != BPF_SUB && opcode != BPF_AND) { 13348 __mark_reg_unknown(env, dst_reg); 13349 return 0; 13350 } 13351 13352 if (sanitize_needed(opcode)) { 13353 ret = sanitize_val_alu(env, insn); 13354 if (ret < 0) 13355 return sanitize_err(env, insn, ret, NULL, NULL); 13356 } 13357 13358 /* Calculate sign/unsigned bounds and tnum for alu32 and alu64 bit ops. 13359 * There are two classes of instructions: The first class we track both 13360 * alu32 and alu64 sign/unsigned bounds independently this provides the 13361 * greatest amount of precision when alu operations are mixed with jmp32 13362 * operations. These operations are BPF_ADD, BPF_SUB, BPF_MUL, BPF_ADD, 13363 * and BPF_OR. This is possible because these ops have fairly easy to 13364 * understand and calculate behavior in both 32-bit and 64-bit alu ops. 13365 * See alu32 verifier tests for examples. The second class of 13366 * operations, BPF_LSH, BPF_RSH, and BPF_ARSH, however are not so easy 13367 * with regards to tracking sign/unsigned bounds because the bits may 13368 * cross subreg boundaries in the alu64 case. When this happens we mark 13369 * the reg unbounded in the subreg bound space and use the resulting 13370 * tnum to calculate an approximation of the sign/unsigned bounds. 13371 */ 13372 switch (opcode) { 13373 case BPF_ADD: 13374 scalar32_min_max_add(dst_reg, &src_reg); 13375 scalar_min_max_add(dst_reg, &src_reg); 13376 dst_reg->var_off = tnum_add(dst_reg->var_off, src_reg.var_off); 13377 break; 13378 case BPF_SUB: 13379 scalar32_min_max_sub(dst_reg, &src_reg); 13380 scalar_min_max_sub(dst_reg, &src_reg); 13381 dst_reg->var_off = tnum_sub(dst_reg->var_off, src_reg.var_off); 13382 break; 13383 case BPF_MUL: 13384 dst_reg->var_off = tnum_mul(dst_reg->var_off, src_reg.var_off); 13385 scalar32_min_max_mul(dst_reg, &src_reg); 13386 scalar_min_max_mul(dst_reg, &src_reg); 13387 break; 13388 case BPF_AND: 13389 dst_reg->var_off = tnum_and(dst_reg->var_off, src_reg.var_off); 13390 scalar32_min_max_and(dst_reg, &src_reg); 13391 scalar_min_max_and(dst_reg, &src_reg); 13392 break; 13393 case BPF_OR: 13394 dst_reg->var_off = tnum_or(dst_reg->var_off, src_reg.var_off); 13395 scalar32_min_max_or(dst_reg, &src_reg); 13396 scalar_min_max_or(dst_reg, &src_reg); 13397 break; 13398 case BPF_XOR: 13399 dst_reg->var_off = tnum_xor(dst_reg->var_off, src_reg.var_off); 13400 scalar32_min_max_xor(dst_reg, &src_reg); 13401 scalar_min_max_xor(dst_reg, &src_reg); 13402 break; 13403 case BPF_LSH: 13404 if (umax_val >= insn_bitness) { 13405 /* Shifts greater than 31 or 63 are undefined. 13406 * This includes shifts by a negative number. 13407 */ 13408 mark_reg_unknown(env, regs, insn->dst_reg); 13409 break; 13410 } 13411 if (alu32) 13412 scalar32_min_max_lsh(dst_reg, &src_reg); 13413 else 13414 scalar_min_max_lsh(dst_reg, &src_reg); 13415 break; 13416 case BPF_RSH: 13417 if (umax_val >= insn_bitness) { 13418 /* Shifts greater than 31 or 63 are undefined. 13419 * This includes shifts by a negative number. 13420 */ 13421 mark_reg_unknown(env, regs, insn->dst_reg); 13422 break; 13423 } 13424 if (alu32) 13425 scalar32_min_max_rsh(dst_reg, &src_reg); 13426 else 13427 scalar_min_max_rsh(dst_reg, &src_reg); 13428 break; 13429 case BPF_ARSH: 13430 if (umax_val >= insn_bitness) { 13431 /* Shifts greater than 31 or 63 are undefined. 13432 * This includes shifts by a negative number. 13433 */ 13434 mark_reg_unknown(env, regs, insn->dst_reg); 13435 break; 13436 } 13437 if (alu32) 13438 scalar32_min_max_arsh(dst_reg, &src_reg); 13439 else 13440 scalar_min_max_arsh(dst_reg, &src_reg); 13441 break; 13442 default: 13443 mark_reg_unknown(env, regs, insn->dst_reg); 13444 break; 13445 } 13446 13447 /* ALU32 ops are zero extended into 64bit register */ 13448 if (alu32) 13449 zext_32_to_64(dst_reg); 13450 reg_bounds_sync(dst_reg); 13451 return 0; 13452 } 13453 13454 /* Handles ALU ops other than BPF_END, BPF_NEG and BPF_MOV: computes new min/max 13455 * and var_off. 13456 */ 13457 static int adjust_reg_min_max_vals(struct bpf_verifier_env *env, 13458 struct bpf_insn *insn) 13459 { 13460 struct bpf_verifier_state *vstate = env->cur_state; 13461 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 13462 struct bpf_reg_state *regs = state->regs, *dst_reg, *src_reg; 13463 struct bpf_reg_state *ptr_reg = NULL, off_reg = {0}; 13464 u8 opcode = BPF_OP(insn->code); 13465 int err; 13466 13467 dst_reg = ®s[insn->dst_reg]; 13468 src_reg = NULL; 13469 if (dst_reg->type != SCALAR_VALUE) 13470 ptr_reg = dst_reg; 13471 else 13472 /* Make sure ID is cleared otherwise dst_reg min/max could be 13473 * incorrectly propagated into other registers by find_equal_scalars() 13474 */ 13475 dst_reg->id = 0; 13476 if (BPF_SRC(insn->code) == BPF_X) { 13477 src_reg = ®s[insn->src_reg]; 13478 if (src_reg->type != SCALAR_VALUE) { 13479 if (dst_reg->type != SCALAR_VALUE) { 13480 /* Combining two pointers by any ALU op yields 13481 * an arbitrary scalar. Disallow all math except 13482 * pointer subtraction 13483 */ 13484 if (opcode == BPF_SUB && env->allow_ptr_leaks) { 13485 mark_reg_unknown(env, regs, insn->dst_reg); 13486 return 0; 13487 } 13488 verbose(env, "R%d pointer %s pointer prohibited\n", 13489 insn->dst_reg, 13490 bpf_alu_string[opcode >> 4]); 13491 return -EACCES; 13492 } else { 13493 /* scalar += pointer 13494 * This is legal, but we have to reverse our 13495 * src/dest handling in computing the range 13496 */ 13497 err = mark_chain_precision(env, insn->dst_reg); 13498 if (err) 13499 return err; 13500 return adjust_ptr_min_max_vals(env, insn, 13501 src_reg, dst_reg); 13502 } 13503 } else if (ptr_reg) { 13504 /* pointer += scalar */ 13505 err = mark_chain_precision(env, insn->src_reg); 13506 if (err) 13507 return err; 13508 return adjust_ptr_min_max_vals(env, insn, 13509 dst_reg, src_reg); 13510 } else if (dst_reg->precise) { 13511 /* if dst_reg is precise, src_reg should be precise as well */ 13512 err = mark_chain_precision(env, insn->src_reg); 13513 if (err) 13514 return err; 13515 } 13516 } else { 13517 /* Pretend the src is a reg with a known value, since we only 13518 * need to be able to read from this state. 13519 */ 13520 off_reg.type = SCALAR_VALUE; 13521 __mark_reg_known(&off_reg, insn->imm); 13522 src_reg = &off_reg; 13523 if (ptr_reg) /* pointer += K */ 13524 return adjust_ptr_min_max_vals(env, insn, 13525 ptr_reg, src_reg); 13526 } 13527 13528 /* Got here implies adding two SCALAR_VALUEs */ 13529 if (WARN_ON_ONCE(ptr_reg)) { 13530 print_verifier_state(env, state, true); 13531 verbose(env, "verifier internal error: unexpected ptr_reg\n"); 13532 return -EINVAL; 13533 } 13534 if (WARN_ON(!src_reg)) { 13535 print_verifier_state(env, state, true); 13536 verbose(env, "verifier internal error: no src_reg\n"); 13537 return -EINVAL; 13538 } 13539 return adjust_scalar_min_max_vals(env, insn, dst_reg, *src_reg); 13540 } 13541 13542 /* check validity of 32-bit and 64-bit arithmetic operations */ 13543 static int check_alu_op(struct bpf_verifier_env *env, struct bpf_insn *insn) 13544 { 13545 struct bpf_reg_state *regs = cur_regs(env); 13546 u8 opcode = BPF_OP(insn->code); 13547 int err; 13548 13549 if (opcode == BPF_END || opcode == BPF_NEG) { 13550 if (opcode == BPF_NEG) { 13551 if (BPF_SRC(insn->code) != BPF_K || 13552 insn->src_reg != BPF_REG_0 || 13553 insn->off != 0 || insn->imm != 0) { 13554 verbose(env, "BPF_NEG uses reserved fields\n"); 13555 return -EINVAL; 13556 } 13557 } else { 13558 if (insn->src_reg != BPF_REG_0 || insn->off != 0 || 13559 (insn->imm != 16 && insn->imm != 32 && insn->imm != 64) || 13560 (BPF_CLASS(insn->code) == BPF_ALU64 && 13561 BPF_SRC(insn->code) != BPF_TO_LE)) { 13562 verbose(env, "BPF_END uses reserved fields\n"); 13563 return -EINVAL; 13564 } 13565 } 13566 13567 /* check src operand */ 13568 err = check_reg_arg(env, insn->dst_reg, SRC_OP); 13569 if (err) 13570 return err; 13571 13572 if (is_pointer_value(env, insn->dst_reg)) { 13573 verbose(env, "R%d pointer arithmetic prohibited\n", 13574 insn->dst_reg); 13575 return -EACCES; 13576 } 13577 13578 /* check dest operand */ 13579 err = check_reg_arg(env, insn->dst_reg, DST_OP); 13580 if (err) 13581 return err; 13582 13583 } else if (opcode == BPF_MOV) { 13584 13585 if (BPF_SRC(insn->code) == BPF_X) { 13586 if (insn->imm != 0) { 13587 verbose(env, "BPF_MOV uses reserved fields\n"); 13588 return -EINVAL; 13589 } 13590 13591 if (BPF_CLASS(insn->code) == BPF_ALU) { 13592 if (insn->off != 0 && insn->off != 8 && insn->off != 16) { 13593 verbose(env, "BPF_MOV uses reserved fields\n"); 13594 return -EINVAL; 13595 } 13596 } else { 13597 if (insn->off != 0 && insn->off != 8 && insn->off != 16 && 13598 insn->off != 32) { 13599 verbose(env, "BPF_MOV uses reserved fields\n"); 13600 return -EINVAL; 13601 } 13602 } 13603 13604 /* check src operand */ 13605 err = check_reg_arg(env, insn->src_reg, SRC_OP); 13606 if (err) 13607 return err; 13608 } else { 13609 if (insn->src_reg != BPF_REG_0 || insn->off != 0) { 13610 verbose(env, "BPF_MOV uses reserved fields\n"); 13611 return -EINVAL; 13612 } 13613 } 13614 13615 /* check dest operand, mark as required later */ 13616 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK); 13617 if (err) 13618 return err; 13619 13620 if (BPF_SRC(insn->code) == BPF_X) { 13621 struct bpf_reg_state *src_reg = regs + insn->src_reg; 13622 struct bpf_reg_state *dst_reg = regs + insn->dst_reg; 13623 bool need_id = src_reg->type == SCALAR_VALUE && !src_reg->id && 13624 !tnum_is_const(src_reg->var_off); 13625 13626 if (BPF_CLASS(insn->code) == BPF_ALU64) { 13627 if (insn->off == 0) { 13628 /* case: R1 = R2 13629 * copy register state to dest reg 13630 */ 13631 if (need_id) 13632 /* Assign src and dst registers the same ID 13633 * that will be used by find_equal_scalars() 13634 * to propagate min/max range. 13635 */ 13636 src_reg->id = ++env->id_gen; 13637 copy_register_state(dst_reg, src_reg); 13638 dst_reg->live |= REG_LIVE_WRITTEN; 13639 dst_reg->subreg_def = DEF_NOT_SUBREG; 13640 } else { 13641 /* case: R1 = (s8, s16 s32)R2 */ 13642 if (is_pointer_value(env, insn->src_reg)) { 13643 verbose(env, 13644 "R%d sign-extension part of pointer\n", 13645 insn->src_reg); 13646 return -EACCES; 13647 } else if (src_reg->type == SCALAR_VALUE) { 13648 bool no_sext; 13649 13650 no_sext = src_reg->umax_value < (1ULL << (insn->off - 1)); 13651 if (no_sext && need_id) 13652 src_reg->id = ++env->id_gen; 13653 copy_register_state(dst_reg, src_reg); 13654 if (!no_sext) 13655 dst_reg->id = 0; 13656 coerce_reg_to_size_sx(dst_reg, insn->off >> 3); 13657 dst_reg->live |= REG_LIVE_WRITTEN; 13658 dst_reg->subreg_def = DEF_NOT_SUBREG; 13659 } else { 13660 mark_reg_unknown(env, regs, insn->dst_reg); 13661 } 13662 } 13663 } else { 13664 /* R1 = (u32) R2 */ 13665 if (is_pointer_value(env, insn->src_reg)) { 13666 verbose(env, 13667 "R%d partial copy of pointer\n", 13668 insn->src_reg); 13669 return -EACCES; 13670 } else if (src_reg->type == SCALAR_VALUE) { 13671 if (insn->off == 0) { 13672 bool is_src_reg_u32 = src_reg->umax_value <= U32_MAX; 13673 13674 if (is_src_reg_u32 && need_id) 13675 src_reg->id = ++env->id_gen; 13676 copy_register_state(dst_reg, src_reg); 13677 /* Make sure ID is cleared if src_reg is not in u32 13678 * range otherwise dst_reg min/max could be incorrectly 13679 * propagated into src_reg by find_equal_scalars() 13680 */ 13681 if (!is_src_reg_u32) 13682 dst_reg->id = 0; 13683 dst_reg->live |= REG_LIVE_WRITTEN; 13684 dst_reg->subreg_def = env->insn_idx + 1; 13685 } else { 13686 /* case: W1 = (s8, s16)W2 */ 13687 bool no_sext = src_reg->umax_value < (1ULL << (insn->off - 1)); 13688 13689 if (no_sext && need_id) 13690 src_reg->id = ++env->id_gen; 13691 copy_register_state(dst_reg, src_reg); 13692 if (!no_sext) 13693 dst_reg->id = 0; 13694 dst_reg->live |= REG_LIVE_WRITTEN; 13695 dst_reg->subreg_def = env->insn_idx + 1; 13696 coerce_subreg_to_size_sx(dst_reg, insn->off >> 3); 13697 } 13698 } else { 13699 mark_reg_unknown(env, regs, 13700 insn->dst_reg); 13701 } 13702 zext_32_to_64(dst_reg); 13703 reg_bounds_sync(dst_reg); 13704 } 13705 } else { 13706 /* case: R = imm 13707 * remember the value we stored into this reg 13708 */ 13709 /* clear any state __mark_reg_known doesn't set */ 13710 mark_reg_unknown(env, regs, insn->dst_reg); 13711 regs[insn->dst_reg].type = SCALAR_VALUE; 13712 if (BPF_CLASS(insn->code) == BPF_ALU64) { 13713 __mark_reg_known(regs + insn->dst_reg, 13714 insn->imm); 13715 } else { 13716 __mark_reg_known(regs + insn->dst_reg, 13717 (u32)insn->imm); 13718 } 13719 } 13720 13721 } else if (opcode > BPF_END) { 13722 verbose(env, "invalid BPF_ALU opcode %x\n", opcode); 13723 return -EINVAL; 13724 13725 } else { /* all other ALU ops: and, sub, xor, add, ... */ 13726 13727 if (BPF_SRC(insn->code) == BPF_X) { 13728 if (insn->imm != 0 || insn->off > 1 || 13729 (insn->off == 1 && opcode != BPF_MOD && opcode != BPF_DIV)) { 13730 verbose(env, "BPF_ALU uses reserved fields\n"); 13731 return -EINVAL; 13732 } 13733 /* check src1 operand */ 13734 err = check_reg_arg(env, insn->src_reg, SRC_OP); 13735 if (err) 13736 return err; 13737 } else { 13738 if (insn->src_reg != BPF_REG_0 || insn->off > 1 || 13739 (insn->off == 1 && opcode != BPF_MOD && opcode != BPF_DIV)) { 13740 verbose(env, "BPF_ALU uses reserved fields\n"); 13741 return -EINVAL; 13742 } 13743 } 13744 13745 /* check src2 operand */ 13746 err = check_reg_arg(env, insn->dst_reg, SRC_OP); 13747 if (err) 13748 return err; 13749 13750 if ((opcode == BPF_MOD || opcode == BPF_DIV) && 13751 BPF_SRC(insn->code) == BPF_K && insn->imm == 0) { 13752 verbose(env, "div by zero\n"); 13753 return -EINVAL; 13754 } 13755 13756 if ((opcode == BPF_LSH || opcode == BPF_RSH || 13757 opcode == BPF_ARSH) && BPF_SRC(insn->code) == BPF_K) { 13758 int size = BPF_CLASS(insn->code) == BPF_ALU64 ? 64 : 32; 13759 13760 if (insn->imm < 0 || insn->imm >= size) { 13761 verbose(env, "invalid shift %d\n", insn->imm); 13762 return -EINVAL; 13763 } 13764 } 13765 13766 /* check dest operand */ 13767 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK); 13768 if (err) 13769 return err; 13770 13771 return adjust_reg_min_max_vals(env, insn); 13772 } 13773 13774 return 0; 13775 } 13776 13777 static void find_good_pkt_pointers(struct bpf_verifier_state *vstate, 13778 struct bpf_reg_state *dst_reg, 13779 enum bpf_reg_type type, 13780 bool range_right_open) 13781 { 13782 struct bpf_func_state *state; 13783 struct bpf_reg_state *reg; 13784 int new_range; 13785 13786 if (dst_reg->off < 0 || 13787 (dst_reg->off == 0 && range_right_open)) 13788 /* This doesn't give us any range */ 13789 return; 13790 13791 if (dst_reg->umax_value > MAX_PACKET_OFF || 13792 dst_reg->umax_value + dst_reg->off > MAX_PACKET_OFF) 13793 /* Risk of overflow. For instance, ptr + (1<<63) may be less 13794 * than pkt_end, but that's because it's also less than pkt. 13795 */ 13796 return; 13797 13798 new_range = dst_reg->off; 13799 if (range_right_open) 13800 new_range++; 13801 13802 /* Examples for register markings: 13803 * 13804 * pkt_data in dst register: 13805 * 13806 * r2 = r3; 13807 * r2 += 8; 13808 * if (r2 > pkt_end) goto <handle exception> 13809 * <access okay> 13810 * 13811 * r2 = r3; 13812 * r2 += 8; 13813 * if (r2 < pkt_end) goto <access okay> 13814 * <handle exception> 13815 * 13816 * Where: 13817 * r2 == dst_reg, pkt_end == src_reg 13818 * r2=pkt(id=n,off=8,r=0) 13819 * r3=pkt(id=n,off=0,r=0) 13820 * 13821 * pkt_data in src register: 13822 * 13823 * r2 = r3; 13824 * r2 += 8; 13825 * if (pkt_end >= r2) goto <access okay> 13826 * <handle exception> 13827 * 13828 * r2 = r3; 13829 * r2 += 8; 13830 * if (pkt_end <= r2) goto <handle exception> 13831 * <access okay> 13832 * 13833 * Where: 13834 * pkt_end == dst_reg, r2 == src_reg 13835 * r2=pkt(id=n,off=8,r=0) 13836 * r3=pkt(id=n,off=0,r=0) 13837 * 13838 * Find register r3 and mark its range as r3=pkt(id=n,off=0,r=8) 13839 * or r3=pkt(id=n,off=0,r=8-1), so that range of bytes [r3, r3 + 8) 13840 * and [r3, r3 + 8-1) respectively is safe to access depending on 13841 * the check. 13842 */ 13843 13844 /* If our ids match, then we must have the same max_value. And we 13845 * don't care about the other reg's fixed offset, since if it's too big 13846 * the range won't allow anything. 13847 * dst_reg->off is known < MAX_PACKET_OFF, therefore it fits in a u16. 13848 */ 13849 bpf_for_each_reg_in_vstate(vstate, state, reg, ({ 13850 if (reg->type == type && reg->id == dst_reg->id) 13851 /* keep the maximum range already checked */ 13852 reg->range = max(reg->range, new_range); 13853 })); 13854 } 13855 13856 static int is_branch32_taken(struct bpf_reg_state *reg, u32 val, u8 opcode) 13857 { 13858 struct tnum subreg = tnum_subreg(reg->var_off); 13859 s32 sval = (s32)val; 13860 13861 switch (opcode) { 13862 case BPF_JEQ: 13863 if (tnum_is_const(subreg)) 13864 return !!tnum_equals_const(subreg, val); 13865 else if (val < reg->u32_min_value || val > reg->u32_max_value) 13866 return 0; 13867 break; 13868 case BPF_JNE: 13869 if (tnum_is_const(subreg)) 13870 return !tnum_equals_const(subreg, val); 13871 else if (val < reg->u32_min_value || val > reg->u32_max_value) 13872 return 1; 13873 break; 13874 case BPF_JSET: 13875 if ((~subreg.mask & subreg.value) & val) 13876 return 1; 13877 if (!((subreg.mask | subreg.value) & val)) 13878 return 0; 13879 break; 13880 case BPF_JGT: 13881 if (reg->u32_min_value > val) 13882 return 1; 13883 else if (reg->u32_max_value <= val) 13884 return 0; 13885 break; 13886 case BPF_JSGT: 13887 if (reg->s32_min_value > sval) 13888 return 1; 13889 else if (reg->s32_max_value <= sval) 13890 return 0; 13891 break; 13892 case BPF_JLT: 13893 if (reg->u32_max_value < val) 13894 return 1; 13895 else if (reg->u32_min_value >= val) 13896 return 0; 13897 break; 13898 case BPF_JSLT: 13899 if (reg->s32_max_value < sval) 13900 return 1; 13901 else if (reg->s32_min_value >= sval) 13902 return 0; 13903 break; 13904 case BPF_JGE: 13905 if (reg->u32_min_value >= val) 13906 return 1; 13907 else if (reg->u32_max_value < val) 13908 return 0; 13909 break; 13910 case BPF_JSGE: 13911 if (reg->s32_min_value >= sval) 13912 return 1; 13913 else if (reg->s32_max_value < sval) 13914 return 0; 13915 break; 13916 case BPF_JLE: 13917 if (reg->u32_max_value <= val) 13918 return 1; 13919 else if (reg->u32_min_value > val) 13920 return 0; 13921 break; 13922 case BPF_JSLE: 13923 if (reg->s32_max_value <= sval) 13924 return 1; 13925 else if (reg->s32_min_value > sval) 13926 return 0; 13927 break; 13928 } 13929 13930 return -1; 13931 } 13932 13933 13934 static int is_branch64_taken(struct bpf_reg_state *reg, u64 val, u8 opcode) 13935 { 13936 s64 sval = (s64)val; 13937 13938 switch (opcode) { 13939 case BPF_JEQ: 13940 if (tnum_is_const(reg->var_off)) 13941 return !!tnum_equals_const(reg->var_off, val); 13942 else if (val < reg->umin_value || val > reg->umax_value) 13943 return 0; 13944 break; 13945 case BPF_JNE: 13946 if (tnum_is_const(reg->var_off)) 13947 return !tnum_equals_const(reg->var_off, val); 13948 else if (val < reg->umin_value || val > reg->umax_value) 13949 return 1; 13950 break; 13951 case BPF_JSET: 13952 if ((~reg->var_off.mask & reg->var_off.value) & val) 13953 return 1; 13954 if (!((reg->var_off.mask | reg->var_off.value) & val)) 13955 return 0; 13956 break; 13957 case BPF_JGT: 13958 if (reg->umin_value > val) 13959 return 1; 13960 else if (reg->umax_value <= val) 13961 return 0; 13962 break; 13963 case BPF_JSGT: 13964 if (reg->smin_value > sval) 13965 return 1; 13966 else if (reg->smax_value <= sval) 13967 return 0; 13968 break; 13969 case BPF_JLT: 13970 if (reg->umax_value < val) 13971 return 1; 13972 else if (reg->umin_value >= val) 13973 return 0; 13974 break; 13975 case BPF_JSLT: 13976 if (reg->smax_value < sval) 13977 return 1; 13978 else if (reg->smin_value >= sval) 13979 return 0; 13980 break; 13981 case BPF_JGE: 13982 if (reg->umin_value >= val) 13983 return 1; 13984 else if (reg->umax_value < val) 13985 return 0; 13986 break; 13987 case BPF_JSGE: 13988 if (reg->smin_value >= sval) 13989 return 1; 13990 else if (reg->smax_value < sval) 13991 return 0; 13992 break; 13993 case BPF_JLE: 13994 if (reg->umax_value <= val) 13995 return 1; 13996 else if (reg->umin_value > val) 13997 return 0; 13998 break; 13999 case BPF_JSLE: 14000 if (reg->smax_value <= sval) 14001 return 1; 14002 else if (reg->smin_value > sval) 14003 return 0; 14004 break; 14005 } 14006 14007 return -1; 14008 } 14009 14010 /* compute branch direction of the expression "if (reg opcode val) goto target;" 14011 * and return: 14012 * 1 - branch will be taken and "goto target" will be executed 14013 * 0 - branch will not be taken and fall-through to next insn 14014 * -1 - unknown. Example: "if (reg < 5)" is unknown when register value 14015 * range [0,10] 14016 */ 14017 static int is_branch_taken(struct bpf_reg_state *reg, u64 val, u8 opcode, 14018 bool is_jmp32) 14019 { 14020 if (__is_pointer_value(false, reg)) { 14021 if (!reg_not_null(reg)) 14022 return -1; 14023 14024 /* If pointer is valid tests against zero will fail so we can 14025 * use this to direct branch taken. 14026 */ 14027 if (val != 0) 14028 return -1; 14029 14030 switch (opcode) { 14031 case BPF_JEQ: 14032 return 0; 14033 case BPF_JNE: 14034 return 1; 14035 default: 14036 return -1; 14037 } 14038 } 14039 14040 if (is_jmp32) 14041 return is_branch32_taken(reg, val, opcode); 14042 return is_branch64_taken(reg, val, opcode); 14043 } 14044 14045 static int flip_opcode(u32 opcode) 14046 { 14047 /* How can we transform "a <op> b" into "b <op> a"? */ 14048 static const u8 opcode_flip[16] = { 14049 /* these stay the same */ 14050 [BPF_JEQ >> 4] = BPF_JEQ, 14051 [BPF_JNE >> 4] = BPF_JNE, 14052 [BPF_JSET >> 4] = BPF_JSET, 14053 /* these swap "lesser" and "greater" (L and G in the opcodes) */ 14054 [BPF_JGE >> 4] = BPF_JLE, 14055 [BPF_JGT >> 4] = BPF_JLT, 14056 [BPF_JLE >> 4] = BPF_JGE, 14057 [BPF_JLT >> 4] = BPF_JGT, 14058 [BPF_JSGE >> 4] = BPF_JSLE, 14059 [BPF_JSGT >> 4] = BPF_JSLT, 14060 [BPF_JSLE >> 4] = BPF_JSGE, 14061 [BPF_JSLT >> 4] = BPF_JSGT 14062 }; 14063 return opcode_flip[opcode >> 4]; 14064 } 14065 14066 static int is_pkt_ptr_branch_taken(struct bpf_reg_state *dst_reg, 14067 struct bpf_reg_state *src_reg, 14068 u8 opcode) 14069 { 14070 struct bpf_reg_state *pkt; 14071 14072 if (src_reg->type == PTR_TO_PACKET_END) { 14073 pkt = dst_reg; 14074 } else if (dst_reg->type == PTR_TO_PACKET_END) { 14075 pkt = src_reg; 14076 opcode = flip_opcode(opcode); 14077 } else { 14078 return -1; 14079 } 14080 14081 if (pkt->range >= 0) 14082 return -1; 14083 14084 switch (opcode) { 14085 case BPF_JLE: 14086 /* pkt <= pkt_end */ 14087 fallthrough; 14088 case BPF_JGT: 14089 /* pkt > pkt_end */ 14090 if (pkt->range == BEYOND_PKT_END) 14091 /* pkt has at last one extra byte beyond pkt_end */ 14092 return opcode == BPF_JGT; 14093 break; 14094 case BPF_JLT: 14095 /* pkt < pkt_end */ 14096 fallthrough; 14097 case BPF_JGE: 14098 /* pkt >= pkt_end */ 14099 if (pkt->range == BEYOND_PKT_END || pkt->range == AT_PKT_END) 14100 return opcode == BPF_JGE; 14101 break; 14102 } 14103 return -1; 14104 } 14105 14106 /* Adjusts the register min/max values in the case that the dst_reg is the 14107 * variable register that we are working on, and src_reg is a constant or we're 14108 * simply doing a BPF_K check. 14109 * In JEQ/JNE cases we also adjust the var_off values. 14110 */ 14111 static void reg_set_min_max(struct bpf_reg_state *true_reg, 14112 struct bpf_reg_state *false_reg, 14113 u64 val, u32 val32, 14114 u8 opcode, bool is_jmp32) 14115 { 14116 struct tnum false_32off = tnum_subreg(false_reg->var_off); 14117 struct tnum false_64off = false_reg->var_off; 14118 struct tnum true_32off = tnum_subreg(true_reg->var_off); 14119 struct tnum true_64off = true_reg->var_off; 14120 s64 sval = (s64)val; 14121 s32 sval32 = (s32)val32; 14122 14123 /* If the dst_reg is a pointer, we can't learn anything about its 14124 * variable offset from the compare (unless src_reg were a pointer into 14125 * the same object, but we don't bother with that. 14126 * Since false_reg and true_reg have the same type by construction, we 14127 * only need to check one of them for pointerness. 14128 */ 14129 if (__is_pointer_value(false, false_reg)) 14130 return; 14131 14132 switch (opcode) { 14133 /* JEQ/JNE comparison doesn't change the register equivalence. 14134 * 14135 * r1 = r2; 14136 * if (r1 == 42) goto label; 14137 * ... 14138 * label: // here both r1 and r2 are known to be 42. 14139 * 14140 * Hence when marking register as known preserve it's ID. 14141 */ 14142 case BPF_JEQ: 14143 if (is_jmp32) { 14144 __mark_reg32_known(true_reg, val32); 14145 true_32off = tnum_subreg(true_reg->var_off); 14146 } else { 14147 ___mark_reg_known(true_reg, val); 14148 true_64off = true_reg->var_off; 14149 } 14150 break; 14151 case BPF_JNE: 14152 if (is_jmp32) { 14153 __mark_reg32_known(false_reg, val32); 14154 false_32off = tnum_subreg(false_reg->var_off); 14155 } else { 14156 ___mark_reg_known(false_reg, val); 14157 false_64off = false_reg->var_off; 14158 } 14159 break; 14160 case BPF_JSET: 14161 if (is_jmp32) { 14162 false_32off = tnum_and(false_32off, tnum_const(~val32)); 14163 if (is_power_of_2(val32)) 14164 true_32off = tnum_or(true_32off, 14165 tnum_const(val32)); 14166 } else { 14167 false_64off = tnum_and(false_64off, tnum_const(~val)); 14168 if (is_power_of_2(val)) 14169 true_64off = tnum_or(true_64off, 14170 tnum_const(val)); 14171 } 14172 break; 14173 case BPF_JGE: 14174 case BPF_JGT: 14175 { 14176 if (is_jmp32) { 14177 u32 false_umax = opcode == BPF_JGT ? val32 : val32 - 1; 14178 u32 true_umin = opcode == BPF_JGT ? val32 + 1 : val32; 14179 14180 false_reg->u32_max_value = min(false_reg->u32_max_value, 14181 false_umax); 14182 true_reg->u32_min_value = max(true_reg->u32_min_value, 14183 true_umin); 14184 } else { 14185 u64 false_umax = opcode == BPF_JGT ? val : val - 1; 14186 u64 true_umin = opcode == BPF_JGT ? val + 1 : val; 14187 14188 false_reg->umax_value = min(false_reg->umax_value, false_umax); 14189 true_reg->umin_value = max(true_reg->umin_value, true_umin); 14190 } 14191 break; 14192 } 14193 case BPF_JSGE: 14194 case BPF_JSGT: 14195 { 14196 if (is_jmp32) { 14197 s32 false_smax = opcode == BPF_JSGT ? sval32 : sval32 - 1; 14198 s32 true_smin = opcode == BPF_JSGT ? sval32 + 1 : sval32; 14199 14200 false_reg->s32_max_value = min(false_reg->s32_max_value, false_smax); 14201 true_reg->s32_min_value = max(true_reg->s32_min_value, true_smin); 14202 } else { 14203 s64 false_smax = opcode == BPF_JSGT ? sval : sval - 1; 14204 s64 true_smin = opcode == BPF_JSGT ? sval + 1 : sval; 14205 14206 false_reg->smax_value = min(false_reg->smax_value, false_smax); 14207 true_reg->smin_value = max(true_reg->smin_value, true_smin); 14208 } 14209 break; 14210 } 14211 case BPF_JLE: 14212 case BPF_JLT: 14213 { 14214 if (is_jmp32) { 14215 u32 false_umin = opcode == BPF_JLT ? val32 : val32 + 1; 14216 u32 true_umax = opcode == BPF_JLT ? val32 - 1 : val32; 14217 14218 false_reg->u32_min_value = max(false_reg->u32_min_value, 14219 false_umin); 14220 true_reg->u32_max_value = min(true_reg->u32_max_value, 14221 true_umax); 14222 } else { 14223 u64 false_umin = opcode == BPF_JLT ? val : val + 1; 14224 u64 true_umax = opcode == BPF_JLT ? val - 1 : val; 14225 14226 false_reg->umin_value = max(false_reg->umin_value, false_umin); 14227 true_reg->umax_value = min(true_reg->umax_value, true_umax); 14228 } 14229 break; 14230 } 14231 case BPF_JSLE: 14232 case BPF_JSLT: 14233 { 14234 if (is_jmp32) { 14235 s32 false_smin = opcode == BPF_JSLT ? sval32 : sval32 + 1; 14236 s32 true_smax = opcode == BPF_JSLT ? sval32 - 1 : sval32; 14237 14238 false_reg->s32_min_value = max(false_reg->s32_min_value, false_smin); 14239 true_reg->s32_max_value = min(true_reg->s32_max_value, true_smax); 14240 } else { 14241 s64 false_smin = opcode == BPF_JSLT ? sval : sval + 1; 14242 s64 true_smax = opcode == BPF_JSLT ? sval - 1 : sval; 14243 14244 false_reg->smin_value = max(false_reg->smin_value, false_smin); 14245 true_reg->smax_value = min(true_reg->smax_value, true_smax); 14246 } 14247 break; 14248 } 14249 default: 14250 return; 14251 } 14252 14253 if (is_jmp32) { 14254 false_reg->var_off = tnum_or(tnum_clear_subreg(false_64off), 14255 tnum_subreg(false_32off)); 14256 true_reg->var_off = tnum_or(tnum_clear_subreg(true_64off), 14257 tnum_subreg(true_32off)); 14258 __reg_combine_32_into_64(false_reg); 14259 __reg_combine_32_into_64(true_reg); 14260 } else { 14261 false_reg->var_off = false_64off; 14262 true_reg->var_off = true_64off; 14263 __reg_combine_64_into_32(false_reg); 14264 __reg_combine_64_into_32(true_reg); 14265 } 14266 } 14267 14268 /* Same as above, but for the case that dst_reg holds a constant and src_reg is 14269 * the variable reg. 14270 */ 14271 static void reg_set_min_max_inv(struct bpf_reg_state *true_reg, 14272 struct bpf_reg_state *false_reg, 14273 u64 val, u32 val32, 14274 u8 opcode, bool is_jmp32) 14275 { 14276 opcode = flip_opcode(opcode); 14277 /* This uses zero as "not present in table"; luckily the zero opcode, 14278 * BPF_JA, can't get here. 14279 */ 14280 if (opcode) 14281 reg_set_min_max(true_reg, false_reg, val, val32, opcode, is_jmp32); 14282 } 14283 14284 /* Regs are known to be equal, so intersect their min/max/var_off */ 14285 static void __reg_combine_min_max(struct bpf_reg_state *src_reg, 14286 struct bpf_reg_state *dst_reg) 14287 { 14288 src_reg->umin_value = dst_reg->umin_value = max(src_reg->umin_value, 14289 dst_reg->umin_value); 14290 src_reg->umax_value = dst_reg->umax_value = min(src_reg->umax_value, 14291 dst_reg->umax_value); 14292 src_reg->smin_value = dst_reg->smin_value = max(src_reg->smin_value, 14293 dst_reg->smin_value); 14294 src_reg->smax_value = dst_reg->smax_value = min(src_reg->smax_value, 14295 dst_reg->smax_value); 14296 src_reg->var_off = dst_reg->var_off = tnum_intersect(src_reg->var_off, 14297 dst_reg->var_off); 14298 reg_bounds_sync(src_reg); 14299 reg_bounds_sync(dst_reg); 14300 } 14301 14302 static void reg_combine_min_max(struct bpf_reg_state *true_src, 14303 struct bpf_reg_state *true_dst, 14304 struct bpf_reg_state *false_src, 14305 struct bpf_reg_state *false_dst, 14306 u8 opcode) 14307 { 14308 switch (opcode) { 14309 case BPF_JEQ: 14310 __reg_combine_min_max(true_src, true_dst); 14311 break; 14312 case BPF_JNE: 14313 __reg_combine_min_max(false_src, false_dst); 14314 break; 14315 } 14316 } 14317 14318 static void mark_ptr_or_null_reg(struct bpf_func_state *state, 14319 struct bpf_reg_state *reg, u32 id, 14320 bool is_null) 14321 { 14322 if (type_may_be_null(reg->type) && reg->id == id && 14323 (is_rcu_reg(reg) || !WARN_ON_ONCE(!reg->id))) { 14324 /* Old offset (both fixed and variable parts) should have been 14325 * known-zero, because we don't allow pointer arithmetic on 14326 * pointers that might be NULL. If we see this happening, don't 14327 * convert the register. 14328 * 14329 * But in some cases, some helpers that return local kptrs 14330 * advance offset for the returned pointer. In those cases, it 14331 * is fine to expect to see reg->off. 14332 */ 14333 if (WARN_ON_ONCE(reg->smin_value || reg->smax_value || !tnum_equals_const(reg->var_off, 0))) 14334 return; 14335 if (!(type_is_ptr_alloc_obj(reg->type) || type_is_non_owning_ref(reg->type)) && 14336 WARN_ON_ONCE(reg->off)) 14337 return; 14338 14339 if (is_null) { 14340 reg->type = SCALAR_VALUE; 14341 /* We don't need id and ref_obj_id from this point 14342 * onwards anymore, thus we should better reset it, 14343 * so that state pruning has chances to take effect. 14344 */ 14345 reg->id = 0; 14346 reg->ref_obj_id = 0; 14347 14348 return; 14349 } 14350 14351 mark_ptr_not_null_reg(reg); 14352 14353 if (!reg_may_point_to_spin_lock(reg)) { 14354 /* For not-NULL ptr, reg->ref_obj_id will be reset 14355 * in release_reference(). 14356 * 14357 * reg->id is still used by spin_lock ptr. Other 14358 * than spin_lock ptr type, reg->id can be reset. 14359 */ 14360 reg->id = 0; 14361 } 14362 } 14363 } 14364 14365 /* The logic is similar to find_good_pkt_pointers(), both could eventually 14366 * be folded together at some point. 14367 */ 14368 static void mark_ptr_or_null_regs(struct bpf_verifier_state *vstate, u32 regno, 14369 bool is_null) 14370 { 14371 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 14372 struct bpf_reg_state *regs = state->regs, *reg; 14373 u32 ref_obj_id = regs[regno].ref_obj_id; 14374 u32 id = regs[regno].id; 14375 14376 if (ref_obj_id && ref_obj_id == id && is_null) 14377 /* regs[regno] is in the " == NULL" branch. 14378 * No one could have freed the reference state before 14379 * doing the NULL check. 14380 */ 14381 WARN_ON_ONCE(release_reference_state(state, id)); 14382 14383 bpf_for_each_reg_in_vstate(vstate, state, reg, ({ 14384 mark_ptr_or_null_reg(state, reg, id, is_null); 14385 })); 14386 } 14387 14388 static bool try_match_pkt_pointers(const struct bpf_insn *insn, 14389 struct bpf_reg_state *dst_reg, 14390 struct bpf_reg_state *src_reg, 14391 struct bpf_verifier_state *this_branch, 14392 struct bpf_verifier_state *other_branch) 14393 { 14394 if (BPF_SRC(insn->code) != BPF_X) 14395 return false; 14396 14397 /* Pointers are always 64-bit. */ 14398 if (BPF_CLASS(insn->code) == BPF_JMP32) 14399 return false; 14400 14401 switch (BPF_OP(insn->code)) { 14402 case BPF_JGT: 14403 if ((dst_reg->type == PTR_TO_PACKET && 14404 src_reg->type == PTR_TO_PACKET_END) || 14405 (dst_reg->type == PTR_TO_PACKET_META && 14406 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) { 14407 /* pkt_data' > pkt_end, pkt_meta' > pkt_data */ 14408 find_good_pkt_pointers(this_branch, dst_reg, 14409 dst_reg->type, false); 14410 mark_pkt_end(other_branch, insn->dst_reg, true); 14411 } else if ((dst_reg->type == PTR_TO_PACKET_END && 14412 src_reg->type == PTR_TO_PACKET) || 14413 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) && 14414 src_reg->type == PTR_TO_PACKET_META)) { 14415 /* pkt_end > pkt_data', pkt_data > pkt_meta' */ 14416 find_good_pkt_pointers(other_branch, src_reg, 14417 src_reg->type, true); 14418 mark_pkt_end(this_branch, insn->src_reg, false); 14419 } else { 14420 return false; 14421 } 14422 break; 14423 case BPF_JLT: 14424 if ((dst_reg->type == PTR_TO_PACKET && 14425 src_reg->type == PTR_TO_PACKET_END) || 14426 (dst_reg->type == PTR_TO_PACKET_META && 14427 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) { 14428 /* pkt_data' < pkt_end, pkt_meta' < pkt_data */ 14429 find_good_pkt_pointers(other_branch, dst_reg, 14430 dst_reg->type, true); 14431 mark_pkt_end(this_branch, insn->dst_reg, false); 14432 } else if ((dst_reg->type == PTR_TO_PACKET_END && 14433 src_reg->type == PTR_TO_PACKET) || 14434 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) && 14435 src_reg->type == PTR_TO_PACKET_META)) { 14436 /* pkt_end < pkt_data', pkt_data > pkt_meta' */ 14437 find_good_pkt_pointers(this_branch, src_reg, 14438 src_reg->type, false); 14439 mark_pkt_end(other_branch, insn->src_reg, true); 14440 } else { 14441 return false; 14442 } 14443 break; 14444 case BPF_JGE: 14445 if ((dst_reg->type == PTR_TO_PACKET && 14446 src_reg->type == PTR_TO_PACKET_END) || 14447 (dst_reg->type == PTR_TO_PACKET_META && 14448 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) { 14449 /* pkt_data' >= pkt_end, pkt_meta' >= pkt_data */ 14450 find_good_pkt_pointers(this_branch, dst_reg, 14451 dst_reg->type, true); 14452 mark_pkt_end(other_branch, insn->dst_reg, false); 14453 } else if ((dst_reg->type == PTR_TO_PACKET_END && 14454 src_reg->type == PTR_TO_PACKET) || 14455 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) && 14456 src_reg->type == PTR_TO_PACKET_META)) { 14457 /* pkt_end >= pkt_data', pkt_data >= pkt_meta' */ 14458 find_good_pkt_pointers(other_branch, src_reg, 14459 src_reg->type, false); 14460 mark_pkt_end(this_branch, insn->src_reg, true); 14461 } else { 14462 return false; 14463 } 14464 break; 14465 case BPF_JLE: 14466 if ((dst_reg->type == PTR_TO_PACKET && 14467 src_reg->type == PTR_TO_PACKET_END) || 14468 (dst_reg->type == PTR_TO_PACKET_META && 14469 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) { 14470 /* pkt_data' <= pkt_end, pkt_meta' <= pkt_data */ 14471 find_good_pkt_pointers(other_branch, dst_reg, 14472 dst_reg->type, false); 14473 mark_pkt_end(this_branch, insn->dst_reg, true); 14474 } else if ((dst_reg->type == PTR_TO_PACKET_END && 14475 src_reg->type == PTR_TO_PACKET) || 14476 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) && 14477 src_reg->type == PTR_TO_PACKET_META)) { 14478 /* pkt_end <= pkt_data', pkt_data <= pkt_meta' */ 14479 find_good_pkt_pointers(this_branch, src_reg, 14480 src_reg->type, true); 14481 mark_pkt_end(other_branch, insn->src_reg, false); 14482 } else { 14483 return false; 14484 } 14485 break; 14486 default: 14487 return false; 14488 } 14489 14490 return true; 14491 } 14492 14493 static void find_equal_scalars(struct bpf_verifier_state *vstate, 14494 struct bpf_reg_state *known_reg) 14495 { 14496 struct bpf_func_state *state; 14497 struct bpf_reg_state *reg; 14498 14499 bpf_for_each_reg_in_vstate(vstate, state, reg, ({ 14500 if (reg->type == SCALAR_VALUE && reg->id == known_reg->id) { 14501 s32 saved_subreg_def = reg->subreg_def; 14502 copy_register_state(reg, known_reg); 14503 reg->subreg_def = saved_subreg_def; 14504 } 14505 })); 14506 } 14507 14508 static int check_cond_jmp_op(struct bpf_verifier_env *env, 14509 struct bpf_insn *insn, int *insn_idx) 14510 { 14511 struct bpf_verifier_state *this_branch = env->cur_state; 14512 struct bpf_verifier_state *other_branch; 14513 struct bpf_reg_state *regs = this_branch->frame[this_branch->curframe]->regs; 14514 struct bpf_reg_state *dst_reg, *other_branch_regs, *src_reg = NULL; 14515 struct bpf_reg_state *eq_branch_regs; 14516 u8 opcode = BPF_OP(insn->code); 14517 bool is_jmp32; 14518 int pred = -1; 14519 int err; 14520 14521 /* Only conditional jumps are expected to reach here. */ 14522 if (opcode == BPF_JA || opcode > BPF_JSLE) { 14523 verbose(env, "invalid BPF_JMP/JMP32 opcode %x\n", opcode); 14524 return -EINVAL; 14525 } 14526 14527 /* check src2 operand */ 14528 err = check_reg_arg(env, insn->dst_reg, SRC_OP); 14529 if (err) 14530 return err; 14531 14532 dst_reg = ®s[insn->dst_reg]; 14533 if (BPF_SRC(insn->code) == BPF_X) { 14534 if (insn->imm != 0) { 14535 verbose(env, "BPF_JMP/JMP32 uses reserved fields\n"); 14536 return -EINVAL; 14537 } 14538 14539 /* check src1 operand */ 14540 err = check_reg_arg(env, insn->src_reg, SRC_OP); 14541 if (err) 14542 return err; 14543 14544 src_reg = ®s[insn->src_reg]; 14545 if (!(reg_is_pkt_pointer_any(dst_reg) && reg_is_pkt_pointer_any(src_reg)) && 14546 is_pointer_value(env, insn->src_reg)) { 14547 verbose(env, "R%d pointer comparison prohibited\n", 14548 insn->src_reg); 14549 return -EACCES; 14550 } 14551 } else { 14552 if (insn->src_reg != BPF_REG_0) { 14553 verbose(env, "BPF_JMP/JMP32 uses reserved fields\n"); 14554 return -EINVAL; 14555 } 14556 } 14557 14558 is_jmp32 = BPF_CLASS(insn->code) == BPF_JMP32; 14559 14560 if (BPF_SRC(insn->code) == BPF_K) { 14561 pred = is_branch_taken(dst_reg, insn->imm, opcode, is_jmp32); 14562 } else if (src_reg->type == SCALAR_VALUE && 14563 is_jmp32 && tnum_is_const(tnum_subreg(src_reg->var_off))) { 14564 pred = is_branch_taken(dst_reg, 14565 tnum_subreg(src_reg->var_off).value, 14566 opcode, 14567 is_jmp32); 14568 } else if (src_reg->type == SCALAR_VALUE && 14569 !is_jmp32 && tnum_is_const(src_reg->var_off)) { 14570 pred = is_branch_taken(dst_reg, 14571 src_reg->var_off.value, 14572 opcode, 14573 is_jmp32); 14574 } else if (dst_reg->type == SCALAR_VALUE && 14575 is_jmp32 && tnum_is_const(tnum_subreg(dst_reg->var_off))) { 14576 pred = is_branch_taken(src_reg, 14577 tnum_subreg(dst_reg->var_off).value, 14578 flip_opcode(opcode), 14579 is_jmp32); 14580 } else if (dst_reg->type == SCALAR_VALUE && 14581 !is_jmp32 && tnum_is_const(dst_reg->var_off)) { 14582 pred = is_branch_taken(src_reg, 14583 dst_reg->var_off.value, 14584 flip_opcode(opcode), 14585 is_jmp32); 14586 } else if (reg_is_pkt_pointer_any(dst_reg) && 14587 reg_is_pkt_pointer_any(src_reg) && 14588 !is_jmp32) { 14589 pred = is_pkt_ptr_branch_taken(dst_reg, src_reg, opcode); 14590 } 14591 14592 if (pred >= 0) { 14593 /* If we get here with a dst_reg pointer type it is because 14594 * above is_branch_taken() special cased the 0 comparison. 14595 */ 14596 if (!__is_pointer_value(false, dst_reg)) 14597 err = mark_chain_precision(env, insn->dst_reg); 14598 if (BPF_SRC(insn->code) == BPF_X && !err && 14599 !__is_pointer_value(false, src_reg)) 14600 err = mark_chain_precision(env, insn->src_reg); 14601 if (err) 14602 return err; 14603 } 14604 14605 if (pred == 1) { 14606 /* Only follow the goto, ignore fall-through. If needed, push 14607 * the fall-through branch for simulation under speculative 14608 * execution. 14609 */ 14610 if (!env->bypass_spec_v1 && 14611 !sanitize_speculative_path(env, insn, *insn_idx + 1, 14612 *insn_idx)) 14613 return -EFAULT; 14614 if (env->log.level & BPF_LOG_LEVEL) 14615 print_insn_state(env, this_branch->frame[this_branch->curframe]); 14616 *insn_idx += insn->off; 14617 return 0; 14618 } else if (pred == 0) { 14619 /* Only follow the fall-through branch, since that's where the 14620 * program will go. If needed, push the goto branch for 14621 * simulation under speculative execution. 14622 */ 14623 if (!env->bypass_spec_v1 && 14624 !sanitize_speculative_path(env, insn, 14625 *insn_idx + insn->off + 1, 14626 *insn_idx)) 14627 return -EFAULT; 14628 if (env->log.level & BPF_LOG_LEVEL) 14629 print_insn_state(env, this_branch->frame[this_branch->curframe]); 14630 return 0; 14631 } 14632 14633 other_branch = push_stack(env, *insn_idx + insn->off + 1, *insn_idx, 14634 false); 14635 if (!other_branch) 14636 return -EFAULT; 14637 other_branch_regs = other_branch->frame[other_branch->curframe]->regs; 14638 14639 /* detect if we are comparing against a constant value so we can adjust 14640 * our min/max values for our dst register. 14641 * this is only legit if both are scalars (or pointers to the same 14642 * object, I suppose, see the PTR_MAYBE_NULL related if block below), 14643 * because otherwise the different base pointers mean the offsets aren't 14644 * comparable. 14645 */ 14646 if (BPF_SRC(insn->code) == BPF_X) { 14647 struct bpf_reg_state *src_reg = ®s[insn->src_reg]; 14648 14649 if (dst_reg->type == SCALAR_VALUE && 14650 src_reg->type == SCALAR_VALUE) { 14651 if (tnum_is_const(src_reg->var_off) || 14652 (is_jmp32 && 14653 tnum_is_const(tnum_subreg(src_reg->var_off)))) 14654 reg_set_min_max(&other_branch_regs[insn->dst_reg], 14655 dst_reg, 14656 src_reg->var_off.value, 14657 tnum_subreg(src_reg->var_off).value, 14658 opcode, is_jmp32); 14659 else if (tnum_is_const(dst_reg->var_off) || 14660 (is_jmp32 && 14661 tnum_is_const(tnum_subreg(dst_reg->var_off)))) 14662 reg_set_min_max_inv(&other_branch_regs[insn->src_reg], 14663 src_reg, 14664 dst_reg->var_off.value, 14665 tnum_subreg(dst_reg->var_off).value, 14666 opcode, is_jmp32); 14667 else if (!is_jmp32 && 14668 (opcode == BPF_JEQ || opcode == BPF_JNE)) 14669 /* Comparing for equality, we can combine knowledge */ 14670 reg_combine_min_max(&other_branch_regs[insn->src_reg], 14671 &other_branch_regs[insn->dst_reg], 14672 src_reg, dst_reg, opcode); 14673 if (src_reg->id && 14674 !WARN_ON_ONCE(src_reg->id != other_branch_regs[insn->src_reg].id)) { 14675 find_equal_scalars(this_branch, src_reg); 14676 find_equal_scalars(other_branch, &other_branch_regs[insn->src_reg]); 14677 } 14678 14679 } 14680 } else if (dst_reg->type == SCALAR_VALUE) { 14681 reg_set_min_max(&other_branch_regs[insn->dst_reg], 14682 dst_reg, insn->imm, (u32)insn->imm, 14683 opcode, is_jmp32); 14684 } 14685 14686 if (dst_reg->type == SCALAR_VALUE && dst_reg->id && 14687 !WARN_ON_ONCE(dst_reg->id != other_branch_regs[insn->dst_reg].id)) { 14688 find_equal_scalars(this_branch, dst_reg); 14689 find_equal_scalars(other_branch, &other_branch_regs[insn->dst_reg]); 14690 } 14691 14692 /* if one pointer register is compared to another pointer 14693 * register check if PTR_MAYBE_NULL could be lifted. 14694 * E.g. register A - maybe null 14695 * register B - not null 14696 * for JNE A, B, ... - A is not null in the false branch; 14697 * for JEQ A, B, ... - A is not null in the true branch. 14698 * 14699 * Since PTR_TO_BTF_ID points to a kernel struct that does 14700 * not need to be null checked by the BPF program, i.e., 14701 * could be null even without PTR_MAYBE_NULL marking, so 14702 * only propagate nullness when neither reg is that type. 14703 */ 14704 if (!is_jmp32 && BPF_SRC(insn->code) == BPF_X && 14705 __is_pointer_value(false, src_reg) && __is_pointer_value(false, dst_reg) && 14706 type_may_be_null(src_reg->type) != type_may_be_null(dst_reg->type) && 14707 base_type(src_reg->type) != PTR_TO_BTF_ID && 14708 base_type(dst_reg->type) != PTR_TO_BTF_ID) { 14709 eq_branch_regs = NULL; 14710 switch (opcode) { 14711 case BPF_JEQ: 14712 eq_branch_regs = other_branch_regs; 14713 break; 14714 case BPF_JNE: 14715 eq_branch_regs = regs; 14716 break; 14717 default: 14718 /* do nothing */ 14719 break; 14720 } 14721 if (eq_branch_regs) { 14722 if (type_may_be_null(src_reg->type)) 14723 mark_ptr_not_null_reg(&eq_branch_regs[insn->src_reg]); 14724 else 14725 mark_ptr_not_null_reg(&eq_branch_regs[insn->dst_reg]); 14726 } 14727 } 14728 14729 /* detect if R == 0 where R is returned from bpf_map_lookup_elem(). 14730 * NOTE: these optimizations below are related with pointer comparison 14731 * which will never be JMP32. 14732 */ 14733 if (!is_jmp32 && BPF_SRC(insn->code) == BPF_K && 14734 insn->imm == 0 && (opcode == BPF_JEQ || opcode == BPF_JNE) && 14735 type_may_be_null(dst_reg->type)) { 14736 /* Mark all identical registers in each branch as either 14737 * safe or unknown depending R == 0 or R != 0 conditional. 14738 */ 14739 mark_ptr_or_null_regs(this_branch, insn->dst_reg, 14740 opcode == BPF_JNE); 14741 mark_ptr_or_null_regs(other_branch, insn->dst_reg, 14742 opcode == BPF_JEQ); 14743 } else if (!try_match_pkt_pointers(insn, dst_reg, ®s[insn->src_reg], 14744 this_branch, other_branch) && 14745 is_pointer_value(env, insn->dst_reg)) { 14746 verbose(env, "R%d pointer comparison prohibited\n", 14747 insn->dst_reg); 14748 return -EACCES; 14749 } 14750 if (env->log.level & BPF_LOG_LEVEL) 14751 print_insn_state(env, this_branch->frame[this_branch->curframe]); 14752 return 0; 14753 } 14754 14755 /* verify BPF_LD_IMM64 instruction */ 14756 static int check_ld_imm(struct bpf_verifier_env *env, struct bpf_insn *insn) 14757 { 14758 struct bpf_insn_aux_data *aux = cur_aux(env); 14759 struct bpf_reg_state *regs = cur_regs(env); 14760 struct bpf_reg_state *dst_reg; 14761 struct bpf_map *map; 14762 int err; 14763 14764 if (BPF_SIZE(insn->code) != BPF_DW) { 14765 verbose(env, "invalid BPF_LD_IMM insn\n"); 14766 return -EINVAL; 14767 } 14768 if (insn->off != 0) { 14769 verbose(env, "BPF_LD_IMM64 uses reserved fields\n"); 14770 return -EINVAL; 14771 } 14772 14773 err = check_reg_arg(env, insn->dst_reg, DST_OP); 14774 if (err) 14775 return err; 14776 14777 dst_reg = ®s[insn->dst_reg]; 14778 if (insn->src_reg == 0) { 14779 u64 imm = ((u64)(insn + 1)->imm << 32) | (u32)insn->imm; 14780 14781 dst_reg->type = SCALAR_VALUE; 14782 __mark_reg_known(®s[insn->dst_reg], imm); 14783 return 0; 14784 } 14785 14786 /* All special src_reg cases are listed below. From this point onwards 14787 * we either succeed and assign a corresponding dst_reg->type after 14788 * zeroing the offset, or fail and reject the program. 14789 */ 14790 mark_reg_known_zero(env, regs, insn->dst_reg); 14791 14792 if (insn->src_reg == BPF_PSEUDO_BTF_ID) { 14793 dst_reg->type = aux->btf_var.reg_type; 14794 switch (base_type(dst_reg->type)) { 14795 case PTR_TO_MEM: 14796 dst_reg->mem_size = aux->btf_var.mem_size; 14797 break; 14798 case PTR_TO_BTF_ID: 14799 dst_reg->btf = aux->btf_var.btf; 14800 dst_reg->btf_id = aux->btf_var.btf_id; 14801 break; 14802 default: 14803 verbose(env, "bpf verifier is misconfigured\n"); 14804 return -EFAULT; 14805 } 14806 return 0; 14807 } 14808 14809 if (insn->src_reg == BPF_PSEUDO_FUNC) { 14810 struct bpf_prog_aux *aux = env->prog->aux; 14811 u32 subprogno = find_subprog(env, 14812 env->insn_idx + insn->imm + 1); 14813 14814 if (!aux->func_info) { 14815 verbose(env, "missing btf func_info\n"); 14816 return -EINVAL; 14817 } 14818 if (aux->func_info_aux[subprogno].linkage != BTF_FUNC_STATIC) { 14819 verbose(env, "callback function not static\n"); 14820 return -EINVAL; 14821 } 14822 14823 dst_reg->type = PTR_TO_FUNC; 14824 dst_reg->subprogno = subprogno; 14825 return 0; 14826 } 14827 14828 map = env->used_maps[aux->map_index]; 14829 dst_reg->map_ptr = map; 14830 14831 if (insn->src_reg == BPF_PSEUDO_MAP_VALUE || 14832 insn->src_reg == BPF_PSEUDO_MAP_IDX_VALUE) { 14833 dst_reg->type = PTR_TO_MAP_VALUE; 14834 dst_reg->off = aux->map_off; 14835 WARN_ON_ONCE(map->max_entries != 1); 14836 /* We want reg->id to be same (0) as map_value is not distinct */ 14837 } else if (insn->src_reg == BPF_PSEUDO_MAP_FD || 14838 insn->src_reg == BPF_PSEUDO_MAP_IDX) { 14839 dst_reg->type = CONST_PTR_TO_MAP; 14840 } else { 14841 verbose(env, "bpf verifier is misconfigured\n"); 14842 return -EINVAL; 14843 } 14844 14845 return 0; 14846 } 14847 14848 static bool may_access_skb(enum bpf_prog_type type) 14849 { 14850 switch (type) { 14851 case BPF_PROG_TYPE_SOCKET_FILTER: 14852 case BPF_PROG_TYPE_SCHED_CLS: 14853 case BPF_PROG_TYPE_SCHED_ACT: 14854 return true; 14855 default: 14856 return false; 14857 } 14858 } 14859 14860 /* verify safety of LD_ABS|LD_IND instructions: 14861 * - they can only appear in the programs where ctx == skb 14862 * - since they are wrappers of function calls, they scratch R1-R5 registers, 14863 * preserve R6-R9, and store return value into R0 14864 * 14865 * Implicit input: 14866 * ctx == skb == R6 == CTX 14867 * 14868 * Explicit input: 14869 * SRC == any register 14870 * IMM == 32-bit immediate 14871 * 14872 * Output: 14873 * R0 - 8/16/32-bit skb data converted to cpu endianness 14874 */ 14875 static int check_ld_abs(struct bpf_verifier_env *env, struct bpf_insn *insn) 14876 { 14877 struct bpf_reg_state *regs = cur_regs(env); 14878 static const int ctx_reg = BPF_REG_6; 14879 u8 mode = BPF_MODE(insn->code); 14880 int i, err; 14881 14882 if (!may_access_skb(resolve_prog_type(env->prog))) { 14883 verbose(env, "BPF_LD_[ABS|IND] instructions not allowed for this program type\n"); 14884 return -EINVAL; 14885 } 14886 14887 if (!env->ops->gen_ld_abs) { 14888 verbose(env, "bpf verifier is misconfigured\n"); 14889 return -EINVAL; 14890 } 14891 14892 if (insn->dst_reg != BPF_REG_0 || insn->off != 0 || 14893 BPF_SIZE(insn->code) == BPF_DW || 14894 (mode == BPF_ABS && insn->src_reg != BPF_REG_0)) { 14895 verbose(env, "BPF_LD_[ABS|IND] uses reserved fields\n"); 14896 return -EINVAL; 14897 } 14898 14899 /* check whether implicit source operand (register R6) is readable */ 14900 err = check_reg_arg(env, ctx_reg, SRC_OP); 14901 if (err) 14902 return err; 14903 14904 /* Disallow usage of BPF_LD_[ABS|IND] with reference tracking, as 14905 * gen_ld_abs() may terminate the program at runtime, leading to 14906 * reference leak. 14907 */ 14908 err = check_reference_leak(env); 14909 if (err) { 14910 verbose(env, "BPF_LD_[ABS|IND] cannot be mixed with socket references\n"); 14911 return err; 14912 } 14913 14914 if (env->cur_state->active_lock.ptr) { 14915 verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_spin_lock-ed region\n"); 14916 return -EINVAL; 14917 } 14918 14919 if (env->cur_state->active_rcu_lock) { 14920 verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_rcu_read_lock-ed region\n"); 14921 return -EINVAL; 14922 } 14923 14924 if (regs[ctx_reg].type != PTR_TO_CTX) { 14925 verbose(env, 14926 "at the time of BPF_LD_ABS|IND R6 != pointer to skb\n"); 14927 return -EINVAL; 14928 } 14929 14930 if (mode == BPF_IND) { 14931 /* check explicit source operand */ 14932 err = check_reg_arg(env, insn->src_reg, SRC_OP); 14933 if (err) 14934 return err; 14935 } 14936 14937 err = check_ptr_off_reg(env, ®s[ctx_reg], ctx_reg); 14938 if (err < 0) 14939 return err; 14940 14941 /* reset caller saved regs to unreadable */ 14942 for (i = 0; i < CALLER_SAVED_REGS; i++) { 14943 mark_reg_not_init(env, regs, caller_saved[i]); 14944 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK); 14945 } 14946 14947 /* mark destination R0 register as readable, since it contains 14948 * the value fetched from the packet. 14949 * Already marked as written above. 14950 */ 14951 mark_reg_unknown(env, regs, BPF_REG_0); 14952 /* ld_abs load up to 32-bit skb data. */ 14953 regs[BPF_REG_0].subreg_def = env->insn_idx + 1; 14954 return 0; 14955 } 14956 14957 static int check_return_code(struct bpf_verifier_env *env) 14958 { 14959 struct tnum enforce_attach_type_range = tnum_unknown; 14960 const struct bpf_prog *prog = env->prog; 14961 struct bpf_reg_state *reg; 14962 struct tnum range = tnum_range(0, 1), const_0 = tnum_const(0); 14963 enum bpf_prog_type prog_type = resolve_prog_type(env->prog); 14964 int err; 14965 struct bpf_func_state *frame = env->cur_state->frame[0]; 14966 const bool is_subprog = frame->subprogno; 14967 14968 /* LSM and struct_ops func-ptr's return type could be "void" */ 14969 if (!is_subprog) { 14970 switch (prog_type) { 14971 case BPF_PROG_TYPE_LSM: 14972 if (prog->expected_attach_type == BPF_LSM_CGROUP) 14973 /* See below, can be 0 or 0-1 depending on hook. */ 14974 break; 14975 fallthrough; 14976 case BPF_PROG_TYPE_STRUCT_OPS: 14977 if (!prog->aux->attach_func_proto->type) 14978 return 0; 14979 break; 14980 default: 14981 break; 14982 } 14983 } 14984 14985 /* eBPF calling convention is such that R0 is used 14986 * to return the value from eBPF program. 14987 * Make sure that it's readable at this time 14988 * of bpf_exit, which means that program wrote 14989 * something into it earlier 14990 */ 14991 err = check_reg_arg(env, BPF_REG_0, SRC_OP); 14992 if (err) 14993 return err; 14994 14995 if (is_pointer_value(env, BPF_REG_0)) { 14996 verbose(env, "R0 leaks addr as return value\n"); 14997 return -EACCES; 14998 } 14999 15000 reg = cur_regs(env) + BPF_REG_0; 15001 15002 if (frame->in_async_callback_fn) { 15003 /* enforce return zero from async callbacks like timer */ 15004 if (reg->type != SCALAR_VALUE) { 15005 verbose(env, "In async callback the register R0 is not a known value (%s)\n", 15006 reg_type_str(env, reg->type)); 15007 return -EINVAL; 15008 } 15009 15010 if (!tnum_in(const_0, reg->var_off)) { 15011 verbose_invalid_scalar(env, reg, &const_0, "async callback", "R0"); 15012 return -EINVAL; 15013 } 15014 return 0; 15015 } 15016 15017 if (is_subprog) { 15018 if (reg->type != SCALAR_VALUE) { 15019 verbose(env, "At subprogram exit the register R0 is not a scalar value (%s)\n", 15020 reg_type_str(env, reg->type)); 15021 return -EINVAL; 15022 } 15023 return 0; 15024 } 15025 15026 switch (prog_type) { 15027 case BPF_PROG_TYPE_CGROUP_SOCK_ADDR: 15028 if (env->prog->expected_attach_type == BPF_CGROUP_UDP4_RECVMSG || 15029 env->prog->expected_attach_type == BPF_CGROUP_UDP6_RECVMSG || 15030 env->prog->expected_attach_type == BPF_CGROUP_INET4_GETPEERNAME || 15031 env->prog->expected_attach_type == BPF_CGROUP_INET6_GETPEERNAME || 15032 env->prog->expected_attach_type == BPF_CGROUP_INET4_GETSOCKNAME || 15033 env->prog->expected_attach_type == BPF_CGROUP_INET6_GETSOCKNAME) 15034 range = tnum_range(1, 1); 15035 if (env->prog->expected_attach_type == BPF_CGROUP_INET4_BIND || 15036 env->prog->expected_attach_type == BPF_CGROUP_INET6_BIND) 15037 range = tnum_range(0, 3); 15038 break; 15039 case BPF_PROG_TYPE_CGROUP_SKB: 15040 if (env->prog->expected_attach_type == BPF_CGROUP_INET_EGRESS) { 15041 range = tnum_range(0, 3); 15042 enforce_attach_type_range = tnum_range(2, 3); 15043 } 15044 break; 15045 case BPF_PROG_TYPE_CGROUP_SOCK: 15046 case BPF_PROG_TYPE_SOCK_OPS: 15047 case BPF_PROG_TYPE_CGROUP_DEVICE: 15048 case BPF_PROG_TYPE_CGROUP_SYSCTL: 15049 case BPF_PROG_TYPE_CGROUP_SOCKOPT: 15050 break; 15051 case BPF_PROG_TYPE_RAW_TRACEPOINT: 15052 if (!env->prog->aux->attach_btf_id) 15053 return 0; 15054 range = tnum_const(0); 15055 break; 15056 case BPF_PROG_TYPE_TRACING: 15057 switch (env->prog->expected_attach_type) { 15058 case BPF_TRACE_FENTRY: 15059 case BPF_TRACE_FEXIT: 15060 range = tnum_const(0); 15061 break; 15062 case BPF_TRACE_RAW_TP: 15063 case BPF_MODIFY_RETURN: 15064 return 0; 15065 case BPF_TRACE_ITER: 15066 break; 15067 default: 15068 return -ENOTSUPP; 15069 } 15070 break; 15071 case BPF_PROG_TYPE_SK_LOOKUP: 15072 range = tnum_range(SK_DROP, SK_PASS); 15073 break; 15074 15075 case BPF_PROG_TYPE_LSM: 15076 if (env->prog->expected_attach_type != BPF_LSM_CGROUP) { 15077 /* Regular BPF_PROG_TYPE_LSM programs can return 15078 * any value. 15079 */ 15080 return 0; 15081 } 15082 if (!env->prog->aux->attach_func_proto->type) { 15083 /* Make sure programs that attach to void 15084 * hooks don't try to modify return value. 15085 */ 15086 range = tnum_range(1, 1); 15087 } 15088 break; 15089 15090 case BPF_PROG_TYPE_NETFILTER: 15091 range = tnum_range(NF_DROP, NF_ACCEPT); 15092 break; 15093 case BPF_PROG_TYPE_EXT: 15094 /* freplace program can return anything as its return value 15095 * depends on the to-be-replaced kernel func or bpf program. 15096 */ 15097 default: 15098 return 0; 15099 } 15100 15101 if (reg->type != SCALAR_VALUE) { 15102 verbose(env, "At program exit the register R0 is not a known value (%s)\n", 15103 reg_type_str(env, reg->type)); 15104 return -EINVAL; 15105 } 15106 15107 if (!tnum_in(range, reg->var_off)) { 15108 verbose_invalid_scalar(env, reg, &range, "program exit", "R0"); 15109 if (prog->expected_attach_type == BPF_LSM_CGROUP && 15110 prog_type == BPF_PROG_TYPE_LSM && 15111 !prog->aux->attach_func_proto->type) 15112 verbose(env, "Note, BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n"); 15113 return -EINVAL; 15114 } 15115 15116 if (!tnum_is_unknown(enforce_attach_type_range) && 15117 tnum_in(enforce_attach_type_range, reg->var_off)) 15118 env->prog->enforce_expected_attach_type = 1; 15119 return 0; 15120 } 15121 15122 /* non-recursive DFS pseudo code 15123 * 1 procedure DFS-iterative(G,v): 15124 * 2 label v as discovered 15125 * 3 let S be a stack 15126 * 4 S.push(v) 15127 * 5 while S is not empty 15128 * 6 t <- S.peek() 15129 * 7 if t is what we're looking for: 15130 * 8 return t 15131 * 9 for all edges e in G.adjacentEdges(t) do 15132 * 10 if edge e is already labelled 15133 * 11 continue with the next edge 15134 * 12 w <- G.adjacentVertex(t,e) 15135 * 13 if vertex w is not discovered and not explored 15136 * 14 label e as tree-edge 15137 * 15 label w as discovered 15138 * 16 S.push(w) 15139 * 17 continue at 5 15140 * 18 else if vertex w is discovered 15141 * 19 label e as back-edge 15142 * 20 else 15143 * 21 // vertex w is explored 15144 * 22 label e as forward- or cross-edge 15145 * 23 label t as explored 15146 * 24 S.pop() 15147 * 15148 * convention: 15149 * 0x10 - discovered 15150 * 0x11 - discovered and fall-through edge labelled 15151 * 0x12 - discovered and fall-through and branch edges labelled 15152 * 0x20 - explored 15153 */ 15154 15155 enum { 15156 DISCOVERED = 0x10, 15157 EXPLORED = 0x20, 15158 FALLTHROUGH = 1, 15159 BRANCH = 2, 15160 }; 15161 15162 static void mark_prune_point(struct bpf_verifier_env *env, int idx) 15163 { 15164 env->insn_aux_data[idx].prune_point = true; 15165 } 15166 15167 static bool is_prune_point(struct bpf_verifier_env *env, int insn_idx) 15168 { 15169 return env->insn_aux_data[insn_idx].prune_point; 15170 } 15171 15172 static void mark_force_checkpoint(struct bpf_verifier_env *env, int idx) 15173 { 15174 env->insn_aux_data[idx].force_checkpoint = true; 15175 } 15176 15177 static bool is_force_checkpoint(struct bpf_verifier_env *env, int insn_idx) 15178 { 15179 return env->insn_aux_data[insn_idx].force_checkpoint; 15180 } 15181 15182 static void mark_calls_callback(struct bpf_verifier_env *env, int idx) 15183 { 15184 env->insn_aux_data[idx].calls_callback = true; 15185 } 15186 15187 static bool calls_callback(struct bpf_verifier_env *env, int insn_idx) 15188 { 15189 return env->insn_aux_data[insn_idx].calls_callback; 15190 } 15191 15192 enum { 15193 DONE_EXPLORING = 0, 15194 KEEP_EXPLORING = 1, 15195 }; 15196 15197 /* t, w, e - match pseudo-code above: 15198 * t - index of current instruction 15199 * w - next instruction 15200 * e - edge 15201 */ 15202 static int push_insn(int t, int w, int e, struct bpf_verifier_env *env) 15203 { 15204 int *insn_stack = env->cfg.insn_stack; 15205 int *insn_state = env->cfg.insn_state; 15206 15207 if (e == FALLTHROUGH && insn_state[t] >= (DISCOVERED | FALLTHROUGH)) 15208 return DONE_EXPLORING; 15209 15210 if (e == BRANCH && insn_state[t] >= (DISCOVERED | BRANCH)) 15211 return DONE_EXPLORING; 15212 15213 if (w < 0 || w >= env->prog->len) { 15214 verbose_linfo(env, t, "%d: ", t); 15215 verbose(env, "jump out of range from insn %d to %d\n", t, w); 15216 return -EINVAL; 15217 } 15218 15219 if (e == BRANCH) { 15220 /* mark branch target for state pruning */ 15221 mark_prune_point(env, w); 15222 mark_jmp_point(env, w); 15223 } 15224 15225 if (insn_state[w] == 0) { 15226 /* tree-edge */ 15227 insn_state[t] = DISCOVERED | e; 15228 insn_state[w] = DISCOVERED; 15229 if (env->cfg.cur_stack >= env->prog->len) 15230 return -E2BIG; 15231 insn_stack[env->cfg.cur_stack++] = w; 15232 return KEEP_EXPLORING; 15233 } else if ((insn_state[w] & 0xF0) == DISCOVERED) { 15234 if (env->bpf_capable) 15235 return DONE_EXPLORING; 15236 verbose_linfo(env, t, "%d: ", t); 15237 verbose_linfo(env, w, "%d: ", w); 15238 verbose(env, "back-edge from insn %d to %d\n", t, w); 15239 return -EINVAL; 15240 } else if (insn_state[w] == EXPLORED) { 15241 /* forward- or cross-edge */ 15242 insn_state[t] = DISCOVERED | e; 15243 } else { 15244 verbose(env, "insn state internal bug\n"); 15245 return -EFAULT; 15246 } 15247 return DONE_EXPLORING; 15248 } 15249 15250 static int visit_func_call_insn(int t, struct bpf_insn *insns, 15251 struct bpf_verifier_env *env, 15252 bool visit_callee) 15253 { 15254 int ret, insn_sz; 15255 15256 insn_sz = bpf_is_ldimm64(&insns[t]) ? 2 : 1; 15257 ret = push_insn(t, t + insn_sz, FALLTHROUGH, env); 15258 if (ret) 15259 return ret; 15260 15261 mark_prune_point(env, t + insn_sz); 15262 /* when we exit from subprog, we need to record non-linear history */ 15263 mark_jmp_point(env, t + insn_sz); 15264 15265 if (visit_callee) { 15266 mark_prune_point(env, t); 15267 ret = push_insn(t, t + insns[t].imm + 1, BRANCH, env); 15268 } 15269 return ret; 15270 } 15271 15272 /* Visits the instruction at index t and returns one of the following: 15273 * < 0 - an error occurred 15274 * DONE_EXPLORING - the instruction was fully explored 15275 * KEEP_EXPLORING - there is still work to be done before it is fully explored 15276 */ 15277 static int visit_insn(int t, struct bpf_verifier_env *env) 15278 { 15279 struct bpf_insn *insns = env->prog->insnsi, *insn = &insns[t]; 15280 int ret, off, insn_sz; 15281 15282 if (bpf_pseudo_func(insn)) 15283 return visit_func_call_insn(t, insns, env, true); 15284 15285 /* All non-branch instructions have a single fall-through edge. */ 15286 if (BPF_CLASS(insn->code) != BPF_JMP && 15287 BPF_CLASS(insn->code) != BPF_JMP32) { 15288 insn_sz = bpf_is_ldimm64(insn) ? 2 : 1; 15289 return push_insn(t, t + insn_sz, FALLTHROUGH, env); 15290 } 15291 15292 switch (BPF_OP(insn->code)) { 15293 case BPF_EXIT: 15294 return DONE_EXPLORING; 15295 15296 case BPF_CALL: 15297 if (insn->src_reg == 0 && insn->imm == BPF_FUNC_timer_set_callback) 15298 /* Mark this call insn as a prune point to trigger 15299 * is_state_visited() check before call itself is 15300 * processed by __check_func_call(). Otherwise new 15301 * async state will be pushed for further exploration. 15302 */ 15303 mark_prune_point(env, t); 15304 /* For functions that invoke callbacks it is not known how many times 15305 * callback would be called. Verifier models callback calling functions 15306 * by repeatedly visiting callback bodies and returning to origin call 15307 * instruction. 15308 * In order to stop such iteration verifier needs to identify when a 15309 * state identical some state from a previous iteration is reached. 15310 * Check below forces creation of checkpoint before callback calling 15311 * instruction to allow search for such identical states. 15312 */ 15313 if (is_sync_callback_calling_insn(insn)) { 15314 mark_calls_callback(env, t); 15315 mark_force_checkpoint(env, t); 15316 mark_prune_point(env, t); 15317 mark_jmp_point(env, t); 15318 } 15319 if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) { 15320 struct bpf_kfunc_call_arg_meta meta; 15321 15322 ret = fetch_kfunc_meta(env, insn, &meta, NULL); 15323 if (ret == 0 && is_iter_next_kfunc(&meta)) { 15324 mark_prune_point(env, t); 15325 /* Checking and saving state checkpoints at iter_next() call 15326 * is crucial for fast convergence of open-coded iterator loop 15327 * logic, so we need to force it. If we don't do that, 15328 * is_state_visited() might skip saving a checkpoint, causing 15329 * unnecessarily long sequence of not checkpointed 15330 * instructions and jumps, leading to exhaustion of jump 15331 * history buffer, and potentially other undesired outcomes. 15332 * It is expected that with correct open-coded iterators 15333 * convergence will happen quickly, so we don't run a risk of 15334 * exhausting memory. 15335 */ 15336 mark_force_checkpoint(env, t); 15337 } 15338 } 15339 return visit_func_call_insn(t, insns, env, insn->src_reg == BPF_PSEUDO_CALL); 15340 15341 case BPF_JA: 15342 if (BPF_SRC(insn->code) != BPF_K) 15343 return -EINVAL; 15344 15345 if (BPF_CLASS(insn->code) == BPF_JMP) 15346 off = insn->off; 15347 else 15348 off = insn->imm; 15349 15350 /* unconditional jump with single edge */ 15351 ret = push_insn(t, t + off + 1, FALLTHROUGH, env); 15352 if (ret) 15353 return ret; 15354 15355 mark_prune_point(env, t + off + 1); 15356 mark_jmp_point(env, t + off + 1); 15357 15358 return ret; 15359 15360 default: 15361 /* conditional jump with two edges */ 15362 mark_prune_point(env, t); 15363 15364 ret = push_insn(t, t + 1, FALLTHROUGH, env); 15365 if (ret) 15366 return ret; 15367 15368 return push_insn(t, t + insn->off + 1, BRANCH, env); 15369 } 15370 } 15371 15372 /* non-recursive depth-first-search to detect loops in BPF program 15373 * loop == back-edge in directed graph 15374 */ 15375 static int check_cfg(struct bpf_verifier_env *env) 15376 { 15377 int insn_cnt = env->prog->len; 15378 int *insn_stack, *insn_state; 15379 int ret = 0; 15380 int i; 15381 15382 insn_state = env->cfg.insn_state = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL); 15383 if (!insn_state) 15384 return -ENOMEM; 15385 15386 insn_stack = env->cfg.insn_stack = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL); 15387 if (!insn_stack) { 15388 kvfree(insn_state); 15389 return -ENOMEM; 15390 } 15391 15392 insn_state[0] = DISCOVERED; /* mark 1st insn as discovered */ 15393 insn_stack[0] = 0; /* 0 is the first instruction */ 15394 env->cfg.cur_stack = 1; 15395 15396 while (env->cfg.cur_stack > 0) { 15397 int t = insn_stack[env->cfg.cur_stack - 1]; 15398 15399 ret = visit_insn(t, env); 15400 switch (ret) { 15401 case DONE_EXPLORING: 15402 insn_state[t] = EXPLORED; 15403 env->cfg.cur_stack--; 15404 break; 15405 case KEEP_EXPLORING: 15406 break; 15407 default: 15408 if (ret > 0) { 15409 verbose(env, "visit_insn internal bug\n"); 15410 ret = -EFAULT; 15411 } 15412 goto err_free; 15413 } 15414 } 15415 15416 if (env->cfg.cur_stack < 0) { 15417 verbose(env, "pop stack internal bug\n"); 15418 ret = -EFAULT; 15419 goto err_free; 15420 } 15421 15422 for (i = 0; i < insn_cnt; i++) { 15423 struct bpf_insn *insn = &env->prog->insnsi[i]; 15424 15425 if (insn_state[i] != EXPLORED) { 15426 verbose(env, "unreachable insn %d\n", i); 15427 ret = -EINVAL; 15428 goto err_free; 15429 } 15430 if (bpf_is_ldimm64(insn)) { 15431 if (insn_state[i + 1] != 0) { 15432 verbose(env, "jump into the middle of ldimm64 insn %d\n", i); 15433 ret = -EINVAL; 15434 goto err_free; 15435 } 15436 i++; /* skip second half of ldimm64 */ 15437 } 15438 } 15439 ret = 0; /* cfg looks good */ 15440 15441 err_free: 15442 kvfree(insn_state); 15443 kvfree(insn_stack); 15444 env->cfg.insn_state = env->cfg.insn_stack = NULL; 15445 return ret; 15446 } 15447 15448 static int check_abnormal_return(struct bpf_verifier_env *env) 15449 { 15450 int i; 15451 15452 for (i = 1; i < env->subprog_cnt; i++) { 15453 if (env->subprog_info[i].has_ld_abs) { 15454 verbose(env, "LD_ABS is not allowed in subprogs without BTF\n"); 15455 return -EINVAL; 15456 } 15457 if (env->subprog_info[i].has_tail_call) { 15458 verbose(env, "tail_call is not allowed in subprogs without BTF\n"); 15459 return -EINVAL; 15460 } 15461 } 15462 return 0; 15463 } 15464 15465 /* The minimum supported BTF func info size */ 15466 #define MIN_BPF_FUNCINFO_SIZE 8 15467 #define MAX_FUNCINFO_REC_SIZE 252 15468 15469 static int check_btf_func(struct bpf_verifier_env *env, 15470 const union bpf_attr *attr, 15471 bpfptr_t uattr) 15472 { 15473 const struct btf_type *type, *func_proto, *ret_type; 15474 u32 i, nfuncs, urec_size, min_size; 15475 u32 krec_size = sizeof(struct bpf_func_info); 15476 struct bpf_func_info *krecord; 15477 struct bpf_func_info_aux *info_aux = NULL; 15478 struct bpf_prog *prog; 15479 const struct btf *btf; 15480 bpfptr_t urecord; 15481 u32 prev_offset = 0; 15482 bool scalar_return; 15483 int ret = -ENOMEM; 15484 15485 nfuncs = attr->func_info_cnt; 15486 if (!nfuncs) { 15487 if (check_abnormal_return(env)) 15488 return -EINVAL; 15489 return 0; 15490 } 15491 15492 if (nfuncs != env->subprog_cnt) { 15493 verbose(env, "number of funcs in func_info doesn't match number of subprogs\n"); 15494 return -EINVAL; 15495 } 15496 15497 urec_size = attr->func_info_rec_size; 15498 if (urec_size < MIN_BPF_FUNCINFO_SIZE || 15499 urec_size > MAX_FUNCINFO_REC_SIZE || 15500 urec_size % sizeof(u32)) { 15501 verbose(env, "invalid func info rec size %u\n", urec_size); 15502 return -EINVAL; 15503 } 15504 15505 prog = env->prog; 15506 btf = prog->aux->btf; 15507 15508 urecord = make_bpfptr(attr->func_info, uattr.is_kernel); 15509 min_size = min_t(u32, krec_size, urec_size); 15510 15511 krecord = kvcalloc(nfuncs, krec_size, GFP_KERNEL | __GFP_NOWARN); 15512 if (!krecord) 15513 return -ENOMEM; 15514 info_aux = kcalloc(nfuncs, sizeof(*info_aux), GFP_KERNEL | __GFP_NOWARN); 15515 if (!info_aux) 15516 goto err_free; 15517 15518 for (i = 0; i < nfuncs; i++) { 15519 ret = bpf_check_uarg_tail_zero(urecord, krec_size, urec_size); 15520 if (ret) { 15521 if (ret == -E2BIG) { 15522 verbose(env, "nonzero tailing record in func info"); 15523 /* set the size kernel expects so loader can zero 15524 * out the rest of the record. 15525 */ 15526 if (copy_to_bpfptr_offset(uattr, 15527 offsetof(union bpf_attr, func_info_rec_size), 15528 &min_size, sizeof(min_size))) 15529 ret = -EFAULT; 15530 } 15531 goto err_free; 15532 } 15533 15534 if (copy_from_bpfptr(&krecord[i], urecord, min_size)) { 15535 ret = -EFAULT; 15536 goto err_free; 15537 } 15538 15539 /* check insn_off */ 15540 ret = -EINVAL; 15541 if (i == 0) { 15542 if (krecord[i].insn_off) { 15543 verbose(env, 15544 "nonzero insn_off %u for the first func info record", 15545 krecord[i].insn_off); 15546 goto err_free; 15547 } 15548 } else if (krecord[i].insn_off <= prev_offset) { 15549 verbose(env, 15550 "same or smaller insn offset (%u) than previous func info record (%u)", 15551 krecord[i].insn_off, prev_offset); 15552 goto err_free; 15553 } 15554 15555 if (env->subprog_info[i].start != krecord[i].insn_off) { 15556 verbose(env, "func_info BTF section doesn't match subprog layout in BPF program\n"); 15557 goto err_free; 15558 } 15559 15560 /* check type_id */ 15561 type = btf_type_by_id(btf, krecord[i].type_id); 15562 if (!type || !btf_type_is_func(type)) { 15563 verbose(env, "invalid type id %d in func info", 15564 krecord[i].type_id); 15565 goto err_free; 15566 } 15567 info_aux[i].linkage = BTF_INFO_VLEN(type->info); 15568 15569 func_proto = btf_type_by_id(btf, type->type); 15570 if (unlikely(!func_proto || !btf_type_is_func_proto(func_proto))) 15571 /* btf_func_check() already verified it during BTF load */ 15572 goto err_free; 15573 ret_type = btf_type_skip_modifiers(btf, func_proto->type, NULL); 15574 scalar_return = 15575 btf_type_is_small_int(ret_type) || btf_is_any_enum(ret_type); 15576 if (i && !scalar_return && env->subprog_info[i].has_ld_abs) { 15577 verbose(env, "LD_ABS is only allowed in functions that return 'int'.\n"); 15578 goto err_free; 15579 } 15580 if (i && !scalar_return && env->subprog_info[i].has_tail_call) { 15581 verbose(env, "tail_call is only allowed in functions that return 'int'.\n"); 15582 goto err_free; 15583 } 15584 15585 prev_offset = krecord[i].insn_off; 15586 bpfptr_add(&urecord, urec_size); 15587 } 15588 15589 prog->aux->func_info = krecord; 15590 prog->aux->func_info_cnt = nfuncs; 15591 prog->aux->func_info_aux = info_aux; 15592 return 0; 15593 15594 err_free: 15595 kvfree(krecord); 15596 kfree(info_aux); 15597 return ret; 15598 } 15599 15600 static void adjust_btf_func(struct bpf_verifier_env *env) 15601 { 15602 struct bpf_prog_aux *aux = env->prog->aux; 15603 int i; 15604 15605 if (!aux->func_info) 15606 return; 15607 15608 for (i = 0; i < env->subprog_cnt; i++) 15609 aux->func_info[i].insn_off = env->subprog_info[i].start; 15610 } 15611 15612 #define MIN_BPF_LINEINFO_SIZE offsetofend(struct bpf_line_info, line_col) 15613 #define MAX_LINEINFO_REC_SIZE MAX_FUNCINFO_REC_SIZE 15614 15615 static int check_btf_line(struct bpf_verifier_env *env, 15616 const union bpf_attr *attr, 15617 bpfptr_t uattr) 15618 { 15619 u32 i, s, nr_linfo, ncopy, expected_size, rec_size, prev_offset = 0; 15620 struct bpf_subprog_info *sub; 15621 struct bpf_line_info *linfo; 15622 struct bpf_prog *prog; 15623 const struct btf *btf; 15624 bpfptr_t ulinfo; 15625 int err; 15626 15627 nr_linfo = attr->line_info_cnt; 15628 if (!nr_linfo) 15629 return 0; 15630 if (nr_linfo > INT_MAX / sizeof(struct bpf_line_info)) 15631 return -EINVAL; 15632 15633 rec_size = attr->line_info_rec_size; 15634 if (rec_size < MIN_BPF_LINEINFO_SIZE || 15635 rec_size > MAX_LINEINFO_REC_SIZE || 15636 rec_size & (sizeof(u32) - 1)) 15637 return -EINVAL; 15638 15639 /* Need to zero it in case the userspace may 15640 * pass in a smaller bpf_line_info object. 15641 */ 15642 linfo = kvcalloc(nr_linfo, sizeof(struct bpf_line_info), 15643 GFP_KERNEL | __GFP_NOWARN); 15644 if (!linfo) 15645 return -ENOMEM; 15646 15647 prog = env->prog; 15648 btf = prog->aux->btf; 15649 15650 s = 0; 15651 sub = env->subprog_info; 15652 ulinfo = make_bpfptr(attr->line_info, uattr.is_kernel); 15653 expected_size = sizeof(struct bpf_line_info); 15654 ncopy = min_t(u32, expected_size, rec_size); 15655 for (i = 0; i < nr_linfo; i++) { 15656 err = bpf_check_uarg_tail_zero(ulinfo, expected_size, rec_size); 15657 if (err) { 15658 if (err == -E2BIG) { 15659 verbose(env, "nonzero tailing record in line_info"); 15660 if (copy_to_bpfptr_offset(uattr, 15661 offsetof(union bpf_attr, line_info_rec_size), 15662 &expected_size, sizeof(expected_size))) 15663 err = -EFAULT; 15664 } 15665 goto err_free; 15666 } 15667 15668 if (copy_from_bpfptr(&linfo[i], ulinfo, ncopy)) { 15669 err = -EFAULT; 15670 goto err_free; 15671 } 15672 15673 /* 15674 * Check insn_off to ensure 15675 * 1) strictly increasing AND 15676 * 2) bounded by prog->len 15677 * 15678 * The linfo[0].insn_off == 0 check logically falls into 15679 * the later "missing bpf_line_info for func..." case 15680 * because the first linfo[0].insn_off must be the 15681 * first sub also and the first sub must have 15682 * subprog_info[0].start == 0. 15683 */ 15684 if ((i && linfo[i].insn_off <= prev_offset) || 15685 linfo[i].insn_off >= prog->len) { 15686 verbose(env, "Invalid line_info[%u].insn_off:%u (prev_offset:%u prog->len:%u)\n", 15687 i, linfo[i].insn_off, prev_offset, 15688 prog->len); 15689 err = -EINVAL; 15690 goto err_free; 15691 } 15692 15693 if (!prog->insnsi[linfo[i].insn_off].code) { 15694 verbose(env, 15695 "Invalid insn code at line_info[%u].insn_off\n", 15696 i); 15697 err = -EINVAL; 15698 goto err_free; 15699 } 15700 15701 if (!btf_name_by_offset(btf, linfo[i].line_off) || 15702 !btf_name_by_offset(btf, linfo[i].file_name_off)) { 15703 verbose(env, "Invalid line_info[%u].line_off or .file_name_off\n", i); 15704 err = -EINVAL; 15705 goto err_free; 15706 } 15707 15708 if (s != env->subprog_cnt) { 15709 if (linfo[i].insn_off == sub[s].start) { 15710 sub[s].linfo_idx = i; 15711 s++; 15712 } else if (sub[s].start < linfo[i].insn_off) { 15713 verbose(env, "missing bpf_line_info for func#%u\n", s); 15714 err = -EINVAL; 15715 goto err_free; 15716 } 15717 } 15718 15719 prev_offset = linfo[i].insn_off; 15720 bpfptr_add(&ulinfo, rec_size); 15721 } 15722 15723 if (s != env->subprog_cnt) { 15724 verbose(env, "missing bpf_line_info for %u funcs starting from func#%u\n", 15725 env->subprog_cnt - s, s); 15726 err = -EINVAL; 15727 goto err_free; 15728 } 15729 15730 prog->aux->linfo = linfo; 15731 prog->aux->nr_linfo = nr_linfo; 15732 15733 return 0; 15734 15735 err_free: 15736 kvfree(linfo); 15737 return err; 15738 } 15739 15740 #define MIN_CORE_RELO_SIZE sizeof(struct bpf_core_relo) 15741 #define MAX_CORE_RELO_SIZE MAX_FUNCINFO_REC_SIZE 15742 15743 static int check_core_relo(struct bpf_verifier_env *env, 15744 const union bpf_attr *attr, 15745 bpfptr_t uattr) 15746 { 15747 u32 i, nr_core_relo, ncopy, expected_size, rec_size; 15748 struct bpf_core_relo core_relo = {}; 15749 struct bpf_prog *prog = env->prog; 15750 const struct btf *btf = prog->aux->btf; 15751 struct bpf_core_ctx ctx = { 15752 .log = &env->log, 15753 .btf = btf, 15754 }; 15755 bpfptr_t u_core_relo; 15756 int err; 15757 15758 nr_core_relo = attr->core_relo_cnt; 15759 if (!nr_core_relo) 15760 return 0; 15761 if (nr_core_relo > INT_MAX / sizeof(struct bpf_core_relo)) 15762 return -EINVAL; 15763 15764 rec_size = attr->core_relo_rec_size; 15765 if (rec_size < MIN_CORE_RELO_SIZE || 15766 rec_size > MAX_CORE_RELO_SIZE || 15767 rec_size % sizeof(u32)) 15768 return -EINVAL; 15769 15770 u_core_relo = make_bpfptr(attr->core_relos, uattr.is_kernel); 15771 expected_size = sizeof(struct bpf_core_relo); 15772 ncopy = min_t(u32, expected_size, rec_size); 15773 15774 /* Unlike func_info and line_info, copy and apply each CO-RE 15775 * relocation record one at a time. 15776 */ 15777 for (i = 0; i < nr_core_relo; i++) { 15778 /* future proofing when sizeof(bpf_core_relo) changes */ 15779 err = bpf_check_uarg_tail_zero(u_core_relo, expected_size, rec_size); 15780 if (err) { 15781 if (err == -E2BIG) { 15782 verbose(env, "nonzero tailing record in core_relo"); 15783 if (copy_to_bpfptr_offset(uattr, 15784 offsetof(union bpf_attr, core_relo_rec_size), 15785 &expected_size, sizeof(expected_size))) 15786 err = -EFAULT; 15787 } 15788 break; 15789 } 15790 15791 if (copy_from_bpfptr(&core_relo, u_core_relo, ncopy)) { 15792 err = -EFAULT; 15793 break; 15794 } 15795 15796 if (core_relo.insn_off % 8 || core_relo.insn_off / 8 >= prog->len) { 15797 verbose(env, "Invalid core_relo[%u].insn_off:%u prog->len:%u\n", 15798 i, core_relo.insn_off, prog->len); 15799 err = -EINVAL; 15800 break; 15801 } 15802 15803 err = bpf_core_apply(&ctx, &core_relo, i, 15804 &prog->insnsi[core_relo.insn_off / 8]); 15805 if (err) 15806 break; 15807 bpfptr_add(&u_core_relo, rec_size); 15808 } 15809 return err; 15810 } 15811 15812 static int check_btf_info(struct bpf_verifier_env *env, 15813 const union bpf_attr *attr, 15814 bpfptr_t uattr) 15815 { 15816 struct btf *btf; 15817 int err; 15818 15819 if (!attr->func_info_cnt && !attr->line_info_cnt) { 15820 if (check_abnormal_return(env)) 15821 return -EINVAL; 15822 return 0; 15823 } 15824 15825 btf = btf_get_by_fd(attr->prog_btf_fd); 15826 if (IS_ERR(btf)) 15827 return PTR_ERR(btf); 15828 if (btf_is_kernel(btf)) { 15829 btf_put(btf); 15830 return -EACCES; 15831 } 15832 env->prog->aux->btf = btf; 15833 15834 err = check_btf_func(env, attr, uattr); 15835 if (err) 15836 return err; 15837 15838 err = check_btf_line(env, attr, uattr); 15839 if (err) 15840 return err; 15841 15842 err = check_core_relo(env, attr, uattr); 15843 if (err) 15844 return err; 15845 15846 return 0; 15847 } 15848 15849 /* check %cur's range satisfies %old's */ 15850 static bool range_within(struct bpf_reg_state *old, 15851 struct bpf_reg_state *cur) 15852 { 15853 return old->umin_value <= cur->umin_value && 15854 old->umax_value >= cur->umax_value && 15855 old->smin_value <= cur->smin_value && 15856 old->smax_value >= cur->smax_value && 15857 old->u32_min_value <= cur->u32_min_value && 15858 old->u32_max_value >= cur->u32_max_value && 15859 old->s32_min_value <= cur->s32_min_value && 15860 old->s32_max_value >= cur->s32_max_value; 15861 } 15862 15863 /* If in the old state two registers had the same id, then they need to have 15864 * the same id in the new state as well. But that id could be different from 15865 * the old state, so we need to track the mapping from old to new ids. 15866 * Once we have seen that, say, a reg with old id 5 had new id 9, any subsequent 15867 * regs with old id 5 must also have new id 9 for the new state to be safe. But 15868 * regs with a different old id could still have new id 9, we don't care about 15869 * that. 15870 * So we look through our idmap to see if this old id has been seen before. If 15871 * so, we require the new id to match; otherwise, we add the id pair to the map. 15872 */ 15873 static bool check_ids(u32 old_id, u32 cur_id, struct bpf_idmap *idmap) 15874 { 15875 struct bpf_id_pair *map = idmap->map; 15876 unsigned int i; 15877 15878 /* either both IDs should be set or both should be zero */ 15879 if (!!old_id != !!cur_id) 15880 return false; 15881 15882 if (old_id == 0) /* cur_id == 0 as well */ 15883 return true; 15884 15885 for (i = 0; i < BPF_ID_MAP_SIZE; i++) { 15886 if (!map[i].old) { 15887 /* Reached an empty slot; haven't seen this id before */ 15888 map[i].old = old_id; 15889 map[i].cur = cur_id; 15890 return true; 15891 } 15892 if (map[i].old == old_id) 15893 return map[i].cur == cur_id; 15894 if (map[i].cur == cur_id) 15895 return false; 15896 } 15897 /* We ran out of idmap slots, which should be impossible */ 15898 WARN_ON_ONCE(1); 15899 return false; 15900 } 15901 15902 /* Similar to check_ids(), but allocate a unique temporary ID 15903 * for 'old_id' or 'cur_id' of zero. 15904 * This makes pairs like '0 vs unique ID', 'unique ID vs 0' valid. 15905 */ 15906 static bool check_scalar_ids(u32 old_id, u32 cur_id, struct bpf_idmap *idmap) 15907 { 15908 old_id = old_id ? old_id : ++idmap->tmp_id_gen; 15909 cur_id = cur_id ? cur_id : ++idmap->tmp_id_gen; 15910 15911 return check_ids(old_id, cur_id, idmap); 15912 } 15913 15914 static void clean_func_state(struct bpf_verifier_env *env, 15915 struct bpf_func_state *st) 15916 { 15917 enum bpf_reg_liveness live; 15918 int i, j; 15919 15920 for (i = 0; i < BPF_REG_FP; i++) { 15921 live = st->regs[i].live; 15922 /* liveness must not touch this register anymore */ 15923 st->regs[i].live |= REG_LIVE_DONE; 15924 if (!(live & REG_LIVE_READ)) 15925 /* since the register is unused, clear its state 15926 * to make further comparison simpler 15927 */ 15928 __mark_reg_not_init(env, &st->regs[i]); 15929 } 15930 15931 for (i = 0; i < st->allocated_stack / BPF_REG_SIZE; i++) { 15932 live = st->stack[i].spilled_ptr.live; 15933 /* liveness must not touch this stack slot anymore */ 15934 st->stack[i].spilled_ptr.live |= REG_LIVE_DONE; 15935 if (!(live & REG_LIVE_READ)) { 15936 __mark_reg_not_init(env, &st->stack[i].spilled_ptr); 15937 for (j = 0; j < BPF_REG_SIZE; j++) 15938 st->stack[i].slot_type[j] = STACK_INVALID; 15939 } 15940 } 15941 } 15942 15943 static void clean_verifier_state(struct bpf_verifier_env *env, 15944 struct bpf_verifier_state *st) 15945 { 15946 int i; 15947 15948 if (st->frame[0]->regs[0].live & REG_LIVE_DONE) 15949 /* all regs in this state in all frames were already marked */ 15950 return; 15951 15952 for (i = 0; i <= st->curframe; i++) 15953 clean_func_state(env, st->frame[i]); 15954 } 15955 15956 /* the parentage chains form a tree. 15957 * the verifier states are added to state lists at given insn and 15958 * pushed into state stack for future exploration. 15959 * when the verifier reaches bpf_exit insn some of the verifer states 15960 * stored in the state lists have their final liveness state already, 15961 * but a lot of states will get revised from liveness point of view when 15962 * the verifier explores other branches. 15963 * Example: 15964 * 1: r0 = 1 15965 * 2: if r1 == 100 goto pc+1 15966 * 3: r0 = 2 15967 * 4: exit 15968 * when the verifier reaches exit insn the register r0 in the state list of 15969 * insn 2 will be seen as !REG_LIVE_READ. Then the verifier pops the other_branch 15970 * of insn 2 and goes exploring further. At the insn 4 it will walk the 15971 * parentage chain from insn 4 into insn 2 and will mark r0 as REG_LIVE_READ. 15972 * 15973 * Since the verifier pushes the branch states as it sees them while exploring 15974 * the program the condition of walking the branch instruction for the second 15975 * time means that all states below this branch were already explored and 15976 * their final liveness marks are already propagated. 15977 * Hence when the verifier completes the search of state list in is_state_visited() 15978 * we can call this clean_live_states() function to mark all liveness states 15979 * as REG_LIVE_DONE to indicate that 'parent' pointers of 'struct bpf_reg_state' 15980 * will not be used. 15981 * This function also clears the registers and stack for states that !READ 15982 * to simplify state merging. 15983 * 15984 * Important note here that walking the same branch instruction in the callee 15985 * doesn't meant that the states are DONE. The verifier has to compare 15986 * the callsites 15987 */ 15988 static void clean_live_states(struct bpf_verifier_env *env, int insn, 15989 struct bpf_verifier_state *cur) 15990 { 15991 struct bpf_verifier_state_list *sl; 15992 15993 sl = *explored_state(env, insn); 15994 while (sl) { 15995 if (sl->state.branches) 15996 goto next; 15997 if (sl->state.insn_idx != insn || 15998 !same_callsites(&sl->state, cur)) 15999 goto next; 16000 clean_verifier_state(env, &sl->state); 16001 next: 16002 sl = sl->next; 16003 } 16004 } 16005 16006 static bool regs_exact(const struct bpf_reg_state *rold, 16007 const struct bpf_reg_state *rcur, 16008 struct bpf_idmap *idmap) 16009 { 16010 return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 && 16011 check_ids(rold->id, rcur->id, idmap) && 16012 check_ids(rold->ref_obj_id, rcur->ref_obj_id, idmap); 16013 } 16014 16015 /* Returns true if (rold safe implies rcur safe) */ 16016 static bool regsafe(struct bpf_verifier_env *env, struct bpf_reg_state *rold, 16017 struct bpf_reg_state *rcur, struct bpf_idmap *idmap, bool exact) 16018 { 16019 if (exact) 16020 return regs_exact(rold, rcur, idmap); 16021 16022 if (!(rold->live & REG_LIVE_READ)) 16023 /* explored state didn't use this */ 16024 return true; 16025 if (rold->type == NOT_INIT) 16026 /* explored state can't have used this */ 16027 return true; 16028 if (rcur->type == NOT_INIT) 16029 return false; 16030 16031 /* Enforce that register types have to match exactly, including their 16032 * modifiers (like PTR_MAYBE_NULL, MEM_RDONLY, etc), as a general 16033 * rule. 16034 * 16035 * One can make a point that using a pointer register as unbounded 16036 * SCALAR would be technically acceptable, but this could lead to 16037 * pointer leaks because scalars are allowed to leak while pointers 16038 * are not. We could make this safe in special cases if root is 16039 * calling us, but it's probably not worth the hassle. 16040 * 16041 * Also, register types that are *not* MAYBE_NULL could technically be 16042 * safe to use as their MAYBE_NULL variants (e.g., PTR_TO_MAP_VALUE 16043 * is safe to be used as PTR_TO_MAP_VALUE_OR_NULL, provided both point 16044 * to the same map). 16045 * However, if the old MAYBE_NULL register then got NULL checked, 16046 * doing so could have affected others with the same id, and we can't 16047 * check for that because we lost the id when we converted to 16048 * a non-MAYBE_NULL variant. 16049 * So, as a general rule we don't allow mixing MAYBE_NULL and 16050 * non-MAYBE_NULL registers as well. 16051 */ 16052 if (rold->type != rcur->type) 16053 return false; 16054 16055 switch (base_type(rold->type)) { 16056 case SCALAR_VALUE: 16057 if (env->explore_alu_limits) { 16058 /* explore_alu_limits disables tnum_in() and range_within() 16059 * logic and requires everything to be strict 16060 */ 16061 return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 && 16062 check_scalar_ids(rold->id, rcur->id, idmap); 16063 } 16064 if (!rold->precise) 16065 return true; 16066 /* Why check_ids() for scalar registers? 16067 * 16068 * Consider the following BPF code: 16069 * 1: r6 = ... unbound scalar, ID=a ... 16070 * 2: r7 = ... unbound scalar, ID=b ... 16071 * 3: if (r6 > r7) goto +1 16072 * 4: r6 = r7 16073 * 5: if (r6 > X) goto ... 16074 * 6: ... memory operation using r7 ... 16075 * 16076 * First verification path is [1-6]: 16077 * - at (4) same bpf_reg_state::id (b) would be assigned to r6 and r7; 16078 * - at (5) r6 would be marked <= X, find_equal_scalars() would also mark 16079 * r7 <= X, because r6 and r7 share same id. 16080 * Next verification path is [1-4, 6]. 16081 * 16082 * Instruction (6) would be reached in two states: 16083 * I. r6{.id=b}, r7{.id=b} via path 1-6; 16084 * II. r6{.id=a}, r7{.id=b} via path 1-4, 6. 16085 * 16086 * Use check_ids() to distinguish these states. 16087 * --- 16088 * Also verify that new value satisfies old value range knowledge. 16089 */ 16090 return range_within(rold, rcur) && 16091 tnum_in(rold->var_off, rcur->var_off) && 16092 check_scalar_ids(rold->id, rcur->id, idmap); 16093 case PTR_TO_MAP_KEY: 16094 case PTR_TO_MAP_VALUE: 16095 case PTR_TO_MEM: 16096 case PTR_TO_BUF: 16097 case PTR_TO_TP_BUFFER: 16098 /* If the new min/max/var_off satisfy the old ones and 16099 * everything else matches, we are OK. 16100 */ 16101 return memcmp(rold, rcur, offsetof(struct bpf_reg_state, var_off)) == 0 && 16102 range_within(rold, rcur) && 16103 tnum_in(rold->var_off, rcur->var_off) && 16104 check_ids(rold->id, rcur->id, idmap) && 16105 check_ids(rold->ref_obj_id, rcur->ref_obj_id, idmap); 16106 case PTR_TO_PACKET_META: 16107 case PTR_TO_PACKET: 16108 /* We must have at least as much range as the old ptr 16109 * did, so that any accesses which were safe before are 16110 * still safe. This is true even if old range < old off, 16111 * since someone could have accessed through (ptr - k), or 16112 * even done ptr -= k in a register, to get a safe access. 16113 */ 16114 if (rold->range > rcur->range) 16115 return false; 16116 /* If the offsets don't match, we can't trust our alignment; 16117 * nor can we be sure that we won't fall out of range. 16118 */ 16119 if (rold->off != rcur->off) 16120 return false; 16121 /* id relations must be preserved */ 16122 if (!check_ids(rold->id, rcur->id, idmap)) 16123 return false; 16124 /* new val must satisfy old val knowledge */ 16125 return range_within(rold, rcur) && 16126 tnum_in(rold->var_off, rcur->var_off); 16127 case PTR_TO_STACK: 16128 /* two stack pointers are equal only if they're pointing to 16129 * the same stack frame, since fp-8 in foo != fp-8 in bar 16130 */ 16131 return regs_exact(rold, rcur, idmap) && rold->frameno == rcur->frameno; 16132 default: 16133 return regs_exact(rold, rcur, idmap); 16134 } 16135 } 16136 16137 static bool stacksafe(struct bpf_verifier_env *env, struct bpf_func_state *old, 16138 struct bpf_func_state *cur, struct bpf_idmap *idmap, bool exact) 16139 { 16140 int i, spi; 16141 16142 /* walk slots of the explored stack and ignore any additional 16143 * slots in the current stack, since explored(safe) state 16144 * didn't use them 16145 */ 16146 for (i = 0; i < old->allocated_stack; i++) { 16147 struct bpf_reg_state *old_reg, *cur_reg; 16148 16149 spi = i / BPF_REG_SIZE; 16150 16151 if (exact && 16152 (i >= cur->allocated_stack || 16153 old->stack[spi].slot_type[i % BPF_REG_SIZE] != 16154 cur->stack[spi].slot_type[i % BPF_REG_SIZE])) 16155 return false; 16156 16157 if (!(old->stack[spi].spilled_ptr.live & REG_LIVE_READ) && !exact) { 16158 i += BPF_REG_SIZE - 1; 16159 /* explored state didn't use this */ 16160 continue; 16161 } 16162 16163 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_INVALID) 16164 continue; 16165 16166 if (env->allow_uninit_stack && 16167 old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC) 16168 continue; 16169 16170 /* explored stack has more populated slots than current stack 16171 * and these slots were used 16172 */ 16173 if (i >= cur->allocated_stack) 16174 return false; 16175 16176 /* if old state was safe with misc data in the stack 16177 * it will be safe with zero-initialized stack. 16178 * The opposite is not true 16179 */ 16180 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC && 16181 cur->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_ZERO) 16182 continue; 16183 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] != 16184 cur->stack[spi].slot_type[i % BPF_REG_SIZE]) 16185 /* Ex: old explored (safe) state has STACK_SPILL in 16186 * this stack slot, but current has STACK_MISC -> 16187 * this verifier states are not equivalent, 16188 * return false to continue verification of this path 16189 */ 16190 return false; 16191 if (i % BPF_REG_SIZE != BPF_REG_SIZE - 1) 16192 continue; 16193 /* Both old and cur are having same slot_type */ 16194 switch (old->stack[spi].slot_type[BPF_REG_SIZE - 1]) { 16195 case STACK_SPILL: 16196 /* when explored and current stack slot are both storing 16197 * spilled registers, check that stored pointers types 16198 * are the same as well. 16199 * Ex: explored safe path could have stored 16200 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -8} 16201 * but current path has stored: 16202 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -16} 16203 * such verifier states are not equivalent. 16204 * return false to continue verification of this path 16205 */ 16206 if (!regsafe(env, &old->stack[spi].spilled_ptr, 16207 &cur->stack[spi].spilled_ptr, idmap, exact)) 16208 return false; 16209 break; 16210 case STACK_DYNPTR: 16211 old_reg = &old->stack[spi].spilled_ptr; 16212 cur_reg = &cur->stack[spi].spilled_ptr; 16213 if (old_reg->dynptr.type != cur_reg->dynptr.type || 16214 old_reg->dynptr.first_slot != cur_reg->dynptr.first_slot || 16215 !check_ids(old_reg->ref_obj_id, cur_reg->ref_obj_id, idmap)) 16216 return false; 16217 break; 16218 case STACK_ITER: 16219 old_reg = &old->stack[spi].spilled_ptr; 16220 cur_reg = &cur->stack[spi].spilled_ptr; 16221 /* iter.depth is not compared between states as it 16222 * doesn't matter for correctness and would otherwise 16223 * prevent convergence; we maintain it only to prevent 16224 * infinite loop check triggering, see 16225 * iter_active_depths_differ() 16226 */ 16227 if (old_reg->iter.btf != cur_reg->iter.btf || 16228 old_reg->iter.btf_id != cur_reg->iter.btf_id || 16229 old_reg->iter.state != cur_reg->iter.state || 16230 /* ignore {old_reg,cur_reg}->iter.depth, see above */ 16231 !check_ids(old_reg->ref_obj_id, cur_reg->ref_obj_id, idmap)) 16232 return false; 16233 break; 16234 case STACK_MISC: 16235 case STACK_ZERO: 16236 case STACK_INVALID: 16237 continue; 16238 /* Ensure that new unhandled slot types return false by default */ 16239 default: 16240 return false; 16241 } 16242 } 16243 return true; 16244 } 16245 16246 static bool refsafe(struct bpf_func_state *old, struct bpf_func_state *cur, 16247 struct bpf_idmap *idmap) 16248 { 16249 int i; 16250 16251 if (old->acquired_refs != cur->acquired_refs) 16252 return false; 16253 16254 for (i = 0; i < old->acquired_refs; i++) { 16255 if (!check_ids(old->refs[i].id, cur->refs[i].id, idmap)) 16256 return false; 16257 } 16258 16259 return true; 16260 } 16261 16262 /* compare two verifier states 16263 * 16264 * all states stored in state_list are known to be valid, since 16265 * verifier reached 'bpf_exit' instruction through them 16266 * 16267 * this function is called when verifier exploring different branches of 16268 * execution popped from the state stack. If it sees an old state that has 16269 * more strict register state and more strict stack state then this execution 16270 * branch doesn't need to be explored further, since verifier already 16271 * concluded that more strict state leads to valid finish. 16272 * 16273 * Therefore two states are equivalent if register state is more conservative 16274 * and explored stack state is more conservative than the current one. 16275 * Example: 16276 * explored current 16277 * (slot1=INV slot2=MISC) == (slot1=MISC slot2=MISC) 16278 * (slot1=MISC slot2=MISC) != (slot1=INV slot2=MISC) 16279 * 16280 * In other words if current stack state (one being explored) has more 16281 * valid slots than old one that already passed validation, it means 16282 * the verifier can stop exploring and conclude that current state is valid too 16283 * 16284 * Similarly with registers. If explored state has register type as invalid 16285 * whereas register type in current state is meaningful, it means that 16286 * the current state will reach 'bpf_exit' instruction safely 16287 */ 16288 static bool func_states_equal(struct bpf_verifier_env *env, struct bpf_func_state *old, 16289 struct bpf_func_state *cur, bool exact) 16290 { 16291 int i; 16292 16293 if (old->callback_depth > cur->callback_depth) 16294 return false; 16295 16296 for (i = 0; i < MAX_BPF_REG; i++) 16297 if (!regsafe(env, &old->regs[i], &cur->regs[i], 16298 &env->idmap_scratch, exact)) 16299 return false; 16300 16301 if (!stacksafe(env, old, cur, &env->idmap_scratch, exact)) 16302 return false; 16303 16304 if (!refsafe(old, cur, &env->idmap_scratch)) 16305 return false; 16306 16307 return true; 16308 } 16309 16310 static void reset_idmap_scratch(struct bpf_verifier_env *env) 16311 { 16312 env->idmap_scratch.tmp_id_gen = env->id_gen; 16313 memset(&env->idmap_scratch.map, 0, sizeof(env->idmap_scratch.map)); 16314 } 16315 16316 static bool states_equal(struct bpf_verifier_env *env, 16317 struct bpf_verifier_state *old, 16318 struct bpf_verifier_state *cur, 16319 bool exact) 16320 { 16321 int i; 16322 16323 if (old->curframe != cur->curframe) 16324 return false; 16325 16326 reset_idmap_scratch(env); 16327 16328 /* Verification state from speculative execution simulation 16329 * must never prune a non-speculative execution one. 16330 */ 16331 if (old->speculative && !cur->speculative) 16332 return false; 16333 16334 if (old->active_lock.ptr != cur->active_lock.ptr) 16335 return false; 16336 16337 /* Old and cur active_lock's have to be either both present 16338 * or both absent. 16339 */ 16340 if (!!old->active_lock.id != !!cur->active_lock.id) 16341 return false; 16342 16343 if (old->active_lock.id && 16344 !check_ids(old->active_lock.id, cur->active_lock.id, &env->idmap_scratch)) 16345 return false; 16346 16347 if (old->active_rcu_lock != cur->active_rcu_lock) 16348 return false; 16349 16350 /* for states to be equal callsites have to be the same 16351 * and all frame states need to be equivalent 16352 */ 16353 for (i = 0; i <= old->curframe; i++) { 16354 if (old->frame[i]->callsite != cur->frame[i]->callsite) 16355 return false; 16356 if (!func_states_equal(env, old->frame[i], cur->frame[i], exact)) 16357 return false; 16358 } 16359 return true; 16360 } 16361 16362 /* Return 0 if no propagation happened. Return negative error code if error 16363 * happened. Otherwise, return the propagated bit. 16364 */ 16365 static int propagate_liveness_reg(struct bpf_verifier_env *env, 16366 struct bpf_reg_state *reg, 16367 struct bpf_reg_state *parent_reg) 16368 { 16369 u8 parent_flag = parent_reg->live & REG_LIVE_READ; 16370 u8 flag = reg->live & REG_LIVE_READ; 16371 int err; 16372 16373 /* When comes here, read flags of PARENT_REG or REG could be any of 16374 * REG_LIVE_READ64, REG_LIVE_READ32, REG_LIVE_NONE. There is no need 16375 * of propagation if PARENT_REG has strongest REG_LIVE_READ64. 16376 */ 16377 if (parent_flag == REG_LIVE_READ64 || 16378 /* Or if there is no read flag from REG. */ 16379 !flag || 16380 /* Or if the read flag from REG is the same as PARENT_REG. */ 16381 parent_flag == flag) 16382 return 0; 16383 16384 err = mark_reg_read(env, reg, parent_reg, flag); 16385 if (err) 16386 return err; 16387 16388 return flag; 16389 } 16390 16391 /* A write screens off any subsequent reads; but write marks come from the 16392 * straight-line code between a state and its parent. When we arrive at an 16393 * equivalent state (jump target or such) we didn't arrive by the straight-line 16394 * code, so read marks in the state must propagate to the parent regardless 16395 * of the state's write marks. That's what 'parent == state->parent' comparison 16396 * in mark_reg_read() is for. 16397 */ 16398 static int propagate_liveness(struct bpf_verifier_env *env, 16399 const struct bpf_verifier_state *vstate, 16400 struct bpf_verifier_state *vparent) 16401 { 16402 struct bpf_reg_state *state_reg, *parent_reg; 16403 struct bpf_func_state *state, *parent; 16404 int i, frame, err = 0; 16405 16406 if (vparent->curframe != vstate->curframe) { 16407 WARN(1, "propagate_live: parent frame %d current frame %d\n", 16408 vparent->curframe, vstate->curframe); 16409 return -EFAULT; 16410 } 16411 /* Propagate read liveness of registers... */ 16412 BUILD_BUG_ON(BPF_REG_FP + 1 != MAX_BPF_REG); 16413 for (frame = 0; frame <= vstate->curframe; frame++) { 16414 parent = vparent->frame[frame]; 16415 state = vstate->frame[frame]; 16416 parent_reg = parent->regs; 16417 state_reg = state->regs; 16418 /* We don't need to worry about FP liveness, it's read-only */ 16419 for (i = frame < vstate->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++) { 16420 err = propagate_liveness_reg(env, &state_reg[i], 16421 &parent_reg[i]); 16422 if (err < 0) 16423 return err; 16424 if (err == REG_LIVE_READ64) 16425 mark_insn_zext(env, &parent_reg[i]); 16426 } 16427 16428 /* Propagate stack slots. */ 16429 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE && 16430 i < parent->allocated_stack / BPF_REG_SIZE; i++) { 16431 parent_reg = &parent->stack[i].spilled_ptr; 16432 state_reg = &state->stack[i].spilled_ptr; 16433 err = propagate_liveness_reg(env, state_reg, 16434 parent_reg); 16435 if (err < 0) 16436 return err; 16437 } 16438 } 16439 return 0; 16440 } 16441 16442 /* find precise scalars in the previous equivalent state and 16443 * propagate them into the current state 16444 */ 16445 static int propagate_precision(struct bpf_verifier_env *env, 16446 const struct bpf_verifier_state *old) 16447 { 16448 struct bpf_reg_state *state_reg; 16449 struct bpf_func_state *state; 16450 int i, err = 0, fr; 16451 bool first; 16452 16453 for (fr = old->curframe; fr >= 0; fr--) { 16454 state = old->frame[fr]; 16455 state_reg = state->regs; 16456 first = true; 16457 for (i = 0; i < BPF_REG_FP; i++, state_reg++) { 16458 if (state_reg->type != SCALAR_VALUE || 16459 !state_reg->precise || 16460 !(state_reg->live & REG_LIVE_READ)) 16461 continue; 16462 if (env->log.level & BPF_LOG_LEVEL2) { 16463 if (first) 16464 verbose(env, "frame %d: propagating r%d", fr, i); 16465 else 16466 verbose(env, ",r%d", i); 16467 } 16468 bt_set_frame_reg(&env->bt, fr, i); 16469 first = false; 16470 } 16471 16472 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) { 16473 if (!is_spilled_reg(&state->stack[i])) 16474 continue; 16475 state_reg = &state->stack[i].spilled_ptr; 16476 if (state_reg->type != SCALAR_VALUE || 16477 !state_reg->precise || 16478 !(state_reg->live & REG_LIVE_READ)) 16479 continue; 16480 if (env->log.level & BPF_LOG_LEVEL2) { 16481 if (first) 16482 verbose(env, "frame %d: propagating fp%d", 16483 fr, (-i - 1) * BPF_REG_SIZE); 16484 else 16485 verbose(env, ",fp%d", (-i - 1) * BPF_REG_SIZE); 16486 } 16487 bt_set_frame_slot(&env->bt, fr, i); 16488 first = false; 16489 } 16490 if (!first) 16491 verbose(env, "\n"); 16492 } 16493 16494 err = mark_chain_precision_batch(env); 16495 if (err < 0) 16496 return err; 16497 16498 return 0; 16499 } 16500 16501 static bool states_maybe_looping(struct bpf_verifier_state *old, 16502 struct bpf_verifier_state *cur) 16503 { 16504 struct bpf_func_state *fold, *fcur; 16505 int i, fr = cur->curframe; 16506 16507 if (old->curframe != fr) 16508 return false; 16509 16510 fold = old->frame[fr]; 16511 fcur = cur->frame[fr]; 16512 for (i = 0; i < MAX_BPF_REG; i++) 16513 if (memcmp(&fold->regs[i], &fcur->regs[i], 16514 offsetof(struct bpf_reg_state, parent))) 16515 return false; 16516 return true; 16517 } 16518 16519 static bool is_iter_next_insn(struct bpf_verifier_env *env, int insn_idx) 16520 { 16521 return env->insn_aux_data[insn_idx].is_iter_next; 16522 } 16523 16524 /* is_state_visited() handles iter_next() (see process_iter_next_call() for 16525 * terminology) calls specially: as opposed to bounded BPF loops, it *expects* 16526 * states to match, which otherwise would look like an infinite loop. So while 16527 * iter_next() calls are taken care of, we still need to be careful and 16528 * prevent erroneous and too eager declaration of "ininite loop", when 16529 * iterators are involved. 16530 * 16531 * Here's a situation in pseudo-BPF assembly form: 16532 * 16533 * 0: again: ; set up iter_next() call args 16534 * 1: r1 = &it ; <CHECKPOINT HERE> 16535 * 2: call bpf_iter_num_next ; this is iter_next() call 16536 * 3: if r0 == 0 goto done 16537 * 4: ... something useful here ... 16538 * 5: goto again ; another iteration 16539 * 6: done: 16540 * 7: r1 = &it 16541 * 8: call bpf_iter_num_destroy ; clean up iter state 16542 * 9: exit 16543 * 16544 * This is a typical loop. Let's assume that we have a prune point at 1:, 16545 * before we get to `call bpf_iter_num_next` (e.g., because of that `goto 16546 * again`, assuming other heuristics don't get in a way). 16547 * 16548 * When we first time come to 1:, let's say we have some state X. We proceed 16549 * to 2:, fork states, enqueue ACTIVE, validate NULL case successfully, exit. 16550 * Now we come back to validate that forked ACTIVE state. We proceed through 16551 * 3-5, come to goto, jump to 1:. Let's assume our state didn't change, so we 16552 * are converging. But the problem is that we don't know that yet, as this 16553 * convergence has to happen at iter_next() call site only. So if nothing is 16554 * done, at 1: verifier will use bounded loop logic and declare infinite 16555 * looping (and would be *technically* correct, if not for iterator's 16556 * "eventual sticky NULL" contract, see process_iter_next_call()). But we 16557 * don't want that. So what we do in process_iter_next_call() when we go on 16558 * another ACTIVE iteration, we bump slot->iter.depth, to mark that it's 16559 * a different iteration. So when we suspect an infinite loop, we additionally 16560 * check if any of the *ACTIVE* iterator states depths differ. If yes, we 16561 * pretend we are not looping and wait for next iter_next() call. 16562 * 16563 * This only applies to ACTIVE state. In DRAINED state we don't expect to 16564 * loop, because that would actually mean infinite loop, as DRAINED state is 16565 * "sticky", and so we'll keep returning into the same instruction with the 16566 * same state (at least in one of possible code paths). 16567 * 16568 * This approach allows to keep infinite loop heuristic even in the face of 16569 * active iterator. E.g., C snippet below is and will be detected as 16570 * inifintely looping: 16571 * 16572 * struct bpf_iter_num it; 16573 * int *p, x; 16574 * 16575 * bpf_iter_num_new(&it, 0, 10); 16576 * while ((p = bpf_iter_num_next(&t))) { 16577 * x = p; 16578 * while (x--) {} // <<-- infinite loop here 16579 * } 16580 * 16581 */ 16582 static bool iter_active_depths_differ(struct bpf_verifier_state *old, struct bpf_verifier_state *cur) 16583 { 16584 struct bpf_reg_state *slot, *cur_slot; 16585 struct bpf_func_state *state; 16586 int i, fr; 16587 16588 for (fr = old->curframe; fr >= 0; fr--) { 16589 state = old->frame[fr]; 16590 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) { 16591 if (state->stack[i].slot_type[0] != STACK_ITER) 16592 continue; 16593 16594 slot = &state->stack[i].spilled_ptr; 16595 if (slot->iter.state != BPF_ITER_STATE_ACTIVE) 16596 continue; 16597 16598 cur_slot = &cur->frame[fr]->stack[i].spilled_ptr; 16599 if (cur_slot->iter.depth != slot->iter.depth) 16600 return true; 16601 } 16602 } 16603 return false; 16604 } 16605 16606 static int is_state_visited(struct bpf_verifier_env *env, int insn_idx) 16607 { 16608 struct bpf_verifier_state_list *new_sl; 16609 struct bpf_verifier_state_list *sl, **pprev; 16610 struct bpf_verifier_state *cur = env->cur_state, *new, *loop_entry; 16611 int i, j, n, err, states_cnt = 0; 16612 bool force_new_state, add_new_state, force_exact; 16613 16614 force_new_state = env->test_state_freq || is_force_checkpoint(env, insn_idx) || 16615 /* Avoid accumulating infinitely long jmp history */ 16616 cur->jmp_history_cnt > 40; 16617 16618 /* bpf progs typically have pruning point every 4 instructions 16619 * http://vger.kernel.org/bpfconf2019.html#session-1 16620 * Do not add new state for future pruning if the verifier hasn't seen 16621 * at least 2 jumps and at least 8 instructions. 16622 * This heuristics helps decrease 'total_states' and 'peak_states' metric. 16623 * In tests that amounts to up to 50% reduction into total verifier 16624 * memory consumption and 20% verifier time speedup. 16625 */ 16626 add_new_state = force_new_state; 16627 if (env->jmps_processed - env->prev_jmps_processed >= 2 && 16628 env->insn_processed - env->prev_insn_processed >= 8) 16629 add_new_state = true; 16630 16631 pprev = explored_state(env, insn_idx); 16632 sl = *pprev; 16633 16634 clean_live_states(env, insn_idx, cur); 16635 16636 while (sl) { 16637 states_cnt++; 16638 if (sl->state.insn_idx != insn_idx) 16639 goto next; 16640 16641 if (sl->state.branches) { 16642 struct bpf_func_state *frame = sl->state.frame[sl->state.curframe]; 16643 16644 if (frame->in_async_callback_fn && 16645 frame->async_entry_cnt != cur->frame[cur->curframe]->async_entry_cnt) { 16646 /* Different async_entry_cnt means that the verifier is 16647 * processing another entry into async callback. 16648 * Seeing the same state is not an indication of infinite 16649 * loop or infinite recursion. 16650 * But finding the same state doesn't mean that it's safe 16651 * to stop processing the current state. The previous state 16652 * hasn't yet reached bpf_exit, since state.branches > 0. 16653 * Checking in_async_callback_fn alone is not enough either. 16654 * Since the verifier still needs to catch infinite loops 16655 * inside async callbacks. 16656 */ 16657 goto skip_inf_loop_check; 16658 } 16659 /* BPF open-coded iterators loop detection is special. 16660 * states_maybe_looping() logic is too simplistic in detecting 16661 * states that *might* be equivalent, because it doesn't know 16662 * about ID remapping, so don't even perform it. 16663 * See process_iter_next_call() and iter_active_depths_differ() 16664 * for overview of the logic. When current and one of parent 16665 * states are detected as equivalent, it's a good thing: we prove 16666 * convergence and can stop simulating further iterations. 16667 * It's safe to assume that iterator loop will finish, taking into 16668 * account iter_next() contract of eventually returning 16669 * sticky NULL result. 16670 * 16671 * Note, that states have to be compared exactly in this case because 16672 * read and precision marks might not be finalized inside the loop. 16673 * E.g. as in the program below: 16674 * 16675 * 1. r7 = -16 16676 * 2. r6 = bpf_get_prandom_u32() 16677 * 3. while (bpf_iter_num_next(&fp[-8])) { 16678 * 4. if (r6 != 42) { 16679 * 5. r7 = -32 16680 * 6. r6 = bpf_get_prandom_u32() 16681 * 7. continue 16682 * 8. } 16683 * 9. r0 = r10 16684 * 10. r0 += r7 16685 * 11. r8 = *(u64 *)(r0 + 0) 16686 * 12. r6 = bpf_get_prandom_u32() 16687 * 13. } 16688 * 16689 * Here verifier would first visit path 1-3, create a checkpoint at 3 16690 * with r7=-16, continue to 4-7,3. Existing checkpoint at 3 does 16691 * not have read or precision mark for r7 yet, thus inexact states 16692 * comparison would discard current state with r7=-32 16693 * => unsafe memory access at 11 would not be caught. 16694 */ 16695 if (is_iter_next_insn(env, insn_idx)) { 16696 if (states_equal(env, &sl->state, cur, true)) { 16697 struct bpf_func_state *cur_frame; 16698 struct bpf_reg_state *iter_state, *iter_reg; 16699 int spi; 16700 16701 cur_frame = cur->frame[cur->curframe]; 16702 /* btf_check_iter_kfuncs() enforces that 16703 * iter state pointer is always the first arg 16704 */ 16705 iter_reg = &cur_frame->regs[BPF_REG_1]; 16706 /* current state is valid due to states_equal(), 16707 * so we can assume valid iter and reg state, 16708 * no need for extra (re-)validations 16709 */ 16710 spi = __get_spi(iter_reg->off + iter_reg->var_off.value); 16711 iter_state = &func(env, iter_reg)->stack[spi].spilled_ptr; 16712 if (iter_state->iter.state == BPF_ITER_STATE_ACTIVE) { 16713 update_loop_entry(cur, &sl->state); 16714 goto hit; 16715 } 16716 } 16717 goto skip_inf_loop_check; 16718 } 16719 if (calls_callback(env, insn_idx)) { 16720 if (states_equal(env, &sl->state, cur, true)) 16721 goto hit; 16722 goto skip_inf_loop_check; 16723 } 16724 /* attempt to detect infinite loop to avoid unnecessary doomed work */ 16725 if (states_maybe_looping(&sl->state, cur) && 16726 states_equal(env, &sl->state, cur, false) && 16727 !iter_active_depths_differ(&sl->state, cur) && 16728 sl->state.callback_unroll_depth == cur->callback_unroll_depth) { 16729 verbose_linfo(env, insn_idx, "; "); 16730 verbose(env, "infinite loop detected at insn %d\n", insn_idx); 16731 verbose(env, "cur state:"); 16732 print_verifier_state(env, cur->frame[cur->curframe], true); 16733 verbose(env, "old state:"); 16734 print_verifier_state(env, sl->state.frame[cur->curframe], true); 16735 return -EINVAL; 16736 } 16737 /* if the verifier is processing a loop, avoid adding new state 16738 * too often, since different loop iterations have distinct 16739 * states and may not help future pruning. 16740 * This threshold shouldn't be too low to make sure that 16741 * a loop with large bound will be rejected quickly. 16742 * The most abusive loop will be: 16743 * r1 += 1 16744 * if r1 < 1000000 goto pc-2 16745 * 1M insn_procssed limit / 100 == 10k peak states. 16746 * This threshold shouldn't be too high either, since states 16747 * at the end of the loop are likely to be useful in pruning. 16748 */ 16749 skip_inf_loop_check: 16750 if (!force_new_state && 16751 env->jmps_processed - env->prev_jmps_processed < 20 && 16752 env->insn_processed - env->prev_insn_processed < 100) 16753 add_new_state = false; 16754 goto miss; 16755 } 16756 /* If sl->state is a part of a loop and this loop's entry is a part of 16757 * current verification path then states have to be compared exactly. 16758 * 'force_exact' is needed to catch the following case: 16759 * 16760 * initial Here state 'succ' was processed first, 16761 * | it was eventually tracked to produce a 16762 * V state identical to 'hdr'. 16763 * .---------> hdr All branches from 'succ' had been explored 16764 * | | and thus 'succ' has its .branches == 0. 16765 * | V 16766 * | .------... Suppose states 'cur' and 'succ' correspond 16767 * | | | to the same instruction + callsites. 16768 * | V V In such case it is necessary to check 16769 * | ... ... if 'succ' and 'cur' are states_equal(). 16770 * | | | If 'succ' and 'cur' are a part of the 16771 * | V V same loop exact flag has to be set. 16772 * | succ <- cur To check if that is the case, verify 16773 * | | if loop entry of 'succ' is in current 16774 * | V DFS path. 16775 * | ... 16776 * | | 16777 * '----' 16778 * 16779 * Additional details are in the comment before get_loop_entry(). 16780 */ 16781 loop_entry = get_loop_entry(&sl->state); 16782 force_exact = loop_entry && loop_entry->branches > 0; 16783 if (states_equal(env, &sl->state, cur, force_exact)) { 16784 if (force_exact) 16785 update_loop_entry(cur, loop_entry); 16786 hit: 16787 sl->hit_cnt++; 16788 /* reached equivalent register/stack state, 16789 * prune the search. 16790 * Registers read by the continuation are read by us. 16791 * If we have any write marks in env->cur_state, they 16792 * will prevent corresponding reads in the continuation 16793 * from reaching our parent (an explored_state). Our 16794 * own state will get the read marks recorded, but 16795 * they'll be immediately forgotten as we're pruning 16796 * this state and will pop a new one. 16797 */ 16798 err = propagate_liveness(env, &sl->state, cur); 16799 16800 /* if previous state reached the exit with precision and 16801 * current state is equivalent to it (except precsion marks) 16802 * the precision needs to be propagated back in 16803 * the current state. 16804 */ 16805 if (is_jmp_point(env, env->insn_idx)) 16806 err = err ? : push_jmp_history(env, cur, 0); 16807 err = err ? : propagate_precision(env, &sl->state); 16808 if (err) 16809 return err; 16810 return 1; 16811 } 16812 miss: 16813 /* when new state is not going to be added do not increase miss count. 16814 * Otherwise several loop iterations will remove the state 16815 * recorded earlier. The goal of these heuristics is to have 16816 * states from some iterations of the loop (some in the beginning 16817 * and some at the end) to help pruning. 16818 */ 16819 if (add_new_state) 16820 sl->miss_cnt++; 16821 /* heuristic to determine whether this state is beneficial 16822 * to keep checking from state equivalence point of view. 16823 * Higher numbers increase max_states_per_insn and verification time, 16824 * but do not meaningfully decrease insn_processed. 16825 * 'n' controls how many times state could miss before eviction. 16826 * Use bigger 'n' for checkpoints because evicting checkpoint states 16827 * too early would hinder iterator convergence. 16828 */ 16829 n = is_force_checkpoint(env, insn_idx) && sl->state.branches > 0 ? 64 : 3; 16830 if (sl->miss_cnt > sl->hit_cnt * n + n) { 16831 /* the state is unlikely to be useful. Remove it to 16832 * speed up verification 16833 */ 16834 *pprev = sl->next; 16835 if (sl->state.frame[0]->regs[0].live & REG_LIVE_DONE && 16836 !sl->state.used_as_loop_entry) { 16837 u32 br = sl->state.branches; 16838 16839 WARN_ONCE(br, 16840 "BUG live_done but branches_to_explore %d\n", 16841 br); 16842 free_verifier_state(&sl->state, false); 16843 kfree(sl); 16844 env->peak_states--; 16845 } else { 16846 /* cannot free this state, since parentage chain may 16847 * walk it later. Add it for free_list instead to 16848 * be freed at the end of verification 16849 */ 16850 sl->next = env->free_list; 16851 env->free_list = sl; 16852 } 16853 sl = *pprev; 16854 continue; 16855 } 16856 next: 16857 pprev = &sl->next; 16858 sl = *pprev; 16859 } 16860 16861 if (env->max_states_per_insn < states_cnt) 16862 env->max_states_per_insn = states_cnt; 16863 16864 if (!env->bpf_capable && states_cnt > BPF_COMPLEXITY_LIMIT_STATES) 16865 return 0; 16866 16867 if (!add_new_state) 16868 return 0; 16869 16870 /* There were no equivalent states, remember the current one. 16871 * Technically the current state is not proven to be safe yet, 16872 * but it will either reach outer most bpf_exit (which means it's safe) 16873 * or it will be rejected. When there are no loops the verifier won't be 16874 * seeing this tuple (frame[0].callsite, frame[1].callsite, .. insn_idx) 16875 * again on the way to bpf_exit. 16876 * When looping the sl->state.branches will be > 0 and this state 16877 * will not be considered for equivalence until branches == 0. 16878 */ 16879 new_sl = kzalloc(sizeof(struct bpf_verifier_state_list), GFP_KERNEL); 16880 if (!new_sl) 16881 return -ENOMEM; 16882 env->total_states++; 16883 env->peak_states++; 16884 env->prev_jmps_processed = env->jmps_processed; 16885 env->prev_insn_processed = env->insn_processed; 16886 16887 /* forget precise markings we inherited, see __mark_chain_precision */ 16888 if (env->bpf_capable) 16889 mark_all_scalars_imprecise(env, cur); 16890 16891 /* add new state to the head of linked list */ 16892 new = &new_sl->state; 16893 err = copy_verifier_state(new, cur); 16894 if (err) { 16895 free_verifier_state(new, false); 16896 kfree(new_sl); 16897 return err; 16898 } 16899 new->insn_idx = insn_idx; 16900 WARN_ONCE(new->branches != 1, 16901 "BUG is_state_visited:branches_to_explore=%d insn %d\n", new->branches, insn_idx); 16902 16903 cur->parent = new; 16904 cur->first_insn_idx = insn_idx; 16905 cur->dfs_depth = new->dfs_depth + 1; 16906 clear_jmp_history(cur); 16907 new_sl->next = *explored_state(env, insn_idx); 16908 *explored_state(env, insn_idx) = new_sl; 16909 /* connect new state to parentage chain. Current frame needs all 16910 * registers connected. Only r6 - r9 of the callers are alive (pushed 16911 * to the stack implicitly by JITs) so in callers' frames connect just 16912 * r6 - r9 as an optimization. Callers will have r1 - r5 connected to 16913 * the state of the call instruction (with WRITTEN set), and r0 comes 16914 * from callee with its full parentage chain, anyway. 16915 */ 16916 /* clear write marks in current state: the writes we did are not writes 16917 * our child did, so they don't screen off its reads from us. 16918 * (There are no read marks in current state, because reads always mark 16919 * their parent and current state never has children yet. Only 16920 * explored_states can get read marks.) 16921 */ 16922 for (j = 0; j <= cur->curframe; j++) { 16923 for (i = j < cur->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++) 16924 cur->frame[j]->regs[i].parent = &new->frame[j]->regs[i]; 16925 for (i = 0; i < BPF_REG_FP; i++) 16926 cur->frame[j]->regs[i].live = REG_LIVE_NONE; 16927 } 16928 16929 /* all stack frames are accessible from callee, clear them all */ 16930 for (j = 0; j <= cur->curframe; j++) { 16931 struct bpf_func_state *frame = cur->frame[j]; 16932 struct bpf_func_state *newframe = new->frame[j]; 16933 16934 for (i = 0; i < frame->allocated_stack / BPF_REG_SIZE; i++) { 16935 frame->stack[i].spilled_ptr.live = REG_LIVE_NONE; 16936 frame->stack[i].spilled_ptr.parent = 16937 &newframe->stack[i].spilled_ptr; 16938 } 16939 } 16940 return 0; 16941 } 16942 16943 /* Return true if it's OK to have the same insn return a different type. */ 16944 static bool reg_type_mismatch_ok(enum bpf_reg_type type) 16945 { 16946 switch (base_type(type)) { 16947 case PTR_TO_CTX: 16948 case PTR_TO_SOCKET: 16949 case PTR_TO_SOCK_COMMON: 16950 case PTR_TO_TCP_SOCK: 16951 case PTR_TO_XDP_SOCK: 16952 case PTR_TO_BTF_ID: 16953 return false; 16954 default: 16955 return true; 16956 } 16957 } 16958 16959 /* If an instruction was previously used with particular pointer types, then we 16960 * need to be careful to avoid cases such as the below, where it may be ok 16961 * for one branch accessing the pointer, but not ok for the other branch: 16962 * 16963 * R1 = sock_ptr 16964 * goto X; 16965 * ... 16966 * R1 = some_other_valid_ptr; 16967 * goto X; 16968 * ... 16969 * R2 = *(u32 *)(R1 + 0); 16970 */ 16971 static bool reg_type_mismatch(enum bpf_reg_type src, enum bpf_reg_type prev) 16972 { 16973 return src != prev && (!reg_type_mismatch_ok(src) || 16974 !reg_type_mismatch_ok(prev)); 16975 } 16976 16977 static int save_aux_ptr_type(struct bpf_verifier_env *env, enum bpf_reg_type type, 16978 bool allow_trust_missmatch) 16979 { 16980 enum bpf_reg_type *prev_type = &env->insn_aux_data[env->insn_idx].ptr_type; 16981 16982 if (*prev_type == NOT_INIT) { 16983 /* Saw a valid insn 16984 * dst_reg = *(u32 *)(src_reg + off) 16985 * save type to validate intersecting paths 16986 */ 16987 *prev_type = type; 16988 } else if (reg_type_mismatch(type, *prev_type)) { 16989 /* Abuser program is trying to use the same insn 16990 * dst_reg = *(u32*) (src_reg + off) 16991 * with different pointer types: 16992 * src_reg == ctx in one branch and 16993 * src_reg == stack|map in some other branch. 16994 * Reject it. 16995 */ 16996 if (allow_trust_missmatch && 16997 base_type(type) == PTR_TO_BTF_ID && 16998 base_type(*prev_type) == PTR_TO_BTF_ID) { 16999 /* 17000 * Have to support a use case when one path through 17001 * the program yields TRUSTED pointer while another 17002 * is UNTRUSTED. Fallback to UNTRUSTED to generate 17003 * BPF_PROBE_MEM/BPF_PROBE_MEMSX. 17004 */ 17005 *prev_type = PTR_TO_BTF_ID | PTR_UNTRUSTED; 17006 } else { 17007 verbose(env, "same insn cannot be used with different pointers\n"); 17008 return -EINVAL; 17009 } 17010 } 17011 17012 return 0; 17013 } 17014 17015 static int do_check(struct bpf_verifier_env *env) 17016 { 17017 bool pop_log = !(env->log.level & BPF_LOG_LEVEL2); 17018 struct bpf_verifier_state *state = env->cur_state; 17019 struct bpf_insn *insns = env->prog->insnsi; 17020 struct bpf_reg_state *regs; 17021 int insn_cnt = env->prog->len; 17022 bool do_print_state = false; 17023 int prev_insn_idx = -1; 17024 17025 for (;;) { 17026 struct bpf_insn *insn; 17027 u8 class; 17028 int err; 17029 17030 /* reset current history entry on each new instruction */ 17031 env->cur_hist_ent = NULL; 17032 17033 env->prev_insn_idx = prev_insn_idx; 17034 if (env->insn_idx >= insn_cnt) { 17035 verbose(env, "invalid insn idx %d insn_cnt %d\n", 17036 env->insn_idx, insn_cnt); 17037 return -EFAULT; 17038 } 17039 17040 insn = &insns[env->insn_idx]; 17041 class = BPF_CLASS(insn->code); 17042 17043 if (++env->insn_processed > BPF_COMPLEXITY_LIMIT_INSNS) { 17044 verbose(env, 17045 "BPF program is too large. Processed %d insn\n", 17046 env->insn_processed); 17047 return -E2BIG; 17048 } 17049 17050 state->last_insn_idx = env->prev_insn_idx; 17051 17052 if (is_prune_point(env, env->insn_idx)) { 17053 err = is_state_visited(env, env->insn_idx); 17054 if (err < 0) 17055 return err; 17056 if (err == 1) { 17057 /* found equivalent state, can prune the search */ 17058 if (env->log.level & BPF_LOG_LEVEL) { 17059 if (do_print_state) 17060 verbose(env, "\nfrom %d to %d%s: safe\n", 17061 env->prev_insn_idx, env->insn_idx, 17062 env->cur_state->speculative ? 17063 " (speculative execution)" : ""); 17064 else 17065 verbose(env, "%d: safe\n", env->insn_idx); 17066 } 17067 goto process_bpf_exit; 17068 } 17069 } 17070 17071 if (is_jmp_point(env, env->insn_idx)) { 17072 err = push_jmp_history(env, state, 0); 17073 if (err) 17074 return err; 17075 } 17076 17077 if (signal_pending(current)) 17078 return -EAGAIN; 17079 17080 if (need_resched()) 17081 cond_resched(); 17082 17083 if (env->log.level & BPF_LOG_LEVEL2 && do_print_state) { 17084 verbose(env, "\nfrom %d to %d%s:", 17085 env->prev_insn_idx, env->insn_idx, 17086 env->cur_state->speculative ? 17087 " (speculative execution)" : ""); 17088 print_verifier_state(env, state->frame[state->curframe], true); 17089 do_print_state = false; 17090 } 17091 17092 if (env->log.level & BPF_LOG_LEVEL) { 17093 const struct bpf_insn_cbs cbs = { 17094 .cb_call = disasm_kfunc_name, 17095 .cb_print = verbose, 17096 .private_data = env, 17097 }; 17098 17099 if (verifier_state_scratched(env)) 17100 print_insn_state(env, state->frame[state->curframe]); 17101 17102 verbose_linfo(env, env->insn_idx, "; "); 17103 env->prev_log_pos = env->log.end_pos; 17104 verbose(env, "%d: ", env->insn_idx); 17105 print_bpf_insn(&cbs, insn, env->allow_ptr_leaks); 17106 env->prev_insn_print_pos = env->log.end_pos - env->prev_log_pos; 17107 env->prev_log_pos = env->log.end_pos; 17108 } 17109 17110 if (bpf_prog_is_offloaded(env->prog->aux)) { 17111 err = bpf_prog_offload_verify_insn(env, env->insn_idx, 17112 env->prev_insn_idx); 17113 if (err) 17114 return err; 17115 } 17116 17117 regs = cur_regs(env); 17118 sanitize_mark_insn_seen(env); 17119 prev_insn_idx = env->insn_idx; 17120 17121 if (class == BPF_ALU || class == BPF_ALU64) { 17122 err = check_alu_op(env, insn); 17123 if (err) 17124 return err; 17125 17126 } else if (class == BPF_LDX) { 17127 enum bpf_reg_type src_reg_type; 17128 17129 /* check for reserved fields is already done */ 17130 17131 /* check src operand */ 17132 err = check_reg_arg(env, insn->src_reg, SRC_OP); 17133 if (err) 17134 return err; 17135 17136 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK); 17137 if (err) 17138 return err; 17139 17140 src_reg_type = regs[insn->src_reg].type; 17141 17142 /* check that memory (src_reg + off) is readable, 17143 * the state of dst_reg will be updated by this func 17144 */ 17145 err = check_mem_access(env, env->insn_idx, insn->src_reg, 17146 insn->off, BPF_SIZE(insn->code), 17147 BPF_READ, insn->dst_reg, false, 17148 BPF_MODE(insn->code) == BPF_MEMSX); 17149 if (err) 17150 return err; 17151 17152 err = save_aux_ptr_type(env, src_reg_type, true); 17153 if (err) 17154 return err; 17155 } else if (class == BPF_STX) { 17156 enum bpf_reg_type dst_reg_type; 17157 17158 if (BPF_MODE(insn->code) == BPF_ATOMIC) { 17159 err = check_atomic(env, env->insn_idx, insn); 17160 if (err) 17161 return err; 17162 env->insn_idx++; 17163 continue; 17164 } 17165 17166 if (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0) { 17167 verbose(env, "BPF_STX uses reserved fields\n"); 17168 return -EINVAL; 17169 } 17170 17171 /* check src1 operand */ 17172 err = check_reg_arg(env, insn->src_reg, SRC_OP); 17173 if (err) 17174 return err; 17175 /* check src2 operand */ 17176 err = check_reg_arg(env, insn->dst_reg, SRC_OP); 17177 if (err) 17178 return err; 17179 17180 dst_reg_type = regs[insn->dst_reg].type; 17181 17182 /* check that memory (dst_reg + off) is writeable */ 17183 err = check_mem_access(env, env->insn_idx, insn->dst_reg, 17184 insn->off, BPF_SIZE(insn->code), 17185 BPF_WRITE, insn->src_reg, false, false); 17186 if (err) 17187 return err; 17188 17189 err = save_aux_ptr_type(env, dst_reg_type, false); 17190 if (err) 17191 return err; 17192 } else if (class == BPF_ST) { 17193 enum bpf_reg_type dst_reg_type; 17194 17195 if (BPF_MODE(insn->code) != BPF_MEM || 17196 insn->src_reg != BPF_REG_0) { 17197 verbose(env, "BPF_ST uses reserved fields\n"); 17198 return -EINVAL; 17199 } 17200 /* check src operand */ 17201 err = check_reg_arg(env, insn->dst_reg, SRC_OP); 17202 if (err) 17203 return err; 17204 17205 dst_reg_type = regs[insn->dst_reg].type; 17206 17207 /* check that memory (dst_reg + off) is writeable */ 17208 err = check_mem_access(env, env->insn_idx, insn->dst_reg, 17209 insn->off, BPF_SIZE(insn->code), 17210 BPF_WRITE, -1, false, false); 17211 if (err) 17212 return err; 17213 17214 err = save_aux_ptr_type(env, dst_reg_type, false); 17215 if (err) 17216 return err; 17217 } else if (class == BPF_JMP || class == BPF_JMP32) { 17218 u8 opcode = BPF_OP(insn->code); 17219 17220 env->jmps_processed++; 17221 if (opcode == BPF_CALL) { 17222 if (BPF_SRC(insn->code) != BPF_K || 17223 (insn->src_reg != BPF_PSEUDO_KFUNC_CALL 17224 && insn->off != 0) || 17225 (insn->src_reg != BPF_REG_0 && 17226 insn->src_reg != BPF_PSEUDO_CALL && 17227 insn->src_reg != BPF_PSEUDO_KFUNC_CALL) || 17228 insn->dst_reg != BPF_REG_0 || 17229 class == BPF_JMP32) { 17230 verbose(env, "BPF_CALL uses reserved fields\n"); 17231 return -EINVAL; 17232 } 17233 17234 if (env->cur_state->active_lock.ptr) { 17235 if ((insn->src_reg == BPF_REG_0 && insn->imm != BPF_FUNC_spin_unlock) || 17236 (insn->src_reg == BPF_PSEUDO_CALL) || 17237 (insn->src_reg == BPF_PSEUDO_KFUNC_CALL && 17238 (insn->off != 0 || !is_bpf_graph_api_kfunc(insn->imm)))) { 17239 verbose(env, "function calls are not allowed while holding a lock\n"); 17240 return -EINVAL; 17241 } 17242 } 17243 if (insn->src_reg == BPF_PSEUDO_CALL) 17244 err = check_func_call(env, insn, &env->insn_idx); 17245 else if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) 17246 err = check_kfunc_call(env, insn, &env->insn_idx); 17247 else 17248 err = check_helper_call(env, insn, &env->insn_idx); 17249 if (err) 17250 return err; 17251 17252 mark_reg_scratched(env, BPF_REG_0); 17253 } else if (opcode == BPF_JA) { 17254 if (BPF_SRC(insn->code) != BPF_K || 17255 insn->src_reg != BPF_REG_0 || 17256 insn->dst_reg != BPF_REG_0 || 17257 (class == BPF_JMP && insn->imm != 0) || 17258 (class == BPF_JMP32 && insn->off != 0)) { 17259 verbose(env, "BPF_JA uses reserved fields\n"); 17260 return -EINVAL; 17261 } 17262 17263 if (class == BPF_JMP) 17264 env->insn_idx += insn->off + 1; 17265 else 17266 env->insn_idx += insn->imm + 1; 17267 continue; 17268 17269 } else if (opcode == BPF_EXIT) { 17270 if (BPF_SRC(insn->code) != BPF_K || 17271 insn->imm != 0 || 17272 insn->src_reg != BPF_REG_0 || 17273 insn->dst_reg != BPF_REG_0 || 17274 class == BPF_JMP32) { 17275 verbose(env, "BPF_EXIT uses reserved fields\n"); 17276 return -EINVAL; 17277 } 17278 17279 if (env->cur_state->active_lock.ptr && 17280 !in_rbtree_lock_required_cb(env)) { 17281 verbose(env, "bpf_spin_unlock is missing\n"); 17282 return -EINVAL; 17283 } 17284 17285 if (env->cur_state->active_rcu_lock && 17286 !in_rbtree_lock_required_cb(env)) { 17287 verbose(env, "bpf_rcu_read_unlock is missing\n"); 17288 return -EINVAL; 17289 } 17290 17291 /* We must do check_reference_leak here before 17292 * prepare_func_exit to handle the case when 17293 * state->curframe > 0, it may be a callback 17294 * function, for which reference_state must 17295 * match caller reference state when it exits. 17296 */ 17297 err = check_reference_leak(env); 17298 if (err) 17299 return err; 17300 17301 if (state->curframe) { 17302 /* exit from nested function */ 17303 err = prepare_func_exit(env, &env->insn_idx); 17304 if (err) 17305 return err; 17306 do_print_state = true; 17307 continue; 17308 } 17309 17310 err = check_return_code(env); 17311 if (err) 17312 return err; 17313 process_bpf_exit: 17314 mark_verifier_state_scratched(env); 17315 update_branch_counts(env, env->cur_state); 17316 err = pop_stack(env, &prev_insn_idx, 17317 &env->insn_idx, pop_log); 17318 if (err < 0) { 17319 if (err != -ENOENT) 17320 return err; 17321 break; 17322 } else { 17323 do_print_state = true; 17324 continue; 17325 } 17326 } else { 17327 err = check_cond_jmp_op(env, insn, &env->insn_idx); 17328 if (err) 17329 return err; 17330 } 17331 } else if (class == BPF_LD) { 17332 u8 mode = BPF_MODE(insn->code); 17333 17334 if (mode == BPF_ABS || mode == BPF_IND) { 17335 err = check_ld_abs(env, insn); 17336 if (err) 17337 return err; 17338 17339 } else if (mode == BPF_IMM) { 17340 err = check_ld_imm(env, insn); 17341 if (err) 17342 return err; 17343 17344 env->insn_idx++; 17345 sanitize_mark_insn_seen(env); 17346 } else { 17347 verbose(env, "invalid BPF_LD mode\n"); 17348 return -EINVAL; 17349 } 17350 } else { 17351 verbose(env, "unknown insn class %d\n", class); 17352 return -EINVAL; 17353 } 17354 17355 env->insn_idx++; 17356 } 17357 17358 return 0; 17359 } 17360 17361 static int find_btf_percpu_datasec(struct btf *btf) 17362 { 17363 const struct btf_type *t; 17364 const char *tname; 17365 int i, n; 17366 17367 /* 17368 * Both vmlinux and module each have their own ".data..percpu" 17369 * DATASECs in BTF. So for module's case, we need to skip vmlinux BTF 17370 * types to look at only module's own BTF types. 17371 */ 17372 n = btf_nr_types(btf); 17373 if (btf_is_module(btf)) 17374 i = btf_nr_types(btf_vmlinux); 17375 else 17376 i = 1; 17377 17378 for(; i < n; i++) { 17379 t = btf_type_by_id(btf, i); 17380 if (BTF_INFO_KIND(t->info) != BTF_KIND_DATASEC) 17381 continue; 17382 17383 tname = btf_name_by_offset(btf, t->name_off); 17384 if (!strcmp(tname, ".data..percpu")) 17385 return i; 17386 } 17387 17388 return -ENOENT; 17389 } 17390 17391 /* replace pseudo btf_id with kernel symbol address */ 17392 static int check_pseudo_btf_id(struct bpf_verifier_env *env, 17393 struct bpf_insn *insn, 17394 struct bpf_insn_aux_data *aux) 17395 { 17396 const struct btf_var_secinfo *vsi; 17397 const struct btf_type *datasec; 17398 struct btf_mod_pair *btf_mod; 17399 const struct btf_type *t; 17400 const char *sym_name; 17401 bool percpu = false; 17402 u32 type, id = insn->imm; 17403 struct btf *btf; 17404 s32 datasec_id; 17405 u64 addr; 17406 int i, btf_fd, err; 17407 17408 btf_fd = insn[1].imm; 17409 if (btf_fd) { 17410 btf = btf_get_by_fd(btf_fd); 17411 if (IS_ERR(btf)) { 17412 verbose(env, "invalid module BTF object FD specified.\n"); 17413 return -EINVAL; 17414 } 17415 } else { 17416 if (!btf_vmlinux) { 17417 verbose(env, "kernel is missing BTF, make sure CONFIG_DEBUG_INFO_BTF=y is specified in Kconfig.\n"); 17418 return -EINVAL; 17419 } 17420 btf = btf_vmlinux; 17421 btf_get(btf); 17422 } 17423 17424 t = btf_type_by_id(btf, id); 17425 if (!t) { 17426 verbose(env, "ldimm64 insn specifies invalid btf_id %d.\n", id); 17427 err = -ENOENT; 17428 goto err_put; 17429 } 17430 17431 if (!btf_type_is_var(t) && !btf_type_is_func(t)) { 17432 verbose(env, "pseudo btf_id %d in ldimm64 isn't KIND_VAR or KIND_FUNC\n", id); 17433 err = -EINVAL; 17434 goto err_put; 17435 } 17436 17437 sym_name = btf_name_by_offset(btf, t->name_off); 17438 addr = kallsyms_lookup_name(sym_name); 17439 if (!addr) { 17440 verbose(env, "ldimm64 failed to find the address for kernel symbol '%s'.\n", 17441 sym_name); 17442 err = -ENOENT; 17443 goto err_put; 17444 } 17445 insn[0].imm = (u32)addr; 17446 insn[1].imm = addr >> 32; 17447 17448 if (btf_type_is_func(t)) { 17449 aux->btf_var.reg_type = PTR_TO_MEM | MEM_RDONLY; 17450 aux->btf_var.mem_size = 0; 17451 goto check_btf; 17452 } 17453 17454 datasec_id = find_btf_percpu_datasec(btf); 17455 if (datasec_id > 0) { 17456 datasec = btf_type_by_id(btf, datasec_id); 17457 for_each_vsi(i, datasec, vsi) { 17458 if (vsi->type == id) { 17459 percpu = true; 17460 break; 17461 } 17462 } 17463 } 17464 17465 type = t->type; 17466 t = btf_type_skip_modifiers(btf, type, NULL); 17467 if (percpu) { 17468 aux->btf_var.reg_type = PTR_TO_BTF_ID | MEM_PERCPU; 17469 aux->btf_var.btf = btf; 17470 aux->btf_var.btf_id = type; 17471 } else if (!btf_type_is_struct(t)) { 17472 const struct btf_type *ret; 17473 const char *tname; 17474 u32 tsize; 17475 17476 /* resolve the type size of ksym. */ 17477 ret = btf_resolve_size(btf, t, &tsize); 17478 if (IS_ERR(ret)) { 17479 tname = btf_name_by_offset(btf, t->name_off); 17480 verbose(env, "ldimm64 unable to resolve the size of type '%s': %ld\n", 17481 tname, PTR_ERR(ret)); 17482 err = -EINVAL; 17483 goto err_put; 17484 } 17485 aux->btf_var.reg_type = PTR_TO_MEM | MEM_RDONLY; 17486 aux->btf_var.mem_size = tsize; 17487 } else { 17488 aux->btf_var.reg_type = PTR_TO_BTF_ID; 17489 aux->btf_var.btf = btf; 17490 aux->btf_var.btf_id = type; 17491 } 17492 check_btf: 17493 /* check whether we recorded this BTF (and maybe module) already */ 17494 for (i = 0; i < env->used_btf_cnt; i++) { 17495 if (env->used_btfs[i].btf == btf) { 17496 btf_put(btf); 17497 return 0; 17498 } 17499 } 17500 17501 if (env->used_btf_cnt >= MAX_USED_BTFS) { 17502 err = -E2BIG; 17503 goto err_put; 17504 } 17505 17506 btf_mod = &env->used_btfs[env->used_btf_cnt]; 17507 btf_mod->btf = btf; 17508 btf_mod->module = NULL; 17509 17510 /* if we reference variables from kernel module, bump its refcount */ 17511 if (btf_is_module(btf)) { 17512 btf_mod->module = btf_try_get_module(btf); 17513 if (!btf_mod->module) { 17514 err = -ENXIO; 17515 goto err_put; 17516 } 17517 } 17518 17519 env->used_btf_cnt++; 17520 17521 return 0; 17522 err_put: 17523 btf_put(btf); 17524 return err; 17525 } 17526 17527 static bool is_tracing_prog_type(enum bpf_prog_type type) 17528 { 17529 switch (type) { 17530 case BPF_PROG_TYPE_KPROBE: 17531 case BPF_PROG_TYPE_TRACEPOINT: 17532 case BPF_PROG_TYPE_PERF_EVENT: 17533 case BPF_PROG_TYPE_RAW_TRACEPOINT: 17534 case BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE: 17535 return true; 17536 default: 17537 return false; 17538 } 17539 } 17540 17541 static int check_map_prog_compatibility(struct bpf_verifier_env *env, 17542 struct bpf_map *map, 17543 struct bpf_prog *prog) 17544 17545 { 17546 enum bpf_prog_type prog_type = resolve_prog_type(prog); 17547 17548 if (btf_record_has_field(map->record, BPF_LIST_HEAD) || 17549 btf_record_has_field(map->record, BPF_RB_ROOT)) { 17550 if (is_tracing_prog_type(prog_type)) { 17551 verbose(env, "tracing progs cannot use bpf_{list_head,rb_root} yet\n"); 17552 return -EINVAL; 17553 } 17554 } 17555 17556 if (btf_record_has_field(map->record, BPF_SPIN_LOCK)) { 17557 if (prog_type == BPF_PROG_TYPE_SOCKET_FILTER) { 17558 verbose(env, "socket filter progs cannot use bpf_spin_lock yet\n"); 17559 return -EINVAL; 17560 } 17561 17562 if (is_tracing_prog_type(prog_type)) { 17563 verbose(env, "tracing progs cannot use bpf_spin_lock yet\n"); 17564 return -EINVAL; 17565 } 17566 } 17567 17568 if (btf_record_has_field(map->record, BPF_TIMER)) { 17569 if (is_tracing_prog_type(prog_type)) { 17570 verbose(env, "tracing progs cannot use bpf_timer yet\n"); 17571 return -EINVAL; 17572 } 17573 } 17574 17575 if ((bpf_prog_is_offloaded(prog->aux) || bpf_map_is_offloaded(map)) && 17576 !bpf_offload_prog_map_match(prog, map)) { 17577 verbose(env, "offload device mismatch between prog and map\n"); 17578 return -EINVAL; 17579 } 17580 17581 if (map->map_type == BPF_MAP_TYPE_STRUCT_OPS) { 17582 verbose(env, "bpf_struct_ops map cannot be used in prog\n"); 17583 return -EINVAL; 17584 } 17585 17586 if (prog->aux->sleepable) 17587 switch (map->map_type) { 17588 case BPF_MAP_TYPE_HASH: 17589 case BPF_MAP_TYPE_LRU_HASH: 17590 case BPF_MAP_TYPE_ARRAY: 17591 case BPF_MAP_TYPE_PERCPU_HASH: 17592 case BPF_MAP_TYPE_PERCPU_ARRAY: 17593 case BPF_MAP_TYPE_LRU_PERCPU_HASH: 17594 case BPF_MAP_TYPE_ARRAY_OF_MAPS: 17595 case BPF_MAP_TYPE_HASH_OF_MAPS: 17596 case BPF_MAP_TYPE_RINGBUF: 17597 case BPF_MAP_TYPE_USER_RINGBUF: 17598 case BPF_MAP_TYPE_INODE_STORAGE: 17599 case BPF_MAP_TYPE_SK_STORAGE: 17600 case BPF_MAP_TYPE_TASK_STORAGE: 17601 case BPF_MAP_TYPE_CGRP_STORAGE: 17602 break; 17603 default: 17604 verbose(env, 17605 "Sleepable programs can only use array, hash, ringbuf and local storage maps\n"); 17606 return -EINVAL; 17607 } 17608 17609 return 0; 17610 } 17611 17612 static bool bpf_map_is_cgroup_storage(struct bpf_map *map) 17613 { 17614 return (map->map_type == BPF_MAP_TYPE_CGROUP_STORAGE || 17615 map->map_type == BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE); 17616 } 17617 17618 /* find and rewrite pseudo imm in ld_imm64 instructions: 17619 * 17620 * 1. if it accesses map FD, replace it with actual map pointer. 17621 * 2. if it accesses btf_id of a VAR, replace it with pointer to the var. 17622 * 17623 * NOTE: btf_vmlinux is required for converting pseudo btf_id. 17624 */ 17625 static int resolve_pseudo_ldimm64(struct bpf_verifier_env *env) 17626 { 17627 struct bpf_insn *insn = env->prog->insnsi; 17628 int insn_cnt = env->prog->len; 17629 int i, j, err; 17630 17631 err = bpf_prog_calc_tag(env->prog); 17632 if (err) 17633 return err; 17634 17635 for (i = 0; i < insn_cnt; i++, insn++) { 17636 if (BPF_CLASS(insn->code) == BPF_LDX && 17637 ((BPF_MODE(insn->code) != BPF_MEM && BPF_MODE(insn->code) != BPF_MEMSX) || 17638 insn->imm != 0)) { 17639 verbose(env, "BPF_LDX uses reserved fields\n"); 17640 return -EINVAL; 17641 } 17642 17643 if (insn[0].code == (BPF_LD | BPF_IMM | BPF_DW)) { 17644 struct bpf_insn_aux_data *aux; 17645 struct bpf_map *map; 17646 struct fd f; 17647 u64 addr; 17648 u32 fd; 17649 17650 if (i == insn_cnt - 1 || insn[1].code != 0 || 17651 insn[1].dst_reg != 0 || insn[1].src_reg != 0 || 17652 insn[1].off != 0) { 17653 verbose(env, "invalid bpf_ld_imm64 insn\n"); 17654 return -EINVAL; 17655 } 17656 17657 if (insn[0].src_reg == 0) 17658 /* valid generic load 64-bit imm */ 17659 goto next_insn; 17660 17661 if (insn[0].src_reg == BPF_PSEUDO_BTF_ID) { 17662 aux = &env->insn_aux_data[i]; 17663 err = check_pseudo_btf_id(env, insn, aux); 17664 if (err) 17665 return err; 17666 goto next_insn; 17667 } 17668 17669 if (insn[0].src_reg == BPF_PSEUDO_FUNC) { 17670 aux = &env->insn_aux_data[i]; 17671 aux->ptr_type = PTR_TO_FUNC; 17672 goto next_insn; 17673 } 17674 17675 /* In final convert_pseudo_ld_imm64() step, this is 17676 * converted into regular 64-bit imm load insn. 17677 */ 17678 switch (insn[0].src_reg) { 17679 case BPF_PSEUDO_MAP_VALUE: 17680 case BPF_PSEUDO_MAP_IDX_VALUE: 17681 break; 17682 case BPF_PSEUDO_MAP_FD: 17683 case BPF_PSEUDO_MAP_IDX: 17684 if (insn[1].imm == 0) 17685 break; 17686 fallthrough; 17687 default: 17688 verbose(env, "unrecognized bpf_ld_imm64 insn\n"); 17689 return -EINVAL; 17690 } 17691 17692 switch (insn[0].src_reg) { 17693 case BPF_PSEUDO_MAP_IDX_VALUE: 17694 case BPF_PSEUDO_MAP_IDX: 17695 if (bpfptr_is_null(env->fd_array)) { 17696 verbose(env, "fd_idx without fd_array is invalid\n"); 17697 return -EPROTO; 17698 } 17699 if (copy_from_bpfptr_offset(&fd, env->fd_array, 17700 insn[0].imm * sizeof(fd), 17701 sizeof(fd))) 17702 return -EFAULT; 17703 break; 17704 default: 17705 fd = insn[0].imm; 17706 break; 17707 } 17708 17709 f = fdget(fd); 17710 map = __bpf_map_get(f); 17711 if (IS_ERR(map)) { 17712 verbose(env, "fd %d is not pointing to valid bpf_map\n", fd); 17713 return PTR_ERR(map); 17714 } 17715 17716 err = check_map_prog_compatibility(env, map, env->prog); 17717 if (err) { 17718 fdput(f); 17719 return err; 17720 } 17721 17722 aux = &env->insn_aux_data[i]; 17723 if (insn[0].src_reg == BPF_PSEUDO_MAP_FD || 17724 insn[0].src_reg == BPF_PSEUDO_MAP_IDX) { 17725 addr = (unsigned long)map; 17726 } else { 17727 u32 off = insn[1].imm; 17728 17729 if (off >= BPF_MAX_VAR_OFF) { 17730 verbose(env, "direct value offset of %u is not allowed\n", off); 17731 fdput(f); 17732 return -EINVAL; 17733 } 17734 17735 if (!map->ops->map_direct_value_addr) { 17736 verbose(env, "no direct value access support for this map type\n"); 17737 fdput(f); 17738 return -EINVAL; 17739 } 17740 17741 err = map->ops->map_direct_value_addr(map, &addr, off); 17742 if (err) { 17743 verbose(env, "invalid access to map value pointer, value_size=%u off=%u\n", 17744 map->value_size, off); 17745 fdput(f); 17746 return err; 17747 } 17748 17749 aux->map_off = off; 17750 addr += off; 17751 } 17752 17753 insn[0].imm = (u32)addr; 17754 insn[1].imm = addr >> 32; 17755 17756 /* check whether we recorded this map already */ 17757 for (j = 0; j < env->used_map_cnt; j++) { 17758 if (env->used_maps[j] == map) { 17759 aux->map_index = j; 17760 fdput(f); 17761 goto next_insn; 17762 } 17763 } 17764 17765 if (env->used_map_cnt >= MAX_USED_MAPS) { 17766 fdput(f); 17767 return -E2BIG; 17768 } 17769 17770 if (env->prog->aux->sleepable) 17771 atomic64_inc(&map->sleepable_refcnt); 17772 /* hold the map. If the program is rejected by verifier, 17773 * the map will be released by release_maps() or it 17774 * will be used by the valid program until it's unloaded 17775 * and all maps are released in bpf_free_used_maps() 17776 */ 17777 bpf_map_inc(map); 17778 17779 aux->map_index = env->used_map_cnt; 17780 env->used_maps[env->used_map_cnt++] = map; 17781 17782 if (bpf_map_is_cgroup_storage(map) && 17783 bpf_cgroup_storage_assign(env->prog->aux, map)) { 17784 verbose(env, "only one cgroup storage of each type is allowed\n"); 17785 fdput(f); 17786 return -EBUSY; 17787 } 17788 17789 fdput(f); 17790 next_insn: 17791 insn++; 17792 i++; 17793 continue; 17794 } 17795 17796 /* Basic sanity check before we invest more work here. */ 17797 if (!bpf_opcode_in_insntable(insn->code)) { 17798 verbose(env, "unknown opcode %02x\n", insn->code); 17799 return -EINVAL; 17800 } 17801 } 17802 17803 /* now all pseudo BPF_LD_IMM64 instructions load valid 17804 * 'struct bpf_map *' into a register instead of user map_fd. 17805 * These pointers will be used later by verifier to validate map access. 17806 */ 17807 return 0; 17808 } 17809 17810 /* drop refcnt of maps used by the rejected program */ 17811 static void release_maps(struct bpf_verifier_env *env) 17812 { 17813 __bpf_free_used_maps(env->prog->aux, env->used_maps, 17814 env->used_map_cnt); 17815 } 17816 17817 /* drop refcnt of maps used by the rejected program */ 17818 static void release_btfs(struct bpf_verifier_env *env) 17819 { 17820 __bpf_free_used_btfs(env->prog->aux, env->used_btfs, 17821 env->used_btf_cnt); 17822 } 17823 17824 /* convert pseudo BPF_LD_IMM64 into generic BPF_LD_IMM64 */ 17825 static void convert_pseudo_ld_imm64(struct bpf_verifier_env *env) 17826 { 17827 struct bpf_insn *insn = env->prog->insnsi; 17828 int insn_cnt = env->prog->len; 17829 int i; 17830 17831 for (i = 0; i < insn_cnt; i++, insn++) { 17832 if (insn->code != (BPF_LD | BPF_IMM | BPF_DW)) 17833 continue; 17834 if (insn->src_reg == BPF_PSEUDO_FUNC) 17835 continue; 17836 insn->src_reg = 0; 17837 } 17838 } 17839 17840 /* single env->prog->insni[off] instruction was replaced with the range 17841 * insni[off, off + cnt). Adjust corresponding insn_aux_data by copying 17842 * [0, off) and [off, end) to new locations, so the patched range stays zero 17843 */ 17844 static void adjust_insn_aux_data(struct bpf_verifier_env *env, 17845 struct bpf_insn_aux_data *new_data, 17846 struct bpf_prog *new_prog, u32 off, u32 cnt) 17847 { 17848 struct bpf_insn_aux_data *old_data = env->insn_aux_data; 17849 struct bpf_insn *insn = new_prog->insnsi; 17850 u32 old_seen = old_data[off].seen; 17851 u32 prog_len; 17852 int i; 17853 17854 /* aux info at OFF always needs adjustment, no matter fast path 17855 * (cnt == 1) is taken or not. There is no guarantee INSN at OFF is the 17856 * original insn at old prog. 17857 */ 17858 old_data[off].zext_dst = insn_has_def32(env, insn + off + cnt - 1); 17859 17860 if (cnt == 1) 17861 return; 17862 prog_len = new_prog->len; 17863 17864 memcpy(new_data, old_data, sizeof(struct bpf_insn_aux_data) * off); 17865 memcpy(new_data + off + cnt - 1, old_data + off, 17866 sizeof(struct bpf_insn_aux_data) * (prog_len - off - cnt + 1)); 17867 for (i = off; i < off + cnt - 1; i++) { 17868 /* Expand insni[off]'s seen count to the patched range. */ 17869 new_data[i].seen = old_seen; 17870 new_data[i].zext_dst = insn_has_def32(env, insn + i); 17871 } 17872 env->insn_aux_data = new_data; 17873 vfree(old_data); 17874 } 17875 17876 static void adjust_subprog_starts(struct bpf_verifier_env *env, u32 off, u32 len) 17877 { 17878 int i; 17879 17880 if (len == 1) 17881 return; 17882 /* NOTE: fake 'exit' subprog should be updated as well. */ 17883 for (i = 0; i <= env->subprog_cnt; i++) { 17884 if (env->subprog_info[i].start <= off) 17885 continue; 17886 env->subprog_info[i].start += len - 1; 17887 } 17888 } 17889 17890 static void adjust_poke_descs(struct bpf_prog *prog, u32 off, u32 len) 17891 { 17892 struct bpf_jit_poke_descriptor *tab = prog->aux->poke_tab; 17893 int i, sz = prog->aux->size_poke_tab; 17894 struct bpf_jit_poke_descriptor *desc; 17895 17896 for (i = 0; i < sz; i++) { 17897 desc = &tab[i]; 17898 if (desc->insn_idx <= off) 17899 continue; 17900 desc->insn_idx += len - 1; 17901 } 17902 } 17903 17904 static struct bpf_prog *bpf_patch_insn_data(struct bpf_verifier_env *env, u32 off, 17905 const struct bpf_insn *patch, u32 len) 17906 { 17907 struct bpf_prog *new_prog; 17908 struct bpf_insn_aux_data *new_data = NULL; 17909 17910 if (len > 1) { 17911 new_data = vzalloc(array_size(env->prog->len + len - 1, 17912 sizeof(struct bpf_insn_aux_data))); 17913 if (!new_data) 17914 return NULL; 17915 } 17916 17917 new_prog = bpf_patch_insn_single(env->prog, off, patch, len); 17918 if (IS_ERR(new_prog)) { 17919 if (PTR_ERR(new_prog) == -ERANGE) 17920 verbose(env, 17921 "insn %d cannot be patched due to 16-bit range\n", 17922 env->insn_aux_data[off].orig_idx); 17923 vfree(new_data); 17924 return NULL; 17925 } 17926 adjust_insn_aux_data(env, new_data, new_prog, off, len); 17927 adjust_subprog_starts(env, off, len); 17928 adjust_poke_descs(new_prog, off, len); 17929 return new_prog; 17930 } 17931 17932 static int adjust_subprog_starts_after_remove(struct bpf_verifier_env *env, 17933 u32 off, u32 cnt) 17934 { 17935 int i, j; 17936 17937 /* find first prog starting at or after off (first to remove) */ 17938 for (i = 0; i < env->subprog_cnt; i++) 17939 if (env->subprog_info[i].start >= off) 17940 break; 17941 /* find first prog starting at or after off + cnt (first to stay) */ 17942 for (j = i; j < env->subprog_cnt; j++) 17943 if (env->subprog_info[j].start >= off + cnt) 17944 break; 17945 /* if j doesn't start exactly at off + cnt, we are just removing 17946 * the front of previous prog 17947 */ 17948 if (env->subprog_info[j].start != off + cnt) 17949 j--; 17950 17951 if (j > i) { 17952 struct bpf_prog_aux *aux = env->prog->aux; 17953 int move; 17954 17955 /* move fake 'exit' subprog as well */ 17956 move = env->subprog_cnt + 1 - j; 17957 17958 memmove(env->subprog_info + i, 17959 env->subprog_info + j, 17960 sizeof(*env->subprog_info) * move); 17961 env->subprog_cnt -= j - i; 17962 17963 /* remove func_info */ 17964 if (aux->func_info) { 17965 move = aux->func_info_cnt - j; 17966 17967 memmove(aux->func_info + i, 17968 aux->func_info + j, 17969 sizeof(*aux->func_info) * move); 17970 aux->func_info_cnt -= j - i; 17971 /* func_info->insn_off is set after all code rewrites, 17972 * in adjust_btf_func() - no need to adjust 17973 */ 17974 } 17975 } else { 17976 /* convert i from "first prog to remove" to "first to adjust" */ 17977 if (env->subprog_info[i].start == off) 17978 i++; 17979 } 17980 17981 /* update fake 'exit' subprog as well */ 17982 for (; i <= env->subprog_cnt; i++) 17983 env->subprog_info[i].start -= cnt; 17984 17985 return 0; 17986 } 17987 17988 static int bpf_adj_linfo_after_remove(struct bpf_verifier_env *env, u32 off, 17989 u32 cnt) 17990 { 17991 struct bpf_prog *prog = env->prog; 17992 u32 i, l_off, l_cnt, nr_linfo; 17993 struct bpf_line_info *linfo; 17994 17995 nr_linfo = prog->aux->nr_linfo; 17996 if (!nr_linfo) 17997 return 0; 17998 17999 linfo = prog->aux->linfo; 18000 18001 /* find first line info to remove, count lines to be removed */ 18002 for (i = 0; i < nr_linfo; i++) 18003 if (linfo[i].insn_off >= off) 18004 break; 18005 18006 l_off = i; 18007 l_cnt = 0; 18008 for (; i < nr_linfo; i++) 18009 if (linfo[i].insn_off < off + cnt) 18010 l_cnt++; 18011 else 18012 break; 18013 18014 /* First live insn doesn't match first live linfo, it needs to "inherit" 18015 * last removed linfo. prog is already modified, so prog->len == off 18016 * means no live instructions after (tail of the program was removed). 18017 */ 18018 if (prog->len != off && l_cnt && 18019 (i == nr_linfo || linfo[i].insn_off != off + cnt)) { 18020 l_cnt--; 18021 linfo[--i].insn_off = off + cnt; 18022 } 18023 18024 /* remove the line info which refer to the removed instructions */ 18025 if (l_cnt) { 18026 memmove(linfo + l_off, linfo + i, 18027 sizeof(*linfo) * (nr_linfo - i)); 18028 18029 prog->aux->nr_linfo -= l_cnt; 18030 nr_linfo = prog->aux->nr_linfo; 18031 } 18032 18033 /* pull all linfo[i].insn_off >= off + cnt in by cnt */ 18034 for (i = l_off; i < nr_linfo; i++) 18035 linfo[i].insn_off -= cnt; 18036 18037 /* fix up all subprogs (incl. 'exit') which start >= off */ 18038 for (i = 0; i <= env->subprog_cnt; i++) 18039 if (env->subprog_info[i].linfo_idx > l_off) { 18040 /* program may have started in the removed region but 18041 * may not be fully removed 18042 */ 18043 if (env->subprog_info[i].linfo_idx >= l_off + l_cnt) 18044 env->subprog_info[i].linfo_idx -= l_cnt; 18045 else 18046 env->subprog_info[i].linfo_idx = l_off; 18047 } 18048 18049 return 0; 18050 } 18051 18052 static int verifier_remove_insns(struct bpf_verifier_env *env, u32 off, u32 cnt) 18053 { 18054 struct bpf_insn_aux_data *aux_data = env->insn_aux_data; 18055 unsigned int orig_prog_len = env->prog->len; 18056 int err; 18057 18058 if (bpf_prog_is_offloaded(env->prog->aux)) 18059 bpf_prog_offload_remove_insns(env, off, cnt); 18060 18061 err = bpf_remove_insns(env->prog, off, cnt); 18062 if (err) 18063 return err; 18064 18065 err = adjust_subprog_starts_after_remove(env, off, cnt); 18066 if (err) 18067 return err; 18068 18069 err = bpf_adj_linfo_after_remove(env, off, cnt); 18070 if (err) 18071 return err; 18072 18073 memmove(aux_data + off, aux_data + off + cnt, 18074 sizeof(*aux_data) * (orig_prog_len - off - cnt)); 18075 18076 return 0; 18077 } 18078 18079 /* The verifier does more data flow analysis than llvm and will not 18080 * explore branches that are dead at run time. Malicious programs can 18081 * have dead code too. Therefore replace all dead at-run-time code 18082 * with 'ja -1'. 18083 * 18084 * Just nops are not optimal, e.g. if they would sit at the end of the 18085 * program and through another bug we would manage to jump there, then 18086 * we'd execute beyond program memory otherwise. Returning exception 18087 * code also wouldn't work since we can have subprogs where the dead 18088 * code could be located. 18089 */ 18090 static void sanitize_dead_code(struct bpf_verifier_env *env) 18091 { 18092 struct bpf_insn_aux_data *aux_data = env->insn_aux_data; 18093 struct bpf_insn trap = BPF_JMP_IMM(BPF_JA, 0, 0, -1); 18094 struct bpf_insn *insn = env->prog->insnsi; 18095 const int insn_cnt = env->prog->len; 18096 int i; 18097 18098 for (i = 0; i < insn_cnt; i++) { 18099 if (aux_data[i].seen) 18100 continue; 18101 memcpy(insn + i, &trap, sizeof(trap)); 18102 aux_data[i].zext_dst = false; 18103 } 18104 } 18105 18106 static bool insn_is_cond_jump(u8 code) 18107 { 18108 u8 op; 18109 18110 op = BPF_OP(code); 18111 if (BPF_CLASS(code) == BPF_JMP32) 18112 return op != BPF_JA; 18113 18114 if (BPF_CLASS(code) != BPF_JMP) 18115 return false; 18116 18117 return op != BPF_JA && op != BPF_EXIT && op != BPF_CALL; 18118 } 18119 18120 static void opt_hard_wire_dead_code_branches(struct bpf_verifier_env *env) 18121 { 18122 struct bpf_insn_aux_data *aux_data = env->insn_aux_data; 18123 struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0); 18124 struct bpf_insn *insn = env->prog->insnsi; 18125 const int insn_cnt = env->prog->len; 18126 int i; 18127 18128 for (i = 0; i < insn_cnt; i++, insn++) { 18129 if (!insn_is_cond_jump(insn->code)) 18130 continue; 18131 18132 if (!aux_data[i + 1].seen) 18133 ja.off = insn->off; 18134 else if (!aux_data[i + 1 + insn->off].seen) 18135 ja.off = 0; 18136 else 18137 continue; 18138 18139 if (bpf_prog_is_offloaded(env->prog->aux)) 18140 bpf_prog_offload_replace_insn(env, i, &ja); 18141 18142 memcpy(insn, &ja, sizeof(ja)); 18143 } 18144 } 18145 18146 static int opt_remove_dead_code(struct bpf_verifier_env *env) 18147 { 18148 struct bpf_insn_aux_data *aux_data = env->insn_aux_data; 18149 int insn_cnt = env->prog->len; 18150 int i, err; 18151 18152 for (i = 0; i < insn_cnt; i++) { 18153 int j; 18154 18155 j = 0; 18156 while (i + j < insn_cnt && !aux_data[i + j].seen) 18157 j++; 18158 if (!j) 18159 continue; 18160 18161 err = verifier_remove_insns(env, i, j); 18162 if (err) 18163 return err; 18164 insn_cnt = env->prog->len; 18165 } 18166 18167 return 0; 18168 } 18169 18170 static int opt_remove_nops(struct bpf_verifier_env *env) 18171 { 18172 const struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0); 18173 struct bpf_insn *insn = env->prog->insnsi; 18174 int insn_cnt = env->prog->len; 18175 int i, err; 18176 18177 for (i = 0; i < insn_cnt; i++) { 18178 if (memcmp(&insn[i], &ja, sizeof(ja))) 18179 continue; 18180 18181 err = verifier_remove_insns(env, i, 1); 18182 if (err) 18183 return err; 18184 insn_cnt--; 18185 i--; 18186 } 18187 18188 return 0; 18189 } 18190 18191 static int opt_subreg_zext_lo32_rnd_hi32(struct bpf_verifier_env *env, 18192 const union bpf_attr *attr) 18193 { 18194 struct bpf_insn *patch, zext_patch[2], rnd_hi32_patch[4]; 18195 struct bpf_insn_aux_data *aux = env->insn_aux_data; 18196 int i, patch_len, delta = 0, len = env->prog->len; 18197 struct bpf_insn *insns = env->prog->insnsi; 18198 struct bpf_prog *new_prog; 18199 bool rnd_hi32; 18200 18201 rnd_hi32 = attr->prog_flags & BPF_F_TEST_RND_HI32; 18202 zext_patch[1] = BPF_ZEXT_REG(0); 18203 rnd_hi32_patch[1] = BPF_ALU64_IMM(BPF_MOV, BPF_REG_AX, 0); 18204 rnd_hi32_patch[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_AX, 32); 18205 rnd_hi32_patch[3] = BPF_ALU64_REG(BPF_OR, 0, BPF_REG_AX); 18206 for (i = 0; i < len; i++) { 18207 int adj_idx = i + delta; 18208 struct bpf_insn insn; 18209 int load_reg; 18210 18211 insn = insns[adj_idx]; 18212 load_reg = insn_def_regno(&insn); 18213 if (!aux[adj_idx].zext_dst) { 18214 u8 code, class; 18215 u32 imm_rnd; 18216 18217 if (!rnd_hi32) 18218 continue; 18219 18220 code = insn.code; 18221 class = BPF_CLASS(code); 18222 if (load_reg == -1) 18223 continue; 18224 18225 /* NOTE: arg "reg" (the fourth one) is only used for 18226 * BPF_STX + SRC_OP, so it is safe to pass NULL 18227 * here. 18228 */ 18229 if (is_reg64(env, &insn, load_reg, NULL, DST_OP)) { 18230 if (class == BPF_LD && 18231 BPF_MODE(code) == BPF_IMM) 18232 i++; 18233 continue; 18234 } 18235 18236 /* ctx load could be transformed into wider load. */ 18237 if (class == BPF_LDX && 18238 aux[adj_idx].ptr_type == PTR_TO_CTX) 18239 continue; 18240 18241 imm_rnd = get_random_u32(); 18242 rnd_hi32_patch[0] = insn; 18243 rnd_hi32_patch[1].imm = imm_rnd; 18244 rnd_hi32_patch[3].dst_reg = load_reg; 18245 patch = rnd_hi32_patch; 18246 patch_len = 4; 18247 goto apply_patch_buffer; 18248 } 18249 18250 /* Add in an zero-extend instruction if a) the JIT has requested 18251 * it or b) it's a CMPXCHG. 18252 * 18253 * The latter is because: BPF_CMPXCHG always loads a value into 18254 * R0, therefore always zero-extends. However some archs' 18255 * equivalent instruction only does this load when the 18256 * comparison is successful. This detail of CMPXCHG is 18257 * orthogonal to the general zero-extension behaviour of the 18258 * CPU, so it's treated independently of bpf_jit_needs_zext. 18259 */ 18260 if (!bpf_jit_needs_zext() && !is_cmpxchg_insn(&insn)) 18261 continue; 18262 18263 /* Zero-extension is done by the caller. */ 18264 if (bpf_pseudo_kfunc_call(&insn)) 18265 continue; 18266 18267 if (WARN_ON(load_reg == -1)) { 18268 verbose(env, "verifier bug. zext_dst is set, but no reg is defined\n"); 18269 return -EFAULT; 18270 } 18271 18272 zext_patch[0] = insn; 18273 zext_patch[1].dst_reg = load_reg; 18274 zext_patch[1].src_reg = load_reg; 18275 patch = zext_patch; 18276 patch_len = 2; 18277 apply_patch_buffer: 18278 new_prog = bpf_patch_insn_data(env, adj_idx, patch, patch_len); 18279 if (!new_prog) 18280 return -ENOMEM; 18281 env->prog = new_prog; 18282 insns = new_prog->insnsi; 18283 aux = env->insn_aux_data; 18284 delta += patch_len - 1; 18285 } 18286 18287 return 0; 18288 } 18289 18290 /* convert load instructions that access fields of a context type into a 18291 * sequence of instructions that access fields of the underlying structure: 18292 * struct __sk_buff -> struct sk_buff 18293 * struct bpf_sock_ops -> struct sock 18294 */ 18295 static int convert_ctx_accesses(struct bpf_verifier_env *env) 18296 { 18297 const struct bpf_verifier_ops *ops = env->ops; 18298 int i, cnt, size, ctx_field_size, delta = 0; 18299 const int insn_cnt = env->prog->len; 18300 struct bpf_insn insn_buf[16], *insn; 18301 u32 target_size, size_default, off; 18302 struct bpf_prog *new_prog; 18303 enum bpf_access_type type; 18304 bool is_narrower_load; 18305 18306 if (ops->gen_prologue || env->seen_direct_write) { 18307 if (!ops->gen_prologue) { 18308 verbose(env, "bpf verifier is misconfigured\n"); 18309 return -EINVAL; 18310 } 18311 cnt = ops->gen_prologue(insn_buf, env->seen_direct_write, 18312 env->prog); 18313 if (cnt >= ARRAY_SIZE(insn_buf)) { 18314 verbose(env, "bpf verifier is misconfigured\n"); 18315 return -EINVAL; 18316 } else if (cnt) { 18317 new_prog = bpf_patch_insn_data(env, 0, insn_buf, cnt); 18318 if (!new_prog) 18319 return -ENOMEM; 18320 18321 env->prog = new_prog; 18322 delta += cnt - 1; 18323 } 18324 } 18325 18326 if (bpf_prog_is_offloaded(env->prog->aux)) 18327 return 0; 18328 18329 insn = env->prog->insnsi + delta; 18330 18331 for (i = 0; i < insn_cnt; i++, insn++) { 18332 bpf_convert_ctx_access_t convert_ctx_access; 18333 u8 mode; 18334 18335 if (insn->code == (BPF_LDX | BPF_MEM | BPF_B) || 18336 insn->code == (BPF_LDX | BPF_MEM | BPF_H) || 18337 insn->code == (BPF_LDX | BPF_MEM | BPF_W) || 18338 insn->code == (BPF_LDX | BPF_MEM | BPF_DW) || 18339 insn->code == (BPF_LDX | BPF_MEMSX | BPF_B) || 18340 insn->code == (BPF_LDX | BPF_MEMSX | BPF_H) || 18341 insn->code == (BPF_LDX | BPF_MEMSX | BPF_W)) { 18342 type = BPF_READ; 18343 } else if (insn->code == (BPF_STX | BPF_MEM | BPF_B) || 18344 insn->code == (BPF_STX | BPF_MEM | BPF_H) || 18345 insn->code == (BPF_STX | BPF_MEM | BPF_W) || 18346 insn->code == (BPF_STX | BPF_MEM | BPF_DW) || 18347 insn->code == (BPF_ST | BPF_MEM | BPF_B) || 18348 insn->code == (BPF_ST | BPF_MEM | BPF_H) || 18349 insn->code == (BPF_ST | BPF_MEM | BPF_W) || 18350 insn->code == (BPF_ST | BPF_MEM | BPF_DW)) { 18351 type = BPF_WRITE; 18352 } else { 18353 continue; 18354 } 18355 18356 if (type == BPF_WRITE && 18357 env->insn_aux_data[i + delta].sanitize_stack_spill) { 18358 struct bpf_insn patch[] = { 18359 *insn, 18360 BPF_ST_NOSPEC(), 18361 }; 18362 18363 cnt = ARRAY_SIZE(patch); 18364 new_prog = bpf_patch_insn_data(env, i + delta, patch, cnt); 18365 if (!new_prog) 18366 return -ENOMEM; 18367 18368 delta += cnt - 1; 18369 env->prog = new_prog; 18370 insn = new_prog->insnsi + i + delta; 18371 continue; 18372 } 18373 18374 switch ((int)env->insn_aux_data[i + delta].ptr_type) { 18375 case PTR_TO_CTX: 18376 if (!ops->convert_ctx_access) 18377 continue; 18378 convert_ctx_access = ops->convert_ctx_access; 18379 break; 18380 case PTR_TO_SOCKET: 18381 case PTR_TO_SOCK_COMMON: 18382 convert_ctx_access = bpf_sock_convert_ctx_access; 18383 break; 18384 case PTR_TO_TCP_SOCK: 18385 convert_ctx_access = bpf_tcp_sock_convert_ctx_access; 18386 break; 18387 case PTR_TO_XDP_SOCK: 18388 convert_ctx_access = bpf_xdp_sock_convert_ctx_access; 18389 break; 18390 case PTR_TO_BTF_ID: 18391 case PTR_TO_BTF_ID | PTR_UNTRUSTED: 18392 /* PTR_TO_BTF_ID | MEM_ALLOC always has a valid lifetime, unlike 18393 * PTR_TO_BTF_ID, and an active ref_obj_id, but the same cannot 18394 * be said once it is marked PTR_UNTRUSTED, hence we must handle 18395 * any faults for loads into such types. BPF_WRITE is disallowed 18396 * for this case. 18397 */ 18398 case PTR_TO_BTF_ID | MEM_ALLOC | PTR_UNTRUSTED: 18399 if (type == BPF_READ) { 18400 if (BPF_MODE(insn->code) == BPF_MEM) 18401 insn->code = BPF_LDX | BPF_PROBE_MEM | 18402 BPF_SIZE((insn)->code); 18403 else 18404 insn->code = BPF_LDX | BPF_PROBE_MEMSX | 18405 BPF_SIZE((insn)->code); 18406 env->prog->aux->num_exentries++; 18407 } 18408 continue; 18409 default: 18410 continue; 18411 } 18412 18413 ctx_field_size = env->insn_aux_data[i + delta].ctx_field_size; 18414 size = BPF_LDST_BYTES(insn); 18415 mode = BPF_MODE(insn->code); 18416 18417 /* If the read access is a narrower load of the field, 18418 * convert to a 4/8-byte load, to minimum program type specific 18419 * convert_ctx_access changes. If conversion is successful, 18420 * we will apply proper mask to the result. 18421 */ 18422 is_narrower_load = size < ctx_field_size; 18423 size_default = bpf_ctx_off_adjust_machine(ctx_field_size); 18424 off = insn->off; 18425 if (is_narrower_load) { 18426 u8 size_code; 18427 18428 if (type == BPF_WRITE) { 18429 verbose(env, "bpf verifier narrow ctx access misconfigured\n"); 18430 return -EINVAL; 18431 } 18432 18433 size_code = BPF_H; 18434 if (ctx_field_size == 4) 18435 size_code = BPF_W; 18436 else if (ctx_field_size == 8) 18437 size_code = BPF_DW; 18438 18439 insn->off = off & ~(size_default - 1); 18440 insn->code = BPF_LDX | BPF_MEM | size_code; 18441 } 18442 18443 target_size = 0; 18444 cnt = convert_ctx_access(type, insn, insn_buf, env->prog, 18445 &target_size); 18446 if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf) || 18447 (ctx_field_size && !target_size)) { 18448 verbose(env, "bpf verifier is misconfigured\n"); 18449 return -EINVAL; 18450 } 18451 18452 if (is_narrower_load && size < target_size) { 18453 u8 shift = bpf_ctx_narrow_access_offset( 18454 off, size, size_default) * 8; 18455 if (shift && cnt + 1 >= ARRAY_SIZE(insn_buf)) { 18456 verbose(env, "bpf verifier narrow ctx load misconfigured\n"); 18457 return -EINVAL; 18458 } 18459 if (ctx_field_size <= 4) { 18460 if (shift) 18461 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_RSH, 18462 insn->dst_reg, 18463 shift); 18464 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg, 18465 (1 << size * 8) - 1); 18466 } else { 18467 if (shift) 18468 insn_buf[cnt++] = BPF_ALU64_IMM(BPF_RSH, 18469 insn->dst_reg, 18470 shift); 18471 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg, 18472 (1ULL << size * 8) - 1); 18473 } 18474 } 18475 if (mode == BPF_MEMSX) 18476 insn_buf[cnt++] = BPF_RAW_INSN(BPF_ALU64 | BPF_MOV | BPF_X, 18477 insn->dst_reg, insn->dst_reg, 18478 size * 8, 0); 18479 18480 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 18481 if (!new_prog) 18482 return -ENOMEM; 18483 18484 delta += cnt - 1; 18485 18486 /* keep walking new program and skip insns we just inserted */ 18487 env->prog = new_prog; 18488 insn = new_prog->insnsi + i + delta; 18489 } 18490 18491 return 0; 18492 } 18493 18494 static int jit_subprogs(struct bpf_verifier_env *env) 18495 { 18496 struct bpf_prog *prog = env->prog, **func, *tmp; 18497 int i, j, subprog_start, subprog_end = 0, len, subprog; 18498 struct bpf_map *map_ptr; 18499 struct bpf_insn *insn; 18500 void *old_bpf_func; 18501 int err, num_exentries; 18502 18503 if (env->subprog_cnt <= 1) 18504 return 0; 18505 18506 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) { 18507 if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn)) 18508 continue; 18509 18510 /* Upon error here we cannot fall back to interpreter but 18511 * need a hard reject of the program. Thus -EFAULT is 18512 * propagated in any case. 18513 */ 18514 subprog = find_subprog(env, i + insn->imm + 1); 18515 if (subprog < 0) { 18516 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n", 18517 i + insn->imm + 1); 18518 return -EFAULT; 18519 } 18520 /* temporarily remember subprog id inside insn instead of 18521 * aux_data, since next loop will split up all insns into funcs 18522 */ 18523 insn->off = subprog; 18524 /* remember original imm in case JIT fails and fallback 18525 * to interpreter will be needed 18526 */ 18527 env->insn_aux_data[i].call_imm = insn->imm; 18528 /* point imm to __bpf_call_base+1 from JITs point of view */ 18529 insn->imm = 1; 18530 if (bpf_pseudo_func(insn)) 18531 /* jit (e.g. x86_64) may emit fewer instructions 18532 * if it learns a u32 imm is the same as a u64 imm. 18533 * Force a non zero here. 18534 */ 18535 insn[1].imm = 1; 18536 } 18537 18538 err = bpf_prog_alloc_jited_linfo(prog); 18539 if (err) 18540 goto out_undo_insn; 18541 18542 err = -ENOMEM; 18543 func = kcalloc(env->subprog_cnt, sizeof(prog), GFP_KERNEL); 18544 if (!func) 18545 goto out_undo_insn; 18546 18547 for (i = 0; i < env->subprog_cnt; i++) { 18548 subprog_start = subprog_end; 18549 subprog_end = env->subprog_info[i + 1].start; 18550 18551 len = subprog_end - subprog_start; 18552 /* bpf_prog_run() doesn't call subprogs directly, 18553 * hence main prog stats include the runtime of subprogs. 18554 * subprogs don't have IDs and not reachable via prog_get_next_id 18555 * func[i]->stats will never be accessed and stays NULL 18556 */ 18557 func[i] = bpf_prog_alloc_no_stats(bpf_prog_size(len), GFP_USER); 18558 if (!func[i]) 18559 goto out_free; 18560 memcpy(func[i]->insnsi, &prog->insnsi[subprog_start], 18561 len * sizeof(struct bpf_insn)); 18562 func[i]->type = prog->type; 18563 func[i]->len = len; 18564 if (bpf_prog_calc_tag(func[i])) 18565 goto out_free; 18566 func[i]->is_func = 1; 18567 func[i]->aux->func_idx = i; 18568 /* Below members will be freed only at prog->aux */ 18569 func[i]->aux->btf = prog->aux->btf; 18570 func[i]->aux->func_info = prog->aux->func_info; 18571 func[i]->aux->func_info_cnt = prog->aux->func_info_cnt; 18572 func[i]->aux->poke_tab = prog->aux->poke_tab; 18573 func[i]->aux->size_poke_tab = prog->aux->size_poke_tab; 18574 18575 for (j = 0; j < prog->aux->size_poke_tab; j++) { 18576 struct bpf_jit_poke_descriptor *poke; 18577 18578 poke = &prog->aux->poke_tab[j]; 18579 if (poke->insn_idx < subprog_end && 18580 poke->insn_idx >= subprog_start) 18581 poke->aux = func[i]->aux; 18582 } 18583 18584 func[i]->aux->name[0] = 'F'; 18585 func[i]->aux->stack_depth = env->subprog_info[i].stack_depth; 18586 func[i]->jit_requested = 1; 18587 func[i]->blinding_requested = prog->blinding_requested; 18588 func[i]->aux->kfunc_tab = prog->aux->kfunc_tab; 18589 func[i]->aux->kfunc_btf_tab = prog->aux->kfunc_btf_tab; 18590 func[i]->aux->linfo = prog->aux->linfo; 18591 func[i]->aux->nr_linfo = prog->aux->nr_linfo; 18592 func[i]->aux->jited_linfo = prog->aux->jited_linfo; 18593 func[i]->aux->linfo_idx = env->subprog_info[i].linfo_idx; 18594 num_exentries = 0; 18595 insn = func[i]->insnsi; 18596 for (j = 0; j < func[i]->len; j++, insn++) { 18597 if (BPF_CLASS(insn->code) == BPF_LDX && 18598 (BPF_MODE(insn->code) == BPF_PROBE_MEM || 18599 BPF_MODE(insn->code) == BPF_PROBE_MEMSX)) 18600 num_exentries++; 18601 } 18602 func[i]->aux->num_exentries = num_exentries; 18603 func[i]->aux->tail_call_reachable = env->subprog_info[i].tail_call_reachable; 18604 func[i] = bpf_int_jit_compile(func[i]); 18605 if (!func[i]->jited) { 18606 err = -ENOTSUPP; 18607 goto out_free; 18608 } 18609 cond_resched(); 18610 } 18611 18612 /* at this point all bpf functions were successfully JITed 18613 * now populate all bpf_calls with correct addresses and 18614 * run last pass of JIT 18615 */ 18616 for (i = 0; i < env->subprog_cnt; i++) { 18617 insn = func[i]->insnsi; 18618 for (j = 0; j < func[i]->len; j++, insn++) { 18619 if (bpf_pseudo_func(insn)) { 18620 subprog = insn->off; 18621 insn[0].imm = (u32)(long)func[subprog]->bpf_func; 18622 insn[1].imm = ((u64)(long)func[subprog]->bpf_func) >> 32; 18623 continue; 18624 } 18625 if (!bpf_pseudo_call(insn)) 18626 continue; 18627 subprog = insn->off; 18628 insn->imm = BPF_CALL_IMM(func[subprog]->bpf_func); 18629 } 18630 18631 /* we use the aux data to keep a list of the start addresses 18632 * of the JITed images for each function in the program 18633 * 18634 * for some architectures, such as powerpc64, the imm field 18635 * might not be large enough to hold the offset of the start 18636 * address of the callee's JITed image from __bpf_call_base 18637 * 18638 * in such cases, we can lookup the start address of a callee 18639 * by using its subprog id, available from the off field of 18640 * the call instruction, as an index for this list 18641 */ 18642 func[i]->aux->func = func; 18643 func[i]->aux->func_cnt = env->subprog_cnt; 18644 } 18645 for (i = 0; i < env->subprog_cnt; i++) { 18646 old_bpf_func = func[i]->bpf_func; 18647 tmp = bpf_int_jit_compile(func[i]); 18648 if (tmp != func[i] || func[i]->bpf_func != old_bpf_func) { 18649 verbose(env, "JIT doesn't support bpf-to-bpf calls\n"); 18650 err = -ENOTSUPP; 18651 goto out_free; 18652 } 18653 cond_resched(); 18654 } 18655 18656 /* finally lock prog and jit images for all functions and 18657 * populate kallsysm. Begin at the first subprogram, since 18658 * bpf_prog_load will add the kallsyms for the main program. 18659 */ 18660 for (i = 1; i < env->subprog_cnt; i++) { 18661 bpf_prog_lock_ro(func[i]); 18662 bpf_prog_kallsyms_add(func[i]); 18663 } 18664 18665 /* Last step: make now unused interpreter insns from main 18666 * prog consistent for later dump requests, so they can 18667 * later look the same as if they were interpreted only. 18668 */ 18669 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) { 18670 if (bpf_pseudo_func(insn)) { 18671 insn[0].imm = env->insn_aux_data[i].call_imm; 18672 insn[1].imm = insn->off; 18673 insn->off = 0; 18674 continue; 18675 } 18676 if (!bpf_pseudo_call(insn)) 18677 continue; 18678 insn->off = env->insn_aux_data[i].call_imm; 18679 subprog = find_subprog(env, i + insn->off + 1); 18680 insn->imm = subprog; 18681 } 18682 18683 prog->jited = 1; 18684 prog->bpf_func = func[0]->bpf_func; 18685 prog->jited_len = func[0]->jited_len; 18686 prog->aux->extable = func[0]->aux->extable; 18687 prog->aux->num_exentries = func[0]->aux->num_exentries; 18688 prog->aux->func = func; 18689 prog->aux->func_cnt = env->subprog_cnt; 18690 bpf_prog_jit_attempt_done(prog); 18691 return 0; 18692 out_free: 18693 /* We failed JIT'ing, so at this point we need to unregister poke 18694 * descriptors from subprogs, so that kernel is not attempting to 18695 * patch it anymore as we're freeing the subprog JIT memory. 18696 */ 18697 for (i = 0; i < prog->aux->size_poke_tab; i++) { 18698 map_ptr = prog->aux->poke_tab[i].tail_call.map; 18699 map_ptr->ops->map_poke_untrack(map_ptr, prog->aux); 18700 } 18701 /* At this point we're guaranteed that poke descriptors are not 18702 * live anymore. We can just unlink its descriptor table as it's 18703 * released with the main prog. 18704 */ 18705 for (i = 0; i < env->subprog_cnt; i++) { 18706 if (!func[i]) 18707 continue; 18708 func[i]->aux->poke_tab = NULL; 18709 bpf_jit_free(func[i]); 18710 } 18711 kfree(func); 18712 out_undo_insn: 18713 /* cleanup main prog to be interpreted */ 18714 prog->jit_requested = 0; 18715 prog->blinding_requested = 0; 18716 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) { 18717 if (!bpf_pseudo_call(insn)) 18718 continue; 18719 insn->off = 0; 18720 insn->imm = env->insn_aux_data[i].call_imm; 18721 } 18722 bpf_prog_jit_attempt_done(prog); 18723 return err; 18724 } 18725 18726 static int fixup_call_args(struct bpf_verifier_env *env) 18727 { 18728 #ifndef CONFIG_BPF_JIT_ALWAYS_ON 18729 struct bpf_prog *prog = env->prog; 18730 struct bpf_insn *insn = prog->insnsi; 18731 bool has_kfunc_call = bpf_prog_has_kfunc_call(prog); 18732 int i, depth; 18733 #endif 18734 int err = 0; 18735 18736 if (env->prog->jit_requested && 18737 !bpf_prog_is_offloaded(env->prog->aux)) { 18738 err = jit_subprogs(env); 18739 if (err == 0) 18740 return 0; 18741 if (err == -EFAULT) 18742 return err; 18743 } 18744 #ifndef CONFIG_BPF_JIT_ALWAYS_ON 18745 if (has_kfunc_call) { 18746 verbose(env, "calling kernel functions are not allowed in non-JITed programs\n"); 18747 return -EINVAL; 18748 } 18749 if (env->subprog_cnt > 1 && env->prog->aux->tail_call_reachable) { 18750 /* When JIT fails the progs with bpf2bpf calls and tail_calls 18751 * have to be rejected, since interpreter doesn't support them yet. 18752 */ 18753 verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n"); 18754 return -EINVAL; 18755 } 18756 for (i = 0; i < prog->len; i++, insn++) { 18757 if (bpf_pseudo_func(insn)) { 18758 /* When JIT fails the progs with callback calls 18759 * have to be rejected, since interpreter doesn't support them yet. 18760 */ 18761 verbose(env, "callbacks are not allowed in non-JITed programs\n"); 18762 return -EINVAL; 18763 } 18764 18765 if (!bpf_pseudo_call(insn)) 18766 continue; 18767 depth = get_callee_stack_depth(env, insn, i); 18768 if (depth < 0) 18769 return depth; 18770 bpf_patch_call_args(insn, depth); 18771 } 18772 err = 0; 18773 #endif 18774 return err; 18775 } 18776 18777 /* replace a generic kfunc with a specialized version if necessary */ 18778 static void specialize_kfunc(struct bpf_verifier_env *env, 18779 u32 func_id, u16 offset, unsigned long *addr) 18780 { 18781 struct bpf_prog *prog = env->prog; 18782 bool seen_direct_write; 18783 void *xdp_kfunc; 18784 bool is_rdonly; 18785 18786 if (bpf_dev_bound_kfunc_id(func_id)) { 18787 xdp_kfunc = bpf_dev_bound_resolve_kfunc(prog, func_id); 18788 if (xdp_kfunc) { 18789 *addr = (unsigned long)xdp_kfunc; 18790 return; 18791 } 18792 /* fallback to default kfunc when not supported by netdev */ 18793 } 18794 18795 if (offset) 18796 return; 18797 18798 if (func_id == special_kfunc_list[KF_bpf_dynptr_from_skb]) { 18799 seen_direct_write = env->seen_direct_write; 18800 is_rdonly = !may_access_direct_pkt_data(env, NULL, BPF_WRITE); 18801 18802 if (is_rdonly) 18803 *addr = (unsigned long)bpf_dynptr_from_skb_rdonly; 18804 18805 /* restore env->seen_direct_write to its original value, since 18806 * may_access_direct_pkt_data mutates it 18807 */ 18808 env->seen_direct_write = seen_direct_write; 18809 } 18810 } 18811 18812 static void __fixup_collection_insert_kfunc(struct bpf_insn_aux_data *insn_aux, 18813 u16 struct_meta_reg, 18814 u16 node_offset_reg, 18815 struct bpf_insn *insn, 18816 struct bpf_insn *insn_buf, 18817 int *cnt) 18818 { 18819 struct btf_struct_meta *kptr_struct_meta = insn_aux->kptr_struct_meta; 18820 struct bpf_insn addr[2] = { BPF_LD_IMM64(struct_meta_reg, (long)kptr_struct_meta) }; 18821 18822 insn_buf[0] = addr[0]; 18823 insn_buf[1] = addr[1]; 18824 insn_buf[2] = BPF_MOV64_IMM(node_offset_reg, insn_aux->insert_off); 18825 insn_buf[3] = *insn; 18826 *cnt = 4; 18827 } 18828 18829 static int fixup_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn, 18830 struct bpf_insn *insn_buf, int insn_idx, int *cnt) 18831 { 18832 const struct bpf_kfunc_desc *desc; 18833 18834 if (!insn->imm) { 18835 verbose(env, "invalid kernel function call not eliminated in verifier pass\n"); 18836 return -EINVAL; 18837 } 18838 18839 *cnt = 0; 18840 18841 /* insn->imm has the btf func_id. Replace it with an offset relative to 18842 * __bpf_call_base, unless the JIT needs to call functions that are 18843 * further than 32 bits away (bpf_jit_supports_far_kfunc_call()). 18844 */ 18845 desc = find_kfunc_desc(env->prog, insn->imm, insn->off); 18846 if (!desc) { 18847 verbose(env, "verifier internal error: kernel function descriptor not found for func_id %u\n", 18848 insn->imm); 18849 return -EFAULT; 18850 } 18851 18852 if (!bpf_jit_supports_far_kfunc_call()) 18853 insn->imm = BPF_CALL_IMM(desc->addr); 18854 if (insn->off) 18855 return 0; 18856 if (desc->func_id == special_kfunc_list[KF_bpf_obj_new_impl]) { 18857 struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta; 18858 struct bpf_insn addr[2] = { BPF_LD_IMM64(BPF_REG_2, (long)kptr_struct_meta) }; 18859 u64 obj_new_size = env->insn_aux_data[insn_idx].obj_new_size; 18860 18861 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_1, obj_new_size); 18862 insn_buf[1] = addr[0]; 18863 insn_buf[2] = addr[1]; 18864 insn_buf[3] = *insn; 18865 *cnt = 4; 18866 } else if (desc->func_id == special_kfunc_list[KF_bpf_obj_drop_impl] || 18867 desc->func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl]) { 18868 struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta; 18869 struct bpf_insn addr[2] = { BPF_LD_IMM64(BPF_REG_2, (long)kptr_struct_meta) }; 18870 18871 if (desc->func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl] && 18872 !kptr_struct_meta) { 18873 verbose(env, "verifier internal error: kptr_struct_meta expected at insn_idx %d\n", 18874 insn_idx); 18875 return -EFAULT; 18876 } 18877 18878 insn_buf[0] = addr[0]; 18879 insn_buf[1] = addr[1]; 18880 insn_buf[2] = *insn; 18881 *cnt = 3; 18882 } else if (desc->func_id == special_kfunc_list[KF_bpf_list_push_back_impl] || 18883 desc->func_id == special_kfunc_list[KF_bpf_list_push_front_impl] || 18884 desc->func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) { 18885 struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta; 18886 int struct_meta_reg = BPF_REG_3; 18887 int node_offset_reg = BPF_REG_4; 18888 18889 /* rbtree_add has extra 'less' arg, so args-to-fixup are in diff regs */ 18890 if (desc->func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) { 18891 struct_meta_reg = BPF_REG_4; 18892 node_offset_reg = BPF_REG_5; 18893 } 18894 18895 if (!kptr_struct_meta) { 18896 verbose(env, "verifier internal error: kptr_struct_meta expected at insn_idx %d\n", 18897 insn_idx); 18898 return -EFAULT; 18899 } 18900 18901 __fixup_collection_insert_kfunc(&env->insn_aux_data[insn_idx], struct_meta_reg, 18902 node_offset_reg, insn, insn_buf, cnt); 18903 } else if (desc->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx] || 18904 desc->func_id == special_kfunc_list[KF_bpf_rdonly_cast]) { 18905 insn_buf[0] = BPF_MOV64_REG(BPF_REG_0, BPF_REG_1); 18906 *cnt = 1; 18907 } 18908 return 0; 18909 } 18910 18911 /* Do various post-verification rewrites in a single program pass. 18912 * These rewrites simplify JIT and interpreter implementations. 18913 */ 18914 static int do_misc_fixups(struct bpf_verifier_env *env) 18915 { 18916 struct bpf_prog *prog = env->prog; 18917 enum bpf_attach_type eatype = prog->expected_attach_type; 18918 enum bpf_prog_type prog_type = resolve_prog_type(prog); 18919 struct bpf_insn *insn = prog->insnsi; 18920 const struct bpf_func_proto *fn; 18921 const int insn_cnt = prog->len; 18922 const struct bpf_map_ops *ops; 18923 struct bpf_insn_aux_data *aux; 18924 struct bpf_insn insn_buf[16]; 18925 struct bpf_prog *new_prog; 18926 struct bpf_map *map_ptr; 18927 int i, ret, cnt, delta = 0; 18928 18929 for (i = 0; i < insn_cnt; i++, insn++) { 18930 /* Make divide-by-zero exceptions impossible. */ 18931 if (insn->code == (BPF_ALU64 | BPF_MOD | BPF_X) || 18932 insn->code == (BPF_ALU64 | BPF_DIV | BPF_X) || 18933 insn->code == (BPF_ALU | BPF_MOD | BPF_X) || 18934 insn->code == (BPF_ALU | BPF_DIV | BPF_X)) { 18935 bool is64 = BPF_CLASS(insn->code) == BPF_ALU64; 18936 bool isdiv = BPF_OP(insn->code) == BPF_DIV; 18937 struct bpf_insn *patchlet; 18938 struct bpf_insn chk_and_div[] = { 18939 /* [R,W]x div 0 -> 0 */ 18940 BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) | 18941 BPF_JNE | BPF_K, insn->src_reg, 18942 0, 2, 0), 18943 BPF_ALU32_REG(BPF_XOR, insn->dst_reg, insn->dst_reg), 18944 BPF_JMP_IMM(BPF_JA, 0, 0, 1), 18945 *insn, 18946 }; 18947 struct bpf_insn chk_and_mod[] = { 18948 /* [R,W]x mod 0 -> [R,W]x */ 18949 BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) | 18950 BPF_JEQ | BPF_K, insn->src_reg, 18951 0, 1 + (is64 ? 0 : 1), 0), 18952 *insn, 18953 BPF_JMP_IMM(BPF_JA, 0, 0, 1), 18954 BPF_MOV32_REG(insn->dst_reg, insn->dst_reg), 18955 }; 18956 18957 patchlet = isdiv ? chk_and_div : chk_and_mod; 18958 cnt = isdiv ? ARRAY_SIZE(chk_and_div) : 18959 ARRAY_SIZE(chk_and_mod) - (is64 ? 2 : 0); 18960 18961 new_prog = bpf_patch_insn_data(env, i + delta, patchlet, cnt); 18962 if (!new_prog) 18963 return -ENOMEM; 18964 18965 delta += cnt - 1; 18966 env->prog = prog = new_prog; 18967 insn = new_prog->insnsi + i + delta; 18968 continue; 18969 } 18970 18971 /* Implement LD_ABS and LD_IND with a rewrite, if supported by the program type. */ 18972 if (BPF_CLASS(insn->code) == BPF_LD && 18973 (BPF_MODE(insn->code) == BPF_ABS || 18974 BPF_MODE(insn->code) == BPF_IND)) { 18975 cnt = env->ops->gen_ld_abs(insn, insn_buf); 18976 if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf)) { 18977 verbose(env, "bpf verifier is misconfigured\n"); 18978 return -EINVAL; 18979 } 18980 18981 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 18982 if (!new_prog) 18983 return -ENOMEM; 18984 18985 delta += cnt - 1; 18986 env->prog = prog = new_prog; 18987 insn = new_prog->insnsi + i + delta; 18988 continue; 18989 } 18990 18991 /* Rewrite pointer arithmetic to mitigate speculation attacks. */ 18992 if (insn->code == (BPF_ALU64 | BPF_ADD | BPF_X) || 18993 insn->code == (BPF_ALU64 | BPF_SUB | BPF_X)) { 18994 const u8 code_add = BPF_ALU64 | BPF_ADD | BPF_X; 18995 const u8 code_sub = BPF_ALU64 | BPF_SUB | BPF_X; 18996 struct bpf_insn *patch = &insn_buf[0]; 18997 bool issrc, isneg, isimm; 18998 u32 off_reg; 18999 19000 aux = &env->insn_aux_data[i + delta]; 19001 if (!aux->alu_state || 19002 aux->alu_state == BPF_ALU_NON_POINTER) 19003 continue; 19004 19005 isneg = aux->alu_state & BPF_ALU_NEG_VALUE; 19006 issrc = (aux->alu_state & BPF_ALU_SANITIZE) == 19007 BPF_ALU_SANITIZE_SRC; 19008 isimm = aux->alu_state & BPF_ALU_IMMEDIATE; 19009 19010 off_reg = issrc ? insn->src_reg : insn->dst_reg; 19011 if (isimm) { 19012 *patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit); 19013 } else { 19014 if (isneg) 19015 *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1); 19016 *patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit); 19017 *patch++ = BPF_ALU64_REG(BPF_SUB, BPF_REG_AX, off_reg); 19018 *patch++ = BPF_ALU64_REG(BPF_OR, BPF_REG_AX, off_reg); 19019 *patch++ = BPF_ALU64_IMM(BPF_NEG, BPF_REG_AX, 0); 19020 *patch++ = BPF_ALU64_IMM(BPF_ARSH, BPF_REG_AX, 63); 19021 *patch++ = BPF_ALU64_REG(BPF_AND, BPF_REG_AX, off_reg); 19022 } 19023 if (!issrc) 19024 *patch++ = BPF_MOV64_REG(insn->dst_reg, insn->src_reg); 19025 insn->src_reg = BPF_REG_AX; 19026 if (isneg) 19027 insn->code = insn->code == code_add ? 19028 code_sub : code_add; 19029 *patch++ = *insn; 19030 if (issrc && isneg && !isimm) 19031 *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1); 19032 cnt = patch - insn_buf; 19033 19034 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 19035 if (!new_prog) 19036 return -ENOMEM; 19037 19038 delta += cnt - 1; 19039 env->prog = prog = new_prog; 19040 insn = new_prog->insnsi + i + delta; 19041 continue; 19042 } 19043 19044 if (insn->code != (BPF_JMP | BPF_CALL)) 19045 continue; 19046 if (insn->src_reg == BPF_PSEUDO_CALL) 19047 continue; 19048 if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) { 19049 ret = fixup_kfunc_call(env, insn, insn_buf, i + delta, &cnt); 19050 if (ret) 19051 return ret; 19052 if (cnt == 0) 19053 continue; 19054 19055 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 19056 if (!new_prog) 19057 return -ENOMEM; 19058 19059 delta += cnt - 1; 19060 env->prog = prog = new_prog; 19061 insn = new_prog->insnsi + i + delta; 19062 continue; 19063 } 19064 19065 if (insn->imm == BPF_FUNC_get_route_realm) 19066 prog->dst_needed = 1; 19067 if (insn->imm == BPF_FUNC_get_prandom_u32) 19068 bpf_user_rnd_init_once(); 19069 if (insn->imm == BPF_FUNC_override_return) 19070 prog->kprobe_override = 1; 19071 if (insn->imm == BPF_FUNC_tail_call) { 19072 /* If we tail call into other programs, we 19073 * cannot make any assumptions since they can 19074 * be replaced dynamically during runtime in 19075 * the program array. 19076 */ 19077 prog->cb_access = 1; 19078 if (!allow_tail_call_in_subprogs(env)) 19079 prog->aux->stack_depth = MAX_BPF_STACK; 19080 prog->aux->max_pkt_offset = MAX_PACKET_OFF; 19081 19082 /* mark bpf_tail_call as different opcode to avoid 19083 * conditional branch in the interpreter for every normal 19084 * call and to prevent accidental JITing by JIT compiler 19085 * that doesn't support bpf_tail_call yet 19086 */ 19087 insn->imm = 0; 19088 insn->code = BPF_JMP | BPF_TAIL_CALL; 19089 19090 aux = &env->insn_aux_data[i + delta]; 19091 if (env->bpf_capable && !prog->blinding_requested && 19092 prog->jit_requested && 19093 !bpf_map_key_poisoned(aux) && 19094 !bpf_map_ptr_poisoned(aux) && 19095 !bpf_map_ptr_unpriv(aux)) { 19096 struct bpf_jit_poke_descriptor desc = { 19097 .reason = BPF_POKE_REASON_TAIL_CALL, 19098 .tail_call.map = BPF_MAP_PTR(aux->map_ptr_state), 19099 .tail_call.key = bpf_map_key_immediate(aux), 19100 .insn_idx = i + delta, 19101 }; 19102 19103 ret = bpf_jit_add_poke_descriptor(prog, &desc); 19104 if (ret < 0) { 19105 verbose(env, "adding tail call poke descriptor failed\n"); 19106 return ret; 19107 } 19108 19109 insn->imm = ret + 1; 19110 continue; 19111 } 19112 19113 if (!bpf_map_ptr_unpriv(aux)) 19114 continue; 19115 19116 /* instead of changing every JIT dealing with tail_call 19117 * emit two extra insns: 19118 * if (index >= max_entries) goto out; 19119 * index &= array->index_mask; 19120 * to avoid out-of-bounds cpu speculation 19121 */ 19122 if (bpf_map_ptr_poisoned(aux)) { 19123 verbose(env, "tail_call abusing map_ptr\n"); 19124 return -EINVAL; 19125 } 19126 19127 map_ptr = BPF_MAP_PTR(aux->map_ptr_state); 19128 insn_buf[0] = BPF_JMP_IMM(BPF_JGE, BPF_REG_3, 19129 map_ptr->max_entries, 2); 19130 insn_buf[1] = BPF_ALU32_IMM(BPF_AND, BPF_REG_3, 19131 container_of(map_ptr, 19132 struct bpf_array, 19133 map)->index_mask); 19134 insn_buf[2] = *insn; 19135 cnt = 3; 19136 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 19137 if (!new_prog) 19138 return -ENOMEM; 19139 19140 delta += cnt - 1; 19141 env->prog = prog = new_prog; 19142 insn = new_prog->insnsi + i + delta; 19143 continue; 19144 } 19145 19146 if (insn->imm == BPF_FUNC_timer_set_callback) { 19147 /* The verifier will process callback_fn as many times as necessary 19148 * with different maps and the register states prepared by 19149 * set_timer_callback_state will be accurate. 19150 * 19151 * The following use case is valid: 19152 * map1 is shared by prog1, prog2, prog3. 19153 * prog1 calls bpf_timer_init for some map1 elements 19154 * prog2 calls bpf_timer_set_callback for some map1 elements. 19155 * Those that were not bpf_timer_init-ed will return -EINVAL. 19156 * prog3 calls bpf_timer_start for some map1 elements. 19157 * Those that were not both bpf_timer_init-ed and 19158 * bpf_timer_set_callback-ed will return -EINVAL. 19159 */ 19160 struct bpf_insn ld_addrs[2] = { 19161 BPF_LD_IMM64(BPF_REG_3, (long)prog->aux), 19162 }; 19163 19164 insn_buf[0] = ld_addrs[0]; 19165 insn_buf[1] = ld_addrs[1]; 19166 insn_buf[2] = *insn; 19167 cnt = 3; 19168 19169 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 19170 if (!new_prog) 19171 return -ENOMEM; 19172 19173 delta += cnt - 1; 19174 env->prog = prog = new_prog; 19175 insn = new_prog->insnsi + i + delta; 19176 goto patch_call_imm; 19177 } 19178 19179 if (is_storage_get_function(insn->imm)) { 19180 if (!env->prog->aux->sleepable || 19181 env->insn_aux_data[i + delta].storage_get_func_atomic) 19182 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_5, (__force __s32)GFP_ATOMIC); 19183 else 19184 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_5, (__force __s32)GFP_KERNEL); 19185 insn_buf[1] = *insn; 19186 cnt = 2; 19187 19188 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 19189 if (!new_prog) 19190 return -ENOMEM; 19191 19192 delta += cnt - 1; 19193 env->prog = prog = new_prog; 19194 insn = new_prog->insnsi + i + delta; 19195 goto patch_call_imm; 19196 } 19197 19198 /* BPF_EMIT_CALL() assumptions in some of the map_gen_lookup 19199 * and other inlining handlers are currently limited to 64 bit 19200 * only. 19201 */ 19202 if (prog->jit_requested && BITS_PER_LONG == 64 && 19203 (insn->imm == BPF_FUNC_map_lookup_elem || 19204 insn->imm == BPF_FUNC_map_update_elem || 19205 insn->imm == BPF_FUNC_map_delete_elem || 19206 insn->imm == BPF_FUNC_map_push_elem || 19207 insn->imm == BPF_FUNC_map_pop_elem || 19208 insn->imm == BPF_FUNC_map_peek_elem || 19209 insn->imm == BPF_FUNC_redirect_map || 19210 insn->imm == BPF_FUNC_for_each_map_elem || 19211 insn->imm == BPF_FUNC_map_lookup_percpu_elem)) { 19212 aux = &env->insn_aux_data[i + delta]; 19213 if (bpf_map_ptr_poisoned(aux)) 19214 goto patch_call_imm; 19215 19216 map_ptr = BPF_MAP_PTR(aux->map_ptr_state); 19217 ops = map_ptr->ops; 19218 if (insn->imm == BPF_FUNC_map_lookup_elem && 19219 ops->map_gen_lookup) { 19220 cnt = ops->map_gen_lookup(map_ptr, insn_buf); 19221 if (cnt == -EOPNOTSUPP) 19222 goto patch_map_ops_generic; 19223 if (cnt <= 0 || cnt >= ARRAY_SIZE(insn_buf)) { 19224 verbose(env, "bpf verifier is misconfigured\n"); 19225 return -EINVAL; 19226 } 19227 19228 new_prog = bpf_patch_insn_data(env, i + delta, 19229 insn_buf, cnt); 19230 if (!new_prog) 19231 return -ENOMEM; 19232 19233 delta += cnt - 1; 19234 env->prog = prog = new_prog; 19235 insn = new_prog->insnsi + i + delta; 19236 continue; 19237 } 19238 19239 BUILD_BUG_ON(!__same_type(ops->map_lookup_elem, 19240 (void *(*)(struct bpf_map *map, void *key))NULL)); 19241 BUILD_BUG_ON(!__same_type(ops->map_delete_elem, 19242 (long (*)(struct bpf_map *map, void *key))NULL)); 19243 BUILD_BUG_ON(!__same_type(ops->map_update_elem, 19244 (long (*)(struct bpf_map *map, void *key, void *value, 19245 u64 flags))NULL)); 19246 BUILD_BUG_ON(!__same_type(ops->map_push_elem, 19247 (long (*)(struct bpf_map *map, void *value, 19248 u64 flags))NULL)); 19249 BUILD_BUG_ON(!__same_type(ops->map_pop_elem, 19250 (long (*)(struct bpf_map *map, void *value))NULL)); 19251 BUILD_BUG_ON(!__same_type(ops->map_peek_elem, 19252 (long (*)(struct bpf_map *map, void *value))NULL)); 19253 BUILD_BUG_ON(!__same_type(ops->map_redirect, 19254 (long (*)(struct bpf_map *map, u64 index, u64 flags))NULL)); 19255 BUILD_BUG_ON(!__same_type(ops->map_for_each_callback, 19256 (long (*)(struct bpf_map *map, 19257 bpf_callback_t callback_fn, 19258 void *callback_ctx, 19259 u64 flags))NULL)); 19260 BUILD_BUG_ON(!__same_type(ops->map_lookup_percpu_elem, 19261 (void *(*)(struct bpf_map *map, void *key, u32 cpu))NULL)); 19262 19263 patch_map_ops_generic: 19264 switch (insn->imm) { 19265 case BPF_FUNC_map_lookup_elem: 19266 insn->imm = BPF_CALL_IMM(ops->map_lookup_elem); 19267 continue; 19268 case BPF_FUNC_map_update_elem: 19269 insn->imm = BPF_CALL_IMM(ops->map_update_elem); 19270 continue; 19271 case BPF_FUNC_map_delete_elem: 19272 insn->imm = BPF_CALL_IMM(ops->map_delete_elem); 19273 continue; 19274 case BPF_FUNC_map_push_elem: 19275 insn->imm = BPF_CALL_IMM(ops->map_push_elem); 19276 continue; 19277 case BPF_FUNC_map_pop_elem: 19278 insn->imm = BPF_CALL_IMM(ops->map_pop_elem); 19279 continue; 19280 case BPF_FUNC_map_peek_elem: 19281 insn->imm = BPF_CALL_IMM(ops->map_peek_elem); 19282 continue; 19283 case BPF_FUNC_redirect_map: 19284 insn->imm = BPF_CALL_IMM(ops->map_redirect); 19285 continue; 19286 case BPF_FUNC_for_each_map_elem: 19287 insn->imm = BPF_CALL_IMM(ops->map_for_each_callback); 19288 continue; 19289 case BPF_FUNC_map_lookup_percpu_elem: 19290 insn->imm = BPF_CALL_IMM(ops->map_lookup_percpu_elem); 19291 continue; 19292 } 19293 19294 goto patch_call_imm; 19295 } 19296 19297 /* Implement bpf_jiffies64 inline. */ 19298 if (prog->jit_requested && BITS_PER_LONG == 64 && 19299 insn->imm == BPF_FUNC_jiffies64) { 19300 struct bpf_insn ld_jiffies_addr[2] = { 19301 BPF_LD_IMM64(BPF_REG_0, 19302 (unsigned long)&jiffies), 19303 }; 19304 19305 insn_buf[0] = ld_jiffies_addr[0]; 19306 insn_buf[1] = ld_jiffies_addr[1]; 19307 insn_buf[2] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, 19308 BPF_REG_0, 0); 19309 cnt = 3; 19310 19311 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 19312 cnt); 19313 if (!new_prog) 19314 return -ENOMEM; 19315 19316 delta += cnt - 1; 19317 env->prog = prog = new_prog; 19318 insn = new_prog->insnsi + i + delta; 19319 continue; 19320 } 19321 19322 /* Implement bpf_get_func_arg inline. */ 19323 if (prog_type == BPF_PROG_TYPE_TRACING && 19324 insn->imm == BPF_FUNC_get_func_arg) { 19325 /* Load nr_args from ctx - 8 */ 19326 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8); 19327 insn_buf[1] = BPF_JMP32_REG(BPF_JGE, BPF_REG_2, BPF_REG_0, 6); 19328 insn_buf[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_2, 3); 19329 insn_buf[3] = BPF_ALU64_REG(BPF_ADD, BPF_REG_2, BPF_REG_1); 19330 insn_buf[4] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_2, 0); 19331 insn_buf[5] = BPF_STX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0); 19332 insn_buf[6] = BPF_MOV64_IMM(BPF_REG_0, 0); 19333 insn_buf[7] = BPF_JMP_A(1); 19334 insn_buf[8] = BPF_MOV64_IMM(BPF_REG_0, -EINVAL); 19335 cnt = 9; 19336 19337 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 19338 if (!new_prog) 19339 return -ENOMEM; 19340 19341 delta += cnt - 1; 19342 env->prog = prog = new_prog; 19343 insn = new_prog->insnsi + i + delta; 19344 continue; 19345 } 19346 19347 /* Implement bpf_get_func_ret inline. */ 19348 if (prog_type == BPF_PROG_TYPE_TRACING && 19349 insn->imm == BPF_FUNC_get_func_ret) { 19350 if (eatype == BPF_TRACE_FEXIT || 19351 eatype == BPF_MODIFY_RETURN) { 19352 /* Load nr_args from ctx - 8 */ 19353 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8); 19354 insn_buf[1] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_0, 3); 19355 insn_buf[2] = BPF_ALU64_REG(BPF_ADD, BPF_REG_0, BPF_REG_1); 19356 insn_buf[3] = BPF_LDX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0); 19357 insn_buf[4] = BPF_STX_MEM(BPF_DW, BPF_REG_2, BPF_REG_3, 0); 19358 insn_buf[5] = BPF_MOV64_IMM(BPF_REG_0, 0); 19359 cnt = 6; 19360 } else { 19361 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_0, -EOPNOTSUPP); 19362 cnt = 1; 19363 } 19364 19365 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 19366 if (!new_prog) 19367 return -ENOMEM; 19368 19369 delta += cnt - 1; 19370 env->prog = prog = new_prog; 19371 insn = new_prog->insnsi + i + delta; 19372 continue; 19373 } 19374 19375 /* Implement get_func_arg_cnt inline. */ 19376 if (prog_type == BPF_PROG_TYPE_TRACING && 19377 insn->imm == BPF_FUNC_get_func_arg_cnt) { 19378 /* Load nr_args from ctx - 8 */ 19379 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8); 19380 19381 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1); 19382 if (!new_prog) 19383 return -ENOMEM; 19384 19385 env->prog = prog = new_prog; 19386 insn = new_prog->insnsi + i + delta; 19387 continue; 19388 } 19389 19390 /* Implement bpf_get_func_ip inline. */ 19391 if (prog_type == BPF_PROG_TYPE_TRACING && 19392 insn->imm == BPF_FUNC_get_func_ip) { 19393 /* Load IP address from ctx - 16 */ 19394 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -16); 19395 19396 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1); 19397 if (!new_prog) 19398 return -ENOMEM; 19399 19400 env->prog = prog = new_prog; 19401 insn = new_prog->insnsi + i + delta; 19402 continue; 19403 } 19404 19405 patch_call_imm: 19406 fn = env->ops->get_func_proto(insn->imm, env->prog); 19407 /* all functions that have prototype and verifier allowed 19408 * programs to call them, must be real in-kernel functions 19409 */ 19410 if (!fn->func) { 19411 verbose(env, 19412 "kernel subsystem misconfigured func %s#%d\n", 19413 func_id_name(insn->imm), insn->imm); 19414 return -EFAULT; 19415 } 19416 insn->imm = fn->func - __bpf_call_base; 19417 } 19418 19419 /* Since poke tab is now finalized, publish aux to tracker. */ 19420 for (i = 0; i < prog->aux->size_poke_tab; i++) { 19421 map_ptr = prog->aux->poke_tab[i].tail_call.map; 19422 if (!map_ptr->ops->map_poke_track || 19423 !map_ptr->ops->map_poke_untrack || 19424 !map_ptr->ops->map_poke_run) { 19425 verbose(env, "bpf verifier is misconfigured\n"); 19426 return -EINVAL; 19427 } 19428 19429 ret = map_ptr->ops->map_poke_track(map_ptr, prog->aux); 19430 if (ret < 0) { 19431 verbose(env, "tracking tail call prog failed\n"); 19432 return ret; 19433 } 19434 } 19435 19436 sort_kfunc_descs_by_imm_off(env->prog); 19437 19438 return 0; 19439 } 19440 19441 static struct bpf_prog *inline_bpf_loop(struct bpf_verifier_env *env, 19442 int position, 19443 s32 stack_base, 19444 u32 callback_subprogno, 19445 u32 *cnt) 19446 { 19447 s32 r6_offset = stack_base + 0 * BPF_REG_SIZE; 19448 s32 r7_offset = stack_base + 1 * BPF_REG_SIZE; 19449 s32 r8_offset = stack_base + 2 * BPF_REG_SIZE; 19450 int reg_loop_max = BPF_REG_6; 19451 int reg_loop_cnt = BPF_REG_7; 19452 int reg_loop_ctx = BPF_REG_8; 19453 19454 struct bpf_prog *new_prog; 19455 u32 callback_start; 19456 u32 call_insn_offset; 19457 s32 callback_offset; 19458 19459 /* This represents an inlined version of bpf_iter.c:bpf_loop, 19460 * be careful to modify this code in sync. 19461 */ 19462 struct bpf_insn insn_buf[] = { 19463 /* Return error and jump to the end of the patch if 19464 * expected number of iterations is too big. 19465 */ 19466 BPF_JMP_IMM(BPF_JLE, BPF_REG_1, BPF_MAX_LOOPS, 2), 19467 BPF_MOV32_IMM(BPF_REG_0, -E2BIG), 19468 BPF_JMP_IMM(BPF_JA, 0, 0, 16), 19469 /* spill R6, R7, R8 to use these as loop vars */ 19470 BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_6, r6_offset), 19471 BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_7, r7_offset), 19472 BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_8, r8_offset), 19473 /* initialize loop vars */ 19474 BPF_MOV64_REG(reg_loop_max, BPF_REG_1), 19475 BPF_MOV32_IMM(reg_loop_cnt, 0), 19476 BPF_MOV64_REG(reg_loop_ctx, BPF_REG_3), 19477 /* loop header, 19478 * if reg_loop_cnt >= reg_loop_max skip the loop body 19479 */ 19480 BPF_JMP_REG(BPF_JGE, reg_loop_cnt, reg_loop_max, 5), 19481 /* callback call, 19482 * correct callback offset would be set after patching 19483 */ 19484 BPF_MOV64_REG(BPF_REG_1, reg_loop_cnt), 19485 BPF_MOV64_REG(BPF_REG_2, reg_loop_ctx), 19486 BPF_CALL_REL(0), 19487 /* increment loop counter */ 19488 BPF_ALU64_IMM(BPF_ADD, reg_loop_cnt, 1), 19489 /* jump to loop header if callback returned 0 */ 19490 BPF_JMP_IMM(BPF_JEQ, BPF_REG_0, 0, -6), 19491 /* return value of bpf_loop, 19492 * set R0 to the number of iterations 19493 */ 19494 BPF_MOV64_REG(BPF_REG_0, reg_loop_cnt), 19495 /* restore original values of R6, R7, R8 */ 19496 BPF_LDX_MEM(BPF_DW, BPF_REG_6, BPF_REG_10, r6_offset), 19497 BPF_LDX_MEM(BPF_DW, BPF_REG_7, BPF_REG_10, r7_offset), 19498 BPF_LDX_MEM(BPF_DW, BPF_REG_8, BPF_REG_10, r8_offset), 19499 }; 19500 19501 *cnt = ARRAY_SIZE(insn_buf); 19502 new_prog = bpf_patch_insn_data(env, position, insn_buf, *cnt); 19503 if (!new_prog) 19504 return new_prog; 19505 19506 /* callback start is known only after patching */ 19507 callback_start = env->subprog_info[callback_subprogno].start; 19508 /* Note: insn_buf[12] is an offset of BPF_CALL_REL instruction */ 19509 call_insn_offset = position + 12; 19510 callback_offset = callback_start - call_insn_offset - 1; 19511 new_prog->insnsi[call_insn_offset].imm = callback_offset; 19512 19513 return new_prog; 19514 } 19515 19516 static bool is_bpf_loop_call(struct bpf_insn *insn) 19517 { 19518 return insn->code == (BPF_JMP | BPF_CALL) && 19519 insn->src_reg == 0 && 19520 insn->imm == BPF_FUNC_loop; 19521 } 19522 19523 /* For all sub-programs in the program (including main) check 19524 * insn_aux_data to see if there are bpf_loop calls that require 19525 * inlining. If such calls are found the calls are replaced with a 19526 * sequence of instructions produced by `inline_bpf_loop` function and 19527 * subprog stack_depth is increased by the size of 3 registers. 19528 * This stack space is used to spill values of the R6, R7, R8. These 19529 * registers are used to store the loop bound, counter and context 19530 * variables. 19531 */ 19532 static int optimize_bpf_loop(struct bpf_verifier_env *env) 19533 { 19534 struct bpf_subprog_info *subprogs = env->subprog_info; 19535 int i, cur_subprog = 0, cnt, delta = 0; 19536 struct bpf_insn *insn = env->prog->insnsi; 19537 int insn_cnt = env->prog->len; 19538 u16 stack_depth = subprogs[cur_subprog].stack_depth; 19539 u16 stack_depth_roundup = round_up(stack_depth, 8) - stack_depth; 19540 u16 stack_depth_extra = 0; 19541 19542 for (i = 0; i < insn_cnt; i++, insn++) { 19543 struct bpf_loop_inline_state *inline_state = 19544 &env->insn_aux_data[i + delta].loop_inline_state; 19545 19546 if (is_bpf_loop_call(insn) && inline_state->fit_for_inline) { 19547 struct bpf_prog *new_prog; 19548 19549 stack_depth_extra = BPF_REG_SIZE * 3 + stack_depth_roundup; 19550 new_prog = inline_bpf_loop(env, 19551 i + delta, 19552 -(stack_depth + stack_depth_extra), 19553 inline_state->callback_subprogno, 19554 &cnt); 19555 if (!new_prog) 19556 return -ENOMEM; 19557 19558 delta += cnt - 1; 19559 env->prog = new_prog; 19560 insn = new_prog->insnsi + i + delta; 19561 } 19562 19563 if (subprogs[cur_subprog + 1].start == i + delta + 1) { 19564 subprogs[cur_subprog].stack_depth += stack_depth_extra; 19565 cur_subprog++; 19566 stack_depth = subprogs[cur_subprog].stack_depth; 19567 stack_depth_roundup = round_up(stack_depth, 8) - stack_depth; 19568 stack_depth_extra = 0; 19569 } 19570 } 19571 19572 env->prog->aux->stack_depth = env->subprog_info[0].stack_depth; 19573 19574 return 0; 19575 } 19576 19577 static void free_states(struct bpf_verifier_env *env) 19578 { 19579 struct bpf_verifier_state_list *sl, *sln; 19580 int i; 19581 19582 sl = env->free_list; 19583 while (sl) { 19584 sln = sl->next; 19585 free_verifier_state(&sl->state, false); 19586 kfree(sl); 19587 sl = sln; 19588 } 19589 env->free_list = NULL; 19590 19591 if (!env->explored_states) 19592 return; 19593 19594 for (i = 0; i < state_htab_size(env); i++) { 19595 sl = env->explored_states[i]; 19596 19597 while (sl) { 19598 sln = sl->next; 19599 free_verifier_state(&sl->state, false); 19600 kfree(sl); 19601 sl = sln; 19602 } 19603 env->explored_states[i] = NULL; 19604 } 19605 } 19606 19607 static int do_check_common(struct bpf_verifier_env *env, int subprog) 19608 { 19609 bool pop_log = !(env->log.level & BPF_LOG_LEVEL2); 19610 struct bpf_verifier_state *state; 19611 struct bpf_reg_state *regs; 19612 int ret, i; 19613 19614 env->prev_linfo = NULL; 19615 env->pass_cnt++; 19616 19617 state = kzalloc(sizeof(struct bpf_verifier_state), GFP_KERNEL); 19618 if (!state) 19619 return -ENOMEM; 19620 state->curframe = 0; 19621 state->speculative = false; 19622 state->branches = 1; 19623 state->frame[0] = kzalloc(sizeof(struct bpf_func_state), GFP_KERNEL); 19624 if (!state->frame[0]) { 19625 kfree(state); 19626 return -ENOMEM; 19627 } 19628 env->cur_state = state; 19629 init_func_state(env, state->frame[0], 19630 BPF_MAIN_FUNC /* callsite */, 19631 0 /* frameno */, 19632 subprog); 19633 state->first_insn_idx = env->subprog_info[subprog].start; 19634 state->last_insn_idx = -1; 19635 19636 regs = state->frame[state->curframe]->regs; 19637 if (subprog || env->prog->type == BPF_PROG_TYPE_EXT) { 19638 ret = btf_prepare_func_args(env, subprog, regs); 19639 if (ret) 19640 goto out; 19641 for (i = BPF_REG_1; i <= BPF_REG_5; i++) { 19642 if (regs[i].type == PTR_TO_CTX) 19643 mark_reg_known_zero(env, regs, i); 19644 else if (regs[i].type == SCALAR_VALUE) 19645 mark_reg_unknown(env, regs, i); 19646 else if (base_type(regs[i].type) == PTR_TO_MEM) { 19647 const u32 mem_size = regs[i].mem_size; 19648 19649 mark_reg_known_zero(env, regs, i); 19650 regs[i].mem_size = mem_size; 19651 regs[i].id = ++env->id_gen; 19652 } 19653 } 19654 } else { 19655 /* 1st arg to a function */ 19656 regs[BPF_REG_1].type = PTR_TO_CTX; 19657 mark_reg_known_zero(env, regs, BPF_REG_1); 19658 ret = btf_check_subprog_arg_match(env, subprog, regs); 19659 if (ret == -EFAULT) 19660 /* unlikely verifier bug. abort. 19661 * ret == 0 and ret < 0 are sadly acceptable for 19662 * main() function due to backward compatibility. 19663 * Like socket filter program may be written as: 19664 * int bpf_prog(struct pt_regs *ctx) 19665 * and never dereference that ctx in the program. 19666 * 'struct pt_regs' is a type mismatch for socket 19667 * filter that should be using 'struct __sk_buff'. 19668 */ 19669 goto out; 19670 } 19671 19672 ret = do_check(env); 19673 out: 19674 /* check for NULL is necessary, since cur_state can be freed inside 19675 * do_check() under memory pressure. 19676 */ 19677 if (env->cur_state) { 19678 free_verifier_state(env->cur_state, true); 19679 env->cur_state = NULL; 19680 } 19681 while (!pop_stack(env, NULL, NULL, false)); 19682 if (!ret && pop_log) 19683 bpf_vlog_reset(&env->log, 0); 19684 free_states(env); 19685 return ret; 19686 } 19687 19688 /* Verify all global functions in a BPF program one by one based on their BTF. 19689 * All global functions must pass verification. Otherwise the whole program is rejected. 19690 * Consider: 19691 * int bar(int); 19692 * int foo(int f) 19693 * { 19694 * return bar(f); 19695 * } 19696 * int bar(int b) 19697 * { 19698 * ... 19699 * } 19700 * foo() will be verified first for R1=any_scalar_value. During verification it 19701 * will be assumed that bar() already verified successfully and call to bar() 19702 * from foo() will be checked for type match only. Later bar() will be verified 19703 * independently to check that it's safe for R1=any_scalar_value. 19704 */ 19705 static int do_check_subprogs(struct bpf_verifier_env *env) 19706 { 19707 struct bpf_prog_aux *aux = env->prog->aux; 19708 int i, ret; 19709 19710 if (!aux->func_info) 19711 return 0; 19712 19713 for (i = 1; i < env->subprog_cnt; i++) { 19714 if (aux->func_info_aux[i].linkage != BTF_FUNC_GLOBAL) 19715 continue; 19716 env->insn_idx = env->subprog_info[i].start; 19717 WARN_ON_ONCE(env->insn_idx == 0); 19718 ret = do_check_common(env, i); 19719 if (ret) { 19720 return ret; 19721 } else if (env->log.level & BPF_LOG_LEVEL) { 19722 verbose(env, 19723 "Func#%d is safe for any args that match its prototype\n", 19724 i); 19725 } 19726 } 19727 return 0; 19728 } 19729 19730 static int do_check_main(struct bpf_verifier_env *env) 19731 { 19732 int ret; 19733 19734 env->insn_idx = 0; 19735 ret = do_check_common(env, 0); 19736 if (!ret) 19737 env->prog->aux->stack_depth = env->subprog_info[0].stack_depth; 19738 return ret; 19739 } 19740 19741 19742 static void print_verification_stats(struct bpf_verifier_env *env) 19743 { 19744 int i; 19745 19746 if (env->log.level & BPF_LOG_STATS) { 19747 verbose(env, "verification time %lld usec\n", 19748 div_u64(env->verification_time, 1000)); 19749 verbose(env, "stack depth "); 19750 for (i = 0; i < env->subprog_cnt; i++) { 19751 u32 depth = env->subprog_info[i].stack_depth; 19752 19753 verbose(env, "%d", depth); 19754 if (i + 1 < env->subprog_cnt) 19755 verbose(env, "+"); 19756 } 19757 verbose(env, "\n"); 19758 } 19759 verbose(env, "processed %d insns (limit %d) max_states_per_insn %d " 19760 "total_states %d peak_states %d mark_read %d\n", 19761 env->insn_processed, BPF_COMPLEXITY_LIMIT_INSNS, 19762 env->max_states_per_insn, env->total_states, 19763 env->peak_states, env->longest_mark_read_walk); 19764 } 19765 19766 static int check_struct_ops_btf_id(struct bpf_verifier_env *env) 19767 { 19768 const struct btf_type *t, *func_proto; 19769 const struct bpf_struct_ops *st_ops; 19770 const struct btf_member *member; 19771 struct bpf_prog *prog = env->prog; 19772 u32 btf_id, member_idx; 19773 const char *mname; 19774 19775 if (!prog->gpl_compatible) { 19776 verbose(env, "struct ops programs must have a GPL compatible license\n"); 19777 return -EINVAL; 19778 } 19779 19780 btf_id = prog->aux->attach_btf_id; 19781 st_ops = bpf_struct_ops_find(btf_id); 19782 if (!st_ops) { 19783 verbose(env, "attach_btf_id %u is not a supported struct\n", 19784 btf_id); 19785 return -ENOTSUPP; 19786 } 19787 19788 t = st_ops->type; 19789 member_idx = prog->expected_attach_type; 19790 if (member_idx >= btf_type_vlen(t)) { 19791 verbose(env, "attach to invalid member idx %u of struct %s\n", 19792 member_idx, st_ops->name); 19793 return -EINVAL; 19794 } 19795 19796 member = &btf_type_member(t)[member_idx]; 19797 mname = btf_name_by_offset(btf_vmlinux, member->name_off); 19798 func_proto = btf_type_resolve_func_ptr(btf_vmlinux, member->type, 19799 NULL); 19800 if (!func_proto) { 19801 verbose(env, "attach to invalid member %s(@idx %u) of struct %s\n", 19802 mname, member_idx, st_ops->name); 19803 return -EINVAL; 19804 } 19805 19806 if (st_ops->check_member) { 19807 int err = st_ops->check_member(t, member, prog); 19808 19809 if (err) { 19810 verbose(env, "attach to unsupported member %s of struct %s\n", 19811 mname, st_ops->name); 19812 return err; 19813 } 19814 } 19815 19816 prog->aux->attach_func_proto = func_proto; 19817 prog->aux->attach_func_name = mname; 19818 env->ops = st_ops->verifier_ops; 19819 19820 return 0; 19821 } 19822 #define SECURITY_PREFIX "security_" 19823 19824 static int check_attach_modify_return(unsigned long addr, const char *func_name) 19825 { 19826 if (within_error_injection_list(addr) || 19827 !strncmp(SECURITY_PREFIX, func_name, sizeof(SECURITY_PREFIX) - 1)) 19828 return 0; 19829 19830 return -EINVAL; 19831 } 19832 19833 /* list of non-sleepable functions that are otherwise on 19834 * ALLOW_ERROR_INJECTION list 19835 */ 19836 BTF_SET_START(btf_non_sleepable_error_inject) 19837 /* Three functions below can be called from sleepable and non-sleepable context. 19838 * Assume non-sleepable from bpf safety point of view. 19839 */ 19840 BTF_ID(func, __filemap_add_folio) 19841 BTF_ID(func, should_fail_alloc_page) 19842 BTF_ID(func, should_failslab) 19843 BTF_SET_END(btf_non_sleepable_error_inject) 19844 19845 static int check_non_sleepable_error_inject(u32 btf_id) 19846 { 19847 return btf_id_set_contains(&btf_non_sleepable_error_inject, btf_id); 19848 } 19849 19850 int bpf_check_attach_target(struct bpf_verifier_log *log, 19851 const struct bpf_prog *prog, 19852 const struct bpf_prog *tgt_prog, 19853 u32 btf_id, 19854 struct bpf_attach_target_info *tgt_info) 19855 { 19856 bool prog_extension = prog->type == BPF_PROG_TYPE_EXT; 19857 const char prefix[] = "btf_trace_"; 19858 int ret = 0, subprog = -1, i; 19859 const struct btf_type *t; 19860 bool conservative = true; 19861 const char *tname; 19862 struct btf *btf; 19863 long addr = 0; 19864 struct module *mod = NULL; 19865 19866 if (!btf_id) { 19867 bpf_log(log, "Tracing programs must provide btf_id\n"); 19868 return -EINVAL; 19869 } 19870 btf = tgt_prog ? tgt_prog->aux->btf : prog->aux->attach_btf; 19871 if (!btf) { 19872 bpf_log(log, 19873 "FENTRY/FEXIT program can only be attached to another program annotated with BTF\n"); 19874 return -EINVAL; 19875 } 19876 t = btf_type_by_id(btf, btf_id); 19877 if (!t) { 19878 bpf_log(log, "attach_btf_id %u is invalid\n", btf_id); 19879 return -EINVAL; 19880 } 19881 tname = btf_name_by_offset(btf, t->name_off); 19882 if (!tname) { 19883 bpf_log(log, "attach_btf_id %u doesn't have a name\n", btf_id); 19884 return -EINVAL; 19885 } 19886 if (tgt_prog) { 19887 struct bpf_prog_aux *aux = tgt_prog->aux; 19888 19889 if (bpf_prog_is_dev_bound(prog->aux) && 19890 !bpf_prog_dev_bound_match(prog, tgt_prog)) { 19891 bpf_log(log, "Target program bound device mismatch"); 19892 return -EINVAL; 19893 } 19894 19895 for (i = 0; i < aux->func_info_cnt; i++) 19896 if (aux->func_info[i].type_id == btf_id) { 19897 subprog = i; 19898 break; 19899 } 19900 if (subprog == -1) { 19901 bpf_log(log, "Subprog %s doesn't exist\n", tname); 19902 return -EINVAL; 19903 } 19904 conservative = aux->func_info_aux[subprog].unreliable; 19905 if (prog_extension) { 19906 if (conservative) { 19907 bpf_log(log, 19908 "Cannot replace static functions\n"); 19909 return -EINVAL; 19910 } 19911 if (!prog->jit_requested) { 19912 bpf_log(log, 19913 "Extension programs should be JITed\n"); 19914 return -EINVAL; 19915 } 19916 } 19917 if (!tgt_prog->jited) { 19918 bpf_log(log, "Can attach to only JITed progs\n"); 19919 return -EINVAL; 19920 } 19921 if (tgt_prog->type == prog->type) { 19922 /* Cannot fentry/fexit another fentry/fexit program. 19923 * Cannot attach program extension to another extension. 19924 * It's ok to attach fentry/fexit to extension program. 19925 */ 19926 bpf_log(log, "Cannot recursively attach\n"); 19927 return -EINVAL; 19928 } 19929 if (tgt_prog->type == BPF_PROG_TYPE_TRACING && 19930 prog_extension && 19931 (tgt_prog->expected_attach_type == BPF_TRACE_FENTRY || 19932 tgt_prog->expected_attach_type == BPF_TRACE_FEXIT)) { 19933 /* Program extensions can extend all program types 19934 * except fentry/fexit. The reason is the following. 19935 * The fentry/fexit programs are used for performance 19936 * analysis, stats and can be attached to any program 19937 * type except themselves. When extension program is 19938 * replacing XDP function it is necessary to allow 19939 * performance analysis of all functions. Both original 19940 * XDP program and its program extension. Hence 19941 * attaching fentry/fexit to BPF_PROG_TYPE_EXT is 19942 * allowed. If extending of fentry/fexit was allowed it 19943 * would be possible to create long call chain 19944 * fentry->extension->fentry->extension beyond 19945 * reasonable stack size. Hence extending fentry is not 19946 * allowed. 19947 */ 19948 bpf_log(log, "Cannot extend fentry/fexit\n"); 19949 return -EINVAL; 19950 } 19951 } else { 19952 if (prog_extension) { 19953 bpf_log(log, "Cannot replace kernel functions\n"); 19954 return -EINVAL; 19955 } 19956 } 19957 19958 switch (prog->expected_attach_type) { 19959 case BPF_TRACE_RAW_TP: 19960 if (tgt_prog) { 19961 bpf_log(log, 19962 "Only FENTRY/FEXIT progs are attachable to another BPF prog\n"); 19963 return -EINVAL; 19964 } 19965 if (!btf_type_is_typedef(t)) { 19966 bpf_log(log, "attach_btf_id %u is not a typedef\n", 19967 btf_id); 19968 return -EINVAL; 19969 } 19970 if (strncmp(prefix, tname, sizeof(prefix) - 1)) { 19971 bpf_log(log, "attach_btf_id %u points to wrong type name %s\n", 19972 btf_id, tname); 19973 return -EINVAL; 19974 } 19975 tname += sizeof(prefix) - 1; 19976 t = btf_type_by_id(btf, t->type); 19977 if (!btf_type_is_ptr(t)) 19978 /* should never happen in valid vmlinux build */ 19979 return -EINVAL; 19980 t = btf_type_by_id(btf, t->type); 19981 if (!btf_type_is_func_proto(t)) 19982 /* should never happen in valid vmlinux build */ 19983 return -EINVAL; 19984 19985 break; 19986 case BPF_TRACE_ITER: 19987 if (!btf_type_is_func(t)) { 19988 bpf_log(log, "attach_btf_id %u is not a function\n", 19989 btf_id); 19990 return -EINVAL; 19991 } 19992 t = btf_type_by_id(btf, t->type); 19993 if (!btf_type_is_func_proto(t)) 19994 return -EINVAL; 19995 ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel); 19996 if (ret) 19997 return ret; 19998 break; 19999 default: 20000 if (!prog_extension) 20001 return -EINVAL; 20002 fallthrough; 20003 case BPF_MODIFY_RETURN: 20004 case BPF_LSM_MAC: 20005 case BPF_LSM_CGROUP: 20006 case BPF_TRACE_FENTRY: 20007 case BPF_TRACE_FEXIT: 20008 if (!btf_type_is_func(t)) { 20009 bpf_log(log, "attach_btf_id %u is not a function\n", 20010 btf_id); 20011 return -EINVAL; 20012 } 20013 if (prog_extension && 20014 btf_check_type_match(log, prog, btf, t)) 20015 return -EINVAL; 20016 t = btf_type_by_id(btf, t->type); 20017 if (!btf_type_is_func_proto(t)) 20018 return -EINVAL; 20019 20020 if ((prog->aux->saved_dst_prog_type || prog->aux->saved_dst_attach_type) && 20021 (!tgt_prog || prog->aux->saved_dst_prog_type != tgt_prog->type || 20022 prog->aux->saved_dst_attach_type != tgt_prog->expected_attach_type)) 20023 return -EINVAL; 20024 20025 if (tgt_prog && conservative) 20026 t = NULL; 20027 20028 ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel); 20029 if (ret < 0) 20030 return ret; 20031 20032 if (tgt_prog) { 20033 if (subprog == 0) 20034 addr = (long) tgt_prog->bpf_func; 20035 else 20036 addr = (long) tgt_prog->aux->func[subprog]->bpf_func; 20037 } else { 20038 if (btf_is_module(btf)) { 20039 mod = btf_try_get_module(btf); 20040 if (mod) 20041 addr = find_kallsyms_symbol_value(mod, tname); 20042 else 20043 addr = 0; 20044 } else { 20045 addr = kallsyms_lookup_name(tname); 20046 } 20047 if (!addr) { 20048 module_put(mod); 20049 bpf_log(log, 20050 "The address of function %s cannot be found\n", 20051 tname); 20052 return -ENOENT; 20053 } 20054 } 20055 20056 if (prog->aux->sleepable) { 20057 ret = -EINVAL; 20058 switch (prog->type) { 20059 case BPF_PROG_TYPE_TRACING: 20060 20061 /* fentry/fexit/fmod_ret progs can be sleepable if they are 20062 * attached to ALLOW_ERROR_INJECTION and are not in denylist. 20063 */ 20064 if (!check_non_sleepable_error_inject(btf_id) && 20065 within_error_injection_list(addr)) 20066 ret = 0; 20067 /* fentry/fexit/fmod_ret progs can also be sleepable if they are 20068 * in the fmodret id set with the KF_SLEEPABLE flag. 20069 */ 20070 else { 20071 u32 *flags = btf_kfunc_is_modify_return(btf, btf_id, 20072 prog); 20073 20074 if (flags && (*flags & KF_SLEEPABLE)) 20075 ret = 0; 20076 } 20077 break; 20078 case BPF_PROG_TYPE_LSM: 20079 /* LSM progs check that they are attached to bpf_lsm_*() funcs. 20080 * Only some of them are sleepable. 20081 */ 20082 if (bpf_lsm_is_sleepable_hook(btf_id)) 20083 ret = 0; 20084 break; 20085 default: 20086 break; 20087 } 20088 if (ret) { 20089 module_put(mod); 20090 bpf_log(log, "%s is not sleepable\n", tname); 20091 return ret; 20092 } 20093 } else if (prog->expected_attach_type == BPF_MODIFY_RETURN) { 20094 if (tgt_prog) { 20095 module_put(mod); 20096 bpf_log(log, "can't modify return codes of BPF programs\n"); 20097 return -EINVAL; 20098 } 20099 ret = -EINVAL; 20100 if (btf_kfunc_is_modify_return(btf, btf_id, prog) || 20101 !check_attach_modify_return(addr, tname)) 20102 ret = 0; 20103 if (ret) { 20104 module_put(mod); 20105 bpf_log(log, "%s() is not modifiable\n", tname); 20106 return ret; 20107 } 20108 } 20109 20110 break; 20111 } 20112 tgt_info->tgt_addr = addr; 20113 tgt_info->tgt_name = tname; 20114 tgt_info->tgt_type = t; 20115 tgt_info->tgt_mod = mod; 20116 return 0; 20117 } 20118 20119 BTF_SET_START(btf_id_deny) 20120 BTF_ID_UNUSED 20121 #ifdef CONFIG_SMP 20122 BTF_ID(func, migrate_disable) 20123 BTF_ID(func, migrate_enable) 20124 #endif 20125 #if !defined CONFIG_PREEMPT_RCU && !defined CONFIG_TINY_RCU 20126 BTF_ID(func, rcu_read_unlock_strict) 20127 #endif 20128 #if defined(CONFIG_DEBUG_PREEMPT) || defined(CONFIG_TRACE_PREEMPT_TOGGLE) 20129 BTF_ID(func, preempt_count_add) 20130 BTF_ID(func, preempt_count_sub) 20131 #endif 20132 #ifdef CONFIG_PREEMPT_RCU 20133 BTF_ID(func, __rcu_read_lock) 20134 BTF_ID(func, __rcu_read_unlock) 20135 #endif 20136 BTF_SET_END(btf_id_deny) 20137 20138 static bool can_be_sleepable(struct bpf_prog *prog) 20139 { 20140 if (prog->type == BPF_PROG_TYPE_TRACING) { 20141 switch (prog->expected_attach_type) { 20142 case BPF_TRACE_FENTRY: 20143 case BPF_TRACE_FEXIT: 20144 case BPF_MODIFY_RETURN: 20145 case BPF_TRACE_ITER: 20146 return true; 20147 default: 20148 return false; 20149 } 20150 } 20151 return prog->type == BPF_PROG_TYPE_LSM || 20152 prog->type == BPF_PROG_TYPE_KPROBE /* only for uprobes */ || 20153 prog->type == BPF_PROG_TYPE_STRUCT_OPS; 20154 } 20155 20156 static int check_attach_btf_id(struct bpf_verifier_env *env) 20157 { 20158 struct bpf_prog *prog = env->prog; 20159 struct bpf_prog *tgt_prog = prog->aux->dst_prog; 20160 struct bpf_attach_target_info tgt_info = {}; 20161 u32 btf_id = prog->aux->attach_btf_id; 20162 struct bpf_trampoline *tr; 20163 int ret; 20164 u64 key; 20165 20166 if (prog->type == BPF_PROG_TYPE_SYSCALL) { 20167 if (prog->aux->sleepable) 20168 /* attach_btf_id checked to be zero already */ 20169 return 0; 20170 verbose(env, "Syscall programs can only be sleepable\n"); 20171 return -EINVAL; 20172 } 20173 20174 if (prog->aux->sleepable && !can_be_sleepable(prog)) { 20175 verbose(env, "Only fentry/fexit/fmod_ret, lsm, iter, uprobe, and struct_ops programs can be sleepable\n"); 20176 return -EINVAL; 20177 } 20178 20179 if (prog->type == BPF_PROG_TYPE_STRUCT_OPS) 20180 return check_struct_ops_btf_id(env); 20181 20182 if (prog->type != BPF_PROG_TYPE_TRACING && 20183 prog->type != BPF_PROG_TYPE_LSM && 20184 prog->type != BPF_PROG_TYPE_EXT) 20185 return 0; 20186 20187 ret = bpf_check_attach_target(&env->log, prog, tgt_prog, btf_id, &tgt_info); 20188 if (ret) 20189 return ret; 20190 20191 if (tgt_prog && prog->type == BPF_PROG_TYPE_EXT) { 20192 /* to make freplace equivalent to their targets, they need to 20193 * inherit env->ops and expected_attach_type for the rest of the 20194 * verification 20195 */ 20196 env->ops = bpf_verifier_ops[tgt_prog->type]; 20197 prog->expected_attach_type = tgt_prog->expected_attach_type; 20198 } 20199 20200 /* store info about the attachment target that will be used later */ 20201 prog->aux->attach_func_proto = tgt_info.tgt_type; 20202 prog->aux->attach_func_name = tgt_info.tgt_name; 20203 prog->aux->mod = tgt_info.tgt_mod; 20204 20205 if (tgt_prog) { 20206 prog->aux->saved_dst_prog_type = tgt_prog->type; 20207 prog->aux->saved_dst_attach_type = tgt_prog->expected_attach_type; 20208 } 20209 20210 if (prog->expected_attach_type == BPF_TRACE_RAW_TP) { 20211 prog->aux->attach_btf_trace = true; 20212 return 0; 20213 } else if (prog->expected_attach_type == BPF_TRACE_ITER) { 20214 if (!bpf_iter_prog_supported(prog)) 20215 return -EINVAL; 20216 return 0; 20217 } 20218 20219 if (prog->type == BPF_PROG_TYPE_LSM) { 20220 ret = bpf_lsm_verify_prog(&env->log, prog); 20221 if (ret < 0) 20222 return ret; 20223 } else if (prog->type == BPF_PROG_TYPE_TRACING && 20224 btf_id_set_contains(&btf_id_deny, btf_id)) { 20225 return -EINVAL; 20226 } 20227 20228 key = bpf_trampoline_compute_key(tgt_prog, prog->aux->attach_btf, btf_id); 20229 tr = bpf_trampoline_get(key, &tgt_info); 20230 if (!tr) 20231 return -ENOMEM; 20232 20233 if (tgt_prog && tgt_prog->aux->tail_call_reachable) 20234 tr->flags = BPF_TRAMP_F_TAIL_CALL_CTX; 20235 20236 prog->aux->dst_trampoline = tr; 20237 return 0; 20238 } 20239 20240 struct btf *bpf_get_btf_vmlinux(void) 20241 { 20242 if (!btf_vmlinux && IS_ENABLED(CONFIG_DEBUG_INFO_BTF)) { 20243 mutex_lock(&bpf_verifier_lock); 20244 if (!btf_vmlinux) 20245 btf_vmlinux = btf_parse_vmlinux(); 20246 mutex_unlock(&bpf_verifier_lock); 20247 } 20248 return btf_vmlinux; 20249 } 20250 20251 int bpf_check(struct bpf_prog **prog, union bpf_attr *attr, bpfptr_t uattr, __u32 uattr_size) 20252 { 20253 u64 start_time = ktime_get_ns(); 20254 struct bpf_verifier_env *env; 20255 int i, len, ret = -EINVAL, err; 20256 u32 log_true_size; 20257 bool is_priv; 20258 20259 /* no program is valid */ 20260 if (ARRAY_SIZE(bpf_verifier_ops) == 0) 20261 return -EINVAL; 20262 20263 /* 'struct bpf_verifier_env' can be global, but since it's not small, 20264 * allocate/free it every time bpf_check() is called 20265 */ 20266 env = kvzalloc(sizeof(struct bpf_verifier_env), GFP_KERNEL); 20267 if (!env) 20268 return -ENOMEM; 20269 20270 env->bt.env = env; 20271 20272 len = (*prog)->len; 20273 env->insn_aux_data = 20274 vzalloc(array_size(sizeof(struct bpf_insn_aux_data), len)); 20275 ret = -ENOMEM; 20276 if (!env->insn_aux_data) 20277 goto err_free_env; 20278 for (i = 0; i < len; i++) 20279 env->insn_aux_data[i].orig_idx = i; 20280 env->prog = *prog; 20281 env->ops = bpf_verifier_ops[env->prog->type]; 20282 env->fd_array = make_bpfptr(attr->fd_array, uattr.is_kernel); 20283 is_priv = bpf_capable(); 20284 20285 bpf_get_btf_vmlinux(); 20286 20287 /* grab the mutex to protect few globals used by verifier */ 20288 if (!is_priv) 20289 mutex_lock(&bpf_verifier_lock); 20290 20291 /* user could have requested verbose verifier output 20292 * and supplied buffer to store the verification trace 20293 */ 20294 ret = bpf_vlog_init(&env->log, attr->log_level, 20295 (char __user *) (unsigned long) attr->log_buf, 20296 attr->log_size); 20297 if (ret) 20298 goto err_unlock; 20299 20300 mark_verifier_state_clean(env); 20301 20302 if (IS_ERR(btf_vmlinux)) { 20303 /* Either gcc or pahole or kernel are broken. */ 20304 verbose(env, "in-kernel BTF is malformed\n"); 20305 ret = PTR_ERR(btf_vmlinux); 20306 goto skip_full_check; 20307 } 20308 20309 env->strict_alignment = !!(attr->prog_flags & BPF_F_STRICT_ALIGNMENT); 20310 if (!IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS)) 20311 env->strict_alignment = true; 20312 if (attr->prog_flags & BPF_F_ANY_ALIGNMENT) 20313 env->strict_alignment = false; 20314 20315 env->allow_ptr_leaks = bpf_allow_ptr_leaks(); 20316 env->allow_uninit_stack = bpf_allow_uninit_stack(); 20317 env->bypass_spec_v1 = bpf_bypass_spec_v1(); 20318 env->bypass_spec_v4 = bpf_bypass_spec_v4(); 20319 env->bpf_capable = bpf_capable(); 20320 20321 if (is_priv) 20322 env->test_state_freq = attr->prog_flags & BPF_F_TEST_STATE_FREQ; 20323 20324 env->explored_states = kvcalloc(state_htab_size(env), 20325 sizeof(struct bpf_verifier_state_list *), 20326 GFP_USER); 20327 ret = -ENOMEM; 20328 if (!env->explored_states) 20329 goto skip_full_check; 20330 20331 ret = add_subprog_and_kfunc(env); 20332 if (ret < 0) 20333 goto skip_full_check; 20334 20335 ret = check_subprogs(env); 20336 if (ret < 0) 20337 goto skip_full_check; 20338 20339 ret = check_btf_info(env, attr, uattr); 20340 if (ret < 0) 20341 goto skip_full_check; 20342 20343 ret = check_attach_btf_id(env); 20344 if (ret) 20345 goto skip_full_check; 20346 20347 ret = resolve_pseudo_ldimm64(env); 20348 if (ret < 0) 20349 goto skip_full_check; 20350 20351 if (bpf_prog_is_offloaded(env->prog->aux)) { 20352 ret = bpf_prog_offload_verifier_prep(env->prog); 20353 if (ret) 20354 goto skip_full_check; 20355 } 20356 20357 ret = check_cfg(env); 20358 if (ret < 0) 20359 goto skip_full_check; 20360 20361 ret = do_check_subprogs(env); 20362 ret = ret ?: do_check_main(env); 20363 20364 if (ret == 0 && bpf_prog_is_offloaded(env->prog->aux)) 20365 ret = bpf_prog_offload_finalize(env); 20366 20367 skip_full_check: 20368 kvfree(env->explored_states); 20369 20370 if (ret == 0) 20371 ret = check_max_stack_depth(env); 20372 20373 /* instruction rewrites happen after this point */ 20374 if (ret == 0) 20375 ret = optimize_bpf_loop(env); 20376 20377 if (is_priv) { 20378 if (ret == 0) 20379 opt_hard_wire_dead_code_branches(env); 20380 if (ret == 0) 20381 ret = opt_remove_dead_code(env); 20382 if (ret == 0) 20383 ret = opt_remove_nops(env); 20384 } else { 20385 if (ret == 0) 20386 sanitize_dead_code(env); 20387 } 20388 20389 if (ret == 0) 20390 /* program is valid, convert *(u32*)(ctx + off) accesses */ 20391 ret = convert_ctx_accesses(env); 20392 20393 if (ret == 0) 20394 ret = do_misc_fixups(env); 20395 20396 /* do 32-bit optimization after insn patching has done so those patched 20397 * insns could be handled correctly. 20398 */ 20399 if (ret == 0 && !bpf_prog_is_offloaded(env->prog->aux)) { 20400 ret = opt_subreg_zext_lo32_rnd_hi32(env, attr); 20401 env->prog->aux->verifier_zext = bpf_jit_needs_zext() ? !ret 20402 : false; 20403 } 20404 20405 if (ret == 0) 20406 ret = fixup_call_args(env); 20407 20408 env->verification_time = ktime_get_ns() - start_time; 20409 print_verification_stats(env); 20410 env->prog->aux->verified_insns = env->insn_processed; 20411 20412 /* preserve original error even if log finalization is successful */ 20413 err = bpf_vlog_finalize(&env->log, &log_true_size); 20414 if (err) 20415 ret = err; 20416 20417 if (uattr_size >= offsetofend(union bpf_attr, log_true_size) && 20418 copy_to_bpfptr_offset(uattr, offsetof(union bpf_attr, log_true_size), 20419 &log_true_size, sizeof(log_true_size))) { 20420 ret = -EFAULT; 20421 goto err_release_maps; 20422 } 20423 20424 if (ret) 20425 goto err_release_maps; 20426 20427 if (env->used_map_cnt) { 20428 /* if program passed verifier, update used_maps in bpf_prog_info */ 20429 env->prog->aux->used_maps = kmalloc_array(env->used_map_cnt, 20430 sizeof(env->used_maps[0]), 20431 GFP_KERNEL); 20432 20433 if (!env->prog->aux->used_maps) { 20434 ret = -ENOMEM; 20435 goto err_release_maps; 20436 } 20437 20438 memcpy(env->prog->aux->used_maps, env->used_maps, 20439 sizeof(env->used_maps[0]) * env->used_map_cnt); 20440 env->prog->aux->used_map_cnt = env->used_map_cnt; 20441 } 20442 if (env->used_btf_cnt) { 20443 /* if program passed verifier, update used_btfs in bpf_prog_aux */ 20444 env->prog->aux->used_btfs = kmalloc_array(env->used_btf_cnt, 20445 sizeof(env->used_btfs[0]), 20446 GFP_KERNEL); 20447 if (!env->prog->aux->used_btfs) { 20448 ret = -ENOMEM; 20449 goto err_release_maps; 20450 } 20451 20452 memcpy(env->prog->aux->used_btfs, env->used_btfs, 20453 sizeof(env->used_btfs[0]) * env->used_btf_cnt); 20454 env->prog->aux->used_btf_cnt = env->used_btf_cnt; 20455 } 20456 if (env->used_map_cnt || env->used_btf_cnt) { 20457 /* program is valid. Convert pseudo bpf_ld_imm64 into generic 20458 * bpf_ld_imm64 instructions 20459 */ 20460 convert_pseudo_ld_imm64(env); 20461 } 20462 20463 adjust_btf_func(env); 20464 20465 err_release_maps: 20466 if (!env->prog->aux->used_maps) 20467 /* if we didn't copy map pointers into bpf_prog_info, release 20468 * them now. Otherwise free_used_maps() will release them. 20469 */ 20470 release_maps(env); 20471 if (!env->prog->aux->used_btfs) 20472 release_btfs(env); 20473 20474 /* extension progs temporarily inherit the attach_type of their targets 20475 for verification purposes, so set it back to zero before returning 20476 */ 20477 if (env->prog->type == BPF_PROG_TYPE_EXT) 20478 env->prog->expected_attach_type = 0; 20479 20480 *prog = env->prog; 20481 err_unlock: 20482 if (!is_priv) 20483 mutex_unlock(&bpf_verifier_lock); 20484 vfree(env->insn_aux_data); 20485 err_free_env: 20486 kvfree(env); 20487 return ret; 20488 } 20489