1 // SPDX-License-Identifier: GPL-2.0-only 2 /* Copyright (c) 2011-2014 PLUMgrid, http://plumgrid.com 3 * Copyright (c) 2016 Facebook 4 * Copyright (c) 2018 Covalent IO, Inc. http://covalent.io 5 */ 6 #include <uapi/linux/btf.h> 7 #include <linux/bpf-cgroup.h> 8 #include <linux/kernel.h> 9 #include <linux/types.h> 10 #include <linux/slab.h> 11 #include <linux/bpf.h> 12 #include <linux/btf.h> 13 #include <linux/bpf_verifier.h> 14 #include <linux/filter.h> 15 #include <net/netlink.h> 16 #include <linux/file.h> 17 #include <linux/vmalloc.h> 18 #include <linux/stringify.h> 19 #include <linux/bsearch.h> 20 #include <linux/sort.h> 21 #include <linux/perf_event.h> 22 #include <linux/ctype.h> 23 #include <linux/error-injection.h> 24 #include <linux/bpf_lsm.h> 25 #include <linux/btf_ids.h> 26 #include <linux/poison.h> 27 #include <linux/module.h> 28 #include <linux/cpumask.h> 29 #include <linux/bpf_mem_alloc.h> 30 #include <net/xdp.h> 31 32 #include "disasm.h" 33 34 static const struct bpf_verifier_ops * const bpf_verifier_ops[] = { 35 #define BPF_PROG_TYPE(_id, _name, prog_ctx_type, kern_ctx_type) \ 36 [_id] = & _name ## _verifier_ops, 37 #define BPF_MAP_TYPE(_id, _ops) 38 #define BPF_LINK_TYPE(_id, _name) 39 #include <linux/bpf_types.h> 40 #undef BPF_PROG_TYPE 41 #undef BPF_MAP_TYPE 42 #undef BPF_LINK_TYPE 43 }; 44 45 struct bpf_mem_alloc bpf_global_percpu_ma; 46 static bool bpf_global_percpu_ma_set; 47 48 /* bpf_check() is a static code analyzer that walks eBPF program 49 * instruction by instruction and updates register/stack state. 50 * All paths of conditional branches are analyzed until 'bpf_exit' insn. 51 * 52 * The first pass is depth-first-search to check that the program is a DAG. 53 * It rejects the following programs: 54 * - larger than BPF_MAXINSNS insns 55 * - if loop is present (detected via back-edge) 56 * - unreachable insns exist (shouldn't be a forest. program = one function) 57 * - out of bounds or malformed jumps 58 * The second pass is all possible path descent from the 1st insn. 59 * Since it's analyzing all paths through the program, the length of the 60 * analysis is limited to 64k insn, which may be hit even if total number of 61 * insn is less then 4K, but there are too many branches that change stack/regs. 62 * Number of 'branches to be analyzed' is limited to 1k 63 * 64 * On entry to each instruction, each register has a type, and the instruction 65 * changes the types of the registers depending on instruction semantics. 66 * If instruction is BPF_MOV64_REG(BPF_REG_1, BPF_REG_5), then type of R5 is 67 * copied to R1. 68 * 69 * All registers are 64-bit. 70 * R0 - return register 71 * R1-R5 argument passing registers 72 * R6-R9 callee saved registers 73 * R10 - frame pointer read-only 74 * 75 * At the start of BPF program the register R1 contains a pointer to bpf_context 76 * and has type PTR_TO_CTX. 77 * 78 * Verifier tracks arithmetic operations on pointers in case: 79 * BPF_MOV64_REG(BPF_REG_1, BPF_REG_10), 80 * BPF_ALU64_IMM(BPF_ADD, BPF_REG_1, -20), 81 * 1st insn copies R10 (which has FRAME_PTR) type into R1 82 * and 2nd arithmetic instruction is pattern matched to recognize 83 * that it wants to construct a pointer to some element within stack. 84 * So after 2nd insn, the register R1 has type PTR_TO_STACK 85 * (and -20 constant is saved for further stack bounds checking). 86 * Meaning that this reg is a pointer to stack plus known immediate constant. 87 * 88 * Most of the time the registers have SCALAR_VALUE type, which 89 * means the register has some value, but it's not a valid pointer. 90 * (like pointer plus pointer becomes SCALAR_VALUE type) 91 * 92 * When verifier sees load or store instructions the type of base register 93 * can be: PTR_TO_MAP_VALUE, PTR_TO_CTX, PTR_TO_STACK, PTR_TO_SOCKET. These are 94 * four pointer types recognized by check_mem_access() function. 95 * 96 * PTR_TO_MAP_VALUE means that this register is pointing to 'map element value' 97 * and the range of [ptr, ptr + map's value_size) is accessible. 98 * 99 * registers used to pass values to function calls are checked against 100 * function argument constraints. 101 * 102 * ARG_PTR_TO_MAP_KEY is one of such argument constraints. 103 * It means that the register type passed to this function must be 104 * PTR_TO_STACK and it will be used inside the function as 105 * 'pointer to map element key' 106 * 107 * For example the argument constraints for bpf_map_lookup_elem(): 108 * .ret_type = RET_PTR_TO_MAP_VALUE_OR_NULL, 109 * .arg1_type = ARG_CONST_MAP_PTR, 110 * .arg2_type = ARG_PTR_TO_MAP_KEY, 111 * 112 * ret_type says that this function returns 'pointer to map elem value or null' 113 * function expects 1st argument to be a const pointer to 'struct bpf_map' and 114 * 2nd argument should be a pointer to stack, which will be used inside 115 * the helper function as a pointer to map element key. 116 * 117 * On the kernel side the helper function looks like: 118 * u64 bpf_map_lookup_elem(u64 r1, u64 r2, u64 r3, u64 r4, u64 r5) 119 * { 120 * struct bpf_map *map = (struct bpf_map *) (unsigned long) r1; 121 * void *key = (void *) (unsigned long) r2; 122 * void *value; 123 * 124 * here kernel can access 'key' and 'map' pointers safely, knowing that 125 * [key, key + map->key_size) bytes are valid and were initialized on 126 * the stack of eBPF program. 127 * } 128 * 129 * Corresponding eBPF program may look like: 130 * BPF_MOV64_REG(BPF_REG_2, BPF_REG_10), // after this insn R2 type is FRAME_PTR 131 * BPF_ALU64_IMM(BPF_ADD, BPF_REG_2, -4), // after this insn R2 type is PTR_TO_STACK 132 * BPF_LD_MAP_FD(BPF_REG_1, map_fd), // after this insn R1 type is CONST_PTR_TO_MAP 133 * BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0, BPF_FUNC_map_lookup_elem), 134 * here verifier looks at prototype of map_lookup_elem() and sees: 135 * .arg1_type == ARG_CONST_MAP_PTR and R1->type == CONST_PTR_TO_MAP, which is ok, 136 * Now verifier knows that this map has key of R1->map_ptr->key_size bytes 137 * 138 * Then .arg2_type == ARG_PTR_TO_MAP_KEY and R2->type == PTR_TO_STACK, ok so far, 139 * Now verifier checks that [R2, R2 + map's key_size) are within stack limits 140 * and were initialized prior to this call. 141 * If it's ok, then verifier allows this BPF_CALL insn and looks at 142 * .ret_type which is RET_PTR_TO_MAP_VALUE_OR_NULL, so it sets 143 * R0->type = PTR_TO_MAP_VALUE_OR_NULL which means bpf_map_lookup_elem() function 144 * returns either pointer to map value or NULL. 145 * 146 * When type PTR_TO_MAP_VALUE_OR_NULL passes through 'if (reg != 0) goto +off' 147 * insn, the register holding that pointer in the true branch changes state to 148 * PTR_TO_MAP_VALUE and the same register changes state to CONST_IMM in the false 149 * branch. See check_cond_jmp_op(). 150 * 151 * After the call R0 is set to return type of the function and registers R1-R5 152 * are set to NOT_INIT to indicate that they are no longer readable. 153 * 154 * The following reference types represent a potential reference to a kernel 155 * resource which, after first being allocated, must be checked and freed by 156 * the BPF program: 157 * - PTR_TO_SOCKET_OR_NULL, PTR_TO_SOCKET 158 * 159 * When the verifier sees a helper call return a reference type, it allocates a 160 * pointer id for the reference and stores it in the current function state. 161 * Similar to the way that PTR_TO_MAP_VALUE_OR_NULL is converted into 162 * PTR_TO_MAP_VALUE, PTR_TO_SOCKET_OR_NULL becomes PTR_TO_SOCKET when the type 163 * passes through a NULL-check conditional. For the branch wherein the state is 164 * changed to CONST_IMM, the verifier releases the reference. 165 * 166 * For each helper function that allocates a reference, such as 167 * bpf_sk_lookup_tcp(), there is a corresponding release function, such as 168 * bpf_sk_release(). When a reference type passes into the release function, 169 * the verifier also releases the reference. If any unchecked or unreleased 170 * reference remains at the end of the program, the verifier rejects it. 171 */ 172 173 /* verifier_state + insn_idx are pushed to stack when branch is encountered */ 174 struct bpf_verifier_stack_elem { 175 /* verifer state is 'st' 176 * before processing instruction 'insn_idx' 177 * and after processing instruction 'prev_insn_idx' 178 */ 179 struct bpf_verifier_state st; 180 int insn_idx; 181 int prev_insn_idx; 182 struct bpf_verifier_stack_elem *next; 183 /* length of verifier log at the time this state was pushed on stack */ 184 u32 log_pos; 185 }; 186 187 #define BPF_COMPLEXITY_LIMIT_JMP_SEQ 8192 188 #define BPF_COMPLEXITY_LIMIT_STATES 64 189 190 #define BPF_MAP_KEY_POISON (1ULL << 63) 191 #define BPF_MAP_KEY_SEEN (1ULL << 62) 192 193 #define BPF_MAP_PTR_UNPRIV 1UL 194 #define BPF_MAP_PTR_POISON ((void *)((0xeB9FUL << 1) + \ 195 POISON_POINTER_DELTA)) 196 #define BPF_MAP_PTR(X) ((struct bpf_map *)((X) & ~BPF_MAP_PTR_UNPRIV)) 197 198 static int acquire_reference_state(struct bpf_verifier_env *env, int insn_idx); 199 static int release_reference(struct bpf_verifier_env *env, int ref_obj_id); 200 static void invalidate_non_owning_refs(struct bpf_verifier_env *env); 201 static bool in_rbtree_lock_required_cb(struct bpf_verifier_env *env); 202 static int ref_set_non_owning(struct bpf_verifier_env *env, 203 struct bpf_reg_state *reg); 204 static void specialize_kfunc(struct bpf_verifier_env *env, 205 u32 func_id, u16 offset, unsigned long *addr); 206 static bool is_trusted_reg(const struct bpf_reg_state *reg); 207 208 static bool bpf_map_ptr_poisoned(const struct bpf_insn_aux_data *aux) 209 { 210 return BPF_MAP_PTR(aux->map_ptr_state) == BPF_MAP_PTR_POISON; 211 } 212 213 static bool bpf_map_ptr_unpriv(const struct bpf_insn_aux_data *aux) 214 { 215 return aux->map_ptr_state & BPF_MAP_PTR_UNPRIV; 216 } 217 218 static void bpf_map_ptr_store(struct bpf_insn_aux_data *aux, 219 const struct bpf_map *map, bool unpriv) 220 { 221 BUILD_BUG_ON((unsigned long)BPF_MAP_PTR_POISON & BPF_MAP_PTR_UNPRIV); 222 unpriv |= bpf_map_ptr_unpriv(aux); 223 aux->map_ptr_state = (unsigned long)map | 224 (unpriv ? BPF_MAP_PTR_UNPRIV : 0UL); 225 } 226 227 static bool bpf_map_key_poisoned(const struct bpf_insn_aux_data *aux) 228 { 229 return aux->map_key_state & BPF_MAP_KEY_POISON; 230 } 231 232 static bool bpf_map_key_unseen(const struct bpf_insn_aux_data *aux) 233 { 234 return !(aux->map_key_state & BPF_MAP_KEY_SEEN); 235 } 236 237 static u64 bpf_map_key_immediate(const struct bpf_insn_aux_data *aux) 238 { 239 return aux->map_key_state & ~(BPF_MAP_KEY_SEEN | BPF_MAP_KEY_POISON); 240 } 241 242 static void bpf_map_key_store(struct bpf_insn_aux_data *aux, u64 state) 243 { 244 bool poisoned = bpf_map_key_poisoned(aux); 245 246 aux->map_key_state = state | BPF_MAP_KEY_SEEN | 247 (poisoned ? BPF_MAP_KEY_POISON : 0ULL); 248 } 249 250 static bool bpf_helper_call(const struct bpf_insn *insn) 251 { 252 return insn->code == (BPF_JMP | BPF_CALL) && 253 insn->src_reg == 0; 254 } 255 256 static bool bpf_pseudo_call(const struct bpf_insn *insn) 257 { 258 return insn->code == (BPF_JMP | BPF_CALL) && 259 insn->src_reg == BPF_PSEUDO_CALL; 260 } 261 262 static bool bpf_pseudo_kfunc_call(const struct bpf_insn *insn) 263 { 264 return insn->code == (BPF_JMP | BPF_CALL) && 265 insn->src_reg == BPF_PSEUDO_KFUNC_CALL; 266 } 267 268 struct bpf_call_arg_meta { 269 struct bpf_map *map_ptr; 270 bool raw_mode; 271 bool pkt_access; 272 u8 release_regno; 273 int regno; 274 int access_size; 275 int mem_size; 276 u64 msize_max_value; 277 int ref_obj_id; 278 int dynptr_id; 279 int map_uid; 280 int func_id; 281 struct btf *btf; 282 u32 btf_id; 283 struct btf *ret_btf; 284 u32 ret_btf_id; 285 u32 subprogno; 286 struct btf_field *kptr_field; 287 }; 288 289 struct bpf_kfunc_call_arg_meta { 290 /* In parameters */ 291 struct btf *btf; 292 u32 func_id; 293 u32 kfunc_flags; 294 const struct btf_type *func_proto; 295 const char *func_name; 296 /* Out parameters */ 297 u32 ref_obj_id; 298 u8 release_regno; 299 bool r0_rdonly; 300 u32 ret_btf_id; 301 u64 r0_size; 302 u32 subprogno; 303 struct { 304 u64 value; 305 bool found; 306 } arg_constant; 307 308 /* arg_{btf,btf_id,owning_ref} are used by kfunc-specific handling, 309 * generally to pass info about user-defined local kptr types to later 310 * verification logic 311 * bpf_obj_drop/bpf_percpu_obj_drop 312 * Record the local kptr type to be drop'd 313 * bpf_refcount_acquire (via KF_ARG_PTR_TO_REFCOUNTED_KPTR arg type) 314 * Record the local kptr type to be refcount_incr'd and use 315 * arg_owning_ref to determine whether refcount_acquire should be 316 * fallible 317 */ 318 struct btf *arg_btf; 319 u32 arg_btf_id; 320 bool arg_owning_ref; 321 322 struct { 323 struct btf_field *field; 324 } arg_list_head; 325 struct { 326 struct btf_field *field; 327 } arg_rbtree_root; 328 struct { 329 enum bpf_dynptr_type type; 330 u32 id; 331 u32 ref_obj_id; 332 } initialized_dynptr; 333 struct { 334 u8 spi; 335 u8 frameno; 336 } iter; 337 u64 mem_size; 338 }; 339 340 struct btf *btf_vmlinux; 341 342 static const char *btf_type_name(const struct btf *btf, u32 id) 343 { 344 return btf_name_by_offset(btf, btf_type_by_id(btf, id)->name_off); 345 } 346 347 static DEFINE_MUTEX(bpf_verifier_lock); 348 static DEFINE_MUTEX(bpf_percpu_ma_lock); 349 350 __printf(2, 3) static void verbose(void *private_data, const char *fmt, ...) 351 { 352 struct bpf_verifier_env *env = private_data; 353 va_list args; 354 355 if (!bpf_verifier_log_needed(&env->log)) 356 return; 357 358 va_start(args, fmt); 359 bpf_verifier_vlog(&env->log, fmt, args); 360 va_end(args); 361 } 362 363 static void verbose_invalid_scalar(struct bpf_verifier_env *env, 364 struct bpf_reg_state *reg, 365 struct bpf_retval_range range, const char *ctx, 366 const char *reg_name) 367 { 368 bool unknown = true; 369 370 verbose(env, "%s the register %s has", ctx, reg_name); 371 if (reg->smin_value > S64_MIN) { 372 verbose(env, " smin=%lld", reg->smin_value); 373 unknown = false; 374 } 375 if (reg->smax_value < S64_MAX) { 376 verbose(env, " smax=%lld", reg->smax_value); 377 unknown = false; 378 } 379 if (unknown) 380 verbose(env, " unknown scalar value"); 381 verbose(env, " should have been in [%d, %d]\n", range.minval, range.maxval); 382 } 383 384 static bool type_may_be_null(u32 type) 385 { 386 return type & PTR_MAYBE_NULL; 387 } 388 389 static bool reg_not_null(const struct bpf_reg_state *reg) 390 { 391 enum bpf_reg_type type; 392 393 type = reg->type; 394 if (type_may_be_null(type)) 395 return false; 396 397 type = base_type(type); 398 return type == PTR_TO_SOCKET || 399 type == PTR_TO_TCP_SOCK || 400 type == PTR_TO_MAP_VALUE || 401 type == PTR_TO_MAP_KEY || 402 type == PTR_TO_SOCK_COMMON || 403 (type == PTR_TO_BTF_ID && is_trusted_reg(reg)) || 404 type == PTR_TO_MEM; 405 } 406 407 static struct btf_record *reg_btf_record(const struct bpf_reg_state *reg) 408 { 409 struct btf_record *rec = NULL; 410 struct btf_struct_meta *meta; 411 412 if (reg->type == PTR_TO_MAP_VALUE) { 413 rec = reg->map_ptr->record; 414 } else if (type_is_ptr_alloc_obj(reg->type)) { 415 meta = btf_find_struct_meta(reg->btf, reg->btf_id); 416 if (meta) 417 rec = meta->record; 418 } 419 return rec; 420 } 421 422 static bool subprog_is_global(const struct bpf_verifier_env *env, int subprog) 423 { 424 struct bpf_func_info_aux *aux = env->prog->aux->func_info_aux; 425 426 return aux && aux[subprog].linkage == BTF_FUNC_GLOBAL; 427 } 428 429 static const char *subprog_name(const struct bpf_verifier_env *env, int subprog) 430 { 431 struct bpf_func_info *info; 432 433 if (!env->prog->aux->func_info) 434 return ""; 435 436 info = &env->prog->aux->func_info[subprog]; 437 return btf_type_name(env->prog->aux->btf, info->type_id); 438 } 439 440 static struct bpf_func_info_aux *subprog_aux(const struct bpf_verifier_env *env, int subprog) 441 { 442 return &env->prog->aux->func_info_aux[subprog]; 443 } 444 445 static struct bpf_subprog_info *subprog_info(struct bpf_verifier_env *env, int subprog) 446 { 447 return &env->subprog_info[subprog]; 448 } 449 450 static void mark_subprog_exc_cb(struct bpf_verifier_env *env, int subprog) 451 { 452 struct bpf_subprog_info *info = subprog_info(env, subprog); 453 454 info->is_cb = true; 455 info->is_async_cb = true; 456 info->is_exception_cb = true; 457 } 458 459 static bool subprog_is_exc_cb(struct bpf_verifier_env *env, int subprog) 460 { 461 return subprog_info(env, subprog)->is_exception_cb; 462 } 463 464 static bool reg_may_point_to_spin_lock(const struct bpf_reg_state *reg) 465 { 466 return btf_record_has_field(reg_btf_record(reg), BPF_SPIN_LOCK); 467 } 468 469 static bool type_is_rdonly_mem(u32 type) 470 { 471 return type & MEM_RDONLY; 472 } 473 474 static bool is_acquire_function(enum bpf_func_id func_id, 475 const struct bpf_map *map) 476 { 477 enum bpf_map_type map_type = map ? map->map_type : BPF_MAP_TYPE_UNSPEC; 478 479 if (func_id == BPF_FUNC_sk_lookup_tcp || 480 func_id == BPF_FUNC_sk_lookup_udp || 481 func_id == BPF_FUNC_skc_lookup_tcp || 482 func_id == BPF_FUNC_ringbuf_reserve || 483 func_id == BPF_FUNC_kptr_xchg) 484 return true; 485 486 if (func_id == BPF_FUNC_map_lookup_elem && 487 (map_type == BPF_MAP_TYPE_SOCKMAP || 488 map_type == BPF_MAP_TYPE_SOCKHASH)) 489 return true; 490 491 return false; 492 } 493 494 static bool is_ptr_cast_function(enum bpf_func_id func_id) 495 { 496 return func_id == BPF_FUNC_tcp_sock || 497 func_id == BPF_FUNC_sk_fullsock || 498 func_id == BPF_FUNC_skc_to_tcp_sock || 499 func_id == BPF_FUNC_skc_to_tcp6_sock || 500 func_id == BPF_FUNC_skc_to_udp6_sock || 501 func_id == BPF_FUNC_skc_to_mptcp_sock || 502 func_id == BPF_FUNC_skc_to_tcp_timewait_sock || 503 func_id == BPF_FUNC_skc_to_tcp_request_sock; 504 } 505 506 static bool is_dynptr_ref_function(enum bpf_func_id func_id) 507 { 508 return func_id == BPF_FUNC_dynptr_data; 509 } 510 511 static bool is_sync_callback_calling_kfunc(u32 btf_id); 512 static bool is_bpf_throw_kfunc(struct bpf_insn *insn); 513 514 static bool is_sync_callback_calling_function(enum bpf_func_id func_id) 515 { 516 return func_id == BPF_FUNC_for_each_map_elem || 517 func_id == BPF_FUNC_find_vma || 518 func_id == BPF_FUNC_loop || 519 func_id == BPF_FUNC_user_ringbuf_drain; 520 } 521 522 static bool is_async_callback_calling_function(enum bpf_func_id func_id) 523 { 524 return func_id == BPF_FUNC_timer_set_callback; 525 } 526 527 static bool is_callback_calling_function(enum bpf_func_id func_id) 528 { 529 return is_sync_callback_calling_function(func_id) || 530 is_async_callback_calling_function(func_id); 531 } 532 533 static bool is_sync_callback_calling_insn(struct bpf_insn *insn) 534 { 535 return (bpf_helper_call(insn) && is_sync_callback_calling_function(insn->imm)) || 536 (bpf_pseudo_kfunc_call(insn) && is_sync_callback_calling_kfunc(insn->imm)); 537 } 538 539 static bool is_storage_get_function(enum bpf_func_id func_id) 540 { 541 return func_id == BPF_FUNC_sk_storage_get || 542 func_id == BPF_FUNC_inode_storage_get || 543 func_id == BPF_FUNC_task_storage_get || 544 func_id == BPF_FUNC_cgrp_storage_get; 545 } 546 547 static bool helper_multiple_ref_obj_use(enum bpf_func_id func_id, 548 const struct bpf_map *map) 549 { 550 int ref_obj_uses = 0; 551 552 if (is_ptr_cast_function(func_id)) 553 ref_obj_uses++; 554 if (is_acquire_function(func_id, map)) 555 ref_obj_uses++; 556 if (is_dynptr_ref_function(func_id)) 557 ref_obj_uses++; 558 559 return ref_obj_uses > 1; 560 } 561 562 static bool is_cmpxchg_insn(const struct bpf_insn *insn) 563 { 564 return BPF_CLASS(insn->code) == BPF_STX && 565 BPF_MODE(insn->code) == BPF_ATOMIC && 566 insn->imm == BPF_CMPXCHG; 567 } 568 569 static int __get_spi(s32 off) 570 { 571 return (-off - 1) / BPF_REG_SIZE; 572 } 573 574 static struct bpf_func_state *func(struct bpf_verifier_env *env, 575 const struct bpf_reg_state *reg) 576 { 577 struct bpf_verifier_state *cur = env->cur_state; 578 579 return cur->frame[reg->frameno]; 580 } 581 582 static bool is_spi_bounds_valid(struct bpf_func_state *state, int spi, int nr_slots) 583 { 584 int allocated_slots = state->allocated_stack / BPF_REG_SIZE; 585 586 /* We need to check that slots between [spi - nr_slots + 1, spi] are 587 * within [0, allocated_stack). 588 * 589 * Please note that the spi grows downwards. For example, a dynptr 590 * takes the size of two stack slots; the first slot will be at 591 * spi and the second slot will be at spi - 1. 592 */ 593 return spi - nr_slots + 1 >= 0 && spi < allocated_slots; 594 } 595 596 static int stack_slot_obj_get_spi(struct bpf_verifier_env *env, struct bpf_reg_state *reg, 597 const char *obj_kind, int nr_slots) 598 { 599 int off, spi; 600 601 if (!tnum_is_const(reg->var_off)) { 602 verbose(env, "%s has to be at a constant offset\n", obj_kind); 603 return -EINVAL; 604 } 605 606 off = reg->off + reg->var_off.value; 607 if (off % BPF_REG_SIZE) { 608 verbose(env, "cannot pass in %s at an offset=%d\n", obj_kind, off); 609 return -EINVAL; 610 } 611 612 spi = __get_spi(off); 613 if (spi + 1 < nr_slots) { 614 verbose(env, "cannot pass in %s at an offset=%d\n", obj_kind, off); 615 return -EINVAL; 616 } 617 618 if (!is_spi_bounds_valid(func(env, reg), spi, nr_slots)) 619 return -ERANGE; 620 return spi; 621 } 622 623 static int dynptr_get_spi(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 624 { 625 return stack_slot_obj_get_spi(env, reg, "dynptr", BPF_DYNPTR_NR_SLOTS); 626 } 627 628 static int iter_get_spi(struct bpf_verifier_env *env, struct bpf_reg_state *reg, int nr_slots) 629 { 630 return stack_slot_obj_get_spi(env, reg, "iter", nr_slots); 631 } 632 633 static enum bpf_dynptr_type arg_to_dynptr_type(enum bpf_arg_type arg_type) 634 { 635 switch (arg_type & DYNPTR_TYPE_FLAG_MASK) { 636 case DYNPTR_TYPE_LOCAL: 637 return BPF_DYNPTR_TYPE_LOCAL; 638 case DYNPTR_TYPE_RINGBUF: 639 return BPF_DYNPTR_TYPE_RINGBUF; 640 case DYNPTR_TYPE_SKB: 641 return BPF_DYNPTR_TYPE_SKB; 642 case DYNPTR_TYPE_XDP: 643 return BPF_DYNPTR_TYPE_XDP; 644 default: 645 return BPF_DYNPTR_TYPE_INVALID; 646 } 647 } 648 649 static enum bpf_type_flag get_dynptr_type_flag(enum bpf_dynptr_type type) 650 { 651 switch (type) { 652 case BPF_DYNPTR_TYPE_LOCAL: 653 return DYNPTR_TYPE_LOCAL; 654 case BPF_DYNPTR_TYPE_RINGBUF: 655 return DYNPTR_TYPE_RINGBUF; 656 case BPF_DYNPTR_TYPE_SKB: 657 return DYNPTR_TYPE_SKB; 658 case BPF_DYNPTR_TYPE_XDP: 659 return DYNPTR_TYPE_XDP; 660 default: 661 return 0; 662 } 663 } 664 665 static bool dynptr_type_refcounted(enum bpf_dynptr_type type) 666 { 667 return type == BPF_DYNPTR_TYPE_RINGBUF; 668 } 669 670 static void __mark_dynptr_reg(struct bpf_reg_state *reg, 671 enum bpf_dynptr_type type, 672 bool first_slot, int dynptr_id); 673 674 static void __mark_reg_not_init(const struct bpf_verifier_env *env, 675 struct bpf_reg_state *reg); 676 677 static void mark_dynptr_stack_regs(struct bpf_verifier_env *env, 678 struct bpf_reg_state *sreg1, 679 struct bpf_reg_state *sreg2, 680 enum bpf_dynptr_type type) 681 { 682 int id = ++env->id_gen; 683 684 __mark_dynptr_reg(sreg1, type, true, id); 685 __mark_dynptr_reg(sreg2, type, false, id); 686 } 687 688 static void mark_dynptr_cb_reg(struct bpf_verifier_env *env, 689 struct bpf_reg_state *reg, 690 enum bpf_dynptr_type type) 691 { 692 __mark_dynptr_reg(reg, type, true, ++env->id_gen); 693 } 694 695 static int destroy_if_dynptr_stack_slot(struct bpf_verifier_env *env, 696 struct bpf_func_state *state, int spi); 697 698 static int mark_stack_slots_dynptr(struct bpf_verifier_env *env, struct bpf_reg_state *reg, 699 enum bpf_arg_type arg_type, int insn_idx, int clone_ref_obj_id) 700 { 701 struct bpf_func_state *state = func(env, reg); 702 enum bpf_dynptr_type type; 703 int spi, i, err; 704 705 spi = dynptr_get_spi(env, reg); 706 if (spi < 0) 707 return spi; 708 709 /* We cannot assume both spi and spi - 1 belong to the same dynptr, 710 * hence we need to call destroy_if_dynptr_stack_slot twice for both, 711 * to ensure that for the following example: 712 * [d1][d1][d2][d2] 713 * spi 3 2 1 0 714 * So marking spi = 2 should lead to destruction of both d1 and d2. In 715 * case they do belong to same dynptr, second call won't see slot_type 716 * as STACK_DYNPTR and will simply skip destruction. 717 */ 718 err = destroy_if_dynptr_stack_slot(env, state, spi); 719 if (err) 720 return err; 721 err = destroy_if_dynptr_stack_slot(env, state, spi - 1); 722 if (err) 723 return err; 724 725 for (i = 0; i < BPF_REG_SIZE; i++) { 726 state->stack[spi].slot_type[i] = STACK_DYNPTR; 727 state->stack[spi - 1].slot_type[i] = STACK_DYNPTR; 728 } 729 730 type = arg_to_dynptr_type(arg_type); 731 if (type == BPF_DYNPTR_TYPE_INVALID) 732 return -EINVAL; 733 734 mark_dynptr_stack_regs(env, &state->stack[spi].spilled_ptr, 735 &state->stack[spi - 1].spilled_ptr, type); 736 737 if (dynptr_type_refcounted(type)) { 738 /* The id is used to track proper releasing */ 739 int id; 740 741 if (clone_ref_obj_id) 742 id = clone_ref_obj_id; 743 else 744 id = acquire_reference_state(env, insn_idx); 745 746 if (id < 0) 747 return id; 748 749 state->stack[spi].spilled_ptr.ref_obj_id = id; 750 state->stack[spi - 1].spilled_ptr.ref_obj_id = id; 751 } 752 753 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN; 754 state->stack[spi - 1].spilled_ptr.live |= REG_LIVE_WRITTEN; 755 756 return 0; 757 } 758 759 static void invalidate_dynptr(struct bpf_verifier_env *env, struct bpf_func_state *state, int spi) 760 { 761 int i; 762 763 for (i = 0; i < BPF_REG_SIZE; i++) { 764 state->stack[spi].slot_type[i] = STACK_INVALID; 765 state->stack[spi - 1].slot_type[i] = STACK_INVALID; 766 } 767 768 __mark_reg_not_init(env, &state->stack[spi].spilled_ptr); 769 __mark_reg_not_init(env, &state->stack[spi - 1].spilled_ptr); 770 771 /* Why do we need to set REG_LIVE_WRITTEN for STACK_INVALID slot? 772 * 773 * While we don't allow reading STACK_INVALID, it is still possible to 774 * do <8 byte writes marking some but not all slots as STACK_MISC. Then, 775 * helpers or insns can do partial read of that part without failing, 776 * but check_stack_range_initialized, check_stack_read_var_off, and 777 * check_stack_read_fixed_off will do mark_reg_read for all 8-bytes of 778 * the slot conservatively. Hence we need to prevent those liveness 779 * marking walks. 780 * 781 * This was not a problem before because STACK_INVALID is only set by 782 * default (where the default reg state has its reg->parent as NULL), or 783 * in clean_live_states after REG_LIVE_DONE (at which point 784 * mark_reg_read won't walk reg->parent chain), but not randomly during 785 * verifier state exploration (like we did above). Hence, for our case 786 * parentage chain will still be live (i.e. reg->parent may be 787 * non-NULL), while earlier reg->parent was NULL, so we need 788 * REG_LIVE_WRITTEN to screen off read marker propagation when it is 789 * done later on reads or by mark_dynptr_read as well to unnecessary 790 * mark registers in verifier state. 791 */ 792 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN; 793 state->stack[spi - 1].spilled_ptr.live |= REG_LIVE_WRITTEN; 794 } 795 796 static int unmark_stack_slots_dynptr(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 797 { 798 struct bpf_func_state *state = func(env, reg); 799 int spi, ref_obj_id, i; 800 801 spi = dynptr_get_spi(env, reg); 802 if (spi < 0) 803 return spi; 804 805 if (!dynptr_type_refcounted(state->stack[spi].spilled_ptr.dynptr.type)) { 806 invalidate_dynptr(env, state, spi); 807 return 0; 808 } 809 810 ref_obj_id = state->stack[spi].spilled_ptr.ref_obj_id; 811 812 /* If the dynptr has a ref_obj_id, then we need to invalidate 813 * two things: 814 * 815 * 1) Any dynptrs with a matching ref_obj_id (clones) 816 * 2) Any slices derived from this dynptr. 817 */ 818 819 /* Invalidate any slices associated with this dynptr */ 820 WARN_ON_ONCE(release_reference(env, ref_obj_id)); 821 822 /* Invalidate any dynptr clones */ 823 for (i = 1; i < state->allocated_stack / BPF_REG_SIZE; i++) { 824 if (state->stack[i].spilled_ptr.ref_obj_id != ref_obj_id) 825 continue; 826 827 /* it should always be the case that if the ref obj id 828 * matches then the stack slot also belongs to a 829 * dynptr 830 */ 831 if (state->stack[i].slot_type[0] != STACK_DYNPTR) { 832 verbose(env, "verifier internal error: misconfigured ref_obj_id\n"); 833 return -EFAULT; 834 } 835 if (state->stack[i].spilled_ptr.dynptr.first_slot) 836 invalidate_dynptr(env, state, i); 837 } 838 839 return 0; 840 } 841 842 static void __mark_reg_unknown(const struct bpf_verifier_env *env, 843 struct bpf_reg_state *reg); 844 845 static void mark_reg_invalid(const struct bpf_verifier_env *env, struct bpf_reg_state *reg) 846 { 847 if (!env->allow_ptr_leaks) 848 __mark_reg_not_init(env, reg); 849 else 850 __mark_reg_unknown(env, reg); 851 } 852 853 static int destroy_if_dynptr_stack_slot(struct bpf_verifier_env *env, 854 struct bpf_func_state *state, int spi) 855 { 856 struct bpf_func_state *fstate; 857 struct bpf_reg_state *dreg; 858 int i, dynptr_id; 859 860 /* We always ensure that STACK_DYNPTR is never set partially, 861 * hence just checking for slot_type[0] is enough. This is 862 * different for STACK_SPILL, where it may be only set for 863 * 1 byte, so code has to use is_spilled_reg. 864 */ 865 if (state->stack[spi].slot_type[0] != STACK_DYNPTR) 866 return 0; 867 868 /* Reposition spi to first slot */ 869 if (!state->stack[spi].spilled_ptr.dynptr.first_slot) 870 spi = spi + 1; 871 872 if (dynptr_type_refcounted(state->stack[spi].spilled_ptr.dynptr.type)) { 873 verbose(env, "cannot overwrite referenced dynptr\n"); 874 return -EINVAL; 875 } 876 877 mark_stack_slot_scratched(env, spi); 878 mark_stack_slot_scratched(env, spi - 1); 879 880 /* Writing partially to one dynptr stack slot destroys both. */ 881 for (i = 0; i < BPF_REG_SIZE; i++) { 882 state->stack[spi].slot_type[i] = STACK_INVALID; 883 state->stack[spi - 1].slot_type[i] = STACK_INVALID; 884 } 885 886 dynptr_id = state->stack[spi].spilled_ptr.id; 887 /* Invalidate any slices associated with this dynptr */ 888 bpf_for_each_reg_in_vstate(env->cur_state, fstate, dreg, ({ 889 /* Dynptr slices are only PTR_TO_MEM_OR_NULL and PTR_TO_MEM */ 890 if (dreg->type != (PTR_TO_MEM | PTR_MAYBE_NULL) && dreg->type != PTR_TO_MEM) 891 continue; 892 if (dreg->dynptr_id == dynptr_id) 893 mark_reg_invalid(env, dreg); 894 })); 895 896 /* Do not release reference state, we are destroying dynptr on stack, 897 * not using some helper to release it. Just reset register. 898 */ 899 __mark_reg_not_init(env, &state->stack[spi].spilled_ptr); 900 __mark_reg_not_init(env, &state->stack[spi - 1].spilled_ptr); 901 902 /* Same reason as unmark_stack_slots_dynptr above */ 903 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN; 904 state->stack[spi - 1].spilled_ptr.live |= REG_LIVE_WRITTEN; 905 906 return 0; 907 } 908 909 static bool is_dynptr_reg_valid_uninit(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 910 { 911 int spi; 912 913 if (reg->type == CONST_PTR_TO_DYNPTR) 914 return false; 915 916 spi = dynptr_get_spi(env, reg); 917 918 /* -ERANGE (i.e. spi not falling into allocated stack slots) isn't an 919 * error because this just means the stack state hasn't been updated yet. 920 * We will do check_mem_access to check and update stack bounds later. 921 */ 922 if (spi < 0 && spi != -ERANGE) 923 return false; 924 925 /* We don't need to check if the stack slots are marked by previous 926 * dynptr initializations because we allow overwriting existing unreferenced 927 * STACK_DYNPTR slots, see mark_stack_slots_dynptr which calls 928 * destroy_if_dynptr_stack_slot to ensure dynptr objects at the slots we are 929 * touching are completely destructed before we reinitialize them for a new 930 * one. For referenced ones, destroy_if_dynptr_stack_slot returns an error early 931 * instead of delaying it until the end where the user will get "Unreleased 932 * reference" error. 933 */ 934 return true; 935 } 936 937 static bool is_dynptr_reg_valid_init(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 938 { 939 struct bpf_func_state *state = func(env, reg); 940 int i, spi; 941 942 /* This already represents first slot of initialized bpf_dynptr. 943 * 944 * CONST_PTR_TO_DYNPTR already has fixed and var_off as 0 due to 945 * check_func_arg_reg_off's logic, so we don't need to check its 946 * offset and alignment. 947 */ 948 if (reg->type == CONST_PTR_TO_DYNPTR) 949 return true; 950 951 spi = dynptr_get_spi(env, reg); 952 if (spi < 0) 953 return false; 954 if (!state->stack[spi].spilled_ptr.dynptr.first_slot) 955 return false; 956 957 for (i = 0; i < BPF_REG_SIZE; i++) { 958 if (state->stack[spi].slot_type[i] != STACK_DYNPTR || 959 state->stack[spi - 1].slot_type[i] != STACK_DYNPTR) 960 return false; 961 } 962 963 return true; 964 } 965 966 static bool is_dynptr_type_expected(struct bpf_verifier_env *env, struct bpf_reg_state *reg, 967 enum bpf_arg_type arg_type) 968 { 969 struct bpf_func_state *state = func(env, reg); 970 enum bpf_dynptr_type dynptr_type; 971 int spi; 972 973 /* ARG_PTR_TO_DYNPTR takes any type of dynptr */ 974 if (arg_type == ARG_PTR_TO_DYNPTR) 975 return true; 976 977 dynptr_type = arg_to_dynptr_type(arg_type); 978 if (reg->type == CONST_PTR_TO_DYNPTR) { 979 return reg->dynptr.type == dynptr_type; 980 } else { 981 spi = dynptr_get_spi(env, reg); 982 if (spi < 0) 983 return false; 984 return state->stack[spi].spilled_ptr.dynptr.type == dynptr_type; 985 } 986 } 987 988 static void __mark_reg_known_zero(struct bpf_reg_state *reg); 989 990 static bool in_rcu_cs(struct bpf_verifier_env *env); 991 992 static bool is_kfunc_rcu_protected(struct bpf_kfunc_call_arg_meta *meta); 993 994 static int mark_stack_slots_iter(struct bpf_verifier_env *env, 995 struct bpf_kfunc_call_arg_meta *meta, 996 struct bpf_reg_state *reg, int insn_idx, 997 struct btf *btf, u32 btf_id, int nr_slots) 998 { 999 struct bpf_func_state *state = func(env, reg); 1000 int spi, i, j, id; 1001 1002 spi = iter_get_spi(env, reg, nr_slots); 1003 if (spi < 0) 1004 return spi; 1005 1006 id = acquire_reference_state(env, insn_idx); 1007 if (id < 0) 1008 return id; 1009 1010 for (i = 0; i < nr_slots; i++) { 1011 struct bpf_stack_state *slot = &state->stack[spi - i]; 1012 struct bpf_reg_state *st = &slot->spilled_ptr; 1013 1014 __mark_reg_known_zero(st); 1015 st->type = PTR_TO_STACK; /* we don't have dedicated reg type */ 1016 if (is_kfunc_rcu_protected(meta)) { 1017 if (in_rcu_cs(env)) 1018 st->type |= MEM_RCU; 1019 else 1020 st->type |= PTR_UNTRUSTED; 1021 } 1022 st->live |= REG_LIVE_WRITTEN; 1023 st->ref_obj_id = i == 0 ? id : 0; 1024 st->iter.btf = btf; 1025 st->iter.btf_id = btf_id; 1026 st->iter.state = BPF_ITER_STATE_ACTIVE; 1027 st->iter.depth = 0; 1028 1029 for (j = 0; j < BPF_REG_SIZE; j++) 1030 slot->slot_type[j] = STACK_ITER; 1031 1032 mark_stack_slot_scratched(env, spi - i); 1033 } 1034 1035 return 0; 1036 } 1037 1038 static int unmark_stack_slots_iter(struct bpf_verifier_env *env, 1039 struct bpf_reg_state *reg, int nr_slots) 1040 { 1041 struct bpf_func_state *state = func(env, reg); 1042 int spi, i, j; 1043 1044 spi = iter_get_spi(env, reg, nr_slots); 1045 if (spi < 0) 1046 return spi; 1047 1048 for (i = 0; i < nr_slots; i++) { 1049 struct bpf_stack_state *slot = &state->stack[spi - i]; 1050 struct bpf_reg_state *st = &slot->spilled_ptr; 1051 1052 if (i == 0) 1053 WARN_ON_ONCE(release_reference(env, st->ref_obj_id)); 1054 1055 __mark_reg_not_init(env, st); 1056 1057 /* see unmark_stack_slots_dynptr() for why we need to set REG_LIVE_WRITTEN */ 1058 st->live |= REG_LIVE_WRITTEN; 1059 1060 for (j = 0; j < BPF_REG_SIZE; j++) 1061 slot->slot_type[j] = STACK_INVALID; 1062 1063 mark_stack_slot_scratched(env, spi - i); 1064 } 1065 1066 return 0; 1067 } 1068 1069 static bool is_iter_reg_valid_uninit(struct bpf_verifier_env *env, 1070 struct bpf_reg_state *reg, int nr_slots) 1071 { 1072 struct bpf_func_state *state = func(env, reg); 1073 int spi, i, j; 1074 1075 /* For -ERANGE (i.e. spi not falling into allocated stack slots), we 1076 * will do check_mem_access to check and update stack bounds later, so 1077 * return true for that case. 1078 */ 1079 spi = iter_get_spi(env, reg, nr_slots); 1080 if (spi == -ERANGE) 1081 return true; 1082 if (spi < 0) 1083 return false; 1084 1085 for (i = 0; i < nr_slots; i++) { 1086 struct bpf_stack_state *slot = &state->stack[spi - i]; 1087 1088 for (j = 0; j < BPF_REG_SIZE; j++) 1089 if (slot->slot_type[j] == STACK_ITER) 1090 return false; 1091 } 1092 1093 return true; 1094 } 1095 1096 static int is_iter_reg_valid_init(struct bpf_verifier_env *env, struct bpf_reg_state *reg, 1097 struct btf *btf, u32 btf_id, int nr_slots) 1098 { 1099 struct bpf_func_state *state = func(env, reg); 1100 int spi, i, j; 1101 1102 spi = iter_get_spi(env, reg, nr_slots); 1103 if (spi < 0) 1104 return -EINVAL; 1105 1106 for (i = 0; i < nr_slots; i++) { 1107 struct bpf_stack_state *slot = &state->stack[spi - i]; 1108 struct bpf_reg_state *st = &slot->spilled_ptr; 1109 1110 if (st->type & PTR_UNTRUSTED) 1111 return -EPROTO; 1112 /* only main (first) slot has ref_obj_id set */ 1113 if (i == 0 && !st->ref_obj_id) 1114 return -EINVAL; 1115 if (i != 0 && st->ref_obj_id) 1116 return -EINVAL; 1117 if (st->iter.btf != btf || st->iter.btf_id != btf_id) 1118 return -EINVAL; 1119 1120 for (j = 0; j < BPF_REG_SIZE; j++) 1121 if (slot->slot_type[j] != STACK_ITER) 1122 return -EINVAL; 1123 } 1124 1125 return 0; 1126 } 1127 1128 /* Check if given stack slot is "special": 1129 * - spilled register state (STACK_SPILL); 1130 * - dynptr state (STACK_DYNPTR); 1131 * - iter state (STACK_ITER). 1132 */ 1133 static bool is_stack_slot_special(const struct bpf_stack_state *stack) 1134 { 1135 enum bpf_stack_slot_type type = stack->slot_type[BPF_REG_SIZE - 1]; 1136 1137 switch (type) { 1138 case STACK_SPILL: 1139 case STACK_DYNPTR: 1140 case STACK_ITER: 1141 return true; 1142 case STACK_INVALID: 1143 case STACK_MISC: 1144 case STACK_ZERO: 1145 return false; 1146 default: 1147 WARN_ONCE(1, "unknown stack slot type %d\n", type); 1148 return true; 1149 } 1150 } 1151 1152 /* The reg state of a pointer or a bounded scalar was saved when 1153 * it was spilled to the stack. 1154 */ 1155 static bool is_spilled_reg(const struct bpf_stack_state *stack) 1156 { 1157 return stack->slot_type[BPF_REG_SIZE - 1] == STACK_SPILL; 1158 } 1159 1160 static bool is_spilled_scalar_reg(const struct bpf_stack_state *stack) 1161 { 1162 return stack->slot_type[BPF_REG_SIZE - 1] == STACK_SPILL && 1163 stack->spilled_ptr.type == SCALAR_VALUE; 1164 } 1165 1166 /* Mark stack slot as STACK_MISC, unless it is already STACK_INVALID, in which 1167 * case they are equivalent, or it's STACK_ZERO, in which case we preserve 1168 * more precise STACK_ZERO. 1169 * Note, in uprivileged mode leaving STACK_INVALID is wrong, so we take 1170 * env->allow_ptr_leaks into account and force STACK_MISC, if necessary. 1171 */ 1172 static void mark_stack_slot_misc(struct bpf_verifier_env *env, u8 *stype) 1173 { 1174 if (*stype == STACK_ZERO) 1175 return; 1176 if (env->allow_ptr_leaks && *stype == STACK_INVALID) 1177 return; 1178 *stype = STACK_MISC; 1179 } 1180 1181 static void scrub_spilled_slot(u8 *stype) 1182 { 1183 if (*stype != STACK_INVALID) 1184 *stype = STACK_MISC; 1185 } 1186 1187 /* copy array src of length n * size bytes to dst. dst is reallocated if it's too 1188 * small to hold src. This is different from krealloc since we don't want to preserve 1189 * the contents of dst. 1190 * 1191 * Leaves dst untouched if src is NULL or length is zero. Returns NULL if memory could 1192 * not be allocated. 1193 */ 1194 static void *copy_array(void *dst, const void *src, size_t n, size_t size, gfp_t flags) 1195 { 1196 size_t alloc_bytes; 1197 void *orig = dst; 1198 size_t bytes; 1199 1200 if (ZERO_OR_NULL_PTR(src)) 1201 goto out; 1202 1203 if (unlikely(check_mul_overflow(n, size, &bytes))) 1204 return NULL; 1205 1206 alloc_bytes = max(ksize(orig), kmalloc_size_roundup(bytes)); 1207 dst = krealloc(orig, alloc_bytes, flags); 1208 if (!dst) { 1209 kfree(orig); 1210 return NULL; 1211 } 1212 1213 memcpy(dst, src, bytes); 1214 out: 1215 return dst ? dst : ZERO_SIZE_PTR; 1216 } 1217 1218 /* resize an array from old_n items to new_n items. the array is reallocated if it's too 1219 * small to hold new_n items. new items are zeroed out if the array grows. 1220 * 1221 * Contrary to krealloc_array, does not free arr if new_n is zero. 1222 */ 1223 static void *realloc_array(void *arr, size_t old_n, size_t new_n, size_t size) 1224 { 1225 size_t alloc_size; 1226 void *new_arr; 1227 1228 if (!new_n || old_n == new_n) 1229 goto out; 1230 1231 alloc_size = kmalloc_size_roundup(size_mul(new_n, size)); 1232 new_arr = krealloc(arr, alloc_size, GFP_KERNEL); 1233 if (!new_arr) { 1234 kfree(arr); 1235 return NULL; 1236 } 1237 arr = new_arr; 1238 1239 if (new_n > old_n) 1240 memset(arr + old_n * size, 0, (new_n - old_n) * size); 1241 1242 out: 1243 return arr ? arr : ZERO_SIZE_PTR; 1244 } 1245 1246 static int copy_reference_state(struct bpf_func_state *dst, const struct bpf_func_state *src) 1247 { 1248 dst->refs = copy_array(dst->refs, src->refs, src->acquired_refs, 1249 sizeof(struct bpf_reference_state), GFP_KERNEL); 1250 if (!dst->refs) 1251 return -ENOMEM; 1252 1253 dst->acquired_refs = src->acquired_refs; 1254 return 0; 1255 } 1256 1257 static int copy_stack_state(struct bpf_func_state *dst, const struct bpf_func_state *src) 1258 { 1259 size_t n = src->allocated_stack / BPF_REG_SIZE; 1260 1261 dst->stack = copy_array(dst->stack, src->stack, n, sizeof(struct bpf_stack_state), 1262 GFP_KERNEL); 1263 if (!dst->stack) 1264 return -ENOMEM; 1265 1266 dst->allocated_stack = src->allocated_stack; 1267 return 0; 1268 } 1269 1270 static int resize_reference_state(struct bpf_func_state *state, size_t n) 1271 { 1272 state->refs = realloc_array(state->refs, state->acquired_refs, n, 1273 sizeof(struct bpf_reference_state)); 1274 if (!state->refs) 1275 return -ENOMEM; 1276 1277 state->acquired_refs = n; 1278 return 0; 1279 } 1280 1281 /* Possibly update state->allocated_stack to be at least size bytes. Also 1282 * possibly update the function's high-water mark in its bpf_subprog_info. 1283 */ 1284 static int grow_stack_state(struct bpf_verifier_env *env, struct bpf_func_state *state, int size) 1285 { 1286 size_t old_n = state->allocated_stack / BPF_REG_SIZE, n; 1287 1288 /* The stack size is always a multiple of BPF_REG_SIZE. */ 1289 size = round_up(size, BPF_REG_SIZE); 1290 n = size / BPF_REG_SIZE; 1291 1292 if (old_n >= n) 1293 return 0; 1294 1295 state->stack = realloc_array(state->stack, old_n, n, sizeof(struct bpf_stack_state)); 1296 if (!state->stack) 1297 return -ENOMEM; 1298 1299 state->allocated_stack = size; 1300 1301 /* update known max for given subprogram */ 1302 if (env->subprog_info[state->subprogno].stack_depth < size) 1303 env->subprog_info[state->subprogno].stack_depth = size; 1304 1305 return 0; 1306 } 1307 1308 /* Acquire a pointer id from the env and update the state->refs to include 1309 * this new pointer reference. 1310 * On success, returns a valid pointer id to associate with the register 1311 * On failure, returns a negative errno. 1312 */ 1313 static int acquire_reference_state(struct bpf_verifier_env *env, int insn_idx) 1314 { 1315 struct bpf_func_state *state = cur_func(env); 1316 int new_ofs = state->acquired_refs; 1317 int id, err; 1318 1319 err = resize_reference_state(state, state->acquired_refs + 1); 1320 if (err) 1321 return err; 1322 id = ++env->id_gen; 1323 state->refs[new_ofs].id = id; 1324 state->refs[new_ofs].insn_idx = insn_idx; 1325 state->refs[new_ofs].callback_ref = state->in_callback_fn ? state->frameno : 0; 1326 1327 return id; 1328 } 1329 1330 /* release function corresponding to acquire_reference_state(). Idempotent. */ 1331 static int release_reference_state(struct bpf_func_state *state, int ptr_id) 1332 { 1333 int i, last_idx; 1334 1335 last_idx = state->acquired_refs - 1; 1336 for (i = 0; i < state->acquired_refs; i++) { 1337 if (state->refs[i].id == ptr_id) { 1338 /* Cannot release caller references in callbacks */ 1339 if (state->in_callback_fn && state->refs[i].callback_ref != state->frameno) 1340 return -EINVAL; 1341 if (last_idx && i != last_idx) 1342 memcpy(&state->refs[i], &state->refs[last_idx], 1343 sizeof(*state->refs)); 1344 memset(&state->refs[last_idx], 0, sizeof(*state->refs)); 1345 state->acquired_refs--; 1346 return 0; 1347 } 1348 } 1349 return -EINVAL; 1350 } 1351 1352 static void free_func_state(struct bpf_func_state *state) 1353 { 1354 if (!state) 1355 return; 1356 kfree(state->refs); 1357 kfree(state->stack); 1358 kfree(state); 1359 } 1360 1361 static void clear_jmp_history(struct bpf_verifier_state *state) 1362 { 1363 kfree(state->jmp_history); 1364 state->jmp_history = NULL; 1365 state->jmp_history_cnt = 0; 1366 } 1367 1368 static void free_verifier_state(struct bpf_verifier_state *state, 1369 bool free_self) 1370 { 1371 int i; 1372 1373 for (i = 0; i <= state->curframe; i++) { 1374 free_func_state(state->frame[i]); 1375 state->frame[i] = NULL; 1376 } 1377 clear_jmp_history(state); 1378 if (free_self) 1379 kfree(state); 1380 } 1381 1382 /* copy verifier state from src to dst growing dst stack space 1383 * when necessary to accommodate larger src stack 1384 */ 1385 static int copy_func_state(struct bpf_func_state *dst, 1386 const struct bpf_func_state *src) 1387 { 1388 int err; 1389 1390 memcpy(dst, src, offsetof(struct bpf_func_state, acquired_refs)); 1391 err = copy_reference_state(dst, src); 1392 if (err) 1393 return err; 1394 return copy_stack_state(dst, src); 1395 } 1396 1397 static int copy_verifier_state(struct bpf_verifier_state *dst_state, 1398 const struct bpf_verifier_state *src) 1399 { 1400 struct bpf_func_state *dst; 1401 int i, err; 1402 1403 dst_state->jmp_history = copy_array(dst_state->jmp_history, src->jmp_history, 1404 src->jmp_history_cnt, sizeof(*dst_state->jmp_history), 1405 GFP_USER); 1406 if (!dst_state->jmp_history) 1407 return -ENOMEM; 1408 dst_state->jmp_history_cnt = src->jmp_history_cnt; 1409 1410 /* if dst has more stack frames then src frame, free them, this is also 1411 * necessary in case of exceptional exits using bpf_throw. 1412 */ 1413 for (i = src->curframe + 1; i <= dst_state->curframe; i++) { 1414 free_func_state(dst_state->frame[i]); 1415 dst_state->frame[i] = NULL; 1416 } 1417 dst_state->speculative = src->speculative; 1418 dst_state->active_rcu_lock = src->active_rcu_lock; 1419 dst_state->curframe = src->curframe; 1420 dst_state->active_lock.ptr = src->active_lock.ptr; 1421 dst_state->active_lock.id = src->active_lock.id; 1422 dst_state->branches = src->branches; 1423 dst_state->parent = src->parent; 1424 dst_state->first_insn_idx = src->first_insn_idx; 1425 dst_state->last_insn_idx = src->last_insn_idx; 1426 dst_state->dfs_depth = src->dfs_depth; 1427 dst_state->callback_unroll_depth = src->callback_unroll_depth; 1428 dst_state->used_as_loop_entry = src->used_as_loop_entry; 1429 for (i = 0; i <= src->curframe; i++) { 1430 dst = dst_state->frame[i]; 1431 if (!dst) { 1432 dst = kzalloc(sizeof(*dst), GFP_KERNEL); 1433 if (!dst) 1434 return -ENOMEM; 1435 dst_state->frame[i] = dst; 1436 } 1437 err = copy_func_state(dst, src->frame[i]); 1438 if (err) 1439 return err; 1440 } 1441 return 0; 1442 } 1443 1444 static u32 state_htab_size(struct bpf_verifier_env *env) 1445 { 1446 return env->prog->len; 1447 } 1448 1449 static struct bpf_verifier_state_list **explored_state(struct bpf_verifier_env *env, int idx) 1450 { 1451 struct bpf_verifier_state *cur = env->cur_state; 1452 struct bpf_func_state *state = cur->frame[cur->curframe]; 1453 1454 return &env->explored_states[(idx ^ state->callsite) % state_htab_size(env)]; 1455 } 1456 1457 static bool same_callsites(struct bpf_verifier_state *a, struct bpf_verifier_state *b) 1458 { 1459 int fr; 1460 1461 if (a->curframe != b->curframe) 1462 return false; 1463 1464 for (fr = a->curframe; fr >= 0; fr--) 1465 if (a->frame[fr]->callsite != b->frame[fr]->callsite) 1466 return false; 1467 1468 return true; 1469 } 1470 1471 /* Open coded iterators allow back-edges in the state graph in order to 1472 * check unbounded loops that iterators. 1473 * 1474 * In is_state_visited() it is necessary to know if explored states are 1475 * part of some loops in order to decide whether non-exact states 1476 * comparison could be used: 1477 * - non-exact states comparison establishes sub-state relation and uses 1478 * read and precision marks to do so, these marks are propagated from 1479 * children states and thus are not guaranteed to be final in a loop; 1480 * - exact states comparison just checks if current and explored states 1481 * are identical (and thus form a back-edge). 1482 * 1483 * Paper "A New Algorithm for Identifying Loops in Decompilation" 1484 * by Tao Wei, Jian Mao, Wei Zou and Yu Chen [1] presents a convenient 1485 * algorithm for loop structure detection and gives an overview of 1486 * relevant terminology. It also has helpful illustrations. 1487 * 1488 * [1] https://api.semanticscholar.org/CorpusID:15784067 1489 * 1490 * We use a similar algorithm but because loop nested structure is 1491 * irrelevant for verifier ours is significantly simpler and resembles 1492 * strongly connected components algorithm from Sedgewick's textbook. 1493 * 1494 * Define topmost loop entry as a first node of the loop traversed in a 1495 * depth first search starting from initial state. The goal of the loop 1496 * tracking algorithm is to associate topmost loop entries with states 1497 * derived from these entries. 1498 * 1499 * For each step in the DFS states traversal algorithm needs to identify 1500 * the following situations: 1501 * 1502 * initial initial initial 1503 * | | | 1504 * V V V 1505 * ... ... .---------> hdr 1506 * | | | | 1507 * V V | V 1508 * cur .-> succ | .------... 1509 * | | | | | | 1510 * V | V | V V 1511 * succ '-- cur | ... ... 1512 * | | | 1513 * | V V 1514 * | succ <- cur 1515 * | | 1516 * | V 1517 * | ... 1518 * | | 1519 * '----' 1520 * 1521 * (A) successor state of cur (B) successor state of cur or it's entry 1522 * not yet traversed are in current DFS path, thus cur and succ 1523 * are members of the same outermost loop 1524 * 1525 * initial initial 1526 * | | 1527 * V V 1528 * ... ... 1529 * | | 1530 * V V 1531 * .------... .------... 1532 * | | | | 1533 * V V V V 1534 * .-> hdr ... ... ... 1535 * | | | | | 1536 * | V V V V 1537 * | succ <- cur succ <- cur 1538 * | | | 1539 * | V V 1540 * | ... ... 1541 * | | | 1542 * '----' exit 1543 * 1544 * (C) successor state of cur is a part of some loop but this loop 1545 * does not include cur or successor state is not in a loop at all. 1546 * 1547 * Algorithm could be described as the following python code: 1548 * 1549 * traversed = set() # Set of traversed nodes 1550 * entries = {} # Mapping from node to loop entry 1551 * depths = {} # Depth level assigned to graph node 1552 * path = set() # Current DFS path 1553 * 1554 * # Find outermost loop entry known for n 1555 * def get_loop_entry(n): 1556 * h = entries.get(n, None) 1557 * while h in entries and entries[h] != h: 1558 * h = entries[h] 1559 * return h 1560 * 1561 * # Update n's loop entry if h's outermost entry comes 1562 * # before n's outermost entry in current DFS path. 1563 * def update_loop_entry(n, h): 1564 * n1 = get_loop_entry(n) or n 1565 * h1 = get_loop_entry(h) or h 1566 * if h1 in path and depths[h1] <= depths[n1]: 1567 * entries[n] = h1 1568 * 1569 * def dfs(n, depth): 1570 * traversed.add(n) 1571 * path.add(n) 1572 * depths[n] = depth 1573 * for succ in G.successors(n): 1574 * if succ not in traversed: 1575 * # Case A: explore succ and update cur's loop entry 1576 * # only if succ's entry is in current DFS path. 1577 * dfs(succ, depth + 1) 1578 * h = get_loop_entry(succ) 1579 * update_loop_entry(n, h) 1580 * else: 1581 * # Case B or C depending on `h1 in path` check in update_loop_entry(). 1582 * update_loop_entry(n, succ) 1583 * path.remove(n) 1584 * 1585 * To adapt this algorithm for use with verifier: 1586 * - use st->branch == 0 as a signal that DFS of succ had been finished 1587 * and cur's loop entry has to be updated (case A), handle this in 1588 * update_branch_counts(); 1589 * - use st->branch > 0 as a signal that st is in the current DFS path; 1590 * - handle cases B and C in is_state_visited(); 1591 * - update topmost loop entry for intermediate states in get_loop_entry(). 1592 */ 1593 static struct bpf_verifier_state *get_loop_entry(struct bpf_verifier_state *st) 1594 { 1595 struct bpf_verifier_state *topmost = st->loop_entry, *old; 1596 1597 while (topmost && topmost->loop_entry && topmost != topmost->loop_entry) 1598 topmost = topmost->loop_entry; 1599 /* Update loop entries for intermediate states to avoid this 1600 * traversal in future get_loop_entry() calls. 1601 */ 1602 while (st && st->loop_entry != topmost) { 1603 old = st->loop_entry; 1604 st->loop_entry = topmost; 1605 st = old; 1606 } 1607 return topmost; 1608 } 1609 1610 static void update_loop_entry(struct bpf_verifier_state *cur, struct bpf_verifier_state *hdr) 1611 { 1612 struct bpf_verifier_state *cur1, *hdr1; 1613 1614 cur1 = get_loop_entry(cur) ?: cur; 1615 hdr1 = get_loop_entry(hdr) ?: hdr; 1616 /* The head1->branches check decides between cases B and C in 1617 * comment for get_loop_entry(). If hdr1->branches == 0 then 1618 * head's topmost loop entry is not in current DFS path, 1619 * hence 'cur' and 'hdr' are not in the same loop and there is 1620 * no need to update cur->loop_entry. 1621 */ 1622 if (hdr1->branches && hdr1->dfs_depth <= cur1->dfs_depth) { 1623 cur->loop_entry = hdr; 1624 hdr->used_as_loop_entry = true; 1625 } 1626 } 1627 1628 static void update_branch_counts(struct bpf_verifier_env *env, struct bpf_verifier_state *st) 1629 { 1630 while (st) { 1631 u32 br = --st->branches; 1632 1633 /* br == 0 signals that DFS exploration for 'st' is finished, 1634 * thus it is necessary to update parent's loop entry if it 1635 * turned out that st is a part of some loop. 1636 * This is a part of 'case A' in get_loop_entry() comment. 1637 */ 1638 if (br == 0 && st->parent && st->loop_entry) 1639 update_loop_entry(st->parent, st->loop_entry); 1640 1641 /* WARN_ON(br > 1) technically makes sense here, 1642 * but see comment in push_stack(), hence: 1643 */ 1644 WARN_ONCE((int)br < 0, 1645 "BUG update_branch_counts:branches_to_explore=%d\n", 1646 br); 1647 if (br) 1648 break; 1649 st = st->parent; 1650 } 1651 } 1652 1653 static int pop_stack(struct bpf_verifier_env *env, int *prev_insn_idx, 1654 int *insn_idx, bool pop_log) 1655 { 1656 struct bpf_verifier_state *cur = env->cur_state; 1657 struct bpf_verifier_stack_elem *elem, *head = env->head; 1658 int err; 1659 1660 if (env->head == NULL) 1661 return -ENOENT; 1662 1663 if (cur) { 1664 err = copy_verifier_state(cur, &head->st); 1665 if (err) 1666 return err; 1667 } 1668 if (pop_log) 1669 bpf_vlog_reset(&env->log, head->log_pos); 1670 if (insn_idx) 1671 *insn_idx = head->insn_idx; 1672 if (prev_insn_idx) 1673 *prev_insn_idx = head->prev_insn_idx; 1674 elem = head->next; 1675 free_verifier_state(&head->st, false); 1676 kfree(head); 1677 env->head = elem; 1678 env->stack_size--; 1679 return 0; 1680 } 1681 1682 static struct bpf_verifier_state *push_stack(struct bpf_verifier_env *env, 1683 int insn_idx, int prev_insn_idx, 1684 bool speculative) 1685 { 1686 struct bpf_verifier_state *cur = env->cur_state; 1687 struct bpf_verifier_stack_elem *elem; 1688 int err; 1689 1690 elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL); 1691 if (!elem) 1692 goto err; 1693 1694 elem->insn_idx = insn_idx; 1695 elem->prev_insn_idx = prev_insn_idx; 1696 elem->next = env->head; 1697 elem->log_pos = env->log.end_pos; 1698 env->head = elem; 1699 env->stack_size++; 1700 err = copy_verifier_state(&elem->st, cur); 1701 if (err) 1702 goto err; 1703 elem->st.speculative |= speculative; 1704 if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) { 1705 verbose(env, "The sequence of %d jumps is too complex.\n", 1706 env->stack_size); 1707 goto err; 1708 } 1709 if (elem->st.parent) { 1710 ++elem->st.parent->branches; 1711 /* WARN_ON(branches > 2) technically makes sense here, 1712 * but 1713 * 1. speculative states will bump 'branches' for non-branch 1714 * instructions 1715 * 2. is_state_visited() heuristics may decide not to create 1716 * a new state for a sequence of branches and all such current 1717 * and cloned states will be pointing to a single parent state 1718 * which might have large 'branches' count. 1719 */ 1720 } 1721 return &elem->st; 1722 err: 1723 free_verifier_state(env->cur_state, true); 1724 env->cur_state = NULL; 1725 /* pop all elements and return */ 1726 while (!pop_stack(env, NULL, NULL, false)); 1727 return NULL; 1728 } 1729 1730 #define CALLER_SAVED_REGS 6 1731 static const int caller_saved[CALLER_SAVED_REGS] = { 1732 BPF_REG_0, BPF_REG_1, BPF_REG_2, BPF_REG_3, BPF_REG_4, BPF_REG_5 1733 }; 1734 1735 /* This helper doesn't clear reg->id */ 1736 static void ___mark_reg_known(struct bpf_reg_state *reg, u64 imm) 1737 { 1738 reg->var_off = tnum_const(imm); 1739 reg->smin_value = (s64)imm; 1740 reg->smax_value = (s64)imm; 1741 reg->umin_value = imm; 1742 reg->umax_value = imm; 1743 1744 reg->s32_min_value = (s32)imm; 1745 reg->s32_max_value = (s32)imm; 1746 reg->u32_min_value = (u32)imm; 1747 reg->u32_max_value = (u32)imm; 1748 } 1749 1750 /* Mark the unknown part of a register (variable offset or scalar value) as 1751 * known to have the value @imm. 1752 */ 1753 static void __mark_reg_known(struct bpf_reg_state *reg, u64 imm) 1754 { 1755 /* Clear off and union(map_ptr, range) */ 1756 memset(((u8 *)reg) + sizeof(reg->type), 0, 1757 offsetof(struct bpf_reg_state, var_off) - sizeof(reg->type)); 1758 reg->id = 0; 1759 reg->ref_obj_id = 0; 1760 ___mark_reg_known(reg, imm); 1761 } 1762 1763 static void __mark_reg32_known(struct bpf_reg_state *reg, u64 imm) 1764 { 1765 reg->var_off = tnum_const_subreg(reg->var_off, imm); 1766 reg->s32_min_value = (s32)imm; 1767 reg->s32_max_value = (s32)imm; 1768 reg->u32_min_value = (u32)imm; 1769 reg->u32_max_value = (u32)imm; 1770 } 1771 1772 /* Mark the 'variable offset' part of a register as zero. This should be 1773 * used only on registers holding a pointer type. 1774 */ 1775 static void __mark_reg_known_zero(struct bpf_reg_state *reg) 1776 { 1777 __mark_reg_known(reg, 0); 1778 } 1779 1780 static void __mark_reg_const_zero(const struct bpf_verifier_env *env, struct bpf_reg_state *reg) 1781 { 1782 __mark_reg_known(reg, 0); 1783 reg->type = SCALAR_VALUE; 1784 /* all scalars are assumed imprecise initially (unless unprivileged, 1785 * in which case everything is forced to be precise) 1786 */ 1787 reg->precise = !env->bpf_capable; 1788 } 1789 1790 static void mark_reg_known_zero(struct bpf_verifier_env *env, 1791 struct bpf_reg_state *regs, u32 regno) 1792 { 1793 if (WARN_ON(regno >= MAX_BPF_REG)) { 1794 verbose(env, "mark_reg_known_zero(regs, %u)\n", regno); 1795 /* Something bad happened, let's kill all regs */ 1796 for (regno = 0; regno < MAX_BPF_REG; regno++) 1797 __mark_reg_not_init(env, regs + regno); 1798 return; 1799 } 1800 __mark_reg_known_zero(regs + regno); 1801 } 1802 1803 static void __mark_dynptr_reg(struct bpf_reg_state *reg, enum bpf_dynptr_type type, 1804 bool first_slot, int dynptr_id) 1805 { 1806 /* reg->type has no meaning for STACK_DYNPTR, but when we set reg for 1807 * callback arguments, it does need to be CONST_PTR_TO_DYNPTR, so simply 1808 * set it unconditionally as it is ignored for STACK_DYNPTR anyway. 1809 */ 1810 __mark_reg_known_zero(reg); 1811 reg->type = CONST_PTR_TO_DYNPTR; 1812 /* Give each dynptr a unique id to uniquely associate slices to it. */ 1813 reg->id = dynptr_id; 1814 reg->dynptr.type = type; 1815 reg->dynptr.first_slot = first_slot; 1816 } 1817 1818 static void mark_ptr_not_null_reg(struct bpf_reg_state *reg) 1819 { 1820 if (base_type(reg->type) == PTR_TO_MAP_VALUE) { 1821 const struct bpf_map *map = reg->map_ptr; 1822 1823 if (map->inner_map_meta) { 1824 reg->type = CONST_PTR_TO_MAP; 1825 reg->map_ptr = map->inner_map_meta; 1826 /* transfer reg's id which is unique for every map_lookup_elem 1827 * as UID of the inner map. 1828 */ 1829 if (btf_record_has_field(map->inner_map_meta->record, BPF_TIMER)) 1830 reg->map_uid = reg->id; 1831 } else if (map->map_type == BPF_MAP_TYPE_XSKMAP) { 1832 reg->type = PTR_TO_XDP_SOCK; 1833 } else if (map->map_type == BPF_MAP_TYPE_SOCKMAP || 1834 map->map_type == BPF_MAP_TYPE_SOCKHASH) { 1835 reg->type = PTR_TO_SOCKET; 1836 } else { 1837 reg->type = PTR_TO_MAP_VALUE; 1838 } 1839 return; 1840 } 1841 1842 reg->type &= ~PTR_MAYBE_NULL; 1843 } 1844 1845 static void mark_reg_graph_node(struct bpf_reg_state *regs, u32 regno, 1846 struct btf_field_graph_root *ds_head) 1847 { 1848 __mark_reg_known_zero(®s[regno]); 1849 regs[regno].type = PTR_TO_BTF_ID | MEM_ALLOC; 1850 regs[regno].btf = ds_head->btf; 1851 regs[regno].btf_id = ds_head->value_btf_id; 1852 regs[regno].off = ds_head->node_offset; 1853 } 1854 1855 static bool reg_is_pkt_pointer(const struct bpf_reg_state *reg) 1856 { 1857 return type_is_pkt_pointer(reg->type); 1858 } 1859 1860 static bool reg_is_pkt_pointer_any(const struct bpf_reg_state *reg) 1861 { 1862 return reg_is_pkt_pointer(reg) || 1863 reg->type == PTR_TO_PACKET_END; 1864 } 1865 1866 static bool reg_is_dynptr_slice_pkt(const struct bpf_reg_state *reg) 1867 { 1868 return base_type(reg->type) == PTR_TO_MEM && 1869 (reg->type & DYNPTR_TYPE_SKB || reg->type & DYNPTR_TYPE_XDP); 1870 } 1871 1872 /* Unmodified PTR_TO_PACKET[_META,_END] register from ctx access. */ 1873 static bool reg_is_init_pkt_pointer(const struct bpf_reg_state *reg, 1874 enum bpf_reg_type which) 1875 { 1876 /* The register can already have a range from prior markings. 1877 * This is fine as long as it hasn't been advanced from its 1878 * origin. 1879 */ 1880 return reg->type == which && 1881 reg->id == 0 && 1882 reg->off == 0 && 1883 tnum_equals_const(reg->var_off, 0); 1884 } 1885 1886 /* Reset the min/max bounds of a register */ 1887 static void __mark_reg_unbounded(struct bpf_reg_state *reg) 1888 { 1889 reg->smin_value = S64_MIN; 1890 reg->smax_value = S64_MAX; 1891 reg->umin_value = 0; 1892 reg->umax_value = U64_MAX; 1893 1894 reg->s32_min_value = S32_MIN; 1895 reg->s32_max_value = S32_MAX; 1896 reg->u32_min_value = 0; 1897 reg->u32_max_value = U32_MAX; 1898 } 1899 1900 static void __mark_reg64_unbounded(struct bpf_reg_state *reg) 1901 { 1902 reg->smin_value = S64_MIN; 1903 reg->smax_value = S64_MAX; 1904 reg->umin_value = 0; 1905 reg->umax_value = U64_MAX; 1906 } 1907 1908 static void __mark_reg32_unbounded(struct bpf_reg_state *reg) 1909 { 1910 reg->s32_min_value = S32_MIN; 1911 reg->s32_max_value = S32_MAX; 1912 reg->u32_min_value = 0; 1913 reg->u32_max_value = U32_MAX; 1914 } 1915 1916 static void __update_reg32_bounds(struct bpf_reg_state *reg) 1917 { 1918 struct tnum var32_off = tnum_subreg(reg->var_off); 1919 1920 /* min signed is max(sign bit) | min(other bits) */ 1921 reg->s32_min_value = max_t(s32, reg->s32_min_value, 1922 var32_off.value | (var32_off.mask & S32_MIN)); 1923 /* max signed is min(sign bit) | max(other bits) */ 1924 reg->s32_max_value = min_t(s32, reg->s32_max_value, 1925 var32_off.value | (var32_off.mask & S32_MAX)); 1926 reg->u32_min_value = max_t(u32, reg->u32_min_value, (u32)var32_off.value); 1927 reg->u32_max_value = min(reg->u32_max_value, 1928 (u32)(var32_off.value | var32_off.mask)); 1929 } 1930 1931 static void __update_reg64_bounds(struct bpf_reg_state *reg) 1932 { 1933 /* min signed is max(sign bit) | min(other bits) */ 1934 reg->smin_value = max_t(s64, reg->smin_value, 1935 reg->var_off.value | (reg->var_off.mask & S64_MIN)); 1936 /* max signed is min(sign bit) | max(other bits) */ 1937 reg->smax_value = min_t(s64, reg->smax_value, 1938 reg->var_off.value | (reg->var_off.mask & S64_MAX)); 1939 reg->umin_value = max(reg->umin_value, reg->var_off.value); 1940 reg->umax_value = min(reg->umax_value, 1941 reg->var_off.value | reg->var_off.mask); 1942 } 1943 1944 static void __update_reg_bounds(struct bpf_reg_state *reg) 1945 { 1946 __update_reg32_bounds(reg); 1947 __update_reg64_bounds(reg); 1948 } 1949 1950 /* Uses signed min/max values to inform unsigned, and vice-versa */ 1951 static void __reg32_deduce_bounds(struct bpf_reg_state *reg) 1952 { 1953 /* If upper 32 bits of u64/s64 range don't change, we can use lower 32 1954 * bits to improve our u32/s32 boundaries. 1955 * 1956 * E.g., the case where we have upper 32 bits as zero ([10, 20] in 1957 * u64) is pretty trivial, it's obvious that in u32 we'll also have 1958 * [10, 20] range. But this property holds for any 64-bit range as 1959 * long as upper 32 bits in that entire range of values stay the same. 1960 * 1961 * E.g., u64 range [0x10000000A, 0x10000000F] ([4294967306, 4294967311] 1962 * in decimal) has the same upper 32 bits throughout all the values in 1963 * that range. As such, lower 32 bits form a valid [0xA, 0xF] ([10, 15]) 1964 * range. 1965 * 1966 * Note also, that [0xA, 0xF] is a valid range both in u32 and in s32, 1967 * following the rules outlined below about u64/s64 correspondence 1968 * (which equally applies to u32 vs s32 correspondence). In general it 1969 * depends on actual hexadecimal values of 32-bit range. They can form 1970 * only valid u32, or only valid s32 ranges in some cases. 1971 * 1972 * So we use all these insights to derive bounds for subregisters here. 1973 */ 1974 if ((reg->umin_value >> 32) == (reg->umax_value >> 32)) { 1975 /* u64 to u32 casting preserves validity of low 32 bits as 1976 * a range, if upper 32 bits are the same 1977 */ 1978 reg->u32_min_value = max_t(u32, reg->u32_min_value, (u32)reg->umin_value); 1979 reg->u32_max_value = min_t(u32, reg->u32_max_value, (u32)reg->umax_value); 1980 1981 if ((s32)reg->umin_value <= (s32)reg->umax_value) { 1982 reg->s32_min_value = max_t(s32, reg->s32_min_value, (s32)reg->umin_value); 1983 reg->s32_max_value = min_t(s32, reg->s32_max_value, (s32)reg->umax_value); 1984 } 1985 } 1986 if ((reg->smin_value >> 32) == (reg->smax_value >> 32)) { 1987 /* low 32 bits should form a proper u32 range */ 1988 if ((u32)reg->smin_value <= (u32)reg->smax_value) { 1989 reg->u32_min_value = max_t(u32, reg->u32_min_value, (u32)reg->smin_value); 1990 reg->u32_max_value = min_t(u32, reg->u32_max_value, (u32)reg->smax_value); 1991 } 1992 /* low 32 bits should form a proper s32 range */ 1993 if ((s32)reg->smin_value <= (s32)reg->smax_value) { 1994 reg->s32_min_value = max_t(s32, reg->s32_min_value, (s32)reg->smin_value); 1995 reg->s32_max_value = min_t(s32, reg->s32_max_value, (s32)reg->smax_value); 1996 } 1997 } 1998 /* Special case where upper bits form a small sequence of two 1999 * sequential numbers (in 32-bit unsigned space, so 0xffffffff to 2000 * 0x00000000 is also valid), while lower bits form a proper s32 range 2001 * going from negative numbers to positive numbers. E.g., let's say we 2002 * have s64 range [-1, 1] ([0xffffffffffffffff, 0x0000000000000001]). 2003 * Possible s64 values are {-1, 0, 1} ({0xffffffffffffffff, 2004 * 0x0000000000000000, 0x00000000000001}). Ignoring upper 32 bits, 2005 * we still get a valid s32 range [-1, 1] ([0xffffffff, 0x00000001]). 2006 * Note that it doesn't have to be 0xffffffff going to 0x00000000 in 2007 * upper 32 bits. As a random example, s64 range 2008 * [0xfffffff0fffffff0; 0xfffffff100000010], forms a valid s32 range 2009 * [-16, 16] ([0xfffffff0; 0x00000010]) in its 32 bit subregister. 2010 */ 2011 if ((u32)(reg->umin_value >> 32) + 1 == (u32)(reg->umax_value >> 32) && 2012 (s32)reg->umin_value < 0 && (s32)reg->umax_value >= 0) { 2013 reg->s32_min_value = max_t(s32, reg->s32_min_value, (s32)reg->umin_value); 2014 reg->s32_max_value = min_t(s32, reg->s32_max_value, (s32)reg->umax_value); 2015 } 2016 if ((u32)(reg->smin_value >> 32) + 1 == (u32)(reg->smax_value >> 32) && 2017 (s32)reg->smin_value < 0 && (s32)reg->smax_value >= 0) { 2018 reg->s32_min_value = max_t(s32, reg->s32_min_value, (s32)reg->smin_value); 2019 reg->s32_max_value = min_t(s32, reg->s32_max_value, (s32)reg->smax_value); 2020 } 2021 /* if u32 range forms a valid s32 range (due to matching sign bit), 2022 * try to learn from that 2023 */ 2024 if ((s32)reg->u32_min_value <= (s32)reg->u32_max_value) { 2025 reg->s32_min_value = max_t(s32, reg->s32_min_value, reg->u32_min_value); 2026 reg->s32_max_value = min_t(s32, reg->s32_max_value, reg->u32_max_value); 2027 } 2028 /* If we cannot cross the sign boundary, then signed and unsigned bounds 2029 * are the same, so combine. This works even in the negative case, e.g. 2030 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff. 2031 */ 2032 if ((u32)reg->s32_min_value <= (u32)reg->s32_max_value) { 2033 reg->u32_min_value = max_t(u32, reg->s32_min_value, reg->u32_min_value); 2034 reg->u32_max_value = min_t(u32, reg->s32_max_value, reg->u32_max_value); 2035 } 2036 } 2037 2038 static void __reg64_deduce_bounds(struct bpf_reg_state *reg) 2039 { 2040 /* If u64 range forms a valid s64 range (due to matching sign bit), 2041 * try to learn from that. Let's do a bit of ASCII art to see when 2042 * this is happening. Let's take u64 range first: 2043 * 2044 * 0 0x7fffffffffffffff 0x8000000000000000 U64_MAX 2045 * |-------------------------------|--------------------------------| 2046 * 2047 * Valid u64 range is formed when umin and umax are anywhere in the 2048 * range [0, U64_MAX], and umin <= umax. u64 case is simple and 2049 * straightforward. Let's see how s64 range maps onto the same range 2050 * of values, annotated below the line for comparison: 2051 * 2052 * 0 0x7fffffffffffffff 0x8000000000000000 U64_MAX 2053 * |-------------------------------|--------------------------------| 2054 * 0 S64_MAX S64_MIN -1 2055 * 2056 * So s64 values basically start in the middle and they are logically 2057 * contiguous to the right of it, wrapping around from -1 to 0, and 2058 * then finishing as S64_MAX (0x7fffffffffffffff) right before 2059 * S64_MIN. We can try drawing the continuity of u64 vs s64 values 2060 * more visually as mapped to sign-agnostic range of hex values. 2061 * 2062 * u64 start u64 end 2063 * _______________________________________________________________ 2064 * / \ 2065 * 0 0x7fffffffffffffff 0x8000000000000000 U64_MAX 2066 * |-------------------------------|--------------------------------| 2067 * 0 S64_MAX S64_MIN -1 2068 * / \ 2069 * >------------------------------ -------------------------------> 2070 * s64 continues... s64 end s64 start s64 "midpoint" 2071 * 2072 * What this means is that, in general, we can't always derive 2073 * something new about u64 from any random s64 range, and vice versa. 2074 * 2075 * But we can do that in two particular cases. One is when entire 2076 * u64/s64 range is *entirely* contained within left half of the above 2077 * diagram or when it is *entirely* contained in the right half. I.e.: 2078 * 2079 * |-------------------------------|--------------------------------| 2080 * ^ ^ ^ ^ 2081 * A B C D 2082 * 2083 * [A, B] and [C, D] are contained entirely in their respective halves 2084 * and form valid contiguous ranges as both u64 and s64 values. [A, B] 2085 * will be non-negative both as u64 and s64 (and in fact it will be 2086 * identical ranges no matter the signedness). [C, D] treated as s64 2087 * will be a range of negative values, while in u64 it will be 2088 * non-negative range of values larger than 0x8000000000000000. 2089 * 2090 * Now, any other range here can't be represented in both u64 and s64 2091 * simultaneously. E.g., [A, C], [A, D], [B, C], [B, D] are valid 2092 * contiguous u64 ranges, but they are discontinuous in s64. [B, C] 2093 * in s64 would be properly presented as [S64_MIN, C] and [B, S64_MAX], 2094 * for example. Similarly, valid s64 range [D, A] (going from negative 2095 * to positive values), would be two separate [D, U64_MAX] and [0, A] 2096 * ranges as u64. Currently reg_state can't represent two segments per 2097 * numeric domain, so in such situations we can only derive maximal 2098 * possible range ([0, U64_MAX] for u64, and [S64_MIN, S64_MAX] for s64). 2099 * 2100 * So we use these facts to derive umin/umax from smin/smax and vice 2101 * versa only if they stay within the same "half". This is equivalent 2102 * to checking sign bit: lower half will have sign bit as zero, upper 2103 * half have sign bit 1. Below in code we simplify this by just 2104 * casting umin/umax as smin/smax and checking if they form valid 2105 * range, and vice versa. Those are equivalent checks. 2106 */ 2107 if ((s64)reg->umin_value <= (s64)reg->umax_value) { 2108 reg->smin_value = max_t(s64, reg->smin_value, reg->umin_value); 2109 reg->smax_value = min_t(s64, reg->smax_value, reg->umax_value); 2110 } 2111 /* If we cannot cross the sign boundary, then signed and unsigned bounds 2112 * are the same, so combine. This works even in the negative case, e.g. 2113 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff. 2114 */ 2115 if ((u64)reg->smin_value <= (u64)reg->smax_value) { 2116 reg->umin_value = max_t(u64, reg->smin_value, reg->umin_value); 2117 reg->umax_value = min_t(u64, reg->smax_value, reg->umax_value); 2118 } 2119 } 2120 2121 static void __reg_deduce_mixed_bounds(struct bpf_reg_state *reg) 2122 { 2123 /* Try to tighten 64-bit bounds from 32-bit knowledge, using 32-bit 2124 * values on both sides of 64-bit range in hope to have tigher range. 2125 * E.g., if r1 is [0x1'00000000, 0x3'80000000], and we learn from 2126 * 32-bit signed > 0 operation that s32 bounds are now [1; 0x7fffffff]. 2127 * With this, we can substitute 1 as low 32-bits of _low_ 64-bit bound 2128 * (0x100000000 -> 0x100000001) and 0x7fffffff as low 32-bits of 2129 * _high_ 64-bit bound (0x380000000 -> 0x37fffffff) and arrive at a 2130 * better overall bounds for r1 as [0x1'000000001; 0x3'7fffffff]. 2131 * We just need to make sure that derived bounds we are intersecting 2132 * with are well-formed ranges in respecitve s64 or u64 domain, just 2133 * like we do with similar kinds of 32-to-64 or 64-to-32 adjustments. 2134 */ 2135 __u64 new_umin, new_umax; 2136 __s64 new_smin, new_smax; 2137 2138 /* u32 -> u64 tightening, it's always well-formed */ 2139 new_umin = (reg->umin_value & ~0xffffffffULL) | reg->u32_min_value; 2140 new_umax = (reg->umax_value & ~0xffffffffULL) | reg->u32_max_value; 2141 reg->umin_value = max_t(u64, reg->umin_value, new_umin); 2142 reg->umax_value = min_t(u64, reg->umax_value, new_umax); 2143 /* u32 -> s64 tightening, u32 range embedded into s64 preserves range validity */ 2144 new_smin = (reg->smin_value & ~0xffffffffULL) | reg->u32_min_value; 2145 new_smax = (reg->smax_value & ~0xffffffffULL) | reg->u32_max_value; 2146 reg->smin_value = max_t(s64, reg->smin_value, new_smin); 2147 reg->smax_value = min_t(s64, reg->smax_value, new_smax); 2148 2149 /* if s32 can be treated as valid u32 range, we can use it as well */ 2150 if ((u32)reg->s32_min_value <= (u32)reg->s32_max_value) { 2151 /* s32 -> u64 tightening */ 2152 new_umin = (reg->umin_value & ~0xffffffffULL) | (u32)reg->s32_min_value; 2153 new_umax = (reg->umax_value & ~0xffffffffULL) | (u32)reg->s32_max_value; 2154 reg->umin_value = max_t(u64, reg->umin_value, new_umin); 2155 reg->umax_value = min_t(u64, reg->umax_value, new_umax); 2156 /* s32 -> s64 tightening */ 2157 new_smin = (reg->smin_value & ~0xffffffffULL) | (u32)reg->s32_min_value; 2158 new_smax = (reg->smax_value & ~0xffffffffULL) | (u32)reg->s32_max_value; 2159 reg->smin_value = max_t(s64, reg->smin_value, new_smin); 2160 reg->smax_value = min_t(s64, reg->smax_value, new_smax); 2161 } 2162 } 2163 2164 static void __reg_deduce_bounds(struct bpf_reg_state *reg) 2165 { 2166 __reg32_deduce_bounds(reg); 2167 __reg64_deduce_bounds(reg); 2168 __reg_deduce_mixed_bounds(reg); 2169 } 2170 2171 /* Attempts to improve var_off based on unsigned min/max information */ 2172 static void __reg_bound_offset(struct bpf_reg_state *reg) 2173 { 2174 struct tnum var64_off = tnum_intersect(reg->var_off, 2175 tnum_range(reg->umin_value, 2176 reg->umax_value)); 2177 struct tnum var32_off = tnum_intersect(tnum_subreg(var64_off), 2178 tnum_range(reg->u32_min_value, 2179 reg->u32_max_value)); 2180 2181 reg->var_off = tnum_or(tnum_clear_subreg(var64_off), var32_off); 2182 } 2183 2184 static void reg_bounds_sync(struct bpf_reg_state *reg) 2185 { 2186 /* We might have learned new bounds from the var_off. */ 2187 __update_reg_bounds(reg); 2188 /* We might have learned something about the sign bit. */ 2189 __reg_deduce_bounds(reg); 2190 __reg_deduce_bounds(reg); 2191 /* We might have learned some bits from the bounds. */ 2192 __reg_bound_offset(reg); 2193 /* Intersecting with the old var_off might have improved our bounds 2194 * slightly, e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc), 2195 * then new var_off is (0; 0x7f...fc) which improves our umax. 2196 */ 2197 __update_reg_bounds(reg); 2198 } 2199 2200 static int reg_bounds_sanity_check(struct bpf_verifier_env *env, 2201 struct bpf_reg_state *reg, const char *ctx) 2202 { 2203 const char *msg; 2204 2205 if (reg->umin_value > reg->umax_value || 2206 reg->smin_value > reg->smax_value || 2207 reg->u32_min_value > reg->u32_max_value || 2208 reg->s32_min_value > reg->s32_max_value) { 2209 msg = "range bounds violation"; 2210 goto out; 2211 } 2212 2213 if (tnum_is_const(reg->var_off)) { 2214 u64 uval = reg->var_off.value; 2215 s64 sval = (s64)uval; 2216 2217 if (reg->umin_value != uval || reg->umax_value != uval || 2218 reg->smin_value != sval || reg->smax_value != sval) { 2219 msg = "const tnum out of sync with range bounds"; 2220 goto out; 2221 } 2222 } 2223 2224 if (tnum_subreg_is_const(reg->var_off)) { 2225 u32 uval32 = tnum_subreg(reg->var_off).value; 2226 s32 sval32 = (s32)uval32; 2227 2228 if (reg->u32_min_value != uval32 || reg->u32_max_value != uval32 || 2229 reg->s32_min_value != sval32 || reg->s32_max_value != sval32) { 2230 msg = "const subreg tnum out of sync with range bounds"; 2231 goto out; 2232 } 2233 } 2234 2235 return 0; 2236 out: 2237 verbose(env, "REG INVARIANTS VIOLATION (%s): %s u64=[%#llx, %#llx] " 2238 "s64=[%#llx, %#llx] u32=[%#x, %#x] s32=[%#x, %#x] var_off=(%#llx, %#llx)\n", 2239 ctx, msg, reg->umin_value, reg->umax_value, 2240 reg->smin_value, reg->smax_value, 2241 reg->u32_min_value, reg->u32_max_value, 2242 reg->s32_min_value, reg->s32_max_value, 2243 reg->var_off.value, reg->var_off.mask); 2244 if (env->test_reg_invariants) 2245 return -EFAULT; 2246 __mark_reg_unbounded(reg); 2247 return 0; 2248 } 2249 2250 static bool __reg32_bound_s64(s32 a) 2251 { 2252 return a >= 0 && a <= S32_MAX; 2253 } 2254 2255 static void __reg_assign_32_into_64(struct bpf_reg_state *reg) 2256 { 2257 reg->umin_value = reg->u32_min_value; 2258 reg->umax_value = reg->u32_max_value; 2259 2260 /* Attempt to pull 32-bit signed bounds into 64-bit bounds but must 2261 * be positive otherwise set to worse case bounds and refine later 2262 * from tnum. 2263 */ 2264 if (__reg32_bound_s64(reg->s32_min_value) && 2265 __reg32_bound_s64(reg->s32_max_value)) { 2266 reg->smin_value = reg->s32_min_value; 2267 reg->smax_value = reg->s32_max_value; 2268 } else { 2269 reg->smin_value = 0; 2270 reg->smax_value = U32_MAX; 2271 } 2272 } 2273 2274 /* Mark a register as having a completely unknown (scalar) value. */ 2275 static void __mark_reg_unknown(const struct bpf_verifier_env *env, 2276 struct bpf_reg_state *reg) 2277 { 2278 /* 2279 * Clear type, off, and union(map_ptr, range) and 2280 * padding between 'type' and union 2281 */ 2282 memset(reg, 0, offsetof(struct bpf_reg_state, var_off)); 2283 reg->type = SCALAR_VALUE; 2284 reg->id = 0; 2285 reg->ref_obj_id = 0; 2286 reg->var_off = tnum_unknown; 2287 reg->frameno = 0; 2288 reg->precise = !env->bpf_capable; 2289 __mark_reg_unbounded(reg); 2290 } 2291 2292 static void mark_reg_unknown(struct bpf_verifier_env *env, 2293 struct bpf_reg_state *regs, u32 regno) 2294 { 2295 if (WARN_ON(regno >= MAX_BPF_REG)) { 2296 verbose(env, "mark_reg_unknown(regs, %u)\n", regno); 2297 /* Something bad happened, let's kill all regs except FP */ 2298 for (regno = 0; regno < BPF_REG_FP; regno++) 2299 __mark_reg_not_init(env, regs + regno); 2300 return; 2301 } 2302 __mark_reg_unknown(env, regs + regno); 2303 } 2304 2305 static void __mark_reg_not_init(const struct bpf_verifier_env *env, 2306 struct bpf_reg_state *reg) 2307 { 2308 __mark_reg_unknown(env, reg); 2309 reg->type = NOT_INIT; 2310 } 2311 2312 static void mark_reg_not_init(struct bpf_verifier_env *env, 2313 struct bpf_reg_state *regs, u32 regno) 2314 { 2315 if (WARN_ON(regno >= MAX_BPF_REG)) { 2316 verbose(env, "mark_reg_not_init(regs, %u)\n", regno); 2317 /* Something bad happened, let's kill all regs except FP */ 2318 for (regno = 0; regno < BPF_REG_FP; regno++) 2319 __mark_reg_not_init(env, regs + regno); 2320 return; 2321 } 2322 __mark_reg_not_init(env, regs + regno); 2323 } 2324 2325 static void mark_btf_ld_reg(struct bpf_verifier_env *env, 2326 struct bpf_reg_state *regs, u32 regno, 2327 enum bpf_reg_type reg_type, 2328 struct btf *btf, u32 btf_id, 2329 enum bpf_type_flag flag) 2330 { 2331 if (reg_type == SCALAR_VALUE) { 2332 mark_reg_unknown(env, regs, regno); 2333 return; 2334 } 2335 mark_reg_known_zero(env, regs, regno); 2336 regs[regno].type = PTR_TO_BTF_ID | flag; 2337 regs[regno].btf = btf; 2338 regs[regno].btf_id = btf_id; 2339 } 2340 2341 #define DEF_NOT_SUBREG (0) 2342 static void init_reg_state(struct bpf_verifier_env *env, 2343 struct bpf_func_state *state) 2344 { 2345 struct bpf_reg_state *regs = state->regs; 2346 int i; 2347 2348 for (i = 0; i < MAX_BPF_REG; i++) { 2349 mark_reg_not_init(env, regs, i); 2350 regs[i].live = REG_LIVE_NONE; 2351 regs[i].parent = NULL; 2352 regs[i].subreg_def = DEF_NOT_SUBREG; 2353 } 2354 2355 /* frame pointer */ 2356 regs[BPF_REG_FP].type = PTR_TO_STACK; 2357 mark_reg_known_zero(env, regs, BPF_REG_FP); 2358 regs[BPF_REG_FP].frameno = state->frameno; 2359 } 2360 2361 static struct bpf_retval_range retval_range(s32 minval, s32 maxval) 2362 { 2363 return (struct bpf_retval_range){ minval, maxval }; 2364 } 2365 2366 #define BPF_MAIN_FUNC (-1) 2367 static void init_func_state(struct bpf_verifier_env *env, 2368 struct bpf_func_state *state, 2369 int callsite, int frameno, int subprogno) 2370 { 2371 state->callsite = callsite; 2372 state->frameno = frameno; 2373 state->subprogno = subprogno; 2374 state->callback_ret_range = retval_range(0, 0); 2375 init_reg_state(env, state); 2376 mark_verifier_state_scratched(env); 2377 } 2378 2379 /* Similar to push_stack(), but for async callbacks */ 2380 static struct bpf_verifier_state *push_async_cb(struct bpf_verifier_env *env, 2381 int insn_idx, int prev_insn_idx, 2382 int subprog) 2383 { 2384 struct bpf_verifier_stack_elem *elem; 2385 struct bpf_func_state *frame; 2386 2387 elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL); 2388 if (!elem) 2389 goto err; 2390 2391 elem->insn_idx = insn_idx; 2392 elem->prev_insn_idx = prev_insn_idx; 2393 elem->next = env->head; 2394 elem->log_pos = env->log.end_pos; 2395 env->head = elem; 2396 env->stack_size++; 2397 if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) { 2398 verbose(env, 2399 "The sequence of %d jumps is too complex for async cb.\n", 2400 env->stack_size); 2401 goto err; 2402 } 2403 /* Unlike push_stack() do not copy_verifier_state(). 2404 * The caller state doesn't matter. 2405 * This is async callback. It starts in a fresh stack. 2406 * Initialize it similar to do_check_common(). 2407 */ 2408 elem->st.branches = 1; 2409 frame = kzalloc(sizeof(*frame), GFP_KERNEL); 2410 if (!frame) 2411 goto err; 2412 init_func_state(env, frame, 2413 BPF_MAIN_FUNC /* callsite */, 2414 0 /* frameno within this callchain */, 2415 subprog /* subprog number within this prog */); 2416 elem->st.frame[0] = frame; 2417 return &elem->st; 2418 err: 2419 free_verifier_state(env->cur_state, true); 2420 env->cur_state = NULL; 2421 /* pop all elements and return */ 2422 while (!pop_stack(env, NULL, NULL, false)); 2423 return NULL; 2424 } 2425 2426 2427 enum reg_arg_type { 2428 SRC_OP, /* register is used as source operand */ 2429 DST_OP, /* register is used as destination operand */ 2430 DST_OP_NO_MARK /* same as above, check only, don't mark */ 2431 }; 2432 2433 static int cmp_subprogs(const void *a, const void *b) 2434 { 2435 return ((struct bpf_subprog_info *)a)->start - 2436 ((struct bpf_subprog_info *)b)->start; 2437 } 2438 2439 static int find_subprog(struct bpf_verifier_env *env, int off) 2440 { 2441 struct bpf_subprog_info *p; 2442 2443 p = bsearch(&off, env->subprog_info, env->subprog_cnt, 2444 sizeof(env->subprog_info[0]), cmp_subprogs); 2445 if (!p) 2446 return -ENOENT; 2447 return p - env->subprog_info; 2448 2449 } 2450 2451 static int add_subprog(struct bpf_verifier_env *env, int off) 2452 { 2453 int insn_cnt = env->prog->len; 2454 int ret; 2455 2456 if (off >= insn_cnt || off < 0) { 2457 verbose(env, "call to invalid destination\n"); 2458 return -EINVAL; 2459 } 2460 ret = find_subprog(env, off); 2461 if (ret >= 0) 2462 return ret; 2463 if (env->subprog_cnt >= BPF_MAX_SUBPROGS) { 2464 verbose(env, "too many subprograms\n"); 2465 return -E2BIG; 2466 } 2467 /* determine subprog starts. The end is one before the next starts */ 2468 env->subprog_info[env->subprog_cnt++].start = off; 2469 sort(env->subprog_info, env->subprog_cnt, 2470 sizeof(env->subprog_info[0]), cmp_subprogs, NULL); 2471 return env->subprog_cnt - 1; 2472 } 2473 2474 static int bpf_find_exception_callback_insn_off(struct bpf_verifier_env *env) 2475 { 2476 struct bpf_prog_aux *aux = env->prog->aux; 2477 struct btf *btf = aux->btf; 2478 const struct btf_type *t; 2479 u32 main_btf_id, id; 2480 const char *name; 2481 int ret, i; 2482 2483 /* Non-zero func_info_cnt implies valid btf */ 2484 if (!aux->func_info_cnt) 2485 return 0; 2486 main_btf_id = aux->func_info[0].type_id; 2487 2488 t = btf_type_by_id(btf, main_btf_id); 2489 if (!t) { 2490 verbose(env, "invalid btf id for main subprog in func_info\n"); 2491 return -EINVAL; 2492 } 2493 2494 name = btf_find_decl_tag_value(btf, t, -1, "exception_callback:"); 2495 if (IS_ERR(name)) { 2496 ret = PTR_ERR(name); 2497 /* If there is no tag present, there is no exception callback */ 2498 if (ret == -ENOENT) 2499 ret = 0; 2500 else if (ret == -EEXIST) 2501 verbose(env, "multiple exception callback tags for main subprog\n"); 2502 return ret; 2503 } 2504 2505 ret = btf_find_by_name_kind(btf, name, BTF_KIND_FUNC); 2506 if (ret < 0) { 2507 verbose(env, "exception callback '%s' could not be found in BTF\n", name); 2508 return ret; 2509 } 2510 id = ret; 2511 t = btf_type_by_id(btf, id); 2512 if (btf_func_linkage(t) != BTF_FUNC_GLOBAL) { 2513 verbose(env, "exception callback '%s' must have global linkage\n", name); 2514 return -EINVAL; 2515 } 2516 ret = 0; 2517 for (i = 0; i < aux->func_info_cnt; i++) { 2518 if (aux->func_info[i].type_id != id) 2519 continue; 2520 ret = aux->func_info[i].insn_off; 2521 /* Further func_info and subprog checks will also happen 2522 * later, so assume this is the right insn_off for now. 2523 */ 2524 if (!ret) { 2525 verbose(env, "invalid exception callback insn_off in func_info: 0\n"); 2526 ret = -EINVAL; 2527 } 2528 } 2529 if (!ret) { 2530 verbose(env, "exception callback type id not found in func_info\n"); 2531 ret = -EINVAL; 2532 } 2533 return ret; 2534 } 2535 2536 #define MAX_KFUNC_DESCS 256 2537 #define MAX_KFUNC_BTFS 256 2538 2539 struct bpf_kfunc_desc { 2540 struct btf_func_model func_model; 2541 u32 func_id; 2542 s32 imm; 2543 u16 offset; 2544 unsigned long addr; 2545 }; 2546 2547 struct bpf_kfunc_btf { 2548 struct btf *btf; 2549 struct module *module; 2550 u16 offset; 2551 }; 2552 2553 struct bpf_kfunc_desc_tab { 2554 /* Sorted by func_id (BTF ID) and offset (fd_array offset) during 2555 * verification. JITs do lookups by bpf_insn, where func_id may not be 2556 * available, therefore at the end of verification do_misc_fixups() 2557 * sorts this by imm and offset. 2558 */ 2559 struct bpf_kfunc_desc descs[MAX_KFUNC_DESCS]; 2560 u32 nr_descs; 2561 }; 2562 2563 struct bpf_kfunc_btf_tab { 2564 struct bpf_kfunc_btf descs[MAX_KFUNC_BTFS]; 2565 u32 nr_descs; 2566 }; 2567 2568 static int kfunc_desc_cmp_by_id_off(const void *a, const void *b) 2569 { 2570 const struct bpf_kfunc_desc *d0 = a; 2571 const struct bpf_kfunc_desc *d1 = b; 2572 2573 /* func_id is not greater than BTF_MAX_TYPE */ 2574 return d0->func_id - d1->func_id ?: d0->offset - d1->offset; 2575 } 2576 2577 static int kfunc_btf_cmp_by_off(const void *a, const void *b) 2578 { 2579 const struct bpf_kfunc_btf *d0 = a; 2580 const struct bpf_kfunc_btf *d1 = b; 2581 2582 return d0->offset - d1->offset; 2583 } 2584 2585 static const struct bpf_kfunc_desc * 2586 find_kfunc_desc(const struct bpf_prog *prog, u32 func_id, u16 offset) 2587 { 2588 struct bpf_kfunc_desc desc = { 2589 .func_id = func_id, 2590 .offset = offset, 2591 }; 2592 struct bpf_kfunc_desc_tab *tab; 2593 2594 tab = prog->aux->kfunc_tab; 2595 return bsearch(&desc, tab->descs, tab->nr_descs, 2596 sizeof(tab->descs[0]), kfunc_desc_cmp_by_id_off); 2597 } 2598 2599 int bpf_get_kfunc_addr(const struct bpf_prog *prog, u32 func_id, 2600 u16 btf_fd_idx, u8 **func_addr) 2601 { 2602 const struct bpf_kfunc_desc *desc; 2603 2604 desc = find_kfunc_desc(prog, func_id, btf_fd_idx); 2605 if (!desc) 2606 return -EFAULT; 2607 2608 *func_addr = (u8 *)desc->addr; 2609 return 0; 2610 } 2611 2612 static struct btf *__find_kfunc_desc_btf(struct bpf_verifier_env *env, 2613 s16 offset) 2614 { 2615 struct bpf_kfunc_btf kf_btf = { .offset = offset }; 2616 struct bpf_kfunc_btf_tab *tab; 2617 struct bpf_kfunc_btf *b; 2618 struct module *mod; 2619 struct btf *btf; 2620 int btf_fd; 2621 2622 tab = env->prog->aux->kfunc_btf_tab; 2623 b = bsearch(&kf_btf, tab->descs, tab->nr_descs, 2624 sizeof(tab->descs[0]), kfunc_btf_cmp_by_off); 2625 if (!b) { 2626 if (tab->nr_descs == MAX_KFUNC_BTFS) { 2627 verbose(env, "too many different module BTFs\n"); 2628 return ERR_PTR(-E2BIG); 2629 } 2630 2631 if (bpfptr_is_null(env->fd_array)) { 2632 verbose(env, "kfunc offset > 0 without fd_array is invalid\n"); 2633 return ERR_PTR(-EPROTO); 2634 } 2635 2636 if (copy_from_bpfptr_offset(&btf_fd, env->fd_array, 2637 offset * sizeof(btf_fd), 2638 sizeof(btf_fd))) 2639 return ERR_PTR(-EFAULT); 2640 2641 btf = btf_get_by_fd(btf_fd); 2642 if (IS_ERR(btf)) { 2643 verbose(env, "invalid module BTF fd specified\n"); 2644 return btf; 2645 } 2646 2647 if (!btf_is_module(btf)) { 2648 verbose(env, "BTF fd for kfunc is not a module BTF\n"); 2649 btf_put(btf); 2650 return ERR_PTR(-EINVAL); 2651 } 2652 2653 mod = btf_try_get_module(btf); 2654 if (!mod) { 2655 btf_put(btf); 2656 return ERR_PTR(-ENXIO); 2657 } 2658 2659 b = &tab->descs[tab->nr_descs++]; 2660 b->btf = btf; 2661 b->module = mod; 2662 b->offset = offset; 2663 2664 sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]), 2665 kfunc_btf_cmp_by_off, NULL); 2666 } 2667 return b->btf; 2668 } 2669 2670 void bpf_free_kfunc_btf_tab(struct bpf_kfunc_btf_tab *tab) 2671 { 2672 if (!tab) 2673 return; 2674 2675 while (tab->nr_descs--) { 2676 module_put(tab->descs[tab->nr_descs].module); 2677 btf_put(tab->descs[tab->nr_descs].btf); 2678 } 2679 kfree(tab); 2680 } 2681 2682 static struct btf *find_kfunc_desc_btf(struct bpf_verifier_env *env, s16 offset) 2683 { 2684 if (offset) { 2685 if (offset < 0) { 2686 /* In the future, this can be allowed to increase limit 2687 * of fd index into fd_array, interpreted as u16. 2688 */ 2689 verbose(env, "negative offset disallowed for kernel module function call\n"); 2690 return ERR_PTR(-EINVAL); 2691 } 2692 2693 return __find_kfunc_desc_btf(env, offset); 2694 } 2695 return btf_vmlinux ?: ERR_PTR(-ENOENT); 2696 } 2697 2698 static int add_kfunc_call(struct bpf_verifier_env *env, u32 func_id, s16 offset) 2699 { 2700 const struct btf_type *func, *func_proto; 2701 struct bpf_kfunc_btf_tab *btf_tab; 2702 struct bpf_kfunc_desc_tab *tab; 2703 struct bpf_prog_aux *prog_aux; 2704 struct bpf_kfunc_desc *desc; 2705 const char *func_name; 2706 struct btf *desc_btf; 2707 unsigned long call_imm; 2708 unsigned long addr; 2709 int err; 2710 2711 prog_aux = env->prog->aux; 2712 tab = prog_aux->kfunc_tab; 2713 btf_tab = prog_aux->kfunc_btf_tab; 2714 if (!tab) { 2715 if (!btf_vmlinux) { 2716 verbose(env, "calling kernel function is not supported without CONFIG_DEBUG_INFO_BTF\n"); 2717 return -ENOTSUPP; 2718 } 2719 2720 if (!env->prog->jit_requested) { 2721 verbose(env, "JIT is required for calling kernel function\n"); 2722 return -ENOTSUPP; 2723 } 2724 2725 if (!bpf_jit_supports_kfunc_call()) { 2726 verbose(env, "JIT does not support calling kernel function\n"); 2727 return -ENOTSUPP; 2728 } 2729 2730 if (!env->prog->gpl_compatible) { 2731 verbose(env, "cannot call kernel function from non-GPL compatible program\n"); 2732 return -EINVAL; 2733 } 2734 2735 tab = kzalloc(sizeof(*tab), GFP_KERNEL); 2736 if (!tab) 2737 return -ENOMEM; 2738 prog_aux->kfunc_tab = tab; 2739 } 2740 2741 /* func_id == 0 is always invalid, but instead of returning an error, be 2742 * conservative and wait until the code elimination pass before returning 2743 * error, so that invalid calls that get pruned out can be in BPF programs 2744 * loaded from userspace. It is also required that offset be untouched 2745 * for such calls. 2746 */ 2747 if (!func_id && !offset) 2748 return 0; 2749 2750 if (!btf_tab && offset) { 2751 btf_tab = kzalloc(sizeof(*btf_tab), GFP_KERNEL); 2752 if (!btf_tab) 2753 return -ENOMEM; 2754 prog_aux->kfunc_btf_tab = btf_tab; 2755 } 2756 2757 desc_btf = find_kfunc_desc_btf(env, offset); 2758 if (IS_ERR(desc_btf)) { 2759 verbose(env, "failed to find BTF for kernel function\n"); 2760 return PTR_ERR(desc_btf); 2761 } 2762 2763 if (find_kfunc_desc(env->prog, func_id, offset)) 2764 return 0; 2765 2766 if (tab->nr_descs == MAX_KFUNC_DESCS) { 2767 verbose(env, "too many different kernel function calls\n"); 2768 return -E2BIG; 2769 } 2770 2771 func = btf_type_by_id(desc_btf, func_id); 2772 if (!func || !btf_type_is_func(func)) { 2773 verbose(env, "kernel btf_id %u is not a function\n", 2774 func_id); 2775 return -EINVAL; 2776 } 2777 func_proto = btf_type_by_id(desc_btf, func->type); 2778 if (!func_proto || !btf_type_is_func_proto(func_proto)) { 2779 verbose(env, "kernel function btf_id %u does not have a valid func_proto\n", 2780 func_id); 2781 return -EINVAL; 2782 } 2783 2784 func_name = btf_name_by_offset(desc_btf, func->name_off); 2785 addr = kallsyms_lookup_name(func_name); 2786 if (!addr) { 2787 verbose(env, "cannot find address for kernel function %s\n", 2788 func_name); 2789 return -EINVAL; 2790 } 2791 specialize_kfunc(env, func_id, offset, &addr); 2792 2793 if (bpf_jit_supports_far_kfunc_call()) { 2794 call_imm = func_id; 2795 } else { 2796 call_imm = BPF_CALL_IMM(addr); 2797 /* Check whether the relative offset overflows desc->imm */ 2798 if ((unsigned long)(s32)call_imm != call_imm) { 2799 verbose(env, "address of kernel function %s is out of range\n", 2800 func_name); 2801 return -EINVAL; 2802 } 2803 } 2804 2805 if (bpf_dev_bound_kfunc_id(func_id)) { 2806 err = bpf_dev_bound_kfunc_check(&env->log, prog_aux); 2807 if (err) 2808 return err; 2809 } 2810 2811 desc = &tab->descs[tab->nr_descs++]; 2812 desc->func_id = func_id; 2813 desc->imm = call_imm; 2814 desc->offset = offset; 2815 desc->addr = addr; 2816 err = btf_distill_func_proto(&env->log, desc_btf, 2817 func_proto, func_name, 2818 &desc->func_model); 2819 if (!err) 2820 sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]), 2821 kfunc_desc_cmp_by_id_off, NULL); 2822 return err; 2823 } 2824 2825 static int kfunc_desc_cmp_by_imm_off(const void *a, const void *b) 2826 { 2827 const struct bpf_kfunc_desc *d0 = a; 2828 const struct bpf_kfunc_desc *d1 = b; 2829 2830 if (d0->imm != d1->imm) 2831 return d0->imm < d1->imm ? -1 : 1; 2832 if (d0->offset != d1->offset) 2833 return d0->offset < d1->offset ? -1 : 1; 2834 return 0; 2835 } 2836 2837 static void sort_kfunc_descs_by_imm_off(struct bpf_prog *prog) 2838 { 2839 struct bpf_kfunc_desc_tab *tab; 2840 2841 tab = prog->aux->kfunc_tab; 2842 if (!tab) 2843 return; 2844 2845 sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]), 2846 kfunc_desc_cmp_by_imm_off, NULL); 2847 } 2848 2849 bool bpf_prog_has_kfunc_call(const struct bpf_prog *prog) 2850 { 2851 return !!prog->aux->kfunc_tab; 2852 } 2853 2854 const struct btf_func_model * 2855 bpf_jit_find_kfunc_model(const struct bpf_prog *prog, 2856 const struct bpf_insn *insn) 2857 { 2858 const struct bpf_kfunc_desc desc = { 2859 .imm = insn->imm, 2860 .offset = insn->off, 2861 }; 2862 const struct bpf_kfunc_desc *res; 2863 struct bpf_kfunc_desc_tab *tab; 2864 2865 tab = prog->aux->kfunc_tab; 2866 res = bsearch(&desc, tab->descs, tab->nr_descs, 2867 sizeof(tab->descs[0]), kfunc_desc_cmp_by_imm_off); 2868 2869 return res ? &res->func_model : NULL; 2870 } 2871 2872 static int add_subprog_and_kfunc(struct bpf_verifier_env *env) 2873 { 2874 struct bpf_subprog_info *subprog = env->subprog_info; 2875 int i, ret, insn_cnt = env->prog->len, ex_cb_insn; 2876 struct bpf_insn *insn = env->prog->insnsi; 2877 2878 /* Add entry function. */ 2879 ret = add_subprog(env, 0); 2880 if (ret) 2881 return ret; 2882 2883 for (i = 0; i < insn_cnt; i++, insn++) { 2884 if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn) && 2885 !bpf_pseudo_kfunc_call(insn)) 2886 continue; 2887 2888 if (!env->bpf_capable) { 2889 verbose(env, "loading/calling other bpf or kernel functions are allowed for CAP_BPF and CAP_SYS_ADMIN\n"); 2890 return -EPERM; 2891 } 2892 2893 if (bpf_pseudo_func(insn) || bpf_pseudo_call(insn)) 2894 ret = add_subprog(env, i + insn->imm + 1); 2895 else 2896 ret = add_kfunc_call(env, insn->imm, insn->off); 2897 2898 if (ret < 0) 2899 return ret; 2900 } 2901 2902 ret = bpf_find_exception_callback_insn_off(env); 2903 if (ret < 0) 2904 return ret; 2905 ex_cb_insn = ret; 2906 2907 /* If ex_cb_insn > 0, this means that the main program has a subprog 2908 * marked using BTF decl tag to serve as the exception callback. 2909 */ 2910 if (ex_cb_insn) { 2911 ret = add_subprog(env, ex_cb_insn); 2912 if (ret < 0) 2913 return ret; 2914 for (i = 1; i < env->subprog_cnt; i++) { 2915 if (env->subprog_info[i].start != ex_cb_insn) 2916 continue; 2917 env->exception_callback_subprog = i; 2918 mark_subprog_exc_cb(env, i); 2919 break; 2920 } 2921 } 2922 2923 /* Add a fake 'exit' subprog which could simplify subprog iteration 2924 * logic. 'subprog_cnt' should not be increased. 2925 */ 2926 subprog[env->subprog_cnt].start = insn_cnt; 2927 2928 if (env->log.level & BPF_LOG_LEVEL2) 2929 for (i = 0; i < env->subprog_cnt; i++) 2930 verbose(env, "func#%d @%d\n", i, subprog[i].start); 2931 2932 return 0; 2933 } 2934 2935 static int check_subprogs(struct bpf_verifier_env *env) 2936 { 2937 int i, subprog_start, subprog_end, off, cur_subprog = 0; 2938 struct bpf_subprog_info *subprog = env->subprog_info; 2939 struct bpf_insn *insn = env->prog->insnsi; 2940 int insn_cnt = env->prog->len; 2941 2942 /* now check that all jumps are within the same subprog */ 2943 subprog_start = subprog[cur_subprog].start; 2944 subprog_end = subprog[cur_subprog + 1].start; 2945 for (i = 0; i < insn_cnt; i++) { 2946 u8 code = insn[i].code; 2947 2948 if (code == (BPF_JMP | BPF_CALL) && 2949 insn[i].src_reg == 0 && 2950 insn[i].imm == BPF_FUNC_tail_call) 2951 subprog[cur_subprog].has_tail_call = true; 2952 if (BPF_CLASS(code) == BPF_LD && 2953 (BPF_MODE(code) == BPF_ABS || BPF_MODE(code) == BPF_IND)) 2954 subprog[cur_subprog].has_ld_abs = true; 2955 if (BPF_CLASS(code) != BPF_JMP && BPF_CLASS(code) != BPF_JMP32) 2956 goto next; 2957 if (BPF_OP(code) == BPF_EXIT || BPF_OP(code) == BPF_CALL) 2958 goto next; 2959 if (code == (BPF_JMP32 | BPF_JA)) 2960 off = i + insn[i].imm + 1; 2961 else 2962 off = i + insn[i].off + 1; 2963 if (off < subprog_start || off >= subprog_end) { 2964 verbose(env, "jump out of range from insn %d to %d\n", i, off); 2965 return -EINVAL; 2966 } 2967 next: 2968 if (i == subprog_end - 1) { 2969 /* to avoid fall-through from one subprog into another 2970 * the last insn of the subprog should be either exit 2971 * or unconditional jump back or bpf_throw call 2972 */ 2973 if (code != (BPF_JMP | BPF_EXIT) && 2974 code != (BPF_JMP32 | BPF_JA) && 2975 code != (BPF_JMP | BPF_JA)) { 2976 verbose(env, "last insn is not an exit or jmp\n"); 2977 return -EINVAL; 2978 } 2979 subprog_start = subprog_end; 2980 cur_subprog++; 2981 if (cur_subprog < env->subprog_cnt) 2982 subprog_end = subprog[cur_subprog + 1].start; 2983 } 2984 } 2985 return 0; 2986 } 2987 2988 /* Parentage chain of this register (or stack slot) should take care of all 2989 * issues like callee-saved registers, stack slot allocation time, etc. 2990 */ 2991 static int mark_reg_read(struct bpf_verifier_env *env, 2992 const struct bpf_reg_state *state, 2993 struct bpf_reg_state *parent, u8 flag) 2994 { 2995 bool writes = parent == state->parent; /* Observe write marks */ 2996 int cnt = 0; 2997 2998 while (parent) { 2999 /* if read wasn't screened by an earlier write ... */ 3000 if (writes && state->live & REG_LIVE_WRITTEN) 3001 break; 3002 if (parent->live & REG_LIVE_DONE) { 3003 verbose(env, "verifier BUG type %s var_off %lld off %d\n", 3004 reg_type_str(env, parent->type), 3005 parent->var_off.value, parent->off); 3006 return -EFAULT; 3007 } 3008 /* The first condition is more likely to be true than the 3009 * second, checked it first. 3010 */ 3011 if ((parent->live & REG_LIVE_READ) == flag || 3012 parent->live & REG_LIVE_READ64) 3013 /* The parentage chain never changes and 3014 * this parent was already marked as LIVE_READ. 3015 * There is no need to keep walking the chain again and 3016 * keep re-marking all parents as LIVE_READ. 3017 * This case happens when the same register is read 3018 * multiple times without writes into it in-between. 3019 * Also, if parent has the stronger REG_LIVE_READ64 set, 3020 * then no need to set the weak REG_LIVE_READ32. 3021 */ 3022 break; 3023 /* ... then we depend on parent's value */ 3024 parent->live |= flag; 3025 /* REG_LIVE_READ64 overrides REG_LIVE_READ32. */ 3026 if (flag == REG_LIVE_READ64) 3027 parent->live &= ~REG_LIVE_READ32; 3028 state = parent; 3029 parent = state->parent; 3030 writes = true; 3031 cnt++; 3032 } 3033 3034 if (env->longest_mark_read_walk < cnt) 3035 env->longest_mark_read_walk = cnt; 3036 return 0; 3037 } 3038 3039 static int mark_dynptr_read(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 3040 { 3041 struct bpf_func_state *state = func(env, reg); 3042 int spi, ret; 3043 3044 /* For CONST_PTR_TO_DYNPTR, it must have already been done by 3045 * check_reg_arg in check_helper_call and mark_btf_func_reg_size in 3046 * check_kfunc_call. 3047 */ 3048 if (reg->type == CONST_PTR_TO_DYNPTR) 3049 return 0; 3050 spi = dynptr_get_spi(env, reg); 3051 if (spi < 0) 3052 return spi; 3053 /* Caller ensures dynptr is valid and initialized, which means spi is in 3054 * bounds and spi is the first dynptr slot. Simply mark stack slot as 3055 * read. 3056 */ 3057 ret = mark_reg_read(env, &state->stack[spi].spilled_ptr, 3058 state->stack[spi].spilled_ptr.parent, REG_LIVE_READ64); 3059 if (ret) 3060 return ret; 3061 return mark_reg_read(env, &state->stack[spi - 1].spilled_ptr, 3062 state->stack[spi - 1].spilled_ptr.parent, REG_LIVE_READ64); 3063 } 3064 3065 static int mark_iter_read(struct bpf_verifier_env *env, struct bpf_reg_state *reg, 3066 int spi, int nr_slots) 3067 { 3068 struct bpf_func_state *state = func(env, reg); 3069 int err, i; 3070 3071 for (i = 0; i < nr_slots; i++) { 3072 struct bpf_reg_state *st = &state->stack[spi - i].spilled_ptr; 3073 3074 err = mark_reg_read(env, st, st->parent, REG_LIVE_READ64); 3075 if (err) 3076 return err; 3077 3078 mark_stack_slot_scratched(env, spi - i); 3079 } 3080 3081 return 0; 3082 } 3083 3084 /* This function is supposed to be used by the following 32-bit optimization 3085 * code only. It returns TRUE if the source or destination register operates 3086 * on 64-bit, otherwise return FALSE. 3087 */ 3088 static bool is_reg64(struct bpf_verifier_env *env, struct bpf_insn *insn, 3089 u32 regno, struct bpf_reg_state *reg, enum reg_arg_type t) 3090 { 3091 u8 code, class, op; 3092 3093 code = insn->code; 3094 class = BPF_CLASS(code); 3095 op = BPF_OP(code); 3096 if (class == BPF_JMP) { 3097 /* BPF_EXIT for "main" will reach here. Return TRUE 3098 * conservatively. 3099 */ 3100 if (op == BPF_EXIT) 3101 return true; 3102 if (op == BPF_CALL) { 3103 /* BPF to BPF call will reach here because of marking 3104 * caller saved clobber with DST_OP_NO_MARK for which we 3105 * don't care the register def because they are anyway 3106 * marked as NOT_INIT already. 3107 */ 3108 if (insn->src_reg == BPF_PSEUDO_CALL) 3109 return false; 3110 /* Helper call will reach here because of arg type 3111 * check, conservatively return TRUE. 3112 */ 3113 if (t == SRC_OP) 3114 return true; 3115 3116 return false; 3117 } 3118 } 3119 3120 if (class == BPF_ALU64 && op == BPF_END && (insn->imm == 16 || insn->imm == 32)) 3121 return false; 3122 3123 if (class == BPF_ALU64 || class == BPF_JMP || 3124 (class == BPF_ALU && op == BPF_END && insn->imm == 64)) 3125 return true; 3126 3127 if (class == BPF_ALU || class == BPF_JMP32) 3128 return false; 3129 3130 if (class == BPF_LDX) { 3131 if (t != SRC_OP) 3132 return BPF_SIZE(code) == BPF_DW || BPF_MODE(code) == BPF_MEMSX; 3133 /* LDX source must be ptr. */ 3134 return true; 3135 } 3136 3137 if (class == BPF_STX) { 3138 /* BPF_STX (including atomic variants) has multiple source 3139 * operands, one of which is a ptr. Check whether the caller is 3140 * asking about it. 3141 */ 3142 if (t == SRC_OP && reg->type != SCALAR_VALUE) 3143 return true; 3144 return BPF_SIZE(code) == BPF_DW; 3145 } 3146 3147 if (class == BPF_LD) { 3148 u8 mode = BPF_MODE(code); 3149 3150 /* LD_IMM64 */ 3151 if (mode == BPF_IMM) 3152 return true; 3153 3154 /* Both LD_IND and LD_ABS return 32-bit data. */ 3155 if (t != SRC_OP) 3156 return false; 3157 3158 /* Implicit ctx ptr. */ 3159 if (regno == BPF_REG_6) 3160 return true; 3161 3162 /* Explicit source could be any width. */ 3163 return true; 3164 } 3165 3166 if (class == BPF_ST) 3167 /* The only source register for BPF_ST is a ptr. */ 3168 return true; 3169 3170 /* Conservatively return true at default. */ 3171 return true; 3172 } 3173 3174 /* Return the regno defined by the insn, or -1. */ 3175 static int insn_def_regno(const struct bpf_insn *insn) 3176 { 3177 switch (BPF_CLASS(insn->code)) { 3178 case BPF_JMP: 3179 case BPF_JMP32: 3180 case BPF_ST: 3181 return -1; 3182 case BPF_STX: 3183 if (BPF_MODE(insn->code) == BPF_ATOMIC && 3184 (insn->imm & BPF_FETCH)) { 3185 if (insn->imm == BPF_CMPXCHG) 3186 return BPF_REG_0; 3187 else 3188 return insn->src_reg; 3189 } else { 3190 return -1; 3191 } 3192 default: 3193 return insn->dst_reg; 3194 } 3195 } 3196 3197 /* Return TRUE if INSN has defined any 32-bit value explicitly. */ 3198 static bool insn_has_def32(struct bpf_verifier_env *env, struct bpf_insn *insn) 3199 { 3200 int dst_reg = insn_def_regno(insn); 3201 3202 if (dst_reg == -1) 3203 return false; 3204 3205 return !is_reg64(env, insn, dst_reg, NULL, DST_OP); 3206 } 3207 3208 static void mark_insn_zext(struct bpf_verifier_env *env, 3209 struct bpf_reg_state *reg) 3210 { 3211 s32 def_idx = reg->subreg_def; 3212 3213 if (def_idx == DEF_NOT_SUBREG) 3214 return; 3215 3216 env->insn_aux_data[def_idx - 1].zext_dst = true; 3217 /* The dst will be zero extended, so won't be sub-register anymore. */ 3218 reg->subreg_def = DEF_NOT_SUBREG; 3219 } 3220 3221 static int __check_reg_arg(struct bpf_verifier_env *env, struct bpf_reg_state *regs, u32 regno, 3222 enum reg_arg_type t) 3223 { 3224 struct bpf_insn *insn = env->prog->insnsi + env->insn_idx; 3225 struct bpf_reg_state *reg; 3226 bool rw64; 3227 3228 if (regno >= MAX_BPF_REG) { 3229 verbose(env, "R%d is invalid\n", regno); 3230 return -EINVAL; 3231 } 3232 3233 mark_reg_scratched(env, regno); 3234 3235 reg = ®s[regno]; 3236 rw64 = is_reg64(env, insn, regno, reg, t); 3237 if (t == SRC_OP) { 3238 /* check whether register used as source operand can be read */ 3239 if (reg->type == NOT_INIT) { 3240 verbose(env, "R%d !read_ok\n", regno); 3241 return -EACCES; 3242 } 3243 /* We don't need to worry about FP liveness because it's read-only */ 3244 if (regno == BPF_REG_FP) 3245 return 0; 3246 3247 if (rw64) 3248 mark_insn_zext(env, reg); 3249 3250 return mark_reg_read(env, reg, reg->parent, 3251 rw64 ? REG_LIVE_READ64 : REG_LIVE_READ32); 3252 } else { 3253 /* check whether register used as dest operand can be written to */ 3254 if (regno == BPF_REG_FP) { 3255 verbose(env, "frame pointer is read only\n"); 3256 return -EACCES; 3257 } 3258 reg->live |= REG_LIVE_WRITTEN; 3259 reg->subreg_def = rw64 ? DEF_NOT_SUBREG : env->insn_idx + 1; 3260 if (t == DST_OP) 3261 mark_reg_unknown(env, regs, regno); 3262 } 3263 return 0; 3264 } 3265 3266 static int check_reg_arg(struct bpf_verifier_env *env, u32 regno, 3267 enum reg_arg_type t) 3268 { 3269 struct bpf_verifier_state *vstate = env->cur_state; 3270 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 3271 3272 return __check_reg_arg(env, state->regs, regno, t); 3273 } 3274 3275 static int insn_stack_access_flags(int frameno, int spi) 3276 { 3277 return INSN_F_STACK_ACCESS | (spi << INSN_F_SPI_SHIFT) | frameno; 3278 } 3279 3280 static int insn_stack_access_spi(int insn_flags) 3281 { 3282 return (insn_flags >> INSN_F_SPI_SHIFT) & INSN_F_SPI_MASK; 3283 } 3284 3285 static int insn_stack_access_frameno(int insn_flags) 3286 { 3287 return insn_flags & INSN_F_FRAMENO_MASK; 3288 } 3289 3290 static void mark_jmp_point(struct bpf_verifier_env *env, int idx) 3291 { 3292 env->insn_aux_data[idx].jmp_point = true; 3293 } 3294 3295 static bool is_jmp_point(struct bpf_verifier_env *env, int insn_idx) 3296 { 3297 return env->insn_aux_data[insn_idx].jmp_point; 3298 } 3299 3300 /* for any branch, call, exit record the history of jmps in the given state */ 3301 static int push_jmp_history(struct bpf_verifier_env *env, struct bpf_verifier_state *cur, 3302 int insn_flags) 3303 { 3304 u32 cnt = cur->jmp_history_cnt; 3305 struct bpf_jmp_history_entry *p; 3306 size_t alloc_size; 3307 3308 /* combine instruction flags if we already recorded this instruction */ 3309 if (env->cur_hist_ent) { 3310 /* atomic instructions push insn_flags twice, for READ and 3311 * WRITE sides, but they should agree on stack slot 3312 */ 3313 WARN_ONCE((env->cur_hist_ent->flags & insn_flags) && 3314 (env->cur_hist_ent->flags & insn_flags) != insn_flags, 3315 "verifier insn history bug: insn_idx %d cur flags %x new flags %x\n", 3316 env->insn_idx, env->cur_hist_ent->flags, insn_flags); 3317 env->cur_hist_ent->flags |= insn_flags; 3318 return 0; 3319 } 3320 3321 cnt++; 3322 alloc_size = kmalloc_size_roundup(size_mul(cnt, sizeof(*p))); 3323 p = krealloc(cur->jmp_history, alloc_size, GFP_USER); 3324 if (!p) 3325 return -ENOMEM; 3326 cur->jmp_history = p; 3327 3328 p = &cur->jmp_history[cnt - 1]; 3329 p->idx = env->insn_idx; 3330 p->prev_idx = env->prev_insn_idx; 3331 p->flags = insn_flags; 3332 cur->jmp_history_cnt = cnt; 3333 env->cur_hist_ent = p; 3334 3335 return 0; 3336 } 3337 3338 static struct bpf_jmp_history_entry *get_jmp_hist_entry(struct bpf_verifier_state *st, 3339 u32 hist_end, int insn_idx) 3340 { 3341 if (hist_end > 0 && st->jmp_history[hist_end - 1].idx == insn_idx) 3342 return &st->jmp_history[hist_end - 1]; 3343 return NULL; 3344 } 3345 3346 /* Backtrack one insn at a time. If idx is not at the top of recorded 3347 * history then previous instruction came from straight line execution. 3348 * Return -ENOENT if we exhausted all instructions within given state. 3349 * 3350 * It's legal to have a bit of a looping with the same starting and ending 3351 * insn index within the same state, e.g.: 3->4->5->3, so just because current 3352 * instruction index is the same as state's first_idx doesn't mean we are 3353 * done. If there is still some jump history left, we should keep going. We 3354 * need to take into account that we might have a jump history between given 3355 * state's parent and itself, due to checkpointing. In this case, we'll have 3356 * history entry recording a jump from last instruction of parent state and 3357 * first instruction of given state. 3358 */ 3359 static int get_prev_insn_idx(struct bpf_verifier_state *st, int i, 3360 u32 *history) 3361 { 3362 u32 cnt = *history; 3363 3364 if (i == st->first_insn_idx) { 3365 if (cnt == 0) 3366 return -ENOENT; 3367 if (cnt == 1 && st->jmp_history[0].idx == i) 3368 return -ENOENT; 3369 } 3370 3371 if (cnt && st->jmp_history[cnt - 1].idx == i) { 3372 i = st->jmp_history[cnt - 1].prev_idx; 3373 (*history)--; 3374 } else { 3375 i--; 3376 } 3377 return i; 3378 } 3379 3380 static const char *disasm_kfunc_name(void *data, const struct bpf_insn *insn) 3381 { 3382 const struct btf_type *func; 3383 struct btf *desc_btf; 3384 3385 if (insn->src_reg != BPF_PSEUDO_KFUNC_CALL) 3386 return NULL; 3387 3388 desc_btf = find_kfunc_desc_btf(data, insn->off); 3389 if (IS_ERR(desc_btf)) 3390 return "<error>"; 3391 3392 func = btf_type_by_id(desc_btf, insn->imm); 3393 return btf_name_by_offset(desc_btf, func->name_off); 3394 } 3395 3396 static inline void bt_init(struct backtrack_state *bt, u32 frame) 3397 { 3398 bt->frame = frame; 3399 } 3400 3401 static inline void bt_reset(struct backtrack_state *bt) 3402 { 3403 struct bpf_verifier_env *env = bt->env; 3404 3405 memset(bt, 0, sizeof(*bt)); 3406 bt->env = env; 3407 } 3408 3409 static inline u32 bt_empty(struct backtrack_state *bt) 3410 { 3411 u64 mask = 0; 3412 int i; 3413 3414 for (i = 0; i <= bt->frame; i++) 3415 mask |= bt->reg_masks[i] | bt->stack_masks[i]; 3416 3417 return mask == 0; 3418 } 3419 3420 static inline int bt_subprog_enter(struct backtrack_state *bt) 3421 { 3422 if (bt->frame == MAX_CALL_FRAMES - 1) { 3423 verbose(bt->env, "BUG subprog enter from frame %d\n", bt->frame); 3424 WARN_ONCE(1, "verifier backtracking bug"); 3425 return -EFAULT; 3426 } 3427 bt->frame++; 3428 return 0; 3429 } 3430 3431 static inline int bt_subprog_exit(struct backtrack_state *bt) 3432 { 3433 if (bt->frame == 0) { 3434 verbose(bt->env, "BUG subprog exit from frame 0\n"); 3435 WARN_ONCE(1, "verifier backtracking bug"); 3436 return -EFAULT; 3437 } 3438 bt->frame--; 3439 return 0; 3440 } 3441 3442 static inline void bt_set_frame_reg(struct backtrack_state *bt, u32 frame, u32 reg) 3443 { 3444 bt->reg_masks[frame] |= 1 << reg; 3445 } 3446 3447 static inline void bt_clear_frame_reg(struct backtrack_state *bt, u32 frame, u32 reg) 3448 { 3449 bt->reg_masks[frame] &= ~(1 << reg); 3450 } 3451 3452 static inline void bt_set_reg(struct backtrack_state *bt, u32 reg) 3453 { 3454 bt_set_frame_reg(bt, bt->frame, reg); 3455 } 3456 3457 static inline void bt_clear_reg(struct backtrack_state *bt, u32 reg) 3458 { 3459 bt_clear_frame_reg(bt, bt->frame, reg); 3460 } 3461 3462 static inline void bt_set_frame_slot(struct backtrack_state *bt, u32 frame, u32 slot) 3463 { 3464 bt->stack_masks[frame] |= 1ull << slot; 3465 } 3466 3467 static inline void bt_clear_frame_slot(struct backtrack_state *bt, u32 frame, u32 slot) 3468 { 3469 bt->stack_masks[frame] &= ~(1ull << slot); 3470 } 3471 3472 static inline u32 bt_frame_reg_mask(struct backtrack_state *bt, u32 frame) 3473 { 3474 return bt->reg_masks[frame]; 3475 } 3476 3477 static inline u32 bt_reg_mask(struct backtrack_state *bt) 3478 { 3479 return bt->reg_masks[bt->frame]; 3480 } 3481 3482 static inline u64 bt_frame_stack_mask(struct backtrack_state *bt, u32 frame) 3483 { 3484 return bt->stack_masks[frame]; 3485 } 3486 3487 static inline u64 bt_stack_mask(struct backtrack_state *bt) 3488 { 3489 return bt->stack_masks[bt->frame]; 3490 } 3491 3492 static inline bool bt_is_reg_set(struct backtrack_state *bt, u32 reg) 3493 { 3494 return bt->reg_masks[bt->frame] & (1 << reg); 3495 } 3496 3497 static inline bool bt_is_frame_slot_set(struct backtrack_state *bt, u32 frame, u32 slot) 3498 { 3499 return bt->stack_masks[frame] & (1ull << slot); 3500 } 3501 3502 /* format registers bitmask, e.g., "r0,r2,r4" for 0x15 mask */ 3503 static void fmt_reg_mask(char *buf, ssize_t buf_sz, u32 reg_mask) 3504 { 3505 DECLARE_BITMAP(mask, 64); 3506 bool first = true; 3507 int i, n; 3508 3509 buf[0] = '\0'; 3510 3511 bitmap_from_u64(mask, reg_mask); 3512 for_each_set_bit(i, mask, 32) { 3513 n = snprintf(buf, buf_sz, "%sr%d", first ? "" : ",", i); 3514 first = false; 3515 buf += n; 3516 buf_sz -= n; 3517 if (buf_sz < 0) 3518 break; 3519 } 3520 } 3521 /* format stack slots bitmask, e.g., "-8,-24,-40" for 0x15 mask */ 3522 static void fmt_stack_mask(char *buf, ssize_t buf_sz, u64 stack_mask) 3523 { 3524 DECLARE_BITMAP(mask, 64); 3525 bool first = true; 3526 int i, n; 3527 3528 buf[0] = '\0'; 3529 3530 bitmap_from_u64(mask, stack_mask); 3531 for_each_set_bit(i, mask, 64) { 3532 n = snprintf(buf, buf_sz, "%s%d", first ? "" : ",", -(i + 1) * 8); 3533 first = false; 3534 buf += n; 3535 buf_sz -= n; 3536 if (buf_sz < 0) 3537 break; 3538 } 3539 } 3540 3541 static bool calls_callback(struct bpf_verifier_env *env, int insn_idx); 3542 3543 /* For given verifier state backtrack_insn() is called from the last insn to 3544 * the first insn. Its purpose is to compute a bitmask of registers and 3545 * stack slots that needs precision in the parent verifier state. 3546 * 3547 * @idx is an index of the instruction we are currently processing; 3548 * @subseq_idx is an index of the subsequent instruction that: 3549 * - *would be* executed next, if jump history is viewed in forward order; 3550 * - *was* processed previously during backtracking. 3551 */ 3552 static int backtrack_insn(struct bpf_verifier_env *env, int idx, int subseq_idx, 3553 struct bpf_jmp_history_entry *hist, struct backtrack_state *bt) 3554 { 3555 const struct bpf_insn_cbs cbs = { 3556 .cb_call = disasm_kfunc_name, 3557 .cb_print = verbose, 3558 .private_data = env, 3559 }; 3560 struct bpf_insn *insn = env->prog->insnsi + idx; 3561 u8 class = BPF_CLASS(insn->code); 3562 u8 opcode = BPF_OP(insn->code); 3563 u8 mode = BPF_MODE(insn->code); 3564 u32 dreg = insn->dst_reg; 3565 u32 sreg = insn->src_reg; 3566 u32 spi, i, fr; 3567 3568 if (insn->code == 0) 3569 return 0; 3570 if (env->log.level & BPF_LOG_LEVEL2) { 3571 fmt_reg_mask(env->tmp_str_buf, TMP_STR_BUF_LEN, bt_reg_mask(bt)); 3572 verbose(env, "mark_precise: frame%d: regs=%s ", 3573 bt->frame, env->tmp_str_buf); 3574 fmt_stack_mask(env->tmp_str_buf, TMP_STR_BUF_LEN, bt_stack_mask(bt)); 3575 verbose(env, "stack=%s before ", env->tmp_str_buf); 3576 verbose(env, "%d: ", idx); 3577 print_bpf_insn(&cbs, insn, env->allow_ptr_leaks); 3578 } 3579 3580 if (class == BPF_ALU || class == BPF_ALU64) { 3581 if (!bt_is_reg_set(bt, dreg)) 3582 return 0; 3583 if (opcode == BPF_END || opcode == BPF_NEG) { 3584 /* sreg is reserved and unused 3585 * dreg still need precision before this insn 3586 */ 3587 return 0; 3588 } else if (opcode == BPF_MOV) { 3589 if (BPF_SRC(insn->code) == BPF_X) { 3590 /* dreg = sreg or dreg = (s8, s16, s32)sreg 3591 * dreg needs precision after this insn 3592 * sreg needs precision before this insn 3593 */ 3594 bt_clear_reg(bt, dreg); 3595 bt_set_reg(bt, sreg); 3596 } else { 3597 /* dreg = K 3598 * dreg needs precision after this insn. 3599 * Corresponding register is already marked 3600 * as precise=true in this verifier state. 3601 * No further markings in parent are necessary 3602 */ 3603 bt_clear_reg(bt, dreg); 3604 } 3605 } else { 3606 if (BPF_SRC(insn->code) == BPF_X) { 3607 /* dreg += sreg 3608 * both dreg and sreg need precision 3609 * before this insn 3610 */ 3611 bt_set_reg(bt, sreg); 3612 } /* else dreg += K 3613 * dreg still needs precision before this insn 3614 */ 3615 } 3616 } else if (class == BPF_LDX) { 3617 if (!bt_is_reg_set(bt, dreg)) 3618 return 0; 3619 bt_clear_reg(bt, dreg); 3620 3621 /* scalars can only be spilled into stack w/o losing precision. 3622 * Load from any other memory can be zero extended. 3623 * The desire to keep that precision is already indicated 3624 * by 'precise' mark in corresponding register of this state. 3625 * No further tracking necessary. 3626 */ 3627 if (!hist || !(hist->flags & INSN_F_STACK_ACCESS)) 3628 return 0; 3629 /* dreg = *(u64 *)[fp - off] was a fill from the stack. 3630 * that [fp - off] slot contains scalar that needs to be 3631 * tracked with precision 3632 */ 3633 spi = insn_stack_access_spi(hist->flags); 3634 fr = insn_stack_access_frameno(hist->flags); 3635 bt_set_frame_slot(bt, fr, spi); 3636 } else if (class == BPF_STX || class == BPF_ST) { 3637 if (bt_is_reg_set(bt, dreg)) 3638 /* stx & st shouldn't be using _scalar_ dst_reg 3639 * to access memory. It means backtracking 3640 * encountered a case of pointer subtraction. 3641 */ 3642 return -ENOTSUPP; 3643 /* scalars can only be spilled into stack */ 3644 if (!hist || !(hist->flags & INSN_F_STACK_ACCESS)) 3645 return 0; 3646 spi = insn_stack_access_spi(hist->flags); 3647 fr = insn_stack_access_frameno(hist->flags); 3648 if (!bt_is_frame_slot_set(bt, fr, spi)) 3649 return 0; 3650 bt_clear_frame_slot(bt, fr, spi); 3651 if (class == BPF_STX) 3652 bt_set_reg(bt, sreg); 3653 } else if (class == BPF_JMP || class == BPF_JMP32) { 3654 if (bpf_pseudo_call(insn)) { 3655 int subprog_insn_idx, subprog; 3656 3657 subprog_insn_idx = idx + insn->imm + 1; 3658 subprog = find_subprog(env, subprog_insn_idx); 3659 if (subprog < 0) 3660 return -EFAULT; 3661 3662 if (subprog_is_global(env, subprog)) { 3663 /* check that jump history doesn't have any 3664 * extra instructions from subprog; the next 3665 * instruction after call to global subprog 3666 * should be literally next instruction in 3667 * caller program 3668 */ 3669 WARN_ONCE(idx + 1 != subseq_idx, "verifier backtracking bug"); 3670 /* r1-r5 are invalidated after subprog call, 3671 * so for global func call it shouldn't be set 3672 * anymore 3673 */ 3674 if (bt_reg_mask(bt) & BPF_REGMASK_ARGS) { 3675 verbose(env, "BUG regs %x\n", bt_reg_mask(bt)); 3676 WARN_ONCE(1, "verifier backtracking bug"); 3677 return -EFAULT; 3678 } 3679 /* global subprog always sets R0 */ 3680 bt_clear_reg(bt, BPF_REG_0); 3681 return 0; 3682 } else { 3683 /* static subprog call instruction, which 3684 * means that we are exiting current subprog, 3685 * so only r1-r5 could be still requested as 3686 * precise, r0 and r6-r10 or any stack slot in 3687 * the current frame should be zero by now 3688 */ 3689 if (bt_reg_mask(bt) & ~BPF_REGMASK_ARGS) { 3690 verbose(env, "BUG regs %x\n", bt_reg_mask(bt)); 3691 WARN_ONCE(1, "verifier backtracking bug"); 3692 return -EFAULT; 3693 } 3694 /* we are now tracking register spills correctly, 3695 * so any instance of leftover slots is a bug 3696 */ 3697 if (bt_stack_mask(bt) != 0) { 3698 verbose(env, "BUG stack slots %llx\n", bt_stack_mask(bt)); 3699 WARN_ONCE(1, "verifier backtracking bug (subprog leftover stack slots)"); 3700 return -EFAULT; 3701 } 3702 /* propagate r1-r5 to the caller */ 3703 for (i = BPF_REG_1; i <= BPF_REG_5; i++) { 3704 if (bt_is_reg_set(bt, i)) { 3705 bt_clear_reg(bt, i); 3706 bt_set_frame_reg(bt, bt->frame - 1, i); 3707 } 3708 } 3709 if (bt_subprog_exit(bt)) 3710 return -EFAULT; 3711 return 0; 3712 } 3713 } else if (is_sync_callback_calling_insn(insn) && idx != subseq_idx - 1) { 3714 /* exit from callback subprog to callback-calling helper or 3715 * kfunc call. Use idx/subseq_idx check to discern it from 3716 * straight line code backtracking. 3717 * Unlike the subprog call handling above, we shouldn't 3718 * propagate precision of r1-r5 (if any requested), as they are 3719 * not actually arguments passed directly to callback subprogs 3720 */ 3721 if (bt_reg_mask(bt) & ~BPF_REGMASK_ARGS) { 3722 verbose(env, "BUG regs %x\n", bt_reg_mask(bt)); 3723 WARN_ONCE(1, "verifier backtracking bug"); 3724 return -EFAULT; 3725 } 3726 if (bt_stack_mask(bt) != 0) { 3727 verbose(env, "BUG stack slots %llx\n", bt_stack_mask(bt)); 3728 WARN_ONCE(1, "verifier backtracking bug (callback leftover stack slots)"); 3729 return -EFAULT; 3730 } 3731 /* clear r1-r5 in callback subprog's mask */ 3732 for (i = BPF_REG_1; i <= BPF_REG_5; i++) 3733 bt_clear_reg(bt, i); 3734 if (bt_subprog_exit(bt)) 3735 return -EFAULT; 3736 return 0; 3737 } else if (opcode == BPF_CALL) { 3738 /* kfunc with imm==0 is invalid and fixup_kfunc_call will 3739 * catch this error later. Make backtracking conservative 3740 * with ENOTSUPP. 3741 */ 3742 if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL && insn->imm == 0) 3743 return -ENOTSUPP; 3744 /* regular helper call sets R0 */ 3745 bt_clear_reg(bt, BPF_REG_0); 3746 if (bt_reg_mask(bt) & BPF_REGMASK_ARGS) { 3747 /* if backtracing was looking for registers R1-R5 3748 * they should have been found already. 3749 */ 3750 verbose(env, "BUG regs %x\n", bt_reg_mask(bt)); 3751 WARN_ONCE(1, "verifier backtracking bug"); 3752 return -EFAULT; 3753 } 3754 } else if (opcode == BPF_EXIT) { 3755 bool r0_precise; 3756 3757 /* Backtracking to a nested function call, 'idx' is a part of 3758 * the inner frame 'subseq_idx' is a part of the outer frame. 3759 * In case of a regular function call, instructions giving 3760 * precision to registers R1-R5 should have been found already. 3761 * In case of a callback, it is ok to have R1-R5 marked for 3762 * backtracking, as these registers are set by the function 3763 * invoking callback. 3764 */ 3765 if (subseq_idx >= 0 && calls_callback(env, subseq_idx)) 3766 for (i = BPF_REG_1; i <= BPF_REG_5; i++) 3767 bt_clear_reg(bt, i); 3768 if (bt_reg_mask(bt) & BPF_REGMASK_ARGS) { 3769 verbose(env, "BUG regs %x\n", bt_reg_mask(bt)); 3770 WARN_ONCE(1, "verifier backtracking bug"); 3771 return -EFAULT; 3772 } 3773 3774 /* BPF_EXIT in subprog or callback always returns 3775 * right after the call instruction, so by checking 3776 * whether the instruction at subseq_idx-1 is subprog 3777 * call or not we can distinguish actual exit from 3778 * *subprog* from exit from *callback*. In the former 3779 * case, we need to propagate r0 precision, if 3780 * necessary. In the former we never do that. 3781 */ 3782 r0_precise = subseq_idx - 1 >= 0 && 3783 bpf_pseudo_call(&env->prog->insnsi[subseq_idx - 1]) && 3784 bt_is_reg_set(bt, BPF_REG_0); 3785 3786 bt_clear_reg(bt, BPF_REG_0); 3787 if (bt_subprog_enter(bt)) 3788 return -EFAULT; 3789 3790 if (r0_precise) 3791 bt_set_reg(bt, BPF_REG_0); 3792 /* r6-r9 and stack slots will stay set in caller frame 3793 * bitmasks until we return back from callee(s) 3794 */ 3795 return 0; 3796 } else if (BPF_SRC(insn->code) == BPF_X) { 3797 if (!bt_is_reg_set(bt, dreg) && !bt_is_reg_set(bt, sreg)) 3798 return 0; 3799 /* dreg <cond> sreg 3800 * Both dreg and sreg need precision before 3801 * this insn. If only sreg was marked precise 3802 * before it would be equally necessary to 3803 * propagate it to dreg. 3804 */ 3805 bt_set_reg(bt, dreg); 3806 bt_set_reg(bt, sreg); 3807 /* else dreg <cond> K 3808 * Only dreg still needs precision before 3809 * this insn, so for the K-based conditional 3810 * there is nothing new to be marked. 3811 */ 3812 } 3813 } else if (class == BPF_LD) { 3814 if (!bt_is_reg_set(bt, dreg)) 3815 return 0; 3816 bt_clear_reg(bt, dreg); 3817 /* It's ld_imm64 or ld_abs or ld_ind. 3818 * For ld_imm64 no further tracking of precision 3819 * into parent is necessary 3820 */ 3821 if (mode == BPF_IND || mode == BPF_ABS) 3822 /* to be analyzed */ 3823 return -ENOTSUPP; 3824 } 3825 return 0; 3826 } 3827 3828 /* the scalar precision tracking algorithm: 3829 * . at the start all registers have precise=false. 3830 * . scalar ranges are tracked as normal through alu and jmp insns. 3831 * . once precise value of the scalar register is used in: 3832 * . ptr + scalar alu 3833 * . if (scalar cond K|scalar) 3834 * . helper_call(.., scalar, ...) where ARG_CONST is expected 3835 * backtrack through the verifier states and mark all registers and 3836 * stack slots with spilled constants that these scalar regisers 3837 * should be precise. 3838 * . during state pruning two registers (or spilled stack slots) 3839 * are equivalent if both are not precise. 3840 * 3841 * Note the verifier cannot simply walk register parentage chain, 3842 * since many different registers and stack slots could have been 3843 * used to compute single precise scalar. 3844 * 3845 * The approach of starting with precise=true for all registers and then 3846 * backtrack to mark a register as not precise when the verifier detects 3847 * that program doesn't care about specific value (e.g., when helper 3848 * takes register as ARG_ANYTHING parameter) is not safe. 3849 * 3850 * It's ok to walk single parentage chain of the verifier states. 3851 * It's possible that this backtracking will go all the way till 1st insn. 3852 * All other branches will be explored for needing precision later. 3853 * 3854 * The backtracking needs to deal with cases like: 3855 * 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) 3856 * r9 -= r8 3857 * r5 = r9 3858 * if r5 > 0x79f goto pc+7 3859 * R5_w=inv(id=0,umax_value=1951,var_off=(0x0; 0x7ff)) 3860 * r5 += 1 3861 * ... 3862 * call bpf_perf_event_output#25 3863 * where .arg5_type = ARG_CONST_SIZE_OR_ZERO 3864 * 3865 * and this case: 3866 * r6 = 1 3867 * call foo // uses callee's r6 inside to compute r0 3868 * r0 += r6 3869 * if r0 == 0 goto 3870 * 3871 * to track above reg_mask/stack_mask needs to be independent for each frame. 3872 * 3873 * Also if parent's curframe > frame where backtracking started, 3874 * the verifier need to mark registers in both frames, otherwise callees 3875 * may incorrectly prune callers. This is similar to 3876 * commit 7640ead93924 ("bpf: verifier: make sure callees don't prune with caller differences") 3877 * 3878 * For now backtracking falls back into conservative marking. 3879 */ 3880 static void mark_all_scalars_precise(struct bpf_verifier_env *env, 3881 struct bpf_verifier_state *st) 3882 { 3883 struct bpf_func_state *func; 3884 struct bpf_reg_state *reg; 3885 int i, j; 3886 3887 if (env->log.level & BPF_LOG_LEVEL2) { 3888 verbose(env, "mark_precise: frame%d: falling back to forcing all scalars precise\n", 3889 st->curframe); 3890 } 3891 3892 /* big hammer: mark all scalars precise in this path. 3893 * pop_stack may still get !precise scalars. 3894 * We also skip current state and go straight to first parent state, 3895 * because precision markings in current non-checkpointed state are 3896 * not needed. See why in the comment in __mark_chain_precision below. 3897 */ 3898 for (st = st->parent; st; st = st->parent) { 3899 for (i = 0; i <= st->curframe; i++) { 3900 func = st->frame[i]; 3901 for (j = 0; j < BPF_REG_FP; j++) { 3902 reg = &func->regs[j]; 3903 if (reg->type != SCALAR_VALUE || reg->precise) 3904 continue; 3905 reg->precise = true; 3906 if (env->log.level & BPF_LOG_LEVEL2) { 3907 verbose(env, "force_precise: frame%d: forcing r%d to be precise\n", 3908 i, j); 3909 } 3910 } 3911 for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) { 3912 if (!is_spilled_reg(&func->stack[j])) 3913 continue; 3914 reg = &func->stack[j].spilled_ptr; 3915 if (reg->type != SCALAR_VALUE || reg->precise) 3916 continue; 3917 reg->precise = true; 3918 if (env->log.level & BPF_LOG_LEVEL2) { 3919 verbose(env, "force_precise: frame%d: forcing fp%d to be precise\n", 3920 i, -(j + 1) * 8); 3921 } 3922 } 3923 } 3924 } 3925 } 3926 3927 static void mark_all_scalars_imprecise(struct bpf_verifier_env *env, struct bpf_verifier_state *st) 3928 { 3929 struct bpf_func_state *func; 3930 struct bpf_reg_state *reg; 3931 int i, j; 3932 3933 for (i = 0; i <= st->curframe; i++) { 3934 func = st->frame[i]; 3935 for (j = 0; j < BPF_REG_FP; j++) { 3936 reg = &func->regs[j]; 3937 if (reg->type != SCALAR_VALUE) 3938 continue; 3939 reg->precise = false; 3940 } 3941 for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) { 3942 if (!is_spilled_reg(&func->stack[j])) 3943 continue; 3944 reg = &func->stack[j].spilled_ptr; 3945 if (reg->type != SCALAR_VALUE) 3946 continue; 3947 reg->precise = false; 3948 } 3949 } 3950 } 3951 3952 static bool idset_contains(struct bpf_idset *s, u32 id) 3953 { 3954 u32 i; 3955 3956 for (i = 0; i < s->count; ++i) 3957 if (s->ids[i] == id) 3958 return true; 3959 3960 return false; 3961 } 3962 3963 static int idset_push(struct bpf_idset *s, u32 id) 3964 { 3965 if (WARN_ON_ONCE(s->count >= ARRAY_SIZE(s->ids))) 3966 return -EFAULT; 3967 s->ids[s->count++] = id; 3968 return 0; 3969 } 3970 3971 static void idset_reset(struct bpf_idset *s) 3972 { 3973 s->count = 0; 3974 } 3975 3976 /* Collect a set of IDs for all registers currently marked as precise in env->bt. 3977 * Mark all registers with these IDs as precise. 3978 */ 3979 static int mark_precise_scalar_ids(struct bpf_verifier_env *env, struct bpf_verifier_state *st) 3980 { 3981 struct bpf_idset *precise_ids = &env->idset_scratch; 3982 struct backtrack_state *bt = &env->bt; 3983 struct bpf_func_state *func; 3984 struct bpf_reg_state *reg; 3985 DECLARE_BITMAP(mask, 64); 3986 int i, fr; 3987 3988 idset_reset(precise_ids); 3989 3990 for (fr = bt->frame; fr >= 0; fr--) { 3991 func = st->frame[fr]; 3992 3993 bitmap_from_u64(mask, bt_frame_reg_mask(bt, fr)); 3994 for_each_set_bit(i, mask, 32) { 3995 reg = &func->regs[i]; 3996 if (!reg->id || reg->type != SCALAR_VALUE) 3997 continue; 3998 if (idset_push(precise_ids, reg->id)) 3999 return -EFAULT; 4000 } 4001 4002 bitmap_from_u64(mask, bt_frame_stack_mask(bt, fr)); 4003 for_each_set_bit(i, mask, 64) { 4004 if (i >= func->allocated_stack / BPF_REG_SIZE) 4005 break; 4006 if (!is_spilled_scalar_reg(&func->stack[i])) 4007 continue; 4008 reg = &func->stack[i].spilled_ptr; 4009 if (!reg->id) 4010 continue; 4011 if (idset_push(precise_ids, reg->id)) 4012 return -EFAULT; 4013 } 4014 } 4015 4016 for (fr = 0; fr <= st->curframe; ++fr) { 4017 func = st->frame[fr]; 4018 4019 for (i = BPF_REG_0; i < BPF_REG_10; ++i) { 4020 reg = &func->regs[i]; 4021 if (!reg->id) 4022 continue; 4023 if (!idset_contains(precise_ids, reg->id)) 4024 continue; 4025 bt_set_frame_reg(bt, fr, i); 4026 } 4027 for (i = 0; i < func->allocated_stack / BPF_REG_SIZE; ++i) { 4028 if (!is_spilled_scalar_reg(&func->stack[i])) 4029 continue; 4030 reg = &func->stack[i].spilled_ptr; 4031 if (!reg->id) 4032 continue; 4033 if (!idset_contains(precise_ids, reg->id)) 4034 continue; 4035 bt_set_frame_slot(bt, fr, i); 4036 } 4037 } 4038 4039 return 0; 4040 } 4041 4042 /* 4043 * __mark_chain_precision() backtracks BPF program instruction sequence and 4044 * chain of verifier states making sure that register *regno* (if regno >= 0) 4045 * and/or stack slot *spi* (if spi >= 0) are marked as precisely tracked 4046 * SCALARS, as well as any other registers and slots that contribute to 4047 * a tracked state of given registers/stack slots, depending on specific BPF 4048 * assembly instructions (see backtrack_insns() for exact instruction handling 4049 * logic). This backtracking relies on recorded jmp_history and is able to 4050 * traverse entire chain of parent states. This process ends only when all the 4051 * necessary registers/slots and their transitive dependencies are marked as 4052 * precise. 4053 * 4054 * One important and subtle aspect is that precise marks *do not matter* in 4055 * the currently verified state (current state). It is important to understand 4056 * why this is the case. 4057 * 4058 * First, note that current state is the state that is not yet "checkpointed", 4059 * i.e., it is not yet put into env->explored_states, and it has no children 4060 * states as well. It's ephemeral, and can end up either a) being discarded if 4061 * compatible explored state is found at some point or BPF_EXIT instruction is 4062 * reached or b) checkpointed and put into env->explored_states, branching out 4063 * into one or more children states. 4064 * 4065 * In the former case, precise markings in current state are completely 4066 * ignored by state comparison code (see regsafe() for details). Only 4067 * checkpointed ("old") state precise markings are important, and if old 4068 * state's register/slot is precise, regsafe() assumes current state's 4069 * register/slot as precise and checks value ranges exactly and precisely. If 4070 * states turn out to be compatible, current state's necessary precise 4071 * markings and any required parent states' precise markings are enforced 4072 * after the fact with propagate_precision() logic, after the fact. But it's 4073 * important to realize that in this case, even after marking current state 4074 * registers/slots as precise, we immediately discard current state. So what 4075 * actually matters is any of the precise markings propagated into current 4076 * state's parent states, which are always checkpointed (due to b) case above). 4077 * As such, for scenario a) it doesn't matter if current state has precise 4078 * markings set or not. 4079 * 4080 * Now, for the scenario b), checkpointing and forking into child(ren) 4081 * state(s). Note that before current state gets to checkpointing step, any 4082 * processed instruction always assumes precise SCALAR register/slot 4083 * knowledge: if precise value or range is useful to prune jump branch, BPF 4084 * verifier takes this opportunity enthusiastically. Similarly, when 4085 * register's value is used to calculate offset or memory address, exact 4086 * knowledge of SCALAR range is assumed, checked, and enforced. So, similar to 4087 * what we mentioned above about state comparison ignoring precise markings 4088 * during state comparison, BPF verifier ignores and also assumes precise 4089 * markings *at will* during instruction verification process. But as verifier 4090 * assumes precision, it also propagates any precision dependencies across 4091 * parent states, which are not yet finalized, so can be further restricted 4092 * based on new knowledge gained from restrictions enforced by their children 4093 * states. This is so that once those parent states are finalized, i.e., when 4094 * they have no more active children state, state comparison logic in 4095 * is_state_visited() would enforce strict and precise SCALAR ranges, if 4096 * required for correctness. 4097 * 4098 * To build a bit more intuition, note also that once a state is checkpointed, 4099 * the path we took to get to that state is not important. This is crucial 4100 * property for state pruning. When state is checkpointed and finalized at 4101 * some instruction index, it can be correctly and safely used to "short 4102 * circuit" any *compatible* state that reaches exactly the same instruction 4103 * index. I.e., if we jumped to that instruction from a completely different 4104 * code path than original finalized state was derived from, it doesn't 4105 * matter, current state can be discarded because from that instruction 4106 * forward having a compatible state will ensure we will safely reach the 4107 * exit. States describe preconditions for further exploration, but completely 4108 * forget the history of how we got here. 4109 * 4110 * This also means that even if we needed precise SCALAR range to get to 4111 * finalized state, but from that point forward *that same* SCALAR register is 4112 * never used in a precise context (i.e., it's precise value is not needed for 4113 * correctness), it's correct and safe to mark such register as "imprecise" 4114 * (i.e., precise marking set to false). This is what we rely on when we do 4115 * not set precise marking in current state. If no child state requires 4116 * precision for any given SCALAR register, it's safe to dictate that it can 4117 * be imprecise. If any child state does require this register to be precise, 4118 * we'll mark it precise later retroactively during precise markings 4119 * propagation from child state to parent states. 4120 * 4121 * Skipping precise marking setting in current state is a mild version of 4122 * relying on the above observation. But we can utilize this property even 4123 * more aggressively by proactively forgetting any precise marking in the 4124 * current state (which we inherited from the parent state), right before we 4125 * checkpoint it and branch off into new child state. This is done by 4126 * mark_all_scalars_imprecise() to hopefully get more permissive and generic 4127 * finalized states which help in short circuiting more future states. 4128 */ 4129 static int __mark_chain_precision(struct bpf_verifier_env *env, int regno) 4130 { 4131 struct backtrack_state *bt = &env->bt; 4132 struct bpf_verifier_state *st = env->cur_state; 4133 int first_idx = st->first_insn_idx; 4134 int last_idx = env->insn_idx; 4135 int subseq_idx = -1; 4136 struct bpf_func_state *func; 4137 struct bpf_reg_state *reg; 4138 bool skip_first = true; 4139 int i, fr, err; 4140 4141 if (!env->bpf_capable) 4142 return 0; 4143 4144 /* set frame number from which we are starting to backtrack */ 4145 bt_init(bt, env->cur_state->curframe); 4146 4147 /* Do sanity checks against current state of register and/or stack 4148 * slot, but don't set precise flag in current state, as precision 4149 * tracking in the current state is unnecessary. 4150 */ 4151 func = st->frame[bt->frame]; 4152 if (regno >= 0) { 4153 reg = &func->regs[regno]; 4154 if (reg->type != SCALAR_VALUE) { 4155 WARN_ONCE(1, "backtracing misuse"); 4156 return -EFAULT; 4157 } 4158 bt_set_reg(bt, regno); 4159 } 4160 4161 if (bt_empty(bt)) 4162 return 0; 4163 4164 for (;;) { 4165 DECLARE_BITMAP(mask, 64); 4166 u32 history = st->jmp_history_cnt; 4167 struct bpf_jmp_history_entry *hist; 4168 4169 if (env->log.level & BPF_LOG_LEVEL2) { 4170 verbose(env, "mark_precise: frame%d: last_idx %d first_idx %d subseq_idx %d \n", 4171 bt->frame, last_idx, first_idx, subseq_idx); 4172 } 4173 4174 /* If some register with scalar ID is marked as precise, 4175 * make sure that all registers sharing this ID are also precise. 4176 * This is needed to estimate effect of find_equal_scalars(). 4177 * Do this at the last instruction of each state, 4178 * bpf_reg_state::id fields are valid for these instructions. 4179 * 4180 * Allows to track precision in situation like below: 4181 * 4182 * r2 = unknown value 4183 * ... 4184 * --- state #0 --- 4185 * ... 4186 * r1 = r2 // r1 and r2 now share the same ID 4187 * ... 4188 * --- state #1 {r1.id = A, r2.id = A} --- 4189 * ... 4190 * if (r2 > 10) goto exit; // find_equal_scalars() assigns range to r1 4191 * ... 4192 * --- state #2 {r1.id = A, r2.id = A} --- 4193 * r3 = r10 4194 * r3 += r1 // need to mark both r1 and r2 4195 */ 4196 if (mark_precise_scalar_ids(env, st)) 4197 return -EFAULT; 4198 4199 if (last_idx < 0) { 4200 /* we are at the entry into subprog, which 4201 * is expected for global funcs, but only if 4202 * requested precise registers are R1-R5 4203 * (which are global func's input arguments) 4204 */ 4205 if (st->curframe == 0 && 4206 st->frame[0]->subprogno > 0 && 4207 st->frame[0]->callsite == BPF_MAIN_FUNC && 4208 bt_stack_mask(bt) == 0 && 4209 (bt_reg_mask(bt) & ~BPF_REGMASK_ARGS) == 0) { 4210 bitmap_from_u64(mask, bt_reg_mask(bt)); 4211 for_each_set_bit(i, mask, 32) { 4212 reg = &st->frame[0]->regs[i]; 4213 bt_clear_reg(bt, i); 4214 if (reg->type == SCALAR_VALUE) 4215 reg->precise = true; 4216 } 4217 return 0; 4218 } 4219 4220 verbose(env, "BUG backtracking func entry subprog %d reg_mask %x stack_mask %llx\n", 4221 st->frame[0]->subprogno, bt_reg_mask(bt), bt_stack_mask(bt)); 4222 WARN_ONCE(1, "verifier backtracking bug"); 4223 return -EFAULT; 4224 } 4225 4226 for (i = last_idx;;) { 4227 if (skip_first) { 4228 err = 0; 4229 skip_first = false; 4230 } else { 4231 hist = get_jmp_hist_entry(st, history, i); 4232 err = backtrack_insn(env, i, subseq_idx, hist, bt); 4233 } 4234 if (err == -ENOTSUPP) { 4235 mark_all_scalars_precise(env, env->cur_state); 4236 bt_reset(bt); 4237 return 0; 4238 } else if (err) { 4239 return err; 4240 } 4241 if (bt_empty(bt)) 4242 /* Found assignment(s) into tracked register in this state. 4243 * Since this state is already marked, just return. 4244 * Nothing to be tracked further in the parent state. 4245 */ 4246 return 0; 4247 subseq_idx = i; 4248 i = get_prev_insn_idx(st, i, &history); 4249 if (i == -ENOENT) 4250 break; 4251 if (i >= env->prog->len) { 4252 /* This can happen if backtracking reached insn 0 4253 * and there are still reg_mask or stack_mask 4254 * to backtrack. 4255 * It means the backtracking missed the spot where 4256 * particular register was initialized with a constant. 4257 */ 4258 verbose(env, "BUG backtracking idx %d\n", i); 4259 WARN_ONCE(1, "verifier backtracking bug"); 4260 return -EFAULT; 4261 } 4262 } 4263 st = st->parent; 4264 if (!st) 4265 break; 4266 4267 for (fr = bt->frame; fr >= 0; fr--) { 4268 func = st->frame[fr]; 4269 bitmap_from_u64(mask, bt_frame_reg_mask(bt, fr)); 4270 for_each_set_bit(i, mask, 32) { 4271 reg = &func->regs[i]; 4272 if (reg->type != SCALAR_VALUE) { 4273 bt_clear_frame_reg(bt, fr, i); 4274 continue; 4275 } 4276 if (reg->precise) 4277 bt_clear_frame_reg(bt, fr, i); 4278 else 4279 reg->precise = true; 4280 } 4281 4282 bitmap_from_u64(mask, bt_frame_stack_mask(bt, fr)); 4283 for_each_set_bit(i, mask, 64) { 4284 if (i >= func->allocated_stack / BPF_REG_SIZE) { 4285 verbose(env, "BUG backtracking (stack slot %d, total slots %d)\n", 4286 i, func->allocated_stack / BPF_REG_SIZE); 4287 WARN_ONCE(1, "verifier backtracking bug (stack slot out of bounds)"); 4288 return -EFAULT; 4289 } 4290 4291 if (!is_spilled_scalar_reg(&func->stack[i])) { 4292 bt_clear_frame_slot(bt, fr, i); 4293 continue; 4294 } 4295 reg = &func->stack[i].spilled_ptr; 4296 if (reg->precise) 4297 bt_clear_frame_slot(bt, fr, i); 4298 else 4299 reg->precise = true; 4300 } 4301 if (env->log.level & BPF_LOG_LEVEL2) { 4302 fmt_reg_mask(env->tmp_str_buf, TMP_STR_BUF_LEN, 4303 bt_frame_reg_mask(bt, fr)); 4304 verbose(env, "mark_precise: frame%d: parent state regs=%s ", 4305 fr, env->tmp_str_buf); 4306 fmt_stack_mask(env->tmp_str_buf, TMP_STR_BUF_LEN, 4307 bt_frame_stack_mask(bt, fr)); 4308 verbose(env, "stack=%s: ", env->tmp_str_buf); 4309 print_verifier_state(env, func, true); 4310 } 4311 } 4312 4313 if (bt_empty(bt)) 4314 return 0; 4315 4316 subseq_idx = first_idx; 4317 last_idx = st->last_insn_idx; 4318 first_idx = st->first_insn_idx; 4319 } 4320 4321 /* if we still have requested precise regs or slots, we missed 4322 * something (e.g., stack access through non-r10 register), so 4323 * fallback to marking all precise 4324 */ 4325 if (!bt_empty(bt)) { 4326 mark_all_scalars_precise(env, env->cur_state); 4327 bt_reset(bt); 4328 } 4329 4330 return 0; 4331 } 4332 4333 int mark_chain_precision(struct bpf_verifier_env *env, int regno) 4334 { 4335 return __mark_chain_precision(env, regno); 4336 } 4337 4338 /* mark_chain_precision_batch() assumes that env->bt is set in the caller to 4339 * desired reg and stack masks across all relevant frames 4340 */ 4341 static int mark_chain_precision_batch(struct bpf_verifier_env *env) 4342 { 4343 return __mark_chain_precision(env, -1); 4344 } 4345 4346 static bool is_spillable_regtype(enum bpf_reg_type type) 4347 { 4348 switch (base_type(type)) { 4349 case PTR_TO_MAP_VALUE: 4350 case PTR_TO_STACK: 4351 case PTR_TO_CTX: 4352 case PTR_TO_PACKET: 4353 case PTR_TO_PACKET_META: 4354 case PTR_TO_PACKET_END: 4355 case PTR_TO_FLOW_KEYS: 4356 case CONST_PTR_TO_MAP: 4357 case PTR_TO_SOCKET: 4358 case PTR_TO_SOCK_COMMON: 4359 case PTR_TO_TCP_SOCK: 4360 case PTR_TO_XDP_SOCK: 4361 case PTR_TO_BTF_ID: 4362 case PTR_TO_BUF: 4363 case PTR_TO_MEM: 4364 case PTR_TO_FUNC: 4365 case PTR_TO_MAP_KEY: 4366 return true; 4367 default: 4368 return false; 4369 } 4370 } 4371 4372 /* Does this register contain a constant zero? */ 4373 static bool register_is_null(struct bpf_reg_state *reg) 4374 { 4375 return reg->type == SCALAR_VALUE && tnum_equals_const(reg->var_off, 0); 4376 } 4377 4378 /* check if register is a constant scalar value */ 4379 static bool is_reg_const(struct bpf_reg_state *reg, bool subreg32) 4380 { 4381 return reg->type == SCALAR_VALUE && 4382 tnum_is_const(subreg32 ? tnum_subreg(reg->var_off) : reg->var_off); 4383 } 4384 4385 /* assuming is_reg_const() is true, return constant value of a register */ 4386 static u64 reg_const_value(struct bpf_reg_state *reg, bool subreg32) 4387 { 4388 return subreg32 ? tnum_subreg(reg->var_off).value : reg->var_off.value; 4389 } 4390 4391 static bool __is_scalar_unbounded(struct bpf_reg_state *reg) 4392 { 4393 return tnum_is_unknown(reg->var_off) && 4394 reg->smin_value == S64_MIN && reg->smax_value == S64_MAX && 4395 reg->umin_value == 0 && reg->umax_value == U64_MAX && 4396 reg->s32_min_value == S32_MIN && reg->s32_max_value == S32_MAX && 4397 reg->u32_min_value == 0 && reg->u32_max_value == U32_MAX; 4398 } 4399 4400 static bool register_is_bounded(struct bpf_reg_state *reg) 4401 { 4402 return reg->type == SCALAR_VALUE && !__is_scalar_unbounded(reg); 4403 } 4404 4405 static bool __is_pointer_value(bool allow_ptr_leaks, 4406 const struct bpf_reg_state *reg) 4407 { 4408 if (allow_ptr_leaks) 4409 return false; 4410 4411 return reg->type != SCALAR_VALUE; 4412 } 4413 4414 /* Copy src state preserving dst->parent and dst->live fields */ 4415 static void copy_register_state(struct bpf_reg_state *dst, const struct bpf_reg_state *src) 4416 { 4417 struct bpf_reg_state *parent = dst->parent; 4418 enum bpf_reg_liveness live = dst->live; 4419 4420 *dst = *src; 4421 dst->parent = parent; 4422 dst->live = live; 4423 } 4424 4425 static void save_register_state(struct bpf_verifier_env *env, 4426 struct bpf_func_state *state, 4427 int spi, struct bpf_reg_state *reg, 4428 int size) 4429 { 4430 int i; 4431 4432 copy_register_state(&state->stack[spi].spilled_ptr, reg); 4433 if (size == BPF_REG_SIZE) 4434 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN; 4435 4436 for (i = BPF_REG_SIZE; i > BPF_REG_SIZE - size; i--) 4437 state->stack[spi].slot_type[i - 1] = STACK_SPILL; 4438 4439 /* size < 8 bytes spill */ 4440 for (; i; i--) 4441 mark_stack_slot_misc(env, &state->stack[spi].slot_type[i - 1]); 4442 } 4443 4444 static bool is_bpf_st_mem(struct bpf_insn *insn) 4445 { 4446 return BPF_CLASS(insn->code) == BPF_ST && BPF_MODE(insn->code) == BPF_MEM; 4447 } 4448 4449 /* check_stack_{read,write}_fixed_off functions track spill/fill of registers, 4450 * stack boundary and alignment are checked in check_mem_access() 4451 */ 4452 static int check_stack_write_fixed_off(struct bpf_verifier_env *env, 4453 /* stack frame we're writing to */ 4454 struct bpf_func_state *state, 4455 int off, int size, int value_regno, 4456 int insn_idx) 4457 { 4458 struct bpf_func_state *cur; /* state of the current function */ 4459 int i, slot = -off - 1, spi = slot / BPF_REG_SIZE, err; 4460 struct bpf_insn *insn = &env->prog->insnsi[insn_idx]; 4461 struct bpf_reg_state *reg = NULL; 4462 int insn_flags = insn_stack_access_flags(state->frameno, spi); 4463 4464 /* caller checked that off % size == 0 and -MAX_BPF_STACK <= off < 0, 4465 * so it's aligned access and [off, off + size) are within stack limits 4466 */ 4467 if (!env->allow_ptr_leaks && 4468 is_spilled_reg(&state->stack[spi]) && 4469 size != BPF_REG_SIZE) { 4470 verbose(env, "attempt to corrupt spilled pointer on stack\n"); 4471 return -EACCES; 4472 } 4473 4474 cur = env->cur_state->frame[env->cur_state->curframe]; 4475 if (value_regno >= 0) 4476 reg = &cur->regs[value_regno]; 4477 if (!env->bypass_spec_v4) { 4478 bool sanitize = reg && is_spillable_regtype(reg->type); 4479 4480 for (i = 0; i < size; i++) { 4481 u8 type = state->stack[spi].slot_type[i]; 4482 4483 if (type != STACK_MISC && type != STACK_ZERO) { 4484 sanitize = true; 4485 break; 4486 } 4487 } 4488 4489 if (sanitize) 4490 env->insn_aux_data[insn_idx].sanitize_stack_spill = true; 4491 } 4492 4493 err = destroy_if_dynptr_stack_slot(env, state, spi); 4494 if (err) 4495 return err; 4496 4497 mark_stack_slot_scratched(env, spi); 4498 if (reg && !(off % BPF_REG_SIZE) && register_is_bounded(reg) && env->bpf_capable) { 4499 save_register_state(env, state, spi, reg, size); 4500 /* Break the relation on a narrowing spill. */ 4501 if (fls64(reg->umax_value) > BITS_PER_BYTE * size) 4502 state->stack[spi].spilled_ptr.id = 0; 4503 } else if (!reg && !(off % BPF_REG_SIZE) && is_bpf_st_mem(insn) && 4504 insn->imm != 0 && env->bpf_capable) { 4505 struct bpf_reg_state fake_reg = {}; 4506 4507 __mark_reg_known(&fake_reg, insn->imm); 4508 fake_reg.type = SCALAR_VALUE; 4509 save_register_state(env, state, spi, &fake_reg, size); 4510 } else if (reg && is_spillable_regtype(reg->type)) { 4511 /* register containing pointer is being spilled into stack */ 4512 if (size != BPF_REG_SIZE) { 4513 verbose_linfo(env, insn_idx, "; "); 4514 verbose(env, "invalid size of register spill\n"); 4515 return -EACCES; 4516 } 4517 if (state != cur && reg->type == PTR_TO_STACK) { 4518 verbose(env, "cannot spill pointers to stack into stack frame of the caller\n"); 4519 return -EINVAL; 4520 } 4521 save_register_state(env, state, spi, reg, size); 4522 } else { 4523 u8 type = STACK_MISC; 4524 4525 /* regular write of data into stack destroys any spilled ptr */ 4526 state->stack[spi].spilled_ptr.type = NOT_INIT; 4527 /* Mark slots as STACK_MISC if they belonged to spilled ptr/dynptr/iter. */ 4528 if (is_stack_slot_special(&state->stack[spi])) 4529 for (i = 0; i < BPF_REG_SIZE; i++) 4530 scrub_spilled_slot(&state->stack[spi].slot_type[i]); 4531 4532 /* only mark the slot as written if all 8 bytes were written 4533 * otherwise read propagation may incorrectly stop too soon 4534 * when stack slots are partially written. 4535 * This heuristic means that read propagation will be 4536 * conservative, since it will add reg_live_read marks 4537 * to stack slots all the way to first state when programs 4538 * writes+reads less than 8 bytes 4539 */ 4540 if (size == BPF_REG_SIZE) 4541 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN; 4542 4543 /* when we zero initialize stack slots mark them as such */ 4544 if ((reg && register_is_null(reg)) || 4545 (!reg && is_bpf_st_mem(insn) && insn->imm == 0)) { 4546 /* STACK_ZERO case happened because register spill 4547 * wasn't properly aligned at the stack slot boundary, 4548 * so it's not a register spill anymore; force 4549 * originating register to be precise to make 4550 * STACK_ZERO correct for subsequent states 4551 */ 4552 err = mark_chain_precision(env, value_regno); 4553 if (err) 4554 return err; 4555 type = STACK_ZERO; 4556 } 4557 4558 /* Mark slots affected by this stack write. */ 4559 for (i = 0; i < size; i++) 4560 state->stack[spi].slot_type[(slot - i) % BPF_REG_SIZE] = type; 4561 insn_flags = 0; /* not a register spill */ 4562 } 4563 4564 if (insn_flags) 4565 return push_jmp_history(env, env->cur_state, insn_flags); 4566 return 0; 4567 } 4568 4569 /* Write the stack: 'stack[ptr_regno + off] = value_regno'. 'ptr_regno' is 4570 * known to contain a variable offset. 4571 * This function checks whether the write is permitted and conservatively 4572 * tracks the effects of the write, considering that each stack slot in the 4573 * dynamic range is potentially written to. 4574 * 4575 * 'off' includes 'regno->off'. 4576 * 'value_regno' can be -1, meaning that an unknown value is being written to 4577 * the stack. 4578 * 4579 * Spilled pointers in range are not marked as written because we don't know 4580 * what's going to be actually written. This means that read propagation for 4581 * future reads cannot be terminated by this write. 4582 * 4583 * For privileged programs, uninitialized stack slots are considered 4584 * initialized by this write (even though we don't know exactly what offsets 4585 * are going to be written to). The idea is that we don't want the verifier to 4586 * reject future reads that access slots written to through variable offsets. 4587 */ 4588 static int check_stack_write_var_off(struct bpf_verifier_env *env, 4589 /* func where register points to */ 4590 struct bpf_func_state *state, 4591 int ptr_regno, int off, int size, 4592 int value_regno, int insn_idx) 4593 { 4594 struct bpf_func_state *cur; /* state of the current function */ 4595 int min_off, max_off; 4596 int i, err; 4597 struct bpf_reg_state *ptr_reg = NULL, *value_reg = NULL; 4598 struct bpf_insn *insn = &env->prog->insnsi[insn_idx]; 4599 bool writing_zero = false; 4600 /* set if the fact that we're writing a zero is used to let any 4601 * stack slots remain STACK_ZERO 4602 */ 4603 bool zero_used = false; 4604 4605 cur = env->cur_state->frame[env->cur_state->curframe]; 4606 ptr_reg = &cur->regs[ptr_regno]; 4607 min_off = ptr_reg->smin_value + off; 4608 max_off = ptr_reg->smax_value + off + size; 4609 if (value_regno >= 0) 4610 value_reg = &cur->regs[value_regno]; 4611 if ((value_reg && register_is_null(value_reg)) || 4612 (!value_reg && is_bpf_st_mem(insn) && insn->imm == 0)) 4613 writing_zero = true; 4614 4615 for (i = min_off; i < max_off; i++) { 4616 int spi; 4617 4618 spi = __get_spi(i); 4619 err = destroy_if_dynptr_stack_slot(env, state, spi); 4620 if (err) 4621 return err; 4622 } 4623 4624 /* Variable offset writes destroy any spilled pointers in range. */ 4625 for (i = min_off; i < max_off; i++) { 4626 u8 new_type, *stype; 4627 int slot, spi; 4628 4629 slot = -i - 1; 4630 spi = slot / BPF_REG_SIZE; 4631 stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE]; 4632 mark_stack_slot_scratched(env, spi); 4633 4634 if (!env->allow_ptr_leaks && *stype != STACK_MISC && *stype != STACK_ZERO) { 4635 /* Reject the write if range we may write to has not 4636 * been initialized beforehand. If we didn't reject 4637 * here, the ptr status would be erased below (even 4638 * though not all slots are actually overwritten), 4639 * possibly opening the door to leaks. 4640 * 4641 * We do however catch STACK_INVALID case below, and 4642 * only allow reading possibly uninitialized memory 4643 * later for CAP_PERFMON, as the write may not happen to 4644 * that slot. 4645 */ 4646 verbose(env, "spilled ptr in range of var-offset stack write; insn %d, ptr off: %d", 4647 insn_idx, i); 4648 return -EINVAL; 4649 } 4650 4651 /* Erase all spilled pointers. */ 4652 state->stack[spi].spilled_ptr.type = NOT_INIT; 4653 4654 /* Update the slot type. */ 4655 new_type = STACK_MISC; 4656 if (writing_zero && *stype == STACK_ZERO) { 4657 new_type = STACK_ZERO; 4658 zero_used = true; 4659 } 4660 /* If the slot is STACK_INVALID, we check whether it's OK to 4661 * pretend that it will be initialized by this write. The slot 4662 * might not actually be written to, and so if we mark it as 4663 * initialized future reads might leak uninitialized memory. 4664 * For privileged programs, we will accept such reads to slots 4665 * that may or may not be written because, if we're reject 4666 * them, the error would be too confusing. 4667 */ 4668 if (*stype == STACK_INVALID && !env->allow_uninit_stack) { 4669 verbose(env, "uninit stack in range of var-offset write prohibited for !root; insn %d, off: %d", 4670 insn_idx, i); 4671 return -EINVAL; 4672 } 4673 *stype = new_type; 4674 } 4675 if (zero_used) { 4676 /* backtracking doesn't work for STACK_ZERO yet. */ 4677 err = mark_chain_precision(env, value_regno); 4678 if (err) 4679 return err; 4680 } 4681 return 0; 4682 } 4683 4684 /* When register 'dst_regno' is assigned some values from stack[min_off, 4685 * max_off), we set the register's type according to the types of the 4686 * respective stack slots. If all the stack values are known to be zeros, then 4687 * so is the destination reg. Otherwise, the register is considered to be 4688 * SCALAR. This function does not deal with register filling; the caller must 4689 * ensure that all spilled registers in the stack range have been marked as 4690 * read. 4691 */ 4692 static void mark_reg_stack_read(struct bpf_verifier_env *env, 4693 /* func where src register points to */ 4694 struct bpf_func_state *ptr_state, 4695 int min_off, int max_off, int dst_regno) 4696 { 4697 struct bpf_verifier_state *vstate = env->cur_state; 4698 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 4699 int i, slot, spi; 4700 u8 *stype; 4701 int zeros = 0; 4702 4703 for (i = min_off; i < max_off; i++) { 4704 slot = -i - 1; 4705 spi = slot / BPF_REG_SIZE; 4706 mark_stack_slot_scratched(env, spi); 4707 stype = ptr_state->stack[spi].slot_type; 4708 if (stype[slot % BPF_REG_SIZE] != STACK_ZERO) 4709 break; 4710 zeros++; 4711 } 4712 if (zeros == max_off - min_off) { 4713 /* Any access_size read into register is zero extended, 4714 * so the whole register == const_zero. 4715 */ 4716 __mark_reg_const_zero(env, &state->regs[dst_regno]); 4717 } else { 4718 /* have read misc data from the stack */ 4719 mark_reg_unknown(env, state->regs, dst_regno); 4720 } 4721 state->regs[dst_regno].live |= REG_LIVE_WRITTEN; 4722 } 4723 4724 /* Read the stack at 'off' and put the results into the register indicated by 4725 * 'dst_regno'. It handles reg filling if the addressed stack slot is a 4726 * spilled reg. 4727 * 4728 * 'dst_regno' can be -1, meaning that the read value is not going to a 4729 * register. 4730 * 4731 * The access is assumed to be within the current stack bounds. 4732 */ 4733 static int check_stack_read_fixed_off(struct bpf_verifier_env *env, 4734 /* func where src register points to */ 4735 struct bpf_func_state *reg_state, 4736 int off, int size, int dst_regno) 4737 { 4738 struct bpf_verifier_state *vstate = env->cur_state; 4739 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 4740 int i, slot = -off - 1, spi = slot / BPF_REG_SIZE; 4741 struct bpf_reg_state *reg; 4742 u8 *stype, type; 4743 int insn_flags = insn_stack_access_flags(reg_state->frameno, spi); 4744 4745 stype = reg_state->stack[spi].slot_type; 4746 reg = ®_state->stack[spi].spilled_ptr; 4747 4748 mark_stack_slot_scratched(env, spi); 4749 4750 if (is_spilled_reg(®_state->stack[spi])) { 4751 u8 spill_size = 1; 4752 4753 for (i = BPF_REG_SIZE - 1; i > 0 && stype[i - 1] == STACK_SPILL; i--) 4754 spill_size++; 4755 4756 if (size != BPF_REG_SIZE || spill_size != BPF_REG_SIZE) { 4757 if (reg->type != SCALAR_VALUE) { 4758 verbose_linfo(env, env->insn_idx, "; "); 4759 verbose(env, "invalid size of register fill\n"); 4760 return -EACCES; 4761 } 4762 4763 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64); 4764 if (dst_regno < 0) 4765 return 0; 4766 4767 if (!(off % BPF_REG_SIZE) && size == spill_size) { 4768 /* The earlier check_reg_arg() has decided the 4769 * subreg_def for this insn. Save it first. 4770 */ 4771 s32 subreg_def = state->regs[dst_regno].subreg_def; 4772 4773 copy_register_state(&state->regs[dst_regno], reg); 4774 state->regs[dst_regno].subreg_def = subreg_def; 4775 } else { 4776 int spill_cnt = 0, zero_cnt = 0; 4777 4778 for (i = 0; i < size; i++) { 4779 type = stype[(slot - i) % BPF_REG_SIZE]; 4780 if (type == STACK_SPILL) { 4781 spill_cnt++; 4782 continue; 4783 } 4784 if (type == STACK_MISC) 4785 continue; 4786 if (type == STACK_ZERO) { 4787 zero_cnt++; 4788 continue; 4789 } 4790 if (type == STACK_INVALID && env->allow_uninit_stack) 4791 continue; 4792 verbose(env, "invalid read from stack off %d+%d size %d\n", 4793 off, i, size); 4794 return -EACCES; 4795 } 4796 4797 if (spill_cnt == size && 4798 tnum_is_const(reg->var_off) && reg->var_off.value == 0) { 4799 __mark_reg_const_zero(env, &state->regs[dst_regno]); 4800 /* this IS register fill, so keep insn_flags */ 4801 } else if (zero_cnt == size) { 4802 /* similarly to mark_reg_stack_read(), preserve zeroes */ 4803 __mark_reg_const_zero(env, &state->regs[dst_regno]); 4804 insn_flags = 0; /* not restoring original register state */ 4805 } else { 4806 mark_reg_unknown(env, state->regs, dst_regno); 4807 insn_flags = 0; /* not restoring original register state */ 4808 } 4809 } 4810 state->regs[dst_regno].live |= REG_LIVE_WRITTEN; 4811 } else if (dst_regno >= 0) { 4812 /* restore register state from stack */ 4813 copy_register_state(&state->regs[dst_regno], reg); 4814 /* mark reg as written since spilled pointer state likely 4815 * has its liveness marks cleared by is_state_visited() 4816 * which resets stack/reg liveness for state transitions 4817 */ 4818 state->regs[dst_regno].live |= REG_LIVE_WRITTEN; 4819 } else if (__is_pointer_value(env->allow_ptr_leaks, reg)) { 4820 /* If dst_regno==-1, the caller is asking us whether 4821 * it is acceptable to use this value as a SCALAR_VALUE 4822 * (e.g. for XADD). 4823 * We must not allow unprivileged callers to do that 4824 * with spilled pointers. 4825 */ 4826 verbose(env, "leaking pointer from stack off %d\n", 4827 off); 4828 return -EACCES; 4829 } 4830 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64); 4831 } else { 4832 for (i = 0; i < size; i++) { 4833 type = stype[(slot - i) % BPF_REG_SIZE]; 4834 if (type == STACK_MISC) 4835 continue; 4836 if (type == STACK_ZERO) 4837 continue; 4838 if (type == STACK_INVALID && env->allow_uninit_stack) 4839 continue; 4840 verbose(env, "invalid read from stack off %d+%d size %d\n", 4841 off, i, size); 4842 return -EACCES; 4843 } 4844 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64); 4845 if (dst_regno >= 0) 4846 mark_reg_stack_read(env, reg_state, off, off + size, dst_regno); 4847 insn_flags = 0; /* we are not restoring spilled register */ 4848 } 4849 if (insn_flags) 4850 return push_jmp_history(env, env->cur_state, insn_flags); 4851 return 0; 4852 } 4853 4854 enum bpf_access_src { 4855 ACCESS_DIRECT = 1, /* the access is performed by an instruction */ 4856 ACCESS_HELPER = 2, /* the access is performed by a helper */ 4857 }; 4858 4859 static int check_stack_range_initialized(struct bpf_verifier_env *env, 4860 int regno, int off, int access_size, 4861 bool zero_size_allowed, 4862 enum bpf_access_src type, 4863 struct bpf_call_arg_meta *meta); 4864 4865 static struct bpf_reg_state *reg_state(struct bpf_verifier_env *env, int regno) 4866 { 4867 return cur_regs(env) + regno; 4868 } 4869 4870 /* Read the stack at 'ptr_regno + off' and put the result into the register 4871 * 'dst_regno'. 4872 * 'off' includes the pointer register's fixed offset(i.e. 'ptr_regno.off'), 4873 * but not its variable offset. 4874 * 'size' is assumed to be <= reg size and the access is assumed to be aligned. 4875 * 4876 * As opposed to check_stack_read_fixed_off, this function doesn't deal with 4877 * filling registers (i.e. reads of spilled register cannot be detected when 4878 * the offset is not fixed). We conservatively mark 'dst_regno' as containing 4879 * SCALAR_VALUE. That's why we assert that the 'ptr_regno' has a variable 4880 * offset; for a fixed offset check_stack_read_fixed_off should be used 4881 * instead. 4882 */ 4883 static int check_stack_read_var_off(struct bpf_verifier_env *env, 4884 int ptr_regno, int off, int size, int dst_regno) 4885 { 4886 /* The state of the source register. */ 4887 struct bpf_reg_state *reg = reg_state(env, ptr_regno); 4888 struct bpf_func_state *ptr_state = func(env, reg); 4889 int err; 4890 int min_off, max_off; 4891 4892 /* Note that we pass a NULL meta, so raw access will not be permitted. 4893 */ 4894 err = check_stack_range_initialized(env, ptr_regno, off, size, 4895 false, ACCESS_DIRECT, NULL); 4896 if (err) 4897 return err; 4898 4899 min_off = reg->smin_value + off; 4900 max_off = reg->smax_value + off; 4901 mark_reg_stack_read(env, ptr_state, min_off, max_off + size, dst_regno); 4902 return 0; 4903 } 4904 4905 /* check_stack_read dispatches to check_stack_read_fixed_off or 4906 * check_stack_read_var_off. 4907 * 4908 * The caller must ensure that the offset falls within the allocated stack 4909 * bounds. 4910 * 4911 * 'dst_regno' is a register which will receive the value from the stack. It 4912 * can be -1, meaning that the read value is not going to a register. 4913 */ 4914 static int check_stack_read(struct bpf_verifier_env *env, 4915 int ptr_regno, int off, int size, 4916 int dst_regno) 4917 { 4918 struct bpf_reg_state *reg = reg_state(env, ptr_regno); 4919 struct bpf_func_state *state = func(env, reg); 4920 int err; 4921 /* Some accesses are only permitted with a static offset. */ 4922 bool var_off = !tnum_is_const(reg->var_off); 4923 4924 /* The offset is required to be static when reads don't go to a 4925 * register, in order to not leak pointers (see 4926 * check_stack_read_fixed_off). 4927 */ 4928 if (dst_regno < 0 && var_off) { 4929 char tn_buf[48]; 4930 4931 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 4932 verbose(env, "variable offset stack pointer cannot be passed into helper function; var_off=%s off=%d size=%d\n", 4933 tn_buf, off, size); 4934 return -EACCES; 4935 } 4936 /* Variable offset is prohibited for unprivileged mode for simplicity 4937 * since it requires corresponding support in Spectre masking for stack 4938 * ALU. See also retrieve_ptr_limit(). The check in 4939 * check_stack_access_for_ptr_arithmetic() called by 4940 * adjust_ptr_min_max_vals() prevents users from creating stack pointers 4941 * with variable offsets, therefore no check is required here. Further, 4942 * just checking it here would be insufficient as speculative stack 4943 * writes could still lead to unsafe speculative behaviour. 4944 */ 4945 if (!var_off) { 4946 off += reg->var_off.value; 4947 err = check_stack_read_fixed_off(env, state, off, size, 4948 dst_regno); 4949 } else { 4950 /* Variable offset stack reads need more conservative handling 4951 * than fixed offset ones. Note that dst_regno >= 0 on this 4952 * branch. 4953 */ 4954 err = check_stack_read_var_off(env, ptr_regno, off, size, 4955 dst_regno); 4956 } 4957 return err; 4958 } 4959 4960 4961 /* check_stack_write dispatches to check_stack_write_fixed_off or 4962 * check_stack_write_var_off. 4963 * 4964 * 'ptr_regno' is the register used as a pointer into the stack. 4965 * 'off' includes 'ptr_regno->off', but not its variable offset (if any). 4966 * 'value_regno' is the register whose value we're writing to the stack. It can 4967 * be -1, meaning that we're not writing from a register. 4968 * 4969 * The caller must ensure that the offset falls within the maximum stack size. 4970 */ 4971 static int check_stack_write(struct bpf_verifier_env *env, 4972 int ptr_regno, int off, int size, 4973 int value_regno, int insn_idx) 4974 { 4975 struct bpf_reg_state *reg = reg_state(env, ptr_regno); 4976 struct bpf_func_state *state = func(env, reg); 4977 int err; 4978 4979 if (tnum_is_const(reg->var_off)) { 4980 off += reg->var_off.value; 4981 err = check_stack_write_fixed_off(env, state, off, size, 4982 value_regno, insn_idx); 4983 } else { 4984 /* Variable offset stack reads need more conservative handling 4985 * than fixed offset ones. 4986 */ 4987 err = check_stack_write_var_off(env, state, 4988 ptr_regno, off, size, 4989 value_regno, insn_idx); 4990 } 4991 return err; 4992 } 4993 4994 static int check_map_access_type(struct bpf_verifier_env *env, u32 regno, 4995 int off, int size, enum bpf_access_type type) 4996 { 4997 struct bpf_reg_state *regs = cur_regs(env); 4998 struct bpf_map *map = regs[regno].map_ptr; 4999 u32 cap = bpf_map_flags_to_cap(map); 5000 5001 if (type == BPF_WRITE && !(cap & BPF_MAP_CAN_WRITE)) { 5002 verbose(env, "write into map forbidden, value_size=%d off=%d size=%d\n", 5003 map->value_size, off, size); 5004 return -EACCES; 5005 } 5006 5007 if (type == BPF_READ && !(cap & BPF_MAP_CAN_READ)) { 5008 verbose(env, "read from map forbidden, value_size=%d off=%d size=%d\n", 5009 map->value_size, off, size); 5010 return -EACCES; 5011 } 5012 5013 return 0; 5014 } 5015 5016 /* check read/write into memory region (e.g., map value, ringbuf sample, etc) */ 5017 static int __check_mem_access(struct bpf_verifier_env *env, int regno, 5018 int off, int size, u32 mem_size, 5019 bool zero_size_allowed) 5020 { 5021 bool size_ok = size > 0 || (size == 0 && zero_size_allowed); 5022 struct bpf_reg_state *reg; 5023 5024 if (off >= 0 && size_ok && (u64)off + size <= mem_size) 5025 return 0; 5026 5027 reg = &cur_regs(env)[regno]; 5028 switch (reg->type) { 5029 case PTR_TO_MAP_KEY: 5030 verbose(env, "invalid access to map key, key_size=%d off=%d size=%d\n", 5031 mem_size, off, size); 5032 break; 5033 case PTR_TO_MAP_VALUE: 5034 verbose(env, "invalid access to map value, value_size=%d off=%d size=%d\n", 5035 mem_size, off, size); 5036 break; 5037 case PTR_TO_PACKET: 5038 case PTR_TO_PACKET_META: 5039 case PTR_TO_PACKET_END: 5040 verbose(env, "invalid access to packet, off=%d size=%d, R%d(id=%d,off=%d,r=%d)\n", 5041 off, size, regno, reg->id, off, mem_size); 5042 break; 5043 case PTR_TO_MEM: 5044 default: 5045 verbose(env, "invalid access to memory, mem_size=%u off=%d size=%d\n", 5046 mem_size, off, size); 5047 } 5048 5049 return -EACCES; 5050 } 5051 5052 /* check read/write into a memory region with possible variable offset */ 5053 static int check_mem_region_access(struct bpf_verifier_env *env, u32 regno, 5054 int off, int size, u32 mem_size, 5055 bool zero_size_allowed) 5056 { 5057 struct bpf_verifier_state *vstate = env->cur_state; 5058 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 5059 struct bpf_reg_state *reg = &state->regs[regno]; 5060 int err; 5061 5062 /* We may have adjusted the register pointing to memory region, so we 5063 * need to try adding each of min_value and max_value to off 5064 * to make sure our theoretical access will be safe. 5065 * 5066 * The minimum value is only important with signed 5067 * comparisons where we can't assume the floor of a 5068 * value is 0. If we are using signed variables for our 5069 * index'es we need to make sure that whatever we use 5070 * will have a set floor within our range. 5071 */ 5072 if (reg->smin_value < 0 && 5073 (reg->smin_value == S64_MIN || 5074 (off + reg->smin_value != (s64)(s32)(off + reg->smin_value)) || 5075 reg->smin_value + off < 0)) { 5076 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n", 5077 regno); 5078 return -EACCES; 5079 } 5080 err = __check_mem_access(env, regno, reg->smin_value + off, size, 5081 mem_size, zero_size_allowed); 5082 if (err) { 5083 verbose(env, "R%d min value is outside of the allowed memory range\n", 5084 regno); 5085 return err; 5086 } 5087 5088 /* If we haven't set a max value then we need to bail since we can't be 5089 * sure we won't do bad things. 5090 * If reg->umax_value + off could overflow, treat that as unbounded too. 5091 */ 5092 if (reg->umax_value >= BPF_MAX_VAR_OFF) { 5093 verbose(env, "R%d unbounded memory access, make sure to bounds check any such access\n", 5094 regno); 5095 return -EACCES; 5096 } 5097 err = __check_mem_access(env, regno, reg->umax_value + off, size, 5098 mem_size, zero_size_allowed); 5099 if (err) { 5100 verbose(env, "R%d max value is outside of the allowed memory range\n", 5101 regno); 5102 return err; 5103 } 5104 5105 return 0; 5106 } 5107 5108 static int __check_ptr_off_reg(struct bpf_verifier_env *env, 5109 const struct bpf_reg_state *reg, int regno, 5110 bool fixed_off_ok) 5111 { 5112 /* Access to this pointer-typed register or passing it to a helper 5113 * is only allowed in its original, unmodified form. 5114 */ 5115 5116 if (reg->off < 0) { 5117 verbose(env, "negative offset %s ptr R%d off=%d disallowed\n", 5118 reg_type_str(env, reg->type), regno, reg->off); 5119 return -EACCES; 5120 } 5121 5122 if (!fixed_off_ok && reg->off) { 5123 verbose(env, "dereference of modified %s ptr R%d off=%d disallowed\n", 5124 reg_type_str(env, reg->type), regno, reg->off); 5125 return -EACCES; 5126 } 5127 5128 if (!tnum_is_const(reg->var_off) || reg->var_off.value) { 5129 char tn_buf[48]; 5130 5131 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 5132 verbose(env, "variable %s access var_off=%s disallowed\n", 5133 reg_type_str(env, reg->type), tn_buf); 5134 return -EACCES; 5135 } 5136 5137 return 0; 5138 } 5139 5140 int check_ptr_off_reg(struct bpf_verifier_env *env, 5141 const struct bpf_reg_state *reg, int regno) 5142 { 5143 return __check_ptr_off_reg(env, reg, regno, false); 5144 } 5145 5146 static int map_kptr_match_type(struct bpf_verifier_env *env, 5147 struct btf_field *kptr_field, 5148 struct bpf_reg_state *reg, u32 regno) 5149 { 5150 const char *targ_name = btf_type_name(kptr_field->kptr.btf, kptr_field->kptr.btf_id); 5151 int perm_flags; 5152 const char *reg_name = ""; 5153 5154 if (btf_is_kernel(reg->btf)) { 5155 perm_flags = PTR_MAYBE_NULL | PTR_TRUSTED | MEM_RCU; 5156 5157 /* Only unreferenced case accepts untrusted pointers */ 5158 if (kptr_field->type == BPF_KPTR_UNREF) 5159 perm_flags |= PTR_UNTRUSTED; 5160 } else { 5161 perm_flags = PTR_MAYBE_NULL | MEM_ALLOC; 5162 if (kptr_field->type == BPF_KPTR_PERCPU) 5163 perm_flags |= MEM_PERCPU; 5164 } 5165 5166 if (base_type(reg->type) != PTR_TO_BTF_ID || (type_flag(reg->type) & ~perm_flags)) 5167 goto bad_type; 5168 5169 /* We need to verify reg->type and reg->btf, before accessing reg->btf */ 5170 reg_name = btf_type_name(reg->btf, reg->btf_id); 5171 5172 /* For ref_ptr case, release function check should ensure we get one 5173 * referenced PTR_TO_BTF_ID, and that its fixed offset is 0. For the 5174 * normal store of unreferenced kptr, we must ensure var_off is zero. 5175 * Since ref_ptr cannot be accessed directly by BPF insns, checks for 5176 * reg->off and reg->ref_obj_id are not needed here. 5177 */ 5178 if (__check_ptr_off_reg(env, reg, regno, true)) 5179 return -EACCES; 5180 5181 /* A full type match is needed, as BTF can be vmlinux, module or prog BTF, and 5182 * we also need to take into account the reg->off. 5183 * 5184 * We want to support cases like: 5185 * 5186 * struct foo { 5187 * struct bar br; 5188 * struct baz bz; 5189 * }; 5190 * 5191 * struct foo *v; 5192 * v = func(); // PTR_TO_BTF_ID 5193 * val->foo = v; // reg->off is zero, btf and btf_id match type 5194 * val->bar = &v->br; // reg->off is still zero, but we need to retry with 5195 * // first member type of struct after comparison fails 5196 * val->baz = &v->bz; // reg->off is non-zero, so struct needs to be walked 5197 * // to match type 5198 * 5199 * In the kptr_ref case, check_func_arg_reg_off already ensures reg->off 5200 * is zero. We must also ensure that btf_struct_ids_match does not walk 5201 * the struct to match type against first member of struct, i.e. reject 5202 * second case from above. Hence, when type is BPF_KPTR_REF, we set 5203 * strict mode to true for type match. 5204 */ 5205 if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off, 5206 kptr_field->kptr.btf, kptr_field->kptr.btf_id, 5207 kptr_field->type != BPF_KPTR_UNREF)) 5208 goto bad_type; 5209 return 0; 5210 bad_type: 5211 verbose(env, "invalid kptr access, R%d type=%s%s ", regno, 5212 reg_type_str(env, reg->type), reg_name); 5213 verbose(env, "expected=%s%s", reg_type_str(env, PTR_TO_BTF_ID), targ_name); 5214 if (kptr_field->type == BPF_KPTR_UNREF) 5215 verbose(env, " or %s%s\n", reg_type_str(env, PTR_TO_BTF_ID | PTR_UNTRUSTED), 5216 targ_name); 5217 else 5218 verbose(env, "\n"); 5219 return -EINVAL; 5220 } 5221 5222 /* The non-sleepable programs and sleepable programs with explicit bpf_rcu_read_lock() 5223 * can dereference RCU protected pointers and result is PTR_TRUSTED. 5224 */ 5225 static bool in_rcu_cs(struct bpf_verifier_env *env) 5226 { 5227 return env->cur_state->active_rcu_lock || 5228 env->cur_state->active_lock.ptr || 5229 !env->prog->aux->sleepable; 5230 } 5231 5232 /* Once GCC supports btf_type_tag the following mechanism will be replaced with tag check */ 5233 BTF_SET_START(rcu_protected_types) 5234 BTF_ID(struct, prog_test_ref_kfunc) 5235 #ifdef CONFIG_CGROUPS 5236 BTF_ID(struct, cgroup) 5237 #endif 5238 BTF_ID(struct, bpf_cpumask) 5239 BTF_ID(struct, task_struct) 5240 BTF_SET_END(rcu_protected_types) 5241 5242 static bool rcu_protected_object(const struct btf *btf, u32 btf_id) 5243 { 5244 if (!btf_is_kernel(btf)) 5245 return true; 5246 return btf_id_set_contains(&rcu_protected_types, btf_id); 5247 } 5248 5249 static struct btf_record *kptr_pointee_btf_record(struct btf_field *kptr_field) 5250 { 5251 struct btf_struct_meta *meta; 5252 5253 if (btf_is_kernel(kptr_field->kptr.btf)) 5254 return NULL; 5255 5256 meta = btf_find_struct_meta(kptr_field->kptr.btf, 5257 kptr_field->kptr.btf_id); 5258 5259 return meta ? meta->record : NULL; 5260 } 5261 5262 static bool rcu_safe_kptr(const struct btf_field *field) 5263 { 5264 const struct btf_field_kptr *kptr = &field->kptr; 5265 5266 return field->type == BPF_KPTR_PERCPU || 5267 (field->type == BPF_KPTR_REF && rcu_protected_object(kptr->btf, kptr->btf_id)); 5268 } 5269 5270 static u32 btf_ld_kptr_type(struct bpf_verifier_env *env, struct btf_field *kptr_field) 5271 { 5272 struct btf_record *rec; 5273 u32 ret; 5274 5275 ret = PTR_MAYBE_NULL; 5276 if (rcu_safe_kptr(kptr_field) && in_rcu_cs(env)) { 5277 ret |= MEM_RCU; 5278 if (kptr_field->type == BPF_KPTR_PERCPU) 5279 ret |= MEM_PERCPU; 5280 else if (!btf_is_kernel(kptr_field->kptr.btf)) 5281 ret |= MEM_ALLOC; 5282 5283 rec = kptr_pointee_btf_record(kptr_field); 5284 if (rec && btf_record_has_field(rec, BPF_GRAPH_NODE)) 5285 ret |= NON_OWN_REF; 5286 } else { 5287 ret |= PTR_UNTRUSTED; 5288 } 5289 5290 return ret; 5291 } 5292 5293 static int check_map_kptr_access(struct bpf_verifier_env *env, u32 regno, 5294 int value_regno, int insn_idx, 5295 struct btf_field *kptr_field) 5296 { 5297 struct bpf_insn *insn = &env->prog->insnsi[insn_idx]; 5298 int class = BPF_CLASS(insn->code); 5299 struct bpf_reg_state *val_reg; 5300 5301 /* Things we already checked for in check_map_access and caller: 5302 * - Reject cases where variable offset may touch kptr 5303 * - size of access (must be BPF_DW) 5304 * - tnum_is_const(reg->var_off) 5305 * - kptr_field->offset == off + reg->var_off.value 5306 */ 5307 /* Only BPF_[LDX,STX,ST] | BPF_MEM | BPF_DW is supported */ 5308 if (BPF_MODE(insn->code) != BPF_MEM) { 5309 verbose(env, "kptr in map can only be accessed using BPF_MEM instruction mode\n"); 5310 return -EACCES; 5311 } 5312 5313 /* We only allow loading referenced kptr, since it will be marked as 5314 * untrusted, similar to unreferenced kptr. 5315 */ 5316 if (class != BPF_LDX && 5317 (kptr_field->type == BPF_KPTR_REF || kptr_field->type == BPF_KPTR_PERCPU)) { 5318 verbose(env, "store to referenced kptr disallowed\n"); 5319 return -EACCES; 5320 } 5321 5322 if (class == BPF_LDX) { 5323 val_reg = reg_state(env, value_regno); 5324 /* We can simply mark the value_regno receiving the pointer 5325 * value from map as PTR_TO_BTF_ID, with the correct type. 5326 */ 5327 mark_btf_ld_reg(env, cur_regs(env), value_regno, PTR_TO_BTF_ID, kptr_field->kptr.btf, 5328 kptr_field->kptr.btf_id, btf_ld_kptr_type(env, kptr_field)); 5329 /* For mark_ptr_or_null_reg */ 5330 val_reg->id = ++env->id_gen; 5331 } else if (class == BPF_STX) { 5332 val_reg = reg_state(env, value_regno); 5333 if (!register_is_null(val_reg) && 5334 map_kptr_match_type(env, kptr_field, val_reg, value_regno)) 5335 return -EACCES; 5336 } else if (class == BPF_ST) { 5337 if (insn->imm) { 5338 verbose(env, "BPF_ST imm must be 0 when storing to kptr at off=%u\n", 5339 kptr_field->offset); 5340 return -EACCES; 5341 } 5342 } else { 5343 verbose(env, "kptr in map can only be accessed using BPF_LDX/BPF_STX/BPF_ST\n"); 5344 return -EACCES; 5345 } 5346 return 0; 5347 } 5348 5349 /* check read/write into a map element with possible variable offset */ 5350 static int check_map_access(struct bpf_verifier_env *env, u32 regno, 5351 int off, int size, bool zero_size_allowed, 5352 enum bpf_access_src src) 5353 { 5354 struct bpf_verifier_state *vstate = env->cur_state; 5355 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 5356 struct bpf_reg_state *reg = &state->regs[regno]; 5357 struct bpf_map *map = reg->map_ptr; 5358 struct btf_record *rec; 5359 int err, i; 5360 5361 err = check_mem_region_access(env, regno, off, size, map->value_size, 5362 zero_size_allowed); 5363 if (err) 5364 return err; 5365 5366 if (IS_ERR_OR_NULL(map->record)) 5367 return 0; 5368 rec = map->record; 5369 for (i = 0; i < rec->cnt; i++) { 5370 struct btf_field *field = &rec->fields[i]; 5371 u32 p = field->offset; 5372 5373 /* If any part of a field can be touched by load/store, reject 5374 * this program. To check that [x1, x2) overlaps with [y1, y2), 5375 * it is sufficient to check x1 < y2 && y1 < x2. 5376 */ 5377 if (reg->smin_value + off < p + btf_field_type_size(field->type) && 5378 p < reg->umax_value + off + size) { 5379 switch (field->type) { 5380 case BPF_KPTR_UNREF: 5381 case BPF_KPTR_REF: 5382 case BPF_KPTR_PERCPU: 5383 if (src != ACCESS_DIRECT) { 5384 verbose(env, "kptr cannot be accessed indirectly by helper\n"); 5385 return -EACCES; 5386 } 5387 if (!tnum_is_const(reg->var_off)) { 5388 verbose(env, "kptr access cannot have variable offset\n"); 5389 return -EACCES; 5390 } 5391 if (p != off + reg->var_off.value) { 5392 verbose(env, "kptr access misaligned expected=%u off=%llu\n", 5393 p, off + reg->var_off.value); 5394 return -EACCES; 5395 } 5396 if (size != bpf_size_to_bytes(BPF_DW)) { 5397 verbose(env, "kptr access size must be BPF_DW\n"); 5398 return -EACCES; 5399 } 5400 break; 5401 default: 5402 verbose(env, "%s cannot be accessed directly by load/store\n", 5403 btf_field_type_name(field->type)); 5404 return -EACCES; 5405 } 5406 } 5407 } 5408 return 0; 5409 } 5410 5411 #define MAX_PACKET_OFF 0xffff 5412 5413 static bool may_access_direct_pkt_data(struct bpf_verifier_env *env, 5414 const struct bpf_call_arg_meta *meta, 5415 enum bpf_access_type t) 5416 { 5417 enum bpf_prog_type prog_type = resolve_prog_type(env->prog); 5418 5419 switch (prog_type) { 5420 /* Program types only with direct read access go here! */ 5421 case BPF_PROG_TYPE_LWT_IN: 5422 case BPF_PROG_TYPE_LWT_OUT: 5423 case BPF_PROG_TYPE_LWT_SEG6LOCAL: 5424 case BPF_PROG_TYPE_SK_REUSEPORT: 5425 case BPF_PROG_TYPE_FLOW_DISSECTOR: 5426 case BPF_PROG_TYPE_CGROUP_SKB: 5427 if (t == BPF_WRITE) 5428 return false; 5429 fallthrough; 5430 5431 /* Program types with direct read + write access go here! */ 5432 case BPF_PROG_TYPE_SCHED_CLS: 5433 case BPF_PROG_TYPE_SCHED_ACT: 5434 case BPF_PROG_TYPE_XDP: 5435 case BPF_PROG_TYPE_LWT_XMIT: 5436 case BPF_PROG_TYPE_SK_SKB: 5437 case BPF_PROG_TYPE_SK_MSG: 5438 if (meta) 5439 return meta->pkt_access; 5440 5441 env->seen_direct_write = true; 5442 return true; 5443 5444 case BPF_PROG_TYPE_CGROUP_SOCKOPT: 5445 if (t == BPF_WRITE) 5446 env->seen_direct_write = true; 5447 5448 return true; 5449 5450 default: 5451 return false; 5452 } 5453 } 5454 5455 static int check_packet_access(struct bpf_verifier_env *env, u32 regno, int off, 5456 int size, bool zero_size_allowed) 5457 { 5458 struct bpf_reg_state *regs = cur_regs(env); 5459 struct bpf_reg_state *reg = ®s[regno]; 5460 int err; 5461 5462 /* We may have added a variable offset to the packet pointer; but any 5463 * reg->range we have comes after that. We are only checking the fixed 5464 * offset. 5465 */ 5466 5467 /* We don't allow negative numbers, because we aren't tracking enough 5468 * detail to prove they're safe. 5469 */ 5470 if (reg->smin_value < 0) { 5471 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n", 5472 regno); 5473 return -EACCES; 5474 } 5475 5476 err = reg->range < 0 ? -EINVAL : 5477 __check_mem_access(env, regno, off, size, reg->range, 5478 zero_size_allowed); 5479 if (err) { 5480 verbose(env, "R%d offset is outside of the packet\n", regno); 5481 return err; 5482 } 5483 5484 /* __check_mem_access has made sure "off + size - 1" is within u16. 5485 * reg->umax_value can't be bigger than MAX_PACKET_OFF which is 0xffff, 5486 * otherwise find_good_pkt_pointers would have refused to set range info 5487 * that __check_mem_access would have rejected this pkt access. 5488 * Therefore, "off + reg->umax_value + size - 1" won't overflow u32. 5489 */ 5490 env->prog->aux->max_pkt_offset = 5491 max_t(u32, env->prog->aux->max_pkt_offset, 5492 off + reg->umax_value + size - 1); 5493 5494 return err; 5495 } 5496 5497 /* check access to 'struct bpf_context' fields. Supports fixed offsets only */ 5498 static int check_ctx_access(struct bpf_verifier_env *env, int insn_idx, int off, int size, 5499 enum bpf_access_type t, enum bpf_reg_type *reg_type, 5500 struct btf **btf, u32 *btf_id) 5501 { 5502 struct bpf_insn_access_aux info = { 5503 .reg_type = *reg_type, 5504 .log = &env->log, 5505 }; 5506 5507 if (env->ops->is_valid_access && 5508 env->ops->is_valid_access(off, size, t, env->prog, &info)) { 5509 /* A non zero info.ctx_field_size indicates that this field is a 5510 * candidate for later verifier transformation to load the whole 5511 * field and then apply a mask when accessed with a narrower 5512 * access than actual ctx access size. A zero info.ctx_field_size 5513 * will only allow for whole field access and rejects any other 5514 * type of narrower access. 5515 */ 5516 *reg_type = info.reg_type; 5517 5518 if (base_type(*reg_type) == PTR_TO_BTF_ID) { 5519 *btf = info.btf; 5520 *btf_id = info.btf_id; 5521 } else { 5522 env->insn_aux_data[insn_idx].ctx_field_size = info.ctx_field_size; 5523 } 5524 /* remember the offset of last byte accessed in ctx */ 5525 if (env->prog->aux->max_ctx_offset < off + size) 5526 env->prog->aux->max_ctx_offset = off + size; 5527 return 0; 5528 } 5529 5530 verbose(env, "invalid bpf_context access off=%d size=%d\n", off, size); 5531 return -EACCES; 5532 } 5533 5534 static int check_flow_keys_access(struct bpf_verifier_env *env, int off, 5535 int size) 5536 { 5537 if (size < 0 || off < 0 || 5538 (u64)off + size > sizeof(struct bpf_flow_keys)) { 5539 verbose(env, "invalid access to flow keys off=%d size=%d\n", 5540 off, size); 5541 return -EACCES; 5542 } 5543 return 0; 5544 } 5545 5546 static int check_sock_access(struct bpf_verifier_env *env, int insn_idx, 5547 u32 regno, int off, int size, 5548 enum bpf_access_type t) 5549 { 5550 struct bpf_reg_state *regs = cur_regs(env); 5551 struct bpf_reg_state *reg = ®s[regno]; 5552 struct bpf_insn_access_aux info = {}; 5553 bool valid; 5554 5555 if (reg->smin_value < 0) { 5556 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n", 5557 regno); 5558 return -EACCES; 5559 } 5560 5561 switch (reg->type) { 5562 case PTR_TO_SOCK_COMMON: 5563 valid = bpf_sock_common_is_valid_access(off, size, t, &info); 5564 break; 5565 case PTR_TO_SOCKET: 5566 valid = bpf_sock_is_valid_access(off, size, t, &info); 5567 break; 5568 case PTR_TO_TCP_SOCK: 5569 valid = bpf_tcp_sock_is_valid_access(off, size, t, &info); 5570 break; 5571 case PTR_TO_XDP_SOCK: 5572 valid = bpf_xdp_sock_is_valid_access(off, size, t, &info); 5573 break; 5574 default: 5575 valid = false; 5576 } 5577 5578 5579 if (valid) { 5580 env->insn_aux_data[insn_idx].ctx_field_size = 5581 info.ctx_field_size; 5582 return 0; 5583 } 5584 5585 verbose(env, "R%d invalid %s access off=%d size=%d\n", 5586 regno, reg_type_str(env, reg->type), off, size); 5587 5588 return -EACCES; 5589 } 5590 5591 static bool is_pointer_value(struct bpf_verifier_env *env, int regno) 5592 { 5593 return __is_pointer_value(env->allow_ptr_leaks, reg_state(env, regno)); 5594 } 5595 5596 static bool is_ctx_reg(struct bpf_verifier_env *env, int regno) 5597 { 5598 const struct bpf_reg_state *reg = reg_state(env, regno); 5599 5600 return reg->type == PTR_TO_CTX; 5601 } 5602 5603 static bool is_sk_reg(struct bpf_verifier_env *env, int regno) 5604 { 5605 const struct bpf_reg_state *reg = reg_state(env, regno); 5606 5607 return type_is_sk_pointer(reg->type); 5608 } 5609 5610 static bool is_pkt_reg(struct bpf_verifier_env *env, int regno) 5611 { 5612 const struct bpf_reg_state *reg = reg_state(env, regno); 5613 5614 return type_is_pkt_pointer(reg->type); 5615 } 5616 5617 static bool is_flow_key_reg(struct bpf_verifier_env *env, int regno) 5618 { 5619 const struct bpf_reg_state *reg = reg_state(env, regno); 5620 5621 /* Separate to is_ctx_reg() since we still want to allow BPF_ST here. */ 5622 return reg->type == PTR_TO_FLOW_KEYS; 5623 } 5624 5625 static u32 *reg2btf_ids[__BPF_REG_TYPE_MAX] = { 5626 #ifdef CONFIG_NET 5627 [PTR_TO_SOCKET] = &btf_sock_ids[BTF_SOCK_TYPE_SOCK], 5628 [PTR_TO_SOCK_COMMON] = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON], 5629 [PTR_TO_TCP_SOCK] = &btf_sock_ids[BTF_SOCK_TYPE_TCP], 5630 #endif 5631 [CONST_PTR_TO_MAP] = btf_bpf_map_id, 5632 }; 5633 5634 static bool is_trusted_reg(const struct bpf_reg_state *reg) 5635 { 5636 /* A referenced register is always trusted. */ 5637 if (reg->ref_obj_id) 5638 return true; 5639 5640 /* Types listed in the reg2btf_ids are always trusted */ 5641 if (reg2btf_ids[base_type(reg->type)]) 5642 return true; 5643 5644 /* If a register is not referenced, it is trusted if it has the 5645 * MEM_ALLOC or PTR_TRUSTED type modifiers, and no others. Some of the 5646 * other type modifiers may be safe, but we elect to take an opt-in 5647 * approach here as some (e.g. PTR_UNTRUSTED and PTR_MAYBE_NULL) are 5648 * not. 5649 * 5650 * Eventually, we should make PTR_TRUSTED the single source of truth 5651 * for whether a register is trusted. 5652 */ 5653 return type_flag(reg->type) & BPF_REG_TRUSTED_MODIFIERS && 5654 !bpf_type_has_unsafe_modifiers(reg->type); 5655 } 5656 5657 static bool is_rcu_reg(const struct bpf_reg_state *reg) 5658 { 5659 return reg->type & MEM_RCU; 5660 } 5661 5662 static void clear_trusted_flags(enum bpf_type_flag *flag) 5663 { 5664 *flag &= ~(BPF_REG_TRUSTED_MODIFIERS | MEM_RCU); 5665 } 5666 5667 static int check_pkt_ptr_alignment(struct bpf_verifier_env *env, 5668 const struct bpf_reg_state *reg, 5669 int off, int size, bool strict) 5670 { 5671 struct tnum reg_off; 5672 int ip_align; 5673 5674 /* Byte size accesses are always allowed. */ 5675 if (!strict || size == 1) 5676 return 0; 5677 5678 /* For platforms that do not have a Kconfig enabling 5679 * CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS the value of 5680 * NET_IP_ALIGN is universally set to '2'. And on platforms 5681 * that do set CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS, we get 5682 * to this code only in strict mode where we want to emulate 5683 * the NET_IP_ALIGN==2 checking. Therefore use an 5684 * unconditional IP align value of '2'. 5685 */ 5686 ip_align = 2; 5687 5688 reg_off = tnum_add(reg->var_off, tnum_const(ip_align + reg->off + off)); 5689 if (!tnum_is_aligned(reg_off, size)) { 5690 char tn_buf[48]; 5691 5692 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 5693 verbose(env, 5694 "misaligned packet access off %d+%s+%d+%d size %d\n", 5695 ip_align, tn_buf, reg->off, off, size); 5696 return -EACCES; 5697 } 5698 5699 return 0; 5700 } 5701 5702 static int check_generic_ptr_alignment(struct bpf_verifier_env *env, 5703 const struct bpf_reg_state *reg, 5704 const char *pointer_desc, 5705 int off, int size, bool strict) 5706 { 5707 struct tnum reg_off; 5708 5709 /* Byte size accesses are always allowed. */ 5710 if (!strict || size == 1) 5711 return 0; 5712 5713 reg_off = tnum_add(reg->var_off, tnum_const(reg->off + off)); 5714 if (!tnum_is_aligned(reg_off, size)) { 5715 char tn_buf[48]; 5716 5717 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 5718 verbose(env, "misaligned %saccess off %s+%d+%d size %d\n", 5719 pointer_desc, tn_buf, reg->off, off, size); 5720 return -EACCES; 5721 } 5722 5723 return 0; 5724 } 5725 5726 static int check_ptr_alignment(struct bpf_verifier_env *env, 5727 const struct bpf_reg_state *reg, int off, 5728 int size, bool strict_alignment_once) 5729 { 5730 bool strict = env->strict_alignment || strict_alignment_once; 5731 const char *pointer_desc = ""; 5732 5733 switch (reg->type) { 5734 case PTR_TO_PACKET: 5735 case PTR_TO_PACKET_META: 5736 /* Special case, because of NET_IP_ALIGN. Given metadata sits 5737 * right in front, treat it the very same way. 5738 */ 5739 return check_pkt_ptr_alignment(env, reg, off, size, strict); 5740 case PTR_TO_FLOW_KEYS: 5741 pointer_desc = "flow keys "; 5742 break; 5743 case PTR_TO_MAP_KEY: 5744 pointer_desc = "key "; 5745 break; 5746 case PTR_TO_MAP_VALUE: 5747 pointer_desc = "value "; 5748 break; 5749 case PTR_TO_CTX: 5750 pointer_desc = "context "; 5751 break; 5752 case PTR_TO_STACK: 5753 pointer_desc = "stack "; 5754 /* The stack spill tracking logic in check_stack_write_fixed_off() 5755 * and check_stack_read_fixed_off() relies on stack accesses being 5756 * aligned. 5757 */ 5758 strict = true; 5759 break; 5760 case PTR_TO_SOCKET: 5761 pointer_desc = "sock "; 5762 break; 5763 case PTR_TO_SOCK_COMMON: 5764 pointer_desc = "sock_common "; 5765 break; 5766 case PTR_TO_TCP_SOCK: 5767 pointer_desc = "tcp_sock "; 5768 break; 5769 case PTR_TO_XDP_SOCK: 5770 pointer_desc = "xdp_sock "; 5771 break; 5772 default: 5773 break; 5774 } 5775 return check_generic_ptr_alignment(env, reg, pointer_desc, off, size, 5776 strict); 5777 } 5778 5779 /* starting from main bpf function walk all instructions of the function 5780 * and recursively walk all callees that given function can call. 5781 * Ignore jump and exit insns. 5782 * Since recursion is prevented by check_cfg() this algorithm 5783 * only needs a local stack of MAX_CALL_FRAMES to remember callsites 5784 */ 5785 static int check_max_stack_depth_subprog(struct bpf_verifier_env *env, int idx) 5786 { 5787 struct bpf_subprog_info *subprog = env->subprog_info; 5788 struct bpf_insn *insn = env->prog->insnsi; 5789 int depth = 0, frame = 0, i, subprog_end; 5790 bool tail_call_reachable = false; 5791 int ret_insn[MAX_CALL_FRAMES]; 5792 int ret_prog[MAX_CALL_FRAMES]; 5793 int j; 5794 5795 i = subprog[idx].start; 5796 process_func: 5797 /* protect against potential stack overflow that might happen when 5798 * bpf2bpf calls get combined with tailcalls. Limit the caller's stack 5799 * depth for such case down to 256 so that the worst case scenario 5800 * would result in 8k stack size (32 which is tailcall limit * 256 = 5801 * 8k). 5802 * 5803 * To get the idea what might happen, see an example: 5804 * func1 -> sub rsp, 128 5805 * subfunc1 -> sub rsp, 256 5806 * tailcall1 -> add rsp, 256 5807 * func2 -> sub rsp, 192 (total stack size = 128 + 192 = 320) 5808 * subfunc2 -> sub rsp, 64 5809 * subfunc22 -> sub rsp, 128 5810 * tailcall2 -> add rsp, 128 5811 * func3 -> sub rsp, 32 (total stack size 128 + 192 + 64 + 32 = 416) 5812 * 5813 * tailcall will unwind the current stack frame but it will not get rid 5814 * of caller's stack as shown on the example above. 5815 */ 5816 if (idx && subprog[idx].has_tail_call && depth >= 256) { 5817 verbose(env, 5818 "tail_calls are not allowed when call stack of previous frames is %d bytes. Too large\n", 5819 depth); 5820 return -EACCES; 5821 } 5822 /* round up to 32-bytes, since this is granularity 5823 * of interpreter stack size 5824 */ 5825 depth += round_up(max_t(u32, subprog[idx].stack_depth, 1), 32); 5826 if (depth > MAX_BPF_STACK) { 5827 verbose(env, "combined stack size of %d calls is %d. Too large\n", 5828 frame + 1, depth); 5829 return -EACCES; 5830 } 5831 continue_func: 5832 subprog_end = subprog[idx + 1].start; 5833 for (; i < subprog_end; i++) { 5834 int next_insn, sidx; 5835 5836 if (bpf_pseudo_kfunc_call(insn + i) && !insn[i].off) { 5837 bool err = false; 5838 5839 if (!is_bpf_throw_kfunc(insn + i)) 5840 continue; 5841 if (subprog[idx].is_cb) 5842 err = true; 5843 for (int c = 0; c < frame && !err; c++) { 5844 if (subprog[ret_prog[c]].is_cb) { 5845 err = true; 5846 break; 5847 } 5848 } 5849 if (!err) 5850 continue; 5851 verbose(env, 5852 "bpf_throw kfunc (insn %d) cannot be called from callback subprog %d\n", 5853 i, idx); 5854 return -EINVAL; 5855 } 5856 5857 if (!bpf_pseudo_call(insn + i) && !bpf_pseudo_func(insn + i)) 5858 continue; 5859 /* remember insn and function to return to */ 5860 ret_insn[frame] = i + 1; 5861 ret_prog[frame] = idx; 5862 5863 /* find the callee */ 5864 next_insn = i + insn[i].imm + 1; 5865 sidx = find_subprog(env, next_insn); 5866 if (sidx < 0) { 5867 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n", 5868 next_insn); 5869 return -EFAULT; 5870 } 5871 if (subprog[sidx].is_async_cb) { 5872 if (subprog[sidx].has_tail_call) { 5873 verbose(env, "verifier bug. subprog has tail_call and async cb\n"); 5874 return -EFAULT; 5875 } 5876 /* async callbacks don't increase bpf prog stack size unless called directly */ 5877 if (!bpf_pseudo_call(insn + i)) 5878 continue; 5879 if (subprog[sidx].is_exception_cb) { 5880 verbose(env, "insn %d cannot call exception cb directly\n", i); 5881 return -EINVAL; 5882 } 5883 } 5884 i = next_insn; 5885 idx = sidx; 5886 5887 if (subprog[idx].has_tail_call) 5888 tail_call_reachable = true; 5889 5890 frame++; 5891 if (frame >= MAX_CALL_FRAMES) { 5892 verbose(env, "the call stack of %d frames is too deep !\n", 5893 frame); 5894 return -E2BIG; 5895 } 5896 goto process_func; 5897 } 5898 /* if tail call got detected across bpf2bpf calls then mark each of the 5899 * currently present subprog frames as tail call reachable subprogs; 5900 * this info will be utilized by JIT so that we will be preserving the 5901 * tail call counter throughout bpf2bpf calls combined with tailcalls 5902 */ 5903 if (tail_call_reachable) 5904 for (j = 0; j < frame; j++) { 5905 if (subprog[ret_prog[j]].is_exception_cb) { 5906 verbose(env, "cannot tail call within exception cb\n"); 5907 return -EINVAL; 5908 } 5909 subprog[ret_prog[j]].tail_call_reachable = true; 5910 } 5911 if (subprog[0].tail_call_reachable) 5912 env->prog->aux->tail_call_reachable = true; 5913 5914 /* end of for() loop means the last insn of the 'subprog' 5915 * was reached. Doesn't matter whether it was JA or EXIT 5916 */ 5917 if (frame == 0) 5918 return 0; 5919 depth -= round_up(max_t(u32, subprog[idx].stack_depth, 1), 32); 5920 frame--; 5921 i = ret_insn[frame]; 5922 idx = ret_prog[frame]; 5923 goto continue_func; 5924 } 5925 5926 static int check_max_stack_depth(struct bpf_verifier_env *env) 5927 { 5928 struct bpf_subprog_info *si = env->subprog_info; 5929 int ret; 5930 5931 for (int i = 0; i < env->subprog_cnt; i++) { 5932 if (!i || si[i].is_async_cb) { 5933 ret = check_max_stack_depth_subprog(env, i); 5934 if (ret < 0) 5935 return ret; 5936 } 5937 continue; 5938 } 5939 return 0; 5940 } 5941 5942 #ifndef CONFIG_BPF_JIT_ALWAYS_ON 5943 static int get_callee_stack_depth(struct bpf_verifier_env *env, 5944 const struct bpf_insn *insn, int idx) 5945 { 5946 int start = idx + insn->imm + 1, subprog; 5947 5948 subprog = find_subprog(env, start); 5949 if (subprog < 0) { 5950 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n", 5951 start); 5952 return -EFAULT; 5953 } 5954 return env->subprog_info[subprog].stack_depth; 5955 } 5956 #endif 5957 5958 static int __check_buffer_access(struct bpf_verifier_env *env, 5959 const char *buf_info, 5960 const struct bpf_reg_state *reg, 5961 int regno, int off, int size) 5962 { 5963 if (off < 0) { 5964 verbose(env, 5965 "R%d invalid %s buffer access: off=%d, size=%d\n", 5966 regno, buf_info, off, size); 5967 return -EACCES; 5968 } 5969 if (!tnum_is_const(reg->var_off) || reg->var_off.value) { 5970 char tn_buf[48]; 5971 5972 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 5973 verbose(env, 5974 "R%d invalid variable buffer offset: off=%d, var_off=%s\n", 5975 regno, off, tn_buf); 5976 return -EACCES; 5977 } 5978 5979 return 0; 5980 } 5981 5982 static int check_tp_buffer_access(struct bpf_verifier_env *env, 5983 const struct bpf_reg_state *reg, 5984 int regno, int off, int size) 5985 { 5986 int err; 5987 5988 err = __check_buffer_access(env, "tracepoint", reg, regno, off, size); 5989 if (err) 5990 return err; 5991 5992 if (off + size > env->prog->aux->max_tp_access) 5993 env->prog->aux->max_tp_access = off + size; 5994 5995 return 0; 5996 } 5997 5998 static int check_buffer_access(struct bpf_verifier_env *env, 5999 const struct bpf_reg_state *reg, 6000 int regno, int off, int size, 6001 bool zero_size_allowed, 6002 u32 *max_access) 6003 { 6004 const char *buf_info = type_is_rdonly_mem(reg->type) ? "rdonly" : "rdwr"; 6005 int err; 6006 6007 err = __check_buffer_access(env, buf_info, reg, regno, off, size); 6008 if (err) 6009 return err; 6010 6011 if (off + size > *max_access) 6012 *max_access = off + size; 6013 6014 return 0; 6015 } 6016 6017 /* BPF architecture zero extends alu32 ops into 64-bit registesr */ 6018 static void zext_32_to_64(struct bpf_reg_state *reg) 6019 { 6020 reg->var_off = tnum_subreg(reg->var_off); 6021 __reg_assign_32_into_64(reg); 6022 } 6023 6024 /* truncate register to smaller size (in bytes) 6025 * must be called with size < BPF_REG_SIZE 6026 */ 6027 static void coerce_reg_to_size(struct bpf_reg_state *reg, int size) 6028 { 6029 u64 mask; 6030 6031 /* clear high bits in bit representation */ 6032 reg->var_off = tnum_cast(reg->var_off, size); 6033 6034 /* fix arithmetic bounds */ 6035 mask = ((u64)1 << (size * 8)) - 1; 6036 if ((reg->umin_value & ~mask) == (reg->umax_value & ~mask)) { 6037 reg->umin_value &= mask; 6038 reg->umax_value &= mask; 6039 } else { 6040 reg->umin_value = 0; 6041 reg->umax_value = mask; 6042 } 6043 reg->smin_value = reg->umin_value; 6044 reg->smax_value = reg->umax_value; 6045 6046 /* If size is smaller than 32bit register the 32bit register 6047 * values are also truncated so we push 64-bit bounds into 6048 * 32-bit bounds. Above were truncated < 32-bits already. 6049 */ 6050 if (size < 4) { 6051 __mark_reg32_unbounded(reg); 6052 reg_bounds_sync(reg); 6053 } 6054 } 6055 6056 static void set_sext64_default_val(struct bpf_reg_state *reg, int size) 6057 { 6058 if (size == 1) { 6059 reg->smin_value = reg->s32_min_value = S8_MIN; 6060 reg->smax_value = reg->s32_max_value = S8_MAX; 6061 } else if (size == 2) { 6062 reg->smin_value = reg->s32_min_value = S16_MIN; 6063 reg->smax_value = reg->s32_max_value = S16_MAX; 6064 } else { 6065 /* size == 4 */ 6066 reg->smin_value = reg->s32_min_value = S32_MIN; 6067 reg->smax_value = reg->s32_max_value = S32_MAX; 6068 } 6069 reg->umin_value = reg->u32_min_value = 0; 6070 reg->umax_value = U64_MAX; 6071 reg->u32_max_value = U32_MAX; 6072 reg->var_off = tnum_unknown; 6073 } 6074 6075 static void coerce_reg_to_size_sx(struct bpf_reg_state *reg, int size) 6076 { 6077 s64 init_s64_max, init_s64_min, s64_max, s64_min, u64_cval; 6078 u64 top_smax_value, top_smin_value; 6079 u64 num_bits = size * 8; 6080 6081 if (tnum_is_const(reg->var_off)) { 6082 u64_cval = reg->var_off.value; 6083 if (size == 1) 6084 reg->var_off = tnum_const((s8)u64_cval); 6085 else if (size == 2) 6086 reg->var_off = tnum_const((s16)u64_cval); 6087 else 6088 /* size == 4 */ 6089 reg->var_off = tnum_const((s32)u64_cval); 6090 6091 u64_cval = reg->var_off.value; 6092 reg->smax_value = reg->smin_value = u64_cval; 6093 reg->umax_value = reg->umin_value = u64_cval; 6094 reg->s32_max_value = reg->s32_min_value = u64_cval; 6095 reg->u32_max_value = reg->u32_min_value = u64_cval; 6096 return; 6097 } 6098 6099 top_smax_value = ((u64)reg->smax_value >> num_bits) << num_bits; 6100 top_smin_value = ((u64)reg->smin_value >> num_bits) << num_bits; 6101 6102 if (top_smax_value != top_smin_value) 6103 goto out; 6104 6105 /* find the s64_min and s64_min after sign extension */ 6106 if (size == 1) { 6107 init_s64_max = (s8)reg->smax_value; 6108 init_s64_min = (s8)reg->smin_value; 6109 } else if (size == 2) { 6110 init_s64_max = (s16)reg->smax_value; 6111 init_s64_min = (s16)reg->smin_value; 6112 } else { 6113 init_s64_max = (s32)reg->smax_value; 6114 init_s64_min = (s32)reg->smin_value; 6115 } 6116 6117 s64_max = max(init_s64_max, init_s64_min); 6118 s64_min = min(init_s64_max, init_s64_min); 6119 6120 /* both of s64_max/s64_min positive or negative */ 6121 if ((s64_max >= 0) == (s64_min >= 0)) { 6122 reg->smin_value = reg->s32_min_value = s64_min; 6123 reg->smax_value = reg->s32_max_value = s64_max; 6124 reg->umin_value = reg->u32_min_value = s64_min; 6125 reg->umax_value = reg->u32_max_value = s64_max; 6126 reg->var_off = tnum_range(s64_min, s64_max); 6127 return; 6128 } 6129 6130 out: 6131 set_sext64_default_val(reg, size); 6132 } 6133 6134 static void set_sext32_default_val(struct bpf_reg_state *reg, int size) 6135 { 6136 if (size == 1) { 6137 reg->s32_min_value = S8_MIN; 6138 reg->s32_max_value = S8_MAX; 6139 } else { 6140 /* size == 2 */ 6141 reg->s32_min_value = S16_MIN; 6142 reg->s32_max_value = S16_MAX; 6143 } 6144 reg->u32_min_value = 0; 6145 reg->u32_max_value = U32_MAX; 6146 } 6147 6148 static void coerce_subreg_to_size_sx(struct bpf_reg_state *reg, int size) 6149 { 6150 s32 init_s32_max, init_s32_min, s32_max, s32_min, u32_val; 6151 u32 top_smax_value, top_smin_value; 6152 u32 num_bits = size * 8; 6153 6154 if (tnum_is_const(reg->var_off)) { 6155 u32_val = reg->var_off.value; 6156 if (size == 1) 6157 reg->var_off = tnum_const((s8)u32_val); 6158 else 6159 reg->var_off = tnum_const((s16)u32_val); 6160 6161 u32_val = reg->var_off.value; 6162 reg->s32_min_value = reg->s32_max_value = u32_val; 6163 reg->u32_min_value = reg->u32_max_value = u32_val; 6164 return; 6165 } 6166 6167 top_smax_value = ((u32)reg->s32_max_value >> num_bits) << num_bits; 6168 top_smin_value = ((u32)reg->s32_min_value >> num_bits) << num_bits; 6169 6170 if (top_smax_value != top_smin_value) 6171 goto out; 6172 6173 /* find the s32_min and s32_min after sign extension */ 6174 if (size == 1) { 6175 init_s32_max = (s8)reg->s32_max_value; 6176 init_s32_min = (s8)reg->s32_min_value; 6177 } else { 6178 /* size == 2 */ 6179 init_s32_max = (s16)reg->s32_max_value; 6180 init_s32_min = (s16)reg->s32_min_value; 6181 } 6182 s32_max = max(init_s32_max, init_s32_min); 6183 s32_min = min(init_s32_max, init_s32_min); 6184 6185 if ((s32_min >= 0) == (s32_max >= 0)) { 6186 reg->s32_min_value = s32_min; 6187 reg->s32_max_value = s32_max; 6188 reg->u32_min_value = (u32)s32_min; 6189 reg->u32_max_value = (u32)s32_max; 6190 return; 6191 } 6192 6193 out: 6194 set_sext32_default_val(reg, size); 6195 } 6196 6197 static bool bpf_map_is_rdonly(const struct bpf_map *map) 6198 { 6199 /* A map is considered read-only if the following condition are true: 6200 * 6201 * 1) BPF program side cannot change any of the map content. The 6202 * BPF_F_RDONLY_PROG flag is throughout the lifetime of a map 6203 * and was set at map creation time. 6204 * 2) The map value(s) have been initialized from user space by a 6205 * loader and then "frozen", such that no new map update/delete 6206 * operations from syscall side are possible for the rest of 6207 * the map's lifetime from that point onwards. 6208 * 3) Any parallel/pending map update/delete operations from syscall 6209 * side have been completed. Only after that point, it's safe to 6210 * assume that map value(s) are immutable. 6211 */ 6212 return (map->map_flags & BPF_F_RDONLY_PROG) && 6213 READ_ONCE(map->frozen) && 6214 !bpf_map_write_active(map); 6215 } 6216 6217 static int bpf_map_direct_read(struct bpf_map *map, int off, int size, u64 *val, 6218 bool is_ldsx) 6219 { 6220 void *ptr; 6221 u64 addr; 6222 int err; 6223 6224 err = map->ops->map_direct_value_addr(map, &addr, off); 6225 if (err) 6226 return err; 6227 ptr = (void *)(long)addr + off; 6228 6229 switch (size) { 6230 case sizeof(u8): 6231 *val = is_ldsx ? (s64)*(s8 *)ptr : (u64)*(u8 *)ptr; 6232 break; 6233 case sizeof(u16): 6234 *val = is_ldsx ? (s64)*(s16 *)ptr : (u64)*(u16 *)ptr; 6235 break; 6236 case sizeof(u32): 6237 *val = is_ldsx ? (s64)*(s32 *)ptr : (u64)*(u32 *)ptr; 6238 break; 6239 case sizeof(u64): 6240 *val = *(u64 *)ptr; 6241 break; 6242 default: 6243 return -EINVAL; 6244 } 6245 return 0; 6246 } 6247 6248 #define BTF_TYPE_SAFE_RCU(__type) __PASTE(__type, __safe_rcu) 6249 #define BTF_TYPE_SAFE_RCU_OR_NULL(__type) __PASTE(__type, __safe_rcu_or_null) 6250 #define BTF_TYPE_SAFE_TRUSTED(__type) __PASTE(__type, __safe_trusted) 6251 6252 /* 6253 * Allow list few fields as RCU trusted or full trusted. 6254 * This logic doesn't allow mix tagging and will be removed once GCC supports 6255 * btf_type_tag. 6256 */ 6257 6258 /* RCU trusted: these fields are trusted in RCU CS and never NULL */ 6259 BTF_TYPE_SAFE_RCU(struct task_struct) { 6260 const cpumask_t *cpus_ptr; 6261 struct css_set __rcu *cgroups; 6262 struct task_struct __rcu *real_parent; 6263 struct task_struct *group_leader; 6264 }; 6265 6266 BTF_TYPE_SAFE_RCU(struct cgroup) { 6267 /* cgrp->kn is always accessible as documented in kernel/cgroup/cgroup.c */ 6268 struct kernfs_node *kn; 6269 }; 6270 6271 BTF_TYPE_SAFE_RCU(struct css_set) { 6272 struct cgroup *dfl_cgrp; 6273 }; 6274 6275 /* RCU trusted: these fields are trusted in RCU CS and can be NULL */ 6276 BTF_TYPE_SAFE_RCU_OR_NULL(struct mm_struct) { 6277 struct file __rcu *exe_file; 6278 }; 6279 6280 /* skb->sk, req->sk are not RCU protected, but we mark them as such 6281 * because bpf prog accessible sockets are SOCK_RCU_FREE. 6282 */ 6283 BTF_TYPE_SAFE_RCU_OR_NULL(struct sk_buff) { 6284 struct sock *sk; 6285 }; 6286 6287 BTF_TYPE_SAFE_RCU_OR_NULL(struct request_sock) { 6288 struct sock *sk; 6289 }; 6290 6291 /* full trusted: these fields are trusted even outside of RCU CS and never NULL */ 6292 BTF_TYPE_SAFE_TRUSTED(struct bpf_iter_meta) { 6293 struct seq_file *seq; 6294 }; 6295 6296 BTF_TYPE_SAFE_TRUSTED(struct bpf_iter__task) { 6297 struct bpf_iter_meta *meta; 6298 struct task_struct *task; 6299 }; 6300 6301 BTF_TYPE_SAFE_TRUSTED(struct linux_binprm) { 6302 struct file *file; 6303 }; 6304 6305 BTF_TYPE_SAFE_TRUSTED(struct file) { 6306 struct inode *f_inode; 6307 }; 6308 6309 BTF_TYPE_SAFE_TRUSTED(struct dentry) { 6310 /* no negative dentry-s in places where bpf can see it */ 6311 struct inode *d_inode; 6312 }; 6313 6314 BTF_TYPE_SAFE_TRUSTED(struct socket) { 6315 struct sock *sk; 6316 }; 6317 6318 static bool type_is_rcu(struct bpf_verifier_env *env, 6319 struct bpf_reg_state *reg, 6320 const char *field_name, u32 btf_id) 6321 { 6322 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct task_struct)); 6323 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct cgroup)); 6324 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct css_set)); 6325 6326 return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_rcu"); 6327 } 6328 6329 static bool type_is_rcu_or_null(struct bpf_verifier_env *env, 6330 struct bpf_reg_state *reg, 6331 const char *field_name, u32 btf_id) 6332 { 6333 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct mm_struct)); 6334 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct sk_buff)); 6335 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct request_sock)); 6336 6337 return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_rcu_or_null"); 6338 } 6339 6340 static bool type_is_trusted(struct bpf_verifier_env *env, 6341 struct bpf_reg_state *reg, 6342 const char *field_name, u32 btf_id) 6343 { 6344 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct bpf_iter_meta)); 6345 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct bpf_iter__task)); 6346 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct linux_binprm)); 6347 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct file)); 6348 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct dentry)); 6349 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct socket)); 6350 6351 return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_trusted"); 6352 } 6353 6354 static int check_ptr_to_btf_access(struct bpf_verifier_env *env, 6355 struct bpf_reg_state *regs, 6356 int regno, int off, int size, 6357 enum bpf_access_type atype, 6358 int value_regno) 6359 { 6360 struct bpf_reg_state *reg = regs + regno; 6361 const struct btf_type *t = btf_type_by_id(reg->btf, reg->btf_id); 6362 const char *tname = btf_name_by_offset(reg->btf, t->name_off); 6363 const char *field_name = NULL; 6364 enum bpf_type_flag flag = 0; 6365 u32 btf_id = 0; 6366 int ret; 6367 6368 if (!env->allow_ptr_leaks) { 6369 verbose(env, 6370 "'struct %s' access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n", 6371 tname); 6372 return -EPERM; 6373 } 6374 if (!env->prog->gpl_compatible && btf_is_kernel(reg->btf)) { 6375 verbose(env, 6376 "Cannot access kernel 'struct %s' from non-GPL compatible program\n", 6377 tname); 6378 return -EINVAL; 6379 } 6380 if (off < 0) { 6381 verbose(env, 6382 "R%d is ptr_%s invalid negative access: off=%d\n", 6383 regno, tname, off); 6384 return -EACCES; 6385 } 6386 if (!tnum_is_const(reg->var_off) || reg->var_off.value) { 6387 char tn_buf[48]; 6388 6389 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 6390 verbose(env, 6391 "R%d is ptr_%s invalid variable offset: off=%d, var_off=%s\n", 6392 regno, tname, off, tn_buf); 6393 return -EACCES; 6394 } 6395 6396 if (reg->type & MEM_USER) { 6397 verbose(env, 6398 "R%d is ptr_%s access user memory: off=%d\n", 6399 regno, tname, off); 6400 return -EACCES; 6401 } 6402 6403 if (reg->type & MEM_PERCPU) { 6404 verbose(env, 6405 "R%d is ptr_%s access percpu memory: off=%d\n", 6406 regno, tname, off); 6407 return -EACCES; 6408 } 6409 6410 if (env->ops->btf_struct_access && !type_is_alloc(reg->type) && atype == BPF_WRITE) { 6411 if (!btf_is_kernel(reg->btf)) { 6412 verbose(env, "verifier internal error: reg->btf must be kernel btf\n"); 6413 return -EFAULT; 6414 } 6415 ret = env->ops->btf_struct_access(&env->log, reg, off, size); 6416 } else { 6417 /* Writes are permitted with default btf_struct_access for 6418 * program allocated objects (which always have ref_obj_id > 0), 6419 * but not for untrusted PTR_TO_BTF_ID | MEM_ALLOC. 6420 */ 6421 if (atype != BPF_READ && !type_is_ptr_alloc_obj(reg->type)) { 6422 verbose(env, "only read is supported\n"); 6423 return -EACCES; 6424 } 6425 6426 if (type_is_alloc(reg->type) && !type_is_non_owning_ref(reg->type) && 6427 !(reg->type & MEM_RCU) && !reg->ref_obj_id) { 6428 verbose(env, "verifier internal error: ref_obj_id for allocated object must be non-zero\n"); 6429 return -EFAULT; 6430 } 6431 6432 ret = btf_struct_access(&env->log, reg, off, size, atype, &btf_id, &flag, &field_name); 6433 } 6434 6435 if (ret < 0) 6436 return ret; 6437 6438 if (ret != PTR_TO_BTF_ID) { 6439 /* just mark; */ 6440 6441 } else if (type_flag(reg->type) & PTR_UNTRUSTED) { 6442 /* If this is an untrusted pointer, all pointers formed by walking it 6443 * also inherit the untrusted flag. 6444 */ 6445 flag = PTR_UNTRUSTED; 6446 6447 } else if (is_trusted_reg(reg) || is_rcu_reg(reg)) { 6448 /* By default any pointer obtained from walking a trusted pointer is no 6449 * longer trusted, unless the field being accessed has explicitly been 6450 * marked as inheriting its parent's state of trust (either full or RCU). 6451 * For example: 6452 * 'cgroups' pointer is untrusted if task->cgroups dereference 6453 * happened in a sleepable program outside of bpf_rcu_read_lock() 6454 * section. In a non-sleepable program it's trusted while in RCU CS (aka MEM_RCU). 6455 * Note bpf_rcu_read_unlock() converts MEM_RCU pointers to PTR_UNTRUSTED. 6456 * 6457 * A regular RCU-protected pointer with __rcu tag can also be deemed 6458 * trusted if we are in an RCU CS. Such pointer can be NULL. 6459 */ 6460 if (type_is_trusted(env, reg, field_name, btf_id)) { 6461 flag |= PTR_TRUSTED; 6462 } else if (in_rcu_cs(env) && !type_may_be_null(reg->type)) { 6463 if (type_is_rcu(env, reg, field_name, btf_id)) { 6464 /* ignore __rcu tag and mark it MEM_RCU */ 6465 flag |= MEM_RCU; 6466 } else if (flag & MEM_RCU || 6467 type_is_rcu_or_null(env, reg, field_name, btf_id)) { 6468 /* __rcu tagged pointers can be NULL */ 6469 flag |= MEM_RCU | PTR_MAYBE_NULL; 6470 6471 /* We always trust them */ 6472 if (type_is_rcu_or_null(env, reg, field_name, btf_id) && 6473 flag & PTR_UNTRUSTED) 6474 flag &= ~PTR_UNTRUSTED; 6475 } else if (flag & (MEM_PERCPU | MEM_USER)) { 6476 /* keep as-is */ 6477 } else { 6478 /* walking unknown pointers yields old deprecated PTR_TO_BTF_ID */ 6479 clear_trusted_flags(&flag); 6480 } 6481 } else { 6482 /* 6483 * If not in RCU CS or MEM_RCU pointer can be NULL then 6484 * aggressively mark as untrusted otherwise such 6485 * pointers will be plain PTR_TO_BTF_ID without flags 6486 * and will be allowed to be passed into helpers for 6487 * compat reasons. 6488 */ 6489 flag = PTR_UNTRUSTED; 6490 } 6491 } else { 6492 /* Old compat. Deprecated */ 6493 clear_trusted_flags(&flag); 6494 } 6495 6496 if (atype == BPF_READ && value_regno >= 0) 6497 mark_btf_ld_reg(env, regs, value_regno, ret, reg->btf, btf_id, flag); 6498 6499 return 0; 6500 } 6501 6502 static int check_ptr_to_map_access(struct bpf_verifier_env *env, 6503 struct bpf_reg_state *regs, 6504 int regno, int off, int size, 6505 enum bpf_access_type atype, 6506 int value_regno) 6507 { 6508 struct bpf_reg_state *reg = regs + regno; 6509 struct bpf_map *map = reg->map_ptr; 6510 struct bpf_reg_state map_reg; 6511 enum bpf_type_flag flag = 0; 6512 const struct btf_type *t; 6513 const char *tname; 6514 u32 btf_id; 6515 int ret; 6516 6517 if (!btf_vmlinux) { 6518 verbose(env, "map_ptr access not supported without CONFIG_DEBUG_INFO_BTF\n"); 6519 return -ENOTSUPP; 6520 } 6521 6522 if (!map->ops->map_btf_id || !*map->ops->map_btf_id) { 6523 verbose(env, "map_ptr access not supported for map type %d\n", 6524 map->map_type); 6525 return -ENOTSUPP; 6526 } 6527 6528 t = btf_type_by_id(btf_vmlinux, *map->ops->map_btf_id); 6529 tname = btf_name_by_offset(btf_vmlinux, t->name_off); 6530 6531 if (!env->allow_ptr_leaks) { 6532 verbose(env, 6533 "'struct %s' access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n", 6534 tname); 6535 return -EPERM; 6536 } 6537 6538 if (off < 0) { 6539 verbose(env, "R%d is %s invalid negative access: off=%d\n", 6540 regno, tname, off); 6541 return -EACCES; 6542 } 6543 6544 if (atype != BPF_READ) { 6545 verbose(env, "only read from %s is supported\n", tname); 6546 return -EACCES; 6547 } 6548 6549 /* Simulate access to a PTR_TO_BTF_ID */ 6550 memset(&map_reg, 0, sizeof(map_reg)); 6551 mark_btf_ld_reg(env, &map_reg, 0, PTR_TO_BTF_ID, btf_vmlinux, *map->ops->map_btf_id, 0); 6552 ret = btf_struct_access(&env->log, &map_reg, off, size, atype, &btf_id, &flag, NULL); 6553 if (ret < 0) 6554 return ret; 6555 6556 if (value_regno >= 0) 6557 mark_btf_ld_reg(env, regs, value_regno, ret, btf_vmlinux, btf_id, flag); 6558 6559 return 0; 6560 } 6561 6562 /* Check that the stack access at the given offset is within bounds. The 6563 * maximum valid offset is -1. 6564 * 6565 * The minimum valid offset is -MAX_BPF_STACK for writes, and 6566 * -state->allocated_stack for reads. 6567 */ 6568 static int check_stack_slot_within_bounds(struct bpf_verifier_env *env, 6569 s64 off, 6570 struct bpf_func_state *state, 6571 enum bpf_access_type t) 6572 { 6573 int min_valid_off; 6574 6575 if (t == BPF_WRITE || env->allow_uninit_stack) 6576 min_valid_off = -MAX_BPF_STACK; 6577 else 6578 min_valid_off = -state->allocated_stack; 6579 6580 if (off < min_valid_off || off > -1) 6581 return -EACCES; 6582 return 0; 6583 } 6584 6585 /* Check that the stack access at 'regno + off' falls within the maximum stack 6586 * bounds. 6587 * 6588 * 'off' includes `regno->offset`, but not its dynamic part (if any). 6589 */ 6590 static int check_stack_access_within_bounds( 6591 struct bpf_verifier_env *env, 6592 int regno, int off, int access_size, 6593 enum bpf_access_src src, enum bpf_access_type type) 6594 { 6595 struct bpf_reg_state *regs = cur_regs(env); 6596 struct bpf_reg_state *reg = regs + regno; 6597 struct bpf_func_state *state = func(env, reg); 6598 s64 min_off, max_off; 6599 int err; 6600 char *err_extra; 6601 6602 if (src == ACCESS_HELPER) 6603 /* We don't know if helpers are reading or writing (or both). */ 6604 err_extra = " indirect access to"; 6605 else if (type == BPF_READ) 6606 err_extra = " read from"; 6607 else 6608 err_extra = " write to"; 6609 6610 if (tnum_is_const(reg->var_off)) { 6611 min_off = (s64)reg->var_off.value + off; 6612 max_off = min_off + access_size; 6613 } else { 6614 if (reg->smax_value >= BPF_MAX_VAR_OFF || 6615 reg->smin_value <= -BPF_MAX_VAR_OFF) { 6616 verbose(env, "invalid unbounded variable-offset%s stack R%d\n", 6617 err_extra, regno); 6618 return -EACCES; 6619 } 6620 min_off = reg->smin_value + off; 6621 max_off = reg->smax_value + off + access_size; 6622 } 6623 6624 err = check_stack_slot_within_bounds(env, min_off, state, type); 6625 if (!err && max_off > 0) 6626 err = -EINVAL; /* out of stack access into non-negative offsets */ 6627 6628 if (err) { 6629 if (tnum_is_const(reg->var_off)) { 6630 verbose(env, "invalid%s stack R%d off=%d size=%d\n", 6631 err_extra, regno, off, access_size); 6632 } else { 6633 char tn_buf[48]; 6634 6635 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 6636 verbose(env, "invalid variable-offset%s stack R%d var_off=%s off=%d size=%d\n", 6637 err_extra, regno, tn_buf, off, access_size); 6638 } 6639 return err; 6640 } 6641 6642 /* Note that there is no stack access with offset zero, so the needed stack 6643 * size is -min_off, not -min_off+1. 6644 */ 6645 return grow_stack_state(env, state, -min_off /* size */); 6646 } 6647 6648 /* check whether memory at (regno + off) is accessible for t = (read | write) 6649 * if t==write, value_regno is a register which value is stored into memory 6650 * if t==read, value_regno is a register which will receive the value from memory 6651 * if t==write && value_regno==-1, some unknown value is stored into memory 6652 * if t==read && value_regno==-1, don't care what we read from memory 6653 */ 6654 static int check_mem_access(struct bpf_verifier_env *env, int insn_idx, u32 regno, 6655 int off, int bpf_size, enum bpf_access_type t, 6656 int value_regno, bool strict_alignment_once, bool is_ldsx) 6657 { 6658 struct bpf_reg_state *regs = cur_regs(env); 6659 struct bpf_reg_state *reg = regs + regno; 6660 int size, err = 0; 6661 6662 size = bpf_size_to_bytes(bpf_size); 6663 if (size < 0) 6664 return size; 6665 6666 /* alignment checks will add in reg->off themselves */ 6667 err = check_ptr_alignment(env, reg, off, size, strict_alignment_once); 6668 if (err) 6669 return err; 6670 6671 /* for access checks, reg->off is just part of off */ 6672 off += reg->off; 6673 6674 if (reg->type == PTR_TO_MAP_KEY) { 6675 if (t == BPF_WRITE) { 6676 verbose(env, "write to change key R%d not allowed\n", regno); 6677 return -EACCES; 6678 } 6679 6680 err = check_mem_region_access(env, regno, off, size, 6681 reg->map_ptr->key_size, false); 6682 if (err) 6683 return err; 6684 if (value_regno >= 0) 6685 mark_reg_unknown(env, regs, value_regno); 6686 } else if (reg->type == PTR_TO_MAP_VALUE) { 6687 struct btf_field *kptr_field = NULL; 6688 6689 if (t == BPF_WRITE && value_regno >= 0 && 6690 is_pointer_value(env, value_regno)) { 6691 verbose(env, "R%d leaks addr into map\n", value_regno); 6692 return -EACCES; 6693 } 6694 err = check_map_access_type(env, regno, off, size, t); 6695 if (err) 6696 return err; 6697 err = check_map_access(env, regno, off, size, false, ACCESS_DIRECT); 6698 if (err) 6699 return err; 6700 if (tnum_is_const(reg->var_off)) 6701 kptr_field = btf_record_find(reg->map_ptr->record, 6702 off + reg->var_off.value, BPF_KPTR); 6703 if (kptr_field) { 6704 err = check_map_kptr_access(env, regno, value_regno, insn_idx, kptr_field); 6705 } else if (t == BPF_READ && value_regno >= 0) { 6706 struct bpf_map *map = reg->map_ptr; 6707 6708 /* if map is read-only, track its contents as scalars */ 6709 if (tnum_is_const(reg->var_off) && 6710 bpf_map_is_rdonly(map) && 6711 map->ops->map_direct_value_addr) { 6712 int map_off = off + reg->var_off.value; 6713 u64 val = 0; 6714 6715 err = bpf_map_direct_read(map, map_off, size, 6716 &val, is_ldsx); 6717 if (err) 6718 return err; 6719 6720 regs[value_regno].type = SCALAR_VALUE; 6721 __mark_reg_known(®s[value_regno], val); 6722 } else { 6723 mark_reg_unknown(env, regs, value_regno); 6724 } 6725 } 6726 } else if (base_type(reg->type) == PTR_TO_MEM) { 6727 bool rdonly_mem = type_is_rdonly_mem(reg->type); 6728 6729 if (type_may_be_null(reg->type)) { 6730 verbose(env, "R%d invalid mem access '%s'\n", regno, 6731 reg_type_str(env, reg->type)); 6732 return -EACCES; 6733 } 6734 6735 if (t == BPF_WRITE && rdonly_mem) { 6736 verbose(env, "R%d cannot write into %s\n", 6737 regno, reg_type_str(env, reg->type)); 6738 return -EACCES; 6739 } 6740 6741 if (t == BPF_WRITE && value_regno >= 0 && 6742 is_pointer_value(env, value_regno)) { 6743 verbose(env, "R%d leaks addr into mem\n", value_regno); 6744 return -EACCES; 6745 } 6746 6747 err = check_mem_region_access(env, regno, off, size, 6748 reg->mem_size, false); 6749 if (!err && value_regno >= 0 && (t == BPF_READ || rdonly_mem)) 6750 mark_reg_unknown(env, regs, value_regno); 6751 } else if (reg->type == PTR_TO_CTX) { 6752 enum bpf_reg_type reg_type = SCALAR_VALUE; 6753 struct btf *btf = NULL; 6754 u32 btf_id = 0; 6755 6756 if (t == BPF_WRITE && value_regno >= 0 && 6757 is_pointer_value(env, value_regno)) { 6758 verbose(env, "R%d leaks addr into ctx\n", value_regno); 6759 return -EACCES; 6760 } 6761 6762 err = check_ptr_off_reg(env, reg, regno); 6763 if (err < 0) 6764 return err; 6765 6766 err = check_ctx_access(env, insn_idx, off, size, t, ®_type, &btf, 6767 &btf_id); 6768 if (err) 6769 verbose_linfo(env, insn_idx, "; "); 6770 if (!err && t == BPF_READ && value_regno >= 0) { 6771 /* ctx access returns either a scalar, or a 6772 * PTR_TO_PACKET[_META,_END]. In the latter 6773 * case, we know the offset is zero. 6774 */ 6775 if (reg_type == SCALAR_VALUE) { 6776 mark_reg_unknown(env, regs, value_regno); 6777 } else { 6778 mark_reg_known_zero(env, regs, 6779 value_regno); 6780 if (type_may_be_null(reg_type)) 6781 regs[value_regno].id = ++env->id_gen; 6782 /* A load of ctx field could have different 6783 * actual load size with the one encoded in the 6784 * insn. When the dst is PTR, it is for sure not 6785 * a sub-register. 6786 */ 6787 regs[value_regno].subreg_def = DEF_NOT_SUBREG; 6788 if (base_type(reg_type) == PTR_TO_BTF_ID) { 6789 regs[value_regno].btf = btf; 6790 regs[value_regno].btf_id = btf_id; 6791 } 6792 } 6793 regs[value_regno].type = reg_type; 6794 } 6795 6796 } else if (reg->type == PTR_TO_STACK) { 6797 /* Basic bounds checks. */ 6798 err = check_stack_access_within_bounds(env, regno, off, size, ACCESS_DIRECT, t); 6799 if (err) 6800 return err; 6801 6802 if (t == BPF_READ) 6803 err = check_stack_read(env, regno, off, size, 6804 value_regno); 6805 else 6806 err = check_stack_write(env, regno, off, size, 6807 value_regno, insn_idx); 6808 } else if (reg_is_pkt_pointer(reg)) { 6809 if (t == BPF_WRITE && !may_access_direct_pkt_data(env, NULL, t)) { 6810 verbose(env, "cannot write into packet\n"); 6811 return -EACCES; 6812 } 6813 if (t == BPF_WRITE && value_regno >= 0 && 6814 is_pointer_value(env, value_regno)) { 6815 verbose(env, "R%d leaks addr into packet\n", 6816 value_regno); 6817 return -EACCES; 6818 } 6819 err = check_packet_access(env, regno, off, size, false); 6820 if (!err && t == BPF_READ && value_regno >= 0) 6821 mark_reg_unknown(env, regs, value_regno); 6822 } else if (reg->type == PTR_TO_FLOW_KEYS) { 6823 if (t == BPF_WRITE && value_regno >= 0 && 6824 is_pointer_value(env, value_regno)) { 6825 verbose(env, "R%d leaks addr into flow keys\n", 6826 value_regno); 6827 return -EACCES; 6828 } 6829 6830 err = check_flow_keys_access(env, off, size); 6831 if (!err && t == BPF_READ && value_regno >= 0) 6832 mark_reg_unknown(env, regs, value_regno); 6833 } else if (type_is_sk_pointer(reg->type)) { 6834 if (t == BPF_WRITE) { 6835 verbose(env, "R%d cannot write into %s\n", 6836 regno, reg_type_str(env, reg->type)); 6837 return -EACCES; 6838 } 6839 err = check_sock_access(env, insn_idx, regno, off, size, t); 6840 if (!err && value_regno >= 0) 6841 mark_reg_unknown(env, regs, value_regno); 6842 } else if (reg->type == PTR_TO_TP_BUFFER) { 6843 err = check_tp_buffer_access(env, reg, regno, off, size); 6844 if (!err && t == BPF_READ && value_regno >= 0) 6845 mark_reg_unknown(env, regs, value_regno); 6846 } else if (base_type(reg->type) == PTR_TO_BTF_ID && 6847 !type_may_be_null(reg->type)) { 6848 err = check_ptr_to_btf_access(env, regs, regno, off, size, t, 6849 value_regno); 6850 } else if (reg->type == CONST_PTR_TO_MAP) { 6851 err = check_ptr_to_map_access(env, regs, regno, off, size, t, 6852 value_regno); 6853 } else if (base_type(reg->type) == PTR_TO_BUF) { 6854 bool rdonly_mem = type_is_rdonly_mem(reg->type); 6855 u32 *max_access; 6856 6857 if (rdonly_mem) { 6858 if (t == BPF_WRITE) { 6859 verbose(env, "R%d cannot write into %s\n", 6860 regno, reg_type_str(env, reg->type)); 6861 return -EACCES; 6862 } 6863 max_access = &env->prog->aux->max_rdonly_access; 6864 } else { 6865 max_access = &env->prog->aux->max_rdwr_access; 6866 } 6867 6868 err = check_buffer_access(env, reg, regno, off, size, false, 6869 max_access); 6870 6871 if (!err && value_regno >= 0 && (rdonly_mem || t == BPF_READ)) 6872 mark_reg_unknown(env, regs, value_regno); 6873 } else { 6874 verbose(env, "R%d invalid mem access '%s'\n", regno, 6875 reg_type_str(env, reg->type)); 6876 return -EACCES; 6877 } 6878 6879 if (!err && size < BPF_REG_SIZE && value_regno >= 0 && t == BPF_READ && 6880 regs[value_regno].type == SCALAR_VALUE) { 6881 if (!is_ldsx) 6882 /* b/h/w load zero-extends, mark upper bits as known 0 */ 6883 coerce_reg_to_size(®s[value_regno], size); 6884 else 6885 coerce_reg_to_size_sx(®s[value_regno], size); 6886 } 6887 return err; 6888 } 6889 6890 static int check_atomic(struct bpf_verifier_env *env, int insn_idx, struct bpf_insn *insn) 6891 { 6892 int load_reg; 6893 int err; 6894 6895 switch (insn->imm) { 6896 case BPF_ADD: 6897 case BPF_ADD | BPF_FETCH: 6898 case BPF_AND: 6899 case BPF_AND | BPF_FETCH: 6900 case BPF_OR: 6901 case BPF_OR | BPF_FETCH: 6902 case BPF_XOR: 6903 case BPF_XOR | BPF_FETCH: 6904 case BPF_XCHG: 6905 case BPF_CMPXCHG: 6906 break; 6907 default: 6908 verbose(env, "BPF_ATOMIC uses invalid atomic opcode %02x\n", insn->imm); 6909 return -EINVAL; 6910 } 6911 6912 if (BPF_SIZE(insn->code) != BPF_W && BPF_SIZE(insn->code) != BPF_DW) { 6913 verbose(env, "invalid atomic operand size\n"); 6914 return -EINVAL; 6915 } 6916 6917 /* check src1 operand */ 6918 err = check_reg_arg(env, insn->src_reg, SRC_OP); 6919 if (err) 6920 return err; 6921 6922 /* check src2 operand */ 6923 err = check_reg_arg(env, insn->dst_reg, SRC_OP); 6924 if (err) 6925 return err; 6926 6927 if (insn->imm == BPF_CMPXCHG) { 6928 /* Check comparison of R0 with memory location */ 6929 const u32 aux_reg = BPF_REG_0; 6930 6931 err = check_reg_arg(env, aux_reg, SRC_OP); 6932 if (err) 6933 return err; 6934 6935 if (is_pointer_value(env, aux_reg)) { 6936 verbose(env, "R%d leaks addr into mem\n", aux_reg); 6937 return -EACCES; 6938 } 6939 } 6940 6941 if (is_pointer_value(env, insn->src_reg)) { 6942 verbose(env, "R%d leaks addr into mem\n", insn->src_reg); 6943 return -EACCES; 6944 } 6945 6946 if (is_ctx_reg(env, insn->dst_reg) || 6947 is_pkt_reg(env, insn->dst_reg) || 6948 is_flow_key_reg(env, insn->dst_reg) || 6949 is_sk_reg(env, insn->dst_reg)) { 6950 verbose(env, "BPF_ATOMIC stores into R%d %s is not allowed\n", 6951 insn->dst_reg, 6952 reg_type_str(env, reg_state(env, insn->dst_reg)->type)); 6953 return -EACCES; 6954 } 6955 6956 if (insn->imm & BPF_FETCH) { 6957 if (insn->imm == BPF_CMPXCHG) 6958 load_reg = BPF_REG_0; 6959 else 6960 load_reg = insn->src_reg; 6961 6962 /* check and record load of old value */ 6963 err = check_reg_arg(env, load_reg, DST_OP); 6964 if (err) 6965 return err; 6966 } else { 6967 /* This instruction accesses a memory location but doesn't 6968 * actually load it into a register. 6969 */ 6970 load_reg = -1; 6971 } 6972 6973 /* Check whether we can read the memory, with second call for fetch 6974 * case to simulate the register fill. 6975 */ 6976 err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off, 6977 BPF_SIZE(insn->code), BPF_READ, -1, true, false); 6978 if (!err && load_reg >= 0) 6979 err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off, 6980 BPF_SIZE(insn->code), BPF_READ, load_reg, 6981 true, false); 6982 if (err) 6983 return err; 6984 6985 /* Check whether we can write into the same memory. */ 6986 err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off, 6987 BPF_SIZE(insn->code), BPF_WRITE, -1, true, false); 6988 if (err) 6989 return err; 6990 return 0; 6991 } 6992 6993 /* When register 'regno' is used to read the stack (either directly or through 6994 * a helper function) make sure that it's within stack boundary and, depending 6995 * on the access type and privileges, that all elements of the stack are 6996 * initialized. 6997 * 6998 * 'off' includes 'regno->off', but not its dynamic part (if any). 6999 * 7000 * All registers that have been spilled on the stack in the slots within the 7001 * read offsets are marked as read. 7002 */ 7003 static int check_stack_range_initialized( 7004 struct bpf_verifier_env *env, int regno, int off, 7005 int access_size, bool zero_size_allowed, 7006 enum bpf_access_src type, struct bpf_call_arg_meta *meta) 7007 { 7008 struct bpf_reg_state *reg = reg_state(env, regno); 7009 struct bpf_func_state *state = func(env, reg); 7010 int err, min_off, max_off, i, j, slot, spi; 7011 char *err_extra = type == ACCESS_HELPER ? " indirect" : ""; 7012 enum bpf_access_type bounds_check_type; 7013 /* Some accesses can write anything into the stack, others are 7014 * read-only. 7015 */ 7016 bool clobber = false; 7017 7018 if (access_size == 0 && !zero_size_allowed) { 7019 verbose(env, "invalid zero-sized read\n"); 7020 return -EACCES; 7021 } 7022 7023 if (type == ACCESS_HELPER) { 7024 /* The bounds checks for writes are more permissive than for 7025 * reads. However, if raw_mode is not set, we'll do extra 7026 * checks below. 7027 */ 7028 bounds_check_type = BPF_WRITE; 7029 clobber = true; 7030 } else { 7031 bounds_check_type = BPF_READ; 7032 } 7033 err = check_stack_access_within_bounds(env, regno, off, access_size, 7034 type, bounds_check_type); 7035 if (err) 7036 return err; 7037 7038 7039 if (tnum_is_const(reg->var_off)) { 7040 min_off = max_off = reg->var_off.value + off; 7041 } else { 7042 /* Variable offset is prohibited for unprivileged mode for 7043 * simplicity since it requires corresponding support in 7044 * Spectre masking for stack ALU. 7045 * See also retrieve_ptr_limit(). 7046 */ 7047 if (!env->bypass_spec_v1) { 7048 char tn_buf[48]; 7049 7050 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 7051 verbose(env, "R%d%s variable offset stack access prohibited for !root, var_off=%s\n", 7052 regno, err_extra, tn_buf); 7053 return -EACCES; 7054 } 7055 /* Only initialized buffer on stack is allowed to be accessed 7056 * with variable offset. With uninitialized buffer it's hard to 7057 * guarantee that whole memory is marked as initialized on 7058 * helper return since specific bounds are unknown what may 7059 * cause uninitialized stack leaking. 7060 */ 7061 if (meta && meta->raw_mode) 7062 meta = NULL; 7063 7064 min_off = reg->smin_value + off; 7065 max_off = reg->smax_value + off; 7066 } 7067 7068 if (meta && meta->raw_mode) { 7069 /* Ensure we won't be overwriting dynptrs when simulating byte 7070 * by byte access in check_helper_call using meta.access_size. 7071 * This would be a problem if we have a helper in the future 7072 * which takes: 7073 * 7074 * helper(uninit_mem, len, dynptr) 7075 * 7076 * Now, uninint_mem may overlap with dynptr pointer. Hence, it 7077 * may end up writing to dynptr itself when touching memory from 7078 * arg 1. This can be relaxed on a case by case basis for known 7079 * safe cases, but reject due to the possibilitiy of aliasing by 7080 * default. 7081 */ 7082 for (i = min_off; i < max_off + access_size; i++) { 7083 int stack_off = -i - 1; 7084 7085 spi = __get_spi(i); 7086 /* raw_mode may write past allocated_stack */ 7087 if (state->allocated_stack <= stack_off) 7088 continue; 7089 if (state->stack[spi].slot_type[stack_off % BPF_REG_SIZE] == STACK_DYNPTR) { 7090 verbose(env, "potential write to dynptr at off=%d disallowed\n", i); 7091 return -EACCES; 7092 } 7093 } 7094 meta->access_size = access_size; 7095 meta->regno = regno; 7096 return 0; 7097 } 7098 7099 for (i = min_off; i < max_off + access_size; i++) { 7100 u8 *stype; 7101 7102 slot = -i - 1; 7103 spi = slot / BPF_REG_SIZE; 7104 if (state->allocated_stack <= slot) { 7105 verbose(env, "verifier bug: allocated_stack too small"); 7106 return -EFAULT; 7107 } 7108 7109 stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE]; 7110 if (*stype == STACK_MISC) 7111 goto mark; 7112 if ((*stype == STACK_ZERO) || 7113 (*stype == STACK_INVALID && env->allow_uninit_stack)) { 7114 if (clobber) { 7115 /* helper can write anything into the stack */ 7116 *stype = STACK_MISC; 7117 } 7118 goto mark; 7119 } 7120 7121 if (is_spilled_reg(&state->stack[spi]) && 7122 (state->stack[spi].spilled_ptr.type == SCALAR_VALUE || 7123 env->allow_ptr_leaks)) { 7124 if (clobber) { 7125 __mark_reg_unknown(env, &state->stack[spi].spilled_ptr); 7126 for (j = 0; j < BPF_REG_SIZE; j++) 7127 scrub_spilled_slot(&state->stack[spi].slot_type[j]); 7128 } 7129 goto mark; 7130 } 7131 7132 if (tnum_is_const(reg->var_off)) { 7133 verbose(env, "invalid%s read from stack R%d off %d+%d size %d\n", 7134 err_extra, regno, min_off, i - min_off, access_size); 7135 } else { 7136 char tn_buf[48]; 7137 7138 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 7139 verbose(env, "invalid%s read from stack R%d var_off %s+%d size %d\n", 7140 err_extra, regno, tn_buf, i - min_off, access_size); 7141 } 7142 return -EACCES; 7143 mark: 7144 /* reading any byte out of 8-byte 'spill_slot' will cause 7145 * the whole slot to be marked as 'read' 7146 */ 7147 mark_reg_read(env, &state->stack[spi].spilled_ptr, 7148 state->stack[spi].spilled_ptr.parent, 7149 REG_LIVE_READ64); 7150 /* We do not set REG_LIVE_WRITTEN for stack slot, as we can not 7151 * be sure that whether stack slot is written to or not. Hence, 7152 * we must still conservatively propagate reads upwards even if 7153 * helper may write to the entire memory range. 7154 */ 7155 } 7156 return 0; 7157 } 7158 7159 static int check_helper_mem_access(struct bpf_verifier_env *env, int regno, 7160 int access_size, bool zero_size_allowed, 7161 struct bpf_call_arg_meta *meta) 7162 { 7163 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno]; 7164 u32 *max_access; 7165 7166 switch (base_type(reg->type)) { 7167 case PTR_TO_PACKET: 7168 case PTR_TO_PACKET_META: 7169 return check_packet_access(env, regno, reg->off, access_size, 7170 zero_size_allowed); 7171 case PTR_TO_MAP_KEY: 7172 if (meta && meta->raw_mode) { 7173 verbose(env, "R%d cannot write into %s\n", regno, 7174 reg_type_str(env, reg->type)); 7175 return -EACCES; 7176 } 7177 return check_mem_region_access(env, regno, reg->off, access_size, 7178 reg->map_ptr->key_size, false); 7179 case PTR_TO_MAP_VALUE: 7180 if (check_map_access_type(env, regno, reg->off, access_size, 7181 meta && meta->raw_mode ? BPF_WRITE : 7182 BPF_READ)) 7183 return -EACCES; 7184 return check_map_access(env, regno, reg->off, access_size, 7185 zero_size_allowed, ACCESS_HELPER); 7186 case PTR_TO_MEM: 7187 if (type_is_rdonly_mem(reg->type)) { 7188 if (meta && meta->raw_mode) { 7189 verbose(env, "R%d cannot write into %s\n", regno, 7190 reg_type_str(env, reg->type)); 7191 return -EACCES; 7192 } 7193 } 7194 return check_mem_region_access(env, regno, reg->off, 7195 access_size, reg->mem_size, 7196 zero_size_allowed); 7197 case PTR_TO_BUF: 7198 if (type_is_rdonly_mem(reg->type)) { 7199 if (meta && meta->raw_mode) { 7200 verbose(env, "R%d cannot write into %s\n", regno, 7201 reg_type_str(env, reg->type)); 7202 return -EACCES; 7203 } 7204 7205 max_access = &env->prog->aux->max_rdonly_access; 7206 } else { 7207 max_access = &env->prog->aux->max_rdwr_access; 7208 } 7209 return check_buffer_access(env, reg, regno, reg->off, 7210 access_size, zero_size_allowed, 7211 max_access); 7212 case PTR_TO_STACK: 7213 return check_stack_range_initialized( 7214 env, 7215 regno, reg->off, access_size, 7216 zero_size_allowed, ACCESS_HELPER, meta); 7217 case PTR_TO_BTF_ID: 7218 return check_ptr_to_btf_access(env, regs, regno, reg->off, 7219 access_size, BPF_READ, -1); 7220 case PTR_TO_CTX: 7221 /* in case the function doesn't know how to access the context, 7222 * (because we are in a program of type SYSCALL for example), we 7223 * can not statically check its size. 7224 * Dynamically check it now. 7225 */ 7226 if (!env->ops->convert_ctx_access) { 7227 enum bpf_access_type atype = meta && meta->raw_mode ? BPF_WRITE : BPF_READ; 7228 int offset = access_size - 1; 7229 7230 /* Allow zero-byte read from PTR_TO_CTX */ 7231 if (access_size == 0) 7232 return zero_size_allowed ? 0 : -EACCES; 7233 7234 return check_mem_access(env, env->insn_idx, regno, offset, BPF_B, 7235 atype, -1, false, false); 7236 } 7237 7238 fallthrough; 7239 default: /* scalar_value or invalid ptr */ 7240 /* Allow zero-byte read from NULL, regardless of pointer type */ 7241 if (zero_size_allowed && access_size == 0 && 7242 register_is_null(reg)) 7243 return 0; 7244 7245 verbose(env, "R%d type=%s ", regno, 7246 reg_type_str(env, reg->type)); 7247 verbose(env, "expected=%s\n", reg_type_str(env, PTR_TO_STACK)); 7248 return -EACCES; 7249 } 7250 } 7251 7252 /* verify arguments to helpers or kfuncs consisting of a pointer and an access 7253 * size. 7254 * 7255 * @regno is the register containing the access size. regno-1 is the register 7256 * containing the pointer. 7257 */ 7258 static int check_mem_size_reg(struct bpf_verifier_env *env, 7259 struct bpf_reg_state *reg, u32 regno, 7260 bool zero_size_allowed, 7261 struct bpf_call_arg_meta *meta) 7262 { 7263 int err; 7264 7265 /* This is used to refine r0 return value bounds for helpers 7266 * that enforce this value as an upper bound on return values. 7267 * See do_refine_retval_range() for helpers that can refine 7268 * the return value. C type of helper is u32 so we pull register 7269 * bound from umax_value however, if negative verifier errors 7270 * out. Only upper bounds can be learned because retval is an 7271 * int type and negative retvals are allowed. 7272 */ 7273 meta->msize_max_value = reg->umax_value; 7274 7275 /* The register is SCALAR_VALUE; the access check 7276 * happens using its boundaries. 7277 */ 7278 if (!tnum_is_const(reg->var_off)) 7279 /* For unprivileged variable accesses, disable raw 7280 * mode so that the program is required to 7281 * initialize all the memory that the helper could 7282 * just partially fill up. 7283 */ 7284 meta = NULL; 7285 7286 if (reg->smin_value < 0) { 7287 verbose(env, "R%d min value is negative, either use unsigned or 'var &= const'\n", 7288 regno); 7289 return -EACCES; 7290 } 7291 7292 if (reg->umin_value == 0) { 7293 err = check_helper_mem_access(env, regno - 1, 0, 7294 zero_size_allowed, 7295 meta); 7296 if (err) 7297 return err; 7298 } 7299 7300 if (reg->umax_value >= BPF_MAX_VAR_SIZ) { 7301 verbose(env, "R%d unbounded memory access, use 'var &= const' or 'if (var < const)'\n", 7302 regno); 7303 return -EACCES; 7304 } 7305 err = check_helper_mem_access(env, regno - 1, 7306 reg->umax_value, 7307 zero_size_allowed, meta); 7308 if (!err) 7309 err = mark_chain_precision(env, regno); 7310 return err; 7311 } 7312 7313 int check_mem_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg, 7314 u32 regno, u32 mem_size) 7315 { 7316 bool may_be_null = type_may_be_null(reg->type); 7317 struct bpf_reg_state saved_reg; 7318 struct bpf_call_arg_meta meta; 7319 int err; 7320 7321 if (register_is_null(reg)) 7322 return 0; 7323 7324 memset(&meta, 0, sizeof(meta)); 7325 /* Assuming that the register contains a value check if the memory 7326 * access is safe. Temporarily save and restore the register's state as 7327 * the conversion shouldn't be visible to a caller. 7328 */ 7329 if (may_be_null) { 7330 saved_reg = *reg; 7331 mark_ptr_not_null_reg(reg); 7332 } 7333 7334 err = check_helper_mem_access(env, regno, mem_size, true, &meta); 7335 /* Check access for BPF_WRITE */ 7336 meta.raw_mode = true; 7337 err = err ?: check_helper_mem_access(env, regno, mem_size, true, &meta); 7338 7339 if (may_be_null) 7340 *reg = saved_reg; 7341 7342 return err; 7343 } 7344 7345 static int check_kfunc_mem_size_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg, 7346 u32 regno) 7347 { 7348 struct bpf_reg_state *mem_reg = &cur_regs(env)[regno - 1]; 7349 bool may_be_null = type_may_be_null(mem_reg->type); 7350 struct bpf_reg_state saved_reg; 7351 struct bpf_call_arg_meta meta; 7352 int err; 7353 7354 WARN_ON_ONCE(regno < BPF_REG_2 || regno > BPF_REG_5); 7355 7356 memset(&meta, 0, sizeof(meta)); 7357 7358 if (may_be_null) { 7359 saved_reg = *mem_reg; 7360 mark_ptr_not_null_reg(mem_reg); 7361 } 7362 7363 err = check_mem_size_reg(env, reg, regno, true, &meta); 7364 /* Check access for BPF_WRITE */ 7365 meta.raw_mode = true; 7366 err = err ?: check_mem_size_reg(env, reg, regno, true, &meta); 7367 7368 if (may_be_null) 7369 *mem_reg = saved_reg; 7370 return err; 7371 } 7372 7373 /* Implementation details: 7374 * bpf_map_lookup returns PTR_TO_MAP_VALUE_OR_NULL. 7375 * bpf_obj_new returns PTR_TO_BTF_ID | MEM_ALLOC | PTR_MAYBE_NULL. 7376 * Two bpf_map_lookups (even with the same key) will have different reg->id. 7377 * Two separate bpf_obj_new will also have different reg->id. 7378 * For traditional PTR_TO_MAP_VALUE or PTR_TO_BTF_ID | MEM_ALLOC, the verifier 7379 * clears reg->id after value_or_null->value transition, since the verifier only 7380 * cares about the range of access to valid map value pointer and doesn't care 7381 * about actual address of the map element. 7382 * For maps with 'struct bpf_spin_lock' inside map value the verifier keeps 7383 * reg->id > 0 after value_or_null->value transition. By doing so 7384 * two bpf_map_lookups will be considered two different pointers that 7385 * point to different bpf_spin_locks. Likewise for pointers to allocated objects 7386 * returned from bpf_obj_new. 7387 * The verifier allows taking only one bpf_spin_lock at a time to avoid 7388 * dead-locks. 7389 * Since only one bpf_spin_lock is allowed the checks are simpler than 7390 * reg_is_refcounted() logic. The verifier needs to remember only 7391 * one spin_lock instead of array of acquired_refs. 7392 * cur_state->active_lock remembers which map value element or allocated 7393 * object got locked and clears it after bpf_spin_unlock. 7394 */ 7395 static int process_spin_lock(struct bpf_verifier_env *env, int regno, 7396 bool is_lock) 7397 { 7398 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno]; 7399 struct bpf_verifier_state *cur = env->cur_state; 7400 bool is_const = tnum_is_const(reg->var_off); 7401 u64 val = reg->var_off.value; 7402 struct bpf_map *map = NULL; 7403 struct btf *btf = NULL; 7404 struct btf_record *rec; 7405 7406 if (!is_const) { 7407 verbose(env, 7408 "R%d doesn't have constant offset. bpf_spin_lock has to be at the constant offset\n", 7409 regno); 7410 return -EINVAL; 7411 } 7412 if (reg->type == PTR_TO_MAP_VALUE) { 7413 map = reg->map_ptr; 7414 if (!map->btf) { 7415 verbose(env, 7416 "map '%s' has to have BTF in order to use bpf_spin_lock\n", 7417 map->name); 7418 return -EINVAL; 7419 } 7420 } else { 7421 btf = reg->btf; 7422 } 7423 7424 rec = reg_btf_record(reg); 7425 if (!btf_record_has_field(rec, BPF_SPIN_LOCK)) { 7426 verbose(env, "%s '%s' has no valid bpf_spin_lock\n", map ? "map" : "local", 7427 map ? map->name : "kptr"); 7428 return -EINVAL; 7429 } 7430 if (rec->spin_lock_off != val + reg->off) { 7431 verbose(env, "off %lld doesn't point to 'struct bpf_spin_lock' that is at %d\n", 7432 val + reg->off, rec->spin_lock_off); 7433 return -EINVAL; 7434 } 7435 if (is_lock) { 7436 if (cur->active_lock.ptr) { 7437 verbose(env, 7438 "Locking two bpf_spin_locks are not allowed\n"); 7439 return -EINVAL; 7440 } 7441 if (map) 7442 cur->active_lock.ptr = map; 7443 else 7444 cur->active_lock.ptr = btf; 7445 cur->active_lock.id = reg->id; 7446 } else { 7447 void *ptr; 7448 7449 if (map) 7450 ptr = map; 7451 else 7452 ptr = btf; 7453 7454 if (!cur->active_lock.ptr) { 7455 verbose(env, "bpf_spin_unlock without taking a lock\n"); 7456 return -EINVAL; 7457 } 7458 if (cur->active_lock.ptr != ptr || 7459 cur->active_lock.id != reg->id) { 7460 verbose(env, "bpf_spin_unlock of different lock\n"); 7461 return -EINVAL; 7462 } 7463 7464 invalidate_non_owning_refs(env); 7465 7466 cur->active_lock.ptr = NULL; 7467 cur->active_lock.id = 0; 7468 } 7469 return 0; 7470 } 7471 7472 static int process_timer_func(struct bpf_verifier_env *env, int regno, 7473 struct bpf_call_arg_meta *meta) 7474 { 7475 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno]; 7476 bool is_const = tnum_is_const(reg->var_off); 7477 struct bpf_map *map = reg->map_ptr; 7478 u64 val = reg->var_off.value; 7479 7480 if (!is_const) { 7481 verbose(env, 7482 "R%d doesn't have constant offset. bpf_timer has to be at the constant offset\n", 7483 regno); 7484 return -EINVAL; 7485 } 7486 if (!map->btf) { 7487 verbose(env, "map '%s' has to have BTF in order to use bpf_timer\n", 7488 map->name); 7489 return -EINVAL; 7490 } 7491 if (!btf_record_has_field(map->record, BPF_TIMER)) { 7492 verbose(env, "map '%s' has no valid bpf_timer\n", map->name); 7493 return -EINVAL; 7494 } 7495 if (map->record->timer_off != val + reg->off) { 7496 verbose(env, "off %lld doesn't point to 'struct bpf_timer' that is at %d\n", 7497 val + reg->off, map->record->timer_off); 7498 return -EINVAL; 7499 } 7500 if (meta->map_ptr) { 7501 verbose(env, "verifier bug. Two map pointers in a timer helper\n"); 7502 return -EFAULT; 7503 } 7504 meta->map_uid = reg->map_uid; 7505 meta->map_ptr = map; 7506 return 0; 7507 } 7508 7509 static int process_kptr_func(struct bpf_verifier_env *env, int regno, 7510 struct bpf_call_arg_meta *meta) 7511 { 7512 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno]; 7513 struct bpf_map *map_ptr = reg->map_ptr; 7514 struct btf_field *kptr_field; 7515 u32 kptr_off; 7516 7517 if (!tnum_is_const(reg->var_off)) { 7518 verbose(env, 7519 "R%d doesn't have constant offset. kptr has to be at the constant offset\n", 7520 regno); 7521 return -EINVAL; 7522 } 7523 if (!map_ptr->btf) { 7524 verbose(env, "map '%s' has to have BTF in order to use bpf_kptr_xchg\n", 7525 map_ptr->name); 7526 return -EINVAL; 7527 } 7528 if (!btf_record_has_field(map_ptr->record, BPF_KPTR)) { 7529 verbose(env, "map '%s' has no valid kptr\n", map_ptr->name); 7530 return -EINVAL; 7531 } 7532 7533 meta->map_ptr = map_ptr; 7534 kptr_off = reg->off + reg->var_off.value; 7535 kptr_field = btf_record_find(map_ptr->record, kptr_off, BPF_KPTR); 7536 if (!kptr_field) { 7537 verbose(env, "off=%d doesn't point to kptr\n", kptr_off); 7538 return -EACCES; 7539 } 7540 if (kptr_field->type != BPF_KPTR_REF && kptr_field->type != BPF_KPTR_PERCPU) { 7541 verbose(env, "off=%d kptr isn't referenced kptr\n", kptr_off); 7542 return -EACCES; 7543 } 7544 meta->kptr_field = kptr_field; 7545 return 0; 7546 } 7547 7548 /* There are two register types representing a bpf_dynptr, one is PTR_TO_STACK 7549 * which points to a stack slot, and the other is CONST_PTR_TO_DYNPTR. 7550 * 7551 * In both cases we deal with the first 8 bytes, but need to mark the next 8 7552 * bytes as STACK_DYNPTR in case of PTR_TO_STACK. In case of 7553 * CONST_PTR_TO_DYNPTR, we are guaranteed to get the beginning of the object. 7554 * 7555 * Mutability of bpf_dynptr is at two levels, one is at the level of struct 7556 * bpf_dynptr itself, i.e. whether the helper is receiving a pointer to struct 7557 * bpf_dynptr or pointer to const struct bpf_dynptr. In the former case, it can 7558 * mutate the view of the dynptr and also possibly destroy it. In the latter 7559 * case, it cannot mutate the bpf_dynptr itself but it can still mutate the 7560 * memory that dynptr points to. 7561 * 7562 * The verifier will keep track both levels of mutation (bpf_dynptr's in 7563 * reg->type and the memory's in reg->dynptr.type), but there is no support for 7564 * readonly dynptr view yet, hence only the first case is tracked and checked. 7565 * 7566 * This is consistent with how C applies the const modifier to a struct object, 7567 * where the pointer itself inside bpf_dynptr becomes const but not what it 7568 * points to. 7569 * 7570 * Helpers which do not mutate the bpf_dynptr set MEM_RDONLY in their argument 7571 * type, and declare it as 'const struct bpf_dynptr *' in their prototype. 7572 */ 7573 static int process_dynptr_func(struct bpf_verifier_env *env, int regno, int insn_idx, 7574 enum bpf_arg_type arg_type, int clone_ref_obj_id) 7575 { 7576 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno]; 7577 int err; 7578 7579 /* MEM_UNINIT and MEM_RDONLY are exclusive, when applied to an 7580 * ARG_PTR_TO_DYNPTR (or ARG_PTR_TO_DYNPTR | DYNPTR_TYPE_*): 7581 */ 7582 if ((arg_type & (MEM_UNINIT | MEM_RDONLY)) == (MEM_UNINIT | MEM_RDONLY)) { 7583 verbose(env, "verifier internal error: misconfigured dynptr helper type flags\n"); 7584 return -EFAULT; 7585 } 7586 7587 /* MEM_UNINIT - Points to memory that is an appropriate candidate for 7588 * constructing a mutable bpf_dynptr object. 7589 * 7590 * Currently, this is only possible with PTR_TO_STACK 7591 * pointing to a region of at least 16 bytes which doesn't 7592 * contain an existing bpf_dynptr. 7593 * 7594 * MEM_RDONLY - Points to a initialized bpf_dynptr that will not be 7595 * mutated or destroyed. However, the memory it points to 7596 * may be mutated. 7597 * 7598 * None - Points to a initialized dynptr that can be mutated and 7599 * destroyed, including mutation of the memory it points 7600 * to. 7601 */ 7602 if (arg_type & MEM_UNINIT) { 7603 int i; 7604 7605 if (!is_dynptr_reg_valid_uninit(env, reg)) { 7606 verbose(env, "Dynptr has to be an uninitialized dynptr\n"); 7607 return -EINVAL; 7608 } 7609 7610 /* we write BPF_DW bits (8 bytes) at a time */ 7611 for (i = 0; i < BPF_DYNPTR_SIZE; i += 8) { 7612 err = check_mem_access(env, insn_idx, regno, 7613 i, BPF_DW, BPF_WRITE, -1, false, false); 7614 if (err) 7615 return err; 7616 } 7617 7618 err = mark_stack_slots_dynptr(env, reg, arg_type, insn_idx, clone_ref_obj_id); 7619 } else /* MEM_RDONLY and None case from above */ { 7620 /* For the reg->type == PTR_TO_STACK case, bpf_dynptr is never const */ 7621 if (reg->type == CONST_PTR_TO_DYNPTR && !(arg_type & MEM_RDONLY)) { 7622 verbose(env, "cannot pass pointer to const bpf_dynptr, the helper mutates it\n"); 7623 return -EINVAL; 7624 } 7625 7626 if (!is_dynptr_reg_valid_init(env, reg)) { 7627 verbose(env, 7628 "Expected an initialized dynptr as arg #%d\n", 7629 regno); 7630 return -EINVAL; 7631 } 7632 7633 /* Fold modifiers (in this case, MEM_RDONLY) when checking expected type */ 7634 if (!is_dynptr_type_expected(env, reg, arg_type & ~MEM_RDONLY)) { 7635 verbose(env, 7636 "Expected a dynptr of type %s as arg #%d\n", 7637 dynptr_type_str(arg_to_dynptr_type(arg_type)), regno); 7638 return -EINVAL; 7639 } 7640 7641 err = mark_dynptr_read(env, reg); 7642 } 7643 return err; 7644 } 7645 7646 static u32 iter_ref_obj_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg, int spi) 7647 { 7648 struct bpf_func_state *state = func(env, reg); 7649 7650 return state->stack[spi].spilled_ptr.ref_obj_id; 7651 } 7652 7653 static bool is_iter_kfunc(struct bpf_kfunc_call_arg_meta *meta) 7654 { 7655 return meta->kfunc_flags & (KF_ITER_NEW | KF_ITER_NEXT | KF_ITER_DESTROY); 7656 } 7657 7658 static bool is_iter_new_kfunc(struct bpf_kfunc_call_arg_meta *meta) 7659 { 7660 return meta->kfunc_flags & KF_ITER_NEW; 7661 } 7662 7663 static bool is_iter_next_kfunc(struct bpf_kfunc_call_arg_meta *meta) 7664 { 7665 return meta->kfunc_flags & KF_ITER_NEXT; 7666 } 7667 7668 static bool is_iter_destroy_kfunc(struct bpf_kfunc_call_arg_meta *meta) 7669 { 7670 return meta->kfunc_flags & KF_ITER_DESTROY; 7671 } 7672 7673 static bool is_kfunc_arg_iter(struct bpf_kfunc_call_arg_meta *meta, int arg) 7674 { 7675 /* btf_check_iter_kfuncs() guarantees that first argument of any iter 7676 * kfunc is iter state pointer 7677 */ 7678 return arg == 0 && is_iter_kfunc(meta); 7679 } 7680 7681 static int process_iter_arg(struct bpf_verifier_env *env, int regno, int insn_idx, 7682 struct bpf_kfunc_call_arg_meta *meta) 7683 { 7684 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno]; 7685 const struct btf_type *t; 7686 const struct btf_param *arg; 7687 int spi, err, i, nr_slots; 7688 u32 btf_id; 7689 7690 /* btf_check_iter_kfuncs() ensures we don't need to validate anything here */ 7691 arg = &btf_params(meta->func_proto)[0]; 7692 t = btf_type_skip_modifiers(meta->btf, arg->type, NULL); /* PTR */ 7693 t = btf_type_skip_modifiers(meta->btf, t->type, &btf_id); /* STRUCT */ 7694 nr_slots = t->size / BPF_REG_SIZE; 7695 7696 if (is_iter_new_kfunc(meta)) { 7697 /* bpf_iter_<type>_new() expects pointer to uninit iter state */ 7698 if (!is_iter_reg_valid_uninit(env, reg, nr_slots)) { 7699 verbose(env, "expected uninitialized iter_%s as arg #%d\n", 7700 iter_type_str(meta->btf, btf_id), regno); 7701 return -EINVAL; 7702 } 7703 7704 for (i = 0; i < nr_slots * 8; i += BPF_REG_SIZE) { 7705 err = check_mem_access(env, insn_idx, regno, 7706 i, BPF_DW, BPF_WRITE, -1, false, false); 7707 if (err) 7708 return err; 7709 } 7710 7711 err = mark_stack_slots_iter(env, meta, reg, insn_idx, meta->btf, btf_id, nr_slots); 7712 if (err) 7713 return err; 7714 } else { 7715 /* iter_next() or iter_destroy() expect initialized iter state*/ 7716 err = is_iter_reg_valid_init(env, reg, meta->btf, btf_id, nr_slots); 7717 switch (err) { 7718 case 0: 7719 break; 7720 case -EINVAL: 7721 verbose(env, "expected an initialized iter_%s as arg #%d\n", 7722 iter_type_str(meta->btf, btf_id), regno); 7723 return err; 7724 case -EPROTO: 7725 verbose(env, "expected an RCU CS when using %s\n", meta->func_name); 7726 return err; 7727 default: 7728 return err; 7729 } 7730 7731 spi = iter_get_spi(env, reg, nr_slots); 7732 if (spi < 0) 7733 return spi; 7734 7735 err = mark_iter_read(env, reg, spi, nr_slots); 7736 if (err) 7737 return err; 7738 7739 /* remember meta->iter info for process_iter_next_call() */ 7740 meta->iter.spi = spi; 7741 meta->iter.frameno = reg->frameno; 7742 meta->ref_obj_id = iter_ref_obj_id(env, reg, spi); 7743 7744 if (is_iter_destroy_kfunc(meta)) { 7745 err = unmark_stack_slots_iter(env, reg, nr_slots); 7746 if (err) 7747 return err; 7748 } 7749 } 7750 7751 return 0; 7752 } 7753 7754 /* Look for a previous loop entry at insn_idx: nearest parent state 7755 * stopped at insn_idx with callsites matching those in cur->frame. 7756 */ 7757 static struct bpf_verifier_state *find_prev_entry(struct bpf_verifier_env *env, 7758 struct bpf_verifier_state *cur, 7759 int insn_idx) 7760 { 7761 struct bpf_verifier_state_list *sl; 7762 struct bpf_verifier_state *st; 7763 7764 /* Explored states are pushed in stack order, most recent states come first */ 7765 sl = *explored_state(env, insn_idx); 7766 for (; sl; sl = sl->next) { 7767 /* If st->branches != 0 state is a part of current DFS verification path, 7768 * hence cur & st for a loop. 7769 */ 7770 st = &sl->state; 7771 if (st->insn_idx == insn_idx && st->branches && same_callsites(st, cur) && 7772 st->dfs_depth < cur->dfs_depth) 7773 return st; 7774 } 7775 7776 return NULL; 7777 } 7778 7779 static void reset_idmap_scratch(struct bpf_verifier_env *env); 7780 static bool regs_exact(const struct bpf_reg_state *rold, 7781 const struct bpf_reg_state *rcur, 7782 struct bpf_idmap *idmap); 7783 7784 static void maybe_widen_reg(struct bpf_verifier_env *env, 7785 struct bpf_reg_state *rold, struct bpf_reg_state *rcur, 7786 struct bpf_idmap *idmap) 7787 { 7788 if (rold->type != SCALAR_VALUE) 7789 return; 7790 if (rold->type != rcur->type) 7791 return; 7792 if (rold->precise || rcur->precise || regs_exact(rold, rcur, idmap)) 7793 return; 7794 __mark_reg_unknown(env, rcur); 7795 } 7796 7797 static int widen_imprecise_scalars(struct bpf_verifier_env *env, 7798 struct bpf_verifier_state *old, 7799 struct bpf_verifier_state *cur) 7800 { 7801 struct bpf_func_state *fold, *fcur; 7802 int i, fr; 7803 7804 reset_idmap_scratch(env); 7805 for (fr = old->curframe; fr >= 0; fr--) { 7806 fold = old->frame[fr]; 7807 fcur = cur->frame[fr]; 7808 7809 for (i = 0; i < MAX_BPF_REG; i++) 7810 maybe_widen_reg(env, 7811 &fold->regs[i], 7812 &fcur->regs[i], 7813 &env->idmap_scratch); 7814 7815 for (i = 0; i < fold->allocated_stack / BPF_REG_SIZE; i++) { 7816 if (!is_spilled_reg(&fold->stack[i]) || 7817 !is_spilled_reg(&fcur->stack[i])) 7818 continue; 7819 7820 maybe_widen_reg(env, 7821 &fold->stack[i].spilled_ptr, 7822 &fcur->stack[i].spilled_ptr, 7823 &env->idmap_scratch); 7824 } 7825 } 7826 return 0; 7827 } 7828 7829 /* process_iter_next_call() is called when verifier gets to iterator's next 7830 * "method" (e.g., bpf_iter_num_next() for numbers iterator) call. We'll refer 7831 * to it as just "iter_next()" in comments below. 7832 * 7833 * BPF verifier relies on a crucial contract for any iter_next() 7834 * implementation: it should *eventually* return NULL, and once that happens 7835 * it should keep returning NULL. That is, once iterator exhausts elements to 7836 * iterate, it should never reset or spuriously return new elements. 7837 * 7838 * With the assumption of such contract, process_iter_next_call() simulates 7839 * a fork in the verifier state to validate loop logic correctness and safety 7840 * without having to simulate infinite amount of iterations. 7841 * 7842 * In current state, we first assume that iter_next() returned NULL and 7843 * iterator state is set to DRAINED (BPF_ITER_STATE_DRAINED). In such 7844 * conditions we should not form an infinite loop and should eventually reach 7845 * exit. 7846 * 7847 * Besides that, we also fork current state and enqueue it for later 7848 * verification. In a forked state we keep iterator state as ACTIVE 7849 * (BPF_ITER_STATE_ACTIVE) and assume non-NULL return from iter_next(). We 7850 * also bump iteration depth to prevent erroneous infinite loop detection 7851 * later on (see iter_active_depths_differ() comment for details). In this 7852 * state we assume that we'll eventually loop back to another iter_next() 7853 * calls (it could be in exactly same location or in some other instruction, 7854 * it doesn't matter, we don't make any unnecessary assumptions about this, 7855 * everything revolves around iterator state in a stack slot, not which 7856 * instruction is calling iter_next()). When that happens, we either will come 7857 * to iter_next() with equivalent state and can conclude that next iteration 7858 * will proceed in exactly the same way as we just verified, so it's safe to 7859 * assume that loop converges. If not, we'll go on another iteration 7860 * simulation with a different input state, until all possible starting states 7861 * are validated or we reach maximum number of instructions limit. 7862 * 7863 * This way, we will either exhaustively discover all possible input states 7864 * that iterator loop can start with and eventually will converge, or we'll 7865 * effectively regress into bounded loop simulation logic and either reach 7866 * maximum number of instructions if loop is not provably convergent, or there 7867 * is some statically known limit on number of iterations (e.g., if there is 7868 * an explicit `if n > 100 then break;` statement somewhere in the loop). 7869 * 7870 * Iteration convergence logic in is_state_visited() relies on exact 7871 * states comparison, which ignores read and precision marks. 7872 * This is necessary because read and precision marks are not finalized 7873 * while in the loop. Exact comparison might preclude convergence for 7874 * simple programs like below: 7875 * 7876 * i = 0; 7877 * while(iter_next(&it)) 7878 * i++; 7879 * 7880 * At each iteration step i++ would produce a new distinct state and 7881 * eventually instruction processing limit would be reached. 7882 * 7883 * To avoid such behavior speculatively forget (widen) range for 7884 * imprecise scalar registers, if those registers were not precise at the 7885 * end of the previous iteration and do not match exactly. 7886 * 7887 * This is a conservative heuristic that allows to verify wide range of programs, 7888 * however it precludes verification of programs that conjure an 7889 * imprecise value on the first loop iteration and use it as precise on a second. 7890 * For example, the following safe program would fail to verify: 7891 * 7892 * struct bpf_num_iter it; 7893 * int arr[10]; 7894 * int i = 0, a = 0; 7895 * bpf_iter_num_new(&it, 0, 10); 7896 * while (bpf_iter_num_next(&it)) { 7897 * if (a == 0) { 7898 * a = 1; 7899 * i = 7; // Because i changed verifier would forget 7900 * // it's range on second loop entry. 7901 * } else { 7902 * arr[i] = 42; // This would fail to verify. 7903 * } 7904 * } 7905 * bpf_iter_num_destroy(&it); 7906 */ 7907 static int process_iter_next_call(struct bpf_verifier_env *env, int insn_idx, 7908 struct bpf_kfunc_call_arg_meta *meta) 7909 { 7910 struct bpf_verifier_state *cur_st = env->cur_state, *queued_st, *prev_st; 7911 struct bpf_func_state *cur_fr = cur_st->frame[cur_st->curframe], *queued_fr; 7912 struct bpf_reg_state *cur_iter, *queued_iter; 7913 int iter_frameno = meta->iter.frameno; 7914 int iter_spi = meta->iter.spi; 7915 7916 BTF_TYPE_EMIT(struct bpf_iter); 7917 7918 cur_iter = &env->cur_state->frame[iter_frameno]->stack[iter_spi].spilled_ptr; 7919 7920 if (cur_iter->iter.state != BPF_ITER_STATE_ACTIVE && 7921 cur_iter->iter.state != BPF_ITER_STATE_DRAINED) { 7922 verbose(env, "verifier internal error: unexpected iterator state %d (%s)\n", 7923 cur_iter->iter.state, iter_state_str(cur_iter->iter.state)); 7924 return -EFAULT; 7925 } 7926 7927 if (cur_iter->iter.state == BPF_ITER_STATE_ACTIVE) { 7928 /* Because iter_next() call is a checkpoint is_state_visitied() 7929 * should guarantee parent state with same call sites and insn_idx. 7930 */ 7931 if (!cur_st->parent || cur_st->parent->insn_idx != insn_idx || 7932 !same_callsites(cur_st->parent, cur_st)) { 7933 verbose(env, "bug: bad parent state for iter next call"); 7934 return -EFAULT; 7935 } 7936 /* Note cur_st->parent in the call below, it is necessary to skip 7937 * checkpoint created for cur_st by is_state_visited() 7938 * right at this instruction. 7939 */ 7940 prev_st = find_prev_entry(env, cur_st->parent, insn_idx); 7941 /* branch out active iter state */ 7942 queued_st = push_stack(env, insn_idx + 1, insn_idx, false); 7943 if (!queued_st) 7944 return -ENOMEM; 7945 7946 queued_iter = &queued_st->frame[iter_frameno]->stack[iter_spi].spilled_ptr; 7947 queued_iter->iter.state = BPF_ITER_STATE_ACTIVE; 7948 queued_iter->iter.depth++; 7949 if (prev_st) 7950 widen_imprecise_scalars(env, prev_st, queued_st); 7951 7952 queued_fr = queued_st->frame[queued_st->curframe]; 7953 mark_ptr_not_null_reg(&queued_fr->regs[BPF_REG_0]); 7954 } 7955 7956 /* switch to DRAINED state, but keep the depth unchanged */ 7957 /* mark current iter state as drained and assume returned NULL */ 7958 cur_iter->iter.state = BPF_ITER_STATE_DRAINED; 7959 __mark_reg_const_zero(env, &cur_fr->regs[BPF_REG_0]); 7960 7961 return 0; 7962 } 7963 7964 static bool arg_type_is_mem_size(enum bpf_arg_type type) 7965 { 7966 return type == ARG_CONST_SIZE || 7967 type == ARG_CONST_SIZE_OR_ZERO; 7968 } 7969 7970 static bool arg_type_is_release(enum bpf_arg_type type) 7971 { 7972 return type & OBJ_RELEASE; 7973 } 7974 7975 static bool arg_type_is_dynptr(enum bpf_arg_type type) 7976 { 7977 return base_type(type) == ARG_PTR_TO_DYNPTR; 7978 } 7979 7980 static int int_ptr_type_to_size(enum bpf_arg_type type) 7981 { 7982 if (type == ARG_PTR_TO_INT) 7983 return sizeof(u32); 7984 else if (type == ARG_PTR_TO_LONG) 7985 return sizeof(u64); 7986 7987 return -EINVAL; 7988 } 7989 7990 static int resolve_map_arg_type(struct bpf_verifier_env *env, 7991 const struct bpf_call_arg_meta *meta, 7992 enum bpf_arg_type *arg_type) 7993 { 7994 if (!meta->map_ptr) { 7995 /* kernel subsystem misconfigured verifier */ 7996 verbose(env, "invalid map_ptr to access map->type\n"); 7997 return -EACCES; 7998 } 7999 8000 switch (meta->map_ptr->map_type) { 8001 case BPF_MAP_TYPE_SOCKMAP: 8002 case BPF_MAP_TYPE_SOCKHASH: 8003 if (*arg_type == ARG_PTR_TO_MAP_VALUE) { 8004 *arg_type = ARG_PTR_TO_BTF_ID_SOCK_COMMON; 8005 } else { 8006 verbose(env, "invalid arg_type for sockmap/sockhash\n"); 8007 return -EINVAL; 8008 } 8009 break; 8010 case BPF_MAP_TYPE_BLOOM_FILTER: 8011 if (meta->func_id == BPF_FUNC_map_peek_elem) 8012 *arg_type = ARG_PTR_TO_MAP_VALUE; 8013 break; 8014 default: 8015 break; 8016 } 8017 return 0; 8018 } 8019 8020 struct bpf_reg_types { 8021 const enum bpf_reg_type types[10]; 8022 u32 *btf_id; 8023 }; 8024 8025 static const struct bpf_reg_types sock_types = { 8026 .types = { 8027 PTR_TO_SOCK_COMMON, 8028 PTR_TO_SOCKET, 8029 PTR_TO_TCP_SOCK, 8030 PTR_TO_XDP_SOCK, 8031 }, 8032 }; 8033 8034 #ifdef CONFIG_NET 8035 static const struct bpf_reg_types btf_id_sock_common_types = { 8036 .types = { 8037 PTR_TO_SOCK_COMMON, 8038 PTR_TO_SOCKET, 8039 PTR_TO_TCP_SOCK, 8040 PTR_TO_XDP_SOCK, 8041 PTR_TO_BTF_ID, 8042 PTR_TO_BTF_ID | PTR_TRUSTED, 8043 }, 8044 .btf_id = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON], 8045 }; 8046 #endif 8047 8048 static const struct bpf_reg_types mem_types = { 8049 .types = { 8050 PTR_TO_STACK, 8051 PTR_TO_PACKET, 8052 PTR_TO_PACKET_META, 8053 PTR_TO_MAP_KEY, 8054 PTR_TO_MAP_VALUE, 8055 PTR_TO_MEM, 8056 PTR_TO_MEM | MEM_RINGBUF, 8057 PTR_TO_BUF, 8058 PTR_TO_BTF_ID | PTR_TRUSTED, 8059 }, 8060 }; 8061 8062 static const struct bpf_reg_types int_ptr_types = { 8063 .types = { 8064 PTR_TO_STACK, 8065 PTR_TO_PACKET, 8066 PTR_TO_PACKET_META, 8067 PTR_TO_MAP_KEY, 8068 PTR_TO_MAP_VALUE, 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 | MEM_RCU, 8095 PTR_TO_BTF_ID | MEM_PERCPU | PTR_TRUSTED, 8096 } 8097 }; 8098 static const struct bpf_reg_types func_ptr_types = { .types = { PTR_TO_FUNC } }; 8099 static const struct bpf_reg_types stack_ptr_types = { .types = { PTR_TO_STACK } }; 8100 static const struct bpf_reg_types const_str_ptr_types = { .types = { PTR_TO_MAP_VALUE } }; 8101 static const struct bpf_reg_types timer_types = { .types = { PTR_TO_MAP_VALUE } }; 8102 static const struct bpf_reg_types kptr_types = { .types = { PTR_TO_MAP_VALUE } }; 8103 static const struct bpf_reg_types dynptr_types = { 8104 .types = { 8105 PTR_TO_STACK, 8106 CONST_PTR_TO_DYNPTR, 8107 } 8108 }; 8109 8110 static const struct bpf_reg_types *compatible_reg_types[__BPF_ARG_TYPE_MAX] = { 8111 [ARG_PTR_TO_MAP_KEY] = &mem_types, 8112 [ARG_PTR_TO_MAP_VALUE] = &mem_types, 8113 [ARG_CONST_SIZE] = &scalar_types, 8114 [ARG_CONST_SIZE_OR_ZERO] = &scalar_types, 8115 [ARG_CONST_ALLOC_SIZE_OR_ZERO] = &scalar_types, 8116 [ARG_CONST_MAP_PTR] = &const_map_ptr_types, 8117 [ARG_PTR_TO_CTX] = &context_types, 8118 [ARG_PTR_TO_SOCK_COMMON] = &sock_types, 8119 #ifdef CONFIG_NET 8120 [ARG_PTR_TO_BTF_ID_SOCK_COMMON] = &btf_id_sock_common_types, 8121 #endif 8122 [ARG_PTR_TO_SOCKET] = &fullsock_types, 8123 [ARG_PTR_TO_BTF_ID] = &btf_ptr_types, 8124 [ARG_PTR_TO_SPIN_LOCK] = &spin_lock_types, 8125 [ARG_PTR_TO_MEM] = &mem_types, 8126 [ARG_PTR_TO_RINGBUF_MEM] = &ringbuf_mem_types, 8127 [ARG_PTR_TO_INT] = &int_ptr_types, 8128 [ARG_PTR_TO_LONG] = &int_ptr_types, 8129 [ARG_PTR_TO_PERCPU_BTF_ID] = &percpu_btf_ptr_types, 8130 [ARG_PTR_TO_FUNC] = &func_ptr_types, 8131 [ARG_PTR_TO_STACK] = &stack_ptr_types, 8132 [ARG_PTR_TO_CONST_STR] = &const_str_ptr_types, 8133 [ARG_PTR_TO_TIMER] = &timer_types, 8134 [ARG_PTR_TO_KPTR] = &kptr_types, 8135 [ARG_PTR_TO_DYNPTR] = &dynptr_types, 8136 }; 8137 8138 static int check_reg_type(struct bpf_verifier_env *env, u32 regno, 8139 enum bpf_arg_type arg_type, 8140 const u32 *arg_btf_id, 8141 struct bpf_call_arg_meta *meta) 8142 { 8143 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno]; 8144 enum bpf_reg_type expected, type = reg->type; 8145 const struct bpf_reg_types *compatible; 8146 int i, j; 8147 8148 compatible = compatible_reg_types[base_type(arg_type)]; 8149 if (!compatible) { 8150 verbose(env, "verifier internal error: unsupported arg type %d\n", arg_type); 8151 return -EFAULT; 8152 } 8153 8154 /* ARG_PTR_TO_MEM + RDONLY is compatible with PTR_TO_MEM and PTR_TO_MEM + RDONLY, 8155 * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM and NOT with PTR_TO_MEM + RDONLY 8156 * 8157 * Same for MAYBE_NULL: 8158 * 8159 * ARG_PTR_TO_MEM + MAYBE_NULL is compatible with PTR_TO_MEM and PTR_TO_MEM + MAYBE_NULL, 8160 * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM but NOT with PTR_TO_MEM + MAYBE_NULL 8161 * 8162 * ARG_PTR_TO_MEM is compatible with PTR_TO_MEM that is tagged with a dynptr type. 8163 * 8164 * Therefore we fold these flags depending on the arg_type before comparison. 8165 */ 8166 if (arg_type & MEM_RDONLY) 8167 type &= ~MEM_RDONLY; 8168 if (arg_type & PTR_MAYBE_NULL) 8169 type &= ~PTR_MAYBE_NULL; 8170 if (base_type(arg_type) == ARG_PTR_TO_MEM) 8171 type &= ~DYNPTR_TYPE_FLAG_MASK; 8172 8173 if (meta->func_id == BPF_FUNC_kptr_xchg && type_is_alloc(type)) { 8174 type &= ~MEM_ALLOC; 8175 type &= ~MEM_PERCPU; 8176 } 8177 8178 for (i = 0; i < ARRAY_SIZE(compatible->types); i++) { 8179 expected = compatible->types[i]; 8180 if (expected == NOT_INIT) 8181 break; 8182 8183 if (type == expected) 8184 goto found; 8185 } 8186 8187 verbose(env, "R%d type=%s expected=", regno, reg_type_str(env, reg->type)); 8188 for (j = 0; j + 1 < i; j++) 8189 verbose(env, "%s, ", reg_type_str(env, compatible->types[j])); 8190 verbose(env, "%s\n", reg_type_str(env, compatible->types[j])); 8191 return -EACCES; 8192 8193 found: 8194 if (base_type(reg->type) != PTR_TO_BTF_ID) 8195 return 0; 8196 8197 if (compatible == &mem_types) { 8198 if (!(arg_type & MEM_RDONLY)) { 8199 verbose(env, 8200 "%s() may write into memory pointed by R%d type=%s\n", 8201 func_id_name(meta->func_id), 8202 regno, reg_type_str(env, reg->type)); 8203 return -EACCES; 8204 } 8205 return 0; 8206 } 8207 8208 switch ((int)reg->type) { 8209 case PTR_TO_BTF_ID: 8210 case PTR_TO_BTF_ID | PTR_TRUSTED: 8211 case PTR_TO_BTF_ID | MEM_RCU: 8212 case PTR_TO_BTF_ID | PTR_MAYBE_NULL: 8213 case PTR_TO_BTF_ID | PTR_MAYBE_NULL | MEM_RCU: 8214 { 8215 /* For bpf_sk_release, it needs to match against first member 8216 * 'struct sock_common', hence make an exception for it. This 8217 * allows bpf_sk_release to work for multiple socket types. 8218 */ 8219 bool strict_type_match = arg_type_is_release(arg_type) && 8220 meta->func_id != BPF_FUNC_sk_release; 8221 8222 if (type_may_be_null(reg->type) && 8223 (!type_may_be_null(arg_type) || arg_type_is_release(arg_type))) { 8224 verbose(env, "Possibly NULL pointer passed to helper arg%d\n", regno); 8225 return -EACCES; 8226 } 8227 8228 if (!arg_btf_id) { 8229 if (!compatible->btf_id) { 8230 verbose(env, "verifier internal error: missing arg compatible BTF ID\n"); 8231 return -EFAULT; 8232 } 8233 arg_btf_id = compatible->btf_id; 8234 } 8235 8236 if (meta->func_id == BPF_FUNC_kptr_xchg) { 8237 if (map_kptr_match_type(env, meta->kptr_field, reg, regno)) 8238 return -EACCES; 8239 } else { 8240 if (arg_btf_id == BPF_PTR_POISON) { 8241 verbose(env, "verifier internal error:"); 8242 verbose(env, "R%d has non-overwritten BPF_PTR_POISON type\n", 8243 regno); 8244 return -EACCES; 8245 } 8246 8247 if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off, 8248 btf_vmlinux, *arg_btf_id, 8249 strict_type_match)) { 8250 verbose(env, "R%d is of type %s but %s is expected\n", 8251 regno, btf_type_name(reg->btf, reg->btf_id), 8252 btf_type_name(btf_vmlinux, *arg_btf_id)); 8253 return -EACCES; 8254 } 8255 } 8256 break; 8257 } 8258 case PTR_TO_BTF_ID | MEM_ALLOC: 8259 case PTR_TO_BTF_ID | MEM_PERCPU | MEM_ALLOC: 8260 if (meta->func_id != BPF_FUNC_spin_lock && meta->func_id != BPF_FUNC_spin_unlock && 8261 meta->func_id != BPF_FUNC_kptr_xchg) { 8262 verbose(env, "verifier internal error: unimplemented handling of MEM_ALLOC\n"); 8263 return -EFAULT; 8264 } 8265 if (meta->func_id == BPF_FUNC_kptr_xchg) { 8266 if (map_kptr_match_type(env, meta->kptr_field, reg, regno)) 8267 return -EACCES; 8268 } 8269 break; 8270 case PTR_TO_BTF_ID | MEM_PERCPU: 8271 case PTR_TO_BTF_ID | MEM_PERCPU | MEM_RCU: 8272 case PTR_TO_BTF_ID | MEM_PERCPU | PTR_TRUSTED: 8273 /* Handled by helper specific checks */ 8274 break; 8275 default: 8276 verbose(env, "verifier internal error: invalid PTR_TO_BTF_ID register for type match\n"); 8277 return -EFAULT; 8278 } 8279 return 0; 8280 } 8281 8282 static struct btf_field * 8283 reg_find_field_offset(const struct bpf_reg_state *reg, s32 off, u32 fields) 8284 { 8285 struct btf_field *field; 8286 struct btf_record *rec; 8287 8288 rec = reg_btf_record(reg); 8289 if (!rec) 8290 return NULL; 8291 8292 field = btf_record_find(rec, off, fields); 8293 if (!field) 8294 return NULL; 8295 8296 return field; 8297 } 8298 8299 int check_func_arg_reg_off(struct bpf_verifier_env *env, 8300 const struct bpf_reg_state *reg, int regno, 8301 enum bpf_arg_type arg_type) 8302 { 8303 u32 type = reg->type; 8304 8305 /* When referenced register is passed to release function, its fixed 8306 * offset must be 0. 8307 * 8308 * We will check arg_type_is_release reg has ref_obj_id when storing 8309 * meta->release_regno. 8310 */ 8311 if (arg_type_is_release(arg_type)) { 8312 /* ARG_PTR_TO_DYNPTR with OBJ_RELEASE is a bit special, as it 8313 * may not directly point to the object being released, but to 8314 * dynptr pointing to such object, which might be at some offset 8315 * on the stack. In that case, we simply to fallback to the 8316 * default handling. 8317 */ 8318 if (arg_type_is_dynptr(arg_type) && type == PTR_TO_STACK) 8319 return 0; 8320 8321 /* Doing check_ptr_off_reg check for the offset will catch this 8322 * because fixed_off_ok is false, but checking here allows us 8323 * to give the user a better error message. 8324 */ 8325 if (reg->off) { 8326 verbose(env, "R%d must have zero offset when passed to release func or trusted arg to kfunc\n", 8327 regno); 8328 return -EINVAL; 8329 } 8330 return __check_ptr_off_reg(env, reg, regno, false); 8331 } 8332 8333 switch (type) { 8334 /* Pointer types where both fixed and variable offset is explicitly allowed: */ 8335 case PTR_TO_STACK: 8336 case PTR_TO_PACKET: 8337 case PTR_TO_PACKET_META: 8338 case PTR_TO_MAP_KEY: 8339 case PTR_TO_MAP_VALUE: 8340 case PTR_TO_MEM: 8341 case PTR_TO_MEM | MEM_RDONLY: 8342 case PTR_TO_MEM | MEM_RINGBUF: 8343 case PTR_TO_BUF: 8344 case PTR_TO_BUF | MEM_RDONLY: 8345 case SCALAR_VALUE: 8346 return 0; 8347 /* All the rest must be rejected, except PTR_TO_BTF_ID which allows 8348 * fixed offset. 8349 */ 8350 case PTR_TO_BTF_ID: 8351 case PTR_TO_BTF_ID | MEM_ALLOC: 8352 case PTR_TO_BTF_ID | PTR_TRUSTED: 8353 case PTR_TO_BTF_ID | MEM_RCU: 8354 case PTR_TO_BTF_ID | MEM_ALLOC | NON_OWN_REF: 8355 case PTR_TO_BTF_ID | MEM_ALLOC | NON_OWN_REF | MEM_RCU: 8356 /* When referenced PTR_TO_BTF_ID is passed to release function, 8357 * its fixed offset must be 0. In the other cases, fixed offset 8358 * can be non-zero. This was already checked above. So pass 8359 * fixed_off_ok as true to allow fixed offset for all other 8360 * cases. var_off always must be 0 for PTR_TO_BTF_ID, hence we 8361 * still need to do checks instead of returning. 8362 */ 8363 return __check_ptr_off_reg(env, reg, regno, true); 8364 default: 8365 return __check_ptr_off_reg(env, reg, regno, false); 8366 } 8367 } 8368 8369 static struct bpf_reg_state *get_dynptr_arg_reg(struct bpf_verifier_env *env, 8370 const struct bpf_func_proto *fn, 8371 struct bpf_reg_state *regs) 8372 { 8373 struct bpf_reg_state *state = NULL; 8374 int i; 8375 8376 for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++) 8377 if (arg_type_is_dynptr(fn->arg_type[i])) { 8378 if (state) { 8379 verbose(env, "verifier internal error: multiple dynptr args\n"); 8380 return NULL; 8381 } 8382 state = ®s[BPF_REG_1 + i]; 8383 } 8384 8385 if (!state) 8386 verbose(env, "verifier internal error: no dynptr arg found\n"); 8387 8388 return state; 8389 } 8390 8391 static int dynptr_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 8392 { 8393 struct bpf_func_state *state = func(env, reg); 8394 int spi; 8395 8396 if (reg->type == CONST_PTR_TO_DYNPTR) 8397 return reg->id; 8398 spi = dynptr_get_spi(env, reg); 8399 if (spi < 0) 8400 return spi; 8401 return state->stack[spi].spilled_ptr.id; 8402 } 8403 8404 static int dynptr_ref_obj_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 8405 { 8406 struct bpf_func_state *state = func(env, reg); 8407 int spi; 8408 8409 if (reg->type == CONST_PTR_TO_DYNPTR) 8410 return reg->ref_obj_id; 8411 spi = dynptr_get_spi(env, reg); 8412 if (spi < 0) 8413 return spi; 8414 return state->stack[spi].spilled_ptr.ref_obj_id; 8415 } 8416 8417 static enum bpf_dynptr_type dynptr_get_type(struct bpf_verifier_env *env, 8418 struct bpf_reg_state *reg) 8419 { 8420 struct bpf_func_state *state = func(env, reg); 8421 int spi; 8422 8423 if (reg->type == CONST_PTR_TO_DYNPTR) 8424 return reg->dynptr.type; 8425 8426 spi = __get_spi(reg->off); 8427 if (spi < 0) { 8428 verbose(env, "verifier internal error: invalid spi when querying dynptr type\n"); 8429 return BPF_DYNPTR_TYPE_INVALID; 8430 } 8431 8432 return state->stack[spi].spilled_ptr.dynptr.type; 8433 } 8434 8435 static int check_reg_const_str(struct bpf_verifier_env *env, 8436 struct bpf_reg_state *reg, u32 regno) 8437 { 8438 struct bpf_map *map = reg->map_ptr; 8439 int err; 8440 int map_off; 8441 u64 map_addr; 8442 char *str_ptr; 8443 8444 if (reg->type != PTR_TO_MAP_VALUE) 8445 return -EINVAL; 8446 8447 if (!bpf_map_is_rdonly(map)) { 8448 verbose(env, "R%d does not point to a readonly map'\n", regno); 8449 return -EACCES; 8450 } 8451 8452 if (!tnum_is_const(reg->var_off)) { 8453 verbose(env, "R%d is not a constant address'\n", regno); 8454 return -EACCES; 8455 } 8456 8457 if (!map->ops->map_direct_value_addr) { 8458 verbose(env, "no direct value access support for this map type\n"); 8459 return -EACCES; 8460 } 8461 8462 err = check_map_access(env, regno, reg->off, 8463 map->value_size - reg->off, false, 8464 ACCESS_HELPER); 8465 if (err) 8466 return err; 8467 8468 map_off = reg->off + reg->var_off.value; 8469 err = map->ops->map_direct_value_addr(map, &map_addr, map_off); 8470 if (err) { 8471 verbose(env, "direct value access on string failed\n"); 8472 return err; 8473 } 8474 8475 str_ptr = (char *)(long)(map_addr); 8476 if (!strnchr(str_ptr + map_off, map->value_size - map_off, 0)) { 8477 verbose(env, "string is not zero-terminated\n"); 8478 return -EINVAL; 8479 } 8480 return 0; 8481 } 8482 8483 static int check_func_arg(struct bpf_verifier_env *env, u32 arg, 8484 struct bpf_call_arg_meta *meta, 8485 const struct bpf_func_proto *fn, 8486 int insn_idx) 8487 { 8488 u32 regno = BPF_REG_1 + arg; 8489 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno]; 8490 enum bpf_arg_type arg_type = fn->arg_type[arg]; 8491 enum bpf_reg_type type = reg->type; 8492 u32 *arg_btf_id = NULL; 8493 int err = 0; 8494 8495 if (arg_type == ARG_DONTCARE) 8496 return 0; 8497 8498 err = check_reg_arg(env, regno, SRC_OP); 8499 if (err) 8500 return err; 8501 8502 if (arg_type == ARG_ANYTHING) { 8503 if (is_pointer_value(env, regno)) { 8504 verbose(env, "R%d leaks addr into helper function\n", 8505 regno); 8506 return -EACCES; 8507 } 8508 return 0; 8509 } 8510 8511 if (type_is_pkt_pointer(type) && 8512 !may_access_direct_pkt_data(env, meta, BPF_READ)) { 8513 verbose(env, "helper access to the packet is not allowed\n"); 8514 return -EACCES; 8515 } 8516 8517 if (base_type(arg_type) == ARG_PTR_TO_MAP_VALUE) { 8518 err = resolve_map_arg_type(env, meta, &arg_type); 8519 if (err) 8520 return err; 8521 } 8522 8523 if (register_is_null(reg) && type_may_be_null(arg_type)) 8524 /* A NULL register has a SCALAR_VALUE type, so skip 8525 * type checking. 8526 */ 8527 goto skip_type_check; 8528 8529 /* arg_btf_id and arg_size are in a union. */ 8530 if (base_type(arg_type) == ARG_PTR_TO_BTF_ID || 8531 base_type(arg_type) == ARG_PTR_TO_SPIN_LOCK) 8532 arg_btf_id = fn->arg_btf_id[arg]; 8533 8534 err = check_reg_type(env, regno, arg_type, arg_btf_id, meta); 8535 if (err) 8536 return err; 8537 8538 err = check_func_arg_reg_off(env, reg, regno, arg_type); 8539 if (err) 8540 return err; 8541 8542 skip_type_check: 8543 if (arg_type_is_release(arg_type)) { 8544 if (arg_type_is_dynptr(arg_type)) { 8545 struct bpf_func_state *state = func(env, reg); 8546 int spi; 8547 8548 /* Only dynptr created on stack can be released, thus 8549 * the get_spi and stack state checks for spilled_ptr 8550 * should only be done before process_dynptr_func for 8551 * PTR_TO_STACK. 8552 */ 8553 if (reg->type == PTR_TO_STACK) { 8554 spi = dynptr_get_spi(env, reg); 8555 if (spi < 0 || !state->stack[spi].spilled_ptr.ref_obj_id) { 8556 verbose(env, "arg %d is an unacquired reference\n", regno); 8557 return -EINVAL; 8558 } 8559 } else { 8560 verbose(env, "cannot release unowned const bpf_dynptr\n"); 8561 return -EINVAL; 8562 } 8563 } else if (!reg->ref_obj_id && !register_is_null(reg)) { 8564 verbose(env, "R%d must be referenced when passed to release function\n", 8565 regno); 8566 return -EINVAL; 8567 } 8568 if (meta->release_regno) { 8569 verbose(env, "verifier internal error: more than one release argument\n"); 8570 return -EFAULT; 8571 } 8572 meta->release_regno = regno; 8573 } 8574 8575 if (reg->ref_obj_id) { 8576 if (meta->ref_obj_id) { 8577 verbose(env, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n", 8578 regno, reg->ref_obj_id, 8579 meta->ref_obj_id); 8580 return -EFAULT; 8581 } 8582 meta->ref_obj_id = reg->ref_obj_id; 8583 } 8584 8585 switch (base_type(arg_type)) { 8586 case ARG_CONST_MAP_PTR: 8587 /* bpf_map_xxx(map_ptr) call: remember that map_ptr */ 8588 if (meta->map_ptr) { 8589 /* Use map_uid (which is unique id of inner map) to reject: 8590 * inner_map1 = bpf_map_lookup_elem(outer_map, key1) 8591 * inner_map2 = bpf_map_lookup_elem(outer_map, key2) 8592 * if (inner_map1 && inner_map2) { 8593 * timer = bpf_map_lookup_elem(inner_map1); 8594 * if (timer) 8595 * // mismatch would have been allowed 8596 * bpf_timer_init(timer, inner_map2); 8597 * } 8598 * 8599 * Comparing map_ptr is enough to distinguish normal and outer maps. 8600 */ 8601 if (meta->map_ptr != reg->map_ptr || 8602 meta->map_uid != reg->map_uid) { 8603 verbose(env, 8604 "timer pointer in R1 map_uid=%d doesn't match map pointer in R2 map_uid=%d\n", 8605 meta->map_uid, reg->map_uid); 8606 return -EINVAL; 8607 } 8608 } 8609 meta->map_ptr = reg->map_ptr; 8610 meta->map_uid = reg->map_uid; 8611 break; 8612 case ARG_PTR_TO_MAP_KEY: 8613 /* bpf_map_xxx(..., map_ptr, ..., key) call: 8614 * check that [key, key + map->key_size) are within 8615 * stack limits and initialized 8616 */ 8617 if (!meta->map_ptr) { 8618 /* in function declaration map_ptr must come before 8619 * map_key, so that it's verified and known before 8620 * we have to check map_key here. Otherwise it means 8621 * that kernel subsystem misconfigured verifier 8622 */ 8623 verbose(env, "invalid map_ptr to access map->key\n"); 8624 return -EACCES; 8625 } 8626 err = check_helper_mem_access(env, regno, 8627 meta->map_ptr->key_size, false, 8628 NULL); 8629 break; 8630 case ARG_PTR_TO_MAP_VALUE: 8631 if (type_may_be_null(arg_type) && register_is_null(reg)) 8632 return 0; 8633 8634 /* bpf_map_xxx(..., map_ptr, ..., value) call: 8635 * check [value, value + map->value_size) validity 8636 */ 8637 if (!meta->map_ptr) { 8638 /* kernel subsystem misconfigured verifier */ 8639 verbose(env, "invalid map_ptr to access map->value\n"); 8640 return -EACCES; 8641 } 8642 meta->raw_mode = arg_type & MEM_UNINIT; 8643 err = check_helper_mem_access(env, regno, 8644 meta->map_ptr->value_size, false, 8645 meta); 8646 break; 8647 case ARG_PTR_TO_PERCPU_BTF_ID: 8648 if (!reg->btf_id) { 8649 verbose(env, "Helper has invalid btf_id in R%d\n", regno); 8650 return -EACCES; 8651 } 8652 meta->ret_btf = reg->btf; 8653 meta->ret_btf_id = reg->btf_id; 8654 break; 8655 case ARG_PTR_TO_SPIN_LOCK: 8656 if (in_rbtree_lock_required_cb(env)) { 8657 verbose(env, "can't spin_{lock,unlock} in rbtree cb\n"); 8658 return -EACCES; 8659 } 8660 if (meta->func_id == BPF_FUNC_spin_lock) { 8661 err = process_spin_lock(env, regno, true); 8662 if (err) 8663 return err; 8664 } else if (meta->func_id == BPF_FUNC_spin_unlock) { 8665 err = process_spin_lock(env, regno, false); 8666 if (err) 8667 return err; 8668 } else { 8669 verbose(env, "verifier internal error\n"); 8670 return -EFAULT; 8671 } 8672 break; 8673 case ARG_PTR_TO_TIMER: 8674 err = process_timer_func(env, regno, meta); 8675 if (err) 8676 return err; 8677 break; 8678 case ARG_PTR_TO_FUNC: 8679 meta->subprogno = reg->subprogno; 8680 break; 8681 case ARG_PTR_TO_MEM: 8682 /* The access to this pointer is only checked when we hit the 8683 * next is_mem_size argument below. 8684 */ 8685 meta->raw_mode = arg_type & MEM_UNINIT; 8686 if (arg_type & MEM_FIXED_SIZE) { 8687 err = check_helper_mem_access(env, regno, 8688 fn->arg_size[arg], false, 8689 meta); 8690 } 8691 break; 8692 case ARG_CONST_SIZE: 8693 err = check_mem_size_reg(env, reg, regno, false, meta); 8694 break; 8695 case ARG_CONST_SIZE_OR_ZERO: 8696 err = check_mem_size_reg(env, reg, regno, true, meta); 8697 break; 8698 case ARG_PTR_TO_DYNPTR: 8699 err = process_dynptr_func(env, regno, insn_idx, arg_type, 0); 8700 if (err) 8701 return err; 8702 break; 8703 case ARG_CONST_ALLOC_SIZE_OR_ZERO: 8704 if (!tnum_is_const(reg->var_off)) { 8705 verbose(env, "R%d is not a known constant'\n", 8706 regno); 8707 return -EACCES; 8708 } 8709 meta->mem_size = reg->var_off.value; 8710 err = mark_chain_precision(env, regno); 8711 if (err) 8712 return err; 8713 break; 8714 case ARG_PTR_TO_INT: 8715 case ARG_PTR_TO_LONG: 8716 { 8717 int size = int_ptr_type_to_size(arg_type); 8718 8719 err = check_helper_mem_access(env, regno, size, false, meta); 8720 if (err) 8721 return err; 8722 err = check_ptr_alignment(env, reg, 0, size, true); 8723 break; 8724 } 8725 case ARG_PTR_TO_CONST_STR: 8726 { 8727 err = check_reg_const_str(env, reg, regno); 8728 if (err) 8729 return err; 8730 break; 8731 } 8732 case ARG_PTR_TO_KPTR: 8733 err = process_kptr_func(env, regno, meta); 8734 if (err) 8735 return err; 8736 break; 8737 } 8738 8739 return err; 8740 } 8741 8742 static bool may_update_sockmap(struct bpf_verifier_env *env, int func_id) 8743 { 8744 enum bpf_attach_type eatype = env->prog->expected_attach_type; 8745 enum bpf_prog_type type = resolve_prog_type(env->prog); 8746 8747 if (func_id != BPF_FUNC_map_update_elem) 8748 return false; 8749 8750 /* It's not possible to get access to a locked struct sock in these 8751 * contexts, so updating is safe. 8752 */ 8753 switch (type) { 8754 case BPF_PROG_TYPE_TRACING: 8755 if (eatype == BPF_TRACE_ITER) 8756 return true; 8757 break; 8758 case BPF_PROG_TYPE_SOCKET_FILTER: 8759 case BPF_PROG_TYPE_SCHED_CLS: 8760 case BPF_PROG_TYPE_SCHED_ACT: 8761 case BPF_PROG_TYPE_XDP: 8762 case BPF_PROG_TYPE_SK_REUSEPORT: 8763 case BPF_PROG_TYPE_FLOW_DISSECTOR: 8764 case BPF_PROG_TYPE_SK_LOOKUP: 8765 return true; 8766 default: 8767 break; 8768 } 8769 8770 verbose(env, "cannot update sockmap in this context\n"); 8771 return false; 8772 } 8773 8774 static bool allow_tail_call_in_subprogs(struct bpf_verifier_env *env) 8775 { 8776 return env->prog->jit_requested && 8777 bpf_jit_supports_subprog_tailcalls(); 8778 } 8779 8780 static int check_map_func_compatibility(struct bpf_verifier_env *env, 8781 struct bpf_map *map, int func_id) 8782 { 8783 if (!map) 8784 return 0; 8785 8786 /* We need a two way check, first is from map perspective ... */ 8787 switch (map->map_type) { 8788 case BPF_MAP_TYPE_PROG_ARRAY: 8789 if (func_id != BPF_FUNC_tail_call) 8790 goto error; 8791 break; 8792 case BPF_MAP_TYPE_PERF_EVENT_ARRAY: 8793 if (func_id != BPF_FUNC_perf_event_read && 8794 func_id != BPF_FUNC_perf_event_output && 8795 func_id != BPF_FUNC_skb_output && 8796 func_id != BPF_FUNC_perf_event_read_value && 8797 func_id != BPF_FUNC_xdp_output) 8798 goto error; 8799 break; 8800 case BPF_MAP_TYPE_RINGBUF: 8801 if (func_id != BPF_FUNC_ringbuf_output && 8802 func_id != BPF_FUNC_ringbuf_reserve && 8803 func_id != BPF_FUNC_ringbuf_query && 8804 func_id != BPF_FUNC_ringbuf_reserve_dynptr && 8805 func_id != BPF_FUNC_ringbuf_submit_dynptr && 8806 func_id != BPF_FUNC_ringbuf_discard_dynptr) 8807 goto error; 8808 break; 8809 case BPF_MAP_TYPE_USER_RINGBUF: 8810 if (func_id != BPF_FUNC_user_ringbuf_drain) 8811 goto error; 8812 break; 8813 case BPF_MAP_TYPE_STACK_TRACE: 8814 if (func_id != BPF_FUNC_get_stackid) 8815 goto error; 8816 break; 8817 case BPF_MAP_TYPE_CGROUP_ARRAY: 8818 if (func_id != BPF_FUNC_skb_under_cgroup && 8819 func_id != BPF_FUNC_current_task_under_cgroup) 8820 goto error; 8821 break; 8822 case BPF_MAP_TYPE_CGROUP_STORAGE: 8823 case BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE: 8824 if (func_id != BPF_FUNC_get_local_storage) 8825 goto error; 8826 break; 8827 case BPF_MAP_TYPE_DEVMAP: 8828 case BPF_MAP_TYPE_DEVMAP_HASH: 8829 if (func_id != BPF_FUNC_redirect_map && 8830 func_id != BPF_FUNC_map_lookup_elem) 8831 goto error; 8832 break; 8833 /* Restrict bpf side of cpumap and xskmap, open when use-cases 8834 * appear. 8835 */ 8836 case BPF_MAP_TYPE_CPUMAP: 8837 if (func_id != BPF_FUNC_redirect_map) 8838 goto error; 8839 break; 8840 case BPF_MAP_TYPE_XSKMAP: 8841 if (func_id != BPF_FUNC_redirect_map && 8842 func_id != BPF_FUNC_map_lookup_elem) 8843 goto error; 8844 break; 8845 case BPF_MAP_TYPE_ARRAY_OF_MAPS: 8846 case BPF_MAP_TYPE_HASH_OF_MAPS: 8847 if (func_id != BPF_FUNC_map_lookup_elem) 8848 goto error; 8849 break; 8850 case BPF_MAP_TYPE_SOCKMAP: 8851 if (func_id != BPF_FUNC_sk_redirect_map && 8852 func_id != BPF_FUNC_sock_map_update && 8853 func_id != BPF_FUNC_map_delete_elem && 8854 func_id != BPF_FUNC_msg_redirect_map && 8855 func_id != BPF_FUNC_sk_select_reuseport && 8856 func_id != BPF_FUNC_map_lookup_elem && 8857 !may_update_sockmap(env, func_id)) 8858 goto error; 8859 break; 8860 case BPF_MAP_TYPE_SOCKHASH: 8861 if (func_id != BPF_FUNC_sk_redirect_hash && 8862 func_id != BPF_FUNC_sock_hash_update && 8863 func_id != BPF_FUNC_map_delete_elem && 8864 func_id != BPF_FUNC_msg_redirect_hash && 8865 func_id != BPF_FUNC_sk_select_reuseport && 8866 func_id != BPF_FUNC_map_lookup_elem && 8867 !may_update_sockmap(env, func_id)) 8868 goto error; 8869 break; 8870 case BPF_MAP_TYPE_REUSEPORT_SOCKARRAY: 8871 if (func_id != BPF_FUNC_sk_select_reuseport) 8872 goto error; 8873 break; 8874 case BPF_MAP_TYPE_QUEUE: 8875 case BPF_MAP_TYPE_STACK: 8876 if (func_id != BPF_FUNC_map_peek_elem && 8877 func_id != BPF_FUNC_map_pop_elem && 8878 func_id != BPF_FUNC_map_push_elem) 8879 goto error; 8880 break; 8881 case BPF_MAP_TYPE_SK_STORAGE: 8882 if (func_id != BPF_FUNC_sk_storage_get && 8883 func_id != BPF_FUNC_sk_storage_delete && 8884 func_id != BPF_FUNC_kptr_xchg) 8885 goto error; 8886 break; 8887 case BPF_MAP_TYPE_INODE_STORAGE: 8888 if (func_id != BPF_FUNC_inode_storage_get && 8889 func_id != BPF_FUNC_inode_storage_delete && 8890 func_id != BPF_FUNC_kptr_xchg) 8891 goto error; 8892 break; 8893 case BPF_MAP_TYPE_TASK_STORAGE: 8894 if (func_id != BPF_FUNC_task_storage_get && 8895 func_id != BPF_FUNC_task_storage_delete && 8896 func_id != BPF_FUNC_kptr_xchg) 8897 goto error; 8898 break; 8899 case BPF_MAP_TYPE_CGRP_STORAGE: 8900 if (func_id != BPF_FUNC_cgrp_storage_get && 8901 func_id != BPF_FUNC_cgrp_storage_delete && 8902 func_id != BPF_FUNC_kptr_xchg) 8903 goto error; 8904 break; 8905 case BPF_MAP_TYPE_BLOOM_FILTER: 8906 if (func_id != BPF_FUNC_map_peek_elem && 8907 func_id != BPF_FUNC_map_push_elem) 8908 goto error; 8909 break; 8910 default: 8911 break; 8912 } 8913 8914 /* ... and second from the function itself. */ 8915 switch (func_id) { 8916 case BPF_FUNC_tail_call: 8917 if (map->map_type != BPF_MAP_TYPE_PROG_ARRAY) 8918 goto error; 8919 if (env->subprog_cnt > 1 && !allow_tail_call_in_subprogs(env)) { 8920 verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n"); 8921 return -EINVAL; 8922 } 8923 break; 8924 case BPF_FUNC_perf_event_read: 8925 case BPF_FUNC_perf_event_output: 8926 case BPF_FUNC_perf_event_read_value: 8927 case BPF_FUNC_skb_output: 8928 case BPF_FUNC_xdp_output: 8929 if (map->map_type != BPF_MAP_TYPE_PERF_EVENT_ARRAY) 8930 goto error; 8931 break; 8932 case BPF_FUNC_ringbuf_output: 8933 case BPF_FUNC_ringbuf_reserve: 8934 case BPF_FUNC_ringbuf_query: 8935 case BPF_FUNC_ringbuf_reserve_dynptr: 8936 case BPF_FUNC_ringbuf_submit_dynptr: 8937 case BPF_FUNC_ringbuf_discard_dynptr: 8938 if (map->map_type != BPF_MAP_TYPE_RINGBUF) 8939 goto error; 8940 break; 8941 case BPF_FUNC_user_ringbuf_drain: 8942 if (map->map_type != BPF_MAP_TYPE_USER_RINGBUF) 8943 goto error; 8944 break; 8945 case BPF_FUNC_get_stackid: 8946 if (map->map_type != BPF_MAP_TYPE_STACK_TRACE) 8947 goto error; 8948 break; 8949 case BPF_FUNC_current_task_under_cgroup: 8950 case BPF_FUNC_skb_under_cgroup: 8951 if (map->map_type != BPF_MAP_TYPE_CGROUP_ARRAY) 8952 goto error; 8953 break; 8954 case BPF_FUNC_redirect_map: 8955 if (map->map_type != BPF_MAP_TYPE_DEVMAP && 8956 map->map_type != BPF_MAP_TYPE_DEVMAP_HASH && 8957 map->map_type != BPF_MAP_TYPE_CPUMAP && 8958 map->map_type != BPF_MAP_TYPE_XSKMAP) 8959 goto error; 8960 break; 8961 case BPF_FUNC_sk_redirect_map: 8962 case BPF_FUNC_msg_redirect_map: 8963 case BPF_FUNC_sock_map_update: 8964 if (map->map_type != BPF_MAP_TYPE_SOCKMAP) 8965 goto error; 8966 break; 8967 case BPF_FUNC_sk_redirect_hash: 8968 case BPF_FUNC_msg_redirect_hash: 8969 case BPF_FUNC_sock_hash_update: 8970 if (map->map_type != BPF_MAP_TYPE_SOCKHASH) 8971 goto error; 8972 break; 8973 case BPF_FUNC_get_local_storage: 8974 if (map->map_type != BPF_MAP_TYPE_CGROUP_STORAGE && 8975 map->map_type != BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE) 8976 goto error; 8977 break; 8978 case BPF_FUNC_sk_select_reuseport: 8979 if (map->map_type != BPF_MAP_TYPE_REUSEPORT_SOCKARRAY && 8980 map->map_type != BPF_MAP_TYPE_SOCKMAP && 8981 map->map_type != BPF_MAP_TYPE_SOCKHASH) 8982 goto error; 8983 break; 8984 case BPF_FUNC_map_pop_elem: 8985 if (map->map_type != BPF_MAP_TYPE_QUEUE && 8986 map->map_type != BPF_MAP_TYPE_STACK) 8987 goto error; 8988 break; 8989 case BPF_FUNC_map_peek_elem: 8990 case BPF_FUNC_map_push_elem: 8991 if (map->map_type != BPF_MAP_TYPE_QUEUE && 8992 map->map_type != BPF_MAP_TYPE_STACK && 8993 map->map_type != BPF_MAP_TYPE_BLOOM_FILTER) 8994 goto error; 8995 break; 8996 case BPF_FUNC_map_lookup_percpu_elem: 8997 if (map->map_type != BPF_MAP_TYPE_PERCPU_ARRAY && 8998 map->map_type != BPF_MAP_TYPE_PERCPU_HASH && 8999 map->map_type != BPF_MAP_TYPE_LRU_PERCPU_HASH) 9000 goto error; 9001 break; 9002 case BPF_FUNC_sk_storage_get: 9003 case BPF_FUNC_sk_storage_delete: 9004 if (map->map_type != BPF_MAP_TYPE_SK_STORAGE) 9005 goto error; 9006 break; 9007 case BPF_FUNC_inode_storage_get: 9008 case BPF_FUNC_inode_storage_delete: 9009 if (map->map_type != BPF_MAP_TYPE_INODE_STORAGE) 9010 goto error; 9011 break; 9012 case BPF_FUNC_task_storage_get: 9013 case BPF_FUNC_task_storage_delete: 9014 if (map->map_type != BPF_MAP_TYPE_TASK_STORAGE) 9015 goto error; 9016 break; 9017 case BPF_FUNC_cgrp_storage_get: 9018 case BPF_FUNC_cgrp_storage_delete: 9019 if (map->map_type != BPF_MAP_TYPE_CGRP_STORAGE) 9020 goto error; 9021 break; 9022 default: 9023 break; 9024 } 9025 9026 return 0; 9027 error: 9028 verbose(env, "cannot pass map_type %d into func %s#%d\n", 9029 map->map_type, func_id_name(func_id), func_id); 9030 return -EINVAL; 9031 } 9032 9033 static bool check_raw_mode_ok(const struct bpf_func_proto *fn) 9034 { 9035 int count = 0; 9036 9037 if (fn->arg1_type == ARG_PTR_TO_UNINIT_MEM) 9038 count++; 9039 if (fn->arg2_type == ARG_PTR_TO_UNINIT_MEM) 9040 count++; 9041 if (fn->arg3_type == ARG_PTR_TO_UNINIT_MEM) 9042 count++; 9043 if (fn->arg4_type == ARG_PTR_TO_UNINIT_MEM) 9044 count++; 9045 if (fn->arg5_type == ARG_PTR_TO_UNINIT_MEM) 9046 count++; 9047 9048 /* We only support one arg being in raw mode at the moment, 9049 * which is sufficient for the helper functions we have 9050 * right now. 9051 */ 9052 return count <= 1; 9053 } 9054 9055 static bool check_args_pair_invalid(const struct bpf_func_proto *fn, int arg) 9056 { 9057 bool is_fixed = fn->arg_type[arg] & MEM_FIXED_SIZE; 9058 bool has_size = fn->arg_size[arg] != 0; 9059 bool is_next_size = false; 9060 9061 if (arg + 1 < ARRAY_SIZE(fn->arg_type)) 9062 is_next_size = arg_type_is_mem_size(fn->arg_type[arg + 1]); 9063 9064 if (base_type(fn->arg_type[arg]) != ARG_PTR_TO_MEM) 9065 return is_next_size; 9066 9067 return has_size == is_next_size || is_next_size == is_fixed; 9068 } 9069 9070 static bool check_arg_pair_ok(const struct bpf_func_proto *fn) 9071 { 9072 /* bpf_xxx(..., buf, len) call will access 'len' 9073 * bytes from memory 'buf'. Both arg types need 9074 * to be paired, so make sure there's no buggy 9075 * helper function specification. 9076 */ 9077 if (arg_type_is_mem_size(fn->arg1_type) || 9078 check_args_pair_invalid(fn, 0) || 9079 check_args_pair_invalid(fn, 1) || 9080 check_args_pair_invalid(fn, 2) || 9081 check_args_pair_invalid(fn, 3) || 9082 check_args_pair_invalid(fn, 4)) 9083 return false; 9084 9085 return true; 9086 } 9087 9088 static bool check_btf_id_ok(const struct bpf_func_proto *fn) 9089 { 9090 int i; 9091 9092 for (i = 0; i < ARRAY_SIZE(fn->arg_type); i++) { 9093 if (base_type(fn->arg_type[i]) == ARG_PTR_TO_BTF_ID) 9094 return !!fn->arg_btf_id[i]; 9095 if (base_type(fn->arg_type[i]) == ARG_PTR_TO_SPIN_LOCK) 9096 return fn->arg_btf_id[i] == BPF_PTR_POISON; 9097 if (base_type(fn->arg_type[i]) != ARG_PTR_TO_BTF_ID && fn->arg_btf_id[i] && 9098 /* arg_btf_id and arg_size are in a union. */ 9099 (base_type(fn->arg_type[i]) != ARG_PTR_TO_MEM || 9100 !(fn->arg_type[i] & MEM_FIXED_SIZE))) 9101 return false; 9102 } 9103 9104 return true; 9105 } 9106 9107 static int check_func_proto(const struct bpf_func_proto *fn, int func_id) 9108 { 9109 return check_raw_mode_ok(fn) && 9110 check_arg_pair_ok(fn) && 9111 check_btf_id_ok(fn) ? 0 : -EINVAL; 9112 } 9113 9114 /* Packet data might have moved, any old PTR_TO_PACKET[_META,_END] 9115 * are now invalid, so turn them into unknown SCALAR_VALUE. 9116 * 9117 * This also applies to dynptr slices belonging to skb and xdp dynptrs, 9118 * since these slices point to packet data. 9119 */ 9120 static void clear_all_pkt_pointers(struct bpf_verifier_env *env) 9121 { 9122 struct bpf_func_state *state; 9123 struct bpf_reg_state *reg; 9124 9125 bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({ 9126 if (reg_is_pkt_pointer_any(reg) || reg_is_dynptr_slice_pkt(reg)) 9127 mark_reg_invalid(env, reg); 9128 })); 9129 } 9130 9131 enum { 9132 AT_PKT_END = -1, 9133 BEYOND_PKT_END = -2, 9134 }; 9135 9136 static void mark_pkt_end(struct bpf_verifier_state *vstate, int regn, bool range_open) 9137 { 9138 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 9139 struct bpf_reg_state *reg = &state->regs[regn]; 9140 9141 if (reg->type != PTR_TO_PACKET) 9142 /* PTR_TO_PACKET_META is not supported yet */ 9143 return; 9144 9145 /* The 'reg' is pkt > pkt_end or pkt >= pkt_end. 9146 * How far beyond pkt_end it goes is unknown. 9147 * if (!range_open) it's the case of pkt >= pkt_end 9148 * if (range_open) it's the case of pkt > pkt_end 9149 * hence this pointer is at least 1 byte bigger than pkt_end 9150 */ 9151 if (range_open) 9152 reg->range = BEYOND_PKT_END; 9153 else 9154 reg->range = AT_PKT_END; 9155 } 9156 9157 /* The pointer with the specified id has released its reference to kernel 9158 * resources. Identify all copies of the same pointer and clear the reference. 9159 */ 9160 static int release_reference(struct bpf_verifier_env *env, 9161 int ref_obj_id) 9162 { 9163 struct bpf_func_state *state; 9164 struct bpf_reg_state *reg; 9165 int err; 9166 9167 err = release_reference_state(cur_func(env), ref_obj_id); 9168 if (err) 9169 return err; 9170 9171 bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({ 9172 if (reg->ref_obj_id == ref_obj_id) 9173 mark_reg_invalid(env, reg); 9174 })); 9175 9176 return 0; 9177 } 9178 9179 static void invalidate_non_owning_refs(struct bpf_verifier_env *env) 9180 { 9181 struct bpf_func_state *unused; 9182 struct bpf_reg_state *reg; 9183 9184 bpf_for_each_reg_in_vstate(env->cur_state, unused, reg, ({ 9185 if (type_is_non_owning_ref(reg->type)) 9186 mark_reg_invalid(env, reg); 9187 })); 9188 } 9189 9190 static void clear_caller_saved_regs(struct bpf_verifier_env *env, 9191 struct bpf_reg_state *regs) 9192 { 9193 int i; 9194 9195 /* after the call registers r0 - r5 were scratched */ 9196 for (i = 0; i < CALLER_SAVED_REGS; i++) { 9197 mark_reg_not_init(env, regs, caller_saved[i]); 9198 __check_reg_arg(env, regs, caller_saved[i], DST_OP_NO_MARK); 9199 } 9200 } 9201 9202 typedef int (*set_callee_state_fn)(struct bpf_verifier_env *env, 9203 struct bpf_func_state *caller, 9204 struct bpf_func_state *callee, 9205 int insn_idx); 9206 9207 static int set_callee_state(struct bpf_verifier_env *env, 9208 struct bpf_func_state *caller, 9209 struct bpf_func_state *callee, int insn_idx); 9210 9211 static int setup_func_entry(struct bpf_verifier_env *env, int subprog, int callsite, 9212 set_callee_state_fn set_callee_state_cb, 9213 struct bpf_verifier_state *state) 9214 { 9215 struct bpf_func_state *caller, *callee; 9216 int err; 9217 9218 if (state->curframe + 1 >= MAX_CALL_FRAMES) { 9219 verbose(env, "the call stack of %d frames is too deep\n", 9220 state->curframe + 2); 9221 return -E2BIG; 9222 } 9223 9224 if (state->frame[state->curframe + 1]) { 9225 verbose(env, "verifier bug. Frame %d already allocated\n", 9226 state->curframe + 1); 9227 return -EFAULT; 9228 } 9229 9230 caller = state->frame[state->curframe]; 9231 callee = kzalloc(sizeof(*callee), GFP_KERNEL); 9232 if (!callee) 9233 return -ENOMEM; 9234 state->frame[state->curframe + 1] = callee; 9235 9236 /* callee cannot access r0, r6 - r9 for reading and has to write 9237 * into its own stack before reading from it. 9238 * callee can read/write into caller's stack 9239 */ 9240 init_func_state(env, callee, 9241 /* remember the callsite, it will be used by bpf_exit */ 9242 callsite, 9243 state->curframe + 1 /* frameno within this callchain */, 9244 subprog /* subprog number within this prog */); 9245 /* Transfer references to the callee */ 9246 err = copy_reference_state(callee, caller); 9247 err = err ?: set_callee_state_cb(env, caller, callee, callsite); 9248 if (err) 9249 goto err_out; 9250 9251 /* only increment it after check_reg_arg() finished */ 9252 state->curframe++; 9253 9254 return 0; 9255 9256 err_out: 9257 free_func_state(callee); 9258 state->frame[state->curframe + 1] = NULL; 9259 return err; 9260 } 9261 9262 static int push_callback_call(struct bpf_verifier_env *env, struct bpf_insn *insn, 9263 int insn_idx, int subprog, 9264 set_callee_state_fn set_callee_state_cb) 9265 { 9266 struct bpf_verifier_state *state = env->cur_state, *callback_state; 9267 struct bpf_func_state *caller, *callee; 9268 int err; 9269 9270 caller = state->frame[state->curframe]; 9271 err = btf_check_subprog_call(env, subprog, caller->regs); 9272 if (err == -EFAULT) 9273 return err; 9274 9275 /* set_callee_state is used for direct subprog calls, but we are 9276 * interested in validating only BPF helpers that can call subprogs as 9277 * callbacks 9278 */ 9279 env->subprog_info[subprog].is_cb = true; 9280 if (bpf_pseudo_kfunc_call(insn) && 9281 !is_sync_callback_calling_kfunc(insn->imm)) { 9282 verbose(env, "verifier bug: kfunc %s#%d not marked as callback-calling\n", 9283 func_id_name(insn->imm), insn->imm); 9284 return -EFAULT; 9285 } else if (!bpf_pseudo_kfunc_call(insn) && 9286 !is_callback_calling_function(insn->imm)) { /* helper */ 9287 verbose(env, "verifier bug: helper %s#%d not marked as callback-calling\n", 9288 func_id_name(insn->imm), insn->imm); 9289 return -EFAULT; 9290 } 9291 9292 if (insn->code == (BPF_JMP | BPF_CALL) && 9293 insn->src_reg == 0 && 9294 insn->imm == BPF_FUNC_timer_set_callback) { 9295 struct bpf_verifier_state *async_cb; 9296 9297 /* there is no real recursion here. timer callbacks are async */ 9298 env->subprog_info[subprog].is_async_cb = true; 9299 async_cb = push_async_cb(env, env->subprog_info[subprog].start, 9300 insn_idx, subprog); 9301 if (!async_cb) 9302 return -EFAULT; 9303 callee = async_cb->frame[0]; 9304 callee->async_entry_cnt = caller->async_entry_cnt + 1; 9305 9306 /* Convert bpf_timer_set_callback() args into timer callback args */ 9307 err = set_callee_state_cb(env, caller, callee, insn_idx); 9308 if (err) 9309 return err; 9310 9311 return 0; 9312 } 9313 9314 /* for callback functions enqueue entry to callback and 9315 * proceed with next instruction within current frame. 9316 */ 9317 callback_state = push_stack(env, env->subprog_info[subprog].start, insn_idx, false); 9318 if (!callback_state) 9319 return -ENOMEM; 9320 9321 err = setup_func_entry(env, subprog, insn_idx, set_callee_state_cb, 9322 callback_state); 9323 if (err) 9324 return err; 9325 9326 callback_state->callback_unroll_depth++; 9327 callback_state->frame[callback_state->curframe - 1]->callback_depth++; 9328 caller->callback_depth = 0; 9329 return 0; 9330 } 9331 9332 static int check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn, 9333 int *insn_idx) 9334 { 9335 struct bpf_verifier_state *state = env->cur_state; 9336 struct bpf_func_state *caller; 9337 int err, subprog, target_insn; 9338 9339 target_insn = *insn_idx + insn->imm + 1; 9340 subprog = find_subprog(env, target_insn); 9341 if (subprog < 0) { 9342 verbose(env, "verifier bug. No program starts at insn %d\n", target_insn); 9343 return -EFAULT; 9344 } 9345 9346 caller = state->frame[state->curframe]; 9347 err = btf_check_subprog_call(env, subprog, caller->regs); 9348 if (err == -EFAULT) 9349 return err; 9350 if (subprog_is_global(env, subprog)) { 9351 const char *sub_name = subprog_name(env, subprog); 9352 9353 if (err) { 9354 verbose(env, "Caller passes invalid args into func#%d ('%s')\n", 9355 subprog, sub_name); 9356 return err; 9357 } 9358 9359 verbose(env, "Func#%d ('%s') is global and assumed valid.\n", 9360 subprog, sub_name); 9361 /* mark global subprog for verifying after main prog */ 9362 subprog_aux(env, subprog)->called = true; 9363 clear_caller_saved_regs(env, caller->regs); 9364 9365 /* All global functions return a 64-bit SCALAR_VALUE */ 9366 mark_reg_unknown(env, caller->regs, BPF_REG_0); 9367 caller->regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG; 9368 9369 /* continue with next insn after call */ 9370 return 0; 9371 } 9372 9373 /* for regular function entry setup new frame and continue 9374 * from that frame. 9375 */ 9376 err = setup_func_entry(env, subprog, *insn_idx, set_callee_state, state); 9377 if (err) 9378 return err; 9379 9380 clear_caller_saved_regs(env, caller->regs); 9381 9382 /* and go analyze first insn of the callee */ 9383 *insn_idx = env->subprog_info[subprog].start - 1; 9384 9385 if (env->log.level & BPF_LOG_LEVEL) { 9386 verbose(env, "caller:\n"); 9387 print_verifier_state(env, caller, true); 9388 verbose(env, "callee:\n"); 9389 print_verifier_state(env, state->frame[state->curframe], true); 9390 } 9391 9392 return 0; 9393 } 9394 9395 int map_set_for_each_callback_args(struct bpf_verifier_env *env, 9396 struct bpf_func_state *caller, 9397 struct bpf_func_state *callee) 9398 { 9399 /* bpf_for_each_map_elem(struct bpf_map *map, void *callback_fn, 9400 * void *callback_ctx, u64 flags); 9401 * callback_fn(struct bpf_map *map, void *key, void *value, 9402 * void *callback_ctx); 9403 */ 9404 callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1]; 9405 9406 callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY; 9407 __mark_reg_known_zero(&callee->regs[BPF_REG_2]); 9408 callee->regs[BPF_REG_2].map_ptr = caller->regs[BPF_REG_1].map_ptr; 9409 9410 callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE; 9411 __mark_reg_known_zero(&callee->regs[BPF_REG_3]); 9412 callee->regs[BPF_REG_3].map_ptr = caller->regs[BPF_REG_1].map_ptr; 9413 9414 /* pointer to stack or null */ 9415 callee->regs[BPF_REG_4] = caller->regs[BPF_REG_3]; 9416 9417 /* unused */ 9418 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]); 9419 return 0; 9420 } 9421 9422 static int set_callee_state(struct bpf_verifier_env *env, 9423 struct bpf_func_state *caller, 9424 struct bpf_func_state *callee, int insn_idx) 9425 { 9426 int i; 9427 9428 /* copy r1 - r5 args that callee can access. The copy includes parent 9429 * pointers, which connects us up to the liveness chain 9430 */ 9431 for (i = BPF_REG_1; i <= BPF_REG_5; i++) 9432 callee->regs[i] = caller->regs[i]; 9433 return 0; 9434 } 9435 9436 static int set_map_elem_callback_state(struct bpf_verifier_env *env, 9437 struct bpf_func_state *caller, 9438 struct bpf_func_state *callee, 9439 int insn_idx) 9440 { 9441 struct bpf_insn_aux_data *insn_aux = &env->insn_aux_data[insn_idx]; 9442 struct bpf_map *map; 9443 int err; 9444 9445 if (bpf_map_ptr_poisoned(insn_aux)) { 9446 verbose(env, "tail_call abusing map_ptr\n"); 9447 return -EINVAL; 9448 } 9449 9450 map = BPF_MAP_PTR(insn_aux->map_ptr_state); 9451 if (!map->ops->map_set_for_each_callback_args || 9452 !map->ops->map_for_each_callback) { 9453 verbose(env, "callback function not allowed for map\n"); 9454 return -ENOTSUPP; 9455 } 9456 9457 err = map->ops->map_set_for_each_callback_args(env, caller, callee); 9458 if (err) 9459 return err; 9460 9461 callee->in_callback_fn = true; 9462 callee->callback_ret_range = retval_range(0, 1); 9463 return 0; 9464 } 9465 9466 static int set_loop_callback_state(struct bpf_verifier_env *env, 9467 struct bpf_func_state *caller, 9468 struct bpf_func_state *callee, 9469 int insn_idx) 9470 { 9471 /* bpf_loop(u32 nr_loops, void *callback_fn, void *callback_ctx, 9472 * u64 flags); 9473 * callback_fn(u32 index, void *callback_ctx); 9474 */ 9475 callee->regs[BPF_REG_1].type = SCALAR_VALUE; 9476 callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3]; 9477 9478 /* unused */ 9479 __mark_reg_not_init(env, &callee->regs[BPF_REG_3]); 9480 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]); 9481 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]); 9482 9483 callee->in_callback_fn = true; 9484 callee->callback_ret_range = retval_range(0, 1); 9485 return 0; 9486 } 9487 9488 static int set_timer_callback_state(struct bpf_verifier_env *env, 9489 struct bpf_func_state *caller, 9490 struct bpf_func_state *callee, 9491 int insn_idx) 9492 { 9493 struct bpf_map *map_ptr = caller->regs[BPF_REG_1].map_ptr; 9494 9495 /* bpf_timer_set_callback(struct bpf_timer *timer, void *callback_fn); 9496 * callback_fn(struct bpf_map *map, void *key, void *value); 9497 */ 9498 callee->regs[BPF_REG_1].type = CONST_PTR_TO_MAP; 9499 __mark_reg_known_zero(&callee->regs[BPF_REG_1]); 9500 callee->regs[BPF_REG_1].map_ptr = map_ptr; 9501 9502 callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY; 9503 __mark_reg_known_zero(&callee->regs[BPF_REG_2]); 9504 callee->regs[BPF_REG_2].map_ptr = map_ptr; 9505 9506 callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE; 9507 __mark_reg_known_zero(&callee->regs[BPF_REG_3]); 9508 callee->regs[BPF_REG_3].map_ptr = map_ptr; 9509 9510 /* unused */ 9511 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]); 9512 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]); 9513 callee->in_async_callback_fn = true; 9514 callee->callback_ret_range = retval_range(0, 1); 9515 return 0; 9516 } 9517 9518 static int set_find_vma_callback_state(struct bpf_verifier_env *env, 9519 struct bpf_func_state *caller, 9520 struct bpf_func_state *callee, 9521 int insn_idx) 9522 { 9523 /* bpf_find_vma(struct task_struct *task, u64 addr, 9524 * void *callback_fn, void *callback_ctx, u64 flags) 9525 * (callback_fn)(struct task_struct *task, 9526 * struct vm_area_struct *vma, void *callback_ctx); 9527 */ 9528 callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1]; 9529 9530 callee->regs[BPF_REG_2].type = PTR_TO_BTF_ID; 9531 __mark_reg_known_zero(&callee->regs[BPF_REG_2]); 9532 callee->regs[BPF_REG_2].btf = btf_vmlinux; 9533 callee->regs[BPF_REG_2].btf_id = btf_tracing_ids[BTF_TRACING_TYPE_VMA], 9534 9535 /* pointer to stack or null */ 9536 callee->regs[BPF_REG_3] = caller->regs[BPF_REG_4]; 9537 9538 /* unused */ 9539 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]); 9540 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]); 9541 callee->in_callback_fn = true; 9542 callee->callback_ret_range = retval_range(0, 1); 9543 return 0; 9544 } 9545 9546 static int set_user_ringbuf_callback_state(struct bpf_verifier_env *env, 9547 struct bpf_func_state *caller, 9548 struct bpf_func_state *callee, 9549 int insn_idx) 9550 { 9551 /* bpf_user_ringbuf_drain(struct bpf_map *map, void *callback_fn, void 9552 * callback_ctx, u64 flags); 9553 * callback_fn(const struct bpf_dynptr_t* dynptr, void *callback_ctx); 9554 */ 9555 __mark_reg_not_init(env, &callee->regs[BPF_REG_0]); 9556 mark_dynptr_cb_reg(env, &callee->regs[BPF_REG_1], BPF_DYNPTR_TYPE_LOCAL); 9557 callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3]; 9558 9559 /* unused */ 9560 __mark_reg_not_init(env, &callee->regs[BPF_REG_3]); 9561 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]); 9562 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]); 9563 9564 callee->in_callback_fn = true; 9565 callee->callback_ret_range = retval_range(0, 1); 9566 return 0; 9567 } 9568 9569 static int set_rbtree_add_callback_state(struct bpf_verifier_env *env, 9570 struct bpf_func_state *caller, 9571 struct bpf_func_state *callee, 9572 int insn_idx) 9573 { 9574 /* void bpf_rbtree_add_impl(struct bpf_rb_root *root, struct bpf_rb_node *node, 9575 * bool (less)(struct bpf_rb_node *a, const struct bpf_rb_node *b)); 9576 * 9577 * 'struct bpf_rb_node *node' arg to bpf_rbtree_add_impl is the same PTR_TO_BTF_ID w/ offset 9578 * that 'less' callback args will be receiving. However, 'node' arg was release_reference'd 9579 * by this point, so look at 'root' 9580 */ 9581 struct btf_field *field; 9582 9583 field = reg_find_field_offset(&caller->regs[BPF_REG_1], caller->regs[BPF_REG_1].off, 9584 BPF_RB_ROOT); 9585 if (!field || !field->graph_root.value_btf_id) 9586 return -EFAULT; 9587 9588 mark_reg_graph_node(callee->regs, BPF_REG_1, &field->graph_root); 9589 ref_set_non_owning(env, &callee->regs[BPF_REG_1]); 9590 mark_reg_graph_node(callee->regs, BPF_REG_2, &field->graph_root); 9591 ref_set_non_owning(env, &callee->regs[BPF_REG_2]); 9592 9593 __mark_reg_not_init(env, &callee->regs[BPF_REG_3]); 9594 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]); 9595 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]); 9596 callee->in_callback_fn = true; 9597 callee->callback_ret_range = retval_range(0, 1); 9598 return 0; 9599 } 9600 9601 static bool is_rbtree_lock_required_kfunc(u32 btf_id); 9602 9603 /* Are we currently verifying the callback for a rbtree helper that must 9604 * be called with lock held? If so, no need to complain about unreleased 9605 * lock 9606 */ 9607 static bool in_rbtree_lock_required_cb(struct bpf_verifier_env *env) 9608 { 9609 struct bpf_verifier_state *state = env->cur_state; 9610 struct bpf_insn *insn = env->prog->insnsi; 9611 struct bpf_func_state *callee; 9612 int kfunc_btf_id; 9613 9614 if (!state->curframe) 9615 return false; 9616 9617 callee = state->frame[state->curframe]; 9618 9619 if (!callee->in_callback_fn) 9620 return false; 9621 9622 kfunc_btf_id = insn[callee->callsite].imm; 9623 return is_rbtree_lock_required_kfunc(kfunc_btf_id); 9624 } 9625 9626 static bool retval_range_within(struct bpf_retval_range range, const struct bpf_reg_state *reg) 9627 { 9628 return range.minval <= reg->smin_value && reg->smax_value <= range.maxval; 9629 } 9630 9631 static int prepare_func_exit(struct bpf_verifier_env *env, int *insn_idx) 9632 { 9633 struct bpf_verifier_state *state = env->cur_state, *prev_st; 9634 struct bpf_func_state *caller, *callee; 9635 struct bpf_reg_state *r0; 9636 bool in_callback_fn; 9637 int err; 9638 9639 callee = state->frame[state->curframe]; 9640 r0 = &callee->regs[BPF_REG_0]; 9641 if (r0->type == PTR_TO_STACK) { 9642 /* technically it's ok to return caller's stack pointer 9643 * (or caller's caller's pointer) back to the caller, 9644 * since these pointers are valid. Only current stack 9645 * pointer will be invalid as soon as function exits, 9646 * but let's be conservative 9647 */ 9648 verbose(env, "cannot return stack pointer to the caller\n"); 9649 return -EINVAL; 9650 } 9651 9652 caller = state->frame[state->curframe - 1]; 9653 if (callee->in_callback_fn) { 9654 if (r0->type != SCALAR_VALUE) { 9655 verbose(env, "R0 not a scalar value\n"); 9656 return -EACCES; 9657 } 9658 9659 /* we are going to rely on register's precise value */ 9660 err = mark_reg_read(env, r0, r0->parent, REG_LIVE_READ64); 9661 err = err ?: mark_chain_precision(env, BPF_REG_0); 9662 if (err) 9663 return err; 9664 9665 /* enforce R0 return value range */ 9666 if (!retval_range_within(callee->callback_ret_range, r0)) { 9667 verbose_invalid_scalar(env, r0, callee->callback_ret_range, 9668 "At callback return", "R0"); 9669 return -EINVAL; 9670 } 9671 if (!calls_callback(env, callee->callsite)) { 9672 verbose(env, "BUG: in callback at %d, callsite %d !calls_callback\n", 9673 *insn_idx, callee->callsite); 9674 return -EFAULT; 9675 } 9676 } else { 9677 /* return to the caller whatever r0 had in the callee */ 9678 caller->regs[BPF_REG_0] = *r0; 9679 } 9680 9681 /* callback_fn frame should have released its own additions to parent's 9682 * reference state at this point, or check_reference_leak would 9683 * complain, hence it must be the same as the caller. There is no need 9684 * to copy it back. 9685 */ 9686 if (!callee->in_callback_fn) { 9687 /* Transfer references to the caller */ 9688 err = copy_reference_state(caller, callee); 9689 if (err) 9690 return err; 9691 } 9692 9693 /* for callbacks like bpf_loop or bpf_for_each_map_elem go back to callsite, 9694 * there function call logic would reschedule callback visit. If iteration 9695 * converges is_state_visited() would prune that visit eventually. 9696 */ 9697 in_callback_fn = callee->in_callback_fn; 9698 if (in_callback_fn) 9699 *insn_idx = callee->callsite; 9700 else 9701 *insn_idx = callee->callsite + 1; 9702 9703 if (env->log.level & BPF_LOG_LEVEL) { 9704 verbose(env, "returning from callee:\n"); 9705 print_verifier_state(env, callee, true); 9706 verbose(env, "to caller at %d:\n", *insn_idx); 9707 print_verifier_state(env, caller, true); 9708 } 9709 /* clear everything in the callee. In case of exceptional exits using 9710 * bpf_throw, this will be done by copy_verifier_state for extra frames. */ 9711 free_func_state(callee); 9712 state->frame[state->curframe--] = NULL; 9713 9714 /* for callbacks widen imprecise scalars to make programs like below verify: 9715 * 9716 * struct ctx { int i; } 9717 * void cb(int idx, struct ctx *ctx) { ctx->i++; ... } 9718 * ... 9719 * struct ctx = { .i = 0; } 9720 * bpf_loop(100, cb, &ctx, 0); 9721 * 9722 * This is similar to what is done in process_iter_next_call() for open 9723 * coded iterators. 9724 */ 9725 prev_st = in_callback_fn ? find_prev_entry(env, state, *insn_idx) : NULL; 9726 if (prev_st) { 9727 err = widen_imprecise_scalars(env, prev_st, state); 9728 if (err) 9729 return err; 9730 } 9731 return 0; 9732 } 9733 9734 static int do_refine_retval_range(struct bpf_verifier_env *env, 9735 struct bpf_reg_state *regs, int ret_type, 9736 int func_id, 9737 struct bpf_call_arg_meta *meta) 9738 { 9739 struct bpf_reg_state *ret_reg = ®s[BPF_REG_0]; 9740 9741 if (ret_type != RET_INTEGER) 9742 return 0; 9743 9744 switch (func_id) { 9745 case BPF_FUNC_get_stack: 9746 case BPF_FUNC_get_task_stack: 9747 case BPF_FUNC_probe_read_str: 9748 case BPF_FUNC_probe_read_kernel_str: 9749 case BPF_FUNC_probe_read_user_str: 9750 ret_reg->smax_value = meta->msize_max_value; 9751 ret_reg->s32_max_value = meta->msize_max_value; 9752 ret_reg->smin_value = -MAX_ERRNO; 9753 ret_reg->s32_min_value = -MAX_ERRNO; 9754 reg_bounds_sync(ret_reg); 9755 break; 9756 case BPF_FUNC_get_smp_processor_id: 9757 ret_reg->umax_value = nr_cpu_ids - 1; 9758 ret_reg->u32_max_value = nr_cpu_ids - 1; 9759 ret_reg->smax_value = nr_cpu_ids - 1; 9760 ret_reg->s32_max_value = nr_cpu_ids - 1; 9761 ret_reg->umin_value = 0; 9762 ret_reg->u32_min_value = 0; 9763 ret_reg->smin_value = 0; 9764 ret_reg->s32_min_value = 0; 9765 reg_bounds_sync(ret_reg); 9766 break; 9767 } 9768 9769 return reg_bounds_sanity_check(env, ret_reg, "retval"); 9770 } 9771 9772 static int 9773 record_func_map(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta, 9774 int func_id, int insn_idx) 9775 { 9776 struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx]; 9777 struct bpf_map *map = meta->map_ptr; 9778 9779 if (func_id != BPF_FUNC_tail_call && 9780 func_id != BPF_FUNC_map_lookup_elem && 9781 func_id != BPF_FUNC_map_update_elem && 9782 func_id != BPF_FUNC_map_delete_elem && 9783 func_id != BPF_FUNC_map_push_elem && 9784 func_id != BPF_FUNC_map_pop_elem && 9785 func_id != BPF_FUNC_map_peek_elem && 9786 func_id != BPF_FUNC_for_each_map_elem && 9787 func_id != BPF_FUNC_redirect_map && 9788 func_id != BPF_FUNC_map_lookup_percpu_elem) 9789 return 0; 9790 9791 if (map == NULL) { 9792 verbose(env, "kernel subsystem misconfigured verifier\n"); 9793 return -EINVAL; 9794 } 9795 9796 /* In case of read-only, some additional restrictions 9797 * need to be applied in order to prevent altering the 9798 * state of the map from program side. 9799 */ 9800 if ((map->map_flags & BPF_F_RDONLY_PROG) && 9801 (func_id == BPF_FUNC_map_delete_elem || 9802 func_id == BPF_FUNC_map_update_elem || 9803 func_id == BPF_FUNC_map_push_elem || 9804 func_id == BPF_FUNC_map_pop_elem)) { 9805 verbose(env, "write into map forbidden\n"); 9806 return -EACCES; 9807 } 9808 9809 if (!BPF_MAP_PTR(aux->map_ptr_state)) 9810 bpf_map_ptr_store(aux, meta->map_ptr, 9811 !meta->map_ptr->bypass_spec_v1); 9812 else if (BPF_MAP_PTR(aux->map_ptr_state) != meta->map_ptr) 9813 bpf_map_ptr_store(aux, BPF_MAP_PTR_POISON, 9814 !meta->map_ptr->bypass_spec_v1); 9815 return 0; 9816 } 9817 9818 static int 9819 record_func_key(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta, 9820 int func_id, int insn_idx) 9821 { 9822 struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx]; 9823 struct bpf_reg_state *regs = cur_regs(env), *reg; 9824 struct bpf_map *map = meta->map_ptr; 9825 u64 val, max; 9826 int err; 9827 9828 if (func_id != BPF_FUNC_tail_call) 9829 return 0; 9830 if (!map || map->map_type != BPF_MAP_TYPE_PROG_ARRAY) { 9831 verbose(env, "kernel subsystem misconfigured verifier\n"); 9832 return -EINVAL; 9833 } 9834 9835 reg = ®s[BPF_REG_3]; 9836 val = reg->var_off.value; 9837 max = map->max_entries; 9838 9839 if (!(is_reg_const(reg, false) && val < max)) { 9840 bpf_map_key_store(aux, BPF_MAP_KEY_POISON); 9841 return 0; 9842 } 9843 9844 err = mark_chain_precision(env, BPF_REG_3); 9845 if (err) 9846 return err; 9847 if (bpf_map_key_unseen(aux)) 9848 bpf_map_key_store(aux, val); 9849 else if (!bpf_map_key_poisoned(aux) && 9850 bpf_map_key_immediate(aux) != val) 9851 bpf_map_key_store(aux, BPF_MAP_KEY_POISON); 9852 return 0; 9853 } 9854 9855 static int check_reference_leak(struct bpf_verifier_env *env, bool exception_exit) 9856 { 9857 struct bpf_func_state *state = cur_func(env); 9858 bool refs_lingering = false; 9859 int i; 9860 9861 if (!exception_exit && state->frameno && !state->in_callback_fn) 9862 return 0; 9863 9864 for (i = 0; i < state->acquired_refs; i++) { 9865 if (!exception_exit && state->in_callback_fn && state->refs[i].callback_ref != state->frameno) 9866 continue; 9867 verbose(env, "Unreleased reference id=%d alloc_insn=%d\n", 9868 state->refs[i].id, state->refs[i].insn_idx); 9869 refs_lingering = true; 9870 } 9871 return refs_lingering ? -EINVAL : 0; 9872 } 9873 9874 static int check_bpf_snprintf_call(struct bpf_verifier_env *env, 9875 struct bpf_reg_state *regs) 9876 { 9877 struct bpf_reg_state *fmt_reg = ®s[BPF_REG_3]; 9878 struct bpf_reg_state *data_len_reg = ®s[BPF_REG_5]; 9879 struct bpf_map *fmt_map = fmt_reg->map_ptr; 9880 struct bpf_bprintf_data data = {}; 9881 int err, fmt_map_off, num_args; 9882 u64 fmt_addr; 9883 char *fmt; 9884 9885 /* data must be an array of u64 */ 9886 if (data_len_reg->var_off.value % 8) 9887 return -EINVAL; 9888 num_args = data_len_reg->var_off.value / 8; 9889 9890 /* fmt being ARG_PTR_TO_CONST_STR guarantees that var_off is const 9891 * and map_direct_value_addr is set. 9892 */ 9893 fmt_map_off = fmt_reg->off + fmt_reg->var_off.value; 9894 err = fmt_map->ops->map_direct_value_addr(fmt_map, &fmt_addr, 9895 fmt_map_off); 9896 if (err) { 9897 verbose(env, "verifier bug\n"); 9898 return -EFAULT; 9899 } 9900 fmt = (char *)(long)fmt_addr + fmt_map_off; 9901 9902 /* We are also guaranteed that fmt+fmt_map_off is NULL terminated, we 9903 * can focus on validating the format specifiers. 9904 */ 9905 err = bpf_bprintf_prepare(fmt, UINT_MAX, NULL, num_args, &data); 9906 if (err < 0) 9907 verbose(env, "Invalid format string\n"); 9908 9909 return err; 9910 } 9911 9912 static int check_get_func_ip(struct bpf_verifier_env *env) 9913 { 9914 enum bpf_prog_type type = resolve_prog_type(env->prog); 9915 int func_id = BPF_FUNC_get_func_ip; 9916 9917 if (type == BPF_PROG_TYPE_TRACING) { 9918 if (!bpf_prog_has_trampoline(env->prog)) { 9919 verbose(env, "func %s#%d supported only for fentry/fexit/fmod_ret programs\n", 9920 func_id_name(func_id), func_id); 9921 return -ENOTSUPP; 9922 } 9923 return 0; 9924 } else if (type == BPF_PROG_TYPE_KPROBE) { 9925 return 0; 9926 } 9927 9928 verbose(env, "func %s#%d not supported for program type %d\n", 9929 func_id_name(func_id), func_id, type); 9930 return -ENOTSUPP; 9931 } 9932 9933 static struct bpf_insn_aux_data *cur_aux(struct bpf_verifier_env *env) 9934 { 9935 return &env->insn_aux_data[env->insn_idx]; 9936 } 9937 9938 static bool loop_flag_is_zero(struct bpf_verifier_env *env) 9939 { 9940 struct bpf_reg_state *regs = cur_regs(env); 9941 struct bpf_reg_state *reg = ®s[BPF_REG_4]; 9942 bool reg_is_null = register_is_null(reg); 9943 9944 if (reg_is_null) 9945 mark_chain_precision(env, BPF_REG_4); 9946 9947 return reg_is_null; 9948 } 9949 9950 static void update_loop_inline_state(struct bpf_verifier_env *env, u32 subprogno) 9951 { 9952 struct bpf_loop_inline_state *state = &cur_aux(env)->loop_inline_state; 9953 9954 if (!state->initialized) { 9955 state->initialized = 1; 9956 state->fit_for_inline = loop_flag_is_zero(env); 9957 state->callback_subprogno = subprogno; 9958 return; 9959 } 9960 9961 if (!state->fit_for_inline) 9962 return; 9963 9964 state->fit_for_inline = (loop_flag_is_zero(env) && 9965 state->callback_subprogno == subprogno); 9966 } 9967 9968 static int check_helper_call(struct bpf_verifier_env *env, struct bpf_insn *insn, 9969 int *insn_idx_p) 9970 { 9971 enum bpf_prog_type prog_type = resolve_prog_type(env->prog); 9972 bool returns_cpu_specific_alloc_ptr = false; 9973 const struct bpf_func_proto *fn = NULL; 9974 enum bpf_return_type ret_type; 9975 enum bpf_type_flag ret_flag; 9976 struct bpf_reg_state *regs; 9977 struct bpf_call_arg_meta meta; 9978 int insn_idx = *insn_idx_p; 9979 bool changes_data; 9980 int i, err, func_id; 9981 9982 /* find function prototype */ 9983 func_id = insn->imm; 9984 if (func_id < 0 || func_id >= __BPF_FUNC_MAX_ID) { 9985 verbose(env, "invalid func %s#%d\n", func_id_name(func_id), 9986 func_id); 9987 return -EINVAL; 9988 } 9989 9990 if (env->ops->get_func_proto) 9991 fn = env->ops->get_func_proto(func_id, env->prog); 9992 if (!fn) { 9993 verbose(env, "unknown func %s#%d\n", func_id_name(func_id), 9994 func_id); 9995 return -EINVAL; 9996 } 9997 9998 /* eBPF programs must be GPL compatible to use GPL-ed functions */ 9999 if (!env->prog->gpl_compatible && fn->gpl_only) { 10000 verbose(env, "cannot call GPL-restricted function from non-GPL compatible program\n"); 10001 return -EINVAL; 10002 } 10003 10004 if (fn->allowed && !fn->allowed(env->prog)) { 10005 verbose(env, "helper call is not allowed in probe\n"); 10006 return -EINVAL; 10007 } 10008 10009 if (!env->prog->aux->sleepable && fn->might_sleep) { 10010 verbose(env, "helper call might sleep in a non-sleepable prog\n"); 10011 return -EINVAL; 10012 } 10013 10014 /* With LD_ABS/IND some JITs save/restore skb from r1. */ 10015 changes_data = bpf_helper_changes_pkt_data(fn->func); 10016 if (changes_data && fn->arg1_type != ARG_PTR_TO_CTX) { 10017 verbose(env, "kernel subsystem misconfigured func %s#%d: r1 != ctx\n", 10018 func_id_name(func_id), func_id); 10019 return -EINVAL; 10020 } 10021 10022 memset(&meta, 0, sizeof(meta)); 10023 meta.pkt_access = fn->pkt_access; 10024 10025 err = check_func_proto(fn, func_id); 10026 if (err) { 10027 verbose(env, "kernel subsystem misconfigured func %s#%d\n", 10028 func_id_name(func_id), func_id); 10029 return err; 10030 } 10031 10032 if (env->cur_state->active_rcu_lock) { 10033 if (fn->might_sleep) { 10034 verbose(env, "sleepable helper %s#%d in rcu_read_lock region\n", 10035 func_id_name(func_id), func_id); 10036 return -EINVAL; 10037 } 10038 10039 if (env->prog->aux->sleepable && is_storage_get_function(func_id)) 10040 env->insn_aux_data[insn_idx].storage_get_func_atomic = true; 10041 } 10042 10043 meta.func_id = func_id; 10044 /* check args */ 10045 for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++) { 10046 err = check_func_arg(env, i, &meta, fn, insn_idx); 10047 if (err) 10048 return err; 10049 } 10050 10051 err = record_func_map(env, &meta, func_id, insn_idx); 10052 if (err) 10053 return err; 10054 10055 err = record_func_key(env, &meta, func_id, insn_idx); 10056 if (err) 10057 return err; 10058 10059 /* Mark slots with STACK_MISC in case of raw mode, stack offset 10060 * is inferred from register state. 10061 */ 10062 for (i = 0; i < meta.access_size; i++) { 10063 err = check_mem_access(env, insn_idx, meta.regno, i, BPF_B, 10064 BPF_WRITE, -1, false, false); 10065 if (err) 10066 return err; 10067 } 10068 10069 regs = cur_regs(env); 10070 10071 if (meta.release_regno) { 10072 err = -EINVAL; 10073 /* This can only be set for PTR_TO_STACK, as CONST_PTR_TO_DYNPTR cannot 10074 * be released by any dynptr helper. Hence, unmark_stack_slots_dynptr 10075 * is safe to do directly. 10076 */ 10077 if (arg_type_is_dynptr(fn->arg_type[meta.release_regno - BPF_REG_1])) { 10078 if (regs[meta.release_regno].type == CONST_PTR_TO_DYNPTR) { 10079 verbose(env, "verifier internal error: CONST_PTR_TO_DYNPTR cannot be released\n"); 10080 return -EFAULT; 10081 } 10082 err = unmark_stack_slots_dynptr(env, ®s[meta.release_regno]); 10083 } else if (func_id == BPF_FUNC_kptr_xchg && meta.ref_obj_id) { 10084 u32 ref_obj_id = meta.ref_obj_id; 10085 bool in_rcu = in_rcu_cs(env); 10086 struct bpf_func_state *state; 10087 struct bpf_reg_state *reg; 10088 10089 err = release_reference_state(cur_func(env), ref_obj_id); 10090 if (!err) { 10091 bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({ 10092 if (reg->ref_obj_id == ref_obj_id) { 10093 if (in_rcu && (reg->type & MEM_ALLOC) && (reg->type & MEM_PERCPU)) { 10094 reg->ref_obj_id = 0; 10095 reg->type &= ~MEM_ALLOC; 10096 reg->type |= MEM_RCU; 10097 } else { 10098 mark_reg_invalid(env, reg); 10099 } 10100 } 10101 })); 10102 } 10103 } else if (meta.ref_obj_id) { 10104 err = release_reference(env, meta.ref_obj_id); 10105 } else if (register_is_null(®s[meta.release_regno])) { 10106 /* meta.ref_obj_id can only be 0 if register that is meant to be 10107 * released is NULL, which must be > R0. 10108 */ 10109 err = 0; 10110 } 10111 if (err) { 10112 verbose(env, "func %s#%d reference has not been acquired before\n", 10113 func_id_name(func_id), func_id); 10114 return err; 10115 } 10116 } 10117 10118 switch (func_id) { 10119 case BPF_FUNC_tail_call: 10120 err = check_reference_leak(env, false); 10121 if (err) { 10122 verbose(env, "tail_call would lead to reference leak\n"); 10123 return err; 10124 } 10125 break; 10126 case BPF_FUNC_get_local_storage: 10127 /* check that flags argument in get_local_storage(map, flags) is 0, 10128 * this is required because get_local_storage() can't return an error. 10129 */ 10130 if (!register_is_null(®s[BPF_REG_2])) { 10131 verbose(env, "get_local_storage() doesn't support non-zero flags\n"); 10132 return -EINVAL; 10133 } 10134 break; 10135 case BPF_FUNC_for_each_map_elem: 10136 err = push_callback_call(env, insn, insn_idx, meta.subprogno, 10137 set_map_elem_callback_state); 10138 break; 10139 case BPF_FUNC_timer_set_callback: 10140 err = push_callback_call(env, insn, insn_idx, meta.subprogno, 10141 set_timer_callback_state); 10142 break; 10143 case BPF_FUNC_find_vma: 10144 err = push_callback_call(env, insn, insn_idx, meta.subprogno, 10145 set_find_vma_callback_state); 10146 break; 10147 case BPF_FUNC_snprintf: 10148 err = check_bpf_snprintf_call(env, regs); 10149 break; 10150 case BPF_FUNC_loop: 10151 update_loop_inline_state(env, meta.subprogno); 10152 /* Verifier relies on R1 value to determine if bpf_loop() iteration 10153 * is finished, thus mark it precise. 10154 */ 10155 err = mark_chain_precision(env, BPF_REG_1); 10156 if (err) 10157 return err; 10158 if (cur_func(env)->callback_depth < regs[BPF_REG_1].umax_value) { 10159 err = push_callback_call(env, insn, insn_idx, meta.subprogno, 10160 set_loop_callback_state); 10161 } else { 10162 cur_func(env)->callback_depth = 0; 10163 if (env->log.level & BPF_LOG_LEVEL2) 10164 verbose(env, "frame%d bpf_loop iteration limit reached\n", 10165 env->cur_state->curframe); 10166 } 10167 break; 10168 case BPF_FUNC_dynptr_from_mem: 10169 if (regs[BPF_REG_1].type != PTR_TO_MAP_VALUE) { 10170 verbose(env, "Unsupported reg type %s for bpf_dynptr_from_mem data\n", 10171 reg_type_str(env, regs[BPF_REG_1].type)); 10172 return -EACCES; 10173 } 10174 break; 10175 case BPF_FUNC_set_retval: 10176 if (prog_type == BPF_PROG_TYPE_LSM && 10177 env->prog->expected_attach_type == BPF_LSM_CGROUP) { 10178 if (!env->prog->aux->attach_func_proto->type) { 10179 /* Make sure programs that attach to void 10180 * hooks don't try to modify return value. 10181 */ 10182 verbose(env, "BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n"); 10183 return -EINVAL; 10184 } 10185 } 10186 break; 10187 case BPF_FUNC_dynptr_data: 10188 { 10189 struct bpf_reg_state *reg; 10190 int id, ref_obj_id; 10191 10192 reg = get_dynptr_arg_reg(env, fn, regs); 10193 if (!reg) 10194 return -EFAULT; 10195 10196 10197 if (meta.dynptr_id) { 10198 verbose(env, "verifier internal error: meta.dynptr_id already set\n"); 10199 return -EFAULT; 10200 } 10201 if (meta.ref_obj_id) { 10202 verbose(env, "verifier internal error: meta.ref_obj_id already set\n"); 10203 return -EFAULT; 10204 } 10205 10206 id = dynptr_id(env, reg); 10207 if (id < 0) { 10208 verbose(env, "verifier internal error: failed to obtain dynptr id\n"); 10209 return id; 10210 } 10211 10212 ref_obj_id = dynptr_ref_obj_id(env, reg); 10213 if (ref_obj_id < 0) { 10214 verbose(env, "verifier internal error: failed to obtain dynptr ref_obj_id\n"); 10215 return ref_obj_id; 10216 } 10217 10218 meta.dynptr_id = id; 10219 meta.ref_obj_id = ref_obj_id; 10220 10221 break; 10222 } 10223 case BPF_FUNC_dynptr_write: 10224 { 10225 enum bpf_dynptr_type dynptr_type; 10226 struct bpf_reg_state *reg; 10227 10228 reg = get_dynptr_arg_reg(env, fn, regs); 10229 if (!reg) 10230 return -EFAULT; 10231 10232 dynptr_type = dynptr_get_type(env, reg); 10233 if (dynptr_type == BPF_DYNPTR_TYPE_INVALID) 10234 return -EFAULT; 10235 10236 if (dynptr_type == BPF_DYNPTR_TYPE_SKB) 10237 /* this will trigger clear_all_pkt_pointers(), which will 10238 * invalidate all dynptr slices associated with the skb 10239 */ 10240 changes_data = true; 10241 10242 break; 10243 } 10244 case BPF_FUNC_per_cpu_ptr: 10245 case BPF_FUNC_this_cpu_ptr: 10246 { 10247 struct bpf_reg_state *reg = ®s[BPF_REG_1]; 10248 const struct btf_type *type; 10249 10250 if (reg->type & MEM_RCU) { 10251 type = btf_type_by_id(reg->btf, reg->btf_id); 10252 if (!type || !btf_type_is_struct(type)) { 10253 verbose(env, "Helper has invalid btf/btf_id in R1\n"); 10254 return -EFAULT; 10255 } 10256 returns_cpu_specific_alloc_ptr = true; 10257 env->insn_aux_data[insn_idx].call_with_percpu_alloc_ptr = true; 10258 } 10259 break; 10260 } 10261 case BPF_FUNC_user_ringbuf_drain: 10262 err = push_callback_call(env, insn, insn_idx, meta.subprogno, 10263 set_user_ringbuf_callback_state); 10264 break; 10265 } 10266 10267 if (err) 10268 return err; 10269 10270 /* reset caller saved regs */ 10271 for (i = 0; i < CALLER_SAVED_REGS; i++) { 10272 mark_reg_not_init(env, regs, caller_saved[i]); 10273 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK); 10274 } 10275 10276 /* helper call returns 64-bit value. */ 10277 regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG; 10278 10279 /* update return register (already marked as written above) */ 10280 ret_type = fn->ret_type; 10281 ret_flag = type_flag(ret_type); 10282 10283 switch (base_type(ret_type)) { 10284 case RET_INTEGER: 10285 /* sets type to SCALAR_VALUE */ 10286 mark_reg_unknown(env, regs, BPF_REG_0); 10287 break; 10288 case RET_VOID: 10289 regs[BPF_REG_0].type = NOT_INIT; 10290 break; 10291 case RET_PTR_TO_MAP_VALUE: 10292 /* There is no offset yet applied, variable or fixed */ 10293 mark_reg_known_zero(env, regs, BPF_REG_0); 10294 /* remember map_ptr, so that check_map_access() 10295 * can check 'value_size' boundary of memory access 10296 * to map element returned from bpf_map_lookup_elem() 10297 */ 10298 if (meta.map_ptr == NULL) { 10299 verbose(env, 10300 "kernel subsystem misconfigured verifier\n"); 10301 return -EINVAL; 10302 } 10303 regs[BPF_REG_0].map_ptr = meta.map_ptr; 10304 regs[BPF_REG_0].map_uid = meta.map_uid; 10305 regs[BPF_REG_0].type = PTR_TO_MAP_VALUE | ret_flag; 10306 if (!type_may_be_null(ret_type) && 10307 btf_record_has_field(meta.map_ptr->record, BPF_SPIN_LOCK)) { 10308 regs[BPF_REG_0].id = ++env->id_gen; 10309 } 10310 break; 10311 case RET_PTR_TO_SOCKET: 10312 mark_reg_known_zero(env, regs, BPF_REG_0); 10313 regs[BPF_REG_0].type = PTR_TO_SOCKET | ret_flag; 10314 break; 10315 case RET_PTR_TO_SOCK_COMMON: 10316 mark_reg_known_zero(env, regs, BPF_REG_0); 10317 regs[BPF_REG_0].type = PTR_TO_SOCK_COMMON | ret_flag; 10318 break; 10319 case RET_PTR_TO_TCP_SOCK: 10320 mark_reg_known_zero(env, regs, BPF_REG_0); 10321 regs[BPF_REG_0].type = PTR_TO_TCP_SOCK | ret_flag; 10322 break; 10323 case RET_PTR_TO_MEM: 10324 mark_reg_known_zero(env, regs, BPF_REG_0); 10325 regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag; 10326 regs[BPF_REG_0].mem_size = meta.mem_size; 10327 break; 10328 case RET_PTR_TO_MEM_OR_BTF_ID: 10329 { 10330 const struct btf_type *t; 10331 10332 mark_reg_known_zero(env, regs, BPF_REG_0); 10333 t = btf_type_skip_modifiers(meta.ret_btf, meta.ret_btf_id, NULL); 10334 if (!btf_type_is_struct(t)) { 10335 u32 tsize; 10336 const struct btf_type *ret; 10337 const char *tname; 10338 10339 /* resolve the type size of ksym. */ 10340 ret = btf_resolve_size(meta.ret_btf, t, &tsize); 10341 if (IS_ERR(ret)) { 10342 tname = btf_name_by_offset(meta.ret_btf, t->name_off); 10343 verbose(env, "unable to resolve the size of type '%s': %ld\n", 10344 tname, PTR_ERR(ret)); 10345 return -EINVAL; 10346 } 10347 regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag; 10348 regs[BPF_REG_0].mem_size = tsize; 10349 } else { 10350 if (returns_cpu_specific_alloc_ptr) { 10351 regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC | MEM_RCU; 10352 } else { 10353 /* MEM_RDONLY may be carried from ret_flag, but it 10354 * doesn't apply on PTR_TO_BTF_ID. Fold it, otherwise 10355 * it will confuse the check of PTR_TO_BTF_ID in 10356 * check_mem_access(). 10357 */ 10358 ret_flag &= ~MEM_RDONLY; 10359 regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag; 10360 } 10361 10362 regs[BPF_REG_0].btf = meta.ret_btf; 10363 regs[BPF_REG_0].btf_id = meta.ret_btf_id; 10364 } 10365 break; 10366 } 10367 case RET_PTR_TO_BTF_ID: 10368 { 10369 struct btf *ret_btf; 10370 int ret_btf_id; 10371 10372 mark_reg_known_zero(env, regs, BPF_REG_0); 10373 regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag; 10374 if (func_id == BPF_FUNC_kptr_xchg) { 10375 ret_btf = meta.kptr_field->kptr.btf; 10376 ret_btf_id = meta.kptr_field->kptr.btf_id; 10377 if (!btf_is_kernel(ret_btf)) { 10378 regs[BPF_REG_0].type |= MEM_ALLOC; 10379 if (meta.kptr_field->type == BPF_KPTR_PERCPU) 10380 regs[BPF_REG_0].type |= MEM_PERCPU; 10381 } 10382 } else { 10383 if (fn->ret_btf_id == BPF_PTR_POISON) { 10384 verbose(env, "verifier internal error:"); 10385 verbose(env, "func %s has non-overwritten BPF_PTR_POISON return type\n", 10386 func_id_name(func_id)); 10387 return -EINVAL; 10388 } 10389 ret_btf = btf_vmlinux; 10390 ret_btf_id = *fn->ret_btf_id; 10391 } 10392 if (ret_btf_id == 0) { 10393 verbose(env, "invalid return type %u of func %s#%d\n", 10394 base_type(ret_type), func_id_name(func_id), 10395 func_id); 10396 return -EINVAL; 10397 } 10398 regs[BPF_REG_0].btf = ret_btf; 10399 regs[BPF_REG_0].btf_id = ret_btf_id; 10400 break; 10401 } 10402 default: 10403 verbose(env, "unknown return type %u of func %s#%d\n", 10404 base_type(ret_type), func_id_name(func_id), func_id); 10405 return -EINVAL; 10406 } 10407 10408 if (type_may_be_null(regs[BPF_REG_0].type)) 10409 regs[BPF_REG_0].id = ++env->id_gen; 10410 10411 if (helper_multiple_ref_obj_use(func_id, meta.map_ptr)) { 10412 verbose(env, "verifier internal error: func %s#%d sets ref_obj_id more than once\n", 10413 func_id_name(func_id), func_id); 10414 return -EFAULT; 10415 } 10416 10417 if (is_dynptr_ref_function(func_id)) 10418 regs[BPF_REG_0].dynptr_id = meta.dynptr_id; 10419 10420 if (is_ptr_cast_function(func_id) || is_dynptr_ref_function(func_id)) { 10421 /* For release_reference() */ 10422 regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id; 10423 } else if (is_acquire_function(func_id, meta.map_ptr)) { 10424 int id = acquire_reference_state(env, insn_idx); 10425 10426 if (id < 0) 10427 return id; 10428 /* For mark_ptr_or_null_reg() */ 10429 regs[BPF_REG_0].id = id; 10430 /* For release_reference() */ 10431 regs[BPF_REG_0].ref_obj_id = id; 10432 } 10433 10434 err = do_refine_retval_range(env, regs, fn->ret_type, func_id, &meta); 10435 if (err) 10436 return err; 10437 10438 err = check_map_func_compatibility(env, meta.map_ptr, func_id); 10439 if (err) 10440 return err; 10441 10442 if ((func_id == BPF_FUNC_get_stack || 10443 func_id == BPF_FUNC_get_task_stack) && 10444 !env->prog->has_callchain_buf) { 10445 const char *err_str; 10446 10447 #ifdef CONFIG_PERF_EVENTS 10448 err = get_callchain_buffers(sysctl_perf_event_max_stack); 10449 err_str = "cannot get callchain buffer for func %s#%d\n"; 10450 #else 10451 err = -ENOTSUPP; 10452 err_str = "func %s#%d not supported without CONFIG_PERF_EVENTS\n"; 10453 #endif 10454 if (err) { 10455 verbose(env, err_str, func_id_name(func_id), func_id); 10456 return err; 10457 } 10458 10459 env->prog->has_callchain_buf = true; 10460 } 10461 10462 if (func_id == BPF_FUNC_get_stackid || func_id == BPF_FUNC_get_stack) 10463 env->prog->call_get_stack = true; 10464 10465 if (func_id == BPF_FUNC_get_func_ip) { 10466 if (check_get_func_ip(env)) 10467 return -ENOTSUPP; 10468 env->prog->call_get_func_ip = true; 10469 } 10470 10471 if (changes_data) 10472 clear_all_pkt_pointers(env); 10473 return 0; 10474 } 10475 10476 /* mark_btf_func_reg_size() is used when the reg size is determined by 10477 * the BTF func_proto's return value size and argument. 10478 */ 10479 static void mark_btf_func_reg_size(struct bpf_verifier_env *env, u32 regno, 10480 size_t reg_size) 10481 { 10482 struct bpf_reg_state *reg = &cur_regs(env)[regno]; 10483 10484 if (regno == BPF_REG_0) { 10485 /* Function return value */ 10486 reg->live |= REG_LIVE_WRITTEN; 10487 reg->subreg_def = reg_size == sizeof(u64) ? 10488 DEF_NOT_SUBREG : env->insn_idx + 1; 10489 } else { 10490 /* Function argument */ 10491 if (reg_size == sizeof(u64)) { 10492 mark_insn_zext(env, reg); 10493 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64); 10494 } else { 10495 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ32); 10496 } 10497 } 10498 } 10499 10500 static bool is_kfunc_acquire(struct bpf_kfunc_call_arg_meta *meta) 10501 { 10502 return meta->kfunc_flags & KF_ACQUIRE; 10503 } 10504 10505 static bool is_kfunc_release(struct bpf_kfunc_call_arg_meta *meta) 10506 { 10507 return meta->kfunc_flags & KF_RELEASE; 10508 } 10509 10510 static bool is_kfunc_trusted_args(struct bpf_kfunc_call_arg_meta *meta) 10511 { 10512 return (meta->kfunc_flags & KF_TRUSTED_ARGS) || is_kfunc_release(meta); 10513 } 10514 10515 static bool is_kfunc_sleepable(struct bpf_kfunc_call_arg_meta *meta) 10516 { 10517 return meta->kfunc_flags & KF_SLEEPABLE; 10518 } 10519 10520 static bool is_kfunc_destructive(struct bpf_kfunc_call_arg_meta *meta) 10521 { 10522 return meta->kfunc_flags & KF_DESTRUCTIVE; 10523 } 10524 10525 static bool is_kfunc_rcu(struct bpf_kfunc_call_arg_meta *meta) 10526 { 10527 return meta->kfunc_flags & KF_RCU; 10528 } 10529 10530 static bool is_kfunc_rcu_protected(struct bpf_kfunc_call_arg_meta *meta) 10531 { 10532 return meta->kfunc_flags & KF_RCU_PROTECTED; 10533 } 10534 10535 static bool __kfunc_param_match_suffix(const struct btf *btf, 10536 const struct btf_param *arg, 10537 const char *suffix) 10538 { 10539 int suffix_len = strlen(suffix), len; 10540 const char *param_name; 10541 10542 /* In the future, this can be ported to use BTF tagging */ 10543 param_name = btf_name_by_offset(btf, arg->name_off); 10544 if (str_is_empty(param_name)) 10545 return false; 10546 len = strlen(param_name); 10547 if (len < suffix_len) 10548 return false; 10549 param_name += len - suffix_len; 10550 return !strncmp(param_name, suffix, suffix_len); 10551 } 10552 10553 static bool is_kfunc_arg_mem_size(const struct btf *btf, 10554 const struct btf_param *arg, 10555 const struct bpf_reg_state *reg) 10556 { 10557 const struct btf_type *t; 10558 10559 t = btf_type_skip_modifiers(btf, arg->type, NULL); 10560 if (!btf_type_is_scalar(t) || reg->type != SCALAR_VALUE) 10561 return false; 10562 10563 return __kfunc_param_match_suffix(btf, arg, "__sz"); 10564 } 10565 10566 static bool is_kfunc_arg_const_mem_size(const struct btf *btf, 10567 const struct btf_param *arg, 10568 const struct bpf_reg_state *reg) 10569 { 10570 const struct btf_type *t; 10571 10572 t = btf_type_skip_modifiers(btf, arg->type, NULL); 10573 if (!btf_type_is_scalar(t) || reg->type != SCALAR_VALUE) 10574 return false; 10575 10576 return __kfunc_param_match_suffix(btf, arg, "__szk"); 10577 } 10578 10579 static bool is_kfunc_arg_optional(const struct btf *btf, const struct btf_param *arg) 10580 { 10581 return __kfunc_param_match_suffix(btf, arg, "__opt"); 10582 } 10583 10584 static bool is_kfunc_arg_constant(const struct btf *btf, const struct btf_param *arg) 10585 { 10586 return __kfunc_param_match_suffix(btf, arg, "__k"); 10587 } 10588 10589 static bool is_kfunc_arg_ignore(const struct btf *btf, const struct btf_param *arg) 10590 { 10591 return __kfunc_param_match_suffix(btf, arg, "__ign"); 10592 } 10593 10594 static bool is_kfunc_arg_alloc_obj(const struct btf *btf, const struct btf_param *arg) 10595 { 10596 return __kfunc_param_match_suffix(btf, arg, "__alloc"); 10597 } 10598 10599 static bool is_kfunc_arg_uninit(const struct btf *btf, const struct btf_param *arg) 10600 { 10601 return __kfunc_param_match_suffix(btf, arg, "__uninit"); 10602 } 10603 10604 static bool is_kfunc_arg_refcounted_kptr(const struct btf *btf, const struct btf_param *arg) 10605 { 10606 return __kfunc_param_match_suffix(btf, arg, "__refcounted_kptr"); 10607 } 10608 10609 static bool is_kfunc_arg_nullable(const struct btf *btf, const struct btf_param *arg) 10610 { 10611 return __kfunc_param_match_suffix(btf, arg, "__nullable"); 10612 } 10613 10614 static bool is_kfunc_arg_const_str(const struct btf *btf, const struct btf_param *arg) 10615 { 10616 return __kfunc_param_match_suffix(btf, arg, "__str"); 10617 } 10618 10619 static bool is_kfunc_arg_scalar_with_name(const struct btf *btf, 10620 const struct btf_param *arg, 10621 const char *name) 10622 { 10623 int len, target_len = strlen(name); 10624 const char *param_name; 10625 10626 param_name = btf_name_by_offset(btf, arg->name_off); 10627 if (str_is_empty(param_name)) 10628 return false; 10629 len = strlen(param_name); 10630 if (len != target_len) 10631 return false; 10632 if (strcmp(param_name, name)) 10633 return false; 10634 10635 return true; 10636 } 10637 10638 enum { 10639 KF_ARG_DYNPTR_ID, 10640 KF_ARG_LIST_HEAD_ID, 10641 KF_ARG_LIST_NODE_ID, 10642 KF_ARG_RB_ROOT_ID, 10643 KF_ARG_RB_NODE_ID, 10644 }; 10645 10646 BTF_ID_LIST(kf_arg_btf_ids) 10647 BTF_ID(struct, bpf_dynptr_kern) 10648 BTF_ID(struct, bpf_list_head) 10649 BTF_ID(struct, bpf_list_node) 10650 BTF_ID(struct, bpf_rb_root) 10651 BTF_ID(struct, bpf_rb_node) 10652 10653 static bool __is_kfunc_ptr_arg_type(const struct btf *btf, 10654 const struct btf_param *arg, int type) 10655 { 10656 const struct btf_type *t; 10657 u32 res_id; 10658 10659 t = btf_type_skip_modifiers(btf, arg->type, NULL); 10660 if (!t) 10661 return false; 10662 if (!btf_type_is_ptr(t)) 10663 return false; 10664 t = btf_type_skip_modifiers(btf, t->type, &res_id); 10665 if (!t) 10666 return false; 10667 return btf_types_are_same(btf, res_id, btf_vmlinux, kf_arg_btf_ids[type]); 10668 } 10669 10670 static bool is_kfunc_arg_dynptr(const struct btf *btf, const struct btf_param *arg) 10671 { 10672 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_DYNPTR_ID); 10673 } 10674 10675 static bool is_kfunc_arg_list_head(const struct btf *btf, const struct btf_param *arg) 10676 { 10677 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_LIST_HEAD_ID); 10678 } 10679 10680 static bool is_kfunc_arg_list_node(const struct btf *btf, const struct btf_param *arg) 10681 { 10682 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_LIST_NODE_ID); 10683 } 10684 10685 static bool is_kfunc_arg_rbtree_root(const struct btf *btf, const struct btf_param *arg) 10686 { 10687 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_RB_ROOT_ID); 10688 } 10689 10690 static bool is_kfunc_arg_rbtree_node(const struct btf *btf, const struct btf_param *arg) 10691 { 10692 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_RB_NODE_ID); 10693 } 10694 10695 static bool is_kfunc_arg_callback(struct bpf_verifier_env *env, const struct btf *btf, 10696 const struct btf_param *arg) 10697 { 10698 const struct btf_type *t; 10699 10700 t = btf_type_resolve_func_ptr(btf, arg->type, NULL); 10701 if (!t) 10702 return false; 10703 10704 return true; 10705 } 10706 10707 /* Returns true if struct is composed of scalars, 4 levels of nesting allowed */ 10708 static bool __btf_type_is_scalar_struct(struct bpf_verifier_env *env, 10709 const struct btf *btf, 10710 const struct btf_type *t, int rec) 10711 { 10712 const struct btf_type *member_type; 10713 const struct btf_member *member; 10714 u32 i; 10715 10716 if (!btf_type_is_struct(t)) 10717 return false; 10718 10719 for_each_member(i, t, member) { 10720 const struct btf_array *array; 10721 10722 member_type = btf_type_skip_modifiers(btf, member->type, NULL); 10723 if (btf_type_is_struct(member_type)) { 10724 if (rec >= 3) { 10725 verbose(env, "max struct nesting depth exceeded\n"); 10726 return false; 10727 } 10728 if (!__btf_type_is_scalar_struct(env, btf, member_type, rec + 1)) 10729 return false; 10730 continue; 10731 } 10732 if (btf_type_is_array(member_type)) { 10733 array = btf_array(member_type); 10734 if (!array->nelems) 10735 return false; 10736 member_type = btf_type_skip_modifiers(btf, array->type, NULL); 10737 if (!btf_type_is_scalar(member_type)) 10738 return false; 10739 continue; 10740 } 10741 if (!btf_type_is_scalar(member_type)) 10742 return false; 10743 } 10744 return true; 10745 } 10746 10747 enum kfunc_ptr_arg_type { 10748 KF_ARG_PTR_TO_CTX, 10749 KF_ARG_PTR_TO_ALLOC_BTF_ID, /* Allocated object */ 10750 KF_ARG_PTR_TO_REFCOUNTED_KPTR, /* Refcounted local kptr */ 10751 KF_ARG_PTR_TO_DYNPTR, 10752 KF_ARG_PTR_TO_ITER, 10753 KF_ARG_PTR_TO_LIST_HEAD, 10754 KF_ARG_PTR_TO_LIST_NODE, 10755 KF_ARG_PTR_TO_BTF_ID, /* Also covers reg2btf_ids conversions */ 10756 KF_ARG_PTR_TO_MEM, 10757 KF_ARG_PTR_TO_MEM_SIZE, /* Size derived from next argument, skip it */ 10758 KF_ARG_PTR_TO_CALLBACK, 10759 KF_ARG_PTR_TO_RB_ROOT, 10760 KF_ARG_PTR_TO_RB_NODE, 10761 KF_ARG_PTR_TO_NULL, 10762 KF_ARG_PTR_TO_CONST_STR, 10763 }; 10764 10765 enum special_kfunc_type { 10766 KF_bpf_obj_new_impl, 10767 KF_bpf_obj_drop_impl, 10768 KF_bpf_refcount_acquire_impl, 10769 KF_bpf_list_push_front_impl, 10770 KF_bpf_list_push_back_impl, 10771 KF_bpf_list_pop_front, 10772 KF_bpf_list_pop_back, 10773 KF_bpf_cast_to_kern_ctx, 10774 KF_bpf_rdonly_cast, 10775 KF_bpf_rcu_read_lock, 10776 KF_bpf_rcu_read_unlock, 10777 KF_bpf_rbtree_remove, 10778 KF_bpf_rbtree_add_impl, 10779 KF_bpf_rbtree_first, 10780 KF_bpf_dynptr_from_skb, 10781 KF_bpf_dynptr_from_xdp, 10782 KF_bpf_dynptr_slice, 10783 KF_bpf_dynptr_slice_rdwr, 10784 KF_bpf_dynptr_clone, 10785 KF_bpf_percpu_obj_new_impl, 10786 KF_bpf_percpu_obj_drop_impl, 10787 KF_bpf_throw, 10788 KF_bpf_iter_css_task_new, 10789 }; 10790 10791 BTF_SET_START(special_kfunc_set) 10792 BTF_ID(func, bpf_obj_new_impl) 10793 BTF_ID(func, bpf_obj_drop_impl) 10794 BTF_ID(func, bpf_refcount_acquire_impl) 10795 BTF_ID(func, bpf_list_push_front_impl) 10796 BTF_ID(func, bpf_list_push_back_impl) 10797 BTF_ID(func, bpf_list_pop_front) 10798 BTF_ID(func, bpf_list_pop_back) 10799 BTF_ID(func, bpf_cast_to_kern_ctx) 10800 BTF_ID(func, bpf_rdonly_cast) 10801 BTF_ID(func, bpf_rbtree_remove) 10802 BTF_ID(func, bpf_rbtree_add_impl) 10803 BTF_ID(func, bpf_rbtree_first) 10804 BTF_ID(func, bpf_dynptr_from_skb) 10805 BTF_ID(func, bpf_dynptr_from_xdp) 10806 BTF_ID(func, bpf_dynptr_slice) 10807 BTF_ID(func, bpf_dynptr_slice_rdwr) 10808 BTF_ID(func, bpf_dynptr_clone) 10809 BTF_ID(func, bpf_percpu_obj_new_impl) 10810 BTF_ID(func, bpf_percpu_obj_drop_impl) 10811 BTF_ID(func, bpf_throw) 10812 #ifdef CONFIG_CGROUPS 10813 BTF_ID(func, bpf_iter_css_task_new) 10814 #endif 10815 BTF_SET_END(special_kfunc_set) 10816 10817 BTF_ID_LIST(special_kfunc_list) 10818 BTF_ID(func, bpf_obj_new_impl) 10819 BTF_ID(func, bpf_obj_drop_impl) 10820 BTF_ID(func, bpf_refcount_acquire_impl) 10821 BTF_ID(func, bpf_list_push_front_impl) 10822 BTF_ID(func, bpf_list_push_back_impl) 10823 BTF_ID(func, bpf_list_pop_front) 10824 BTF_ID(func, bpf_list_pop_back) 10825 BTF_ID(func, bpf_cast_to_kern_ctx) 10826 BTF_ID(func, bpf_rdonly_cast) 10827 BTF_ID(func, bpf_rcu_read_lock) 10828 BTF_ID(func, bpf_rcu_read_unlock) 10829 BTF_ID(func, bpf_rbtree_remove) 10830 BTF_ID(func, bpf_rbtree_add_impl) 10831 BTF_ID(func, bpf_rbtree_first) 10832 BTF_ID(func, bpf_dynptr_from_skb) 10833 BTF_ID(func, bpf_dynptr_from_xdp) 10834 BTF_ID(func, bpf_dynptr_slice) 10835 BTF_ID(func, bpf_dynptr_slice_rdwr) 10836 BTF_ID(func, bpf_dynptr_clone) 10837 BTF_ID(func, bpf_percpu_obj_new_impl) 10838 BTF_ID(func, bpf_percpu_obj_drop_impl) 10839 BTF_ID(func, bpf_throw) 10840 #ifdef CONFIG_CGROUPS 10841 BTF_ID(func, bpf_iter_css_task_new) 10842 #else 10843 BTF_ID_UNUSED 10844 #endif 10845 10846 static bool is_kfunc_ret_null(struct bpf_kfunc_call_arg_meta *meta) 10847 { 10848 if (meta->func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl] && 10849 meta->arg_owning_ref) { 10850 return false; 10851 } 10852 10853 return meta->kfunc_flags & KF_RET_NULL; 10854 } 10855 10856 static bool is_kfunc_bpf_rcu_read_lock(struct bpf_kfunc_call_arg_meta *meta) 10857 { 10858 return meta->func_id == special_kfunc_list[KF_bpf_rcu_read_lock]; 10859 } 10860 10861 static bool is_kfunc_bpf_rcu_read_unlock(struct bpf_kfunc_call_arg_meta *meta) 10862 { 10863 return meta->func_id == special_kfunc_list[KF_bpf_rcu_read_unlock]; 10864 } 10865 10866 static enum kfunc_ptr_arg_type 10867 get_kfunc_ptr_arg_type(struct bpf_verifier_env *env, 10868 struct bpf_kfunc_call_arg_meta *meta, 10869 const struct btf_type *t, const struct btf_type *ref_t, 10870 const char *ref_tname, const struct btf_param *args, 10871 int argno, int nargs) 10872 { 10873 u32 regno = argno + 1; 10874 struct bpf_reg_state *regs = cur_regs(env); 10875 struct bpf_reg_state *reg = ®s[regno]; 10876 bool arg_mem_size = false; 10877 10878 if (meta->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx]) 10879 return KF_ARG_PTR_TO_CTX; 10880 10881 /* In this function, we verify the kfunc's BTF as per the argument type, 10882 * leaving the rest of the verification with respect to the register 10883 * type to our caller. When a set of conditions hold in the BTF type of 10884 * arguments, we resolve it to a known kfunc_ptr_arg_type. 10885 */ 10886 if (btf_get_prog_ctx_type(&env->log, meta->btf, t, resolve_prog_type(env->prog), argno)) 10887 return KF_ARG_PTR_TO_CTX; 10888 10889 if (is_kfunc_arg_alloc_obj(meta->btf, &args[argno])) 10890 return KF_ARG_PTR_TO_ALLOC_BTF_ID; 10891 10892 if (is_kfunc_arg_refcounted_kptr(meta->btf, &args[argno])) 10893 return KF_ARG_PTR_TO_REFCOUNTED_KPTR; 10894 10895 if (is_kfunc_arg_dynptr(meta->btf, &args[argno])) 10896 return KF_ARG_PTR_TO_DYNPTR; 10897 10898 if (is_kfunc_arg_iter(meta, argno)) 10899 return KF_ARG_PTR_TO_ITER; 10900 10901 if (is_kfunc_arg_list_head(meta->btf, &args[argno])) 10902 return KF_ARG_PTR_TO_LIST_HEAD; 10903 10904 if (is_kfunc_arg_list_node(meta->btf, &args[argno])) 10905 return KF_ARG_PTR_TO_LIST_NODE; 10906 10907 if (is_kfunc_arg_rbtree_root(meta->btf, &args[argno])) 10908 return KF_ARG_PTR_TO_RB_ROOT; 10909 10910 if (is_kfunc_arg_rbtree_node(meta->btf, &args[argno])) 10911 return KF_ARG_PTR_TO_RB_NODE; 10912 10913 if (is_kfunc_arg_const_str(meta->btf, &args[argno])) 10914 return KF_ARG_PTR_TO_CONST_STR; 10915 10916 if ((base_type(reg->type) == PTR_TO_BTF_ID || reg2btf_ids[base_type(reg->type)])) { 10917 if (!btf_type_is_struct(ref_t)) { 10918 verbose(env, "kernel function %s args#%d pointer type %s %s is not supported\n", 10919 meta->func_name, argno, btf_type_str(ref_t), ref_tname); 10920 return -EINVAL; 10921 } 10922 return KF_ARG_PTR_TO_BTF_ID; 10923 } 10924 10925 if (is_kfunc_arg_callback(env, meta->btf, &args[argno])) 10926 return KF_ARG_PTR_TO_CALLBACK; 10927 10928 if (is_kfunc_arg_nullable(meta->btf, &args[argno]) && register_is_null(reg)) 10929 return KF_ARG_PTR_TO_NULL; 10930 10931 if (argno + 1 < nargs && 10932 (is_kfunc_arg_mem_size(meta->btf, &args[argno + 1], ®s[regno + 1]) || 10933 is_kfunc_arg_const_mem_size(meta->btf, &args[argno + 1], ®s[regno + 1]))) 10934 arg_mem_size = true; 10935 10936 /* This is the catch all argument type of register types supported by 10937 * check_helper_mem_access. However, we only allow when argument type is 10938 * pointer to scalar, or struct composed (recursively) of scalars. When 10939 * arg_mem_size is true, the pointer can be void *. 10940 */ 10941 if (!btf_type_is_scalar(ref_t) && !__btf_type_is_scalar_struct(env, meta->btf, ref_t, 0) && 10942 (arg_mem_size ? !btf_type_is_void(ref_t) : 1)) { 10943 verbose(env, "arg#%d pointer type %s %s must point to %sscalar, or struct with scalar\n", 10944 argno, btf_type_str(ref_t), ref_tname, arg_mem_size ? "void, " : ""); 10945 return -EINVAL; 10946 } 10947 return arg_mem_size ? KF_ARG_PTR_TO_MEM_SIZE : KF_ARG_PTR_TO_MEM; 10948 } 10949 10950 static int process_kf_arg_ptr_to_btf_id(struct bpf_verifier_env *env, 10951 struct bpf_reg_state *reg, 10952 const struct btf_type *ref_t, 10953 const char *ref_tname, u32 ref_id, 10954 struct bpf_kfunc_call_arg_meta *meta, 10955 int argno) 10956 { 10957 const struct btf_type *reg_ref_t; 10958 bool strict_type_match = false; 10959 const struct btf *reg_btf; 10960 const char *reg_ref_tname; 10961 u32 reg_ref_id; 10962 10963 if (base_type(reg->type) == PTR_TO_BTF_ID) { 10964 reg_btf = reg->btf; 10965 reg_ref_id = reg->btf_id; 10966 } else { 10967 reg_btf = btf_vmlinux; 10968 reg_ref_id = *reg2btf_ids[base_type(reg->type)]; 10969 } 10970 10971 /* Enforce strict type matching for calls to kfuncs that are acquiring 10972 * or releasing a reference, or are no-cast aliases. We do _not_ 10973 * enforce strict matching for plain KF_TRUSTED_ARGS kfuncs by default, 10974 * as we want to enable BPF programs to pass types that are bitwise 10975 * equivalent without forcing them to explicitly cast with something 10976 * like bpf_cast_to_kern_ctx(). 10977 * 10978 * For example, say we had a type like the following: 10979 * 10980 * struct bpf_cpumask { 10981 * cpumask_t cpumask; 10982 * refcount_t usage; 10983 * }; 10984 * 10985 * Note that as specified in <linux/cpumask.h>, cpumask_t is typedef'ed 10986 * to a struct cpumask, so it would be safe to pass a struct 10987 * bpf_cpumask * to a kfunc expecting a struct cpumask *. 10988 * 10989 * The philosophy here is similar to how we allow scalars of different 10990 * types to be passed to kfuncs as long as the size is the same. The 10991 * only difference here is that we're simply allowing 10992 * btf_struct_ids_match() to walk the struct at the 0th offset, and 10993 * resolve types. 10994 */ 10995 if (is_kfunc_acquire(meta) || 10996 (is_kfunc_release(meta) && reg->ref_obj_id) || 10997 btf_type_ids_nocast_alias(&env->log, reg_btf, reg_ref_id, meta->btf, ref_id)) 10998 strict_type_match = true; 10999 11000 WARN_ON_ONCE(is_kfunc_trusted_args(meta) && reg->off); 11001 11002 reg_ref_t = btf_type_skip_modifiers(reg_btf, reg_ref_id, ®_ref_id); 11003 reg_ref_tname = btf_name_by_offset(reg_btf, reg_ref_t->name_off); 11004 if (!btf_struct_ids_match(&env->log, reg_btf, reg_ref_id, reg->off, meta->btf, ref_id, strict_type_match)) { 11005 verbose(env, "kernel function %s args#%d expected pointer to %s %s but R%d has a pointer to %s %s\n", 11006 meta->func_name, argno, btf_type_str(ref_t), ref_tname, argno + 1, 11007 btf_type_str(reg_ref_t), reg_ref_tname); 11008 return -EINVAL; 11009 } 11010 return 0; 11011 } 11012 11013 static int ref_set_non_owning(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 11014 { 11015 struct bpf_verifier_state *state = env->cur_state; 11016 struct btf_record *rec = reg_btf_record(reg); 11017 11018 if (!state->active_lock.ptr) { 11019 verbose(env, "verifier internal error: ref_set_non_owning w/o active lock\n"); 11020 return -EFAULT; 11021 } 11022 11023 if (type_flag(reg->type) & NON_OWN_REF) { 11024 verbose(env, "verifier internal error: NON_OWN_REF already set\n"); 11025 return -EFAULT; 11026 } 11027 11028 reg->type |= NON_OWN_REF; 11029 if (rec->refcount_off >= 0) 11030 reg->type |= MEM_RCU; 11031 11032 return 0; 11033 } 11034 11035 static int ref_convert_owning_non_owning(struct bpf_verifier_env *env, u32 ref_obj_id) 11036 { 11037 struct bpf_func_state *state, *unused; 11038 struct bpf_reg_state *reg; 11039 int i; 11040 11041 state = cur_func(env); 11042 11043 if (!ref_obj_id) { 11044 verbose(env, "verifier internal error: ref_obj_id is zero for " 11045 "owning -> non-owning conversion\n"); 11046 return -EFAULT; 11047 } 11048 11049 for (i = 0; i < state->acquired_refs; i++) { 11050 if (state->refs[i].id != ref_obj_id) 11051 continue; 11052 11053 /* Clear ref_obj_id here so release_reference doesn't clobber 11054 * the whole reg 11055 */ 11056 bpf_for_each_reg_in_vstate(env->cur_state, unused, reg, ({ 11057 if (reg->ref_obj_id == ref_obj_id) { 11058 reg->ref_obj_id = 0; 11059 ref_set_non_owning(env, reg); 11060 } 11061 })); 11062 return 0; 11063 } 11064 11065 verbose(env, "verifier internal error: ref state missing for ref_obj_id\n"); 11066 return -EFAULT; 11067 } 11068 11069 /* Implementation details: 11070 * 11071 * Each register points to some region of memory, which we define as an 11072 * allocation. Each allocation may embed a bpf_spin_lock which protects any 11073 * special BPF objects (bpf_list_head, bpf_rb_root, etc.) part of the same 11074 * allocation. The lock and the data it protects are colocated in the same 11075 * memory region. 11076 * 11077 * Hence, everytime a register holds a pointer value pointing to such 11078 * allocation, the verifier preserves a unique reg->id for it. 11079 * 11080 * The verifier remembers the lock 'ptr' and the lock 'id' whenever 11081 * bpf_spin_lock is called. 11082 * 11083 * To enable this, lock state in the verifier captures two values: 11084 * active_lock.ptr = Register's type specific pointer 11085 * active_lock.id = A unique ID for each register pointer value 11086 * 11087 * Currently, PTR_TO_MAP_VALUE and PTR_TO_BTF_ID | MEM_ALLOC are the two 11088 * supported register types. 11089 * 11090 * The active_lock.ptr in case of map values is the reg->map_ptr, and in case of 11091 * allocated objects is the reg->btf pointer. 11092 * 11093 * The active_lock.id is non-unique for maps supporting direct_value_addr, as we 11094 * can establish the provenance of the map value statically for each distinct 11095 * lookup into such maps. They always contain a single map value hence unique 11096 * IDs for each pseudo load pessimizes the algorithm and rejects valid programs. 11097 * 11098 * So, in case of global variables, they use array maps with max_entries = 1, 11099 * hence their active_lock.ptr becomes map_ptr and id = 0 (since they all point 11100 * into the same map value as max_entries is 1, as described above). 11101 * 11102 * In case of inner map lookups, the inner map pointer has same map_ptr as the 11103 * outer map pointer (in verifier context), but each lookup into an inner map 11104 * assigns a fresh reg->id to the lookup, so while lookups into distinct inner 11105 * maps from the same outer map share the same map_ptr as active_lock.ptr, they 11106 * will get different reg->id assigned to each lookup, hence different 11107 * active_lock.id. 11108 * 11109 * In case of allocated objects, active_lock.ptr is the reg->btf, and the 11110 * reg->id is a unique ID preserved after the NULL pointer check on the pointer 11111 * returned from bpf_obj_new. Each allocation receives a new reg->id. 11112 */ 11113 static int check_reg_allocation_locked(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 11114 { 11115 void *ptr; 11116 u32 id; 11117 11118 switch ((int)reg->type) { 11119 case PTR_TO_MAP_VALUE: 11120 ptr = reg->map_ptr; 11121 break; 11122 case PTR_TO_BTF_ID | MEM_ALLOC: 11123 ptr = reg->btf; 11124 break; 11125 default: 11126 verbose(env, "verifier internal error: unknown reg type for lock check\n"); 11127 return -EFAULT; 11128 } 11129 id = reg->id; 11130 11131 if (!env->cur_state->active_lock.ptr) 11132 return -EINVAL; 11133 if (env->cur_state->active_lock.ptr != ptr || 11134 env->cur_state->active_lock.id != id) { 11135 verbose(env, "held lock and object are not in the same allocation\n"); 11136 return -EINVAL; 11137 } 11138 return 0; 11139 } 11140 11141 static bool is_bpf_list_api_kfunc(u32 btf_id) 11142 { 11143 return btf_id == special_kfunc_list[KF_bpf_list_push_front_impl] || 11144 btf_id == special_kfunc_list[KF_bpf_list_push_back_impl] || 11145 btf_id == special_kfunc_list[KF_bpf_list_pop_front] || 11146 btf_id == special_kfunc_list[KF_bpf_list_pop_back]; 11147 } 11148 11149 static bool is_bpf_rbtree_api_kfunc(u32 btf_id) 11150 { 11151 return btf_id == special_kfunc_list[KF_bpf_rbtree_add_impl] || 11152 btf_id == special_kfunc_list[KF_bpf_rbtree_remove] || 11153 btf_id == special_kfunc_list[KF_bpf_rbtree_first]; 11154 } 11155 11156 static bool is_bpf_graph_api_kfunc(u32 btf_id) 11157 { 11158 return is_bpf_list_api_kfunc(btf_id) || is_bpf_rbtree_api_kfunc(btf_id) || 11159 btf_id == special_kfunc_list[KF_bpf_refcount_acquire_impl]; 11160 } 11161 11162 static bool is_sync_callback_calling_kfunc(u32 btf_id) 11163 { 11164 return btf_id == special_kfunc_list[KF_bpf_rbtree_add_impl]; 11165 } 11166 11167 static bool is_bpf_throw_kfunc(struct bpf_insn *insn) 11168 { 11169 return bpf_pseudo_kfunc_call(insn) && insn->off == 0 && 11170 insn->imm == special_kfunc_list[KF_bpf_throw]; 11171 } 11172 11173 static bool is_rbtree_lock_required_kfunc(u32 btf_id) 11174 { 11175 return is_bpf_rbtree_api_kfunc(btf_id); 11176 } 11177 11178 static bool check_kfunc_is_graph_root_api(struct bpf_verifier_env *env, 11179 enum btf_field_type head_field_type, 11180 u32 kfunc_btf_id) 11181 { 11182 bool ret; 11183 11184 switch (head_field_type) { 11185 case BPF_LIST_HEAD: 11186 ret = is_bpf_list_api_kfunc(kfunc_btf_id); 11187 break; 11188 case BPF_RB_ROOT: 11189 ret = is_bpf_rbtree_api_kfunc(kfunc_btf_id); 11190 break; 11191 default: 11192 verbose(env, "verifier internal error: unexpected graph root argument type %s\n", 11193 btf_field_type_name(head_field_type)); 11194 return false; 11195 } 11196 11197 if (!ret) 11198 verbose(env, "verifier internal error: %s head arg for unknown kfunc\n", 11199 btf_field_type_name(head_field_type)); 11200 return ret; 11201 } 11202 11203 static bool check_kfunc_is_graph_node_api(struct bpf_verifier_env *env, 11204 enum btf_field_type node_field_type, 11205 u32 kfunc_btf_id) 11206 { 11207 bool ret; 11208 11209 switch (node_field_type) { 11210 case BPF_LIST_NODE: 11211 ret = (kfunc_btf_id == special_kfunc_list[KF_bpf_list_push_front_impl] || 11212 kfunc_btf_id == special_kfunc_list[KF_bpf_list_push_back_impl]); 11213 break; 11214 case BPF_RB_NODE: 11215 ret = (kfunc_btf_id == special_kfunc_list[KF_bpf_rbtree_remove] || 11216 kfunc_btf_id == special_kfunc_list[KF_bpf_rbtree_add_impl]); 11217 break; 11218 default: 11219 verbose(env, "verifier internal error: unexpected graph node argument type %s\n", 11220 btf_field_type_name(node_field_type)); 11221 return false; 11222 } 11223 11224 if (!ret) 11225 verbose(env, "verifier internal error: %s node arg for unknown kfunc\n", 11226 btf_field_type_name(node_field_type)); 11227 return ret; 11228 } 11229 11230 static int 11231 __process_kf_arg_ptr_to_graph_root(struct bpf_verifier_env *env, 11232 struct bpf_reg_state *reg, u32 regno, 11233 struct bpf_kfunc_call_arg_meta *meta, 11234 enum btf_field_type head_field_type, 11235 struct btf_field **head_field) 11236 { 11237 const char *head_type_name; 11238 struct btf_field *field; 11239 struct btf_record *rec; 11240 u32 head_off; 11241 11242 if (meta->btf != btf_vmlinux) { 11243 verbose(env, "verifier internal error: unexpected btf mismatch in kfunc call\n"); 11244 return -EFAULT; 11245 } 11246 11247 if (!check_kfunc_is_graph_root_api(env, head_field_type, meta->func_id)) 11248 return -EFAULT; 11249 11250 head_type_name = btf_field_type_name(head_field_type); 11251 if (!tnum_is_const(reg->var_off)) { 11252 verbose(env, 11253 "R%d doesn't have constant offset. %s has to be at the constant offset\n", 11254 regno, head_type_name); 11255 return -EINVAL; 11256 } 11257 11258 rec = reg_btf_record(reg); 11259 head_off = reg->off + reg->var_off.value; 11260 field = btf_record_find(rec, head_off, head_field_type); 11261 if (!field) { 11262 verbose(env, "%s not found at offset=%u\n", head_type_name, head_off); 11263 return -EINVAL; 11264 } 11265 11266 /* All functions require bpf_list_head to be protected using a bpf_spin_lock */ 11267 if (check_reg_allocation_locked(env, reg)) { 11268 verbose(env, "bpf_spin_lock at off=%d must be held for %s\n", 11269 rec->spin_lock_off, head_type_name); 11270 return -EINVAL; 11271 } 11272 11273 if (*head_field) { 11274 verbose(env, "verifier internal error: repeating %s arg\n", head_type_name); 11275 return -EFAULT; 11276 } 11277 *head_field = field; 11278 return 0; 11279 } 11280 11281 static int process_kf_arg_ptr_to_list_head(struct bpf_verifier_env *env, 11282 struct bpf_reg_state *reg, u32 regno, 11283 struct bpf_kfunc_call_arg_meta *meta) 11284 { 11285 return __process_kf_arg_ptr_to_graph_root(env, reg, regno, meta, BPF_LIST_HEAD, 11286 &meta->arg_list_head.field); 11287 } 11288 11289 static int process_kf_arg_ptr_to_rbtree_root(struct bpf_verifier_env *env, 11290 struct bpf_reg_state *reg, u32 regno, 11291 struct bpf_kfunc_call_arg_meta *meta) 11292 { 11293 return __process_kf_arg_ptr_to_graph_root(env, reg, regno, meta, BPF_RB_ROOT, 11294 &meta->arg_rbtree_root.field); 11295 } 11296 11297 static int 11298 __process_kf_arg_ptr_to_graph_node(struct bpf_verifier_env *env, 11299 struct bpf_reg_state *reg, u32 regno, 11300 struct bpf_kfunc_call_arg_meta *meta, 11301 enum btf_field_type head_field_type, 11302 enum btf_field_type node_field_type, 11303 struct btf_field **node_field) 11304 { 11305 const char *node_type_name; 11306 const struct btf_type *et, *t; 11307 struct btf_field *field; 11308 u32 node_off; 11309 11310 if (meta->btf != btf_vmlinux) { 11311 verbose(env, "verifier internal error: unexpected btf mismatch in kfunc call\n"); 11312 return -EFAULT; 11313 } 11314 11315 if (!check_kfunc_is_graph_node_api(env, node_field_type, meta->func_id)) 11316 return -EFAULT; 11317 11318 node_type_name = btf_field_type_name(node_field_type); 11319 if (!tnum_is_const(reg->var_off)) { 11320 verbose(env, 11321 "R%d doesn't have constant offset. %s has to be at the constant offset\n", 11322 regno, node_type_name); 11323 return -EINVAL; 11324 } 11325 11326 node_off = reg->off + reg->var_off.value; 11327 field = reg_find_field_offset(reg, node_off, node_field_type); 11328 if (!field || field->offset != node_off) { 11329 verbose(env, "%s not found at offset=%u\n", node_type_name, node_off); 11330 return -EINVAL; 11331 } 11332 11333 field = *node_field; 11334 11335 et = btf_type_by_id(field->graph_root.btf, field->graph_root.value_btf_id); 11336 t = btf_type_by_id(reg->btf, reg->btf_id); 11337 if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, 0, field->graph_root.btf, 11338 field->graph_root.value_btf_id, true)) { 11339 verbose(env, "operation on %s expects arg#1 %s at offset=%d " 11340 "in struct %s, but arg is at offset=%d in struct %s\n", 11341 btf_field_type_name(head_field_type), 11342 btf_field_type_name(node_field_type), 11343 field->graph_root.node_offset, 11344 btf_name_by_offset(field->graph_root.btf, et->name_off), 11345 node_off, btf_name_by_offset(reg->btf, t->name_off)); 11346 return -EINVAL; 11347 } 11348 meta->arg_btf = reg->btf; 11349 meta->arg_btf_id = reg->btf_id; 11350 11351 if (node_off != field->graph_root.node_offset) { 11352 verbose(env, "arg#1 offset=%d, but expected %s at offset=%d in struct %s\n", 11353 node_off, btf_field_type_name(node_field_type), 11354 field->graph_root.node_offset, 11355 btf_name_by_offset(field->graph_root.btf, et->name_off)); 11356 return -EINVAL; 11357 } 11358 11359 return 0; 11360 } 11361 11362 static int process_kf_arg_ptr_to_list_node(struct bpf_verifier_env *env, 11363 struct bpf_reg_state *reg, u32 regno, 11364 struct bpf_kfunc_call_arg_meta *meta) 11365 { 11366 return __process_kf_arg_ptr_to_graph_node(env, reg, regno, meta, 11367 BPF_LIST_HEAD, BPF_LIST_NODE, 11368 &meta->arg_list_head.field); 11369 } 11370 11371 static int process_kf_arg_ptr_to_rbtree_node(struct bpf_verifier_env *env, 11372 struct bpf_reg_state *reg, u32 regno, 11373 struct bpf_kfunc_call_arg_meta *meta) 11374 { 11375 return __process_kf_arg_ptr_to_graph_node(env, reg, regno, meta, 11376 BPF_RB_ROOT, BPF_RB_NODE, 11377 &meta->arg_rbtree_root.field); 11378 } 11379 11380 /* 11381 * css_task iter allowlist is needed to avoid dead locking on css_set_lock. 11382 * LSM hooks and iters (both sleepable and non-sleepable) are safe. 11383 * Any sleepable progs are also safe since bpf_check_attach_target() enforce 11384 * them can only be attached to some specific hook points. 11385 */ 11386 static bool check_css_task_iter_allowlist(struct bpf_verifier_env *env) 11387 { 11388 enum bpf_prog_type prog_type = resolve_prog_type(env->prog); 11389 11390 switch (prog_type) { 11391 case BPF_PROG_TYPE_LSM: 11392 return true; 11393 case BPF_PROG_TYPE_TRACING: 11394 if (env->prog->expected_attach_type == BPF_TRACE_ITER) 11395 return true; 11396 fallthrough; 11397 default: 11398 return env->prog->aux->sleepable; 11399 } 11400 } 11401 11402 static int check_kfunc_args(struct bpf_verifier_env *env, struct bpf_kfunc_call_arg_meta *meta, 11403 int insn_idx) 11404 { 11405 const char *func_name = meta->func_name, *ref_tname; 11406 const struct btf *btf = meta->btf; 11407 const struct btf_param *args; 11408 struct btf_record *rec; 11409 u32 i, nargs; 11410 int ret; 11411 11412 args = (const struct btf_param *)(meta->func_proto + 1); 11413 nargs = btf_type_vlen(meta->func_proto); 11414 if (nargs > MAX_BPF_FUNC_REG_ARGS) { 11415 verbose(env, "Function %s has %d > %d args\n", func_name, nargs, 11416 MAX_BPF_FUNC_REG_ARGS); 11417 return -EINVAL; 11418 } 11419 11420 /* Check that BTF function arguments match actual types that the 11421 * verifier sees. 11422 */ 11423 for (i = 0; i < nargs; i++) { 11424 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[i + 1]; 11425 const struct btf_type *t, *ref_t, *resolve_ret; 11426 enum bpf_arg_type arg_type = ARG_DONTCARE; 11427 u32 regno = i + 1, ref_id, type_size; 11428 bool is_ret_buf_sz = false; 11429 int kf_arg_type; 11430 11431 t = btf_type_skip_modifiers(btf, args[i].type, NULL); 11432 11433 if (is_kfunc_arg_ignore(btf, &args[i])) 11434 continue; 11435 11436 if (btf_type_is_scalar(t)) { 11437 if (reg->type != SCALAR_VALUE) { 11438 verbose(env, "R%d is not a scalar\n", regno); 11439 return -EINVAL; 11440 } 11441 11442 if (is_kfunc_arg_constant(meta->btf, &args[i])) { 11443 if (meta->arg_constant.found) { 11444 verbose(env, "verifier internal error: only one constant argument permitted\n"); 11445 return -EFAULT; 11446 } 11447 if (!tnum_is_const(reg->var_off)) { 11448 verbose(env, "R%d must be a known constant\n", regno); 11449 return -EINVAL; 11450 } 11451 ret = mark_chain_precision(env, regno); 11452 if (ret < 0) 11453 return ret; 11454 meta->arg_constant.found = true; 11455 meta->arg_constant.value = reg->var_off.value; 11456 } else if (is_kfunc_arg_scalar_with_name(btf, &args[i], "rdonly_buf_size")) { 11457 meta->r0_rdonly = true; 11458 is_ret_buf_sz = true; 11459 } else if (is_kfunc_arg_scalar_with_name(btf, &args[i], "rdwr_buf_size")) { 11460 is_ret_buf_sz = true; 11461 } 11462 11463 if (is_ret_buf_sz) { 11464 if (meta->r0_size) { 11465 verbose(env, "2 or more rdonly/rdwr_buf_size parameters for kfunc"); 11466 return -EINVAL; 11467 } 11468 11469 if (!tnum_is_const(reg->var_off)) { 11470 verbose(env, "R%d is not a const\n", regno); 11471 return -EINVAL; 11472 } 11473 11474 meta->r0_size = reg->var_off.value; 11475 ret = mark_chain_precision(env, regno); 11476 if (ret) 11477 return ret; 11478 } 11479 continue; 11480 } 11481 11482 if (!btf_type_is_ptr(t)) { 11483 verbose(env, "Unrecognized arg#%d type %s\n", i, btf_type_str(t)); 11484 return -EINVAL; 11485 } 11486 11487 if ((is_kfunc_trusted_args(meta) || is_kfunc_rcu(meta)) && 11488 (register_is_null(reg) || type_may_be_null(reg->type)) && 11489 !is_kfunc_arg_nullable(meta->btf, &args[i])) { 11490 verbose(env, "Possibly NULL pointer passed to trusted arg%d\n", i); 11491 return -EACCES; 11492 } 11493 11494 if (reg->ref_obj_id) { 11495 if (is_kfunc_release(meta) && meta->ref_obj_id) { 11496 verbose(env, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n", 11497 regno, reg->ref_obj_id, 11498 meta->ref_obj_id); 11499 return -EFAULT; 11500 } 11501 meta->ref_obj_id = reg->ref_obj_id; 11502 if (is_kfunc_release(meta)) 11503 meta->release_regno = regno; 11504 } 11505 11506 ref_t = btf_type_skip_modifiers(btf, t->type, &ref_id); 11507 ref_tname = btf_name_by_offset(btf, ref_t->name_off); 11508 11509 kf_arg_type = get_kfunc_ptr_arg_type(env, meta, t, ref_t, ref_tname, args, i, nargs); 11510 if (kf_arg_type < 0) 11511 return kf_arg_type; 11512 11513 switch (kf_arg_type) { 11514 case KF_ARG_PTR_TO_NULL: 11515 continue; 11516 case KF_ARG_PTR_TO_ALLOC_BTF_ID: 11517 case KF_ARG_PTR_TO_BTF_ID: 11518 if (!is_kfunc_trusted_args(meta) && !is_kfunc_rcu(meta)) 11519 break; 11520 11521 if (!is_trusted_reg(reg)) { 11522 if (!is_kfunc_rcu(meta)) { 11523 verbose(env, "R%d must be referenced or trusted\n", regno); 11524 return -EINVAL; 11525 } 11526 if (!is_rcu_reg(reg)) { 11527 verbose(env, "R%d must be a rcu pointer\n", regno); 11528 return -EINVAL; 11529 } 11530 } 11531 11532 fallthrough; 11533 case KF_ARG_PTR_TO_CTX: 11534 /* Trusted arguments have the same offset checks as release arguments */ 11535 arg_type |= OBJ_RELEASE; 11536 break; 11537 case KF_ARG_PTR_TO_DYNPTR: 11538 case KF_ARG_PTR_TO_ITER: 11539 case KF_ARG_PTR_TO_LIST_HEAD: 11540 case KF_ARG_PTR_TO_LIST_NODE: 11541 case KF_ARG_PTR_TO_RB_ROOT: 11542 case KF_ARG_PTR_TO_RB_NODE: 11543 case KF_ARG_PTR_TO_MEM: 11544 case KF_ARG_PTR_TO_MEM_SIZE: 11545 case KF_ARG_PTR_TO_CALLBACK: 11546 case KF_ARG_PTR_TO_REFCOUNTED_KPTR: 11547 case KF_ARG_PTR_TO_CONST_STR: 11548 /* Trusted by default */ 11549 break; 11550 default: 11551 WARN_ON_ONCE(1); 11552 return -EFAULT; 11553 } 11554 11555 if (is_kfunc_release(meta) && reg->ref_obj_id) 11556 arg_type |= OBJ_RELEASE; 11557 ret = check_func_arg_reg_off(env, reg, regno, arg_type); 11558 if (ret < 0) 11559 return ret; 11560 11561 switch (kf_arg_type) { 11562 case KF_ARG_PTR_TO_CTX: 11563 if (reg->type != PTR_TO_CTX) { 11564 verbose(env, "arg#%d expected pointer to ctx, but got %s\n", i, btf_type_str(t)); 11565 return -EINVAL; 11566 } 11567 11568 if (meta->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx]) { 11569 ret = get_kern_ctx_btf_id(&env->log, resolve_prog_type(env->prog)); 11570 if (ret < 0) 11571 return -EINVAL; 11572 meta->ret_btf_id = ret; 11573 } 11574 break; 11575 case KF_ARG_PTR_TO_ALLOC_BTF_ID: 11576 if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC)) { 11577 if (meta->func_id != special_kfunc_list[KF_bpf_obj_drop_impl]) { 11578 verbose(env, "arg#%d expected for bpf_obj_drop_impl()\n", i); 11579 return -EINVAL; 11580 } 11581 } else if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC | MEM_PERCPU)) { 11582 if (meta->func_id != special_kfunc_list[KF_bpf_percpu_obj_drop_impl]) { 11583 verbose(env, "arg#%d expected for bpf_percpu_obj_drop_impl()\n", i); 11584 return -EINVAL; 11585 } 11586 } else { 11587 verbose(env, "arg#%d expected pointer to allocated object\n", i); 11588 return -EINVAL; 11589 } 11590 if (!reg->ref_obj_id) { 11591 verbose(env, "allocated object must be referenced\n"); 11592 return -EINVAL; 11593 } 11594 if (meta->btf == btf_vmlinux) { 11595 meta->arg_btf = reg->btf; 11596 meta->arg_btf_id = reg->btf_id; 11597 } 11598 break; 11599 case KF_ARG_PTR_TO_DYNPTR: 11600 { 11601 enum bpf_arg_type dynptr_arg_type = ARG_PTR_TO_DYNPTR; 11602 int clone_ref_obj_id = 0; 11603 11604 if (reg->type != PTR_TO_STACK && 11605 reg->type != CONST_PTR_TO_DYNPTR) { 11606 verbose(env, "arg#%d expected pointer to stack or dynptr_ptr\n", i); 11607 return -EINVAL; 11608 } 11609 11610 if (reg->type == CONST_PTR_TO_DYNPTR) 11611 dynptr_arg_type |= MEM_RDONLY; 11612 11613 if (is_kfunc_arg_uninit(btf, &args[i])) 11614 dynptr_arg_type |= MEM_UNINIT; 11615 11616 if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_from_skb]) { 11617 dynptr_arg_type |= DYNPTR_TYPE_SKB; 11618 } else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_from_xdp]) { 11619 dynptr_arg_type |= DYNPTR_TYPE_XDP; 11620 } else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_clone] && 11621 (dynptr_arg_type & MEM_UNINIT)) { 11622 enum bpf_dynptr_type parent_type = meta->initialized_dynptr.type; 11623 11624 if (parent_type == BPF_DYNPTR_TYPE_INVALID) { 11625 verbose(env, "verifier internal error: no dynptr type for parent of clone\n"); 11626 return -EFAULT; 11627 } 11628 11629 dynptr_arg_type |= (unsigned int)get_dynptr_type_flag(parent_type); 11630 clone_ref_obj_id = meta->initialized_dynptr.ref_obj_id; 11631 if (dynptr_type_refcounted(parent_type) && !clone_ref_obj_id) { 11632 verbose(env, "verifier internal error: missing ref obj id for parent of clone\n"); 11633 return -EFAULT; 11634 } 11635 } 11636 11637 ret = process_dynptr_func(env, regno, insn_idx, dynptr_arg_type, clone_ref_obj_id); 11638 if (ret < 0) 11639 return ret; 11640 11641 if (!(dynptr_arg_type & MEM_UNINIT)) { 11642 int id = dynptr_id(env, reg); 11643 11644 if (id < 0) { 11645 verbose(env, "verifier internal error: failed to obtain dynptr id\n"); 11646 return id; 11647 } 11648 meta->initialized_dynptr.id = id; 11649 meta->initialized_dynptr.type = dynptr_get_type(env, reg); 11650 meta->initialized_dynptr.ref_obj_id = dynptr_ref_obj_id(env, reg); 11651 } 11652 11653 break; 11654 } 11655 case KF_ARG_PTR_TO_ITER: 11656 if (meta->func_id == special_kfunc_list[KF_bpf_iter_css_task_new]) { 11657 if (!check_css_task_iter_allowlist(env)) { 11658 verbose(env, "css_task_iter is only allowed in bpf_lsm, bpf_iter and sleepable progs\n"); 11659 return -EINVAL; 11660 } 11661 } 11662 ret = process_iter_arg(env, regno, insn_idx, meta); 11663 if (ret < 0) 11664 return ret; 11665 break; 11666 case KF_ARG_PTR_TO_LIST_HEAD: 11667 if (reg->type != PTR_TO_MAP_VALUE && 11668 reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) { 11669 verbose(env, "arg#%d expected pointer to map value or allocated object\n", i); 11670 return -EINVAL; 11671 } 11672 if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC) && !reg->ref_obj_id) { 11673 verbose(env, "allocated object must be referenced\n"); 11674 return -EINVAL; 11675 } 11676 ret = process_kf_arg_ptr_to_list_head(env, reg, regno, meta); 11677 if (ret < 0) 11678 return ret; 11679 break; 11680 case KF_ARG_PTR_TO_RB_ROOT: 11681 if (reg->type != PTR_TO_MAP_VALUE && 11682 reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) { 11683 verbose(env, "arg#%d expected pointer to map value or allocated object\n", i); 11684 return -EINVAL; 11685 } 11686 if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC) && !reg->ref_obj_id) { 11687 verbose(env, "allocated object must be referenced\n"); 11688 return -EINVAL; 11689 } 11690 ret = process_kf_arg_ptr_to_rbtree_root(env, reg, regno, meta); 11691 if (ret < 0) 11692 return ret; 11693 break; 11694 case KF_ARG_PTR_TO_LIST_NODE: 11695 if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) { 11696 verbose(env, "arg#%d expected pointer to allocated object\n", i); 11697 return -EINVAL; 11698 } 11699 if (!reg->ref_obj_id) { 11700 verbose(env, "allocated object must be referenced\n"); 11701 return -EINVAL; 11702 } 11703 ret = process_kf_arg_ptr_to_list_node(env, reg, regno, meta); 11704 if (ret < 0) 11705 return ret; 11706 break; 11707 case KF_ARG_PTR_TO_RB_NODE: 11708 if (meta->func_id == special_kfunc_list[KF_bpf_rbtree_remove]) { 11709 if (!type_is_non_owning_ref(reg->type) || reg->ref_obj_id) { 11710 verbose(env, "rbtree_remove node input must be non-owning ref\n"); 11711 return -EINVAL; 11712 } 11713 if (in_rbtree_lock_required_cb(env)) { 11714 verbose(env, "rbtree_remove not allowed in rbtree cb\n"); 11715 return -EINVAL; 11716 } 11717 } else { 11718 if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) { 11719 verbose(env, "arg#%d expected pointer to allocated object\n", i); 11720 return -EINVAL; 11721 } 11722 if (!reg->ref_obj_id) { 11723 verbose(env, "allocated object must be referenced\n"); 11724 return -EINVAL; 11725 } 11726 } 11727 11728 ret = process_kf_arg_ptr_to_rbtree_node(env, reg, regno, meta); 11729 if (ret < 0) 11730 return ret; 11731 break; 11732 case KF_ARG_PTR_TO_BTF_ID: 11733 /* Only base_type is checked, further checks are done here */ 11734 if ((base_type(reg->type) != PTR_TO_BTF_ID || 11735 (bpf_type_has_unsafe_modifiers(reg->type) && !is_rcu_reg(reg))) && 11736 !reg2btf_ids[base_type(reg->type)]) { 11737 verbose(env, "arg#%d is %s ", i, reg_type_str(env, reg->type)); 11738 verbose(env, "expected %s or socket\n", 11739 reg_type_str(env, base_type(reg->type) | 11740 (type_flag(reg->type) & BPF_REG_TRUSTED_MODIFIERS))); 11741 return -EINVAL; 11742 } 11743 ret = process_kf_arg_ptr_to_btf_id(env, reg, ref_t, ref_tname, ref_id, meta, i); 11744 if (ret < 0) 11745 return ret; 11746 break; 11747 case KF_ARG_PTR_TO_MEM: 11748 resolve_ret = btf_resolve_size(btf, ref_t, &type_size); 11749 if (IS_ERR(resolve_ret)) { 11750 verbose(env, "arg#%d reference type('%s %s') size cannot be determined: %ld\n", 11751 i, btf_type_str(ref_t), ref_tname, PTR_ERR(resolve_ret)); 11752 return -EINVAL; 11753 } 11754 ret = check_mem_reg(env, reg, regno, type_size); 11755 if (ret < 0) 11756 return ret; 11757 break; 11758 case KF_ARG_PTR_TO_MEM_SIZE: 11759 { 11760 struct bpf_reg_state *buff_reg = ®s[regno]; 11761 const struct btf_param *buff_arg = &args[i]; 11762 struct bpf_reg_state *size_reg = ®s[regno + 1]; 11763 const struct btf_param *size_arg = &args[i + 1]; 11764 11765 if (!register_is_null(buff_reg) || !is_kfunc_arg_optional(meta->btf, buff_arg)) { 11766 ret = check_kfunc_mem_size_reg(env, size_reg, regno + 1); 11767 if (ret < 0) { 11768 verbose(env, "arg#%d arg#%d memory, len pair leads to invalid memory access\n", i, i + 1); 11769 return ret; 11770 } 11771 } 11772 11773 if (is_kfunc_arg_const_mem_size(meta->btf, size_arg, size_reg)) { 11774 if (meta->arg_constant.found) { 11775 verbose(env, "verifier internal error: only one constant argument permitted\n"); 11776 return -EFAULT; 11777 } 11778 if (!tnum_is_const(size_reg->var_off)) { 11779 verbose(env, "R%d must be a known constant\n", regno + 1); 11780 return -EINVAL; 11781 } 11782 meta->arg_constant.found = true; 11783 meta->arg_constant.value = size_reg->var_off.value; 11784 } 11785 11786 /* Skip next '__sz' or '__szk' argument */ 11787 i++; 11788 break; 11789 } 11790 case KF_ARG_PTR_TO_CALLBACK: 11791 if (reg->type != PTR_TO_FUNC) { 11792 verbose(env, "arg%d expected pointer to func\n", i); 11793 return -EINVAL; 11794 } 11795 meta->subprogno = reg->subprogno; 11796 break; 11797 case KF_ARG_PTR_TO_REFCOUNTED_KPTR: 11798 if (!type_is_ptr_alloc_obj(reg->type)) { 11799 verbose(env, "arg#%d is neither owning or non-owning ref\n", i); 11800 return -EINVAL; 11801 } 11802 if (!type_is_non_owning_ref(reg->type)) 11803 meta->arg_owning_ref = true; 11804 11805 rec = reg_btf_record(reg); 11806 if (!rec) { 11807 verbose(env, "verifier internal error: Couldn't find btf_record\n"); 11808 return -EFAULT; 11809 } 11810 11811 if (rec->refcount_off < 0) { 11812 verbose(env, "arg#%d doesn't point to a type with bpf_refcount field\n", i); 11813 return -EINVAL; 11814 } 11815 11816 meta->arg_btf = reg->btf; 11817 meta->arg_btf_id = reg->btf_id; 11818 break; 11819 case KF_ARG_PTR_TO_CONST_STR: 11820 if (reg->type != PTR_TO_MAP_VALUE) { 11821 verbose(env, "arg#%d doesn't point to a const string\n", i); 11822 return -EINVAL; 11823 } 11824 ret = check_reg_const_str(env, reg, regno); 11825 if (ret) 11826 return ret; 11827 break; 11828 } 11829 } 11830 11831 if (is_kfunc_release(meta) && !meta->release_regno) { 11832 verbose(env, "release kernel function %s expects refcounted PTR_TO_BTF_ID\n", 11833 func_name); 11834 return -EINVAL; 11835 } 11836 11837 return 0; 11838 } 11839 11840 static int fetch_kfunc_meta(struct bpf_verifier_env *env, 11841 struct bpf_insn *insn, 11842 struct bpf_kfunc_call_arg_meta *meta, 11843 const char **kfunc_name) 11844 { 11845 const struct btf_type *func, *func_proto; 11846 u32 func_id, *kfunc_flags; 11847 const char *func_name; 11848 struct btf *desc_btf; 11849 11850 if (kfunc_name) 11851 *kfunc_name = NULL; 11852 11853 if (!insn->imm) 11854 return -EINVAL; 11855 11856 desc_btf = find_kfunc_desc_btf(env, insn->off); 11857 if (IS_ERR(desc_btf)) 11858 return PTR_ERR(desc_btf); 11859 11860 func_id = insn->imm; 11861 func = btf_type_by_id(desc_btf, func_id); 11862 func_name = btf_name_by_offset(desc_btf, func->name_off); 11863 if (kfunc_name) 11864 *kfunc_name = func_name; 11865 func_proto = btf_type_by_id(desc_btf, func->type); 11866 11867 kfunc_flags = btf_kfunc_id_set_contains(desc_btf, func_id, env->prog); 11868 if (!kfunc_flags) { 11869 return -EACCES; 11870 } 11871 11872 memset(meta, 0, sizeof(*meta)); 11873 meta->btf = desc_btf; 11874 meta->func_id = func_id; 11875 meta->kfunc_flags = *kfunc_flags; 11876 meta->func_proto = func_proto; 11877 meta->func_name = func_name; 11878 11879 return 0; 11880 } 11881 11882 static int check_return_code(struct bpf_verifier_env *env, int regno, const char *reg_name); 11883 11884 static int check_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn, 11885 int *insn_idx_p) 11886 { 11887 const struct btf_type *t, *ptr_type; 11888 u32 i, nargs, ptr_type_id, release_ref_obj_id; 11889 struct bpf_reg_state *regs = cur_regs(env); 11890 const char *func_name, *ptr_type_name; 11891 bool sleepable, rcu_lock, rcu_unlock; 11892 struct bpf_kfunc_call_arg_meta meta; 11893 struct bpf_insn_aux_data *insn_aux; 11894 int err, insn_idx = *insn_idx_p; 11895 const struct btf_param *args; 11896 const struct btf_type *ret_t; 11897 struct btf *desc_btf; 11898 11899 /* skip for now, but return error when we find this in fixup_kfunc_call */ 11900 if (!insn->imm) 11901 return 0; 11902 11903 err = fetch_kfunc_meta(env, insn, &meta, &func_name); 11904 if (err == -EACCES && func_name) 11905 verbose(env, "calling kernel function %s is not allowed\n", func_name); 11906 if (err) 11907 return err; 11908 desc_btf = meta.btf; 11909 insn_aux = &env->insn_aux_data[insn_idx]; 11910 11911 insn_aux->is_iter_next = is_iter_next_kfunc(&meta); 11912 11913 if (is_kfunc_destructive(&meta) && !capable(CAP_SYS_BOOT)) { 11914 verbose(env, "destructive kfunc calls require CAP_SYS_BOOT capability\n"); 11915 return -EACCES; 11916 } 11917 11918 sleepable = is_kfunc_sleepable(&meta); 11919 if (sleepable && !env->prog->aux->sleepable) { 11920 verbose(env, "program must be sleepable to call sleepable kfunc %s\n", func_name); 11921 return -EACCES; 11922 } 11923 11924 /* Check the arguments */ 11925 err = check_kfunc_args(env, &meta, insn_idx); 11926 if (err < 0) 11927 return err; 11928 11929 if (meta.func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) { 11930 err = push_callback_call(env, insn, insn_idx, meta.subprogno, 11931 set_rbtree_add_callback_state); 11932 if (err) { 11933 verbose(env, "kfunc %s#%d failed callback verification\n", 11934 func_name, meta.func_id); 11935 return err; 11936 } 11937 } 11938 11939 rcu_lock = is_kfunc_bpf_rcu_read_lock(&meta); 11940 rcu_unlock = is_kfunc_bpf_rcu_read_unlock(&meta); 11941 11942 if (env->cur_state->active_rcu_lock) { 11943 struct bpf_func_state *state; 11944 struct bpf_reg_state *reg; 11945 u32 clear_mask = (1 << STACK_SPILL) | (1 << STACK_ITER); 11946 11947 if (in_rbtree_lock_required_cb(env) && (rcu_lock || rcu_unlock)) { 11948 verbose(env, "Calling bpf_rcu_read_{lock,unlock} in unnecessary rbtree callback\n"); 11949 return -EACCES; 11950 } 11951 11952 if (rcu_lock) { 11953 verbose(env, "nested rcu read lock (kernel function %s)\n", func_name); 11954 return -EINVAL; 11955 } else if (rcu_unlock) { 11956 bpf_for_each_reg_in_vstate_mask(env->cur_state, state, reg, clear_mask, ({ 11957 if (reg->type & MEM_RCU) { 11958 reg->type &= ~(MEM_RCU | PTR_MAYBE_NULL); 11959 reg->type |= PTR_UNTRUSTED; 11960 } 11961 })); 11962 env->cur_state->active_rcu_lock = false; 11963 } else if (sleepable) { 11964 verbose(env, "kernel func %s is sleepable within rcu_read_lock region\n", func_name); 11965 return -EACCES; 11966 } 11967 } else if (rcu_lock) { 11968 env->cur_state->active_rcu_lock = true; 11969 } else if (rcu_unlock) { 11970 verbose(env, "unmatched rcu read unlock (kernel function %s)\n", func_name); 11971 return -EINVAL; 11972 } 11973 11974 /* In case of release function, we get register number of refcounted 11975 * PTR_TO_BTF_ID in bpf_kfunc_arg_meta, do the release now. 11976 */ 11977 if (meta.release_regno) { 11978 err = release_reference(env, regs[meta.release_regno].ref_obj_id); 11979 if (err) { 11980 verbose(env, "kfunc %s#%d reference has not been acquired before\n", 11981 func_name, meta.func_id); 11982 return err; 11983 } 11984 } 11985 11986 if (meta.func_id == special_kfunc_list[KF_bpf_list_push_front_impl] || 11987 meta.func_id == special_kfunc_list[KF_bpf_list_push_back_impl] || 11988 meta.func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) { 11989 release_ref_obj_id = regs[BPF_REG_2].ref_obj_id; 11990 insn_aux->insert_off = regs[BPF_REG_2].off; 11991 insn_aux->kptr_struct_meta = btf_find_struct_meta(meta.arg_btf, meta.arg_btf_id); 11992 err = ref_convert_owning_non_owning(env, release_ref_obj_id); 11993 if (err) { 11994 verbose(env, "kfunc %s#%d conversion of owning ref to non-owning failed\n", 11995 func_name, meta.func_id); 11996 return err; 11997 } 11998 11999 err = release_reference(env, release_ref_obj_id); 12000 if (err) { 12001 verbose(env, "kfunc %s#%d reference has not been acquired before\n", 12002 func_name, meta.func_id); 12003 return err; 12004 } 12005 } 12006 12007 if (meta.func_id == special_kfunc_list[KF_bpf_throw]) { 12008 if (!bpf_jit_supports_exceptions()) { 12009 verbose(env, "JIT does not support calling kfunc %s#%d\n", 12010 func_name, meta.func_id); 12011 return -ENOTSUPP; 12012 } 12013 env->seen_exception = true; 12014 12015 /* In the case of the default callback, the cookie value passed 12016 * to bpf_throw becomes the return value of the program. 12017 */ 12018 if (!env->exception_callback_subprog) { 12019 err = check_return_code(env, BPF_REG_1, "R1"); 12020 if (err < 0) 12021 return err; 12022 } 12023 } 12024 12025 for (i = 0; i < CALLER_SAVED_REGS; i++) 12026 mark_reg_not_init(env, regs, caller_saved[i]); 12027 12028 /* Check return type */ 12029 t = btf_type_skip_modifiers(desc_btf, meta.func_proto->type, NULL); 12030 12031 if (is_kfunc_acquire(&meta) && !btf_type_is_struct_ptr(meta.btf, t)) { 12032 /* Only exception is bpf_obj_new_impl */ 12033 if (meta.btf != btf_vmlinux || 12034 (meta.func_id != special_kfunc_list[KF_bpf_obj_new_impl] && 12035 meta.func_id != special_kfunc_list[KF_bpf_percpu_obj_new_impl] && 12036 meta.func_id != special_kfunc_list[KF_bpf_refcount_acquire_impl])) { 12037 verbose(env, "acquire kernel function does not return PTR_TO_BTF_ID\n"); 12038 return -EINVAL; 12039 } 12040 } 12041 12042 if (btf_type_is_scalar(t)) { 12043 mark_reg_unknown(env, regs, BPF_REG_0); 12044 mark_btf_func_reg_size(env, BPF_REG_0, t->size); 12045 } else if (btf_type_is_ptr(t)) { 12046 ptr_type = btf_type_skip_modifiers(desc_btf, t->type, &ptr_type_id); 12047 12048 if (meta.btf == btf_vmlinux && btf_id_set_contains(&special_kfunc_set, meta.func_id)) { 12049 if (meta.func_id == special_kfunc_list[KF_bpf_obj_new_impl] || 12050 meta.func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl]) { 12051 struct btf_struct_meta *struct_meta; 12052 struct btf *ret_btf; 12053 u32 ret_btf_id; 12054 12055 if (meta.func_id == special_kfunc_list[KF_bpf_obj_new_impl] && !bpf_global_ma_set) 12056 return -ENOMEM; 12057 12058 if (meta.func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl]) { 12059 if (!bpf_global_percpu_ma_set) { 12060 mutex_lock(&bpf_percpu_ma_lock); 12061 if (!bpf_global_percpu_ma_set) { 12062 err = bpf_mem_alloc_init(&bpf_global_percpu_ma, 0, true); 12063 if (!err) 12064 bpf_global_percpu_ma_set = true; 12065 } 12066 mutex_unlock(&bpf_percpu_ma_lock); 12067 if (err) 12068 return err; 12069 } 12070 } 12071 12072 if (((u64)(u32)meta.arg_constant.value) != meta.arg_constant.value) { 12073 verbose(env, "local type ID argument must be in range [0, U32_MAX]\n"); 12074 return -EINVAL; 12075 } 12076 12077 ret_btf = env->prog->aux->btf; 12078 ret_btf_id = meta.arg_constant.value; 12079 12080 /* This may be NULL due to user not supplying a BTF */ 12081 if (!ret_btf) { 12082 verbose(env, "bpf_obj_new/bpf_percpu_obj_new requires prog BTF\n"); 12083 return -EINVAL; 12084 } 12085 12086 ret_t = btf_type_by_id(ret_btf, ret_btf_id); 12087 if (!ret_t || !__btf_type_is_struct(ret_t)) { 12088 verbose(env, "bpf_obj_new/bpf_percpu_obj_new type ID argument must be of a struct\n"); 12089 return -EINVAL; 12090 } 12091 12092 struct_meta = btf_find_struct_meta(ret_btf, ret_btf_id); 12093 if (meta.func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl]) { 12094 if (!__btf_type_is_scalar_struct(env, ret_btf, ret_t, 0)) { 12095 verbose(env, "bpf_percpu_obj_new type ID argument must be of a struct of scalars\n"); 12096 return -EINVAL; 12097 } 12098 12099 if (struct_meta) { 12100 verbose(env, "bpf_percpu_obj_new type ID argument must not contain special fields\n"); 12101 return -EINVAL; 12102 } 12103 } 12104 12105 mark_reg_known_zero(env, regs, BPF_REG_0); 12106 regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC; 12107 regs[BPF_REG_0].btf = ret_btf; 12108 regs[BPF_REG_0].btf_id = ret_btf_id; 12109 if (meta.func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl]) 12110 regs[BPF_REG_0].type |= MEM_PERCPU; 12111 12112 insn_aux->obj_new_size = ret_t->size; 12113 insn_aux->kptr_struct_meta = struct_meta; 12114 } else if (meta.func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl]) { 12115 mark_reg_known_zero(env, regs, BPF_REG_0); 12116 regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC; 12117 regs[BPF_REG_0].btf = meta.arg_btf; 12118 regs[BPF_REG_0].btf_id = meta.arg_btf_id; 12119 12120 insn_aux->kptr_struct_meta = 12121 btf_find_struct_meta(meta.arg_btf, 12122 meta.arg_btf_id); 12123 } else if (meta.func_id == special_kfunc_list[KF_bpf_list_pop_front] || 12124 meta.func_id == special_kfunc_list[KF_bpf_list_pop_back]) { 12125 struct btf_field *field = meta.arg_list_head.field; 12126 12127 mark_reg_graph_node(regs, BPF_REG_0, &field->graph_root); 12128 } else if (meta.func_id == special_kfunc_list[KF_bpf_rbtree_remove] || 12129 meta.func_id == special_kfunc_list[KF_bpf_rbtree_first]) { 12130 struct btf_field *field = meta.arg_rbtree_root.field; 12131 12132 mark_reg_graph_node(regs, BPF_REG_0, &field->graph_root); 12133 } else if (meta.func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx]) { 12134 mark_reg_known_zero(env, regs, BPF_REG_0); 12135 regs[BPF_REG_0].type = PTR_TO_BTF_ID | PTR_TRUSTED; 12136 regs[BPF_REG_0].btf = desc_btf; 12137 regs[BPF_REG_0].btf_id = meta.ret_btf_id; 12138 } else if (meta.func_id == special_kfunc_list[KF_bpf_rdonly_cast]) { 12139 ret_t = btf_type_by_id(desc_btf, meta.arg_constant.value); 12140 if (!ret_t || !btf_type_is_struct(ret_t)) { 12141 verbose(env, 12142 "kfunc bpf_rdonly_cast type ID argument must be of a struct\n"); 12143 return -EINVAL; 12144 } 12145 12146 mark_reg_known_zero(env, regs, BPF_REG_0); 12147 regs[BPF_REG_0].type = PTR_TO_BTF_ID | PTR_UNTRUSTED; 12148 regs[BPF_REG_0].btf = desc_btf; 12149 regs[BPF_REG_0].btf_id = meta.arg_constant.value; 12150 } else if (meta.func_id == special_kfunc_list[KF_bpf_dynptr_slice] || 12151 meta.func_id == special_kfunc_list[KF_bpf_dynptr_slice_rdwr]) { 12152 enum bpf_type_flag type_flag = get_dynptr_type_flag(meta.initialized_dynptr.type); 12153 12154 mark_reg_known_zero(env, regs, BPF_REG_0); 12155 12156 if (!meta.arg_constant.found) { 12157 verbose(env, "verifier internal error: bpf_dynptr_slice(_rdwr) no constant size\n"); 12158 return -EFAULT; 12159 } 12160 12161 regs[BPF_REG_0].mem_size = meta.arg_constant.value; 12162 12163 /* PTR_MAYBE_NULL will be added when is_kfunc_ret_null is checked */ 12164 regs[BPF_REG_0].type = PTR_TO_MEM | type_flag; 12165 12166 if (meta.func_id == special_kfunc_list[KF_bpf_dynptr_slice]) { 12167 regs[BPF_REG_0].type |= MEM_RDONLY; 12168 } else { 12169 /* this will set env->seen_direct_write to true */ 12170 if (!may_access_direct_pkt_data(env, NULL, BPF_WRITE)) { 12171 verbose(env, "the prog does not allow writes to packet data\n"); 12172 return -EINVAL; 12173 } 12174 } 12175 12176 if (!meta.initialized_dynptr.id) { 12177 verbose(env, "verifier internal error: no dynptr id\n"); 12178 return -EFAULT; 12179 } 12180 regs[BPF_REG_0].dynptr_id = meta.initialized_dynptr.id; 12181 12182 /* we don't need to set BPF_REG_0's ref obj id 12183 * because packet slices are not refcounted (see 12184 * dynptr_type_refcounted) 12185 */ 12186 } else { 12187 verbose(env, "kernel function %s unhandled dynamic return type\n", 12188 meta.func_name); 12189 return -EFAULT; 12190 } 12191 } else if (!__btf_type_is_struct(ptr_type)) { 12192 if (!meta.r0_size) { 12193 __u32 sz; 12194 12195 if (!IS_ERR(btf_resolve_size(desc_btf, ptr_type, &sz))) { 12196 meta.r0_size = sz; 12197 meta.r0_rdonly = true; 12198 } 12199 } 12200 if (!meta.r0_size) { 12201 ptr_type_name = btf_name_by_offset(desc_btf, 12202 ptr_type->name_off); 12203 verbose(env, 12204 "kernel function %s returns pointer type %s %s is not supported\n", 12205 func_name, 12206 btf_type_str(ptr_type), 12207 ptr_type_name); 12208 return -EINVAL; 12209 } 12210 12211 mark_reg_known_zero(env, regs, BPF_REG_0); 12212 regs[BPF_REG_0].type = PTR_TO_MEM; 12213 regs[BPF_REG_0].mem_size = meta.r0_size; 12214 12215 if (meta.r0_rdonly) 12216 regs[BPF_REG_0].type |= MEM_RDONLY; 12217 12218 /* Ensures we don't access the memory after a release_reference() */ 12219 if (meta.ref_obj_id) 12220 regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id; 12221 } else { 12222 mark_reg_known_zero(env, regs, BPF_REG_0); 12223 regs[BPF_REG_0].btf = desc_btf; 12224 regs[BPF_REG_0].type = PTR_TO_BTF_ID; 12225 regs[BPF_REG_0].btf_id = ptr_type_id; 12226 } 12227 12228 if (is_kfunc_ret_null(&meta)) { 12229 regs[BPF_REG_0].type |= PTR_MAYBE_NULL; 12230 /* For mark_ptr_or_null_reg, see 93c230e3f5bd6 */ 12231 regs[BPF_REG_0].id = ++env->id_gen; 12232 } 12233 mark_btf_func_reg_size(env, BPF_REG_0, sizeof(void *)); 12234 if (is_kfunc_acquire(&meta)) { 12235 int id = acquire_reference_state(env, insn_idx); 12236 12237 if (id < 0) 12238 return id; 12239 if (is_kfunc_ret_null(&meta)) 12240 regs[BPF_REG_0].id = id; 12241 regs[BPF_REG_0].ref_obj_id = id; 12242 } else if (meta.func_id == special_kfunc_list[KF_bpf_rbtree_first]) { 12243 ref_set_non_owning(env, ®s[BPF_REG_0]); 12244 } 12245 12246 if (reg_may_point_to_spin_lock(®s[BPF_REG_0]) && !regs[BPF_REG_0].id) 12247 regs[BPF_REG_0].id = ++env->id_gen; 12248 } else if (btf_type_is_void(t)) { 12249 if (meta.btf == btf_vmlinux && btf_id_set_contains(&special_kfunc_set, meta.func_id)) { 12250 if (meta.func_id == special_kfunc_list[KF_bpf_obj_drop_impl] || 12251 meta.func_id == special_kfunc_list[KF_bpf_percpu_obj_drop_impl]) { 12252 insn_aux->kptr_struct_meta = 12253 btf_find_struct_meta(meta.arg_btf, 12254 meta.arg_btf_id); 12255 } 12256 } 12257 } 12258 12259 nargs = btf_type_vlen(meta.func_proto); 12260 args = (const struct btf_param *)(meta.func_proto + 1); 12261 for (i = 0; i < nargs; i++) { 12262 u32 regno = i + 1; 12263 12264 t = btf_type_skip_modifiers(desc_btf, args[i].type, NULL); 12265 if (btf_type_is_ptr(t)) 12266 mark_btf_func_reg_size(env, regno, sizeof(void *)); 12267 else 12268 /* scalar. ensured by btf_check_kfunc_arg_match() */ 12269 mark_btf_func_reg_size(env, regno, t->size); 12270 } 12271 12272 if (is_iter_next_kfunc(&meta)) { 12273 err = process_iter_next_call(env, insn_idx, &meta); 12274 if (err) 12275 return err; 12276 } 12277 12278 return 0; 12279 } 12280 12281 static bool signed_add_overflows(s64 a, s64 b) 12282 { 12283 /* Do the add in u64, where overflow is well-defined */ 12284 s64 res = (s64)((u64)a + (u64)b); 12285 12286 if (b < 0) 12287 return res > a; 12288 return res < a; 12289 } 12290 12291 static bool signed_add32_overflows(s32 a, s32 b) 12292 { 12293 /* Do the add in u32, where overflow is well-defined */ 12294 s32 res = (s32)((u32)a + (u32)b); 12295 12296 if (b < 0) 12297 return res > a; 12298 return res < a; 12299 } 12300 12301 static bool signed_sub_overflows(s64 a, s64 b) 12302 { 12303 /* Do the sub in u64, where overflow is well-defined */ 12304 s64 res = (s64)((u64)a - (u64)b); 12305 12306 if (b < 0) 12307 return res < a; 12308 return res > a; 12309 } 12310 12311 static bool signed_sub32_overflows(s32 a, s32 b) 12312 { 12313 /* Do the sub in u32, where overflow is well-defined */ 12314 s32 res = (s32)((u32)a - (u32)b); 12315 12316 if (b < 0) 12317 return res < a; 12318 return res > a; 12319 } 12320 12321 static bool check_reg_sane_offset(struct bpf_verifier_env *env, 12322 const struct bpf_reg_state *reg, 12323 enum bpf_reg_type type) 12324 { 12325 bool known = tnum_is_const(reg->var_off); 12326 s64 val = reg->var_off.value; 12327 s64 smin = reg->smin_value; 12328 12329 if (known && (val >= BPF_MAX_VAR_OFF || val <= -BPF_MAX_VAR_OFF)) { 12330 verbose(env, "math between %s pointer and %lld is not allowed\n", 12331 reg_type_str(env, type), val); 12332 return false; 12333 } 12334 12335 if (reg->off >= BPF_MAX_VAR_OFF || reg->off <= -BPF_MAX_VAR_OFF) { 12336 verbose(env, "%s pointer offset %d is not allowed\n", 12337 reg_type_str(env, type), reg->off); 12338 return false; 12339 } 12340 12341 if (smin == S64_MIN) { 12342 verbose(env, "math between %s pointer and register with unbounded min value is not allowed\n", 12343 reg_type_str(env, type)); 12344 return false; 12345 } 12346 12347 if (smin >= BPF_MAX_VAR_OFF || smin <= -BPF_MAX_VAR_OFF) { 12348 verbose(env, "value %lld makes %s pointer be out of bounds\n", 12349 smin, reg_type_str(env, type)); 12350 return false; 12351 } 12352 12353 return true; 12354 } 12355 12356 enum { 12357 REASON_BOUNDS = -1, 12358 REASON_TYPE = -2, 12359 REASON_PATHS = -3, 12360 REASON_LIMIT = -4, 12361 REASON_STACK = -5, 12362 }; 12363 12364 static int retrieve_ptr_limit(const struct bpf_reg_state *ptr_reg, 12365 u32 *alu_limit, bool mask_to_left) 12366 { 12367 u32 max = 0, ptr_limit = 0; 12368 12369 switch (ptr_reg->type) { 12370 case PTR_TO_STACK: 12371 /* Offset 0 is out-of-bounds, but acceptable start for the 12372 * left direction, see BPF_REG_FP. Also, unknown scalar 12373 * offset where we would need to deal with min/max bounds is 12374 * currently prohibited for unprivileged. 12375 */ 12376 max = MAX_BPF_STACK + mask_to_left; 12377 ptr_limit = -(ptr_reg->var_off.value + ptr_reg->off); 12378 break; 12379 case PTR_TO_MAP_VALUE: 12380 max = ptr_reg->map_ptr->value_size; 12381 ptr_limit = (mask_to_left ? 12382 ptr_reg->smin_value : 12383 ptr_reg->umax_value) + ptr_reg->off; 12384 break; 12385 default: 12386 return REASON_TYPE; 12387 } 12388 12389 if (ptr_limit >= max) 12390 return REASON_LIMIT; 12391 *alu_limit = ptr_limit; 12392 return 0; 12393 } 12394 12395 static bool can_skip_alu_sanitation(const struct bpf_verifier_env *env, 12396 const struct bpf_insn *insn) 12397 { 12398 return env->bypass_spec_v1 || BPF_SRC(insn->code) == BPF_K; 12399 } 12400 12401 static int update_alu_sanitation_state(struct bpf_insn_aux_data *aux, 12402 u32 alu_state, u32 alu_limit) 12403 { 12404 /* If we arrived here from different branches with different 12405 * state or limits to sanitize, then this won't work. 12406 */ 12407 if (aux->alu_state && 12408 (aux->alu_state != alu_state || 12409 aux->alu_limit != alu_limit)) 12410 return REASON_PATHS; 12411 12412 /* Corresponding fixup done in do_misc_fixups(). */ 12413 aux->alu_state = alu_state; 12414 aux->alu_limit = alu_limit; 12415 return 0; 12416 } 12417 12418 static int sanitize_val_alu(struct bpf_verifier_env *env, 12419 struct bpf_insn *insn) 12420 { 12421 struct bpf_insn_aux_data *aux = cur_aux(env); 12422 12423 if (can_skip_alu_sanitation(env, insn)) 12424 return 0; 12425 12426 return update_alu_sanitation_state(aux, BPF_ALU_NON_POINTER, 0); 12427 } 12428 12429 static bool sanitize_needed(u8 opcode) 12430 { 12431 return opcode == BPF_ADD || opcode == BPF_SUB; 12432 } 12433 12434 struct bpf_sanitize_info { 12435 struct bpf_insn_aux_data aux; 12436 bool mask_to_left; 12437 }; 12438 12439 static struct bpf_verifier_state * 12440 sanitize_speculative_path(struct bpf_verifier_env *env, 12441 const struct bpf_insn *insn, 12442 u32 next_idx, u32 curr_idx) 12443 { 12444 struct bpf_verifier_state *branch; 12445 struct bpf_reg_state *regs; 12446 12447 branch = push_stack(env, next_idx, curr_idx, true); 12448 if (branch && insn) { 12449 regs = branch->frame[branch->curframe]->regs; 12450 if (BPF_SRC(insn->code) == BPF_K) { 12451 mark_reg_unknown(env, regs, insn->dst_reg); 12452 } else if (BPF_SRC(insn->code) == BPF_X) { 12453 mark_reg_unknown(env, regs, insn->dst_reg); 12454 mark_reg_unknown(env, regs, insn->src_reg); 12455 } 12456 } 12457 return branch; 12458 } 12459 12460 static int sanitize_ptr_alu(struct bpf_verifier_env *env, 12461 struct bpf_insn *insn, 12462 const struct bpf_reg_state *ptr_reg, 12463 const struct bpf_reg_state *off_reg, 12464 struct bpf_reg_state *dst_reg, 12465 struct bpf_sanitize_info *info, 12466 const bool commit_window) 12467 { 12468 struct bpf_insn_aux_data *aux = commit_window ? cur_aux(env) : &info->aux; 12469 struct bpf_verifier_state *vstate = env->cur_state; 12470 bool off_is_imm = tnum_is_const(off_reg->var_off); 12471 bool off_is_neg = off_reg->smin_value < 0; 12472 bool ptr_is_dst_reg = ptr_reg == dst_reg; 12473 u8 opcode = BPF_OP(insn->code); 12474 u32 alu_state, alu_limit; 12475 struct bpf_reg_state tmp; 12476 bool ret; 12477 int err; 12478 12479 if (can_skip_alu_sanitation(env, insn)) 12480 return 0; 12481 12482 /* We already marked aux for masking from non-speculative 12483 * paths, thus we got here in the first place. We only care 12484 * to explore bad access from here. 12485 */ 12486 if (vstate->speculative) 12487 goto do_sim; 12488 12489 if (!commit_window) { 12490 if (!tnum_is_const(off_reg->var_off) && 12491 (off_reg->smin_value < 0) != (off_reg->smax_value < 0)) 12492 return REASON_BOUNDS; 12493 12494 info->mask_to_left = (opcode == BPF_ADD && off_is_neg) || 12495 (opcode == BPF_SUB && !off_is_neg); 12496 } 12497 12498 err = retrieve_ptr_limit(ptr_reg, &alu_limit, info->mask_to_left); 12499 if (err < 0) 12500 return err; 12501 12502 if (commit_window) { 12503 /* In commit phase we narrow the masking window based on 12504 * the observed pointer move after the simulated operation. 12505 */ 12506 alu_state = info->aux.alu_state; 12507 alu_limit = abs(info->aux.alu_limit - alu_limit); 12508 } else { 12509 alu_state = off_is_neg ? BPF_ALU_NEG_VALUE : 0; 12510 alu_state |= off_is_imm ? BPF_ALU_IMMEDIATE : 0; 12511 alu_state |= ptr_is_dst_reg ? 12512 BPF_ALU_SANITIZE_SRC : BPF_ALU_SANITIZE_DST; 12513 12514 /* Limit pruning on unknown scalars to enable deep search for 12515 * potential masking differences from other program paths. 12516 */ 12517 if (!off_is_imm) 12518 env->explore_alu_limits = true; 12519 } 12520 12521 err = update_alu_sanitation_state(aux, alu_state, alu_limit); 12522 if (err < 0) 12523 return err; 12524 do_sim: 12525 /* If we're in commit phase, we're done here given we already 12526 * pushed the truncated dst_reg into the speculative verification 12527 * stack. 12528 * 12529 * Also, when register is a known constant, we rewrite register-based 12530 * operation to immediate-based, and thus do not need masking (and as 12531 * a consequence, do not need to simulate the zero-truncation either). 12532 */ 12533 if (commit_window || off_is_imm) 12534 return 0; 12535 12536 /* Simulate and find potential out-of-bounds access under 12537 * speculative execution from truncation as a result of 12538 * masking when off was not within expected range. If off 12539 * sits in dst, then we temporarily need to move ptr there 12540 * to simulate dst (== 0) +/-= ptr. Needed, for example, 12541 * for cases where we use K-based arithmetic in one direction 12542 * and truncated reg-based in the other in order to explore 12543 * bad access. 12544 */ 12545 if (!ptr_is_dst_reg) { 12546 tmp = *dst_reg; 12547 copy_register_state(dst_reg, ptr_reg); 12548 } 12549 ret = sanitize_speculative_path(env, NULL, env->insn_idx + 1, 12550 env->insn_idx); 12551 if (!ptr_is_dst_reg && ret) 12552 *dst_reg = tmp; 12553 return !ret ? REASON_STACK : 0; 12554 } 12555 12556 static void sanitize_mark_insn_seen(struct bpf_verifier_env *env) 12557 { 12558 struct bpf_verifier_state *vstate = env->cur_state; 12559 12560 /* If we simulate paths under speculation, we don't update the 12561 * insn as 'seen' such that when we verify unreachable paths in 12562 * the non-speculative domain, sanitize_dead_code() can still 12563 * rewrite/sanitize them. 12564 */ 12565 if (!vstate->speculative) 12566 env->insn_aux_data[env->insn_idx].seen = env->pass_cnt; 12567 } 12568 12569 static int sanitize_err(struct bpf_verifier_env *env, 12570 const struct bpf_insn *insn, int reason, 12571 const struct bpf_reg_state *off_reg, 12572 const struct bpf_reg_state *dst_reg) 12573 { 12574 static const char *err = "pointer arithmetic with it prohibited for !root"; 12575 const char *op = BPF_OP(insn->code) == BPF_ADD ? "add" : "sub"; 12576 u32 dst = insn->dst_reg, src = insn->src_reg; 12577 12578 switch (reason) { 12579 case REASON_BOUNDS: 12580 verbose(env, "R%d has unknown scalar with mixed signed bounds, %s\n", 12581 off_reg == dst_reg ? dst : src, err); 12582 break; 12583 case REASON_TYPE: 12584 verbose(env, "R%d has pointer with unsupported alu operation, %s\n", 12585 off_reg == dst_reg ? src : dst, err); 12586 break; 12587 case REASON_PATHS: 12588 verbose(env, "R%d tried to %s from different maps, paths or scalars, %s\n", 12589 dst, op, err); 12590 break; 12591 case REASON_LIMIT: 12592 verbose(env, "R%d tried to %s beyond pointer bounds, %s\n", 12593 dst, op, err); 12594 break; 12595 case REASON_STACK: 12596 verbose(env, "R%d could not be pushed for speculative verification, %s\n", 12597 dst, err); 12598 break; 12599 default: 12600 verbose(env, "verifier internal error: unknown reason (%d)\n", 12601 reason); 12602 break; 12603 } 12604 12605 return -EACCES; 12606 } 12607 12608 /* check that stack access falls within stack limits and that 'reg' doesn't 12609 * have a variable offset. 12610 * 12611 * Variable offset is prohibited for unprivileged mode for simplicity since it 12612 * requires corresponding support in Spectre masking for stack ALU. See also 12613 * retrieve_ptr_limit(). 12614 * 12615 * 12616 * 'off' includes 'reg->off'. 12617 */ 12618 static int check_stack_access_for_ptr_arithmetic( 12619 struct bpf_verifier_env *env, 12620 int regno, 12621 const struct bpf_reg_state *reg, 12622 int off) 12623 { 12624 if (!tnum_is_const(reg->var_off)) { 12625 char tn_buf[48]; 12626 12627 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 12628 verbose(env, "R%d variable stack access prohibited for !root, var_off=%s off=%d\n", 12629 regno, tn_buf, off); 12630 return -EACCES; 12631 } 12632 12633 if (off >= 0 || off < -MAX_BPF_STACK) { 12634 verbose(env, "R%d stack pointer arithmetic goes out of range, " 12635 "prohibited for !root; off=%d\n", regno, off); 12636 return -EACCES; 12637 } 12638 12639 return 0; 12640 } 12641 12642 static int sanitize_check_bounds(struct bpf_verifier_env *env, 12643 const struct bpf_insn *insn, 12644 const struct bpf_reg_state *dst_reg) 12645 { 12646 u32 dst = insn->dst_reg; 12647 12648 /* For unprivileged we require that resulting offset must be in bounds 12649 * in order to be able to sanitize access later on. 12650 */ 12651 if (env->bypass_spec_v1) 12652 return 0; 12653 12654 switch (dst_reg->type) { 12655 case PTR_TO_STACK: 12656 if (check_stack_access_for_ptr_arithmetic(env, dst, dst_reg, 12657 dst_reg->off + dst_reg->var_off.value)) 12658 return -EACCES; 12659 break; 12660 case PTR_TO_MAP_VALUE: 12661 if (check_map_access(env, dst, dst_reg->off, 1, false, ACCESS_HELPER)) { 12662 verbose(env, "R%d pointer arithmetic of map value goes out of range, " 12663 "prohibited for !root\n", dst); 12664 return -EACCES; 12665 } 12666 break; 12667 default: 12668 break; 12669 } 12670 12671 return 0; 12672 } 12673 12674 /* Handles arithmetic on a pointer and a scalar: computes new min/max and var_off. 12675 * Caller should also handle BPF_MOV case separately. 12676 * If we return -EACCES, caller may want to try again treating pointer as a 12677 * scalar. So we only emit a diagnostic if !env->allow_ptr_leaks. 12678 */ 12679 static int adjust_ptr_min_max_vals(struct bpf_verifier_env *env, 12680 struct bpf_insn *insn, 12681 const struct bpf_reg_state *ptr_reg, 12682 const struct bpf_reg_state *off_reg) 12683 { 12684 struct bpf_verifier_state *vstate = env->cur_state; 12685 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 12686 struct bpf_reg_state *regs = state->regs, *dst_reg; 12687 bool known = tnum_is_const(off_reg->var_off); 12688 s64 smin_val = off_reg->smin_value, smax_val = off_reg->smax_value, 12689 smin_ptr = ptr_reg->smin_value, smax_ptr = ptr_reg->smax_value; 12690 u64 umin_val = off_reg->umin_value, umax_val = off_reg->umax_value, 12691 umin_ptr = ptr_reg->umin_value, umax_ptr = ptr_reg->umax_value; 12692 struct bpf_sanitize_info info = {}; 12693 u8 opcode = BPF_OP(insn->code); 12694 u32 dst = insn->dst_reg; 12695 int ret; 12696 12697 dst_reg = ®s[dst]; 12698 12699 if ((known && (smin_val != smax_val || umin_val != umax_val)) || 12700 smin_val > smax_val || umin_val > umax_val) { 12701 /* Taint dst register if offset had invalid bounds derived from 12702 * e.g. dead branches. 12703 */ 12704 __mark_reg_unknown(env, dst_reg); 12705 return 0; 12706 } 12707 12708 if (BPF_CLASS(insn->code) != BPF_ALU64) { 12709 /* 32-bit ALU ops on pointers produce (meaningless) scalars */ 12710 if (opcode == BPF_SUB && env->allow_ptr_leaks) { 12711 __mark_reg_unknown(env, dst_reg); 12712 return 0; 12713 } 12714 12715 verbose(env, 12716 "R%d 32-bit pointer arithmetic prohibited\n", 12717 dst); 12718 return -EACCES; 12719 } 12720 12721 if (ptr_reg->type & PTR_MAYBE_NULL) { 12722 verbose(env, "R%d pointer arithmetic on %s prohibited, null-check it first\n", 12723 dst, reg_type_str(env, ptr_reg->type)); 12724 return -EACCES; 12725 } 12726 12727 switch (base_type(ptr_reg->type)) { 12728 case CONST_PTR_TO_MAP: 12729 /* smin_val represents the known value */ 12730 if (known && smin_val == 0 && opcode == BPF_ADD) 12731 break; 12732 fallthrough; 12733 case PTR_TO_PACKET_END: 12734 case PTR_TO_SOCKET: 12735 case PTR_TO_SOCK_COMMON: 12736 case PTR_TO_TCP_SOCK: 12737 case PTR_TO_XDP_SOCK: 12738 verbose(env, "R%d pointer arithmetic on %s prohibited\n", 12739 dst, reg_type_str(env, ptr_reg->type)); 12740 return -EACCES; 12741 default: 12742 break; 12743 } 12744 12745 /* In case of 'scalar += pointer', dst_reg inherits pointer type and id. 12746 * The id may be overwritten later if we create a new variable offset. 12747 */ 12748 dst_reg->type = ptr_reg->type; 12749 dst_reg->id = ptr_reg->id; 12750 12751 if (!check_reg_sane_offset(env, off_reg, ptr_reg->type) || 12752 !check_reg_sane_offset(env, ptr_reg, ptr_reg->type)) 12753 return -EINVAL; 12754 12755 /* pointer types do not carry 32-bit bounds at the moment. */ 12756 __mark_reg32_unbounded(dst_reg); 12757 12758 if (sanitize_needed(opcode)) { 12759 ret = sanitize_ptr_alu(env, insn, ptr_reg, off_reg, dst_reg, 12760 &info, false); 12761 if (ret < 0) 12762 return sanitize_err(env, insn, ret, off_reg, dst_reg); 12763 } 12764 12765 switch (opcode) { 12766 case BPF_ADD: 12767 /* We can take a fixed offset as long as it doesn't overflow 12768 * the s32 'off' field 12769 */ 12770 if (known && (ptr_reg->off + smin_val == 12771 (s64)(s32)(ptr_reg->off + smin_val))) { 12772 /* pointer += K. Accumulate it into fixed offset */ 12773 dst_reg->smin_value = smin_ptr; 12774 dst_reg->smax_value = smax_ptr; 12775 dst_reg->umin_value = umin_ptr; 12776 dst_reg->umax_value = umax_ptr; 12777 dst_reg->var_off = ptr_reg->var_off; 12778 dst_reg->off = ptr_reg->off + smin_val; 12779 dst_reg->raw = ptr_reg->raw; 12780 break; 12781 } 12782 /* A new variable offset is created. Note that off_reg->off 12783 * == 0, since it's a scalar. 12784 * dst_reg gets the pointer type and since some positive 12785 * integer value was added to the pointer, give it a new 'id' 12786 * if it's a PTR_TO_PACKET. 12787 * this creates a new 'base' pointer, off_reg (variable) gets 12788 * added into the variable offset, and we copy the fixed offset 12789 * from ptr_reg. 12790 */ 12791 if (signed_add_overflows(smin_ptr, smin_val) || 12792 signed_add_overflows(smax_ptr, smax_val)) { 12793 dst_reg->smin_value = S64_MIN; 12794 dst_reg->smax_value = S64_MAX; 12795 } else { 12796 dst_reg->smin_value = smin_ptr + smin_val; 12797 dst_reg->smax_value = smax_ptr + smax_val; 12798 } 12799 if (umin_ptr + umin_val < umin_ptr || 12800 umax_ptr + umax_val < umax_ptr) { 12801 dst_reg->umin_value = 0; 12802 dst_reg->umax_value = U64_MAX; 12803 } else { 12804 dst_reg->umin_value = umin_ptr + umin_val; 12805 dst_reg->umax_value = umax_ptr + umax_val; 12806 } 12807 dst_reg->var_off = tnum_add(ptr_reg->var_off, off_reg->var_off); 12808 dst_reg->off = ptr_reg->off; 12809 dst_reg->raw = ptr_reg->raw; 12810 if (reg_is_pkt_pointer(ptr_reg)) { 12811 dst_reg->id = ++env->id_gen; 12812 /* something was added to pkt_ptr, set range to zero */ 12813 memset(&dst_reg->raw, 0, sizeof(dst_reg->raw)); 12814 } 12815 break; 12816 case BPF_SUB: 12817 if (dst_reg == off_reg) { 12818 /* scalar -= pointer. Creates an unknown scalar */ 12819 verbose(env, "R%d tried to subtract pointer from scalar\n", 12820 dst); 12821 return -EACCES; 12822 } 12823 /* We don't allow subtraction from FP, because (according to 12824 * test_verifier.c test "invalid fp arithmetic", JITs might not 12825 * be able to deal with it. 12826 */ 12827 if (ptr_reg->type == PTR_TO_STACK) { 12828 verbose(env, "R%d subtraction from stack pointer prohibited\n", 12829 dst); 12830 return -EACCES; 12831 } 12832 if (known && (ptr_reg->off - smin_val == 12833 (s64)(s32)(ptr_reg->off - smin_val))) { 12834 /* pointer -= K. Subtract it from fixed offset */ 12835 dst_reg->smin_value = smin_ptr; 12836 dst_reg->smax_value = smax_ptr; 12837 dst_reg->umin_value = umin_ptr; 12838 dst_reg->umax_value = umax_ptr; 12839 dst_reg->var_off = ptr_reg->var_off; 12840 dst_reg->id = ptr_reg->id; 12841 dst_reg->off = ptr_reg->off - smin_val; 12842 dst_reg->raw = ptr_reg->raw; 12843 break; 12844 } 12845 /* A new variable offset is created. If the subtrahend is known 12846 * nonnegative, then any reg->range we had before is still good. 12847 */ 12848 if (signed_sub_overflows(smin_ptr, smax_val) || 12849 signed_sub_overflows(smax_ptr, smin_val)) { 12850 /* Overflow possible, we know nothing */ 12851 dst_reg->smin_value = S64_MIN; 12852 dst_reg->smax_value = S64_MAX; 12853 } else { 12854 dst_reg->smin_value = smin_ptr - smax_val; 12855 dst_reg->smax_value = smax_ptr - smin_val; 12856 } 12857 if (umin_ptr < umax_val) { 12858 /* Overflow possible, we know nothing */ 12859 dst_reg->umin_value = 0; 12860 dst_reg->umax_value = U64_MAX; 12861 } else { 12862 /* Cannot overflow (as long as bounds are consistent) */ 12863 dst_reg->umin_value = umin_ptr - umax_val; 12864 dst_reg->umax_value = umax_ptr - umin_val; 12865 } 12866 dst_reg->var_off = tnum_sub(ptr_reg->var_off, off_reg->var_off); 12867 dst_reg->off = ptr_reg->off; 12868 dst_reg->raw = ptr_reg->raw; 12869 if (reg_is_pkt_pointer(ptr_reg)) { 12870 dst_reg->id = ++env->id_gen; 12871 /* something was added to pkt_ptr, set range to zero */ 12872 if (smin_val < 0) 12873 memset(&dst_reg->raw, 0, sizeof(dst_reg->raw)); 12874 } 12875 break; 12876 case BPF_AND: 12877 case BPF_OR: 12878 case BPF_XOR: 12879 /* bitwise ops on pointers are troublesome, prohibit. */ 12880 verbose(env, "R%d bitwise operator %s on pointer prohibited\n", 12881 dst, bpf_alu_string[opcode >> 4]); 12882 return -EACCES; 12883 default: 12884 /* other operators (e.g. MUL,LSH) produce non-pointer results */ 12885 verbose(env, "R%d pointer arithmetic with %s operator prohibited\n", 12886 dst, bpf_alu_string[opcode >> 4]); 12887 return -EACCES; 12888 } 12889 12890 if (!check_reg_sane_offset(env, dst_reg, ptr_reg->type)) 12891 return -EINVAL; 12892 reg_bounds_sync(dst_reg); 12893 if (sanitize_check_bounds(env, insn, dst_reg) < 0) 12894 return -EACCES; 12895 if (sanitize_needed(opcode)) { 12896 ret = sanitize_ptr_alu(env, insn, dst_reg, off_reg, dst_reg, 12897 &info, true); 12898 if (ret < 0) 12899 return sanitize_err(env, insn, ret, off_reg, dst_reg); 12900 } 12901 12902 return 0; 12903 } 12904 12905 static void scalar32_min_max_add(struct bpf_reg_state *dst_reg, 12906 struct bpf_reg_state *src_reg) 12907 { 12908 s32 smin_val = src_reg->s32_min_value; 12909 s32 smax_val = src_reg->s32_max_value; 12910 u32 umin_val = src_reg->u32_min_value; 12911 u32 umax_val = src_reg->u32_max_value; 12912 12913 if (signed_add32_overflows(dst_reg->s32_min_value, smin_val) || 12914 signed_add32_overflows(dst_reg->s32_max_value, smax_val)) { 12915 dst_reg->s32_min_value = S32_MIN; 12916 dst_reg->s32_max_value = S32_MAX; 12917 } else { 12918 dst_reg->s32_min_value += smin_val; 12919 dst_reg->s32_max_value += smax_val; 12920 } 12921 if (dst_reg->u32_min_value + umin_val < umin_val || 12922 dst_reg->u32_max_value + umax_val < umax_val) { 12923 dst_reg->u32_min_value = 0; 12924 dst_reg->u32_max_value = U32_MAX; 12925 } else { 12926 dst_reg->u32_min_value += umin_val; 12927 dst_reg->u32_max_value += umax_val; 12928 } 12929 } 12930 12931 static void scalar_min_max_add(struct bpf_reg_state *dst_reg, 12932 struct bpf_reg_state *src_reg) 12933 { 12934 s64 smin_val = src_reg->smin_value; 12935 s64 smax_val = src_reg->smax_value; 12936 u64 umin_val = src_reg->umin_value; 12937 u64 umax_val = src_reg->umax_value; 12938 12939 if (signed_add_overflows(dst_reg->smin_value, smin_val) || 12940 signed_add_overflows(dst_reg->smax_value, smax_val)) { 12941 dst_reg->smin_value = S64_MIN; 12942 dst_reg->smax_value = S64_MAX; 12943 } else { 12944 dst_reg->smin_value += smin_val; 12945 dst_reg->smax_value += smax_val; 12946 } 12947 if (dst_reg->umin_value + umin_val < umin_val || 12948 dst_reg->umax_value + umax_val < umax_val) { 12949 dst_reg->umin_value = 0; 12950 dst_reg->umax_value = U64_MAX; 12951 } else { 12952 dst_reg->umin_value += umin_val; 12953 dst_reg->umax_value += umax_val; 12954 } 12955 } 12956 12957 static void scalar32_min_max_sub(struct bpf_reg_state *dst_reg, 12958 struct bpf_reg_state *src_reg) 12959 { 12960 s32 smin_val = src_reg->s32_min_value; 12961 s32 smax_val = src_reg->s32_max_value; 12962 u32 umin_val = src_reg->u32_min_value; 12963 u32 umax_val = src_reg->u32_max_value; 12964 12965 if (signed_sub32_overflows(dst_reg->s32_min_value, smax_val) || 12966 signed_sub32_overflows(dst_reg->s32_max_value, smin_val)) { 12967 /* Overflow possible, we know nothing */ 12968 dst_reg->s32_min_value = S32_MIN; 12969 dst_reg->s32_max_value = S32_MAX; 12970 } else { 12971 dst_reg->s32_min_value -= smax_val; 12972 dst_reg->s32_max_value -= smin_val; 12973 } 12974 if (dst_reg->u32_min_value < umax_val) { 12975 /* Overflow possible, we know nothing */ 12976 dst_reg->u32_min_value = 0; 12977 dst_reg->u32_max_value = U32_MAX; 12978 } else { 12979 /* Cannot overflow (as long as bounds are consistent) */ 12980 dst_reg->u32_min_value -= umax_val; 12981 dst_reg->u32_max_value -= umin_val; 12982 } 12983 } 12984 12985 static void scalar_min_max_sub(struct bpf_reg_state *dst_reg, 12986 struct bpf_reg_state *src_reg) 12987 { 12988 s64 smin_val = src_reg->smin_value; 12989 s64 smax_val = src_reg->smax_value; 12990 u64 umin_val = src_reg->umin_value; 12991 u64 umax_val = src_reg->umax_value; 12992 12993 if (signed_sub_overflows(dst_reg->smin_value, smax_val) || 12994 signed_sub_overflows(dst_reg->smax_value, smin_val)) { 12995 /* Overflow possible, we know nothing */ 12996 dst_reg->smin_value = S64_MIN; 12997 dst_reg->smax_value = S64_MAX; 12998 } else { 12999 dst_reg->smin_value -= smax_val; 13000 dst_reg->smax_value -= smin_val; 13001 } 13002 if (dst_reg->umin_value < umax_val) { 13003 /* Overflow possible, we know nothing */ 13004 dst_reg->umin_value = 0; 13005 dst_reg->umax_value = U64_MAX; 13006 } else { 13007 /* Cannot overflow (as long as bounds are consistent) */ 13008 dst_reg->umin_value -= umax_val; 13009 dst_reg->umax_value -= umin_val; 13010 } 13011 } 13012 13013 static void scalar32_min_max_mul(struct bpf_reg_state *dst_reg, 13014 struct bpf_reg_state *src_reg) 13015 { 13016 s32 smin_val = src_reg->s32_min_value; 13017 u32 umin_val = src_reg->u32_min_value; 13018 u32 umax_val = src_reg->u32_max_value; 13019 13020 if (smin_val < 0 || dst_reg->s32_min_value < 0) { 13021 /* Ain't nobody got time to multiply that sign */ 13022 __mark_reg32_unbounded(dst_reg); 13023 return; 13024 } 13025 /* Both values are positive, so we can work with unsigned and 13026 * copy the result to signed (unless it exceeds S32_MAX). 13027 */ 13028 if (umax_val > U16_MAX || dst_reg->u32_max_value > U16_MAX) { 13029 /* Potential overflow, we know nothing */ 13030 __mark_reg32_unbounded(dst_reg); 13031 return; 13032 } 13033 dst_reg->u32_min_value *= umin_val; 13034 dst_reg->u32_max_value *= umax_val; 13035 if (dst_reg->u32_max_value > S32_MAX) { 13036 /* Overflow possible, we know nothing */ 13037 dst_reg->s32_min_value = S32_MIN; 13038 dst_reg->s32_max_value = S32_MAX; 13039 } else { 13040 dst_reg->s32_min_value = dst_reg->u32_min_value; 13041 dst_reg->s32_max_value = dst_reg->u32_max_value; 13042 } 13043 } 13044 13045 static void scalar_min_max_mul(struct bpf_reg_state *dst_reg, 13046 struct bpf_reg_state *src_reg) 13047 { 13048 s64 smin_val = src_reg->smin_value; 13049 u64 umin_val = src_reg->umin_value; 13050 u64 umax_val = src_reg->umax_value; 13051 13052 if (smin_val < 0 || dst_reg->smin_value < 0) { 13053 /* Ain't nobody got time to multiply that sign */ 13054 __mark_reg64_unbounded(dst_reg); 13055 return; 13056 } 13057 /* Both values are positive, so we can work with unsigned and 13058 * copy the result to signed (unless it exceeds S64_MAX). 13059 */ 13060 if (umax_val > U32_MAX || dst_reg->umax_value > U32_MAX) { 13061 /* Potential overflow, we know nothing */ 13062 __mark_reg64_unbounded(dst_reg); 13063 return; 13064 } 13065 dst_reg->umin_value *= umin_val; 13066 dst_reg->umax_value *= umax_val; 13067 if (dst_reg->umax_value > S64_MAX) { 13068 /* Overflow possible, we know nothing */ 13069 dst_reg->smin_value = S64_MIN; 13070 dst_reg->smax_value = S64_MAX; 13071 } else { 13072 dst_reg->smin_value = dst_reg->umin_value; 13073 dst_reg->smax_value = dst_reg->umax_value; 13074 } 13075 } 13076 13077 static void scalar32_min_max_and(struct bpf_reg_state *dst_reg, 13078 struct bpf_reg_state *src_reg) 13079 { 13080 bool src_known = tnum_subreg_is_const(src_reg->var_off); 13081 bool dst_known = tnum_subreg_is_const(dst_reg->var_off); 13082 struct tnum var32_off = tnum_subreg(dst_reg->var_off); 13083 s32 smin_val = src_reg->s32_min_value; 13084 u32 umax_val = src_reg->u32_max_value; 13085 13086 if (src_known && dst_known) { 13087 __mark_reg32_known(dst_reg, var32_off.value); 13088 return; 13089 } 13090 13091 /* We get our minimum from the var_off, since that's inherently 13092 * bitwise. Our maximum is the minimum of the operands' maxima. 13093 */ 13094 dst_reg->u32_min_value = var32_off.value; 13095 dst_reg->u32_max_value = min(dst_reg->u32_max_value, umax_val); 13096 if (dst_reg->s32_min_value < 0 || smin_val < 0) { 13097 /* Lose signed bounds when ANDing negative numbers, 13098 * ain't nobody got time for that. 13099 */ 13100 dst_reg->s32_min_value = S32_MIN; 13101 dst_reg->s32_max_value = S32_MAX; 13102 } else { 13103 /* ANDing two positives gives a positive, so safe to 13104 * cast result into s64. 13105 */ 13106 dst_reg->s32_min_value = dst_reg->u32_min_value; 13107 dst_reg->s32_max_value = dst_reg->u32_max_value; 13108 } 13109 } 13110 13111 static void scalar_min_max_and(struct bpf_reg_state *dst_reg, 13112 struct bpf_reg_state *src_reg) 13113 { 13114 bool src_known = tnum_is_const(src_reg->var_off); 13115 bool dst_known = tnum_is_const(dst_reg->var_off); 13116 s64 smin_val = src_reg->smin_value; 13117 u64 umax_val = src_reg->umax_value; 13118 13119 if (src_known && dst_known) { 13120 __mark_reg_known(dst_reg, dst_reg->var_off.value); 13121 return; 13122 } 13123 13124 /* We get our minimum from the var_off, since that's inherently 13125 * bitwise. Our maximum is the minimum of the operands' maxima. 13126 */ 13127 dst_reg->umin_value = dst_reg->var_off.value; 13128 dst_reg->umax_value = min(dst_reg->umax_value, umax_val); 13129 if (dst_reg->smin_value < 0 || smin_val < 0) { 13130 /* Lose signed bounds when ANDing negative numbers, 13131 * ain't nobody got time for that. 13132 */ 13133 dst_reg->smin_value = S64_MIN; 13134 dst_reg->smax_value = S64_MAX; 13135 } else { 13136 /* ANDing two positives gives a positive, so safe to 13137 * cast result into s64. 13138 */ 13139 dst_reg->smin_value = dst_reg->umin_value; 13140 dst_reg->smax_value = dst_reg->umax_value; 13141 } 13142 /* We may learn something more from the var_off */ 13143 __update_reg_bounds(dst_reg); 13144 } 13145 13146 static void scalar32_min_max_or(struct bpf_reg_state *dst_reg, 13147 struct bpf_reg_state *src_reg) 13148 { 13149 bool src_known = tnum_subreg_is_const(src_reg->var_off); 13150 bool dst_known = tnum_subreg_is_const(dst_reg->var_off); 13151 struct tnum var32_off = tnum_subreg(dst_reg->var_off); 13152 s32 smin_val = src_reg->s32_min_value; 13153 u32 umin_val = src_reg->u32_min_value; 13154 13155 if (src_known && dst_known) { 13156 __mark_reg32_known(dst_reg, var32_off.value); 13157 return; 13158 } 13159 13160 /* We get our maximum from the var_off, and our minimum is the 13161 * maximum of the operands' minima 13162 */ 13163 dst_reg->u32_min_value = max(dst_reg->u32_min_value, umin_val); 13164 dst_reg->u32_max_value = var32_off.value | var32_off.mask; 13165 if (dst_reg->s32_min_value < 0 || smin_val < 0) { 13166 /* Lose signed bounds when ORing negative numbers, 13167 * ain't nobody got time for that. 13168 */ 13169 dst_reg->s32_min_value = S32_MIN; 13170 dst_reg->s32_max_value = S32_MAX; 13171 } else { 13172 /* ORing two positives gives a positive, so safe to 13173 * cast result into s64. 13174 */ 13175 dst_reg->s32_min_value = dst_reg->u32_min_value; 13176 dst_reg->s32_max_value = dst_reg->u32_max_value; 13177 } 13178 } 13179 13180 static void scalar_min_max_or(struct bpf_reg_state *dst_reg, 13181 struct bpf_reg_state *src_reg) 13182 { 13183 bool src_known = tnum_is_const(src_reg->var_off); 13184 bool dst_known = tnum_is_const(dst_reg->var_off); 13185 s64 smin_val = src_reg->smin_value; 13186 u64 umin_val = src_reg->umin_value; 13187 13188 if (src_known && dst_known) { 13189 __mark_reg_known(dst_reg, dst_reg->var_off.value); 13190 return; 13191 } 13192 13193 /* We get our maximum from the var_off, and our minimum is the 13194 * maximum of the operands' minima 13195 */ 13196 dst_reg->umin_value = max(dst_reg->umin_value, umin_val); 13197 dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask; 13198 if (dst_reg->smin_value < 0 || smin_val < 0) { 13199 /* Lose signed bounds when ORing negative numbers, 13200 * ain't nobody got time for that. 13201 */ 13202 dst_reg->smin_value = S64_MIN; 13203 dst_reg->smax_value = S64_MAX; 13204 } else { 13205 /* ORing two positives gives a positive, so safe to 13206 * cast result into s64. 13207 */ 13208 dst_reg->smin_value = dst_reg->umin_value; 13209 dst_reg->smax_value = dst_reg->umax_value; 13210 } 13211 /* We may learn something more from the var_off */ 13212 __update_reg_bounds(dst_reg); 13213 } 13214 13215 static void scalar32_min_max_xor(struct bpf_reg_state *dst_reg, 13216 struct bpf_reg_state *src_reg) 13217 { 13218 bool src_known = tnum_subreg_is_const(src_reg->var_off); 13219 bool dst_known = tnum_subreg_is_const(dst_reg->var_off); 13220 struct tnum var32_off = tnum_subreg(dst_reg->var_off); 13221 s32 smin_val = src_reg->s32_min_value; 13222 13223 if (src_known && dst_known) { 13224 __mark_reg32_known(dst_reg, var32_off.value); 13225 return; 13226 } 13227 13228 /* We get both minimum and maximum from the var32_off. */ 13229 dst_reg->u32_min_value = var32_off.value; 13230 dst_reg->u32_max_value = var32_off.value | var32_off.mask; 13231 13232 if (dst_reg->s32_min_value >= 0 && smin_val >= 0) { 13233 /* XORing two positive sign numbers gives a positive, 13234 * so safe to cast u32 result into s32. 13235 */ 13236 dst_reg->s32_min_value = dst_reg->u32_min_value; 13237 dst_reg->s32_max_value = dst_reg->u32_max_value; 13238 } else { 13239 dst_reg->s32_min_value = S32_MIN; 13240 dst_reg->s32_max_value = S32_MAX; 13241 } 13242 } 13243 13244 static void scalar_min_max_xor(struct bpf_reg_state *dst_reg, 13245 struct bpf_reg_state *src_reg) 13246 { 13247 bool src_known = tnum_is_const(src_reg->var_off); 13248 bool dst_known = tnum_is_const(dst_reg->var_off); 13249 s64 smin_val = src_reg->smin_value; 13250 13251 if (src_known && dst_known) { 13252 /* dst_reg->var_off.value has been updated earlier */ 13253 __mark_reg_known(dst_reg, dst_reg->var_off.value); 13254 return; 13255 } 13256 13257 /* We get both minimum and maximum from the var_off. */ 13258 dst_reg->umin_value = dst_reg->var_off.value; 13259 dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask; 13260 13261 if (dst_reg->smin_value >= 0 && smin_val >= 0) { 13262 /* XORing two positive sign numbers gives a positive, 13263 * so safe to cast u64 result into s64. 13264 */ 13265 dst_reg->smin_value = dst_reg->umin_value; 13266 dst_reg->smax_value = dst_reg->umax_value; 13267 } else { 13268 dst_reg->smin_value = S64_MIN; 13269 dst_reg->smax_value = S64_MAX; 13270 } 13271 13272 __update_reg_bounds(dst_reg); 13273 } 13274 13275 static void __scalar32_min_max_lsh(struct bpf_reg_state *dst_reg, 13276 u64 umin_val, u64 umax_val) 13277 { 13278 /* We lose all sign bit information (except what we can pick 13279 * up from var_off) 13280 */ 13281 dst_reg->s32_min_value = S32_MIN; 13282 dst_reg->s32_max_value = S32_MAX; 13283 /* If we might shift our top bit out, then we know nothing */ 13284 if (umax_val > 31 || dst_reg->u32_max_value > 1ULL << (31 - umax_val)) { 13285 dst_reg->u32_min_value = 0; 13286 dst_reg->u32_max_value = U32_MAX; 13287 } else { 13288 dst_reg->u32_min_value <<= umin_val; 13289 dst_reg->u32_max_value <<= umax_val; 13290 } 13291 } 13292 13293 static void scalar32_min_max_lsh(struct bpf_reg_state *dst_reg, 13294 struct bpf_reg_state *src_reg) 13295 { 13296 u32 umax_val = src_reg->u32_max_value; 13297 u32 umin_val = src_reg->u32_min_value; 13298 /* u32 alu operation will zext upper bits */ 13299 struct tnum subreg = tnum_subreg(dst_reg->var_off); 13300 13301 __scalar32_min_max_lsh(dst_reg, umin_val, umax_val); 13302 dst_reg->var_off = tnum_subreg(tnum_lshift(subreg, umin_val)); 13303 /* Not required but being careful mark reg64 bounds as unknown so 13304 * that we are forced to pick them up from tnum and zext later and 13305 * if some path skips this step we are still safe. 13306 */ 13307 __mark_reg64_unbounded(dst_reg); 13308 __update_reg32_bounds(dst_reg); 13309 } 13310 13311 static void __scalar64_min_max_lsh(struct bpf_reg_state *dst_reg, 13312 u64 umin_val, u64 umax_val) 13313 { 13314 /* Special case <<32 because it is a common compiler pattern to sign 13315 * extend subreg by doing <<32 s>>32. In this case if 32bit bounds are 13316 * positive we know this shift will also be positive so we can track 13317 * bounds correctly. Otherwise we lose all sign bit information except 13318 * what we can pick up from var_off. Perhaps we can generalize this 13319 * later to shifts of any length. 13320 */ 13321 if (umin_val == 32 && umax_val == 32 && dst_reg->s32_max_value >= 0) 13322 dst_reg->smax_value = (s64)dst_reg->s32_max_value << 32; 13323 else 13324 dst_reg->smax_value = S64_MAX; 13325 13326 if (umin_val == 32 && umax_val == 32 && dst_reg->s32_min_value >= 0) 13327 dst_reg->smin_value = (s64)dst_reg->s32_min_value << 32; 13328 else 13329 dst_reg->smin_value = S64_MIN; 13330 13331 /* If we might shift our top bit out, then we know nothing */ 13332 if (dst_reg->umax_value > 1ULL << (63 - umax_val)) { 13333 dst_reg->umin_value = 0; 13334 dst_reg->umax_value = U64_MAX; 13335 } else { 13336 dst_reg->umin_value <<= umin_val; 13337 dst_reg->umax_value <<= umax_val; 13338 } 13339 } 13340 13341 static void scalar_min_max_lsh(struct bpf_reg_state *dst_reg, 13342 struct bpf_reg_state *src_reg) 13343 { 13344 u64 umax_val = src_reg->umax_value; 13345 u64 umin_val = src_reg->umin_value; 13346 13347 /* scalar64 calc uses 32bit unshifted bounds so must be called first */ 13348 __scalar64_min_max_lsh(dst_reg, umin_val, umax_val); 13349 __scalar32_min_max_lsh(dst_reg, umin_val, umax_val); 13350 13351 dst_reg->var_off = tnum_lshift(dst_reg->var_off, umin_val); 13352 /* We may learn something more from the var_off */ 13353 __update_reg_bounds(dst_reg); 13354 } 13355 13356 static void scalar32_min_max_rsh(struct bpf_reg_state *dst_reg, 13357 struct bpf_reg_state *src_reg) 13358 { 13359 struct tnum subreg = tnum_subreg(dst_reg->var_off); 13360 u32 umax_val = src_reg->u32_max_value; 13361 u32 umin_val = src_reg->u32_min_value; 13362 13363 /* BPF_RSH is an unsigned shift. If the value in dst_reg might 13364 * be negative, then either: 13365 * 1) src_reg might be zero, so the sign bit of the result is 13366 * unknown, so we lose our signed bounds 13367 * 2) it's known negative, thus the unsigned bounds capture the 13368 * signed bounds 13369 * 3) the signed bounds cross zero, so they tell us nothing 13370 * about the result 13371 * If the value in dst_reg is known nonnegative, then again the 13372 * unsigned bounds capture the signed bounds. 13373 * Thus, in all cases it suffices to blow away our signed bounds 13374 * and rely on inferring new ones from the unsigned bounds and 13375 * var_off of the result. 13376 */ 13377 dst_reg->s32_min_value = S32_MIN; 13378 dst_reg->s32_max_value = S32_MAX; 13379 13380 dst_reg->var_off = tnum_rshift(subreg, umin_val); 13381 dst_reg->u32_min_value >>= umax_val; 13382 dst_reg->u32_max_value >>= umin_val; 13383 13384 __mark_reg64_unbounded(dst_reg); 13385 __update_reg32_bounds(dst_reg); 13386 } 13387 13388 static void scalar_min_max_rsh(struct bpf_reg_state *dst_reg, 13389 struct bpf_reg_state *src_reg) 13390 { 13391 u64 umax_val = src_reg->umax_value; 13392 u64 umin_val = src_reg->umin_value; 13393 13394 /* BPF_RSH is an unsigned shift. If the value in dst_reg might 13395 * be negative, then either: 13396 * 1) src_reg might be zero, so the sign bit of the result is 13397 * unknown, so we lose our signed bounds 13398 * 2) it's known negative, thus the unsigned bounds capture the 13399 * signed bounds 13400 * 3) the signed bounds cross zero, so they tell us nothing 13401 * about the result 13402 * If the value in dst_reg is known nonnegative, then again the 13403 * unsigned bounds capture the signed bounds. 13404 * Thus, in all cases it suffices to blow away our signed bounds 13405 * and rely on inferring new ones from the unsigned bounds and 13406 * var_off of the result. 13407 */ 13408 dst_reg->smin_value = S64_MIN; 13409 dst_reg->smax_value = S64_MAX; 13410 dst_reg->var_off = tnum_rshift(dst_reg->var_off, umin_val); 13411 dst_reg->umin_value >>= umax_val; 13412 dst_reg->umax_value >>= umin_val; 13413 13414 /* Its not easy to operate on alu32 bounds here because it depends 13415 * on bits being shifted in. Take easy way out and mark unbounded 13416 * so we can recalculate later from tnum. 13417 */ 13418 __mark_reg32_unbounded(dst_reg); 13419 __update_reg_bounds(dst_reg); 13420 } 13421 13422 static void scalar32_min_max_arsh(struct bpf_reg_state *dst_reg, 13423 struct bpf_reg_state *src_reg) 13424 { 13425 u64 umin_val = src_reg->u32_min_value; 13426 13427 /* Upon reaching here, src_known is true and 13428 * umax_val is equal to umin_val. 13429 */ 13430 dst_reg->s32_min_value = (u32)(((s32)dst_reg->s32_min_value) >> umin_val); 13431 dst_reg->s32_max_value = (u32)(((s32)dst_reg->s32_max_value) >> umin_val); 13432 13433 dst_reg->var_off = tnum_arshift(tnum_subreg(dst_reg->var_off), umin_val, 32); 13434 13435 /* blow away the dst_reg umin_value/umax_value and rely on 13436 * dst_reg var_off to refine the result. 13437 */ 13438 dst_reg->u32_min_value = 0; 13439 dst_reg->u32_max_value = U32_MAX; 13440 13441 __mark_reg64_unbounded(dst_reg); 13442 __update_reg32_bounds(dst_reg); 13443 } 13444 13445 static void scalar_min_max_arsh(struct bpf_reg_state *dst_reg, 13446 struct bpf_reg_state *src_reg) 13447 { 13448 u64 umin_val = src_reg->umin_value; 13449 13450 /* Upon reaching here, src_known is true and umax_val is equal 13451 * to umin_val. 13452 */ 13453 dst_reg->smin_value >>= umin_val; 13454 dst_reg->smax_value >>= umin_val; 13455 13456 dst_reg->var_off = tnum_arshift(dst_reg->var_off, umin_val, 64); 13457 13458 /* blow away the dst_reg umin_value/umax_value and rely on 13459 * dst_reg var_off to refine the result. 13460 */ 13461 dst_reg->umin_value = 0; 13462 dst_reg->umax_value = U64_MAX; 13463 13464 /* Its not easy to operate on alu32 bounds here because it depends 13465 * on bits being shifted in from upper 32-bits. Take easy way out 13466 * and mark unbounded so we can recalculate later from tnum. 13467 */ 13468 __mark_reg32_unbounded(dst_reg); 13469 __update_reg_bounds(dst_reg); 13470 } 13471 13472 /* WARNING: This function does calculations on 64-bit values, but the actual 13473 * execution may occur on 32-bit values. Therefore, things like bitshifts 13474 * need extra checks in the 32-bit case. 13475 */ 13476 static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env, 13477 struct bpf_insn *insn, 13478 struct bpf_reg_state *dst_reg, 13479 struct bpf_reg_state src_reg) 13480 { 13481 struct bpf_reg_state *regs = cur_regs(env); 13482 u8 opcode = BPF_OP(insn->code); 13483 bool src_known; 13484 s64 smin_val, smax_val; 13485 u64 umin_val, umax_val; 13486 s32 s32_min_val, s32_max_val; 13487 u32 u32_min_val, u32_max_val; 13488 u64 insn_bitness = (BPF_CLASS(insn->code) == BPF_ALU64) ? 64 : 32; 13489 bool alu32 = (BPF_CLASS(insn->code) != BPF_ALU64); 13490 int ret; 13491 13492 smin_val = src_reg.smin_value; 13493 smax_val = src_reg.smax_value; 13494 umin_val = src_reg.umin_value; 13495 umax_val = src_reg.umax_value; 13496 13497 s32_min_val = src_reg.s32_min_value; 13498 s32_max_val = src_reg.s32_max_value; 13499 u32_min_val = src_reg.u32_min_value; 13500 u32_max_val = src_reg.u32_max_value; 13501 13502 if (alu32) { 13503 src_known = tnum_subreg_is_const(src_reg.var_off); 13504 if ((src_known && 13505 (s32_min_val != s32_max_val || u32_min_val != u32_max_val)) || 13506 s32_min_val > s32_max_val || u32_min_val > u32_max_val) { 13507 /* Taint dst register if offset had invalid bounds 13508 * derived from e.g. dead branches. 13509 */ 13510 __mark_reg_unknown(env, dst_reg); 13511 return 0; 13512 } 13513 } else { 13514 src_known = tnum_is_const(src_reg.var_off); 13515 if ((src_known && 13516 (smin_val != smax_val || umin_val != umax_val)) || 13517 smin_val > smax_val || umin_val > umax_val) { 13518 /* Taint dst register if offset had invalid bounds 13519 * derived from e.g. dead branches. 13520 */ 13521 __mark_reg_unknown(env, dst_reg); 13522 return 0; 13523 } 13524 } 13525 13526 if (!src_known && 13527 opcode != BPF_ADD && opcode != BPF_SUB && opcode != BPF_AND) { 13528 __mark_reg_unknown(env, dst_reg); 13529 return 0; 13530 } 13531 13532 if (sanitize_needed(opcode)) { 13533 ret = sanitize_val_alu(env, insn); 13534 if (ret < 0) 13535 return sanitize_err(env, insn, ret, NULL, NULL); 13536 } 13537 13538 /* Calculate sign/unsigned bounds and tnum for alu32 and alu64 bit ops. 13539 * There are two classes of instructions: The first class we track both 13540 * alu32 and alu64 sign/unsigned bounds independently this provides the 13541 * greatest amount of precision when alu operations are mixed with jmp32 13542 * operations. These operations are BPF_ADD, BPF_SUB, BPF_MUL, BPF_ADD, 13543 * and BPF_OR. This is possible because these ops have fairly easy to 13544 * understand and calculate behavior in both 32-bit and 64-bit alu ops. 13545 * See alu32 verifier tests for examples. The second class of 13546 * operations, BPF_LSH, BPF_RSH, and BPF_ARSH, however are not so easy 13547 * with regards to tracking sign/unsigned bounds because the bits may 13548 * cross subreg boundaries in the alu64 case. When this happens we mark 13549 * the reg unbounded in the subreg bound space and use the resulting 13550 * tnum to calculate an approximation of the sign/unsigned bounds. 13551 */ 13552 switch (opcode) { 13553 case BPF_ADD: 13554 scalar32_min_max_add(dst_reg, &src_reg); 13555 scalar_min_max_add(dst_reg, &src_reg); 13556 dst_reg->var_off = tnum_add(dst_reg->var_off, src_reg.var_off); 13557 break; 13558 case BPF_SUB: 13559 scalar32_min_max_sub(dst_reg, &src_reg); 13560 scalar_min_max_sub(dst_reg, &src_reg); 13561 dst_reg->var_off = tnum_sub(dst_reg->var_off, src_reg.var_off); 13562 break; 13563 case BPF_MUL: 13564 dst_reg->var_off = tnum_mul(dst_reg->var_off, src_reg.var_off); 13565 scalar32_min_max_mul(dst_reg, &src_reg); 13566 scalar_min_max_mul(dst_reg, &src_reg); 13567 break; 13568 case BPF_AND: 13569 dst_reg->var_off = tnum_and(dst_reg->var_off, src_reg.var_off); 13570 scalar32_min_max_and(dst_reg, &src_reg); 13571 scalar_min_max_and(dst_reg, &src_reg); 13572 break; 13573 case BPF_OR: 13574 dst_reg->var_off = tnum_or(dst_reg->var_off, src_reg.var_off); 13575 scalar32_min_max_or(dst_reg, &src_reg); 13576 scalar_min_max_or(dst_reg, &src_reg); 13577 break; 13578 case BPF_XOR: 13579 dst_reg->var_off = tnum_xor(dst_reg->var_off, src_reg.var_off); 13580 scalar32_min_max_xor(dst_reg, &src_reg); 13581 scalar_min_max_xor(dst_reg, &src_reg); 13582 break; 13583 case BPF_LSH: 13584 if (umax_val >= insn_bitness) { 13585 /* Shifts greater than 31 or 63 are undefined. 13586 * This includes shifts by a negative number. 13587 */ 13588 mark_reg_unknown(env, regs, insn->dst_reg); 13589 break; 13590 } 13591 if (alu32) 13592 scalar32_min_max_lsh(dst_reg, &src_reg); 13593 else 13594 scalar_min_max_lsh(dst_reg, &src_reg); 13595 break; 13596 case BPF_RSH: 13597 if (umax_val >= insn_bitness) { 13598 /* Shifts greater than 31 or 63 are undefined. 13599 * This includes shifts by a negative number. 13600 */ 13601 mark_reg_unknown(env, regs, insn->dst_reg); 13602 break; 13603 } 13604 if (alu32) 13605 scalar32_min_max_rsh(dst_reg, &src_reg); 13606 else 13607 scalar_min_max_rsh(dst_reg, &src_reg); 13608 break; 13609 case BPF_ARSH: 13610 if (umax_val >= insn_bitness) { 13611 /* Shifts greater than 31 or 63 are undefined. 13612 * This includes shifts by a negative number. 13613 */ 13614 mark_reg_unknown(env, regs, insn->dst_reg); 13615 break; 13616 } 13617 if (alu32) 13618 scalar32_min_max_arsh(dst_reg, &src_reg); 13619 else 13620 scalar_min_max_arsh(dst_reg, &src_reg); 13621 break; 13622 default: 13623 mark_reg_unknown(env, regs, insn->dst_reg); 13624 break; 13625 } 13626 13627 /* ALU32 ops are zero extended into 64bit register */ 13628 if (alu32) 13629 zext_32_to_64(dst_reg); 13630 reg_bounds_sync(dst_reg); 13631 return 0; 13632 } 13633 13634 /* Handles ALU ops other than BPF_END, BPF_NEG and BPF_MOV: computes new min/max 13635 * and var_off. 13636 */ 13637 static int adjust_reg_min_max_vals(struct bpf_verifier_env *env, 13638 struct bpf_insn *insn) 13639 { 13640 struct bpf_verifier_state *vstate = env->cur_state; 13641 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 13642 struct bpf_reg_state *regs = state->regs, *dst_reg, *src_reg; 13643 struct bpf_reg_state *ptr_reg = NULL, off_reg = {0}; 13644 u8 opcode = BPF_OP(insn->code); 13645 int err; 13646 13647 dst_reg = ®s[insn->dst_reg]; 13648 src_reg = NULL; 13649 if (dst_reg->type != SCALAR_VALUE) 13650 ptr_reg = dst_reg; 13651 else 13652 /* Make sure ID is cleared otherwise dst_reg min/max could be 13653 * incorrectly propagated into other registers by find_equal_scalars() 13654 */ 13655 dst_reg->id = 0; 13656 if (BPF_SRC(insn->code) == BPF_X) { 13657 src_reg = ®s[insn->src_reg]; 13658 if (src_reg->type != SCALAR_VALUE) { 13659 if (dst_reg->type != SCALAR_VALUE) { 13660 /* Combining two pointers by any ALU op yields 13661 * an arbitrary scalar. Disallow all math except 13662 * pointer subtraction 13663 */ 13664 if (opcode == BPF_SUB && env->allow_ptr_leaks) { 13665 mark_reg_unknown(env, regs, insn->dst_reg); 13666 return 0; 13667 } 13668 verbose(env, "R%d pointer %s pointer prohibited\n", 13669 insn->dst_reg, 13670 bpf_alu_string[opcode >> 4]); 13671 return -EACCES; 13672 } else { 13673 /* scalar += pointer 13674 * This is legal, but we have to reverse our 13675 * src/dest handling in computing the range 13676 */ 13677 err = mark_chain_precision(env, insn->dst_reg); 13678 if (err) 13679 return err; 13680 return adjust_ptr_min_max_vals(env, insn, 13681 src_reg, dst_reg); 13682 } 13683 } else if (ptr_reg) { 13684 /* pointer += scalar */ 13685 err = mark_chain_precision(env, insn->src_reg); 13686 if (err) 13687 return err; 13688 return adjust_ptr_min_max_vals(env, insn, 13689 dst_reg, src_reg); 13690 } else if (dst_reg->precise) { 13691 /* if dst_reg is precise, src_reg should be precise as well */ 13692 err = mark_chain_precision(env, insn->src_reg); 13693 if (err) 13694 return err; 13695 } 13696 } else { 13697 /* Pretend the src is a reg with a known value, since we only 13698 * need to be able to read from this state. 13699 */ 13700 off_reg.type = SCALAR_VALUE; 13701 __mark_reg_known(&off_reg, insn->imm); 13702 src_reg = &off_reg; 13703 if (ptr_reg) /* pointer += K */ 13704 return adjust_ptr_min_max_vals(env, insn, 13705 ptr_reg, src_reg); 13706 } 13707 13708 /* Got here implies adding two SCALAR_VALUEs */ 13709 if (WARN_ON_ONCE(ptr_reg)) { 13710 print_verifier_state(env, state, true); 13711 verbose(env, "verifier internal error: unexpected ptr_reg\n"); 13712 return -EINVAL; 13713 } 13714 if (WARN_ON(!src_reg)) { 13715 print_verifier_state(env, state, true); 13716 verbose(env, "verifier internal error: no src_reg\n"); 13717 return -EINVAL; 13718 } 13719 return adjust_scalar_min_max_vals(env, insn, dst_reg, *src_reg); 13720 } 13721 13722 /* check validity of 32-bit and 64-bit arithmetic operations */ 13723 static int check_alu_op(struct bpf_verifier_env *env, struct bpf_insn *insn) 13724 { 13725 struct bpf_reg_state *regs = cur_regs(env); 13726 u8 opcode = BPF_OP(insn->code); 13727 int err; 13728 13729 if (opcode == BPF_END || opcode == BPF_NEG) { 13730 if (opcode == BPF_NEG) { 13731 if (BPF_SRC(insn->code) != BPF_K || 13732 insn->src_reg != BPF_REG_0 || 13733 insn->off != 0 || insn->imm != 0) { 13734 verbose(env, "BPF_NEG uses reserved fields\n"); 13735 return -EINVAL; 13736 } 13737 } else { 13738 if (insn->src_reg != BPF_REG_0 || insn->off != 0 || 13739 (insn->imm != 16 && insn->imm != 32 && insn->imm != 64) || 13740 (BPF_CLASS(insn->code) == BPF_ALU64 && 13741 BPF_SRC(insn->code) != BPF_TO_LE)) { 13742 verbose(env, "BPF_END uses reserved fields\n"); 13743 return -EINVAL; 13744 } 13745 } 13746 13747 /* check src operand */ 13748 err = check_reg_arg(env, insn->dst_reg, SRC_OP); 13749 if (err) 13750 return err; 13751 13752 if (is_pointer_value(env, insn->dst_reg)) { 13753 verbose(env, "R%d pointer arithmetic prohibited\n", 13754 insn->dst_reg); 13755 return -EACCES; 13756 } 13757 13758 /* check dest operand */ 13759 err = check_reg_arg(env, insn->dst_reg, DST_OP); 13760 if (err) 13761 return err; 13762 13763 } else if (opcode == BPF_MOV) { 13764 13765 if (BPF_SRC(insn->code) == BPF_X) { 13766 if (insn->imm != 0) { 13767 verbose(env, "BPF_MOV uses reserved fields\n"); 13768 return -EINVAL; 13769 } 13770 13771 if (BPF_CLASS(insn->code) == BPF_ALU) { 13772 if (insn->off != 0 && insn->off != 8 && insn->off != 16) { 13773 verbose(env, "BPF_MOV uses reserved fields\n"); 13774 return -EINVAL; 13775 } 13776 } else { 13777 if (insn->off != 0 && insn->off != 8 && insn->off != 16 && 13778 insn->off != 32) { 13779 verbose(env, "BPF_MOV uses reserved fields\n"); 13780 return -EINVAL; 13781 } 13782 } 13783 13784 /* check src operand */ 13785 err = check_reg_arg(env, insn->src_reg, SRC_OP); 13786 if (err) 13787 return err; 13788 } else { 13789 if (insn->src_reg != BPF_REG_0 || insn->off != 0) { 13790 verbose(env, "BPF_MOV uses reserved fields\n"); 13791 return -EINVAL; 13792 } 13793 } 13794 13795 /* check dest operand, mark as required later */ 13796 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK); 13797 if (err) 13798 return err; 13799 13800 if (BPF_SRC(insn->code) == BPF_X) { 13801 struct bpf_reg_state *src_reg = regs + insn->src_reg; 13802 struct bpf_reg_state *dst_reg = regs + insn->dst_reg; 13803 bool need_id = src_reg->type == SCALAR_VALUE && !src_reg->id && 13804 !tnum_is_const(src_reg->var_off); 13805 13806 if (BPF_CLASS(insn->code) == BPF_ALU64) { 13807 if (insn->off == 0) { 13808 /* case: R1 = R2 13809 * copy register state to dest reg 13810 */ 13811 if (need_id) 13812 /* Assign src and dst registers the same ID 13813 * that will be used by find_equal_scalars() 13814 * to propagate min/max range. 13815 */ 13816 src_reg->id = ++env->id_gen; 13817 copy_register_state(dst_reg, src_reg); 13818 dst_reg->live |= REG_LIVE_WRITTEN; 13819 dst_reg->subreg_def = DEF_NOT_SUBREG; 13820 } else { 13821 /* case: R1 = (s8, s16 s32)R2 */ 13822 if (is_pointer_value(env, insn->src_reg)) { 13823 verbose(env, 13824 "R%d sign-extension part of pointer\n", 13825 insn->src_reg); 13826 return -EACCES; 13827 } else if (src_reg->type == SCALAR_VALUE) { 13828 bool no_sext; 13829 13830 no_sext = src_reg->umax_value < (1ULL << (insn->off - 1)); 13831 if (no_sext && need_id) 13832 src_reg->id = ++env->id_gen; 13833 copy_register_state(dst_reg, src_reg); 13834 if (!no_sext) 13835 dst_reg->id = 0; 13836 coerce_reg_to_size_sx(dst_reg, insn->off >> 3); 13837 dst_reg->live |= REG_LIVE_WRITTEN; 13838 dst_reg->subreg_def = DEF_NOT_SUBREG; 13839 } else { 13840 mark_reg_unknown(env, regs, insn->dst_reg); 13841 } 13842 } 13843 } else { 13844 /* R1 = (u32) R2 */ 13845 if (is_pointer_value(env, insn->src_reg)) { 13846 verbose(env, 13847 "R%d partial copy of pointer\n", 13848 insn->src_reg); 13849 return -EACCES; 13850 } else if (src_reg->type == SCALAR_VALUE) { 13851 if (insn->off == 0) { 13852 bool is_src_reg_u32 = src_reg->umax_value <= U32_MAX; 13853 13854 if (is_src_reg_u32 && need_id) 13855 src_reg->id = ++env->id_gen; 13856 copy_register_state(dst_reg, src_reg); 13857 /* Make sure ID is cleared if src_reg is not in u32 13858 * range otherwise dst_reg min/max could be incorrectly 13859 * propagated into src_reg by find_equal_scalars() 13860 */ 13861 if (!is_src_reg_u32) 13862 dst_reg->id = 0; 13863 dst_reg->live |= REG_LIVE_WRITTEN; 13864 dst_reg->subreg_def = env->insn_idx + 1; 13865 } else { 13866 /* case: W1 = (s8, s16)W2 */ 13867 bool no_sext = src_reg->umax_value < (1ULL << (insn->off - 1)); 13868 13869 if (no_sext && need_id) 13870 src_reg->id = ++env->id_gen; 13871 copy_register_state(dst_reg, src_reg); 13872 if (!no_sext) 13873 dst_reg->id = 0; 13874 dst_reg->live |= REG_LIVE_WRITTEN; 13875 dst_reg->subreg_def = env->insn_idx + 1; 13876 coerce_subreg_to_size_sx(dst_reg, insn->off >> 3); 13877 } 13878 } else { 13879 mark_reg_unknown(env, regs, 13880 insn->dst_reg); 13881 } 13882 zext_32_to_64(dst_reg); 13883 reg_bounds_sync(dst_reg); 13884 } 13885 } else { 13886 /* case: R = imm 13887 * remember the value we stored into this reg 13888 */ 13889 /* clear any state __mark_reg_known doesn't set */ 13890 mark_reg_unknown(env, regs, insn->dst_reg); 13891 regs[insn->dst_reg].type = SCALAR_VALUE; 13892 if (BPF_CLASS(insn->code) == BPF_ALU64) { 13893 __mark_reg_known(regs + insn->dst_reg, 13894 insn->imm); 13895 } else { 13896 __mark_reg_known(regs + insn->dst_reg, 13897 (u32)insn->imm); 13898 } 13899 } 13900 13901 } else if (opcode > BPF_END) { 13902 verbose(env, "invalid BPF_ALU opcode %x\n", opcode); 13903 return -EINVAL; 13904 13905 } else { /* all other ALU ops: and, sub, xor, add, ... */ 13906 13907 if (BPF_SRC(insn->code) == BPF_X) { 13908 if (insn->imm != 0 || insn->off > 1 || 13909 (insn->off == 1 && opcode != BPF_MOD && opcode != BPF_DIV)) { 13910 verbose(env, "BPF_ALU uses reserved fields\n"); 13911 return -EINVAL; 13912 } 13913 /* check src1 operand */ 13914 err = check_reg_arg(env, insn->src_reg, SRC_OP); 13915 if (err) 13916 return err; 13917 } else { 13918 if (insn->src_reg != BPF_REG_0 || insn->off > 1 || 13919 (insn->off == 1 && opcode != BPF_MOD && opcode != BPF_DIV)) { 13920 verbose(env, "BPF_ALU uses reserved fields\n"); 13921 return -EINVAL; 13922 } 13923 } 13924 13925 /* check src2 operand */ 13926 err = check_reg_arg(env, insn->dst_reg, SRC_OP); 13927 if (err) 13928 return err; 13929 13930 if ((opcode == BPF_MOD || opcode == BPF_DIV) && 13931 BPF_SRC(insn->code) == BPF_K && insn->imm == 0) { 13932 verbose(env, "div by zero\n"); 13933 return -EINVAL; 13934 } 13935 13936 if ((opcode == BPF_LSH || opcode == BPF_RSH || 13937 opcode == BPF_ARSH) && BPF_SRC(insn->code) == BPF_K) { 13938 int size = BPF_CLASS(insn->code) == BPF_ALU64 ? 64 : 32; 13939 13940 if (insn->imm < 0 || insn->imm >= size) { 13941 verbose(env, "invalid shift %d\n", insn->imm); 13942 return -EINVAL; 13943 } 13944 } 13945 13946 /* check dest operand */ 13947 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK); 13948 err = err ?: adjust_reg_min_max_vals(env, insn); 13949 if (err) 13950 return err; 13951 } 13952 13953 return reg_bounds_sanity_check(env, ®s[insn->dst_reg], "alu"); 13954 } 13955 13956 static void find_good_pkt_pointers(struct bpf_verifier_state *vstate, 13957 struct bpf_reg_state *dst_reg, 13958 enum bpf_reg_type type, 13959 bool range_right_open) 13960 { 13961 struct bpf_func_state *state; 13962 struct bpf_reg_state *reg; 13963 int new_range; 13964 13965 if (dst_reg->off < 0 || 13966 (dst_reg->off == 0 && range_right_open)) 13967 /* This doesn't give us any range */ 13968 return; 13969 13970 if (dst_reg->umax_value > MAX_PACKET_OFF || 13971 dst_reg->umax_value + dst_reg->off > MAX_PACKET_OFF) 13972 /* Risk of overflow. For instance, ptr + (1<<63) may be less 13973 * than pkt_end, but that's because it's also less than pkt. 13974 */ 13975 return; 13976 13977 new_range = dst_reg->off; 13978 if (range_right_open) 13979 new_range++; 13980 13981 /* Examples for register markings: 13982 * 13983 * pkt_data in dst register: 13984 * 13985 * r2 = r3; 13986 * r2 += 8; 13987 * if (r2 > pkt_end) goto <handle exception> 13988 * <access okay> 13989 * 13990 * r2 = r3; 13991 * r2 += 8; 13992 * if (r2 < pkt_end) goto <access okay> 13993 * <handle exception> 13994 * 13995 * Where: 13996 * r2 == dst_reg, pkt_end == src_reg 13997 * r2=pkt(id=n,off=8,r=0) 13998 * r3=pkt(id=n,off=0,r=0) 13999 * 14000 * pkt_data in src register: 14001 * 14002 * r2 = r3; 14003 * r2 += 8; 14004 * if (pkt_end >= r2) goto <access okay> 14005 * <handle exception> 14006 * 14007 * r2 = r3; 14008 * r2 += 8; 14009 * if (pkt_end <= r2) goto <handle exception> 14010 * <access okay> 14011 * 14012 * Where: 14013 * pkt_end == dst_reg, r2 == src_reg 14014 * r2=pkt(id=n,off=8,r=0) 14015 * r3=pkt(id=n,off=0,r=0) 14016 * 14017 * Find register r3 and mark its range as r3=pkt(id=n,off=0,r=8) 14018 * or r3=pkt(id=n,off=0,r=8-1), so that range of bytes [r3, r3 + 8) 14019 * and [r3, r3 + 8-1) respectively is safe to access depending on 14020 * the check. 14021 */ 14022 14023 /* If our ids match, then we must have the same max_value. And we 14024 * don't care about the other reg's fixed offset, since if it's too big 14025 * the range won't allow anything. 14026 * dst_reg->off is known < MAX_PACKET_OFF, therefore it fits in a u16. 14027 */ 14028 bpf_for_each_reg_in_vstate(vstate, state, reg, ({ 14029 if (reg->type == type && reg->id == dst_reg->id) 14030 /* keep the maximum range already checked */ 14031 reg->range = max(reg->range, new_range); 14032 })); 14033 } 14034 14035 /* 14036 * <reg1> <op> <reg2>, currently assuming reg2 is a constant 14037 */ 14038 static int is_scalar_branch_taken(struct bpf_reg_state *reg1, struct bpf_reg_state *reg2, 14039 u8 opcode, bool is_jmp32) 14040 { 14041 struct tnum t1 = is_jmp32 ? tnum_subreg(reg1->var_off) : reg1->var_off; 14042 struct tnum t2 = is_jmp32 ? tnum_subreg(reg2->var_off) : reg2->var_off; 14043 u64 umin1 = is_jmp32 ? (u64)reg1->u32_min_value : reg1->umin_value; 14044 u64 umax1 = is_jmp32 ? (u64)reg1->u32_max_value : reg1->umax_value; 14045 s64 smin1 = is_jmp32 ? (s64)reg1->s32_min_value : reg1->smin_value; 14046 s64 smax1 = is_jmp32 ? (s64)reg1->s32_max_value : reg1->smax_value; 14047 u64 umin2 = is_jmp32 ? (u64)reg2->u32_min_value : reg2->umin_value; 14048 u64 umax2 = is_jmp32 ? (u64)reg2->u32_max_value : reg2->umax_value; 14049 s64 smin2 = is_jmp32 ? (s64)reg2->s32_min_value : reg2->smin_value; 14050 s64 smax2 = is_jmp32 ? (s64)reg2->s32_max_value : reg2->smax_value; 14051 14052 switch (opcode) { 14053 case BPF_JEQ: 14054 /* constants, umin/umax and smin/smax checks would be 14055 * redundant in this case because they all should match 14056 */ 14057 if (tnum_is_const(t1) && tnum_is_const(t2)) 14058 return t1.value == t2.value; 14059 /* non-overlapping ranges */ 14060 if (umin1 > umax2 || umax1 < umin2) 14061 return 0; 14062 if (smin1 > smax2 || smax1 < smin2) 14063 return 0; 14064 if (!is_jmp32) { 14065 /* if 64-bit ranges are inconclusive, see if we can 14066 * utilize 32-bit subrange knowledge to eliminate 14067 * branches that can't be taken a priori 14068 */ 14069 if (reg1->u32_min_value > reg2->u32_max_value || 14070 reg1->u32_max_value < reg2->u32_min_value) 14071 return 0; 14072 if (reg1->s32_min_value > reg2->s32_max_value || 14073 reg1->s32_max_value < reg2->s32_min_value) 14074 return 0; 14075 } 14076 break; 14077 case BPF_JNE: 14078 /* constants, umin/umax and smin/smax checks would be 14079 * redundant in this case because they all should match 14080 */ 14081 if (tnum_is_const(t1) && tnum_is_const(t2)) 14082 return t1.value != t2.value; 14083 /* non-overlapping ranges */ 14084 if (umin1 > umax2 || umax1 < umin2) 14085 return 1; 14086 if (smin1 > smax2 || smax1 < smin2) 14087 return 1; 14088 if (!is_jmp32) { 14089 /* if 64-bit ranges are inconclusive, see if we can 14090 * utilize 32-bit subrange knowledge to eliminate 14091 * branches that can't be taken a priori 14092 */ 14093 if (reg1->u32_min_value > reg2->u32_max_value || 14094 reg1->u32_max_value < reg2->u32_min_value) 14095 return 1; 14096 if (reg1->s32_min_value > reg2->s32_max_value || 14097 reg1->s32_max_value < reg2->s32_min_value) 14098 return 1; 14099 } 14100 break; 14101 case BPF_JSET: 14102 if (!is_reg_const(reg2, is_jmp32)) { 14103 swap(reg1, reg2); 14104 swap(t1, t2); 14105 } 14106 if (!is_reg_const(reg2, is_jmp32)) 14107 return -1; 14108 if ((~t1.mask & t1.value) & t2.value) 14109 return 1; 14110 if (!((t1.mask | t1.value) & t2.value)) 14111 return 0; 14112 break; 14113 case BPF_JGT: 14114 if (umin1 > umax2) 14115 return 1; 14116 else if (umax1 <= umin2) 14117 return 0; 14118 break; 14119 case BPF_JSGT: 14120 if (smin1 > smax2) 14121 return 1; 14122 else if (smax1 <= smin2) 14123 return 0; 14124 break; 14125 case BPF_JLT: 14126 if (umax1 < umin2) 14127 return 1; 14128 else if (umin1 >= umax2) 14129 return 0; 14130 break; 14131 case BPF_JSLT: 14132 if (smax1 < smin2) 14133 return 1; 14134 else if (smin1 >= smax2) 14135 return 0; 14136 break; 14137 case BPF_JGE: 14138 if (umin1 >= umax2) 14139 return 1; 14140 else if (umax1 < umin2) 14141 return 0; 14142 break; 14143 case BPF_JSGE: 14144 if (smin1 >= smax2) 14145 return 1; 14146 else if (smax1 < smin2) 14147 return 0; 14148 break; 14149 case BPF_JLE: 14150 if (umax1 <= umin2) 14151 return 1; 14152 else if (umin1 > umax2) 14153 return 0; 14154 break; 14155 case BPF_JSLE: 14156 if (smax1 <= smin2) 14157 return 1; 14158 else if (smin1 > smax2) 14159 return 0; 14160 break; 14161 } 14162 14163 return -1; 14164 } 14165 14166 static int flip_opcode(u32 opcode) 14167 { 14168 /* How can we transform "a <op> b" into "b <op> a"? */ 14169 static const u8 opcode_flip[16] = { 14170 /* these stay the same */ 14171 [BPF_JEQ >> 4] = BPF_JEQ, 14172 [BPF_JNE >> 4] = BPF_JNE, 14173 [BPF_JSET >> 4] = BPF_JSET, 14174 /* these swap "lesser" and "greater" (L and G in the opcodes) */ 14175 [BPF_JGE >> 4] = BPF_JLE, 14176 [BPF_JGT >> 4] = BPF_JLT, 14177 [BPF_JLE >> 4] = BPF_JGE, 14178 [BPF_JLT >> 4] = BPF_JGT, 14179 [BPF_JSGE >> 4] = BPF_JSLE, 14180 [BPF_JSGT >> 4] = BPF_JSLT, 14181 [BPF_JSLE >> 4] = BPF_JSGE, 14182 [BPF_JSLT >> 4] = BPF_JSGT 14183 }; 14184 return opcode_flip[opcode >> 4]; 14185 } 14186 14187 static int is_pkt_ptr_branch_taken(struct bpf_reg_state *dst_reg, 14188 struct bpf_reg_state *src_reg, 14189 u8 opcode) 14190 { 14191 struct bpf_reg_state *pkt; 14192 14193 if (src_reg->type == PTR_TO_PACKET_END) { 14194 pkt = dst_reg; 14195 } else if (dst_reg->type == PTR_TO_PACKET_END) { 14196 pkt = src_reg; 14197 opcode = flip_opcode(opcode); 14198 } else { 14199 return -1; 14200 } 14201 14202 if (pkt->range >= 0) 14203 return -1; 14204 14205 switch (opcode) { 14206 case BPF_JLE: 14207 /* pkt <= pkt_end */ 14208 fallthrough; 14209 case BPF_JGT: 14210 /* pkt > pkt_end */ 14211 if (pkt->range == BEYOND_PKT_END) 14212 /* pkt has at last one extra byte beyond pkt_end */ 14213 return opcode == BPF_JGT; 14214 break; 14215 case BPF_JLT: 14216 /* pkt < pkt_end */ 14217 fallthrough; 14218 case BPF_JGE: 14219 /* pkt >= pkt_end */ 14220 if (pkt->range == BEYOND_PKT_END || pkt->range == AT_PKT_END) 14221 return opcode == BPF_JGE; 14222 break; 14223 } 14224 return -1; 14225 } 14226 14227 /* compute branch direction of the expression "if (<reg1> opcode <reg2>) goto target;" 14228 * and return: 14229 * 1 - branch will be taken and "goto target" will be executed 14230 * 0 - branch will not be taken and fall-through to next insn 14231 * -1 - unknown. Example: "if (reg1 < 5)" is unknown when register value 14232 * range [0,10] 14233 */ 14234 static int is_branch_taken(struct bpf_reg_state *reg1, struct bpf_reg_state *reg2, 14235 u8 opcode, bool is_jmp32) 14236 { 14237 if (reg_is_pkt_pointer_any(reg1) && reg_is_pkt_pointer_any(reg2) && !is_jmp32) 14238 return is_pkt_ptr_branch_taken(reg1, reg2, opcode); 14239 14240 if (__is_pointer_value(false, reg1) || __is_pointer_value(false, reg2)) { 14241 u64 val; 14242 14243 /* arrange that reg2 is a scalar, and reg1 is a pointer */ 14244 if (!is_reg_const(reg2, is_jmp32)) { 14245 opcode = flip_opcode(opcode); 14246 swap(reg1, reg2); 14247 } 14248 /* and ensure that reg2 is a constant */ 14249 if (!is_reg_const(reg2, is_jmp32)) 14250 return -1; 14251 14252 if (!reg_not_null(reg1)) 14253 return -1; 14254 14255 /* If pointer is valid tests against zero will fail so we can 14256 * use this to direct branch taken. 14257 */ 14258 val = reg_const_value(reg2, is_jmp32); 14259 if (val != 0) 14260 return -1; 14261 14262 switch (opcode) { 14263 case BPF_JEQ: 14264 return 0; 14265 case BPF_JNE: 14266 return 1; 14267 default: 14268 return -1; 14269 } 14270 } 14271 14272 /* now deal with two scalars, but not necessarily constants */ 14273 return is_scalar_branch_taken(reg1, reg2, opcode, is_jmp32); 14274 } 14275 14276 /* Opcode that corresponds to a *false* branch condition. 14277 * E.g., if r1 < r2, then reverse (false) condition is r1 >= r2 14278 */ 14279 static u8 rev_opcode(u8 opcode) 14280 { 14281 switch (opcode) { 14282 case BPF_JEQ: return BPF_JNE; 14283 case BPF_JNE: return BPF_JEQ; 14284 /* JSET doesn't have it's reverse opcode in BPF, so add 14285 * BPF_X flag to denote the reverse of that operation 14286 */ 14287 case BPF_JSET: return BPF_JSET | BPF_X; 14288 case BPF_JSET | BPF_X: return BPF_JSET; 14289 case BPF_JGE: return BPF_JLT; 14290 case BPF_JGT: return BPF_JLE; 14291 case BPF_JLE: return BPF_JGT; 14292 case BPF_JLT: return BPF_JGE; 14293 case BPF_JSGE: return BPF_JSLT; 14294 case BPF_JSGT: return BPF_JSLE; 14295 case BPF_JSLE: return BPF_JSGT; 14296 case BPF_JSLT: return BPF_JSGE; 14297 default: return 0; 14298 } 14299 } 14300 14301 /* Refine range knowledge for <reg1> <op> <reg>2 conditional operation. */ 14302 static void regs_refine_cond_op(struct bpf_reg_state *reg1, struct bpf_reg_state *reg2, 14303 u8 opcode, bool is_jmp32) 14304 { 14305 struct tnum t; 14306 u64 val; 14307 14308 again: 14309 switch (opcode) { 14310 case BPF_JEQ: 14311 if (is_jmp32) { 14312 reg1->u32_min_value = max(reg1->u32_min_value, reg2->u32_min_value); 14313 reg1->u32_max_value = min(reg1->u32_max_value, reg2->u32_max_value); 14314 reg1->s32_min_value = max(reg1->s32_min_value, reg2->s32_min_value); 14315 reg1->s32_max_value = min(reg1->s32_max_value, reg2->s32_max_value); 14316 reg2->u32_min_value = reg1->u32_min_value; 14317 reg2->u32_max_value = reg1->u32_max_value; 14318 reg2->s32_min_value = reg1->s32_min_value; 14319 reg2->s32_max_value = reg1->s32_max_value; 14320 14321 t = tnum_intersect(tnum_subreg(reg1->var_off), tnum_subreg(reg2->var_off)); 14322 reg1->var_off = tnum_with_subreg(reg1->var_off, t); 14323 reg2->var_off = tnum_with_subreg(reg2->var_off, t); 14324 } else { 14325 reg1->umin_value = max(reg1->umin_value, reg2->umin_value); 14326 reg1->umax_value = min(reg1->umax_value, reg2->umax_value); 14327 reg1->smin_value = max(reg1->smin_value, reg2->smin_value); 14328 reg1->smax_value = min(reg1->smax_value, reg2->smax_value); 14329 reg2->umin_value = reg1->umin_value; 14330 reg2->umax_value = reg1->umax_value; 14331 reg2->smin_value = reg1->smin_value; 14332 reg2->smax_value = reg1->smax_value; 14333 14334 reg1->var_off = tnum_intersect(reg1->var_off, reg2->var_off); 14335 reg2->var_off = reg1->var_off; 14336 } 14337 break; 14338 case BPF_JNE: 14339 /* we don't derive any new information for inequality yet */ 14340 break; 14341 case BPF_JSET: 14342 if (!is_reg_const(reg2, is_jmp32)) 14343 swap(reg1, reg2); 14344 if (!is_reg_const(reg2, is_jmp32)) 14345 break; 14346 val = reg_const_value(reg2, is_jmp32); 14347 /* BPF_JSET (i.e., TRUE branch, *not* BPF_JSET | BPF_X) 14348 * requires single bit to learn something useful. E.g., if we 14349 * know that `r1 & 0x3` is true, then which bits (0, 1, or both) 14350 * are actually set? We can learn something definite only if 14351 * it's a single-bit value to begin with. 14352 * 14353 * BPF_JSET | BPF_X (i.e., negation of BPF_JSET) doesn't have 14354 * this restriction. I.e., !(r1 & 0x3) means neither bit 0 nor 14355 * bit 1 is set, which we can readily use in adjustments. 14356 */ 14357 if (!is_power_of_2(val)) 14358 break; 14359 if (is_jmp32) { 14360 t = tnum_or(tnum_subreg(reg1->var_off), tnum_const(val)); 14361 reg1->var_off = tnum_with_subreg(reg1->var_off, t); 14362 } else { 14363 reg1->var_off = tnum_or(reg1->var_off, tnum_const(val)); 14364 } 14365 break; 14366 case BPF_JSET | BPF_X: /* reverse of BPF_JSET, see rev_opcode() */ 14367 if (!is_reg_const(reg2, is_jmp32)) 14368 swap(reg1, reg2); 14369 if (!is_reg_const(reg2, is_jmp32)) 14370 break; 14371 val = reg_const_value(reg2, is_jmp32); 14372 if (is_jmp32) { 14373 t = tnum_and(tnum_subreg(reg1->var_off), tnum_const(~val)); 14374 reg1->var_off = tnum_with_subreg(reg1->var_off, t); 14375 } else { 14376 reg1->var_off = tnum_and(reg1->var_off, tnum_const(~val)); 14377 } 14378 break; 14379 case BPF_JLE: 14380 if (is_jmp32) { 14381 reg1->u32_max_value = min(reg1->u32_max_value, reg2->u32_max_value); 14382 reg2->u32_min_value = max(reg1->u32_min_value, reg2->u32_min_value); 14383 } else { 14384 reg1->umax_value = min(reg1->umax_value, reg2->umax_value); 14385 reg2->umin_value = max(reg1->umin_value, reg2->umin_value); 14386 } 14387 break; 14388 case BPF_JLT: 14389 if (is_jmp32) { 14390 reg1->u32_max_value = min(reg1->u32_max_value, reg2->u32_max_value - 1); 14391 reg2->u32_min_value = max(reg1->u32_min_value + 1, reg2->u32_min_value); 14392 } else { 14393 reg1->umax_value = min(reg1->umax_value, reg2->umax_value - 1); 14394 reg2->umin_value = max(reg1->umin_value + 1, reg2->umin_value); 14395 } 14396 break; 14397 case BPF_JSLE: 14398 if (is_jmp32) { 14399 reg1->s32_max_value = min(reg1->s32_max_value, reg2->s32_max_value); 14400 reg2->s32_min_value = max(reg1->s32_min_value, reg2->s32_min_value); 14401 } else { 14402 reg1->smax_value = min(reg1->smax_value, reg2->smax_value); 14403 reg2->smin_value = max(reg1->smin_value, reg2->smin_value); 14404 } 14405 break; 14406 case BPF_JSLT: 14407 if (is_jmp32) { 14408 reg1->s32_max_value = min(reg1->s32_max_value, reg2->s32_max_value - 1); 14409 reg2->s32_min_value = max(reg1->s32_min_value + 1, reg2->s32_min_value); 14410 } else { 14411 reg1->smax_value = min(reg1->smax_value, reg2->smax_value - 1); 14412 reg2->smin_value = max(reg1->smin_value + 1, reg2->smin_value); 14413 } 14414 break; 14415 case BPF_JGE: 14416 case BPF_JGT: 14417 case BPF_JSGE: 14418 case BPF_JSGT: 14419 /* just reuse LE/LT logic above */ 14420 opcode = flip_opcode(opcode); 14421 swap(reg1, reg2); 14422 goto again; 14423 default: 14424 return; 14425 } 14426 } 14427 14428 /* Adjusts the register min/max values in the case that the dst_reg and 14429 * src_reg are both SCALAR_VALUE registers (or we are simply doing a BPF_K 14430 * check, in which case we havea fake SCALAR_VALUE representing insn->imm). 14431 * Technically we can do similar adjustments for pointers to the same object, 14432 * but we don't support that right now. 14433 */ 14434 static int reg_set_min_max(struct bpf_verifier_env *env, 14435 struct bpf_reg_state *true_reg1, 14436 struct bpf_reg_state *true_reg2, 14437 struct bpf_reg_state *false_reg1, 14438 struct bpf_reg_state *false_reg2, 14439 u8 opcode, bool is_jmp32) 14440 { 14441 int err; 14442 14443 /* If either register is a pointer, we can't learn anything about its 14444 * variable offset from the compare (unless they were a pointer into 14445 * the same object, but we don't bother with that). 14446 */ 14447 if (false_reg1->type != SCALAR_VALUE || false_reg2->type != SCALAR_VALUE) 14448 return 0; 14449 14450 /* fallthrough (FALSE) branch */ 14451 regs_refine_cond_op(false_reg1, false_reg2, rev_opcode(opcode), is_jmp32); 14452 reg_bounds_sync(false_reg1); 14453 reg_bounds_sync(false_reg2); 14454 14455 /* jump (TRUE) branch */ 14456 regs_refine_cond_op(true_reg1, true_reg2, opcode, is_jmp32); 14457 reg_bounds_sync(true_reg1); 14458 reg_bounds_sync(true_reg2); 14459 14460 err = reg_bounds_sanity_check(env, true_reg1, "true_reg1"); 14461 err = err ?: reg_bounds_sanity_check(env, true_reg2, "true_reg2"); 14462 err = err ?: reg_bounds_sanity_check(env, false_reg1, "false_reg1"); 14463 err = err ?: reg_bounds_sanity_check(env, false_reg2, "false_reg2"); 14464 return err; 14465 } 14466 14467 static void mark_ptr_or_null_reg(struct bpf_func_state *state, 14468 struct bpf_reg_state *reg, u32 id, 14469 bool is_null) 14470 { 14471 if (type_may_be_null(reg->type) && reg->id == id && 14472 (is_rcu_reg(reg) || !WARN_ON_ONCE(!reg->id))) { 14473 /* Old offset (both fixed and variable parts) should have been 14474 * known-zero, because we don't allow pointer arithmetic on 14475 * pointers that might be NULL. If we see this happening, don't 14476 * convert the register. 14477 * 14478 * But in some cases, some helpers that return local kptrs 14479 * advance offset for the returned pointer. In those cases, it 14480 * is fine to expect to see reg->off. 14481 */ 14482 if (WARN_ON_ONCE(reg->smin_value || reg->smax_value || !tnum_equals_const(reg->var_off, 0))) 14483 return; 14484 if (!(type_is_ptr_alloc_obj(reg->type) || type_is_non_owning_ref(reg->type)) && 14485 WARN_ON_ONCE(reg->off)) 14486 return; 14487 14488 if (is_null) { 14489 reg->type = SCALAR_VALUE; 14490 /* We don't need id and ref_obj_id from this point 14491 * onwards anymore, thus we should better reset it, 14492 * so that state pruning has chances to take effect. 14493 */ 14494 reg->id = 0; 14495 reg->ref_obj_id = 0; 14496 14497 return; 14498 } 14499 14500 mark_ptr_not_null_reg(reg); 14501 14502 if (!reg_may_point_to_spin_lock(reg)) { 14503 /* For not-NULL ptr, reg->ref_obj_id will be reset 14504 * in release_reference(). 14505 * 14506 * reg->id is still used by spin_lock ptr. Other 14507 * than spin_lock ptr type, reg->id can be reset. 14508 */ 14509 reg->id = 0; 14510 } 14511 } 14512 } 14513 14514 /* The logic is similar to find_good_pkt_pointers(), both could eventually 14515 * be folded together at some point. 14516 */ 14517 static void mark_ptr_or_null_regs(struct bpf_verifier_state *vstate, u32 regno, 14518 bool is_null) 14519 { 14520 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 14521 struct bpf_reg_state *regs = state->regs, *reg; 14522 u32 ref_obj_id = regs[regno].ref_obj_id; 14523 u32 id = regs[regno].id; 14524 14525 if (ref_obj_id && ref_obj_id == id && is_null) 14526 /* regs[regno] is in the " == NULL" branch. 14527 * No one could have freed the reference state before 14528 * doing the NULL check. 14529 */ 14530 WARN_ON_ONCE(release_reference_state(state, id)); 14531 14532 bpf_for_each_reg_in_vstate(vstate, state, reg, ({ 14533 mark_ptr_or_null_reg(state, reg, id, is_null); 14534 })); 14535 } 14536 14537 static bool try_match_pkt_pointers(const struct bpf_insn *insn, 14538 struct bpf_reg_state *dst_reg, 14539 struct bpf_reg_state *src_reg, 14540 struct bpf_verifier_state *this_branch, 14541 struct bpf_verifier_state *other_branch) 14542 { 14543 if (BPF_SRC(insn->code) != BPF_X) 14544 return false; 14545 14546 /* Pointers are always 64-bit. */ 14547 if (BPF_CLASS(insn->code) == BPF_JMP32) 14548 return false; 14549 14550 switch (BPF_OP(insn->code)) { 14551 case BPF_JGT: 14552 if ((dst_reg->type == PTR_TO_PACKET && 14553 src_reg->type == PTR_TO_PACKET_END) || 14554 (dst_reg->type == PTR_TO_PACKET_META && 14555 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) { 14556 /* pkt_data' > pkt_end, pkt_meta' > pkt_data */ 14557 find_good_pkt_pointers(this_branch, dst_reg, 14558 dst_reg->type, false); 14559 mark_pkt_end(other_branch, insn->dst_reg, true); 14560 } else if ((dst_reg->type == PTR_TO_PACKET_END && 14561 src_reg->type == PTR_TO_PACKET) || 14562 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) && 14563 src_reg->type == PTR_TO_PACKET_META)) { 14564 /* pkt_end > pkt_data', pkt_data > pkt_meta' */ 14565 find_good_pkt_pointers(other_branch, src_reg, 14566 src_reg->type, true); 14567 mark_pkt_end(this_branch, insn->src_reg, false); 14568 } else { 14569 return false; 14570 } 14571 break; 14572 case BPF_JLT: 14573 if ((dst_reg->type == PTR_TO_PACKET && 14574 src_reg->type == PTR_TO_PACKET_END) || 14575 (dst_reg->type == PTR_TO_PACKET_META && 14576 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) { 14577 /* pkt_data' < pkt_end, pkt_meta' < pkt_data */ 14578 find_good_pkt_pointers(other_branch, dst_reg, 14579 dst_reg->type, true); 14580 mark_pkt_end(this_branch, insn->dst_reg, false); 14581 } else if ((dst_reg->type == PTR_TO_PACKET_END && 14582 src_reg->type == PTR_TO_PACKET) || 14583 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) && 14584 src_reg->type == PTR_TO_PACKET_META)) { 14585 /* pkt_end < pkt_data', pkt_data > pkt_meta' */ 14586 find_good_pkt_pointers(this_branch, src_reg, 14587 src_reg->type, false); 14588 mark_pkt_end(other_branch, insn->src_reg, true); 14589 } else { 14590 return false; 14591 } 14592 break; 14593 case BPF_JGE: 14594 if ((dst_reg->type == PTR_TO_PACKET && 14595 src_reg->type == PTR_TO_PACKET_END) || 14596 (dst_reg->type == PTR_TO_PACKET_META && 14597 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) { 14598 /* pkt_data' >= pkt_end, pkt_meta' >= pkt_data */ 14599 find_good_pkt_pointers(this_branch, dst_reg, 14600 dst_reg->type, true); 14601 mark_pkt_end(other_branch, insn->dst_reg, false); 14602 } else if ((dst_reg->type == PTR_TO_PACKET_END && 14603 src_reg->type == PTR_TO_PACKET) || 14604 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) && 14605 src_reg->type == PTR_TO_PACKET_META)) { 14606 /* pkt_end >= pkt_data', pkt_data >= pkt_meta' */ 14607 find_good_pkt_pointers(other_branch, src_reg, 14608 src_reg->type, false); 14609 mark_pkt_end(this_branch, insn->src_reg, true); 14610 } else { 14611 return false; 14612 } 14613 break; 14614 case BPF_JLE: 14615 if ((dst_reg->type == PTR_TO_PACKET && 14616 src_reg->type == PTR_TO_PACKET_END) || 14617 (dst_reg->type == PTR_TO_PACKET_META && 14618 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) { 14619 /* pkt_data' <= pkt_end, pkt_meta' <= pkt_data */ 14620 find_good_pkt_pointers(other_branch, dst_reg, 14621 dst_reg->type, false); 14622 mark_pkt_end(this_branch, insn->dst_reg, true); 14623 } else if ((dst_reg->type == PTR_TO_PACKET_END && 14624 src_reg->type == PTR_TO_PACKET) || 14625 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) && 14626 src_reg->type == PTR_TO_PACKET_META)) { 14627 /* pkt_end <= pkt_data', pkt_data <= pkt_meta' */ 14628 find_good_pkt_pointers(this_branch, src_reg, 14629 src_reg->type, true); 14630 mark_pkt_end(other_branch, insn->src_reg, false); 14631 } else { 14632 return false; 14633 } 14634 break; 14635 default: 14636 return false; 14637 } 14638 14639 return true; 14640 } 14641 14642 static void find_equal_scalars(struct bpf_verifier_state *vstate, 14643 struct bpf_reg_state *known_reg) 14644 { 14645 struct bpf_func_state *state; 14646 struct bpf_reg_state *reg; 14647 14648 bpf_for_each_reg_in_vstate(vstate, state, reg, ({ 14649 if (reg->type == SCALAR_VALUE && reg->id == known_reg->id) 14650 copy_register_state(reg, known_reg); 14651 })); 14652 } 14653 14654 static int check_cond_jmp_op(struct bpf_verifier_env *env, 14655 struct bpf_insn *insn, int *insn_idx) 14656 { 14657 struct bpf_verifier_state *this_branch = env->cur_state; 14658 struct bpf_verifier_state *other_branch; 14659 struct bpf_reg_state *regs = this_branch->frame[this_branch->curframe]->regs; 14660 struct bpf_reg_state *dst_reg, *other_branch_regs, *src_reg = NULL; 14661 struct bpf_reg_state *eq_branch_regs; 14662 struct bpf_reg_state fake_reg = {}; 14663 u8 opcode = BPF_OP(insn->code); 14664 bool is_jmp32; 14665 int pred = -1; 14666 int err; 14667 14668 /* Only conditional jumps are expected to reach here. */ 14669 if (opcode == BPF_JA || opcode > BPF_JSLE) { 14670 verbose(env, "invalid BPF_JMP/JMP32 opcode %x\n", opcode); 14671 return -EINVAL; 14672 } 14673 14674 /* check src2 operand */ 14675 err = check_reg_arg(env, insn->dst_reg, SRC_OP); 14676 if (err) 14677 return err; 14678 14679 dst_reg = ®s[insn->dst_reg]; 14680 if (BPF_SRC(insn->code) == BPF_X) { 14681 if (insn->imm != 0) { 14682 verbose(env, "BPF_JMP/JMP32 uses reserved fields\n"); 14683 return -EINVAL; 14684 } 14685 14686 /* check src1 operand */ 14687 err = check_reg_arg(env, insn->src_reg, SRC_OP); 14688 if (err) 14689 return err; 14690 14691 src_reg = ®s[insn->src_reg]; 14692 if (!(reg_is_pkt_pointer_any(dst_reg) && reg_is_pkt_pointer_any(src_reg)) && 14693 is_pointer_value(env, insn->src_reg)) { 14694 verbose(env, "R%d pointer comparison prohibited\n", 14695 insn->src_reg); 14696 return -EACCES; 14697 } 14698 } else { 14699 if (insn->src_reg != BPF_REG_0) { 14700 verbose(env, "BPF_JMP/JMP32 uses reserved fields\n"); 14701 return -EINVAL; 14702 } 14703 src_reg = &fake_reg; 14704 src_reg->type = SCALAR_VALUE; 14705 __mark_reg_known(src_reg, insn->imm); 14706 } 14707 14708 is_jmp32 = BPF_CLASS(insn->code) == BPF_JMP32; 14709 pred = is_branch_taken(dst_reg, src_reg, opcode, is_jmp32); 14710 if (pred >= 0) { 14711 /* If we get here with a dst_reg pointer type it is because 14712 * above is_branch_taken() special cased the 0 comparison. 14713 */ 14714 if (!__is_pointer_value(false, dst_reg)) 14715 err = mark_chain_precision(env, insn->dst_reg); 14716 if (BPF_SRC(insn->code) == BPF_X && !err && 14717 !__is_pointer_value(false, src_reg)) 14718 err = mark_chain_precision(env, insn->src_reg); 14719 if (err) 14720 return err; 14721 } 14722 14723 if (pred == 1) { 14724 /* Only follow the goto, ignore fall-through. If needed, push 14725 * the fall-through branch for simulation under speculative 14726 * execution. 14727 */ 14728 if (!env->bypass_spec_v1 && 14729 !sanitize_speculative_path(env, insn, *insn_idx + 1, 14730 *insn_idx)) 14731 return -EFAULT; 14732 if (env->log.level & BPF_LOG_LEVEL) 14733 print_insn_state(env, this_branch->frame[this_branch->curframe]); 14734 *insn_idx += insn->off; 14735 return 0; 14736 } else if (pred == 0) { 14737 /* Only follow the fall-through branch, since that's where the 14738 * program will go. If needed, push the goto branch for 14739 * simulation under speculative execution. 14740 */ 14741 if (!env->bypass_spec_v1 && 14742 !sanitize_speculative_path(env, insn, 14743 *insn_idx + insn->off + 1, 14744 *insn_idx)) 14745 return -EFAULT; 14746 if (env->log.level & BPF_LOG_LEVEL) 14747 print_insn_state(env, this_branch->frame[this_branch->curframe]); 14748 return 0; 14749 } 14750 14751 other_branch = push_stack(env, *insn_idx + insn->off + 1, *insn_idx, 14752 false); 14753 if (!other_branch) 14754 return -EFAULT; 14755 other_branch_regs = other_branch->frame[other_branch->curframe]->regs; 14756 14757 if (BPF_SRC(insn->code) == BPF_X) { 14758 err = reg_set_min_max(env, 14759 &other_branch_regs[insn->dst_reg], 14760 &other_branch_regs[insn->src_reg], 14761 dst_reg, src_reg, opcode, is_jmp32); 14762 } else /* BPF_SRC(insn->code) == BPF_K */ { 14763 err = reg_set_min_max(env, 14764 &other_branch_regs[insn->dst_reg], 14765 src_reg /* fake one */, 14766 dst_reg, src_reg /* same fake one */, 14767 opcode, is_jmp32); 14768 } 14769 if (err) 14770 return err; 14771 14772 if (BPF_SRC(insn->code) == BPF_X && 14773 src_reg->type == SCALAR_VALUE && src_reg->id && 14774 !WARN_ON_ONCE(src_reg->id != other_branch_regs[insn->src_reg].id)) { 14775 find_equal_scalars(this_branch, src_reg); 14776 find_equal_scalars(other_branch, &other_branch_regs[insn->src_reg]); 14777 } 14778 if (dst_reg->type == SCALAR_VALUE && dst_reg->id && 14779 !WARN_ON_ONCE(dst_reg->id != other_branch_regs[insn->dst_reg].id)) { 14780 find_equal_scalars(this_branch, dst_reg); 14781 find_equal_scalars(other_branch, &other_branch_regs[insn->dst_reg]); 14782 } 14783 14784 /* if one pointer register is compared to another pointer 14785 * register check if PTR_MAYBE_NULL could be lifted. 14786 * E.g. register A - maybe null 14787 * register B - not null 14788 * for JNE A, B, ... - A is not null in the false branch; 14789 * for JEQ A, B, ... - A is not null in the true branch. 14790 * 14791 * Since PTR_TO_BTF_ID points to a kernel struct that does 14792 * not need to be null checked by the BPF program, i.e., 14793 * could be null even without PTR_MAYBE_NULL marking, so 14794 * only propagate nullness when neither reg is that type. 14795 */ 14796 if (!is_jmp32 && BPF_SRC(insn->code) == BPF_X && 14797 __is_pointer_value(false, src_reg) && __is_pointer_value(false, dst_reg) && 14798 type_may_be_null(src_reg->type) != type_may_be_null(dst_reg->type) && 14799 base_type(src_reg->type) != PTR_TO_BTF_ID && 14800 base_type(dst_reg->type) != PTR_TO_BTF_ID) { 14801 eq_branch_regs = NULL; 14802 switch (opcode) { 14803 case BPF_JEQ: 14804 eq_branch_regs = other_branch_regs; 14805 break; 14806 case BPF_JNE: 14807 eq_branch_regs = regs; 14808 break; 14809 default: 14810 /* do nothing */ 14811 break; 14812 } 14813 if (eq_branch_regs) { 14814 if (type_may_be_null(src_reg->type)) 14815 mark_ptr_not_null_reg(&eq_branch_regs[insn->src_reg]); 14816 else 14817 mark_ptr_not_null_reg(&eq_branch_regs[insn->dst_reg]); 14818 } 14819 } 14820 14821 /* detect if R == 0 where R is returned from bpf_map_lookup_elem(). 14822 * NOTE: these optimizations below are related with pointer comparison 14823 * which will never be JMP32. 14824 */ 14825 if (!is_jmp32 && BPF_SRC(insn->code) == BPF_K && 14826 insn->imm == 0 && (opcode == BPF_JEQ || opcode == BPF_JNE) && 14827 type_may_be_null(dst_reg->type)) { 14828 /* Mark all identical registers in each branch as either 14829 * safe or unknown depending R == 0 or R != 0 conditional. 14830 */ 14831 mark_ptr_or_null_regs(this_branch, insn->dst_reg, 14832 opcode == BPF_JNE); 14833 mark_ptr_or_null_regs(other_branch, insn->dst_reg, 14834 opcode == BPF_JEQ); 14835 } else if (!try_match_pkt_pointers(insn, dst_reg, ®s[insn->src_reg], 14836 this_branch, other_branch) && 14837 is_pointer_value(env, insn->dst_reg)) { 14838 verbose(env, "R%d pointer comparison prohibited\n", 14839 insn->dst_reg); 14840 return -EACCES; 14841 } 14842 if (env->log.level & BPF_LOG_LEVEL) 14843 print_insn_state(env, this_branch->frame[this_branch->curframe]); 14844 return 0; 14845 } 14846 14847 /* verify BPF_LD_IMM64 instruction */ 14848 static int check_ld_imm(struct bpf_verifier_env *env, struct bpf_insn *insn) 14849 { 14850 struct bpf_insn_aux_data *aux = cur_aux(env); 14851 struct bpf_reg_state *regs = cur_regs(env); 14852 struct bpf_reg_state *dst_reg; 14853 struct bpf_map *map; 14854 int err; 14855 14856 if (BPF_SIZE(insn->code) != BPF_DW) { 14857 verbose(env, "invalid BPF_LD_IMM insn\n"); 14858 return -EINVAL; 14859 } 14860 if (insn->off != 0) { 14861 verbose(env, "BPF_LD_IMM64 uses reserved fields\n"); 14862 return -EINVAL; 14863 } 14864 14865 err = check_reg_arg(env, insn->dst_reg, DST_OP); 14866 if (err) 14867 return err; 14868 14869 dst_reg = ®s[insn->dst_reg]; 14870 if (insn->src_reg == 0) { 14871 u64 imm = ((u64)(insn + 1)->imm << 32) | (u32)insn->imm; 14872 14873 dst_reg->type = SCALAR_VALUE; 14874 __mark_reg_known(®s[insn->dst_reg], imm); 14875 return 0; 14876 } 14877 14878 /* All special src_reg cases are listed below. From this point onwards 14879 * we either succeed and assign a corresponding dst_reg->type after 14880 * zeroing the offset, or fail and reject the program. 14881 */ 14882 mark_reg_known_zero(env, regs, insn->dst_reg); 14883 14884 if (insn->src_reg == BPF_PSEUDO_BTF_ID) { 14885 dst_reg->type = aux->btf_var.reg_type; 14886 switch (base_type(dst_reg->type)) { 14887 case PTR_TO_MEM: 14888 dst_reg->mem_size = aux->btf_var.mem_size; 14889 break; 14890 case PTR_TO_BTF_ID: 14891 dst_reg->btf = aux->btf_var.btf; 14892 dst_reg->btf_id = aux->btf_var.btf_id; 14893 break; 14894 default: 14895 verbose(env, "bpf verifier is misconfigured\n"); 14896 return -EFAULT; 14897 } 14898 return 0; 14899 } 14900 14901 if (insn->src_reg == BPF_PSEUDO_FUNC) { 14902 struct bpf_prog_aux *aux = env->prog->aux; 14903 u32 subprogno = find_subprog(env, 14904 env->insn_idx + insn->imm + 1); 14905 14906 if (!aux->func_info) { 14907 verbose(env, "missing btf func_info\n"); 14908 return -EINVAL; 14909 } 14910 if (aux->func_info_aux[subprogno].linkage != BTF_FUNC_STATIC) { 14911 verbose(env, "callback function not static\n"); 14912 return -EINVAL; 14913 } 14914 14915 dst_reg->type = PTR_TO_FUNC; 14916 dst_reg->subprogno = subprogno; 14917 return 0; 14918 } 14919 14920 map = env->used_maps[aux->map_index]; 14921 dst_reg->map_ptr = map; 14922 14923 if (insn->src_reg == BPF_PSEUDO_MAP_VALUE || 14924 insn->src_reg == BPF_PSEUDO_MAP_IDX_VALUE) { 14925 dst_reg->type = PTR_TO_MAP_VALUE; 14926 dst_reg->off = aux->map_off; 14927 WARN_ON_ONCE(map->max_entries != 1); 14928 /* We want reg->id to be same (0) as map_value is not distinct */ 14929 } else if (insn->src_reg == BPF_PSEUDO_MAP_FD || 14930 insn->src_reg == BPF_PSEUDO_MAP_IDX) { 14931 dst_reg->type = CONST_PTR_TO_MAP; 14932 } else { 14933 verbose(env, "bpf verifier is misconfigured\n"); 14934 return -EINVAL; 14935 } 14936 14937 return 0; 14938 } 14939 14940 static bool may_access_skb(enum bpf_prog_type type) 14941 { 14942 switch (type) { 14943 case BPF_PROG_TYPE_SOCKET_FILTER: 14944 case BPF_PROG_TYPE_SCHED_CLS: 14945 case BPF_PROG_TYPE_SCHED_ACT: 14946 return true; 14947 default: 14948 return false; 14949 } 14950 } 14951 14952 /* verify safety of LD_ABS|LD_IND instructions: 14953 * - they can only appear in the programs where ctx == skb 14954 * - since they are wrappers of function calls, they scratch R1-R5 registers, 14955 * preserve R6-R9, and store return value into R0 14956 * 14957 * Implicit input: 14958 * ctx == skb == R6 == CTX 14959 * 14960 * Explicit input: 14961 * SRC == any register 14962 * IMM == 32-bit immediate 14963 * 14964 * Output: 14965 * R0 - 8/16/32-bit skb data converted to cpu endianness 14966 */ 14967 static int check_ld_abs(struct bpf_verifier_env *env, struct bpf_insn *insn) 14968 { 14969 struct bpf_reg_state *regs = cur_regs(env); 14970 static const int ctx_reg = BPF_REG_6; 14971 u8 mode = BPF_MODE(insn->code); 14972 int i, err; 14973 14974 if (!may_access_skb(resolve_prog_type(env->prog))) { 14975 verbose(env, "BPF_LD_[ABS|IND] instructions not allowed for this program type\n"); 14976 return -EINVAL; 14977 } 14978 14979 if (!env->ops->gen_ld_abs) { 14980 verbose(env, "bpf verifier is misconfigured\n"); 14981 return -EINVAL; 14982 } 14983 14984 if (insn->dst_reg != BPF_REG_0 || insn->off != 0 || 14985 BPF_SIZE(insn->code) == BPF_DW || 14986 (mode == BPF_ABS && insn->src_reg != BPF_REG_0)) { 14987 verbose(env, "BPF_LD_[ABS|IND] uses reserved fields\n"); 14988 return -EINVAL; 14989 } 14990 14991 /* check whether implicit source operand (register R6) is readable */ 14992 err = check_reg_arg(env, ctx_reg, SRC_OP); 14993 if (err) 14994 return err; 14995 14996 /* Disallow usage of BPF_LD_[ABS|IND] with reference tracking, as 14997 * gen_ld_abs() may terminate the program at runtime, leading to 14998 * reference leak. 14999 */ 15000 err = check_reference_leak(env, false); 15001 if (err) { 15002 verbose(env, "BPF_LD_[ABS|IND] cannot be mixed with socket references\n"); 15003 return err; 15004 } 15005 15006 if (env->cur_state->active_lock.ptr) { 15007 verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_spin_lock-ed region\n"); 15008 return -EINVAL; 15009 } 15010 15011 if (env->cur_state->active_rcu_lock) { 15012 verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_rcu_read_lock-ed region\n"); 15013 return -EINVAL; 15014 } 15015 15016 if (regs[ctx_reg].type != PTR_TO_CTX) { 15017 verbose(env, 15018 "at the time of BPF_LD_ABS|IND R6 != pointer to skb\n"); 15019 return -EINVAL; 15020 } 15021 15022 if (mode == BPF_IND) { 15023 /* check explicit source operand */ 15024 err = check_reg_arg(env, insn->src_reg, SRC_OP); 15025 if (err) 15026 return err; 15027 } 15028 15029 err = check_ptr_off_reg(env, ®s[ctx_reg], ctx_reg); 15030 if (err < 0) 15031 return err; 15032 15033 /* reset caller saved regs to unreadable */ 15034 for (i = 0; i < CALLER_SAVED_REGS; i++) { 15035 mark_reg_not_init(env, regs, caller_saved[i]); 15036 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK); 15037 } 15038 15039 /* mark destination R0 register as readable, since it contains 15040 * the value fetched from the packet. 15041 * Already marked as written above. 15042 */ 15043 mark_reg_unknown(env, regs, BPF_REG_0); 15044 /* ld_abs load up to 32-bit skb data. */ 15045 regs[BPF_REG_0].subreg_def = env->insn_idx + 1; 15046 return 0; 15047 } 15048 15049 static int check_return_code(struct bpf_verifier_env *env, int regno, const char *reg_name) 15050 { 15051 const char *exit_ctx = "At program exit"; 15052 struct tnum enforce_attach_type_range = tnum_unknown; 15053 const struct bpf_prog *prog = env->prog; 15054 struct bpf_reg_state *reg; 15055 struct bpf_retval_range range = retval_range(0, 1); 15056 enum bpf_prog_type prog_type = resolve_prog_type(env->prog); 15057 int err; 15058 struct bpf_func_state *frame = env->cur_state->frame[0]; 15059 const bool is_subprog = frame->subprogno; 15060 15061 /* LSM and struct_ops func-ptr's return type could be "void" */ 15062 if (!is_subprog || frame->in_exception_callback_fn) { 15063 switch (prog_type) { 15064 case BPF_PROG_TYPE_LSM: 15065 if (prog->expected_attach_type == BPF_LSM_CGROUP) 15066 /* See below, can be 0 or 0-1 depending on hook. */ 15067 break; 15068 fallthrough; 15069 case BPF_PROG_TYPE_STRUCT_OPS: 15070 if (!prog->aux->attach_func_proto->type) 15071 return 0; 15072 break; 15073 default: 15074 break; 15075 } 15076 } 15077 15078 /* eBPF calling convention is such that R0 is used 15079 * to return the value from eBPF program. 15080 * Make sure that it's readable at this time 15081 * of bpf_exit, which means that program wrote 15082 * something into it earlier 15083 */ 15084 err = check_reg_arg(env, regno, SRC_OP); 15085 if (err) 15086 return err; 15087 15088 if (is_pointer_value(env, regno)) { 15089 verbose(env, "R%d leaks addr as return value\n", regno); 15090 return -EACCES; 15091 } 15092 15093 reg = cur_regs(env) + regno; 15094 15095 if (frame->in_async_callback_fn) { 15096 /* enforce return zero from async callbacks like timer */ 15097 exit_ctx = "At async callback return"; 15098 range = retval_range(0, 0); 15099 goto enforce_retval; 15100 } 15101 15102 if (is_subprog && !frame->in_exception_callback_fn) { 15103 if (reg->type != SCALAR_VALUE) { 15104 verbose(env, "At subprogram exit the register R%d is not a scalar value (%s)\n", 15105 regno, reg_type_str(env, reg->type)); 15106 return -EINVAL; 15107 } 15108 return 0; 15109 } 15110 15111 switch (prog_type) { 15112 case BPF_PROG_TYPE_CGROUP_SOCK_ADDR: 15113 if (env->prog->expected_attach_type == BPF_CGROUP_UDP4_RECVMSG || 15114 env->prog->expected_attach_type == BPF_CGROUP_UDP6_RECVMSG || 15115 env->prog->expected_attach_type == BPF_CGROUP_UNIX_RECVMSG || 15116 env->prog->expected_attach_type == BPF_CGROUP_INET4_GETPEERNAME || 15117 env->prog->expected_attach_type == BPF_CGROUP_INET6_GETPEERNAME || 15118 env->prog->expected_attach_type == BPF_CGROUP_UNIX_GETPEERNAME || 15119 env->prog->expected_attach_type == BPF_CGROUP_INET4_GETSOCKNAME || 15120 env->prog->expected_attach_type == BPF_CGROUP_INET6_GETSOCKNAME || 15121 env->prog->expected_attach_type == BPF_CGROUP_UNIX_GETSOCKNAME) 15122 range = retval_range(1, 1); 15123 if (env->prog->expected_attach_type == BPF_CGROUP_INET4_BIND || 15124 env->prog->expected_attach_type == BPF_CGROUP_INET6_BIND) 15125 range = retval_range(0, 3); 15126 break; 15127 case BPF_PROG_TYPE_CGROUP_SKB: 15128 if (env->prog->expected_attach_type == BPF_CGROUP_INET_EGRESS) { 15129 range = retval_range(0, 3); 15130 enforce_attach_type_range = tnum_range(2, 3); 15131 } 15132 break; 15133 case BPF_PROG_TYPE_CGROUP_SOCK: 15134 case BPF_PROG_TYPE_SOCK_OPS: 15135 case BPF_PROG_TYPE_CGROUP_DEVICE: 15136 case BPF_PROG_TYPE_CGROUP_SYSCTL: 15137 case BPF_PROG_TYPE_CGROUP_SOCKOPT: 15138 break; 15139 case BPF_PROG_TYPE_RAW_TRACEPOINT: 15140 if (!env->prog->aux->attach_btf_id) 15141 return 0; 15142 range = retval_range(0, 0); 15143 break; 15144 case BPF_PROG_TYPE_TRACING: 15145 switch (env->prog->expected_attach_type) { 15146 case BPF_TRACE_FENTRY: 15147 case BPF_TRACE_FEXIT: 15148 range = retval_range(0, 0); 15149 break; 15150 case BPF_TRACE_RAW_TP: 15151 case BPF_MODIFY_RETURN: 15152 return 0; 15153 case BPF_TRACE_ITER: 15154 break; 15155 default: 15156 return -ENOTSUPP; 15157 } 15158 break; 15159 case BPF_PROG_TYPE_SK_LOOKUP: 15160 range = retval_range(SK_DROP, SK_PASS); 15161 break; 15162 15163 case BPF_PROG_TYPE_LSM: 15164 if (env->prog->expected_attach_type != BPF_LSM_CGROUP) { 15165 /* Regular BPF_PROG_TYPE_LSM programs can return 15166 * any value. 15167 */ 15168 return 0; 15169 } 15170 if (!env->prog->aux->attach_func_proto->type) { 15171 /* Make sure programs that attach to void 15172 * hooks don't try to modify return value. 15173 */ 15174 range = retval_range(1, 1); 15175 } 15176 break; 15177 15178 case BPF_PROG_TYPE_NETFILTER: 15179 range = retval_range(NF_DROP, NF_ACCEPT); 15180 break; 15181 case BPF_PROG_TYPE_EXT: 15182 /* freplace program can return anything as its return value 15183 * depends on the to-be-replaced kernel func or bpf program. 15184 */ 15185 default: 15186 return 0; 15187 } 15188 15189 enforce_retval: 15190 if (reg->type != SCALAR_VALUE) { 15191 verbose(env, "%s the register R%d is not a known value (%s)\n", 15192 exit_ctx, regno, reg_type_str(env, reg->type)); 15193 return -EINVAL; 15194 } 15195 15196 err = mark_chain_precision(env, regno); 15197 if (err) 15198 return err; 15199 15200 if (!retval_range_within(range, reg)) { 15201 verbose_invalid_scalar(env, reg, range, exit_ctx, reg_name); 15202 if (!is_subprog && 15203 prog->expected_attach_type == BPF_LSM_CGROUP && 15204 prog_type == BPF_PROG_TYPE_LSM && 15205 !prog->aux->attach_func_proto->type) 15206 verbose(env, "Note, BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n"); 15207 return -EINVAL; 15208 } 15209 15210 if (!tnum_is_unknown(enforce_attach_type_range) && 15211 tnum_in(enforce_attach_type_range, reg->var_off)) 15212 env->prog->enforce_expected_attach_type = 1; 15213 return 0; 15214 } 15215 15216 /* non-recursive DFS pseudo code 15217 * 1 procedure DFS-iterative(G,v): 15218 * 2 label v as discovered 15219 * 3 let S be a stack 15220 * 4 S.push(v) 15221 * 5 while S is not empty 15222 * 6 t <- S.peek() 15223 * 7 if t is what we're looking for: 15224 * 8 return t 15225 * 9 for all edges e in G.adjacentEdges(t) do 15226 * 10 if edge e is already labelled 15227 * 11 continue with the next edge 15228 * 12 w <- G.adjacentVertex(t,e) 15229 * 13 if vertex w is not discovered and not explored 15230 * 14 label e as tree-edge 15231 * 15 label w as discovered 15232 * 16 S.push(w) 15233 * 17 continue at 5 15234 * 18 else if vertex w is discovered 15235 * 19 label e as back-edge 15236 * 20 else 15237 * 21 // vertex w is explored 15238 * 22 label e as forward- or cross-edge 15239 * 23 label t as explored 15240 * 24 S.pop() 15241 * 15242 * convention: 15243 * 0x10 - discovered 15244 * 0x11 - discovered and fall-through edge labelled 15245 * 0x12 - discovered and fall-through and branch edges labelled 15246 * 0x20 - explored 15247 */ 15248 15249 enum { 15250 DISCOVERED = 0x10, 15251 EXPLORED = 0x20, 15252 FALLTHROUGH = 1, 15253 BRANCH = 2, 15254 }; 15255 15256 static void mark_prune_point(struct bpf_verifier_env *env, int idx) 15257 { 15258 env->insn_aux_data[idx].prune_point = true; 15259 } 15260 15261 static bool is_prune_point(struct bpf_verifier_env *env, int insn_idx) 15262 { 15263 return env->insn_aux_data[insn_idx].prune_point; 15264 } 15265 15266 static void mark_force_checkpoint(struct bpf_verifier_env *env, int idx) 15267 { 15268 env->insn_aux_data[idx].force_checkpoint = true; 15269 } 15270 15271 static bool is_force_checkpoint(struct bpf_verifier_env *env, int insn_idx) 15272 { 15273 return env->insn_aux_data[insn_idx].force_checkpoint; 15274 } 15275 15276 static void mark_calls_callback(struct bpf_verifier_env *env, int idx) 15277 { 15278 env->insn_aux_data[idx].calls_callback = true; 15279 } 15280 15281 static bool calls_callback(struct bpf_verifier_env *env, int insn_idx) 15282 { 15283 return env->insn_aux_data[insn_idx].calls_callback; 15284 } 15285 15286 enum { 15287 DONE_EXPLORING = 0, 15288 KEEP_EXPLORING = 1, 15289 }; 15290 15291 /* t, w, e - match pseudo-code above: 15292 * t - index of current instruction 15293 * w - next instruction 15294 * e - edge 15295 */ 15296 static int push_insn(int t, int w, int e, struct bpf_verifier_env *env) 15297 { 15298 int *insn_stack = env->cfg.insn_stack; 15299 int *insn_state = env->cfg.insn_state; 15300 15301 if (e == FALLTHROUGH && insn_state[t] >= (DISCOVERED | FALLTHROUGH)) 15302 return DONE_EXPLORING; 15303 15304 if (e == BRANCH && insn_state[t] >= (DISCOVERED | BRANCH)) 15305 return DONE_EXPLORING; 15306 15307 if (w < 0 || w >= env->prog->len) { 15308 verbose_linfo(env, t, "%d: ", t); 15309 verbose(env, "jump out of range from insn %d to %d\n", t, w); 15310 return -EINVAL; 15311 } 15312 15313 if (e == BRANCH) { 15314 /* mark branch target for state pruning */ 15315 mark_prune_point(env, w); 15316 mark_jmp_point(env, w); 15317 } 15318 15319 if (insn_state[w] == 0) { 15320 /* tree-edge */ 15321 insn_state[t] = DISCOVERED | e; 15322 insn_state[w] = DISCOVERED; 15323 if (env->cfg.cur_stack >= env->prog->len) 15324 return -E2BIG; 15325 insn_stack[env->cfg.cur_stack++] = w; 15326 return KEEP_EXPLORING; 15327 } else if ((insn_state[w] & 0xF0) == DISCOVERED) { 15328 if (env->bpf_capable) 15329 return DONE_EXPLORING; 15330 verbose_linfo(env, t, "%d: ", t); 15331 verbose_linfo(env, w, "%d: ", w); 15332 verbose(env, "back-edge from insn %d to %d\n", t, w); 15333 return -EINVAL; 15334 } else if (insn_state[w] == EXPLORED) { 15335 /* forward- or cross-edge */ 15336 insn_state[t] = DISCOVERED | e; 15337 } else { 15338 verbose(env, "insn state internal bug\n"); 15339 return -EFAULT; 15340 } 15341 return DONE_EXPLORING; 15342 } 15343 15344 static int visit_func_call_insn(int t, struct bpf_insn *insns, 15345 struct bpf_verifier_env *env, 15346 bool visit_callee) 15347 { 15348 int ret, insn_sz; 15349 15350 insn_sz = bpf_is_ldimm64(&insns[t]) ? 2 : 1; 15351 ret = push_insn(t, t + insn_sz, FALLTHROUGH, env); 15352 if (ret) 15353 return ret; 15354 15355 mark_prune_point(env, t + insn_sz); 15356 /* when we exit from subprog, we need to record non-linear history */ 15357 mark_jmp_point(env, t + insn_sz); 15358 15359 if (visit_callee) { 15360 mark_prune_point(env, t); 15361 ret = push_insn(t, t + insns[t].imm + 1, BRANCH, env); 15362 } 15363 return ret; 15364 } 15365 15366 /* Visits the instruction at index t and returns one of the following: 15367 * < 0 - an error occurred 15368 * DONE_EXPLORING - the instruction was fully explored 15369 * KEEP_EXPLORING - there is still work to be done before it is fully explored 15370 */ 15371 static int visit_insn(int t, struct bpf_verifier_env *env) 15372 { 15373 struct bpf_insn *insns = env->prog->insnsi, *insn = &insns[t]; 15374 int ret, off, insn_sz; 15375 15376 if (bpf_pseudo_func(insn)) 15377 return visit_func_call_insn(t, insns, env, true); 15378 15379 /* All non-branch instructions have a single fall-through edge. */ 15380 if (BPF_CLASS(insn->code) != BPF_JMP && 15381 BPF_CLASS(insn->code) != BPF_JMP32) { 15382 insn_sz = bpf_is_ldimm64(insn) ? 2 : 1; 15383 return push_insn(t, t + insn_sz, FALLTHROUGH, env); 15384 } 15385 15386 switch (BPF_OP(insn->code)) { 15387 case BPF_EXIT: 15388 return DONE_EXPLORING; 15389 15390 case BPF_CALL: 15391 if (insn->src_reg == 0 && insn->imm == BPF_FUNC_timer_set_callback) 15392 /* Mark this call insn as a prune point to trigger 15393 * is_state_visited() check before call itself is 15394 * processed by __check_func_call(). Otherwise new 15395 * async state will be pushed for further exploration. 15396 */ 15397 mark_prune_point(env, t); 15398 /* For functions that invoke callbacks it is not known how many times 15399 * callback would be called. Verifier models callback calling functions 15400 * by repeatedly visiting callback bodies and returning to origin call 15401 * instruction. 15402 * In order to stop such iteration verifier needs to identify when a 15403 * state identical some state from a previous iteration is reached. 15404 * Check below forces creation of checkpoint before callback calling 15405 * instruction to allow search for such identical states. 15406 */ 15407 if (is_sync_callback_calling_insn(insn)) { 15408 mark_calls_callback(env, t); 15409 mark_force_checkpoint(env, t); 15410 mark_prune_point(env, t); 15411 mark_jmp_point(env, t); 15412 } 15413 if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) { 15414 struct bpf_kfunc_call_arg_meta meta; 15415 15416 ret = fetch_kfunc_meta(env, insn, &meta, NULL); 15417 if (ret == 0 && is_iter_next_kfunc(&meta)) { 15418 mark_prune_point(env, t); 15419 /* Checking and saving state checkpoints at iter_next() call 15420 * is crucial for fast convergence of open-coded iterator loop 15421 * logic, so we need to force it. If we don't do that, 15422 * is_state_visited() might skip saving a checkpoint, causing 15423 * unnecessarily long sequence of not checkpointed 15424 * instructions and jumps, leading to exhaustion of jump 15425 * history buffer, and potentially other undesired outcomes. 15426 * It is expected that with correct open-coded iterators 15427 * convergence will happen quickly, so we don't run a risk of 15428 * exhausting memory. 15429 */ 15430 mark_force_checkpoint(env, t); 15431 } 15432 } 15433 return visit_func_call_insn(t, insns, env, insn->src_reg == BPF_PSEUDO_CALL); 15434 15435 case BPF_JA: 15436 if (BPF_SRC(insn->code) != BPF_K) 15437 return -EINVAL; 15438 15439 if (BPF_CLASS(insn->code) == BPF_JMP) 15440 off = insn->off; 15441 else 15442 off = insn->imm; 15443 15444 /* unconditional jump with single edge */ 15445 ret = push_insn(t, t + off + 1, FALLTHROUGH, env); 15446 if (ret) 15447 return ret; 15448 15449 mark_prune_point(env, t + off + 1); 15450 mark_jmp_point(env, t + off + 1); 15451 15452 return ret; 15453 15454 default: 15455 /* conditional jump with two edges */ 15456 mark_prune_point(env, t); 15457 15458 ret = push_insn(t, t + 1, FALLTHROUGH, env); 15459 if (ret) 15460 return ret; 15461 15462 return push_insn(t, t + insn->off + 1, BRANCH, env); 15463 } 15464 } 15465 15466 /* non-recursive depth-first-search to detect loops in BPF program 15467 * loop == back-edge in directed graph 15468 */ 15469 static int check_cfg(struct bpf_verifier_env *env) 15470 { 15471 int insn_cnt = env->prog->len; 15472 int *insn_stack, *insn_state; 15473 int ex_insn_beg, i, ret = 0; 15474 bool ex_done = false; 15475 15476 insn_state = env->cfg.insn_state = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL); 15477 if (!insn_state) 15478 return -ENOMEM; 15479 15480 insn_stack = env->cfg.insn_stack = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL); 15481 if (!insn_stack) { 15482 kvfree(insn_state); 15483 return -ENOMEM; 15484 } 15485 15486 insn_state[0] = DISCOVERED; /* mark 1st insn as discovered */ 15487 insn_stack[0] = 0; /* 0 is the first instruction */ 15488 env->cfg.cur_stack = 1; 15489 15490 walk_cfg: 15491 while (env->cfg.cur_stack > 0) { 15492 int t = insn_stack[env->cfg.cur_stack - 1]; 15493 15494 ret = visit_insn(t, env); 15495 switch (ret) { 15496 case DONE_EXPLORING: 15497 insn_state[t] = EXPLORED; 15498 env->cfg.cur_stack--; 15499 break; 15500 case KEEP_EXPLORING: 15501 break; 15502 default: 15503 if (ret > 0) { 15504 verbose(env, "visit_insn internal bug\n"); 15505 ret = -EFAULT; 15506 } 15507 goto err_free; 15508 } 15509 } 15510 15511 if (env->cfg.cur_stack < 0) { 15512 verbose(env, "pop stack internal bug\n"); 15513 ret = -EFAULT; 15514 goto err_free; 15515 } 15516 15517 if (env->exception_callback_subprog && !ex_done) { 15518 ex_insn_beg = env->subprog_info[env->exception_callback_subprog].start; 15519 15520 insn_state[ex_insn_beg] = DISCOVERED; 15521 insn_stack[0] = ex_insn_beg; 15522 env->cfg.cur_stack = 1; 15523 ex_done = true; 15524 goto walk_cfg; 15525 } 15526 15527 for (i = 0; i < insn_cnt; i++) { 15528 struct bpf_insn *insn = &env->prog->insnsi[i]; 15529 15530 if (insn_state[i] != EXPLORED) { 15531 verbose(env, "unreachable insn %d\n", i); 15532 ret = -EINVAL; 15533 goto err_free; 15534 } 15535 if (bpf_is_ldimm64(insn)) { 15536 if (insn_state[i + 1] != 0) { 15537 verbose(env, "jump into the middle of ldimm64 insn %d\n", i); 15538 ret = -EINVAL; 15539 goto err_free; 15540 } 15541 i++; /* skip second half of ldimm64 */ 15542 } 15543 } 15544 ret = 0; /* cfg looks good */ 15545 15546 err_free: 15547 kvfree(insn_state); 15548 kvfree(insn_stack); 15549 env->cfg.insn_state = env->cfg.insn_stack = NULL; 15550 return ret; 15551 } 15552 15553 static int check_abnormal_return(struct bpf_verifier_env *env) 15554 { 15555 int i; 15556 15557 for (i = 1; i < env->subprog_cnt; i++) { 15558 if (env->subprog_info[i].has_ld_abs) { 15559 verbose(env, "LD_ABS is not allowed in subprogs without BTF\n"); 15560 return -EINVAL; 15561 } 15562 if (env->subprog_info[i].has_tail_call) { 15563 verbose(env, "tail_call is not allowed in subprogs without BTF\n"); 15564 return -EINVAL; 15565 } 15566 } 15567 return 0; 15568 } 15569 15570 /* The minimum supported BTF func info size */ 15571 #define MIN_BPF_FUNCINFO_SIZE 8 15572 #define MAX_FUNCINFO_REC_SIZE 252 15573 15574 static int check_btf_func_early(struct bpf_verifier_env *env, 15575 const union bpf_attr *attr, 15576 bpfptr_t uattr) 15577 { 15578 u32 krec_size = sizeof(struct bpf_func_info); 15579 const struct btf_type *type, *func_proto; 15580 u32 i, nfuncs, urec_size, min_size; 15581 struct bpf_func_info *krecord; 15582 struct bpf_prog *prog; 15583 const struct btf *btf; 15584 u32 prev_offset = 0; 15585 bpfptr_t urecord; 15586 int ret = -ENOMEM; 15587 15588 nfuncs = attr->func_info_cnt; 15589 if (!nfuncs) { 15590 if (check_abnormal_return(env)) 15591 return -EINVAL; 15592 return 0; 15593 } 15594 15595 urec_size = attr->func_info_rec_size; 15596 if (urec_size < MIN_BPF_FUNCINFO_SIZE || 15597 urec_size > MAX_FUNCINFO_REC_SIZE || 15598 urec_size % sizeof(u32)) { 15599 verbose(env, "invalid func info rec size %u\n", urec_size); 15600 return -EINVAL; 15601 } 15602 15603 prog = env->prog; 15604 btf = prog->aux->btf; 15605 15606 urecord = make_bpfptr(attr->func_info, uattr.is_kernel); 15607 min_size = min_t(u32, krec_size, urec_size); 15608 15609 krecord = kvcalloc(nfuncs, krec_size, GFP_KERNEL | __GFP_NOWARN); 15610 if (!krecord) 15611 return -ENOMEM; 15612 15613 for (i = 0; i < nfuncs; i++) { 15614 ret = bpf_check_uarg_tail_zero(urecord, krec_size, urec_size); 15615 if (ret) { 15616 if (ret == -E2BIG) { 15617 verbose(env, "nonzero tailing record in func info"); 15618 /* set the size kernel expects so loader can zero 15619 * out the rest of the record. 15620 */ 15621 if (copy_to_bpfptr_offset(uattr, 15622 offsetof(union bpf_attr, func_info_rec_size), 15623 &min_size, sizeof(min_size))) 15624 ret = -EFAULT; 15625 } 15626 goto err_free; 15627 } 15628 15629 if (copy_from_bpfptr(&krecord[i], urecord, min_size)) { 15630 ret = -EFAULT; 15631 goto err_free; 15632 } 15633 15634 /* check insn_off */ 15635 ret = -EINVAL; 15636 if (i == 0) { 15637 if (krecord[i].insn_off) { 15638 verbose(env, 15639 "nonzero insn_off %u for the first func info record", 15640 krecord[i].insn_off); 15641 goto err_free; 15642 } 15643 } else if (krecord[i].insn_off <= prev_offset) { 15644 verbose(env, 15645 "same or smaller insn offset (%u) than previous func info record (%u)", 15646 krecord[i].insn_off, prev_offset); 15647 goto err_free; 15648 } 15649 15650 /* check type_id */ 15651 type = btf_type_by_id(btf, krecord[i].type_id); 15652 if (!type || !btf_type_is_func(type)) { 15653 verbose(env, "invalid type id %d in func info", 15654 krecord[i].type_id); 15655 goto err_free; 15656 } 15657 15658 func_proto = btf_type_by_id(btf, type->type); 15659 if (unlikely(!func_proto || !btf_type_is_func_proto(func_proto))) 15660 /* btf_func_check() already verified it during BTF load */ 15661 goto err_free; 15662 15663 prev_offset = krecord[i].insn_off; 15664 bpfptr_add(&urecord, urec_size); 15665 } 15666 15667 prog->aux->func_info = krecord; 15668 prog->aux->func_info_cnt = nfuncs; 15669 return 0; 15670 15671 err_free: 15672 kvfree(krecord); 15673 return ret; 15674 } 15675 15676 static int check_btf_func(struct bpf_verifier_env *env, 15677 const union bpf_attr *attr, 15678 bpfptr_t uattr) 15679 { 15680 const struct btf_type *type, *func_proto, *ret_type; 15681 u32 i, nfuncs, urec_size; 15682 struct bpf_func_info *krecord; 15683 struct bpf_func_info_aux *info_aux = NULL; 15684 struct bpf_prog *prog; 15685 const struct btf *btf; 15686 bpfptr_t urecord; 15687 bool scalar_return; 15688 int ret = -ENOMEM; 15689 15690 nfuncs = attr->func_info_cnt; 15691 if (!nfuncs) { 15692 if (check_abnormal_return(env)) 15693 return -EINVAL; 15694 return 0; 15695 } 15696 if (nfuncs != env->subprog_cnt) { 15697 verbose(env, "number of funcs in func_info doesn't match number of subprogs\n"); 15698 return -EINVAL; 15699 } 15700 15701 urec_size = attr->func_info_rec_size; 15702 15703 prog = env->prog; 15704 btf = prog->aux->btf; 15705 15706 urecord = make_bpfptr(attr->func_info, uattr.is_kernel); 15707 15708 krecord = prog->aux->func_info; 15709 info_aux = kcalloc(nfuncs, sizeof(*info_aux), GFP_KERNEL | __GFP_NOWARN); 15710 if (!info_aux) 15711 return -ENOMEM; 15712 15713 for (i = 0; i < nfuncs; i++) { 15714 /* check insn_off */ 15715 ret = -EINVAL; 15716 15717 if (env->subprog_info[i].start != krecord[i].insn_off) { 15718 verbose(env, "func_info BTF section doesn't match subprog layout in BPF program\n"); 15719 goto err_free; 15720 } 15721 15722 /* Already checked type_id */ 15723 type = btf_type_by_id(btf, krecord[i].type_id); 15724 info_aux[i].linkage = BTF_INFO_VLEN(type->info); 15725 /* Already checked func_proto */ 15726 func_proto = btf_type_by_id(btf, type->type); 15727 15728 ret_type = btf_type_skip_modifiers(btf, func_proto->type, NULL); 15729 scalar_return = 15730 btf_type_is_small_int(ret_type) || btf_is_any_enum(ret_type); 15731 if (i && !scalar_return && env->subprog_info[i].has_ld_abs) { 15732 verbose(env, "LD_ABS is only allowed in functions that return 'int'.\n"); 15733 goto err_free; 15734 } 15735 if (i && !scalar_return && env->subprog_info[i].has_tail_call) { 15736 verbose(env, "tail_call is only allowed in functions that return 'int'.\n"); 15737 goto err_free; 15738 } 15739 15740 bpfptr_add(&urecord, urec_size); 15741 } 15742 15743 prog->aux->func_info_aux = info_aux; 15744 return 0; 15745 15746 err_free: 15747 kfree(info_aux); 15748 return ret; 15749 } 15750 15751 static void adjust_btf_func(struct bpf_verifier_env *env) 15752 { 15753 struct bpf_prog_aux *aux = env->prog->aux; 15754 int i; 15755 15756 if (!aux->func_info) 15757 return; 15758 15759 /* func_info is not available for hidden subprogs */ 15760 for (i = 0; i < env->subprog_cnt - env->hidden_subprog_cnt; i++) 15761 aux->func_info[i].insn_off = env->subprog_info[i].start; 15762 } 15763 15764 #define MIN_BPF_LINEINFO_SIZE offsetofend(struct bpf_line_info, line_col) 15765 #define MAX_LINEINFO_REC_SIZE MAX_FUNCINFO_REC_SIZE 15766 15767 static int check_btf_line(struct bpf_verifier_env *env, 15768 const union bpf_attr *attr, 15769 bpfptr_t uattr) 15770 { 15771 u32 i, s, nr_linfo, ncopy, expected_size, rec_size, prev_offset = 0; 15772 struct bpf_subprog_info *sub; 15773 struct bpf_line_info *linfo; 15774 struct bpf_prog *prog; 15775 const struct btf *btf; 15776 bpfptr_t ulinfo; 15777 int err; 15778 15779 nr_linfo = attr->line_info_cnt; 15780 if (!nr_linfo) 15781 return 0; 15782 if (nr_linfo > INT_MAX / sizeof(struct bpf_line_info)) 15783 return -EINVAL; 15784 15785 rec_size = attr->line_info_rec_size; 15786 if (rec_size < MIN_BPF_LINEINFO_SIZE || 15787 rec_size > MAX_LINEINFO_REC_SIZE || 15788 rec_size & (sizeof(u32) - 1)) 15789 return -EINVAL; 15790 15791 /* Need to zero it in case the userspace may 15792 * pass in a smaller bpf_line_info object. 15793 */ 15794 linfo = kvcalloc(nr_linfo, sizeof(struct bpf_line_info), 15795 GFP_KERNEL | __GFP_NOWARN); 15796 if (!linfo) 15797 return -ENOMEM; 15798 15799 prog = env->prog; 15800 btf = prog->aux->btf; 15801 15802 s = 0; 15803 sub = env->subprog_info; 15804 ulinfo = make_bpfptr(attr->line_info, uattr.is_kernel); 15805 expected_size = sizeof(struct bpf_line_info); 15806 ncopy = min_t(u32, expected_size, rec_size); 15807 for (i = 0; i < nr_linfo; i++) { 15808 err = bpf_check_uarg_tail_zero(ulinfo, expected_size, rec_size); 15809 if (err) { 15810 if (err == -E2BIG) { 15811 verbose(env, "nonzero tailing record in line_info"); 15812 if (copy_to_bpfptr_offset(uattr, 15813 offsetof(union bpf_attr, line_info_rec_size), 15814 &expected_size, sizeof(expected_size))) 15815 err = -EFAULT; 15816 } 15817 goto err_free; 15818 } 15819 15820 if (copy_from_bpfptr(&linfo[i], ulinfo, ncopy)) { 15821 err = -EFAULT; 15822 goto err_free; 15823 } 15824 15825 /* 15826 * Check insn_off to ensure 15827 * 1) strictly increasing AND 15828 * 2) bounded by prog->len 15829 * 15830 * The linfo[0].insn_off == 0 check logically falls into 15831 * the later "missing bpf_line_info for func..." case 15832 * because the first linfo[0].insn_off must be the 15833 * first sub also and the first sub must have 15834 * subprog_info[0].start == 0. 15835 */ 15836 if ((i && linfo[i].insn_off <= prev_offset) || 15837 linfo[i].insn_off >= prog->len) { 15838 verbose(env, "Invalid line_info[%u].insn_off:%u (prev_offset:%u prog->len:%u)\n", 15839 i, linfo[i].insn_off, prev_offset, 15840 prog->len); 15841 err = -EINVAL; 15842 goto err_free; 15843 } 15844 15845 if (!prog->insnsi[linfo[i].insn_off].code) { 15846 verbose(env, 15847 "Invalid insn code at line_info[%u].insn_off\n", 15848 i); 15849 err = -EINVAL; 15850 goto err_free; 15851 } 15852 15853 if (!btf_name_by_offset(btf, linfo[i].line_off) || 15854 !btf_name_by_offset(btf, linfo[i].file_name_off)) { 15855 verbose(env, "Invalid line_info[%u].line_off or .file_name_off\n", i); 15856 err = -EINVAL; 15857 goto err_free; 15858 } 15859 15860 if (s != env->subprog_cnt) { 15861 if (linfo[i].insn_off == sub[s].start) { 15862 sub[s].linfo_idx = i; 15863 s++; 15864 } else if (sub[s].start < linfo[i].insn_off) { 15865 verbose(env, "missing bpf_line_info for func#%u\n", s); 15866 err = -EINVAL; 15867 goto err_free; 15868 } 15869 } 15870 15871 prev_offset = linfo[i].insn_off; 15872 bpfptr_add(&ulinfo, rec_size); 15873 } 15874 15875 if (s != env->subprog_cnt) { 15876 verbose(env, "missing bpf_line_info for %u funcs starting from func#%u\n", 15877 env->subprog_cnt - s, s); 15878 err = -EINVAL; 15879 goto err_free; 15880 } 15881 15882 prog->aux->linfo = linfo; 15883 prog->aux->nr_linfo = nr_linfo; 15884 15885 return 0; 15886 15887 err_free: 15888 kvfree(linfo); 15889 return err; 15890 } 15891 15892 #define MIN_CORE_RELO_SIZE sizeof(struct bpf_core_relo) 15893 #define MAX_CORE_RELO_SIZE MAX_FUNCINFO_REC_SIZE 15894 15895 static int check_core_relo(struct bpf_verifier_env *env, 15896 const union bpf_attr *attr, 15897 bpfptr_t uattr) 15898 { 15899 u32 i, nr_core_relo, ncopy, expected_size, rec_size; 15900 struct bpf_core_relo core_relo = {}; 15901 struct bpf_prog *prog = env->prog; 15902 const struct btf *btf = prog->aux->btf; 15903 struct bpf_core_ctx ctx = { 15904 .log = &env->log, 15905 .btf = btf, 15906 }; 15907 bpfptr_t u_core_relo; 15908 int err; 15909 15910 nr_core_relo = attr->core_relo_cnt; 15911 if (!nr_core_relo) 15912 return 0; 15913 if (nr_core_relo > INT_MAX / sizeof(struct bpf_core_relo)) 15914 return -EINVAL; 15915 15916 rec_size = attr->core_relo_rec_size; 15917 if (rec_size < MIN_CORE_RELO_SIZE || 15918 rec_size > MAX_CORE_RELO_SIZE || 15919 rec_size % sizeof(u32)) 15920 return -EINVAL; 15921 15922 u_core_relo = make_bpfptr(attr->core_relos, uattr.is_kernel); 15923 expected_size = sizeof(struct bpf_core_relo); 15924 ncopy = min_t(u32, expected_size, rec_size); 15925 15926 /* Unlike func_info and line_info, copy and apply each CO-RE 15927 * relocation record one at a time. 15928 */ 15929 for (i = 0; i < nr_core_relo; i++) { 15930 /* future proofing when sizeof(bpf_core_relo) changes */ 15931 err = bpf_check_uarg_tail_zero(u_core_relo, expected_size, rec_size); 15932 if (err) { 15933 if (err == -E2BIG) { 15934 verbose(env, "nonzero tailing record in core_relo"); 15935 if (copy_to_bpfptr_offset(uattr, 15936 offsetof(union bpf_attr, core_relo_rec_size), 15937 &expected_size, sizeof(expected_size))) 15938 err = -EFAULT; 15939 } 15940 break; 15941 } 15942 15943 if (copy_from_bpfptr(&core_relo, u_core_relo, ncopy)) { 15944 err = -EFAULT; 15945 break; 15946 } 15947 15948 if (core_relo.insn_off % 8 || core_relo.insn_off / 8 >= prog->len) { 15949 verbose(env, "Invalid core_relo[%u].insn_off:%u prog->len:%u\n", 15950 i, core_relo.insn_off, prog->len); 15951 err = -EINVAL; 15952 break; 15953 } 15954 15955 err = bpf_core_apply(&ctx, &core_relo, i, 15956 &prog->insnsi[core_relo.insn_off / 8]); 15957 if (err) 15958 break; 15959 bpfptr_add(&u_core_relo, rec_size); 15960 } 15961 return err; 15962 } 15963 15964 static int check_btf_info_early(struct bpf_verifier_env *env, 15965 const union bpf_attr *attr, 15966 bpfptr_t uattr) 15967 { 15968 struct btf *btf; 15969 int err; 15970 15971 if (!attr->func_info_cnt && !attr->line_info_cnt) { 15972 if (check_abnormal_return(env)) 15973 return -EINVAL; 15974 return 0; 15975 } 15976 15977 btf = btf_get_by_fd(attr->prog_btf_fd); 15978 if (IS_ERR(btf)) 15979 return PTR_ERR(btf); 15980 if (btf_is_kernel(btf)) { 15981 btf_put(btf); 15982 return -EACCES; 15983 } 15984 env->prog->aux->btf = btf; 15985 15986 err = check_btf_func_early(env, attr, uattr); 15987 if (err) 15988 return err; 15989 return 0; 15990 } 15991 15992 static int check_btf_info(struct bpf_verifier_env *env, 15993 const union bpf_attr *attr, 15994 bpfptr_t uattr) 15995 { 15996 int err; 15997 15998 if (!attr->func_info_cnt && !attr->line_info_cnt) { 15999 if (check_abnormal_return(env)) 16000 return -EINVAL; 16001 return 0; 16002 } 16003 16004 err = check_btf_func(env, attr, uattr); 16005 if (err) 16006 return err; 16007 16008 err = check_btf_line(env, attr, uattr); 16009 if (err) 16010 return err; 16011 16012 err = check_core_relo(env, attr, uattr); 16013 if (err) 16014 return err; 16015 16016 return 0; 16017 } 16018 16019 /* check %cur's range satisfies %old's */ 16020 static bool range_within(struct bpf_reg_state *old, 16021 struct bpf_reg_state *cur) 16022 { 16023 return old->umin_value <= cur->umin_value && 16024 old->umax_value >= cur->umax_value && 16025 old->smin_value <= cur->smin_value && 16026 old->smax_value >= cur->smax_value && 16027 old->u32_min_value <= cur->u32_min_value && 16028 old->u32_max_value >= cur->u32_max_value && 16029 old->s32_min_value <= cur->s32_min_value && 16030 old->s32_max_value >= cur->s32_max_value; 16031 } 16032 16033 /* If in the old state two registers had the same id, then they need to have 16034 * the same id in the new state as well. But that id could be different from 16035 * the old state, so we need to track the mapping from old to new ids. 16036 * Once we have seen that, say, a reg with old id 5 had new id 9, any subsequent 16037 * regs with old id 5 must also have new id 9 for the new state to be safe. But 16038 * regs with a different old id could still have new id 9, we don't care about 16039 * that. 16040 * So we look through our idmap to see if this old id has been seen before. If 16041 * so, we require the new id to match; otherwise, we add the id pair to the map. 16042 */ 16043 static bool check_ids(u32 old_id, u32 cur_id, struct bpf_idmap *idmap) 16044 { 16045 struct bpf_id_pair *map = idmap->map; 16046 unsigned int i; 16047 16048 /* either both IDs should be set or both should be zero */ 16049 if (!!old_id != !!cur_id) 16050 return false; 16051 16052 if (old_id == 0) /* cur_id == 0 as well */ 16053 return true; 16054 16055 for (i = 0; i < BPF_ID_MAP_SIZE; i++) { 16056 if (!map[i].old) { 16057 /* Reached an empty slot; haven't seen this id before */ 16058 map[i].old = old_id; 16059 map[i].cur = cur_id; 16060 return true; 16061 } 16062 if (map[i].old == old_id) 16063 return map[i].cur == cur_id; 16064 if (map[i].cur == cur_id) 16065 return false; 16066 } 16067 /* We ran out of idmap slots, which should be impossible */ 16068 WARN_ON_ONCE(1); 16069 return false; 16070 } 16071 16072 /* Similar to check_ids(), but allocate a unique temporary ID 16073 * for 'old_id' or 'cur_id' of zero. 16074 * This makes pairs like '0 vs unique ID', 'unique ID vs 0' valid. 16075 */ 16076 static bool check_scalar_ids(u32 old_id, u32 cur_id, struct bpf_idmap *idmap) 16077 { 16078 old_id = old_id ? old_id : ++idmap->tmp_id_gen; 16079 cur_id = cur_id ? cur_id : ++idmap->tmp_id_gen; 16080 16081 return check_ids(old_id, cur_id, idmap); 16082 } 16083 16084 static void clean_func_state(struct bpf_verifier_env *env, 16085 struct bpf_func_state *st) 16086 { 16087 enum bpf_reg_liveness live; 16088 int i, j; 16089 16090 for (i = 0; i < BPF_REG_FP; i++) { 16091 live = st->regs[i].live; 16092 /* liveness must not touch this register anymore */ 16093 st->regs[i].live |= REG_LIVE_DONE; 16094 if (!(live & REG_LIVE_READ)) 16095 /* since the register is unused, clear its state 16096 * to make further comparison simpler 16097 */ 16098 __mark_reg_not_init(env, &st->regs[i]); 16099 } 16100 16101 for (i = 0; i < st->allocated_stack / BPF_REG_SIZE; i++) { 16102 live = st->stack[i].spilled_ptr.live; 16103 /* liveness must not touch this stack slot anymore */ 16104 st->stack[i].spilled_ptr.live |= REG_LIVE_DONE; 16105 if (!(live & REG_LIVE_READ)) { 16106 __mark_reg_not_init(env, &st->stack[i].spilled_ptr); 16107 for (j = 0; j < BPF_REG_SIZE; j++) 16108 st->stack[i].slot_type[j] = STACK_INVALID; 16109 } 16110 } 16111 } 16112 16113 static void clean_verifier_state(struct bpf_verifier_env *env, 16114 struct bpf_verifier_state *st) 16115 { 16116 int i; 16117 16118 if (st->frame[0]->regs[0].live & REG_LIVE_DONE) 16119 /* all regs in this state in all frames were already marked */ 16120 return; 16121 16122 for (i = 0; i <= st->curframe; i++) 16123 clean_func_state(env, st->frame[i]); 16124 } 16125 16126 /* the parentage chains form a tree. 16127 * the verifier states are added to state lists at given insn and 16128 * pushed into state stack for future exploration. 16129 * when the verifier reaches bpf_exit insn some of the verifer states 16130 * stored in the state lists have their final liveness state already, 16131 * but a lot of states will get revised from liveness point of view when 16132 * the verifier explores other branches. 16133 * Example: 16134 * 1: r0 = 1 16135 * 2: if r1 == 100 goto pc+1 16136 * 3: r0 = 2 16137 * 4: exit 16138 * when the verifier reaches exit insn the register r0 in the state list of 16139 * insn 2 will be seen as !REG_LIVE_READ. Then the verifier pops the other_branch 16140 * of insn 2 and goes exploring further. At the insn 4 it will walk the 16141 * parentage chain from insn 4 into insn 2 and will mark r0 as REG_LIVE_READ. 16142 * 16143 * Since the verifier pushes the branch states as it sees them while exploring 16144 * the program the condition of walking the branch instruction for the second 16145 * time means that all states below this branch were already explored and 16146 * their final liveness marks are already propagated. 16147 * Hence when the verifier completes the search of state list in is_state_visited() 16148 * we can call this clean_live_states() function to mark all liveness states 16149 * as REG_LIVE_DONE to indicate that 'parent' pointers of 'struct bpf_reg_state' 16150 * will not be used. 16151 * This function also clears the registers and stack for states that !READ 16152 * to simplify state merging. 16153 * 16154 * Important note here that walking the same branch instruction in the callee 16155 * doesn't meant that the states are DONE. The verifier has to compare 16156 * the callsites 16157 */ 16158 static void clean_live_states(struct bpf_verifier_env *env, int insn, 16159 struct bpf_verifier_state *cur) 16160 { 16161 struct bpf_verifier_state_list *sl; 16162 16163 sl = *explored_state(env, insn); 16164 while (sl) { 16165 if (sl->state.branches) 16166 goto next; 16167 if (sl->state.insn_idx != insn || 16168 !same_callsites(&sl->state, cur)) 16169 goto next; 16170 clean_verifier_state(env, &sl->state); 16171 next: 16172 sl = sl->next; 16173 } 16174 } 16175 16176 static bool regs_exact(const struct bpf_reg_state *rold, 16177 const struct bpf_reg_state *rcur, 16178 struct bpf_idmap *idmap) 16179 { 16180 return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 && 16181 check_ids(rold->id, rcur->id, idmap) && 16182 check_ids(rold->ref_obj_id, rcur->ref_obj_id, idmap); 16183 } 16184 16185 /* Returns true if (rold safe implies rcur safe) */ 16186 static bool regsafe(struct bpf_verifier_env *env, struct bpf_reg_state *rold, 16187 struct bpf_reg_state *rcur, struct bpf_idmap *idmap, bool exact) 16188 { 16189 if (exact) 16190 return regs_exact(rold, rcur, idmap); 16191 16192 if (!(rold->live & REG_LIVE_READ)) 16193 /* explored state didn't use this */ 16194 return true; 16195 if (rold->type == NOT_INIT) 16196 /* explored state can't have used this */ 16197 return true; 16198 if (rcur->type == NOT_INIT) 16199 return false; 16200 16201 /* Enforce that register types have to match exactly, including their 16202 * modifiers (like PTR_MAYBE_NULL, MEM_RDONLY, etc), as a general 16203 * rule. 16204 * 16205 * One can make a point that using a pointer register as unbounded 16206 * SCALAR would be technically acceptable, but this could lead to 16207 * pointer leaks because scalars are allowed to leak while pointers 16208 * are not. We could make this safe in special cases if root is 16209 * calling us, but it's probably not worth the hassle. 16210 * 16211 * Also, register types that are *not* MAYBE_NULL could technically be 16212 * safe to use as their MAYBE_NULL variants (e.g., PTR_TO_MAP_VALUE 16213 * is safe to be used as PTR_TO_MAP_VALUE_OR_NULL, provided both point 16214 * to the same map). 16215 * However, if the old MAYBE_NULL register then got NULL checked, 16216 * doing so could have affected others with the same id, and we can't 16217 * check for that because we lost the id when we converted to 16218 * a non-MAYBE_NULL variant. 16219 * So, as a general rule we don't allow mixing MAYBE_NULL and 16220 * non-MAYBE_NULL registers as well. 16221 */ 16222 if (rold->type != rcur->type) 16223 return false; 16224 16225 switch (base_type(rold->type)) { 16226 case SCALAR_VALUE: 16227 if (env->explore_alu_limits) { 16228 /* explore_alu_limits disables tnum_in() and range_within() 16229 * logic and requires everything to be strict 16230 */ 16231 return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 && 16232 check_scalar_ids(rold->id, rcur->id, idmap); 16233 } 16234 if (!rold->precise) 16235 return true; 16236 /* Why check_ids() for scalar registers? 16237 * 16238 * Consider the following BPF code: 16239 * 1: r6 = ... unbound scalar, ID=a ... 16240 * 2: r7 = ... unbound scalar, ID=b ... 16241 * 3: if (r6 > r7) goto +1 16242 * 4: r6 = r7 16243 * 5: if (r6 > X) goto ... 16244 * 6: ... memory operation using r7 ... 16245 * 16246 * First verification path is [1-6]: 16247 * - at (4) same bpf_reg_state::id (b) would be assigned to r6 and r7; 16248 * - at (5) r6 would be marked <= X, find_equal_scalars() would also mark 16249 * r7 <= X, because r6 and r7 share same id. 16250 * Next verification path is [1-4, 6]. 16251 * 16252 * Instruction (6) would be reached in two states: 16253 * I. r6{.id=b}, r7{.id=b} via path 1-6; 16254 * II. r6{.id=a}, r7{.id=b} via path 1-4, 6. 16255 * 16256 * Use check_ids() to distinguish these states. 16257 * --- 16258 * Also verify that new value satisfies old value range knowledge. 16259 */ 16260 return range_within(rold, rcur) && 16261 tnum_in(rold->var_off, rcur->var_off) && 16262 check_scalar_ids(rold->id, rcur->id, idmap); 16263 case PTR_TO_MAP_KEY: 16264 case PTR_TO_MAP_VALUE: 16265 case PTR_TO_MEM: 16266 case PTR_TO_BUF: 16267 case PTR_TO_TP_BUFFER: 16268 /* If the new min/max/var_off satisfy the old ones and 16269 * everything else matches, we are OK. 16270 */ 16271 return memcmp(rold, rcur, offsetof(struct bpf_reg_state, var_off)) == 0 && 16272 range_within(rold, rcur) && 16273 tnum_in(rold->var_off, rcur->var_off) && 16274 check_ids(rold->id, rcur->id, idmap) && 16275 check_ids(rold->ref_obj_id, rcur->ref_obj_id, idmap); 16276 case PTR_TO_PACKET_META: 16277 case PTR_TO_PACKET: 16278 /* We must have at least as much range as the old ptr 16279 * did, so that any accesses which were safe before are 16280 * still safe. This is true even if old range < old off, 16281 * since someone could have accessed through (ptr - k), or 16282 * even done ptr -= k in a register, to get a safe access. 16283 */ 16284 if (rold->range > rcur->range) 16285 return false; 16286 /* If the offsets don't match, we can't trust our alignment; 16287 * nor can we be sure that we won't fall out of range. 16288 */ 16289 if (rold->off != rcur->off) 16290 return false; 16291 /* id relations must be preserved */ 16292 if (!check_ids(rold->id, rcur->id, idmap)) 16293 return false; 16294 /* new val must satisfy old val knowledge */ 16295 return range_within(rold, rcur) && 16296 tnum_in(rold->var_off, rcur->var_off); 16297 case PTR_TO_STACK: 16298 /* two stack pointers are equal only if they're pointing to 16299 * the same stack frame, since fp-8 in foo != fp-8 in bar 16300 */ 16301 return regs_exact(rold, rcur, idmap) && rold->frameno == rcur->frameno; 16302 default: 16303 return regs_exact(rold, rcur, idmap); 16304 } 16305 } 16306 16307 static bool stacksafe(struct bpf_verifier_env *env, struct bpf_func_state *old, 16308 struct bpf_func_state *cur, struct bpf_idmap *idmap, bool exact) 16309 { 16310 int i, spi; 16311 16312 /* walk slots of the explored stack and ignore any additional 16313 * slots in the current stack, since explored(safe) state 16314 * didn't use them 16315 */ 16316 for (i = 0; i < old->allocated_stack; i++) { 16317 struct bpf_reg_state *old_reg, *cur_reg; 16318 16319 spi = i / BPF_REG_SIZE; 16320 16321 if (exact && 16322 old->stack[spi].slot_type[i % BPF_REG_SIZE] != 16323 cur->stack[spi].slot_type[i % BPF_REG_SIZE]) 16324 return false; 16325 16326 if (!(old->stack[spi].spilled_ptr.live & REG_LIVE_READ) && !exact) { 16327 i += BPF_REG_SIZE - 1; 16328 /* explored state didn't use this */ 16329 continue; 16330 } 16331 16332 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_INVALID) 16333 continue; 16334 16335 if (env->allow_uninit_stack && 16336 old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC) 16337 continue; 16338 16339 /* explored stack has more populated slots than current stack 16340 * and these slots were used 16341 */ 16342 if (i >= cur->allocated_stack) 16343 return false; 16344 16345 /* if old state was safe with misc data in the stack 16346 * it will be safe with zero-initialized stack. 16347 * The opposite is not true 16348 */ 16349 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC && 16350 cur->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_ZERO) 16351 continue; 16352 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] != 16353 cur->stack[spi].slot_type[i % BPF_REG_SIZE]) 16354 /* Ex: old explored (safe) state has STACK_SPILL in 16355 * this stack slot, but current has STACK_MISC -> 16356 * this verifier states are not equivalent, 16357 * return false to continue verification of this path 16358 */ 16359 return false; 16360 if (i % BPF_REG_SIZE != BPF_REG_SIZE - 1) 16361 continue; 16362 /* Both old and cur are having same slot_type */ 16363 switch (old->stack[spi].slot_type[BPF_REG_SIZE - 1]) { 16364 case STACK_SPILL: 16365 /* when explored and current stack slot are both storing 16366 * spilled registers, check that stored pointers types 16367 * are the same as well. 16368 * Ex: explored safe path could have stored 16369 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -8} 16370 * but current path has stored: 16371 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -16} 16372 * such verifier states are not equivalent. 16373 * return false to continue verification of this path 16374 */ 16375 if (!regsafe(env, &old->stack[spi].spilled_ptr, 16376 &cur->stack[spi].spilled_ptr, idmap, exact)) 16377 return false; 16378 break; 16379 case STACK_DYNPTR: 16380 old_reg = &old->stack[spi].spilled_ptr; 16381 cur_reg = &cur->stack[spi].spilled_ptr; 16382 if (old_reg->dynptr.type != cur_reg->dynptr.type || 16383 old_reg->dynptr.first_slot != cur_reg->dynptr.first_slot || 16384 !check_ids(old_reg->ref_obj_id, cur_reg->ref_obj_id, idmap)) 16385 return false; 16386 break; 16387 case STACK_ITER: 16388 old_reg = &old->stack[spi].spilled_ptr; 16389 cur_reg = &cur->stack[spi].spilled_ptr; 16390 /* iter.depth is not compared between states as it 16391 * doesn't matter for correctness and would otherwise 16392 * prevent convergence; we maintain it only to prevent 16393 * infinite loop check triggering, see 16394 * iter_active_depths_differ() 16395 */ 16396 if (old_reg->iter.btf != cur_reg->iter.btf || 16397 old_reg->iter.btf_id != cur_reg->iter.btf_id || 16398 old_reg->iter.state != cur_reg->iter.state || 16399 /* ignore {old_reg,cur_reg}->iter.depth, see above */ 16400 !check_ids(old_reg->ref_obj_id, cur_reg->ref_obj_id, idmap)) 16401 return false; 16402 break; 16403 case STACK_MISC: 16404 case STACK_ZERO: 16405 case STACK_INVALID: 16406 continue; 16407 /* Ensure that new unhandled slot types return false by default */ 16408 default: 16409 return false; 16410 } 16411 } 16412 return true; 16413 } 16414 16415 static bool refsafe(struct bpf_func_state *old, struct bpf_func_state *cur, 16416 struct bpf_idmap *idmap) 16417 { 16418 int i; 16419 16420 if (old->acquired_refs != cur->acquired_refs) 16421 return false; 16422 16423 for (i = 0; i < old->acquired_refs; i++) { 16424 if (!check_ids(old->refs[i].id, cur->refs[i].id, idmap)) 16425 return false; 16426 } 16427 16428 return true; 16429 } 16430 16431 /* compare two verifier states 16432 * 16433 * all states stored in state_list are known to be valid, since 16434 * verifier reached 'bpf_exit' instruction through them 16435 * 16436 * this function is called when verifier exploring different branches of 16437 * execution popped from the state stack. If it sees an old state that has 16438 * more strict register state and more strict stack state then this execution 16439 * branch doesn't need to be explored further, since verifier already 16440 * concluded that more strict state leads to valid finish. 16441 * 16442 * Therefore two states are equivalent if register state is more conservative 16443 * and explored stack state is more conservative than the current one. 16444 * Example: 16445 * explored current 16446 * (slot1=INV slot2=MISC) == (slot1=MISC slot2=MISC) 16447 * (slot1=MISC slot2=MISC) != (slot1=INV slot2=MISC) 16448 * 16449 * In other words if current stack state (one being explored) has more 16450 * valid slots than old one that already passed validation, it means 16451 * the verifier can stop exploring and conclude that current state is valid too 16452 * 16453 * Similarly with registers. If explored state has register type as invalid 16454 * whereas register type in current state is meaningful, it means that 16455 * the current state will reach 'bpf_exit' instruction safely 16456 */ 16457 static bool func_states_equal(struct bpf_verifier_env *env, struct bpf_func_state *old, 16458 struct bpf_func_state *cur, bool exact) 16459 { 16460 int i; 16461 16462 for (i = 0; i < MAX_BPF_REG; i++) 16463 if (!regsafe(env, &old->regs[i], &cur->regs[i], 16464 &env->idmap_scratch, exact)) 16465 return false; 16466 16467 if (!stacksafe(env, old, cur, &env->idmap_scratch, exact)) 16468 return false; 16469 16470 if (!refsafe(old, cur, &env->idmap_scratch)) 16471 return false; 16472 16473 return true; 16474 } 16475 16476 static void reset_idmap_scratch(struct bpf_verifier_env *env) 16477 { 16478 env->idmap_scratch.tmp_id_gen = env->id_gen; 16479 memset(&env->idmap_scratch.map, 0, sizeof(env->idmap_scratch.map)); 16480 } 16481 16482 static bool states_equal(struct bpf_verifier_env *env, 16483 struct bpf_verifier_state *old, 16484 struct bpf_verifier_state *cur, 16485 bool exact) 16486 { 16487 int i; 16488 16489 if (old->curframe != cur->curframe) 16490 return false; 16491 16492 reset_idmap_scratch(env); 16493 16494 /* Verification state from speculative execution simulation 16495 * must never prune a non-speculative execution one. 16496 */ 16497 if (old->speculative && !cur->speculative) 16498 return false; 16499 16500 if (old->active_lock.ptr != cur->active_lock.ptr) 16501 return false; 16502 16503 /* Old and cur active_lock's have to be either both present 16504 * or both absent. 16505 */ 16506 if (!!old->active_lock.id != !!cur->active_lock.id) 16507 return false; 16508 16509 if (old->active_lock.id && 16510 !check_ids(old->active_lock.id, cur->active_lock.id, &env->idmap_scratch)) 16511 return false; 16512 16513 if (old->active_rcu_lock != cur->active_rcu_lock) 16514 return false; 16515 16516 /* for states to be equal callsites have to be the same 16517 * and all frame states need to be equivalent 16518 */ 16519 for (i = 0; i <= old->curframe; i++) { 16520 if (old->frame[i]->callsite != cur->frame[i]->callsite) 16521 return false; 16522 if (!func_states_equal(env, old->frame[i], cur->frame[i], exact)) 16523 return false; 16524 } 16525 return true; 16526 } 16527 16528 /* Return 0 if no propagation happened. Return negative error code if error 16529 * happened. Otherwise, return the propagated bit. 16530 */ 16531 static int propagate_liveness_reg(struct bpf_verifier_env *env, 16532 struct bpf_reg_state *reg, 16533 struct bpf_reg_state *parent_reg) 16534 { 16535 u8 parent_flag = parent_reg->live & REG_LIVE_READ; 16536 u8 flag = reg->live & REG_LIVE_READ; 16537 int err; 16538 16539 /* When comes here, read flags of PARENT_REG or REG could be any of 16540 * REG_LIVE_READ64, REG_LIVE_READ32, REG_LIVE_NONE. There is no need 16541 * of propagation if PARENT_REG has strongest REG_LIVE_READ64. 16542 */ 16543 if (parent_flag == REG_LIVE_READ64 || 16544 /* Or if there is no read flag from REG. */ 16545 !flag || 16546 /* Or if the read flag from REG is the same as PARENT_REG. */ 16547 parent_flag == flag) 16548 return 0; 16549 16550 err = mark_reg_read(env, reg, parent_reg, flag); 16551 if (err) 16552 return err; 16553 16554 return flag; 16555 } 16556 16557 /* A write screens off any subsequent reads; but write marks come from the 16558 * straight-line code between a state and its parent. When we arrive at an 16559 * equivalent state (jump target or such) we didn't arrive by the straight-line 16560 * code, so read marks in the state must propagate to the parent regardless 16561 * of the state's write marks. That's what 'parent == state->parent' comparison 16562 * in mark_reg_read() is for. 16563 */ 16564 static int propagate_liveness(struct bpf_verifier_env *env, 16565 const struct bpf_verifier_state *vstate, 16566 struct bpf_verifier_state *vparent) 16567 { 16568 struct bpf_reg_state *state_reg, *parent_reg; 16569 struct bpf_func_state *state, *parent; 16570 int i, frame, err = 0; 16571 16572 if (vparent->curframe != vstate->curframe) { 16573 WARN(1, "propagate_live: parent frame %d current frame %d\n", 16574 vparent->curframe, vstate->curframe); 16575 return -EFAULT; 16576 } 16577 /* Propagate read liveness of registers... */ 16578 BUILD_BUG_ON(BPF_REG_FP + 1 != MAX_BPF_REG); 16579 for (frame = 0; frame <= vstate->curframe; frame++) { 16580 parent = vparent->frame[frame]; 16581 state = vstate->frame[frame]; 16582 parent_reg = parent->regs; 16583 state_reg = state->regs; 16584 /* We don't need to worry about FP liveness, it's read-only */ 16585 for (i = frame < vstate->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++) { 16586 err = propagate_liveness_reg(env, &state_reg[i], 16587 &parent_reg[i]); 16588 if (err < 0) 16589 return err; 16590 if (err == REG_LIVE_READ64) 16591 mark_insn_zext(env, &parent_reg[i]); 16592 } 16593 16594 /* Propagate stack slots. */ 16595 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE && 16596 i < parent->allocated_stack / BPF_REG_SIZE; i++) { 16597 parent_reg = &parent->stack[i].spilled_ptr; 16598 state_reg = &state->stack[i].spilled_ptr; 16599 err = propagate_liveness_reg(env, state_reg, 16600 parent_reg); 16601 if (err < 0) 16602 return err; 16603 } 16604 } 16605 return 0; 16606 } 16607 16608 /* find precise scalars in the previous equivalent state and 16609 * propagate them into the current state 16610 */ 16611 static int propagate_precision(struct bpf_verifier_env *env, 16612 const struct bpf_verifier_state *old) 16613 { 16614 struct bpf_reg_state *state_reg; 16615 struct bpf_func_state *state; 16616 int i, err = 0, fr; 16617 bool first; 16618 16619 for (fr = old->curframe; fr >= 0; fr--) { 16620 state = old->frame[fr]; 16621 state_reg = state->regs; 16622 first = true; 16623 for (i = 0; i < BPF_REG_FP; i++, state_reg++) { 16624 if (state_reg->type != SCALAR_VALUE || 16625 !state_reg->precise || 16626 !(state_reg->live & REG_LIVE_READ)) 16627 continue; 16628 if (env->log.level & BPF_LOG_LEVEL2) { 16629 if (first) 16630 verbose(env, "frame %d: propagating r%d", fr, i); 16631 else 16632 verbose(env, ",r%d", i); 16633 } 16634 bt_set_frame_reg(&env->bt, fr, i); 16635 first = false; 16636 } 16637 16638 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) { 16639 if (!is_spilled_reg(&state->stack[i])) 16640 continue; 16641 state_reg = &state->stack[i].spilled_ptr; 16642 if (state_reg->type != SCALAR_VALUE || 16643 !state_reg->precise || 16644 !(state_reg->live & REG_LIVE_READ)) 16645 continue; 16646 if (env->log.level & BPF_LOG_LEVEL2) { 16647 if (first) 16648 verbose(env, "frame %d: propagating fp%d", 16649 fr, (-i - 1) * BPF_REG_SIZE); 16650 else 16651 verbose(env, ",fp%d", (-i - 1) * BPF_REG_SIZE); 16652 } 16653 bt_set_frame_slot(&env->bt, fr, i); 16654 first = false; 16655 } 16656 if (!first) 16657 verbose(env, "\n"); 16658 } 16659 16660 err = mark_chain_precision_batch(env); 16661 if (err < 0) 16662 return err; 16663 16664 return 0; 16665 } 16666 16667 static bool states_maybe_looping(struct bpf_verifier_state *old, 16668 struct bpf_verifier_state *cur) 16669 { 16670 struct bpf_func_state *fold, *fcur; 16671 int i, fr = cur->curframe; 16672 16673 if (old->curframe != fr) 16674 return false; 16675 16676 fold = old->frame[fr]; 16677 fcur = cur->frame[fr]; 16678 for (i = 0; i < MAX_BPF_REG; i++) 16679 if (memcmp(&fold->regs[i], &fcur->regs[i], 16680 offsetof(struct bpf_reg_state, parent))) 16681 return false; 16682 return true; 16683 } 16684 16685 static bool is_iter_next_insn(struct bpf_verifier_env *env, int insn_idx) 16686 { 16687 return env->insn_aux_data[insn_idx].is_iter_next; 16688 } 16689 16690 /* is_state_visited() handles iter_next() (see process_iter_next_call() for 16691 * terminology) calls specially: as opposed to bounded BPF loops, it *expects* 16692 * states to match, which otherwise would look like an infinite loop. So while 16693 * iter_next() calls are taken care of, we still need to be careful and 16694 * prevent erroneous and too eager declaration of "ininite loop", when 16695 * iterators are involved. 16696 * 16697 * Here's a situation in pseudo-BPF assembly form: 16698 * 16699 * 0: again: ; set up iter_next() call args 16700 * 1: r1 = &it ; <CHECKPOINT HERE> 16701 * 2: call bpf_iter_num_next ; this is iter_next() call 16702 * 3: if r0 == 0 goto done 16703 * 4: ... something useful here ... 16704 * 5: goto again ; another iteration 16705 * 6: done: 16706 * 7: r1 = &it 16707 * 8: call bpf_iter_num_destroy ; clean up iter state 16708 * 9: exit 16709 * 16710 * This is a typical loop. Let's assume that we have a prune point at 1:, 16711 * before we get to `call bpf_iter_num_next` (e.g., because of that `goto 16712 * again`, assuming other heuristics don't get in a way). 16713 * 16714 * When we first time come to 1:, let's say we have some state X. We proceed 16715 * to 2:, fork states, enqueue ACTIVE, validate NULL case successfully, exit. 16716 * Now we come back to validate that forked ACTIVE state. We proceed through 16717 * 3-5, come to goto, jump to 1:. Let's assume our state didn't change, so we 16718 * are converging. But the problem is that we don't know that yet, as this 16719 * convergence has to happen at iter_next() call site only. So if nothing is 16720 * done, at 1: verifier will use bounded loop logic and declare infinite 16721 * looping (and would be *technically* correct, if not for iterator's 16722 * "eventual sticky NULL" contract, see process_iter_next_call()). But we 16723 * don't want that. So what we do in process_iter_next_call() when we go on 16724 * another ACTIVE iteration, we bump slot->iter.depth, to mark that it's 16725 * a different iteration. So when we suspect an infinite loop, we additionally 16726 * check if any of the *ACTIVE* iterator states depths differ. If yes, we 16727 * pretend we are not looping and wait for next iter_next() call. 16728 * 16729 * This only applies to ACTIVE state. In DRAINED state we don't expect to 16730 * loop, because that would actually mean infinite loop, as DRAINED state is 16731 * "sticky", and so we'll keep returning into the same instruction with the 16732 * same state (at least in one of possible code paths). 16733 * 16734 * This approach allows to keep infinite loop heuristic even in the face of 16735 * active iterator. E.g., C snippet below is and will be detected as 16736 * inifintely looping: 16737 * 16738 * struct bpf_iter_num it; 16739 * int *p, x; 16740 * 16741 * bpf_iter_num_new(&it, 0, 10); 16742 * while ((p = bpf_iter_num_next(&t))) { 16743 * x = p; 16744 * while (x--) {} // <<-- infinite loop here 16745 * } 16746 * 16747 */ 16748 static bool iter_active_depths_differ(struct bpf_verifier_state *old, struct bpf_verifier_state *cur) 16749 { 16750 struct bpf_reg_state *slot, *cur_slot; 16751 struct bpf_func_state *state; 16752 int i, fr; 16753 16754 for (fr = old->curframe; fr >= 0; fr--) { 16755 state = old->frame[fr]; 16756 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) { 16757 if (state->stack[i].slot_type[0] != STACK_ITER) 16758 continue; 16759 16760 slot = &state->stack[i].spilled_ptr; 16761 if (slot->iter.state != BPF_ITER_STATE_ACTIVE) 16762 continue; 16763 16764 cur_slot = &cur->frame[fr]->stack[i].spilled_ptr; 16765 if (cur_slot->iter.depth != slot->iter.depth) 16766 return true; 16767 } 16768 } 16769 return false; 16770 } 16771 16772 static int is_state_visited(struct bpf_verifier_env *env, int insn_idx) 16773 { 16774 struct bpf_verifier_state_list *new_sl; 16775 struct bpf_verifier_state_list *sl, **pprev; 16776 struct bpf_verifier_state *cur = env->cur_state, *new, *loop_entry; 16777 int i, j, n, err, states_cnt = 0; 16778 bool force_new_state = env->test_state_freq || is_force_checkpoint(env, insn_idx); 16779 bool add_new_state = force_new_state; 16780 bool force_exact; 16781 16782 /* bpf progs typically have pruning point every 4 instructions 16783 * http://vger.kernel.org/bpfconf2019.html#session-1 16784 * Do not add new state for future pruning if the verifier hasn't seen 16785 * at least 2 jumps and at least 8 instructions. 16786 * This heuristics helps decrease 'total_states' and 'peak_states' metric. 16787 * In tests that amounts to up to 50% reduction into total verifier 16788 * memory consumption and 20% verifier time speedup. 16789 */ 16790 if (env->jmps_processed - env->prev_jmps_processed >= 2 && 16791 env->insn_processed - env->prev_insn_processed >= 8) 16792 add_new_state = true; 16793 16794 pprev = explored_state(env, insn_idx); 16795 sl = *pprev; 16796 16797 clean_live_states(env, insn_idx, cur); 16798 16799 while (sl) { 16800 states_cnt++; 16801 if (sl->state.insn_idx != insn_idx) 16802 goto next; 16803 16804 if (sl->state.branches) { 16805 struct bpf_func_state *frame = sl->state.frame[sl->state.curframe]; 16806 16807 if (frame->in_async_callback_fn && 16808 frame->async_entry_cnt != cur->frame[cur->curframe]->async_entry_cnt) { 16809 /* Different async_entry_cnt means that the verifier is 16810 * processing another entry into async callback. 16811 * Seeing the same state is not an indication of infinite 16812 * loop or infinite recursion. 16813 * But finding the same state doesn't mean that it's safe 16814 * to stop processing the current state. The previous state 16815 * hasn't yet reached bpf_exit, since state.branches > 0. 16816 * Checking in_async_callback_fn alone is not enough either. 16817 * Since the verifier still needs to catch infinite loops 16818 * inside async callbacks. 16819 */ 16820 goto skip_inf_loop_check; 16821 } 16822 /* BPF open-coded iterators loop detection is special. 16823 * states_maybe_looping() logic is too simplistic in detecting 16824 * states that *might* be equivalent, because it doesn't know 16825 * about ID remapping, so don't even perform it. 16826 * See process_iter_next_call() and iter_active_depths_differ() 16827 * for overview of the logic. When current and one of parent 16828 * states are detected as equivalent, it's a good thing: we prove 16829 * convergence and can stop simulating further iterations. 16830 * It's safe to assume that iterator loop will finish, taking into 16831 * account iter_next() contract of eventually returning 16832 * sticky NULL result. 16833 * 16834 * Note, that states have to be compared exactly in this case because 16835 * read and precision marks might not be finalized inside the loop. 16836 * E.g. as in the program below: 16837 * 16838 * 1. r7 = -16 16839 * 2. r6 = bpf_get_prandom_u32() 16840 * 3. while (bpf_iter_num_next(&fp[-8])) { 16841 * 4. if (r6 != 42) { 16842 * 5. r7 = -32 16843 * 6. r6 = bpf_get_prandom_u32() 16844 * 7. continue 16845 * 8. } 16846 * 9. r0 = r10 16847 * 10. r0 += r7 16848 * 11. r8 = *(u64 *)(r0 + 0) 16849 * 12. r6 = bpf_get_prandom_u32() 16850 * 13. } 16851 * 16852 * Here verifier would first visit path 1-3, create a checkpoint at 3 16853 * with r7=-16, continue to 4-7,3. Existing checkpoint at 3 does 16854 * not have read or precision mark for r7 yet, thus inexact states 16855 * comparison would discard current state with r7=-32 16856 * => unsafe memory access at 11 would not be caught. 16857 */ 16858 if (is_iter_next_insn(env, insn_idx)) { 16859 if (states_equal(env, &sl->state, cur, true)) { 16860 struct bpf_func_state *cur_frame; 16861 struct bpf_reg_state *iter_state, *iter_reg; 16862 int spi; 16863 16864 cur_frame = cur->frame[cur->curframe]; 16865 /* btf_check_iter_kfuncs() enforces that 16866 * iter state pointer is always the first arg 16867 */ 16868 iter_reg = &cur_frame->regs[BPF_REG_1]; 16869 /* current state is valid due to states_equal(), 16870 * so we can assume valid iter and reg state, 16871 * no need for extra (re-)validations 16872 */ 16873 spi = __get_spi(iter_reg->off + iter_reg->var_off.value); 16874 iter_state = &func(env, iter_reg)->stack[spi].spilled_ptr; 16875 if (iter_state->iter.state == BPF_ITER_STATE_ACTIVE) { 16876 update_loop_entry(cur, &sl->state); 16877 goto hit; 16878 } 16879 } 16880 goto skip_inf_loop_check; 16881 } 16882 if (calls_callback(env, insn_idx)) { 16883 if (states_equal(env, &sl->state, cur, true)) 16884 goto hit; 16885 goto skip_inf_loop_check; 16886 } 16887 /* attempt to detect infinite loop to avoid unnecessary doomed work */ 16888 if (states_maybe_looping(&sl->state, cur) && 16889 states_equal(env, &sl->state, cur, false) && 16890 !iter_active_depths_differ(&sl->state, cur) && 16891 sl->state.callback_unroll_depth == cur->callback_unroll_depth) { 16892 verbose_linfo(env, insn_idx, "; "); 16893 verbose(env, "infinite loop detected at insn %d\n", insn_idx); 16894 verbose(env, "cur state:"); 16895 print_verifier_state(env, cur->frame[cur->curframe], true); 16896 verbose(env, "old state:"); 16897 print_verifier_state(env, sl->state.frame[cur->curframe], true); 16898 return -EINVAL; 16899 } 16900 /* if the verifier is processing a loop, avoid adding new state 16901 * too often, since different loop iterations have distinct 16902 * states and may not help future pruning. 16903 * This threshold shouldn't be too low to make sure that 16904 * a loop with large bound will be rejected quickly. 16905 * The most abusive loop will be: 16906 * r1 += 1 16907 * if r1 < 1000000 goto pc-2 16908 * 1M insn_procssed limit / 100 == 10k peak states. 16909 * This threshold shouldn't be too high either, since states 16910 * at the end of the loop are likely to be useful in pruning. 16911 */ 16912 skip_inf_loop_check: 16913 if (!force_new_state && 16914 env->jmps_processed - env->prev_jmps_processed < 20 && 16915 env->insn_processed - env->prev_insn_processed < 100) 16916 add_new_state = false; 16917 goto miss; 16918 } 16919 /* If sl->state is a part of a loop and this loop's entry is a part of 16920 * current verification path then states have to be compared exactly. 16921 * 'force_exact' is needed to catch the following case: 16922 * 16923 * initial Here state 'succ' was processed first, 16924 * | it was eventually tracked to produce a 16925 * V state identical to 'hdr'. 16926 * .---------> hdr All branches from 'succ' had been explored 16927 * | | and thus 'succ' has its .branches == 0. 16928 * | V 16929 * | .------... Suppose states 'cur' and 'succ' correspond 16930 * | | | to the same instruction + callsites. 16931 * | V V In such case it is necessary to check 16932 * | ... ... if 'succ' and 'cur' are states_equal(). 16933 * | | | If 'succ' and 'cur' are a part of the 16934 * | V V same loop exact flag has to be set. 16935 * | succ <- cur To check if that is the case, verify 16936 * | | if loop entry of 'succ' is in current 16937 * | V DFS path. 16938 * | ... 16939 * | | 16940 * '----' 16941 * 16942 * Additional details are in the comment before get_loop_entry(). 16943 */ 16944 loop_entry = get_loop_entry(&sl->state); 16945 force_exact = loop_entry && loop_entry->branches > 0; 16946 if (states_equal(env, &sl->state, cur, force_exact)) { 16947 if (force_exact) 16948 update_loop_entry(cur, loop_entry); 16949 hit: 16950 sl->hit_cnt++; 16951 /* reached equivalent register/stack state, 16952 * prune the search. 16953 * Registers read by the continuation are read by us. 16954 * If we have any write marks in env->cur_state, they 16955 * will prevent corresponding reads in the continuation 16956 * from reaching our parent (an explored_state). Our 16957 * own state will get the read marks recorded, but 16958 * they'll be immediately forgotten as we're pruning 16959 * this state and will pop a new one. 16960 */ 16961 err = propagate_liveness(env, &sl->state, cur); 16962 16963 /* if previous state reached the exit with precision and 16964 * current state is equivalent to it (except precsion marks) 16965 * the precision needs to be propagated back in 16966 * the current state. 16967 */ 16968 if (is_jmp_point(env, env->insn_idx)) 16969 err = err ? : push_jmp_history(env, cur, 0); 16970 err = err ? : propagate_precision(env, &sl->state); 16971 if (err) 16972 return err; 16973 return 1; 16974 } 16975 miss: 16976 /* when new state is not going to be added do not increase miss count. 16977 * Otherwise several loop iterations will remove the state 16978 * recorded earlier. The goal of these heuristics is to have 16979 * states from some iterations of the loop (some in the beginning 16980 * and some at the end) to help pruning. 16981 */ 16982 if (add_new_state) 16983 sl->miss_cnt++; 16984 /* heuristic to determine whether this state is beneficial 16985 * to keep checking from state equivalence point of view. 16986 * Higher numbers increase max_states_per_insn and verification time, 16987 * but do not meaningfully decrease insn_processed. 16988 * 'n' controls how many times state could miss before eviction. 16989 * Use bigger 'n' for checkpoints because evicting checkpoint states 16990 * too early would hinder iterator convergence. 16991 */ 16992 n = is_force_checkpoint(env, insn_idx) && sl->state.branches > 0 ? 64 : 3; 16993 if (sl->miss_cnt > sl->hit_cnt * n + n) { 16994 /* the state is unlikely to be useful. Remove it to 16995 * speed up verification 16996 */ 16997 *pprev = sl->next; 16998 if (sl->state.frame[0]->regs[0].live & REG_LIVE_DONE && 16999 !sl->state.used_as_loop_entry) { 17000 u32 br = sl->state.branches; 17001 17002 WARN_ONCE(br, 17003 "BUG live_done but branches_to_explore %d\n", 17004 br); 17005 free_verifier_state(&sl->state, false); 17006 kfree(sl); 17007 env->peak_states--; 17008 } else { 17009 /* cannot free this state, since parentage chain may 17010 * walk it later. Add it for free_list instead to 17011 * be freed at the end of verification 17012 */ 17013 sl->next = env->free_list; 17014 env->free_list = sl; 17015 } 17016 sl = *pprev; 17017 continue; 17018 } 17019 next: 17020 pprev = &sl->next; 17021 sl = *pprev; 17022 } 17023 17024 if (env->max_states_per_insn < states_cnt) 17025 env->max_states_per_insn = states_cnt; 17026 17027 if (!env->bpf_capable && states_cnt > BPF_COMPLEXITY_LIMIT_STATES) 17028 return 0; 17029 17030 if (!add_new_state) 17031 return 0; 17032 17033 /* There were no equivalent states, remember the current one. 17034 * Technically the current state is not proven to be safe yet, 17035 * but it will either reach outer most bpf_exit (which means it's safe) 17036 * or it will be rejected. When there are no loops the verifier won't be 17037 * seeing this tuple (frame[0].callsite, frame[1].callsite, .. insn_idx) 17038 * again on the way to bpf_exit. 17039 * When looping the sl->state.branches will be > 0 and this state 17040 * will not be considered for equivalence until branches == 0. 17041 */ 17042 new_sl = kzalloc(sizeof(struct bpf_verifier_state_list), GFP_KERNEL); 17043 if (!new_sl) 17044 return -ENOMEM; 17045 env->total_states++; 17046 env->peak_states++; 17047 env->prev_jmps_processed = env->jmps_processed; 17048 env->prev_insn_processed = env->insn_processed; 17049 17050 /* forget precise markings we inherited, see __mark_chain_precision */ 17051 if (env->bpf_capable) 17052 mark_all_scalars_imprecise(env, cur); 17053 17054 /* add new state to the head of linked list */ 17055 new = &new_sl->state; 17056 err = copy_verifier_state(new, cur); 17057 if (err) { 17058 free_verifier_state(new, false); 17059 kfree(new_sl); 17060 return err; 17061 } 17062 new->insn_idx = insn_idx; 17063 WARN_ONCE(new->branches != 1, 17064 "BUG is_state_visited:branches_to_explore=%d insn %d\n", new->branches, insn_idx); 17065 17066 cur->parent = new; 17067 cur->first_insn_idx = insn_idx; 17068 cur->dfs_depth = new->dfs_depth + 1; 17069 clear_jmp_history(cur); 17070 new_sl->next = *explored_state(env, insn_idx); 17071 *explored_state(env, insn_idx) = new_sl; 17072 /* connect new state to parentage chain. Current frame needs all 17073 * registers connected. Only r6 - r9 of the callers are alive (pushed 17074 * to the stack implicitly by JITs) so in callers' frames connect just 17075 * r6 - r9 as an optimization. Callers will have r1 - r5 connected to 17076 * the state of the call instruction (with WRITTEN set), and r0 comes 17077 * from callee with its full parentage chain, anyway. 17078 */ 17079 /* clear write marks in current state: the writes we did are not writes 17080 * our child did, so they don't screen off its reads from us. 17081 * (There are no read marks in current state, because reads always mark 17082 * their parent and current state never has children yet. Only 17083 * explored_states can get read marks.) 17084 */ 17085 for (j = 0; j <= cur->curframe; j++) { 17086 for (i = j < cur->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++) 17087 cur->frame[j]->regs[i].parent = &new->frame[j]->regs[i]; 17088 for (i = 0; i < BPF_REG_FP; i++) 17089 cur->frame[j]->regs[i].live = REG_LIVE_NONE; 17090 } 17091 17092 /* all stack frames are accessible from callee, clear them all */ 17093 for (j = 0; j <= cur->curframe; j++) { 17094 struct bpf_func_state *frame = cur->frame[j]; 17095 struct bpf_func_state *newframe = new->frame[j]; 17096 17097 for (i = 0; i < frame->allocated_stack / BPF_REG_SIZE; i++) { 17098 frame->stack[i].spilled_ptr.live = REG_LIVE_NONE; 17099 frame->stack[i].spilled_ptr.parent = 17100 &newframe->stack[i].spilled_ptr; 17101 } 17102 } 17103 return 0; 17104 } 17105 17106 /* Return true if it's OK to have the same insn return a different type. */ 17107 static bool reg_type_mismatch_ok(enum bpf_reg_type type) 17108 { 17109 switch (base_type(type)) { 17110 case PTR_TO_CTX: 17111 case PTR_TO_SOCKET: 17112 case PTR_TO_SOCK_COMMON: 17113 case PTR_TO_TCP_SOCK: 17114 case PTR_TO_XDP_SOCK: 17115 case PTR_TO_BTF_ID: 17116 return false; 17117 default: 17118 return true; 17119 } 17120 } 17121 17122 /* If an instruction was previously used with particular pointer types, then we 17123 * need to be careful to avoid cases such as the below, where it may be ok 17124 * for one branch accessing the pointer, but not ok for the other branch: 17125 * 17126 * R1 = sock_ptr 17127 * goto X; 17128 * ... 17129 * R1 = some_other_valid_ptr; 17130 * goto X; 17131 * ... 17132 * R2 = *(u32 *)(R1 + 0); 17133 */ 17134 static bool reg_type_mismatch(enum bpf_reg_type src, enum bpf_reg_type prev) 17135 { 17136 return src != prev && (!reg_type_mismatch_ok(src) || 17137 !reg_type_mismatch_ok(prev)); 17138 } 17139 17140 static int save_aux_ptr_type(struct bpf_verifier_env *env, enum bpf_reg_type type, 17141 bool allow_trust_missmatch) 17142 { 17143 enum bpf_reg_type *prev_type = &env->insn_aux_data[env->insn_idx].ptr_type; 17144 17145 if (*prev_type == NOT_INIT) { 17146 /* Saw a valid insn 17147 * dst_reg = *(u32 *)(src_reg + off) 17148 * save type to validate intersecting paths 17149 */ 17150 *prev_type = type; 17151 } else if (reg_type_mismatch(type, *prev_type)) { 17152 /* Abuser program is trying to use the same insn 17153 * dst_reg = *(u32*) (src_reg + off) 17154 * with different pointer types: 17155 * src_reg == ctx in one branch and 17156 * src_reg == stack|map in some other branch. 17157 * Reject it. 17158 */ 17159 if (allow_trust_missmatch && 17160 base_type(type) == PTR_TO_BTF_ID && 17161 base_type(*prev_type) == PTR_TO_BTF_ID) { 17162 /* 17163 * Have to support a use case when one path through 17164 * the program yields TRUSTED pointer while another 17165 * is UNTRUSTED. Fallback to UNTRUSTED to generate 17166 * BPF_PROBE_MEM/BPF_PROBE_MEMSX. 17167 */ 17168 *prev_type = PTR_TO_BTF_ID | PTR_UNTRUSTED; 17169 } else { 17170 verbose(env, "same insn cannot be used with different pointers\n"); 17171 return -EINVAL; 17172 } 17173 } 17174 17175 return 0; 17176 } 17177 17178 static int do_check(struct bpf_verifier_env *env) 17179 { 17180 bool pop_log = !(env->log.level & BPF_LOG_LEVEL2); 17181 struct bpf_verifier_state *state = env->cur_state; 17182 struct bpf_insn *insns = env->prog->insnsi; 17183 struct bpf_reg_state *regs; 17184 int insn_cnt = env->prog->len; 17185 bool do_print_state = false; 17186 int prev_insn_idx = -1; 17187 17188 for (;;) { 17189 bool exception_exit = false; 17190 struct bpf_insn *insn; 17191 u8 class; 17192 int err; 17193 17194 /* reset current history entry on each new instruction */ 17195 env->cur_hist_ent = NULL; 17196 17197 env->prev_insn_idx = prev_insn_idx; 17198 if (env->insn_idx >= insn_cnt) { 17199 verbose(env, "invalid insn idx %d insn_cnt %d\n", 17200 env->insn_idx, insn_cnt); 17201 return -EFAULT; 17202 } 17203 17204 insn = &insns[env->insn_idx]; 17205 class = BPF_CLASS(insn->code); 17206 17207 if (++env->insn_processed > BPF_COMPLEXITY_LIMIT_INSNS) { 17208 verbose(env, 17209 "BPF program is too large. Processed %d insn\n", 17210 env->insn_processed); 17211 return -E2BIG; 17212 } 17213 17214 state->last_insn_idx = env->prev_insn_idx; 17215 17216 if (is_prune_point(env, env->insn_idx)) { 17217 err = is_state_visited(env, env->insn_idx); 17218 if (err < 0) 17219 return err; 17220 if (err == 1) { 17221 /* found equivalent state, can prune the search */ 17222 if (env->log.level & BPF_LOG_LEVEL) { 17223 if (do_print_state) 17224 verbose(env, "\nfrom %d to %d%s: safe\n", 17225 env->prev_insn_idx, env->insn_idx, 17226 env->cur_state->speculative ? 17227 " (speculative execution)" : ""); 17228 else 17229 verbose(env, "%d: safe\n", env->insn_idx); 17230 } 17231 goto process_bpf_exit; 17232 } 17233 } 17234 17235 if (is_jmp_point(env, env->insn_idx)) { 17236 err = push_jmp_history(env, state, 0); 17237 if (err) 17238 return err; 17239 } 17240 17241 if (signal_pending(current)) 17242 return -EAGAIN; 17243 17244 if (need_resched()) 17245 cond_resched(); 17246 17247 if (env->log.level & BPF_LOG_LEVEL2 && do_print_state) { 17248 verbose(env, "\nfrom %d to %d%s:", 17249 env->prev_insn_idx, env->insn_idx, 17250 env->cur_state->speculative ? 17251 " (speculative execution)" : ""); 17252 print_verifier_state(env, state->frame[state->curframe], true); 17253 do_print_state = false; 17254 } 17255 17256 if (env->log.level & BPF_LOG_LEVEL) { 17257 const struct bpf_insn_cbs cbs = { 17258 .cb_call = disasm_kfunc_name, 17259 .cb_print = verbose, 17260 .private_data = env, 17261 }; 17262 17263 if (verifier_state_scratched(env)) 17264 print_insn_state(env, state->frame[state->curframe]); 17265 17266 verbose_linfo(env, env->insn_idx, "; "); 17267 env->prev_log_pos = env->log.end_pos; 17268 verbose(env, "%d: ", env->insn_idx); 17269 print_bpf_insn(&cbs, insn, env->allow_ptr_leaks); 17270 env->prev_insn_print_pos = env->log.end_pos - env->prev_log_pos; 17271 env->prev_log_pos = env->log.end_pos; 17272 } 17273 17274 if (bpf_prog_is_offloaded(env->prog->aux)) { 17275 err = bpf_prog_offload_verify_insn(env, env->insn_idx, 17276 env->prev_insn_idx); 17277 if (err) 17278 return err; 17279 } 17280 17281 regs = cur_regs(env); 17282 sanitize_mark_insn_seen(env); 17283 prev_insn_idx = env->insn_idx; 17284 17285 if (class == BPF_ALU || class == BPF_ALU64) { 17286 err = check_alu_op(env, insn); 17287 if (err) 17288 return err; 17289 17290 } else if (class == BPF_LDX) { 17291 enum bpf_reg_type src_reg_type; 17292 17293 /* check for reserved fields is already done */ 17294 17295 /* check src operand */ 17296 err = check_reg_arg(env, insn->src_reg, SRC_OP); 17297 if (err) 17298 return err; 17299 17300 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK); 17301 if (err) 17302 return err; 17303 17304 src_reg_type = regs[insn->src_reg].type; 17305 17306 /* check that memory (src_reg + off) is readable, 17307 * the state of dst_reg will be updated by this func 17308 */ 17309 err = check_mem_access(env, env->insn_idx, insn->src_reg, 17310 insn->off, BPF_SIZE(insn->code), 17311 BPF_READ, insn->dst_reg, false, 17312 BPF_MODE(insn->code) == BPF_MEMSX); 17313 err = err ?: save_aux_ptr_type(env, src_reg_type, true); 17314 err = err ?: reg_bounds_sanity_check(env, ®s[insn->dst_reg], "ldx"); 17315 if (err) 17316 return err; 17317 } else if (class == BPF_STX) { 17318 enum bpf_reg_type dst_reg_type; 17319 17320 if (BPF_MODE(insn->code) == BPF_ATOMIC) { 17321 err = check_atomic(env, env->insn_idx, insn); 17322 if (err) 17323 return err; 17324 env->insn_idx++; 17325 continue; 17326 } 17327 17328 if (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0) { 17329 verbose(env, "BPF_STX uses reserved fields\n"); 17330 return -EINVAL; 17331 } 17332 17333 /* check src1 operand */ 17334 err = check_reg_arg(env, insn->src_reg, SRC_OP); 17335 if (err) 17336 return err; 17337 /* check src2 operand */ 17338 err = check_reg_arg(env, insn->dst_reg, SRC_OP); 17339 if (err) 17340 return err; 17341 17342 dst_reg_type = regs[insn->dst_reg].type; 17343 17344 /* check that memory (dst_reg + off) is writeable */ 17345 err = check_mem_access(env, env->insn_idx, insn->dst_reg, 17346 insn->off, BPF_SIZE(insn->code), 17347 BPF_WRITE, insn->src_reg, false, false); 17348 if (err) 17349 return err; 17350 17351 err = save_aux_ptr_type(env, dst_reg_type, false); 17352 if (err) 17353 return err; 17354 } else if (class == BPF_ST) { 17355 enum bpf_reg_type dst_reg_type; 17356 17357 if (BPF_MODE(insn->code) != BPF_MEM || 17358 insn->src_reg != BPF_REG_0) { 17359 verbose(env, "BPF_ST uses reserved fields\n"); 17360 return -EINVAL; 17361 } 17362 /* check src operand */ 17363 err = check_reg_arg(env, insn->dst_reg, SRC_OP); 17364 if (err) 17365 return err; 17366 17367 dst_reg_type = regs[insn->dst_reg].type; 17368 17369 /* check that memory (dst_reg + off) is writeable */ 17370 err = check_mem_access(env, env->insn_idx, insn->dst_reg, 17371 insn->off, BPF_SIZE(insn->code), 17372 BPF_WRITE, -1, false, false); 17373 if (err) 17374 return err; 17375 17376 err = save_aux_ptr_type(env, dst_reg_type, false); 17377 if (err) 17378 return err; 17379 } else if (class == BPF_JMP || class == BPF_JMP32) { 17380 u8 opcode = BPF_OP(insn->code); 17381 17382 env->jmps_processed++; 17383 if (opcode == BPF_CALL) { 17384 if (BPF_SRC(insn->code) != BPF_K || 17385 (insn->src_reg != BPF_PSEUDO_KFUNC_CALL 17386 && insn->off != 0) || 17387 (insn->src_reg != BPF_REG_0 && 17388 insn->src_reg != BPF_PSEUDO_CALL && 17389 insn->src_reg != BPF_PSEUDO_KFUNC_CALL) || 17390 insn->dst_reg != BPF_REG_0 || 17391 class == BPF_JMP32) { 17392 verbose(env, "BPF_CALL uses reserved fields\n"); 17393 return -EINVAL; 17394 } 17395 17396 if (env->cur_state->active_lock.ptr) { 17397 if ((insn->src_reg == BPF_REG_0 && insn->imm != BPF_FUNC_spin_unlock) || 17398 (insn->src_reg == BPF_PSEUDO_CALL) || 17399 (insn->src_reg == BPF_PSEUDO_KFUNC_CALL && 17400 (insn->off != 0 || !is_bpf_graph_api_kfunc(insn->imm)))) { 17401 verbose(env, "function calls are not allowed while holding a lock\n"); 17402 return -EINVAL; 17403 } 17404 } 17405 if (insn->src_reg == BPF_PSEUDO_CALL) { 17406 err = check_func_call(env, insn, &env->insn_idx); 17407 } else if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) { 17408 err = check_kfunc_call(env, insn, &env->insn_idx); 17409 if (!err && is_bpf_throw_kfunc(insn)) { 17410 exception_exit = true; 17411 goto process_bpf_exit_full; 17412 } 17413 } else { 17414 err = check_helper_call(env, insn, &env->insn_idx); 17415 } 17416 if (err) 17417 return err; 17418 17419 mark_reg_scratched(env, BPF_REG_0); 17420 } else if (opcode == BPF_JA) { 17421 if (BPF_SRC(insn->code) != BPF_K || 17422 insn->src_reg != BPF_REG_0 || 17423 insn->dst_reg != BPF_REG_0 || 17424 (class == BPF_JMP && insn->imm != 0) || 17425 (class == BPF_JMP32 && insn->off != 0)) { 17426 verbose(env, "BPF_JA uses reserved fields\n"); 17427 return -EINVAL; 17428 } 17429 17430 if (class == BPF_JMP) 17431 env->insn_idx += insn->off + 1; 17432 else 17433 env->insn_idx += insn->imm + 1; 17434 continue; 17435 17436 } else if (opcode == BPF_EXIT) { 17437 if (BPF_SRC(insn->code) != BPF_K || 17438 insn->imm != 0 || 17439 insn->src_reg != BPF_REG_0 || 17440 insn->dst_reg != BPF_REG_0 || 17441 class == BPF_JMP32) { 17442 verbose(env, "BPF_EXIT uses reserved fields\n"); 17443 return -EINVAL; 17444 } 17445 process_bpf_exit_full: 17446 if (env->cur_state->active_lock.ptr && 17447 !in_rbtree_lock_required_cb(env)) { 17448 verbose(env, "bpf_spin_unlock is missing\n"); 17449 return -EINVAL; 17450 } 17451 17452 if (env->cur_state->active_rcu_lock && 17453 !in_rbtree_lock_required_cb(env)) { 17454 verbose(env, "bpf_rcu_read_unlock is missing\n"); 17455 return -EINVAL; 17456 } 17457 17458 /* We must do check_reference_leak here before 17459 * prepare_func_exit to handle the case when 17460 * state->curframe > 0, it may be a callback 17461 * function, for which reference_state must 17462 * match caller reference state when it exits. 17463 */ 17464 err = check_reference_leak(env, exception_exit); 17465 if (err) 17466 return err; 17467 17468 /* The side effect of the prepare_func_exit 17469 * which is being skipped is that it frees 17470 * bpf_func_state. Typically, process_bpf_exit 17471 * will only be hit with outermost exit. 17472 * copy_verifier_state in pop_stack will handle 17473 * freeing of any extra bpf_func_state left over 17474 * from not processing all nested function 17475 * exits. We also skip return code checks as 17476 * they are not needed for exceptional exits. 17477 */ 17478 if (exception_exit) 17479 goto process_bpf_exit; 17480 17481 if (state->curframe) { 17482 /* exit from nested function */ 17483 err = prepare_func_exit(env, &env->insn_idx); 17484 if (err) 17485 return err; 17486 do_print_state = true; 17487 continue; 17488 } 17489 17490 err = check_return_code(env, BPF_REG_0, "R0"); 17491 if (err) 17492 return err; 17493 process_bpf_exit: 17494 mark_verifier_state_scratched(env); 17495 update_branch_counts(env, env->cur_state); 17496 err = pop_stack(env, &prev_insn_idx, 17497 &env->insn_idx, pop_log); 17498 if (err < 0) { 17499 if (err != -ENOENT) 17500 return err; 17501 break; 17502 } else { 17503 do_print_state = true; 17504 continue; 17505 } 17506 } else { 17507 err = check_cond_jmp_op(env, insn, &env->insn_idx); 17508 if (err) 17509 return err; 17510 } 17511 } else if (class == BPF_LD) { 17512 u8 mode = BPF_MODE(insn->code); 17513 17514 if (mode == BPF_ABS || mode == BPF_IND) { 17515 err = check_ld_abs(env, insn); 17516 if (err) 17517 return err; 17518 17519 } else if (mode == BPF_IMM) { 17520 err = check_ld_imm(env, insn); 17521 if (err) 17522 return err; 17523 17524 env->insn_idx++; 17525 sanitize_mark_insn_seen(env); 17526 } else { 17527 verbose(env, "invalid BPF_LD mode\n"); 17528 return -EINVAL; 17529 } 17530 } else { 17531 verbose(env, "unknown insn class %d\n", class); 17532 return -EINVAL; 17533 } 17534 17535 env->insn_idx++; 17536 } 17537 17538 return 0; 17539 } 17540 17541 static int find_btf_percpu_datasec(struct btf *btf) 17542 { 17543 const struct btf_type *t; 17544 const char *tname; 17545 int i, n; 17546 17547 /* 17548 * Both vmlinux and module each have their own ".data..percpu" 17549 * DATASECs in BTF. So for module's case, we need to skip vmlinux BTF 17550 * types to look at only module's own BTF types. 17551 */ 17552 n = btf_nr_types(btf); 17553 if (btf_is_module(btf)) 17554 i = btf_nr_types(btf_vmlinux); 17555 else 17556 i = 1; 17557 17558 for(; i < n; i++) { 17559 t = btf_type_by_id(btf, i); 17560 if (BTF_INFO_KIND(t->info) != BTF_KIND_DATASEC) 17561 continue; 17562 17563 tname = btf_name_by_offset(btf, t->name_off); 17564 if (!strcmp(tname, ".data..percpu")) 17565 return i; 17566 } 17567 17568 return -ENOENT; 17569 } 17570 17571 /* replace pseudo btf_id with kernel symbol address */ 17572 static int check_pseudo_btf_id(struct bpf_verifier_env *env, 17573 struct bpf_insn *insn, 17574 struct bpf_insn_aux_data *aux) 17575 { 17576 const struct btf_var_secinfo *vsi; 17577 const struct btf_type *datasec; 17578 struct btf_mod_pair *btf_mod; 17579 const struct btf_type *t; 17580 const char *sym_name; 17581 bool percpu = false; 17582 u32 type, id = insn->imm; 17583 struct btf *btf; 17584 s32 datasec_id; 17585 u64 addr; 17586 int i, btf_fd, err; 17587 17588 btf_fd = insn[1].imm; 17589 if (btf_fd) { 17590 btf = btf_get_by_fd(btf_fd); 17591 if (IS_ERR(btf)) { 17592 verbose(env, "invalid module BTF object FD specified.\n"); 17593 return -EINVAL; 17594 } 17595 } else { 17596 if (!btf_vmlinux) { 17597 verbose(env, "kernel is missing BTF, make sure CONFIG_DEBUG_INFO_BTF=y is specified in Kconfig.\n"); 17598 return -EINVAL; 17599 } 17600 btf = btf_vmlinux; 17601 btf_get(btf); 17602 } 17603 17604 t = btf_type_by_id(btf, id); 17605 if (!t) { 17606 verbose(env, "ldimm64 insn specifies invalid btf_id %d.\n", id); 17607 err = -ENOENT; 17608 goto err_put; 17609 } 17610 17611 if (!btf_type_is_var(t) && !btf_type_is_func(t)) { 17612 verbose(env, "pseudo btf_id %d in ldimm64 isn't KIND_VAR or KIND_FUNC\n", id); 17613 err = -EINVAL; 17614 goto err_put; 17615 } 17616 17617 sym_name = btf_name_by_offset(btf, t->name_off); 17618 addr = kallsyms_lookup_name(sym_name); 17619 if (!addr) { 17620 verbose(env, "ldimm64 failed to find the address for kernel symbol '%s'.\n", 17621 sym_name); 17622 err = -ENOENT; 17623 goto err_put; 17624 } 17625 insn[0].imm = (u32)addr; 17626 insn[1].imm = addr >> 32; 17627 17628 if (btf_type_is_func(t)) { 17629 aux->btf_var.reg_type = PTR_TO_MEM | MEM_RDONLY; 17630 aux->btf_var.mem_size = 0; 17631 goto check_btf; 17632 } 17633 17634 datasec_id = find_btf_percpu_datasec(btf); 17635 if (datasec_id > 0) { 17636 datasec = btf_type_by_id(btf, datasec_id); 17637 for_each_vsi(i, datasec, vsi) { 17638 if (vsi->type == id) { 17639 percpu = true; 17640 break; 17641 } 17642 } 17643 } 17644 17645 type = t->type; 17646 t = btf_type_skip_modifiers(btf, type, NULL); 17647 if (percpu) { 17648 aux->btf_var.reg_type = PTR_TO_BTF_ID | MEM_PERCPU; 17649 aux->btf_var.btf = btf; 17650 aux->btf_var.btf_id = type; 17651 } else if (!btf_type_is_struct(t)) { 17652 const struct btf_type *ret; 17653 const char *tname; 17654 u32 tsize; 17655 17656 /* resolve the type size of ksym. */ 17657 ret = btf_resolve_size(btf, t, &tsize); 17658 if (IS_ERR(ret)) { 17659 tname = btf_name_by_offset(btf, t->name_off); 17660 verbose(env, "ldimm64 unable to resolve the size of type '%s': %ld\n", 17661 tname, PTR_ERR(ret)); 17662 err = -EINVAL; 17663 goto err_put; 17664 } 17665 aux->btf_var.reg_type = PTR_TO_MEM | MEM_RDONLY; 17666 aux->btf_var.mem_size = tsize; 17667 } else { 17668 aux->btf_var.reg_type = PTR_TO_BTF_ID; 17669 aux->btf_var.btf = btf; 17670 aux->btf_var.btf_id = type; 17671 } 17672 check_btf: 17673 /* check whether we recorded this BTF (and maybe module) already */ 17674 for (i = 0; i < env->used_btf_cnt; i++) { 17675 if (env->used_btfs[i].btf == btf) { 17676 btf_put(btf); 17677 return 0; 17678 } 17679 } 17680 17681 if (env->used_btf_cnt >= MAX_USED_BTFS) { 17682 err = -E2BIG; 17683 goto err_put; 17684 } 17685 17686 btf_mod = &env->used_btfs[env->used_btf_cnt]; 17687 btf_mod->btf = btf; 17688 btf_mod->module = NULL; 17689 17690 /* if we reference variables from kernel module, bump its refcount */ 17691 if (btf_is_module(btf)) { 17692 btf_mod->module = btf_try_get_module(btf); 17693 if (!btf_mod->module) { 17694 err = -ENXIO; 17695 goto err_put; 17696 } 17697 } 17698 17699 env->used_btf_cnt++; 17700 17701 return 0; 17702 err_put: 17703 btf_put(btf); 17704 return err; 17705 } 17706 17707 static bool is_tracing_prog_type(enum bpf_prog_type type) 17708 { 17709 switch (type) { 17710 case BPF_PROG_TYPE_KPROBE: 17711 case BPF_PROG_TYPE_TRACEPOINT: 17712 case BPF_PROG_TYPE_PERF_EVENT: 17713 case BPF_PROG_TYPE_RAW_TRACEPOINT: 17714 case BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE: 17715 return true; 17716 default: 17717 return false; 17718 } 17719 } 17720 17721 static int check_map_prog_compatibility(struct bpf_verifier_env *env, 17722 struct bpf_map *map, 17723 struct bpf_prog *prog) 17724 17725 { 17726 enum bpf_prog_type prog_type = resolve_prog_type(prog); 17727 17728 if (btf_record_has_field(map->record, BPF_LIST_HEAD) || 17729 btf_record_has_field(map->record, BPF_RB_ROOT)) { 17730 if (is_tracing_prog_type(prog_type)) { 17731 verbose(env, "tracing progs cannot use bpf_{list_head,rb_root} yet\n"); 17732 return -EINVAL; 17733 } 17734 } 17735 17736 if (btf_record_has_field(map->record, BPF_SPIN_LOCK)) { 17737 if (prog_type == BPF_PROG_TYPE_SOCKET_FILTER) { 17738 verbose(env, "socket filter progs cannot use bpf_spin_lock yet\n"); 17739 return -EINVAL; 17740 } 17741 17742 if (is_tracing_prog_type(prog_type)) { 17743 verbose(env, "tracing progs cannot use bpf_spin_lock yet\n"); 17744 return -EINVAL; 17745 } 17746 } 17747 17748 if (btf_record_has_field(map->record, BPF_TIMER)) { 17749 if (is_tracing_prog_type(prog_type)) { 17750 verbose(env, "tracing progs cannot use bpf_timer yet\n"); 17751 return -EINVAL; 17752 } 17753 } 17754 17755 if ((bpf_prog_is_offloaded(prog->aux) || bpf_map_is_offloaded(map)) && 17756 !bpf_offload_prog_map_match(prog, map)) { 17757 verbose(env, "offload device mismatch between prog and map\n"); 17758 return -EINVAL; 17759 } 17760 17761 if (map->map_type == BPF_MAP_TYPE_STRUCT_OPS) { 17762 verbose(env, "bpf_struct_ops map cannot be used in prog\n"); 17763 return -EINVAL; 17764 } 17765 17766 if (prog->aux->sleepable) 17767 switch (map->map_type) { 17768 case BPF_MAP_TYPE_HASH: 17769 case BPF_MAP_TYPE_LRU_HASH: 17770 case BPF_MAP_TYPE_ARRAY: 17771 case BPF_MAP_TYPE_PERCPU_HASH: 17772 case BPF_MAP_TYPE_PERCPU_ARRAY: 17773 case BPF_MAP_TYPE_LRU_PERCPU_HASH: 17774 case BPF_MAP_TYPE_ARRAY_OF_MAPS: 17775 case BPF_MAP_TYPE_HASH_OF_MAPS: 17776 case BPF_MAP_TYPE_RINGBUF: 17777 case BPF_MAP_TYPE_USER_RINGBUF: 17778 case BPF_MAP_TYPE_INODE_STORAGE: 17779 case BPF_MAP_TYPE_SK_STORAGE: 17780 case BPF_MAP_TYPE_TASK_STORAGE: 17781 case BPF_MAP_TYPE_CGRP_STORAGE: 17782 break; 17783 default: 17784 verbose(env, 17785 "Sleepable programs can only use array, hash, ringbuf and local storage maps\n"); 17786 return -EINVAL; 17787 } 17788 17789 return 0; 17790 } 17791 17792 static bool bpf_map_is_cgroup_storage(struct bpf_map *map) 17793 { 17794 return (map->map_type == BPF_MAP_TYPE_CGROUP_STORAGE || 17795 map->map_type == BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE); 17796 } 17797 17798 /* find and rewrite pseudo imm in ld_imm64 instructions: 17799 * 17800 * 1. if it accesses map FD, replace it with actual map pointer. 17801 * 2. if it accesses btf_id of a VAR, replace it with pointer to the var. 17802 * 17803 * NOTE: btf_vmlinux is required for converting pseudo btf_id. 17804 */ 17805 static int resolve_pseudo_ldimm64(struct bpf_verifier_env *env) 17806 { 17807 struct bpf_insn *insn = env->prog->insnsi; 17808 int insn_cnt = env->prog->len; 17809 int i, j, err; 17810 17811 err = bpf_prog_calc_tag(env->prog); 17812 if (err) 17813 return err; 17814 17815 for (i = 0; i < insn_cnt; i++, insn++) { 17816 if (BPF_CLASS(insn->code) == BPF_LDX && 17817 ((BPF_MODE(insn->code) != BPF_MEM && BPF_MODE(insn->code) != BPF_MEMSX) || 17818 insn->imm != 0)) { 17819 verbose(env, "BPF_LDX uses reserved fields\n"); 17820 return -EINVAL; 17821 } 17822 17823 if (insn[0].code == (BPF_LD | BPF_IMM | BPF_DW)) { 17824 struct bpf_insn_aux_data *aux; 17825 struct bpf_map *map; 17826 struct fd f; 17827 u64 addr; 17828 u32 fd; 17829 17830 if (i == insn_cnt - 1 || insn[1].code != 0 || 17831 insn[1].dst_reg != 0 || insn[1].src_reg != 0 || 17832 insn[1].off != 0) { 17833 verbose(env, "invalid bpf_ld_imm64 insn\n"); 17834 return -EINVAL; 17835 } 17836 17837 if (insn[0].src_reg == 0) 17838 /* valid generic load 64-bit imm */ 17839 goto next_insn; 17840 17841 if (insn[0].src_reg == BPF_PSEUDO_BTF_ID) { 17842 aux = &env->insn_aux_data[i]; 17843 err = check_pseudo_btf_id(env, insn, aux); 17844 if (err) 17845 return err; 17846 goto next_insn; 17847 } 17848 17849 if (insn[0].src_reg == BPF_PSEUDO_FUNC) { 17850 aux = &env->insn_aux_data[i]; 17851 aux->ptr_type = PTR_TO_FUNC; 17852 goto next_insn; 17853 } 17854 17855 /* In final convert_pseudo_ld_imm64() step, this is 17856 * converted into regular 64-bit imm load insn. 17857 */ 17858 switch (insn[0].src_reg) { 17859 case BPF_PSEUDO_MAP_VALUE: 17860 case BPF_PSEUDO_MAP_IDX_VALUE: 17861 break; 17862 case BPF_PSEUDO_MAP_FD: 17863 case BPF_PSEUDO_MAP_IDX: 17864 if (insn[1].imm == 0) 17865 break; 17866 fallthrough; 17867 default: 17868 verbose(env, "unrecognized bpf_ld_imm64 insn\n"); 17869 return -EINVAL; 17870 } 17871 17872 switch (insn[0].src_reg) { 17873 case BPF_PSEUDO_MAP_IDX_VALUE: 17874 case BPF_PSEUDO_MAP_IDX: 17875 if (bpfptr_is_null(env->fd_array)) { 17876 verbose(env, "fd_idx without fd_array is invalid\n"); 17877 return -EPROTO; 17878 } 17879 if (copy_from_bpfptr_offset(&fd, env->fd_array, 17880 insn[0].imm * sizeof(fd), 17881 sizeof(fd))) 17882 return -EFAULT; 17883 break; 17884 default: 17885 fd = insn[0].imm; 17886 break; 17887 } 17888 17889 f = fdget(fd); 17890 map = __bpf_map_get(f); 17891 if (IS_ERR(map)) { 17892 verbose(env, "fd %d is not pointing to valid bpf_map\n", 17893 insn[0].imm); 17894 return PTR_ERR(map); 17895 } 17896 17897 err = check_map_prog_compatibility(env, map, env->prog); 17898 if (err) { 17899 fdput(f); 17900 return err; 17901 } 17902 17903 aux = &env->insn_aux_data[i]; 17904 if (insn[0].src_reg == BPF_PSEUDO_MAP_FD || 17905 insn[0].src_reg == BPF_PSEUDO_MAP_IDX) { 17906 addr = (unsigned long)map; 17907 } else { 17908 u32 off = insn[1].imm; 17909 17910 if (off >= BPF_MAX_VAR_OFF) { 17911 verbose(env, "direct value offset of %u is not allowed\n", off); 17912 fdput(f); 17913 return -EINVAL; 17914 } 17915 17916 if (!map->ops->map_direct_value_addr) { 17917 verbose(env, "no direct value access support for this map type\n"); 17918 fdput(f); 17919 return -EINVAL; 17920 } 17921 17922 err = map->ops->map_direct_value_addr(map, &addr, off); 17923 if (err) { 17924 verbose(env, "invalid access to map value pointer, value_size=%u off=%u\n", 17925 map->value_size, off); 17926 fdput(f); 17927 return err; 17928 } 17929 17930 aux->map_off = off; 17931 addr += off; 17932 } 17933 17934 insn[0].imm = (u32)addr; 17935 insn[1].imm = addr >> 32; 17936 17937 /* check whether we recorded this map already */ 17938 for (j = 0; j < env->used_map_cnt; j++) { 17939 if (env->used_maps[j] == map) { 17940 aux->map_index = j; 17941 fdput(f); 17942 goto next_insn; 17943 } 17944 } 17945 17946 if (env->used_map_cnt >= MAX_USED_MAPS) { 17947 fdput(f); 17948 return -E2BIG; 17949 } 17950 17951 if (env->prog->aux->sleepable) 17952 atomic64_inc(&map->sleepable_refcnt); 17953 /* hold the map. If the program is rejected by verifier, 17954 * the map will be released by release_maps() or it 17955 * will be used by the valid program until it's unloaded 17956 * and all maps are released in bpf_free_used_maps() 17957 */ 17958 bpf_map_inc(map); 17959 17960 aux->map_index = env->used_map_cnt; 17961 env->used_maps[env->used_map_cnt++] = map; 17962 17963 if (bpf_map_is_cgroup_storage(map) && 17964 bpf_cgroup_storage_assign(env->prog->aux, map)) { 17965 verbose(env, "only one cgroup storage of each type is allowed\n"); 17966 fdput(f); 17967 return -EBUSY; 17968 } 17969 17970 fdput(f); 17971 next_insn: 17972 insn++; 17973 i++; 17974 continue; 17975 } 17976 17977 /* Basic sanity check before we invest more work here. */ 17978 if (!bpf_opcode_in_insntable(insn->code)) { 17979 verbose(env, "unknown opcode %02x\n", insn->code); 17980 return -EINVAL; 17981 } 17982 } 17983 17984 /* now all pseudo BPF_LD_IMM64 instructions load valid 17985 * 'struct bpf_map *' into a register instead of user map_fd. 17986 * These pointers will be used later by verifier to validate map access. 17987 */ 17988 return 0; 17989 } 17990 17991 /* drop refcnt of maps used by the rejected program */ 17992 static void release_maps(struct bpf_verifier_env *env) 17993 { 17994 __bpf_free_used_maps(env->prog->aux, env->used_maps, 17995 env->used_map_cnt); 17996 } 17997 17998 /* drop refcnt of maps used by the rejected program */ 17999 static void release_btfs(struct bpf_verifier_env *env) 18000 { 18001 __bpf_free_used_btfs(env->prog->aux, env->used_btfs, 18002 env->used_btf_cnt); 18003 } 18004 18005 /* convert pseudo BPF_LD_IMM64 into generic BPF_LD_IMM64 */ 18006 static void convert_pseudo_ld_imm64(struct bpf_verifier_env *env) 18007 { 18008 struct bpf_insn *insn = env->prog->insnsi; 18009 int insn_cnt = env->prog->len; 18010 int i; 18011 18012 for (i = 0; i < insn_cnt; i++, insn++) { 18013 if (insn->code != (BPF_LD | BPF_IMM | BPF_DW)) 18014 continue; 18015 if (insn->src_reg == BPF_PSEUDO_FUNC) 18016 continue; 18017 insn->src_reg = 0; 18018 } 18019 } 18020 18021 /* single env->prog->insni[off] instruction was replaced with the range 18022 * insni[off, off + cnt). Adjust corresponding insn_aux_data by copying 18023 * [0, off) and [off, end) to new locations, so the patched range stays zero 18024 */ 18025 static void adjust_insn_aux_data(struct bpf_verifier_env *env, 18026 struct bpf_insn_aux_data *new_data, 18027 struct bpf_prog *new_prog, u32 off, u32 cnt) 18028 { 18029 struct bpf_insn_aux_data *old_data = env->insn_aux_data; 18030 struct bpf_insn *insn = new_prog->insnsi; 18031 u32 old_seen = old_data[off].seen; 18032 u32 prog_len; 18033 int i; 18034 18035 /* aux info at OFF always needs adjustment, no matter fast path 18036 * (cnt == 1) is taken or not. There is no guarantee INSN at OFF is the 18037 * original insn at old prog. 18038 */ 18039 old_data[off].zext_dst = insn_has_def32(env, insn + off + cnt - 1); 18040 18041 if (cnt == 1) 18042 return; 18043 prog_len = new_prog->len; 18044 18045 memcpy(new_data, old_data, sizeof(struct bpf_insn_aux_data) * off); 18046 memcpy(new_data + off + cnt - 1, old_data + off, 18047 sizeof(struct bpf_insn_aux_data) * (prog_len - off - cnt + 1)); 18048 for (i = off; i < off + cnt - 1; i++) { 18049 /* Expand insni[off]'s seen count to the patched range. */ 18050 new_data[i].seen = old_seen; 18051 new_data[i].zext_dst = insn_has_def32(env, insn + i); 18052 } 18053 env->insn_aux_data = new_data; 18054 vfree(old_data); 18055 } 18056 18057 static void adjust_subprog_starts(struct bpf_verifier_env *env, u32 off, u32 len) 18058 { 18059 int i; 18060 18061 if (len == 1) 18062 return; 18063 /* NOTE: fake 'exit' subprog should be updated as well. */ 18064 for (i = 0; i <= env->subprog_cnt; i++) { 18065 if (env->subprog_info[i].start <= off) 18066 continue; 18067 env->subprog_info[i].start += len - 1; 18068 } 18069 } 18070 18071 static void adjust_poke_descs(struct bpf_prog *prog, u32 off, u32 len) 18072 { 18073 struct bpf_jit_poke_descriptor *tab = prog->aux->poke_tab; 18074 int i, sz = prog->aux->size_poke_tab; 18075 struct bpf_jit_poke_descriptor *desc; 18076 18077 for (i = 0; i < sz; i++) { 18078 desc = &tab[i]; 18079 if (desc->insn_idx <= off) 18080 continue; 18081 desc->insn_idx += len - 1; 18082 } 18083 } 18084 18085 static struct bpf_prog *bpf_patch_insn_data(struct bpf_verifier_env *env, u32 off, 18086 const struct bpf_insn *patch, u32 len) 18087 { 18088 struct bpf_prog *new_prog; 18089 struct bpf_insn_aux_data *new_data = NULL; 18090 18091 if (len > 1) { 18092 new_data = vzalloc(array_size(env->prog->len + len - 1, 18093 sizeof(struct bpf_insn_aux_data))); 18094 if (!new_data) 18095 return NULL; 18096 } 18097 18098 new_prog = bpf_patch_insn_single(env->prog, off, patch, len); 18099 if (IS_ERR(new_prog)) { 18100 if (PTR_ERR(new_prog) == -ERANGE) 18101 verbose(env, 18102 "insn %d cannot be patched due to 16-bit range\n", 18103 env->insn_aux_data[off].orig_idx); 18104 vfree(new_data); 18105 return NULL; 18106 } 18107 adjust_insn_aux_data(env, new_data, new_prog, off, len); 18108 adjust_subprog_starts(env, off, len); 18109 adjust_poke_descs(new_prog, off, len); 18110 return new_prog; 18111 } 18112 18113 static int adjust_subprog_starts_after_remove(struct bpf_verifier_env *env, 18114 u32 off, u32 cnt) 18115 { 18116 int i, j; 18117 18118 /* find first prog starting at or after off (first to remove) */ 18119 for (i = 0; i < env->subprog_cnt; i++) 18120 if (env->subprog_info[i].start >= off) 18121 break; 18122 /* find first prog starting at or after off + cnt (first to stay) */ 18123 for (j = i; j < env->subprog_cnt; j++) 18124 if (env->subprog_info[j].start >= off + cnt) 18125 break; 18126 /* if j doesn't start exactly at off + cnt, we are just removing 18127 * the front of previous prog 18128 */ 18129 if (env->subprog_info[j].start != off + cnt) 18130 j--; 18131 18132 if (j > i) { 18133 struct bpf_prog_aux *aux = env->prog->aux; 18134 int move; 18135 18136 /* move fake 'exit' subprog as well */ 18137 move = env->subprog_cnt + 1 - j; 18138 18139 memmove(env->subprog_info + i, 18140 env->subprog_info + j, 18141 sizeof(*env->subprog_info) * move); 18142 env->subprog_cnt -= j - i; 18143 18144 /* remove func_info */ 18145 if (aux->func_info) { 18146 move = aux->func_info_cnt - j; 18147 18148 memmove(aux->func_info + i, 18149 aux->func_info + j, 18150 sizeof(*aux->func_info) * move); 18151 aux->func_info_cnt -= j - i; 18152 /* func_info->insn_off is set after all code rewrites, 18153 * in adjust_btf_func() - no need to adjust 18154 */ 18155 } 18156 } else { 18157 /* convert i from "first prog to remove" to "first to adjust" */ 18158 if (env->subprog_info[i].start == off) 18159 i++; 18160 } 18161 18162 /* update fake 'exit' subprog as well */ 18163 for (; i <= env->subprog_cnt; i++) 18164 env->subprog_info[i].start -= cnt; 18165 18166 return 0; 18167 } 18168 18169 static int bpf_adj_linfo_after_remove(struct bpf_verifier_env *env, u32 off, 18170 u32 cnt) 18171 { 18172 struct bpf_prog *prog = env->prog; 18173 u32 i, l_off, l_cnt, nr_linfo; 18174 struct bpf_line_info *linfo; 18175 18176 nr_linfo = prog->aux->nr_linfo; 18177 if (!nr_linfo) 18178 return 0; 18179 18180 linfo = prog->aux->linfo; 18181 18182 /* find first line info to remove, count lines to be removed */ 18183 for (i = 0; i < nr_linfo; i++) 18184 if (linfo[i].insn_off >= off) 18185 break; 18186 18187 l_off = i; 18188 l_cnt = 0; 18189 for (; i < nr_linfo; i++) 18190 if (linfo[i].insn_off < off + cnt) 18191 l_cnt++; 18192 else 18193 break; 18194 18195 /* First live insn doesn't match first live linfo, it needs to "inherit" 18196 * last removed linfo. prog is already modified, so prog->len == off 18197 * means no live instructions after (tail of the program was removed). 18198 */ 18199 if (prog->len != off && l_cnt && 18200 (i == nr_linfo || linfo[i].insn_off != off + cnt)) { 18201 l_cnt--; 18202 linfo[--i].insn_off = off + cnt; 18203 } 18204 18205 /* remove the line info which refer to the removed instructions */ 18206 if (l_cnt) { 18207 memmove(linfo + l_off, linfo + i, 18208 sizeof(*linfo) * (nr_linfo - i)); 18209 18210 prog->aux->nr_linfo -= l_cnt; 18211 nr_linfo = prog->aux->nr_linfo; 18212 } 18213 18214 /* pull all linfo[i].insn_off >= off + cnt in by cnt */ 18215 for (i = l_off; i < nr_linfo; i++) 18216 linfo[i].insn_off -= cnt; 18217 18218 /* fix up all subprogs (incl. 'exit') which start >= off */ 18219 for (i = 0; i <= env->subprog_cnt; i++) 18220 if (env->subprog_info[i].linfo_idx > l_off) { 18221 /* program may have started in the removed region but 18222 * may not be fully removed 18223 */ 18224 if (env->subprog_info[i].linfo_idx >= l_off + l_cnt) 18225 env->subprog_info[i].linfo_idx -= l_cnt; 18226 else 18227 env->subprog_info[i].linfo_idx = l_off; 18228 } 18229 18230 return 0; 18231 } 18232 18233 static int verifier_remove_insns(struct bpf_verifier_env *env, u32 off, u32 cnt) 18234 { 18235 struct bpf_insn_aux_data *aux_data = env->insn_aux_data; 18236 unsigned int orig_prog_len = env->prog->len; 18237 int err; 18238 18239 if (bpf_prog_is_offloaded(env->prog->aux)) 18240 bpf_prog_offload_remove_insns(env, off, cnt); 18241 18242 err = bpf_remove_insns(env->prog, off, cnt); 18243 if (err) 18244 return err; 18245 18246 err = adjust_subprog_starts_after_remove(env, off, cnt); 18247 if (err) 18248 return err; 18249 18250 err = bpf_adj_linfo_after_remove(env, off, cnt); 18251 if (err) 18252 return err; 18253 18254 memmove(aux_data + off, aux_data + off + cnt, 18255 sizeof(*aux_data) * (orig_prog_len - off - cnt)); 18256 18257 return 0; 18258 } 18259 18260 /* The verifier does more data flow analysis than llvm and will not 18261 * explore branches that are dead at run time. Malicious programs can 18262 * have dead code too. Therefore replace all dead at-run-time code 18263 * with 'ja -1'. 18264 * 18265 * Just nops are not optimal, e.g. if they would sit at the end of the 18266 * program and through another bug we would manage to jump there, then 18267 * we'd execute beyond program memory otherwise. Returning exception 18268 * code also wouldn't work since we can have subprogs where the dead 18269 * code could be located. 18270 */ 18271 static void sanitize_dead_code(struct bpf_verifier_env *env) 18272 { 18273 struct bpf_insn_aux_data *aux_data = env->insn_aux_data; 18274 struct bpf_insn trap = BPF_JMP_IMM(BPF_JA, 0, 0, -1); 18275 struct bpf_insn *insn = env->prog->insnsi; 18276 const int insn_cnt = env->prog->len; 18277 int i; 18278 18279 for (i = 0; i < insn_cnt; i++) { 18280 if (aux_data[i].seen) 18281 continue; 18282 memcpy(insn + i, &trap, sizeof(trap)); 18283 aux_data[i].zext_dst = false; 18284 } 18285 } 18286 18287 static bool insn_is_cond_jump(u8 code) 18288 { 18289 u8 op; 18290 18291 op = BPF_OP(code); 18292 if (BPF_CLASS(code) == BPF_JMP32) 18293 return op != BPF_JA; 18294 18295 if (BPF_CLASS(code) != BPF_JMP) 18296 return false; 18297 18298 return op != BPF_JA && op != BPF_EXIT && op != BPF_CALL; 18299 } 18300 18301 static void opt_hard_wire_dead_code_branches(struct bpf_verifier_env *env) 18302 { 18303 struct bpf_insn_aux_data *aux_data = env->insn_aux_data; 18304 struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0); 18305 struct bpf_insn *insn = env->prog->insnsi; 18306 const int insn_cnt = env->prog->len; 18307 int i; 18308 18309 for (i = 0; i < insn_cnt; i++, insn++) { 18310 if (!insn_is_cond_jump(insn->code)) 18311 continue; 18312 18313 if (!aux_data[i + 1].seen) 18314 ja.off = insn->off; 18315 else if (!aux_data[i + 1 + insn->off].seen) 18316 ja.off = 0; 18317 else 18318 continue; 18319 18320 if (bpf_prog_is_offloaded(env->prog->aux)) 18321 bpf_prog_offload_replace_insn(env, i, &ja); 18322 18323 memcpy(insn, &ja, sizeof(ja)); 18324 } 18325 } 18326 18327 static int opt_remove_dead_code(struct bpf_verifier_env *env) 18328 { 18329 struct bpf_insn_aux_data *aux_data = env->insn_aux_data; 18330 int insn_cnt = env->prog->len; 18331 int i, err; 18332 18333 for (i = 0; i < insn_cnt; i++) { 18334 int j; 18335 18336 j = 0; 18337 while (i + j < insn_cnt && !aux_data[i + j].seen) 18338 j++; 18339 if (!j) 18340 continue; 18341 18342 err = verifier_remove_insns(env, i, j); 18343 if (err) 18344 return err; 18345 insn_cnt = env->prog->len; 18346 } 18347 18348 return 0; 18349 } 18350 18351 static int opt_remove_nops(struct bpf_verifier_env *env) 18352 { 18353 const struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0); 18354 struct bpf_insn *insn = env->prog->insnsi; 18355 int insn_cnt = env->prog->len; 18356 int i, err; 18357 18358 for (i = 0; i < insn_cnt; i++) { 18359 if (memcmp(&insn[i], &ja, sizeof(ja))) 18360 continue; 18361 18362 err = verifier_remove_insns(env, i, 1); 18363 if (err) 18364 return err; 18365 insn_cnt--; 18366 i--; 18367 } 18368 18369 return 0; 18370 } 18371 18372 static int opt_subreg_zext_lo32_rnd_hi32(struct bpf_verifier_env *env, 18373 const union bpf_attr *attr) 18374 { 18375 struct bpf_insn *patch, zext_patch[2], rnd_hi32_patch[4]; 18376 struct bpf_insn_aux_data *aux = env->insn_aux_data; 18377 int i, patch_len, delta = 0, len = env->prog->len; 18378 struct bpf_insn *insns = env->prog->insnsi; 18379 struct bpf_prog *new_prog; 18380 bool rnd_hi32; 18381 18382 rnd_hi32 = attr->prog_flags & BPF_F_TEST_RND_HI32; 18383 zext_patch[1] = BPF_ZEXT_REG(0); 18384 rnd_hi32_patch[1] = BPF_ALU64_IMM(BPF_MOV, BPF_REG_AX, 0); 18385 rnd_hi32_patch[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_AX, 32); 18386 rnd_hi32_patch[3] = BPF_ALU64_REG(BPF_OR, 0, BPF_REG_AX); 18387 for (i = 0; i < len; i++) { 18388 int adj_idx = i + delta; 18389 struct bpf_insn insn; 18390 int load_reg; 18391 18392 insn = insns[adj_idx]; 18393 load_reg = insn_def_regno(&insn); 18394 if (!aux[adj_idx].zext_dst) { 18395 u8 code, class; 18396 u32 imm_rnd; 18397 18398 if (!rnd_hi32) 18399 continue; 18400 18401 code = insn.code; 18402 class = BPF_CLASS(code); 18403 if (load_reg == -1) 18404 continue; 18405 18406 /* NOTE: arg "reg" (the fourth one) is only used for 18407 * BPF_STX + SRC_OP, so it is safe to pass NULL 18408 * here. 18409 */ 18410 if (is_reg64(env, &insn, load_reg, NULL, DST_OP)) { 18411 if (class == BPF_LD && 18412 BPF_MODE(code) == BPF_IMM) 18413 i++; 18414 continue; 18415 } 18416 18417 /* ctx load could be transformed into wider load. */ 18418 if (class == BPF_LDX && 18419 aux[adj_idx].ptr_type == PTR_TO_CTX) 18420 continue; 18421 18422 imm_rnd = get_random_u32(); 18423 rnd_hi32_patch[0] = insn; 18424 rnd_hi32_patch[1].imm = imm_rnd; 18425 rnd_hi32_patch[3].dst_reg = load_reg; 18426 patch = rnd_hi32_patch; 18427 patch_len = 4; 18428 goto apply_patch_buffer; 18429 } 18430 18431 /* Add in an zero-extend instruction if a) the JIT has requested 18432 * it or b) it's a CMPXCHG. 18433 * 18434 * The latter is because: BPF_CMPXCHG always loads a value into 18435 * R0, therefore always zero-extends. However some archs' 18436 * equivalent instruction only does this load when the 18437 * comparison is successful. This detail of CMPXCHG is 18438 * orthogonal to the general zero-extension behaviour of the 18439 * CPU, so it's treated independently of bpf_jit_needs_zext. 18440 */ 18441 if (!bpf_jit_needs_zext() && !is_cmpxchg_insn(&insn)) 18442 continue; 18443 18444 /* Zero-extension is done by the caller. */ 18445 if (bpf_pseudo_kfunc_call(&insn)) 18446 continue; 18447 18448 if (WARN_ON(load_reg == -1)) { 18449 verbose(env, "verifier bug. zext_dst is set, but no reg is defined\n"); 18450 return -EFAULT; 18451 } 18452 18453 zext_patch[0] = insn; 18454 zext_patch[1].dst_reg = load_reg; 18455 zext_patch[1].src_reg = load_reg; 18456 patch = zext_patch; 18457 patch_len = 2; 18458 apply_patch_buffer: 18459 new_prog = bpf_patch_insn_data(env, adj_idx, patch, patch_len); 18460 if (!new_prog) 18461 return -ENOMEM; 18462 env->prog = new_prog; 18463 insns = new_prog->insnsi; 18464 aux = env->insn_aux_data; 18465 delta += patch_len - 1; 18466 } 18467 18468 return 0; 18469 } 18470 18471 /* convert load instructions that access fields of a context type into a 18472 * sequence of instructions that access fields of the underlying structure: 18473 * struct __sk_buff -> struct sk_buff 18474 * struct bpf_sock_ops -> struct sock 18475 */ 18476 static int convert_ctx_accesses(struct bpf_verifier_env *env) 18477 { 18478 const struct bpf_verifier_ops *ops = env->ops; 18479 int i, cnt, size, ctx_field_size, delta = 0; 18480 const int insn_cnt = env->prog->len; 18481 struct bpf_insn insn_buf[16], *insn; 18482 u32 target_size, size_default, off; 18483 struct bpf_prog *new_prog; 18484 enum bpf_access_type type; 18485 bool is_narrower_load; 18486 18487 if (ops->gen_prologue || env->seen_direct_write) { 18488 if (!ops->gen_prologue) { 18489 verbose(env, "bpf verifier is misconfigured\n"); 18490 return -EINVAL; 18491 } 18492 cnt = ops->gen_prologue(insn_buf, env->seen_direct_write, 18493 env->prog); 18494 if (cnt >= ARRAY_SIZE(insn_buf)) { 18495 verbose(env, "bpf verifier is misconfigured\n"); 18496 return -EINVAL; 18497 } else if (cnt) { 18498 new_prog = bpf_patch_insn_data(env, 0, insn_buf, cnt); 18499 if (!new_prog) 18500 return -ENOMEM; 18501 18502 env->prog = new_prog; 18503 delta += cnt - 1; 18504 } 18505 } 18506 18507 if (bpf_prog_is_offloaded(env->prog->aux)) 18508 return 0; 18509 18510 insn = env->prog->insnsi + delta; 18511 18512 for (i = 0; i < insn_cnt; i++, insn++) { 18513 bpf_convert_ctx_access_t convert_ctx_access; 18514 u8 mode; 18515 18516 if (insn->code == (BPF_LDX | BPF_MEM | BPF_B) || 18517 insn->code == (BPF_LDX | BPF_MEM | BPF_H) || 18518 insn->code == (BPF_LDX | BPF_MEM | BPF_W) || 18519 insn->code == (BPF_LDX | BPF_MEM | BPF_DW) || 18520 insn->code == (BPF_LDX | BPF_MEMSX | BPF_B) || 18521 insn->code == (BPF_LDX | BPF_MEMSX | BPF_H) || 18522 insn->code == (BPF_LDX | BPF_MEMSX | BPF_W)) { 18523 type = BPF_READ; 18524 } else if (insn->code == (BPF_STX | BPF_MEM | BPF_B) || 18525 insn->code == (BPF_STX | BPF_MEM | BPF_H) || 18526 insn->code == (BPF_STX | BPF_MEM | BPF_W) || 18527 insn->code == (BPF_STX | BPF_MEM | BPF_DW) || 18528 insn->code == (BPF_ST | BPF_MEM | BPF_B) || 18529 insn->code == (BPF_ST | BPF_MEM | BPF_H) || 18530 insn->code == (BPF_ST | BPF_MEM | BPF_W) || 18531 insn->code == (BPF_ST | BPF_MEM | BPF_DW)) { 18532 type = BPF_WRITE; 18533 } else { 18534 continue; 18535 } 18536 18537 if (type == BPF_WRITE && 18538 env->insn_aux_data[i + delta].sanitize_stack_spill) { 18539 struct bpf_insn patch[] = { 18540 *insn, 18541 BPF_ST_NOSPEC(), 18542 }; 18543 18544 cnt = ARRAY_SIZE(patch); 18545 new_prog = bpf_patch_insn_data(env, i + delta, patch, cnt); 18546 if (!new_prog) 18547 return -ENOMEM; 18548 18549 delta += cnt - 1; 18550 env->prog = new_prog; 18551 insn = new_prog->insnsi + i + delta; 18552 continue; 18553 } 18554 18555 switch ((int)env->insn_aux_data[i + delta].ptr_type) { 18556 case PTR_TO_CTX: 18557 if (!ops->convert_ctx_access) 18558 continue; 18559 convert_ctx_access = ops->convert_ctx_access; 18560 break; 18561 case PTR_TO_SOCKET: 18562 case PTR_TO_SOCK_COMMON: 18563 convert_ctx_access = bpf_sock_convert_ctx_access; 18564 break; 18565 case PTR_TO_TCP_SOCK: 18566 convert_ctx_access = bpf_tcp_sock_convert_ctx_access; 18567 break; 18568 case PTR_TO_XDP_SOCK: 18569 convert_ctx_access = bpf_xdp_sock_convert_ctx_access; 18570 break; 18571 case PTR_TO_BTF_ID: 18572 case PTR_TO_BTF_ID | PTR_UNTRUSTED: 18573 /* PTR_TO_BTF_ID | MEM_ALLOC always has a valid lifetime, unlike 18574 * PTR_TO_BTF_ID, and an active ref_obj_id, but the same cannot 18575 * be said once it is marked PTR_UNTRUSTED, hence we must handle 18576 * any faults for loads into such types. BPF_WRITE is disallowed 18577 * for this case. 18578 */ 18579 case PTR_TO_BTF_ID | MEM_ALLOC | PTR_UNTRUSTED: 18580 if (type == BPF_READ) { 18581 if (BPF_MODE(insn->code) == BPF_MEM) 18582 insn->code = BPF_LDX | BPF_PROBE_MEM | 18583 BPF_SIZE((insn)->code); 18584 else 18585 insn->code = BPF_LDX | BPF_PROBE_MEMSX | 18586 BPF_SIZE((insn)->code); 18587 env->prog->aux->num_exentries++; 18588 } 18589 continue; 18590 default: 18591 continue; 18592 } 18593 18594 ctx_field_size = env->insn_aux_data[i + delta].ctx_field_size; 18595 size = BPF_LDST_BYTES(insn); 18596 mode = BPF_MODE(insn->code); 18597 18598 /* If the read access is a narrower load of the field, 18599 * convert to a 4/8-byte load, to minimum program type specific 18600 * convert_ctx_access changes. If conversion is successful, 18601 * we will apply proper mask to the result. 18602 */ 18603 is_narrower_load = size < ctx_field_size; 18604 size_default = bpf_ctx_off_adjust_machine(ctx_field_size); 18605 off = insn->off; 18606 if (is_narrower_load) { 18607 u8 size_code; 18608 18609 if (type == BPF_WRITE) { 18610 verbose(env, "bpf verifier narrow ctx access misconfigured\n"); 18611 return -EINVAL; 18612 } 18613 18614 size_code = BPF_H; 18615 if (ctx_field_size == 4) 18616 size_code = BPF_W; 18617 else if (ctx_field_size == 8) 18618 size_code = BPF_DW; 18619 18620 insn->off = off & ~(size_default - 1); 18621 insn->code = BPF_LDX | BPF_MEM | size_code; 18622 } 18623 18624 target_size = 0; 18625 cnt = convert_ctx_access(type, insn, insn_buf, env->prog, 18626 &target_size); 18627 if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf) || 18628 (ctx_field_size && !target_size)) { 18629 verbose(env, "bpf verifier is misconfigured\n"); 18630 return -EINVAL; 18631 } 18632 18633 if (is_narrower_load && size < target_size) { 18634 u8 shift = bpf_ctx_narrow_access_offset( 18635 off, size, size_default) * 8; 18636 if (shift && cnt + 1 >= ARRAY_SIZE(insn_buf)) { 18637 verbose(env, "bpf verifier narrow ctx load misconfigured\n"); 18638 return -EINVAL; 18639 } 18640 if (ctx_field_size <= 4) { 18641 if (shift) 18642 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_RSH, 18643 insn->dst_reg, 18644 shift); 18645 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg, 18646 (1 << size * 8) - 1); 18647 } else { 18648 if (shift) 18649 insn_buf[cnt++] = BPF_ALU64_IMM(BPF_RSH, 18650 insn->dst_reg, 18651 shift); 18652 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg, 18653 (1ULL << size * 8) - 1); 18654 } 18655 } 18656 if (mode == BPF_MEMSX) 18657 insn_buf[cnt++] = BPF_RAW_INSN(BPF_ALU64 | BPF_MOV | BPF_X, 18658 insn->dst_reg, insn->dst_reg, 18659 size * 8, 0); 18660 18661 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 18662 if (!new_prog) 18663 return -ENOMEM; 18664 18665 delta += cnt - 1; 18666 18667 /* keep walking new program and skip insns we just inserted */ 18668 env->prog = new_prog; 18669 insn = new_prog->insnsi + i + delta; 18670 } 18671 18672 return 0; 18673 } 18674 18675 static int jit_subprogs(struct bpf_verifier_env *env) 18676 { 18677 struct bpf_prog *prog = env->prog, **func, *tmp; 18678 int i, j, subprog_start, subprog_end = 0, len, subprog; 18679 struct bpf_map *map_ptr; 18680 struct bpf_insn *insn; 18681 void *old_bpf_func; 18682 int err, num_exentries; 18683 18684 if (env->subprog_cnt <= 1) 18685 return 0; 18686 18687 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) { 18688 if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn)) 18689 continue; 18690 18691 /* Upon error here we cannot fall back to interpreter but 18692 * need a hard reject of the program. Thus -EFAULT is 18693 * propagated in any case. 18694 */ 18695 subprog = find_subprog(env, i + insn->imm + 1); 18696 if (subprog < 0) { 18697 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n", 18698 i + insn->imm + 1); 18699 return -EFAULT; 18700 } 18701 /* temporarily remember subprog id inside insn instead of 18702 * aux_data, since next loop will split up all insns into funcs 18703 */ 18704 insn->off = subprog; 18705 /* remember original imm in case JIT fails and fallback 18706 * to interpreter will be needed 18707 */ 18708 env->insn_aux_data[i].call_imm = insn->imm; 18709 /* point imm to __bpf_call_base+1 from JITs point of view */ 18710 insn->imm = 1; 18711 if (bpf_pseudo_func(insn)) 18712 /* jit (e.g. x86_64) may emit fewer instructions 18713 * if it learns a u32 imm is the same as a u64 imm. 18714 * Force a non zero here. 18715 */ 18716 insn[1].imm = 1; 18717 } 18718 18719 err = bpf_prog_alloc_jited_linfo(prog); 18720 if (err) 18721 goto out_undo_insn; 18722 18723 err = -ENOMEM; 18724 func = kcalloc(env->subprog_cnt, sizeof(prog), GFP_KERNEL); 18725 if (!func) 18726 goto out_undo_insn; 18727 18728 for (i = 0; i < env->subprog_cnt; i++) { 18729 subprog_start = subprog_end; 18730 subprog_end = env->subprog_info[i + 1].start; 18731 18732 len = subprog_end - subprog_start; 18733 /* bpf_prog_run() doesn't call subprogs directly, 18734 * hence main prog stats include the runtime of subprogs. 18735 * subprogs don't have IDs and not reachable via prog_get_next_id 18736 * func[i]->stats will never be accessed and stays NULL 18737 */ 18738 func[i] = bpf_prog_alloc_no_stats(bpf_prog_size(len), GFP_USER); 18739 if (!func[i]) 18740 goto out_free; 18741 memcpy(func[i]->insnsi, &prog->insnsi[subprog_start], 18742 len * sizeof(struct bpf_insn)); 18743 func[i]->type = prog->type; 18744 func[i]->len = len; 18745 if (bpf_prog_calc_tag(func[i])) 18746 goto out_free; 18747 func[i]->is_func = 1; 18748 func[i]->aux->func_idx = i; 18749 /* Below members will be freed only at prog->aux */ 18750 func[i]->aux->btf = prog->aux->btf; 18751 func[i]->aux->func_info = prog->aux->func_info; 18752 func[i]->aux->func_info_cnt = prog->aux->func_info_cnt; 18753 func[i]->aux->poke_tab = prog->aux->poke_tab; 18754 func[i]->aux->size_poke_tab = prog->aux->size_poke_tab; 18755 18756 for (j = 0; j < prog->aux->size_poke_tab; j++) { 18757 struct bpf_jit_poke_descriptor *poke; 18758 18759 poke = &prog->aux->poke_tab[j]; 18760 if (poke->insn_idx < subprog_end && 18761 poke->insn_idx >= subprog_start) 18762 poke->aux = func[i]->aux; 18763 } 18764 18765 func[i]->aux->name[0] = 'F'; 18766 func[i]->aux->stack_depth = env->subprog_info[i].stack_depth; 18767 func[i]->jit_requested = 1; 18768 func[i]->blinding_requested = prog->blinding_requested; 18769 func[i]->aux->kfunc_tab = prog->aux->kfunc_tab; 18770 func[i]->aux->kfunc_btf_tab = prog->aux->kfunc_btf_tab; 18771 func[i]->aux->linfo = prog->aux->linfo; 18772 func[i]->aux->nr_linfo = prog->aux->nr_linfo; 18773 func[i]->aux->jited_linfo = prog->aux->jited_linfo; 18774 func[i]->aux->linfo_idx = env->subprog_info[i].linfo_idx; 18775 num_exentries = 0; 18776 insn = func[i]->insnsi; 18777 for (j = 0; j < func[i]->len; j++, insn++) { 18778 if (BPF_CLASS(insn->code) == BPF_LDX && 18779 (BPF_MODE(insn->code) == BPF_PROBE_MEM || 18780 BPF_MODE(insn->code) == BPF_PROBE_MEMSX)) 18781 num_exentries++; 18782 } 18783 func[i]->aux->num_exentries = num_exentries; 18784 func[i]->aux->tail_call_reachable = env->subprog_info[i].tail_call_reachable; 18785 func[i]->aux->exception_cb = env->subprog_info[i].is_exception_cb; 18786 if (!i) 18787 func[i]->aux->exception_boundary = env->seen_exception; 18788 func[i] = bpf_int_jit_compile(func[i]); 18789 if (!func[i]->jited) { 18790 err = -ENOTSUPP; 18791 goto out_free; 18792 } 18793 cond_resched(); 18794 } 18795 18796 /* at this point all bpf functions were successfully JITed 18797 * now populate all bpf_calls with correct addresses and 18798 * run last pass of JIT 18799 */ 18800 for (i = 0; i < env->subprog_cnt; i++) { 18801 insn = func[i]->insnsi; 18802 for (j = 0; j < func[i]->len; j++, insn++) { 18803 if (bpf_pseudo_func(insn)) { 18804 subprog = insn->off; 18805 insn[0].imm = (u32)(long)func[subprog]->bpf_func; 18806 insn[1].imm = ((u64)(long)func[subprog]->bpf_func) >> 32; 18807 continue; 18808 } 18809 if (!bpf_pseudo_call(insn)) 18810 continue; 18811 subprog = insn->off; 18812 insn->imm = BPF_CALL_IMM(func[subprog]->bpf_func); 18813 } 18814 18815 /* we use the aux data to keep a list of the start addresses 18816 * of the JITed images for each function in the program 18817 * 18818 * for some architectures, such as powerpc64, the imm field 18819 * might not be large enough to hold the offset of the start 18820 * address of the callee's JITed image from __bpf_call_base 18821 * 18822 * in such cases, we can lookup the start address of a callee 18823 * by using its subprog id, available from the off field of 18824 * the call instruction, as an index for this list 18825 */ 18826 func[i]->aux->func = func; 18827 func[i]->aux->func_cnt = env->subprog_cnt - env->hidden_subprog_cnt; 18828 func[i]->aux->real_func_cnt = env->subprog_cnt; 18829 } 18830 for (i = 0; i < env->subprog_cnt; i++) { 18831 old_bpf_func = func[i]->bpf_func; 18832 tmp = bpf_int_jit_compile(func[i]); 18833 if (tmp != func[i] || func[i]->bpf_func != old_bpf_func) { 18834 verbose(env, "JIT doesn't support bpf-to-bpf calls\n"); 18835 err = -ENOTSUPP; 18836 goto out_free; 18837 } 18838 cond_resched(); 18839 } 18840 18841 /* finally lock prog and jit images for all functions and 18842 * populate kallsysm. Begin at the first subprogram, since 18843 * bpf_prog_load will add the kallsyms for the main program. 18844 */ 18845 for (i = 1; i < env->subprog_cnt; i++) { 18846 bpf_prog_lock_ro(func[i]); 18847 bpf_prog_kallsyms_add(func[i]); 18848 } 18849 18850 /* Last step: make now unused interpreter insns from main 18851 * prog consistent for later dump requests, so they can 18852 * later look the same as if they were interpreted only. 18853 */ 18854 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) { 18855 if (bpf_pseudo_func(insn)) { 18856 insn[0].imm = env->insn_aux_data[i].call_imm; 18857 insn[1].imm = insn->off; 18858 insn->off = 0; 18859 continue; 18860 } 18861 if (!bpf_pseudo_call(insn)) 18862 continue; 18863 insn->off = env->insn_aux_data[i].call_imm; 18864 subprog = find_subprog(env, i + insn->off + 1); 18865 insn->imm = subprog; 18866 } 18867 18868 prog->jited = 1; 18869 prog->bpf_func = func[0]->bpf_func; 18870 prog->jited_len = func[0]->jited_len; 18871 prog->aux->extable = func[0]->aux->extable; 18872 prog->aux->num_exentries = func[0]->aux->num_exentries; 18873 prog->aux->func = func; 18874 prog->aux->func_cnt = env->subprog_cnt - env->hidden_subprog_cnt; 18875 prog->aux->real_func_cnt = env->subprog_cnt; 18876 prog->aux->bpf_exception_cb = (void *)func[env->exception_callback_subprog]->bpf_func; 18877 prog->aux->exception_boundary = func[0]->aux->exception_boundary; 18878 bpf_prog_jit_attempt_done(prog); 18879 return 0; 18880 out_free: 18881 /* We failed JIT'ing, so at this point we need to unregister poke 18882 * descriptors from subprogs, so that kernel is not attempting to 18883 * patch it anymore as we're freeing the subprog JIT memory. 18884 */ 18885 for (i = 0; i < prog->aux->size_poke_tab; i++) { 18886 map_ptr = prog->aux->poke_tab[i].tail_call.map; 18887 map_ptr->ops->map_poke_untrack(map_ptr, prog->aux); 18888 } 18889 /* At this point we're guaranteed that poke descriptors are not 18890 * live anymore. We can just unlink its descriptor table as it's 18891 * released with the main prog. 18892 */ 18893 for (i = 0; i < env->subprog_cnt; i++) { 18894 if (!func[i]) 18895 continue; 18896 func[i]->aux->poke_tab = NULL; 18897 bpf_jit_free(func[i]); 18898 } 18899 kfree(func); 18900 out_undo_insn: 18901 /* cleanup main prog to be interpreted */ 18902 prog->jit_requested = 0; 18903 prog->blinding_requested = 0; 18904 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) { 18905 if (!bpf_pseudo_call(insn)) 18906 continue; 18907 insn->off = 0; 18908 insn->imm = env->insn_aux_data[i].call_imm; 18909 } 18910 bpf_prog_jit_attempt_done(prog); 18911 return err; 18912 } 18913 18914 static int fixup_call_args(struct bpf_verifier_env *env) 18915 { 18916 #ifndef CONFIG_BPF_JIT_ALWAYS_ON 18917 struct bpf_prog *prog = env->prog; 18918 struct bpf_insn *insn = prog->insnsi; 18919 bool has_kfunc_call = bpf_prog_has_kfunc_call(prog); 18920 int i, depth; 18921 #endif 18922 int err = 0; 18923 18924 if (env->prog->jit_requested && 18925 !bpf_prog_is_offloaded(env->prog->aux)) { 18926 err = jit_subprogs(env); 18927 if (err == 0) 18928 return 0; 18929 if (err == -EFAULT) 18930 return err; 18931 } 18932 #ifndef CONFIG_BPF_JIT_ALWAYS_ON 18933 if (has_kfunc_call) { 18934 verbose(env, "calling kernel functions are not allowed in non-JITed programs\n"); 18935 return -EINVAL; 18936 } 18937 if (env->subprog_cnt > 1 && env->prog->aux->tail_call_reachable) { 18938 /* When JIT fails the progs with bpf2bpf calls and tail_calls 18939 * have to be rejected, since interpreter doesn't support them yet. 18940 */ 18941 verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n"); 18942 return -EINVAL; 18943 } 18944 for (i = 0; i < prog->len; i++, insn++) { 18945 if (bpf_pseudo_func(insn)) { 18946 /* When JIT fails the progs with callback calls 18947 * have to be rejected, since interpreter doesn't support them yet. 18948 */ 18949 verbose(env, "callbacks are not allowed in non-JITed programs\n"); 18950 return -EINVAL; 18951 } 18952 18953 if (!bpf_pseudo_call(insn)) 18954 continue; 18955 depth = get_callee_stack_depth(env, insn, i); 18956 if (depth < 0) 18957 return depth; 18958 bpf_patch_call_args(insn, depth); 18959 } 18960 err = 0; 18961 #endif 18962 return err; 18963 } 18964 18965 /* replace a generic kfunc with a specialized version if necessary */ 18966 static void specialize_kfunc(struct bpf_verifier_env *env, 18967 u32 func_id, u16 offset, unsigned long *addr) 18968 { 18969 struct bpf_prog *prog = env->prog; 18970 bool seen_direct_write; 18971 void *xdp_kfunc; 18972 bool is_rdonly; 18973 18974 if (bpf_dev_bound_kfunc_id(func_id)) { 18975 xdp_kfunc = bpf_dev_bound_resolve_kfunc(prog, func_id); 18976 if (xdp_kfunc) { 18977 *addr = (unsigned long)xdp_kfunc; 18978 return; 18979 } 18980 /* fallback to default kfunc when not supported by netdev */ 18981 } 18982 18983 if (offset) 18984 return; 18985 18986 if (func_id == special_kfunc_list[KF_bpf_dynptr_from_skb]) { 18987 seen_direct_write = env->seen_direct_write; 18988 is_rdonly = !may_access_direct_pkt_data(env, NULL, BPF_WRITE); 18989 18990 if (is_rdonly) 18991 *addr = (unsigned long)bpf_dynptr_from_skb_rdonly; 18992 18993 /* restore env->seen_direct_write to its original value, since 18994 * may_access_direct_pkt_data mutates it 18995 */ 18996 env->seen_direct_write = seen_direct_write; 18997 } 18998 } 18999 19000 static void __fixup_collection_insert_kfunc(struct bpf_insn_aux_data *insn_aux, 19001 u16 struct_meta_reg, 19002 u16 node_offset_reg, 19003 struct bpf_insn *insn, 19004 struct bpf_insn *insn_buf, 19005 int *cnt) 19006 { 19007 struct btf_struct_meta *kptr_struct_meta = insn_aux->kptr_struct_meta; 19008 struct bpf_insn addr[2] = { BPF_LD_IMM64(struct_meta_reg, (long)kptr_struct_meta) }; 19009 19010 insn_buf[0] = addr[0]; 19011 insn_buf[1] = addr[1]; 19012 insn_buf[2] = BPF_MOV64_IMM(node_offset_reg, insn_aux->insert_off); 19013 insn_buf[3] = *insn; 19014 *cnt = 4; 19015 } 19016 19017 static int fixup_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn, 19018 struct bpf_insn *insn_buf, int insn_idx, int *cnt) 19019 { 19020 const struct bpf_kfunc_desc *desc; 19021 19022 if (!insn->imm) { 19023 verbose(env, "invalid kernel function call not eliminated in verifier pass\n"); 19024 return -EINVAL; 19025 } 19026 19027 *cnt = 0; 19028 19029 /* insn->imm has the btf func_id. Replace it with an offset relative to 19030 * __bpf_call_base, unless the JIT needs to call functions that are 19031 * further than 32 bits away (bpf_jit_supports_far_kfunc_call()). 19032 */ 19033 desc = find_kfunc_desc(env->prog, insn->imm, insn->off); 19034 if (!desc) { 19035 verbose(env, "verifier internal error: kernel function descriptor not found for func_id %u\n", 19036 insn->imm); 19037 return -EFAULT; 19038 } 19039 19040 if (!bpf_jit_supports_far_kfunc_call()) 19041 insn->imm = BPF_CALL_IMM(desc->addr); 19042 if (insn->off) 19043 return 0; 19044 if (desc->func_id == special_kfunc_list[KF_bpf_obj_new_impl] || 19045 desc->func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl]) { 19046 struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta; 19047 struct bpf_insn addr[2] = { BPF_LD_IMM64(BPF_REG_2, (long)kptr_struct_meta) }; 19048 u64 obj_new_size = env->insn_aux_data[insn_idx].obj_new_size; 19049 19050 if (desc->func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl] && kptr_struct_meta) { 19051 verbose(env, "verifier internal error: NULL kptr_struct_meta expected at insn_idx %d\n", 19052 insn_idx); 19053 return -EFAULT; 19054 } 19055 19056 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_1, obj_new_size); 19057 insn_buf[1] = addr[0]; 19058 insn_buf[2] = addr[1]; 19059 insn_buf[3] = *insn; 19060 *cnt = 4; 19061 } else if (desc->func_id == special_kfunc_list[KF_bpf_obj_drop_impl] || 19062 desc->func_id == special_kfunc_list[KF_bpf_percpu_obj_drop_impl] || 19063 desc->func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl]) { 19064 struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta; 19065 struct bpf_insn addr[2] = { BPF_LD_IMM64(BPF_REG_2, (long)kptr_struct_meta) }; 19066 19067 if (desc->func_id == special_kfunc_list[KF_bpf_percpu_obj_drop_impl] && kptr_struct_meta) { 19068 verbose(env, "verifier internal error: NULL kptr_struct_meta expected at insn_idx %d\n", 19069 insn_idx); 19070 return -EFAULT; 19071 } 19072 19073 if (desc->func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl] && 19074 !kptr_struct_meta) { 19075 verbose(env, "verifier internal error: kptr_struct_meta expected at insn_idx %d\n", 19076 insn_idx); 19077 return -EFAULT; 19078 } 19079 19080 insn_buf[0] = addr[0]; 19081 insn_buf[1] = addr[1]; 19082 insn_buf[2] = *insn; 19083 *cnt = 3; 19084 } else if (desc->func_id == special_kfunc_list[KF_bpf_list_push_back_impl] || 19085 desc->func_id == special_kfunc_list[KF_bpf_list_push_front_impl] || 19086 desc->func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) { 19087 struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta; 19088 int struct_meta_reg = BPF_REG_3; 19089 int node_offset_reg = BPF_REG_4; 19090 19091 /* rbtree_add has extra 'less' arg, so args-to-fixup are in diff regs */ 19092 if (desc->func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) { 19093 struct_meta_reg = BPF_REG_4; 19094 node_offset_reg = BPF_REG_5; 19095 } 19096 19097 if (!kptr_struct_meta) { 19098 verbose(env, "verifier internal error: kptr_struct_meta expected at insn_idx %d\n", 19099 insn_idx); 19100 return -EFAULT; 19101 } 19102 19103 __fixup_collection_insert_kfunc(&env->insn_aux_data[insn_idx], struct_meta_reg, 19104 node_offset_reg, insn, insn_buf, cnt); 19105 } else if (desc->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx] || 19106 desc->func_id == special_kfunc_list[KF_bpf_rdonly_cast]) { 19107 insn_buf[0] = BPF_MOV64_REG(BPF_REG_0, BPF_REG_1); 19108 *cnt = 1; 19109 } 19110 return 0; 19111 } 19112 19113 /* The function requires that first instruction in 'patch' is insnsi[prog->len - 1] */ 19114 static int add_hidden_subprog(struct bpf_verifier_env *env, struct bpf_insn *patch, int len) 19115 { 19116 struct bpf_subprog_info *info = env->subprog_info; 19117 int cnt = env->subprog_cnt; 19118 struct bpf_prog *prog; 19119 19120 /* We only reserve one slot for hidden subprogs in subprog_info. */ 19121 if (env->hidden_subprog_cnt) { 19122 verbose(env, "verifier internal error: only one hidden subprog supported\n"); 19123 return -EFAULT; 19124 } 19125 /* We're not patching any existing instruction, just appending the new 19126 * ones for the hidden subprog. Hence all of the adjustment operations 19127 * in bpf_patch_insn_data are no-ops. 19128 */ 19129 prog = bpf_patch_insn_data(env, env->prog->len - 1, patch, len); 19130 if (!prog) 19131 return -ENOMEM; 19132 env->prog = prog; 19133 info[cnt + 1].start = info[cnt].start; 19134 info[cnt].start = prog->len - len + 1; 19135 env->subprog_cnt++; 19136 env->hidden_subprog_cnt++; 19137 return 0; 19138 } 19139 19140 /* Do various post-verification rewrites in a single program pass. 19141 * These rewrites simplify JIT and interpreter implementations. 19142 */ 19143 static int do_misc_fixups(struct bpf_verifier_env *env) 19144 { 19145 struct bpf_prog *prog = env->prog; 19146 enum bpf_attach_type eatype = prog->expected_attach_type; 19147 enum bpf_prog_type prog_type = resolve_prog_type(prog); 19148 struct bpf_insn *insn = prog->insnsi; 19149 const struct bpf_func_proto *fn; 19150 const int insn_cnt = prog->len; 19151 const struct bpf_map_ops *ops; 19152 struct bpf_insn_aux_data *aux; 19153 struct bpf_insn insn_buf[16]; 19154 struct bpf_prog *new_prog; 19155 struct bpf_map *map_ptr; 19156 int i, ret, cnt, delta = 0; 19157 19158 if (env->seen_exception && !env->exception_callback_subprog) { 19159 struct bpf_insn patch[] = { 19160 env->prog->insnsi[insn_cnt - 1], 19161 BPF_MOV64_REG(BPF_REG_0, BPF_REG_1), 19162 BPF_EXIT_INSN(), 19163 }; 19164 19165 ret = add_hidden_subprog(env, patch, ARRAY_SIZE(patch)); 19166 if (ret < 0) 19167 return ret; 19168 prog = env->prog; 19169 insn = prog->insnsi; 19170 19171 env->exception_callback_subprog = env->subprog_cnt - 1; 19172 /* Don't update insn_cnt, as add_hidden_subprog always appends insns */ 19173 mark_subprog_exc_cb(env, env->exception_callback_subprog); 19174 } 19175 19176 for (i = 0; i < insn_cnt; i++, insn++) { 19177 /* Make divide-by-zero exceptions impossible. */ 19178 if (insn->code == (BPF_ALU64 | BPF_MOD | BPF_X) || 19179 insn->code == (BPF_ALU64 | BPF_DIV | BPF_X) || 19180 insn->code == (BPF_ALU | BPF_MOD | BPF_X) || 19181 insn->code == (BPF_ALU | BPF_DIV | BPF_X)) { 19182 bool is64 = BPF_CLASS(insn->code) == BPF_ALU64; 19183 bool isdiv = BPF_OP(insn->code) == BPF_DIV; 19184 struct bpf_insn *patchlet; 19185 struct bpf_insn chk_and_div[] = { 19186 /* [R,W]x div 0 -> 0 */ 19187 BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) | 19188 BPF_JNE | BPF_K, insn->src_reg, 19189 0, 2, 0), 19190 BPF_ALU32_REG(BPF_XOR, insn->dst_reg, insn->dst_reg), 19191 BPF_JMP_IMM(BPF_JA, 0, 0, 1), 19192 *insn, 19193 }; 19194 struct bpf_insn chk_and_mod[] = { 19195 /* [R,W]x mod 0 -> [R,W]x */ 19196 BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) | 19197 BPF_JEQ | BPF_K, insn->src_reg, 19198 0, 1 + (is64 ? 0 : 1), 0), 19199 *insn, 19200 BPF_JMP_IMM(BPF_JA, 0, 0, 1), 19201 BPF_MOV32_REG(insn->dst_reg, insn->dst_reg), 19202 }; 19203 19204 patchlet = isdiv ? chk_and_div : chk_and_mod; 19205 cnt = isdiv ? ARRAY_SIZE(chk_and_div) : 19206 ARRAY_SIZE(chk_and_mod) - (is64 ? 2 : 0); 19207 19208 new_prog = bpf_patch_insn_data(env, i + delta, patchlet, cnt); 19209 if (!new_prog) 19210 return -ENOMEM; 19211 19212 delta += cnt - 1; 19213 env->prog = prog = new_prog; 19214 insn = new_prog->insnsi + i + delta; 19215 continue; 19216 } 19217 19218 /* Implement LD_ABS and LD_IND with a rewrite, if supported by the program type. */ 19219 if (BPF_CLASS(insn->code) == BPF_LD && 19220 (BPF_MODE(insn->code) == BPF_ABS || 19221 BPF_MODE(insn->code) == BPF_IND)) { 19222 cnt = env->ops->gen_ld_abs(insn, insn_buf); 19223 if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf)) { 19224 verbose(env, "bpf verifier is misconfigured\n"); 19225 return -EINVAL; 19226 } 19227 19228 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 19229 if (!new_prog) 19230 return -ENOMEM; 19231 19232 delta += cnt - 1; 19233 env->prog = prog = new_prog; 19234 insn = new_prog->insnsi + i + delta; 19235 continue; 19236 } 19237 19238 /* Rewrite pointer arithmetic to mitigate speculation attacks. */ 19239 if (insn->code == (BPF_ALU64 | BPF_ADD | BPF_X) || 19240 insn->code == (BPF_ALU64 | BPF_SUB | BPF_X)) { 19241 const u8 code_add = BPF_ALU64 | BPF_ADD | BPF_X; 19242 const u8 code_sub = BPF_ALU64 | BPF_SUB | BPF_X; 19243 struct bpf_insn *patch = &insn_buf[0]; 19244 bool issrc, isneg, isimm; 19245 u32 off_reg; 19246 19247 aux = &env->insn_aux_data[i + delta]; 19248 if (!aux->alu_state || 19249 aux->alu_state == BPF_ALU_NON_POINTER) 19250 continue; 19251 19252 isneg = aux->alu_state & BPF_ALU_NEG_VALUE; 19253 issrc = (aux->alu_state & BPF_ALU_SANITIZE) == 19254 BPF_ALU_SANITIZE_SRC; 19255 isimm = aux->alu_state & BPF_ALU_IMMEDIATE; 19256 19257 off_reg = issrc ? insn->src_reg : insn->dst_reg; 19258 if (isimm) { 19259 *patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit); 19260 } else { 19261 if (isneg) 19262 *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1); 19263 *patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit); 19264 *patch++ = BPF_ALU64_REG(BPF_SUB, BPF_REG_AX, off_reg); 19265 *patch++ = BPF_ALU64_REG(BPF_OR, BPF_REG_AX, off_reg); 19266 *patch++ = BPF_ALU64_IMM(BPF_NEG, BPF_REG_AX, 0); 19267 *patch++ = BPF_ALU64_IMM(BPF_ARSH, BPF_REG_AX, 63); 19268 *patch++ = BPF_ALU64_REG(BPF_AND, BPF_REG_AX, off_reg); 19269 } 19270 if (!issrc) 19271 *patch++ = BPF_MOV64_REG(insn->dst_reg, insn->src_reg); 19272 insn->src_reg = BPF_REG_AX; 19273 if (isneg) 19274 insn->code = insn->code == code_add ? 19275 code_sub : code_add; 19276 *patch++ = *insn; 19277 if (issrc && isneg && !isimm) 19278 *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1); 19279 cnt = patch - insn_buf; 19280 19281 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 19282 if (!new_prog) 19283 return -ENOMEM; 19284 19285 delta += cnt - 1; 19286 env->prog = prog = new_prog; 19287 insn = new_prog->insnsi + i + delta; 19288 continue; 19289 } 19290 19291 if (insn->code != (BPF_JMP | BPF_CALL)) 19292 continue; 19293 if (insn->src_reg == BPF_PSEUDO_CALL) 19294 continue; 19295 if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) { 19296 ret = fixup_kfunc_call(env, insn, insn_buf, i + delta, &cnt); 19297 if (ret) 19298 return ret; 19299 if (cnt == 0) 19300 continue; 19301 19302 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 19303 if (!new_prog) 19304 return -ENOMEM; 19305 19306 delta += cnt - 1; 19307 env->prog = prog = new_prog; 19308 insn = new_prog->insnsi + i + delta; 19309 continue; 19310 } 19311 19312 if (insn->imm == BPF_FUNC_get_route_realm) 19313 prog->dst_needed = 1; 19314 if (insn->imm == BPF_FUNC_get_prandom_u32) 19315 bpf_user_rnd_init_once(); 19316 if (insn->imm == BPF_FUNC_override_return) 19317 prog->kprobe_override = 1; 19318 if (insn->imm == BPF_FUNC_tail_call) { 19319 /* If we tail call into other programs, we 19320 * cannot make any assumptions since they can 19321 * be replaced dynamically during runtime in 19322 * the program array. 19323 */ 19324 prog->cb_access = 1; 19325 if (!allow_tail_call_in_subprogs(env)) 19326 prog->aux->stack_depth = MAX_BPF_STACK; 19327 prog->aux->max_pkt_offset = MAX_PACKET_OFF; 19328 19329 /* mark bpf_tail_call as different opcode to avoid 19330 * conditional branch in the interpreter for every normal 19331 * call and to prevent accidental JITing by JIT compiler 19332 * that doesn't support bpf_tail_call yet 19333 */ 19334 insn->imm = 0; 19335 insn->code = BPF_JMP | BPF_TAIL_CALL; 19336 19337 aux = &env->insn_aux_data[i + delta]; 19338 if (env->bpf_capable && !prog->blinding_requested && 19339 prog->jit_requested && 19340 !bpf_map_key_poisoned(aux) && 19341 !bpf_map_ptr_poisoned(aux) && 19342 !bpf_map_ptr_unpriv(aux)) { 19343 struct bpf_jit_poke_descriptor desc = { 19344 .reason = BPF_POKE_REASON_TAIL_CALL, 19345 .tail_call.map = BPF_MAP_PTR(aux->map_ptr_state), 19346 .tail_call.key = bpf_map_key_immediate(aux), 19347 .insn_idx = i + delta, 19348 }; 19349 19350 ret = bpf_jit_add_poke_descriptor(prog, &desc); 19351 if (ret < 0) { 19352 verbose(env, "adding tail call poke descriptor failed\n"); 19353 return ret; 19354 } 19355 19356 insn->imm = ret + 1; 19357 continue; 19358 } 19359 19360 if (!bpf_map_ptr_unpriv(aux)) 19361 continue; 19362 19363 /* instead of changing every JIT dealing with tail_call 19364 * emit two extra insns: 19365 * if (index >= max_entries) goto out; 19366 * index &= array->index_mask; 19367 * to avoid out-of-bounds cpu speculation 19368 */ 19369 if (bpf_map_ptr_poisoned(aux)) { 19370 verbose(env, "tail_call abusing map_ptr\n"); 19371 return -EINVAL; 19372 } 19373 19374 map_ptr = BPF_MAP_PTR(aux->map_ptr_state); 19375 insn_buf[0] = BPF_JMP_IMM(BPF_JGE, BPF_REG_3, 19376 map_ptr->max_entries, 2); 19377 insn_buf[1] = BPF_ALU32_IMM(BPF_AND, BPF_REG_3, 19378 container_of(map_ptr, 19379 struct bpf_array, 19380 map)->index_mask); 19381 insn_buf[2] = *insn; 19382 cnt = 3; 19383 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 19384 if (!new_prog) 19385 return -ENOMEM; 19386 19387 delta += cnt - 1; 19388 env->prog = prog = new_prog; 19389 insn = new_prog->insnsi + i + delta; 19390 continue; 19391 } 19392 19393 if (insn->imm == BPF_FUNC_timer_set_callback) { 19394 /* The verifier will process callback_fn as many times as necessary 19395 * with different maps and the register states prepared by 19396 * set_timer_callback_state will be accurate. 19397 * 19398 * The following use case is valid: 19399 * map1 is shared by prog1, prog2, prog3. 19400 * prog1 calls bpf_timer_init for some map1 elements 19401 * prog2 calls bpf_timer_set_callback for some map1 elements. 19402 * Those that were not bpf_timer_init-ed will return -EINVAL. 19403 * prog3 calls bpf_timer_start for some map1 elements. 19404 * Those that were not both bpf_timer_init-ed and 19405 * bpf_timer_set_callback-ed will return -EINVAL. 19406 */ 19407 struct bpf_insn ld_addrs[2] = { 19408 BPF_LD_IMM64(BPF_REG_3, (long)prog->aux), 19409 }; 19410 19411 insn_buf[0] = ld_addrs[0]; 19412 insn_buf[1] = ld_addrs[1]; 19413 insn_buf[2] = *insn; 19414 cnt = 3; 19415 19416 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 19417 if (!new_prog) 19418 return -ENOMEM; 19419 19420 delta += cnt - 1; 19421 env->prog = prog = new_prog; 19422 insn = new_prog->insnsi + i + delta; 19423 goto patch_call_imm; 19424 } 19425 19426 if (is_storage_get_function(insn->imm)) { 19427 if (!env->prog->aux->sleepable || 19428 env->insn_aux_data[i + delta].storage_get_func_atomic) 19429 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_5, (__force __s32)GFP_ATOMIC); 19430 else 19431 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_5, (__force __s32)GFP_KERNEL); 19432 insn_buf[1] = *insn; 19433 cnt = 2; 19434 19435 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 19436 if (!new_prog) 19437 return -ENOMEM; 19438 19439 delta += cnt - 1; 19440 env->prog = prog = new_prog; 19441 insn = new_prog->insnsi + i + delta; 19442 goto patch_call_imm; 19443 } 19444 19445 /* bpf_per_cpu_ptr() and bpf_this_cpu_ptr() */ 19446 if (env->insn_aux_data[i + delta].call_with_percpu_alloc_ptr) { 19447 /* patch with 'r1 = *(u64 *)(r1 + 0)' since for percpu data, 19448 * bpf_mem_alloc() returns a ptr to the percpu data ptr. 19449 */ 19450 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_1, BPF_REG_1, 0); 19451 insn_buf[1] = *insn; 19452 cnt = 2; 19453 19454 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 19455 if (!new_prog) 19456 return -ENOMEM; 19457 19458 delta += cnt - 1; 19459 env->prog = prog = new_prog; 19460 insn = new_prog->insnsi + i + delta; 19461 goto patch_call_imm; 19462 } 19463 19464 /* BPF_EMIT_CALL() assumptions in some of the map_gen_lookup 19465 * and other inlining handlers are currently limited to 64 bit 19466 * only. 19467 */ 19468 if (prog->jit_requested && BITS_PER_LONG == 64 && 19469 (insn->imm == BPF_FUNC_map_lookup_elem || 19470 insn->imm == BPF_FUNC_map_update_elem || 19471 insn->imm == BPF_FUNC_map_delete_elem || 19472 insn->imm == BPF_FUNC_map_push_elem || 19473 insn->imm == BPF_FUNC_map_pop_elem || 19474 insn->imm == BPF_FUNC_map_peek_elem || 19475 insn->imm == BPF_FUNC_redirect_map || 19476 insn->imm == BPF_FUNC_for_each_map_elem || 19477 insn->imm == BPF_FUNC_map_lookup_percpu_elem)) { 19478 aux = &env->insn_aux_data[i + delta]; 19479 if (bpf_map_ptr_poisoned(aux)) 19480 goto patch_call_imm; 19481 19482 map_ptr = BPF_MAP_PTR(aux->map_ptr_state); 19483 ops = map_ptr->ops; 19484 if (insn->imm == BPF_FUNC_map_lookup_elem && 19485 ops->map_gen_lookup) { 19486 cnt = ops->map_gen_lookup(map_ptr, insn_buf); 19487 if (cnt == -EOPNOTSUPP) 19488 goto patch_map_ops_generic; 19489 if (cnt <= 0 || cnt >= ARRAY_SIZE(insn_buf)) { 19490 verbose(env, "bpf verifier is misconfigured\n"); 19491 return -EINVAL; 19492 } 19493 19494 new_prog = bpf_patch_insn_data(env, i + delta, 19495 insn_buf, cnt); 19496 if (!new_prog) 19497 return -ENOMEM; 19498 19499 delta += cnt - 1; 19500 env->prog = prog = new_prog; 19501 insn = new_prog->insnsi + i + delta; 19502 continue; 19503 } 19504 19505 BUILD_BUG_ON(!__same_type(ops->map_lookup_elem, 19506 (void *(*)(struct bpf_map *map, void *key))NULL)); 19507 BUILD_BUG_ON(!__same_type(ops->map_delete_elem, 19508 (long (*)(struct bpf_map *map, void *key))NULL)); 19509 BUILD_BUG_ON(!__same_type(ops->map_update_elem, 19510 (long (*)(struct bpf_map *map, void *key, void *value, 19511 u64 flags))NULL)); 19512 BUILD_BUG_ON(!__same_type(ops->map_push_elem, 19513 (long (*)(struct bpf_map *map, void *value, 19514 u64 flags))NULL)); 19515 BUILD_BUG_ON(!__same_type(ops->map_pop_elem, 19516 (long (*)(struct bpf_map *map, void *value))NULL)); 19517 BUILD_BUG_ON(!__same_type(ops->map_peek_elem, 19518 (long (*)(struct bpf_map *map, void *value))NULL)); 19519 BUILD_BUG_ON(!__same_type(ops->map_redirect, 19520 (long (*)(struct bpf_map *map, u64 index, u64 flags))NULL)); 19521 BUILD_BUG_ON(!__same_type(ops->map_for_each_callback, 19522 (long (*)(struct bpf_map *map, 19523 bpf_callback_t callback_fn, 19524 void *callback_ctx, 19525 u64 flags))NULL)); 19526 BUILD_BUG_ON(!__same_type(ops->map_lookup_percpu_elem, 19527 (void *(*)(struct bpf_map *map, void *key, u32 cpu))NULL)); 19528 19529 patch_map_ops_generic: 19530 switch (insn->imm) { 19531 case BPF_FUNC_map_lookup_elem: 19532 insn->imm = BPF_CALL_IMM(ops->map_lookup_elem); 19533 continue; 19534 case BPF_FUNC_map_update_elem: 19535 insn->imm = BPF_CALL_IMM(ops->map_update_elem); 19536 continue; 19537 case BPF_FUNC_map_delete_elem: 19538 insn->imm = BPF_CALL_IMM(ops->map_delete_elem); 19539 continue; 19540 case BPF_FUNC_map_push_elem: 19541 insn->imm = BPF_CALL_IMM(ops->map_push_elem); 19542 continue; 19543 case BPF_FUNC_map_pop_elem: 19544 insn->imm = BPF_CALL_IMM(ops->map_pop_elem); 19545 continue; 19546 case BPF_FUNC_map_peek_elem: 19547 insn->imm = BPF_CALL_IMM(ops->map_peek_elem); 19548 continue; 19549 case BPF_FUNC_redirect_map: 19550 insn->imm = BPF_CALL_IMM(ops->map_redirect); 19551 continue; 19552 case BPF_FUNC_for_each_map_elem: 19553 insn->imm = BPF_CALL_IMM(ops->map_for_each_callback); 19554 continue; 19555 case BPF_FUNC_map_lookup_percpu_elem: 19556 insn->imm = BPF_CALL_IMM(ops->map_lookup_percpu_elem); 19557 continue; 19558 } 19559 19560 goto patch_call_imm; 19561 } 19562 19563 /* Implement bpf_jiffies64 inline. */ 19564 if (prog->jit_requested && BITS_PER_LONG == 64 && 19565 insn->imm == BPF_FUNC_jiffies64) { 19566 struct bpf_insn ld_jiffies_addr[2] = { 19567 BPF_LD_IMM64(BPF_REG_0, 19568 (unsigned long)&jiffies), 19569 }; 19570 19571 insn_buf[0] = ld_jiffies_addr[0]; 19572 insn_buf[1] = ld_jiffies_addr[1]; 19573 insn_buf[2] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, 19574 BPF_REG_0, 0); 19575 cnt = 3; 19576 19577 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 19578 cnt); 19579 if (!new_prog) 19580 return -ENOMEM; 19581 19582 delta += cnt - 1; 19583 env->prog = prog = new_prog; 19584 insn = new_prog->insnsi + i + delta; 19585 continue; 19586 } 19587 19588 /* Implement bpf_get_func_arg inline. */ 19589 if (prog_type == BPF_PROG_TYPE_TRACING && 19590 insn->imm == BPF_FUNC_get_func_arg) { 19591 /* Load nr_args from ctx - 8 */ 19592 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8); 19593 insn_buf[1] = BPF_JMP32_REG(BPF_JGE, BPF_REG_2, BPF_REG_0, 6); 19594 insn_buf[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_2, 3); 19595 insn_buf[3] = BPF_ALU64_REG(BPF_ADD, BPF_REG_2, BPF_REG_1); 19596 insn_buf[4] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_2, 0); 19597 insn_buf[5] = BPF_STX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0); 19598 insn_buf[6] = BPF_MOV64_IMM(BPF_REG_0, 0); 19599 insn_buf[7] = BPF_JMP_A(1); 19600 insn_buf[8] = BPF_MOV64_IMM(BPF_REG_0, -EINVAL); 19601 cnt = 9; 19602 19603 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 19604 if (!new_prog) 19605 return -ENOMEM; 19606 19607 delta += cnt - 1; 19608 env->prog = prog = new_prog; 19609 insn = new_prog->insnsi + i + delta; 19610 continue; 19611 } 19612 19613 /* Implement bpf_get_func_ret inline. */ 19614 if (prog_type == BPF_PROG_TYPE_TRACING && 19615 insn->imm == BPF_FUNC_get_func_ret) { 19616 if (eatype == BPF_TRACE_FEXIT || 19617 eatype == BPF_MODIFY_RETURN) { 19618 /* Load nr_args from ctx - 8 */ 19619 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8); 19620 insn_buf[1] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_0, 3); 19621 insn_buf[2] = BPF_ALU64_REG(BPF_ADD, BPF_REG_0, BPF_REG_1); 19622 insn_buf[3] = BPF_LDX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0); 19623 insn_buf[4] = BPF_STX_MEM(BPF_DW, BPF_REG_2, BPF_REG_3, 0); 19624 insn_buf[5] = BPF_MOV64_IMM(BPF_REG_0, 0); 19625 cnt = 6; 19626 } else { 19627 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_0, -EOPNOTSUPP); 19628 cnt = 1; 19629 } 19630 19631 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 19632 if (!new_prog) 19633 return -ENOMEM; 19634 19635 delta += cnt - 1; 19636 env->prog = prog = new_prog; 19637 insn = new_prog->insnsi + i + delta; 19638 continue; 19639 } 19640 19641 /* Implement get_func_arg_cnt inline. */ 19642 if (prog_type == BPF_PROG_TYPE_TRACING && 19643 insn->imm == BPF_FUNC_get_func_arg_cnt) { 19644 /* Load nr_args from ctx - 8 */ 19645 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8); 19646 19647 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1); 19648 if (!new_prog) 19649 return -ENOMEM; 19650 19651 env->prog = prog = new_prog; 19652 insn = new_prog->insnsi + i + delta; 19653 continue; 19654 } 19655 19656 /* Implement bpf_get_func_ip inline. */ 19657 if (prog_type == BPF_PROG_TYPE_TRACING && 19658 insn->imm == BPF_FUNC_get_func_ip) { 19659 /* Load IP address from ctx - 16 */ 19660 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -16); 19661 19662 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1); 19663 if (!new_prog) 19664 return -ENOMEM; 19665 19666 env->prog = prog = new_prog; 19667 insn = new_prog->insnsi + i + delta; 19668 continue; 19669 } 19670 19671 patch_call_imm: 19672 fn = env->ops->get_func_proto(insn->imm, env->prog); 19673 /* all functions that have prototype and verifier allowed 19674 * programs to call them, must be real in-kernel functions 19675 */ 19676 if (!fn->func) { 19677 verbose(env, 19678 "kernel subsystem misconfigured func %s#%d\n", 19679 func_id_name(insn->imm), insn->imm); 19680 return -EFAULT; 19681 } 19682 insn->imm = fn->func - __bpf_call_base; 19683 } 19684 19685 /* Since poke tab is now finalized, publish aux to tracker. */ 19686 for (i = 0; i < prog->aux->size_poke_tab; i++) { 19687 map_ptr = prog->aux->poke_tab[i].tail_call.map; 19688 if (!map_ptr->ops->map_poke_track || 19689 !map_ptr->ops->map_poke_untrack || 19690 !map_ptr->ops->map_poke_run) { 19691 verbose(env, "bpf verifier is misconfigured\n"); 19692 return -EINVAL; 19693 } 19694 19695 ret = map_ptr->ops->map_poke_track(map_ptr, prog->aux); 19696 if (ret < 0) { 19697 verbose(env, "tracking tail call prog failed\n"); 19698 return ret; 19699 } 19700 } 19701 19702 sort_kfunc_descs_by_imm_off(env->prog); 19703 19704 return 0; 19705 } 19706 19707 static struct bpf_prog *inline_bpf_loop(struct bpf_verifier_env *env, 19708 int position, 19709 s32 stack_base, 19710 u32 callback_subprogno, 19711 u32 *cnt) 19712 { 19713 s32 r6_offset = stack_base + 0 * BPF_REG_SIZE; 19714 s32 r7_offset = stack_base + 1 * BPF_REG_SIZE; 19715 s32 r8_offset = stack_base + 2 * BPF_REG_SIZE; 19716 int reg_loop_max = BPF_REG_6; 19717 int reg_loop_cnt = BPF_REG_7; 19718 int reg_loop_ctx = BPF_REG_8; 19719 19720 struct bpf_prog *new_prog; 19721 u32 callback_start; 19722 u32 call_insn_offset; 19723 s32 callback_offset; 19724 19725 /* This represents an inlined version of bpf_iter.c:bpf_loop, 19726 * be careful to modify this code in sync. 19727 */ 19728 struct bpf_insn insn_buf[] = { 19729 /* Return error and jump to the end of the patch if 19730 * expected number of iterations is too big. 19731 */ 19732 BPF_JMP_IMM(BPF_JLE, BPF_REG_1, BPF_MAX_LOOPS, 2), 19733 BPF_MOV32_IMM(BPF_REG_0, -E2BIG), 19734 BPF_JMP_IMM(BPF_JA, 0, 0, 16), 19735 /* spill R6, R7, R8 to use these as loop vars */ 19736 BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_6, r6_offset), 19737 BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_7, r7_offset), 19738 BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_8, r8_offset), 19739 /* initialize loop vars */ 19740 BPF_MOV64_REG(reg_loop_max, BPF_REG_1), 19741 BPF_MOV32_IMM(reg_loop_cnt, 0), 19742 BPF_MOV64_REG(reg_loop_ctx, BPF_REG_3), 19743 /* loop header, 19744 * if reg_loop_cnt >= reg_loop_max skip the loop body 19745 */ 19746 BPF_JMP_REG(BPF_JGE, reg_loop_cnt, reg_loop_max, 5), 19747 /* callback call, 19748 * correct callback offset would be set after patching 19749 */ 19750 BPF_MOV64_REG(BPF_REG_1, reg_loop_cnt), 19751 BPF_MOV64_REG(BPF_REG_2, reg_loop_ctx), 19752 BPF_CALL_REL(0), 19753 /* increment loop counter */ 19754 BPF_ALU64_IMM(BPF_ADD, reg_loop_cnt, 1), 19755 /* jump to loop header if callback returned 0 */ 19756 BPF_JMP_IMM(BPF_JEQ, BPF_REG_0, 0, -6), 19757 /* return value of bpf_loop, 19758 * set R0 to the number of iterations 19759 */ 19760 BPF_MOV64_REG(BPF_REG_0, reg_loop_cnt), 19761 /* restore original values of R6, R7, R8 */ 19762 BPF_LDX_MEM(BPF_DW, BPF_REG_6, BPF_REG_10, r6_offset), 19763 BPF_LDX_MEM(BPF_DW, BPF_REG_7, BPF_REG_10, r7_offset), 19764 BPF_LDX_MEM(BPF_DW, BPF_REG_8, BPF_REG_10, r8_offset), 19765 }; 19766 19767 *cnt = ARRAY_SIZE(insn_buf); 19768 new_prog = bpf_patch_insn_data(env, position, insn_buf, *cnt); 19769 if (!new_prog) 19770 return new_prog; 19771 19772 /* callback start is known only after patching */ 19773 callback_start = env->subprog_info[callback_subprogno].start; 19774 /* Note: insn_buf[12] is an offset of BPF_CALL_REL instruction */ 19775 call_insn_offset = position + 12; 19776 callback_offset = callback_start - call_insn_offset - 1; 19777 new_prog->insnsi[call_insn_offset].imm = callback_offset; 19778 19779 return new_prog; 19780 } 19781 19782 static bool is_bpf_loop_call(struct bpf_insn *insn) 19783 { 19784 return insn->code == (BPF_JMP | BPF_CALL) && 19785 insn->src_reg == 0 && 19786 insn->imm == BPF_FUNC_loop; 19787 } 19788 19789 /* For all sub-programs in the program (including main) check 19790 * insn_aux_data to see if there are bpf_loop calls that require 19791 * inlining. If such calls are found the calls are replaced with a 19792 * sequence of instructions produced by `inline_bpf_loop` function and 19793 * subprog stack_depth is increased by the size of 3 registers. 19794 * This stack space is used to spill values of the R6, R7, R8. These 19795 * registers are used to store the loop bound, counter and context 19796 * variables. 19797 */ 19798 static int optimize_bpf_loop(struct bpf_verifier_env *env) 19799 { 19800 struct bpf_subprog_info *subprogs = env->subprog_info; 19801 int i, cur_subprog = 0, cnt, delta = 0; 19802 struct bpf_insn *insn = env->prog->insnsi; 19803 int insn_cnt = env->prog->len; 19804 u16 stack_depth = subprogs[cur_subprog].stack_depth; 19805 u16 stack_depth_roundup = round_up(stack_depth, 8) - stack_depth; 19806 u16 stack_depth_extra = 0; 19807 19808 for (i = 0; i < insn_cnt; i++, insn++) { 19809 struct bpf_loop_inline_state *inline_state = 19810 &env->insn_aux_data[i + delta].loop_inline_state; 19811 19812 if (is_bpf_loop_call(insn) && inline_state->fit_for_inline) { 19813 struct bpf_prog *new_prog; 19814 19815 stack_depth_extra = BPF_REG_SIZE * 3 + stack_depth_roundup; 19816 new_prog = inline_bpf_loop(env, 19817 i + delta, 19818 -(stack_depth + stack_depth_extra), 19819 inline_state->callback_subprogno, 19820 &cnt); 19821 if (!new_prog) 19822 return -ENOMEM; 19823 19824 delta += cnt - 1; 19825 env->prog = new_prog; 19826 insn = new_prog->insnsi + i + delta; 19827 } 19828 19829 if (subprogs[cur_subprog + 1].start == i + delta + 1) { 19830 subprogs[cur_subprog].stack_depth += stack_depth_extra; 19831 cur_subprog++; 19832 stack_depth = subprogs[cur_subprog].stack_depth; 19833 stack_depth_roundup = round_up(stack_depth, 8) - stack_depth; 19834 stack_depth_extra = 0; 19835 } 19836 } 19837 19838 env->prog->aux->stack_depth = env->subprog_info[0].stack_depth; 19839 19840 return 0; 19841 } 19842 19843 static void free_states(struct bpf_verifier_env *env) 19844 { 19845 struct bpf_verifier_state_list *sl, *sln; 19846 int i; 19847 19848 sl = env->free_list; 19849 while (sl) { 19850 sln = sl->next; 19851 free_verifier_state(&sl->state, false); 19852 kfree(sl); 19853 sl = sln; 19854 } 19855 env->free_list = NULL; 19856 19857 if (!env->explored_states) 19858 return; 19859 19860 for (i = 0; i < state_htab_size(env); i++) { 19861 sl = env->explored_states[i]; 19862 19863 while (sl) { 19864 sln = sl->next; 19865 free_verifier_state(&sl->state, false); 19866 kfree(sl); 19867 sl = sln; 19868 } 19869 env->explored_states[i] = NULL; 19870 } 19871 } 19872 19873 static int do_check_common(struct bpf_verifier_env *env, int subprog) 19874 { 19875 bool pop_log = !(env->log.level & BPF_LOG_LEVEL2); 19876 struct bpf_verifier_state *state; 19877 struct bpf_reg_state *regs; 19878 int ret, i; 19879 19880 env->prev_linfo = NULL; 19881 env->pass_cnt++; 19882 19883 state = kzalloc(sizeof(struct bpf_verifier_state), GFP_KERNEL); 19884 if (!state) 19885 return -ENOMEM; 19886 state->curframe = 0; 19887 state->speculative = false; 19888 state->branches = 1; 19889 state->frame[0] = kzalloc(sizeof(struct bpf_func_state), GFP_KERNEL); 19890 if (!state->frame[0]) { 19891 kfree(state); 19892 return -ENOMEM; 19893 } 19894 env->cur_state = state; 19895 init_func_state(env, state->frame[0], 19896 BPF_MAIN_FUNC /* callsite */, 19897 0 /* frameno */, 19898 subprog); 19899 state->first_insn_idx = env->subprog_info[subprog].start; 19900 state->last_insn_idx = -1; 19901 19902 regs = state->frame[state->curframe]->regs; 19903 if (subprog || env->prog->type == BPF_PROG_TYPE_EXT) { 19904 u32 nargs; 19905 19906 ret = btf_prepare_func_args(env, subprog, regs, &nargs); 19907 if (ret) 19908 goto out; 19909 if (subprog_is_exc_cb(env, subprog)) { 19910 state->frame[0]->in_exception_callback_fn = true; 19911 /* We have already ensured that the callback returns an integer, just 19912 * like all global subprogs. We need to determine it only has a single 19913 * scalar argument. 19914 */ 19915 if (nargs != 1 || regs[BPF_REG_1].type != SCALAR_VALUE) { 19916 verbose(env, "exception cb only supports single integer argument\n"); 19917 ret = -EINVAL; 19918 goto out; 19919 } 19920 } 19921 for (i = BPF_REG_1; i <= BPF_REG_5; i++) { 19922 if (regs[i].type == PTR_TO_CTX) 19923 mark_reg_known_zero(env, regs, i); 19924 else if (regs[i].type == SCALAR_VALUE) 19925 mark_reg_unknown(env, regs, i); 19926 else if (base_type(regs[i].type) == PTR_TO_MEM) { 19927 const u32 mem_size = regs[i].mem_size; 19928 19929 mark_reg_known_zero(env, regs, i); 19930 regs[i].mem_size = mem_size; 19931 regs[i].id = ++env->id_gen; 19932 } 19933 } 19934 } else { 19935 /* 1st arg to a function */ 19936 regs[BPF_REG_1].type = PTR_TO_CTX; 19937 mark_reg_known_zero(env, regs, BPF_REG_1); 19938 ret = btf_check_subprog_arg_match(env, subprog, regs); 19939 if (ret == -EFAULT) 19940 /* unlikely verifier bug. abort. 19941 * ret == 0 and ret < 0 are sadly acceptable for 19942 * main() function due to backward compatibility. 19943 * Like socket filter program may be written as: 19944 * int bpf_prog(struct pt_regs *ctx) 19945 * and never dereference that ctx in the program. 19946 * 'struct pt_regs' is a type mismatch for socket 19947 * filter that should be using 'struct __sk_buff'. 19948 */ 19949 goto out; 19950 } 19951 19952 ret = do_check(env); 19953 out: 19954 /* check for NULL is necessary, since cur_state can be freed inside 19955 * do_check() under memory pressure. 19956 */ 19957 if (env->cur_state) { 19958 free_verifier_state(env->cur_state, true); 19959 env->cur_state = NULL; 19960 } 19961 while (!pop_stack(env, NULL, NULL, false)); 19962 if (!ret && pop_log) 19963 bpf_vlog_reset(&env->log, 0); 19964 free_states(env); 19965 return ret; 19966 } 19967 19968 /* Lazily verify all global functions based on their BTF, if they are called 19969 * from main BPF program or any of subprograms transitively. 19970 * BPF global subprogs called from dead code are not validated. 19971 * All callable global functions must pass verification. 19972 * Otherwise the whole program is rejected. 19973 * Consider: 19974 * int bar(int); 19975 * int foo(int f) 19976 * { 19977 * return bar(f); 19978 * } 19979 * int bar(int b) 19980 * { 19981 * ... 19982 * } 19983 * foo() will be verified first for R1=any_scalar_value. During verification it 19984 * will be assumed that bar() already verified successfully and call to bar() 19985 * from foo() will be checked for type match only. Later bar() will be verified 19986 * independently to check that it's safe for R1=any_scalar_value. 19987 */ 19988 static int do_check_subprogs(struct bpf_verifier_env *env) 19989 { 19990 struct bpf_prog_aux *aux = env->prog->aux; 19991 struct bpf_func_info_aux *sub_aux; 19992 int i, ret, new_cnt; 19993 19994 if (!aux->func_info) 19995 return 0; 19996 19997 /* exception callback is presumed to be always called */ 19998 if (env->exception_callback_subprog) 19999 subprog_aux(env, env->exception_callback_subprog)->called = true; 20000 20001 again: 20002 new_cnt = 0; 20003 for (i = 1; i < env->subprog_cnt; i++) { 20004 if (!subprog_is_global(env, i)) 20005 continue; 20006 20007 sub_aux = subprog_aux(env, i); 20008 if (!sub_aux->called || sub_aux->verified) 20009 continue; 20010 20011 env->insn_idx = env->subprog_info[i].start; 20012 WARN_ON_ONCE(env->insn_idx == 0); 20013 ret = do_check_common(env, i); 20014 if (ret) { 20015 return ret; 20016 } else if (env->log.level & BPF_LOG_LEVEL) { 20017 verbose(env, "Func#%d ('%s') is safe for any args that match its prototype\n", 20018 i, subprog_name(env, i)); 20019 } 20020 20021 /* We verified new global subprog, it might have called some 20022 * more global subprogs that we haven't verified yet, so we 20023 * need to do another pass over subprogs to verify those. 20024 */ 20025 sub_aux->verified = true; 20026 new_cnt++; 20027 } 20028 20029 /* We can't loop forever as we verify at least one global subprog on 20030 * each pass. 20031 */ 20032 if (new_cnt) 20033 goto again; 20034 20035 return 0; 20036 } 20037 20038 static int do_check_main(struct bpf_verifier_env *env) 20039 { 20040 int ret; 20041 20042 env->insn_idx = 0; 20043 ret = do_check_common(env, 0); 20044 if (!ret) 20045 env->prog->aux->stack_depth = env->subprog_info[0].stack_depth; 20046 return ret; 20047 } 20048 20049 20050 static void print_verification_stats(struct bpf_verifier_env *env) 20051 { 20052 int i; 20053 20054 if (env->log.level & BPF_LOG_STATS) { 20055 verbose(env, "verification time %lld usec\n", 20056 div_u64(env->verification_time, 1000)); 20057 verbose(env, "stack depth "); 20058 for (i = 0; i < env->subprog_cnt; i++) { 20059 u32 depth = env->subprog_info[i].stack_depth; 20060 20061 verbose(env, "%d", depth); 20062 if (i + 1 < env->subprog_cnt) 20063 verbose(env, "+"); 20064 } 20065 verbose(env, "\n"); 20066 } 20067 verbose(env, "processed %d insns (limit %d) max_states_per_insn %d " 20068 "total_states %d peak_states %d mark_read %d\n", 20069 env->insn_processed, BPF_COMPLEXITY_LIMIT_INSNS, 20070 env->max_states_per_insn, env->total_states, 20071 env->peak_states, env->longest_mark_read_walk); 20072 } 20073 20074 static int check_struct_ops_btf_id(struct bpf_verifier_env *env) 20075 { 20076 const struct btf_type *t, *func_proto; 20077 const struct bpf_struct_ops *st_ops; 20078 const struct btf_member *member; 20079 struct bpf_prog *prog = env->prog; 20080 u32 btf_id, member_idx; 20081 const char *mname; 20082 20083 if (!prog->gpl_compatible) { 20084 verbose(env, "struct ops programs must have a GPL compatible license\n"); 20085 return -EINVAL; 20086 } 20087 20088 btf_id = prog->aux->attach_btf_id; 20089 st_ops = bpf_struct_ops_find(btf_id); 20090 if (!st_ops) { 20091 verbose(env, "attach_btf_id %u is not a supported struct\n", 20092 btf_id); 20093 return -ENOTSUPP; 20094 } 20095 20096 t = st_ops->type; 20097 member_idx = prog->expected_attach_type; 20098 if (member_idx >= btf_type_vlen(t)) { 20099 verbose(env, "attach to invalid member idx %u of struct %s\n", 20100 member_idx, st_ops->name); 20101 return -EINVAL; 20102 } 20103 20104 member = &btf_type_member(t)[member_idx]; 20105 mname = btf_name_by_offset(btf_vmlinux, member->name_off); 20106 func_proto = btf_type_resolve_func_ptr(btf_vmlinux, member->type, 20107 NULL); 20108 if (!func_proto) { 20109 verbose(env, "attach to invalid member %s(@idx %u) of struct %s\n", 20110 mname, member_idx, st_ops->name); 20111 return -EINVAL; 20112 } 20113 20114 if (st_ops->check_member) { 20115 int err = st_ops->check_member(t, member, prog); 20116 20117 if (err) { 20118 verbose(env, "attach to unsupported member %s of struct %s\n", 20119 mname, st_ops->name); 20120 return err; 20121 } 20122 } 20123 20124 prog->aux->attach_func_proto = func_proto; 20125 prog->aux->attach_func_name = mname; 20126 env->ops = st_ops->verifier_ops; 20127 20128 return 0; 20129 } 20130 #define SECURITY_PREFIX "security_" 20131 20132 static int check_attach_modify_return(unsigned long addr, const char *func_name) 20133 { 20134 if (within_error_injection_list(addr) || 20135 !strncmp(SECURITY_PREFIX, func_name, sizeof(SECURITY_PREFIX) - 1)) 20136 return 0; 20137 20138 return -EINVAL; 20139 } 20140 20141 /* list of non-sleepable functions that are otherwise on 20142 * ALLOW_ERROR_INJECTION list 20143 */ 20144 BTF_SET_START(btf_non_sleepable_error_inject) 20145 /* Three functions below can be called from sleepable and non-sleepable context. 20146 * Assume non-sleepable from bpf safety point of view. 20147 */ 20148 BTF_ID(func, __filemap_add_folio) 20149 BTF_ID(func, should_fail_alloc_page) 20150 BTF_ID(func, should_failslab) 20151 BTF_SET_END(btf_non_sleepable_error_inject) 20152 20153 static int check_non_sleepable_error_inject(u32 btf_id) 20154 { 20155 return btf_id_set_contains(&btf_non_sleepable_error_inject, btf_id); 20156 } 20157 20158 int bpf_check_attach_target(struct bpf_verifier_log *log, 20159 const struct bpf_prog *prog, 20160 const struct bpf_prog *tgt_prog, 20161 u32 btf_id, 20162 struct bpf_attach_target_info *tgt_info) 20163 { 20164 bool prog_extension = prog->type == BPF_PROG_TYPE_EXT; 20165 const char prefix[] = "btf_trace_"; 20166 int ret = 0, subprog = -1, i; 20167 const struct btf_type *t; 20168 bool conservative = true; 20169 const char *tname; 20170 struct btf *btf; 20171 long addr = 0; 20172 struct module *mod = NULL; 20173 20174 if (!btf_id) { 20175 bpf_log(log, "Tracing programs must provide btf_id\n"); 20176 return -EINVAL; 20177 } 20178 btf = tgt_prog ? tgt_prog->aux->btf : prog->aux->attach_btf; 20179 if (!btf) { 20180 bpf_log(log, 20181 "FENTRY/FEXIT program can only be attached to another program annotated with BTF\n"); 20182 return -EINVAL; 20183 } 20184 t = btf_type_by_id(btf, btf_id); 20185 if (!t) { 20186 bpf_log(log, "attach_btf_id %u is invalid\n", btf_id); 20187 return -EINVAL; 20188 } 20189 tname = btf_name_by_offset(btf, t->name_off); 20190 if (!tname) { 20191 bpf_log(log, "attach_btf_id %u doesn't have a name\n", btf_id); 20192 return -EINVAL; 20193 } 20194 if (tgt_prog) { 20195 struct bpf_prog_aux *aux = tgt_prog->aux; 20196 20197 if (bpf_prog_is_dev_bound(prog->aux) && 20198 !bpf_prog_dev_bound_match(prog, tgt_prog)) { 20199 bpf_log(log, "Target program bound device mismatch"); 20200 return -EINVAL; 20201 } 20202 20203 for (i = 0; i < aux->func_info_cnt; i++) 20204 if (aux->func_info[i].type_id == btf_id) { 20205 subprog = i; 20206 break; 20207 } 20208 if (subprog == -1) { 20209 bpf_log(log, "Subprog %s doesn't exist\n", tname); 20210 return -EINVAL; 20211 } 20212 if (aux->func && aux->func[subprog]->aux->exception_cb) { 20213 bpf_log(log, 20214 "%s programs cannot attach to exception callback\n", 20215 prog_extension ? "Extension" : "FENTRY/FEXIT"); 20216 return -EINVAL; 20217 } 20218 conservative = aux->func_info_aux[subprog].unreliable; 20219 if (prog_extension) { 20220 if (conservative) { 20221 bpf_log(log, 20222 "Cannot replace static functions\n"); 20223 return -EINVAL; 20224 } 20225 if (!prog->jit_requested) { 20226 bpf_log(log, 20227 "Extension programs should be JITed\n"); 20228 return -EINVAL; 20229 } 20230 } 20231 if (!tgt_prog->jited) { 20232 bpf_log(log, "Can attach to only JITed progs\n"); 20233 return -EINVAL; 20234 } 20235 if (tgt_prog->type == prog->type) { 20236 /* Cannot fentry/fexit another fentry/fexit program. 20237 * Cannot attach program extension to another extension. 20238 * It's ok to attach fentry/fexit to extension program. 20239 */ 20240 bpf_log(log, "Cannot recursively attach\n"); 20241 return -EINVAL; 20242 } 20243 if (tgt_prog->type == BPF_PROG_TYPE_TRACING && 20244 prog_extension && 20245 (tgt_prog->expected_attach_type == BPF_TRACE_FENTRY || 20246 tgt_prog->expected_attach_type == BPF_TRACE_FEXIT)) { 20247 /* Program extensions can extend all program types 20248 * except fentry/fexit. The reason is the following. 20249 * The fentry/fexit programs are used for performance 20250 * analysis, stats and can be attached to any program 20251 * type except themselves. When extension program is 20252 * replacing XDP function it is necessary to allow 20253 * performance analysis of all functions. Both original 20254 * XDP program and its program extension. Hence 20255 * attaching fentry/fexit to BPF_PROG_TYPE_EXT is 20256 * allowed. If extending of fentry/fexit was allowed it 20257 * would be possible to create long call chain 20258 * fentry->extension->fentry->extension beyond 20259 * reasonable stack size. Hence extending fentry is not 20260 * allowed. 20261 */ 20262 bpf_log(log, "Cannot extend fentry/fexit\n"); 20263 return -EINVAL; 20264 } 20265 } else { 20266 if (prog_extension) { 20267 bpf_log(log, "Cannot replace kernel functions\n"); 20268 return -EINVAL; 20269 } 20270 } 20271 20272 switch (prog->expected_attach_type) { 20273 case BPF_TRACE_RAW_TP: 20274 if (tgt_prog) { 20275 bpf_log(log, 20276 "Only FENTRY/FEXIT progs are attachable to another BPF prog\n"); 20277 return -EINVAL; 20278 } 20279 if (!btf_type_is_typedef(t)) { 20280 bpf_log(log, "attach_btf_id %u is not a typedef\n", 20281 btf_id); 20282 return -EINVAL; 20283 } 20284 if (strncmp(prefix, tname, sizeof(prefix) - 1)) { 20285 bpf_log(log, "attach_btf_id %u points to wrong type name %s\n", 20286 btf_id, tname); 20287 return -EINVAL; 20288 } 20289 tname += sizeof(prefix) - 1; 20290 t = btf_type_by_id(btf, t->type); 20291 if (!btf_type_is_ptr(t)) 20292 /* should never happen in valid vmlinux build */ 20293 return -EINVAL; 20294 t = btf_type_by_id(btf, t->type); 20295 if (!btf_type_is_func_proto(t)) 20296 /* should never happen in valid vmlinux build */ 20297 return -EINVAL; 20298 20299 break; 20300 case BPF_TRACE_ITER: 20301 if (!btf_type_is_func(t)) { 20302 bpf_log(log, "attach_btf_id %u is not a function\n", 20303 btf_id); 20304 return -EINVAL; 20305 } 20306 t = btf_type_by_id(btf, t->type); 20307 if (!btf_type_is_func_proto(t)) 20308 return -EINVAL; 20309 ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel); 20310 if (ret) 20311 return ret; 20312 break; 20313 default: 20314 if (!prog_extension) 20315 return -EINVAL; 20316 fallthrough; 20317 case BPF_MODIFY_RETURN: 20318 case BPF_LSM_MAC: 20319 case BPF_LSM_CGROUP: 20320 case BPF_TRACE_FENTRY: 20321 case BPF_TRACE_FEXIT: 20322 if (!btf_type_is_func(t)) { 20323 bpf_log(log, "attach_btf_id %u is not a function\n", 20324 btf_id); 20325 return -EINVAL; 20326 } 20327 if (prog_extension && 20328 btf_check_type_match(log, prog, btf, t)) 20329 return -EINVAL; 20330 t = btf_type_by_id(btf, t->type); 20331 if (!btf_type_is_func_proto(t)) 20332 return -EINVAL; 20333 20334 if ((prog->aux->saved_dst_prog_type || prog->aux->saved_dst_attach_type) && 20335 (!tgt_prog || prog->aux->saved_dst_prog_type != tgt_prog->type || 20336 prog->aux->saved_dst_attach_type != tgt_prog->expected_attach_type)) 20337 return -EINVAL; 20338 20339 if (tgt_prog && conservative) 20340 t = NULL; 20341 20342 ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel); 20343 if (ret < 0) 20344 return ret; 20345 20346 if (tgt_prog) { 20347 if (subprog == 0) 20348 addr = (long) tgt_prog->bpf_func; 20349 else 20350 addr = (long) tgt_prog->aux->func[subprog]->bpf_func; 20351 } else { 20352 if (btf_is_module(btf)) { 20353 mod = btf_try_get_module(btf); 20354 if (mod) 20355 addr = find_kallsyms_symbol_value(mod, tname); 20356 else 20357 addr = 0; 20358 } else { 20359 addr = kallsyms_lookup_name(tname); 20360 } 20361 if (!addr) { 20362 module_put(mod); 20363 bpf_log(log, 20364 "The address of function %s cannot be found\n", 20365 tname); 20366 return -ENOENT; 20367 } 20368 } 20369 20370 if (prog->aux->sleepable) { 20371 ret = -EINVAL; 20372 switch (prog->type) { 20373 case BPF_PROG_TYPE_TRACING: 20374 20375 /* fentry/fexit/fmod_ret progs can be sleepable if they are 20376 * attached to ALLOW_ERROR_INJECTION and are not in denylist. 20377 */ 20378 if (!check_non_sleepable_error_inject(btf_id) && 20379 within_error_injection_list(addr)) 20380 ret = 0; 20381 /* fentry/fexit/fmod_ret progs can also be sleepable if they are 20382 * in the fmodret id set with the KF_SLEEPABLE flag. 20383 */ 20384 else { 20385 u32 *flags = btf_kfunc_is_modify_return(btf, btf_id, 20386 prog); 20387 20388 if (flags && (*flags & KF_SLEEPABLE)) 20389 ret = 0; 20390 } 20391 break; 20392 case BPF_PROG_TYPE_LSM: 20393 /* LSM progs check that they are attached to bpf_lsm_*() funcs. 20394 * Only some of them are sleepable. 20395 */ 20396 if (bpf_lsm_is_sleepable_hook(btf_id)) 20397 ret = 0; 20398 break; 20399 default: 20400 break; 20401 } 20402 if (ret) { 20403 module_put(mod); 20404 bpf_log(log, "%s is not sleepable\n", tname); 20405 return ret; 20406 } 20407 } else if (prog->expected_attach_type == BPF_MODIFY_RETURN) { 20408 if (tgt_prog) { 20409 module_put(mod); 20410 bpf_log(log, "can't modify return codes of BPF programs\n"); 20411 return -EINVAL; 20412 } 20413 ret = -EINVAL; 20414 if (btf_kfunc_is_modify_return(btf, btf_id, prog) || 20415 !check_attach_modify_return(addr, tname)) 20416 ret = 0; 20417 if (ret) { 20418 module_put(mod); 20419 bpf_log(log, "%s() is not modifiable\n", tname); 20420 return ret; 20421 } 20422 } 20423 20424 break; 20425 } 20426 tgt_info->tgt_addr = addr; 20427 tgt_info->tgt_name = tname; 20428 tgt_info->tgt_type = t; 20429 tgt_info->tgt_mod = mod; 20430 return 0; 20431 } 20432 20433 BTF_SET_START(btf_id_deny) 20434 BTF_ID_UNUSED 20435 #ifdef CONFIG_SMP 20436 BTF_ID(func, migrate_disable) 20437 BTF_ID(func, migrate_enable) 20438 #endif 20439 #if !defined CONFIG_PREEMPT_RCU && !defined CONFIG_TINY_RCU 20440 BTF_ID(func, rcu_read_unlock_strict) 20441 #endif 20442 #if defined(CONFIG_DEBUG_PREEMPT) || defined(CONFIG_TRACE_PREEMPT_TOGGLE) 20443 BTF_ID(func, preempt_count_add) 20444 BTF_ID(func, preempt_count_sub) 20445 #endif 20446 #ifdef CONFIG_PREEMPT_RCU 20447 BTF_ID(func, __rcu_read_lock) 20448 BTF_ID(func, __rcu_read_unlock) 20449 #endif 20450 BTF_SET_END(btf_id_deny) 20451 20452 static bool can_be_sleepable(struct bpf_prog *prog) 20453 { 20454 if (prog->type == BPF_PROG_TYPE_TRACING) { 20455 switch (prog->expected_attach_type) { 20456 case BPF_TRACE_FENTRY: 20457 case BPF_TRACE_FEXIT: 20458 case BPF_MODIFY_RETURN: 20459 case BPF_TRACE_ITER: 20460 return true; 20461 default: 20462 return false; 20463 } 20464 } 20465 return prog->type == BPF_PROG_TYPE_LSM || 20466 prog->type == BPF_PROG_TYPE_KPROBE /* only for uprobes */ || 20467 prog->type == BPF_PROG_TYPE_STRUCT_OPS; 20468 } 20469 20470 static int check_attach_btf_id(struct bpf_verifier_env *env) 20471 { 20472 struct bpf_prog *prog = env->prog; 20473 struct bpf_prog *tgt_prog = prog->aux->dst_prog; 20474 struct bpf_attach_target_info tgt_info = {}; 20475 u32 btf_id = prog->aux->attach_btf_id; 20476 struct bpf_trampoline *tr; 20477 int ret; 20478 u64 key; 20479 20480 if (prog->type == BPF_PROG_TYPE_SYSCALL) { 20481 if (prog->aux->sleepable) 20482 /* attach_btf_id checked to be zero already */ 20483 return 0; 20484 verbose(env, "Syscall programs can only be sleepable\n"); 20485 return -EINVAL; 20486 } 20487 20488 if (prog->aux->sleepable && !can_be_sleepable(prog)) { 20489 verbose(env, "Only fentry/fexit/fmod_ret, lsm, iter, uprobe, and struct_ops programs can be sleepable\n"); 20490 return -EINVAL; 20491 } 20492 20493 if (prog->type == BPF_PROG_TYPE_STRUCT_OPS) 20494 return check_struct_ops_btf_id(env); 20495 20496 if (prog->type != BPF_PROG_TYPE_TRACING && 20497 prog->type != BPF_PROG_TYPE_LSM && 20498 prog->type != BPF_PROG_TYPE_EXT) 20499 return 0; 20500 20501 ret = bpf_check_attach_target(&env->log, prog, tgt_prog, btf_id, &tgt_info); 20502 if (ret) 20503 return ret; 20504 20505 if (tgt_prog && prog->type == BPF_PROG_TYPE_EXT) { 20506 /* to make freplace equivalent to their targets, they need to 20507 * inherit env->ops and expected_attach_type for the rest of the 20508 * verification 20509 */ 20510 env->ops = bpf_verifier_ops[tgt_prog->type]; 20511 prog->expected_attach_type = tgt_prog->expected_attach_type; 20512 } 20513 20514 /* store info about the attachment target that will be used later */ 20515 prog->aux->attach_func_proto = tgt_info.tgt_type; 20516 prog->aux->attach_func_name = tgt_info.tgt_name; 20517 prog->aux->mod = tgt_info.tgt_mod; 20518 20519 if (tgt_prog) { 20520 prog->aux->saved_dst_prog_type = tgt_prog->type; 20521 prog->aux->saved_dst_attach_type = tgt_prog->expected_attach_type; 20522 } 20523 20524 if (prog->expected_attach_type == BPF_TRACE_RAW_TP) { 20525 prog->aux->attach_btf_trace = true; 20526 return 0; 20527 } else if (prog->expected_attach_type == BPF_TRACE_ITER) { 20528 if (!bpf_iter_prog_supported(prog)) 20529 return -EINVAL; 20530 return 0; 20531 } 20532 20533 if (prog->type == BPF_PROG_TYPE_LSM) { 20534 ret = bpf_lsm_verify_prog(&env->log, prog); 20535 if (ret < 0) 20536 return ret; 20537 } else if (prog->type == BPF_PROG_TYPE_TRACING && 20538 btf_id_set_contains(&btf_id_deny, btf_id)) { 20539 return -EINVAL; 20540 } 20541 20542 key = bpf_trampoline_compute_key(tgt_prog, prog->aux->attach_btf, btf_id); 20543 tr = bpf_trampoline_get(key, &tgt_info); 20544 if (!tr) 20545 return -ENOMEM; 20546 20547 if (tgt_prog && tgt_prog->aux->tail_call_reachable) 20548 tr->flags = BPF_TRAMP_F_TAIL_CALL_CTX; 20549 20550 prog->aux->dst_trampoline = tr; 20551 return 0; 20552 } 20553 20554 struct btf *bpf_get_btf_vmlinux(void) 20555 { 20556 if (!btf_vmlinux && IS_ENABLED(CONFIG_DEBUG_INFO_BTF)) { 20557 mutex_lock(&bpf_verifier_lock); 20558 if (!btf_vmlinux) 20559 btf_vmlinux = btf_parse_vmlinux(); 20560 mutex_unlock(&bpf_verifier_lock); 20561 } 20562 return btf_vmlinux; 20563 } 20564 20565 int bpf_check(struct bpf_prog **prog, union bpf_attr *attr, bpfptr_t uattr, __u32 uattr_size) 20566 { 20567 u64 start_time = ktime_get_ns(); 20568 struct bpf_verifier_env *env; 20569 int i, len, ret = -EINVAL, err; 20570 u32 log_true_size; 20571 bool is_priv; 20572 20573 /* no program is valid */ 20574 if (ARRAY_SIZE(bpf_verifier_ops) == 0) 20575 return -EINVAL; 20576 20577 /* 'struct bpf_verifier_env' can be global, but since it's not small, 20578 * allocate/free it every time bpf_check() is called 20579 */ 20580 env = kzalloc(sizeof(struct bpf_verifier_env), GFP_KERNEL); 20581 if (!env) 20582 return -ENOMEM; 20583 20584 env->bt.env = env; 20585 20586 len = (*prog)->len; 20587 env->insn_aux_data = 20588 vzalloc(array_size(sizeof(struct bpf_insn_aux_data), len)); 20589 ret = -ENOMEM; 20590 if (!env->insn_aux_data) 20591 goto err_free_env; 20592 for (i = 0; i < len; i++) 20593 env->insn_aux_data[i].orig_idx = i; 20594 env->prog = *prog; 20595 env->ops = bpf_verifier_ops[env->prog->type]; 20596 env->fd_array = make_bpfptr(attr->fd_array, uattr.is_kernel); 20597 is_priv = bpf_capable(); 20598 20599 bpf_get_btf_vmlinux(); 20600 20601 /* grab the mutex to protect few globals used by verifier */ 20602 if (!is_priv) 20603 mutex_lock(&bpf_verifier_lock); 20604 20605 /* user could have requested verbose verifier output 20606 * and supplied buffer to store the verification trace 20607 */ 20608 ret = bpf_vlog_init(&env->log, attr->log_level, 20609 (char __user *) (unsigned long) attr->log_buf, 20610 attr->log_size); 20611 if (ret) 20612 goto err_unlock; 20613 20614 mark_verifier_state_clean(env); 20615 20616 if (IS_ERR(btf_vmlinux)) { 20617 /* Either gcc or pahole or kernel are broken. */ 20618 verbose(env, "in-kernel BTF is malformed\n"); 20619 ret = PTR_ERR(btf_vmlinux); 20620 goto skip_full_check; 20621 } 20622 20623 env->strict_alignment = !!(attr->prog_flags & BPF_F_STRICT_ALIGNMENT); 20624 if (!IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS)) 20625 env->strict_alignment = true; 20626 if (attr->prog_flags & BPF_F_ANY_ALIGNMENT) 20627 env->strict_alignment = false; 20628 20629 env->allow_ptr_leaks = bpf_allow_ptr_leaks(); 20630 env->allow_uninit_stack = bpf_allow_uninit_stack(); 20631 env->bypass_spec_v1 = bpf_bypass_spec_v1(); 20632 env->bypass_spec_v4 = bpf_bypass_spec_v4(); 20633 env->bpf_capable = bpf_capable(); 20634 20635 if (is_priv) 20636 env->test_state_freq = attr->prog_flags & BPF_F_TEST_STATE_FREQ; 20637 env->test_reg_invariants = attr->prog_flags & BPF_F_TEST_REG_INVARIANTS; 20638 20639 env->explored_states = kvcalloc(state_htab_size(env), 20640 sizeof(struct bpf_verifier_state_list *), 20641 GFP_USER); 20642 ret = -ENOMEM; 20643 if (!env->explored_states) 20644 goto skip_full_check; 20645 20646 ret = check_btf_info_early(env, attr, uattr); 20647 if (ret < 0) 20648 goto skip_full_check; 20649 20650 ret = add_subprog_and_kfunc(env); 20651 if (ret < 0) 20652 goto skip_full_check; 20653 20654 ret = check_subprogs(env); 20655 if (ret < 0) 20656 goto skip_full_check; 20657 20658 ret = check_btf_info(env, attr, uattr); 20659 if (ret < 0) 20660 goto skip_full_check; 20661 20662 ret = check_attach_btf_id(env); 20663 if (ret) 20664 goto skip_full_check; 20665 20666 ret = resolve_pseudo_ldimm64(env); 20667 if (ret < 0) 20668 goto skip_full_check; 20669 20670 if (bpf_prog_is_offloaded(env->prog->aux)) { 20671 ret = bpf_prog_offload_verifier_prep(env->prog); 20672 if (ret) 20673 goto skip_full_check; 20674 } 20675 20676 ret = check_cfg(env); 20677 if (ret < 0) 20678 goto skip_full_check; 20679 20680 ret = do_check_main(env); 20681 ret = ret ?: do_check_subprogs(env); 20682 20683 if (ret == 0 && bpf_prog_is_offloaded(env->prog->aux)) 20684 ret = bpf_prog_offload_finalize(env); 20685 20686 skip_full_check: 20687 kvfree(env->explored_states); 20688 20689 if (ret == 0) 20690 ret = check_max_stack_depth(env); 20691 20692 /* instruction rewrites happen after this point */ 20693 if (ret == 0) 20694 ret = optimize_bpf_loop(env); 20695 20696 if (is_priv) { 20697 if (ret == 0) 20698 opt_hard_wire_dead_code_branches(env); 20699 if (ret == 0) 20700 ret = opt_remove_dead_code(env); 20701 if (ret == 0) 20702 ret = opt_remove_nops(env); 20703 } else { 20704 if (ret == 0) 20705 sanitize_dead_code(env); 20706 } 20707 20708 if (ret == 0) 20709 /* program is valid, convert *(u32*)(ctx + off) accesses */ 20710 ret = convert_ctx_accesses(env); 20711 20712 if (ret == 0) 20713 ret = do_misc_fixups(env); 20714 20715 /* do 32-bit optimization after insn patching has done so those patched 20716 * insns could be handled correctly. 20717 */ 20718 if (ret == 0 && !bpf_prog_is_offloaded(env->prog->aux)) { 20719 ret = opt_subreg_zext_lo32_rnd_hi32(env, attr); 20720 env->prog->aux->verifier_zext = bpf_jit_needs_zext() ? !ret 20721 : false; 20722 } 20723 20724 if (ret == 0) 20725 ret = fixup_call_args(env); 20726 20727 env->verification_time = ktime_get_ns() - start_time; 20728 print_verification_stats(env); 20729 env->prog->aux->verified_insns = env->insn_processed; 20730 20731 /* preserve original error even if log finalization is successful */ 20732 err = bpf_vlog_finalize(&env->log, &log_true_size); 20733 if (err) 20734 ret = err; 20735 20736 if (uattr_size >= offsetofend(union bpf_attr, log_true_size) && 20737 copy_to_bpfptr_offset(uattr, offsetof(union bpf_attr, log_true_size), 20738 &log_true_size, sizeof(log_true_size))) { 20739 ret = -EFAULT; 20740 goto err_release_maps; 20741 } 20742 20743 if (ret) 20744 goto err_release_maps; 20745 20746 if (env->used_map_cnt) { 20747 /* if program passed verifier, update used_maps in bpf_prog_info */ 20748 env->prog->aux->used_maps = kmalloc_array(env->used_map_cnt, 20749 sizeof(env->used_maps[0]), 20750 GFP_KERNEL); 20751 20752 if (!env->prog->aux->used_maps) { 20753 ret = -ENOMEM; 20754 goto err_release_maps; 20755 } 20756 20757 memcpy(env->prog->aux->used_maps, env->used_maps, 20758 sizeof(env->used_maps[0]) * env->used_map_cnt); 20759 env->prog->aux->used_map_cnt = env->used_map_cnt; 20760 } 20761 if (env->used_btf_cnt) { 20762 /* if program passed verifier, update used_btfs in bpf_prog_aux */ 20763 env->prog->aux->used_btfs = kmalloc_array(env->used_btf_cnt, 20764 sizeof(env->used_btfs[0]), 20765 GFP_KERNEL); 20766 if (!env->prog->aux->used_btfs) { 20767 ret = -ENOMEM; 20768 goto err_release_maps; 20769 } 20770 20771 memcpy(env->prog->aux->used_btfs, env->used_btfs, 20772 sizeof(env->used_btfs[0]) * env->used_btf_cnt); 20773 env->prog->aux->used_btf_cnt = env->used_btf_cnt; 20774 } 20775 if (env->used_map_cnt || env->used_btf_cnt) { 20776 /* program is valid. Convert pseudo bpf_ld_imm64 into generic 20777 * bpf_ld_imm64 instructions 20778 */ 20779 convert_pseudo_ld_imm64(env); 20780 } 20781 20782 adjust_btf_func(env); 20783 20784 err_release_maps: 20785 if (!env->prog->aux->used_maps) 20786 /* if we didn't copy map pointers into bpf_prog_info, release 20787 * them now. Otherwise free_used_maps() will release them. 20788 */ 20789 release_maps(env); 20790 if (!env->prog->aux->used_btfs) 20791 release_btfs(env); 20792 20793 /* extension progs temporarily inherit the attach_type of their targets 20794 for verification purposes, so set it back to zero before returning 20795 */ 20796 if (env->prog->type == BPF_PROG_TYPE_EXT) 20797 env->prog->expected_attach_type = 0; 20798 20799 *prog = env->prog; 20800 err_unlock: 20801 if (!is_priv) 20802 mutex_unlock(&bpf_verifier_lock); 20803 vfree(env->insn_aux_data); 20804 err_free_env: 20805 kfree(env); 20806 return ret; 20807 } 20808