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 copy_register_state(reg, known_reg); 14502 })); 14503 } 14504 14505 static int check_cond_jmp_op(struct bpf_verifier_env *env, 14506 struct bpf_insn *insn, int *insn_idx) 14507 { 14508 struct bpf_verifier_state *this_branch = env->cur_state; 14509 struct bpf_verifier_state *other_branch; 14510 struct bpf_reg_state *regs = this_branch->frame[this_branch->curframe]->regs; 14511 struct bpf_reg_state *dst_reg, *other_branch_regs, *src_reg = NULL; 14512 struct bpf_reg_state *eq_branch_regs; 14513 u8 opcode = BPF_OP(insn->code); 14514 bool is_jmp32; 14515 int pred = -1; 14516 int err; 14517 14518 /* Only conditional jumps are expected to reach here. */ 14519 if (opcode == BPF_JA || opcode > BPF_JSLE) { 14520 verbose(env, "invalid BPF_JMP/JMP32 opcode %x\n", opcode); 14521 return -EINVAL; 14522 } 14523 14524 /* check src2 operand */ 14525 err = check_reg_arg(env, insn->dst_reg, SRC_OP); 14526 if (err) 14527 return err; 14528 14529 dst_reg = ®s[insn->dst_reg]; 14530 if (BPF_SRC(insn->code) == BPF_X) { 14531 if (insn->imm != 0) { 14532 verbose(env, "BPF_JMP/JMP32 uses reserved fields\n"); 14533 return -EINVAL; 14534 } 14535 14536 /* check src1 operand */ 14537 err = check_reg_arg(env, insn->src_reg, SRC_OP); 14538 if (err) 14539 return err; 14540 14541 src_reg = ®s[insn->src_reg]; 14542 if (!(reg_is_pkt_pointer_any(dst_reg) && reg_is_pkt_pointer_any(src_reg)) && 14543 is_pointer_value(env, insn->src_reg)) { 14544 verbose(env, "R%d pointer comparison prohibited\n", 14545 insn->src_reg); 14546 return -EACCES; 14547 } 14548 } else { 14549 if (insn->src_reg != BPF_REG_0) { 14550 verbose(env, "BPF_JMP/JMP32 uses reserved fields\n"); 14551 return -EINVAL; 14552 } 14553 } 14554 14555 is_jmp32 = BPF_CLASS(insn->code) == BPF_JMP32; 14556 14557 if (BPF_SRC(insn->code) == BPF_K) { 14558 pred = is_branch_taken(dst_reg, insn->imm, opcode, is_jmp32); 14559 } else if (src_reg->type == SCALAR_VALUE && 14560 is_jmp32 && tnum_is_const(tnum_subreg(src_reg->var_off))) { 14561 pred = is_branch_taken(dst_reg, 14562 tnum_subreg(src_reg->var_off).value, 14563 opcode, 14564 is_jmp32); 14565 } else if (src_reg->type == SCALAR_VALUE && 14566 !is_jmp32 && tnum_is_const(src_reg->var_off)) { 14567 pred = is_branch_taken(dst_reg, 14568 src_reg->var_off.value, 14569 opcode, 14570 is_jmp32); 14571 } else if (dst_reg->type == SCALAR_VALUE && 14572 is_jmp32 && tnum_is_const(tnum_subreg(dst_reg->var_off))) { 14573 pred = is_branch_taken(src_reg, 14574 tnum_subreg(dst_reg->var_off).value, 14575 flip_opcode(opcode), 14576 is_jmp32); 14577 } else if (dst_reg->type == SCALAR_VALUE && 14578 !is_jmp32 && tnum_is_const(dst_reg->var_off)) { 14579 pred = is_branch_taken(src_reg, 14580 dst_reg->var_off.value, 14581 flip_opcode(opcode), 14582 is_jmp32); 14583 } else if (reg_is_pkt_pointer_any(dst_reg) && 14584 reg_is_pkt_pointer_any(src_reg) && 14585 !is_jmp32) { 14586 pred = is_pkt_ptr_branch_taken(dst_reg, src_reg, opcode); 14587 } 14588 14589 if (pred >= 0) { 14590 /* If we get here with a dst_reg pointer type it is because 14591 * above is_branch_taken() special cased the 0 comparison. 14592 */ 14593 if (!__is_pointer_value(false, dst_reg)) 14594 err = mark_chain_precision(env, insn->dst_reg); 14595 if (BPF_SRC(insn->code) == BPF_X && !err && 14596 !__is_pointer_value(false, src_reg)) 14597 err = mark_chain_precision(env, insn->src_reg); 14598 if (err) 14599 return err; 14600 } 14601 14602 if (pred == 1) { 14603 /* Only follow the goto, ignore fall-through. If needed, push 14604 * the fall-through branch for simulation under speculative 14605 * execution. 14606 */ 14607 if (!env->bypass_spec_v1 && 14608 !sanitize_speculative_path(env, insn, *insn_idx + 1, 14609 *insn_idx)) 14610 return -EFAULT; 14611 if (env->log.level & BPF_LOG_LEVEL) 14612 print_insn_state(env, this_branch->frame[this_branch->curframe]); 14613 *insn_idx += insn->off; 14614 return 0; 14615 } else if (pred == 0) { 14616 /* Only follow the fall-through branch, since that's where the 14617 * program will go. If needed, push the goto branch for 14618 * simulation under speculative execution. 14619 */ 14620 if (!env->bypass_spec_v1 && 14621 !sanitize_speculative_path(env, insn, 14622 *insn_idx + insn->off + 1, 14623 *insn_idx)) 14624 return -EFAULT; 14625 if (env->log.level & BPF_LOG_LEVEL) 14626 print_insn_state(env, this_branch->frame[this_branch->curframe]); 14627 return 0; 14628 } 14629 14630 other_branch = push_stack(env, *insn_idx + insn->off + 1, *insn_idx, 14631 false); 14632 if (!other_branch) 14633 return -EFAULT; 14634 other_branch_regs = other_branch->frame[other_branch->curframe]->regs; 14635 14636 /* detect if we are comparing against a constant value so we can adjust 14637 * our min/max values for our dst register. 14638 * this is only legit if both are scalars (or pointers to the same 14639 * object, I suppose, see the PTR_MAYBE_NULL related if block below), 14640 * because otherwise the different base pointers mean the offsets aren't 14641 * comparable. 14642 */ 14643 if (BPF_SRC(insn->code) == BPF_X) { 14644 struct bpf_reg_state *src_reg = ®s[insn->src_reg]; 14645 14646 if (dst_reg->type == SCALAR_VALUE && 14647 src_reg->type == SCALAR_VALUE) { 14648 if (tnum_is_const(src_reg->var_off) || 14649 (is_jmp32 && 14650 tnum_is_const(tnum_subreg(src_reg->var_off)))) 14651 reg_set_min_max(&other_branch_regs[insn->dst_reg], 14652 dst_reg, 14653 src_reg->var_off.value, 14654 tnum_subreg(src_reg->var_off).value, 14655 opcode, is_jmp32); 14656 else if (tnum_is_const(dst_reg->var_off) || 14657 (is_jmp32 && 14658 tnum_is_const(tnum_subreg(dst_reg->var_off)))) 14659 reg_set_min_max_inv(&other_branch_regs[insn->src_reg], 14660 src_reg, 14661 dst_reg->var_off.value, 14662 tnum_subreg(dst_reg->var_off).value, 14663 opcode, is_jmp32); 14664 else if (!is_jmp32 && 14665 (opcode == BPF_JEQ || opcode == BPF_JNE)) 14666 /* Comparing for equality, we can combine knowledge */ 14667 reg_combine_min_max(&other_branch_regs[insn->src_reg], 14668 &other_branch_regs[insn->dst_reg], 14669 src_reg, dst_reg, opcode); 14670 if (src_reg->id && 14671 !WARN_ON_ONCE(src_reg->id != other_branch_regs[insn->src_reg].id)) { 14672 find_equal_scalars(this_branch, src_reg); 14673 find_equal_scalars(other_branch, &other_branch_regs[insn->src_reg]); 14674 } 14675 14676 } 14677 } else if (dst_reg->type == SCALAR_VALUE) { 14678 reg_set_min_max(&other_branch_regs[insn->dst_reg], 14679 dst_reg, insn->imm, (u32)insn->imm, 14680 opcode, is_jmp32); 14681 } 14682 14683 if (dst_reg->type == SCALAR_VALUE && dst_reg->id && 14684 !WARN_ON_ONCE(dst_reg->id != other_branch_regs[insn->dst_reg].id)) { 14685 find_equal_scalars(this_branch, dst_reg); 14686 find_equal_scalars(other_branch, &other_branch_regs[insn->dst_reg]); 14687 } 14688 14689 /* if one pointer register is compared to another pointer 14690 * register check if PTR_MAYBE_NULL could be lifted. 14691 * E.g. register A - maybe null 14692 * register B - not null 14693 * for JNE A, B, ... - A is not null in the false branch; 14694 * for JEQ A, B, ... - A is not null in the true branch. 14695 * 14696 * Since PTR_TO_BTF_ID points to a kernel struct that does 14697 * not need to be null checked by the BPF program, i.e., 14698 * could be null even without PTR_MAYBE_NULL marking, so 14699 * only propagate nullness when neither reg is that type. 14700 */ 14701 if (!is_jmp32 && BPF_SRC(insn->code) == BPF_X && 14702 __is_pointer_value(false, src_reg) && __is_pointer_value(false, dst_reg) && 14703 type_may_be_null(src_reg->type) != type_may_be_null(dst_reg->type) && 14704 base_type(src_reg->type) != PTR_TO_BTF_ID && 14705 base_type(dst_reg->type) != PTR_TO_BTF_ID) { 14706 eq_branch_regs = NULL; 14707 switch (opcode) { 14708 case BPF_JEQ: 14709 eq_branch_regs = other_branch_regs; 14710 break; 14711 case BPF_JNE: 14712 eq_branch_regs = regs; 14713 break; 14714 default: 14715 /* do nothing */ 14716 break; 14717 } 14718 if (eq_branch_regs) { 14719 if (type_may_be_null(src_reg->type)) 14720 mark_ptr_not_null_reg(&eq_branch_regs[insn->src_reg]); 14721 else 14722 mark_ptr_not_null_reg(&eq_branch_regs[insn->dst_reg]); 14723 } 14724 } 14725 14726 /* detect if R == 0 where R is returned from bpf_map_lookup_elem(). 14727 * NOTE: these optimizations below are related with pointer comparison 14728 * which will never be JMP32. 14729 */ 14730 if (!is_jmp32 && BPF_SRC(insn->code) == BPF_K && 14731 insn->imm == 0 && (opcode == BPF_JEQ || opcode == BPF_JNE) && 14732 type_may_be_null(dst_reg->type)) { 14733 /* Mark all identical registers in each branch as either 14734 * safe or unknown depending R == 0 or R != 0 conditional. 14735 */ 14736 mark_ptr_or_null_regs(this_branch, insn->dst_reg, 14737 opcode == BPF_JNE); 14738 mark_ptr_or_null_regs(other_branch, insn->dst_reg, 14739 opcode == BPF_JEQ); 14740 } else if (!try_match_pkt_pointers(insn, dst_reg, ®s[insn->src_reg], 14741 this_branch, other_branch) && 14742 is_pointer_value(env, insn->dst_reg)) { 14743 verbose(env, "R%d pointer comparison prohibited\n", 14744 insn->dst_reg); 14745 return -EACCES; 14746 } 14747 if (env->log.level & BPF_LOG_LEVEL) 14748 print_insn_state(env, this_branch->frame[this_branch->curframe]); 14749 return 0; 14750 } 14751 14752 /* verify BPF_LD_IMM64 instruction */ 14753 static int check_ld_imm(struct bpf_verifier_env *env, struct bpf_insn *insn) 14754 { 14755 struct bpf_insn_aux_data *aux = cur_aux(env); 14756 struct bpf_reg_state *regs = cur_regs(env); 14757 struct bpf_reg_state *dst_reg; 14758 struct bpf_map *map; 14759 int err; 14760 14761 if (BPF_SIZE(insn->code) != BPF_DW) { 14762 verbose(env, "invalid BPF_LD_IMM insn\n"); 14763 return -EINVAL; 14764 } 14765 if (insn->off != 0) { 14766 verbose(env, "BPF_LD_IMM64 uses reserved fields\n"); 14767 return -EINVAL; 14768 } 14769 14770 err = check_reg_arg(env, insn->dst_reg, DST_OP); 14771 if (err) 14772 return err; 14773 14774 dst_reg = ®s[insn->dst_reg]; 14775 if (insn->src_reg == 0) { 14776 u64 imm = ((u64)(insn + 1)->imm << 32) | (u32)insn->imm; 14777 14778 dst_reg->type = SCALAR_VALUE; 14779 __mark_reg_known(®s[insn->dst_reg], imm); 14780 return 0; 14781 } 14782 14783 /* All special src_reg cases are listed below. From this point onwards 14784 * we either succeed and assign a corresponding dst_reg->type after 14785 * zeroing the offset, or fail and reject the program. 14786 */ 14787 mark_reg_known_zero(env, regs, insn->dst_reg); 14788 14789 if (insn->src_reg == BPF_PSEUDO_BTF_ID) { 14790 dst_reg->type = aux->btf_var.reg_type; 14791 switch (base_type(dst_reg->type)) { 14792 case PTR_TO_MEM: 14793 dst_reg->mem_size = aux->btf_var.mem_size; 14794 break; 14795 case PTR_TO_BTF_ID: 14796 dst_reg->btf = aux->btf_var.btf; 14797 dst_reg->btf_id = aux->btf_var.btf_id; 14798 break; 14799 default: 14800 verbose(env, "bpf verifier is misconfigured\n"); 14801 return -EFAULT; 14802 } 14803 return 0; 14804 } 14805 14806 if (insn->src_reg == BPF_PSEUDO_FUNC) { 14807 struct bpf_prog_aux *aux = env->prog->aux; 14808 u32 subprogno = find_subprog(env, 14809 env->insn_idx + insn->imm + 1); 14810 14811 if (!aux->func_info) { 14812 verbose(env, "missing btf func_info\n"); 14813 return -EINVAL; 14814 } 14815 if (aux->func_info_aux[subprogno].linkage != BTF_FUNC_STATIC) { 14816 verbose(env, "callback function not static\n"); 14817 return -EINVAL; 14818 } 14819 14820 dst_reg->type = PTR_TO_FUNC; 14821 dst_reg->subprogno = subprogno; 14822 return 0; 14823 } 14824 14825 map = env->used_maps[aux->map_index]; 14826 dst_reg->map_ptr = map; 14827 14828 if (insn->src_reg == BPF_PSEUDO_MAP_VALUE || 14829 insn->src_reg == BPF_PSEUDO_MAP_IDX_VALUE) { 14830 dst_reg->type = PTR_TO_MAP_VALUE; 14831 dst_reg->off = aux->map_off; 14832 WARN_ON_ONCE(map->max_entries != 1); 14833 /* We want reg->id to be same (0) as map_value is not distinct */ 14834 } else if (insn->src_reg == BPF_PSEUDO_MAP_FD || 14835 insn->src_reg == BPF_PSEUDO_MAP_IDX) { 14836 dst_reg->type = CONST_PTR_TO_MAP; 14837 } else { 14838 verbose(env, "bpf verifier is misconfigured\n"); 14839 return -EINVAL; 14840 } 14841 14842 return 0; 14843 } 14844 14845 static bool may_access_skb(enum bpf_prog_type type) 14846 { 14847 switch (type) { 14848 case BPF_PROG_TYPE_SOCKET_FILTER: 14849 case BPF_PROG_TYPE_SCHED_CLS: 14850 case BPF_PROG_TYPE_SCHED_ACT: 14851 return true; 14852 default: 14853 return false; 14854 } 14855 } 14856 14857 /* verify safety of LD_ABS|LD_IND instructions: 14858 * - they can only appear in the programs where ctx == skb 14859 * - since they are wrappers of function calls, they scratch R1-R5 registers, 14860 * preserve R6-R9, and store return value into R0 14861 * 14862 * Implicit input: 14863 * ctx == skb == R6 == CTX 14864 * 14865 * Explicit input: 14866 * SRC == any register 14867 * IMM == 32-bit immediate 14868 * 14869 * Output: 14870 * R0 - 8/16/32-bit skb data converted to cpu endianness 14871 */ 14872 static int check_ld_abs(struct bpf_verifier_env *env, struct bpf_insn *insn) 14873 { 14874 struct bpf_reg_state *regs = cur_regs(env); 14875 static const int ctx_reg = BPF_REG_6; 14876 u8 mode = BPF_MODE(insn->code); 14877 int i, err; 14878 14879 if (!may_access_skb(resolve_prog_type(env->prog))) { 14880 verbose(env, "BPF_LD_[ABS|IND] instructions not allowed for this program type\n"); 14881 return -EINVAL; 14882 } 14883 14884 if (!env->ops->gen_ld_abs) { 14885 verbose(env, "bpf verifier is misconfigured\n"); 14886 return -EINVAL; 14887 } 14888 14889 if (insn->dst_reg != BPF_REG_0 || insn->off != 0 || 14890 BPF_SIZE(insn->code) == BPF_DW || 14891 (mode == BPF_ABS && insn->src_reg != BPF_REG_0)) { 14892 verbose(env, "BPF_LD_[ABS|IND] uses reserved fields\n"); 14893 return -EINVAL; 14894 } 14895 14896 /* check whether implicit source operand (register R6) is readable */ 14897 err = check_reg_arg(env, ctx_reg, SRC_OP); 14898 if (err) 14899 return err; 14900 14901 /* Disallow usage of BPF_LD_[ABS|IND] with reference tracking, as 14902 * gen_ld_abs() may terminate the program at runtime, leading to 14903 * reference leak. 14904 */ 14905 err = check_reference_leak(env); 14906 if (err) { 14907 verbose(env, "BPF_LD_[ABS|IND] cannot be mixed with socket references\n"); 14908 return err; 14909 } 14910 14911 if (env->cur_state->active_lock.ptr) { 14912 verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_spin_lock-ed region\n"); 14913 return -EINVAL; 14914 } 14915 14916 if (env->cur_state->active_rcu_lock) { 14917 verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_rcu_read_lock-ed region\n"); 14918 return -EINVAL; 14919 } 14920 14921 if (regs[ctx_reg].type != PTR_TO_CTX) { 14922 verbose(env, 14923 "at the time of BPF_LD_ABS|IND R6 != pointer to skb\n"); 14924 return -EINVAL; 14925 } 14926 14927 if (mode == BPF_IND) { 14928 /* check explicit source operand */ 14929 err = check_reg_arg(env, insn->src_reg, SRC_OP); 14930 if (err) 14931 return err; 14932 } 14933 14934 err = check_ptr_off_reg(env, ®s[ctx_reg], ctx_reg); 14935 if (err < 0) 14936 return err; 14937 14938 /* reset caller saved regs to unreadable */ 14939 for (i = 0; i < CALLER_SAVED_REGS; i++) { 14940 mark_reg_not_init(env, regs, caller_saved[i]); 14941 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK); 14942 } 14943 14944 /* mark destination R0 register as readable, since it contains 14945 * the value fetched from the packet. 14946 * Already marked as written above. 14947 */ 14948 mark_reg_unknown(env, regs, BPF_REG_0); 14949 /* ld_abs load up to 32-bit skb data. */ 14950 regs[BPF_REG_0].subreg_def = env->insn_idx + 1; 14951 return 0; 14952 } 14953 14954 static int check_return_code(struct bpf_verifier_env *env) 14955 { 14956 struct tnum enforce_attach_type_range = tnum_unknown; 14957 const struct bpf_prog *prog = env->prog; 14958 struct bpf_reg_state *reg; 14959 struct tnum range = tnum_range(0, 1), const_0 = tnum_const(0); 14960 enum bpf_prog_type prog_type = resolve_prog_type(env->prog); 14961 int err; 14962 struct bpf_func_state *frame = env->cur_state->frame[0]; 14963 const bool is_subprog = frame->subprogno; 14964 14965 /* LSM and struct_ops func-ptr's return type could be "void" */ 14966 if (!is_subprog) { 14967 switch (prog_type) { 14968 case BPF_PROG_TYPE_LSM: 14969 if (prog->expected_attach_type == BPF_LSM_CGROUP) 14970 /* See below, can be 0 or 0-1 depending on hook. */ 14971 break; 14972 fallthrough; 14973 case BPF_PROG_TYPE_STRUCT_OPS: 14974 if (!prog->aux->attach_func_proto->type) 14975 return 0; 14976 break; 14977 default: 14978 break; 14979 } 14980 } 14981 14982 /* eBPF calling convention is such that R0 is used 14983 * to return the value from eBPF program. 14984 * Make sure that it's readable at this time 14985 * of bpf_exit, which means that program wrote 14986 * something into it earlier 14987 */ 14988 err = check_reg_arg(env, BPF_REG_0, SRC_OP); 14989 if (err) 14990 return err; 14991 14992 if (is_pointer_value(env, BPF_REG_0)) { 14993 verbose(env, "R0 leaks addr as return value\n"); 14994 return -EACCES; 14995 } 14996 14997 reg = cur_regs(env) + BPF_REG_0; 14998 14999 if (frame->in_async_callback_fn) { 15000 /* enforce return zero from async callbacks like timer */ 15001 if (reg->type != SCALAR_VALUE) { 15002 verbose(env, "In async callback the register R0 is not a known value (%s)\n", 15003 reg_type_str(env, reg->type)); 15004 return -EINVAL; 15005 } 15006 15007 if (!tnum_in(const_0, reg->var_off)) { 15008 verbose_invalid_scalar(env, reg, &const_0, "async callback", "R0"); 15009 return -EINVAL; 15010 } 15011 return 0; 15012 } 15013 15014 if (is_subprog) { 15015 if (reg->type != SCALAR_VALUE) { 15016 verbose(env, "At subprogram exit the register R0 is not a scalar value (%s)\n", 15017 reg_type_str(env, reg->type)); 15018 return -EINVAL; 15019 } 15020 return 0; 15021 } 15022 15023 switch (prog_type) { 15024 case BPF_PROG_TYPE_CGROUP_SOCK_ADDR: 15025 if (env->prog->expected_attach_type == BPF_CGROUP_UDP4_RECVMSG || 15026 env->prog->expected_attach_type == BPF_CGROUP_UDP6_RECVMSG || 15027 env->prog->expected_attach_type == BPF_CGROUP_INET4_GETPEERNAME || 15028 env->prog->expected_attach_type == BPF_CGROUP_INET6_GETPEERNAME || 15029 env->prog->expected_attach_type == BPF_CGROUP_INET4_GETSOCKNAME || 15030 env->prog->expected_attach_type == BPF_CGROUP_INET6_GETSOCKNAME) 15031 range = tnum_range(1, 1); 15032 if (env->prog->expected_attach_type == BPF_CGROUP_INET4_BIND || 15033 env->prog->expected_attach_type == BPF_CGROUP_INET6_BIND) 15034 range = tnum_range(0, 3); 15035 break; 15036 case BPF_PROG_TYPE_CGROUP_SKB: 15037 if (env->prog->expected_attach_type == BPF_CGROUP_INET_EGRESS) { 15038 range = tnum_range(0, 3); 15039 enforce_attach_type_range = tnum_range(2, 3); 15040 } 15041 break; 15042 case BPF_PROG_TYPE_CGROUP_SOCK: 15043 case BPF_PROG_TYPE_SOCK_OPS: 15044 case BPF_PROG_TYPE_CGROUP_DEVICE: 15045 case BPF_PROG_TYPE_CGROUP_SYSCTL: 15046 case BPF_PROG_TYPE_CGROUP_SOCKOPT: 15047 break; 15048 case BPF_PROG_TYPE_RAW_TRACEPOINT: 15049 if (!env->prog->aux->attach_btf_id) 15050 return 0; 15051 range = tnum_const(0); 15052 break; 15053 case BPF_PROG_TYPE_TRACING: 15054 switch (env->prog->expected_attach_type) { 15055 case BPF_TRACE_FENTRY: 15056 case BPF_TRACE_FEXIT: 15057 range = tnum_const(0); 15058 break; 15059 case BPF_TRACE_RAW_TP: 15060 case BPF_MODIFY_RETURN: 15061 return 0; 15062 case BPF_TRACE_ITER: 15063 break; 15064 default: 15065 return -ENOTSUPP; 15066 } 15067 break; 15068 case BPF_PROG_TYPE_SK_LOOKUP: 15069 range = tnum_range(SK_DROP, SK_PASS); 15070 break; 15071 15072 case BPF_PROG_TYPE_LSM: 15073 if (env->prog->expected_attach_type != BPF_LSM_CGROUP) { 15074 /* Regular BPF_PROG_TYPE_LSM programs can return 15075 * any value. 15076 */ 15077 return 0; 15078 } 15079 if (!env->prog->aux->attach_func_proto->type) { 15080 /* Make sure programs that attach to void 15081 * hooks don't try to modify return value. 15082 */ 15083 range = tnum_range(1, 1); 15084 } 15085 break; 15086 15087 case BPF_PROG_TYPE_NETFILTER: 15088 range = tnum_range(NF_DROP, NF_ACCEPT); 15089 break; 15090 case BPF_PROG_TYPE_EXT: 15091 /* freplace program can return anything as its return value 15092 * depends on the to-be-replaced kernel func or bpf program. 15093 */ 15094 default: 15095 return 0; 15096 } 15097 15098 if (reg->type != SCALAR_VALUE) { 15099 verbose(env, "At program exit the register R0 is not a known value (%s)\n", 15100 reg_type_str(env, reg->type)); 15101 return -EINVAL; 15102 } 15103 15104 if (!tnum_in(range, reg->var_off)) { 15105 verbose_invalid_scalar(env, reg, &range, "program exit", "R0"); 15106 if (prog->expected_attach_type == BPF_LSM_CGROUP && 15107 prog_type == BPF_PROG_TYPE_LSM && 15108 !prog->aux->attach_func_proto->type) 15109 verbose(env, "Note, BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n"); 15110 return -EINVAL; 15111 } 15112 15113 if (!tnum_is_unknown(enforce_attach_type_range) && 15114 tnum_in(enforce_attach_type_range, reg->var_off)) 15115 env->prog->enforce_expected_attach_type = 1; 15116 return 0; 15117 } 15118 15119 /* non-recursive DFS pseudo code 15120 * 1 procedure DFS-iterative(G,v): 15121 * 2 label v as discovered 15122 * 3 let S be a stack 15123 * 4 S.push(v) 15124 * 5 while S is not empty 15125 * 6 t <- S.peek() 15126 * 7 if t is what we're looking for: 15127 * 8 return t 15128 * 9 for all edges e in G.adjacentEdges(t) do 15129 * 10 if edge e is already labelled 15130 * 11 continue with the next edge 15131 * 12 w <- G.adjacentVertex(t,e) 15132 * 13 if vertex w is not discovered and not explored 15133 * 14 label e as tree-edge 15134 * 15 label w as discovered 15135 * 16 S.push(w) 15136 * 17 continue at 5 15137 * 18 else if vertex w is discovered 15138 * 19 label e as back-edge 15139 * 20 else 15140 * 21 // vertex w is explored 15141 * 22 label e as forward- or cross-edge 15142 * 23 label t as explored 15143 * 24 S.pop() 15144 * 15145 * convention: 15146 * 0x10 - discovered 15147 * 0x11 - discovered and fall-through edge labelled 15148 * 0x12 - discovered and fall-through and branch edges labelled 15149 * 0x20 - explored 15150 */ 15151 15152 enum { 15153 DISCOVERED = 0x10, 15154 EXPLORED = 0x20, 15155 FALLTHROUGH = 1, 15156 BRANCH = 2, 15157 }; 15158 15159 static void mark_prune_point(struct bpf_verifier_env *env, int idx) 15160 { 15161 env->insn_aux_data[idx].prune_point = true; 15162 } 15163 15164 static bool is_prune_point(struct bpf_verifier_env *env, int insn_idx) 15165 { 15166 return env->insn_aux_data[insn_idx].prune_point; 15167 } 15168 15169 static void mark_force_checkpoint(struct bpf_verifier_env *env, int idx) 15170 { 15171 env->insn_aux_data[idx].force_checkpoint = true; 15172 } 15173 15174 static bool is_force_checkpoint(struct bpf_verifier_env *env, int insn_idx) 15175 { 15176 return env->insn_aux_data[insn_idx].force_checkpoint; 15177 } 15178 15179 static void mark_calls_callback(struct bpf_verifier_env *env, int idx) 15180 { 15181 env->insn_aux_data[idx].calls_callback = true; 15182 } 15183 15184 static bool calls_callback(struct bpf_verifier_env *env, int insn_idx) 15185 { 15186 return env->insn_aux_data[insn_idx].calls_callback; 15187 } 15188 15189 enum { 15190 DONE_EXPLORING = 0, 15191 KEEP_EXPLORING = 1, 15192 }; 15193 15194 /* t, w, e - match pseudo-code above: 15195 * t - index of current instruction 15196 * w - next instruction 15197 * e - edge 15198 */ 15199 static int push_insn(int t, int w, int e, struct bpf_verifier_env *env) 15200 { 15201 int *insn_stack = env->cfg.insn_stack; 15202 int *insn_state = env->cfg.insn_state; 15203 15204 if (e == FALLTHROUGH && insn_state[t] >= (DISCOVERED | FALLTHROUGH)) 15205 return DONE_EXPLORING; 15206 15207 if (e == BRANCH && insn_state[t] >= (DISCOVERED | BRANCH)) 15208 return DONE_EXPLORING; 15209 15210 if (w < 0 || w >= env->prog->len) { 15211 verbose_linfo(env, t, "%d: ", t); 15212 verbose(env, "jump out of range from insn %d to %d\n", t, w); 15213 return -EINVAL; 15214 } 15215 15216 if (e == BRANCH) { 15217 /* mark branch target for state pruning */ 15218 mark_prune_point(env, w); 15219 mark_jmp_point(env, w); 15220 } 15221 15222 if (insn_state[w] == 0) { 15223 /* tree-edge */ 15224 insn_state[t] = DISCOVERED | e; 15225 insn_state[w] = DISCOVERED; 15226 if (env->cfg.cur_stack >= env->prog->len) 15227 return -E2BIG; 15228 insn_stack[env->cfg.cur_stack++] = w; 15229 return KEEP_EXPLORING; 15230 } else if ((insn_state[w] & 0xF0) == DISCOVERED) { 15231 if (env->bpf_capable) 15232 return DONE_EXPLORING; 15233 verbose_linfo(env, t, "%d: ", t); 15234 verbose_linfo(env, w, "%d: ", w); 15235 verbose(env, "back-edge from insn %d to %d\n", t, w); 15236 return -EINVAL; 15237 } else if (insn_state[w] == EXPLORED) { 15238 /* forward- or cross-edge */ 15239 insn_state[t] = DISCOVERED | e; 15240 } else { 15241 verbose(env, "insn state internal bug\n"); 15242 return -EFAULT; 15243 } 15244 return DONE_EXPLORING; 15245 } 15246 15247 static int visit_func_call_insn(int t, struct bpf_insn *insns, 15248 struct bpf_verifier_env *env, 15249 bool visit_callee) 15250 { 15251 int ret, insn_sz; 15252 15253 insn_sz = bpf_is_ldimm64(&insns[t]) ? 2 : 1; 15254 ret = push_insn(t, t + insn_sz, FALLTHROUGH, env); 15255 if (ret) 15256 return ret; 15257 15258 mark_prune_point(env, t + insn_sz); 15259 /* when we exit from subprog, we need to record non-linear history */ 15260 mark_jmp_point(env, t + insn_sz); 15261 15262 if (visit_callee) { 15263 mark_prune_point(env, t); 15264 ret = push_insn(t, t + insns[t].imm + 1, BRANCH, env); 15265 } 15266 return ret; 15267 } 15268 15269 /* Visits the instruction at index t and returns one of the following: 15270 * < 0 - an error occurred 15271 * DONE_EXPLORING - the instruction was fully explored 15272 * KEEP_EXPLORING - there is still work to be done before it is fully explored 15273 */ 15274 static int visit_insn(int t, struct bpf_verifier_env *env) 15275 { 15276 struct bpf_insn *insns = env->prog->insnsi, *insn = &insns[t]; 15277 int ret, off, insn_sz; 15278 15279 if (bpf_pseudo_func(insn)) 15280 return visit_func_call_insn(t, insns, env, true); 15281 15282 /* All non-branch instructions have a single fall-through edge. */ 15283 if (BPF_CLASS(insn->code) != BPF_JMP && 15284 BPF_CLASS(insn->code) != BPF_JMP32) { 15285 insn_sz = bpf_is_ldimm64(insn) ? 2 : 1; 15286 return push_insn(t, t + insn_sz, FALLTHROUGH, env); 15287 } 15288 15289 switch (BPF_OP(insn->code)) { 15290 case BPF_EXIT: 15291 return DONE_EXPLORING; 15292 15293 case BPF_CALL: 15294 if (insn->src_reg == 0 && insn->imm == BPF_FUNC_timer_set_callback) 15295 /* Mark this call insn as a prune point to trigger 15296 * is_state_visited() check before call itself is 15297 * processed by __check_func_call(). Otherwise new 15298 * async state will be pushed for further exploration. 15299 */ 15300 mark_prune_point(env, t); 15301 /* For functions that invoke callbacks it is not known how many times 15302 * callback would be called. Verifier models callback calling functions 15303 * by repeatedly visiting callback bodies and returning to origin call 15304 * instruction. 15305 * In order to stop such iteration verifier needs to identify when a 15306 * state identical some state from a previous iteration is reached. 15307 * Check below forces creation of checkpoint before callback calling 15308 * instruction to allow search for such identical states. 15309 */ 15310 if (is_sync_callback_calling_insn(insn)) { 15311 mark_calls_callback(env, t); 15312 mark_force_checkpoint(env, t); 15313 mark_prune_point(env, t); 15314 mark_jmp_point(env, t); 15315 } 15316 if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) { 15317 struct bpf_kfunc_call_arg_meta meta; 15318 15319 ret = fetch_kfunc_meta(env, insn, &meta, NULL); 15320 if (ret == 0 && is_iter_next_kfunc(&meta)) { 15321 mark_prune_point(env, t); 15322 /* Checking and saving state checkpoints at iter_next() call 15323 * is crucial for fast convergence of open-coded iterator loop 15324 * logic, so we need to force it. If we don't do that, 15325 * is_state_visited() might skip saving a checkpoint, causing 15326 * unnecessarily long sequence of not checkpointed 15327 * instructions and jumps, leading to exhaustion of jump 15328 * history buffer, and potentially other undesired outcomes. 15329 * It is expected that with correct open-coded iterators 15330 * convergence will happen quickly, so we don't run a risk of 15331 * exhausting memory. 15332 */ 15333 mark_force_checkpoint(env, t); 15334 } 15335 } 15336 return visit_func_call_insn(t, insns, env, insn->src_reg == BPF_PSEUDO_CALL); 15337 15338 case BPF_JA: 15339 if (BPF_SRC(insn->code) != BPF_K) 15340 return -EINVAL; 15341 15342 if (BPF_CLASS(insn->code) == BPF_JMP) 15343 off = insn->off; 15344 else 15345 off = insn->imm; 15346 15347 /* unconditional jump with single edge */ 15348 ret = push_insn(t, t + off + 1, FALLTHROUGH, env); 15349 if (ret) 15350 return ret; 15351 15352 mark_prune_point(env, t + off + 1); 15353 mark_jmp_point(env, t + off + 1); 15354 15355 return ret; 15356 15357 default: 15358 /* conditional jump with two edges */ 15359 mark_prune_point(env, t); 15360 15361 ret = push_insn(t, t + 1, FALLTHROUGH, env); 15362 if (ret) 15363 return ret; 15364 15365 return push_insn(t, t + insn->off + 1, BRANCH, env); 15366 } 15367 } 15368 15369 /* non-recursive depth-first-search to detect loops in BPF program 15370 * loop == back-edge in directed graph 15371 */ 15372 static int check_cfg(struct bpf_verifier_env *env) 15373 { 15374 int insn_cnt = env->prog->len; 15375 int *insn_stack, *insn_state; 15376 int ret = 0; 15377 int i; 15378 15379 insn_state = env->cfg.insn_state = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL); 15380 if (!insn_state) 15381 return -ENOMEM; 15382 15383 insn_stack = env->cfg.insn_stack = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL); 15384 if (!insn_stack) { 15385 kvfree(insn_state); 15386 return -ENOMEM; 15387 } 15388 15389 insn_state[0] = DISCOVERED; /* mark 1st insn as discovered */ 15390 insn_stack[0] = 0; /* 0 is the first instruction */ 15391 env->cfg.cur_stack = 1; 15392 15393 while (env->cfg.cur_stack > 0) { 15394 int t = insn_stack[env->cfg.cur_stack - 1]; 15395 15396 ret = visit_insn(t, env); 15397 switch (ret) { 15398 case DONE_EXPLORING: 15399 insn_state[t] = EXPLORED; 15400 env->cfg.cur_stack--; 15401 break; 15402 case KEEP_EXPLORING: 15403 break; 15404 default: 15405 if (ret > 0) { 15406 verbose(env, "visit_insn internal bug\n"); 15407 ret = -EFAULT; 15408 } 15409 goto err_free; 15410 } 15411 } 15412 15413 if (env->cfg.cur_stack < 0) { 15414 verbose(env, "pop stack internal bug\n"); 15415 ret = -EFAULT; 15416 goto err_free; 15417 } 15418 15419 for (i = 0; i < insn_cnt; i++) { 15420 struct bpf_insn *insn = &env->prog->insnsi[i]; 15421 15422 if (insn_state[i] != EXPLORED) { 15423 verbose(env, "unreachable insn %d\n", i); 15424 ret = -EINVAL; 15425 goto err_free; 15426 } 15427 if (bpf_is_ldimm64(insn)) { 15428 if (insn_state[i + 1] != 0) { 15429 verbose(env, "jump into the middle of ldimm64 insn %d\n", i); 15430 ret = -EINVAL; 15431 goto err_free; 15432 } 15433 i++; /* skip second half of ldimm64 */ 15434 } 15435 } 15436 ret = 0; /* cfg looks good */ 15437 15438 err_free: 15439 kvfree(insn_state); 15440 kvfree(insn_stack); 15441 env->cfg.insn_state = env->cfg.insn_stack = NULL; 15442 return ret; 15443 } 15444 15445 static int check_abnormal_return(struct bpf_verifier_env *env) 15446 { 15447 int i; 15448 15449 for (i = 1; i < env->subprog_cnt; i++) { 15450 if (env->subprog_info[i].has_ld_abs) { 15451 verbose(env, "LD_ABS is not allowed in subprogs without BTF\n"); 15452 return -EINVAL; 15453 } 15454 if (env->subprog_info[i].has_tail_call) { 15455 verbose(env, "tail_call is not allowed in subprogs without BTF\n"); 15456 return -EINVAL; 15457 } 15458 } 15459 return 0; 15460 } 15461 15462 /* The minimum supported BTF func info size */ 15463 #define MIN_BPF_FUNCINFO_SIZE 8 15464 #define MAX_FUNCINFO_REC_SIZE 252 15465 15466 static int check_btf_func(struct bpf_verifier_env *env, 15467 const union bpf_attr *attr, 15468 bpfptr_t uattr) 15469 { 15470 const struct btf_type *type, *func_proto, *ret_type; 15471 u32 i, nfuncs, urec_size, min_size; 15472 u32 krec_size = sizeof(struct bpf_func_info); 15473 struct bpf_func_info *krecord; 15474 struct bpf_func_info_aux *info_aux = NULL; 15475 struct bpf_prog *prog; 15476 const struct btf *btf; 15477 bpfptr_t urecord; 15478 u32 prev_offset = 0; 15479 bool scalar_return; 15480 int ret = -ENOMEM; 15481 15482 nfuncs = attr->func_info_cnt; 15483 if (!nfuncs) { 15484 if (check_abnormal_return(env)) 15485 return -EINVAL; 15486 return 0; 15487 } 15488 15489 if (nfuncs != env->subprog_cnt) { 15490 verbose(env, "number of funcs in func_info doesn't match number of subprogs\n"); 15491 return -EINVAL; 15492 } 15493 15494 urec_size = attr->func_info_rec_size; 15495 if (urec_size < MIN_BPF_FUNCINFO_SIZE || 15496 urec_size > MAX_FUNCINFO_REC_SIZE || 15497 urec_size % sizeof(u32)) { 15498 verbose(env, "invalid func info rec size %u\n", urec_size); 15499 return -EINVAL; 15500 } 15501 15502 prog = env->prog; 15503 btf = prog->aux->btf; 15504 15505 urecord = make_bpfptr(attr->func_info, uattr.is_kernel); 15506 min_size = min_t(u32, krec_size, urec_size); 15507 15508 krecord = kvcalloc(nfuncs, krec_size, GFP_KERNEL | __GFP_NOWARN); 15509 if (!krecord) 15510 return -ENOMEM; 15511 info_aux = kcalloc(nfuncs, sizeof(*info_aux), GFP_KERNEL | __GFP_NOWARN); 15512 if (!info_aux) 15513 goto err_free; 15514 15515 for (i = 0; i < nfuncs; i++) { 15516 ret = bpf_check_uarg_tail_zero(urecord, krec_size, urec_size); 15517 if (ret) { 15518 if (ret == -E2BIG) { 15519 verbose(env, "nonzero tailing record in func info"); 15520 /* set the size kernel expects so loader can zero 15521 * out the rest of the record. 15522 */ 15523 if (copy_to_bpfptr_offset(uattr, 15524 offsetof(union bpf_attr, func_info_rec_size), 15525 &min_size, sizeof(min_size))) 15526 ret = -EFAULT; 15527 } 15528 goto err_free; 15529 } 15530 15531 if (copy_from_bpfptr(&krecord[i], urecord, min_size)) { 15532 ret = -EFAULT; 15533 goto err_free; 15534 } 15535 15536 /* check insn_off */ 15537 ret = -EINVAL; 15538 if (i == 0) { 15539 if (krecord[i].insn_off) { 15540 verbose(env, 15541 "nonzero insn_off %u for the first func info record", 15542 krecord[i].insn_off); 15543 goto err_free; 15544 } 15545 } else if (krecord[i].insn_off <= prev_offset) { 15546 verbose(env, 15547 "same or smaller insn offset (%u) than previous func info record (%u)", 15548 krecord[i].insn_off, prev_offset); 15549 goto err_free; 15550 } 15551 15552 if (env->subprog_info[i].start != krecord[i].insn_off) { 15553 verbose(env, "func_info BTF section doesn't match subprog layout in BPF program\n"); 15554 goto err_free; 15555 } 15556 15557 /* check type_id */ 15558 type = btf_type_by_id(btf, krecord[i].type_id); 15559 if (!type || !btf_type_is_func(type)) { 15560 verbose(env, "invalid type id %d in func info", 15561 krecord[i].type_id); 15562 goto err_free; 15563 } 15564 info_aux[i].linkage = BTF_INFO_VLEN(type->info); 15565 15566 func_proto = btf_type_by_id(btf, type->type); 15567 if (unlikely(!func_proto || !btf_type_is_func_proto(func_proto))) 15568 /* btf_func_check() already verified it during BTF load */ 15569 goto err_free; 15570 ret_type = btf_type_skip_modifiers(btf, func_proto->type, NULL); 15571 scalar_return = 15572 btf_type_is_small_int(ret_type) || btf_is_any_enum(ret_type); 15573 if (i && !scalar_return && env->subprog_info[i].has_ld_abs) { 15574 verbose(env, "LD_ABS is only allowed in functions that return 'int'.\n"); 15575 goto err_free; 15576 } 15577 if (i && !scalar_return && env->subprog_info[i].has_tail_call) { 15578 verbose(env, "tail_call is only allowed in functions that return 'int'.\n"); 15579 goto err_free; 15580 } 15581 15582 prev_offset = krecord[i].insn_off; 15583 bpfptr_add(&urecord, urec_size); 15584 } 15585 15586 prog->aux->func_info = krecord; 15587 prog->aux->func_info_cnt = nfuncs; 15588 prog->aux->func_info_aux = info_aux; 15589 return 0; 15590 15591 err_free: 15592 kvfree(krecord); 15593 kfree(info_aux); 15594 return ret; 15595 } 15596 15597 static void adjust_btf_func(struct bpf_verifier_env *env) 15598 { 15599 struct bpf_prog_aux *aux = env->prog->aux; 15600 int i; 15601 15602 if (!aux->func_info) 15603 return; 15604 15605 for (i = 0; i < env->subprog_cnt; i++) 15606 aux->func_info[i].insn_off = env->subprog_info[i].start; 15607 } 15608 15609 #define MIN_BPF_LINEINFO_SIZE offsetofend(struct bpf_line_info, line_col) 15610 #define MAX_LINEINFO_REC_SIZE MAX_FUNCINFO_REC_SIZE 15611 15612 static int check_btf_line(struct bpf_verifier_env *env, 15613 const union bpf_attr *attr, 15614 bpfptr_t uattr) 15615 { 15616 u32 i, s, nr_linfo, ncopy, expected_size, rec_size, prev_offset = 0; 15617 struct bpf_subprog_info *sub; 15618 struct bpf_line_info *linfo; 15619 struct bpf_prog *prog; 15620 const struct btf *btf; 15621 bpfptr_t ulinfo; 15622 int err; 15623 15624 nr_linfo = attr->line_info_cnt; 15625 if (!nr_linfo) 15626 return 0; 15627 if (nr_linfo > INT_MAX / sizeof(struct bpf_line_info)) 15628 return -EINVAL; 15629 15630 rec_size = attr->line_info_rec_size; 15631 if (rec_size < MIN_BPF_LINEINFO_SIZE || 15632 rec_size > MAX_LINEINFO_REC_SIZE || 15633 rec_size & (sizeof(u32) - 1)) 15634 return -EINVAL; 15635 15636 /* Need to zero it in case the userspace may 15637 * pass in a smaller bpf_line_info object. 15638 */ 15639 linfo = kvcalloc(nr_linfo, sizeof(struct bpf_line_info), 15640 GFP_KERNEL | __GFP_NOWARN); 15641 if (!linfo) 15642 return -ENOMEM; 15643 15644 prog = env->prog; 15645 btf = prog->aux->btf; 15646 15647 s = 0; 15648 sub = env->subprog_info; 15649 ulinfo = make_bpfptr(attr->line_info, uattr.is_kernel); 15650 expected_size = sizeof(struct bpf_line_info); 15651 ncopy = min_t(u32, expected_size, rec_size); 15652 for (i = 0; i < nr_linfo; i++) { 15653 err = bpf_check_uarg_tail_zero(ulinfo, expected_size, rec_size); 15654 if (err) { 15655 if (err == -E2BIG) { 15656 verbose(env, "nonzero tailing record in line_info"); 15657 if (copy_to_bpfptr_offset(uattr, 15658 offsetof(union bpf_attr, line_info_rec_size), 15659 &expected_size, sizeof(expected_size))) 15660 err = -EFAULT; 15661 } 15662 goto err_free; 15663 } 15664 15665 if (copy_from_bpfptr(&linfo[i], ulinfo, ncopy)) { 15666 err = -EFAULT; 15667 goto err_free; 15668 } 15669 15670 /* 15671 * Check insn_off to ensure 15672 * 1) strictly increasing AND 15673 * 2) bounded by prog->len 15674 * 15675 * The linfo[0].insn_off == 0 check logically falls into 15676 * the later "missing bpf_line_info for func..." case 15677 * because the first linfo[0].insn_off must be the 15678 * first sub also and the first sub must have 15679 * subprog_info[0].start == 0. 15680 */ 15681 if ((i && linfo[i].insn_off <= prev_offset) || 15682 linfo[i].insn_off >= prog->len) { 15683 verbose(env, "Invalid line_info[%u].insn_off:%u (prev_offset:%u prog->len:%u)\n", 15684 i, linfo[i].insn_off, prev_offset, 15685 prog->len); 15686 err = -EINVAL; 15687 goto err_free; 15688 } 15689 15690 if (!prog->insnsi[linfo[i].insn_off].code) { 15691 verbose(env, 15692 "Invalid insn code at line_info[%u].insn_off\n", 15693 i); 15694 err = -EINVAL; 15695 goto err_free; 15696 } 15697 15698 if (!btf_name_by_offset(btf, linfo[i].line_off) || 15699 !btf_name_by_offset(btf, linfo[i].file_name_off)) { 15700 verbose(env, "Invalid line_info[%u].line_off or .file_name_off\n", i); 15701 err = -EINVAL; 15702 goto err_free; 15703 } 15704 15705 if (s != env->subprog_cnt) { 15706 if (linfo[i].insn_off == sub[s].start) { 15707 sub[s].linfo_idx = i; 15708 s++; 15709 } else if (sub[s].start < linfo[i].insn_off) { 15710 verbose(env, "missing bpf_line_info for func#%u\n", s); 15711 err = -EINVAL; 15712 goto err_free; 15713 } 15714 } 15715 15716 prev_offset = linfo[i].insn_off; 15717 bpfptr_add(&ulinfo, rec_size); 15718 } 15719 15720 if (s != env->subprog_cnt) { 15721 verbose(env, "missing bpf_line_info for %u funcs starting from func#%u\n", 15722 env->subprog_cnt - s, s); 15723 err = -EINVAL; 15724 goto err_free; 15725 } 15726 15727 prog->aux->linfo = linfo; 15728 prog->aux->nr_linfo = nr_linfo; 15729 15730 return 0; 15731 15732 err_free: 15733 kvfree(linfo); 15734 return err; 15735 } 15736 15737 #define MIN_CORE_RELO_SIZE sizeof(struct bpf_core_relo) 15738 #define MAX_CORE_RELO_SIZE MAX_FUNCINFO_REC_SIZE 15739 15740 static int check_core_relo(struct bpf_verifier_env *env, 15741 const union bpf_attr *attr, 15742 bpfptr_t uattr) 15743 { 15744 u32 i, nr_core_relo, ncopy, expected_size, rec_size; 15745 struct bpf_core_relo core_relo = {}; 15746 struct bpf_prog *prog = env->prog; 15747 const struct btf *btf = prog->aux->btf; 15748 struct bpf_core_ctx ctx = { 15749 .log = &env->log, 15750 .btf = btf, 15751 }; 15752 bpfptr_t u_core_relo; 15753 int err; 15754 15755 nr_core_relo = attr->core_relo_cnt; 15756 if (!nr_core_relo) 15757 return 0; 15758 if (nr_core_relo > INT_MAX / sizeof(struct bpf_core_relo)) 15759 return -EINVAL; 15760 15761 rec_size = attr->core_relo_rec_size; 15762 if (rec_size < MIN_CORE_RELO_SIZE || 15763 rec_size > MAX_CORE_RELO_SIZE || 15764 rec_size % sizeof(u32)) 15765 return -EINVAL; 15766 15767 u_core_relo = make_bpfptr(attr->core_relos, uattr.is_kernel); 15768 expected_size = sizeof(struct bpf_core_relo); 15769 ncopy = min_t(u32, expected_size, rec_size); 15770 15771 /* Unlike func_info and line_info, copy and apply each CO-RE 15772 * relocation record one at a time. 15773 */ 15774 for (i = 0; i < nr_core_relo; i++) { 15775 /* future proofing when sizeof(bpf_core_relo) changes */ 15776 err = bpf_check_uarg_tail_zero(u_core_relo, expected_size, rec_size); 15777 if (err) { 15778 if (err == -E2BIG) { 15779 verbose(env, "nonzero tailing record in core_relo"); 15780 if (copy_to_bpfptr_offset(uattr, 15781 offsetof(union bpf_attr, core_relo_rec_size), 15782 &expected_size, sizeof(expected_size))) 15783 err = -EFAULT; 15784 } 15785 break; 15786 } 15787 15788 if (copy_from_bpfptr(&core_relo, u_core_relo, ncopy)) { 15789 err = -EFAULT; 15790 break; 15791 } 15792 15793 if (core_relo.insn_off % 8 || core_relo.insn_off / 8 >= prog->len) { 15794 verbose(env, "Invalid core_relo[%u].insn_off:%u prog->len:%u\n", 15795 i, core_relo.insn_off, prog->len); 15796 err = -EINVAL; 15797 break; 15798 } 15799 15800 err = bpf_core_apply(&ctx, &core_relo, i, 15801 &prog->insnsi[core_relo.insn_off / 8]); 15802 if (err) 15803 break; 15804 bpfptr_add(&u_core_relo, rec_size); 15805 } 15806 return err; 15807 } 15808 15809 static int check_btf_info(struct bpf_verifier_env *env, 15810 const union bpf_attr *attr, 15811 bpfptr_t uattr) 15812 { 15813 struct btf *btf; 15814 int err; 15815 15816 if (!attr->func_info_cnt && !attr->line_info_cnt) { 15817 if (check_abnormal_return(env)) 15818 return -EINVAL; 15819 return 0; 15820 } 15821 15822 btf = btf_get_by_fd(attr->prog_btf_fd); 15823 if (IS_ERR(btf)) 15824 return PTR_ERR(btf); 15825 if (btf_is_kernel(btf)) { 15826 btf_put(btf); 15827 return -EACCES; 15828 } 15829 env->prog->aux->btf = btf; 15830 15831 err = check_btf_func(env, attr, uattr); 15832 if (err) 15833 return err; 15834 15835 err = check_btf_line(env, attr, uattr); 15836 if (err) 15837 return err; 15838 15839 err = check_core_relo(env, attr, uattr); 15840 if (err) 15841 return err; 15842 15843 return 0; 15844 } 15845 15846 /* check %cur's range satisfies %old's */ 15847 static bool range_within(struct bpf_reg_state *old, 15848 struct bpf_reg_state *cur) 15849 { 15850 return old->umin_value <= cur->umin_value && 15851 old->umax_value >= cur->umax_value && 15852 old->smin_value <= cur->smin_value && 15853 old->smax_value >= cur->smax_value && 15854 old->u32_min_value <= cur->u32_min_value && 15855 old->u32_max_value >= cur->u32_max_value && 15856 old->s32_min_value <= cur->s32_min_value && 15857 old->s32_max_value >= cur->s32_max_value; 15858 } 15859 15860 /* If in the old state two registers had the same id, then they need to have 15861 * the same id in the new state as well. But that id could be different from 15862 * the old state, so we need to track the mapping from old to new ids. 15863 * Once we have seen that, say, a reg with old id 5 had new id 9, any subsequent 15864 * regs with old id 5 must also have new id 9 for the new state to be safe. But 15865 * regs with a different old id could still have new id 9, we don't care about 15866 * that. 15867 * So we look through our idmap to see if this old id has been seen before. If 15868 * so, we require the new id to match; otherwise, we add the id pair to the map. 15869 */ 15870 static bool check_ids(u32 old_id, u32 cur_id, struct bpf_idmap *idmap) 15871 { 15872 struct bpf_id_pair *map = idmap->map; 15873 unsigned int i; 15874 15875 /* either both IDs should be set or both should be zero */ 15876 if (!!old_id != !!cur_id) 15877 return false; 15878 15879 if (old_id == 0) /* cur_id == 0 as well */ 15880 return true; 15881 15882 for (i = 0; i < BPF_ID_MAP_SIZE; i++) { 15883 if (!map[i].old) { 15884 /* Reached an empty slot; haven't seen this id before */ 15885 map[i].old = old_id; 15886 map[i].cur = cur_id; 15887 return true; 15888 } 15889 if (map[i].old == old_id) 15890 return map[i].cur == cur_id; 15891 if (map[i].cur == cur_id) 15892 return false; 15893 } 15894 /* We ran out of idmap slots, which should be impossible */ 15895 WARN_ON_ONCE(1); 15896 return false; 15897 } 15898 15899 /* Similar to check_ids(), but allocate a unique temporary ID 15900 * for 'old_id' or 'cur_id' of zero. 15901 * This makes pairs like '0 vs unique ID', 'unique ID vs 0' valid. 15902 */ 15903 static bool check_scalar_ids(u32 old_id, u32 cur_id, struct bpf_idmap *idmap) 15904 { 15905 old_id = old_id ? old_id : ++idmap->tmp_id_gen; 15906 cur_id = cur_id ? cur_id : ++idmap->tmp_id_gen; 15907 15908 return check_ids(old_id, cur_id, idmap); 15909 } 15910 15911 static void clean_func_state(struct bpf_verifier_env *env, 15912 struct bpf_func_state *st) 15913 { 15914 enum bpf_reg_liveness live; 15915 int i, j; 15916 15917 for (i = 0; i < BPF_REG_FP; i++) { 15918 live = st->regs[i].live; 15919 /* liveness must not touch this register anymore */ 15920 st->regs[i].live |= REG_LIVE_DONE; 15921 if (!(live & REG_LIVE_READ)) 15922 /* since the register is unused, clear its state 15923 * to make further comparison simpler 15924 */ 15925 __mark_reg_not_init(env, &st->regs[i]); 15926 } 15927 15928 for (i = 0; i < st->allocated_stack / BPF_REG_SIZE; i++) { 15929 live = st->stack[i].spilled_ptr.live; 15930 /* liveness must not touch this stack slot anymore */ 15931 st->stack[i].spilled_ptr.live |= REG_LIVE_DONE; 15932 if (!(live & REG_LIVE_READ)) { 15933 __mark_reg_not_init(env, &st->stack[i].spilled_ptr); 15934 for (j = 0; j < BPF_REG_SIZE; j++) 15935 st->stack[i].slot_type[j] = STACK_INVALID; 15936 } 15937 } 15938 } 15939 15940 static void clean_verifier_state(struct bpf_verifier_env *env, 15941 struct bpf_verifier_state *st) 15942 { 15943 int i; 15944 15945 if (st->frame[0]->regs[0].live & REG_LIVE_DONE) 15946 /* all regs in this state in all frames were already marked */ 15947 return; 15948 15949 for (i = 0; i <= st->curframe; i++) 15950 clean_func_state(env, st->frame[i]); 15951 } 15952 15953 /* the parentage chains form a tree. 15954 * the verifier states are added to state lists at given insn and 15955 * pushed into state stack for future exploration. 15956 * when the verifier reaches bpf_exit insn some of the verifer states 15957 * stored in the state lists have their final liveness state already, 15958 * but a lot of states will get revised from liveness point of view when 15959 * the verifier explores other branches. 15960 * Example: 15961 * 1: r0 = 1 15962 * 2: if r1 == 100 goto pc+1 15963 * 3: r0 = 2 15964 * 4: exit 15965 * when the verifier reaches exit insn the register r0 in the state list of 15966 * insn 2 will be seen as !REG_LIVE_READ. Then the verifier pops the other_branch 15967 * of insn 2 and goes exploring further. At the insn 4 it will walk the 15968 * parentage chain from insn 4 into insn 2 and will mark r0 as REG_LIVE_READ. 15969 * 15970 * Since the verifier pushes the branch states as it sees them while exploring 15971 * the program the condition of walking the branch instruction for the second 15972 * time means that all states below this branch were already explored and 15973 * their final liveness marks are already propagated. 15974 * Hence when the verifier completes the search of state list in is_state_visited() 15975 * we can call this clean_live_states() function to mark all liveness states 15976 * as REG_LIVE_DONE to indicate that 'parent' pointers of 'struct bpf_reg_state' 15977 * will not be used. 15978 * This function also clears the registers and stack for states that !READ 15979 * to simplify state merging. 15980 * 15981 * Important note here that walking the same branch instruction in the callee 15982 * doesn't meant that the states are DONE. The verifier has to compare 15983 * the callsites 15984 */ 15985 static void clean_live_states(struct bpf_verifier_env *env, int insn, 15986 struct bpf_verifier_state *cur) 15987 { 15988 struct bpf_verifier_state_list *sl; 15989 15990 sl = *explored_state(env, insn); 15991 while (sl) { 15992 if (sl->state.branches) 15993 goto next; 15994 if (sl->state.insn_idx != insn || 15995 !same_callsites(&sl->state, cur)) 15996 goto next; 15997 clean_verifier_state(env, &sl->state); 15998 next: 15999 sl = sl->next; 16000 } 16001 } 16002 16003 static bool regs_exact(const struct bpf_reg_state *rold, 16004 const struct bpf_reg_state *rcur, 16005 struct bpf_idmap *idmap) 16006 { 16007 return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 && 16008 check_ids(rold->id, rcur->id, idmap) && 16009 check_ids(rold->ref_obj_id, rcur->ref_obj_id, idmap); 16010 } 16011 16012 /* Returns true if (rold safe implies rcur safe) */ 16013 static bool regsafe(struct bpf_verifier_env *env, struct bpf_reg_state *rold, 16014 struct bpf_reg_state *rcur, struct bpf_idmap *idmap, bool exact) 16015 { 16016 if (exact) 16017 return regs_exact(rold, rcur, idmap); 16018 16019 if (!(rold->live & REG_LIVE_READ)) 16020 /* explored state didn't use this */ 16021 return true; 16022 if (rold->type == NOT_INIT) 16023 /* explored state can't have used this */ 16024 return true; 16025 if (rcur->type == NOT_INIT) 16026 return false; 16027 16028 /* Enforce that register types have to match exactly, including their 16029 * modifiers (like PTR_MAYBE_NULL, MEM_RDONLY, etc), as a general 16030 * rule. 16031 * 16032 * One can make a point that using a pointer register as unbounded 16033 * SCALAR would be technically acceptable, but this could lead to 16034 * pointer leaks because scalars are allowed to leak while pointers 16035 * are not. We could make this safe in special cases if root is 16036 * calling us, but it's probably not worth the hassle. 16037 * 16038 * Also, register types that are *not* MAYBE_NULL could technically be 16039 * safe to use as their MAYBE_NULL variants (e.g., PTR_TO_MAP_VALUE 16040 * is safe to be used as PTR_TO_MAP_VALUE_OR_NULL, provided both point 16041 * to the same map). 16042 * However, if the old MAYBE_NULL register then got NULL checked, 16043 * doing so could have affected others with the same id, and we can't 16044 * check for that because we lost the id when we converted to 16045 * a non-MAYBE_NULL variant. 16046 * So, as a general rule we don't allow mixing MAYBE_NULL and 16047 * non-MAYBE_NULL registers as well. 16048 */ 16049 if (rold->type != rcur->type) 16050 return false; 16051 16052 switch (base_type(rold->type)) { 16053 case SCALAR_VALUE: 16054 if (env->explore_alu_limits) { 16055 /* explore_alu_limits disables tnum_in() and range_within() 16056 * logic and requires everything to be strict 16057 */ 16058 return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 && 16059 check_scalar_ids(rold->id, rcur->id, idmap); 16060 } 16061 if (!rold->precise) 16062 return true; 16063 /* Why check_ids() for scalar registers? 16064 * 16065 * Consider the following BPF code: 16066 * 1: r6 = ... unbound scalar, ID=a ... 16067 * 2: r7 = ... unbound scalar, ID=b ... 16068 * 3: if (r6 > r7) goto +1 16069 * 4: r6 = r7 16070 * 5: if (r6 > X) goto ... 16071 * 6: ... memory operation using r7 ... 16072 * 16073 * First verification path is [1-6]: 16074 * - at (4) same bpf_reg_state::id (b) would be assigned to r6 and r7; 16075 * - at (5) r6 would be marked <= X, find_equal_scalars() would also mark 16076 * r7 <= X, because r6 and r7 share same id. 16077 * Next verification path is [1-4, 6]. 16078 * 16079 * Instruction (6) would be reached in two states: 16080 * I. r6{.id=b}, r7{.id=b} via path 1-6; 16081 * II. r6{.id=a}, r7{.id=b} via path 1-4, 6. 16082 * 16083 * Use check_ids() to distinguish these states. 16084 * --- 16085 * Also verify that new value satisfies old value range knowledge. 16086 */ 16087 return range_within(rold, rcur) && 16088 tnum_in(rold->var_off, rcur->var_off) && 16089 check_scalar_ids(rold->id, rcur->id, idmap); 16090 case PTR_TO_MAP_KEY: 16091 case PTR_TO_MAP_VALUE: 16092 case PTR_TO_MEM: 16093 case PTR_TO_BUF: 16094 case PTR_TO_TP_BUFFER: 16095 /* If the new min/max/var_off satisfy the old ones and 16096 * everything else matches, we are OK. 16097 */ 16098 return memcmp(rold, rcur, offsetof(struct bpf_reg_state, var_off)) == 0 && 16099 range_within(rold, rcur) && 16100 tnum_in(rold->var_off, rcur->var_off) && 16101 check_ids(rold->id, rcur->id, idmap) && 16102 check_ids(rold->ref_obj_id, rcur->ref_obj_id, idmap); 16103 case PTR_TO_PACKET_META: 16104 case PTR_TO_PACKET: 16105 /* We must have at least as much range as the old ptr 16106 * did, so that any accesses which were safe before are 16107 * still safe. This is true even if old range < old off, 16108 * since someone could have accessed through (ptr - k), or 16109 * even done ptr -= k in a register, to get a safe access. 16110 */ 16111 if (rold->range > rcur->range) 16112 return false; 16113 /* If the offsets don't match, we can't trust our alignment; 16114 * nor can we be sure that we won't fall out of range. 16115 */ 16116 if (rold->off != rcur->off) 16117 return false; 16118 /* id relations must be preserved */ 16119 if (!check_ids(rold->id, rcur->id, idmap)) 16120 return false; 16121 /* new val must satisfy old val knowledge */ 16122 return range_within(rold, rcur) && 16123 tnum_in(rold->var_off, rcur->var_off); 16124 case PTR_TO_STACK: 16125 /* two stack pointers are equal only if they're pointing to 16126 * the same stack frame, since fp-8 in foo != fp-8 in bar 16127 */ 16128 return regs_exact(rold, rcur, idmap) && rold->frameno == rcur->frameno; 16129 default: 16130 return regs_exact(rold, rcur, idmap); 16131 } 16132 } 16133 16134 static bool stacksafe(struct bpf_verifier_env *env, struct bpf_func_state *old, 16135 struct bpf_func_state *cur, struct bpf_idmap *idmap, bool exact) 16136 { 16137 int i, spi; 16138 16139 /* walk slots of the explored stack and ignore any additional 16140 * slots in the current stack, since explored(safe) state 16141 * didn't use them 16142 */ 16143 for (i = 0; i < old->allocated_stack; i++) { 16144 struct bpf_reg_state *old_reg, *cur_reg; 16145 16146 spi = i / BPF_REG_SIZE; 16147 16148 if (exact && 16149 (i >= cur->allocated_stack || 16150 old->stack[spi].slot_type[i % BPF_REG_SIZE] != 16151 cur->stack[spi].slot_type[i % BPF_REG_SIZE])) 16152 return false; 16153 16154 if (!(old->stack[spi].spilled_ptr.live & REG_LIVE_READ) && !exact) { 16155 i += BPF_REG_SIZE - 1; 16156 /* explored state didn't use this */ 16157 continue; 16158 } 16159 16160 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_INVALID) 16161 continue; 16162 16163 if (env->allow_uninit_stack && 16164 old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC) 16165 continue; 16166 16167 /* explored stack has more populated slots than current stack 16168 * and these slots were used 16169 */ 16170 if (i >= cur->allocated_stack) 16171 return false; 16172 16173 /* if old state was safe with misc data in the stack 16174 * it will be safe with zero-initialized stack. 16175 * The opposite is not true 16176 */ 16177 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC && 16178 cur->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_ZERO) 16179 continue; 16180 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] != 16181 cur->stack[spi].slot_type[i % BPF_REG_SIZE]) 16182 /* Ex: old explored (safe) state has STACK_SPILL in 16183 * this stack slot, but current has STACK_MISC -> 16184 * this verifier states are not equivalent, 16185 * return false to continue verification of this path 16186 */ 16187 return false; 16188 if (i % BPF_REG_SIZE != BPF_REG_SIZE - 1) 16189 continue; 16190 /* Both old and cur are having same slot_type */ 16191 switch (old->stack[spi].slot_type[BPF_REG_SIZE - 1]) { 16192 case STACK_SPILL: 16193 /* when explored and current stack slot are both storing 16194 * spilled registers, check that stored pointers types 16195 * are the same as well. 16196 * Ex: explored safe path could have stored 16197 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -8} 16198 * but current path has stored: 16199 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -16} 16200 * such verifier states are not equivalent. 16201 * return false to continue verification of this path 16202 */ 16203 if (!regsafe(env, &old->stack[spi].spilled_ptr, 16204 &cur->stack[spi].spilled_ptr, idmap, exact)) 16205 return false; 16206 break; 16207 case STACK_DYNPTR: 16208 old_reg = &old->stack[spi].spilled_ptr; 16209 cur_reg = &cur->stack[spi].spilled_ptr; 16210 if (old_reg->dynptr.type != cur_reg->dynptr.type || 16211 old_reg->dynptr.first_slot != cur_reg->dynptr.first_slot || 16212 !check_ids(old_reg->ref_obj_id, cur_reg->ref_obj_id, idmap)) 16213 return false; 16214 break; 16215 case STACK_ITER: 16216 old_reg = &old->stack[spi].spilled_ptr; 16217 cur_reg = &cur->stack[spi].spilled_ptr; 16218 /* iter.depth is not compared between states as it 16219 * doesn't matter for correctness and would otherwise 16220 * prevent convergence; we maintain it only to prevent 16221 * infinite loop check triggering, see 16222 * iter_active_depths_differ() 16223 */ 16224 if (old_reg->iter.btf != cur_reg->iter.btf || 16225 old_reg->iter.btf_id != cur_reg->iter.btf_id || 16226 old_reg->iter.state != cur_reg->iter.state || 16227 /* ignore {old_reg,cur_reg}->iter.depth, see above */ 16228 !check_ids(old_reg->ref_obj_id, cur_reg->ref_obj_id, idmap)) 16229 return false; 16230 break; 16231 case STACK_MISC: 16232 case STACK_ZERO: 16233 case STACK_INVALID: 16234 continue; 16235 /* Ensure that new unhandled slot types return false by default */ 16236 default: 16237 return false; 16238 } 16239 } 16240 return true; 16241 } 16242 16243 static bool refsafe(struct bpf_func_state *old, struct bpf_func_state *cur, 16244 struct bpf_idmap *idmap) 16245 { 16246 int i; 16247 16248 if (old->acquired_refs != cur->acquired_refs) 16249 return false; 16250 16251 for (i = 0; i < old->acquired_refs; i++) { 16252 if (!check_ids(old->refs[i].id, cur->refs[i].id, idmap)) 16253 return false; 16254 } 16255 16256 return true; 16257 } 16258 16259 /* compare two verifier states 16260 * 16261 * all states stored in state_list are known to be valid, since 16262 * verifier reached 'bpf_exit' instruction through them 16263 * 16264 * this function is called when verifier exploring different branches of 16265 * execution popped from the state stack. If it sees an old state that has 16266 * more strict register state and more strict stack state then this execution 16267 * branch doesn't need to be explored further, since verifier already 16268 * concluded that more strict state leads to valid finish. 16269 * 16270 * Therefore two states are equivalent if register state is more conservative 16271 * and explored stack state is more conservative than the current one. 16272 * Example: 16273 * explored current 16274 * (slot1=INV slot2=MISC) == (slot1=MISC slot2=MISC) 16275 * (slot1=MISC slot2=MISC) != (slot1=INV slot2=MISC) 16276 * 16277 * In other words if current stack state (one being explored) has more 16278 * valid slots than old one that already passed validation, it means 16279 * the verifier can stop exploring and conclude that current state is valid too 16280 * 16281 * Similarly with registers. If explored state has register type as invalid 16282 * whereas register type in current state is meaningful, it means that 16283 * the current state will reach 'bpf_exit' instruction safely 16284 */ 16285 static bool func_states_equal(struct bpf_verifier_env *env, struct bpf_func_state *old, 16286 struct bpf_func_state *cur, bool exact) 16287 { 16288 int i; 16289 16290 if (old->callback_depth > cur->callback_depth) 16291 return false; 16292 16293 for (i = 0; i < MAX_BPF_REG; i++) 16294 if (!regsafe(env, &old->regs[i], &cur->regs[i], 16295 &env->idmap_scratch, exact)) 16296 return false; 16297 16298 if (!stacksafe(env, old, cur, &env->idmap_scratch, exact)) 16299 return false; 16300 16301 if (!refsafe(old, cur, &env->idmap_scratch)) 16302 return false; 16303 16304 return true; 16305 } 16306 16307 static void reset_idmap_scratch(struct bpf_verifier_env *env) 16308 { 16309 env->idmap_scratch.tmp_id_gen = env->id_gen; 16310 memset(&env->idmap_scratch.map, 0, sizeof(env->idmap_scratch.map)); 16311 } 16312 16313 static bool states_equal(struct bpf_verifier_env *env, 16314 struct bpf_verifier_state *old, 16315 struct bpf_verifier_state *cur, 16316 bool exact) 16317 { 16318 int i; 16319 16320 if (old->curframe != cur->curframe) 16321 return false; 16322 16323 reset_idmap_scratch(env); 16324 16325 /* Verification state from speculative execution simulation 16326 * must never prune a non-speculative execution one. 16327 */ 16328 if (old->speculative && !cur->speculative) 16329 return false; 16330 16331 if (old->active_lock.ptr != cur->active_lock.ptr) 16332 return false; 16333 16334 /* Old and cur active_lock's have to be either both present 16335 * or both absent. 16336 */ 16337 if (!!old->active_lock.id != !!cur->active_lock.id) 16338 return false; 16339 16340 if (old->active_lock.id && 16341 !check_ids(old->active_lock.id, cur->active_lock.id, &env->idmap_scratch)) 16342 return false; 16343 16344 if (old->active_rcu_lock != cur->active_rcu_lock) 16345 return false; 16346 16347 /* for states to be equal callsites have to be the same 16348 * and all frame states need to be equivalent 16349 */ 16350 for (i = 0; i <= old->curframe; i++) { 16351 if (old->frame[i]->callsite != cur->frame[i]->callsite) 16352 return false; 16353 if (!func_states_equal(env, old->frame[i], cur->frame[i], exact)) 16354 return false; 16355 } 16356 return true; 16357 } 16358 16359 /* Return 0 if no propagation happened. Return negative error code if error 16360 * happened. Otherwise, return the propagated bit. 16361 */ 16362 static int propagate_liveness_reg(struct bpf_verifier_env *env, 16363 struct bpf_reg_state *reg, 16364 struct bpf_reg_state *parent_reg) 16365 { 16366 u8 parent_flag = parent_reg->live & REG_LIVE_READ; 16367 u8 flag = reg->live & REG_LIVE_READ; 16368 int err; 16369 16370 /* When comes here, read flags of PARENT_REG or REG could be any of 16371 * REG_LIVE_READ64, REG_LIVE_READ32, REG_LIVE_NONE. There is no need 16372 * of propagation if PARENT_REG has strongest REG_LIVE_READ64. 16373 */ 16374 if (parent_flag == REG_LIVE_READ64 || 16375 /* Or if there is no read flag from REG. */ 16376 !flag || 16377 /* Or if the read flag from REG is the same as PARENT_REG. */ 16378 parent_flag == flag) 16379 return 0; 16380 16381 err = mark_reg_read(env, reg, parent_reg, flag); 16382 if (err) 16383 return err; 16384 16385 return flag; 16386 } 16387 16388 /* A write screens off any subsequent reads; but write marks come from the 16389 * straight-line code between a state and its parent. When we arrive at an 16390 * equivalent state (jump target or such) we didn't arrive by the straight-line 16391 * code, so read marks in the state must propagate to the parent regardless 16392 * of the state's write marks. That's what 'parent == state->parent' comparison 16393 * in mark_reg_read() is for. 16394 */ 16395 static int propagate_liveness(struct bpf_verifier_env *env, 16396 const struct bpf_verifier_state *vstate, 16397 struct bpf_verifier_state *vparent) 16398 { 16399 struct bpf_reg_state *state_reg, *parent_reg; 16400 struct bpf_func_state *state, *parent; 16401 int i, frame, err = 0; 16402 16403 if (vparent->curframe != vstate->curframe) { 16404 WARN(1, "propagate_live: parent frame %d current frame %d\n", 16405 vparent->curframe, vstate->curframe); 16406 return -EFAULT; 16407 } 16408 /* Propagate read liveness of registers... */ 16409 BUILD_BUG_ON(BPF_REG_FP + 1 != MAX_BPF_REG); 16410 for (frame = 0; frame <= vstate->curframe; frame++) { 16411 parent = vparent->frame[frame]; 16412 state = vstate->frame[frame]; 16413 parent_reg = parent->regs; 16414 state_reg = state->regs; 16415 /* We don't need to worry about FP liveness, it's read-only */ 16416 for (i = frame < vstate->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++) { 16417 err = propagate_liveness_reg(env, &state_reg[i], 16418 &parent_reg[i]); 16419 if (err < 0) 16420 return err; 16421 if (err == REG_LIVE_READ64) 16422 mark_insn_zext(env, &parent_reg[i]); 16423 } 16424 16425 /* Propagate stack slots. */ 16426 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE && 16427 i < parent->allocated_stack / BPF_REG_SIZE; i++) { 16428 parent_reg = &parent->stack[i].spilled_ptr; 16429 state_reg = &state->stack[i].spilled_ptr; 16430 err = propagate_liveness_reg(env, state_reg, 16431 parent_reg); 16432 if (err < 0) 16433 return err; 16434 } 16435 } 16436 return 0; 16437 } 16438 16439 /* find precise scalars in the previous equivalent state and 16440 * propagate them into the current state 16441 */ 16442 static int propagate_precision(struct bpf_verifier_env *env, 16443 const struct bpf_verifier_state *old) 16444 { 16445 struct bpf_reg_state *state_reg; 16446 struct bpf_func_state *state; 16447 int i, err = 0, fr; 16448 bool first; 16449 16450 for (fr = old->curframe; fr >= 0; fr--) { 16451 state = old->frame[fr]; 16452 state_reg = state->regs; 16453 first = true; 16454 for (i = 0; i < BPF_REG_FP; i++, state_reg++) { 16455 if (state_reg->type != SCALAR_VALUE || 16456 !state_reg->precise || 16457 !(state_reg->live & REG_LIVE_READ)) 16458 continue; 16459 if (env->log.level & BPF_LOG_LEVEL2) { 16460 if (first) 16461 verbose(env, "frame %d: propagating r%d", fr, i); 16462 else 16463 verbose(env, ",r%d", i); 16464 } 16465 bt_set_frame_reg(&env->bt, fr, i); 16466 first = false; 16467 } 16468 16469 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) { 16470 if (!is_spilled_reg(&state->stack[i])) 16471 continue; 16472 state_reg = &state->stack[i].spilled_ptr; 16473 if (state_reg->type != SCALAR_VALUE || 16474 !state_reg->precise || 16475 !(state_reg->live & REG_LIVE_READ)) 16476 continue; 16477 if (env->log.level & BPF_LOG_LEVEL2) { 16478 if (first) 16479 verbose(env, "frame %d: propagating fp%d", 16480 fr, (-i - 1) * BPF_REG_SIZE); 16481 else 16482 verbose(env, ",fp%d", (-i - 1) * BPF_REG_SIZE); 16483 } 16484 bt_set_frame_slot(&env->bt, fr, i); 16485 first = false; 16486 } 16487 if (!first) 16488 verbose(env, "\n"); 16489 } 16490 16491 err = mark_chain_precision_batch(env); 16492 if (err < 0) 16493 return err; 16494 16495 return 0; 16496 } 16497 16498 static bool states_maybe_looping(struct bpf_verifier_state *old, 16499 struct bpf_verifier_state *cur) 16500 { 16501 struct bpf_func_state *fold, *fcur; 16502 int i, fr = cur->curframe; 16503 16504 if (old->curframe != fr) 16505 return false; 16506 16507 fold = old->frame[fr]; 16508 fcur = cur->frame[fr]; 16509 for (i = 0; i < MAX_BPF_REG; i++) 16510 if (memcmp(&fold->regs[i], &fcur->regs[i], 16511 offsetof(struct bpf_reg_state, parent))) 16512 return false; 16513 return true; 16514 } 16515 16516 static bool is_iter_next_insn(struct bpf_verifier_env *env, int insn_idx) 16517 { 16518 return env->insn_aux_data[insn_idx].is_iter_next; 16519 } 16520 16521 /* is_state_visited() handles iter_next() (see process_iter_next_call() for 16522 * terminology) calls specially: as opposed to bounded BPF loops, it *expects* 16523 * states to match, which otherwise would look like an infinite loop. So while 16524 * iter_next() calls are taken care of, we still need to be careful and 16525 * prevent erroneous and too eager declaration of "ininite loop", when 16526 * iterators are involved. 16527 * 16528 * Here's a situation in pseudo-BPF assembly form: 16529 * 16530 * 0: again: ; set up iter_next() call args 16531 * 1: r1 = &it ; <CHECKPOINT HERE> 16532 * 2: call bpf_iter_num_next ; this is iter_next() call 16533 * 3: if r0 == 0 goto done 16534 * 4: ... something useful here ... 16535 * 5: goto again ; another iteration 16536 * 6: done: 16537 * 7: r1 = &it 16538 * 8: call bpf_iter_num_destroy ; clean up iter state 16539 * 9: exit 16540 * 16541 * This is a typical loop. Let's assume that we have a prune point at 1:, 16542 * before we get to `call bpf_iter_num_next` (e.g., because of that `goto 16543 * again`, assuming other heuristics don't get in a way). 16544 * 16545 * When we first time come to 1:, let's say we have some state X. We proceed 16546 * to 2:, fork states, enqueue ACTIVE, validate NULL case successfully, exit. 16547 * Now we come back to validate that forked ACTIVE state. We proceed through 16548 * 3-5, come to goto, jump to 1:. Let's assume our state didn't change, so we 16549 * are converging. But the problem is that we don't know that yet, as this 16550 * convergence has to happen at iter_next() call site only. So if nothing is 16551 * done, at 1: verifier will use bounded loop logic and declare infinite 16552 * looping (and would be *technically* correct, if not for iterator's 16553 * "eventual sticky NULL" contract, see process_iter_next_call()). But we 16554 * don't want that. So what we do in process_iter_next_call() when we go on 16555 * another ACTIVE iteration, we bump slot->iter.depth, to mark that it's 16556 * a different iteration. So when we suspect an infinite loop, we additionally 16557 * check if any of the *ACTIVE* iterator states depths differ. If yes, we 16558 * pretend we are not looping and wait for next iter_next() call. 16559 * 16560 * This only applies to ACTIVE state. In DRAINED state we don't expect to 16561 * loop, because that would actually mean infinite loop, as DRAINED state is 16562 * "sticky", and so we'll keep returning into the same instruction with the 16563 * same state (at least in one of possible code paths). 16564 * 16565 * This approach allows to keep infinite loop heuristic even in the face of 16566 * active iterator. E.g., C snippet below is and will be detected as 16567 * inifintely looping: 16568 * 16569 * struct bpf_iter_num it; 16570 * int *p, x; 16571 * 16572 * bpf_iter_num_new(&it, 0, 10); 16573 * while ((p = bpf_iter_num_next(&t))) { 16574 * x = p; 16575 * while (x--) {} // <<-- infinite loop here 16576 * } 16577 * 16578 */ 16579 static bool iter_active_depths_differ(struct bpf_verifier_state *old, struct bpf_verifier_state *cur) 16580 { 16581 struct bpf_reg_state *slot, *cur_slot; 16582 struct bpf_func_state *state; 16583 int i, fr; 16584 16585 for (fr = old->curframe; fr >= 0; fr--) { 16586 state = old->frame[fr]; 16587 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) { 16588 if (state->stack[i].slot_type[0] != STACK_ITER) 16589 continue; 16590 16591 slot = &state->stack[i].spilled_ptr; 16592 if (slot->iter.state != BPF_ITER_STATE_ACTIVE) 16593 continue; 16594 16595 cur_slot = &cur->frame[fr]->stack[i].spilled_ptr; 16596 if (cur_slot->iter.depth != slot->iter.depth) 16597 return true; 16598 } 16599 } 16600 return false; 16601 } 16602 16603 static int is_state_visited(struct bpf_verifier_env *env, int insn_idx) 16604 { 16605 struct bpf_verifier_state_list *new_sl; 16606 struct bpf_verifier_state_list *sl, **pprev; 16607 struct bpf_verifier_state *cur = env->cur_state, *new, *loop_entry; 16608 int i, j, n, err, states_cnt = 0; 16609 bool force_new_state, add_new_state, force_exact; 16610 16611 force_new_state = env->test_state_freq || is_force_checkpoint(env, insn_idx) || 16612 /* Avoid accumulating infinitely long jmp history */ 16613 cur->jmp_history_cnt > 40; 16614 16615 /* bpf progs typically have pruning point every 4 instructions 16616 * http://vger.kernel.org/bpfconf2019.html#session-1 16617 * Do not add new state for future pruning if the verifier hasn't seen 16618 * at least 2 jumps and at least 8 instructions. 16619 * This heuristics helps decrease 'total_states' and 'peak_states' metric. 16620 * In tests that amounts to up to 50% reduction into total verifier 16621 * memory consumption and 20% verifier time speedup. 16622 */ 16623 add_new_state = force_new_state; 16624 if (env->jmps_processed - env->prev_jmps_processed >= 2 && 16625 env->insn_processed - env->prev_insn_processed >= 8) 16626 add_new_state = true; 16627 16628 pprev = explored_state(env, insn_idx); 16629 sl = *pprev; 16630 16631 clean_live_states(env, insn_idx, cur); 16632 16633 while (sl) { 16634 states_cnt++; 16635 if (sl->state.insn_idx != insn_idx) 16636 goto next; 16637 16638 if (sl->state.branches) { 16639 struct bpf_func_state *frame = sl->state.frame[sl->state.curframe]; 16640 16641 if (frame->in_async_callback_fn && 16642 frame->async_entry_cnt != cur->frame[cur->curframe]->async_entry_cnt) { 16643 /* Different async_entry_cnt means that the verifier is 16644 * processing another entry into async callback. 16645 * Seeing the same state is not an indication of infinite 16646 * loop or infinite recursion. 16647 * But finding the same state doesn't mean that it's safe 16648 * to stop processing the current state. The previous state 16649 * hasn't yet reached bpf_exit, since state.branches > 0. 16650 * Checking in_async_callback_fn alone is not enough either. 16651 * Since the verifier still needs to catch infinite loops 16652 * inside async callbacks. 16653 */ 16654 goto skip_inf_loop_check; 16655 } 16656 /* BPF open-coded iterators loop detection is special. 16657 * states_maybe_looping() logic is too simplistic in detecting 16658 * states that *might* be equivalent, because it doesn't know 16659 * about ID remapping, so don't even perform it. 16660 * See process_iter_next_call() and iter_active_depths_differ() 16661 * for overview of the logic. When current and one of parent 16662 * states are detected as equivalent, it's a good thing: we prove 16663 * convergence and can stop simulating further iterations. 16664 * It's safe to assume that iterator loop will finish, taking into 16665 * account iter_next() contract of eventually returning 16666 * sticky NULL result. 16667 * 16668 * Note, that states have to be compared exactly in this case because 16669 * read and precision marks might not be finalized inside the loop. 16670 * E.g. as in the program below: 16671 * 16672 * 1. r7 = -16 16673 * 2. r6 = bpf_get_prandom_u32() 16674 * 3. while (bpf_iter_num_next(&fp[-8])) { 16675 * 4. if (r6 != 42) { 16676 * 5. r7 = -32 16677 * 6. r6 = bpf_get_prandom_u32() 16678 * 7. continue 16679 * 8. } 16680 * 9. r0 = r10 16681 * 10. r0 += r7 16682 * 11. r8 = *(u64 *)(r0 + 0) 16683 * 12. r6 = bpf_get_prandom_u32() 16684 * 13. } 16685 * 16686 * Here verifier would first visit path 1-3, create a checkpoint at 3 16687 * with r7=-16, continue to 4-7,3. Existing checkpoint at 3 does 16688 * not have read or precision mark for r7 yet, thus inexact states 16689 * comparison would discard current state with r7=-32 16690 * => unsafe memory access at 11 would not be caught. 16691 */ 16692 if (is_iter_next_insn(env, insn_idx)) { 16693 if (states_equal(env, &sl->state, cur, true)) { 16694 struct bpf_func_state *cur_frame; 16695 struct bpf_reg_state *iter_state, *iter_reg; 16696 int spi; 16697 16698 cur_frame = cur->frame[cur->curframe]; 16699 /* btf_check_iter_kfuncs() enforces that 16700 * iter state pointer is always the first arg 16701 */ 16702 iter_reg = &cur_frame->regs[BPF_REG_1]; 16703 /* current state is valid due to states_equal(), 16704 * so we can assume valid iter and reg state, 16705 * no need for extra (re-)validations 16706 */ 16707 spi = __get_spi(iter_reg->off + iter_reg->var_off.value); 16708 iter_state = &func(env, iter_reg)->stack[spi].spilled_ptr; 16709 if (iter_state->iter.state == BPF_ITER_STATE_ACTIVE) { 16710 update_loop_entry(cur, &sl->state); 16711 goto hit; 16712 } 16713 } 16714 goto skip_inf_loop_check; 16715 } 16716 if (calls_callback(env, insn_idx)) { 16717 if (states_equal(env, &sl->state, cur, true)) 16718 goto hit; 16719 goto skip_inf_loop_check; 16720 } 16721 /* attempt to detect infinite loop to avoid unnecessary doomed work */ 16722 if (states_maybe_looping(&sl->state, cur) && 16723 states_equal(env, &sl->state, cur, false) && 16724 !iter_active_depths_differ(&sl->state, cur) && 16725 sl->state.callback_unroll_depth == cur->callback_unroll_depth) { 16726 verbose_linfo(env, insn_idx, "; "); 16727 verbose(env, "infinite loop detected at insn %d\n", insn_idx); 16728 verbose(env, "cur state:"); 16729 print_verifier_state(env, cur->frame[cur->curframe], true); 16730 verbose(env, "old state:"); 16731 print_verifier_state(env, sl->state.frame[cur->curframe], true); 16732 return -EINVAL; 16733 } 16734 /* if the verifier is processing a loop, avoid adding new state 16735 * too often, since different loop iterations have distinct 16736 * states and may not help future pruning. 16737 * This threshold shouldn't be too low to make sure that 16738 * a loop with large bound will be rejected quickly. 16739 * The most abusive loop will be: 16740 * r1 += 1 16741 * if r1 < 1000000 goto pc-2 16742 * 1M insn_procssed limit / 100 == 10k peak states. 16743 * This threshold shouldn't be too high either, since states 16744 * at the end of the loop are likely to be useful in pruning. 16745 */ 16746 skip_inf_loop_check: 16747 if (!force_new_state && 16748 env->jmps_processed - env->prev_jmps_processed < 20 && 16749 env->insn_processed - env->prev_insn_processed < 100) 16750 add_new_state = false; 16751 goto miss; 16752 } 16753 /* If sl->state is a part of a loop and this loop's entry is a part of 16754 * current verification path then states have to be compared exactly. 16755 * 'force_exact' is needed to catch the following case: 16756 * 16757 * initial Here state 'succ' was processed first, 16758 * | it was eventually tracked to produce a 16759 * V state identical to 'hdr'. 16760 * .---------> hdr All branches from 'succ' had been explored 16761 * | | and thus 'succ' has its .branches == 0. 16762 * | V 16763 * | .------... Suppose states 'cur' and 'succ' correspond 16764 * | | | to the same instruction + callsites. 16765 * | V V In such case it is necessary to check 16766 * | ... ... if 'succ' and 'cur' are states_equal(). 16767 * | | | If 'succ' and 'cur' are a part of the 16768 * | V V same loop exact flag has to be set. 16769 * | succ <- cur To check if that is the case, verify 16770 * | | if loop entry of 'succ' is in current 16771 * | V DFS path. 16772 * | ... 16773 * | | 16774 * '----' 16775 * 16776 * Additional details are in the comment before get_loop_entry(). 16777 */ 16778 loop_entry = get_loop_entry(&sl->state); 16779 force_exact = loop_entry && loop_entry->branches > 0; 16780 if (states_equal(env, &sl->state, cur, force_exact)) { 16781 if (force_exact) 16782 update_loop_entry(cur, loop_entry); 16783 hit: 16784 sl->hit_cnt++; 16785 /* reached equivalent register/stack state, 16786 * prune the search. 16787 * Registers read by the continuation are read by us. 16788 * If we have any write marks in env->cur_state, they 16789 * will prevent corresponding reads in the continuation 16790 * from reaching our parent (an explored_state). Our 16791 * own state will get the read marks recorded, but 16792 * they'll be immediately forgotten as we're pruning 16793 * this state and will pop a new one. 16794 */ 16795 err = propagate_liveness(env, &sl->state, cur); 16796 16797 /* if previous state reached the exit with precision and 16798 * current state is equivalent to it (except precsion marks) 16799 * the precision needs to be propagated back in 16800 * the current state. 16801 */ 16802 if (is_jmp_point(env, env->insn_idx)) 16803 err = err ? : push_jmp_history(env, cur, 0); 16804 err = err ? : propagate_precision(env, &sl->state); 16805 if (err) 16806 return err; 16807 return 1; 16808 } 16809 miss: 16810 /* when new state is not going to be added do not increase miss count. 16811 * Otherwise several loop iterations will remove the state 16812 * recorded earlier. The goal of these heuristics is to have 16813 * states from some iterations of the loop (some in the beginning 16814 * and some at the end) to help pruning. 16815 */ 16816 if (add_new_state) 16817 sl->miss_cnt++; 16818 /* heuristic to determine whether this state is beneficial 16819 * to keep checking from state equivalence point of view. 16820 * Higher numbers increase max_states_per_insn and verification time, 16821 * but do not meaningfully decrease insn_processed. 16822 * 'n' controls how many times state could miss before eviction. 16823 * Use bigger 'n' for checkpoints because evicting checkpoint states 16824 * too early would hinder iterator convergence. 16825 */ 16826 n = is_force_checkpoint(env, insn_idx) && sl->state.branches > 0 ? 64 : 3; 16827 if (sl->miss_cnt > sl->hit_cnt * n + n) { 16828 /* the state is unlikely to be useful. Remove it to 16829 * speed up verification 16830 */ 16831 *pprev = sl->next; 16832 if (sl->state.frame[0]->regs[0].live & REG_LIVE_DONE && 16833 !sl->state.used_as_loop_entry) { 16834 u32 br = sl->state.branches; 16835 16836 WARN_ONCE(br, 16837 "BUG live_done but branches_to_explore %d\n", 16838 br); 16839 free_verifier_state(&sl->state, false); 16840 kfree(sl); 16841 env->peak_states--; 16842 } else { 16843 /* cannot free this state, since parentage chain may 16844 * walk it later. Add it for free_list instead to 16845 * be freed at the end of verification 16846 */ 16847 sl->next = env->free_list; 16848 env->free_list = sl; 16849 } 16850 sl = *pprev; 16851 continue; 16852 } 16853 next: 16854 pprev = &sl->next; 16855 sl = *pprev; 16856 } 16857 16858 if (env->max_states_per_insn < states_cnt) 16859 env->max_states_per_insn = states_cnt; 16860 16861 if (!env->bpf_capable && states_cnt > BPF_COMPLEXITY_LIMIT_STATES) 16862 return 0; 16863 16864 if (!add_new_state) 16865 return 0; 16866 16867 /* There were no equivalent states, remember the current one. 16868 * Technically the current state is not proven to be safe yet, 16869 * but it will either reach outer most bpf_exit (which means it's safe) 16870 * or it will be rejected. When there are no loops the verifier won't be 16871 * seeing this tuple (frame[0].callsite, frame[1].callsite, .. insn_idx) 16872 * again on the way to bpf_exit. 16873 * When looping the sl->state.branches will be > 0 and this state 16874 * will not be considered for equivalence until branches == 0. 16875 */ 16876 new_sl = kzalloc(sizeof(struct bpf_verifier_state_list), GFP_KERNEL); 16877 if (!new_sl) 16878 return -ENOMEM; 16879 env->total_states++; 16880 env->peak_states++; 16881 env->prev_jmps_processed = env->jmps_processed; 16882 env->prev_insn_processed = env->insn_processed; 16883 16884 /* forget precise markings we inherited, see __mark_chain_precision */ 16885 if (env->bpf_capable) 16886 mark_all_scalars_imprecise(env, cur); 16887 16888 /* add new state to the head of linked list */ 16889 new = &new_sl->state; 16890 err = copy_verifier_state(new, cur); 16891 if (err) { 16892 free_verifier_state(new, false); 16893 kfree(new_sl); 16894 return err; 16895 } 16896 new->insn_idx = insn_idx; 16897 WARN_ONCE(new->branches != 1, 16898 "BUG is_state_visited:branches_to_explore=%d insn %d\n", new->branches, insn_idx); 16899 16900 cur->parent = new; 16901 cur->first_insn_idx = insn_idx; 16902 cur->dfs_depth = new->dfs_depth + 1; 16903 clear_jmp_history(cur); 16904 new_sl->next = *explored_state(env, insn_idx); 16905 *explored_state(env, insn_idx) = new_sl; 16906 /* connect new state to parentage chain. Current frame needs all 16907 * registers connected. Only r6 - r9 of the callers are alive (pushed 16908 * to the stack implicitly by JITs) so in callers' frames connect just 16909 * r6 - r9 as an optimization. Callers will have r1 - r5 connected to 16910 * the state of the call instruction (with WRITTEN set), and r0 comes 16911 * from callee with its full parentage chain, anyway. 16912 */ 16913 /* clear write marks in current state: the writes we did are not writes 16914 * our child did, so they don't screen off its reads from us. 16915 * (There are no read marks in current state, because reads always mark 16916 * their parent and current state never has children yet. Only 16917 * explored_states can get read marks.) 16918 */ 16919 for (j = 0; j <= cur->curframe; j++) { 16920 for (i = j < cur->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++) 16921 cur->frame[j]->regs[i].parent = &new->frame[j]->regs[i]; 16922 for (i = 0; i < BPF_REG_FP; i++) 16923 cur->frame[j]->regs[i].live = REG_LIVE_NONE; 16924 } 16925 16926 /* all stack frames are accessible from callee, clear them all */ 16927 for (j = 0; j <= cur->curframe; j++) { 16928 struct bpf_func_state *frame = cur->frame[j]; 16929 struct bpf_func_state *newframe = new->frame[j]; 16930 16931 for (i = 0; i < frame->allocated_stack / BPF_REG_SIZE; i++) { 16932 frame->stack[i].spilled_ptr.live = REG_LIVE_NONE; 16933 frame->stack[i].spilled_ptr.parent = 16934 &newframe->stack[i].spilled_ptr; 16935 } 16936 } 16937 return 0; 16938 } 16939 16940 /* Return true if it's OK to have the same insn return a different type. */ 16941 static bool reg_type_mismatch_ok(enum bpf_reg_type type) 16942 { 16943 switch (base_type(type)) { 16944 case PTR_TO_CTX: 16945 case PTR_TO_SOCKET: 16946 case PTR_TO_SOCK_COMMON: 16947 case PTR_TO_TCP_SOCK: 16948 case PTR_TO_XDP_SOCK: 16949 case PTR_TO_BTF_ID: 16950 return false; 16951 default: 16952 return true; 16953 } 16954 } 16955 16956 /* If an instruction was previously used with particular pointer types, then we 16957 * need to be careful to avoid cases such as the below, where it may be ok 16958 * for one branch accessing the pointer, but not ok for the other branch: 16959 * 16960 * R1 = sock_ptr 16961 * goto X; 16962 * ... 16963 * R1 = some_other_valid_ptr; 16964 * goto X; 16965 * ... 16966 * R2 = *(u32 *)(R1 + 0); 16967 */ 16968 static bool reg_type_mismatch(enum bpf_reg_type src, enum bpf_reg_type prev) 16969 { 16970 return src != prev && (!reg_type_mismatch_ok(src) || 16971 !reg_type_mismatch_ok(prev)); 16972 } 16973 16974 static int save_aux_ptr_type(struct bpf_verifier_env *env, enum bpf_reg_type type, 16975 bool allow_trust_missmatch) 16976 { 16977 enum bpf_reg_type *prev_type = &env->insn_aux_data[env->insn_idx].ptr_type; 16978 16979 if (*prev_type == NOT_INIT) { 16980 /* Saw a valid insn 16981 * dst_reg = *(u32 *)(src_reg + off) 16982 * save type to validate intersecting paths 16983 */ 16984 *prev_type = type; 16985 } else if (reg_type_mismatch(type, *prev_type)) { 16986 /* Abuser program is trying to use the same insn 16987 * dst_reg = *(u32*) (src_reg + off) 16988 * with different pointer types: 16989 * src_reg == ctx in one branch and 16990 * src_reg == stack|map in some other branch. 16991 * Reject it. 16992 */ 16993 if (allow_trust_missmatch && 16994 base_type(type) == PTR_TO_BTF_ID && 16995 base_type(*prev_type) == PTR_TO_BTF_ID) { 16996 /* 16997 * Have to support a use case when one path through 16998 * the program yields TRUSTED pointer while another 16999 * is UNTRUSTED. Fallback to UNTRUSTED to generate 17000 * BPF_PROBE_MEM/BPF_PROBE_MEMSX. 17001 */ 17002 *prev_type = PTR_TO_BTF_ID | PTR_UNTRUSTED; 17003 } else { 17004 verbose(env, "same insn cannot be used with different pointers\n"); 17005 return -EINVAL; 17006 } 17007 } 17008 17009 return 0; 17010 } 17011 17012 static int do_check(struct bpf_verifier_env *env) 17013 { 17014 bool pop_log = !(env->log.level & BPF_LOG_LEVEL2); 17015 struct bpf_verifier_state *state = env->cur_state; 17016 struct bpf_insn *insns = env->prog->insnsi; 17017 struct bpf_reg_state *regs; 17018 int insn_cnt = env->prog->len; 17019 bool do_print_state = false; 17020 int prev_insn_idx = -1; 17021 17022 for (;;) { 17023 struct bpf_insn *insn; 17024 u8 class; 17025 int err; 17026 17027 /* reset current history entry on each new instruction */ 17028 env->cur_hist_ent = NULL; 17029 17030 env->prev_insn_idx = prev_insn_idx; 17031 if (env->insn_idx >= insn_cnt) { 17032 verbose(env, "invalid insn idx %d insn_cnt %d\n", 17033 env->insn_idx, insn_cnt); 17034 return -EFAULT; 17035 } 17036 17037 insn = &insns[env->insn_idx]; 17038 class = BPF_CLASS(insn->code); 17039 17040 if (++env->insn_processed > BPF_COMPLEXITY_LIMIT_INSNS) { 17041 verbose(env, 17042 "BPF program is too large. Processed %d insn\n", 17043 env->insn_processed); 17044 return -E2BIG; 17045 } 17046 17047 state->last_insn_idx = env->prev_insn_idx; 17048 17049 if (is_prune_point(env, env->insn_idx)) { 17050 err = is_state_visited(env, env->insn_idx); 17051 if (err < 0) 17052 return err; 17053 if (err == 1) { 17054 /* found equivalent state, can prune the search */ 17055 if (env->log.level & BPF_LOG_LEVEL) { 17056 if (do_print_state) 17057 verbose(env, "\nfrom %d to %d%s: safe\n", 17058 env->prev_insn_idx, env->insn_idx, 17059 env->cur_state->speculative ? 17060 " (speculative execution)" : ""); 17061 else 17062 verbose(env, "%d: safe\n", env->insn_idx); 17063 } 17064 goto process_bpf_exit; 17065 } 17066 } 17067 17068 if (is_jmp_point(env, env->insn_idx)) { 17069 err = push_jmp_history(env, state, 0); 17070 if (err) 17071 return err; 17072 } 17073 17074 if (signal_pending(current)) 17075 return -EAGAIN; 17076 17077 if (need_resched()) 17078 cond_resched(); 17079 17080 if (env->log.level & BPF_LOG_LEVEL2 && do_print_state) { 17081 verbose(env, "\nfrom %d to %d%s:", 17082 env->prev_insn_idx, env->insn_idx, 17083 env->cur_state->speculative ? 17084 " (speculative execution)" : ""); 17085 print_verifier_state(env, state->frame[state->curframe], true); 17086 do_print_state = false; 17087 } 17088 17089 if (env->log.level & BPF_LOG_LEVEL) { 17090 const struct bpf_insn_cbs cbs = { 17091 .cb_call = disasm_kfunc_name, 17092 .cb_print = verbose, 17093 .private_data = env, 17094 }; 17095 17096 if (verifier_state_scratched(env)) 17097 print_insn_state(env, state->frame[state->curframe]); 17098 17099 verbose_linfo(env, env->insn_idx, "; "); 17100 env->prev_log_pos = env->log.end_pos; 17101 verbose(env, "%d: ", env->insn_idx); 17102 print_bpf_insn(&cbs, insn, env->allow_ptr_leaks); 17103 env->prev_insn_print_pos = env->log.end_pos - env->prev_log_pos; 17104 env->prev_log_pos = env->log.end_pos; 17105 } 17106 17107 if (bpf_prog_is_offloaded(env->prog->aux)) { 17108 err = bpf_prog_offload_verify_insn(env, env->insn_idx, 17109 env->prev_insn_idx); 17110 if (err) 17111 return err; 17112 } 17113 17114 regs = cur_regs(env); 17115 sanitize_mark_insn_seen(env); 17116 prev_insn_idx = env->insn_idx; 17117 17118 if (class == BPF_ALU || class == BPF_ALU64) { 17119 err = check_alu_op(env, insn); 17120 if (err) 17121 return err; 17122 17123 } else if (class == BPF_LDX) { 17124 enum bpf_reg_type src_reg_type; 17125 17126 /* check for reserved fields is already done */ 17127 17128 /* check src operand */ 17129 err = check_reg_arg(env, insn->src_reg, SRC_OP); 17130 if (err) 17131 return err; 17132 17133 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK); 17134 if (err) 17135 return err; 17136 17137 src_reg_type = regs[insn->src_reg].type; 17138 17139 /* check that memory (src_reg + off) is readable, 17140 * the state of dst_reg will be updated by this func 17141 */ 17142 err = check_mem_access(env, env->insn_idx, insn->src_reg, 17143 insn->off, BPF_SIZE(insn->code), 17144 BPF_READ, insn->dst_reg, false, 17145 BPF_MODE(insn->code) == BPF_MEMSX); 17146 if (err) 17147 return err; 17148 17149 err = save_aux_ptr_type(env, src_reg_type, true); 17150 if (err) 17151 return err; 17152 } else if (class == BPF_STX) { 17153 enum bpf_reg_type dst_reg_type; 17154 17155 if (BPF_MODE(insn->code) == BPF_ATOMIC) { 17156 err = check_atomic(env, env->insn_idx, insn); 17157 if (err) 17158 return err; 17159 env->insn_idx++; 17160 continue; 17161 } 17162 17163 if (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0) { 17164 verbose(env, "BPF_STX uses reserved fields\n"); 17165 return -EINVAL; 17166 } 17167 17168 /* check src1 operand */ 17169 err = check_reg_arg(env, insn->src_reg, SRC_OP); 17170 if (err) 17171 return err; 17172 /* check src2 operand */ 17173 err = check_reg_arg(env, insn->dst_reg, SRC_OP); 17174 if (err) 17175 return err; 17176 17177 dst_reg_type = regs[insn->dst_reg].type; 17178 17179 /* check that memory (dst_reg + off) is writeable */ 17180 err = check_mem_access(env, env->insn_idx, insn->dst_reg, 17181 insn->off, BPF_SIZE(insn->code), 17182 BPF_WRITE, insn->src_reg, false, false); 17183 if (err) 17184 return err; 17185 17186 err = save_aux_ptr_type(env, dst_reg_type, false); 17187 if (err) 17188 return err; 17189 } else if (class == BPF_ST) { 17190 enum bpf_reg_type dst_reg_type; 17191 17192 if (BPF_MODE(insn->code) != BPF_MEM || 17193 insn->src_reg != BPF_REG_0) { 17194 verbose(env, "BPF_ST uses reserved fields\n"); 17195 return -EINVAL; 17196 } 17197 /* check src operand */ 17198 err = check_reg_arg(env, insn->dst_reg, SRC_OP); 17199 if (err) 17200 return err; 17201 17202 dst_reg_type = regs[insn->dst_reg].type; 17203 17204 /* check that memory (dst_reg + off) is writeable */ 17205 err = check_mem_access(env, env->insn_idx, insn->dst_reg, 17206 insn->off, BPF_SIZE(insn->code), 17207 BPF_WRITE, -1, false, false); 17208 if (err) 17209 return err; 17210 17211 err = save_aux_ptr_type(env, dst_reg_type, false); 17212 if (err) 17213 return err; 17214 } else if (class == BPF_JMP || class == BPF_JMP32) { 17215 u8 opcode = BPF_OP(insn->code); 17216 17217 env->jmps_processed++; 17218 if (opcode == BPF_CALL) { 17219 if (BPF_SRC(insn->code) != BPF_K || 17220 (insn->src_reg != BPF_PSEUDO_KFUNC_CALL 17221 && insn->off != 0) || 17222 (insn->src_reg != BPF_REG_0 && 17223 insn->src_reg != BPF_PSEUDO_CALL && 17224 insn->src_reg != BPF_PSEUDO_KFUNC_CALL) || 17225 insn->dst_reg != BPF_REG_0 || 17226 class == BPF_JMP32) { 17227 verbose(env, "BPF_CALL uses reserved fields\n"); 17228 return -EINVAL; 17229 } 17230 17231 if (env->cur_state->active_lock.ptr) { 17232 if ((insn->src_reg == BPF_REG_0 && insn->imm != BPF_FUNC_spin_unlock) || 17233 (insn->src_reg == BPF_PSEUDO_CALL) || 17234 (insn->src_reg == BPF_PSEUDO_KFUNC_CALL && 17235 (insn->off != 0 || !is_bpf_graph_api_kfunc(insn->imm)))) { 17236 verbose(env, "function calls are not allowed while holding a lock\n"); 17237 return -EINVAL; 17238 } 17239 } 17240 if (insn->src_reg == BPF_PSEUDO_CALL) 17241 err = check_func_call(env, insn, &env->insn_idx); 17242 else if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) 17243 err = check_kfunc_call(env, insn, &env->insn_idx); 17244 else 17245 err = check_helper_call(env, insn, &env->insn_idx); 17246 if (err) 17247 return err; 17248 17249 mark_reg_scratched(env, BPF_REG_0); 17250 } else if (opcode == BPF_JA) { 17251 if (BPF_SRC(insn->code) != BPF_K || 17252 insn->src_reg != BPF_REG_0 || 17253 insn->dst_reg != BPF_REG_0 || 17254 (class == BPF_JMP && insn->imm != 0) || 17255 (class == BPF_JMP32 && insn->off != 0)) { 17256 verbose(env, "BPF_JA uses reserved fields\n"); 17257 return -EINVAL; 17258 } 17259 17260 if (class == BPF_JMP) 17261 env->insn_idx += insn->off + 1; 17262 else 17263 env->insn_idx += insn->imm + 1; 17264 continue; 17265 17266 } else if (opcode == BPF_EXIT) { 17267 if (BPF_SRC(insn->code) != BPF_K || 17268 insn->imm != 0 || 17269 insn->src_reg != BPF_REG_0 || 17270 insn->dst_reg != BPF_REG_0 || 17271 class == BPF_JMP32) { 17272 verbose(env, "BPF_EXIT uses reserved fields\n"); 17273 return -EINVAL; 17274 } 17275 17276 if (env->cur_state->active_lock.ptr && 17277 !in_rbtree_lock_required_cb(env)) { 17278 verbose(env, "bpf_spin_unlock is missing\n"); 17279 return -EINVAL; 17280 } 17281 17282 if (env->cur_state->active_rcu_lock && 17283 !in_rbtree_lock_required_cb(env)) { 17284 verbose(env, "bpf_rcu_read_unlock is missing\n"); 17285 return -EINVAL; 17286 } 17287 17288 /* We must do check_reference_leak here before 17289 * prepare_func_exit to handle the case when 17290 * state->curframe > 0, it may be a callback 17291 * function, for which reference_state must 17292 * match caller reference state when it exits. 17293 */ 17294 err = check_reference_leak(env); 17295 if (err) 17296 return err; 17297 17298 if (state->curframe) { 17299 /* exit from nested function */ 17300 err = prepare_func_exit(env, &env->insn_idx); 17301 if (err) 17302 return err; 17303 do_print_state = true; 17304 continue; 17305 } 17306 17307 err = check_return_code(env); 17308 if (err) 17309 return err; 17310 process_bpf_exit: 17311 mark_verifier_state_scratched(env); 17312 update_branch_counts(env, env->cur_state); 17313 err = pop_stack(env, &prev_insn_idx, 17314 &env->insn_idx, pop_log); 17315 if (err < 0) { 17316 if (err != -ENOENT) 17317 return err; 17318 break; 17319 } else { 17320 do_print_state = true; 17321 continue; 17322 } 17323 } else { 17324 err = check_cond_jmp_op(env, insn, &env->insn_idx); 17325 if (err) 17326 return err; 17327 } 17328 } else if (class == BPF_LD) { 17329 u8 mode = BPF_MODE(insn->code); 17330 17331 if (mode == BPF_ABS || mode == BPF_IND) { 17332 err = check_ld_abs(env, insn); 17333 if (err) 17334 return err; 17335 17336 } else if (mode == BPF_IMM) { 17337 err = check_ld_imm(env, insn); 17338 if (err) 17339 return err; 17340 17341 env->insn_idx++; 17342 sanitize_mark_insn_seen(env); 17343 } else { 17344 verbose(env, "invalid BPF_LD mode\n"); 17345 return -EINVAL; 17346 } 17347 } else { 17348 verbose(env, "unknown insn class %d\n", class); 17349 return -EINVAL; 17350 } 17351 17352 env->insn_idx++; 17353 } 17354 17355 return 0; 17356 } 17357 17358 static int find_btf_percpu_datasec(struct btf *btf) 17359 { 17360 const struct btf_type *t; 17361 const char *tname; 17362 int i, n; 17363 17364 /* 17365 * Both vmlinux and module each have their own ".data..percpu" 17366 * DATASECs in BTF. So for module's case, we need to skip vmlinux BTF 17367 * types to look at only module's own BTF types. 17368 */ 17369 n = btf_nr_types(btf); 17370 if (btf_is_module(btf)) 17371 i = btf_nr_types(btf_vmlinux); 17372 else 17373 i = 1; 17374 17375 for(; i < n; i++) { 17376 t = btf_type_by_id(btf, i); 17377 if (BTF_INFO_KIND(t->info) != BTF_KIND_DATASEC) 17378 continue; 17379 17380 tname = btf_name_by_offset(btf, t->name_off); 17381 if (!strcmp(tname, ".data..percpu")) 17382 return i; 17383 } 17384 17385 return -ENOENT; 17386 } 17387 17388 /* replace pseudo btf_id with kernel symbol address */ 17389 static int check_pseudo_btf_id(struct bpf_verifier_env *env, 17390 struct bpf_insn *insn, 17391 struct bpf_insn_aux_data *aux) 17392 { 17393 const struct btf_var_secinfo *vsi; 17394 const struct btf_type *datasec; 17395 struct btf_mod_pair *btf_mod; 17396 const struct btf_type *t; 17397 const char *sym_name; 17398 bool percpu = false; 17399 u32 type, id = insn->imm; 17400 struct btf *btf; 17401 s32 datasec_id; 17402 u64 addr; 17403 int i, btf_fd, err; 17404 17405 btf_fd = insn[1].imm; 17406 if (btf_fd) { 17407 btf = btf_get_by_fd(btf_fd); 17408 if (IS_ERR(btf)) { 17409 verbose(env, "invalid module BTF object FD specified.\n"); 17410 return -EINVAL; 17411 } 17412 } else { 17413 if (!btf_vmlinux) { 17414 verbose(env, "kernel is missing BTF, make sure CONFIG_DEBUG_INFO_BTF=y is specified in Kconfig.\n"); 17415 return -EINVAL; 17416 } 17417 btf = btf_vmlinux; 17418 btf_get(btf); 17419 } 17420 17421 t = btf_type_by_id(btf, id); 17422 if (!t) { 17423 verbose(env, "ldimm64 insn specifies invalid btf_id %d.\n", id); 17424 err = -ENOENT; 17425 goto err_put; 17426 } 17427 17428 if (!btf_type_is_var(t) && !btf_type_is_func(t)) { 17429 verbose(env, "pseudo btf_id %d in ldimm64 isn't KIND_VAR or KIND_FUNC\n", id); 17430 err = -EINVAL; 17431 goto err_put; 17432 } 17433 17434 sym_name = btf_name_by_offset(btf, t->name_off); 17435 addr = kallsyms_lookup_name(sym_name); 17436 if (!addr) { 17437 verbose(env, "ldimm64 failed to find the address for kernel symbol '%s'.\n", 17438 sym_name); 17439 err = -ENOENT; 17440 goto err_put; 17441 } 17442 insn[0].imm = (u32)addr; 17443 insn[1].imm = addr >> 32; 17444 17445 if (btf_type_is_func(t)) { 17446 aux->btf_var.reg_type = PTR_TO_MEM | MEM_RDONLY; 17447 aux->btf_var.mem_size = 0; 17448 goto check_btf; 17449 } 17450 17451 datasec_id = find_btf_percpu_datasec(btf); 17452 if (datasec_id > 0) { 17453 datasec = btf_type_by_id(btf, datasec_id); 17454 for_each_vsi(i, datasec, vsi) { 17455 if (vsi->type == id) { 17456 percpu = true; 17457 break; 17458 } 17459 } 17460 } 17461 17462 type = t->type; 17463 t = btf_type_skip_modifiers(btf, type, NULL); 17464 if (percpu) { 17465 aux->btf_var.reg_type = PTR_TO_BTF_ID | MEM_PERCPU; 17466 aux->btf_var.btf = btf; 17467 aux->btf_var.btf_id = type; 17468 } else if (!btf_type_is_struct(t)) { 17469 const struct btf_type *ret; 17470 const char *tname; 17471 u32 tsize; 17472 17473 /* resolve the type size of ksym. */ 17474 ret = btf_resolve_size(btf, t, &tsize); 17475 if (IS_ERR(ret)) { 17476 tname = btf_name_by_offset(btf, t->name_off); 17477 verbose(env, "ldimm64 unable to resolve the size of type '%s': %ld\n", 17478 tname, PTR_ERR(ret)); 17479 err = -EINVAL; 17480 goto err_put; 17481 } 17482 aux->btf_var.reg_type = PTR_TO_MEM | MEM_RDONLY; 17483 aux->btf_var.mem_size = tsize; 17484 } else { 17485 aux->btf_var.reg_type = PTR_TO_BTF_ID; 17486 aux->btf_var.btf = btf; 17487 aux->btf_var.btf_id = type; 17488 } 17489 check_btf: 17490 /* check whether we recorded this BTF (and maybe module) already */ 17491 for (i = 0; i < env->used_btf_cnt; i++) { 17492 if (env->used_btfs[i].btf == btf) { 17493 btf_put(btf); 17494 return 0; 17495 } 17496 } 17497 17498 if (env->used_btf_cnt >= MAX_USED_BTFS) { 17499 err = -E2BIG; 17500 goto err_put; 17501 } 17502 17503 btf_mod = &env->used_btfs[env->used_btf_cnt]; 17504 btf_mod->btf = btf; 17505 btf_mod->module = NULL; 17506 17507 /* if we reference variables from kernel module, bump its refcount */ 17508 if (btf_is_module(btf)) { 17509 btf_mod->module = btf_try_get_module(btf); 17510 if (!btf_mod->module) { 17511 err = -ENXIO; 17512 goto err_put; 17513 } 17514 } 17515 17516 env->used_btf_cnt++; 17517 17518 return 0; 17519 err_put: 17520 btf_put(btf); 17521 return err; 17522 } 17523 17524 static bool is_tracing_prog_type(enum bpf_prog_type type) 17525 { 17526 switch (type) { 17527 case BPF_PROG_TYPE_KPROBE: 17528 case BPF_PROG_TYPE_TRACEPOINT: 17529 case BPF_PROG_TYPE_PERF_EVENT: 17530 case BPF_PROG_TYPE_RAW_TRACEPOINT: 17531 case BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE: 17532 return true; 17533 default: 17534 return false; 17535 } 17536 } 17537 17538 static int check_map_prog_compatibility(struct bpf_verifier_env *env, 17539 struct bpf_map *map, 17540 struct bpf_prog *prog) 17541 17542 { 17543 enum bpf_prog_type prog_type = resolve_prog_type(prog); 17544 17545 if (btf_record_has_field(map->record, BPF_LIST_HEAD) || 17546 btf_record_has_field(map->record, BPF_RB_ROOT)) { 17547 if (is_tracing_prog_type(prog_type)) { 17548 verbose(env, "tracing progs cannot use bpf_{list_head,rb_root} yet\n"); 17549 return -EINVAL; 17550 } 17551 } 17552 17553 if (btf_record_has_field(map->record, BPF_SPIN_LOCK)) { 17554 if (prog_type == BPF_PROG_TYPE_SOCKET_FILTER) { 17555 verbose(env, "socket filter progs cannot use bpf_spin_lock yet\n"); 17556 return -EINVAL; 17557 } 17558 17559 if (is_tracing_prog_type(prog_type)) { 17560 verbose(env, "tracing progs cannot use bpf_spin_lock yet\n"); 17561 return -EINVAL; 17562 } 17563 } 17564 17565 if (btf_record_has_field(map->record, BPF_TIMER)) { 17566 if (is_tracing_prog_type(prog_type)) { 17567 verbose(env, "tracing progs cannot use bpf_timer yet\n"); 17568 return -EINVAL; 17569 } 17570 } 17571 17572 if ((bpf_prog_is_offloaded(prog->aux) || bpf_map_is_offloaded(map)) && 17573 !bpf_offload_prog_map_match(prog, map)) { 17574 verbose(env, "offload device mismatch between prog and map\n"); 17575 return -EINVAL; 17576 } 17577 17578 if (map->map_type == BPF_MAP_TYPE_STRUCT_OPS) { 17579 verbose(env, "bpf_struct_ops map cannot be used in prog\n"); 17580 return -EINVAL; 17581 } 17582 17583 if (prog->aux->sleepable) 17584 switch (map->map_type) { 17585 case BPF_MAP_TYPE_HASH: 17586 case BPF_MAP_TYPE_LRU_HASH: 17587 case BPF_MAP_TYPE_ARRAY: 17588 case BPF_MAP_TYPE_PERCPU_HASH: 17589 case BPF_MAP_TYPE_PERCPU_ARRAY: 17590 case BPF_MAP_TYPE_LRU_PERCPU_HASH: 17591 case BPF_MAP_TYPE_ARRAY_OF_MAPS: 17592 case BPF_MAP_TYPE_HASH_OF_MAPS: 17593 case BPF_MAP_TYPE_RINGBUF: 17594 case BPF_MAP_TYPE_USER_RINGBUF: 17595 case BPF_MAP_TYPE_INODE_STORAGE: 17596 case BPF_MAP_TYPE_SK_STORAGE: 17597 case BPF_MAP_TYPE_TASK_STORAGE: 17598 case BPF_MAP_TYPE_CGRP_STORAGE: 17599 break; 17600 default: 17601 verbose(env, 17602 "Sleepable programs can only use array, hash, ringbuf and local storage maps\n"); 17603 return -EINVAL; 17604 } 17605 17606 return 0; 17607 } 17608 17609 static bool bpf_map_is_cgroup_storage(struct bpf_map *map) 17610 { 17611 return (map->map_type == BPF_MAP_TYPE_CGROUP_STORAGE || 17612 map->map_type == BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE); 17613 } 17614 17615 /* find and rewrite pseudo imm in ld_imm64 instructions: 17616 * 17617 * 1. if it accesses map FD, replace it with actual map pointer. 17618 * 2. if it accesses btf_id of a VAR, replace it with pointer to the var. 17619 * 17620 * NOTE: btf_vmlinux is required for converting pseudo btf_id. 17621 */ 17622 static int resolve_pseudo_ldimm64(struct bpf_verifier_env *env) 17623 { 17624 struct bpf_insn *insn = env->prog->insnsi; 17625 int insn_cnt = env->prog->len; 17626 int i, j, err; 17627 17628 err = bpf_prog_calc_tag(env->prog); 17629 if (err) 17630 return err; 17631 17632 for (i = 0; i < insn_cnt; i++, insn++) { 17633 if (BPF_CLASS(insn->code) == BPF_LDX && 17634 ((BPF_MODE(insn->code) != BPF_MEM && BPF_MODE(insn->code) != BPF_MEMSX) || 17635 insn->imm != 0)) { 17636 verbose(env, "BPF_LDX uses reserved fields\n"); 17637 return -EINVAL; 17638 } 17639 17640 if (insn[0].code == (BPF_LD | BPF_IMM | BPF_DW)) { 17641 struct bpf_insn_aux_data *aux; 17642 struct bpf_map *map; 17643 struct fd f; 17644 u64 addr; 17645 u32 fd; 17646 17647 if (i == insn_cnt - 1 || insn[1].code != 0 || 17648 insn[1].dst_reg != 0 || insn[1].src_reg != 0 || 17649 insn[1].off != 0) { 17650 verbose(env, "invalid bpf_ld_imm64 insn\n"); 17651 return -EINVAL; 17652 } 17653 17654 if (insn[0].src_reg == 0) 17655 /* valid generic load 64-bit imm */ 17656 goto next_insn; 17657 17658 if (insn[0].src_reg == BPF_PSEUDO_BTF_ID) { 17659 aux = &env->insn_aux_data[i]; 17660 err = check_pseudo_btf_id(env, insn, aux); 17661 if (err) 17662 return err; 17663 goto next_insn; 17664 } 17665 17666 if (insn[0].src_reg == BPF_PSEUDO_FUNC) { 17667 aux = &env->insn_aux_data[i]; 17668 aux->ptr_type = PTR_TO_FUNC; 17669 goto next_insn; 17670 } 17671 17672 /* In final convert_pseudo_ld_imm64() step, this is 17673 * converted into regular 64-bit imm load insn. 17674 */ 17675 switch (insn[0].src_reg) { 17676 case BPF_PSEUDO_MAP_VALUE: 17677 case BPF_PSEUDO_MAP_IDX_VALUE: 17678 break; 17679 case BPF_PSEUDO_MAP_FD: 17680 case BPF_PSEUDO_MAP_IDX: 17681 if (insn[1].imm == 0) 17682 break; 17683 fallthrough; 17684 default: 17685 verbose(env, "unrecognized bpf_ld_imm64 insn\n"); 17686 return -EINVAL; 17687 } 17688 17689 switch (insn[0].src_reg) { 17690 case BPF_PSEUDO_MAP_IDX_VALUE: 17691 case BPF_PSEUDO_MAP_IDX: 17692 if (bpfptr_is_null(env->fd_array)) { 17693 verbose(env, "fd_idx without fd_array is invalid\n"); 17694 return -EPROTO; 17695 } 17696 if (copy_from_bpfptr_offset(&fd, env->fd_array, 17697 insn[0].imm * sizeof(fd), 17698 sizeof(fd))) 17699 return -EFAULT; 17700 break; 17701 default: 17702 fd = insn[0].imm; 17703 break; 17704 } 17705 17706 f = fdget(fd); 17707 map = __bpf_map_get(f); 17708 if (IS_ERR(map)) { 17709 verbose(env, "fd %d is not pointing to valid bpf_map\n", fd); 17710 return PTR_ERR(map); 17711 } 17712 17713 err = check_map_prog_compatibility(env, map, env->prog); 17714 if (err) { 17715 fdput(f); 17716 return err; 17717 } 17718 17719 aux = &env->insn_aux_data[i]; 17720 if (insn[0].src_reg == BPF_PSEUDO_MAP_FD || 17721 insn[0].src_reg == BPF_PSEUDO_MAP_IDX) { 17722 addr = (unsigned long)map; 17723 } else { 17724 u32 off = insn[1].imm; 17725 17726 if (off >= BPF_MAX_VAR_OFF) { 17727 verbose(env, "direct value offset of %u is not allowed\n", off); 17728 fdput(f); 17729 return -EINVAL; 17730 } 17731 17732 if (!map->ops->map_direct_value_addr) { 17733 verbose(env, "no direct value access support for this map type\n"); 17734 fdput(f); 17735 return -EINVAL; 17736 } 17737 17738 err = map->ops->map_direct_value_addr(map, &addr, off); 17739 if (err) { 17740 verbose(env, "invalid access to map value pointer, value_size=%u off=%u\n", 17741 map->value_size, off); 17742 fdput(f); 17743 return err; 17744 } 17745 17746 aux->map_off = off; 17747 addr += off; 17748 } 17749 17750 insn[0].imm = (u32)addr; 17751 insn[1].imm = addr >> 32; 17752 17753 /* check whether we recorded this map already */ 17754 for (j = 0; j < env->used_map_cnt; j++) { 17755 if (env->used_maps[j] == map) { 17756 aux->map_index = j; 17757 fdput(f); 17758 goto next_insn; 17759 } 17760 } 17761 17762 if (env->used_map_cnt >= MAX_USED_MAPS) { 17763 fdput(f); 17764 return -E2BIG; 17765 } 17766 17767 if (env->prog->aux->sleepable) 17768 atomic64_inc(&map->sleepable_refcnt); 17769 /* hold the map. If the program is rejected by verifier, 17770 * the map will be released by release_maps() or it 17771 * will be used by the valid program until it's unloaded 17772 * and all maps are released in bpf_free_used_maps() 17773 */ 17774 bpf_map_inc(map); 17775 17776 aux->map_index = env->used_map_cnt; 17777 env->used_maps[env->used_map_cnt++] = map; 17778 17779 if (bpf_map_is_cgroup_storage(map) && 17780 bpf_cgroup_storage_assign(env->prog->aux, map)) { 17781 verbose(env, "only one cgroup storage of each type is allowed\n"); 17782 fdput(f); 17783 return -EBUSY; 17784 } 17785 17786 fdput(f); 17787 next_insn: 17788 insn++; 17789 i++; 17790 continue; 17791 } 17792 17793 /* Basic sanity check before we invest more work here. */ 17794 if (!bpf_opcode_in_insntable(insn->code)) { 17795 verbose(env, "unknown opcode %02x\n", insn->code); 17796 return -EINVAL; 17797 } 17798 } 17799 17800 /* now all pseudo BPF_LD_IMM64 instructions load valid 17801 * 'struct bpf_map *' into a register instead of user map_fd. 17802 * These pointers will be used later by verifier to validate map access. 17803 */ 17804 return 0; 17805 } 17806 17807 /* drop refcnt of maps used by the rejected program */ 17808 static void release_maps(struct bpf_verifier_env *env) 17809 { 17810 __bpf_free_used_maps(env->prog->aux, env->used_maps, 17811 env->used_map_cnt); 17812 } 17813 17814 /* drop refcnt of maps used by the rejected program */ 17815 static void release_btfs(struct bpf_verifier_env *env) 17816 { 17817 __bpf_free_used_btfs(env->prog->aux, env->used_btfs, 17818 env->used_btf_cnt); 17819 } 17820 17821 /* convert pseudo BPF_LD_IMM64 into generic BPF_LD_IMM64 */ 17822 static void convert_pseudo_ld_imm64(struct bpf_verifier_env *env) 17823 { 17824 struct bpf_insn *insn = env->prog->insnsi; 17825 int insn_cnt = env->prog->len; 17826 int i; 17827 17828 for (i = 0; i < insn_cnt; i++, insn++) { 17829 if (insn->code != (BPF_LD | BPF_IMM | BPF_DW)) 17830 continue; 17831 if (insn->src_reg == BPF_PSEUDO_FUNC) 17832 continue; 17833 insn->src_reg = 0; 17834 } 17835 } 17836 17837 /* single env->prog->insni[off] instruction was replaced with the range 17838 * insni[off, off + cnt). Adjust corresponding insn_aux_data by copying 17839 * [0, off) and [off, end) to new locations, so the patched range stays zero 17840 */ 17841 static void adjust_insn_aux_data(struct bpf_verifier_env *env, 17842 struct bpf_insn_aux_data *new_data, 17843 struct bpf_prog *new_prog, u32 off, u32 cnt) 17844 { 17845 struct bpf_insn_aux_data *old_data = env->insn_aux_data; 17846 struct bpf_insn *insn = new_prog->insnsi; 17847 u32 old_seen = old_data[off].seen; 17848 u32 prog_len; 17849 int i; 17850 17851 /* aux info at OFF always needs adjustment, no matter fast path 17852 * (cnt == 1) is taken or not. There is no guarantee INSN at OFF is the 17853 * original insn at old prog. 17854 */ 17855 old_data[off].zext_dst = insn_has_def32(env, insn + off + cnt - 1); 17856 17857 if (cnt == 1) 17858 return; 17859 prog_len = new_prog->len; 17860 17861 memcpy(new_data, old_data, sizeof(struct bpf_insn_aux_data) * off); 17862 memcpy(new_data + off + cnt - 1, old_data + off, 17863 sizeof(struct bpf_insn_aux_data) * (prog_len - off - cnt + 1)); 17864 for (i = off; i < off + cnt - 1; i++) { 17865 /* Expand insni[off]'s seen count to the patched range. */ 17866 new_data[i].seen = old_seen; 17867 new_data[i].zext_dst = insn_has_def32(env, insn + i); 17868 } 17869 env->insn_aux_data = new_data; 17870 vfree(old_data); 17871 } 17872 17873 static void adjust_subprog_starts(struct bpf_verifier_env *env, u32 off, u32 len) 17874 { 17875 int i; 17876 17877 if (len == 1) 17878 return; 17879 /* NOTE: fake 'exit' subprog should be updated as well. */ 17880 for (i = 0; i <= env->subprog_cnt; i++) { 17881 if (env->subprog_info[i].start <= off) 17882 continue; 17883 env->subprog_info[i].start += len - 1; 17884 } 17885 } 17886 17887 static void adjust_poke_descs(struct bpf_prog *prog, u32 off, u32 len) 17888 { 17889 struct bpf_jit_poke_descriptor *tab = prog->aux->poke_tab; 17890 int i, sz = prog->aux->size_poke_tab; 17891 struct bpf_jit_poke_descriptor *desc; 17892 17893 for (i = 0; i < sz; i++) { 17894 desc = &tab[i]; 17895 if (desc->insn_idx <= off) 17896 continue; 17897 desc->insn_idx += len - 1; 17898 } 17899 } 17900 17901 static struct bpf_prog *bpf_patch_insn_data(struct bpf_verifier_env *env, u32 off, 17902 const struct bpf_insn *patch, u32 len) 17903 { 17904 struct bpf_prog *new_prog; 17905 struct bpf_insn_aux_data *new_data = NULL; 17906 17907 if (len > 1) { 17908 new_data = vzalloc(array_size(env->prog->len + len - 1, 17909 sizeof(struct bpf_insn_aux_data))); 17910 if (!new_data) 17911 return NULL; 17912 } 17913 17914 new_prog = bpf_patch_insn_single(env->prog, off, patch, len); 17915 if (IS_ERR(new_prog)) { 17916 if (PTR_ERR(new_prog) == -ERANGE) 17917 verbose(env, 17918 "insn %d cannot be patched due to 16-bit range\n", 17919 env->insn_aux_data[off].orig_idx); 17920 vfree(new_data); 17921 return NULL; 17922 } 17923 adjust_insn_aux_data(env, new_data, new_prog, off, len); 17924 adjust_subprog_starts(env, off, len); 17925 adjust_poke_descs(new_prog, off, len); 17926 return new_prog; 17927 } 17928 17929 static int adjust_subprog_starts_after_remove(struct bpf_verifier_env *env, 17930 u32 off, u32 cnt) 17931 { 17932 int i, j; 17933 17934 /* find first prog starting at or after off (first to remove) */ 17935 for (i = 0; i < env->subprog_cnt; i++) 17936 if (env->subprog_info[i].start >= off) 17937 break; 17938 /* find first prog starting at or after off + cnt (first to stay) */ 17939 for (j = i; j < env->subprog_cnt; j++) 17940 if (env->subprog_info[j].start >= off + cnt) 17941 break; 17942 /* if j doesn't start exactly at off + cnt, we are just removing 17943 * the front of previous prog 17944 */ 17945 if (env->subprog_info[j].start != off + cnt) 17946 j--; 17947 17948 if (j > i) { 17949 struct bpf_prog_aux *aux = env->prog->aux; 17950 int move; 17951 17952 /* move fake 'exit' subprog as well */ 17953 move = env->subprog_cnt + 1 - j; 17954 17955 memmove(env->subprog_info + i, 17956 env->subprog_info + j, 17957 sizeof(*env->subprog_info) * move); 17958 env->subprog_cnt -= j - i; 17959 17960 /* remove func_info */ 17961 if (aux->func_info) { 17962 move = aux->func_info_cnt - j; 17963 17964 memmove(aux->func_info + i, 17965 aux->func_info + j, 17966 sizeof(*aux->func_info) * move); 17967 aux->func_info_cnt -= j - i; 17968 /* func_info->insn_off is set after all code rewrites, 17969 * in adjust_btf_func() - no need to adjust 17970 */ 17971 } 17972 } else { 17973 /* convert i from "first prog to remove" to "first to adjust" */ 17974 if (env->subprog_info[i].start == off) 17975 i++; 17976 } 17977 17978 /* update fake 'exit' subprog as well */ 17979 for (; i <= env->subprog_cnt; i++) 17980 env->subprog_info[i].start -= cnt; 17981 17982 return 0; 17983 } 17984 17985 static int bpf_adj_linfo_after_remove(struct bpf_verifier_env *env, u32 off, 17986 u32 cnt) 17987 { 17988 struct bpf_prog *prog = env->prog; 17989 u32 i, l_off, l_cnt, nr_linfo; 17990 struct bpf_line_info *linfo; 17991 17992 nr_linfo = prog->aux->nr_linfo; 17993 if (!nr_linfo) 17994 return 0; 17995 17996 linfo = prog->aux->linfo; 17997 17998 /* find first line info to remove, count lines to be removed */ 17999 for (i = 0; i < nr_linfo; i++) 18000 if (linfo[i].insn_off >= off) 18001 break; 18002 18003 l_off = i; 18004 l_cnt = 0; 18005 for (; i < nr_linfo; i++) 18006 if (linfo[i].insn_off < off + cnt) 18007 l_cnt++; 18008 else 18009 break; 18010 18011 /* First live insn doesn't match first live linfo, it needs to "inherit" 18012 * last removed linfo. prog is already modified, so prog->len == off 18013 * means no live instructions after (tail of the program was removed). 18014 */ 18015 if (prog->len != off && l_cnt && 18016 (i == nr_linfo || linfo[i].insn_off != off + cnt)) { 18017 l_cnt--; 18018 linfo[--i].insn_off = off + cnt; 18019 } 18020 18021 /* remove the line info which refer to the removed instructions */ 18022 if (l_cnt) { 18023 memmove(linfo + l_off, linfo + i, 18024 sizeof(*linfo) * (nr_linfo - i)); 18025 18026 prog->aux->nr_linfo -= l_cnt; 18027 nr_linfo = prog->aux->nr_linfo; 18028 } 18029 18030 /* pull all linfo[i].insn_off >= off + cnt in by cnt */ 18031 for (i = l_off; i < nr_linfo; i++) 18032 linfo[i].insn_off -= cnt; 18033 18034 /* fix up all subprogs (incl. 'exit') which start >= off */ 18035 for (i = 0; i <= env->subprog_cnt; i++) 18036 if (env->subprog_info[i].linfo_idx > l_off) { 18037 /* program may have started in the removed region but 18038 * may not be fully removed 18039 */ 18040 if (env->subprog_info[i].linfo_idx >= l_off + l_cnt) 18041 env->subprog_info[i].linfo_idx -= l_cnt; 18042 else 18043 env->subprog_info[i].linfo_idx = l_off; 18044 } 18045 18046 return 0; 18047 } 18048 18049 static int verifier_remove_insns(struct bpf_verifier_env *env, u32 off, u32 cnt) 18050 { 18051 struct bpf_insn_aux_data *aux_data = env->insn_aux_data; 18052 unsigned int orig_prog_len = env->prog->len; 18053 int err; 18054 18055 if (bpf_prog_is_offloaded(env->prog->aux)) 18056 bpf_prog_offload_remove_insns(env, off, cnt); 18057 18058 err = bpf_remove_insns(env->prog, off, cnt); 18059 if (err) 18060 return err; 18061 18062 err = adjust_subprog_starts_after_remove(env, off, cnt); 18063 if (err) 18064 return err; 18065 18066 err = bpf_adj_linfo_after_remove(env, off, cnt); 18067 if (err) 18068 return err; 18069 18070 memmove(aux_data + off, aux_data + off + cnt, 18071 sizeof(*aux_data) * (orig_prog_len - off - cnt)); 18072 18073 return 0; 18074 } 18075 18076 /* The verifier does more data flow analysis than llvm and will not 18077 * explore branches that are dead at run time. Malicious programs can 18078 * have dead code too. Therefore replace all dead at-run-time code 18079 * with 'ja -1'. 18080 * 18081 * Just nops are not optimal, e.g. if they would sit at the end of the 18082 * program and through another bug we would manage to jump there, then 18083 * we'd execute beyond program memory otherwise. Returning exception 18084 * code also wouldn't work since we can have subprogs where the dead 18085 * code could be located. 18086 */ 18087 static void sanitize_dead_code(struct bpf_verifier_env *env) 18088 { 18089 struct bpf_insn_aux_data *aux_data = env->insn_aux_data; 18090 struct bpf_insn trap = BPF_JMP_IMM(BPF_JA, 0, 0, -1); 18091 struct bpf_insn *insn = env->prog->insnsi; 18092 const int insn_cnt = env->prog->len; 18093 int i; 18094 18095 for (i = 0; i < insn_cnt; i++) { 18096 if (aux_data[i].seen) 18097 continue; 18098 memcpy(insn + i, &trap, sizeof(trap)); 18099 aux_data[i].zext_dst = false; 18100 } 18101 } 18102 18103 static bool insn_is_cond_jump(u8 code) 18104 { 18105 u8 op; 18106 18107 op = BPF_OP(code); 18108 if (BPF_CLASS(code) == BPF_JMP32) 18109 return op != BPF_JA; 18110 18111 if (BPF_CLASS(code) != BPF_JMP) 18112 return false; 18113 18114 return op != BPF_JA && op != BPF_EXIT && op != BPF_CALL; 18115 } 18116 18117 static void opt_hard_wire_dead_code_branches(struct bpf_verifier_env *env) 18118 { 18119 struct bpf_insn_aux_data *aux_data = env->insn_aux_data; 18120 struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0); 18121 struct bpf_insn *insn = env->prog->insnsi; 18122 const int insn_cnt = env->prog->len; 18123 int i; 18124 18125 for (i = 0; i < insn_cnt; i++, insn++) { 18126 if (!insn_is_cond_jump(insn->code)) 18127 continue; 18128 18129 if (!aux_data[i + 1].seen) 18130 ja.off = insn->off; 18131 else if (!aux_data[i + 1 + insn->off].seen) 18132 ja.off = 0; 18133 else 18134 continue; 18135 18136 if (bpf_prog_is_offloaded(env->prog->aux)) 18137 bpf_prog_offload_replace_insn(env, i, &ja); 18138 18139 memcpy(insn, &ja, sizeof(ja)); 18140 } 18141 } 18142 18143 static int opt_remove_dead_code(struct bpf_verifier_env *env) 18144 { 18145 struct bpf_insn_aux_data *aux_data = env->insn_aux_data; 18146 int insn_cnt = env->prog->len; 18147 int i, err; 18148 18149 for (i = 0; i < insn_cnt; i++) { 18150 int j; 18151 18152 j = 0; 18153 while (i + j < insn_cnt && !aux_data[i + j].seen) 18154 j++; 18155 if (!j) 18156 continue; 18157 18158 err = verifier_remove_insns(env, i, j); 18159 if (err) 18160 return err; 18161 insn_cnt = env->prog->len; 18162 } 18163 18164 return 0; 18165 } 18166 18167 static int opt_remove_nops(struct bpf_verifier_env *env) 18168 { 18169 const struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0); 18170 struct bpf_insn *insn = env->prog->insnsi; 18171 int insn_cnt = env->prog->len; 18172 int i, err; 18173 18174 for (i = 0; i < insn_cnt; i++) { 18175 if (memcmp(&insn[i], &ja, sizeof(ja))) 18176 continue; 18177 18178 err = verifier_remove_insns(env, i, 1); 18179 if (err) 18180 return err; 18181 insn_cnt--; 18182 i--; 18183 } 18184 18185 return 0; 18186 } 18187 18188 static int opt_subreg_zext_lo32_rnd_hi32(struct bpf_verifier_env *env, 18189 const union bpf_attr *attr) 18190 { 18191 struct bpf_insn *patch, zext_patch[2], rnd_hi32_patch[4]; 18192 struct bpf_insn_aux_data *aux = env->insn_aux_data; 18193 int i, patch_len, delta = 0, len = env->prog->len; 18194 struct bpf_insn *insns = env->prog->insnsi; 18195 struct bpf_prog *new_prog; 18196 bool rnd_hi32; 18197 18198 rnd_hi32 = attr->prog_flags & BPF_F_TEST_RND_HI32; 18199 zext_patch[1] = BPF_ZEXT_REG(0); 18200 rnd_hi32_patch[1] = BPF_ALU64_IMM(BPF_MOV, BPF_REG_AX, 0); 18201 rnd_hi32_patch[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_AX, 32); 18202 rnd_hi32_patch[3] = BPF_ALU64_REG(BPF_OR, 0, BPF_REG_AX); 18203 for (i = 0; i < len; i++) { 18204 int adj_idx = i + delta; 18205 struct bpf_insn insn; 18206 int load_reg; 18207 18208 insn = insns[adj_idx]; 18209 load_reg = insn_def_regno(&insn); 18210 if (!aux[adj_idx].zext_dst) { 18211 u8 code, class; 18212 u32 imm_rnd; 18213 18214 if (!rnd_hi32) 18215 continue; 18216 18217 code = insn.code; 18218 class = BPF_CLASS(code); 18219 if (load_reg == -1) 18220 continue; 18221 18222 /* NOTE: arg "reg" (the fourth one) is only used for 18223 * BPF_STX + SRC_OP, so it is safe to pass NULL 18224 * here. 18225 */ 18226 if (is_reg64(env, &insn, load_reg, NULL, DST_OP)) { 18227 if (class == BPF_LD && 18228 BPF_MODE(code) == BPF_IMM) 18229 i++; 18230 continue; 18231 } 18232 18233 /* ctx load could be transformed into wider load. */ 18234 if (class == BPF_LDX && 18235 aux[adj_idx].ptr_type == PTR_TO_CTX) 18236 continue; 18237 18238 imm_rnd = get_random_u32(); 18239 rnd_hi32_patch[0] = insn; 18240 rnd_hi32_patch[1].imm = imm_rnd; 18241 rnd_hi32_patch[3].dst_reg = load_reg; 18242 patch = rnd_hi32_patch; 18243 patch_len = 4; 18244 goto apply_patch_buffer; 18245 } 18246 18247 /* Add in an zero-extend instruction if a) the JIT has requested 18248 * it or b) it's a CMPXCHG. 18249 * 18250 * The latter is because: BPF_CMPXCHG always loads a value into 18251 * R0, therefore always zero-extends. However some archs' 18252 * equivalent instruction only does this load when the 18253 * comparison is successful. This detail of CMPXCHG is 18254 * orthogonal to the general zero-extension behaviour of the 18255 * CPU, so it's treated independently of bpf_jit_needs_zext. 18256 */ 18257 if (!bpf_jit_needs_zext() && !is_cmpxchg_insn(&insn)) 18258 continue; 18259 18260 /* Zero-extension is done by the caller. */ 18261 if (bpf_pseudo_kfunc_call(&insn)) 18262 continue; 18263 18264 if (WARN_ON(load_reg == -1)) { 18265 verbose(env, "verifier bug. zext_dst is set, but no reg is defined\n"); 18266 return -EFAULT; 18267 } 18268 18269 zext_patch[0] = insn; 18270 zext_patch[1].dst_reg = load_reg; 18271 zext_patch[1].src_reg = load_reg; 18272 patch = zext_patch; 18273 patch_len = 2; 18274 apply_patch_buffer: 18275 new_prog = bpf_patch_insn_data(env, adj_idx, patch, patch_len); 18276 if (!new_prog) 18277 return -ENOMEM; 18278 env->prog = new_prog; 18279 insns = new_prog->insnsi; 18280 aux = env->insn_aux_data; 18281 delta += patch_len - 1; 18282 } 18283 18284 return 0; 18285 } 18286 18287 /* convert load instructions that access fields of a context type into a 18288 * sequence of instructions that access fields of the underlying structure: 18289 * struct __sk_buff -> struct sk_buff 18290 * struct bpf_sock_ops -> struct sock 18291 */ 18292 static int convert_ctx_accesses(struct bpf_verifier_env *env) 18293 { 18294 const struct bpf_verifier_ops *ops = env->ops; 18295 int i, cnt, size, ctx_field_size, delta = 0; 18296 const int insn_cnt = env->prog->len; 18297 struct bpf_insn insn_buf[16], *insn; 18298 u32 target_size, size_default, off; 18299 struct bpf_prog *new_prog; 18300 enum bpf_access_type type; 18301 bool is_narrower_load; 18302 18303 if (ops->gen_prologue || env->seen_direct_write) { 18304 if (!ops->gen_prologue) { 18305 verbose(env, "bpf verifier is misconfigured\n"); 18306 return -EINVAL; 18307 } 18308 cnt = ops->gen_prologue(insn_buf, env->seen_direct_write, 18309 env->prog); 18310 if (cnt >= ARRAY_SIZE(insn_buf)) { 18311 verbose(env, "bpf verifier is misconfigured\n"); 18312 return -EINVAL; 18313 } else if (cnt) { 18314 new_prog = bpf_patch_insn_data(env, 0, insn_buf, cnt); 18315 if (!new_prog) 18316 return -ENOMEM; 18317 18318 env->prog = new_prog; 18319 delta += cnt - 1; 18320 } 18321 } 18322 18323 if (bpf_prog_is_offloaded(env->prog->aux)) 18324 return 0; 18325 18326 insn = env->prog->insnsi + delta; 18327 18328 for (i = 0; i < insn_cnt; i++, insn++) { 18329 bpf_convert_ctx_access_t convert_ctx_access; 18330 u8 mode; 18331 18332 if (insn->code == (BPF_LDX | BPF_MEM | BPF_B) || 18333 insn->code == (BPF_LDX | BPF_MEM | BPF_H) || 18334 insn->code == (BPF_LDX | BPF_MEM | BPF_W) || 18335 insn->code == (BPF_LDX | BPF_MEM | BPF_DW) || 18336 insn->code == (BPF_LDX | BPF_MEMSX | BPF_B) || 18337 insn->code == (BPF_LDX | BPF_MEMSX | BPF_H) || 18338 insn->code == (BPF_LDX | BPF_MEMSX | BPF_W)) { 18339 type = BPF_READ; 18340 } else if (insn->code == (BPF_STX | BPF_MEM | BPF_B) || 18341 insn->code == (BPF_STX | BPF_MEM | BPF_H) || 18342 insn->code == (BPF_STX | BPF_MEM | BPF_W) || 18343 insn->code == (BPF_STX | BPF_MEM | BPF_DW) || 18344 insn->code == (BPF_ST | BPF_MEM | BPF_B) || 18345 insn->code == (BPF_ST | BPF_MEM | BPF_H) || 18346 insn->code == (BPF_ST | BPF_MEM | BPF_W) || 18347 insn->code == (BPF_ST | BPF_MEM | BPF_DW)) { 18348 type = BPF_WRITE; 18349 } else { 18350 continue; 18351 } 18352 18353 if (type == BPF_WRITE && 18354 env->insn_aux_data[i + delta].sanitize_stack_spill) { 18355 struct bpf_insn patch[] = { 18356 *insn, 18357 BPF_ST_NOSPEC(), 18358 }; 18359 18360 cnt = ARRAY_SIZE(patch); 18361 new_prog = bpf_patch_insn_data(env, i + delta, patch, cnt); 18362 if (!new_prog) 18363 return -ENOMEM; 18364 18365 delta += cnt - 1; 18366 env->prog = new_prog; 18367 insn = new_prog->insnsi + i + delta; 18368 continue; 18369 } 18370 18371 switch ((int)env->insn_aux_data[i + delta].ptr_type) { 18372 case PTR_TO_CTX: 18373 if (!ops->convert_ctx_access) 18374 continue; 18375 convert_ctx_access = ops->convert_ctx_access; 18376 break; 18377 case PTR_TO_SOCKET: 18378 case PTR_TO_SOCK_COMMON: 18379 convert_ctx_access = bpf_sock_convert_ctx_access; 18380 break; 18381 case PTR_TO_TCP_SOCK: 18382 convert_ctx_access = bpf_tcp_sock_convert_ctx_access; 18383 break; 18384 case PTR_TO_XDP_SOCK: 18385 convert_ctx_access = bpf_xdp_sock_convert_ctx_access; 18386 break; 18387 case PTR_TO_BTF_ID: 18388 case PTR_TO_BTF_ID | PTR_UNTRUSTED: 18389 /* PTR_TO_BTF_ID | MEM_ALLOC always has a valid lifetime, unlike 18390 * PTR_TO_BTF_ID, and an active ref_obj_id, but the same cannot 18391 * be said once it is marked PTR_UNTRUSTED, hence we must handle 18392 * any faults for loads into such types. BPF_WRITE is disallowed 18393 * for this case. 18394 */ 18395 case PTR_TO_BTF_ID | MEM_ALLOC | PTR_UNTRUSTED: 18396 if (type == BPF_READ) { 18397 if (BPF_MODE(insn->code) == BPF_MEM) 18398 insn->code = BPF_LDX | BPF_PROBE_MEM | 18399 BPF_SIZE((insn)->code); 18400 else 18401 insn->code = BPF_LDX | BPF_PROBE_MEMSX | 18402 BPF_SIZE((insn)->code); 18403 env->prog->aux->num_exentries++; 18404 } 18405 continue; 18406 default: 18407 continue; 18408 } 18409 18410 ctx_field_size = env->insn_aux_data[i + delta].ctx_field_size; 18411 size = BPF_LDST_BYTES(insn); 18412 mode = BPF_MODE(insn->code); 18413 18414 /* If the read access is a narrower load of the field, 18415 * convert to a 4/8-byte load, to minimum program type specific 18416 * convert_ctx_access changes. If conversion is successful, 18417 * we will apply proper mask to the result. 18418 */ 18419 is_narrower_load = size < ctx_field_size; 18420 size_default = bpf_ctx_off_adjust_machine(ctx_field_size); 18421 off = insn->off; 18422 if (is_narrower_load) { 18423 u8 size_code; 18424 18425 if (type == BPF_WRITE) { 18426 verbose(env, "bpf verifier narrow ctx access misconfigured\n"); 18427 return -EINVAL; 18428 } 18429 18430 size_code = BPF_H; 18431 if (ctx_field_size == 4) 18432 size_code = BPF_W; 18433 else if (ctx_field_size == 8) 18434 size_code = BPF_DW; 18435 18436 insn->off = off & ~(size_default - 1); 18437 insn->code = BPF_LDX | BPF_MEM | size_code; 18438 } 18439 18440 target_size = 0; 18441 cnt = convert_ctx_access(type, insn, insn_buf, env->prog, 18442 &target_size); 18443 if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf) || 18444 (ctx_field_size && !target_size)) { 18445 verbose(env, "bpf verifier is misconfigured\n"); 18446 return -EINVAL; 18447 } 18448 18449 if (is_narrower_load && size < target_size) { 18450 u8 shift = bpf_ctx_narrow_access_offset( 18451 off, size, size_default) * 8; 18452 if (shift && cnt + 1 >= ARRAY_SIZE(insn_buf)) { 18453 verbose(env, "bpf verifier narrow ctx load misconfigured\n"); 18454 return -EINVAL; 18455 } 18456 if (ctx_field_size <= 4) { 18457 if (shift) 18458 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_RSH, 18459 insn->dst_reg, 18460 shift); 18461 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg, 18462 (1 << size * 8) - 1); 18463 } else { 18464 if (shift) 18465 insn_buf[cnt++] = BPF_ALU64_IMM(BPF_RSH, 18466 insn->dst_reg, 18467 shift); 18468 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg, 18469 (1ULL << size * 8) - 1); 18470 } 18471 } 18472 if (mode == BPF_MEMSX) 18473 insn_buf[cnt++] = BPF_RAW_INSN(BPF_ALU64 | BPF_MOV | BPF_X, 18474 insn->dst_reg, insn->dst_reg, 18475 size * 8, 0); 18476 18477 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 18478 if (!new_prog) 18479 return -ENOMEM; 18480 18481 delta += cnt - 1; 18482 18483 /* keep walking new program and skip insns we just inserted */ 18484 env->prog = new_prog; 18485 insn = new_prog->insnsi + i + delta; 18486 } 18487 18488 return 0; 18489 } 18490 18491 static int jit_subprogs(struct bpf_verifier_env *env) 18492 { 18493 struct bpf_prog *prog = env->prog, **func, *tmp; 18494 int i, j, subprog_start, subprog_end = 0, len, subprog; 18495 struct bpf_map *map_ptr; 18496 struct bpf_insn *insn; 18497 void *old_bpf_func; 18498 int err, num_exentries; 18499 18500 if (env->subprog_cnt <= 1) 18501 return 0; 18502 18503 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) { 18504 if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn)) 18505 continue; 18506 18507 /* Upon error here we cannot fall back to interpreter but 18508 * need a hard reject of the program. Thus -EFAULT is 18509 * propagated in any case. 18510 */ 18511 subprog = find_subprog(env, i + insn->imm + 1); 18512 if (subprog < 0) { 18513 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n", 18514 i + insn->imm + 1); 18515 return -EFAULT; 18516 } 18517 /* temporarily remember subprog id inside insn instead of 18518 * aux_data, since next loop will split up all insns into funcs 18519 */ 18520 insn->off = subprog; 18521 /* remember original imm in case JIT fails and fallback 18522 * to interpreter will be needed 18523 */ 18524 env->insn_aux_data[i].call_imm = insn->imm; 18525 /* point imm to __bpf_call_base+1 from JITs point of view */ 18526 insn->imm = 1; 18527 if (bpf_pseudo_func(insn)) 18528 /* jit (e.g. x86_64) may emit fewer instructions 18529 * if it learns a u32 imm is the same as a u64 imm. 18530 * Force a non zero here. 18531 */ 18532 insn[1].imm = 1; 18533 } 18534 18535 err = bpf_prog_alloc_jited_linfo(prog); 18536 if (err) 18537 goto out_undo_insn; 18538 18539 err = -ENOMEM; 18540 func = kcalloc(env->subprog_cnt, sizeof(prog), GFP_KERNEL); 18541 if (!func) 18542 goto out_undo_insn; 18543 18544 for (i = 0; i < env->subprog_cnt; i++) { 18545 subprog_start = subprog_end; 18546 subprog_end = env->subprog_info[i + 1].start; 18547 18548 len = subprog_end - subprog_start; 18549 /* bpf_prog_run() doesn't call subprogs directly, 18550 * hence main prog stats include the runtime of subprogs. 18551 * subprogs don't have IDs and not reachable via prog_get_next_id 18552 * func[i]->stats will never be accessed and stays NULL 18553 */ 18554 func[i] = bpf_prog_alloc_no_stats(bpf_prog_size(len), GFP_USER); 18555 if (!func[i]) 18556 goto out_free; 18557 memcpy(func[i]->insnsi, &prog->insnsi[subprog_start], 18558 len * sizeof(struct bpf_insn)); 18559 func[i]->type = prog->type; 18560 func[i]->len = len; 18561 if (bpf_prog_calc_tag(func[i])) 18562 goto out_free; 18563 func[i]->is_func = 1; 18564 func[i]->aux->func_idx = i; 18565 /* Below members will be freed only at prog->aux */ 18566 func[i]->aux->btf = prog->aux->btf; 18567 func[i]->aux->func_info = prog->aux->func_info; 18568 func[i]->aux->func_info_cnt = prog->aux->func_info_cnt; 18569 func[i]->aux->poke_tab = prog->aux->poke_tab; 18570 func[i]->aux->size_poke_tab = prog->aux->size_poke_tab; 18571 18572 for (j = 0; j < prog->aux->size_poke_tab; j++) { 18573 struct bpf_jit_poke_descriptor *poke; 18574 18575 poke = &prog->aux->poke_tab[j]; 18576 if (poke->insn_idx < subprog_end && 18577 poke->insn_idx >= subprog_start) 18578 poke->aux = func[i]->aux; 18579 } 18580 18581 func[i]->aux->name[0] = 'F'; 18582 func[i]->aux->stack_depth = env->subprog_info[i].stack_depth; 18583 func[i]->jit_requested = 1; 18584 func[i]->blinding_requested = prog->blinding_requested; 18585 func[i]->aux->kfunc_tab = prog->aux->kfunc_tab; 18586 func[i]->aux->kfunc_btf_tab = prog->aux->kfunc_btf_tab; 18587 func[i]->aux->linfo = prog->aux->linfo; 18588 func[i]->aux->nr_linfo = prog->aux->nr_linfo; 18589 func[i]->aux->jited_linfo = prog->aux->jited_linfo; 18590 func[i]->aux->linfo_idx = env->subprog_info[i].linfo_idx; 18591 num_exentries = 0; 18592 insn = func[i]->insnsi; 18593 for (j = 0; j < func[i]->len; j++, insn++) { 18594 if (BPF_CLASS(insn->code) == BPF_LDX && 18595 (BPF_MODE(insn->code) == BPF_PROBE_MEM || 18596 BPF_MODE(insn->code) == BPF_PROBE_MEMSX)) 18597 num_exentries++; 18598 } 18599 func[i]->aux->num_exentries = num_exentries; 18600 func[i]->aux->tail_call_reachable = env->subprog_info[i].tail_call_reachable; 18601 func[i] = bpf_int_jit_compile(func[i]); 18602 if (!func[i]->jited) { 18603 err = -ENOTSUPP; 18604 goto out_free; 18605 } 18606 cond_resched(); 18607 } 18608 18609 /* at this point all bpf functions were successfully JITed 18610 * now populate all bpf_calls with correct addresses and 18611 * run last pass of JIT 18612 */ 18613 for (i = 0; i < env->subprog_cnt; i++) { 18614 insn = func[i]->insnsi; 18615 for (j = 0; j < func[i]->len; j++, insn++) { 18616 if (bpf_pseudo_func(insn)) { 18617 subprog = insn->off; 18618 insn[0].imm = (u32)(long)func[subprog]->bpf_func; 18619 insn[1].imm = ((u64)(long)func[subprog]->bpf_func) >> 32; 18620 continue; 18621 } 18622 if (!bpf_pseudo_call(insn)) 18623 continue; 18624 subprog = insn->off; 18625 insn->imm = BPF_CALL_IMM(func[subprog]->bpf_func); 18626 } 18627 18628 /* we use the aux data to keep a list of the start addresses 18629 * of the JITed images for each function in the program 18630 * 18631 * for some architectures, such as powerpc64, the imm field 18632 * might not be large enough to hold the offset of the start 18633 * address of the callee's JITed image from __bpf_call_base 18634 * 18635 * in such cases, we can lookup the start address of a callee 18636 * by using its subprog id, available from the off field of 18637 * the call instruction, as an index for this list 18638 */ 18639 func[i]->aux->func = func; 18640 func[i]->aux->func_cnt = env->subprog_cnt; 18641 } 18642 for (i = 0; i < env->subprog_cnt; i++) { 18643 old_bpf_func = func[i]->bpf_func; 18644 tmp = bpf_int_jit_compile(func[i]); 18645 if (tmp != func[i] || func[i]->bpf_func != old_bpf_func) { 18646 verbose(env, "JIT doesn't support bpf-to-bpf calls\n"); 18647 err = -ENOTSUPP; 18648 goto out_free; 18649 } 18650 cond_resched(); 18651 } 18652 18653 /* finally lock prog and jit images for all functions and 18654 * populate kallsysm. Begin at the first subprogram, since 18655 * bpf_prog_load will add the kallsyms for the main program. 18656 */ 18657 for (i = 1; i < env->subprog_cnt; i++) { 18658 bpf_prog_lock_ro(func[i]); 18659 bpf_prog_kallsyms_add(func[i]); 18660 } 18661 18662 /* Last step: make now unused interpreter insns from main 18663 * prog consistent for later dump requests, so they can 18664 * later look the same as if they were interpreted only. 18665 */ 18666 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) { 18667 if (bpf_pseudo_func(insn)) { 18668 insn[0].imm = env->insn_aux_data[i].call_imm; 18669 insn[1].imm = insn->off; 18670 insn->off = 0; 18671 continue; 18672 } 18673 if (!bpf_pseudo_call(insn)) 18674 continue; 18675 insn->off = env->insn_aux_data[i].call_imm; 18676 subprog = find_subprog(env, i + insn->off + 1); 18677 insn->imm = subprog; 18678 } 18679 18680 prog->jited = 1; 18681 prog->bpf_func = func[0]->bpf_func; 18682 prog->jited_len = func[0]->jited_len; 18683 prog->aux->extable = func[0]->aux->extable; 18684 prog->aux->num_exentries = func[0]->aux->num_exentries; 18685 prog->aux->func = func; 18686 prog->aux->func_cnt = env->subprog_cnt; 18687 bpf_prog_jit_attempt_done(prog); 18688 return 0; 18689 out_free: 18690 /* We failed JIT'ing, so at this point we need to unregister poke 18691 * descriptors from subprogs, so that kernel is not attempting to 18692 * patch it anymore as we're freeing the subprog JIT memory. 18693 */ 18694 for (i = 0; i < prog->aux->size_poke_tab; i++) { 18695 map_ptr = prog->aux->poke_tab[i].tail_call.map; 18696 map_ptr->ops->map_poke_untrack(map_ptr, prog->aux); 18697 } 18698 /* At this point we're guaranteed that poke descriptors are not 18699 * live anymore. We can just unlink its descriptor table as it's 18700 * released with the main prog. 18701 */ 18702 for (i = 0; i < env->subprog_cnt; i++) { 18703 if (!func[i]) 18704 continue; 18705 func[i]->aux->poke_tab = NULL; 18706 bpf_jit_free(func[i]); 18707 } 18708 kfree(func); 18709 out_undo_insn: 18710 /* cleanup main prog to be interpreted */ 18711 prog->jit_requested = 0; 18712 prog->blinding_requested = 0; 18713 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) { 18714 if (!bpf_pseudo_call(insn)) 18715 continue; 18716 insn->off = 0; 18717 insn->imm = env->insn_aux_data[i].call_imm; 18718 } 18719 bpf_prog_jit_attempt_done(prog); 18720 return err; 18721 } 18722 18723 static int fixup_call_args(struct bpf_verifier_env *env) 18724 { 18725 #ifndef CONFIG_BPF_JIT_ALWAYS_ON 18726 struct bpf_prog *prog = env->prog; 18727 struct bpf_insn *insn = prog->insnsi; 18728 bool has_kfunc_call = bpf_prog_has_kfunc_call(prog); 18729 int i, depth; 18730 #endif 18731 int err = 0; 18732 18733 if (env->prog->jit_requested && 18734 !bpf_prog_is_offloaded(env->prog->aux)) { 18735 err = jit_subprogs(env); 18736 if (err == 0) 18737 return 0; 18738 if (err == -EFAULT) 18739 return err; 18740 } 18741 #ifndef CONFIG_BPF_JIT_ALWAYS_ON 18742 if (has_kfunc_call) { 18743 verbose(env, "calling kernel functions are not allowed in non-JITed programs\n"); 18744 return -EINVAL; 18745 } 18746 if (env->subprog_cnt > 1 && env->prog->aux->tail_call_reachable) { 18747 /* When JIT fails the progs with bpf2bpf calls and tail_calls 18748 * have to be rejected, since interpreter doesn't support them yet. 18749 */ 18750 verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n"); 18751 return -EINVAL; 18752 } 18753 for (i = 0; i < prog->len; i++, insn++) { 18754 if (bpf_pseudo_func(insn)) { 18755 /* When JIT fails the progs with callback calls 18756 * have to be rejected, since interpreter doesn't support them yet. 18757 */ 18758 verbose(env, "callbacks are not allowed in non-JITed programs\n"); 18759 return -EINVAL; 18760 } 18761 18762 if (!bpf_pseudo_call(insn)) 18763 continue; 18764 depth = get_callee_stack_depth(env, insn, i); 18765 if (depth < 0) 18766 return depth; 18767 bpf_patch_call_args(insn, depth); 18768 } 18769 err = 0; 18770 #endif 18771 return err; 18772 } 18773 18774 /* replace a generic kfunc with a specialized version if necessary */ 18775 static void specialize_kfunc(struct bpf_verifier_env *env, 18776 u32 func_id, u16 offset, unsigned long *addr) 18777 { 18778 struct bpf_prog *prog = env->prog; 18779 bool seen_direct_write; 18780 void *xdp_kfunc; 18781 bool is_rdonly; 18782 18783 if (bpf_dev_bound_kfunc_id(func_id)) { 18784 xdp_kfunc = bpf_dev_bound_resolve_kfunc(prog, func_id); 18785 if (xdp_kfunc) { 18786 *addr = (unsigned long)xdp_kfunc; 18787 return; 18788 } 18789 /* fallback to default kfunc when not supported by netdev */ 18790 } 18791 18792 if (offset) 18793 return; 18794 18795 if (func_id == special_kfunc_list[KF_bpf_dynptr_from_skb]) { 18796 seen_direct_write = env->seen_direct_write; 18797 is_rdonly = !may_access_direct_pkt_data(env, NULL, BPF_WRITE); 18798 18799 if (is_rdonly) 18800 *addr = (unsigned long)bpf_dynptr_from_skb_rdonly; 18801 18802 /* restore env->seen_direct_write to its original value, since 18803 * may_access_direct_pkt_data mutates it 18804 */ 18805 env->seen_direct_write = seen_direct_write; 18806 } 18807 } 18808 18809 static void __fixup_collection_insert_kfunc(struct bpf_insn_aux_data *insn_aux, 18810 u16 struct_meta_reg, 18811 u16 node_offset_reg, 18812 struct bpf_insn *insn, 18813 struct bpf_insn *insn_buf, 18814 int *cnt) 18815 { 18816 struct btf_struct_meta *kptr_struct_meta = insn_aux->kptr_struct_meta; 18817 struct bpf_insn addr[2] = { BPF_LD_IMM64(struct_meta_reg, (long)kptr_struct_meta) }; 18818 18819 insn_buf[0] = addr[0]; 18820 insn_buf[1] = addr[1]; 18821 insn_buf[2] = BPF_MOV64_IMM(node_offset_reg, insn_aux->insert_off); 18822 insn_buf[3] = *insn; 18823 *cnt = 4; 18824 } 18825 18826 static int fixup_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn, 18827 struct bpf_insn *insn_buf, int insn_idx, int *cnt) 18828 { 18829 const struct bpf_kfunc_desc *desc; 18830 18831 if (!insn->imm) { 18832 verbose(env, "invalid kernel function call not eliminated in verifier pass\n"); 18833 return -EINVAL; 18834 } 18835 18836 *cnt = 0; 18837 18838 /* insn->imm has the btf func_id. Replace it with an offset relative to 18839 * __bpf_call_base, unless the JIT needs to call functions that are 18840 * further than 32 bits away (bpf_jit_supports_far_kfunc_call()). 18841 */ 18842 desc = find_kfunc_desc(env->prog, insn->imm, insn->off); 18843 if (!desc) { 18844 verbose(env, "verifier internal error: kernel function descriptor not found for func_id %u\n", 18845 insn->imm); 18846 return -EFAULT; 18847 } 18848 18849 if (!bpf_jit_supports_far_kfunc_call()) 18850 insn->imm = BPF_CALL_IMM(desc->addr); 18851 if (insn->off) 18852 return 0; 18853 if (desc->func_id == special_kfunc_list[KF_bpf_obj_new_impl]) { 18854 struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta; 18855 struct bpf_insn addr[2] = { BPF_LD_IMM64(BPF_REG_2, (long)kptr_struct_meta) }; 18856 u64 obj_new_size = env->insn_aux_data[insn_idx].obj_new_size; 18857 18858 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_1, obj_new_size); 18859 insn_buf[1] = addr[0]; 18860 insn_buf[2] = addr[1]; 18861 insn_buf[3] = *insn; 18862 *cnt = 4; 18863 } else if (desc->func_id == special_kfunc_list[KF_bpf_obj_drop_impl] || 18864 desc->func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl]) { 18865 struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta; 18866 struct bpf_insn addr[2] = { BPF_LD_IMM64(BPF_REG_2, (long)kptr_struct_meta) }; 18867 18868 if (desc->func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl] && 18869 !kptr_struct_meta) { 18870 verbose(env, "verifier internal error: kptr_struct_meta expected at insn_idx %d\n", 18871 insn_idx); 18872 return -EFAULT; 18873 } 18874 18875 insn_buf[0] = addr[0]; 18876 insn_buf[1] = addr[1]; 18877 insn_buf[2] = *insn; 18878 *cnt = 3; 18879 } else if (desc->func_id == special_kfunc_list[KF_bpf_list_push_back_impl] || 18880 desc->func_id == special_kfunc_list[KF_bpf_list_push_front_impl] || 18881 desc->func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) { 18882 struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta; 18883 int struct_meta_reg = BPF_REG_3; 18884 int node_offset_reg = BPF_REG_4; 18885 18886 /* rbtree_add has extra 'less' arg, so args-to-fixup are in diff regs */ 18887 if (desc->func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) { 18888 struct_meta_reg = BPF_REG_4; 18889 node_offset_reg = BPF_REG_5; 18890 } 18891 18892 if (!kptr_struct_meta) { 18893 verbose(env, "verifier internal error: kptr_struct_meta expected at insn_idx %d\n", 18894 insn_idx); 18895 return -EFAULT; 18896 } 18897 18898 __fixup_collection_insert_kfunc(&env->insn_aux_data[insn_idx], struct_meta_reg, 18899 node_offset_reg, insn, insn_buf, cnt); 18900 } else if (desc->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx] || 18901 desc->func_id == special_kfunc_list[KF_bpf_rdonly_cast]) { 18902 insn_buf[0] = BPF_MOV64_REG(BPF_REG_0, BPF_REG_1); 18903 *cnt = 1; 18904 } 18905 return 0; 18906 } 18907 18908 /* Do various post-verification rewrites in a single program pass. 18909 * These rewrites simplify JIT and interpreter implementations. 18910 */ 18911 static int do_misc_fixups(struct bpf_verifier_env *env) 18912 { 18913 struct bpf_prog *prog = env->prog; 18914 enum bpf_attach_type eatype = prog->expected_attach_type; 18915 enum bpf_prog_type prog_type = resolve_prog_type(prog); 18916 struct bpf_insn *insn = prog->insnsi; 18917 const struct bpf_func_proto *fn; 18918 const int insn_cnt = prog->len; 18919 const struct bpf_map_ops *ops; 18920 struct bpf_insn_aux_data *aux; 18921 struct bpf_insn insn_buf[16]; 18922 struct bpf_prog *new_prog; 18923 struct bpf_map *map_ptr; 18924 int i, ret, cnt, delta = 0; 18925 18926 for (i = 0; i < insn_cnt; i++, insn++) { 18927 /* Make divide-by-zero exceptions impossible. */ 18928 if (insn->code == (BPF_ALU64 | BPF_MOD | BPF_X) || 18929 insn->code == (BPF_ALU64 | BPF_DIV | BPF_X) || 18930 insn->code == (BPF_ALU | BPF_MOD | BPF_X) || 18931 insn->code == (BPF_ALU | BPF_DIV | BPF_X)) { 18932 bool is64 = BPF_CLASS(insn->code) == BPF_ALU64; 18933 bool isdiv = BPF_OP(insn->code) == BPF_DIV; 18934 struct bpf_insn *patchlet; 18935 struct bpf_insn chk_and_div[] = { 18936 /* [R,W]x div 0 -> 0 */ 18937 BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) | 18938 BPF_JNE | BPF_K, insn->src_reg, 18939 0, 2, 0), 18940 BPF_ALU32_REG(BPF_XOR, insn->dst_reg, insn->dst_reg), 18941 BPF_JMP_IMM(BPF_JA, 0, 0, 1), 18942 *insn, 18943 }; 18944 struct bpf_insn chk_and_mod[] = { 18945 /* [R,W]x mod 0 -> [R,W]x */ 18946 BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) | 18947 BPF_JEQ | BPF_K, insn->src_reg, 18948 0, 1 + (is64 ? 0 : 1), 0), 18949 *insn, 18950 BPF_JMP_IMM(BPF_JA, 0, 0, 1), 18951 BPF_MOV32_REG(insn->dst_reg, insn->dst_reg), 18952 }; 18953 18954 patchlet = isdiv ? chk_and_div : chk_and_mod; 18955 cnt = isdiv ? ARRAY_SIZE(chk_and_div) : 18956 ARRAY_SIZE(chk_and_mod) - (is64 ? 2 : 0); 18957 18958 new_prog = bpf_patch_insn_data(env, i + delta, patchlet, cnt); 18959 if (!new_prog) 18960 return -ENOMEM; 18961 18962 delta += cnt - 1; 18963 env->prog = prog = new_prog; 18964 insn = new_prog->insnsi + i + delta; 18965 continue; 18966 } 18967 18968 /* Implement LD_ABS and LD_IND with a rewrite, if supported by the program type. */ 18969 if (BPF_CLASS(insn->code) == BPF_LD && 18970 (BPF_MODE(insn->code) == BPF_ABS || 18971 BPF_MODE(insn->code) == BPF_IND)) { 18972 cnt = env->ops->gen_ld_abs(insn, insn_buf); 18973 if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf)) { 18974 verbose(env, "bpf verifier is misconfigured\n"); 18975 return -EINVAL; 18976 } 18977 18978 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 18979 if (!new_prog) 18980 return -ENOMEM; 18981 18982 delta += cnt - 1; 18983 env->prog = prog = new_prog; 18984 insn = new_prog->insnsi + i + delta; 18985 continue; 18986 } 18987 18988 /* Rewrite pointer arithmetic to mitigate speculation attacks. */ 18989 if (insn->code == (BPF_ALU64 | BPF_ADD | BPF_X) || 18990 insn->code == (BPF_ALU64 | BPF_SUB | BPF_X)) { 18991 const u8 code_add = BPF_ALU64 | BPF_ADD | BPF_X; 18992 const u8 code_sub = BPF_ALU64 | BPF_SUB | BPF_X; 18993 struct bpf_insn *patch = &insn_buf[0]; 18994 bool issrc, isneg, isimm; 18995 u32 off_reg; 18996 18997 aux = &env->insn_aux_data[i + delta]; 18998 if (!aux->alu_state || 18999 aux->alu_state == BPF_ALU_NON_POINTER) 19000 continue; 19001 19002 isneg = aux->alu_state & BPF_ALU_NEG_VALUE; 19003 issrc = (aux->alu_state & BPF_ALU_SANITIZE) == 19004 BPF_ALU_SANITIZE_SRC; 19005 isimm = aux->alu_state & BPF_ALU_IMMEDIATE; 19006 19007 off_reg = issrc ? insn->src_reg : insn->dst_reg; 19008 if (isimm) { 19009 *patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit); 19010 } else { 19011 if (isneg) 19012 *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1); 19013 *patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit); 19014 *patch++ = BPF_ALU64_REG(BPF_SUB, BPF_REG_AX, off_reg); 19015 *patch++ = BPF_ALU64_REG(BPF_OR, BPF_REG_AX, off_reg); 19016 *patch++ = BPF_ALU64_IMM(BPF_NEG, BPF_REG_AX, 0); 19017 *patch++ = BPF_ALU64_IMM(BPF_ARSH, BPF_REG_AX, 63); 19018 *patch++ = BPF_ALU64_REG(BPF_AND, BPF_REG_AX, off_reg); 19019 } 19020 if (!issrc) 19021 *patch++ = BPF_MOV64_REG(insn->dst_reg, insn->src_reg); 19022 insn->src_reg = BPF_REG_AX; 19023 if (isneg) 19024 insn->code = insn->code == code_add ? 19025 code_sub : code_add; 19026 *patch++ = *insn; 19027 if (issrc && isneg && !isimm) 19028 *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1); 19029 cnt = patch - insn_buf; 19030 19031 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 19032 if (!new_prog) 19033 return -ENOMEM; 19034 19035 delta += cnt - 1; 19036 env->prog = prog = new_prog; 19037 insn = new_prog->insnsi + i + delta; 19038 continue; 19039 } 19040 19041 if (insn->code != (BPF_JMP | BPF_CALL)) 19042 continue; 19043 if (insn->src_reg == BPF_PSEUDO_CALL) 19044 continue; 19045 if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) { 19046 ret = fixup_kfunc_call(env, insn, insn_buf, i + delta, &cnt); 19047 if (ret) 19048 return ret; 19049 if (cnt == 0) 19050 continue; 19051 19052 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 19053 if (!new_prog) 19054 return -ENOMEM; 19055 19056 delta += cnt - 1; 19057 env->prog = prog = new_prog; 19058 insn = new_prog->insnsi + i + delta; 19059 continue; 19060 } 19061 19062 if (insn->imm == BPF_FUNC_get_route_realm) 19063 prog->dst_needed = 1; 19064 if (insn->imm == BPF_FUNC_get_prandom_u32) 19065 bpf_user_rnd_init_once(); 19066 if (insn->imm == BPF_FUNC_override_return) 19067 prog->kprobe_override = 1; 19068 if (insn->imm == BPF_FUNC_tail_call) { 19069 /* If we tail call into other programs, we 19070 * cannot make any assumptions since they can 19071 * be replaced dynamically during runtime in 19072 * the program array. 19073 */ 19074 prog->cb_access = 1; 19075 if (!allow_tail_call_in_subprogs(env)) 19076 prog->aux->stack_depth = MAX_BPF_STACK; 19077 prog->aux->max_pkt_offset = MAX_PACKET_OFF; 19078 19079 /* mark bpf_tail_call as different opcode to avoid 19080 * conditional branch in the interpreter for every normal 19081 * call and to prevent accidental JITing by JIT compiler 19082 * that doesn't support bpf_tail_call yet 19083 */ 19084 insn->imm = 0; 19085 insn->code = BPF_JMP | BPF_TAIL_CALL; 19086 19087 aux = &env->insn_aux_data[i + delta]; 19088 if (env->bpf_capable && !prog->blinding_requested && 19089 prog->jit_requested && 19090 !bpf_map_key_poisoned(aux) && 19091 !bpf_map_ptr_poisoned(aux) && 19092 !bpf_map_ptr_unpriv(aux)) { 19093 struct bpf_jit_poke_descriptor desc = { 19094 .reason = BPF_POKE_REASON_TAIL_CALL, 19095 .tail_call.map = BPF_MAP_PTR(aux->map_ptr_state), 19096 .tail_call.key = bpf_map_key_immediate(aux), 19097 .insn_idx = i + delta, 19098 }; 19099 19100 ret = bpf_jit_add_poke_descriptor(prog, &desc); 19101 if (ret < 0) { 19102 verbose(env, "adding tail call poke descriptor failed\n"); 19103 return ret; 19104 } 19105 19106 insn->imm = ret + 1; 19107 continue; 19108 } 19109 19110 if (!bpf_map_ptr_unpriv(aux)) 19111 continue; 19112 19113 /* instead of changing every JIT dealing with tail_call 19114 * emit two extra insns: 19115 * if (index >= max_entries) goto out; 19116 * index &= array->index_mask; 19117 * to avoid out-of-bounds cpu speculation 19118 */ 19119 if (bpf_map_ptr_poisoned(aux)) { 19120 verbose(env, "tail_call abusing map_ptr\n"); 19121 return -EINVAL; 19122 } 19123 19124 map_ptr = BPF_MAP_PTR(aux->map_ptr_state); 19125 insn_buf[0] = BPF_JMP_IMM(BPF_JGE, BPF_REG_3, 19126 map_ptr->max_entries, 2); 19127 insn_buf[1] = BPF_ALU32_IMM(BPF_AND, BPF_REG_3, 19128 container_of(map_ptr, 19129 struct bpf_array, 19130 map)->index_mask); 19131 insn_buf[2] = *insn; 19132 cnt = 3; 19133 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 19134 if (!new_prog) 19135 return -ENOMEM; 19136 19137 delta += cnt - 1; 19138 env->prog = prog = new_prog; 19139 insn = new_prog->insnsi + i + delta; 19140 continue; 19141 } 19142 19143 if (insn->imm == BPF_FUNC_timer_set_callback) { 19144 /* The verifier will process callback_fn as many times as necessary 19145 * with different maps and the register states prepared by 19146 * set_timer_callback_state will be accurate. 19147 * 19148 * The following use case is valid: 19149 * map1 is shared by prog1, prog2, prog3. 19150 * prog1 calls bpf_timer_init for some map1 elements 19151 * prog2 calls bpf_timer_set_callback for some map1 elements. 19152 * Those that were not bpf_timer_init-ed will return -EINVAL. 19153 * prog3 calls bpf_timer_start for some map1 elements. 19154 * Those that were not both bpf_timer_init-ed and 19155 * bpf_timer_set_callback-ed will return -EINVAL. 19156 */ 19157 struct bpf_insn ld_addrs[2] = { 19158 BPF_LD_IMM64(BPF_REG_3, (long)prog->aux), 19159 }; 19160 19161 insn_buf[0] = ld_addrs[0]; 19162 insn_buf[1] = ld_addrs[1]; 19163 insn_buf[2] = *insn; 19164 cnt = 3; 19165 19166 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 19167 if (!new_prog) 19168 return -ENOMEM; 19169 19170 delta += cnt - 1; 19171 env->prog = prog = new_prog; 19172 insn = new_prog->insnsi + i + delta; 19173 goto patch_call_imm; 19174 } 19175 19176 if (is_storage_get_function(insn->imm)) { 19177 if (!env->prog->aux->sleepable || 19178 env->insn_aux_data[i + delta].storage_get_func_atomic) 19179 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_5, (__force __s32)GFP_ATOMIC); 19180 else 19181 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_5, (__force __s32)GFP_KERNEL); 19182 insn_buf[1] = *insn; 19183 cnt = 2; 19184 19185 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 19186 if (!new_prog) 19187 return -ENOMEM; 19188 19189 delta += cnt - 1; 19190 env->prog = prog = new_prog; 19191 insn = new_prog->insnsi + i + delta; 19192 goto patch_call_imm; 19193 } 19194 19195 /* BPF_EMIT_CALL() assumptions in some of the map_gen_lookup 19196 * and other inlining handlers are currently limited to 64 bit 19197 * only. 19198 */ 19199 if (prog->jit_requested && BITS_PER_LONG == 64 && 19200 (insn->imm == BPF_FUNC_map_lookup_elem || 19201 insn->imm == BPF_FUNC_map_update_elem || 19202 insn->imm == BPF_FUNC_map_delete_elem || 19203 insn->imm == BPF_FUNC_map_push_elem || 19204 insn->imm == BPF_FUNC_map_pop_elem || 19205 insn->imm == BPF_FUNC_map_peek_elem || 19206 insn->imm == BPF_FUNC_redirect_map || 19207 insn->imm == BPF_FUNC_for_each_map_elem || 19208 insn->imm == BPF_FUNC_map_lookup_percpu_elem)) { 19209 aux = &env->insn_aux_data[i + delta]; 19210 if (bpf_map_ptr_poisoned(aux)) 19211 goto patch_call_imm; 19212 19213 map_ptr = BPF_MAP_PTR(aux->map_ptr_state); 19214 ops = map_ptr->ops; 19215 if (insn->imm == BPF_FUNC_map_lookup_elem && 19216 ops->map_gen_lookup) { 19217 cnt = ops->map_gen_lookup(map_ptr, insn_buf); 19218 if (cnt == -EOPNOTSUPP) 19219 goto patch_map_ops_generic; 19220 if (cnt <= 0 || cnt >= ARRAY_SIZE(insn_buf)) { 19221 verbose(env, "bpf verifier is misconfigured\n"); 19222 return -EINVAL; 19223 } 19224 19225 new_prog = bpf_patch_insn_data(env, i + delta, 19226 insn_buf, cnt); 19227 if (!new_prog) 19228 return -ENOMEM; 19229 19230 delta += cnt - 1; 19231 env->prog = prog = new_prog; 19232 insn = new_prog->insnsi + i + delta; 19233 continue; 19234 } 19235 19236 BUILD_BUG_ON(!__same_type(ops->map_lookup_elem, 19237 (void *(*)(struct bpf_map *map, void *key))NULL)); 19238 BUILD_BUG_ON(!__same_type(ops->map_delete_elem, 19239 (long (*)(struct bpf_map *map, void *key))NULL)); 19240 BUILD_BUG_ON(!__same_type(ops->map_update_elem, 19241 (long (*)(struct bpf_map *map, void *key, void *value, 19242 u64 flags))NULL)); 19243 BUILD_BUG_ON(!__same_type(ops->map_push_elem, 19244 (long (*)(struct bpf_map *map, void *value, 19245 u64 flags))NULL)); 19246 BUILD_BUG_ON(!__same_type(ops->map_pop_elem, 19247 (long (*)(struct bpf_map *map, void *value))NULL)); 19248 BUILD_BUG_ON(!__same_type(ops->map_peek_elem, 19249 (long (*)(struct bpf_map *map, void *value))NULL)); 19250 BUILD_BUG_ON(!__same_type(ops->map_redirect, 19251 (long (*)(struct bpf_map *map, u64 index, u64 flags))NULL)); 19252 BUILD_BUG_ON(!__same_type(ops->map_for_each_callback, 19253 (long (*)(struct bpf_map *map, 19254 bpf_callback_t callback_fn, 19255 void *callback_ctx, 19256 u64 flags))NULL)); 19257 BUILD_BUG_ON(!__same_type(ops->map_lookup_percpu_elem, 19258 (void *(*)(struct bpf_map *map, void *key, u32 cpu))NULL)); 19259 19260 patch_map_ops_generic: 19261 switch (insn->imm) { 19262 case BPF_FUNC_map_lookup_elem: 19263 insn->imm = BPF_CALL_IMM(ops->map_lookup_elem); 19264 continue; 19265 case BPF_FUNC_map_update_elem: 19266 insn->imm = BPF_CALL_IMM(ops->map_update_elem); 19267 continue; 19268 case BPF_FUNC_map_delete_elem: 19269 insn->imm = BPF_CALL_IMM(ops->map_delete_elem); 19270 continue; 19271 case BPF_FUNC_map_push_elem: 19272 insn->imm = BPF_CALL_IMM(ops->map_push_elem); 19273 continue; 19274 case BPF_FUNC_map_pop_elem: 19275 insn->imm = BPF_CALL_IMM(ops->map_pop_elem); 19276 continue; 19277 case BPF_FUNC_map_peek_elem: 19278 insn->imm = BPF_CALL_IMM(ops->map_peek_elem); 19279 continue; 19280 case BPF_FUNC_redirect_map: 19281 insn->imm = BPF_CALL_IMM(ops->map_redirect); 19282 continue; 19283 case BPF_FUNC_for_each_map_elem: 19284 insn->imm = BPF_CALL_IMM(ops->map_for_each_callback); 19285 continue; 19286 case BPF_FUNC_map_lookup_percpu_elem: 19287 insn->imm = BPF_CALL_IMM(ops->map_lookup_percpu_elem); 19288 continue; 19289 } 19290 19291 goto patch_call_imm; 19292 } 19293 19294 /* Implement bpf_jiffies64 inline. */ 19295 if (prog->jit_requested && BITS_PER_LONG == 64 && 19296 insn->imm == BPF_FUNC_jiffies64) { 19297 struct bpf_insn ld_jiffies_addr[2] = { 19298 BPF_LD_IMM64(BPF_REG_0, 19299 (unsigned long)&jiffies), 19300 }; 19301 19302 insn_buf[0] = ld_jiffies_addr[0]; 19303 insn_buf[1] = ld_jiffies_addr[1]; 19304 insn_buf[2] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, 19305 BPF_REG_0, 0); 19306 cnt = 3; 19307 19308 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 19309 cnt); 19310 if (!new_prog) 19311 return -ENOMEM; 19312 19313 delta += cnt - 1; 19314 env->prog = prog = new_prog; 19315 insn = new_prog->insnsi + i + delta; 19316 continue; 19317 } 19318 19319 /* Implement bpf_get_func_arg inline. */ 19320 if (prog_type == BPF_PROG_TYPE_TRACING && 19321 insn->imm == BPF_FUNC_get_func_arg) { 19322 /* Load nr_args from ctx - 8 */ 19323 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8); 19324 insn_buf[1] = BPF_JMP32_REG(BPF_JGE, BPF_REG_2, BPF_REG_0, 6); 19325 insn_buf[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_2, 3); 19326 insn_buf[3] = BPF_ALU64_REG(BPF_ADD, BPF_REG_2, BPF_REG_1); 19327 insn_buf[4] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_2, 0); 19328 insn_buf[5] = BPF_STX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0); 19329 insn_buf[6] = BPF_MOV64_IMM(BPF_REG_0, 0); 19330 insn_buf[7] = BPF_JMP_A(1); 19331 insn_buf[8] = BPF_MOV64_IMM(BPF_REG_0, -EINVAL); 19332 cnt = 9; 19333 19334 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 19335 if (!new_prog) 19336 return -ENOMEM; 19337 19338 delta += cnt - 1; 19339 env->prog = prog = new_prog; 19340 insn = new_prog->insnsi + i + delta; 19341 continue; 19342 } 19343 19344 /* Implement bpf_get_func_ret inline. */ 19345 if (prog_type == BPF_PROG_TYPE_TRACING && 19346 insn->imm == BPF_FUNC_get_func_ret) { 19347 if (eatype == BPF_TRACE_FEXIT || 19348 eatype == BPF_MODIFY_RETURN) { 19349 /* Load nr_args from ctx - 8 */ 19350 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8); 19351 insn_buf[1] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_0, 3); 19352 insn_buf[2] = BPF_ALU64_REG(BPF_ADD, BPF_REG_0, BPF_REG_1); 19353 insn_buf[3] = BPF_LDX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0); 19354 insn_buf[4] = BPF_STX_MEM(BPF_DW, BPF_REG_2, BPF_REG_3, 0); 19355 insn_buf[5] = BPF_MOV64_IMM(BPF_REG_0, 0); 19356 cnt = 6; 19357 } else { 19358 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_0, -EOPNOTSUPP); 19359 cnt = 1; 19360 } 19361 19362 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 19363 if (!new_prog) 19364 return -ENOMEM; 19365 19366 delta += cnt - 1; 19367 env->prog = prog = new_prog; 19368 insn = new_prog->insnsi + i + delta; 19369 continue; 19370 } 19371 19372 /* Implement get_func_arg_cnt inline. */ 19373 if (prog_type == BPF_PROG_TYPE_TRACING && 19374 insn->imm == BPF_FUNC_get_func_arg_cnt) { 19375 /* Load nr_args from ctx - 8 */ 19376 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8); 19377 19378 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1); 19379 if (!new_prog) 19380 return -ENOMEM; 19381 19382 env->prog = prog = new_prog; 19383 insn = new_prog->insnsi + i + delta; 19384 continue; 19385 } 19386 19387 /* Implement bpf_get_func_ip inline. */ 19388 if (prog_type == BPF_PROG_TYPE_TRACING && 19389 insn->imm == BPF_FUNC_get_func_ip) { 19390 /* Load IP address from ctx - 16 */ 19391 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -16); 19392 19393 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1); 19394 if (!new_prog) 19395 return -ENOMEM; 19396 19397 env->prog = prog = new_prog; 19398 insn = new_prog->insnsi + i + delta; 19399 continue; 19400 } 19401 19402 patch_call_imm: 19403 fn = env->ops->get_func_proto(insn->imm, env->prog); 19404 /* all functions that have prototype and verifier allowed 19405 * programs to call them, must be real in-kernel functions 19406 */ 19407 if (!fn->func) { 19408 verbose(env, 19409 "kernel subsystem misconfigured func %s#%d\n", 19410 func_id_name(insn->imm), insn->imm); 19411 return -EFAULT; 19412 } 19413 insn->imm = fn->func - __bpf_call_base; 19414 } 19415 19416 /* Since poke tab is now finalized, publish aux to tracker. */ 19417 for (i = 0; i < prog->aux->size_poke_tab; i++) { 19418 map_ptr = prog->aux->poke_tab[i].tail_call.map; 19419 if (!map_ptr->ops->map_poke_track || 19420 !map_ptr->ops->map_poke_untrack || 19421 !map_ptr->ops->map_poke_run) { 19422 verbose(env, "bpf verifier is misconfigured\n"); 19423 return -EINVAL; 19424 } 19425 19426 ret = map_ptr->ops->map_poke_track(map_ptr, prog->aux); 19427 if (ret < 0) { 19428 verbose(env, "tracking tail call prog failed\n"); 19429 return ret; 19430 } 19431 } 19432 19433 sort_kfunc_descs_by_imm_off(env->prog); 19434 19435 return 0; 19436 } 19437 19438 static struct bpf_prog *inline_bpf_loop(struct bpf_verifier_env *env, 19439 int position, 19440 s32 stack_base, 19441 u32 callback_subprogno, 19442 u32 *cnt) 19443 { 19444 s32 r6_offset = stack_base + 0 * BPF_REG_SIZE; 19445 s32 r7_offset = stack_base + 1 * BPF_REG_SIZE; 19446 s32 r8_offset = stack_base + 2 * BPF_REG_SIZE; 19447 int reg_loop_max = BPF_REG_6; 19448 int reg_loop_cnt = BPF_REG_7; 19449 int reg_loop_ctx = BPF_REG_8; 19450 19451 struct bpf_prog *new_prog; 19452 u32 callback_start; 19453 u32 call_insn_offset; 19454 s32 callback_offset; 19455 19456 /* This represents an inlined version of bpf_iter.c:bpf_loop, 19457 * be careful to modify this code in sync. 19458 */ 19459 struct bpf_insn insn_buf[] = { 19460 /* Return error and jump to the end of the patch if 19461 * expected number of iterations is too big. 19462 */ 19463 BPF_JMP_IMM(BPF_JLE, BPF_REG_1, BPF_MAX_LOOPS, 2), 19464 BPF_MOV32_IMM(BPF_REG_0, -E2BIG), 19465 BPF_JMP_IMM(BPF_JA, 0, 0, 16), 19466 /* spill R6, R7, R8 to use these as loop vars */ 19467 BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_6, r6_offset), 19468 BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_7, r7_offset), 19469 BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_8, r8_offset), 19470 /* initialize loop vars */ 19471 BPF_MOV64_REG(reg_loop_max, BPF_REG_1), 19472 BPF_MOV32_IMM(reg_loop_cnt, 0), 19473 BPF_MOV64_REG(reg_loop_ctx, BPF_REG_3), 19474 /* loop header, 19475 * if reg_loop_cnt >= reg_loop_max skip the loop body 19476 */ 19477 BPF_JMP_REG(BPF_JGE, reg_loop_cnt, reg_loop_max, 5), 19478 /* callback call, 19479 * correct callback offset would be set after patching 19480 */ 19481 BPF_MOV64_REG(BPF_REG_1, reg_loop_cnt), 19482 BPF_MOV64_REG(BPF_REG_2, reg_loop_ctx), 19483 BPF_CALL_REL(0), 19484 /* increment loop counter */ 19485 BPF_ALU64_IMM(BPF_ADD, reg_loop_cnt, 1), 19486 /* jump to loop header if callback returned 0 */ 19487 BPF_JMP_IMM(BPF_JEQ, BPF_REG_0, 0, -6), 19488 /* return value of bpf_loop, 19489 * set R0 to the number of iterations 19490 */ 19491 BPF_MOV64_REG(BPF_REG_0, reg_loop_cnt), 19492 /* restore original values of R6, R7, R8 */ 19493 BPF_LDX_MEM(BPF_DW, BPF_REG_6, BPF_REG_10, r6_offset), 19494 BPF_LDX_MEM(BPF_DW, BPF_REG_7, BPF_REG_10, r7_offset), 19495 BPF_LDX_MEM(BPF_DW, BPF_REG_8, BPF_REG_10, r8_offset), 19496 }; 19497 19498 *cnt = ARRAY_SIZE(insn_buf); 19499 new_prog = bpf_patch_insn_data(env, position, insn_buf, *cnt); 19500 if (!new_prog) 19501 return new_prog; 19502 19503 /* callback start is known only after patching */ 19504 callback_start = env->subprog_info[callback_subprogno].start; 19505 /* Note: insn_buf[12] is an offset of BPF_CALL_REL instruction */ 19506 call_insn_offset = position + 12; 19507 callback_offset = callback_start - call_insn_offset - 1; 19508 new_prog->insnsi[call_insn_offset].imm = callback_offset; 19509 19510 return new_prog; 19511 } 19512 19513 static bool is_bpf_loop_call(struct bpf_insn *insn) 19514 { 19515 return insn->code == (BPF_JMP | BPF_CALL) && 19516 insn->src_reg == 0 && 19517 insn->imm == BPF_FUNC_loop; 19518 } 19519 19520 /* For all sub-programs in the program (including main) check 19521 * insn_aux_data to see if there are bpf_loop calls that require 19522 * inlining. If such calls are found the calls are replaced with a 19523 * sequence of instructions produced by `inline_bpf_loop` function and 19524 * subprog stack_depth is increased by the size of 3 registers. 19525 * This stack space is used to spill values of the R6, R7, R8. These 19526 * registers are used to store the loop bound, counter and context 19527 * variables. 19528 */ 19529 static int optimize_bpf_loop(struct bpf_verifier_env *env) 19530 { 19531 struct bpf_subprog_info *subprogs = env->subprog_info; 19532 int i, cur_subprog = 0, cnt, delta = 0; 19533 struct bpf_insn *insn = env->prog->insnsi; 19534 int insn_cnt = env->prog->len; 19535 u16 stack_depth = subprogs[cur_subprog].stack_depth; 19536 u16 stack_depth_roundup = round_up(stack_depth, 8) - stack_depth; 19537 u16 stack_depth_extra = 0; 19538 19539 for (i = 0; i < insn_cnt; i++, insn++) { 19540 struct bpf_loop_inline_state *inline_state = 19541 &env->insn_aux_data[i + delta].loop_inline_state; 19542 19543 if (is_bpf_loop_call(insn) && inline_state->fit_for_inline) { 19544 struct bpf_prog *new_prog; 19545 19546 stack_depth_extra = BPF_REG_SIZE * 3 + stack_depth_roundup; 19547 new_prog = inline_bpf_loop(env, 19548 i + delta, 19549 -(stack_depth + stack_depth_extra), 19550 inline_state->callback_subprogno, 19551 &cnt); 19552 if (!new_prog) 19553 return -ENOMEM; 19554 19555 delta += cnt - 1; 19556 env->prog = new_prog; 19557 insn = new_prog->insnsi + i + delta; 19558 } 19559 19560 if (subprogs[cur_subprog + 1].start == i + delta + 1) { 19561 subprogs[cur_subprog].stack_depth += stack_depth_extra; 19562 cur_subprog++; 19563 stack_depth = subprogs[cur_subprog].stack_depth; 19564 stack_depth_roundup = round_up(stack_depth, 8) - stack_depth; 19565 stack_depth_extra = 0; 19566 } 19567 } 19568 19569 env->prog->aux->stack_depth = env->subprog_info[0].stack_depth; 19570 19571 return 0; 19572 } 19573 19574 static void free_states(struct bpf_verifier_env *env) 19575 { 19576 struct bpf_verifier_state_list *sl, *sln; 19577 int i; 19578 19579 sl = env->free_list; 19580 while (sl) { 19581 sln = sl->next; 19582 free_verifier_state(&sl->state, false); 19583 kfree(sl); 19584 sl = sln; 19585 } 19586 env->free_list = NULL; 19587 19588 if (!env->explored_states) 19589 return; 19590 19591 for (i = 0; i < state_htab_size(env); i++) { 19592 sl = env->explored_states[i]; 19593 19594 while (sl) { 19595 sln = sl->next; 19596 free_verifier_state(&sl->state, false); 19597 kfree(sl); 19598 sl = sln; 19599 } 19600 env->explored_states[i] = NULL; 19601 } 19602 } 19603 19604 static int do_check_common(struct bpf_verifier_env *env, int subprog) 19605 { 19606 bool pop_log = !(env->log.level & BPF_LOG_LEVEL2); 19607 struct bpf_verifier_state *state; 19608 struct bpf_reg_state *regs; 19609 int ret, i; 19610 19611 env->prev_linfo = NULL; 19612 env->pass_cnt++; 19613 19614 state = kzalloc(sizeof(struct bpf_verifier_state), GFP_KERNEL); 19615 if (!state) 19616 return -ENOMEM; 19617 state->curframe = 0; 19618 state->speculative = false; 19619 state->branches = 1; 19620 state->frame[0] = kzalloc(sizeof(struct bpf_func_state), GFP_KERNEL); 19621 if (!state->frame[0]) { 19622 kfree(state); 19623 return -ENOMEM; 19624 } 19625 env->cur_state = state; 19626 init_func_state(env, state->frame[0], 19627 BPF_MAIN_FUNC /* callsite */, 19628 0 /* frameno */, 19629 subprog); 19630 state->first_insn_idx = env->subprog_info[subprog].start; 19631 state->last_insn_idx = -1; 19632 19633 regs = state->frame[state->curframe]->regs; 19634 if (subprog || env->prog->type == BPF_PROG_TYPE_EXT) { 19635 ret = btf_prepare_func_args(env, subprog, regs); 19636 if (ret) 19637 goto out; 19638 for (i = BPF_REG_1; i <= BPF_REG_5; i++) { 19639 if (regs[i].type == PTR_TO_CTX) 19640 mark_reg_known_zero(env, regs, i); 19641 else if (regs[i].type == SCALAR_VALUE) 19642 mark_reg_unknown(env, regs, i); 19643 else if (base_type(regs[i].type) == PTR_TO_MEM) { 19644 const u32 mem_size = regs[i].mem_size; 19645 19646 mark_reg_known_zero(env, regs, i); 19647 regs[i].mem_size = mem_size; 19648 regs[i].id = ++env->id_gen; 19649 } 19650 } 19651 } else { 19652 /* 1st arg to a function */ 19653 regs[BPF_REG_1].type = PTR_TO_CTX; 19654 mark_reg_known_zero(env, regs, BPF_REG_1); 19655 ret = btf_check_subprog_arg_match(env, subprog, regs); 19656 if (ret == -EFAULT) 19657 /* unlikely verifier bug. abort. 19658 * ret == 0 and ret < 0 are sadly acceptable for 19659 * main() function due to backward compatibility. 19660 * Like socket filter program may be written as: 19661 * int bpf_prog(struct pt_regs *ctx) 19662 * and never dereference that ctx in the program. 19663 * 'struct pt_regs' is a type mismatch for socket 19664 * filter that should be using 'struct __sk_buff'. 19665 */ 19666 goto out; 19667 } 19668 19669 ret = do_check(env); 19670 out: 19671 /* check for NULL is necessary, since cur_state can be freed inside 19672 * do_check() under memory pressure. 19673 */ 19674 if (env->cur_state) { 19675 free_verifier_state(env->cur_state, true); 19676 env->cur_state = NULL; 19677 } 19678 while (!pop_stack(env, NULL, NULL, false)); 19679 if (!ret && pop_log) 19680 bpf_vlog_reset(&env->log, 0); 19681 free_states(env); 19682 return ret; 19683 } 19684 19685 /* Verify all global functions in a BPF program one by one based on their BTF. 19686 * All global functions must pass verification. Otherwise the whole program is rejected. 19687 * Consider: 19688 * int bar(int); 19689 * int foo(int f) 19690 * { 19691 * return bar(f); 19692 * } 19693 * int bar(int b) 19694 * { 19695 * ... 19696 * } 19697 * foo() will be verified first for R1=any_scalar_value. During verification it 19698 * will be assumed that bar() already verified successfully and call to bar() 19699 * from foo() will be checked for type match only. Later bar() will be verified 19700 * independently to check that it's safe for R1=any_scalar_value. 19701 */ 19702 static int do_check_subprogs(struct bpf_verifier_env *env) 19703 { 19704 struct bpf_prog_aux *aux = env->prog->aux; 19705 int i, ret; 19706 19707 if (!aux->func_info) 19708 return 0; 19709 19710 for (i = 1; i < env->subprog_cnt; i++) { 19711 if (aux->func_info_aux[i].linkage != BTF_FUNC_GLOBAL) 19712 continue; 19713 env->insn_idx = env->subprog_info[i].start; 19714 WARN_ON_ONCE(env->insn_idx == 0); 19715 ret = do_check_common(env, i); 19716 if (ret) { 19717 return ret; 19718 } else if (env->log.level & BPF_LOG_LEVEL) { 19719 verbose(env, 19720 "Func#%d is safe for any args that match its prototype\n", 19721 i); 19722 } 19723 } 19724 return 0; 19725 } 19726 19727 static int do_check_main(struct bpf_verifier_env *env) 19728 { 19729 int ret; 19730 19731 env->insn_idx = 0; 19732 ret = do_check_common(env, 0); 19733 if (!ret) 19734 env->prog->aux->stack_depth = env->subprog_info[0].stack_depth; 19735 return ret; 19736 } 19737 19738 19739 static void print_verification_stats(struct bpf_verifier_env *env) 19740 { 19741 int i; 19742 19743 if (env->log.level & BPF_LOG_STATS) { 19744 verbose(env, "verification time %lld usec\n", 19745 div_u64(env->verification_time, 1000)); 19746 verbose(env, "stack depth "); 19747 for (i = 0; i < env->subprog_cnt; i++) { 19748 u32 depth = env->subprog_info[i].stack_depth; 19749 19750 verbose(env, "%d", depth); 19751 if (i + 1 < env->subprog_cnt) 19752 verbose(env, "+"); 19753 } 19754 verbose(env, "\n"); 19755 } 19756 verbose(env, "processed %d insns (limit %d) max_states_per_insn %d " 19757 "total_states %d peak_states %d mark_read %d\n", 19758 env->insn_processed, BPF_COMPLEXITY_LIMIT_INSNS, 19759 env->max_states_per_insn, env->total_states, 19760 env->peak_states, env->longest_mark_read_walk); 19761 } 19762 19763 static int check_struct_ops_btf_id(struct bpf_verifier_env *env) 19764 { 19765 const struct btf_type *t, *func_proto; 19766 const struct bpf_struct_ops *st_ops; 19767 const struct btf_member *member; 19768 struct bpf_prog *prog = env->prog; 19769 u32 btf_id, member_idx; 19770 const char *mname; 19771 19772 if (!prog->gpl_compatible) { 19773 verbose(env, "struct ops programs must have a GPL compatible license\n"); 19774 return -EINVAL; 19775 } 19776 19777 btf_id = prog->aux->attach_btf_id; 19778 st_ops = bpf_struct_ops_find(btf_id); 19779 if (!st_ops) { 19780 verbose(env, "attach_btf_id %u is not a supported struct\n", 19781 btf_id); 19782 return -ENOTSUPP; 19783 } 19784 19785 t = st_ops->type; 19786 member_idx = prog->expected_attach_type; 19787 if (member_idx >= btf_type_vlen(t)) { 19788 verbose(env, "attach to invalid member idx %u of struct %s\n", 19789 member_idx, st_ops->name); 19790 return -EINVAL; 19791 } 19792 19793 member = &btf_type_member(t)[member_idx]; 19794 mname = btf_name_by_offset(btf_vmlinux, member->name_off); 19795 func_proto = btf_type_resolve_func_ptr(btf_vmlinux, member->type, 19796 NULL); 19797 if (!func_proto) { 19798 verbose(env, "attach to invalid member %s(@idx %u) of struct %s\n", 19799 mname, member_idx, st_ops->name); 19800 return -EINVAL; 19801 } 19802 19803 if (st_ops->check_member) { 19804 int err = st_ops->check_member(t, member, prog); 19805 19806 if (err) { 19807 verbose(env, "attach to unsupported member %s of struct %s\n", 19808 mname, st_ops->name); 19809 return err; 19810 } 19811 } 19812 19813 prog->aux->attach_func_proto = func_proto; 19814 prog->aux->attach_func_name = mname; 19815 env->ops = st_ops->verifier_ops; 19816 19817 return 0; 19818 } 19819 #define SECURITY_PREFIX "security_" 19820 19821 static int check_attach_modify_return(unsigned long addr, const char *func_name) 19822 { 19823 if (within_error_injection_list(addr) || 19824 !strncmp(SECURITY_PREFIX, func_name, sizeof(SECURITY_PREFIX) - 1)) 19825 return 0; 19826 19827 return -EINVAL; 19828 } 19829 19830 /* list of non-sleepable functions that are otherwise on 19831 * ALLOW_ERROR_INJECTION list 19832 */ 19833 BTF_SET_START(btf_non_sleepable_error_inject) 19834 /* Three functions below can be called from sleepable and non-sleepable context. 19835 * Assume non-sleepable from bpf safety point of view. 19836 */ 19837 BTF_ID(func, __filemap_add_folio) 19838 BTF_ID(func, should_fail_alloc_page) 19839 BTF_ID(func, should_failslab) 19840 BTF_SET_END(btf_non_sleepable_error_inject) 19841 19842 static int check_non_sleepable_error_inject(u32 btf_id) 19843 { 19844 return btf_id_set_contains(&btf_non_sleepable_error_inject, btf_id); 19845 } 19846 19847 int bpf_check_attach_target(struct bpf_verifier_log *log, 19848 const struct bpf_prog *prog, 19849 const struct bpf_prog *tgt_prog, 19850 u32 btf_id, 19851 struct bpf_attach_target_info *tgt_info) 19852 { 19853 bool prog_extension = prog->type == BPF_PROG_TYPE_EXT; 19854 const char prefix[] = "btf_trace_"; 19855 int ret = 0, subprog = -1, i; 19856 const struct btf_type *t; 19857 bool conservative = true; 19858 const char *tname; 19859 struct btf *btf; 19860 long addr = 0; 19861 struct module *mod = NULL; 19862 19863 if (!btf_id) { 19864 bpf_log(log, "Tracing programs must provide btf_id\n"); 19865 return -EINVAL; 19866 } 19867 btf = tgt_prog ? tgt_prog->aux->btf : prog->aux->attach_btf; 19868 if (!btf) { 19869 bpf_log(log, 19870 "FENTRY/FEXIT program can only be attached to another program annotated with BTF\n"); 19871 return -EINVAL; 19872 } 19873 t = btf_type_by_id(btf, btf_id); 19874 if (!t) { 19875 bpf_log(log, "attach_btf_id %u is invalid\n", btf_id); 19876 return -EINVAL; 19877 } 19878 tname = btf_name_by_offset(btf, t->name_off); 19879 if (!tname) { 19880 bpf_log(log, "attach_btf_id %u doesn't have a name\n", btf_id); 19881 return -EINVAL; 19882 } 19883 if (tgt_prog) { 19884 struct bpf_prog_aux *aux = tgt_prog->aux; 19885 19886 if (bpf_prog_is_dev_bound(prog->aux) && 19887 !bpf_prog_dev_bound_match(prog, tgt_prog)) { 19888 bpf_log(log, "Target program bound device mismatch"); 19889 return -EINVAL; 19890 } 19891 19892 for (i = 0; i < aux->func_info_cnt; i++) 19893 if (aux->func_info[i].type_id == btf_id) { 19894 subprog = i; 19895 break; 19896 } 19897 if (subprog == -1) { 19898 bpf_log(log, "Subprog %s doesn't exist\n", tname); 19899 return -EINVAL; 19900 } 19901 conservative = aux->func_info_aux[subprog].unreliable; 19902 if (prog_extension) { 19903 if (conservative) { 19904 bpf_log(log, 19905 "Cannot replace static functions\n"); 19906 return -EINVAL; 19907 } 19908 if (!prog->jit_requested) { 19909 bpf_log(log, 19910 "Extension programs should be JITed\n"); 19911 return -EINVAL; 19912 } 19913 } 19914 if (!tgt_prog->jited) { 19915 bpf_log(log, "Can attach to only JITed progs\n"); 19916 return -EINVAL; 19917 } 19918 if (tgt_prog->type == prog->type) { 19919 /* Cannot fentry/fexit another fentry/fexit program. 19920 * Cannot attach program extension to another extension. 19921 * It's ok to attach fentry/fexit to extension program. 19922 */ 19923 bpf_log(log, "Cannot recursively attach\n"); 19924 return -EINVAL; 19925 } 19926 if (tgt_prog->type == BPF_PROG_TYPE_TRACING && 19927 prog_extension && 19928 (tgt_prog->expected_attach_type == BPF_TRACE_FENTRY || 19929 tgt_prog->expected_attach_type == BPF_TRACE_FEXIT)) { 19930 /* Program extensions can extend all program types 19931 * except fentry/fexit. The reason is the following. 19932 * The fentry/fexit programs are used for performance 19933 * analysis, stats and can be attached to any program 19934 * type except themselves. When extension program is 19935 * replacing XDP function it is necessary to allow 19936 * performance analysis of all functions. Both original 19937 * XDP program and its program extension. Hence 19938 * attaching fentry/fexit to BPF_PROG_TYPE_EXT is 19939 * allowed. If extending of fentry/fexit was allowed it 19940 * would be possible to create long call chain 19941 * fentry->extension->fentry->extension beyond 19942 * reasonable stack size. Hence extending fentry is not 19943 * allowed. 19944 */ 19945 bpf_log(log, "Cannot extend fentry/fexit\n"); 19946 return -EINVAL; 19947 } 19948 } else { 19949 if (prog_extension) { 19950 bpf_log(log, "Cannot replace kernel functions\n"); 19951 return -EINVAL; 19952 } 19953 } 19954 19955 switch (prog->expected_attach_type) { 19956 case BPF_TRACE_RAW_TP: 19957 if (tgt_prog) { 19958 bpf_log(log, 19959 "Only FENTRY/FEXIT progs are attachable to another BPF prog\n"); 19960 return -EINVAL; 19961 } 19962 if (!btf_type_is_typedef(t)) { 19963 bpf_log(log, "attach_btf_id %u is not a typedef\n", 19964 btf_id); 19965 return -EINVAL; 19966 } 19967 if (strncmp(prefix, tname, sizeof(prefix) - 1)) { 19968 bpf_log(log, "attach_btf_id %u points to wrong type name %s\n", 19969 btf_id, tname); 19970 return -EINVAL; 19971 } 19972 tname += sizeof(prefix) - 1; 19973 t = btf_type_by_id(btf, t->type); 19974 if (!btf_type_is_ptr(t)) 19975 /* should never happen in valid vmlinux build */ 19976 return -EINVAL; 19977 t = btf_type_by_id(btf, t->type); 19978 if (!btf_type_is_func_proto(t)) 19979 /* should never happen in valid vmlinux build */ 19980 return -EINVAL; 19981 19982 break; 19983 case BPF_TRACE_ITER: 19984 if (!btf_type_is_func(t)) { 19985 bpf_log(log, "attach_btf_id %u is not a function\n", 19986 btf_id); 19987 return -EINVAL; 19988 } 19989 t = btf_type_by_id(btf, t->type); 19990 if (!btf_type_is_func_proto(t)) 19991 return -EINVAL; 19992 ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel); 19993 if (ret) 19994 return ret; 19995 break; 19996 default: 19997 if (!prog_extension) 19998 return -EINVAL; 19999 fallthrough; 20000 case BPF_MODIFY_RETURN: 20001 case BPF_LSM_MAC: 20002 case BPF_LSM_CGROUP: 20003 case BPF_TRACE_FENTRY: 20004 case BPF_TRACE_FEXIT: 20005 if (!btf_type_is_func(t)) { 20006 bpf_log(log, "attach_btf_id %u is not a function\n", 20007 btf_id); 20008 return -EINVAL; 20009 } 20010 if (prog_extension && 20011 btf_check_type_match(log, prog, btf, t)) 20012 return -EINVAL; 20013 t = btf_type_by_id(btf, t->type); 20014 if (!btf_type_is_func_proto(t)) 20015 return -EINVAL; 20016 20017 if ((prog->aux->saved_dst_prog_type || prog->aux->saved_dst_attach_type) && 20018 (!tgt_prog || prog->aux->saved_dst_prog_type != tgt_prog->type || 20019 prog->aux->saved_dst_attach_type != tgt_prog->expected_attach_type)) 20020 return -EINVAL; 20021 20022 if (tgt_prog && conservative) 20023 t = NULL; 20024 20025 ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel); 20026 if (ret < 0) 20027 return ret; 20028 20029 if (tgt_prog) { 20030 if (subprog == 0) 20031 addr = (long) tgt_prog->bpf_func; 20032 else 20033 addr = (long) tgt_prog->aux->func[subprog]->bpf_func; 20034 } else { 20035 if (btf_is_module(btf)) { 20036 mod = btf_try_get_module(btf); 20037 if (mod) 20038 addr = find_kallsyms_symbol_value(mod, tname); 20039 else 20040 addr = 0; 20041 } else { 20042 addr = kallsyms_lookup_name(tname); 20043 } 20044 if (!addr) { 20045 module_put(mod); 20046 bpf_log(log, 20047 "The address of function %s cannot be found\n", 20048 tname); 20049 return -ENOENT; 20050 } 20051 } 20052 20053 if (prog->aux->sleepable) { 20054 ret = -EINVAL; 20055 switch (prog->type) { 20056 case BPF_PROG_TYPE_TRACING: 20057 20058 /* fentry/fexit/fmod_ret progs can be sleepable if they are 20059 * attached to ALLOW_ERROR_INJECTION and are not in denylist. 20060 */ 20061 if (!check_non_sleepable_error_inject(btf_id) && 20062 within_error_injection_list(addr)) 20063 ret = 0; 20064 /* fentry/fexit/fmod_ret progs can also be sleepable if they are 20065 * in the fmodret id set with the KF_SLEEPABLE flag. 20066 */ 20067 else { 20068 u32 *flags = btf_kfunc_is_modify_return(btf, btf_id, 20069 prog); 20070 20071 if (flags && (*flags & KF_SLEEPABLE)) 20072 ret = 0; 20073 } 20074 break; 20075 case BPF_PROG_TYPE_LSM: 20076 /* LSM progs check that they are attached to bpf_lsm_*() funcs. 20077 * Only some of them are sleepable. 20078 */ 20079 if (bpf_lsm_is_sleepable_hook(btf_id)) 20080 ret = 0; 20081 break; 20082 default: 20083 break; 20084 } 20085 if (ret) { 20086 module_put(mod); 20087 bpf_log(log, "%s is not sleepable\n", tname); 20088 return ret; 20089 } 20090 } else if (prog->expected_attach_type == BPF_MODIFY_RETURN) { 20091 if (tgt_prog) { 20092 module_put(mod); 20093 bpf_log(log, "can't modify return codes of BPF programs\n"); 20094 return -EINVAL; 20095 } 20096 ret = -EINVAL; 20097 if (btf_kfunc_is_modify_return(btf, btf_id, prog) || 20098 !check_attach_modify_return(addr, tname)) 20099 ret = 0; 20100 if (ret) { 20101 module_put(mod); 20102 bpf_log(log, "%s() is not modifiable\n", tname); 20103 return ret; 20104 } 20105 } 20106 20107 break; 20108 } 20109 tgt_info->tgt_addr = addr; 20110 tgt_info->tgt_name = tname; 20111 tgt_info->tgt_type = t; 20112 tgt_info->tgt_mod = mod; 20113 return 0; 20114 } 20115 20116 BTF_SET_START(btf_id_deny) 20117 BTF_ID_UNUSED 20118 #ifdef CONFIG_SMP 20119 BTF_ID(func, migrate_disable) 20120 BTF_ID(func, migrate_enable) 20121 #endif 20122 #if !defined CONFIG_PREEMPT_RCU && !defined CONFIG_TINY_RCU 20123 BTF_ID(func, rcu_read_unlock_strict) 20124 #endif 20125 #if defined(CONFIG_DEBUG_PREEMPT) || defined(CONFIG_TRACE_PREEMPT_TOGGLE) 20126 BTF_ID(func, preempt_count_add) 20127 BTF_ID(func, preempt_count_sub) 20128 #endif 20129 #ifdef CONFIG_PREEMPT_RCU 20130 BTF_ID(func, __rcu_read_lock) 20131 BTF_ID(func, __rcu_read_unlock) 20132 #endif 20133 BTF_SET_END(btf_id_deny) 20134 20135 static bool can_be_sleepable(struct bpf_prog *prog) 20136 { 20137 if (prog->type == BPF_PROG_TYPE_TRACING) { 20138 switch (prog->expected_attach_type) { 20139 case BPF_TRACE_FENTRY: 20140 case BPF_TRACE_FEXIT: 20141 case BPF_MODIFY_RETURN: 20142 case BPF_TRACE_ITER: 20143 return true; 20144 default: 20145 return false; 20146 } 20147 } 20148 return prog->type == BPF_PROG_TYPE_LSM || 20149 prog->type == BPF_PROG_TYPE_KPROBE /* only for uprobes */ || 20150 prog->type == BPF_PROG_TYPE_STRUCT_OPS; 20151 } 20152 20153 static int check_attach_btf_id(struct bpf_verifier_env *env) 20154 { 20155 struct bpf_prog *prog = env->prog; 20156 struct bpf_prog *tgt_prog = prog->aux->dst_prog; 20157 struct bpf_attach_target_info tgt_info = {}; 20158 u32 btf_id = prog->aux->attach_btf_id; 20159 struct bpf_trampoline *tr; 20160 int ret; 20161 u64 key; 20162 20163 if (prog->type == BPF_PROG_TYPE_SYSCALL) { 20164 if (prog->aux->sleepable) 20165 /* attach_btf_id checked to be zero already */ 20166 return 0; 20167 verbose(env, "Syscall programs can only be sleepable\n"); 20168 return -EINVAL; 20169 } 20170 20171 if (prog->aux->sleepable && !can_be_sleepable(prog)) { 20172 verbose(env, "Only fentry/fexit/fmod_ret, lsm, iter, uprobe, and struct_ops programs can be sleepable\n"); 20173 return -EINVAL; 20174 } 20175 20176 if (prog->type == BPF_PROG_TYPE_STRUCT_OPS) 20177 return check_struct_ops_btf_id(env); 20178 20179 if (prog->type != BPF_PROG_TYPE_TRACING && 20180 prog->type != BPF_PROG_TYPE_LSM && 20181 prog->type != BPF_PROG_TYPE_EXT) 20182 return 0; 20183 20184 ret = bpf_check_attach_target(&env->log, prog, tgt_prog, btf_id, &tgt_info); 20185 if (ret) 20186 return ret; 20187 20188 if (tgt_prog && prog->type == BPF_PROG_TYPE_EXT) { 20189 /* to make freplace equivalent to their targets, they need to 20190 * inherit env->ops and expected_attach_type for the rest of the 20191 * verification 20192 */ 20193 env->ops = bpf_verifier_ops[tgt_prog->type]; 20194 prog->expected_attach_type = tgt_prog->expected_attach_type; 20195 } 20196 20197 /* store info about the attachment target that will be used later */ 20198 prog->aux->attach_func_proto = tgt_info.tgt_type; 20199 prog->aux->attach_func_name = tgt_info.tgt_name; 20200 prog->aux->mod = tgt_info.tgt_mod; 20201 20202 if (tgt_prog) { 20203 prog->aux->saved_dst_prog_type = tgt_prog->type; 20204 prog->aux->saved_dst_attach_type = tgt_prog->expected_attach_type; 20205 } 20206 20207 if (prog->expected_attach_type == BPF_TRACE_RAW_TP) { 20208 prog->aux->attach_btf_trace = true; 20209 return 0; 20210 } else if (prog->expected_attach_type == BPF_TRACE_ITER) { 20211 if (!bpf_iter_prog_supported(prog)) 20212 return -EINVAL; 20213 return 0; 20214 } 20215 20216 if (prog->type == BPF_PROG_TYPE_LSM) { 20217 ret = bpf_lsm_verify_prog(&env->log, prog); 20218 if (ret < 0) 20219 return ret; 20220 } else if (prog->type == BPF_PROG_TYPE_TRACING && 20221 btf_id_set_contains(&btf_id_deny, btf_id)) { 20222 return -EINVAL; 20223 } 20224 20225 key = bpf_trampoline_compute_key(tgt_prog, prog->aux->attach_btf, btf_id); 20226 tr = bpf_trampoline_get(key, &tgt_info); 20227 if (!tr) 20228 return -ENOMEM; 20229 20230 if (tgt_prog && tgt_prog->aux->tail_call_reachable) 20231 tr->flags = BPF_TRAMP_F_TAIL_CALL_CTX; 20232 20233 prog->aux->dst_trampoline = tr; 20234 return 0; 20235 } 20236 20237 struct btf *bpf_get_btf_vmlinux(void) 20238 { 20239 if (!btf_vmlinux && IS_ENABLED(CONFIG_DEBUG_INFO_BTF)) { 20240 mutex_lock(&bpf_verifier_lock); 20241 if (!btf_vmlinux) 20242 btf_vmlinux = btf_parse_vmlinux(); 20243 mutex_unlock(&bpf_verifier_lock); 20244 } 20245 return btf_vmlinux; 20246 } 20247 20248 int bpf_check(struct bpf_prog **prog, union bpf_attr *attr, bpfptr_t uattr, __u32 uattr_size) 20249 { 20250 u64 start_time = ktime_get_ns(); 20251 struct bpf_verifier_env *env; 20252 int i, len, ret = -EINVAL, err; 20253 u32 log_true_size; 20254 bool is_priv; 20255 20256 /* no program is valid */ 20257 if (ARRAY_SIZE(bpf_verifier_ops) == 0) 20258 return -EINVAL; 20259 20260 /* 'struct bpf_verifier_env' can be global, but since it's not small, 20261 * allocate/free it every time bpf_check() is called 20262 */ 20263 env = kvzalloc(sizeof(struct bpf_verifier_env), GFP_KERNEL); 20264 if (!env) 20265 return -ENOMEM; 20266 20267 env->bt.env = env; 20268 20269 len = (*prog)->len; 20270 env->insn_aux_data = 20271 vzalloc(array_size(sizeof(struct bpf_insn_aux_data), len)); 20272 ret = -ENOMEM; 20273 if (!env->insn_aux_data) 20274 goto err_free_env; 20275 for (i = 0; i < len; i++) 20276 env->insn_aux_data[i].orig_idx = i; 20277 env->prog = *prog; 20278 env->ops = bpf_verifier_ops[env->prog->type]; 20279 env->fd_array = make_bpfptr(attr->fd_array, uattr.is_kernel); 20280 is_priv = bpf_capable(); 20281 20282 bpf_get_btf_vmlinux(); 20283 20284 /* grab the mutex to protect few globals used by verifier */ 20285 if (!is_priv) 20286 mutex_lock(&bpf_verifier_lock); 20287 20288 /* user could have requested verbose verifier output 20289 * and supplied buffer to store the verification trace 20290 */ 20291 ret = bpf_vlog_init(&env->log, attr->log_level, 20292 (char __user *) (unsigned long) attr->log_buf, 20293 attr->log_size); 20294 if (ret) 20295 goto err_unlock; 20296 20297 mark_verifier_state_clean(env); 20298 20299 if (IS_ERR(btf_vmlinux)) { 20300 /* Either gcc or pahole or kernel are broken. */ 20301 verbose(env, "in-kernel BTF is malformed\n"); 20302 ret = PTR_ERR(btf_vmlinux); 20303 goto skip_full_check; 20304 } 20305 20306 env->strict_alignment = !!(attr->prog_flags & BPF_F_STRICT_ALIGNMENT); 20307 if (!IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS)) 20308 env->strict_alignment = true; 20309 if (attr->prog_flags & BPF_F_ANY_ALIGNMENT) 20310 env->strict_alignment = false; 20311 20312 env->allow_ptr_leaks = bpf_allow_ptr_leaks(); 20313 env->allow_uninit_stack = bpf_allow_uninit_stack(); 20314 env->bypass_spec_v1 = bpf_bypass_spec_v1(); 20315 env->bypass_spec_v4 = bpf_bypass_spec_v4(); 20316 env->bpf_capable = bpf_capable(); 20317 20318 if (is_priv) 20319 env->test_state_freq = attr->prog_flags & BPF_F_TEST_STATE_FREQ; 20320 20321 env->explored_states = kvcalloc(state_htab_size(env), 20322 sizeof(struct bpf_verifier_state_list *), 20323 GFP_USER); 20324 ret = -ENOMEM; 20325 if (!env->explored_states) 20326 goto skip_full_check; 20327 20328 ret = add_subprog_and_kfunc(env); 20329 if (ret < 0) 20330 goto skip_full_check; 20331 20332 ret = check_subprogs(env); 20333 if (ret < 0) 20334 goto skip_full_check; 20335 20336 ret = check_btf_info(env, attr, uattr); 20337 if (ret < 0) 20338 goto skip_full_check; 20339 20340 ret = check_attach_btf_id(env); 20341 if (ret) 20342 goto skip_full_check; 20343 20344 ret = resolve_pseudo_ldimm64(env); 20345 if (ret < 0) 20346 goto skip_full_check; 20347 20348 if (bpf_prog_is_offloaded(env->prog->aux)) { 20349 ret = bpf_prog_offload_verifier_prep(env->prog); 20350 if (ret) 20351 goto skip_full_check; 20352 } 20353 20354 ret = check_cfg(env); 20355 if (ret < 0) 20356 goto skip_full_check; 20357 20358 ret = do_check_subprogs(env); 20359 ret = ret ?: do_check_main(env); 20360 20361 if (ret == 0 && bpf_prog_is_offloaded(env->prog->aux)) 20362 ret = bpf_prog_offload_finalize(env); 20363 20364 skip_full_check: 20365 kvfree(env->explored_states); 20366 20367 if (ret == 0) 20368 ret = check_max_stack_depth(env); 20369 20370 /* instruction rewrites happen after this point */ 20371 if (ret == 0) 20372 ret = optimize_bpf_loop(env); 20373 20374 if (is_priv) { 20375 if (ret == 0) 20376 opt_hard_wire_dead_code_branches(env); 20377 if (ret == 0) 20378 ret = opt_remove_dead_code(env); 20379 if (ret == 0) 20380 ret = opt_remove_nops(env); 20381 } else { 20382 if (ret == 0) 20383 sanitize_dead_code(env); 20384 } 20385 20386 if (ret == 0) 20387 /* program is valid, convert *(u32*)(ctx + off) accesses */ 20388 ret = convert_ctx_accesses(env); 20389 20390 if (ret == 0) 20391 ret = do_misc_fixups(env); 20392 20393 /* do 32-bit optimization after insn patching has done so those patched 20394 * insns could be handled correctly. 20395 */ 20396 if (ret == 0 && !bpf_prog_is_offloaded(env->prog->aux)) { 20397 ret = opt_subreg_zext_lo32_rnd_hi32(env, attr); 20398 env->prog->aux->verifier_zext = bpf_jit_needs_zext() ? !ret 20399 : false; 20400 } 20401 20402 if (ret == 0) 20403 ret = fixup_call_args(env); 20404 20405 env->verification_time = ktime_get_ns() - start_time; 20406 print_verification_stats(env); 20407 env->prog->aux->verified_insns = env->insn_processed; 20408 20409 /* preserve original error even if log finalization is successful */ 20410 err = bpf_vlog_finalize(&env->log, &log_true_size); 20411 if (err) 20412 ret = err; 20413 20414 if (uattr_size >= offsetofend(union bpf_attr, log_true_size) && 20415 copy_to_bpfptr_offset(uattr, offsetof(union bpf_attr, log_true_size), 20416 &log_true_size, sizeof(log_true_size))) { 20417 ret = -EFAULT; 20418 goto err_release_maps; 20419 } 20420 20421 if (ret) 20422 goto err_release_maps; 20423 20424 if (env->used_map_cnt) { 20425 /* if program passed verifier, update used_maps in bpf_prog_info */ 20426 env->prog->aux->used_maps = kmalloc_array(env->used_map_cnt, 20427 sizeof(env->used_maps[0]), 20428 GFP_KERNEL); 20429 20430 if (!env->prog->aux->used_maps) { 20431 ret = -ENOMEM; 20432 goto err_release_maps; 20433 } 20434 20435 memcpy(env->prog->aux->used_maps, env->used_maps, 20436 sizeof(env->used_maps[0]) * env->used_map_cnt); 20437 env->prog->aux->used_map_cnt = env->used_map_cnt; 20438 } 20439 if (env->used_btf_cnt) { 20440 /* if program passed verifier, update used_btfs in bpf_prog_aux */ 20441 env->prog->aux->used_btfs = kmalloc_array(env->used_btf_cnt, 20442 sizeof(env->used_btfs[0]), 20443 GFP_KERNEL); 20444 if (!env->prog->aux->used_btfs) { 20445 ret = -ENOMEM; 20446 goto err_release_maps; 20447 } 20448 20449 memcpy(env->prog->aux->used_btfs, env->used_btfs, 20450 sizeof(env->used_btfs[0]) * env->used_btf_cnt); 20451 env->prog->aux->used_btf_cnt = env->used_btf_cnt; 20452 } 20453 if (env->used_map_cnt || env->used_btf_cnt) { 20454 /* program is valid. Convert pseudo bpf_ld_imm64 into generic 20455 * bpf_ld_imm64 instructions 20456 */ 20457 convert_pseudo_ld_imm64(env); 20458 } 20459 20460 adjust_btf_func(env); 20461 20462 err_release_maps: 20463 if (!env->prog->aux->used_maps) 20464 /* if we didn't copy map pointers into bpf_prog_info, release 20465 * them now. Otherwise free_used_maps() will release them. 20466 */ 20467 release_maps(env); 20468 if (!env->prog->aux->used_btfs) 20469 release_btfs(env); 20470 20471 /* extension progs temporarily inherit the attach_type of their targets 20472 for verification purposes, so set it back to zero before returning 20473 */ 20474 if (env->prog->type == BPF_PROG_TYPE_EXT) 20475 env->prog->expected_attach_type = 0; 20476 20477 *prog = env->prog; 20478 err_unlock: 20479 if (!is_priv) 20480 mutex_unlock(&bpf_verifier_lock); 20481 vfree(env->insn_aux_data); 20482 err_free_env: 20483 kvfree(env); 20484 return ret; 20485 } 20486