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(struct bpf_idx_pair), 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(tab->descs, tab->nr_descs, sizeof(tab->descs[0]), 2803 kfunc_btf_cmp_by_off, NULL); 2804 } 2805 return b->btf; 2806 } 2807 2808 void bpf_free_kfunc_btf_tab(struct bpf_kfunc_btf_tab *tab) 2809 { 2810 if (!tab) 2811 return; 2812 2813 while (tab->nr_descs--) { 2814 module_put(tab->descs[tab->nr_descs].module); 2815 btf_put(tab->descs[tab->nr_descs].btf); 2816 } 2817 kfree(tab); 2818 } 2819 2820 static struct btf *find_kfunc_desc_btf(struct bpf_verifier_env *env, s16 offset) 2821 { 2822 if (offset) { 2823 if (offset < 0) { 2824 /* In the future, this can be allowed to increase limit 2825 * of fd index into fd_array, interpreted as u16. 2826 */ 2827 verbose(env, "negative offset disallowed for kernel module function call\n"); 2828 return ERR_PTR(-EINVAL); 2829 } 2830 2831 return __find_kfunc_desc_btf(env, offset); 2832 } 2833 return btf_vmlinux ?: ERR_PTR(-ENOENT); 2834 } 2835 2836 static int add_kfunc_call(struct bpf_verifier_env *env, u32 func_id, s16 offset) 2837 { 2838 const struct btf_type *func, *func_proto; 2839 struct bpf_kfunc_btf_tab *btf_tab; 2840 struct bpf_kfunc_desc_tab *tab; 2841 struct bpf_prog_aux *prog_aux; 2842 struct bpf_kfunc_desc *desc; 2843 const char *func_name; 2844 struct btf *desc_btf; 2845 unsigned long call_imm; 2846 unsigned long addr; 2847 int err; 2848 2849 prog_aux = env->prog->aux; 2850 tab = prog_aux->kfunc_tab; 2851 btf_tab = prog_aux->kfunc_btf_tab; 2852 if (!tab) { 2853 if (!btf_vmlinux) { 2854 verbose(env, "calling kernel function is not supported without CONFIG_DEBUG_INFO_BTF\n"); 2855 return -ENOTSUPP; 2856 } 2857 2858 if (!env->prog->jit_requested) { 2859 verbose(env, "JIT is required for calling kernel function\n"); 2860 return -ENOTSUPP; 2861 } 2862 2863 if (!bpf_jit_supports_kfunc_call()) { 2864 verbose(env, "JIT does not support calling kernel function\n"); 2865 return -ENOTSUPP; 2866 } 2867 2868 if (!env->prog->gpl_compatible) { 2869 verbose(env, "cannot call kernel function from non-GPL compatible program\n"); 2870 return -EINVAL; 2871 } 2872 2873 tab = kzalloc(sizeof(*tab), GFP_KERNEL); 2874 if (!tab) 2875 return -ENOMEM; 2876 prog_aux->kfunc_tab = tab; 2877 } 2878 2879 /* func_id == 0 is always invalid, but instead of returning an error, be 2880 * conservative and wait until the code elimination pass before returning 2881 * error, so that invalid calls that get pruned out can be in BPF programs 2882 * loaded from userspace. It is also required that offset be untouched 2883 * for such calls. 2884 */ 2885 if (!func_id && !offset) 2886 return 0; 2887 2888 if (!btf_tab && offset) { 2889 btf_tab = kzalloc(sizeof(*btf_tab), GFP_KERNEL); 2890 if (!btf_tab) 2891 return -ENOMEM; 2892 prog_aux->kfunc_btf_tab = btf_tab; 2893 } 2894 2895 desc_btf = find_kfunc_desc_btf(env, offset); 2896 if (IS_ERR(desc_btf)) { 2897 verbose(env, "failed to find BTF for kernel function\n"); 2898 return PTR_ERR(desc_btf); 2899 } 2900 2901 if (find_kfunc_desc(env->prog, func_id, offset)) 2902 return 0; 2903 2904 if (tab->nr_descs == MAX_KFUNC_DESCS) { 2905 verbose(env, "too many different kernel function calls\n"); 2906 return -E2BIG; 2907 } 2908 2909 func = btf_type_by_id(desc_btf, func_id); 2910 if (!func || !btf_type_is_func(func)) { 2911 verbose(env, "kernel btf_id %u is not a function\n", 2912 func_id); 2913 return -EINVAL; 2914 } 2915 func_proto = btf_type_by_id(desc_btf, func->type); 2916 if (!func_proto || !btf_type_is_func_proto(func_proto)) { 2917 verbose(env, "kernel function btf_id %u does not have a valid func_proto\n", 2918 func_id); 2919 return -EINVAL; 2920 } 2921 2922 func_name = btf_name_by_offset(desc_btf, func->name_off); 2923 addr = kallsyms_lookup_name(func_name); 2924 if (!addr) { 2925 verbose(env, "cannot find address for kernel function %s\n", 2926 func_name); 2927 return -EINVAL; 2928 } 2929 specialize_kfunc(env, func_id, offset, &addr); 2930 2931 if (bpf_jit_supports_far_kfunc_call()) { 2932 call_imm = func_id; 2933 } else { 2934 call_imm = BPF_CALL_IMM(addr); 2935 /* Check whether the relative offset overflows desc->imm */ 2936 if ((unsigned long)(s32)call_imm != call_imm) { 2937 verbose(env, "address of kernel function %s is out of range\n", 2938 func_name); 2939 return -EINVAL; 2940 } 2941 } 2942 2943 if (bpf_dev_bound_kfunc_id(func_id)) { 2944 err = bpf_dev_bound_kfunc_check(&env->log, prog_aux); 2945 if (err) 2946 return err; 2947 } 2948 2949 desc = &tab->descs[tab->nr_descs++]; 2950 desc->func_id = func_id; 2951 desc->imm = call_imm; 2952 desc->offset = offset; 2953 desc->addr = addr; 2954 err = btf_distill_func_proto(&env->log, desc_btf, 2955 func_proto, func_name, 2956 &desc->func_model); 2957 if (!err) 2958 sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]), 2959 kfunc_desc_cmp_by_id_off, NULL); 2960 return err; 2961 } 2962 2963 static int kfunc_desc_cmp_by_imm_off(const void *a, const void *b) 2964 { 2965 const struct bpf_kfunc_desc *d0 = a; 2966 const struct bpf_kfunc_desc *d1 = b; 2967 2968 if (d0->imm != d1->imm) 2969 return d0->imm < d1->imm ? -1 : 1; 2970 if (d0->offset != d1->offset) 2971 return d0->offset < d1->offset ? -1 : 1; 2972 return 0; 2973 } 2974 2975 static void sort_kfunc_descs_by_imm_off(struct bpf_prog *prog) 2976 { 2977 struct bpf_kfunc_desc_tab *tab; 2978 2979 tab = prog->aux->kfunc_tab; 2980 if (!tab) 2981 return; 2982 2983 sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]), 2984 kfunc_desc_cmp_by_imm_off, NULL); 2985 } 2986 2987 bool bpf_prog_has_kfunc_call(const struct bpf_prog *prog) 2988 { 2989 return !!prog->aux->kfunc_tab; 2990 } 2991 2992 const struct btf_func_model * 2993 bpf_jit_find_kfunc_model(const struct bpf_prog *prog, 2994 const struct bpf_insn *insn) 2995 { 2996 const struct bpf_kfunc_desc desc = { 2997 .imm = insn->imm, 2998 .offset = insn->off, 2999 }; 3000 const struct bpf_kfunc_desc *res; 3001 struct bpf_kfunc_desc_tab *tab; 3002 3003 tab = prog->aux->kfunc_tab; 3004 res = bsearch(&desc, tab->descs, tab->nr_descs, 3005 sizeof(tab->descs[0]), kfunc_desc_cmp_by_imm_off); 3006 3007 return res ? &res->func_model : NULL; 3008 } 3009 3010 static int add_subprog_and_kfunc(struct bpf_verifier_env *env) 3011 { 3012 struct bpf_subprog_info *subprog = env->subprog_info; 3013 struct bpf_insn *insn = env->prog->insnsi; 3014 int i, ret, insn_cnt = env->prog->len; 3015 3016 /* Add entry function. */ 3017 ret = add_subprog(env, 0); 3018 if (ret) 3019 return ret; 3020 3021 for (i = 0; i < insn_cnt; i++, insn++) { 3022 if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn) && 3023 !bpf_pseudo_kfunc_call(insn)) 3024 continue; 3025 3026 if (!env->bpf_capable) { 3027 verbose(env, "loading/calling other bpf or kernel functions are allowed for CAP_BPF and CAP_SYS_ADMIN\n"); 3028 return -EPERM; 3029 } 3030 3031 if (bpf_pseudo_func(insn) || bpf_pseudo_call(insn)) 3032 ret = add_subprog(env, i + insn->imm + 1); 3033 else 3034 ret = add_kfunc_call(env, insn->imm, insn->off); 3035 3036 if (ret < 0) 3037 return ret; 3038 } 3039 3040 /* Add a fake 'exit' subprog which could simplify subprog iteration 3041 * logic. 'subprog_cnt' should not be increased. 3042 */ 3043 subprog[env->subprog_cnt].start = insn_cnt; 3044 3045 if (env->log.level & BPF_LOG_LEVEL2) 3046 for (i = 0; i < env->subprog_cnt; i++) 3047 verbose(env, "func#%d @%d\n", i, subprog[i].start); 3048 3049 return 0; 3050 } 3051 3052 static int check_subprogs(struct bpf_verifier_env *env) 3053 { 3054 int i, subprog_start, subprog_end, off, cur_subprog = 0; 3055 struct bpf_subprog_info *subprog = env->subprog_info; 3056 struct bpf_insn *insn = env->prog->insnsi; 3057 int insn_cnt = env->prog->len; 3058 3059 /* now check that all jumps are within the same subprog */ 3060 subprog_start = subprog[cur_subprog].start; 3061 subprog_end = subprog[cur_subprog + 1].start; 3062 for (i = 0; i < insn_cnt; i++) { 3063 u8 code = insn[i].code; 3064 3065 if (code == (BPF_JMP | BPF_CALL) && 3066 insn[i].src_reg == 0 && 3067 insn[i].imm == BPF_FUNC_tail_call) { 3068 subprog[cur_subprog].has_tail_call = true; 3069 subprog[cur_subprog].tail_call_reachable = true; 3070 } 3071 if (BPF_CLASS(code) == BPF_LD && 3072 (BPF_MODE(code) == BPF_ABS || BPF_MODE(code) == BPF_IND)) 3073 subprog[cur_subprog].has_ld_abs = true; 3074 if (BPF_CLASS(code) != BPF_JMP && BPF_CLASS(code) != BPF_JMP32) 3075 goto next; 3076 if (BPF_OP(code) == BPF_EXIT || BPF_OP(code) == BPF_CALL) 3077 goto next; 3078 if (code == (BPF_JMP32 | BPF_JA)) 3079 off = i + insn[i].imm + 1; 3080 else 3081 off = i + insn[i].off + 1; 3082 if (off < subprog_start || off >= subprog_end) { 3083 verbose(env, "jump out of range from insn %d to %d\n", i, off); 3084 return -EINVAL; 3085 } 3086 next: 3087 if (i == subprog_end - 1) { 3088 /* to avoid fall-through from one subprog into another 3089 * the last insn of the subprog should be either exit 3090 * or unconditional jump back 3091 */ 3092 if (code != (BPF_JMP | BPF_EXIT) && 3093 code != (BPF_JMP32 | BPF_JA) && 3094 code != (BPF_JMP | BPF_JA)) { 3095 verbose(env, "last insn is not an exit or jmp\n"); 3096 return -EINVAL; 3097 } 3098 subprog_start = subprog_end; 3099 cur_subprog++; 3100 if (cur_subprog < env->subprog_cnt) 3101 subprog_end = subprog[cur_subprog + 1].start; 3102 } 3103 } 3104 return 0; 3105 } 3106 3107 /* Parentage chain of this register (or stack slot) should take care of all 3108 * issues like callee-saved registers, stack slot allocation time, etc. 3109 */ 3110 static int mark_reg_read(struct bpf_verifier_env *env, 3111 const struct bpf_reg_state *state, 3112 struct bpf_reg_state *parent, u8 flag) 3113 { 3114 bool writes = parent == state->parent; /* Observe write marks */ 3115 int cnt = 0; 3116 3117 while (parent) { 3118 /* if read wasn't screened by an earlier write ... */ 3119 if (writes && state->live & REG_LIVE_WRITTEN) 3120 break; 3121 if (parent->live & REG_LIVE_DONE) { 3122 verbose(env, "verifier BUG type %s var_off %lld off %d\n", 3123 reg_type_str(env, parent->type), 3124 parent->var_off.value, parent->off); 3125 return -EFAULT; 3126 } 3127 /* The first condition is more likely to be true than the 3128 * second, checked it first. 3129 */ 3130 if ((parent->live & REG_LIVE_READ) == flag || 3131 parent->live & REG_LIVE_READ64) 3132 /* The parentage chain never changes and 3133 * this parent was already marked as LIVE_READ. 3134 * There is no need to keep walking the chain again and 3135 * keep re-marking all parents as LIVE_READ. 3136 * This case happens when the same register is read 3137 * multiple times without writes into it in-between. 3138 * Also, if parent has the stronger REG_LIVE_READ64 set, 3139 * then no need to set the weak REG_LIVE_READ32. 3140 */ 3141 break; 3142 /* ... then we depend on parent's value */ 3143 parent->live |= flag; 3144 /* REG_LIVE_READ64 overrides REG_LIVE_READ32. */ 3145 if (flag == REG_LIVE_READ64) 3146 parent->live &= ~REG_LIVE_READ32; 3147 state = parent; 3148 parent = state->parent; 3149 writes = true; 3150 cnt++; 3151 } 3152 3153 if (env->longest_mark_read_walk < cnt) 3154 env->longest_mark_read_walk = cnt; 3155 return 0; 3156 } 3157 3158 static int mark_dynptr_read(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 3159 { 3160 struct bpf_func_state *state = func(env, reg); 3161 int spi, ret; 3162 3163 /* For CONST_PTR_TO_DYNPTR, it must have already been done by 3164 * check_reg_arg in check_helper_call and mark_btf_func_reg_size in 3165 * check_kfunc_call. 3166 */ 3167 if (reg->type == CONST_PTR_TO_DYNPTR) 3168 return 0; 3169 spi = dynptr_get_spi(env, reg); 3170 if (spi < 0) 3171 return spi; 3172 /* Caller ensures dynptr is valid and initialized, which means spi is in 3173 * bounds and spi is the first dynptr slot. Simply mark stack slot as 3174 * read. 3175 */ 3176 ret = mark_reg_read(env, &state->stack[spi].spilled_ptr, 3177 state->stack[spi].spilled_ptr.parent, REG_LIVE_READ64); 3178 if (ret) 3179 return ret; 3180 return mark_reg_read(env, &state->stack[spi - 1].spilled_ptr, 3181 state->stack[spi - 1].spilled_ptr.parent, REG_LIVE_READ64); 3182 } 3183 3184 static int mark_iter_read(struct bpf_verifier_env *env, struct bpf_reg_state *reg, 3185 int spi, int nr_slots) 3186 { 3187 struct bpf_func_state *state = func(env, reg); 3188 int err, i; 3189 3190 for (i = 0; i < nr_slots; i++) { 3191 struct bpf_reg_state *st = &state->stack[spi - i].spilled_ptr; 3192 3193 err = mark_reg_read(env, st, st->parent, REG_LIVE_READ64); 3194 if (err) 3195 return err; 3196 3197 mark_stack_slot_scratched(env, spi - i); 3198 } 3199 3200 return 0; 3201 } 3202 3203 /* This function is supposed to be used by the following 32-bit optimization 3204 * code only. It returns TRUE if the source or destination register operates 3205 * on 64-bit, otherwise return FALSE. 3206 */ 3207 static bool is_reg64(struct bpf_verifier_env *env, struct bpf_insn *insn, 3208 u32 regno, struct bpf_reg_state *reg, enum reg_arg_type t) 3209 { 3210 u8 code, class, op; 3211 3212 code = insn->code; 3213 class = BPF_CLASS(code); 3214 op = BPF_OP(code); 3215 if (class == BPF_JMP) { 3216 /* BPF_EXIT for "main" will reach here. Return TRUE 3217 * conservatively. 3218 */ 3219 if (op == BPF_EXIT) 3220 return true; 3221 if (op == BPF_CALL) { 3222 /* BPF to BPF call will reach here because of marking 3223 * caller saved clobber with DST_OP_NO_MARK for which we 3224 * don't care the register def because they are anyway 3225 * marked as NOT_INIT already. 3226 */ 3227 if (insn->src_reg == BPF_PSEUDO_CALL) 3228 return false; 3229 /* Helper call will reach here because of arg type 3230 * check, conservatively return TRUE. 3231 */ 3232 if (t == SRC_OP) 3233 return true; 3234 3235 return false; 3236 } 3237 } 3238 3239 if (class == BPF_ALU64 && op == BPF_END && (insn->imm == 16 || insn->imm == 32)) 3240 return false; 3241 3242 if (class == BPF_ALU64 || class == BPF_JMP || 3243 (class == BPF_ALU && op == BPF_END && insn->imm == 64)) 3244 return true; 3245 3246 if (class == BPF_ALU || class == BPF_JMP32) 3247 return false; 3248 3249 if (class == BPF_LDX) { 3250 if (t != SRC_OP) 3251 return BPF_SIZE(code) == BPF_DW; 3252 /* LDX source must be ptr. */ 3253 return true; 3254 } 3255 3256 if (class == BPF_STX) { 3257 /* BPF_STX (including atomic variants) has multiple source 3258 * operands, one of which is a ptr. Check whether the caller is 3259 * asking about it. 3260 */ 3261 if (t == SRC_OP && reg->type != SCALAR_VALUE) 3262 return true; 3263 return BPF_SIZE(code) == BPF_DW; 3264 } 3265 3266 if (class == BPF_LD) { 3267 u8 mode = BPF_MODE(code); 3268 3269 /* LD_IMM64 */ 3270 if (mode == BPF_IMM) 3271 return true; 3272 3273 /* Both LD_IND and LD_ABS return 32-bit data. */ 3274 if (t != SRC_OP) 3275 return false; 3276 3277 /* Implicit ctx ptr. */ 3278 if (regno == BPF_REG_6) 3279 return true; 3280 3281 /* Explicit source could be any width. */ 3282 return true; 3283 } 3284 3285 if (class == BPF_ST) 3286 /* The only source register for BPF_ST is a ptr. */ 3287 return true; 3288 3289 /* Conservatively return true at default. */ 3290 return true; 3291 } 3292 3293 /* Return the regno defined by the insn, or -1. */ 3294 static int insn_def_regno(const struct bpf_insn *insn) 3295 { 3296 switch (BPF_CLASS(insn->code)) { 3297 case BPF_JMP: 3298 case BPF_JMP32: 3299 case BPF_ST: 3300 return -1; 3301 case BPF_STX: 3302 if (BPF_MODE(insn->code) == BPF_ATOMIC && 3303 (insn->imm & BPF_FETCH)) { 3304 if (insn->imm == BPF_CMPXCHG) 3305 return BPF_REG_0; 3306 else 3307 return insn->src_reg; 3308 } else { 3309 return -1; 3310 } 3311 default: 3312 return insn->dst_reg; 3313 } 3314 } 3315 3316 /* Return TRUE if INSN has defined any 32-bit value explicitly. */ 3317 static bool insn_has_def32(struct bpf_verifier_env *env, struct bpf_insn *insn) 3318 { 3319 int dst_reg = insn_def_regno(insn); 3320 3321 if (dst_reg == -1) 3322 return false; 3323 3324 return !is_reg64(env, insn, dst_reg, NULL, DST_OP); 3325 } 3326 3327 static void mark_insn_zext(struct bpf_verifier_env *env, 3328 struct bpf_reg_state *reg) 3329 { 3330 s32 def_idx = reg->subreg_def; 3331 3332 if (def_idx == DEF_NOT_SUBREG) 3333 return; 3334 3335 env->insn_aux_data[def_idx - 1].zext_dst = true; 3336 /* The dst will be zero extended, so won't be sub-register anymore. */ 3337 reg->subreg_def = DEF_NOT_SUBREG; 3338 } 3339 3340 static int __check_reg_arg(struct bpf_verifier_env *env, struct bpf_reg_state *regs, u32 regno, 3341 enum reg_arg_type t) 3342 { 3343 struct bpf_insn *insn = env->prog->insnsi + env->insn_idx; 3344 struct bpf_reg_state *reg; 3345 bool rw64; 3346 3347 if (regno >= MAX_BPF_REG) { 3348 verbose(env, "R%d is invalid\n", regno); 3349 return -EINVAL; 3350 } 3351 3352 mark_reg_scratched(env, regno); 3353 3354 reg = ®s[regno]; 3355 rw64 = is_reg64(env, insn, regno, reg, t); 3356 if (t == SRC_OP) { 3357 /* check whether register used as source operand can be read */ 3358 if (reg->type == NOT_INIT) { 3359 verbose(env, "R%d !read_ok\n", regno); 3360 return -EACCES; 3361 } 3362 /* We don't need to worry about FP liveness because it's read-only */ 3363 if (regno == BPF_REG_FP) 3364 return 0; 3365 3366 if (rw64) 3367 mark_insn_zext(env, reg); 3368 3369 return mark_reg_read(env, reg, reg->parent, 3370 rw64 ? REG_LIVE_READ64 : REG_LIVE_READ32); 3371 } else { 3372 /* check whether register used as dest operand can be written to */ 3373 if (regno == BPF_REG_FP) { 3374 verbose(env, "frame pointer is read only\n"); 3375 return -EACCES; 3376 } 3377 reg->live |= REG_LIVE_WRITTEN; 3378 reg->subreg_def = rw64 ? DEF_NOT_SUBREG : env->insn_idx + 1; 3379 if (t == DST_OP) 3380 mark_reg_unknown(env, regs, regno); 3381 } 3382 return 0; 3383 } 3384 3385 static int check_reg_arg(struct bpf_verifier_env *env, u32 regno, 3386 enum reg_arg_type t) 3387 { 3388 struct bpf_verifier_state *vstate = env->cur_state; 3389 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 3390 3391 return __check_reg_arg(env, state->regs, regno, t); 3392 } 3393 3394 static void mark_jmp_point(struct bpf_verifier_env *env, int idx) 3395 { 3396 env->insn_aux_data[idx].jmp_point = true; 3397 } 3398 3399 static bool is_jmp_point(struct bpf_verifier_env *env, int insn_idx) 3400 { 3401 return env->insn_aux_data[insn_idx].jmp_point; 3402 } 3403 3404 /* for any branch, call, exit record the history of jmps in the given state */ 3405 static int push_jmp_history(struct bpf_verifier_env *env, 3406 struct bpf_verifier_state *cur) 3407 { 3408 u32 cnt = cur->jmp_history_cnt; 3409 struct bpf_idx_pair *p; 3410 size_t alloc_size; 3411 3412 if (!is_jmp_point(env, env->insn_idx)) 3413 return 0; 3414 3415 cnt++; 3416 alloc_size = kmalloc_size_roundup(size_mul(cnt, sizeof(*p))); 3417 p = krealloc(cur->jmp_history, alloc_size, GFP_USER); 3418 if (!p) 3419 return -ENOMEM; 3420 p[cnt - 1].idx = env->insn_idx; 3421 p[cnt - 1].prev_idx = env->prev_insn_idx; 3422 cur->jmp_history = p; 3423 cur->jmp_history_cnt = cnt; 3424 return 0; 3425 } 3426 3427 /* Backtrack one insn at a time. If idx is not at the top of recorded 3428 * history then previous instruction came from straight line execution. 3429 * Return -ENOENT if we exhausted all instructions within given state. 3430 * 3431 * It's legal to have a bit of a looping with the same starting and ending 3432 * insn index within the same state, e.g.: 3->4->5->3, so just because current 3433 * instruction index is the same as state's first_idx doesn't mean we are 3434 * done. If there is still some jump history left, we should keep going. We 3435 * need to take into account that we might have a jump history between given 3436 * state's parent and itself, due to checkpointing. In this case, we'll have 3437 * history entry recording a jump from last instruction of parent state and 3438 * first instruction of given state. 3439 */ 3440 static int get_prev_insn_idx(struct bpf_verifier_state *st, int i, 3441 u32 *history) 3442 { 3443 u32 cnt = *history; 3444 3445 if (i == st->first_insn_idx) { 3446 if (cnt == 0) 3447 return -ENOENT; 3448 if (cnt == 1 && st->jmp_history[0].idx == i) 3449 return -ENOENT; 3450 } 3451 3452 if (cnt && st->jmp_history[cnt - 1].idx == i) { 3453 i = st->jmp_history[cnt - 1].prev_idx; 3454 (*history)--; 3455 } else { 3456 i--; 3457 } 3458 return i; 3459 } 3460 3461 static const char *disasm_kfunc_name(void *data, const struct bpf_insn *insn) 3462 { 3463 const struct btf_type *func; 3464 struct btf *desc_btf; 3465 3466 if (insn->src_reg != BPF_PSEUDO_KFUNC_CALL) 3467 return NULL; 3468 3469 desc_btf = find_kfunc_desc_btf(data, insn->off); 3470 if (IS_ERR(desc_btf)) 3471 return "<error>"; 3472 3473 func = btf_type_by_id(desc_btf, insn->imm); 3474 return btf_name_by_offset(desc_btf, func->name_off); 3475 } 3476 3477 static inline void bt_init(struct backtrack_state *bt, u32 frame) 3478 { 3479 bt->frame = frame; 3480 } 3481 3482 static inline void bt_reset(struct backtrack_state *bt) 3483 { 3484 struct bpf_verifier_env *env = bt->env; 3485 3486 memset(bt, 0, sizeof(*bt)); 3487 bt->env = env; 3488 } 3489 3490 static inline u32 bt_empty(struct backtrack_state *bt) 3491 { 3492 u64 mask = 0; 3493 int i; 3494 3495 for (i = 0; i <= bt->frame; i++) 3496 mask |= bt->reg_masks[i] | bt->stack_masks[i]; 3497 3498 return mask == 0; 3499 } 3500 3501 static inline int bt_subprog_enter(struct backtrack_state *bt) 3502 { 3503 if (bt->frame == MAX_CALL_FRAMES - 1) { 3504 verbose(bt->env, "BUG subprog enter from frame %d\n", bt->frame); 3505 WARN_ONCE(1, "verifier backtracking bug"); 3506 return -EFAULT; 3507 } 3508 bt->frame++; 3509 return 0; 3510 } 3511 3512 static inline int bt_subprog_exit(struct backtrack_state *bt) 3513 { 3514 if (bt->frame == 0) { 3515 verbose(bt->env, "BUG subprog exit from frame 0\n"); 3516 WARN_ONCE(1, "verifier backtracking bug"); 3517 return -EFAULT; 3518 } 3519 bt->frame--; 3520 return 0; 3521 } 3522 3523 static inline void bt_set_frame_reg(struct backtrack_state *bt, u32 frame, u32 reg) 3524 { 3525 bt->reg_masks[frame] |= 1 << reg; 3526 } 3527 3528 static inline void bt_clear_frame_reg(struct backtrack_state *bt, u32 frame, u32 reg) 3529 { 3530 bt->reg_masks[frame] &= ~(1 << reg); 3531 } 3532 3533 static inline void bt_set_reg(struct backtrack_state *bt, u32 reg) 3534 { 3535 bt_set_frame_reg(bt, bt->frame, reg); 3536 } 3537 3538 static inline void bt_clear_reg(struct backtrack_state *bt, u32 reg) 3539 { 3540 bt_clear_frame_reg(bt, bt->frame, reg); 3541 } 3542 3543 static inline void bt_set_frame_slot(struct backtrack_state *bt, u32 frame, u32 slot) 3544 { 3545 bt->stack_masks[frame] |= 1ull << slot; 3546 } 3547 3548 static inline void bt_clear_frame_slot(struct backtrack_state *bt, u32 frame, u32 slot) 3549 { 3550 bt->stack_masks[frame] &= ~(1ull << slot); 3551 } 3552 3553 static inline void bt_set_slot(struct backtrack_state *bt, u32 slot) 3554 { 3555 bt_set_frame_slot(bt, bt->frame, slot); 3556 } 3557 3558 static inline void bt_clear_slot(struct backtrack_state *bt, u32 slot) 3559 { 3560 bt_clear_frame_slot(bt, bt->frame, slot); 3561 } 3562 3563 static inline u32 bt_frame_reg_mask(struct backtrack_state *bt, u32 frame) 3564 { 3565 return bt->reg_masks[frame]; 3566 } 3567 3568 static inline u32 bt_reg_mask(struct backtrack_state *bt) 3569 { 3570 return bt->reg_masks[bt->frame]; 3571 } 3572 3573 static inline u64 bt_frame_stack_mask(struct backtrack_state *bt, u32 frame) 3574 { 3575 return bt->stack_masks[frame]; 3576 } 3577 3578 static inline u64 bt_stack_mask(struct backtrack_state *bt) 3579 { 3580 return bt->stack_masks[bt->frame]; 3581 } 3582 3583 static inline bool bt_is_reg_set(struct backtrack_state *bt, u32 reg) 3584 { 3585 return bt->reg_masks[bt->frame] & (1 << reg); 3586 } 3587 3588 static inline bool bt_is_slot_set(struct backtrack_state *bt, u32 slot) 3589 { 3590 return bt->stack_masks[bt->frame] & (1ull << slot); 3591 } 3592 3593 /* format registers bitmask, e.g., "r0,r2,r4" for 0x15 mask */ 3594 static void fmt_reg_mask(char *buf, ssize_t buf_sz, u32 reg_mask) 3595 { 3596 DECLARE_BITMAP(mask, 64); 3597 bool first = true; 3598 int i, n; 3599 3600 buf[0] = '\0'; 3601 3602 bitmap_from_u64(mask, reg_mask); 3603 for_each_set_bit(i, mask, 32) { 3604 n = snprintf(buf, buf_sz, "%sr%d", first ? "" : ",", i); 3605 first = false; 3606 buf += n; 3607 buf_sz -= n; 3608 if (buf_sz < 0) 3609 break; 3610 } 3611 } 3612 /* format stack slots bitmask, e.g., "-8,-24,-40" for 0x15 mask */ 3613 static void fmt_stack_mask(char *buf, ssize_t buf_sz, u64 stack_mask) 3614 { 3615 DECLARE_BITMAP(mask, 64); 3616 bool first = true; 3617 int i, n; 3618 3619 buf[0] = '\0'; 3620 3621 bitmap_from_u64(mask, stack_mask); 3622 for_each_set_bit(i, mask, 64) { 3623 n = snprintf(buf, buf_sz, "%s%d", first ? "" : ",", -(i + 1) * 8); 3624 first = false; 3625 buf += n; 3626 buf_sz -= n; 3627 if (buf_sz < 0) 3628 break; 3629 } 3630 } 3631 3632 static bool calls_callback(struct bpf_verifier_env *env, int insn_idx); 3633 3634 /* For given verifier state backtrack_insn() is called from the last insn to 3635 * the first insn. Its purpose is to compute a bitmask of registers and 3636 * stack slots that needs precision in the parent verifier state. 3637 * 3638 * @idx is an index of the instruction we are currently processing; 3639 * @subseq_idx is an index of the subsequent instruction that: 3640 * - *would be* executed next, if jump history is viewed in forward order; 3641 * - *was* processed previously during backtracking. 3642 */ 3643 static int backtrack_insn(struct bpf_verifier_env *env, int idx, int subseq_idx, 3644 struct backtrack_state *bt) 3645 { 3646 const struct bpf_insn_cbs cbs = { 3647 .cb_call = disasm_kfunc_name, 3648 .cb_print = verbose, 3649 .private_data = env, 3650 }; 3651 struct bpf_insn *insn = env->prog->insnsi + idx; 3652 u8 class = BPF_CLASS(insn->code); 3653 u8 opcode = BPF_OP(insn->code); 3654 u8 mode = BPF_MODE(insn->code); 3655 u32 dreg = insn->dst_reg; 3656 u32 sreg = insn->src_reg; 3657 u32 spi, i; 3658 3659 if (insn->code == 0) 3660 return 0; 3661 if (env->log.level & BPF_LOG_LEVEL2) { 3662 fmt_reg_mask(env->tmp_str_buf, TMP_STR_BUF_LEN, bt_reg_mask(bt)); 3663 verbose(env, "mark_precise: frame%d: regs=%s ", 3664 bt->frame, env->tmp_str_buf); 3665 fmt_stack_mask(env->tmp_str_buf, TMP_STR_BUF_LEN, bt_stack_mask(bt)); 3666 verbose(env, "stack=%s before ", env->tmp_str_buf); 3667 verbose(env, "%d: ", idx); 3668 print_bpf_insn(&cbs, insn, env->allow_ptr_leaks); 3669 } 3670 3671 if (class == BPF_ALU || class == BPF_ALU64) { 3672 if (!bt_is_reg_set(bt, dreg)) 3673 return 0; 3674 if (opcode == BPF_END || opcode == BPF_NEG) { 3675 /* sreg is reserved and unused 3676 * dreg still need precision before this insn 3677 */ 3678 return 0; 3679 } else if (opcode == BPF_MOV) { 3680 if (BPF_SRC(insn->code) == BPF_X) { 3681 /* dreg = sreg or dreg = (s8, s16, s32)sreg 3682 * dreg needs precision after this insn 3683 * sreg needs precision before this insn 3684 */ 3685 bt_clear_reg(bt, dreg); 3686 if (sreg != BPF_REG_FP) 3687 bt_set_reg(bt, sreg); 3688 } else { 3689 /* dreg = K 3690 * dreg needs precision after this insn. 3691 * Corresponding register is already marked 3692 * as precise=true in this verifier state. 3693 * No further markings in parent are necessary 3694 */ 3695 bt_clear_reg(bt, dreg); 3696 } 3697 } else { 3698 if (BPF_SRC(insn->code) == BPF_X) { 3699 /* dreg += sreg 3700 * both dreg and sreg need precision 3701 * before this insn 3702 */ 3703 if (sreg != BPF_REG_FP) 3704 bt_set_reg(bt, sreg); 3705 } /* else dreg += K 3706 * dreg still needs precision before this insn 3707 */ 3708 } 3709 } else if (class == BPF_LDX) { 3710 if (!bt_is_reg_set(bt, dreg)) 3711 return 0; 3712 bt_clear_reg(bt, dreg); 3713 3714 /* scalars can only be spilled into stack w/o losing precision. 3715 * Load from any other memory can be zero extended. 3716 * The desire to keep that precision is already indicated 3717 * by 'precise' mark in corresponding register of this state. 3718 * No further tracking necessary. 3719 */ 3720 if (insn->src_reg != BPF_REG_FP) 3721 return 0; 3722 3723 /* dreg = *(u64 *)[fp - off] was a fill from the stack. 3724 * that [fp - off] slot contains scalar that needs to be 3725 * tracked with precision 3726 */ 3727 spi = (-insn->off - 1) / BPF_REG_SIZE; 3728 if (spi >= 64) { 3729 verbose(env, "BUG spi %d\n", spi); 3730 WARN_ONCE(1, "verifier backtracking bug"); 3731 return -EFAULT; 3732 } 3733 bt_set_slot(bt, spi); 3734 } else if (class == BPF_STX || class == BPF_ST) { 3735 if (bt_is_reg_set(bt, dreg)) 3736 /* stx & st shouldn't be using _scalar_ dst_reg 3737 * to access memory. It means backtracking 3738 * encountered a case of pointer subtraction. 3739 */ 3740 return -ENOTSUPP; 3741 /* scalars can only be spilled into stack */ 3742 if (insn->dst_reg != BPF_REG_FP) 3743 return 0; 3744 spi = (-insn->off - 1) / BPF_REG_SIZE; 3745 if (spi >= 64) { 3746 verbose(env, "BUG spi %d\n", spi); 3747 WARN_ONCE(1, "verifier backtracking bug"); 3748 return -EFAULT; 3749 } 3750 if (!bt_is_slot_set(bt, spi)) 3751 return 0; 3752 bt_clear_slot(bt, spi); 3753 if (class == BPF_STX) 3754 bt_set_reg(bt, sreg); 3755 } else if (class == BPF_JMP || class == BPF_JMP32) { 3756 if (bpf_pseudo_call(insn)) { 3757 int subprog_insn_idx, subprog; 3758 3759 subprog_insn_idx = idx + insn->imm + 1; 3760 subprog = find_subprog(env, subprog_insn_idx); 3761 if (subprog < 0) 3762 return -EFAULT; 3763 3764 if (subprog_is_global(env, subprog)) { 3765 /* check that jump history doesn't have any 3766 * extra instructions from subprog; the next 3767 * instruction after call to global subprog 3768 * should be literally next instruction in 3769 * caller program 3770 */ 3771 WARN_ONCE(idx + 1 != subseq_idx, "verifier backtracking bug"); 3772 /* r1-r5 are invalidated after subprog call, 3773 * so for global func call it shouldn't be set 3774 * anymore 3775 */ 3776 if (bt_reg_mask(bt) & BPF_REGMASK_ARGS) { 3777 verbose(env, "BUG regs %x\n", bt_reg_mask(bt)); 3778 WARN_ONCE(1, "verifier backtracking bug"); 3779 return -EFAULT; 3780 } 3781 /* global subprog always sets R0 */ 3782 bt_clear_reg(bt, BPF_REG_0); 3783 return 0; 3784 } else { 3785 /* static subprog call instruction, which 3786 * means that we are exiting current subprog, 3787 * so only r1-r5 could be still requested as 3788 * precise, r0 and r6-r10 or any stack slot in 3789 * the current frame should be zero by now 3790 */ 3791 if (bt_reg_mask(bt) & ~BPF_REGMASK_ARGS) { 3792 verbose(env, "BUG regs %x\n", bt_reg_mask(bt)); 3793 WARN_ONCE(1, "verifier backtracking bug"); 3794 return -EFAULT; 3795 } 3796 /* we don't track register spills perfectly, 3797 * so fallback to force-precise instead of failing */ 3798 if (bt_stack_mask(bt) != 0) 3799 return -ENOTSUPP; 3800 /* propagate r1-r5 to the caller */ 3801 for (i = BPF_REG_1; i <= BPF_REG_5; i++) { 3802 if (bt_is_reg_set(bt, i)) { 3803 bt_clear_reg(bt, i); 3804 bt_set_frame_reg(bt, bt->frame - 1, i); 3805 } 3806 } 3807 if (bt_subprog_exit(bt)) 3808 return -EFAULT; 3809 return 0; 3810 } 3811 } else if (is_sync_callback_calling_insn(insn) && idx != subseq_idx - 1) { 3812 /* exit from callback subprog to callback-calling helper or 3813 * kfunc call. Use idx/subseq_idx check to discern it from 3814 * straight line code backtracking. 3815 * Unlike the subprog call handling above, we shouldn't 3816 * propagate precision of r1-r5 (if any requested), as they are 3817 * not actually arguments passed directly to callback subprogs 3818 */ 3819 if (bt_reg_mask(bt) & ~BPF_REGMASK_ARGS) { 3820 verbose(env, "BUG regs %x\n", bt_reg_mask(bt)); 3821 WARN_ONCE(1, "verifier backtracking bug"); 3822 return -EFAULT; 3823 } 3824 if (bt_stack_mask(bt) != 0) 3825 return -ENOTSUPP; 3826 /* clear r1-r5 in callback subprog's mask */ 3827 for (i = BPF_REG_1; i <= BPF_REG_5; i++) 3828 bt_clear_reg(bt, i); 3829 if (bt_subprog_exit(bt)) 3830 return -EFAULT; 3831 return 0; 3832 } else if (opcode == BPF_CALL) { 3833 /* kfunc with imm==0 is invalid and fixup_kfunc_call will 3834 * catch this error later. Make backtracking conservative 3835 * with ENOTSUPP. 3836 */ 3837 if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL && insn->imm == 0) 3838 return -ENOTSUPP; 3839 /* regular helper call sets R0 */ 3840 bt_clear_reg(bt, BPF_REG_0); 3841 if (bt_reg_mask(bt) & BPF_REGMASK_ARGS) { 3842 /* if backtracing was looking for registers R1-R5 3843 * they should have been found already. 3844 */ 3845 verbose(env, "BUG regs %x\n", bt_reg_mask(bt)); 3846 WARN_ONCE(1, "verifier backtracking bug"); 3847 return -EFAULT; 3848 } 3849 } else if (opcode == BPF_EXIT) { 3850 bool r0_precise; 3851 3852 /* Backtracking to a nested function call, 'idx' is a part of 3853 * the inner frame 'subseq_idx' is a part of the outer frame. 3854 * In case of a regular function call, instructions giving 3855 * precision to registers R1-R5 should have been found already. 3856 * In case of a callback, it is ok to have R1-R5 marked for 3857 * backtracking, as these registers are set by the function 3858 * invoking callback. 3859 */ 3860 if (subseq_idx >= 0 && calls_callback(env, subseq_idx)) 3861 for (i = BPF_REG_1; i <= BPF_REG_5; i++) 3862 bt_clear_reg(bt, i); 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 3869 /* BPF_EXIT in subprog or callback always returns 3870 * right after the call instruction, so by checking 3871 * whether the instruction at subseq_idx-1 is subprog 3872 * call or not we can distinguish actual exit from 3873 * *subprog* from exit from *callback*. In the former 3874 * case, we need to propagate r0 precision, if 3875 * necessary. In the former we never do that. 3876 */ 3877 r0_precise = subseq_idx - 1 >= 0 && 3878 bpf_pseudo_call(&env->prog->insnsi[subseq_idx - 1]) && 3879 bt_is_reg_set(bt, BPF_REG_0); 3880 3881 bt_clear_reg(bt, BPF_REG_0); 3882 if (bt_subprog_enter(bt)) 3883 return -EFAULT; 3884 3885 if (r0_precise) 3886 bt_set_reg(bt, BPF_REG_0); 3887 /* r6-r9 and stack slots will stay set in caller frame 3888 * bitmasks until we return back from callee(s) 3889 */ 3890 return 0; 3891 } else if (BPF_SRC(insn->code) == BPF_X) { 3892 if (!bt_is_reg_set(bt, dreg) && !bt_is_reg_set(bt, sreg)) 3893 return 0; 3894 /* dreg <cond> sreg 3895 * Both dreg and sreg need precision before 3896 * this insn. If only sreg was marked precise 3897 * before it would be equally necessary to 3898 * propagate it to dreg. 3899 */ 3900 bt_set_reg(bt, dreg); 3901 bt_set_reg(bt, sreg); 3902 /* else dreg <cond> K 3903 * Only dreg still needs precision before 3904 * this insn, so for the K-based conditional 3905 * there is nothing new to be marked. 3906 */ 3907 } 3908 } else if (class == BPF_LD) { 3909 if (!bt_is_reg_set(bt, dreg)) 3910 return 0; 3911 bt_clear_reg(bt, dreg); 3912 /* It's ld_imm64 or ld_abs or ld_ind. 3913 * For ld_imm64 no further tracking of precision 3914 * into parent is necessary 3915 */ 3916 if (mode == BPF_IND || mode == BPF_ABS) 3917 /* to be analyzed */ 3918 return -ENOTSUPP; 3919 } 3920 return 0; 3921 } 3922 3923 /* the scalar precision tracking algorithm: 3924 * . at the start all registers have precise=false. 3925 * . scalar ranges are tracked as normal through alu and jmp insns. 3926 * . once precise value of the scalar register is used in: 3927 * . ptr + scalar alu 3928 * . if (scalar cond K|scalar) 3929 * . helper_call(.., scalar, ...) where ARG_CONST is expected 3930 * backtrack through the verifier states and mark all registers and 3931 * stack slots with spilled constants that these scalar regisers 3932 * should be precise. 3933 * . during state pruning two registers (or spilled stack slots) 3934 * are equivalent if both are not precise. 3935 * 3936 * Note the verifier cannot simply walk register parentage chain, 3937 * since many different registers and stack slots could have been 3938 * used to compute single precise scalar. 3939 * 3940 * The approach of starting with precise=true for all registers and then 3941 * backtrack to mark a register as not precise when the verifier detects 3942 * that program doesn't care about specific value (e.g., when helper 3943 * takes register as ARG_ANYTHING parameter) is not safe. 3944 * 3945 * It's ok to walk single parentage chain of the verifier states. 3946 * It's possible that this backtracking will go all the way till 1st insn. 3947 * All other branches will be explored for needing precision later. 3948 * 3949 * The backtracking needs to deal with cases like: 3950 * 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) 3951 * r9 -= r8 3952 * r5 = r9 3953 * if r5 > 0x79f goto pc+7 3954 * R5_w=inv(id=0,umax_value=1951,var_off=(0x0; 0x7ff)) 3955 * r5 += 1 3956 * ... 3957 * call bpf_perf_event_output#25 3958 * where .arg5_type = ARG_CONST_SIZE_OR_ZERO 3959 * 3960 * and this case: 3961 * r6 = 1 3962 * call foo // uses callee's r6 inside to compute r0 3963 * r0 += r6 3964 * if r0 == 0 goto 3965 * 3966 * to track above reg_mask/stack_mask needs to be independent for each frame. 3967 * 3968 * Also if parent's curframe > frame where backtracking started, 3969 * the verifier need to mark registers in both frames, otherwise callees 3970 * may incorrectly prune callers. This is similar to 3971 * commit 7640ead93924 ("bpf: verifier: make sure callees don't prune with caller differences") 3972 * 3973 * For now backtracking falls back into conservative marking. 3974 */ 3975 static void mark_all_scalars_precise(struct bpf_verifier_env *env, 3976 struct bpf_verifier_state *st) 3977 { 3978 struct bpf_func_state *func; 3979 struct bpf_reg_state *reg; 3980 int i, j; 3981 3982 if (env->log.level & BPF_LOG_LEVEL2) { 3983 verbose(env, "mark_precise: frame%d: falling back to forcing all scalars precise\n", 3984 st->curframe); 3985 } 3986 3987 /* big hammer: mark all scalars precise in this path. 3988 * pop_stack may still get !precise scalars. 3989 * We also skip current state and go straight to first parent state, 3990 * because precision markings in current non-checkpointed state are 3991 * not needed. See why in the comment in __mark_chain_precision below. 3992 */ 3993 for (st = st->parent; st; st = st->parent) { 3994 for (i = 0; i <= st->curframe; i++) { 3995 func = st->frame[i]; 3996 for (j = 0; j < BPF_REG_FP; j++) { 3997 reg = &func->regs[j]; 3998 if (reg->type != SCALAR_VALUE || reg->precise) 3999 continue; 4000 reg->precise = true; 4001 if (env->log.level & BPF_LOG_LEVEL2) { 4002 verbose(env, "force_precise: frame%d: forcing r%d to be precise\n", 4003 i, j); 4004 } 4005 } 4006 for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) { 4007 if (!is_spilled_reg(&func->stack[j])) 4008 continue; 4009 reg = &func->stack[j].spilled_ptr; 4010 if (reg->type != SCALAR_VALUE || reg->precise) 4011 continue; 4012 reg->precise = true; 4013 if (env->log.level & BPF_LOG_LEVEL2) { 4014 verbose(env, "force_precise: frame%d: forcing fp%d to be precise\n", 4015 i, -(j + 1) * 8); 4016 } 4017 } 4018 } 4019 } 4020 } 4021 4022 static void mark_all_scalars_imprecise(struct bpf_verifier_env *env, struct bpf_verifier_state *st) 4023 { 4024 struct bpf_func_state *func; 4025 struct bpf_reg_state *reg; 4026 int i, j; 4027 4028 for (i = 0; i <= st->curframe; i++) { 4029 func = st->frame[i]; 4030 for (j = 0; j < BPF_REG_FP; j++) { 4031 reg = &func->regs[j]; 4032 if (reg->type != SCALAR_VALUE) 4033 continue; 4034 reg->precise = false; 4035 } 4036 for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) { 4037 if (!is_spilled_reg(&func->stack[j])) 4038 continue; 4039 reg = &func->stack[j].spilled_ptr; 4040 if (reg->type != SCALAR_VALUE) 4041 continue; 4042 reg->precise = false; 4043 } 4044 } 4045 } 4046 4047 static bool idset_contains(struct bpf_idset *s, u32 id) 4048 { 4049 u32 i; 4050 4051 for (i = 0; i < s->count; ++i) 4052 if (s->ids[i] == id) 4053 return true; 4054 4055 return false; 4056 } 4057 4058 static int idset_push(struct bpf_idset *s, u32 id) 4059 { 4060 if (WARN_ON_ONCE(s->count >= ARRAY_SIZE(s->ids))) 4061 return -EFAULT; 4062 s->ids[s->count++] = id; 4063 return 0; 4064 } 4065 4066 static void idset_reset(struct bpf_idset *s) 4067 { 4068 s->count = 0; 4069 } 4070 4071 /* Collect a set of IDs for all registers currently marked as precise in env->bt. 4072 * Mark all registers with these IDs as precise. 4073 */ 4074 static int mark_precise_scalar_ids(struct bpf_verifier_env *env, struct bpf_verifier_state *st) 4075 { 4076 struct bpf_idset *precise_ids = &env->idset_scratch; 4077 struct backtrack_state *bt = &env->bt; 4078 struct bpf_func_state *func; 4079 struct bpf_reg_state *reg; 4080 DECLARE_BITMAP(mask, 64); 4081 int i, fr; 4082 4083 idset_reset(precise_ids); 4084 4085 for (fr = bt->frame; fr >= 0; fr--) { 4086 func = st->frame[fr]; 4087 4088 bitmap_from_u64(mask, bt_frame_reg_mask(bt, fr)); 4089 for_each_set_bit(i, mask, 32) { 4090 reg = &func->regs[i]; 4091 if (!reg->id || reg->type != SCALAR_VALUE) 4092 continue; 4093 if (idset_push(precise_ids, reg->id)) 4094 return -EFAULT; 4095 } 4096 4097 bitmap_from_u64(mask, bt_frame_stack_mask(bt, fr)); 4098 for_each_set_bit(i, mask, 64) { 4099 if (i >= func->allocated_stack / BPF_REG_SIZE) 4100 break; 4101 if (!is_spilled_scalar_reg(&func->stack[i])) 4102 continue; 4103 reg = &func->stack[i].spilled_ptr; 4104 if (!reg->id) 4105 continue; 4106 if (idset_push(precise_ids, reg->id)) 4107 return -EFAULT; 4108 } 4109 } 4110 4111 for (fr = 0; fr <= st->curframe; ++fr) { 4112 func = st->frame[fr]; 4113 4114 for (i = BPF_REG_0; i < BPF_REG_10; ++i) { 4115 reg = &func->regs[i]; 4116 if (!reg->id) 4117 continue; 4118 if (!idset_contains(precise_ids, reg->id)) 4119 continue; 4120 bt_set_frame_reg(bt, fr, i); 4121 } 4122 for (i = 0; i < func->allocated_stack / BPF_REG_SIZE; ++i) { 4123 if (!is_spilled_scalar_reg(&func->stack[i])) 4124 continue; 4125 reg = &func->stack[i].spilled_ptr; 4126 if (!reg->id) 4127 continue; 4128 if (!idset_contains(precise_ids, reg->id)) 4129 continue; 4130 bt_set_frame_slot(bt, fr, i); 4131 } 4132 } 4133 4134 return 0; 4135 } 4136 4137 /* 4138 * __mark_chain_precision() backtracks BPF program instruction sequence and 4139 * chain of verifier states making sure that register *regno* (if regno >= 0) 4140 * and/or stack slot *spi* (if spi >= 0) are marked as precisely tracked 4141 * SCALARS, as well as any other registers and slots that contribute to 4142 * a tracked state of given registers/stack slots, depending on specific BPF 4143 * assembly instructions (see backtrack_insns() for exact instruction handling 4144 * logic). This backtracking relies on recorded jmp_history and is able to 4145 * traverse entire chain of parent states. This process ends only when all the 4146 * necessary registers/slots and their transitive dependencies are marked as 4147 * precise. 4148 * 4149 * One important and subtle aspect is that precise marks *do not matter* in 4150 * the currently verified state (current state). It is important to understand 4151 * why this is the case. 4152 * 4153 * First, note that current state is the state that is not yet "checkpointed", 4154 * i.e., it is not yet put into env->explored_states, and it has no children 4155 * states as well. It's ephemeral, and can end up either a) being discarded if 4156 * compatible explored state is found at some point or BPF_EXIT instruction is 4157 * reached or b) checkpointed and put into env->explored_states, branching out 4158 * into one or more children states. 4159 * 4160 * In the former case, precise markings in current state are completely 4161 * ignored by state comparison code (see regsafe() for details). Only 4162 * checkpointed ("old") state precise markings are important, and if old 4163 * state's register/slot is precise, regsafe() assumes current state's 4164 * register/slot as precise and checks value ranges exactly and precisely. If 4165 * states turn out to be compatible, current state's necessary precise 4166 * markings and any required parent states' precise markings are enforced 4167 * after the fact with propagate_precision() logic, after the fact. But it's 4168 * important to realize that in this case, even after marking current state 4169 * registers/slots as precise, we immediately discard current state. So what 4170 * actually matters is any of the precise markings propagated into current 4171 * state's parent states, which are always checkpointed (due to b) case above). 4172 * As such, for scenario a) it doesn't matter if current state has precise 4173 * markings set or not. 4174 * 4175 * Now, for the scenario b), checkpointing and forking into child(ren) 4176 * state(s). Note that before current state gets to checkpointing step, any 4177 * processed instruction always assumes precise SCALAR register/slot 4178 * knowledge: if precise value or range is useful to prune jump branch, BPF 4179 * verifier takes this opportunity enthusiastically. Similarly, when 4180 * register's value is used to calculate offset or memory address, exact 4181 * knowledge of SCALAR range is assumed, checked, and enforced. So, similar to 4182 * what we mentioned above about state comparison ignoring precise markings 4183 * during state comparison, BPF verifier ignores and also assumes precise 4184 * markings *at will* during instruction verification process. But as verifier 4185 * assumes precision, it also propagates any precision dependencies across 4186 * parent states, which are not yet finalized, so can be further restricted 4187 * based on new knowledge gained from restrictions enforced by their children 4188 * states. This is so that once those parent states are finalized, i.e., when 4189 * they have no more active children state, state comparison logic in 4190 * is_state_visited() would enforce strict and precise SCALAR ranges, if 4191 * required for correctness. 4192 * 4193 * To build a bit more intuition, note also that once a state is checkpointed, 4194 * the path we took to get to that state is not important. This is crucial 4195 * property for state pruning. When state is checkpointed and finalized at 4196 * some instruction index, it can be correctly and safely used to "short 4197 * circuit" any *compatible* state that reaches exactly the same instruction 4198 * index. I.e., if we jumped to that instruction from a completely different 4199 * code path than original finalized state was derived from, it doesn't 4200 * matter, current state can be discarded because from that instruction 4201 * forward having a compatible state will ensure we will safely reach the 4202 * exit. States describe preconditions for further exploration, but completely 4203 * forget the history of how we got here. 4204 * 4205 * This also means that even if we needed precise SCALAR range to get to 4206 * finalized state, but from that point forward *that same* SCALAR register is 4207 * never used in a precise context (i.e., it's precise value is not needed for 4208 * correctness), it's correct and safe to mark such register as "imprecise" 4209 * (i.e., precise marking set to false). This is what we rely on when we do 4210 * not set precise marking in current state. If no child state requires 4211 * precision for any given SCALAR register, it's safe to dictate that it can 4212 * be imprecise. If any child state does require this register to be precise, 4213 * we'll mark it precise later retroactively during precise markings 4214 * propagation from child state to parent states. 4215 * 4216 * Skipping precise marking setting in current state is a mild version of 4217 * relying on the above observation. But we can utilize this property even 4218 * more aggressively by proactively forgetting any precise marking in the 4219 * current state (which we inherited from the parent state), right before we 4220 * checkpoint it and branch off into new child state. This is done by 4221 * mark_all_scalars_imprecise() to hopefully get more permissive and generic 4222 * finalized states which help in short circuiting more future states. 4223 */ 4224 static int __mark_chain_precision(struct bpf_verifier_env *env, int regno) 4225 { 4226 struct backtrack_state *bt = &env->bt; 4227 struct bpf_verifier_state *st = env->cur_state; 4228 int first_idx = st->first_insn_idx; 4229 int last_idx = env->insn_idx; 4230 int subseq_idx = -1; 4231 struct bpf_func_state *func; 4232 struct bpf_reg_state *reg; 4233 bool skip_first = true; 4234 int i, fr, err; 4235 4236 if (!env->bpf_capable) 4237 return 0; 4238 4239 /* set frame number from which we are starting to backtrack */ 4240 bt_init(bt, env->cur_state->curframe); 4241 4242 /* Do sanity checks against current state of register and/or stack 4243 * slot, but don't set precise flag in current state, as precision 4244 * tracking in the current state is unnecessary. 4245 */ 4246 func = st->frame[bt->frame]; 4247 if (regno >= 0) { 4248 reg = &func->regs[regno]; 4249 if (reg->type != SCALAR_VALUE) { 4250 WARN_ONCE(1, "backtracing misuse"); 4251 return -EFAULT; 4252 } 4253 bt_set_reg(bt, regno); 4254 } 4255 4256 if (bt_empty(bt)) 4257 return 0; 4258 4259 for (;;) { 4260 DECLARE_BITMAP(mask, 64); 4261 u32 history = st->jmp_history_cnt; 4262 4263 if (env->log.level & BPF_LOG_LEVEL2) { 4264 verbose(env, "mark_precise: frame%d: last_idx %d first_idx %d subseq_idx %d \n", 4265 bt->frame, last_idx, first_idx, subseq_idx); 4266 } 4267 4268 /* If some register with scalar ID is marked as precise, 4269 * make sure that all registers sharing this ID are also precise. 4270 * This is needed to estimate effect of find_equal_scalars(). 4271 * Do this at the last instruction of each state, 4272 * bpf_reg_state::id fields are valid for these instructions. 4273 * 4274 * Allows to track precision in situation like below: 4275 * 4276 * r2 = unknown value 4277 * ... 4278 * --- state #0 --- 4279 * ... 4280 * r1 = r2 // r1 and r2 now share the same ID 4281 * ... 4282 * --- state #1 {r1.id = A, r2.id = A} --- 4283 * ... 4284 * if (r2 > 10) goto exit; // find_equal_scalars() assigns range to r1 4285 * ... 4286 * --- state #2 {r1.id = A, r2.id = A} --- 4287 * r3 = r10 4288 * r3 += r1 // need to mark both r1 and r2 4289 */ 4290 if (mark_precise_scalar_ids(env, st)) 4291 return -EFAULT; 4292 4293 if (last_idx < 0) { 4294 /* we are at the entry into subprog, which 4295 * is expected for global funcs, but only if 4296 * requested precise registers are R1-R5 4297 * (which are global func's input arguments) 4298 */ 4299 if (st->curframe == 0 && 4300 st->frame[0]->subprogno > 0 && 4301 st->frame[0]->callsite == BPF_MAIN_FUNC && 4302 bt_stack_mask(bt) == 0 && 4303 (bt_reg_mask(bt) & ~BPF_REGMASK_ARGS) == 0) { 4304 bitmap_from_u64(mask, bt_reg_mask(bt)); 4305 for_each_set_bit(i, mask, 32) { 4306 reg = &st->frame[0]->regs[i]; 4307 bt_clear_reg(bt, i); 4308 if (reg->type == SCALAR_VALUE) 4309 reg->precise = true; 4310 } 4311 return 0; 4312 } 4313 4314 verbose(env, "BUG backtracking func entry subprog %d reg_mask %x stack_mask %llx\n", 4315 st->frame[0]->subprogno, bt_reg_mask(bt), bt_stack_mask(bt)); 4316 WARN_ONCE(1, "verifier backtracking bug"); 4317 return -EFAULT; 4318 } 4319 4320 for (i = last_idx;;) { 4321 if (skip_first) { 4322 err = 0; 4323 skip_first = false; 4324 } else { 4325 err = backtrack_insn(env, i, subseq_idx, bt); 4326 } 4327 if (err == -ENOTSUPP) { 4328 mark_all_scalars_precise(env, env->cur_state); 4329 bt_reset(bt); 4330 return 0; 4331 } else if (err) { 4332 return err; 4333 } 4334 if (bt_empty(bt)) 4335 /* Found assignment(s) into tracked register in this state. 4336 * Since this state is already marked, just return. 4337 * Nothing to be tracked further in the parent state. 4338 */ 4339 return 0; 4340 subseq_idx = i; 4341 i = get_prev_insn_idx(st, i, &history); 4342 if (i == -ENOENT) 4343 break; 4344 if (i >= env->prog->len) { 4345 /* This can happen if backtracking reached insn 0 4346 * and there are still reg_mask or stack_mask 4347 * to backtrack. 4348 * It means the backtracking missed the spot where 4349 * particular register was initialized with a constant. 4350 */ 4351 verbose(env, "BUG backtracking idx %d\n", i); 4352 WARN_ONCE(1, "verifier backtracking bug"); 4353 return -EFAULT; 4354 } 4355 } 4356 st = st->parent; 4357 if (!st) 4358 break; 4359 4360 for (fr = bt->frame; fr >= 0; fr--) { 4361 func = st->frame[fr]; 4362 bitmap_from_u64(mask, bt_frame_reg_mask(bt, fr)); 4363 for_each_set_bit(i, mask, 32) { 4364 reg = &func->regs[i]; 4365 if (reg->type != SCALAR_VALUE) { 4366 bt_clear_frame_reg(bt, fr, i); 4367 continue; 4368 } 4369 if (reg->precise) 4370 bt_clear_frame_reg(bt, fr, i); 4371 else 4372 reg->precise = true; 4373 } 4374 4375 bitmap_from_u64(mask, bt_frame_stack_mask(bt, fr)); 4376 for_each_set_bit(i, mask, 64) { 4377 if (i >= func->allocated_stack / BPF_REG_SIZE) { 4378 /* the sequence of instructions: 4379 * 2: (bf) r3 = r10 4380 * 3: (7b) *(u64 *)(r3 -8) = r0 4381 * 4: (79) r4 = *(u64 *)(r10 -8) 4382 * doesn't contain jmps. It's backtracked 4383 * as a single block. 4384 * During backtracking insn 3 is not recognized as 4385 * stack access, so at the end of backtracking 4386 * stack slot fp-8 is still marked in stack_mask. 4387 * However the parent state may not have accessed 4388 * fp-8 and it's "unallocated" stack space. 4389 * In such case fallback to conservative. 4390 */ 4391 mark_all_scalars_precise(env, env->cur_state); 4392 bt_reset(bt); 4393 return 0; 4394 } 4395 4396 if (!is_spilled_scalar_reg(&func->stack[i])) { 4397 bt_clear_frame_slot(bt, fr, i); 4398 continue; 4399 } 4400 reg = &func->stack[i].spilled_ptr; 4401 if (reg->precise) 4402 bt_clear_frame_slot(bt, fr, i); 4403 else 4404 reg->precise = true; 4405 } 4406 if (env->log.level & BPF_LOG_LEVEL2) { 4407 fmt_reg_mask(env->tmp_str_buf, TMP_STR_BUF_LEN, 4408 bt_frame_reg_mask(bt, fr)); 4409 verbose(env, "mark_precise: frame%d: parent state regs=%s ", 4410 fr, env->tmp_str_buf); 4411 fmt_stack_mask(env->tmp_str_buf, TMP_STR_BUF_LEN, 4412 bt_frame_stack_mask(bt, fr)); 4413 verbose(env, "stack=%s: ", env->tmp_str_buf); 4414 print_verifier_state(env, func, true); 4415 } 4416 } 4417 4418 if (bt_empty(bt)) 4419 return 0; 4420 4421 subseq_idx = first_idx; 4422 last_idx = st->last_insn_idx; 4423 first_idx = st->first_insn_idx; 4424 } 4425 4426 /* if we still have requested precise regs or slots, we missed 4427 * something (e.g., stack access through non-r10 register), so 4428 * fallback to marking all precise 4429 */ 4430 if (!bt_empty(bt)) { 4431 mark_all_scalars_precise(env, env->cur_state); 4432 bt_reset(bt); 4433 } 4434 4435 return 0; 4436 } 4437 4438 int mark_chain_precision(struct bpf_verifier_env *env, int regno) 4439 { 4440 return __mark_chain_precision(env, regno); 4441 } 4442 4443 /* mark_chain_precision_batch() assumes that env->bt is set in the caller to 4444 * desired reg and stack masks across all relevant frames 4445 */ 4446 static int mark_chain_precision_batch(struct bpf_verifier_env *env) 4447 { 4448 return __mark_chain_precision(env, -1); 4449 } 4450 4451 static bool is_spillable_regtype(enum bpf_reg_type type) 4452 { 4453 switch (base_type(type)) { 4454 case PTR_TO_MAP_VALUE: 4455 case PTR_TO_STACK: 4456 case PTR_TO_CTX: 4457 case PTR_TO_PACKET: 4458 case PTR_TO_PACKET_META: 4459 case PTR_TO_PACKET_END: 4460 case PTR_TO_FLOW_KEYS: 4461 case CONST_PTR_TO_MAP: 4462 case PTR_TO_SOCKET: 4463 case PTR_TO_SOCK_COMMON: 4464 case PTR_TO_TCP_SOCK: 4465 case PTR_TO_XDP_SOCK: 4466 case PTR_TO_BTF_ID: 4467 case PTR_TO_BUF: 4468 case PTR_TO_MEM: 4469 case PTR_TO_FUNC: 4470 case PTR_TO_MAP_KEY: 4471 return true; 4472 default: 4473 return false; 4474 } 4475 } 4476 4477 /* Does this register contain a constant zero? */ 4478 static bool register_is_null(struct bpf_reg_state *reg) 4479 { 4480 return reg->type == SCALAR_VALUE && tnum_equals_const(reg->var_off, 0); 4481 } 4482 4483 static bool register_is_const(struct bpf_reg_state *reg) 4484 { 4485 return reg->type == SCALAR_VALUE && tnum_is_const(reg->var_off); 4486 } 4487 4488 static bool __is_scalar_unbounded(struct bpf_reg_state *reg) 4489 { 4490 return tnum_is_unknown(reg->var_off) && 4491 reg->smin_value == S64_MIN && reg->smax_value == S64_MAX && 4492 reg->umin_value == 0 && reg->umax_value == U64_MAX && 4493 reg->s32_min_value == S32_MIN && reg->s32_max_value == S32_MAX && 4494 reg->u32_min_value == 0 && reg->u32_max_value == U32_MAX; 4495 } 4496 4497 static bool register_is_bounded(struct bpf_reg_state *reg) 4498 { 4499 return reg->type == SCALAR_VALUE && !__is_scalar_unbounded(reg); 4500 } 4501 4502 static bool __is_pointer_value(bool allow_ptr_leaks, 4503 const struct bpf_reg_state *reg) 4504 { 4505 if (allow_ptr_leaks) 4506 return false; 4507 4508 return reg->type != SCALAR_VALUE; 4509 } 4510 4511 /* Copy src state preserving dst->parent and dst->live fields */ 4512 static void copy_register_state(struct bpf_reg_state *dst, const struct bpf_reg_state *src) 4513 { 4514 struct bpf_reg_state *parent = dst->parent; 4515 enum bpf_reg_liveness live = dst->live; 4516 4517 *dst = *src; 4518 dst->parent = parent; 4519 dst->live = live; 4520 } 4521 4522 static void save_register_state(struct bpf_func_state *state, 4523 int spi, struct bpf_reg_state *reg, 4524 int size) 4525 { 4526 int i; 4527 4528 copy_register_state(&state->stack[spi].spilled_ptr, reg); 4529 if (size == BPF_REG_SIZE) 4530 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN; 4531 4532 for (i = BPF_REG_SIZE; i > BPF_REG_SIZE - size; i--) 4533 state->stack[spi].slot_type[i - 1] = STACK_SPILL; 4534 4535 /* size < 8 bytes spill */ 4536 for (; i; i--) 4537 scrub_spilled_slot(&state->stack[spi].slot_type[i - 1]); 4538 } 4539 4540 static bool is_bpf_st_mem(struct bpf_insn *insn) 4541 { 4542 return BPF_CLASS(insn->code) == BPF_ST && BPF_MODE(insn->code) == BPF_MEM; 4543 } 4544 4545 /* check_stack_{read,write}_fixed_off functions track spill/fill of registers, 4546 * stack boundary and alignment are checked in check_mem_access() 4547 */ 4548 static int check_stack_write_fixed_off(struct bpf_verifier_env *env, 4549 /* stack frame we're writing to */ 4550 struct bpf_func_state *state, 4551 int off, int size, int value_regno, 4552 int insn_idx) 4553 { 4554 struct bpf_func_state *cur; /* state of the current function */ 4555 int i, slot = -off - 1, spi = slot / BPF_REG_SIZE, err; 4556 struct bpf_insn *insn = &env->prog->insnsi[insn_idx]; 4557 struct bpf_reg_state *reg = NULL; 4558 u32 dst_reg = insn->dst_reg; 4559 4560 /* caller checked that off % size == 0 and -MAX_BPF_STACK <= off < 0, 4561 * so it's aligned access and [off, off + size) are within stack limits 4562 */ 4563 if (!env->allow_ptr_leaks && 4564 is_spilled_reg(&state->stack[spi]) && 4565 size != BPF_REG_SIZE) { 4566 verbose(env, "attempt to corrupt spilled pointer on stack\n"); 4567 return -EACCES; 4568 } 4569 4570 cur = env->cur_state->frame[env->cur_state->curframe]; 4571 if (value_regno >= 0) 4572 reg = &cur->regs[value_regno]; 4573 if (!env->bypass_spec_v4) { 4574 bool sanitize = reg && is_spillable_regtype(reg->type); 4575 4576 for (i = 0; i < size; i++) { 4577 u8 type = state->stack[spi].slot_type[i]; 4578 4579 if (type != STACK_MISC && type != STACK_ZERO) { 4580 sanitize = true; 4581 break; 4582 } 4583 } 4584 4585 if (sanitize) 4586 env->insn_aux_data[insn_idx].sanitize_stack_spill = true; 4587 } 4588 4589 err = destroy_if_dynptr_stack_slot(env, state, spi); 4590 if (err) 4591 return err; 4592 4593 mark_stack_slot_scratched(env, spi); 4594 if (reg && !(off % BPF_REG_SIZE) && register_is_bounded(reg) && 4595 !register_is_null(reg) && env->bpf_capable) { 4596 if (dst_reg != BPF_REG_FP) { 4597 /* The backtracking logic can only recognize explicit 4598 * stack slot address like [fp - 8]. Other spill of 4599 * scalar via different register has to be conservative. 4600 * Backtrack from here and mark all registers as precise 4601 * that contributed into 'reg' being a constant. 4602 */ 4603 err = mark_chain_precision(env, value_regno); 4604 if (err) 4605 return err; 4606 } 4607 save_register_state(state, spi, reg, size); 4608 /* Break the relation on a narrowing spill. */ 4609 if (fls64(reg->umax_value) > BITS_PER_BYTE * size) 4610 state->stack[spi].spilled_ptr.id = 0; 4611 } else if (!reg && !(off % BPF_REG_SIZE) && is_bpf_st_mem(insn) && 4612 insn->imm != 0 && env->bpf_capable) { 4613 struct bpf_reg_state fake_reg = {}; 4614 4615 __mark_reg_known(&fake_reg, insn->imm); 4616 fake_reg.type = SCALAR_VALUE; 4617 save_register_state(state, spi, &fake_reg, size); 4618 } else if (reg && is_spillable_regtype(reg->type)) { 4619 /* register containing pointer is being spilled into stack */ 4620 if (size != BPF_REG_SIZE) { 4621 verbose_linfo(env, insn_idx, "; "); 4622 verbose(env, "invalid size of register spill\n"); 4623 return -EACCES; 4624 } 4625 if (state != cur && reg->type == PTR_TO_STACK) { 4626 verbose(env, "cannot spill pointers to stack into stack frame of the caller\n"); 4627 return -EINVAL; 4628 } 4629 save_register_state(state, spi, reg, size); 4630 } else { 4631 u8 type = STACK_MISC; 4632 4633 /* regular write of data into stack destroys any spilled ptr */ 4634 state->stack[spi].spilled_ptr.type = NOT_INIT; 4635 /* Mark slots as STACK_MISC if they belonged to spilled ptr/dynptr/iter. */ 4636 if (is_stack_slot_special(&state->stack[spi])) 4637 for (i = 0; i < BPF_REG_SIZE; i++) 4638 scrub_spilled_slot(&state->stack[spi].slot_type[i]); 4639 4640 /* only mark the slot as written if all 8 bytes were written 4641 * otherwise read propagation may incorrectly stop too soon 4642 * when stack slots are partially written. 4643 * This heuristic means that read propagation will be 4644 * conservative, since it will add reg_live_read marks 4645 * to stack slots all the way to first state when programs 4646 * writes+reads less than 8 bytes 4647 */ 4648 if (size == BPF_REG_SIZE) 4649 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN; 4650 4651 /* when we zero initialize stack slots mark them as such */ 4652 if ((reg && register_is_null(reg)) || 4653 (!reg && is_bpf_st_mem(insn) && insn->imm == 0)) { 4654 /* backtracking doesn't work for STACK_ZERO yet. */ 4655 err = mark_chain_precision(env, value_regno); 4656 if (err) 4657 return err; 4658 type = STACK_ZERO; 4659 } 4660 4661 /* Mark slots affected by this stack write. */ 4662 for (i = 0; i < size; i++) 4663 state->stack[spi].slot_type[(slot - i) % BPF_REG_SIZE] = 4664 type; 4665 } 4666 return 0; 4667 } 4668 4669 /* Write the stack: 'stack[ptr_regno + off] = value_regno'. 'ptr_regno' is 4670 * known to contain a variable offset. 4671 * This function checks whether the write is permitted and conservatively 4672 * tracks the effects of the write, considering that each stack slot in the 4673 * dynamic range is potentially written to. 4674 * 4675 * 'off' includes 'regno->off'. 4676 * 'value_regno' can be -1, meaning that an unknown value is being written to 4677 * the stack. 4678 * 4679 * Spilled pointers in range are not marked as written because we don't know 4680 * what's going to be actually written. This means that read propagation for 4681 * future reads cannot be terminated by this write. 4682 * 4683 * For privileged programs, uninitialized stack slots are considered 4684 * initialized by this write (even though we don't know exactly what offsets 4685 * are going to be written to). The idea is that we don't want the verifier to 4686 * reject future reads that access slots written to through variable offsets. 4687 */ 4688 static int check_stack_write_var_off(struct bpf_verifier_env *env, 4689 /* func where register points to */ 4690 struct bpf_func_state *state, 4691 int ptr_regno, int off, int size, 4692 int value_regno, int insn_idx) 4693 { 4694 struct bpf_func_state *cur; /* state of the current function */ 4695 int min_off, max_off; 4696 int i, err; 4697 struct bpf_reg_state *ptr_reg = NULL, *value_reg = NULL; 4698 struct bpf_insn *insn = &env->prog->insnsi[insn_idx]; 4699 bool writing_zero = false; 4700 /* set if the fact that we're writing a zero is used to let any 4701 * stack slots remain STACK_ZERO 4702 */ 4703 bool zero_used = false; 4704 4705 cur = env->cur_state->frame[env->cur_state->curframe]; 4706 ptr_reg = &cur->regs[ptr_regno]; 4707 min_off = ptr_reg->smin_value + off; 4708 max_off = ptr_reg->smax_value + off + size; 4709 if (value_regno >= 0) 4710 value_reg = &cur->regs[value_regno]; 4711 if ((value_reg && register_is_null(value_reg)) || 4712 (!value_reg && is_bpf_st_mem(insn) && insn->imm == 0)) 4713 writing_zero = true; 4714 4715 for (i = min_off; i < max_off; i++) { 4716 int spi; 4717 4718 spi = __get_spi(i); 4719 err = destroy_if_dynptr_stack_slot(env, state, spi); 4720 if (err) 4721 return err; 4722 } 4723 4724 /* Variable offset writes destroy any spilled pointers in range. */ 4725 for (i = min_off; i < max_off; i++) { 4726 u8 new_type, *stype; 4727 int slot, spi; 4728 4729 slot = -i - 1; 4730 spi = slot / BPF_REG_SIZE; 4731 stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE]; 4732 mark_stack_slot_scratched(env, spi); 4733 4734 if (!env->allow_ptr_leaks && *stype != STACK_MISC && *stype != STACK_ZERO) { 4735 /* Reject the write if range we may write to has not 4736 * been initialized beforehand. If we didn't reject 4737 * here, the ptr status would be erased below (even 4738 * though not all slots are actually overwritten), 4739 * possibly opening the door to leaks. 4740 * 4741 * We do however catch STACK_INVALID case below, and 4742 * only allow reading possibly uninitialized memory 4743 * later for CAP_PERFMON, as the write may not happen to 4744 * that slot. 4745 */ 4746 verbose(env, "spilled ptr in range of var-offset stack write; insn %d, ptr off: %d", 4747 insn_idx, i); 4748 return -EINVAL; 4749 } 4750 4751 /* Erase all spilled pointers. */ 4752 state->stack[spi].spilled_ptr.type = NOT_INIT; 4753 4754 /* Update the slot type. */ 4755 new_type = STACK_MISC; 4756 if (writing_zero && *stype == STACK_ZERO) { 4757 new_type = STACK_ZERO; 4758 zero_used = true; 4759 } 4760 /* If the slot is STACK_INVALID, we check whether it's OK to 4761 * pretend that it will be initialized by this write. The slot 4762 * might not actually be written to, and so if we mark it as 4763 * initialized future reads might leak uninitialized memory. 4764 * For privileged programs, we will accept such reads to slots 4765 * that may or may not be written because, if we're reject 4766 * them, the error would be too confusing. 4767 */ 4768 if (*stype == STACK_INVALID && !env->allow_uninit_stack) { 4769 verbose(env, "uninit stack in range of var-offset write prohibited for !root; insn %d, off: %d", 4770 insn_idx, i); 4771 return -EINVAL; 4772 } 4773 *stype = new_type; 4774 } 4775 if (zero_used) { 4776 /* backtracking doesn't work for STACK_ZERO yet. */ 4777 err = mark_chain_precision(env, value_regno); 4778 if (err) 4779 return err; 4780 } 4781 return 0; 4782 } 4783 4784 /* When register 'dst_regno' is assigned some values from stack[min_off, 4785 * max_off), we set the register's type according to the types of the 4786 * respective stack slots. If all the stack values are known to be zeros, then 4787 * so is the destination reg. Otherwise, the register is considered to be 4788 * SCALAR. This function does not deal with register filling; the caller must 4789 * ensure that all spilled registers in the stack range have been marked as 4790 * read. 4791 */ 4792 static void mark_reg_stack_read(struct bpf_verifier_env *env, 4793 /* func where src register points to */ 4794 struct bpf_func_state *ptr_state, 4795 int min_off, int max_off, int dst_regno) 4796 { 4797 struct bpf_verifier_state *vstate = env->cur_state; 4798 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 4799 int i, slot, spi; 4800 u8 *stype; 4801 int zeros = 0; 4802 4803 for (i = min_off; i < max_off; i++) { 4804 slot = -i - 1; 4805 spi = slot / BPF_REG_SIZE; 4806 mark_stack_slot_scratched(env, spi); 4807 stype = ptr_state->stack[spi].slot_type; 4808 if (stype[slot % BPF_REG_SIZE] != STACK_ZERO) 4809 break; 4810 zeros++; 4811 } 4812 if (zeros == max_off - min_off) { 4813 /* any access_size read into register is zero extended, 4814 * so the whole register == const_zero 4815 */ 4816 __mark_reg_const_zero(&state->regs[dst_regno]); 4817 /* backtracking doesn't support STACK_ZERO yet, 4818 * so mark it precise here, so that later 4819 * backtracking can stop here. 4820 * Backtracking may not need this if this register 4821 * doesn't participate in pointer adjustment. 4822 * Forward propagation of precise flag is not 4823 * necessary either. This mark is only to stop 4824 * backtracking. Any register that contributed 4825 * to const 0 was marked precise before spill. 4826 */ 4827 state->regs[dst_regno].precise = true; 4828 } else { 4829 /* have read misc data from the stack */ 4830 mark_reg_unknown(env, state->regs, dst_regno); 4831 } 4832 state->regs[dst_regno].live |= REG_LIVE_WRITTEN; 4833 } 4834 4835 /* Read the stack at 'off' and put the results into the register indicated by 4836 * 'dst_regno'. It handles reg filling if the addressed stack slot is a 4837 * spilled reg. 4838 * 4839 * 'dst_regno' can be -1, meaning that the read value is not going to a 4840 * register. 4841 * 4842 * The access is assumed to be within the current stack bounds. 4843 */ 4844 static int check_stack_read_fixed_off(struct bpf_verifier_env *env, 4845 /* func where src register points to */ 4846 struct bpf_func_state *reg_state, 4847 int off, int size, int dst_regno) 4848 { 4849 struct bpf_verifier_state *vstate = env->cur_state; 4850 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 4851 int i, slot = -off - 1, spi = slot / BPF_REG_SIZE; 4852 struct bpf_reg_state *reg; 4853 u8 *stype, type; 4854 4855 stype = reg_state->stack[spi].slot_type; 4856 reg = ®_state->stack[spi].spilled_ptr; 4857 4858 mark_stack_slot_scratched(env, spi); 4859 4860 if (is_spilled_reg(®_state->stack[spi])) { 4861 u8 spill_size = 1; 4862 4863 for (i = BPF_REG_SIZE - 1; i > 0 && stype[i - 1] == STACK_SPILL; i--) 4864 spill_size++; 4865 4866 if (size != BPF_REG_SIZE || spill_size != BPF_REG_SIZE) { 4867 if (reg->type != SCALAR_VALUE) { 4868 verbose_linfo(env, env->insn_idx, "; "); 4869 verbose(env, "invalid size of register fill\n"); 4870 return -EACCES; 4871 } 4872 4873 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64); 4874 if (dst_regno < 0) 4875 return 0; 4876 4877 if (!(off % BPF_REG_SIZE) && size == spill_size) { 4878 /* The earlier check_reg_arg() has decided the 4879 * subreg_def for this insn. Save it first. 4880 */ 4881 s32 subreg_def = state->regs[dst_regno].subreg_def; 4882 4883 copy_register_state(&state->regs[dst_regno], reg); 4884 state->regs[dst_regno].subreg_def = subreg_def; 4885 } else { 4886 for (i = 0; i < size; i++) { 4887 type = stype[(slot - i) % BPF_REG_SIZE]; 4888 if (type == STACK_SPILL) 4889 continue; 4890 if (type == STACK_MISC) 4891 continue; 4892 if (type == STACK_INVALID && env->allow_uninit_stack) 4893 continue; 4894 verbose(env, "invalid read from stack off %d+%d size %d\n", 4895 off, i, size); 4896 return -EACCES; 4897 } 4898 mark_reg_unknown(env, state->regs, dst_regno); 4899 } 4900 state->regs[dst_regno].live |= REG_LIVE_WRITTEN; 4901 return 0; 4902 } 4903 4904 if (dst_regno >= 0) { 4905 /* restore register state from stack */ 4906 copy_register_state(&state->regs[dst_regno], reg); 4907 /* mark reg as written since spilled pointer state likely 4908 * has its liveness marks cleared by is_state_visited() 4909 * which resets stack/reg liveness for state transitions 4910 */ 4911 state->regs[dst_regno].live |= REG_LIVE_WRITTEN; 4912 } else if (__is_pointer_value(env->allow_ptr_leaks, reg)) { 4913 /* If dst_regno==-1, the caller is asking us whether 4914 * it is acceptable to use this value as a SCALAR_VALUE 4915 * (e.g. for XADD). 4916 * We must not allow unprivileged callers to do that 4917 * with spilled pointers. 4918 */ 4919 verbose(env, "leaking pointer from stack off %d\n", 4920 off); 4921 return -EACCES; 4922 } 4923 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64); 4924 } else { 4925 for (i = 0; i < size; i++) { 4926 type = stype[(slot - i) % BPF_REG_SIZE]; 4927 if (type == STACK_MISC) 4928 continue; 4929 if (type == STACK_ZERO) 4930 continue; 4931 if (type == STACK_INVALID && env->allow_uninit_stack) 4932 continue; 4933 verbose(env, "invalid read from stack off %d+%d size %d\n", 4934 off, i, size); 4935 return -EACCES; 4936 } 4937 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64); 4938 if (dst_regno >= 0) 4939 mark_reg_stack_read(env, reg_state, off, off + size, dst_regno); 4940 } 4941 return 0; 4942 } 4943 4944 enum bpf_access_src { 4945 ACCESS_DIRECT = 1, /* the access is performed by an instruction */ 4946 ACCESS_HELPER = 2, /* the access is performed by a helper */ 4947 }; 4948 4949 static int check_stack_range_initialized(struct bpf_verifier_env *env, 4950 int regno, int off, int access_size, 4951 bool zero_size_allowed, 4952 enum bpf_access_src type, 4953 struct bpf_call_arg_meta *meta); 4954 4955 static struct bpf_reg_state *reg_state(struct bpf_verifier_env *env, int regno) 4956 { 4957 return cur_regs(env) + regno; 4958 } 4959 4960 /* Read the stack at 'ptr_regno + off' and put the result into the register 4961 * 'dst_regno'. 4962 * 'off' includes the pointer register's fixed offset(i.e. 'ptr_regno.off'), 4963 * but not its variable offset. 4964 * 'size' is assumed to be <= reg size and the access is assumed to be aligned. 4965 * 4966 * As opposed to check_stack_read_fixed_off, this function doesn't deal with 4967 * filling registers (i.e. reads of spilled register cannot be detected when 4968 * the offset is not fixed). We conservatively mark 'dst_regno' as containing 4969 * SCALAR_VALUE. That's why we assert that the 'ptr_regno' has a variable 4970 * offset; for a fixed offset check_stack_read_fixed_off should be used 4971 * instead. 4972 */ 4973 static int check_stack_read_var_off(struct bpf_verifier_env *env, 4974 int ptr_regno, int off, int size, int dst_regno) 4975 { 4976 /* The state of the source register. */ 4977 struct bpf_reg_state *reg = reg_state(env, ptr_regno); 4978 struct bpf_func_state *ptr_state = func(env, reg); 4979 int err; 4980 int min_off, max_off; 4981 4982 /* Note that we pass a NULL meta, so raw access will not be permitted. 4983 */ 4984 err = check_stack_range_initialized(env, ptr_regno, off, size, 4985 false, ACCESS_DIRECT, NULL); 4986 if (err) 4987 return err; 4988 4989 min_off = reg->smin_value + off; 4990 max_off = reg->smax_value + off; 4991 mark_reg_stack_read(env, ptr_state, min_off, max_off + size, dst_regno); 4992 return 0; 4993 } 4994 4995 /* check_stack_read dispatches to check_stack_read_fixed_off or 4996 * check_stack_read_var_off. 4997 * 4998 * The caller must ensure that the offset falls within the allocated stack 4999 * bounds. 5000 * 5001 * 'dst_regno' is a register which will receive the value from the stack. It 5002 * can be -1, meaning that the read value is not going to a register. 5003 */ 5004 static int check_stack_read(struct bpf_verifier_env *env, 5005 int ptr_regno, int off, int size, 5006 int dst_regno) 5007 { 5008 struct bpf_reg_state *reg = reg_state(env, ptr_regno); 5009 struct bpf_func_state *state = func(env, reg); 5010 int err; 5011 /* Some accesses are only permitted with a static offset. */ 5012 bool var_off = !tnum_is_const(reg->var_off); 5013 5014 /* The offset is required to be static when reads don't go to a 5015 * register, in order to not leak pointers (see 5016 * check_stack_read_fixed_off). 5017 */ 5018 if (dst_regno < 0 && var_off) { 5019 char tn_buf[48]; 5020 5021 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 5022 verbose(env, "variable offset stack pointer cannot be passed into helper function; var_off=%s off=%d size=%d\n", 5023 tn_buf, off, size); 5024 return -EACCES; 5025 } 5026 /* Variable offset is prohibited for unprivileged mode for simplicity 5027 * since it requires corresponding support in Spectre masking for stack 5028 * ALU. See also retrieve_ptr_limit(). The check in 5029 * check_stack_access_for_ptr_arithmetic() called by 5030 * adjust_ptr_min_max_vals() prevents users from creating stack pointers 5031 * with variable offsets, therefore no check is required here. Further, 5032 * just checking it here would be insufficient as speculative stack 5033 * writes could still lead to unsafe speculative behaviour. 5034 */ 5035 if (!var_off) { 5036 off += reg->var_off.value; 5037 err = check_stack_read_fixed_off(env, state, off, size, 5038 dst_regno); 5039 } else { 5040 /* Variable offset stack reads need more conservative handling 5041 * than fixed offset ones. Note that dst_regno >= 0 on this 5042 * branch. 5043 */ 5044 err = check_stack_read_var_off(env, ptr_regno, off, size, 5045 dst_regno); 5046 } 5047 return err; 5048 } 5049 5050 5051 /* check_stack_write dispatches to check_stack_write_fixed_off or 5052 * check_stack_write_var_off. 5053 * 5054 * 'ptr_regno' is the register used as a pointer into the stack. 5055 * 'off' includes 'ptr_regno->off', but not its variable offset (if any). 5056 * 'value_regno' is the register whose value we're writing to the stack. It can 5057 * be -1, meaning that we're not writing from a register. 5058 * 5059 * The caller must ensure that the offset falls within the maximum stack size. 5060 */ 5061 static int check_stack_write(struct bpf_verifier_env *env, 5062 int ptr_regno, int off, int size, 5063 int value_regno, int insn_idx) 5064 { 5065 struct bpf_reg_state *reg = reg_state(env, ptr_regno); 5066 struct bpf_func_state *state = func(env, reg); 5067 int err; 5068 5069 if (tnum_is_const(reg->var_off)) { 5070 off += reg->var_off.value; 5071 err = check_stack_write_fixed_off(env, state, off, size, 5072 value_regno, insn_idx); 5073 } else { 5074 /* Variable offset stack reads need more conservative handling 5075 * than fixed offset ones. 5076 */ 5077 err = check_stack_write_var_off(env, state, 5078 ptr_regno, off, size, 5079 value_regno, insn_idx); 5080 } 5081 return err; 5082 } 5083 5084 static int check_map_access_type(struct bpf_verifier_env *env, u32 regno, 5085 int off, int size, enum bpf_access_type type) 5086 { 5087 struct bpf_reg_state *regs = cur_regs(env); 5088 struct bpf_map *map = regs[regno].map_ptr; 5089 u32 cap = bpf_map_flags_to_cap(map); 5090 5091 if (type == BPF_WRITE && !(cap & BPF_MAP_CAN_WRITE)) { 5092 verbose(env, "write into map forbidden, value_size=%d off=%d size=%d\n", 5093 map->value_size, off, size); 5094 return -EACCES; 5095 } 5096 5097 if (type == BPF_READ && !(cap & BPF_MAP_CAN_READ)) { 5098 verbose(env, "read from map forbidden, value_size=%d off=%d size=%d\n", 5099 map->value_size, off, size); 5100 return -EACCES; 5101 } 5102 5103 return 0; 5104 } 5105 5106 /* check read/write into memory region (e.g., map value, ringbuf sample, etc) */ 5107 static int __check_mem_access(struct bpf_verifier_env *env, int regno, 5108 int off, int size, u32 mem_size, 5109 bool zero_size_allowed) 5110 { 5111 bool size_ok = size > 0 || (size == 0 && zero_size_allowed); 5112 struct bpf_reg_state *reg; 5113 5114 if (off >= 0 && size_ok && (u64)off + size <= mem_size) 5115 return 0; 5116 5117 reg = &cur_regs(env)[regno]; 5118 switch (reg->type) { 5119 case PTR_TO_MAP_KEY: 5120 verbose(env, "invalid access to map key, key_size=%d off=%d size=%d\n", 5121 mem_size, off, size); 5122 break; 5123 case PTR_TO_MAP_VALUE: 5124 verbose(env, "invalid access to map value, value_size=%d off=%d size=%d\n", 5125 mem_size, off, size); 5126 break; 5127 case PTR_TO_PACKET: 5128 case PTR_TO_PACKET_META: 5129 case PTR_TO_PACKET_END: 5130 verbose(env, "invalid access to packet, off=%d size=%d, R%d(id=%d,off=%d,r=%d)\n", 5131 off, size, regno, reg->id, off, mem_size); 5132 break; 5133 case PTR_TO_MEM: 5134 default: 5135 verbose(env, "invalid access to memory, mem_size=%u off=%d size=%d\n", 5136 mem_size, off, size); 5137 } 5138 5139 return -EACCES; 5140 } 5141 5142 /* check read/write into a memory region with possible variable offset */ 5143 static int check_mem_region_access(struct bpf_verifier_env *env, u32 regno, 5144 int off, int size, u32 mem_size, 5145 bool zero_size_allowed) 5146 { 5147 struct bpf_verifier_state *vstate = env->cur_state; 5148 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 5149 struct bpf_reg_state *reg = &state->regs[regno]; 5150 int err; 5151 5152 /* We may have adjusted the register pointing to memory region, so we 5153 * need to try adding each of min_value and max_value to off 5154 * to make sure our theoretical access will be safe. 5155 * 5156 * The minimum value is only important with signed 5157 * comparisons where we can't assume the floor of a 5158 * value is 0. If we are using signed variables for our 5159 * index'es we need to make sure that whatever we use 5160 * will have a set floor within our range. 5161 */ 5162 if (reg->smin_value < 0 && 5163 (reg->smin_value == S64_MIN || 5164 (off + reg->smin_value != (s64)(s32)(off + reg->smin_value)) || 5165 reg->smin_value + off < 0)) { 5166 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n", 5167 regno); 5168 return -EACCES; 5169 } 5170 err = __check_mem_access(env, regno, reg->smin_value + off, size, 5171 mem_size, zero_size_allowed); 5172 if (err) { 5173 verbose(env, "R%d min value is outside of the allowed memory range\n", 5174 regno); 5175 return err; 5176 } 5177 5178 /* If we haven't set a max value then we need to bail since we can't be 5179 * sure we won't do bad things. 5180 * If reg->umax_value + off could overflow, treat that as unbounded too. 5181 */ 5182 if (reg->umax_value >= BPF_MAX_VAR_OFF) { 5183 verbose(env, "R%d unbounded memory access, make sure to bounds check any such access\n", 5184 regno); 5185 return -EACCES; 5186 } 5187 err = __check_mem_access(env, regno, reg->umax_value + off, size, 5188 mem_size, zero_size_allowed); 5189 if (err) { 5190 verbose(env, "R%d max value is outside of the allowed memory range\n", 5191 regno); 5192 return err; 5193 } 5194 5195 return 0; 5196 } 5197 5198 static int __check_ptr_off_reg(struct bpf_verifier_env *env, 5199 const struct bpf_reg_state *reg, int regno, 5200 bool fixed_off_ok) 5201 { 5202 /* Access to this pointer-typed register or passing it to a helper 5203 * is only allowed in its original, unmodified form. 5204 */ 5205 5206 if (reg->off < 0) { 5207 verbose(env, "negative offset %s ptr R%d off=%d disallowed\n", 5208 reg_type_str(env, reg->type), regno, reg->off); 5209 return -EACCES; 5210 } 5211 5212 if (!fixed_off_ok && reg->off) { 5213 verbose(env, "dereference of modified %s ptr R%d off=%d disallowed\n", 5214 reg_type_str(env, reg->type), regno, reg->off); 5215 return -EACCES; 5216 } 5217 5218 if (!tnum_is_const(reg->var_off) || reg->var_off.value) { 5219 char tn_buf[48]; 5220 5221 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 5222 verbose(env, "variable %s access var_off=%s disallowed\n", 5223 reg_type_str(env, reg->type), tn_buf); 5224 return -EACCES; 5225 } 5226 5227 return 0; 5228 } 5229 5230 int check_ptr_off_reg(struct bpf_verifier_env *env, 5231 const struct bpf_reg_state *reg, int regno) 5232 { 5233 return __check_ptr_off_reg(env, reg, regno, false); 5234 } 5235 5236 static int map_kptr_match_type(struct bpf_verifier_env *env, 5237 struct btf_field *kptr_field, 5238 struct bpf_reg_state *reg, u32 regno) 5239 { 5240 const char *targ_name = btf_type_name(kptr_field->kptr.btf, kptr_field->kptr.btf_id); 5241 int perm_flags; 5242 const char *reg_name = ""; 5243 5244 if (btf_is_kernel(reg->btf)) { 5245 perm_flags = PTR_MAYBE_NULL | PTR_TRUSTED | MEM_RCU; 5246 5247 /* Only unreferenced case accepts untrusted pointers */ 5248 if (kptr_field->type == BPF_KPTR_UNREF) 5249 perm_flags |= PTR_UNTRUSTED; 5250 } else { 5251 perm_flags = PTR_MAYBE_NULL | MEM_ALLOC; 5252 } 5253 5254 if (base_type(reg->type) != PTR_TO_BTF_ID || (type_flag(reg->type) & ~perm_flags)) 5255 goto bad_type; 5256 5257 /* We need to verify reg->type and reg->btf, before accessing reg->btf */ 5258 reg_name = btf_type_name(reg->btf, reg->btf_id); 5259 5260 /* For ref_ptr case, release function check should ensure we get one 5261 * referenced PTR_TO_BTF_ID, and that its fixed offset is 0. For the 5262 * normal store of unreferenced kptr, we must ensure var_off is zero. 5263 * Since ref_ptr cannot be accessed directly by BPF insns, checks for 5264 * reg->off and reg->ref_obj_id are not needed here. 5265 */ 5266 if (__check_ptr_off_reg(env, reg, regno, true)) 5267 return -EACCES; 5268 5269 /* A full type match is needed, as BTF can be vmlinux, module or prog BTF, and 5270 * we also need to take into account the reg->off. 5271 * 5272 * We want to support cases like: 5273 * 5274 * struct foo { 5275 * struct bar br; 5276 * struct baz bz; 5277 * }; 5278 * 5279 * struct foo *v; 5280 * v = func(); // PTR_TO_BTF_ID 5281 * val->foo = v; // reg->off is zero, btf and btf_id match type 5282 * val->bar = &v->br; // reg->off is still zero, but we need to retry with 5283 * // first member type of struct after comparison fails 5284 * val->baz = &v->bz; // reg->off is non-zero, so struct needs to be walked 5285 * // to match type 5286 * 5287 * In the kptr_ref case, check_func_arg_reg_off already ensures reg->off 5288 * is zero. We must also ensure that btf_struct_ids_match does not walk 5289 * the struct to match type against first member of struct, i.e. reject 5290 * second case from above. Hence, when type is BPF_KPTR_REF, we set 5291 * strict mode to true for type match. 5292 */ 5293 if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off, 5294 kptr_field->kptr.btf, kptr_field->kptr.btf_id, 5295 kptr_field->type == BPF_KPTR_REF)) 5296 goto bad_type; 5297 return 0; 5298 bad_type: 5299 verbose(env, "invalid kptr access, R%d type=%s%s ", regno, 5300 reg_type_str(env, reg->type), reg_name); 5301 verbose(env, "expected=%s%s", reg_type_str(env, PTR_TO_BTF_ID), targ_name); 5302 if (kptr_field->type == BPF_KPTR_UNREF) 5303 verbose(env, " or %s%s\n", reg_type_str(env, PTR_TO_BTF_ID | PTR_UNTRUSTED), 5304 targ_name); 5305 else 5306 verbose(env, "\n"); 5307 return -EINVAL; 5308 } 5309 5310 /* The non-sleepable programs and sleepable programs with explicit bpf_rcu_read_lock() 5311 * can dereference RCU protected pointers and result is PTR_TRUSTED. 5312 */ 5313 static bool in_rcu_cs(struct bpf_verifier_env *env) 5314 { 5315 return env->cur_state->active_rcu_lock || 5316 env->cur_state->active_lock.ptr || 5317 !env->prog->aux->sleepable; 5318 } 5319 5320 /* Once GCC supports btf_type_tag the following mechanism will be replaced with tag check */ 5321 BTF_SET_START(rcu_protected_types) 5322 BTF_ID(struct, prog_test_ref_kfunc) 5323 BTF_ID(struct, cgroup) 5324 BTF_ID(struct, bpf_cpumask) 5325 BTF_ID(struct, task_struct) 5326 BTF_SET_END(rcu_protected_types) 5327 5328 static bool rcu_protected_object(const struct btf *btf, u32 btf_id) 5329 { 5330 if (!btf_is_kernel(btf)) 5331 return false; 5332 return btf_id_set_contains(&rcu_protected_types, btf_id); 5333 } 5334 5335 static bool rcu_safe_kptr(const struct btf_field *field) 5336 { 5337 const struct btf_field_kptr *kptr = &field->kptr; 5338 5339 return field->type == BPF_KPTR_REF && rcu_protected_object(kptr->btf, kptr->btf_id); 5340 } 5341 5342 static int check_map_kptr_access(struct bpf_verifier_env *env, u32 regno, 5343 int value_regno, int insn_idx, 5344 struct btf_field *kptr_field) 5345 { 5346 struct bpf_insn *insn = &env->prog->insnsi[insn_idx]; 5347 int class = BPF_CLASS(insn->code); 5348 struct bpf_reg_state *val_reg; 5349 5350 /* Things we already checked for in check_map_access and caller: 5351 * - Reject cases where variable offset may touch kptr 5352 * - size of access (must be BPF_DW) 5353 * - tnum_is_const(reg->var_off) 5354 * - kptr_field->offset == off + reg->var_off.value 5355 */ 5356 /* Only BPF_[LDX,STX,ST] | BPF_MEM | BPF_DW is supported */ 5357 if (BPF_MODE(insn->code) != BPF_MEM) { 5358 verbose(env, "kptr in map can only be accessed using BPF_MEM instruction mode\n"); 5359 return -EACCES; 5360 } 5361 5362 /* We only allow loading referenced kptr, since it will be marked as 5363 * untrusted, similar to unreferenced kptr. 5364 */ 5365 if (class != BPF_LDX && kptr_field->type == BPF_KPTR_REF) { 5366 verbose(env, "store to referenced kptr disallowed\n"); 5367 return -EACCES; 5368 } 5369 5370 if (class == BPF_LDX) { 5371 val_reg = reg_state(env, value_regno); 5372 /* We can simply mark the value_regno receiving the pointer 5373 * value from map as PTR_TO_BTF_ID, with the correct type. 5374 */ 5375 mark_btf_ld_reg(env, cur_regs(env), value_regno, PTR_TO_BTF_ID, kptr_field->kptr.btf, 5376 kptr_field->kptr.btf_id, 5377 rcu_safe_kptr(kptr_field) && in_rcu_cs(env) ? 5378 PTR_MAYBE_NULL | MEM_RCU : 5379 PTR_MAYBE_NULL | PTR_UNTRUSTED); 5380 } else if (class == BPF_STX) { 5381 val_reg = reg_state(env, value_regno); 5382 if (!register_is_null(val_reg) && 5383 map_kptr_match_type(env, kptr_field, val_reg, value_regno)) 5384 return -EACCES; 5385 } else if (class == BPF_ST) { 5386 if (insn->imm) { 5387 verbose(env, "BPF_ST imm must be 0 when storing to kptr at off=%u\n", 5388 kptr_field->offset); 5389 return -EACCES; 5390 } 5391 } else { 5392 verbose(env, "kptr in map can only be accessed using BPF_LDX/BPF_STX/BPF_ST\n"); 5393 return -EACCES; 5394 } 5395 return 0; 5396 } 5397 5398 /* check read/write into a map element with possible variable offset */ 5399 static int check_map_access(struct bpf_verifier_env *env, u32 regno, 5400 int off, int size, bool zero_size_allowed, 5401 enum bpf_access_src src) 5402 { 5403 struct bpf_verifier_state *vstate = env->cur_state; 5404 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 5405 struct bpf_reg_state *reg = &state->regs[regno]; 5406 struct bpf_map *map = reg->map_ptr; 5407 struct btf_record *rec; 5408 int err, i; 5409 5410 err = check_mem_region_access(env, regno, off, size, map->value_size, 5411 zero_size_allowed); 5412 if (err) 5413 return err; 5414 5415 if (IS_ERR_OR_NULL(map->record)) 5416 return 0; 5417 rec = map->record; 5418 for (i = 0; i < rec->cnt; i++) { 5419 struct btf_field *field = &rec->fields[i]; 5420 u32 p = field->offset; 5421 5422 /* If any part of a field can be touched by load/store, reject 5423 * this program. To check that [x1, x2) overlaps with [y1, y2), 5424 * it is sufficient to check x1 < y2 && y1 < x2. 5425 */ 5426 if (reg->smin_value + off < p + btf_field_type_size(field->type) && 5427 p < reg->umax_value + off + size) { 5428 switch (field->type) { 5429 case BPF_KPTR_UNREF: 5430 case BPF_KPTR_REF: 5431 if (src != ACCESS_DIRECT) { 5432 verbose(env, "kptr cannot be accessed indirectly by helper\n"); 5433 return -EACCES; 5434 } 5435 if (!tnum_is_const(reg->var_off)) { 5436 verbose(env, "kptr access cannot have variable offset\n"); 5437 return -EACCES; 5438 } 5439 if (p != off + reg->var_off.value) { 5440 verbose(env, "kptr access misaligned expected=%u off=%llu\n", 5441 p, off + reg->var_off.value); 5442 return -EACCES; 5443 } 5444 if (size != bpf_size_to_bytes(BPF_DW)) { 5445 verbose(env, "kptr access size must be BPF_DW\n"); 5446 return -EACCES; 5447 } 5448 break; 5449 default: 5450 verbose(env, "%s cannot be accessed directly by load/store\n", 5451 btf_field_type_name(field->type)); 5452 return -EACCES; 5453 } 5454 } 5455 } 5456 return 0; 5457 } 5458 5459 #define MAX_PACKET_OFF 0xffff 5460 5461 static bool may_access_direct_pkt_data(struct bpf_verifier_env *env, 5462 const struct bpf_call_arg_meta *meta, 5463 enum bpf_access_type t) 5464 { 5465 enum bpf_prog_type prog_type = resolve_prog_type(env->prog); 5466 5467 switch (prog_type) { 5468 /* Program types only with direct read access go here! */ 5469 case BPF_PROG_TYPE_LWT_IN: 5470 case BPF_PROG_TYPE_LWT_OUT: 5471 case BPF_PROG_TYPE_LWT_SEG6LOCAL: 5472 case BPF_PROG_TYPE_SK_REUSEPORT: 5473 case BPF_PROG_TYPE_FLOW_DISSECTOR: 5474 case BPF_PROG_TYPE_CGROUP_SKB: 5475 if (t == BPF_WRITE) 5476 return false; 5477 fallthrough; 5478 5479 /* Program types with direct read + write access go here! */ 5480 case BPF_PROG_TYPE_SCHED_CLS: 5481 case BPF_PROG_TYPE_SCHED_ACT: 5482 case BPF_PROG_TYPE_XDP: 5483 case BPF_PROG_TYPE_LWT_XMIT: 5484 case BPF_PROG_TYPE_SK_SKB: 5485 case BPF_PROG_TYPE_SK_MSG: 5486 if (meta) 5487 return meta->pkt_access; 5488 5489 env->seen_direct_write = true; 5490 return true; 5491 5492 case BPF_PROG_TYPE_CGROUP_SOCKOPT: 5493 if (t == BPF_WRITE) 5494 env->seen_direct_write = true; 5495 5496 return true; 5497 5498 default: 5499 return false; 5500 } 5501 } 5502 5503 static int check_packet_access(struct bpf_verifier_env *env, u32 regno, int off, 5504 int size, bool zero_size_allowed) 5505 { 5506 struct bpf_reg_state *regs = cur_regs(env); 5507 struct bpf_reg_state *reg = ®s[regno]; 5508 int err; 5509 5510 /* We may have added a variable offset to the packet pointer; but any 5511 * reg->range we have comes after that. We are only checking the fixed 5512 * offset. 5513 */ 5514 5515 /* We don't allow negative numbers, because we aren't tracking enough 5516 * detail to prove they're safe. 5517 */ 5518 if (reg->smin_value < 0) { 5519 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n", 5520 regno); 5521 return -EACCES; 5522 } 5523 5524 err = reg->range < 0 ? -EINVAL : 5525 __check_mem_access(env, regno, off, size, reg->range, 5526 zero_size_allowed); 5527 if (err) { 5528 verbose(env, "R%d offset is outside of the packet\n", regno); 5529 return err; 5530 } 5531 5532 /* __check_mem_access has made sure "off + size - 1" is within u16. 5533 * reg->umax_value can't be bigger than MAX_PACKET_OFF which is 0xffff, 5534 * otherwise find_good_pkt_pointers would have refused to set range info 5535 * that __check_mem_access would have rejected this pkt access. 5536 * Therefore, "off + reg->umax_value + size - 1" won't overflow u32. 5537 */ 5538 env->prog->aux->max_pkt_offset = 5539 max_t(u32, env->prog->aux->max_pkt_offset, 5540 off + reg->umax_value + size - 1); 5541 5542 return err; 5543 } 5544 5545 /* check access to 'struct bpf_context' fields. Supports fixed offsets only */ 5546 static int check_ctx_access(struct bpf_verifier_env *env, int insn_idx, int off, int size, 5547 enum bpf_access_type t, enum bpf_reg_type *reg_type, 5548 struct btf **btf, u32 *btf_id) 5549 { 5550 struct bpf_insn_access_aux info = { 5551 .reg_type = *reg_type, 5552 .log = &env->log, 5553 }; 5554 5555 if (env->ops->is_valid_access && 5556 env->ops->is_valid_access(off, size, t, env->prog, &info)) { 5557 /* A non zero info.ctx_field_size indicates that this field is a 5558 * candidate for later verifier transformation to load the whole 5559 * field and then apply a mask when accessed with a narrower 5560 * access than actual ctx access size. A zero info.ctx_field_size 5561 * will only allow for whole field access and rejects any other 5562 * type of narrower access. 5563 */ 5564 *reg_type = info.reg_type; 5565 5566 if (base_type(*reg_type) == PTR_TO_BTF_ID) { 5567 *btf = info.btf; 5568 *btf_id = info.btf_id; 5569 } else { 5570 env->insn_aux_data[insn_idx].ctx_field_size = info.ctx_field_size; 5571 } 5572 /* remember the offset of last byte accessed in ctx */ 5573 if (env->prog->aux->max_ctx_offset < off + size) 5574 env->prog->aux->max_ctx_offset = off + size; 5575 return 0; 5576 } 5577 5578 verbose(env, "invalid bpf_context access off=%d size=%d\n", off, size); 5579 return -EACCES; 5580 } 5581 5582 static int check_flow_keys_access(struct bpf_verifier_env *env, int off, 5583 int size) 5584 { 5585 if (size < 0 || off < 0 || 5586 (u64)off + size > sizeof(struct bpf_flow_keys)) { 5587 verbose(env, "invalid access to flow keys off=%d size=%d\n", 5588 off, size); 5589 return -EACCES; 5590 } 5591 return 0; 5592 } 5593 5594 static int check_sock_access(struct bpf_verifier_env *env, int insn_idx, 5595 u32 regno, int off, int size, 5596 enum bpf_access_type t) 5597 { 5598 struct bpf_reg_state *regs = cur_regs(env); 5599 struct bpf_reg_state *reg = ®s[regno]; 5600 struct bpf_insn_access_aux info = {}; 5601 bool valid; 5602 5603 if (reg->smin_value < 0) { 5604 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n", 5605 regno); 5606 return -EACCES; 5607 } 5608 5609 switch (reg->type) { 5610 case PTR_TO_SOCK_COMMON: 5611 valid = bpf_sock_common_is_valid_access(off, size, t, &info); 5612 break; 5613 case PTR_TO_SOCKET: 5614 valid = bpf_sock_is_valid_access(off, size, t, &info); 5615 break; 5616 case PTR_TO_TCP_SOCK: 5617 valid = bpf_tcp_sock_is_valid_access(off, size, t, &info); 5618 break; 5619 case PTR_TO_XDP_SOCK: 5620 valid = bpf_xdp_sock_is_valid_access(off, size, t, &info); 5621 break; 5622 default: 5623 valid = false; 5624 } 5625 5626 5627 if (valid) { 5628 env->insn_aux_data[insn_idx].ctx_field_size = 5629 info.ctx_field_size; 5630 return 0; 5631 } 5632 5633 verbose(env, "R%d invalid %s access off=%d size=%d\n", 5634 regno, reg_type_str(env, reg->type), off, size); 5635 5636 return -EACCES; 5637 } 5638 5639 static bool is_pointer_value(struct bpf_verifier_env *env, int regno) 5640 { 5641 return __is_pointer_value(env->allow_ptr_leaks, reg_state(env, regno)); 5642 } 5643 5644 static bool is_ctx_reg(struct bpf_verifier_env *env, int regno) 5645 { 5646 const struct bpf_reg_state *reg = reg_state(env, regno); 5647 5648 return reg->type == PTR_TO_CTX; 5649 } 5650 5651 static bool is_sk_reg(struct bpf_verifier_env *env, int regno) 5652 { 5653 const struct bpf_reg_state *reg = reg_state(env, regno); 5654 5655 return type_is_sk_pointer(reg->type); 5656 } 5657 5658 static bool is_pkt_reg(struct bpf_verifier_env *env, int regno) 5659 { 5660 const struct bpf_reg_state *reg = reg_state(env, regno); 5661 5662 return type_is_pkt_pointer(reg->type); 5663 } 5664 5665 static bool is_flow_key_reg(struct bpf_verifier_env *env, int regno) 5666 { 5667 const struct bpf_reg_state *reg = reg_state(env, regno); 5668 5669 /* Separate to is_ctx_reg() since we still want to allow BPF_ST here. */ 5670 return reg->type == PTR_TO_FLOW_KEYS; 5671 } 5672 5673 static u32 *reg2btf_ids[__BPF_REG_TYPE_MAX] = { 5674 #ifdef CONFIG_NET 5675 [PTR_TO_SOCKET] = &btf_sock_ids[BTF_SOCK_TYPE_SOCK], 5676 [PTR_TO_SOCK_COMMON] = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON], 5677 [PTR_TO_TCP_SOCK] = &btf_sock_ids[BTF_SOCK_TYPE_TCP], 5678 #endif 5679 [CONST_PTR_TO_MAP] = btf_bpf_map_id, 5680 }; 5681 5682 static bool is_trusted_reg(const struct bpf_reg_state *reg) 5683 { 5684 /* A referenced register is always trusted. */ 5685 if (reg->ref_obj_id) 5686 return true; 5687 5688 /* Types listed in the reg2btf_ids are always trusted */ 5689 if (reg2btf_ids[base_type(reg->type)] && 5690 !bpf_type_has_unsafe_modifiers(reg->type)) 5691 return true; 5692 5693 /* If a register is not referenced, it is trusted if it has the 5694 * MEM_ALLOC or PTR_TRUSTED type modifiers, and no others. Some of the 5695 * other type modifiers may be safe, but we elect to take an opt-in 5696 * approach here as some (e.g. PTR_UNTRUSTED and PTR_MAYBE_NULL) are 5697 * not. 5698 * 5699 * Eventually, we should make PTR_TRUSTED the single source of truth 5700 * for whether a register is trusted. 5701 */ 5702 return type_flag(reg->type) & BPF_REG_TRUSTED_MODIFIERS && 5703 !bpf_type_has_unsafe_modifiers(reg->type); 5704 } 5705 5706 static bool is_rcu_reg(const struct bpf_reg_state *reg) 5707 { 5708 return reg->type & MEM_RCU; 5709 } 5710 5711 static void clear_trusted_flags(enum bpf_type_flag *flag) 5712 { 5713 *flag &= ~(BPF_REG_TRUSTED_MODIFIERS | MEM_RCU); 5714 } 5715 5716 static int check_pkt_ptr_alignment(struct bpf_verifier_env *env, 5717 const struct bpf_reg_state *reg, 5718 int off, int size, bool strict) 5719 { 5720 struct tnum reg_off; 5721 int ip_align; 5722 5723 /* Byte size accesses are always allowed. */ 5724 if (!strict || size == 1) 5725 return 0; 5726 5727 /* For platforms that do not have a Kconfig enabling 5728 * CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS the value of 5729 * NET_IP_ALIGN is universally set to '2'. And on platforms 5730 * that do set CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS, we get 5731 * to this code only in strict mode where we want to emulate 5732 * the NET_IP_ALIGN==2 checking. Therefore use an 5733 * unconditional IP align value of '2'. 5734 */ 5735 ip_align = 2; 5736 5737 reg_off = tnum_add(reg->var_off, tnum_const(ip_align + reg->off + off)); 5738 if (!tnum_is_aligned(reg_off, size)) { 5739 char tn_buf[48]; 5740 5741 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 5742 verbose(env, 5743 "misaligned packet access off %d+%s+%d+%d size %d\n", 5744 ip_align, tn_buf, reg->off, off, size); 5745 return -EACCES; 5746 } 5747 5748 return 0; 5749 } 5750 5751 static int check_generic_ptr_alignment(struct bpf_verifier_env *env, 5752 const struct bpf_reg_state *reg, 5753 const char *pointer_desc, 5754 int off, int size, bool strict) 5755 { 5756 struct tnum reg_off; 5757 5758 /* Byte size accesses are always allowed. */ 5759 if (!strict || size == 1) 5760 return 0; 5761 5762 reg_off = tnum_add(reg->var_off, tnum_const(reg->off + off)); 5763 if (!tnum_is_aligned(reg_off, size)) { 5764 char tn_buf[48]; 5765 5766 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 5767 verbose(env, "misaligned %saccess off %s+%d+%d size %d\n", 5768 pointer_desc, tn_buf, reg->off, off, size); 5769 return -EACCES; 5770 } 5771 5772 return 0; 5773 } 5774 5775 static int check_ptr_alignment(struct bpf_verifier_env *env, 5776 const struct bpf_reg_state *reg, int off, 5777 int size, bool strict_alignment_once) 5778 { 5779 bool strict = env->strict_alignment || strict_alignment_once; 5780 const char *pointer_desc = ""; 5781 5782 switch (reg->type) { 5783 case PTR_TO_PACKET: 5784 case PTR_TO_PACKET_META: 5785 /* Special case, because of NET_IP_ALIGN. Given metadata sits 5786 * right in front, treat it the very same way. 5787 */ 5788 return check_pkt_ptr_alignment(env, reg, off, size, strict); 5789 case PTR_TO_FLOW_KEYS: 5790 pointer_desc = "flow keys "; 5791 break; 5792 case PTR_TO_MAP_KEY: 5793 pointer_desc = "key "; 5794 break; 5795 case PTR_TO_MAP_VALUE: 5796 pointer_desc = "value "; 5797 break; 5798 case PTR_TO_CTX: 5799 pointer_desc = "context "; 5800 break; 5801 case PTR_TO_STACK: 5802 pointer_desc = "stack "; 5803 /* The stack spill tracking logic in check_stack_write_fixed_off() 5804 * and check_stack_read_fixed_off() relies on stack accesses being 5805 * aligned. 5806 */ 5807 strict = true; 5808 break; 5809 case PTR_TO_SOCKET: 5810 pointer_desc = "sock "; 5811 break; 5812 case PTR_TO_SOCK_COMMON: 5813 pointer_desc = "sock_common "; 5814 break; 5815 case PTR_TO_TCP_SOCK: 5816 pointer_desc = "tcp_sock "; 5817 break; 5818 case PTR_TO_XDP_SOCK: 5819 pointer_desc = "xdp_sock "; 5820 break; 5821 default: 5822 break; 5823 } 5824 return check_generic_ptr_alignment(env, reg, pointer_desc, off, size, 5825 strict); 5826 } 5827 5828 /* starting from main bpf function walk all instructions of the function 5829 * and recursively walk all callees that given function can call. 5830 * Ignore jump and exit insns. 5831 * Since recursion is prevented by check_cfg() this algorithm 5832 * only needs a local stack of MAX_CALL_FRAMES to remember callsites 5833 */ 5834 static int check_max_stack_depth_subprog(struct bpf_verifier_env *env, int idx) 5835 { 5836 struct bpf_subprog_info *subprog = env->subprog_info; 5837 struct bpf_insn *insn = env->prog->insnsi; 5838 int depth = 0, frame = 0, i, subprog_end; 5839 bool tail_call_reachable = false; 5840 int ret_insn[MAX_CALL_FRAMES]; 5841 int ret_prog[MAX_CALL_FRAMES]; 5842 int j; 5843 5844 i = subprog[idx].start; 5845 process_func: 5846 /* protect against potential stack overflow that might happen when 5847 * bpf2bpf calls get combined with tailcalls. Limit the caller's stack 5848 * depth for such case down to 256 so that the worst case scenario 5849 * would result in 8k stack size (32 which is tailcall limit * 256 = 5850 * 8k). 5851 * 5852 * To get the idea what might happen, see an example: 5853 * func1 -> sub rsp, 128 5854 * subfunc1 -> sub rsp, 256 5855 * tailcall1 -> add rsp, 256 5856 * func2 -> sub rsp, 192 (total stack size = 128 + 192 = 320) 5857 * subfunc2 -> sub rsp, 64 5858 * subfunc22 -> sub rsp, 128 5859 * tailcall2 -> add rsp, 128 5860 * func3 -> sub rsp, 32 (total stack size 128 + 192 + 64 + 32 = 416) 5861 * 5862 * tailcall will unwind the current stack frame but it will not get rid 5863 * of caller's stack as shown on the example above. 5864 */ 5865 if (idx && subprog[idx].has_tail_call && depth >= 256) { 5866 verbose(env, 5867 "tail_calls are not allowed when call stack of previous frames is %d bytes. Too large\n", 5868 depth); 5869 return -EACCES; 5870 } 5871 /* round up to 32-bytes, since this is granularity 5872 * of interpreter stack size 5873 */ 5874 depth += round_up(max_t(u32, subprog[idx].stack_depth, 1), 32); 5875 if (depth > MAX_BPF_STACK) { 5876 verbose(env, "combined stack size of %d calls is %d. Too large\n", 5877 frame + 1, depth); 5878 return -EACCES; 5879 } 5880 continue_func: 5881 subprog_end = subprog[idx + 1].start; 5882 for (; i < subprog_end; i++) { 5883 int next_insn, sidx; 5884 5885 if (!bpf_pseudo_call(insn + i) && !bpf_pseudo_func(insn + i)) 5886 continue; 5887 /* remember insn and function to return to */ 5888 ret_insn[frame] = i + 1; 5889 ret_prog[frame] = idx; 5890 5891 /* find the callee */ 5892 next_insn = i + insn[i].imm + 1; 5893 sidx = find_subprog(env, next_insn); 5894 if (sidx < 0) { 5895 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n", 5896 next_insn); 5897 return -EFAULT; 5898 } 5899 if (subprog[sidx].is_async_cb) { 5900 if (subprog[sidx].has_tail_call) { 5901 verbose(env, "verifier bug. subprog has tail_call and async cb\n"); 5902 return -EFAULT; 5903 } 5904 /* async callbacks don't increase bpf prog stack size unless called directly */ 5905 if (!bpf_pseudo_call(insn + i)) 5906 continue; 5907 } 5908 i = next_insn; 5909 idx = sidx; 5910 5911 if (subprog[idx].has_tail_call) 5912 tail_call_reachable = true; 5913 5914 frame++; 5915 if (frame >= MAX_CALL_FRAMES) { 5916 verbose(env, "the call stack of %d frames is too deep !\n", 5917 frame); 5918 return -E2BIG; 5919 } 5920 goto process_func; 5921 } 5922 /* if tail call got detected across bpf2bpf calls then mark each of the 5923 * currently present subprog frames as tail call reachable subprogs; 5924 * this info will be utilized by JIT so that we will be preserving the 5925 * tail call counter throughout bpf2bpf calls combined with tailcalls 5926 */ 5927 if (tail_call_reachable) 5928 for (j = 0; j < frame; j++) 5929 subprog[ret_prog[j]].tail_call_reachable = true; 5930 if (subprog[0].tail_call_reachable) 5931 env->prog->aux->tail_call_reachable = true; 5932 5933 /* end of for() loop means the last insn of the 'subprog' 5934 * was reached. Doesn't matter whether it was JA or EXIT 5935 */ 5936 if (frame == 0) 5937 return 0; 5938 depth -= round_up(max_t(u32, subprog[idx].stack_depth, 1), 32); 5939 frame--; 5940 i = ret_insn[frame]; 5941 idx = ret_prog[frame]; 5942 goto continue_func; 5943 } 5944 5945 static int check_max_stack_depth(struct bpf_verifier_env *env) 5946 { 5947 struct bpf_subprog_info *si = env->subprog_info; 5948 int ret; 5949 5950 for (int i = 0; i < env->subprog_cnt; i++) { 5951 if (!i || si[i].is_async_cb) { 5952 ret = check_max_stack_depth_subprog(env, i); 5953 if (ret < 0) 5954 return ret; 5955 } 5956 continue; 5957 } 5958 return 0; 5959 } 5960 5961 #ifndef CONFIG_BPF_JIT_ALWAYS_ON 5962 static int get_callee_stack_depth(struct bpf_verifier_env *env, 5963 const struct bpf_insn *insn, int idx) 5964 { 5965 int start = idx + insn->imm + 1, subprog; 5966 5967 subprog = find_subprog(env, start); 5968 if (subprog < 0) { 5969 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n", 5970 start); 5971 return -EFAULT; 5972 } 5973 return env->subprog_info[subprog].stack_depth; 5974 } 5975 #endif 5976 5977 static int __check_buffer_access(struct bpf_verifier_env *env, 5978 const char *buf_info, 5979 const struct bpf_reg_state *reg, 5980 int regno, int off, int size) 5981 { 5982 if (off < 0) { 5983 verbose(env, 5984 "R%d invalid %s buffer access: off=%d, size=%d\n", 5985 regno, buf_info, off, size); 5986 return -EACCES; 5987 } 5988 if (!tnum_is_const(reg->var_off) || reg->var_off.value) { 5989 char tn_buf[48]; 5990 5991 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 5992 verbose(env, 5993 "R%d invalid variable buffer offset: off=%d, var_off=%s\n", 5994 regno, off, tn_buf); 5995 return -EACCES; 5996 } 5997 5998 return 0; 5999 } 6000 6001 static int check_tp_buffer_access(struct bpf_verifier_env *env, 6002 const struct bpf_reg_state *reg, 6003 int regno, int off, int size) 6004 { 6005 int err; 6006 6007 err = __check_buffer_access(env, "tracepoint", reg, regno, off, size); 6008 if (err) 6009 return err; 6010 6011 if (off + size > env->prog->aux->max_tp_access) 6012 env->prog->aux->max_tp_access = off + size; 6013 6014 return 0; 6015 } 6016 6017 static int check_buffer_access(struct bpf_verifier_env *env, 6018 const struct bpf_reg_state *reg, 6019 int regno, int off, int size, 6020 bool zero_size_allowed, 6021 u32 *max_access) 6022 { 6023 const char *buf_info = type_is_rdonly_mem(reg->type) ? "rdonly" : "rdwr"; 6024 int err; 6025 6026 err = __check_buffer_access(env, buf_info, reg, regno, off, size); 6027 if (err) 6028 return err; 6029 6030 if (off + size > *max_access) 6031 *max_access = off + size; 6032 6033 return 0; 6034 } 6035 6036 /* BPF architecture zero extends alu32 ops into 64-bit registesr */ 6037 static void zext_32_to_64(struct bpf_reg_state *reg) 6038 { 6039 reg->var_off = tnum_subreg(reg->var_off); 6040 __reg_assign_32_into_64(reg); 6041 } 6042 6043 /* truncate register to smaller size (in bytes) 6044 * must be called with size < BPF_REG_SIZE 6045 */ 6046 static void coerce_reg_to_size(struct bpf_reg_state *reg, int size) 6047 { 6048 u64 mask; 6049 6050 /* clear high bits in bit representation */ 6051 reg->var_off = tnum_cast(reg->var_off, size); 6052 6053 /* fix arithmetic bounds */ 6054 mask = ((u64)1 << (size * 8)) - 1; 6055 if ((reg->umin_value & ~mask) == (reg->umax_value & ~mask)) { 6056 reg->umin_value &= mask; 6057 reg->umax_value &= mask; 6058 } else { 6059 reg->umin_value = 0; 6060 reg->umax_value = mask; 6061 } 6062 reg->smin_value = reg->umin_value; 6063 reg->smax_value = reg->umax_value; 6064 6065 /* If size is smaller than 32bit register the 32bit register 6066 * values are also truncated so we push 64-bit bounds into 6067 * 32-bit bounds. Above were truncated < 32-bits already. 6068 */ 6069 if (size >= 4) 6070 return; 6071 __reg_combine_64_into_32(reg); 6072 } 6073 6074 static void set_sext64_default_val(struct bpf_reg_state *reg, int size) 6075 { 6076 if (size == 1) { 6077 reg->smin_value = reg->s32_min_value = S8_MIN; 6078 reg->smax_value = reg->s32_max_value = S8_MAX; 6079 } else if (size == 2) { 6080 reg->smin_value = reg->s32_min_value = S16_MIN; 6081 reg->smax_value = reg->s32_max_value = S16_MAX; 6082 } else { 6083 /* size == 4 */ 6084 reg->smin_value = reg->s32_min_value = S32_MIN; 6085 reg->smax_value = reg->s32_max_value = S32_MAX; 6086 } 6087 reg->umin_value = reg->u32_min_value = 0; 6088 reg->umax_value = U64_MAX; 6089 reg->u32_max_value = U32_MAX; 6090 reg->var_off = tnum_unknown; 6091 } 6092 6093 static void coerce_reg_to_size_sx(struct bpf_reg_state *reg, int size) 6094 { 6095 s64 init_s64_max, init_s64_min, s64_max, s64_min, u64_cval; 6096 u64 top_smax_value, top_smin_value; 6097 u64 num_bits = size * 8; 6098 6099 if (tnum_is_const(reg->var_off)) { 6100 u64_cval = reg->var_off.value; 6101 if (size == 1) 6102 reg->var_off = tnum_const((s8)u64_cval); 6103 else if (size == 2) 6104 reg->var_off = tnum_const((s16)u64_cval); 6105 else 6106 /* size == 4 */ 6107 reg->var_off = tnum_const((s32)u64_cval); 6108 6109 u64_cval = reg->var_off.value; 6110 reg->smax_value = reg->smin_value = u64_cval; 6111 reg->umax_value = reg->umin_value = u64_cval; 6112 reg->s32_max_value = reg->s32_min_value = u64_cval; 6113 reg->u32_max_value = reg->u32_min_value = u64_cval; 6114 return; 6115 } 6116 6117 top_smax_value = ((u64)reg->smax_value >> num_bits) << num_bits; 6118 top_smin_value = ((u64)reg->smin_value >> num_bits) << num_bits; 6119 6120 if (top_smax_value != top_smin_value) 6121 goto out; 6122 6123 /* find the s64_min and s64_min after sign extension */ 6124 if (size == 1) { 6125 init_s64_max = (s8)reg->smax_value; 6126 init_s64_min = (s8)reg->smin_value; 6127 } else if (size == 2) { 6128 init_s64_max = (s16)reg->smax_value; 6129 init_s64_min = (s16)reg->smin_value; 6130 } else { 6131 init_s64_max = (s32)reg->smax_value; 6132 init_s64_min = (s32)reg->smin_value; 6133 } 6134 6135 s64_max = max(init_s64_max, init_s64_min); 6136 s64_min = min(init_s64_max, init_s64_min); 6137 6138 /* both of s64_max/s64_min positive or negative */ 6139 if ((s64_max >= 0) == (s64_min >= 0)) { 6140 reg->smin_value = reg->s32_min_value = s64_min; 6141 reg->smax_value = reg->s32_max_value = s64_max; 6142 reg->umin_value = reg->u32_min_value = s64_min; 6143 reg->umax_value = reg->u32_max_value = s64_max; 6144 reg->var_off = tnum_range(s64_min, s64_max); 6145 return; 6146 } 6147 6148 out: 6149 set_sext64_default_val(reg, size); 6150 } 6151 6152 static void set_sext32_default_val(struct bpf_reg_state *reg, int size) 6153 { 6154 if (size == 1) { 6155 reg->s32_min_value = S8_MIN; 6156 reg->s32_max_value = S8_MAX; 6157 } else { 6158 /* size == 2 */ 6159 reg->s32_min_value = S16_MIN; 6160 reg->s32_max_value = S16_MAX; 6161 } 6162 reg->u32_min_value = 0; 6163 reg->u32_max_value = U32_MAX; 6164 reg->var_off = tnum_subreg(tnum_unknown); 6165 } 6166 6167 static void coerce_subreg_to_size_sx(struct bpf_reg_state *reg, int size) 6168 { 6169 s32 init_s32_max, init_s32_min, s32_max, s32_min, u32_val; 6170 u32 top_smax_value, top_smin_value; 6171 u32 num_bits = size * 8; 6172 6173 if (tnum_is_const(reg->var_off)) { 6174 u32_val = reg->var_off.value; 6175 if (size == 1) 6176 reg->var_off = tnum_const((s8)u32_val); 6177 else 6178 reg->var_off = tnum_const((s16)u32_val); 6179 6180 u32_val = reg->var_off.value; 6181 reg->s32_min_value = reg->s32_max_value = u32_val; 6182 reg->u32_min_value = reg->u32_max_value = u32_val; 6183 return; 6184 } 6185 6186 top_smax_value = ((u32)reg->s32_max_value >> num_bits) << num_bits; 6187 top_smin_value = ((u32)reg->s32_min_value >> num_bits) << num_bits; 6188 6189 if (top_smax_value != top_smin_value) 6190 goto out; 6191 6192 /* find the s32_min and s32_min after sign extension */ 6193 if (size == 1) { 6194 init_s32_max = (s8)reg->s32_max_value; 6195 init_s32_min = (s8)reg->s32_min_value; 6196 } else { 6197 /* size == 2 */ 6198 init_s32_max = (s16)reg->s32_max_value; 6199 init_s32_min = (s16)reg->s32_min_value; 6200 } 6201 s32_max = max(init_s32_max, init_s32_min); 6202 s32_min = min(init_s32_max, init_s32_min); 6203 6204 if ((s32_min >= 0) == (s32_max >= 0)) { 6205 reg->s32_min_value = s32_min; 6206 reg->s32_max_value = s32_max; 6207 reg->u32_min_value = (u32)s32_min; 6208 reg->u32_max_value = (u32)s32_max; 6209 reg->var_off = tnum_subreg(tnum_range(s32_min, s32_max)); 6210 return; 6211 } 6212 6213 out: 6214 set_sext32_default_val(reg, size); 6215 } 6216 6217 static bool bpf_map_is_rdonly(const struct bpf_map *map) 6218 { 6219 /* A map is considered read-only if the following condition are true: 6220 * 6221 * 1) BPF program side cannot change any of the map content. The 6222 * BPF_F_RDONLY_PROG flag is throughout the lifetime of a map 6223 * and was set at map creation time. 6224 * 2) The map value(s) have been initialized from user space by a 6225 * loader and then "frozen", such that no new map update/delete 6226 * operations from syscall side are possible for the rest of 6227 * the map's lifetime from that point onwards. 6228 * 3) Any parallel/pending map update/delete operations from syscall 6229 * side have been completed. Only after that point, it's safe to 6230 * assume that map value(s) are immutable. 6231 */ 6232 return (map->map_flags & BPF_F_RDONLY_PROG) && 6233 READ_ONCE(map->frozen) && 6234 !bpf_map_write_active(map); 6235 } 6236 6237 static int bpf_map_direct_read(struct bpf_map *map, int off, int size, u64 *val, 6238 bool is_ldsx) 6239 { 6240 void *ptr; 6241 u64 addr; 6242 int err; 6243 6244 err = map->ops->map_direct_value_addr(map, &addr, off); 6245 if (err) 6246 return err; 6247 ptr = (void *)(long)addr + off; 6248 6249 switch (size) { 6250 case sizeof(u8): 6251 *val = is_ldsx ? (s64)*(s8 *)ptr : (u64)*(u8 *)ptr; 6252 break; 6253 case sizeof(u16): 6254 *val = is_ldsx ? (s64)*(s16 *)ptr : (u64)*(u16 *)ptr; 6255 break; 6256 case sizeof(u32): 6257 *val = is_ldsx ? (s64)*(s32 *)ptr : (u64)*(u32 *)ptr; 6258 break; 6259 case sizeof(u64): 6260 *val = *(u64 *)ptr; 6261 break; 6262 default: 6263 return -EINVAL; 6264 } 6265 return 0; 6266 } 6267 6268 #define BTF_TYPE_SAFE_RCU(__type) __PASTE(__type, __safe_rcu) 6269 #define BTF_TYPE_SAFE_RCU_OR_NULL(__type) __PASTE(__type, __safe_rcu_or_null) 6270 #define BTF_TYPE_SAFE_TRUSTED(__type) __PASTE(__type, __safe_trusted) 6271 #define BTF_TYPE_SAFE_TRUSTED_OR_NULL(__type) __PASTE(__type, __safe_trusted_or_null) 6272 6273 /* 6274 * Allow list few fields as RCU trusted or full trusted. 6275 * This logic doesn't allow mix tagging and will be removed once GCC supports 6276 * btf_type_tag. 6277 */ 6278 6279 /* RCU trusted: these fields are trusted in RCU CS and never NULL */ 6280 BTF_TYPE_SAFE_RCU(struct task_struct) { 6281 const cpumask_t *cpus_ptr; 6282 struct css_set __rcu *cgroups; 6283 struct task_struct __rcu *real_parent; 6284 struct task_struct *group_leader; 6285 }; 6286 6287 BTF_TYPE_SAFE_RCU(struct cgroup) { 6288 /* cgrp->kn is always accessible as documented in kernel/cgroup/cgroup.c */ 6289 struct kernfs_node *kn; 6290 }; 6291 6292 BTF_TYPE_SAFE_RCU(struct css_set) { 6293 struct cgroup *dfl_cgrp; 6294 }; 6295 6296 /* RCU trusted: these fields are trusted in RCU CS and can be NULL */ 6297 BTF_TYPE_SAFE_RCU_OR_NULL(struct mm_struct) { 6298 struct file __rcu *exe_file; 6299 }; 6300 6301 /* skb->sk, req->sk are not RCU protected, but we mark them as such 6302 * because bpf prog accessible sockets are SOCK_RCU_FREE. 6303 */ 6304 BTF_TYPE_SAFE_RCU_OR_NULL(struct sk_buff) { 6305 struct sock *sk; 6306 }; 6307 6308 BTF_TYPE_SAFE_RCU_OR_NULL(struct request_sock) { 6309 struct sock *sk; 6310 }; 6311 6312 /* full trusted: these fields are trusted even outside of RCU CS and never NULL */ 6313 BTF_TYPE_SAFE_TRUSTED(struct bpf_iter_meta) { 6314 struct seq_file *seq; 6315 }; 6316 6317 BTF_TYPE_SAFE_TRUSTED(struct bpf_iter__task) { 6318 struct bpf_iter_meta *meta; 6319 struct task_struct *task; 6320 }; 6321 6322 BTF_TYPE_SAFE_TRUSTED(struct linux_binprm) { 6323 struct file *file; 6324 }; 6325 6326 BTF_TYPE_SAFE_TRUSTED(struct file) { 6327 struct inode *f_inode; 6328 }; 6329 6330 BTF_TYPE_SAFE_TRUSTED(struct dentry) { 6331 /* no negative dentry-s in places where bpf can see it */ 6332 struct inode *d_inode; 6333 }; 6334 6335 BTF_TYPE_SAFE_TRUSTED_OR_NULL(struct socket) { 6336 struct sock *sk; 6337 }; 6338 6339 static bool type_is_rcu(struct bpf_verifier_env *env, 6340 struct bpf_reg_state *reg, 6341 const char *field_name, u32 btf_id) 6342 { 6343 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct task_struct)); 6344 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct cgroup)); 6345 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct css_set)); 6346 6347 return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_rcu"); 6348 } 6349 6350 static bool type_is_rcu_or_null(struct bpf_verifier_env *env, 6351 struct bpf_reg_state *reg, 6352 const char *field_name, u32 btf_id) 6353 { 6354 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct mm_struct)); 6355 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct sk_buff)); 6356 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct request_sock)); 6357 6358 return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_rcu_or_null"); 6359 } 6360 6361 static bool type_is_trusted(struct bpf_verifier_env *env, 6362 struct bpf_reg_state *reg, 6363 const char *field_name, u32 btf_id) 6364 { 6365 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct bpf_iter_meta)); 6366 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct bpf_iter__task)); 6367 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct linux_binprm)); 6368 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct file)); 6369 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct dentry)); 6370 6371 return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_trusted"); 6372 } 6373 6374 static bool type_is_trusted_or_null(struct bpf_verifier_env *env, 6375 struct bpf_reg_state *reg, 6376 const char *field_name, u32 btf_id) 6377 { 6378 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED_OR_NULL(struct socket)); 6379 6380 return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, 6381 "__safe_trusted_or_null"); 6382 } 6383 6384 static int check_ptr_to_btf_access(struct bpf_verifier_env *env, 6385 struct bpf_reg_state *regs, 6386 int regno, int off, int size, 6387 enum bpf_access_type atype, 6388 int value_regno) 6389 { 6390 struct bpf_reg_state *reg = regs + regno; 6391 const struct btf_type *t = btf_type_by_id(reg->btf, reg->btf_id); 6392 const char *tname = btf_name_by_offset(reg->btf, t->name_off); 6393 const char *field_name = NULL; 6394 enum bpf_type_flag flag = 0; 6395 u32 btf_id = 0; 6396 int ret; 6397 6398 if (!env->allow_ptr_leaks) { 6399 verbose(env, 6400 "'struct %s' access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n", 6401 tname); 6402 return -EPERM; 6403 } 6404 if (!env->prog->gpl_compatible && btf_is_kernel(reg->btf)) { 6405 verbose(env, 6406 "Cannot access kernel 'struct %s' from non-GPL compatible program\n", 6407 tname); 6408 return -EINVAL; 6409 } 6410 if (off < 0) { 6411 verbose(env, 6412 "R%d is ptr_%s invalid negative access: off=%d\n", 6413 regno, tname, off); 6414 return -EACCES; 6415 } 6416 if (!tnum_is_const(reg->var_off) || reg->var_off.value) { 6417 char tn_buf[48]; 6418 6419 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 6420 verbose(env, 6421 "R%d is ptr_%s invalid variable offset: off=%d, var_off=%s\n", 6422 regno, tname, off, tn_buf); 6423 return -EACCES; 6424 } 6425 6426 if (reg->type & MEM_USER) { 6427 verbose(env, 6428 "R%d is ptr_%s access user memory: off=%d\n", 6429 regno, tname, off); 6430 return -EACCES; 6431 } 6432 6433 if (reg->type & MEM_PERCPU) { 6434 verbose(env, 6435 "R%d is ptr_%s access percpu memory: off=%d\n", 6436 regno, tname, off); 6437 return -EACCES; 6438 } 6439 6440 if (env->ops->btf_struct_access && !type_is_alloc(reg->type) && atype == BPF_WRITE) { 6441 if (!btf_is_kernel(reg->btf)) { 6442 verbose(env, "verifier internal error: reg->btf must be kernel btf\n"); 6443 return -EFAULT; 6444 } 6445 ret = env->ops->btf_struct_access(&env->log, reg, off, size); 6446 } else { 6447 /* Writes are permitted with default btf_struct_access for 6448 * program allocated objects (which always have ref_obj_id > 0), 6449 * but not for untrusted PTR_TO_BTF_ID | MEM_ALLOC. 6450 */ 6451 if (atype != BPF_READ && !type_is_ptr_alloc_obj(reg->type)) { 6452 verbose(env, "only read is supported\n"); 6453 return -EACCES; 6454 } 6455 6456 if (type_is_alloc(reg->type) && !type_is_non_owning_ref(reg->type) && 6457 !reg->ref_obj_id) { 6458 verbose(env, "verifier internal error: ref_obj_id for allocated object must be non-zero\n"); 6459 return -EFAULT; 6460 } 6461 6462 ret = btf_struct_access(&env->log, reg, off, size, atype, &btf_id, &flag, &field_name); 6463 } 6464 6465 if (ret < 0) 6466 return ret; 6467 6468 if (ret != PTR_TO_BTF_ID) { 6469 /* just mark; */ 6470 6471 } else if (type_flag(reg->type) & PTR_UNTRUSTED) { 6472 /* If this is an untrusted pointer, all pointers formed by walking it 6473 * also inherit the untrusted flag. 6474 */ 6475 flag = PTR_UNTRUSTED; 6476 6477 } else if (is_trusted_reg(reg) || is_rcu_reg(reg)) { 6478 /* By default any pointer obtained from walking a trusted pointer is no 6479 * longer trusted, unless the field being accessed has explicitly been 6480 * marked as inheriting its parent's state of trust (either full or RCU). 6481 * For example: 6482 * 'cgroups' pointer is untrusted if task->cgroups dereference 6483 * happened in a sleepable program outside of bpf_rcu_read_lock() 6484 * section. In a non-sleepable program it's trusted while in RCU CS (aka MEM_RCU). 6485 * Note bpf_rcu_read_unlock() converts MEM_RCU pointers to PTR_UNTRUSTED. 6486 * 6487 * A regular RCU-protected pointer with __rcu tag can also be deemed 6488 * trusted if we are in an RCU CS. Such pointer can be NULL. 6489 */ 6490 if (type_is_trusted(env, reg, field_name, btf_id)) { 6491 flag |= PTR_TRUSTED; 6492 } else if (type_is_trusted_or_null(env, reg, field_name, btf_id)) { 6493 flag |= PTR_TRUSTED | PTR_MAYBE_NULL; 6494 } else if (in_rcu_cs(env) && !type_may_be_null(reg->type)) { 6495 if (type_is_rcu(env, reg, field_name, btf_id)) { 6496 /* ignore __rcu tag and mark it MEM_RCU */ 6497 flag |= MEM_RCU; 6498 } else if (flag & MEM_RCU || 6499 type_is_rcu_or_null(env, reg, field_name, btf_id)) { 6500 /* __rcu tagged pointers can be NULL */ 6501 flag |= MEM_RCU | PTR_MAYBE_NULL; 6502 6503 /* We always trust them */ 6504 if (type_is_rcu_or_null(env, reg, field_name, btf_id) && 6505 flag & PTR_UNTRUSTED) 6506 flag &= ~PTR_UNTRUSTED; 6507 } else if (flag & (MEM_PERCPU | MEM_USER)) { 6508 /* keep as-is */ 6509 } else { 6510 /* walking unknown pointers yields old deprecated PTR_TO_BTF_ID */ 6511 clear_trusted_flags(&flag); 6512 } 6513 } else { 6514 /* 6515 * If not in RCU CS or MEM_RCU pointer can be NULL then 6516 * aggressively mark as untrusted otherwise such 6517 * pointers will be plain PTR_TO_BTF_ID without flags 6518 * and will be allowed to be passed into helpers for 6519 * compat reasons. 6520 */ 6521 flag = PTR_UNTRUSTED; 6522 } 6523 } else { 6524 /* Old compat. Deprecated */ 6525 clear_trusted_flags(&flag); 6526 } 6527 6528 if (atype == BPF_READ && value_regno >= 0) 6529 mark_btf_ld_reg(env, regs, value_regno, ret, reg->btf, btf_id, flag); 6530 6531 return 0; 6532 } 6533 6534 static int check_ptr_to_map_access(struct bpf_verifier_env *env, 6535 struct bpf_reg_state *regs, 6536 int regno, int off, int size, 6537 enum bpf_access_type atype, 6538 int value_regno) 6539 { 6540 struct bpf_reg_state *reg = regs + regno; 6541 struct bpf_map *map = reg->map_ptr; 6542 struct bpf_reg_state map_reg; 6543 enum bpf_type_flag flag = 0; 6544 const struct btf_type *t; 6545 const char *tname; 6546 u32 btf_id; 6547 int ret; 6548 6549 if (!btf_vmlinux) { 6550 verbose(env, "map_ptr access not supported without CONFIG_DEBUG_INFO_BTF\n"); 6551 return -ENOTSUPP; 6552 } 6553 6554 if (!map->ops->map_btf_id || !*map->ops->map_btf_id) { 6555 verbose(env, "map_ptr access not supported for map type %d\n", 6556 map->map_type); 6557 return -ENOTSUPP; 6558 } 6559 6560 t = btf_type_by_id(btf_vmlinux, *map->ops->map_btf_id); 6561 tname = btf_name_by_offset(btf_vmlinux, t->name_off); 6562 6563 if (!env->allow_ptr_leaks) { 6564 verbose(env, 6565 "'struct %s' access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n", 6566 tname); 6567 return -EPERM; 6568 } 6569 6570 if (off < 0) { 6571 verbose(env, "R%d is %s invalid negative access: off=%d\n", 6572 regno, tname, off); 6573 return -EACCES; 6574 } 6575 6576 if (atype != BPF_READ) { 6577 verbose(env, "only read from %s is supported\n", tname); 6578 return -EACCES; 6579 } 6580 6581 /* Simulate access to a PTR_TO_BTF_ID */ 6582 memset(&map_reg, 0, sizeof(map_reg)); 6583 mark_btf_ld_reg(env, &map_reg, 0, PTR_TO_BTF_ID, btf_vmlinux, *map->ops->map_btf_id, 0); 6584 ret = btf_struct_access(&env->log, &map_reg, off, size, atype, &btf_id, &flag, NULL); 6585 if (ret < 0) 6586 return ret; 6587 6588 if (value_regno >= 0) 6589 mark_btf_ld_reg(env, regs, value_regno, ret, btf_vmlinux, btf_id, flag); 6590 6591 return 0; 6592 } 6593 6594 /* Check that the stack access at the given offset is within bounds. The 6595 * maximum valid offset is -1. 6596 * 6597 * The minimum valid offset is -MAX_BPF_STACK for writes, and 6598 * -state->allocated_stack for reads. 6599 */ 6600 static int check_stack_slot_within_bounds(struct bpf_verifier_env *env, 6601 s64 off, 6602 struct bpf_func_state *state, 6603 enum bpf_access_type t) 6604 { 6605 int min_valid_off; 6606 6607 if (t == BPF_WRITE || env->allow_uninit_stack) 6608 min_valid_off = -MAX_BPF_STACK; 6609 else 6610 min_valid_off = -state->allocated_stack; 6611 6612 if (off < min_valid_off || off > -1) 6613 return -EACCES; 6614 return 0; 6615 } 6616 6617 /* Check that the stack access at 'regno + off' falls within the maximum stack 6618 * bounds. 6619 * 6620 * 'off' includes `regno->offset`, but not its dynamic part (if any). 6621 */ 6622 static int check_stack_access_within_bounds( 6623 struct bpf_verifier_env *env, 6624 int regno, int off, int access_size, 6625 enum bpf_access_src src, enum bpf_access_type type) 6626 { 6627 struct bpf_reg_state *regs = cur_regs(env); 6628 struct bpf_reg_state *reg = regs + regno; 6629 struct bpf_func_state *state = func(env, reg); 6630 s64 min_off, max_off; 6631 int err; 6632 char *err_extra; 6633 6634 if (src == ACCESS_HELPER) 6635 /* We don't know if helpers are reading or writing (or both). */ 6636 err_extra = " indirect access to"; 6637 else if (type == BPF_READ) 6638 err_extra = " read from"; 6639 else 6640 err_extra = " write to"; 6641 6642 if (tnum_is_const(reg->var_off)) { 6643 min_off = (s64)reg->var_off.value + off; 6644 max_off = min_off + access_size; 6645 } else { 6646 if (reg->smax_value >= BPF_MAX_VAR_OFF || 6647 reg->smin_value <= -BPF_MAX_VAR_OFF) { 6648 verbose(env, "invalid unbounded variable-offset%s stack R%d\n", 6649 err_extra, regno); 6650 return -EACCES; 6651 } 6652 min_off = reg->smin_value + off; 6653 max_off = reg->smax_value + off + access_size; 6654 } 6655 6656 err = check_stack_slot_within_bounds(env, min_off, state, type); 6657 if (!err && max_off > 0) 6658 err = -EINVAL; /* out of stack access into non-negative offsets */ 6659 if (!err && access_size < 0) 6660 /* access_size should not be negative (or overflow an int); others checks 6661 * along the way should have prevented such an access. 6662 */ 6663 err = -EFAULT; /* invalid negative access size; integer overflow? */ 6664 6665 if (err) { 6666 if (tnum_is_const(reg->var_off)) { 6667 verbose(env, "invalid%s stack R%d off=%d size=%d\n", 6668 err_extra, regno, off, access_size); 6669 } else { 6670 char tn_buf[48]; 6671 6672 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 6673 verbose(env, "invalid variable-offset%s stack R%d var_off=%s size=%d\n", 6674 err_extra, regno, tn_buf, access_size); 6675 } 6676 return err; 6677 } 6678 6679 return grow_stack_state(env, state, round_up(-min_off, BPF_REG_SIZE)); 6680 } 6681 6682 /* check whether memory at (regno + off) is accessible for t = (read | write) 6683 * if t==write, value_regno is a register which value is stored into memory 6684 * if t==read, value_regno is a register which will receive the value from memory 6685 * if t==write && value_regno==-1, some unknown value is stored into memory 6686 * if t==read && value_regno==-1, don't care what we read from memory 6687 */ 6688 static int check_mem_access(struct bpf_verifier_env *env, int insn_idx, u32 regno, 6689 int off, int bpf_size, enum bpf_access_type t, 6690 int value_regno, bool strict_alignment_once, bool is_ldsx) 6691 { 6692 struct bpf_reg_state *regs = cur_regs(env); 6693 struct bpf_reg_state *reg = regs + regno; 6694 int size, err = 0; 6695 6696 size = bpf_size_to_bytes(bpf_size); 6697 if (size < 0) 6698 return size; 6699 6700 /* alignment checks will add in reg->off themselves */ 6701 err = check_ptr_alignment(env, reg, off, size, strict_alignment_once); 6702 if (err) 6703 return err; 6704 6705 /* for access checks, reg->off is just part of off */ 6706 off += reg->off; 6707 6708 if (reg->type == PTR_TO_MAP_KEY) { 6709 if (t == BPF_WRITE) { 6710 verbose(env, "write to change key R%d not allowed\n", regno); 6711 return -EACCES; 6712 } 6713 6714 err = check_mem_region_access(env, regno, off, size, 6715 reg->map_ptr->key_size, false); 6716 if (err) 6717 return err; 6718 if (value_regno >= 0) 6719 mark_reg_unknown(env, regs, value_regno); 6720 } else if (reg->type == PTR_TO_MAP_VALUE) { 6721 struct btf_field *kptr_field = NULL; 6722 6723 if (t == BPF_WRITE && value_regno >= 0 && 6724 is_pointer_value(env, value_regno)) { 6725 verbose(env, "R%d leaks addr into map\n", value_regno); 6726 return -EACCES; 6727 } 6728 err = check_map_access_type(env, regno, off, size, t); 6729 if (err) 6730 return err; 6731 err = check_map_access(env, regno, off, size, false, ACCESS_DIRECT); 6732 if (err) 6733 return err; 6734 if (tnum_is_const(reg->var_off)) 6735 kptr_field = btf_record_find(reg->map_ptr->record, 6736 off + reg->var_off.value, BPF_KPTR); 6737 if (kptr_field) { 6738 err = check_map_kptr_access(env, regno, value_regno, insn_idx, kptr_field); 6739 } else if (t == BPF_READ && value_regno >= 0) { 6740 struct bpf_map *map = reg->map_ptr; 6741 6742 /* if map is read-only, track its contents as scalars */ 6743 if (tnum_is_const(reg->var_off) && 6744 bpf_map_is_rdonly(map) && 6745 map->ops->map_direct_value_addr) { 6746 int map_off = off + reg->var_off.value; 6747 u64 val = 0; 6748 6749 err = bpf_map_direct_read(map, map_off, size, 6750 &val, is_ldsx); 6751 if (err) 6752 return err; 6753 6754 regs[value_regno].type = SCALAR_VALUE; 6755 __mark_reg_known(®s[value_regno], val); 6756 } else { 6757 mark_reg_unknown(env, regs, value_regno); 6758 } 6759 } 6760 } else if (base_type(reg->type) == PTR_TO_MEM) { 6761 bool rdonly_mem = type_is_rdonly_mem(reg->type); 6762 6763 if (type_may_be_null(reg->type)) { 6764 verbose(env, "R%d invalid mem access '%s'\n", regno, 6765 reg_type_str(env, reg->type)); 6766 return -EACCES; 6767 } 6768 6769 if (t == BPF_WRITE && rdonly_mem) { 6770 verbose(env, "R%d cannot write into %s\n", 6771 regno, reg_type_str(env, reg->type)); 6772 return -EACCES; 6773 } 6774 6775 if (t == BPF_WRITE && value_regno >= 0 && 6776 is_pointer_value(env, value_regno)) { 6777 verbose(env, "R%d leaks addr into mem\n", value_regno); 6778 return -EACCES; 6779 } 6780 6781 err = check_mem_region_access(env, regno, off, size, 6782 reg->mem_size, false); 6783 if (!err && value_regno >= 0 && (t == BPF_READ || rdonly_mem)) 6784 mark_reg_unknown(env, regs, value_regno); 6785 } else if (reg->type == PTR_TO_CTX) { 6786 enum bpf_reg_type reg_type = SCALAR_VALUE; 6787 struct btf *btf = NULL; 6788 u32 btf_id = 0; 6789 6790 if (t == BPF_WRITE && value_regno >= 0 && 6791 is_pointer_value(env, value_regno)) { 6792 verbose(env, "R%d leaks addr into ctx\n", value_regno); 6793 return -EACCES; 6794 } 6795 6796 err = check_ptr_off_reg(env, reg, regno); 6797 if (err < 0) 6798 return err; 6799 6800 err = check_ctx_access(env, insn_idx, off, size, t, ®_type, &btf, 6801 &btf_id); 6802 if (err) 6803 verbose_linfo(env, insn_idx, "; "); 6804 if (!err && t == BPF_READ && value_regno >= 0) { 6805 /* ctx access returns either a scalar, or a 6806 * PTR_TO_PACKET[_META,_END]. In the latter 6807 * case, we know the offset is zero. 6808 */ 6809 if (reg_type == SCALAR_VALUE) { 6810 mark_reg_unknown(env, regs, value_regno); 6811 } else { 6812 mark_reg_known_zero(env, regs, 6813 value_regno); 6814 if (type_may_be_null(reg_type)) 6815 regs[value_regno].id = ++env->id_gen; 6816 /* A load of ctx field could have different 6817 * actual load size with the one encoded in the 6818 * insn. When the dst is PTR, it is for sure not 6819 * a sub-register. 6820 */ 6821 regs[value_regno].subreg_def = DEF_NOT_SUBREG; 6822 if (base_type(reg_type) == PTR_TO_BTF_ID) { 6823 regs[value_regno].btf = btf; 6824 regs[value_regno].btf_id = btf_id; 6825 } 6826 } 6827 regs[value_regno].type = reg_type; 6828 } 6829 6830 } else if (reg->type == PTR_TO_STACK) { 6831 /* Basic bounds checks. */ 6832 err = check_stack_access_within_bounds(env, regno, off, size, ACCESS_DIRECT, t); 6833 if (err) 6834 return err; 6835 6836 if (t == BPF_READ) 6837 err = check_stack_read(env, regno, off, size, 6838 value_regno); 6839 else 6840 err = check_stack_write(env, regno, off, size, 6841 value_regno, insn_idx); 6842 } else if (reg_is_pkt_pointer(reg)) { 6843 if (t == BPF_WRITE && !may_access_direct_pkt_data(env, NULL, t)) { 6844 verbose(env, "cannot write into packet\n"); 6845 return -EACCES; 6846 } 6847 if (t == BPF_WRITE && value_regno >= 0 && 6848 is_pointer_value(env, value_regno)) { 6849 verbose(env, "R%d leaks addr into packet\n", 6850 value_regno); 6851 return -EACCES; 6852 } 6853 err = check_packet_access(env, regno, off, size, false); 6854 if (!err && t == BPF_READ && value_regno >= 0) 6855 mark_reg_unknown(env, regs, value_regno); 6856 } else if (reg->type == PTR_TO_FLOW_KEYS) { 6857 if (t == BPF_WRITE && value_regno >= 0 && 6858 is_pointer_value(env, value_regno)) { 6859 verbose(env, "R%d leaks addr into flow keys\n", 6860 value_regno); 6861 return -EACCES; 6862 } 6863 6864 err = check_flow_keys_access(env, off, size); 6865 if (!err && t == BPF_READ && value_regno >= 0) 6866 mark_reg_unknown(env, regs, value_regno); 6867 } else if (type_is_sk_pointer(reg->type)) { 6868 if (t == BPF_WRITE) { 6869 verbose(env, "R%d cannot write into %s\n", 6870 regno, reg_type_str(env, reg->type)); 6871 return -EACCES; 6872 } 6873 err = check_sock_access(env, insn_idx, regno, off, size, t); 6874 if (!err && value_regno >= 0) 6875 mark_reg_unknown(env, regs, value_regno); 6876 } else if (reg->type == PTR_TO_TP_BUFFER) { 6877 err = check_tp_buffer_access(env, reg, regno, off, size); 6878 if (!err && t == BPF_READ && value_regno >= 0) 6879 mark_reg_unknown(env, regs, value_regno); 6880 } else if (base_type(reg->type) == PTR_TO_BTF_ID && 6881 !type_may_be_null(reg->type)) { 6882 err = check_ptr_to_btf_access(env, regs, regno, off, size, t, 6883 value_regno); 6884 } else if (reg->type == CONST_PTR_TO_MAP) { 6885 err = check_ptr_to_map_access(env, regs, regno, off, size, t, 6886 value_regno); 6887 } else if (base_type(reg->type) == PTR_TO_BUF) { 6888 bool rdonly_mem = type_is_rdonly_mem(reg->type); 6889 u32 *max_access; 6890 6891 if (rdonly_mem) { 6892 if (t == BPF_WRITE) { 6893 verbose(env, "R%d cannot write into %s\n", 6894 regno, reg_type_str(env, reg->type)); 6895 return -EACCES; 6896 } 6897 max_access = &env->prog->aux->max_rdonly_access; 6898 } else { 6899 max_access = &env->prog->aux->max_rdwr_access; 6900 } 6901 6902 err = check_buffer_access(env, reg, regno, off, size, false, 6903 max_access); 6904 6905 if (!err && value_regno >= 0 && (rdonly_mem || t == BPF_READ)) 6906 mark_reg_unknown(env, regs, value_regno); 6907 } else { 6908 verbose(env, "R%d invalid mem access '%s'\n", regno, 6909 reg_type_str(env, reg->type)); 6910 return -EACCES; 6911 } 6912 6913 if (!err && size < BPF_REG_SIZE && value_regno >= 0 && t == BPF_READ && 6914 regs[value_regno].type == SCALAR_VALUE) { 6915 if (!is_ldsx) 6916 /* b/h/w load zero-extends, mark upper bits as known 0 */ 6917 coerce_reg_to_size(®s[value_regno], size); 6918 else 6919 coerce_reg_to_size_sx(®s[value_regno], size); 6920 } 6921 return err; 6922 } 6923 6924 static int check_atomic(struct bpf_verifier_env *env, int insn_idx, struct bpf_insn *insn) 6925 { 6926 int load_reg; 6927 int err; 6928 6929 switch (insn->imm) { 6930 case BPF_ADD: 6931 case BPF_ADD | BPF_FETCH: 6932 case BPF_AND: 6933 case BPF_AND | BPF_FETCH: 6934 case BPF_OR: 6935 case BPF_OR | BPF_FETCH: 6936 case BPF_XOR: 6937 case BPF_XOR | BPF_FETCH: 6938 case BPF_XCHG: 6939 case BPF_CMPXCHG: 6940 break; 6941 default: 6942 verbose(env, "BPF_ATOMIC uses invalid atomic opcode %02x\n", insn->imm); 6943 return -EINVAL; 6944 } 6945 6946 if (BPF_SIZE(insn->code) != BPF_W && BPF_SIZE(insn->code) != BPF_DW) { 6947 verbose(env, "invalid atomic operand size\n"); 6948 return -EINVAL; 6949 } 6950 6951 /* check src1 operand */ 6952 err = check_reg_arg(env, insn->src_reg, SRC_OP); 6953 if (err) 6954 return err; 6955 6956 /* check src2 operand */ 6957 err = check_reg_arg(env, insn->dst_reg, SRC_OP); 6958 if (err) 6959 return err; 6960 6961 if (insn->imm == BPF_CMPXCHG) { 6962 /* Check comparison of R0 with memory location */ 6963 const u32 aux_reg = BPF_REG_0; 6964 6965 err = check_reg_arg(env, aux_reg, SRC_OP); 6966 if (err) 6967 return err; 6968 6969 if (is_pointer_value(env, aux_reg)) { 6970 verbose(env, "R%d leaks addr into mem\n", aux_reg); 6971 return -EACCES; 6972 } 6973 } 6974 6975 if (is_pointer_value(env, insn->src_reg)) { 6976 verbose(env, "R%d leaks addr into mem\n", insn->src_reg); 6977 return -EACCES; 6978 } 6979 6980 if (is_ctx_reg(env, insn->dst_reg) || 6981 is_pkt_reg(env, insn->dst_reg) || 6982 is_flow_key_reg(env, insn->dst_reg) || 6983 is_sk_reg(env, insn->dst_reg)) { 6984 verbose(env, "BPF_ATOMIC stores into R%d %s is not allowed\n", 6985 insn->dst_reg, 6986 reg_type_str(env, reg_state(env, insn->dst_reg)->type)); 6987 return -EACCES; 6988 } 6989 6990 if (insn->imm & BPF_FETCH) { 6991 if (insn->imm == BPF_CMPXCHG) 6992 load_reg = BPF_REG_0; 6993 else 6994 load_reg = insn->src_reg; 6995 6996 /* check and record load of old value */ 6997 err = check_reg_arg(env, load_reg, DST_OP); 6998 if (err) 6999 return err; 7000 } else { 7001 /* This instruction accesses a memory location but doesn't 7002 * actually load it into a register. 7003 */ 7004 load_reg = -1; 7005 } 7006 7007 /* Check whether we can read the memory, with second call for fetch 7008 * case to simulate the register fill. 7009 */ 7010 err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off, 7011 BPF_SIZE(insn->code), BPF_READ, -1, true, false); 7012 if (!err && load_reg >= 0) 7013 err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off, 7014 BPF_SIZE(insn->code), BPF_READ, load_reg, 7015 true, false); 7016 if (err) 7017 return err; 7018 7019 /* Check whether we can write into the same memory. */ 7020 err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off, 7021 BPF_SIZE(insn->code), BPF_WRITE, -1, true, false); 7022 if (err) 7023 return err; 7024 7025 return 0; 7026 } 7027 7028 /* When register 'regno' is used to read the stack (either directly or through 7029 * a helper function) make sure that it's within stack boundary and, depending 7030 * on the access type and privileges, that all elements of the stack are 7031 * initialized. 7032 * 7033 * 'off' includes 'regno->off', but not its dynamic part (if any). 7034 * 7035 * All registers that have been spilled on the stack in the slots within the 7036 * read offsets are marked as read. 7037 */ 7038 static int check_stack_range_initialized( 7039 struct bpf_verifier_env *env, int regno, int off, 7040 int access_size, bool zero_size_allowed, 7041 enum bpf_access_src type, struct bpf_call_arg_meta *meta) 7042 { 7043 struct bpf_reg_state *reg = reg_state(env, regno); 7044 struct bpf_func_state *state = func(env, reg); 7045 int err, min_off, max_off, i, j, slot, spi; 7046 char *err_extra = type == ACCESS_HELPER ? " indirect" : ""; 7047 enum bpf_access_type bounds_check_type; 7048 /* Some accesses can write anything into the stack, others are 7049 * read-only. 7050 */ 7051 bool clobber = false; 7052 7053 if (access_size == 0 && !zero_size_allowed) { 7054 verbose(env, "invalid zero-sized read\n"); 7055 return -EACCES; 7056 } 7057 7058 if (type == ACCESS_HELPER) { 7059 /* The bounds checks for writes are more permissive than for 7060 * reads. However, if raw_mode is not set, we'll do extra 7061 * checks below. 7062 */ 7063 bounds_check_type = BPF_WRITE; 7064 clobber = true; 7065 } else { 7066 bounds_check_type = BPF_READ; 7067 } 7068 err = check_stack_access_within_bounds(env, regno, off, access_size, 7069 type, bounds_check_type); 7070 if (err) 7071 return err; 7072 7073 7074 if (tnum_is_const(reg->var_off)) { 7075 min_off = max_off = reg->var_off.value + off; 7076 } else { 7077 /* Variable offset is prohibited for unprivileged mode for 7078 * simplicity since it requires corresponding support in 7079 * Spectre masking for stack ALU. 7080 * See also retrieve_ptr_limit(). 7081 */ 7082 if (!env->bypass_spec_v1) { 7083 char tn_buf[48]; 7084 7085 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 7086 verbose(env, "R%d%s variable offset stack access prohibited for !root, var_off=%s\n", 7087 regno, err_extra, tn_buf); 7088 return -EACCES; 7089 } 7090 /* Only initialized buffer on stack is allowed to be accessed 7091 * with variable offset. With uninitialized buffer it's hard to 7092 * guarantee that whole memory is marked as initialized on 7093 * helper return since specific bounds are unknown what may 7094 * cause uninitialized stack leaking. 7095 */ 7096 if (meta && meta->raw_mode) 7097 meta = NULL; 7098 7099 min_off = reg->smin_value + off; 7100 max_off = reg->smax_value + off; 7101 } 7102 7103 if (meta && meta->raw_mode) { 7104 /* Ensure we won't be overwriting dynptrs when simulating byte 7105 * by byte access in check_helper_call using meta.access_size. 7106 * This would be a problem if we have a helper in the future 7107 * which takes: 7108 * 7109 * helper(uninit_mem, len, dynptr) 7110 * 7111 * Now, uninint_mem may overlap with dynptr pointer. Hence, it 7112 * may end up writing to dynptr itself when touching memory from 7113 * arg 1. This can be relaxed on a case by case basis for known 7114 * safe cases, but reject due to the possibilitiy of aliasing by 7115 * default. 7116 */ 7117 for (i = min_off; i < max_off + access_size; i++) { 7118 int stack_off = -i - 1; 7119 7120 spi = __get_spi(i); 7121 /* raw_mode may write past allocated_stack */ 7122 if (state->allocated_stack <= stack_off) 7123 continue; 7124 if (state->stack[spi].slot_type[stack_off % BPF_REG_SIZE] == STACK_DYNPTR) { 7125 verbose(env, "potential write to dynptr at off=%d disallowed\n", i); 7126 return -EACCES; 7127 } 7128 } 7129 meta->access_size = access_size; 7130 meta->regno = regno; 7131 return 0; 7132 } 7133 7134 for (i = min_off; i < max_off + access_size; i++) { 7135 u8 *stype; 7136 7137 slot = -i - 1; 7138 spi = slot / BPF_REG_SIZE; 7139 if (state->allocated_stack <= slot) { 7140 verbose(env, "verifier bug: allocated_stack too small"); 7141 return -EFAULT; 7142 } 7143 7144 stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE]; 7145 if (*stype == STACK_MISC) 7146 goto mark; 7147 if ((*stype == STACK_ZERO) || 7148 (*stype == STACK_INVALID && env->allow_uninit_stack)) { 7149 if (clobber) { 7150 /* helper can write anything into the stack */ 7151 *stype = STACK_MISC; 7152 } 7153 goto mark; 7154 } 7155 7156 if (is_spilled_reg(&state->stack[spi]) && 7157 (state->stack[spi].spilled_ptr.type == SCALAR_VALUE || 7158 env->allow_ptr_leaks)) { 7159 if (clobber) { 7160 __mark_reg_unknown(env, &state->stack[spi].spilled_ptr); 7161 for (j = 0; j < BPF_REG_SIZE; j++) 7162 scrub_spilled_slot(&state->stack[spi].slot_type[j]); 7163 } 7164 goto mark; 7165 } 7166 7167 if (tnum_is_const(reg->var_off)) { 7168 verbose(env, "invalid%s read from stack R%d off %d+%d size %d\n", 7169 err_extra, regno, min_off, i - min_off, access_size); 7170 } else { 7171 char tn_buf[48]; 7172 7173 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 7174 verbose(env, "invalid%s read from stack R%d var_off %s+%d size %d\n", 7175 err_extra, regno, tn_buf, i - min_off, access_size); 7176 } 7177 return -EACCES; 7178 mark: 7179 /* reading any byte out of 8-byte 'spill_slot' will cause 7180 * the whole slot to be marked as 'read' 7181 */ 7182 mark_reg_read(env, &state->stack[spi].spilled_ptr, 7183 state->stack[spi].spilled_ptr.parent, 7184 REG_LIVE_READ64); 7185 /* We do not set REG_LIVE_WRITTEN for stack slot, as we can not 7186 * be sure that whether stack slot is written to or not. Hence, 7187 * we must still conservatively propagate reads upwards even if 7188 * helper may write to the entire memory range. 7189 */ 7190 } 7191 return 0; 7192 } 7193 7194 static int check_helper_mem_access(struct bpf_verifier_env *env, int regno, 7195 int access_size, bool zero_size_allowed, 7196 struct bpf_call_arg_meta *meta) 7197 { 7198 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno]; 7199 u32 *max_access; 7200 7201 switch (base_type(reg->type)) { 7202 case PTR_TO_PACKET: 7203 case PTR_TO_PACKET_META: 7204 return check_packet_access(env, regno, reg->off, access_size, 7205 zero_size_allowed); 7206 case PTR_TO_MAP_KEY: 7207 if (meta && meta->raw_mode) { 7208 verbose(env, "R%d cannot write into %s\n", regno, 7209 reg_type_str(env, reg->type)); 7210 return -EACCES; 7211 } 7212 return check_mem_region_access(env, regno, reg->off, access_size, 7213 reg->map_ptr->key_size, false); 7214 case PTR_TO_MAP_VALUE: 7215 if (check_map_access_type(env, regno, reg->off, access_size, 7216 meta && meta->raw_mode ? BPF_WRITE : 7217 BPF_READ)) 7218 return -EACCES; 7219 return check_map_access(env, regno, reg->off, access_size, 7220 zero_size_allowed, ACCESS_HELPER); 7221 case PTR_TO_MEM: 7222 if (type_is_rdonly_mem(reg->type)) { 7223 if (meta && meta->raw_mode) { 7224 verbose(env, "R%d cannot write into %s\n", regno, 7225 reg_type_str(env, reg->type)); 7226 return -EACCES; 7227 } 7228 } 7229 return check_mem_region_access(env, regno, reg->off, 7230 access_size, reg->mem_size, 7231 zero_size_allowed); 7232 case PTR_TO_BUF: 7233 if (type_is_rdonly_mem(reg->type)) { 7234 if (meta && meta->raw_mode) { 7235 verbose(env, "R%d cannot write into %s\n", regno, 7236 reg_type_str(env, reg->type)); 7237 return -EACCES; 7238 } 7239 7240 max_access = &env->prog->aux->max_rdonly_access; 7241 } else { 7242 max_access = &env->prog->aux->max_rdwr_access; 7243 } 7244 return check_buffer_access(env, reg, regno, reg->off, 7245 access_size, zero_size_allowed, 7246 max_access); 7247 case PTR_TO_STACK: 7248 return check_stack_range_initialized( 7249 env, 7250 regno, reg->off, access_size, 7251 zero_size_allowed, ACCESS_HELPER, meta); 7252 case PTR_TO_BTF_ID: 7253 return check_ptr_to_btf_access(env, regs, regno, reg->off, 7254 access_size, BPF_READ, -1); 7255 case PTR_TO_CTX: 7256 /* in case the function doesn't know how to access the context, 7257 * (because we are in a program of type SYSCALL for example), we 7258 * can not statically check its size. 7259 * Dynamically check it now. 7260 */ 7261 if (!env->ops->convert_ctx_access) { 7262 enum bpf_access_type atype = meta && meta->raw_mode ? BPF_WRITE : BPF_READ; 7263 int offset = access_size - 1; 7264 7265 /* Allow zero-byte read from PTR_TO_CTX */ 7266 if (access_size == 0) 7267 return zero_size_allowed ? 0 : -EACCES; 7268 7269 return check_mem_access(env, env->insn_idx, regno, offset, BPF_B, 7270 atype, -1, false, false); 7271 } 7272 7273 fallthrough; 7274 default: /* scalar_value or invalid ptr */ 7275 /* Allow zero-byte read from NULL, regardless of pointer type */ 7276 if (zero_size_allowed && access_size == 0 && 7277 register_is_null(reg)) 7278 return 0; 7279 7280 verbose(env, "R%d type=%s ", regno, 7281 reg_type_str(env, reg->type)); 7282 verbose(env, "expected=%s\n", reg_type_str(env, PTR_TO_STACK)); 7283 return -EACCES; 7284 } 7285 } 7286 7287 static int check_mem_size_reg(struct bpf_verifier_env *env, 7288 struct bpf_reg_state *reg, u32 regno, 7289 bool zero_size_allowed, 7290 struct bpf_call_arg_meta *meta) 7291 { 7292 int err; 7293 7294 /* This is used to refine r0 return value bounds for helpers 7295 * that enforce this value as an upper bound on return values. 7296 * See do_refine_retval_range() for helpers that can refine 7297 * the return value. C type of helper is u32 so we pull register 7298 * bound from umax_value however, if negative verifier errors 7299 * out. Only upper bounds can be learned because retval is an 7300 * int type and negative retvals are allowed. 7301 */ 7302 meta->msize_max_value = reg->umax_value; 7303 7304 /* The register is SCALAR_VALUE; the access check 7305 * happens using its boundaries. 7306 */ 7307 if (!tnum_is_const(reg->var_off)) 7308 /* For unprivileged variable accesses, disable raw 7309 * mode so that the program is required to 7310 * initialize all the memory that the helper could 7311 * just partially fill up. 7312 */ 7313 meta = NULL; 7314 7315 if (reg->smin_value < 0) { 7316 verbose(env, "R%d min value is negative, either use unsigned or 'var &= const'\n", 7317 regno); 7318 return -EACCES; 7319 } 7320 7321 if (reg->umin_value == 0) { 7322 err = check_helper_mem_access(env, regno - 1, 0, 7323 zero_size_allowed, 7324 meta); 7325 if (err) 7326 return err; 7327 } 7328 7329 if (reg->umax_value >= BPF_MAX_VAR_SIZ) { 7330 verbose(env, "R%d unbounded memory access, use 'var &= const' or 'if (var < const)'\n", 7331 regno); 7332 return -EACCES; 7333 } 7334 err = check_helper_mem_access(env, regno - 1, 7335 reg->umax_value, 7336 zero_size_allowed, meta); 7337 if (!err) 7338 err = mark_chain_precision(env, regno); 7339 return err; 7340 } 7341 7342 int check_mem_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg, 7343 u32 regno, u32 mem_size) 7344 { 7345 bool may_be_null = type_may_be_null(reg->type); 7346 struct bpf_reg_state saved_reg; 7347 struct bpf_call_arg_meta meta; 7348 int err; 7349 7350 if (register_is_null(reg)) 7351 return 0; 7352 7353 memset(&meta, 0, sizeof(meta)); 7354 /* Assuming that the register contains a value check if the memory 7355 * access is safe. Temporarily save and restore the register's state as 7356 * the conversion shouldn't be visible to a caller. 7357 */ 7358 if (may_be_null) { 7359 saved_reg = *reg; 7360 mark_ptr_not_null_reg(reg); 7361 } 7362 7363 err = check_helper_mem_access(env, regno, mem_size, true, &meta); 7364 /* Check access for BPF_WRITE */ 7365 meta.raw_mode = true; 7366 err = err ?: check_helper_mem_access(env, regno, mem_size, true, &meta); 7367 7368 if (may_be_null) 7369 *reg = saved_reg; 7370 7371 return err; 7372 } 7373 7374 static int check_kfunc_mem_size_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg, 7375 u32 regno) 7376 { 7377 struct bpf_reg_state *mem_reg = &cur_regs(env)[regno - 1]; 7378 bool may_be_null = type_may_be_null(mem_reg->type); 7379 struct bpf_reg_state saved_reg; 7380 struct bpf_call_arg_meta meta; 7381 int err; 7382 7383 WARN_ON_ONCE(regno < BPF_REG_2 || regno > BPF_REG_5); 7384 7385 memset(&meta, 0, sizeof(meta)); 7386 7387 if (may_be_null) { 7388 saved_reg = *mem_reg; 7389 mark_ptr_not_null_reg(mem_reg); 7390 } 7391 7392 err = check_mem_size_reg(env, reg, regno, true, &meta); 7393 /* Check access for BPF_WRITE */ 7394 meta.raw_mode = true; 7395 err = err ?: check_mem_size_reg(env, reg, regno, true, &meta); 7396 7397 if (may_be_null) 7398 *mem_reg = saved_reg; 7399 return err; 7400 } 7401 7402 /* Implementation details: 7403 * bpf_map_lookup returns PTR_TO_MAP_VALUE_OR_NULL. 7404 * bpf_obj_new returns PTR_TO_BTF_ID | MEM_ALLOC | PTR_MAYBE_NULL. 7405 * Two bpf_map_lookups (even with the same key) will have different reg->id. 7406 * Two separate bpf_obj_new will also have different reg->id. 7407 * For traditional PTR_TO_MAP_VALUE or PTR_TO_BTF_ID | MEM_ALLOC, the verifier 7408 * clears reg->id after value_or_null->value transition, since the verifier only 7409 * cares about the range of access to valid map value pointer and doesn't care 7410 * about actual address of the map element. 7411 * For maps with 'struct bpf_spin_lock' inside map value the verifier keeps 7412 * reg->id > 0 after value_or_null->value transition. By doing so 7413 * two bpf_map_lookups will be considered two different pointers that 7414 * point to different bpf_spin_locks. Likewise for pointers to allocated objects 7415 * returned from bpf_obj_new. 7416 * The verifier allows taking only one bpf_spin_lock at a time to avoid 7417 * dead-locks. 7418 * Since only one bpf_spin_lock is allowed the checks are simpler than 7419 * reg_is_refcounted() logic. The verifier needs to remember only 7420 * one spin_lock instead of array of acquired_refs. 7421 * cur_state->active_lock remembers which map value element or allocated 7422 * object got locked and clears it after bpf_spin_unlock. 7423 */ 7424 static int process_spin_lock(struct bpf_verifier_env *env, int regno, 7425 bool is_lock) 7426 { 7427 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno]; 7428 struct bpf_verifier_state *cur = env->cur_state; 7429 bool is_const = tnum_is_const(reg->var_off); 7430 u64 val = reg->var_off.value; 7431 struct bpf_map *map = NULL; 7432 struct btf *btf = NULL; 7433 struct btf_record *rec; 7434 7435 if (!is_const) { 7436 verbose(env, 7437 "R%d doesn't have constant offset. bpf_spin_lock has to be at the constant offset\n", 7438 regno); 7439 return -EINVAL; 7440 } 7441 if (reg->type == PTR_TO_MAP_VALUE) { 7442 map = reg->map_ptr; 7443 if (!map->btf) { 7444 verbose(env, 7445 "map '%s' has to have BTF in order to use bpf_spin_lock\n", 7446 map->name); 7447 return -EINVAL; 7448 } 7449 } else { 7450 btf = reg->btf; 7451 } 7452 7453 rec = reg_btf_record(reg); 7454 if (!btf_record_has_field(rec, BPF_SPIN_LOCK)) { 7455 verbose(env, "%s '%s' has no valid bpf_spin_lock\n", map ? "map" : "local", 7456 map ? map->name : "kptr"); 7457 return -EINVAL; 7458 } 7459 if (rec->spin_lock_off != val + reg->off) { 7460 verbose(env, "off %lld doesn't point to 'struct bpf_spin_lock' that is at %d\n", 7461 val + reg->off, rec->spin_lock_off); 7462 return -EINVAL; 7463 } 7464 if (is_lock) { 7465 if (cur->active_lock.ptr) { 7466 verbose(env, 7467 "Locking two bpf_spin_locks are not allowed\n"); 7468 return -EINVAL; 7469 } 7470 if (map) 7471 cur->active_lock.ptr = map; 7472 else 7473 cur->active_lock.ptr = btf; 7474 cur->active_lock.id = reg->id; 7475 } else { 7476 void *ptr; 7477 7478 if (map) 7479 ptr = map; 7480 else 7481 ptr = btf; 7482 7483 if (!cur->active_lock.ptr) { 7484 verbose(env, "bpf_spin_unlock without taking a lock\n"); 7485 return -EINVAL; 7486 } 7487 if (cur->active_lock.ptr != ptr || 7488 cur->active_lock.id != reg->id) { 7489 verbose(env, "bpf_spin_unlock of different lock\n"); 7490 return -EINVAL; 7491 } 7492 7493 invalidate_non_owning_refs(env); 7494 7495 cur->active_lock.ptr = NULL; 7496 cur->active_lock.id = 0; 7497 } 7498 return 0; 7499 } 7500 7501 static int process_timer_func(struct bpf_verifier_env *env, int regno, 7502 struct bpf_call_arg_meta *meta) 7503 { 7504 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno]; 7505 bool is_const = tnum_is_const(reg->var_off); 7506 struct bpf_map *map = reg->map_ptr; 7507 u64 val = reg->var_off.value; 7508 7509 if (!is_const) { 7510 verbose(env, 7511 "R%d doesn't have constant offset. bpf_timer has to be at the constant offset\n", 7512 regno); 7513 return -EINVAL; 7514 } 7515 if (!map->btf) { 7516 verbose(env, "map '%s' has to have BTF in order to use bpf_timer\n", 7517 map->name); 7518 return -EINVAL; 7519 } 7520 if (!btf_record_has_field(map->record, BPF_TIMER)) { 7521 verbose(env, "map '%s' has no valid bpf_timer\n", map->name); 7522 return -EINVAL; 7523 } 7524 if (map->record->timer_off != val + reg->off) { 7525 verbose(env, "off %lld doesn't point to 'struct bpf_timer' that is at %d\n", 7526 val + reg->off, map->record->timer_off); 7527 return -EINVAL; 7528 } 7529 if (meta->map_ptr) { 7530 verbose(env, "verifier bug. Two map pointers in a timer helper\n"); 7531 return -EFAULT; 7532 } 7533 meta->map_uid = reg->map_uid; 7534 meta->map_ptr = map; 7535 return 0; 7536 } 7537 7538 static int process_kptr_func(struct bpf_verifier_env *env, int regno, 7539 struct bpf_call_arg_meta *meta) 7540 { 7541 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno]; 7542 struct bpf_map *map_ptr = reg->map_ptr; 7543 struct btf_field *kptr_field; 7544 u32 kptr_off; 7545 7546 if (!tnum_is_const(reg->var_off)) { 7547 verbose(env, 7548 "R%d doesn't have constant offset. kptr has to be at the constant offset\n", 7549 regno); 7550 return -EINVAL; 7551 } 7552 if (!map_ptr->btf) { 7553 verbose(env, "map '%s' has to have BTF in order to use bpf_kptr_xchg\n", 7554 map_ptr->name); 7555 return -EINVAL; 7556 } 7557 if (!btf_record_has_field(map_ptr->record, BPF_KPTR)) { 7558 verbose(env, "map '%s' has no valid kptr\n", map_ptr->name); 7559 return -EINVAL; 7560 } 7561 7562 meta->map_ptr = map_ptr; 7563 kptr_off = reg->off + reg->var_off.value; 7564 kptr_field = btf_record_find(map_ptr->record, kptr_off, BPF_KPTR); 7565 if (!kptr_field) { 7566 verbose(env, "off=%d doesn't point to kptr\n", kptr_off); 7567 return -EACCES; 7568 } 7569 if (kptr_field->type != BPF_KPTR_REF) { 7570 verbose(env, "off=%d kptr isn't referenced kptr\n", kptr_off); 7571 return -EACCES; 7572 } 7573 meta->kptr_field = kptr_field; 7574 return 0; 7575 } 7576 7577 /* There are two register types representing a bpf_dynptr, one is PTR_TO_STACK 7578 * which points to a stack slot, and the other is CONST_PTR_TO_DYNPTR. 7579 * 7580 * In both cases we deal with the first 8 bytes, but need to mark the next 8 7581 * bytes as STACK_DYNPTR in case of PTR_TO_STACK. In case of 7582 * CONST_PTR_TO_DYNPTR, we are guaranteed to get the beginning of the object. 7583 * 7584 * Mutability of bpf_dynptr is at two levels, one is at the level of struct 7585 * bpf_dynptr itself, i.e. whether the helper is receiving a pointer to struct 7586 * bpf_dynptr or pointer to const struct bpf_dynptr. In the former case, it can 7587 * mutate the view of the dynptr and also possibly destroy it. In the latter 7588 * case, it cannot mutate the bpf_dynptr itself but it can still mutate the 7589 * memory that dynptr points to. 7590 * 7591 * The verifier will keep track both levels of mutation (bpf_dynptr's in 7592 * reg->type and the memory's in reg->dynptr.type), but there is no support for 7593 * readonly dynptr view yet, hence only the first case is tracked and checked. 7594 * 7595 * This is consistent with how C applies the const modifier to a struct object, 7596 * where the pointer itself inside bpf_dynptr becomes const but not what it 7597 * points to. 7598 * 7599 * Helpers which do not mutate the bpf_dynptr set MEM_RDONLY in their argument 7600 * type, and declare it as 'const struct bpf_dynptr *' in their prototype. 7601 */ 7602 static int process_dynptr_func(struct bpf_verifier_env *env, int regno, int insn_idx, 7603 enum bpf_arg_type arg_type, int clone_ref_obj_id) 7604 { 7605 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno]; 7606 int err; 7607 7608 /* MEM_UNINIT and MEM_RDONLY are exclusive, when applied to an 7609 * ARG_PTR_TO_DYNPTR (or ARG_PTR_TO_DYNPTR | DYNPTR_TYPE_*): 7610 */ 7611 if ((arg_type & (MEM_UNINIT | MEM_RDONLY)) == (MEM_UNINIT | MEM_RDONLY)) { 7612 verbose(env, "verifier internal error: misconfigured dynptr helper type flags\n"); 7613 return -EFAULT; 7614 } 7615 7616 /* MEM_UNINIT - Points to memory that is an appropriate candidate for 7617 * constructing a mutable bpf_dynptr object. 7618 * 7619 * Currently, this is only possible with PTR_TO_STACK 7620 * pointing to a region of at least 16 bytes which doesn't 7621 * contain an existing bpf_dynptr. 7622 * 7623 * MEM_RDONLY - Points to a initialized bpf_dynptr that will not be 7624 * mutated or destroyed. However, the memory it points to 7625 * may be mutated. 7626 * 7627 * None - Points to a initialized dynptr that can be mutated and 7628 * destroyed, including mutation of the memory it points 7629 * to. 7630 */ 7631 if (arg_type & MEM_UNINIT) { 7632 int i; 7633 7634 if (!is_dynptr_reg_valid_uninit(env, reg)) { 7635 verbose(env, "Dynptr has to be an uninitialized dynptr\n"); 7636 return -EINVAL; 7637 } 7638 7639 /* we write BPF_DW bits (8 bytes) at a time */ 7640 for (i = 0; i < BPF_DYNPTR_SIZE; i += 8) { 7641 err = check_mem_access(env, insn_idx, regno, 7642 i, BPF_DW, BPF_WRITE, -1, false, false); 7643 if (err) 7644 return err; 7645 } 7646 7647 err = mark_stack_slots_dynptr(env, reg, arg_type, insn_idx, clone_ref_obj_id); 7648 } else /* MEM_RDONLY and None case from above */ { 7649 /* For the reg->type == PTR_TO_STACK case, bpf_dynptr is never const */ 7650 if (reg->type == CONST_PTR_TO_DYNPTR && !(arg_type & MEM_RDONLY)) { 7651 verbose(env, "cannot pass pointer to const bpf_dynptr, the helper mutates it\n"); 7652 return -EINVAL; 7653 } 7654 7655 if (!is_dynptr_reg_valid_init(env, reg)) { 7656 verbose(env, 7657 "Expected an initialized dynptr as arg #%d\n", 7658 regno); 7659 return -EINVAL; 7660 } 7661 7662 /* Fold modifiers (in this case, MEM_RDONLY) when checking expected type */ 7663 if (!is_dynptr_type_expected(env, reg, arg_type & ~MEM_RDONLY)) { 7664 verbose(env, 7665 "Expected a dynptr of type %s as arg #%d\n", 7666 dynptr_type_str(arg_to_dynptr_type(arg_type)), regno); 7667 return -EINVAL; 7668 } 7669 7670 err = mark_dynptr_read(env, reg); 7671 } 7672 return err; 7673 } 7674 7675 static u32 iter_ref_obj_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg, int spi) 7676 { 7677 struct bpf_func_state *state = func(env, reg); 7678 7679 return state->stack[spi].spilled_ptr.ref_obj_id; 7680 } 7681 7682 static bool is_iter_kfunc(struct bpf_kfunc_call_arg_meta *meta) 7683 { 7684 return meta->kfunc_flags & (KF_ITER_NEW | KF_ITER_NEXT | KF_ITER_DESTROY); 7685 } 7686 7687 static bool is_iter_new_kfunc(struct bpf_kfunc_call_arg_meta *meta) 7688 { 7689 return meta->kfunc_flags & KF_ITER_NEW; 7690 } 7691 7692 static bool is_iter_next_kfunc(struct bpf_kfunc_call_arg_meta *meta) 7693 { 7694 return meta->kfunc_flags & KF_ITER_NEXT; 7695 } 7696 7697 static bool is_iter_destroy_kfunc(struct bpf_kfunc_call_arg_meta *meta) 7698 { 7699 return meta->kfunc_flags & KF_ITER_DESTROY; 7700 } 7701 7702 static bool is_kfunc_arg_iter(struct bpf_kfunc_call_arg_meta *meta, int arg) 7703 { 7704 /* btf_check_iter_kfuncs() guarantees that first argument of any iter 7705 * kfunc is iter state pointer 7706 */ 7707 return arg == 0 && is_iter_kfunc(meta); 7708 } 7709 7710 static int process_iter_arg(struct bpf_verifier_env *env, int regno, int insn_idx, 7711 struct bpf_kfunc_call_arg_meta *meta) 7712 { 7713 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno]; 7714 const struct btf_type *t; 7715 const struct btf_param *arg; 7716 int spi, err, i, nr_slots; 7717 u32 btf_id; 7718 7719 /* btf_check_iter_kfuncs() ensures we don't need to validate anything here */ 7720 arg = &btf_params(meta->func_proto)[0]; 7721 t = btf_type_skip_modifiers(meta->btf, arg->type, NULL); /* PTR */ 7722 t = btf_type_skip_modifiers(meta->btf, t->type, &btf_id); /* STRUCT */ 7723 nr_slots = t->size / BPF_REG_SIZE; 7724 7725 if (is_iter_new_kfunc(meta)) { 7726 /* bpf_iter_<type>_new() expects pointer to uninit iter state */ 7727 if (!is_iter_reg_valid_uninit(env, reg, nr_slots)) { 7728 verbose(env, "expected uninitialized iter_%s as arg #%d\n", 7729 iter_type_str(meta->btf, btf_id), regno); 7730 return -EINVAL; 7731 } 7732 7733 for (i = 0; i < nr_slots * 8; i += BPF_REG_SIZE) { 7734 err = check_mem_access(env, insn_idx, regno, 7735 i, BPF_DW, BPF_WRITE, -1, false, false); 7736 if (err) 7737 return err; 7738 } 7739 7740 err = mark_stack_slots_iter(env, reg, insn_idx, meta->btf, btf_id, nr_slots); 7741 if (err) 7742 return err; 7743 } else { 7744 /* iter_next() or iter_destroy() expect initialized iter state*/ 7745 if (!is_iter_reg_valid_init(env, reg, meta->btf, btf_id, nr_slots)) { 7746 verbose(env, "expected an initialized iter_%s as arg #%d\n", 7747 iter_type_str(meta->btf, btf_id), regno); 7748 return -EINVAL; 7749 } 7750 7751 spi = iter_get_spi(env, reg, nr_slots); 7752 if (spi < 0) 7753 return spi; 7754 7755 err = mark_iter_read(env, reg, spi, nr_slots); 7756 if (err) 7757 return err; 7758 7759 /* remember meta->iter info for process_iter_next_call() */ 7760 meta->iter.spi = spi; 7761 meta->iter.frameno = reg->frameno; 7762 meta->ref_obj_id = iter_ref_obj_id(env, reg, spi); 7763 7764 if (is_iter_destroy_kfunc(meta)) { 7765 err = unmark_stack_slots_iter(env, reg, nr_slots); 7766 if (err) 7767 return err; 7768 } 7769 } 7770 7771 return 0; 7772 } 7773 7774 /* Look for a previous loop entry at insn_idx: nearest parent state 7775 * stopped at insn_idx with callsites matching those in cur->frame. 7776 */ 7777 static struct bpf_verifier_state *find_prev_entry(struct bpf_verifier_env *env, 7778 struct bpf_verifier_state *cur, 7779 int insn_idx) 7780 { 7781 struct bpf_verifier_state_list *sl; 7782 struct bpf_verifier_state *st; 7783 7784 /* Explored states are pushed in stack order, most recent states come first */ 7785 sl = *explored_state(env, insn_idx); 7786 for (; sl; sl = sl->next) { 7787 /* If st->branches != 0 state is a part of current DFS verification path, 7788 * hence cur & st for a loop. 7789 */ 7790 st = &sl->state; 7791 if (st->insn_idx == insn_idx && st->branches && same_callsites(st, cur) && 7792 st->dfs_depth < cur->dfs_depth) 7793 return st; 7794 } 7795 7796 return NULL; 7797 } 7798 7799 static void reset_idmap_scratch(struct bpf_verifier_env *env); 7800 static bool regs_exact(const struct bpf_reg_state *rold, 7801 const struct bpf_reg_state *rcur, 7802 struct bpf_idmap *idmap); 7803 7804 static void maybe_widen_reg(struct bpf_verifier_env *env, 7805 struct bpf_reg_state *rold, struct bpf_reg_state *rcur, 7806 struct bpf_idmap *idmap) 7807 { 7808 if (rold->type != SCALAR_VALUE) 7809 return; 7810 if (rold->type != rcur->type) 7811 return; 7812 if (rold->precise || rcur->precise || regs_exact(rold, rcur, idmap)) 7813 return; 7814 __mark_reg_unknown(env, rcur); 7815 } 7816 7817 static int widen_imprecise_scalars(struct bpf_verifier_env *env, 7818 struct bpf_verifier_state *old, 7819 struct bpf_verifier_state *cur) 7820 { 7821 struct bpf_func_state *fold, *fcur; 7822 int i, fr; 7823 7824 reset_idmap_scratch(env); 7825 for (fr = old->curframe; fr >= 0; fr--) { 7826 fold = old->frame[fr]; 7827 fcur = cur->frame[fr]; 7828 7829 for (i = 0; i < MAX_BPF_REG; i++) 7830 maybe_widen_reg(env, 7831 &fold->regs[i], 7832 &fcur->regs[i], 7833 &env->idmap_scratch); 7834 7835 for (i = 0; i < fold->allocated_stack / BPF_REG_SIZE; i++) { 7836 if (!is_spilled_reg(&fold->stack[i]) || 7837 !is_spilled_reg(&fcur->stack[i])) 7838 continue; 7839 7840 maybe_widen_reg(env, 7841 &fold->stack[i].spilled_ptr, 7842 &fcur->stack[i].spilled_ptr, 7843 &env->idmap_scratch); 7844 } 7845 } 7846 return 0; 7847 } 7848 7849 /* process_iter_next_call() is called when verifier gets to iterator's next 7850 * "method" (e.g., bpf_iter_num_next() for numbers iterator) call. We'll refer 7851 * to it as just "iter_next()" in comments below. 7852 * 7853 * BPF verifier relies on a crucial contract for any iter_next() 7854 * implementation: it should *eventually* return NULL, and once that happens 7855 * it should keep returning NULL. That is, once iterator exhausts elements to 7856 * iterate, it should never reset or spuriously return new elements. 7857 * 7858 * With the assumption of such contract, process_iter_next_call() simulates 7859 * a fork in the verifier state to validate loop logic correctness and safety 7860 * without having to simulate infinite amount of iterations. 7861 * 7862 * In current state, we first assume that iter_next() returned NULL and 7863 * iterator state is set to DRAINED (BPF_ITER_STATE_DRAINED). In such 7864 * conditions we should not form an infinite loop and should eventually reach 7865 * exit. 7866 * 7867 * Besides that, we also fork current state and enqueue it for later 7868 * verification. In a forked state we keep iterator state as ACTIVE 7869 * (BPF_ITER_STATE_ACTIVE) and assume non-NULL return from iter_next(). We 7870 * also bump iteration depth to prevent erroneous infinite loop detection 7871 * later on (see iter_active_depths_differ() comment for details). In this 7872 * state we assume that we'll eventually loop back to another iter_next() 7873 * calls (it could be in exactly same location or in some other instruction, 7874 * it doesn't matter, we don't make any unnecessary assumptions about this, 7875 * everything revolves around iterator state in a stack slot, not which 7876 * instruction is calling iter_next()). When that happens, we either will come 7877 * to iter_next() with equivalent state and can conclude that next iteration 7878 * will proceed in exactly the same way as we just verified, so it's safe to 7879 * assume that loop converges. If not, we'll go on another iteration 7880 * simulation with a different input state, until all possible starting states 7881 * are validated or we reach maximum number of instructions limit. 7882 * 7883 * This way, we will either exhaustively discover all possible input states 7884 * that iterator loop can start with and eventually will converge, or we'll 7885 * effectively regress into bounded loop simulation logic and either reach 7886 * maximum number of instructions if loop is not provably convergent, or there 7887 * is some statically known limit on number of iterations (e.g., if there is 7888 * an explicit `if n > 100 then break;` statement somewhere in the loop). 7889 * 7890 * Iteration convergence logic in is_state_visited() relies on exact 7891 * states comparison, which ignores read and precision marks. 7892 * This is necessary because read and precision marks are not finalized 7893 * while in the loop. Exact comparison might preclude convergence for 7894 * simple programs like below: 7895 * 7896 * i = 0; 7897 * while(iter_next(&it)) 7898 * i++; 7899 * 7900 * At each iteration step i++ would produce a new distinct state and 7901 * eventually instruction processing limit would be reached. 7902 * 7903 * To avoid such behavior speculatively forget (widen) range for 7904 * imprecise scalar registers, if those registers were not precise at the 7905 * end of the previous iteration and do not match exactly. 7906 * 7907 * This is a conservative heuristic that allows to verify wide range of programs, 7908 * however it precludes verification of programs that conjure an 7909 * imprecise value on the first loop iteration and use it as precise on a second. 7910 * For example, the following safe program would fail to verify: 7911 * 7912 * struct bpf_num_iter it; 7913 * int arr[10]; 7914 * int i = 0, a = 0; 7915 * bpf_iter_num_new(&it, 0, 10); 7916 * while (bpf_iter_num_next(&it)) { 7917 * if (a == 0) { 7918 * a = 1; 7919 * i = 7; // Because i changed verifier would forget 7920 * // it's range on second loop entry. 7921 * } else { 7922 * arr[i] = 42; // This would fail to verify. 7923 * } 7924 * } 7925 * bpf_iter_num_destroy(&it); 7926 */ 7927 static int process_iter_next_call(struct bpf_verifier_env *env, int insn_idx, 7928 struct bpf_kfunc_call_arg_meta *meta) 7929 { 7930 struct bpf_verifier_state *cur_st = env->cur_state, *queued_st, *prev_st; 7931 struct bpf_func_state *cur_fr = cur_st->frame[cur_st->curframe], *queued_fr; 7932 struct bpf_reg_state *cur_iter, *queued_iter; 7933 int iter_frameno = meta->iter.frameno; 7934 int iter_spi = meta->iter.spi; 7935 7936 BTF_TYPE_EMIT(struct bpf_iter); 7937 7938 cur_iter = &env->cur_state->frame[iter_frameno]->stack[iter_spi].spilled_ptr; 7939 7940 if (cur_iter->iter.state != BPF_ITER_STATE_ACTIVE && 7941 cur_iter->iter.state != BPF_ITER_STATE_DRAINED) { 7942 verbose(env, "verifier internal error: unexpected iterator state %d (%s)\n", 7943 cur_iter->iter.state, iter_state_str(cur_iter->iter.state)); 7944 return -EFAULT; 7945 } 7946 7947 if (cur_iter->iter.state == BPF_ITER_STATE_ACTIVE) { 7948 /* Because iter_next() call is a checkpoint is_state_visitied() 7949 * should guarantee parent state with same call sites and insn_idx. 7950 */ 7951 if (!cur_st->parent || cur_st->parent->insn_idx != insn_idx || 7952 !same_callsites(cur_st->parent, cur_st)) { 7953 verbose(env, "bug: bad parent state for iter next call"); 7954 return -EFAULT; 7955 } 7956 /* Note cur_st->parent in the call below, it is necessary to skip 7957 * checkpoint created for cur_st by is_state_visited() 7958 * right at this instruction. 7959 */ 7960 prev_st = find_prev_entry(env, cur_st->parent, insn_idx); 7961 /* branch out active iter state */ 7962 queued_st = push_stack(env, insn_idx + 1, insn_idx, false); 7963 if (!queued_st) 7964 return -ENOMEM; 7965 7966 queued_iter = &queued_st->frame[iter_frameno]->stack[iter_spi].spilled_ptr; 7967 queued_iter->iter.state = BPF_ITER_STATE_ACTIVE; 7968 queued_iter->iter.depth++; 7969 if (prev_st) 7970 widen_imprecise_scalars(env, prev_st, queued_st); 7971 7972 queued_fr = queued_st->frame[queued_st->curframe]; 7973 mark_ptr_not_null_reg(&queued_fr->regs[BPF_REG_0]); 7974 } 7975 7976 /* switch to DRAINED state, but keep the depth unchanged */ 7977 /* mark current iter state as drained and assume returned NULL */ 7978 cur_iter->iter.state = BPF_ITER_STATE_DRAINED; 7979 __mark_reg_const_zero(&cur_fr->regs[BPF_REG_0]); 7980 7981 return 0; 7982 } 7983 7984 static bool arg_type_is_mem_size(enum bpf_arg_type type) 7985 { 7986 return type == ARG_CONST_SIZE || 7987 type == ARG_CONST_SIZE_OR_ZERO; 7988 } 7989 7990 static bool arg_type_is_release(enum bpf_arg_type type) 7991 { 7992 return type & OBJ_RELEASE; 7993 } 7994 7995 static bool arg_type_is_dynptr(enum bpf_arg_type type) 7996 { 7997 return base_type(type) == ARG_PTR_TO_DYNPTR; 7998 } 7999 8000 static int resolve_map_arg_type(struct bpf_verifier_env *env, 8001 const struct bpf_call_arg_meta *meta, 8002 enum bpf_arg_type *arg_type) 8003 { 8004 if (!meta->map_ptr) { 8005 /* kernel subsystem misconfigured verifier */ 8006 verbose(env, "invalid map_ptr to access map->type\n"); 8007 return -EACCES; 8008 } 8009 8010 switch (meta->map_ptr->map_type) { 8011 case BPF_MAP_TYPE_SOCKMAP: 8012 case BPF_MAP_TYPE_SOCKHASH: 8013 if (*arg_type == ARG_PTR_TO_MAP_VALUE) { 8014 *arg_type = ARG_PTR_TO_BTF_ID_SOCK_COMMON; 8015 } else { 8016 verbose(env, "invalid arg_type for sockmap/sockhash\n"); 8017 return -EINVAL; 8018 } 8019 break; 8020 case BPF_MAP_TYPE_BLOOM_FILTER: 8021 if (meta->func_id == BPF_FUNC_map_peek_elem) 8022 *arg_type = ARG_PTR_TO_MAP_VALUE; 8023 break; 8024 default: 8025 break; 8026 } 8027 return 0; 8028 } 8029 8030 struct bpf_reg_types { 8031 const enum bpf_reg_type types[10]; 8032 u32 *btf_id; 8033 }; 8034 8035 static const struct bpf_reg_types sock_types = { 8036 .types = { 8037 PTR_TO_SOCK_COMMON, 8038 PTR_TO_SOCKET, 8039 PTR_TO_TCP_SOCK, 8040 PTR_TO_XDP_SOCK, 8041 }, 8042 }; 8043 8044 #ifdef CONFIG_NET 8045 static const struct bpf_reg_types btf_id_sock_common_types = { 8046 .types = { 8047 PTR_TO_SOCK_COMMON, 8048 PTR_TO_SOCKET, 8049 PTR_TO_TCP_SOCK, 8050 PTR_TO_XDP_SOCK, 8051 PTR_TO_BTF_ID, 8052 PTR_TO_BTF_ID | PTR_TRUSTED, 8053 }, 8054 .btf_id = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON], 8055 }; 8056 #endif 8057 8058 static const struct bpf_reg_types mem_types = { 8059 .types = { 8060 PTR_TO_STACK, 8061 PTR_TO_PACKET, 8062 PTR_TO_PACKET_META, 8063 PTR_TO_MAP_KEY, 8064 PTR_TO_MAP_VALUE, 8065 PTR_TO_MEM, 8066 PTR_TO_MEM | MEM_RINGBUF, 8067 PTR_TO_BUF, 8068 PTR_TO_BTF_ID | PTR_TRUSTED, 8069 }, 8070 }; 8071 8072 static const struct bpf_reg_types spin_lock_types = { 8073 .types = { 8074 PTR_TO_MAP_VALUE, 8075 PTR_TO_BTF_ID | MEM_ALLOC, 8076 } 8077 }; 8078 8079 static const struct bpf_reg_types fullsock_types = { .types = { PTR_TO_SOCKET } }; 8080 static const struct bpf_reg_types scalar_types = { .types = { SCALAR_VALUE } }; 8081 static const struct bpf_reg_types context_types = { .types = { PTR_TO_CTX } }; 8082 static const struct bpf_reg_types ringbuf_mem_types = { .types = { PTR_TO_MEM | MEM_RINGBUF } }; 8083 static const struct bpf_reg_types const_map_ptr_types = { .types = { CONST_PTR_TO_MAP } }; 8084 static const struct bpf_reg_types btf_ptr_types = { 8085 .types = { 8086 PTR_TO_BTF_ID, 8087 PTR_TO_BTF_ID | PTR_TRUSTED, 8088 PTR_TO_BTF_ID | MEM_RCU, 8089 }, 8090 }; 8091 static const struct bpf_reg_types percpu_btf_ptr_types = { 8092 .types = { 8093 PTR_TO_BTF_ID | MEM_PERCPU, 8094 PTR_TO_BTF_ID | MEM_PERCPU | PTR_TRUSTED, 8095 } 8096 }; 8097 static const struct bpf_reg_types func_ptr_types = { .types = { PTR_TO_FUNC } }; 8098 static const struct bpf_reg_types stack_ptr_types = { .types = { PTR_TO_STACK } }; 8099 static const struct bpf_reg_types const_str_ptr_types = { .types = { PTR_TO_MAP_VALUE } }; 8100 static const struct bpf_reg_types timer_types = { .types = { PTR_TO_MAP_VALUE } }; 8101 static const struct bpf_reg_types kptr_types = { .types = { PTR_TO_MAP_VALUE } }; 8102 static const struct bpf_reg_types dynptr_types = { 8103 .types = { 8104 PTR_TO_STACK, 8105 CONST_PTR_TO_DYNPTR, 8106 } 8107 }; 8108 8109 static const struct bpf_reg_types *compatible_reg_types[__BPF_ARG_TYPE_MAX] = { 8110 [ARG_PTR_TO_MAP_KEY] = &mem_types, 8111 [ARG_PTR_TO_MAP_VALUE] = &mem_types, 8112 [ARG_CONST_SIZE] = &scalar_types, 8113 [ARG_CONST_SIZE_OR_ZERO] = &scalar_types, 8114 [ARG_CONST_ALLOC_SIZE_OR_ZERO] = &scalar_types, 8115 [ARG_CONST_MAP_PTR] = &const_map_ptr_types, 8116 [ARG_PTR_TO_CTX] = &context_types, 8117 [ARG_PTR_TO_SOCK_COMMON] = &sock_types, 8118 #ifdef CONFIG_NET 8119 [ARG_PTR_TO_BTF_ID_SOCK_COMMON] = &btf_id_sock_common_types, 8120 #endif 8121 [ARG_PTR_TO_SOCKET] = &fullsock_types, 8122 [ARG_PTR_TO_BTF_ID] = &btf_ptr_types, 8123 [ARG_PTR_TO_SPIN_LOCK] = &spin_lock_types, 8124 [ARG_PTR_TO_MEM] = &mem_types, 8125 [ARG_PTR_TO_RINGBUF_MEM] = &ringbuf_mem_types, 8126 [ARG_PTR_TO_PERCPU_BTF_ID] = &percpu_btf_ptr_types, 8127 [ARG_PTR_TO_FUNC] = &func_ptr_types, 8128 [ARG_PTR_TO_STACK] = &stack_ptr_types, 8129 [ARG_PTR_TO_CONST_STR] = &const_str_ptr_types, 8130 [ARG_PTR_TO_TIMER] = &timer_types, 8131 [ARG_PTR_TO_KPTR] = &kptr_types, 8132 [ARG_PTR_TO_DYNPTR] = &dynptr_types, 8133 }; 8134 8135 static int check_reg_type(struct bpf_verifier_env *env, u32 regno, 8136 enum bpf_arg_type arg_type, 8137 const u32 *arg_btf_id, 8138 struct bpf_call_arg_meta *meta) 8139 { 8140 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno]; 8141 enum bpf_reg_type expected, type = reg->type; 8142 const struct bpf_reg_types *compatible; 8143 int i, j; 8144 8145 compatible = compatible_reg_types[base_type(arg_type)]; 8146 if (!compatible) { 8147 verbose(env, "verifier internal error: unsupported arg type %d\n", arg_type); 8148 return -EFAULT; 8149 } 8150 8151 /* ARG_PTR_TO_MEM + RDONLY is compatible with PTR_TO_MEM and PTR_TO_MEM + RDONLY, 8152 * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM and NOT with PTR_TO_MEM + RDONLY 8153 * 8154 * Same for MAYBE_NULL: 8155 * 8156 * ARG_PTR_TO_MEM + MAYBE_NULL is compatible with PTR_TO_MEM and PTR_TO_MEM + MAYBE_NULL, 8157 * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM but NOT with PTR_TO_MEM + MAYBE_NULL 8158 * 8159 * ARG_PTR_TO_MEM is compatible with PTR_TO_MEM that is tagged with a dynptr type. 8160 * 8161 * Therefore we fold these flags depending on the arg_type before comparison. 8162 */ 8163 if (arg_type & MEM_RDONLY) 8164 type &= ~MEM_RDONLY; 8165 if (arg_type & PTR_MAYBE_NULL) 8166 type &= ~PTR_MAYBE_NULL; 8167 if (base_type(arg_type) == ARG_PTR_TO_MEM) 8168 type &= ~DYNPTR_TYPE_FLAG_MASK; 8169 8170 if (meta->func_id == BPF_FUNC_kptr_xchg && type_is_alloc(type)) 8171 type &= ~MEM_ALLOC; 8172 8173 for (i = 0; i < ARRAY_SIZE(compatible->types); i++) { 8174 expected = compatible->types[i]; 8175 if (expected == NOT_INIT) 8176 break; 8177 8178 if (type == expected) 8179 goto found; 8180 } 8181 8182 verbose(env, "R%d type=%s expected=", regno, reg_type_str(env, reg->type)); 8183 for (j = 0; j + 1 < i; j++) 8184 verbose(env, "%s, ", reg_type_str(env, compatible->types[j])); 8185 verbose(env, "%s\n", reg_type_str(env, compatible->types[j])); 8186 return -EACCES; 8187 8188 found: 8189 if (base_type(reg->type) != PTR_TO_BTF_ID) 8190 return 0; 8191 8192 if (compatible == &mem_types) { 8193 if (!(arg_type & MEM_RDONLY)) { 8194 verbose(env, 8195 "%s() may write into memory pointed by R%d type=%s\n", 8196 func_id_name(meta->func_id), 8197 regno, reg_type_str(env, reg->type)); 8198 return -EACCES; 8199 } 8200 return 0; 8201 } 8202 8203 switch ((int)reg->type) { 8204 case PTR_TO_BTF_ID: 8205 case PTR_TO_BTF_ID | PTR_TRUSTED: 8206 case PTR_TO_BTF_ID | MEM_RCU: 8207 case PTR_TO_BTF_ID | PTR_MAYBE_NULL: 8208 case PTR_TO_BTF_ID | PTR_MAYBE_NULL | MEM_RCU: 8209 { 8210 /* For bpf_sk_release, it needs to match against first member 8211 * 'struct sock_common', hence make an exception for it. This 8212 * allows bpf_sk_release to work for multiple socket types. 8213 */ 8214 bool strict_type_match = arg_type_is_release(arg_type) && 8215 meta->func_id != BPF_FUNC_sk_release; 8216 8217 if (type_may_be_null(reg->type) && 8218 (!type_may_be_null(arg_type) || arg_type_is_release(arg_type))) { 8219 verbose(env, "Possibly NULL pointer passed to helper arg%d\n", regno); 8220 return -EACCES; 8221 } 8222 8223 if (!arg_btf_id) { 8224 if (!compatible->btf_id) { 8225 verbose(env, "verifier internal error: missing arg compatible BTF ID\n"); 8226 return -EFAULT; 8227 } 8228 arg_btf_id = compatible->btf_id; 8229 } 8230 8231 if (meta->func_id == BPF_FUNC_kptr_xchg) { 8232 if (map_kptr_match_type(env, meta->kptr_field, reg, regno)) 8233 return -EACCES; 8234 } else { 8235 if (arg_btf_id == BPF_PTR_POISON) { 8236 verbose(env, "verifier internal error:"); 8237 verbose(env, "R%d has non-overwritten BPF_PTR_POISON type\n", 8238 regno); 8239 return -EACCES; 8240 } 8241 8242 if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off, 8243 btf_vmlinux, *arg_btf_id, 8244 strict_type_match)) { 8245 verbose(env, "R%d is of type %s but %s is expected\n", 8246 regno, btf_type_name(reg->btf, reg->btf_id), 8247 btf_type_name(btf_vmlinux, *arg_btf_id)); 8248 return -EACCES; 8249 } 8250 } 8251 break; 8252 } 8253 case PTR_TO_BTF_ID | MEM_ALLOC: 8254 if (meta->func_id != BPF_FUNC_spin_lock && meta->func_id != BPF_FUNC_spin_unlock && 8255 meta->func_id != BPF_FUNC_kptr_xchg) { 8256 verbose(env, "verifier internal error: unimplemented handling of MEM_ALLOC\n"); 8257 return -EFAULT; 8258 } 8259 if (meta->func_id == BPF_FUNC_kptr_xchg) { 8260 if (map_kptr_match_type(env, meta->kptr_field, reg, regno)) 8261 return -EACCES; 8262 } 8263 break; 8264 case PTR_TO_BTF_ID | MEM_PERCPU: 8265 case PTR_TO_BTF_ID | MEM_PERCPU | PTR_TRUSTED: 8266 /* Handled by helper specific checks */ 8267 break; 8268 default: 8269 verbose(env, "verifier internal error: invalid PTR_TO_BTF_ID register for type match\n"); 8270 return -EFAULT; 8271 } 8272 return 0; 8273 } 8274 8275 static struct btf_field * 8276 reg_find_field_offset(const struct bpf_reg_state *reg, s32 off, u32 fields) 8277 { 8278 struct btf_field *field; 8279 struct btf_record *rec; 8280 8281 rec = reg_btf_record(reg); 8282 if (!rec) 8283 return NULL; 8284 8285 field = btf_record_find(rec, off, fields); 8286 if (!field) 8287 return NULL; 8288 8289 return field; 8290 } 8291 8292 int check_func_arg_reg_off(struct bpf_verifier_env *env, 8293 const struct bpf_reg_state *reg, int regno, 8294 enum bpf_arg_type arg_type) 8295 { 8296 u32 type = reg->type; 8297 8298 /* When referenced register is passed to release function, its fixed 8299 * offset must be 0. 8300 * 8301 * We will check arg_type_is_release reg has ref_obj_id when storing 8302 * meta->release_regno. 8303 */ 8304 if (arg_type_is_release(arg_type)) { 8305 /* ARG_PTR_TO_DYNPTR with OBJ_RELEASE is a bit special, as it 8306 * may not directly point to the object being released, but to 8307 * dynptr pointing to such object, which might be at some offset 8308 * on the stack. In that case, we simply to fallback to the 8309 * default handling. 8310 */ 8311 if (arg_type_is_dynptr(arg_type) && type == PTR_TO_STACK) 8312 return 0; 8313 8314 /* Doing check_ptr_off_reg check for the offset will catch this 8315 * because fixed_off_ok is false, but checking here allows us 8316 * to give the user a better error message. 8317 */ 8318 if (reg->off) { 8319 verbose(env, "R%d must have zero offset when passed to release func or trusted arg to kfunc\n", 8320 regno); 8321 return -EINVAL; 8322 } 8323 return __check_ptr_off_reg(env, reg, regno, false); 8324 } 8325 8326 switch (type) { 8327 /* Pointer types where both fixed and variable offset is explicitly allowed: */ 8328 case PTR_TO_STACK: 8329 case PTR_TO_PACKET: 8330 case PTR_TO_PACKET_META: 8331 case PTR_TO_MAP_KEY: 8332 case PTR_TO_MAP_VALUE: 8333 case PTR_TO_MEM: 8334 case PTR_TO_MEM | MEM_RDONLY: 8335 case PTR_TO_MEM | MEM_RINGBUF: 8336 case PTR_TO_BUF: 8337 case PTR_TO_BUF | MEM_RDONLY: 8338 case SCALAR_VALUE: 8339 return 0; 8340 /* All the rest must be rejected, except PTR_TO_BTF_ID which allows 8341 * fixed offset. 8342 */ 8343 case PTR_TO_BTF_ID: 8344 case PTR_TO_BTF_ID | MEM_ALLOC: 8345 case PTR_TO_BTF_ID | PTR_TRUSTED: 8346 case PTR_TO_BTF_ID | MEM_RCU: 8347 case PTR_TO_BTF_ID | MEM_ALLOC | NON_OWN_REF: 8348 case PTR_TO_BTF_ID | MEM_ALLOC | NON_OWN_REF | MEM_RCU: 8349 /* When referenced PTR_TO_BTF_ID is passed to release function, 8350 * its fixed offset must be 0. In the other cases, fixed offset 8351 * can be non-zero. This was already checked above. So pass 8352 * fixed_off_ok as true to allow fixed offset for all other 8353 * cases. var_off always must be 0 for PTR_TO_BTF_ID, hence we 8354 * still need to do checks instead of returning. 8355 */ 8356 return __check_ptr_off_reg(env, reg, regno, true); 8357 default: 8358 return __check_ptr_off_reg(env, reg, regno, false); 8359 } 8360 } 8361 8362 static struct bpf_reg_state *get_dynptr_arg_reg(struct bpf_verifier_env *env, 8363 const struct bpf_func_proto *fn, 8364 struct bpf_reg_state *regs) 8365 { 8366 struct bpf_reg_state *state = NULL; 8367 int i; 8368 8369 for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++) 8370 if (arg_type_is_dynptr(fn->arg_type[i])) { 8371 if (state) { 8372 verbose(env, "verifier internal error: multiple dynptr args\n"); 8373 return NULL; 8374 } 8375 state = ®s[BPF_REG_1 + i]; 8376 } 8377 8378 if (!state) 8379 verbose(env, "verifier internal error: no dynptr arg found\n"); 8380 8381 return state; 8382 } 8383 8384 static int dynptr_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 8385 { 8386 struct bpf_func_state *state = func(env, reg); 8387 int spi; 8388 8389 if (reg->type == CONST_PTR_TO_DYNPTR) 8390 return reg->id; 8391 spi = dynptr_get_spi(env, reg); 8392 if (spi < 0) 8393 return spi; 8394 return state->stack[spi].spilled_ptr.id; 8395 } 8396 8397 static int dynptr_ref_obj_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 8398 { 8399 struct bpf_func_state *state = func(env, reg); 8400 int spi; 8401 8402 if (reg->type == CONST_PTR_TO_DYNPTR) 8403 return reg->ref_obj_id; 8404 spi = dynptr_get_spi(env, reg); 8405 if (spi < 0) 8406 return spi; 8407 return state->stack[spi].spilled_ptr.ref_obj_id; 8408 } 8409 8410 static enum bpf_dynptr_type dynptr_get_type(struct bpf_verifier_env *env, 8411 struct bpf_reg_state *reg) 8412 { 8413 struct bpf_func_state *state = func(env, reg); 8414 int spi; 8415 8416 if (reg->type == CONST_PTR_TO_DYNPTR) 8417 return reg->dynptr.type; 8418 8419 spi = __get_spi(reg->off); 8420 if (spi < 0) { 8421 verbose(env, "verifier internal error: invalid spi when querying dynptr type\n"); 8422 return BPF_DYNPTR_TYPE_INVALID; 8423 } 8424 8425 return state->stack[spi].spilled_ptr.dynptr.type; 8426 } 8427 8428 static int check_func_arg(struct bpf_verifier_env *env, u32 arg, 8429 struct bpf_call_arg_meta *meta, 8430 const struct bpf_func_proto *fn, 8431 int insn_idx) 8432 { 8433 u32 regno = BPF_REG_1 + arg; 8434 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno]; 8435 enum bpf_arg_type arg_type = fn->arg_type[arg]; 8436 enum bpf_reg_type type = reg->type; 8437 u32 *arg_btf_id = NULL; 8438 int err = 0; 8439 8440 if (arg_type == ARG_DONTCARE) 8441 return 0; 8442 8443 err = check_reg_arg(env, regno, SRC_OP); 8444 if (err) 8445 return err; 8446 8447 if (arg_type == ARG_ANYTHING) { 8448 if (is_pointer_value(env, regno)) { 8449 verbose(env, "R%d leaks addr into helper function\n", 8450 regno); 8451 return -EACCES; 8452 } 8453 return 0; 8454 } 8455 8456 if (type_is_pkt_pointer(type) && 8457 !may_access_direct_pkt_data(env, meta, BPF_READ)) { 8458 verbose(env, "helper access to the packet is not allowed\n"); 8459 return -EACCES; 8460 } 8461 8462 if (base_type(arg_type) == ARG_PTR_TO_MAP_VALUE) { 8463 err = resolve_map_arg_type(env, meta, &arg_type); 8464 if (err) 8465 return err; 8466 } 8467 8468 if (register_is_null(reg) && type_may_be_null(arg_type)) 8469 /* A NULL register has a SCALAR_VALUE type, so skip 8470 * type checking. 8471 */ 8472 goto skip_type_check; 8473 8474 /* arg_btf_id and arg_size are in a union. */ 8475 if (base_type(arg_type) == ARG_PTR_TO_BTF_ID || 8476 base_type(arg_type) == ARG_PTR_TO_SPIN_LOCK) 8477 arg_btf_id = fn->arg_btf_id[arg]; 8478 8479 err = check_reg_type(env, regno, arg_type, arg_btf_id, meta); 8480 if (err) 8481 return err; 8482 8483 err = check_func_arg_reg_off(env, reg, regno, arg_type); 8484 if (err) 8485 return err; 8486 8487 skip_type_check: 8488 if (arg_type_is_release(arg_type)) { 8489 if (arg_type_is_dynptr(arg_type)) { 8490 struct bpf_func_state *state = func(env, reg); 8491 int spi; 8492 8493 /* Only dynptr created on stack can be released, thus 8494 * the get_spi and stack state checks for spilled_ptr 8495 * should only be done before process_dynptr_func for 8496 * PTR_TO_STACK. 8497 */ 8498 if (reg->type == PTR_TO_STACK) { 8499 spi = dynptr_get_spi(env, reg); 8500 if (spi < 0 || !state->stack[spi].spilled_ptr.ref_obj_id) { 8501 verbose(env, "arg %d is an unacquired reference\n", regno); 8502 return -EINVAL; 8503 } 8504 } else { 8505 verbose(env, "cannot release unowned const bpf_dynptr\n"); 8506 return -EINVAL; 8507 } 8508 } else if (!reg->ref_obj_id && !register_is_null(reg)) { 8509 verbose(env, "R%d must be referenced when passed to release function\n", 8510 regno); 8511 return -EINVAL; 8512 } 8513 if (meta->release_regno) { 8514 verbose(env, "verifier internal error: more than one release argument\n"); 8515 return -EFAULT; 8516 } 8517 meta->release_regno = regno; 8518 } 8519 8520 if (reg->ref_obj_id) { 8521 if (meta->ref_obj_id) { 8522 verbose(env, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n", 8523 regno, reg->ref_obj_id, 8524 meta->ref_obj_id); 8525 return -EFAULT; 8526 } 8527 meta->ref_obj_id = reg->ref_obj_id; 8528 } 8529 8530 switch (base_type(arg_type)) { 8531 case ARG_CONST_MAP_PTR: 8532 /* bpf_map_xxx(map_ptr) call: remember that map_ptr */ 8533 if (meta->map_ptr) { 8534 /* Use map_uid (which is unique id of inner map) to reject: 8535 * inner_map1 = bpf_map_lookup_elem(outer_map, key1) 8536 * inner_map2 = bpf_map_lookup_elem(outer_map, key2) 8537 * if (inner_map1 && inner_map2) { 8538 * timer = bpf_map_lookup_elem(inner_map1); 8539 * if (timer) 8540 * // mismatch would have been allowed 8541 * bpf_timer_init(timer, inner_map2); 8542 * } 8543 * 8544 * Comparing map_ptr is enough to distinguish normal and outer maps. 8545 */ 8546 if (meta->map_ptr != reg->map_ptr || 8547 meta->map_uid != reg->map_uid) { 8548 verbose(env, 8549 "timer pointer in R1 map_uid=%d doesn't match map pointer in R2 map_uid=%d\n", 8550 meta->map_uid, reg->map_uid); 8551 return -EINVAL; 8552 } 8553 } 8554 meta->map_ptr = reg->map_ptr; 8555 meta->map_uid = reg->map_uid; 8556 break; 8557 case ARG_PTR_TO_MAP_KEY: 8558 /* bpf_map_xxx(..., map_ptr, ..., key) call: 8559 * check that [key, key + map->key_size) are within 8560 * stack limits and initialized 8561 */ 8562 if (!meta->map_ptr) { 8563 /* in function declaration map_ptr must come before 8564 * map_key, so that it's verified and known before 8565 * we have to check map_key here. Otherwise it means 8566 * that kernel subsystem misconfigured verifier 8567 */ 8568 verbose(env, "invalid map_ptr to access map->key\n"); 8569 return -EACCES; 8570 } 8571 err = check_helper_mem_access(env, regno, 8572 meta->map_ptr->key_size, false, 8573 NULL); 8574 break; 8575 case ARG_PTR_TO_MAP_VALUE: 8576 if (type_may_be_null(arg_type) && register_is_null(reg)) 8577 return 0; 8578 8579 /* bpf_map_xxx(..., map_ptr, ..., value) call: 8580 * check [value, value + map->value_size) validity 8581 */ 8582 if (!meta->map_ptr) { 8583 /* kernel subsystem misconfigured verifier */ 8584 verbose(env, "invalid map_ptr to access map->value\n"); 8585 return -EACCES; 8586 } 8587 meta->raw_mode = arg_type & MEM_UNINIT; 8588 err = check_helper_mem_access(env, regno, 8589 meta->map_ptr->value_size, false, 8590 meta); 8591 break; 8592 case ARG_PTR_TO_PERCPU_BTF_ID: 8593 if (!reg->btf_id) { 8594 verbose(env, "Helper has invalid btf_id in R%d\n", regno); 8595 return -EACCES; 8596 } 8597 meta->ret_btf = reg->btf; 8598 meta->ret_btf_id = reg->btf_id; 8599 break; 8600 case ARG_PTR_TO_SPIN_LOCK: 8601 if (in_rbtree_lock_required_cb(env)) { 8602 verbose(env, "can't spin_{lock,unlock} in rbtree cb\n"); 8603 return -EACCES; 8604 } 8605 if (meta->func_id == BPF_FUNC_spin_lock) { 8606 err = process_spin_lock(env, regno, true); 8607 if (err) 8608 return err; 8609 } else if (meta->func_id == BPF_FUNC_spin_unlock) { 8610 err = process_spin_lock(env, regno, false); 8611 if (err) 8612 return err; 8613 } else { 8614 verbose(env, "verifier internal error\n"); 8615 return -EFAULT; 8616 } 8617 break; 8618 case ARG_PTR_TO_TIMER: 8619 err = process_timer_func(env, regno, meta); 8620 if (err) 8621 return err; 8622 break; 8623 case ARG_PTR_TO_FUNC: 8624 meta->subprogno = reg->subprogno; 8625 break; 8626 case ARG_PTR_TO_MEM: 8627 /* The access to this pointer is only checked when we hit the 8628 * next is_mem_size argument below. 8629 */ 8630 meta->raw_mode = arg_type & MEM_UNINIT; 8631 if (arg_type & MEM_FIXED_SIZE) { 8632 err = check_helper_mem_access(env, regno, fn->arg_size[arg], false, meta); 8633 if (err) 8634 return err; 8635 if (arg_type & MEM_ALIGNED) 8636 err = check_ptr_alignment(env, reg, 0, fn->arg_size[arg], true); 8637 } 8638 break; 8639 case ARG_CONST_SIZE: 8640 err = check_mem_size_reg(env, reg, regno, false, meta); 8641 break; 8642 case ARG_CONST_SIZE_OR_ZERO: 8643 err = check_mem_size_reg(env, reg, regno, true, meta); 8644 break; 8645 case ARG_PTR_TO_DYNPTR: 8646 err = process_dynptr_func(env, regno, insn_idx, arg_type, 0); 8647 if (err) 8648 return err; 8649 break; 8650 case ARG_CONST_ALLOC_SIZE_OR_ZERO: 8651 if (!tnum_is_const(reg->var_off)) { 8652 verbose(env, "R%d is not a known constant'\n", 8653 regno); 8654 return -EACCES; 8655 } 8656 meta->mem_size = reg->var_off.value; 8657 err = mark_chain_precision(env, regno); 8658 if (err) 8659 return err; 8660 break; 8661 case ARG_PTR_TO_CONST_STR: 8662 { 8663 struct bpf_map *map = reg->map_ptr; 8664 int map_off; 8665 u64 map_addr; 8666 char *str_ptr; 8667 8668 if (!bpf_map_is_rdonly(map)) { 8669 verbose(env, "R%d does not point to a readonly map'\n", regno); 8670 return -EACCES; 8671 } 8672 8673 if (!tnum_is_const(reg->var_off)) { 8674 verbose(env, "R%d is not a constant address'\n", regno); 8675 return -EACCES; 8676 } 8677 8678 if (!map->ops->map_direct_value_addr) { 8679 verbose(env, "no direct value access support for this map type\n"); 8680 return -EACCES; 8681 } 8682 8683 err = check_map_access(env, regno, reg->off, 8684 map->value_size - reg->off, false, 8685 ACCESS_HELPER); 8686 if (err) 8687 return err; 8688 8689 map_off = reg->off + reg->var_off.value; 8690 err = map->ops->map_direct_value_addr(map, &map_addr, map_off); 8691 if (err) { 8692 verbose(env, "direct value access on string failed\n"); 8693 return err; 8694 } 8695 8696 str_ptr = (char *)(long)(map_addr); 8697 if (!strnchr(str_ptr + map_off, map->value_size - map_off, 0)) { 8698 verbose(env, "string is not zero-terminated\n"); 8699 return -EINVAL; 8700 } 8701 break; 8702 } 8703 case ARG_PTR_TO_KPTR: 8704 err = process_kptr_func(env, regno, meta); 8705 if (err) 8706 return err; 8707 break; 8708 } 8709 8710 return err; 8711 } 8712 8713 static bool may_update_sockmap(struct bpf_verifier_env *env, int func_id) 8714 { 8715 enum bpf_attach_type eatype = env->prog->expected_attach_type; 8716 enum bpf_prog_type type = resolve_prog_type(env->prog); 8717 8718 if (func_id != BPF_FUNC_map_update_elem && 8719 func_id != BPF_FUNC_map_delete_elem) 8720 return false; 8721 8722 /* It's not possible to get access to a locked struct sock in these 8723 * contexts, so updating is safe. 8724 */ 8725 switch (type) { 8726 case BPF_PROG_TYPE_TRACING: 8727 if (eatype == BPF_TRACE_ITER) 8728 return true; 8729 break; 8730 case BPF_PROG_TYPE_SOCK_OPS: 8731 /* map_update allowed only via dedicated helpers with event type checks */ 8732 if (func_id == BPF_FUNC_map_delete_elem) 8733 return true; 8734 break; 8735 case BPF_PROG_TYPE_SOCKET_FILTER: 8736 case BPF_PROG_TYPE_SCHED_CLS: 8737 case BPF_PROG_TYPE_SCHED_ACT: 8738 case BPF_PROG_TYPE_XDP: 8739 case BPF_PROG_TYPE_SK_REUSEPORT: 8740 case BPF_PROG_TYPE_FLOW_DISSECTOR: 8741 case BPF_PROG_TYPE_SK_LOOKUP: 8742 return true; 8743 default: 8744 break; 8745 } 8746 8747 verbose(env, "cannot update sockmap in this context\n"); 8748 return false; 8749 } 8750 8751 static bool allow_tail_call_in_subprogs(struct bpf_verifier_env *env) 8752 { 8753 return env->prog->jit_requested && 8754 bpf_jit_supports_subprog_tailcalls(); 8755 } 8756 8757 static int check_map_func_compatibility(struct bpf_verifier_env *env, 8758 struct bpf_map *map, int func_id) 8759 { 8760 if (!map) 8761 return 0; 8762 8763 /* We need a two way check, first is from map perspective ... */ 8764 switch (map->map_type) { 8765 case BPF_MAP_TYPE_PROG_ARRAY: 8766 if (func_id != BPF_FUNC_tail_call) 8767 goto error; 8768 break; 8769 case BPF_MAP_TYPE_PERF_EVENT_ARRAY: 8770 if (func_id != BPF_FUNC_perf_event_read && 8771 func_id != BPF_FUNC_perf_event_output && 8772 func_id != BPF_FUNC_skb_output && 8773 func_id != BPF_FUNC_perf_event_read_value && 8774 func_id != BPF_FUNC_xdp_output) 8775 goto error; 8776 break; 8777 case BPF_MAP_TYPE_RINGBUF: 8778 if (func_id != BPF_FUNC_ringbuf_output && 8779 func_id != BPF_FUNC_ringbuf_reserve && 8780 func_id != BPF_FUNC_ringbuf_query && 8781 func_id != BPF_FUNC_ringbuf_reserve_dynptr && 8782 func_id != BPF_FUNC_ringbuf_submit_dynptr && 8783 func_id != BPF_FUNC_ringbuf_discard_dynptr) 8784 goto error; 8785 break; 8786 case BPF_MAP_TYPE_USER_RINGBUF: 8787 if (func_id != BPF_FUNC_user_ringbuf_drain) 8788 goto error; 8789 break; 8790 case BPF_MAP_TYPE_STACK_TRACE: 8791 if (func_id != BPF_FUNC_get_stackid) 8792 goto error; 8793 break; 8794 case BPF_MAP_TYPE_CGROUP_ARRAY: 8795 if (func_id != BPF_FUNC_skb_under_cgroup && 8796 func_id != BPF_FUNC_current_task_under_cgroup) 8797 goto error; 8798 break; 8799 case BPF_MAP_TYPE_CGROUP_STORAGE: 8800 case BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE: 8801 if (func_id != BPF_FUNC_get_local_storage) 8802 goto error; 8803 break; 8804 case BPF_MAP_TYPE_DEVMAP: 8805 case BPF_MAP_TYPE_DEVMAP_HASH: 8806 if (func_id != BPF_FUNC_redirect_map && 8807 func_id != BPF_FUNC_map_lookup_elem) 8808 goto error; 8809 break; 8810 /* Restrict bpf side of cpumap and xskmap, open when use-cases 8811 * appear. 8812 */ 8813 case BPF_MAP_TYPE_CPUMAP: 8814 if (func_id != BPF_FUNC_redirect_map) 8815 goto error; 8816 break; 8817 case BPF_MAP_TYPE_XSKMAP: 8818 if (func_id != BPF_FUNC_redirect_map && 8819 func_id != BPF_FUNC_map_lookup_elem) 8820 goto error; 8821 break; 8822 case BPF_MAP_TYPE_ARRAY_OF_MAPS: 8823 case BPF_MAP_TYPE_HASH_OF_MAPS: 8824 if (func_id != BPF_FUNC_map_lookup_elem) 8825 goto error; 8826 break; 8827 case BPF_MAP_TYPE_SOCKMAP: 8828 if (func_id != BPF_FUNC_sk_redirect_map && 8829 func_id != BPF_FUNC_sock_map_update && 8830 func_id != BPF_FUNC_msg_redirect_map && 8831 func_id != BPF_FUNC_sk_select_reuseport && 8832 func_id != BPF_FUNC_map_lookup_elem && 8833 !may_update_sockmap(env, func_id)) 8834 goto error; 8835 break; 8836 case BPF_MAP_TYPE_SOCKHASH: 8837 if (func_id != BPF_FUNC_sk_redirect_hash && 8838 func_id != BPF_FUNC_sock_hash_update && 8839 func_id != BPF_FUNC_msg_redirect_hash && 8840 func_id != BPF_FUNC_sk_select_reuseport && 8841 func_id != BPF_FUNC_map_lookup_elem && 8842 !may_update_sockmap(env, func_id)) 8843 goto error; 8844 break; 8845 case BPF_MAP_TYPE_REUSEPORT_SOCKARRAY: 8846 if (func_id != BPF_FUNC_sk_select_reuseport) 8847 goto error; 8848 break; 8849 case BPF_MAP_TYPE_QUEUE: 8850 case BPF_MAP_TYPE_STACK: 8851 if (func_id != BPF_FUNC_map_peek_elem && 8852 func_id != BPF_FUNC_map_pop_elem && 8853 func_id != BPF_FUNC_map_push_elem) 8854 goto error; 8855 break; 8856 case BPF_MAP_TYPE_SK_STORAGE: 8857 if (func_id != BPF_FUNC_sk_storage_get && 8858 func_id != BPF_FUNC_sk_storage_delete && 8859 func_id != BPF_FUNC_kptr_xchg) 8860 goto error; 8861 break; 8862 case BPF_MAP_TYPE_INODE_STORAGE: 8863 if (func_id != BPF_FUNC_inode_storage_get && 8864 func_id != BPF_FUNC_inode_storage_delete && 8865 func_id != BPF_FUNC_kptr_xchg) 8866 goto error; 8867 break; 8868 case BPF_MAP_TYPE_TASK_STORAGE: 8869 if (func_id != BPF_FUNC_task_storage_get && 8870 func_id != BPF_FUNC_task_storage_delete && 8871 func_id != BPF_FUNC_kptr_xchg) 8872 goto error; 8873 break; 8874 case BPF_MAP_TYPE_CGRP_STORAGE: 8875 if (func_id != BPF_FUNC_cgrp_storage_get && 8876 func_id != BPF_FUNC_cgrp_storage_delete && 8877 func_id != BPF_FUNC_kptr_xchg) 8878 goto error; 8879 break; 8880 case BPF_MAP_TYPE_BLOOM_FILTER: 8881 if (func_id != BPF_FUNC_map_peek_elem && 8882 func_id != BPF_FUNC_map_push_elem) 8883 goto error; 8884 break; 8885 default: 8886 break; 8887 } 8888 8889 /* ... and second from the function itself. */ 8890 switch (func_id) { 8891 case BPF_FUNC_tail_call: 8892 if (map->map_type != BPF_MAP_TYPE_PROG_ARRAY) 8893 goto error; 8894 if (env->subprog_cnt > 1 && !allow_tail_call_in_subprogs(env)) { 8895 verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n"); 8896 return -EINVAL; 8897 } 8898 break; 8899 case BPF_FUNC_perf_event_read: 8900 case BPF_FUNC_perf_event_output: 8901 case BPF_FUNC_perf_event_read_value: 8902 case BPF_FUNC_skb_output: 8903 case BPF_FUNC_xdp_output: 8904 if (map->map_type != BPF_MAP_TYPE_PERF_EVENT_ARRAY) 8905 goto error; 8906 break; 8907 case BPF_FUNC_ringbuf_output: 8908 case BPF_FUNC_ringbuf_reserve: 8909 case BPF_FUNC_ringbuf_query: 8910 case BPF_FUNC_ringbuf_reserve_dynptr: 8911 case BPF_FUNC_ringbuf_submit_dynptr: 8912 case BPF_FUNC_ringbuf_discard_dynptr: 8913 if (map->map_type != BPF_MAP_TYPE_RINGBUF) 8914 goto error; 8915 break; 8916 case BPF_FUNC_user_ringbuf_drain: 8917 if (map->map_type != BPF_MAP_TYPE_USER_RINGBUF) 8918 goto error; 8919 break; 8920 case BPF_FUNC_get_stackid: 8921 if (map->map_type != BPF_MAP_TYPE_STACK_TRACE) 8922 goto error; 8923 break; 8924 case BPF_FUNC_current_task_under_cgroup: 8925 case BPF_FUNC_skb_under_cgroup: 8926 if (map->map_type != BPF_MAP_TYPE_CGROUP_ARRAY) 8927 goto error; 8928 break; 8929 case BPF_FUNC_redirect_map: 8930 if (map->map_type != BPF_MAP_TYPE_DEVMAP && 8931 map->map_type != BPF_MAP_TYPE_DEVMAP_HASH && 8932 map->map_type != BPF_MAP_TYPE_CPUMAP && 8933 map->map_type != BPF_MAP_TYPE_XSKMAP) 8934 goto error; 8935 break; 8936 case BPF_FUNC_sk_redirect_map: 8937 case BPF_FUNC_msg_redirect_map: 8938 case BPF_FUNC_sock_map_update: 8939 if (map->map_type != BPF_MAP_TYPE_SOCKMAP) 8940 goto error; 8941 break; 8942 case BPF_FUNC_sk_redirect_hash: 8943 case BPF_FUNC_msg_redirect_hash: 8944 case BPF_FUNC_sock_hash_update: 8945 if (map->map_type != BPF_MAP_TYPE_SOCKHASH) 8946 goto error; 8947 break; 8948 case BPF_FUNC_get_local_storage: 8949 if (map->map_type != BPF_MAP_TYPE_CGROUP_STORAGE && 8950 map->map_type != BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE) 8951 goto error; 8952 break; 8953 case BPF_FUNC_sk_select_reuseport: 8954 if (map->map_type != BPF_MAP_TYPE_REUSEPORT_SOCKARRAY && 8955 map->map_type != BPF_MAP_TYPE_SOCKMAP && 8956 map->map_type != BPF_MAP_TYPE_SOCKHASH) 8957 goto error; 8958 break; 8959 case BPF_FUNC_map_pop_elem: 8960 if (map->map_type != BPF_MAP_TYPE_QUEUE && 8961 map->map_type != BPF_MAP_TYPE_STACK) 8962 goto error; 8963 break; 8964 case BPF_FUNC_map_peek_elem: 8965 case BPF_FUNC_map_push_elem: 8966 if (map->map_type != BPF_MAP_TYPE_QUEUE && 8967 map->map_type != BPF_MAP_TYPE_STACK && 8968 map->map_type != BPF_MAP_TYPE_BLOOM_FILTER) 8969 goto error; 8970 break; 8971 case BPF_FUNC_map_lookup_percpu_elem: 8972 if (map->map_type != BPF_MAP_TYPE_PERCPU_ARRAY && 8973 map->map_type != BPF_MAP_TYPE_PERCPU_HASH && 8974 map->map_type != BPF_MAP_TYPE_LRU_PERCPU_HASH) 8975 goto error; 8976 break; 8977 case BPF_FUNC_sk_storage_get: 8978 case BPF_FUNC_sk_storage_delete: 8979 if (map->map_type != BPF_MAP_TYPE_SK_STORAGE) 8980 goto error; 8981 break; 8982 case BPF_FUNC_inode_storage_get: 8983 case BPF_FUNC_inode_storage_delete: 8984 if (map->map_type != BPF_MAP_TYPE_INODE_STORAGE) 8985 goto error; 8986 break; 8987 case BPF_FUNC_task_storage_get: 8988 case BPF_FUNC_task_storage_delete: 8989 if (map->map_type != BPF_MAP_TYPE_TASK_STORAGE) 8990 goto error; 8991 break; 8992 case BPF_FUNC_cgrp_storage_get: 8993 case BPF_FUNC_cgrp_storage_delete: 8994 if (map->map_type != BPF_MAP_TYPE_CGRP_STORAGE) 8995 goto error; 8996 break; 8997 default: 8998 break; 8999 } 9000 9001 return 0; 9002 error: 9003 verbose(env, "cannot pass map_type %d into func %s#%d\n", 9004 map->map_type, func_id_name(func_id), func_id); 9005 return -EINVAL; 9006 } 9007 9008 static bool check_raw_mode_ok(const struct bpf_func_proto *fn) 9009 { 9010 int count = 0; 9011 9012 if (fn->arg1_type == ARG_PTR_TO_UNINIT_MEM) 9013 count++; 9014 if (fn->arg2_type == ARG_PTR_TO_UNINIT_MEM) 9015 count++; 9016 if (fn->arg3_type == ARG_PTR_TO_UNINIT_MEM) 9017 count++; 9018 if (fn->arg4_type == ARG_PTR_TO_UNINIT_MEM) 9019 count++; 9020 if (fn->arg5_type == ARG_PTR_TO_UNINIT_MEM) 9021 count++; 9022 9023 /* We only support one arg being in raw mode at the moment, 9024 * which is sufficient for the helper functions we have 9025 * right now. 9026 */ 9027 return count <= 1; 9028 } 9029 9030 static bool check_args_pair_invalid(const struct bpf_func_proto *fn, int arg) 9031 { 9032 bool is_fixed = fn->arg_type[arg] & MEM_FIXED_SIZE; 9033 bool has_size = fn->arg_size[arg] != 0; 9034 bool is_next_size = false; 9035 9036 if (arg + 1 < ARRAY_SIZE(fn->arg_type)) 9037 is_next_size = arg_type_is_mem_size(fn->arg_type[arg + 1]); 9038 9039 if (base_type(fn->arg_type[arg]) != ARG_PTR_TO_MEM) 9040 return is_next_size; 9041 9042 return has_size == is_next_size || is_next_size == is_fixed; 9043 } 9044 9045 static bool check_arg_pair_ok(const struct bpf_func_proto *fn) 9046 { 9047 /* bpf_xxx(..., buf, len) call will access 'len' 9048 * bytes from memory 'buf'. Both arg types need 9049 * to be paired, so make sure there's no buggy 9050 * helper function specification. 9051 */ 9052 if (arg_type_is_mem_size(fn->arg1_type) || 9053 check_args_pair_invalid(fn, 0) || 9054 check_args_pair_invalid(fn, 1) || 9055 check_args_pair_invalid(fn, 2) || 9056 check_args_pair_invalid(fn, 3) || 9057 check_args_pair_invalid(fn, 4)) 9058 return false; 9059 9060 return true; 9061 } 9062 9063 static bool check_btf_id_ok(const struct bpf_func_proto *fn) 9064 { 9065 int i; 9066 9067 for (i = 0; i < ARRAY_SIZE(fn->arg_type); i++) { 9068 if (base_type(fn->arg_type[i]) == ARG_PTR_TO_BTF_ID) 9069 return !!fn->arg_btf_id[i]; 9070 if (base_type(fn->arg_type[i]) == ARG_PTR_TO_SPIN_LOCK) 9071 return fn->arg_btf_id[i] == BPF_PTR_POISON; 9072 if (base_type(fn->arg_type[i]) != ARG_PTR_TO_BTF_ID && fn->arg_btf_id[i] && 9073 /* arg_btf_id and arg_size are in a union. */ 9074 (base_type(fn->arg_type[i]) != ARG_PTR_TO_MEM || 9075 !(fn->arg_type[i] & MEM_FIXED_SIZE))) 9076 return false; 9077 } 9078 9079 return true; 9080 } 9081 9082 static int check_func_proto(const struct bpf_func_proto *fn, int func_id) 9083 { 9084 return check_raw_mode_ok(fn) && 9085 check_arg_pair_ok(fn) && 9086 check_btf_id_ok(fn) ? 0 : -EINVAL; 9087 } 9088 9089 /* Packet data might have moved, any old PTR_TO_PACKET[_META,_END] 9090 * are now invalid, so turn them into unknown SCALAR_VALUE. 9091 * 9092 * This also applies to dynptr slices belonging to skb and xdp dynptrs, 9093 * since these slices point to packet data. 9094 */ 9095 static void clear_all_pkt_pointers(struct bpf_verifier_env *env) 9096 { 9097 struct bpf_func_state *state; 9098 struct bpf_reg_state *reg; 9099 9100 bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({ 9101 if (reg_is_pkt_pointer_any(reg) || reg_is_dynptr_slice_pkt(reg)) 9102 mark_reg_invalid(env, reg); 9103 })); 9104 } 9105 9106 enum { 9107 AT_PKT_END = -1, 9108 BEYOND_PKT_END = -2, 9109 }; 9110 9111 static void mark_pkt_end(struct bpf_verifier_state *vstate, int regn, bool range_open) 9112 { 9113 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 9114 struct bpf_reg_state *reg = &state->regs[regn]; 9115 9116 if (reg->type != PTR_TO_PACKET) 9117 /* PTR_TO_PACKET_META is not supported yet */ 9118 return; 9119 9120 /* The 'reg' is pkt > pkt_end or pkt >= pkt_end. 9121 * How far beyond pkt_end it goes is unknown. 9122 * if (!range_open) it's the case of pkt >= pkt_end 9123 * if (range_open) it's the case of pkt > pkt_end 9124 * hence this pointer is at least 1 byte bigger than pkt_end 9125 */ 9126 if (range_open) 9127 reg->range = BEYOND_PKT_END; 9128 else 9129 reg->range = AT_PKT_END; 9130 } 9131 9132 /* The pointer with the specified id has released its reference to kernel 9133 * resources. Identify all copies of the same pointer and clear the reference. 9134 */ 9135 static int release_reference(struct bpf_verifier_env *env, 9136 int ref_obj_id) 9137 { 9138 struct bpf_func_state *state; 9139 struct bpf_reg_state *reg; 9140 int err; 9141 9142 err = release_reference_state(cur_func(env), ref_obj_id); 9143 if (err) 9144 return err; 9145 9146 bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({ 9147 if (reg->ref_obj_id == ref_obj_id) 9148 mark_reg_invalid(env, reg); 9149 })); 9150 9151 return 0; 9152 } 9153 9154 static void invalidate_non_owning_refs(struct bpf_verifier_env *env) 9155 { 9156 struct bpf_func_state *unused; 9157 struct bpf_reg_state *reg; 9158 9159 bpf_for_each_reg_in_vstate(env->cur_state, unused, reg, ({ 9160 if (type_is_non_owning_ref(reg->type)) 9161 mark_reg_invalid(env, reg); 9162 })); 9163 } 9164 9165 static void clear_caller_saved_regs(struct bpf_verifier_env *env, 9166 struct bpf_reg_state *regs) 9167 { 9168 int i; 9169 9170 /* after the call registers r0 - r5 were scratched */ 9171 for (i = 0; i < CALLER_SAVED_REGS; i++) { 9172 mark_reg_not_init(env, regs, caller_saved[i]); 9173 __check_reg_arg(env, regs, caller_saved[i], DST_OP_NO_MARK); 9174 } 9175 } 9176 9177 typedef int (*set_callee_state_fn)(struct bpf_verifier_env *env, 9178 struct bpf_func_state *caller, 9179 struct bpf_func_state *callee, 9180 int insn_idx); 9181 9182 static int set_callee_state(struct bpf_verifier_env *env, 9183 struct bpf_func_state *caller, 9184 struct bpf_func_state *callee, int insn_idx); 9185 9186 static int setup_func_entry(struct bpf_verifier_env *env, int subprog, int callsite, 9187 set_callee_state_fn set_callee_state_cb, 9188 struct bpf_verifier_state *state) 9189 { 9190 struct bpf_func_state *caller, *callee; 9191 int err; 9192 9193 if (state->curframe + 1 >= MAX_CALL_FRAMES) { 9194 verbose(env, "the call stack of %d frames is too deep\n", 9195 state->curframe + 2); 9196 return -E2BIG; 9197 } 9198 9199 if (state->frame[state->curframe + 1]) { 9200 verbose(env, "verifier bug. Frame %d already allocated\n", 9201 state->curframe + 1); 9202 return -EFAULT; 9203 } 9204 9205 caller = state->frame[state->curframe]; 9206 callee = kzalloc(sizeof(*callee), GFP_KERNEL); 9207 if (!callee) 9208 return -ENOMEM; 9209 state->frame[state->curframe + 1] = callee; 9210 9211 /* callee cannot access r0, r6 - r9 for reading and has to write 9212 * into its own stack before reading from it. 9213 * callee can read/write into caller's stack 9214 */ 9215 init_func_state(env, callee, 9216 /* remember the callsite, it will be used by bpf_exit */ 9217 callsite, 9218 state->curframe + 1 /* frameno within this callchain */, 9219 subprog /* subprog number within this prog */); 9220 /* Transfer references to the callee */ 9221 err = copy_reference_state(callee, caller); 9222 err = err ?: set_callee_state_cb(env, caller, callee, callsite); 9223 if (err) 9224 goto err_out; 9225 9226 /* only increment it after check_reg_arg() finished */ 9227 state->curframe++; 9228 9229 return 0; 9230 9231 err_out: 9232 free_func_state(callee); 9233 state->frame[state->curframe + 1] = NULL; 9234 return err; 9235 } 9236 9237 static int push_callback_call(struct bpf_verifier_env *env, struct bpf_insn *insn, 9238 int insn_idx, int subprog, 9239 set_callee_state_fn set_callee_state_cb) 9240 { 9241 struct bpf_verifier_state *state = env->cur_state, *callback_state; 9242 struct bpf_func_state *caller, *callee; 9243 int err; 9244 9245 caller = state->frame[state->curframe]; 9246 err = btf_check_subprog_call(env, subprog, caller->regs); 9247 if (err == -EFAULT) 9248 return err; 9249 9250 /* set_callee_state is used for direct subprog calls, but we are 9251 * interested in validating only BPF helpers that can call subprogs as 9252 * callbacks 9253 */ 9254 if (bpf_pseudo_kfunc_call(insn) && 9255 !is_sync_callback_calling_kfunc(insn->imm)) { 9256 verbose(env, "verifier bug: kfunc %s#%d not marked as callback-calling\n", 9257 func_id_name(insn->imm), insn->imm); 9258 return -EFAULT; 9259 } else if (!bpf_pseudo_kfunc_call(insn) && 9260 !is_callback_calling_function(insn->imm)) { /* helper */ 9261 verbose(env, "verifier bug: helper %s#%d not marked as callback-calling\n", 9262 func_id_name(insn->imm), insn->imm); 9263 return -EFAULT; 9264 } 9265 9266 if (insn->code == (BPF_JMP | BPF_CALL) && 9267 insn->src_reg == 0 && 9268 insn->imm == BPF_FUNC_timer_set_callback) { 9269 struct bpf_verifier_state *async_cb; 9270 9271 /* there is no real recursion here. timer callbacks are async */ 9272 env->subprog_info[subprog].is_async_cb = true; 9273 async_cb = push_async_cb(env, env->subprog_info[subprog].start, 9274 insn_idx, subprog); 9275 if (!async_cb) 9276 return -EFAULT; 9277 callee = async_cb->frame[0]; 9278 callee->async_entry_cnt = caller->async_entry_cnt + 1; 9279 9280 /* Convert bpf_timer_set_callback() args into timer callback args */ 9281 err = set_callee_state_cb(env, caller, callee, insn_idx); 9282 if (err) 9283 return err; 9284 9285 return 0; 9286 } 9287 9288 /* for callback functions enqueue entry to callback and 9289 * proceed with next instruction within current frame. 9290 */ 9291 callback_state = push_stack(env, env->subprog_info[subprog].start, insn_idx, false); 9292 if (!callback_state) 9293 return -ENOMEM; 9294 9295 err = setup_func_entry(env, subprog, insn_idx, set_callee_state_cb, 9296 callback_state); 9297 if (err) 9298 return err; 9299 9300 callback_state->callback_unroll_depth++; 9301 callback_state->frame[callback_state->curframe - 1]->callback_depth++; 9302 caller->callback_depth = 0; 9303 return 0; 9304 } 9305 9306 static int check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn, 9307 int *insn_idx) 9308 { 9309 struct bpf_verifier_state *state = env->cur_state; 9310 struct bpf_func_state *caller; 9311 int err, subprog, target_insn; 9312 9313 target_insn = *insn_idx + insn->imm + 1; 9314 subprog = find_subprog(env, target_insn); 9315 if (subprog < 0) { 9316 verbose(env, "verifier bug. No program starts at insn %d\n", target_insn); 9317 return -EFAULT; 9318 } 9319 9320 caller = state->frame[state->curframe]; 9321 err = btf_check_subprog_call(env, subprog, caller->regs); 9322 if (err == -EFAULT) 9323 return err; 9324 if (subprog_is_global(env, subprog)) { 9325 if (err) { 9326 verbose(env, "Caller passes invalid args into func#%d\n", subprog); 9327 return err; 9328 } 9329 9330 if (env->log.level & BPF_LOG_LEVEL) 9331 verbose(env, "Func#%d is global and valid. Skipping.\n", subprog); 9332 clear_caller_saved_regs(env, caller->regs); 9333 9334 /* All global functions return a 64-bit SCALAR_VALUE */ 9335 mark_reg_unknown(env, caller->regs, BPF_REG_0); 9336 caller->regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG; 9337 9338 /* continue with next insn after call */ 9339 return 0; 9340 } 9341 9342 /* for regular function entry setup new frame and continue 9343 * from that frame. 9344 */ 9345 err = setup_func_entry(env, subprog, *insn_idx, set_callee_state, state); 9346 if (err) 9347 return err; 9348 9349 clear_caller_saved_regs(env, caller->regs); 9350 9351 /* and go analyze first insn of the callee */ 9352 *insn_idx = env->subprog_info[subprog].start - 1; 9353 9354 if (env->log.level & BPF_LOG_LEVEL) { 9355 verbose(env, "caller:\n"); 9356 print_verifier_state(env, caller, true); 9357 verbose(env, "callee:\n"); 9358 print_verifier_state(env, state->frame[state->curframe], true); 9359 } 9360 9361 return 0; 9362 } 9363 9364 int map_set_for_each_callback_args(struct bpf_verifier_env *env, 9365 struct bpf_func_state *caller, 9366 struct bpf_func_state *callee) 9367 { 9368 /* bpf_for_each_map_elem(struct bpf_map *map, void *callback_fn, 9369 * void *callback_ctx, u64 flags); 9370 * callback_fn(struct bpf_map *map, void *key, void *value, 9371 * void *callback_ctx); 9372 */ 9373 callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1]; 9374 9375 callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY; 9376 __mark_reg_known_zero(&callee->regs[BPF_REG_2]); 9377 callee->regs[BPF_REG_2].map_ptr = caller->regs[BPF_REG_1].map_ptr; 9378 9379 callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE; 9380 __mark_reg_known_zero(&callee->regs[BPF_REG_3]); 9381 callee->regs[BPF_REG_3].map_ptr = caller->regs[BPF_REG_1].map_ptr; 9382 9383 /* pointer to stack or null */ 9384 callee->regs[BPF_REG_4] = caller->regs[BPF_REG_3]; 9385 9386 /* unused */ 9387 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]); 9388 return 0; 9389 } 9390 9391 static int set_callee_state(struct bpf_verifier_env *env, 9392 struct bpf_func_state *caller, 9393 struct bpf_func_state *callee, int insn_idx) 9394 { 9395 int i; 9396 9397 /* copy r1 - r5 args that callee can access. The copy includes parent 9398 * pointers, which connects us up to the liveness chain 9399 */ 9400 for (i = BPF_REG_1; i <= BPF_REG_5; i++) 9401 callee->regs[i] = caller->regs[i]; 9402 return 0; 9403 } 9404 9405 static int set_map_elem_callback_state(struct bpf_verifier_env *env, 9406 struct bpf_func_state *caller, 9407 struct bpf_func_state *callee, 9408 int insn_idx) 9409 { 9410 struct bpf_insn_aux_data *insn_aux = &env->insn_aux_data[insn_idx]; 9411 struct bpf_map *map; 9412 int err; 9413 9414 if (bpf_map_ptr_poisoned(insn_aux)) { 9415 verbose(env, "tail_call abusing map_ptr\n"); 9416 return -EINVAL; 9417 } 9418 9419 map = BPF_MAP_PTR(insn_aux->map_ptr_state); 9420 if (!map->ops->map_set_for_each_callback_args || 9421 !map->ops->map_for_each_callback) { 9422 verbose(env, "callback function not allowed for map\n"); 9423 return -ENOTSUPP; 9424 } 9425 9426 err = map->ops->map_set_for_each_callback_args(env, caller, callee); 9427 if (err) 9428 return err; 9429 9430 callee->in_callback_fn = true; 9431 callee->callback_ret_range = tnum_range(0, 1); 9432 return 0; 9433 } 9434 9435 static int set_loop_callback_state(struct bpf_verifier_env *env, 9436 struct bpf_func_state *caller, 9437 struct bpf_func_state *callee, 9438 int insn_idx) 9439 { 9440 /* bpf_loop(u32 nr_loops, void *callback_fn, void *callback_ctx, 9441 * u64 flags); 9442 * callback_fn(u32 index, void *callback_ctx); 9443 */ 9444 callee->regs[BPF_REG_1].type = SCALAR_VALUE; 9445 callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3]; 9446 9447 /* unused */ 9448 __mark_reg_not_init(env, &callee->regs[BPF_REG_3]); 9449 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]); 9450 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]); 9451 9452 callee->in_callback_fn = true; 9453 callee->callback_ret_range = tnum_range(0, 1); 9454 return 0; 9455 } 9456 9457 static int set_timer_callback_state(struct bpf_verifier_env *env, 9458 struct bpf_func_state *caller, 9459 struct bpf_func_state *callee, 9460 int insn_idx) 9461 { 9462 struct bpf_map *map_ptr = caller->regs[BPF_REG_1].map_ptr; 9463 9464 /* bpf_timer_set_callback(struct bpf_timer *timer, void *callback_fn); 9465 * callback_fn(struct bpf_map *map, void *key, void *value); 9466 */ 9467 callee->regs[BPF_REG_1].type = CONST_PTR_TO_MAP; 9468 __mark_reg_known_zero(&callee->regs[BPF_REG_1]); 9469 callee->regs[BPF_REG_1].map_ptr = map_ptr; 9470 9471 callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY; 9472 __mark_reg_known_zero(&callee->regs[BPF_REG_2]); 9473 callee->regs[BPF_REG_2].map_ptr = map_ptr; 9474 9475 callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE; 9476 __mark_reg_known_zero(&callee->regs[BPF_REG_3]); 9477 callee->regs[BPF_REG_3].map_ptr = map_ptr; 9478 9479 /* unused */ 9480 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]); 9481 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]); 9482 callee->in_async_callback_fn = true; 9483 callee->callback_ret_range = tnum_range(0, 1); 9484 return 0; 9485 } 9486 9487 static int set_find_vma_callback_state(struct bpf_verifier_env *env, 9488 struct bpf_func_state *caller, 9489 struct bpf_func_state *callee, 9490 int insn_idx) 9491 { 9492 /* bpf_find_vma(struct task_struct *task, u64 addr, 9493 * void *callback_fn, void *callback_ctx, u64 flags) 9494 * (callback_fn)(struct task_struct *task, 9495 * struct vm_area_struct *vma, void *callback_ctx); 9496 */ 9497 callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1]; 9498 9499 callee->regs[BPF_REG_2].type = PTR_TO_BTF_ID; 9500 __mark_reg_known_zero(&callee->regs[BPF_REG_2]); 9501 callee->regs[BPF_REG_2].btf = btf_vmlinux; 9502 callee->regs[BPF_REG_2].btf_id = btf_tracing_ids[BTF_TRACING_TYPE_VMA], 9503 9504 /* pointer to stack or null */ 9505 callee->regs[BPF_REG_3] = caller->regs[BPF_REG_4]; 9506 9507 /* unused */ 9508 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]); 9509 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]); 9510 callee->in_callback_fn = true; 9511 callee->callback_ret_range = tnum_range(0, 1); 9512 return 0; 9513 } 9514 9515 static int set_user_ringbuf_callback_state(struct bpf_verifier_env *env, 9516 struct bpf_func_state *caller, 9517 struct bpf_func_state *callee, 9518 int insn_idx) 9519 { 9520 /* bpf_user_ringbuf_drain(struct bpf_map *map, void *callback_fn, void 9521 * callback_ctx, u64 flags); 9522 * callback_fn(const struct bpf_dynptr_t* dynptr, void *callback_ctx); 9523 */ 9524 __mark_reg_not_init(env, &callee->regs[BPF_REG_0]); 9525 mark_dynptr_cb_reg(env, &callee->regs[BPF_REG_1], BPF_DYNPTR_TYPE_LOCAL); 9526 callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3]; 9527 9528 /* unused */ 9529 __mark_reg_not_init(env, &callee->regs[BPF_REG_3]); 9530 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]); 9531 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]); 9532 9533 callee->in_callback_fn = true; 9534 callee->callback_ret_range = tnum_range(0, 1); 9535 return 0; 9536 } 9537 9538 static int set_rbtree_add_callback_state(struct bpf_verifier_env *env, 9539 struct bpf_func_state *caller, 9540 struct bpf_func_state *callee, 9541 int insn_idx) 9542 { 9543 /* void bpf_rbtree_add_impl(struct bpf_rb_root *root, struct bpf_rb_node *node, 9544 * bool (less)(struct bpf_rb_node *a, const struct bpf_rb_node *b)); 9545 * 9546 * 'struct bpf_rb_node *node' arg to bpf_rbtree_add_impl is the same PTR_TO_BTF_ID w/ offset 9547 * that 'less' callback args will be receiving. However, 'node' arg was release_reference'd 9548 * by this point, so look at 'root' 9549 */ 9550 struct btf_field *field; 9551 9552 field = reg_find_field_offset(&caller->regs[BPF_REG_1], caller->regs[BPF_REG_1].off, 9553 BPF_RB_ROOT); 9554 if (!field || !field->graph_root.value_btf_id) 9555 return -EFAULT; 9556 9557 mark_reg_graph_node(callee->regs, BPF_REG_1, &field->graph_root); 9558 ref_set_non_owning(env, &callee->regs[BPF_REG_1]); 9559 mark_reg_graph_node(callee->regs, BPF_REG_2, &field->graph_root); 9560 ref_set_non_owning(env, &callee->regs[BPF_REG_2]); 9561 9562 __mark_reg_not_init(env, &callee->regs[BPF_REG_3]); 9563 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]); 9564 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]); 9565 callee->in_callback_fn = true; 9566 callee->callback_ret_range = tnum_range(0, 1); 9567 return 0; 9568 } 9569 9570 static bool is_rbtree_lock_required_kfunc(u32 btf_id); 9571 9572 /* Are we currently verifying the callback for a rbtree helper that must 9573 * be called with lock held? If so, no need to complain about unreleased 9574 * lock 9575 */ 9576 static bool in_rbtree_lock_required_cb(struct bpf_verifier_env *env) 9577 { 9578 struct bpf_verifier_state *state = env->cur_state; 9579 struct bpf_insn *insn = env->prog->insnsi; 9580 struct bpf_func_state *callee; 9581 int kfunc_btf_id; 9582 9583 if (!state->curframe) 9584 return false; 9585 9586 callee = state->frame[state->curframe]; 9587 9588 if (!callee->in_callback_fn) 9589 return false; 9590 9591 kfunc_btf_id = insn[callee->callsite].imm; 9592 return is_rbtree_lock_required_kfunc(kfunc_btf_id); 9593 } 9594 9595 static int prepare_func_exit(struct bpf_verifier_env *env, int *insn_idx) 9596 { 9597 struct bpf_verifier_state *state = env->cur_state, *prev_st; 9598 struct bpf_func_state *caller, *callee; 9599 struct bpf_reg_state *r0; 9600 bool in_callback_fn; 9601 int err; 9602 9603 callee = state->frame[state->curframe]; 9604 r0 = &callee->regs[BPF_REG_0]; 9605 if (r0->type == PTR_TO_STACK) { 9606 /* technically it's ok to return caller's stack pointer 9607 * (or caller's caller's pointer) back to the caller, 9608 * since these pointers are valid. Only current stack 9609 * pointer will be invalid as soon as function exits, 9610 * but let's be conservative 9611 */ 9612 verbose(env, "cannot return stack pointer to the caller\n"); 9613 return -EINVAL; 9614 } 9615 9616 caller = state->frame[state->curframe - 1]; 9617 if (callee->in_callback_fn) { 9618 /* enforce R0 return value range [0, 1]. */ 9619 struct tnum range = callee->callback_ret_range; 9620 9621 if (r0->type != SCALAR_VALUE) { 9622 verbose(env, "R0 not a scalar value\n"); 9623 return -EACCES; 9624 } 9625 9626 /* we are going to rely on register's precise value */ 9627 err = mark_reg_read(env, r0, r0->parent, REG_LIVE_READ64); 9628 err = err ?: mark_chain_precision(env, BPF_REG_0); 9629 if (err) 9630 return err; 9631 9632 if (!tnum_in(range, r0->var_off)) { 9633 verbose_invalid_scalar(env, r0, &range, "callback return", "R0"); 9634 return -EINVAL; 9635 } 9636 if (!calls_callback(env, callee->callsite)) { 9637 verbose(env, "BUG: in callback at %d, callsite %d !calls_callback\n", 9638 *insn_idx, callee->callsite); 9639 return -EFAULT; 9640 } 9641 } else { 9642 /* return to the caller whatever r0 had in the callee */ 9643 caller->regs[BPF_REG_0] = *r0; 9644 } 9645 9646 /* callback_fn frame should have released its own additions to parent's 9647 * reference state at this point, or check_reference_leak would 9648 * complain, hence it must be the same as the caller. There is no need 9649 * to copy it back. 9650 */ 9651 if (!callee->in_callback_fn) { 9652 /* Transfer references to the caller */ 9653 err = copy_reference_state(caller, callee); 9654 if (err) 9655 return err; 9656 } 9657 9658 /* for callbacks like bpf_loop or bpf_for_each_map_elem go back to callsite, 9659 * there function call logic would reschedule callback visit. If iteration 9660 * converges is_state_visited() would prune that visit eventually. 9661 */ 9662 in_callback_fn = callee->in_callback_fn; 9663 if (in_callback_fn) 9664 *insn_idx = callee->callsite; 9665 else 9666 *insn_idx = callee->callsite + 1; 9667 9668 if (env->log.level & BPF_LOG_LEVEL) { 9669 verbose(env, "returning from callee:\n"); 9670 print_verifier_state(env, callee, true); 9671 verbose(env, "to caller at %d:\n", *insn_idx); 9672 print_verifier_state(env, caller, true); 9673 } 9674 /* clear everything in the callee */ 9675 free_func_state(callee); 9676 state->frame[state->curframe--] = NULL; 9677 9678 /* for callbacks widen imprecise scalars to make programs like below verify: 9679 * 9680 * struct ctx { int i; } 9681 * void cb(int idx, struct ctx *ctx) { ctx->i++; ... } 9682 * ... 9683 * struct ctx = { .i = 0; } 9684 * bpf_loop(100, cb, &ctx, 0); 9685 * 9686 * This is similar to what is done in process_iter_next_call() for open 9687 * coded iterators. 9688 */ 9689 prev_st = in_callback_fn ? find_prev_entry(env, state, *insn_idx) : NULL; 9690 if (prev_st) { 9691 err = widen_imprecise_scalars(env, prev_st, state); 9692 if (err) 9693 return err; 9694 } 9695 return 0; 9696 } 9697 9698 static void do_refine_retval_range(struct bpf_reg_state *regs, int ret_type, 9699 int func_id, 9700 struct bpf_call_arg_meta *meta) 9701 { 9702 struct bpf_reg_state *ret_reg = ®s[BPF_REG_0]; 9703 9704 if (ret_type != RET_INTEGER) 9705 return; 9706 9707 switch (func_id) { 9708 case BPF_FUNC_get_stack: 9709 case BPF_FUNC_get_task_stack: 9710 case BPF_FUNC_probe_read_str: 9711 case BPF_FUNC_probe_read_kernel_str: 9712 case BPF_FUNC_probe_read_user_str: 9713 ret_reg->smax_value = meta->msize_max_value; 9714 ret_reg->s32_max_value = meta->msize_max_value; 9715 ret_reg->smin_value = -MAX_ERRNO; 9716 ret_reg->s32_min_value = -MAX_ERRNO; 9717 reg_bounds_sync(ret_reg); 9718 break; 9719 case BPF_FUNC_get_smp_processor_id: 9720 ret_reg->umax_value = nr_cpu_ids - 1; 9721 ret_reg->u32_max_value = nr_cpu_ids - 1; 9722 ret_reg->smax_value = nr_cpu_ids - 1; 9723 ret_reg->s32_max_value = nr_cpu_ids - 1; 9724 ret_reg->umin_value = 0; 9725 ret_reg->u32_min_value = 0; 9726 ret_reg->smin_value = 0; 9727 ret_reg->s32_min_value = 0; 9728 reg_bounds_sync(ret_reg); 9729 break; 9730 } 9731 } 9732 9733 static int 9734 record_func_map(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta, 9735 int func_id, int insn_idx) 9736 { 9737 struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx]; 9738 struct bpf_map *map = meta->map_ptr; 9739 9740 if (func_id != BPF_FUNC_tail_call && 9741 func_id != BPF_FUNC_map_lookup_elem && 9742 func_id != BPF_FUNC_map_update_elem && 9743 func_id != BPF_FUNC_map_delete_elem && 9744 func_id != BPF_FUNC_map_push_elem && 9745 func_id != BPF_FUNC_map_pop_elem && 9746 func_id != BPF_FUNC_map_peek_elem && 9747 func_id != BPF_FUNC_for_each_map_elem && 9748 func_id != BPF_FUNC_redirect_map && 9749 func_id != BPF_FUNC_map_lookup_percpu_elem) 9750 return 0; 9751 9752 if (map == NULL) { 9753 verbose(env, "kernel subsystem misconfigured verifier\n"); 9754 return -EINVAL; 9755 } 9756 9757 /* In case of read-only, some additional restrictions 9758 * need to be applied in order to prevent altering the 9759 * state of the map from program side. 9760 */ 9761 if ((map->map_flags & BPF_F_RDONLY_PROG) && 9762 (func_id == BPF_FUNC_map_delete_elem || 9763 func_id == BPF_FUNC_map_update_elem || 9764 func_id == BPF_FUNC_map_push_elem || 9765 func_id == BPF_FUNC_map_pop_elem)) { 9766 verbose(env, "write into map forbidden\n"); 9767 return -EACCES; 9768 } 9769 9770 if (!BPF_MAP_PTR(aux->map_ptr_state)) 9771 bpf_map_ptr_store(aux, meta->map_ptr, 9772 !meta->map_ptr->bypass_spec_v1); 9773 else if (BPF_MAP_PTR(aux->map_ptr_state) != meta->map_ptr) 9774 bpf_map_ptr_store(aux, BPF_MAP_PTR_POISON, 9775 !meta->map_ptr->bypass_spec_v1); 9776 return 0; 9777 } 9778 9779 static int 9780 record_func_key(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta, 9781 int func_id, int insn_idx) 9782 { 9783 struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx]; 9784 struct bpf_reg_state *regs = cur_regs(env), *reg; 9785 struct bpf_map *map = meta->map_ptr; 9786 u64 val, max; 9787 int err; 9788 9789 if (func_id != BPF_FUNC_tail_call) 9790 return 0; 9791 if (!map || map->map_type != BPF_MAP_TYPE_PROG_ARRAY) { 9792 verbose(env, "kernel subsystem misconfigured verifier\n"); 9793 return -EINVAL; 9794 } 9795 9796 reg = ®s[BPF_REG_3]; 9797 val = reg->var_off.value; 9798 max = map->max_entries; 9799 9800 if (!(register_is_const(reg) && val < max)) { 9801 bpf_map_key_store(aux, BPF_MAP_KEY_POISON); 9802 return 0; 9803 } 9804 9805 err = mark_chain_precision(env, BPF_REG_3); 9806 if (err) 9807 return err; 9808 if (bpf_map_key_unseen(aux)) 9809 bpf_map_key_store(aux, val); 9810 else if (!bpf_map_key_poisoned(aux) && 9811 bpf_map_key_immediate(aux) != val) 9812 bpf_map_key_store(aux, BPF_MAP_KEY_POISON); 9813 return 0; 9814 } 9815 9816 static int check_reference_leak(struct bpf_verifier_env *env) 9817 { 9818 struct bpf_func_state *state = cur_func(env); 9819 bool refs_lingering = false; 9820 int i; 9821 9822 if (state->frameno && !state->in_callback_fn) 9823 return 0; 9824 9825 for (i = 0; i < state->acquired_refs; i++) { 9826 if (state->in_callback_fn && state->refs[i].callback_ref != state->frameno) 9827 continue; 9828 verbose(env, "Unreleased reference id=%d alloc_insn=%d\n", 9829 state->refs[i].id, state->refs[i].insn_idx); 9830 refs_lingering = true; 9831 } 9832 return refs_lingering ? -EINVAL : 0; 9833 } 9834 9835 static int check_bpf_snprintf_call(struct bpf_verifier_env *env, 9836 struct bpf_reg_state *regs) 9837 { 9838 struct bpf_reg_state *fmt_reg = ®s[BPF_REG_3]; 9839 struct bpf_reg_state *data_len_reg = ®s[BPF_REG_5]; 9840 struct bpf_map *fmt_map = fmt_reg->map_ptr; 9841 struct bpf_bprintf_data data = {}; 9842 int err, fmt_map_off, num_args; 9843 u64 fmt_addr; 9844 char *fmt; 9845 9846 /* data must be an array of u64 */ 9847 if (data_len_reg->var_off.value % 8) 9848 return -EINVAL; 9849 num_args = data_len_reg->var_off.value / 8; 9850 9851 /* fmt being ARG_PTR_TO_CONST_STR guarantees that var_off is const 9852 * and map_direct_value_addr is set. 9853 */ 9854 fmt_map_off = fmt_reg->off + fmt_reg->var_off.value; 9855 err = fmt_map->ops->map_direct_value_addr(fmt_map, &fmt_addr, 9856 fmt_map_off); 9857 if (err) { 9858 verbose(env, "verifier bug\n"); 9859 return -EFAULT; 9860 } 9861 fmt = (char *)(long)fmt_addr + fmt_map_off; 9862 9863 /* We are also guaranteed that fmt+fmt_map_off is NULL terminated, we 9864 * can focus on validating the format specifiers. 9865 */ 9866 err = bpf_bprintf_prepare(fmt, UINT_MAX, NULL, num_args, &data); 9867 if (err < 0) 9868 verbose(env, "Invalid format string\n"); 9869 9870 return err; 9871 } 9872 9873 static int check_get_func_ip(struct bpf_verifier_env *env) 9874 { 9875 enum bpf_prog_type type = resolve_prog_type(env->prog); 9876 int func_id = BPF_FUNC_get_func_ip; 9877 9878 if (type == BPF_PROG_TYPE_TRACING) { 9879 if (!bpf_prog_has_trampoline(env->prog)) { 9880 verbose(env, "func %s#%d supported only for fentry/fexit/fmod_ret programs\n", 9881 func_id_name(func_id), func_id); 9882 return -ENOTSUPP; 9883 } 9884 return 0; 9885 } else if (type == BPF_PROG_TYPE_KPROBE) { 9886 return 0; 9887 } 9888 9889 verbose(env, "func %s#%d not supported for program type %d\n", 9890 func_id_name(func_id), func_id, type); 9891 return -ENOTSUPP; 9892 } 9893 9894 static struct bpf_insn_aux_data *cur_aux(struct bpf_verifier_env *env) 9895 { 9896 return &env->insn_aux_data[env->insn_idx]; 9897 } 9898 9899 static bool loop_flag_is_zero(struct bpf_verifier_env *env) 9900 { 9901 struct bpf_reg_state *regs = cur_regs(env); 9902 struct bpf_reg_state *reg = ®s[BPF_REG_4]; 9903 bool reg_is_null = register_is_null(reg); 9904 9905 if (reg_is_null) 9906 mark_chain_precision(env, BPF_REG_4); 9907 9908 return reg_is_null; 9909 } 9910 9911 static void update_loop_inline_state(struct bpf_verifier_env *env, u32 subprogno) 9912 { 9913 struct bpf_loop_inline_state *state = &cur_aux(env)->loop_inline_state; 9914 9915 if (!state->initialized) { 9916 state->initialized = 1; 9917 state->fit_for_inline = loop_flag_is_zero(env); 9918 state->callback_subprogno = subprogno; 9919 return; 9920 } 9921 9922 if (!state->fit_for_inline) 9923 return; 9924 9925 state->fit_for_inline = (loop_flag_is_zero(env) && 9926 state->callback_subprogno == subprogno); 9927 } 9928 9929 static int check_helper_call(struct bpf_verifier_env *env, struct bpf_insn *insn, 9930 int *insn_idx_p) 9931 { 9932 enum bpf_prog_type prog_type = resolve_prog_type(env->prog); 9933 const struct bpf_func_proto *fn = NULL; 9934 enum bpf_return_type ret_type; 9935 enum bpf_type_flag ret_flag; 9936 struct bpf_reg_state *regs; 9937 struct bpf_call_arg_meta meta; 9938 int insn_idx = *insn_idx_p; 9939 bool changes_data; 9940 int i, err, func_id; 9941 9942 /* find function prototype */ 9943 func_id = insn->imm; 9944 if (func_id < 0 || func_id >= __BPF_FUNC_MAX_ID) { 9945 verbose(env, "invalid func %s#%d\n", func_id_name(func_id), 9946 func_id); 9947 return -EINVAL; 9948 } 9949 9950 if (env->ops->get_func_proto) 9951 fn = env->ops->get_func_proto(func_id, env->prog); 9952 if (!fn) { 9953 verbose(env, "unknown func %s#%d\n", func_id_name(func_id), 9954 func_id); 9955 return -EINVAL; 9956 } 9957 9958 /* eBPF programs must be GPL compatible to use GPL-ed functions */ 9959 if (!env->prog->gpl_compatible && fn->gpl_only) { 9960 verbose(env, "cannot call GPL-restricted function from non-GPL compatible program\n"); 9961 return -EINVAL; 9962 } 9963 9964 if (fn->allowed && !fn->allowed(env->prog)) { 9965 verbose(env, "helper call is not allowed in probe\n"); 9966 return -EINVAL; 9967 } 9968 9969 if (!env->prog->aux->sleepable && fn->might_sleep) { 9970 verbose(env, "helper call might sleep in a non-sleepable prog\n"); 9971 return -EINVAL; 9972 } 9973 9974 /* With LD_ABS/IND some JITs save/restore skb from r1. */ 9975 changes_data = bpf_helper_changes_pkt_data(fn->func); 9976 if (changes_data && fn->arg1_type != ARG_PTR_TO_CTX) { 9977 verbose(env, "kernel subsystem misconfigured func %s#%d: r1 != ctx\n", 9978 func_id_name(func_id), func_id); 9979 return -EINVAL; 9980 } 9981 9982 memset(&meta, 0, sizeof(meta)); 9983 meta.pkt_access = fn->pkt_access; 9984 9985 err = check_func_proto(fn, func_id); 9986 if (err) { 9987 verbose(env, "kernel subsystem misconfigured func %s#%d\n", 9988 func_id_name(func_id), func_id); 9989 return err; 9990 } 9991 9992 if (env->cur_state->active_rcu_lock) { 9993 if (fn->might_sleep) { 9994 verbose(env, "sleepable helper %s#%d in rcu_read_lock region\n", 9995 func_id_name(func_id), func_id); 9996 return -EINVAL; 9997 } 9998 9999 if (env->prog->aux->sleepable && is_storage_get_function(func_id)) 10000 env->insn_aux_data[insn_idx].storage_get_func_atomic = true; 10001 } 10002 10003 meta.func_id = func_id; 10004 /* check args */ 10005 for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++) { 10006 err = check_func_arg(env, i, &meta, fn, insn_idx); 10007 if (err) 10008 return err; 10009 } 10010 10011 err = record_func_map(env, &meta, func_id, insn_idx); 10012 if (err) 10013 return err; 10014 10015 err = record_func_key(env, &meta, func_id, insn_idx); 10016 if (err) 10017 return err; 10018 10019 /* Mark slots with STACK_MISC in case of raw mode, stack offset 10020 * is inferred from register state. 10021 */ 10022 for (i = 0; i < meta.access_size; i++) { 10023 err = check_mem_access(env, insn_idx, meta.regno, i, BPF_B, 10024 BPF_WRITE, -1, false, false); 10025 if (err) 10026 return err; 10027 } 10028 10029 regs = cur_regs(env); 10030 10031 if (meta.release_regno) { 10032 err = -EINVAL; 10033 /* This can only be set for PTR_TO_STACK, as CONST_PTR_TO_DYNPTR cannot 10034 * be released by any dynptr helper. Hence, unmark_stack_slots_dynptr 10035 * is safe to do directly. 10036 */ 10037 if (arg_type_is_dynptr(fn->arg_type[meta.release_regno - BPF_REG_1])) { 10038 if (regs[meta.release_regno].type == CONST_PTR_TO_DYNPTR) { 10039 verbose(env, "verifier internal error: CONST_PTR_TO_DYNPTR cannot be released\n"); 10040 return -EFAULT; 10041 } 10042 err = unmark_stack_slots_dynptr(env, ®s[meta.release_regno]); 10043 } else if (meta.ref_obj_id) { 10044 err = release_reference(env, meta.ref_obj_id); 10045 } else if (register_is_null(®s[meta.release_regno])) { 10046 /* meta.ref_obj_id can only be 0 if register that is meant to be 10047 * released is NULL, which must be > R0. 10048 */ 10049 err = 0; 10050 } 10051 if (err) { 10052 verbose(env, "func %s#%d reference has not been acquired before\n", 10053 func_id_name(func_id), func_id); 10054 return err; 10055 } 10056 } 10057 10058 switch (func_id) { 10059 case BPF_FUNC_tail_call: 10060 err = check_reference_leak(env); 10061 if (err) { 10062 verbose(env, "tail_call would lead to reference leak\n"); 10063 return err; 10064 } 10065 break; 10066 case BPF_FUNC_get_local_storage: 10067 /* check that flags argument in get_local_storage(map, flags) is 0, 10068 * this is required because get_local_storage() can't return an error. 10069 */ 10070 if (!register_is_null(®s[BPF_REG_2])) { 10071 verbose(env, "get_local_storage() doesn't support non-zero flags\n"); 10072 return -EINVAL; 10073 } 10074 break; 10075 case BPF_FUNC_for_each_map_elem: 10076 err = push_callback_call(env, insn, insn_idx, meta.subprogno, 10077 set_map_elem_callback_state); 10078 break; 10079 case BPF_FUNC_timer_set_callback: 10080 err = push_callback_call(env, insn, insn_idx, meta.subprogno, 10081 set_timer_callback_state); 10082 break; 10083 case BPF_FUNC_find_vma: 10084 err = push_callback_call(env, insn, insn_idx, meta.subprogno, 10085 set_find_vma_callback_state); 10086 break; 10087 case BPF_FUNC_snprintf: 10088 err = check_bpf_snprintf_call(env, regs); 10089 break; 10090 case BPF_FUNC_loop: 10091 update_loop_inline_state(env, meta.subprogno); 10092 /* Verifier relies on R1 value to determine if bpf_loop() iteration 10093 * is finished, thus mark it precise. 10094 */ 10095 err = mark_chain_precision(env, BPF_REG_1); 10096 if (err) 10097 return err; 10098 if (cur_func(env)->callback_depth < regs[BPF_REG_1].umax_value) { 10099 err = push_callback_call(env, insn, insn_idx, meta.subprogno, 10100 set_loop_callback_state); 10101 } else { 10102 cur_func(env)->callback_depth = 0; 10103 if (env->log.level & BPF_LOG_LEVEL2) 10104 verbose(env, "frame%d bpf_loop iteration limit reached\n", 10105 env->cur_state->curframe); 10106 } 10107 break; 10108 case BPF_FUNC_dynptr_from_mem: 10109 if (regs[BPF_REG_1].type != PTR_TO_MAP_VALUE) { 10110 verbose(env, "Unsupported reg type %s for bpf_dynptr_from_mem data\n", 10111 reg_type_str(env, regs[BPF_REG_1].type)); 10112 return -EACCES; 10113 } 10114 break; 10115 case BPF_FUNC_set_retval: 10116 if (prog_type == BPF_PROG_TYPE_LSM && 10117 env->prog->expected_attach_type == BPF_LSM_CGROUP) { 10118 if (!env->prog->aux->attach_func_proto->type) { 10119 /* Make sure programs that attach to void 10120 * hooks don't try to modify return value. 10121 */ 10122 verbose(env, "BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n"); 10123 return -EINVAL; 10124 } 10125 } 10126 break; 10127 case BPF_FUNC_dynptr_data: 10128 { 10129 struct bpf_reg_state *reg; 10130 int id, ref_obj_id; 10131 10132 reg = get_dynptr_arg_reg(env, fn, regs); 10133 if (!reg) 10134 return -EFAULT; 10135 10136 10137 if (meta.dynptr_id) { 10138 verbose(env, "verifier internal error: meta.dynptr_id already set\n"); 10139 return -EFAULT; 10140 } 10141 if (meta.ref_obj_id) { 10142 verbose(env, "verifier internal error: meta.ref_obj_id already set\n"); 10143 return -EFAULT; 10144 } 10145 10146 id = dynptr_id(env, reg); 10147 if (id < 0) { 10148 verbose(env, "verifier internal error: failed to obtain dynptr id\n"); 10149 return id; 10150 } 10151 10152 ref_obj_id = dynptr_ref_obj_id(env, reg); 10153 if (ref_obj_id < 0) { 10154 verbose(env, "verifier internal error: failed to obtain dynptr ref_obj_id\n"); 10155 return ref_obj_id; 10156 } 10157 10158 meta.dynptr_id = id; 10159 meta.ref_obj_id = ref_obj_id; 10160 10161 break; 10162 } 10163 case BPF_FUNC_dynptr_write: 10164 { 10165 enum bpf_dynptr_type dynptr_type; 10166 struct bpf_reg_state *reg; 10167 10168 reg = get_dynptr_arg_reg(env, fn, regs); 10169 if (!reg) 10170 return -EFAULT; 10171 10172 dynptr_type = dynptr_get_type(env, reg); 10173 if (dynptr_type == BPF_DYNPTR_TYPE_INVALID) 10174 return -EFAULT; 10175 10176 if (dynptr_type == BPF_DYNPTR_TYPE_SKB) 10177 /* this will trigger clear_all_pkt_pointers(), which will 10178 * invalidate all dynptr slices associated with the skb 10179 */ 10180 changes_data = true; 10181 10182 break; 10183 } 10184 case BPF_FUNC_user_ringbuf_drain: 10185 err = push_callback_call(env, insn, insn_idx, meta.subprogno, 10186 set_user_ringbuf_callback_state); 10187 break; 10188 } 10189 10190 if (err) 10191 return err; 10192 10193 /* reset caller saved regs */ 10194 for (i = 0; i < CALLER_SAVED_REGS; i++) { 10195 mark_reg_not_init(env, regs, caller_saved[i]); 10196 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK); 10197 } 10198 10199 /* helper call returns 64-bit value. */ 10200 regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG; 10201 10202 /* update return register (already marked as written above) */ 10203 ret_type = fn->ret_type; 10204 ret_flag = type_flag(ret_type); 10205 10206 switch (base_type(ret_type)) { 10207 case RET_INTEGER: 10208 /* sets type to SCALAR_VALUE */ 10209 mark_reg_unknown(env, regs, BPF_REG_0); 10210 break; 10211 case RET_VOID: 10212 regs[BPF_REG_0].type = NOT_INIT; 10213 break; 10214 case RET_PTR_TO_MAP_VALUE: 10215 /* There is no offset yet applied, variable or fixed */ 10216 mark_reg_known_zero(env, regs, BPF_REG_0); 10217 /* remember map_ptr, so that check_map_access() 10218 * can check 'value_size' boundary of memory access 10219 * to map element returned from bpf_map_lookup_elem() 10220 */ 10221 if (meta.map_ptr == NULL) { 10222 verbose(env, 10223 "kernel subsystem misconfigured verifier\n"); 10224 return -EINVAL; 10225 } 10226 regs[BPF_REG_0].map_ptr = meta.map_ptr; 10227 regs[BPF_REG_0].map_uid = meta.map_uid; 10228 regs[BPF_REG_0].type = PTR_TO_MAP_VALUE | ret_flag; 10229 if (!type_may_be_null(ret_type) && 10230 btf_record_has_field(meta.map_ptr->record, BPF_SPIN_LOCK)) { 10231 regs[BPF_REG_0].id = ++env->id_gen; 10232 } 10233 break; 10234 case RET_PTR_TO_SOCKET: 10235 mark_reg_known_zero(env, regs, BPF_REG_0); 10236 regs[BPF_REG_0].type = PTR_TO_SOCKET | ret_flag; 10237 break; 10238 case RET_PTR_TO_SOCK_COMMON: 10239 mark_reg_known_zero(env, regs, BPF_REG_0); 10240 regs[BPF_REG_0].type = PTR_TO_SOCK_COMMON | ret_flag; 10241 break; 10242 case RET_PTR_TO_TCP_SOCK: 10243 mark_reg_known_zero(env, regs, BPF_REG_0); 10244 regs[BPF_REG_0].type = PTR_TO_TCP_SOCK | ret_flag; 10245 break; 10246 case RET_PTR_TO_MEM: 10247 mark_reg_known_zero(env, regs, BPF_REG_0); 10248 regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag; 10249 regs[BPF_REG_0].mem_size = meta.mem_size; 10250 break; 10251 case RET_PTR_TO_MEM_OR_BTF_ID: 10252 { 10253 const struct btf_type *t; 10254 10255 mark_reg_known_zero(env, regs, BPF_REG_0); 10256 t = btf_type_skip_modifiers(meta.ret_btf, meta.ret_btf_id, NULL); 10257 if (!btf_type_is_struct(t)) { 10258 u32 tsize; 10259 const struct btf_type *ret; 10260 const char *tname; 10261 10262 /* resolve the type size of ksym. */ 10263 ret = btf_resolve_size(meta.ret_btf, t, &tsize); 10264 if (IS_ERR(ret)) { 10265 tname = btf_name_by_offset(meta.ret_btf, t->name_off); 10266 verbose(env, "unable to resolve the size of type '%s': %ld\n", 10267 tname, PTR_ERR(ret)); 10268 return -EINVAL; 10269 } 10270 regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag; 10271 regs[BPF_REG_0].mem_size = tsize; 10272 } else { 10273 /* MEM_RDONLY may be carried from ret_flag, but it 10274 * doesn't apply on PTR_TO_BTF_ID. Fold it, otherwise 10275 * it will confuse the check of PTR_TO_BTF_ID in 10276 * check_mem_access(). 10277 */ 10278 ret_flag &= ~MEM_RDONLY; 10279 10280 regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag; 10281 regs[BPF_REG_0].btf = meta.ret_btf; 10282 regs[BPF_REG_0].btf_id = meta.ret_btf_id; 10283 } 10284 break; 10285 } 10286 case RET_PTR_TO_BTF_ID: 10287 { 10288 struct btf *ret_btf; 10289 int ret_btf_id; 10290 10291 mark_reg_known_zero(env, regs, BPF_REG_0); 10292 regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag; 10293 if (func_id == BPF_FUNC_kptr_xchg) { 10294 ret_btf = meta.kptr_field->kptr.btf; 10295 ret_btf_id = meta.kptr_field->kptr.btf_id; 10296 if (!btf_is_kernel(ret_btf)) 10297 regs[BPF_REG_0].type |= MEM_ALLOC; 10298 } else { 10299 if (fn->ret_btf_id == BPF_PTR_POISON) { 10300 verbose(env, "verifier internal error:"); 10301 verbose(env, "func %s has non-overwritten BPF_PTR_POISON return type\n", 10302 func_id_name(func_id)); 10303 return -EINVAL; 10304 } 10305 ret_btf = btf_vmlinux; 10306 ret_btf_id = *fn->ret_btf_id; 10307 } 10308 if (ret_btf_id == 0) { 10309 verbose(env, "invalid return type %u of func %s#%d\n", 10310 base_type(ret_type), func_id_name(func_id), 10311 func_id); 10312 return -EINVAL; 10313 } 10314 regs[BPF_REG_0].btf = ret_btf; 10315 regs[BPF_REG_0].btf_id = ret_btf_id; 10316 break; 10317 } 10318 default: 10319 verbose(env, "unknown return type %u of func %s#%d\n", 10320 base_type(ret_type), func_id_name(func_id), func_id); 10321 return -EINVAL; 10322 } 10323 10324 if (type_may_be_null(regs[BPF_REG_0].type)) 10325 regs[BPF_REG_0].id = ++env->id_gen; 10326 10327 if (helper_multiple_ref_obj_use(func_id, meta.map_ptr)) { 10328 verbose(env, "verifier internal error: func %s#%d sets ref_obj_id more than once\n", 10329 func_id_name(func_id), func_id); 10330 return -EFAULT; 10331 } 10332 10333 if (is_dynptr_ref_function(func_id)) 10334 regs[BPF_REG_0].dynptr_id = meta.dynptr_id; 10335 10336 if (is_ptr_cast_function(func_id) || is_dynptr_ref_function(func_id)) { 10337 /* For release_reference() */ 10338 regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id; 10339 } else if (is_acquire_function(func_id, meta.map_ptr)) { 10340 int id = acquire_reference_state(env, insn_idx); 10341 10342 if (id < 0) 10343 return id; 10344 /* For mark_ptr_or_null_reg() */ 10345 regs[BPF_REG_0].id = id; 10346 /* For release_reference() */ 10347 regs[BPF_REG_0].ref_obj_id = id; 10348 } 10349 10350 do_refine_retval_range(regs, fn->ret_type, func_id, &meta); 10351 10352 err = check_map_func_compatibility(env, meta.map_ptr, func_id); 10353 if (err) 10354 return err; 10355 10356 if ((func_id == BPF_FUNC_get_stack || 10357 func_id == BPF_FUNC_get_task_stack) && 10358 !env->prog->has_callchain_buf) { 10359 const char *err_str; 10360 10361 #ifdef CONFIG_PERF_EVENTS 10362 err = get_callchain_buffers(sysctl_perf_event_max_stack); 10363 err_str = "cannot get callchain buffer for func %s#%d\n"; 10364 #else 10365 err = -ENOTSUPP; 10366 err_str = "func %s#%d not supported without CONFIG_PERF_EVENTS\n"; 10367 #endif 10368 if (err) { 10369 verbose(env, err_str, func_id_name(func_id), func_id); 10370 return err; 10371 } 10372 10373 env->prog->has_callchain_buf = true; 10374 } 10375 10376 if (func_id == BPF_FUNC_get_stackid || func_id == BPF_FUNC_get_stack) 10377 env->prog->call_get_stack = true; 10378 10379 if (func_id == BPF_FUNC_get_func_ip) { 10380 if (check_get_func_ip(env)) 10381 return -ENOTSUPP; 10382 env->prog->call_get_func_ip = true; 10383 } 10384 10385 if (changes_data) 10386 clear_all_pkt_pointers(env); 10387 return 0; 10388 } 10389 10390 /* mark_btf_func_reg_size() is used when the reg size is determined by 10391 * the BTF func_proto's return value size and argument. 10392 */ 10393 static void mark_btf_func_reg_size(struct bpf_verifier_env *env, u32 regno, 10394 size_t reg_size) 10395 { 10396 struct bpf_reg_state *reg = &cur_regs(env)[regno]; 10397 10398 if (regno == BPF_REG_0) { 10399 /* Function return value */ 10400 reg->live |= REG_LIVE_WRITTEN; 10401 reg->subreg_def = reg_size == sizeof(u64) ? 10402 DEF_NOT_SUBREG : env->insn_idx + 1; 10403 } else { 10404 /* Function argument */ 10405 if (reg_size == sizeof(u64)) { 10406 mark_insn_zext(env, reg); 10407 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64); 10408 } else { 10409 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ32); 10410 } 10411 } 10412 } 10413 10414 static bool is_kfunc_acquire(struct bpf_kfunc_call_arg_meta *meta) 10415 { 10416 return meta->kfunc_flags & KF_ACQUIRE; 10417 } 10418 10419 static bool is_kfunc_release(struct bpf_kfunc_call_arg_meta *meta) 10420 { 10421 return meta->kfunc_flags & KF_RELEASE; 10422 } 10423 10424 static bool is_kfunc_trusted_args(struct bpf_kfunc_call_arg_meta *meta) 10425 { 10426 return (meta->kfunc_flags & KF_TRUSTED_ARGS) || is_kfunc_release(meta); 10427 } 10428 10429 static bool is_kfunc_sleepable(struct bpf_kfunc_call_arg_meta *meta) 10430 { 10431 return meta->kfunc_flags & KF_SLEEPABLE; 10432 } 10433 10434 static bool is_kfunc_destructive(struct bpf_kfunc_call_arg_meta *meta) 10435 { 10436 return meta->kfunc_flags & KF_DESTRUCTIVE; 10437 } 10438 10439 static bool is_kfunc_rcu(struct bpf_kfunc_call_arg_meta *meta) 10440 { 10441 return meta->kfunc_flags & KF_RCU; 10442 } 10443 10444 static bool __kfunc_param_match_suffix(const struct btf *btf, 10445 const struct btf_param *arg, 10446 const char *suffix) 10447 { 10448 int suffix_len = strlen(suffix), len; 10449 const char *param_name; 10450 10451 /* In the future, this can be ported to use BTF tagging */ 10452 param_name = btf_name_by_offset(btf, arg->name_off); 10453 if (str_is_empty(param_name)) 10454 return false; 10455 len = strlen(param_name); 10456 if (len < suffix_len) 10457 return false; 10458 param_name += len - suffix_len; 10459 return !strncmp(param_name, suffix, suffix_len); 10460 } 10461 10462 static bool is_kfunc_arg_mem_size(const struct btf *btf, 10463 const struct btf_param *arg, 10464 const struct bpf_reg_state *reg) 10465 { 10466 const struct btf_type *t; 10467 10468 t = btf_type_skip_modifiers(btf, arg->type, NULL); 10469 if (!btf_type_is_scalar(t) || reg->type != SCALAR_VALUE) 10470 return false; 10471 10472 return __kfunc_param_match_suffix(btf, arg, "__sz"); 10473 } 10474 10475 static bool is_kfunc_arg_const_mem_size(const struct btf *btf, 10476 const struct btf_param *arg, 10477 const struct bpf_reg_state *reg) 10478 { 10479 const struct btf_type *t; 10480 10481 t = btf_type_skip_modifiers(btf, arg->type, NULL); 10482 if (!btf_type_is_scalar(t) || reg->type != SCALAR_VALUE) 10483 return false; 10484 10485 return __kfunc_param_match_suffix(btf, arg, "__szk"); 10486 } 10487 10488 static bool is_kfunc_arg_optional(const struct btf *btf, const struct btf_param *arg) 10489 { 10490 return __kfunc_param_match_suffix(btf, arg, "__opt"); 10491 } 10492 10493 static bool is_kfunc_arg_constant(const struct btf *btf, const struct btf_param *arg) 10494 { 10495 return __kfunc_param_match_suffix(btf, arg, "__k"); 10496 } 10497 10498 static bool is_kfunc_arg_ignore(const struct btf *btf, const struct btf_param *arg) 10499 { 10500 return __kfunc_param_match_suffix(btf, arg, "__ign"); 10501 } 10502 10503 static bool is_kfunc_arg_alloc_obj(const struct btf *btf, const struct btf_param *arg) 10504 { 10505 return __kfunc_param_match_suffix(btf, arg, "__alloc"); 10506 } 10507 10508 static bool is_kfunc_arg_uninit(const struct btf *btf, const struct btf_param *arg) 10509 { 10510 return __kfunc_param_match_suffix(btf, arg, "__uninit"); 10511 } 10512 10513 static bool is_kfunc_arg_refcounted_kptr(const struct btf *btf, const struct btf_param *arg) 10514 { 10515 return __kfunc_param_match_suffix(btf, arg, "__refcounted_kptr"); 10516 } 10517 10518 static bool is_kfunc_arg_scalar_with_name(const struct btf *btf, 10519 const struct btf_param *arg, 10520 const char *name) 10521 { 10522 int len, target_len = strlen(name); 10523 const char *param_name; 10524 10525 param_name = btf_name_by_offset(btf, arg->name_off); 10526 if (str_is_empty(param_name)) 10527 return false; 10528 len = strlen(param_name); 10529 if (len != target_len) 10530 return false; 10531 if (strcmp(param_name, name)) 10532 return false; 10533 10534 return true; 10535 } 10536 10537 enum { 10538 KF_ARG_DYNPTR_ID, 10539 KF_ARG_LIST_HEAD_ID, 10540 KF_ARG_LIST_NODE_ID, 10541 KF_ARG_RB_ROOT_ID, 10542 KF_ARG_RB_NODE_ID, 10543 }; 10544 10545 BTF_ID_LIST(kf_arg_btf_ids) 10546 BTF_ID(struct, bpf_dynptr_kern) 10547 BTF_ID(struct, bpf_list_head) 10548 BTF_ID(struct, bpf_list_node) 10549 BTF_ID(struct, bpf_rb_root) 10550 BTF_ID(struct, bpf_rb_node) 10551 10552 static bool __is_kfunc_ptr_arg_type(const struct btf *btf, 10553 const struct btf_param *arg, int type) 10554 { 10555 const struct btf_type *t; 10556 u32 res_id; 10557 10558 t = btf_type_skip_modifiers(btf, arg->type, NULL); 10559 if (!t) 10560 return false; 10561 if (!btf_type_is_ptr(t)) 10562 return false; 10563 t = btf_type_skip_modifiers(btf, t->type, &res_id); 10564 if (!t) 10565 return false; 10566 return btf_types_are_same(btf, res_id, btf_vmlinux, kf_arg_btf_ids[type]); 10567 } 10568 10569 static bool is_kfunc_arg_dynptr(const struct btf *btf, const struct btf_param *arg) 10570 { 10571 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_DYNPTR_ID); 10572 } 10573 10574 static bool is_kfunc_arg_list_head(const struct btf *btf, const struct btf_param *arg) 10575 { 10576 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_LIST_HEAD_ID); 10577 } 10578 10579 static bool is_kfunc_arg_list_node(const struct btf *btf, const struct btf_param *arg) 10580 { 10581 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_LIST_NODE_ID); 10582 } 10583 10584 static bool is_kfunc_arg_rbtree_root(const struct btf *btf, const struct btf_param *arg) 10585 { 10586 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_RB_ROOT_ID); 10587 } 10588 10589 static bool is_kfunc_arg_rbtree_node(const struct btf *btf, const struct btf_param *arg) 10590 { 10591 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_RB_NODE_ID); 10592 } 10593 10594 static bool is_kfunc_arg_callback(struct bpf_verifier_env *env, const struct btf *btf, 10595 const struct btf_param *arg) 10596 { 10597 const struct btf_type *t; 10598 10599 t = btf_type_resolve_func_ptr(btf, arg->type, NULL); 10600 if (!t) 10601 return false; 10602 10603 return true; 10604 } 10605 10606 /* Returns true if struct is composed of scalars, 4 levels of nesting allowed */ 10607 static bool __btf_type_is_scalar_struct(struct bpf_verifier_env *env, 10608 const struct btf *btf, 10609 const struct btf_type *t, int rec) 10610 { 10611 const struct btf_type *member_type; 10612 const struct btf_member *member; 10613 u32 i; 10614 10615 if (!btf_type_is_struct(t)) 10616 return false; 10617 10618 for_each_member(i, t, member) { 10619 const struct btf_array *array; 10620 10621 member_type = btf_type_skip_modifiers(btf, member->type, NULL); 10622 if (btf_type_is_struct(member_type)) { 10623 if (rec >= 3) { 10624 verbose(env, "max struct nesting depth exceeded\n"); 10625 return false; 10626 } 10627 if (!__btf_type_is_scalar_struct(env, btf, member_type, rec + 1)) 10628 return false; 10629 continue; 10630 } 10631 if (btf_type_is_array(member_type)) { 10632 array = btf_array(member_type); 10633 if (!array->nelems) 10634 return false; 10635 member_type = btf_type_skip_modifiers(btf, array->type, NULL); 10636 if (!btf_type_is_scalar(member_type)) 10637 return false; 10638 continue; 10639 } 10640 if (!btf_type_is_scalar(member_type)) 10641 return false; 10642 } 10643 return true; 10644 } 10645 10646 enum kfunc_ptr_arg_type { 10647 KF_ARG_PTR_TO_CTX, 10648 KF_ARG_PTR_TO_ALLOC_BTF_ID, /* Allocated object */ 10649 KF_ARG_PTR_TO_REFCOUNTED_KPTR, /* Refcounted local kptr */ 10650 KF_ARG_PTR_TO_DYNPTR, 10651 KF_ARG_PTR_TO_ITER, 10652 KF_ARG_PTR_TO_LIST_HEAD, 10653 KF_ARG_PTR_TO_LIST_NODE, 10654 KF_ARG_PTR_TO_BTF_ID, /* Also covers reg2btf_ids conversions */ 10655 KF_ARG_PTR_TO_MEM, 10656 KF_ARG_PTR_TO_MEM_SIZE, /* Size derived from next argument, skip it */ 10657 KF_ARG_PTR_TO_CALLBACK, 10658 KF_ARG_PTR_TO_RB_ROOT, 10659 KF_ARG_PTR_TO_RB_NODE, 10660 }; 10661 10662 enum special_kfunc_type { 10663 KF_bpf_obj_new_impl, 10664 KF_bpf_obj_drop_impl, 10665 KF_bpf_refcount_acquire_impl, 10666 KF_bpf_list_push_front_impl, 10667 KF_bpf_list_push_back_impl, 10668 KF_bpf_list_pop_front, 10669 KF_bpf_list_pop_back, 10670 KF_bpf_cast_to_kern_ctx, 10671 KF_bpf_rdonly_cast, 10672 KF_bpf_rcu_read_lock, 10673 KF_bpf_rcu_read_unlock, 10674 KF_bpf_rbtree_remove, 10675 KF_bpf_rbtree_add_impl, 10676 KF_bpf_rbtree_first, 10677 KF_bpf_dynptr_from_skb, 10678 KF_bpf_dynptr_from_xdp, 10679 KF_bpf_dynptr_slice, 10680 KF_bpf_dynptr_slice_rdwr, 10681 KF_bpf_dynptr_clone, 10682 }; 10683 10684 BTF_SET_START(special_kfunc_set) 10685 BTF_ID(func, bpf_obj_new_impl) 10686 BTF_ID(func, bpf_obj_drop_impl) 10687 BTF_ID(func, bpf_refcount_acquire_impl) 10688 BTF_ID(func, bpf_list_push_front_impl) 10689 BTF_ID(func, bpf_list_push_back_impl) 10690 BTF_ID(func, bpf_list_pop_front) 10691 BTF_ID(func, bpf_list_pop_back) 10692 BTF_ID(func, bpf_cast_to_kern_ctx) 10693 BTF_ID(func, bpf_rdonly_cast) 10694 BTF_ID(func, bpf_rbtree_remove) 10695 BTF_ID(func, bpf_rbtree_add_impl) 10696 BTF_ID(func, bpf_rbtree_first) 10697 BTF_ID(func, bpf_dynptr_from_skb) 10698 BTF_ID(func, bpf_dynptr_from_xdp) 10699 BTF_ID(func, bpf_dynptr_slice) 10700 BTF_ID(func, bpf_dynptr_slice_rdwr) 10701 BTF_ID(func, bpf_dynptr_clone) 10702 BTF_SET_END(special_kfunc_set) 10703 10704 BTF_ID_LIST(special_kfunc_list) 10705 BTF_ID(func, bpf_obj_new_impl) 10706 BTF_ID(func, bpf_obj_drop_impl) 10707 BTF_ID(func, bpf_refcount_acquire_impl) 10708 BTF_ID(func, bpf_list_push_front_impl) 10709 BTF_ID(func, bpf_list_push_back_impl) 10710 BTF_ID(func, bpf_list_pop_front) 10711 BTF_ID(func, bpf_list_pop_back) 10712 BTF_ID(func, bpf_cast_to_kern_ctx) 10713 BTF_ID(func, bpf_rdonly_cast) 10714 BTF_ID(func, bpf_rcu_read_lock) 10715 BTF_ID(func, bpf_rcu_read_unlock) 10716 BTF_ID(func, bpf_rbtree_remove) 10717 BTF_ID(func, bpf_rbtree_add_impl) 10718 BTF_ID(func, bpf_rbtree_first) 10719 BTF_ID(func, bpf_dynptr_from_skb) 10720 BTF_ID(func, bpf_dynptr_from_xdp) 10721 BTF_ID(func, bpf_dynptr_slice) 10722 BTF_ID(func, bpf_dynptr_slice_rdwr) 10723 BTF_ID(func, bpf_dynptr_clone) 10724 10725 static bool is_kfunc_ret_null(struct bpf_kfunc_call_arg_meta *meta) 10726 { 10727 if (meta->func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl] && 10728 meta->arg_owning_ref) { 10729 return false; 10730 } 10731 10732 return meta->kfunc_flags & KF_RET_NULL; 10733 } 10734 10735 static bool is_kfunc_bpf_rcu_read_lock(struct bpf_kfunc_call_arg_meta *meta) 10736 { 10737 return meta->func_id == special_kfunc_list[KF_bpf_rcu_read_lock]; 10738 } 10739 10740 static bool is_kfunc_bpf_rcu_read_unlock(struct bpf_kfunc_call_arg_meta *meta) 10741 { 10742 return meta->func_id == special_kfunc_list[KF_bpf_rcu_read_unlock]; 10743 } 10744 10745 static enum kfunc_ptr_arg_type 10746 get_kfunc_ptr_arg_type(struct bpf_verifier_env *env, 10747 struct bpf_kfunc_call_arg_meta *meta, 10748 const struct btf_type *t, const struct btf_type *ref_t, 10749 const char *ref_tname, const struct btf_param *args, 10750 int argno, int nargs) 10751 { 10752 u32 regno = argno + 1; 10753 struct bpf_reg_state *regs = cur_regs(env); 10754 struct bpf_reg_state *reg = ®s[regno]; 10755 bool arg_mem_size = false; 10756 10757 if (meta->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx]) 10758 return KF_ARG_PTR_TO_CTX; 10759 10760 /* In this function, we verify the kfunc's BTF as per the argument type, 10761 * leaving the rest of the verification with respect to the register 10762 * type to our caller. When a set of conditions hold in the BTF type of 10763 * arguments, we resolve it to a known kfunc_ptr_arg_type. 10764 */ 10765 if (btf_get_prog_ctx_type(&env->log, meta->btf, t, resolve_prog_type(env->prog), argno)) 10766 return KF_ARG_PTR_TO_CTX; 10767 10768 if (is_kfunc_arg_alloc_obj(meta->btf, &args[argno])) 10769 return KF_ARG_PTR_TO_ALLOC_BTF_ID; 10770 10771 if (is_kfunc_arg_refcounted_kptr(meta->btf, &args[argno])) 10772 return KF_ARG_PTR_TO_REFCOUNTED_KPTR; 10773 10774 if (is_kfunc_arg_dynptr(meta->btf, &args[argno])) 10775 return KF_ARG_PTR_TO_DYNPTR; 10776 10777 if (is_kfunc_arg_iter(meta, argno)) 10778 return KF_ARG_PTR_TO_ITER; 10779 10780 if (is_kfunc_arg_list_head(meta->btf, &args[argno])) 10781 return KF_ARG_PTR_TO_LIST_HEAD; 10782 10783 if (is_kfunc_arg_list_node(meta->btf, &args[argno])) 10784 return KF_ARG_PTR_TO_LIST_NODE; 10785 10786 if (is_kfunc_arg_rbtree_root(meta->btf, &args[argno])) 10787 return KF_ARG_PTR_TO_RB_ROOT; 10788 10789 if (is_kfunc_arg_rbtree_node(meta->btf, &args[argno])) 10790 return KF_ARG_PTR_TO_RB_NODE; 10791 10792 if ((base_type(reg->type) == PTR_TO_BTF_ID || reg2btf_ids[base_type(reg->type)])) { 10793 if (!btf_type_is_struct(ref_t)) { 10794 verbose(env, "kernel function %s args#%d pointer type %s %s is not supported\n", 10795 meta->func_name, argno, btf_type_str(ref_t), ref_tname); 10796 return -EINVAL; 10797 } 10798 return KF_ARG_PTR_TO_BTF_ID; 10799 } 10800 10801 if (is_kfunc_arg_callback(env, meta->btf, &args[argno])) 10802 return KF_ARG_PTR_TO_CALLBACK; 10803 10804 10805 if (argno + 1 < nargs && 10806 (is_kfunc_arg_mem_size(meta->btf, &args[argno + 1], ®s[regno + 1]) || 10807 is_kfunc_arg_const_mem_size(meta->btf, &args[argno + 1], ®s[regno + 1]))) 10808 arg_mem_size = true; 10809 10810 /* This is the catch all argument type of register types supported by 10811 * check_helper_mem_access. However, we only allow when argument type is 10812 * pointer to scalar, or struct composed (recursively) of scalars. When 10813 * arg_mem_size is true, the pointer can be void *. 10814 */ 10815 if (!btf_type_is_scalar(ref_t) && !__btf_type_is_scalar_struct(env, meta->btf, ref_t, 0) && 10816 (arg_mem_size ? !btf_type_is_void(ref_t) : 1)) { 10817 verbose(env, "arg#%d pointer type %s %s must point to %sscalar, or struct with scalar\n", 10818 argno, btf_type_str(ref_t), ref_tname, arg_mem_size ? "void, " : ""); 10819 return -EINVAL; 10820 } 10821 return arg_mem_size ? KF_ARG_PTR_TO_MEM_SIZE : KF_ARG_PTR_TO_MEM; 10822 } 10823 10824 static int process_kf_arg_ptr_to_btf_id(struct bpf_verifier_env *env, 10825 struct bpf_reg_state *reg, 10826 const struct btf_type *ref_t, 10827 const char *ref_tname, u32 ref_id, 10828 struct bpf_kfunc_call_arg_meta *meta, 10829 int argno) 10830 { 10831 const struct btf_type *reg_ref_t; 10832 bool strict_type_match = false; 10833 const struct btf *reg_btf; 10834 const char *reg_ref_tname; 10835 u32 reg_ref_id; 10836 10837 if (base_type(reg->type) == PTR_TO_BTF_ID) { 10838 reg_btf = reg->btf; 10839 reg_ref_id = reg->btf_id; 10840 } else { 10841 reg_btf = btf_vmlinux; 10842 reg_ref_id = *reg2btf_ids[base_type(reg->type)]; 10843 } 10844 10845 /* Enforce strict type matching for calls to kfuncs that are acquiring 10846 * or releasing a reference, or are no-cast aliases. We do _not_ 10847 * enforce strict matching for plain KF_TRUSTED_ARGS kfuncs by default, 10848 * as we want to enable BPF programs to pass types that are bitwise 10849 * equivalent without forcing them to explicitly cast with something 10850 * like bpf_cast_to_kern_ctx(). 10851 * 10852 * For example, say we had a type like the following: 10853 * 10854 * struct bpf_cpumask { 10855 * cpumask_t cpumask; 10856 * refcount_t usage; 10857 * }; 10858 * 10859 * Note that as specified in <linux/cpumask.h>, cpumask_t is typedef'ed 10860 * to a struct cpumask, so it would be safe to pass a struct 10861 * bpf_cpumask * to a kfunc expecting a struct cpumask *. 10862 * 10863 * The philosophy here is similar to how we allow scalars of different 10864 * types to be passed to kfuncs as long as the size is the same. The 10865 * only difference here is that we're simply allowing 10866 * btf_struct_ids_match() to walk the struct at the 0th offset, and 10867 * resolve types. 10868 */ 10869 if (is_kfunc_acquire(meta) || 10870 (is_kfunc_release(meta) && reg->ref_obj_id) || 10871 btf_type_ids_nocast_alias(&env->log, reg_btf, reg_ref_id, meta->btf, ref_id)) 10872 strict_type_match = true; 10873 10874 WARN_ON_ONCE(is_kfunc_trusted_args(meta) && reg->off); 10875 10876 reg_ref_t = btf_type_skip_modifiers(reg_btf, reg_ref_id, ®_ref_id); 10877 reg_ref_tname = btf_name_by_offset(reg_btf, reg_ref_t->name_off); 10878 if (!btf_struct_ids_match(&env->log, reg_btf, reg_ref_id, reg->off, meta->btf, ref_id, strict_type_match)) { 10879 verbose(env, "kernel function %s args#%d expected pointer to %s %s but R%d has a pointer to %s %s\n", 10880 meta->func_name, argno, btf_type_str(ref_t), ref_tname, argno + 1, 10881 btf_type_str(reg_ref_t), reg_ref_tname); 10882 return -EINVAL; 10883 } 10884 return 0; 10885 } 10886 10887 static int ref_set_non_owning(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 10888 { 10889 struct bpf_verifier_state *state = env->cur_state; 10890 struct btf_record *rec = reg_btf_record(reg); 10891 10892 if (!state->active_lock.ptr) { 10893 verbose(env, "verifier internal error: ref_set_non_owning w/o active lock\n"); 10894 return -EFAULT; 10895 } 10896 10897 if (type_flag(reg->type) & NON_OWN_REF) { 10898 verbose(env, "verifier internal error: NON_OWN_REF already set\n"); 10899 return -EFAULT; 10900 } 10901 10902 reg->type |= NON_OWN_REF; 10903 if (rec->refcount_off >= 0) 10904 reg->type |= MEM_RCU; 10905 10906 return 0; 10907 } 10908 10909 static int ref_convert_owning_non_owning(struct bpf_verifier_env *env, u32 ref_obj_id) 10910 { 10911 struct bpf_func_state *state, *unused; 10912 struct bpf_reg_state *reg; 10913 int i; 10914 10915 state = cur_func(env); 10916 10917 if (!ref_obj_id) { 10918 verbose(env, "verifier internal error: ref_obj_id is zero for " 10919 "owning -> non-owning conversion\n"); 10920 return -EFAULT; 10921 } 10922 10923 for (i = 0; i < state->acquired_refs; i++) { 10924 if (state->refs[i].id != ref_obj_id) 10925 continue; 10926 10927 /* Clear ref_obj_id here so release_reference doesn't clobber 10928 * the whole reg 10929 */ 10930 bpf_for_each_reg_in_vstate(env->cur_state, unused, reg, ({ 10931 if (reg->ref_obj_id == ref_obj_id) { 10932 reg->ref_obj_id = 0; 10933 ref_set_non_owning(env, reg); 10934 } 10935 })); 10936 return 0; 10937 } 10938 10939 verbose(env, "verifier internal error: ref state missing for ref_obj_id\n"); 10940 return -EFAULT; 10941 } 10942 10943 /* Implementation details: 10944 * 10945 * Each register points to some region of memory, which we define as an 10946 * allocation. Each allocation may embed a bpf_spin_lock which protects any 10947 * special BPF objects (bpf_list_head, bpf_rb_root, etc.) part of the same 10948 * allocation. The lock and the data it protects are colocated in the same 10949 * memory region. 10950 * 10951 * Hence, everytime a register holds a pointer value pointing to such 10952 * allocation, the verifier preserves a unique reg->id for it. 10953 * 10954 * The verifier remembers the lock 'ptr' and the lock 'id' whenever 10955 * bpf_spin_lock is called. 10956 * 10957 * To enable this, lock state in the verifier captures two values: 10958 * active_lock.ptr = Register's type specific pointer 10959 * active_lock.id = A unique ID for each register pointer value 10960 * 10961 * Currently, PTR_TO_MAP_VALUE and PTR_TO_BTF_ID | MEM_ALLOC are the two 10962 * supported register types. 10963 * 10964 * The active_lock.ptr in case of map values is the reg->map_ptr, and in case of 10965 * allocated objects is the reg->btf pointer. 10966 * 10967 * The active_lock.id is non-unique for maps supporting direct_value_addr, as we 10968 * can establish the provenance of the map value statically for each distinct 10969 * lookup into such maps. They always contain a single map value hence unique 10970 * IDs for each pseudo load pessimizes the algorithm and rejects valid programs. 10971 * 10972 * So, in case of global variables, they use array maps with max_entries = 1, 10973 * hence their active_lock.ptr becomes map_ptr and id = 0 (since they all point 10974 * into the same map value as max_entries is 1, as described above). 10975 * 10976 * In case of inner map lookups, the inner map pointer has same map_ptr as the 10977 * outer map pointer (in verifier context), but each lookup into an inner map 10978 * assigns a fresh reg->id to the lookup, so while lookups into distinct inner 10979 * maps from the same outer map share the same map_ptr as active_lock.ptr, they 10980 * will get different reg->id assigned to each lookup, hence different 10981 * active_lock.id. 10982 * 10983 * In case of allocated objects, active_lock.ptr is the reg->btf, and the 10984 * reg->id is a unique ID preserved after the NULL pointer check on the pointer 10985 * returned from bpf_obj_new. Each allocation receives a new reg->id. 10986 */ 10987 static int check_reg_allocation_locked(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 10988 { 10989 void *ptr; 10990 u32 id; 10991 10992 switch ((int)reg->type) { 10993 case PTR_TO_MAP_VALUE: 10994 ptr = reg->map_ptr; 10995 break; 10996 case PTR_TO_BTF_ID | MEM_ALLOC: 10997 ptr = reg->btf; 10998 break; 10999 default: 11000 verbose(env, "verifier internal error: unknown reg type for lock check\n"); 11001 return -EFAULT; 11002 } 11003 id = reg->id; 11004 11005 if (!env->cur_state->active_lock.ptr) 11006 return -EINVAL; 11007 if (env->cur_state->active_lock.ptr != ptr || 11008 env->cur_state->active_lock.id != id) { 11009 verbose(env, "held lock and object are not in the same allocation\n"); 11010 return -EINVAL; 11011 } 11012 return 0; 11013 } 11014 11015 static bool is_bpf_list_api_kfunc(u32 btf_id) 11016 { 11017 return btf_id == special_kfunc_list[KF_bpf_list_push_front_impl] || 11018 btf_id == special_kfunc_list[KF_bpf_list_push_back_impl] || 11019 btf_id == special_kfunc_list[KF_bpf_list_pop_front] || 11020 btf_id == special_kfunc_list[KF_bpf_list_pop_back]; 11021 } 11022 11023 static bool is_bpf_rbtree_api_kfunc(u32 btf_id) 11024 { 11025 return btf_id == special_kfunc_list[KF_bpf_rbtree_add_impl] || 11026 btf_id == special_kfunc_list[KF_bpf_rbtree_remove] || 11027 btf_id == special_kfunc_list[KF_bpf_rbtree_first]; 11028 } 11029 11030 static bool is_bpf_graph_api_kfunc(u32 btf_id) 11031 { 11032 return is_bpf_list_api_kfunc(btf_id) || is_bpf_rbtree_api_kfunc(btf_id) || 11033 btf_id == special_kfunc_list[KF_bpf_refcount_acquire_impl]; 11034 } 11035 11036 static bool is_sync_callback_calling_kfunc(u32 btf_id) 11037 { 11038 return btf_id == special_kfunc_list[KF_bpf_rbtree_add_impl]; 11039 } 11040 11041 static bool is_rbtree_lock_required_kfunc(u32 btf_id) 11042 { 11043 return is_bpf_rbtree_api_kfunc(btf_id); 11044 } 11045 11046 static bool check_kfunc_is_graph_root_api(struct bpf_verifier_env *env, 11047 enum btf_field_type head_field_type, 11048 u32 kfunc_btf_id) 11049 { 11050 bool ret; 11051 11052 switch (head_field_type) { 11053 case BPF_LIST_HEAD: 11054 ret = is_bpf_list_api_kfunc(kfunc_btf_id); 11055 break; 11056 case BPF_RB_ROOT: 11057 ret = is_bpf_rbtree_api_kfunc(kfunc_btf_id); 11058 break; 11059 default: 11060 verbose(env, "verifier internal error: unexpected graph root argument type %s\n", 11061 btf_field_type_name(head_field_type)); 11062 return false; 11063 } 11064 11065 if (!ret) 11066 verbose(env, "verifier internal error: %s head arg for unknown kfunc\n", 11067 btf_field_type_name(head_field_type)); 11068 return ret; 11069 } 11070 11071 static bool check_kfunc_is_graph_node_api(struct bpf_verifier_env *env, 11072 enum btf_field_type node_field_type, 11073 u32 kfunc_btf_id) 11074 { 11075 bool ret; 11076 11077 switch (node_field_type) { 11078 case BPF_LIST_NODE: 11079 ret = (kfunc_btf_id == special_kfunc_list[KF_bpf_list_push_front_impl] || 11080 kfunc_btf_id == special_kfunc_list[KF_bpf_list_push_back_impl]); 11081 break; 11082 case BPF_RB_NODE: 11083 ret = (kfunc_btf_id == special_kfunc_list[KF_bpf_rbtree_remove] || 11084 kfunc_btf_id == special_kfunc_list[KF_bpf_rbtree_add_impl]); 11085 break; 11086 default: 11087 verbose(env, "verifier internal error: unexpected graph node argument type %s\n", 11088 btf_field_type_name(node_field_type)); 11089 return false; 11090 } 11091 11092 if (!ret) 11093 verbose(env, "verifier internal error: %s node arg for unknown kfunc\n", 11094 btf_field_type_name(node_field_type)); 11095 return ret; 11096 } 11097 11098 static int 11099 __process_kf_arg_ptr_to_graph_root(struct bpf_verifier_env *env, 11100 struct bpf_reg_state *reg, u32 regno, 11101 struct bpf_kfunc_call_arg_meta *meta, 11102 enum btf_field_type head_field_type, 11103 struct btf_field **head_field) 11104 { 11105 const char *head_type_name; 11106 struct btf_field *field; 11107 struct btf_record *rec; 11108 u32 head_off; 11109 11110 if (meta->btf != btf_vmlinux) { 11111 verbose(env, "verifier internal error: unexpected btf mismatch in kfunc call\n"); 11112 return -EFAULT; 11113 } 11114 11115 if (!check_kfunc_is_graph_root_api(env, head_field_type, meta->func_id)) 11116 return -EFAULT; 11117 11118 head_type_name = btf_field_type_name(head_field_type); 11119 if (!tnum_is_const(reg->var_off)) { 11120 verbose(env, 11121 "R%d doesn't have constant offset. %s has to be at the constant offset\n", 11122 regno, head_type_name); 11123 return -EINVAL; 11124 } 11125 11126 rec = reg_btf_record(reg); 11127 head_off = reg->off + reg->var_off.value; 11128 field = btf_record_find(rec, head_off, head_field_type); 11129 if (!field) { 11130 verbose(env, "%s not found at offset=%u\n", head_type_name, head_off); 11131 return -EINVAL; 11132 } 11133 11134 /* All functions require bpf_list_head to be protected using a bpf_spin_lock */ 11135 if (check_reg_allocation_locked(env, reg)) { 11136 verbose(env, "bpf_spin_lock at off=%d must be held for %s\n", 11137 rec->spin_lock_off, head_type_name); 11138 return -EINVAL; 11139 } 11140 11141 if (*head_field) { 11142 verbose(env, "verifier internal error: repeating %s arg\n", head_type_name); 11143 return -EFAULT; 11144 } 11145 *head_field = field; 11146 return 0; 11147 } 11148 11149 static int process_kf_arg_ptr_to_list_head(struct bpf_verifier_env *env, 11150 struct bpf_reg_state *reg, u32 regno, 11151 struct bpf_kfunc_call_arg_meta *meta) 11152 { 11153 return __process_kf_arg_ptr_to_graph_root(env, reg, regno, meta, BPF_LIST_HEAD, 11154 &meta->arg_list_head.field); 11155 } 11156 11157 static int process_kf_arg_ptr_to_rbtree_root(struct bpf_verifier_env *env, 11158 struct bpf_reg_state *reg, u32 regno, 11159 struct bpf_kfunc_call_arg_meta *meta) 11160 { 11161 return __process_kf_arg_ptr_to_graph_root(env, reg, regno, meta, BPF_RB_ROOT, 11162 &meta->arg_rbtree_root.field); 11163 } 11164 11165 static int 11166 __process_kf_arg_ptr_to_graph_node(struct bpf_verifier_env *env, 11167 struct bpf_reg_state *reg, u32 regno, 11168 struct bpf_kfunc_call_arg_meta *meta, 11169 enum btf_field_type head_field_type, 11170 enum btf_field_type node_field_type, 11171 struct btf_field **node_field) 11172 { 11173 const char *node_type_name; 11174 const struct btf_type *et, *t; 11175 struct btf_field *field; 11176 u32 node_off; 11177 11178 if (meta->btf != btf_vmlinux) { 11179 verbose(env, "verifier internal error: unexpected btf mismatch in kfunc call\n"); 11180 return -EFAULT; 11181 } 11182 11183 if (!check_kfunc_is_graph_node_api(env, node_field_type, meta->func_id)) 11184 return -EFAULT; 11185 11186 node_type_name = btf_field_type_name(node_field_type); 11187 if (!tnum_is_const(reg->var_off)) { 11188 verbose(env, 11189 "R%d doesn't have constant offset. %s has to be at the constant offset\n", 11190 regno, node_type_name); 11191 return -EINVAL; 11192 } 11193 11194 node_off = reg->off + reg->var_off.value; 11195 field = reg_find_field_offset(reg, node_off, node_field_type); 11196 if (!field || field->offset != node_off) { 11197 verbose(env, "%s not found at offset=%u\n", node_type_name, node_off); 11198 return -EINVAL; 11199 } 11200 11201 field = *node_field; 11202 11203 et = btf_type_by_id(field->graph_root.btf, field->graph_root.value_btf_id); 11204 t = btf_type_by_id(reg->btf, reg->btf_id); 11205 if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, 0, field->graph_root.btf, 11206 field->graph_root.value_btf_id, true)) { 11207 verbose(env, "operation on %s expects arg#1 %s at offset=%d " 11208 "in struct %s, but arg is at offset=%d in struct %s\n", 11209 btf_field_type_name(head_field_type), 11210 btf_field_type_name(node_field_type), 11211 field->graph_root.node_offset, 11212 btf_name_by_offset(field->graph_root.btf, et->name_off), 11213 node_off, btf_name_by_offset(reg->btf, t->name_off)); 11214 return -EINVAL; 11215 } 11216 meta->arg_btf = reg->btf; 11217 meta->arg_btf_id = reg->btf_id; 11218 11219 if (node_off != field->graph_root.node_offset) { 11220 verbose(env, "arg#1 offset=%d, but expected %s at offset=%d in struct %s\n", 11221 node_off, btf_field_type_name(node_field_type), 11222 field->graph_root.node_offset, 11223 btf_name_by_offset(field->graph_root.btf, et->name_off)); 11224 return -EINVAL; 11225 } 11226 11227 return 0; 11228 } 11229 11230 static int process_kf_arg_ptr_to_list_node(struct bpf_verifier_env *env, 11231 struct bpf_reg_state *reg, u32 regno, 11232 struct bpf_kfunc_call_arg_meta *meta) 11233 { 11234 return __process_kf_arg_ptr_to_graph_node(env, reg, regno, meta, 11235 BPF_LIST_HEAD, BPF_LIST_NODE, 11236 &meta->arg_list_head.field); 11237 } 11238 11239 static int process_kf_arg_ptr_to_rbtree_node(struct bpf_verifier_env *env, 11240 struct bpf_reg_state *reg, u32 regno, 11241 struct bpf_kfunc_call_arg_meta *meta) 11242 { 11243 return __process_kf_arg_ptr_to_graph_node(env, reg, regno, meta, 11244 BPF_RB_ROOT, BPF_RB_NODE, 11245 &meta->arg_rbtree_root.field); 11246 } 11247 11248 static int check_kfunc_args(struct bpf_verifier_env *env, struct bpf_kfunc_call_arg_meta *meta, 11249 int insn_idx) 11250 { 11251 const char *func_name = meta->func_name, *ref_tname; 11252 const struct btf *btf = meta->btf; 11253 const struct btf_param *args; 11254 struct btf_record *rec; 11255 u32 i, nargs; 11256 int ret; 11257 11258 args = (const struct btf_param *)(meta->func_proto + 1); 11259 nargs = btf_type_vlen(meta->func_proto); 11260 if (nargs > MAX_BPF_FUNC_REG_ARGS) { 11261 verbose(env, "Function %s has %d > %d args\n", func_name, nargs, 11262 MAX_BPF_FUNC_REG_ARGS); 11263 return -EINVAL; 11264 } 11265 11266 /* Check that BTF function arguments match actual types that the 11267 * verifier sees. 11268 */ 11269 for (i = 0; i < nargs; i++) { 11270 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[i + 1]; 11271 const struct btf_type *t, *ref_t, *resolve_ret; 11272 enum bpf_arg_type arg_type = ARG_DONTCARE; 11273 u32 regno = i + 1, ref_id, type_size; 11274 bool is_ret_buf_sz = false; 11275 int kf_arg_type; 11276 11277 t = btf_type_skip_modifiers(btf, args[i].type, NULL); 11278 11279 if (is_kfunc_arg_ignore(btf, &args[i])) 11280 continue; 11281 11282 if (btf_type_is_scalar(t)) { 11283 if (reg->type != SCALAR_VALUE) { 11284 verbose(env, "R%d is not a scalar\n", regno); 11285 return -EINVAL; 11286 } 11287 11288 if (is_kfunc_arg_constant(meta->btf, &args[i])) { 11289 if (meta->arg_constant.found) { 11290 verbose(env, "verifier internal error: only one constant argument permitted\n"); 11291 return -EFAULT; 11292 } 11293 if (!tnum_is_const(reg->var_off)) { 11294 verbose(env, "R%d must be a known constant\n", regno); 11295 return -EINVAL; 11296 } 11297 ret = mark_chain_precision(env, regno); 11298 if (ret < 0) 11299 return ret; 11300 meta->arg_constant.found = true; 11301 meta->arg_constant.value = reg->var_off.value; 11302 } else if (is_kfunc_arg_scalar_with_name(btf, &args[i], "rdonly_buf_size")) { 11303 meta->r0_rdonly = true; 11304 is_ret_buf_sz = true; 11305 } else if (is_kfunc_arg_scalar_with_name(btf, &args[i], "rdwr_buf_size")) { 11306 is_ret_buf_sz = true; 11307 } 11308 11309 if (is_ret_buf_sz) { 11310 if (meta->r0_size) { 11311 verbose(env, "2 or more rdonly/rdwr_buf_size parameters for kfunc"); 11312 return -EINVAL; 11313 } 11314 11315 if (!tnum_is_const(reg->var_off)) { 11316 verbose(env, "R%d is not a const\n", regno); 11317 return -EINVAL; 11318 } 11319 11320 meta->r0_size = reg->var_off.value; 11321 ret = mark_chain_precision(env, regno); 11322 if (ret) 11323 return ret; 11324 } 11325 continue; 11326 } 11327 11328 if (!btf_type_is_ptr(t)) { 11329 verbose(env, "Unrecognized arg#%d type %s\n", i, btf_type_str(t)); 11330 return -EINVAL; 11331 } 11332 11333 if ((is_kfunc_trusted_args(meta) || is_kfunc_rcu(meta)) && 11334 (register_is_null(reg) || type_may_be_null(reg->type))) { 11335 verbose(env, "Possibly NULL pointer passed to trusted arg%d\n", i); 11336 return -EACCES; 11337 } 11338 11339 if (reg->ref_obj_id) { 11340 if (is_kfunc_release(meta) && meta->ref_obj_id) { 11341 verbose(env, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n", 11342 regno, reg->ref_obj_id, 11343 meta->ref_obj_id); 11344 return -EFAULT; 11345 } 11346 meta->ref_obj_id = reg->ref_obj_id; 11347 if (is_kfunc_release(meta)) 11348 meta->release_regno = regno; 11349 } 11350 11351 ref_t = btf_type_skip_modifiers(btf, t->type, &ref_id); 11352 ref_tname = btf_name_by_offset(btf, ref_t->name_off); 11353 11354 kf_arg_type = get_kfunc_ptr_arg_type(env, meta, t, ref_t, ref_tname, args, i, nargs); 11355 if (kf_arg_type < 0) 11356 return kf_arg_type; 11357 11358 switch (kf_arg_type) { 11359 case KF_ARG_PTR_TO_ALLOC_BTF_ID: 11360 case KF_ARG_PTR_TO_BTF_ID: 11361 if (!is_kfunc_trusted_args(meta) && !is_kfunc_rcu(meta)) 11362 break; 11363 11364 if (!is_trusted_reg(reg)) { 11365 if (!is_kfunc_rcu(meta)) { 11366 verbose(env, "R%d must be referenced or trusted\n", regno); 11367 return -EINVAL; 11368 } 11369 if (!is_rcu_reg(reg)) { 11370 verbose(env, "R%d must be a rcu pointer\n", regno); 11371 return -EINVAL; 11372 } 11373 } 11374 11375 fallthrough; 11376 case KF_ARG_PTR_TO_CTX: 11377 /* Trusted arguments have the same offset checks as release arguments */ 11378 arg_type |= OBJ_RELEASE; 11379 break; 11380 case KF_ARG_PTR_TO_DYNPTR: 11381 case KF_ARG_PTR_TO_ITER: 11382 case KF_ARG_PTR_TO_LIST_HEAD: 11383 case KF_ARG_PTR_TO_LIST_NODE: 11384 case KF_ARG_PTR_TO_RB_ROOT: 11385 case KF_ARG_PTR_TO_RB_NODE: 11386 case KF_ARG_PTR_TO_MEM: 11387 case KF_ARG_PTR_TO_MEM_SIZE: 11388 case KF_ARG_PTR_TO_CALLBACK: 11389 case KF_ARG_PTR_TO_REFCOUNTED_KPTR: 11390 /* Trusted by default */ 11391 break; 11392 default: 11393 WARN_ON_ONCE(1); 11394 return -EFAULT; 11395 } 11396 11397 if (is_kfunc_release(meta) && reg->ref_obj_id) 11398 arg_type |= OBJ_RELEASE; 11399 ret = check_func_arg_reg_off(env, reg, regno, arg_type); 11400 if (ret < 0) 11401 return ret; 11402 11403 switch (kf_arg_type) { 11404 case KF_ARG_PTR_TO_CTX: 11405 if (reg->type != PTR_TO_CTX) { 11406 verbose(env, "arg#%d expected pointer to ctx, but got %s\n", i, btf_type_str(t)); 11407 return -EINVAL; 11408 } 11409 11410 if (meta->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx]) { 11411 ret = get_kern_ctx_btf_id(&env->log, resolve_prog_type(env->prog)); 11412 if (ret < 0) 11413 return -EINVAL; 11414 meta->ret_btf_id = ret; 11415 } 11416 break; 11417 case KF_ARG_PTR_TO_ALLOC_BTF_ID: 11418 if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) { 11419 verbose(env, "arg#%d expected pointer to allocated object\n", i); 11420 return -EINVAL; 11421 } 11422 if (!reg->ref_obj_id) { 11423 verbose(env, "allocated object must be referenced\n"); 11424 return -EINVAL; 11425 } 11426 if (meta->btf == btf_vmlinux && 11427 meta->func_id == special_kfunc_list[KF_bpf_obj_drop_impl]) { 11428 meta->arg_btf = reg->btf; 11429 meta->arg_btf_id = reg->btf_id; 11430 } 11431 break; 11432 case KF_ARG_PTR_TO_DYNPTR: 11433 { 11434 enum bpf_arg_type dynptr_arg_type = ARG_PTR_TO_DYNPTR; 11435 int clone_ref_obj_id = 0; 11436 11437 if (reg->type != PTR_TO_STACK && 11438 reg->type != CONST_PTR_TO_DYNPTR) { 11439 verbose(env, "arg#%d expected pointer to stack or dynptr_ptr\n", i); 11440 return -EINVAL; 11441 } 11442 11443 if (reg->type == CONST_PTR_TO_DYNPTR) 11444 dynptr_arg_type |= MEM_RDONLY; 11445 11446 if (is_kfunc_arg_uninit(btf, &args[i])) 11447 dynptr_arg_type |= MEM_UNINIT; 11448 11449 if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_from_skb]) { 11450 dynptr_arg_type |= DYNPTR_TYPE_SKB; 11451 } else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_from_xdp]) { 11452 dynptr_arg_type |= DYNPTR_TYPE_XDP; 11453 } else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_clone] && 11454 (dynptr_arg_type & MEM_UNINIT)) { 11455 enum bpf_dynptr_type parent_type = meta->initialized_dynptr.type; 11456 11457 if (parent_type == BPF_DYNPTR_TYPE_INVALID) { 11458 verbose(env, "verifier internal error: no dynptr type for parent of clone\n"); 11459 return -EFAULT; 11460 } 11461 11462 dynptr_arg_type |= (unsigned int)get_dynptr_type_flag(parent_type); 11463 clone_ref_obj_id = meta->initialized_dynptr.ref_obj_id; 11464 if (dynptr_type_refcounted(parent_type) && !clone_ref_obj_id) { 11465 verbose(env, "verifier internal error: missing ref obj id for parent of clone\n"); 11466 return -EFAULT; 11467 } 11468 } 11469 11470 ret = process_dynptr_func(env, regno, insn_idx, dynptr_arg_type, clone_ref_obj_id); 11471 if (ret < 0) 11472 return ret; 11473 11474 if (!(dynptr_arg_type & MEM_UNINIT)) { 11475 int id = dynptr_id(env, reg); 11476 11477 if (id < 0) { 11478 verbose(env, "verifier internal error: failed to obtain dynptr id\n"); 11479 return id; 11480 } 11481 meta->initialized_dynptr.id = id; 11482 meta->initialized_dynptr.type = dynptr_get_type(env, reg); 11483 meta->initialized_dynptr.ref_obj_id = dynptr_ref_obj_id(env, reg); 11484 } 11485 11486 break; 11487 } 11488 case KF_ARG_PTR_TO_ITER: 11489 ret = process_iter_arg(env, regno, insn_idx, meta); 11490 if (ret < 0) 11491 return ret; 11492 break; 11493 case KF_ARG_PTR_TO_LIST_HEAD: 11494 if (reg->type != PTR_TO_MAP_VALUE && 11495 reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) { 11496 verbose(env, "arg#%d expected pointer to map value or allocated object\n", i); 11497 return -EINVAL; 11498 } 11499 if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC) && !reg->ref_obj_id) { 11500 verbose(env, "allocated object must be referenced\n"); 11501 return -EINVAL; 11502 } 11503 ret = process_kf_arg_ptr_to_list_head(env, reg, regno, meta); 11504 if (ret < 0) 11505 return ret; 11506 break; 11507 case KF_ARG_PTR_TO_RB_ROOT: 11508 if (reg->type != PTR_TO_MAP_VALUE && 11509 reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) { 11510 verbose(env, "arg#%d expected pointer to map value or allocated object\n", i); 11511 return -EINVAL; 11512 } 11513 if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC) && !reg->ref_obj_id) { 11514 verbose(env, "allocated object must be referenced\n"); 11515 return -EINVAL; 11516 } 11517 ret = process_kf_arg_ptr_to_rbtree_root(env, reg, regno, meta); 11518 if (ret < 0) 11519 return ret; 11520 break; 11521 case KF_ARG_PTR_TO_LIST_NODE: 11522 if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) { 11523 verbose(env, "arg#%d expected pointer to allocated object\n", i); 11524 return -EINVAL; 11525 } 11526 if (!reg->ref_obj_id) { 11527 verbose(env, "allocated object must be referenced\n"); 11528 return -EINVAL; 11529 } 11530 ret = process_kf_arg_ptr_to_list_node(env, reg, regno, meta); 11531 if (ret < 0) 11532 return ret; 11533 break; 11534 case KF_ARG_PTR_TO_RB_NODE: 11535 if (meta->func_id == special_kfunc_list[KF_bpf_rbtree_remove]) { 11536 if (!type_is_non_owning_ref(reg->type) || reg->ref_obj_id) { 11537 verbose(env, "rbtree_remove node input must be non-owning ref\n"); 11538 return -EINVAL; 11539 } 11540 if (in_rbtree_lock_required_cb(env)) { 11541 verbose(env, "rbtree_remove not allowed in rbtree cb\n"); 11542 return -EINVAL; 11543 } 11544 } else { 11545 if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) { 11546 verbose(env, "arg#%d expected pointer to allocated object\n", i); 11547 return -EINVAL; 11548 } 11549 if (!reg->ref_obj_id) { 11550 verbose(env, "allocated object must be referenced\n"); 11551 return -EINVAL; 11552 } 11553 } 11554 11555 ret = process_kf_arg_ptr_to_rbtree_node(env, reg, regno, meta); 11556 if (ret < 0) 11557 return ret; 11558 break; 11559 case KF_ARG_PTR_TO_BTF_ID: 11560 /* Only base_type is checked, further checks are done here */ 11561 if ((base_type(reg->type) != PTR_TO_BTF_ID || 11562 (bpf_type_has_unsafe_modifiers(reg->type) && !is_rcu_reg(reg))) && 11563 !reg2btf_ids[base_type(reg->type)]) { 11564 verbose(env, "arg#%d is %s ", i, reg_type_str(env, reg->type)); 11565 verbose(env, "expected %s or socket\n", 11566 reg_type_str(env, base_type(reg->type) | 11567 (type_flag(reg->type) & BPF_REG_TRUSTED_MODIFIERS))); 11568 return -EINVAL; 11569 } 11570 ret = process_kf_arg_ptr_to_btf_id(env, reg, ref_t, ref_tname, ref_id, meta, i); 11571 if (ret < 0) 11572 return ret; 11573 break; 11574 case KF_ARG_PTR_TO_MEM: 11575 resolve_ret = btf_resolve_size(btf, ref_t, &type_size); 11576 if (IS_ERR(resolve_ret)) { 11577 verbose(env, "arg#%d reference type('%s %s') size cannot be determined: %ld\n", 11578 i, btf_type_str(ref_t), ref_tname, PTR_ERR(resolve_ret)); 11579 return -EINVAL; 11580 } 11581 ret = check_mem_reg(env, reg, regno, type_size); 11582 if (ret < 0) 11583 return ret; 11584 break; 11585 case KF_ARG_PTR_TO_MEM_SIZE: 11586 { 11587 struct bpf_reg_state *buff_reg = ®s[regno]; 11588 const struct btf_param *buff_arg = &args[i]; 11589 struct bpf_reg_state *size_reg = ®s[regno + 1]; 11590 const struct btf_param *size_arg = &args[i + 1]; 11591 11592 if (!register_is_null(buff_reg) || !is_kfunc_arg_optional(meta->btf, buff_arg)) { 11593 ret = check_kfunc_mem_size_reg(env, size_reg, regno + 1); 11594 if (ret < 0) { 11595 verbose(env, "arg#%d arg#%d memory, len pair leads to invalid memory access\n", i, i + 1); 11596 return ret; 11597 } 11598 } 11599 11600 if (is_kfunc_arg_const_mem_size(meta->btf, size_arg, size_reg)) { 11601 if (meta->arg_constant.found) { 11602 verbose(env, "verifier internal error: only one constant argument permitted\n"); 11603 return -EFAULT; 11604 } 11605 if (!tnum_is_const(size_reg->var_off)) { 11606 verbose(env, "R%d must be a known constant\n", regno + 1); 11607 return -EINVAL; 11608 } 11609 meta->arg_constant.found = true; 11610 meta->arg_constant.value = size_reg->var_off.value; 11611 } 11612 11613 /* Skip next '__sz' or '__szk' argument */ 11614 i++; 11615 break; 11616 } 11617 case KF_ARG_PTR_TO_CALLBACK: 11618 if (reg->type != PTR_TO_FUNC) { 11619 verbose(env, "arg%d expected pointer to func\n", i); 11620 return -EINVAL; 11621 } 11622 meta->subprogno = reg->subprogno; 11623 break; 11624 case KF_ARG_PTR_TO_REFCOUNTED_KPTR: 11625 if (!type_is_ptr_alloc_obj(reg->type)) { 11626 verbose(env, "arg#%d is neither owning or non-owning ref\n", i); 11627 return -EINVAL; 11628 } 11629 if (!type_is_non_owning_ref(reg->type)) 11630 meta->arg_owning_ref = true; 11631 11632 rec = reg_btf_record(reg); 11633 if (!rec) { 11634 verbose(env, "verifier internal error: Couldn't find btf_record\n"); 11635 return -EFAULT; 11636 } 11637 11638 if (rec->refcount_off < 0) { 11639 verbose(env, "arg#%d doesn't point to a type with bpf_refcount field\n", i); 11640 return -EINVAL; 11641 } 11642 11643 meta->arg_btf = reg->btf; 11644 meta->arg_btf_id = reg->btf_id; 11645 break; 11646 } 11647 } 11648 11649 if (is_kfunc_release(meta) && !meta->release_regno) { 11650 verbose(env, "release kernel function %s expects refcounted PTR_TO_BTF_ID\n", 11651 func_name); 11652 return -EINVAL; 11653 } 11654 11655 return 0; 11656 } 11657 11658 static int fetch_kfunc_meta(struct bpf_verifier_env *env, 11659 struct bpf_insn *insn, 11660 struct bpf_kfunc_call_arg_meta *meta, 11661 const char **kfunc_name) 11662 { 11663 const struct btf_type *func, *func_proto; 11664 u32 func_id, *kfunc_flags; 11665 const char *func_name; 11666 struct btf *desc_btf; 11667 11668 if (kfunc_name) 11669 *kfunc_name = NULL; 11670 11671 if (!insn->imm) 11672 return -EINVAL; 11673 11674 desc_btf = find_kfunc_desc_btf(env, insn->off); 11675 if (IS_ERR(desc_btf)) 11676 return PTR_ERR(desc_btf); 11677 11678 func_id = insn->imm; 11679 func = btf_type_by_id(desc_btf, func_id); 11680 func_name = btf_name_by_offset(desc_btf, func->name_off); 11681 if (kfunc_name) 11682 *kfunc_name = func_name; 11683 func_proto = btf_type_by_id(desc_btf, func->type); 11684 11685 kfunc_flags = btf_kfunc_id_set_contains(desc_btf, func_id, env->prog); 11686 if (!kfunc_flags) { 11687 return -EACCES; 11688 } 11689 11690 memset(meta, 0, sizeof(*meta)); 11691 meta->btf = desc_btf; 11692 meta->func_id = func_id; 11693 meta->kfunc_flags = *kfunc_flags; 11694 meta->func_proto = func_proto; 11695 meta->func_name = func_name; 11696 11697 return 0; 11698 } 11699 11700 static int check_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn, 11701 int *insn_idx_p) 11702 { 11703 const struct btf_type *t, *ptr_type; 11704 u32 i, nargs, ptr_type_id, release_ref_obj_id; 11705 struct bpf_reg_state *regs = cur_regs(env); 11706 const char *func_name, *ptr_type_name; 11707 bool sleepable, rcu_lock, rcu_unlock; 11708 struct bpf_kfunc_call_arg_meta meta; 11709 struct bpf_insn_aux_data *insn_aux; 11710 int err, insn_idx = *insn_idx_p; 11711 const struct btf_param *args; 11712 const struct btf_type *ret_t; 11713 struct btf *desc_btf; 11714 11715 /* skip for now, but return error when we find this in fixup_kfunc_call */ 11716 if (!insn->imm) 11717 return 0; 11718 11719 err = fetch_kfunc_meta(env, insn, &meta, &func_name); 11720 if (err == -EACCES && func_name) 11721 verbose(env, "calling kernel function %s is not allowed\n", func_name); 11722 if (err) 11723 return err; 11724 desc_btf = meta.btf; 11725 insn_aux = &env->insn_aux_data[insn_idx]; 11726 11727 insn_aux->is_iter_next = is_iter_next_kfunc(&meta); 11728 11729 if (is_kfunc_destructive(&meta) && !capable(CAP_SYS_BOOT)) { 11730 verbose(env, "destructive kfunc calls require CAP_SYS_BOOT capability\n"); 11731 return -EACCES; 11732 } 11733 11734 sleepable = is_kfunc_sleepable(&meta); 11735 if (sleepable && !env->prog->aux->sleepable) { 11736 verbose(env, "program must be sleepable to call sleepable kfunc %s\n", func_name); 11737 return -EACCES; 11738 } 11739 11740 /* Check the arguments */ 11741 err = check_kfunc_args(env, &meta, insn_idx); 11742 if (err < 0) 11743 return err; 11744 11745 if (meta.func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) { 11746 err = push_callback_call(env, insn, insn_idx, meta.subprogno, 11747 set_rbtree_add_callback_state); 11748 if (err) { 11749 verbose(env, "kfunc %s#%d failed callback verification\n", 11750 func_name, meta.func_id); 11751 return err; 11752 } 11753 } 11754 11755 rcu_lock = is_kfunc_bpf_rcu_read_lock(&meta); 11756 rcu_unlock = is_kfunc_bpf_rcu_read_unlock(&meta); 11757 11758 if (env->cur_state->active_rcu_lock) { 11759 struct bpf_func_state *state; 11760 struct bpf_reg_state *reg; 11761 11762 if (in_rbtree_lock_required_cb(env) && (rcu_lock || rcu_unlock)) { 11763 verbose(env, "Calling bpf_rcu_read_{lock,unlock} in unnecessary rbtree callback\n"); 11764 return -EACCES; 11765 } 11766 11767 if (rcu_lock) { 11768 verbose(env, "nested rcu read lock (kernel function %s)\n", func_name); 11769 return -EINVAL; 11770 } else if (rcu_unlock) { 11771 bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({ 11772 if (reg->type & MEM_RCU) { 11773 reg->type &= ~(MEM_RCU | PTR_MAYBE_NULL); 11774 reg->type |= PTR_UNTRUSTED; 11775 } 11776 })); 11777 env->cur_state->active_rcu_lock = false; 11778 } else if (sleepable) { 11779 verbose(env, "kernel func %s is sleepable within rcu_read_lock region\n", func_name); 11780 return -EACCES; 11781 } 11782 } else if (rcu_lock) { 11783 env->cur_state->active_rcu_lock = true; 11784 } else if (rcu_unlock) { 11785 verbose(env, "unmatched rcu read unlock (kernel function %s)\n", func_name); 11786 return -EINVAL; 11787 } 11788 11789 /* In case of release function, we get register number of refcounted 11790 * PTR_TO_BTF_ID in bpf_kfunc_arg_meta, do the release now. 11791 */ 11792 if (meta.release_regno) { 11793 err = release_reference(env, regs[meta.release_regno].ref_obj_id); 11794 if (err) { 11795 verbose(env, "kfunc %s#%d reference has not been acquired before\n", 11796 func_name, meta.func_id); 11797 return err; 11798 } 11799 } 11800 11801 if (meta.func_id == special_kfunc_list[KF_bpf_list_push_front_impl] || 11802 meta.func_id == special_kfunc_list[KF_bpf_list_push_back_impl] || 11803 meta.func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) { 11804 release_ref_obj_id = regs[BPF_REG_2].ref_obj_id; 11805 insn_aux->insert_off = regs[BPF_REG_2].off; 11806 insn_aux->kptr_struct_meta = btf_find_struct_meta(meta.arg_btf, meta.arg_btf_id); 11807 err = ref_convert_owning_non_owning(env, release_ref_obj_id); 11808 if (err) { 11809 verbose(env, "kfunc %s#%d conversion of owning ref to non-owning failed\n", 11810 func_name, meta.func_id); 11811 return err; 11812 } 11813 11814 err = release_reference(env, release_ref_obj_id); 11815 if (err) { 11816 verbose(env, "kfunc %s#%d reference has not been acquired before\n", 11817 func_name, meta.func_id); 11818 return err; 11819 } 11820 } 11821 11822 for (i = 0; i < CALLER_SAVED_REGS; i++) 11823 mark_reg_not_init(env, regs, caller_saved[i]); 11824 11825 /* Check return type */ 11826 t = btf_type_skip_modifiers(desc_btf, meta.func_proto->type, NULL); 11827 11828 if (is_kfunc_acquire(&meta) && !btf_type_is_struct_ptr(meta.btf, t)) { 11829 /* Only exception is bpf_obj_new_impl */ 11830 if (meta.btf != btf_vmlinux || 11831 (meta.func_id != special_kfunc_list[KF_bpf_obj_new_impl] && 11832 meta.func_id != special_kfunc_list[KF_bpf_refcount_acquire_impl])) { 11833 verbose(env, "acquire kernel function does not return PTR_TO_BTF_ID\n"); 11834 return -EINVAL; 11835 } 11836 } 11837 11838 if (btf_type_is_scalar(t)) { 11839 mark_reg_unknown(env, regs, BPF_REG_0); 11840 mark_btf_func_reg_size(env, BPF_REG_0, t->size); 11841 } else if (btf_type_is_ptr(t)) { 11842 ptr_type = btf_type_skip_modifiers(desc_btf, t->type, &ptr_type_id); 11843 11844 if (meta.btf == btf_vmlinux && btf_id_set_contains(&special_kfunc_set, meta.func_id)) { 11845 if (meta.func_id == special_kfunc_list[KF_bpf_obj_new_impl]) { 11846 struct btf *ret_btf; 11847 u32 ret_btf_id; 11848 11849 if (unlikely(!bpf_global_ma_set)) 11850 return -ENOMEM; 11851 11852 if (((u64)(u32)meta.arg_constant.value) != meta.arg_constant.value) { 11853 verbose(env, "local type ID argument must be in range [0, U32_MAX]\n"); 11854 return -EINVAL; 11855 } 11856 11857 ret_btf = env->prog->aux->btf; 11858 ret_btf_id = meta.arg_constant.value; 11859 11860 /* This may be NULL due to user not supplying a BTF */ 11861 if (!ret_btf) { 11862 verbose(env, "bpf_obj_new requires prog BTF\n"); 11863 return -EINVAL; 11864 } 11865 11866 ret_t = btf_type_by_id(ret_btf, ret_btf_id); 11867 if (!ret_t || !__btf_type_is_struct(ret_t)) { 11868 verbose(env, "bpf_obj_new type ID argument must be of a struct\n"); 11869 return -EINVAL; 11870 } 11871 11872 mark_reg_known_zero(env, regs, BPF_REG_0); 11873 regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC; 11874 regs[BPF_REG_0].btf = ret_btf; 11875 regs[BPF_REG_0].btf_id = ret_btf_id; 11876 11877 insn_aux->obj_new_size = ret_t->size; 11878 insn_aux->kptr_struct_meta = 11879 btf_find_struct_meta(ret_btf, ret_btf_id); 11880 } else if (meta.func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl]) { 11881 mark_reg_known_zero(env, regs, BPF_REG_0); 11882 regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC; 11883 regs[BPF_REG_0].btf = meta.arg_btf; 11884 regs[BPF_REG_0].btf_id = meta.arg_btf_id; 11885 11886 insn_aux->kptr_struct_meta = 11887 btf_find_struct_meta(meta.arg_btf, 11888 meta.arg_btf_id); 11889 } else if (meta.func_id == special_kfunc_list[KF_bpf_list_pop_front] || 11890 meta.func_id == special_kfunc_list[KF_bpf_list_pop_back]) { 11891 struct btf_field *field = meta.arg_list_head.field; 11892 11893 mark_reg_graph_node(regs, BPF_REG_0, &field->graph_root); 11894 } else if (meta.func_id == special_kfunc_list[KF_bpf_rbtree_remove] || 11895 meta.func_id == special_kfunc_list[KF_bpf_rbtree_first]) { 11896 struct btf_field *field = meta.arg_rbtree_root.field; 11897 11898 mark_reg_graph_node(regs, BPF_REG_0, &field->graph_root); 11899 } else if (meta.func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx]) { 11900 mark_reg_known_zero(env, regs, BPF_REG_0); 11901 regs[BPF_REG_0].type = PTR_TO_BTF_ID | PTR_TRUSTED; 11902 regs[BPF_REG_0].btf = desc_btf; 11903 regs[BPF_REG_0].btf_id = meta.ret_btf_id; 11904 } else if (meta.func_id == special_kfunc_list[KF_bpf_rdonly_cast]) { 11905 ret_t = btf_type_by_id(desc_btf, meta.arg_constant.value); 11906 if (!ret_t || !btf_type_is_struct(ret_t)) { 11907 verbose(env, 11908 "kfunc bpf_rdonly_cast 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 | PTR_UNTRUSTED; 11914 regs[BPF_REG_0].btf = desc_btf; 11915 regs[BPF_REG_0].btf_id = meta.arg_constant.value; 11916 } else if (meta.func_id == special_kfunc_list[KF_bpf_dynptr_slice] || 11917 meta.func_id == special_kfunc_list[KF_bpf_dynptr_slice_rdwr]) { 11918 enum bpf_type_flag type_flag = get_dynptr_type_flag(meta.initialized_dynptr.type); 11919 11920 mark_reg_known_zero(env, regs, BPF_REG_0); 11921 11922 if (!meta.arg_constant.found) { 11923 verbose(env, "verifier internal error: bpf_dynptr_slice(_rdwr) no constant size\n"); 11924 return -EFAULT; 11925 } 11926 11927 regs[BPF_REG_0].mem_size = meta.arg_constant.value; 11928 11929 /* PTR_MAYBE_NULL will be added when is_kfunc_ret_null is checked */ 11930 regs[BPF_REG_0].type = PTR_TO_MEM | type_flag; 11931 11932 if (meta.func_id == special_kfunc_list[KF_bpf_dynptr_slice]) { 11933 regs[BPF_REG_0].type |= MEM_RDONLY; 11934 } else { 11935 /* this will set env->seen_direct_write to true */ 11936 if (!may_access_direct_pkt_data(env, NULL, BPF_WRITE)) { 11937 verbose(env, "the prog does not allow writes to packet data\n"); 11938 return -EINVAL; 11939 } 11940 } 11941 11942 if (!meta.initialized_dynptr.id) { 11943 verbose(env, "verifier internal error: no dynptr id\n"); 11944 return -EFAULT; 11945 } 11946 regs[BPF_REG_0].dynptr_id = meta.initialized_dynptr.id; 11947 11948 /* we don't need to set BPF_REG_0's ref obj id 11949 * because packet slices are not refcounted (see 11950 * dynptr_type_refcounted) 11951 */ 11952 } else { 11953 verbose(env, "kernel function %s unhandled dynamic return type\n", 11954 meta.func_name); 11955 return -EFAULT; 11956 } 11957 } else if (!__btf_type_is_struct(ptr_type)) { 11958 if (!meta.r0_size) { 11959 __u32 sz; 11960 11961 if (!IS_ERR(btf_resolve_size(desc_btf, ptr_type, &sz))) { 11962 meta.r0_size = sz; 11963 meta.r0_rdonly = true; 11964 } 11965 } 11966 if (!meta.r0_size) { 11967 ptr_type_name = btf_name_by_offset(desc_btf, 11968 ptr_type->name_off); 11969 verbose(env, 11970 "kernel function %s returns pointer type %s %s is not supported\n", 11971 func_name, 11972 btf_type_str(ptr_type), 11973 ptr_type_name); 11974 return -EINVAL; 11975 } 11976 11977 mark_reg_known_zero(env, regs, BPF_REG_0); 11978 regs[BPF_REG_0].type = PTR_TO_MEM; 11979 regs[BPF_REG_0].mem_size = meta.r0_size; 11980 11981 if (meta.r0_rdonly) 11982 regs[BPF_REG_0].type |= MEM_RDONLY; 11983 11984 /* Ensures we don't access the memory after a release_reference() */ 11985 if (meta.ref_obj_id) 11986 regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id; 11987 } else { 11988 mark_reg_known_zero(env, regs, BPF_REG_0); 11989 regs[BPF_REG_0].btf = desc_btf; 11990 regs[BPF_REG_0].type = PTR_TO_BTF_ID; 11991 regs[BPF_REG_0].btf_id = ptr_type_id; 11992 } 11993 11994 if (is_kfunc_ret_null(&meta)) { 11995 regs[BPF_REG_0].type |= PTR_MAYBE_NULL; 11996 /* For mark_ptr_or_null_reg, see 93c230e3f5bd6 */ 11997 regs[BPF_REG_0].id = ++env->id_gen; 11998 } 11999 mark_btf_func_reg_size(env, BPF_REG_0, sizeof(void *)); 12000 if (is_kfunc_acquire(&meta)) { 12001 int id = acquire_reference_state(env, insn_idx); 12002 12003 if (id < 0) 12004 return id; 12005 if (is_kfunc_ret_null(&meta)) 12006 regs[BPF_REG_0].id = id; 12007 regs[BPF_REG_0].ref_obj_id = id; 12008 } else if (meta.func_id == special_kfunc_list[KF_bpf_rbtree_first]) { 12009 ref_set_non_owning(env, ®s[BPF_REG_0]); 12010 } 12011 12012 if (reg_may_point_to_spin_lock(®s[BPF_REG_0]) && !regs[BPF_REG_0].id) 12013 regs[BPF_REG_0].id = ++env->id_gen; 12014 } else if (btf_type_is_void(t)) { 12015 if (meta.btf == btf_vmlinux && btf_id_set_contains(&special_kfunc_set, meta.func_id)) { 12016 if (meta.func_id == special_kfunc_list[KF_bpf_obj_drop_impl]) { 12017 insn_aux->kptr_struct_meta = 12018 btf_find_struct_meta(meta.arg_btf, 12019 meta.arg_btf_id); 12020 } 12021 } 12022 } 12023 12024 nargs = btf_type_vlen(meta.func_proto); 12025 args = (const struct btf_param *)(meta.func_proto + 1); 12026 for (i = 0; i < nargs; i++) { 12027 u32 regno = i + 1; 12028 12029 t = btf_type_skip_modifiers(desc_btf, args[i].type, NULL); 12030 if (btf_type_is_ptr(t)) 12031 mark_btf_func_reg_size(env, regno, sizeof(void *)); 12032 else 12033 /* scalar. ensured by btf_check_kfunc_arg_match() */ 12034 mark_btf_func_reg_size(env, regno, t->size); 12035 } 12036 12037 if (is_iter_next_kfunc(&meta)) { 12038 err = process_iter_next_call(env, insn_idx, &meta); 12039 if (err) 12040 return err; 12041 } 12042 12043 return 0; 12044 } 12045 12046 static bool signed_add_overflows(s64 a, s64 b) 12047 { 12048 /* Do the add in u64, where overflow is well-defined */ 12049 s64 res = (s64)((u64)a + (u64)b); 12050 12051 if (b < 0) 12052 return res > a; 12053 return res < a; 12054 } 12055 12056 static bool signed_add32_overflows(s32 a, s32 b) 12057 { 12058 /* Do the add in u32, where overflow is well-defined */ 12059 s32 res = (s32)((u32)a + (u32)b); 12060 12061 if (b < 0) 12062 return res > a; 12063 return res < a; 12064 } 12065 12066 static bool signed_sub_overflows(s64 a, s64 b) 12067 { 12068 /* Do the sub in u64, where overflow is well-defined */ 12069 s64 res = (s64)((u64)a - (u64)b); 12070 12071 if (b < 0) 12072 return res < a; 12073 return res > a; 12074 } 12075 12076 static bool signed_sub32_overflows(s32 a, s32 b) 12077 { 12078 /* Do the sub in u32, where overflow is well-defined */ 12079 s32 res = (s32)((u32)a - (u32)b); 12080 12081 if (b < 0) 12082 return res < a; 12083 return res > a; 12084 } 12085 12086 static bool check_reg_sane_offset(struct bpf_verifier_env *env, 12087 const struct bpf_reg_state *reg, 12088 enum bpf_reg_type type) 12089 { 12090 bool known = tnum_is_const(reg->var_off); 12091 s64 val = reg->var_off.value; 12092 s64 smin = reg->smin_value; 12093 12094 if (known && (val >= BPF_MAX_VAR_OFF || val <= -BPF_MAX_VAR_OFF)) { 12095 verbose(env, "math between %s pointer and %lld is not allowed\n", 12096 reg_type_str(env, type), val); 12097 return false; 12098 } 12099 12100 if (reg->off >= BPF_MAX_VAR_OFF || reg->off <= -BPF_MAX_VAR_OFF) { 12101 verbose(env, "%s pointer offset %d is not allowed\n", 12102 reg_type_str(env, type), reg->off); 12103 return false; 12104 } 12105 12106 if (smin == S64_MIN) { 12107 verbose(env, "math between %s pointer and register with unbounded min value is not allowed\n", 12108 reg_type_str(env, type)); 12109 return false; 12110 } 12111 12112 if (smin >= BPF_MAX_VAR_OFF || smin <= -BPF_MAX_VAR_OFF) { 12113 verbose(env, "value %lld makes %s pointer be out of bounds\n", 12114 smin, reg_type_str(env, type)); 12115 return false; 12116 } 12117 12118 return true; 12119 } 12120 12121 enum { 12122 REASON_BOUNDS = -1, 12123 REASON_TYPE = -2, 12124 REASON_PATHS = -3, 12125 REASON_LIMIT = -4, 12126 REASON_STACK = -5, 12127 }; 12128 12129 static int retrieve_ptr_limit(const struct bpf_reg_state *ptr_reg, 12130 u32 *alu_limit, bool mask_to_left) 12131 { 12132 u32 max = 0, ptr_limit = 0; 12133 12134 switch (ptr_reg->type) { 12135 case PTR_TO_STACK: 12136 /* Offset 0 is out-of-bounds, but acceptable start for the 12137 * left direction, see BPF_REG_FP. Also, unknown scalar 12138 * offset where we would need to deal with min/max bounds is 12139 * currently prohibited for unprivileged. 12140 */ 12141 max = MAX_BPF_STACK + mask_to_left; 12142 ptr_limit = -(ptr_reg->var_off.value + ptr_reg->off); 12143 break; 12144 case PTR_TO_MAP_VALUE: 12145 max = ptr_reg->map_ptr->value_size; 12146 ptr_limit = (mask_to_left ? 12147 ptr_reg->smin_value : 12148 ptr_reg->umax_value) + ptr_reg->off; 12149 break; 12150 default: 12151 return REASON_TYPE; 12152 } 12153 12154 if (ptr_limit >= max) 12155 return REASON_LIMIT; 12156 *alu_limit = ptr_limit; 12157 return 0; 12158 } 12159 12160 static bool can_skip_alu_sanitation(const struct bpf_verifier_env *env, 12161 const struct bpf_insn *insn) 12162 { 12163 return env->bypass_spec_v1 || BPF_SRC(insn->code) == BPF_K; 12164 } 12165 12166 static int update_alu_sanitation_state(struct bpf_insn_aux_data *aux, 12167 u32 alu_state, u32 alu_limit) 12168 { 12169 /* If we arrived here from different branches with different 12170 * state or limits to sanitize, then this won't work. 12171 */ 12172 if (aux->alu_state && 12173 (aux->alu_state != alu_state || 12174 aux->alu_limit != alu_limit)) 12175 return REASON_PATHS; 12176 12177 /* Corresponding fixup done in do_misc_fixups(). */ 12178 aux->alu_state = alu_state; 12179 aux->alu_limit = alu_limit; 12180 return 0; 12181 } 12182 12183 static int sanitize_val_alu(struct bpf_verifier_env *env, 12184 struct bpf_insn *insn) 12185 { 12186 struct bpf_insn_aux_data *aux = cur_aux(env); 12187 12188 if (can_skip_alu_sanitation(env, insn)) 12189 return 0; 12190 12191 return update_alu_sanitation_state(aux, BPF_ALU_NON_POINTER, 0); 12192 } 12193 12194 static bool sanitize_needed(u8 opcode) 12195 { 12196 return opcode == BPF_ADD || opcode == BPF_SUB; 12197 } 12198 12199 struct bpf_sanitize_info { 12200 struct bpf_insn_aux_data aux; 12201 bool mask_to_left; 12202 }; 12203 12204 static struct bpf_verifier_state * 12205 sanitize_speculative_path(struct bpf_verifier_env *env, 12206 const struct bpf_insn *insn, 12207 u32 next_idx, u32 curr_idx) 12208 { 12209 struct bpf_verifier_state *branch; 12210 struct bpf_reg_state *regs; 12211 12212 branch = push_stack(env, next_idx, curr_idx, true); 12213 if (branch && insn) { 12214 regs = branch->frame[branch->curframe]->regs; 12215 if (BPF_SRC(insn->code) == BPF_K) { 12216 mark_reg_unknown(env, regs, insn->dst_reg); 12217 } else if (BPF_SRC(insn->code) == BPF_X) { 12218 mark_reg_unknown(env, regs, insn->dst_reg); 12219 mark_reg_unknown(env, regs, insn->src_reg); 12220 } 12221 } 12222 return branch; 12223 } 12224 12225 static int sanitize_ptr_alu(struct bpf_verifier_env *env, 12226 struct bpf_insn *insn, 12227 const struct bpf_reg_state *ptr_reg, 12228 const struct bpf_reg_state *off_reg, 12229 struct bpf_reg_state *dst_reg, 12230 struct bpf_sanitize_info *info, 12231 const bool commit_window) 12232 { 12233 struct bpf_insn_aux_data *aux = commit_window ? cur_aux(env) : &info->aux; 12234 struct bpf_verifier_state *vstate = env->cur_state; 12235 bool off_is_imm = tnum_is_const(off_reg->var_off); 12236 bool off_is_neg = off_reg->smin_value < 0; 12237 bool ptr_is_dst_reg = ptr_reg == dst_reg; 12238 u8 opcode = BPF_OP(insn->code); 12239 u32 alu_state, alu_limit; 12240 struct bpf_reg_state tmp; 12241 bool ret; 12242 int err; 12243 12244 if (can_skip_alu_sanitation(env, insn)) 12245 return 0; 12246 12247 /* We already marked aux for masking from non-speculative 12248 * paths, thus we got here in the first place. We only care 12249 * to explore bad access from here. 12250 */ 12251 if (vstate->speculative) 12252 goto do_sim; 12253 12254 if (!commit_window) { 12255 if (!tnum_is_const(off_reg->var_off) && 12256 (off_reg->smin_value < 0) != (off_reg->smax_value < 0)) 12257 return REASON_BOUNDS; 12258 12259 info->mask_to_left = (opcode == BPF_ADD && off_is_neg) || 12260 (opcode == BPF_SUB && !off_is_neg); 12261 } 12262 12263 err = retrieve_ptr_limit(ptr_reg, &alu_limit, info->mask_to_left); 12264 if (err < 0) 12265 return err; 12266 12267 if (commit_window) { 12268 /* In commit phase we narrow the masking window based on 12269 * the observed pointer move after the simulated operation. 12270 */ 12271 alu_state = info->aux.alu_state; 12272 alu_limit = abs(info->aux.alu_limit - alu_limit); 12273 } else { 12274 alu_state = off_is_neg ? BPF_ALU_NEG_VALUE : 0; 12275 alu_state |= off_is_imm ? BPF_ALU_IMMEDIATE : 0; 12276 alu_state |= ptr_is_dst_reg ? 12277 BPF_ALU_SANITIZE_SRC : BPF_ALU_SANITIZE_DST; 12278 12279 /* Limit pruning on unknown scalars to enable deep search for 12280 * potential masking differences from other program paths. 12281 */ 12282 if (!off_is_imm) 12283 env->explore_alu_limits = true; 12284 } 12285 12286 err = update_alu_sanitation_state(aux, alu_state, alu_limit); 12287 if (err < 0) 12288 return err; 12289 do_sim: 12290 /* If we're in commit phase, we're done here given we already 12291 * pushed the truncated dst_reg into the speculative verification 12292 * stack. 12293 * 12294 * Also, when register is a known constant, we rewrite register-based 12295 * operation to immediate-based, and thus do not need masking (and as 12296 * a consequence, do not need to simulate the zero-truncation either). 12297 */ 12298 if (commit_window || off_is_imm) 12299 return 0; 12300 12301 /* Simulate and find potential out-of-bounds access under 12302 * speculative execution from truncation as a result of 12303 * masking when off was not within expected range. If off 12304 * sits in dst, then we temporarily need to move ptr there 12305 * to simulate dst (== 0) +/-= ptr. Needed, for example, 12306 * for cases where we use K-based arithmetic in one direction 12307 * and truncated reg-based in the other in order to explore 12308 * bad access. 12309 */ 12310 if (!ptr_is_dst_reg) { 12311 tmp = *dst_reg; 12312 copy_register_state(dst_reg, ptr_reg); 12313 } 12314 ret = sanitize_speculative_path(env, NULL, env->insn_idx + 1, 12315 env->insn_idx); 12316 if (!ptr_is_dst_reg && ret) 12317 *dst_reg = tmp; 12318 return !ret ? REASON_STACK : 0; 12319 } 12320 12321 static void sanitize_mark_insn_seen(struct bpf_verifier_env *env) 12322 { 12323 struct bpf_verifier_state *vstate = env->cur_state; 12324 12325 /* If we simulate paths under speculation, we don't update the 12326 * insn as 'seen' such that when we verify unreachable paths in 12327 * the non-speculative domain, sanitize_dead_code() can still 12328 * rewrite/sanitize them. 12329 */ 12330 if (!vstate->speculative) 12331 env->insn_aux_data[env->insn_idx].seen = env->pass_cnt; 12332 } 12333 12334 static int sanitize_err(struct bpf_verifier_env *env, 12335 const struct bpf_insn *insn, int reason, 12336 const struct bpf_reg_state *off_reg, 12337 const struct bpf_reg_state *dst_reg) 12338 { 12339 static const char *err = "pointer arithmetic with it prohibited for !root"; 12340 const char *op = BPF_OP(insn->code) == BPF_ADD ? "add" : "sub"; 12341 u32 dst = insn->dst_reg, src = insn->src_reg; 12342 12343 switch (reason) { 12344 case REASON_BOUNDS: 12345 verbose(env, "R%d has unknown scalar with mixed signed bounds, %s\n", 12346 off_reg == dst_reg ? dst : src, err); 12347 break; 12348 case REASON_TYPE: 12349 verbose(env, "R%d has pointer with unsupported alu operation, %s\n", 12350 off_reg == dst_reg ? src : dst, err); 12351 break; 12352 case REASON_PATHS: 12353 verbose(env, "R%d tried to %s from different maps, paths or scalars, %s\n", 12354 dst, op, err); 12355 break; 12356 case REASON_LIMIT: 12357 verbose(env, "R%d tried to %s beyond pointer bounds, %s\n", 12358 dst, op, err); 12359 break; 12360 case REASON_STACK: 12361 verbose(env, "R%d could not be pushed for speculative verification, %s\n", 12362 dst, err); 12363 break; 12364 default: 12365 verbose(env, "verifier internal error: unknown reason (%d)\n", 12366 reason); 12367 break; 12368 } 12369 12370 return -EACCES; 12371 } 12372 12373 /* check that stack access falls within stack limits and that 'reg' doesn't 12374 * have a variable offset. 12375 * 12376 * Variable offset is prohibited for unprivileged mode for simplicity since it 12377 * requires corresponding support in Spectre masking for stack ALU. See also 12378 * retrieve_ptr_limit(). 12379 * 12380 * 12381 * 'off' includes 'reg->off'. 12382 */ 12383 static int check_stack_access_for_ptr_arithmetic( 12384 struct bpf_verifier_env *env, 12385 int regno, 12386 const struct bpf_reg_state *reg, 12387 int off) 12388 { 12389 if (!tnum_is_const(reg->var_off)) { 12390 char tn_buf[48]; 12391 12392 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 12393 verbose(env, "R%d variable stack access prohibited for !root, var_off=%s off=%d\n", 12394 regno, tn_buf, off); 12395 return -EACCES; 12396 } 12397 12398 if (off >= 0 || off < -MAX_BPF_STACK) { 12399 verbose(env, "R%d stack pointer arithmetic goes out of range, " 12400 "prohibited for !root; off=%d\n", regno, off); 12401 return -EACCES; 12402 } 12403 12404 return 0; 12405 } 12406 12407 static int sanitize_check_bounds(struct bpf_verifier_env *env, 12408 const struct bpf_insn *insn, 12409 const struct bpf_reg_state *dst_reg) 12410 { 12411 u32 dst = insn->dst_reg; 12412 12413 /* For unprivileged we require that resulting offset must be in bounds 12414 * in order to be able to sanitize access later on. 12415 */ 12416 if (env->bypass_spec_v1) 12417 return 0; 12418 12419 switch (dst_reg->type) { 12420 case PTR_TO_STACK: 12421 if (check_stack_access_for_ptr_arithmetic(env, dst, dst_reg, 12422 dst_reg->off + dst_reg->var_off.value)) 12423 return -EACCES; 12424 break; 12425 case PTR_TO_MAP_VALUE: 12426 if (check_map_access(env, dst, dst_reg->off, 1, false, ACCESS_HELPER)) { 12427 verbose(env, "R%d pointer arithmetic of map value goes out of range, " 12428 "prohibited for !root\n", dst); 12429 return -EACCES; 12430 } 12431 break; 12432 default: 12433 break; 12434 } 12435 12436 return 0; 12437 } 12438 12439 /* Handles arithmetic on a pointer and a scalar: computes new min/max and var_off. 12440 * Caller should also handle BPF_MOV case separately. 12441 * If we return -EACCES, caller may want to try again treating pointer as a 12442 * scalar. So we only emit a diagnostic if !env->allow_ptr_leaks. 12443 */ 12444 static int adjust_ptr_min_max_vals(struct bpf_verifier_env *env, 12445 struct bpf_insn *insn, 12446 const struct bpf_reg_state *ptr_reg, 12447 const struct bpf_reg_state *off_reg) 12448 { 12449 struct bpf_verifier_state *vstate = env->cur_state; 12450 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 12451 struct bpf_reg_state *regs = state->regs, *dst_reg; 12452 bool known = tnum_is_const(off_reg->var_off); 12453 s64 smin_val = off_reg->smin_value, smax_val = off_reg->smax_value, 12454 smin_ptr = ptr_reg->smin_value, smax_ptr = ptr_reg->smax_value; 12455 u64 umin_val = off_reg->umin_value, umax_val = off_reg->umax_value, 12456 umin_ptr = ptr_reg->umin_value, umax_ptr = ptr_reg->umax_value; 12457 struct bpf_sanitize_info info = {}; 12458 u8 opcode = BPF_OP(insn->code); 12459 u32 dst = insn->dst_reg; 12460 int ret; 12461 12462 dst_reg = ®s[dst]; 12463 12464 if ((known && (smin_val != smax_val || umin_val != umax_val)) || 12465 smin_val > smax_val || umin_val > umax_val) { 12466 /* Taint dst register if offset had invalid bounds derived from 12467 * e.g. dead branches. 12468 */ 12469 __mark_reg_unknown(env, dst_reg); 12470 return 0; 12471 } 12472 12473 if (BPF_CLASS(insn->code) != BPF_ALU64) { 12474 /* 32-bit ALU ops on pointers produce (meaningless) scalars */ 12475 if (opcode == BPF_SUB && env->allow_ptr_leaks) { 12476 __mark_reg_unknown(env, dst_reg); 12477 return 0; 12478 } 12479 12480 verbose(env, 12481 "R%d 32-bit pointer arithmetic prohibited\n", 12482 dst); 12483 return -EACCES; 12484 } 12485 12486 if (ptr_reg->type & PTR_MAYBE_NULL) { 12487 verbose(env, "R%d pointer arithmetic on %s prohibited, null-check it first\n", 12488 dst, reg_type_str(env, ptr_reg->type)); 12489 return -EACCES; 12490 } 12491 12492 switch (base_type(ptr_reg->type)) { 12493 case PTR_TO_FLOW_KEYS: 12494 if (known) 12495 break; 12496 fallthrough; 12497 case CONST_PTR_TO_MAP: 12498 /* smin_val represents the known value */ 12499 if (known && smin_val == 0 && opcode == BPF_ADD) 12500 break; 12501 fallthrough; 12502 case PTR_TO_PACKET_END: 12503 case PTR_TO_SOCKET: 12504 case PTR_TO_SOCK_COMMON: 12505 case PTR_TO_TCP_SOCK: 12506 case PTR_TO_XDP_SOCK: 12507 verbose(env, "R%d pointer arithmetic on %s prohibited\n", 12508 dst, reg_type_str(env, ptr_reg->type)); 12509 return -EACCES; 12510 default: 12511 break; 12512 } 12513 12514 /* In case of 'scalar += pointer', dst_reg inherits pointer type and id. 12515 * The id may be overwritten later if we create a new variable offset. 12516 */ 12517 dst_reg->type = ptr_reg->type; 12518 dst_reg->id = ptr_reg->id; 12519 12520 if (!check_reg_sane_offset(env, off_reg, ptr_reg->type) || 12521 !check_reg_sane_offset(env, ptr_reg, ptr_reg->type)) 12522 return -EINVAL; 12523 12524 /* pointer types do not carry 32-bit bounds at the moment. */ 12525 __mark_reg32_unbounded(dst_reg); 12526 12527 if (sanitize_needed(opcode)) { 12528 ret = sanitize_ptr_alu(env, insn, ptr_reg, off_reg, dst_reg, 12529 &info, false); 12530 if (ret < 0) 12531 return sanitize_err(env, insn, ret, off_reg, dst_reg); 12532 } 12533 12534 switch (opcode) { 12535 case BPF_ADD: 12536 /* We can take a fixed offset as long as it doesn't overflow 12537 * the s32 'off' field 12538 */ 12539 if (known && (ptr_reg->off + smin_val == 12540 (s64)(s32)(ptr_reg->off + smin_val))) { 12541 /* pointer += K. Accumulate it into fixed offset */ 12542 dst_reg->smin_value = smin_ptr; 12543 dst_reg->smax_value = smax_ptr; 12544 dst_reg->umin_value = umin_ptr; 12545 dst_reg->umax_value = umax_ptr; 12546 dst_reg->var_off = ptr_reg->var_off; 12547 dst_reg->off = ptr_reg->off + smin_val; 12548 dst_reg->raw = ptr_reg->raw; 12549 break; 12550 } 12551 /* A new variable offset is created. Note that off_reg->off 12552 * == 0, since it's a scalar. 12553 * dst_reg gets the pointer type and since some positive 12554 * integer value was added to the pointer, give it a new 'id' 12555 * if it's a PTR_TO_PACKET. 12556 * this creates a new 'base' pointer, off_reg (variable) gets 12557 * added into the variable offset, and we copy the fixed offset 12558 * from ptr_reg. 12559 */ 12560 if (signed_add_overflows(smin_ptr, smin_val) || 12561 signed_add_overflows(smax_ptr, smax_val)) { 12562 dst_reg->smin_value = S64_MIN; 12563 dst_reg->smax_value = S64_MAX; 12564 } else { 12565 dst_reg->smin_value = smin_ptr + smin_val; 12566 dst_reg->smax_value = smax_ptr + smax_val; 12567 } 12568 if (umin_ptr + umin_val < umin_ptr || 12569 umax_ptr + umax_val < umax_ptr) { 12570 dst_reg->umin_value = 0; 12571 dst_reg->umax_value = U64_MAX; 12572 } else { 12573 dst_reg->umin_value = umin_ptr + umin_val; 12574 dst_reg->umax_value = umax_ptr + umax_val; 12575 } 12576 dst_reg->var_off = tnum_add(ptr_reg->var_off, off_reg->var_off); 12577 dst_reg->off = ptr_reg->off; 12578 dst_reg->raw = ptr_reg->raw; 12579 if (reg_is_pkt_pointer(ptr_reg)) { 12580 dst_reg->id = ++env->id_gen; 12581 /* something was added to pkt_ptr, set range to zero */ 12582 memset(&dst_reg->raw, 0, sizeof(dst_reg->raw)); 12583 } 12584 break; 12585 case BPF_SUB: 12586 if (dst_reg == off_reg) { 12587 /* scalar -= pointer. Creates an unknown scalar */ 12588 verbose(env, "R%d tried to subtract pointer from scalar\n", 12589 dst); 12590 return -EACCES; 12591 } 12592 /* We don't allow subtraction from FP, because (according to 12593 * test_verifier.c test "invalid fp arithmetic", JITs might not 12594 * be able to deal with it. 12595 */ 12596 if (ptr_reg->type == PTR_TO_STACK) { 12597 verbose(env, "R%d subtraction from stack pointer prohibited\n", 12598 dst); 12599 return -EACCES; 12600 } 12601 if (known && (ptr_reg->off - smin_val == 12602 (s64)(s32)(ptr_reg->off - smin_val))) { 12603 /* pointer -= K. Subtract it from fixed offset */ 12604 dst_reg->smin_value = smin_ptr; 12605 dst_reg->smax_value = smax_ptr; 12606 dst_reg->umin_value = umin_ptr; 12607 dst_reg->umax_value = umax_ptr; 12608 dst_reg->var_off = ptr_reg->var_off; 12609 dst_reg->id = ptr_reg->id; 12610 dst_reg->off = ptr_reg->off - smin_val; 12611 dst_reg->raw = ptr_reg->raw; 12612 break; 12613 } 12614 /* A new variable offset is created. If the subtrahend is known 12615 * nonnegative, then any reg->range we had before is still good. 12616 */ 12617 if (signed_sub_overflows(smin_ptr, smax_val) || 12618 signed_sub_overflows(smax_ptr, smin_val)) { 12619 /* Overflow possible, we know nothing */ 12620 dst_reg->smin_value = S64_MIN; 12621 dst_reg->smax_value = S64_MAX; 12622 } else { 12623 dst_reg->smin_value = smin_ptr - smax_val; 12624 dst_reg->smax_value = smax_ptr - smin_val; 12625 } 12626 if (umin_ptr < umax_val) { 12627 /* Overflow possible, we know nothing */ 12628 dst_reg->umin_value = 0; 12629 dst_reg->umax_value = U64_MAX; 12630 } else { 12631 /* Cannot overflow (as long as bounds are consistent) */ 12632 dst_reg->umin_value = umin_ptr - umax_val; 12633 dst_reg->umax_value = umax_ptr - umin_val; 12634 } 12635 dst_reg->var_off = tnum_sub(ptr_reg->var_off, off_reg->var_off); 12636 dst_reg->off = ptr_reg->off; 12637 dst_reg->raw = ptr_reg->raw; 12638 if (reg_is_pkt_pointer(ptr_reg)) { 12639 dst_reg->id = ++env->id_gen; 12640 /* something was added to pkt_ptr, set range to zero */ 12641 if (smin_val < 0) 12642 memset(&dst_reg->raw, 0, sizeof(dst_reg->raw)); 12643 } 12644 break; 12645 case BPF_AND: 12646 case BPF_OR: 12647 case BPF_XOR: 12648 /* bitwise ops on pointers are troublesome, prohibit. */ 12649 verbose(env, "R%d bitwise operator %s on pointer prohibited\n", 12650 dst, bpf_alu_string[opcode >> 4]); 12651 return -EACCES; 12652 default: 12653 /* other operators (e.g. MUL,LSH) produce non-pointer results */ 12654 verbose(env, "R%d pointer arithmetic with %s operator prohibited\n", 12655 dst, bpf_alu_string[opcode >> 4]); 12656 return -EACCES; 12657 } 12658 12659 if (!check_reg_sane_offset(env, dst_reg, ptr_reg->type)) 12660 return -EINVAL; 12661 reg_bounds_sync(dst_reg); 12662 if (sanitize_check_bounds(env, insn, dst_reg) < 0) 12663 return -EACCES; 12664 if (sanitize_needed(opcode)) { 12665 ret = sanitize_ptr_alu(env, insn, dst_reg, off_reg, dst_reg, 12666 &info, true); 12667 if (ret < 0) 12668 return sanitize_err(env, insn, ret, off_reg, dst_reg); 12669 } 12670 12671 return 0; 12672 } 12673 12674 static void scalar32_min_max_add(struct bpf_reg_state *dst_reg, 12675 struct bpf_reg_state *src_reg) 12676 { 12677 s32 smin_val = src_reg->s32_min_value; 12678 s32 smax_val = src_reg->s32_max_value; 12679 u32 umin_val = src_reg->u32_min_value; 12680 u32 umax_val = src_reg->u32_max_value; 12681 12682 if (signed_add32_overflows(dst_reg->s32_min_value, smin_val) || 12683 signed_add32_overflows(dst_reg->s32_max_value, smax_val)) { 12684 dst_reg->s32_min_value = S32_MIN; 12685 dst_reg->s32_max_value = S32_MAX; 12686 } else { 12687 dst_reg->s32_min_value += smin_val; 12688 dst_reg->s32_max_value += smax_val; 12689 } 12690 if (dst_reg->u32_min_value + umin_val < umin_val || 12691 dst_reg->u32_max_value + umax_val < umax_val) { 12692 dst_reg->u32_min_value = 0; 12693 dst_reg->u32_max_value = U32_MAX; 12694 } else { 12695 dst_reg->u32_min_value += umin_val; 12696 dst_reg->u32_max_value += umax_val; 12697 } 12698 } 12699 12700 static void scalar_min_max_add(struct bpf_reg_state *dst_reg, 12701 struct bpf_reg_state *src_reg) 12702 { 12703 s64 smin_val = src_reg->smin_value; 12704 s64 smax_val = src_reg->smax_value; 12705 u64 umin_val = src_reg->umin_value; 12706 u64 umax_val = src_reg->umax_value; 12707 12708 if (signed_add_overflows(dst_reg->smin_value, smin_val) || 12709 signed_add_overflows(dst_reg->smax_value, smax_val)) { 12710 dst_reg->smin_value = S64_MIN; 12711 dst_reg->smax_value = S64_MAX; 12712 } else { 12713 dst_reg->smin_value += smin_val; 12714 dst_reg->smax_value += smax_val; 12715 } 12716 if (dst_reg->umin_value + umin_val < umin_val || 12717 dst_reg->umax_value + umax_val < umax_val) { 12718 dst_reg->umin_value = 0; 12719 dst_reg->umax_value = U64_MAX; 12720 } else { 12721 dst_reg->umin_value += umin_val; 12722 dst_reg->umax_value += umax_val; 12723 } 12724 } 12725 12726 static void scalar32_min_max_sub(struct bpf_reg_state *dst_reg, 12727 struct bpf_reg_state *src_reg) 12728 { 12729 s32 smin_val = src_reg->s32_min_value; 12730 s32 smax_val = src_reg->s32_max_value; 12731 u32 umin_val = src_reg->u32_min_value; 12732 u32 umax_val = src_reg->u32_max_value; 12733 12734 if (signed_sub32_overflows(dst_reg->s32_min_value, smax_val) || 12735 signed_sub32_overflows(dst_reg->s32_max_value, smin_val)) { 12736 /* Overflow possible, we know nothing */ 12737 dst_reg->s32_min_value = S32_MIN; 12738 dst_reg->s32_max_value = S32_MAX; 12739 } else { 12740 dst_reg->s32_min_value -= smax_val; 12741 dst_reg->s32_max_value -= smin_val; 12742 } 12743 if (dst_reg->u32_min_value < umax_val) { 12744 /* Overflow possible, we know nothing */ 12745 dst_reg->u32_min_value = 0; 12746 dst_reg->u32_max_value = U32_MAX; 12747 } else { 12748 /* Cannot overflow (as long as bounds are consistent) */ 12749 dst_reg->u32_min_value -= umax_val; 12750 dst_reg->u32_max_value -= umin_val; 12751 } 12752 } 12753 12754 static void scalar_min_max_sub(struct bpf_reg_state *dst_reg, 12755 struct bpf_reg_state *src_reg) 12756 { 12757 s64 smin_val = src_reg->smin_value; 12758 s64 smax_val = src_reg->smax_value; 12759 u64 umin_val = src_reg->umin_value; 12760 u64 umax_val = src_reg->umax_value; 12761 12762 if (signed_sub_overflows(dst_reg->smin_value, smax_val) || 12763 signed_sub_overflows(dst_reg->smax_value, smin_val)) { 12764 /* Overflow possible, we know nothing */ 12765 dst_reg->smin_value = S64_MIN; 12766 dst_reg->smax_value = S64_MAX; 12767 } else { 12768 dst_reg->smin_value -= smax_val; 12769 dst_reg->smax_value -= smin_val; 12770 } 12771 if (dst_reg->umin_value < umax_val) { 12772 /* Overflow possible, we know nothing */ 12773 dst_reg->umin_value = 0; 12774 dst_reg->umax_value = U64_MAX; 12775 } else { 12776 /* Cannot overflow (as long as bounds are consistent) */ 12777 dst_reg->umin_value -= umax_val; 12778 dst_reg->umax_value -= umin_val; 12779 } 12780 } 12781 12782 static void scalar32_min_max_mul(struct bpf_reg_state *dst_reg, 12783 struct bpf_reg_state *src_reg) 12784 { 12785 s32 smin_val = src_reg->s32_min_value; 12786 u32 umin_val = src_reg->u32_min_value; 12787 u32 umax_val = src_reg->u32_max_value; 12788 12789 if (smin_val < 0 || dst_reg->s32_min_value < 0) { 12790 /* Ain't nobody got time to multiply that sign */ 12791 __mark_reg32_unbounded(dst_reg); 12792 return; 12793 } 12794 /* Both values are positive, so we can work with unsigned and 12795 * copy the result to signed (unless it exceeds S32_MAX). 12796 */ 12797 if (umax_val > U16_MAX || dst_reg->u32_max_value > U16_MAX) { 12798 /* Potential overflow, we know nothing */ 12799 __mark_reg32_unbounded(dst_reg); 12800 return; 12801 } 12802 dst_reg->u32_min_value *= umin_val; 12803 dst_reg->u32_max_value *= umax_val; 12804 if (dst_reg->u32_max_value > S32_MAX) { 12805 /* Overflow possible, we know nothing */ 12806 dst_reg->s32_min_value = S32_MIN; 12807 dst_reg->s32_max_value = S32_MAX; 12808 } else { 12809 dst_reg->s32_min_value = dst_reg->u32_min_value; 12810 dst_reg->s32_max_value = dst_reg->u32_max_value; 12811 } 12812 } 12813 12814 static void scalar_min_max_mul(struct bpf_reg_state *dst_reg, 12815 struct bpf_reg_state *src_reg) 12816 { 12817 s64 smin_val = src_reg->smin_value; 12818 u64 umin_val = src_reg->umin_value; 12819 u64 umax_val = src_reg->umax_value; 12820 12821 if (smin_val < 0 || dst_reg->smin_value < 0) { 12822 /* Ain't nobody got time to multiply that sign */ 12823 __mark_reg64_unbounded(dst_reg); 12824 return; 12825 } 12826 /* Both values are positive, so we can work with unsigned and 12827 * copy the result to signed (unless it exceeds S64_MAX). 12828 */ 12829 if (umax_val > U32_MAX || dst_reg->umax_value > U32_MAX) { 12830 /* Potential overflow, we know nothing */ 12831 __mark_reg64_unbounded(dst_reg); 12832 return; 12833 } 12834 dst_reg->umin_value *= umin_val; 12835 dst_reg->umax_value *= umax_val; 12836 if (dst_reg->umax_value > S64_MAX) { 12837 /* Overflow possible, we know nothing */ 12838 dst_reg->smin_value = S64_MIN; 12839 dst_reg->smax_value = S64_MAX; 12840 } else { 12841 dst_reg->smin_value = dst_reg->umin_value; 12842 dst_reg->smax_value = dst_reg->umax_value; 12843 } 12844 } 12845 12846 static void scalar32_min_max_and(struct bpf_reg_state *dst_reg, 12847 struct bpf_reg_state *src_reg) 12848 { 12849 bool src_known = tnum_subreg_is_const(src_reg->var_off); 12850 bool dst_known = tnum_subreg_is_const(dst_reg->var_off); 12851 struct tnum var32_off = tnum_subreg(dst_reg->var_off); 12852 s32 smin_val = src_reg->s32_min_value; 12853 u32 umax_val = src_reg->u32_max_value; 12854 12855 if (src_known && dst_known) { 12856 __mark_reg32_known(dst_reg, var32_off.value); 12857 return; 12858 } 12859 12860 /* We get our minimum from the var_off, since that's inherently 12861 * bitwise. Our maximum is the minimum of the operands' maxima. 12862 */ 12863 dst_reg->u32_min_value = var32_off.value; 12864 dst_reg->u32_max_value = min(dst_reg->u32_max_value, umax_val); 12865 if (dst_reg->s32_min_value < 0 || smin_val < 0) { 12866 /* Lose signed bounds when ANDing negative numbers, 12867 * ain't nobody got time for that. 12868 */ 12869 dst_reg->s32_min_value = S32_MIN; 12870 dst_reg->s32_max_value = S32_MAX; 12871 } else { 12872 /* ANDing two positives gives a positive, so safe to 12873 * cast result into s64. 12874 */ 12875 dst_reg->s32_min_value = dst_reg->u32_min_value; 12876 dst_reg->s32_max_value = dst_reg->u32_max_value; 12877 } 12878 } 12879 12880 static void scalar_min_max_and(struct bpf_reg_state *dst_reg, 12881 struct bpf_reg_state *src_reg) 12882 { 12883 bool src_known = tnum_is_const(src_reg->var_off); 12884 bool dst_known = tnum_is_const(dst_reg->var_off); 12885 s64 smin_val = src_reg->smin_value; 12886 u64 umax_val = src_reg->umax_value; 12887 12888 if (src_known && dst_known) { 12889 __mark_reg_known(dst_reg, dst_reg->var_off.value); 12890 return; 12891 } 12892 12893 /* We get our minimum from the var_off, since that's inherently 12894 * bitwise. Our maximum is the minimum of the operands' maxima. 12895 */ 12896 dst_reg->umin_value = dst_reg->var_off.value; 12897 dst_reg->umax_value = min(dst_reg->umax_value, umax_val); 12898 if (dst_reg->smin_value < 0 || smin_val < 0) { 12899 /* Lose signed bounds when ANDing negative numbers, 12900 * ain't nobody got time for that. 12901 */ 12902 dst_reg->smin_value = S64_MIN; 12903 dst_reg->smax_value = S64_MAX; 12904 } else { 12905 /* ANDing two positives gives a positive, so safe to 12906 * cast result into s64. 12907 */ 12908 dst_reg->smin_value = dst_reg->umin_value; 12909 dst_reg->smax_value = dst_reg->umax_value; 12910 } 12911 /* We may learn something more from the var_off */ 12912 __update_reg_bounds(dst_reg); 12913 } 12914 12915 static void scalar32_min_max_or(struct bpf_reg_state *dst_reg, 12916 struct bpf_reg_state *src_reg) 12917 { 12918 bool src_known = tnum_subreg_is_const(src_reg->var_off); 12919 bool dst_known = tnum_subreg_is_const(dst_reg->var_off); 12920 struct tnum var32_off = tnum_subreg(dst_reg->var_off); 12921 s32 smin_val = src_reg->s32_min_value; 12922 u32 umin_val = src_reg->u32_min_value; 12923 12924 if (src_known && dst_known) { 12925 __mark_reg32_known(dst_reg, var32_off.value); 12926 return; 12927 } 12928 12929 /* We get our maximum from the var_off, and our minimum is the 12930 * maximum of the operands' minima 12931 */ 12932 dst_reg->u32_min_value = max(dst_reg->u32_min_value, umin_val); 12933 dst_reg->u32_max_value = var32_off.value | var32_off.mask; 12934 if (dst_reg->s32_min_value < 0 || smin_val < 0) { 12935 /* Lose signed bounds when ORing negative numbers, 12936 * ain't nobody got time for that. 12937 */ 12938 dst_reg->s32_min_value = S32_MIN; 12939 dst_reg->s32_max_value = S32_MAX; 12940 } else { 12941 /* ORing two positives gives a positive, so safe to 12942 * cast result into s64. 12943 */ 12944 dst_reg->s32_min_value = dst_reg->u32_min_value; 12945 dst_reg->s32_max_value = dst_reg->u32_max_value; 12946 } 12947 } 12948 12949 static void scalar_min_max_or(struct bpf_reg_state *dst_reg, 12950 struct bpf_reg_state *src_reg) 12951 { 12952 bool src_known = tnum_is_const(src_reg->var_off); 12953 bool dst_known = tnum_is_const(dst_reg->var_off); 12954 s64 smin_val = src_reg->smin_value; 12955 u64 umin_val = src_reg->umin_value; 12956 12957 if (src_known && dst_known) { 12958 __mark_reg_known(dst_reg, dst_reg->var_off.value); 12959 return; 12960 } 12961 12962 /* We get our maximum from the var_off, and our minimum is the 12963 * maximum of the operands' minima 12964 */ 12965 dst_reg->umin_value = max(dst_reg->umin_value, umin_val); 12966 dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask; 12967 if (dst_reg->smin_value < 0 || smin_val < 0) { 12968 /* Lose signed bounds when ORing negative numbers, 12969 * ain't nobody got time for that. 12970 */ 12971 dst_reg->smin_value = S64_MIN; 12972 dst_reg->smax_value = S64_MAX; 12973 } else { 12974 /* ORing two positives gives a positive, so safe to 12975 * cast result into s64. 12976 */ 12977 dst_reg->smin_value = dst_reg->umin_value; 12978 dst_reg->smax_value = dst_reg->umax_value; 12979 } 12980 /* We may learn something more from the var_off */ 12981 __update_reg_bounds(dst_reg); 12982 } 12983 12984 static void scalar32_min_max_xor(struct bpf_reg_state *dst_reg, 12985 struct bpf_reg_state *src_reg) 12986 { 12987 bool src_known = tnum_subreg_is_const(src_reg->var_off); 12988 bool dst_known = tnum_subreg_is_const(dst_reg->var_off); 12989 struct tnum var32_off = tnum_subreg(dst_reg->var_off); 12990 s32 smin_val = src_reg->s32_min_value; 12991 12992 if (src_known && dst_known) { 12993 __mark_reg32_known(dst_reg, var32_off.value); 12994 return; 12995 } 12996 12997 /* We get both minimum and maximum from the var32_off. */ 12998 dst_reg->u32_min_value = var32_off.value; 12999 dst_reg->u32_max_value = var32_off.value | var32_off.mask; 13000 13001 if (dst_reg->s32_min_value >= 0 && smin_val >= 0) { 13002 /* XORing two positive sign numbers gives a positive, 13003 * so safe to cast u32 result into s32. 13004 */ 13005 dst_reg->s32_min_value = dst_reg->u32_min_value; 13006 dst_reg->s32_max_value = dst_reg->u32_max_value; 13007 } else { 13008 dst_reg->s32_min_value = S32_MIN; 13009 dst_reg->s32_max_value = S32_MAX; 13010 } 13011 } 13012 13013 static void scalar_min_max_xor(struct bpf_reg_state *dst_reg, 13014 struct bpf_reg_state *src_reg) 13015 { 13016 bool src_known = tnum_is_const(src_reg->var_off); 13017 bool dst_known = tnum_is_const(dst_reg->var_off); 13018 s64 smin_val = src_reg->smin_value; 13019 13020 if (src_known && dst_known) { 13021 /* dst_reg->var_off.value has been updated earlier */ 13022 __mark_reg_known(dst_reg, dst_reg->var_off.value); 13023 return; 13024 } 13025 13026 /* We get both minimum and maximum from the var_off. */ 13027 dst_reg->umin_value = dst_reg->var_off.value; 13028 dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask; 13029 13030 if (dst_reg->smin_value >= 0 && smin_val >= 0) { 13031 /* XORing two positive sign numbers gives a positive, 13032 * so safe to cast u64 result into s64. 13033 */ 13034 dst_reg->smin_value = dst_reg->umin_value; 13035 dst_reg->smax_value = dst_reg->umax_value; 13036 } else { 13037 dst_reg->smin_value = S64_MIN; 13038 dst_reg->smax_value = S64_MAX; 13039 } 13040 13041 __update_reg_bounds(dst_reg); 13042 } 13043 13044 static void __scalar32_min_max_lsh(struct bpf_reg_state *dst_reg, 13045 u64 umin_val, u64 umax_val) 13046 { 13047 /* We lose all sign bit information (except what we can pick 13048 * up from var_off) 13049 */ 13050 dst_reg->s32_min_value = S32_MIN; 13051 dst_reg->s32_max_value = S32_MAX; 13052 /* If we might shift our top bit out, then we know nothing */ 13053 if (umax_val > 31 || dst_reg->u32_max_value > 1ULL << (31 - umax_val)) { 13054 dst_reg->u32_min_value = 0; 13055 dst_reg->u32_max_value = U32_MAX; 13056 } else { 13057 dst_reg->u32_min_value <<= umin_val; 13058 dst_reg->u32_max_value <<= umax_val; 13059 } 13060 } 13061 13062 static void scalar32_min_max_lsh(struct bpf_reg_state *dst_reg, 13063 struct bpf_reg_state *src_reg) 13064 { 13065 u32 umax_val = src_reg->u32_max_value; 13066 u32 umin_val = src_reg->u32_min_value; 13067 /* u32 alu operation will zext upper bits */ 13068 struct tnum subreg = tnum_subreg(dst_reg->var_off); 13069 13070 __scalar32_min_max_lsh(dst_reg, umin_val, umax_val); 13071 dst_reg->var_off = tnum_subreg(tnum_lshift(subreg, umin_val)); 13072 /* Not required but being careful mark reg64 bounds as unknown so 13073 * that we are forced to pick them up from tnum and zext later and 13074 * if some path skips this step we are still safe. 13075 */ 13076 __mark_reg64_unbounded(dst_reg); 13077 __update_reg32_bounds(dst_reg); 13078 } 13079 13080 static void __scalar64_min_max_lsh(struct bpf_reg_state *dst_reg, 13081 u64 umin_val, u64 umax_val) 13082 { 13083 /* Special case <<32 because it is a common compiler pattern to sign 13084 * extend subreg by doing <<32 s>>32. In this case if 32bit bounds are 13085 * positive we know this shift will also be positive so we can track 13086 * bounds correctly. Otherwise we lose all sign bit information except 13087 * what we can pick up from var_off. Perhaps we can generalize this 13088 * later to shifts of any length. 13089 */ 13090 if (umin_val == 32 && umax_val == 32 && dst_reg->s32_max_value >= 0) 13091 dst_reg->smax_value = (s64)dst_reg->s32_max_value << 32; 13092 else 13093 dst_reg->smax_value = S64_MAX; 13094 13095 if (umin_val == 32 && umax_val == 32 && dst_reg->s32_min_value >= 0) 13096 dst_reg->smin_value = (s64)dst_reg->s32_min_value << 32; 13097 else 13098 dst_reg->smin_value = S64_MIN; 13099 13100 /* If we might shift our top bit out, then we know nothing */ 13101 if (dst_reg->umax_value > 1ULL << (63 - umax_val)) { 13102 dst_reg->umin_value = 0; 13103 dst_reg->umax_value = U64_MAX; 13104 } else { 13105 dst_reg->umin_value <<= umin_val; 13106 dst_reg->umax_value <<= umax_val; 13107 } 13108 } 13109 13110 static void scalar_min_max_lsh(struct bpf_reg_state *dst_reg, 13111 struct bpf_reg_state *src_reg) 13112 { 13113 u64 umax_val = src_reg->umax_value; 13114 u64 umin_val = src_reg->umin_value; 13115 13116 /* scalar64 calc uses 32bit unshifted bounds so must be called first */ 13117 __scalar64_min_max_lsh(dst_reg, umin_val, umax_val); 13118 __scalar32_min_max_lsh(dst_reg, umin_val, umax_val); 13119 13120 dst_reg->var_off = tnum_lshift(dst_reg->var_off, umin_val); 13121 /* We may learn something more from the var_off */ 13122 __update_reg_bounds(dst_reg); 13123 } 13124 13125 static void scalar32_min_max_rsh(struct bpf_reg_state *dst_reg, 13126 struct bpf_reg_state *src_reg) 13127 { 13128 struct tnum subreg = tnum_subreg(dst_reg->var_off); 13129 u32 umax_val = src_reg->u32_max_value; 13130 u32 umin_val = src_reg->u32_min_value; 13131 13132 /* BPF_RSH is an unsigned shift. If the value in dst_reg might 13133 * be negative, then either: 13134 * 1) src_reg might be zero, so the sign bit of the result is 13135 * unknown, so we lose our signed bounds 13136 * 2) it's known negative, thus the unsigned bounds capture the 13137 * signed bounds 13138 * 3) the signed bounds cross zero, so they tell us nothing 13139 * about the result 13140 * If the value in dst_reg is known nonnegative, then again the 13141 * unsigned bounds capture the signed bounds. 13142 * Thus, in all cases it suffices to blow away our signed bounds 13143 * and rely on inferring new ones from the unsigned bounds and 13144 * var_off of the result. 13145 */ 13146 dst_reg->s32_min_value = S32_MIN; 13147 dst_reg->s32_max_value = S32_MAX; 13148 13149 dst_reg->var_off = tnum_rshift(subreg, umin_val); 13150 dst_reg->u32_min_value >>= umax_val; 13151 dst_reg->u32_max_value >>= umin_val; 13152 13153 __mark_reg64_unbounded(dst_reg); 13154 __update_reg32_bounds(dst_reg); 13155 } 13156 13157 static void scalar_min_max_rsh(struct bpf_reg_state *dst_reg, 13158 struct bpf_reg_state *src_reg) 13159 { 13160 u64 umax_val = src_reg->umax_value; 13161 u64 umin_val = src_reg->umin_value; 13162 13163 /* BPF_RSH is an unsigned shift. If the value in dst_reg might 13164 * be negative, then either: 13165 * 1) src_reg might be zero, so the sign bit of the result is 13166 * unknown, so we lose our signed bounds 13167 * 2) it's known negative, thus the unsigned bounds capture the 13168 * signed bounds 13169 * 3) the signed bounds cross zero, so they tell us nothing 13170 * about the result 13171 * If the value in dst_reg is known nonnegative, then again the 13172 * unsigned bounds capture the signed bounds. 13173 * Thus, in all cases it suffices to blow away our signed bounds 13174 * and rely on inferring new ones from the unsigned bounds and 13175 * var_off of the result. 13176 */ 13177 dst_reg->smin_value = S64_MIN; 13178 dst_reg->smax_value = S64_MAX; 13179 dst_reg->var_off = tnum_rshift(dst_reg->var_off, umin_val); 13180 dst_reg->umin_value >>= umax_val; 13181 dst_reg->umax_value >>= umin_val; 13182 13183 /* Its not easy to operate on alu32 bounds here because it depends 13184 * on bits being shifted in. Take easy way out and mark unbounded 13185 * so we can recalculate later from tnum. 13186 */ 13187 __mark_reg32_unbounded(dst_reg); 13188 __update_reg_bounds(dst_reg); 13189 } 13190 13191 static void scalar32_min_max_arsh(struct bpf_reg_state *dst_reg, 13192 struct bpf_reg_state *src_reg) 13193 { 13194 u64 umin_val = src_reg->u32_min_value; 13195 13196 /* Upon reaching here, src_known is true and 13197 * umax_val is equal to umin_val. 13198 */ 13199 dst_reg->s32_min_value = (u32)(((s32)dst_reg->s32_min_value) >> umin_val); 13200 dst_reg->s32_max_value = (u32)(((s32)dst_reg->s32_max_value) >> umin_val); 13201 13202 dst_reg->var_off = tnum_arshift(tnum_subreg(dst_reg->var_off), umin_val, 32); 13203 13204 /* blow away the dst_reg umin_value/umax_value and rely on 13205 * dst_reg var_off to refine the result. 13206 */ 13207 dst_reg->u32_min_value = 0; 13208 dst_reg->u32_max_value = U32_MAX; 13209 13210 __mark_reg64_unbounded(dst_reg); 13211 __update_reg32_bounds(dst_reg); 13212 } 13213 13214 static void scalar_min_max_arsh(struct bpf_reg_state *dst_reg, 13215 struct bpf_reg_state *src_reg) 13216 { 13217 u64 umin_val = src_reg->umin_value; 13218 13219 /* Upon reaching here, src_known is true and umax_val is equal 13220 * to umin_val. 13221 */ 13222 dst_reg->smin_value >>= umin_val; 13223 dst_reg->smax_value >>= umin_val; 13224 13225 dst_reg->var_off = tnum_arshift(dst_reg->var_off, umin_val, 64); 13226 13227 /* blow away the dst_reg umin_value/umax_value and rely on 13228 * dst_reg var_off to refine the result. 13229 */ 13230 dst_reg->umin_value = 0; 13231 dst_reg->umax_value = U64_MAX; 13232 13233 /* Its not easy to operate on alu32 bounds here because it depends 13234 * on bits being shifted in from upper 32-bits. Take easy way out 13235 * and mark unbounded so we can recalculate later from tnum. 13236 */ 13237 __mark_reg32_unbounded(dst_reg); 13238 __update_reg_bounds(dst_reg); 13239 } 13240 13241 /* WARNING: This function does calculations on 64-bit values, but the actual 13242 * execution may occur on 32-bit values. Therefore, things like bitshifts 13243 * need extra checks in the 32-bit case. 13244 */ 13245 static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env, 13246 struct bpf_insn *insn, 13247 struct bpf_reg_state *dst_reg, 13248 struct bpf_reg_state src_reg) 13249 { 13250 struct bpf_reg_state *regs = cur_regs(env); 13251 u8 opcode = BPF_OP(insn->code); 13252 bool src_known; 13253 s64 smin_val, smax_val; 13254 u64 umin_val, umax_val; 13255 s32 s32_min_val, s32_max_val; 13256 u32 u32_min_val, u32_max_val; 13257 u64 insn_bitness = (BPF_CLASS(insn->code) == BPF_ALU64) ? 64 : 32; 13258 bool alu32 = (BPF_CLASS(insn->code) != BPF_ALU64); 13259 int ret; 13260 13261 smin_val = src_reg.smin_value; 13262 smax_val = src_reg.smax_value; 13263 umin_val = src_reg.umin_value; 13264 umax_val = src_reg.umax_value; 13265 13266 s32_min_val = src_reg.s32_min_value; 13267 s32_max_val = src_reg.s32_max_value; 13268 u32_min_val = src_reg.u32_min_value; 13269 u32_max_val = src_reg.u32_max_value; 13270 13271 if (alu32) { 13272 src_known = tnum_subreg_is_const(src_reg.var_off); 13273 if ((src_known && 13274 (s32_min_val != s32_max_val || u32_min_val != u32_max_val)) || 13275 s32_min_val > s32_max_val || u32_min_val > u32_max_val) { 13276 /* Taint dst register if offset had invalid bounds 13277 * derived from e.g. dead branches. 13278 */ 13279 __mark_reg_unknown(env, dst_reg); 13280 return 0; 13281 } 13282 } else { 13283 src_known = tnum_is_const(src_reg.var_off); 13284 if ((src_known && 13285 (smin_val != smax_val || umin_val != umax_val)) || 13286 smin_val > smax_val || umin_val > umax_val) { 13287 /* Taint dst register if offset had invalid bounds 13288 * derived from e.g. dead branches. 13289 */ 13290 __mark_reg_unknown(env, dst_reg); 13291 return 0; 13292 } 13293 } 13294 13295 if (!src_known && 13296 opcode != BPF_ADD && opcode != BPF_SUB && opcode != BPF_AND) { 13297 __mark_reg_unknown(env, dst_reg); 13298 return 0; 13299 } 13300 13301 if (sanitize_needed(opcode)) { 13302 ret = sanitize_val_alu(env, insn); 13303 if (ret < 0) 13304 return sanitize_err(env, insn, ret, NULL, NULL); 13305 } 13306 13307 /* Calculate sign/unsigned bounds and tnum for alu32 and alu64 bit ops. 13308 * There are two classes of instructions: The first class we track both 13309 * alu32 and alu64 sign/unsigned bounds independently this provides the 13310 * greatest amount of precision when alu operations are mixed with jmp32 13311 * operations. These operations are BPF_ADD, BPF_SUB, BPF_MUL, BPF_ADD, 13312 * and BPF_OR. This is possible because these ops have fairly easy to 13313 * understand and calculate behavior in both 32-bit and 64-bit alu ops. 13314 * See alu32 verifier tests for examples. The second class of 13315 * operations, BPF_LSH, BPF_RSH, and BPF_ARSH, however are not so easy 13316 * with regards to tracking sign/unsigned bounds because the bits may 13317 * cross subreg boundaries in the alu64 case. When this happens we mark 13318 * the reg unbounded in the subreg bound space and use the resulting 13319 * tnum to calculate an approximation of the sign/unsigned bounds. 13320 */ 13321 switch (opcode) { 13322 case BPF_ADD: 13323 scalar32_min_max_add(dst_reg, &src_reg); 13324 scalar_min_max_add(dst_reg, &src_reg); 13325 dst_reg->var_off = tnum_add(dst_reg->var_off, src_reg.var_off); 13326 break; 13327 case BPF_SUB: 13328 scalar32_min_max_sub(dst_reg, &src_reg); 13329 scalar_min_max_sub(dst_reg, &src_reg); 13330 dst_reg->var_off = tnum_sub(dst_reg->var_off, src_reg.var_off); 13331 break; 13332 case BPF_MUL: 13333 dst_reg->var_off = tnum_mul(dst_reg->var_off, src_reg.var_off); 13334 scalar32_min_max_mul(dst_reg, &src_reg); 13335 scalar_min_max_mul(dst_reg, &src_reg); 13336 break; 13337 case BPF_AND: 13338 dst_reg->var_off = tnum_and(dst_reg->var_off, src_reg.var_off); 13339 scalar32_min_max_and(dst_reg, &src_reg); 13340 scalar_min_max_and(dst_reg, &src_reg); 13341 break; 13342 case BPF_OR: 13343 dst_reg->var_off = tnum_or(dst_reg->var_off, src_reg.var_off); 13344 scalar32_min_max_or(dst_reg, &src_reg); 13345 scalar_min_max_or(dst_reg, &src_reg); 13346 break; 13347 case BPF_XOR: 13348 dst_reg->var_off = tnum_xor(dst_reg->var_off, src_reg.var_off); 13349 scalar32_min_max_xor(dst_reg, &src_reg); 13350 scalar_min_max_xor(dst_reg, &src_reg); 13351 break; 13352 case BPF_LSH: 13353 if (umax_val >= insn_bitness) { 13354 /* Shifts greater than 31 or 63 are undefined. 13355 * This includes shifts by a negative number. 13356 */ 13357 mark_reg_unknown(env, regs, insn->dst_reg); 13358 break; 13359 } 13360 if (alu32) 13361 scalar32_min_max_lsh(dst_reg, &src_reg); 13362 else 13363 scalar_min_max_lsh(dst_reg, &src_reg); 13364 break; 13365 case BPF_RSH: 13366 if (umax_val >= insn_bitness) { 13367 /* Shifts greater than 31 or 63 are undefined. 13368 * This includes shifts by a negative number. 13369 */ 13370 mark_reg_unknown(env, regs, insn->dst_reg); 13371 break; 13372 } 13373 if (alu32) 13374 scalar32_min_max_rsh(dst_reg, &src_reg); 13375 else 13376 scalar_min_max_rsh(dst_reg, &src_reg); 13377 break; 13378 case BPF_ARSH: 13379 if (umax_val >= insn_bitness) { 13380 /* Shifts greater than 31 or 63 are undefined. 13381 * This includes shifts by a negative number. 13382 */ 13383 mark_reg_unknown(env, regs, insn->dst_reg); 13384 break; 13385 } 13386 if (alu32) 13387 scalar32_min_max_arsh(dst_reg, &src_reg); 13388 else 13389 scalar_min_max_arsh(dst_reg, &src_reg); 13390 break; 13391 default: 13392 mark_reg_unknown(env, regs, insn->dst_reg); 13393 break; 13394 } 13395 13396 /* ALU32 ops are zero extended into 64bit register */ 13397 if (alu32) 13398 zext_32_to_64(dst_reg); 13399 reg_bounds_sync(dst_reg); 13400 return 0; 13401 } 13402 13403 /* Handles ALU ops other than BPF_END, BPF_NEG and BPF_MOV: computes new min/max 13404 * and var_off. 13405 */ 13406 static int adjust_reg_min_max_vals(struct bpf_verifier_env *env, 13407 struct bpf_insn *insn) 13408 { 13409 struct bpf_verifier_state *vstate = env->cur_state; 13410 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 13411 struct bpf_reg_state *regs = state->regs, *dst_reg, *src_reg; 13412 struct bpf_reg_state *ptr_reg = NULL, off_reg = {0}; 13413 u8 opcode = BPF_OP(insn->code); 13414 int err; 13415 13416 dst_reg = ®s[insn->dst_reg]; 13417 src_reg = NULL; 13418 if (dst_reg->type != SCALAR_VALUE) 13419 ptr_reg = dst_reg; 13420 else 13421 /* Make sure ID is cleared otherwise dst_reg min/max could be 13422 * incorrectly propagated into other registers by find_equal_scalars() 13423 */ 13424 dst_reg->id = 0; 13425 if (BPF_SRC(insn->code) == BPF_X) { 13426 src_reg = ®s[insn->src_reg]; 13427 if (src_reg->type != SCALAR_VALUE) { 13428 if (dst_reg->type != SCALAR_VALUE) { 13429 /* Combining two pointers by any ALU op yields 13430 * an arbitrary scalar. Disallow all math except 13431 * pointer subtraction 13432 */ 13433 if (opcode == BPF_SUB && env->allow_ptr_leaks) { 13434 mark_reg_unknown(env, regs, insn->dst_reg); 13435 return 0; 13436 } 13437 verbose(env, "R%d pointer %s pointer prohibited\n", 13438 insn->dst_reg, 13439 bpf_alu_string[opcode >> 4]); 13440 return -EACCES; 13441 } else { 13442 /* scalar += pointer 13443 * This is legal, but we have to reverse our 13444 * src/dest handling in computing the range 13445 */ 13446 err = mark_chain_precision(env, insn->dst_reg); 13447 if (err) 13448 return err; 13449 return adjust_ptr_min_max_vals(env, insn, 13450 src_reg, dst_reg); 13451 } 13452 } else if (ptr_reg) { 13453 /* pointer += scalar */ 13454 err = mark_chain_precision(env, insn->src_reg); 13455 if (err) 13456 return err; 13457 return adjust_ptr_min_max_vals(env, insn, 13458 dst_reg, src_reg); 13459 } else if (dst_reg->precise) { 13460 /* if dst_reg is precise, src_reg should be precise as well */ 13461 err = mark_chain_precision(env, insn->src_reg); 13462 if (err) 13463 return err; 13464 } 13465 } else { 13466 /* Pretend the src is a reg with a known value, since we only 13467 * need to be able to read from this state. 13468 */ 13469 off_reg.type = SCALAR_VALUE; 13470 __mark_reg_known(&off_reg, insn->imm); 13471 src_reg = &off_reg; 13472 if (ptr_reg) /* pointer += K */ 13473 return adjust_ptr_min_max_vals(env, insn, 13474 ptr_reg, src_reg); 13475 } 13476 13477 /* Got here implies adding two SCALAR_VALUEs */ 13478 if (WARN_ON_ONCE(ptr_reg)) { 13479 print_verifier_state(env, state, true); 13480 verbose(env, "verifier internal error: unexpected ptr_reg\n"); 13481 return -EINVAL; 13482 } 13483 if (WARN_ON(!src_reg)) { 13484 print_verifier_state(env, state, true); 13485 verbose(env, "verifier internal error: no src_reg\n"); 13486 return -EINVAL; 13487 } 13488 return adjust_scalar_min_max_vals(env, insn, dst_reg, *src_reg); 13489 } 13490 13491 /* check validity of 32-bit and 64-bit arithmetic operations */ 13492 static int check_alu_op(struct bpf_verifier_env *env, struct bpf_insn *insn) 13493 { 13494 struct bpf_reg_state *regs = cur_regs(env); 13495 u8 opcode = BPF_OP(insn->code); 13496 int err; 13497 13498 if (opcode == BPF_END || opcode == BPF_NEG) { 13499 if (opcode == BPF_NEG) { 13500 if (BPF_SRC(insn->code) != BPF_K || 13501 insn->src_reg != BPF_REG_0 || 13502 insn->off != 0 || insn->imm != 0) { 13503 verbose(env, "BPF_NEG uses reserved fields\n"); 13504 return -EINVAL; 13505 } 13506 } else { 13507 if (insn->src_reg != BPF_REG_0 || insn->off != 0 || 13508 (insn->imm != 16 && insn->imm != 32 && insn->imm != 64) || 13509 (BPF_CLASS(insn->code) == BPF_ALU64 && 13510 BPF_SRC(insn->code) != BPF_TO_LE)) { 13511 verbose(env, "BPF_END uses reserved fields\n"); 13512 return -EINVAL; 13513 } 13514 } 13515 13516 /* check src operand */ 13517 err = check_reg_arg(env, insn->dst_reg, SRC_OP); 13518 if (err) 13519 return err; 13520 13521 if (is_pointer_value(env, insn->dst_reg)) { 13522 verbose(env, "R%d pointer arithmetic prohibited\n", 13523 insn->dst_reg); 13524 return -EACCES; 13525 } 13526 13527 /* check dest operand */ 13528 err = check_reg_arg(env, insn->dst_reg, DST_OP); 13529 if (err) 13530 return err; 13531 13532 } else if (opcode == BPF_MOV) { 13533 13534 if (BPF_SRC(insn->code) == BPF_X) { 13535 if (insn->imm != 0) { 13536 verbose(env, "BPF_MOV uses reserved fields\n"); 13537 return -EINVAL; 13538 } 13539 13540 if (BPF_CLASS(insn->code) == BPF_ALU) { 13541 if (insn->off != 0 && insn->off != 8 && insn->off != 16) { 13542 verbose(env, "BPF_MOV uses reserved fields\n"); 13543 return -EINVAL; 13544 } 13545 } else { 13546 if (insn->off != 0 && insn->off != 8 && insn->off != 16 && 13547 insn->off != 32) { 13548 verbose(env, "BPF_MOV uses reserved fields\n"); 13549 return -EINVAL; 13550 } 13551 } 13552 13553 /* check src operand */ 13554 err = check_reg_arg(env, insn->src_reg, SRC_OP); 13555 if (err) 13556 return err; 13557 } else { 13558 if (insn->src_reg != BPF_REG_0 || insn->off != 0) { 13559 verbose(env, "BPF_MOV uses reserved fields\n"); 13560 return -EINVAL; 13561 } 13562 } 13563 13564 /* check dest operand, mark as required later */ 13565 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK); 13566 if (err) 13567 return err; 13568 13569 if (BPF_SRC(insn->code) == BPF_X) { 13570 struct bpf_reg_state *src_reg = regs + insn->src_reg; 13571 struct bpf_reg_state *dst_reg = regs + insn->dst_reg; 13572 bool need_id = src_reg->type == SCALAR_VALUE && !src_reg->id && 13573 !tnum_is_const(src_reg->var_off); 13574 13575 if (BPF_CLASS(insn->code) == BPF_ALU64) { 13576 if (insn->off == 0) { 13577 /* case: R1 = R2 13578 * copy register state to dest reg 13579 */ 13580 if (need_id) 13581 /* Assign src and dst registers the same ID 13582 * that will be used by find_equal_scalars() 13583 * to propagate min/max range. 13584 */ 13585 src_reg->id = ++env->id_gen; 13586 copy_register_state(dst_reg, src_reg); 13587 dst_reg->live |= REG_LIVE_WRITTEN; 13588 dst_reg->subreg_def = DEF_NOT_SUBREG; 13589 } else { 13590 /* case: R1 = (s8, s16 s32)R2 */ 13591 if (is_pointer_value(env, insn->src_reg)) { 13592 verbose(env, 13593 "R%d sign-extension part of pointer\n", 13594 insn->src_reg); 13595 return -EACCES; 13596 } else if (src_reg->type == SCALAR_VALUE) { 13597 bool no_sext; 13598 13599 no_sext = src_reg->umax_value < (1ULL << (insn->off - 1)); 13600 if (no_sext && need_id) 13601 src_reg->id = ++env->id_gen; 13602 copy_register_state(dst_reg, src_reg); 13603 if (!no_sext) 13604 dst_reg->id = 0; 13605 coerce_reg_to_size_sx(dst_reg, insn->off >> 3); 13606 dst_reg->live |= REG_LIVE_WRITTEN; 13607 dst_reg->subreg_def = DEF_NOT_SUBREG; 13608 } else { 13609 mark_reg_unknown(env, regs, insn->dst_reg); 13610 } 13611 } 13612 } else { 13613 /* R1 = (u32) R2 */ 13614 if (is_pointer_value(env, insn->src_reg)) { 13615 verbose(env, 13616 "R%d partial copy of pointer\n", 13617 insn->src_reg); 13618 return -EACCES; 13619 } else if (src_reg->type == SCALAR_VALUE) { 13620 if (insn->off == 0) { 13621 bool is_src_reg_u32 = src_reg->umax_value <= U32_MAX; 13622 13623 if (is_src_reg_u32 && need_id) 13624 src_reg->id = ++env->id_gen; 13625 copy_register_state(dst_reg, src_reg); 13626 /* Make sure ID is cleared if src_reg is not in u32 13627 * range otherwise dst_reg min/max could be incorrectly 13628 * propagated into src_reg by find_equal_scalars() 13629 */ 13630 if (!is_src_reg_u32) 13631 dst_reg->id = 0; 13632 dst_reg->live |= REG_LIVE_WRITTEN; 13633 dst_reg->subreg_def = env->insn_idx + 1; 13634 } else { 13635 /* case: W1 = (s8, s16)W2 */ 13636 bool no_sext = src_reg->umax_value < (1ULL << (insn->off - 1)); 13637 13638 if (no_sext && need_id) 13639 src_reg->id = ++env->id_gen; 13640 copy_register_state(dst_reg, src_reg); 13641 if (!no_sext) 13642 dst_reg->id = 0; 13643 dst_reg->live |= REG_LIVE_WRITTEN; 13644 dst_reg->subreg_def = env->insn_idx + 1; 13645 coerce_subreg_to_size_sx(dst_reg, insn->off >> 3); 13646 } 13647 } else { 13648 mark_reg_unknown(env, regs, 13649 insn->dst_reg); 13650 } 13651 zext_32_to_64(dst_reg); 13652 reg_bounds_sync(dst_reg); 13653 } 13654 } else { 13655 /* case: R = imm 13656 * remember the value we stored into this reg 13657 */ 13658 /* clear any state __mark_reg_known doesn't set */ 13659 mark_reg_unknown(env, regs, insn->dst_reg); 13660 regs[insn->dst_reg].type = SCALAR_VALUE; 13661 if (BPF_CLASS(insn->code) == BPF_ALU64) { 13662 __mark_reg_known(regs + insn->dst_reg, 13663 insn->imm); 13664 } else { 13665 __mark_reg_known(regs + insn->dst_reg, 13666 (u32)insn->imm); 13667 } 13668 } 13669 13670 } else if (opcode > BPF_END) { 13671 verbose(env, "invalid BPF_ALU opcode %x\n", opcode); 13672 return -EINVAL; 13673 13674 } else { /* all other ALU ops: and, sub, xor, add, ... */ 13675 13676 if (BPF_SRC(insn->code) == BPF_X) { 13677 if (insn->imm != 0 || insn->off > 1 || 13678 (insn->off == 1 && opcode != BPF_MOD && opcode != BPF_DIV)) { 13679 verbose(env, "BPF_ALU uses reserved fields\n"); 13680 return -EINVAL; 13681 } 13682 /* check src1 operand */ 13683 err = check_reg_arg(env, insn->src_reg, SRC_OP); 13684 if (err) 13685 return err; 13686 } else { 13687 if (insn->src_reg != BPF_REG_0 || insn->off > 1 || 13688 (insn->off == 1 && opcode != BPF_MOD && opcode != BPF_DIV)) { 13689 verbose(env, "BPF_ALU uses reserved fields\n"); 13690 return -EINVAL; 13691 } 13692 } 13693 13694 /* check src2 operand */ 13695 err = check_reg_arg(env, insn->dst_reg, SRC_OP); 13696 if (err) 13697 return err; 13698 13699 if ((opcode == BPF_MOD || opcode == BPF_DIV) && 13700 BPF_SRC(insn->code) == BPF_K && insn->imm == 0) { 13701 verbose(env, "div by zero\n"); 13702 return -EINVAL; 13703 } 13704 13705 if ((opcode == BPF_LSH || opcode == BPF_RSH || 13706 opcode == BPF_ARSH) && BPF_SRC(insn->code) == BPF_K) { 13707 int size = BPF_CLASS(insn->code) == BPF_ALU64 ? 64 : 32; 13708 13709 if (insn->imm < 0 || insn->imm >= size) { 13710 verbose(env, "invalid shift %d\n", insn->imm); 13711 return -EINVAL; 13712 } 13713 } 13714 13715 /* check dest operand */ 13716 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK); 13717 if (err) 13718 return err; 13719 13720 return adjust_reg_min_max_vals(env, insn); 13721 } 13722 13723 return 0; 13724 } 13725 13726 static void find_good_pkt_pointers(struct bpf_verifier_state *vstate, 13727 struct bpf_reg_state *dst_reg, 13728 enum bpf_reg_type type, 13729 bool range_right_open) 13730 { 13731 struct bpf_func_state *state; 13732 struct bpf_reg_state *reg; 13733 int new_range; 13734 13735 if (dst_reg->off < 0 || 13736 (dst_reg->off == 0 && range_right_open)) 13737 /* This doesn't give us any range */ 13738 return; 13739 13740 if (dst_reg->umax_value > MAX_PACKET_OFF || 13741 dst_reg->umax_value + dst_reg->off > MAX_PACKET_OFF) 13742 /* Risk of overflow. For instance, ptr + (1<<63) may be less 13743 * than pkt_end, but that's because it's also less than pkt. 13744 */ 13745 return; 13746 13747 new_range = dst_reg->off; 13748 if (range_right_open) 13749 new_range++; 13750 13751 /* Examples for register markings: 13752 * 13753 * pkt_data in dst register: 13754 * 13755 * r2 = r3; 13756 * r2 += 8; 13757 * if (r2 > pkt_end) goto <handle exception> 13758 * <access okay> 13759 * 13760 * r2 = r3; 13761 * r2 += 8; 13762 * if (r2 < pkt_end) goto <access okay> 13763 * <handle exception> 13764 * 13765 * Where: 13766 * r2 == dst_reg, pkt_end == src_reg 13767 * r2=pkt(id=n,off=8,r=0) 13768 * r3=pkt(id=n,off=0,r=0) 13769 * 13770 * pkt_data in src register: 13771 * 13772 * r2 = r3; 13773 * r2 += 8; 13774 * if (pkt_end >= r2) goto <access okay> 13775 * <handle exception> 13776 * 13777 * r2 = r3; 13778 * r2 += 8; 13779 * if (pkt_end <= r2) goto <handle exception> 13780 * <access okay> 13781 * 13782 * Where: 13783 * pkt_end == dst_reg, r2 == src_reg 13784 * r2=pkt(id=n,off=8,r=0) 13785 * r3=pkt(id=n,off=0,r=0) 13786 * 13787 * Find register r3 and mark its range as r3=pkt(id=n,off=0,r=8) 13788 * or r3=pkt(id=n,off=0,r=8-1), so that range of bytes [r3, r3 + 8) 13789 * and [r3, r3 + 8-1) respectively is safe to access depending on 13790 * the check. 13791 */ 13792 13793 /* If our ids match, then we must have the same max_value. And we 13794 * don't care about the other reg's fixed offset, since if it's too big 13795 * the range won't allow anything. 13796 * dst_reg->off is known < MAX_PACKET_OFF, therefore it fits in a u16. 13797 */ 13798 bpf_for_each_reg_in_vstate(vstate, state, reg, ({ 13799 if (reg->type == type && reg->id == dst_reg->id) 13800 /* keep the maximum range already checked */ 13801 reg->range = max(reg->range, new_range); 13802 })); 13803 } 13804 13805 static int is_branch32_taken(struct bpf_reg_state *reg, u32 val, u8 opcode) 13806 { 13807 struct tnum subreg = tnum_subreg(reg->var_off); 13808 s32 sval = (s32)val; 13809 13810 switch (opcode) { 13811 case BPF_JEQ: 13812 if (tnum_is_const(subreg)) 13813 return !!tnum_equals_const(subreg, val); 13814 else if (val < reg->u32_min_value || val > reg->u32_max_value) 13815 return 0; 13816 break; 13817 case BPF_JNE: 13818 if (tnum_is_const(subreg)) 13819 return !tnum_equals_const(subreg, val); 13820 else if (val < reg->u32_min_value || val > reg->u32_max_value) 13821 return 1; 13822 break; 13823 case BPF_JSET: 13824 if ((~subreg.mask & subreg.value) & val) 13825 return 1; 13826 if (!((subreg.mask | subreg.value) & val)) 13827 return 0; 13828 break; 13829 case BPF_JGT: 13830 if (reg->u32_min_value > val) 13831 return 1; 13832 else if (reg->u32_max_value <= val) 13833 return 0; 13834 break; 13835 case BPF_JSGT: 13836 if (reg->s32_min_value > sval) 13837 return 1; 13838 else if (reg->s32_max_value <= sval) 13839 return 0; 13840 break; 13841 case BPF_JLT: 13842 if (reg->u32_max_value < val) 13843 return 1; 13844 else if (reg->u32_min_value >= val) 13845 return 0; 13846 break; 13847 case BPF_JSLT: 13848 if (reg->s32_max_value < sval) 13849 return 1; 13850 else if (reg->s32_min_value >= sval) 13851 return 0; 13852 break; 13853 case BPF_JGE: 13854 if (reg->u32_min_value >= val) 13855 return 1; 13856 else if (reg->u32_max_value < val) 13857 return 0; 13858 break; 13859 case BPF_JSGE: 13860 if (reg->s32_min_value >= sval) 13861 return 1; 13862 else if (reg->s32_max_value < sval) 13863 return 0; 13864 break; 13865 case BPF_JLE: 13866 if (reg->u32_max_value <= val) 13867 return 1; 13868 else if (reg->u32_min_value > val) 13869 return 0; 13870 break; 13871 case BPF_JSLE: 13872 if (reg->s32_max_value <= sval) 13873 return 1; 13874 else if (reg->s32_min_value > sval) 13875 return 0; 13876 break; 13877 } 13878 13879 return -1; 13880 } 13881 13882 13883 static int is_branch64_taken(struct bpf_reg_state *reg, u64 val, u8 opcode) 13884 { 13885 s64 sval = (s64)val; 13886 13887 switch (opcode) { 13888 case BPF_JEQ: 13889 if (tnum_is_const(reg->var_off)) 13890 return !!tnum_equals_const(reg->var_off, val); 13891 else if (val < reg->umin_value || val > reg->umax_value) 13892 return 0; 13893 break; 13894 case BPF_JNE: 13895 if (tnum_is_const(reg->var_off)) 13896 return !tnum_equals_const(reg->var_off, val); 13897 else if (val < reg->umin_value || val > reg->umax_value) 13898 return 1; 13899 break; 13900 case BPF_JSET: 13901 if ((~reg->var_off.mask & reg->var_off.value) & val) 13902 return 1; 13903 if (!((reg->var_off.mask | reg->var_off.value) & val)) 13904 return 0; 13905 break; 13906 case BPF_JGT: 13907 if (reg->umin_value > val) 13908 return 1; 13909 else if (reg->umax_value <= val) 13910 return 0; 13911 break; 13912 case BPF_JSGT: 13913 if (reg->smin_value > sval) 13914 return 1; 13915 else if (reg->smax_value <= sval) 13916 return 0; 13917 break; 13918 case BPF_JLT: 13919 if (reg->umax_value < val) 13920 return 1; 13921 else if (reg->umin_value >= val) 13922 return 0; 13923 break; 13924 case BPF_JSLT: 13925 if (reg->smax_value < sval) 13926 return 1; 13927 else if (reg->smin_value >= sval) 13928 return 0; 13929 break; 13930 case BPF_JGE: 13931 if (reg->umin_value >= val) 13932 return 1; 13933 else if (reg->umax_value < val) 13934 return 0; 13935 break; 13936 case BPF_JSGE: 13937 if (reg->smin_value >= sval) 13938 return 1; 13939 else if (reg->smax_value < sval) 13940 return 0; 13941 break; 13942 case BPF_JLE: 13943 if (reg->umax_value <= val) 13944 return 1; 13945 else if (reg->umin_value > val) 13946 return 0; 13947 break; 13948 case BPF_JSLE: 13949 if (reg->smax_value <= sval) 13950 return 1; 13951 else if (reg->smin_value > sval) 13952 return 0; 13953 break; 13954 } 13955 13956 return -1; 13957 } 13958 13959 /* compute branch direction of the expression "if (reg opcode val) goto target;" 13960 * and return: 13961 * 1 - branch will be taken and "goto target" will be executed 13962 * 0 - branch will not be taken and fall-through to next insn 13963 * -1 - unknown. Example: "if (reg < 5)" is unknown when register value 13964 * range [0,10] 13965 */ 13966 static int is_branch_taken(struct bpf_reg_state *reg, u64 val, u8 opcode, 13967 bool is_jmp32) 13968 { 13969 if (__is_pointer_value(false, reg)) { 13970 if (!reg_not_null(reg)) 13971 return -1; 13972 13973 /* If pointer is valid tests against zero will fail so we can 13974 * use this to direct branch taken. 13975 */ 13976 if (val != 0) 13977 return -1; 13978 13979 switch (opcode) { 13980 case BPF_JEQ: 13981 return 0; 13982 case BPF_JNE: 13983 return 1; 13984 default: 13985 return -1; 13986 } 13987 } 13988 13989 if (is_jmp32) 13990 return is_branch32_taken(reg, val, opcode); 13991 return is_branch64_taken(reg, val, opcode); 13992 } 13993 13994 static int flip_opcode(u32 opcode) 13995 { 13996 /* How can we transform "a <op> b" into "b <op> a"? */ 13997 static const u8 opcode_flip[16] = { 13998 /* these stay the same */ 13999 [BPF_JEQ >> 4] = BPF_JEQ, 14000 [BPF_JNE >> 4] = BPF_JNE, 14001 [BPF_JSET >> 4] = BPF_JSET, 14002 /* these swap "lesser" and "greater" (L and G in the opcodes) */ 14003 [BPF_JGE >> 4] = BPF_JLE, 14004 [BPF_JGT >> 4] = BPF_JLT, 14005 [BPF_JLE >> 4] = BPF_JGE, 14006 [BPF_JLT >> 4] = BPF_JGT, 14007 [BPF_JSGE >> 4] = BPF_JSLE, 14008 [BPF_JSGT >> 4] = BPF_JSLT, 14009 [BPF_JSLE >> 4] = BPF_JSGE, 14010 [BPF_JSLT >> 4] = BPF_JSGT 14011 }; 14012 return opcode_flip[opcode >> 4]; 14013 } 14014 14015 static int is_pkt_ptr_branch_taken(struct bpf_reg_state *dst_reg, 14016 struct bpf_reg_state *src_reg, 14017 u8 opcode) 14018 { 14019 struct bpf_reg_state *pkt; 14020 14021 if (src_reg->type == PTR_TO_PACKET_END) { 14022 pkt = dst_reg; 14023 } else if (dst_reg->type == PTR_TO_PACKET_END) { 14024 pkt = src_reg; 14025 opcode = flip_opcode(opcode); 14026 } else { 14027 return -1; 14028 } 14029 14030 if (pkt->range >= 0) 14031 return -1; 14032 14033 switch (opcode) { 14034 case BPF_JLE: 14035 /* pkt <= pkt_end */ 14036 fallthrough; 14037 case BPF_JGT: 14038 /* pkt > pkt_end */ 14039 if (pkt->range == BEYOND_PKT_END) 14040 /* pkt has at last one extra byte beyond pkt_end */ 14041 return opcode == BPF_JGT; 14042 break; 14043 case BPF_JLT: 14044 /* pkt < pkt_end */ 14045 fallthrough; 14046 case BPF_JGE: 14047 /* pkt >= pkt_end */ 14048 if (pkt->range == BEYOND_PKT_END || pkt->range == AT_PKT_END) 14049 return opcode == BPF_JGE; 14050 break; 14051 } 14052 return -1; 14053 } 14054 14055 /* Adjusts the register min/max values in the case that the dst_reg is the 14056 * variable register that we are working on, and src_reg is a constant or we're 14057 * simply doing a BPF_K check. 14058 * In JEQ/JNE cases we also adjust the var_off values. 14059 */ 14060 static void reg_set_min_max(struct bpf_reg_state *true_reg, 14061 struct bpf_reg_state *false_reg, 14062 u64 val, u32 val32, 14063 u8 opcode, bool is_jmp32) 14064 { 14065 struct tnum false_32off = tnum_subreg(false_reg->var_off); 14066 struct tnum false_64off = false_reg->var_off; 14067 struct tnum true_32off = tnum_subreg(true_reg->var_off); 14068 struct tnum true_64off = true_reg->var_off; 14069 s64 sval = (s64)val; 14070 s32 sval32 = (s32)val32; 14071 14072 /* If the dst_reg is a pointer, we can't learn anything about its 14073 * variable offset from the compare (unless src_reg were a pointer into 14074 * the same object, but we don't bother with that. 14075 * Since false_reg and true_reg have the same type by construction, we 14076 * only need to check one of them for pointerness. 14077 */ 14078 if (__is_pointer_value(false, false_reg)) 14079 return; 14080 14081 switch (opcode) { 14082 /* JEQ/JNE comparison doesn't change the register equivalence. 14083 * 14084 * r1 = r2; 14085 * if (r1 == 42) goto label; 14086 * ... 14087 * label: // here both r1 and r2 are known to be 42. 14088 * 14089 * Hence when marking register as known preserve it's ID. 14090 */ 14091 case BPF_JEQ: 14092 if (is_jmp32) { 14093 __mark_reg32_known(true_reg, val32); 14094 true_32off = tnum_subreg(true_reg->var_off); 14095 } else { 14096 ___mark_reg_known(true_reg, val); 14097 true_64off = true_reg->var_off; 14098 } 14099 break; 14100 case BPF_JNE: 14101 if (is_jmp32) { 14102 __mark_reg32_known(false_reg, val32); 14103 false_32off = tnum_subreg(false_reg->var_off); 14104 } else { 14105 ___mark_reg_known(false_reg, val); 14106 false_64off = false_reg->var_off; 14107 } 14108 break; 14109 case BPF_JSET: 14110 if (is_jmp32) { 14111 false_32off = tnum_and(false_32off, tnum_const(~val32)); 14112 if (is_power_of_2(val32)) 14113 true_32off = tnum_or(true_32off, 14114 tnum_const(val32)); 14115 } else { 14116 false_64off = tnum_and(false_64off, tnum_const(~val)); 14117 if (is_power_of_2(val)) 14118 true_64off = tnum_or(true_64off, 14119 tnum_const(val)); 14120 } 14121 break; 14122 case BPF_JGE: 14123 case BPF_JGT: 14124 { 14125 if (is_jmp32) { 14126 u32 false_umax = opcode == BPF_JGT ? val32 : val32 - 1; 14127 u32 true_umin = opcode == BPF_JGT ? val32 + 1 : val32; 14128 14129 false_reg->u32_max_value = min(false_reg->u32_max_value, 14130 false_umax); 14131 true_reg->u32_min_value = max(true_reg->u32_min_value, 14132 true_umin); 14133 } else { 14134 u64 false_umax = opcode == BPF_JGT ? val : val - 1; 14135 u64 true_umin = opcode == BPF_JGT ? val + 1 : val; 14136 14137 false_reg->umax_value = min(false_reg->umax_value, false_umax); 14138 true_reg->umin_value = max(true_reg->umin_value, true_umin); 14139 } 14140 break; 14141 } 14142 case BPF_JSGE: 14143 case BPF_JSGT: 14144 { 14145 if (is_jmp32) { 14146 s32 false_smax = opcode == BPF_JSGT ? sval32 : sval32 - 1; 14147 s32 true_smin = opcode == BPF_JSGT ? sval32 + 1 : sval32; 14148 14149 false_reg->s32_max_value = min(false_reg->s32_max_value, false_smax); 14150 true_reg->s32_min_value = max(true_reg->s32_min_value, true_smin); 14151 } else { 14152 s64 false_smax = opcode == BPF_JSGT ? sval : sval - 1; 14153 s64 true_smin = opcode == BPF_JSGT ? sval + 1 : sval; 14154 14155 false_reg->smax_value = min(false_reg->smax_value, false_smax); 14156 true_reg->smin_value = max(true_reg->smin_value, true_smin); 14157 } 14158 break; 14159 } 14160 case BPF_JLE: 14161 case BPF_JLT: 14162 { 14163 if (is_jmp32) { 14164 u32 false_umin = opcode == BPF_JLT ? val32 : val32 + 1; 14165 u32 true_umax = opcode == BPF_JLT ? val32 - 1 : val32; 14166 14167 false_reg->u32_min_value = max(false_reg->u32_min_value, 14168 false_umin); 14169 true_reg->u32_max_value = min(true_reg->u32_max_value, 14170 true_umax); 14171 } else { 14172 u64 false_umin = opcode == BPF_JLT ? val : val + 1; 14173 u64 true_umax = opcode == BPF_JLT ? val - 1 : val; 14174 14175 false_reg->umin_value = max(false_reg->umin_value, false_umin); 14176 true_reg->umax_value = min(true_reg->umax_value, true_umax); 14177 } 14178 break; 14179 } 14180 case BPF_JSLE: 14181 case BPF_JSLT: 14182 { 14183 if (is_jmp32) { 14184 s32 false_smin = opcode == BPF_JSLT ? sval32 : sval32 + 1; 14185 s32 true_smax = opcode == BPF_JSLT ? sval32 - 1 : sval32; 14186 14187 false_reg->s32_min_value = max(false_reg->s32_min_value, false_smin); 14188 true_reg->s32_max_value = min(true_reg->s32_max_value, true_smax); 14189 } else { 14190 s64 false_smin = opcode == BPF_JSLT ? sval : sval + 1; 14191 s64 true_smax = opcode == BPF_JSLT ? sval - 1 : sval; 14192 14193 false_reg->smin_value = max(false_reg->smin_value, false_smin); 14194 true_reg->smax_value = min(true_reg->smax_value, true_smax); 14195 } 14196 break; 14197 } 14198 default: 14199 return; 14200 } 14201 14202 if (is_jmp32) { 14203 false_reg->var_off = tnum_or(tnum_clear_subreg(false_64off), 14204 tnum_subreg(false_32off)); 14205 true_reg->var_off = tnum_or(tnum_clear_subreg(true_64off), 14206 tnum_subreg(true_32off)); 14207 __reg_combine_32_into_64(false_reg); 14208 __reg_combine_32_into_64(true_reg); 14209 } else { 14210 false_reg->var_off = false_64off; 14211 true_reg->var_off = true_64off; 14212 __reg_combine_64_into_32(false_reg); 14213 __reg_combine_64_into_32(true_reg); 14214 } 14215 } 14216 14217 /* Same as above, but for the case that dst_reg holds a constant and src_reg is 14218 * the variable reg. 14219 */ 14220 static void reg_set_min_max_inv(struct bpf_reg_state *true_reg, 14221 struct bpf_reg_state *false_reg, 14222 u64 val, u32 val32, 14223 u8 opcode, bool is_jmp32) 14224 { 14225 opcode = flip_opcode(opcode); 14226 /* This uses zero as "not present in table"; luckily the zero opcode, 14227 * BPF_JA, can't get here. 14228 */ 14229 if (opcode) 14230 reg_set_min_max(true_reg, false_reg, val, val32, opcode, is_jmp32); 14231 } 14232 14233 /* Regs are known to be equal, so intersect their min/max/var_off */ 14234 static void __reg_combine_min_max(struct bpf_reg_state *src_reg, 14235 struct bpf_reg_state *dst_reg) 14236 { 14237 src_reg->umin_value = dst_reg->umin_value = max(src_reg->umin_value, 14238 dst_reg->umin_value); 14239 src_reg->umax_value = dst_reg->umax_value = min(src_reg->umax_value, 14240 dst_reg->umax_value); 14241 src_reg->smin_value = dst_reg->smin_value = max(src_reg->smin_value, 14242 dst_reg->smin_value); 14243 src_reg->smax_value = dst_reg->smax_value = min(src_reg->smax_value, 14244 dst_reg->smax_value); 14245 src_reg->var_off = dst_reg->var_off = tnum_intersect(src_reg->var_off, 14246 dst_reg->var_off); 14247 reg_bounds_sync(src_reg); 14248 reg_bounds_sync(dst_reg); 14249 } 14250 14251 static void reg_combine_min_max(struct bpf_reg_state *true_src, 14252 struct bpf_reg_state *true_dst, 14253 struct bpf_reg_state *false_src, 14254 struct bpf_reg_state *false_dst, 14255 u8 opcode) 14256 { 14257 switch (opcode) { 14258 case BPF_JEQ: 14259 __reg_combine_min_max(true_src, true_dst); 14260 break; 14261 case BPF_JNE: 14262 __reg_combine_min_max(false_src, false_dst); 14263 break; 14264 } 14265 } 14266 14267 static void mark_ptr_or_null_reg(struct bpf_func_state *state, 14268 struct bpf_reg_state *reg, u32 id, 14269 bool is_null) 14270 { 14271 if (type_may_be_null(reg->type) && reg->id == id && 14272 (is_rcu_reg(reg) || !WARN_ON_ONCE(!reg->id))) { 14273 /* Old offset (both fixed and variable parts) should have been 14274 * known-zero, because we don't allow pointer arithmetic on 14275 * pointers that might be NULL. If we see this happening, don't 14276 * convert the register. 14277 * 14278 * But in some cases, some helpers that return local kptrs 14279 * advance offset for the returned pointer. In those cases, it 14280 * is fine to expect to see reg->off. 14281 */ 14282 if (WARN_ON_ONCE(reg->smin_value || reg->smax_value || !tnum_equals_const(reg->var_off, 0))) 14283 return; 14284 if (!(type_is_ptr_alloc_obj(reg->type) || type_is_non_owning_ref(reg->type)) && 14285 WARN_ON_ONCE(reg->off)) 14286 return; 14287 14288 if (is_null) { 14289 reg->type = SCALAR_VALUE; 14290 /* We don't need id and ref_obj_id from this point 14291 * onwards anymore, thus we should better reset it, 14292 * so that state pruning has chances to take effect. 14293 */ 14294 reg->id = 0; 14295 reg->ref_obj_id = 0; 14296 14297 return; 14298 } 14299 14300 mark_ptr_not_null_reg(reg); 14301 14302 if (!reg_may_point_to_spin_lock(reg)) { 14303 /* For not-NULL ptr, reg->ref_obj_id will be reset 14304 * in release_reference(). 14305 * 14306 * reg->id is still used by spin_lock ptr. Other 14307 * than spin_lock ptr type, reg->id can be reset. 14308 */ 14309 reg->id = 0; 14310 } 14311 } 14312 } 14313 14314 /* The logic is similar to find_good_pkt_pointers(), both could eventually 14315 * be folded together at some point. 14316 */ 14317 static void mark_ptr_or_null_regs(struct bpf_verifier_state *vstate, u32 regno, 14318 bool is_null) 14319 { 14320 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 14321 struct bpf_reg_state *regs = state->regs, *reg; 14322 u32 ref_obj_id = regs[regno].ref_obj_id; 14323 u32 id = regs[regno].id; 14324 14325 if (ref_obj_id && ref_obj_id == id && is_null) 14326 /* regs[regno] is in the " == NULL" branch. 14327 * No one could have freed the reference state before 14328 * doing the NULL check. 14329 */ 14330 WARN_ON_ONCE(release_reference_state(state, id)); 14331 14332 bpf_for_each_reg_in_vstate(vstate, state, reg, ({ 14333 mark_ptr_or_null_reg(state, reg, id, is_null); 14334 })); 14335 } 14336 14337 static bool try_match_pkt_pointers(const struct bpf_insn *insn, 14338 struct bpf_reg_state *dst_reg, 14339 struct bpf_reg_state *src_reg, 14340 struct bpf_verifier_state *this_branch, 14341 struct bpf_verifier_state *other_branch) 14342 { 14343 if (BPF_SRC(insn->code) != BPF_X) 14344 return false; 14345 14346 /* Pointers are always 64-bit. */ 14347 if (BPF_CLASS(insn->code) == BPF_JMP32) 14348 return false; 14349 14350 switch (BPF_OP(insn->code)) { 14351 case BPF_JGT: 14352 if ((dst_reg->type == PTR_TO_PACKET && 14353 src_reg->type == PTR_TO_PACKET_END) || 14354 (dst_reg->type == PTR_TO_PACKET_META && 14355 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) { 14356 /* pkt_data' > pkt_end, pkt_meta' > pkt_data */ 14357 find_good_pkt_pointers(this_branch, dst_reg, 14358 dst_reg->type, false); 14359 mark_pkt_end(other_branch, insn->dst_reg, true); 14360 } else if ((dst_reg->type == PTR_TO_PACKET_END && 14361 src_reg->type == PTR_TO_PACKET) || 14362 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) && 14363 src_reg->type == PTR_TO_PACKET_META)) { 14364 /* pkt_end > pkt_data', pkt_data > pkt_meta' */ 14365 find_good_pkt_pointers(other_branch, src_reg, 14366 src_reg->type, true); 14367 mark_pkt_end(this_branch, insn->src_reg, false); 14368 } else { 14369 return false; 14370 } 14371 break; 14372 case BPF_JLT: 14373 if ((dst_reg->type == PTR_TO_PACKET && 14374 src_reg->type == PTR_TO_PACKET_END) || 14375 (dst_reg->type == PTR_TO_PACKET_META && 14376 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) { 14377 /* pkt_data' < pkt_end, pkt_meta' < pkt_data */ 14378 find_good_pkt_pointers(other_branch, dst_reg, 14379 dst_reg->type, true); 14380 mark_pkt_end(this_branch, insn->dst_reg, false); 14381 } else if ((dst_reg->type == PTR_TO_PACKET_END && 14382 src_reg->type == PTR_TO_PACKET) || 14383 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) && 14384 src_reg->type == PTR_TO_PACKET_META)) { 14385 /* pkt_end < pkt_data', pkt_data > pkt_meta' */ 14386 find_good_pkt_pointers(this_branch, src_reg, 14387 src_reg->type, false); 14388 mark_pkt_end(other_branch, insn->src_reg, true); 14389 } else { 14390 return false; 14391 } 14392 break; 14393 case BPF_JGE: 14394 if ((dst_reg->type == PTR_TO_PACKET && 14395 src_reg->type == PTR_TO_PACKET_END) || 14396 (dst_reg->type == PTR_TO_PACKET_META && 14397 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) { 14398 /* pkt_data' >= pkt_end, pkt_meta' >= pkt_data */ 14399 find_good_pkt_pointers(this_branch, dst_reg, 14400 dst_reg->type, true); 14401 mark_pkt_end(other_branch, insn->dst_reg, false); 14402 } else if ((dst_reg->type == PTR_TO_PACKET_END && 14403 src_reg->type == PTR_TO_PACKET) || 14404 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) && 14405 src_reg->type == PTR_TO_PACKET_META)) { 14406 /* pkt_end >= pkt_data', pkt_data >= pkt_meta' */ 14407 find_good_pkt_pointers(other_branch, src_reg, 14408 src_reg->type, false); 14409 mark_pkt_end(this_branch, insn->src_reg, true); 14410 } else { 14411 return false; 14412 } 14413 break; 14414 case BPF_JLE: 14415 if ((dst_reg->type == PTR_TO_PACKET && 14416 src_reg->type == PTR_TO_PACKET_END) || 14417 (dst_reg->type == PTR_TO_PACKET_META && 14418 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) { 14419 /* pkt_data' <= pkt_end, pkt_meta' <= pkt_data */ 14420 find_good_pkt_pointers(other_branch, dst_reg, 14421 dst_reg->type, false); 14422 mark_pkt_end(this_branch, insn->dst_reg, true); 14423 } else if ((dst_reg->type == PTR_TO_PACKET_END && 14424 src_reg->type == PTR_TO_PACKET) || 14425 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) && 14426 src_reg->type == PTR_TO_PACKET_META)) { 14427 /* pkt_end <= pkt_data', pkt_data <= pkt_meta' */ 14428 find_good_pkt_pointers(this_branch, src_reg, 14429 src_reg->type, true); 14430 mark_pkt_end(other_branch, insn->src_reg, false); 14431 } else { 14432 return false; 14433 } 14434 break; 14435 default: 14436 return false; 14437 } 14438 14439 return true; 14440 } 14441 14442 static void find_equal_scalars(struct bpf_verifier_state *vstate, 14443 struct bpf_reg_state *known_reg) 14444 { 14445 struct bpf_func_state *state; 14446 struct bpf_reg_state *reg; 14447 14448 bpf_for_each_reg_in_vstate(vstate, state, reg, ({ 14449 if (reg->type == SCALAR_VALUE && reg->id == known_reg->id) 14450 copy_register_state(reg, known_reg); 14451 })); 14452 } 14453 14454 static int check_cond_jmp_op(struct bpf_verifier_env *env, 14455 struct bpf_insn *insn, int *insn_idx) 14456 { 14457 struct bpf_verifier_state *this_branch = env->cur_state; 14458 struct bpf_verifier_state *other_branch; 14459 struct bpf_reg_state *regs = this_branch->frame[this_branch->curframe]->regs; 14460 struct bpf_reg_state *dst_reg, *other_branch_regs, *src_reg = NULL; 14461 struct bpf_reg_state *eq_branch_regs; 14462 u8 opcode = BPF_OP(insn->code); 14463 bool is_jmp32; 14464 int pred = -1; 14465 int err; 14466 14467 /* Only conditional jumps are expected to reach here. */ 14468 if (opcode == BPF_JA || opcode > BPF_JSLE) { 14469 verbose(env, "invalid BPF_JMP/JMP32 opcode %x\n", opcode); 14470 return -EINVAL; 14471 } 14472 14473 /* check src2 operand */ 14474 err = check_reg_arg(env, insn->dst_reg, SRC_OP); 14475 if (err) 14476 return err; 14477 14478 dst_reg = ®s[insn->dst_reg]; 14479 if (BPF_SRC(insn->code) == BPF_X) { 14480 if (insn->imm != 0) { 14481 verbose(env, "BPF_JMP/JMP32 uses reserved fields\n"); 14482 return -EINVAL; 14483 } 14484 14485 /* check src1 operand */ 14486 err = check_reg_arg(env, insn->src_reg, SRC_OP); 14487 if (err) 14488 return err; 14489 14490 src_reg = ®s[insn->src_reg]; 14491 if (!(reg_is_pkt_pointer_any(dst_reg) && reg_is_pkt_pointer_any(src_reg)) && 14492 is_pointer_value(env, insn->src_reg)) { 14493 verbose(env, "R%d pointer comparison prohibited\n", 14494 insn->src_reg); 14495 return -EACCES; 14496 } 14497 } else { 14498 if (insn->src_reg != BPF_REG_0) { 14499 verbose(env, "BPF_JMP/JMP32 uses reserved fields\n"); 14500 return -EINVAL; 14501 } 14502 } 14503 14504 is_jmp32 = BPF_CLASS(insn->code) == BPF_JMP32; 14505 14506 if (BPF_SRC(insn->code) == BPF_K) { 14507 pred = is_branch_taken(dst_reg, insn->imm, opcode, is_jmp32); 14508 } else if (src_reg->type == SCALAR_VALUE && 14509 is_jmp32 && tnum_is_const(tnum_subreg(src_reg->var_off))) { 14510 pred = is_branch_taken(dst_reg, 14511 tnum_subreg(src_reg->var_off).value, 14512 opcode, 14513 is_jmp32); 14514 } else if (src_reg->type == SCALAR_VALUE && 14515 !is_jmp32 && tnum_is_const(src_reg->var_off)) { 14516 pred = is_branch_taken(dst_reg, 14517 src_reg->var_off.value, 14518 opcode, 14519 is_jmp32); 14520 } else if (dst_reg->type == SCALAR_VALUE && 14521 is_jmp32 && tnum_is_const(tnum_subreg(dst_reg->var_off))) { 14522 pred = is_branch_taken(src_reg, 14523 tnum_subreg(dst_reg->var_off).value, 14524 flip_opcode(opcode), 14525 is_jmp32); 14526 } else if (dst_reg->type == SCALAR_VALUE && 14527 !is_jmp32 && tnum_is_const(dst_reg->var_off)) { 14528 pred = is_branch_taken(src_reg, 14529 dst_reg->var_off.value, 14530 flip_opcode(opcode), 14531 is_jmp32); 14532 } else if (reg_is_pkt_pointer_any(dst_reg) && 14533 reg_is_pkt_pointer_any(src_reg) && 14534 !is_jmp32) { 14535 pred = is_pkt_ptr_branch_taken(dst_reg, src_reg, opcode); 14536 } 14537 14538 if (pred >= 0) { 14539 /* If we get here with a dst_reg pointer type it is because 14540 * above is_branch_taken() special cased the 0 comparison. 14541 */ 14542 if (!__is_pointer_value(false, dst_reg)) 14543 err = mark_chain_precision(env, insn->dst_reg); 14544 if (BPF_SRC(insn->code) == BPF_X && !err && 14545 !__is_pointer_value(false, src_reg)) 14546 err = mark_chain_precision(env, insn->src_reg); 14547 if (err) 14548 return err; 14549 } 14550 14551 if (pred == 1) { 14552 /* Only follow the goto, ignore fall-through. If needed, push 14553 * the fall-through branch for simulation under speculative 14554 * execution. 14555 */ 14556 if (!env->bypass_spec_v1 && 14557 !sanitize_speculative_path(env, insn, *insn_idx + 1, 14558 *insn_idx)) 14559 return -EFAULT; 14560 if (env->log.level & BPF_LOG_LEVEL) 14561 print_insn_state(env, this_branch->frame[this_branch->curframe]); 14562 *insn_idx += insn->off; 14563 return 0; 14564 } else if (pred == 0) { 14565 /* Only follow the fall-through branch, since that's where the 14566 * program will go. If needed, push the goto branch for 14567 * simulation under speculative execution. 14568 */ 14569 if (!env->bypass_spec_v1 && 14570 !sanitize_speculative_path(env, insn, 14571 *insn_idx + insn->off + 1, 14572 *insn_idx)) 14573 return -EFAULT; 14574 if (env->log.level & BPF_LOG_LEVEL) 14575 print_insn_state(env, this_branch->frame[this_branch->curframe]); 14576 return 0; 14577 } 14578 14579 other_branch = push_stack(env, *insn_idx + insn->off + 1, *insn_idx, 14580 false); 14581 if (!other_branch) 14582 return -EFAULT; 14583 other_branch_regs = other_branch->frame[other_branch->curframe]->regs; 14584 14585 /* detect if we are comparing against a constant value so we can adjust 14586 * our min/max values for our dst register. 14587 * this is only legit if both are scalars (or pointers to the same 14588 * object, I suppose, see the PTR_MAYBE_NULL related if block below), 14589 * because otherwise the different base pointers mean the offsets aren't 14590 * comparable. 14591 */ 14592 if (BPF_SRC(insn->code) == BPF_X) { 14593 struct bpf_reg_state *src_reg = ®s[insn->src_reg]; 14594 14595 if (dst_reg->type == SCALAR_VALUE && 14596 src_reg->type == SCALAR_VALUE) { 14597 if (tnum_is_const(src_reg->var_off) || 14598 (is_jmp32 && 14599 tnum_is_const(tnum_subreg(src_reg->var_off)))) 14600 reg_set_min_max(&other_branch_regs[insn->dst_reg], 14601 dst_reg, 14602 src_reg->var_off.value, 14603 tnum_subreg(src_reg->var_off).value, 14604 opcode, is_jmp32); 14605 else if (tnum_is_const(dst_reg->var_off) || 14606 (is_jmp32 && 14607 tnum_is_const(tnum_subreg(dst_reg->var_off)))) 14608 reg_set_min_max_inv(&other_branch_regs[insn->src_reg], 14609 src_reg, 14610 dst_reg->var_off.value, 14611 tnum_subreg(dst_reg->var_off).value, 14612 opcode, is_jmp32); 14613 else if (!is_jmp32 && 14614 (opcode == BPF_JEQ || opcode == BPF_JNE)) 14615 /* Comparing for equality, we can combine knowledge */ 14616 reg_combine_min_max(&other_branch_regs[insn->src_reg], 14617 &other_branch_regs[insn->dst_reg], 14618 src_reg, dst_reg, opcode); 14619 if (src_reg->id && 14620 !WARN_ON_ONCE(src_reg->id != other_branch_regs[insn->src_reg].id)) { 14621 find_equal_scalars(this_branch, src_reg); 14622 find_equal_scalars(other_branch, &other_branch_regs[insn->src_reg]); 14623 } 14624 14625 } 14626 } else if (dst_reg->type == SCALAR_VALUE) { 14627 reg_set_min_max(&other_branch_regs[insn->dst_reg], 14628 dst_reg, insn->imm, (u32)insn->imm, 14629 opcode, is_jmp32); 14630 } 14631 14632 if (dst_reg->type == SCALAR_VALUE && dst_reg->id && 14633 !WARN_ON_ONCE(dst_reg->id != other_branch_regs[insn->dst_reg].id)) { 14634 find_equal_scalars(this_branch, dst_reg); 14635 find_equal_scalars(other_branch, &other_branch_regs[insn->dst_reg]); 14636 } 14637 14638 /* if one pointer register is compared to another pointer 14639 * register check if PTR_MAYBE_NULL could be lifted. 14640 * E.g. register A - maybe null 14641 * register B - not null 14642 * for JNE A, B, ... - A is not null in the false branch; 14643 * for JEQ A, B, ... - A is not null in the true branch. 14644 * 14645 * Since PTR_TO_BTF_ID points to a kernel struct that does 14646 * not need to be null checked by the BPF program, i.e., 14647 * could be null even without PTR_MAYBE_NULL marking, so 14648 * only propagate nullness when neither reg is that type. 14649 */ 14650 if (!is_jmp32 && BPF_SRC(insn->code) == BPF_X && 14651 __is_pointer_value(false, src_reg) && __is_pointer_value(false, dst_reg) && 14652 type_may_be_null(src_reg->type) != type_may_be_null(dst_reg->type) && 14653 base_type(src_reg->type) != PTR_TO_BTF_ID && 14654 base_type(dst_reg->type) != PTR_TO_BTF_ID) { 14655 eq_branch_regs = NULL; 14656 switch (opcode) { 14657 case BPF_JEQ: 14658 eq_branch_regs = other_branch_regs; 14659 break; 14660 case BPF_JNE: 14661 eq_branch_regs = regs; 14662 break; 14663 default: 14664 /* do nothing */ 14665 break; 14666 } 14667 if (eq_branch_regs) { 14668 if (type_may_be_null(src_reg->type)) 14669 mark_ptr_not_null_reg(&eq_branch_regs[insn->src_reg]); 14670 else 14671 mark_ptr_not_null_reg(&eq_branch_regs[insn->dst_reg]); 14672 } 14673 } 14674 14675 /* detect if R == 0 where R is returned from bpf_map_lookup_elem(). 14676 * NOTE: these optimizations below are related with pointer comparison 14677 * which will never be JMP32. 14678 */ 14679 if (!is_jmp32 && BPF_SRC(insn->code) == BPF_K && 14680 insn->imm == 0 && (opcode == BPF_JEQ || opcode == BPF_JNE) && 14681 type_may_be_null(dst_reg->type)) { 14682 /* Mark all identical registers in each branch as either 14683 * safe or unknown depending R == 0 or R != 0 conditional. 14684 */ 14685 mark_ptr_or_null_regs(this_branch, insn->dst_reg, 14686 opcode == BPF_JNE); 14687 mark_ptr_or_null_regs(other_branch, insn->dst_reg, 14688 opcode == BPF_JEQ); 14689 } else if (!try_match_pkt_pointers(insn, dst_reg, ®s[insn->src_reg], 14690 this_branch, other_branch) && 14691 is_pointer_value(env, insn->dst_reg)) { 14692 verbose(env, "R%d pointer comparison prohibited\n", 14693 insn->dst_reg); 14694 return -EACCES; 14695 } 14696 if (env->log.level & BPF_LOG_LEVEL) 14697 print_insn_state(env, this_branch->frame[this_branch->curframe]); 14698 return 0; 14699 } 14700 14701 /* verify BPF_LD_IMM64 instruction */ 14702 static int check_ld_imm(struct bpf_verifier_env *env, struct bpf_insn *insn) 14703 { 14704 struct bpf_insn_aux_data *aux = cur_aux(env); 14705 struct bpf_reg_state *regs = cur_regs(env); 14706 struct bpf_reg_state *dst_reg; 14707 struct bpf_map *map; 14708 int err; 14709 14710 if (BPF_SIZE(insn->code) != BPF_DW) { 14711 verbose(env, "invalid BPF_LD_IMM insn\n"); 14712 return -EINVAL; 14713 } 14714 if (insn->off != 0) { 14715 verbose(env, "BPF_LD_IMM64 uses reserved fields\n"); 14716 return -EINVAL; 14717 } 14718 14719 err = check_reg_arg(env, insn->dst_reg, DST_OP); 14720 if (err) 14721 return err; 14722 14723 dst_reg = ®s[insn->dst_reg]; 14724 if (insn->src_reg == 0) { 14725 u64 imm = ((u64)(insn + 1)->imm << 32) | (u32)insn->imm; 14726 14727 dst_reg->type = SCALAR_VALUE; 14728 __mark_reg_known(®s[insn->dst_reg], imm); 14729 return 0; 14730 } 14731 14732 /* All special src_reg cases are listed below. From this point onwards 14733 * we either succeed and assign a corresponding dst_reg->type after 14734 * zeroing the offset, or fail and reject the program. 14735 */ 14736 mark_reg_known_zero(env, regs, insn->dst_reg); 14737 14738 if (insn->src_reg == BPF_PSEUDO_BTF_ID) { 14739 dst_reg->type = aux->btf_var.reg_type; 14740 switch (base_type(dst_reg->type)) { 14741 case PTR_TO_MEM: 14742 dst_reg->mem_size = aux->btf_var.mem_size; 14743 break; 14744 case PTR_TO_BTF_ID: 14745 dst_reg->btf = aux->btf_var.btf; 14746 dst_reg->btf_id = aux->btf_var.btf_id; 14747 break; 14748 default: 14749 verbose(env, "bpf verifier is misconfigured\n"); 14750 return -EFAULT; 14751 } 14752 return 0; 14753 } 14754 14755 if (insn->src_reg == BPF_PSEUDO_FUNC) { 14756 struct bpf_prog_aux *aux = env->prog->aux; 14757 u32 subprogno = find_subprog(env, 14758 env->insn_idx + insn->imm + 1); 14759 14760 if (!aux->func_info) { 14761 verbose(env, "missing btf func_info\n"); 14762 return -EINVAL; 14763 } 14764 if (aux->func_info_aux[subprogno].linkage != BTF_FUNC_STATIC) { 14765 verbose(env, "callback function not static\n"); 14766 return -EINVAL; 14767 } 14768 14769 dst_reg->type = PTR_TO_FUNC; 14770 dst_reg->subprogno = subprogno; 14771 return 0; 14772 } 14773 14774 map = env->used_maps[aux->map_index]; 14775 dst_reg->map_ptr = map; 14776 14777 if (insn->src_reg == BPF_PSEUDO_MAP_VALUE || 14778 insn->src_reg == BPF_PSEUDO_MAP_IDX_VALUE) { 14779 dst_reg->type = PTR_TO_MAP_VALUE; 14780 dst_reg->off = aux->map_off; 14781 WARN_ON_ONCE(map->max_entries != 1); 14782 /* We want reg->id to be same (0) as map_value is not distinct */ 14783 } else if (insn->src_reg == BPF_PSEUDO_MAP_FD || 14784 insn->src_reg == BPF_PSEUDO_MAP_IDX) { 14785 dst_reg->type = CONST_PTR_TO_MAP; 14786 } else { 14787 verbose(env, "bpf verifier is misconfigured\n"); 14788 return -EINVAL; 14789 } 14790 14791 return 0; 14792 } 14793 14794 static bool may_access_skb(enum bpf_prog_type type) 14795 { 14796 switch (type) { 14797 case BPF_PROG_TYPE_SOCKET_FILTER: 14798 case BPF_PROG_TYPE_SCHED_CLS: 14799 case BPF_PROG_TYPE_SCHED_ACT: 14800 return true; 14801 default: 14802 return false; 14803 } 14804 } 14805 14806 /* verify safety of LD_ABS|LD_IND instructions: 14807 * - they can only appear in the programs where ctx == skb 14808 * - since they are wrappers of function calls, they scratch R1-R5 registers, 14809 * preserve R6-R9, and store return value into R0 14810 * 14811 * Implicit input: 14812 * ctx == skb == R6 == CTX 14813 * 14814 * Explicit input: 14815 * SRC == any register 14816 * IMM == 32-bit immediate 14817 * 14818 * Output: 14819 * R0 - 8/16/32-bit skb data converted to cpu endianness 14820 */ 14821 static int check_ld_abs(struct bpf_verifier_env *env, struct bpf_insn *insn) 14822 { 14823 struct bpf_reg_state *regs = cur_regs(env); 14824 static const int ctx_reg = BPF_REG_6; 14825 u8 mode = BPF_MODE(insn->code); 14826 int i, err; 14827 14828 if (!may_access_skb(resolve_prog_type(env->prog))) { 14829 verbose(env, "BPF_LD_[ABS|IND] instructions not allowed for this program type\n"); 14830 return -EINVAL; 14831 } 14832 14833 if (!env->ops->gen_ld_abs) { 14834 verbose(env, "bpf verifier is misconfigured\n"); 14835 return -EINVAL; 14836 } 14837 14838 if (insn->dst_reg != BPF_REG_0 || insn->off != 0 || 14839 BPF_SIZE(insn->code) == BPF_DW || 14840 (mode == BPF_ABS && insn->src_reg != BPF_REG_0)) { 14841 verbose(env, "BPF_LD_[ABS|IND] uses reserved fields\n"); 14842 return -EINVAL; 14843 } 14844 14845 /* check whether implicit source operand (register R6) is readable */ 14846 err = check_reg_arg(env, ctx_reg, SRC_OP); 14847 if (err) 14848 return err; 14849 14850 /* Disallow usage of BPF_LD_[ABS|IND] with reference tracking, as 14851 * gen_ld_abs() may terminate the program at runtime, leading to 14852 * reference leak. 14853 */ 14854 err = check_reference_leak(env); 14855 if (err) { 14856 verbose(env, "BPF_LD_[ABS|IND] cannot be mixed with socket references\n"); 14857 return err; 14858 } 14859 14860 if (env->cur_state->active_lock.ptr) { 14861 verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_spin_lock-ed region\n"); 14862 return -EINVAL; 14863 } 14864 14865 if (env->cur_state->active_rcu_lock) { 14866 verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_rcu_read_lock-ed region\n"); 14867 return -EINVAL; 14868 } 14869 14870 if (regs[ctx_reg].type != PTR_TO_CTX) { 14871 verbose(env, 14872 "at the time of BPF_LD_ABS|IND R6 != pointer to skb\n"); 14873 return -EINVAL; 14874 } 14875 14876 if (mode == BPF_IND) { 14877 /* check explicit source operand */ 14878 err = check_reg_arg(env, insn->src_reg, SRC_OP); 14879 if (err) 14880 return err; 14881 } 14882 14883 err = check_ptr_off_reg(env, ®s[ctx_reg], ctx_reg); 14884 if (err < 0) 14885 return err; 14886 14887 /* reset caller saved regs to unreadable */ 14888 for (i = 0; i < CALLER_SAVED_REGS; i++) { 14889 mark_reg_not_init(env, regs, caller_saved[i]); 14890 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK); 14891 } 14892 14893 /* mark destination R0 register as readable, since it contains 14894 * the value fetched from the packet. 14895 * Already marked as written above. 14896 */ 14897 mark_reg_unknown(env, regs, BPF_REG_0); 14898 /* ld_abs load up to 32-bit skb data. */ 14899 regs[BPF_REG_0].subreg_def = env->insn_idx + 1; 14900 return 0; 14901 } 14902 14903 static int check_return_code(struct bpf_verifier_env *env) 14904 { 14905 struct tnum enforce_attach_type_range = tnum_unknown; 14906 const struct bpf_prog *prog = env->prog; 14907 struct bpf_reg_state *reg; 14908 struct tnum range = tnum_range(0, 1), const_0 = tnum_const(0); 14909 enum bpf_prog_type prog_type = resolve_prog_type(env->prog); 14910 int err; 14911 struct bpf_func_state *frame = env->cur_state->frame[0]; 14912 const bool is_subprog = frame->subprogno; 14913 14914 /* LSM and struct_ops func-ptr's return type could be "void" */ 14915 if (!is_subprog) { 14916 switch (prog_type) { 14917 case BPF_PROG_TYPE_LSM: 14918 if (prog->expected_attach_type == BPF_LSM_CGROUP) 14919 /* See below, can be 0 or 0-1 depending on hook. */ 14920 break; 14921 fallthrough; 14922 case BPF_PROG_TYPE_STRUCT_OPS: 14923 if (!prog->aux->attach_func_proto->type) 14924 return 0; 14925 break; 14926 default: 14927 break; 14928 } 14929 } 14930 14931 /* eBPF calling convention is such that R0 is used 14932 * to return the value from eBPF program. 14933 * Make sure that it's readable at this time 14934 * of bpf_exit, which means that program wrote 14935 * something into it earlier 14936 */ 14937 err = check_reg_arg(env, BPF_REG_0, SRC_OP); 14938 if (err) 14939 return err; 14940 14941 if (is_pointer_value(env, BPF_REG_0)) { 14942 verbose(env, "R0 leaks addr as return value\n"); 14943 return -EACCES; 14944 } 14945 14946 reg = cur_regs(env) + BPF_REG_0; 14947 14948 if (frame->in_async_callback_fn) { 14949 /* enforce return zero from async callbacks like timer */ 14950 if (reg->type != SCALAR_VALUE) { 14951 verbose(env, "In async callback the register R0 is not a known value (%s)\n", 14952 reg_type_str(env, reg->type)); 14953 return -EINVAL; 14954 } 14955 14956 if (!tnum_in(const_0, reg->var_off)) { 14957 verbose_invalid_scalar(env, reg, &const_0, "async callback", "R0"); 14958 return -EINVAL; 14959 } 14960 return 0; 14961 } 14962 14963 if (is_subprog) { 14964 if (reg->type != SCALAR_VALUE) { 14965 verbose(env, "At subprogram exit the register R0 is not a scalar value (%s)\n", 14966 reg_type_str(env, reg->type)); 14967 return -EINVAL; 14968 } 14969 return 0; 14970 } 14971 14972 switch (prog_type) { 14973 case BPF_PROG_TYPE_CGROUP_SOCK_ADDR: 14974 if (env->prog->expected_attach_type == BPF_CGROUP_UDP4_RECVMSG || 14975 env->prog->expected_attach_type == BPF_CGROUP_UDP6_RECVMSG || 14976 env->prog->expected_attach_type == BPF_CGROUP_INET4_GETPEERNAME || 14977 env->prog->expected_attach_type == BPF_CGROUP_INET6_GETPEERNAME || 14978 env->prog->expected_attach_type == BPF_CGROUP_INET4_GETSOCKNAME || 14979 env->prog->expected_attach_type == BPF_CGROUP_INET6_GETSOCKNAME) 14980 range = tnum_range(1, 1); 14981 if (env->prog->expected_attach_type == BPF_CGROUP_INET4_BIND || 14982 env->prog->expected_attach_type == BPF_CGROUP_INET6_BIND) 14983 range = tnum_range(0, 3); 14984 break; 14985 case BPF_PROG_TYPE_CGROUP_SKB: 14986 if (env->prog->expected_attach_type == BPF_CGROUP_INET_EGRESS) { 14987 range = tnum_range(0, 3); 14988 enforce_attach_type_range = tnum_range(2, 3); 14989 } 14990 break; 14991 case BPF_PROG_TYPE_CGROUP_SOCK: 14992 case BPF_PROG_TYPE_SOCK_OPS: 14993 case BPF_PROG_TYPE_CGROUP_DEVICE: 14994 case BPF_PROG_TYPE_CGROUP_SYSCTL: 14995 case BPF_PROG_TYPE_CGROUP_SOCKOPT: 14996 break; 14997 case BPF_PROG_TYPE_RAW_TRACEPOINT: 14998 if (!env->prog->aux->attach_btf_id) 14999 return 0; 15000 range = tnum_const(0); 15001 break; 15002 case BPF_PROG_TYPE_TRACING: 15003 switch (env->prog->expected_attach_type) { 15004 case BPF_TRACE_FENTRY: 15005 case BPF_TRACE_FEXIT: 15006 range = tnum_const(0); 15007 break; 15008 case BPF_TRACE_RAW_TP: 15009 case BPF_MODIFY_RETURN: 15010 return 0; 15011 case BPF_TRACE_ITER: 15012 break; 15013 default: 15014 return -ENOTSUPP; 15015 } 15016 break; 15017 case BPF_PROG_TYPE_SK_LOOKUP: 15018 range = tnum_range(SK_DROP, SK_PASS); 15019 break; 15020 15021 case BPF_PROG_TYPE_LSM: 15022 if (env->prog->expected_attach_type != BPF_LSM_CGROUP) { 15023 /* Regular BPF_PROG_TYPE_LSM programs can return 15024 * any value. 15025 */ 15026 return 0; 15027 } 15028 if (!env->prog->aux->attach_func_proto->type) { 15029 /* Make sure programs that attach to void 15030 * hooks don't try to modify return value. 15031 */ 15032 range = tnum_range(1, 1); 15033 } 15034 break; 15035 15036 case BPF_PROG_TYPE_NETFILTER: 15037 range = tnum_range(NF_DROP, NF_ACCEPT); 15038 break; 15039 case BPF_PROG_TYPE_EXT: 15040 /* freplace program can return anything as its return value 15041 * depends on the to-be-replaced kernel func or bpf program. 15042 */ 15043 default: 15044 return 0; 15045 } 15046 15047 if (reg->type != SCALAR_VALUE) { 15048 verbose(env, "At program exit the register R0 is not a known value (%s)\n", 15049 reg_type_str(env, reg->type)); 15050 return -EINVAL; 15051 } 15052 15053 if (!tnum_in(range, reg->var_off)) { 15054 verbose_invalid_scalar(env, reg, &range, "program exit", "R0"); 15055 if (prog->expected_attach_type == BPF_LSM_CGROUP && 15056 prog_type == BPF_PROG_TYPE_LSM && 15057 !prog->aux->attach_func_proto->type) 15058 verbose(env, "Note, BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n"); 15059 return -EINVAL; 15060 } 15061 15062 if (!tnum_is_unknown(enforce_attach_type_range) && 15063 tnum_in(enforce_attach_type_range, reg->var_off)) 15064 env->prog->enforce_expected_attach_type = 1; 15065 return 0; 15066 } 15067 15068 /* non-recursive DFS pseudo code 15069 * 1 procedure DFS-iterative(G,v): 15070 * 2 label v as discovered 15071 * 3 let S be a stack 15072 * 4 S.push(v) 15073 * 5 while S is not empty 15074 * 6 t <- S.peek() 15075 * 7 if t is what we're looking for: 15076 * 8 return t 15077 * 9 for all edges e in G.adjacentEdges(t) do 15078 * 10 if edge e is already labelled 15079 * 11 continue with the next edge 15080 * 12 w <- G.adjacentVertex(t,e) 15081 * 13 if vertex w is not discovered and not explored 15082 * 14 label e as tree-edge 15083 * 15 label w as discovered 15084 * 16 S.push(w) 15085 * 17 continue at 5 15086 * 18 else if vertex w is discovered 15087 * 19 label e as back-edge 15088 * 20 else 15089 * 21 // vertex w is explored 15090 * 22 label e as forward- or cross-edge 15091 * 23 label t as explored 15092 * 24 S.pop() 15093 * 15094 * convention: 15095 * 0x10 - discovered 15096 * 0x11 - discovered and fall-through edge labelled 15097 * 0x12 - discovered and fall-through and branch edges labelled 15098 * 0x20 - explored 15099 */ 15100 15101 enum { 15102 DISCOVERED = 0x10, 15103 EXPLORED = 0x20, 15104 FALLTHROUGH = 1, 15105 BRANCH = 2, 15106 }; 15107 15108 static void mark_prune_point(struct bpf_verifier_env *env, int idx) 15109 { 15110 env->insn_aux_data[idx].prune_point = true; 15111 } 15112 15113 static bool is_prune_point(struct bpf_verifier_env *env, int insn_idx) 15114 { 15115 return env->insn_aux_data[insn_idx].prune_point; 15116 } 15117 15118 static void mark_force_checkpoint(struct bpf_verifier_env *env, int idx) 15119 { 15120 env->insn_aux_data[idx].force_checkpoint = true; 15121 } 15122 15123 static bool is_force_checkpoint(struct bpf_verifier_env *env, int insn_idx) 15124 { 15125 return env->insn_aux_data[insn_idx].force_checkpoint; 15126 } 15127 15128 static void mark_calls_callback(struct bpf_verifier_env *env, int idx) 15129 { 15130 env->insn_aux_data[idx].calls_callback = true; 15131 } 15132 15133 static bool calls_callback(struct bpf_verifier_env *env, int insn_idx) 15134 { 15135 return env->insn_aux_data[insn_idx].calls_callback; 15136 } 15137 15138 enum { 15139 DONE_EXPLORING = 0, 15140 KEEP_EXPLORING = 1, 15141 }; 15142 15143 /* t, w, e - match pseudo-code above: 15144 * t - index of current instruction 15145 * w - next instruction 15146 * e - edge 15147 */ 15148 static int push_insn(int t, int w, int e, struct bpf_verifier_env *env) 15149 { 15150 int *insn_stack = env->cfg.insn_stack; 15151 int *insn_state = env->cfg.insn_state; 15152 15153 if (e == FALLTHROUGH && insn_state[t] >= (DISCOVERED | FALLTHROUGH)) 15154 return DONE_EXPLORING; 15155 15156 if (e == BRANCH && insn_state[t] >= (DISCOVERED | BRANCH)) 15157 return DONE_EXPLORING; 15158 15159 if (w < 0 || w >= env->prog->len) { 15160 verbose_linfo(env, t, "%d: ", t); 15161 verbose(env, "jump out of range from insn %d to %d\n", t, w); 15162 return -EINVAL; 15163 } 15164 15165 if (e == BRANCH) { 15166 /* mark branch target for state pruning */ 15167 mark_prune_point(env, w); 15168 mark_jmp_point(env, w); 15169 } 15170 15171 if (insn_state[w] == 0) { 15172 /* tree-edge */ 15173 insn_state[t] = DISCOVERED | e; 15174 insn_state[w] = DISCOVERED; 15175 if (env->cfg.cur_stack >= env->prog->len) 15176 return -E2BIG; 15177 insn_stack[env->cfg.cur_stack++] = w; 15178 return KEEP_EXPLORING; 15179 } else if ((insn_state[w] & 0xF0) == DISCOVERED) { 15180 if (env->bpf_capable) 15181 return DONE_EXPLORING; 15182 verbose_linfo(env, t, "%d: ", t); 15183 verbose_linfo(env, w, "%d: ", w); 15184 verbose(env, "back-edge from insn %d to %d\n", t, w); 15185 return -EINVAL; 15186 } else if (insn_state[w] == EXPLORED) { 15187 /* forward- or cross-edge */ 15188 insn_state[t] = DISCOVERED | e; 15189 } else { 15190 verbose(env, "insn state internal bug\n"); 15191 return -EFAULT; 15192 } 15193 return DONE_EXPLORING; 15194 } 15195 15196 static int visit_func_call_insn(int t, struct bpf_insn *insns, 15197 struct bpf_verifier_env *env, 15198 bool visit_callee) 15199 { 15200 int ret, insn_sz; 15201 15202 insn_sz = bpf_is_ldimm64(&insns[t]) ? 2 : 1; 15203 ret = push_insn(t, t + insn_sz, FALLTHROUGH, env); 15204 if (ret) 15205 return ret; 15206 15207 mark_prune_point(env, t + insn_sz); 15208 /* when we exit from subprog, we need to record non-linear history */ 15209 mark_jmp_point(env, t + insn_sz); 15210 15211 if (visit_callee) { 15212 mark_prune_point(env, t); 15213 ret = push_insn(t, t + insns[t].imm + 1, BRANCH, env); 15214 } 15215 return ret; 15216 } 15217 15218 /* Visits the instruction at index t and returns one of the following: 15219 * < 0 - an error occurred 15220 * DONE_EXPLORING - the instruction was fully explored 15221 * KEEP_EXPLORING - there is still work to be done before it is fully explored 15222 */ 15223 static int visit_insn(int t, struct bpf_verifier_env *env) 15224 { 15225 struct bpf_insn *insns = env->prog->insnsi, *insn = &insns[t]; 15226 int ret, off, insn_sz; 15227 15228 if (bpf_pseudo_func(insn)) 15229 return visit_func_call_insn(t, insns, env, true); 15230 15231 /* All non-branch instructions have a single fall-through edge. */ 15232 if (BPF_CLASS(insn->code) != BPF_JMP && 15233 BPF_CLASS(insn->code) != BPF_JMP32) { 15234 insn_sz = bpf_is_ldimm64(insn) ? 2 : 1; 15235 return push_insn(t, t + insn_sz, FALLTHROUGH, env); 15236 } 15237 15238 switch (BPF_OP(insn->code)) { 15239 case BPF_EXIT: 15240 return DONE_EXPLORING; 15241 15242 case BPF_CALL: 15243 if (insn->src_reg == 0 && insn->imm == BPF_FUNC_timer_set_callback) 15244 /* Mark this call insn as a prune point to trigger 15245 * is_state_visited() check before call itself is 15246 * processed by __check_func_call(). Otherwise new 15247 * async state will be pushed for further exploration. 15248 */ 15249 mark_prune_point(env, t); 15250 /* For functions that invoke callbacks it is not known how many times 15251 * callback would be called. Verifier models callback calling functions 15252 * by repeatedly visiting callback bodies and returning to origin call 15253 * instruction. 15254 * In order to stop such iteration verifier needs to identify when a 15255 * state identical some state from a previous iteration is reached. 15256 * Check below forces creation of checkpoint before callback calling 15257 * instruction to allow search for such identical states. 15258 */ 15259 if (is_sync_callback_calling_insn(insn)) { 15260 mark_calls_callback(env, t); 15261 mark_force_checkpoint(env, t); 15262 mark_prune_point(env, t); 15263 mark_jmp_point(env, t); 15264 } 15265 if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) { 15266 struct bpf_kfunc_call_arg_meta meta; 15267 15268 ret = fetch_kfunc_meta(env, insn, &meta, NULL); 15269 if (ret == 0 && is_iter_next_kfunc(&meta)) { 15270 mark_prune_point(env, t); 15271 /* Checking and saving state checkpoints at iter_next() call 15272 * is crucial for fast convergence of open-coded iterator loop 15273 * logic, so we need to force it. If we don't do that, 15274 * is_state_visited() might skip saving a checkpoint, causing 15275 * unnecessarily long sequence of not checkpointed 15276 * instructions and jumps, leading to exhaustion of jump 15277 * history buffer, and potentially other undesired outcomes. 15278 * It is expected that with correct open-coded iterators 15279 * convergence will happen quickly, so we don't run a risk of 15280 * exhausting memory. 15281 */ 15282 mark_force_checkpoint(env, t); 15283 } 15284 } 15285 return visit_func_call_insn(t, insns, env, insn->src_reg == BPF_PSEUDO_CALL); 15286 15287 case BPF_JA: 15288 if (BPF_SRC(insn->code) != BPF_K) 15289 return -EINVAL; 15290 15291 if (BPF_CLASS(insn->code) == BPF_JMP) 15292 off = insn->off; 15293 else 15294 off = insn->imm; 15295 15296 /* unconditional jump with single edge */ 15297 ret = push_insn(t, t + off + 1, FALLTHROUGH, env); 15298 if (ret) 15299 return ret; 15300 15301 mark_prune_point(env, t + off + 1); 15302 mark_jmp_point(env, t + off + 1); 15303 15304 return ret; 15305 15306 default: 15307 /* conditional jump with two edges */ 15308 mark_prune_point(env, t); 15309 15310 ret = push_insn(t, t + 1, FALLTHROUGH, env); 15311 if (ret) 15312 return ret; 15313 15314 return push_insn(t, t + insn->off + 1, BRANCH, env); 15315 } 15316 } 15317 15318 /* non-recursive depth-first-search to detect loops in BPF program 15319 * loop == back-edge in directed graph 15320 */ 15321 static int check_cfg(struct bpf_verifier_env *env) 15322 { 15323 int insn_cnt = env->prog->len; 15324 int *insn_stack, *insn_state; 15325 int ret = 0; 15326 int i; 15327 15328 insn_state = env->cfg.insn_state = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL); 15329 if (!insn_state) 15330 return -ENOMEM; 15331 15332 insn_stack = env->cfg.insn_stack = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL); 15333 if (!insn_stack) { 15334 kvfree(insn_state); 15335 return -ENOMEM; 15336 } 15337 15338 insn_state[0] = DISCOVERED; /* mark 1st insn as discovered */ 15339 insn_stack[0] = 0; /* 0 is the first instruction */ 15340 env->cfg.cur_stack = 1; 15341 15342 while (env->cfg.cur_stack > 0) { 15343 int t = insn_stack[env->cfg.cur_stack - 1]; 15344 15345 ret = visit_insn(t, env); 15346 switch (ret) { 15347 case DONE_EXPLORING: 15348 insn_state[t] = EXPLORED; 15349 env->cfg.cur_stack--; 15350 break; 15351 case KEEP_EXPLORING: 15352 break; 15353 default: 15354 if (ret > 0) { 15355 verbose(env, "visit_insn internal bug\n"); 15356 ret = -EFAULT; 15357 } 15358 goto err_free; 15359 } 15360 } 15361 15362 if (env->cfg.cur_stack < 0) { 15363 verbose(env, "pop stack internal bug\n"); 15364 ret = -EFAULT; 15365 goto err_free; 15366 } 15367 15368 for (i = 0; i < insn_cnt; i++) { 15369 struct bpf_insn *insn = &env->prog->insnsi[i]; 15370 15371 if (insn_state[i] != EXPLORED) { 15372 verbose(env, "unreachable insn %d\n", i); 15373 ret = -EINVAL; 15374 goto err_free; 15375 } 15376 if (bpf_is_ldimm64(insn)) { 15377 if (insn_state[i + 1] != 0) { 15378 verbose(env, "jump into the middle of ldimm64 insn %d\n", i); 15379 ret = -EINVAL; 15380 goto err_free; 15381 } 15382 i++; /* skip second half of ldimm64 */ 15383 } 15384 } 15385 ret = 0; /* cfg looks good */ 15386 15387 err_free: 15388 kvfree(insn_state); 15389 kvfree(insn_stack); 15390 env->cfg.insn_state = env->cfg.insn_stack = NULL; 15391 return ret; 15392 } 15393 15394 static int check_abnormal_return(struct bpf_verifier_env *env) 15395 { 15396 int i; 15397 15398 for (i = 1; i < env->subprog_cnt; i++) { 15399 if (env->subprog_info[i].has_ld_abs) { 15400 verbose(env, "LD_ABS is not allowed in subprogs without BTF\n"); 15401 return -EINVAL; 15402 } 15403 if (env->subprog_info[i].has_tail_call) { 15404 verbose(env, "tail_call is not allowed in subprogs without BTF\n"); 15405 return -EINVAL; 15406 } 15407 } 15408 return 0; 15409 } 15410 15411 /* The minimum supported BTF func info size */ 15412 #define MIN_BPF_FUNCINFO_SIZE 8 15413 #define MAX_FUNCINFO_REC_SIZE 252 15414 15415 static int check_btf_func(struct bpf_verifier_env *env, 15416 const union bpf_attr *attr, 15417 bpfptr_t uattr) 15418 { 15419 const struct btf_type *type, *func_proto, *ret_type; 15420 u32 i, nfuncs, urec_size, min_size; 15421 u32 krec_size = sizeof(struct bpf_func_info); 15422 struct bpf_func_info *krecord; 15423 struct bpf_func_info_aux *info_aux = NULL; 15424 struct bpf_prog *prog; 15425 const struct btf *btf; 15426 bpfptr_t urecord; 15427 u32 prev_offset = 0; 15428 bool scalar_return; 15429 int ret = -ENOMEM; 15430 15431 nfuncs = attr->func_info_cnt; 15432 if (!nfuncs) { 15433 if (check_abnormal_return(env)) 15434 return -EINVAL; 15435 return 0; 15436 } 15437 15438 if (nfuncs != env->subprog_cnt) { 15439 verbose(env, "number of funcs in func_info doesn't match number of subprogs\n"); 15440 return -EINVAL; 15441 } 15442 15443 urec_size = attr->func_info_rec_size; 15444 if (urec_size < MIN_BPF_FUNCINFO_SIZE || 15445 urec_size > MAX_FUNCINFO_REC_SIZE || 15446 urec_size % sizeof(u32)) { 15447 verbose(env, "invalid func info rec size %u\n", urec_size); 15448 return -EINVAL; 15449 } 15450 15451 prog = env->prog; 15452 btf = prog->aux->btf; 15453 15454 urecord = make_bpfptr(attr->func_info, uattr.is_kernel); 15455 min_size = min_t(u32, krec_size, urec_size); 15456 15457 krecord = kvcalloc(nfuncs, krec_size, GFP_KERNEL | __GFP_NOWARN); 15458 if (!krecord) 15459 return -ENOMEM; 15460 info_aux = kcalloc(nfuncs, sizeof(*info_aux), GFP_KERNEL | __GFP_NOWARN); 15461 if (!info_aux) 15462 goto err_free; 15463 15464 for (i = 0; i < nfuncs; i++) { 15465 ret = bpf_check_uarg_tail_zero(urecord, krec_size, urec_size); 15466 if (ret) { 15467 if (ret == -E2BIG) { 15468 verbose(env, "nonzero tailing record in func info"); 15469 /* set the size kernel expects so loader can zero 15470 * out the rest of the record. 15471 */ 15472 if (copy_to_bpfptr_offset(uattr, 15473 offsetof(union bpf_attr, func_info_rec_size), 15474 &min_size, sizeof(min_size))) 15475 ret = -EFAULT; 15476 } 15477 goto err_free; 15478 } 15479 15480 if (copy_from_bpfptr(&krecord[i], urecord, min_size)) { 15481 ret = -EFAULT; 15482 goto err_free; 15483 } 15484 15485 /* check insn_off */ 15486 ret = -EINVAL; 15487 if (i == 0) { 15488 if (krecord[i].insn_off) { 15489 verbose(env, 15490 "nonzero insn_off %u for the first func info record", 15491 krecord[i].insn_off); 15492 goto err_free; 15493 } 15494 } else if (krecord[i].insn_off <= prev_offset) { 15495 verbose(env, 15496 "same or smaller insn offset (%u) than previous func info record (%u)", 15497 krecord[i].insn_off, prev_offset); 15498 goto err_free; 15499 } 15500 15501 if (env->subprog_info[i].start != krecord[i].insn_off) { 15502 verbose(env, "func_info BTF section doesn't match subprog layout in BPF program\n"); 15503 goto err_free; 15504 } 15505 15506 /* check type_id */ 15507 type = btf_type_by_id(btf, krecord[i].type_id); 15508 if (!type || !btf_type_is_func(type)) { 15509 verbose(env, "invalid type id %d in func info", 15510 krecord[i].type_id); 15511 goto err_free; 15512 } 15513 info_aux[i].linkage = BTF_INFO_VLEN(type->info); 15514 15515 func_proto = btf_type_by_id(btf, type->type); 15516 if (unlikely(!func_proto || !btf_type_is_func_proto(func_proto))) 15517 /* btf_func_check() already verified it during BTF load */ 15518 goto err_free; 15519 ret_type = btf_type_skip_modifiers(btf, func_proto->type, NULL); 15520 scalar_return = 15521 btf_type_is_small_int(ret_type) || btf_is_any_enum(ret_type); 15522 if (i && !scalar_return && env->subprog_info[i].has_ld_abs) { 15523 verbose(env, "LD_ABS is only allowed in functions that return 'int'.\n"); 15524 goto err_free; 15525 } 15526 if (i && !scalar_return && env->subprog_info[i].has_tail_call) { 15527 verbose(env, "tail_call is only allowed in functions that return 'int'.\n"); 15528 goto err_free; 15529 } 15530 15531 prev_offset = krecord[i].insn_off; 15532 bpfptr_add(&urecord, urec_size); 15533 } 15534 15535 prog->aux->func_info = krecord; 15536 prog->aux->func_info_cnt = nfuncs; 15537 prog->aux->func_info_aux = info_aux; 15538 return 0; 15539 15540 err_free: 15541 kvfree(krecord); 15542 kfree(info_aux); 15543 return ret; 15544 } 15545 15546 static void adjust_btf_func(struct bpf_verifier_env *env) 15547 { 15548 struct bpf_prog_aux *aux = env->prog->aux; 15549 int i; 15550 15551 if (!aux->func_info) 15552 return; 15553 15554 for (i = 0; i < env->subprog_cnt; i++) 15555 aux->func_info[i].insn_off = env->subprog_info[i].start; 15556 } 15557 15558 #define MIN_BPF_LINEINFO_SIZE offsetofend(struct bpf_line_info, line_col) 15559 #define MAX_LINEINFO_REC_SIZE MAX_FUNCINFO_REC_SIZE 15560 15561 static int check_btf_line(struct bpf_verifier_env *env, 15562 const union bpf_attr *attr, 15563 bpfptr_t uattr) 15564 { 15565 u32 i, s, nr_linfo, ncopy, expected_size, rec_size, prev_offset = 0; 15566 struct bpf_subprog_info *sub; 15567 struct bpf_line_info *linfo; 15568 struct bpf_prog *prog; 15569 const struct btf *btf; 15570 bpfptr_t ulinfo; 15571 int err; 15572 15573 nr_linfo = attr->line_info_cnt; 15574 if (!nr_linfo) 15575 return 0; 15576 if (nr_linfo > INT_MAX / sizeof(struct bpf_line_info)) 15577 return -EINVAL; 15578 15579 rec_size = attr->line_info_rec_size; 15580 if (rec_size < MIN_BPF_LINEINFO_SIZE || 15581 rec_size > MAX_LINEINFO_REC_SIZE || 15582 rec_size & (sizeof(u32) - 1)) 15583 return -EINVAL; 15584 15585 /* Need to zero it in case the userspace may 15586 * pass in a smaller bpf_line_info object. 15587 */ 15588 linfo = kvcalloc(nr_linfo, sizeof(struct bpf_line_info), 15589 GFP_KERNEL | __GFP_NOWARN); 15590 if (!linfo) 15591 return -ENOMEM; 15592 15593 prog = env->prog; 15594 btf = prog->aux->btf; 15595 15596 s = 0; 15597 sub = env->subprog_info; 15598 ulinfo = make_bpfptr(attr->line_info, uattr.is_kernel); 15599 expected_size = sizeof(struct bpf_line_info); 15600 ncopy = min_t(u32, expected_size, rec_size); 15601 for (i = 0; i < nr_linfo; i++) { 15602 err = bpf_check_uarg_tail_zero(ulinfo, expected_size, rec_size); 15603 if (err) { 15604 if (err == -E2BIG) { 15605 verbose(env, "nonzero tailing record in line_info"); 15606 if (copy_to_bpfptr_offset(uattr, 15607 offsetof(union bpf_attr, line_info_rec_size), 15608 &expected_size, sizeof(expected_size))) 15609 err = -EFAULT; 15610 } 15611 goto err_free; 15612 } 15613 15614 if (copy_from_bpfptr(&linfo[i], ulinfo, ncopy)) { 15615 err = -EFAULT; 15616 goto err_free; 15617 } 15618 15619 /* 15620 * Check insn_off to ensure 15621 * 1) strictly increasing AND 15622 * 2) bounded by prog->len 15623 * 15624 * The linfo[0].insn_off == 0 check logically falls into 15625 * the later "missing bpf_line_info for func..." case 15626 * because the first linfo[0].insn_off must be the 15627 * first sub also and the first sub must have 15628 * subprog_info[0].start == 0. 15629 */ 15630 if ((i && linfo[i].insn_off <= prev_offset) || 15631 linfo[i].insn_off >= prog->len) { 15632 verbose(env, "Invalid line_info[%u].insn_off:%u (prev_offset:%u prog->len:%u)\n", 15633 i, linfo[i].insn_off, prev_offset, 15634 prog->len); 15635 err = -EINVAL; 15636 goto err_free; 15637 } 15638 15639 if (!prog->insnsi[linfo[i].insn_off].code) { 15640 verbose(env, 15641 "Invalid insn code at line_info[%u].insn_off\n", 15642 i); 15643 err = -EINVAL; 15644 goto err_free; 15645 } 15646 15647 if (!btf_name_by_offset(btf, linfo[i].line_off) || 15648 !btf_name_by_offset(btf, linfo[i].file_name_off)) { 15649 verbose(env, "Invalid line_info[%u].line_off or .file_name_off\n", i); 15650 err = -EINVAL; 15651 goto err_free; 15652 } 15653 15654 if (s != env->subprog_cnt) { 15655 if (linfo[i].insn_off == sub[s].start) { 15656 sub[s].linfo_idx = i; 15657 s++; 15658 } else if (sub[s].start < linfo[i].insn_off) { 15659 verbose(env, "missing bpf_line_info for func#%u\n", s); 15660 err = -EINVAL; 15661 goto err_free; 15662 } 15663 } 15664 15665 prev_offset = linfo[i].insn_off; 15666 bpfptr_add(&ulinfo, rec_size); 15667 } 15668 15669 if (s != env->subprog_cnt) { 15670 verbose(env, "missing bpf_line_info for %u funcs starting from func#%u\n", 15671 env->subprog_cnt - s, s); 15672 err = -EINVAL; 15673 goto err_free; 15674 } 15675 15676 prog->aux->linfo = linfo; 15677 prog->aux->nr_linfo = nr_linfo; 15678 15679 return 0; 15680 15681 err_free: 15682 kvfree(linfo); 15683 return err; 15684 } 15685 15686 #define MIN_CORE_RELO_SIZE sizeof(struct bpf_core_relo) 15687 #define MAX_CORE_RELO_SIZE MAX_FUNCINFO_REC_SIZE 15688 15689 static int check_core_relo(struct bpf_verifier_env *env, 15690 const union bpf_attr *attr, 15691 bpfptr_t uattr) 15692 { 15693 u32 i, nr_core_relo, ncopy, expected_size, rec_size; 15694 struct bpf_core_relo core_relo = {}; 15695 struct bpf_prog *prog = env->prog; 15696 const struct btf *btf = prog->aux->btf; 15697 struct bpf_core_ctx ctx = { 15698 .log = &env->log, 15699 .btf = btf, 15700 }; 15701 bpfptr_t u_core_relo; 15702 int err; 15703 15704 nr_core_relo = attr->core_relo_cnt; 15705 if (!nr_core_relo) 15706 return 0; 15707 if (nr_core_relo > INT_MAX / sizeof(struct bpf_core_relo)) 15708 return -EINVAL; 15709 15710 rec_size = attr->core_relo_rec_size; 15711 if (rec_size < MIN_CORE_RELO_SIZE || 15712 rec_size > MAX_CORE_RELO_SIZE || 15713 rec_size % sizeof(u32)) 15714 return -EINVAL; 15715 15716 u_core_relo = make_bpfptr(attr->core_relos, uattr.is_kernel); 15717 expected_size = sizeof(struct bpf_core_relo); 15718 ncopy = min_t(u32, expected_size, rec_size); 15719 15720 /* Unlike func_info and line_info, copy and apply each CO-RE 15721 * relocation record one at a time. 15722 */ 15723 for (i = 0; i < nr_core_relo; i++) { 15724 /* future proofing when sizeof(bpf_core_relo) changes */ 15725 err = bpf_check_uarg_tail_zero(u_core_relo, expected_size, rec_size); 15726 if (err) { 15727 if (err == -E2BIG) { 15728 verbose(env, "nonzero tailing record in core_relo"); 15729 if (copy_to_bpfptr_offset(uattr, 15730 offsetof(union bpf_attr, core_relo_rec_size), 15731 &expected_size, sizeof(expected_size))) 15732 err = -EFAULT; 15733 } 15734 break; 15735 } 15736 15737 if (copy_from_bpfptr(&core_relo, u_core_relo, ncopy)) { 15738 err = -EFAULT; 15739 break; 15740 } 15741 15742 if (core_relo.insn_off % 8 || core_relo.insn_off / 8 >= prog->len) { 15743 verbose(env, "Invalid core_relo[%u].insn_off:%u prog->len:%u\n", 15744 i, core_relo.insn_off, prog->len); 15745 err = -EINVAL; 15746 break; 15747 } 15748 15749 err = bpf_core_apply(&ctx, &core_relo, i, 15750 &prog->insnsi[core_relo.insn_off / 8]); 15751 if (err) 15752 break; 15753 bpfptr_add(&u_core_relo, rec_size); 15754 } 15755 return err; 15756 } 15757 15758 static int check_btf_info(struct bpf_verifier_env *env, 15759 const union bpf_attr *attr, 15760 bpfptr_t uattr) 15761 { 15762 struct btf *btf; 15763 int err; 15764 15765 if (!attr->func_info_cnt && !attr->line_info_cnt) { 15766 if (check_abnormal_return(env)) 15767 return -EINVAL; 15768 return 0; 15769 } 15770 15771 btf = btf_get_by_fd(attr->prog_btf_fd); 15772 if (IS_ERR(btf)) 15773 return PTR_ERR(btf); 15774 if (btf_is_kernel(btf)) { 15775 btf_put(btf); 15776 return -EACCES; 15777 } 15778 env->prog->aux->btf = btf; 15779 15780 err = check_btf_func(env, attr, uattr); 15781 if (err) 15782 return err; 15783 15784 err = check_btf_line(env, attr, uattr); 15785 if (err) 15786 return err; 15787 15788 err = check_core_relo(env, attr, uattr); 15789 if (err) 15790 return err; 15791 15792 return 0; 15793 } 15794 15795 /* check %cur's range satisfies %old's */ 15796 static bool range_within(struct bpf_reg_state *old, 15797 struct bpf_reg_state *cur) 15798 { 15799 return old->umin_value <= cur->umin_value && 15800 old->umax_value >= cur->umax_value && 15801 old->smin_value <= cur->smin_value && 15802 old->smax_value >= cur->smax_value && 15803 old->u32_min_value <= cur->u32_min_value && 15804 old->u32_max_value >= cur->u32_max_value && 15805 old->s32_min_value <= cur->s32_min_value && 15806 old->s32_max_value >= cur->s32_max_value; 15807 } 15808 15809 /* If in the old state two registers had the same id, then they need to have 15810 * the same id in the new state as well. But that id could be different from 15811 * the old state, so we need to track the mapping from old to new ids. 15812 * Once we have seen that, say, a reg with old id 5 had new id 9, any subsequent 15813 * regs with old id 5 must also have new id 9 for the new state to be safe. But 15814 * regs with a different old id could still have new id 9, we don't care about 15815 * that. 15816 * So we look through our idmap to see if this old id has been seen before. If 15817 * so, we require the new id to match; otherwise, we add the id pair to the map. 15818 */ 15819 static bool check_ids(u32 old_id, u32 cur_id, struct bpf_idmap *idmap) 15820 { 15821 struct bpf_id_pair *map = idmap->map; 15822 unsigned int i; 15823 15824 /* either both IDs should be set or both should be zero */ 15825 if (!!old_id != !!cur_id) 15826 return false; 15827 15828 if (old_id == 0) /* cur_id == 0 as well */ 15829 return true; 15830 15831 for (i = 0; i < BPF_ID_MAP_SIZE; i++) { 15832 if (!map[i].old) { 15833 /* Reached an empty slot; haven't seen this id before */ 15834 map[i].old = old_id; 15835 map[i].cur = cur_id; 15836 return true; 15837 } 15838 if (map[i].old == old_id) 15839 return map[i].cur == cur_id; 15840 if (map[i].cur == cur_id) 15841 return false; 15842 } 15843 /* We ran out of idmap slots, which should be impossible */ 15844 WARN_ON_ONCE(1); 15845 return false; 15846 } 15847 15848 /* Similar to check_ids(), but allocate a unique temporary ID 15849 * for 'old_id' or 'cur_id' of zero. 15850 * This makes pairs like '0 vs unique ID', 'unique ID vs 0' valid. 15851 */ 15852 static bool check_scalar_ids(u32 old_id, u32 cur_id, struct bpf_idmap *idmap) 15853 { 15854 old_id = old_id ? old_id : ++idmap->tmp_id_gen; 15855 cur_id = cur_id ? cur_id : ++idmap->tmp_id_gen; 15856 15857 return check_ids(old_id, cur_id, idmap); 15858 } 15859 15860 static void clean_func_state(struct bpf_verifier_env *env, 15861 struct bpf_func_state *st) 15862 { 15863 enum bpf_reg_liveness live; 15864 int i, j; 15865 15866 for (i = 0; i < BPF_REG_FP; i++) { 15867 live = st->regs[i].live; 15868 /* liveness must not touch this register anymore */ 15869 st->regs[i].live |= REG_LIVE_DONE; 15870 if (!(live & REG_LIVE_READ)) 15871 /* since the register is unused, clear its state 15872 * to make further comparison simpler 15873 */ 15874 __mark_reg_not_init(env, &st->regs[i]); 15875 } 15876 15877 for (i = 0; i < st->allocated_stack / BPF_REG_SIZE; i++) { 15878 live = st->stack[i].spilled_ptr.live; 15879 /* liveness must not touch this stack slot anymore */ 15880 st->stack[i].spilled_ptr.live |= REG_LIVE_DONE; 15881 if (!(live & REG_LIVE_READ)) { 15882 __mark_reg_not_init(env, &st->stack[i].spilled_ptr); 15883 for (j = 0; j < BPF_REG_SIZE; j++) 15884 st->stack[i].slot_type[j] = STACK_INVALID; 15885 } 15886 } 15887 } 15888 15889 static void clean_verifier_state(struct bpf_verifier_env *env, 15890 struct bpf_verifier_state *st) 15891 { 15892 int i; 15893 15894 if (st->frame[0]->regs[0].live & REG_LIVE_DONE) 15895 /* all regs in this state in all frames were already marked */ 15896 return; 15897 15898 for (i = 0; i <= st->curframe; i++) 15899 clean_func_state(env, st->frame[i]); 15900 } 15901 15902 /* the parentage chains form a tree. 15903 * the verifier states are added to state lists at given insn and 15904 * pushed into state stack for future exploration. 15905 * when the verifier reaches bpf_exit insn some of the verifer states 15906 * stored in the state lists have their final liveness state already, 15907 * but a lot of states will get revised from liveness point of view when 15908 * the verifier explores other branches. 15909 * Example: 15910 * 1: r0 = 1 15911 * 2: if r1 == 100 goto pc+1 15912 * 3: r0 = 2 15913 * 4: exit 15914 * when the verifier reaches exit insn the register r0 in the state list of 15915 * insn 2 will be seen as !REG_LIVE_READ. Then the verifier pops the other_branch 15916 * of insn 2 and goes exploring further. At the insn 4 it will walk the 15917 * parentage chain from insn 4 into insn 2 and will mark r0 as REG_LIVE_READ. 15918 * 15919 * Since the verifier pushes the branch states as it sees them while exploring 15920 * the program the condition of walking the branch instruction for the second 15921 * time means that all states below this branch were already explored and 15922 * their final liveness marks are already propagated. 15923 * Hence when the verifier completes the search of state list in is_state_visited() 15924 * we can call this clean_live_states() function to mark all liveness states 15925 * as REG_LIVE_DONE to indicate that 'parent' pointers of 'struct bpf_reg_state' 15926 * will not be used. 15927 * This function also clears the registers and stack for states that !READ 15928 * to simplify state merging. 15929 * 15930 * Important note here that walking the same branch instruction in the callee 15931 * doesn't meant that the states are DONE. The verifier has to compare 15932 * the callsites 15933 */ 15934 static void clean_live_states(struct bpf_verifier_env *env, int insn, 15935 struct bpf_verifier_state *cur) 15936 { 15937 struct bpf_verifier_state_list *sl; 15938 15939 sl = *explored_state(env, insn); 15940 while (sl) { 15941 if (sl->state.branches) 15942 goto next; 15943 if (sl->state.insn_idx != insn || 15944 !same_callsites(&sl->state, cur)) 15945 goto next; 15946 clean_verifier_state(env, &sl->state); 15947 next: 15948 sl = sl->next; 15949 } 15950 } 15951 15952 static bool regs_exact(const struct bpf_reg_state *rold, 15953 const struct bpf_reg_state *rcur, 15954 struct bpf_idmap *idmap) 15955 { 15956 return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 && 15957 check_ids(rold->id, rcur->id, idmap) && 15958 check_ids(rold->ref_obj_id, rcur->ref_obj_id, idmap); 15959 } 15960 15961 /* Returns true if (rold safe implies rcur safe) */ 15962 static bool regsafe(struct bpf_verifier_env *env, struct bpf_reg_state *rold, 15963 struct bpf_reg_state *rcur, struct bpf_idmap *idmap, bool exact) 15964 { 15965 if (exact) 15966 return regs_exact(rold, rcur, idmap); 15967 15968 if (!(rold->live & REG_LIVE_READ)) 15969 /* explored state didn't use this */ 15970 return true; 15971 if (rold->type == NOT_INIT) 15972 /* explored state can't have used this */ 15973 return true; 15974 if (rcur->type == NOT_INIT) 15975 return false; 15976 15977 /* Enforce that register types have to match exactly, including their 15978 * modifiers (like PTR_MAYBE_NULL, MEM_RDONLY, etc), as a general 15979 * rule. 15980 * 15981 * One can make a point that using a pointer register as unbounded 15982 * SCALAR would be technically acceptable, but this could lead to 15983 * pointer leaks because scalars are allowed to leak while pointers 15984 * are not. We could make this safe in special cases if root is 15985 * calling us, but it's probably not worth the hassle. 15986 * 15987 * Also, register types that are *not* MAYBE_NULL could technically be 15988 * safe to use as their MAYBE_NULL variants (e.g., PTR_TO_MAP_VALUE 15989 * is safe to be used as PTR_TO_MAP_VALUE_OR_NULL, provided both point 15990 * to the same map). 15991 * However, if the old MAYBE_NULL register then got NULL checked, 15992 * doing so could have affected others with the same id, and we can't 15993 * check for that because we lost the id when we converted to 15994 * a non-MAYBE_NULL variant. 15995 * So, as a general rule we don't allow mixing MAYBE_NULL and 15996 * non-MAYBE_NULL registers as well. 15997 */ 15998 if (rold->type != rcur->type) 15999 return false; 16000 16001 switch (base_type(rold->type)) { 16002 case SCALAR_VALUE: 16003 if (env->explore_alu_limits) { 16004 /* explore_alu_limits disables tnum_in() and range_within() 16005 * logic and requires everything to be strict 16006 */ 16007 return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 && 16008 check_scalar_ids(rold->id, rcur->id, idmap); 16009 } 16010 if (!rold->precise) 16011 return true; 16012 /* Why check_ids() for scalar registers? 16013 * 16014 * Consider the following BPF code: 16015 * 1: r6 = ... unbound scalar, ID=a ... 16016 * 2: r7 = ... unbound scalar, ID=b ... 16017 * 3: if (r6 > r7) goto +1 16018 * 4: r6 = r7 16019 * 5: if (r6 > X) goto ... 16020 * 6: ... memory operation using r7 ... 16021 * 16022 * First verification path is [1-6]: 16023 * - at (4) same bpf_reg_state::id (b) would be assigned to r6 and r7; 16024 * - at (5) r6 would be marked <= X, find_equal_scalars() would also mark 16025 * r7 <= X, because r6 and r7 share same id. 16026 * Next verification path is [1-4, 6]. 16027 * 16028 * Instruction (6) would be reached in two states: 16029 * I. r6{.id=b}, r7{.id=b} via path 1-6; 16030 * II. r6{.id=a}, r7{.id=b} via path 1-4, 6. 16031 * 16032 * Use check_ids() to distinguish these states. 16033 * --- 16034 * Also verify that new value satisfies old value range knowledge. 16035 */ 16036 return range_within(rold, rcur) && 16037 tnum_in(rold->var_off, rcur->var_off) && 16038 check_scalar_ids(rold->id, rcur->id, idmap); 16039 case PTR_TO_MAP_KEY: 16040 case PTR_TO_MAP_VALUE: 16041 case PTR_TO_MEM: 16042 case PTR_TO_BUF: 16043 case PTR_TO_TP_BUFFER: 16044 /* If the new min/max/var_off satisfy the old ones and 16045 * everything else matches, we are OK. 16046 */ 16047 return memcmp(rold, rcur, offsetof(struct bpf_reg_state, var_off)) == 0 && 16048 range_within(rold, rcur) && 16049 tnum_in(rold->var_off, rcur->var_off) && 16050 check_ids(rold->id, rcur->id, idmap) && 16051 check_ids(rold->ref_obj_id, rcur->ref_obj_id, idmap); 16052 case PTR_TO_PACKET_META: 16053 case PTR_TO_PACKET: 16054 /* We must have at least as much range as the old ptr 16055 * did, so that any accesses which were safe before are 16056 * still safe. This is true even if old range < old off, 16057 * since someone could have accessed through (ptr - k), or 16058 * even done ptr -= k in a register, to get a safe access. 16059 */ 16060 if (rold->range > rcur->range) 16061 return false; 16062 /* If the offsets don't match, we can't trust our alignment; 16063 * nor can we be sure that we won't fall out of range. 16064 */ 16065 if (rold->off != rcur->off) 16066 return false; 16067 /* id relations must be preserved */ 16068 if (!check_ids(rold->id, rcur->id, idmap)) 16069 return false; 16070 /* new val must satisfy old val knowledge */ 16071 return range_within(rold, rcur) && 16072 tnum_in(rold->var_off, rcur->var_off); 16073 case PTR_TO_STACK: 16074 /* two stack pointers are equal only if they're pointing to 16075 * the same stack frame, since fp-8 in foo != fp-8 in bar 16076 */ 16077 return regs_exact(rold, rcur, idmap) && rold->frameno == rcur->frameno; 16078 default: 16079 return regs_exact(rold, rcur, idmap); 16080 } 16081 } 16082 16083 static bool stacksafe(struct bpf_verifier_env *env, struct bpf_func_state *old, 16084 struct bpf_func_state *cur, struct bpf_idmap *idmap, bool exact) 16085 { 16086 int i, spi; 16087 16088 /* walk slots of the explored stack and ignore any additional 16089 * slots in the current stack, since explored(safe) state 16090 * didn't use them 16091 */ 16092 for (i = 0; i < old->allocated_stack; i++) { 16093 struct bpf_reg_state *old_reg, *cur_reg; 16094 16095 spi = i / BPF_REG_SIZE; 16096 16097 if (exact && 16098 (i >= cur->allocated_stack || 16099 old->stack[spi].slot_type[i % BPF_REG_SIZE] != 16100 cur->stack[spi].slot_type[i % BPF_REG_SIZE])) 16101 return false; 16102 16103 if (!(old->stack[spi].spilled_ptr.live & REG_LIVE_READ) && !exact) { 16104 i += BPF_REG_SIZE - 1; 16105 /* explored state didn't use this */ 16106 continue; 16107 } 16108 16109 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_INVALID) 16110 continue; 16111 16112 if (env->allow_uninit_stack && 16113 old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC) 16114 continue; 16115 16116 /* explored stack has more populated slots than current stack 16117 * and these slots were used 16118 */ 16119 if (i >= cur->allocated_stack) 16120 return false; 16121 16122 /* if old state was safe with misc data in the stack 16123 * it will be safe with zero-initialized stack. 16124 * The opposite is not true 16125 */ 16126 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC && 16127 cur->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_ZERO) 16128 continue; 16129 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] != 16130 cur->stack[spi].slot_type[i % BPF_REG_SIZE]) 16131 /* Ex: old explored (safe) state has STACK_SPILL in 16132 * this stack slot, but current has STACK_MISC -> 16133 * this verifier states are not equivalent, 16134 * return false to continue verification of this path 16135 */ 16136 return false; 16137 if (i % BPF_REG_SIZE != BPF_REG_SIZE - 1) 16138 continue; 16139 /* Both old and cur are having same slot_type */ 16140 switch (old->stack[spi].slot_type[BPF_REG_SIZE - 1]) { 16141 case STACK_SPILL: 16142 /* when explored and current stack slot are both storing 16143 * spilled registers, check that stored pointers types 16144 * are the same as well. 16145 * Ex: explored safe path could have stored 16146 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -8} 16147 * but current path has stored: 16148 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -16} 16149 * such verifier states are not equivalent. 16150 * return false to continue verification of this path 16151 */ 16152 if (!regsafe(env, &old->stack[spi].spilled_ptr, 16153 &cur->stack[spi].spilled_ptr, idmap, exact)) 16154 return false; 16155 break; 16156 case STACK_DYNPTR: 16157 old_reg = &old->stack[spi].spilled_ptr; 16158 cur_reg = &cur->stack[spi].spilled_ptr; 16159 if (old_reg->dynptr.type != cur_reg->dynptr.type || 16160 old_reg->dynptr.first_slot != cur_reg->dynptr.first_slot || 16161 !check_ids(old_reg->ref_obj_id, cur_reg->ref_obj_id, idmap)) 16162 return false; 16163 break; 16164 case STACK_ITER: 16165 old_reg = &old->stack[spi].spilled_ptr; 16166 cur_reg = &cur->stack[spi].spilled_ptr; 16167 /* iter.depth is not compared between states as it 16168 * doesn't matter for correctness and would otherwise 16169 * prevent convergence; we maintain it only to prevent 16170 * infinite loop check triggering, see 16171 * iter_active_depths_differ() 16172 */ 16173 if (old_reg->iter.btf != cur_reg->iter.btf || 16174 old_reg->iter.btf_id != cur_reg->iter.btf_id || 16175 old_reg->iter.state != cur_reg->iter.state || 16176 /* ignore {old_reg,cur_reg}->iter.depth, see above */ 16177 !check_ids(old_reg->ref_obj_id, cur_reg->ref_obj_id, idmap)) 16178 return false; 16179 break; 16180 case STACK_MISC: 16181 case STACK_ZERO: 16182 case STACK_INVALID: 16183 continue; 16184 /* Ensure that new unhandled slot types return false by default */ 16185 default: 16186 return false; 16187 } 16188 } 16189 return true; 16190 } 16191 16192 static bool refsafe(struct bpf_func_state *old, struct bpf_func_state *cur, 16193 struct bpf_idmap *idmap) 16194 { 16195 int i; 16196 16197 if (old->acquired_refs != cur->acquired_refs) 16198 return false; 16199 16200 for (i = 0; i < old->acquired_refs; i++) { 16201 if (!check_ids(old->refs[i].id, cur->refs[i].id, idmap)) 16202 return false; 16203 } 16204 16205 return true; 16206 } 16207 16208 /* compare two verifier states 16209 * 16210 * all states stored in state_list are known to be valid, since 16211 * verifier reached 'bpf_exit' instruction through them 16212 * 16213 * this function is called when verifier exploring different branches of 16214 * execution popped from the state stack. If it sees an old state that has 16215 * more strict register state and more strict stack state then this execution 16216 * branch doesn't need to be explored further, since verifier already 16217 * concluded that more strict state leads to valid finish. 16218 * 16219 * Therefore two states are equivalent if register state is more conservative 16220 * and explored stack state is more conservative than the current one. 16221 * Example: 16222 * explored current 16223 * (slot1=INV slot2=MISC) == (slot1=MISC slot2=MISC) 16224 * (slot1=MISC slot2=MISC) != (slot1=INV slot2=MISC) 16225 * 16226 * In other words if current stack state (one being explored) has more 16227 * valid slots than old one that already passed validation, it means 16228 * the verifier can stop exploring and conclude that current state is valid too 16229 * 16230 * Similarly with registers. If explored state has register type as invalid 16231 * whereas register type in current state is meaningful, it means that 16232 * the current state will reach 'bpf_exit' instruction safely 16233 */ 16234 static bool func_states_equal(struct bpf_verifier_env *env, struct bpf_func_state *old, 16235 struct bpf_func_state *cur, bool exact) 16236 { 16237 int i; 16238 16239 if (old->callback_depth > cur->callback_depth) 16240 return false; 16241 16242 for (i = 0; i < MAX_BPF_REG; i++) 16243 if (!regsafe(env, &old->regs[i], &cur->regs[i], 16244 &env->idmap_scratch, exact)) 16245 return false; 16246 16247 if (!stacksafe(env, old, cur, &env->idmap_scratch, exact)) 16248 return false; 16249 16250 if (!refsafe(old, cur, &env->idmap_scratch)) 16251 return false; 16252 16253 return true; 16254 } 16255 16256 static void reset_idmap_scratch(struct bpf_verifier_env *env) 16257 { 16258 env->idmap_scratch.tmp_id_gen = env->id_gen; 16259 memset(&env->idmap_scratch.map, 0, sizeof(env->idmap_scratch.map)); 16260 } 16261 16262 static bool states_equal(struct bpf_verifier_env *env, 16263 struct bpf_verifier_state *old, 16264 struct bpf_verifier_state *cur, 16265 bool exact) 16266 { 16267 int i; 16268 16269 if (old->curframe != cur->curframe) 16270 return false; 16271 16272 reset_idmap_scratch(env); 16273 16274 /* Verification state from speculative execution simulation 16275 * must never prune a non-speculative execution one. 16276 */ 16277 if (old->speculative && !cur->speculative) 16278 return false; 16279 16280 if (old->active_lock.ptr != cur->active_lock.ptr) 16281 return false; 16282 16283 /* Old and cur active_lock's have to be either both present 16284 * or both absent. 16285 */ 16286 if (!!old->active_lock.id != !!cur->active_lock.id) 16287 return false; 16288 16289 if (old->active_lock.id && 16290 !check_ids(old->active_lock.id, cur->active_lock.id, &env->idmap_scratch)) 16291 return false; 16292 16293 if (old->active_rcu_lock != cur->active_rcu_lock) 16294 return false; 16295 16296 /* for states to be equal callsites have to be the same 16297 * and all frame states need to be equivalent 16298 */ 16299 for (i = 0; i <= old->curframe; i++) { 16300 if (old->frame[i]->callsite != cur->frame[i]->callsite) 16301 return false; 16302 if (!func_states_equal(env, old->frame[i], cur->frame[i], exact)) 16303 return false; 16304 } 16305 return true; 16306 } 16307 16308 /* Return 0 if no propagation happened. Return negative error code if error 16309 * happened. Otherwise, return the propagated bit. 16310 */ 16311 static int propagate_liveness_reg(struct bpf_verifier_env *env, 16312 struct bpf_reg_state *reg, 16313 struct bpf_reg_state *parent_reg) 16314 { 16315 u8 parent_flag = parent_reg->live & REG_LIVE_READ; 16316 u8 flag = reg->live & REG_LIVE_READ; 16317 int err; 16318 16319 /* When comes here, read flags of PARENT_REG or REG could be any of 16320 * REG_LIVE_READ64, REG_LIVE_READ32, REG_LIVE_NONE. There is no need 16321 * of propagation if PARENT_REG has strongest REG_LIVE_READ64. 16322 */ 16323 if (parent_flag == REG_LIVE_READ64 || 16324 /* Or if there is no read flag from REG. */ 16325 !flag || 16326 /* Or if the read flag from REG is the same as PARENT_REG. */ 16327 parent_flag == flag) 16328 return 0; 16329 16330 err = mark_reg_read(env, reg, parent_reg, flag); 16331 if (err) 16332 return err; 16333 16334 return flag; 16335 } 16336 16337 /* A write screens off any subsequent reads; but write marks come from the 16338 * straight-line code between a state and its parent. When we arrive at an 16339 * equivalent state (jump target or such) we didn't arrive by the straight-line 16340 * code, so read marks in the state must propagate to the parent regardless 16341 * of the state's write marks. That's what 'parent == state->parent' comparison 16342 * in mark_reg_read() is for. 16343 */ 16344 static int propagate_liveness(struct bpf_verifier_env *env, 16345 const struct bpf_verifier_state *vstate, 16346 struct bpf_verifier_state *vparent) 16347 { 16348 struct bpf_reg_state *state_reg, *parent_reg; 16349 struct bpf_func_state *state, *parent; 16350 int i, frame, err = 0; 16351 16352 if (vparent->curframe != vstate->curframe) { 16353 WARN(1, "propagate_live: parent frame %d current frame %d\n", 16354 vparent->curframe, vstate->curframe); 16355 return -EFAULT; 16356 } 16357 /* Propagate read liveness of registers... */ 16358 BUILD_BUG_ON(BPF_REG_FP + 1 != MAX_BPF_REG); 16359 for (frame = 0; frame <= vstate->curframe; frame++) { 16360 parent = vparent->frame[frame]; 16361 state = vstate->frame[frame]; 16362 parent_reg = parent->regs; 16363 state_reg = state->regs; 16364 /* We don't need to worry about FP liveness, it's read-only */ 16365 for (i = frame < vstate->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++) { 16366 err = propagate_liveness_reg(env, &state_reg[i], 16367 &parent_reg[i]); 16368 if (err < 0) 16369 return err; 16370 if (err == REG_LIVE_READ64) 16371 mark_insn_zext(env, &parent_reg[i]); 16372 } 16373 16374 /* Propagate stack slots. */ 16375 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE && 16376 i < parent->allocated_stack / BPF_REG_SIZE; i++) { 16377 parent_reg = &parent->stack[i].spilled_ptr; 16378 state_reg = &state->stack[i].spilled_ptr; 16379 err = propagate_liveness_reg(env, state_reg, 16380 parent_reg); 16381 if (err < 0) 16382 return err; 16383 } 16384 } 16385 return 0; 16386 } 16387 16388 /* find precise scalars in the previous equivalent state and 16389 * propagate them into the current state 16390 */ 16391 static int propagate_precision(struct bpf_verifier_env *env, 16392 const struct bpf_verifier_state *old) 16393 { 16394 struct bpf_reg_state *state_reg; 16395 struct bpf_func_state *state; 16396 int i, err = 0, fr; 16397 bool first; 16398 16399 for (fr = old->curframe; fr >= 0; fr--) { 16400 state = old->frame[fr]; 16401 state_reg = state->regs; 16402 first = true; 16403 for (i = 0; i < BPF_REG_FP; i++, state_reg++) { 16404 if (state_reg->type != SCALAR_VALUE || 16405 !state_reg->precise || 16406 !(state_reg->live & REG_LIVE_READ)) 16407 continue; 16408 if (env->log.level & BPF_LOG_LEVEL2) { 16409 if (first) 16410 verbose(env, "frame %d: propagating r%d", fr, i); 16411 else 16412 verbose(env, ",r%d", i); 16413 } 16414 bt_set_frame_reg(&env->bt, fr, i); 16415 first = false; 16416 } 16417 16418 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) { 16419 if (!is_spilled_reg(&state->stack[i])) 16420 continue; 16421 state_reg = &state->stack[i].spilled_ptr; 16422 if (state_reg->type != SCALAR_VALUE || 16423 !state_reg->precise || 16424 !(state_reg->live & REG_LIVE_READ)) 16425 continue; 16426 if (env->log.level & BPF_LOG_LEVEL2) { 16427 if (first) 16428 verbose(env, "frame %d: propagating fp%d", 16429 fr, (-i - 1) * BPF_REG_SIZE); 16430 else 16431 verbose(env, ",fp%d", (-i - 1) * BPF_REG_SIZE); 16432 } 16433 bt_set_frame_slot(&env->bt, fr, i); 16434 first = false; 16435 } 16436 if (!first) 16437 verbose(env, "\n"); 16438 } 16439 16440 err = mark_chain_precision_batch(env); 16441 if (err < 0) 16442 return err; 16443 16444 return 0; 16445 } 16446 16447 static bool states_maybe_looping(struct bpf_verifier_state *old, 16448 struct bpf_verifier_state *cur) 16449 { 16450 struct bpf_func_state *fold, *fcur; 16451 int i, fr = cur->curframe; 16452 16453 if (old->curframe != fr) 16454 return false; 16455 16456 fold = old->frame[fr]; 16457 fcur = cur->frame[fr]; 16458 for (i = 0; i < MAX_BPF_REG; i++) 16459 if (memcmp(&fold->regs[i], &fcur->regs[i], 16460 offsetof(struct bpf_reg_state, parent))) 16461 return false; 16462 return true; 16463 } 16464 16465 static bool is_iter_next_insn(struct bpf_verifier_env *env, int insn_idx) 16466 { 16467 return env->insn_aux_data[insn_idx].is_iter_next; 16468 } 16469 16470 /* is_state_visited() handles iter_next() (see process_iter_next_call() for 16471 * terminology) calls specially: as opposed to bounded BPF loops, it *expects* 16472 * states to match, which otherwise would look like an infinite loop. So while 16473 * iter_next() calls are taken care of, we still need to be careful and 16474 * prevent erroneous and too eager declaration of "ininite loop", when 16475 * iterators are involved. 16476 * 16477 * Here's a situation in pseudo-BPF assembly form: 16478 * 16479 * 0: again: ; set up iter_next() call args 16480 * 1: r1 = &it ; <CHECKPOINT HERE> 16481 * 2: call bpf_iter_num_next ; this is iter_next() call 16482 * 3: if r0 == 0 goto done 16483 * 4: ... something useful here ... 16484 * 5: goto again ; another iteration 16485 * 6: done: 16486 * 7: r1 = &it 16487 * 8: call bpf_iter_num_destroy ; clean up iter state 16488 * 9: exit 16489 * 16490 * This is a typical loop. Let's assume that we have a prune point at 1:, 16491 * before we get to `call bpf_iter_num_next` (e.g., because of that `goto 16492 * again`, assuming other heuristics don't get in a way). 16493 * 16494 * When we first time come to 1:, let's say we have some state X. We proceed 16495 * to 2:, fork states, enqueue ACTIVE, validate NULL case successfully, exit. 16496 * Now we come back to validate that forked ACTIVE state. We proceed through 16497 * 3-5, come to goto, jump to 1:. Let's assume our state didn't change, so we 16498 * are converging. But the problem is that we don't know that yet, as this 16499 * convergence has to happen at iter_next() call site only. So if nothing is 16500 * done, at 1: verifier will use bounded loop logic and declare infinite 16501 * looping (and would be *technically* correct, if not for iterator's 16502 * "eventual sticky NULL" contract, see process_iter_next_call()). But we 16503 * don't want that. So what we do in process_iter_next_call() when we go on 16504 * another ACTIVE iteration, we bump slot->iter.depth, to mark that it's 16505 * a different iteration. So when we suspect an infinite loop, we additionally 16506 * check if any of the *ACTIVE* iterator states depths differ. If yes, we 16507 * pretend we are not looping and wait for next iter_next() call. 16508 * 16509 * This only applies to ACTIVE state. In DRAINED state we don't expect to 16510 * loop, because that would actually mean infinite loop, as DRAINED state is 16511 * "sticky", and so we'll keep returning into the same instruction with the 16512 * same state (at least in one of possible code paths). 16513 * 16514 * This approach allows to keep infinite loop heuristic even in the face of 16515 * active iterator. E.g., C snippet below is and will be detected as 16516 * inifintely looping: 16517 * 16518 * struct bpf_iter_num it; 16519 * int *p, x; 16520 * 16521 * bpf_iter_num_new(&it, 0, 10); 16522 * while ((p = bpf_iter_num_next(&t))) { 16523 * x = p; 16524 * while (x--) {} // <<-- infinite loop here 16525 * } 16526 * 16527 */ 16528 static bool iter_active_depths_differ(struct bpf_verifier_state *old, struct bpf_verifier_state *cur) 16529 { 16530 struct bpf_reg_state *slot, *cur_slot; 16531 struct bpf_func_state *state; 16532 int i, fr; 16533 16534 for (fr = old->curframe; fr >= 0; fr--) { 16535 state = old->frame[fr]; 16536 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) { 16537 if (state->stack[i].slot_type[0] != STACK_ITER) 16538 continue; 16539 16540 slot = &state->stack[i].spilled_ptr; 16541 if (slot->iter.state != BPF_ITER_STATE_ACTIVE) 16542 continue; 16543 16544 cur_slot = &cur->frame[fr]->stack[i].spilled_ptr; 16545 if (cur_slot->iter.depth != slot->iter.depth) 16546 return true; 16547 } 16548 } 16549 return false; 16550 } 16551 16552 static int is_state_visited(struct bpf_verifier_env *env, int insn_idx) 16553 { 16554 struct bpf_verifier_state_list *new_sl; 16555 struct bpf_verifier_state_list *sl, **pprev; 16556 struct bpf_verifier_state *cur = env->cur_state, *new, *loop_entry; 16557 int i, j, n, err, states_cnt = 0; 16558 bool force_new_state = env->test_state_freq || is_force_checkpoint(env, insn_idx); 16559 bool add_new_state = force_new_state; 16560 bool force_exact; 16561 16562 /* bpf progs typically have pruning point every 4 instructions 16563 * http://vger.kernel.org/bpfconf2019.html#session-1 16564 * Do not add new state for future pruning if the verifier hasn't seen 16565 * at least 2 jumps and at least 8 instructions. 16566 * This heuristics helps decrease 'total_states' and 'peak_states' metric. 16567 * In tests that amounts to up to 50% reduction into total verifier 16568 * memory consumption and 20% verifier time speedup. 16569 */ 16570 if (env->jmps_processed - env->prev_jmps_processed >= 2 && 16571 env->insn_processed - env->prev_insn_processed >= 8) 16572 add_new_state = true; 16573 16574 pprev = explored_state(env, insn_idx); 16575 sl = *pprev; 16576 16577 clean_live_states(env, insn_idx, cur); 16578 16579 while (sl) { 16580 states_cnt++; 16581 if (sl->state.insn_idx != insn_idx) 16582 goto next; 16583 16584 if (sl->state.branches) { 16585 struct bpf_func_state *frame = sl->state.frame[sl->state.curframe]; 16586 16587 if (frame->in_async_callback_fn && 16588 frame->async_entry_cnt != cur->frame[cur->curframe]->async_entry_cnt) { 16589 /* Different async_entry_cnt means that the verifier is 16590 * processing another entry into async callback. 16591 * Seeing the same state is not an indication of infinite 16592 * loop or infinite recursion. 16593 * But finding the same state doesn't mean that it's safe 16594 * to stop processing the current state. The previous state 16595 * hasn't yet reached bpf_exit, since state.branches > 0. 16596 * Checking in_async_callback_fn alone is not enough either. 16597 * Since the verifier still needs to catch infinite loops 16598 * inside async callbacks. 16599 */ 16600 goto skip_inf_loop_check; 16601 } 16602 /* BPF open-coded iterators loop detection is special. 16603 * states_maybe_looping() logic is too simplistic in detecting 16604 * states that *might* be equivalent, because it doesn't know 16605 * about ID remapping, so don't even perform it. 16606 * See process_iter_next_call() and iter_active_depths_differ() 16607 * for overview of the logic. When current and one of parent 16608 * states are detected as equivalent, it's a good thing: we prove 16609 * convergence and can stop simulating further iterations. 16610 * It's safe to assume that iterator loop will finish, taking into 16611 * account iter_next() contract of eventually returning 16612 * sticky NULL result. 16613 * 16614 * Note, that states have to be compared exactly in this case because 16615 * read and precision marks might not be finalized inside the loop. 16616 * E.g. as in the program below: 16617 * 16618 * 1. r7 = -16 16619 * 2. r6 = bpf_get_prandom_u32() 16620 * 3. while (bpf_iter_num_next(&fp[-8])) { 16621 * 4. if (r6 != 42) { 16622 * 5. r7 = -32 16623 * 6. r6 = bpf_get_prandom_u32() 16624 * 7. continue 16625 * 8. } 16626 * 9. r0 = r10 16627 * 10. r0 += r7 16628 * 11. r8 = *(u64 *)(r0 + 0) 16629 * 12. r6 = bpf_get_prandom_u32() 16630 * 13. } 16631 * 16632 * Here verifier would first visit path 1-3, create a checkpoint at 3 16633 * with r7=-16, continue to 4-7,3. Existing checkpoint at 3 does 16634 * not have read or precision mark for r7 yet, thus inexact states 16635 * comparison would discard current state with r7=-32 16636 * => unsafe memory access at 11 would not be caught. 16637 */ 16638 if (is_iter_next_insn(env, insn_idx)) { 16639 if (states_equal(env, &sl->state, cur, true)) { 16640 struct bpf_func_state *cur_frame; 16641 struct bpf_reg_state *iter_state, *iter_reg; 16642 int spi; 16643 16644 cur_frame = cur->frame[cur->curframe]; 16645 /* btf_check_iter_kfuncs() enforces that 16646 * iter state pointer is always the first arg 16647 */ 16648 iter_reg = &cur_frame->regs[BPF_REG_1]; 16649 /* current state is valid due to states_equal(), 16650 * so we can assume valid iter and reg state, 16651 * no need for extra (re-)validations 16652 */ 16653 spi = __get_spi(iter_reg->off + iter_reg->var_off.value); 16654 iter_state = &func(env, iter_reg)->stack[spi].spilled_ptr; 16655 if (iter_state->iter.state == BPF_ITER_STATE_ACTIVE) { 16656 update_loop_entry(cur, &sl->state); 16657 goto hit; 16658 } 16659 } 16660 goto skip_inf_loop_check; 16661 } 16662 if (calls_callback(env, insn_idx)) { 16663 if (states_equal(env, &sl->state, cur, true)) 16664 goto hit; 16665 goto skip_inf_loop_check; 16666 } 16667 /* attempt to detect infinite loop to avoid unnecessary doomed work */ 16668 if (states_maybe_looping(&sl->state, cur) && 16669 states_equal(env, &sl->state, cur, false) && 16670 !iter_active_depths_differ(&sl->state, cur) && 16671 sl->state.callback_unroll_depth == cur->callback_unroll_depth) { 16672 verbose_linfo(env, insn_idx, "; "); 16673 verbose(env, "infinite loop detected at insn %d\n", insn_idx); 16674 verbose(env, "cur state:"); 16675 print_verifier_state(env, cur->frame[cur->curframe], true); 16676 verbose(env, "old state:"); 16677 print_verifier_state(env, sl->state.frame[cur->curframe], true); 16678 return -EINVAL; 16679 } 16680 /* if the verifier is processing a loop, avoid adding new state 16681 * too often, since different loop iterations have distinct 16682 * states and may not help future pruning. 16683 * This threshold shouldn't be too low to make sure that 16684 * a loop with large bound will be rejected quickly. 16685 * The most abusive loop will be: 16686 * r1 += 1 16687 * if r1 < 1000000 goto pc-2 16688 * 1M insn_procssed limit / 100 == 10k peak states. 16689 * This threshold shouldn't be too high either, since states 16690 * at the end of the loop are likely to be useful in pruning. 16691 */ 16692 skip_inf_loop_check: 16693 if (!force_new_state && 16694 env->jmps_processed - env->prev_jmps_processed < 20 && 16695 env->insn_processed - env->prev_insn_processed < 100) 16696 add_new_state = false; 16697 goto miss; 16698 } 16699 /* If sl->state is a part of a loop and this loop's entry is a part of 16700 * current verification path then states have to be compared exactly. 16701 * 'force_exact' is needed to catch the following case: 16702 * 16703 * initial Here state 'succ' was processed first, 16704 * | it was eventually tracked to produce a 16705 * V state identical to 'hdr'. 16706 * .---------> hdr All branches from 'succ' had been explored 16707 * | | and thus 'succ' has its .branches == 0. 16708 * | V 16709 * | .------... Suppose states 'cur' and 'succ' correspond 16710 * | | | to the same instruction + callsites. 16711 * | V V In such case it is necessary to check 16712 * | ... ... if 'succ' and 'cur' are states_equal(). 16713 * | | | If 'succ' and 'cur' are a part of the 16714 * | V V same loop exact flag has to be set. 16715 * | succ <- cur To check if that is the case, verify 16716 * | | if loop entry of 'succ' is in current 16717 * | V DFS path. 16718 * | ... 16719 * | | 16720 * '----' 16721 * 16722 * Additional details are in the comment before get_loop_entry(). 16723 */ 16724 loop_entry = get_loop_entry(&sl->state); 16725 force_exact = loop_entry && loop_entry->branches > 0; 16726 if (states_equal(env, &sl->state, cur, force_exact)) { 16727 if (force_exact) 16728 update_loop_entry(cur, loop_entry); 16729 hit: 16730 sl->hit_cnt++; 16731 /* reached equivalent register/stack state, 16732 * prune the search. 16733 * Registers read by the continuation are read by us. 16734 * If we have any write marks in env->cur_state, they 16735 * will prevent corresponding reads in the continuation 16736 * from reaching our parent (an explored_state). Our 16737 * own state will get the read marks recorded, but 16738 * they'll be immediately forgotten as we're pruning 16739 * this state and will pop a new one. 16740 */ 16741 err = propagate_liveness(env, &sl->state, cur); 16742 16743 /* if previous state reached the exit with precision and 16744 * current state is equivalent to it (except precsion marks) 16745 * the precision needs to be propagated back in 16746 * the current state. 16747 */ 16748 err = err ? : push_jmp_history(env, cur); 16749 err = err ? : propagate_precision(env, &sl->state); 16750 if (err) 16751 return err; 16752 return 1; 16753 } 16754 miss: 16755 /* when new state is not going to be added do not increase miss count. 16756 * Otherwise several loop iterations will remove the state 16757 * recorded earlier. The goal of these heuristics is to have 16758 * states from some iterations of the loop (some in the beginning 16759 * and some at the end) to help pruning. 16760 */ 16761 if (add_new_state) 16762 sl->miss_cnt++; 16763 /* heuristic to determine whether this state is beneficial 16764 * to keep checking from state equivalence point of view. 16765 * Higher numbers increase max_states_per_insn and verification time, 16766 * but do not meaningfully decrease insn_processed. 16767 * 'n' controls how many times state could miss before eviction. 16768 * Use bigger 'n' for checkpoints because evicting checkpoint states 16769 * too early would hinder iterator convergence. 16770 */ 16771 n = is_force_checkpoint(env, insn_idx) && sl->state.branches > 0 ? 64 : 3; 16772 if (sl->miss_cnt > sl->hit_cnt * n + n) { 16773 /* the state is unlikely to be useful. Remove it to 16774 * speed up verification 16775 */ 16776 *pprev = sl->next; 16777 if (sl->state.frame[0]->regs[0].live & REG_LIVE_DONE && 16778 !sl->state.used_as_loop_entry) { 16779 u32 br = sl->state.branches; 16780 16781 WARN_ONCE(br, 16782 "BUG live_done but branches_to_explore %d\n", 16783 br); 16784 free_verifier_state(&sl->state, false); 16785 kfree(sl); 16786 env->peak_states--; 16787 } else { 16788 /* cannot free this state, since parentage chain may 16789 * walk it later. Add it for free_list instead to 16790 * be freed at the end of verification 16791 */ 16792 sl->next = env->free_list; 16793 env->free_list = sl; 16794 } 16795 sl = *pprev; 16796 continue; 16797 } 16798 next: 16799 pprev = &sl->next; 16800 sl = *pprev; 16801 } 16802 16803 if (env->max_states_per_insn < states_cnt) 16804 env->max_states_per_insn = states_cnt; 16805 16806 if (!env->bpf_capable && states_cnt > BPF_COMPLEXITY_LIMIT_STATES) 16807 return 0; 16808 16809 if (!add_new_state) 16810 return 0; 16811 16812 /* There were no equivalent states, remember the current one. 16813 * Technically the current state is not proven to be safe yet, 16814 * but it will either reach outer most bpf_exit (which means it's safe) 16815 * or it will be rejected. When there are no loops the verifier won't be 16816 * seeing this tuple (frame[0].callsite, frame[1].callsite, .. insn_idx) 16817 * again on the way to bpf_exit. 16818 * When looping the sl->state.branches will be > 0 and this state 16819 * will not be considered for equivalence until branches == 0. 16820 */ 16821 new_sl = kzalloc(sizeof(struct bpf_verifier_state_list), GFP_KERNEL); 16822 if (!new_sl) 16823 return -ENOMEM; 16824 env->total_states++; 16825 env->peak_states++; 16826 env->prev_jmps_processed = env->jmps_processed; 16827 env->prev_insn_processed = env->insn_processed; 16828 16829 /* forget precise markings we inherited, see __mark_chain_precision */ 16830 if (env->bpf_capable) 16831 mark_all_scalars_imprecise(env, cur); 16832 16833 /* add new state to the head of linked list */ 16834 new = &new_sl->state; 16835 err = copy_verifier_state(new, cur); 16836 if (err) { 16837 free_verifier_state(new, false); 16838 kfree(new_sl); 16839 return err; 16840 } 16841 new->insn_idx = insn_idx; 16842 WARN_ONCE(new->branches != 1, 16843 "BUG is_state_visited:branches_to_explore=%d insn %d\n", new->branches, insn_idx); 16844 16845 cur->parent = new; 16846 cur->first_insn_idx = insn_idx; 16847 cur->dfs_depth = new->dfs_depth + 1; 16848 clear_jmp_history(cur); 16849 new_sl->next = *explored_state(env, insn_idx); 16850 *explored_state(env, insn_idx) = new_sl; 16851 /* connect new state to parentage chain. Current frame needs all 16852 * registers connected. Only r6 - r9 of the callers are alive (pushed 16853 * to the stack implicitly by JITs) so in callers' frames connect just 16854 * r6 - r9 as an optimization. Callers will have r1 - r5 connected to 16855 * the state of the call instruction (with WRITTEN set), and r0 comes 16856 * from callee with its full parentage chain, anyway. 16857 */ 16858 /* clear write marks in current state: the writes we did are not writes 16859 * our child did, so they don't screen off its reads from us. 16860 * (There are no read marks in current state, because reads always mark 16861 * their parent and current state never has children yet. Only 16862 * explored_states can get read marks.) 16863 */ 16864 for (j = 0; j <= cur->curframe; j++) { 16865 for (i = j < cur->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++) 16866 cur->frame[j]->regs[i].parent = &new->frame[j]->regs[i]; 16867 for (i = 0; i < BPF_REG_FP; i++) 16868 cur->frame[j]->regs[i].live = REG_LIVE_NONE; 16869 } 16870 16871 /* all stack frames are accessible from callee, clear them all */ 16872 for (j = 0; j <= cur->curframe; j++) { 16873 struct bpf_func_state *frame = cur->frame[j]; 16874 struct bpf_func_state *newframe = new->frame[j]; 16875 16876 for (i = 0; i < frame->allocated_stack / BPF_REG_SIZE; i++) { 16877 frame->stack[i].spilled_ptr.live = REG_LIVE_NONE; 16878 frame->stack[i].spilled_ptr.parent = 16879 &newframe->stack[i].spilled_ptr; 16880 } 16881 } 16882 return 0; 16883 } 16884 16885 /* Return true if it's OK to have the same insn return a different type. */ 16886 static bool reg_type_mismatch_ok(enum bpf_reg_type type) 16887 { 16888 switch (base_type(type)) { 16889 case PTR_TO_CTX: 16890 case PTR_TO_SOCKET: 16891 case PTR_TO_SOCK_COMMON: 16892 case PTR_TO_TCP_SOCK: 16893 case PTR_TO_XDP_SOCK: 16894 case PTR_TO_BTF_ID: 16895 return false; 16896 default: 16897 return true; 16898 } 16899 } 16900 16901 /* If an instruction was previously used with particular pointer types, then we 16902 * need to be careful to avoid cases such as the below, where it may be ok 16903 * for one branch accessing the pointer, but not ok for the other branch: 16904 * 16905 * R1 = sock_ptr 16906 * goto X; 16907 * ... 16908 * R1 = some_other_valid_ptr; 16909 * goto X; 16910 * ... 16911 * R2 = *(u32 *)(R1 + 0); 16912 */ 16913 static bool reg_type_mismatch(enum bpf_reg_type src, enum bpf_reg_type prev) 16914 { 16915 return src != prev && (!reg_type_mismatch_ok(src) || 16916 !reg_type_mismatch_ok(prev)); 16917 } 16918 16919 static int save_aux_ptr_type(struct bpf_verifier_env *env, enum bpf_reg_type type, 16920 bool allow_trust_missmatch) 16921 { 16922 enum bpf_reg_type *prev_type = &env->insn_aux_data[env->insn_idx].ptr_type; 16923 16924 if (*prev_type == NOT_INIT) { 16925 /* Saw a valid insn 16926 * dst_reg = *(u32 *)(src_reg + off) 16927 * save type to validate intersecting paths 16928 */ 16929 *prev_type = type; 16930 } else if (reg_type_mismatch(type, *prev_type)) { 16931 /* Abuser program is trying to use the same insn 16932 * dst_reg = *(u32*) (src_reg + off) 16933 * with different pointer types: 16934 * src_reg == ctx in one branch and 16935 * src_reg == stack|map in some other branch. 16936 * Reject it. 16937 */ 16938 if (allow_trust_missmatch && 16939 base_type(type) == PTR_TO_BTF_ID && 16940 base_type(*prev_type) == PTR_TO_BTF_ID) { 16941 /* 16942 * Have to support a use case when one path through 16943 * the program yields TRUSTED pointer while another 16944 * is UNTRUSTED. Fallback to UNTRUSTED to generate 16945 * BPF_PROBE_MEM/BPF_PROBE_MEMSX. 16946 */ 16947 *prev_type = PTR_TO_BTF_ID | PTR_UNTRUSTED; 16948 } else { 16949 verbose(env, "same insn cannot be used with different pointers\n"); 16950 return -EINVAL; 16951 } 16952 } 16953 16954 return 0; 16955 } 16956 16957 static int do_check(struct bpf_verifier_env *env) 16958 { 16959 bool pop_log = !(env->log.level & BPF_LOG_LEVEL2); 16960 struct bpf_verifier_state *state = env->cur_state; 16961 struct bpf_insn *insns = env->prog->insnsi; 16962 struct bpf_reg_state *regs; 16963 int insn_cnt = env->prog->len; 16964 bool do_print_state = false; 16965 int prev_insn_idx = -1; 16966 16967 for (;;) { 16968 struct bpf_insn *insn; 16969 u8 class; 16970 int err; 16971 16972 env->prev_insn_idx = prev_insn_idx; 16973 if (env->insn_idx >= insn_cnt) { 16974 verbose(env, "invalid insn idx %d insn_cnt %d\n", 16975 env->insn_idx, insn_cnt); 16976 return -EFAULT; 16977 } 16978 16979 insn = &insns[env->insn_idx]; 16980 class = BPF_CLASS(insn->code); 16981 16982 if (++env->insn_processed > BPF_COMPLEXITY_LIMIT_INSNS) { 16983 verbose(env, 16984 "BPF program is too large. Processed %d insn\n", 16985 env->insn_processed); 16986 return -E2BIG; 16987 } 16988 16989 state->last_insn_idx = env->prev_insn_idx; 16990 16991 if (is_prune_point(env, env->insn_idx)) { 16992 err = is_state_visited(env, env->insn_idx); 16993 if (err < 0) 16994 return err; 16995 if (err == 1) { 16996 /* found equivalent state, can prune the search */ 16997 if (env->log.level & BPF_LOG_LEVEL) { 16998 if (do_print_state) 16999 verbose(env, "\nfrom %d to %d%s: safe\n", 17000 env->prev_insn_idx, env->insn_idx, 17001 env->cur_state->speculative ? 17002 " (speculative execution)" : ""); 17003 else 17004 verbose(env, "%d: safe\n", env->insn_idx); 17005 } 17006 goto process_bpf_exit; 17007 } 17008 } 17009 17010 if (is_jmp_point(env, env->insn_idx)) { 17011 err = push_jmp_history(env, state); 17012 if (err) 17013 return err; 17014 } 17015 17016 if (signal_pending(current)) 17017 return -EAGAIN; 17018 17019 if (need_resched()) 17020 cond_resched(); 17021 17022 if (env->log.level & BPF_LOG_LEVEL2 && do_print_state) { 17023 verbose(env, "\nfrom %d to %d%s:", 17024 env->prev_insn_idx, env->insn_idx, 17025 env->cur_state->speculative ? 17026 " (speculative execution)" : ""); 17027 print_verifier_state(env, state->frame[state->curframe], true); 17028 do_print_state = false; 17029 } 17030 17031 if (env->log.level & BPF_LOG_LEVEL) { 17032 const struct bpf_insn_cbs cbs = { 17033 .cb_call = disasm_kfunc_name, 17034 .cb_print = verbose, 17035 .private_data = env, 17036 }; 17037 17038 if (verifier_state_scratched(env)) 17039 print_insn_state(env, state->frame[state->curframe]); 17040 17041 verbose_linfo(env, env->insn_idx, "; "); 17042 env->prev_log_pos = env->log.end_pos; 17043 verbose(env, "%d: ", env->insn_idx); 17044 print_bpf_insn(&cbs, insn, env->allow_ptr_leaks); 17045 env->prev_insn_print_pos = env->log.end_pos - env->prev_log_pos; 17046 env->prev_log_pos = env->log.end_pos; 17047 } 17048 17049 if (bpf_prog_is_offloaded(env->prog->aux)) { 17050 err = bpf_prog_offload_verify_insn(env, env->insn_idx, 17051 env->prev_insn_idx); 17052 if (err) 17053 return err; 17054 } 17055 17056 regs = cur_regs(env); 17057 sanitize_mark_insn_seen(env); 17058 prev_insn_idx = env->insn_idx; 17059 17060 if (class == BPF_ALU || class == BPF_ALU64) { 17061 err = check_alu_op(env, insn); 17062 if (err) 17063 return err; 17064 17065 } else if (class == BPF_LDX) { 17066 enum bpf_reg_type src_reg_type; 17067 17068 /* check for reserved fields is already done */ 17069 17070 /* check src operand */ 17071 err = check_reg_arg(env, insn->src_reg, SRC_OP); 17072 if (err) 17073 return err; 17074 17075 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK); 17076 if (err) 17077 return err; 17078 17079 src_reg_type = regs[insn->src_reg].type; 17080 17081 /* check that memory (src_reg + off) is readable, 17082 * the state of dst_reg will be updated by this func 17083 */ 17084 err = check_mem_access(env, env->insn_idx, insn->src_reg, 17085 insn->off, BPF_SIZE(insn->code), 17086 BPF_READ, insn->dst_reg, false, 17087 BPF_MODE(insn->code) == BPF_MEMSX); 17088 if (err) 17089 return err; 17090 17091 err = save_aux_ptr_type(env, src_reg_type, true); 17092 if (err) 17093 return err; 17094 } else if (class == BPF_STX) { 17095 enum bpf_reg_type dst_reg_type; 17096 17097 if (BPF_MODE(insn->code) == BPF_ATOMIC) { 17098 err = check_atomic(env, env->insn_idx, insn); 17099 if (err) 17100 return err; 17101 env->insn_idx++; 17102 continue; 17103 } 17104 17105 if (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0) { 17106 verbose(env, "BPF_STX uses reserved fields\n"); 17107 return -EINVAL; 17108 } 17109 17110 /* check src1 operand */ 17111 err = check_reg_arg(env, insn->src_reg, SRC_OP); 17112 if (err) 17113 return err; 17114 /* check src2 operand */ 17115 err = check_reg_arg(env, insn->dst_reg, SRC_OP); 17116 if (err) 17117 return err; 17118 17119 dst_reg_type = regs[insn->dst_reg].type; 17120 17121 /* check that memory (dst_reg + off) is writeable */ 17122 err = check_mem_access(env, env->insn_idx, insn->dst_reg, 17123 insn->off, BPF_SIZE(insn->code), 17124 BPF_WRITE, insn->src_reg, false, false); 17125 if (err) 17126 return err; 17127 17128 err = save_aux_ptr_type(env, dst_reg_type, false); 17129 if (err) 17130 return err; 17131 } else if (class == BPF_ST) { 17132 enum bpf_reg_type dst_reg_type; 17133 17134 if (BPF_MODE(insn->code) != BPF_MEM || 17135 insn->src_reg != BPF_REG_0) { 17136 verbose(env, "BPF_ST uses reserved fields\n"); 17137 return -EINVAL; 17138 } 17139 /* check src operand */ 17140 err = check_reg_arg(env, insn->dst_reg, SRC_OP); 17141 if (err) 17142 return err; 17143 17144 dst_reg_type = regs[insn->dst_reg].type; 17145 17146 /* check that memory (dst_reg + off) is writeable */ 17147 err = check_mem_access(env, env->insn_idx, insn->dst_reg, 17148 insn->off, BPF_SIZE(insn->code), 17149 BPF_WRITE, -1, false, false); 17150 if (err) 17151 return err; 17152 17153 err = save_aux_ptr_type(env, dst_reg_type, false); 17154 if (err) 17155 return err; 17156 } else if (class == BPF_JMP || class == BPF_JMP32) { 17157 u8 opcode = BPF_OP(insn->code); 17158 17159 env->jmps_processed++; 17160 if (opcode == BPF_CALL) { 17161 if (BPF_SRC(insn->code) != BPF_K || 17162 (insn->src_reg != BPF_PSEUDO_KFUNC_CALL 17163 && insn->off != 0) || 17164 (insn->src_reg != BPF_REG_0 && 17165 insn->src_reg != BPF_PSEUDO_CALL && 17166 insn->src_reg != BPF_PSEUDO_KFUNC_CALL) || 17167 insn->dst_reg != BPF_REG_0 || 17168 class == BPF_JMP32) { 17169 verbose(env, "BPF_CALL uses reserved fields\n"); 17170 return -EINVAL; 17171 } 17172 17173 if (env->cur_state->active_lock.ptr) { 17174 if ((insn->src_reg == BPF_REG_0 && insn->imm != BPF_FUNC_spin_unlock) || 17175 (insn->src_reg == BPF_PSEUDO_CALL) || 17176 (insn->src_reg == BPF_PSEUDO_KFUNC_CALL && 17177 (insn->off != 0 || !is_bpf_graph_api_kfunc(insn->imm)))) { 17178 verbose(env, "function calls are not allowed while holding a lock\n"); 17179 return -EINVAL; 17180 } 17181 } 17182 if (insn->src_reg == BPF_PSEUDO_CALL) 17183 err = check_func_call(env, insn, &env->insn_idx); 17184 else if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) 17185 err = check_kfunc_call(env, insn, &env->insn_idx); 17186 else 17187 err = check_helper_call(env, insn, &env->insn_idx); 17188 if (err) 17189 return err; 17190 17191 mark_reg_scratched(env, BPF_REG_0); 17192 } else if (opcode == BPF_JA) { 17193 if (BPF_SRC(insn->code) != BPF_K || 17194 insn->src_reg != BPF_REG_0 || 17195 insn->dst_reg != BPF_REG_0 || 17196 (class == BPF_JMP && insn->imm != 0) || 17197 (class == BPF_JMP32 && insn->off != 0)) { 17198 verbose(env, "BPF_JA uses reserved fields\n"); 17199 return -EINVAL; 17200 } 17201 17202 if (class == BPF_JMP) 17203 env->insn_idx += insn->off + 1; 17204 else 17205 env->insn_idx += insn->imm + 1; 17206 continue; 17207 17208 } else if (opcode == BPF_EXIT) { 17209 if (BPF_SRC(insn->code) != BPF_K || 17210 insn->imm != 0 || 17211 insn->src_reg != BPF_REG_0 || 17212 insn->dst_reg != BPF_REG_0 || 17213 class == BPF_JMP32) { 17214 verbose(env, "BPF_EXIT uses reserved fields\n"); 17215 return -EINVAL; 17216 } 17217 17218 if (env->cur_state->active_lock.ptr && 17219 !in_rbtree_lock_required_cb(env)) { 17220 verbose(env, "bpf_spin_unlock is missing\n"); 17221 return -EINVAL; 17222 } 17223 17224 if (env->cur_state->active_rcu_lock && 17225 !in_rbtree_lock_required_cb(env)) { 17226 verbose(env, "bpf_rcu_read_unlock is missing\n"); 17227 return -EINVAL; 17228 } 17229 17230 /* We must do check_reference_leak here before 17231 * prepare_func_exit to handle the case when 17232 * state->curframe > 0, it may be a callback 17233 * function, for which reference_state must 17234 * match caller reference state when it exits. 17235 */ 17236 err = check_reference_leak(env); 17237 if (err) 17238 return err; 17239 17240 if (state->curframe) { 17241 /* exit from nested function */ 17242 err = prepare_func_exit(env, &env->insn_idx); 17243 if (err) 17244 return err; 17245 do_print_state = true; 17246 continue; 17247 } 17248 17249 err = check_return_code(env); 17250 if (err) 17251 return err; 17252 process_bpf_exit: 17253 mark_verifier_state_scratched(env); 17254 update_branch_counts(env, env->cur_state); 17255 err = pop_stack(env, &prev_insn_idx, 17256 &env->insn_idx, pop_log); 17257 if (err < 0) { 17258 if (err != -ENOENT) 17259 return err; 17260 break; 17261 } else { 17262 do_print_state = true; 17263 continue; 17264 } 17265 } else { 17266 err = check_cond_jmp_op(env, insn, &env->insn_idx); 17267 if (err) 17268 return err; 17269 } 17270 } else if (class == BPF_LD) { 17271 u8 mode = BPF_MODE(insn->code); 17272 17273 if (mode == BPF_ABS || mode == BPF_IND) { 17274 err = check_ld_abs(env, insn); 17275 if (err) 17276 return err; 17277 17278 } else if (mode == BPF_IMM) { 17279 err = check_ld_imm(env, insn); 17280 if (err) 17281 return err; 17282 17283 env->insn_idx++; 17284 sanitize_mark_insn_seen(env); 17285 } else { 17286 verbose(env, "invalid BPF_LD mode\n"); 17287 return -EINVAL; 17288 } 17289 } else { 17290 verbose(env, "unknown insn class %d\n", class); 17291 return -EINVAL; 17292 } 17293 17294 env->insn_idx++; 17295 } 17296 17297 return 0; 17298 } 17299 17300 static int find_btf_percpu_datasec(struct btf *btf) 17301 { 17302 const struct btf_type *t; 17303 const char *tname; 17304 int i, n; 17305 17306 /* 17307 * Both vmlinux and module each have their own ".data..percpu" 17308 * DATASECs in BTF. So for module's case, we need to skip vmlinux BTF 17309 * types to look at only module's own BTF types. 17310 */ 17311 n = btf_nr_types(btf); 17312 if (btf_is_module(btf)) 17313 i = btf_nr_types(btf_vmlinux); 17314 else 17315 i = 1; 17316 17317 for(; i < n; i++) { 17318 t = btf_type_by_id(btf, i); 17319 if (BTF_INFO_KIND(t->info) != BTF_KIND_DATASEC) 17320 continue; 17321 17322 tname = btf_name_by_offset(btf, t->name_off); 17323 if (!strcmp(tname, ".data..percpu")) 17324 return i; 17325 } 17326 17327 return -ENOENT; 17328 } 17329 17330 /* replace pseudo btf_id with kernel symbol address */ 17331 static int check_pseudo_btf_id(struct bpf_verifier_env *env, 17332 struct bpf_insn *insn, 17333 struct bpf_insn_aux_data *aux) 17334 { 17335 const struct btf_var_secinfo *vsi; 17336 const struct btf_type *datasec; 17337 struct btf_mod_pair *btf_mod; 17338 const struct btf_type *t; 17339 const char *sym_name; 17340 bool percpu = false; 17341 u32 type, id = insn->imm; 17342 struct btf *btf; 17343 s32 datasec_id; 17344 u64 addr; 17345 int i, btf_fd, err; 17346 17347 btf_fd = insn[1].imm; 17348 if (btf_fd) { 17349 btf = btf_get_by_fd(btf_fd); 17350 if (IS_ERR(btf)) { 17351 verbose(env, "invalid module BTF object FD specified.\n"); 17352 return -EINVAL; 17353 } 17354 } else { 17355 if (!btf_vmlinux) { 17356 verbose(env, "kernel is missing BTF, make sure CONFIG_DEBUG_INFO_BTF=y is specified in Kconfig.\n"); 17357 return -EINVAL; 17358 } 17359 btf = btf_vmlinux; 17360 btf_get(btf); 17361 } 17362 17363 t = btf_type_by_id(btf, id); 17364 if (!t) { 17365 verbose(env, "ldimm64 insn specifies invalid btf_id %d.\n", id); 17366 err = -ENOENT; 17367 goto err_put; 17368 } 17369 17370 if (!btf_type_is_var(t) && !btf_type_is_func(t)) { 17371 verbose(env, "pseudo btf_id %d in ldimm64 isn't KIND_VAR or KIND_FUNC\n", id); 17372 err = -EINVAL; 17373 goto err_put; 17374 } 17375 17376 sym_name = btf_name_by_offset(btf, t->name_off); 17377 addr = kallsyms_lookup_name(sym_name); 17378 if (!addr) { 17379 verbose(env, "ldimm64 failed to find the address for kernel symbol '%s'.\n", 17380 sym_name); 17381 err = -ENOENT; 17382 goto err_put; 17383 } 17384 insn[0].imm = (u32)addr; 17385 insn[1].imm = addr >> 32; 17386 17387 if (btf_type_is_func(t)) { 17388 aux->btf_var.reg_type = PTR_TO_MEM | MEM_RDONLY; 17389 aux->btf_var.mem_size = 0; 17390 goto check_btf; 17391 } 17392 17393 datasec_id = find_btf_percpu_datasec(btf); 17394 if (datasec_id > 0) { 17395 datasec = btf_type_by_id(btf, datasec_id); 17396 for_each_vsi(i, datasec, vsi) { 17397 if (vsi->type == id) { 17398 percpu = true; 17399 break; 17400 } 17401 } 17402 } 17403 17404 type = t->type; 17405 t = btf_type_skip_modifiers(btf, type, NULL); 17406 if (percpu) { 17407 aux->btf_var.reg_type = PTR_TO_BTF_ID | MEM_PERCPU; 17408 aux->btf_var.btf = btf; 17409 aux->btf_var.btf_id = type; 17410 } else if (!btf_type_is_struct(t)) { 17411 const struct btf_type *ret; 17412 const char *tname; 17413 u32 tsize; 17414 17415 /* resolve the type size of ksym. */ 17416 ret = btf_resolve_size(btf, t, &tsize); 17417 if (IS_ERR(ret)) { 17418 tname = btf_name_by_offset(btf, t->name_off); 17419 verbose(env, "ldimm64 unable to resolve the size of type '%s': %ld\n", 17420 tname, PTR_ERR(ret)); 17421 err = -EINVAL; 17422 goto err_put; 17423 } 17424 aux->btf_var.reg_type = PTR_TO_MEM | MEM_RDONLY; 17425 aux->btf_var.mem_size = tsize; 17426 } else { 17427 aux->btf_var.reg_type = PTR_TO_BTF_ID; 17428 aux->btf_var.btf = btf; 17429 aux->btf_var.btf_id = type; 17430 } 17431 check_btf: 17432 /* check whether we recorded this BTF (and maybe module) already */ 17433 for (i = 0; i < env->used_btf_cnt; i++) { 17434 if (env->used_btfs[i].btf == btf) { 17435 btf_put(btf); 17436 return 0; 17437 } 17438 } 17439 17440 if (env->used_btf_cnt >= MAX_USED_BTFS) { 17441 err = -E2BIG; 17442 goto err_put; 17443 } 17444 17445 btf_mod = &env->used_btfs[env->used_btf_cnt]; 17446 btf_mod->btf = btf; 17447 btf_mod->module = NULL; 17448 17449 /* if we reference variables from kernel module, bump its refcount */ 17450 if (btf_is_module(btf)) { 17451 btf_mod->module = btf_try_get_module(btf); 17452 if (!btf_mod->module) { 17453 err = -ENXIO; 17454 goto err_put; 17455 } 17456 } 17457 17458 env->used_btf_cnt++; 17459 17460 return 0; 17461 err_put: 17462 btf_put(btf); 17463 return err; 17464 } 17465 17466 static bool is_tracing_prog_type(enum bpf_prog_type type) 17467 { 17468 switch (type) { 17469 case BPF_PROG_TYPE_KPROBE: 17470 case BPF_PROG_TYPE_TRACEPOINT: 17471 case BPF_PROG_TYPE_PERF_EVENT: 17472 case BPF_PROG_TYPE_RAW_TRACEPOINT: 17473 case BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE: 17474 return true; 17475 default: 17476 return false; 17477 } 17478 } 17479 17480 static int check_map_prog_compatibility(struct bpf_verifier_env *env, 17481 struct bpf_map *map, 17482 struct bpf_prog *prog) 17483 17484 { 17485 enum bpf_prog_type prog_type = resolve_prog_type(prog); 17486 17487 if (btf_record_has_field(map->record, BPF_LIST_HEAD) || 17488 btf_record_has_field(map->record, BPF_RB_ROOT)) { 17489 if (is_tracing_prog_type(prog_type)) { 17490 verbose(env, "tracing progs cannot use bpf_{list_head,rb_root} yet\n"); 17491 return -EINVAL; 17492 } 17493 } 17494 17495 if (btf_record_has_field(map->record, BPF_SPIN_LOCK)) { 17496 if (prog_type == BPF_PROG_TYPE_SOCKET_FILTER) { 17497 verbose(env, "socket filter progs cannot use bpf_spin_lock yet\n"); 17498 return -EINVAL; 17499 } 17500 17501 if (is_tracing_prog_type(prog_type)) { 17502 verbose(env, "tracing progs cannot use bpf_spin_lock yet\n"); 17503 return -EINVAL; 17504 } 17505 } 17506 17507 if (btf_record_has_field(map->record, BPF_TIMER)) { 17508 if (is_tracing_prog_type(prog_type)) { 17509 verbose(env, "tracing progs cannot use bpf_timer yet\n"); 17510 return -EINVAL; 17511 } 17512 } 17513 17514 if ((bpf_prog_is_offloaded(prog->aux) || bpf_map_is_offloaded(map)) && 17515 !bpf_offload_prog_map_match(prog, map)) { 17516 verbose(env, "offload device mismatch between prog and map\n"); 17517 return -EINVAL; 17518 } 17519 17520 if (map->map_type == BPF_MAP_TYPE_STRUCT_OPS) { 17521 verbose(env, "bpf_struct_ops map cannot be used in prog\n"); 17522 return -EINVAL; 17523 } 17524 17525 if (prog->aux->sleepable) 17526 switch (map->map_type) { 17527 case BPF_MAP_TYPE_HASH: 17528 case BPF_MAP_TYPE_LRU_HASH: 17529 case BPF_MAP_TYPE_ARRAY: 17530 case BPF_MAP_TYPE_PERCPU_HASH: 17531 case BPF_MAP_TYPE_PERCPU_ARRAY: 17532 case BPF_MAP_TYPE_LRU_PERCPU_HASH: 17533 case BPF_MAP_TYPE_ARRAY_OF_MAPS: 17534 case BPF_MAP_TYPE_HASH_OF_MAPS: 17535 case BPF_MAP_TYPE_RINGBUF: 17536 case BPF_MAP_TYPE_USER_RINGBUF: 17537 case BPF_MAP_TYPE_INODE_STORAGE: 17538 case BPF_MAP_TYPE_SK_STORAGE: 17539 case BPF_MAP_TYPE_TASK_STORAGE: 17540 case BPF_MAP_TYPE_CGRP_STORAGE: 17541 break; 17542 default: 17543 verbose(env, 17544 "Sleepable programs can only use array, hash, ringbuf and local storage maps\n"); 17545 return -EINVAL; 17546 } 17547 17548 return 0; 17549 } 17550 17551 static bool bpf_map_is_cgroup_storage(struct bpf_map *map) 17552 { 17553 return (map->map_type == BPF_MAP_TYPE_CGROUP_STORAGE || 17554 map->map_type == BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE); 17555 } 17556 17557 /* find and rewrite pseudo imm in ld_imm64 instructions: 17558 * 17559 * 1. if it accesses map FD, replace it with actual map pointer. 17560 * 2. if it accesses btf_id of a VAR, replace it with pointer to the var. 17561 * 17562 * NOTE: btf_vmlinux is required for converting pseudo btf_id. 17563 */ 17564 static int resolve_pseudo_ldimm64(struct bpf_verifier_env *env) 17565 { 17566 struct bpf_insn *insn = env->prog->insnsi; 17567 int insn_cnt = env->prog->len; 17568 int i, j, err; 17569 17570 err = bpf_prog_calc_tag(env->prog); 17571 if (err) 17572 return err; 17573 17574 for (i = 0; i < insn_cnt; i++, insn++) { 17575 if (BPF_CLASS(insn->code) == BPF_LDX && 17576 ((BPF_MODE(insn->code) != BPF_MEM && BPF_MODE(insn->code) != BPF_MEMSX) || 17577 insn->imm != 0)) { 17578 verbose(env, "BPF_LDX uses reserved fields\n"); 17579 return -EINVAL; 17580 } 17581 17582 if (insn[0].code == (BPF_LD | BPF_IMM | BPF_DW)) { 17583 struct bpf_insn_aux_data *aux; 17584 struct bpf_map *map; 17585 struct fd f; 17586 u64 addr; 17587 u32 fd; 17588 17589 if (i == insn_cnt - 1 || insn[1].code != 0 || 17590 insn[1].dst_reg != 0 || insn[1].src_reg != 0 || 17591 insn[1].off != 0) { 17592 verbose(env, "invalid bpf_ld_imm64 insn\n"); 17593 return -EINVAL; 17594 } 17595 17596 if (insn[0].src_reg == 0) 17597 /* valid generic load 64-bit imm */ 17598 goto next_insn; 17599 17600 if (insn[0].src_reg == BPF_PSEUDO_BTF_ID) { 17601 aux = &env->insn_aux_data[i]; 17602 err = check_pseudo_btf_id(env, insn, aux); 17603 if (err) 17604 return err; 17605 goto next_insn; 17606 } 17607 17608 if (insn[0].src_reg == BPF_PSEUDO_FUNC) { 17609 aux = &env->insn_aux_data[i]; 17610 aux->ptr_type = PTR_TO_FUNC; 17611 goto next_insn; 17612 } 17613 17614 /* In final convert_pseudo_ld_imm64() step, this is 17615 * converted into regular 64-bit imm load insn. 17616 */ 17617 switch (insn[0].src_reg) { 17618 case BPF_PSEUDO_MAP_VALUE: 17619 case BPF_PSEUDO_MAP_IDX_VALUE: 17620 break; 17621 case BPF_PSEUDO_MAP_FD: 17622 case BPF_PSEUDO_MAP_IDX: 17623 if (insn[1].imm == 0) 17624 break; 17625 fallthrough; 17626 default: 17627 verbose(env, "unrecognized bpf_ld_imm64 insn\n"); 17628 return -EINVAL; 17629 } 17630 17631 switch (insn[0].src_reg) { 17632 case BPF_PSEUDO_MAP_IDX_VALUE: 17633 case BPF_PSEUDO_MAP_IDX: 17634 if (bpfptr_is_null(env->fd_array)) { 17635 verbose(env, "fd_idx without fd_array is invalid\n"); 17636 return -EPROTO; 17637 } 17638 if (copy_from_bpfptr_offset(&fd, env->fd_array, 17639 insn[0].imm * sizeof(fd), 17640 sizeof(fd))) 17641 return -EFAULT; 17642 break; 17643 default: 17644 fd = insn[0].imm; 17645 break; 17646 } 17647 17648 f = fdget(fd); 17649 map = __bpf_map_get(f); 17650 if (IS_ERR(map)) { 17651 verbose(env, "fd %d is not pointing to valid bpf_map\n", fd); 17652 return PTR_ERR(map); 17653 } 17654 17655 err = check_map_prog_compatibility(env, map, env->prog); 17656 if (err) { 17657 fdput(f); 17658 return err; 17659 } 17660 17661 aux = &env->insn_aux_data[i]; 17662 if (insn[0].src_reg == BPF_PSEUDO_MAP_FD || 17663 insn[0].src_reg == BPF_PSEUDO_MAP_IDX) { 17664 addr = (unsigned long)map; 17665 } else { 17666 u32 off = insn[1].imm; 17667 17668 if (off >= BPF_MAX_VAR_OFF) { 17669 verbose(env, "direct value offset of %u is not allowed\n", off); 17670 fdput(f); 17671 return -EINVAL; 17672 } 17673 17674 if (!map->ops->map_direct_value_addr) { 17675 verbose(env, "no direct value access support for this map type\n"); 17676 fdput(f); 17677 return -EINVAL; 17678 } 17679 17680 err = map->ops->map_direct_value_addr(map, &addr, off); 17681 if (err) { 17682 verbose(env, "invalid access to map value pointer, value_size=%u off=%u\n", 17683 map->value_size, off); 17684 fdput(f); 17685 return err; 17686 } 17687 17688 aux->map_off = off; 17689 addr += off; 17690 } 17691 17692 insn[0].imm = (u32)addr; 17693 insn[1].imm = addr >> 32; 17694 17695 /* check whether we recorded this map already */ 17696 for (j = 0; j < env->used_map_cnt; j++) { 17697 if (env->used_maps[j] == map) { 17698 aux->map_index = j; 17699 fdput(f); 17700 goto next_insn; 17701 } 17702 } 17703 17704 if (env->used_map_cnt >= MAX_USED_MAPS) { 17705 fdput(f); 17706 return -E2BIG; 17707 } 17708 17709 if (env->prog->aux->sleepable) 17710 atomic64_inc(&map->sleepable_refcnt); 17711 /* hold the map. If the program is rejected by verifier, 17712 * the map will be released by release_maps() or it 17713 * will be used by the valid program until it's unloaded 17714 * and all maps are released in bpf_free_used_maps() 17715 */ 17716 bpf_map_inc(map); 17717 17718 aux->map_index = env->used_map_cnt; 17719 env->used_maps[env->used_map_cnt++] = map; 17720 17721 if (bpf_map_is_cgroup_storage(map) && 17722 bpf_cgroup_storage_assign(env->prog->aux, map)) { 17723 verbose(env, "only one cgroup storage of each type is allowed\n"); 17724 fdput(f); 17725 return -EBUSY; 17726 } 17727 17728 fdput(f); 17729 next_insn: 17730 insn++; 17731 i++; 17732 continue; 17733 } 17734 17735 /* Basic sanity check before we invest more work here. */ 17736 if (!bpf_opcode_in_insntable(insn->code)) { 17737 verbose(env, "unknown opcode %02x\n", insn->code); 17738 return -EINVAL; 17739 } 17740 } 17741 17742 /* now all pseudo BPF_LD_IMM64 instructions load valid 17743 * 'struct bpf_map *' into a register instead of user map_fd. 17744 * These pointers will be used later by verifier to validate map access. 17745 */ 17746 return 0; 17747 } 17748 17749 /* drop refcnt of maps used by the rejected program */ 17750 static void release_maps(struct bpf_verifier_env *env) 17751 { 17752 __bpf_free_used_maps(env->prog->aux, env->used_maps, 17753 env->used_map_cnt); 17754 } 17755 17756 /* drop refcnt of maps used by the rejected program */ 17757 static void release_btfs(struct bpf_verifier_env *env) 17758 { 17759 __bpf_free_used_btfs(env->prog->aux, env->used_btfs, 17760 env->used_btf_cnt); 17761 } 17762 17763 /* convert pseudo BPF_LD_IMM64 into generic BPF_LD_IMM64 */ 17764 static void convert_pseudo_ld_imm64(struct bpf_verifier_env *env) 17765 { 17766 struct bpf_insn *insn = env->prog->insnsi; 17767 int insn_cnt = env->prog->len; 17768 int i; 17769 17770 for (i = 0; i < insn_cnt; i++, insn++) { 17771 if (insn->code != (BPF_LD | BPF_IMM | BPF_DW)) 17772 continue; 17773 if (insn->src_reg == BPF_PSEUDO_FUNC) 17774 continue; 17775 insn->src_reg = 0; 17776 } 17777 } 17778 17779 /* single env->prog->insni[off] instruction was replaced with the range 17780 * insni[off, off + cnt). Adjust corresponding insn_aux_data by copying 17781 * [0, off) and [off, end) to new locations, so the patched range stays zero 17782 */ 17783 static void adjust_insn_aux_data(struct bpf_verifier_env *env, 17784 struct bpf_insn_aux_data *new_data, 17785 struct bpf_prog *new_prog, u32 off, u32 cnt) 17786 { 17787 struct bpf_insn_aux_data *old_data = env->insn_aux_data; 17788 struct bpf_insn *insn = new_prog->insnsi; 17789 u32 old_seen = old_data[off].seen; 17790 u32 prog_len; 17791 int i; 17792 17793 /* aux info at OFF always needs adjustment, no matter fast path 17794 * (cnt == 1) is taken or not. There is no guarantee INSN at OFF is the 17795 * original insn at old prog. 17796 */ 17797 old_data[off].zext_dst = insn_has_def32(env, insn + off + cnt - 1); 17798 17799 if (cnt == 1) 17800 return; 17801 prog_len = new_prog->len; 17802 17803 memcpy(new_data, old_data, sizeof(struct bpf_insn_aux_data) * off); 17804 memcpy(new_data + off + cnt - 1, old_data + off, 17805 sizeof(struct bpf_insn_aux_data) * (prog_len - off - cnt + 1)); 17806 for (i = off; i < off + cnt - 1; i++) { 17807 /* Expand insni[off]'s seen count to the patched range. */ 17808 new_data[i].seen = old_seen; 17809 new_data[i].zext_dst = insn_has_def32(env, insn + i); 17810 } 17811 env->insn_aux_data = new_data; 17812 vfree(old_data); 17813 } 17814 17815 static void adjust_subprog_starts(struct bpf_verifier_env *env, u32 off, u32 len) 17816 { 17817 int i; 17818 17819 if (len == 1) 17820 return; 17821 /* NOTE: fake 'exit' subprog should be updated as well. */ 17822 for (i = 0; i <= env->subprog_cnt; i++) { 17823 if (env->subprog_info[i].start <= off) 17824 continue; 17825 env->subprog_info[i].start += len - 1; 17826 } 17827 } 17828 17829 static void adjust_poke_descs(struct bpf_prog *prog, u32 off, u32 len) 17830 { 17831 struct bpf_jit_poke_descriptor *tab = prog->aux->poke_tab; 17832 int i, sz = prog->aux->size_poke_tab; 17833 struct bpf_jit_poke_descriptor *desc; 17834 17835 for (i = 0; i < sz; i++) { 17836 desc = &tab[i]; 17837 if (desc->insn_idx <= off) 17838 continue; 17839 desc->insn_idx += len - 1; 17840 } 17841 } 17842 17843 static struct bpf_prog *bpf_patch_insn_data(struct bpf_verifier_env *env, u32 off, 17844 const struct bpf_insn *patch, u32 len) 17845 { 17846 struct bpf_prog *new_prog; 17847 struct bpf_insn_aux_data *new_data = NULL; 17848 17849 if (len > 1) { 17850 new_data = vzalloc(array_size(env->prog->len + len - 1, 17851 sizeof(struct bpf_insn_aux_data))); 17852 if (!new_data) 17853 return NULL; 17854 } 17855 17856 new_prog = bpf_patch_insn_single(env->prog, off, patch, len); 17857 if (IS_ERR(new_prog)) { 17858 if (PTR_ERR(new_prog) == -ERANGE) 17859 verbose(env, 17860 "insn %d cannot be patched due to 16-bit range\n", 17861 env->insn_aux_data[off].orig_idx); 17862 vfree(new_data); 17863 return NULL; 17864 } 17865 adjust_insn_aux_data(env, new_data, new_prog, off, len); 17866 adjust_subprog_starts(env, off, len); 17867 adjust_poke_descs(new_prog, off, len); 17868 return new_prog; 17869 } 17870 17871 static int adjust_subprog_starts_after_remove(struct bpf_verifier_env *env, 17872 u32 off, u32 cnt) 17873 { 17874 int i, j; 17875 17876 /* find first prog starting at or after off (first to remove) */ 17877 for (i = 0; i < env->subprog_cnt; i++) 17878 if (env->subprog_info[i].start >= off) 17879 break; 17880 /* find first prog starting at or after off + cnt (first to stay) */ 17881 for (j = i; j < env->subprog_cnt; j++) 17882 if (env->subprog_info[j].start >= off + cnt) 17883 break; 17884 /* if j doesn't start exactly at off + cnt, we are just removing 17885 * the front of previous prog 17886 */ 17887 if (env->subprog_info[j].start != off + cnt) 17888 j--; 17889 17890 if (j > i) { 17891 struct bpf_prog_aux *aux = env->prog->aux; 17892 int move; 17893 17894 /* move fake 'exit' subprog as well */ 17895 move = env->subprog_cnt + 1 - j; 17896 17897 memmove(env->subprog_info + i, 17898 env->subprog_info + j, 17899 sizeof(*env->subprog_info) * move); 17900 env->subprog_cnt -= j - i; 17901 17902 /* remove func_info */ 17903 if (aux->func_info) { 17904 move = aux->func_info_cnt - j; 17905 17906 memmove(aux->func_info + i, 17907 aux->func_info + j, 17908 sizeof(*aux->func_info) * move); 17909 aux->func_info_cnt -= j - i; 17910 /* func_info->insn_off is set after all code rewrites, 17911 * in adjust_btf_func() - no need to adjust 17912 */ 17913 } 17914 } else { 17915 /* convert i from "first prog to remove" to "first to adjust" */ 17916 if (env->subprog_info[i].start == off) 17917 i++; 17918 } 17919 17920 /* update fake 'exit' subprog as well */ 17921 for (; i <= env->subprog_cnt; i++) 17922 env->subprog_info[i].start -= cnt; 17923 17924 return 0; 17925 } 17926 17927 static int bpf_adj_linfo_after_remove(struct bpf_verifier_env *env, u32 off, 17928 u32 cnt) 17929 { 17930 struct bpf_prog *prog = env->prog; 17931 u32 i, l_off, l_cnt, nr_linfo; 17932 struct bpf_line_info *linfo; 17933 17934 nr_linfo = prog->aux->nr_linfo; 17935 if (!nr_linfo) 17936 return 0; 17937 17938 linfo = prog->aux->linfo; 17939 17940 /* find first line info to remove, count lines to be removed */ 17941 for (i = 0; i < nr_linfo; i++) 17942 if (linfo[i].insn_off >= off) 17943 break; 17944 17945 l_off = i; 17946 l_cnt = 0; 17947 for (; i < nr_linfo; i++) 17948 if (linfo[i].insn_off < off + cnt) 17949 l_cnt++; 17950 else 17951 break; 17952 17953 /* First live insn doesn't match first live linfo, it needs to "inherit" 17954 * last removed linfo. prog is already modified, so prog->len == off 17955 * means no live instructions after (tail of the program was removed). 17956 */ 17957 if (prog->len != off && l_cnt && 17958 (i == nr_linfo || linfo[i].insn_off != off + cnt)) { 17959 l_cnt--; 17960 linfo[--i].insn_off = off + cnt; 17961 } 17962 17963 /* remove the line info which refer to the removed instructions */ 17964 if (l_cnt) { 17965 memmove(linfo + l_off, linfo + i, 17966 sizeof(*linfo) * (nr_linfo - i)); 17967 17968 prog->aux->nr_linfo -= l_cnt; 17969 nr_linfo = prog->aux->nr_linfo; 17970 } 17971 17972 /* pull all linfo[i].insn_off >= off + cnt in by cnt */ 17973 for (i = l_off; i < nr_linfo; i++) 17974 linfo[i].insn_off -= cnt; 17975 17976 /* fix up all subprogs (incl. 'exit') which start >= off */ 17977 for (i = 0; i <= env->subprog_cnt; i++) 17978 if (env->subprog_info[i].linfo_idx > l_off) { 17979 /* program may have started in the removed region but 17980 * may not be fully removed 17981 */ 17982 if (env->subprog_info[i].linfo_idx >= l_off + l_cnt) 17983 env->subprog_info[i].linfo_idx -= l_cnt; 17984 else 17985 env->subprog_info[i].linfo_idx = l_off; 17986 } 17987 17988 return 0; 17989 } 17990 17991 static int verifier_remove_insns(struct bpf_verifier_env *env, u32 off, u32 cnt) 17992 { 17993 struct bpf_insn_aux_data *aux_data = env->insn_aux_data; 17994 unsigned int orig_prog_len = env->prog->len; 17995 int err; 17996 17997 if (bpf_prog_is_offloaded(env->prog->aux)) 17998 bpf_prog_offload_remove_insns(env, off, cnt); 17999 18000 err = bpf_remove_insns(env->prog, off, cnt); 18001 if (err) 18002 return err; 18003 18004 err = adjust_subprog_starts_after_remove(env, off, cnt); 18005 if (err) 18006 return err; 18007 18008 err = bpf_adj_linfo_after_remove(env, off, cnt); 18009 if (err) 18010 return err; 18011 18012 memmove(aux_data + off, aux_data + off + cnt, 18013 sizeof(*aux_data) * (orig_prog_len - off - cnt)); 18014 18015 return 0; 18016 } 18017 18018 /* The verifier does more data flow analysis than llvm and will not 18019 * explore branches that are dead at run time. Malicious programs can 18020 * have dead code too. Therefore replace all dead at-run-time code 18021 * with 'ja -1'. 18022 * 18023 * Just nops are not optimal, e.g. if they would sit at the end of the 18024 * program and through another bug we would manage to jump there, then 18025 * we'd execute beyond program memory otherwise. Returning exception 18026 * code also wouldn't work since we can have subprogs where the dead 18027 * code could be located. 18028 */ 18029 static void sanitize_dead_code(struct bpf_verifier_env *env) 18030 { 18031 struct bpf_insn_aux_data *aux_data = env->insn_aux_data; 18032 struct bpf_insn trap = BPF_JMP_IMM(BPF_JA, 0, 0, -1); 18033 struct bpf_insn *insn = env->prog->insnsi; 18034 const int insn_cnt = env->prog->len; 18035 int i; 18036 18037 for (i = 0; i < insn_cnt; i++) { 18038 if (aux_data[i].seen) 18039 continue; 18040 memcpy(insn + i, &trap, sizeof(trap)); 18041 aux_data[i].zext_dst = false; 18042 } 18043 } 18044 18045 static bool insn_is_cond_jump(u8 code) 18046 { 18047 u8 op; 18048 18049 op = BPF_OP(code); 18050 if (BPF_CLASS(code) == BPF_JMP32) 18051 return op != BPF_JA; 18052 18053 if (BPF_CLASS(code) != BPF_JMP) 18054 return false; 18055 18056 return op != BPF_JA && op != BPF_EXIT && op != BPF_CALL; 18057 } 18058 18059 static void opt_hard_wire_dead_code_branches(struct bpf_verifier_env *env) 18060 { 18061 struct bpf_insn_aux_data *aux_data = env->insn_aux_data; 18062 struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0); 18063 struct bpf_insn *insn = env->prog->insnsi; 18064 const int insn_cnt = env->prog->len; 18065 int i; 18066 18067 for (i = 0; i < insn_cnt; i++, insn++) { 18068 if (!insn_is_cond_jump(insn->code)) 18069 continue; 18070 18071 if (!aux_data[i + 1].seen) 18072 ja.off = insn->off; 18073 else if (!aux_data[i + 1 + insn->off].seen) 18074 ja.off = 0; 18075 else 18076 continue; 18077 18078 if (bpf_prog_is_offloaded(env->prog->aux)) 18079 bpf_prog_offload_replace_insn(env, i, &ja); 18080 18081 memcpy(insn, &ja, sizeof(ja)); 18082 } 18083 } 18084 18085 static int opt_remove_dead_code(struct bpf_verifier_env *env) 18086 { 18087 struct bpf_insn_aux_data *aux_data = env->insn_aux_data; 18088 int insn_cnt = env->prog->len; 18089 int i, err; 18090 18091 for (i = 0; i < insn_cnt; i++) { 18092 int j; 18093 18094 j = 0; 18095 while (i + j < insn_cnt && !aux_data[i + j].seen) 18096 j++; 18097 if (!j) 18098 continue; 18099 18100 err = verifier_remove_insns(env, i, j); 18101 if (err) 18102 return err; 18103 insn_cnt = env->prog->len; 18104 } 18105 18106 return 0; 18107 } 18108 18109 static int opt_remove_nops(struct bpf_verifier_env *env) 18110 { 18111 const struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0); 18112 struct bpf_insn *insn = env->prog->insnsi; 18113 int insn_cnt = env->prog->len; 18114 int i, err; 18115 18116 for (i = 0; i < insn_cnt; i++) { 18117 if (memcmp(&insn[i], &ja, sizeof(ja))) 18118 continue; 18119 18120 err = verifier_remove_insns(env, i, 1); 18121 if (err) 18122 return err; 18123 insn_cnt--; 18124 i--; 18125 } 18126 18127 return 0; 18128 } 18129 18130 static int opt_subreg_zext_lo32_rnd_hi32(struct bpf_verifier_env *env, 18131 const union bpf_attr *attr) 18132 { 18133 struct bpf_insn *patch, zext_patch[2], rnd_hi32_patch[4]; 18134 struct bpf_insn_aux_data *aux = env->insn_aux_data; 18135 int i, patch_len, delta = 0, len = env->prog->len; 18136 struct bpf_insn *insns = env->prog->insnsi; 18137 struct bpf_prog *new_prog; 18138 bool rnd_hi32; 18139 18140 rnd_hi32 = attr->prog_flags & BPF_F_TEST_RND_HI32; 18141 zext_patch[1] = BPF_ZEXT_REG(0); 18142 rnd_hi32_patch[1] = BPF_ALU64_IMM(BPF_MOV, BPF_REG_AX, 0); 18143 rnd_hi32_patch[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_AX, 32); 18144 rnd_hi32_patch[3] = BPF_ALU64_REG(BPF_OR, 0, BPF_REG_AX); 18145 for (i = 0; i < len; i++) { 18146 int adj_idx = i + delta; 18147 struct bpf_insn insn; 18148 int load_reg; 18149 18150 insn = insns[adj_idx]; 18151 load_reg = insn_def_regno(&insn); 18152 if (!aux[adj_idx].zext_dst) { 18153 u8 code, class; 18154 u32 imm_rnd; 18155 18156 if (!rnd_hi32) 18157 continue; 18158 18159 code = insn.code; 18160 class = BPF_CLASS(code); 18161 if (load_reg == -1) 18162 continue; 18163 18164 /* NOTE: arg "reg" (the fourth one) is only used for 18165 * BPF_STX + SRC_OP, so it is safe to pass NULL 18166 * here. 18167 */ 18168 if (is_reg64(env, &insn, load_reg, NULL, DST_OP)) { 18169 if (class == BPF_LD && 18170 BPF_MODE(code) == BPF_IMM) 18171 i++; 18172 continue; 18173 } 18174 18175 /* ctx load could be transformed into wider load. */ 18176 if (class == BPF_LDX && 18177 aux[adj_idx].ptr_type == PTR_TO_CTX) 18178 continue; 18179 18180 imm_rnd = get_random_u32(); 18181 rnd_hi32_patch[0] = insn; 18182 rnd_hi32_patch[1].imm = imm_rnd; 18183 rnd_hi32_patch[3].dst_reg = load_reg; 18184 patch = rnd_hi32_patch; 18185 patch_len = 4; 18186 goto apply_patch_buffer; 18187 } 18188 18189 /* Add in an zero-extend instruction if a) the JIT has requested 18190 * it or b) it's a CMPXCHG. 18191 * 18192 * The latter is because: BPF_CMPXCHG always loads a value into 18193 * R0, therefore always zero-extends. However some archs' 18194 * equivalent instruction only does this load when the 18195 * comparison is successful. This detail of CMPXCHG is 18196 * orthogonal to the general zero-extension behaviour of the 18197 * CPU, so it's treated independently of bpf_jit_needs_zext. 18198 */ 18199 if (!bpf_jit_needs_zext() && !is_cmpxchg_insn(&insn)) 18200 continue; 18201 18202 /* Zero-extension is done by the caller. */ 18203 if (bpf_pseudo_kfunc_call(&insn)) 18204 continue; 18205 18206 if (WARN_ON(load_reg == -1)) { 18207 verbose(env, "verifier bug. zext_dst is set, but no reg is defined\n"); 18208 return -EFAULT; 18209 } 18210 18211 zext_patch[0] = insn; 18212 zext_patch[1].dst_reg = load_reg; 18213 zext_patch[1].src_reg = load_reg; 18214 patch = zext_patch; 18215 patch_len = 2; 18216 apply_patch_buffer: 18217 new_prog = bpf_patch_insn_data(env, adj_idx, patch, patch_len); 18218 if (!new_prog) 18219 return -ENOMEM; 18220 env->prog = new_prog; 18221 insns = new_prog->insnsi; 18222 aux = env->insn_aux_data; 18223 delta += patch_len - 1; 18224 } 18225 18226 return 0; 18227 } 18228 18229 /* convert load instructions that access fields of a context type into a 18230 * sequence of instructions that access fields of the underlying structure: 18231 * struct __sk_buff -> struct sk_buff 18232 * struct bpf_sock_ops -> struct sock 18233 */ 18234 static int convert_ctx_accesses(struct bpf_verifier_env *env) 18235 { 18236 const struct bpf_verifier_ops *ops = env->ops; 18237 int i, cnt, size, ctx_field_size, delta = 0; 18238 const int insn_cnt = env->prog->len; 18239 struct bpf_insn insn_buf[16], *insn; 18240 u32 target_size, size_default, off; 18241 struct bpf_prog *new_prog; 18242 enum bpf_access_type type; 18243 bool is_narrower_load; 18244 18245 if (ops->gen_prologue || env->seen_direct_write) { 18246 if (!ops->gen_prologue) { 18247 verbose(env, "bpf verifier is misconfigured\n"); 18248 return -EINVAL; 18249 } 18250 cnt = ops->gen_prologue(insn_buf, env->seen_direct_write, 18251 env->prog); 18252 if (cnt >= ARRAY_SIZE(insn_buf)) { 18253 verbose(env, "bpf verifier is misconfigured\n"); 18254 return -EINVAL; 18255 } else if (cnt) { 18256 new_prog = bpf_patch_insn_data(env, 0, insn_buf, cnt); 18257 if (!new_prog) 18258 return -ENOMEM; 18259 18260 env->prog = new_prog; 18261 delta += cnt - 1; 18262 } 18263 } 18264 18265 if (bpf_prog_is_offloaded(env->prog->aux)) 18266 return 0; 18267 18268 insn = env->prog->insnsi + delta; 18269 18270 for (i = 0; i < insn_cnt; i++, insn++) { 18271 bpf_convert_ctx_access_t convert_ctx_access; 18272 u8 mode; 18273 18274 if (insn->code == (BPF_LDX | BPF_MEM | BPF_B) || 18275 insn->code == (BPF_LDX | BPF_MEM | BPF_H) || 18276 insn->code == (BPF_LDX | BPF_MEM | BPF_W) || 18277 insn->code == (BPF_LDX | BPF_MEM | BPF_DW) || 18278 insn->code == (BPF_LDX | BPF_MEMSX | BPF_B) || 18279 insn->code == (BPF_LDX | BPF_MEMSX | BPF_H) || 18280 insn->code == (BPF_LDX | BPF_MEMSX | BPF_W)) { 18281 type = BPF_READ; 18282 } else if (insn->code == (BPF_STX | BPF_MEM | BPF_B) || 18283 insn->code == (BPF_STX | BPF_MEM | BPF_H) || 18284 insn->code == (BPF_STX | BPF_MEM | BPF_W) || 18285 insn->code == (BPF_STX | BPF_MEM | BPF_DW) || 18286 insn->code == (BPF_ST | BPF_MEM | BPF_B) || 18287 insn->code == (BPF_ST | BPF_MEM | BPF_H) || 18288 insn->code == (BPF_ST | BPF_MEM | BPF_W) || 18289 insn->code == (BPF_ST | BPF_MEM | BPF_DW)) { 18290 type = BPF_WRITE; 18291 } else { 18292 continue; 18293 } 18294 18295 if (type == BPF_WRITE && 18296 env->insn_aux_data[i + delta].sanitize_stack_spill) { 18297 struct bpf_insn patch[] = { 18298 *insn, 18299 BPF_ST_NOSPEC(), 18300 }; 18301 18302 cnt = ARRAY_SIZE(patch); 18303 new_prog = bpf_patch_insn_data(env, i + delta, patch, cnt); 18304 if (!new_prog) 18305 return -ENOMEM; 18306 18307 delta += cnt - 1; 18308 env->prog = new_prog; 18309 insn = new_prog->insnsi + i + delta; 18310 continue; 18311 } 18312 18313 switch ((int)env->insn_aux_data[i + delta].ptr_type) { 18314 case PTR_TO_CTX: 18315 if (!ops->convert_ctx_access) 18316 continue; 18317 convert_ctx_access = ops->convert_ctx_access; 18318 break; 18319 case PTR_TO_SOCKET: 18320 case PTR_TO_SOCK_COMMON: 18321 convert_ctx_access = bpf_sock_convert_ctx_access; 18322 break; 18323 case PTR_TO_TCP_SOCK: 18324 convert_ctx_access = bpf_tcp_sock_convert_ctx_access; 18325 break; 18326 case PTR_TO_XDP_SOCK: 18327 convert_ctx_access = bpf_xdp_sock_convert_ctx_access; 18328 break; 18329 case PTR_TO_BTF_ID: 18330 case PTR_TO_BTF_ID | PTR_UNTRUSTED: 18331 /* PTR_TO_BTF_ID | MEM_ALLOC always has a valid lifetime, unlike 18332 * PTR_TO_BTF_ID, and an active ref_obj_id, but the same cannot 18333 * be said once it is marked PTR_UNTRUSTED, hence we must handle 18334 * any faults for loads into such types. BPF_WRITE is disallowed 18335 * for this case. 18336 */ 18337 case PTR_TO_BTF_ID | MEM_ALLOC | PTR_UNTRUSTED: 18338 if (type == BPF_READ) { 18339 if (BPF_MODE(insn->code) == BPF_MEM) 18340 insn->code = BPF_LDX | BPF_PROBE_MEM | 18341 BPF_SIZE((insn)->code); 18342 else 18343 insn->code = BPF_LDX | BPF_PROBE_MEMSX | 18344 BPF_SIZE((insn)->code); 18345 env->prog->aux->num_exentries++; 18346 } 18347 continue; 18348 default: 18349 continue; 18350 } 18351 18352 ctx_field_size = env->insn_aux_data[i + delta].ctx_field_size; 18353 size = BPF_LDST_BYTES(insn); 18354 mode = BPF_MODE(insn->code); 18355 18356 /* If the read access is a narrower load of the field, 18357 * convert to a 4/8-byte load, to minimum program type specific 18358 * convert_ctx_access changes. If conversion is successful, 18359 * we will apply proper mask to the result. 18360 */ 18361 is_narrower_load = size < ctx_field_size; 18362 size_default = bpf_ctx_off_adjust_machine(ctx_field_size); 18363 off = insn->off; 18364 if (is_narrower_load) { 18365 u8 size_code; 18366 18367 if (type == BPF_WRITE) { 18368 verbose(env, "bpf verifier narrow ctx access misconfigured\n"); 18369 return -EINVAL; 18370 } 18371 18372 size_code = BPF_H; 18373 if (ctx_field_size == 4) 18374 size_code = BPF_W; 18375 else if (ctx_field_size == 8) 18376 size_code = BPF_DW; 18377 18378 insn->off = off & ~(size_default - 1); 18379 insn->code = BPF_LDX | BPF_MEM | size_code; 18380 } 18381 18382 target_size = 0; 18383 cnt = convert_ctx_access(type, insn, insn_buf, env->prog, 18384 &target_size); 18385 if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf) || 18386 (ctx_field_size && !target_size)) { 18387 verbose(env, "bpf verifier is misconfigured\n"); 18388 return -EINVAL; 18389 } 18390 18391 if (is_narrower_load && size < target_size) { 18392 u8 shift = bpf_ctx_narrow_access_offset( 18393 off, size, size_default) * 8; 18394 if (shift && cnt + 1 >= ARRAY_SIZE(insn_buf)) { 18395 verbose(env, "bpf verifier narrow ctx load misconfigured\n"); 18396 return -EINVAL; 18397 } 18398 if (ctx_field_size <= 4) { 18399 if (shift) 18400 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_RSH, 18401 insn->dst_reg, 18402 shift); 18403 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg, 18404 (1 << size * 8) - 1); 18405 } else { 18406 if (shift) 18407 insn_buf[cnt++] = BPF_ALU64_IMM(BPF_RSH, 18408 insn->dst_reg, 18409 shift); 18410 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg, 18411 (1ULL << size * 8) - 1); 18412 } 18413 } 18414 if (mode == BPF_MEMSX) 18415 insn_buf[cnt++] = BPF_RAW_INSN(BPF_ALU64 | BPF_MOV | BPF_X, 18416 insn->dst_reg, insn->dst_reg, 18417 size * 8, 0); 18418 18419 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 18420 if (!new_prog) 18421 return -ENOMEM; 18422 18423 delta += cnt - 1; 18424 18425 /* keep walking new program and skip insns we just inserted */ 18426 env->prog = new_prog; 18427 insn = new_prog->insnsi + i + delta; 18428 } 18429 18430 return 0; 18431 } 18432 18433 static int jit_subprogs(struct bpf_verifier_env *env) 18434 { 18435 struct bpf_prog *prog = env->prog, **func, *tmp; 18436 int i, j, subprog_start, subprog_end = 0, len, subprog; 18437 struct bpf_map *map_ptr; 18438 struct bpf_insn *insn; 18439 void *old_bpf_func; 18440 int err, num_exentries; 18441 18442 if (env->subprog_cnt <= 1) 18443 return 0; 18444 18445 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) { 18446 if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn)) 18447 continue; 18448 18449 /* Upon error here we cannot fall back to interpreter but 18450 * need a hard reject of the program. Thus -EFAULT is 18451 * propagated in any case. 18452 */ 18453 subprog = find_subprog(env, i + insn->imm + 1); 18454 if (subprog < 0) { 18455 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n", 18456 i + insn->imm + 1); 18457 return -EFAULT; 18458 } 18459 /* temporarily remember subprog id inside insn instead of 18460 * aux_data, since next loop will split up all insns into funcs 18461 */ 18462 insn->off = subprog; 18463 /* remember original imm in case JIT fails and fallback 18464 * to interpreter will be needed 18465 */ 18466 env->insn_aux_data[i].call_imm = insn->imm; 18467 /* point imm to __bpf_call_base+1 from JITs point of view */ 18468 insn->imm = 1; 18469 if (bpf_pseudo_func(insn)) 18470 /* jit (e.g. x86_64) may emit fewer instructions 18471 * if it learns a u32 imm is the same as a u64 imm. 18472 * Force a non zero here. 18473 */ 18474 insn[1].imm = 1; 18475 } 18476 18477 err = bpf_prog_alloc_jited_linfo(prog); 18478 if (err) 18479 goto out_undo_insn; 18480 18481 err = -ENOMEM; 18482 func = kcalloc(env->subprog_cnt, sizeof(prog), GFP_KERNEL); 18483 if (!func) 18484 goto out_undo_insn; 18485 18486 for (i = 0; i < env->subprog_cnt; i++) { 18487 subprog_start = subprog_end; 18488 subprog_end = env->subprog_info[i + 1].start; 18489 18490 len = subprog_end - subprog_start; 18491 /* bpf_prog_run() doesn't call subprogs directly, 18492 * hence main prog stats include the runtime of subprogs. 18493 * subprogs don't have IDs and not reachable via prog_get_next_id 18494 * func[i]->stats will never be accessed and stays NULL 18495 */ 18496 func[i] = bpf_prog_alloc_no_stats(bpf_prog_size(len), GFP_USER); 18497 if (!func[i]) 18498 goto out_free; 18499 memcpy(func[i]->insnsi, &prog->insnsi[subprog_start], 18500 len * sizeof(struct bpf_insn)); 18501 func[i]->type = prog->type; 18502 func[i]->len = len; 18503 if (bpf_prog_calc_tag(func[i])) 18504 goto out_free; 18505 func[i]->is_func = 1; 18506 func[i]->aux->func_idx = i; 18507 /* Below members will be freed only at prog->aux */ 18508 func[i]->aux->btf = prog->aux->btf; 18509 func[i]->aux->func_info = prog->aux->func_info; 18510 func[i]->aux->func_info_cnt = prog->aux->func_info_cnt; 18511 func[i]->aux->poke_tab = prog->aux->poke_tab; 18512 func[i]->aux->size_poke_tab = prog->aux->size_poke_tab; 18513 18514 for (j = 0; j < prog->aux->size_poke_tab; j++) { 18515 struct bpf_jit_poke_descriptor *poke; 18516 18517 poke = &prog->aux->poke_tab[j]; 18518 if (poke->insn_idx < subprog_end && 18519 poke->insn_idx >= subprog_start) 18520 poke->aux = func[i]->aux; 18521 } 18522 18523 func[i]->aux->name[0] = 'F'; 18524 func[i]->aux->stack_depth = env->subprog_info[i].stack_depth; 18525 func[i]->jit_requested = 1; 18526 func[i]->blinding_requested = prog->blinding_requested; 18527 func[i]->aux->kfunc_tab = prog->aux->kfunc_tab; 18528 func[i]->aux->kfunc_btf_tab = prog->aux->kfunc_btf_tab; 18529 func[i]->aux->linfo = prog->aux->linfo; 18530 func[i]->aux->nr_linfo = prog->aux->nr_linfo; 18531 func[i]->aux->jited_linfo = prog->aux->jited_linfo; 18532 func[i]->aux->linfo_idx = env->subprog_info[i].linfo_idx; 18533 num_exentries = 0; 18534 insn = func[i]->insnsi; 18535 for (j = 0; j < func[i]->len; j++, insn++) { 18536 if (BPF_CLASS(insn->code) == BPF_LDX && 18537 (BPF_MODE(insn->code) == BPF_PROBE_MEM || 18538 BPF_MODE(insn->code) == BPF_PROBE_MEMSX)) 18539 num_exentries++; 18540 } 18541 func[i]->aux->num_exentries = num_exentries; 18542 func[i]->aux->tail_call_reachable = env->subprog_info[i].tail_call_reachable; 18543 func[i] = bpf_int_jit_compile(func[i]); 18544 if (!func[i]->jited) { 18545 err = -ENOTSUPP; 18546 goto out_free; 18547 } 18548 cond_resched(); 18549 } 18550 18551 /* at this point all bpf functions were successfully JITed 18552 * now populate all bpf_calls with correct addresses and 18553 * run last pass of JIT 18554 */ 18555 for (i = 0; i < env->subprog_cnt; i++) { 18556 insn = func[i]->insnsi; 18557 for (j = 0; j < func[i]->len; j++, insn++) { 18558 if (bpf_pseudo_func(insn)) { 18559 subprog = insn->off; 18560 insn[0].imm = (u32)(long)func[subprog]->bpf_func; 18561 insn[1].imm = ((u64)(long)func[subprog]->bpf_func) >> 32; 18562 continue; 18563 } 18564 if (!bpf_pseudo_call(insn)) 18565 continue; 18566 subprog = insn->off; 18567 insn->imm = BPF_CALL_IMM(func[subprog]->bpf_func); 18568 } 18569 18570 /* we use the aux data to keep a list of the start addresses 18571 * of the JITed images for each function in the program 18572 * 18573 * for some architectures, such as powerpc64, the imm field 18574 * might not be large enough to hold the offset of the start 18575 * address of the callee's JITed image from __bpf_call_base 18576 * 18577 * in such cases, we can lookup the start address of a callee 18578 * by using its subprog id, available from the off field of 18579 * the call instruction, as an index for this list 18580 */ 18581 func[i]->aux->func = func; 18582 func[i]->aux->func_cnt = env->subprog_cnt; 18583 } 18584 for (i = 0; i < env->subprog_cnt; i++) { 18585 old_bpf_func = func[i]->bpf_func; 18586 tmp = bpf_int_jit_compile(func[i]); 18587 if (tmp != func[i] || func[i]->bpf_func != old_bpf_func) { 18588 verbose(env, "JIT doesn't support bpf-to-bpf calls\n"); 18589 err = -ENOTSUPP; 18590 goto out_free; 18591 } 18592 cond_resched(); 18593 } 18594 18595 /* finally lock prog and jit images for all functions and 18596 * populate kallsysm. Begin at the first subprogram, since 18597 * bpf_prog_load will add the kallsyms for the main program. 18598 */ 18599 for (i = 1; i < env->subprog_cnt; i++) { 18600 bpf_prog_lock_ro(func[i]); 18601 bpf_prog_kallsyms_add(func[i]); 18602 } 18603 18604 /* Last step: make now unused interpreter insns from main 18605 * prog consistent for later dump requests, so they can 18606 * later look the same as if they were interpreted only. 18607 */ 18608 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) { 18609 if (bpf_pseudo_func(insn)) { 18610 insn[0].imm = env->insn_aux_data[i].call_imm; 18611 insn[1].imm = insn->off; 18612 insn->off = 0; 18613 continue; 18614 } 18615 if (!bpf_pseudo_call(insn)) 18616 continue; 18617 insn->off = env->insn_aux_data[i].call_imm; 18618 subprog = find_subprog(env, i + insn->off + 1); 18619 insn->imm = subprog; 18620 } 18621 18622 prog->jited = 1; 18623 prog->bpf_func = func[0]->bpf_func; 18624 prog->jited_len = func[0]->jited_len; 18625 prog->aux->extable = func[0]->aux->extable; 18626 prog->aux->num_exentries = func[0]->aux->num_exentries; 18627 prog->aux->func = func; 18628 prog->aux->func_cnt = env->subprog_cnt; 18629 bpf_prog_jit_attempt_done(prog); 18630 return 0; 18631 out_free: 18632 /* We failed JIT'ing, so at this point we need to unregister poke 18633 * descriptors from subprogs, so that kernel is not attempting to 18634 * patch it anymore as we're freeing the subprog JIT memory. 18635 */ 18636 for (i = 0; i < prog->aux->size_poke_tab; i++) { 18637 map_ptr = prog->aux->poke_tab[i].tail_call.map; 18638 map_ptr->ops->map_poke_untrack(map_ptr, prog->aux); 18639 } 18640 /* At this point we're guaranteed that poke descriptors are not 18641 * live anymore. We can just unlink its descriptor table as it's 18642 * released with the main prog. 18643 */ 18644 for (i = 0; i < env->subprog_cnt; i++) { 18645 if (!func[i]) 18646 continue; 18647 func[i]->aux->poke_tab = NULL; 18648 bpf_jit_free(func[i]); 18649 } 18650 kfree(func); 18651 out_undo_insn: 18652 /* cleanup main prog to be interpreted */ 18653 prog->jit_requested = 0; 18654 prog->blinding_requested = 0; 18655 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) { 18656 if (!bpf_pseudo_call(insn)) 18657 continue; 18658 insn->off = 0; 18659 insn->imm = env->insn_aux_data[i].call_imm; 18660 } 18661 bpf_prog_jit_attempt_done(prog); 18662 return err; 18663 } 18664 18665 static int fixup_call_args(struct bpf_verifier_env *env) 18666 { 18667 #ifndef CONFIG_BPF_JIT_ALWAYS_ON 18668 struct bpf_prog *prog = env->prog; 18669 struct bpf_insn *insn = prog->insnsi; 18670 bool has_kfunc_call = bpf_prog_has_kfunc_call(prog); 18671 int i, depth; 18672 #endif 18673 int err = 0; 18674 18675 if (env->prog->jit_requested && 18676 !bpf_prog_is_offloaded(env->prog->aux)) { 18677 err = jit_subprogs(env); 18678 if (err == 0) 18679 return 0; 18680 if (err == -EFAULT) 18681 return err; 18682 } 18683 #ifndef CONFIG_BPF_JIT_ALWAYS_ON 18684 if (has_kfunc_call) { 18685 verbose(env, "calling kernel functions are not allowed in non-JITed programs\n"); 18686 return -EINVAL; 18687 } 18688 if (env->subprog_cnt > 1 && env->prog->aux->tail_call_reachable) { 18689 /* When JIT fails the progs with bpf2bpf calls and tail_calls 18690 * have to be rejected, since interpreter doesn't support them yet. 18691 */ 18692 verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n"); 18693 return -EINVAL; 18694 } 18695 for (i = 0; i < prog->len; i++, insn++) { 18696 if (bpf_pseudo_func(insn)) { 18697 /* When JIT fails the progs with callback calls 18698 * have to be rejected, since interpreter doesn't support them yet. 18699 */ 18700 verbose(env, "callbacks are not allowed in non-JITed programs\n"); 18701 return -EINVAL; 18702 } 18703 18704 if (!bpf_pseudo_call(insn)) 18705 continue; 18706 depth = get_callee_stack_depth(env, insn, i); 18707 if (depth < 0) 18708 return depth; 18709 bpf_patch_call_args(insn, depth); 18710 } 18711 err = 0; 18712 #endif 18713 return err; 18714 } 18715 18716 /* replace a generic kfunc with a specialized version if necessary */ 18717 static void specialize_kfunc(struct bpf_verifier_env *env, 18718 u32 func_id, u16 offset, unsigned long *addr) 18719 { 18720 struct bpf_prog *prog = env->prog; 18721 bool seen_direct_write; 18722 void *xdp_kfunc; 18723 bool is_rdonly; 18724 18725 if (bpf_dev_bound_kfunc_id(func_id)) { 18726 xdp_kfunc = bpf_dev_bound_resolve_kfunc(prog, func_id); 18727 if (xdp_kfunc) { 18728 *addr = (unsigned long)xdp_kfunc; 18729 return; 18730 } 18731 /* fallback to default kfunc when not supported by netdev */ 18732 } 18733 18734 if (offset) 18735 return; 18736 18737 if (func_id == special_kfunc_list[KF_bpf_dynptr_from_skb]) { 18738 seen_direct_write = env->seen_direct_write; 18739 is_rdonly = !may_access_direct_pkt_data(env, NULL, BPF_WRITE); 18740 18741 if (is_rdonly) 18742 *addr = (unsigned long)bpf_dynptr_from_skb_rdonly; 18743 18744 /* restore env->seen_direct_write to its original value, since 18745 * may_access_direct_pkt_data mutates it 18746 */ 18747 env->seen_direct_write = seen_direct_write; 18748 } 18749 } 18750 18751 static void __fixup_collection_insert_kfunc(struct bpf_insn_aux_data *insn_aux, 18752 u16 struct_meta_reg, 18753 u16 node_offset_reg, 18754 struct bpf_insn *insn, 18755 struct bpf_insn *insn_buf, 18756 int *cnt) 18757 { 18758 struct btf_struct_meta *kptr_struct_meta = insn_aux->kptr_struct_meta; 18759 struct bpf_insn addr[2] = { BPF_LD_IMM64(struct_meta_reg, (long)kptr_struct_meta) }; 18760 18761 insn_buf[0] = addr[0]; 18762 insn_buf[1] = addr[1]; 18763 insn_buf[2] = BPF_MOV64_IMM(node_offset_reg, insn_aux->insert_off); 18764 insn_buf[3] = *insn; 18765 *cnt = 4; 18766 } 18767 18768 static int fixup_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn, 18769 struct bpf_insn *insn_buf, int insn_idx, int *cnt) 18770 { 18771 const struct bpf_kfunc_desc *desc; 18772 18773 if (!insn->imm) { 18774 verbose(env, "invalid kernel function call not eliminated in verifier pass\n"); 18775 return -EINVAL; 18776 } 18777 18778 *cnt = 0; 18779 18780 /* insn->imm has the btf func_id. Replace it with an offset relative to 18781 * __bpf_call_base, unless the JIT needs to call functions that are 18782 * further than 32 bits away (bpf_jit_supports_far_kfunc_call()). 18783 */ 18784 desc = find_kfunc_desc(env->prog, insn->imm, insn->off); 18785 if (!desc) { 18786 verbose(env, "verifier internal error: kernel function descriptor not found for func_id %u\n", 18787 insn->imm); 18788 return -EFAULT; 18789 } 18790 18791 if (!bpf_jit_supports_far_kfunc_call()) 18792 insn->imm = BPF_CALL_IMM(desc->addr); 18793 if (insn->off) 18794 return 0; 18795 if (desc->func_id == special_kfunc_list[KF_bpf_obj_new_impl]) { 18796 struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta; 18797 struct bpf_insn addr[2] = { BPF_LD_IMM64(BPF_REG_2, (long)kptr_struct_meta) }; 18798 u64 obj_new_size = env->insn_aux_data[insn_idx].obj_new_size; 18799 18800 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_1, obj_new_size); 18801 insn_buf[1] = addr[0]; 18802 insn_buf[2] = addr[1]; 18803 insn_buf[3] = *insn; 18804 *cnt = 4; 18805 } else if (desc->func_id == special_kfunc_list[KF_bpf_obj_drop_impl] || 18806 desc->func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl]) { 18807 struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta; 18808 struct bpf_insn addr[2] = { BPF_LD_IMM64(BPF_REG_2, (long)kptr_struct_meta) }; 18809 18810 if (desc->func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl] && 18811 !kptr_struct_meta) { 18812 verbose(env, "verifier internal error: kptr_struct_meta expected at insn_idx %d\n", 18813 insn_idx); 18814 return -EFAULT; 18815 } 18816 18817 insn_buf[0] = addr[0]; 18818 insn_buf[1] = addr[1]; 18819 insn_buf[2] = *insn; 18820 *cnt = 3; 18821 } else if (desc->func_id == special_kfunc_list[KF_bpf_list_push_back_impl] || 18822 desc->func_id == special_kfunc_list[KF_bpf_list_push_front_impl] || 18823 desc->func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) { 18824 struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta; 18825 int struct_meta_reg = BPF_REG_3; 18826 int node_offset_reg = BPF_REG_4; 18827 18828 /* rbtree_add has extra 'less' arg, so args-to-fixup are in diff regs */ 18829 if (desc->func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) { 18830 struct_meta_reg = BPF_REG_4; 18831 node_offset_reg = BPF_REG_5; 18832 } 18833 18834 if (!kptr_struct_meta) { 18835 verbose(env, "verifier internal error: kptr_struct_meta expected at insn_idx %d\n", 18836 insn_idx); 18837 return -EFAULT; 18838 } 18839 18840 __fixup_collection_insert_kfunc(&env->insn_aux_data[insn_idx], struct_meta_reg, 18841 node_offset_reg, insn, insn_buf, cnt); 18842 } else if (desc->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx] || 18843 desc->func_id == special_kfunc_list[KF_bpf_rdonly_cast]) { 18844 insn_buf[0] = BPF_MOV64_REG(BPF_REG_0, BPF_REG_1); 18845 *cnt = 1; 18846 } 18847 return 0; 18848 } 18849 18850 /* Do various post-verification rewrites in a single program pass. 18851 * These rewrites simplify JIT and interpreter implementations. 18852 */ 18853 static int do_misc_fixups(struct bpf_verifier_env *env) 18854 { 18855 struct bpf_prog *prog = env->prog; 18856 enum bpf_attach_type eatype = prog->expected_attach_type; 18857 enum bpf_prog_type prog_type = resolve_prog_type(prog); 18858 struct bpf_insn *insn = prog->insnsi; 18859 const struct bpf_func_proto *fn; 18860 const int insn_cnt = prog->len; 18861 const struct bpf_map_ops *ops; 18862 struct bpf_insn_aux_data *aux; 18863 struct bpf_insn insn_buf[16]; 18864 struct bpf_prog *new_prog; 18865 struct bpf_map *map_ptr; 18866 int i, ret, cnt, delta = 0; 18867 18868 for (i = 0; i < insn_cnt; i++, insn++) { 18869 /* Make divide-by-zero exceptions impossible. */ 18870 if (insn->code == (BPF_ALU64 | BPF_MOD | BPF_X) || 18871 insn->code == (BPF_ALU64 | BPF_DIV | BPF_X) || 18872 insn->code == (BPF_ALU | BPF_MOD | BPF_X) || 18873 insn->code == (BPF_ALU | BPF_DIV | BPF_X)) { 18874 bool is64 = BPF_CLASS(insn->code) == BPF_ALU64; 18875 bool isdiv = BPF_OP(insn->code) == BPF_DIV; 18876 struct bpf_insn *patchlet; 18877 struct bpf_insn chk_and_div[] = { 18878 /* [R,W]x div 0 -> 0 */ 18879 BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) | 18880 BPF_JNE | BPF_K, insn->src_reg, 18881 0, 2, 0), 18882 BPF_ALU32_REG(BPF_XOR, insn->dst_reg, insn->dst_reg), 18883 BPF_JMP_IMM(BPF_JA, 0, 0, 1), 18884 *insn, 18885 }; 18886 struct bpf_insn chk_and_mod[] = { 18887 /* [R,W]x mod 0 -> [R,W]x */ 18888 BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) | 18889 BPF_JEQ | BPF_K, insn->src_reg, 18890 0, 1 + (is64 ? 0 : 1), 0), 18891 *insn, 18892 BPF_JMP_IMM(BPF_JA, 0, 0, 1), 18893 BPF_MOV32_REG(insn->dst_reg, insn->dst_reg), 18894 }; 18895 18896 patchlet = isdiv ? chk_and_div : chk_and_mod; 18897 cnt = isdiv ? ARRAY_SIZE(chk_and_div) : 18898 ARRAY_SIZE(chk_and_mod) - (is64 ? 2 : 0); 18899 18900 new_prog = bpf_patch_insn_data(env, i + delta, patchlet, cnt); 18901 if (!new_prog) 18902 return -ENOMEM; 18903 18904 delta += cnt - 1; 18905 env->prog = prog = new_prog; 18906 insn = new_prog->insnsi + i + delta; 18907 continue; 18908 } 18909 18910 /* Implement LD_ABS and LD_IND with a rewrite, if supported by the program type. */ 18911 if (BPF_CLASS(insn->code) == BPF_LD && 18912 (BPF_MODE(insn->code) == BPF_ABS || 18913 BPF_MODE(insn->code) == BPF_IND)) { 18914 cnt = env->ops->gen_ld_abs(insn, insn_buf); 18915 if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf)) { 18916 verbose(env, "bpf verifier is misconfigured\n"); 18917 return -EINVAL; 18918 } 18919 18920 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 18921 if (!new_prog) 18922 return -ENOMEM; 18923 18924 delta += cnt - 1; 18925 env->prog = prog = new_prog; 18926 insn = new_prog->insnsi + i + delta; 18927 continue; 18928 } 18929 18930 /* Rewrite pointer arithmetic to mitigate speculation attacks. */ 18931 if (insn->code == (BPF_ALU64 | BPF_ADD | BPF_X) || 18932 insn->code == (BPF_ALU64 | BPF_SUB | BPF_X)) { 18933 const u8 code_add = BPF_ALU64 | BPF_ADD | BPF_X; 18934 const u8 code_sub = BPF_ALU64 | BPF_SUB | BPF_X; 18935 struct bpf_insn *patch = &insn_buf[0]; 18936 bool issrc, isneg, isimm; 18937 u32 off_reg; 18938 18939 aux = &env->insn_aux_data[i + delta]; 18940 if (!aux->alu_state || 18941 aux->alu_state == BPF_ALU_NON_POINTER) 18942 continue; 18943 18944 isneg = aux->alu_state & BPF_ALU_NEG_VALUE; 18945 issrc = (aux->alu_state & BPF_ALU_SANITIZE) == 18946 BPF_ALU_SANITIZE_SRC; 18947 isimm = aux->alu_state & BPF_ALU_IMMEDIATE; 18948 18949 off_reg = issrc ? insn->src_reg : insn->dst_reg; 18950 if (isimm) { 18951 *patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit); 18952 } else { 18953 if (isneg) 18954 *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1); 18955 *patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit); 18956 *patch++ = BPF_ALU64_REG(BPF_SUB, BPF_REG_AX, off_reg); 18957 *patch++ = BPF_ALU64_REG(BPF_OR, BPF_REG_AX, off_reg); 18958 *patch++ = BPF_ALU64_IMM(BPF_NEG, BPF_REG_AX, 0); 18959 *patch++ = BPF_ALU64_IMM(BPF_ARSH, BPF_REG_AX, 63); 18960 *patch++ = BPF_ALU64_REG(BPF_AND, BPF_REG_AX, off_reg); 18961 } 18962 if (!issrc) 18963 *patch++ = BPF_MOV64_REG(insn->dst_reg, insn->src_reg); 18964 insn->src_reg = BPF_REG_AX; 18965 if (isneg) 18966 insn->code = insn->code == code_add ? 18967 code_sub : code_add; 18968 *patch++ = *insn; 18969 if (issrc && isneg && !isimm) 18970 *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1); 18971 cnt = patch - insn_buf; 18972 18973 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 18974 if (!new_prog) 18975 return -ENOMEM; 18976 18977 delta += cnt - 1; 18978 env->prog = prog = new_prog; 18979 insn = new_prog->insnsi + i + delta; 18980 continue; 18981 } 18982 18983 if (insn->code != (BPF_JMP | BPF_CALL)) 18984 continue; 18985 if (insn->src_reg == BPF_PSEUDO_CALL) 18986 continue; 18987 if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) { 18988 ret = fixup_kfunc_call(env, insn, insn_buf, i + delta, &cnt); 18989 if (ret) 18990 return ret; 18991 if (cnt == 0) 18992 continue; 18993 18994 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 18995 if (!new_prog) 18996 return -ENOMEM; 18997 18998 delta += cnt - 1; 18999 env->prog = prog = new_prog; 19000 insn = new_prog->insnsi + i + delta; 19001 continue; 19002 } 19003 19004 if (insn->imm == BPF_FUNC_get_route_realm) 19005 prog->dst_needed = 1; 19006 if (insn->imm == BPF_FUNC_get_prandom_u32) 19007 bpf_user_rnd_init_once(); 19008 if (insn->imm == BPF_FUNC_override_return) 19009 prog->kprobe_override = 1; 19010 if (insn->imm == BPF_FUNC_tail_call) { 19011 /* If we tail call into other programs, we 19012 * cannot make any assumptions since they can 19013 * be replaced dynamically during runtime in 19014 * the program array. 19015 */ 19016 prog->cb_access = 1; 19017 if (!allow_tail_call_in_subprogs(env)) 19018 prog->aux->stack_depth = MAX_BPF_STACK; 19019 prog->aux->max_pkt_offset = MAX_PACKET_OFF; 19020 19021 /* mark bpf_tail_call as different opcode to avoid 19022 * conditional branch in the interpreter for every normal 19023 * call and to prevent accidental JITing by JIT compiler 19024 * that doesn't support bpf_tail_call yet 19025 */ 19026 insn->imm = 0; 19027 insn->code = BPF_JMP | BPF_TAIL_CALL; 19028 19029 aux = &env->insn_aux_data[i + delta]; 19030 if (env->bpf_capable && !prog->blinding_requested && 19031 prog->jit_requested && 19032 !bpf_map_key_poisoned(aux) && 19033 !bpf_map_ptr_poisoned(aux) && 19034 !bpf_map_ptr_unpriv(aux)) { 19035 struct bpf_jit_poke_descriptor desc = { 19036 .reason = BPF_POKE_REASON_TAIL_CALL, 19037 .tail_call.map = BPF_MAP_PTR(aux->map_ptr_state), 19038 .tail_call.key = bpf_map_key_immediate(aux), 19039 .insn_idx = i + delta, 19040 }; 19041 19042 ret = bpf_jit_add_poke_descriptor(prog, &desc); 19043 if (ret < 0) { 19044 verbose(env, "adding tail call poke descriptor failed\n"); 19045 return ret; 19046 } 19047 19048 insn->imm = ret + 1; 19049 continue; 19050 } 19051 19052 if (!bpf_map_ptr_unpriv(aux)) 19053 continue; 19054 19055 /* instead of changing every JIT dealing with tail_call 19056 * emit two extra insns: 19057 * if (index >= max_entries) goto out; 19058 * index &= array->index_mask; 19059 * to avoid out-of-bounds cpu speculation 19060 */ 19061 if (bpf_map_ptr_poisoned(aux)) { 19062 verbose(env, "tail_call abusing map_ptr\n"); 19063 return -EINVAL; 19064 } 19065 19066 map_ptr = BPF_MAP_PTR(aux->map_ptr_state); 19067 insn_buf[0] = BPF_JMP_IMM(BPF_JGE, BPF_REG_3, 19068 map_ptr->max_entries, 2); 19069 insn_buf[1] = BPF_ALU32_IMM(BPF_AND, BPF_REG_3, 19070 container_of(map_ptr, 19071 struct bpf_array, 19072 map)->index_mask); 19073 insn_buf[2] = *insn; 19074 cnt = 3; 19075 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 19076 if (!new_prog) 19077 return -ENOMEM; 19078 19079 delta += cnt - 1; 19080 env->prog = prog = new_prog; 19081 insn = new_prog->insnsi + i + delta; 19082 continue; 19083 } 19084 19085 if (insn->imm == BPF_FUNC_timer_set_callback) { 19086 /* The verifier will process callback_fn as many times as necessary 19087 * with different maps and the register states prepared by 19088 * set_timer_callback_state will be accurate. 19089 * 19090 * The following use case is valid: 19091 * map1 is shared by prog1, prog2, prog3. 19092 * prog1 calls bpf_timer_init for some map1 elements 19093 * prog2 calls bpf_timer_set_callback for some map1 elements. 19094 * Those that were not bpf_timer_init-ed will return -EINVAL. 19095 * prog3 calls bpf_timer_start for some map1 elements. 19096 * Those that were not both bpf_timer_init-ed and 19097 * bpf_timer_set_callback-ed will return -EINVAL. 19098 */ 19099 struct bpf_insn ld_addrs[2] = { 19100 BPF_LD_IMM64(BPF_REG_3, (long)prog->aux), 19101 }; 19102 19103 insn_buf[0] = ld_addrs[0]; 19104 insn_buf[1] = ld_addrs[1]; 19105 insn_buf[2] = *insn; 19106 cnt = 3; 19107 19108 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 19109 if (!new_prog) 19110 return -ENOMEM; 19111 19112 delta += cnt - 1; 19113 env->prog = prog = new_prog; 19114 insn = new_prog->insnsi + i + delta; 19115 goto patch_call_imm; 19116 } 19117 19118 if (is_storage_get_function(insn->imm)) { 19119 if (!env->prog->aux->sleepable || 19120 env->insn_aux_data[i + delta].storage_get_func_atomic) 19121 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_5, (__force __s32)GFP_ATOMIC); 19122 else 19123 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_5, (__force __s32)GFP_KERNEL); 19124 insn_buf[1] = *insn; 19125 cnt = 2; 19126 19127 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 19128 if (!new_prog) 19129 return -ENOMEM; 19130 19131 delta += cnt - 1; 19132 env->prog = prog = new_prog; 19133 insn = new_prog->insnsi + i + delta; 19134 goto patch_call_imm; 19135 } 19136 19137 /* BPF_EMIT_CALL() assumptions in some of the map_gen_lookup 19138 * and other inlining handlers are currently limited to 64 bit 19139 * only. 19140 */ 19141 if (prog->jit_requested && BITS_PER_LONG == 64 && 19142 (insn->imm == BPF_FUNC_map_lookup_elem || 19143 insn->imm == BPF_FUNC_map_update_elem || 19144 insn->imm == BPF_FUNC_map_delete_elem || 19145 insn->imm == BPF_FUNC_map_push_elem || 19146 insn->imm == BPF_FUNC_map_pop_elem || 19147 insn->imm == BPF_FUNC_map_peek_elem || 19148 insn->imm == BPF_FUNC_redirect_map || 19149 insn->imm == BPF_FUNC_for_each_map_elem || 19150 insn->imm == BPF_FUNC_map_lookup_percpu_elem)) { 19151 aux = &env->insn_aux_data[i + delta]; 19152 if (bpf_map_ptr_poisoned(aux)) 19153 goto patch_call_imm; 19154 19155 map_ptr = BPF_MAP_PTR(aux->map_ptr_state); 19156 ops = map_ptr->ops; 19157 if (insn->imm == BPF_FUNC_map_lookup_elem && 19158 ops->map_gen_lookup) { 19159 cnt = ops->map_gen_lookup(map_ptr, insn_buf); 19160 if (cnt == -EOPNOTSUPP) 19161 goto patch_map_ops_generic; 19162 if (cnt <= 0 || cnt >= ARRAY_SIZE(insn_buf)) { 19163 verbose(env, "bpf verifier is misconfigured\n"); 19164 return -EINVAL; 19165 } 19166 19167 new_prog = bpf_patch_insn_data(env, i + delta, 19168 insn_buf, cnt); 19169 if (!new_prog) 19170 return -ENOMEM; 19171 19172 delta += cnt - 1; 19173 env->prog = prog = new_prog; 19174 insn = new_prog->insnsi + i + delta; 19175 continue; 19176 } 19177 19178 BUILD_BUG_ON(!__same_type(ops->map_lookup_elem, 19179 (void *(*)(struct bpf_map *map, void *key))NULL)); 19180 BUILD_BUG_ON(!__same_type(ops->map_delete_elem, 19181 (long (*)(struct bpf_map *map, void *key))NULL)); 19182 BUILD_BUG_ON(!__same_type(ops->map_update_elem, 19183 (long (*)(struct bpf_map *map, void *key, void *value, 19184 u64 flags))NULL)); 19185 BUILD_BUG_ON(!__same_type(ops->map_push_elem, 19186 (long (*)(struct bpf_map *map, void *value, 19187 u64 flags))NULL)); 19188 BUILD_BUG_ON(!__same_type(ops->map_pop_elem, 19189 (long (*)(struct bpf_map *map, void *value))NULL)); 19190 BUILD_BUG_ON(!__same_type(ops->map_peek_elem, 19191 (long (*)(struct bpf_map *map, void *value))NULL)); 19192 BUILD_BUG_ON(!__same_type(ops->map_redirect, 19193 (long (*)(struct bpf_map *map, u64 index, u64 flags))NULL)); 19194 BUILD_BUG_ON(!__same_type(ops->map_for_each_callback, 19195 (long (*)(struct bpf_map *map, 19196 bpf_callback_t callback_fn, 19197 void *callback_ctx, 19198 u64 flags))NULL)); 19199 BUILD_BUG_ON(!__same_type(ops->map_lookup_percpu_elem, 19200 (void *(*)(struct bpf_map *map, void *key, u32 cpu))NULL)); 19201 19202 patch_map_ops_generic: 19203 switch (insn->imm) { 19204 case BPF_FUNC_map_lookup_elem: 19205 insn->imm = BPF_CALL_IMM(ops->map_lookup_elem); 19206 continue; 19207 case BPF_FUNC_map_update_elem: 19208 insn->imm = BPF_CALL_IMM(ops->map_update_elem); 19209 continue; 19210 case BPF_FUNC_map_delete_elem: 19211 insn->imm = BPF_CALL_IMM(ops->map_delete_elem); 19212 continue; 19213 case BPF_FUNC_map_push_elem: 19214 insn->imm = BPF_CALL_IMM(ops->map_push_elem); 19215 continue; 19216 case BPF_FUNC_map_pop_elem: 19217 insn->imm = BPF_CALL_IMM(ops->map_pop_elem); 19218 continue; 19219 case BPF_FUNC_map_peek_elem: 19220 insn->imm = BPF_CALL_IMM(ops->map_peek_elem); 19221 continue; 19222 case BPF_FUNC_redirect_map: 19223 insn->imm = BPF_CALL_IMM(ops->map_redirect); 19224 continue; 19225 case BPF_FUNC_for_each_map_elem: 19226 insn->imm = BPF_CALL_IMM(ops->map_for_each_callback); 19227 continue; 19228 case BPF_FUNC_map_lookup_percpu_elem: 19229 insn->imm = BPF_CALL_IMM(ops->map_lookup_percpu_elem); 19230 continue; 19231 } 19232 19233 goto patch_call_imm; 19234 } 19235 19236 /* Implement bpf_jiffies64 inline. */ 19237 if (prog->jit_requested && BITS_PER_LONG == 64 && 19238 insn->imm == BPF_FUNC_jiffies64) { 19239 struct bpf_insn ld_jiffies_addr[2] = { 19240 BPF_LD_IMM64(BPF_REG_0, 19241 (unsigned long)&jiffies), 19242 }; 19243 19244 insn_buf[0] = ld_jiffies_addr[0]; 19245 insn_buf[1] = ld_jiffies_addr[1]; 19246 insn_buf[2] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, 19247 BPF_REG_0, 0); 19248 cnt = 3; 19249 19250 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 19251 cnt); 19252 if (!new_prog) 19253 return -ENOMEM; 19254 19255 delta += cnt - 1; 19256 env->prog = prog = new_prog; 19257 insn = new_prog->insnsi + i + delta; 19258 continue; 19259 } 19260 19261 /* Implement bpf_get_func_arg inline. */ 19262 if (prog_type == BPF_PROG_TYPE_TRACING && 19263 insn->imm == BPF_FUNC_get_func_arg) { 19264 /* Load nr_args from ctx - 8 */ 19265 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8); 19266 insn_buf[1] = BPF_JMP32_REG(BPF_JGE, BPF_REG_2, BPF_REG_0, 6); 19267 insn_buf[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_2, 3); 19268 insn_buf[3] = BPF_ALU64_REG(BPF_ADD, BPF_REG_2, BPF_REG_1); 19269 insn_buf[4] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_2, 0); 19270 insn_buf[5] = BPF_STX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0); 19271 insn_buf[6] = BPF_MOV64_IMM(BPF_REG_0, 0); 19272 insn_buf[7] = BPF_JMP_A(1); 19273 insn_buf[8] = BPF_MOV64_IMM(BPF_REG_0, -EINVAL); 19274 cnt = 9; 19275 19276 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 19277 if (!new_prog) 19278 return -ENOMEM; 19279 19280 delta += cnt - 1; 19281 env->prog = prog = new_prog; 19282 insn = new_prog->insnsi + i + delta; 19283 continue; 19284 } 19285 19286 /* Implement bpf_get_func_ret inline. */ 19287 if (prog_type == BPF_PROG_TYPE_TRACING && 19288 insn->imm == BPF_FUNC_get_func_ret) { 19289 if (eatype == BPF_TRACE_FEXIT || 19290 eatype == BPF_MODIFY_RETURN) { 19291 /* Load nr_args from ctx - 8 */ 19292 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8); 19293 insn_buf[1] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_0, 3); 19294 insn_buf[2] = BPF_ALU64_REG(BPF_ADD, BPF_REG_0, BPF_REG_1); 19295 insn_buf[3] = BPF_LDX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0); 19296 insn_buf[4] = BPF_STX_MEM(BPF_DW, BPF_REG_2, BPF_REG_3, 0); 19297 insn_buf[5] = BPF_MOV64_IMM(BPF_REG_0, 0); 19298 cnt = 6; 19299 } else { 19300 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_0, -EOPNOTSUPP); 19301 cnt = 1; 19302 } 19303 19304 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 19305 if (!new_prog) 19306 return -ENOMEM; 19307 19308 delta += cnt - 1; 19309 env->prog = prog = new_prog; 19310 insn = new_prog->insnsi + i + delta; 19311 continue; 19312 } 19313 19314 /* Implement get_func_arg_cnt inline. */ 19315 if (prog_type == BPF_PROG_TYPE_TRACING && 19316 insn->imm == BPF_FUNC_get_func_arg_cnt) { 19317 /* Load nr_args from ctx - 8 */ 19318 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8); 19319 19320 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1); 19321 if (!new_prog) 19322 return -ENOMEM; 19323 19324 env->prog = prog = new_prog; 19325 insn = new_prog->insnsi + i + delta; 19326 continue; 19327 } 19328 19329 /* Implement bpf_get_func_ip inline. */ 19330 if (prog_type == BPF_PROG_TYPE_TRACING && 19331 insn->imm == BPF_FUNC_get_func_ip) { 19332 /* Load IP address from ctx - 16 */ 19333 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -16); 19334 19335 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1); 19336 if (!new_prog) 19337 return -ENOMEM; 19338 19339 env->prog = prog = new_prog; 19340 insn = new_prog->insnsi + i + delta; 19341 continue; 19342 } 19343 19344 patch_call_imm: 19345 fn = env->ops->get_func_proto(insn->imm, env->prog); 19346 /* all functions that have prototype and verifier allowed 19347 * programs to call them, must be real in-kernel functions 19348 */ 19349 if (!fn->func) { 19350 verbose(env, 19351 "kernel subsystem misconfigured func %s#%d\n", 19352 func_id_name(insn->imm), insn->imm); 19353 return -EFAULT; 19354 } 19355 insn->imm = fn->func - __bpf_call_base; 19356 } 19357 19358 /* Since poke tab is now finalized, publish aux to tracker. */ 19359 for (i = 0; i < prog->aux->size_poke_tab; i++) { 19360 map_ptr = prog->aux->poke_tab[i].tail_call.map; 19361 if (!map_ptr->ops->map_poke_track || 19362 !map_ptr->ops->map_poke_untrack || 19363 !map_ptr->ops->map_poke_run) { 19364 verbose(env, "bpf verifier is misconfigured\n"); 19365 return -EINVAL; 19366 } 19367 19368 ret = map_ptr->ops->map_poke_track(map_ptr, prog->aux); 19369 if (ret < 0) { 19370 verbose(env, "tracking tail call prog failed\n"); 19371 return ret; 19372 } 19373 } 19374 19375 sort_kfunc_descs_by_imm_off(env->prog); 19376 19377 return 0; 19378 } 19379 19380 static struct bpf_prog *inline_bpf_loop(struct bpf_verifier_env *env, 19381 int position, 19382 s32 stack_base, 19383 u32 callback_subprogno, 19384 u32 *cnt) 19385 { 19386 s32 r6_offset = stack_base + 0 * BPF_REG_SIZE; 19387 s32 r7_offset = stack_base + 1 * BPF_REG_SIZE; 19388 s32 r8_offset = stack_base + 2 * BPF_REG_SIZE; 19389 int reg_loop_max = BPF_REG_6; 19390 int reg_loop_cnt = BPF_REG_7; 19391 int reg_loop_ctx = BPF_REG_8; 19392 19393 struct bpf_prog *new_prog; 19394 u32 callback_start; 19395 u32 call_insn_offset; 19396 s32 callback_offset; 19397 19398 /* This represents an inlined version of bpf_iter.c:bpf_loop, 19399 * be careful to modify this code in sync. 19400 */ 19401 struct bpf_insn insn_buf[] = { 19402 /* Return error and jump to the end of the patch if 19403 * expected number of iterations is too big. 19404 */ 19405 BPF_JMP_IMM(BPF_JLE, BPF_REG_1, BPF_MAX_LOOPS, 2), 19406 BPF_MOV32_IMM(BPF_REG_0, -E2BIG), 19407 BPF_JMP_IMM(BPF_JA, 0, 0, 16), 19408 /* spill R6, R7, R8 to use these as loop vars */ 19409 BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_6, r6_offset), 19410 BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_7, r7_offset), 19411 BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_8, r8_offset), 19412 /* initialize loop vars */ 19413 BPF_MOV64_REG(reg_loop_max, BPF_REG_1), 19414 BPF_MOV32_IMM(reg_loop_cnt, 0), 19415 BPF_MOV64_REG(reg_loop_ctx, BPF_REG_3), 19416 /* loop header, 19417 * if reg_loop_cnt >= reg_loop_max skip the loop body 19418 */ 19419 BPF_JMP_REG(BPF_JGE, reg_loop_cnt, reg_loop_max, 5), 19420 /* callback call, 19421 * correct callback offset would be set after patching 19422 */ 19423 BPF_MOV64_REG(BPF_REG_1, reg_loop_cnt), 19424 BPF_MOV64_REG(BPF_REG_2, reg_loop_ctx), 19425 BPF_CALL_REL(0), 19426 /* increment loop counter */ 19427 BPF_ALU64_IMM(BPF_ADD, reg_loop_cnt, 1), 19428 /* jump to loop header if callback returned 0 */ 19429 BPF_JMP_IMM(BPF_JEQ, BPF_REG_0, 0, -6), 19430 /* return value of bpf_loop, 19431 * set R0 to the number of iterations 19432 */ 19433 BPF_MOV64_REG(BPF_REG_0, reg_loop_cnt), 19434 /* restore original values of R6, R7, R8 */ 19435 BPF_LDX_MEM(BPF_DW, BPF_REG_6, BPF_REG_10, r6_offset), 19436 BPF_LDX_MEM(BPF_DW, BPF_REG_7, BPF_REG_10, r7_offset), 19437 BPF_LDX_MEM(BPF_DW, BPF_REG_8, BPF_REG_10, r8_offset), 19438 }; 19439 19440 *cnt = ARRAY_SIZE(insn_buf); 19441 new_prog = bpf_patch_insn_data(env, position, insn_buf, *cnt); 19442 if (!new_prog) 19443 return new_prog; 19444 19445 /* callback start is known only after patching */ 19446 callback_start = env->subprog_info[callback_subprogno].start; 19447 /* Note: insn_buf[12] is an offset of BPF_CALL_REL instruction */ 19448 call_insn_offset = position + 12; 19449 callback_offset = callback_start - call_insn_offset - 1; 19450 new_prog->insnsi[call_insn_offset].imm = callback_offset; 19451 19452 return new_prog; 19453 } 19454 19455 static bool is_bpf_loop_call(struct bpf_insn *insn) 19456 { 19457 return insn->code == (BPF_JMP | BPF_CALL) && 19458 insn->src_reg == 0 && 19459 insn->imm == BPF_FUNC_loop; 19460 } 19461 19462 /* For all sub-programs in the program (including main) check 19463 * insn_aux_data to see if there are bpf_loop calls that require 19464 * inlining. If such calls are found the calls are replaced with a 19465 * sequence of instructions produced by `inline_bpf_loop` function and 19466 * subprog stack_depth is increased by the size of 3 registers. 19467 * This stack space is used to spill values of the R6, R7, R8. These 19468 * registers are used to store the loop bound, counter and context 19469 * variables. 19470 */ 19471 static int optimize_bpf_loop(struct bpf_verifier_env *env) 19472 { 19473 struct bpf_subprog_info *subprogs = env->subprog_info; 19474 int i, cur_subprog = 0, cnt, delta = 0; 19475 struct bpf_insn *insn = env->prog->insnsi; 19476 int insn_cnt = env->prog->len; 19477 u16 stack_depth = subprogs[cur_subprog].stack_depth; 19478 u16 stack_depth_roundup = round_up(stack_depth, 8) - stack_depth; 19479 u16 stack_depth_extra = 0; 19480 19481 for (i = 0; i < insn_cnt; i++, insn++) { 19482 struct bpf_loop_inline_state *inline_state = 19483 &env->insn_aux_data[i + delta].loop_inline_state; 19484 19485 if (is_bpf_loop_call(insn) && inline_state->fit_for_inline) { 19486 struct bpf_prog *new_prog; 19487 19488 stack_depth_extra = BPF_REG_SIZE * 3 + stack_depth_roundup; 19489 new_prog = inline_bpf_loop(env, 19490 i + delta, 19491 -(stack_depth + stack_depth_extra), 19492 inline_state->callback_subprogno, 19493 &cnt); 19494 if (!new_prog) 19495 return -ENOMEM; 19496 19497 delta += cnt - 1; 19498 env->prog = new_prog; 19499 insn = new_prog->insnsi + i + delta; 19500 } 19501 19502 if (subprogs[cur_subprog + 1].start == i + delta + 1) { 19503 subprogs[cur_subprog].stack_depth += stack_depth_extra; 19504 cur_subprog++; 19505 stack_depth = subprogs[cur_subprog].stack_depth; 19506 stack_depth_roundup = round_up(stack_depth, 8) - stack_depth; 19507 stack_depth_extra = 0; 19508 } 19509 } 19510 19511 env->prog->aux->stack_depth = env->subprog_info[0].stack_depth; 19512 19513 return 0; 19514 } 19515 19516 static void free_states(struct bpf_verifier_env *env) 19517 { 19518 struct bpf_verifier_state_list *sl, *sln; 19519 int i; 19520 19521 sl = env->free_list; 19522 while (sl) { 19523 sln = sl->next; 19524 free_verifier_state(&sl->state, false); 19525 kfree(sl); 19526 sl = sln; 19527 } 19528 env->free_list = NULL; 19529 19530 if (!env->explored_states) 19531 return; 19532 19533 for (i = 0; i < state_htab_size(env); i++) { 19534 sl = env->explored_states[i]; 19535 19536 while (sl) { 19537 sln = sl->next; 19538 free_verifier_state(&sl->state, false); 19539 kfree(sl); 19540 sl = sln; 19541 } 19542 env->explored_states[i] = NULL; 19543 } 19544 } 19545 19546 static int do_check_common(struct bpf_verifier_env *env, int subprog) 19547 { 19548 bool pop_log = !(env->log.level & BPF_LOG_LEVEL2); 19549 struct bpf_verifier_state *state; 19550 struct bpf_reg_state *regs; 19551 int ret, i; 19552 19553 env->prev_linfo = NULL; 19554 env->pass_cnt++; 19555 19556 state = kzalloc(sizeof(struct bpf_verifier_state), GFP_KERNEL); 19557 if (!state) 19558 return -ENOMEM; 19559 state->curframe = 0; 19560 state->speculative = false; 19561 state->branches = 1; 19562 state->frame[0] = kzalloc(sizeof(struct bpf_func_state), GFP_KERNEL); 19563 if (!state->frame[0]) { 19564 kfree(state); 19565 return -ENOMEM; 19566 } 19567 env->cur_state = state; 19568 init_func_state(env, state->frame[0], 19569 BPF_MAIN_FUNC /* callsite */, 19570 0 /* frameno */, 19571 subprog); 19572 state->first_insn_idx = env->subprog_info[subprog].start; 19573 state->last_insn_idx = -1; 19574 19575 regs = state->frame[state->curframe]->regs; 19576 if (subprog || env->prog->type == BPF_PROG_TYPE_EXT) { 19577 ret = btf_prepare_func_args(env, subprog, regs); 19578 if (ret) 19579 goto out; 19580 for (i = BPF_REG_1; i <= BPF_REG_5; i++) { 19581 if (regs[i].type == PTR_TO_CTX) 19582 mark_reg_known_zero(env, regs, i); 19583 else if (regs[i].type == SCALAR_VALUE) 19584 mark_reg_unknown(env, regs, i); 19585 else if (base_type(regs[i].type) == PTR_TO_MEM) { 19586 const u32 mem_size = regs[i].mem_size; 19587 19588 mark_reg_known_zero(env, regs, i); 19589 regs[i].mem_size = mem_size; 19590 regs[i].id = ++env->id_gen; 19591 } 19592 } 19593 } else { 19594 /* 1st arg to a function */ 19595 regs[BPF_REG_1].type = PTR_TO_CTX; 19596 mark_reg_known_zero(env, regs, BPF_REG_1); 19597 ret = btf_check_subprog_arg_match(env, subprog, regs); 19598 if (ret == -EFAULT) 19599 /* unlikely verifier bug. abort. 19600 * ret == 0 and ret < 0 are sadly acceptable for 19601 * main() function due to backward compatibility. 19602 * Like socket filter program may be written as: 19603 * int bpf_prog(struct pt_regs *ctx) 19604 * and never dereference that ctx in the program. 19605 * 'struct pt_regs' is a type mismatch for socket 19606 * filter that should be using 'struct __sk_buff'. 19607 */ 19608 goto out; 19609 } 19610 19611 ret = do_check(env); 19612 out: 19613 /* check for NULL is necessary, since cur_state can be freed inside 19614 * do_check() under memory pressure. 19615 */ 19616 if (env->cur_state) { 19617 free_verifier_state(env->cur_state, true); 19618 env->cur_state = NULL; 19619 } 19620 while (!pop_stack(env, NULL, NULL, false)); 19621 if (!ret && pop_log) 19622 bpf_vlog_reset(&env->log, 0); 19623 free_states(env); 19624 return ret; 19625 } 19626 19627 /* Verify all global functions in a BPF program one by one based on their BTF. 19628 * All global functions must pass verification. Otherwise the whole program is rejected. 19629 * Consider: 19630 * int bar(int); 19631 * int foo(int f) 19632 * { 19633 * return bar(f); 19634 * } 19635 * int bar(int b) 19636 * { 19637 * ... 19638 * } 19639 * foo() will be verified first for R1=any_scalar_value. During verification it 19640 * will be assumed that bar() already verified successfully and call to bar() 19641 * from foo() will be checked for type match only. Later bar() will be verified 19642 * independently to check that it's safe for R1=any_scalar_value. 19643 */ 19644 static int do_check_subprogs(struct bpf_verifier_env *env) 19645 { 19646 struct bpf_prog_aux *aux = env->prog->aux; 19647 int i, ret; 19648 19649 if (!aux->func_info) 19650 return 0; 19651 19652 for (i = 1; i < env->subprog_cnt; i++) { 19653 if (aux->func_info_aux[i].linkage != BTF_FUNC_GLOBAL) 19654 continue; 19655 env->insn_idx = env->subprog_info[i].start; 19656 WARN_ON_ONCE(env->insn_idx == 0); 19657 ret = do_check_common(env, i); 19658 if (ret) { 19659 return ret; 19660 } else if (env->log.level & BPF_LOG_LEVEL) { 19661 verbose(env, 19662 "Func#%d is safe for any args that match its prototype\n", 19663 i); 19664 } 19665 } 19666 return 0; 19667 } 19668 19669 static int do_check_main(struct bpf_verifier_env *env) 19670 { 19671 int ret; 19672 19673 env->insn_idx = 0; 19674 ret = do_check_common(env, 0); 19675 if (!ret) 19676 env->prog->aux->stack_depth = env->subprog_info[0].stack_depth; 19677 return ret; 19678 } 19679 19680 19681 static void print_verification_stats(struct bpf_verifier_env *env) 19682 { 19683 int i; 19684 19685 if (env->log.level & BPF_LOG_STATS) { 19686 verbose(env, "verification time %lld usec\n", 19687 div_u64(env->verification_time, 1000)); 19688 verbose(env, "stack depth "); 19689 for (i = 0; i < env->subprog_cnt; i++) { 19690 u32 depth = env->subprog_info[i].stack_depth; 19691 19692 verbose(env, "%d", depth); 19693 if (i + 1 < env->subprog_cnt) 19694 verbose(env, "+"); 19695 } 19696 verbose(env, "\n"); 19697 } 19698 verbose(env, "processed %d insns (limit %d) max_states_per_insn %d " 19699 "total_states %d peak_states %d mark_read %d\n", 19700 env->insn_processed, BPF_COMPLEXITY_LIMIT_INSNS, 19701 env->max_states_per_insn, env->total_states, 19702 env->peak_states, env->longest_mark_read_walk); 19703 } 19704 19705 static int check_struct_ops_btf_id(struct bpf_verifier_env *env) 19706 { 19707 const struct btf_type *t, *func_proto; 19708 const struct bpf_struct_ops *st_ops; 19709 const struct btf_member *member; 19710 struct bpf_prog *prog = env->prog; 19711 u32 btf_id, member_idx; 19712 const char *mname; 19713 19714 if (!prog->gpl_compatible) { 19715 verbose(env, "struct ops programs must have a GPL compatible license\n"); 19716 return -EINVAL; 19717 } 19718 19719 btf_id = prog->aux->attach_btf_id; 19720 st_ops = bpf_struct_ops_find(btf_id); 19721 if (!st_ops) { 19722 verbose(env, "attach_btf_id %u is not a supported struct\n", 19723 btf_id); 19724 return -ENOTSUPP; 19725 } 19726 19727 t = st_ops->type; 19728 member_idx = prog->expected_attach_type; 19729 if (member_idx >= btf_type_vlen(t)) { 19730 verbose(env, "attach to invalid member idx %u of struct %s\n", 19731 member_idx, st_ops->name); 19732 return -EINVAL; 19733 } 19734 19735 member = &btf_type_member(t)[member_idx]; 19736 mname = btf_name_by_offset(btf_vmlinux, member->name_off); 19737 func_proto = btf_type_resolve_func_ptr(btf_vmlinux, member->type, 19738 NULL); 19739 if (!func_proto) { 19740 verbose(env, "attach to invalid member %s(@idx %u) of struct %s\n", 19741 mname, member_idx, st_ops->name); 19742 return -EINVAL; 19743 } 19744 19745 if (st_ops->check_member) { 19746 int err = st_ops->check_member(t, member, prog); 19747 19748 if (err) { 19749 verbose(env, "attach to unsupported member %s of struct %s\n", 19750 mname, st_ops->name); 19751 return err; 19752 } 19753 } 19754 19755 prog->aux->attach_func_proto = func_proto; 19756 prog->aux->attach_func_name = mname; 19757 env->ops = st_ops->verifier_ops; 19758 19759 return 0; 19760 } 19761 #define SECURITY_PREFIX "security_" 19762 19763 static int check_attach_modify_return(unsigned long addr, const char *func_name) 19764 { 19765 if (within_error_injection_list(addr) || 19766 !strncmp(SECURITY_PREFIX, func_name, sizeof(SECURITY_PREFIX) - 1)) 19767 return 0; 19768 19769 return -EINVAL; 19770 } 19771 19772 /* list of non-sleepable functions that are otherwise on 19773 * ALLOW_ERROR_INJECTION list 19774 */ 19775 BTF_SET_START(btf_non_sleepable_error_inject) 19776 /* Three functions below can be called from sleepable and non-sleepable context. 19777 * Assume non-sleepable from bpf safety point of view. 19778 */ 19779 BTF_ID(func, __filemap_add_folio) 19780 BTF_ID(func, should_fail_alloc_page) 19781 BTF_ID(func, should_failslab) 19782 BTF_SET_END(btf_non_sleepable_error_inject) 19783 19784 static int check_non_sleepable_error_inject(u32 btf_id) 19785 { 19786 return btf_id_set_contains(&btf_non_sleepable_error_inject, btf_id); 19787 } 19788 19789 int bpf_check_attach_target(struct bpf_verifier_log *log, 19790 const struct bpf_prog *prog, 19791 const struct bpf_prog *tgt_prog, 19792 u32 btf_id, 19793 struct bpf_attach_target_info *tgt_info) 19794 { 19795 bool prog_extension = prog->type == BPF_PROG_TYPE_EXT; 19796 const char prefix[] = "btf_trace_"; 19797 int ret = 0, subprog = -1, i; 19798 const struct btf_type *t; 19799 bool conservative = true; 19800 const char *tname; 19801 struct btf *btf; 19802 long addr = 0; 19803 struct module *mod = NULL; 19804 19805 if (!btf_id) { 19806 bpf_log(log, "Tracing programs must provide btf_id\n"); 19807 return -EINVAL; 19808 } 19809 btf = tgt_prog ? tgt_prog->aux->btf : prog->aux->attach_btf; 19810 if (!btf) { 19811 bpf_log(log, 19812 "FENTRY/FEXIT program can only be attached to another program annotated with BTF\n"); 19813 return -EINVAL; 19814 } 19815 t = btf_type_by_id(btf, btf_id); 19816 if (!t) { 19817 bpf_log(log, "attach_btf_id %u is invalid\n", btf_id); 19818 return -EINVAL; 19819 } 19820 tname = btf_name_by_offset(btf, t->name_off); 19821 if (!tname) { 19822 bpf_log(log, "attach_btf_id %u doesn't have a name\n", btf_id); 19823 return -EINVAL; 19824 } 19825 if (tgt_prog) { 19826 struct bpf_prog_aux *aux = tgt_prog->aux; 19827 19828 if (bpf_prog_is_dev_bound(prog->aux) && 19829 !bpf_prog_dev_bound_match(prog, tgt_prog)) { 19830 bpf_log(log, "Target program bound device mismatch"); 19831 return -EINVAL; 19832 } 19833 19834 for (i = 0; i < aux->func_info_cnt; i++) 19835 if (aux->func_info[i].type_id == btf_id) { 19836 subprog = i; 19837 break; 19838 } 19839 if (subprog == -1) { 19840 bpf_log(log, "Subprog %s doesn't exist\n", tname); 19841 return -EINVAL; 19842 } 19843 conservative = aux->func_info_aux[subprog].unreliable; 19844 if (prog_extension) { 19845 if (conservative) { 19846 bpf_log(log, 19847 "Cannot replace static functions\n"); 19848 return -EINVAL; 19849 } 19850 if (!prog->jit_requested) { 19851 bpf_log(log, 19852 "Extension programs should be JITed\n"); 19853 return -EINVAL; 19854 } 19855 } 19856 if (!tgt_prog->jited) { 19857 bpf_log(log, "Can attach to only JITed progs\n"); 19858 return -EINVAL; 19859 } 19860 if (tgt_prog->type == prog->type) { 19861 /* Cannot fentry/fexit another fentry/fexit program. 19862 * Cannot attach program extension to another extension. 19863 * It's ok to attach fentry/fexit to extension program. 19864 */ 19865 bpf_log(log, "Cannot recursively attach\n"); 19866 return -EINVAL; 19867 } 19868 if (tgt_prog->type == BPF_PROG_TYPE_TRACING && 19869 prog_extension && 19870 (tgt_prog->expected_attach_type == BPF_TRACE_FENTRY || 19871 tgt_prog->expected_attach_type == BPF_TRACE_FEXIT)) { 19872 /* Program extensions can extend all program types 19873 * except fentry/fexit. The reason is the following. 19874 * The fentry/fexit programs are used for performance 19875 * analysis, stats and can be attached to any program 19876 * type except themselves. When extension program is 19877 * replacing XDP function it is necessary to allow 19878 * performance analysis of all functions. Both original 19879 * XDP program and its program extension. Hence 19880 * attaching fentry/fexit to BPF_PROG_TYPE_EXT is 19881 * allowed. If extending of fentry/fexit was allowed it 19882 * would be possible to create long call chain 19883 * fentry->extension->fentry->extension beyond 19884 * reasonable stack size. Hence extending fentry is not 19885 * allowed. 19886 */ 19887 bpf_log(log, "Cannot extend fentry/fexit\n"); 19888 return -EINVAL; 19889 } 19890 } else { 19891 if (prog_extension) { 19892 bpf_log(log, "Cannot replace kernel functions\n"); 19893 return -EINVAL; 19894 } 19895 } 19896 19897 switch (prog->expected_attach_type) { 19898 case BPF_TRACE_RAW_TP: 19899 if (tgt_prog) { 19900 bpf_log(log, 19901 "Only FENTRY/FEXIT progs are attachable to another BPF prog\n"); 19902 return -EINVAL; 19903 } 19904 if (!btf_type_is_typedef(t)) { 19905 bpf_log(log, "attach_btf_id %u is not a typedef\n", 19906 btf_id); 19907 return -EINVAL; 19908 } 19909 if (strncmp(prefix, tname, sizeof(prefix) - 1)) { 19910 bpf_log(log, "attach_btf_id %u points to wrong type name %s\n", 19911 btf_id, tname); 19912 return -EINVAL; 19913 } 19914 tname += sizeof(prefix) - 1; 19915 t = btf_type_by_id(btf, t->type); 19916 if (!btf_type_is_ptr(t)) 19917 /* should never happen in valid vmlinux build */ 19918 return -EINVAL; 19919 t = btf_type_by_id(btf, t->type); 19920 if (!btf_type_is_func_proto(t)) 19921 /* should never happen in valid vmlinux build */ 19922 return -EINVAL; 19923 19924 break; 19925 case BPF_TRACE_ITER: 19926 if (!btf_type_is_func(t)) { 19927 bpf_log(log, "attach_btf_id %u is not a function\n", 19928 btf_id); 19929 return -EINVAL; 19930 } 19931 t = btf_type_by_id(btf, t->type); 19932 if (!btf_type_is_func_proto(t)) 19933 return -EINVAL; 19934 ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel); 19935 if (ret) 19936 return ret; 19937 break; 19938 default: 19939 if (!prog_extension) 19940 return -EINVAL; 19941 fallthrough; 19942 case BPF_MODIFY_RETURN: 19943 case BPF_LSM_MAC: 19944 case BPF_LSM_CGROUP: 19945 case BPF_TRACE_FENTRY: 19946 case BPF_TRACE_FEXIT: 19947 if (!btf_type_is_func(t)) { 19948 bpf_log(log, "attach_btf_id %u is not a function\n", 19949 btf_id); 19950 return -EINVAL; 19951 } 19952 if (prog_extension && 19953 btf_check_type_match(log, prog, btf, t)) 19954 return -EINVAL; 19955 t = btf_type_by_id(btf, t->type); 19956 if (!btf_type_is_func_proto(t)) 19957 return -EINVAL; 19958 19959 if ((prog->aux->saved_dst_prog_type || prog->aux->saved_dst_attach_type) && 19960 (!tgt_prog || prog->aux->saved_dst_prog_type != tgt_prog->type || 19961 prog->aux->saved_dst_attach_type != tgt_prog->expected_attach_type)) 19962 return -EINVAL; 19963 19964 if (tgt_prog && conservative) 19965 t = NULL; 19966 19967 ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel); 19968 if (ret < 0) 19969 return ret; 19970 19971 if (tgt_prog) { 19972 if (subprog == 0) 19973 addr = (long) tgt_prog->bpf_func; 19974 else 19975 addr = (long) tgt_prog->aux->func[subprog]->bpf_func; 19976 } else { 19977 if (btf_is_module(btf)) { 19978 mod = btf_try_get_module(btf); 19979 if (mod) 19980 addr = find_kallsyms_symbol_value(mod, tname); 19981 else 19982 addr = 0; 19983 } else { 19984 addr = kallsyms_lookup_name(tname); 19985 } 19986 if (!addr) { 19987 module_put(mod); 19988 bpf_log(log, 19989 "The address of function %s cannot be found\n", 19990 tname); 19991 return -ENOENT; 19992 } 19993 } 19994 19995 if (prog->aux->sleepable) { 19996 ret = -EINVAL; 19997 switch (prog->type) { 19998 case BPF_PROG_TYPE_TRACING: 19999 20000 /* fentry/fexit/fmod_ret progs can be sleepable if they are 20001 * attached to ALLOW_ERROR_INJECTION and are not in denylist. 20002 */ 20003 if (!check_non_sleepable_error_inject(btf_id) && 20004 within_error_injection_list(addr)) 20005 ret = 0; 20006 /* fentry/fexit/fmod_ret progs can also be sleepable if they are 20007 * in the fmodret id set with the KF_SLEEPABLE flag. 20008 */ 20009 else { 20010 u32 *flags = btf_kfunc_is_modify_return(btf, btf_id, 20011 prog); 20012 20013 if (flags && (*flags & KF_SLEEPABLE)) 20014 ret = 0; 20015 } 20016 break; 20017 case BPF_PROG_TYPE_LSM: 20018 /* LSM progs check that they are attached to bpf_lsm_*() funcs. 20019 * Only some of them are sleepable. 20020 */ 20021 if (bpf_lsm_is_sleepable_hook(btf_id)) 20022 ret = 0; 20023 break; 20024 default: 20025 break; 20026 } 20027 if (ret) { 20028 module_put(mod); 20029 bpf_log(log, "%s is not sleepable\n", tname); 20030 return ret; 20031 } 20032 } else if (prog->expected_attach_type == BPF_MODIFY_RETURN) { 20033 if (tgt_prog) { 20034 module_put(mod); 20035 bpf_log(log, "can't modify return codes of BPF programs\n"); 20036 return -EINVAL; 20037 } 20038 ret = -EINVAL; 20039 if (btf_kfunc_is_modify_return(btf, btf_id, prog) || 20040 !check_attach_modify_return(addr, tname)) 20041 ret = 0; 20042 if (ret) { 20043 module_put(mod); 20044 bpf_log(log, "%s() is not modifiable\n", tname); 20045 return ret; 20046 } 20047 } 20048 20049 break; 20050 } 20051 tgt_info->tgt_addr = addr; 20052 tgt_info->tgt_name = tname; 20053 tgt_info->tgt_type = t; 20054 tgt_info->tgt_mod = mod; 20055 return 0; 20056 } 20057 20058 BTF_SET_START(btf_id_deny) 20059 BTF_ID_UNUSED 20060 #ifdef CONFIG_SMP 20061 BTF_ID(func, migrate_disable) 20062 BTF_ID(func, migrate_enable) 20063 #endif 20064 #if !defined CONFIG_PREEMPT_RCU && !defined CONFIG_TINY_RCU 20065 BTF_ID(func, rcu_read_unlock_strict) 20066 #endif 20067 #if defined(CONFIG_DEBUG_PREEMPT) || defined(CONFIG_TRACE_PREEMPT_TOGGLE) 20068 BTF_ID(func, preempt_count_add) 20069 BTF_ID(func, preempt_count_sub) 20070 #endif 20071 #ifdef CONFIG_PREEMPT_RCU 20072 BTF_ID(func, __rcu_read_lock) 20073 BTF_ID(func, __rcu_read_unlock) 20074 #endif 20075 BTF_SET_END(btf_id_deny) 20076 20077 static bool can_be_sleepable(struct bpf_prog *prog) 20078 { 20079 if (prog->type == BPF_PROG_TYPE_TRACING) { 20080 switch (prog->expected_attach_type) { 20081 case BPF_TRACE_FENTRY: 20082 case BPF_TRACE_FEXIT: 20083 case BPF_MODIFY_RETURN: 20084 case BPF_TRACE_ITER: 20085 return true; 20086 default: 20087 return false; 20088 } 20089 } 20090 return prog->type == BPF_PROG_TYPE_LSM || 20091 prog->type == BPF_PROG_TYPE_KPROBE /* only for uprobes */ || 20092 prog->type == BPF_PROG_TYPE_STRUCT_OPS; 20093 } 20094 20095 static int check_attach_btf_id(struct bpf_verifier_env *env) 20096 { 20097 struct bpf_prog *prog = env->prog; 20098 struct bpf_prog *tgt_prog = prog->aux->dst_prog; 20099 struct bpf_attach_target_info tgt_info = {}; 20100 u32 btf_id = prog->aux->attach_btf_id; 20101 struct bpf_trampoline *tr; 20102 int ret; 20103 u64 key; 20104 20105 if (prog->type == BPF_PROG_TYPE_SYSCALL) { 20106 if (prog->aux->sleepable) 20107 /* attach_btf_id checked to be zero already */ 20108 return 0; 20109 verbose(env, "Syscall programs can only be sleepable\n"); 20110 return -EINVAL; 20111 } 20112 20113 if (prog->aux->sleepable && !can_be_sleepable(prog)) { 20114 verbose(env, "Only fentry/fexit/fmod_ret, lsm, iter, uprobe, and struct_ops programs can be sleepable\n"); 20115 return -EINVAL; 20116 } 20117 20118 if (prog->type == BPF_PROG_TYPE_STRUCT_OPS) 20119 return check_struct_ops_btf_id(env); 20120 20121 if (prog->type != BPF_PROG_TYPE_TRACING && 20122 prog->type != BPF_PROG_TYPE_LSM && 20123 prog->type != BPF_PROG_TYPE_EXT) 20124 return 0; 20125 20126 ret = bpf_check_attach_target(&env->log, prog, tgt_prog, btf_id, &tgt_info); 20127 if (ret) 20128 return ret; 20129 20130 if (tgt_prog && prog->type == BPF_PROG_TYPE_EXT) { 20131 /* to make freplace equivalent to their targets, they need to 20132 * inherit env->ops and expected_attach_type for the rest of the 20133 * verification 20134 */ 20135 env->ops = bpf_verifier_ops[tgt_prog->type]; 20136 prog->expected_attach_type = tgt_prog->expected_attach_type; 20137 } 20138 20139 /* store info about the attachment target that will be used later */ 20140 prog->aux->attach_func_proto = tgt_info.tgt_type; 20141 prog->aux->attach_func_name = tgt_info.tgt_name; 20142 prog->aux->mod = tgt_info.tgt_mod; 20143 20144 if (tgt_prog) { 20145 prog->aux->saved_dst_prog_type = tgt_prog->type; 20146 prog->aux->saved_dst_attach_type = tgt_prog->expected_attach_type; 20147 } 20148 20149 if (prog->expected_attach_type == BPF_TRACE_RAW_TP) { 20150 prog->aux->attach_btf_trace = true; 20151 return 0; 20152 } else if (prog->expected_attach_type == BPF_TRACE_ITER) { 20153 if (!bpf_iter_prog_supported(prog)) 20154 return -EINVAL; 20155 return 0; 20156 } 20157 20158 if (prog->type == BPF_PROG_TYPE_LSM) { 20159 ret = bpf_lsm_verify_prog(&env->log, prog); 20160 if (ret < 0) 20161 return ret; 20162 } else if (prog->type == BPF_PROG_TYPE_TRACING && 20163 btf_id_set_contains(&btf_id_deny, btf_id)) { 20164 return -EINVAL; 20165 } 20166 20167 key = bpf_trampoline_compute_key(tgt_prog, prog->aux->attach_btf, btf_id); 20168 tr = bpf_trampoline_get(key, &tgt_info); 20169 if (!tr) 20170 return -ENOMEM; 20171 20172 if (tgt_prog && tgt_prog->aux->tail_call_reachable) 20173 tr->flags = BPF_TRAMP_F_TAIL_CALL_CTX; 20174 20175 prog->aux->dst_trampoline = tr; 20176 return 0; 20177 } 20178 20179 struct btf *bpf_get_btf_vmlinux(void) 20180 { 20181 if (!btf_vmlinux && IS_ENABLED(CONFIG_DEBUG_INFO_BTF)) { 20182 mutex_lock(&bpf_verifier_lock); 20183 if (!btf_vmlinux) 20184 btf_vmlinux = btf_parse_vmlinux(); 20185 mutex_unlock(&bpf_verifier_lock); 20186 } 20187 return btf_vmlinux; 20188 } 20189 20190 int bpf_check(struct bpf_prog **prog, union bpf_attr *attr, bpfptr_t uattr, __u32 uattr_size) 20191 { 20192 u64 start_time = ktime_get_ns(); 20193 struct bpf_verifier_env *env; 20194 int i, len, ret = -EINVAL, err; 20195 u32 log_true_size; 20196 bool is_priv; 20197 20198 /* no program is valid */ 20199 if (ARRAY_SIZE(bpf_verifier_ops) == 0) 20200 return -EINVAL; 20201 20202 /* 'struct bpf_verifier_env' can be global, but since it's not small, 20203 * allocate/free it every time bpf_check() is called 20204 */ 20205 env = kzalloc(sizeof(struct bpf_verifier_env), GFP_KERNEL); 20206 if (!env) 20207 return -ENOMEM; 20208 20209 env->bt.env = env; 20210 20211 len = (*prog)->len; 20212 env->insn_aux_data = 20213 vzalloc(array_size(sizeof(struct bpf_insn_aux_data), len)); 20214 ret = -ENOMEM; 20215 if (!env->insn_aux_data) 20216 goto err_free_env; 20217 for (i = 0; i < len; i++) 20218 env->insn_aux_data[i].orig_idx = i; 20219 env->prog = *prog; 20220 env->ops = bpf_verifier_ops[env->prog->type]; 20221 env->fd_array = make_bpfptr(attr->fd_array, uattr.is_kernel); 20222 is_priv = bpf_capable(); 20223 20224 bpf_get_btf_vmlinux(); 20225 20226 /* grab the mutex to protect few globals used by verifier */ 20227 if (!is_priv) 20228 mutex_lock(&bpf_verifier_lock); 20229 20230 /* user could have requested verbose verifier output 20231 * and supplied buffer to store the verification trace 20232 */ 20233 ret = bpf_vlog_init(&env->log, attr->log_level, 20234 (char __user *) (unsigned long) attr->log_buf, 20235 attr->log_size); 20236 if (ret) 20237 goto err_unlock; 20238 20239 mark_verifier_state_clean(env); 20240 20241 if (IS_ERR(btf_vmlinux)) { 20242 /* Either gcc or pahole or kernel are broken. */ 20243 verbose(env, "in-kernel BTF is malformed\n"); 20244 ret = PTR_ERR(btf_vmlinux); 20245 goto skip_full_check; 20246 } 20247 20248 env->strict_alignment = !!(attr->prog_flags & BPF_F_STRICT_ALIGNMENT); 20249 if (!IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS)) 20250 env->strict_alignment = true; 20251 if (attr->prog_flags & BPF_F_ANY_ALIGNMENT) 20252 env->strict_alignment = false; 20253 20254 env->allow_ptr_leaks = bpf_allow_ptr_leaks(); 20255 env->allow_uninit_stack = bpf_allow_uninit_stack(); 20256 env->bypass_spec_v1 = bpf_bypass_spec_v1(); 20257 env->bypass_spec_v4 = bpf_bypass_spec_v4(); 20258 env->bpf_capable = bpf_capable(); 20259 20260 if (is_priv) 20261 env->test_state_freq = attr->prog_flags & BPF_F_TEST_STATE_FREQ; 20262 20263 env->explored_states = kvcalloc(state_htab_size(env), 20264 sizeof(struct bpf_verifier_state_list *), 20265 GFP_USER); 20266 ret = -ENOMEM; 20267 if (!env->explored_states) 20268 goto skip_full_check; 20269 20270 ret = add_subprog_and_kfunc(env); 20271 if (ret < 0) 20272 goto skip_full_check; 20273 20274 ret = check_subprogs(env); 20275 if (ret < 0) 20276 goto skip_full_check; 20277 20278 ret = check_btf_info(env, attr, uattr); 20279 if (ret < 0) 20280 goto skip_full_check; 20281 20282 ret = check_attach_btf_id(env); 20283 if (ret) 20284 goto skip_full_check; 20285 20286 ret = resolve_pseudo_ldimm64(env); 20287 if (ret < 0) 20288 goto skip_full_check; 20289 20290 if (bpf_prog_is_offloaded(env->prog->aux)) { 20291 ret = bpf_prog_offload_verifier_prep(env->prog); 20292 if (ret) 20293 goto skip_full_check; 20294 } 20295 20296 ret = check_cfg(env); 20297 if (ret < 0) 20298 goto skip_full_check; 20299 20300 ret = do_check_subprogs(env); 20301 ret = ret ?: do_check_main(env); 20302 20303 if (ret == 0 && bpf_prog_is_offloaded(env->prog->aux)) 20304 ret = bpf_prog_offload_finalize(env); 20305 20306 skip_full_check: 20307 kvfree(env->explored_states); 20308 20309 if (ret == 0) 20310 ret = check_max_stack_depth(env); 20311 20312 /* instruction rewrites happen after this point */ 20313 if (ret == 0) 20314 ret = optimize_bpf_loop(env); 20315 20316 if (is_priv) { 20317 if (ret == 0) 20318 opt_hard_wire_dead_code_branches(env); 20319 if (ret == 0) 20320 ret = opt_remove_dead_code(env); 20321 if (ret == 0) 20322 ret = opt_remove_nops(env); 20323 } else { 20324 if (ret == 0) 20325 sanitize_dead_code(env); 20326 } 20327 20328 if (ret == 0) 20329 /* program is valid, convert *(u32*)(ctx + off) accesses */ 20330 ret = convert_ctx_accesses(env); 20331 20332 if (ret == 0) 20333 ret = do_misc_fixups(env); 20334 20335 /* do 32-bit optimization after insn patching has done so those patched 20336 * insns could be handled correctly. 20337 */ 20338 if (ret == 0 && !bpf_prog_is_offloaded(env->prog->aux)) { 20339 ret = opt_subreg_zext_lo32_rnd_hi32(env, attr); 20340 env->prog->aux->verifier_zext = bpf_jit_needs_zext() ? !ret 20341 : false; 20342 } 20343 20344 if (ret == 0) 20345 ret = fixup_call_args(env); 20346 20347 env->verification_time = ktime_get_ns() - start_time; 20348 print_verification_stats(env); 20349 env->prog->aux->verified_insns = env->insn_processed; 20350 20351 /* preserve original error even if log finalization is successful */ 20352 err = bpf_vlog_finalize(&env->log, &log_true_size); 20353 if (err) 20354 ret = err; 20355 20356 if (uattr_size >= offsetofend(union bpf_attr, log_true_size) && 20357 copy_to_bpfptr_offset(uattr, offsetof(union bpf_attr, log_true_size), 20358 &log_true_size, sizeof(log_true_size))) { 20359 ret = -EFAULT; 20360 goto err_release_maps; 20361 } 20362 20363 if (ret) 20364 goto err_release_maps; 20365 20366 if (env->used_map_cnt) { 20367 /* if program passed verifier, update used_maps in bpf_prog_info */ 20368 env->prog->aux->used_maps = kmalloc_array(env->used_map_cnt, 20369 sizeof(env->used_maps[0]), 20370 GFP_KERNEL); 20371 20372 if (!env->prog->aux->used_maps) { 20373 ret = -ENOMEM; 20374 goto err_release_maps; 20375 } 20376 20377 memcpy(env->prog->aux->used_maps, env->used_maps, 20378 sizeof(env->used_maps[0]) * env->used_map_cnt); 20379 env->prog->aux->used_map_cnt = env->used_map_cnt; 20380 } 20381 if (env->used_btf_cnt) { 20382 /* if program passed verifier, update used_btfs in bpf_prog_aux */ 20383 env->prog->aux->used_btfs = kmalloc_array(env->used_btf_cnt, 20384 sizeof(env->used_btfs[0]), 20385 GFP_KERNEL); 20386 if (!env->prog->aux->used_btfs) { 20387 ret = -ENOMEM; 20388 goto err_release_maps; 20389 } 20390 20391 memcpy(env->prog->aux->used_btfs, env->used_btfs, 20392 sizeof(env->used_btfs[0]) * env->used_btf_cnt); 20393 env->prog->aux->used_btf_cnt = env->used_btf_cnt; 20394 } 20395 if (env->used_map_cnt || env->used_btf_cnt) { 20396 /* program is valid. Convert pseudo bpf_ld_imm64 into generic 20397 * bpf_ld_imm64 instructions 20398 */ 20399 convert_pseudo_ld_imm64(env); 20400 } 20401 20402 adjust_btf_func(env); 20403 20404 err_release_maps: 20405 if (!env->prog->aux->used_maps) 20406 /* if we didn't copy map pointers into bpf_prog_info, release 20407 * them now. Otherwise free_used_maps() will release them. 20408 */ 20409 release_maps(env); 20410 if (!env->prog->aux->used_btfs) 20411 release_btfs(env); 20412 20413 /* extension progs temporarily inherit the attach_type of their targets 20414 for verification purposes, so set it back to zero before returning 20415 */ 20416 if (env->prog->type == BPF_PROG_TYPE_EXT) 20417 env->prog->expected_attach_type = 0; 20418 20419 *prog = env->prog; 20420 err_unlock: 20421 if (!is_priv) 20422 mutex_unlock(&bpf_verifier_lock); 20423 vfree(env->insn_aux_data); 20424 err_free_env: 20425 kfree(env); 20426 return ret; 20427 } 20428